tsbase: Handle more program updates
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / gst / mpegtsdemux / mpegtsbase.c
1 /*
2  * mpegtsbase.c -
3  * Copyright (C) 2007 Alessandro Decina
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  *   Alessandro Decina <alessandro@nnva.org>
12  *   Zaheer Abbas Merali <zaheerabbas at merali dot org>
13  *   Edward Hervey <edward.hervey@collabora.co.uk>
14  *
15  * This library is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU Library General Public
17  * License as published by the Free Software Foundation; either
18  * version 2 of the License, or (at your option) any later version.
19  *
20  * This library is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23  * Library General Public License for more details.
24  *
25  * You should have received a copy of the GNU Library General Public
26  * License along with this library; if not, write to the
27  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
28  * Boston, MA 02110-1301, USA.
29  */
30
31 #ifdef HAVE_CONFIG_H
32 #include "config.h"
33 #endif
34
35 #include <stdlib.h>
36 #include <string.h>
37
38 #include <glib.h>
39
40 #include <gst/gst-i18n-plugin.h>
41 #include "mpegtsbase.h"
42 #include "gstmpegdesc.h"
43
44 #define RUNNING_STATUS_RUNNING 4
45
46 GST_DEBUG_CATEGORY_STATIC (mpegts_base_debug);
47 #define GST_CAT_DEFAULT mpegts_base_debug
48
49 static GQuark QUARK_PROGRAMS;
50 static GQuark QUARK_PROGRAM_NUMBER;
51 static GQuark QUARK_PID;
52 static GQuark QUARK_PCR_PID;
53 static GQuark QUARK_STREAMS;
54 static GQuark QUARK_STREAM_TYPE;
55
56 static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
57     GST_PAD_SINK,
58     GST_PAD_ALWAYS,
59     GST_STATIC_CAPS ("video/mpegts, " "systemstream = (boolean) true ")
60     );
61
62 #define DEFAULT_IGNORE_PCR FALSE
63
64 enum
65 {
66   PROP_0,
67   PROP_PARSE_PRIVATE_SECTIONS,
68   PROP_IGNORE_PCR,
69   /* FILL ME */
70 };
71
72 static void mpegts_base_dispose (GObject * object);
73 static void mpegts_base_finalize (GObject * object);
74 static void mpegts_base_set_property (GObject * object, guint prop_id,
75     const GValue * value, GParamSpec * pspec);
76 static void mpegts_base_get_property (GObject * object, guint prop_id,
77     GValue * value, GParamSpec * pspec);
78
79 static void mpegts_base_free_program (MpegTSBaseProgram * program);
80 static void mpegts_base_deactivate_program (MpegTSBase * base,
81     MpegTSBaseProgram * program);
82 static gboolean mpegts_base_sink_activate (GstPad * pad, GstObject * parent);
83 static gboolean mpegts_base_sink_activate_mode (GstPad * pad,
84     GstObject * parent, GstPadMode mode, gboolean active);
85 static GstFlowReturn mpegts_base_chain (GstPad * pad, GstObject * parent,
86     GstBuffer * buf);
87 static gboolean mpegts_base_sink_event (GstPad * pad, GstObject * parent,
88     GstEvent * event);
89 static gboolean mpegts_base_sink_query (GstPad * pad, GstObject * parent,
90     GstQuery * query);
91 static gboolean mpegts_base_default_sink_query (MpegTSBase * base,
92     GstQuery * query);
93 static GstStateChangeReturn mpegts_base_change_state (GstElement * element,
94     GstStateChange transition);
95 static gboolean mpegts_base_get_tags_from_eit (MpegTSBase * base,
96     GstMpegtsSection * section);
97 static gboolean mpegts_base_parse_atsc_mgt (MpegTSBase * base,
98     GstMpegtsSection * section);
99 static void remove_each_program (MpegTSBaseProgram * program,
100     MpegTSBase * base);
101
102 static void
103 _extra_init (void)
104 {
105   QUARK_PROGRAMS = g_quark_from_string ("programs");
106   QUARK_PROGRAM_NUMBER = g_quark_from_string ("program-number");
107   QUARK_PID = g_quark_from_string ("pid");
108   QUARK_PCR_PID = g_quark_from_string ("pcr-pid");
109   QUARK_STREAMS = g_quark_from_string ("streams");
110   QUARK_STREAM_TYPE = g_quark_from_string ("stream-type");
111   GST_DEBUG_CATEGORY_INIT (mpegts_base_debug, "mpegtsbase", 0,
112       "MPEG transport stream base class");
113   gst_mpegts_initialize ();
114 }
115
116 #define mpegts_base_parent_class parent_class
117 G_DEFINE_TYPE_WITH_CODE (MpegTSBase, mpegts_base, GST_TYPE_ELEMENT,
118     _extra_init ());
119
120 /* Default implementation is that mpegtsbase can remove any program */
121 static gboolean
122 mpegts_base_can_remove_program (MpegTSBase * base, MpegTSBaseProgram * program)
123 {
124   return TRUE;
125 }
126
127 static void
128 mpegts_base_class_init (MpegTSBaseClass * klass)
129 {
130   GObjectClass *gobject_class;
131   GstElementClass *element_class;
132
133   klass->can_remove_program = mpegts_base_can_remove_program;
134
135   element_class = GST_ELEMENT_CLASS (klass);
136   element_class->change_state = mpegts_base_change_state;
137
138   gst_element_class_add_static_pad_template (element_class, &sink_template);
139
140   gobject_class = G_OBJECT_CLASS (klass);
141   gobject_class->dispose = mpegts_base_dispose;
142   gobject_class->finalize = mpegts_base_finalize;
143   gobject_class->set_property = mpegts_base_set_property;
144   gobject_class->get_property = mpegts_base_get_property;
145
146   g_object_class_install_property (gobject_class, PROP_PARSE_PRIVATE_SECTIONS,
147       g_param_spec_boolean ("parse-private-sections", "Parse private sections",
148           "Parse private sections", FALSE,
149           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
150
151   /**
152    * GstMpegtsBase:ignore-pcr:
153    *
154    * Ignore PCR (Program Clock Reference) data from MPEG-TS PSI.
155    * This can help with playback of some broken files.
156    *
157    * Since: 1.18
158    */
159   g_object_class_install_property (gobject_class, PROP_IGNORE_PCR,
160       g_param_spec_boolean ("ignore-pcr", "Ignore PCR stream for timing",
161           "Ignore PCR stream for timing", DEFAULT_IGNORE_PCR,
162           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
163
164   klass->sink_query = GST_DEBUG_FUNCPTR (mpegts_base_default_sink_query);
165   klass->handle_psi = NULL;
166
167   gst_type_mark_as_plugin_api (GST_TYPE_MPEGTS_BASE, 0);
168 }
169
170 static void
171 mpegts_base_set_property (GObject * object, guint prop_id,
172     const GValue * value, GParamSpec * pspec)
173 {
174   MpegTSBase *base = GST_MPEGTS_BASE (object);
175
176   switch (prop_id) {
177     case PROP_PARSE_PRIVATE_SECTIONS:
178       base->parse_private_sections = g_value_get_boolean (value);
179       break;
180     case PROP_IGNORE_PCR:
181       base->ignore_pcr = g_value_get_boolean (value);
182       break;
183     default:
184       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
185   }
186 }
187
188 static void
189 mpegts_base_get_property (GObject * object, guint prop_id,
190     GValue * value, GParamSpec * pspec)
191 {
192   MpegTSBase *base = GST_MPEGTS_BASE (object);
193
194   switch (prop_id) {
195     case PROP_PARSE_PRIVATE_SECTIONS:
196       g_value_set_boolean (value, base->parse_private_sections);
197       break;
198     case PROP_IGNORE_PCR:
199       g_value_set_boolean (value, base->ignore_pcr);
200       break;
201     default:
202       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
203   }
204 }
205
206
207 static void
208 mpegts_base_reset (MpegTSBase * base)
209 {
210   MpegTSBaseClass *klass = GST_MPEGTS_BASE_GET_CLASS (base);
211
212   mpegts_packetizer_clear (base->packetizer);
213   memset (base->is_pes, 0, 1024);
214   memset (base->known_psi, 0, 1024);
215
216   /* FIXME : Actually these are not *always* know SI streams
217    * depending on the variant of mpeg-ts being used. */
218
219   /* Known PIDs : PAT, TSDT, IPMP CIT */
220   MPEGTS_BIT_SET (base->known_psi, 0);
221   MPEGTS_BIT_SET (base->known_psi, 2);
222   MPEGTS_BIT_SET (base->known_psi, 3);
223   /* TDT, TOT, ST */
224   MPEGTS_BIT_SET (base->known_psi, 0x14);
225   /* network synchronization */
226   MPEGTS_BIT_SET (base->known_psi, 0x15);
227
228   /* ATSC */
229   MPEGTS_BIT_SET (base->known_psi, 0x1ffb);
230
231   if (base->pat) {
232     g_ptr_array_unref (base->pat);
233     base->pat = NULL;
234   }
235
236   gst_segment_init (&base->segment, GST_FORMAT_UNDEFINED);
237   gst_segment_init (&base->out_segment, GST_FORMAT_UNDEFINED);
238   base->last_seek_seqnum = GST_SEQNUM_INVALID;
239
240   base->mode = BASE_MODE_STREAMING;
241   base->seen_pat = FALSE;
242   base->seek_offset = -1;
243
244   g_ptr_array_foreach (base->programs, (GFunc) remove_each_program, base);
245   g_ptr_array_remove_range (base->programs, 0, base->programs->len);
246
247   base->streams_aware = GST_OBJECT_PARENT (base)
248       && GST_OBJECT_FLAG_IS_SET (GST_OBJECT_PARENT (base),
249       GST_BIN_FLAG_STREAMS_AWARE);
250   GST_DEBUG_OBJECT (base, "Streams aware : %d", base->streams_aware);
251
252   gst_event_replace (&base->seek_event, NULL);
253
254   if (klass->reset)
255     klass->reset (base);
256 }
257
258 static void
259 mpegts_base_init (MpegTSBase * base)
260 {
261   base->sinkpad = gst_pad_new_from_static_template (&sink_template, "sink");
262   gst_pad_set_activate_function (base->sinkpad, mpegts_base_sink_activate);
263   gst_pad_set_activatemode_function (base->sinkpad,
264       mpegts_base_sink_activate_mode);
265   gst_pad_set_chain_function (base->sinkpad, mpegts_base_chain);
266   gst_pad_set_event_function (base->sinkpad, mpegts_base_sink_event);
267   gst_pad_set_query_function (base->sinkpad, mpegts_base_sink_query);
268   gst_element_add_pad (GST_ELEMENT (base), base->sinkpad);
269
270   base->disposed = FALSE;
271   base->packetizer = mpegts_packetizer_new ();
272   base->programs =
273       g_ptr_array_new_full (16, (GDestroyNotify) mpegts_base_free_program);
274
275   base->parse_private_sections = FALSE;
276   base->is_pes = g_new0 (guint8, 1024);
277   base->known_psi = g_new0 (guint8, 1024);
278   base->program_size = sizeof (MpegTSBaseProgram);
279   base->stream_size = sizeof (MpegTSBaseStream);
280
281   base->push_data = TRUE;
282   base->push_section = TRUE;
283   base->ignore_pcr = DEFAULT_IGNORE_PCR;
284
285   mpegts_base_reset (base);
286 }
287
288 static void
289 mpegts_base_dispose (GObject * object)
290 {
291   MpegTSBase *base = GST_MPEGTS_BASE (object);
292
293   if (!base->disposed) {
294     g_object_unref (base->packetizer);
295     base->disposed = TRUE;
296     g_free (base->known_psi);
297     g_free (base->is_pes);
298   }
299
300   if (G_OBJECT_CLASS (parent_class)->dispose)
301     G_OBJECT_CLASS (parent_class)->dispose (object);
302 }
303
304 static void
305 mpegts_base_finalize (GObject * object)
306 {
307   MpegTSBase *base = GST_MPEGTS_BASE (object);
308
309   if (base->pat) {
310     g_ptr_array_unref (base->pat);
311     base->pat = NULL;
312   }
313   g_ptr_array_free (base->programs, TRUE);
314
315   gst_event_replace (&base->seek_event, NULL);
316
317   if (G_OBJECT_CLASS (parent_class)->finalize)
318     G_OBJECT_CLASS (parent_class)->finalize (object);
319 }
320
321
322 /* returns NULL if no matching descriptor found *
323  * otherwise returns a descriptor that needs to *
324  * be freed */
325 const GstMpegtsDescriptor *
326 mpegts_get_descriptor_from_stream (MpegTSBaseStream * stream, guint8 tag)
327 {
328   GstMpegtsPMTStream *pmt = stream->stream;
329
330   GST_DEBUG ("Searching for tag 0x%02x in stream 0x%04x (stream_type 0x%02x)",
331       tag, stream->pid, stream->stream_type);
332
333   return gst_mpegts_find_descriptor (pmt->descriptors, tag);
334 }
335
336 const GstMpegtsDescriptor *
337 mpegts_get_descriptor_from_stream_with_extension (MpegTSBaseStream * stream,
338     guint8 tag, guint8 tag_extension)
339 {
340   GstMpegtsPMTStream *pmt = stream->stream;
341
342   GST_DEBUG ("Searching for tag 0x%02x tag_extension 0x%02x "
343       "in stream 0x%04x (stream_type 0x%02x)",
344       tag, tag_extension, stream->pid, stream->stream_type);
345
346   return gst_mpegts_find_descriptor_with_extension (pmt->descriptors, tag,
347       tag_extension);
348 }
349
350 typedef struct
351 {
352   gboolean res;
353   guint16 pid;
354 } PIDLookup;
355
356 static void
357 foreach_pid_in_program (MpegTSBaseProgram * program, PIDLookup * lookup)
358 {
359   if (!program->active)
360     return;
361   if (program->streams[lookup->pid])
362     lookup->res = TRUE;
363 }
364
365 static gboolean
366 mpegts_pid_in_active_programs (MpegTSBase * base, guint16 pid)
367 {
368   PIDLookup lookup;
369
370   lookup.res = FALSE;
371   lookup.pid = pid;
372   g_ptr_array_foreach (base->programs, (GFunc) foreach_pid_in_program, &lookup);
373
374   return lookup.res;
375 }
376
377 /* returns NULL if no matching descriptor found *
378  * otherwise returns a descriptor that needs to *
379  * be freed */
380 const GstMpegtsDescriptor *
381 mpegts_get_descriptor_from_program (MpegTSBaseProgram * program, guint8 tag)
382 {
383   const GstMpegtsPMT *pmt = program->pmt;
384
385   return gst_mpegts_find_descriptor (pmt->descriptors, tag);
386 }
387
388 static gchar *
389 _get_upstream_id (GstElement * element, GstPad * sinkpad)
390 {
391   gchar *upstream_id = gst_pad_get_stream_id (sinkpad);
392
393   if (!upstream_id) {
394     /* Try to create one from the upstream URI, else use a randome number */
395     GstQuery *query;
396     gchar *uri = NULL;
397
398     /* Try to generate one from the URI query and
399      * if it fails take a random number instead */
400     query = gst_query_new_uri ();
401     if (gst_element_query (element, query)) {
402       gst_query_parse_uri (query, &uri);
403     }
404
405     if (uri) {
406       GChecksum *cs;
407
408       /* And then generate an SHA256 sum of the URI */
409       cs = g_checksum_new (G_CHECKSUM_SHA256);
410       g_checksum_update (cs, (const guchar *) uri, strlen (uri));
411       g_free (uri);
412       upstream_id = g_strdup (g_checksum_get_string (cs));
413       g_checksum_free (cs);
414     } else {
415       /* Just get some random number if the URI query fails */
416       GST_FIXME_OBJECT (element, "Creating random stream-id, consider "
417           "implementing a deterministic way of creating a stream-id");
418       upstream_id =
419           g_strdup_printf ("%08x%08x%08x%08x", g_random_int (), g_random_int (),
420           g_random_int (), g_random_int ());
421     }
422
423     gst_query_unref (query);
424   }
425   return upstream_id;
426 }
427
428 static MpegTSBaseProgram *
429 mpegts_base_new_program (MpegTSBase * base,
430     gint program_number, guint16 pmt_pid)
431 {
432   MpegTSBaseProgram *program;
433   gchar *upstream_id, *stream_id;
434
435   GST_DEBUG_OBJECT (base, "program_number : %d, pmt_pid : 0x%04x",
436       program_number, pmt_pid);
437
438   program = g_malloc0 (base->program_size);
439   program->program_number = program_number;
440   program->pmt_pid = pmt_pid;
441   program->pcr_pid = G_MAXUINT16;
442   program->streams = g_new0 (MpegTSBaseStream *, 0x2000);
443   program->patcount = 0;
444
445   upstream_id = _get_upstream_id ((GstElement *) base, base->sinkpad);
446   stream_id = g_strdup_printf ("%s:%d", upstream_id, program_number);
447   program->collection = gst_stream_collection_new (stream_id);
448   g_free (stream_id);
449   g_free (upstream_id);
450
451   return program;
452 }
453
454 MpegTSBaseProgram *
455 mpegts_base_add_program (MpegTSBase * base,
456     gint program_number, guint16 pmt_pid)
457 {
458   MpegTSBaseProgram *program;
459
460   GST_DEBUG_OBJECT (base, "program_number : %d, pmt_pid : 0x%04x",
461       program_number, pmt_pid);
462
463   program = mpegts_base_new_program (base, program_number, pmt_pid);
464
465   /* Mark the PMT PID as being a known PSI PID */
466   if (G_UNLIKELY (MPEGTS_BIT_IS_SET (base->known_psi, pmt_pid))) {
467     GST_FIXME ("Refcounting. Setting twice a PID (0x%04x) as known PSI",
468         pmt_pid);
469   }
470   MPEGTS_BIT_SET (base->known_psi, pmt_pid);
471
472   /* Ensure the PMT PID was not used by some PES stream */
473   if (G_UNLIKELY (MPEGTS_BIT_IS_SET (base->is_pes, pmt_pid))) {
474     GST_DEBUG ("New program PMT PID was previously used by a PES stream");
475     MPEGTS_BIT_UNSET (base->is_pes, pmt_pid);
476   }
477
478
479   g_ptr_array_add (base->programs, program);
480
481   return program;
482 }
483
484 MpegTSBaseProgram *
485 mpegts_base_get_program (MpegTSBase * base, gint program_number)
486 {
487   guint i;
488
489   for (i = 0; i < base->programs->len; i++) {
490     MpegTSBaseProgram *program = g_ptr_array_index (base->programs, i);
491     if (program->program_number == program_number)
492       return program;
493   }
494   return NULL;
495 }
496
497 static MpegTSBaseProgram *
498 mpegts_base_steal_program (MpegTSBase * base, gint program_number)
499 {
500   guint i;
501
502   for (i = 0; i < base->programs->len; i++) {
503     MpegTSBaseProgram *program = g_ptr_array_index (base->programs, i);
504     if (program->program_number == program_number)
505       return g_ptr_array_steal_index (base->programs, i);
506   }
507
508   return NULL;
509 }
510
511 static void
512 mpegts_base_free_stream (MpegTSBaseStream * stream)
513 {
514   if (stream->stream_object)
515     gst_object_unref (stream->stream_object);
516   if (stream->stream_id)
517     g_free (stream->stream_id);
518   g_free (stream);
519 }
520
521 static void
522 mpegts_base_free_program (MpegTSBaseProgram * program)
523 {
524   GList *tmp;
525
526   if (program->pmt) {
527     gst_mpegts_section_unref (program->section);
528     program->pmt = NULL;
529   }
530
531   /* FIXME FIXME FIXME FREE STREAM OBJECT ! */
532   for (tmp = program->stream_list; tmp; tmp = tmp->next)
533     mpegts_base_free_stream ((MpegTSBaseStream *) tmp->data);
534
535   if (program->stream_list)
536     g_list_free (program->stream_list);
537
538   g_free (program->streams);
539
540   if (program->tags)
541     gst_tag_list_unref (program->tags);
542   if (program->collection)
543     gst_object_unref (program->collection);
544
545   g_free (program);
546 }
547
548 void
549 mpegts_base_deactivate_and_free_program (MpegTSBase * base,
550     MpegTSBaseProgram * program)
551 {
552   GST_DEBUG_OBJECT (base, "program_number : %d", program->program_number);
553
554   mpegts_base_deactivate_program (base, program);
555   mpegts_base_free_program (program);
556 }
557
558 static void
559 mpegts_base_remove_program (MpegTSBase * base, MpegTSBaseProgram * program)
560 {
561   GST_DEBUG_OBJECT (base, "program_number : %d", program->program_number);
562
563   g_ptr_array_remove (base->programs, program);
564 }
565
566 static guint32
567 get_registration_from_descriptors (GPtrArray * descriptors)
568 {
569   const GstMpegtsDescriptor *desc;
570
571   if ((desc =
572           gst_mpegts_find_descriptor (descriptors,
573               GST_MTS_DESC_REGISTRATION))) {
574     if (G_UNLIKELY (desc->length < 4)) {
575       GST_WARNING ("Registration descriptor with length < 4. (Corrupted ?)");
576     } else
577       return GST_READ_UINT32_BE (desc->data + 2);
578   }
579
580   return 0;
581 }
582
583 static gboolean
584 find_registration_in_descriptors (GPtrArray * descriptors,
585     guint32 registration_id)
586 {
587
588   guint i, nb_desc;
589
590   if (!descriptors)
591     return FALSE;
592
593   nb_desc = descriptors->len;
594   for (i = 0; i < nb_desc; i++) {
595     GstMpegtsDescriptor *desc = g_ptr_array_index (descriptors, i);
596     if (desc->tag == GST_MTS_DESC_REGISTRATION) {
597       guint32 reg_desc = GST_READ_UINT32_BE (desc->data + 2);
598       if (reg_desc == registration_id)
599         return TRUE;
600     }
601   }
602   return FALSE;
603 }
604
605 static MpegTSBaseStream *
606 mpegts_base_program_add_stream (MpegTSBase * base,
607     MpegTSBaseProgram * program, guint16 pid, guint8 stream_type,
608     GstMpegtsPMTStream * stream)
609 {
610   MpegTSBaseClass *klass = GST_MPEGTS_BASE_GET_CLASS (base);
611   MpegTSBaseStream *bstream;
612
613   GST_DEBUG ("pid:0x%04x, stream_type:0x%03x", pid, stream_type);
614
615   /* FIXME : PID information/nature might change through time.
616    * We therefore *do* want to be able to replace an existing stream
617    * with updated information */
618   if (G_UNLIKELY (program->streams[pid])) {
619     if (stream_type != 0xff)
620       GST_WARNING ("Stream already present !");
621     return NULL;
622   }
623
624   bstream = g_malloc0 (base->stream_size);
625   bstream->stream_id =
626       g_strdup_printf ("%s/%08x",
627       gst_stream_collection_get_upstream_id (program->collection), pid);
628   bstream->pid = pid;
629   bstream->stream_type = stream_type;
630   bstream->stream = stream;
631   /* We don't yet know the stream type, subclasses will fill that */
632   bstream->stream_object = gst_stream_new (bstream->stream_id, NULL,
633       GST_STREAM_TYPE_UNKNOWN, GST_STREAM_FLAG_NONE);
634   if (stream) {
635     bstream->registration_id =
636         get_registration_from_descriptors (stream->descriptors);
637     GST_DEBUG ("PID 0x%04x, registration_id %" SAFE_FOURCC_FORMAT,
638         bstream->pid, SAFE_FOURCC_ARGS (bstream->registration_id));
639   }
640
641   program->streams[pid] = bstream;
642   program->stream_list = g_list_append (program->stream_list, bstream);
643
644   if (klass->stream_added)
645     if (klass->stream_added (base, bstream, program)) {
646       gst_stream_collection_add_stream (program->collection,
647           (GstStream *) gst_object_ref (bstream->stream_object));
648       bstream->in_collection = TRUE;
649     }
650
651
652   return bstream;
653 }
654
655 static void
656 mpegts_base_program_remove_stream (MpegTSBase * base,
657     MpegTSBaseProgram * program, guint16 pid)
658 {
659   MpegTSBaseClass *klass;
660   MpegTSBaseStream *stream = program->streams[pid];
661
662   GST_DEBUG ("pid:0x%04x", pid);
663
664   if (G_UNLIKELY (stream == NULL)) {
665     /* Can happen if the PCR PID is the same as a audio/video PID */
666     GST_DEBUG ("Stream already removed");
667     return;
668   }
669
670   klass = GST_MPEGTS_BASE_GET_CLASS (base);
671
672   /* If subclass needs it, inform it of the stream we are about to remove */
673   if (klass->stream_removed)
674     klass->stream_removed (base, stream);
675
676   program->stream_list = g_list_remove_all (program->stream_list, stream);
677   mpegts_base_free_stream (stream);
678   program->streams[pid] = NULL;
679 }
680
681 /* Check if pmtstream is already present in the program */
682 static inline gboolean
683 _stream_in_pmt (const GstMpegtsPMT * pmt, MpegTSBaseStream * stream)
684 {
685   guint i, nbstreams = pmt->streams->len;
686
687   for (i = 0; i < nbstreams; i++) {
688     GstMpegtsPMTStream *pmt_stream = g_ptr_array_index (pmt->streams, i);
689
690     if (pmt_stream->pid == stream->pid &&
691         pmt_stream->stream_type == stream->stream_type)
692       return TRUE;
693   }
694
695   return FALSE;
696 }
697
698 static inline gboolean
699 _pmt_stream_in_program (MpegTSBaseProgram * program,
700     GstMpegtsPMTStream * stream)
701 {
702   MpegTSBaseStream *old_stream = program->streams[stream->pid];
703   if (!old_stream)
704     return FALSE;
705   return old_stream->stream_type == stream->stream_type;
706 }
707
708 static gboolean
709 mpegts_base_update_program (MpegTSBase * base, MpegTSBaseProgram * program,
710     GstMpegtsSection * section, const GstMpegtsPMT * pmt)
711 {
712   MpegTSBaseClass *klass = GST_MPEGTS_BASE_GET_CLASS (base);
713   const gchar *stream_id =
714       gst_stream_collection_get_upstream_id (program->collection);
715   GstStreamCollection *collection;
716   GList *tmp, *toremove;
717   guint i, nbstreams;
718
719   /* Create new collection */
720   collection = gst_stream_collection_new (stream_id);
721   gst_object_unref (program->collection);
722   program->collection = collection;
723
724   /* Replace section and pmt with the new one */
725   gst_mpegts_section_unref (program->section);
726   program->section = gst_mpegts_section_ref (section);
727   program->pmt = pmt;
728
729   /* Copy over gststream that still exist into the collection */
730   for (tmp = program->stream_list; tmp; tmp = tmp->next) {
731     MpegTSBaseStream *stream = (MpegTSBaseStream *) tmp->data;
732     if (_stream_in_pmt (pmt, stream) && stream->in_collection) {
733       gst_stream_collection_add_stream (program->collection,
734           gst_object_ref (stream->stream_object));
735     }
736   }
737
738   /* Add new streams (will also create and add gststream to the collection) */
739   nbstreams = pmt->streams->len;
740   for (i = 0; i < nbstreams; i++) {
741     GstMpegtsPMTStream *stream = g_ptr_array_index (pmt->streams, i);
742     if (!_pmt_stream_in_program (program, stream))
743       mpegts_base_program_add_stream (base, program, stream->pid,
744           stream->stream_type, stream);
745   }
746
747   /* Call subclass update */
748   if (klass->update_program)
749     klass->update_program (base, program);
750
751   /* Remove streams no longer present */
752   toremove = NULL;
753   for (tmp = program->stream_list; tmp; tmp = tmp->next) {
754     MpegTSBaseStream *stream = (MpegTSBaseStream *) tmp->data;
755     if (!_stream_in_pmt (pmt, stream))
756       toremove = g_list_prepend (toremove, stream);
757   }
758   for (tmp = toremove; tmp; tmp = tmp->next) {
759     MpegTSBaseStream *stream = (MpegTSBaseStream *) tmp->data;
760     mpegts_base_program_remove_stream (base, program, stream->pid);
761   }
762   return TRUE;
763 }
764
765
766 static gboolean
767 _stream_is_private_section (const GstMpegtsPMT * pmt,
768     GstMpegtsPMTStream * stream)
769 {
770   switch (stream->stream_type) {
771     case GST_MPEGTS_STREAM_TYPE_SCTE_DSMCC_DCB:
772     case GST_MPEGTS_STREAM_TYPE_SCTE_SIGNALING:
773     {
774       guint32 registration_id =
775           get_registration_from_descriptors (stream->descriptors);
776       /* Not a private section stream */
777       if (registration_id != DRF_ID_CUEI && registration_id != DRF_ID_ETV1)
778         return FALSE;
779     }
780     case GST_MPEGTS_STREAM_TYPE_PRIVATE_SECTIONS:
781     case GST_MPEGTS_STREAM_TYPE_MHEG:
782     case GST_MPEGTS_STREAM_TYPE_DSM_CC:
783     case GST_MPEGTS_STREAM_TYPE_DSMCC_A:
784     case GST_MPEGTS_STREAM_TYPE_DSMCC_B:
785     case GST_MPEGTS_STREAM_TYPE_DSMCC_C:
786     case GST_MPEGTS_STREAM_TYPE_DSMCC_D:
787     case GST_MPEGTS_STREAM_TYPE_SL_FLEXMUX_SECTIONS:
788     case GST_MPEGTS_STREAM_TYPE_METADATA_SECTIONS:
789       /* known PSI streams */
790       return TRUE;
791     case GST_MPEGTS_STREAM_TYPE_SCTE_SIT:
792     {
793       /* Not a private section stream */
794       if (!find_registration_in_descriptors (pmt->descriptors, DRF_ID_CUEI))
795         return FALSE;
796       return TRUE;
797     }
798     default:
799       return FALSE;
800   }
801 }
802
803 /* Return TRUE if programs are equal */
804 static gboolean
805 mpegts_base_is_same_program (MpegTSBase * base, MpegTSBaseProgram * oldprogram,
806     guint16 new_pmt_pid, const GstMpegtsPMT * new_pmt)
807 {
808   guint i, nbstreams;
809   MpegTSBaseStream *oldstream;
810   gboolean sawpcrpid = FALSE;
811
812   if (oldprogram->pmt_pid != new_pmt_pid) {
813     GST_DEBUG ("Different pmt_pid (new:0x%04x, old:0x%04x)", new_pmt_pid,
814         oldprogram->pmt_pid);
815     return FALSE;
816   }
817
818   if (!base->ignore_pcr && oldprogram->pcr_pid != new_pmt->pcr_pid) {
819     GST_DEBUG ("Different pcr_pid (new:0x%04x, old:0x%04x)",
820         new_pmt->pcr_pid, oldprogram->pcr_pid);
821     return FALSE;
822   }
823
824   /* Check the streams */
825   nbstreams = new_pmt->streams->len;
826   for (i = 0; i < nbstreams; ++i) {
827     GstMpegtsPMTStream *stream = g_ptr_array_index (new_pmt->streams, i);
828
829     oldstream = oldprogram->streams[stream->pid];
830     if (!oldstream) {
831       GST_DEBUG ("New stream 0x%04x not present in old program", stream->pid);
832       return FALSE;
833     }
834     if (oldstream->stream_type != stream->stream_type) {
835       GST_DEBUG
836           ("New stream 0x%04x has a different stream type (new:%d, old:%d)",
837           stream->pid, stream->stream_type, oldstream->stream_type);
838       return FALSE;
839     }
840     if (stream->pid == oldprogram->pcr_pid)
841       sawpcrpid = TRUE;
842   }
843
844   /* If the pcr is not shared with an existing stream, we'll have one extra stream */
845   if (!sawpcrpid)
846     nbstreams += 1;
847
848   if (nbstreams != g_list_length (oldprogram->stream_list)) {
849     GST_DEBUG ("Different number of streams (new:%d, old:%d)",
850         nbstreams, g_list_length (oldprogram->stream_list));
851     return FALSE;
852   }
853
854   GST_DEBUG ("Programs are equal");
855   return TRUE;
856 }
857
858 /* Return TRUE if program is an update
859  *
860  * A program is equal if:
861  * * The program number is the same (will be if it enters this function)
862  * * AND The PMT PID is equal to the old one
863  * * AND It contains at least one stream from the previous program
864  *
865  * Changes that are acceptable are therefore:
866  * * New streams appearing
867  * * Old streams going away
868  * * PCR PID changing
869  *
870  * Unclear changes:
871  * * PMT PID being changed ?
872  * * Properties of elementary stream being changed ? (new tags ? metadata ?)
873  */
874 static gboolean
875 mpegts_base_is_program_update (MpegTSBase * base,
876     MpegTSBaseProgram * oldprogram, guint16 new_pmt_pid,
877     const GstMpegtsPMT * new_pmt)
878 {
879   guint i, nbstreams;
880   MpegTSBaseStream *oldstream;
881
882   if (oldprogram->pmt_pid != new_pmt_pid) {
883     /* FIXME/CHECK: Can a program be updated by just changing its PID
884      * in the PAT ? */
885     GST_DEBUG ("Different pmt_pid (new:0x%04x, old:0x%04x)", new_pmt_pid,
886         oldprogram->pmt_pid);
887     return FALSE;
888   }
889
890   /* Check if at least one stream from the previous program is still present
891    * in the new program */
892
893   /* Check the streams */
894   nbstreams = new_pmt->streams->len;
895   for (i = 0; i < nbstreams; ++i) {
896     GstMpegtsPMTStream *stream = g_ptr_array_index (new_pmt->streams, i);
897
898     oldstream = oldprogram->streams[stream->pid];
899     if (!oldstream) {
900       GST_DEBUG ("New stream 0x%04x not present in old program", stream->pid);
901     } else if (oldstream->stream_type != stream->stream_type) {
902       GST_DEBUG
903           ("New stream 0x%04x has a different stream type (new:%d, old:%d)",
904           stream->pid, stream->stream_type, oldstream->stream_type);
905     } else if (!_stream_is_private_section (new_pmt, stream)) {
906       /* FIXME : We should actually be checking a bit deeper,
907        * especially for private streams (where the differentiation is
908        * done at the registration level) */
909       GST_DEBUG
910           ("Stream 0x%04x is identical (stream_type %d) ! Program is an update",
911           stream->pid, stream->stream_type);
912       return TRUE;
913     }
914   }
915
916   GST_DEBUG ("Program is not an update of the previous one");
917   return FALSE;
918 }
919
920 static void
921 mpegts_base_deactivate_program (MpegTSBase * base, MpegTSBaseProgram * program)
922 {
923   gint i;
924   MpegTSBaseClass *klass = GST_MPEGTS_BASE_GET_CLASS (base);
925
926   if (G_UNLIKELY (program->active == FALSE))
927     return;
928
929   GST_DEBUG_OBJECT (base, "Deactivating PMT");
930
931   program->active = FALSE;
932
933   if (program->pmt) {
934     for (i = 0; i < program->pmt->streams->len; ++i) {
935       GstMpegtsPMTStream *stream = g_ptr_array_index (program->pmt->streams, i);
936
937       mpegts_base_program_remove_stream (base, program, stream->pid);
938
939       /* Only unset the is_pes/known_psi bit if the PID isn't used in any other active
940        * program */
941       if (!mpegts_pid_in_active_programs (base, stream->pid)) {
942         if (_stream_is_private_section (program->pmt, stream)) {
943           if (base->parse_private_sections)
944             MPEGTS_BIT_UNSET (base->known_psi, stream->pid);
945         } else {
946           MPEGTS_BIT_UNSET (base->is_pes, stream->pid);
947         }
948       }
949     }
950
951     /* remove pcr stream */
952     /* FIXME : This might actually be shared with another stream ? */
953     mpegts_base_program_remove_stream (base, program, program->pcr_pid);
954     if (!mpegts_pid_in_active_programs (base, program->pcr_pid))
955       MPEGTS_BIT_UNSET (base->is_pes, program->pcr_pid);
956
957     GST_DEBUG ("program stream_list is now %p", program->stream_list);
958   }
959
960   /* Inform subclasses we're deactivating this program */
961   if (klass->program_stopped)
962     klass->program_stopped (base, program);
963 }
964
965 static void
966 mpegts_base_activate_program (MpegTSBase * base, MpegTSBaseProgram * program,
967     guint16 pmt_pid, GstMpegtsSection * section, const GstMpegtsPMT * pmt,
968     gboolean initial_program)
969 {
970   guint i;
971   MpegTSBaseClass *klass;
972
973   if (G_UNLIKELY (program->active))
974     return;
975
976   GST_DEBUG ("Activating program %d", program->program_number);
977
978   /* activate new pmt */
979   if (program->section)
980     gst_mpegts_section_unref (program->section);
981   program->section = gst_mpegts_section_ref (section);
982
983   program->pmt = pmt;
984   program->pmt_pid = pmt_pid;
985   if (!base->ignore_pcr)
986     program->pcr_pid = pmt->pcr_pid;
987   else
988     program->pcr_pid = 0x1fff;
989
990   /* extract top-level registration_id if present */
991   program->registration_id =
992       get_registration_from_descriptors (pmt->descriptors);
993   GST_DEBUG ("program 0x%04x, registration_id %" SAFE_FOURCC_FORMAT,
994       program->program_number, SAFE_FOURCC_ARGS (program->registration_id));
995
996   for (i = 0; i < pmt->streams->len; ++i) {
997     GstMpegtsPMTStream *stream = g_ptr_array_index (pmt->streams, i);
998     if (_stream_is_private_section (pmt, stream)) {
999       if (base->parse_private_sections)
1000         MPEGTS_BIT_SET (base->known_psi, stream->pid);
1001     } else {
1002       if (G_UNLIKELY (MPEGTS_BIT_IS_SET (base->is_pes, stream->pid)))
1003         GST_FIXME
1004             ("Refcounting issue. Setting twice a PID (0x%04x) as known PES",
1005             stream->pid);
1006       if (G_UNLIKELY (MPEGTS_BIT_IS_SET (base->known_psi, stream->pid))) {
1007         GST_FIXME
1008             ("Refcounting issue. Setting a known PSI PID (0x%04x) as known PES",
1009             stream->pid);
1010         MPEGTS_BIT_UNSET (base->known_psi, stream->pid);
1011       }
1012       MPEGTS_BIT_SET (base->is_pes, stream->pid);
1013     }
1014     mpegts_base_program_add_stream (base, program,
1015         stream->pid, stream->stream_type, stream);
1016   }
1017   /* We add the PCR pid last. If that PID is already used by one of the media
1018    * streams above, no new stream will be created */
1019   mpegts_base_program_add_stream (base, program, program->pcr_pid, -1, NULL);
1020   MPEGTS_BIT_SET (base->is_pes, program->pcr_pid);
1021
1022   program->active = TRUE;
1023   program->initial_program = initial_program;
1024
1025   klass = GST_MPEGTS_BASE_GET_CLASS (base);
1026   if (klass->program_started != NULL)
1027     klass->program_started (base, program);
1028
1029   GST_DEBUG_OBJECT (base, "new pmt activated");
1030 }
1031
1032
1033 static gboolean
1034 mpegts_base_apply_pat (MpegTSBase * base, GstMpegtsSection * section)
1035 {
1036   GPtrArray *pat = gst_mpegts_section_get_pat (section);
1037   GPtrArray *old_pat;
1038   MpegTSBaseProgram *program;
1039   gint i;
1040
1041   if (G_UNLIKELY (pat == NULL))
1042     return FALSE;
1043
1044   GST_INFO_OBJECT (base, "PAT");
1045
1046   /* Applying a new PAT does two things:
1047    * * It adds the new programs to the list of programs this element handles
1048    *   and increments at the same time the number of times a program is referenced.
1049    *
1050    * * If there was a previously active PAT, It decrements the reference count
1051    *   of all program it used. If a program is no longer needed, it is removed.
1052    */
1053
1054   old_pat = base->pat;
1055   base->pat = pat;
1056
1057   GST_LOG ("Activating new Program Association Table");
1058   /* activate the new table */
1059   for (i = 0; i < pat->len; ++i) {
1060     GstMpegtsPatProgram *patp = g_ptr_array_index (pat, i);
1061
1062     GST_LOG ("Looking for program %d / 0x%04x", patp->program_number,
1063         patp->network_or_program_map_PID);
1064     program = mpegts_base_get_program (base, patp->program_number);
1065     if (program) {
1066       GST_LOG ("Program exists on pid 0x%04x", program->pmt_pid);
1067       /* If the new PMT PID clashes with an existing known PES stream, we know
1068        * it is not an update */
1069       if (MPEGTS_BIT_IS_SET (base->is_pes, patp->network_or_program_map_PID)) {
1070         GST_LOG ("Program is not an update");
1071         program =
1072             mpegts_base_add_program (base, patp->program_number,
1073             patp->network_or_program_map_PID);
1074       } else if (program->pmt_pid != patp->network_or_program_map_PID) {
1075         /* IF the program already existed, just check if the PMT PID changed */
1076         GST_LOG ("PMT is on a different PID");
1077         if (program->pmt_pid != G_MAXUINT16) {
1078           /* pmt pid changed */
1079           /* FIXME: when this happens it may still be pmt pid of another
1080            * program, so setting to False may make it go through expensive
1081            * path in is_psi unnecessarily */
1082           MPEGTS_BIT_UNSET (base->known_psi, program->pmt_pid);
1083         }
1084
1085         program->pmt_pid = patp->network_or_program_map_PID;
1086         if (G_UNLIKELY (MPEGTS_BIT_IS_SET (base->known_psi, program->pmt_pid)))
1087           GST_FIXME
1088               ("Refcounting issue. Setting twice a PMT PID (0x%04x) as know PSI",
1089               program->pmt_pid);
1090         MPEGTS_BIT_SET (base->known_psi, patp->network_or_program_map_PID);
1091       } else {
1092         GST_LOG ("Regular program update");
1093       }
1094     } else {
1095       /* Create a new program */
1096       program =
1097           mpegts_base_add_program (base, patp->program_number,
1098           patp->network_or_program_map_PID);
1099     }
1100     /* We mark this program as being referenced by one PAT */
1101     program->patcount += 1;
1102   }
1103
1104   if (old_pat) {
1105     MpegTSBaseClass *klass = GST_MPEGTS_BASE_GET_CLASS (base);
1106     /* deactivate the old table */
1107     GST_LOG ("Deactivating old Program Association Table");
1108
1109     for (i = 0; i < old_pat->len; ++i) {
1110       GstMpegtsPatProgram *patp = g_ptr_array_index (old_pat, i);
1111
1112       program = mpegts_base_get_program (base, patp->program_number);
1113       if (G_UNLIKELY (program == NULL)) {
1114         GST_DEBUG_OBJECT (base, "broken PAT, duplicated entry for program %d",
1115             patp->program_number);
1116         continue;
1117       }
1118
1119       GST_LOG ("Deactivating program %d / 0x%04x", patp->program_number,
1120           patp->network_or_program_map_PID);
1121
1122       if (--program->patcount > 0) {
1123         GST_LOG ("Referenced by new program, keeping");
1124         /* the program has been referenced by the new pat, keep it */
1125         continue;
1126       }
1127
1128       GST_INFO_OBJECT (base, "PAT removing program 0x%04x 0x%04x",
1129           patp->program_number, patp->network_or_program_map_PID);
1130
1131       if (klass->can_remove_program (base, program)) {
1132         mpegts_base_deactivate_program (base, program);
1133         mpegts_base_remove_program (base, program);
1134       } else {
1135         /* sub-class now owns the program and must call
1136          * mpegts_base_deactivate_and_free_program later */
1137         mpegts_base_steal_program (base, patp->program_number);
1138       }
1139       /* FIXME: when this happens it may still be pmt pid of another
1140        * program, so setting to False may make it go through expensive
1141        * path in is_psi unnecessarily */
1142       if (G_UNLIKELY (MPEGTS_BIT_IS_SET (base->known_psi,
1143                   patp->network_or_program_map_PID))) {
1144         GST_FIXME
1145             ("Program refcounting : Setting twice a pid (0x%04x) as known PSI",
1146             patp->network_or_program_map_PID);
1147       }
1148       MPEGTS_BIT_SET (base->known_psi, patp->network_or_program_map_PID);
1149       mpegts_packetizer_remove_stream (base->packetizer,
1150           patp->network_or_program_map_PID);
1151     }
1152
1153     g_ptr_array_unref (old_pat);
1154   }
1155
1156   return TRUE;
1157 }
1158
1159 static gboolean
1160 mpegts_base_apply_pmt (MpegTSBase * base, GstMpegtsSection * section)
1161 {
1162   const GstMpegtsPMT *pmt;
1163   MpegTSBaseProgram *program, *old_program;
1164   guint program_number;
1165   gboolean initial_program = TRUE;
1166
1167   pmt = gst_mpegts_section_get_pmt (section);
1168   if (G_UNLIKELY (pmt == NULL)) {
1169     GST_ERROR ("Could not get PMT (corrupted ?)");
1170     return FALSE;
1171   }
1172
1173   /* FIXME : not so sure this is valid anymore */
1174   if (G_UNLIKELY (base->seen_pat == FALSE)) {
1175     GST_WARNING ("Got pmt without pat first. Returning");
1176     /* remove the stream since we won't get another PMT otherwise */
1177     mpegts_packetizer_remove_stream (base->packetizer, section->pid);
1178     return TRUE;
1179   }
1180
1181   program_number = section->subtable_extension;
1182   GST_DEBUG ("Applying PMT (program_number:%d, pid:0x%04x)",
1183       program_number, section->pid);
1184
1185   /* In order for stream switching to happen properly in decodebin(2),
1186    * we need to first add the new pads (i.e. activate the new program)
1187    * before removing the old ones (i.e. deactivating the old program)
1188    */
1189
1190   old_program = mpegts_base_get_program (base, program_number);
1191   if (G_UNLIKELY (old_program == NULL))
1192     goto no_program;
1193
1194   if (base->streams_aware
1195       && mpegts_base_is_program_update (base, old_program, section->pid, pmt)) {
1196     GST_FIXME ("We are streams_aware and new program is an update");
1197     /* The program is an update, and we can add/remove pads dynamically */
1198     mpegts_base_update_program (base, old_program, section, pmt);
1199     goto beach;
1200   }
1201
1202   if (G_UNLIKELY (mpegts_base_is_same_program (base, old_program, section->pid,
1203               pmt)))
1204     goto same_program;
1205
1206   /* If the current program is active, this means we have a new program */
1207   if (old_program->active) {
1208     MpegTSBaseClass *klass = GST_MPEGTS_BASE_GET_CLASS (base);
1209     old_program = mpegts_base_steal_program (base, program_number);
1210     program = mpegts_base_new_program (base, program_number, section->pid);
1211     program->patcount = old_program->patcount;
1212
1213     /* Deactivate the old program */
1214     /* FIXME : THIS IS BREAKING THE STREAM SWITCHING LOGIC !
1215      *  */
1216     if (klass->can_remove_program (base, old_program)) {
1217       mpegts_base_deactivate_program (base, old_program);
1218       mpegts_base_free_program (old_program);
1219     } else {
1220       /* sub-class now owns the program and must call
1221        * mpegts_base_deactivate_and_free_program later */
1222       mpegts_base_steal_program (base, old_program->program_number);
1223     }
1224     /* Add new program to the programs we track */
1225     g_ptr_array_add (base->programs, program);
1226     initial_program = FALSE;
1227   } else {
1228     GST_DEBUG ("Program update, re-using same program");
1229     program = old_program;
1230   }
1231
1232   /* activate program */
1233   /* Ownership of pmt_info is given to the program */
1234   mpegts_base_activate_program (base, program, section->pid, section, pmt,
1235       initial_program);
1236
1237 beach:
1238   GST_DEBUG ("Done activating program");
1239   return TRUE;
1240
1241 no_program:
1242   {
1243     GST_ERROR ("Attempted to apply a PMT on a program that wasn't created");
1244     return TRUE;
1245   }
1246
1247 same_program:
1248   {
1249     GST_DEBUG ("Not applying identical program");
1250     return TRUE;
1251   }
1252 }
1253
1254 static void
1255 mpegts_base_handle_psi (MpegTSBase * base, GstMpegtsSection * section)
1256 {
1257   gboolean post_message = TRUE;
1258
1259   GST_DEBUG ("Handling PSI (pid: 0x%04x , table_id: 0x%02x)",
1260       section->pid, section->table_id);
1261
1262   switch (section->section_type) {
1263     case GST_MPEGTS_SECTION_PAT:
1264       post_message = mpegts_base_apply_pat (base, section);
1265       if (base->seen_pat == FALSE) {
1266         base->seen_pat = TRUE;
1267         GST_DEBUG ("First PAT offset: %" G_GUINT64_FORMAT, section->offset);
1268         mpegts_packetizer_set_reference_offset (base->packetizer,
1269             section->offset);
1270       }
1271       break;
1272     case GST_MPEGTS_SECTION_PMT:
1273       post_message = mpegts_base_apply_pmt (base, section);
1274       break;
1275     case GST_MPEGTS_SECTION_EIT:
1276       /* some tag xtraction + posting */
1277       post_message = mpegts_base_get_tags_from_eit (base, section);
1278       break;
1279     case GST_MPEGTS_SECTION_ATSC_MGT:
1280       post_message = mpegts_base_parse_atsc_mgt (base, section);
1281       break;
1282     default:
1283       break;
1284   }
1285
1286   /* Give the subclass a chance to look at the section */
1287   if (GST_MPEGTS_BASE_GET_CLASS (base)->handle_psi)
1288     GST_MPEGTS_BASE_GET_CLASS (base)->handle_psi (base, section);
1289
1290   /* Finally post message (if it wasn't corrupted) */
1291   if (post_message)
1292     gst_element_post_message (GST_ELEMENT_CAST (base),
1293         gst_message_new_mpegts_section (GST_OBJECT (base), section));
1294   gst_mpegts_section_unref (section);
1295 }
1296
1297 static gboolean
1298 mpegts_base_parse_atsc_mgt (MpegTSBase * base, GstMpegtsSection * section)
1299 {
1300   const GstMpegtsAtscMGT *mgt;
1301   gint i;
1302
1303   mgt = gst_mpegts_section_get_atsc_mgt (section);
1304   if (G_UNLIKELY (mgt == NULL))
1305     return FALSE;
1306
1307   for (i = 0; i < mgt->tables->len; ++i) {
1308     GstMpegtsAtscMGTTable *table = g_ptr_array_index (mgt->tables, i);
1309
1310     if ((table->table_type >= GST_MPEGTS_ATSC_MGT_TABLE_TYPE_EIT0 &&
1311             table->table_type <= GST_MPEGTS_ATSC_MGT_TABLE_TYPE_EIT127) ||
1312         (table->table_type >= GST_MPEGTS_ATSC_MGT_TABLE_TYPE_ETT0 &&
1313             table->table_type <= GST_MPEGTS_ATSC_MGT_TABLE_TYPE_ETT127)) {
1314       MPEGTS_BIT_SET (base->known_psi, table->pid);
1315     }
1316   }
1317
1318   return TRUE;
1319 }
1320
1321 static gboolean
1322 mpegts_base_get_tags_from_eit (MpegTSBase * base, GstMpegtsSection * section)
1323 {
1324   const GstMpegtsEIT *eit;
1325   guint i;
1326   MpegTSBaseProgram *program;
1327
1328   /* Early exit if it's not from the present/following table_id */
1329   if (section->table_id != GST_MTS_TABLE_ID_EVENT_INFORMATION_ACTUAL_TS_PRESENT
1330       && section->table_id !=
1331       GST_MTS_TABLE_ID_EVENT_INFORMATION_OTHER_TS_PRESENT)
1332     return TRUE;
1333
1334   eit = gst_mpegts_section_get_eit (section);
1335   if (G_UNLIKELY (eit == NULL))
1336     return FALSE;
1337
1338   program = mpegts_base_get_program (base, section->subtable_extension);
1339
1340   GST_DEBUG
1341       ("program_id:0x%04x, table_id:0x%02x, actual_stream:%d, present_following:%d, program:%p",
1342       section->subtable_extension, section->table_id, eit->actual_stream,
1343       eit->present_following, program);
1344
1345   if (program && eit->present_following) {
1346     for (i = 0; i < eit->events->len; i++) {
1347       GstMpegtsEITEvent *event = g_ptr_array_index (eit->events, i);
1348       const GstMpegtsDescriptor *desc;
1349
1350       if (event->running_status == RUNNING_STATUS_RUNNING) {
1351         program->event_id = event->event_id;
1352         if ((desc =
1353                 gst_mpegts_find_descriptor (event->descriptors,
1354                     GST_MTS_DESC_DVB_SHORT_EVENT))) {
1355           gchar *name = NULL, *text = NULL;
1356
1357           if (gst_mpegts_descriptor_parse_dvb_short_event (desc, NULL, &name,
1358                   &text)) {
1359             if (!program->tags)
1360               program->tags = gst_tag_list_new_empty ();
1361
1362             if (name) {
1363               gst_tag_list_add (program->tags, GST_TAG_MERGE_APPEND,
1364                   GST_TAG_TITLE, name, NULL);
1365               g_free (name);
1366             }
1367             if (text) {
1368               gst_tag_list_add (program->tags, GST_TAG_MERGE_APPEND,
1369                   GST_TAG_DESCRIPTION, text, NULL);
1370               g_free (text);
1371             }
1372             /* FIXME : Is it correct to post an event duration as a GST_TAG_DURATION ??? */
1373             gst_tag_list_add (program->tags, GST_TAG_MERGE_APPEND,
1374                 GST_TAG_DURATION, event->duration * GST_SECOND, NULL);
1375             return TRUE;
1376           }
1377         }
1378       }
1379     }
1380   }
1381
1382   return TRUE;
1383 }
1384
1385 static void
1386 remove_each_program (MpegTSBaseProgram * program, MpegTSBase * base)
1387 {
1388   /* First deactivate it */
1389   mpegts_base_deactivate_program (base, program);
1390 }
1391
1392 static inline GstFlowReturn
1393 mpegts_base_drain (MpegTSBase * base)
1394 {
1395   MpegTSBaseClass *klass = GST_MPEGTS_BASE_GET_CLASS (base);
1396
1397   /* Call implementation */
1398   if (klass->drain)
1399     return klass->drain (base);
1400
1401   return GST_FLOW_OK;
1402 }
1403
1404 static inline void
1405 mpegts_base_flush (MpegTSBase * base, gboolean hard)
1406 {
1407   MpegTSBaseClass *klass = GST_MPEGTS_BASE_GET_CLASS (base);
1408
1409   /* Call implementation */
1410   if (klass->flush)
1411     klass->flush (base, hard);
1412 }
1413
1414 static gboolean
1415 mpegts_base_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
1416 {
1417   gboolean res = TRUE;
1418   gboolean hard;
1419   MpegTSBase *base = GST_MPEGTS_BASE (parent);
1420   gboolean is_sticky = GST_EVENT_IS_STICKY (event);
1421
1422   GST_DEBUG_OBJECT (base, "Got event %s",
1423       gst_event_type_get_name (GST_EVENT_TYPE (event)));
1424
1425   switch (GST_EVENT_TYPE (event)) {
1426     case GST_EVENT_SEGMENT:
1427       gst_event_copy_segment (event, &base->segment);
1428       GST_DEBUG_OBJECT (base, "Received segment %" GST_SEGMENT_FORMAT,
1429           &base->segment);
1430       /* Check if we need to switch PCR/PTS handling */
1431       if (base->segment.format == GST_FORMAT_TIME) {
1432         base->packetizer->calculate_offset = FALSE;
1433         base->packetizer->calculate_skew = TRUE;
1434         /* Seek was handled upstream */
1435         base->last_seek_seqnum = gst_event_get_seqnum (event);
1436       } else {
1437         base->packetizer->calculate_offset = TRUE;
1438         base->packetizer->calculate_skew = FALSE;
1439       }
1440
1441       res = GST_MPEGTS_BASE_GET_CLASS (base)->push_event (base, event);
1442       break;
1443     case GST_EVENT_STREAM_START:
1444       gst_event_unref (event);
1445       break;
1446     case GST_EVENT_CAPS:
1447       /* FIXME, do something */
1448       gst_event_unref (event);
1449       break;
1450     case GST_EVENT_FLUSH_STOP:
1451       res = GST_MPEGTS_BASE_GET_CLASS (base)->push_event (base, event);
1452       hard = (base->mode != BASE_MODE_SEEKING);
1453       mpegts_packetizer_flush (base->packetizer, hard);
1454       mpegts_base_flush (base, hard);
1455       gst_segment_init (&base->segment, GST_FORMAT_UNDEFINED);
1456       base->seen_pat = FALSE;
1457       break;
1458     default:
1459       res = GST_MPEGTS_BASE_GET_CLASS (base)->push_event (base, event);
1460   }
1461
1462   /* Always return TRUE for sticky events */
1463   if (is_sticky)
1464     res = TRUE;
1465
1466   return res;
1467 }
1468
1469 static gboolean
1470 mpegts_base_default_sink_query (MpegTSBase * base, GstQuery * query)
1471 {
1472   return gst_pad_query_default (base->sinkpad, GST_OBJECT (base), query);
1473 }
1474
1475 static gboolean
1476 mpegts_base_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
1477 {
1478   MpegTSBase *base = GST_MPEGTS_BASE (parent);
1479
1480   GST_DEBUG_OBJECT (base, "Got query %s",
1481       gst_query_type_get_name (GST_QUERY_TYPE (query)));
1482
1483   return GST_MPEGTS_BASE_GET_CLASS (base)->sink_query (base, query);
1484 }
1485
1486 static GstFlowReturn
1487 mpegts_base_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
1488 {
1489   GstFlowReturn res = GST_FLOW_OK;
1490   MpegTSBase *base;
1491   MpegTSPacketizerPacketReturn pret;
1492   MpegTSPacketizer2 *packetizer;
1493   MpegTSPacketizerPacket packet;
1494   MpegTSBaseClass *klass;
1495
1496   base = GST_MPEGTS_BASE (parent);
1497   klass = GST_MPEGTS_BASE_GET_CLASS (base);
1498
1499   packetizer = base->packetizer;
1500
1501   if (GST_BUFFER_IS_DISCONT (buf)) {
1502     GST_DEBUG_OBJECT (base, "Got DISCONT buffer, flushing");
1503     res = mpegts_base_drain (base);
1504     if (G_UNLIKELY (res != GST_FLOW_OK))
1505       return res;
1506
1507     mpegts_base_flush (base, FALSE);
1508     /* In the case of discontinuities in push-mode with TIME segment
1509      * we want to drop all previous observations (hard:TRUE) from
1510      * the packetizer */
1511     if (base->mode == BASE_MODE_PUSHING
1512         && base->segment.format == GST_FORMAT_TIME) {
1513       mpegts_packetizer_flush (base->packetizer, TRUE);
1514       mpegts_packetizer_clear (base->packetizer);
1515     } else
1516       mpegts_packetizer_flush (base->packetizer, FALSE);
1517   }
1518
1519   mpegts_packetizer_push (base->packetizer, buf);
1520
1521   while (res == GST_FLOW_OK) {
1522     pret = mpegts_packetizer_next_packet (base->packetizer, &packet);
1523
1524     /* If we don't have enough data, return */
1525     if (G_UNLIKELY (pret == PACKET_NEED_MORE))
1526       break;
1527
1528     if (G_UNLIKELY (pret == PACKET_BAD)) {
1529       /* bad header, skip the packet */
1530       GST_DEBUG_OBJECT (base, "bad packet, skipping");
1531       goto next;
1532     }
1533
1534     if (klass->inspect_packet)
1535       klass->inspect_packet (base, &packet);
1536
1537     /* If it's a known PES, push it */
1538     if (MPEGTS_BIT_IS_SET (base->is_pes, packet.pid)) {
1539       /* push the packet downstream */
1540       if (base->push_data)
1541         res = klass->push (base, &packet, NULL);
1542     } else if (packet.payload
1543         && MPEGTS_BIT_IS_SET (base->known_psi, packet.pid)) {
1544       /* base PSI data */
1545       GList *others, *tmp;
1546       GstMpegtsSection *section;
1547
1548       section = mpegts_packetizer_push_section (packetizer, &packet, &others);
1549       if (section)
1550         mpegts_base_handle_psi (base, section);
1551       if (G_UNLIKELY (others)) {
1552         for (tmp = others; tmp; tmp = tmp->next)
1553           mpegts_base_handle_psi (base, (GstMpegtsSection *) tmp->data);
1554         g_list_free (others);
1555       }
1556
1557       /* we need to push section packet downstream */
1558       if (base->push_section)
1559         res = klass->push (base, &packet, section);
1560
1561     } else if (base->push_unknown) {
1562       res = klass->push (base, &packet, NULL);
1563     } else if (packet.payload && packet.pid != 0x1fff)
1564       GST_LOG ("PID 0x%04x Saw packet on a pid we don't handle", packet.pid);
1565
1566   next:
1567     mpegts_packetizer_clear_packet (base->packetizer, &packet);
1568   }
1569
1570   if (res == GST_FLOW_OK && klass->input_done)
1571     res = klass->input_done (base);
1572
1573   return res;
1574 }
1575
1576 static GstFlowReturn
1577 mpegts_base_scan (MpegTSBase * base)
1578 {
1579   GstFlowReturn ret = GST_FLOW_OK;
1580   GstBuffer *buf = NULL;
1581   guint i;
1582   gboolean done = FALSE;
1583   MpegTSPacketizerPacketReturn pret;
1584   gint64 tmpval;
1585   gint64 upstream_size, seek_pos, reverse_limit;
1586   GstFormat format;
1587   guint initial_pcr_seen;
1588
1589   GST_DEBUG ("Scanning for initial sync point");
1590
1591   /* Find initial sync point and at least 5 PCR values */
1592   for (i = 0; i < 20 && !done; i++) {
1593     GST_DEBUG ("Grabbing %d => %d", i * 65536, (i + 1) * 65536);
1594
1595     ret = gst_pad_pull_range (base->sinkpad, i * 65536, 65536, &buf);
1596     if (G_UNLIKELY (ret == GST_FLOW_EOS))
1597       break;
1598     if (G_UNLIKELY (ret != GST_FLOW_OK))
1599       goto beach;
1600
1601     /* Push to packetizer */
1602     mpegts_packetizer_push (base->packetizer, buf);
1603     buf = NULL;
1604
1605     if (mpegts_packetizer_has_packets (base->packetizer)) {
1606       if (base->seek_offset == -1) {
1607         /* Mark the initial sync point and remember the packetsize */
1608         base->seek_offset = base->packetizer->offset;
1609         GST_DEBUG ("Sync point is now %" G_GUINT64_FORMAT, base->seek_offset);
1610         base->packetsize = base->packetizer->packet_size;
1611       }
1612       while (1) {
1613         /* Eat up all packets */
1614         pret = mpegts_packetizer_process_next_packet (base->packetizer);
1615         if (pret == PACKET_NEED_MORE)
1616           break;
1617         if (pret != PACKET_BAD && base->packetizer->nb_seen_offsets >= 5) {
1618           GST_DEBUG ("Got enough initial PCR");
1619           done = TRUE;
1620           break;
1621         }
1622       }
1623     }
1624   }
1625
1626   initial_pcr_seen = base->packetizer->nb_seen_offsets;
1627   if (G_UNLIKELY (initial_pcr_seen == 0))
1628     goto no_initial_pcr;
1629   GST_DEBUG ("Seen %d initial PCR", initial_pcr_seen);
1630
1631   /* Now send data from the end */
1632
1633   /* Get the size of upstream */
1634   format = GST_FORMAT_BYTES;
1635   if (!gst_pad_peer_query_duration (base->sinkpad, format, &tmpval))
1636     goto beach;
1637   upstream_size = tmpval;
1638
1639   /* The scanning takes place on the last 2048kB. Considering PCR should
1640    * be present at least every 100ms, this should cope with streams
1641    * up to 160Mbit/s */
1642   reverse_limit = MAX (0, upstream_size - 2097152);
1643
1644   /* Find last PCR value, searching backwards by chunks of 300 MPEG-ts packets */
1645   for (seek_pos = MAX (0, upstream_size - 56400);
1646       seek_pos >= reverse_limit; seek_pos -= 56400) {
1647     mpegts_packetizer_clear (base->packetizer);
1648     GST_DEBUG ("Grabbing %" G_GUINT64_FORMAT " => %" G_GUINT64_FORMAT, seek_pos,
1649         seek_pos + 56400);
1650
1651     ret = gst_pad_pull_range (base->sinkpad, seek_pos, 56400, &buf);
1652     if (G_UNLIKELY (ret == GST_FLOW_EOS))
1653       break;
1654     if (G_UNLIKELY (ret != GST_FLOW_OK))
1655       goto beach;
1656
1657     /* Push to packetizer */
1658     mpegts_packetizer_push (base->packetizer, buf);
1659     buf = NULL;
1660
1661     if (mpegts_packetizer_has_packets (base->packetizer)) {
1662       pret = PACKET_OK;
1663       /* Eat up all packets, really try to get last PCR(s) */
1664       while (pret != PACKET_NEED_MORE)
1665         pret = mpegts_packetizer_process_next_packet (base->packetizer);
1666
1667       if (base->packetizer->nb_seen_offsets > initial_pcr_seen) {
1668         GST_DEBUG ("Got last PCR(s) (total seen:%d)",
1669             base->packetizer->nb_seen_offsets);
1670         break;
1671       }
1672     }
1673   }
1674
1675 beach:
1676   mpegts_packetizer_clear (base->packetizer);
1677   return ret;
1678
1679 no_initial_pcr:
1680   mpegts_packetizer_clear (base->packetizer);
1681   GST_WARNING_OBJECT (base, "Couldn't find any PCR within the first %d bytes",
1682       10 * 65536);
1683   return GST_FLOW_OK;
1684 }
1685
1686
1687 static void
1688 mpegts_base_loop (MpegTSBase * base)
1689 {
1690   GstFlowReturn ret = GST_FLOW_ERROR;
1691
1692   switch (base->mode) {
1693     case BASE_MODE_SCANNING:
1694       /* Find first sync point */
1695       ret = mpegts_base_scan (base);
1696       if (G_UNLIKELY (ret != GST_FLOW_OK))
1697         goto error;
1698       base->mode = BASE_MODE_STREAMING;
1699       GST_DEBUG ("Changing to Streaming");
1700       break;
1701     case BASE_MODE_SEEKING:
1702       /* FIXME : unclear if we still need mode_seeking... */
1703       base->mode = BASE_MODE_STREAMING;
1704       break;
1705     case BASE_MODE_STREAMING:
1706     {
1707       GstBuffer *buf = NULL;
1708
1709       GST_DEBUG ("Pulling data from %" G_GUINT64_FORMAT, base->seek_offset);
1710
1711       if (G_UNLIKELY (base->last_seek_seqnum == GST_SEQNUM_INVALID)) {
1712         /* No configured seek, set a valid seqnum */
1713         base->last_seek_seqnum = gst_util_seqnum_next ();
1714       }
1715       ret = gst_pad_pull_range (base->sinkpad, base->seek_offset,
1716           100 * base->packetsize, &buf);
1717       if (G_UNLIKELY (ret != GST_FLOW_OK))
1718         goto error;
1719       base->seek_offset += gst_buffer_get_size (buf);
1720       ret = mpegts_base_chain (base->sinkpad, GST_OBJECT_CAST (base), buf);
1721       if (G_UNLIKELY (ret != GST_FLOW_OK))
1722         goto error;
1723     }
1724       break;
1725     case BASE_MODE_PUSHING:
1726       GST_WARNING ("wrong BASE_MODE_PUSHING mode in pull loop");
1727       break;
1728   }
1729
1730   return;
1731
1732 error:
1733   {
1734     GST_DEBUG_OBJECT (base, "Pausing task, reason %s", gst_flow_get_name (ret));
1735     if (ret == GST_FLOW_EOS) {
1736       if (!GST_MPEGTS_BASE_GET_CLASS (base)->push_event (base,
1737               gst_event_new_eos ()))
1738         GST_ELEMENT_ERROR (base, STREAM, FAILED,
1739             (_("Internal data stream error.")),
1740             ("No program activated before EOS"));
1741     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
1742       GST_ELEMENT_FLOW_ERROR (base, ret);
1743       GST_MPEGTS_BASE_GET_CLASS (base)->push_event (base, gst_event_new_eos ());
1744     }
1745     gst_pad_pause_task (base->sinkpad);
1746   }
1747 }
1748
1749
1750 gboolean
1751 mpegts_base_handle_seek_event (MpegTSBase * base, GstPad * pad,
1752     GstEvent * event)
1753 {
1754   MpegTSBaseClass *klass = GST_MPEGTS_BASE_GET_CLASS (base);
1755   GstFlowReturn ret = GST_FLOW_ERROR;
1756   gdouble rate;
1757   gboolean flush, instant_rate_change;
1758   GstFormat format;
1759   GstSeekFlags flags;
1760   GstSeekType start_type, stop_type;
1761   gint64 start, stop;
1762   GstEvent *flush_event = NULL;
1763
1764   gst_event_parse_seek (event, &rate, &format, &flags, &start_type, &start,
1765       &stop_type, &stop);
1766
1767   if (format != GST_FORMAT_TIME)
1768     return FALSE;
1769
1770   if (GST_EVENT_SEQNUM (event) == base->last_seek_seqnum) {
1771     GST_DEBUG_OBJECT (base, "Skipping already handled seek");
1772     return TRUE;
1773   }
1774
1775   if (base->mode == BASE_MODE_PUSHING) {
1776     /* First try if upstream supports seeking in TIME format */
1777     if (gst_pad_push_event (base->sinkpad, gst_event_ref (event))) {
1778       GST_DEBUG ("upstream handled SEEK event");
1779       return TRUE;
1780     }
1781
1782     /* If the subclass can seek, do that */
1783     if (klass->seek) {
1784       ret = klass->seek (base, event);
1785       if (G_UNLIKELY (ret != GST_FLOW_OK))
1786         GST_WARNING ("seeking failed %s", gst_flow_get_name (ret));
1787       else {
1788         GstEvent *new_seek;
1789
1790         if (GST_CLOCK_TIME_IS_VALID (base->seek_offset)) {
1791           base->mode = BASE_MODE_SEEKING;
1792           new_seek = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
1793               GST_SEEK_TYPE_SET, base->seek_offset, GST_SEEK_TYPE_NONE, -1);
1794           gst_event_set_seqnum (new_seek, GST_EVENT_SEQNUM (event));
1795           if (!gst_pad_push_event (base->sinkpad, new_seek))
1796             ret = GST_FLOW_ERROR;
1797           else
1798             base->last_seek_seqnum = GST_EVENT_SEQNUM (event);
1799         }
1800         base->mode = BASE_MODE_PUSHING;
1801       }
1802     } else {
1803       GST_WARNING ("subclass has no seek implementation");
1804     }
1805
1806     return ret == GST_FLOW_OK;
1807   }
1808
1809   if (!klass->seek) {
1810     GST_WARNING ("subclass has no seek implementation");
1811     return FALSE;
1812   }
1813
1814   if (rate <= 0.0) {
1815     GST_WARNING ("Negative rate not supported");
1816     return FALSE;
1817   }
1818
1819   GST_DEBUG ("seek event, rate: %f start: %" GST_TIME_FORMAT
1820       " stop: %" GST_TIME_FORMAT, rate, GST_TIME_ARGS (start),
1821       GST_TIME_ARGS (stop));
1822
1823   flush = ! !(flags & GST_SEEK_FLAG_FLUSH);
1824   instant_rate_change = ! !(flags & GST_SEEK_FLAG_INSTANT_RATE_CHANGE);
1825
1826   /* Directly send the instant-rate-change event here before taking the
1827    * stream-lock so that it can be applied as soon as possible */
1828   if (base->mode != BASE_MODE_PUSHING && instant_rate_change) {
1829     GstEvent *ev;
1830
1831     /* instant rate change only supported if direction does not change. All
1832      * other requirements are already checked before creating the seek event
1833      * but let's double-check here to be sure */
1834     if ((rate > 0 && base->out_segment.rate < 0) ||
1835         (rate < 0 && base->out_segment.rate > 0) ||
1836         start_type != GST_SEEK_TYPE_NONE ||
1837         stop_type != GST_SEEK_TYPE_NONE || flush) {
1838       GST_ERROR_OBJECT (base,
1839           "Instant rate change seeks only supported in the "
1840           "same direction, without flushing and position change");
1841       return FALSE;
1842     }
1843
1844     ev = gst_event_new_instant_rate_change (rate / base->out_segment.rate,
1845         (GstSegmentFlags) (flags));
1846     gst_event_set_seqnum (ev, GST_EVENT_SEQNUM (event));
1847     GST_MPEGTS_BASE_GET_CLASS (base)->push_event (base, ev);
1848     return TRUE;
1849   }
1850
1851   /* stop streaming, either by flushing or by pausing the task */
1852   base->mode = BASE_MODE_SEEKING;
1853   if (flush) {
1854     GST_DEBUG_OBJECT (base, "sending flush start");
1855     flush_event = gst_event_new_flush_start ();
1856     gst_event_set_seqnum (flush_event, GST_EVENT_SEQNUM (event));
1857     gst_pad_push_event (base->sinkpad, gst_event_ref (flush_event));
1858     GST_MPEGTS_BASE_GET_CLASS (base)->push_event (base, flush_event);
1859   } else
1860     gst_pad_pause_task (base->sinkpad);
1861
1862   /* wait for streaming to finish */
1863   GST_PAD_STREAM_LOCK (base->sinkpad);
1864
1865   if (flush) {
1866     /* send a FLUSH_STOP for the sinkpad, since we need data for seeking */
1867     GST_DEBUG_OBJECT (base, "sending flush stop");
1868     flush_event = gst_event_new_flush_stop (TRUE);
1869     gst_event_set_seqnum (flush_event, GST_EVENT_SEQNUM (event));
1870
1871     /* ref for it to be reused later */
1872     gst_pad_push_event (base->sinkpad, gst_event_ref (flush_event));
1873     /* And actually flush our pending data but allow to preserve some info
1874      * to perform the seek */
1875     mpegts_base_flush (base, FALSE);
1876     mpegts_packetizer_flush (base->packetizer, FALSE);
1877   }
1878
1879   if (flags & (GST_SEEK_FLAG_SEGMENT)) {
1880     GST_WARNING ("seek flags 0x%x are not supported", (int) flags);
1881     goto done;
1882   }
1883
1884
1885   /* If the subclass can seek, do that */
1886   ret = klass->seek (base, event);
1887   if (G_UNLIKELY (ret != GST_FLOW_OK))
1888     GST_WARNING ("seeking failed %s", gst_flow_get_name (ret));
1889   else
1890     base->last_seek_seqnum = GST_EVENT_SEQNUM (event);
1891
1892   if (flush_event) {
1893     /* if we sent a FLUSH_START, we now send a FLUSH_STOP */
1894     GST_DEBUG_OBJECT (base, "sending flush stop");
1895     GST_MPEGTS_BASE_GET_CLASS (base)->push_event (base, flush_event);
1896     flush_event = NULL;
1897   }
1898 done:
1899   if (flush_event)
1900     gst_event_unref (flush_event);
1901   gst_pad_start_task (base->sinkpad, (GstTaskFunction) mpegts_base_loop, base,
1902       NULL);
1903
1904   GST_PAD_STREAM_UNLOCK (base->sinkpad);
1905   return ret == GST_FLOW_OK;
1906 }
1907
1908
1909 static gboolean
1910 mpegts_base_sink_activate (GstPad * sinkpad, GstObject * parent)
1911 {
1912   GstQuery *query;
1913   gboolean pull_mode;
1914
1915   query = gst_query_new_scheduling ();
1916
1917   if (!gst_pad_peer_query (sinkpad, query)) {
1918     gst_query_unref (query);
1919     goto activate_push;
1920   }
1921
1922   pull_mode = gst_query_has_scheduling_mode_with_flags (query,
1923       GST_PAD_MODE_PULL, GST_SCHEDULING_FLAG_SEEKABLE);
1924   gst_query_unref (query);
1925
1926   if (!pull_mode)
1927     goto activate_push;
1928
1929   GST_DEBUG_OBJECT (sinkpad, "activating pull");
1930   return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
1931
1932 activate_push:
1933   {
1934     GST_DEBUG_OBJECT (sinkpad, "activating push");
1935     return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
1936   }
1937 }
1938
1939 static gboolean
1940 mpegts_base_sink_activate_mode (GstPad * pad, GstObject * parent,
1941     GstPadMode mode, gboolean active)
1942 {
1943   gboolean res;
1944   MpegTSBase *base = GST_MPEGTS_BASE (parent);
1945
1946   switch (mode) {
1947     case GST_PAD_MODE_PUSH:
1948       base->mode = BASE_MODE_PUSHING;
1949       res = TRUE;
1950       break;
1951     case GST_PAD_MODE_PULL:
1952       if (active) {
1953         base->mode = BASE_MODE_SCANNING;
1954         /* When working pull-based, we always use offsets for estimation */
1955         base->packetizer->calculate_offset = TRUE;
1956         base->packetizer->calculate_skew = FALSE;
1957         gst_segment_init (&base->segment, GST_FORMAT_BYTES);
1958         res =
1959             gst_pad_start_task (pad, (GstTaskFunction) mpegts_base_loop, base,
1960             NULL);
1961       } else
1962         res = gst_pad_stop_task (pad);
1963       break;
1964     default:
1965       res = FALSE;
1966       break;
1967   }
1968   return res;
1969 }
1970
1971 static GstStateChangeReturn
1972 mpegts_base_change_state (GstElement * element, GstStateChange transition)
1973 {
1974   MpegTSBase *base;
1975   GstStateChangeReturn ret;
1976
1977   base = GST_MPEGTS_BASE (element);
1978
1979   switch (transition) {
1980     case GST_STATE_CHANGE_READY_TO_PAUSED:
1981       mpegts_base_reset (base);
1982       break;
1983     default:
1984       break;
1985   }
1986
1987   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1988
1989   switch (transition) {
1990     case GST_STATE_CHANGE_PAUSED_TO_READY:
1991       mpegts_base_reset (base);
1992       if (base->mode != BASE_MODE_PUSHING)
1993         base->mode = BASE_MODE_SCANNING;
1994       break;
1995     default:
1996       break;
1997   }
1998
1999   return ret;
2000 }
2001
2002 gboolean
2003 gst_mpegtsbase_plugin_init (GstPlugin * plugin)
2004 {
2005   GST_DEBUG_CATEGORY_INIT (mpegts_base_debug, "mpegtsbase", 0,
2006       "MPEG transport stream base class");
2007
2008   return TRUE;
2009 }