b74f4ef150892544e62a8b202a429be0fb9bb4bd
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-good / gst / isomp4 / qtdemux.c
1 /* GStreamer
2  * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
3  * Copyright (C) <2003> David A. Schleef <ds@schleef.org>
4  * Copyright (C) <2006> Wim Taymans <wim@fluendo.com>
5  * Copyright (C) <2007> Julien Moutte <julien@fluendo.com>
6  * Copyright (C) <2009> Tim-Philipp Müller <tim centricular net>
7  * Copyright (C) <2009> STEricsson <benjamin.gaignard@stericsson.com>
8  * Copyright (C) <2013> Sreerenj Balachandran <sreerenj.balachandran@intel.com>
9  * Copyright (C) <2013> Intel Corporation
10  * Copyright (C) <2014> Centricular Ltd
11  * Copyright (C) <2015> YouView TV Ltd.
12  * Copyright (C) <2016> British Broadcasting Corporation
13  *
14  * This library is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Library General Public
16  * License as published by the Free Software Foundation; either
17  * version 2 of the License, or (at your option) any later version.
18  *
19  * This library is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22  * Library General Public License for more details.
23  *
24  * You should have received a copy of the GNU Library General Public
25  * License along with this library; if not, write to the
26  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
27  * Boston, MA 02110-1301, USA.
28  */
29
30 /**
31  * SECTION:element-qtdemux
32  * @title: qtdemux
33  *
34  * Demuxes a .mov file into raw or compressed audio and/or video streams.
35  *
36  * This element supports both push and pull-based scheduling, depending on the
37  * capabilities of the upstream elements.
38  *
39  * ## Example launch line
40  * |[
41  * gst-launch-1.0 filesrc location=test.mov ! qtdemux name=demux  demux.audio_0 ! queue ! decodebin ! audioconvert ! audioresample ! autoaudiosink   demux.video_0 ! queue ! decodebin ! videoconvert ! videoscale ! autovideosink
42  * ]| Play (parse and decode) a .mov file and try to output it to
43  * an automatically detected soundcard and videosink. If the MOV file contains
44  * compressed audio or video data, this will only work if you have the
45  * right decoder elements/plugins installed.
46  *
47  */
48
49 #ifdef HAVE_CONFIG_H
50 #include "config.h"
51 #endif
52
53 #include "gst/gst-i18n-plugin.h"
54
55 #include <glib/gprintf.h>
56 #include <gst/base/base.h>
57 #include <gst/tag/tag.h>
58 #include <gst/audio/audio.h>
59 #include <gst/riff/riff.h>
60 #include <gst/pbutils/pbutils.h>
61
62 #include "gstisomp4elements.h"
63 #include "qtatomparser.h"
64 #include "qtdemux_types.h"
65 #include "qtdemux_dump.h"
66 #include "fourcc.h"
67 #include "descriptors.h"
68 #include "qtdemux_lang.h"
69 #include "qtdemux.h"
70 #include "qtpalette.h"
71 #include "qtdemux_tags.h"
72 #include "qtdemux_tree.h"
73 #include "qtdemux-webvtt.h"
74
75 #include <stdlib.h>
76 #include <string.h>
77
78 #include <math.h>
79 #include <gst/math-compat.h>
80
81 #ifdef HAVE_ZLIB
82 # include <zlib.h>
83 #endif
84
85 /* max. size considered 'sane' for non-mdat atoms */
86 #define QTDEMUX_MAX_ATOM_SIZE (32*1024*1024)
87
88 /* if the sample index is larger than this, something is likely wrong */
89 #define QTDEMUX_MAX_SAMPLE_INDEX_SIZE (200*1024*1024)
90
91 /* For converting qt creation times to unix epoch times */
92 #define QTDEMUX_SECONDS_PER_DAY (60 * 60 * 24)
93 #define QTDEMUX_LEAP_YEARS_FROM_1904_TO_1970 17
94 #define QTDEMUX_SECONDS_FROM_1904_TO_1970 (((1970 - 1904) * (guint64) 365 + \
95     QTDEMUX_LEAP_YEARS_FROM_1904_TO_1970) * QTDEMUX_SECONDS_PER_DAY)
96
97 #define QTDEMUX_TREE_NODE_FOURCC(n) (QT_FOURCC(((guint8 *) (n)->data) + 4))
98
99 #define STREAM_IS_EOS(s) ((s)->time_position == GST_CLOCK_TIME_NONE)
100
101 #define ABSDIFF(x, y) ( (x) > (y) ? ((x) - (y)) : ((y) - (x)) )
102
103 #define QTDEMUX_STREAM(s) ((QtDemuxStream *)(s))
104 #define QTDEMUX_N_STREAMS(demux) ((demux)->active_streams->len)
105 #define QTDEMUX_NTH_STREAM(demux,idx) \
106    QTDEMUX_STREAM(g_ptr_array_index((demux)->active_streams,idx))
107 #define QTDEMUX_NTH_OLD_STREAM(demux,idx) \
108    QTDEMUX_STREAM(g_ptr_array_index((demux)->old_streams,idx))
109
110 #define CUR_STREAM(s) (&((s)->stsd_entries[(s)->cur_stsd_entry_index]))
111
112 GST_DEBUG_CATEGORY (qtdemux_debug);
113 #define GST_CAT_DEFAULT qtdemux_debug
114
115 typedef struct _QtDemuxCencSampleSetInfo QtDemuxCencSampleSetInfo;
116 typedef struct _QtDemuxAavdEncryptionInfo QtDemuxAavdEncryptionInfo;
117
118 /* Macros for converting to/from timescale */
119 #define QTSTREAMTIME_TO_GSTTIME(stream, value) (gst_util_uint64_scale((value), GST_SECOND, (stream)->timescale))
120 #define GSTTIME_TO_QTSTREAMTIME(stream, value) (gst_util_uint64_scale((value), (stream)->timescale, GST_SECOND))
121
122 #define QTTIME_TO_GSTTIME(qtdemux, value) (gst_util_uint64_scale((value), GST_SECOND, (qtdemux)->timescale))
123 #define GSTTIME_TO_QTTIME(qtdemux, value) (gst_util_uint64_scale((value), (qtdemux)->timescale, GST_SECOND))
124
125 /* timestamp is the DTS */
126 #define QTSAMPLE_DTS(stream,sample) (QTSTREAMTIME_TO_GSTTIME((stream), (sample)->timestamp))
127 /* timestamp + offset + cslg_shift is the outgoing PTS */
128 #define QTSAMPLE_PTS(stream,sample) (QTSTREAMTIME_TO_GSTTIME((stream), (sample)->timestamp + (stream)->cslg_shift + (sample)->pts_offset))
129 /* timestamp + offset is the PTS used for internal seek calculations */
130 #define QTSAMPLE_PTS_NO_CSLG(stream,sample) (QTSTREAMTIME_TO_GSTTIME((stream), (sample)->timestamp + (sample)->pts_offset))
131 /* timestamp + duration - dts is the duration */
132 #define QTSAMPLE_DUR_DTS(stream, sample, dts) (QTSTREAMTIME_TO_GSTTIME ((stream), (sample)->timestamp + (sample)->duration) - (dts))
133
134 #define QTSAMPLE_KEYFRAME(stream,sample) ((stream)->all_keyframe || (sample)->keyframe)
135
136 #define QTDEMUX_EXPOSE_GET_LOCK(demux) (&((demux)->expose_lock))
137 #define QTDEMUX_EXPOSE_LOCK(demux) G_STMT_START { \
138     GST_TRACE("Locking from thread %p", g_thread_self()); \
139     g_mutex_lock (QTDEMUX_EXPOSE_GET_LOCK (demux)); \
140     GST_TRACE("Locked from thread %p", g_thread_self()); \
141  } G_STMT_END
142
143 #define QTDEMUX_EXPOSE_UNLOCK(demux) G_STMT_START { \
144     GST_TRACE("Unlocking from thread %p", g_thread_self()); \
145     g_mutex_unlock (QTDEMUX_EXPOSE_GET_LOCK (demux)); \
146  } G_STMT_END
147
148 /*
149  * Quicktime has tracks and segments. A track is a continuous piece of
150  * multimedia content. The track is not always played from start to finish but
151  * instead, pieces of the track are 'cut out' and played in sequence. This is
152  * what the segments do.
153  *
154  * Inside the track we have keyframes (K) and delta frames. The track has its
155  * own timing, which starts from 0 and extends to end. The position in the track
156  * is called the media_time.
157  *
158  * The segments now describe the pieces that should be played from this track
159  * and are basically tuples of media_time/duration/rate entries. We can have
160  * multiple segments and they are all played after one another. An example:
161  *
162  * segment 1: media_time: 1 second, duration: 1 second, rate 1
163  * segment 2: media_time: 3 second, duration: 2 second, rate 2
164  *
165  * To correctly play back this track, one must play: 1 second of media starting
166  * from media_time 1 followed by 2 seconds of media starting from media_time 3
167  * at a rate of 2.
168  *
169  * Each of the segments will be played at a specific time, the first segment at
170  * time 0, the second one after the duration of the first one, etc.. Note that
171  * the time in resulting playback is not identical to the media_time of the
172  * track anymore.
173  *
174  * Visually, assuming the track has 4 second of media_time:
175  *
176  *                (a)                   (b)          (c)              (d)
177  *         .-----------------------------------------------------------.
178  * track:  | K.....K.........K........K.......K.......K...........K... |
179  *         '-----------------------------------------------------------'
180  *         0              1              2              3              4
181  *           .------------^              ^   .----------^              ^
182  *          /              .-------------'  /       .------------------'
183  *         /              /          .-----'       /
184  *         .--------------.         .--------------.
185  *         | segment 1    |         | segment 2    |
186  *         '--------------'         '--------------'
187  *
188  * The challenge here is to cut out the right pieces of the track for each of
189  * the playback segments. This fortunately can easily be done with the SEGMENT
190  * events of GStreamer.
191  *
192  * For playback of segment 1, we need to provide the decoder with the keyframe
193  * (a), in the above figure, but we must instruct it only to output the decoded
194  * data between second 1 and 2. We do this with a SEGMENT event for 1 to 2, time
195  * position set to the time of the segment: 0.
196  *
197  * We then proceed to push data from keyframe (a) to frame (b). The decoder
198  * decodes but clips all before media_time 1.
199  *
200  * After finishing a segment, we push out a new SEGMENT event with the clipping
201  * boundaries of the new data.
202  *
203  * This is a good usecase for the GStreamer accumulated SEGMENT events.
204  */
205
206 struct _QtDemuxSegment
207 {
208   /* global time and duration, all gst time */
209   GstClockTime time;
210   GstClockTime stop_time;
211   GstClockTime duration;
212   /* media time of trak, all gst time */
213   GstClockTime media_start;
214   GstClockTime media_stop;
215   gdouble rate;
216   /* Media start time in trak timescale units */
217   guint32 trak_media_start;
218 };
219
220 #define QTSEGMENT_IS_EMPTY(s) ((s)->media_start == GST_CLOCK_TIME_NONE)
221
222 /* Used with fragmented MP4 files (mfra atom) */
223 struct _QtDemuxRandomAccessEntry
224 {
225   GstClockTime ts;
226   guint64 moof_offset;
227 };
228
229
230 /* Contains properties and cryptographic info for a set of samples from a
231  * track protected using Common Encryption (cenc) */
232 struct _QtDemuxCencSampleSetInfo
233 {
234   GstStructure *default_properties;
235
236   /* @crypto_info holds one GstStructure per sample */
237   GPtrArray *crypto_info;
238 };
239
240 struct _QtDemuxAavdEncryptionInfo
241 {
242   GstStructure *default_properties;
243 };
244
245 static const gchar *
246 qt_demux_state_string (enum QtDemuxState state)
247 {
248   switch (state) {
249     case QTDEMUX_STATE_INITIAL:
250       return "<INITIAL>";
251     case QTDEMUX_STATE_HEADER:
252       return "<HEADER>";
253     case QTDEMUX_STATE_MOVIE:
254       return "<MOVIE>";
255     case QTDEMUX_STATE_BUFFER_MDAT:
256       return "<BUFFER_MDAT>";
257     default:
258       return "<UNKNOWN>";
259   }
260 }
261
262 static GstFlowReturn qtdemux_add_fragmented_samples (GstQTDemux * qtdemux);
263
264 static void gst_qtdemux_check_send_pending_segment (GstQTDemux * demux);
265
266 static GstStaticPadTemplate gst_qtdemux_sink_template =
267     GST_STATIC_PAD_TEMPLATE ("sink",
268     GST_PAD_SINK,
269     GST_PAD_ALWAYS,
270     GST_STATIC_CAPS ("video/quicktime; video/mj2; audio/x-m4a; "
271         "application/x-3gp")
272     );
273
274 static GstStaticPadTemplate gst_qtdemux_videosrc_template =
275 GST_STATIC_PAD_TEMPLATE ("video_%u",
276     GST_PAD_SRC,
277     GST_PAD_SOMETIMES,
278     GST_STATIC_CAPS_ANY);
279
280 static GstStaticPadTemplate gst_qtdemux_audiosrc_template =
281 GST_STATIC_PAD_TEMPLATE ("audio_%u",
282     GST_PAD_SRC,
283     GST_PAD_SOMETIMES,
284     GST_STATIC_CAPS_ANY);
285
286 static GstStaticPadTemplate gst_qtdemux_subsrc_template =
287 GST_STATIC_PAD_TEMPLATE ("subtitle_%u",
288     GST_PAD_SRC,
289     GST_PAD_SOMETIMES,
290     GST_STATIC_CAPS_ANY);
291
292 #define gst_qtdemux_parent_class parent_class
293 G_DEFINE_TYPE (GstQTDemux, gst_qtdemux, GST_TYPE_ELEMENT);
294 GST_ELEMENT_REGISTER_DEFINE_WITH_CODE (qtdemux, "qtdemux",
295     GST_RANK_PRIMARY, GST_TYPE_QTDEMUX, isomp4_element_init (plugin));
296
297 static void gst_qtdemux_dispose (GObject * object);
298 static void gst_qtdemux_finalize (GObject * object);
299
300 static guint32
301 gst_qtdemux_find_index_linear (GstQTDemux * qtdemux, QtDemuxStream * str,
302     GstClockTime media_time);
303 static guint32
304 gst_qtdemux_find_index_for_given_media_offset_linear (GstQTDemux * qtdemux,
305     QtDemuxStream * str, gint64 media_offset);
306
307 #if 0
308 static void gst_qtdemux_set_index (GstElement * element, GstIndex * index);
309 static GstIndex *gst_qtdemux_get_index (GstElement * element);
310 #endif
311 static GstStateChangeReturn gst_qtdemux_change_state (GstElement * element,
312     GstStateChange transition);
313 static void gst_qtdemux_set_context (GstElement * element,
314     GstContext * context);
315 static gboolean qtdemux_sink_activate (GstPad * sinkpad, GstObject * parent);
316 static gboolean qtdemux_sink_activate_mode (GstPad * sinkpad,
317     GstObject * parent, GstPadMode mode, gboolean active);
318
319 static void gst_qtdemux_loop (GstPad * pad);
320 static GstFlowReturn gst_qtdemux_chain (GstPad * sinkpad, GstObject * parent,
321     GstBuffer * inbuf);
322 static gboolean gst_qtdemux_handle_sink_event (GstPad * pad, GstObject * parent,
323     GstEvent * event);
324 static gboolean gst_qtdemux_handle_sink_query (GstPad * pad, GstObject * parent,
325     GstQuery * query);
326 static gboolean gst_qtdemux_setcaps (GstQTDemux * qtdemux, GstCaps * caps);
327 static gboolean gst_qtdemux_configure_stream (GstQTDemux * qtdemux,
328     QtDemuxStream * stream);
329 static void gst_qtdemux_stream_check_and_change_stsd_index (GstQTDemux * demux,
330     QtDemuxStream * stream);
331 static GstFlowReturn gst_qtdemux_process_adapter (GstQTDemux * demux,
332     gboolean force);
333
334 static void gst_qtdemux_check_seekability (GstQTDemux * demux);
335
336 static gboolean qtdemux_parse_moov (GstQTDemux * qtdemux,
337     const guint8 * buffer, guint length);
338 static gboolean qtdemux_parse_node (GstQTDemux * qtdemux, GNode * node,
339     const guint8 * buffer, guint length);
340 static gboolean qtdemux_parse_tree (GstQTDemux * qtdemux);
341
342 static void gst_qtdemux_handle_esds (GstQTDemux * qtdemux,
343     QtDemuxStream * stream, QtDemuxStreamStsdEntry * entry, GNode * esds,
344     GstTagList * list);
345 static GstCaps *qtdemux_video_caps (GstQTDemux * qtdemux,
346     QtDemuxStream * stream, QtDemuxStreamStsdEntry * entry, guint32 fourcc,
347     const guint8 * stsd_entry_data, gchar ** codec_name);
348 static GstCaps *qtdemux_audio_caps (GstQTDemux * qtdemux,
349     QtDemuxStream * stream, QtDemuxStreamStsdEntry * entry, guint32 fourcc,
350     const guint8 * data, int len, gchar ** codec_name);
351 static GstCaps *qtdemux_sub_caps (GstQTDemux * qtdemux, QtDemuxStream * stream,
352     QtDemuxStreamStsdEntry * entry, guint32 fourcc, const guint8 * data,
353     gchar ** codec_name);
354 static GstCaps *qtdemux_generic_caps (GstQTDemux * qtdemux,
355     QtDemuxStream * stream, QtDemuxStreamStsdEntry * entry, guint32 fourcc,
356     const guint8 * stsd_entry_data, gchar ** codec_name);
357
358 static gboolean qtdemux_parse_samples (GstQTDemux * qtdemux,
359     QtDemuxStream * stream, guint32 n);
360 static GstFlowReturn qtdemux_expose_streams (GstQTDemux * qtdemux);
361 static QtDemuxStream *gst_qtdemux_stream_ref (QtDemuxStream * stream);
362 static void gst_qtdemux_stream_unref (QtDemuxStream * stream);
363 static void gst_qtdemux_stream_clear (QtDemuxStream * stream);
364 static GstFlowReturn qtdemux_prepare_streams (GstQTDemux * qtdemux);
365 static void qtdemux_do_allocation (QtDemuxStream * stream,
366     GstQTDemux * qtdemux);
367 static gboolean gst_qtdemux_activate_segment (GstQTDemux * qtdemux,
368     QtDemuxStream * stream, guint32 seg_idx, GstClockTime offset);
369 static gboolean gst_qtdemux_stream_update_segment (GstQTDemux * qtdemux,
370     QtDemuxStream * stream, gint seg_idx, GstClockTime offset,
371     GstClockTime * _start, GstClockTime * _stop);
372 static void gst_qtdemux_send_gap_for_segment (GstQTDemux * demux,
373     QtDemuxStream * stream, gint segment_index, GstClockTime pos);
374
375 static gboolean qtdemux_pull_mfro_mfra (GstQTDemux * qtdemux);
376 static void check_update_duration (GstQTDemux * qtdemux, GstClockTime duration);
377
378 static gchar *qtdemux_uuid_bytes_to_string (gconstpointer uuid_bytes);
379
380 static GstStructure *qtdemux_get_cenc_sample_properties (GstQTDemux * qtdemux,
381     QtDemuxStream * stream, guint sample_index);
382 static void gst_qtdemux_append_protection_system_id (GstQTDemux * qtdemux,
383     const gchar * id);
384 static void qtdemux_gst_structure_free (GstStructure * gststructure);
385 static void gst_qtdemux_reset (GstQTDemux * qtdemux, gboolean hard);
386
387 static void
388 gst_qtdemux_class_init (GstQTDemuxClass * klass)
389 {
390   GObjectClass *gobject_class;
391   GstElementClass *gstelement_class;
392
393   gobject_class = (GObjectClass *) klass;
394   gstelement_class = (GstElementClass *) klass;
395
396   parent_class = g_type_class_peek_parent (klass);
397
398   gobject_class->dispose = gst_qtdemux_dispose;
399   gobject_class->finalize = gst_qtdemux_finalize;
400
401   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_qtdemux_change_state);
402 #if 0
403   gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_qtdemux_set_index);
404   gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_qtdemux_get_index);
405 #endif
406   gstelement_class->set_context = GST_DEBUG_FUNCPTR (gst_qtdemux_set_context);
407
408   gst_tag_register_musicbrainz_tags ();
409
410   gst_element_class_add_static_pad_template (gstelement_class,
411       &gst_qtdemux_sink_template);
412   gst_element_class_add_static_pad_template (gstelement_class,
413       &gst_qtdemux_videosrc_template);
414   gst_element_class_add_static_pad_template (gstelement_class,
415       &gst_qtdemux_audiosrc_template);
416   gst_element_class_add_static_pad_template (gstelement_class,
417       &gst_qtdemux_subsrc_template);
418   gst_element_class_set_static_metadata (gstelement_class, "QuickTime demuxer",
419       "Codec/Demuxer",
420       "Demultiplex a QuickTime file into audio and video streams",
421       "David Schleef <ds@schleef.org>, Wim Taymans <wim@fluendo.com>");
422
423   GST_DEBUG_CATEGORY_INIT (qtdemux_debug, "qtdemux", 0, "qtdemux plugin");
424   gst_riff_init ();
425 }
426
427 static void
428 gst_qtdemux_init (GstQTDemux * qtdemux)
429 {
430   qtdemux->sinkpad =
431       gst_pad_new_from_static_template (&gst_qtdemux_sink_template, "sink");
432   gst_pad_set_activate_function (qtdemux->sinkpad, qtdemux_sink_activate);
433   gst_pad_set_activatemode_function (qtdemux->sinkpad,
434       qtdemux_sink_activate_mode);
435   gst_pad_set_chain_function (qtdemux->sinkpad, gst_qtdemux_chain);
436   gst_pad_set_event_function (qtdemux->sinkpad, gst_qtdemux_handle_sink_event);
437   gst_pad_set_query_function (qtdemux->sinkpad, gst_qtdemux_handle_sink_query);
438   gst_element_add_pad (GST_ELEMENT_CAST (qtdemux), qtdemux->sinkpad);
439
440   qtdemux->adapter = gst_adapter_new ();
441   g_queue_init (&qtdemux->protection_event_queue);
442   qtdemux->flowcombiner = gst_flow_combiner_new ();
443   g_mutex_init (&qtdemux->expose_lock);
444
445   qtdemux->active_streams = g_ptr_array_new_with_free_func
446       ((GDestroyNotify) gst_qtdemux_stream_unref);
447   qtdemux->old_streams = g_ptr_array_new_with_free_func
448       ((GDestroyNotify) gst_qtdemux_stream_unref);
449
450   GST_OBJECT_FLAG_SET (qtdemux, GST_ELEMENT_FLAG_INDEXABLE);
451
452   gst_qtdemux_reset (qtdemux, TRUE);
453 }
454
455 static void
456 gst_qtdemux_finalize (GObject * object)
457 {
458   GstQTDemux *qtdemux = GST_QTDEMUX (object);
459
460   g_free (qtdemux->redirect_location);
461
462   G_OBJECT_CLASS (parent_class)->finalize (object);
463 }
464
465 static void
466 gst_qtdemux_dispose (GObject * object)
467 {
468   GstQTDemux *qtdemux = GST_QTDEMUX (object);
469
470   if (qtdemux->adapter) {
471     g_object_unref (G_OBJECT (qtdemux->adapter));
472     qtdemux->adapter = NULL;
473   }
474   gst_tag_list_unref (qtdemux->tag_list);
475   gst_flow_combiner_free (qtdemux->flowcombiner);
476   g_queue_foreach (&qtdemux->protection_event_queue, (GFunc) gst_event_unref,
477       NULL);
478   g_queue_clear (&qtdemux->protection_event_queue);
479
480   g_free (qtdemux->cenc_aux_info_sizes);
481   qtdemux->cenc_aux_info_sizes = NULL;
482   g_mutex_clear (&qtdemux->expose_lock);
483
484   g_ptr_array_free (qtdemux->active_streams, TRUE);
485   g_ptr_array_free (qtdemux->old_streams, TRUE);
486
487   G_OBJECT_CLASS (parent_class)->dispose (object);
488 }
489
490 static void
491 gst_qtdemux_post_no_playable_stream_error (GstQTDemux * qtdemux)
492 {
493   if (qtdemux->redirect_location) {
494     GST_ELEMENT_ERROR_WITH_DETAILS (qtdemux, STREAM, DEMUX,
495         (_("This file contains no playable streams.")),
496         ("no known streams found, a redirect message has been posted"),
497         ("redirect-location", G_TYPE_STRING, qtdemux->redirect_location, NULL));
498   } else {
499     GST_ELEMENT_ERROR (qtdemux, STREAM, DEMUX,
500         (_("This file contains no playable streams.")),
501         ("no known streams found"));
502   }
503 }
504
505 static GstBuffer *
506 _gst_buffer_new_wrapped (gpointer mem, gsize size, GFreeFunc free_func)
507 {
508   return gst_buffer_new_wrapped_full (free_func ? 0 : GST_MEMORY_FLAG_READONLY,
509       mem, size, 0, size, mem, free_func);
510 }
511
512 static GstFlowReturn
513 gst_qtdemux_pull_atom (GstQTDemux * qtdemux, guint64 offset, guint64 size,
514     GstBuffer ** buf)
515 {
516   GstFlowReturn flow;
517   GstMapInfo map;
518   gsize bsize;
519
520   if (G_UNLIKELY (size == 0)) {
521     GstFlowReturn ret;
522     GstBuffer *tmp = NULL;
523
524     ret = gst_qtdemux_pull_atom (qtdemux, offset, sizeof (guint32), &tmp);
525     if (ret != GST_FLOW_OK)
526       return ret;
527
528     gst_buffer_map (tmp, &map, GST_MAP_READ);
529     size = QT_UINT32 (map.data);
530     GST_DEBUG_OBJECT (qtdemux, "size 0x%08" G_GINT64_MODIFIER "x", size);
531
532     gst_buffer_unmap (tmp, &map);
533     gst_buffer_unref (tmp);
534   }
535
536   /* Sanity check: catch bogus sizes (fuzzed/broken files) */
537   if (G_UNLIKELY (size > QTDEMUX_MAX_ATOM_SIZE)) {
538     if (qtdemux->state != QTDEMUX_STATE_MOVIE && qtdemux->got_moov) {
539       /* we're pulling header but already got most interesting bits,
540        * so never mind the rest (e.g. tags) (that much) */
541       GST_WARNING_OBJECT (qtdemux, "atom has bogus size %" G_GUINT64_FORMAT,
542           size);
543       return GST_FLOW_EOS;
544     } else {
545       GST_ELEMENT_ERROR (qtdemux, STREAM, DEMUX,
546           (_("This file is invalid and cannot be played.")),
547           ("atom has bogus size %" G_GUINT64_FORMAT, size));
548       return GST_FLOW_ERROR;
549     }
550   }
551
552   flow = gst_pad_pull_range (qtdemux->sinkpad, offset, size, buf);
553
554   if (G_UNLIKELY (flow != GST_FLOW_OK))
555     return flow;
556
557   bsize = gst_buffer_get_size (*buf);
558   /* Catch short reads - we don't want any partial atoms */
559   if (G_UNLIKELY (bsize < size)) {
560     GST_WARNING_OBJECT (qtdemux,
561         "short read: %" G_GSIZE_FORMAT " < %" G_GUINT64_FORMAT, bsize, size);
562     gst_buffer_unref (*buf);
563     *buf = NULL;
564     return GST_FLOW_EOS;
565   }
566
567   return flow;
568 }
569
570 #if 1
571 static gboolean
572 gst_qtdemux_src_convert (GstQTDemux * qtdemux, GstPad * pad,
573     GstFormat src_format, gint64 src_value, GstFormat dest_format,
574     gint64 * dest_value)
575 {
576   gboolean res = TRUE;
577   QtDemuxStream *stream = gst_pad_get_element_private (pad);
578   gint32 index;
579
580   if (stream->subtype != FOURCC_vide) {
581     res = FALSE;
582     goto done;
583   }
584
585   switch (src_format) {
586     case GST_FORMAT_TIME:
587       switch (dest_format) {
588         case GST_FORMAT_BYTES:{
589           index = gst_qtdemux_find_index_linear (qtdemux, stream, src_value);
590           if (-1 == index) {
591             res = FALSE;
592             goto done;
593           }
594
595           *dest_value = stream->samples[index].offset;
596
597           GST_DEBUG_OBJECT (qtdemux, "Format Conversion Time->Offset :%"
598               GST_TIME_FORMAT "->%" G_GUINT64_FORMAT,
599               GST_TIME_ARGS (src_value), *dest_value);
600           break;
601         }
602         default:
603           res = FALSE;
604           break;
605       }
606       break;
607     case GST_FORMAT_BYTES:
608       switch (dest_format) {
609         case GST_FORMAT_TIME:{
610           index =
611               gst_qtdemux_find_index_for_given_media_offset_linear (qtdemux,
612               stream, src_value);
613
614           if (-1 == index) {
615             res = FALSE;
616             goto done;
617           }
618
619           *dest_value =
620               QTSTREAMTIME_TO_GSTTIME (stream,
621               stream->samples[index].timestamp);
622           GST_DEBUG_OBJECT (qtdemux,
623               "Format Conversion Offset->Time :%" G_GUINT64_FORMAT "->%"
624               GST_TIME_FORMAT, src_value, GST_TIME_ARGS (*dest_value));
625           break;
626         }
627         default:
628           res = FALSE;
629           break;
630       }
631       break;
632     default:
633       res = FALSE;
634       break;
635   }
636
637 done:
638   return res;
639 }
640 #endif
641
642 static gboolean
643 gst_qtdemux_get_duration (GstQTDemux * qtdemux, GstClockTime * duration)
644 {
645   gboolean res = FALSE;
646
647   *duration = GST_CLOCK_TIME_NONE;
648
649   if (qtdemux->duration != 0 &&
650       qtdemux->duration != G_MAXINT64 && qtdemux->timescale != 0) {
651     *duration = QTTIME_TO_GSTTIME (qtdemux, qtdemux->duration);
652     res = TRUE;
653   } else {
654     *duration = GST_CLOCK_TIME_NONE;
655   }
656
657   return res;
658 }
659
660 static gboolean
661 gst_qtdemux_handle_src_query (GstPad * pad, GstObject * parent,
662     GstQuery * query)
663 {
664   gboolean res = FALSE;
665   GstQTDemux *qtdemux = GST_QTDEMUX (parent);
666
667   GST_LOG_OBJECT (pad, "%s query", GST_QUERY_TYPE_NAME (query));
668
669   switch (GST_QUERY_TYPE (query)) {
670     case GST_QUERY_POSITION:{
671       GstFormat fmt;
672
673       gst_query_parse_position (query, &fmt, NULL);
674       if (fmt == GST_FORMAT_TIME
675           && GST_CLOCK_TIME_IS_VALID (qtdemux->segment.position)) {
676         gst_query_set_position (query, GST_FORMAT_TIME,
677             qtdemux->segment.position);
678         res = TRUE;
679       }
680     }
681       break;
682     case GST_QUERY_DURATION:{
683       GstFormat fmt;
684
685       gst_query_parse_duration (query, &fmt, NULL);
686       if (fmt == GST_FORMAT_TIME) {
687         /* First try to query upstream */
688         res = gst_pad_query_default (pad, parent, query);
689         if (!res) {
690           GstClockTime duration;
691           if (gst_qtdemux_get_duration (qtdemux, &duration) && duration > 0) {
692             gst_query_set_duration (query, GST_FORMAT_TIME, duration);
693             res = TRUE;
694           }
695         }
696       }
697       break;
698     }
699     case GST_QUERY_CONVERT:{
700       GstFormat src_fmt, dest_fmt;
701       gint64 src_value, dest_value = 0;
702
703       gst_query_parse_convert (query, &src_fmt, &src_value, &dest_fmt, NULL);
704
705       res = gst_qtdemux_src_convert (qtdemux, pad,
706           src_fmt, src_value, dest_fmt, &dest_value);
707       if (res)
708         gst_query_set_convert (query, src_fmt, src_value, dest_fmt, dest_value);
709
710       break;
711     }
712     case GST_QUERY_FORMATS:
713       gst_query_set_formats (query, 2, GST_FORMAT_TIME, GST_FORMAT_BYTES);
714       res = TRUE;
715       break;
716     case GST_QUERY_SEEKING:{
717       GstFormat fmt;
718       gboolean seekable;
719
720       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
721
722       if (fmt == GST_FORMAT_BYTES) {
723         /* We always refuse BYTES seeks from downstream */
724         break;
725       }
726
727       /* try upstream first */
728       res = gst_pad_query_default (pad, parent, query);
729
730       if (!res) {
731         gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
732         if (fmt == GST_FORMAT_TIME) {
733           GstClockTime duration;
734
735           gst_qtdemux_get_duration (qtdemux, &duration);
736           seekable = TRUE;
737           if (!qtdemux->pullbased) {
738             GstQuery *q;
739
740             /* we might be able with help from upstream */
741             seekable = FALSE;
742             q = gst_query_new_seeking (GST_FORMAT_BYTES);
743             if (gst_pad_peer_query (qtdemux->sinkpad, q)) {
744               gst_query_parse_seeking (q, &fmt, &seekable, NULL, NULL);
745               GST_LOG_OBJECT (qtdemux, "upstream BYTE seekable %d", seekable);
746             }
747             gst_query_unref (q);
748           }
749           gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
750           res = TRUE;
751         }
752       }
753       break;
754     }
755     case GST_QUERY_SEGMENT:
756     {
757       GstFormat format;
758       gint64 start, stop;
759
760       format = qtdemux->segment.format;
761
762       start =
763           gst_segment_to_stream_time (&qtdemux->segment, format,
764           qtdemux->segment.start);
765       if ((stop = qtdemux->segment.stop) == -1)
766         stop = qtdemux->segment.duration;
767       else
768         stop = gst_segment_to_stream_time (&qtdemux->segment, format, stop);
769
770       gst_query_set_segment (query, qtdemux->segment.rate, format, start, stop);
771       res = TRUE;
772       break;
773     }
774     default:
775       res = gst_pad_query_default (pad, parent, query);
776       break;
777   }
778
779   return res;
780 }
781
782 static void
783 gst_qtdemux_push_tags (GstQTDemux * qtdemux, QtDemuxStream * stream)
784 {
785   if (G_LIKELY (stream->pad)) {
786     GST_DEBUG_OBJECT (qtdemux, "Checking pad %s:%s for tags",
787         GST_DEBUG_PAD_NAME (stream->pad));
788
789     if (!gst_tag_list_is_empty (stream->stream_tags)) {
790       GST_DEBUG_OBJECT (qtdemux, "Sending tags %" GST_PTR_FORMAT,
791           stream->stream_tags);
792       gst_pad_push_event (stream->pad,
793           gst_event_new_tag (gst_tag_list_ref (stream->stream_tags)));
794     }
795
796     if (G_UNLIKELY (stream->send_global_tags)) {
797       GST_DEBUG_OBJECT (qtdemux, "Sending global tags %" GST_PTR_FORMAT,
798           qtdemux->tag_list);
799       gst_pad_push_event (stream->pad,
800           gst_event_new_tag (gst_tag_list_ref (qtdemux->tag_list)));
801       stream->send_global_tags = FALSE;
802     }
803   }
804 }
805
806 /* push event on all source pads; takes ownership of the event */
807 static void
808 gst_qtdemux_push_event (GstQTDemux * qtdemux, GstEvent * event)
809 {
810   gboolean has_valid_stream = FALSE;
811   GstEventType etype = GST_EVENT_TYPE (event);
812   guint i;
813
814   GST_DEBUG_OBJECT (qtdemux, "pushing %s event on all source pads",
815       GST_EVENT_TYPE_NAME (event));
816
817   for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
818     GstPad *pad;
819     QtDemuxStream *stream = QTDEMUX_NTH_STREAM (qtdemux, i);
820     GST_DEBUG_OBJECT (qtdemux, "pushing on track-id %u", stream->track_id);
821
822     if ((pad = stream->pad)) {
823       has_valid_stream = TRUE;
824
825       if (etype == GST_EVENT_EOS) {
826         /* let's not send twice */
827         if (stream->sent_eos)
828           continue;
829         stream->sent_eos = TRUE;
830       }
831
832       gst_pad_push_event (pad, gst_event_ref (event));
833     }
834   }
835
836   gst_event_unref (event);
837
838   /* if it is EOS and there are no pads, post an error */
839   if (!has_valid_stream && etype == GST_EVENT_EOS) {
840     gst_qtdemux_post_no_playable_stream_error (qtdemux);
841   }
842 }
843
844 typedef struct
845 {
846   guint64 media_time;
847 } FindData;
848
849 static gint
850 find_func (QtDemuxSample * s1, gint64 * media_time, gpointer user_data)
851 {
852   if ((gint64) s1->timestamp > *media_time)
853     return 1;
854   if ((gint64) s1->timestamp == *media_time)
855     return 0;
856
857   return -1;
858 }
859
860 /* find the index of the sample that includes the data for @media_time using a
861  * binary search.  Only to be called in optimized cases of linear search below.
862  *
863  * Returns the index of the sample with the corresponding *DTS*.
864  */
865 static guint32
866 gst_qtdemux_find_index (GstQTDemux * qtdemux, QtDemuxStream * str,
867     guint64 media_time)
868 {
869   QtDemuxSample *result;
870   guint32 index;
871
872   /* convert media_time to mov format */
873   media_time =
874       gst_util_uint64_scale_ceil (media_time, str->timescale, GST_SECOND);
875
876   result = gst_util_array_binary_search (str->samples, str->stbl_index + 1,
877       sizeof (QtDemuxSample), (GCompareDataFunc) find_func,
878       GST_SEARCH_MODE_BEFORE, &media_time, NULL);
879
880   if (G_LIKELY (result))
881     index = result - str->samples;
882   else
883     index = 0;
884
885   return index;
886 }
887
888
889
890 /* find the index of the sample that includes the data for @media_offset using a
891  * linear search
892  *
893  * Returns the index of the sample.
894  */
895 static guint32
896 gst_qtdemux_find_index_for_given_media_offset_linear (GstQTDemux * qtdemux,
897     QtDemuxStream * str, gint64 media_offset)
898 {
899   QtDemuxSample *result = str->samples;
900   guint32 index = 0;
901
902   if (result == NULL || str->n_samples == 0)
903     return -1;
904
905   if (media_offset == result->offset)
906     return index;
907
908   result++;
909   while (index < str->n_samples - 1) {
910     if (!qtdemux_parse_samples (qtdemux, str, index + 1))
911       goto parse_failed;
912
913     if (media_offset < result->offset)
914       break;
915
916     index++;
917     result++;
918   }
919   return index;
920
921   /* ERRORS */
922 parse_failed:
923   {
924     GST_LOG_OBJECT (qtdemux, "Parsing of index %u failed!", index + 1);
925     return -1;
926   }
927 }
928
929 /* find the index of the sample that includes the data for @media_time using a
930  * linear search, and keeping in mind that not all samples may have been parsed
931  * yet.  If possible, it will delegate to binary search.
932  *
933  * Returns the index of the sample.
934  */
935 static guint32
936 gst_qtdemux_find_index_linear (GstQTDemux * qtdemux, QtDemuxStream * str,
937     GstClockTime media_time)
938 {
939   guint32 index = 0;
940   guint64 mov_time;
941   QtDemuxSample *sample;
942
943   /* convert media_time to mov format */
944   mov_time =
945       gst_util_uint64_scale_ceil (media_time, str->timescale, GST_SECOND);
946
947   sample = str->samples;
948   if (mov_time == sample->timestamp + sample->pts_offset)
949     return index;
950
951   /* use faster search if requested time in already parsed range */
952   sample = str->samples + str->stbl_index;
953   if (str->stbl_index >= 0 && mov_time <= sample->timestamp) {
954     index = gst_qtdemux_find_index (qtdemux, str, media_time);
955     sample = str->samples + index;
956   } else {
957     while (index < str->n_samples - 1) {
958       if (!qtdemux_parse_samples (qtdemux, str, index + 1))
959         goto parse_failed;
960
961       sample = str->samples + index + 1;
962       if (mov_time < sample->timestamp) {
963         sample = str->samples + index;
964         break;
965       }
966
967       index++;
968     }
969   }
970
971   /* sample->timestamp is now <= media_time, need to find the corresponding
972    * PTS now by looking backwards */
973   while (index > 0 && sample->timestamp + sample->pts_offset > mov_time) {
974     index--;
975     sample = str->samples + index;
976   }
977
978   return index;
979
980   /* ERRORS */
981 parse_failed:
982   {
983     GST_LOG_OBJECT (qtdemux, "Parsing of index %u failed!", index + 1);
984     return -1;
985   }
986 }
987
988 /* find the index of the keyframe needed to decode the sample at @index
989  * of stream @str, or of a subsequent keyframe (depending on @next)
990  *
991  * Returns the index of the keyframe.
992  */
993 static guint32
994 gst_qtdemux_find_keyframe (GstQTDemux * qtdemux, QtDemuxStream * str,
995     guint32 index, gboolean next)
996 {
997   guint32 new_index = index;
998
999   if (index >= str->n_samples) {
1000     new_index = str->n_samples;
1001     goto beach;
1002   }
1003
1004   /* all keyframes, return index */
1005   if (str->all_keyframe) {
1006     new_index = index;
1007     goto beach;
1008   }
1009
1010   /* else search until we have a keyframe */
1011   while (new_index < str->n_samples) {
1012     if (next && !qtdemux_parse_samples (qtdemux, str, new_index))
1013       goto parse_failed;
1014
1015     if (str->samples[new_index].keyframe)
1016       break;
1017
1018     if (new_index == 0)
1019       break;
1020
1021     if (next)
1022       new_index++;
1023     else
1024       new_index--;
1025   }
1026
1027   if (new_index == str->n_samples) {
1028     GST_DEBUG_OBJECT (qtdemux, "no next keyframe");
1029     new_index = -1;
1030   }
1031
1032 beach:
1033   GST_DEBUG_OBJECT (qtdemux, "searching for keyframe index %s index %u "
1034       "gave %u", next ? "after" : "before", index, new_index);
1035
1036   return new_index;
1037
1038   /* ERRORS */
1039 parse_failed:
1040   {
1041     GST_LOG_OBJECT (qtdemux, "Parsing of index %u failed!", new_index);
1042     return -1;
1043   }
1044 }
1045
1046 /* find the segment for @time_position for @stream
1047  *
1048  * Returns the index of the segment containing @time_position.
1049  * Returns the last segment and sets the @eos variable to TRUE
1050  * if the time is beyond the end. @eos may be NULL
1051  */
1052 static guint32
1053 gst_qtdemux_find_segment (GstQTDemux * qtdemux, QtDemuxStream * stream,
1054     GstClockTime time_position)
1055 {
1056   gint i;
1057   guint32 seg_idx;
1058
1059   GST_LOG_OBJECT (stream->pad, "finding segment for %" GST_TIME_FORMAT,
1060       GST_TIME_ARGS (time_position));
1061
1062   seg_idx = -1;
1063   for (i = 0; i < stream->n_segments; i++) {
1064     QtDemuxSegment *segment = &stream->segments[i];
1065
1066     GST_LOG_OBJECT (stream->pad,
1067         "looking at segment %" GST_TIME_FORMAT "-%" GST_TIME_FORMAT,
1068         GST_TIME_ARGS (segment->time), GST_TIME_ARGS (segment->stop_time));
1069
1070     /* For the last segment we include stop_time in the last segment */
1071     if (i < stream->n_segments - 1) {
1072       if (segment->time <= time_position && time_position < segment->stop_time) {
1073         GST_LOG_OBJECT (stream->pad, "segment %d matches", i);
1074         seg_idx = i;
1075         break;
1076       }
1077     } else {
1078       /* Last segment always matches */
1079       seg_idx = i;
1080       break;
1081     }
1082   }
1083   return seg_idx;
1084 }
1085
1086 /* move the stream @str to the sample position @index.
1087  *
1088  * Updates @str->sample_index and marks discontinuity if needed.
1089  */
1090 static void
1091 gst_qtdemux_move_stream (GstQTDemux * qtdemux, QtDemuxStream * str,
1092     guint32 index)
1093 {
1094   /* no change needed */
1095   if (index == str->sample_index)
1096     return;
1097
1098   GST_DEBUG_OBJECT (qtdemux, "moving to sample %u of %u", index,
1099       str->n_samples);
1100
1101   /* position changed, we have a discont */
1102   str->sample_index = index;
1103   str->offset_in_sample = 0;
1104   /* Each time we move in the stream we store the position where we are
1105    * starting from */
1106   str->from_sample = index;
1107   str->discont = TRUE;
1108 }
1109
1110 static void
1111 gst_qtdemux_adjust_seek (GstQTDemux * qtdemux, gint64 desired_time,
1112     gboolean use_sparse, gboolean next, gint64 * key_time, gint64 * key_offset)
1113 {
1114   guint64 min_offset;
1115   gint64 min_byte_offset = -1;
1116   guint i;
1117
1118   min_offset = desired_time;
1119
1120   /* for each stream, find the index of the sample in the segment
1121    * and move back to the previous keyframe. */
1122   for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
1123     QtDemuxStream *str;
1124     guint32 index, kindex;
1125     guint32 seg_idx;
1126     GstClockTime media_start;
1127     GstClockTime media_time;
1128     GstClockTime seg_time;
1129     QtDemuxSegment *seg;
1130     gboolean empty_segment = FALSE;
1131
1132     str = QTDEMUX_NTH_STREAM (qtdemux, i);
1133
1134     if (CUR_STREAM (str)->sparse && !use_sparse)
1135       continue;
1136
1137     seg_idx = gst_qtdemux_find_segment (qtdemux, str, desired_time);
1138     GST_DEBUG_OBJECT (qtdemux, "align segment %d", seg_idx);
1139
1140     /* get segment and time in the segment */
1141     seg = &str->segments[seg_idx];
1142     seg_time = (desired_time - seg->time) * seg->rate;
1143
1144     while (QTSEGMENT_IS_EMPTY (seg)) {
1145       seg_time = 0;
1146       empty_segment = TRUE;
1147       GST_DEBUG_OBJECT (str->pad, "Segment %d is empty, moving to next one",
1148           seg_idx);
1149       seg_idx++;
1150       if (seg_idx == str->n_segments)
1151         break;
1152       seg = &str->segments[seg_idx];
1153     }
1154
1155     if (seg_idx == str->n_segments) {
1156       /* FIXME track shouldn't have the last segment as empty, but if it
1157        * happens we better handle it */
1158       continue;
1159     }
1160
1161     /* get the media time in the segment */
1162     media_start = seg->media_start + seg_time;
1163
1164     /* get the index of the sample with media time */
1165     index = gst_qtdemux_find_index_linear (qtdemux, str, media_start);
1166     GST_DEBUG_OBJECT (qtdemux, "sample for %" GST_TIME_FORMAT " at %u"
1167         " at offset %" G_GUINT64_FORMAT " (empty segment: %d)",
1168         GST_TIME_ARGS (media_start), index, str->samples[index].offset,
1169         empty_segment);
1170
1171     /* shift to next frame if we are looking for next keyframe */
1172     if (next && QTSAMPLE_PTS_NO_CSLG (str, &str->samples[index]) < media_start
1173         && index < str->stbl_index)
1174       index++;
1175
1176     if (!empty_segment) {
1177       /* find previous keyframe */
1178       kindex = gst_qtdemux_find_keyframe (qtdemux, str, index, next);
1179
1180       /* we will settle for one before if none found after */
1181       if (next && kindex == -1)
1182         kindex = gst_qtdemux_find_keyframe (qtdemux, str, index, FALSE);
1183
1184       /* Update the requested time whenever a keyframe was found, to make it
1185        * accurate and avoid having the first buffer fall outside of the segment
1186        */
1187       if (kindex != -1) {
1188         index = kindex;
1189
1190         /* get timestamp of keyframe */
1191         media_time = QTSAMPLE_PTS_NO_CSLG (str, &str->samples[kindex]);
1192         GST_DEBUG_OBJECT (qtdemux,
1193             "keyframe at %u with time %" GST_TIME_FORMAT " at offset %"
1194             G_GUINT64_FORMAT, kindex, GST_TIME_ARGS (media_time),
1195             str->samples[kindex].offset);
1196
1197         /* keyframes in the segment get a chance to change the
1198          * desired_offset. keyframes out of the segment are
1199          * ignored. */
1200         if (media_time >= seg->media_start) {
1201           GstClockTime seg_time;
1202
1203           /* this keyframe is inside the segment, convert back to
1204            * segment time */
1205           seg_time = (media_time - seg->media_start) + seg->time;
1206           if ((!next && (seg_time < min_offset)) ||
1207               (next && (seg_time > min_offset)))
1208             min_offset = seg_time;
1209         }
1210       }
1211     }
1212
1213     if (min_byte_offset < 0 || str->samples[index].offset < min_byte_offset)
1214       min_byte_offset = str->samples[index].offset;
1215   }
1216
1217   if (key_time)
1218     *key_time = min_offset;
1219   if (key_offset)
1220     *key_offset = min_byte_offset;
1221 }
1222
1223 static gboolean
1224 gst_qtdemux_convert_seek (GstPad * pad, GstFormat * format,
1225     GstSeekType cur_type, gint64 * cur, GstSeekType stop_type, gint64 * stop)
1226 {
1227   gboolean res;
1228
1229   g_return_val_if_fail (format != NULL, FALSE);
1230   g_return_val_if_fail (cur != NULL, FALSE);
1231   g_return_val_if_fail (stop != NULL, FALSE);
1232
1233   if (*format == GST_FORMAT_TIME)
1234     return TRUE;
1235
1236   res = TRUE;
1237   if (cur_type != GST_SEEK_TYPE_NONE)
1238     res = gst_pad_query_convert (pad, *format, *cur, GST_FORMAT_TIME, cur);
1239   if (res && stop_type != GST_SEEK_TYPE_NONE)
1240     res = gst_pad_query_convert (pad, *format, *stop, GST_FORMAT_TIME, stop);
1241
1242   if (res)
1243     *format = GST_FORMAT_TIME;
1244
1245   return res;
1246 }
1247
1248 /* perform seek in push based mode:
1249    find BYTE position to move to based on time and delegate to upstream
1250 */
1251 static gboolean
1252 gst_qtdemux_do_push_seek (GstQTDemux * qtdemux, GstPad * pad, GstEvent * event)
1253 {
1254   gdouble rate;
1255   GstFormat format;
1256   GstSeekFlags flags;
1257   GstSeekType cur_type, stop_type;
1258   gint64 cur, stop, key_cur;
1259   gboolean res;
1260   gint64 byte_cur;
1261   gint64 original_stop;
1262   guint32 seqnum;
1263
1264   GST_DEBUG_OBJECT (qtdemux, "doing push-based seek");
1265
1266   gst_event_parse_seek (event, &rate, &format, &flags,
1267       &cur_type, &cur, &stop_type, &stop);
1268   seqnum = gst_event_get_seqnum (event);
1269
1270   /* Directly send the instant-rate-change event here before taking the
1271    * stream-lock so that it can be applied as soon as possible */
1272   if (flags & GST_SEEK_FLAG_INSTANT_RATE_CHANGE) {
1273     GstEvent *ev;
1274
1275     /* instant rate change only supported if direction does not change. All
1276      * other requirements are already checked before creating the seek event
1277      * but let's double-check here to be sure */
1278     if ((qtdemux->segment.rate > 0 && rate < 0) ||
1279         (qtdemux->segment.rate < 0 && rate > 0) ||
1280         cur_type != GST_SEEK_TYPE_NONE ||
1281         stop_type != GST_SEEK_TYPE_NONE || (flags & GST_SEEK_FLAG_FLUSH)) {
1282       GST_ERROR_OBJECT (qtdemux,
1283           "Instant rate change seeks only supported in the "
1284           "same direction, without flushing and position change");
1285       return FALSE;
1286     }
1287
1288     ev = gst_event_new_instant_rate_change (rate / qtdemux->segment.rate,
1289         (GstSegmentFlags) flags);
1290     gst_event_set_seqnum (ev, seqnum);
1291     gst_qtdemux_push_event (qtdemux, ev);
1292     return TRUE;
1293   }
1294
1295   /* only forward streaming and seeking is possible */
1296   if (rate <= 0)
1297     goto unsupported_seek;
1298
1299   /* convert to TIME if needed and possible */
1300   if (!gst_qtdemux_convert_seek (pad, &format, cur_type, &cur,
1301           stop_type, &stop))
1302     goto no_format;
1303
1304   /* Upstream seek in bytes will have undefined stop, but qtdemux stores
1305    * the original stop position to use when upstream pushes the new segment
1306    * for this seek */
1307   original_stop = stop;
1308   stop = -1;
1309
1310   /* find reasonable corresponding BYTE position,
1311    * also try to mind about keyframes, since we can not go back a bit for them
1312    * later on */
1313   /* determining @next here based on SNAP_BEFORE/SNAP_AFTER should
1314    * mostly just work, but let's not yet boldly go there  ... */
1315   gst_qtdemux_adjust_seek (qtdemux, cur, FALSE, FALSE, &key_cur, &byte_cur);
1316
1317   if (byte_cur == -1)
1318     goto abort_seek;
1319
1320   GST_DEBUG_OBJECT (qtdemux, "Pushing BYTE seek rate %g, "
1321       "start %" G_GINT64_FORMAT ", stop %" G_GINT64_FORMAT, rate, byte_cur,
1322       stop);
1323
1324   GST_OBJECT_LOCK (qtdemux);
1325   qtdemux->seek_offset = byte_cur;
1326   if (!(flags & GST_SEEK_FLAG_KEY_UNIT)) {
1327     qtdemux->push_seek_start = cur;
1328   } else {
1329     qtdemux->push_seek_start = key_cur;
1330   }
1331
1332   if (stop_type == GST_SEEK_TYPE_NONE) {
1333     qtdemux->push_seek_stop = qtdemux->segment.stop;
1334   } else {
1335     qtdemux->push_seek_stop = original_stop;
1336   }
1337   GST_OBJECT_UNLOCK (qtdemux);
1338
1339   qtdemux->segment_seqnum = seqnum;
1340   /* BYTE seek event */
1341   event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags, cur_type, byte_cur,
1342       stop_type, stop);
1343   gst_event_set_seqnum (event, seqnum);
1344   res = gst_pad_push_event (qtdemux->sinkpad, event);
1345
1346   return res;
1347
1348   /* ERRORS */
1349 abort_seek:
1350   {
1351     GST_DEBUG_OBJECT (qtdemux, "could not determine byte position to seek to, "
1352         "seek aborted.");
1353     return FALSE;
1354   }
1355 unsupported_seek:
1356   {
1357     GST_DEBUG_OBJECT (qtdemux, "unsupported seek, seek aborted.");
1358     return FALSE;
1359   }
1360 no_format:
1361   {
1362     GST_DEBUG_OBJECT (qtdemux, "unsupported format given, seek aborted.");
1363     return FALSE;
1364   }
1365 }
1366
1367 /* perform the seek.
1368  *
1369  * We set all segment_indexes in the streams to unknown and
1370  * adjust the time_position to the desired position. this is enough
1371  * to trigger a segment switch in the streaming thread to start
1372  * streaming from the desired position.
1373  *
1374  * Keyframe seeking is a little more complicated when dealing with
1375  * segments. Ideally we want to move to the previous keyframe in
1376  * the segment but there might not be a keyframe in the segment. In
1377  * fact, none of the segments could contain a keyframe. We take a
1378  * practical approach: seek to the previous keyframe in the segment,
1379  * if there is none, seek to the beginning of the segment.
1380  *
1381  * Called with STREAM_LOCK
1382  */
1383 static gboolean
1384 gst_qtdemux_perform_seek (GstQTDemux * qtdemux, GstSegment * segment,
1385     guint32 seqnum, GstSeekFlags flags)
1386 {
1387   gint64 desired_offset;
1388   guint i;
1389
1390   desired_offset = segment->position;
1391
1392   GST_DEBUG_OBJECT (qtdemux, "seeking to %" GST_TIME_FORMAT,
1393       GST_TIME_ARGS (desired_offset));
1394
1395   /* may not have enough fragmented info to do this adjustment,
1396    * and we can't scan (and probably should not) at this time with
1397    * possibly flushing upstream */
1398   if ((flags & GST_SEEK_FLAG_KEY_UNIT) && !qtdemux->fragmented) {
1399     gint64 min_offset;
1400     gboolean next, before, after;
1401
1402     before = ! !(flags & GST_SEEK_FLAG_SNAP_BEFORE);
1403     after = ! !(flags & GST_SEEK_FLAG_SNAP_AFTER);
1404     next = after && !before;
1405     if (segment->rate < 0)
1406       next = !next;
1407
1408     gst_qtdemux_adjust_seek (qtdemux, desired_offset, TRUE, next, &min_offset,
1409         NULL);
1410     GST_DEBUG_OBJECT (qtdemux, "keyframe seek, align to %"
1411         GST_TIME_FORMAT, GST_TIME_ARGS (min_offset));
1412     desired_offset = min_offset;
1413   }
1414
1415   /* and set all streams to the final position */
1416   GST_OBJECT_LOCK (qtdemux);
1417   gst_flow_combiner_reset (qtdemux->flowcombiner);
1418   GST_OBJECT_UNLOCK (qtdemux);
1419   qtdemux->segment_seqnum = seqnum;
1420   for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
1421     QtDemuxStream *stream = QTDEMUX_NTH_STREAM (qtdemux, i);
1422
1423     stream->time_position = desired_offset;
1424     stream->accumulated_base = 0;
1425     stream->sample_index = -1;
1426     stream->offset_in_sample = 0;
1427     stream->segment_index = -1;
1428     stream->sent_eos = FALSE;
1429     stream->last_keyframe_dts = GST_CLOCK_TIME_NONE;
1430
1431     if (segment->flags & GST_SEEK_FLAG_FLUSH)
1432       gst_segment_init (&stream->segment, GST_FORMAT_TIME);
1433   }
1434   segment->position = desired_offset;
1435   if (segment->rate >= 0) {
1436     segment->start = desired_offset;
1437     /* We need to update time as we update start in that direction */
1438     segment->time = desired_offset;
1439
1440     /* we stop at the end */
1441     if (segment->stop == -1)
1442       segment->stop = segment->duration;
1443   } else {
1444     segment->stop = desired_offset;
1445   }
1446
1447   if (qtdemux->fragmented)
1448     qtdemux->fragmented_seek_pending = TRUE;
1449
1450   return TRUE;
1451 }
1452
1453 /* do a seek in pull based mode */
1454 static gboolean
1455 gst_qtdemux_do_seek (GstQTDemux * qtdemux, GstPad * pad, GstEvent * event)
1456 {
1457   gdouble rate = 1.0;
1458   GstFormat format;
1459   GstSeekFlags flags;
1460   GstSeekType cur_type, stop_type;
1461   gint64 cur, stop;
1462   gboolean flush, instant_rate_change;
1463   gboolean update;
1464   GstSegment seeksegment;
1465   guint32 seqnum = GST_SEQNUM_INVALID;
1466   GstEvent *flush_event;
1467   gboolean ret;
1468
1469   GST_DEBUG_OBJECT (qtdemux, "doing seek with event");
1470
1471   gst_event_parse_seek (event, &rate, &format, &flags,
1472       &cur_type, &cur, &stop_type, &stop);
1473   seqnum = gst_event_get_seqnum (event);
1474
1475   /* we have to have a format as the segment format. Try to convert
1476    * if not. */
1477   if (!gst_qtdemux_convert_seek (pad, &format, cur_type, &cur,
1478           stop_type, &stop))
1479     goto no_format;
1480
1481   GST_DEBUG_OBJECT (qtdemux, "seek format %s", gst_format_get_name (format));
1482
1483   flush = ! !(flags & GST_SEEK_FLAG_FLUSH);
1484   instant_rate_change = ! !(flags & GST_SEEK_FLAG_INSTANT_RATE_CHANGE);
1485
1486   /* Directly send the instant-rate-change event here before taking the
1487    * stream-lock so that it can be applied as soon as possible */
1488   if (instant_rate_change) {
1489     GstEvent *ev;
1490
1491     /* instant rate change only supported if direction does not change. All
1492      * other requirements are already checked before creating the seek event
1493      * but let's double-check here to be sure */
1494     if ((qtdemux->segment.rate > 0 && rate < 0) ||
1495         (qtdemux->segment.rate < 0 && rate > 0) ||
1496         cur_type != GST_SEEK_TYPE_NONE ||
1497         stop_type != GST_SEEK_TYPE_NONE || flush) {
1498       GST_ERROR_OBJECT (qtdemux,
1499           "Instant rate change seeks only supported in the "
1500           "same direction, without flushing and position change");
1501       return FALSE;
1502     }
1503
1504     ev = gst_event_new_instant_rate_change (rate / qtdemux->segment.rate,
1505         (GstSegmentFlags) flags);
1506     gst_event_set_seqnum (ev, seqnum);
1507     gst_qtdemux_push_event (qtdemux, ev);
1508     return TRUE;
1509   }
1510
1511   /* stop streaming, either by flushing or by pausing the task */
1512   if (flush) {
1513     flush_event = gst_event_new_flush_start ();
1514     if (seqnum != GST_SEQNUM_INVALID)
1515       gst_event_set_seqnum (flush_event, seqnum);
1516     /* unlock upstream pull_range */
1517     gst_pad_push_event (qtdemux->sinkpad, gst_event_ref (flush_event));
1518     /* make sure out loop function exits */
1519     gst_qtdemux_push_event (qtdemux, flush_event);
1520   } else {
1521     /* non flushing seek, pause the task */
1522     gst_pad_pause_task (qtdemux->sinkpad);
1523   }
1524
1525   /* wait for streaming to finish */
1526   GST_PAD_STREAM_LOCK (qtdemux->sinkpad);
1527
1528   /* copy segment, we need this because we still need the old
1529    * segment when we close the current segment. */
1530   memcpy (&seeksegment, &qtdemux->segment, sizeof (GstSegment));
1531
1532   /* configure the segment with the seek variables */
1533   GST_DEBUG_OBJECT (qtdemux, "configuring seek");
1534   if (!gst_segment_do_seek (&seeksegment, rate, format, flags,
1535           cur_type, cur, stop_type, stop, &update)) {
1536     ret = FALSE;
1537     GST_ERROR_OBJECT (qtdemux, "inconsistent seek values, doing nothing");
1538   } else {
1539     /* now do the seek */
1540     ret = gst_qtdemux_perform_seek (qtdemux, &seeksegment, seqnum, flags);
1541   }
1542
1543   /* prepare for streaming again */
1544   if (flush) {
1545     flush_event = gst_event_new_flush_stop (TRUE);
1546     if (seqnum != GST_SEQNUM_INVALID)
1547       gst_event_set_seqnum (flush_event, seqnum);
1548
1549     gst_pad_push_event (qtdemux->sinkpad, gst_event_ref (flush_event));
1550     gst_qtdemux_push_event (qtdemux, flush_event);
1551   }
1552
1553   /* commit the new segment */
1554   memcpy (&qtdemux->segment, &seeksegment, sizeof (GstSegment));
1555
1556   if (qtdemux->segment.flags & GST_SEEK_FLAG_SEGMENT) {
1557     GstMessage *msg = gst_message_new_segment_start (GST_OBJECT_CAST (qtdemux),
1558         qtdemux->segment.format, qtdemux->segment.position);
1559     if (seqnum != GST_SEQNUM_INVALID)
1560       gst_message_set_seqnum (msg, seqnum);
1561     gst_element_post_message (GST_ELEMENT_CAST (qtdemux), msg);
1562   }
1563
1564   /* restart streaming, NEWSEGMENT will be sent from the streaming thread. */
1565   gst_pad_start_task (qtdemux->sinkpad, (GstTaskFunction) gst_qtdemux_loop,
1566       qtdemux->sinkpad, NULL);
1567
1568   GST_PAD_STREAM_UNLOCK (qtdemux->sinkpad);
1569
1570   return ret;
1571
1572   /* ERRORS */
1573 no_format:
1574   {
1575     GST_DEBUG_OBJECT (qtdemux, "unsupported format given, seek aborted.");
1576     return FALSE;
1577   }
1578 }
1579
1580 static gboolean
1581 qtdemux_ensure_index (GstQTDemux * qtdemux)
1582 {
1583   guint i;
1584
1585   GST_DEBUG_OBJECT (qtdemux, "collecting all metadata for all streams");
1586
1587   /* Build complete index */
1588   for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
1589     QtDemuxStream *stream = QTDEMUX_NTH_STREAM (qtdemux, i);
1590
1591     if (!qtdemux_parse_samples (qtdemux, stream, stream->n_samples - 1)) {
1592       GST_LOG_OBJECT (qtdemux,
1593           "Building complete index of track-id %u for seeking failed!",
1594           stream->track_id);
1595       return FALSE;
1596     }
1597   }
1598
1599   return TRUE;
1600 }
1601
1602 static gboolean
1603 gst_qtdemux_handle_src_event (GstPad * pad, GstObject * parent,
1604     GstEvent * event)
1605 {
1606   gboolean res = TRUE;
1607   GstQTDemux *qtdemux = GST_QTDEMUX (parent);
1608
1609   switch (GST_EVENT_TYPE (event)) {
1610     case GST_EVENT_RECONFIGURE:
1611       GST_OBJECT_LOCK (qtdemux);
1612       gst_flow_combiner_reset (qtdemux->flowcombiner);
1613       GST_OBJECT_UNLOCK (qtdemux);
1614       res = gst_pad_event_default (pad, parent, event);
1615       break;
1616     case GST_EVENT_SEEK:
1617     {
1618       GstSeekFlags flags = 0;
1619       GstFormat seek_format;
1620       gboolean instant_rate_change;
1621
1622 #ifndef GST_DISABLE_GST_DEBUG
1623       GstClockTime ts = gst_util_get_timestamp ();
1624 #endif
1625       guint32 seqnum = gst_event_get_seqnum (event);
1626
1627       qtdemux->received_seek = TRUE;
1628
1629       gst_event_parse_seek (event, NULL, &seek_format, &flags, NULL, NULL, NULL,
1630           NULL);
1631       instant_rate_change = ! !(flags & GST_SEEK_FLAG_INSTANT_RATE_CHANGE);
1632
1633       if (seqnum == qtdemux->segment_seqnum) {
1634         GST_LOG_OBJECT (pad,
1635             "Drop duplicated SEEK event seqnum %" G_GUINT32_FORMAT, seqnum);
1636         gst_event_unref (event);
1637         return TRUE;
1638       }
1639
1640       if (qtdemux->upstream_format_is_time && qtdemux->fragmented) {
1641         /* seek should be handled by upstream, we might need to re-download fragments */
1642         GST_DEBUG_OBJECT (qtdemux,
1643             "let upstream handle seek for fragmented playback");
1644         goto upstream;
1645       }
1646
1647       if (seek_format == GST_FORMAT_BYTES) {
1648         GST_DEBUG_OBJECT (pad, "Rejecting seek request in bytes format");
1649         gst_event_unref (event);
1650         return FALSE;
1651       }
1652
1653       gst_event_parse_seek_trickmode_interval (event,
1654           &qtdemux->trickmode_interval);
1655
1656       /* Build complete index for seeking;
1657        * if not a fragmented file at least and we're really doing a seek,
1658        * not just an instant-rate-change */
1659       if (!qtdemux->fragmented && !instant_rate_change) {
1660         if (!qtdemux_ensure_index (qtdemux))
1661           goto index_failed;
1662       }
1663 #ifndef GST_DISABLE_GST_DEBUG
1664       ts = gst_util_get_timestamp () - ts;
1665       GST_INFO_OBJECT (qtdemux,
1666           "Time taken to parse index %" GST_TIME_FORMAT, GST_TIME_ARGS (ts));
1667 #endif
1668       if (qtdemux->pullbased) {
1669         res = gst_qtdemux_do_seek (qtdemux, pad, event);
1670       } else if (gst_pad_push_event (qtdemux->sinkpad, gst_event_ref (event))) {
1671         GST_DEBUG_OBJECT (qtdemux, "Upstream successfully seeked");
1672         res = TRUE;
1673       } else if (qtdemux->state == QTDEMUX_STATE_MOVIE
1674           && QTDEMUX_N_STREAMS (qtdemux)
1675           && !qtdemux->fragmented) {
1676         res = gst_qtdemux_do_push_seek (qtdemux, pad, event);
1677       } else {
1678         GST_DEBUG_OBJECT (qtdemux,
1679             "ignoring seek in push mode in current state");
1680         res = FALSE;
1681       }
1682       gst_event_unref (event);
1683     }
1684       break;
1685     default:
1686     upstream:
1687       res = gst_pad_event_default (pad, parent, event);
1688       break;
1689   }
1690
1691 done:
1692   return res;
1693
1694   /* ERRORS */
1695 index_failed:
1696   {
1697     GST_ERROR_OBJECT (qtdemux, "Index failed");
1698     gst_event_unref (event);
1699     res = FALSE;
1700     goto done;
1701   }
1702 }
1703
1704 /* Find, for each track, the first sample in coding order that has a file offset >= @byte_pos.
1705  *
1706  * If @fw is false, the coding order is explored backwards.
1707  *
1708  * If @set is true, each stream will be moved to its matched sample, or EOS if no matching
1709  * sample is found for that track.
1710  *
1711  * The stream and sample index of the sample with the minimum offset in the direction explored
1712  * (see @fw) is returned in the output parameters @_stream and @_index respectively.
1713  *
1714  * @_time is set to the QTSAMPLE_PTS of the matched sample with the minimum QTSAMPLE_PTS in the
1715  * direction explored, which may not always match the QTSAMPLE_PTS of the sample returned in
1716  * @_stream and @_index. */
1717 static void
1718 gst_qtdemux_find_sample (GstQTDemux * qtdemux, gint64 byte_pos, gboolean fw,
1719     gboolean set, QtDemuxStream ** _stream, gint * _index, gint64 * _time)
1720 {
1721   gint i, index;
1722   gint64 time, min_time;
1723   QtDemuxStream *stream;
1724   gint iter;
1725
1726   min_time = -1;
1727   stream = NULL;
1728   index = -1;
1729
1730   for (iter = 0; iter < QTDEMUX_N_STREAMS (qtdemux); iter++) {
1731     QtDemuxStream *str;
1732     gint inc;
1733     gboolean set_sample;
1734
1735     str = QTDEMUX_NTH_STREAM (qtdemux, iter);
1736     set_sample = !set;
1737
1738     if (fw) {
1739       i = 0;
1740       inc = 1;
1741     } else {
1742       i = str->n_samples - 1;
1743       inc = -1;
1744     }
1745
1746     for (; (i >= 0) && (i < str->n_samples); i += inc) {
1747       if (str->samples[i].size == 0)
1748         continue;
1749
1750       if (fw && (str->samples[i].offset < byte_pos))
1751         continue;
1752
1753       if (!fw && (str->samples[i].offset + str->samples[i].size > byte_pos))
1754         continue;
1755
1756       /* move stream to first available sample */
1757       if (set) {
1758         gst_qtdemux_move_stream (qtdemux, str, i);
1759         set_sample = TRUE;
1760       }
1761
1762       /* avoid index from sparse streams since they might be far away */
1763       if (!CUR_STREAM (str)->sparse) {
1764         /* determine min/max time */
1765         time = QTSAMPLE_PTS (str, &str->samples[i]);
1766         if (min_time == -1 || (!fw && time > min_time) ||
1767             (fw && time < min_time)) {
1768           min_time = time;
1769         }
1770
1771         /* determine stream with leading sample, to get its position */
1772         if (!stream ||
1773             (fw && (str->samples[i].offset < stream->samples[index].offset)) ||
1774             (!fw && (str->samples[i].offset > stream->samples[index].offset))) {
1775           stream = str;
1776           index = i;
1777         }
1778       }
1779       break;
1780     }
1781
1782     /* no sample for this stream, mark eos */
1783     if (!set_sample)
1784       gst_qtdemux_move_stream (qtdemux, str, str->n_samples);
1785   }
1786
1787   if (_time)
1788     *_time = min_time;
1789   if (_stream)
1790     *_stream = stream;
1791   if (_index)
1792     *_index = index;
1793 }
1794
1795 /* Copied from mpegtsbase code */
1796 /* FIXME: replace this function when we add new util function for stream-id creation */
1797 static gchar *
1798 _get_upstream_id (GstQTDemux * demux)
1799 {
1800   gchar *upstream_id = gst_pad_get_stream_id (demux->sinkpad);
1801
1802   if (!upstream_id) {
1803     /* Try to create one from the upstream URI, else use a randome number */
1804     GstQuery *query;
1805     gchar *uri = NULL;
1806
1807     /* Try to generate one from the URI query and
1808      * if it fails take a random number instead */
1809     query = gst_query_new_uri ();
1810     if (gst_element_query (GST_ELEMENT_CAST (demux), query)) {
1811       gst_query_parse_uri (query, &uri);
1812     }
1813
1814     if (uri) {
1815       GChecksum *cs;
1816
1817       /* And then generate an SHA256 sum of the URI */
1818       cs = g_checksum_new (G_CHECKSUM_SHA256);
1819       g_checksum_update (cs, (const guchar *) uri, strlen (uri));
1820       g_free (uri);
1821       upstream_id = g_strdup (g_checksum_get_string (cs));
1822       g_checksum_free (cs);
1823     } else {
1824       /* Just get some random number if the URI query fails */
1825       GST_FIXME_OBJECT (demux, "Creating random stream-id, consider "
1826           "implementing a deterministic way of creating a stream-id");
1827       upstream_id =
1828           g_strdup_printf ("%08x%08x%08x%08x", g_random_int (), g_random_int (),
1829           g_random_int (), g_random_int ());
1830     }
1831
1832     gst_query_unref (query);
1833   }
1834   return upstream_id;
1835 }
1836
1837 static QtDemuxStream *
1838 _create_stream (GstQTDemux * demux, guint32 track_id)
1839 {
1840   QtDemuxStream *stream;
1841   gchar *upstream_id;
1842
1843   stream = g_new0 (QtDemuxStream, 1);
1844   stream->demux = demux;
1845   stream->track_id = track_id;
1846   upstream_id = _get_upstream_id (demux);
1847   stream->stream_id = g_strdup_printf ("%s/%03u", upstream_id, track_id);
1848   g_free (upstream_id);
1849   /* new streams always need a discont */
1850   stream->discont = TRUE;
1851   /* we enable clipping for raw audio/video streams */
1852   stream->need_clip = FALSE;
1853   stream->process_func = NULL;
1854   stream->segment_index = -1;
1855   stream->time_position = 0;
1856   stream->sample_index = -1;
1857   stream->offset_in_sample = 0;
1858   stream->new_stream = TRUE;
1859   stream->multiview_mode = GST_VIDEO_MULTIVIEW_MODE_NONE;
1860   stream->multiview_flags = GST_VIDEO_MULTIVIEW_FLAGS_NONE;
1861   stream->protected = FALSE;
1862   stream->protection_scheme_type = 0;
1863   stream->protection_scheme_version = 0;
1864   stream->protection_scheme_info = NULL;
1865   stream->n_samples_moof = 0;
1866   stream->duration_moof = 0;
1867   stream->duration_last_moof = 0;
1868   stream->alignment = 1;
1869   stream->stream_tags = gst_tag_list_new_empty ();
1870   gst_tag_list_set_scope (stream->stream_tags, GST_TAG_SCOPE_STREAM);
1871   g_queue_init (&stream->protection_scheme_event_queue);
1872   stream->ref_count = 1;
1873   /* consistent default for push based mode */
1874   gst_segment_init (&stream->segment, GST_FORMAT_TIME);
1875   return stream;
1876 }
1877
1878 static gboolean
1879 gst_qtdemux_setcaps (GstQTDemux * demux, GstCaps * caps)
1880 {
1881   GstStructure *structure;
1882   const gchar *variant;
1883   const GstCaps *mediacaps = NULL;
1884
1885   GST_DEBUG_OBJECT (demux, "Sink set caps: %" GST_PTR_FORMAT, caps);
1886
1887   structure = gst_caps_get_structure (caps, 0);
1888   variant = gst_structure_get_string (structure, "variant");
1889
1890   if (variant && strcmp (variant, "mss-fragmented") == 0) {
1891     QtDemuxStream *stream;
1892     const GValue *value;
1893
1894     demux->fragmented = TRUE;
1895     demux->mss_mode = TRUE;
1896
1897     if (QTDEMUX_N_STREAMS (demux) > 1) {
1898       /* can't do this, we can only renegotiate for another mss format */
1899       return FALSE;
1900     }
1901
1902     value = gst_structure_get_value (structure, "media-caps");
1903     /* create stream */
1904     if (value) {
1905       const GValue *timescale_v;
1906
1907       /* TODO update when stream changes during playback */
1908
1909       if (QTDEMUX_N_STREAMS (demux) == 0) {
1910         stream = _create_stream (demux, 1);
1911         g_ptr_array_add (demux->active_streams, stream);
1912         /* mss has no stsd/stsd entry, use id 0 as default */
1913         stream->stsd_entries_length = 1;
1914         stream->stsd_sample_description_id = stream->cur_stsd_entry_index = 0;
1915         stream->stsd_entries = g_new0 (QtDemuxStreamStsdEntry, 1);
1916       } else {
1917         stream = QTDEMUX_NTH_STREAM (demux, 0);
1918       }
1919
1920       timescale_v = gst_structure_get_value (structure, "timescale");
1921       if (timescale_v) {
1922         stream->timescale = g_value_get_uint64 (timescale_v);
1923       } else {
1924         /* default mss timescale */
1925         stream->timescale = 10000000;
1926       }
1927       demux->timescale = stream->timescale;
1928
1929       mediacaps = gst_value_get_caps (value);
1930       if (!CUR_STREAM (stream)->caps
1931           || !gst_caps_is_equal_fixed (mediacaps, CUR_STREAM (stream)->caps)) {
1932         GST_DEBUG_OBJECT (demux, "We have a new caps %" GST_PTR_FORMAT,
1933             mediacaps);
1934         stream->new_caps = TRUE;
1935       }
1936       gst_caps_replace (&CUR_STREAM (stream)->caps, (GstCaps *) mediacaps);
1937       structure = gst_caps_get_structure (mediacaps, 0);
1938       if (g_str_has_prefix (gst_structure_get_name (structure), "video")) {
1939         stream->subtype = FOURCC_vide;
1940
1941         gst_structure_get_int (structure, "width", &CUR_STREAM (stream)->width);
1942         gst_structure_get_int (structure, "height",
1943             &CUR_STREAM (stream)->height);
1944         gst_structure_get_fraction (structure, "framerate",
1945             &CUR_STREAM (stream)->fps_n, &CUR_STREAM (stream)->fps_d);
1946       } else if (g_str_has_prefix (gst_structure_get_name (structure), "audio")) {
1947         gint rate = 0;
1948         stream->subtype = FOURCC_soun;
1949         gst_structure_get_int (structure, "channels",
1950             &CUR_STREAM (stream)->n_channels);
1951         gst_structure_get_int (structure, "rate", &rate);
1952         CUR_STREAM (stream)->rate = rate;
1953       } else if (gst_structure_has_name (structure, "application/x-cenc")) {
1954         if (gst_structure_has_field (structure, "original-media-type")) {
1955           const gchar *media_type =
1956               gst_structure_get_string (structure, "original-media-type");
1957           if (g_str_has_prefix (media_type, "video")) {
1958             stream->subtype = FOURCC_vide;
1959           } else if (g_str_has_prefix (media_type, "audio")) {
1960             stream->subtype = FOURCC_soun;
1961           }
1962         }
1963       }
1964     }
1965     gst_caps_replace (&demux->media_caps, (GstCaps *) mediacaps);
1966   } else {
1967     demux->mss_mode = FALSE;
1968   }
1969
1970   return TRUE;
1971 }
1972
1973 static void
1974 gst_qtdemux_reset (GstQTDemux * qtdemux, gboolean hard)
1975 {
1976   gint i;
1977
1978   GST_DEBUG_OBJECT (qtdemux, "Resetting demux");
1979   gst_pad_stop_task (qtdemux->sinkpad);
1980
1981   if (hard || qtdemux->upstream_format_is_time) {
1982     qtdemux->state = QTDEMUX_STATE_INITIAL;
1983     qtdemux->neededbytes = 16;
1984     qtdemux->todrop = 0;
1985     qtdemux->pullbased = FALSE;
1986     g_clear_pointer (&qtdemux->redirect_location, g_free);
1987     qtdemux->first_mdat = -1;
1988     qtdemux->header_size = 0;
1989     qtdemux->mdatoffset = -1;
1990     qtdemux->restoredata_offset = -1;
1991     if (qtdemux->mdatbuffer)
1992       gst_buffer_unref (qtdemux->mdatbuffer);
1993     if (qtdemux->restoredata_buffer)
1994       gst_buffer_unref (qtdemux->restoredata_buffer);
1995     qtdemux->mdatbuffer = NULL;
1996     qtdemux->restoredata_buffer = NULL;
1997     qtdemux->mdatleft = 0;
1998     qtdemux->mdatsize = 0;
1999     if (qtdemux->comp_brands)
2000       gst_buffer_unref (qtdemux->comp_brands);
2001     qtdemux->comp_brands = NULL;
2002     qtdemux->last_moov_offset = -1;
2003     if (qtdemux->moov_node_compressed) {
2004       g_node_destroy (qtdemux->moov_node_compressed);
2005       if (qtdemux->moov_node)
2006         g_free (qtdemux->moov_node->data);
2007     }
2008     qtdemux->moov_node_compressed = NULL;
2009     if (qtdemux->moov_node)
2010       g_node_destroy (qtdemux->moov_node);
2011     qtdemux->moov_node = NULL;
2012     if (qtdemux->tag_list)
2013       gst_mini_object_unref (GST_MINI_OBJECT_CAST (qtdemux->tag_list));
2014     qtdemux->tag_list = gst_tag_list_new_empty ();
2015     gst_tag_list_set_scope (qtdemux->tag_list, GST_TAG_SCOPE_GLOBAL);
2016 #if 0
2017     if (qtdemux->element_index)
2018       gst_object_unref (qtdemux->element_index);
2019     qtdemux->element_index = NULL;
2020 #endif
2021     qtdemux->major_brand = 0;
2022     qtdemux->upstream_format_is_time = FALSE;
2023     qtdemux->upstream_seekable = FALSE;
2024     qtdemux->upstream_size = 0;
2025
2026     qtdemux->fragment_start = -1;
2027     qtdemux->fragment_start_offset = -1;
2028     qtdemux->duration = 0;
2029     qtdemux->moof_offset = 0;
2030     qtdemux->chapters_track_id = 0;
2031     qtdemux->have_group_id = FALSE;
2032     qtdemux->group_id = G_MAXUINT;
2033
2034     g_queue_foreach (&qtdemux->protection_event_queue, (GFunc) gst_event_unref,
2035         NULL);
2036     g_queue_clear (&qtdemux->protection_event_queue);
2037
2038     qtdemux->received_seek = FALSE;
2039     qtdemux->first_moof_already_parsed = FALSE;
2040   }
2041   qtdemux->offset = 0;
2042   gst_adapter_clear (qtdemux->adapter);
2043   gst_segment_init (&qtdemux->segment, GST_FORMAT_TIME);
2044   qtdemux->need_segment = TRUE;
2045
2046   if (hard) {
2047     qtdemux->segment_seqnum = GST_SEQNUM_INVALID;
2048     qtdemux->trickmode_interval = 0;
2049     g_ptr_array_set_size (qtdemux->active_streams, 0);
2050     g_ptr_array_set_size (qtdemux->old_streams, 0);
2051     qtdemux->n_video_streams = 0;
2052     qtdemux->n_audio_streams = 0;
2053     qtdemux->n_sub_streams = 0;
2054     qtdemux->exposed = FALSE;
2055     qtdemux->fragmented = FALSE;
2056     qtdemux->mss_mode = FALSE;
2057     gst_caps_replace (&qtdemux->media_caps, NULL);
2058     qtdemux->timescale = 0;
2059     qtdemux->got_moov = FALSE;
2060     qtdemux->cenc_aux_info_offset = 0;
2061     qtdemux->cenc_aux_info_sizes = NULL;
2062     qtdemux->cenc_aux_sample_count = 0;
2063     if (qtdemux->protection_system_ids) {
2064       g_ptr_array_free (qtdemux->protection_system_ids, TRUE);
2065       qtdemux->protection_system_ids = NULL;
2066     }
2067     qtdemux->streams_aware = GST_OBJECT_PARENT (qtdemux)
2068         && GST_OBJECT_FLAG_IS_SET (GST_OBJECT_PARENT (qtdemux),
2069         GST_BIN_FLAG_STREAMS_AWARE);
2070
2071     if (qtdemux->preferred_protection_system_id) {
2072       g_free (qtdemux->preferred_protection_system_id);
2073       qtdemux->preferred_protection_system_id = NULL;
2074     }
2075   } else if (qtdemux->mss_mode) {
2076     gst_flow_combiner_reset (qtdemux->flowcombiner);
2077     g_ptr_array_foreach (qtdemux->active_streams,
2078         (GFunc) gst_qtdemux_stream_clear, NULL);
2079   } else {
2080     gst_flow_combiner_reset (qtdemux->flowcombiner);
2081     for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
2082       QtDemuxStream *stream = QTDEMUX_NTH_STREAM (qtdemux, i);
2083       stream->sent_eos = FALSE;
2084       stream->time_position = 0;
2085       stream->accumulated_base = 0;
2086       stream->last_keyframe_dts = GST_CLOCK_TIME_NONE;
2087     }
2088   }
2089 }
2090
2091
2092 /* Maps the @segment to the qt edts internal segments and pushes
2093  * the corresponding segment event.
2094  *
2095  * If it ends up being at a empty segment, a gap will be pushed and the next
2096  * edts segment will be activated in sequence.
2097  *
2098  * To be used in push-mode only */
2099 static void
2100 gst_qtdemux_map_and_push_segments (GstQTDemux * qtdemux, GstSegment * segment)
2101 {
2102   gint i, iter;
2103
2104   for (iter = 0; iter < QTDEMUX_N_STREAMS (qtdemux); iter++) {
2105     QtDemuxStream *stream = QTDEMUX_NTH_STREAM (qtdemux, iter);
2106
2107     stream->time_position = segment->start;
2108
2109     /* in push mode we should be guaranteed that we will have empty segments
2110      * at the beginning and then one segment after, other scenarios are not
2111      * supported and are discarded when parsing the edts */
2112     for (i = 0; i < stream->n_segments; i++) {
2113       if (stream->segments[i].stop_time > segment->start) {
2114         /* push the empty segment and move to the next one */
2115         gst_qtdemux_activate_segment (qtdemux, stream, i,
2116             stream->time_position);
2117         if (QTSEGMENT_IS_EMPTY (&stream->segments[i])) {
2118           gst_qtdemux_send_gap_for_segment (qtdemux, stream, i,
2119               stream->time_position);
2120
2121           /* accumulate previous segments */
2122           if (GST_CLOCK_TIME_IS_VALID (stream->segment.stop))
2123             stream->accumulated_base +=
2124                 (stream->segment.stop -
2125                 stream->segment.start) / ABS (stream->segment.rate);
2126           continue;
2127         }
2128
2129         g_assert (i == stream->n_segments - 1);
2130       }
2131     }
2132   }
2133 }
2134
2135 static void
2136 gst_qtdemux_stream_concat (GstQTDemux * qtdemux, GPtrArray * dest,
2137     GPtrArray * src)
2138 {
2139   guint i;
2140   guint len;
2141
2142   len = src->len;
2143
2144   if (len == 0)
2145     return;
2146
2147   for (i = 0; i < len; i++) {
2148     QtDemuxStream *stream = g_ptr_array_index (src, i);
2149
2150 #ifndef GST_DISABLE_GST_DEBUG
2151     GST_DEBUG_OBJECT (qtdemux, "Move stream %p (stream-id %s) to %p",
2152         stream, GST_STR_NULL (stream->stream_id), dest);
2153 #endif
2154     g_ptr_array_add (dest, gst_qtdemux_stream_ref (stream));
2155   }
2156
2157   g_ptr_array_set_size (src, 0);
2158 }
2159
2160 static gboolean
2161 gst_qtdemux_handle_sink_event (GstPad * sinkpad, GstObject * parent,
2162     GstEvent * event)
2163 {
2164   GstQTDemux *demux = GST_QTDEMUX (parent);
2165   gboolean res = TRUE;
2166
2167   GST_LOG_OBJECT (demux, "handling %s event", GST_EVENT_TYPE_NAME (event));
2168
2169   switch (GST_EVENT_TYPE (event)) {
2170     case GST_EVENT_SEGMENT:
2171     {
2172       gint64 offset = 0;
2173       QtDemuxStream *stream;
2174       gint idx;
2175       GstSegment segment;
2176
2177       /* some debug output */
2178       gst_event_copy_segment (event, &segment);
2179       GST_DEBUG_OBJECT (demux, "received newsegment %" GST_SEGMENT_FORMAT,
2180           &segment);
2181
2182       if (segment.format == GST_FORMAT_TIME) {
2183         demux->upstream_format_is_time = TRUE;
2184         demux->segment_seqnum = gst_event_get_seqnum (event);
2185       } else {
2186         GST_DEBUG_OBJECT (demux, "Not storing upstream newsegment, "
2187             "not in time format");
2188
2189         /* chain will send initial newsegment after pads have been added */
2190         if (demux->state != QTDEMUX_STATE_MOVIE || !QTDEMUX_N_STREAMS (demux)) {
2191           GST_DEBUG_OBJECT (demux, "still starting, eating event");
2192           goto exit;
2193         }
2194       }
2195
2196       /* check if this matches a time seek we received previously
2197        * FIXME for backwards compatibility reasons we use the
2198        * seek_offset here to compare. In the future we might want to
2199        * change this to use the seqnum as it uniquely should identify
2200        * the segment that corresponds to the seek. */
2201       GST_DEBUG_OBJECT (demux, "Stored seek offset: %" G_GINT64_FORMAT
2202           ", received segment offset %" G_GINT64_FORMAT,
2203           demux->seek_offset, segment.start);
2204       if (segment.format == GST_FORMAT_BYTES
2205           && demux->seek_offset == segment.start) {
2206         GST_OBJECT_LOCK (demux);
2207         offset = segment.start;
2208
2209         segment.format = GST_FORMAT_TIME;
2210         segment.start = demux->push_seek_start;
2211         segment.stop = demux->push_seek_stop;
2212         GST_DEBUG_OBJECT (demux, "Replaced segment with stored seek "
2213             "segment %" GST_TIME_FORMAT " - %" GST_TIME_FORMAT,
2214             GST_TIME_ARGS (segment.start), GST_TIME_ARGS (segment.stop));
2215         GST_OBJECT_UNLOCK (demux);
2216       }
2217
2218       /* we only expect a BYTE segment, e.g. following a seek */
2219       if (segment.format == GST_FORMAT_BYTES) {
2220         if (GST_CLOCK_TIME_IS_VALID (segment.start)) {
2221           offset = segment.start;
2222
2223           gst_qtdemux_find_sample (demux, segment.start, TRUE, FALSE, NULL,
2224               NULL, (gint64 *) & segment.start);
2225           if ((gint64) segment.start < 0)
2226             segment.start = 0;
2227         }
2228         if (GST_CLOCK_TIME_IS_VALID (segment.stop)) {
2229           gst_qtdemux_find_sample (demux, segment.stop, FALSE, FALSE, NULL,
2230               NULL, (gint64 *) & segment.stop);
2231           /* keyframe seeking should already arrange for start >= stop,
2232            * but make sure in other rare cases */
2233           segment.stop = MAX (segment.stop, segment.start);
2234         }
2235       } else if (segment.format == GST_FORMAT_TIME) {
2236         /* push all data on the adapter before starting this
2237          * new segment */
2238         gst_qtdemux_process_adapter (demux, TRUE);
2239       } else {
2240         GST_DEBUG_OBJECT (demux, "unsupported segment format, ignoring");
2241         goto exit;
2242       }
2243
2244       /* We shouldn't modify upstream driven TIME FORMAT segment */
2245       if (!demux->upstream_format_is_time) {
2246         /* accept upstream's notion of segment and distribute along */
2247         segment.format = GST_FORMAT_TIME;
2248         segment.position = segment.time = segment.start;
2249         segment.duration = demux->segment.duration;
2250         segment.base = gst_segment_to_running_time (&demux->segment,
2251             GST_FORMAT_TIME, demux->segment.position);
2252       }
2253
2254       gst_segment_copy_into (&segment, &demux->segment);
2255       GST_DEBUG_OBJECT (demux, "Pushing newseg %" GST_SEGMENT_FORMAT, &segment);
2256
2257       /* map segment to internal qt segments and push on each stream */
2258       if (QTDEMUX_N_STREAMS (demux)) {
2259         demux->need_segment = TRUE;
2260         gst_qtdemux_check_send_pending_segment (demux);
2261       }
2262
2263       /* clear leftover in current segment, if any */
2264       gst_adapter_clear (demux->adapter);
2265
2266       /* set up streaming thread */
2267       demux->offset = offset;
2268       if (demux->upstream_format_is_time) {
2269         GST_DEBUG_OBJECT (demux, "Upstream is driving in time format, "
2270             "set values to restart reading from a new atom");
2271         demux->neededbytes = 16;
2272         demux->todrop = 0;
2273       } else {
2274         gst_qtdemux_find_sample (demux, offset, TRUE, TRUE, &stream, &idx,
2275             NULL);
2276         if (stream) {
2277           demux->todrop = stream->samples[idx].offset - offset;
2278           demux->neededbytes = demux->todrop + stream->samples[idx].size;
2279         } else {
2280           /* set up for EOS */
2281           demux->neededbytes = -1;
2282           demux->todrop = 0;
2283         }
2284       }
2285     exit:
2286       gst_event_unref (event);
2287       res = TRUE;
2288       goto drop;
2289     }
2290     case GST_EVENT_FLUSH_START:
2291     {
2292       if (gst_event_get_seqnum (event) == demux->offset_seek_seqnum) {
2293         gst_event_unref (event);
2294         goto drop;
2295       }
2296       QTDEMUX_EXPOSE_LOCK (demux);
2297       res = gst_pad_event_default (demux->sinkpad, parent, event);
2298       QTDEMUX_EXPOSE_UNLOCK (demux);
2299       goto drop;
2300     }
2301     case GST_EVENT_FLUSH_STOP:
2302     {
2303       guint64 dur;
2304
2305       dur = demux->segment.duration;
2306       gst_qtdemux_reset (demux, FALSE);
2307       demux->segment.duration = dur;
2308
2309       if (gst_event_get_seqnum (event) == demux->offset_seek_seqnum) {
2310         gst_event_unref (event);
2311         goto drop;
2312       }
2313       break;
2314     }
2315     case GST_EVENT_EOS:
2316       /* If we are in push mode, and get an EOS before we've seen any streams,
2317        * then error out - we have nowhere to send the EOS */
2318       if (!demux->pullbased) {
2319         gint i;
2320         gboolean has_valid_stream = FALSE;
2321         for (i = 0; i < QTDEMUX_N_STREAMS (demux); i++) {
2322           if (QTDEMUX_NTH_STREAM (demux, i)->pad != NULL) {
2323             has_valid_stream = TRUE;
2324             break;
2325           }
2326         }
2327         if (!has_valid_stream)
2328           gst_qtdemux_post_no_playable_stream_error (demux);
2329         else {
2330           GST_DEBUG_OBJECT (demux, "Data still available after EOS: %u",
2331               (guint) gst_adapter_available (demux->adapter));
2332           if (gst_qtdemux_process_adapter (demux, TRUE) != GST_FLOW_OK) {
2333             res = FALSE;
2334           }
2335         }
2336       }
2337       break;
2338     case GST_EVENT_CAPS:{
2339       GstCaps *caps = NULL;
2340
2341       gst_event_parse_caps (event, &caps);
2342       gst_qtdemux_setcaps (demux, caps);
2343       res = TRUE;
2344       gst_event_unref (event);
2345       goto drop;
2346     }
2347     case GST_EVENT_PROTECTION:
2348     {
2349       const gchar *system_id = NULL;
2350
2351       gst_event_parse_protection (event, &system_id, NULL, NULL);
2352       GST_DEBUG_OBJECT (demux, "Received protection event for system ID %s",
2353           system_id);
2354       gst_qtdemux_append_protection_system_id (demux, system_id);
2355       /* save the event for later, for source pads that have not been created */
2356       g_queue_push_tail (&demux->protection_event_queue, gst_event_ref (event));
2357       /* send it to all pads that already exist */
2358       gst_qtdemux_push_event (demux, event);
2359       res = TRUE;
2360       goto drop;
2361     }
2362     case GST_EVENT_STREAM_START:
2363     {
2364       res = TRUE;
2365       gst_event_unref (event);
2366
2367       /* Drain all the buffers */
2368       gst_qtdemux_process_adapter (demux, TRUE);
2369       gst_qtdemux_reset (demux, FALSE);
2370       /* We expect new moov box after new stream-start event */
2371       if (demux->exposed) {
2372         gst_qtdemux_stream_concat (demux,
2373             demux->old_streams, demux->active_streams);
2374       }
2375
2376       goto drop;
2377     }
2378     default:
2379       break;
2380   }
2381
2382   res = gst_pad_event_default (demux->sinkpad, parent, event) & res;
2383
2384 drop:
2385   return res;
2386 }
2387
2388 static gboolean
2389 gst_qtdemux_handle_sink_query (GstPad * pad, GstObject * parent,
2390     GstQuery * query)
2391 {
2392   GstQTDemux *demux = GST_QTDEMUX (parent);
2393   gboolean res = FALSE;
2394
2395   switch (GST_QUERY_TYPE (query)) {
2396     case GST_QUERY_BITRATE:
2397     {
2398       GstClockTime duration;
2399
2400       /* populate demux->upstream_size if not done yet */
2401       gst_qtdemux_check_seekability (demux);
2402
2403       if (demux->upstream_size != -1
2404           && gst_qtdemux_get_duration (demux, &duration)) {
2405         guint bitrate =
2406             gst_util_uint64_scale (8 * demux->upstream_size, GST_SECOND,
2407             duration);
2408
2409         GST_LOG_OBJECT (demux, "bitrate query byte length: %" G_GUINT64_FORMAT
2410             " duration %" GST_TIME_FORMAT " resulting a bitrate of %u",
2411             demux->upstream_size, GST_TIME_ARGS (duration), bitrate);
2412
2413         /* TODO: better results based on ranges/index tables */
2414         gst_query_set_bitrate (query, bitrate);
2415         res = TRUE;
2416       }
2417       break;
2418     }
2419     default:
2420       res = gst_pad_query_default (pad, (GstObject *) demux, query);
2421       break;
2422   }
2423
2424   return res;
2425 }
2426
2427
2428 #if 0
2429 static void
2430 gst_qtdemux_set_index (GstElement * element, GstIndex * index)
2431 {
2432   GstQTDemux *demux = GST_QTDEMUX (element);
2433
2434   GST_OBJECT_LOCK (demux);
2435   if (demux->element_index)
2436     gst_object_unref (demux->element_index);
2437   if (index) {
2438     demux->element_index = gst_object_ref (index);
2439   } else {
2440     demux->element_index = NULL;
2441   }
2442   GST_OBJECT_UNLOCK (demux);
2443   /* object lock might be taken again */
2444   if (index)
2445     gst_index_get_writer_id (index, GST_OBJECT (element), &demux->index_id);
2446   GST_DEBUG_OBJECT (demux, "Set index %" GST_PTR_FORMAT "for writer id %d",
2447       demux->element_index, demux->index_id);
2448 }
2449
2450 static GstIndex *
2451 gst_qtdemux_get_index (GstElement * element)
2452 {
2453   GstIndex *result = NULL;
2454   GstQTDemux *demux = GST_QTDEMUX (element);
2455
2456   GST_OBJECT_LOCK (demux);
2457   if (demux->element_index)
2458     result = gst_object_ref (demux->element_index);
2459   GST_OBJECT_UNLOCK (demux);
2460
2461   GST_DEBUG_OBJECT (demux, "Returning index %" GST_PTR_FORMAT, result);
2462
2463   return result;
2464 }
2465 #endif
2466
2467 static void
2468 gst_qtdemux_stbl_free (QtDemuxStream * stream)
2469 {
2470   g_free ((gpointer) stream->stco.data);
2471   stream->stco.data = NULL;
2472   g_free ((gpointer) stream->stsz.data);
2473   stream->stsz.data = NULL;
2474   g_free ((gpointer) stream->stsc.data);
2475   stream->stsc.data = NULL;
2476   g_free ((gpointer) stream->stts.data);
2477   stream->stts.data = NULL;
2478   g_free ((gpointer) stream->stss.data);
2479   stream->stss.data = NULL;
2480   g_free ((gpointer) stream->stps.data);
2481   stream->stps.data = NULL;
2482   g_free ((gpointer) stream->ctts.data);
2483   stream->ctts.data = NULL;
2484 }
2485
2486 static void
2487 gst_qtdemux_stream_flush_segments_data (QtDemuxStream * stream)
2488 {
2489   g_free (stream->segments);
2490   stream->segments = NULL;
2491   stream->segment_index = -1;
2492   stream->accumulated_base = 0;
2493 }
2494
2495 static void
2496 gst_qtdemux_stream_flush_samples_data (QtDemuxStream * stream)
2497 {
2498   g_free (stream->samples);
2499   stream->samples = NULL;
2500   gst_qtdemux_stbl_free (stream);
2501
2502   /* fragments */
2503   g_free (stream->ra_entries);
2504   stream->ra_entries = NULL;
2505   stream->n_ra_entries = 0;
2506
2507   stream->sample_index = -1;
2508   stream->stbl_index = -1;
2509   stream->n_samples = 0;
2510   stream->time_position = 0;
2511
2512   stream->n_samples_moof = 0;
2513   stream->duration_moof = 0;
2514   stream->duration_last_moof = 0;
2515 }
2516
2517 static void
2518 gst_qtdemux_stream_clear (QtDemuxStream * stream)
2519 {
2520   gint i;
2521   if (stream->allocator)
2522     gst_object_unref (stream->allocator);
2523   while (stream->buffers) {
2524     gst_buffer_unref (GST_BUFFER_CAST (stream->buffers->data));
2525     stream->buffers = g_slist_delete_link (stream->buffers, stream->buffers);
2526   }
2527   for (i = 0; i < stream->stsd_entries_length; i++) {
2528     QtDemuxStreamStsdEntry *entry = &stream->stsd_entries[i];
2529     if (entry->rgb8_palette) {
2530       gst_memory_unref (entry->rgb8_palette);
2531       entry->rgb8_palette = NULL;
2532     }
2533     entry->sparse = FALSE;
2534   }
2535
2536   if (stream->stream_tags)
2537     gst_tag_list_unref (stream->stream_tags);
2538
2539   stream->stream_tags = gst_tag_list_new_empty ();
2540   gst_tag_list_set_scope (stream->stream_tags, GST_TAG_SCOPE_STREAM);
2541   g_free (stream->redirect_uri);
2542   stream->redirect_uri = NULL;
2543   stream->sent_eos = FALSE;
2544   stream->protected = FALSE;
2545   if (stream->protection_scheme_info) {
2546     if (stream->protection_scheme_type == FOURCC_cenc
2547         || stream->protection_scheme_type == FOURCC_cbcs) {
2548       QtDemuxCencSampleSetInfo *info =
2549           (QtDemuxCencSampleSetInfo *) stream->protection_scheme_info;
2550       if (info->default_properties)
2551         gst_structure_free (info->default_properties);
2552       if (info->crypto_info)
2553         g_ptr_array_free (info->crypto_info, TRUE);
2554     }
2555     if (stream->protection_scheme_type == FOURCC_aavd) {
2556       QtDemuxAavdEncryptionInfo *info =
2557           (QtDemuxAavdEncryptionInfo *) stream->protection_scheme_info;
2558       if (info->default_properties)
2559         gst_structure_free (info->default_properties);
2560     }
2561     g_free (stream->protection_scheme_info);
2562     stream->protection_scheme_info = NULL;
2563   }
2564   stream->protection_scheme_type = 0;
2565   stream->protection_scheme_version = 0;
2566   g_queue_foreach (&stream->protection_scheme_event_queue,
2567       (GFunc) gst_event_unref, NULL);
2568   g_queue_clear (&stream->protection_scheme_event_queue);
2569   gst_qtdemux_stream_flush_segments_data (stream);
2570   gst_qtdemux_stream_flush_samples_data (stream);
2571 }
2572
2573 static void
2574 gst_qtdemux_stream_reset (QtDemuxStream * stream)
2575 {
2576   gint i;
2577   gst_qtdemux_stream_clear (stream);
2578   for (i = 0; i < stream->stsd_entries_length; i++) {
2579     QtDemuxStreamStsdEntry *entry = &stream->stsd_entries[i];
2580     if (entry->caps) {
2581       gst_caps_unref (entry->caps);
2582       entry->caps = NULL;
2583     }
2584   }
2585   g_free (stream->stsd_entries);
2586   stream->stsd_entries = NULL;
2587   stream->stsd_entries_length = 0;
2588 }
2589
2590 static QtDemuxStream *
2591 gst_qtdemux_stream_ref (QtDemuxStream * stream)
2592 {
2593   g_atomic_int_add (&stream->ref_count, 1);
2594
2595   return stream;
2596 }
2597
2598 static void
2599 gst_qtdemux_stream_unref (QtDemuxStream * stream)
2600 {
2601   if (g_atomic_int_dec_and_test (&stream->ref_count)) {
2602     gst_qtdemux_stream_reset (stream);
2603     gst_tag_list_unref (stream->stream_tags);
2604     if (stream->pad) {
2605       GstQTDemux *demux = stream->demux;
2606       gst_element_remove_pad (GST_ELEMENT_CAST (demux), stream->pad);
2607       GST_OBJECT_LOCK (demux);
2608       gst_flow_combiner_remove_pad (demux->flowcombiner, stream->pad);
2609       GST_OBJECT_UNLOCK (demux);
2610     }
2611     g_free (stream->stream_id);
2612     g_free (stream);
2613   }
2614 }
2615
2616 static GstStateChangeReturn
2617 gst_qtdemux_change_state (GstElement * element, GstStateChange transition)
2618 {
2619   GstQTDemux *qtdemux = GST_QTDEMUX (element);
2620   GstStateChangeReturn result = GST_STATE_CHANGE_FAILURE;
2621
2622   switch (transition) {
2623     case GST_STATE_CHANGE_READY_TO_PAUSED:
2624       gst_qtdemux_reset (qtdemux, TRUE);
2625       break;
2626     default:
2627       break;
2628   }
2629
2630   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2631
2632   switch (transition) {
2633     case GST_STATE_CHANGE_PAUSED_TO_READY:{
2634       gst_qtdemux_reset (qtdemux, TRUE);
2635       break;
2636     }
2637     default:
2638       break;
2639   }
2640
2641   return result;
2642 }
2643
2644 static void
2645 gst_qtdemux_set_context (GstElement * element, GstContext * context)
2646 {
2647   GstQTDemux *qtdemux = GST_QTDEMUX (element);
2648
2649   g_return_if_fail (GST_IS_CONTEXT (context));
2650
2651   if (gst_context_has_context_type (context,
2652           "drm-preferred-decryption-system-id")) {
2653     const GstStructure *s;
2654
2655     s = gst_context_get_structure (context);
2656     g_free (qtdemux->preferred_protection_system_id);
2657     qtdemux->preferred_protection_system_id =
2658         g_strdup (gst_structure_get_string (s, "decryption-system-id"));
2659     GST_DEBUG_OBJECT (element, "set preferred decryption system to %s",
2660         qtdemux->preferred_protection_system_id);
2661   }
2662
2663   GST_ELEMENT_CLASS (parent_class)->set_context (element, context);
2664 }
2665
2666 static void
2667 qtdemux_parse_ftyp (GstQTDemux * qtdemux, const guint8 * buffer, gint length)
2668 {
2669   /* counts as header data */
2670   qtdemux->header_size += length;
2671
2672   /* only consider at least a sufficiently complete ftyp atom */
2673   if (length >= 20) {
2674     GstBuffer *buf;
2675
2676     qtdemux->major_brand = QT_FOURCC (buffer + 8);
2677     GST_DEBUG_OBJECT (qtdemux, "major brand: %" GST_FOURCC_FORMAT,
2678         GST_FOURCC_ARGS (qtdemux->major_brand));
2679     if (qtdemux->comp_brands)
2680       gst_buffer_unref (qtdemux->comp_brands);
2681     buf = qtdemux->comp_brands = gst_buffer_new_and_alloc (length - 16);
2682     gst_buffer_fill (buf, 0, buffer + 16, length - 16);
2683   }
2684 }
2685
2686 static void
2687 qtdemux_update_default_sample_cenc_settings (GstQTDemux * qtdemux,
2688     QtDemuxCencSampleSetInfo * info, guint32 is_encrypted,
2689     guint32 protection_scheme_type, guint8 iv_size, const guint8 * kid,
2690     guint crypt_byte_block, guint skip_byte_block, guint8 constant_iv_size,
2691     const guint8 * constant_iv)
2692 {
2693   GstBuffer *kid_buf = gst_buffer_new_allocate (NULL, 16, NULL);
2694   gst_buffer_fill (kid_buf, 0, kid, 16);
2695   if (info->default_properties)
2696     gst_structure_free (info->default_properties);
2697   info->default_properties =
2698       gst_structure_new ("application/x-cenc",
2699       "iv_size", G_TYPE_UINT, iv_size,
2700       "encrypted", G_TYPE_BOOLEAN, (is_encrypted == 1),
2701       "kid", GST_TYPE_BUFFER, kid_buf, NULL);
2702   GST_DEBUG_OBJECT (qtdemux, "default sample properties: "
2703       "is_encrypted=%u, iv_size=%u", is_encrypted, iv_size);
2704   gst_buffer_unref (kid_buf);
2705   if (protection_scheme_type == FOURCC_cbcs) {
2706     if (crypt_byte_block != 0 || skip_byte_block != 0) {
2707       gst_structure_set (info->default_properties, "crypt_byte_block",
2708           G_TYPE_UINT, crypt_byte_block, "skip_byte_block", G_TYPE_UINT,
2709           skip_byte_block, NULL);
2710     }
2711     if (constant_iv != NULL) {
2712       GstBuffer *constant_iv_buf =
2713           gst_buffer_new_allocate (NULL, constant_iv_size, NULL);
2714       gst_buffer_fill (constant_iv_buf, 0, constant_iv, constant_iv_size);
2715       gst_structure_set (info->default_properties, "constant_iv_size",
2716           G_TYPE_UINT, constant_iv_size, "iv", GST_TYPE_BUFFER, constant_iv_buf,
2717           NULL);
2718       gst_buffer_unref (constant_iv_buf);
2719     }
2720     gst_structure_set (info->default_properties, "cipher-mode",
2721         G_TYPE_STRING, "cbcs", NULL);
2722   } else {
2723     gst_structure_set (info->default_properties, "cipher-mode",
2724         G_TYPE_STRING, "cenc", NULL);
2725   }
2726 }
2727
2728 static gboolean
2729 qtdemux_update_default_piff_encryption_settings (GstQTDemux * qtdemux,
2730     QtDemuxCencSampleSetInfo * info, GstByteReader * br)
2731 {
2732   guint32 algorithm_id = 0;
2733   const guint8 *kid;
2734   gboolean is_encrypted = TRUE;
2735   guint8 iv_size = 8;
2736
2737   if (!gst_byte_reader_get_uint24_le (br, &algorithm_id)) {
2738     GST_ERROR_OBJECT (qtdemux, "Error getting box's algorithm ID field");
2739     return FALSE;
2740   }
2741
2742   algorithm_id >>= 8;
2743   if (algorithm_id == 0) {
2744     is_encrypted = FALSE;
2745   } else if (algorithm_id == 1) {
2746     GST_DEBUG_OBJECT (qtdemux, "AES 128-bits CTR encrypted stream");
2747   } else if (algorithm_id == 2) {
2748     GST_DEBUG_OBJECT (qtdemux, "AES 128-bits CBC encrypted stream");
2749   }
2750
2751   if (!gst_byte_reader_get_uint8 (br, &iv_size))
2752     return FALSE;
2753
2754   if (!gst_byte_reader_get_data (br, 16, &kid))
2755     return FALSE;
2756
2757   qtdemux_update_default_sample_cenc_settings (qtdemux, info,
2758       is_encrypted, FOURCC_cenc, iv_size, kid, 0, 0, 0, NULL);
2759   gst_structure_set (info->default_properties, "piff_algorithm_id",
2760       G_TYPE_UINT, algorithm_id, NULL);
2761   return TRUE;
2762 }
2763
2764
2765 static void
2766 qtdemux_parse_piff (GstQTDemux * qtdemux, const guint8 * buffer, gint length,
2767     guint offset)
2768 {
2769   GstByteReader br;
2770   guint8 version;
2771   guint32 flags = 0;
2772   guint i;
2773   guint iv_size = 8;
2774   QtDemuxStream *stream;
2775   GstStructure *structure;
2776   QtDemuxCencSampleSetInfo *ss_info = NULL;
2777   const gchar *system_id;
2778   gboolean uses_sub_sample_encryption = FALSE;
2779   guint32 sample_count;
2780
2781   if (QTDEMUX_N_STREAMS (qtdemux) == 0)
2782     return;
2783
2784   stream = QTDEMUX_NTH_STREAM (qtdemux, 0);
2785
2786   structure = gst_caps_get_structure (CUR_STREAM (stream)->caps, 0);
2787   if (!gst_structure_has_name (structure, "application/x-cenc")) {
2788     GST_WARNING_OBJECT (qtdemux,
2789         "Attempting PIFF box parsing on an unencrypted stream.");
2790     return;
2791   }
2792
2793   gst_structure_get (structure, GST_PROTECTION_SYSTEM_ID_CAPS_FIELD,
2794       G_TYPE_STRING, &system_id, NULL);
2795   gst_qtdemux_append_protection_system_id (qtdemux, system_id);
2796
2797   stream->protected = TRUE;
2798   stream->protection_scheme_type = FOURCC_cenc;
2799
2800   if (!stream->protection_scheme_info)
2801     stream->protection_scheme_info = g_new0 (QtDemuxCencSampleSetInfo, 1);
2802
2803   ss_info = (QtDemuxCencSampleSetInfo *) stream->protection_scheme_info;
2804   if (!ss_info->default_properties) {
2805     ss_info->default_properties =
2806         gst_structure_new ("application/x-cenc",
2807         "iv_size", G_TYPE_UINT, iv_size, "encrypted", G_TYPE_BOOLEAN, TRUE,
2808         NULL);
2809
2810   }
2811
2812   if (ss_info->crypto_info) {
2813     GST_LOG_OBJECT (qtdemux, "unreffing existing crypto_info");
2814     g_ptr_array_free (ss_info->crypto_info, TRUE);
2815     ss_info->crypto_info = NULL;
2816   }
2817
2818   /* skip UUID */
2819   gst_byte_reader_init (&br, buffer + offset + 16, length - offset - 16);
2820
2821   if (!gst_byte_reader_get_uint8 (&br, &version)) {
2822     GST_ERROR_OBJECT (qtdemux, "Error getting box's version field");
2823     return;
2824   }
2825
2826   if (!gst_byte_reader_get_uint24_be (&br, &flags)) {
2827     GST_ERROR_OBJECT (qtdemux, "Error getting box's flags field");
2828     return;
2829   }
2830
2831   if ((flags & 0x000001)) {
2832     if (!qtdemux_update_default_piff_encryption_settings (qtdemux, ss_info,
2833             &br))
2834       return;
2835   } else if ((flags & 0x000002)) {
2836     uses_sub_sample_encryption = TRUE;
2837   }
2838
2839   if (!gst_structure_get_uint (ss_info->default_properties, "iv_size",
2840           &iv_size)) {
2841     GST_ERROR_OBJECT (qtdemux, "Error getting encryption IV size field");
2842     return;
2843   }
2844
2845   if (!gst_byte_reader_get_uint32_be (&br, &sample_count)) {
2846     GST_ERROR_OBJECT (qtdemux, "Error getting box's sample count field");
2847     return;
2848   }
2849
2850   ss_info->crypto_info =
2851       g_ptr_array_new_full (sample_count,
2852       (GDestroyNotify) qtdemux_gst_structure_free);
2853
2854   for (i = 0; i < sample_count; ++i) {
2855     GstStructure *properties;
2856     guint8 *data;
2857     GstBuffer *buf;
2858
2859     properties = qtdemux_get_cenc_sample_properties (qtdemux, stream, i);
2860     if (properties == NULL) {
2861       GST_ERROR_OBJECT (qtdemux, "failed to get properties for sample %u", i);
2862       qtdemux->cenc_aux_sample_count = i;
2863       return;
2864     }
2865
2866     if (!gst_byte_reader_dup_data (&br, iv_size, &data)) {
2867       GST_ERROR_OBJECT (qtdemux, "IV data not present for sample %u", i);
2868       gst_structure_free (properties);
2869       qtdemux->cenc_aux_sample_count = i;
2870       return;
2871     }
2872     buf = gst_buffer_new_wrapped (data, iv_size);
2873     gst_structure_set (properties, "iv", GST_TYPE_BUFFER, buf, NULL);
2874     gst_buffer_unref (buf);
2875
2876     if (uses_sub_sample_encryption) {
2877       guint16 n_subsamples;
2878       const GValue *kid_buf_value;
2879
2880       if (!gst_byte_reader_get_uint16_be (&br, &n_subsamples)
2881           || n_subsamples == 0) {
2882         GST_ERROR_OBJECT (qtdemux,
2883             "failed to get subsample count for sample %u", i);
2884         gst_structure_free (properties);
2885         qtdemux->cenc_aux_sample_count = i;
2886         return;
2887       }
2888       GST_LOG_OBJECT (qtdemux, "subsample count: %u", n_subsamples);
2889       if (!gst_byte_reader_dup_data (&br, n_subsamples * 6, &data)) {
2890         GST_ERROR_OBJECT (qtdemux, "failed to get subsample data for sample %u",
2891             i);
2892         gst_structure_free (properties);
2893         qtdemux->cenc_aux_sample_count = i;
2894         return;
2895       }
2896       buf = gst_buffer_new_wrapped (data, n_subsamples * 6);
2897
2898       kid_buf_value =
2899           gst_structure_get_value (ss_info->default_properties, "kid");
2900
2901       gst_structure_set (properties,
2902           "subsample_count", G_TYPE_UINT, n_subsamples,
2903           "subsamples", GST_TYPE_BUFFER, buf, NULL);
2904       gst_structure_set_value (properties, "kid", kid_buf_value);
2905       gst_buffer_unref (buf);
2906     } else {
2907       gst_structure_set (properties, "subsample_count", G_TYPE_UINT, 0, NULL);
2908     }
2909
2910     g_ptr_array_add (ss_info->crypto_info, properties);
2911   }
2912
2913   qtdemux->cenc_aux_sample_count = sample_count;
2914 }
2915
2916 static void
2917 qtdemux_parse_uuid (GstQTDemux * qtdemux, const guint8 * buffer, gint length)
2918 {
2919   static const guint8 xmp_uuid[] = { 0xBE, 0x7A, 0xCF, 0xCB,
2920     0x97, 0xA9, 0x42, 0xE8,
2921     0x9C, 0x71, 0x99, 0x94,
2922     0x91, 0xE3, 0xAF, 0xAC
2923   };
2924   static const guint8 playready_uuid[] = {
2925     0xd0, 0x8a, 0x4f, 0x18, 0x10, 0xf3, 0x4a, 0x82,
2926     0xb6, 0xc8, 0x32, 0xd8, 0xab, 0xa1, 0x83, 0xd3
2927   };
2928
2929   static const guint8 piff_sample_encryption_uuid[] = {
2930     0xa2, 0x39, 0x4f, 0x52, 0x5a, 0x9b, 0x4f, 0x14,
2931     0xa2, 0x44, 0x6c, 0x42, 0x7c, 0x64, 0x8d, 0xf4
2932   };
2933
2934   guint offset;
2935
2936   /* counts as header data */
2937   qtdemux->header_size += length;
2938
2939   offset = (QT_UINT32 (buffer) == 0) ? 16 : 8;
2940
2941   if (length <= offset + 16) {
2942     GST_DEBUG_OBJECT (qtdemux, "uuid atom is too short, skipping");
2943     return;
2944   }
2945
2946   if (memcmp (buffer + offset, xmp_uuid, 16) == 0) {
2947     GstBuffer *buf;
2948     GstTagList *taglist;
2949
2950     buf = _gst_buffer_new_wrapped ((guint8 *) buffer + offset + 16,
2951         length - offset - 16, NULL);
2952     taglist = gst_tag_list_from_xmp_buffer (buf);
2953     gst_buffer_unref (buf);
2954
2955     /* make sure we have a usable taglist */
2956     qtdemux->tag_list = gst_tag_list_make_writable (qtdemux->tag_list);
2957
2958     qtdemux_handle_xmp_taglist (qtdemux, qtdemux->tag_list, taglist);
2959
2960   } else if (memcmp (buffer + offset, playready_uuid, 16) == 0) {
2961     int len;
2962     const gunichar2 *s_utf16;
2963     char *contents;
2964
2965     len = GST_READ_UINT16_LE (buffer + offset + 0x30);
2966     s_utf16 = (const gunichar2 *) (buffer + offset + 0x32);
2967     contents = g_utf16_to_utf8 (s_utf16, len / 2, NULL, NULL, NULL);
2968     GST_ERROR_OBJECT (qtdemux, "contents: %s", contents);
2969
2970     g_free (contents);
2971
2972     GST_ELEMENT_ERROR (qtdemux, STREAM, DECRYPT,
2973         (_("Cannot play stream because it is encrypted with PlayReady DRM.")),
2974         (NULL));
2975   } else if (memcmp (buffer + offset, piff_sample_encryption_uuid, 16) == 0) {
2976     qtdemux_parse_piff (qtdemux, buffer, length, offset);
2977   } else {
2978     GST_DEBUG_OBJECT (qtdemux, "Ignoring unknown uuid: %08x-%08x-%08x-%08x",
2979         GST_READ_UINT32_LE (buffer + offset),
2980         GST_READ_UINT32_LE (buffer + offset + 4),
2981         GST_READ_UINT32_LE (buffer + offset + 8),
2982         GST_READ_UINT32_LE (buffer + offset + 12));
2983   }
2984 }
2985
2986 static void
2987 qtdemux_parse_sidx (GstQTDemux * qtdemux, const guint8 * buffer, gint length)
2988 {
2989   GstSidxParser sidx_parser;
2990   GstIsoffParserResult res;
2991   guint consumed;
2992
2993   gst_isoff_qt_sidx_parser_init (&sidx_parser);
2994
2995   res =
2996       gst_isoff_qt_sidx_parser_add_data (&sidx_parser, buffer, length,
2997       &consumed);
2998   GST_DEBUG_OBJECT (qtdemux, "sidx parse result: %d", res);
2999   if (res == GST_ISOFF_QT_PARSER_DONE) {
3000     check_update_duration (qtdemux, sidx_parser.cumulative_pts);
3001   }
3002   gst_isoff_qt_sidx_parser_clear (&sidx_parser);
3003 }
3004
3005 /* caller verifies at least 8 bytes in buf */
3006 static void
3007 extract_initial_length_and_fourcc (const guint8 * data, guint size,
3008     guint64 * plength, guint32 * pfourcc)
3009 {
3010   guint64 length;
3011   guint32 fourcc;
3012
3013   length = QT_UINT32 (data);
3014   GST_DEBUG ("length 0x%08" G_GINT64_MODIFIER "x", length);
3015   fourcc = QT_FOURCC (data + 4);
3016   GST_DEBUG ("atom type %" GST_FOURCC_FORMAT, GST_FOURCC_ARGS (fourcc));
3017
3018   if (length == 0) {
3019     length = G_MAXUINT64;
3020   } else if (length == 1 && size >= 16) {
3021     /* this means we have an extended size, which is the 64 bit value of
3022      * the next 8 bytes */
3023     length = QT_UINT64 (data + 8);
3024     GST_DEBUG ("length 0x%08" G_GINT64_MODIFIER "x", length);
3025   }
3026
3027   if (plength)
3028     *plength = length;
3029   if (pfourcc)
3030     *pfourcc = fourcc;
3031 }
3032
3033 static gboolean
3034 qtdemux_parse_mehd (GstQTDemux * qtdemux, GstByteReader * br)
3035 {
3036   guint32 version = 0;
3037   GstClockTime duration = 0;
3038
3039   if (!gst_byte_reader_get_uint32_be (br, &version))
3040     goto failed;
3041
3042   version >>= 24;
3043   if (version == 1) {
3044     if (!gst_byte_reader_get_uint64_be (br, &duration))
3045       goto failed;
3046   } else {
3047     guint32 dur = 0;
3048
3049     if (!gst_byte_reader_get_uint32_be (br, &dur))
3050       goto failed;
3051     duration = dur;
3052   }
3053
3054   GST_INFO_OBJECT (qtdemux, "mehd duration: %" G_GUINT64_FORMAT, duration);
3055   qtdemux->duration = duration;
3056
3057   return TRUE;
3058
3059 failed:
3060   {
3061     GST_DEBUG_OBJECT (qtdemux, "parsing mehd failed");
3062     return FALSE;
3063   }
3064 }
3065
3066 static gboolean
3067 qtdemux_parse_trex (GstQTDemux * qtdemux, QtDemuxStream * stream,
3068     guint32 * ds_duration, guint32 * ds_size, guint32 * ds_flags)
3069 {
3070   if (!stream->parsed_trex && qtdemux->moov_node) {
3071     GNode *mvex, *trex;
3072     GstByteReader trex_data;
3073
3074     mvex = qtdemux_tree_get_child_by_type (qtdemux->moov_node, FOURCC_mvex);
3075     if (mvex) {
3076       trex = qtdemux_tree_get_child_by_type_full (mvex, FOURCC_trex,
3077           &trex_data);
3078       while (trex) {
3079         guint32 id = 0, sdi = 0, dur = 0, size = 0, flags = 0;
3080
3081         /* skip version/flags */
3082         if (!gst_byte_reader_skip (&trex_data, 4))
3083           goto next;
3084         if (!gst_byte_reader_get_uint32_be (&trex_data, &id))
3085           goto next;
3086         if (id != stream->track_id)
3087           goto next;
3088         if (!gst_byte_reader_get_uint32_be (&trex_data, &sdi))
3089           goto next;
3090         if (!gst_byte_reader_get_uint32_be (&trex_data, &dur))
3091           goto next;
3092         if (!gst_byte_reader_get_uint32_be (&trex_data, &size))
3093           goto next;
3094         if (!gst_byte_reader_get_uint32_be (&trex_data, &flags))
3095           goto next;
3096
3097         GST_DEBUG_OBJECT (qtdemux, "fragment defaults for stream %d; "
3098             "duration %d,  size %d, flags 0x%x", stream->track_id,
3099             dur, size, flags);
3100
3101         stream->parsed_trex = TRUE;
3102         stream->def_sample_description_index = sdi;
3103         stream->def_sample_duration = dur;
3104         stream->def_sample_size = size;
3105         stream->def_sample_flags = flags;
3106
3107       next:
3108         /* iterate all siblings */
3109         trex = qtdemux_tree_get_sibling_by_type_full (trex, FOURCC_trex,
3110             &trex_data);
3111       }
3112     }
3113   }
3114
3115   *ds_duration = stream->def_sample_duration;
3116   *ds_size = stream->def_sample_size;
3117   *ds_flags = stream->def_sample_flags;
3118
3119   /* even then, above values are better than random ... */
3120   if (G_UNLIKELY (!stream->parsed_trex)) {
3121     GST_WARNING_OBJECT (qtdemux,
3122         "failed to find fragment defaults for stream %d", stream->track_id);
3123     return FALSE;
3124   }
3125
3126   return TRUE;
3127 }
3128
3129 /* This method should be called whenever a more accurate duration might
3130  * have been found. It will update all relevant variables if/where needed
3131  */
3132 static void
3133 check_update_duration (GstQTDemux * qtdemux, GstClockTime duration)
3134 {
3135   guint i;
3136   guint64 movdur;
3137   GstClockTime prevdur;
3138
3139   movdur = GSTTIME_TO_QTTIME (qtdemux, duration);
3140
3141   if (movdur > qtdemux->duration) {
3142     prevdur = QTTIME_TO_GSTTIME (qtdemux, qtdemux->duration);
3143     GST_DEBUG_OBJECT (qtdemux,
3144         "Updating total duration to %" GST_TIME_FORMAT " was %" GST_TIME_FORMAT,
3145         GST_TIME_ARGS (duration), GST_TIME_ARGS (prevdur));
3146     qtdemux->duration = movdur;
3147     GST_DEBUG_OBJECT (qtdemux,
3148         "qtdemux->segment.duration: %" GST_TIME_FORMAT " .stop: %"
3149         GST_TIME_FORMAT, GST_TIME_ARGS (qtdemux->segment.duration),
3150         GST_TIME_ARGS (qtdemux->segment.stop));
3151     if (qtdemux->segment.duration == prevdur) {
3152       /* If the current segment has duration/stop identical to previous duration
3153        * update them also (because they were set at that point in time with
3154        * the wrong duration */
3155       /* We convert the value *from* the timescale version to avoid rounding errors */
3156       GstClockTime fixeddur = QTTIME_TO_GSTTIME (qtdemux, movdur);
3157       GST_DEBUG_OBJECT (qtdemux, "Updated segment.duration and segment.stop");
3158       qtdemux->segment.duration = fixeddur;
3159       qtdemux->segment.stop = fixeddur;
3160     }
3161   }
3162
3163   for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
3164     QtDemuxStream *stream = QTDEMUX_NTH_STREAM (qtdemux, i);
3165
3166     movdur = GSTTIME_TO_QTSTREAMTIME (stream, duration);
3167     if (movdur > stream->duration) {
3168       GST_DEBUG_OBJECT (qtdemux,
3169           "Updating stream #%d duration to %" GST_TIME_FORMAT, i,
3170           GST_TIME_ARGS (duration));
3171       stream->duration = movdur;
3172       /* internal duration tracking state has been updated above, so */
3173       /* preserve an open-ended dummy segment rather than repeatedly updating
3174        * it and spamming downstream accordingly with segment events */
3175       /* also mangle the edit list end time when fragmented with a single edit
3176        * list that may only cover any non-fragmented data */
3177       if ((stream->dummy_segment ||
3178               (qtdemux->fragmented && stream->n_segments == 1)) &&
3179           GST_CLOCK_TIME_IS_VALID (stream->segments[0].duration)) {
3180         /* Update all dummy values to new duration */
3181         stream->segments[0].stop_time = duration;
3182         stream->segments[0].duration = duration;
3183         stream->segments[0].media_stop = duration;
3184
3185         /* let downstream know we possibly have a new stop time */
3186         if (stream->segment_index != -1) {
3187           GstClockTime pos;
3188
3189           if (qtdemux->segment.rate >= 0) {
3190             pos = stream->segment.start;
3191           } else {
3192             pos = stream->segment.stop;
3193           }
3194
3195           gst_qtdemux_stream_update_segment (qtdemux, stream,
3196               stream->segment_index, pos, NULL, NULL);
3197         }
3198       }
3199     }
3200   }
3201 }
3202
3203 static gboolean
3204 qtdemux_parse_trun (GstQTDemux * qtdemux, GstByteReader * trun,
3205     QtDemuxStream * stream, guint32 d_sample_duration, guint32 d_sample_size,
3206     guint32 d_sample_flags, gint64 moof_offset, gint64 moof_length,
3207     gint64 * base_offset, gint64 * running_offset, gint64 decode_ts,
3208     gboolean has_tfdt)
3209 {
3210   GstClockTime gst_ts = GST_CLOCK_TIME_NONE;
3211   guint64 timestamp;
3212   gint32 data_offset = 0;
3213   guint8 version;
3214   guint32 flags = 0, first_flags = 0, samples_count = 0;
3215   gint i;
3216   guint8 *data;
3217   guint entry_size, dur_offset, size_offset, flags_offset = 0, ct_offset = 0;
3218   QtDemuxSample *sample;
3219   gboolean ismv = FALSE;
3220   gint64 initial_offset;
3221   gint32 min_ct = 0;
3222
3223   GST_LOG_OBJECT (qtdemux, "parsing trun track-id %d; "
3224       "default dur %d, size %d, flags 0x%x, base offset %" G_GINT64_FORMAT ", "
3225       "decode ts %" G_GINT64_FORMAT, stream->track_id, d_sample_duration,
3226       d_sample_size, d_sample_flags, *base_offset, decode_ts);
3227
3228   if (stream->pending_seek && moof_offset < stream->pending_seek->moof_offset) {
3229     GST_INFO_OBJECT (stream->pad, "skipping trun before seek target fragment");
3230     return TRUE;
3231   }
3232
3233   /* presence of stss or not can't really tell us much,
3234    * and flags and so on tend to be marginally reliable in these files */
3235   if (stream->subtype == FOURCC_soun) {
3236     GST_DEBUG_OBJECT (qtdemux,
3237         "sound track in fragmented file; marking all keyframes");
3238     stream->all_keyframe = TRUE;
3239   }
3240
3241   if (!gst_byte_reader_get_uint8 (trun, &version) ||
3242       !gst_byte_reader_get_uint24_be (trun, &flags))
3243     goto fail;
3244
3245   if (!gst_byte_reader_get_uint32_be (trun, &samples_count))
3246     goto fail;
3247
3248   if (flags & TR_DATA_OFFSET) {
3249     /* note this is really signed */
3250     if (!gst_byte_reader_get_int32_be (trun, &data_offset))
3251       goto fail;
3252     GST_LOG_OBJECT (qtdemux, "trun data offset %d", data_offset);
3253     /* default base offset = first byte of moof */
3254     if (*base_offset == -1) {
3255       GST_LOG_OBJECT (qtdemux, "base_offset at moof");
3256       *base_offset = moof_offset;
3257     }
3258     *running_offset = *base_offset + data_offset;
3259   } else {
3260     /* if no offset at all, that would mean data starts at moof start,
3261      * which is a bit wrong and is ismv crappy way, so compensate
3262      * assuming data is in mdat following moof */
3263     if (*base_offset == -1) {
3264       *base_offset = moof_offset + moof_length + 8;
3265       GST_LOG_OBJECT (qtdemux, "base_offset assumed in mdat after moof");
3266       ismv = TRUE;
3267     }
3268     if (*running_offset == -1)
3269       *running_offset = *base_offset;
3270   }
3271
3272   GST_LOG_OBJECT (qtdemux, "running offset now %" G_GINT64_FORMAT,
3273       *running_offset);
3274   GST_LOG_OBJECT (qtdemux, "trun offset %d, flags 0x%x, entries %d",
3275       data_offset, flags, samples_count);
3276
3277   if (flags & TR_FIRST_SAMPLE_FLAGS) {
3278     if (G_UNLIKELY (flags & TR_SAMPLE_FLAGS)) {
3279       GST_DEBUG_OBJECT (qtdemux,
3280           "invalid flags; SAMPLE and FIRST_SAMPLE present, discarding latter");
3281       flags ^= TR_FIRST_SAMPLE_FLAGS;
3282     } else {
3283       if (!gst_byte_reader_get_uint32_be (trun, &first_flags))
3284         goto fail;
3285       GST_LOG_OBJECT (qtdemux, "first flags: 0x%x", first_flags);
3286     }
3287   }
3288
3289   /* FIXME ? spec says other bits should also be checked to determine
3290    * entry size (and prefix size for that matter) */
3291   entry_size = 0;
3292   dur_offset = size_offset = 0;
3293   if (flags & TR_SAMPLE_DURATION) {
3294     GST_LOG_OBJECT (qtdemux, "entry duration present");
3295     dur_offset = entry_size;
3296     entry_size += 4;
3297   }
3298   if (flags & TR_SAMPLE_SIZE) {
3299     GST_LOG_OBJECT (qtdemux, "entry size present");
3300     size_offset = entry_size;
3301     entry_size += 4;
3302   }
3303   if (flags & TR_SAMPLE_FLAGS) {
3304     GST_LOG_OBJECT (qtdemux, "entry flags present");
3305     flags_offset = entry_size;
3306     entry_size += 4;
3307   }
3308   if (flags & TR_COMPOSITION_TIME_OFFSETS) {
3309     GST_LOG_OBJECT (qtdemux, "entry ct offset present");
3310     ct_offset = entry_size;
3311     entry_size += 4;
3312   }
3313
3314   if (!qt_atom_parser_has_chunks (trun, samples_count, entry_size))
3315     goto fail;
3316   data = (guint8 *) gst_byte_reader_peek_data_unchecked (trun);
3317
3318   if (stream->n_samples + samples_count >=
3319       QTDEMUX_MAX_SAMPLE_INDEX_SIZE / sizeof (QtDemuxSample))
3320     goto index_too_big;
3321
3322   GST_DEBUG_OBJECT (qtdemux, "allocating n_samples %u * %u (%.2f MB)",
3323       stream->n_samples + samples_count, (guint) sizeof (QtDemuxSample),
3324       (stream->n_samples + samples_count) *
3325       sizeof (QtDemuxSample) / (1024.0 * 1024.0));
3326
3327   /* create a new array of samples if it's the first sample parsed */
3328   if (stream->n_samples == 0) {
3329     g_assert (stream->samples == NULL);
3330     stream->samples = g_try_new0 (QtDemuxSample, samples_count);
3331     /* or try to reallocate it with space enough to insert the new samples */
3332   } else
3333     stream->samples = g_try_renew (QtDemuxSample, stream->samples,
3334         stream->n_samples + samples_count);
3335   if (stream->samples == NULL)
3336     goto out_of_memory;
3337
3338   if (qtdemux->fragment_start != -1) {
3339     timestamp = GSTTIME_TO_QTSTREAMTIME (stream, qtdemux->fragment_start);
3340     qtdemux->fragment_start = -1;
3341   } else {
3342     if (stream->n_samples == 0) {
3343       if (decode_ts > 0) {
3344         timestamp = decode_ts;
3345       } else if (stream->pending_seek != NULL) {
3346         /* if we don't have a timestamp from a tfdt box, we'll use the one
3347          * from the mfra seek table */
3348         GST_INFO_OBJECT (stream->pad, "pending seek ts = %" GST_TIME_FORMAT,
3349             GST_TIME_ARGS (stream->pending_seek->ts));
3350
3351         /* FIXME: this is not fully correct, the timestamp refers to the random
3352          * access sample refered to in the tfra entry, which may not necessarily
3353          * be the first sample in the tfrag/trun (but hopefully/usually is) */
3354         timestamp = GSTTIME_TO_QTSTREAMTIME (stream, stream->pending_seek->ts);
3355       } else {
3356         timestamp = 0;
3357       }
3358
3359       gst_ts = QTSTREAMTIME_TO_GSTTIME (stream, timestamp);
3360       GST_INFO_OBJECT (stream->pad, "first sample ts %" GST_TIME_FORMAT,
3361           GST_TIME_ARGS (gst_ts));
3362     } else {
3363       /* subsequent fragments extend stream */
3364       timestamp =
3365           stream->samples[stream->n_samples - 1].timestamp +
3366           stream->samples[stream->n_samples - 1].duration;
3367
3368       /* If this is a GST_FORMAT_BYTES stream and there's a significant
3369        * difference (1 sec.) between decode_ts and timestamp, prefer the
3370        * former */
3371       if (has_tfdt && !qtdemux->upstream_format_is_time
3372           && ABSDIFF (decode_ts, timestamp) >
3373           MAX (stream->duration_last_moof / 2,
3374               GSTTIME_TO_QTSTREAMTIME (stream, GST_SECOND))) {
3375         GST_INFO_OBJECT (qtdemux,
3376             "decode_ts (%" GST_TIME_FORMAT ") and timestamp (%" GST_TIME_FORMAT
3377             ") are significantly different (more than %" GST_TIME_FORMAT
3378             "), using decode_ts",
3379             GST_TIME_ARGS (QTSTREAMTIME_TO_GSTTIME (stream, decode_ts)),
3380             GST_TIME_ARGS (QTSTREAMTIME_TO_GSTTIME (stream, timestamp)),
3381             GST_TIME_ARGS (QTSTREAMTIME_TO_GSTTIME (stream,
3382                     MAX (stream->duration_last_moof / 2,
3383                         GSTTIME_TO_QTSTREAMTIME (stream, GST_SECOND)))));
3384         timestamp = decode_ts;
3385       }
3386
3387       gst_ts = QTSTREAMTIME_TO_GSTTIME (stream, timestamp);
3388       GST_INFO_OBJECT (qtdemux, "first sample ts %" GST_TIME_FORMAT
3389           " (extends previous samples)", GST_TIME_ARGS (gst_ts));
3390     }
3391   }
3392
3393   initial_offset = *running_offset;
3394
3395   sample = stream->samples + stream->n_samples;
3396   for (i = 0; i < samples_count; i++) {
3397     guint32 dur, size, sflags;
3398     gint32 ct;
3399
3400     /* first read sample data */
3401     if (flags & TR_SAMPLE_DURATION) {
3402       dur = QT_UINT32 (data + dur_offset);
3403     } else {
3404       dur = d_sample_duration;
3405     }
3406     if (flags & TR_SAMPLE_SIZE) {
3407       size = QT_UINT32 (data + size_offset);
3408     } else {
3409       size = d_sample_size;
3410     }
3411     if (flags & TR_FIRST_SAMPLE_FLAGS) {
3412       if (i == 0) {
3413         sflags = first_flags;
3414       } else {
3415         sflags = d_sample_flags;
3416       }
3417     } else if (flags & TR_SAMPLE_FLAGS) {
3418       sflags = QT_UINT32 (data + flags_offset);
3419     } else {
3420       sflags = d_sample_flags;
3421     }
3422
3423     if (flags & TR_COMPOSITION_TIME_OFFSETS) {
3424       /* Read offsets as signed numbers regardless of trun version as very
3425        * high offsets are unlikely and there are files out there that use
3426        * version=0 truns with negative offsets */
3427       ct = QT_UINT32 (data + ct_offset);
3428
3429       /* FIXME: Set offset to 0 for "no decode samples". This needs
3430        * to be handled in a codec specific manner ideally. */
3431       if (ct == G_MININT32)
3432         ct = 0;
3433     } else {
3434       ct = 0;
3435     }
3436     data += entry_size;
3437
3438     /* fill the sample information */
3439     sample->offset = *running_offset;
3440     sample->pts_offset = ct;
3441     sample->size = size;
3442     sample->timestamp = timestamp;
3443     sample->duration = dur;
3444     /* sample-is-difference-sample */
3445     /* ismv seems to use 0x40 for keyframe, 0xc0 for non-keyframe,
3446      * now idea how it relates to bitfield other than massive LE/BE confusion */
3447     sample->keyframe = ismv ? ((sflags & 0xff) == 0x40) : !(sflags & 0x10000);
3448     *running_offset += size;
3449     timestamp += dur;
3450     stream->duration_moof += dur;
3451     sample++;
3452
3453     if (ct < min_ct)
3454       min_ct = ct;
3455   }
3456
3457   /* Shift PTS/DTS to allow for negative composition offsets while keeping
3458    * A/V sync in place. This is similar to the code handling ctts/cslg in the
3459    * non-fragmented case.
3460    */
3461   if (min_ct < 0)
3462     stream->cslg_shift = -min_ct;
3463   else
3464     stream->cslg_shift = 0;
3465
3466   GST_DEBUG_OBJECT (qtdemux, "Using clsg_shift %" G_GUINT64_FORMAT,
3467       stream->cslg_shift);
3468
3469   /* Update total duration if needed */
3470   check_update_duration (qtdemux, QTSTREAMTIME_TO_GSTTIME (stream, timestamp));
3471
3472   /* Pre-emptively figure out size of mdat based on trun information.
3473    * If the [mdat] atom is effectivelly read, it will be replaced by the actual
3474    * size, else we will still be able to use this when dealing with gap'ed
3475    * input */
3476   qtdemux->mdatleft = *running_offset - initial_offset;
3477   qtdemux->mdatoffset = initial_offset;
3478   qtdemux->mdatsize = qtdemux->mdatleft;
3479
3480   stream->n_samples += samples_count;
3481   stream->n_samples_moof += samples_count;
3482
3483   if (stream->pending_seek != NULL)
3484     stream->pending_seek = NULL;
3485
3486   return TRUE;
3487
3488 fail:
3489   {
3490     GST_WARNING_OBJECT (qtdemux, "failed to parse trun");
3491     return FALSE;
3492   }
3493 out_of_memory:
3494   {
3495     GST_WARNING_OBJECT (qtdemux, "failed to allocate %d samples",
3496         stream->n_samples);
3497     return FALSE;
3498   }
3499 index_too_big:
3500   {
3501     GST_WARNING_OBJECT (qtdemux, "not allocating index of %d samples, would "
3502         "be larger than %uMB (broken file?)", stream->n_samples,
3503         QTDEMUX_MAX_SAMPLE_INDEX_SIZE >> 20);
3504     return FALSE;
3505   }
3506 }
3507
3508 /* find stream with @id */
3509 static inline QtDemuxStream *
3510 qtdemux_find_stream (GstQTDemux * qtdemux, guint32 id)
3511 {
3512   QtDemuxStream *stream;
3513   gint i;
3514
3515   /* check */
3516   if (G_UNLIKELY (!id)) {
3517     GST_DEBUG_OBJECT (qtdemux, "invalid track id 0");
3518     return NULL;
3519   }
3520
3521   for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
3522     stream = QTDEMUX_NTH_STREAM (qtdemux, i);
3523     if (stream->track_id == id)
3524       return stream;
3525   }
3526   if (qtdemux->mss_mode) {
3527     /* mss should have only 1 stream anyway */
3528     return QTDEMUX_NTH_STREAM (qtdemux, 0);
3529   }
3530
3531   return NULL;
3532 }
3533
3534 static gboolean
3535 qtdemux_parse_mfhd (GstQTDemux * qtdemux, GstByteReader * mfhd,
3536     guint32 * fragment_number)
3537 {
3538   if (!gst_byte_reader_skip (mfhd, 4))
3539     goto fail;
3540   if (!gst_byte_reader_get_uint32_be (mfhd, fragment_number))
3541     goto fail;
3542   return TRUE;
3543 fail:
3544   {
3545     GST_WARNING_OBJECT (qtdemux, "Failed to parse mfhd atom");
3546     return FALSE;
3547   }
3548 }
3549
3550 static gboolean
3551 qtdemux_parse_tfhd (GstQTDemux * qtdemux, GstByteReader * tfhd,
3552     QtDemuxStream ** stream, guint32 * default_sample_duration,
3553     guint32 * default_sample_size, guint32 * default_sample_flags,
3554     gint64 * base_offset)
3555 {
3556   guint32 flags = 0;
3557   guint32 track_id = 0;
3558
3559   if (!gst_byte_reader_skip (tfhd, 1) ||
3560       !gst_byte_reader_get_uint24_be (tfhd, &flags))
3561     goto invalid_track;
3562
3563   if (!gst_byte_reader_get_uint32_be (tfhd, &track_id))
3564     goto invalid_track;
3565
3566   *stream = qtdemux_find_stream (qtdemux, track_id);
3567   if (G_UNLIKELY (!*stream))
3568     goto unknown_stream;
3569
3570   if (flags & TF_DEFAULT_BASE_IS_MOOF)
3571     *base_offset = qtdemux->moof_offset;
3572
3573   if (flags & TF_BASE_DATA_OFFSET)
3574     if (!gst_byte_reader_get_uint64_be (tfhd, (guint64 *) base_offset))
3575       goto invalid_track;
3576
3577   /* obtain stream defaults */
3578   qtdemux_parse_trex (qtdemux, *stream,
3579       default_sample_duration, default_sample_size, default_sample_flags);
3580
3581   (*stream)->stsd_sample_description_id =
3582       (*stream)->def_sample_description_index - 1;
3583
3584   if (flags & TF_SAMPLE_DESCRIPTION_INDEX) {
3585     guint32 sample_description_index;
3586     if (!gst_byte_reader_get_uint32_be (tfhd, &sample_description_index))
3587       goto invalid_track;
3588     (*stream)->stsd_sample_description_id = sample_description_index - 1;
3589   }
3590
3591   if (qtdemux->mss_mode) {
3592     /* mss has no stsd entry */
3593     (*stream)->stsd_sample_description_id = 0;
3594   }
3595
3596   if (flags & TF_DEFAULT_SAMPLE_DURATION)
3597     if (!gst_byte_reader_get_uint32_be (tfhd, default_sample_duration))
3598       goto invalid_track;
3599
3600   if (flags & TF_DEFAULT_SAMPLE_SIZE)
3601     if (!gst_byte_reader_get_uint32_be (tfhd, default_sample_size))
3602       goto invalid_track;
3603
3604   if (flags & TF_DEFAULT_SAMPLE_FLAGS)
3605     if (!gst_byte_reader_get_uint32_be (tfhd, default_sample_flags))
3606       goto invalid_track;
3607
3608   return TRUE;
3609
3610 invalid_track:
3611   {
3612     GST_WARNING_OBJECT (qtdemux, "invalid track fragment header");
3613     return FALSE;
3614   }
3615 unknown_stream:
3616   {
3617     GST_DEBUG_OBJECT (qtdemux, "unknown stream (%u) in tfhd", track_id);
3618     return TRUE;
3619   }
3620 }
3621
3622 static gboolean
3623 qtdemux_parse_tfdt (GstQTDemux * qtdemux, GstByteReader * br,
3624     guint64 * decode_time)
3625 {
3626   guint32 version = 0;
3627
3628   if (!gst_byte_reader_get_uint32_be (br, &version))
3629     return FALSE;
3630
3631   version >>= 24;
3632   if (version == 1) {
3633     if (!gst_byte_reader_get_uint64_be (br, decode_time))
3634       goto failed;
3635   } else {
3636     guint32 dec_time = 0;
3637     if (!gst_byte_reader_get_uint32_be (br, &dec_time))
3638       goto failed;
3639     *decode_time = dec_time;
3640   }
3641
3642   GST_INFO_OBJECT (qtdemux, "Track fragment decode time: %" G_GUINT64_FORMAT,
3643       *decode_time);
3644
3645   return TRUE;
3646
3647 failed:
3648   {
3649     GST_DEBUG_OBJECT (qtdemux, "parsing tfdt failed");
3650     return FALSE;
3651   }
3652 }
3653
3654 /* Returns a pointer to a GstStructure containing the properties of
3655  * the stream sample identified by @sample_index. The caller must unref
3656  * the returned object after use. Returns NULL if unsuccessful. */
3657 static GstStructure *
3658 qtdemux_get_cenc_sample_properties (GstQTDemux * qtdemux,
3659     QtDemuxStream * stream, guint sample_index)
3660 {
3661   QtDemuxCencSampleSetInfo *info = NULL;
3662
3663   g_return_val_if_fail (stream != NULL, NULL);
3664   g_return_val_if_fail (stream->protected, NULL);
3665   g_return_val_if_fail (stream->protection_scheme_info != NULL, NULL);
3666
3667   info = (QtDemuxCencSampleSetInfo *) stream->protection_scheme_info;
3668
3669   /* Currently, cenc properties for groups of samples are not supported, so
3670    * simply return a copy of the default sample properties */
3671   return gst_structure_copy (info->default_properties);
3672 }
3673
3674 /* Parses the sizes of sample auxiliary information contained within a stream,
3675  * as given in a saiz box. Returns array of sample_count guint8 size values,
3676  * or NULL on failure */
3677 static guint8 *
3678 qtdemux_parse_saiz (GstQTDemux * qtdemux, QtDemuxStream * stream,
3679     GstByteReader * br, guint32 * sample_count)
3680 {
3681   guint32 flags = 0;
3682   guint8 *info_sizes;
3683   guint8 default_info_size;
3684
3685   g_return_val_if_fail (qtdemux != NULL, NULL);
3686   g_return_val_if_fail (stream != NULL, NULL);
3687   g_return_val_if_fail (br != NULL, NULL);
3688   g_return_val_if_fail (sample_count != NULL, NULL);
3689
3690   if (!gst_byte_reader_get_uint32_be (br, &flags))
3691     return NULL;
3692
3693   if (flags & 0x1) {
3694     /* aux_info_type and aux_info_type_parameter are ignored */
3695     if (!gst_byte_reader_skip (br, 8))
3696       return NULL;
3697   }
3698
3699   if (!gst_byte_reader_get_uint8 (br, &default_info_size))
3700     return NULL;
3701   GST_DEBUG_OBJECT (qtdemux, "default_info_size: %u", default_info_size);
3702
3703   if (!gst_byte_reader_get_uint32_be (br, sample_count))
3704     return NULL;
3705   GST_DEBUG_OBJECT (qtdemux, "sample_count: %u", *sample_count);
3706
3707
3708   if (default_info_size == 0) {
3709     if (!gst_byte_reader_dup_data (br, *sample_count, &info_sizes)) {
3710       return NULL;
3711     }
3712   } else {
3713     info_sizes = g_new (guint8, *sample_count);
3714     memset (info_sizes, default_info_size, *sample_count);
3715   }
3716
3717   return info_sizes;
3718 }
3719
3720 /* Parses the offset of sample auxiliary information contained within a stream,
3721  * as given in a saio box. Returns TRUE if successful; FALSE otherwise. */
3722 static gboolean
3723 qtdemux_parse_saio (GstQTDemux * qtdemux, QtDemuxStream * stream,
3724     GstByteReader * br, guint32 * info_type, guint32 * info_type_parameter,
3725     guint64 * offset)
3726 {
3727   guint8 version = 0;
3728   guint32 flags = 0;
3729   guint32 aux_info_type = 0;
3730   guint32 aux_info_type_parameter = 0;
3731   guint32 entry_count;
3732   guint32 off_32;
3733   guint64 off_64;
3734   const guint8 *aux_info_type_data = NULL;
3735
3736   g_return_val_if_fail (qtdemux != NULL, FALSE);
3737   g_return_val_if_fail (stream != NULL, FALSE);
3738   g_return_val_if_fail (br != NULL, FALSE);
3739   g_return_val_if_fail (offset != NULL, FALSE);
3740
3741   if (!gst_byte_reader_get_uint8 (br, &version))
3742     return FALSE;
3743
3744   if (!gst_byte_reader_get_uint24_be (br, &flags))
3745     return FALSE;
3746
3747   if (flags & 0x1) {
3748
3749     if (!gst_byte_reader_get_data (br, 4, &aux_info_type_data))
3750       return FALSE;
3751     aux_info_type = QT_FOURCC (aux_info_type_data);
3752
3753     if (!gst_byte_reader_get_uint32_be (br, &aux_info_type_parameter))
3754       return FALSE;
3755   } else if (stream->protected) {
3756     aux_info_type = stream->protection_scheme_type;
3757   } else {
3758     aux_info_type = CUR_STREAM (stream)->fourcc;
3759   }
3760
3761   if (info_type)
3762     *info_type = aux_info_type;
3763   if (info_type_parameter)
3764     *info_type_parameter = aux_info_type_parameter;
3765
3766   GST_DEBUG_OBJECT (qtdemux, "aux_info_type: '%" GST_FOURCC_FORMAT "', "
3767       "aux_info_type_parameter:  %#06x",
3768       GST_FOURCC_ARGS (aux_info_type), aux_info_type_parameter);
3769
3770   if (!gst_byte_reader_get_uint32_be (br, &entry_count))
3771     return FALSE;
3772
3773   if (entry_count != 1) {
3774     GST_ERROR_OBJECT (qtdemux, "multiple offsets are not supported");
3775     return FALSE;
3776   }
3777
3778   if (version == 0) {
3779     if (!gst_byte_reader_get_uint32_be (br, &off_32))
3780       return FALSE;
3781     *offset = (guint64) off_32;
3782   } else {
3783     if (!gst_byte_reader_get_uint64_be (br, &off_64))
3784       return FALSE;
3785     *offset = off_64;
3786   }
3787
3788   GST_DEBUG_OBJECT (qtdemux, "offset: %" G_GUINT64_FORMAT, *offset);
3789   return TRUE;
3790 }
3791
3792 static void
3793 qtdemux_gst_structure_free (GstStructure * gststructure)
3794 {
3795   if (gststructure) {
3796     gst_structure_free (gststructure);
3797   }
3798 }
3799
3800 /* Parses auxiliary information relating to samples protected using
3801  * Common Encryption (cenc); the format of this information
3802  * is defined in ISO/IEC 23001-7. Returns TRUE if successful; FALSE
3803  * otherwise. */
3804 static gboolean
3805 qtdemux_parse_cenc_aux_info (GstQTDemux * qtdemux, QtDemuxStream * stream,
3806     GstByteReader * br, guint8 * info_sizes, guint32 sample_count)
3807 {
3808   QtDemuxCencSampleSetInfo *ss_info = NULL;
3809   guint8 size;
3810   gint i;
3811   GPtrArray *old_crypto_info = NULL;
3812   guint old_entries = 0;
3813
3814   g_return_val_if_fail (qtdemux != NULL, FALSE);
3815   g_return_val_if_fail (stream != NULL, FALSE);
3816   g_return_val_if_fail (br != NULL, FALSE);
3817   g_return_val_if_fail (stream->protected, FALSE);
3818   g_return_val_if_fail (stream->protection_scheme_info != NULL, FALSE);
3819
3820   ss_info = (QtDemuxCencSampleSetInfo *) stream->protection_scheme_info;
3821
3822   if (ss_info->crypto_info) {
3823     old_crypto_info = ss_info->crypto_info;
3824     /* Count number of non-null entries remaining at the tail end */
3825     for (i = old_crypto_info->len - 1; i >= 0; i--) {
3826       if (g_ptr_array_index (old_crypto_info, i) == NULL)
3827         break;
3828       old_entries++;
3829     }
3830   }
3831
3832   ss_info->crypto_info =
3833       g_ptr_array_new_full (sample_count + old_entries,
3834       (GDestroyNotify) qtdemux_gst_structure_free);
3835
3836   /* We preserve old entries because we parse the next moof in advance
3837    * of consuming all samples from the previous moof, and otherwise
3838    * we'd discard the corresponding crypto info for the samples
3839    * from the previous fragment. */
3840   if (old_entries) {
3841     GST_DEBUG_OBJECT (qtdemux, "Preserving %d old crypto info entries",
3842         old_entries);
3843     for (i = old_crypto_info->len - old_entries; i < old_crypto_info->len; i++) {
3844       g_ptr_array_add (ss_info->crypto_info, g_ptr_array_index (old_crypto_info,
3845               i));
3846       g_ptr_array_index (old_crypto_info, i) = NULL;
3847     }
3848   }
3849
3850   if (old_crypto_info) {
3851     /* Everything now belongs to the new array */
3852     g_ptr_array_free (old_crypto_info, TRUE);
3853   }
3854
3855   for (i = 0; i < sample_count; ++i) {
3856     GstStructure *properties;
3857     guint16 n_subsamples = 0;
3858     guint8 *data;
3859     guint iv_size;
3860     GstBuffer *buf;
3861     gboolean could_read_iv;
3862
3863     properties = qtdemux_get_cenc_sample_properties (qtdemux, stream, i);
3864     if (properties == NULL) {
3865       GST_ERROR_OBJECT (qtdemux, "failed to get properties for sample %u", i);
3866       return FALSE;
3867     }
3868     if (!gst_structure_get_uint (properties, "iv_size", &iv_size)) {
3869       GST_ERROR_OBJECT (qtdemux, "failed to get iv_size for sample %u", i);
3870       gst_structure_free (properties);
3871       return FALSE;
3872     }
3873     could_read_iv =
3874         iv_size > 0 ? gst_byte_reader_dup_data (br, iv_size, &data) : FALSE;
3875     if (could_read_iv) {
3876       buf = gst_buffer_new_wrapped (data, iv_size);
3877       gst_structure_set (properties, "iv", GST_TYPE_BUFFER, buf, NULL);
3878       gst_buffer_unref (buf);
3879     } else if (stream->protection_scheme_type == FOURCC_cbcs) {
3880       const GValue *constant_iv_size_value =
3881           gst_structure_get_value (properties, "constant_iv_size");
3882       const GValue *constant_iv_value =
3883           gst_structure_get_value (properties, "iv");
3884       if (constant_iv_size_value == NULL || constant_iv_value == NULL) {
3885         GST_ERROR_OBJECT (qtdemux, "failed to get constant_iv");
3886         gst_structure_free (properties);
3887         return FALSE;
3888       }
3889       gst_structure_set_value (properties, "iv_size", constant_iv_size_value);
3890       gst_structure_remove_field (properties, "constant_iv_size");
3891     } else if (stream->protection_scheme_type == FOURCC_cenc) {
3892       GST_ERROR_OBJECT (qtdemux, "failed to get IV for sample %u", i);
3893       gst_structure_free (properties);
3894       return FALSE;
3895     }
3896     size = info_sizes[i];
3897     if (size > iv_size) {
3898       if (!gst_byte_reader_get_uint16_be (br, &n_subsamples)
3899           || !(n_subsamples > 0)) {
3900         gst_structure_free (properties);
3901         GST_ERROR_OBJECT (qtdemux,
3902             "failed to get subsample count for sample %u", i);
3903         return FALSE;
3904       }
3905       GST_LOG_OBJECT (qtdemux, "subsample count: %u", n_subsamples);
3906       if (!gst_byte_reader_dup_data (br, n_subsamples * 6, &data)) {
3907         GST_ERROR_OBJECT (qtdemux, "failed to get subsample data for sample %u",
3908             i);
3909         gst_structure_free (properties);
3910         return FALSE;
3911       }
3912       buf = gst_buffer_new_wrapped (data, n_subsamples * 6);
3913       if (!buf) {
3914         gst_structure_free (properties);
3915         return FALSE;
3916       }
3917       gst_structure_set (properties,
3918           "subsample_count", G_TYPE_UINT, n_subsamples,
3919           "subsamples", GST_TYPE_BUFFER, buf, NULL);
3920       gst_buffer_unref (buf);
3921     } else {
3922       gst_structure_set (properties, "subsample_count", G_TYPE_UINT, 0, NULL);
3923     }
3924     g_ptr_array_add (ss_info->crypto_info, properties);
3925   }
3926   return TRUE;
3927 }
3928
3929 /* Converts a UUID in raw byte form to a string representation, as defined in
3930  * RFC 4122. The caller takes ownership of the returned string and is
3931  * responsible for freeing it after use. */
3932 static gchar *
3933 qtdemux_uuid_bytes_to_string (gconstpointer uuid_bytes)
3934 {
3935   const guint8 *uuid = (const guint8 *) uuid_bytes;
3936
3937   return g_strdup_printf ("%02x%02x%02x%02x-%02x%02x-%02x%02x-"
3938       "%02x%02x-%02x%02x%02x%02x%02x%02x",
3939       uuid[0], uuid[1], uuid[2], uuid[3],
3940       uuid[4], uuid[5], uuid[6], uuid[7],
3941       uuid[8], uuid[9], uuid[10], uuid[11],
3942       uuid[12], uuid[13], uuid[14], uuid[15]);
3943 }
3944
3945 /* Parses a Protection System Specific Header box (pssh), as defined in the
3946  * Common Encryption (cenc) standard (ISO/IEC 23001-7), which contains
3947  * information needed by a specific content protection system in order to
3948  * decrypt cenc-protected tracks. Returns TRUE if successful; FALSE
3949  * otherwise. */
3950 static gboolean
3951 qtdemux_parse_pssh (GstQTDemux * qtdemux, GNode * node)
3952 {
3953   gchar *sysid_string;
3954   guint32 pssh_size = QT_UINT32 (node->data);
3955   GstBuffer *pssh = NULL;
3956   GstEvent *event = NULL;
3957   guint32 parent_box_type;
3958   gint i;
3959
3960   if (G_UNLIKELY (pssh_size < 32U)) {
3961     GST_ERROR_OBJECT (qtdemux, "invalid box size");
3962     return FALSE;
3963   }
3964
3965   sysid_string =
3966       qtdemux_uuid_bytes_to_string ((const guint8 *) node->data + 12);
3967
3968   gst_qtdemux_append_protection_system_id (qtdemux, sysid_string);
3969
3970   pssh = gst_buffer_new_memdup (node->data, pssh_size);
3971   GST_LOG_OBJECT (qtdemux, "cenc pssh size: %" G_GSIZE_FORMAT,
3972       gst_buffer_get_size (pssh));
3973
3974   parent_box_type = QT_FOURCC ((const guint8 *) node->parent->data + 4);
3975
3976   /* Push an event containing the pssh box onto the queues of all streams. */
3977   event = gst_event_new_protection (sysid_string, pssh,
3978       (parent_box_type == FOURCC_moov) ? "isobmff/moov" : "isobmff/moof");
3979   for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
3980     QtDemuxStream *stream = QTDEMUX_NTH_STREAM (qtdemux, i);
3981     GST_TRACE_OBJECT (qtdemux,
3982         "adding protection event for stream %s and system %s",
3983         stream->stream_id, sysid_string);
3984     g_queue_push_tail (&stream->protection_scheme_event_queue,
3985         gst_event_ref (event));
3986   }
3987   g_free (sysid_string);
3988   gst_event_unref (event);
3989   gst_buffer_unref (pssh);
3990   return TRUE;
3991 }
3992
3993 static gboolean
3994 qtdemux_parse_moof (GstQTDemux * qtdemux, const guint8 * buffer, guint length,
3995     guint64 moof_offset, QtDemuxStream * stream)
3996 {
3997   GNode *moof_node, *traf_node, *tfhd_node, *trun_node, *tfdt_node, *mfhd_node;
3998   GNode *uuid_node;
3999   GstByteReader mfhd_data, trun_data, tfhd_data, tfdt_data;
4000   GNode *saiz_node, *saio_node, *pssh_node;
4001   GstByteReader saiz_data, saio_data;
4002   guint32 ds_size = 0, ds_duration = 0, ds_flags = 0;
4003   gint64 base_offset, running_offset;
4004   guint32 frag_num;
4005   GstClockTime min_dts = GST_CLOCK_TIME_NONE;
4006
4007   /* NOTE @stream ignored */
4008
4009   moof_node = g_node_new ((guint8 *) buffer);
4010   qtdemux_parse_node (qtdemux, moof_node, buffer, length);
4011   qtdemux_node_dump (qtdemux, moof_node);
4012
4013   /* Get fragment number from mfhd and check it's valid */
4014   mfhd_node =
4015       qtdemux_tree_get_child_by_type_full (moof_node, FOURCC_mfhd, &mfhd_data);
4016   if (mfhd_node == NULL)
4017     goto missing_mfhd;
4018   if (!qtdemux_parse_mfhd (qtdemux, &mfhd_data, &frag_num))
4019     goto fail;
4020   GST_DEBUG_OBJECT (qtdemux, "Fragment #%d", frag_num);
4021
4022   /* unknown base_offset to start with */
4023   base_offset = running_offset = -1;
4024   traf_node = qtdemux_tree_get_child_by_type (moof_node, FOURCC_traf);
4025   while (traf_node) {
4026     guint64 decode_time = 0;
4027
4028     /* Fragment Header node */
4029     tfhd_node =
4030         qtdemux_tree_get_child_by_type_full (traf_node, FOURCC_tfhd,
4031         &tfhd_data);
4032     if (!tfhd_node)
4033       goto missing_tfhd;
4034     if (!qtdemux_parse_tfhd (qtdemux, &tfhd_data, &stream, &ds_duration,
4035             &ds_size, &ds_flags, &base_offset))
4036       goto missing_tfhd;
4037
4038     /* The following code assumes at most a single set of sample auxiliary
4039      * data in the fragment (consisting of a saiz box and a corresponding saio
4040      * box); in theory, however, there could be multiple sets of sample
4041      * auxiliary data in a fragment. */
4042     saiz_node =
4043         qtdemux_tree_get_child_by_type_full (traf_node, FOURCC_saiz,
4044         &saiz_data);
4045     if (saiz_node) {
4046       guint32 info_type = 0;
4047       guint64 offset = 0;
4048       guint32 info_type_parameter = 0;
4049
4050       g_free (qtdemux->cenc_aux_info_sizes);
4051
4052       qtdemux->cenc_aux_info_sizes =
4053           qtdemux_parse_saiz (qtdemux, stream, &saiz_data,
4054           &qtdemux->cenc_aux_sample_count);
4055       if (qtdemux->cenc_aux_info_sizes == NULL) {
4056         GST_ERROR_OBJECT (qtdemux, "failed to parse saiz box");
4057         goto fail;
4058       }
4059       saio_node =
4060           qtdemux_tree_get_child_by_type_full (traf_node, FOURCC_saio,
4061           &saio_data);
4062       if (!saio_node) {
4063         GST_ERROR_OBJECT (qtdemux, "saiz box without a corresponding saio box");
4064         g_free (qtdemux->cenc_aux_info_sizes);
4065         qtdemux->cenc_aux_info_sizes = NULL;
4066         goto fail;
4067       }
4068
4069       if (G_UNLIKELY (!qtdemux_parse_saio (qtdemux, stream, &saio_data,
4070                   &info_type, &info_type_parameter, &offset))) {
4071         GST_ERROR_OBJECT (qtdemux, "failed to parse saio box");
4072         g_free (qtdemux->cenc_aux_info_sizes);
4073         qtdemux->cenc_aux_info_sizes = NULL;
4074         goto fail;
4075       }
4076       if (base_offset > -1 && base_offset > qtdemux->moof_offset)
4077         offset += (guint64) (base_offset - qtdemux->moof_offset);
4078       if ((info_type == FOURCC_cenc || info_type == FOURCC_cbcs)
4079           && info_type_parameter == 0U) {
4080         GstByteReader br;
4081         if (offset > length) {
4082           GST_DEBUG_OBJECT (qtdemux, "cenc auxiliary info stored out of moof");
4083           qtdemux->cenc_aux_info_offset = offset;
4084         } else {
4085           gst_byte_reader_init (&br, buffer + offset, length - offset);
4086           if (!qtdemux_parse_cenc_aux_info (qtdemux, stream, &br,
4087                   qtdemux->cenc_aux_info_sizes,
4088                   qtdemux->cenc_aux_sample_count)) {
4089             GST_ERROR_OBJECT (qtdemux, "failed to parse cenc auxiliary info");
4090             g_free (qtdemux->cenc_aux_info_sizes);
4091             qtdemux->cenc_aux_info_sizes = NULL;
4092             goto fail;
4093           }
4094         }
4095       }
4096     }
4097
4098     tfdt_node =
4099         qtdemux_tree_get_child_by_type_full (traf_node, FOURCC_tfdt,
4100         &tfdt_data);
4101     if (tfdt_node) {
4102       /* We'll use decode_time to interpolate timestamps
4103        * in case the input timestamps are missing */
4104       qtdemux_parse_tfdt (qtdemux, &tfdt_data, &decode_time);
4105
4106       GST_DEBUG_OBJECT (qtdemux, "decode time %" G_GINT64_FORMAT
4107           " (%" GST_TIME_FORMAT ")", decode_time,
4108           GST_TIME_ARGS (stream ? QTSTREAMTIME_TO_GSTTIME (stream,
4109                   decode_time) : GST_CLOCK_TIME_NONE));
4110
4111       /* Discard the fragment buffer timestamp info to avoid using it.
4112        * Rely on tfdt instead as it is more accurate than the timestamp
4113        * that is fetched from a manifest/playlist and is usually
4114        * less accurate. */
4115       qtdemux->fragment_start = -1;
4116     }
4117
4118     if (G_UNLIKELY (!stream)) {
4119       /* we lost track of offset, we'll need to regain it,
4120        * but can delay complaining until later or avoid doing so altogether */
4121       base_offset = -2;
4122       goto next;
4123     }
4124     if (G_UNLIKELY (base_offset < -1))
4125       goto lost_offset;
4126
4127     min_dts = MIN (min_dts, QTSTREAMTIME_TO_GSTTIME (stream, decode_time));
4128
4129     if (!qtdemux->pullbased) {
4130       /* Sample tables can grow enough to be problematic if the system memory
4131        * is very low (e.g. embedded devices) and the videos very long
4132        * (~8 MiB/hour for 25-30 fps video + typical AAC audio frames).
4133        * Fortunately, we can easily discard them for each new fragment when
4134        * we know qtdemux will not receive seeks outside of the current fragment.
4135        * adaptivedemux honors this assumption.
4136        * This optimization is also useful for applications that use qtdemux as
4137        * a push-based simple demuxer, like Media Source Extensions. */
4138       gst_qtdemux_stream_flush_samples_data (stream);
4139     }
4140
4141     /* initialise moof sample data */
4142     stream->n_samples_moof = 0;
4143     stream->duration_last_moof = stream->duration_moof;
4144     stream->duration_moof = 0;
4145
4146     /* Track Run node */
4147     trun_node =
4148         qtdemux_tree_get_child_by_type_full (traf_node, FOURCC_trun,
4149         &trun_data);
4150     while (trun_node) {
4151       qtdemux_parse_trun (qtdemux, &trun_data, stream,
4152           ds_duration, ds_size, ds_flags, moof_offset, length, &base_offset,
4153           &running_offset, decode_time, (tfdt_node != NULL));
4154       /* iterate all siblings */
4155       trun_node = qtdemux_tree_get_sibling_by_type_full (trun_node, FOURCC_trun,
4156           &trun_data);
4157     }
4158
4159     uuid_node = qtdemux_tree_get_child_by_type (traf_node, FOURCC_uuid);
4160     if (uuid_node) {
4161       guint8 *uuid_buffer = (guint8 *) uuid_node->data;
4162       guint32 box_length = QT_UINT32 (uuid_buffer);
4163
4164       qtdemux_parse_uuid (qtdemux, uuid_buffer, box_length);
4165     }
4166
4167     /* if no new base_offset provided for next traf,
4168      * base is end of current traf */
4169     base_offset = running_offset;
4170     running_offset = -1;
4171
4172     if (stream->n_samples_moof && stream->duration_moof)
4173       stream->new_caps = TRUE;
4174
4175   next:
4176     /* iterate all siblings */
4177     traf_node = qtdemux_tree_get_sibling_by_type (traf_node, FOURCC_traf);
4178   }
4179
4180   /* parse any protection system info */
4181   pssh_node = qtdemux_tree_get_child_by_type (moof_node, FOURCC_pssh);
4182   while (pssh_node) {
4183     GST_LOG_OBJECT (qtdemux, "Parsing pssh box.");
4184     qtdemux_parse_pssh (qtdemux, pssh_node);
4185     pssh_node = qtdemux_tree_get_sibling_by_type (pssh_node, FOURCC_pssh);
4186   }
4187
4188   if (!qtdemux->upstream_format_is_time && !qtdemux->first_moof_already_parsed
4189       && !qtdemux->received_seek && GST_CLOCK_TIME_IS_VALID (min_dts)
4190       && min_dts != 0) {
4191     /* Unless the user has explicitly requested another seek, perform an
4192      * internal seek to the time specified in the tfdt.
4193      *
4194      * This way if the user opens a file where the first tfdt is 1 hour
4195      * into the presentation, they will not have to wait 1 hour for run
4196      * time to catch up and actual playback to start. */
4197     gint i;
4198
4199     GST_DEBUG_OBJECT (qtdemux, "First fragment has a non-zero tfdt, "
4200         "performing an internal seek to %" GST_TIME_FORMAT,
4201         GST_TIME_ARGS (min_dts));
4202
4203     qtdemux->segment.start = min_dts;
4204     qtdemux->segment.time = qtdemux->segment.position = min_dts;
4205
4206     for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
4207       QtDemuxStream *stream = QTDEMUX_NTH_STREAM (qtdemux, i);
4208       stream->time_position = min_dts;
4209     }
4210
4211     /* Before this code was run a segment was already sent when the moov was
4212      * parsed... which is OK -- some apps (mostly tests) expect a segment to
4213      * be emitted after a moov, and we can emit a second segment anyway for
4214      * special cases like this. */
4215     qtdemux->need_segment = TRUE;
4216   }
4217
4218   qtdemux->first_moof_already_parsed = TRUE;
4219
4220   g_node_destroy (moof_node);
4221   return TRUE;
4222
4223 missing_tfhd:
4224   {
4225     GST_DEBUG_OBJECT (qtdemux, "missing tfhd box");
4226     goto fail;
4227   }
4228 missing_mfhd:
4229   {
4230     GST_DEBUG_OBJECT (qtdemux, "Missing mfhd box");
4231     goto fail;
4232   }
4233 lost_offset:
4234   {
4235     GST_DEBUG_OBJECT (qtdemux, "lost offset");
4236     goto fail;
4237   }
4238 fail:
4239   {
4240     g_node_destroy (moof_node);
4241     GST_ELEMENT_ERROR (qtdemux, STREAM, DEMUX,
4242         (_("This file is corrupt and cannot be played.")), (NULL));
4243     return FALSE;
4244   }
4245 }
4246
4247 #if 0
4248 /* might be used if some day we actually use mfra & co
4249  * for random access to fragments,
4250  * but that will require quite some modifications and much less relying
4251  * on a sample array */
4252 #endif
4253
4254 static gboolean
4255 qtdemux_parse_tfra (GstQTDemux * qtdemux, GNode * tfra_node)
4256 {
4257   QtDemuxStream *stream;
4258   guint32 ver_flags, track_id, len, num_entries, i;
4259   guint value_size, traf_size, trun_size, sample_size;
4260   guint64 time = 0, moof_offset = 0;
4261 #if 0
4262   GstBuffer *buf = NULL;
4263   GstFlowReturn ret;
4264 #endif
4265   GstByteReader tfra;
4266
4267   gst_byte_reader_init (&tfra, tfra_node->data, QT_UINT32 (tfra_node->data));
4268
4269   if (!gst_byte_reader_skip (&tfra, 8))
4270     return FALSE;
4271
4272   if (!gst_byte_reader_get_uint32_be (&tfra, &ver_flags))
4273     return FALSE;
4274
4275   if (!gst_byte_reader_get_uint32_be (&tfra, &track_id)
4276       || !gst_byte_reader_get_uint32_be (&tfra, &len)
4277       || !gst_byte_reader_get_uint32_be (&tfra, &num_entries))
4278     return FALSE;
4279
4280   GST_DEBUG_OBJECT (qtdemux, "parsing tfra box for track id %u", track_id);
4281
4282   stream = qtdemux_find_stream (qtdemux, track_id);
4283   if (stream == NULL)
4284     goto unknown_trackid;
4285
4286   value_size = ((ver_flags >> 24) == 1) ? sizeof (guint64) : sizeof (guint32);
4287   sample_size = (len & 3) + 1;
4288   trun_size = ((len & 12) >> 2) + 1;
4289   traf_size = ((len & 48) >> 4) + 1;
4290
4291   GST_DEBUG_OBJECT (qtdemux, "%u entries, sizes: value %u, traf %u, trun %u, "
4292       "sample %u", num_entries, value_size, traf_size, trun_size, sample_size);
4293
4294   if (num_entries == 0)
4295     goto no_samples;
4296
4297   if (!qt_atom_parser_has_chunks (&tfra, num_entries,
4298           value_size + value_size + traf_size + trun_size + sample_size))
4299     goto corrupt_file;
4300
4301   g_free (stream->ra_entries);
4302   stream->ra_entries = g_new (QtDemuxRandomAccessEntry, num_entries);
4303   stream->n_ra_entries = num_entries;
4304
4305   for (i = 0; i < num_entries; i++) {
4306     qt_atom_parser_get_offset (&tfra, value_size, &time);
4307     qt_atom_parser_get_offset (&tfra, value_size, &moof_offset);
4308     qt_atom_parser_get_uint_with_size_unchecked (&tfra, traf_size);
4309     qt_atom_parser_get_uint_with_size_unchecked (&tfra, trun_size);
4310     qt_atom_parser_get_uint_with_size_unchecked (&tfra, sample_size);
4311
4312     time = QTSTREAMTIME_TO_GSTTIME (stream, time);
4313
4314     GST_LOG_OBJECT (qtdemux, "fragment time: %" GST_TIME_FORMAT ", "
4315         " moof_offset: %" G_GUINT64_FORMAT, GST_TIME_ARGS (time), moof_offset);
4316
4317     stream->ra_entries[i].ts = time;
4318     stream->ra_entries[i].moof_offset = moof_offset;
4319
4320     /* don't want to go through the entire file and read all moofs at startup */
4321 #if 0
4322     ret = gst_qtdemux_pull_atom (qtdemux, moof_offset, 0, &buf);
4323     if (ret != GST_FLOW_OK)
4324       goto corrupt_file;
4325     qtdemux_parse_moof (qtdemux, GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf),
4326         moof_offset, stream);
4327     gst_buffer_unref (buf);
4328 #endif
4329   }
4330
4331   check_update_duration (qtdemux, time);
4332
4333   return TRUE;
4334
4335 /* ERRORS */
4336 unknown_trackid:
4337   {
4338     GST_WARNING_OBJECT (qtdemux, "Couldn't find stream for track %u", track_id);
4339     return FALSE;
4340   }
4341 corrupt_file:
4342   {
4343     GST_WARNING_OBJECT (qtdemux, "broken traf box, ignoring");
4344     return FALSE;
4345   }
4346 no_samples:
4347   {
4348     GST_WARNING_OBJECT (qtdemux, "stream has no samples");
4349     return FALSE;
4350   }
4351 }
4352
4353 static gboolean
4354 qtdemux_pull_mfro_mfra (GstQTDemux * qtdemux)
4355 {
4356   GstMapInfo mfro_map = GST_MAP_INFO_INIT;
4357   GstMapInfo mfra_map = GST_MAP_INFO_INIT;
4358   GstBuffer *mfro = NULL, *mfra = NULL;
4359   GstFlowReturn flow;
4360   gboolean ret = FALSE;
4361   GNode *mfra_node, *tfra_node;
4362   guint64 mfra_offset = 0;
4363   guint32 fourcc, mfra_size;
4364   gint64 len;
4365
4366   /* query upstream size in bytes */
4367   if (!gst_pad_peer_query_duration (qtdemux->sinkpad, GST_FORMAT_BYTES, &len))
4368     goto size_query_failed;
4369
4370   /* mfro box should be at the very end of the file */
4371   flow = gst_qtdemux_pull_atom (qtdemux, len - 16, 16, &mfro);
4372   if (flow != GST_FLOW_OK)
4373     goto exit;
4374
4375   gst_buffer_map (mfro, &mfro_map, GST_MAP_READ);
4376
4377   fourcc = QT_FOURCC (mfro_map.data + 4);
4378   if (fourcc != FOURCC_mfro)
4379     goto exit;
4380
4381   GST_INFO_OBJECT (qtdemux, "Found mfro box");
4382   if (mfro_map.size < 16)
4383     goto invalid_mfro_size;
4384
4385   mfra_size = QT_UINT32 (mfro_map.data + 12);
4386   if (mfra_size >= len)
4387     goto invalid_mfra_size;
4388
4389   mfra_offset = len - mfra_size;
4390
4391   GST_INFO_OBJECT (qtdemux, "mfra offset: %" G_GUINT64_FORMAT ", size %u",
4392       mfra_offset, mfra_size);
4393
4394   /* now get and parse mfra box */
4395   flow = gst_qtdemux_pull_atom (qtdemux, mfra_offset, mfra_size, &mfra);
4396   if (flow != GST_FLOW_OK)
4397     goto broken_file;
4398
4399   gst_buffer_map (mfra, &mfra_map, GST_MAP_READ);
4400
4401   mfra_node = g_node_new ((guint8 *) mfra_map.data);
4402   qtdemux_parse_node (qtdemux, mfra_node, mfra_map.data, mfra_map.size);
4403
4404   tfra_node = qtdemux_tree_get_child_by_type (mfra_node, FOURCC_tfra);
4405
4406   while (tfra_node) {
4407     qtdemux_parse_tfra (qtdemux, tfra_node);
4408     /* iterate all siblings */
4409     tfra_node = qtdemux_tree_get_sibling_by_type (tfra_node, FOURCC_tfra);
4410   }
4411   g_node_destroy (mfra_node);
4412
4413   GST_INFO_OBJECT (qtdemux, "parsed movie fragment random access box (mfra)");
4414   ret = TRUE;
4415
4416 exit:
4417
4418   if (mfro) {
4419     if (mfro_map.memory != NULL)
4420       gst_buffer_unmap (mfro, &mfro_map);
4421     gst_buffer_unref (mfro);
4422   }
4423   if (mfra) {
4424     if (mfra_map.memory != NULL)
4425       gst_buffer_unmap (mfra, &mfra_map);
4426     gst_buffer_unref (mfra);
4427   }
4428   return ret;
4429
4430 /* ERRORS */
4431 size_query_failed:
4432   {
4433     GST_WARNING_OBJECT (qtdemux, "could not query upstream size");
4434     goto exit;
4435   }
4436 invalid_mfro_size:
4437   {
4438     GST_WARNING_OBJECT (qtdemux, "mfro size is too small");
4439     goto exit;
4440   }
4441 invalid_mfra_size:
4442   {
4443     GST_WARNING_OBJECT (qtdemux, "mfra_size in mfro box is invalid");
4444     goto exit;
4445   }
4446 broken_file:
4447   {
4448     GST_WARNING_OBJECT (qtdemux, "bogus mfra offset or size, broken file");
4449     goto exit;
4450   }
4451 }
4452
4453 static guint64
4454 add_offset (guint64 offset, guint64 advance)
4455 {
4456   /* Avoid 64-bit overflow by clamping */
4457   if (offset > G_MAXUINT64 - advance)
4458     return G_MAXUINT64;
4459   return offset + advance;
4460 }
4461
4462 static GstFlowReturn
4463 gst_qtdemux_loop_state_header (GstQTDemux * qtdemux)
4464 {
4465   guint64 length = 0;
4466   guint32 fourcc = 0;
4467   GstBuffer *buf = NULL;
4468   GstFlowReturn ret = GST_FLOW_OK;
4469   guint64 cur_offset = qtdemux->offset;
4470   GstMapInfo map;
4471
4472   ret = gst_pad_pull_range (qtdemux->sinkpad, cur_offset, 16, &buf);
4473   if (G_UNLIKELY (ret != GST_FLOW_OK))
4474     goto beach;
4475   gst_buffer_map (buf, &map, GST_MAP_READ);
4476   if (G_LIKELY (map.size >= 8))
4477     extract_initial_length_and_fourcc (map.data, map.size, &length, &fourcc);
4478   gst_buffer_unmap (buf, &map);
4479   gst_buffer_unref (buf);
4480
4481   /* maybe we already got most we needed, so only consider this eof */
4482   if (G_UNLIKELY (length == 0)) {
4483     GST_ELEMENT_WARNING (qtdemux, STREAM, DEMUX,
4484         (_("Invalid atom size.")),
4485         ("Header atom '%" GST_FOURCC_FORMAT "' has empty length",
4486             GST_FOURCC_ARGS (fourcc)));
4487     ret = GST_FLOW_EOS;
4488     goto beach;
4489   }
4490
4491   switch (fourcc) {
4492     case FOURCC_moof:
4493       /* record for later parsing when needed */
4494       if (!qtdemux->moof_offset) {
4495         qtdemux->moof_offset = qtdemux->offset;
4496       }
4497       if (qtdemux_pull_mfro_mfra (qtdemux)) {
4498         /* FIXME */
4499       } else {
4500         qtdemux->offset += length;      /* skip moof and keep going */
4501       }
4502       if (qtdemux->got_moov) {
4503         GST_INFO_OBJECT (qtdemux, "moof header, got moov, done with headers");
4504         ret = GST_FLOW_EOS;
4505         goto beach;
4506       }
4507       break;
4508     case FOURCC_mdat:
4509     case FOURCC_free:
4510     case FOURCC_skip:
4511     case FOURCC_wide:
4512     case FOURCC_PICT:
4513     case FOURCC_pnot:
4514     {
4515       GST_LOG_OBJECT (qtdemux,
4516           "skipping atom '%" GST_FOURCC_FORMAT "' at %" G_GUINT64_FORMAT,
4517           GST_FOURCC_ARGS (fourcc), cur_offset);
4518       qtdemux->offset = add_offset (qtdemux->offset, length);
4519       break;
4520     }
4521     case FOURCC_moov:
4522     {
4523       GstBuffer *moov = NULL;
4524
4525       if (qtdemux->got_moov) {
4526         GST_DEBUG_OBJECT (qtdemux, "Skipping moov atom as we have one already");
4527         qtdemux->offset = add_offset (qtdemux->offset, length);
4528         goto beach;
4529       }
4530
4531       ret = gst_pad_pull_range (qtdemux->sinkpad, cur_offset, length, &moov);
4532       if (ret != GST_FLOW_OK)
4533         goto beach;
4534       gst_buffer_map (moov, &map, GST_MAP_READ);
4535
4536       if (length != map.size) {
4537         /* Some files have a 'moov' atom at the end of the file which contains
4538          * a terminal 'free' atom where the body of the atom is missing.
4539          * Check for, and permit, this special case.
4540          */
4541         if (map.size >= 8) {
4542           guint8 *final_data = map.data + (map.size - 8);
4543           guint32 final_length = QT_UINT32 (final_data);
4544           guint32 final_fourcc = QT_FOURCC (final_data + 4);
4545
4546           if (final_fourcc == FOURCC_free
4547               && map.size + final_length - 8 == length) {
4548             /* Ok, we've found that special case. Allocate a new buffer with
4549              * that free atom actually present. */
4550             GstBuffer *newmoov = gst_buffer_new_and_alloc (length);
4551             gst_buffer_fill (newmoov, 0, map.data, map.size);
4552             gst_buffer_memset (newmoov, map.size, 0, final_length - 8);
4553             gst_buffer_unmap (moov, &map);
4554             gst_buffer_unref (moov);
4555             moov = newmoov;
4556             gst_buffer_map (moov, &map, GST_MAP_READ);
4557           }
4558         }
4559       }
4560
4561       if (length != map.size) {
4562         GST_ELEMENT_ERROR (qtdemux, STREAM, DEMUX,
4563             (_("This file is incomplete and cannot be played.")),
4564             ("We got less than expected (received %" G_GSIZE_FORMAT
4565                 ", wanted %u, offset %" G_GUINT64_FORMAT ")", map.size,
4566                 (guint) length, cur_offset));
4567         gst_buffer_unmap (moov, &map);
4568         gst_buffer_unref (moov);
4569         ret = GST_FLOW_ERROR;
4570         goto beach;
4571       }
4572       qtdemux->offset += length;
4573
4574       qtdemux_parse_moov (qtdemux, map.data, length);
4575       qtdemux_node_dump (qtdemux, qtdemux->moov_node);
4576
4577       qtdemux_parse_tree (qtdemux);
4578       if (qtdemux->moov_node_compressed) {
4579         g_node_destroy (qtdemux->moov_node_compressed);
4580         g_free (qtdemux->moov_node->data);
4581       }
4582       qtdemux->moov_node_compressed = NULL;
4583       g_node_destroy (qtdemux->moov_node);
4584       qtdemux->moov_node = NULL;
4585       gst_buffer_unmap (moov, &map);
4586       gst_buffer_unref (moov);
4587       qtdemux->got_moov = TRUE;
4588
4589       break;
4590     }
4591     case FOURCC_ftyp:
4592     {
4593       GstBuffer *ftyp = NULL;
4594
4595       /* extract major brand; might come in handy for ISO vs QT issues */
4596       ret = gst_qtdemux_pull_atom (qtdemux, cur_offset, length, &ftyp);
4597       if (ret != GST_FLOW_OK)
4598         goto beach;
4599       qtdemux->offset += length;
4600       gst_buffer_map (ftyp, &map, GST_MAP_READ);
4601       qtdemux_parse_ftyp (qtdemux, map.data, map.size);
4602       gst_buffer_unmap (ftyp, &map);
4603       gst_buffer_unref (ftyp);
4604       break;
4605     }
4606     case FOURCC_uuid:
4607     {
4608       GstBuffer *uuid = NULL;
4609
4610       /* uuid are extension atoms */
4611       ret = gst_qtdemux_pull_atom (qtdemux, cur_offset, length, &uuid);
4612       if (ret != GST_FLOW_OK)
4613         goto beach;
4614       qtdemux->offset += length;
4615       gst_buffer_map (uuid, &map, GST_MAP_READ);
4616       qtdemux_parse_uuid (qtdemux, map.data, map.size);
4617       gst_buffer_unmap (uuid, &map);
4618       gst_buffer_unref (uuid);
4619       break;
4620     }
4621     case FOURCC_sidx:
4622     {
4623       GstBuffer *sidx = NULL;
4624       ret = gst_qtdemux_pull_atom (qtdemux, cur_offset, length, &sidx);
4625       if (ret != GST_FLOW_OK)
4626         goto beach;
4627       qtdemux->offset += length;
4628       gst_buffer_map (sidx, &map, GST_MAP_READ);
4629       qtdemux_parse_sidx (qtdemux, map.data, map.size);
4630       gst_buffer_unmap (sidx, &map);
4631       gst_buffer_unref (sidx);
4632       break;
4633     }
4634     default:
4635     {
4636       GstBuffer *unknown = NULL;
4637
4638       GST_LOG_OBJECT (qtdemux,
4639           "unknown %08x '%" GST_FOURCC_FORMAT "' of size %" G_GUINT64_FORMAT
4640           " at %" G_GUINT64_FORMAT, fourcc, GST_FOURCC_ARGS (fourcc), length,
4641           cur_offset);
4642       ret = gst_qtdemux_pull_atom (qtdemux, cur_offset, length, &unknown);
4643       if (ret != GST_FLOW_OK)
4644         goto beach;
4645       gst_buffer_map (unknown, &map, GST_MAP_READ);
4646       GST_MEMDUMP ("Unknown tag", map.data, map.size);
4647       gst_buffer_unmap (unknown, &map);
4648       gst_buffer_unref (unknown);
4649       qtdemux->offset += length;
4650       break;
4651     }
4652   }
4653
4654 beach:
4655   if (ret == GST_FLOW_EOS && (qtdemux->got_moov || qtdemux->media_caps)) {
4656     /* digested all data, show what we have */
4657     qtdemux_prepare_streams (qtdemux);
4658     QTDEMUX_EXPOSE_LOCK (qtdemux);
4659     ret = qtdemux_expose_streams (qtdemux);
4660     QTDEMUX_EXPOSE_UNLOCK (qtdemux);
4661
4662     qtdemux->state = QTDEMUX_STATE_MOVIE;
4663     GST_DEBUG_OBJECT (qtdemux, "switching state to STATE_MOVIE (%d)",
4664         qtdemux->state);
4665     return ret;
4666   }
4667   return ret;
4668 }
4669
4670 /* Seeks to the previous keyframe of the indexed stream and
4671  * aligns other streams with respect to the keyframe timestamp
4672  * of indexed stream. Only called in case of Reverse Playback
4673  */
4674 static GstFlowReturn
4675 gst_qtdemux_seek_to_previous_keyframe (GstQTDemux * qtdemux)
4676 {
4677   guint32 seg_idx = 0, k_index = 0;
4678   guint32 ref_seg_idx, ref_k_index;
4679   GstClockTime k_pos = 0, last_stop = 0;
4680   QtDemuxSegment *seg = NULL;
4681   QtDemuxStream *ref_str = NULL;
4682   guint64 seg_media_start_mov;  /* segment media start time in mov format */
4683   guint64 target_ts;
4684   gint i;
4685
4686   /* Now we choose an arbitrary stream, get the previous keyframe timestamp
4687    * and finally align all the other streams on that timestamp with their
4688    * respective keyframes */
4689   for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
4690     QtDemuxStream *str = QTDEMUX_NTH_STREAM (qtdemux, i);
4691
4692     /* No candidate yet, take the first stream */
4693     if (!ref_str) {
4694       ref_str = str;
4695       continue;
4696     }
4697
4698     /* So that stream has a segment, we prefer video streams */
4699     if (str->subtype == FOURCC_vide) {
4700       ref_str = str;
4701       break;
4702     }
4703   }
4704
4705   if (G_UNLIKELY (!ref_str)) {
4706     GST_DEBUG_OBJECT (qtdemux, "couldn't find any stream");
4707     goto eos;
4708   }
4709
4710   if (G_UNLIKELY (!ref_str->from_sample)) {
4711     GST_DEBUG_OBJECT (qtdemux, "reached the beginning of the file");
4712     goto eos;
4713   }
4714
4715   /* So that stream has been playing from from_sample to to_sample. We will
4716    * get the timestamp of the previous sample and search for a keyframe before
4717    * that. For audio streams we do an arbitrary jump in the past (10 samples) */
4718   if (ref_str->subtype == FOURCC_vide) {
4719     k_index = gst_qtdemux_find_keyframe (qtdemux, ref_str,
4720         ref_str->from_sample - 1, FALSE);
4721   } else {
4722     if (ref_str->from_sample >= 10)
4723       k_index = ref_str->from_sample - 10;
4724     else
4725       k_index = 0;
4726   }
4727
4728   target_ts =
4729       ref_str->samples[k_index].timestamp +
4730       ref_str->samples[k_index].pts_offset;
4731
4732   /* get current segment for that stream */
4733   seg = &ref_str->segments[ref_str->segment_index];
4734   /* Use segment start in original timescale for comparisons */
4735   seg_media_start_mov = seg->trak_media_start;
4736
4737   GST_LOG_OBJECT (qtdemux, "keyframe index %u ts %" G_GUINT64_FORMAT
4738       " seg start %" G_GUINT64_FORMAT " %" GST_TIME_FORMAT,
4739       k_index, target_ts, seg_media_start_mov,
4740       GST_TIME_ARGS (seg->media_start));
4741
4742   /* Crawl back through segments to find the one containing this I frame */
4743   while (target_ts < seg_media_start_mov) {
4744     GST_DEBUG_OBJECT (qtdemux,
4745         "keyframe position (sample %u) is out of segment %u " " target %"
4746         G_GUINT64_FORMAT " seg start %" G_GUINT64_FORMAT, k_index,
4747         ref_str->segment_index, target_ts, seg_media_start_mov);
4748
4749     if (G_UNLIKELY (!ref_str->segment_index)) {
4750       /* Reached first segment, let's consider it's EOS */
4751       goto eos;
4752     }
4753     ref_str->segment_index--;
4754     seg = &ref_str->segments[ref_str->segment_index];
4755     /* Use segment start in original timescale for comparisons */
4756     seg_media_start_mov = seg->trak_media_start;
4757   }
4758   /* Calculate time position of the keyframe and where we should stop */
4759   k_pos =
4760       QTSTREAMTIME_TO_GSTTIME (ref_str,
4761       target_ts - seg->trak_media_start) + seg->time;
4762   last_stop =
4763       QTSTREAMTIME_TO_GSTTIME (ref_str,
4764       ref_str->samples[ref_str->from_sample].timestamp -
4765       seg->trak_media_start) + seg->time;
4766
4767   GST_DEBUG_OBJECT (qtdemux, "preferred stream played from sample %u, "
4768       "now going to sample %u (pts %" GST_TIME_FORMAT ")", ref_str->from_sample,
4769       k_index, GST_TIME_ARGS (k_pos));
4770
4771   /* Set last_stop with the keyframe timestamp we pushed of that stream */
4772   qtdemux->segment.position = last_stop;
4773   GST_DEBUG_OBJECT (qtdemux, "last_stop now is %" GST_TIME_FORMAT,
4774       GST_TIME_ARGS (last_stop));
4775
4776   if (G_UNLIKELY (last_stop < qtdemux->segment.start)) {
4777     GST_DEBUG_OBJECT (qtdemux, "reached the beginning of segment");
4778     goto eos;
4779   }
4780
4781   ref_seg_idx = ref_str->segment_index;
4782   ref_k_index = k_index;
4783
4784   /* Align them all on this */
4785   for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
4786     guint32 index = 0;
4787     GstClockTime seg_time = 0;
4788     QtDemuxStream *str = QTDEMUX_NTH_STREAM (qtdemux, i);
4789
4790     /* aligning reference stream again might lead to backing up to yet another
4791      * keyframe (due to timestamp rounding issues),
4792      * potentially putting more load on downstream; so let's try to avoid */
4793     if (str == ref_str) {
4794       seg_idx = ref_seg_idx;
4795       seg = &str->segments[seg_idx];
4796       k_index = ref_k_index;
4797       GST_DEBUG_OBJECT (qtdemux, "reference track-id %u segment %d, "
4798           "sample at index %d", str->track_id, ref_str->segment_index, k_index);
4799     } else {
4800       seg_idx = gst_qtdemux_find_segment (qtdemux, str, k_pos);
4801       GST_DEBUG_OBJECT (qtdemux,
4802           "track-id %u align segment %d for keyframe pos %" GST_TIME_FORMAT,
4803           str->track_id, seg_idx, GST_TIME_ARGS (k_pos));
4804
4805       /* get segment and time in the segment */
4806       seg = &str->segments[seg_idx];
4807       seg_time = k_pos - seg->time;
4808
4809       /* get the media time in the segment.
4810        * No adjustment for empty "filler" segments */
4811       if (seg->media_start != GST_CLOCK_TIME_NONE)
4812         seg_time += seg->media_start;
4813
4814       /* get the index of the sample with media time */
4815       index = gst_qtdemux_find_index_linear (qtdemux, str, seg_time);
4816       GST_DEBUG_OBJECT (qtdemux,
4817           "track-id %u sample for %" GST_TIME_FORMAT " at %u", str->track_id,
4818           GST_TIME_ARGS (seg_time), index);
4819
4820       /* find previous keyframe */
4821       k_index = gst_qtdemux_find_keyframe (qtdemux, str, index, FALSE);
4822     }
4823
4824     /* Remember until where we want to go */
4825     str->to_sample = str->from_sample - 1;
4826     /* Define our time position */
4827     target_ts =
4828         str->samples[k_index].timestamp + str->samples[k_index].pts_offset;
4829     str->time_position = QTSTREAMTIME_TO_GSTTIME (str, target_ts) + seg->time;
4830     if (seg->media_start != GST_CLOCK_TIME_NONE)
4831       str->time_position -= seg->media_start;
4832
4833     /* Now seek back in time */
4834     gst_qtdemux_move_stream (qtdemux, str, k_index);
4835     GST_DEBUG_OBJECT (qtdemux, "track-id %u keyframe at %u, time position %"
4836         GST_TIME_FORMAT " playing from sample %u to %u", str->track_id, k_index,
4837         GST_TIME_ARGS (str->time_position), str->from_sample, str->to_sample);
4838   }
4839
4840   return GST_FLOW_OK;
4841
4842 eos:
4843   return GST_FLOW_EOS;
4844 }
4845
4846 /*
4847  * Gets the current qt segment start, stop and position for the
4848  * given time offset. This is used in update_segment()
4849  */
4850 static void
4851 gst_qtdemux_stream_segment_get_boundaries (GstQTDemux * qtdemux,
4852     QtDemuxStream * stream, GstClockTime offset,
4853     GstClockTime * _start, GstClockTime * _stop, GstClockTime * _time)
4854 {
4855   GstClockTime seg_time;
4856   GstClockTime start, stop, time;
4857   QtDemuxSegment *segment;
4858
4859   segment = &stream->segments[stream->segment_index];
4860
4861   /* get time in this segment */
4862   seg_time = (offset - segment->time) * segment->rate;
4863
4864   GST_LOG_OBJECT (stream->pad, "seg_time %" GST_TIME_FORMAT,
4865       GST_TIME_ARGS (seg_time));
4866
4867   if (G_UNLIKELY (seg_time > segment->duration)) {
4868     GST_LOG_OBJECT (stream->pad,
4869         "seg_time > segment->duration %" GST_TIME_FORMAT,
4870         GST_TIME_ARGS (segment->duration));
4871     seg_time = segment->duration;
4872   }
4873
4874   /* qtdemux->segment.stop is in outside-time-realm, whereas
4875    * segment->media_stop is in track-time-realm.
4876    *
4877    * In order to compare the two, we need to bring segment.stop
4878    * into the track-time-realm
4879    *
4880    * FIXME - does this comment still hold? Don't see any conversion here */
4881
4882   stop = qtdemux->segment.stop;
4883   if (stop == GST_CLOCK_TIME_NONE)
4884     stop = qtdemux->segment.duration;
4885   if (stop == GST_CLOCK_TIME_NONE)
4886     stop = segment->media_stop;
4887   else
4888     stop =
4889         MIN (segment->media_stop, stop - segment->time + segment->media_start);
4890
4891   if (G_UNLIKELY (QTSEGMENT_IS_EMPTY (segment))) {
4892     start = segment->time + seg_time;
4893     time = offset;
4894     stop = start - seg_time + segment->duration;
4895   } else if (qtdemux->segment.rate >= 0) {
4896     start = MIN (segment->media_start + seg_time, stop);
4897     time = offset;
4898   } else {
4899     if (segment->media_start >= qtdemux->segment.start) {
4900       time = segment->time;
4901     } else {
4902       time = segment->time + (qtdemux->segment.start - segment->media_start);
4903     }
4904
4905     start = MAX (segment->media_start, qtdemux->segment.start);
4906     stop = MIN (segment->media_start + seg_time, stop);
4907   }
4908
4909   *_start = start;
4910   *_stop = stop;
4911   *_time = time;
4912 }
4913
4914 /*
4915  * Updates the qt segment used for the stream and pushes a new segment event
4916  * downstream on this stream's pad.
4917  */
4918 static gboolean
4919 gst_qtdemux_stream_update_segment (GstQTDemux * qtdemux, QtDemuxStream * stream,
4920     gint seg_idx, GstClockTime offset, GstClockTime * _start,
4921     GstClockTime * _stop)
4922 {
4923   QtDemuxSegment *segment;
4924   GstClockTime start = 0, stop = GST_CLOCK_TIME_NONE, time = 0;
4925   gdouble rate;
4926   GstEvent *event;
4927
4928   /* update the current segment */
4929   stream->segment_index = seg_idx;
4930
4931   /* get the segment */
4932   segment = &stream->segments[seg_idx];
4933
4934   if (G_UNLIKELY (offset < segment->time)) {
4935     GST_WARNING_OBJECT (stream->pad, "offset < segment->time %" GST_TIME_FORMAT,
4936         GST_TIME_ARGS (segment->time));
4937     return FALSE;
4938   }
4939
4940   /* segment lies beyond total indicated duration */
4941   if (G_UNLIKELY (qtdemux->segment.duration != GST_CLOCK_TIME_NONE &&
4942           segment->time > qtdemux->segment.duration)) {
4943     GST_WARNING_OBJECT (stream->pad, "file duration %" GST_TIME_FORMAT
4944         " < segment->time %" GST_TIME_FORMAT,
4945         GST_TIME_ARGS (qtdemux->segment.duration),
4946         GST_TIME_ARGS (segment->time));
4947     return FALSE;
4948   }
4949
4950   gst_qtdemux_stream_segment_get_boundaries (qtdemux, stream, offset,
4951       &start, &stop, &time);
4952
4953   GST_DEBUG_OBJECT (stream->pad, "new segment %d from %" GST_TIME_FORMAT
4954       " to %" GST_TIME_FORMAT ", time %" GST_TIME_FORMAT, seg_idx,
4955       GST_TIME_ARGS (start), GST_TIME_ARGS (stop), GST_TIME_ARGS (time));
4956
4957   /* combine global rate with that of the segment */
4958   rate = segment->rate * qtdemux->segment.rate;
4959
4960   /* Copy flags from main segment */
4961   stream->segment.flags = qtdemux->segment.flags;
4962
4963   /* update the segment values used for clipping */
4964   stream->segment.offset = qtdemux->segment.offset;
4965   stream->segment.base = qtdemux->segment.base + stream->accumulated_base;
4966   stream->segment.applied_rate = qtdemux->segment.applied_rate;
4967   stream->segment.rate = rate;
4968   stream->segment.start = start + QTSTREAMTIME_TO_GSTTIME (stream,
4969       stream->cslg_shift);
4970   if (stop != -1)
4971     stream->segment.stop = stop + QTSTREAMTIME_TO_GSTTIME (stream,
4972         stream->cslg_shift);
4973   else
4974     stream->segment.stop = stop;
4975   stream->segment.time = time;
4976   stream->segment.position = stream->segment.start;
4977
4978   GST_DEBUG_OBJECT (stream->pad, "New segment: %" GST_SEGMENT_FORMAT,
4979       &stream->segment);
4980
4981   /* now prepare and send the segment */
4982   if (stream->pad) {
4983     event = gst_event_new_segment (&stream->segment);
4984     if (qtdemux->segment_seqnum != GST_SEQNUM_INVALID) {
4985       gst_event_set_seqnum (event, qtdemux->segment_seqnum);
4986     }
4987     gst_pad_push_event (stream->pad, event);
4988     /* assume we can send more data now */
4989     GST_PAD_LAST_FLOW_RETURN (stream->pad) = GST_FLOW_OK;
4990     /* clear to send tags on this pad now */
4991     gst_qtdemux_push_tags (qtdemux, stream);
4992   }
4993
4994   if (_start)
4995     *_start = start;
4996   if (_stop)
4997     *_stop = stop;
4998
4999   return TRUE;
5000 }
5001
5002 /* activate the given segment number @seg_idx of @stream at time @offset.
5003  * @offset is an absolute global position over all the segments.
5004  *
5005  * This will push out a NEWSEGMENT event with the right values and
5006  * position the stream index to the first decodable sample before
5007  * @offset.
5008  */
5009 static gboolean
5010 gst_qtdemux_activate_segment (GstQTDemux * qtdemux, QtDemuxStream * stream,
5011     guint32 seg_idx, GstClockTime offset)
5012 {
5013   QtDemuxSegment *segment;
5014   guint32 index, kf_index;
5015   GstClockTime start = 0, stop = GST_CLOCK_TIME_NONE;
5016
5017   GST_LOG_OBJECT (stream->pad, "activate segment %d, offset %" GST_TIME_FORMAT,
5018       seg_idx, GST_TIME_ARGS (offset));
5019
5020   if (!gst_qtdemux_stream_update_segment (qtdemux, stream, seg_idx, offset,
5021           &start, &stop))
5022     return FALSE;
5023
5024   segment = &stream->segments[stream->segment_index];
5025
5026   /* in the fragmented case, we pick a fragment that starts before our
5027    * desired position and rely on downstream to wait for a keyframe
5028    * (FIXME: doesn't seem to work so well with ismv and wmv, as no parser; the
5029    * tfra entries tells us which trun/sample the key unit is in, but we don't
5030    * make use of this additional information at the moment) */
5031   if (qtdemux->fragmented && !qtdemux->fragmented_seek_pending) {
5032     stream->to_sample = G_MAXUINT32;
5033     return TRUE;
5034   } else {
5035     /* well, it will be taken care of below */
5036     qtdemux->fragmented_seek_pending = FALSE;
5037     /* FIXME ideally the do_fragmented_seek can be done right here,
5038      * rather than at loop level
5039      * (which might even allow handling edit lists in a fragmented file) */
5040   }
5041
5042   /* We don't need to look for a sample in push-based */
5043   if (!qtdemux->pullbased)
5044     return TRUE;
5045
5046   /* and move to the keyframe before the indicated media time of the
5047    * segment */
5048   if (G_LIKELY (!QTSEGMENT_IS_EMPTY (segment))) {
5049     if (qtdemux->segment.rate >= 0) {
5050       index = gst_qtdemux_find_index_linear (qtdemux, stream, start);
5051       stream->to_sample = G_MAXUINT32;
5052       GST_DEBUG_OBJECT (stream->pad,
5053           "moving data pointer to %" GST_TIME_FORMAT ", index: %u, pts %"
5054           GST_TIME_FORMAT, GST_TIME_ARGS (start), index,
5055           GST_TIME_ARGS (QTSAMPLE_PTS (stream, &stream->samples[index])));
5056     } else {
5057       index = gst_qtdemux_find_index_linear (qtdemux, stream, stop);
5058       stream->to_sample = index;
5059       GST_DEBUG_OBJECT (stream->pad,
5060           "moving data pointer to %" GST_TIME_FORMAT ", index: %u, pts %"
5061           GST_TIME_FORMAT, GST_TIME_ARGS (stop), index,
5062           GST_TIME_ARGS (QTSAMPLE_PTS (stream, &stream->samples[index])));
5063     }
5064   } else {
5065     GST_DEBUG_OBJECT (stream->pad, "No need to look for keyframe, "
5066         "this is an empty segment");
5067     return TRUE;
5068   }
5069
5070   /* gst_qtdemux_parse_sample () called from gst_qtdemux_find_index_linear ()
5071    * encountered an error and printed a message so we return appropriately */
5072   if (index == -1)
5073     return FALSE;
5074
5075   /* we're at the right spot */
5076   if (index == stream->sample_index) {
5077     GST_DEBUG_OBJECT (stream->pad, "we are at the right index");
5078     return TRUE;
5079   }
5080
5081   /* find keyframe of the target index */
5082   kf_index = gst_qtdemux_find_keyframe (qtdemux, stream, index, FALSE);
5083
5084   /* go back two frames to provide lead-in for non-raw audio decoders */
5085   if (stream->subtype == FOURCC_soun && !stream->need_clip) {
5086     guint32 lead_in = 2;
5087     guint32 old_index = kf_index;
5088     GstStructure *s = gst_caps_get_structure (CUR_STREAM (stream)->caps, 0);
5089
5090     if (gst_structure_has_name (s, "audio/mpeg")) {
5091       gint mpegversion;
5092       if (gst_structure_get_int (s, "mpegversion", &mpegversion)
5093           && mpegversion == 1) {
5094         /* mp3 could need up to 30 frames of lead-in per mpegaudioparse */
5095         lead_in = 30;
5096       }
5097     }
5098
5099     kf_index = MAX (kf_index, lead_in) - lead_in;
5100     if (qtdemux_parse_samples (qtdemux, stream, kf_index)) {
5101       GST_DEBUG_OBJECT (stream->pad,
5102           "Moving backwards %u frames to ensure sufficient sound lead-in",
5103           old_index - kf_index);
5104     } else {
5105       kf_index = old_index;
5106     }
5107   }
5108
5109   /* if we move forwards, we don't have to go back to the previous
5110    * keyframe since we already sent that. We can also just jump to
5111    * the keyframe right before the target index if there is one. */
5112   if (index > stream->sample_index) {
5113     /* moving forwards check if we move past a keyframe */
5114     if (kf_index > stream->sample_index) {
5115       GST_DEBUG_OBJECT (stream->pad,
5116           "moving forwards to keyframe at %u "
5117           "(pts %" GST_TIME_FORMAT " dts %" GST_TIME_FORMAT " )",
5118           kf_index,
5119           GST_TIME_ARGS (QTSAMPLE_PTS (stream, &stream->samples[kf_index])),
5120           GST_TIME_ARGS (QTSAMPLE_DTS (stream, &stream->samples[kf_index])));
5121       gst_qtdemux_move_stream (qtdemux, stream, kf_index);
5122     } else {
5123       GST_DEBUG_OBJECT (stream->pad,
5124           "moving forwards, keyframe at %u "
5125           "(pts %" GST_TIME_FORMAT " dts %" GST_TIME_FORMAT " ) already sent",
5126           kf_index,
5127           GST_TIME_ARGS (QTSAMPLE_PTS (stream, &stream->samples[kf_index])),
5128           GST_TIME_ARGS (QTSAMPLE_DTS (stream, &stream->samples[kf_index])));
5129     }
5130   } else {
5131     GST_DEBUG_OBJECT (stream->pad,
5132         "moving backwards to %sframe at %u "
5133         "(pts %" GST_TIME_FORMAT " dts %" GST_TIME_FORMAT " )",
5134         (stream->subtype == FOURCC_soun) ? "audio " : "key", kf_index,
5135         GST_TIME_ARGS (QTSAMPLE_PTS (stream, &stream->samples[kf_index])),
5136         GST_TIME_ARGS (QTSAMPLE_DTS (stream, &stream->samples[kf_index])));
5137     gst_qtdemux_move_stream (qtdemux, stream, kf_index);
5138   }
5139
5140   return TRUE;
5141 }
5142
5143 /* prepare to get the current sample of @stream, getting essential values.
5144  *
5145  * This function will also prepare and send the segment when needed.
5146  *
5147  * Return FALSE if the stream is EOS.
5148  *
5149  * PULL-BASED
5150  */
5151 static gboolean
5152 gst_qtdemux_prepare_current_sample (GstQTDemux * qtdemux,
5153     QtDemuxStream * stream, gboolean * empty, guint64 * offset, guint * size,
5154     GstClockTime * dts, GstClockTime * pts, GstClockTime * duration,
5155     gboolean * keyframe)
5156 {
5157   QtDemuxSample *sample;
5158   GstClockTime time_position;
5159   guint32 seg_idx;
5160
5161   g_return_val_if_fail (stream != NULL, FALSE);
5162
5163   time_position = stream->time_position;
5164   if (G_UNLIKELY (time_position == GST_CLOCK_TIME_NONE))
5165     goto eos;
5166
5167   seg_idx = stream->segment_index;
5168   if (G_UNLIKELY (seg_idx == -1)) {
5169     /* find segment corresponding to time_position if we are looking
5170      * for a segment. */
5171     seg_idx = gst_qtdemux_find_segment (qtdemux, stream, time_position);
5172   }
5173
5174   /* different segment, activate it, sample_index will be set. */
5175   if (G_UNLIKELY (stream->segment_index != seg_idx))
5176     gst_qtdemux_activate_segment (qtdemux, stream, seg_idx, time_position);
5177
5178   if (G_UNLIKELY (QTSEGMENT_IS_EMPTY (&stream->
5179               segments[stream->segment_index]))) {
5180     QtDemuxSegment *seg = &stream->segments[stream->segment_index];
5181
5182     GST_LOG_OBJECT (qtdemux, "Empty segment activated,"
5183         " prepare empty sample");
5184
5185     *empty = TRUE;
5186     *pts = *dts = time_position;
5187     *duration = seg->duration - (time_position - seg->time);
5188
5189     return TRUE;
5190   }
5191
5192   *empty = FALSE;
5193
5194   if (stream->sample_index == -1)
5195     stream->sample_index = 0;
5196
5197   GST_LOG_OBJECT (qtdemux, "segment active, index = %u of %u",
5198       stream->sample_index, stream->n_samples);
5199
5200   if (G_UNLIKELY (stream->sample_index >= stream->n_samples)) {
5201     if (!qtdemux->fragmented)
5202       goto eos;
5203
5204     GST_INFO_OBJECT (qtdemux, "out of samples, trying to add more");
5205     do {
5206       GstFlowReturn flow;
5207
5208       GST_OBJECT_LOCK (qtdemux);
5209       flow = qtdemux_add_fragmented_samples (qtdemux);
5210       GST_OBJECT_UNLOCK (qtdemux);
5211
5212       if (flow != GST_FLOW_OK)
5213         goto eos;
5214     }
5215     while (stream->sample_index >= stream->n_samples);
5216   }
5217
5218   if (!qtdemux_parse_samples (qtdemux, stream, stream->sample_index)) {
5219     GST_LOG_OBJECT (qtdemux, "Parsing of index %u failed!",
5220         stream->sample_index);
5221     return FALSE;
5222   }
5223
5224   /* now get the info for the sample we're at */
5225   sample = &stream->samples[stream->sample_index];
5226
5227   *dts = QTSAMPLE_DTS (stream, sample);
5228   *pts = QTSAMPLE_PTS (stream, sample);
5229   *offset = sample->offset;
5230   *size = sample->size;
5231   *duration = QTSAMPLE_DUR_DTS (stream, sample, *dts);
5232   *keyframe = QTSAMPLE_KEYFRAME (stream, sample);
5233
5234   return TRUE;
5235
5236   /* special cases */
5237 eos:
5238   {
5239     stream->time_position = GST_CLOCK_TIME_NONE;
5240     return FALSE;
5241   }
5242 }
5243
5244 /* move to the next sample in @stream.
5245  *
5246  * Moves to the next segment when needed.
5247  */
5248 static void
5249 gst_qtdemux_advance_sample (GstQTDemux * qtdemux, QtDemuxStream * stream)
5250 {
5251   QtDemuxSample *sample;
5252   QtDemuxSegment *segment;
5253
5254   /* get current segment */
5255   segment = &stream->segments[stream->segment_index];
5256
5257   if (G_UNLIKELY (QTSEGMENT_IS_EMPTY (segment))) {
5258     GST_DEBUG_OBJECT (qtdemux, "Empty segment, no samples to advance");
5259     goto next_segment;
5260   }
5261
5262   if (G_UNLIKELY (stream->sample_index >= stream->to_sample)) {
5263     /* Mark the stream as EOS */
5264     GST_DEBUG_OBJECT (qtdemux,
5265         "reached max allowed sample %u, mark EOS", stream->to_sample);
5266     stream->time_position = GST_CLOCK_TIME_NONE;
5267     return;
5268   }
5269
5270   /* move to next sample */
5271   stream->sample_index++;
5272   stream->offset_in_sample = 0;
5273
5274   GST_TRACE_OBJECT (qtdemux, "advance to sample %u/%u", stream->sample_index,
5275       stream->n_samples);
5276
5277   /* reached the last sample, we need the next segment */
5278   if (G_UNLIKELY (stream->sample_index >= stream->n_samples))
5279     goto next_segment;
5280
5281   if (!qtdemux_parse_samples (qtdemux, stream, stream->sample_index)) {
5282     GST_LOG_OBJECT (qtdemux, "Parsing of index %u failed!",
5283         stream->sample_index);
5284     return;
5285   }
5286
5287   /* get next sample */
5288   sample = &stream->samples[stream->sample_index];
5289
5290   GST_TRACE_OBJECT (qtdemux, "sample dts %" GST_TIME_FORMAT " media_stop: %"
5291       GST_TIME_FORMAT, GST_TIME_ARGS (QTSAMPLE_DTS (stream, sample)),
5292       GST_TIME_ARGS (segment->media_stop));
5293
5294   /* see if we are past the segment */
5295   if (G_UNLIKELY (QTSAMPLE_DTS (stream, sample) >= segment->media_stop))
5296     goto next_segment;
5297
5298   if (QTSAMPLE_DTS (stream, sample) >= segment->media_start) {
5299     /* inside the segment, update time_position, looks very familiar to
5300      * GStreamer segments, doesn't it? */
5301     stream->time_position =
5302         QTSAMPLE_DTS (stream, sample) - segment->media_start + segment->time;
5303   } else {
5304     /* not yet in segment, time does not yet increment. This means
5305      * that we are still prerolling keyframes to the decoder so it can
5306      * decode the first sample of the segment. */
5307     stream->time_position = segment->time;
5308   }
5309   return;
5310
5311   /* move to the next segment */
5312 next_segment:
5313   {
5314     GST_DEBUG_OBJECT (qtdemux, "segment %d ended ", stream->segment_index);
5315
5316     if (stream->segment_index == stream->n_segments - 1) {
5317       /* are we at the end of the last segment, we're EOS */
5318       stream->time_position = GST_CLOCK_TIME_NONE;
5319     } else {
5320       /* else we're only at the end of the current segment */
5321       stream->time_position = segment->stop_time;
5322     }
5323     /* make sure we select a new segment */
5324
5325     /* accumulate previous segments */
5326     if (GST_CLOCK_TIME_IS_VALID (stream->segment.stop))
5327       stream->accumulated_base +=
5328           (stream->segment.stop -
5329           stream->segment.start) / ABS (stream->segment.rate);
5330
5331     stream->segment_index = -1;
5332   }
5333 }
5334
5335 static void
5336 gst_qtdemux_sync_streams (GstQTDemux * demux)
5337 {
5338   gint i;
5339
5340   if (QTDEMUX_N_STREAMS (demux) <= 1)
5341     return;
5342
5343   for (i = 0; i < QTDEMUX_N_STREAMS (demux); i++) {
5344     QtDemuxStream *stream;
5345     GstClockTime end_time;
5346
5347     stream = QTDEMUX_NTH_STREAM (demux, i);
5348
5349     if (!stream->pad)
5350       continue;
5351
5352     /* TODO advance time on subtitle streams here, if any some day */
5353
5354     /* some clips/trailers may have unbalanced streams at the end,
5355      * so send EOS on shorter stream to prevent stalling others */
5356
5357     /* do not mess with EOS if SEGMENT seeking */
5358     if (demux->segment.flags & GST_SEEK_FLAG_SEGMENT)
5359       continue;
5360
5361     if (demux->pullbased) {
5362       /* loop mode is sample time based */
5363       if (!STREAM_IS_EOS (stream))
5364         continue;
5365     } else {
5366       /* push mode is byte position based */
5367       if (stream->n_samples &&
5368           stream->samples[stream->n_samples - 1].offset >= demux->offset)
5369         continue;
5370     }
5371
5372     if (stream->sent_eos)
5373       continue;
5374
5375     /* only act if some gap */
5376     end_time = stream->segments[stream->n_segments - 1].stop_time;
5377     GST_LOG_OBJECT (demux, "current position: %" GST_TIME_FORMAT
5378         ", stream end: %" GST_TIME_FORMAT,
5379         GST_TIME_ARGS (demux->segment.position), GST_TIME_ARGS (end_time));
5380     if (GST_CLOCK_TIME_IS_VALID (end_time)
5381         && (end_time + 2 * GST_SECOND < demux->segment.position)) {
5382       GstEvent *event;
5383
5384       GST_DEBUG_OBJECT (demux, "sending EOS for stream %s",
5385           GST_PAD_NAME (stream->pad));
5386       stream->sent_eos = TRUE;
5387       event = gst_event_new_eos ();
5388       if (demux->segment_seqnum != GST_SEQNUM_INVALID)
5389         gst_event_set_seqnum (event, demux->segment_seqnum);
5390       gst_pad_push_event (stream->pad, event);
5391     }
5392   }
5393 }
5394
5395 /* EOS and NOT_LINKED need to be combined. This means that we return:
5396  *
5397  *  GST_FLOW_NOT_LINKED: when all pads NOT_LINKED.
5398  *  GST_FLOW_EOS: when all pads EOS or NOT_LINKED.
5399  */
5400 static GstFlowReturn
5401 gst_qtdemux_combine_flows (GstQTDemux * demux, QtDemuxStream * stream,
5402     GstFlowReturn ret)
5403 {
5404   GST_LOG_OBJECT (demux, "flow return: %s", gst_flow_get_name (ret));
5405
5406   if (stream->pad)
5407     ret = gst_flow_combiner_update_pad_flow (demux->flowcombiner, stream->pad,
5408         ret);
5409   else
5410     ret = gst_flow_combiner_update_flow (demux->flowcombiner, ret);
5411
5412   GST_LOG_OBJECT (demux, "combined flow return: %s", gst_flow_get_name (ret));
5413   return ret;
5414 }
5415
5416 /* the input buffer metadata must be writable. Returns NULL when the buffer is
5417  * completely clipped
5418  *
5419  * Should be used only with raw buffers */
5420 static GstBuffer *
5421 gst_qtdemux_clip_buffer (GstQTDemux * qtdemux, QtDemuxStream * stream,
5422     GstBuffer * buf)
5423 {
5424   guint64 start, stop, cstart, cstop, diff;
5425   GstClockTime pts, duration;
5426   gsize size, osize;
5427   gint num_rate, denom_rate;
5428   gint frame_size;
5429   gboolean clip_data;
5430   guint offset;
5431
5432   osize = size = gst_buffer_get_size (buf);
5433   offset = 0;
5434
5435   /* depending on the type, setup the clip parameters */
5436   if (stream->subtype == FOURCC_soun) {
5437     frame_size = CUR_STREAM (stream)->bytes_per_frame;
5438     num_rate = GST_SECOND;
5439     denom_rate = (gint) CUR_STREAM (stream)->rate;
5440     clip_data = TRUE;
5441   } else if (stream->subtype == FOURCC_vide) {
5442     frame_size = size;
5443     num_rate = CUR_STREAM (stream)->fps_n;
5444     denom_rate = CUR_STREAM (stream)->fps_d;
5445     clip_data = FALSE;
5446   } else
5447     goto wrong_type;
5448
5449   if (frame_size <= 0)
5450     goto bad_frame_size;
5451
5452   /* we can only clip if we have a valid pts */
5453   pts = GST_BUFFER_PTS (buf);
5454   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (pts)))
5455     goto no_pts;
5456
5457   duration = GST_BUFFER_DURATION (buf);
5458
5459   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (duration))) {
5460     duration =
5461         gst_util_uint64_scale_int (size / frame_size, num_rate, denom_rate);
5462   }
5463
5464   start = pts;
5465   stop = start + duration;
5466
5467   if (G_UNLIKELY (!gst_segment_clip (&stream->segment,
5468               GST_FORMAT_TIME, start, stop, &cstart, &cstop)))
5469     goto clipped;
5470
5471   /* see if some clipping happened */
5472   diff = cstart - start;
5473   if (diff > 0) {
5474     pts += diff;
5475     duration -= diff;
5476
5477     if (clip_data) {
5478       /* bring clipped time to samples and to bytes */
5479       diff = gst_util_uint64_scale_int (diff, denom_rate, num_rate);
5480       diff *= frame_size;
5481
5482       GST_DEBUG_OBJECT (qtdemux,
5483           "clipping start to %" GST_TIME_FORMAT " %"
5484           G_GUINT64_FORMAT " bytes", GST_TIME_ARGS (cstart), diff);
5485
5486       offset = diff;
5487       size -= diff;
5488     }
5489   }
5490   diff = stop - cstop;
5491   if (diff > 0) {
5492     duration -= diff;
5493
5494     if (clip_data) {
5495       /* bring clipped time to samples and then to bytes */
5496       diff = gst_util_uint64_scale_int (diff, denom_rate, num_rate);
5497       diff *= frame_size;
5498       GST_DEBUG_OBJECT (qtdemux,
5499           "clipping stop to %" GST_TIME_FORMAT " %" G_GUINT64_FORMAT
5500           " bytes", GST_TIME_ARGS (cstop), diff);
5501       size -= diff;
5502     }
5503   }
5504
5505   if (offset != 0 || size != osize)
5506     gst_buffer_resize (buf, offset, size);
5507
5508   GST_BUFFER_DTS (buf) = GST_CLOCK_TIME_NONE;
5509   GST_BUFFER_PTS (buf) = pts;
5510   GST_BUFFER_DURATION (buf) = duration;
5511
5512   return buf;
5513
5514   /* dropped buffer */
5515 wrong_type:
5516   {
5517     GST_DEBUG_OBJECT (qtdemux, "unknown stream type");
5518     return buf;
5519   }
5520 bad_frame_size:
5521   {
5522     GST_DEBUG_OBJECT (qtdemux, "bad frame size");
5523     return buf;
5524   }
5525 no_pts:
5526   {
5527     GST_DEBUG_OBJECT (qtdemux, "no pts on buffer");
5528     return buf;
5529   }
5530 clipped:
5531   {
5532     GST_DEBUG_OBJECT (qtdemux, "clipped buffer");
5533     gst_buffer_unref (buf);
5534     return NULL;
5535   }
5536 }
5537
5538 static GstBuffer *
5539 gst_qtdemux_align_buffer (GstQTDemux * demux,
5540     GstBuffer * buffer, gsize alignment)
5541 {
5542   GstMapInfo map;
5543
5544   gst_buffer_map (buffer, &map, GST_MAP_READ);
5545
5546   if (map.size < sizeof (guintptr)) {
5547     gst_buffer_unmap (buffer, &map);
5548     return buffer;
5549   }
5550
5551   if (((guintptr) map.data) & (alignment - 1)) {
5552     GstBuffer *new_buffer;
5553     GstAllocationParams params = { 0, alignment - 1, 0, 0, };
5554
5555     new_buffer = gst_buffer_new_allocate (NULL,
5556         gst_buffer_get_size (buffer), &params);
5557
5558     /* Copy data "by hand", so ensure alignment is kept: */
5559     gst_buffer_fill (new_buffer, 0, map.data, map.size);
5560
5561     gst_buffer_copy_into (new_buffer, buffer, GST_BUFFER_COPY_METADATA, 0, -1);
5562     GST_DEBUG_OBJECT (demux,
5563         "We want output aligned on %" G_GSIZE_FORMAT ", reallocated",
5564         alignment);
5565
5566     gst_buffer_unmap (buffer, &map);
5567     gst_buffer_unref (buffer);
5568
5569     return new_buffer;
5570   }
5571
5572   gst_buffer_unmap (buffer, &map);
5573   return buffer;
5574 }
5575
5576 static guint8 *
5577 convert_to_s334_1a (const guint8 * ccpair, guint8 ccpair_size, guint field,
5578     gsize * res)
5579 {
5580   guint8 *storage;
5581   gsize i;
5582
5583   /* We are converting from pairs to triplets */
5584   *res = ccpair_size / 2 * 3;
5585   storage = g_malloc (*res);
5586   for (i = 0; i * 2 < ccpair_size; i += 1) {
5587     /* FIXME: Use line offset 0 as we simply can't know here */
5588     if (field == 1)
5589       storage[i * 3] = 0x80 | 0x00;
5590     else
5591       storage[i * 3] = 0x00 | 0x00;
5592     storage[i * 3 + 1] = ccpair[i * 2];
5593     storage[i * 3 + 2] = ccpair[i * 2 + 1];
5594   }
5595
5596   return storage;
5597 }
5598
5599 static guint8 *
5600 extract_cc_from_data (QtDemuxStream * stream, const guint8 * data, gsize size,
5601     gsize * cclen)
5602 {
5603   guint8 *res = NULL;
5604   guint32 atom_length, fourcc;
5605   QtDemuxStreamStsdEntry *stsd_entry;
5606
5607   GST_MEMDUMP ("caption atom", data, size);
5608
5609   /* There might be multiple atoms */
5610
5611   *cclen = 0;
5612   if (size < 8)
5613     goto invalid_cdat;
5614   atom_length = QT_UINT32 (data);
5615   fourcc = QT_FOURCC (data + 4);
5616   if (G_UNLIKELY (atom_length > size || atom_length == 8))
5617     goto invalid_cdat;
5618
5619   GST_DEBUG_OBJECT (stream->pad, "here");
5620
5621   /* Check if we have something compatible */
5622   stsd_entry = CUR_STREAM (stream);
5623   switch (stsd_entry->fourcc) {
5624     case FOURCC_c608:{
5625       guint8 *cdat = NULL, *cdt2 = NULL;
5626       gsize cdat_size = 0, cdt2_size = 0;
5627       /* Should be cdat or cdt2 */
5628       if (fourcc != FOURCC_cdat && fourcc != FOURCC_cdt2) {
5629         GST_WARNING_OBJECT (stream->pad,
5630             "Unknown data atom (%" GST_FOURCC_FORMAT ") for CEA608",
5631             GST_FOURCC_ARGS (fourcc));
5632         goto invalid_cdat;
5633       }
5634
5635       /* Convert to S334-1 Annex A byte triplet */
5636       if (fourcc == FOURCC_cdat)
5637         cdat = convert_to_s334_1a (data + 8, atom_length - 8, 1, &cdat_size);
5638       else
5639         cdt2 = convert_to_s334_1a (data + 8, atom_length - 8, 2, &cdt2_size);
5640       GST_DEBUG_OBJECT (stream->pad, "size:%" G_GSIZE_FORMAT " atom_length:%u",
5641           size, atom_length);
5642
5643       /* Check for another atom ? */
5644       if (size > atom_length + 8) {
5645         guint32 new_atom_length = QT_UINT32 (data + atom_length);
5646         if (size >= atom_length + new_atom_length) {
5647           fourcc = QT_FOURCC (data + atom_length + 4);
5648           if (fourcc == FOURCC_cdat) {
5649             if (cdat == NULL)
5650               cdat =
5651                   convert_to_s334_1a (data + atom_length + 8,
5652                   new_atom_length - 8, 1, &cdat_size);
5653             else
5654               GST_WARNING_OBJECT (stream->pad,
5655                   "Got multiple [cdat] atoms in a c608 sample. This is unsupported for now. Please file a bug");
5656           } else {
5657             if (cdt2 == NULL)
5658               cdt2 =
5659                   convert_to_s334_1a (data + atom_length + 8,
5660                   new_atom_length - 8, 2, &cdt2_size);
5661             else
5662               GST_WARNING_OBJECT (stream->pad,
5663                   "Got multiple [cdt2] atoms in a c608 sample. This is unsupported for now. Please file a bug");
5664           }
5665         }
5666       }
5667
5668       *cclen = cdat_size + cdt2_size;
5669       res = g_malloc (*cclen);
5670       if (cdat_size)
5671         memcpy (res, cdat, cdat_size);
5672       if (cdt2_size)
5673         memcpy (res + cdat_size, cdt2, cdt2_size);
5674       g_free (cdat);
5675       g_free (cdt2);
5676     }
5677       break;
5678     case FOURCC_c708:
5679       if (fourcc != FOURCC_ccdp) {
5680         GST_WARNING_OBJECT (stream->pad,
5681             "Unknown data atom (%" GST_FOURCC_FORMAT ") for CEA708",
5682             GST_FOURCC_ARGS (fourcc));
5683         goto invalid_cdat;
5684       }
5685       *cclen = atom_length - 8;
5686       res = g_memdup2 (data + 8, *cclen);
5687       break;
5688     default:
5689       /* Keep this here in case other closed caption formats are added */
5690       g_assert_not_reached ();
5691       break;
5692   }
5693
5694   GST_MEMDUMP ("Output", res, *cclen);
5695   return res;
5696
5697   /* Errors */
5698 invalid_cdat:
5699   GST_WARNING ("[cdat] atom is too small or invalid");
5700   return NULL;
5701 }
5702
5703 /* Handle Closed Caption sample buffers.
5704  * The input buffer metadata must be writable,
5705  * but time/duration etc not yet set and need not be preserved */
5706 static GstBuffer *
5707 gst_qtdemux_process_buffer_clcp (GstQTDemux * qtdemux, QtDemuxStream * stream,
5708     GstBuffer * buf)
5709 {
5710   GstBuffer *outbuf = NULL;
5711   GstMapInfo map;
5712   guint8 *cc;
5713   gsize cclen = 0;
5714
5715   gst_buffer_map (buf, &map, GST_MAP_READ);
5716
5717   /* empty buffer is sent to terminate previous subtitle */
5718   if (map.size <= 2) {
5719     gst_buffer_unmap (buf, &map);
5720     gst_buffer_unref (buf);
5721     return NULL;
5722   }
5723
5724   /* For closed caption, we need to extract the information from the
5725    * [cdat],[cdt2] or [ccdp] atom */
5726   cc = extract_cc_from_data (stream, map.data, map.size, &cclen);
5727   gst_buffer_unmap (buf, &map);
5728   if (cc) {
5729     outbuf = _gst_buffer_new_wrapped (cc, cclen, g_free);
5730     gst_buffer_copy_into (outbuf, buf, GST_BUFFER_COPY_METADATA, 0, -1);
5731   } else {
5732     /* Conversion failed or there's nothing */
5733   }
5734   gst_buffer_unref (buf);
5735
5736   return outbuf;
5737 }
5738
5739 /* DVD subpicture specific sample handling.
5740  * the input buffer metadata must be writable,
5741  * but time/duration etc not yet set and need not be preserved */
5742 static GstBuffer *
5743 gst_qtdemux_process_buffer_dvd (GstQTDemux * qtdemux, QtDemuxStream * stream,
5744     GstBuffer * buf)
5745 {
5746   /* send a one time dvd clut event */
5747   if (stream->pending_event && stream->pad)
5748     gst_pad_push_event (stream->pad, stream->pending_event);
5749   stream->pending_event = NULL;
5750
5751   /* empty buffer is sent to terminate previous subtitle */
5752   if (gst_buffer_get_size (buf) <= 2) {
5753     gst_buffer_unref (buf);
5754     return NULL;
5755   }
5756
5757   /* That's all the processing needed for subpictures */
5758   return buf;
5759 }
5760
5761 /* Timed text formats
5762  * the input buffer metadata must be writable,
5763  * but time/duration etc not yet set and need not be preserved */
5764 static GstBuffer *
5765 gst_qtdemux_process_buffer_text (GstQTDemux * qtdemux, QtDemuxStream * stream,
5766     GstBuffer * buf)
5767 {
5768   GstBuffer *outbuf = NULL;
5769   GstMapInfo map;
5770   guint nsize = 0;
5771   gchar *str;
5772
5773   /* not many cases for now */
5774   if (G_UNLIKELY (stream->subtype != FOURCC_text &&
5775           stream->subtype != FOURCC_sbtl)) {
5776     return buf;
5777   }
5778
5779   gst_buffer_map (buf, &map, GST_MAP_READ);
5780
5781   /* empty buffer is sent to terminate previous subtitle */
5782   if (map.size <= 2) {
5783     gst_buffer_unmap (buf, &map);
5784     gst_buffer_unref (buf);
5785     return NULL;
5786   }
5787
5788   nsize = GST_READ_UINT16_BE (map.data);
5789   nsize = MIN (nsize, map.size - 2);
5790
5791   GST_LOG_OBJECT (qtdemux, "3GPP timed text subtitle: %d/%" G_GSIZE_FORMAT "",
5792       nsize, map.size);
5793
5794   /* takes care of UTF-8 validation or UTF-16 recognition,
5795    * no other encoding expected */
5796   str = gst_tag_freeform_string_to_utf8 ((gchar *) map.data + 2, nsize, NULL);
5797   gst_buffer_unmap (buf, &map);
5798
5799   if (str) {
5800     outbuf = _gst_buffer_new_wrapped (str, strlen (str), g_free);
5801     gst_buffer_copy_into (outbuf, buf, GST_BUFFER_COPY_METADATA, 0, -1);
5802   } else {
5803     /* this should not really happen unless the subtitle is corrupted */
5804   }
5805   gst_buffer_unref (buf);
5806
5807   /* FIXME ? convert optional subsequent style info to markup */
5808
5809   return outbuf;
5810 }
5811
5812 /* WebVTT sample handling according to 14496-30 */
5813 static GstBuffer *
5814 gst_qtdemux_process_buffer_wvtt (GstQTDemux * qtdemux, QtDemuxStream * stream,
5815     GstBuffer * buf)
5816 {
5817   GstBuffer *outbuf = NULL;
5818   GstMapInfo map;
5819
5820   if (!gst_buffer_map (buf, &map, GST_MAP_READ)) {
5821     g_assert_not_reached ();    /* The buffer must be mappable */
5822   }
5823
5824   if (qtdemux_webvtt_is_empty (qtdemux, map.data, map.size)) {
5825     GstEvent *gap = NULL;
5826     /* Push a gap event */
5827     stream->segment.position = GST_BUFFER_PTS (buf);
5828     gap =
5829         gst_event_new_gap (stream->segment.position, GST_BUFFER_DURATION (buf));
5830     gst_pad_push_event (stream->pad, gap);
5831
5832     if (GST_BUFFER_DURATION_IS_VALID (buf))
5833       stream->segment.position += GST_BUFFER_DURATION (buf);
5834   } else {
5835     outbuf =
5836         qtdemux_webvtt_decode (qtdemux, GST_BUFFER_PTS (buf),
5837         GST_BUFFER_DURATION (buf), map.data, map.size);
5838     gst_buffer_copy_into (outbuf, buf, GST_BUFFER_COPY_METADATA, 0, -1);
5839   }
5840
5841   gst_buffer_unmap (buf, &map);
5842   gst_buffer_unref (buf);
5843
5844   return outbuf;
5845 }
5846
5847 static GstFlowReturn
5848 gst_qtdemux_push_buffer (GstQTDemux * qtdemux, QtDemuxStream * stream,
5849     GstBuffer * buf)
5850 {
5851   GstFlowReturn ret = GST_FLOW_OK;
5852   GstClockTime pts, duration;
5853
5854   if (stream->need_clip)
5855     buf = gst_qtdemux_clip_buffer (qtdemux, stream, buf);
5856
5857   if (G_UNLIKELY (buf == NULL))
5858     goto exit;
5859
5860   if (G_UNLIKELY (stream->discont)) {
5861     GST_LOG_OBJECT (qtdemux, "marking discont buffer");
5862     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
5863     stream->discont = FALSE;
5864   } else {
5865     GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DISCONT);
5866   }
5867
5868   GST_LOG_OBJECT (qtdemux,
5869       "Pushing buffer with dts %" GST_TIME_FORMAT ", pts %" GST_TIME_FORMAT
5870       ", duration %" GST_TIME_FORMAT " on pad %s",
5871       GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
5872       GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
5873       GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_PAD_NAME (stream->pad));
5874
5875   if (stream->protected && stream->protection_scheme_type == FOURCC_aavd) {
5876     GstStructure *crypto_info;
5877     QtDemuxAavdEncryptionInfo *info =
5878         (QtDemuxAavdEncryptionInfo *) stream->protection_scheme_info;
5879
5880     crypto_info = gst_structure_copy (info->default_properties);
5881     if (!crypto_info || !gst_buffer_add_protection_meta (buf, crypto_info))
5882       GST_ERROR_OBJECT (qtdemux, "failed to attach aavd metadata to buffer");
5883   }
5884
5885   if (stream->protected && (stream->protection_scheme_type == FOURCC_cenc
5886           || stream->protection_scheme_type == FOURCC_cbcs)) {
5887     GstStructure *crypto_info;
5888     QtDemuxCencSampleSetInfo *info =
5889         (QtDemuxCencSampleSetInfo *) stream->protection_scheme_info;
5890     gint index;
5891     GstEvent *event;
5892
5893     while ((event = g_queue_pop_head (&stream->protection_scheme_event_queue))) {
5894       GST_TRACE_OBJECT (stream->pad, "pushing protection event: %"
5895           GST_PTR_FORMAT, event);
5896       gst_pad_push_event (stream->pad, event);
5897     }
5898
5899     if (info->crypto_info == NULL) {
5900       if (stream->protection_scheme_type == FOURCC_cbcs) {
5901         crypto_info = qtdemux_get_cenc_sample_properties (qtdemux, stream, 0);
5902         if (!crypto_info || !gst_buffer_add_protection_meta (buf, crypto_info)) {
5903           GST_ERROR_OBJECT (qtdemux,
5904               "failed to attach cbcs metadata to buffer");
5905           qtdemux_gst_structure_free (crypto_info);
5906         } else {
5907           GST_TRACE_OBJECT (qtdemux, "added cbcs protection metadata");
5908         }
5909       } else {
5910         GST_DEBUG_OBJECT (qtdemux,
5911             "cenc metadata hasn't been parsed yet, pushing buffer as if it wasn't encrypted");
5912       }
5913     } else {
5914       /* The end of the crypto_info array matches our n_samples position,
5915        * so count backward from there */
5916       index = stream->sample_index - stream->n_samples + info->crypto_info->len;
5917       if (G_LIKELY (index >= 0 && index < info->crypto_info->len)) {
5918         /* steal structure from array */
5919         crypto_info = g_ptr_array_index (info->crypto_info, index);
5920         g_ptr_array_index (info->crypto_info, index) = NULL;
5921         GST_LOG_OBJECT (qtdemux, "attaching cenc metadata [%u/%u]", index,
5922             info->crypto_info->len);
5923         if (!crypto_info || !gst_buffer_add_protection_meta (buf, crypto_info))
5924           GST_ERROR_OBJECT (qtdemux,
5925               "failed to attach cenc metadata to buffer");
5926       } else {
5927         GST_INFO_OBJECT (qtdemux, "No crypto info with index %d and sample %d",
5928             index, stream->sample_index);
5929       }
5930     }
5931   }
5932
5933   if (stream->alignment > 1)
5934     buf = gst_qtdemux_align_buffer (qtdemux, buf, stream->alignment);
5935
5936   pts = GST_BUFFER_PTS (buf);
5937   duration = GST_BUFFER_DURATION (buf);
5938
5939   ret = gst_pad_push (stream->pad, buf);
5940
5941   if (GST_CLOCK_TIME_IS_VALID (pts) && GST_CLOCK_TIME_IS_VALID (duration)) {
5942     /* mark position in stream, we'll need this to know when to send GAP event */
5943     stream->segment.position = pts + duration;
5944   }
5945
5946 exit:
5947
5948   return ret;
5949 }
5950
5951 static GstFlowReturn
5952 gst_qtdemux_split_and_push_buffer (GstQTDemux * qtdemux, QtDemuxStream * stream,
5953     GstBuffer * buf)
5954 {
5955   GstFlowReturn ret = GST_FLOW_OK;
5956
5957   if (stream->subtype == FOURCC_clcp
5958       && CUR_STREAM (stream)->fourcc == FOURCC_c608 && stream->need_split) {
5959     GstMapInfo map;
5960     guint n_output_buffers, n_field1 = 0, n_field2 = 0;
5961     guint n_triplets, i;
5962     guint field1_off = 0, field2_off = 0;
5963
5964     /* We have to split CEA608 buffers so that each outgoing buffer contains
5965      * one byte pair per field according to the framerate of the video track.
5966      *
5967      * If there is only a single byte pair per field we don't have to do
5968      * anything
5969      */
5970
5971     gst_buffer_map (buf, &map, GST_MAP_READ);
5972
5973     n_triplets = map.size / 3;
5974     for (i = 0; i < n_triplets; i++) {
5975       if (map.data[3 * i] & 0x80)
5976         n_field1++;
5977       else
5978         n_field2++;
5979     }
5980
5981     g_assert (n_field1 || n_field2);
5982
5983     /* If there's more than 1 frame we have to split, otherwise we can just
5984      * pass through */
5985     if (n_field1 > 1 || n_field2 > 1) {
5986       n_output_buffers =
5987           gst_util_uint64_scale (GST_BUFFER_DURATION (buf),
5988           CUR_STREAM (stream)->fps_n, GST_SECOND * CUR_STREAM (stream)->fps_d);
5989
5990       for (i = 0; i < n_output_buffers; i++) {
5991         GstBuffer *outbuf =
5992             gst_buffer_new_and_alloc ((n_field1 ? 3 : 0) + (n_field2 ? 3 : 0));
5993         GstMapInfo outmap;
5994         guint8 *outptr;
5995
5996         gst_buffer_map (outbuf, &outmap, GST_MAP_WRITE);
5997         outptr = outmap.data;
5998
5999         if (n_field1) {
6000           gboolean found = FALSE;
6001
6002           while (map.data + field1_off < map.data + map.size) {
6003             if (map.data[field1_off] & 0x80) {
6004               memcpy (outptr, &map.data[field1_off], 3);
6005               field1_off += 3;
6006               found = TRUE;
6007               break;
6008             }
6009             field1_off += 3;
6010           }
6011
6012           if (!found) {
6013             const guint8 empty[] = { 0x80, 0x80, 0x80 };
6014
6015             memcpy (outptr, empty, 3);
6016           }
6017
6018           outptr += 3;
6019         }
6020
6021         if (n_field2) {
6022           gboolean found = FALSE;
6023
6024           while (map.data + field2_off < map.data + map.size) {
6025             if ((map.data[field2_off] & 0x80) == 0) {
6026               memcpy (outptr, &map.data[field2_off], 3);
6027               field2_off += 3;
6028               found = TRUE;
6029               break;
6030             }
6031             field2_off += 3;
6032           }
6033
6034           if (!found) {
6035             const guint8 empty[] = { 0x00, 0x80, 0x80 };
6036
6037             memcpy (outptr, empty, 3);
6038           }
6039
6040           outptr += 3;
6041         }
6042
6043         gst_buffer_unmap (outbuf, &outmap);
6044
6045         GST_BUFFER_PTS (outbuf) =
6046             GST_BUFFER_PTS (buf) + gst_util_uint64_scale (i,
6047             GST_SECOND * CUR_STREAM (stream)->fps_d,
6048             CUR_STREAM (stream)->fps_n);
6049         GST_BUFFER_DURATION (outbuf) =
6050             gst_util_uint64_scale (GST_SECOND, CUR_STREAM (stream)->fps_d,
6051             CUR_STREAM (stream)->fps_n);
6052         GST_BUFFER_OFFSET (outbuf) = -1;
6053         GST_BUFFER_OFFSET_END (outbuf) = -1;
6054
6055         ret = gst_qtdemux_push_buffer (qtdemux, stream, outbuf);
6056
6057         if (ret != GST_FLOW_OK && ret != GST_FLOW_NOT_LINKED)
6058           break;
6059       }
6060       gst_buffer_unmap (buf, &map);
6061       gst_buffer_unref (buf);
6062     } else {
6063       gst_buffer_unmap (buf, &map);
6064       ret = gst_qtdemux_push_buffer (qtdemux, stream, buf);
6065     }
6066   } else {
6067     ret = gst_qtdemux_push_buffer (qtdemux, stream, buf);
6068   }
6069
6070   return ret;
6071 }
6072
6073 /* Sets a buffer's attributes properly and pushes it downstream.
6074  * Also checks for additional actions and custom processing that may
6075  * need to be done first.
6076  */
6077 static GstFlowReturn
6078 gst_qtdemux_decorate_and_push_buffer (GstQTDemux * qtdemux,
6079     QtDemuxStream * stream, GstBuffer * buf,
6080     GstClockTime dts, GstClockTime pts, GstClockTime duration,
6081     gboolean keyframe, GstClockTime position, guint64 byte_position)
6082 {
6083   GstFlowReturn ret = GST_FLOW_OK;
6084
6085   /* offset the timestamps according to the edit list */
6086
6087   if (G_UNLIKELY (CUR_STREAM (stream)->fourcc == FOURCC_rtsp)) {
6088     gchar *url;
6089     GstMapInfo map;
6090
6091     gst_buffer_map (buf, &map, GST_MAP_READ);
6092     url = g_strndup ((gchar *) map.data, map.size);
6093     gst_buffer_unmap (buf, &map);
6094     if (url != NULL && strlen (url) != 0) {
6095       /* we have RTSP redirect now */
6096       g_free (qtdemux->redirect_location);
6097       qtdemux->redirect_location = g_strdup (url);
6098       gst_element_post_message (GST_ELEMENT_CAST (qtdemux),
6099           gst_message_new_element (GST_OBJECT_CAST (qtdemux),
6100               gst_structure_new ("redirect",
6101                   "new-location", G_TYPE_STRING, url, NULL)));
6102     } else {
6103       GST_WARNING_OBJECT (qtdemux, "Redirect URI of stream is empty, not "
6104           "posting");
6105     }
6106     g_free (url);
6107   }
6108
6109   /* position reporting */
6110   if (qtdemux->segment.rate >= 0) {
6111     qtdemux->segment.position = position;
6112     gst_qtdemux_sync_streams (qtdemux);
6113   }
6114
6115   if (G_UNLIKELY (!stream->pad)) {
6116     GST_DEBUG_OBJECT (qtdemux, "No output pad for stream, ignoring");
6117     gst_buffer_unref (buf);
6118     goto exit;
6119   }
6120
6121   /* send out pending buffers */
6122   while (stream->buffers) {
6123     GstBuffer *buffer = (GstBuffer *) stream->buffers->data;
6124
6125     if (G_UNLIKELY (stream->discont)) {
6126       GST_LOG_OBJECT (qtdemux, "marking discont buffer");
6127       GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
6128       stream->discont = FALSE;
6129     } else {
6130       GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DISCONT);
6131     }
6132
6133     if (stream->alignment > 1)
6134       buffer = gst_qtdemux_align_buffer (qtdemux, buffer, stream->alignment);
6135     gst_pad_push (stream->pad, buffer);
6136
6137     stream->buffers = g_slist_delete_link (stream->buffers, stream->buffers);
6138   }
6139
6140   /* we're going to modify the metadata */
6141   buf = gst_buffer_make_writable (buf);
6142
6143   GST_BUFFER_DTS (buf) = dts;
6144   GST_BUFFER_PTS (buf) = pts;
6145   GST_BUFFER_DURATION (buf) = duration;
6146   GST_BUFFER_OFFSET (buf) = -1;
6147   GST_BUFFER_OFFSET_END (buf) = -1;
6148
6149   if (G_UNLIKELY (stream->process_func))
6150     buf = stream->process_func (qtdemux, stream, buf);
6151
6152   if (!buf) {
6153     goto exit;
6154   }
6155
6156   if (!keyframe) {
6157     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
6158     stream->on_keyframe = FALSE;
6159   } else {
6160     stream->on_keyframe = TRUE;
6161   }
6162
6163   if (G_UNLIKELY (CUR_STREAM (stream)->rgb8_palette))
6164     gst_buffer_append_memory (buf,
6165         gst_memory_ref (CUR_STREAM (stream)->rgb8_palette));
6166
6167   if (G_UNLIKELY (CUR_STREAM (stream)->padding)) {
6168     gst_buffer_resize (buf, CUR_STREAM (stream)->padding, -1);
6169   }
6170 #if 0
6171   if (G_UNLIKELY (qtdemux->element_index)) {
6172     GstClockTime stream_time;
6173
6174     stream_time =
6175         gst_segment_to_stream_time (&stream->segment, GST_FORMAT_TIME,
6176         timestamp);
6177     if (GST_CLOCK_TIME_IS_VALID (stream_time)) {
6178       GST_LOG_OBJECT (qtdemux,
6179           "adding association %" GST_TIME_FORMAT "-> %"
6180           G_GUINT64_FORMAT, GST_TIME_ARGS (stream_time), byte_position);
6181       gst_index_add_association (qtdemux->element_index,
6182           qtdemux->index_id,
6183           keyframe ? GST_ASSOCIATION_FLAG_KEY_UNIT :
6184           GST_ASSOCIATION_FLAG_DELTA_UNIT, GST_FORMAT_TIME, stream_time,
6185           GST_FORMAT_BYTES, byte_position, NULL);
6186     }
6187   }
6188 #endif
6189
6190   ret = gst_qtdemux_split_and_push_buffer (qtdemux, stream, buf);
6191
6192 exit:
6193   return ret;
6194 }
6195
6196 static const QtDemuxRandomAccessEntry *
6197 gst_qtdemux_stream_seek_fragment (GstQTDemux * qtdemux, QtDemuxStream * stream,
6198     GstClockTime pos, gboolean after)
6199 {
6200   QtDemuxRandomAccessEntry *entries = stream->ra_entries;
6201   guint n_entries = stream->n_ra_entries;
6202   guint i;
6203
6204   /* we assume the table is sorted */
6205   for (i = 0; i < n_entries; ++i) {
6206     if (entries[i].ts > pos)
6207       break;
6208   }
6209
6210   /* FIXME: maybe save first moof_offset somewhere instead, but for now it's
6211    * probably okay to assume that the index lists the very first fragment */
6212   if (i == 0)
6213     return &entries[0];
6214
6215   if (after)
6216     return &entries[i];
6217   else
6218     return &entries[i - 1];
6219 }
6220
6221 static gboolean
6222 gst_qtdemux_do_fragmented_seek (GstQTDemux * qtdemux)
6223 {
6224   const QtDemuxRandomAccessEntry *best_entry = NULL;
6225   gint i;
6226
6227   GST_OBJECT_LOCK (qtdemux);
6228
6229   g_assert (QTDEMUX_N_STREAMS (qtdemux) > 0);
6230
6231   /* first see if we can determine where to go to using mfra,
6232    * before we start clearing things */
6233   for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
6234     const QtDemuxRandomAccessEntry *entry;
6235     QtDemuxStream *stream;
6236     gboolean is_audio_or_video;
6237
6238     stream = QTDEMUX_NTH_STREAM (qtdemux, i);
6239
6240     if (stream->ra_entries == NULL)
6241       continue;
6242
6243     if (stream->subtype == FOURCC_vide || stream->subtype == FOURCC_soun)
6244       is_audio_or_video = TRUE;
6245     else
6246       is_audio_or_video = FALSE;
6247
6248     entry =
6249         gst_qtdemux_stream_seek_fragment (qtdemux, stream,
6250         stream->time_position, !is_audio_or_video);
6251
6252     GST_INFO_OBJECT (stream->pad, "%" GST_TIME_FORMAT " at offset "
6253         "%" G_GUINT64_FORMAT, GST_TIME_ARGS (entry->ts), entry->moof_offset);
6254
6255     stream->pending_seek = entry;
6256
6257     /* decide position to jump to just based on audio/video tracks, not subs */
6258     if (!is_audio_or_video)
6259       continue;
6260
6261     if (best_entry == NULL || entry->moof_offset < best_entry->moof_offset)
6262       best_entry = entry;
6263   }
6264
6265   /* no luck, will handle seek otherwise */
6266   if (best_entry == NULL) {
6267     GST_OBJECT_UNLOCK (qtdemux);
6268     return FALSE;
6269   }
6270
6271   /* ok, now we can prepare for processing as of located moof */
6272   for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
6273     QtDemuxStream *stream;
6274
6275     stream = QTDEMUX_NTH_STREAM (qtdemux, i);
6276
6277     g_free (stream->samples);
6278     stream->samples = NULL;
6279     stream->n_samples = 0;
6280     stream->stbl_index = -1;    /* no samples have yet been parsed */
6281     stream->sample_index = -1;
6282
6283     if (stream->protection_scheme_info) {
6284       /* Clear out any old cenc crypto info entries as we'll move to a new moof */
6285       if (stream->protection_scheme_type == FOURCC_cenc
6286           || stream->protection_scheme_type == FOURCC_cbcs) {
6287         QtDemuxCencSampleSetInfo *info =
6288             (QtDemuxCencSampleSetInfo *) stream->protection_scheme_info;
6289         if (info->crypto_info) {
6290           g_ptr_array_free (info->crypto_info, TRUE);
6291           info->crypto_info = NULL;
6292         }
6293       }
6294     }
6295   }
6296
6297   GST_INFO_OBJECT (qtdemux, "seek to %" GST_TIME_FORMAT ", best fragment "
6298       "moof offset: %" G_GUINT64_FORMAT ", ts %" GST_TIME_FORMAT,
6299       GST_TIME_ARGS (QTDEMUX_NTH_STREAM (qtdemux, 0)->time_position),
6300       best_entry->moof_offset, GST_TIME_ARGS (best_entry->ts));
6301
6302   qtdemux->moof_offset = best_entry->moof_offset;
6303
6304   qtdemux_add_fragmented_samples (qtdemux);
6305
6306   GST_OBJECT_UNLOCK (qtdemux);
6307   return TRUE;
6308 }
6309
6310 static GstFlowReturn
6311 gst_qtdemux_loop_state_movie (GstQTDemux * qtdemux)
6312 {
6313   GstFlowReturn ret = GST_FLOW_OK;
6314   GstBuffer *buf = NULL;
6315   QtDemuxStream *stream, *target_stream = NULL;
6316   GstClockTime min_time;
6317   guint64 offset = 0;
6318   GstClockTime dts = GST_CLOCK_TIME_NONE;
6319   GstClockTime pts = GST_CLOCK_TIME_NONE;
6320   GstClockTime duration = 0;
6321   gboolean keyframe = FALSE;
6322   guint sample_size = 0;
6323   guint num_samples = 1;
6324   gboolean empty = 0;
6325   guint size;
6326   gint i;
6327
6328   if (qtdemux->fragmented_seek_pending) {
6329     GST_INFO_OBJECT (qtdemux, "pending fragmented seek");
6330     if (gst_qtdemux_do_fragmented_seek (qtdemux)) {
6331       GST_INFO_OBJECT (qtdemux, "fragmented seek done!");
6332       qtdemux->fragmented_seek_pending = FALSE;
6333     } else {
6334       GST_INFO_OBJECT (qtdemux, "fragmented seek still pending");
6335     }
6336   }
6337
6338   /* Figure out the next stream sample to output, min_time is expressed in
6339    * global time and runs over the edit list segments. */
6340   min_time = G_MAXUINT64;
6341   for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
6342     GstClockTime position;
6343
6344     stream = QTDEMUX_NTH_STREAM (qtdemux, i);
6345     position = stream->time_position;
6346
6347     if (!GST_CLOCK_TIME_IS_VALID (position))
6348       continue;
6349
6350     if (stream->segment_index != -1) {
6351       QtDemuxSegment *segment = &stream->segments[stream->segment_index];
6352       position += segment->media_start;
6353     }
6354
6355     /* position of -1 is EOS */
6356     if (position < min_time) {
6357       min_time = position;
6358       target_stream = stream;
6359     }
6360   }
6361   /* all are EOS */
6362   if (G_UNLIKELY (target_stream == NULL)) {
6363     GST_DEBUG_OBJECT (qtdemux, "all streams are EOS");
6364     goto eos;
6365   }
6366
6367   /* check for segment end */
6368   if (G_UNLIKELY (qtdemux->segment.stop != -1
6369           && qtdemux->segment.rate >= 0
6370           && qtdemux->segment.stop <= min_time && target_stream->on_keyframe)) {
6371     GST_DEBUG_OBJECT (qtdemux, "we reached the end of our segment.");
6372     target_stream->time_position = GST_CLOCK_TIME_NONE;
6373     goto eos_stream;
6374   }
6375
6376   /* gap events for subtitle streams */
6377   for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
6378     stream = QTDEMUX_NTH_STREAM (qtdemux, i);
6379     if (stream->pad) {
6380       GstClockTime gap_threshold;
6381
6382       /* Only send gap events on non-subtitle streams if lagging way behind. */
6383       if (stream->subtype == FOURCC_subp
6384           || stream->subtype == FOURCC_text || stream->subtype == FOURCC_sbtl ||
6385           stream->subtype == FOURCC_wvtt)
6386         gap_threshold = 1 * GST_SECOND;
6387       else
6388         gap_threshold = 3 * GST_SECOND;
6389
6390       /* send gap events until the stream catches up */
6391       /* gaps can only be sent after segment is activated (segment.stop is no longer -1) */
6392       while (GST_CLOCK_TIME_IS_VALID (stream->segment.stop) &&
6393           GST_CLOCK_TIME_IS_VALID (stream->segment.position) &&
6394           stream->segment.position + gap_threshold < min_time) {
6395         GstEvent *gap =
6396             gst_event_new_gap (stream->segment.position, gap_threshold);
6397         gst_pad_push_event (stream->pad, gap);
6398         stream->segment.position += gap_threshold;
6399       }
6400     }
6401   }
6402
6403   stream = target_stream;
6404   /* fetch info for the current sample of this stream */
6405   if (G_UNLIKELY (!gst_qtdemux_prepare_current_sample (qtdemux, stream, &empty,
6406               &offset, &sample_size, &dts, &pts, &duration, &keyframe)))
6407     goto eos_stream;
6408
6409   gst_qtdemux_stream_check_and_change_stsd_index (qtdemux, stream);
6410   if (stream->new_caps) {
6411     gst_qtdemux_configure_stream (qtdemux, stream);
6412     qtdemux_do_allocation (stream, qtdemux);
6413   }
6414
6415   /* If we're doing a keyframe-only trickmode, only push keyframes on video streams */
6416   if (G_UNLIKELY (qtdemux->segment.
6417           flags & GST_SEGMENT_FLAG_TRICKMODE_KEY_UNITS)) {
6418     if (stream->subtype == FOURCC_vide) {
6419       if (!keyframe) {
6420         GST_LOG_OBJECT (qtdemux, "Skipping non-keyframe on track-id %u",
6421             stream->track_id);
6422         goto next;
6423       } else if (qtdemux->trickmode_interval > 0) {
6424         GstClockTimeDiff interval;
6425
6426         if (qtdemux->segment.rate > 0)
6427           interval = stream->time_position - stream->last_keyframe_dts;
6428         else
6429           interval = stream->last_keyframe_dts - stream->time_position;
6430
6431         if (GST_CLOCK_TIME_IS_VALID (stream->last_keyframe_dts)
6432             && interval < qtdemux->trickmode_interval) {
6433           GST_LOG_OBJECT (qtdemux,
6434               "Skipping keyframe within interval on track-id %u",
6435               stream->track_id);
6436           goto next;
6437         } else {
6438           stream->last_keyframe_dts = stream->time_position;
6439         }
6440       }
6441     }
6442   }
6443
6444   GST_DEBUG_OBJECT (qtdemux,
6445       "pushing from track-id %u, empty %d offset %" G_GUINT64_FORMAT
6446       ", size %d, dts=%" GST_TIME_FORMAT ", pts=%" GST_TIME_FORMAT
6447       ", duration %" GST_TIME_FORMAT, stream->track_id, empty, offset,
6448       sample_size, GST_TIME_ARGS (dts), GST_TIME_ARGS (pts),
6449       GST_TIME_ARGS (duration));
6450
6451   if (G_UNLIKELY (empty)) {
6452     /* empty segment, push a gap if there's a second or more
6453      * difference and move to the next one */
6454     if ((pts + duration - stream->segment.position) >= GST_SECOND)
6455       gst_pad_push_event (stream->pad, gst_event_new_gap (pts, duration));
6456     stream->segment.position = pts + duration;
6457     goto next;
6458   }
6459
6460   /* hmm, empty sample, skip and move to next sample */
6461   if (G_UNLIKELY (sample_size <= 0))
6462     goto next;
6463
6464   /* last pushed sample was out of boundary, goto next sample */
6465   if (G_UNLIKELY (GST_PAD_LAST_FLOW_RETURN (stream->pad) == GST_FLOW_EOS))
6466     goto next;
6467
6468   if (stream->max_buffer_size != 0 && sample_size > stream->max_buffer_size) {
6469     GST_DEBUG_OBJECT (qtdemux,
6470         "size %d larger than stream max_buffer_size %d, trimming",
6471         sample_size, stream->max_buffer_size);
6472     size =
6473         MIN (sample_size - stream->offset_in_sample, stream->max_buffer_size);
6474   } else if (stream->min_buffer_size != 0 && stream->offset_in_sample == 0
6475       && sample_size < stream->min_buffer_size) {
6476     guint start_sample_index = stream->sample_index;
6477     guint accumulated_size = sample_size;
6478     guint64 expected_next_offset = offset + sample_size;
6479
6480     GST_DEBUG_OBJECT (qtdemux,
6481         "size %d smaller than stream min_buffer_size %d, combining with the next",
6482         sample_size, stream->min_buffer_size);
6483
6484     while (stream->sample_index < stream->to_sample
6485         && stream->sample_index + 1 < stream->n_samples) {
6486       const QtDemuxSample *next_sample;
6487
6488       /* Increment temporarily */
6489       stream->sample_index++;
6490
6491       /* Failed to parse sample so let's go back to the previous one that was
6492        * still successful */
6493       if (!qtdemux_parse_samples (qtdemux, stream, stream->sample_index)) {
6494         stream->sample_index--;
6495         break;
6496       }
6497
6498       next_sample = &stream->samples[stream->sample_index];
6499
6500       /* Not contiguous with the previous sample so let's go back to the
6501        * previous one that was still successful */
6502       if (next_sample->offset != expected_next_offset) {
6503         stream->sample_index--;
6504         break;
6505       }
6506
6507       accumulated_size += next_sample->size;
6508       expected_next_offset += next_sample->size;
6509       if (accumulated_size >= stream->min_buffer_size)
6510         break;
6511     }
6512
6513     num_samples = stream->sample_index + 1 - start_sample_index;
6514     stream->sample_index = start_sample_index;
6515     GST_DEBUG_OBJECT (qtdemux, "Pulling %u samples of size %u at once",
6516         num_samples, accumulated_size);
6517     size = accumulated_size;
6518   } else {
6519     size = sample_size;
6520   }
6521
6522   if (qtdemux->cenc_aux_info_offset > 0) {
6523     GstMapInfo map;
6524     GstByteReader br;
6525     GstBuffer *aux_info = NULL;
6526
6527     /* pull the data stored before the sample */
6528     ret =
6529         gst_qtdemux_pull_atom (qtdemux, qtdemux->offset,
6530         offset + stream->offset_in_sample - qtdemux->offset, &aux_info);
6531     if (G_UNLIKELY (ret != GST_FLOW_OK))
6532       goto beach;
6533     gst_buffer_map (aux_info, &map, GST_MAP_READ);
6534     GST_DEBUG_OBJECT (qtdemux, "parsing cenc auxiliary info");
6535     gst_byte_reader_init (&br, map.data + 8, map.size);
6536     if (!qtdemux_parse_cenc_aux_info (qtdemux, stream, &br,
6537             qtdemux->cenc_aux_info_sizes, qtdemux->cenc_aux_sample_count)) {
6538       GST_ERROR_OBJECT (qtdemux, "failed to parse cenc auxiliary info");
6539       gst_buffer_unmap (aux_info, &map);
6540       gst_buffer_unref (aux_info);
6541       ret = GST_FLOW_ERROR;
6542       goto beach;
6543     }
6544     gst_buffer_unmap (aux_info, &map);
6545     gst_buffer_unref (aux_info);
6546   }
6547
6548   GST_LOG_OBJECT (qtdemux, "reading %d bytes @ %" G_GUINT64_FORMAT, size,
6549       offset);
6550
6551   if (stream->use_allocator) {
6552     /* if we have a per-stream allocator, use it */
6553     buf = gst_buffer_new_allocate (stream->allocator, size, &stream->params);
6554   }
6555
6556   ret = gst_qtdemux_pull_atom (qtdemux, offset + stream->offset_in_sample,
6557       size, &buf);
6558   if (G_UNLIKELY (ret != GST_FLOW_OK))
6559     goto beach;
6560
6561   /* Update for both splitting and combining of samples */
6562   if (size != sample_size) {
6563     pts += gst_util_uint64_scale_int (GST_SECOND,
6564         stream->offset_in_sample / CUR_STREAM (stream)->bytes_per_frame,
6565         stream->timescale);
6566     dts +=
6567         gst_util_uint64_scale_int (GST_SECOND,
6568         stream->offset_in_sample / CUR_STREAM (stream)->bytes_per_frame,
6569         stream->timescale);
6570     duration =
6571         gst_util_uint64_scale_int (GST_SECOND,
6572         size / CUR_STREAM (stream)->bytes_per_frame, stream->timescale);
6573   }
6574
6575   ret = gst_qtdemux_decorate_and_push_buffer (qtdemux, stream, buf,
6576       dts, pts, duration, keyframe, min_time, offset);
6577
6578   if (size < sample_size) {
6579     QtDemuxSample *sample = &stream->samples[stream->sample_index];
6580     QtDemuxSegment *segment = &stream->segments[stream->segment_index];
6581
6582     GstClockTime time_position = QTSTREAMTIME_TO_GSTTIME (stream,
6583         sample->timestamp +
6584         stream->offset_in_sample / CUR_STREAM (stream)->bytes_per_frame);
6585     if (time_position >= segment->media_start) {
6586       /* inside the segment, update time_position, looks very familiar to
6587        * GStreamer segments, doesn't it? */
6588       stream->time_position = (time_position - segment->media_start) +
6589           segment->time;
6590     } else {
6591       /* not yet in segment, time does not yet increment. This means
6592        * that we are still prerolling keyframes to the decoder so it can
6593        * decode the first sample of the segment. */
6594       stream->time_position = segment->time;
6595     }
6596   } else if (size > sample_size) {
6597     /* Increase to the last sample we already pulled so that advancing
6598      * below brings us to the next sample we need to pull */
6599     stream->sample_index += num_samples - 1;
6600   }
6601
6602   /* combine flows */
6603   GST_OBJECT_LOCK (qtdemux);
6604   ret = gst_qtdemux_combine_flows (qtdemux, stream, ret);
6605   GST_OBJECT_UNLOCK (qtdemux);
6606   /* ignore unlinked, we will not push on the pad anymore and we will EOS when
6607    * we have no more data for the pad to push */
6608   if (ret == GST_FLOW_EOS)
6609     ret = GST_FLOW_OK;
6610
6611   stream->offset_in_sample += size;
6612   if (stream->offset_in_sample >= sample_size) {
6613     gst_qtdemux_advance_sample (qtdemux, stream);
6614   }
6615   goto beach;
6616
6617 next:
6618   gst_qtdemux_advance_sample (qtdemux, stream);
6619
6620 beach:
6621   return ret;
6622
6623   /* special cases */
6624 eos:
6625   {
6626     GST_DEBUG_OBJECT (qtdemux, "No samples left for any streams - EOS");
6627     ret = GST_FLOW_EOS;
6628     goto beach;
6629   }
6630 eos_stream:
6631   {
6632     GST_DEBUG_OBJECT (qtdemux, "No samples left for stream");
6633     /* EOS will be raised if all are EOS */
6634     ret = GST_FLOW_OK;
6635     goto beach;
6636   }
6637 }
6638
6639 static void
6640 gst_qtdemux_loop (GstPad * pad)
6641 {
6642   GstQTDemux *qtdemux;
6643   guint64 cur_offset;
6644   GstFlowReturn ret;
6645
6646   qtdemux = GST_QTDEMUX (gst_pad_get_parent (pad));
6647
6648   cur_offset = qtdemux->offset;
6649   GST_LOG_OBJECT (qtdemux, "loop at position %" G_GUINT64_FORMAT ", state %s",
6650       cur_offset, qt_demux_state_string (qtdemux->state));
6651
6652   switch (qtdemux->state) {
6653     case QTDEMUX_STATE_INITIAL:
6654     case QTDEMUX_STATE_HEADER:
6655       ret = gst_qtdemux_loop_state_header (qtdemux);
6656       break;
6657     case QTDEMUX_STATE_MOVIE:
6658       ret = gst_qtdemux_loop_state_movie (qtdemux);
6659       if (qtdemux->segment.rate < 0 && ret == GST_FLOW_EOS) {
6660         ret = gst_qtdemux_seek_to_previous_keyframe (qtdemux);
6661       }
6662       break;
6663     default:
6664       /* ouch */
6665       goto invalid_state;
6666   }
6667
6668   /* if something went wrong, pause */
6669   if (ret != GST_FLOW_OK)
6670     goto pause;
6671
6672 done:
6673   gst_object_unref (qtdemux);
6674   return;
6675
6676   /* ERRORS */
6677 invalid_state:
6678   {
6679     GST_ELEMENT_ERROR (qtdemux, STREAM, FAILED,
6680         (NULL), ("streaming stopped, invalid state"));
6681     gst_pad_pause_task (pad);
6682     gst_qtdemux_push_event (qtdemux, gst_event_new_eos ());
6683     goto done;
6684   }
6685 pause:
6686   {
6687     const gchar *reason = gst_flow_get_name (ret);
6688
6689     GST_LOG_OBJECT (qtdemux, "pausing task, reason %s", reason);
6690
6691     gst_pad_pause_task (pad);
6692
6693     /* fatal errors need special actions */
6694     /* check EOS */
6695     if (ret == GST_FLOW_EOS) {
6696       if (QTDEMUX_N_STREAMS (qtdemux) == 0) {
6697         /* we have no streams, post an error */
6698         gst_qtdemux_post_no_playable_stream_error (qtdemux);
6699       }
6700       if (qtdemux->segment.flags & GST_SEEK_FLAG_SEGMENT) {
6701         gint64 stop;
6702
6703         if ((stop = qtdemux->segment.stop) == -1)
6704           stop = qtdemux->segment.duration;
6705
6706         if (qtdemux->segment.rate >= 0) {
6707           GstMessage *message;
6708           GstEvent *event;
6709
6710           GST_LOG_OBJECT (qtdemux, "Sending segment done, at end of segment");
6711           message = gst_message_new_segment_done (GST_OBJECT_CAST (qtdemux),
6712               GST_FORMAT_TIME, stop);
6713           event = gst_event_new_segment_done (GST_FORMAT_TIME, stop);
6714           if (qtdemux->segment_seqnum != GST_SEQNUM_INVALID) {
6715             gst_message_set_seqnum (message, qtdemux->segment_seqnum);
6716             gst_event_set_seqnum (event, qtdemux->segment_seqnum);
6717           }
6718           gst_element_post_message (GST_ELEMENT_CAST (qtdemux), message);
6719           gst_qtdemux_push_event (qtdemux, event);
6720         } else {
6721           GstMessage *message;
6722           GstEvent *event;
6723
6724           /*  For Reverse Playback */
6725           GST_LOG_OBJECT (qtdemux, "Sending segment done, at start of segment");
6726           message = gst_message_new_segment_done (GST_OBJECT_CAST (qtdemux),
6727               GST_FORMAT_TIME, qtdemux->segment.start);
6728           event = gst_event_new_segment_done (GST_FORMAT_TIME,
6729               qtdemux->segment.start);
6730           if (qtdemux->segment_seqnum != GST_SEQNUM_INVALID) {
6731             gst_message_set_seqnum (message, qtdemux->segment_seqnum);
6732             gst_event_set_seqnum (event, qtdemux->segment_seqnum);
6733           }
6734           gst_element_post_message (GST_ELEMENT_CAST (qtdemux), message);
6735           gst_qtdemux_push_event (qtdemux, event);
6736         }
6737       } else {
6738         GstEvent *event;
6739
6740         GST_LOG_OBJECT (qtdemux, "Sending EOS at end of segment");
6741         event = gst_event_new_eos ();
6742         if (qtdemux->segment_seqnum != GST_SEQNUM_INVALID)
6743           gst_event_set_seqnum (event, qtdemux->segment_seqnum);
6744         gst_qtdemux_push_event (qtdemux, event);
6745       }
6746     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
6747       GST_ELEMENT_FLOW_ERROR (qtdemux, ret);
6748       gst_qtdemux_push_event (qtdemux, gst_event_new_eos ());
6749     }
6750     goto done;
6751   }
6752 }
6753
6754 /*
6755  * has_next_entry
6756  *
6757  * Returns if there are samples to be played.
6758  */
6759 static gboolean
6760 has_next_entry (GstQTDemux * demux)
6761 {
6762   QtDemuxStream *stream;
6763   gint i;
6764
6765   GST_DEBUG_OBJECT (demux, "Checking if there are samples not played yet");
6766
6767   for (i = 0; i < QTDEMUX_N_STREAMS (demux); i++) {
6768     stream = QTDEMUX_NTH_STREAM (demux, i);
6769
6770     if (stream->sample_index == -1) {
6771       stream->sample_index = 0;
6772       stream->offset_in_sample = 0;
6773     }
6774
6775     if (stream->sample_index >= stream->n_samples) {
6776       GST_LOG_OBJECT (demux, "track-id %u samples exhausted", stream->track_id);
6777       continue;
6778     }
6779     GST_DEBUG_OBJECT (demux, "Found a sample");
6780     return TRUE;
6781   }
6782
6783   GST_DEBUG_OBJECT (demux, "There wasn't any next sample");
6784   return FALSE;
6785 }
6786
6787 /*
6788  * next_entry_size
6789  *
6790  * Returns the size of the first entry at the current offset.
6791  * If -1, there are none (which means EOS or empty file).
6792  */
6793 static guint64
6794 next_entry_size (GstQTDemux * demux)
6795 {
6796   QtDemuxStream *stream, *target_stream = NULL;
6797   guint64 smalloffs = (guint64) - 1;
6798   QtDemuxSample *sample;
6799   gint i;
6800
6801   GST_LOG_OBJECT (demux, "Finding entry at offset %" G_GUINT64_FORMAT,
6802       demux->offset);
6803
6804   for (i = 0; i < QTDEMUX_N_STREAMS (demux); i++) {
6805     stream = QTDEMUX_NTH_STREAM (demux, i);
6806
6807     if (stream->sample_index == -1) {
6808       stream->sample_index = 0;
6809       stream->offset_in_sample = 0;
6810     }
6811
6812     if (stream->sample_index >= stream->n_samples) {
6813       GST_LOG_OBJECT (demux, "track-id %u samples exhausted", stream->track_id);
6814       continue;
6815     }
6816
6817     if (!qtdemux_parse_samples (demux, stream, stream->sample_index)) {
6818       GST_LOG_OBJECT (demux, "Parsing of index %u from stbl atom failed!",
6819           stream->sample_index);
6820       return -1;
6821     }
6822
6823     sample = &stream->samples[stream->sample_index];
6824
6825     GST_LOG_OBJECT (demux,
6826         "Checking track-id %u (sample_index:%d / offset:%" G_GUINT64_FORMAT
6827         " / size:%" G_GUINT32_FORMAT ")", stream->track_id,
6828         stream->sample_index, sample->offset, sample->size);
6829
6830     if (((smalloffs == -1)
6831             || (sample->offset < smalloffs)) && (sample->size)) {
6832       smalloffs = sample->offset;
6833       target_stream = stream;
6834     }
6835   }
6836
6837   if (!target_stream)
6838     return -1;
6839
6840   GST_LOG_OBJECT (demux,
6841       "track-id %u offset %" G_GUINT64_FORMAT " demux->offset :%"
6842       G_GUINT64_FORMAT, target_stream->track_id, smalloffs, demux->offset);
6843
6844   stream = target_stream;
6845   sample = &stream->samples[stream->sample_index];
6846
6847   if (sample->offset >= demux->offset) {
6848     demux->todrop = sample->offset - demux->offset;
6849     return sample->size + demux->todrop;
6850   }
6851
6852   GST_DEBUG_OBJECT (demux,
6853       "There wasn't any entry at offset %" G_GUINT64_FORMAT, demux->offset);
6854   return -1;
6855 }
6856
6857 static void
6858 gst_qtdemux_post_progress (GstQTDemux * demux, gint num, gint denom)
6859 {
6860   gint perc = (gint) ((gdouble) num * 100.0 / (gdouble) denom);
6861
6862   gst_element_post_message (GST_ELEMENT_CAST (demux),
6863       gst_message_new_element (GST_OBJECT_CAST (demux),
6864           gst_structure_new ("progress", "percent", G_TYPE_INT, perc, NULL)));
6865 }
6866
6867 static gboolean
6868 qtdemux_seek_offset (GstQTDemux * demux, guint64 offset)
6869 {
6870   GstEvent *event;
6871   gboolean res = 0;
6872
6873   GST_DEBUG_OBJECT (demux, "Seeking to %" G_GUINT64_FORMAT, offset);
6874
6875   event =
6876       gst_event_new_seek (1.0, GST_FORMAT_BYTES,
6877       GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE, GST_SEEK_TYPE_SET, offset,
6878       GST_SEEK_TYPE_NONE, -1);
6879
6880   /* store seqnum to drop flush events, they don't need to reach downstream */
6881   demux->offset_seek_seqnum = gst_event_get_seqnum (event);
6882   res = gst_pad_push_event (demux->sinkpad, event);
6883   demux->offset_seek_seqnum = GST_SEQNUM_INVALID;
6884
6885   return res;
6886 }
6887
6888 /* check for seekable upstream, above and beyond a mere query */
6889 static void
6890 gst_qtdemux_check_seekability (GstQTDemux * demux)
6891 {
6892   GstQuery *query;
6893   gboolean seekable = FALSE;
6894   gint64 start = -1, stop = -1;
6895
6896   if (demux->upstream_size)
6897     return;
6898
6899   if (demux->upstream_format_is_time)
6900     return;
6901
6902   query = gst_query_new_seeking (GST_FORMAT_BYTES);
6903   if (!gst_pad_peer_query (demux->sinkpad, query)) {
6904     GST_DEBUG_OBJECT (demux, "seeking query failed");
6905     goto done;
6906   }
6907
6908   gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
6909
6910   /* try harder to query upstream size if we didn't get it the first time */
6911   if (seekable && stop == -1) {
6912     GST_DEBUG_OBJECT (demux, "doing duration query to fix up unset stop");
6913     gst_pad_peer_query_duration (demux->sinkpad, GST_FORMAT_BYTES, &stop);
6914   }
6915
6916   /* if upstream doesn't know the size, it's likely that it's not seekable in
6917    * practice even if it technically may be seekable */
6918   if (seekable && (start != 0 || stop <= start)) {
6919     GST_DEBUG_OBJECT (demux, "seekable but unknown start/stop -> disable");
6920     seekable = FALSE;
6921   }
6922
6923 done:
6924   gst_query_unref (query);
6925
6926   GST_DEBUG_OBJECT (demux, "seekable: %d (%" G_GUINT64_FORMAT " - %"
6927       G_GUINT64_FORMAT ")", seekable, start, stop);
6928   demux->upstream_seekable = seekable;
6929   demux->upstream_size = seekable ? stop : -1;
6930 }
6931
6932 static void
6933 gst_qtdemux_drop_data (GstQTDemux * demux, gint bytes)
6934 {
6935   g_return_if_fail (bytes <= demux->todrop);
6936
6937   GST_LOG_OBJECT (demux, "Dropping %d bytes", bytes);
6938   gst_adapter_flush (demux->adapter, bytes);
6939   demux->neededbytes -= bytes;
6940   demux->offset += bytes;
6941   demux->todrop -= bytes;
6942 }
6943
6944 /* PUSH-MODE only: Send a segment, if not done already. */
6945 static void
6946 gst_qtdemux_check_send_pending_segment (GstQTDemux * demux)
6947 {
6948   if (G_UNLIKELY (demux->need_segment)) {
6949     gint i;
6950
6951     if (!demux->upstream_format_is_time) {
6952       gst_qtdemux_map_and_push_segments (demux, &demux->segment);
6953     } else {
6954       GstEvent *segment_event;
6955       segment_event = gst_event_new_segment (&demux->segment);
6956       if (demux->segment_seqnum != GST_SEQNUM_INVALID)
6957         gst_event_set_seqnum (segment_event, demux->segment_seqnum);
6958       gst_qtdemux_push_event (demux, segment_event);
6959     }
6960
6961     demux->need_segment = FALSE;
6962
6963     /* clear to send tags on all streams */
6964     for (i = 0; i < QTDEMUX_N_STREAMS (demux); i++) {
6965       QtDemuxStream *stream = QTDEMUX_NTH_STREAM (demux, i);
6966       gst_qtdemux_push_tags (demux, stream);
6967       if (CUR_STREAM (stream)->sparse) {
6968         GST_INFO_OBJECT (demux, "Sending gap event on stream %d", i);
6969         gst_pad_push_event (stream->pad,
6970             gst_event_new_gap (stream->segment.position, GST_CLOCK_TIME_NONE));
6971       }
6972     }
6973   }
6974 }
6975
6976 /* Used for push mode only. */
6977 static void
6978 gst_qtdemux_send_gap_for_segment (GstQTDemux * demux,
6979     QtDemuxStream * stream, gint segment_index, GstClockTime pos)
6980 {
6981   GstClockTime ts, dur;
6982
6983   ts = pos;
6984   dur =
6985       stream->segments[segment_index].duration - (pos -
6986       stream->segments[segment_index].time);
6987   stream->time_position += dur;
6988
6989   /* Only gaps with a duration of at least one second are propagated.
6990    * Same workaround as in pull mode.
6991    * (See 2e45926a96ec5298c6ef29bf912e5e6a06dc3e0e) */
6992   if (dur >= GST_SECOND) {
6993     GstEvent *gap;
6994     gap = gst_event_new_gap (ts, dur);
6995
6996     GST_DEBUG_OBJECT (stream->pad, "Pushing gap for empty "
6997         "segment: %" GST_PTR_FORMAT, gap);
6998     gst_pad_push_event (stream->pad, gap);
6999   }
7000 }
7001
7002 static GstFlowReturn
7003 gst_qtdemux_chain (GstPad * sinkpad, GstObject * parent, GstBuffer * inbuf)
7004 {
7005   GstQTDemux *demux;
7006
7007   demux = GST_QTDEMUX (parent);
7008
7009   GST_DEBUG_OBJECT (demux,
7010       "Received buffer pts:%" GST_TIME_FORMAT " dts:%" GST_TIME_FORMAT
7011       " offset:%" G_GUINT64_FORMAT " size:%" G_GSIZE_FORMAT " demux offset:%"
7012       G_GUINT64_FORMAT, GST_TIME_ARGS (GST_BUFFER_PTS (inbuf)),
7013       GST_TIME_ARGS (GST_BUFFER_DTS (inbuf)), GST_BUFFER_OFFSET (inbuf),
7014       gst_buffer_get_size (inbuf), demux->offset);
7015
7016   if (GST_BUFFER_FLAG_IS_SET (inbuf, GST_BUFFER_FLAG_DISCONT)) {
7017     gboolean is_gap_input = FALSE;
7018     gint i;
7019
7020     GST_DEBUG_OBJECT (demux, "Got DISCONT, marking all streams as DISCONT");
7021
7022     for (i = 0; i < QTDEMUX_N_STREAMS (demux); i++) {
7023       QTDEMUX_NTH_STREAM (demux, i)->discont = TRUE;
7024     }
7025
7026     /* Check if we can land back on our feet in the case where upstream is
7027      * handling the seeking/pushing of samples with gaps in between (like
7028      * in the case of trick-mode DASH for example) */
7029     if (demux->upstream_format_is_time
7030         && GST_BUFFER_OFFSET (inbuf) != GST_BUFFER_OFFSET_NONE) {
7031       for (i = 0; i < QTDEMUX_N_STREAMS (demux); i++) {
7032         guint32 res;
7033         QtDemuxStream *stream = QTDEMUX_NTH_STREAM (demux, i);
7034         GST_LOG_OBJECT (demux,
7035             "track-id #%u , checking if offset %" G_GUINT64_FORMAT
7036             " is a sample start", stream->track_id, GST_BUFFER_OFFSET (inbuf));
7037         res =
7038             gst_qtdemux_find_index_for_given_media_offset_linear (demux,
7039             stream, GST_BUFFER_OFFSET (inbuf));
7040         if (res != -1) {
7041           QtDemuxSample *sample = &stream->samples[res];
7042           GST_LOG_OBJECT (demux,
7043               "Checking if sample %d from track-id %u is valid (offset:%"
7044               G_GUINT64_FORMAT " size:%" G_GUINT32_FORMAT ")", res,
7045               stream->track_id, sample->offset, sample->size);
7046           if (sample->offset == GST_BUFFER_OFFSET (inbuf)) {
7047             GST_LOG_OBJECT (demux,
7048                 "new buffer corresponds to a valid sample : %" G_GUINT32_FORMAT,
7049                 res);
7050             is_gap_input = TRUE;
7051             /* We can go back to standard playback mode */
7052             demux->state = QTDEMUX_STATE_MOVIE;
7053             /* Remember which sample this stream is at */
7054             stream->sample_index = res;
7055             /* Finally update all push-based values to the expected values */
7056             demux->neededbytes = stream->samples[res].size;
7057             demux->offset = GST_BUFFER_OFFSET (inbuf);
7058             demux->mdatleft =
7059                 demux->mdatsize - demux->offset + demux->mdatoffset;
7060             demux->todrop = 0;
7061           }
7062         }
7063       }
7064       if (!is_gap_input) {
7065         GST_DEBUG_OBJECT (demux, "Resetting, actual DISCONT");
7066         /* Reset state if it's a real discont */
7067         demux->neededbytes = 16;
7068         demux->state = QTDEMUX_STATE_INITIAL;
7069         demux->offset = GST_BUFFER_OFFSET (inbuf);
7070         gst_adapter_clear (demux->adapter);
7071       }
7072     }
7073     /* Reverse fragmented playback, need to flush all we have before
7074      * consuming a new fragment.
7075      * The samples array have the timestamps calculated by accumulating the
7076      * durations but this won't work for reverse playback of fragments as
7077      * the timestamps of a subsequent fragment should be smaller than the
7078      * previously received one. */
7079     if (!is_gap_input && demux->fragmented && demux->segment.rate < 0) {
7080       gst_qtdemux_process_adapter (demux, TRUE);
7081       g_ptr_array_foreach (demux->active_streams,
7082           (GFunc) gst_qtdemux_stream_flush_samples_data, NULL);
7083     }
7084   }
7085
7086   gst_adapter_push (demux->adapter, inbuf);
7087
7088   GST_DEBUG_OBJECT (demux,
7089       "pushing in inbuf %p, neededbytes:%u, available:%" G_GSIZE_FORMAT, inbuf,
7090       demux->neededbytes, gst_adapter_available (demux->adapter));
7091
7092   return gst_qtdemux_process_adapter (demux, FALSE);
7093 }
7094
7095 static GstFlowReturn
7096 gst_qtdemux_process_adapter (GstQTDemux * demux, gboolean force)
7097 {
7098   GstFlowReturn ret = GST_FLOW_OK;
7099
7100   /* we never really mean to buffer that much */
7101   if (demux->neededbytes == -1) {
7102     goto eos;
7103   }
7104
7105   while (((gst_adapter_available (demux->adapter)) >= demux->neededbytes) &&
7106       (ret == GST_FLOW_OK || (ret == GST_FLOW_NOT_LINKED && force))) {
7107
7108 #ifndef GST_DISABLE_GST_DEBUG
7109     {
7110       guint64 discont_offset, distance_from_discont;
7111
7112       discont_offset = gst_adapter_offset_at_discont (demux->adapter);
7113       distance_from_discont =
7114           gst_adapter_distance_from_discont (demux->adapter);
7115
7116       GST_DEBUG_OBJECT (demux,
7117           "state:%s , demux->neededbytes:%d, demux->offset:%" G_GUINT64_FORMAT
7118           " adapter offset :%" G_GUINT64_FORMAT " (+ %" G_GUINT64_FORMAT
7119           " bytes)", qt_demux_state_string (demux->state), demux->neededbytes,
7120           demux->offset, discont_offset, distance_from_discont);
7121     }
7122 #endif
7123
7124     switch (demux->state) {
7125       case QTDEMUX_STATE_INITIAL:{
7126         const guint8 *data;
7127         guint32 fourcc;
7128         guint64 size;
7129
7130         gst_qtdemux_check_seekability (demux);
7131
7132         data = gst_adapter_map (demux->adapter, demux->neededbytes);
7133
7134         /* get fourcc/length, set neededbytes */
7135         extract_initial_length_and_fourcc ((guint8 *) data, demux->neededbytes,
7136             &size, &fourcc);
7137         gst_adapter_unmap (demux->adapter);
7138         data = NULL;
7139         GST_DEBUG_OBJECT (demux, "Peeking found [%" GST_FOURCC_FORMAT "] "
7140             "size: %" G_GUINT64_FORMAT, GST_FOURCC_ARGS (fourcc), size);
7141         if (size == 0) {
7142           GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
7143               (_("This file is invalid and cannot be played.")),
7144               ("initial atom '%" GST_FOURCC_FORMAT "' has empty length",
7145                   GST_FOURCC_ARGS (fourcc)));
7146           ret = GST_FLOW_ERROR;
7147           break;
7148         }
7149         if (fourcc == FOURCC_mdat) {
7150           gint next_entry = next_entry_size (demux);
7151           if (QTDEMUX_N_STREAMS (demux) > 0 && (next_entry != -1
7152                   || !demux->fragmented)) {
7153             /* we have the headers, start playback */
7154             demux->state = QTDEMUX_STATE_MOVIE;
7155             demux->neededbytes = next_entry;
7156             demux->mdatleft = size;
7157             demux->mdatsize = demux->mdatleft;
7158           } else {
7159             /* no headers yet, try to get them */
7160             guint bs;
7161             gboolean res;
7162             guint64 old, target;
7163
7164           buffer_data:
7165             old = demux->offset;
7166             target = old + size;
7167
7168             /* try to jump over the atom with a seek */
7169             /* only bother if it seems worth doing so,
7170              * and avoids possible upstream/server problems */
7171             if (demux->upstream_seekable &&
7172                 demux->upstream_size > 4 * (1 << 20)) {
7173               res = qtdemux_seek_offset (demux, target);
7174             } else {
7175               GST_DEBUG_OBJECT (demux, "skipping seek");
7176               res = FALSE;
7177             }
7178
7179             if (res) {
7180               GST_DEBUG_OBJECT (demux, "seek success");
7181               /* remember the offset fo the first mdat so we can seek back to it
7182                * after we have the headers */
7183               if (fourcc == FOURCC_mdat && demux->first_mdat == -1) {
7184                 demux->first_mdat = old;
7185                 GST_DEBUG_OBJECT (demux, "first mdat at %" G_GUINT64_FORMAT,
7186                     demux->first_mdat);
7187               }
7188               /* seek worked, continue reading */
7189               demux->offset = target;
7190               demux->neededbytes = 16;
7191               demux->state = QTDEMUX_STATE_INITIAL;
7192             } else {
7193               /* seek failed, need to buffer */
7194               demux->offset = old;
7195               GST_DEBUG_OBJECT (demux, "seek failed/skipped");
7196               /* there may be multiple mdat (or alike) buffers */
7197               /* sanity check */
7198               if (demux->mdatbuffer)
7199                 bs = gst_buffer_get_size (demux->mdatbuffer);
7200               else
7201                 bs = 0;
7202               if (size + bs > 10 * (1 << 20))
7203                 goto no_moov;
7204               demux->state = QTDEMUX_STATE_BUFFER_MDAT;
7205               demux->neededbytes = size;
7206               if (!demux->mdatbuffer)
7207                 demux->mdatoffset = demux->offset;
7208             }
7209           }
7210         } else if (G_UNLIKELY (size > QTDEMUX_MAX_ATOM_SIZE)) {
7211           GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
7212               (_("This file is invalid and cannot be played.")),
7213               ("atom %" GST_FOURCC_FORMAT " has bogus size %" G_GUINT64_FORMAT,
7214                   GST_FOURCC_ARGS (fourcc), size));
7215           ret = GST_FLOW_ERROR;
7216           break;
7217         } else {
7218           /* this means we already started buffering and still no moov header,
7219            * let's continue buffering everything till we get moov */
7220           if (demux->mdatbuffer && !(fourcc == FOURCC_moov
7221                   || fourcc == FOURCC_moof))
7222             goto buffer_data;
7223           demux->neededbytes = size;
7224           demux->state = QTDEMUX_STATE_HEADER;
7225         }
7226         break;
7227       }
7228       case QTDEMUX_STATE_HEADER:{
7229         const guint8 *data;
7230         guint32 fourcc;
7231
7232         GST_DEBUG_OBJECT (demux, "In header");
7233
7234         data = gst_adapter_map (demux->adapter, demux->neededbytes);
7235
7236         /* parse the header */
7237         extract_initial_length_and_fourcc (data, demux->neededbytes, NULL,
7238             &fourcc);
7239         if (fourcc == FOURCC_moov) {
7240           /* in usual fragmented setup we could try to scan for more
7241            * and end up at the the moov (after mdat) again */
7242           if (demux->got_moov && QTDEMUX_N_STREAMS (demux) > 0 &&
7243               (!demux->fragmented
7244                   || demux->last_moov_offset == demux->offset)) {
7245             GST_DEBUG_OBJECT (demux,
7246                 "Skipping moov atom as we have (this) one already");
7247           } else {
7248             GST_DEBUG_OBJECT (demux, "Parsing [moov]");
7249
7250             if (demux->got_moov && demux->fragmented) {
7251               GST_DEBUG_OBJECT (demux,
7252                   "Got a second moov, clean up data from old one");
7253               if (demux->moov_node_compressed) {
7254                 g_node_destroy (demux->moov_node_compressed);
7255                 if (demux->moov_node)
7256                   g_free (demux->moov_node->data);
7257               }
7258               demux->moov_node_compressed = NULL;
7259               if (demux->moov_node)
7260                 g_node_destroy (demux->moov_node);
7261               demux->moov_node = NULL;
7262             }
7263
7264             demux->last_moov_offset = demux->offset;
7265
7266             /* Update streams with new moov */
7267             gst_qtdemux_stream_concat (demux,
7268                 demux->old_streams, demux->active_streams);
7269
7270             qtdemux_parse_moov (demux, data, demux->neededbytes);
7271             qtdemux_node_dump (demux, demux->moov_node);
7272             qtdemux_parse_tree (demux);
7273             qtdemux_prepare_streams (demux);
7274             QTDEMUX_EXPOSE_LOCK (demux);
7275             qtdemux_expose_streams (demux);
7276             QTDEMUX_EXPOSE_UNLOCK (demux);
7277
7278             demux->got_moov = TRUE;
7279
7280             gst_qtdemux_check_send_pending_segment (demux);
7281
7282             if (demux->moov_node_compressed) {
7283               g_node_destroy (demux->moov_node_compressed);
7284               g_free (demux->moov_node->data);
7285             }
7286             demux->moov_node_compressed = NULL;
7287             g_node_destroy (demux->moov_node);
7288             demux->moov_node = NULL;
7289             GST_DEBUG_OBJECT (demux, "Finished parsing the header");
7290           }
7291         } else if (fourcc == FOURCC_moof) {
7292           if ((demux->got_moov || demux->media_caps) && demux->fragmented) {
7293             guint64 dist = 0;
7294             GstClockTime prev_pts;
7295             guint64 prev_offset;
7296             guint64 adapter_discont_offset, adapter_discont_dist;
7297
7298             GST_DEBUG_OBJECT (demux, "Parsing [moof]");
7299
7300             /*
7301              * The timestamp of the moof buffer is relevant as some scenarios
7302              * won't have the initial timestamp in the atoms. Whenever a new
7303              * buffer has started, we get that buffer's PTS and use it as a base
7304              * timestamp for the trun entries.
7305              *
7306              * To keep track of the current buffer timestamp and starting point
7307              * we use gst_adapter_prev_pts that gives us the PTS and the distance
7308              * from the beginning of the buffer, with the distance and demux->offset
7309              * we know if it is still the same buffer or not.
7310              */
7311             prev_pts = gst_adapter_prev_pts (demux->adapter, &dist);
7312             prev_offset = demux->offset - dist;
7313             if (demux->fragment_start_offset == -1
7314                 || prev_offset > demux->fragment_start_offset) {
7315               demux->fragment_start_offset = prev_offset;
7316               demux->fragment_start = prev_pts;
7317               GST_DEBUG_OBJECT (demux,
7318                   "New fragment start found at: %" G_GUINT64_FORMAT " : %"
7319                   GST_TIME_FORMAT, demux->fragment_start_offset,
7320                   GST_TIME_ARGS (demux->fragment_start));
7321             }
7322
7323             /* We can't use prev_offset() here because this would require
7324              * upstream to set consistent and correct offsets on all buffers
7325              * since the discont. Nothing ever did that in the past and we
7326              * would break backwards compatibility here then.
7327              * Instead take the offset we had at the last discont and count
7328              * the bytes from there. This works with old code as there would
7329              * be no discont between moov and moof, and also works with
7330              * adaptivedemux which correctly sets offset and will set the
7331              * DISCONT flag accordingly when needed.
7332              *
7333              * We also only do this for upstream TIME segments as otherwise
7334              * there are potential backwards compatibility problems with
7335              * seeking in PUSH mode and upstream providing inconsistent
7336              * timestamps. */
7337             adapter_discont_offset =
7338                 gst_adapter_offset_at_discont (demux->adapter);
7339             adapter_discont_dist =
7340                 gst_adapter_distance_from_discont (demux->adapter);
7341
7342             GST_DEBUG_OBJECT (demux,
7343                 "demux offset %" G_GUINT64_FORMAT " adapter offset %"
7344                 G_GUINT64_FORMAT " (+ %" G_GUINT64_FORMAT " bytes)",
7345                 demux->offset, adapter_discont_offset, adapter_discont_dist);
7346
7347             if (demux->upstream_format_is_time) {
7348               demux->moof_offset = adapter_discont_offset;
7349               if (demux->moof_offset != GST_BUFFER_OFFSET_NONE)
7350                 demux->moof_offset += adapter_discont_dist;
7351               if (demux->moof_offset == GST_BUFFER_OFFSET_NONE)
7352                 demux->moof_offset = demux->offset;
7353             } else {
7354               demux->moof_offset = demux->offset;
7355             }
7356
7357             if (!qtdemux_parse_moof (demux, data, demux->neededbytes,
7358                     demux->moof_offset, NULL)) {
7359               gst_adapter_unmap (demux->adapter);
7360               ret = GST_FLOW_ERROR;
7361               goto done;
7362             }
7363
7364             /* in MSS we need to expose the pads after the first moof as we won't get a moov */
7365             if (demux->mss_mode && !demux->exposed) {
7366               QTDEMUX_EXPOSE_LOCK (demux);
7367               qtdemux_expose_streams (demux);
7368               QTDEMUX_EXPOSE_UNLOCK (demux);
7369             }
7370
7371             gst_qtdemux_check_send_pending_segment (demux);
7372           } else {
7373             GST_DEBUG_OBJECT (demux, "Discarding [moof]");
7374           }
7375         } else if (fourcc == FOURCC_ftyp) {
7376           GST_DEBUG_OBJECT (demux, "Parsing [ftyp]");
7377           qtdemux_parse_ftyp (demux, data, demux->neededbytes);
7378         } else if (fourcc == FOURCC_uuid) {
7379           GST_DEBUG_OBJECT (demux, "Parsing [uuid]");
7380           qtdemux_parse_uuid (demux, data, demux->neededbytes);
7381         } else if (fourcc == FOURCC_sidx) {
7382           GST_DEBUG_OBJECT (demux, "Parsing [sidx]");
7383           qtdemux_parse_sidx (demux, data, demux->neededbytes);
7384         } else {
7385           switch (fourcc) {
7386             case FOURCC_styp:
7387               /* [styp] is like a [ftyp], but in fragment header. We ignore it for now
7388                * FALLTHROUGH */
7389             case FOURCC_skip:
7390             case FOURCC_free:
7391               /* [free] and [skip] are padding atoms */
7392               GST_DEBUG_OBJECT (demux,
7393                   "Skipping fourcc while parsing header : %" GST_FOURCC_FORMAT,
7394                   GST_FOURCC_ARGS (fourcc));
7395               break;
7396             default:
7397               GST_WARNING_OBJECT (demux,
7398                   "Unknown fourcc while parsing header : %" GST_FOURCC_FORMAT,
7399                   GST_FOURCC_ARGS (fourcc));
7400               /* Let's jump that one and go back to initial state */
7401               break;
7402           }
7403         }
7404         gst_adapter_unmap (demux->adapter);
7405         data = NULL;
7406
7407         if (demux->mdatbuffer && QTDEMUX_N_STREAMS (demux)) {
7408           gsize remaining_data_size = 0;
7409
7410           /* the mdat was before the header */
7411           GST_DEBUG_OBJECT (demux, "We have n_streams:%d and mdatbuffer:%p",
7412               QTDEMUX_N_STREAMS (demux), demux->mdatbuffer);
7413           /* restore our adapter/offset view of things with upstream;
7414            * put preceding buffered data ahead of current moov data.
7415            * This should also handle evil mdat, moov, mdat cases and alike */
7416           gst_adapter_flush (demux->adapter, demux->neededbytes);
7417
7418           /* Store any remaining data after the mdat for later usage */
7419           remaining_data_size = gst_adapter_available (demux->adapter);
7420           if (remaining_data_size > 0) {
7421             g_assert (demux->restoredata_buffer == NULL);
7422             demux->restoredata_buffer =
7423                 gst_adapter_take_buffer (demux->adapter, remaining_data_size);
7424             demux->restoredata_offset = demux->offset + demux->neededbytes;
7425             GST_DEBUG_OBJECT (demux,
7426                 "Stored %" G_GSIZE_FORMAT " post mdat bytes at offset %"
7427                 G_GUINT64_FORMAT, remaining_data_size,
7428                 demux->restoredata_offset);
7429           }
7430
7431           gst_adapter_push (demux->adapter, demux->mdatbuffer);
7432           demux->mdatbuffer = NULL;
7433           demux->offset = demux->mdatoffset;
7434           demux->neededbytes = next_entry_size (demux);
7435           demux->state = QTDEMUX_STATE_MOVIE;
7436           demux->mdatleft = gst_adapter_available (demux->adapter);
7437           demux->mdatsize = demux->mdatleft;
7438         } else {
7439           GST_DEBUG_OBJECT (demux, "Carrying on normally");
7440           gst_adapter_flush (demux->adapter, demux->neededbytes);
7441
7442           /* only go back to the mdat if there are samples to play */
7443           if (demux->got_moov && demux->first_mdat != -1
7444               && has_next_entry (demux)) {
7445             gboolean res;
7446
7447             /* we need to seek back */
7448             res = qtdemux_seek_offset (demux, demux->first_mdat);
7449             if (res) {
7450               demux->offset = demux->first_mdat;
7451             } else {
7452               GST_DEBUG_OBJECT (demux, "Seek back failed");
7453             }
7454           } else {
7455             demux->offset += demux->neededbytes;
7456           }
7457           demux->neededbytes = 16;
7458           demux->state = QTDEMUX_STATE_INITIAL;
7459         }
7460
7461         break;
7462       }
7463       case QTDEMUX_STATE_BUFFER_MDAT:{
7464         GstBuffer *buf;
7465         guint8 fourcc[4];
7466
7467         GST_DEBUG_OBJECT (demux, "Got our buffer at offset %" G_GUINT64_FORMAT,
7468             demux->offset);
7469         buf = gst_adapter_take_buffer (demux->adapter, demux->neededbytes);
7470         gst_buffer_extract (buf, 0, fourcc, 4);
7471         GST_DEBUG_OBJECT (demux, "mdatbuffer starts with %" GST_FOURCC_FORMAT,
7472             GST_FOURCC_ARGS (QT_FOURCC (fourcc)));
7473         if (demux->mdatbuffer)
7474           demux->mdatbuffer = gst_buffer_append (demux->mdatbuffer, buf);
7475         else
7476           demux->mdatbuffer = buf;
7477         demux->offset += demux->neededbytes;
7478         demux->neededbytes = 16;
7479         demux->state = QTDEMUX_STATE_INITIAL;
7480         gst_qtdemux_post_progress (demux, 1, 1);
7481
7482         break;
7483       }
7484       case QTDEMUX_STATE_MOVIE:{
7485         QtDemuxStream *stream = NULL;
7486         QtDemuxSample *sample;
7487         GstClockTime dts, pts, duration;
7488         gboolean keyframe;
7489         gint i;
7490
7491         GST_DEBUG_OBJECT (demux,
7492             "BEGIN // in MOVIE for offset %" G_GUINT64_FORMAT, demux->offset);
7493
7494         if (demux->fragmented) {
7495           GST_DEBUG_OBJECT (demux, "mdat remaining %" G_GUINT64_FORMAT,
7496               demux->mdatleft);
7497           if (G_LIKELY (demux->todrop < demux->mdatleft)) {
7498             /* if needed data starts within this atom,
7499              * then it should not exceed this atom */
7500             if (G_UNLIKELY (demux->neededbytes > demux->mdatleft)) {
7501               GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
7502                   (_("This file is invalid and cannot be played.")),
7503                   ("sample data crosses atom boundary"));
7504               ret = GST_FLOW_ERROR;
7505               break;
7506             }
7507             demux->mdatleft -= demux->neededbytes;
7508           } else {
7509             GST_DEBUG_OBJECT (demux, "data atom emptied; resuming atom scan");
7510             /* so we are dropping more than left in this atom */
7511             gst_qtdemux_drop_data (demux, demux->mdatleft);
7512             demux->mdatleft = 0;
7513
7514             /* need to resume atom parsing so we do not miss any other pieces */
7515             demux->state = QTDEMUX_STATE_INITIAL;
7516             demux->neededbytes = 16;
7517
7518             /* check if there was any stored post mdat data from previous buffers */
7519             if (demux->restoredata_buffer) {
7520               g_assert (gst_adapter_available (demux->adapter) == 0);
7521
7522               gst_adapter_push (demux->adapter, demux->restoredata_buffer);
7523               demux->restoredata_buffer = NULL;
7524               demux->offset = demux->restoredata_offset;
7525             }
7526
7527             break;
7528           }
7529         }
7530
7531         if (demux->todrop) {
7532           if (demux->cenc_aux_info_offset > 0) {
7533             GstByteReader br;
7534             const guint8 *data;
7535
7536             GST_DEBUG_OBJECT (demux, "parsing cenc auxiliary info");
7537             data = gst_adapter_map (demux->adapter, demux->todrop);
7538             gst_byte_reader_init (&br, data + 8, demux->todrop);
7539             if (!qtdemux_parse_cenc_aux_info (demux,
7540                     QTDEMUX_NTH_STREAM (demux, 0), &br,
7541                     demux->cenc_aux_info_sizes, demux->cenc_aux_sample_count)) {
7542               GST_ERROR_OBJECT (demux, "failed to parse cenc auxiliary info");
7543               ret = GST_FLOW_ERROR;
7544               gst_adapter_unmap (demux->adapter);
7545               g_free (demux->cenc_aux_info_sizes);
7546               demux->cenc_aux_info_sizes = NULL;
7547               goto done;
7548             }
7549             demux->cenc_aux_info_offset = 0;
7550             g_free (demux->cenc_aux_info_sizes);
7551             demux->cenc_aux_info_sizes = NULL;
7552             gst_adapter_unmap (demux->adapter);
7553           }
7554           gst_qtdemux_drop_data (demux, demux->todrop);
7555         }
7556
7557         /* first buffer? */
7558         /* initial newsegment sent here after having added pads,
7559          * possible others in sink_event */
7560         gst_qtdemux_check_send_pending_segment (demux);
7561
7562         /* Figure out which stream this packet belongs to */
7563         for (i = 0; i < QTDEMUX_N_STREAMS (demux); i++) {
7564           stream = QTDEMUX_NTH_STREAM (demux, i);
7565           if (stream->sample_index >= stream->n_samples) {
7566             /* reset to be checked below G_UNLIKELY (stream == NULL) */
7567             stream = NULL;
7568             continue;
7569           }
7570           GST_LOG_OBJECT (demux,
7571               "Checking track-id %u (sample_index:%d / offset:%"
7572               G_GUINT64_FORMAT " / size:%d)", stream->track_id,
7573               stream->sample_index,
7574               stream->samples[stream->sample_index].offset,
7575               stream->samples[stream->sample_index].size);
7576
7577           if (stream->samples[stream->sample_index].offset == demux->offset)
7578             break;
7579         }
7580
7581         if (G_UNLIKELY (stream == NULL))
7582           goto unknown_stream;
7583
7584         gst_qtdemux_stream_check_and_change_stsd_index (demux, stream);
7585
7586         if (stream->new_caps) {
7587           gst_qtdemux_configure_stream (demux, stream);
7588         }
7589
7590         /* Put data in a buffer, set timestamps, caps, ... */
7591         sample = &stream->samples[stream->sample_index];
7592
7593         if (G_LIKELY (!(STREAM_IS_EOS (stream)))) {
7594           GST_DEBUG_OBJECT (demux, "stream : %" GST_FOURCC_FORMAT,
7595               GST_FOURCC_ARGS (CUR_STREAM (stream)->fourcc));
7596
7597           dts = QTSAMPLE_DTS (stream, sample);
7598           pts = QTSAMPLE_PTS (stream, sample);
7599           duration = QTSAMPLE_DUR_DTS (stream, sample, dts);
7600           keyframe = QTSAMPLE_KEYFRAME (stream, sample);
7601
7602           /* check for segment end */
7603           if (G_UNLIKELY (demux->segment.stop != -1
7604                   && demux->segment.stop <= pts && stream->on_keyframe)
7605               && !(demux->upstream_format_is_time && demux->segment.rate < 0)) {
7606             GST_DEBUG_OBJECT (demux, "we reached the end of our segment.");
7607             stream->time_position = GST_CLOCK_TIME_NONE;        /* this means EOS */
7608
7609             /* skip this data, stream is EOS */
7610             gst_adapter_flush (demux->adapter, demux->neededbytes);
7611             demux->offset += demux->neededbytes;
7612
7613             /* check if all streams are eos */
7614             ret = GST_FLOW_EOS;
7615             for (i = 0; i < QTDEMUX_N_STREAMS (demux); i++) {
7616               if (!STREAM_IS_EOS (QTDEMUX_NTH_STREAM (demux, i))) {
7617                 ret = GST_FLOW_OK;
7618                 break;
7619               }
7620             }
7621           } else {
7622             GstBuffer *outbuf;
7623
7624             outbuf =
7625                 gst_adapter_take_buffer (demux->adapter, demux->neededbytes);
7626
7627             /* FIXME: should either be an assert or a plain check */
7628             g_return_val_if_fail (outbuf != NULL, GST_FLOW_ERROR);
7629
7630             ret = gst_qtdemux_decorate_and_push_buffer (demux, stream, outbuf,
7631                 dts, pts, duration, keyframe, dts, demux->offset);
7632           }
7633
7634           /* combine flows */
7635           GST_OBJECT_LOCK (demux);
7636           ret = gst_qtdemux_combine_flows (demux, stream, ret);
7637           GST_OBJECT_UNLOCK (demux);
7638         } else {
7639           /* skip this data, stream is EOS */
7640           gst_adapter_flush (demux->adapter, demux->neededbytes);
7641         }
7642
7643         stream->sample_index++;
7644         stream->offset_in_sample = 0;
7645
7646         /* update current offset and figure out size of next buffer */
7647         GST_LOG_OBJECT (demux, "increasing offset %" G_GUINT64_FORMAT " by %u",
7648             demux->offset, demux->neededbytes);
7649         demux->offset += demux->neededbytes;
7650         GST_LOG_OBJECT (demux, "offset is now %" G_GUINT64_FORMAT,
7651             demux->offset);
7652
7653
7654         if (ret == GST_FLOW_EOS) {
7655           GST_DEBUG_OBJECT (demux, "All streams are EOS, signal upstream");
7656           demux->neededbytes = -1;
7657           goto eos;
7658         }
7659
7660         if ((demux->neededbytes = next_entry_size (demux)) == -1) {
7661           if (demux->fragmented) {
7662             GST_DEBUG_OBJECT (demux, "(temporarily) out of fragmented samples");
7663             /* there may be more to follow, only finish this atom */
7664             demux->todrop = demux->mdatleft;
7665             demux->neededbytes = demux->todrop;
7666             break;
7667           }
7668           goto eos;
7669         }
7670         if (ret != GST_FLOW_OK && ret != GST_FLOW_NOT_LINKED) {
7671           goto non_ok_unlinked_flow;
7672         }
7673         break;
7674       }
7675       default:
7676         goto invalid_state;
7677     }
7678   }
7679
7680   /* when buffering movie data, at least show user something is happening */
7681   if (ret == GST_FLOW_OK && demux->state == QTDEMUX_STATE_BUFFER_MDAT &&
7682       gst_adapter_available (demux->adapter) <= demux->neededbytes) {
7683     gst_qtdemux_post_progress (demux, gst_adapter_available (demux->adapter),
7684         demux->neededbytes);
7685   }
7686 done:
7687
7688   return ret;
7689
7690   /* ERRORS */
7691 non_ok_unlinked_flow:
7692   {
7693     GST_DEBUG_OBJECT (demux, "Stopping, combined return flow %s",
7694         gst_flow_get_name (ret));
7695     return ret;
7696   }
7697 unknown_stream:
7698   {
7699     GST_ELEMENT_ERROR (demux, STREAM, FAILED, (NULL), ("unknown stream found"));
7700     ret = GST_FLOW_ERROR;
7701     goto done;
7702   }
7703 eos:
7704   {
7705     GST_DEBUG_OBJECT (demux, "no next entry, EOS");
7706     ret = GST_FLOW_EOS;
7707     goto done;
7708   }
7709 invalid_state:
7710   {
7711     GST_ELEMENT_ERROR (demux, STREAM, FAILED,
7712         (NULL), ("qtdemuxer invalid state %d", demux->state));
7713     ret = GST_FLOW_ERROR;
7714     goto done;
7715   }
7716 no_moov:
7717   {
7718     GST_ELEMENT_ERROR (demux, STREAM, FAILED,
7719         (NULL), ("no 'moov' atom within the first 10 MB"));
7720     ret = GST_FLOW_ERROR;
7721     goto done;
7722   }
7723 }
7724
7725 static gboolean
7726 qtdemux_sink_activate (GstPad * sinkpad, GstObject * parent)
7727 {
7728   GstQuery *query;
7729   gboolean pull_mode;
7730
7731   query = gst_query_new_scheduling ();
7732
7733   if (!gst_pad_peer_query (sinkpad, query)) {
7734     gst_query_unref (query);
7735     goto activate_push;
7736   }
7737
7738   pull_mode = gst_query_has_scheduling_mode_with_flags (query,
7739       GST_PAD_MODE_PULL, GST_SCHEDULING_FLAG_SEEKABLE);
7740   gst_query_unref (query);
7741
7742   if (!pull_mode)
7743     goto activate_push;
7744
7745   GST_DEBUG_OBJECT (sinkpad, "activating pull");
7746   return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
7747
7748 activate_push:
7749   {
7750     GST_DEBUG_OBJECT (sinkpad, "activating push");
7751     return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
7752   }
7753 }
7754
7755 static gboolean
7756 qtdemux_sink_activate_mode (GstPad * sinkpad, GstObject * parent,
7757     GstPadMode mode, gboolean active)
7758 {
7759   gboolean res;
7760   GstQTDemux *demux = GST_QTDEMUX (parent);
7761
7762   switch (mode) {
7763     case GST_PAD_MODE_PUSH:
7764       demux->pullbased = FALSE;
7765       res = TRUE;
7766       break;
7767     case GST_PAD_MODE_PULL:
7768       if (active) {
7769         demux->pullbased = TRUE;
7770         res = gst_pad_start_task (sinkpad, (GstTaskFunction) gst_qtdemux_loop,
7771             sinkpad, NULL);
7772       } else {
7773         res = gst_pad_stop_task (sinkpad);
7774       }
7775       break;
7776     default:
7777       res = FALSE;
7778       break;
7779   }
7780   return res;
7781 }
7782
7783 #ifdef HAVE_ZLIB
7784 static void *
7785 qtdemux_inflate (void *z_buffer, guint z_length, guint * length)
7786 {
7787   guint8 *buffer;
7788   z_stream z;
7789   int ret;
7790
7791   memset (&z, 0, sizeof (z));
7792   z.zalloc = NULL;
7793   z.zfree = NULL;
7794   z.opaque = NULL;
7795
7796   if ((ret = inflateInit (&z)) != Z_OK) {
7797     GST_ERROR ("inflateInit() returned %d", ret);
7798     return NULL;
7799   }
7800
7801   z.next_in = z_buffer;
7802   z.avail_in = z_length;
7803
7804   buffer = (guint8 *) g_malloc (*length);
7805   z.avail_out = *length;
7806   z.next_out = (Bytef *) buffer;
7807   do {
7808     ret = inflate (&z, Z_NO_FLUSH);
7809     if (ret == Z_STREAM_END) {
7810       break;
7811     } else if (ret != Z_OK) {
7812       GST_WARNING ("inflate() returned %d", ret);
7813       break;
7814     }
7815
7816     *length += 4096;
7817     buffer = (guint8 *) g_realloc (buffer, *length);
7818     z.next_out = (Bytef *) (buffer + z.total_out);
7819     z.avail_out += 4096;
7820   } while (z.avail_in > 0);
7821
7822   if (ret != Z_STREAM_END) {
7823     g_free (buffer);
7824     buffer = NULL;
7825     *length = 0;
7826   } else {
7827     *length = z.total_out;
7828   }
7829
7830   inflateEnd (&z);
7831
7832   return buffer;
7833 }
7834 #endif /* HAVE_ZLIB */
7835
7836 static gboolean
7837 qtdemux_parse_moov (GstQTDemux * qtdemux, const guint8 * buffer, guint length)
7838 {
7839   GNode *cmov;
7840
7841   qtdemux->moov_node = g_node_new ((guint8 *) buffer);
7842
7843   /* counts as header data */
7844   qtdemux->header_size += length;
7845
7846   GST_DEBUG_OBJECT (qtdemux, "parsing 'moov' atom");
7847   qtdemux_parse_node (qtdemux, qtdemux->moov_node, buffer, length);
7848
7849   cmov = qtdemux_tree_get_child_by_type (qtdemux->moov_node, FOURCC_cmov);
7850   if (cmov) {
7851     guint32 method;
7852     GNode *dcom;
7853     GNode *cmvd;
7854     guint32 dcom_len;
7855
7856     dcom = qtdemux_tree_get_child_by_type (cmov, FOURCC_dcom);
7857     cmvd = qtdemux_tree_get_child_by_type (cmov, FOURCC_cmvd);
7858     if (dcom == NULL || cmvd == NULL)
7859       goto invalid_compression;
7860
7861     dcom_len = QT_UINT32 (dcom->data);
7862     if (dcom_len < 12)
7863       goto invalid_compression;
7864
7865     method = QT_FOURCC ((guint8 *) dcom->data + 8);
7866     switch (method) {
7867 #ifdef HAVE_ZLIB
7868       case FOURCC_zlib:{
7869         guint uncompressed_length;
7870         guint compressed_length;
7871         guint8 *buf;
7872         guint32 cmvd_len;
7873
7874         cmvd_len = QT_UINT32 ((guint8 *) cmvd->data);
7875         if (cmvd_len < 12)
7876           goto invalid_compression;
7877
7878         uncompressed_length = QT_UINT32 ((guint8 *) cmvd->data + 8);
7879         compressed_length = cmvd_len - 12;
7880         GST_LOG ("length = %u", uncompressed_length);
7881
7882         buf =
7883             (guint8 *) qtdemux_inflate ((guint8 *) cmvd->data + 12,
7884             compressed_length, &uncompressed_length);
7885
7886         if (buf) {
7887           qtdemux->moov_node_compressed = qtdemux->moov_node;
7888           qtdemux->moov_node = g_node_new (buf);
7889
7890           qtdemux_parse_node (qtdemux, qtdemux->moov_node, buf,
7891               uncompressed_length);
7892         }
7893         break;
7894       }
7895 #endif /* HAVE_ZLIB */
7896       default:
7897         GST_WARNING_OBJECT (qtdemux, "unknown or unhandled header compression "
7898             "type %" GST_FOURCC_FORMAT, GST_FOURCC_ARGS (method));
7899         break;
7900     }
7901   }
7902   return TRUE;
7903
7904   /* ERRORS */
7905 invalid_compression:
7906   {
7907     GST_ERROR_OBJECT (qtdemux, "invalid compressed header");
7908     return FALSE;
7909   }
7910 }
7911
7912 static gboolean
7913 qtdemux_parse_container (GstQTDemux * qtdemux, GNode * node, const guint8 * buf,
7914     const guint8 * end)
7915 {
7916   while (G_UNLIKELY (buf < end)) {
7917     GNode *child;
7918     guint32 len;
7919
7920     if (G_UNLIKELY (buf + 4 > end)) {
7921       GST_LOG_OBJECT (qtdemux, "buffer overrun");
7922       break;
7923     }
7924     len = QT_UINT32 (buf);
7925     if (G_UNLIKELY (len == 0)) {
7926       GST_LOG_OBJECT (qtdemux, "empty container");
7927       break;
7928     }
7929     if (G_UNLIKELY (len < 8)) {
7930       GST_WARNING_OBJECT (qtdemux, "length too short (%d < 8)", len);
7931       break;
7932     }
7933     if (G_UNLIKELY (len > (end - buf))) {
7934       GST_WARNING_OBJECT (qtdemux, "length too long (%d > %d)", len,
7935           (gint) (end - buf));
7936       break;
7937     }
7938
7939     child = g_node_new ((guint8 *) buf);
7940     g_node_append (node, child);
7941     GST_LOG_OBJECT (qtdemux, "adding new node of len %d", len);
7942     qtdemux_parse_node (qtdemux, child, buf, len);
7943
7944     buf += len;
7945   }
7946   return TRUE;
7947 }
7948
7949 static gboolean
7950 qtdemux_parse_theora_extension (GstQTDemux * qtdemux, QtDemuxStream * stream,
7951     GNode * xdxt)
7952 {
7953   int len = QT_UINT32 (xdxt->data);
7954   guint8 *buf = xdxt->data;
7955   guint8 *end = buf + len;
7956   GstBuffer *buffer;
7957
7958   /* skip size and type */
7959   buf += 8;
7960   end -= 8;
7961
7962   while (buf < end) {
7963     gint size;
7964     guint32 type;
7965
7966     size = QT_UINT32 (buf);
7967     type = QT_FOURCC (buf + 4);
7968
7969     GST_LOG_OBJECT (qtdemux, "%p %p", buf, end);
7970
7971     if (buf + size > end || size <= 0)
7972       break;
7973
7974     buf += 8;
7975     size -= 8;
7976
7977     GST_WARNING_OBJECT (qtdemux, "have cookie %" GST_FOURCC_FORMAT,
7978         GST_FOURCC_ARGS (type));
7979
7980     switch (type) {
7981       case FOURCC_tCtH:
7982         buffer = gst_buffer_new_and_alloc (size);
7983         gst_buffer_fill (buffer, 0, buf, size);
7984         stream->buffers = g_slist_append (stream->buffers, buffer);
7985         GST_LOG_OBJECT (qtdemux, "parsing theora header");
7986         break;
7987       case FOURCC_tCt_:
7988         buffer = gst_buffer_new_and_alloc (size);
7989         gst_buffer_fill (buffer, 0, buf, size);
7990         stream->buffers = g_slist_append (stream->buffers, buffer);
7991         GST_LOG_OBJECT (qtdemux, "parsing theora comment");
7992         break;
7993       case FOURCC_tCtC:
7994         buffer = gst_buffer_new_and_alloc (size);
7995         gst_buffer_fill (buffer, 0, buf, size);
7996         stream->buffers = g_slist_append (stream->buffers, buffer);
7997         GST_LOG_OBJECT (qtdemux, "parsing theora codebook");
7998         break;
7999       default:
8000         GST_WARNING_OBJECT (qtdemux,
8001             "unknown theora cookie %" GST_FOURCC_FORMAT,
8002             GST_FOURCC_ARGS (type));
8003         break;
8004     }
8005     buf += size;
8006   }
8007   return TRUE;
8008 }
8009
8010 static gboolean
8011 qtdemux_parse_node (GstQTDemux * qtdemux, GNode * node, const guint8 * buffer,
8012     guint length)
8013 {
8014   guint32 fourcc = 0;
8015   guint32 node_length = 0;
8016   const QtNodeType *type;
8017   const guint8 *end;
8018
8019   GST_LOG_OBJECT (qtdemux, "qtdemux_parse buffer %p length %u", buffer, length);
8020
8021   if (G_UNLIKELY (length < 8))
8022     goto not_enough_data;
8023
8024   node_length = QT_UINT32 (buffer);
8025   fourcc = QT_FOURCC (buffer + 4);
8026
8027   /* ignore empty nodes */
8028   if (G_UNLIKELY (fourcc == 0 || node_length == 8))
8029     return TRUE;
8030
8031   type = qtdemux_type_get (fourcc);
8032
8033   end = buffer + length;
8034
8035   GST_LOG_OBJECT (qtdemux,
8036       "parsing '%" GST_FOURCC_FORMAT "', length=%u, name '%s'",
8037       GST_FOURCC_ARGS (fourcc), node_length, type->name);
8038
8039   if (node_length > length)
8040     goto broken_atom_size;
8041
8042   if (type->flags & QT_FLAG_CONTAINER) {
8043     qtdemux_parse_container (qtdemux, node, buffer + 8, end);
8044   } else {
8045     switch (fourcc) {
8046       case FOURCC_stsd:
8047       {
8048         if (node_length < 20) {
8049           GST_LOG_OBJECT (qtdemux, "skipping small stsd box");
8050           break;
8051         }
8052         GST_DEBUG_OBJECT (qtdemux,
8053             "parsing stsd (sample table, sample description) atom");
8054         /* Skip over 8 byte atom hdr + 1 byte version, 3 bytes flags, 4 byte num_entries */
8055         qtdemux_parse_container (qtdemux, node, buffer + 16, end);
8056         break;
8057       }
8058       case FOURCC_mp4a:
8059       case FOURCC_alac:
8060       case FOURCC_fLaC:
8061       case FOURCC_aavd:
8062       {
8063         guint32 version;
8064         guint32 offset;
8065         guint min_size;
8066
8067         /* also read alac (or whatever) in stead of mp4a in the following,
8068          * since a similar layout is used in other cases as well */
8069         if (fourcc == FOURCC_mp4a)
8070           min_size = 20;
8071         else if (fourcc == FOURCC_fLaC)
8072           min_size = 86;
8073         else
8074           min_size = 40;
8075
8076         /* There are two things we might encounter here: a true mp4a atom, and
8077            an mp4a entry in an stsd atom. The latter is what we're interested
8078            in, and it looks like an atom, but isn't really one. The true mp4a
8079            atom is short, so we detect it based on length here. */
8080         if (length < min_size) {
8081           GST_LOG_OBJECT (qtdemux, "skipping small %" GST_FOURCC_FORMAT " box",
8082               GST_FOURCC_ARGS (fourcc));
8083           break;
8084         }
8085
8086         /* 'version' here is the sound sample description version. Types 0 and
8087            1 are documented in the QTFF reference, but type 2 is not: it's
8088            described in Apple header files instead (struct SoundDescriptionV2
8089            in Movies.h) */
8090         version = QT_UINT16 (buffer + 16);
8091
8092         GST_DEBUG_OBJECT (qtdemux, "%" GST_FOURCC_FORMAT " version 0x%08x",
8093             GST_FOURCC_ARGS (fourcc), version);
8094
8095         /* parse any esds descriptors */
8096         switch (version) {
8097           case 0:
8098             offset = 0x24;
8099             break;
8100           case 1:
8101             offset = 0x34;
8102             break;
8103           case 2:
8104             offset = 0x48;
8105             break;
8106           default:
8107             GST_WARNING_OBJECT (qtdemux,
8108                 "unhandled %" GST_FOURCC_FORMAT " version 0x%08x",
8109                 GST_FOURCC_ARGS (fourcc), version);
8110             offset = 0;
8111             break;
8112         }
8113         if (offset)
8114           qtdemux_parse_container (qtdemux, node, buffer + offset, end);
8115         break;
8116       }
8117       case FOURCC_mp4v:
8118       case FOURCC_MP4V:
8119       case FOURCC_fmp4:
8120       case FOURCC_FMP4:
8121       case FOURCC_apcs:
8122       case FOURCC_apch:
8123       case FOURCC_apcn:
8124       case FOURCC_apco:
8125       case FOURCC_ap4h:
8126       case FOURCC_xvid:
8127       case FOURCC_XVID:
8128       case FOURCC_H264:
8129       case FOURCC_avc1:
8130       case FOURCC_avc3:
8131       case FOURCC_H265:
8132       case FOURCC_hvc1:
8133       case FOURCC_hev1:
8134       case FOURCC_dvh1:
8135       case FOURCC_dvhe:
8136       case FOURCC_mjp2:
8137       case FOURCC_encv:
8138       {
8139         guint32 version;
8140         guint32 str_len;
8141
8142         /* codec_data is contained inside these atoms, which all have
8143          * the same format. */
8144         /* video sample description size is 86 bytes without extension.
8145          * node_length have to be bigger than 86 bytes because video sample
8146          * description can include extensions such as esds, fiel, glbl, etc. */
8147         if (node_length < 86) {
8148           GST_WARNING_OBJECT (qtdemux, "%" GST_FOURCC_FORMAT
8149               " sample description length too short (%u < 86)",
8150               GST_FOURCC_ARGS (fourcc), node_length);
8151           break;
8152         }
8153
8154         GST_DEBUG_OBJECT (qtdemux, "parsing in %" GST_FOURCC_FORMAT,
8155             GST_FOURCC_ARGS (fourcc));
8156
8157         /* version (2 bytes) : this is set to 0, unless a compressor has changed
8158          *              its data format.
8159          * revision level (2 bytes) : must be set to 0. */
8160         version = QT_UINT32 (buffer + 16);
8161         GST_DEBUG_OBJECT (qtdemux, "version %08x", version);
8162
8163         /* compressor name : PASCAL string and informative purposes
8164          * first byte : the number of bytes to be displayed.
8165          *              it has to be less than 32 because it is reserved
8166          *              space of 32 bytes total including itself. */
8167         str_len = QT_UINT8 (buffer + 50);
8168         if (str_len < 32)
8169           GST_DEBUG_OBJECT (qtdemux, "compressorname = %.*s", str_len,
8170               (char *) buffer + 51);
8171         else
8172           GST_WARNING_OBJECT (qtdemux,
8173               "compressorname length too big (%u > 31)", str_len);
8174
8175         GST_MEMDUMP_OBJECT (qtdemux, "video sample description", buffer,
8176             end - buffer);
8177         qtdemux_parse_container (qtdemux, node, buffer + 86, end);
8178         break;
8179       }
8180       case FOURCC_meta:
8181       {
8182         GST_DEBUG_OBJECT (qtdemux, "parsing meta atom");
8183
8184         /* You are reading this correctly. QTFF specifies that the
8185          * metadata atom is a short atom, whereas ISO BMFF specifies
8186          * it's a full atom. But since so many people are doing things
8187          * differently, we actually peek into the atom to see which
8188          * variant it is */
8189         if (length < 16) {
8190           GST_LOG_OBJECT (qtdemux, "skipping small %" GST_FOURCC_FORMAT " box",
8191               GST_FOURCC_ARGS (fourcc));
8192           break;
8193         }
8194         if (QT_FOURCC (buffer + 12) == FOURCC_hdlr) {
8195           /* Variant 1: What QTFF specifies. 'meta' is a short header which
8196            * starts with a 'hdlr' atom */
8197           qtdemux_parse_container (qtdemux, node, buffer + 8, end);
8198         } else if (QT_UINT32 (buffer + 8) == 0x00000000) {
8199           /* Variant 2: What ISO BMFF specifies. 'meta' is a _full_ atom
8200            * with version/flags both set to zero */
8201           qtdemux_parse_container (qtdemux, node, buffer + 12, end);
8202         } else
8203           GST_WARNING_OBJECT (qtdemux, "Unknown 'meta' atom format");
8204         break;
8205       }
8206       case FOURCC_mp4s:
8207       {
8208         GST_MEMDUMP_OBJECT (qtdemux, "mp4s", buffer, end - buffer);
8209         /* Skip 8 byte header, plus 8 byte version + flags + entry_count */
8210         qtdemux_parse_container (qtdemux, node, buffer + 16, end);
8211         break;
8212       }
8213       case FOURCC_XiTh:
8214       {
8215         guint32 version;
8216         guint32 offset;
8217
8218         if (length < 16) {
8219           GST_LOG_OBJECT (qtdemux, "skipping small %" GST_FOURCC_FORMAT " box",
8220               GST_FOURCC_ARGS (fourcc));
8221           break;
8222         }
8223
8224         version = QT_UINT32 (buffer + 12);
8225         GST_DEBUG_OBJECT (qtdemux, "parsing XiTh atom version 0x%08x", version);
8226
8227         switch (version) {
8228           case 0x00000001:
8229             offset = 0x62;
8230             break;
8231           default:
8232             GST_DEBUG_OBJECT (qtdemux, "unknown version 0x%08x", version);
8233             offset = 0;
8234             break;
8235         }
8236         if (offset) {
8237           if (length < offset) {
8238             GST_WARNING_OBJECT (qtdemux,
8239                 "skipping too small %" GST_FOURCC_FORMAT " box",
8240                 GST_FOURCC_ARGS (fourcc));
8241             break;
8242           }
8243           qtdemux_parse_container (qtdemux, node, buffer + offset, end);
8244         }
8245         break;
8246       }
8247       case FOURCC_in24:
8248       {
8249         qtdemux_parse_container (qtdemux, node, buffer + 0x34, end);
8250         break;
8251       }
8252       case FOURCC_uuid:
8253       {
8254         qtdemux_parse_uuid (qtdemux, buffer, end - buffer);
8255         break;
8256       }
8257       case FOURCC_enca:
8258       {
8259         qtdemux_parse_container (qtdemux, node, buffer + 36, end);
8260         break;
8261       }
8262       default:
8263         if (!strcmp (type->name, "unknown"))
8264           GST_MEMDUMP ("Unknown tag", buffer + 4, end - buffer - 4);
8265         break;
8266     }
8267   }
8268   GST_LOG_OBJECT (qtdemux, "parsed '%" GST_FOURCC_FORMAT "'",
8269       GST_FOURCC_ARGS (fourcc));
8270   return TRUE;
8271
8272 /* ERRORS */
8273 not_enough_data:
8274   {
8275     GST_ELEMENT_ERROR (qtdemux, STREAM, DEMUX,
8276         (_("This file is corrupt and cannot be played.")),
8277         ("Not enough data for an atom header, got only %u bytes", length));
8278     return FALSE;
8279   }
8280 broken_atom_size:
8281   {
8282     GST_ELEMENT_ERROR (qtdemux, STREAM, DEMUX,
8283         (_("This file is corrupt and cannot be played.")),
8284         ("Atom '%" GST_FOURCC_FORMAT "' has size of %u bytes, but we have only "
8285             "%u bytes available.", GST_FOURCC_ARGS (fourcc), node_length,
8286             length));
8287     return FALSE;
8288   }
8289 }
8290
8291 static void
8292 qtdemux_do_allocation (QtDemuxStream * stream, GstQTDemux * qtdemux)
8293 {
8294 /* FIXME: This can only reliably work if demuxers have a
8295  * separate streaming thread per srcpad. This should be
8296  * done in a demuxer base class, which integrates parts
8297  * of multiqueue
8298  *
8299  * https://bugzilla.gnome.org/show_bug.cgi?id=701856
8300  */
8301 #if 0
8302   GstQuery *query;
8303
8304   query = gst_query_new_allocation (stream->caps, FALSE);
8305
8306   if (!gst_pad_peer_query (stream->pad, query)) {
8307     /* not a problem, just debug a little */
8308     GST_DEBUG_OBJECT (qtdemux, "peer ALLOCATION query failed");
8309   }
8310
8311   if (stream->allocator)
8312     gst_object_unref (stream->allocator);
8313
8314   if (gst_query_get_n_allocation_params (query) > 0) {
8315     /* try the allocator */
8316     gst_query_parse_nth_allocation_param (query, 0, &stream->allocator,
8317         &stream->params);
8318     stream->use_allocator = TRUE;
8319   } else {
8320     stream->allocator = NULL;
8321     gst_allocation_params_init (&stream->params);
8322     stream->use_allocator = FALSE;
8323   }
8324   gst_query_unref (query);
8325 #endif
8326 }
8327
8328 static gboolean
8329 pad_query (const GValue * item, GValue * value, gpointer user_data)
8330 {
8331   GstPad *pad = g_value_get_object (item);
8332   GstQuery *query = user_data;
8333   gboolean res;
8334
8335   res = gst_pad_peer_query (pad, query);
8336
8337   if (res) {
8338     g_value_set_boolean (value, TRUE);
8339     return FALSE;
8340   }
8341
8342   GST_INFO_OBJECT (pad, "pad peer query failed");
8343   return TRUE;
8344 }
8345
8346 static gboolean
8347 gst_qtdemux_run_query (GstElement * element, GstQuery * query,
8348     GstPadDirection direction)
8349 {
8350   GstIterator *it;
8351   GstIteratorFoldFunction func = pad_query;
8352   GValue res = { 0, };
8353
8354   g_value_init (&res, G_TYPE_BOOLEAN);
8355   g_value_set_boolean (&res, FALSE);
8356
8357   /* Ask neighbor */
8358   if (direction == GST_PAD_SRC)
8359     it = gst_element_iterate_src_pads (element);
8360   else
8361     it = gst_element_iterate_sink_pads (element);
8362
8363   while (gst_iterator_fold (it, func, &res, query) == GST_ITERATOR_RESYNC)
8364     gst_iterator_resync (it);
8365
8366   gst_iterator_free (it);
8367
8368   return g_value_get_boolean (&res);
8369 }
8370
8371 static void
8372 gst_qtdemux_request_protection_context (GstQTDemux * qtdemux,
8373     QtDemuxStream * stream)
8374 {
8375   GstQuery *query;
8376   GstContext *ctxt;
8377   GstElement *element = GST_ELEMENT (qtdemux);
8378   GstStructure *st;
8379   gchar **filtered_sys_ids;
8380   GValue event_list = G_VALUE_INIT;
8381   GList *walk;
8382
8383   /* 1. Check if we already have the context. */
8384   if (qtdemux->preferred_protection_system_id != NULL) {
8385     GST_LOG_OBJECT (element,
8386         "already have the protection context, no need to request it again");
8387     return;
8388   }
8389
8390   g_ptr_array_add (qtdemux->protection_system_ids, NULL);
8391   filtered_sys_ids = gst_protection_filter_systems_by_available_decryptors (
8392       (const gchar **) qtdemux->protection_system_ids->pdata);
8393
8394   g_ptr_array_remove_index (qtdemux->protection_system_ids,
8395       qtdemux->protection_system_ids->len - 1);
8396   GST_TRACE_OBJECT (qtdemux, "detected %u protection systems, we have "
8397       "decryptors for %u of them, running context request",
8398       qtdemux->protection_system_ids->len,
8399       filtered_sys_ids ? g_strv_length (filtered_sys_ids) : 0);
8400
8401
8402   if (stream->protection_scheme_event_queue.length) {
8403     GST_TRACE_OBJECT (qtdemux, "using stream event queue, length %u",
8404         stream->protection_scheme_event_queue.length);
8405     walk = stream->protection_scheme_event_queue.tail;
8406   } else {
8407     GST_TRACE_OBJECT (qtdemux, "using demuxer event queue, length %u",
8408         qtdemux->protection_event_queue.length);
8409     walk = qtdemux->protection_event_queue.tail;
8410   }
8411
8412   g_value_init (&event_list, GST_TYPE_LIST);
8413   for (; walk; walk = g_list_previous (walk)) {
8414     GValue *event_value = g_new0 (GValue, 1);
8415     g_value_init (event_value, GST_TYPE_EVENT);
8416     g_value_set_boxed (event_value, walk->data);
8417     gst_value_list_append_and_take_value (&event_list, event_value);
8418   }
8419
8420   /*  2a) Query downstream with GST_QUERY_CONTEXT for the context and
8421    *      check if downstream already has a context of the specific type
8422    *  2b) Query upstream as above.
8423    */
8424   query = gst_query_new_context ("drm-preferred-decryption-system-id");
8425   st = gst_query_writable_structure (query);
8426   gst_structure_set (st, "track-id", G_TYPE_UINT, stream->track_id,
8427       "available-stream-encryption-systems", G_TYPE_STRV, filtered_sys_ids,
8428       NULL);
8429   gst_structure_set_value (st, "stream-encryption-events", &event_list);
8430   if (gst_qtdemux_run_query (element, query, GST_PAD_SRC)) {
8431     gst_query_parse_context (query, &ctxt);
8432     GST_INFO_OBJECT (element, "found context (%p) in downstream query", ctxt);
8433     gst_element_set_context (element, ctxt);
8434   } else if (gst_qtdemux_run_query (element, query, GST_PAD_SINK)) {
8435     gst_query_parse_context (query, &ctxt);
8436     GST_INFO_OBJECT (element, "found context (%p) in upstream query", ctxt);
8437     gst_element_set_context (element, ctxt);
8438   } else {
8439     /* 3) Post a GST_MESSAGE_NEED_CONTEXT message on the bus with
8440      *    the required context type and afterwards check if a
8441      *    usable context was set now as in 1). The message could
8442      *    be handled by the parent bins of the element and the
8443      *    application.
8444      */
8445     GstMessage *msg;
8446
8447     GST_INFO_OBJECT (element, "posting need context message");
8448     msg = gst_message_new_need_context (GST_OBJECT_CAST (element),
8449         "drm-preferred-decryption-system-id");
8450     st = (GstStructure *) gst_message_get_structure (msg);
8451     gst_structure_set (st, "track-id", G_TYPE_UINT, stream->track_id,
8452         "available-stream-encryption-systems", G_TYPE_STRV, filtered_sys_ids,
8453         NULL);
8454
8455     gst_structure_set_value (st, "stream-encryption-events", &event_list);
8456     gst_element_post_message (element, msg);
8457   }
8458
8459   g_strfreev (filtered_sys_ids);
8460   g_value_unset (&event_list);
8461   gst_query_unref (query);
8462 }
8463
8464 static gboolean
8465 gst_qtdemux_configure_protected_caps (GstQTDemux * qtdemux,
8466     QtDemuxStream * stream)
8467 {
8468   GstStructure *s;
8469   const gchar *selected_system = NULL;
8470
8471   g_return_val_if_fail (qtdemux != NULL, FALSE);
8472   g_return_val_if_fail (stream != NULL, FALSE);
8473   g_return_val_if_fail (gst_caps_get_size (CUR_STREAM (stream)->caps) == 1,
8474       FALSE);
8475
8476   if (stream->protection_scheme_type == FOURCC_aavd) {
8477     s = gst_caps_get_structure (CUR_STREAM (stream)->caps, 0);
8478     if (!gst_structure_has_name (s, "application/x-aavd")) {
8479       gst_structure_set (s,
8480           "original-media-type", G_TYPE_STRING, gst_structure_get_name (s),
8481           NULL);
8482       gst_structure_set_name (s, "application/x-aavd");
8483     }
8484     return TRUE;
8485   }
8486
8487   if (stream->protection_scheme_type != FOURCC_cenc
8488       && stream->protection_scheme_type != FOURCC_cbcs) {
8489     GST_ERROR_OBJECT (qtdemux,
8490         "unsupported protection scheme: %" GST_FOURCC_FORMAT,
8491         GST_FOURCC_ARGS (stream->protection_scheme_type));
8492     return FALSE;
8493   }
8494
8495   s = gst_caps_get_structure (CUR_STREAM (stream)->caps, 0);
8496   if (!gst_structure_has_name (s, "application/x-cenc")) {
8497     gst_structure_set (s,
8498         "original-media-type", G_TYPE_STRING, gst_structure_get_name (s), NULL);
8499     gst_structure_set (s, "cipher-mode", G_TYPE_STRING,
8500         (stream->protection_scheme_type == FOURCC_cbcs) ? "cbcs" : "cenc",
8501         NULL);
8502     gst_structure_set_name (s, "application/x-cenc");
8503   }
8504
8505   if (qtdemux->protection_system_ids == NULL) {
8506     GST_DEBUG_OBJECT (qtdemux, "stream is protected using cenc, but no "
8507         "cenc protection system information has been found, not setting a "
8508         "protection system UUID");
8509     return TRUE;
8510   }
8511
8512   gst_qtdemux_request_protection_context (qtdemux, stream);
8513   if (qtdemux->preferred_protection_system_id != NULL) {
8514     const gchar *preferred_system_array[] =
8515         { qtdemux->preferred_protection_system_id, NULL };
8516
8517     selected_system = gst_protection_select_system (preferred_system_array);
8518
8519     if (selected_system) {
8520       GST_TRACE_OBJECT (qtdemux, "selected preferred system %s",
8521           qtdemux->preferred_protection_system_id);
8522     } else {
8523       GST_WARNING_OBJECT (qtdemux, "could not select preferred system %s "
8524           "because there is no available decryptor",
8525           qtdemux->preferred_protection_system_id);
8526     }
8527   }
8528
8529   if (!selected_system) {
8530     g_ptr_array_add (qtdemux->protection_system_ids, NULL);
8531     selected_system = gst_protection_select_system ((const gchar **)
8532         qtdemux->protection_system_ids->pdata);
8533     g_ptr_array_remove_index (qtdemux->protection_system_ids,
8534         qtdemux->protection_system_ids->len - 1);
8535   }
8536
8537   if (!selected_system) {
8538     GST_ERROR_OBJECT (qtdemux, "stream is protected, but no "
8539         "suitable decryptor element has been found");
8540     return FALSE;
8541   }
8542
8543   GST_DEBUG_OBJECT (qtdemux, "selected protection system is %s",
8544       selected_system);
8545
8546   gst_structure_set (s,
8547       GST_PROTECTION_SYSTEM_ID_CAPS_FIELD, G_TYPE_STRING, selected_system,
8548       NULL);
8549
8550   return TRUE;
8551 }
8552
8553 static gboolean
8554 gst_qtdemux_guess_framerate (GstQTDemux * qtdemux, QtDemuxStream * stream)
8555 {
8556   /* fps is calculated base on the duration of the average framerate since
8557    * qt does not have a fixed framerate. */
8558   gboolean fps_available = TRUE;
8559   guint32 first_duration = 0;
8560
8561   if (stream->n_samples > 0)
8562     first_duration = stream->samples[0].duration;
8563
8564   if ((stream->n_samples == 1 && first_duration == 0)
8565       || (qtdemux->fragmented && stream->n_samples_moof == 1)) {
8566     /* still frame */
8567     CUR_STREAM (stream)->fps_n = 0;
8568     CUR_STREAM (stream)->fps_d = 1;
8569   } else {
8570     if (stream->duration == 0 || stream->n_samples < 2) {
8571       CUR_STREAM (stream)->fps_n = stream->timescale;
8572       CUR_STREAM (stream)->fps_d = 1;
8573       fps_available = FALSE;
8574     } else {
8575       GstClockTime avg_duration;
8576       guint64 duration;
8577       guint32 n_samples;
8578
8579       /* duration and n_samples can be updated for fragmented format
8580        * so, framerate of fragmented format is calculated using data in a moof */
8581       if (qtdemux->fragmented && stream->n_samples_moof > 0
8582           && stream->duration_moof > 0) {
8583         n_samples = stream->n_samples_moof;
8584         duration = stream->duration_moof;
8585       } else {
8586         n_samples = stream->n_samples;
8587         duration = stream->duration;
8588       }
8589
8590       /* Calculate a framerate, ignoring the first sample which is sometimes truncated */
8591       /* stream->duration is guint64, timescale, n_samples are guint32 */
8592       avg_duration =
8593           gst_util_uint64_scale_round (duration -
8594           first_duration, GST_SECOND,
8595           (guint64) (stream->timescale) * (n_samples - 1));
8596
8597       GST_LOG_OBJECT (qtdemux,
8598           "Calculating avg sample duration based on stream (or moof) duration %"
8599           G_GUINT64_FORMAT
8600           " minus first sample %u, leaving %d samples gives %"
8601           GST_TIME_FORMAT, duration, first_duration,
8602           n_samples - 1, GST_TIME_ARGS (avg_duration));
8603
8604       fps_available =
8605           gst_video_guess_framerate (avg_duration,
8606           &CUR_STREAM (stream)->fps_n, &CUR_STREAM (stream)->fps_d);
8607
8608       GST_DEBUG_OBJECT (qtdemux,
8609           "Calculating framerate, timescale %u gave fps_n %d fps_d %d",
8610           stream->timescale, CUR_STREAM (stream)->fps_n,
8611           CUR_STREAM (stream)->fps_d);
8612     }
8613   }
8614
8615   return fps_available;
8616 }
8617
8618 static gboolean
8619 gst_qtdemux_configure_stream (GstQTDemux * qtdemux, QtDemuxStream * stream)
8620 {
8621   if (stream->subtype == FOURCC_vide) {
8622     gboolean fps_available = gst_qtdemux_guess_framerate (qtdemux, stream);
8623
8624     if (CUR_STREAM (stream)->caps) {
8625       CUR_STREAM (stream)->caps =
8626           gst_caps_make_writable (CUR_STREAM (stream)->caps);
8627
8628       if (CUR_STREAM (stream)->width && CUR_STREAM (stream)->height)
8629         gst_caps_set_simple (CUR_STREAM (stream)->caps,
8630             "width", G_TYPE_INT, CUR_STREAM (stream)->width,
8631             "height", G_TYPE_INT, CUR_STREAM (stream)->height, NULL);
8632
8633       /* set framerate if calculated framerate is reliable */
8634       if (fps_available) {
8635         gst_caps_set_simple (CUR_STREAM (stream)->caps,
8636             "framerate", GST_TYPE_FRACTION, CUR_STREAM (stream)->fps_n,
8637             CUR_STREAM (stream)->fps_d, NULL);
8638       }
8639
8640       /* calculate pixel-aspect-ratio using display width and height */
8641       GST_DEBUG_OBJECT (qtdemux,
8642           "video size %dx%d, target display size %dx%d",
8643           CUR_STREAM (stream)->width, CUR_STREAM (stream)->height,
8644           stream->display_width, stream->display_height);
8645       /* qt file might have pasp atom */
8646       if (CUR_STREAM (stream)->par_w > 0 && CUR_STREAM (stream)->par_h > 0) {
8647         GST_DEBUG_OBJECT (qtdemux, "par %d:%d", CUR_STREAM (stream)->par_w,
8648             CUR_STREAM (stream)->par_h);
8649         gst_caps_set_simple (CUR_STREAM (stream)->caps, "pixel-aspect-ratio",
8650             GST_TYPE_FRACTION, CUR_STREAM (stream)->par_w,
8651             CUR_STREAM (stream)->par_h, NULL);
8652       } else if (stream->display_width > 0 && stream->display_height > 0
8653           && CUR_STREAM (stream)->width > 0
8654           && CUR_STREAM (stream)->height > 0) {
8655         gint n, d;
8656
8657         /* calculate the pixel aspect ratio using the display and pixel w/h */
8658         n = stream->display_width * CUR_STREAM (stream)->height;
8659         d = stream->display_height * CUR_STREAM (stream)->width;
8660         if (n == d)
8661           n = d = 1;
8662         GST_DEBUG_OBJECT (qtdemux, "setting PAR to %d/%d", n, d);
8663         CUR_STREAM (stream)->par_w = n;
8664         CUR_STREAM (stream)->par_h = d;
8665         gst_caps_set_simple (CUR_STREAM (stream)->caps, "pixel-aspect-ratio",
8666             GST_TYPE_FRACTION, CUR_STREAM (stream)->par_w,
8667             CUR_STREAM (stream)->par_h, NULL);
8668       }
8669
8670       if (CUR_STREAM (stream)->interlace_mode > 0) {
8671         if (CUR_STREAM (stream)->interlace_mode == 1) {
8672           gst_caps_set_simple (CUR_STREAM (stream)->caps, "interlace-mode",
8673               G_TYPE_STRING, "progressive", NULL);
8674         } else if (CUR_STREAM (stream)->interlace_mode == 2) {
8675           gst_caps_set_simple (CUR_STREAM (stream)->caps, "interlace-mode",
8676               G_TYPE_STRING, "interleaved", NULL);
8677           if (CUR_STREAM (stream)->field_order == 9) {
8678             gst_caps_set_simple (CUR_STREAM (stream)->caps, "field-order",
8679                 G_TYPE_STRING, "top-field-first", NULL);
8680           } else if (CUR_STREAM (stream)->field_order == 14) {
8681             gst_caps_set_simple (CUR_STREAM (stream)->caps, "field-order",
8682                 G_TYPE_STRING, "bottom-field-first", NULL);
8683           }
8684         }
8685       }
8686
8687       /* Create incomplete colorimetry here if needed */
8688       if (CUR_STREAM (stream)->colorimetry.range ||
8689           CUR_STREAM (stream)->colorimetry.matrix ||
8690           CUR_STREAM (stream)->colorimetry.transfer
8691           || CUR_STREAM (stream)->colorimetry.primaries) {
8692         gchar *colorimetry =
8693             gst_video_colorimetry_to_string (&CUR_STREAM (stream)->colorimetry);
8694         gst_caps_set_simple (CUR_STREAM (stream)->caps, "colorimetry",
8695             G_TYPE_STRING, colorimetry, NULL);
8696         g_free (colorimetry);
8697       }
8698
8699       if (stream->multiview_mode != GST_VIDEO_MULTIVIEW_MODE_NONE) {
8700         guint par_w = 1, par_h = 1;
8701
8702         if (CUR_STREAM (stream)->par_w > 0 && CUR_STREAM (stream)->par_h > 0) {
8703           par_w = CUR_STREAM (stream)->par_w;
8704           par_h = CUR_STREAM (stream)->par_h;
8705         }
8706
8707         if (gst_video_multiview_guess_half_aspect (stream->multiview_mode,
8708                 CUR_STREAM (stream)->width, CUR_STREAM (stream)->height, par_w,
8709                 par_h)) {
8710           stream->multiview_flags |= GST_VIDEO_MULTIVIEW_FLAGS_HALF_ASPECT;
8711         }
8712
8713         gst_caps_set_simple (CUR_STREAM (stream)->caps,
8714             "multiview-mode", G_TYPE_STRING,
8715             gst_video_multiview_mode_to_caps_string (stream->multiview_mode),
8716             "multiview-flags", GST_TYPE_VIDEO_MULTIVIEW_FLAGSET,
8717             stream->multiview_flags, GST_FLAG_SET_MASK_EXACT, NULL);
8718       }
8719     }
8720   }
8721
8722   else if (stream->subtype == FOURCC_soun) {
8723     if (CUR_STREAM (stream)->caps) {
8724       CUR_STREAM (stream)->caps =
8725           gst_caps_make_writable (CUR_STREAM (stream)->caps);
8726       if (CUR_STREAM (stream)->rate > 0)
8727         gst_caps_set_simple (CUR_STREAM (stream)->caps,
8728             "rate", G_TYPE_INT, (int) CUR_STREAM (stream)->rate, NULL);
8729       if (CUR_STREAM (stream)->n_channels > 0)
8730         gst_caps_set_simple (CUR_STREAM (stream)->caps,
8731             "channels", G_TYPE_INT, CUR_STREAM (stream)->n_channels, NULL);
8732       if (CUR_STREAM (stream)->n_channels > 2) {
8733         /* FIXME: Need to parse the 'chan' atom to get channel layouts
8734          * correctly; this is just the minimum we can do - assume
8735          * we don't actually have any channel positions. */
8736         gst_caps_set_simple (CUR_STREAM (stream)->caps,
8737             "channel-mask", GST_TYPE_BITMASK, G_GUINT64_CONSTANT (0), NULL);
8738       }
8739     }
8740   }
8741
8742   else if (stream->subtype == FOURCC_clcp && CUR_STREAM (stream)->caps) {
8743     const GstStructure *s;
8744     QtDemuxStream *fps_stream = NULL;
8745     gboolean fps_available = FALSE;
8746
8747     /* CEA608 closed caption tracks are a bit special in that each sample
8748      * can contain CCs for multiple frames, and CCs can be omitted and have to
8749      * be inferred from the duration of the sample then.
8750      *
8751      * As such we take the framerate from the (first) video track here for
8752      * CEA608 as there must be one CC byte pair for every video frame
8753      * according to the spec.
8754      *
8755      * For CEA708 all is fine and there is one sample per frame.
8756      */
8757
8758     s = gst_caps_get_structure (CUR_STREAM (stream)->caps, 0);
8759     if (gst_structure_has_name (s, "closedcaption/x-cea-608")) {
8760       gint i;
8761
8762       for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
8763         QtDemuxStream *tmp = QTDEMUX_NTH_STREAM (qtdemux, i);
8764
8765         if (tmp->subtype == FOURCC_vide) {
8766           fps_stream = tmp;
8767           break;
8768         }
8769       }
8770
8771       if (fps_stream) {
8772         fps_available = gst_qtdemux_guess_framerate (qtdemux, fps_stream);
8773         CUR_STREAM (stream)->fps_n = CUR_STREAM (fps_stream)->fps_n;
8774         CUR_STREAM (stream)->fps_d = CUR_STREAM (fps_stream)->fps_d;
8775       }
8776     } else {
8777       fps_available = gst_qtdemux_guess_framerate (qtdemux, stream);
8778       fps_stream = stream;
8779     }
8780
8781     CUR_STREAM (stream)->caps =
8782         gst_caps_make_writable (CUR_STREAM (stream)->caps);
8783
8784     /* set framerate if calculated framerate is reliable */
8785     if (fps_available) {
8786       gst_caps_set_simple (CUR_STREAM (stream)->caps,
8787           "framerate", GST_TYPE_FRACTION, CUR_STREAM (stream)->fps_n,
8788           CUR_STREAM (stream)->fps_d, NULL);
8789     }
8790   }
8791
8792   if (stream->pad) {
8793     GstCaps *prev_caps = NULL;
8794
8795     GST_PAD_ELEMENT_PRIVATE (stream->pad) = stream;
8796     gst_pad_set_event_function (stream->pad, gst_qtdemux_handle_src_event);
8797     gst_pad_set_query_function (stream->pad, gst_qtdemux_handle_src_query);
8798     gst_pad_set_active (stream->pad, TRUE);
8799
8800     gst_pad_use_fixed_caps (stream->pad);
8801
8802     if (stream->protected) {
8803       if (!gst_qtdemux_configure_protected_caps (qtdemux, stream)) {
8804         GST_ERROR_OBJECT (qtdemux,
8805             "Failed to configure protected stream caps.");
8806         return FALSE;
8807       }
8808     }
8809
8810     GST_DEBUG_OBJECT (qtdemux, "setting caps %" GST_PTR_FORMAT,
8811         CUR_STREAM (stream)->caps);
8812     if (stream->new_stream) {
8813       GstEvent *event;
8814       GstStreamFlags stream_flags = GST_STREAM_FLAG_NONE;
8815
8816       event =
8817           gst_pad_get_sticky_event (qtdemux->sinkpad, GST_EVENT_STREAM_START,
8818           0);
8819       if (event) {
8820         gst_event_parse_stream_flags (event, &stream_flags);
8821         if (gst_event_parse_group_id (event, &qtdemux->group_id))
8822           qtdemux->have_group_id = TRUE;
8823         else
8824           qtdemux->have_group_id = FALSE;
8825         gst_event_unref (event);
8826       } else if (!qtdemux->have_group_id) {
8827         qtdemux->have_group_id = TRUE;
8828         qtdemux->group_id = gst_util_group_id_next ();
8829       }
8830
8831       stream->new_stream = FALSE;
8832       event = gst_event_new_stream_start (stream->stream_id);
8833       if (qtdemux->have_group_id)
8834         gst_event_set_group_id (event, qtdemux->group_id);
8835       if (stream->disabled)
8836         stream_flags |= GST_STREAM_FLAG_UNSELECT;
8837       if (CUR_STREAM (stream)->sparse) {
8838         stream_flags |= GST_STREAM_FLAG_SPARSE;
8839       } else {
8840         stream_flags &= ~GST_STREAM_FLAG_SPARSE;
8841       }
8842       gst_event_set_stream_flags (event, stream_flags);
8843       gst_pad_push_event (stream->pad, event);
8844     }
8845
8846     prev_caps = gst_pad_get_current_caps (stream->pad);
8847
8848     if (CUR_STREAM (stream)->caps) {
8849       if (!prev_caps
8850           || !gst_caps_is_equal_fixed (prev_caps, CUR_STREAM (stream)->caps)) {
8851         GST_DEBUG_OBJECT (qtdemux, "setting caps %" GST_PTR_FORMAT,
8852             CUR_STREAM (stream)->caps);
8853         gst_pad_set_caps (stream->pad, CUR_STREAM (stream)->caps);
8854       } else {
8855         GST_DEBUG_OBJECT (qtdemux, "ignore duplicated caps");
8856       }
8857     } else {
8858       GST_WARNING_OBJECT (qtdemux, "stream without caps");
8859     }
8860
8861     if (prev_caps)
8862       gst_caps_unref (prev_caps);
8863     stream->new_caps = FALSE;
8864   }
8865   return TRUE;
8866 }
8867
8868 static void
8869 gst_qtdemux_stream_check_and_change_stsd_index (GstQTDemux * demux,
8870     QtDemuxStream * stream)
8871 {
8872   if (stream->cur_stsd_entry_index == stream->stsd_sample_description_id)
8873     return;
8874
8875   GST_DEBUG_OBJECT (stream->pad, "Changing stsd index from '%u' to '%u'",
8876       stream->cur_stsd_entry_index, stream->stsd_sample_description_id);
8877   if (G_UNLIKELY (stream->stsd_sample_description_id >=
8878           stream->stsd_entries_length)) {
8879     GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
8880         (_("This file is invalid and cannot be played.")),
8881         ("New sample description id is out of bounds (%d >= %d)",
8882             stream->stsd_sample_description_id, stream->stsd_entries_length));
8883   } else {
8884     stream->cur_stsd_entry_index = stream->stsd_sample_description_id;
8885     stream->new_caps = TRUE;
8886   }
8887 }
8888
8889 static gboolean
8890 gst_qtdemux_add_stream (GstQTDemux * qtdemux,
8891     QtDemuxStream * stream, GstTagList * list)
8892 {
8893   gboolean ret = TRUE;
8894
8895   if (stream->subtype == FOURCC_vide) {
8896     gchar *name = g_strdup_printf ("video_%u", qtdemux->n_video_streams);
8897
8898     stream->pad =
8899         gst_pad_new_from_static_template (&gst_qtdemux_videosrc_template, name);
8900     g_free (name);
8901
8902     if (!gst_qtdemux_configure_stream (qtdemux, stream)) {
8903       gst_object_unref (stream->pad);
8904       stream->pad = NULL;
8905       ret = FALSE;
8906       goto done;
8907     }
8908
8909     qtdemux->n_video_streams++;
8910   } else if (stream->subtype == FOURCC_soun) {
8911     gchar *name = g_strdup_printf ("audio_%u", qtdemux->n_audio_streams);
8912
8913     stream->pad =
8914         gst_pad_new_from_static_template (&gst_qtdemux_audiosrc_template, name);
8915     g_free (name);
8916     if (!gst_qtdemux_configure_stream (qtdemux, stream)) {
8917       gst_object_unref (stream->pad);
8918       stream->pad = NULL;
8919       ret = FALSE;
8920       goto done;
8921     }
8922     qtdemux->n_audio_streams++;
8923   } else if (stream->subtype == FOURCC_strm) {
8924     GST_DEBUG_OBJECT (qtdemux, "stream type, not creating pad");
8925   } else if (stream->subtype == FOURCC_subp || stream->subtype == FOURCC_text
8926       || stream->subtype == FOURCC_sbtl || stream->subtype == FOURCC_subt
8927       || stream->subtype == FOURCC_clcp || stream->subtype == FOURCC_wvtt) {
8928     gchar *name = g_strdup_printf ("subtitle_%u", qtdemux->n_sub_streams);
8929
8930     stream->pad =
8931         gst_pad_new_from_static_template (&gst_qtdemux_subsrc_template, name);
8932     g_free (name);
8933     if (!gst_qtdemux_configure_stream (qtdemux, stream)) {
8934       gst_object_unref (stream->pad);
8935       stream->pad = NULL;
8936       ret = FALSE;
8937       goto done;
8938     }
8939     qtdemux->n_sub_streams++;
8940   } else if (CUR_STREAM (stream)->caps) {
8941     gchar *name = g_strdup_printf ("video_%u", qtdemux->n_video_streams);
8942
8943     stream->pad =
8944         gst_pad_new_from_static_template (&gst_qtdemux_videosrc_template, name);
8945     g_free (name);
8946     if (!gst_qtdemux_configure_stream (qtdemux, stream)) {
8947       gst_object_unref (stream->pad);
8948       stream->pad = NULL;
8949       ret = FALSE;
8950       goto done;
8951     }
8952     qtdemux->n_video_streams++;
8953   } else {
8954     GST_DEBUG_OBJECT (qtdemux, "unknown stream type");
8955     goto done;
8956   }
8957
8958   if (stream->pad) {
8959     GList *l;
8960
8961     GST_DEBUG_OBJECT (qtdemux, "adding pad %s %p to qtdemux %p",
8962         GST_OBJECT_NAME (stream->pad), stream->pad, qtdemux);
8963     gst_element_add_pad (GST_ELEMENT_CAST (qtdemux), stream->pad);
8964     GST_OBJECT_LOCK (qtdemux);
8965     gst_flow_combiner_add_pad (qtdemux->flowcombiner, stream->pad);
8966     GST_OBJECT_UNLOCK (qtdemux);
8967
8968     if (stream->stream_tags)
8969       gst_tag_list_unref (stream->stream_tags);
8970     stream->stream_tags = list;
8971     list = NULL;
8972     /* global tags go on each pad anyway */
8973     stream->send_global_tags = TRUE;
8974     /* send upstream GST_EVENT_PROTECTION events that were received before
8975        this source pad was created */
8976     for (l = qtdemux->protection_event_queue.head; l != NULL; l = l->next)
8977       gst_pad_push_event (stream->pad, gst_event_ref (l->data));
8978   }
8979 done:
8980   if (list)
8981     gst_tag_list_unref (list);
8982   return ret;
8983 }
8984
8985 /* find next atom with @fourcc starting at @offset */
8986 static GstFlowReturn
8987 qtdemux_find_atom (GstQTDemux * qtdemux, guint64 * offset,
8988     guint64 * length, guint32 fourcc)
8989 {
8990   GstFlowReturn ret;
8991   guint32 lfourcc;
8992   GstBuffer *buf;
8993
8994   GST_LOG_OBJECT (qtdemux, "finding fourcc %" GST_FOURCC_FORMAT " at offset %"
8995       G_GUINT64_FORMAT, GST_FOURCC_ARGS (fourcc), *offset);
8996
8997   while (TRUE) {
8998     GstMapInfo map;
8999
9000     buf = NULL;
9001     ret = gst_pad_pull_range (qtdemux->sinkpad, *offset, 16, &buf);
9002     if (G_UNLIKELY (ret != GST_FLOW_OK))
9003       goto locate_failed;
9004     if (G_UNLIKELY (gst_buffer_get_size (buf) != 16)) {
9005       /* likely EOF */
9006       ret = GST_FLOW_EOS;
9007       gst_buffer_unref (buf);
9008       goto locate_failed;
9009     }
9010     gst_buffer_map (buf, &map, GST_MAP_READ);
9011     extract_initial_length_and_fourcc (map.data, 16, length, &lfourcc);
9012     gst_buffer_unmap (buf, &map);
9013     gst_buffer_unref (buf);
9014
9015     if (G_UNLIKELY (*length == 0)) {
9016       GST_DEBUG_OBJECT (qtdemux, "invalid length 0");
9017       ret = GST_FLOW_ERROR;
9018       goto locate_failed;
9019     }
9020
9021     if (lfourcc == fourcc) {
9022       GST_DEBUG_OBJECT (qtdemux, "found '%" GST_FOURCC_FORMAT " at offset %"
9023           G_GUINT64_FORMAT, GST_FOURCC_ARGS (fourcc), *offset);
9024       break;
9025     } else {
9026       GST_LOG_OBJECT (qtdemux,
9027           "skipping atom '%" GST_FOURCC_FORMAT "' at %" G_GUINT64_FORMAT,
9028           GST_FOURCC_ARGS (lfourcc), *offset);
9029       if (*offset == G_MAXUINT64)
9030         goto locate_failed;
9031       *offset += *length;
9032     }
9033   }
9034
9035   return GST_FLOW_OK;
9036
9037 locate_failed:
9038   {
9039     /* might simply have had last one */
9040     GST_DEBUG_OBJECT (qtdemux, "fourcc not found");
9041     return ret;
9042   }
9043 }
9044
9045 /* should only do something in pull mode */
9046 /* call with OBJECT lock */
9047 static GstFlowReturn
9048 qtdemux_add_fragmented_samples (GstQTDemux * qtdemux)
9049 {
9050   guint64 length, offset;
9051   GstBuffer *buf = NULL;
9052   GstFlowReturn ret = GST_FLOW_OK;
9053   GstFlowReturn res = GST_FLOW_OK;
9054   GstMapInfo map;
9055
9056   offset = qtdemux->moof_offset;
9057   GST_DEBUG_OBJECT (qtdemux, "next moof at offset %" G_GUINT64_FORMAT, offset);
9058
9059   if (!offset) {
9060     GST_DEBUG_OBJECT (qtdemux, "no next moof");
9061     return GST_FLOW_EOS;
9062   }
9063
9064   /* best not do pull etc with lock held */
9065   GST_OBJECT_UNLOCK (qtdemux);
9066
9067   ret = qtdemux_find_atom (qtdemux, &offset, &length, FOURCC_moof);
9068   if (ret != GST_FLOW_OK)
9069     goto flow_failed;
9070
9071   ret = gst_qtdemux_pull_atom (qtdemux, offset, length, &buf);
9072   if (G_UNLIKELY (ret != GST_FLOW_OK))
9073     goto flow_failed;
9074   gst_buffer_map (buf, &map, GST_MAP_READ);
9075   if (!qtdemux_parse_moof (qtdemux, map.data, map.size, offset, NULL)) {
9076     gst_buffer_unmap (buf, &map);
9077     gst_buffer_unref (buf);
9078     buf = NULL;
9079     goto parse_failed;
9080   }
9081
9082   gst_buffer_unmap (buf, &map);
9083   gst_buffer_unref (buf);
9084   buf = NULL;
9085
9086   offset += length;
9087   /* look for next moof */
9088   ret = qtdemux_find_atom (qtdemux, &offset, &length, FOURCC_moof);
9089   if (G_UNLIKELY (ret != GST_FLOW_OK))
9090     goto flow_failed;
9091
9092 exit:
9093   GST_OBJECT_LOCK (qtdemux);
9094
9095   qtdemux->moof_offset = offset;
9096
9097   return res;
9098
9099 parse_failed:
9100   {
9101     GST_DEBUG_OBJECT (qtdemux, "failed to parse moof");
9102     offset = 0;
9103     res = GST_FLOW_ERROR;
9104     goto exit;
9105   }
9106 flow_failed:
9107   {
9108     /* maybe upstream temporarily flushing */
9109     if (ret != GST_FLOW_FLUSHING) {
9110       GST_DEBUG_OBJECT (qtdemux, "no next moof");
9111       offset = 0;
9112     } else {
9113       GST_DEBUG_OBJECT (qtdemux, "upstream WRONG_STATE");
9114       /* resume at current position next time */
9115     }
9116     res = ret;
9117     goto exit;
9118   }
9119 }
9120
9121 static void
9122 qtdemux_merge_sample_table (GstQTDemux * qtdemux, QtDemuxStream * stream)
9123 {
9124   guint i;
9125   guint32 num_chunks;
9126   gint32 stts_duration;
9127   GstByteWriter stsc, stts, stsz;
9128
9129   /* Each sample has a different size, which we don't support for merging */
9130   if (stream->sample_size == 0) {
9131     GST_DEBUG_OBJECT (qtdemux,
9132         "Not all samples have the same size, not merging");
9133     return;
9134   }
9135
9136   /* The stream has a ctts table, we don't support that */
9137   if (stream->ctts_present) {
9138     GST_DEBUG_OBJECT (qtdemux, "Have ctts, not merging");
9139     return;
9140   }
9141
9142   /* If there's a sync sample table also ignore this stream */
9143   if (stream->stps_present || stream->stss_present) {
9144     GST_DEBUG_OBJECT (qtdemux, "Have stss/stps, not merging");
9145     return;
9146   }
9147
9148   /* If chunks are considered samples already ignore this stream */
9149   if (stream->chunks_are_samples) {
9150     GST_DEBUG_OBJECT (qtdemux, "Chunks are samples, not merging");
9151     return;
9152   }
9153
9154   /* Require that all samples have the same duration */
9155   if (stream->n_sample_times > 1) {
9156     GST_DEBUG_OBJECT (qtdemux, "Not all samples have the same duration");
9157     return;
9158   }
9159
9160   /* Parse the stts to get the sample duration and number of samples */
9161   gst_byte_reader_skip_unchecked (&stream->stts, 4);
9162   stts_duration = gst_byte_reader_get_uint32_be_unchecked (&stream->stts);
9163
9164   /* Parse the number of chunks from the stco manually because the
9165    * reader is already behind that */
9166   num_chunks = GST_READ_UINT32_BE (stream->stco.data + 4);
9167
9168   GST_DEBUG_OBJECT (qtdemux, "sample_duration %d, num_chunks %u", stts_duration,
9169       num_chunks);
9170
9171   /* Now parse stsc, convert chunks into single samples and generate a
9172    * new stsc, stts and stsz from this information */
9173   gst_byte_writer_init (&stsc);
9174   gst_byte_writer_init (&stts);
9175   gst_byte_writer_init (&stsz);
9176
9177   /* Note: we skip fourccs, size, version, flags and other fields of the new
9178    * atoms as the byte readers with them are already behind that position
9179    * anyway and only update the values of those inside the stream directly.
9180    */
9181   stream->n_sample_times = 0;
9182   stream->n_samples = 0;
9183   for (i = 0; i < stream->n_samples_per_chunk; i++) {
9184     guint j;
9185     guint32 first_chunk, last_chunk, samples_per_chunk, sample_description_id;
9186
9187     first_chunk = gst_byte_reader_get_uint32_be_unchecked (&stream->stsc);
9188     samples_per_chunk = gst_byte_reader_get_uint32_be_unchecked (&stream->stsc);
9189     sample_description_id =
9190         gst_byte_reader_get_uint32_be_unchecked (&stream->stsc);
9191
9192     if (i == stream->n_samples_per_chunk - 1) {
9193       /* +1 because first_chunk is 1-based */
9194       last_chunk = num_chunks + 1;
9195     } else {
9196       last_chunk = gst_byte_reader_peek_uint32_be_unchecked (&stream->stsc);
9197     }
9198
9199     GST_DEBUG_OBJECT (qtdemux,
9200         "Merging first_chunk: %u, last_chunk: %u, samples_per_chunk: %u, sample_description_id: %u",
9201         first_chunk, last_chunk, samples_per_chunk, sample_description_id);
9202
9203     gst_byte_writer_put_uint32_be (&stsc, first_chunk);
9204     /* One sample in this chunk */
9205     gst_byte_writer_put_uint32_be (&stsc, 1);
9206     gst_byte_writer_put_uint32_be (&stsc, sample_description_id);
9207
9208     /* For each chunk write a stts and stsz entry now */
9209     gst_byte_writer_put_uint32_be (&stts, last_chunk - first_chunk);
9210     gst_byte_writer_put_uint32_be (&stts, stts_duration * samples_per_chunk);
9211     for (j = first_chunk; j < last_chunk; j++) {
9212       gst_byte_writer_put_uint32_be (&stsz,
9213           stream->sample_size * samples_per_chunk);
9214     }
9215
9216     stream->n_sample_times += 1;
9217     stream->n_samples += last_chunk - first_chunk;
9218   }
9219
9220   g_assert_cmpint (stream->n_samples, ==, num_chunks);
9221
9222   GST_DEBUG_OBJECT (qtdemux, "Have %u samples and %u sample times",
9223       stream->n_samples, stream->n_sample_times);
9224
9225   /* We don't have a fixed sample size anymore */
9226   stream->sample_size = 0;
9227
9228   /* Free old data for the atoms */
9229   g_free ((gpointer) stream->stsz.data);
9230   stream->stsz.data = NULL;
9231   g_free ((gpointer) stream->stsc.data);
9232   stream->stsc.data = NULL;
9233   g_free ((gpointer) stream->stts.data);
9234   stream->stts.data = NULL;
9235
9236   /* Store new data and replace byte readers */
9237   stream->stsz.size = gst_byte_writer_get_size (&stsz);
9238   stream->stsz.data = gst_byte_writer_reset_and_get_data (&stsz);
9239   gst_byte_reader_init (&stream->stsz, stream->stsz.data, stream->stsz.size);
9240   stream->stts.size = gst_byte_writer_get_size (&stts);
9241   stream->stts.data = gst_byte_writer_reset_and_get_data (&stts);
9242   gst_byte_reader_init (&stream->stts, stream->stts.data, stream->stts.size);
9243   stream->stsc.size = gst_byte_writer_get_size (&stsc);
9244   stream->stsc.data = gst_byte_writer_reset_and_get_data (&stsc);
9245   gst_byte_reader_init (&stream->stsc, stream->stsc.data, stream->stsc.size);
9246 }
9247
9248 /* initialise bytereaders for stbl sub-atoms */
9249 static gboolean
9250 qtdemux_stbl_init (GstQTDemux * qtdemux, QtDemuxStream * stream, GNode * stbl)
9251 {
9252   stream->stbl_index = -1;      /* no samples have yet been parsed */
9253   stream->sample_index = -1;
9254
9255   /* time-to-sample atom */
9256   if (!qtdemux_tree_get_child_by_type_full (stbl, FOURCC_stts, &stream->stts))
9257     goto corrupt_file;
9258
9259   /* copy atom data into a new buffer for later use */
9260   stream->stts.data = g_memdup2 (stream->stts.data, stream->stts.size);
9261
9262   /* skip version + flags */
9263   if (!gst_byte_reader_skip (&stream->stts, 1 + 3) ||
9264       !gst_byte_reader_get_uint32_be (&stream->stts, &stream->n_sample_times))
9265     goto corrupt_file;
9266   GST_LOG_OBJECT (qtdemux, "%u timestamp blocks", stream->n_sample_times);
9267
9268   /* make sure there's enough data */
9269   if (!qt_atom_parser_has_chunks (&stream->stts, stream->n_sample_times, 8)) {
9270     stream->n_sample_times = gst_byte_reader_get_remaining (&stream->stts) / 8;
9271     GST_LOG_OBJECT (qtdemux, "overriding to %u timestamp blocks",
9272         stream->n_sample_times);
9273     if (!stream->n_sample_times)
9274       goto corrupt_file;
9275   }
9276
9277   /* sync sample atom */
9278   stream->stps_present = FALSE;
9279   if ((stream->stss_present =
9280           ! !qtdemux_tree_get_child_by_type_full (stbl, FOURCC_stss,
9281               &stream->stss) ? TRUE : FALSE) == TRUE) {
9282     /* copy atom data into a new buffer for later use */
9283     stream->stss.data = g_memdup2 (stream->stss.data, stream->stss.size);
9284
9285     /* skip version + flags */
9286     if (!gst_byte_reader_skip (&stream->stss, 1 + 3) ||
9287         !gst_byte_reader_get_uint32_be (&stream->stss, &stream->n_sample_syncs))
9288       goto corrupt_file;
9289
9290     if (stream->n_sample_syncs) {
9291       /* make sure there's enough data */
9292       if (!qt_atom_parser_has_chunks (&stream->stss, stream->n_sample_syncs, 4))
9293         goto corrupt_file;
9294     }
9295
9296     /* partial sync sample atom */
9297     if ((stream->stps_present =
9298             ! !qtdemux_tree_get_child_by_type_full (stbl, FOURCC_stps,
9299                 &stream->stps) ? TRUE : FALSE) == TRUE) {
9300       /* copy atom data into a new buffer for later use */
9301       stream->stps.data = g_memdup2 (stream->stps.data, stream->stps.size);
9302
9303       /* skip version + flags */
9304       if (!gst_byte_reader_skip (&stream->stps, 1 + 3) ||
9305           !gst_byte_reader_get_uint32_be (&stream->stps,
9306               &stream->n_sample_partial_syncs))
9307         goto corrupt_file;
9308
9309       /* if there are no entries, the stss table contains the real
9310        * sync samples */
9311       if (stream->n_sample_partial_syncs) {
9312         /* make sure there's enough data */
9313         if (!qt_atom_parser_has_chunks (&stream->stps,
9314                 stream->n_sample_partial_syncs, 4))
9315           goto corrupt_file;
9316       }
9317     }
9318   }
9319
9320   /* sample size */
9321   if (!qtdemux_tree_get_child_by_type_full (stbl, FOURCC_stsz, &stream->stsz))
9322     goto no_samples;
9323
9324   /* copy atom data into a new buffer for later use */
9325   stream->stsz.data = g_memdup2 (stream->stsz.data, stream->stsz.size);
9326
9327   /* skip version + flags */
9328   if (!gst_byte_reader_skip (&stream->stsz, 1 + 3) ||
9329       !gst_byte_reader_get_uint32_be (&stream->stsz, &stream->sample_size))
9330     goto corrupt_file;
9331
9332   if (!gst_byte_reader_get_uint32_be (&stream->stsz, &stream->n_samples))
9333     goto corrupt_file;
9334
9335   if (!stream->n_samples)
9336     goto no_samples;
9337
9338   /* sample-to-chunk atom */
9339   if (!qtdemux_tree_get_child_by_type_full (stbl, FOURCC_stsc, &stream->stsc))
9340     goto corrupt_file;
9341
9342   /* copy atom data into a new buffer for later use */
9343   stream->stsc.data = g_memdup2 (stream->stsc.data, stream->stsc.size);
9344
9345   /* skip version + flags */
9346   if (!gst_byte_reader_skip (&stream->stsc, 1 + 3) ||
9347       !gst_byte_reader_get_uint32_be (&stream->stsc,
9348           &stream->n_samples_per_chunk))
9349     goto corrupt_file;
9350
9351   GST_DEBUG_OBJECT (qtdemux, "n_samples_per_chunk %u",
9352       stream->n_samples_per_chunk);
9353
9354   /* make sure there's enough data */
9355   if (!qt_atom_parser_has_chunks (&stream->stsc, stream->n_samples_per_chunk,
9356           12))
9357     goto corrupt_file;
9358
9359
9360   /* chunk offset */
9361   if (qtdemux_tree_get_child_by_type_full (stbl, FOURCC_stco, &stream->stco))
9362     stream->co_size = sizeof (guint32);
9363   else if (qtdemux_tree_get_child_by_type_full (stbl, FOURCC_co64,
9364           &stream->stco))
9365     stream->co_size = sizeof (guint64);
9366   else
9367     goto corrupt_file;
9368
9369   /* copy atom data into a new buffer for later use */
9370   stream->stco.data = g_memdup2 (stream->stco.data, stream->stco.size);
9371
9372   /* skip version + flags */
9373   if (!gst_byte_reader_skip (&stream->stco, 1 + 3))
9374     goto corrupt_file;
9375
9376   /* chunks_are_samples == TRUE means treat chunks as samples */
9377   stream->chunks_are_samples = stream->sample_size
9378       && !CUR_STREAM (stream)->sampled;
9379   if (stream->chunks_are_samples) {
9380     /* treat chunks as samples */
9381     if (!gst_byte_reader_get_uint32_be (&stream->stco, &stream->n_samples))
9382       goto corrupt_file;
9383   } else {
9384     /* skip number of entries */
9385     if (!gst_byte_reader_skip (&stream->stco, 4))
9386       goto corrupt_file;
9387
9388     /* make sure there are enough data in the stsz atom */
9389     if (!stream->sample_size) {
9390       /* different sizes for each sample */
9391       if (!qt_atom_parser_has_chunks (&stream->stsz, stream->n_samples, 4))
9392         goto corrupt_file;
9393     }
9394   }
9395
9396   /* composition time-to-sample */
9397   if ((stream->ctts_present =
9398           ! !qtdemux_tree_get_child_by_type_full (stbl, FOURCC_ctts,
9399               &stream->ctts) ? TRUE : FALSE) == TRUE) {
9400     GstByteReader cslg = GST_BYTE_READER_INIT (NULL, 0);
9401     guint8 ctts_version;
9402     gboolean checked_ctts = FALSE;
9403
9404     /* copy atom data into a new buffer for later use */
9405     stream->ctts.data = g_memdup2 (stream->ctts.data, stream->ctts.size);
9406
9407     /* version 1 has signed offsets */
9408     if (!gst_byte_reader_get_uint8 (&stream->ctts, &ctts_version))
9409       goto corrupt_file;
9410
9411     /* flags */
9412     if (!gst_byte_reader_skip (&stream->ctts, 3)
9413         || !gst_byte_reader_get_uint32_be (&stream->ctts,
9414             &stream->n_composition_times))
9415       goto corrupt_file;
9416
9417     /* make sure there's enough data */
9418     if (!qt_atom_parser_has_chunks (&stream->ctts, stream->n_composition_times,
9419             4 + 4))
9420       goto corrupt_file;
9421
9422     /* This is optional, if missing we iterate the ctts */
9423     if (qtdemux_tree_get_child_by_type_full (stbl, FOURCC_cslg, &cslg)) {
9424       guint8 cslg_version;
9425
9426       /* cslg version 1 has 64 bit fields */
9427       if (!gst_byte_reader_get_uint8 (&cslg, &cslg_version))
9428         goto corrupt_file;
9429
9430       /* skip flags */
9431       if (!gst_byte_reader_skip (&cslg, 3))
9432         goto corrupt_file;
9433
9434       if (cslg_version == 0) {
9435         gint32 composition_to_dts_shift;
9436
9437         if (!gst_byte_reader_get_int32_be (&cslg, &composition_to_dts_shift))
9438           goto corrupt_file;
9439
9440         stream->cslg_shift = MAX (0, composition_to_dts_shift);
9441       } else {
9442         gint64 composition_to_dts_shift;
9443
9444         if (!gst_byte_reader_get_int64_be (&cslg, &composition_to_dts_shift))
9445           goto corrupt_file;
9446
9447         stream->cslg_shift = MAX (0, composition_to_dts_shift);
9448       }
9449     } else {
9450       gint32 cslg_least = 0;
9451       guint num_entries, pos;
9452       gint i;
9453
9454       pos = gst_byte_reader_get_pos (&stream->ctts);
9455       num_entries = stream->n_composition_times;
9456
9457       checked_ctts = TRUE;
9458
9459       stream->cslg_shift = 0;
9460
9461       for (i = 0; i < num_entries; i++) {
9462         gint32 offset;
9463
9464         gst_byte_reader_skip_unchecked (&stream->ctts, 4);
9465         offset = gst_byte_reader_get_int32_be_unchecked (&stream->ctts);
9466         /* HACK: if sample_offset is larger than 2 * duration, ignore the box.
9467          * slightly inaccurate PTS could be more usable than corrupted one */
9468         if (G_UNLIKELY ((ctts_version == 0 || offset != G_MININT32)
9469                 && ABS (offset) / 2 > stream->duration)) {
9470           GST_WARNING_OBJECT (qtdemux,
9471               "Ignore corrupted ctts, sample_offset %" G_GINT32_FORMAT
9472               " larger than duration %" G_GUINT64_FORMAT, offset,
9473               stream->duration);
9474
9475           stream->cslg_shift = 0;
9476           stream->ctts_present = FALSE;
9477           goto done;
9478         }
9479
9480         /* Don't consider "no decode samples" with offset G_MININT32
9481          * for the DTS/PTS shift */
9482         if (offset != G_MININT32 && offset < cslg_least)
9483           cslg_least = offset;
9484       }
9485
9486       if (cslg_least < 0)
9487         stream->cslg_shift = -cslg_least;
9488       else
9489         stream->cslg_shift = 0;
9490
9491       /* reset the reader so we can generate sample table */
9492       gst_byte_reader_set_pos (&stream->ctts, pos);
9493     }
9494
9495     /* Check if ctts values are looking reasonable if that didn't happen above */
9496     if (!checked_ctts) {
9497       guint num_entries, pos;
9498       gint i;
9499
9500       pos = gst_byte_reader_get_pos (&stream->ctts);
9501       num_entries = stream->n_composition_times;
9502
9503       for (i = 0; i < num_entries; i++) {
9504         gint32 offset;
9505
9506         gst_byte_reader_skip_unchecked (&stream->ctts, 4);
9507         offset = gst_byte_reader_get_int32_be_unchecked (&stream->ctts);
9508         /* HACK: if sample_offset is larger than 2 * duration, ignore the box.
9509          * slightly inaccurate PTS could be more usable than corrupted one */
9510         if (G_UNLIKELY ((ctts_version == 0 || offset != G_MININT32)
9511                 && ABS (offset) / 2 > stream->duration)) {
9512           GST_WARNING_OBJECT (qtdemux,
9513               "Ignore corrupted ctts, sample_offset %" G_GINT32_FORMAT
9514               " larger than duration %" G_GUINT64_FORMAT, offset,
9515               stream->duration);
9516
9517           stream->cslg_shift = 0;
9518           stream->ctts_present = FALSE;
9519           goto done;
9520         }
9521       }
9522
9523       /* reset the reader so we can generate sample table */
9524       gst_byte_reader_set_pos (&stream->ctts, pos);
9525     }
9526   } else {
9527     /* Ensure the cslg_shift value is consistent so we can use it
9528      * unconditionally to produce TS and Segment */
9529     stream->cslg_shift = 0;
9530   }
9531
9532   GST_DEBUG_OBJECT (qtdemux, "Using clsg_shift %" G_GUINT64_FORMAT,
9533       stream->cslg_shift);
9534
9535   /* For raw audio streams especially we might want to merge the samples
9536    * to not output one audio sample per buffer. We're doing this here
9537    * before allocating the sample tables so that from this point onwards
9538    * the number of container samples are static */
9539   if (stream->min_buffer_size > 0) {
9540     qtdemux_merge_sample_table (qtdemux, stream);
9541   }
9542
9543 done:
9544   GST_DEBUG_OBJECT (qtdemux, "allocating n_samples %u * %u (%.2f MB)",
9545       stream->n_samples, (guint) sizeof (QtDemuxSample),
9546       stream->n_samples * sizeof (QtDemuxSample) / (1024.0 * 1024.0));
9547
9548   if (stream->n_samples >=
9549       QTDEMUX_MAX_SAMPLE_INDEX_SIZE / sizeof (QtDemuxSample)) {
9550     GST_WARNING_OBJECT (qtdemux, "not allocating index of %d samples, would "
9551         "be larger than %uMB (broken file?)", stream->n_samples,
9552         QTDEMUX_MAX_SAMPLE_INDEX_SIZE >> 20);
9553     return FALSE;
9554   }
9555
9556   g_assert (stream->samples == NULL);
9557   stream->samples = g_try_new0 (QtDemuxSample, stream->n_samples);
9558   if (!stream->samples) {
9559     GST_WARNING_OBJECT (qtdemux, "failed to allocate %d samples",
9560         stream->n_samples);
9561     return FALSE;
9562   }
9563
9564   return TRUE;
9565
9566 corrupt_file:
9567   {
9568     GST_ELEMENT_ERROR (qtdemux, STREAM, DEMUX,
9569         (_("This file is corrupt and cannot be played.")), (NULL));
9570     return FALSE;
9571   }
9572 no_samples:
9573   {
9574     gst_qtdemux_stbl_free (stream);
9575     if (!qtdemux->fragmented) {
9576       /* not quite good */
9577       GST_WARNING_OBJECT (qtdemux, "stream has no samples");
9578       return FALSE;
9579     } else {
9580       /* may pick up samples elsewhere */
9581       return TRUE;
9582     }
9583   }
9584 }
9585
9586 /* collect samples from the next sample to be parsed up to sample @n for @stream
9587  * by reading the info from @stbl
9588  *
9589  * This code can be executed from both the streaming thread and the seeking
9590  * thread so it takes the object lock to protect itself
9591  */
9592 static gboolean
9593 qtdemux_parse_samples (GstQTDemux * qtdemux, QtDemuxStream * stream, guint32 n)
9594 {
9595   gint i, j, k;
9596   QtDemuxSample *samples, *first, *cur, *last;
9597   guint32 n_samples_per_chunk;
9598   guint32 n_samples;
9599
9600   GST_LOG_OBJECT (qtdemux, "parsing samples for stream fourcc %"
9601       GST_FOURCC_FORMAT ", pad %s",
9602       GST_FOURCC_ARGS (CUR_STREAM (stream)->fourcc),
9603       stream->pad ? GST_PAD_NAME (stream->pad) : "(NULL)");
9604
9605   n_samples = stream->n_samples;
9606
9607   if (n >= n_samples)
9608     goto out_of_samples;
9609
9610   GST_OBJECT_LOCK (qtdemux);
9611   if (n <= stream->stbl_index)
9612     goto already_parsed;
9613
9614   GST_DEBUG_OBJECT (qtdemux, "parsing up to sample %u", n);
9615
9616   if (!stream->stsz.data) {
9617     /* so we already parsed and passed all the moov samples;
9618      * onto fragmented ones */
9619     g_assert (qtdemux->fragmented);
9620     goto done;
9621   }
9622
9623   /* pointer to the sample table */
9624   samples = stream->samples;
9625
9626   /* starts from -1, moves to the next sample index to parse */
9627   stream->stbl_index++;
9628
9629   /* keep track of the first and last sample to fill */
9630   first = &samples[stream->stbl_index];
9631   last = &samples[n];
9632
9633   if (!stream->chunks_are_samples) {
9634     /* set the sample sizes */
9635     if (stream->sample_size == 0) {
9636       /* different sizes for each sample */
9637       for (cur = first; cur <= last; cur++) {
9638         cur->size = gst_byte_reader_get_uint32_be_unchecked (&stream->stsz);
9639         GST_LOG_OBJECT (qtdemux, "sample %d has size %u",
9640             (guint) (cur - samples), cur->size);
9641       }
9642     } else {
9643       /* samples have the same size */
9644       GST_LOG_OBJECT (qtdemux, "all samples have size %u", stream->sample_size);
9645       for (cur = first; cur <= last; cur++)
9646         cur->size = stream->sample_size;
9647     }
9648   }
9649
9650   n_samples_per_chunk = stream->n_samples_per_chunk;
9651   cur = first;
9652
9653   for (i = stream->stsc_index; i < n_samples_per_chunk; i++) {
9654     guint32 last_chunk;
9655
9656     if (stream->stsc_chunk_index >= stream->last_chunk
9657         || stream->stsc_chunk_index < stream->first_chunk) {
9658       stream->first_chunk =
9659           gst_byte_reader_get_uint32_be_unchecked (&stream->stsc);
9660       stream->samples_per_chunk =
9661           gst_byte_reader_get_uint32_be_unchecked (&stream->stsc);
9662       /* starts from 1 */
9663       stream->stsd_sample_description_id =
9664           gst_byte_reader_get_uint32_be_unchecked (&stream->stsc) - 1;
9665
9666       /* chunk numbers are counted from 1 it seems */
9667       if (G_UNLIKELY (stream->first_chunk == 0))
9668         goto corrupt_file;
9669
9670       --stream->first_chunk;
9671
9672       /* the last chunk of each entry is calculated by taking the first chunk
9673        * of the next entry; except if there is no next, where we fake it with
9674        * INT_MAX */
9675       if (G_UNLIKELY (i == (stream->n_samples_per_chunk - 1))) {
9676         stream->last_chunk = G_MAXUINT32;
9677       } else {
9678         stream->last_chunk =
9679             gst_byte_reader_peek_uint32_be_unchecked (&stream->stsc);
9680         if (G_UNLIKELY (stream->last_chunk == 0))
9681           goto corrupt_file;
9682
9683         --stream->last_chunk;
9684       }
9685
9686       GST_LOG_OBJECT (qtdemux,
9687           "entry %d has first_chunk %d, last_chunk %d, samples_per_chunk %d"
9688           "sample desc ID: %d", i, stream->first_chunk, stream->last_chunk,
9689           stream->samples_per_chunk, stream->stsd_sample_description_id);
9690
9691       if (G_UNLIKELY (stream->last_chunk < stream->first_chunk))
9692         goto corrupt_file;
9693
9694       if (stream->last_chunk != G_MAXUINT32) {
9695         if (!qt_atom_parser_peek_sub (&stream->stco,
9696                 stream->first_chunk * stream->co_size,
9697                 (stream->last_chunk - stream->first_chunk) * stream->co_size,
9698                 &stream->co_chunk))
9699           goto corrupt_file;
9700
9701       } else {
9702         stream->co_chunk = stream->stco;
9703         if (!gst_byte_reader_skip (&stream->co_chunk,
9704                 stream->first_chunk * stream->co_size))
9705           goto corrupt_file;
9706       }
9707
9708       stream->stsc_chunk_index = stream->first_chunk;
9709     }
9710
9711     last_chunk = stream->last_chunk;
9712
9713     if (stream->chunks_are_samples) {
9714       cur = &samples[stream->stsc_chunk_index];
9715
9716       for (j = stream->stsc_chunk_index; j < last_chunk; j++) {
9717         if (j > n) {
9718           /* save state */
9719           stream->stsc_chunk_index = j;
9720           goto done;
9721         }
9722
9723         cur->offset =
9724             qt_atom_parser_get_offset_unchecked (&stream->co_chunk,
9725             stream->co_size);
9726
9727         GST_LOG_OBJECT (qtdemux, "Created entry %d with offset "
9728             "%" G_GUINT64_FORMAT, j, cur->offset);
9729
9730         if (CUR_STREAM (stream)->samples_per_frame > 0 &&
9731             CUR_STREAM (stream)->bytes_per_frame > 0) {
9732           cur->size =
9733               (stream->samples_per_chunk * CUR_STREAM (stream)->n_channels) /
9734               CUR_STREAM (stream)->samples_per_frame *
9735               CUR_STREAM (stream)->bytes_per_frame;
9736         } else {
9737           cur->size = stream->samples_per_chunk;
9738         }
9739
9740         GST_DEBUG_OBJECT (qtdemux,
9741             "keyframe sample %d: timestamp %" GST_TIME_FORMAT ", size %u",
9742             j, GST_TIME_ARGS (QTSTREAMTIME_TO_GSTTIME (stream,
9743                     stream->stco_sample_index)), cur->size);
9744
9745         cur->timestamp = stream->stco_sample_index;
9746         cur->duration = stream->samples_per_chunk;
9747         cur->keyframe = TRUE;
9748         cur++;
9749
9750         stream->stco_sample_index += stream->samples_per_chunk;
9751       }
9752       stream->stsc_chunk_index = j;
9753     } else {
9754       for (j = stream->stsc_chunk_index; j < last_chunk; j++) {
9755         guint32 samples_per_chunk;
9756         guint64 chunk_offset;
9757
9758         if (!stream->stsc_sample_index
9759             && !qt_atom_parser_get_offset (&stream->co_chunk, stream->co_size,
9760                 &stream->chunk_offset))
9761           goto corrupt_file;
9762
9763         samples_per_chunk = stream->samples_per_chunk;
9764         chunk_offset = stream->chunk_offset;
9765
9766         for (k = stream->stsc_sample_index; k < samples_per_chunk; k++) {
9767           GST_LOG_OBJECT (qtdemux, "creating entry %d with offset %"
9768               G_GUINT64_FORMAT " and size %d",
9769               (guint) (cur - samples), chunk_offset, cur->size);
9770
9771           cur->offset = chunk_offset;
9772           chunk_offset += cur->size;
9773           cur++;
9774
9775           if (G_UNLIKELY (cur > last)) {
9776             /* save state */
9777             stream->stsc_sample_index = k + 1;
9778             stream->chunk_offset = chunk_offset;
9779             stream->stsc_chunk_index = j;
9780             goto done2;
9781           }
9782         }
9783         stream->stsc_sample_index = 0;
9784       }
9785       stream->stsc_chunk_index = j;
9786     }
9787     stream->stsc_index++;
9788   }
9789
9790   if (stream->chunks_are_samples)
9791     goto ctts;
9792 done2:
9793   {
9794     guint32 n_sample_times;
9795
9796     n_sample_times = stream->n_sample_times;
9797     cur = first;
9798
9799     for (i = stream->stts_index; i < n_sample_times; i++) {
9800       guint32 stts_samples;
9801       gint32 stts_duration;
9802       gint64 stts_time;
9803
9804       if (stream->stts_sample_index >= stream->stts_samples
9805           || !stream->stts_sample_index) {
9806
9807         stream->stts_samples =
9808             gst_byte_reader_get_uint32_be_unchecked (&stream->stts);
9809         stream->stts_duration =
9810             gst_byte_reader_get_uint32_be_unchecked (&stream->stts);
9811
9812         GST_LOG_OBJECT (qtdemux, "block %d, %u timestamps, duration %u",
9813             i, stream->stts_samples, stream->stts_duration);
9814
9815         stream->stts_sample_index = 0;
9816       }
9817
9818       stts_samples = stream->stts_samples;
9819       stts_duration = stream->stts_duration;
9820       stts_time = stream->stts_time;
9821
9822       for (j = stream->stts_sample_index; j < stts_samples; j++) {
9823         GST_DEBUG_OBJECT (qtdemux,
9824             "sample %d: index %d, timestamp %" GST_TIME_FORMAT,
9825             (guint) (cur - samples), j,
9826             GST_TIME_ARGS (QTSTREAMTIME_TO_GSTTIME (stream, stts_time)));
9827
9828         cur->timestamp = stts_time;
9829         cur->duration = stts_duration;
9830
9831         /* avoid 32-bit wrap-around,
9832          * but still mind possible 'negative' duration */
9833         stts_time += (gint64) stts_duration;
9834         cur++;
9835
9836         if (G_UNLIKELY (cur > last)) {
9837           /* save values */
9838           stream->stts_time = stts_time;
9839           stream->stts_sample_index = j + 1;
9840           if (stream->stts_sample_index >= stream->stts_samples)
9841             stream->stts_index++;
9842           goto done3;
9843         }
9844       }
9845       stream->stts_sample_index = 0;
9846       stream->stts_time = stts_time;
9847       stream->stts_index++;
9848     }
9849     /* fill up empty timestamps with the last timestamp, this can happen when
9850      * the last samples do not decode and so we don't have timestamps for them.
9851      * We however look at the last timestamp to estimate the track length so we
9852      * need something in here. */
9853     for (; cur < last; cur++) {
9854       GST_DEBUG_OBJECT (qtdemux,
9855           "fill sample %d: timestamp %" GST_TIME_FORMAT,
9856           (guint) (cur - samples),
9857           GST_TIME_ARGS (QTSTREAMTIME_TO_GSTTIME (stream, stream->stts_time)));
9858       cur->timestamp = stream->stts_time;
9859       cur->duration = -1;
9860     }
9861   }
9862 done3:
9863   {
9864     /* sample sync, can be NULL */
9865     if (stream->stss_present == TRUE) {
9866       guint32 n_sample_syncs;
9867
9868       n_sample_syncs = stream->n_sample_syncs;
9869
9870       if (!n_sample_syncs) {
9871         GST_DEBUG_OBJECT (qtdemux, "all samples are keyframes");
9872         stream->all_keyframe = TRUE;
9873       } else {
9874         for (i = stream->stss_index; i < n_sample_syncs; i++) {
9875           /* note that the first sample is index 1, not 0 */
9876           guint32 index;
9877
9878           index = gst_byte_reader_get_uint32_be_unchecked (&stream->stss);
9879
9880           if (G_LIKELY (index > 0 && index <= n_samples)) {
9881             index -= 1;
9882             samples[index].keyframe = TRUE;
9883             GST_DEBUG_OBJECT (qtdemux, "samples at %u is keyframe", index);
9884             /* and exit if we have enough samples */
9885             if (G_UNLIKELY (index >= n)) {
9886               i++;
9887               break;
9888             }
9889           }
9890         }
9891         /* save state */
9892         stream->stss_index = i;
9893       }
9894
9895       /* stps marks partial sync frames like open GOP I-Frames */
9896       if (stream->stps_present == TRUE) {
9897         guint32 n_sample_partial_syncs;
9898
9899         n_sample_partial_syncs = stream->n_sample_partial_syncs;
9900
9901         /* if there are no entries, the stss table contains the real
9902          * sync samples */
9903         if (n_sample_partial_syncs) {
9904           for (i = stream->stps_index; i < n_sample_partial_syncs; i++) {
9905             /* note that the first sample is index 1, not 0 */
9906             guint32 index;
9907
9908             index = gst_byte_reader_get_uint32_be_unchecked (&stream->stps);
9909
9910             if (G_LIKELY (index > 0 && index <= n_samples)) {
9911               index -= 1;
9912               samples[index].keyframe = TRUE;
9913               GST_DEBUG_OBJECT (qtdemux, "samples at %u is keyframe", index);
9914               /* and exit if we have enough samples */
9915               if (G_UNLIKELY (index >= n)) {
9916                 i++;
9917                 break;
9918               }
9919             }
9920           }
9921           /* save state */
9922           stream->stps_index = i;
9923         }
9924       }
9925     } else {
9926       /* no stss, all samples are keyframes */
9927       stream->all_keyframe = TRUE;
9928       GST_DEBUG_OBJECT (qtdemux, "setting all keyframes");
9929     }
9930   }
9931
9932 ctts:
9933   /* composition time to sample */
9934   if (stream->ctts_present == TRUE) {
9935     guint32 n_composition_times;
9936     guint32 ctts_count;
9937     gint32 ctts_soffset;
9938
9939     /* Fill in the pts_offsets */
9940     cur = first;
9941     n_composition_times = stream->n_composition_times;
9942
9943     for (i = stream->ctts_index; i < n_composition_times; i++) {
9944       if (stream->ctts_sample_index >= stream->ctts_count
9945           || !stream->ctts_sample_index) {
9946         stream->ctts_count =
9947             gst_byte_reader_get_uint32_be_unchecked (&stream->ctts);
9948         stream->ctts_soffset =
9949             gst_byte_reader_get_int32_be_unchecked (&stream->ctts);
9950         stream->ctts_sample_index = 0;
9951       }
9952
9953       ctts_count = stream->ctts_count;
9954       ctts_soffset = stream->ctts_soffset;
9955
9956       /* FIXME: Set offset to 0 for "no decode samples". This needs
9957        * to be handled in a codec specific manner ideally. */
9958       if (ctts_soffset == G_MININT32)
9959         ctts_soffset = 0;
9960
9961       for (j = stream->ctts_sample_index; j < ctts_count; j++) {
9962         cur->pts_offset = ctts_soffset;
9963         cur++;
9964
9965         if (G_UNLIKELY (cur > last)) {
9966           /* save state */
9967           stream->ctts_sample_index = j + 1;
9968           goto done;
9969         }
9970       }
9971       stream->ctts_sample_index = 0;
9972       stream->ctts_index++;
9973     }
9974   }
9975 done:
9976   stream->stbl_index = n;
9977   /* if index has been completely parsed, free data that is no-longer needed */
9978   if (n + 1 == stream->n_samples) {
9979     gst_qtdemux_stbl_free (stream);
9980     GST_DEBUG_OBJECT (qtdemux, "parsed all available samples;");
9981     if (qtdemux->pullbased) {
9982       GST_DEBUG_OBJECT (qtdemux, "checking for more samples");
9983       while (n + 1 == stream->n_samples)
9984         if (qtdemux_add_fragmented_samples (qtdemux) != GST_FLOW_OK)
9985           break;
9986     }
9987   }
9988   GST_OBJECT_UNLOCK (qtdemux);
9989
9990   return TRUE;
9991
9992   /* SUCCESS */
9993 already_parsed:
9994   {
9995     GST_LOG_OBJECT (qtdemux,
9996         "Tried to parse up to sample %u but this sample has already been parsed",
9997         n);
9998     /* if fragmented, there may be more */
9999     if (qtdemux->fragmented && n == stream->stbl_index)
10000       goto done;
10001     GST_OBJECT_UNLOCK (qtdemux);
10002     return TRUE;
10003   }
10004   /* ERRORS */
10005 out_of_samples:
10006   {
10007     GST_LOG_OBJECT (qtdemux,
10008         "Tried to parse up to sample %u but there are only %u samples", n + 1,
10009         stream->n_samples);
10010     GST_ELEMENT_ERROR (qtdemux, STREAM, DEMUX,
10011         (_("This file is corrupt and cannot be played.")), (NULL));
10012     return FALSE;
10013   }
10014 corrupt_file:
10015   {
10016     GST_OBJECT_UNLOCK (qtdemux);
10017     GST_ELEMENT_ERROR (qtdemux, STREAM, DEMUX,
10018         (_("This file is corrupt and cannot be played.")), (NULL));
10019     return FALSE;
10020   }
10021 }
10022
10023 /* collect all segment info for @stream.
10024  */
10025 static gboolean
10026 qtdemux_parse_segments (GstQTDemux * qtdemux, QtDemuxStream * stream,
10027     GNode * trak)
10028 {
10029   GNode *edts;
10030   /* accept edts if they contain gaps at start and there is only
10031    * one media segment */
10032   gboolean allow_pushbased_edts = TRUE;
10033   gint media_segments_count = 0;
10034
10035   /* parse and prepare segment info from the edit list */
10036   GST_DEBUG_OBJECT (qtdemux, "looking for edit list container");
10037   stream->n_segments = 0;
10038   stream->segments = NULL;
10039   if ((edts = qtdemux_tree_get_child_by_type (trak, FOURCC_edts))) {
10040     GNode *elst;
10041     gint n_segments;
10042     gint segment_number, entry_size;
10043     guint64 time;
10044     GstClockTime stime;
10045     const guint8 *buffer;
10046     guint8 version;
10047     guint32 size;
10048
10049     GST_DEBUG_OBJECT (qtdemux, "looking for edit list");
10050     if (!(elst = qtdemux_tree_get_child_by_type (edts, FOURCC_elst)))
10051       goto done;
10052
10053     buffer = elst->data;
10054
10055     size = QT_UINT32 (buffer);
10056     /* version, flags, n_segments */
10057     if (size < 16) {
10058       GST_WARNING_OBJECT (qtdemux, "Invalid edit list");
10059       goto done;
10060     }
10061     version = QT_UINT8 (buffer + 8);
10062     entry_size = (version == 1) ? 20 : 12;
10063
10064     n_segments = QT_UINT32 (buffer + 12);
10065
10066     if (n_segments > 100000 || size < 16 + n_segments * entry_size) {
10067       GST_WARNING_OBJECT (qtdemux, "Invalid edit list");
10068       goto done;
10069     }
10070
10071     /* we might allocate a bit too much, at least allocate 1 segment */
10072     stream->segments = g_new (QtDemuxSegment, MAX (n_segments, 1));
10073
10074     /* segments always start from 0 */
10075     time = 0;
10076     stime = 0;
10077     buffer += 16;
10078     for (segment_number = 0; segment_number < n_segments; segment_number++) {
10079       guint64 duration;
10080       guint64 media_time;
10081       gboolean empty_edit = FALSE;
10082       QtDemuxSegment *segment;
10083       guint32 rate_int;
10084       GstClockTime media_start = GST_CLOCK_TIME_NONE;
10085
10086       if (version == 1) {
10087         media_time = QT_UINT64 (buffer + 8);
10088         duration = QT_UINT64 (buffer);
10089         if (media_time == G_MAXUINT64)
10090           empty_edit = TRUE;
10091       } else {
10092         media_time = QT_UINT32 (buffer + 4);
10093         duration = QT_UINT32 (buffer);
10094         if (media_time == G_MAXUINT32)
10095           empty_edit = TRUE;
10096       }
10097
10098       if (!empty_edit)
10099         media_start = QTSTREAMTIME_TO_GSTTIME (stream, media_time);
10100
10101       segment = &stream->segments[segment_number];
10102
10103       /* time and duration expressed in global timescale */
10104       segment->time = stime;
10105       if (duration != 0 || empty_edit) {
10106         /* edge case: empty edits with duration=zero are treated here.
10107          * (files should not have these anyway). */
10108
10109         /* add non scaled values so we don't cause roundoff errors */
10110         time += duration;
10111         stime = QTTIME_TO_GSTTIME (qtdemux, time);
10112         segment->duration = stime - segment->time;
10113       } else {
10114         /* zero duration does not imply media_start == media_stop
10115          * but, only specify media_start. The edit ends with the track. */
10116         stime = segment->duration = GST_CLOCK_TIME_NONE;
10117         /* Don't allow more edits after this one. */
10118         n_segments = segment_number + 1;
10119       }
10120       segment->stop_time = stime;
10121
10122       segment->trak_media_start = media_time;
10123       /* media_time expressed in stream timescale */
10124       if (!empty_edit) {
10125         segment->media_start = media_start;
10126         segment->media_stop = GST_CLOCK_TIME_IS_VALID (segment->duration)
10127             ? segment->media_start + segment->duration : GST_CLOCK_TIME_NONE;
10128         media_segments_count++;
10129       } else {
10130         segment->media_start = GST_CLOCK_TIME_NONE;
10131         segment->media_stop = GST_CLOCK_TIME_NONE;
10132       }
10133       rate_int = QT_UINT32 (buffer + ((version == 1) ? 16 : 8));
10134
10135       if (rate_int <= 1) {
10136         /* 0 is not allowed, some programs write 1 instead of the floating point
10137          * value */
10138         GST_WARNING_OBJECT (qtdemux, "found suspicious rate %" G_GUINT32_FORMAT,
10139             rate_int);
10140         segment->rate = 1;
10141       } else {
10142         segment->rate = rate_int / 65536.0;
10143       }
10144
10145       GST_DEBUG_OBJECT (qtdemux, "created segment %d time %" GST_TIME_FORMAT
10146           ", duration %" GST_TIME_FORMAT ", media_start %" GST_TIME_FORMAT
10147           " (%" G_GUINT64_FORMAT ") , media_stop %" GST_TIME_FORMAT
10148           " stop_time %" GST_TIME_FORMAT " rate %g, (%d) timescale %u",
10149           segment_number, GST_TIME_ARGS (segment->time),
10150           GST_TIME_ARGS (segment->duration),
10151           GST_TIME_ARGS (segment->media_start), media_time,
10152           GST_TIME_ARGS (segment->media_stop),
10153           GST_TIME_ARGS (segment->stop_time), segment->rate, rate_int,
10154           stream->timescale);
10155       if (segment->stop_time > qtdemux->segment.stop &&
10156           !qtdemux->upstream_format_is_time) {
10157         GST_WARNING_OBJECT (qtdemux, "Segment %d "
10158             " extends to %" GST_TIME_FORMAT
10159             " past the end of the declared movie duration %" GST_TIME_FORMAT
10160             " movie segment will be extended", segment_number,
10161             GST_TIME_ARGS (segment->stop_time),
10162             GST_TIME_ARGS (qtdemux->segment.stop));
10163         qtdemux->segment.stop = qtdemux->segment.duration = segment->stop_time;
10164       }
10165
10166       buffer += entry_size;
10167     }
10168     GST_DEBUG_OBJECT (qtdemux, "found %d segments", n_segments);
10169     stream->n_segments = n_segments;
10170     if (media_segments_count != 1)
10171       allow_pushbased_edts = FALSE;
10172   }
10173 done:
10174
10175   /* push based does not handle segments, so act accordingly here,
10176    * and warn if applicable */
10177   if (!qtdemux->pullbased && !allow_pushbased_edts) {
10178     GST_WARNING_OBJECT (qtdemux, "streaming; discarding edit list segments");
10179     /* remove and use default one below, we stream like it anyway */
10180     g_free (stream->segments);
10181     stream->segments = NULL;
10182     stream->n_segments = 0;
10183   }
10184
10185   /* no segments, create one to play the complete trak */
10186   if (stream->n_segments == 0) {
10187     GstClockTime stream_duration =
10188         QTSTREAMTIME_TO_GSTTIME (stream, stream->duration);
10189
10190     if (stream->segments == NULL)
10191       stream->segments = g_new (QtDemuxSegment, 1);
10192
10193     /* represent unknown our way */
10194     if (stream_duration == 0)
10195       stream_duration = GST_CLOCK_TIME_NONE;
10196
10197     stream->segments[0].time = 0;
10198     stream->segments[0].stop_time = stream_duration;
10199     stream->segments[0].duration = stream_duration;
10200     stream->segments[0].media_start = 0;
10201     stream->segments[0].media_stop = stream_duration;
10202     stream->segments[0].rate = 1.0;
10203     stream->segments[0].trak_media_start = 0;
10204
10205     GST_DEBUG_OBJECT (qtdemux, "created dummy segment %" GST_TIME_FORMAT,
10206         GST_TIME_ARGS (stream_duration));
10207     stream->n_segments = 1;
10208     stream->dummy_segment = TRUE;
10209   }
10210   GST_DEBUG_OBJECT (qtdemux, "using %d segments", stream->n_segments);
10211
10212   return TRUE;
10213 }
10214
10215 /*
10216  * Parses the stsd atom of a svq3 trak looking for
10217  * the SMI and gama atoms.
10218  */
10219 static void
10220 qtdemux_parse_svq3_stsd_data (GstQTDemux * qtdemux,
10221     const guint8 * stsd_entry_data, const guint8 ** gamma, GstBuffer ** seqh)
10222 {
10223   const guint8 *_gamma = NULL;
10224   GstBuffer *_seqh = NULL;
10225   const guint8 *stsd_data = stsd_entry_data;
10226   guint32 length = QT_UINT32 (stsd_data);
10227   guint16 version;
10228
10229   if (length < 32) {
10230     GST_WARNING_OBJECT (qtdemux, "stsd too short");
10231     goto end;
10232   }
10233
10234   stsd_data += 16;
10235   length -= 16;
10236   version = QT_UINT16 (stsd_data);
10237   if (version == 3) {
10238     if (length >= 70) {
10239       length -= 70;
10240       stsd_data += 70;
10241       while (length > 8) {
10242         guint32 fourcc, size;
10243         const guint8 *data;
10244         size = QT_UINT32 (stsd_data);
10245         fourcc = QT_FOURCC (stsd_data + 4);
10246         data = stsd_data + 8;
10247
10248         if (size == 0) {
10249           GST_WARNING_OBJECT (qtdemux, "Atom of size 0 found, aborting "
10250               "svq3 atom parsing");
10251           goto end;
10252         }
10253
10254         switch (fourcc) {
10255           case FOURCC_gama:{
10256             if (size == 12) {
10257               _gamma = data;
10258             } else {
10259               GST_WARNING_OBJECT (qtdemux, "Unexpected size %" G_GUINT32_FORMAT
10260                   " for gama atom, expected 12", size);
10261             }
10262             break;
10263           }
10264           case FOURCC_SMI_:{
10265             if (size > 16 && QT_FOURCC (data) == FOURCC_SEQH) {
10266               guint32 seqh_size;
10267               if (_seqh != NULL) {
10268                 GST_WARNING_OBJECT (qtdemux, "Unexpected second SEQH SMI atom "
10269                     " found, ignoring");
10270               } else {
10271                 seqh_size = QT_UINT32 (data + 4);
10272                 if (seqh_size > 0) {
10273                   _seqh = gst_buffer_new_and_alloc (seqh_size);
10274                   gst_buffer_fill (_seqh, 0, data + 8, seqh_size);
10275                 }
10276               }
10277             }
10278             break;
10279           }
10280           default:{
10281             GST_WARNING_OBJECT (qtdemux, "Unhandled atom %" GST_FOURCC_FORMAT
10282                 " in SVQ3 entry in stsd atom", GST_FOURCC_ARGS (fourcc));
10283           }
10284         }
10285
10286         if (size <= length) {
10287           length -= size;
10288           stsd_data += size;
10289         }
10290       }
10291     } else {
10292       GST_WARNING_OBJECT (qtdemux, "SVQ3 entry too short in stsd atom");
10293     }
10294   } else {
10295     GST_WARNING_OBJECT (qtdemux, "Unexpected version for SVQ3 entry %"
10296         G_GUINT16_FORMAT, version);
10297     goto end;
10298   }
10299
10300 end:
10301   if (gamma) {
10302     *gamma = _gamma;
10303   }
10304   if (seqh) {
10305     *seqh = _seqh;
10306   } else if (_seqh) {
10307     gst_buffer_unref (_seqh);
10308   }
10309 }
10310
10311 static gchar *
10312 qtdemux_get_rtsp_uri_from_hndl (GstQTDemux * qtdemux, GNode * minf)
10313 {
10314   GNode *dinf;
10315   GstByteReader dref;
10316   gchar *uri = NULL;
10317
10318   /*
10319    * Get 'dinf', to get its child 'dref', that might contain a 'hndl'
10320    * atom that might contain a 'data' atom with the rtsp uri.
10321    * This case was reported in bug #597497, some info about
10322    * the hndl atom can be found in TN1195
10323    */
10324   dinf = qtdemux_tree_get_child_by_type (minf, FOURCC_dinf);
10325   GST_DEBUG_OBJECT (qtdemux, "Trying to obtain rtsp URI for stream trak");
10326
10327   if (dinf) {
10328     guint32 dref_num_entries = 0;
10329     if (qtdemux_tree_get_child_by_type_full (dinf, FOURCC_dref, &dref) &&
10330         gst_byte_reader_skip (&dref, 4) &&
10331         gst_byte_reader_get_uint32_be (&dref, &dref_num_entries)) {
10332       gint i;
10333
10334       /* search dref entries for hndl atom */
10335       for (i = 0; i < dref_num_entries; i++) {
10336         guint32 size = 0, type;
10337         guint8 string_len = 0;
10338         if (gst_byte_reader_get_uint32_be (&dref, &size) &&
10339             qt_atom_parser_get_fourcc (&dref, &type)) {
10340           if (type == FOURCC_hndl) {
10341             GST_DEBUG_OBJECT (qtdemux, "Found hndl atom");
10342
10343             /* skip data reference handle bytes and the
10344              * following pascal string and some extra 4
10345              * bytes I have no idea what are */
10346             if (!gst_byte_reader_skip (&dref, 4) ||
10347                 !gst_byte_reader_get_uint8 (&dref, &string_len) ||
10348                 !gst_byte_reader_skip (&dref, string_len + 4)) {
10349               GST_WARNING_OBJECT (qtdemux, "Failed to parse hndl atom");
10350               break;
10351             }
10352
10353             /* iterate over the atoms to find the data atom */
10354             while (gst_byte_reader_get_remaining (&dref) >= 8) {
10355               guint32 atom_size;
10356               guint32 atom_type;
10357
10358               if (gst_byte_reader_get_uint32_be (&dref, &atom_size) &&
10359                   qt_atom_parser_get_fourcc (&dref, &atom_type)) {
10360                 if (atom_type == FOURCC_data) {
10361                   const guint8 *uri_aux = NULL;
10362
10363                   /* found the data atom that might contain the rtsp uri */
10364                   GST_DEBUG_OBJECT (qtdemux, "Found data atom inside "
10365                       "hndl atom, interpreting it as an URI");
10366                   if (gst_byte_reader_peek_data (&dref, atom_size - 8,
10367                           &uri_aux)) {
10368                     if (g_strstr_len ((gchar *) uri_aux, 7, "rtsp://") != NULL)
10369                       uri = g_strndup ((gchar *) uri_aux, atom_size - 8);
10370                     else
10371                       GST_WARNING_OBJECT (qtdemux, "Data atom in hndl atom "
10372                           "didn't contain a rtsp address");
10373                   } else {
10374                     GST_WARNING_OBJECT (qtdemux, "Failed to get the data "
10375                         "atom contents");
10376                   }
10377                   break;
10378                 }
10379                 /* skipping to the next entry */
10380                 if (!gst_byte_reader_skip (&dref, atom_size - 8))
10381                   break;
10382               } else {
10383                 GST_WARNING_OBJECT (qtdemux, "Failed to parse hndl child "
10384                     "atom header");
10385                 break;
10386               }
10387             }
10388             break;
10389           }
10390           /* skip to the next entry */
10391           if (!gst_byte_reader_skip (&dref, size - 8))
10392             break;
10393         } else {
10394           GST_WARNING_OBJECT (qtdemux, "Error parsing dref atom");
10395         }
10396       }
10397       GST_DEBUG_OBJECT (qtdemux, "Finished parsing dref atom");
10398     }
10399   }
10400   return uri;
10401 }
10402
10403 #define AMR_NB_ALL_MODES        0x81ff
10404 #define AMR_WB_ALL_MODES        0x83ff
10405 static guint
10406 qtdemux_parse_amr_bitrate (GstBuffer * buf, gboolean wb)
10407 {
10408   /* The 'damr' atom is of the form:
10409    *
10410    * | vendor | decoder_ver | mode_set | mode_change_period | frames/sample |
10411    *    32 b       8 b          16 b           8 b                 8 b
10412    *
10413    * The highest set bit of the first 7 (AMR-NB) or 8 (AMR-WB) bits of mode_set
10414    * represents the highest mode used in the stream (and thus the maximum
10415    * bitrate), with a couple of special cases as seen below.
10416    */
10417
10418   /* Map of frame type ID -> bitrate */
10419   static const guint nb_bitrates[] = {
10420     4750, 5150, 5900, 6700, 7400, 7950, 10200, 12200
10421   };
10422   static const guint wb_bitrates[] = {
10423     6600, 8850, 12650, 14250, 15850, 18250, 19850, 23050, 23850
10424   };
10425   GstMapInfo map;
10426   gsize max_mode;
10427   guint16 mode_set;
10428
10429   gst_buffer_map (buf, &map, GST_MAP_READ);
10430
10431   if (map.size != 0x11) {
10432     GST_DEBUG ("Atom should have size 0x11, not %" G_GSIZE_FORMAT, map.size);
10433     goto bad_data;
10434   }
10435
10436   if (QT_FOURCC (map.data + 4) != FOURCC_damr) {
10437     GST_DEBUG ("Unknown atom in %" GST_FOURCC_FORMAT,
10438         GST_FOURCC_ARGS (QT_UINT32 (map.data + 4)));
10439     goto bad_data;
10440   }
10441
10442   mode_set = QT_UINT16 (map.data + 13);
10443
10444   if (mode_set == (wb ? AMR_WB_ALL_MODES : AMR_NB_ALL_MODES))
10445     max_mode = 7 + (wb ? 1 : 0);
10446   else
10447     /* AMR-NB modes fo from 0-7, and AMR-WB modes go from 0-8 */
10448     max_mode = g_bit_nth_msf ((gulong) mode_set & (wb ? 0x1ff : 0xff), -1);
10449
10450   if (max_mode == -1) {
10451     GST_DEBUG ("No mode indication was found (mode set) = %x",
10452         (guint) mode_set);
10453     goto bad_data;
10454   }
10455
10456   gst_buffer_unmap (buf, &map);
10457   return wb ? wb_bitrates[max_mode] : nb_bitrates[max_mode];
10458
10459 bad_data:
10460   gst_buffer_unmap (buf, &map);
10461   return 0;
10462 }
10463
10464 static gboolean
10465 qtdemux_parse_transformation_matrix (GstQTDemux * qtdemux,
10466     GstByteReader * reader, guint32 * matrix, const gchar * atom)
10467 {
10468   /*
10469    * 9 values of 32 bits (fixed point 16.16, except 2 5 and 8 that are 2.30)
10470    * [0 1 2]
10471    * [3 4 5]
10472    * [6 7 8]
10473    */
10474
10475   if (gst_byte_reader_get_remaining (reader) < 36)
10476     return FALSE;
10477
10478   matrix[0] = gst_byte_reader_get_uint32_be_unchecked (reader);
10479   matrix[1] = gst_byte_reader_get_uint32_be_unchecked (reader);
10480   matrix[2] = gst_byte_reader_get_uint32_be_unchecked (reader);
10481   matrix[3] = gst_byte_reader_get_uint32_be_unchecked (reader);
10482   matrix[4] = gst_byte_reader_get_uint32_be_unchecked (reader);
10483   matrix[5] = gst_byte_reader_get_uint32_be_unchecked (reader);
10484   matrix[6] = gst_byte_reader_get_uint32_be_unchecked (reader);
10485   matrix[7] = gst_byte_reader_get_uint32_be_unchecked (reader);
10486   matrix[8] = gst_byte_reader_get_uint32_be_unchecked (reader);
10487
10488   GST_DEBUG_OBJECT (qtdemux, "Transformation matrix from atom %s", atom);
10489   GST_DEBUG_OBJECT (qtdemux, "%u.%u %u.%u %u.%u", matrix[0] >> 16,
10490       matrix[0] & 0xFFFF, matrix[1] >> 16, matrix[1] & 0xFF, matrix[2] >> 16,
10491       matrix[2] & 0xFF);
10492   GST_DEBUG_OBJECT (qtdemux, "%u.%u %u.%u %u.%u", matrix[3] >> 16,
10493       matrix[3] & 0xFFFF, matrix[4] >> 16, matrix[4] & 0xFF, matrix[5] >> 16,
10494       matrix[5] & 0xFF);
10495   GST_DEBUG_OBJECT (qtdemux, "%u.%u %u.%u %u.%u", matrix[6] >> 16,
10496       matrix[6] & 0xFFFF, matrix[7] >> 16, matrix[7] & 0xFF, matrix[8] >> 16,
10497       matrix[8] & 0xFF);
10498
10499   return TRUE;
10500 }
10501
10502 static void
10503 qtdemux_inspect_transformation_matrix (GstQTDemux * qtdemux,
10504     QtDemuxStream * stream, guint32 * matrix, GstTagList ** taglist)
10505 {
10506
10507 /* [a b c]
10508  * [d e f]
10509  * [g h i]
10510  *
10511  * This macro will only compare value abdegh, it expects cfi to have already
10512  * been checked
10513  */
10514 #define QTCHECK_MATRIX(m,a,b,d,e) ((m)[0] == (a << 16) && (m)[1] == (b << 16) && \
10515                                    (m)[3] == (d << 16) && (m)[4] == (e << 16))
10516
10517   /* only handle the cases where the last column has standard values */
10518   if (matrix[2] == 0 && matrix[5] == 0 && matrix[8] == 1 << 30) {
10519     const gchar *rotation_tag = NULL;
10520
10521     /* no rotation needed */
10522     if (QTCHECK_MATRIX (matrix, 1, 0, 0, 1)) {
10523       /* NOP */
10524     } else if (QTCHECK_MATRIX (matrix, 0, 1, G_MAXUINT16, 0)) {
10525       rotation_tag = "rotate-90";
10526     } else if (QTCHECK_MATRIX (matrix, G_MAXUINT16, 0, 0, G_MAXUINT16)) {
10527       rotation_tag = "rotate-180";
10528     } else if (QTCHECK_MATRIX (matrix, 0, G_MAXUINT16, 1, 0)) {
10529       rotation_tag = "rotate-270";
10530     } else {
10531       GST_FIXME_OBJECT (qtdemux, "Unhandled transformation matrix values");
10532     }
10533
10534     GST_DEBUG_OBJECT (qtdemux, "Transformation matrix rotation %s",
10535         GST_STR_NULL (rotation_tag));
10536     if (rotation_tag != NULL) {
10537       if (*taglist == NULL)
10538         *taglist = gst_tag_list_new_empty ();
10539       gst_tag_list_add (*taglist, GST_TAG_MERGE_REPLACE,
10540           GST_TAG_IMAGE_ORIENTATION, rotation_tag, NULL);
10541     }
10542   } else {
10543     GST_FIXME_OBJECT (qtdemux, "Unhandled transformation matrix values");
10544   }
10545 }
10546
10547 static gboolean
10548 qtdemux_parse_protection_aavd (GstQTDemux * qtdemux,
10549     QtDemuxStream * stream, GNode * container, guint32 * original_fmt)
10550 {
10551   GNode *adrm;
10552   guint32 adrm_size;
10553   GstBuffer *adrm_buf = NULL;
10554   QtDemuxAavdEncryptionInfo *info;
10555
10556   adrm = qtdemux_tree_get_child_by_type (container, FOURCC_adrm);
10557   if (G_UNLIKELY (!adrm)) {
10558     GST_ERROR_OBJECT (qtdemux, "aavd box does not contain mandatory adrm box");
10559     return FALSE;
10560   }
10561   adrm_size = QT_UINT32 (adrm->data);
10562   adrm_buf = gst_buffer_new_memdup (adrm->data, adrm_size);
10563
10564   stream->protection_scheme_type = FOURCC_aavd;
10565
10566   if (!stream->protection_scheme_info)
10567     stream->protection_scheme_info = g_new0 (QtDemuxAavdEncryptionInfo, 1);
10568
10569   info = (QtDemuxAavdEncryptionInfo *) stream->protection_scheme_info;
10570
10571   if (info->default_properties)
10572     gst_structure_free (info->default_properties);
10573   info->default_properties = gst_structure_new ("application/x-aavd",
10574       "encrypted", G_TYPE_BOOLEAN, TRUE,
10575       "adrm", GST_TYPE_BUFFER, adrm_buf, NULL);
10576   gst_buffer_unref (adrm_buf);
10577
10578   *original_fmt = FOURCC_mp4a;
10579   return TRUE;
10580 }
10581
10582 /* Parses the boxes defined in ISO/IEC 14496-12 that enable support for
10583  * protected streams (sinf, frma, schm and schi); if the protection scheme is
10584  * Common Encryption (cenc), the function will also parse the tenc box (defined
10585  * in ISO/IEC 23001-7). @container points to the node that contains these boxes
10586  * (typically an enc[v|a|t|s] sample entry); the function will set
10587  * @original_fmt to the fourcc of the original unencrypted stream format.
10588  * Returns TRUE if successful; FALSE otherwise. */
10589 static gboolean
10590 qtdemux_parse_protection_scheme_info (GstQTDemux * qtdemux,
10591     QtDemuxStream * stream, GNode * container, guint32 * original_fmt)
10592 {
10593   GNode *sinf;
10594   GNode *frma;
10595   GNode *schm;
10596   GNode *schi;
10597   QtDemuxCencSampleSetInfo *info;
10598   GNode *tenc;
10599   const guint8 *tenc_data;
10600
10601   g_return_val_if_fail (qtdemux != NULL, FALSE);
10602   g_return_val_if_fail (stream != NULL, FALSE);
10603   g_return_val_if_fail (container != NULL, FALSE);
10604   g_return_val_if_fail (original_fmt != NULL, FALSE);
10605
10606   sinf = qtdemux_tree_get_child_by_type (container, FOURCC_sinf);
10607   if (G_UNLIKELY (!sinf)) {
10608     if (stream->protection_scheme_type == FOURCC_cenc
10609         || stream->protection_scheme_type == FOURCC_cbcs) {
10610       GST_ERROR_OBJECT (qtdemux, "sinf box does not contain schi box, which is "
10611           "mandatory for Common Encryption");
10612       return FALSE;
10613     }
10614     return TRUE;
10615   }
10616
10617   frma = qtdemux_tree_get_child_by_type (sinf, FOURCC_frma);
10618   if (G_UNLIKELY (!frma)) {
10619     GST_ERROR_OBJECT (qtdemux, "sinf box does not contain mandatory frma box");
10620     return FALSE;
10621   }
10622
10623   *original_fmt = QT_FOURCC ((const guint8 *) frma->data + 8);
10624   GST_DEBUG_OBJECT (qtdemux, "original stream format: '%" GST_FOURCC_FORMAT "'",
10625       GST_FOURCC_ARGS (*original_fmt));
10626
10627   schm = qtdemux_tree_get_child_by_type (sinf, FOURCC_schm);
10628   if (!schm) {
10629     GST_DEBUG_OBJECT (qtdemux, "sinf box does not contain schm box");
10630     return FALSE;
10631   }
10632   stream->protection_scheme_type = QT_FOURCC ((const guint8 *) schm->data + 12);
10633   stream->protection_scheme_version =
10634       QT_UINT32 ((const guint8 *) schm->data + 16);
10635
10636   GST_DEBUG_OBJECT (qtdemux,
10637       "protection_scheme_type: %" GST_FOURCC_FORMAT ", "
10638       "protection_scheme_version: %#010x",
10639       GST_FOURCC_ARGS (stream->protection_scheme_type),
10640       stream->protection_scheme_version);
10641
10642   schi = qtdemux_tree_get_child_by_type (sinf, FOURCC_schi);
10643   if (!schi) {
10644     GST_DEBUG_OBJECT (qtdemux, "sinf box does not contain schi box");
10645     return FALSE;
10646   }
10647   if (stream->protection_scheme_type != FOURCC_cenc &&
10648       stream->protection_scheme_type != FOURCC_piff &&
10649       stream->protection_scheme_type != FOURCC_cbcs) {
10650     GST_ERROR_OBJECT (qtdemux,
10651         "Invalid protection_scheme_type: %" GST_FOURCC_FORMAT,
10652         GST_FOURCC_ARGS (stream->protection_scheme_type));
10653     return FALSE;
10654   }
10655
10656   if (G_UNLIKELY (!stream->protection_scheme_info))
10657     stream->protection_scheme_info =
10658         g_malloc0 (sizeof (QtDemuxCencSampleSetInfo));
10659
10660   info = (QtDemuxCencSampleSetInfo *) stream->protection_scheme_info;
10661
10662   if (stream->protection_scheme_type == FOURCC_cenc
10663       || stream->protection_scheme_type == FOURCC_cbcs) {
10664     guint8 is_encrypted;
10665     guint8 iv_size;
10666     guint8 constant_iv_size = 0;
10667     const guint8 *default_kid;
10668     guint8 crypt_byte_block = 0;
10669     guint8 skip_byte_block = 0;
10670     const guint8 *constant_iv = NULL;
10671
10672     tenc = qtdemux_tree_get_child_by_type (schi, FOURCC_tenc);
10673     if (!tenc) {
10674       GST_ERROR_OBJECT (qtdemux, "schi box does not contain tenc box, "
10675           "which is mandatory for Common Encryption");
10676       return FALSE;
10677     }
10678     tenc_data = (const guint8 *) tenc->data + 12;
10679     is_encrypted = QT_UINT8 (tenc_data + 2);
10680     iv_size = QT_UINT8 (tenc_data + 3);
10681     default_kid = (tenc_data + 4);
10682     if (stream->protection_scheme_type == FOURCC_cbcs) {
10683       guint8 possible_pattern_info;
10684       if (iv_size == 0) {
10685         constant_iv_size = QT_UINT8 (tenc_data + 20);
10686         if (constant_iv_size != 8 && constant_iv_size != 16) {
10687           GST_ERROR_OBJECT (qtdemux,
10688               "constant IV size should be 8 or 16, not %hhu", constant_iv_size);
10689           return FALSE;
10690         }
10691         constant_iv = (tenc_data + 21);
10692       }
10693       possible_pattern_info = QT_UINT8 (tenc_data + 1);
10694       crypt_byte_block = (possible_pattern_info >> 4) & 0x0f;
10695       skip_byte_block = possible_pattern_info & 0x0f;
10696     }
10697     qtdemux_update_default_sample_cenc_settings (qtdemux, info,
10698         is_encrypted, stream->protection_scheme_type, iv_size, default_kid,
10699         crypt_byte_block, skip_byte_block, constant_iv_size, constant_iv);
10700   } else if (stream->protection_scheme_type == FOURCC_piff) {
10701     GstByteReader br;
10702     static const guint8 piff_track_encryption_uuid[] = {
10703       0x89, 0x74, 0xdb, 0xce, 0x7b, 0xe7, 0x4c, 0x51,
10704       0x84, 0xf9, 0x71, 0x48, 0xf9, 0x88, 0x25, 0x54
10705     };
10706
10707     tenc = qtdemux_tree_get_child_by_type (schi, FOURCC_uuid);
10708     if (!tenc) {
10709       GST_ERROR_OBJECT (qtdemux, "schi box does not contain tenc box, "
10710           "which is mandatory for Common Encryption");
10711       return FALSE;
10712     }
10713
10714     tenc_data = (const guint8 *) tenc->data + 8;
10715     if (memcmp (tenc_data, piff_track_encryption_uuid, 16) != 0) {
10716       gchar *box_uuid = qtdemux_uuid_bytes_to_string (tenc_data);
10717       GST_ERROR_OBJECT (qtdemux,
10718           "Unsupported track encryption box with uuid: %s", box_uuid);
10719       g_free (box_uuid);
10720       return FALSE;
10721     }
10722     tenc_data = (const guint8 *) tenc->data + 16 + 12;
10723     gst_byte_reader_init (&br, tenc_data, 20);
10724     if (!qtdemux_update_default_piff_encryption_settings (qtdemux, info, &br)) {
10725       GST_ERROR_OBJECT (qtdemux, "PIFF track box parsing error");
10726       return FALSE;
10727     }
10728     stream->protection_scheme_type = FOURCC_cenc;
10729   }
10730
10731   return TRUE;
10732 }
10733
10734 static gint
10735 qtdemux_track_id_compare_func (QtDemuxStream ** stream1,
10736     QtDemuxStream ** stream2)
10737 {
10738   return (gint) (*stream1)->track_id - (gint) (*stream2)->track_id;
10739 }
10740
10741 static gboolean
10742 qtdemux_parse_stereo_svmi_atom (GstQTDemux * qtdemux, QtDemuxStream * stream,
10743     GNode * stbl)
10744 {
10745   GNode *svmi;
10746
10747   /*parse svmi header if existing */
10748   svmi = qtdemux_tree_get_child_by_type (stbl, FOURCC_svmi);
10749   if (svmi) {
10750     guint len = QT_UINT32 ((guint8 *) svmi->data);
10751     guint32 version = QT_UINT32 ((guint8 *) svmi->data + 8);
10752     if (!version) {
10753       GstVideoMultiviewMode mode = GST_VIDEO_MULTIVIEW_MODE_NONE;
10754       GstVideoMultiviewFlags flags = GST_VIDEO_MULTIVIEW_FLAGS_NONE;
10755       guint8 frame_type, frame_layout;
10756       guint32 stereo_mono_change_count;
10757
10758       if (len < 18)
10759         return FALSE;
10760
10761       /* MPEG-A stereo video */
10762       if (qtdemux->major_brand == FOURCC_ss02)
10763         flags |= GST_VIDEO_MULTIVIEW_FLAGS_MIXED_MONO;
10764
10765       frame_type = QT_UINT8 ((guint8 *) svmi->data + 12);
10766       frame_layout = QT_UINT8 ((guint8 *) svmi->data + 13) & 0x01;
10767       stereo_mono_change_count = QT_UINT32 ((guint8 *) svmi->data + 14);
10768
10769       switch (frame_type) {
10770         case 0:
10771           mode = GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE;
10772           break;
10773         case 1:
10774           mode = GST_VIDEO_MULTIVIEW_MODE_ROW_INTERLEAVED;
10775           break;
10776         case 2:
10777           mode = GST_VIDEO_MULTIVIEW_MODE_FRAME_BY_FRAME;
10778           break;
10779         case 3:
10780           /* mode 3 is primary/secondary view sequence, ie
10781            * left/right views in separate tracks. See section 7.2
10782            * of ISO/IEC 23000-11:2009 */
10783           /* In the future this might be supported using related
10784            * streams, like an enhancement track - if files like this
10785            * ever exist */
10786           GST_FIXME_OBJECT (qtdemux,
10787               "Implement stereo video in separate streams");
10788       }
10789
10790       if ((frame_layout & 0x1) == 0)
10791         flags |= GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST;
10792
10793       GST_LOG_OBJECT (qtdemux,
10794           "StereoVideo: composition type: %u, is_left_first: %u",
10795           frame_type, frame_layout);
10796
10797       if (stereo_mono_change_count > 1) {
10798         GST_FIXME_OBJECT (qtdemux,
10799             "Mixed-mono flags are not yet supported in qtdemux.");
10800       }
10801
10802       stream->multiview_mode = mode;
10803       stream->multiview_flags = flags;
10804     }
10805   }
10806
10807   return TRUE;
10808 }
10809
10810 /* parse the traks.
10811  * With each track we associate a new QtDemuxStream that contains all the info
10812  * about the trak.
10813  * traks that do not decode to something (like strm traks) will not have a pad.
10814  */
10815 static gboolean
10816 qtdemux_parse_trak (GstQTDemux * qtdemux, GNode * trak)
10817 {
10818   GstByteReader tkhd;
10819   int offset;
10820   GNode *mdia;
10821   GNode *mdhd;
10822   GNode *hdlr;
10823   GNode *minf;
10824   GNode *stbl;
10825   GNode *stsd;
10826   GNode *mp4a;
10827   GNode *mp4v;
10828   GNode *esds;
10829   GNode *tref;
10830   GNode *udta;
10831
10832   QtDemuxStream *stream = NULL;
10833   const guint8 *stsd_data;
10834   const guint8 *stsd_entry_data;
10835   guint remaining_stsd_len;
10836   guint stsd_entry_count;
10837   guint stsd_index;
10838   guint16 lang_code;            /* quicktime lang code or packed iso code */
10839   guint32 version;
10840   guint32 tkhd_flags = 0;
10841   guint8 tkhd_version = 0;
10842   guint32 w = 0, h = 0;
10843   guint value_size, stsd_len, len;
10844   guint32 track_id;
10845   guint32 dummy;
10846
10847   GST_DEBUG_OBJECT (qtdemux, "parse_trak");
10848
10849   if (!qtdemux_tree_get_child_by_type_full (trak, FOURCC_tkhd, &tkhd)
10850       || !gst_byte_reader_get_uint8 (&tkhd, &tkhd_version)
10851       || !gst_byte_reader_get_uint24_be (&tkhd, &tkhd_flags))
10852     goto corrupt_file;
10853
10854   /* pick between 64 or 32 bits */
10855   value_size = tkhd_version == 1 ? 8 : 4;
10856   if (!gst_byte_reader_skip (&tkhd, value_size * 2) ||
10857       !gst_byte_reader_get_uint32_be (&tkhd, &track_id))
10858     goto corrupt_file;
10859
10860   /* Check if current moov has duplicated track_id */
10861   if (qtdemux_find_stream (qtdemux, track_id))
10862     goto existing_stream;
10863
10864   stream = _create_stream (qtdemux, track_id);
10865   stream->stream_tags = gst_tag_list_make_writable (stream->stream_tags);
10866
10867   /* need defaults for fragments */
10868   qtdemux_parse_trex (qtdemux, stream, &dummy, &dummy, &dummy);
10869
10870   if ((tkhd_flags & 1) == 0)
10871     stream->disabled = TRUE;
10872
10873   GST_LOG_OBJECT (qtdemux, "track[tkhd] version/flags/id: 0x%02x/%06x/%u",
10874       tkhd_version, tkhd_flags, stream->track_id);
10875
10876   if (!(mdia = qtdemux_tree_get_child_by_type (trak, FOURCC_mdia)))
10877     goto corrupt_file;
10878
10879   if (!(mdhd = qtdemux_tree_get_child_by_type (mdia, FOURCC_mdhd))) {
10880     /* be nice for some crooked mjp2 files that use mhdr for mdhd */
10881     if (qtdemux->major_brand != FOURCC_mjp2 ||
10882         !(mdhd = qtdemux_tree_get_child_by_type (mdia, FOURCC_mhdr)))
10883       goto corrupt_file;
10884   }
10885
10886   len = QT_UINT32 ((guint8 *) mdhd->data);
10887   version = QT_UINT32 ((guint8 *) mdhd->data + 8);
10888   GST_LOG_OBJECT (qtdemux, "track version/flags: %08x", version);
10889   if (version == 0x01000000) {
10890     if (len < 42)
10891       goto corrupt_file;
10892     stream->timescale = QT_UINT32 ((guint8 *) mdhd->data + 28);
10893     stream->duration = QT_UINT64 ((guint8 *) mdhd->data + 32);
10894     lang_code = QT_UINT16 ((guint8 *) mdhd->data + 40);
10895   } else {
10896     if (len < 30)
10897       goto corrupt_file;
10898     stream->timescale = QT_UINT32 ((guint8 *) mdhd->data + 20);
10899     stream->duration = QT_UINT32 ((guint8 *) mdhd->data + 24);
10900     lang_code = QT_UINT16 ((guint8 *) mdhd->data + 28);
10901   }
10902
10903   if (lang_code < 0x400) {
10904     qtdemux_lang_map_qt_code_to_iso (stream->lang_id, lang_code);
10905   } else if (lang_code == 0x7fff) {
10906     stream->lang_id[0] = 0;     /* unspecified */
10907   } else {
10908     stream->lang_id[0] = 0x60 + ((lang_code >> 10) & 0x1F);
10909     stream->lang_id[1] = 0x60 + ((lang_code >> 5) & 0x1F);
10910     stream->lang_id[2] = 0x60 + (lang_code & 0x1F);
10911     stream->lang_id[3] = 0;
10912   }
10913
10914   GST_LOG_OBJECT (qtdemux, "track timescale: %" G_GUINT32_FORMAT,
10915       stream->timescale);
10916   GST_LOG_OBJECT (qtdemux, "track duration: %" G_GUINT64_FORMAT,
10917       stream->duration);
10918   GST_LOG_OBJECT (qtdemux, "track language code/id: 0x%04x/%s",
10919       lang_code, stream->lang_id);
10920
10921   if (G_UNLIKELY (stream->timescale == 0 || qtdemux->timescale == 0))
10922     goto corrupt_file;
10923
10924   if ((tref = qtdemux_tree_get_child_by_type (trak, FOURCC_tref))) {
10925     /* chapters track reference */
10926     GNode *chap = qtdemux_tree_get_child_by_type (tref, FOURCC_chap);
10927     if (chap) {
10928       gsize length = GST_READ_UINT32_BE (chap->data);
10929       if (qtdemux->chapters_track_id)
10930         GST_FIXME_OBJECT (qtdemux, "Multiple CHAP tracks");
10931
10932       if (length >= 12) {
10933         qtdemux->chapters_track_id =
10934             GST_READ_UINT32_BE ((gint8 *) chap->data + 8);
10935       }
10936     }
10937   }
10938
10939   /* fragmented files may have bogus duration in moov */
10940   if (!qtdemux->fragmented &&
10941       qtdemux->duration != G_MAXINT64 && stream->duration != G_MAXINT32) {
10942     guint64 tdur1, tdur2;
10943
10944     /* don't overflow */
10945     tdur1 = stream->timescale * (guint64) qtdemux->duration;
10946     tdur2 = qtdemux->timescale * (guint64) stream->duration;
10947
10948     /* HACK:
10949      * some of those trailers, nowadays, have prologue images that are
10950      * themselves video tracks as well. I haven't really found a way to
10951      * identify those yet, except for just looking at their duration. */
10952     if (tdur1 != 0 && (tdur2 * 10 / tdur1) < 2) {
10953       GST_WARNING_OBJECT (qtdemux,
10954           "Track shorter than 20%% (%" G_GUINT64_FORMAT "/%" G_GUINT32_FORMAT
10955           " vs. %" G_GUINT64_FORMAT "/%" G_GUINT32_FORMAT ") of the stream "
10956           "found, assuming preview image or something; skipping track",
10957           stream->duration, stream->timescale, qtdemux->duration,
10958           qtdemux->timescale);
10959       gst_qtdemux_stream_unref (stream);
10960       return TRUE;
10961     }
10962   }
10963
10964   if (!(hdlr = qtdemux_tree_get_child_by_type (mdia, FOURCC_hdlr)))
10965     goto corrupt_file;
10966
10967   GST_LOG_OBJECT (qtdemux, "track type: %" GST_FOURCC_FORMAT,
10968       GST_FOURCC_ARGS (QT_FOURCC ((guint8 *) hdlr->data + 12)));
10969
10970   len = QT_UINT32 ((guint8 *) hdlr->data);
10971   if (len >= 20)
10972     stream->subtype = QT_FOURCC ((guint8 *) hdlr->data + 16);
10973   GST_LOG_OBJECT (qtdemux, "track subtype: %" GST_FOURCC_FORMAT,
10974       GST_FOURCC_ARGS (stream->subtype));
10975
10976   if (!(minf = qtdemux_tree_get_child_by_type (mdia, FOURCC_minf)))
10977     goto corrupt_file;
10978
10979   if (!(stbl = qtdemux_tree_get_child_by_type (minf, FOURCC_stbl)))
10980     goto corrupt_file;
10981
10982   /* Parse out svmi (and later st3d/sv3d) atoms */
10983   if (!qtdemux_parse_stereo_svmi_atom (qtdemux, stream, stbl))
10984     goto corrupt_file;
10985
10986   /* parse rest of tkhd */
10987   if (stream->subtype == FOURCC_vide) {
10988     guint32 matrix[9];
10989
10990     /* version 1 uses some 64-bit ints */
10991     if (!gst_byte_reader_skip (&tkhd, 20 + value_size))
10992       goto corrupt_file;
10993
10994     if (!qtdemux_parse_transformation_matrix (qtdemux, &tkhd, matrix, "tkhd"))
10995       goto corrupt_file;
10996
10997     if (!gst_byte_reader_get_uint32_be (&tkhd, &w)
10998         || !gst_byte_reader_get_uint32_be (&tkhd, &h))
10999       goto corrupt_file;
11000
11001     qtdemux_inspect_transformation_matrix (qtdemux, stream, matrix,
11002         &stream->stream_tags);
11003   }
11004
11005   /* parse stsd */
11006   if (!(stsd = qtdemux_tree_get_child_by_type (stbl, FOURCC_stsd)))
11007     goto corrupt_file;
11008   stsd_data = (const guint8 *) stsd->data;
11009
11010   /* stsd should at least have one entry */
11011   stsd_len = QT_UINT32 (stsd_data);
11012   if (stsd_len < 24) {
11013     /* .. but skip stream with empty stsd produced by some Vivotek cameras */
11014     if (stream->subtype == FOURCC_vivo) {
11015       gst_qtdemux_stream_unref (stream);
11016       return TRUE;
11017     } else {
11018       goto corrupt_file;
11019     }
11020   }
11021
11022   stream->stsd_entries_length = stsd_entry_count = QT_UINT32 (stsd_data + 12);
11023   /* each stsd entry must contain at least 8 bytes */
11024   if (stream->stsd_entries_length == 0
11025       || stream->stsd_entries_length > stsd_len / 8) {
11026     stream->stsd_entries_length = 0;
11027     goto corrupt_file;
11028   }
11029   stream->stsd_entries = g_new0 (QtDemuxStreamStsdEntry, stsd_entry_count);
11030   GST_LOG_OBJECT (qtdemux, "stsd len:           %d", stsd_len);
11031   GST_LOG_OBJECT (qtdemux, "stsd entry count:   %u", stsd_entry_count);
11032
11033   stsd_entry_data = stsd_data + 16;
11034   remaining_stsd_len = stsd_len - 16;
11035   for (stsd_index = 0; stsd_index < stsd_entry_count; stsd_index++) {
11036     guint32 fourcc;
11037     gchar *codec = NULL;
11038     QtDemuxStreamStsdEntry *entry = &stream->stsd_entries[stsd_index];
11039
11040     /* and that entry should fit within stsd */
11041     len = QT_UINT32 (stsd_entry_data);
11042     if (len > remaining_stsd_len)
11043       goto corrupt_file;
11044
11045     entry->fourcc = fourcc = QT_FOURCC (stsd_entry_data + 4);
11046     GST_LOG_OBJECT (qtdemux, "stsd type:          %" GST_FOURCC_FORMAT,
11047         GST_FOURCC_ARGS (entry->fourcc));
11048     GST_LOG_OBJECT (qtdemux, "stsd type len:      %d", len);
11049
11050     if ((fourcc == FOURCC_drms) || (fourcc == FOURCC_drmi))
11051       goto error_encrypted;
11052
11053     if (fourcc == FOURCC_aavd) {
11054       if (stream->subtype != FOURCC_soun) {
11055         GST_ERROR_OBJECT (qtdemux,
11056             "Unexpeced stsd type 'aavd' outside 'soun' track");
11057       } else {
11058         /* encrypted audio with sound sample description v0 */
11059         GNode *enc = qtdemux_tree_get_child_by_type (stsd, fourcc);
11060         stream->protected = TRUE;
11061         if (!qtdemux_parse_protection_aavd (qtdemux, stream, enc, &fourcc))
11062           GST_ERROR_OBJECT (qtdemux, "Failed to parse protection scheme info");
11063       }
11064     }
11065
11066     if (fourcc == FOURCC_encv || fourcc == FOURCC_enca) {
11067       /* FIXME this looks wrong, there might be multiple children
11068        * with the same type */
11069       GNode *enc = qtdemux_tree_get_child_by_type (stsd, fourcc);
11070       stream->protected = TRUE;
11071       if (!qtdemux_parse_protection_scheme_info (qtdemux, stream, enc, &fourcc))
11072         GST_ERROR_OBJECT (qtdemux, "Failed to parse protection scheme info");
11073     }
11074
11075     if (stream->subtype == FOURCC_vide) {
11076       GNode *colr;
11077       GNode *fiel;
11078       GNode *pasp;
11079       gboolean gray;
11080       gint depth, palette_size, palette_count;
11081       guint32 *palette_data = NULL;
11082
11083       entry->sampled = TRUE;
11084
11085       stream->display_width = w >> 16;
11086       stream->display_height = h >> 16;
11087
11088       offset = 16;
11089       if (len < 86)             /* TODO verify */
11090         goto corrupt_file;
11091
11092       entry->width = QT_UINT16 (stsd_entry_data + offset + 16);
11093       entry->height = QT_UINT16 (stsd_entry_data + offset + 18);
11094       entry->fps_n = 0;         /* this is filled in later */
11095       entry->fps_d = 0;         /* this is filled in later */
11096       entry->bits_per_sample = QT_UINT16 (stsd_entry_data + offset + 66);
11097       entry->color_table_id = QT_UINT16 (stsd_entry_data + offset + 68);
11098
11099       /* if color_table_id is 0, ctab atom must follow; however some files
11100        * produced by TMPEGEnc have color_table_id = 0 and no ctab atom, so
11101        * if color table is not present we'll correct the value */
11102       if (entry->color_table_id == 0 &&
11103           (len < 90
11104               || QT_FOURCC (stsd_entry_data + offset + 70) != FOURCC_ctab)) {
11105         entry->color_table_id = -1;
11106       }
11107
11108       GST_LOG_OBJECT (qtdemux, "width %d, height %d, bps %d, color table id %d",
11109           entry->width, entry->height, entry->bits_per_sample,
11110           entry->color_table_id);
11111
11112       depth = entry->bits_per_sample;
11113
11114       /* more than 32 bits means grayscale */
11115       gray = (depth > 32);
11116       /* low 32 bits specify the depth  */
11117       depth &= 0x1F;
11118
11119       /* different number of palette entries is determined by depth. */
11120       palette_count = 0;
11121       if ((depth == 1) || (depth == 2) || (depth == 4) || (depth == 8))
11122         palette_count = (1 << depth);
11123       palette_size = palette_count * 4;
11124
11125       if (entry->color_table_id) {
11126         switch (palette_count) {
11127           case 0:
11128             break;
11129           case 2:
11130             palette_data = g_memdup2 (ff_qt_default_palette_2, palette_size);
11131             break;
11132           case 4:
11133             palette_data = g_memdup2 (ff_qt_default_palette_4, palette_size);
11134             break;
11135           case 16:
11136             if (gray)
11137               palette_data =
11138                   g_memdup2 (ff_qt_grayscale_palette_16, palette_size);
11139             else
11140               palette_data = g_memdup2 (ff_qt_default_palette_16, palette_size);
11141             break;
11142           case 256:
11143             if (gray)
11144               palette_data =
11145                   g_memdup2 (ff_qt_grayscale_palette_256, palette_size);
11146             else
11147               palette_data =
11148                   g_memdup2 (ff_qt_default_palette_256, palette_size);
11149             break;
11150           default:
11151             GST_ELEMENT_WARNING (qtdemux, STREAM, DEMUX,
11152                 (_("The video in this file might not play correctly.")),
11153                 ("unsupported palette depth %d", depth));
11154             break;
11155         }
11156       } else {
11157         gint i, j, start, end;
11158
11159         if (len < 94)
11160           goto corrupt_file;
11161
11162         /* read table */
11163         start = QT_UINT32 (stsd_entry_data + offset + 70);
11164         palette_count = QT_UINT16 (stsd_entry_data + offset + 74);
11165         end = QT_UINT16 (stsd_entry_data + offset + 76);
11166
11167         GST_LOG_OBJECT (qtdemux, "start %d, end %d, palette_count %d",
11168             start, end, palette_count);
11169
11170         if (end > 255)
11171           end = 255;
11172         if (start > end)
11173           start = end;
11174
11175         if (len < 94 + (end - start) * 8)
11176           goto corrupt_file;
11177
11178         /* palette is always the same size */
11179         palette_data = g_malloc0 (256 * 4);
11180         palette_size = 256 * 4;
11181
11182         for (j = 0, i = start; i <= end; j++, i++) {
11183           guint32 a, r, g, b;
11184
11185           a = QT_UINT16 (stsd_entry_data + offset + 78 + (j * 8));
11186           r = QT_UINT16 (stsd_entry_data + offset + 80 + (j * 8));
11187           g = QT_UINT16 (stsd_entry_data + offset + 82 + (j * 8));
11188           b = QT_UINT16 (stsd_entry_data + offset + 84 + (j * 8));
11189
11190           palette_data[i] = ((a & 0xff00) << 16) | ((r & 0xff00) << 8) |
11191               (g & 0xff00) | (b >> 8);
11192         }
11193       }
11194
11195       if (entry->caps)
11196         gst_caps_unref (entry->caps);
11197
11198       entry->caps =
11199           qtdemux_video_caps (qtdemux, stream, entry, fourcc, stsd_entry_data,
11200           &codec);
11201       if (G_UNLIKELY (!entry->caps)) {
11202         g_free (palette_data);
11203         goto unknown_stream;
11204       }
11205
11206       if (codec) {
11207         gst_tag_list_add (stream->stream_tags, GST_TAG_MERGE_REPLACE,
11208             GST_TAG_VIDEO_CODEC, codec, NULL);
11209         g_free (codec);
11210         codec = NULL;
11211       }
11212
11213       if (palette_data) {
11214         GstStructure *s;
11215
11216         if (entry->rgb8_palette)
11217           gst_memory_unref (entry->rgb8_palette);
11218         entry->rgb8_palette = gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY,
11219             palette_data, palette_size, 0, palette_size, palette_data, g_free);
11220
11221         s = gst_caps_get_structure (entry->caps, 0);
11222
11223         /* non-raw video has a palette_data property. raw video has the palette as
11224          * an extra plane that we append to the output buffers before we push
11225          * them*/
11226         if (!gst_structure_has_name (s, "video/x-raw")) {
11227           GstBuffer *palette;
11228
11229           palette = gst_buffer_new ();
11230           gst_buffer_append_memory (palette, entry->rgb8_palette);
11231           entry->rgb8_palette = NULL;
11232
11233           gst_caps_set_simple (entry->caps, "palette_data",
11234               GST_TYPE_BUFFER, palette, NULL);
11235           gst_buffer_unref (palette);
11236         }
11237       } else if (palette_count != 0) {
11238         GST_ELEMENT_WARNING (qtdemux, STREAM, NOT_IMPLEMENTED,
11239             (NULL), ("Unsupported palette depth %d", depth));
11240       }
11241
11242       GST_LOG_OBJECT (qtdemux, "frame count:   %u",
11243           QT_UINT16 (stsd_entry_data + offset + 32));
11244
11245       esds = NULL;
11246       pasp = NULL;
11247       colr = NULL;
11248       fiel = NULL;
11249       /* pick 'the' stsd child */
11250       mp4v = qtdemux_tree_get_child_by_index (stsd, stsd_index);
11251       // We should skip parsing the stsd for non-protected streams if
11252       // the entry doesn't match the fourcc, since they don't change
11253       // format. However, for protected streams we can have partial
11254       // encryption, where parts of the stream are encrypted and parts
11255       // not. For both parts of such streams, we should ensure the
11256       // esds overrides are parsed for both from the stsd.
11257       if (QTDEMUX_TREE_NODE_FOURCC (mp4v) != fourcc) {
11258         if (stream->protected && QTDEMUX_TREE_NODE_FOURCC (mp4v) != FOURCC_encv)
11259           mp4v = NULL;
11260         else if (!stream->protected)
11261           mp4v = NULL;
11262       }
11263
11264       if (mp4v) {
11265         esds = qtdemux_tree_get_child_by_type (mp4v, FOURCC_esds);
11266         pasp = qtdemux_tree_get_child_by_type (mp4v, FOURCC_pasp);
11267         colr = qtdemux_tree_get_child_by_type (mp4v, FOURCC_colr);
11268         fiel = qtdemux_tree_get_child_by_type (mp4v, FOURCC_fiel);
11269       }
11270
11271       if (pasp) {
11272         const guint8 *pasp_data = (const guint8 *) pasp->data;
11273         gint len = QT_UINT32 (pasp_data);
11274
11275         if (len == 16) {
11276           CUR_STREAM (stream)->par_w = QT_UINT32 (pasp_data + 8);
11277           CUR_STREAM (stream)->par_h = QT_UINT32 (pasp_data + 12);
11278         } else {
11279           CUR_STREAM (stream)->par_w = 0;
11280           CUR_STREAM (stream)->par_h = 0;
11281         }
11282       } else {
11283         CUR_STREAM (stream)->par_w = 0;
11284         CUR_STREAM (stream)->par_h = 0;
11285       }
11286
11287       if (fiel) {
11288         const guint8 *fiel_data = (const guint8 *) fiel->data;
11289         gint len = QT_UINT32 (fiel_data);
11290
11291         if (len == 10) {
11292           CUR_STREAM (stream)->interlace_mode = GST_READ_UINT8 (fiel_data + 8);
11293           CUR_STREAM (stream)->field_order = GST_READ_UINT8 (fiel_data + 9);
11294         }
11295       }
11296
11297       if (colr) {
11298         const guint8 *colr_data = (const guint8 *) colr->data;
11299         gint len = QT_UINT32 (colr_data);
11300
11301         if (len == 19 || len == 18) {
11302           guint32 color_type = GST_READ_UINT32_LE (colr_data + 8);
11303
11304           if (color_type == FOURCC_nclx || color_type == FOURCC_nclc) {
11305             guint16 primaries = GST_READ_UINT16_BE (colr_data + 12);
11306             guint16 transfer_function = GST_READ_UINT16_BE (colr_data + 14);
11307             guint16 matrix = GST_READ_UINT16_BE (colr_data + 16);
11308             gboolean full_range = len == 19 ? colr_data[17] >> 7 : FALSE;
11309
11310             CUR_STREAM (stream)->colorimetry.primaries =
11311                 gst_video_color_primaries_from_iso (primaries);
11312             CUR_STREAM (stream)->colorimetry.transfer =
11313                 gst_video_transfer_function_from_iso (transfer_function);
11314             CUR_STREAM (stream)->colorimetry.matrix =
11315                 gst_video_color_matrix_from_iso (matrix);
11316             CUR_STREAM (stream)->colorimetry.range =
11317                 full_range ? GST_VIDEO_COLOR_RANGE_0_255 :
11318                 GST_VIDEO_COLOR_RANGE_16_235;
11319           } else {
11320             GST_DEBUG_OBJECT (qtdemux, "Unsupported color type");
11321           }
11322         } else {
11323           GST_WARNING_OBJECT (qtdemux, "Invalid colr atom size");
11324         }
11325       }
11326
11327       if (esds) {
11328         gst_qtdemux_handle_esds (qtdemux, stream, entry, esds,
11329             stream->stream_tags);
11330       } else {
11331         switch (fourcc) {
11332           case FOURCC_H264:
11333           case FOURCC_avc1:
11334           case FOURCC_avc3:
11335           {
11336             gint len = QT_UINT32 (stsd_entry_data) - 0x56;
11337             const guint8 *avc_data = stsd_entry_data + 0x56;
11338
11339             /* find avcC */
11340             while (len >= 0x8) {
11341               gint size;
11342
11343               if (QT_UINT32 (avc_data) <= len)
11344                 size = QT_UINT32 (avc_data) - 0x8;
11345               else
11346                 size = len - 0x8;
11347
11348               if (size < 1)
11349                 /* No real data, so break out */
11350                 break;
11351
11352               switch (QT_FOURCC (avc_data + 0x4)) {
11353                 case FOURCC_avcC:
11354                 {
11355                   /* parse, if found */
11356                   GstBuffer *buf;
11357
11358                   GST_DEBUG_OBJECT (qtdemux, "found avcC codec_data in stsd");
11359
11360                   /* First 4 bytes are the length of the atom, the next 4 bytes
11361                    * are the fourcc, the next 1 byte is the version, and the
11362                    * subsequent bytes are profile_tier_level structure like data. */
11363                   gst_codec_utils_h264_caps_set_level_and_profile (entry->caps,
11364                       avc_data + 8 + 1, size - 1);
11365                   buf = gst_buffer_new_and_alloc (size);
11366                   gst_buffer_fill (buf, 0, avc_data + 0x8, size);
11367                   gst_caps_set_simple (entry->caps,
11368                       "codec_data", GST_TYPE_BUFFER, buf, NULL);
11369                   gst_buffer_unref (buf);
11370
11371                   break;
11372                 }
11373                 case FOURCC_strf:
11374                 {
11375                   GstBuffer *buf;
11376
11377                   GST_DEBUG_OBJECT (qtdemux, "found strf codec_data in stsd");
11378
11379                   /* First 4 bytes are the length of the atom, the next 4 bytes
11380                    * are the fourcc, next 40 bytes are BITMAPINFOHEADER,
11381                    * next 1 byte is the version, and the
11382                    * subsequent bytes are sequence parameter set like data. */
11383
11384                   size -= 40;   /* we'll be skipping BITMAPINFOHEADER */
11385                   if (size > 1) {
11386                     gst_codec_utils_h264_caps_set_level_and_profile
11387                         (entry->caps, avc_data + 8 + 40 + 1, size - 1);
11388
11389                     buf = gst_buffer_new_and_alloc (size);
11390                     gst_buffer_fill (buf, 0, avc_data + 8 + 40, size);
11391                     gst_caps_set_simple (entry->caps,
11392                         "codec_data", GST_TYPE_BUFFER, buf, NULL);
11393                     gst_buffer_unref (buf);
11394                   }
11395                   break;
11396                 }
11397                 case FOURCC_btrt:
11398                 {
11399                   guint avg_bitrate, max_bitrate;
11400
11401                   /* bufferSizeDB, maxBitrate and avgBitrate - 4 bytes each */
11402                   if (size < 12)
11403                     break;
11404
11405                   max_bitrate = QT_UINT32 (avc_data + 0xc);
11406                   avg_bitrate = QT_UINT32 (avc_data + 0x10);
11407
11408                   if (!max_bitrate && !avg_bitrate)
11409                     break;
11410
11411                   /* Some muxers seem to swap the average and maximum bitrates
11412                    * (I'm looking at you, YouTube), so we swap for sanity. */
11413                   if (max_bitrate > 0 && max_bitrate < avg_bitrate) {
11414                     guint temp = avg_bitrate;
11415
11416                     avg_bitrate = max_bitrate;
11417                     max_bitrate = temp;
11418                   }
11419
11420                   if (max_bitrate > 0 && max_bitrate < G_MAXUINT32) {
11421                     gst_tag_list_add (stream->stream_tags,
11422                         GST_TAG_MERGE_REPLACE, GST_TAG_MAXIMUM_BITRATE,
11423                         max_bitrate, NULL);
11424                   }
11425                   if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32) {
11426                     gst_tag_list_add (stream->stream_tags,
11427                         GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE, avg_bitrate,
11428                         NULL);
11429                   }
11430
11431                   break;
11432                 }
11433
11434                 default:
11435                   break;
11436               }
11437
11438               len -= size + 8;
11439               avc_data += size + 8;
11440             }
11441
11442             break;
11443           }
11444           case FOURCC_H265:
11445           case FOURCC_hvc1:
11446           case FOURCC_hev1:
11447           case FOURCC_dvh1:
11448           case FOURCC_dvhe:
11449           {
11450             gint len = QT_UINT32 (stsd_entry_data) - 0x56;
11451             const guint8 *hevc_data = stsd_entry_data + 0x56;
11452
11453             /* find hevc */
11454             while (len >= 0x8) {
11455               gint size;
11456
11457               if (QT_UINT32 (hevc_data) <= len)
11458                 size = QT_UINT32 (hevc_data) - 0x8;
11459               else
11460                 size = len - 0x8;
11461
11462               if (size < 1)
11463                 /* No real data, so break out */
11464                 break;
11465
11466               switch (QT_FOURCC (hevc_data + 0x4)) {
11467                 case FOURCC_hvcC:
11468                 {
11469                   /* parse, if found */
11470                   GstBuffer *buf;
11471
11472                   GST_DEBUG_OBJECT (qtdemux, "found hvcC codec_data in stsd");
11473
11474                   /* First 4 bytes are the length of the atom, the next 4 bytes
11475                    * are the fourcc, the next 1 byte is the version, and the
11476                    * subsequent bytes are sequence parameter set like data. */
11477                   gst_codec_utils_h265_caps_set_level_tier_and_profile
11478                       (entry->caps, hevc_data + 8 + 1, size - 1);
11479
11480                   buf = gst_buffer_new_and_alloc (size);
11481                   gst_buffer_fill (buf, 0, hevc_data + 0x8, size);
11482                   gst_caps_set_simple (entry->caps,
11483                       "codec_data", GST_TYPE_BUFFER, buf, NULL);
11484                   gst_buffer_unref (buf);
11485                   break;
11486                 }
11487                 default:
11488                   break;
11489               }
11490               len -= size + 8;
11491               hevc_data += size + 8;
11492             }
11493             break;
11494           }
11495           case FOURCC_mp4v:
11496           case FOURCC_MP4V:
11497           case FOURCC_fmp4:
11498           case FOURCC_FMP4:
11499           case FOURCC_xvid:
11500           case FOURCC_XVID:
11501           {
11502             GNode *glbl;
11503
11504             GST_DEBUG_OBJECT (qtdemux, "found %" GST_FOURCC_FORMAT,
11505                 GST_FOURCC_ARGS (fourcc));
11506
11507             /* codec data might be in glbl extension atom */
11508             glbl = mp4v ?
11509                 qtdemux_tree_get_child_by_type (mp4v, FOURCC_glbl) : NULL;
11510             if (glbl) {
11511               guint8 *data;
11512               GstBuffer *buf;
11513               gint len;
11514
11515               GST_DEBUG_OBJECT (qtdemux, "found glbl data in stsd");
11516               data = glbl->data;
11517               len = QT_UINT32 (data);
11518               if (len > 0x8) {
11519                 len -= 0x8;
11520                 buf = gst_buffer_new_and_alloc (len);
11521                 gst_buffer_fill (buf, 0, data + 8, len);
11522                 gst_caps_set_simple (entry->caps,
11523                     "codec_data", GST_TYPE_BUFFER, buf, NULL);
11524                 gst_buffer_unref (buf);
11525               }
11526             }
11527             break;
11528           }
11529           case FOURCC_mjp2:
11530           {
11531             /* see annex I of the jpeg2000 spec */
11532             GNode *jp2h, *ihdr, *colr, *mjp2, *field, *prefix, *cmap, *cdef;
11533             const guint8 *data;
11534             const gchar *colorspace = NULL;
11535             gint ncomp = 0;
11536             guint32 ncomp_map = 0;
11537             gint32 *comp_map = NULL;
11538             guint32 nchan_def = 0;
11539             gint32 *chan_def = NULL;
11540
11541             GST_DEBUG_OBJECT (qtdemux, "found mjp2");
11542             /* some required atoms */
11543             mjp2 = qtdemux_tree_get_child_by_index (stsd, stsd_index);
11544             if (!mjp2)
11545               break;
11546             jp2h = qtdemux_tree_get_child_by_type (mjp2, FOURCC_jp2h);
11547             if (!jp2h)
11548               break;
11549
11550             /* number of components; redundant with info in codestream, but useful
11551                to a muxer */
11552             ihdr = qtdemux_tree_get_child_by_type (jp2h, FOURCC_ihdr);
11553             if (!ihdr || QT_UINT32 (ihdr->data) != 22)
11554               break;
11555             ncomp = QT_UINT16 (((guint8 *) ihdr->data) + 16);
11556
11557             colr = qtdemux_tree_get_child_by_type (jp2h, FOURCC_colr);
11558             if (!colr)
11559               break;
11560             GST_DEBUG_OBJECT (qtdemux, "found colr");
11561             /* extract colour space info */
11562             if (QT_UINT8 ((guint8 *) colr->data + 8) == 1) {
11563               switch (QT_UINT32 ((guint8 *) colr->data + 11)) {
11564                 case 16:
11565                   colorspace = "sRGB";
11566                   break;
11567                 case 17:
11568                   colorspace = "GRAY";
11569                   break;
11570                 case 18:
11571                   colorspace = "sYUV";
11572                   break;
11573                 default:
11574                   colorspace = NULL;
11575                   break;
11576               }
11577             }
11578             if (!colorspace)
11579               /* colr is required, and only values 16, 17, and 18 are specified,
11580                  so error if we have no colorspace */
11581               break;
11582
11583             /* extract component mapping */
11584             cmap = qtdemux_tree_get_child_by_type (jp2h, FOURCC_cmap);
11585             if (cmap) {
11586               guint32 cmap_len = 0;
11587               int i;
11588               cmap_len = QT_UINT32 (cmap->data);
11589               if (cmap_len >= 8) {
11590                 /* normal box, subtract off header */
11591                 cmap_len -= 8;
11592                 /* cmap: { u16 cmp; u8 mtyp; u8 pcol; }* */
11593                 if (cmap_len % 4 == 0) {
11594                   ncomp_map = (cmap_len / 4);
11595                   comp_map = g_new0 (gint32, ncomp_map);
11596                   for (i = 0; i < ncomp_map; i++) {
11597                     guint16 cmp;
11598                     guint8 mtyp, pcol;
11599                     cmp = QT_UINT16 (((guint8 *) cmap->data) + 8 + i * 4);
11600                     mtyp = QT_UINT8 (((guint8 *) cmap->data) + 8 + i * 4 + 2);
11601                     pcol = QT_UINT8 (((guint8 *) cmap->data) + 8 + i * 4 + 3);
11602                     comp_map[i] = (mtyp << 24) | (pcol << 16) | cmp;
11603                   }
11604                 }
11605               }
11606             }
11607             /* extract channel definitions */
11608             cdef = qtdemux_tree_get_child_by_type (jp2h, FOURCC_cdef);
11609             if (cdef) {
11610               guint32 cdef_len = 0;
11611               int i;
11612               cdef_len = QT_UINT32 (cdef->data);
11613               if (cdef_len >= 10) {
11614                 /* normal box, subtract off header and len */
11615                 cdef_len -= 10;
11616                 /* cdef: u16 n; { u16 cn; u16 typ; u16 asoc; }* */
11617                 if (cdef_len % 6 == 0) {
11618                   nchan_def = (cdef_len / 6);
11619                   chan_def = g_new0 (gint32, nchan_def);
11620                   for (i = 0; i < nchan_def; i++)
11621                     chan_def[i] = -1;
11622                   for (i = 0; i < nchan_def; i++) {
11623                     guint16 cn, typ, asoc;
11624                     cn = QT_UINT16 (((guint8 *) cdef->data) + 10 + i * 6);
11625                     typ = QT_UINT16 (((guint8 *) cdef->data) + 10 + i * 6 + 2);
11626                     asoc = QT_UINT16 (((guint8 *) cdef->data) + 10 + i * 6 + 4);
11627                     if (cn < nchan_def) {
11628                       switch (typ) {
11629                         case 0:
11630                           chan_def[cn] = asoc;
11631                           break;
11632                         case 1:
11633                           chan_def[cn] = 0;     /* alpha */
11634                           break;
11635                         default:
11636                           chan_def[cn] = -typ;
11637                       }
11638                     }
11639                   }
11640                 }
11641               }
11642             }
11643
11644             gst_caps_set_simple (entry->caps,
11645                 "num-components", G_TYPE_INT, ncomp, NULL);
11646             gst_caps_set_simple (entry->caps,
11647                 "colorspace", G_TYPE_STRING, colorspace, NULL);
11648
11649             if (comp_map) {
11650               GValue arr = { 0, };
11651               GValue elt = { 0, };
11652               int i;
11653               g_value_init (&arr, GST_TYPE_ARRAY);
11654               g_value_init (&elt, G_TYPE_INT);
11655               for (i = 0; i < ncomp_map; i++) {
11656                 g_value_set_int (&elt, comp_map[i]);
11657                 gst_value_array_append_value (&arr, &elt);
11658               }
11659               gst_structure_set_value (gst_caps_get_structure (entry->caps, 0),
11660                   "component-map", &arr);
11661               g_value_unset (&elt);
11662               g_value_unset (&arr);
11663               g_free (comp_map);
11664             }
11665
11666             if (chan_def) {
11667               GValue arr = { 0, };
11668               GValue elt = { 0, };
11669               int i;
11670               g_value_init (&arr, GST_TYPE_ARRAY);
11671               g_value_init (&elt, G_TYPE_INT);
11672               for (i = 0; i < nchan_def; i++) {
11673                 g_value_set_int (&elt, chan_def[i]);
11674                 gst_value_array_append_value (&arr, &elt);
11675               }
11676               gst_structure_set_value (gst_caps_get_structure (entry->caps, 0),
11677                   "channel-definitions", &arr);
11678               g_value_unset (&elt);
11679               g_value_unset (&arr);
11680               g_free (chan_def);
11681             }
11682
11683             /* some optional atoms */
11684             field = qtdemux_tree_get_child_by_type (mjp2, FOURCC_fiel);
11685             prefix = qtdemux_tree_get_child_by_type (mjp2, FOURCC_jp2x);
11686
11687             /* indicate possible fields in caps */
11688             if (field) {
11689               data = (guint8 *) field->data + 8;
11690               if (*data != 1)
11691                 gst_caps_set_simple (entry->caps, "fields", G_TYPE_INT,
11692                     (gint) * data, NULL);
11693             }
11694             /* add codec_data if provided */
11695             if (prefix) {
11696               GstBuffer *buf;
11697               gint len;
11698
11699               GST_DEBUG_OBJECT (qtdemux, "found prefix data in stsd");
11700               data = prefix->data;
11701               len = QT_UINT32 (data);
11702               if (len > 0x8) {
11703                 len -= 0x8;
11704                 buf = gst_buffer_new_and_alloc (len);
11705                 gst_buffer_fill (buf, 0, data + 8, len);
11706                 gst_caps_set_simple (entry->caps,
11707                     "codec_data", GST_TYPE_BUFFER, buf, NULL);
11708                 gst_buffer_unref (buf);
11709               }
11710             }
11711             break;
11712           }
11713           case FOURCC_SVQ3:
11714           case FOURCC_VP31:
11715           {
11716             GstBuffer *buf;
11717             GstBuffer *seqh = NULL;
11718             const guint8 *gamma_data = NULL;
11719             gint len = QT_UINT32 (stsd_data);   /* FIXME review - why put the whole stsd in codec data? */
11720
11721             qtdemux_parse_svq3_stsd_data (qtdemux, stsd_entry_data, &gamma_data,
11722                 &seqh);
11723             if (gamma_data) {
11724               gst_caps_set_simple (entry->caps, "applied-gamma", G_TYPE_DOUBLE,
11725                   QT_FP32 (gamma_data), NULL);
11726             }
11727             if (seqh) {
11728               /* sorry for the bad name, but we don't know what this is, other
11729                * than its own fourcc */
11730               gst_caps_set_simple (entry->caps, "seqh", GST_TYPE_BUFFER, seqh,
11731                   NULL);
11732               gst_buffer_unref (seqh);
11733             }
11734
11735             GST_DEBUG_OBJECT (qtdemux, "found codec_data in stsd");
11736             buf = gst_buffer_new_and_alloc (len);
11737             gst_buffer_fill (buf, 0, stsd_data, len);
11738             gst_caps_set_simple (entry->caps,
11739                 "codec_data", GST_TYPE_BUFFER, buf, NULL);
11740             gst_buffer_unref (buf);
11741             break;
11742           }
11743           case FOURCC_jpeg:
11744           {
11745             /* https://developer.apple.com/standards/qtff-2001.pdf,
11746              * page 92, "Video Sample Description", under table 3.1 */
11747             GstByteReader br;
11748
11749             const gint compressor_offset =
11750                 16 + 4 + 4 * 3 + 2 * 2 + 2 * 4 + 4 + 2;
11751             const gint min_size = compressor_offset + 32 + 2 + 2;
11752             GNode *jpeg;
11753             guint32 len;
11754             guint16 color_table_id = 0;
11755             gboolean ok;
11756
11757             GST_DEBUG_OBJECT (qtdemux, "found jpeg");
11758
11759             /* recover information on interlaced/progressive */
11760             jpeg = qtdemux_tree_get_child_by_type (stsd, FOURCC_jpeg);
11761             if (!jpeg)
11762               break;
11763
11764             len = QT_UINT32 (jpeg->data);
11765             GST_DEBUG_OBJECT (qtdemux, "Found jpeg: len %u, need %d", len,
11766                 min_size);
11767             if (len >= min_size) {
11768               gst_byte_reader_init (&br, jpeg->data, len);
11769
11770               gst_byte_reader_skip (&br, compressor_offset + 32 + 2);
11771               gst_byte_reader_get_uint16_le (&br, &color_table_id);
11772               if (color_table_id != 0) {
11773                 /* the spec says there can be concatenated chunks in the data, and we want
11774                  * to find one called field. Walk through them. */
11775                 gint offset = min_size;
11776                 while (offset + 8 < len) {
11777                   guint32 size = 0, tag;
11778                   ok = gst_byte_reader_get_uint32_le (&br, &size);
11779                   ok &= gst_byte_reader_get_uint32_le (&br, &tag);
11780                   if (!ok || size < 8) {
11781                     GST_WARNING_OBJECT (qtdemux,
11782                         "Failed to walk optional chunk list");
11783                     break;
11784                   }
11785                   GST_DEBUG_OBJECT (qtdemux,
11786                       "Found optional %4.4s chunk, size %u",
11787                       (const char *) &tag, size);
11788                   if (tag == FOURCC_fiel) {
11789                     guint8 n_fields = 0, ordering = 0;
11790                     gst_byte_reader_get_uint8 (&br, &n_fields);
11791                     gst_byte_reader_get_uint8 (&br, &ordering);
11792                     if (n_fields == 1 || n_fields == 2) {
11793                       GST_DEBUG_OBJECT (qtdemux,
11794                           "Found fiel tag with %u fields, ordering %u",
11795                           n_fields, ordering);
11796                       if (n_fields == 2)
11797                         gst_caps_set_simple (CUR_STREAM (stream)->caps,
11798                             "interlace-mode", G_TYPE_STRING, "interleaved",
11799                             NULL);
11800                     } else {
11801                       GST_WARNING_OBJECT (qtdemux,
11802                           "Found fiel tag with invalid fields (%u)", n_fields);
11803                     }
11804                   }
11805                   offset += size;
11806                 }
11807               } else {
11808                 GST_DEBUG_OBJECT (qtdemux,
11809                     "Color table ID is 0, not trying to get interlacedness");
11810               }
11811             } else {
11812               GST_WARNING_OBJECT (qtdemux,
11813                   "Length of jpeg chunk is too small, not trying to get interlacedness");
11814             }
11815
11816             break;
11817           }
11818           case FOURCC_rle_:
11819           case FOURCC_WRLE:
11820           {
11821             gst_caps_set_simple (entry->caps,
11822                 "depth", G_TYPE_INT, QT_UINT16 (stsd_entry_data + offset + 66),
11823                 NULL);
11824             break;
11825           }
11826           case FOURCC_XiTh:
11827           {
11828             GNode *xith, *xdxt;
11829
11830             GST_DEBUG_OBJECT (qtdemux, "found XiTh");
11831             xith = qtdemux_tree_get_child_by_index (stsd, stsd_index);
11832             if (!xith)
11833               break;
11834
11835             xdxt = qtdemux_tree_get_child_by_type (xith, FOURCC_XdxT);
11836             if (!xdxt)
11837               break;
11838
11839             GST_DEBUG_OBJECT (qtdemux, "found XdxT node");
11840             /* collect the headers and store them in a stream list so that we can
11841              * send them out first */
11842             qtdemux_parse_theora_extension (qtdemux, stream, xdxt);
11843             break;
11844           }
11845           case FOURCC_ovc1:
11846           {
11847             GNode *ovc1;
11848             guint8 *ovc1_data;
11849             guint ovc1_len;
11850             GstBuffer *buf;
11851
11852             GST_DEBUG_OBJECT (qtdemux, "parse ovc1 header");
11853             ovc1 = qtdemux_tree_get_child_by_index (stsd, stsd_index);
11854             if (!ovc1)
11855               break;
11856             ovc1_data = ovc1->data;
11857             ovc1_len = QT_UINT32 (ovc1_data);
11858             if (ovc1_len <= 198) {
11859               GST_WARNING_OBJECT (qtdemux, "Too small ovc1 header, skipping");
11860               break;
11861             }
11862             buf = gst_buffer_new_and_alloc (ovc1_len - 198);
11863             gst_buffer_fill (buf, 0, ovc1_data + 198, ovc1_len - 198);
11864             gst_caps_set_simple (entry->caps,
11865                 "codec_data", GST_TYPE_BUFFER, buf, NULL);
11866             gst_buffer_unref (buf);
11867             break;
11868           }
11869           case FOURCC_vc_1:
11870           {
11871             gint len = QT_UINT32 (stsd_entry_data) - 0x56;
11872             const guint8 *vc1_data = stsd_entry_data + 0x56;
11873
11874             /* find dvc1 */
11875             while (len >= 8) {
11876               gint size;
11877
11878               if (QT_UINT32 (vc1_data) <= len)
11879                 size = QT_UINT32 (vc1_data) - 8;
11880               else
11881                 size = len - 8;
11882
11883               if (size < 1)
11884                 /* No real data, so break out */
11885                 break;
11886
11887               switch (QT_FOURCC (vc1_data + 0x4)) {
11888                 case GST_MAKE_FOURCC ('d', 'v', 'c', '1'):
11889                 {
11890                   GstBuffer *buf;
11891
11892                   GST_DEBUG_OBJECT (qtdemux, "found dvc1 codec_data in stsd");
11893                   buf = gst_buffer_new_and_alloc (size);
11894                   gst_buffer_fill (buf, 0, vc1_data + 8, size);
11895                   gst_caps_set_simple (entry->caps,
11896                       "codec_data", GST_TYPE_BUFFER, buf, NULL);
11897                   gst_buffer_unref (buf);
11898                   break;
11899                 }
11900                 default:
11901                   break;
11902               }
11903               len -= size + 8;
11904               vc1_data += size + 8;
11905             }
11906             break;
11907           }
11908           case FOURCC_av01:
11909           {
11910             gint len = QT_UINT32 (stsd_entry_data) - 0x56;
11911             const guint8 *av1_data = stsd_entry_data + 0x56;
11912
11913             /* find av1C */
11914             while (len >= 0x8) {
11915               gint size;
11916
11917               if (QT_UINT32 (av1_data) <= len)
11918                 size = QT_UINT32 (av1_data) - 0x8;
11919               else
11920                 size = len - 0x8;
11921
11922               if (size < 1)
11923                 /* No real data, so break out */
11924                 break;
11925
11926               switch (QT_FOURCC (av1_data + 0x4)) {
11927                 case FOURCC_av1C:
11928                 {
11929                   /* parse, if found */
11930                   GstBuffer *buf;
11931                   guint8 pres_delay_field;
11932
11933                   GST_DEBUG_OBJECT (qtdemux,
11934                       "found av1C codec_data in stsd of size %d", size);
11935
11936                   /* not enough data, just ignore and hope for the best */
11937                   if (size < 5)
11938                     break;
11939
11940                   /* Content is:
11941                    * 4 bytes: atom length
11942                    * 4 bytes: fourcc
11943                    * 1 byte: version
11944                    * 3 bytes: flags
11945                    * 3 bits: reserved
11946                    * 1 bits:  initial_presentation_delay_present
11947                    * 4 bits: initial_presentation_delay (if present else reserved
11948                    * rest: OBUs.
11949                    */
11950
11951                   if (av1_data[9] != 0) {
11952                     GST_WARNING ("Unknown version %d of av1C box", av1_data[9]);
11953                     break;
11954                   }
11955
11956                   /* We skip initial_presentation_delay* for now */
11957                   pres_delay_field = *(av1_data + 12);
11958                   if (pres_delay_field & (1 << 5)) {
11959                     gst_caps_set_simple (entry->caps,
11960                         "presentation-delay", G_TYPE_INT,
11961                         (gint) (pres_delay_field & 0x0F) + 1, NULL);
11962                   }
11963                   if (size > 5) {
11964                     buf = gst_buffer_new_and_alloc (size - 5);
11965                     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
11966                     gst_buffer_fill (buf, 0, av1_data + 13, size - 5);
11967                     gst_caps_set_simple (entry->caps,
11968                         "codec_data", GST_TYPE_BUFFER, buf, NULL);
11969                     gst_buffer_unref (buf);
11970                   }
11971                   break;
11972                 }
11973                 default:
11974                   break;
11975               }
11976
11977               len -= size + 8;
11978               av1_data += size + 8;
11979             }
11980
11981             break;
11982           }
11983
11984             /* TODO: Need to parse vpcC for VP8 codec too.
11985              * Note that VPCodecConfigurationBox (vpcC) is defined for
11986              * vp08, vp09, and vp10 fourcc. */
11987           case FOURCC_vp09:
11988           {
11989             gint len = QT_UINT32 (stsd_entry_data) - 0x56;
11990             const guint8 *vpcc_data = stsd_entry_data + 0x56;
11991
11992             /* find vpcC */
11993             while (len >= 0x8) {
11994               gint size;
11995
11996               if (QT_UINT32 (vpcc_data) <= len)
11997                 size = QT_UINT32 (vpcc_data) - 0x8;
11998               else
11999                 size = len - 0x8;
12000
12001               if (size < 1)
12002                 /* No real data, so break out */
12003                 break;
12004
12005               switch (QT_FOURCC (vpcc_data + 0x4)) {
12006                 case FOURCC_vpcC:
12007                 {
12008                   const gchar *profile_str = NULL;
12009                   const gchar *chroma_format_str = NULL;
12010                   guint8 profile;
12011                   guint8 bitdepth;
12012                   guint8 chroma_format;
12013                   GstVideoColorimetry cinfo;
12014
12015                   /* parse, if found */
12016                   GST_DEBUG_OBJECT (qtdemux,
12017                       "found vp codec_data in stsd of size %d", size);
12018
12019                   /* the meaning of "size" is length of the atom body, excluding
12020                    * atom length and fourcc fields */
12021                   if (size < 12)
12022                     break;
12023
12024                   /* Content is:
12025                    * 4 bytes: atom length
12026                    * 4 bytes: fourcc
12027                    * 1 byte: version
12028                    * 3 bytes: flags
12029                    * 1 byte: profile
12030                    * 1 byte: level
12031                    * 4 bits: bitDepth
12032                    * 3 bits: chromaSubsampling
12033                    * 1 bit: videoFullRangeFlag
12034                    * 1 byte: colourPrimaries
12035                    * 1 byte: transferCharacteristics
12036                    * 1 byte: matrixCoefficients
12037                    * 2 bytes: codecIntializationDataSize (should be zero for vp8 and vp9)
12038                    * rest: codecIntializationData (not used for vp8 and vp9)
12039                    */
12040
12041                   if (vpcc_data[8] != 1) {
12042                     GST_WARNING_OBJECT (qtdemux,
12043                         "unknown vpcC version %d", vpcc_data[8]);
12044                     break;
12045                   }
12046
12047                   profile = vpcc_data[12];
12048                   switch (profile) {
12049                     case 0:
12050                       profile_str = "0";
12051                       break;
12052                     case 1:
12053                       profile_str = "1";
12054                       break;
12055                     case 2:
12056                       profile_str = "2";
12057                       break;
12058                     case 3:
12059                       profile_str = "3";
12060                       break;
12061                     default:
12062                       break;
12063                   }
12064
12065                   if (profile_str) {
12066                     gst_caps_set_simple (entry->caps,
12067                         "profile", G_TYPE_STRING, profile_str, NULL);
12068                   }
12069
12070                   /* skip level, the VP9 spec v0.6 defines only one level atm,
12071                    * but webm spec define various ones. Add level to caps
12072                    * if we really need it then */
12073
12074                   bitdepth = (vpcc_data[14] & 0xf0) >> 4;
12075                   if (bitdepth == 8 || bitdepth == 10 || bitdepth == 12) {
12076                     gst_caps_set_simple (entry->caps,
12077                         "bit-depth-luma", G_TYPE_UINT, bitdepth,
12078                         "bit-depth-chroma", G_TYPE_UINT, bitdepth, NULL);
12079                   }
12080
12081                   chroma_format = (vpcc_data[14] & 0xe) >> 1;
12082                   switch (chroma_format) {
12083                     case 0:
12084                     case 1:
12085                       chroma_format_str = "4:2:0";
12086                       break;
12087                     case 2:
12088                       chroma_format_str = "4:2:2";
12089                       break;
12090                     case 3:
12091                       chroma_format_str = "4:4:4";
12092                       break;
12093                     default:
12094                       break;
12095                   }
12096
12097                   if (chroma_format_str) {
12098                     gst_caps_set_simple (entry->caps,
12099                         "chroma-format", G_TYPE_STRING, chroma_format_str,
12100                         NULL);
12101                   }
12102
12103                   if ((vpcc_data[14] & 0x1) != 0)
12104                     cinfo.range = GST_VIDEO_COLOR_RANGE_0_255;
12105                   else
12106                     cinfo.range = GST_VIDEO_COLOR_RANGE_16_235;
12107                   cinfo.primaries =
12108                       gst_video_color_primaries_from_iso (vpcc_data[15]);
12109                   cinfo.transfer =
12110                       gst_video_transfer_function_from_iso (vpcc_data[16]);
12111                   cinfo.matrix =
12112                       gst_video_color_matrix_from_iso (vpcc_data[17]);
12113
12114                   if (cinfo.primaries != GST_VIDEO_COLOR_PRIMARIES_UNKNOWN &&
12115                       cinfo.transfer != GST_VIDEO_TRANSFER_UNKNOWN &&
12116                       cinfo.matrix != GST_VIDEO_COLOR_MATRIX_UNKNOWN) {
12117                     /* set this only if all values are known, otherwise this
12118                      * might overwrite valid ones parsed from other color box */
12119                     CUR_STREAM (stream)->colorimetry = cinfo;
12120                   }
12121                   break;
12122                 }
12123                 default:
12124                   break;
12125               }
12126
12127               len -= size + 8;
12128               vpcc_data += size + 8;
12129             }
12130
12131             break;
12132           }
12133           default:
12134             break;
12135         }
12136       }
12137
12138       GST_INFO_OBJECT (qtdemux,
12139           "type %" GST_FOURCC_FORMAT " caps %" GST_PTR_FORMAT,
12140           GST_FOURCC_ARGS (fourcc), entry->caps);
12141
12142     } else if (stream->subtype == FOURCC_soun) {
12143       GNode *wave;
12144       int version, samplesize;
12145       guint16 compression_id;
12146       gboolean amrwb = FALSE;
12147
12148       offset = 16;
12149       /* sample description entry (16) + sound sample description v0 (20) */
12150       if (len < 36)
12151         goto corrupt_file;
12152
12153       version = QT_UINT32 (stsd_entry_data + offset);
12154       entry->n_channels = QT_UINT16 (stsd_entry_data + offset + 8);
12155       samplesize = QT_UINT16 (stsd_entry_data + offset + 10);
12156       compression_id = QT_UINT16 (stsd_entry_data + offset + 12);
12157       entry->rate = QT_FP32 (stsd_entry_data + offset + 16);
12158
12159       GST_LOG_OBJECT (qtdemux, "version/rev:      %08x", version);
12160       GST_LOG_OBJECT (qtdemux, "vendor:           %08x",
12161           QT_UINT32 (stsd_entry_data + offset + 4));
12162       GST_LOG_OBJECT (qtdemux, "n_channels:       %d", entry->n_channels);
12163       GST_LOG_OBJECT (qtdemux, "sample_size:      %d", samplesize);
12164       GST_LOG_OBJECT (qtdemux, "compression_id:   %d", compression_id);
12165       GST_LOG_OBJECT (qtdemux, "packet size:      %d",
12166           QT_UINT16 (stsd_entry_data + offset + 14));
12167       GST_LOG_OBJECT (qtdemux, "sample rate:      %g", entry->rate);
12168
12169       if (compression_id == 0xfffe)
12170         entry->sampled = TRUE;
12171
12172       /* first assume uncompressed audio */
12173       entry->bytes_per_sample = samplesize / 8;
12174       entry->samples_per_frame = entry->n_channels;
12175       entry->bytes_per_frame = entry->n_channels * entry->bytes_per_sample;
12176       entry->samples_per_packet = entry->samples_per_frame;
12177       entry->bytes_per_packet = entry->bytes_per_sample;
12178
12179       offset = 36;
12180
12181       if (version == 0x00010000) {
12182         /* sample description entry (16) + sound sample description v1 (20+16) */
12183         if (len < 52)
12184           goto corrupt_file;
12185
12186         /* take information from here over the normal sample description */
12187         entry->samples_per_packet = QT_UINT32 (stsd_entry_data + offset);
12188         entry->bytes_per_packet = QT_UINT32 (stsd_entry_data + offset + 4);
12189         entry->bytes_per_frame = QT_UINT32 (stsd_entry_data + offset + 8);
12190         entry->bytes_per_sample = QT_UINT32 (stsd_entry_data + offset + 12);
12191
12192         GST_LOG_OBJECT (qtdemux, "Sound sample description Version 1");
12193         GST_LOG_OBJECT (qtdemux, "samples/packet:   %d",
12194             entry->samples_per_packet);
12195         GST_LOG_OBJECT (qtdemux, "bytes/packet:     %d",
12196             entry->bytes_per_packet);
12197         GST_LOG_OBJECT (qtdemux, "bytes/frame:      %d",
12198             entry->bytes_per_frame);
12199         GST_LOG_OBJECT (qtdemux, "bytes/sample:     %d",
12200             entry->bytes_per_sample);
12201
12202         if (!entry->sampled && entry->bytes_per_packet) {
12203           entry->samples_per_frame = (entry->bytes_per_frame /
12204               entry->bytes_per_packet) * entry->samples_per_packet;
12205           GST_LOG_OBJECT (qtdemux, "samples/frame:    %d",
12206               entry->samples_per_frame);
12207         }
12208       } else if (version == 0x00020000) {
12209         /* sample description entry (16) + sound sample description v2 (56) */
12210         if (len < 72)
12211           goto corrupt_file;
12212
12213         /* take information from here over the normal sample description */
12214         entry->rate = GST_READ_DOUBLE_BE (stsd_entry_data + offset + 4);
12215         entry->n_channels = QT_UINT32 (stsd_entry_data + offset + 12);
12216         entry->samples_per_frame = entry->n_channels;
12217         entry->bytes_per_sample = QT_UINT32 (stsd_entry_data + offset + 20) / 8;
12218         entry->bytes_per_packet = QT_UINT32 (stsd_entry_data + offset + 28);
12219         entry->samples_per_packet = QT_UINT32 (stsd_entry_data + offset + 32);
12220         entry->bytes_per_frame = entry->bytes_per_sample * entry->n_channels;
12221
12222         GST_LOG_OBJECT (qtdemux, "Sound sample description Version 2");
12223         GST_LOG_OBJECT (qtdemux, "sample rate:        %g", entry->rate);
12224         GST_LOG_OBJECT (qtdemux, "n_channels:         %d", entry->n_channels);
12225         GST_LOG_OBJECT (qtdemux, "bits/channel:       %d",
12226             entry->bytes_per_sample * 8);
12227         GST_LOG_OBJECT (qtdemux, "format flags:       %X",
12228             QT_UINT32 (stsd_entry_data + offset + 24));
12229         GST_LOG_OBJECT (qtdemux, "bytes/packet:       %d",
12230             entry->bytes_per_packet);
12231         GST_LOG_OBJECT (qtdemux, "LPCM frames/packet: %d",
12232             entry->samples_per_packet);
12233       } else if (version != 0x00000) {
12234         GST_WARNING_OBJECT (qtdemux, "unknown audio STSD version %08x",
12235             version);
12236       }
12237
12238       switch (fourcc) {
12239           /* Yes, these have to be hard-coded */
12240         case FOURCC_MAC6:
12241         {
12242           entry->samples_per_packet = 6;
12243           entry->bytes_per_packet = 1;
12244           entry->bytes_per_frame = 1 * entry->n_channels;
12245           entry->bytes_per_sample = 1;
12246           entry->samples_per_frame = 6 * entry->n_channels;
12247           break;
12248         }
12249         case FOURCC_MAC3:
12250         {
12251           entry->samples_per_packet = 3;
12252           entry->bytes_per_packet = 1;
12253           entry->bytes_per_frame = 1 * entry->n_channels;
12254           entry->bytes_per_sample = 1;
12255           entry->samples_per_frame = 3 * entry->n_channels;
12256           break;
12257         }
12258         case FOURCC_ima4:
12259         {
12260           entry->samples_per_packet = 64;
12261           entry->bytes_per_packet = 34;
12262           entry->bytes_per_frame = 34 * entry->n_channels;
12263           entry->bytes_per_sample = 2;
12264           entry->samples_per_frame = 64 * entry->n_channels;
12265           break;
12266         }
12267         case FOURCC_ulaw:
12268         case FOURCC_alaw:
12269         {
12270           entry->samples_per_packet = 1;
12271           entry->bytes_per_packet = 1;
12272           entry->bytes_per_frame = 1 * entry->n_channels;
12273           entry->bytes_per_sample = 1;
12274           entry->samples_per_frame = 1 * entry->n_channels;
12275           break;
12276         }
12277         case FOURCC_agsm:
12278         {
12279           entry->samples_per_packet = 160;
12280           entry->bytes_per_packet = 33;
12281           entry->bytes_per_frame = 33 * entry->n_channels;
12282           entry->bytes_per_sample = 2;
12283           entry->samples_per_frame = 160 * entry->n_channels;
12284           break;
12285         }
12286           /* fix up any invalid header information from above */
12287         case FOURCC_twos:
12288         case FOURCC_sowt:
12289         case FOURCC_raw_:
12290         case FOURCC_lpcm:
12291           /* Sometimes these are set to 0 in the sound sample descriptions so
12292            * let's try to infer useful values from the other information we
12293            * have available */
12294           if (entry->bytes_per_sample == 0)
12295             entry->bytes_per_sample =
12296                 entry->bytes_per_frame / entry->n_channels;
12297           if (entry->bytes_per_sample == 0)
12298             entry->bytes_per_sample = samplesize / 8;
12299
12300           if (entry->bytes_per_frame == 0)
12301             entry->bytes_per_frame =
12302                 entry->bytes_per_sample * entry->n_channels;
12303
12304           if (entry->bytes_per_packet == 0)
12305             entry->bytes_per_packet = entry->bytes_per_sample;
12306
12307           if (entry->samples_per_frame == 0)
12308             entry->samples_per_frame = entry->n_channels;
12309
12310           if (entry->samples_per_packet == 0)
12311             entry->samples_per_packet = entry->samples_per_frame;
12312
12313           break;
12314         case FOURCC_in24:
12315         case FOURCC_in32:
12316         case FOURCC_fl32:
12317         case FOURCC_fl64:
12318         case FOURCC_s16l:{
12319           switch (fourcc) {
12320             case FOURCC_in24:
12321               entry->bytes_per_sample = 3;
12322               break;
12323             case FOURCC_in32:
12324             case FOURCC_fl32:
12325               entry->bytes_per_sample = 4;
12326               break;
12327             case FOURCC_fl64:
12328               entry->bytes_per_sample = 8;
12329               break;
12330             case FOURCC_s16l:
12331               entry->bytes_per_sample = 2;
12332               break;
12333             default:
12334               g_assert_not_reached ();
12335               break;
12336           }
12337           entry->samples_per_frame = entry->n_channels;
12338           entry->bytes_per_frame = entry->n_channels * entry->bytes_per_sample;
12339           entry->samples_per_packet = entry->samples_per_frame;
12340           entry->bytes_per_packet = entry->bytes_per_sample;
12341           break;
12342         }
12343         default:
12344           break;
12345       }
12346
12347       if (entry->caps)
12348         gst_caps_unref (entry->caps);
12349
12350       entry->caps = qtdemux_audio_caps (qtdemux, stream, entry, fourcc,
12351           stsd_entry_data + 32, len - 16, &codec);
12352
12353       switch (fourcc) {
12354         case FOURCC_in24:
12355         case FOURCC_in32:
12356         case FOURCC_fl32:
12357         case FOURCC_fl64:
12358         {
12359           GNode *enda;
12360           GNode *fmt;
12361
12362           fmt = qtdemux_tree_get_child_by_type (stsd, fourcc);
12363
12364           enda = qtdemux_tree_get_child_by_type (fmt, FOURCC_enda);
12365           if (!enda) {
12366             wave = qtdemux_tree_get_child_by_type (fmt, FOURCC_wave);
12367             if (wave)
12368               enda = qtdemux_tree_get_child_by_type (wave, FOURCC_enda);
12369           }
12370           if (enda) {
12371             int enda_value = QT_UINT16 ((guint8 *) enda->data + 8);
12372             const gchar *format_str;
12373
12374             switch (fourcc) {
12375               case FOURCC_in24:
12376                 format_str = (enda_value) ? "S24LE" : "S24BE";
12377                 break;
12378               case FOURCC_in32:
12379                 format_str = (enda_value) ? "S32LE" : "S32BE";
12380                 break;
12381               case FOURCC_fl32:
12382                 format_str = (enda_value) ? "F32LE" : "F32BE";
12383                 break;
12384               case FOURCC_fl64:
12385                 format_str = (enda_value) ? "F64LE" : "F64BE";
12386                 break;
12387               default:
12388                 g_assert_not_reached ();
12389                 break;
12390             }
12391             gst_caps_set_simple (entry->caps,
12392                 "format", G_TYPE_STRING, format_str, NULL);
12393           }
12394           break;
12395         }
12396         case FOURCC_owma:
12397         {
12398           const guint8 *owma_data;
12399           const gchar *codec_name = NULL;
12400           guint owma_len;
12401           GstBuffer *buf;
12402           gint version = 1;
12403           /* from http://msdn.microsoft.com/en-us/library/dd757720(VS.85).aspx */
12404           /* FIXME this should also be gst_riff_strf_auds,
12405            * but the latter one is actually missing bits-per-sample :( */
12406           typedef struct
12407           {
12408             gint16 wFormatTag;
12409             gint16 nChannels;
12410             gint32 nSamplesPerSec;
12411             gint32 nAvgBytesPerSec;
12412             gint16 nBlockAlign;
12413             gint16 wBitsPerSample;
12414             gint16 cbSize;
12415           } WAVEFORMATEX;
12416           WAVEFORMATEX *wfex;
12417
12418           GST_DEBUG_OBJECT (qtdemux, "parse owma");
12419           owma_data = stsd_entry_data;
12420           owma_len = QT_UINT32 (owma_data);
12421           if (owma_len <= 54) {
12422             GST_WARNING_OBJECT (qtdemux, "Too small owma header, skipping");
12423             break;
12424           }
12425           wfex = (WAVEFORMATEX *) (owma_data + 36);
12426           buf = gst_buffer_new_and_alloc (owma_len - 54);
12427           gst_buffer_fill (buf, 0, owma_data + 54, owma_len - 54);
12428           if (wfex->wFormatTag == 0x0161) {
12429             codec_name = "Windows Media Audio";
12430             version = 2;
12431           } else if (wfex->wFormatTag == 0x0162) {
12432             codec_name = "Windows Media Audio 9 Pro";
12433             version = 3;
12434           } else if (wfex->wFormatTag == 0x0163) {
12435             codec_name = "Windows Media Audio 9 Lossless";
12436             /* is that correct? gstffmpegcodecmap.c is missing it, but
12437              * fluendo codec seems to support it */
12438             version = 4;
12439           }
12440
12441           gst_caps_set_simple (entry->caps,
12442               "codec_data", GST_TYPE_BUFFER, buf,
12443               "wmaversion", G_TYPE_INT, version,
12444               "block_align", G_TYPE_INT,
12445               GST_READ_UINT16_LE (&wfex->nBlockAlign), "bitrate", G_TYPE_INT,
12446               GST_READ_UINT32_LE (&wfex->nAvgBytesPerSec), "width", G_TYPE_INT,
12447               GST_READ_UINT16_LE (&wfex->wBitsPerSample), "depth", G_TYPE_INT,
12448               GST_READ_UINT16_LE (&wfex->wBitsPerSample), NULL);
12449           gst_buffer_unref (buf);
12450
12451           if (codec_name) {
12452             g_free (codec);
12453             codec = g_strdup (codec_name);
12454           }
12455           break;
12456         }
12457         case FOURCC_wma_:
12458         {
12459           gint len = QT_UINT32 (stsd_entry_data) - offset;
12460           const guint8 *wfex_data = stsd_entry_data + offset;
12461           const gchar *codec_name = NULL;
12462           gint version = 1;
12463           /* from http://msdn.microsoft.com/en-us/library/dd757720(VS.85).aspx */
12464           /* FIXME this should also be gst_riff_strf_auds,
12465            * but the latter one is actually missing bits-per-sample :( */
12466           typedef struct
12467           {
12468             gint16 wFormatTag;
12469             gint16 nChannels;
12470             gint32 nSamplesPerSec;
12471             gint32 nAvgBytesPerSec;
12472             gint16 nBlockAlign;
12473             gint16 wBitsPerSample;
12474             gint16 cbSize;
12475           } WAVEFORMATEX;
12476           WAVEFORMATEX wfex;
12477
12478           /* FIXME: unify with similar wavformatex parsing code above */
12479           GST_DEBUG_OBJECT (qtdemux, "parse wma, looking for wfex");
12480
12481           /* find wfex */
12482           while (len >= 8) {
12483             gint size;
12484
12485             if (QT_UINT32 (wfex_data) <= len)
12486               size = QT_UINT32 (wfex_data) - 8;
12487             else
12488               size = len - 8;
12489
12490             if (size < 1)
12491               /* No real data, so break out */
12492               break;
12493
12494             switch (QT_FOURCC (wfex_data + 4)) {
12495               case GST_MAKE_FOURCC ('w', 'f', 'e', 'x'):
12496               {
12497                 GST_DEBUG_OBJECT (qtdemux, "found wfex in stsd");
12498
12499                 if (size < 8 + 18)
12500                   break;
12501
12502                 wfex.wFormatTag = GST_READ_UINT16_LE (wfex_data + 8 + 0);
12503                 wfex.nChannels = GST_READ_UINT16_LE (wfex_data + 8 + 2);
12504                 wfex.nSamplesPerSec = GST_READ_UINT32_LE (wfex_data + 8 + 4);
12505                 wfex.nAvgBytesPerSec = GST_READ_UINT32_LE (wfex_data + 8 + 8);
12506                 wfex.nBlockAlign = GST_READ_UINT16_LE (wfex_data + 8 + 12);
12507                 wfex.wBitsPerSample = GST_READ_UINT16_LE (wfex_data + 8 + 14);
12508                 wfex.cbSize = GST_READ_UINT16_LE (wfex_data + 8 + 16);
12509
12510                 GST_LOG_OBJECT (qtdemux, "Found wfex box in stsd:");
12511                 GST_LOG_OBJECT (qtdemux, "FormatTag = 0x%04x, Channels = %u, "
12512                     "SamplesPerSec = %u, AvgBytesPerSec = %u, BlockAlign = %u, "
12513                     "BitsPerSample = %u, Size = %u", wfex.wFormatTag,
12514                     wfex.nChannels, wfex.nSamplesPerSec, wfex.nAvgBytesPerSec,
12515                     wfex.nBlockAlign, wfex.wBitsPerSample, wfex.cbSize);
12516
12517                 if (wfex.wFormatTag == 0x0161) {
12518                   codec_name = "Windows Media Audio";
12519                   version = 2;
12520                 } else if (wfex.wFormatTag == 0x0162) {
12521                   codec_name = "Windows Media Audio 9 Pro";
12522                   version = 3;
12523                 } else if (wfex.wFormatTag == 0x0163) {
12524                   codec_name = "Windows Media Audio 9 Lossless";
12525                   /* is that correct? gstffmpegcodecmap.c is missing it, but
12526                    * fluendo codec seems to support it */
12527                   version = 4;
12528                 }
12529
12530                 gst_caps_set_simple (entry->caps,
12531                     "wmaversion", G_TYPE_INT, version,
12532                     "block_align", G_TYPE_INT, wfex.nBlockAlign,
12533                     "bitrate", G_TYPE_INT, wfex.nAvgBytesPerSec,
12534                     "width", G_TYPE_INT, wfex.wBitsPerSample,
12535                     "depth", G_TYPE_INT, wfex.wBitsPerSample, NULL);
12536
12537                 if (size > wfex.cbSize) {
12538                   GstBuffer *buf;
12539
12540                   buf = gst_buffer_new_and_alloc (size - wfex.cbSize);
12541                   gst_buffer_fill (buf, 0, wfex_data + 8 + wfex.cbSize,
12542                       size - wfex.cbSize);
12543                   gst_caps_set_simple (entry->caps,
12544                       "codec_data", GST_TYPE_BUFFER, buf, NULL);
12545                   gst_buffer_unref (buf);
12546                 } else {
12547                   GST_WARNING_OBJECT (qtdemux, "no codec data");
12548                 }
12549
12550                 if (codec_name) {
12551                   g_free (codec);
12552                   codec = g_strdup (codec_name);
12553                 }
12554                 break;
12555               }
12556               default:
12557                 break;
12558             }
12559             len -= size + 8;
12560             wfex_data += size + 8;
12561           }
12562           break;
12563         }
12564         case FOURCC_opus:
12565         {
12566           const guint8 *dops_data;
12567           guint8 *channel_mapping = NULL;
12568           guint32 rate;
12569           guint8 channels;
12570           guint8 channel_mapping_family;
12571           guint8 stream_count;
12572           guint8 coupled_count;
12573           guint8 i;
12574
12575           version = GST_READ_UINT16_BE (stsd_entry_data + 16);
12576           if (version == 1)
12577             dops_data = stsd_entry_data + 51;
12578           else
12579             dops_data = stsd_entry_data + 35;
12580
12581           channels = GST_READ_UINT8 (dops_data + 10);
12582           rate = GST_READ_UINT32_LE (dops_data + 13);
12583           channel_mapping_family = GST_READ_UINT8 (dops_data + 19);
12584           stream_count = GST_READ_UINT8 (dops_data + 20);
12585           coupled_count = GST_READ_UINT8 (dops_data + 21);
12586
12587           if (channels > 0) {
12588             channel_mapping = g_malloc (channels * sizeof (guint8));
12589             for (i = 0; i < channels; i++)
12590               channel_mapping[i] = GST_READ_UINT8 (dops_data + i + 22);
12591           }
12592
12593           entry->caps = gst_codec_utils_opus_create_caps (rate, channels,
12594               channel_mapping_family, stream_count, coupled_count,
12595               channel_mapping);
12596           break;
12597         }
12598         default:
12599           break;
12600       }
12601
12602       if (codec) {
12603         GstStructure *s;
12604         gint bitrate = 0;
12605
12606         gst_tag_list_add (stream->stream_tags, GST_TAG_MERGE_REPLACE,
12607             GST_TAG_AUDIO_CODEC, codec, NULL);
12608         g_free (codec);
12609         codec = NULL;
12610
12611         /* some bitrate info may have ended up in caps */
12612         s = gst_caps_get_structure (entry->caps, 0);
12613         gst_structure_get_int (s, "bitrate", &bitrate);
12614         if (bitrate > 0)
12615           gst_tag_list_add (stream->stream_tags, GST_TAG_MERGE_REPLACE,
12616               GST_TAG_BITRATE, bitrate, NULL);
12617       }
12618
12619       esds = NULL;
12620       mp4a = qtdemux_tree_get_child_by_index (stsd, stsd_index);
12621       if (QTDEMUX_TREE_NODE_FOURCC (mp4a) != fourcc) {
12622         if (stream->protected) {
12623           if (QTDEMUX_TREE_NODE_FOURCC (mp4a) == FOURCC_aavd) {
12624             esds = qtdemux_tree_get_child_by_type (mp4a, FOURCC_esds);
12625           }
12626           if (QTDEMUX_TREE_NODE_FOURCC (mp4a) != FOURCC_enca) {
12627             mp4a = NULL;
12628           }
12629         } else {
12630           mp4a = NULL;
12631         }
12632       }
12633
12634       wave = NULL;
12635       if (mp4a) {
12636         wave = qtdemux_tree_get_child_by_type (mp4a, FOURCC_wave);
12637         if (wave)
12638           esds = qtdemux_tree_get_child_by_type (wave, FOURCC_esds);
12639         if (!esds)
12640           esds = qtdemux_tree_get_child_by_type (mp4a, FOURCC_esds);
12641       }
12642
12643
12644       /* If the fourcc's bottom 16 bits gives 'sm', then the top
12645          16 bits is a byte-swapped wave-style codec identifier,
12646          and we can find a WAVE header internally to a 'wave' atom here.
12647          This can more clearly be thought of as 'ms' as the top 16 bits, and a
12648          codec id as the bottom 16 bits - but byte-swapped to store in QT (which
12649          is big-endian).
12650        */
12651       if ((fourcc & 0xffff) == (('s' << 8) | 'm')) {
12652         if (len < offset + 20) {
12653           GST_WARNING_OBJECT (qtdemux, "No wave atom in MS-style audio");
12654         } else {
12655           guint32 datalen = QT_UINT32 (stsd_entry_data + offset + 16);
12656           const guint8 *data = stsd_entry_data + offset + 16;
12657           GNode *wavenode;
12658           GNode *waveheadernode;
12659
12660           wavenode = g_node_new ((guint8 *) data);
12661           if (qtdemux_parse_node (qtdemux, wavenode, data, datalen)) {
12662             const guint8 *waveheader;
12663             guint32 headerlen;
12664
12665             waveheadernode = qtdemux_tree_get_child_by_type (wavenode, fourcc);
12666             if (waveheadernode) {
12667               waveheader = (const guint8 *) waveheadernode->data;
12668               headerlen = QT_UINT32 (waveheader);
12669
12670               if (headerlen > 8) {
12671                 gst_riff_strf_auds *header = NULL;
12672                 GstBuffer *headerbuf;
12673                 GstBuffer *extra;
12674
12675                 waveheader += 8;
12676                 headerlen -= 8;
12677
12678                 headerbuf = gst_buffer_new_and_alloc (headerlen);
12679                 gst_buffer_fill (headerbuf, 0, waveheader, headerlen);
12680
12681                 if (gst_riff_parse_strf_auds (GST_ELEMENT_CAST (qtdemux),
12682                         headerbuf, &header, &extra)) {
12683                   gst_caps_unref (entry->caps);
12684                   /* FIXME: Need to do something with the channel reorder map */
12685                   entry->caps =
12686                       gst_riff_create_audio_caps (header->format, NULL, header,
12687                       extra, NULL, NULL, NULL);
12688
12689                   if (extra)
12690                     gst_buffer_unref (extra);
12691                   g_free (header);
12692                 }
12693               }
12694             } else
12695               GST_DEBUG ("Didn't find waveheadernode for this codec");
12696           }
12697           g_node_destroy (wavenode);
12698         }
12699       } else if (esds) {
12700         gst_qtdemux_handle_esds (qtdemux, stream, entry, esds,
12701             stream->stream_tags);
12702       } else {
12703         switch (fourcc) {
12704 #if 0
12705             /* FIXME: what is in the chunk? */
12706           case FOURCC_QDMC:
12707           {
12708             gint len = QT_UINT32 (stsd_data);
12709
12710             /* seems to be always = 116 = 0x74 */
12711             break;
12712           }
12713 #endif
12714           case FOURCC_QDM2:
12715           {
12716             gint len = QT_UINT32 (stsd_entry_data);
12717
12718             if (len > 0x3C) {
12719               GstBuffer *buf = gst_buffer_new_and_alloc (len - 0x3C);
12720
12721               gst_buffer_fill (buf, 0, stsd_entry_data + 0x3C, len - 0x3C);
12722               gst_caps_set_simple (entry->caps,
12723                   "codec_data", GST_TYPE_BUFFER, buf, NULL);
12724               gst_buffer_unref (buf);
12725             }
12726             gst_caps_set_simple (entry->caps,
12727                 "samplesize", G_TYPE_INT, samplesize, NULL);
12728             break;
12729           }
12730           case FOURCC_alac:
12731           {
12732             GNode *alac, *wave = NULL;
12733
12734             /* apparently, m4a has this atom appended directly in the stsd entry,
12735              * while mov has it in a wave atom */
12736             alac = qtdemux_tree_get_child_by_type (stsd, FOURCC_alac);
12737             if (alac) {
12738               /* alac now refers to stsd entry atom */
12739               wave = qtdemux_tree_get_child_by_type (alac, FOURCC_wave);
12740               if (wave)
12741                 alac = qtdemux_tree_get_child_by_type (wave, FOURCC_alac);
12742               else
12743                 alac = qtdemux_tree_get_child_by_type (alac, FOURCC_alac);
12744             }
12745             if (alac) {
12746               const guint8 *alac_data = alac->data;
12747               gint len = QT_UINT32 (alac->data);
12748               GstBuffer *buf;
12749
12750               if (len < 36) {
12751                 GST_DEBUG_OBJECT (qtdemux,
12752                     "discarding alac atom with unexpected len %d", len);
12753               } else {
12754                 /* codec-data contains alac atom size and prefix,
12755                  * ffmpeg likes it that way, not quite gst-ish though ...*/
12756                 buf = gst_buffer_new_and_alloc (len);
12757                 gst_buffer_fill (buf, 0, alac->data, len);
12758                 gst_caps_set_simple (entry->caps,
12759                     "codec_data", GST_TYPE_BUFFER, buf, NULL);
12760                 gst_buffer_unref (buf);
12761
12762                 entry->bytes_per_frame = QT_UINT32 (alac_data + 12);
12763                 entry->n_channels = QT_UINT8 (alac_data + 21);
12764                 entry->rate = QT_UINT32 (alac_data + 32);
12765                 samplesize = QT_UINT8 (alac_data + 16 + 1);
12766               }
12767             }
12768             gst_caps_set_simple (entry->caps,
12769                 "samplesize", G_TYPE_INT, samplesize, NULL);
12770             break;
12771           }
12772           case FOURCC_fLaC:
12773           {
12774             /* The codingname of the sample entry is 'fLaC' */
12775             GNode *flac = qtdemux_tree_get_child_by_type (stsd, FOURCC_fLaC);
12776
12777             if (flac) {
12778               /* The 'dfLa' box is added to the sample entry to convey
12779                  initializing information for the decoder. */
12780               const GNode *dfla =
12781                   qtdemux_tree_get_child_by_type (flac, FOURCC_dfLa);
12782
12783               if (dfla) {
12784                 const guint32 len = QT_UINT32 (dfla->data);
12785
12786                 /* Must contain at least dfLa box header (12),
12787                  * METADATA_BLOCK_HEADER (4), METADATA_BLOCK_STREAMINFO (34) */
12788                 if (len < 50) {
12789                   GST_DEBUG_OBJECT (qtdemux,
12790                       "discarding dfla atom with unexpected len %d", len);
12791                 } else {
12792                   /* skip dfLa header to get the METADATA_BLOCKs */
12793                   const guint8 *metadata_blocks = (guint8 *) dfla->data + 12;
12794                   const guint32 metadata_blocks_len = len - 12;
12795
12796                   gchar *stream_marker = g_strdup ("fLaC");
12797                   GstBuffer *block = gst_buffer_new_wrapped (stream_marker,
12798                       strlen (stream_marker));
12799
12800                   guint32 index = 0;
12801                   guint32 remainder = 0;
12802                   guint32 block_size = 0;
12803                   gboolean is_last = FALSE;
12804
12805                   GValue array = G_VALUE_INIT;
12806                   GValue value = G_VALUE_INIT;
12807
12808                   g_value_init (&array, GST_TYPE_ARRAY);
12809                   g_value_init (&value, GST_TYPE_BUFFER);
12810
12811                   gst_value_set_buffer (&value, block);
12812                   gst_value_array_append_value (&array, &value);
12813                   g_value_reset (&value);
12814
12815                   gst_buffer_unref (block);
12816
12817                   /* check there's at least one METADATA_BLOCK_HEADER's worth
12818                    * of data, and we haven't already finished parsing */
12819                   while (!is_last && ((index + 3) < metadata_blocks_len)) {
12820                     remainder = metadata_blocks_len - index;
12821
12822                     /* add the METADATA_BLOCK_HEADER size to the signalled size */
12823                     block_size = 4 +
12824                         (metadata_blocks[index + 1] << 16) +
12825                         (metadata_blocks[index + 2] << 8) +
12826                         metadata_blocks[index + 3];
12827
12828                     /* be careful not to read off end of box */
12829                     if (block_size > remainder) {
12830                       break;
12831                     }
12832
12833                     is_last = metadata_blocks[index] >> 7;
12834
12835                     block = gst_buffer_new_and_alloc (block_size);
12836
12837                     gst_buffer_fill (block, 0, &metadata_blocks[index],
12838                         block_size);
12839
12840                     gst_value_set_buffer (&value, block);
12841                     gst_value_array_append_value (&array, &value);
12842                     g_value_reset (&value);
12843
12844                     gst_buffer_unref (block);
12845
12846                     index += block_size;
12847                   }
12848
12849                   /* only append the metadata if we successfully read all of it */
12850                   if (is_last) {
12851                     gst_structure_set_value (gst_caps_get_structure (CUR_STREAM
12852                             (stream)->caps, 0), "streamheader", &array);
12853                   } else {
12854                     GST_WARNING_OBJECT (qtdemux,
12855                         "discarding all METADATA_BLOCKs due to invalid "
12856                         "block_size %d at idx %d, rem %d", block_size, index,
12857                         remainder);
12858                   }
12859
12860                   g_value_unset (&value);
12861                   g_value_unset (&array);
12862
12863                   /* The sample rate obtained from the stsd may not be accurate
12864                    * since it cannot represent rates greater than 65535Hz, so
12865                    * override that value with the sample rate from the
12866                    * METADATA_BLOCK_STREAMINFO block */
12867                   CUR_STREAM (stream)->rate =
12868                       (QT_UINT32 (metadata_blocks + 14) >> 12) & 0xFFFFF;
12869                 }
12870               }
12871             }
12872             break;
12873           }
12874           case FOURCC_sawb:
12875             /* Fallthrough! */
12876             amrwb = TRUE;
12877           case FOURCC_samr:
12878           {
12879             gint len = QT_UINT32 (stsd_entry_data);
12880
12881             if (len > 0x24) {
12882               GstBuffer *buf = gst_buffer_new_and_alloc (len - 0x24);
12883               guint bitrate;
12884
12885               gst_buffer_fill (buf, 0, stsd_entry_data + 0x24, len - 0x24);
12886
12887               /* If we have enough data, let's try to get the 'damr' atom. See
12888                * the 3GPP container spec (26.244) for more details. */
12889               if ((len - 0x34) > 8 &&
12890                   (bitrate = qtdemux_parse_amr_bitrate (buf, amrwb))) {
12891                 gst_tag_list_add (stream->stream_tags, GST_TAG_MERGE_REPLACE,
12892                     GST_TAG_MAXIMUM_BITRATE, bitrate, NULL);
12893               }
12894
12895               gst_caps_set_simple (entry->caps,
12896                   "codec_data", GST_TYPE_BUFFER, buf, NULL);
12897               gst_buffer_unref (buf);
12898             }
12899             break;
12900           }
12901           case FOURCC_mp4a:
12902           {
12903             /* mp4a atom withtout ESDS; Attempt to build codec data from atom */
12904             gint len = QT_UINT32 (stsd_entry_data);
12905             guint16 sound_version = 0;
12906             /* FIXME: Can this be determined somehow? There doesn't seem to be
12907              * anything in mp4a atom that specifis compression */
12908             gint profile = 2;
12909             guint16 channels = entry->n_channels;
12910             guint32 time_scale = (guint32) entry->rate;
12911             gint sample_rate_index = -1;
12912
12913             if (len >= 34) {
12914               sound_version = QT_UINT16 (stsd_entry_data + 16);
12915
12916               if (sound_version == 1) {
12917                 channels = QT_UINT16 (stsd_entry_data + 24);
12918                 time_scale = QT_UINT32 (stsd_entry_data + 30);
12919               } else {
12920                 GST_FIXME_OBJECT (qtdemux, "Unhandled mp4a atom version %d",
12921                     sound_version);
12922               }
12923             } else {
12924               GST_DEBUG_OBJECT (qtdemux, "Too small stsd entry data len %d",
12925                   len);
12926             }
12927
12928             sample_rate_index =
12929                 gst_codec_utils_aac_get_index_from_sample_rate (time_scale);
12930             if (sample_rate_index >= 0 && channels > 0) {
12931               guint8 codec_data[2];
12932               GstBuffer *buf;
12933
12934               /* build AAC codec data */
12935               codec_data[0] = profile << 3;
12936               codec_data[0] |= ((sample_rate_index >> 1) & 0x7);
12937               codec_data[1] = (sample_rate_index & 0x01) << 7;
12938               codec_data[1] |= (channels & 0xF) << 3;
12939
12940               buf = gst_buffer_new_and_alloc (2);
12941               gst_buffer_fill (buf, 0, codec_data, 2);
12942               gst_caps_set_simple (entry->caps,
12943                   "codec_data", GST_TYPE_BUFFER, buf, NULL);
12944               gst_buffer_unref (buf);
12945             }
12946             break;
12947           }
12948           case FOURCC_lpcm:
12949           case FOURCC_in24:
12950           case FOURCC_in32:
12951           case FOURCC_fl32:
12952           case FOURCC_fl64:
12953           case FOURCC_s16l:
12954             /* Fully handled elsewhere */
12955             break;
12956           default:
12957             GST_INFO_OBJECT (qtdemux,
12958                 "unhandled type %" GST_FOURCC_FORMAT, GST_FOURCC_ARGS (fourcc));
12959             break;
12960         }
12961       }
12962       GST_INFO_OBJECT (qtdemux,
12963           "type %" GST_FOURCC_FORMAT " caps %" GST_PTR_FORMAT,
12964           GST_FOURCC_ARGS (fourcc), entry->caps);
12965
12966     } else if (stream->subtype == FOURCC_strm) {
12967       if (fourcc == FOURCC_rtsp) {
12968         stream->redirect_uri = qtdemux_get_rtsp_uri_from_hndl (qtdemux, minf);
12969       } else {
12970         GST_INFO_OBJECT (qtdemux, "unhandled stream type %" GST_FOURCC_FORMAT,
12971             GST_FOURCC_ARGS (fourcc));
12972         goto unknown_stream;
12973       }
12974       entry->sampled = TRUE;
12975     } else if (stream->subtype == FOURCC_subp || stream->subtype == FOURCC_text
12976         || stream->subtype == FOURCC_sbtl || stream->subtype == FOURCC_subt
12977         || stream->subtype == FOURCC_clcp || stream->subtype == FOURCC_wvtt) {
12978
12979       entry->sampled = TRUE;
12980       entry->sparse = TRUE;
12981
12982       entry->caps =
12983           qtdemux_sub_caps (qtdemux, stream, entry, fourcc, stsd_entry_data,
12984           &codec);
12985       if (codec) {
12986         gst_tag_list_add (stream->stream_tags, GST_TAG_MERGE_REPLACE,
12987             GST_TAG_SUBTITLE_CODEC, codec, NULL);
12988         g_free (codec);
12989         codec = NULL;
12990       }
12991
12992       /* hunt for sort-of codec data */
12993       switch (fourcc) {
12994         case FOURCC_mp4s:
12995         {
12996           GNode *mp4s = NULL;
12997           GNode *esds = NULL;
12998
12999           /* look for palette in a stsd->mp4s->esds sub-atom */
13000           mp4s = qtdemux_tree_get_child_by_type (stsd, FOURCC_mp4s);
13001           if (mp4s)
13002             esds = qtdemux_tree_get_child_by_type (mp4s, FOURCC_esds);
13003           if (esds == NULL) {
13004             /* Invalid STSD */
13005             GST_LOG_OBJECT (qtdemux, "Skipping invalid stsd: no esds child");
13006             break;
13007           }
13008
13009           gst_qtdemux_handle_esds (qtdemux, stream, entry, esds,
13010               stream->stream_tags);
13011           break;
13012         }
13013         default:
13014           GST_INFO_OBJECT (qtdemux,
13015               "unhandled type %" GST_FOURCC_FORMAT, GST_FOURCC_ARGS (fourcc));
13016           break;
13017       }
13018       GST_INFO_OBJECT (qtdemux,
13019           "type %" GST_FOURCC_FORMAT " caps %" GST_PTR_FORMAT,
13020           GST_FOURCC_ARGS (fourcc), entry->caps);
13021     } else {
13022       /* everything in 1 sample */
13023       entry->sampled = TRUE;
13024
13025       entry->caps =
13026           qtdemux_generic_caps (qtdemux, stream, entry, fourcc, stsd_entry_data,
13027           &codec);
13028
13029       if (entry->caps == NULL)
13030         goto unknown_stream;
13031
13032       if (codec) {
13033         gst_tag_list_add (stream->stream_tags, GST_TAG_MERGE_REPLACE,
13034             GST_TAG_SUBTITLE_CODEC, codec, NULL);
13035         g_free (codec);
13036         codec = NULL;
13037       }
13038     }
13039
13040     /* promote to sampled format */
13041     if (entry->fourcc == FOURCC_samr) {
13042       /* force mono 8000 Hz for AMR */
13043       entry->sampled = TRUE;
13044       entry->n_channels = 1;
13045       entry->rate = 8000;
13046     } else if (entry->fourcc == FOURCC_sawb) {
13047       /* force mono 16000 Hz for AMR-WB */
13048       entry->sampled = TRUE;
13049       entry->n_channels = 1;
13050       entry->rate = 16000;
13051     } else if (entry->fourcc == FOURCC_mp4a) {
13052       entry->sampled = TRUE;
13053     }
13054
13055
13056     stsd_entry_data += len;
13057     remaining_stsd_len -= len;
13058
13059   }
13060
13061   /* collect sample information */
13062   if (!qtdemux_stbl_init (qtdemux, stream, stbl))
13063     goto samples_failed;
13064
13065   if (qtdemux->fragmented) {
13066     guint64 offset;
13067
13068     /* need all moov samples as basis; probably not many if any at all */
13069     /* prevent moof parsing taking of at this time */
13070     offset = qtdemux->moof_offset;
13071     qtdemux->moof_offset = 0;
13072     if (stream->n_samples &&
13073         !qtdemux_parse_samples (qtdemux, stream, stream->n_samples - 1)) {
13074       qtdemux->moof_offset = offset;
13075       goto samples_failed;
13076     }
13077     qtdemux->moof_offset = offset;
13078     /* movie duration more reliable in this case (e.g. mehd) */
13079     if (qtdemux->segment.duration &&
13080         GST_CLOCK_TIME_IS_VALID (qtdemux->segment.duration))
13081       stream->duration =
13082           GSTTIME_TO_QTSTREAMTIME (stream, qtdemux->segment.duration);
13083   }
13084
13085   /* configure segments */
13086   if (!qtdemux_parse_segments (qtdemux, stream, trak))
13087     goto segments_failed;
13088
13089   /* add some language tag, if useful */
13090   if (stream->lang_id[0] != '\0' && strcmp (stream->lang_id, "unk") &&
13091       strcmp (stream->lang_id, "und")) {
13092     const gchar *lang_code;
13093
13094     /* convert ISO 639-2 code to ISO 639-1 */
13095     lang_code = gst_tag_get_language_code (stream->lang_id);
13096     gst_tag_list_add (stream->stream_tags, GST_TAG_MERGE_REPLACE,
13097         GST_TAG_LANGUAGE_CODE, (lang_code) ? lang_code : stream->lang_id, NULL);
13098   }
13099
13100   /* Check for UDTA tags */
13101   if ((udta = qtdemux_tree_get_child_by_type (trak, FOURCC_udta))) {
13102     qtdemux_parse_udta (qtdemux, stream->stream_tags, udta);
13103   }
13104
13105   /* Insert and sort new stream in track-id order.
13106    * This will help in comparing old/new streams during stream update check */
13107   g_ptr_array_add (qtdemux->active_streams, stream);
13108   g_ptr_array_sort (qtdemux->active_streams,
13109       (GCompareFunc) qtdemux_track_id_compare_func);
13110   GST_DEBUG_OBJECT (qtdemux, "n_streams is now %d",
13111       QTDEMUX_N_STREAMS (qtdemux));
13112
13113   return TRUE;
13114
13115 /* ERRORS */
13116 corrupt_file:
13117   {
13118     GST_ELEMENT_ERROR (qtdemux, STREAM, DEMUX,
13119         (_("This file is corrupt and cannot be played.")), (NULL));
13120     if (stream)
13121       gst_qtdemux_stream_unref (stream);
13122     return FALSE;
13123   }
13124 error_encrypted:
13125   {
13126     GST_ELEMENT_ERROR (qtdemux, STREAM, DECRYPT, (NULL), (NULL));
13127     gst_qtdemux_stream_unref (stream);
13128     return FALSE;
13129   }
13130 samples_failed:
13131 segments_failed:
13132   {
13133     /* we posted an error already */
13134     /* free stbl sub-atoms */
13135     gst_qtdemux_stbl_free (stream);
13136     gst_qtdemux_stream_unref (stream);
13137     return FALSE;
13138   }
13139 existing_stream:
13140   {
13141     GST_INFO_OBJECT (qtdemux, "stream with track id %i already exists",
13142         track_id);
13143     return TRUE;
13144   }
13145 unknown_stream:
13146   {
13147     GST_INFO_OBJECT (qtdemux, "unknown subtype %" GST_FOURCC_FORMAT,
13148         GST_FOURCC_ARGS (stream->subtype));
13149     gst_qtdemux_stream_unref (stream);
13150     return TRUE;
13151   }
13152 }
13153
13154 /* If we can estimate the overall bitrate, and don't have information about the
13155  * stream bitrate for exactly one stream, this guesses the stream bitrate as
13156  * the overall bitrate minus the sum of the bitrates of all other streams. This
13157  * should be useful for the common case where we have one audio and one video
13158  * stream and can estimate the bitrate of one, but not the other. */
13159 static void
13160 gst_qtdemux_guess_bitrate (GstQTDemux * qtdemux)
13161 {
13162   QtDemuxStream *stream = NULL;
13163   gint64 size, sys_bitrate, sum_bitrate = 0;
13164   GstClockTime duration;
13165   guint bitrate;
13166   gint i;
13167
13168   if (qtdemux->fragmented)
13169     return;
13170
13171   GST_DEBUG_OBJECT (qtdemux, "Looking for streams with unknown bitrate");
13172
13173   if (!gst_pad_peer_query_duration (qtdemux->sinkpad, GST_FORMAT_BYTES, &size)
13174       || size <= 0) {
13175     GST_DEBUG_OBJECT (qtdemux,
13176         "Size in bytes of the stream not known - bailing");
13177     return;
13178   }
13179
13180   /* Subtract the header size */
13181   GST_DEBUG_OBJECT (qtdemux, "Total size %" G_GINT64_FORMAT ", header size %u",
13182       size, qtdemux->header_size);
13183
13184   if (size < qtdemux->header_size)
13185     return;
13186
13187   size = size - qtdemux->header_size;
13188
13189   if (!gst_qtdemux_get_duration (qtdemux, &duration)) {
13190     GST_DEBUG_OBJECT (qtdemux, "Stream duration not known - bailing");
13191     return;
13192   }
13193
13194   for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
13195     QtDemuxStream *str = QTDEMUX_NTH_STREAM (qtdemux, i);
13196     switch (str->subtype) {
13197       case FOURCC_soun:
13198       case FOURCC_vide:
13199         GST_DEBUG_OBJECT (qtdemux, "checking bitrate for %" GST_PTR_FORMAT,
13200             CUR_STREAM (str)->caps);
13201         /* retrieve bitrate, prefer avg then max */
13202         bitrate = 0;
13203         if (str->stream_tags) {
13204           if (gst_tag_list_get_uint (str->stream_tags,
13205                   GST_TAG_MAXIMUM_BITRATE, &bitrate))
13206             GST_DEBUG_OBJECT (qtdemux, "max-bitrate: %u", bitrate);
13207           if (gst_tag_list_get_uint (str->stream_tags,
13208                   GST_TAG_NOMINAL_BITRATE, &bitrate))
13209             GST_DEBUG_OBJECT (qtdemux, "nominal-bitrate: %u", bitrate);
13210           if (gst_tag_list_get_uint (str->stream_tags,
13211                   GST_TAG_BITRATE, &bitrate))
13212             GST_DEBUG_OBJECT (qtdemux, "bitrate: %u", bitrate);
13213         }
13214         if (bitrate)
13215           sum_bitrate += bitrate;
13216         else {
13217           if (stream) {
13218             GST_DEBUG_OBJECT (qtdemux,
13219                 ">1 stream with unknown bitrate - bailing");
13220             return;
13221           } else
13222             stream = str;
13223         }
13224
13225       default:
13226         /* For other subtypes, we assume no significant impact on bitrate */
13227         break;
13228     }
13229   }
13230
13231   if (!stream) {
13232     GST_DEBUG_OBJECT (qtdemux, "All stream bitrates are known");
13233     return;
13234   }
13235
13236   sys_bitrate = gst_util_uint64_scale (size, GST_SECOND * 8, duration);
13237
13238   if (sys_bitrate < sum_bitrate) {
13239     /* This can happen, since sum_bitrate might be derived from maximum
13240      * bitrates and not average bitrates */
13241     GST_DEBUG_OBJECT (qtdemux,
13242         "System bitrate less than sum bitrate - bailing");
13243     return;
13244   }
13245
13246   bitrate = sys_bitrate - sum_bitrate;
13247   GST_DEBUG_OBJECT (qtdemux, "System bitrate = %" G_GINT64_FORMAT
13248       ", Stream bitrate = %u", sys_bitrate, bitrate);
13249
13250   if (!stream->stream_tags)
13251     stream->stream_tags = gst_tag_list_new_empty ();
13252   else
13253     stream->stream_tags = gst_tag_list_make_writable (stream->stream_tags);
13254
13255   gst_tag_list_add (stream->stream_tags, GST_TAG_MERGE_REPLACE,
13256       GST_TAG_BITRATE, bitrate, NULL);
13257 }
13258
13259 static GstFlowReturn
13260 qtdemux_prepare_streams (GstQTDemux * qtdemux)
13261 {
13262   GstFlowReturn ret = GST_FLOW_OK;
13263   gint i;
13264
13265   GST_DEBUG_OBJECT (qtdemux, "prepare %u streams", QTDEMUX_N_STREAMS (qtdemux));
13266
13267   for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
13268     QtDemuxStream *stream = QTDEMUX_NTH_STREAM (qtdemux, i);
13269     guint32 sample_num = 0;
13270
13271     GST_DEBUG_OBJECT (qtdemux, "track-id %u, fourcc %" GST_FOURCC_FORMAT,
13272         stream->track_id, GST_FOURCC_ARGS (CUR_STREAM (stream)->fourcc));
13273
13274     if (qtdemux->fragmented && qtdemux->pullbased) {
13275       /* need all moov samples first */
13276       GST_OBJECT_LOCK (qtdemux);
13277       while (stream->n_samples == 0)
13278         if ((ret = qtdemux_add_fragmented_samples (qtdemux)) != GST_FLOW_OK)
13279           break;
13280       GST_OBJECT_UNLOCK (qtdemux);
13281     } else {
13282       /* discard any stray moof */
13283       qtdemux->moof_offset = 0;
13284     }
13285
13286     /* prepare braking */
13287     if (ret != GST_FLOW_ERROR)
13288       ret = GST_FLOW_OK;
13289
13290     /* in pull mode, we should have parsed some sample info by now;
13291      * and quite some code will not handle no samples.
13292      * in push mode, we'll just have to deal with it */
13293     if (G_UNLIKELY (qtdemux->pullbased && !stream->n_samples)) {
13294       GST_DEBUG_OBJECT (qtdemux, "no samples for stream; discarding");
13295       g_ptr_array_remove_index (qtdemux->active_streams, i);
13296       i--;
13297       continue;
13298     } else if (stream->track_id == qtdemux->chapters_track_id &&
13299         (stream->subtype == FOURCC_text || stream->subtype == FOURCC_sbtl)) {
13300       /* TODO - parse chapters track and expose it as GstToc; For now just ignore it
13301          so that it doesn't look like a subtitle track */
13302       g_ptr_array_remove_index (qtdemux->active_streams, i);
13303       i--;
13304       continue;
13305     }
13306
13307     /* parse the initial sample for use in setting the frame rate cap */
13308     while (sample_num == 0 && sample_num < stream->n_samples) {
13309       if (!qtdemux_parse_samples (qtdemux, stream, sample_num))
13310         break;
13311       ++sample_num;
13312     }
13313   }
13314
13315   return ret;
13316 }
13317
13318 static gboolean
13319 _stream_equal_func (const QtDemuxStream * stream, const gchar * stream_id)
13320 {
13321   return g_strcmp0 (stream->stream_id, stream_id) == 0;
13322 }
13323
13324 static gboolean
13325 qtdemux_is_streams_update (GstQTDemux * qtdemux)
13326 {
13327   gint i;
13328
13329   /* Different length, updated */
13330   if (QTDEMUX_N_STREAMS (qtdemux) != qtdemux->old_streams->len)
13331     return TRUE;
13332
13333   /* streams in list are sorted in track-id order */
13334   for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
13335     /* Different stream-id, updated */
13336     if (g_strcmp0 (QTDEMUX_NTH_STREAM (qtdemux, i)->stream_id,
13337             QTDEMUX_NTH_OLD_STREAM (qtdemux, i)->stream_id))
13338       return TRUE;
13339   }
13340
13341   return FALSE;
13342 }
13343
13344 static gboolean
13345 qtdemux_reuse_and_configure_stream (GstQTDemux * qtdemux,
13346     QtDemuxStream * oldstream, QtDemuxStream * newstream)
13347 {
13348   /* Connect old stream's srcpad to new stream */
13349   newstream->pad = oldstream->pad;
13350   oldstream->pad = NULL;
13351
13352   /* unset new_stream to prevent stream-start event, unless we are EOS in which
13353    * case we need to force one through */
13354   newstream->new_stream = GST_PAD_IS_EOS (newstream->pad);
13355
13356   return gst_qtdemux_configure_stream (qtdemux, newstream);
13357 }
13358
13359 static gboolean
13360 qtdemux_update_streams (GstQTDemux * qtdemux)
13361 {
13362   gint i;
13363   g_assert (qtdemux->streams_aware);
13364
13365   /* At below, figure out which stream in active_streams has identical stream-id
13366    * with that of in old_streams. If there is matching stream-id,
13367    * corresponding newstream will not be exposed again,
13368    * but demux will reuse srcpad of matched old stream
13369    *
13370    * active_streams : newly created streams from the latest moov
13371    * old_streams : existing streams (belong to previous moov)
13372    */
13373
13374   for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
13375     QtDemuxStream *stream = QTDEMUX_NTH_STREAM (qtdemux, i);
13376     QtDemuxStream *oldstream = NULL;
13377     guint target;
13378
13379     GST_DEBUG_OBJECT (qtdemux, "track-id %u, fourcc %" GST_FOURCC_FORMAT,
13380         stream->track_id, GST_FOURCC_ARGS (CUR_STREAM (stream)->fourcc));
13381
13382     if (g_ptr_array_find_with_equal_func (qtdemux->old_streams,
13383             stream->stream_id, (GEqualFunc) _stream_equal_func, &target)) {
13384       oldstream = QTDEMUX_NTH_OLD_STREAM (qtdemux, target);
13385
13386       /* null pad stream cannot be reused */
13387       if (oldstream->pad == NULL)
13388         oldstream = NULL;
13389     }
13390
13391     if (oldstream) {
13392       GST_DEBUG_OBJECT (qtdemux, "Reuse track-id %d", oldstream->track_id);
13393
13394       if (!qtdemux_reuse_and_configure_stream (qtdemux, oldstream, stream))
13395         return FALSE;
13396
13397       /* we don't need to preserve order of old streams */
13398       g_ptr_array_remove_fast (qtdemux->old_streams, oldstream);
13399     } else {
13400       GstTagList *list;
13401
13402       /* now we have all info and can expose */
13403       list = stream->stream_tags;
13404       stream->stream_tags = NULL;
13405       if (!gst_qtdemux_add_stream (qtdemux, stream, list))
13406         return FALSE;
13407     }
13408   }
13409
13410   return TRUE;
13411 }
13412
13413 /* Must be called with expose lock */
13414 static GstFlowReturn
13415 qtdemux_expose_streams (GstQTDemux * qtdemux)
13416 {
13417   gint i;
13418
13419   GST_DEBUG_OBJECT (qtdemux, "exposing streams");
13420
13421   if (!qtdemux_is_streams_update (qtdemux)) {
13422     GST_DEBUG_OBJECT (qtdemux, "Reuse all streams");
13423     for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
13424       QtDemuxStream *new_stream = QTDEMUX_NTH_STREAM (qtdemux, i);
13425       QtDemuxStream *old_stream = QTDEMUX_NTH_OLD_STREAM (qtdemux, i);
13426       if (!qtdemux_reuse_and_configure_stream (qtdemux, old_stream, new_stream))
13427         return GST_FLOW_ERROR;
13428     }
13429
13430     g_ptr_array_set_size (qtdemux->old_streams, 0);
13431     qtdemux->need_segment = TRUE;
13432
13433     return GST_FLOW_OK;
13434   }
13435
13436   if (qtdemux->streams_aware) {
13437     if (!qtdemux_update_streams (qtdemux))
13438       return GST_FLOW_ERROR;
13439   } else {
13440     for (i = 0; i < QTDEMUX_N_STREAMS (qtdemux); i++) {
13441       QtDemuxStream *stream = QTDEMUX_NTH_STREAM (qtdemux, i);
13442       GstTagList *list;
13443
13444       /* now we have all info and can expose */
13445       list = stream->stream_tags;
13446       stream->stream_tags = NULL;
13447       if (!gst_qtdemux_add_stream (qtdemux, stream, list))
13448         return GST_FLOW_ERROR;
13449
13450     }
13451   }
13452
13453   gst_qtdemux_guess_bitrate (qtdemux);
13454
13455   gst_element_no_more_pads (GST_ELEMENT_CAST (qtdemux));
13456
13457   /* If we have still old_streams, it's no more used stream */
13458   for (i = 0; i < qtdemux->old_streams->len; i++) {
13459     QtDemuxStream *stream = QTDEMUX_NTH_OLD_STREAM (qtdemux, i);
13460
13461     if (stream->pad) {
13462       GstEvent *event;
13463
13464       event = gst_event_new_eos ();
13465       if (qtdemux->segment_seqnum)
13466         gst_event_set_seqnum (event, qtdemux->segment_seqnum);
13467
13468       gst_pad_push_event (stream->pad, event);
13469     }
13470   }
13471
13472   g_ptr_array_set_size (qtdemux->old_streams, 0);
13473
13474   /* check if we should post a redirect in case there is a single trak
13475    * and it is a redirecting trak */
13476   if (QTDEMUX_N_STREAMS (qtdemux) == 1 &&
13477       QTDEMUX_NTH_STREAM (qtdemux, 0)->redirect_uri != NULL) {
13478     GstMessage *m;
13479
13480     GST_INFO_OBJECT (qtdemux, "Issuing a redirect due to a single track with "
13481         "an external content");
13482     m = gst_message_new_element (GST_OBJECT_CAST (qtdemux),
13483         gst_structure_new ("redirect",
13484             "new-location", G_TYPE_STRING,
13485             QTDEMUX_NTH_STREAM (qtdemux, 0)->redirect_uri, NULL));
13486     gst_element_post_message (GST_ELEMENT_CAST (qtdemux), m);
13487     g_free (qtdemux->redirect_location);
13488     qtdemux->redirect_location =
13489         g_strdup (QTDEMUX_NTH_STREAM (qtdemux, 0)->redirect_uri);
13490   }
13491
13492   g_ptr_array_foreach (qtdemux->active_streams,
13493       (GFunc) qtdemux_do_allocation, qtdemux);
13494
13495   qtdemux->need_segment = TRUE;
13496
13497   qtdemux->exposed = TRUE;
13498   return GST_FLOW_OK;
13499 }
13500
13501 typedef struct
13502 {
13503   GstStructure *structure;      /* helper for sort function */
13504   gchar *location;
13505   guint min_req_bitrate;
13506   guint min_req_qt_version;
13507 } GstQtReference;
13508
13509 static gint
13510 qtdemux_redirects_sort_func (gconstpointer a, gconstpointer b)
13511 {
13512   GstQtReference *ref_a = (GstQtReference *) a;
13513   GstQtReference *ref_b = (GstQtReference *) b;
13514
13515   if (ref_b->min_req_qt_version != ref_a->min_req_qt_version)
13516     return ref_b->min_req_qt_version - ref_a->min_req_qt_version;
13517
13518   /* known bitrates go before unknown; higher bitrates go first */
13519   return ref_b->min_req_bitrate - ref_a->min_req_bitrate;
13520 }
13521
13522 /* sort the redirects and post a message for the application.
13523  */
13524 static void
13525 qtdemux_process_redirects (GstQTDemux * qtdemux, GList * references)
13526 {
13527   GstQtReference *best;
13528   GstStructure *s;
13529   GstMessage *msg;
13530   GValue list_val = { 0, };
13531   GList *l;
13532
13533   g_assert (references != NULL);
13534
13535   references = g_list_sort (references, qtdemux_redirects_sort_func);
13536
13537   best = (GstQtReference *) references->data;
13538
13539   g_value_init (&list_val, GST_TYPE_LIST);
13540
13541   for (l = references; l != NULL; l = l->next) {
13542     GstQtReference *ref = (GstQtReference *) l->data;
13543     GValue struct_val = { 0, };
13544
13545     ref->structure = gst_structure_new ("redirect",
13546         "new-location", G_TYPE_STRING, ref->location, NULL);
13547
13548     if (ref->min_req_bitrate > 0) {
13549       gst_structure_set (ref->structure, "minimum-bitrate", G_TYPE_INT,
13550           ref->min_req_bitrate, NULL);
13551     }
13552
13553     g_value_init (&struct_val, GST_TYPE_STRUCTURE);
13554     g_value_set_boxed (&struct_val, ref->structure);
13555     gst_value_list_append_value (&list_val, &struct_val);
13556     g_value_unset (&struct_val);
13557     /* don't free anything here yet, since we need best->structure below */
13558   }
13559
13560   g_assert (best != NULL);
13561   s = gst_structure_copy (best->structure);
13562
13563   if (g_list_length (references) > 1) {
13564     gst_structure_set_value (s, "locations", &list_val);
13565   }
13566
13567   g_value_unset (&list_val);
13568
13569   for (l = references; l != NULL; l = l->next) {
13570     GstQtReference *ref = (GstQtReference *) l->data;
13571
13572     gst_structure_free (ref->structure);
13573     g_free (ref->location);
13574     g_free (ref);
13575   }
13576   g_list_free (references);
13577
13578   GST_INFO_OBJECT (qtdemux, "posting redirect message: %" GST_PTR_FORMAT, s);
13579   g_free (qtdemux->redirect_location);
13580   qtdemux->redirect_location =
13581       g_strdup (gst_structure_get_string (s, "new-location"));
13582   msg = gst_message_new_element (GST_OBJECT_CAST (qtdemux), s);
13583   gst_element_post_message (GST_ELEMENT_CAST (qtdemux), msg);
13584 }
13585
13586 /* look for redirect nodes, collect all redirect information and
13587  * process it.
13588  */
13589 static gboolean
13590 qtdemux_parse_redirects (GstQTDemux * qtdemux)
13591 {
13592   GNode *rmra, *rmda, *rdrf;
13593
13594   rmra = qtdemux_tree_get_child_by_type (qtdemux->moov_node, FOURCC_rmra);
13595   if (rmra) {
13596     GList *redirects = NULL;
13597
13598     rmda = qtdemux_tree_get_child_by_type (rmra, FOURCC_rmda);
13599     while (rmda) {
13600       GstQtReference ref = { NULL, NULL, 0, 0 };
13601       GNode *rmdr, *rmvc;
13602
13603       if ((rmdr = qtdemux_tree_get_child_by_type (rmda, FOURCC_rmdr))) {
13604         ref.min_req_bitrate = QT_UINT32 ((guint8 *) rmdr->data + 12);
13605         GST_LOG_OBJECT (qtdemux, "data rate atom, required bitrate = %u",
13606             ref.min_req_bitrate);
13607       }
13608
13609       if ((rmvc = qtdemux_tree_get_child_by_type (rmda, FOURCC_rmvc))) {
13610         guint32 package = QT_FOURCC ((guint8 *) rmvc->data + 12);
13611         guint version = QT_UINT32 ((guint8 *) rmvc->data + 16);
13612
13613 #ifndef GST_DISABLE_GST_DEBUG
13614         guint bitmask = QT_UINT32 ((guint8 *) rmvc->data + 20);
13615 #endif
13616         guint check_type = QT_UINT16 ((guint8 *) rmvc->data + 24);
13617
13618         GST_LOG_OBJECT (qtdemux,
13619             "version check atom [%" GST_FOURCC_FORMAT "], version=0x%08x"
13620             ", mask=%08x, check_type=%u", GST_FOURCC_ARGS (package), version,
13621             bitmask, check_type);
13622         if (package == FOURCC_qtim && check_type == 0) {
13623           ref.min_req_qt_version = version;
13624         }
13625       }
13626
13627       rdrf = qtdemux_tree_get_child_by_type (rmda, FOURCC_rdrf);
13628       if (rdrf) {
13629         guint32 ref_type;
13630         guint8 *ref_data;
13631         guint ref_len;
13632
13633         ref_len = QT_UINT32 ((guint8 *) rdrf->data);
13634         if (ref_len > 20) {
13635           ref_type = QT_FOURCC ((guint8 *) rdrf->data + 12);
13636           ref_data = (guint8 *) rdrf->data + 20;
13637           if (ref_type == FOURCC_alis) {
13638             guint record_len, record_version, fn_len;
13639
13640             if (ref_len > 70) {
13641               /* MacOSX alias record, google for alias-layout.txt */
13642               record_len = QT_UINT16 (ref_data + 4);
13643               record_version = QT_UINT16 (ref_data + 4 + 2);
13644               fn_len = QT_UINT8 (ref_data + 50);
13645               if (record_len > 50 && record_version == 2 && fn_len > 0) {
13646                 ref.location = g_strndup ((gchar *) ref_data + 51, fn_len);
13647               }
13648             } else {
13649               GST_WARNING_OBJECT (qtdemux, "Invalid rdrf/alis size (%u < 70)",
13650                   ref_len);
13651             }
13652           } else if (ref_type == FOURCC_url_) {
13653             ref.location = g_strndup ((gchar *) ref_data, ref_len - 8);
13654           } else {
13655             GST_DEBUG_OBJECT (qtdemux,
13656                 "unknown rdrf reference type %" GST_FOURCC_FORMAT,
13657                 GST_FOURCC_ARGS (ref_type));
13658           }
13659           if (ref.location != NULL) {
13660             GST_INFO_OBJECT (qtdemux, "New location: %s", ref.location);
13661             redirects =
13662                 g_list_prepend (redirects, g_memdup2 (&ref, sizeof (ref)));
13663           } else {
13664             GST_WARNING_OBJECT (qtdemux,
13665                 "Failed to extract redirect location from rdrf atom");
13666           }
13667         } else {
13668           GST_WARNING_OBJECT (qtdemux, "Invalid rdrf size (%u < 20)", ref_len);
13669         }
13670       }
13671
13672       /* look for others */
13673       rmda = qtdemux_tree_get_sibling_by_type (rmda, FOURCC_rmda);
13674     }
13675
13676     if (redirects != NULL) {
13677       qtdemux_process_redirects (qtdemux, redirects);
13678     }
13679   }
13680   return TRUE;
13681 }
13682
13683 static GstTagList *
13684 qtdemux_add_container_format (GstQTDemux * qtdemux, GstTagList * tags)
13685 {
13686   const gchar *fmt;
13687
13688   if (tags == NULL) {
13689     tags = gst_tag_list_new_empty ();
13690     gst_tag_list_set_scope (tags, GST_TAG_SCOPE_GLOBAL);
13691   }
13692
13693   if (qtdemux->major_brand == FOURCC_mjp2)
13694     fmt = "Motion JPEG 2000";
13695   else if ((qtdemux->major_brand & 0xffff) == FOURCC_3g__)
13696     fmt = "3GP";
13697   else if (qtdemux->major_brand == FOURCC_qt__)
13698     fmt = "Quicktime";
13699   else if (qtdemux->fragmented)
13700     fmt = "ISO fMP4";
13701   else
13702     fmt = "ISO MP4/M4A";
13703
13704   GST_LOG_OBJECT (qtdemux, "mapped %" GST_FOURCC_FORMAT " to '%s'",
13705       GST_FOURCC_ARGS (qtdemux->major_brand), fmt);
13706
13707   gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE, GST_TAG_CONTAINER_FORMAT,
13708       fmt, NULL);
13709
13710   return tags;
13711 }
13712
13713 /* we have read the complete moov node now.
13714  * This function parses all of the relevant info, creates the traks and
13715  * prepares all data structures for playback
13716  */
13717 static gboolean
13718 qtdemux_parse_tree (GstQTDemux * qtdemux)
13719 {
13720   GNode *mvhd;
13721   GNode *trak;
13722   GNode *udta;
13723   GNode *mvex;
13724   GNode *pssh;
13725   guint64 creation_time;
13726   GstDateTime *datetime = NULL;
13727   gint version;
13728
13729   /* make sure we have a usable taglist */
13730   qtdemux->tag_list = gst_tag_list_make_writable (qtdemux->tag_list);
13731
13732   mvhd = qtdemux_tree_get_child_by_type (qtdemux->moov_node, FOURCC_mvhd);
13733   if (mvhd == NULL) {
13734     GST_LOG_OBJECT (qtdemux, "No mvhd node found, looking for redirects.");
13735     return qtdemux_parse_redirects (qtdemux);
13736   }
13737
13738   version = QT_UINT8 ((guint8 *) mvhd->data + 8);
13739   if (version == 1) {
13740     creation_time = QT_UINT64 ((guint8 *) mvhd->data + 12);
13741     qtdemux->timescale = QT_UINT32 ((guint8 *) mvhd->data + 28);
13742     qtdemux->duration = QT_UINT64 ((guint8 *) mvhd->data + 32);
13743   } else if (version == 0) {
13744     creation_time = QT_UINT32 ((guint8 *) mvhd->data + 12);
13745     qtdemux->timescale = QT_UINT32 ((guint8 *) mvhd->data + 20);
13746     qtdemux->duration = QT_UINT32 ((guint8 *) mvhd->data + 24);
13747   } else {
13748     GST_WARNING_OBJECT (qtdemux, "Unhandled mvhd version %d", version);
13749     return FALSE;
13750   }
13751
13752   /* Moving qt creation time (secs since 1904) to unix time */
13753   if (creation_time != 0) {
13754     /* Try to use epoch first as it should be faster and more commonly found */
13755     if (creation_time >= QTDEMUX_SECONDS_FROM_1904_TO_1970) {
13756       gint64 now_s;
13757
13758       creation_time -= QTDEMUX_SECONDS_FROM_1904_TO_1970;
13759       /* some data cleansing sanity */
13760       now_s = g_get_real_time () / G_USEC_PER_SEC;
13761       if (now_s + 24 * 3600 < creation_time) {
13762         GST_DEBUG_OBJECT (qtdemux, "discarding bogus future creation time");
13763       } else {
13764         datetime = gst_date_time_new_from_unix_epoch_utc (creation_time);
13765       }
13766     } else {
13767       GDateTime *base_dt = g_date_time_new_utc (1904, 1, 1, 0, 0, 0);
13768       GDateTime *dt, *dt_local;
13769
13770       dt = g_date_time_add_seconds (base_dt, creation_time);
13771       dt_local = g_date_time_to_local (dt);
13772       datetime = gst_date_time_new_from_g_date_time (dt_local);
13773
13774       g_date_time_unref (base_dt);
13775       g_date_time_unref (dt);
13776     }
13777   }
13778   if (datetime) {
13779     /* Use KEEP as explicit tags should have a higher priority than mvhd tag */
13780     gst_tag_list_add (qtdemux->tag_list, GST_TAG_MERGE_KEEP, GST_TAG_DATE_TIME,
13781         datetime, NULL);
13782     gst_date_time_unref (datetime);
13783   }
13784
13785   GST_INFO_OBJECT (qtdemux, "timescale: %u", qtdemux->timescale);
13786   GST_INFO_OBJECT (qtdemux, "duration: %" G_GUINT64_FORMAT, qtdemux->duration);
13787
13788   /* check for fragmented file and get some (default) data */
13789   mvex = qtdemux_tree_get_child_by_type (qtdemux->moov_node, FOURCC_mvex);
13790   if (mvex) {
13791     GNode *mehd;
13792     GstByteReader mehd_data;
13793
13794     /* let track parsing or anyone know weird stuff might happen ... */
13795     qtdemux->fragmented = TRUE;
13796
13797     /* compensate for total duration */
13798     mehd = qtdemux_tree_get_child_by_type_full (mvex, FOURCC_mehd, &mehd_data);
13799     if (mehd)
13800       qtdemux_parse_mehd (qtdemux, &mehd_data);
13801   }
13802
13803   /* Update the movie segment duration, unless it was directly given to us
13804    * by upstream. Otherwise let it as is, as we don't want to mangle the
13805    * duration provided by upstream that may come e.g. from a MPD file. */
13806   if (!qtdemux->upstream_format_is_time) {
13807     GstClockTime duration;
13808     /* set duration in the segment info */
13809     gst_qtdemux_get_duration (qtdemux, &duration);
13810     qtdemux->segment.duration = duration;
13811     /* also do not exceed duration; stop is set that way post seek anyway,
13812      * and segment activation falls back to duration,
13813      * whereas loop only checks stop, so let's align this here as well */
13814     qtdemux->segment.stop = duration;
13815   }
13816
13817   /* parse all traks */
13818   trak = qtdemux_tree_get_child_by_type (qtdemux->moov_node, FOURCC_trak);
13819   while (trak) {
13820     qtdemux_parse_trak (qtdemux, trak);
13821     /* iterate all siblings */
13822     trak = qtdemux_tree_get_sibling_by_type (trak, FOURCC_trak);
13823   }
13824
13825   qtdemux->tag_list = gst_tag_list_make_writable (qtdemux->tag_list);
13826
13827   /* find tags */
13828   udta = qtdemux_tree_get_child_by_type (qtdemux->moov_node, FOURCC_udta);
13829   if (udta) {
13830     qtdemux_parse_udta (qtdemux, qtdemux->tag_list, udta);
13831   } else {
13832     GST_LOG_OBJECT (qtdemux, "No udta node found.");
13833   }
13834
13835   /* maybe also some tags in meta box */
13836   udta = qtdemux_tree_get_child_by_type (qtdemux->moov_node, FOURCC_meta);
13837   if (udta) {
13838     GST_DEBUG_OBJECT (qtdemux, "Parsing meta box for tags.");
13839     qtdemux_parse_udta (qtdemux, qtdemux->tag_list, udta);
13840   } else {
13841     GST_LOG_OBJECT (qtdemux, "No meta node found.");
13842   }
13843
13844   /* parse any protection system info */
13845   pssh = qtdemux_tree_get_child_by_type (qtdemux->moov_node, FOURCC_pssh);
13846   while (pssh) {
13847     GST_LOG_OBJECT (qtdemux, "Parsing pssh box.");
13848     qtdemux_parse_pssh (qtdemux, pssh);
13849     pssh = qtdemux_tree_get_sibling_by_type (pssh, FOURCC_pssh);
13850   }
13851
13852   qtdemux->tag_list = qtdemux_add_container_format (qtdemux, qtdemux->tag_list);
13853
13854   return TRUE;
13855 }
13856
13857 /* taken from ffmpeg */
13858 static int
13859 read_descr_size (guint8 * ptr, guint8 * end, guint8 ** end_out)
13860 {
13861   int count = 4;
13862   int len = 0;
13863
13864   while (count--) {
13865     int c;
13866
13867     if (ptr >= end)
13868       return -1;
13869
13870     c = *ptr++;
13871     len = (len << 7) | (c & 0x7f);
13872     if (!(c & 0x80))
13873       break;
13874   }
13875   *end_out = ptr;
13876   return len;
13877 }
13878
13879 static GList *
13880 parse_xiph_stream_headers (GstQTDemux * qtdemux, gpointer codec_data,
13881     gsize codec_data_size)
13882 {
13883   GList *list = NULL;
13884   guint8 *p = codec_data;
13885   gint i, offset, num_packets;
13886   guint *length, last;
13887
13888   GST_MEMDUMP_OBJECT (qtdemux, "xiph codec data", codec_data, codec_data_size);
13889
13890   if (codec_data == NULL || codec_data_size == 0)
13891     goto error;
13892
13893   /* start of the stream and vorbis audio or theora video, need to
13894    * send the codec_priv data as first three packets */
13895   num_packets = p[0] + 1;
13896   GST_DEBUG_OBJECT (qtdemux,
13897       "%u stream headers, total length=%" G_GSIZE_FORMAT " bytes",
13898       (guint) num_packets, codec_data_size);
13899
13900   /* Let's put some limits, Don't think there even is a xiph codec
13901    * with more than 3-4 headers */
13902   if (G_UNLIKELY (num_packets > 16)) {
13903     GST_WARNING_OBJECT (qtdemux,
13904         "Unlikely number of xiph headers, most likely not valid");
13905     goto error;
13906   }
13907
13908   length = g_alloca (num_packets * sizeof (guint));
13909   last = 0;
13910   offset = 1;
13911
13912   /* first packets, read length values */
13913   for (i = 0; i < num_packets - 1; i++) {
13914     length[i] = 0;
13915     while (offset < codec_data_size) {
13916       length[i] += p[offset];
13917       if (p[offset++] != 0xff)
13918         break;
13919     }
13920     last += length[i];
13921   }
13922   if (offset + last > codec_data_size)
13923     goto error;
13924
13925   /* last packet is the remaining size */
13926   length[i] = codec_data_size - offset - last;
13927
13928   for (i = 0; i < num_packets; i++) {
13929     GstBuffer *hdr;
13930
13931     GST_DEBUG_OBJECT (qtdemux, "buffer %d: %u bytes", i, (guint) length[i]);
13932
13933     if (offset + length[i] > codec_data_size)
13934       goto error;
13935
13936     hdr = gst_buffer_new_memdup (p + offset, length[i]);
13937     list = g_list_append (list, hdr);
13938
13939     offset += length[i];
13940   }
13941
13942   return list;
13943
13944   /* ERRORS */
13945 error:
13946   {
13947     if (list != NULL)
13948       g_list_free_full (list, (GDestroyNotify) gst_buffer_unref);
13949     return NULL;
13950   }
13951
13952 }
13953
13954 /* this can change the codec originally present in @list */
13955 static void
13956 gst_qtdemux_handle_esds (GstQTDemux * qtdemux, QtDemuxStream * stream,
13957     QtDemuxStreamStsdEntry * entry, GNode * esds, GstTagList * list)
13958 {
13959   int len = QT_UINT32 (esds->data);
13960   guint8 *ptr = esds->data;
13961   guint8 *end = ptr + len;
13962   int tag;
13963   guint8 *data_ptr = NULL;
13964   int data_len = 0;
13965   guint8 object_type_id = 0;
13966   guint8 stream_type = 0;
13967   const char *codec_name = NULL;
13968   GstCaps *caps = NULL;
13969
13970   GST_MEMDUMP_OBJECT (qtdemux, "esds", ptr, len);
13971   ptr += 8;
13972   GST_DEBUG_OBJECT (qtdemux, "version/flags = %08x", QT_UINT32 (ptr));
13973   ptr += 4;
13974   while (ptr + 1 < end) {
13975     tag = QT_UINT8 (ptr);
13976     GST_DEBUG_OBJECT (qtdemux, "tag = %02x", tag);
13977     ptr++;
13978     len = read_descr_size (ptr, end, &ptr);
13979     GST_DEBUG_OBJECT (qtdemux, "len = %d", len);
13980
13981     /* Check the stated amount of data is available for reading */
13982     if (len < 0 || ptr + len > end)
13983       break;
13984
13985     switch (tag) {
13986       case ES_DESCRIPTOR_TAG:
13987         GST_DEBUG_OBJECT (qtdemux, "ID 0x%04x", QT_UINT16 (ptr));
13988         GST_DEBUG_OBJECT (qtdemux, "priority 0x%04x", QT_UINT8 (ptr + 2));
13989         ptr += 3;
13990         break;
13991       case DECODER_CONFIG_DESC_TAG:{
13992         guint max_bitrate, avg_bitrate;
13993
13994         object_type_id = QT_UINT8 (ptr);
13995         stream_type = QT_UINT8 (ptr + 1) >> 2;
13996         max_bitrate = QT_UINT32 (ptr + 5);
13997         avg_bitrate = QT_UINT32 (ptr + 9);
13998         GST_DEBUG_OBJECT (qtdemux, "object_type_id %02x", object_type_id);
13999         GST_DEBUG_OBJECT (qtdemux, "stream_type %02x", stream_type);
14000         GST_DEBUG_OBJECT (qtdemux, "buffer_size_db %02x", QT_UINT24 (ptr + 2));
14001         GST_DEBUG_OBJECT (qtdemux, "max bitrate %u", max_bitrate);
14002         GST_DEBUG_OBJECT (qtdemux, "avg bitrate %u", avg_bitrate);
14003         if (max_bitrate > 0 && max_bitrate < G_MAXUINT32) {
14004           gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
14005               GST_TAG_MAXIMUM_BITRATE, max_bitrate, NULL);
14006         }
14007         if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32) {
14008           gst_tag_list_add (list, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
14009               avg_bitrate, NULL);
14010         }
14011         ptr += 13;
14012         break;
14013       }
14014       case DECODER_SPECIFIC_INFO_TAG:
14015         GST_MEMDUMP_OBJECT (qtdemux, "data", ptr, len);
14016         if (object_type_id == 0xe0 && len == 0x40) {
14017           guint8 *data;
14018           GstStructure *s;
14019           guint32 clut[16];
14020           gint i;
14021
14022           GST_DEBUG_OBJECT (qtdemux,
14023               "Have VOBSUB palette. Creating palette event");
14024           /* move to decConfigDescr data and read palette */
14025           data = ptr;
14026           for (i = 0; i < 16; i++) {
14027             clut[i] = QT_UINT32 (data);
14028             data += 4;
14029           }
14030
14031           s = gst_structure_new ("application/x-gst-dvd", "event",
14032               G_TYPE_STRING, "dvd-spu-clut-change",
14033               "clut00", G_TYPE_INT, clut[0], "clut01", G_TYPE_INT, clut[1],
14034               "clut02", G_TYPE_INT, clut[2], "clut03", G_TYPE_INT, clut[3],
14035               "clut04", G_TYPE_INT, clut[4], "clut05", G_TYPE_INT, clut[5],
14036               "clut06", G_TYPE_INT, clut[6], "clut07", G_TYPE_INT, clut[7],
14037               "clut08", G_TYPE_INT, clut[8], "clut09", G_TYPE_INT, clut[9],
14038               "clut10", G_TYPE_INT, clut[10], "clut11", G_TYPE_INT, clut[11],
14039               "clut12", G_TYPE_INT, clut[12], "clut13", G_TYPE_INT, clut[13],
14040               "clut14", G_TYPE_INT, clut[14], "clut15", G_TYPE_INT, clut[15],
14041               NULL);
14042
14043           /* store event and trigger custom processing */
14044           stream->pending_event =
14045               gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM, s);
14046         } else {
14047           /* Generic codec_data handler puts it on the caps */
14048           data_ptr = ptr;
14049           data_len = len;
14050         }
14051
14052         ptr += len;
14053         break;
14054       case SL_CONFIG_DESC_TAG:
14055         GST_DEBUG_OBJECT (qtdemux, "data %02x", QT_UINT8 (ptr));
14056         ptr += 1;
14057         break;
14058       default:
14059         GST_DEBUG_OBJECT (qtdemux, "Unknown/unhandled descriptor tag %02x",
14060             tag);
14061         GST_MEMDUMP_OBJECT (qtdemux, "descriptor data", ptr, len);
14062         ptr += len;
14063         break;
14064     }
14065   }
14066
14067   /* object_type_id in the esds atom in mp4a and mp4v tells us which codec is
14068    * in use, and should also be used to override some other parameters for some
14069    * codecs. */
14070   switch (object_type_id) {
14071     case 0x20:                 /* MPEG-4 */
14072       /* 4 bytes for the visual_object_sequence_start_code and 1 byte for the
14073        * profile_and_level_indication */
14074       if (data_ptr != NULL && data_len >= 5 &&
14075           GST_READ_UINT32_BE (data_ptr) == 0x000001b0) {
14076         gst_codec_utils_mpeg4video_caps_set_level_and_profile (entry->caps,
14077             data_ptr + 4, data_len - 4);
14078       }
14079       break;                    /* Nothing special needed here */
14080     case 0x21:                 /* H.264 */
14081       codec_name = "H.264 / AVC";
14082       caps = gst_caps_new_simple ("video/x-h264",
14083           "stream-format", G_TYPE_STRING, "avc",
14084           "alignment", G_TYPE_STRING, "au", NULL);
14085       break;
14086     case 0x40:                 /* AAC (any) */
14087     case 0x66:                 /* AAC Main */
14088     case 0x67:                 /* AAC LC */
14089     case 0x68:                 /* AAC SSR */
14090       /* Override channels and rate based on the codec_data, as it's often
14091        * wrong. */
14092       /* Only do so for basic setup without HE-AAC extension */
14093       if (data_ptr && data_len == 2) {
14094         guint channels, rate;
14095
14096         channels = gst_codec_utils_aac_get_channels (data_ptr, data_len);
14097         if (channels > 0)
14098           entry->n_channels = channels;
14099
14100         rate = gst_codec_utils_aac_get_sample_rate (data_ptr, data_len);
14101         if (rate > 0)
14102           entry->rate = rate;
14103       }
14104
14105       /* Set level and profile if possible */
14106       if (data_ptr != NULL && data_len >= 2) {
14107         gst_codec_utils_aac_caps_set_level_and_profile (entry->caps,
14108             data_ptr, data_len);
14109       } else {
14110         const gchar *profile_str = NULL;
14111         GstBuffer *buffer;
14112         GstMapInfo map;
14113         guint8 *codec_data;
14114         gint rate_idx, profile;
14115
14116         /* No codec_data, let's invent something.
14117          * FIXME: This is wrong for SBR! */
14118
14119         GST_WARNING_OBJECT (qtdemux, "No codec_data for AAC available");
14120
14121         buffer = gst_buffer_new_and_alloc (2);
14122         gst_buffer_map (buffer, &map, GST_MAP_WRITE);
14123         codec_data = map.data;
14124
14125         rate_idx =
14126             gst_codec_utils_aac_get_index_from_sample_rate (CUR_STREAM
14127             (stream)->rate);
14128
14129         switch (object_type_id) {
14130           case 0x66:
14131             profile_str = "main";
14132             profile = 0;
14133             break;
14134           case 0x67:
14135             profile_str = "lc";
14136             profile = 1;
14137             break;
14138           case 0x68:
14139             profile_str = "ssr";
14140             profile = 2;
14141             break;
14142           default:
14143             profile = 3;
14144             break;
14145         }
14146
14147         codec_data[0] = ((profile + 1) << 3) | ((rate_idx & 0xE) >> 1);
14148         codec_data[1] =
14149             ((rate_idx & 0x1) << 7) | (CUR_STREAM (stream)->n_channels << 3);
14150
14151         gst_buffer_unmap (buffer, &map);
14152         gst_caps_set_simple (CUR_STREAM (stream)->caps, "codec_data",
14153             GST_TYPE_BUFFER, buffer, NULL);
14154         gst_buffer_unref (buffer);
14155
14156         if (profile_str) {
14157           gst_caps_set_simple (CUR_STREAM (stream)->caps, "profile",
14158               G_TYPE_STRING, profile_str, NULL);
14159         }
14160       }
14161       break;
14162     case 0x60:                 /* MPEG-2, various profiles */
14163     case 0x61:
14164     case 0x62:
14165     case 0x63:
14166     case 0x64:
14167     case 0x65:
14168       codec_name = "MPEG-2 video";
14169       caps = gst_caps_new_simple ("video/mpeg",
14170           "mpegversion", G_TYPE_INT, 2,
14171           "systemstream", G_TYPE_BOOLEAN, FALSE, NULL);
14172       break;
14173     case 0x69:                 /* MPEG-2 BC audio */
14174     case 0x6B:                 /* MPEG-1 audio */
14175       caps = gst_caps_new_simple ("audio/mpeg",
14176           "mpegversion", G_TYPE_INT, 1, NULL);
14177       codec_name = "MPEG-1 audio";
14178       break;
14179     case 0x6A:                 /* MPEG-1 */
14180       codec_name = "MPEG-1 video";
14181       caps = gst_caps_new_simple ("video/mpeg",
14182           "mpegversion", G_TYPE_INT, 1,
14183           "systemstream", G_TYPE_BOOLEAN, FALSE, NULL);
14184       break;
14185     case 0x6C:                 /* MJPEG */
14186       caps =
14187           gst_caps_new_simple ("image/jpeg", "parsed", G_TYPE_BOOLEAN, TRUE,
14188           NULL);
14189       codec_name = "Motion-JPEG";
14190       break;
14191     case 0x6D:                 /* PNG */
14192       caps =
14193           gst_caps_new_simple ("image/png", "parsed", G_TYPE_BOOLEAN, TRUE,
14194           NULL);
14195       codec_name = "PNG still images";
14196       break;
14197     case 0x6E:                 /* JPEG2000 */
14198       codec_name = "JPEG-2000";
14199       caps = gst_caps_new_simple ("image/x-j2c", "fields", G_TYPE_INT, 1, NULL);
14200       break;
14201     case 0xA4:                 /* Dirac */
14202       codec_name = "Dirac";
14203       caps = gst_caps_new_empty_simple ("video/x-dirac");
14204       break;
14205     case 0xA5:                 /* AC3 */
14206       codec_name = "AC-3 audio";
14207       caps = gst_caps_new_simple ("audio/x-ac3",
14208           "framed", G_TYPE_BOOLEAN, TRUE, NULL);
14209       break;
14210     case 0xA9:                 /* AC3 */
14211       codec_name = "DTS audio";
14212       caps = gst_caps_new_simple ("audio/x-dts",
14213           "framed", G_TYPE_BOOLEAN, TRUE, NULL);
14214       break;
14215     case 0xDD:
14216       if (stream_type == 0x05 && data_ptr) {
14217         GList *headers =
14218             parse_xiph_stream_headers (qtdemux, data_ptr, data_len);
14219         if (headers) {
14220           GList *tmp;
14221           GValue arr_val = G_VALUE_INIT;
14222           GValue buf_val = G_VALUE_INIT;
14223           GstStructure *s;
14224
14225           /* Let's assume it's vorbis if it's an audio stream of type 0xdd and we have codec data that extracts properly */
14226           codec_name = "Vorbis";
14227           caps = gst_caps_new_empty_simple ("audio/x-vorbis");
14228           g_value_init (&arr_val, GST_TYPE_ARRAY);
14229           g_value_init (&buf_val, GST_TYPE_BUFFER);
14230           for (tmp = headers; tmp; tmp = tmp->next) {
14231             g_value_set_boxed (&buf_val, (GstBuffer *) tmp->data);
14232             gst_value_array_append_value (&arr_val, &buf_val);
14233           }
14234           s = gst_caps_get_structure (caps, 0);
14235           gst_structure_take_value (s, "streamheader", &arr_val);
14236           g_value_unset (&buf_val);
14237           g_list_free (headers);
14238
14239           data_ptr = NULL;
14240           data_len = 0;
14241         }
14242       }
14243       break;
14244     case 0xE1:                 /* QCELP */
14245       /* QCELP, the codec_data is a riff tag (little endian) with
14246        * more info (http://ftp.3gpp2.org/TSGC/Working/2003/2003-05-SanDiego/TSG-C-2003-05-San%20Diego/WG1/SWG12/C12-20030512-006%20=%20C12-20030217-015_Draft_Baseline%20Text%20of%20FFMS_R2.doc). */
14247       caps = gst_caps_new_empty_simple ("audio/qcelp");
14248       codec_name = "QCELP";
14249       break;
14250     default:
14251       break;
14252   }
14253
14254   /* If we have a replacement caps, then change our caps for this stream */
14255   if (caps) {
14256     gst_caps_unref (entry->caps);
14257     entry->caps = caps;
14258   }
14259
14260   if (codec_name && list)
14261     gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
14262         GST_TAG_AUDIO_CODEC, codec_name, NULL);
14263
14264   /* Add the codec_data attribute to caps, if we have it */
14265   if (data_ptr) {
14266     GstBuffer *buffer;
14267
14268     buffer = gst_buffer_new_and_alloc (data_len);
14269     gst_buffer_fill (buffer, 0, data_ptr, data_len);
14270
14271     GST_DEBUG_OBJECT (qtdemux, "setting codec_data from esds");
14272     GST_MEMDUMP_OBJECT (qtdemux, "codec_data from esds", data_ptr, data_len);
14273
14274     gst_caps_set_simple (entry->caps, "codec_data", GST_TYPE_BUFFER,
14275         buffer, NULL);
14276     gst_buffer_unref (buffer);
14277   }
14278
14279 }
14280
14281 static inline GstCaps *
14282 _get_unknown_codec_name (const gchar * type, guint32 fourcc)
14283 {
14284   GstCaps *caps;
14285   guint i;
14286   char *s, fourstr[5];
14287
14288   g_snprintf (fourstr, 5, "%" GST_FOURCC_FORMAT, GST_FOURCC_ARGS (fourcc));
14289   for (i = 0; i < 4; i++) {
14290     if (!g_ascii_isalnum (fourstr[i]))
14291       fourstr[i] = '_';
14292   }
14293   s = g_strdup_printf ("%s/x-gst-fourcc-%s", type, g_strstrip (fourstr));
14294   caps = gst_caps_new_empty_simple (s);
14295   g_free (s);
14296   return caps;
14297 }
14298
14299 #define _codec(name) \
14300   do { \
14301     if (codec_name) { \
14302       *codec_name = g_strdup (name); \
14303     } \
14304   } while (0)
14305
14306 static GstCaps *
14307 qtdemux_video_caps (GstQTDemux * qtdemux, QtDemuxStream * stream,
14308     QtDemuxStreamStsdEntry * entry, guint32 fourcc,
14309     const guint8 * stsd_entry_data, gchar ** codec_name)
14310 {
14311   GstCaps *caps = NULL;
14312   GstVideoFormat format = GST_VIDEO_FORMAT_UNKNOWN;
14313
14314   switch (fourcc) {
14315     case FOURCC_png:
14316       _codec ("PNG still images");
14317       caps = gst_caps_new_empty_simple ("image/png");
14318       break;
14319     case FOURCC_jpeg:
14320       _codec ("JPEG still images");
14321       caps =
14322           gst_caps_new_simple ("image/jpeg", "parsed", G_TYPE_BOOLEAN, TRUE,
14323           NULL);
14324       break;
14325     case GST_MAKE_FOURCC ('m', 'j', 'p', 'a'):
14326     case GST_MAKE_FOURCC ('A', 'V', 'D', 'J'):
14327     case GST_MAKE_FOURCC ('M', 'J', 'P', 'G'):
14328     case GST_MAKE_FOURCC ('d', 'm', 'b', '1'):
14329       _codec ("Motion-JPEG");
14330       caps =
14331           gst_caps_new_simple ("image/jpeg", "parsed", G_TYPE_BOOLEAN, TRUE,
14332           NULL);
14333       break;
14334     case GST_MAKE_FOURCC ('m', 'j', 'p', 'b'):
14335       _codec ("Motion-JPEG format B");
14336       caps = gst_caps_new_empty_simple ("video/x-mjpeg-b");
14337       break;
14338     case FOURCC_mjp2:
14339       _codec ("JPEG-2000");
14340       /* override to what it should be according to spec, avoid palette_data */
14341       entry->bits_per_sample = 24;
14342       caps = gst_caps_new_simple ("image/x-j2c", "fields", G_TYPE_INT, 1, NULL);
14343       break;
14344     case FOURCC_SVQ3:
14345       _codec ("Sorensen video v.3");
14346       caps = gst_caps_new_simple ("video/x-svq",
14347           "svqversion", G_TYPE_INT, 3, NULL);
14348       break;
14349     case GST_MAKE_FOURCC ('s', 'v', 'q', 'i'):
14350     case GST_MAKE_FOURCC ('S', 'V', 'Q', '1'):
14351       _codec ("Sorensen video v.1");
14352       caps = gst_caps_new_simple ("video/x-svq",
14353           "svqversion", G_TYPE_INT, 1, NULL);
14354       break;
14355     case GST_MAKE_FOURCC ('W', 'R', 'A', 'W'):
14356       caps = gst_caps_new_empty_simple ("video/x-raw");
14357       gst_caps_set_simple (caps, "format", G_TYPE_STRING, "RGB8P", NULL);
14358       _codec ("Windows Raw RGB");
14359       stream->alignment = 32;
14360       break;
14361     case FOURCC_raw_:
14362     {
14363       guint16 bps;
14364
14365       bps = QT_UINT16 (stsd_entry_data + 82);
14366       switch (bps) {
14367         case 15:
14368           format = GST_VIDEO_FORMAT_RGB15;
14369           break;
14370         case 16:
14371           format = GST_VIDEO_FORMAT_RGB16;
14372           break;
14373         case 24:
14374           format = GST_VIDEO_FORMAT_RGB;
14375           break;
14376         case 32:
14377           format = GST_VIDEO_FORMAT_ARGB;
14378           break;
14379         default:
14380           /* unknown */
14381           break;
14382       }
14383       break;
14384     }
14385     case GST_MAKE_FOURCC ('y', 'v', '1', '2'):
14386       format = GST_VIDEO_FORMAT_I420;
14387       break;
14388     case GST_MAKE_FOURCC ('y', 'u', 'v', '2'):
14389     case GST_MAKE_FOURCC ('Y', 'u', 'v', '2'):
14390       format = GST_VIDEO_FORMAT_I420;
14391       break;
14392     case FOURCC_2vuy:
14393     case GST_MAKE_FOURCC ('2', 'V', 'u', 'y'):
14394       format = GST_VIDEO_FORMAT_UYVY;
14395       break;
14396     case GST_MAKE_FOURCC ('v', '3', '0', '8'):
14397       format = GST_VIDEO_FORMAT_v308;
14398       break;
14399     case GST_MAKE_FOURCC ('v', '2', '1', '6'):
14400       format = GST_VIDEO_FORMAT_v216;
14401       break;
14402     case FOURCC_v210:
14403       format = GST_VIDEO_FORMAT_v210;
14404       break;
14405     case GST_MAKE_FOURCC ('r', '2', '1', '0'):
14406       format = GST_VIDEO_FORMAT_r210;
14407       break;
14408       /* Packed YUV 4:4:4 10 bit in 32 bits, complex
14409          case GST_MAKE_FOURCC ('v', '4', '1', '0'):
14410          format = GST_VIDEO_FORMAT_v410;
14411          break;
14412        */
14413       /* Packed YUV 4:4:4:4 8 bit in 32 bits
14414        * but different order than AYUV
14415        case GST_MAKE_FOURCC ('v', '4', '0', '8'):
14416        format = GST_VIDEO_FORMAT_v408;
14417        break;
14418        */
14419     case GST_MAKE_FOURCC ('m', 'p', 'e', 'g'):
14420     case GST_MAKE_FOURCC ('m', 'p', 'g', '1'):
14421       _codec ("MPEG-1 video");
14422       caps = gst_caps_new_simple ("video/mpeg", "mpegversion", G_TYPE_INT, 1,
14423           "systemstream", G_TYPE_BOOLEAN, FALSE, NULL);
14424       break;
14425     case GST_MAKE_FOURCC ('h', 'd', 'v', '1'): /* HDV 720p30 */
14426     case GST_MAKE_FOURCC ('h', 'd', 'v', '2'): /* HDV 1080i60 */
14427     case GST_MAKE_FOURCC ('h', 'd', 'v', '3'): /* HDV 1080i50 */
14428     case GST_MAKE_FOURCC ('h', 'd', 'v', '4'): /* HDV 720p24 */
14429     case GST_MAKE_FOURCC ('h', 'd', 'v', '5'): /* HDV 720p25 */
14430     case GST_MAKE_FOURCC ('h', 'd', 'v', '6'): /* HDV 1080p24 */
14431     case GST_MAKE_FOURCC ('h', 'd', 'v', '7'): /* HDV 1080p25 */
14432     case GST_MAKE_FOURCC ('h', 'd', 'v', '8'): /* HDV 1080p30 */
14433     case GST_MAKE_FOURCC ('h', 'd', 'v', '9'): /* HDV 720p60 */
14434     case GST_MAKE_FOURCC ('h', 'd', 'v', 'a'): /* HDV 720p50 */
14435     case GST_MAKE_FOURCC ('m', 'x', '5', 'n'): /* MPEG2 IMX NTSC 525/60 50mb/s produced by FCP */
14436     case GST_MAKE_FOURCC ('m', 'x', '5', 'p'): /* MPEG2 IMX PAL 625/60 50mb/s produced by FCP */
14437     case GST_MAKE_FOURCC ('m', 'x', '4', 'n'): /* MPEG2 IMX NTSC 525/60 40mb/s produced by FCP */
14438     case GST_MAKE_FOURCC ('m', 'x', '4', 'p'): /* MPEG2 IMX PAL 625/60 40mb/s produced by FCP */
14439     case GST_MAKE_FOURCC ('m', 'x', '3', 'n'): /* MPEG2 IMX NTSC 525/60 30mb/s produced by FCP */
14440     case GST_MAKE_FOURCC ('m', 'x', '3', 'p'): /* MPEG2 IMX PAL 625/50 30mb/s produced by FCP */
14441     case GST_MAKE_FOURCC ('x', 'd', 'v', '1'): /* XDCAM HD 720p30 35Mb/s */
14442     case GST_MAKE_FOURCC ('x', 'd', 'v', '2'): /* XDCAM HD 1080i60 35Mb/s */
14443     case GST_MAKE_FOURCC ('x', 'd', 'v', '3'): /* XDCAM HD 1080i50 35Mb/s */
14444     case GST_MAKE_FOURCC ('x', 'd', 'v', '4'): /* XDCAM HD 720p24 35Mb/s */
14445     case GST_MAKE_FOURCC ('x', 'd', 'v', '5'): /* XDCAM HD 720p25 35Mb/s */
14446     case GST_MAKE_FOURCC ('x', 'd', 'v', '6'): /* XDCAM HD 1080p24 35Mb/s */
14447     case GST_MAKE_FOURCC ('x', 'd', 'v', '7'): /* XDCAM HD 1080p25 35Mb/s */
14448     case GST_MAKE_FOURCC ('x', 'd', 'v', '8'): /* XDCAM HD 1080p30 35Mb/s */
14449     case GST_MAKE_FOURCC ('x', 'd', 'v', '9'): /* XDCAM HD 720p60 35Mb/s */
14450     case GST_MAKE_FOURCC ('x', 'd', 'v', 'a'): /* XDCAM HD 720p50 35Mb/s */
14451     case GST_MAKE_FOURCC ('x', 'd', 'v', 'b'): /* XDCAM EX 1080i60 50Mb/s CBR */
14452     case GST_MAKE_FOURCC ('x', 'd', 'v', 'c'): /* XDCAM EX 1080i50 50Mb/s CBR */
14453     case GST_MAKE_FOURCC ('x', 'd', 'v', 'd'): /* XDCAM HD 1080p24 50Mb/s CBR */
14454     case GST_MAKE_FOURCC ('x', 'd', 'v', 'e'): /* XDCAM HD 1080p25 50Mb/s CBR */
14455     case GST_MAKE_FOURCC ('x', 'd', 'v', 'f'): /* XDCAM HD 1080p30 50Mb/s CBR */
14456     case GST_MAKE_FOURCC ('x', 'd', '5', '1'): /* XDCAM HD422 720p30 50Mb/s CBR */
14457     case GST_MAKE_FOURCC ('x', 'd', '5', '4'): /* XDCAM HD422 720p24 50Mb/s CBR */
14458     case GST_MAKE_FOURCC ('x', 'd', '5', '5'): /* XDCAM HD422 720p25 50Mb/s CBR */
14459     case GST_MAKE_FOURCC ('x', 'd', '5', '9'): /* XDCAM HD422 720p60 50Mb/s CBR */
14460     case GST_MAKE_FOURCC ('x', 'd', '5', 'a'): /* XDCAM HD422 720p50 50Mb/s CBR */
14461     case GST_MAKE_FOURCC ('x', 'd', '5', 'b'): /* XDCAM HD422 1080i50 50Mb/s CBR */
14462     case GST_MAKE_FOURCC ('x', 'd', '5', 'c'): /* XDCAM HD422 1080i50 50Mb/s CBR */
14463     case GST_MAKE_FOURCC ('x', 'd', '5', 'd'): /* XDCAM HD422 1080p24 50Mb/s CBR */
14464     case GST_MAKE_FOURCC ('x', 'd', '5', 'e'): /* XDCAM HD422 1080p25 50Mb/s CBR */
14465     case GST_MAKE_FOURCC ('x', 'd', '5', 'f'): /* XDCAM HD422 1080p30 50Mb/s CBR */
14466     case GST_MAKE_FOURCC ('x', 'd', 'h', 'd'): /* XDCAM HD 540p */
14467     case GST_MAKE_FOURCC ('x', 'd', 'h', '2'): /* XDCAM HD422 540p */
14468     case GST_MAKE_FOURCC ('A', 'V', 'm', 'p'): /* AVID IMX PAL */
14469     case GST_MAKE_FOURCC ('m', 'p', 'g', '2'): /* AVID IMX PAL */
14470     case GST_MAKE_FOURCC ('m', 'p', '2', 'v'): /* AVID IMX PAL */
14471     case GST_MAKE_FOURCC ('m', '2', 'v', '1'):
14472       _codec ("MPEG-2 video");
14473       caps = gst_caps_new_simple ("video/mpeg", "mpegversion", G_TYPE_INT, 2,
14474           "systemstream", G_TYPE_BOOLEAN, FALSE, NULL);
14475       break;
14476     case GST_MAKE_FOURCC ('g', 'i', 'f', ' '):
14477       _codec ("GIF still images");
14478       caps = gst_caps_new_empty_simple ("image/gif");
14479       break;
14480     case FOURCC_h263:
14481     case GST_MAKE_FOURCC ('H', '2', '6', '3'):
14482     case FOURCC_s263:
14483     case GST_MAKE_FOURCC ('U', '2', '6', '3'):
14484       _codec ("H.263");
14485       /* ffmpeg uses the height/width props, don't know why */
14486       caps = gst_caps_new_simple ("video/x-h263",
14487           "variant", G_TYPE_STRING, "itu", NULL);
14488       break;
14489     case FOURCC_mp4v:
14490     case FOURCC_MP4V:
14491       _codec ("MPEG-4 video");
14492       caps = gst_caps_new_simple ("video/mpeg", "mpegversion", G_TYPE_INT, 4,
14493           "systemstream", G_TYPE_BOOLEAN, FALSE, NULL);
14494       break;
14495     case GST_MAKE_FOURCC ('3', 'i', 'v', 'd'):
14496     case GST_MAKE_FOURCC ('3', 'I', 'V', 'D'):
14497       _codec ("Microsoft MPEG-4 4.3");  /* FIXME? */
14498       caps = gst_caps_new_simple ("video/x-msmpeg",
14499           "msmpegversion", G_TYPE_INT, 43, NULL);
14500       break;
14501     case GST_MAKE_FOURCC ('D', 'I', 'V', '3'):
14502       _codec ("DivX 3");
14503       caps = gst_caps_new_simple ("video/x-divx",
14504           "divxversion", G_TYPE_INT, 3, NULL);
14505       break;
14506     case GST_MAKE_FOURCC ('D', 'I', 'V', 'X'):
14507     case GST_MAKE_FOURCC ('d', 'i', 'v', 'x'):
14508       _codec ("DivX 4");
14509       caps = gst_caps_new_simple ("video/x-divx",
14510           "divxversion", G_TYPE_INT, 4, NULL);
14511       break;
14512     case GST_MAKE_FOURCC ('D', 'X', '5', '0'):
14513       _codec ("DivX 5");
14514       caps = gst_caps_new_simple ("video/x-divx",
14515           "divxversion", G_TYPE_INT, 5, NULL);
14516       break;
14517
14518     case GST_MAKE_FOURCC ('F', 'F', 'V', '1'):
14519       _codec ("FFV1");
14520       caps = gst_caps_new_simple ("video/x-ffv",
14521           "ffvversion", G_TYPE_INT, 1, NULL);
14522       break;
14523
14524     case GST_MAKE_FOURCC ('3', 'I', 'V', '1'):
14525     case GST_MAKE_FOURCC ('3', 'I', 'V', '2'):
14526     case FOURCC_XVID:
14527     case FOURCC_xvid:
14528     case FOURCC_FMP4:
14529     case FOURCC_fmp4:
14530     case GST_MAKE_FOURCC ('U', 'M', 'P', '4'):
14531       caps = gst_caps_new_simple ("video/mpeg", "mpegversion", G_TYPE_INT, 4,
14532           "systemstream", G_TYPE_BOOLEAN, FALSE, NULL);
14533       _codec ("MPEG-4");
14534       break;
14535
14536     case GST_MAKE_FOURCC ('c', 'v', 'i', 'd'):
14537       _codec ("Cinepak");
14538       caps = gst_caps_new_empty_simple ("video/x-cinepak");
14539       break;
14540     case GST_MAKE_FOURCC ('q', 'd', 'r', 'w'):
14541       _codec ("Apple QuickDraw");
14542       caps = gst_caps_new_empty_simple ("video/x-qdrw");
14543       break;
14544     case GST_MAKE_FOURCC ('r', 'p', 'z', 'a'):
14545       _codec ("Apple video");
14546       caps = gst_caps_new_empty_simple ("video/x-apple-video");
14547       break;
14548     case FOURCC_H264:
14549     case FOURCC_avc1:
14550     case FOURCC_dva1:
14551       _codec ("H.264 / AVC");
14552       caps = gst_caps_new_simple ("video/x-h264",
14553           "stream-format", G_TYPE_STRING, "avc",
14554           "alignment", G_TYPE_STRING, "au", NULL);
14555       break;
14556     case FOURCC_avc3:
14557     case FOURCC_dvav:
14558       _codec ("H.264 / AVC");
14559       caps = gst_caps_new_simple ("video/x-h264",
14560           "stream-format", G_TYPE_STRING, "avc3",
14561           "alignment", G_TYPE_STRING, "au", NULL);
14562       break;
14563     case FOURCC_H265:
14564     case FOURCC_hvc1:
14565     case FOURCC_dvh1:
14566       _codec ("H.265 / HEVC");
14567       caps = gst_caps_new_simple ("video/x-h265",
14568           "stream-format", G_TYPE_STRING, "hvc1",
14569           "alignment", G_TYPE_STRING, "au", NULL);
14570       break;
14571     case FOURCC_hev1:
14572     case FOURCC_dvhe:
14573       _codec ("H.265 / HEVC");
14574       caps = gst_caps_new_simple ("video/x-h265",
14575           "stream-format", G_TYPE_STRING, "hev1",
14576           "alignment", G_TYPE_STRING, "au", NULL);
14577       break;
14578     case FOURCC_rle_:
14579       _codec ("Run-length encoding");
14580       caps = gst_caps_new_simple ("video/x-rle",
14581           "layout", G_TYPE_STRING, "quicktime", NULL);
14582       break;
14583     case FOURCC_WRLE:
14584       _codec ("Run-length encoding");
14585       caps = gst_caps_new_simple ("video/x-rle",
14586           "layout", G_TYPE_STRING, "microsoft", NULL);
14587       break;
14588     case GST_MAKE_FOURCC ('I', 'V', '3', '2'):
14589     case GST_MAKE_FOURCC ('i', 'v', '3', '2'):
14590       _codec ("Indeo Video 3");
14591       caps = gst_caps_new_simple ("video/x-indeo",
14592           "indeoversion", G_TYPE_INT, 3, NULL);
14593       break;
14594     case GST_MAKE_FOURCC ('I', 'V', '4', '1'):
14595     case GST_MAKE_FOURCC ('i', 'v', '4', '1'):
14596       _codec ("Intel Video 4");
14597       caps = gst_caps_new_simple ("video/x-indeo",
14598           "indeoversion", G_TYPE_INT, 4, NULL);
14599       break;
14600     case FOURCC_dvcp:
14601     case FOURCC_dvc_:
14602     case GST_MAKE_FOURCC ('d', 'v', 's', 'd'):
14603     case GST_MAKE_FOURCC ('D', 'V', 'S', 'D'):
14604     case GST_MAKE_FOURCC ('d', 'v', 'c', 's'):
14605     case GST_MAKE_FOURCC ('D', 'V', 'C', 'S'):
14606     case GST_MAKE_FOURCC ('d', 'v', '2', '5'):
14607     case GST_MAKE_FOURCC ('d', 'v', 'p', 'p'):
14608       _codec ("DV Video");
14609       caps = gst_caps_new_simple ("video/x-dv", "dvversion", G_TYPE_INT, 25,
14610           "systemstream", G_TYPE_BOOLEAN, FALSE, NULL);
14611       break;
14612     case FOURCC_dv5n:          /* DVCPRO50 NTSC */
14613     case FOURCC_dv5p:          /* DVCPRO50 PAL */
14614       _codec ("DVCPro50 Video");
14615       caps = gst_caps_new_simple ("video/x-dv", "dvversion", G_TYPE_INT, 50,
14616           "systemstream", G_TYPE_BOOLEAN, FALSE, NULL);
14617       break;
14618     case GST_MAKE_FOURCC ('d', 'v', 'h', '5'): /* DVCPRO HD 50i produced by FCP */
14619     case GST_MAKE_FOURCC ('d', 'v', 'h', '6'): /* DVCPRO HD 60i produced by FCP */
14620       _codec ("DVCProHD Video");
14621       caps = gst_caps_new_simple ("video/x-dv", "dvversion", G_TYPE_INT, 100,
14622           "systemstream", G_TYPE_BOOLEAN, FALSE, NULL);
14623       break;
14624     case GST_MAKE_FOURCC ('s', 'm', 'c', ' '):
14625       _codec ("Apple Graphics (SMC)");
14626       caps = gst_caps_new_empty_simple ("video/x-smc");
14627       break;
14628     case GST_MAKE_FOURCC ('V', 'P', '3', '1'):
14629       _codec ("VP3");
14630       caps = gst_caps_new_empty_simple ("video/x-vp3");
14631       break;
14632     case GST_MAKE_FOURCC ('V', 'P', '6', 'F'):
14633       _codec ("VP6 Flash");
14634       caps = gst_caps_new_empty_simple ("video/x-vp6-flash");
14635       break;
14636     case FOURCC_XiTh:
14637       _codec ("Theora");
14638       caps = gst_caps_new_empty_simple ("video/x-theora");
14639       /* theora uses one byte of padding in the data stream because it does not
14640        * allow 0 sized packets while theora does */
14641       entry->padding = 1;
14642       break;
14643     case FOURCC_drac:
14644       _codec ("Dirac");
14645       caps = gst_caps_new_empty_simple ("video/x-dirac");
14646       break;
14647     case GST_MAKE_FOURCC ('t', 'i', 'f', 'f'):
14648       _codec ("TIFF still images");
14649       caps = gst_caps_new_empty_simple ("image/tiff");
14650       break;
14651     case GST_MAKE_FOURCC ('i', 'c', 'o', 'd'):
14652       _codec ("Apple Intermediate Codec");
14653       caps = gst_caps_from_string ("video/x-apple-intermediate-codec");
14654       break;
14655     case GST_MAKE_FOURCC ('A', 'V', 'd', 'n'):
14656       _codec ("AVID DNxHD");
14657       caps = gst_caps_from_string ("video/x-dnxhd");
14658       break;
14659     case FOURCC_VP80:
14660     case FOURCC_vp08:
14661       _codec ("On2 VP8");
14662       caps = gst_caps_from_string ("video/x-vp8");
14663       break;
14664     case FOURCC_vp09:
14665       _codec ("Google VP9");
14666       caps = gst_caps_from_string ("video/x-vp9");
14667       break;
14668     case FOURCC_apcs:
14669       _codec ("Apple ProRes LT");
14670       caps =
14671           gst_caps_new_simple ("video/x-prores", "variant", G_TYPE_STRING, "lt",
14672           NULL);
14673       break;
14674     case FOURCC_apch:
14675       _codec ("Apple ProRes HQ");
14676       caps =
14677           gst_caps_new_simple ("video/x-prores", "variant", G_TYPE_STRING, "hq",
14678           NULL);
14679       break;
14680     case FOURCC_apcn:
14681       _codec ("Apple ProRes");
14682       caps =
14683           gst_caps_new_simple ("video/x-prores", "variant", G_TYPE_STRING,
14684           "standard", NULL);
14685       break;
14686     case FOURCC_apco:
14687       _codec ("Apple ProRes Proxy");
14688       caps =
14689           gst_caps_new_simple ("video/x-prores", "variant", G_TYPE_STRING,
14690           "proxy", NULL);
14691       break;
14692     case FOURCC_ap4h:
14693       _codec ("Apple ProRes 4444");
14694       caps =
14695           gst_caps_new_simple ("video/x-prores", "variant", G_TYPE_STRING,
14696           "4444", NULL);
14697
14698       /* 24 bits per sample = an alpha channel is coded but image is always opaque */
14699       if (entry->bits_per_sample > 0) {
14700         gst_caps_set_simple (caps, "depth", G_TYPE_INT, entry->bits_per_sample,
14701             NULL);
14702       }
14703       break;
14704     case FOURCC_ap4x:
14705       _codec ("Apple ProRes 4444 XQ");
14706       caps =
14707           gst_caps_new_simple ("video/x-prores", "variant", G_TYPE_STRING,
14708           "4444xq", NULL);
14709
14710       /* 24 bits per sample = an alpha channel is coded but image is always opaque */
14711       if (entry->bits_per_sample > 0) {
14712         gst_caps_set_simple (caps, "depth", G_TYPE_INT, entry->bits_per_sample,
14713             NULL);
14714       }
14715       break;
14716     case FOURCC_cfhd:
14717       _codec ("GoPro CineForm");
14718       caps = gst_caps_from_string ("video/x-cineform");
14719       break;
14720     case FOURCC_vc_1:
14721     case FOURCC_ovc1:
14722       _codec ("VC-1");
14723       caps = gst_caps_new_simple ("video/x-wmv",
14724           "wmvversion", G_TYPE_INT, 3, "format", G_TYPE_STRING, "WVC1", NULL);
14725       break;
14726     case FOURCC_av01:
14727       _codec ("AV1");
14728       caps = gst_caps_new_empty_simple ("video/x-av1");
14729       break;
14730     case GST_MAKE_FOURCC ('k', 'p', 'c', 'd'):
14731     default:
14732     {
14733       caps = _get_unknown_codec_name ("video", fourcc);
14734       break;
14735     }
14736   }
14737
14738   if (format != GST_VIDEO_FORMAT_UNKNOWN) {
14739     GstVideoInfo info;
14740
14741     gst_video_info_init (&info);
14742     gst_video_info_set_format (&info, format, entry->width, entry->height);
14743
14744     caps = gst_video_info_to_caps (&info);
14745     *codec_name = gst_pb_utils_get_codec_description (caps);
14746
14747     /* enable clipping for raw video streams */
14748     stream->need_clip = TRUE;
14749     stream->alignment = 32;
14750   }
14751
14752   return caps;
14753 }
14754
14755 static guint
14756 round_up_pow2 (guint n)
14757 {
14758   n = n - 1;
14759   n = n | (n >> 1);
14760   n = n | (n >> 2);
14761   n = n | (n >> 4);
14762   n = n | (n >> 8);
14763   n = n | (n >> 16);
14764   return n + 1;
14765 }
14766
14767 static GstCaps *
14768 qtdemux_audio_caps (GstQTDemux * qtdemux, QtDemuxStream * stream,
14769     QtDemuxStreamStsdEntry * entry, guint32 fourcc, const guint8 * data,
14770     int len, gchar ** codec_name)
14771 {
14772   GstCaps *caps;
14773   const GstStructure *s;
14774   const gchar *name;
14775   gint endian = 0;
14776   GstAudioFormat format = 0;
14777   gint depth;
14778
14779   GST_DEBUG_OBJECT (qtdemux, "resolve fourcc 0x%08x", GUINT32_TO_BE (fourcc));
14780
14781   depth = entry->bytes_per_packet * 8;
14782
14783   switch (fourcc) {
14784     case GST_MAKE_FOURCC ('N', 'O', 'N', 'E'):
14785     case FOURCC_raw_:
14786       /* 8-bit audio is unsigned */
14787       if (depth == 8)
14788         format = GST_AUDIO_FORMAT_U8;
14789       /* otherwise it's signed and big-endian just like 'twos' */
14790     case FOURCC_twos:
14791       endian = G_BIG_ENDIAN;
14792       /* fall-through */
14793     case FOURCC_sowt:
14794     {
14795       gchar *str;
14796
14797       if (!endian)
14798         endian = G_LITTLE_ENDIAN;
14799
14800       if (!format)
14801         format = gst_audio_format_build_integer (TRUE, endian, depth, depth);
14802
14803       str = g_strdup_printf ("Raw %d-bit PCM audio", depth);
14804       _codec (str);
14805       g_free (str);
14806
14807       caps = gst_caps_new_simple ("audio/x-raw",
14808           "format", G_TYPE_STRING, gst_audio_format_to_string (format),
14809           "layout", G_TYPE_STRING, "interleaved", NULL);
14810       stream->alignment = GST_ROUND_UP_8 (depth);
14811       stream->alignment = round_up_pow2 (stream->alignment);
14812       break;
14813     }
14814     case FOURCC_fl64:
14815       _codec ("Raw 64-bit floating-point audio");
14816       /* we assume BIG ENDIAN, an enda box will tell us to change this to little
14817        * endian later */
14818       caps = gst_caps_new_simple ("audio/x-raw",
14819           "format", G_TYPE_STRING, "F64BE",
14820           "layout", G_TYPE_STRING, "interleaved", NULL);
14821       stream->alignment = 8;
14822       break;
14823     case FOURCC_fl32:
14824       _codec ("Raw 32-bit floating-point audio");
14825       /* we assume BIG ENDIAN, an enda box will tell us to change this to little
14826        * endian later */
14827       caps = gst_caps_new_simple ("audio/x-raw",
14828           "format", G_TYPE_STRING, "F32BE",
14829           "layout", G_TYPE_STRING, "interleaved", NULL);
14830       stream->alignment = 4;
14831       break;
14832     case FOURCC_in24:
14833       _codec ("Raw 24-bit PCM audio");
14834       /* we assume BIG ENDIAN, an enda box will tell us to change this to little
14835        * endian later */
14836       caps = gst_caps_new_simple ("audio/x-raw",
14837           "format", G_TYPE_STRING, "S24BE",
14838           "layout", G_TYPE_STRING, "interleaved", NULL);
14839       stream->alignment = 4;
14840       break;
14841     case FOURCC_in32:
14842       _codec ("Raw 32-bit PCM audio");
14843       /* we assume BIG ENDIAN, an enda box will tell us to change this to little
14844        * endian later */
14845       caps = gst_caps_new_simple ("audio/x-raw",
14846           "format", G_TYPE_STRING, "S32BE",
14847           "layout", G_TYPE_STRING, "interleaved", NULL);
14848       stream->alignment = 4;
14849       break;
14850     case FOURCC_s16l:
14851       _codec ("Raw 16-bit PCM audio");
14852       caps = gst_caps_new_simple ("audio/x-raw",
14853           "format", G_TYPE_STRING, "S16LE",
14854           "layout", G_TYPE_STRING, "interleaved", NULL);
14855       stream->alignment = 2;
14856       break;
14857     case FOURCC_ulaw:
14858       _codec ("Mu-law audio");
14859       caps = gst_caps_new_empty_simple ("audio/x-mulaw");
14860       break;
14861     case FOURCC_alaw:
14862       _codec ("A-law audio");
14863       caps = gst_caps_new_empty_simple ("audio/x-alaw");
14864       break;
14865     case 0x0200736d:
14866     case 0x6d730002:
14867       _codec ("Microsoft ADPCM");
14868       /* Microsoft ADPCM-ACM code 2 */
14869       caps = gst_caps_new_simple ("audio/x-adpcm",
14870           "layout", G_TYPE_STRING, "microsoft", NULL);
14871       break;
14872     case 0x1100736d:
14873     case 0x6d730011:
14874       _codec ("DVI/IMA ADPCM");
14875       caps = gst_caps_new_simple ("audio/x-adpcm",
14876           "layout", G_TYPE_STRING, "dvi", NULL);
14877       break;
14878     case 0x1700736d:
14879     case 0x6d730017:
14880       _codec ("DVI/Intel IMA ADPCM");
14881       /* FIXME DVI/Intel IMA ADPCM/ACM code 17 */
14882       caps = gst_caps_new_simple ("audio/x-adpcm",
14883           "layout", G_TYPE_STRING, "quicktime", NULL);
14884       break;
14885     case 0x5500736d:
14886     case 0x6d730055:
14887       /* MPEG layer 3, CBR only (pre QT4.1) */
14888     case FOURCC__mp3:
14889     case FOURCC_mp3_:
14890       _codec ("MPEG-1 layer 3");
14891       /* MPEG layer 3, CBR & VBR (QT4.1 and later) */
14892       caps = gst_caps_new_simple ("audio/mpeg", "layer", G_TYPE_INT, 3,
14893           "mpegversion", G_TYPE_INT, 1, NULL);
14894       break;
14895     case GST_MAKE_FOURCC ('.', 'm', 'p', '2'):
14896       _codec ("MPEG-1 layer 2");
14897       /* MPEG layer 2 */
14898       caps = gst_caps_new_simple ("audio/mpeg", "layer", G_TYPE_INT, 2,
14899           "mpegversion", G_TYPE_INT, 1, NULL);
14900       break;
14901     case 0x20736d:
14902     case GST_MAKE_FOURCC ('e', 'c', '-', '3'):
14903       _codec ("EAC-3 audio");
14904       caps = gst_caps_new_simple ("audio/x-eac3",
14905           "framed", G_TYPE_BOOLEAN, TRUE, NULL);
14906       entry->sampled = TRUE;
14907       break;
14908     case GST_MAKE_FOURCC ('s', 'a', 'c', '3'): // Nero Recode
14909     case FOURCC_ac_3:
14910       _codec ("AC-3 audio");
14911       caps = gst_caps_new_simple ("audio/x-ac3",
14912           "framed", G_TYPE_BOOLEAN, TRUE, NULL);
14913       entry->sampled = TRUE;
14914       break;
14915     case GST_MAKE_FOURCC ('d', 't', 's', 'c'):
14916     case GST_MAKE_FOURCC ('D', 'T', 'S', ' '):
14917       _codec ("DTS audio");
14918       caps = gst_caps_new_simple ("audio/x-dts",
14919           "framed", G_TYPE_BOOLEAN, TRUE, NULL);
14920       entry->sampled = TRUE;
14921       break;
14922     case GST_MAKE_FOURCC ('d', 't', 's', 'h'): // DTS-HD
14923     case GST_MAKE_FOURCC ('d', 't', 's', 'l'): // DTS-HD Lossless
14924       _codec ("DTS-HD audio");
14925       caps = gst_caps_new_simple ("audio/x-dts",
14926           "framed", G_TYPE_BOOLEAN, TRUE, NULL);
14927       entry->sampled = TRUE;
14928       break;
14929     case FOURCC_MAC3:
14930       _codec ("MACE-3");
14931       caps = gst_caps_new_simple ("audio/x-mace",
14932           "maceversion", G_TYPE_INT, 3, NULL);
14933       break;
14934     case FOURCC_MAC6:
14935       _codec ("MACE-6");
14936       caps = gst_caps_new_simple ("audio/x-mace",
14937           "maceversion", G_TYPE_INT, 6, NULL);
14938       break;
14939     case GST_MAKE_FOURCC ('O', 'g', 'g', 'V'):
14940       /* ogg/vorbis */
14941       caps = gst_caps_new_empty_simple ("application/ogg");
14942       break;
14943     case GST_MAKE_FOURCC ('d', 'v', 'c', 'a'):
14944       _codec ("DV audio");
14945       caps = gst_caps_new_empty_simple ("audio/x-dv");
14946       break;
14947     case FOURCC_mp4a:
14948       _codec ("MPEG-4 AAC audio");
14949       caps = gst_caps_new_simple ("audio/mpeg",
14950           "mpegversion", G_TYPE_INT, 4, "framed", G_TYPE_BOOLEAN, TRUE,
14951           "stream-format", G_TYPE_STRING, "raw", NULL);
14952       break;
14953     case GST_MAKE_FOURCC ('Q', 'D', 'M', 'C'):
14954       _codec ("QDesign Music");
14955       caps = gst_caps_new_empty_simple ("audio/x-qdm");
14956       break;
14957     case FOURCC_QDM2:
14958       _codec ("QDesign Music v.2");
14959       /* FIXME: QDesign music version 2 (no constant) */
14960       if (FALSE && data) {
14961         caps = gst_caps_new_simple ("audio/x-qdm2",
14962             "framesize", G_TYPE_INT, QT_UINT32 (data + 52),
14963             "bitrate", G_TYPE_INT, QT_UINT32 (data + 40),
14964             "blocksize", G_TYPE_INT, QT_UINT32 (data + 44), NULL);
14965       } else {
14966         caps = gst_caps_new_empty_simple ("audio/x-qdm2");
14967       }
14968       break;
14969     case FOURCC_agsm:
14970       _codec ("GSM audio");
14971       caps = gst_caps_new_empty_simple ("audio/x-gsm");
14972       break;
14973     case FOURCC_samr:
14974       _codec ("AMR audio");
14975       caps = gst_caps_new_empty_simple ("audio/AMR");
14976       break;
14977     case FOURCC_sawb:
14978       _codec ("AMR-WB audio");
14979       caps = gst_caps_new_empty_simple ("audio/AMR-WB");
14980       break;
14981     case FOURCC_ima4:
14982       _codec ("Quicktime IMA ADPCM");
14983       caps = gst_caps_new_simple ("audio/x-adpcm",
14984           "layout", G_TYPE_STRING, "quicktime", NULL);
14985       break;
14986     case FOURCC_alac:
14987       _codec ("Apple lossless audio");
14988       caps = gst_caps_new_empty_simple ("audio/x-alac");
14989       break;
14990     case FOURCC_fLaC:
14991       _codec ("Free Lossless Audio Codec");
14992       caps = gst_caps_new_simple ("audio/x-flac",
14993           "framed", G_TYPE_BOOLEAN, TRUE, NULL);
14994       break;
14995     case GST_MAKE_FOURCC ('Q', 'c', 'l', 'p'):
14996       _codec ("QualComm PureVoice");
14997       caps = gst_caps_from_string ("audio/qcelp");
14998       break;
14999     case FOURCC_wma_:
15000     case FOURCC_owma:
15001       _codec ("WMA");
15002       caps = gst_caps_new_empty_simple ("audio/x-wma");
15003       break;
15004     case FOURCC_opus:
15005       _codec ("Opus");
15006       caps = gst_caps_new_empty_simple ("audio/x-opus");
15007       break;
15008     case FOURCC_lpcm:
15009     {
15010       guint32 flags = 0;
15011       guint32 depth = 0;
15012       guint32 width = 0;
15013       GstAudioFormat format;
15014       enum
15015       {
15016         FLAG_IS_FLOAT = 0x1,
15017         FLAG_IS_BIG_ENDIAN = 0x2,
15018         FLAG_IS_SIGNED = 0x4,
15019         FLAG_IS_PACKED = 0x8,
15020         FLAG_IS_ALIGNED_HIGH = 0x10,
15021         FLAG_IS_NON_INTERLEAVED = 0x20
15022       };
15023       _codec ("Raw LPCM audio");
15024
15025       if (data && len >= 36) {
15026         depth = QT_UINT32 (data + 24);
15027         flags = QT_UINT32 (data + 28);
15028         width = QT_UINT32 (data + 32) * 8 / entry->n_channels;
15029       }
15030       if ((flags & FLAG_IS_FLOAT) == 0) {
15031         if (depth == 0)
15032           depth = 16;
15033         if (width == 0)
15034           width = 16;
15035         if ((flags & FLAG_IS_ALIGNED_HIGH))
15036           depth = width;
15037
15038         format = gst_audio_format_build_integer ((flags & FLAG_IS_SIGNED) ?
15039             TRUE : FALSE, (flags & FLAG_IS_BIG_ENDIAN) ?
15040             G_BIG_ENDIAN : G_LITTLE_ENDIAN, width, depth);
15041         caps = gst_caps_new_simple ("audio/x-raw",
15042             "format", G_TYPE_STRING,
15043             format !=
15044             GST_AUDIO_FORMAT_UNKNOWN ? gst_audio_format_to_string (format) :
15045             "UNKNOWN", "layout", G_TYPE_STRING,
15046             (flags & FLAG_IS_NON_INTERLEAVED) ? "non-interleaved" :
15047             "interleaved", NULL);
15048         stream->alignment = GST_ROUND_UP_8 (depth);
15049         stream->alignment = round_up_pow2 (stream->alignment);
15050       } else {
15051         if (width == 0)
15052           width = 32;
15053         if (width == 64) {
15054           if (flags & FLAG_IS_BIG_ENDIAN)
15055             format = GST_AUDIO_FORMAT_F64BE;
15056           else
15057             format = GST_AUDIO_FORMAT_F64LE;
15058         } else {
15059           if (flags & FLAG_IS_BIG_ENDIAN)
15060             format = GST_AUDIO_FORMAT_F32BE;
15061           else
15062             format = GST_AUDIO_FORMAT_F32LE;
15063         }
15064         caps = gst_caps_new_simple ("audio/x-raw",
15065             "format", G_TYPE_STRING, gst_audio_format_to_string (format),
15066             "layout", G_TYPE_STRING, (flags & FLAG_IS_NON_INTERLEAVED) ?
15067             "non-interleaved" : "interleaved", NULL);
15068         stream->alignment = width / 8;
15069       }
15070       break;
15071     }
15072     case GST_MAKE_FOURCC ('a', 'c', '-', '4'):
15073     {
15074       _codec ("AC4");
15075       caps = gst_caps_new_empty_simple ("audio/x-ac4");
15076       break;
15077     }
15078     case GST_MAKE_FOURCC ('q', 't', 'v', 'r'):
15079       /* ? */
15080     default:
15081     {
15082       caps = _get_unknown_codec_name ("audio", fourcc);
15083       break;
15084     }
15085   }
15086
15087   if (caps) {
15088     GstCaps *templ_caps =
15089         gst_static_pad_template_get_caps (&gst_qtdemux_audiosrc_template);
15090     GstCaps *intersection = gst_caps_intersect (caps, templ_caps);
15091     gst_caps_unref (caps);
15092     gst_caps_unref (templ_caps);
15093     caps = intersection;
15094   }
15095
15096   /* enable clipping for raw audio streams */
15097   s = gst_caps_get_structure (caps, 0);
15098   name = gst_structure_get_name (s);
15099   if (g_str_has_prefix (name, "audio/x-raw")) {
15100     stream->need_clip = TRUE;
15101     stream->min_buffer_size = 1024 * entry->bytes_per_frame;
15102     stream->max_buffer_size = 4096 * entry->bytes_per_frame;
15103     GST_DEBUG ("setting min/max buffer sizes to %d/%d", stream->min_buffer_size,
15104         stream->max_buffer_size);
15105   }
15106   return caps;
15107 }
15108
15109 static GstCaps *
15110 qtdemux_sub_caps (GstQTDemux * qtdemux, QtDemuxStream * stream,
15111     QtDemuxStreamStsdEntry * entry, guint32 fourcc,
15112     const guint8 * stsd_entry_data, gchar ** codec_name)
15113 {
15114   GstCaps *caps;
15115
15116   GST_DEBUG_OBJECT (qtdemux, "resolve fourcc 0x%08x", GUINT32_TO_BE (fourcc));
15117
15118   switch (fourcc) {
15119     case FOURCC_mp4s:
15120       _codec ("DVD subtitle");
15121       caps = gst_caps_new_empty_simple ("subpicture/x-dvd");
15122       stream->process_func = gst_qtdemux_process_buffer_dvd;
15123       break;
15124     case FOURCC_text:
15125       _codec ("Quicktime timed text");
15126       goto text;
15127     case FOURCC_tx3g:
15128       _codec ("3GPP timed text");
15129     text:
15130       caps = gst_caps_new_simple ("text/x-raw", "format", G_TYPE_STRING,
15131           "utf8", NULL);
15132       /* actual text piece needs to be extracted */
15133       stream->process_func = gst_qtdemux_process_buffer_text;
15134       break;
15135     case FOURCC_stpp:
15136       _codec ("XML subtitles");
15137       caps = gst_caps_new_empty_simple ("application/ttml+xml");
15138       break;
15139     case FOURCC_wvtt:
15140     {
15141       GstBuffer *buffer;
15142       const gchar *buf = "WEBVTT\n\n";
15143
15144       _codec ("WebVTT subtitles");
15145       caps = gst_caps_new_empty_simple ("application/x-subtitle-vtt");
15146       stream->process_func = gst_qtdemux_process_buffer_wvtt;
15147
15148       /* FIXME: Parse the vttC atom and get the entire WEBVTT header */
15149       buffer = gst_buffer_new_and_alloc (8);
15150       gst_buffer_fill (buffer, 0, buf, 8);
15151       stream->buffers = g_slist_append (stream->buffers, buffer);
15152
15153       break;
15154     }
15155     case FOURCC_c608:
15156       _codec ("CEA 608 Closed Caption");
15157       caps =
15158           gst_caps_new_simple ("closedcaption/x-cea-608", "format",
15159           G_TYPE_STRING, "s334-1a", NULL);
15160       stream->process_func = gst_qtdemux_process_buffer_clcp;
15161       stream->need_split = TRUE;
15162       break;
15163     case FOURCC_c708:
15164       _codec ("CEA 708 Closed Caption");
15165       caps =
15166           gst_caps_new_simple ("closedcaption/x-cea-708", "format",
15167           G_TYPE_STRING, "cdp", NULL);
15168       stream->process_func = gst_qtdemux_process_buffer_clcp;
15169       break;
15170
15171     default:
15172     {
15173       caps = _get_unknown_codec_name ("text", fourcc);
15174       break;
15175     }
15176   }
15177   return caps;
15178 }
15179
15180 static GstCaps *
15181 qtdemux_generic_caps (GstQTDemux * qtdemux, QtDemuxStream * stream,
15182     QtDemuxStreamStsdEntry * entry, guint32 fourcc,
15183     const guint8 * stsd_entry_data, gchar ** codec_name)
15184 {
15185   GstCaps *caps;
15186
15187   switch (fourcc) {
15188     case FOURCC_m1v:
15189       _codec ("MPEG 1 video");
15190       caps = gst_caps_new_simple ("video/mpeg", "mpegversion", G_TYPE_INT, 1,
15191           "systemstream", G_TYPE_BOOLEAN, FALSE, NULL);
15192       break;
15193     default:
15194       caps = NULL;
15195       break;
15196   }
15197   return caps;
15198 }
15199
15200 static void
15201 gst_qtdemux_append_protection_system_id (GstQTDemux * qtdemux,
15202     const gchar * system_id)
15203 {
15204   gint i;
15205
15206   if (!qtdemux->protection_system_ids)
15207     qtdemux->protection_system_ids =
15208         g_ptr_array_new_with_free_func ((GDestroyNotify) g_free);
15209   /* Check whether we already have an entry for this system ID. */
15210   for (i = 0; i < qtdemux->protection_system_ids->len; ++i) {
15211     const gchar *id = g_ptr_array_index (qtdemux->protection_system_ids, i);
15212     if (g_ascii_strcasecmp (system_id, id) == 0) {
15213       return;
15214     }
15215   }
15216   GST_DEBUG_OBJECT (qtdemux, "Adding cenc protection system ID %s", system_id);
15217   g_ptr_array_add (qtdemux->protection_system_ids, g_ascii_strdown (system_id,
15218           -1));
15219 }