Move files from gst-plugins-ugly into the "subprojects/gst-plugins-ugly/" subdir
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / gst / mpegtsdemux / tsdemux.c
1 /*
2  * tsdemux.c
3  * Copyright (C) 2009 Zaheer Abbas Merali
4  *               2010 Edward Hervey
5  * Copyright (C) 2011, Hewlett-Packard Development Company, L.P.
6  *  Author: Youness Alaoui <youness.alaoui@collabora.co.uk>, Collabora Ltd.
7  *  Author: Sebastian Dröge <sebastian.droege@collabora.co.uk>, Collabora Ltd.
8  *  Author: Edward Hervey <bilboed@bilboed.com>, Collabora Ltd.
9  *
10  * Authors:
11  *   Zaheer Abbas Merali <zaheerabbas at merali dot org>
12  *   Edward Hervey <edward.hervey@collabora.co.uk>
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 #ifdef HAVE_CONFIG_H
31 #include "config.h"
32 #endif
33
34 #include <stdlib.h>
35 #include <string.h>
36
37 #include <glib.h>
38 #include <gst/tag/tag.h>
39 #include <gst/pbutils/pbutils.h>
40 #include <gst/base/base.h>
41 #include <gst/audio/audio.h>
42
43 #include "mpegtsbase.h"
44 #include "tsdemux.h"
45 #include "gstmpegdesc.h"
46 #include "gstmpegdefs.h"
47 #include "mpegtspacketizer.h"
48 #include "pesparse.h"
49 #include <gst/codecparsers/gsth264parser.h>
50 #include <gst/codecparsers/gstmpegvideoparser.h>
51 #include <gst/video/video-color.h>
52
53 #include <math.h>
54
55 #define _gst_log2(x) (log(x)/log(2))
56
57 /*
58  * tsdemux
59  *
60  * See TODO for explanations on improvements needed
61  */
62
63 #define CONTINUITY_UNSET 255
64 #define MAX_CONTINUITY 15
65
66 /* Seeking/Scanning related variables */
67
68 /* seek to SEEK_TIMESTAMP_OFFSET before the desired offset and search then
69  * either accurately or for the next timestamp
70  */
71 #define SEEK_TIMESTAMP_OFFSET (2500 * GST_MSECOND)
72
73 #define GST_FLOW_REWINDING GST_FLOW_CUSTOM_ERROR
74
75 /* latency in msecs */
76 #define DEFAULT_LATENCY (700)
77
78 /* Limit PES packet collection to a maximum of 32MB
79  * which is more than large enough to support an H264 frame at
80  * maximum profile/level/bitrate at 30fps or above.
81  * PES bigger than this limit will be output in buffers of
82  * up to this size */
83 #define MAX_PES_PAYLOAD (32 * 1024 * 1024)
84
85 GST_DEBUG_CATEGORY_STATIC (ts_demux_debug);
86 #define GST_CAT_DEFAULT ts_demux_debug
87
88 #define ABSDIFF(a,b) (((a) > (b)) ? ((a) - (b)) : ((b) - (a)))
89
90 static GQuark QUARK_TSDEMUX;
91 static GQuark QUARK_PID;
92 static GQuark QUARK_PCR;
93 static GQuark QUARK_OPCR;
94 static GQuark QUARK_PTS;
95 static GQuark QUARK_DTS;
96 static GQuark QUARK_OFFSET;
97
98 typedef enum
99 {
100   PENDING_PACKET_EMPTY = 0,     /* No pending packet/buffer
101                                  * Push incoming buffers to the array */
102   PENDING_PACKET_HEADER,        /* PES header needs to be parsed
103                                  * Push incoming buffers to the array */
104   PENDING_PACKET_BUFFER,        /* Currently filling up output buffer
105                                  * Push incoming buffers to the bufferlist */
106   PENDING_PACKET_DISCONT        /* Discontinuity in incoming packets
107                                  * Drop all incoming buffers */
108 } PendingPacketState;
109
110 /* Pending buffer */
111 typedef struct
112 {
113   /* The fully reconstructed buffer */
114   GstBuffer *buffer;
115
116   /* Raw PTS/DTS (in 90kHz units) */
117   guint64 pts, dts;
118 } PendingBuffer;
119
120 typedef struct _TSDemuxStream TSDemuxStream;
121
122 typedef struct _TSDemuxH264ParsingInfos TSDemuxH264ParsingInfos;
123 typedef struct _TSDemuxJP2KParsingInfos TSDemuxJP2KParsingInfos;
124 typedef struct _TSDemuxADTSParsingInfos TSDemuxADTSParsingInfos;
125
126 /* Returns TRUE if a keyframe was found */
127 typedef gboolean (*GstTsDemuxKeyFrameScanFunction) (TSDemuxStream * stream,
128     guint8 * data, const gsize data_size, const gsize max_frame_offset);
129
130 typedef struct
131 {
132   guint8 *data;
133   gsize size;
134 } SimpleBuffer;
135
136 struct _TSDemuxH264ParsingInfos
137 {
138   /* H264 parsing data */
139   GstH264NalParser *parser;
140   GstByteWriter *sps;
141   GstByteWriter *pps;
142   GstByteWriter *sei;
143   SimpleBuffer framedata;
144 };
145
146 struct _TSDemuxJP2KParsingInfos
147 {
148   /* J2K parsing data */
149   gboolean interlace;
150 };
151
152 struct _TSDemuxADTSParsingInfos
153 {
154   guint mpegversion;
155 };
156
157 struct _TSDemuxStream
158 {
159   MpegTSBaseStream stream;
160
161   GstPad *pad;
162
163   /* Whether the pad was added or not */
164   gboolean active;
165
166   /* Whether this is a sparse stream (subtitles or metadata) */
167   gboolean sparse;
168
169   /* TRUE if we are waiting for a valid timestamp */
170   gboolean pending_ts;
171
172   /* Output data */
173   PendingPacketState state;
174
175   /* Data being reconstructed (allocated) */
176   guint8 *data;
177
178   /* Size of data being reconstructed (if known, else 0) */
179   guint expected_size;
180
181   /* Amount of bytes in current ->data */
182   guint current_size;
183   /* Size of ->data */
184   guint allocated_size;
185
186   /* Current PTS/DTS for this stream (in running time) */
187   GstClockTime pts;
188   GstClockTime dts;
189
190   /* Reference PTS used to detect gaps */
191   GstClockTime gap_ref_pts;
192   /* Number of outputted buffers */
193   guint32 nb_out_buffers;
194   /* Reference number of buffers for gaps */
195   guint32 gap_ref_buffers;
196
197   /* Current PTS/DTS for this stream (in 90kHz unit) */
198   guint64 raw_pts, raw_dts;
199
200   /* Whether this stream needs to send a newsegment */
201   gboolean need_newsegment;
202
203   /* Whether the next output buffer should be DISCONT */
204   gboolean discont;
205
206   /* The value to use when calculating the newsegment */
207   GstClockTime first_pts;
208
209   GstTagList *taglist;
210
211   gint continuity_counter;
212
213   /* List of pending buffers */
214   GList *pending;
215
216   /* if != 0, output only PES from that substream */
217   guint8 target_pes_substream;
218   gboolean needs_keyframe;
219
220   GstClockTime seeked_pts, seeked_dts;
221
222   GstTsDemuxKeyFrameScanFunction scan_function;
223   TSDemuxH264ParsingInfos h264infos;
224   TSDemuxJP2KParsingInfos jp2kInfos;
225   TSDemuxADTSParsingInfos atdsInfos;
226 };
227
228 #define VIDEO_CAPS \
229   GST_STATIC_CAPS (\
230     "video/mpeg, " \
231       "mpegversion = (int) { 1, 2, 4 }, " \
232       "systemstream = (boolean) FALSE; " \
233     "video/x-h264,stream-format=(string)byte-stream;" \
234     "video/x-h265,stream-format=(string)byte-stream;" \
235     "video/x-dirac;" \
236     "video/x-cavs;" \
237     "video/x-wmv," \
238       "wmvversion = (int) 3, " \
239       "format = (string) WVC1;" \
240       "image/x-jpc;" \
241 )
242
243 #define AUDIO_CAPS \
244   GST_STATIC_CAPS ( \
245     "audio/mpeg, " \
246       "mpegversion = (int) 1;" \
247     "audio/mpeg, " \
248       "mpegversion = (int) { 2, 4 }, " \
249       "stream-format = (string) adts; " \
250     "audio/mpeg, " \
251       "mpegversion = (int) 4, " \
252       "stream-format = (string) loas; " \
253     "audio/x-lpcm, " \
254       "width = (int) { 16, 20, 24 }, " \
255       "rate = (int) { 48000, 96000 }, " \
256       "channels = (int) [ 1, 8 ], " \
257       "dynamic_range = (int) [ 0, 255 ], " \
258       "emphasis = (boolean) { FALSE, TRUE }, " \
259       "mute = (boolean) { FALSE, TRUE }; " \
260     "audio/x-ac3; audio/x-eac3;" \
261     "audio/x-ac4;" \
262     "audio/x-dts;" \
263     "audio/x-opus;" \
264     "audio/x-private-ts-lpcm" \
265   )
266
267 /* Can also use the subpicture pads for text subtitles? */
268 #define SUBPICTURE_CAPS \
269     GST_STATIC_CAPS ("subpicture/x-pgs; subpicture/x-dvd; subpicture/x-dvb")
270
271 static GstStaticPadTemplate video_template =
272 GST_STATIC_PAD_TEMPLATE ("video_%01x_%05x", GST_PAD_SRC,
273     GST_PAD_SOMETIMES,
274     VIDEO_CAPS);
275
276 static GstStaticPadTemplate audio_template =
277 GST_STATIC_PAD_TEMPLATE ("audio_%01x_%05x",
278     GST_PAD_SRC,
279     GST_PAD_SOMETIMES,
280     AUDIO_CAPS);
281
282 static GstStaticPadTemplate subpicture_template =
283 GST_STATIC_PAD_TEMPLATE ("subpicture_%01x_%05x",
284     GST_PAD_SRC,
285     GST_PAD_SOMETIMES,
286     SUBPICTURE_CAPS);
287
288 static GstStaticPadTemplate private_template =
289 GST_STATIC_PAD_TEMPLATE ("private_%01x_%05x",
290     GST_PAD_SRC,
291     GST_PAD_SOMETIMES,
292     GST_STATIC_CAPS_ANY);
293
294 enum
295 {
296   PROP_0,
297   PROP_PROGRAM_NUMBER,
298   PROP_EMIT_STATS,
299   PROP_LATENCY,
300   /* FILL ME */
301 };
302
303 /* Pad functions */
304
305
306 /* mpegtsbase methods */
307 static void
308 gst_ts_demux_update_program (MpegTSBase * base, MpegTSBaseProgram * program);
309 static void
310 gst_ts_demux_program_started (MpegTSBase * base, MpegTSBaseProgram * program);
311 static void
312 gst_ts_demux_program_stopped (MpegTSBase * base, MpegTSBaseProgram * program);
313 static gboolean
314 gst_ts_demux_can_remove_program (MpegTSBase * base,
315     MpegTSBaseProgram * program);
316 static void gst_ts_demux_reset (MpegTSBase * base);
317 static GstFlowReturn
318 gst_ts_demux_push (MpegTSBase * base, MpegTSPacketizerPacket * packet,
319     GstMpegtsSection * section);
320 static void gst_ts_demux_flush (MpegTSBase * base, gboolean hard);
321 static GstFlowReturn gst_ts_demux_drain (MpegTSBase * base);
322 static gboolean
323 gst_ts_demux_stream_added (MpegTSBase * base, MpegTSBaseStream * stream,
324     MpegTSBaseProgram * program);
325 static void
326 gst_ts_demux_stream_removed (MpegTSBase * base, MpegTSBaseStream * stream);
327 static GstFlowReturn gst_ts_demux_do_seek (MpegTSBase * base, GstEvent * event);
328 static void gst_ts_demux_set_property (GObject * object, guint prop_id,
329     const GValue * value, GParamSpec * pspec);
330 static void gst_ts_demux_get_property (GObject * object, guint prop_id,
331     GValue * value, GParamSpec * pspec);
332 static void gst_ts_demux_flush_streams (GstTSDemux * tsdemux, gboolean hard);
333 static GstFlowReturn
334 gst_ts_demux_push_pending_data (GstTSDemux * demux, TSDemuxStream * stream,
335     MpegTSBaseProgram * program);
336 static void gst_ts_demux_stream_flush (TSDemuxStream * stream,
337     GstTSDemux * demux, gboolean hard);
338
339 static gboolean push_event (MpegTSBase * base, GstEvent * event);
340 static gboolean sink_query (MpegTSBase * base, GstQuery * query);
341 static void gst_ts_demux_check_and_sync_streams (GstTSDemux * demux,
342     GstClockTime time);
343
344 static void
345 _extra_init (void)
346 {
347   QUARK_TSDEMUX = g_quark_from_string ("tsdemux");
348   QUARK_PID = g_quark_from_string ("pid");
349   QUARK_PCR = g_quark_from_string ("pcr");
350   QUARK_OPCR = g_quark_from_string ("opcr");
351   QUARK_PTS = g_quark_from_string ("pts");
352   QUARK_DTS = g_quark_from_string ("dts");
353   QUARK_OFFSET = g_quark_from_string ("offset");
354 }
355
356 #define gst_ts_demux_parent_class parent_class
357 G_DEFINE_TYPE_WITH_CODE (GstTSDemux, gst_ts_demux, GST_TYPE_MPEGTS_BASE,
358     _extra_init ());
359 #define _do_element_init \
360   GST_DEBUG_CATEGORY_INIT (ts_demux_debug, "tsdemux", 0, \
361       "MPEG transport stream demuxer");\
362   init_pes_parser ();
363 GST_ELEMENT_REGISTER_DEFINE_WITH_CODE (tsdemux, "tsdemux",
364     GST_RANK_PRIMARY, GST_TYPE_TS_DEMUX, _do_element_init);
365
366 static void
367 gst_ts_demux_dispose (GObject * object)
368 {
369   GstTSDemux *demux = GST_TS_DEMUX_CAST (object);
370
371   gst_flow_combiner_free (demux->flowcombiner);
372
373   GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
374 }
375
376 static void
377 gst_ts_demux_class_init (GstTSDemuxClass * klass)
378 {
379   GObjectClass *gobject_class;
380   GstElementClass *element_class;
381   MpegTSBaseClass *ts_class;
382
383   gobject_class = G_OBJECT_CLASS (klass);
384   gobject_class->set_property = gst_ts_demux_set_property;
385   gobject_class->get_property = gst_ts_demux_get_property;
386   gobject_class->dispose = gst_ts_demux_dispose;
387
388   g_object_class_install_property (gobject_class, PROP_PROGRAM_NUMBER,
389       g_param_spec_int ("program-number", "Program number",
390           "Program Number to demux for (-1 to ignore)", -1, G_MAXINT,
391           -1, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
392
393   g_object_class_install_property (gobject_class, PROP_EMIT_STATS,
394       g_param_spec_boolean ("emit-stats", "Emit statistics",
395           "Emit messages for every pcr/opcr/pts/dts", FALSE,
396           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
397
398   g_object_class_install_property (gobject_class, PROP_LATENCY,
399       g_param_spec_int ("latency", "Latency",
400           "Latency to add for smooth demuxing (in ms)", -1,
401           G_MAXINT, DEFAULT_LATENCY,
402           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
403
404   element_class = GST_ELEMENT_CLASS (klass);
405   gst_element_class_add_pad_template (element_class,
406       gst_static_pad_template_get (&video_template));
407   gst_element_class_add_pad_template (element_class,
408       gst_static_pad_template_get (&audio_template));
409   gst_element_class_add_pad_template (element_class,
410       gst_static_pad_template_get (&subpicture_template));
411   gst_element_class_add_pad_template (element_class,
412       gst_static_pad_template_get (&private_template));
413
414   gst_element_class_set_static_metadata (element_class,
415       "MPEG transport stream demuxer",
416       "Codec/Demuxer",
417       "Demuxes MPEG2 transport streams",
418       "Zaheer Abbas Merali <zaheerabbas at merali dot org>\n"
419       "Edward Hervey <edward.hervey@collabora.co.uk>");
420
421   ts_class = GST_MPEGTS_BASE_CLASS (klass);
422   ts_class->reset = GST_DEBUG_FUNCPTR (gst_ts_demux_reset);
423   ts_class->push = GST_DEBUG_FUNCPTR (gst_ts_demux_push);
424   ts_class->push_event = GST_DEBUG_FUNCPTR (push_event);
425   ts_class->sink_query = GST_DEBUG_FUNCPTR (sink_query);
426   ts_class->program_started = GST_DEBUG_FUNCPTR (gst_ts_demux_program_started);
427   ts_class->program_stopped = GST_DEBUG_FUNCPTR (gst_ts_demux_program_stopped);
428   ts_class->update_program = GST_DEBUG_FUNCPTR (gst_ts_demux_update_program);
429   ts_class->can_remove_program = gst_ts_demux_can_remove_program;
430   ts_class->stream_added = gst_ts_demux_stream_added;
431   ts_class->stream_removed = gst_ts_demux_stream_removed;
432   ts_class->seek = GST_DEBUG_FUNCPTR (gst_ts_demux_do_seek);
433   ts_class->flush = GST_DEBUG_FUNCPTR (gst_ts_demux_flush);
434   ts_class->drain = GST_DEBUG_FUNCPTR (gst_ts_demux_drain);
435 }
436
437 static void
438 gst_ts_demux_reset (MpegTSBase * base)
439 {
440   GstTSDemux *demux = (GstTSDemux *) base;
441
442   demux->rate = 1.0;
443   if (demux->segment_event) {
444     gst_event_unref (demux->segment_event);
445     demux->segment_event = NULL;
446   }
447
448   if (demux->global_tags) {
449     gst_tag_list_unref (demux->global_tags);
450     demux->global_tags = NULL;
451   }
452
453   if (demux->previous_program) {
454     mpegts_base_deactivate_and_free_program (base, demux->previous_program);
455     demux->previous_program = NULL;
456   }
457
458   demux->have_group_id = FALSE;
459   demux->group_id = G_MAXUINT;
460
461   demux->last_seek_offset = -1;
462   demux->program_generation = 0;
463 }
464
465 static void
466 gst_ts_demux_init (GstTSDemux * demux)
467 {
468   MpegTSBase *base = (MpegTSBase *) demux;
469
470   base->stream_size = sizeof (TSDemuxStream);
471   base->parse_private_sections = TRUE;
472   /* We are not interested in sections (all handled by mpegtsbase) */
473   base->push_section = FALSE;
474
475   demux->flowcombiner = gst_flow_combiner_new ();
476   demux->requested_program_number = -1;
477   demux->program_number = -1;
478   demux->latency = DEFAULT_LATENCY;
479   gst_ts_demux_reset (base);
480 }
481
482
483 static void
484 gst_ts_demux_set_property (GObject * object, guint prop_id,
485     const GValue * value, GParamSpec * pspec)
486 {
487   GstTSDemux *demux = GST_TS_DEMUX (object);
488
489   switch (prop_id) {
490     case PROP_PROGRAM_NUMBER:
491       /* FIXME: do something if program is switched as opposed to set at
492        * beginning */
493       demux->requested_program_number = g_value_get_int (value);
494       break;
495     case PROP_EMIT_STATS:
496       demux->emit_statistics = g_value_get_boolean (value);
497       break;
498     case PROP_LATENCY:
499       demux->latency = g_value_get_int (value);
500       break;
501     default:
502       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
503   }
504 }
505
506 static void
507 gst_ts_demux_get_property (GObject * object, guint prop_id,
508     GValue * value, GParamSpec * pspec)
509 {
510   GstTSDemux *demux = GST_TS_DEMUX (object);
511
512   switch (prop_id) {
513     case PROP_PROGRAM_NUMBER:
514       g_value_set_int (value, demux->requested_program_number);
515       break;
516     case PROP_EMIT_STATS:
517       g_value_set_boolean (value, demux->emit_statistics);
518       break;
519     case PROP_LATENCY:
520       g_value_set_int (value, demux->latency);
521       break;
522     default:
523       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
524   }
525 }
526
527 static gboolean
528 gst_ts_demux_get_duration (GstTSDemux * demux, GstClockTime * dur)
529 {
530   MpegTSBase *base = (MpegTSBase *) demux;
531   gboolean res = FALSE;
532   gint64 val;
533
534   if (!demux->program) {
535     GST_DEBUG_OBJECT (demux, "No active program yet, can't provide duration");
536     return FALSE;
537   }
538
539   /* Get total size in bytes */
540   if (gst_pad_peer_query_duration (base->sinkpad, GST_FORMAT_BYTES, &val)) {
541     /* Convert it to duration */
542     *dur =
543         mpegts_packetizer_offset_to_ts (base->packetizer, val,
544         demux->program->pcr_pid);
545     if (GST_CLOCK_TIME_IS_VALID (*dur))
546       res = TRUE;
547   }
548   return res;
549 }
550
551 static gboolean
552 gst_ts_demux_srcpad_query (GstPad * pad, GstObject * parent, GstQuery * query)
553 {
554   gboolean res = TRUE;
555   GstFormat format;
556   GstTSDemux *demux;
557   MpegTSBase *base;
558
559   demux = GST_TS_DEMUX (parent);
560   base = GST_MPEGTS_BASE (demux);
561
562   switch (GST_QUERY_TYPE (query)) {
563     case GST_QUERY_DURATION:
564     {
565       GST_DEBUG ("query duration");
566       gst_query_parse_duration (query, &format, NULL);
567       if (format == GST_FORMAT_TIME) {
568         if (!gst_pad_peer_query (base->sinkpad, query)) {
569           GstClockTime dur;
570           if (gst_ts_demux_get_duration (demux, &dur))
571             gst_query_set_duration (query, GST_FORMAT_TIME, dur);
572           else
573             res = FALSE;
574         }
575       } else {
576         GST_DEBUG_OBJECT (demux, "only query duration on TIME is supported");
577         res = FALSE;
578       }
579       break;
580     }
581     case GST_QUERY_LATENCY:
582     {
583       GST_DEBUG ("query latency");
584       res = gst_pad_peer_query (base->sinkpad, query);
585       if (res) {
586         GstClockTime min_lat, max_lat;
587         gboolean live;
588         gint latency;
589
590         /* According to H.222.0
591            Annex D.0.3 (System Time Clock recovery in the decoder)
592            and D.0.2 (Audio and video presentation synchronization)
593
594            We can end up with an interval of up to 700ms between valid
595            PTS/DTS. We therefore allow a latency of 700ms for that.
596          */
597         latency = demux->latency;
598         if (latency < 0)
599           latency = 700;
600         gst_query_parse_latency (query, &live, &min_lat, &max_lat);
601         min_lat += latency * GST_MSECOND;
602         if (GST_CLOCK_TIME_IS_VALID (max_lat))
603           max_lat += latency * GST_MSECOND;
604         gst_query_set_latency (query, live, min_lat, max_lat);
605       }
606       break;
607     }
608     case GST_QUERY_SEEKING:
609     {
610       GST_DEBUG ("query seeking");
611       gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
612       GST_DEBUG ("asked for format %s", gst_format_get_name (format));
613       if (format == GST_FORMAT_TIME) {
614         gboolean seekable = FALSE;
615
616         if (gst_pad_peer_query (base->sinkpad, query))
617           gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
618
619         /* If upstream is not seekable in TIME format we use
620          * our own values here */
621         if (!seekable) {
622           GstClockTime dur;
623           if (gst_ts_demux_get_duration (demux, &dur)) {
624             gst_query_set_seeking (query, GST_FORMAT_TIME, TRUE, 0, dur);
625             GST_DEBUG ("Gave duration: %" GST_TIME_FORMAT, GST_TIME_ARGS (dur));
626           }
627         }
628       } else {
629         GST_DEBUG_OBJECT (demux, "only TIME is supported for query seeking");
630         res = FALSE;
631       }
632       break;
633     }
634     case GST_QUERY_SEGMENT:{
635       GstFormat format;
636       gint64 start, stop;
637
638       format = base->out_segment.format;
639
640       start =
641           gst_segment_to_stream_time (&base->out_segment, format,
642           base->out_segment.start);
643       if ((stop = base->out_segment.stop) == -1)
644         stop = base->out_segment.duration;
645       else
646         stop = gst_segment_to_stream_time (&base->out_segment, format, stop);
647
648       gst_query_set_segment (query, base->out_segment.rate, format, start,
649           stop);
650       res = TRUE;
651       break;
652     }
653     default:
654       res = gst_pad_query_default (pad, parent, query);
655   }
656
657   return res;
658
659 }
660
661 static void
662 clear_simple_buffer (SimpleBuffer * sbuf)
663 {
664   if (!sbuf->data)
665     return;
666
667   g_free (sbuf->data);
668   sbuf->size = 0;
669   sbuf->data = NULL;
670 }
671
672 static gboolean
673 scan_keyframe_h264 (TSDemuxStream * stream, const guint8 * data,
674     const gsize data_size, const gsize max_frame_offset)
675 {
676   gint offset = 0;
677   GstH264NalUnit unit, frame_unit = { 0, };
678   GstH264ParserResult res = GST_H264_PARSER_OK;
679   TSDemuxH264ParsingInfos *h264infos = &stream->h264infos;
680
681   GstH264NalParser *parser = h264infos->parser;
682
683   if (G_UNLIKELY (parser == NULL)) {
684     parser = h264infos->parser = gst_h264_nal_parser_new ();
685     h264infos->sps = gst_byte_writer_new ();
686     h264infos->pps = gst_byte_writer_new ();
687     h264infos->sei = gst_byte_writer_new ();
688   }
689
690   while (res == GST_H264_PARSER_OK) {
691     res =
692         gst_h264_parser_identify_nalu (parser, data, offset, data_size, &unit);
693
694     if (res != GST_H264_PARSER_OK && res != GST_H264_PARSER_NO_NAL_END) {
695       GST_INFO_OBJECT (stream->pad, "Error identifying nalu: %i", res);
696       break;
697     }
698
699     res = gst_h264_parser_parse_nal (parser, &unit);
700     if (res != GST_H264_PARSER_OK) {
701       break;
702     }
703
704     switch (unit.type) {
705       case GST_H264_NAL_SEI:
706         if (frame_unit.size)
707           break;
708
709         if (gst_byte_writer_put_data (h264infos->sei,
710                 unit.data + unit.sc_offset,
711                 unit.size + unit.offset - unit.sc_offset)) {
712           GST_DEBUG ("adding SEI %u", unit.size + unit.offset - unit.sc_offset);
713         } else {
714           GST_WARNING ("Could not write SEI");
715         }
716         break;
717       case GST_H264_NAL_PPS:
718         if (frame_unit.size)
719           break;
720
721         if (gst_byte_writer_put_data (h264infos->pps,
722                 unit.data + unit.sc_offset,
723                 unit.size + unit.offset - unit.sc_offset)) {
724           GST_DEBUG ("adding PPS %u", unit.size + unit.offset - unit.sc_offset);
725         } else {
726           GST_WARNING ("Could not write PPS");
727         }
728         break;
729       case GST_H264_NAL_SPS:
730         if (frame_unit.size)
731           break;
732
733         if (gst_byte_writer_put_data (h264infos->sps,
734                 unit.data + unit.sc_offset,
735                 unit.size + unit.offset - unit.sc_offset)) {
736           GST_DEBUG ("adding SPS %u", unit.size + unit.offset - unit.sc_offset);
737         } else {
738           GST_WARNING ("Could not write SPS");
739         }
740         break;
741         /* these units are considered keyframes in h264parse */
742       case GST_H264_NAL_SLICE:
743       case GST_H264_NAL_SLICE_DPA:
744       case GST_H264_NAL_SLICE_DPB:
745       case GST_H264_NAL_SLICE_DPC:
746       case GST_H264_NAL_SLICE_IDR:
747       {
748         GstH264SliceHdr slice;
749
750         if (h264infos->framedata.size)
751           break;
752
753         res = gst_h264_parser_parse_slice_hdr (parser, &unit, &slice,
754             FALSE, FALSE);
755
756         if (GST_H264_IS_I_SLICE (&slice) || GST_H264_IS_SI_SLICE (&slice)) {
757           if (*(unit.data + unit.offset + 1) & 0x80) {
758             /* means first_mb_in_slice == 0 */
759             /* real frame data */
760             GST_DEBUG_OBJECT (stream->pad, "Found keyframe at: %u",
761                 unit.sc_offset);
762             frame_unit = unit;
763           }
764         }
765
766         break;
767       }
768       default:
769         break;
770     }
771
772     if (offset == unit.sc_offset + unit.size)
773       break;
774
775     offset = unit.sc_offset + unit.size;
776   }
777
778   /* We've got all the infos we need (SPS / PPS and a keyframe, plus
779    * and possibly SEI units. We can stop rewinding the stream
780    */
781   if (gst_byte_writer_get_size (h264infos->sps) &&
782       gst_byte_writer_get_size (h264infos->pps) &&
783       (h264infos->framedata.size || frame_unit.size)) {
784     guint8 *data = NULL;
785
786     gsize tmpsize = gst_byte_writer_get_size (h264infos->pps);
787
788     /*  We know that the SPS is first so just put all our data in there */
789     data = gst_byte_writer_reset_and_get_data (h264infos->pps);
790     gst_byte_writer_put_data (h264infos->sps, data, tmpsize);
791     g_free (data);
792
793     tmpsize = gst_byte_writer_get_size (h264infos->sei);
794     if (tmpsize) {
795       GST_DEBUG ("Adding SEI");
796       data = gst_byte_writer_reset_and_get_data (h264infos->sei);
797       gst_byte_writer_put_data (h264infos->sps, data, tmpsize);
798       g_free (data);
799     }
800
801     if (frame_unit.size) {      /*  We found the everything in one go! */
802       GST_DEBUG ("Adding Keyframe");
803       gst_byte_writer_put_data (h264infos->sps,
804           frame_unit.data + frame_unit.sc_offset,
805           stream->current_size - frame_unit.sc_offset);
806     } else {
807       GST_DEBUG ("Adding Keyframe");
808       gst_byte_writer_put_data (h264infos->sps,
809           h264infos->framedata.data, h264infos->framedata.size);
810       clear_simple_buffer (&h264infos->framedata);
811     }
812
813     g_free (stream->data);
814     stream->current_size = gst_byte_writer_get_size (h264infos->sps);
815     stream->data = gst_byte_writer_reset_and_get_data (h264infos->sps);
816     gst_byte_writer_init (h264infos->sps);
817     gst_byte_writer_init (h264infos->pps);
818     gst_byte_writer_init (h264infos->sei);
819
820     return TRUE;
821   }
822
823   if (frame_unit.size) {
824     GST_DEBUG_OBJECT (stream->pad, "Keep the keyframe as this is the one"
825         " we will push later");
826
827     h264infos->framedata.data =
828         g_memdup2 (frame_unit.data + frame_unit.sc_offset,
829         stream->current_size - frame_unit.sc_offset);
830     h264infos->framedata.size = stream->current_size - frame_unit.sc_offset;
831   }
832
833   return FALSE;
834 }
835
836 /* We merge data from TS packets so that the scanning methods get a continuous chunk,
837  however the scanning method will return keyframe offset which needs to be translated
838  back to actual offset in file */
839 typedef struct
840 {
841   gint64 real_offset;           /* offset of TS packet */
842   gint merged_offset;           /* offset of merged data in buffer */
843 } OffsetInfo;
844
845 static gboolean
846 gst_ts_demux_adjust_seek_offset_for_keyframe (TSDemuxStream * stream,
847     guint8 * data, guint64 size)
848 {
849   int scan_pid = -1;
850
851   if (!stream->scan_function)
852     return TRUE;
853
854   scan_pid = ((MpegTSBaseStream *) stream)->pid;
855
856   if (scan_pid != -1) {
857     return stream->scan_function (stream, data, size, size);
858   }
859
860   return TRUE;
861 }
862
863 static GstFlowReturn
864 gst_ts_demux_do_seek (MpegTSBase * base, GstEvent * event)
865 {
866   GList *tmp;
867
868   GstTSDemux *demux = (GstTSDemux *) base;
869   GstFlowReturn res = GST_FLOW_ERROR;
870   gdouble rate;
871   GstFormat format;
872   GstSeekFlags flags;
873   GstSeekType start_type, stop_type;
874   gint64 start, stop;
875   guint64 start_offset;
876   gboolean update = FALSE;
877   GstSegment seeksegment;
878
879   GST_DEBUG ("seek event, %" GST_PTR_FORMAT, event);
880
881   gst_event_parse_seek (event, &rate, &format, &flags, &start_type, &start,
882       &stop_type, &stop);
883
884   if (rate <= 0.0) {
885     GST_WARNING ("Negative rate not supported");
886     goto done;
887   }
888
889   if (flags & (GST_SEEK_FLAG_SEGMENT)) {
890     GST_WARNING ("seek flags 0x%x are not supported", (int) flags);
891     goto done;
892   }
893
894   /* configure the segment with the seek variables */
895   memcpy (&seeksegment, &base->out_segment, sizeof (GstSegment));
896   GST_LOG_OBJECT (demux, "Before seek, output segment %" GST_SEGMENT_FORMAT,
897       &seeksegment);
898
899   /* record offset and rate */
900   demux->rate = rate;
901   if (!gst_segment_do_seek (&seeksegment, rate, format, flags, start_type,
902           start, stop_type, stop, &update)) {
903     GST_DEBUG_OBJECT (demux, "Seek failed in gst_segment_do_seek()");
904     goto done;
905   }
906
907   GST_DEBUG_OBJECT (demux,
908       "After seek, update %d output segment now %" GST_SEGMENT_FORMAT, update,
909       &seeksegment);
910
911   /* If the position actually changed, update == TRUE */
912   if (update) {
913     GstClockTime target = seeksegment.start;
914     if (target >= SEEK_TIMESTAMP_OFFSET)
915       target -= SEEK_TIMESTAMP_OFFSET;
916     else
917       target = 0;
918
919     start_offset =
920         mpegts_packetizer_ts_to_offset (base->packetizer, target,
921         demux->program->pcr_pid);
922     if (G_UNLIKELY (start_offset == -1)) {
923       GST_WARNING ("Couldn't convert start position to an offset");
924       goto done;
925     }
926
927     base->seek_offset = start_offset;
928     demux->last_seek_offset = base->seek_offset;
929     /* Reset segment if we're not doing an accurate seek */
930     demux->reset_segment = (!(flags & GST_SEEK_FLAG_ACCURATE));
931
932     /* Clear any existing segment - it will be recalculated after streaming recommences */
933     gst_event_replace (&demux->segment_event, NULL);
934
935     for (tmp = demux->program->stream_list; tmp; tmp = tmp->next) {
936       TSDemuxStream *stream = tmp->data;
937
938       if (flags & GST_SEEK_FLAG_ACCURATE)
939         stream->needs_keyframe = TRUE;
940
941       stream->seeked_pts = GST_CLOCK_TIME_NONE;
942       stream->seeked_dts = GST_CLOCK_TIME_NONE;
943       stream->first_pts = GST_CLOCK_TIME_NONE;
944       stream->need_newsegment = TRUE;
945     }
946   } else {
947     /* Position didn't change, just update the output segment based on
948      * our new one */
949     gst_event_replace (&demux->segment_event, NULL);
950     demux->segment_event = gst_event_new_segment (&seeksegment);
951     if (base->last_seek_seqnum)
952       gst_event_set_seqnum (demux->segment_event, base->last_seek_seqnum);
953     for (tmp = demux->program->stream_list; tmp; tmp = tmp->next) {
954       TSDemuxStream *stream = tmp->data;
955       stream->need_newsegment = TRUE;
956     }
957   }
958
959   /* Commit the new segment */
960   memcpy (&base->out_segment, &seeksegment, sizeof (GstSegment));
961   res = GST_FLOW_OK;
962
963 done:
964   return res;
965 }
966
967 static gboolean
968 gst_ts_demux_srcpad_event (GstPad * pad, GstObject * parent, GstEvent * event)
969 {
970   gboolean res = TRUE;
971   GstTSDemux *demux = GST_TS_DEMUX (parent);
972
973   GST_DEBUG_OBJECT (pad, "Got event %s",
974       gst_event_type_get_name (GST_EVENT_TYPE (event)));
975
976   switch (GST_EVENT_TYPE (event)) {
977     case GST_EVENT_SEEK:
978       res = mpegts_base_handle_seek_event ((MpegTSBase *) demux, pad, event);
979       if (!res)
980         GST_WARNING ("seeking failed");
981       gst_event_unref (event);
982       break;
983     default:
984       res = gst_pad_event_default (pad, parent, event);
985   }
986
987   return res;
988 }
989
990 static void
991 clean_global_taglist (GstTagList * taglist)
992 {
993   gst_tag_list_remove_tag (taglist, GST_TAG_CONTAINER_FORMAT);
994   gst_tag_list_remove_tag (taglist, GST_TAG_CODEC);
995 }
996
997 static gboolean
998 push_event (MpegTSBase * base, GstEvent * event)
999 {
1000   GstTSDemux *demux = (GstTSDemux *) base;
1001   GList *tmp;
1002   gboolean early_ret = FALSE;
1003
1004   if (GST_EVENT_TYPE (event) == GST_EVENT_SEGMENT) {
1005     GST_DEBUG_OBJECT (base, "Ignoring segment event (recreated later)");
1006     gst_event_unref (event);
1007     return TRUE;
1008
1009   } else if (GST_EVENT_TYPE (event) == GST_EVENT_TAG) {
1010     /* In case we receive tags before data, store them to send later
1011      * If we already have the program, send it right away */
1012     GstTagList *taglist;
1013
1014     gst_event_parse_tag (event, &taglist);
1015
1016     if (demux->global_tags == NULL) {
1017       demux->global_tags = gst_tag_list_copy (taglist);
1018
1019       /* Tags that are stream specific for the container should be considered
1020        * global for the container streams */
1021       if (gst_tag_list_get_scope (taglist) == GST_TAG_SCOPE_STREAM) {
1022         gst_tag_list_set_scope (demux->global_tags, GST_TAG_SCOPE_GLOBAL);
1023       }
1024     } else {
1025       demux->global_tags = gst_tag_list_make_writable (demux->global_tags);
1026       gst_tag_list_insert (demux->global_tags, taglist, GST_TAG_MERGE_REPLACE);
1027     }
1028     clean_global_taglist (demux->global_tags);
1029
1030     /* tags are stored to be used after if there are no streams yet,
1031      * so we should never reject */
1032     early_ret = TRUE;
1033   }
1034
1035   if (G_UNLIKELY (demux->program == NULL)) {
1036     gst_event_unref (event);
1037     return early_ret;
1038   }
1039
1040   for (tmp = demux->program->stream_list; tmp; tmp = tmp->next) {
1041     TSDemuxStream *stream = (TSDemuxStream *) tmp->data;
1042     if (stream->pad) {
1043       /* If we are pushing out EOS, flush out pending data first */
1044       if (GST_EVENT_TYPE (event) == GST_EVENT_EOS &&
1045           gst_pad_is_active (stream->pad))
1046         gst_ts_demux_push_pending_data (demux, stream, NULL);
1047
1048       gst_event_ref (event);
1049       gst_pad_push_event (stream->pad, event);
1050     }
1051   }
1052
1053   gst_event_unref (event);
1054
1055   return TRUE;
1056 }
1057
1058 static gboolean
1059 sink_query (MpegTSBase * base, GstQuery * query)
1060 {
1061   GstTSDemux *demux = (GstTSDemux *) base;
1062   gboolean res = FALSE;
1063
1064   switch (GST_QUERY_TYPE (query)) {
1065     case GST_QUERY_BITRATE:{
1066       gint64 size_bytes;
1067       GstClockTime duration;
1068
1069       if (gst_pad_peer_query_duration (base->sinkpad, GST_FORMAT_BYTES,
1070               &size_bytes) && size_bytes > 0) {
1071         if (gst_ts_demux_get_duration (demux, &duration) && duration > 0
1072             && duration != GST_CLOCK_TIME_NONE) {
1073           guint bitrate =
1074               gst_util_uint64_scale (8 * size_bytes, GST_SECOND, duration);
1075
1076           GST_LOG_OBJECT (demux, "bitrate query byte length: %" G_GINT64_FORMAT
1077               " duration %" GST_TIME_FORMAT " resulting in a bitrate of %u",
1078               size_bytes, GST_TIME_ARGS (duration), bitrate);
1079           gst_query_set_bitrate (query, bitrate);
1080           res = TRUE;
1081         }
1082       }
1083       break;
1084     }
1085     default:
1086       res = GST_MPEGTS_BASE_CLASS (parent_class)->sink_query (base, query);
1087       break;
1088   }
1089
1090   return res;
1091 }
1092
1093 static inline void
1094 add_iso639_language_to_tags (TSDemuxStream * stream, gchar * lang_code)
1095 {
1096   const gchar *lc;
1097
1098   GST_LOG ("Add language code for stream: '%s'", lang_code);
1099
1100   if (!stream->taglist)
1101     stream->taglist = gst_tag_list_new_empty ();
1102
1103   /* descriptor contains ISO 639-2 code, we want the ISO 639-1 code */
1104   lc = gst_tag_get_language_code (lang_code);
1105
1106   /* Only set tag if we have a valid one */
1107   if (lc || (lang_code[0] && lang_code[1]))
1108     gst_tag_list_add (stream->taglist, GST_TAG_MERGE_REPLACE,
1109         GST_TAG_LANGUAGE_CODE, (lc) ? lc : lang_code, NULL);
1110 }
1111
1112 static void
1113 gst_ts_demux_create_tags (TSDemuxStream * stream)
1114 {
1115   MpegTSBaseStream *bstream = (MpegTSBaseStream *) stream;
1116   const GstMpegtsDescriptor *desc = NULL;
1117   int i, nb;
1118
1119   desc =
1120       mpegts_get_descriptor_from_stream (bstream,
1121       GST_MTS_DESC_ISO_639_LANGUAGE);
1122   if (desc) {
1123     gchar *lang_code;
1124
1125     nb = gst_mpegts_descriptor_parse_iso_639_language_nb (desc);
1126
1127     GST_DEBUG ("Found ISO 639 descriptor (%d entries)", nb);
1128
1129     for (i = 0; i < nb; i++)
1130       if (gst_mpegts_descriptor_parse_iso_639_language_idx (desc, i, &lang_code,
1131               NULL)) {
1132         add_iso639_language_to_tags (stream, lang_code);
1133         g_free (lang_code);
1134       }
1135
1136     return;
1137   }
1138
1139   desc =
1140       mpegts_get_descriptor_from_stream (bstream, GST_MTS_DESC_DVB_SUBTITLING);
1141
1142   if (desc) {
1143     gchar *lang_code;
1144
1145     nb = gst_mpegts_descriptor_parse_dvb_subtitling_nb (desc);
1146
1147     GST_DEBUG ("Found SUBTITLING descriptor (%d entries)", nb);
1148
1149     for (i = 0; i < nb; i++)
1150       if (gst_mpegts_descriptor_parse_dvb_subtitling_idx (desc, i, &lang_code,
1151               NULL, NULL, NULL)) {
1152         add_iso639_language_to_tags (stream, lang_code);
1153         g_free (lang_code);
1154       }
1155   }
1156
1157   if (bstream->stream_type == GST_MPEGTS_STREAM_TYPE_PRIVATE_PES_PACKETS) {
1158     desc = mpegts_get_descriptor_from_stream_with_extension (bstream,
1159         GST_MTS_DESC_DVB_EXTENSION, GST_MTS_DESC_EXT_DVB_AUDIO_PRESELECTION);
1160
1161     if (desc) {
1162       GPtrArray *list;
1163       GstMpegtsAudioPreselectionDescriptor *item;
1164
1165       if (gst_mpegts_descriptor_parse_audio_preselection_list (desc, &list)) {
1166         GST_DEBUG ("Found AUDIO PRESELECTION descriptor (%d entries)",
1167             list->len);
1168
1169         for (i = 0; i < list->len; i++) {
1170           item = g_ptr_array_index (list, i);
1171           gst_mpegts_descriptor_parse_audio_preselection_dump (item);
1172
1173           if (item->language_code_present) {
1174             add_iso639_language_to_tags (stream, item->language_code);
1175             break;
1176           }
1177         }
1178         g_ptr_array_unref (list);
1179       }
1180     }
1181   }
1182 }
1183
1184 static GstPad *
1185 create_pad_for_stream (MpegTSBase * base, MpegTSBaseStream * bstream,
1186     MpegTSBaseProgram * program)
1187 {
1188   GstTSDemux *demux = GST_TS_DEMUX (base);
1189   TSDemuxStream *stream = (TSDemuxStream *) bstream;
1190   gchar *name = NULL;
1191   GstCaps *caps = NULL;
1192   GstPadTemplate *template = NULL;
1193   const GstMpegtsDescriptor *desc = NULL;
1194   GstPad *pad = NULL;
1195   gboolean sparse = FALSE;
1196   gboolean is_audio = FALSE, is_video = FALSE, is_subpicture = FALSE,
1197       is_private = FALSE;
1198
1199   gst_ts_demux_create_tags (stream);
1200
1201   GST_LOG ("Attempting to create pad for stream 0x%04x with stream_type %d",
1202       bstream->pid, bstream->stream_type);
1203
1204   /* First handle BluRay-specific stream types since there is some overlap
1205    * between BluRay and non-BluRay streay type identifiers */
1206   if (program->registration_id == DRF_ID_HDMV) {
1207     switch (bstream->stream_type) {
1208       case ST_BD_AUDIO_AC3:
1209       {
1210         const GstMpegtsDescriptor *ac3_desc;
1211
1212         /* ATSC ac3 audio descriptor */
1213         ac3_desc =
1214             mpegts_get_descriptor_from_stream (bstream,
1215             GST_MTS_DESC_AC3_AUDIO_STREAM);
1216         if (ac3_desc && DESC_AC_AUDIO_STREAM_bsid (ac3_desc->data) != 16) {
1217           GST_LOG ("ac3 audio");
1218           is_audio = TRUE;
1219           caps = gst_caps_new_empty_simple ("audio/x-ac3");
1220         } else {
1221           is_audio = TRUE;
1222           caps = gst_caps_new_empty_simple ("audio/x-eac3");
1223         }
1224         break;
1225       }
1226       case ST_BD_AUDIO_EAC3:
1227       case ST_BD_AUDIO_AC3_PLUS:
1228         is_audio = TRUE;
1229         caps = gst_caps_new_empty_simple ("audio/x-eac3");
1230         break;
1231       case ST_BD_AUDIO_AC4:
1232         /* Opus also uses 0x06, and there are bad streams that have HDMV registration ID,
1233          * but contain an Opus registration id, so check for it */
1234         if (bstream->registration_id != DRF_ID_OPUS) {
1235           is_audio = TRUE;
1236           caps = gst_caps_new_empty_simple ("audio/x-ac4");
1237         }
1238         break;
1239       case ST_BD_AUDIO_AC3_TRUE_HD:
1240         is_audio = TRUE;
1241         caps = gst_caps_new_empty_simple ("audio/x-true-hd");
1242         stream->target_pes_substream = 0x72;
1243         break;
1244       case ST_BD_AUDIO_LPCM:
1245         is_audio = TRUE;
1246         caps = gst_caps_new_empty_simple ("audio/x-private-ts-lpcm");
1247         break;
1248       case ST_BD_PGS_SUBPICTURE:
1249         is_subpicture = TRUE;
1250         caps = gst_caps_new_empty_simple ("subpicture/x-pgs");
1251         sparse = TRUE;
1252         break;
1253       case ST_BD_AUDIO_DTS_HD:
1254       case ST_BD_AUDIO_DTS_HD_MASTER_AUDIO:
1255         is_audio = TRUE;
1256         caps = gst_caps_new_empty_simple ("audio/x-dts");
1257         stream->target_pes_substream = 0x71;
1258         break;
1259     }
1260   }
1261
1262   if (caps)
1263     goto done;
1264
1265   /* Handle non-BluRay stream types */
1266   switch (bstream->stream_type) {
1267     case GST_MPEGTS_STREAM_TYPE_VIDEO_MPEG1:
1268     case GST_MPEGTS_STREAM_TYPE_VIDEO_MPEG2:
1269     case ST_PS_VIDEO_MPEG2_DCII:
1270       /* FIXME : Use DCII registration code (ETV1 ?) to handle that special
1271        * Stream type (ST_PS_VIDEO_MPEG2_DCII) */
1272       /* FIXME : Use video descriptor (0x1) to refine caps with:
1273        * * frame_rate
1274        * * profile_and_level
1275        */
1276       GST_LOG ("mpeg video");
1277       is_video = TRUE;
1278       caps = gst_caps_new_simple ("video/mpeg",
1279           "mpegversion", G_TYPE_INT,
1280           bstream->stream_type == GST_MPEGTS_STREAM_TYPE_VIDEO_MPEG1 ? 1 : 2,
1281           "systemstream", G_TYPE_BOOLEAN, FALSE, NULL);
1282
1283       break;
1284     case GST_MPEGTS_STREAM_TYPE_AUDIO_MPEG1:
1285     case GST_MPEGTS_STREAM_TYPE_AUDIO_MPEG2:
1286       GST_LOG ("mpeg audio");
1287       is_audio = TRUE;
1288       caps =
1289           gst_caps_new_simple ("audio/mpeg", "mpegversion", G_TYPE_INT, 1,
1290           NULL);
1291       /* HDV is always mpeg 1 audio layer 2 */
1292       if (program->registration_id == DRF_ID_TSHV)
1293         gst_caps_set_simple (caps, "layer", G_TYPE_INT, 2, NULL);
1294       break;
1295     case GST_MPEGTS_STREAM_TYPE_PRIVATE_PES_PACKETS:
1296       GST_LOG ("private data");
1297       /* FIXME: Move all of this into a common method (there might be other
1298        * types also, depending on registratino descriptors also
1299        */
1300
1301       desc = mpegts_get_descriptor_from_stream_with_extension (bstream,
1302           GST_MTS_DESC_DVB_EXTENSION, GST_MTS_DESC_EXT_DVB_AC4);
1303       if (desc) {
1304         GST_LOG ("ac4 audio");
1305         is_audio = TRUE;
1306         caps = gst_caps_new_empty_simple ("audio/x-ac4");
1307         break;
1308       }
1309
1310       desc = mpegts_get_descriptor_from_stream (bstream, GST_MTS_DESC_DVB_AC3);
1311       if (desc) {
1312         GST_LOG ("ac3 audio");
1313         is_audio = TRUE;
1314         caps = gst_caps_new_empty_simple ("audio/x-ac3");
1315         break;
1316       }
1317
1318       desc =
1319           mpegts_get_descriptor_from_stream (bstream,
1320           GST_MTS_DESC_DVB_ENHANCED_AC3);
1321       if (desc) {
1322         GST_LOG ("ac3 audio");
1323         is_audio = TRUE;
1324         caps = gst_caps_new_empty_simple ("audio/x-eac3");
1325         break;
1326       }
1327       desc =
1328           mpegts_get_descriptor_from_stream (bstream,
1329           GST_MTS_DESC_DVB_TELETEXT);
1330       if (desc) {
1331         GST_LOG ("teletext");
1332         is_private = TRUE;
1333         caps = gst_caps_new_empty_simple ("application/x-teletext");
1334         sparse = TRUE;
1335         break;
1336       }
1337       desc =
1338           mpegts_get_descriptor_from_stream (bstream,
1339           GST_MTS_DESC_DVB_SUBTITLING);
1340       if (desc) {
1341         GST_LOG ("subtitling");
1342         is_subpicture = TRUE;
1343         caps = gst_caps_new_empty_simple ("subpicture/x-dvb");
1344         sparse = TRUE;
1345         break;
1346       }
1347
1348       switch (bstream->registration_id) {
1349         case DRF_ID_DTS1:
1350         case DRF_ID_DTS2:
1351         case DRF_ID_DTS3:
1352           /* SMPTE registered DTS */
1353           is_private = TRUE;
1354           caps = gst_caps_new_empty_simple ("audio/x-dts");
1355           break;
1356         case DRF_ID_S302M:
1357           is_audio = TRUE;
1358           caps = gst_caps_new_empty_simple ("audio/x-smpte-302m");
1359           break;
1360         case DRF_ID_OPUS:
1361           desc = mpegts_get_descriptor_from_stream (bstream,
1362               GST_MTS_DESC_DVB_EXTENSION);
1363           if (desc != NULL && desc->tag_extension == 0x80 && desc->length >= 1) {       /* User defined (provisional Opus) */
1364             guint8 channel_config_code;
1365             GstByteReader br;
1366
1367             /* skip tag, length and tag_extension */
1368             gst_byte_reader_init (&br, desc->data + 3, desc->length - 1);
1369             channel_config_code = gst_byte_reader_get_uint8_unchecked (&br);
1370
1371             if ((channel_config_code & 0x8f) <= 8) {
1372               static const guint8 coupled_stream_counts[9] = {
1373                 1, 0, 1, 1, 2, 2, 2, 3, 3
1374               };
1375               static const guint8 channel_map_a[8][8] = {
1376                 {0},
1377                 {0, 1},
1378                 {0, 2, 1},
1379                 {0, 1, 2, 3},
1380                 {0, 4, 1, 2, 3},
1381                 {0, 4, 1, 2, 3, 5},
1382                 {0, 4, 1, 2, 3, 5, 6},
1383                 {0, 6, 1, 2, 3, 4, 5, 7},
1384               };
1385               static const guint8 channel_map_b[8][8] = {
1386                 {0},
1387                 {0, 1},
1388                 {0, 1, 2},
1389                 {0, 1, 2, 3},
1390                 {0, 1, 2, 3, 4},
1391                 {0, 1, 2, 3, 4, 5},
1392                 {0, 1, 2, 3, 4, 5, 6},
1393                 {0, 1, 2, 3, 4, 5, 6, 7},
1394               };
1395
1396               gint channels = -1, stream_count, coupled_count, mapping_family;
1397               guint8 *channel_mapping = NULL;
1398
1399               channels = channel_config_code ? (channel_config_code & 0x0f) : 2;
1400               if (channel_config_code == 0 || channel_config_code == 0x80) {
1401                 /* Dual Mono */
1402                 mapping_family = 255;
1403                 if (channel_config_code == 0) {
1404                   stream_count = 1;
1405                   coupled_count = 1;
1406                 } else {
1407                   stream_count = 2;
1408                   coupled_count = 0;
1409                 }
1410                 channel_mapping = g_new0 (guint8, channels);
1411                 memcpy (channel_mapping, &channel_map_a[1], channels);
1412               } else if (channel_config_code <= 8) {
1413                 mapping_family = (channels > 2) ? 1 : 0;
1414                 stream_count =
1415                     channel_config_code -
1416                     coupled_stream_counts[channel_config_code];
1417                 coupled_count = coupled_stream_counts[channel_config_code];
1418                 if (mapping_family != 0) {
1419                   channel_mapping = g_new0 (guint8, channels);
1420                   memcpy (channel_mapping, &channel_map_a[channels - 1],
1421                       channels);
1422                 }
1423               } else if (channel_config_code >= 0x82
1424                   && channel_config_code <= 0x88) {
1425                 mapping_family = 1;
1426                 stream_count = channels;
1427                 coupled_count = 0;
1428                 channel_mapping = g_new0 (guint8, channels);
1429                 memcpy (channel_mapping, &channel_map_b[channels - 1],
1430                     channels);
1431               } else if (channel_config_code == 0x81) {
1432                 if (gst_byte_reader_get_remaining (&br) < 2) {
1433                   GST_WARNING_OBJECT (demux,
1434                       "Invalid Opus descriptor with extended channel configuration");
1435                   channels = -1;
1436                   break;
1437                 }
1438
1439                 channels = gst_byte_reader_get_uint8_unchecked (&br);
1440                 mapping_family = gst_byte_reader_get_uint8_unchecked (&br);
1441
1442                 /* Overwrite values from above */
1443                 if (channels == 0) {
1444                   GST_WARNING_OBJECT (demux,
1445                       "Invalid Opus descriptor with extended channel configuration");
1446                   channels = -1;
1447                   break;
1448                 }
1449
1450                 if (mapping_family == 0 && channels <= 2) {
1451                   stream_count = channels - coupled_stream_counts[channels];
1452                   coupled_count = coupled_stream_counts[channels];
1453                 } else {
1454                   GstBitReader breader;
1455                   guint8 stream_count_minus_one, coupled_stream_count;
1456                   gint stream_count_minus_one_len, coupled_stream_count_len;
1457                   gint channel_mapping_len, i;
1458
1459                   gst_bit_reader_init (&breader,
1460                       gst_byte_reader_get_data_unchecked
1461                       (&br, gst_byte_reader_get_remaining
1462                           (&br)), gst_byte_reader_get_remaining (&br));
1463
1464                   stream_count_minus_one_len = ceil (_gst_log2 (channels));
1465                   if (!gst_bit_reader_get_bits_uint8 (&breader,
1466                           &stream_count_minus_one,
1467                           stream_count_minus_one_len)) {
1468                     GST_WARNING_OBJECT (demux,
1469                         "Invalid Opus descriptor with extended channel configuration");
1470                     channels = -1;
1471                     break;
1472                   }
1473
1474                   stream_count = stream_count_minus_one + 1;
1475                   coupled_stream_count_len =
1476                       ceil (_gst_log2 (stream_count_minus_one + 2));
1477
1478                   if (!gst_bit_reader_get_bits_uint8 (&breader,
1479                           &coupled_stream_count, coupled_stream_count_len)) {
1480                     GST_WARNING_OBJECT (demux,
1481                         "Invalid Opus descriptor with extended channel configuration");
1482                     channels = -1;
1483                     break;
1484                   }
1485
1486                   coupled_count = coupled_stream_count;
1487
1488                   channel_mapping_len =
1489                       ceil (_gst_log2 (stream_count_minus_one + 1 +
1490                           coupled_stream_count + 1));
1491                   channel_mapping = g_new0 (guint8, channels);
1492                   for (i = 0; i < channels; i++) {
1493                     if (!gst_bit_reader_get_bits_uint8 (&breader,
1494                             &channel_mapping[i], channel_mapping_len)) {
1495                       GST_WARNING_OBJECT (demux,
1496                           "Invalid Opus descriptor with extended channel configuration");
1497                       break;
1498                     }
1499                   }
1500
1501                   /* error above */
1502                   if (i != channels) {
1503                     channels = -1;
1504                     g_free (channel_mapping);
1505                     channel_mapping = NULL;
1506                     break;
1507                   }
1508                 }
1509               } else {
1510                 g_assert_not_reached ();
1511               }
1512
1513               if (channels != -1) {
1514                 is_audio = TRUE;
1515                 caps =
1516                     gst_codec_utils_opus_create_caps (48000, channels,
1517                     mapping_family, stream_count, coupled_count,
1518                     channel_mapping);
1519
1520                 g_free (channel_mapping);
1521               }
1522             } else {
1523               GST_WARNING_OBJECT (demux,
1524                   "unexpected channel config code 0x%02x", channel_config_code);
1525             }
1526           } else {
1527             GST_WARNING_OBJECT (demux, "Opus, but no extension descriptor");
1528           }
1529           break;
1530         case DRF_ID_HEVC:
1531           is_video = TRUE;
1532           caps = gst_caps_new_simple ("video/x-h265",
1533               "stream-format", G_TYPE_STRING, "byte-stream", NULL);
1534           break;
1535         case DRF_ID_KLVA:
1536           sparse = TRUE;
1537           is_private = TRUE;
1538           caps = gst_caps_new_simple ("meta/x-klv",
1539               "parsed", G_TYPE_BOOLEAN, TRUE, NULL);
1540           break;
1541         case DRF_ID_AC4:
1542           is_audio = TRUE;
1543           caps = gst_caps_new_empty_simple ("audio/x-ac4");
1544           break;
1545       }
1546       if (caps)
1547         break;
1548
1549       /* hack for itv hd (sid 10510, video pid 3401 */
1550       if (program->program_number == 10510 && bstream->pid == 3401) {
1551         is_video = TRUE;
1552         caps = gst_caps_new_simple ("video/x-h264",
1553             "stream-format", G_TYPE_STRING, "byte-stream", NULL);
1554       }
1555       break;
1556     case ST_HDV_AUX_V:
1557       /* FIXME : Should only be used with specific PMT registration_descriptor */
1558       /* We don't expose those streams since they're only helper streams */
1559       /* template = gst_static_pad_template_get (&private_template); */
1560       /* name = g_strdup_printf ("private_%04x", bstream->pid); */
1561       /* caps = gst_caps_new_simple ("hdv/aux-v", NULL); */
1562       break;
1563     case ST_HDV_AUX_A:
1564       /* FIXME : Should only be used with specific PMT registration_descriptor */
1565       /* We don't expose those streams since they're only helper streams */
1566       /* template = gst_static_pad_template_get (&private_template); */
1567       /* name = g_strdup_printf ("private_%04x", bstream->pid); */
1568       /* caps = gst_caps_new_simple ("hdv/aux-a", NULL); */
1569       break;
1570     case GST_MPEGTS_STREAM_TYPE_AUDIO_AAC_ADTS:
1571       is_audio = TRUE;
1572       /* prefer mpegversion 4 since it's more commonly supported one */
1573       caps = gst_caps_new_simple ("audio/mpeg",
1574           "mpegversion", G_TYPE_INT, 4,
1575           "stream-format", G_TYPE_STRING, "adts", NULL);
1576       /* we will set caps later once parsing adts header is done */
1577       stream->atdsInfos.mpegversion = 4;
1578       break;
1579     case GST_MPEGTS_STREAM_TYPE_AUDIO_AAC_LATM:
1580       is_audio = TRUE;
1581       caps = gst_caps_new_simple ("audio/mpeg",
1582           "mpegversion", G_TYPE_INT, 4,
1583           "stream-format", G_TYPE_STRING, "loas", NULL);
1584       break;
1585     case GST_MPEGTS_STREAM_TYPE_VIDEO_MPEG4:
1586       is_video = TRUE;
1587       caps = gst_caps_new_simple ("video/mpeg",
1588           "mpegversion", G_TYPE_INT, 4,
1589           "systemstream", G_TYPE_BOOLEAN, FALSE, NULL);
1590       break;
1591     case GST_MPEGTS_STREAM_TYPE_VIDEO_H264:
1592       is_video = TRUE;
1593       caps = gst_caps_new_simple ("video/x-h264",
1594           "stream-format", G_TYPE_STRING, "byte-stream", NULL);
1595       break;
1596     case GST_MPEGTS_STREAM_TYPE_VIDEO_HEVC:
1597       is_video = TRUE;
1598       caps = gst_caps_new_simple ("video/x-h265",
1599           "stream-format", G_TYPE_STRING, "byte-stream", NULL);
1600       break;
1601     case GST_MPEGTS_STREAM_TYPE_VIDEO_JP2K:
1602       is_video = TRUE;
1603       desc =
1604           mpegts_get_descriptor_from_stream (bstream, GST_MTS_DESC_J2K_VIDEO);
1605       if (desc == NULL) {
1606         caps = gst_caps_new_empty_simple ("image/x-jpc");
1607         break;
1608       } else {
1609         GstByteReader br;
1610         guint16 DEN_frame_rate = 0;
1611         guint16 NUM_frame_rate = 0;
1612         guint8 color_specification = 0;
1613         guint8 remaining_8b = 0;
1614         gboolean interlaced_video = 0;
1615         const gchar *interlace_mode = NULL;
1616         const gchar *colorspace = NULL;
1617         const gchar *colorimetry_mode = NULL;
1618         guint16 profile_and_level G_GNUC_UNUSED;
1619         guint32 horizontal_size G_GNUC_UNUSED;
1620         guint32 vertical_size G_GNUC_UNUSED;
1621         guint32 max_bit_rate G_GNUC_UNUSED;
1622         guint32 max_buffer_size G_GNUC_UNUSED;
1623         const guint desc_min_length = 24;
1624
1625         if (desc->length < desc_min_length) {
1626           GST_ERROR
1627               ("GST_MPEGTS_STREAM_TYPE_VIDEO_JP2K: descriptor length %d too short",
1628               desc->length);
1629           return NULL;
1630         }
1631
1632         /* Skip the descriptor tag and length */
1633         gst_byte_reader_init (&br, desc->data + 2, desc->length);
1634
1635         profile_and_level = gst_byte_reader_get_uint16_be_unchecked (&br);
1636         horizontal_size = gst_byte_reader_get_uint32_be_unchecked (&br);
1637         vertical_size = gst_byte_reader_get_uint32_be_unchecked (&br);
1638         max_bit_rate = gst_byte_reader_get_uint32_be_unchecked (&br);
1639         max_buffer_size = gst_byte_reader_get_uint32_be_unchecked (&br);
1640         DEN_frame_rate = gst_byte_reader_get_uint16_be_unchecked (&br);
1641         NUM_frame_rate = gst_byte_reader_get_uint16_be_unchecked (&br);
1642         color_specification = gst_byte_reader_get_uint8_unchecked (&br);
1643         remaining_8b = gst_byte_reader_get_uint8_unchecked (&br);
1644         interlaced_video = remaining_8b & 0x40;
1645         /* we don't support demuxing interlaced at the moment */
1646         if (interlaced_video) {
1647           GST_ERROR
1648               ("GST_MPEGTS_STREAM_TYPE_VIDEO_JP2K: interlaced video not supported");
1649           return NULL;
1650         } else {
1651           interlace_mode = "progressive";
1652           stream->jp2kInfos.interlace = FALSE;
1653         }
1654         switch (color_specification) {
1655           case GST_MPEGTSDEMUX_JPEG2000_COLORSPEC_SRGB:
1656             colorspace = "sRGB";
1657             colorimetry_mode = GST_VIDEO_COLORIMETRY_SRGB;
1658             break;
1659           case GST_MPEGTSDEMUX_JPEG2000_COLORSPEC_REC601:
1660             colorspace = "sYUV";
1661             colorimetry_mode = GST_VIDEO_COLORIMETRY_BT601;
1662             break;
1663           case GST_MPEGTSDEMUX_JPEG2000_COLORSPEC_REC709:
1664           case GST_MPEGTSDEMUX_JPEG2000_COLORSPEC_CIELUV:
1665             colorspace = "sYUV";
1666             colorimetry_mode = GST_VIDEO_COLORIMETRY_BT709;
1667             break;
1668           default:
1669             break;
1670         }
1671         caps = gst_caps_new_simple ("image/x-jpc",
1672             "framerate", GST_TYPE_FRACTION, NUM_frame_rate, DEN_frame_rate,
1673             "interlace-mode", G_TYPE_STRING, interlace_mode,
1674             "colorimetry", G_TYPE_STRING, colorimetry_mode,
1675             "colorspace", G_TYPE_STRING, colorspace, NULL);
1676       }
1677       break;
1678     case ST_VIDEO_DIRAC:
1679       if (bstream->registration_id == 0x64726163) {
1680         GST_LOG ("dirac");
1681         /* dirac in hex */
1682         is_video = TRUE;
1683         caps = gst_caps_new_empty_simple ("video/x-dirac");
1684       }
1685       break;
1686     case ST_PRIVATE_EA:        /* Try to detect a VC1 stream */
1687     {
1688       gboolean is_vc1 = FALSE;
1689
1690       /* Note/FIXME: RP-227 specifies that the registration descriptor
1691        * for vc1 can also contain other information, such as profile,
1692        * level, alignment, buffer_size, .... */
1693       if (bstream->registration_id == DRF_ID_VC1)
1694         is_vc1 = TRUE;
1695       if (!is_vc1) {
1696         GST_WARNING ("0xea private stream type found but no descriptor "
1697             "for VC1. Assuming plain VC1.");
1698       }
1699
1700       is_video = TRUE;
1701       caps = gst_caps_new_simple ("video/x-wmv",
1702           "wmvversion", G_TYPE_INT, 3, "format", G_TYPE_STRING, "WVC1", NULL);
1703
1704       break;
1705     }
1706     case ST_PS_AUDIO_AC3:
1707       /* DVB_ENHANCED_AC3 */
1708       desc =
1709           mpegts_get_descriptor_from_stream (bstream,
1710           GST_MTS_DESC_DVB_ENHANCED_AC3);
1711       if (desc) {
1712         is_audio = TRUE;
1713         caps = gst_caps_new_empty_simple ("audio/x-eac3");
1714         break;
1715       }
1716
1717       /* If stream has ac3 descriptor
1718        * OR program is ATSC (GA94)
1719        * OR stream registration is AC-3
1720        * then it's regular AC3 */
1721       if (bstream->registration_id == DRF_ID_AC3 ||
1722           program->registration_id == DRF_ID_GA94 ||
1723           mpegts_get_descriptor_from_stream (bstream, GST_MTS_DESC_DVB_AC3)) {
1724         is_audio = TRUE;
1725         caps = gst_caps_new_empty_simple ("audio/x-ac3");
1726         break;
1727       }
1728
1729       GST_WARNING ("AC3 stream type found but no guaranteed "
1730           "way found to differentiate between AC3 and EAC3. "
1731           "Assuming plain AC3.");
1732       is_audio = TRUE;
1733       caps = gst_caps_new_empty_simple ("audio/x-ac3");
1734       break;
1735     case ST_PS_AUDIO_EAC3:
1736     {
1737       /* ATSC_ENHANCED_AC3 */
1738       if (bstream->registration_id == DRF_ID_EAC3 ||
1739           mpegts_get_descriptor_from_stream (bstream, GST_MTS_DESC_ATSC_EAC3)) {
1740         is_audio = TRUE;
1741         caps = gst_caps_new_empty_simple ("audio/x-eac3");
1742         break;
1743       }
1744
1745       GST_ELEMENT_WARNING (demux, STREAM, DEMUX,
1746           ("Assuming ATSC E-AC3 audio stream."),
1747           ("ATSC E-AC3 stream type found but no guarantee way found to "
1748               "differentiate among other standards (DVB, ISDB and etc..)"));
1749
1750       is_audio = TRUE;
1751       caps = gst_caps_new_empty_simple ("audio/x-eac3");
1752       break;
1753     }
1754     case ST_PS_AUDIO_LPCM2:
1755       is_audio = TRUE;
1756       caps = gst_caps_new_empty_simple ("audio/x-private2-lpcm");
1757       break;
1758     case ST_PS_AUDIO_DTS:
1759       is_audio = TRUE;
1760       caps = gst_caps_new_empty_simple ("audio/x-dts");
1761       break;
1762     case ST_PS_AUDIO_LPCM:
1763       is_audio = TRUE;
1764       caps = gst_caps_new_empty_simple ("audio/x-lpcm");
1765       break;
1766     case ST_PS_DVD_SUBPICTURE:
1767       is_subpicture = TRUE;
1768       caps = gst_caps_new_empty_simple ("subpicture/x-dvd");
1769       sparse = TRUE;
1770       break;
1771     case 0x42:
1772       /* hack for Chinese AVS video stream which use 0x42 as stream_id
1773        * NOTE: this is unofficial and within the ISO reserved range. */
1774       is_video = TRUE;
1775       caps = gst_caps_new_empty_simple ("video/x-cavs");
1776       break;
1777     default:
1778       GST_DEBUG ("Non-media stream (stream_type:0x%x). Not creating pad",
1779           bstream->stream_type);
1780       break;
1781   }
1782
1783 done:
1784   if (caps) {
1785     if (is_audio) {
1786       template = gst_static_pad_template_get (&audio_template);
1787       name =
1788           g_strdup_printf ("audio_%01x_%04x", demux->program_generation,
1789           bstream->pid);
1790       gst_stream_set_stream_type (bstream->stream_object,
1791           GST_STREAM_TYPE_AUDIO);
1792     } else if (is_video) {
1793       template = gst_static_pad_template_get (&video_template);
1794       name =
1795           g_strdup_printf ("video_%01x_%04x", demux->program_generation,
1796           bstream->pid);
1797       gst_stream_set_stream_type (bstream->stream_object,
1798           GST_STREAM_TYPE_VIDEO);
1799     } else if (is_private) {
1800       template = gst_static_pad_template_get (&private_template);
1801       name =
1802           g_strdup_printf ("private_%01x_%04x", demux->program_generation,
1803           bstream->pid);
1804     } else if (is_subpicture) {
1805       template = gst_static_pad_template_get (&subpicture_template);
1806       name =
1807           g_strdup_printf ("subpicture_%01x_%04x", demux->program_generation,
1808           bstream->pid);
1809       gst_stream_set_stream_type (bstream->stream_object, GST_STREAM_TYPE_TEXT);
1810     } else
1811       g_assert_not_reached ();
1812
1813   }
1814
1815   if (template && name && caps) {
1816     GstEvent *event;
1817     const gchar *stream_id;
1818
1819     GST_LOG ("stream:%p creating pad with name %s and caps %" GST_PTR_FORMAT,
1820         stream, name, caps);
1821     pad = gst_pad_new_from_template (template, name);
1822     gst_pad_set_active (pad, TRUE);
1823     gst_pad_use_fixed_caps (pad);
1824     stream_id = gst_stream_get_stream_id (bstream->stream_object);
1825
1826     event = gst_pad_get_sticky_event (base->sinkpad, GST_EVENT_STREAM_START, 0);
1827     if (event) {
1828       if (gst_event_parse_group_id (event, &demux->group_id))
1829         demux->have_group_id = TRUE;
1830       else
1831         demux->have_group_id = FALSE;
1832       gst_event_unref (event);
1833     } else if (!demux->have_group_id) {
1834       demux->have_group_id = TRUE;
1835       demux->group_id = gst_util_group_id_next ();
1836     }
1837     event = gst_event_new_stream_start (stream_id);
1838     gst_event_set_stream (event, bstream->stream_object);
1839     if (demux->have_group_id)
1840       gst_event_set_group_id (event, demux->group_id);
1841     if (sparse) {
1842       gst_event_set_stream_flags (event, GST_STREAM_FLAG_SPARSE);
1843       gst_stream_set_stream_flags (bstream->stream_object,
1844           GST_STREAM_FLAG_SPARSE);
1845     }
1846     stream->sparse = sparse;
1847     gst_stream_set_caps (bstream->stream_object, caps);
1848     if (!stream->taglist)
1849       stream->taglist = gst_tag_list_new_empty ();
1850     gst_pb_utils_add_codec_description_to_tag_list (stream->taglist, NULL,
1851         caps);
1852     gst_stream_set_tags (bstream->stream_object, stream->taglist);
1853
1854     gst_pad_push_event (pad, event);
1855     gst_pad_set_caps (pad, caps);
1856     gst_pad_set_query_function (pad, gst_ts_demux_srcpad_query);
1857     gst_pad_set_event_function (pad, gst_ts_demux_srcpad_event);
1858   }
1859
1860   g_free (name);
1861   if (template)
1862     gst_object_unref (template);
1863   if (caps)
1864     gst_caps_unref (caps);
1865
1866   return pad;
1867 }
1868
1869 static gboolean
1870 gst_ts_demux_stream_added (MpegTSBase * base, MpegTSBaseStream * bstream,
1871     MpegTSBaseProgram * program)
1872 {
1873   GstTSDemux *demux = (GstTSDemux *) base;
1874   TSDemuxStream *stream = (TSDemuxStream *) bstream;
1875
1876   if (!stream->pad) {
1877     /* Create the pad */
1878     if (bstream->stream_type != 0xff) {
1879       stream->pad = create_pad_for_stream (base, bstream, program);
1880       if (stream->pad)
1881         gst_flow_combiner_add_pad (demux->flowcombiner, stream->pad);
1882     }
1883
1884     if (base->mode != BASE_MODE_PUSHING
1885         && bstream->stream_type == GST_MPEGTS_STREAM_TYPE_VIDEO_H264) {
1886       stream->scan_function =
1887           (GstTsDemuxKeyFrameScanFunction) scan_keyframe_h264;
1888     } else {
1889       stream->scan_function = NULL;
1890     }
1891
1892     stream->active = FALSE;
1893
1894     stream->need_newsegment = TRUE;
1895     /* Reset segment if we're not doing an accurate seek */
1896     demux->reset_segment =
1897         (!(base->out_segment.flags & GST_SEEK_FLAG_ACCURATE));
1898     stream->needs_keyframe = FALSE;
1899     stream->discont = TRUE;
1900     stream->pts = GST_CLOCK_TIME_NONE;
1901     stream->dts = GST_CLOCK_TIME_NONE;
1902     stream->first_pts = GST_CLOCK_TIME_NONE;
1903     stream->raw_pts = -1;
1904     stream->raw_dts = -1;
1905     stream->pending_ts = TRUE;
1906     stream->nb_out_buffers = 0;
1907     stream->gap_ref_buffers = 0;
1908     stream->gap_ref_pts = GST_CLOCK_TIME_NONE;
1909     /* Only wait for a valid timestamp if we have a PCR_PID */
1910     stream->pending_ts = program->pcr_pid < 0x1fff;
1911     stream->continuity_counter = CONTINUITY_UNSET;
1912   }
1913
1914   return (stream->pad != NULL);
1915 }
1916
1917 static void
1918 tsdemux_h264_parsing_info_clear (TSDemuxH264ParsingInfos * h264infos)
1919 {
1920   clear_simple_buffer (&h264infos->framedata);
1921
1922   if (h264infos->parser) {
1923     gst_h264_nal_parser_free (h264infos->parser);
1924     gst_byte_writer_free (h264infos->sps);
1925     gst_byte_writer_free (h264infos->pps);
1926     gst_byte_writer_free (h264infos->sei);
1927   }
1928 }
1929
1930 static void
1931 gst_ts_demux_stream_removed (MpegTSBase * base, MpegTSBaseStream * bstream)
1932 {
1933   TSDemuxStream *stream = (TSDemuxStream *) bstream;
1934
1935   if (stream->pad) {
1936     gst_flow_combiner_remove_pad (GST_TS_DEMUX_CAST (base)->flowcombiner,
1937         stream->pad);
1938     if (stream->active) {
1939
1940       if (gst_pad_is_active (stream->pad)) {
1941         /* Flush out all data */
1942         GST_DEBUG_OBJECT (stream->pad, "Flushing out pending data");
1943         gst_ts_demux_push_pending_data ((GstTSDemux *) base, stream, NULL);
1944
1945         GST_DEBUG_OBJECT (stream->pad, "Pushing out EOS");
1946         gst_pad_push_event (stream->pad, gst_event_new_eos ());
1947         gst_pad_set_active (stream->pad, FALSE);
1948       }
1949
1950       GST_DEBUG_OBJECT (stream->pad, "Removing pad");
1951       gst_element_remove_pad (GST_ELEMENT_CAST (base), stream->pad);
1952       stream->active = FALSE;
1953     } else {
1954       gst_object_unref (stream->pad);
1955     }
1956     stream->pad = NULL;
1957   }
1958
1959   gst_ts_demux_stream_flush (stream, GST_TS_DEMUX_CAST (base), TRUE);
1960
1961   if (stream->taglist != NULL) {
1962     gst_tag_list_unref (stream->taglist);
1963     stream->taglist = NULL;
1964   }
1965
1966   tsdemux_h264_parsing_info_clear (&stream->h264infos);
1967 }
1968
1969 static void
1970 activate_pad_for_stream (GstTSDemux * tsdemux, TSDemuxStream * stream)
1971 {
1972   if (stream->pad) {
1973     GST_DEBUG_OBJECT (tsdemux, "Activating pad %s:%s for stream %p",
1974         GST_DEBUG_PAD_NAME (stream->pad), stream);
1975     gst_element_add_pad ((GstElement *) tsdemux, stream->pad);
1976     stream->active = TRUE;
1977     GST_DEBUG_OBJECT (stream->pad, "done adding pad");
1978   } else if (((MpegTSBaseStream *) stream)->stream_type != 0xff) {
1979     GST_DEBUG_OBJECT (tsdemux,
1980         "stream %p (pid 0x%04x, type:0x%02x) has no pad", stream,
1981         ((MpegTSBaseStream *) stream)->pid,
1982         ((MpegTSBaseStream *) stream)->stream_type);
1983   }
1984 }
1985
1986 static void
1987 gst_ts_demux_stream_flush (TSDemuxStream * stream, GstTSDemux * tsdemux,
1988     gboolean hard)
1989 {
1990   GST_DEBUG ("flushing stream %p", stream);
1991
1992   g_free (stream->data);
1993   stream->data = NULL;
1994   stream->state = PENDING_PACKET_EMPTY;
1995   stream->expected_size = 0;
1996   stream->allocated_size = 0;
1997   stream->current_size = 0;
1998   stream->discont = TRUE;
1999   stream->pts = GST_CLOCK_TIME_NONE;
2000   stream->dts = GST_CLOCK_TIME_NONE;
2001   stream->raw_pts = -1;
2002   stream->raw_dts = -1;
2003   stream->pending_ts = TRUE;
2004   stream->nb_out_buffers = 0;
2005   stream->gap_ref_buffers = 0;
2006   stream->gap_ref_pts = GST_CLOCK_TIME_NONE;
2007   stream->continuity_counter = CONTINUITY_UNSET;
2008
2009   if (G_UNLIKELY (stream->pending)) {
2010     GList *tmp;
2011
2012     GST_DEBUG ("clearing pending %p", stream);
2013     for (tmp = stream->pending; tmp; tmp = tmp->next) {
2014       PendingBuffer *pend = (PendingBuffer *) tmp->data;
2015       gst_buffer_unref (pend->buffer);
2016       g_slice_free (PendingBuffer, pend);
2017     }
2018     g_list_free (stream->pending);
2019     stream->pending = NULL;
2020   }
2021
2022   if (hard) {
2023     stream->first_pts = GST_CLOCK_TIME_NONE;
2024     stream->need_newsegment = TRUE;
2025   }
2026 }
2027
2028 static void
2029 gst_ts_demux_flush_streams (GstTSDemux * demux, gboolean hard)
2030 {
2031   GList *walk;
2032   if (!demux->program)
2033     return;
2034
2035   for (walk = demux->program->stream_list; walk; walk = g_list_next (walk))
2036     gst_ts_demux_stream_flush (walk->data, demux, hard);
2037 }
2038
2039 static gboolean
2040 gst_ts_demux_can_remove_program (MpegTSBase * base, MpegTSBaseProgram * program)
2041 {
2042   GstTSDemux *demux = GST_TS_DEMUX (base);
2043
2044   /* If it's our current active program, we return FALSE, we'll deactivate it
2045    * ourselves when the next program gets activated */
2046   if (demux->program == program) {
2047     GST_DEBUG
2048         ("Attempting to remove current program, delaying until new program gets activated");
2049     demux->previous_program = program;
2050     demux->program_number = -1;
2051     return FALSE;
2052   }
2053   return TRUE;
2054 }
2055
2056 static void
2057 gst_ts_demux_update_program (MpegTSBase * base, MpegTSBaseProgram * program)
2058 {
2059   GstTSDemux *demux = GST_TS_DEMUX (base);
2060   GList *tmp;
2061
2062   GST_DEBUG ("Updating program %d", program->program_number);
2063   /* Emit collection message */
2064   gst_element_post_message ((GstElement *) base,
2065       gst_message_new_stream_collection ((GstObject *) base,
2066           program->collection));
2067
2068   /* Add all streams, then fire no-more-pads */
2069   for (tmp = program->stream_list; tmp; tmp = tmp->next) {
2070     TSDemuxStream *stream = (TSDemuxStream *) tmp->data;
2071     if (!stream->pad) {
2072       activate_pad_for_stream (demux, stream);
2073       if (stream->sparse) {
2074         /* force sending of pending sticky events which have been stored on the
2075          * pad already and which otherwise would only be sent on the first buffer
2076          * or serialized event (which means very late in case of subtitle streams),
2077          * and playsink waits for stream-start or another serialized event */
2078         GST_DEBUG_OBJECT (stream->pad, "sparse stream, pushing GAP event");
2079         gst_pad_push_event (stream->pad, gst_event_new_gap (0, 0));
2080       }
2081     }
2082   }
2083 }
2084
2085 static void
2086 gst_ts_demux_program_started (MpegTSBase * base, MpegTSBaseProgram * program)
2087 {
2088   GstTSDemux *demux = GST_TS_DEMUX (base);
2089
2090   GST_DEBUG ("Current program %d, new program %d requested program %d",
2091       (gint) demux->program_number, program->program_number,
2092       demux->requested_program_number);
2093
2094   if (demux->requested_program_number == program->program_number ||
2095       (demux->requested_program_number == -1 && demux->program_number == -1)) {
2096     GList *tmp;
2097     gboolean have_pads = FALSE;
2098
2099     GST_LOG ("program %d started", program->program_number);
2100     demux->program_number = program->program_number;
2101     demux->program = program;
2102
2103     /* Increment the program_generation counter */
2104     demux->program_generation = (demux->program_generation + 1) & 0xf;
2105
2106     /* Emit collection message */
2107     gst_element_post_message ((GstElement *) base,
2108         gst_message_new_stream_collection ((GstObject *) base,
2109             program->collection));
2110
2111     /* If this is not the initial program, we need to calculate
2112      * a new segment */
2113     if (demux->segment_event) {
2114       gst_event_unref (demux->segment_event);
2115       demux->segment_event = NULL;
2116     }
2117
2118     /* DRAIN ALL STREAMS FIRST ! */
2119     if (demux->previous_program) {
2120       GList *tmp;
2121       GST_DEBUG_OBJECT (demux, "Draining previous program");
2122       for (tmp = demux->previous_program->stream_list; tmp; tmp = tmp->next) {
2123         TSDemuxStream *stream = (TSDemuxStream *) tmp->data;
2124         if (stream->pad)
2125           gst_ts_demux_push_pending_data (demux, stream,
2126               demux->previous_program);
2127       }
2128     }
2129
2130     /* Add all streams, then fire no-more-pads */
2131     for (tmp = program->stream_list; tmp; tmp = tmp->next) {
2132       TSDemuxStream *stream = (TSDemuxStream *) tmp->data;
2133       activate_pad_for_stream (demux, stream);
2134       if (stream->pad)
2135         have_pads = TRUE;
2136     }
2137
2138     /* If there was a previous program, now is the time to deactivate it
2139      * and remove old pads (including pushing EOS) */
2140     if (demux->previous_program) {
2141       GST_DEBUG ("Deactivating previous program");
2142       mpegts_base_deactivate_and_free_program (base, demux->previous_program);
2143       demux->previous_program = NULL;
2144     }
2145
2146     if (!have_pads) {
2147       /* If we had no pads, this stream is likely corrupted or unsupported and
2148        * there's not much we can do at this point */
2149       GST_ELEMENT_ERROR (demux, STREAM, WRONG_TYPE,
2150           ("This stream contains no valid or supported streams."),
2151           ("activating program but got no pads"));
2152       return;
2153     }
2154
2155     /* If any of the stream is sparse, push a GAP event before anything else
2156      * This is done here, and not in activate_pad_for_stream() because pushing
2157      * a GAP event *is* considering data, and we want to ensure the (potential)
2158      * old pads are all removed before we push any data on the new ones */
2159     for (tmp = program->stream_list; tmp; tmp = tmp->next) {
2160       TSDemuxStream *stream = (TSDemuxStream *) tmp->data;
2161       if (stream->sparse) {
2162         /* force sending of pending sticky events which have been stored on the
2163          * pad already and which otherwise would only be sent on the first buffer
2164          * or serialized event (which means very late in case of subtitle streams),
2165          * and playsink waits for stream-start or another serialized event */
2166         GST_DEBUG_OBJECT (stream->pad, "sparse stream, pushing GAP event");
2167         gst_pad_push_event (stream->pad, gst_event_new_gap (0, 0));
2168       }
2169     }
2170
2171     gst_element_no_more_pads ((GstElement *) demux);
2172   }
2173 }
2174
2175 static void
2176 gst_ts_demux_program_stopped (MpegTSBase * base, MpegTSBaseProgram * program)
2177 {
2178   GstTSDemux *demux = GST_TS_DEMUX (base);
2179
2180   if (demux->program == program) {
2181     demux->program = NULL;
2182     demux->program_number = -1;
2183   }
2184 }
2185
2186
2187 static inline void
2188 gst_ts_demux_record_pts (GstTSDemux * demux, TSDemuxStream * stream,
2189     guint64 pts, guint64 offset)
2190 {
2191   MpegTSBaseStream *bs = (MpegTSBaseStream *) stream;
2192
2193   stream->raw_pts = pts;
2194   if (pts == -1) {
2195     stream->pts = GST_CLOCK_TIME_NONE;
2196     return;
2197   }
2198
2199   GST_LOG ("pid 0x%04x raw pts:%" G_GUINT64_FORMAT " at offset %"
2200       G_GUINT64_FORMAT, bs->pid, pts, offset);
2201
2202   /* Compute PTS in GstClockTime */
2203   stream->pts =
2204       mpegts_packetizer_pts_to_ts (MPEG_TS_BASE_PACKETIZER (demux),
2205       MPEGTIME_TO_GSTTIME (pts), demux->program->pcr_pid);
2206
2207   GST_LOG ("pid 0x%04x Stored PTS %" G_GUINT64_FORMAT, bs->pid, stream->pts);
2208
2209   if (G_UNLIKELY (demux->emit_statistics)) {
2210     GstStructure *st;
2211     st = gst_structure_new_id_empty (QUARK_TSDEMUX);
2212     gst_structure_id_set (st,
2213         QUARK_PID, G_TYPE_UINT, bs->pid,
2214         QUARK_OFFSET, G_TYPE_UINT64, offset, QUARK_PTS, G_TYPE_UINT64, pts,
2215         NULL);
2216     gst_element_post_message (GST_ELEMENT_CAST (demux),
2217         gst_message_new_element (GST_OBJECT (demux), st));
2218   }
2219 }
2220
2221 static inline void
2222 gst_ts_demux_record_dts (GstTSDemux * demux, TSDemuxStream * stream,
2223     guint64 dts, guint64 offset)
2224 {
2225   MpegTSBaseStream *bs = (MpegTSBaseStream *) stream;
2226
2227   stream->raw_dts = dts;
2228   if (dts == -1) {
2229     stream->dts = GST_CLOCK_TIME_NONE;
2230     return;
2231   }
2232
2233   GST_LOG ("pid 0x%04x raw dts:%" G_GUINT64_FORMAT " at offset %"
2234       G_GUINT64_FORMAT, bs->pid, dts, offset);
2235
2236   /* Compute DTS in GstClockTime */
2237   stream->dts =
2238       mpegts_packetizer_pts_to_ts (MPEG_TS_BASE_PACKETIZER (demux),
2239       MPEGTIME_TO_GSTTIME (dts), demux->program->pcr_pid);
2240
2241   GST_LOG ("pid 0x%04x Stored DTS %" G_GUINT64_FORMAT, bs->pid, stream->dts);
2242
2243   if (G_UNLIKELY (demux->emit_statistics)) {
2244     GstStructure *st;
2245     st = gst_structure_new_id_empty (QUARK_TSDEMUX);
2246     gst_structure_id_set (st,
2247         QUARK_PID, G_TYPE_UINT, bs->pid,
2248         QUARK_OFFSET, G_TYPE_UINT64, offset, QUARK_DTS, G_TYPE_UINT64, dts,
2249         NULL);
2250     gst_element_post_message (GST_ELEMENT_CAST (demux),
2251         gst_message_new_element (GST_OBJECT (demux), st));
2252   }
2253 }
2254
2255 /* This is called when we haven't got a valid initial PTS/DTS on all streams */
2256 static gboolean
2257 check_pending_buffers (GstTSDemux * demux)
2258 {
2259   gboolean have_observation = FALSE;
2260   /* The biggest offset */
2261   guint64 offset = 0;
2262   GList *tmp;
2263   gboolean have_only_sparse = TRUE;
2264   gboolean exceeded_threshold = FALSE;
2265
2266   /* 0. Do we only have sparse stream */
2267   for (tmp = demux->program->stream_list; tmp; tmp = tmp->next) {
2268     TSDemuxStream *tmpstream = (TSDemuxStream *) tmp->data;
2269
2270     if (!tmpstream->sparse) {
2271       have_only_sparse = FALSE;
2272       break;
2273     }
2274   }
2275
2276   /* 1. Go over all streams */
2277   for (tmp = demux->program->stream_list; tmp; tmp = tmp->next) {
2278     TSDemuxStream *tmpstream = (TSDemuxStream *) tmp->data;
2279     /* 1.1 check if at least one stream got a valid DTS */
2280     if (have_only_sparse || !tmpstream->sparse) {
2281       if ((tmpstream->raw_dts != -1 && tmpstream->dts != GST_CLOCK_TIME_NONE) ||
2282           (tmpstream->raw_pts != -1 && tmpstream->pts != GST_CLOCK_TIME_NONE)) {
2283         have_observation = TRUE;
2284         break;
2285       }
2286       /* 1.2 Check if we exceeded the maximum threshold of pending data */
2287       if (tmpstream->pending && (tmpstream->raw_dts != -1
2288               || tmpstream->raw_pts != -1)) {
2289         PendingBuffer *pend = tmpstream->pending->data;
2290         guint64 lastval =
2291             tmpstream->raw_dts != -1 ? tmpstream->raw_dts : tmpstream->raw_pts;
2292         guint64 firstval = pend->dts != -1 ? pend->dts : pend->pts;
2293         GstClockTime dur;
2294         g_assert (firstval != -1);
2295         dur = MPEGTIME_TO_GSTTIME (lastval - firstval);
2296         GST_DEBUG_OBJECT (tmpstream->pad,
2297             "Pending content duration: %" GST_TIME_FORMAT, GST_TIME_ARGS (dur));
2298         if (dur > 500 * GST_MSECOND) {
2299           exceeded_threshold = TRUE;
2300           break;
2301         }
2302       }
2303     }
2304   }
2305
2306   if (have_observation == FALSE) {
2307     /* 2. If we don't have a valid value yet, break out */
2308     if (!exceeded_threshold)
2309       return FALSE;
2310
2311     /* Except if we've exceed the maximum amount of pending buffers, in which
2312      * case we ignore PCR from now on */
2313     GST_DEBUG_OBJECT (demux,
2314         "Saw more than 500ms of data without PCR. Ignoring PCR from now on");
2315     GST_MPEGTS_BASE (demux)->ignore_pcr = TRUE;
2316     demux->program->pcr_pid = 0x1fff;
2317     g_object_notify (G_OBJECT (demux), "ignore-pcr");
2318   }
2319
2320   /* 3. Go over all streams that have current/pending data */
2321   for (tmp = demux->program->stream_list; tmp; tmp = tmp->next) {
2322     TSDemuxStream *tmpstream = (TSDemuxStream *) tmp->data;
2323     PendingBuffer *pend;
2324     guint64 firstval, lastval, ts;
2325
2326     /* 3.1 Calculate the offset between current DTS and first DTS */
2327     if (tmpstream->pending == NULL || tmpstream->state == PENDING_PACKET_EMPTY)
2328       continue;
2329     /* If we don't have any pending data, the offset is 0 for this stream */
2330     if (tmpstream->pending == NULL)
2331       break;
2332     if (tmpstream->raw_dts != -1)
2333       lastval = tmpstream->raw_dts;
2334     else if (tmpstream->raw_pts != -1)
2335       lastval = tmpstream->raw_pts;
2336     else {
2337       GST_WARNING ("Don't have a last DTS/PTS to use for offset recalculation");
2338       continue;
2339     }
2340     pend = tmpstream->pending->data;
2341     if (pend->dts != -1)
2342       firstval = pend->dts;
2343     else if (pend->pts != -1)
2344       firstval = pend->pts;
2345     else {
2346       GST_WARNING
2347           ("Don't have a first DTS/PTS to use for offset recalculation");
2348       continue;
2349     }
2350     /* 3.2 Add to the offset the report TS for the current DTS */
2351     ts = mpegts_packetizer_pts_to_ts (MPEG_TS_BASE_PACKETIZER (demux),
2352         MPEGTIME_TO_GSTTIME (lastval), demux->program->pcr_pid);
2353     if (ts == GST_CLOCK_TIME_NONE) {
2354       GST_WARNING ("THIS SHOULD NOT HAPPEN !");
2355       continue;
2356     }
2357     ts += MPEGTIME_TO_GSTTIME (lastval - firstval);
2358     /* 3.3 If that offset is bigger than the current offset, store it */
2359     if (ts > offset)
2360       offset = ts;
2361   }
2362
2363   GST_DEBUG ("New initial pcr_offset %" GST_TIME_FORMAT,
2364       GST_TIME_ARGS (offset));
2365
2366   /* 4. Set the offset on the packetizer */
2367   mpegts_packetizer_set_current_pcr_offset (MPEG_TS_BASE_PACKETIZER (demux),
2368       offset, demux->program->pcr_pid);
2369
2370   /* 4. Go over all streams */
2371   for (tmp = demux->program->stream_list; tmp; tmp = tmp->next) {
2372     TSDemuxStream *stream = (TSDemuxStream *) tmp->data;
2373
2374     stream->pending_ts = FALSE;
2375     /* 4.1 Set pending_ts for FALSE */
2376
2377     /* 4.2 Recalculate PTS/DTS (in running time) for pending data */
2378     if (stream->pending) {
2379       GList *tmp2;
2380       for (tmp2 = stream->pending; tmp2; tmp2 = tmp2->next) {
2381         PendingBuffer *pend = (PendingBuffer *) tmp2->data;
2382         if (pend->pts != -1)
2383           GST_BUFFER_PTS (pend->buffer) =
2384               mpegts_packetizer_pts_to_ts (MPEG_TS_BASE_PACKETIZER (demux),
2385               MPEGTIME_TO_GSTTIME (pend->pts), demux->program->pcr_pid);
2386         if (pend->dts != -1)
2387           GST_BUFFER_DTS (pend->buffer) =
2388               mpegts_packetizer_pts_to_ts (MPEG_TS_BASE_PACKETIZER (demux),
2389               MPEGTIME_TO_GSTTIME (pend->dts), demux->program->pcr_pid);
2390         /* 4.2.2 Set first_pts to TS of lowest PTS (for segment) */
2391         if (stream->first_pts == GST_CLOCK_TIME_NONE) {
2392           if (GST_BUFFER_PTS (pend->buffer) != GST_CLOCK_TIME_NONE)
2393             stream->first_pts = GST_BUFFER_PTS (pend->buffer);
2394           else if (GST_BUFFER_DTS (pend->buffer) != GST_CLOCK_TIME_NONE)
2395             stream->first_pts = GST_BUFFER_DTS (pend->buffer);
2396         }
2397       }
2398     }
2399     /* Recalculate PTS/DTS (in running time) for current data */
2400     if (stream->state != PENDING_PACKET_EMPTY) {
2401       if (stream->raw_pts != -1) {
2402         stream->pts =
2403             mpegts_packetizer_pts_to_ts (MPEG_TS_BASE_PACKETIZER (demux),
2404             MPEGTIME_TO_GSTTIME (stream->raw_pts), demux->program->pcr_pid);
2405         if (stream->first_pts == GST_CLOCK_TIME_NONE)
2406           stream->first_pts = stream->pts;
2407       }
2408       if (stream->raw_dts != -1) {
2409         stream->dts =
2410             mpegts_packetizer_pts_to_ts (MPEG_TS_BASE_PACKETIZER (demux),
2411             MPEGTIME_TO_GSTTIME (stream->raw_dts), demux->program->pcr_pid);
2412         if (stream->first_pts == GST_CLOCK_TIME_NONE)
2413           stream->first_pts = stream->dts;
2414       }
2415     }
2416   }
2417
2418   return TRUE;
2419 }
2420
2421 static void
2422 gst_ts_demux_parse_pes_header (GstTSDemux * demux, TSDemuxStream * stream,
2423     guint8 * data, guint32 length, guint64 bufferoffset)
2424 {
2425   PESHeader header;
2426   PESParsingResult parseres;
2427
2428   GST_MEMDUMP ("Header buffer", data, MIN (length, 32));
2429
2430   parseres = mpegts_parse_pes_header (data, length, &header);
2431   if (G_UNLIKELY (parseres == PES_PARSING_NEED_MORE))
2432     goto discont;
2433   if (G_UNLIKELY (parseres == PES_PARSING_BAD)) {
2434     GST_WARNING ("Error parsing PES header. pid: 0x%x stream_type: 0x%x",
2435         stream->stream.pid, stream->stream.stream_type);
2436     goto discont;
2437   }
2438
2439   if (stream->target_pes_substream != 0
2440       && header.stream_id_extension != stream->target_pes_substream) {
2441     GST_DEBUG ("Skipping unwanted substream");
2442     goto discont;
2443   }
2444
2445   gst_ts_demux_record_dts (demux, stream, header.DTS, bufferoffset);
2446   gst_ts_demux_record_pts (demux, stream, header.PTS, bufferoffset);
2447   if (G_UNLIKELY (stream->pending_ts &&
2448           (stream->pts != GST_CLOCK_TIME_NONE
2449               || stream->dts != GST_CLOCK_TIME_NONE))) {
2450     GST_DEBUG ("Got pts/dts update, rechecking all streams");
2451     check_pending_buffers (demux);
2452   } else if (stream->first_pts == GST_CLOCK_TIME_NONE) {
2453     if (GST_CLOCK_TIME_IS_VALID (stream->pts))
2454       stream->first_pts = stream->pts;
2455     else if (GST_CLOCK_TIME_IS_VALID (stream->dts))
2456       stream->first_pts = stream->dts;
2457   }
2458
2459   GST_DEBUG_OBJECT (demux,
2460       "stream PTS %" GST_TIME_FORMAT " DTS %" GST_TIME_FORMAT,
2461       GST_TIME_ARGS (stream->pts), GST_TIME_ARGS (stream->dts));
2462
2463   /* Remove PES headers */
2464   GST_DEBUG ("Moving data forward by %d bytes (packet_size:%d, have:%d)",
2465       header.header_size, header.packet_length, length);
2466   stream->expected_size = header.packet_length;
2467   if (stream->expected_size) {
2468     if (G_LIKELY (stream->expected_size > header.header_size)) {
2469       stream->expected_size -= header.header_size;
2470     } else {
2471       /* next packet will have to complete this one */
2472       GST_WARNING ("invalid header and packet size combination, empty packet");
2473       stream->expected_size = 0;
2474     }
2475   }
2476   data += header.header_size;
2477   length -= header.header_size;
2478
2479   /* Create the output buffer */
2480   if (stream->expected_size)
2481     stream->allocated_size = MAX (stream->expected_size, length);
2482   else
2483     stream->allocated_size = MAX (8192, length);
2484
2485   g_assert (stream->data == NULL);
2486   stream->data = g_malloc (stream->allocated_size);
2487   memcpy (stream->data, data, length);
2488   stream->current_size = length;
2489
2490   stream->state = PENDING_PACKET_BUFFER;
2491
2492   return;
2493
2494 discont:
2495   stream->state = PENDING_PACKET_DISCONT;
2496   return;
2497 }
2498
2499  /* ONLY CALL THIS:
2500   * * WITH packet->payload != NULL
2501   * * WITH pending/current flushed out if beginning of new PES packet
2502   */
2503 static inline void
2504 gst_ts_demux_queue_data (GstTSDemux * demux, TSDemuxStream * stream,
2505     MpegTSPacketizerPacket * packet)
2506 {
2507   guint8 *data;
2508   guint size;
2509   guint8 cc = FLAGS_CONTINUITY_COUNTER (packet->scram_afc_cc);
2510
2511   GST_LOG ("pid: 0x%04x state:%d", stream->stream.pid, stream->state);
2512
2513   size = packet->data_end - packet->payload;
2514   data = packet->payload;
2515
2516   if (stream->continuity_counter == CONTINUITY_UNSET) {
2517     GST_DEBUG ("CONTINUITY: Initialize to %d", cc);
2518   } else if ((cc == stream->continuity_counter + 1 ||
2519           (stream->continuity_counter == MAX_CONTINUITY && cc == 0))) {
2520     GST_LOG ("CONTINUITY: Got expected %d", cc);
2521   } else {
2522     if (stream->state != PENDING_PACKET_EMPTY) {
2523       if (packet->payload_unit_start_indicator) {
2524         /* A mismatch is fatal, except if this is the beginning of a new
2525          * frame (from which we can recover) */
2526         if (G_UNLIKELY (stream->data)) {
2527           g_free (stream->data);
2528           stream->data = NULL;
2529         }
2530         stream->state = PENDING_PACKET_HEADER;
2531       } else {
2532         GST_WARNING ("CONTINUITY: Mismatch packet %d, stream %d",
2533             cc, stream->continuity_counter);
2534         stream->state = PENDING_PACKET_DISCONT;
2535       }
2536     }
2537   }
2538   stream->continuity_counter = cc;
2539
2540   if (stream->state == PENDING_PACKET_EMPTY) {
2541     if (G_UNLIKELY (!packet->payload_unit_start_indicator)) {
2542       stream->state = PENDING_PACKET_DISCONT;
2543       GST_DEBUG ("Didn't get the first packet of this PES");
2544     } else {
2545       GST_LOG ("EMPTY=>HEADER");
2546       stream->state = PENDING_PACKET_HEADER;
2547     }
2548   }
2549
2550   switch (stream->state) {
2551     case PENDING_PACKET_HEADER:
2552     {
2553       GST_LOG ("HEADER: Parsing PES header");
2554
2555       /* parse the header */
2556       gst_ts_demux_parse_pes_header (demux, stream, data, size, packet->offset);
2557       break;
2558     }
2559     case PENDING_PACKET_BUFFER:
2560     {
2561       GST_LOG ("BUFFER: appending data");
2562       if (G_UNLIKELY (stream->current_size + size > stream->allocated_size)) {
2563         GST_LOG ("resizing buffer");
2564         do {
2565           stream->allocated_size = MAX (8192, 2 * stream->allocated_size);
2566         } while (stream->current_size + size > stream->allocated_size);
2567         stream->data = g_realloc (stream->data, stream->allocated_size);
2568       }
2569       memcpy (stream->data + stream->current_size, data, size);
2570       stream->current_size += size;
2571       break;
2572     }
2573     case PENDING_PACKET_DISCONT:
2574     {
2575       GST_LOG ("DISCONT: not storing/pushing");
2576       if (G_UNLIKELY (stream->data)) {
2577         g_free (stream->data);
2578         stream->data = NULL;
2579       }
2580       stream->continuity_counter = CONTINUITY_UNSET;
2581       break;
2582     }
2583     default:
2584       break;
2585   }
2586
2587   return;
2588 }
2589
2590 static void
2591 calculate_and_push_newsegment (GstTSDemux * demux, TSDemuxStream * stream,
2592     MpegTSBaseProgram * target_program)
2593 {
2594   MpegTSBase *base = (MpegTSBase *) demux;
2595   GstClockTime lowest_pts = GST_CLOCK_TIME_NONE;
2596   GstClockTime firstts = 0;
2597   GList *tmp;
2598
2599   GST_DEBUG ("Creating new newsegment for stream %p", stream);
2600
2601   if (target_program == NULL)
2602     target_program = demux->program;
2603
2604   /* Speedup : if we don't need to calculate anything, go straight to pushing */
2605   if (demux->segment_event)
2606     goto push_new_segment;
2607
2608   /* Calculate the 'new_start' value, used for newsegment */
2609   for (tmp = target_program->stream_list; tmp; tmp = tmp->next) {
2610     TSDemuxStream *pstream = (TSDemuxStream *) tmp->data;
2611
2612     if (GST_CLOCK_TIME_IS_VALID (pstream->first_pts)) {
2613       if (!GST_CLOCK_TIME_IS_VALID (lowest_pts)
2614           || pstream->first_pts < lowest_pts)
2615         lowest_pts = pstream->first_pts;
2616     }
2617   }
2618   if (GST_CLOCK_TIME_IS_VALID (lowest_pts))
2619     firstts = lowest_pts;
2620   GST_DEBUG ("lowest_pts %" G_GUINT64_FORMAT " => clocktime %" GST_TIME_FORMAT,
2621       lowest_pts, GST_TIME_ARGS (firstts));
2622
2623   if (base->out_segment.format != GST_FORMAT_TIME || demux->reset_segment) {
2624     /* It will happen only if it's first program or after flushes. */
2625     GST_DEBUG ("Calculating actual segment");
2626     if (base->segment.format == GST_FORMAT_TIME) {
2627       /* Try to recover segment info from base if it's in TIME format */
2628       base->out_segment = base->segment;
2629     } else {
2630       /* Start from the first ts/pts */
2631       GstSegment *seg = &base->out_segment;
2632       GstClockTime base =
2633           seg->base + seg->position - (seg->start + seg->offset);
2634       GstClockTime stop = seg->stop;
2635
2636       gst_segment_init (seg, GST_FORMAT_TIME);
2637       seg->start = firstts;
2638       seg->stop = MAX (seg->start, stop);
2639       seg->position = firstts;
2640       seg->time = firstts;
2641       seg->rate = demux->rate;
2642       seg->base = base;
2643     }
2644   } else if (base->out_segment.start < firstts) {
2645     /* Take into account the offset to the first buffer timestamp */
2646     if (base->out_segment.rate > 0) {
2647       if (GST_CLOCK_TIME_IS_VALID (base->out_segment.stop))
2648         base->out_segment.stop += firstts - base->out_segment.start;
2649       base->out_segment.start = firstts;
2650       base->out_segment.position = firstts;
2651     }
2652   }
2653
2654   GST_LOG_OBJECT (demux, "Output segment now %" GST_SEGMENT_FORMAT,
2655       &base->out_segment);
2656
2657   if (!demux->segment_event) {
2658     demux->segment_event = gst_event_new_segment (&base->out_segment);
2659
2660     if (base->last_seek_seqnum != GST_SEQNUM_INVALID)
2661       gst_event_set_seqnum (demux->segment_event, base->last_seek_seqnum);
2662   }
2663
2664 push_new_segment:
2665   for (tmp = target_program->stream_list; tmp; tmp = tmp->next) {
2666     stream = (TSDemuxStream *) tmp->data;
2667     if (stream->pad == NULL)
2668       continue;
2669
2670     if (demux->segment_event) {
2671       GST_DEBUG_OBJECT (stream->pad, "Pushing newsegment event");
2672
2673       gst_event_ref (demux->segment_event);
2674       gst_pad_push_event (stream->pad, demux->segment_event);
2675     }
2676
2677     if (demux->global_tags) {
2678       gst_pad_push_event (stream->pad,
2679           gst_event_new_tag (gst_tag_list_ref (demux->global_tags)));
2680     }
2681
2682     /* Push pending tags */
2683     if (stream->taglist) {
2684       GST_DEBUG_OBJECT (stream->pad, "Sending tags %" GST_PTR_FORMAT,
2685           stream->taglist);
2686       gst_pad_push_event (stream->pad, gst_event_new_tag (stream->taglist));
2687       stream->taglist = NULL;
2688     }
2689
2690     stream->need_newsegment = FALSE;
2691   }
2692 }
2693
2694 static void
2695 gst_ts_demux_check_and_sync_streams (GstTSDemux * demux, GstClockTime time)
2696 {
2697   GList *tmp;
2698
2699   GST_DEBUG_OBJECT (demux,
2700       "Recheck streams and sync to at least: %" GST_TIME_FORMAT,
2701       GST_TIME_ARGS (time));
2702
2703   if (G_UNLIKELY (demux->program == NULL))
2704     return;
2705
2706   /* Go over each stream and update it to at least 'time' time.
2707    * For each stream, the pad stores the buffer counter the last time
2708    * a gap check occurred (gap_ref_buffers) and a gap_ref_pts timestamp
2709    * that is either the PTS from the stream or the PCR the pad was updated
2710    * to.
2711    *
2712    * We can check nb_out_buffers to see if any buffers were pushed since then.
2713    * This means we can detect buffers passing without PTSes fine and still generate
2714    * gaps.
2715    *
2716    * If there haven't been any buffers pushed on this stream since the last
2717    * gap check, push a gap event updating to the indicated input PCR time
2718    * and update the pad's tracking.
2719    *
2720    * If there have been buffers pushed, update the reference buffer count
2721    * and but don't push a gap event
2722    */
2723   for (tmp = demux->program->stream_list; tmp; tmp = tmp->next) {
2724     TSDemuxStream *ps = (TSDemuxStream *) tmp->data;
2725     GST_DEBUG_OBJECT (ps->pad,
2726         "0x%04x, PTS:%" GST_TIME_FORMAT " REFPTS:%" GST_TIME_FORMAT " Gap:%"
2727         GST_TIME_FORMAT " nb_buffers: %d (ref:%d)",
2728         ((MpegTSBaseStream *) ps)->pid, GST_TIME_ARGS (ps->pts),
2729         GST_TIME_ARGS (ps->gap_ref_pts),
2730         GST_TIME_ARGS (ps->pts - ps->gap_ref_pts), ps->nb_out_buffers,
2731         ps->gap_ref_buffers);
2732     if (ps->pad == NULL)
2733       continue;
2734
2735     if (ps->nb_out_buffers == ps->gap_ref_buffers && ps->gap_ref_pts != ps->pts) {
2736       /* Do initial setup of pad if needed - segment etc */
2737       GST_DEBUG_OBJECT (ps->pad,
2738           "Stream needs update. Pushing GAP event to TS %" GST_TIME_FORMAT,
2739           GST_TIME_ARGS (time));
2740       if (G_UNLIKELY (ps->need_newsegment))
2741         calculate_and_push_newsegment (demux, ps, NULL);
2742
2743       /* Now send gap event */
2744       gst_pad_push_event (ps->pad, gst_event_new_gap (time, 0));
2745     }
2746
2747     /* Update GAP tracking vars so we don't re-check this stream for a while */
2748     ps->gap_ref_pts = time;
2749     if (ps->pts != GST_CLOCK_TIME_NONE && ps->pts > time)
2750       ps->gap_ref_pts = ps->pts;
2751     ps->gap_ref_buffers = ps->nb_out_buffers;
2752   }
2753 }
2754
2755 static GstBufferList *
2756 parse_opus_access_unit (TSDemuxStream * stream)
2757 {
2758   GstByteReader reader;
2759   GstBufferList *buffer_list = NULL;
2760
2761   buffer_list = gst_buffer_list_new ();
2762   gst_byte_reader_init (&reader, stream->data, stream->current_size);
2763
2764   do {
2765     GstBuffer *buffer;
2766     guint16 id;
2767     guint au_size = 0;
2768     guint8 b;
2769     gboolean start_trim_flag, end_trim_flag, control_extension_flag;
2770     guint16 start_trim = 0, end_trim = 0;
2771     guint8 *packet_data;
2772     guint packet_size;
2773
2774     if (!gst_byte_reader_get_uint16_be (&reader, &id))
2775       goto error;
2776
2777     /* No control header */
2778     if ((id >> 5) != 0x3ff)
2779       goto error;
2780
2781     do {
2782       if (!gst_byte_reader_get_uint8 (&reader, &b))
2783         goto error;
2784       au_size += b;
2785     } while (b == 0xff);
2786
2787     start_trim_flag = (id >> 4) & 0x1;
2788     end_trim_flag = (id >> 3) & 0x1;
2789     control_extension_flag = (id >> 2) & 0x1;
2790
2791     if (start_trim_flag) {
2792       if (!gst_byte_reader_get_uint16_be (&reader, &start_trim))
2793         goto error;
2794     }
2795
2796     if (end_trim_flag) {
2797       if (!gst_byte_reader_get_uint16_be (&reader, &end_trim))
2798         goto error;
2799     }
2800
2801     if (control_extension_flag) {
2802       if (!gst_byte_reader_get_uint8 (&reader, &b))
2803         goto error;
2804
2805       if (!gst_byte_reader_skip (&reader, b))
2806         goto error;
2807     }
2808
2809     packet_size = au_size;
2810
2811     /* FIXME: this should be
2812      *   packet_size = au_size - gst_byte_reader_get_pos (&reader);
2813      * but ffmpeg and the only available sample stream from obe.tv
2814      * are not including the control header size in au_size
2815      */
2816     if (gst_byte_reader_get_remaining (&reader) < packet_size)
2817       goto error;
2818     if (!gst_byte_reader_dup_data (&reader, packet_size, &packet_data))
2819       goto error;
2820
2821     buffer = gst_buffer_new_wrapped (packet_data, packet_size);
2822
2823     if (start_trim != 0 || end_trim != 0) {
2824       gst_buffer_add_audio_clipping_meta (buffer, GST_FORMAT_DEFAULT,
2825           start_trim, end_trim);
2826     }
2827
2828     gst_buffer_list_add (buffer_list, buffer);
2829   } while (gst_byte_reader_get_remaining (&reader) > 0);
2830
2831   g_free (stream->data);
2832   stream->data = NULL;
2833   stream->current_size = 0;
2834
2835   return buffer_list;
2836
2837 error:
2838   {
2839     GST_ERROR ("Failed to parse Opus access unit");
2840     g_free (stream->data);
2841     stream->data = NULL;
2842     stream->current_size = 0;
2843     if (buffer_list)
2844       gst_buffer_list_unref (buffer_list);
2845     return NULL;
2846   }
2847 }
2848
2849 /* interlaced mode is disabled at the moment */
2850 /*#define TSDEMUX_JP2K_SUPPORT_INTERLACE */
2851 static GstBuffer *
2852 parse_jp2k_access_unit (TSDemuxStream * stream)
2853 {
2854   GstByteReader reader;
2855   /* header tag */
2856   guint32 header_tag;
2857   /* Framerate box */
2858   guint16 den G_GNUC_UNUSED;
2859   guint16 num G_GNUC_UNUSED;
2860   /* Maximum bitrate box */
2861   guint32 MaxBr G_GNUC_UNUSED;
2862   guint32 AUF[2] = { 0, 0 };
2863 #ifdef TSDEMUX_JP2K_SUPPORT_INTERLACE
2864   /* Field Coding Box */
2865   guint8 Fic G_GNUC_UNUSED = 1;
2866   guint8 Fio G_GNUC_UNUSED = 0;
2867   /* header size equals 38 for non-interlaced, and 48 for interlaced */
2868   guint header_size = stream->jp2kInfos.interlace ? 48 : 38;
2869 #else
2870   /* header size equals 38 for non-interlaced, and 48 for interlaced */
2871   guint header_size = 38;
2872 #endif
2873   /* Time Code box */
2874   guint32 HHMMSSFF G_GNUC_UNUSED;
2875   /* Broadcast color box */
2876   guint8 CollC G_GNUC_UNUSED;
2877   guint8 b G_GNUC_UNUSED;
2878
2879   guint data_location;
2880   GstBuffer *retbuf = NULL;
2881
2882   if (stream->current_size < header_size) {
2883     GST_ERROR_OBJECT (stream->pad, "Not enough data for header");
2884     goto error;
2885   }
2886
2887   gst_byte_reader_init (&reader, stream->data, stream->current_size);
2888
2889   /* Check for the location of the jp2k magic */
2890   data_location =
2891       gst_byte_reader_masked_scan_uint32 (&reader, 0xffffffff, 0xff4fff51, 0,
2892       stream->current_size);
2893   GST_DEBUG_OBJECT (stream->pad, "data location %d", data_location);
2894   if (data_location == -1) {
2895     GST_ERROR_OBJECT (stream->pad, "Stream does not contain jp2k magic header");
2896     goto error;
2897   }
2898
2899   /* Elementary stream header box 'elsm' == 0x656c736d */
2900   header_tag = gst_byte_reader_get_uint32_be_unchecked (&reader);
2901   if (header_tag != 0x656c736d) {
2902     GST_ERROR_OBJECT (stream->pad, "Expected ELSM box but found box %x instead",
2903         header_tag);
2904     goto error;
2905   }
2906   /* Frame rate box 'frat' == 0x66726174 */
2907   header_tag = gst_byte_reader_get_uint32_be_unchecked (&reader);
2908   if (header_tag != 0x66726174) {
2909     GST_ERROR_OBJECT (stream->pad,
2910         "Expected frame rate box, but found box %x instead", header_tag);
2911     goto error;
2912
2913   }
2914   den = gst_byte_reader_get_uint16_be_unchecked (&reader);
2915   num = gst_byte_reader_get_uint16_be_unchecked (&reader);
2916   /* Maximum bit rate box 'brat' == 0x62726174 */
2917   header_tag = gst_byte_reader_get_uint32_be_unchecked (&reader);
2918   if (header_tag != 0x62726174) {
2919     GST_ERROR_OBJECT (stream->pad, "Expected brat box but read box %x instead",
2920         header_tag);
2921     goto error;
2922
2923   }
2924   MaxBr = gst_byte_reader_get_uint32_be_unchecked (&reader);
2925   AUF[0] = gst_byte_reader_get_uint32_be_unchecked (&reader);
2926   if (stream->jp2kInfos.interlace) {
2927 #ifdef TSDEMUX_JP2K_SUPPORT_INTERLACE
2928     AUF[1] = gst_byte_reader_get_uint32_be_unchecked (&reader);
2929     /*  Field Coding Box 'fiel' == 0x6669656c */
2930     header_tag = gst_byte_reader_get_uint32_be_unchecked (&reader);
2931     if (header_tag != 0x6669656c) {
2932       GST_ERROR_OBJECT (stream->pad,
2933           "Expected Field Coding box but found box %x instead", header_tag);
2934       goto error;
2935     }
2936     Fic = gst_byte_reader_get_uint8_unchecked (&reader);
2937     Fio = gst_byte_reader_get_uint8_unchecked (&reader);
2938 #else
2939     GST_ERROR_OBJECT (stream->pad, "interlaced mode not supported");
2940     goto error;
2941 #endif
2942   }
2943
2944   /* Time Code Box 'tcod' == 0x74636f64 */
2945   /* Some progressive streams might have a AUF[1] of value 0 present */
2946   header_tag = gst_byte_reader_get_uint32_be_unchecked (&reader);
2947   if (header_tag == 0 && !stream->jp2kInfos.interlace) {
2948     AUF[1] = header_tag;
2949     header_tag = gst_byte_reader_get_uint32_be_unchecked (&reader);
2950     /* Bump up header size and recheck */
2951     header_size += 4;
2952     if (stream->current_size < header_size) {
2953       GST_ERROR_OBJECT (stream->pad, "Not enough data for header");
2954       goto error;
2955     }
2956   }
2957   if (header_tag != 0x74636f64) {
2958     GST_ERROR_OBJECT (stream->pad,
2959         "Expected Time code box but found %d box instead", header_tag);
2960     goto error;
2961   }
2962   HHMMSSFF = gst_byte_reader_get_uint32_be_unchecked (&reader);
2963   /* Broadcast Color Box 'bcol' == 0x6263686c */
2964   header_tag = gst_byte_reader_get_uint32_be_unchecked (&reader);
2965   if (header_tag != 0x62636f6c) {
2966     GST_ERROR_OBJECT (stream->pad,
2967         "Expected Broadcast color box but found %x box instead", header_tag);
2968     goto error;
2969   }
2970   CollC = gst_byte_reader_get_uint8_unchecked (&reader);
2971   b = gst_byte_reader_get_uint8_unchecked (&reader);
2972
2973   /* Check if we have enough data to create a valid buffer */
2974   if ((stream->current_size - data_location) < (AUF[0] + AUF[1])) {
2975     GST_ERROR_OBJECT
2976         (stream->pad,
2977         "Required size (%d) greater than remaining size in buffer (%d)",
2978         AUF[0] + AUF[1], (stream->current_size - data_location));
2979     if (stream->expected_size && stream->current_size != stream->expected_size) {
2980       /* warn if buffer is truncated due to draining */
2981       GST_WARNING_OBJECT
2982           (stream->pad,
2983           "Truncated buffer: current size (%d) doesn't match expected size (%d)",
2984           stream->current_size, stream->expected_size);
2985     } else {
2986       /* kill pipeline if either we don't know what expected size is, or
2987        * we know the expected size, and thus are sure that the buffer is not
2988        *  truncated due to draining */
2989       goto error;
2990     }
2991   }
2992
2993   retbuf = gst_buffer_new_wrapped_full (0, stream->data, stream->current_size,
2994       data_location, stream->current_size - data_location,
2995       stream->data, g_free);
2996   stream->data = NULL;
2997   stream->current_size = 0;
2998   return retbuf;
2999
3000 error:
3001   GST_ERROR ("Failed to parse JP2K access unit");
3002   g_free (stream->data);
3003   stream->data = NULL;
3004   stream->current_size = 0;
3005   return NULL;
3006 }
3007
3008 static GstBuffer *
3009 parse_aac_adts_frame (TSDemuxStream * stream)
3010 {
3011   gint data_location = -1;
3012   guint frame_len;
3013   guint crc_size;
3014   guint mpegversion = 4;
3015   gint i;
3016
3017   if (stream->current_size < 6) {
3018     GST_DEBUG_OBJECT (stream->pad, "Not enough data for header");
3019     goto out;
3020   }
3021
3022   /* check syncword */
3023   for (i = 0; i < stream->current_size - 2; i++) {
3024     if ((stream->data[i] == 0xff) && ((stream->data[i + 1] & 0xf6) == 0xf0)) {
3025       data_location = i;
3026       break;
3027     }
3028   }
3029
3030   GST_TRACE_OBJECT (stream->pad, "data location %d", data_location);
3031
3032   if (data_location == -1) {
3033     GST_DEBUG_OBJECT (stream->pad, "Stream does not contain adts syncword");
3034     goto out;
3035   }
3036
3037   if (stream->current_size - data_location < 6) {
3038     GST_DEBUG_OBJECT (stream->pad, "Not enough data for header");
3039     goto out;
3040   }
3041
3042   frame_len = ((stream->data[data_location + 3] & 0x03) << 11) |
3043       (stream->data[data_location + 4] << 3) | ((stream->data[data_location +
3044               5] & 0xe0) >> 5);
3045
3046   crc_size = (stream->data[data_location + 1] & 0x01) ? 0 : 2;
3047
3048   if (frame_len < 7 + crc_size) {
3049     GST_DEBUG_OBJECT (stream->pad, "Invalid frame len %d", frame_len);
3050     goto out;
3051   }
3052
3053   /* this seems to be valid adts header, check mpeg version now
3054    *
3055    * TODO: check channels, rate, and profile and then update caps too?
3056    */
3057   mpegversion = (stream->data[data_location + 1] & 0x08) ? 2 : 4;
3058
3059 out:
3060   if (mpegversion != stream->atdsInfos.mpegversion) {
3061     GstCaps *caps;
3062     MpegTSBaseStream *bstream = (MpegTSBaseStream *) stream;
3063
3064     GST_DEBUG_OBJECT (stream->pad, "Update mpegversion from %d to %d",
3065         stream->atdsInfos.mpegversion, mpegversion);
3066     stream->atdsInfos.mpegversion = mpegversion;
3067
3068     caps = gst_stream_get_caps (bstream->stream_object);
3069     caps = gst_caps_make_writable (caps);
3070
3071     gst_caps_set_simple (caps, "mpegversion", G_TYPE_INT, mpegversion, NULL);
3072     gst_stream_set_caps (bstream->stream_object, caps);
3073     gst_pad_set_caps (stream->pad, caps);
3074     gst_caps_unref (caps);
3075   }
3076
3077   return gst_buffer_new_wrapped (stream->data, stream->current_size);
3078 }
3079
3080
3081 static GstFlowReturn
3082 gst_ts_demux_push_pending_data (GstTSDemux * demux, TSDemuxStream * stream,
3083     MpegTSBaseProgram * target_program)
3084 {
3085   MpegTSBase *base = GST_MPEGTS_BASE (demux);
3086   GstFlowReturn res = GST_FLOW_OK;
3087   MpegTSBaseStream *bs = (MpegTSBaseStream *) stream;
3088   GstBuffer *buffer = NULL;
3089   GstBufferList *buffer_list = NULL;
3090
3091
3092   GST_DEBUG_OBJECT (stream->pad,
3093       "stream:%p, pid:0x%04x stream_type:%d state:%d", stream, bs->pid,
3094       bs->stream_type, stream->state);
3095
3096   if (G_UNLIKELY (stream->data == NULL)) {
3097     GST_LOG ("stream->data == NULL");
3098     goto beach;
3099   }
3100
3101   if (G_UNLIKELY (stream->state == PENDING_PACKET_EMPTY)) {
3102     GST_LOG ("EMPTY: returning");
3103     goto beach;
3104   }
3105
3106   if (G_UNLIKELY (stream->state != PENDING_PACKET_BUFFER)) {
3107     GST_LOG ("state:%d, returning", stream->state);
3108     goto beach;
3109   }
3110
3111   if (G_UNLIKELY (demux->program == NULL)) {
3112     GST_LOG_OBJECT (demux, "No program");
3113     g_free (stream->data);
3114     goto beach;
3115   }
3116
3117   if (stream->needs_keyframe) {
3118     MpegTSBase *base = (MpegTSBase *) demux;
3119
3120     if ((gst_ts_demux_adjust_seek_offset_for_keyframe (stream, stream->data,
3121                 stream->current_size)) || demux->last_seek_offset == 0) {
3122       GST_DEBUG_OBJECT (stream->pad,
3123           "Got Keyframe, ready to go at %" GST_TIME_FORMAT,
3124           GST_TIME_ARGS (stream->pts));
3125
3126       if (bs->stream_type == GST_MPEGTS_STREAM_TYPE_PRIVATE_PES_PACKETS &&
3127           bs->registration_id == DRF_ID_OPUS) {
3128         buffer_list = parse_opus_access_unit (stream);
3129         if (!buffer_list) {
3130           res = GST_FLOW_ERROR;
3131           goto beach;
3132         }
3133
3134         if (gst_buffer_list_length (buffer_list) == 1) {
3135           buffer = gst_buffer_ref (gst_buffer_list_get (buffer_list, 0));
3136           gst_buffer_list_unref (buffer_list);
3137           buffer_list = NULL;
3138         }
3139       } else if (bs->stream_type == GST_MPEGTS_STREAM_TYPE_VIDEO_JP2K) {
3140         buffer = parse_jp2k_access_unit (stream);
3141         if (!buffer) {
3142           res = GST_FLOW_ERROR;
3143           goto beach;
3144         }
3145       } else {
3146         buffer = gst_buffer_new_wrapped (stream->data, stream->current_size);
3147       }
3148
3149       stream->seeked_pts = stream->pts;
3150       stream->seeked_dts = stream->dts;
3151       stream->needs_keyframe = FALSE;
3152     } else {
3153       GList *tmp;
3154       GST_DEBUG_OBJECT (stream->pad, "Rewinding after keyframe seek failure");
3155       base->seek_offset = demux->last_seek_offset - 200 * base->packetsize;
3156       if (demux->last_seek_offset < 200 * base->packetsize)
3157         base->seek_offset = 0;
3158       demux->last_seek_offset = base->seek_offset;
3159       mpegts_packetizer_flush (base->packetizer, FALSE);
3160
3161       /* Reset all streams accordingly */
3162       for (tmp = demux->program->stream_list; tmp; tmp = tmp->next) {
3163         TSDemuxStream *cand = tmp->data;
3164
3165         GST_DEBUG_OBJECT (cand->pad, "Clearing stream");
3166         cand->continuity_counter = CONTINUITY_UNSET;
3167         cand->state = PENDING_PACKET_EMPTY;
3168         if (cand->data)
3169           g_free (cand->data);
3170         cand->data = NULL;
3171         cand->allocated_size = 0;
3172         cand->current_size = 0;
3173       }
3174       base->mode = BASE_MODE_SEEKING;
3175
3176       res = GST_FLOW_REWINDING;
3177       goto beach;
3178     }
3179   } else {
3180     if (bs->stream_type == GST_MPEGTS_STREAM_TYPE_PRIVATE_PES_PACKETS &&
3181         bs->registration_id == DRF_ID_OPUS) {
3182       buffer_list = parse_opus_access_unit (stream);
3183       if (!buffer_list) {
3184         res = GST_FLOW_ERROR;
3185         goto beach;
3186       }
3187
3188       if (gst_buffer_list_length (buffer_list) == 1) {
3189         buffer = gst_buffer_ref (gst_buffer_list_get (buffer_list, 0));
3190         gst_buffer_list_unref (buffer_list);
3191         buffer_list = NULL;
3192       }
3193     } else if (bs->stream_type == GST_MPEGTS_STREAM_TYPE_VIDEO_JP2K) {
3194       buffer = parse_jp2k_access_unit (stream);
3195       if (!buffer) {
3196         res = GST_FLOW_ERROR;
3197         goto beach;
3198       }
3199     } else if (bs->stream_type == GST_MPEGTS_STREAM_TYPE_AUDIO_AAC_ADTS) {
3200       buffer = parse_aac_adts_frame (stream);
3201       if (!buffer) {
3202         res = GST_FLOW_ERROR;
3203         goto beach;
3204       }
3205     } else {
3206       buffer = gst_buffer_new_wrapped (stream->data, stream->current_size);
3207     }
3208
3209     if (G_UNLIKELY (stream->pending_ts && !check_pending_buffers (demux))) {
3210       if (buffer) {
3211         PendingBuffer *pend;
3212         pend = g_slice_new0 (PendingBuffer);
3213         pend->buffer = buffer;
3214         pend->pts = stream->raw_pts;
3215         pend->dts = stream->raw_dts;
3216         stream->pending = g_list_append (stream->pending, pend);
3217       } else {
3218         guint i, n;
3219
3220         n = gst_buffer_list_length (buffer_list);
3221         for (i = 0; i < n; i++) {
3222           PendingBuffer *pend;
3223           pend = g_slice_new0 (PendingBuffer);
3224           pend->buffer = gst_buffer_ref (gst_buffer_list_get (buffer_list, i));
3225           pend->pts = i == 0 ? stream->raw_pts : -1;
3226           pend->dts = i == 0 ? stream->raw_dts : -1;
3227           stream->pending = g_list_append (stream->pending, pend);
3228         }
3229         gst_buffer_list_unref (buffer_list);
3230       }
3231       GST_DEBUG ("Not enough information to push buffers yet, storing buffer");
3232       goto beach;
3233     }
3234   }
3235
3236   if (G_UNLIKELY (stream->need_newsegment))
3237     calculate_and_push_newsegment (demux, stream, target_program);
3238
3239   /* FIXME : Push pending buffers if any */
3240   if (G_UNLIKELY (stream->pending)) {
3241     GList *tmp;
3242     for (tmp = stream->pending; tmp; tmp = tmp->next) {
3243       PendingBuffer *pend = (PendingBuffer *) tmp->data;
3244
3245       GST_DEBUG_OBJECT (stream->pad,
3246           "Pushing pending buffer PTS:%" GST_TIME_FORMAT " DTS:%"
3247           GST_TIME_FORMAT, GST_TIME_ARGS (GST_BUFFER_PTS (pend->buffer)),
3248           GST_TIME_ARGS (GST_BUFFER_DTS (pend->buffer)));
3249
3250       if (stream->discont)
3251         GST_BUFFER_FLAG_SET (pend->buffer, GST_BUFFER_FLAG_DISCONT);
3252       stream->discont = FALSE;
3253
3254       res = gst_pad_push (stream->pad, pend->buffer);
3255       stream->nb_out_buffers += 1;
3256       g_slice_free (PendingBuffer, pend);
3257     }
3258     g_list_free (stream->pending);
3259     stream->pending = NULL;
3260   }
3261
3262   if ((GST_CLOCK_TIME_IS_VALID (stream->seeked_pts)
3263           && stream->pts < stream->seeked_pts) ||
3264       (GST_CLOCK_TIME_IS_VALID (stream->seeked_dts) &&
3265           stream->pts < stream->seeked_dts)) {
3266     GST_INFO_OBJECT (stream->pad,
3267         "Droping with PTS: %" GST_TIME_FORMAT " DTS: %" GST_TIME_FORMAT
3268         " after seeking as other stream needed to be seeked further"
3269         "(seeked PTS: %" GST_TIME_FORMAT " DTS: %" GST_TIME_FORMAT ")",
3270         GST_TIME_ARGS (stream->pts), GST_TIME_ARGS (stream->dts),
3271         GST_TIME_ARGS (stream->seeked_pts), GST_TIME_ARGS (stream->seeked_dts));
3272     if (buffer)
3273       gst_buffer_unref (buffer);
3274     if (buffer_list)
3275       gst_buffer_list_unref (buffer_list);
3276     goto beach;
3277   }
3278
3279   GST_DEBUG_OBJECT (stream->pad, "stream->pts %" GST_TIME_FORMAT,
3280       GST_TIME_ARGS (stream->pts));
3281
3282   /* Decorate buffer or first buffer of the buffer list */
3283   if (buffer_list)
3284     buffer = gst_buffer_list_get (buffer_list, 0);
3285
3286   if (GST_CLOCK_TIME_IS_VALID (stream->pts))
3287     GST_BUFFER_PTS (buffer) = GST_BUFFER_DTS (buffer) = stream->pts;
3288   /* DTS = PTS by default, we override it if there's a real DTS */
3289   if (GST_CLOCK_TIME_IS_VALID (stream->dts))
3290     GST_BUFFER_DTS (buffer) = stream->dts;
3291
3292   if (stream->discont)
3293     GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
3294   stream->discont = FALSE;
3295
3296   if (buffer_list)
3297     buffer = NULL;
3298
3299   GST_DEBUG_OBJECT (stream->pad,
3300       "Pushing buffer%s with PTS: %" GST_TIME_FORMAT " , DTS: %"
3301       GST_TIME_FORMAT, (buffer_list ? "list" : ""), GST_TIME_ARGS (stream->pts),
3302       GST_TIME_ARGS (stream->dts));
3303
3304   if (GST_CLOCK_TIME_IS_VALID (stream->dts)) {
3305     if (stream->dts > base->out_segment.position)
3306       base->out_segment.position = stream->dts;
3307   } else if (GST_CLOCK_TIME_IS_VALID (stream->pts)) {
3308     if (stream->pts > base->out_segment.position)
3309       base->out_segment.position = stream->pts;
3310   }
3311
3312   if (buffer) {
3313     res = gst_pad_push (stream->pad, buffer);
3314     /* Record that a buffer was pushed */
3315     stream->nb_out_buffers += 1;
3316   } else {
3317     guint n = gst_buffer_list_length (buffer_list);
3318     res = gst_pad_push_list (stream->pad, buffer_list);
3319     /* Record that a buffer was pushed */
3320     stream->nb_out_buffers += n;
3321   }
3322   GST_DEBUG_OBJECT (stream->pad, "Returned %s", gst_flow_get_name (res));
3323   res = gst_flow_combiner_update_flow (demux->flowcombiner, res);
3324   GST_DEBUG_OBJECT (stream->pad, "combined %s", gst_flow_get_name (res));
3325
3326   /* GAP / sparse stream tracking */
3327   if (G_UNLIKELY (stream->gap_ref_pts == GST_CLOCK_TIME_NONE))
3328     stream->gap_ref_pts = stream->pts;
3329   else {
3330     /* Look if the stream PTS has advanced 2 seconds since the last
3331      * gap check, and sync streams if it has. The first stream to
3332      * hit this will trigger a gap check */
3333     if (G_UNLIKELY (stream->pts != GST_CLOCK_TIME_NONE &&
3334             stream->pts > stream->gap_ref_pts + 2 * GST_SECOND)) {
3335       if (demux->program->pcr_pid != 0x1fff) {
3336         GstClockTime curpcr =
3337             mpegts_packetizer_get_current_time (MPEG_TS_BASE_PACKETIZER (demux),
3338             demux->program->pcr_pid);
3339         if (curpcr == GST_CLOCK_TIME_NONE || curpcr < 800 * GST_MSECOND)
3340           goto beach;
3341         curpcr -= 800 * GST_MSECOND;
3342         /* Use the current PCR (with a safety margin) to sync against */
3343         gst_ts_demux_check_and_sync_streams (demux, curpcr);
3344       } else {
3345         /* If we don't have a PCR track, just use the current stream PTS */
3346         gst_ts_demux_check_and_sync_streams (demux, stream->pts);
3347       }
3348     }
3349   }
3350
3351 beach:
3352   /* Reset the PES payload collection, but don't clear the state,
3353    * we might want to keep collecting this PES */
3354   GST_LOG ("Cleared PES data. returning %s", gst_flow_get_name (res));
3355   if (stream->expected_size) {
3356     if (stream->current_size > stream->expected_size)
3357       stream->expected_size = 0;
3358     else
3359       stream->expected_size -= stream->current_size;
3360   }
3361   stream->data = NULL;
3362   stream->allocated_size = 0;
3363   stream->current_size = 0;
3364
3365   return res;
3366 }
3367
3368 static GstFlowReturn
3369 gst_ts_demux_handle_packet (GstTSDemux * demux, TSDemuxStream * stream,
3370     MpegTSPacketizerPacket * packet, GstMpegtsSection * section)
3371 {
3372   GstFlowReturn res = GST_FLOW_OK;
3373
3374   GST_LOG ("pid 0x%04x pusi:%d, afc:%d, cont:%d, payload:%p", packet->pid,
3375       packet->payload_unit_start_indicator, packet->scram_afc_cc & 0x30,
3376       FLAGS_CONTINUITY_COUNTER (packet->scram_afc_cc), packet->payload);
3377
3378   if (G_UNLIKELY (packet->payload_unit_start_indicator) &&
3379       FLAGS_HAS_PAYLOAD (packet->scram_afc_cc)) {
3380     /* Flush previous data */
3381     res = gst_ts_demux_push_pending_data (demux, stream, NULL);
3382     if (res != GST_FLOW_REWINDING) {
3383       /* Tell the data collecting to expect this header. We don't do this when
3384        * rewinding since the states will have been resetted accordingly */
3385       stream->state = PENDING_PACKET_HEADER;
3386     }
3387   }
3388
3389   if (packet->payload && (res == GST_FLOW_OK || res == GST_FLOW_NOT_LINKED)
3390       && stream->pad) {
3391     gst_ts_demux_queue_data (demux, stream, packet);
3392     GST_LOG ("current_size:%d, expected_size:%d",
3393         stream->current_size, stream->expected_size);
3394     /* Finally check if the data we queued completes a packet, or got too
3395      * large and needs output now */
3396     if ((stream->expected_size && stream->current_size >= stream->expected_size)
3397         || (stream->current_size >= MAX_PES_PAYLOAD)) {
3398       GST_LOG ("pushing packet of size %u", stream->current_size);
3399       res = gst_ts_demux_push_pending_data (demux, stream, NULL);
3400     }
3401   }
3402
3403   /* We are rewinding to find a keyframe,
3404    * and didn't want the data to be queued
3405    */
3406   if (res == GST_FLOW_REWINDING)
3407     res = GST_FLOW_OK;
3408
3409   return res;
3410 }
3411
3412 static void
3413 gst_ts_demux_flush (MpegTSBase * base, gboolean hard)
3414 {
3415   GstTSDemux *demux = GST_TS_DEMUX_CAST (base);
3416
3417   gst_ts_demux_flush_streams (demux, hard);
3418
3419   if (demux->segment_event) {
3420     gst_event_unref (demux->segment_event);
3421     demux->segment_event = NULL;
3422   }
3423   if (demux->global_tags) {
3424     gst_tag_list_unref (demux->global_tags);
3425     demux->global_tags = NULL;
3426   }
3427   if (hard) {
3428     /* For pull mode seeks the current segment needs to be preserved */
3429     demux->rate = 1.0;
3430     gst_segment_init (&base->out_segment, GST_FORMAT_UNDEFINED);
3431   }
3432 }
3433
3434 static GstFlowReturn
3435 gst_ts_demux_drain (MpegTSBase * base)
3436 {
3437   GstTSDemux *demux = GST_TS_DEMUX_CAST (base);
3438   GList *tmp;
3439   GstFlowReturn res = GST_FLOW_OK;
3440
3441   if (!demux->program)
3442     return res;
3443
3444   for (tmp = demux->program->stream_list; tmp; tmp = tmp->next) {
3445     TSDemuxStream *stream = (TSDemuxStream *) tmp->data;
3446     if (stream->pad) {
3447       res = gst_ts_demux_push_pending_data (demux, stream, NULL);
3448       if (G_UNLIKELY (res != GST_FLOW_OK))
3449         break;
3450     }
3451   }
3452
3453   return res;
3454 }
3455
3456 static GstFlowReturn
3457 gst_ts_demux_push (MpegTSBase * base, MpegTSPacketizerPacket * packet,
3458     GstMpegtsSection * section)
3459 {
3460   GstTSDemux *demux = GST_TS_DEMUX_CAST (base);
3461   TSDemuxStream *stream = NULL;
3462   GstFlowReturn res = GST_FLOW_OK;
3463
3464   if (G_LIKELY (demux->program)) {
3465     stream = (TSDemuxStream *) demux->program->streams[packet->pid];
3466
3467     if (stream) {
3468       res = gst_ts_demux_handle_packet (demux, stream, packet, section);
3469     }
3470   }
3471   return res;
3472 }