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