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