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