Merge branch 'upstream/1.22.7' into tizen_gst_1.22.7
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / gst / mpegdemux / gstmpegdemux.c
1  /*
2   * This library is licensed under 2 different licenses and you
3   * can choose to use it under the terms of either one of them. The
4   * two licenses are the MPL 1.1 and the LGPL.
5   *
6   * MPL:
7   *
8   * The contents of this file are subject to the Mozilla Public License
9   * Version 1.1 (the "License"); you may not use this file except in
10   * compliance with the License. You may obtain a copy of the License at
11   * http://www.mozilla.org/MPL/.
12   *
13   * Software distributed under the License is distributed on an "AS IS"
14   * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
15   * License for the specific language governing rights and limitations
16   * under the License.
17   *
18   * LGPL:
19   *
20   * This library is free software; you can redistribute it and/or
21   * modify it under the terms of the GNU Library General Public
22   * License as published by the Free Software Foundation; either
23   * version 2 of the License, or (at your option) any later version.
24   *
25   * This library is distributed in the hope that it will be useful,
26   * but WITHOUT ANY WARRANTY; without even the implied warranty of
27   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
28   * Library General Public License for more details.
29   *
30   * You should have received a copy of the GNU Library General Public
31   * License along with this library; if not, write to the
32   * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
33   * Boston, MA 02110-1301, USA.
34   *
35   * The Original Code is Fluendo MPEG Demuxer plugin.
36   *
37   * The Initial Developer of the Original Code is Fluendo, S.L.
38   * Portions created by Fluendo, S.L. are Copyright (C) 2005
39   * Fluendo, S.L. All Rights Reserved.
40   *
41   * Contributor(s): Wim Taymans <wim@fluendo.com>
42   *                 Jan Schmidt <thaytan@noraisin.net>
43   */
44
45 #ifdef HAVE_CONFIG_H
46 #include "config.h"
47 #endif
48
49 #include <string.h>
50
51 #include <gst/tag/tag.h>
52 #include <gst/pbutils/pbutils.h>
53 #include <gst/base/gstbytereader.h>
54
55 #include "gstmpegdefs.h"
56 #include "gstmpegdemux.h"
57
58 #define BLOCK_SZ                    32768
59 #define SCAN_SCR_SZ                 12
60 #define SCAN_PTS_SZ                 80
61
62 #define DEFAULT_GAP_THRESHOLD (300*GST_MSECOND)
63 #define VIDEO_GAP_THRESHOLD   (500*GST_MSECOND)
64
65 #define DURATION_SCAN_LIMIT         4 * 1024 * 1024
66
67 typedef enum
68 {
69   SCAN_SCR,
70   SCAN_DTS,
71   SCAN_PTS
72 } SCAN_MODE;
73
74 /* We clamp scr delta with 0 so negative bytes won't be possible */
75 #define GSTTIME_TO_BYTES(time) \
76   ((time != -1) ? gst_util_uint64_scale (MAX(0,(gint64) (GSTTIME_TO_MPEGTIME(time))), demux->scr_rate_n, demux->scr_rate_d) : -1)
77 #define BYTES_TO_GSTTIME(bytes) ((bytes != -1) ? MPEGTIME_TO_GSTTIME(gst_util_uint64_scale (bytes, demux->scr_rate_d, demux->scr_rate_n)) : -1)
78
79 #define ADAPTER_OFFSET_FLUSH(_bytes_) demux->adapter_offset += (_bytes_)
80
81 GST_DEBUG_CATEGORY_STATIC (gstflupsdemux_debug);
82 #define GST_CAT_DEFAULT (gstflupsdemux_debug)
83
84 GST_DEBUG_CATEGORY_EXTERN (mpegpspesfilter_debug);
85
86 /* MPEG2Demux signals and args */
87 enum
88 {
89   /* FILL ME */
90   LAST_SIGNAL
91 };
92
93 enum
94 {
95   PROP_0,
96   PROP_IGNORE_SCR,
97   /* FILL ME */
98 };
99
100 #define DEFAULT_IGNORE_SCR FALSE
101
102 static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
103     GST_PAD_SINK,
104     GST_PAD_ALWAYS,
105     GST_STATIC_CAPS ("video/mpeg, "
106         "mpegversion = (int) { 1, 2 }, "
107         "systemstream = (boolean) TRUE;" "video/x-cdxa")
108     );
109
110 static GstStaticPadTemplate video_template =
111     GST_STATIC_PAD_TEMPLATE ("video_%02x",
112     GST_PAD_SRC,
113     GST_PAD_SOMETIMES,
114     GST_STATIC_CAPS ("video/mpeg, "
115         "mpegversion = (int) { 1, 2, 4 }, " "systemstream = (boolean) FALSE, "
116         "parsed = (boolean) FALSE; " "video/x-h264, "
117         "stream-format=(string)byte-stream; " "video/x-h265, "
118         "stream-format=(string)byte-stream;")
119     );
120
121 static GstStaticPadTemplate audio_template =
122     GST_STATIC_PAD_TEMPLATE ("audio_%02x",
123     GST_PAD_SRC,
124     GST_PAD_SOMETIMES,
125     GST_STATIC_CAPS ("audio/mpeg, mpegversion = (int) 1;"
126         "audio/mpeg, mpegversion = (int) 4, stream-format = (string) { adts, loas };"
127         "audio/x-private1-lpcm; "
128         "audio/x-private1-ac3;" "audio/x-private1-dts;" "audio/ac3")
129     );
130
131 static GstStaticPadTemplate subpicture_template =
132 GST_STATIC_PAD_TEMPLATE ("subpicture_%02x",
133     GST_PAD_SRC,
134     GST_PAD_SOMETIMES,
135     GST_STATIC_CAPS ("subpicture/x-dvd")
136     );
137
138 static GstStaticPadTemplate private_template =
139 GST_STATIC_PAD_TEMPLATE ("private_%d",
140     GST_PAD_SRC,
141     GST_PAD_SOMETIMES,
142     GST_STATIC_CAPS_ANY);
143
144 static void gst_ps_demux_base_init (GstPsDemuxClass * klass);
145 static void gst_ps_demux_class_init (GstPsDemuxClass * klass);
146 static void gst_ps_demux_init (GstPsDemux * demux);
147 static void gst_ps_demux_finalize (GstPsDemux * demux);
148 static void gst_ps_demux_set_property (GObject * object, guint prop_id,
149     const GValue * value, GParamSpec * pspec);
150 static void gst_ps_demux_get_property (GObject * object, guint prop_id,
151     GValue * value, GParamSpec * pspec);
152 static void gst_ps_demux_reset (GstPsDemux * demux);
153
154 static gboolean gst_ps_demux_sink_event (GstPad * pad, GstObject * parent,
155     GstEvent * event);
156 static GstFlowReturn gst_ps_demux_chain (GstPad * pad, GstObject * parent,
157     GstBuffer * buffer);
158 static gboolean gst_ps_demux_sink_activate (GstPad * sinkpad,
159     GstObject * parent);
160 static gboolean gst_ps_demux_sink_activate_mode (GstPad * pad,
161     GstObject * parent, GstPadMode mode, gboolean active);
162 static void gst_ps_demux_loop (GstPad * pad);
163
164 static gboolean gst_ps_demux_src_event (GstPad * pad, GstObject * parent,
165     GstEvent * event);
166 static gboolean gst_ps_demux_src_query (GstPad * pad, GstObject * parent,
167     GstQuery * query);
168
169 static GstStateChangeReturn gst_ps_demux_change_state (GstElement * element,
170     GstStateChange transition);
171
172 static inline gboolean gst_ps_demux_scan_forward_ts (GstPsDemux * demux,
173     guint64 * pos, SCAN_MODE mode, guint64 * rts, gint limit);
174 static inline gboolean gst_ps_demux_scan_backward_ts (GstPsDemux * demux,
175     guint64 * pos, SCAN_MODE mode, guint64 * rts, gint limit);
176
177 static inline void gst_ps_demux_send_gap_updates (GstPsDemux * demux,
178     GstClockTime new_time);
179 static inline void gst_ps_demux_clear_times (GstPsDemux * demux);
180
181 static void gst_ps_demux_reset_psm (GstPsDemux * demux);
182 static void gst_ps_demux_flush (GstPsDemux * demux);
183
184 static GstElementClass *parent_class = NULL;
185
186 static void gst_segment_set_position (GstSegment * segment, GstFormat format,
187     guint64 position);
188 static void gst_segment_set_duration (GstSegment * segment, GstFormat format,
189     guint64 duration);
190
191 /*static guint gst_ps_demux_signals[LAST_SIGNAL] = { 0 };*/
192
193 GType
194 gst_ps_demux_get_type (void)
195 {
196   static GType ps_demux_type = 0;
197
198   if (!ps_demux_type) {
199     static const GTypeInfo ps_demux_info = {
200       sizeof (GstPsDemuxClass),
201       (GBaseInitFunc) gst_ps_demux_base_init,
202       NULL,
203       (GClassInitFunc) gst_ps_demux_class_init,
204       NULL,
205       NULL,
206       sizeof (GstPsDemux),
207       0,
208       (GInstanceInitFunc) gst_ps_demux_init,
209       NULL
210     };
211
212     ps_demux_type =
213         g_type_register_static (GST_TYPE_ELEMENT, "GstMpegPSDemux",
214         &ps_demux_info, 0);
215
216     GST_DEBUG_CATEGORY_INIT (gstflupsdemux_debug, "mpegpsdemux", 0,
217         "MPEG program stream demultiplexer element");
218   }
219
220   return ps_demux_type;
221 }
222
223 GST_ELEMENT_REGISTER_DEFINE_WITH_CODE (mpegpsdemux, "mpegpsdemux",
224     GST_RANK_PRIMARY, GST_TYPE_PS_DEMUX,
225     GST_DEBUG_CATEGORY_INIT (mpegpspesfilter_debug, "mpegpspesfilter", 0,
226         "MPEG-PS PES filter"));
227
228 static void
229 gst_ps_demux_base_init (GstPsDemuxClass * klass)
230 {
231   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
232
233   klass->sink_template = gst_static_pad_template_get (&sink_template);
234   klass->video_template = gst_static_pad_template_get (&video_template);
235   klass->audio_template = gst_static_pad_template_get (&audio_template);
236   klass->subpicture_template =
237       gst_static_pad_template_get (&subpicture_template);
238   klass->private_template = gst_static_pad_template_get (&private_template);
239
240   gst_element_class_add_pad_template (element_class, klass->video_template);
241   gst_element_class_add_pad_template (element_class, klass->audio_template);
242   gst_element_class_add_pad_template (element_class,
243       klass->subpicture_template);
244   gst_element_class_add_pad_template (element_class, klass->private_template);
245   gst_element_class_add_pad_template (element_class, klass->sink_template);
246
247   gst_element_class_set_static_metadata (element_class,
248       "MPEG Program Stream Demuxer", "Codec/Demuxer",
249       "Demultiplexes MPEG Program Streams", "Wim Taymans <wim@fluendo.com>");
250 }
251
252 static void
253 gst_ps_demux_class_init (GstPsDemuxClass * klass)
254 {
255   GObjectClass *gobject_class;
256   GstElementClass *gstelement_class;
257
258   parent_class = g_type_class_ref (GST_TYPE_ELEMENT);
259
260   gobject_class = (GObjectClass *) klass;
261   gstelement_class = (GstElementClass *) klass;
262
263   gobject_class->finalize = (GObjectFinalizeFunc) gst_ps_demux_finalize;
264   gobject_class->set_property = gst_ps_demux_set_property;
265   gobject_class->get_property = gst_ps_demux_get_property;
266
267   gstelement_class->change_state = gst_ps_demux_change_state;
268
269   /**
270    * GstPsDemux:ignore-scr:
271    *
272    * Ignore SCR (System Clock Reference) data from MPEG-PS Pack Header.
273    * This can help with playback of some broken files.
274    *
275    * Since: 1.18
276    */
277   g_object_class_install_property (gobject_class, PROP_IGNORE_SCR,
278       g_param_spec_boolean ("ignore-scr", "Ignore SCR data for timing",
279           "Ignore SCR data for timing", DEFAULT_IGNORE_SCR,
280           G_PARAM_READWRITE | GST_PARAM_MUTABLE_READY |
281           G_PARAM_STATIC_STRINGS));
282 }
283
284 static void
285 gst_ps_demux_init (GstPsDemux * demux)
286 {
287   GstPsDemuxClass *klass = GST_PS_DEMUX_GET_CLASS (demux);
288
289   demux->sinkpad = gst_pad_new_from_template (klass->sink_template, "sink");
290   gst_pad_set_event_function (demux->sinkpad,
291       GST_DEBUG_FUNCPTR (gst_ps_demux_sink_event));
292   gst_pad_set_chain_function (demux->sinkpad,
293       GST_DEBUG_FUNCPTR (gst_ps_demux_chain));
294   gst_pad_set_activate_function (demux->sinkpad,
295       GST_DEBUG_FUNCPTR (gst_ps_demux_sink_activate));
296   gst_pad_set_activatemode_function (demux->sinkpad,
297       GST_DEBUG_FUNCPTR (gst_ps_demux_sink_activate_mode));
298
299   gst_element_add_pad (GST_ELEMENT (demux), demux->sinkpad);
300
301   demux->streams =
302       g_malloc0 (sizeof (GstPsStream *) * (GST_PS_DEMUX_MAX_STREAMS));
303   demux->streams_found =
304       g_malloc0 (sizeof (GstPsStream *) * (GST_PS_DEMUX_MAX_STREAMS));
305   demux->found_count = 0;
306
307   demux->adapter = gst_adapter_new ();
308   demux->rev_adapter = gst_adapter_new ();
309   demux->flowcombiner = gst_flow_combiner_new ();
310
311   gst_ps_demux_reset (demux);
312
313   demux->ignore_scr = DEFAULT_IGNORE_SCR;
314 }
315
316 static void
317 gst_ps_demux_finalize (GstPsDemux * demux)
318 {
319   gst_ps_demux_reset (demux);
320   g_free (demux->streams);
321   g_free (demux->streams_found);
322
323   gst_flow_combiner_free (demux->flowcombiner);
324   g_object_unref (demux->adapter);
325   g_object_unref (demux->rev_adapter);
326
327   G_OBJECT_CLASS (parent_class)->finalize (G_OBJECT (demux));
328 }
329
330 static void
331 gst_ps_demux_set_property (GObject * object, guint prop_id,
332     const GValue * value, GParamSpec * pspec)
333 {
334   GstPsDemux *demux = GST_PS_DEMUX (object);
335
336   switch (prop_id) {
337     case PROP_IGNORE_SCR:
338       demux->ignore_scr = g_value_get_boolean (value);
339       break;
340     default:
341       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
342   }
343 }
344
345 static void
346 gst_ps_demux_get_property (GObject * object, guint prop_id,
347     GValue * value, GParamSpec * pspec)
348 {
349   GstPsDemux *demux = GST_PS_DEMUX (object);
350
351   switch (prop_id) {
352     case PROP_IGNORE_SCR:
353       g_value_set_boolean (value, demux->ignore_scr);
354       break;
355     default:
356       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
357   }
358 }
359
360 static void
361 gst_ps_demux_reset (GstPsDemux * demux)
362 {
363   /* Clean up the streams and pads we allocated */
364   gint i;
365
366   for (i = 0; i < GST_PS_DEMUX_MAX_STREAMS; i++) {
367     GstPsStream *stream = demux->streams[i];
368
369     if (stream != NULL) {
370       if (stream->pad && GST_PAD_PARENT (stream->pad)) {
371         gst_flow_combiner_remove_pad (demux->flowcombiner, stream->pad);
372         gst_element_remove_pad (GST_ELEMENT_CAST (demux), stream->pad);
373       } else {
374         gst_object_unref (stream->pad);
375       }
376
377       if (stream->pending_tags)
378         gst_tag_list_unref (stream->pending_tags);
379       g_free (stream);
380       demux->streams[i] = NULL;
381     }
382   }
383   memset (demux->streams_found, 0,
384       sizeof (GstPsStream *) * (GST_PS_DEMUX_MAX_STREAMS));
385   demux->found_count = 0;
386
387   gst_adapter_clear (demux->adapter);
388   gst_adapter_clear (demux->rev_adapter);
389
390   demux->adapter_offset = G_MAXUINT64;
391   demux->first_scr = G_MAXUINT64;
392   demux->last_scr = G_MAXUINT64;
393   demux->current_scr = G_MAXUINT64;
394   demux->base_time = G_MAXUINT64;
395   demux->scr_rate_n = G_MAXUINT64;
396   demux->scr_rate_d = G_MAXUINT64;
397   demux->first_pts = G_MAXUINT64;
398   demux->last_pts = G_MAXUINT64;
399   demux->mux_rate = G_MAXUINT64;
400   demux->next_pts = G_MAXUINT64;
401   demux->next_dts = G_MAXUINT64;
402   demux->need_no_more_pads = TRUE;
403   gst_ps_demux_reset_psm (demux);
404   gst_segment_init (&demux->sink_segment, GST_FORMAT_UNDEFINED);
405   gst_segment_init (&demux->src_segment, GST_FORMAT_TIME);
406   gst_ps_demux_flush (demux);
407   demux->have_group_id = FALSE;
408   demux->group_id = G_MAXUINT;
409 }
410
411 static GstPsStream *
412 gst_ps_demux_create_stream (GstPsDemux * demux, gint id, gint stream_type,
413     gint layer)
414 {
415   GstPsStream *stream;
416   GstPadTemplate *template;
417   gchar *name;
418   GstPsDemuxClass *klass = GST_PS_DEMUX_GET_CLASS (demux);
419   GstCaps *caps;
420   GstClockTime gap_threshold = DEFAULT_GAP_THRESHOLD;
421   GstEvent *event;
422   gchar *stream_id;
423
424   name = NULL;
425   template = NULL;
426   caps = NULL;
427
428   GST_DEBUG_OBJECT (demux, "create stream id 0x%02x, type 0x%02x", id,
429       stream_type);
430
431   switch (stream_type) {
432     case ST_VIDEO_MPEG1:
433     case ST_VIDEO_MPEG2:
434     case ST_VIDEO_MPEG4:
435     case ST_GST_VIDEO_MPEG1_OR_2:
436     {
437       gint mpeg_version = 1;
438       if (stream_type == ST_VIDEO_MPEG2 ||
439           (stream_type == ST_GST_VIDEO_MPEG1_OR_2 && demux->is_mpeg2_pack)) {
440         mpeg_version = 2;
441       }
442       if (stream_type == ST_VIDEO_MPEG4) {
443         mpeg_version = 4;
444       }
445
446       template = klass->video_template;
447       name = g_strdup_printf ("video_%02x", id);
448       caps = gst_caps_new_simple ("video/mpeg",
449           "mpegversion", G_TYPE_INT, mpeg_version,
450           "systemstream", G_TYPE_BOOLEAN, FALSE,
451           "parsed", G_TYPE_BOOLEAN, FALSE, NULL);
452       gap_threshold = VIDEO_GAP_THRESHOLD;
453       break;
454     }
455     case ST_AUDIO_MPEG1:
456     case ST_AUDIO_MPEG2:
457       template = klass->audio_template;
458       name = g_strdup_printf ("audio_%02x", id);
459       if (layer) {
460         caps = gst_caps_new_simple ("audio/mpeg",
461             "mpegversion", G_TYPE_INT, 1, "layer", G_TYPE_INT, layer, NULL);
462       } else {
463         caps = gst_caps_new_simple ("audio/mpeg",
464             "mpegversion", G_TYPE_INT, 1, NULL);
465       }
466       break;
467     case ST_PRIVATE_SECTIONS:
468     case ST_PRIVATE_DATA:
469     case ST_MHEG:
470     case ST_DSMCC:
471       break;
472     case ST_AUDIO_AAC_ADTS:
473       template = klass->audio_template;
474       name = g_strdup_printf ("audio_%02x", id);
475       caps = gst_caps_new_simple ("audio/mpeg",
476           "mpegversion", G_TYPE_INT, 4,
477           "stream-format", G_TYPE_STRING, "adts", NULL);
478       break;
479     case ST_AUDIO_AAC_LOAS:    // LATM/LOAS AAC syntax
480       template = klass->audio_template;
481       name = g_strdup_printf ("audio_%02x", id);
482       caps = gst_caps_new_simple ("audio/mpeg",
483           "mpegversion", G_TYPE_INT, 4,
484           "stream-format", G_TYPE_STRING, "loas", NULL);
485       break;
486     case ST_VIDEO_H264:
487       template = klass->video_template;
488       name = g_strdup_printf ("video_%02x", id);
489       caps = gst_caps_new_simple ("video/x-h264",
490           "stream-format", G_TYPE_STRING, "byte-stream", NULL);
491       gap_threshold = VIDEO_GAP_THRESHOLD;
492       break;
493     case ST_VIDEO_H265:
494       template = klass->video_template;
495       name = g_strdup_printf ("video_%02x", id);
496       caps = gst_caps_new_simple ("video/x-h265",
497           "stream-format", G_TYPE_STRING, "byte-stream", NULL);
498       gap_threshold = VIDEO_GAP_THRESHOLD;
499       break;
500
501     case ST_PS_AUDIO_AC3:
502       template = klass->audio_template;
503       name = g_strdup_printf ("audio_%02x", id);
504       caps = gst_caps_new_empty_simple ("audio/x-private1-ac3");
505       break;
506     case ST_PS_AUDIO_DTS:
507       template = klass->audio_template;
508       name = g_strdup_printf ("audio_%02x", id);
509       caps = gst_caps_new_empty_simple ("audio/x-private1-dts");
510       break;
511     case ST_PS_AUDIO_LPCM:
512       template = klass->audio_template;
513       name = g_strdup_printf ("audio_%02x", id);
514       caps = gst_caps_new_empty_simple ("audio/x-private1-lpcm");
515       break;
516     case ST_PS_DVD_SUBPICTURE:
517       template = klass->subpicture_template;
518       name = g_strdup_printf ("subpicture_%02x", id);
519       caps = gst_caps_new_empty_simple ("subpicture/x-dvd");
520       break;
521     case ST_GST_AUDIO_RAWA52:
522       template = klass->audio_template;
523       name = g_strdup_printf ("audio_%02x", id);
524       caps = gst_caps_new_empty_simple ("audio/ac3");
525       break;
526     default:
527       break;
528   }
529
530   if (name == NULL || template == NULL || caps == NULL) {
531     g_free (name);
532     if (caps)
533       gst_caps_unref (caps);
534     return FALSE;
535   }
536
537   stream = g_new0 (GstPsStream, 1);
538   stream->id = id;
539   stream->discont = TRUE;
540   stream->need_segment = TRUE;
541   stream->notlinked = FALSE;
542   stream->type = stream_type;
543   stream->pending_tags = NULL;
544   stream->pad = gst_pad_new_from_template (template, name);
545   stream->gap_threshold = gap_threshold;
546   stream->nb_out_buffers = 0;
547   stream->gap_ref_buffers = 0;
548   stream->gap_ref_pts = GST_CLOCK_TIME_NONE;
549
550   gst_pad_set_event_function (stream->pad,
551       GST_DEBUG_FUNCPTR (gst_ps_demux_src_event));
552   gst_pad_set_query_function (stream->pad,
553       GST_DEBUG_FUNCPTR (gst_ps_demux_src_query));
554   gst_pad_use_fixed_caps (stream->pad);
555
556   /* needed for set_caps to work */
557   if (!gst_pad_set_active (stream->pad, TRUE)) {
558     GST_WARNING_OBJECT (demux, "Failed to activate pad %" GST_PTR_FORMAT,
559         stream->pad);
560   }
561
562   stream_id =
563       gst_pad_create_stream_id_printf (stream->pad, GST_ELEMENT_CAST (demux),
564       "%02x", id);
565
566   event = gst_pad_get_sticky_event (demux->sinkpad, GST_EVENT_STREAM_START, 0);
567   if (event) {
568     if (gst_event_parse_group_id (event, &demux->group_id))
569       demux->have_group_id = TRUE;
570     else
571       demux->have_group_id = FALSE;
572     gst_event_unref (event);
573   } else if (!demux->have_group_id) {
574     demux->have_group_id = TRUE;
575     demux->group_id = gst_util_group_id_next ();
576   }
577   event = gst_event_new_stream_start (stream_id);
578   if (demux->have_group_id)
579     gst_event_set_group_id (event, demux->group_id);
580
581   gst_pad_push_event (stream->pad, event);
582   g_free (stream_id);
583
584   gst_pad_set_caps (stream->pad, caps);
585
586   if (!stream->pending_tags)
587     stream->pending_tags = gst_tag_list_new_empty ();
588   gst_pb_utils_add_codec_description_to_tag_list (stream->pending_tags, NULL,
589       caps);
590
591   GST_DEBUG_OBJECT (demux, "create pad %s, caps %" GST_PTR_FORMAT, name, caps);
592   gst_caps_unref (caps);
593   g_free (name);
594
595   return stream;
596 }
597
598 static GstPsStream *
599 gst_ps_demux_get_stream (GstPsDemux * demux, gint id, gint type, gint layer)
600 {
601   GstPsStream *stream = demux->streams[id];
602
603   if (stream == NULL) {
604     if (!(stream = gst_ps_demux_create_stream (demux, id, type, layer)))
605       goto unknown_stream;
606
607     GST_DEBUG_OBJECT (demux, "adding pad for stream id 0x%02x type 0x%02x", id,
608         type);
609
610     demux->streams[id] = stream;
611     demux->streams_found[demux->found_count++] = stream;
612
613     if (demux->need_no_more_pads) {
614       gst_element_add_pad (GST_ELEMENT (demux), stream->pad);
615       gst_flow_combiner_add_pad (demux->flowcombiner, stream->pad);
616     } else {
617       /* only likely to confuse decodebin etc, so discard */
618       /* FIXME should perform full switch protocol:
619        * add a whole new set of pads, drop old and no-more-pads again */
620       GST_DEBUG_OBJECT (demux,
621           "but already signalled no-more-pads; not adding");
622       gst_object_ref_sink (stream->pad);
623     }
624   }
625   return stream;
626
627   /* ERROR */
628 unknown_stream:
629   {
630     GST_DEBUG_OBJECT (demux, "unknown stream id 0x%02x type 0x%02x", id, type);
631     return NULL;
632   }
633 }
634
635 static GstPsStream *
636 gst_ps_demux_get_stream_from_pad (GstPsDemux * demux, GstPad * srcpad)
637 {
638   gint i, count;
639
640   count = demux->found_count;
641   for (i = 0; i < count; i++) {
642     GstPsStream *stream = demux->streams_found[i];
643
644     if (stream && stream->pad == srcpad)
645       return stream;
646   }
647
648   GST_DEBUG_OBJECT (srcpad, "no stream found for pad!");
649   return NULL;
650 }
651
652 static inline void
653 gst_ps_demux_send_segment (GstPsDemux * demux, GstPsStream * stream,
654     GstClockTime pts)
655 {
656   /* discont */
657   if (G_UNLIKELY (stream->need_segment)) {
658     GstSegment segment;
659     GstEvent *segment_event;
660
661     GST_DEBUG ("PTS timestamp:%" GST_TIME_FORMAT " base_time %" GST_TIME_FORMAT
662         " src_segment.start:%" GST_TIME_FORMAT " .stop:%" GST_TIME_FORMAT,
663         GST_TIME_ARGS (pts), GST_TIME_ARGS (demux->base_time),
664         GST_TIME_ARGS (demux->src_segment.start),
665         GST_TIME_ARGS (demux->src_segment.stop));
666
667     /* we should be in sync with downstream, so start from our segment notion,
668      * which also includes proper base_time etc, tweak it a bit and send */
669     gst_segment_copy_into (&demux->src_segment, &segment);
670     if (GST_CLOCK_TIME_IS_VALID (demux->base_time)) {
671       if (GST_CLOCK_TIME_IS_VALID (segment.start))
672         segment.start += demux->base_time;
673       if (GST_CLOCK_TIME_IS_VALID (segment.stop))
674         segment.stop += demux->base_time;
675       segment.time = segment.start - demux->base_time;
676     }
677
678     segment_event = gst_event_new_segment (&segment);
679     if (demux->segment_seqnum)
680       gst_event_set_seqnum (segment_event, demux->segment_seqnum);
681     else
682       demux->segment_seqnum = gst_event_get_seqnum (segment_event);
683     GST_INFO_OBJECT (demux, "sending segment event %" GST_SEGMENT_FORMAT
684         " to pad %" GST_PTR_FORMAT, &segment, stream->pad);
685
686     gst_pad_push_event (stream->pad, segment_event);
687
688     stream->need_segment = FALSE;
689   }
690
691   if (G_UNLIKELY (stream->pending_tags)) {
692     GST_DEBUG_OBJECT (demux, "Sending pending_tags %p for pad %s:%s : %"
693         GST_PTR_FORMAT, stream->pending_tags,
694         GST_DEBUG_PAD_NAME (stream->pad), stream->pending_tags);
695     gst_pad_push_event (stream->pad, gst_event_new_tag (stream->pending_tags));
696     stream->pending_tags = NULL;
697   }
698 }
699
700 static GstFlowReturn
701 gst_ps_demux_send_data (GstPsDemux * demux, GstPsStream * stream,
702     GstBuffer * buf)
703 {
704   GstFlowReturn result;
705   GstClockTime pts = GST_CLOCK_TIME_NONE, dts = GST_CLOCK_TIME_NONE;
706   GstClockTime ts;
707
708   if (stream == NULL)
709     goto no_stream;
710
711   /* timestamps */
712   if (G_UNLIKELY (demux->next_pts != G_MAXUINT64))
713     pts = MPEGTIME_TO_GSTTIME (demux->next_pts);
714   if (G_UNLIKELY (demux->next_dts != G_MAXUINT64))
715     dts = MPEGTIME_TO_GSTTIME (demux->next_dts);
716
717   gst_ps_demux_send_segment (demux, stream, pts);
718
719   /* Ignores DTS if PTS < DTS. Maybe additional sanity checking is possible
720    * by comparing 33bits timestap rollover case, but PTS < DTS is already
721    * invalid case */
722   if (GST_CLOCK_TIME_IS_VALID (pts) && GST_CLOCK_TIME_IS_VALID (dts) &&
723       dts > pts) {
724     GST_WARNING_OBJECT (demux, "PTS (%" GST_TIME_FORMAT ") < DTS (%"
725         GST_TIME_FORMAT ")", GST_TIME_ARGS (pts), GST_TIME_ARGS (dts));
726     dts = GST_CLOCK_TIME_NONE;
727   }
728
729   /* OK, sent new segment now prepare the buffer for sending */
730   GST_BUFFER_PTS (buf) = pts;
731   GST_BUFFER_DTS (buf) = dts;
732
733   /* If we have no DTS but a PTS that means both are the same,
734    * if we have neither than we don't know the current position */
735   ts = dts;
736   if (ts == GST_CLOCK_TIME_NONE)
737     ts = pts;
738
739   /* update position in the segment */
740   if (ts != GST_CLOCK_TIME_NONE && (stream->last_ts == GST_CLOCK_TIME_NONE
741           || stream->last_ts < ts)) {
742     GST_LOG_OBJECT (demux,
743         "last_ts update on pad %s to time %" GST_TIME_FORMAT
744         ", current scr is %" GST_TIME_FORMAT, GST_PAD_NAME (stream->pad),
745         GST_TIME_ARGS (ts),
746         GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (demux->current_scr)));
747     stream->last_ts = ts;
748     if (demux->src_segment.position == GST_CLOCK_TIME_NONE
749         || stream->last_ts > demux->src_segment.position)
750       gst_segment_set_position (&demux->src_segment, GST_FORMAT_TIME,
751           stream->last_ts);
752   }
753
754   /* Set the buffer discont flag, and clear discont state on the stream */
755   if (stream->discont) {
756     GST_DEBUG_OBJECT (demux, "discont buffer to pad %" GST_PTR_FORMAT
757         " with PTS %" GST_TIME_FORMAT " DTS %" GST_TIME_FORMAT,
758         stream->pad, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts));
759     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
760
761     stream->discont = FALSE;
762   } else {
763     GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DISCONT);
764   }
765
766   demux->next_pts = G_MAXUINT64;
767   demux->next_dts = G_MAXUINT64;
768
769   GST_LOG_OBJECT (demux, "pushing stream id 0x%02x type 0x%02x, pts time: %"
770       GST_TIME_FORMAT ", size %" G_GSIZE_FORMAT,
771       stream->id, stream->type, GST_TIME_ARGS (pts), gst_buffer_get_size (buf));
772   result = gst_pad_push (stream->pad, buf);
773   stream->nb_out_buffers += 1;
774
775   GST_LOG_OBJECT (demux, "result: %s", gst_flow_get_name (result));
776
777   return result;
778
779   /* ERROR */
780 no_stream:
781   {
782     GST_DEBUG_OBJECT (demux, "no stream given");
783     gst_buffer_unref (buf);
784     return GST_FLOW_OK;
785   }
786 }
787
788 static inline void
789 gst_ps_demux_mark_discont (GstPsDemux * demux, gboolean discont,
790     gboolean need_segment)
791 {
792   gint i, count = demux->found_count;
793
794   /* mark discont on all streams */
795   for (i = 0; i < count; i++) {
796     GstPsStream *stream = demux->streams_found[i];
797
798     if (G_LIKELY (stream)) {
799       stream->discont |= discont;
800       stream->need_segment |= need_segment;
801       if (need_segment)
802         demux->segment_seqnum = 0;
803       GST_DEBUG_OBJECT (demux, "marked stream as discont %d, need_segment %d",
804           stream->discont, stream->need_segment);
805     }
806   }
807 }
808
809 static gboolean
810 gst_ps_demux_send_event (GstPsDemux * demux, GstEvent * event)
811 {
812   gint i, count = demux->found_count;
813   gboolean ret = FALSE;
814
815   for (i = 0; i < count; i++) {
816     GstPsStream *stream = demux->streams_found[i];
817
818     if (stream) {
819       if (!gst_pad_push_event (stream->pad, gst_event_ref (event))) {
820         GST_DEBUG_OBJECT (stream->pad, "%s event was not handled",
821             GST_EVENT_TYPE_NAME (event));
822       } else {
823         /* If at least one push returns TRUE, then we return TRUE. */
824         GST_DEBUG_OBJECT (stream->pad, "%s event was handled",
825             GST_EVENT_TYPE_NAME (event));
826         ret = TRUE;
827       }
828     }
829   }
830
831   gst_event_unref (event);
832   return ret;
833 }
834
835 static gboolean
836 gst_ps_demux_handle_dvd_event (GstPsDemux * demux, GstEvent * event)
837 {
838   const GstStructure *structure = gst_event_get_structure (event);
839   const char *type = gst_structure_get_string (structure, "event");
840   gint i;
841   gchar cur_stream_name[32];
842   GstPsStream *temp = NULL;
843   const gchar *lang_code;
844
845   if (strcmp (type, "dvd-lang-codes") == 0) {
846     GST_DEBUG_OBJECT (demux, "Handling language codes event");
847
848     /* Create a video pad to ensure have it before emit no more pads */
849     (void) gst_ps_demux_get_stream (demux, 0xe0, ST_VIDEO_MPEG2, 0);
850
851     /* Read out the languages for audio streams and request each one that
852      * is present */
853     for (i = 0; i < MAX_DVD_AUDIO_STREAMS; i++) {
854       gint stream_format;
855       gint stream_id;
856
857       g_snprintf (cur_stream_name, 32, "audio-%d-format", i);
858       if (!gst_structure_get_int (structure, cur_stream_name, &stream_format))
859         continue;
860
861       g_snprintf (cur_stream_name, 32, "audio-%d-stream", i);
862       if (!gst_structure_get_int (structure, cur_stream_name, &stream_id))
863         continue;
864       if (stream_id < 0 || stream_id >= MAX_DVD_AUDIO_STREAMS)
865         continue;
866
867       switch (stream_format) {
868         case 0x0:
869           /* AC3 */
870           stream_id += 0x80;
871           GST_DEBUG_OBJECT (demux,
872               "Audio stream %d format %d ID 0x%02x - AC3", i,
873               stream_format, stream_id);
874           temp = gst_ps_demux_get_stream (demux, stream_id, ST_PS_AUDIO_AC3, 0);
875           break;
876         case 0x2:
877         case 0x3:
878           /* MPEG audio without and with extension stream are
879            * treated the same */
880           stream_id += 0xC0;
881           GST_DEBUG_OBJECT (demux,
882               "Audio stream %d format %d ID 0x%02x - MPEG audio", i,
883               stream_format, stream_id);
884           temp = gst_ps_demux_get_stream (demux, stream_id, ST_AUDIO_MPEG1, 0);
885           break;
886         case 0x4:
887           /* LPCM */
888           stream_id += 0xA0;
889           GST_DEBUG_OBJECT (demux,
890               "Audio stream %d format %d ID 0x%02x - DVD LPCM", i,
891               stream_format, stream_id);
892           temp =
893               gst_ps_demux_get_stream (demux, stream_id, ST_PS_AUDIO_LPCM, 0);
894           break;
895         case 0x6:
896           /* DTS */
897           stream_id += 0x88;
898           GST_DEBUG_OBJECT (demux,
899               "Audio stream %d format %d ID 0x%02x - DTS", i,
900               stream_format, stream_id);
901           temp = gst_ps_demux_get_stream (demux, stream_id, ST_PS_AUDIO_DTS, 0);
902           break;
903         case 0x7:
904           /* FIXME: What range is SDDS? */
905         default:
906           GST_WARNING_OBJECT (demux,
907               "Unknown audio stream format in language code event: %d",
908               stream_format);
909           temp = NULL;
910           continue;
911       }
912
913       if (temp == NULL)
914         continue;
915
916       g_snprintf (cur_stream_name, 32, "audio-%d-language", i);
917       lang_code = gst_structure_get_string (structure, cur_stream_name);
918       if (lang_code) {
919         GstTagList *list = temp->pending_tags;
920
921         if (!list)
922           list = gst_tag_list_new_empty ();
923         gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
924             GST_TAG_LANGUAGE_CODE, lang_code, NULL);
925         temp->pending_tags = list;
926       }
927     }
928
929     /* And subtitle streams */
930     for (i = 0; i < MAX_DVD_SUBPICTURE_STREAMS; i++) {
931       gint stream_id;
932
933       g_snprintf (cur_stream_name, 32, "subpicture-%d-format", i);
934       if (!gst_structure_get_int (structure, cur_stream_name, &stream_id))
935         continue;
936
937       g_snprintf (cur_stream_name, 32, "subpicture-%d-stream", i);
938       if (!gst_structure_get_int (structure, cur_stream_name, &stream_id))
939         continue;
940       if (stream_id < 0 || stream_id >= MAX_DVD_SUBPICTURE_STREAMS)
941         continue;
942
943       GST_DEBUG_OBJECT (demux, "Subpicture stream %d ID 0x%02x", i,
944           0x20 + stream_id);
945
946       /* Retrieve the subpicture stream to force pad creation */
947       temp = gst_ps_demux_get_stream (demux, 0x20 + stream_id,
948           ST_PS_DVD_SUBPICTURE, 0);
949       if (temp == NULL)
950         continue;
951
952       g_snprintf (cur_stream_name, 32, "subpicture-%d-language", i);
953       lang_code = gst_structure_get_string (structure, cur_stream_name);
954       if (lang_code) {
955         GstTagList *list = temp->pending_tags;
956
957         if (!list)
958           list = gst_tag_list_new_empty ();
959         gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
960             GST_TAG_LANGUAGE_CODE, lang_code, NULL);
961         temp->pending_tags = list;
962       }
963     }
964
965     GST_DEBUG_OBJECT (demux, "Created all pads from Language Codes event, "
966         "signalling no-more-pads");
967
968     gst_element_no_more_pads (GST_ELEMENT (demux));
969     demux->need_no_more_pads = FALSE;
970   } else {
971     /* forward to all pads, e.g. dvd clut event */
972     gst_event_ref (event);
973     gst_ps_demux_send_event (demux, event);
974   }
975
976   gst_event_unref (event);
977   return TRUE;
978 }
979
980 static void
981 gst_ps_demux_flush (GstPsDemux * demux)
982 {
983   GST_DEBUG_OBJECT (demux, "flushing demuxer");
984   gst_adapter_clear (demux->adapter);
985   gst_adapter_clear (demux->rev_adapter);
986   gst_pes_filter_drain (&demux->filter);
987   gst_ps_demux_clear_times (demux);
988   demux->adapter_offset = G_MAXUINT64;
989   demux->current_scr = G_MAXUINT64;
990   demux->bytes_since_scr = 0;
991 }
992
993 static inline void
994 gst_ps_demux_clear_times (GstPsDemux * demux)
995 {
996   gint i, count = demux->found_count;
997
998   gst_flow_combiner_reset (demux->flowcombiner);
999   /* Clear the last ts for all streams */
1000   for (i = 0; i < count; i++) {
1001     GstPsStream *stream = demux->streams_found[i];
1002
1003     if (G_LIKELY (stream)) {
1004       stream->last_ts = GST_CLOCK_TIME_NONE;
1005     }
1006   }
1007 }
1008
1009 static inline void
1010 gst_ps_demux_send_gap_updates (GstPsDemux * demux, GstClockTime time)
1011 {
1012   GstClockTime base_time, stop;
1013   gint i, count = demux->found_count;
1014   GstEvent *event = NULL;
1015
1016   if (time == GST_CLOCK_TIME_NONE)
1017     return;
1018
1019   /* Advance all lagging streams by sending a gap event */
1020   if ((base_time = demux->base_time) == GST_CLOCK_TIME_NONE)
1021     base_time = 0;
1022
1023   stop = demux->src_segment.stop;
1024   if (stop != GST_CLOCK_TIME_NONE)
1025     stop += base_time;
1026
1027   if (time > stop)
1028     return;
1029
1030   /* FIXME: Handle reverse playback */
1031   for (i = 0; i < count; i++) {
1032     GstPsStream *stream = demux->streams_found[i];
1033
1034     if (stream) {
1035       if (stream->last_ts == GST_CLOCK_TIME_NONE ||
1036           stream->last_ts < demux->src_segment.start + base_time)
1037         stream->last_ts = demux->src_segment.start + base_time;
1038
1039       if (stream->last_ts + stream->gap_threshold < time &&
1040           stream->nb_out_buffers == stream->gap_ref_buffers &&
1041           stream->gap_ref_pts != stream->last_ts) {
1042         /* should send segment info before gap event */
1043         gst_ps_demux_send_segment (demux, stream, GST_CLOCK_TIME_NONE);
1044
1045         GST_LOG_OBJECT (demux,
1046             "Sending gap update to pad %s from time %" GST_TIME_FORMAT " to %"
1047             GST_TIME_FORMAT, GST_PAD_NAME (stream->pad),
1048             GST_TIME_ARGS (stream->last_ts), GST_TIME_ARGS (time));
1049         event = gst_event_new_gap (stream->last_ts, time - stream->last_ts);
1050         gst_pad_push_event (stream->pad, event);
1051         stream->last_ts = time;
1052       }
1053
1054       /* Update GAP tracking vars so we don't re-check this stream for a while */
1055       stream->gap_ref_pts = time;
1056       if (stream->last_ts != GST_CLOCK_TIME_NONE && stream->last_ts > time)
1057         stream->gap_ref_pts = stream->last_ts;
1058     }
1059   }
1060 }
1061
1062 static inline gboolean
1063 have_open_streams (GstPsDemux * demux)
1064 {
1065   return (demux->streams_found[0] != NULL);
1066 }
1067
1068 static gboolean
1069 gst_ps_demux_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
1070 {
1071   gboolean res = TRUE;
1072   GstPsDemux *demux = GST_PS_DEMUX (parent);
1073
1074   switch (GST_EVENT_TYPE (event)) {
1075     case GST_EVENT_FLUSH_START:
1076       gst_ps_demux_send_event (demux, event);
1077       break;
1078     case GST_EVENT_FLUSH_STOP:
1079       gst_ps_demux_send_event (demux, event);
1080       gst_segment_init (&demux->sink_segment, GST_FORMAT_UNDEFINED);
1081       gst_ps_demux_flush (demux);
1082       break;
1083     case GST_EVENT_SEGMENT:
1084     {
1085       const GstSegment *segment;
1086
1087       gst_event_parse_segment (event, &segment);
1088       gst_segment_copy_into (segment, &demux->sink_segment);
1089
1090       GST_INFO_OBJECT (demux, "received segment %" GST_SEGMENT_FORMAT, segment);
1091
1092       /* we need to emit a new segment */
1093       gst_ps_demux_mark_discont (demux, TRUE, TRUE);
1094
1095       if (segment->format == GST_FORMAT_BYTES
1096           && demux->scr_rate_n != G_MAXUINT64
1097           && demux->scr_rate_d != G_MAXUINT64) {
1098         demux->src_segment.rate = segment->rate;
1099         demux->src_segment.applied_rate = segment->applied_rate;
1100         demux->src_segment.format = GST_FORMAT_TIME;
1101         demux->src_segment.start = BYTES_TO_GSTTIME (segment->start);
1102         demux->src_segment.stop = BYTES_TO_GSTTIME (segment->stop);
1103         demux->src_segment.time = BYTES_TO_GSTTIME (segment->time);
1104       } else if (segment->format == GST_FORMAT_TIME) {
1105         /* we expect our timeline (SCR, PTS) to match the one from upstream,
1106          * if not, will adjust with offset later on */
1107         gst_segment_copy_into (segment, &demux->src_segment);
1108       }
1109
1110       gst_event_unref (event);
1111
1112       break;
1113     }
1114     case GST_EVENT_EOS:
1115       GST_INFO_OBJECT (demux, "Received EOS");
1116       if (!gst_ps_demux_send_event (demux, event)
1117           && !have_open_streams (demux)) {
1118         GST_WARNING_OBJECT (demux, "EOS and no streams open");
1119         GST_ELEMENT_ERROR (demux, STREAM, FAILED,
1120             ("Internal data stream error."), ("No valid streams detected"));
1121       }
1122       break;
1123     case GST_EVENT_CUSTOM_DOWNSTREAM:
1124     case GST_EVENT_CUSTOM_DOWNSTREAM_OOB:
1125     {
1126       const GstStructure *structure = gst_event_get_structure (event);
1127
1128       if (structure != NULL
1129           && gst_structure_has_name (structure, "application/x-gst-dvd")) {
1130         res = gst_ps_demux_handle_dvd_event (demux, event);
1131       } else {
1132         gst_ps_demux_send_event (demux, event);
1133       }
1134       break;
1135     }
1136     case GST_EVENT_CAPS:
1137       gst_event_unref (event);
1138       break;
1139     default:
1140       gst_ps_demux_send_event (demux, event);
1141       break;
1142   }
1143
1144   return res;
1145 }
1146
1147 static gboolean
1148 gst_ps_demux_handle_seek_push (GstPsDemux * demux, GstEvent * event)
1149 {
1150   gboolean res = FALSE;
1151   gdouble rate;
1152   GstFormat format;
1153   GstSeekFlags flags;
1154   GstSeekType start_type, stop_type;
1155   gint64 start, stop;
1156   gint64 bstart, bstop;
1157   GstEvent *bevent;
1158
1159   gst_event_parse_seek (event, &rate, &format, &flags, &start_type, &start,
1160       &stop_type, &stop);
1161
1162   GST_DEBUG_OBJECT (demux, "seek event, rate: %f start: %" GST_TIME_FORMAT
1163       " stop: %" GST_TIME_FORMAT, rate, GST_TIME_ARGS (start),
1164       GST_TIME_ARGS (stop));
1165
1166   if (format == GST_FORMAT_BYTES) {
1167     GST_DEBUG_OBJECT (demux, "seek not supported on format %d", format);
1168     goto not_supported;
1169   }
1170
1171   GST_DEBUG_OBJECT (demux, "seek - trying directly upstream first");
1172
1173   /* first try original format seek */
1174   (void) gst_event_ref (event);
1175   if ((res = gst_pad_push_event (demux->sinkpad, event)))
1176     goto done;
1177
1178   if (format != GST_FORMAT_TIME) {
1179     /* From here down, we only support time based seeks */
1180     GST_DEBUG_OBJECT (demux, "seek not supported on format %d", format);
1181     goto not_supported;
1182   }
1183
1184   /* We need to convert to byte based seek and we need a scr_rate for that. */
1185   if (demux->scr_rate_n == G_MAXUINT64 || demux->scr_rate_d == G_MAXUINT64) {
1186     GST_DEBUG_OBJECT (demux, "seek not possible, no scr_rate");
1187     goto not_supported;
1188   }
1189
1190   GST_DEBUG_OBJECT (demux, "try with scr_rate interpolation");
1191
1192   bstart = GSTTIME_TO_BYTES ((guint64) start);
1193   bstop = GSTTIME_TO_BYTES ((guint64) stop);
1194
1195   GST_DEBUG_OBJECT (demux, "in bytes bstart %" G_GINT64_FORMAT " bstop %"
1196       G_GINT64_FORMAT, bstart, bstop);
1197   bevent = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags, start_type,
1198       bstart, stop_type, bstop);
1199
1200   res = gst_pad_push_event (demux->sinkpad, bevent);
1201
1202 done:
1203   gst_event_unref (event);
1204   return res;
1205
1206 not_supported:
1207   {
1208     gst_event_unref (event);
1209
1210     return FALSE;
1211   }
1212 }
1213
1214 #define MAX_RECURSION_COUNT 100
1215
1216 /* Binary search for requested SCR */
1217 static inline guint64
1218 find_offset (GstPsDemux * demux, guint64 scr,
1219     guint64 min_scr, guint64 min_scr_offset,
1220     guint64 max_scr, guint64 max_scr_offset, int recursion_count)
1221 {
1222   guint64 scr_rate_n = max_scr_offset - min_scr_offset;
1223   guint64 scr_rate_d = max_scr - min_scr;
1224   guint64 fscr = scr;
1225   guint64 offset;
1226
1227   if (recursion_count > MAX_RECURSION_COUNT) {
1228     return -1;
1229   }
1230
1231   offset = min_scr_offset +
1232       MIN (gst_util_uint64_scale (scr - min_scr, scr_rate_n,
1233           scr_rate_d), demux->sink_segment.stop);
1234
1235   if (!gst_ps_demux_scan_forward_ts (demux, &offset, SCAN_SCR, &fscr, 0)) {
1236     gst_ps_demux_scan_backward_ts (demux, &offset, SCAN_SCR, &fscr, 0);
1237   }
1238
1239   if (fscr == scr || fscr == min_scr || fscr == max_scr) {
1240     return offset;
1241   }
1242
1243   if (fscr < scr) {
1244     return find_offset (demux, scr, fscr, offset, max_scr, max_scr_offset,
1245         recursion_count + 1);
1246   } else {
1247     return find_offset (demux, scr, min_scr, min_scr_offset, fscr, offset,
1248         recursion_count + 1);
1249   }
1250 }
1251
1252 static inline gboolean
1253 gst_ps_demux_do_seek (GstPsDemux * demux, GstSegment * seeksegment)
1254 {
1255   gboolean found;
1256   guint64 fscr, offset;
1257   guint64 scr = GSTTIME_TO_MPEGTIME (seeksegment->position + demux->base_time);
1258
1259   /* In some clips the PTS values are completely unaligned with SCR values.
1260    * To improve the seek in that situation we apply a factor considering the
1261    * relationship between last PTS and last SCR */
1262   if (demux->last_scr > demux->last_pts)
1263     scr = gst_util_uint64_scale (scr, demux->last_scr, demux->last_pts);
1264
1265   scr = MIN (demux->last_scr, scr);
1266   scr = MAX (demux->first_scr, scr);
1267   fscr = scr;
1268
1269   GST_INFO_OBJECT (demux, "sink segment configured %" GST_SEGMENT_FORMAT
1270       ", trying to go at SCR: %" G_GUINT64_FORMAT, &demux->sink_segment, scr);
1271
1272   offset =
1273       find_offset (demux, scr, demux->first_scr, demux->first_scr_offset,
1274       demux->last_scr, demux->last_scr_offset, 0);
1275
1276   if (offset == (guint64) - 1) {
1277     return FALSE;
1278   }
1279
1280   found = gst_ps_demux_scan_forward_ts (demux, &offset, SCAN_SCR, &fscr, 0);
1281   if (!found)
1282     found = gst_ps_demux_scan_backward_ts (demux, &offset, SCAN_SCR, &fscr, 0);
1283
1284   while (found && fscr < scr) {
1285     offset++;
1286     found = gst_ps_demux_scan_forward_ts (demux, &offset, SCAN_SCR, &fscr, 0);
1287   }
1288
1289   while (found && fscr > scr && offset > 0) {
1290     offset--;
1291     found = gst_ps_demux_scan_backward_ts (demux, &offset, SCAN_SCR, &fscr, 0);
1292   }
1293
1294   GST_INFO_OBJECT (demux, "doing seek at offset %" G_GUINT64_FORMAT
1295       " SCR: %" G_GUINT64_FORMAT " %" GST_TIME_FORMAT,
1296       offset, fscr, GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (fscr)));
1297
1298   gst_segment_set_position (&demux->sink_segment, GST_FORMAT_BYTES, offset);
1299
1300   return TRUE;
1301 }
1302
1303 static gboolean
1304 gst_ps_demux_handle_seek_pull (GstPsDemux * demux, GstEvent * event)
1305 {
1306   GstFormat format;
1307   GstSeekFlags flags;
1308   GstSeekType start_type, stop_type;
1309   gint64 start, stop;
1310   gdouble rate;
1311   gboolean update, flush, accurate;
1312   GstSegment seeksegment;
1313   GstClockTime first_pts = MPEGTIME_TO_GSTTIME (demux->first_pts);
1314   guint32 seek_seqnum = gst_event_get_seqnum (event);
1315
1316   gst_event_parse_seek (event, &rate, &format, &flags,
1317       &start_type, &start, &stop_type, &stop);
1318
1319   if (format != GST_FORMAT_TIME)
1320     goto wrong_format;
1321
1322   GST_DEBUG_OBJECT (demux, "Seek requested start %" GST_TIME_FORMAT " stop %"
1323       GST_TIME_FORMAT, GST_TIME_ARGS (start), GST_TIME_ARGS (stop));
1324
1325   /* We need to convert to byte based seek and we need a scr_rate for that. */
1326   if (demux->scr_rate_n == G_MAXUINT64 || demux->scr_rate_d == G_MAXUINT64)
1327     goto no_scr_rate;
1328
1329   flush = flags & GST_SEEK_FLAG_FLUSH;
1330   accurate = flags & GST_SEEK_FLAG_ACCURATE;
1331
1332   /* keyframe = flags & GST_SEEK_FLAG_KEY_UNIT; *//* FIXME */
1333
1334   if (flush) {
1335     GstEvent *event = gst_event_new_flush_start ();
1336     gst_event_set_seqnum (event, seek_seqnum);
1337     /* Flush start up and downstream to make sure data flow and loops are
1338        idle */
1339     demux->flushing = TRUE;
1340     gst_ps_demux_send_event (demux, event);
1341     gst_pad_push_event (demux->sinkpad, gst_event_new_flush_start ());
1342   } else {
1343     /* Pause the pulling task */
1344     gst_pad_pause_task (demux->sinkpad);
1345   }
1346
1347   /* Take the stream lock */
1348   GST_PAD_STREAM_LOCK (demux->sinkpad);
1349
1350   if (flush) {
1351     /* Stop flushing upstream we need to pull */
1352     demux->flushing = FALSE;
1353     gst_pad_push_event (demux->sinkpad, gst_event_new_flush_stop (TRUE));
1354   }
1355
1356   /* Work on a copy until we are sure the seek succeeded. */
1357   memcpy (&seeksegment, &demux->src_segment, sizeof (GstSegment));
1358
1359   GST_DEBUG_OBJECT (demux, "segment before configure %" GST_SEGMENT_FORMAT,
1360       &demux->src_segment);
1361
1362   /* Apply the seek to our segment */
1363   if (!gst_segment_do_seek (&seeksegment, rate, format, flags,
1364           start_type, start, stop_type, stop, &update))
1365     goto seek_error;
1366
1367   GST_DEBUG_OBJECT (demux, "seek segment configured %" GST_SEGMENT_FORMAT,
1368       &seeksegment);
1369
1370   if (flush || seeksegment.position != demux->src_segment.position) {
1371     /* Do the actual seeking */
1372     if (!gst_ps_demux_do_seek (demux, &seeksegment)) {
1373 #ifdef TIZEN_FEATURE_MPEGDEMUX_MODIFICATION
1374       goto seek_error;
1375 #else
1376       return FALSE;
1377 #endif
1378     }
1379   }
1380
1381   /* check the limits */
1382   if (seeksegment.rate > 0.0 && first_pts != G_MAXUINT64
1383       && seeksegment.start < first_pts - demux->base_time) {
1384     seeksegment.position = first_pts - demux->base_time;
1385     if (!accurate)
1386       seeksegment.start = seeksegment.position;
1387   }
1388
1389   /* update the rate in our src segment */
1390   demux->sink_segment.rate = rate;
1391
1392   GST_DEBUG_OBJECT (demux, "seek segment adjusted %" GST_SEGMENT_FORMAT,
1393       &seeksegment);
1394
1395   if (flush) {
1396     GstEvent *event = gst_event_new_flush_stop (TRUE);
1397     /* Stop flushing, the sinks are at time 0 now */
1398     gst_event_set_seqnum (event, seek_seqnum);
1399     gst_ps_demux_send_event (demux, event);
1400   }
1401
1402   if (flush || seeksegment.position != demux->src_segment.position) {
1403     gst_ps_demux_flush (demux);
1404   }
1405
1406   /* Ok seek succeeded, take the newly configured segment */
1407   memcpy (&demux->src_segment, &seeksegment, sizeof (GstSegment));
1408
1409   /* Notify about the start of a new segment */
1410   if (demux->src_segment.flags & GST_SEEK_FLAG_SEGMENT) {
1411     gst_element_post_message (GST_ELEMENT (demux),
1412         gst_message_new_segment_start (GST_OBJECT (demux),
1413             demux->src_segment.format, demux->src_segment.position));
1414   }
1415
1416   /* Tell all the stream a new segment is needed */
1417   gst_ps_demux_mark_discont (demux, TRUE, TRUE);
1418
1419   /* Update the segment_seqnum with the seek event seqnum */
1420   demux->segment_seqnum = seek_seqnum;
1421
1422   gst_pad_start_task (demux->sinkpad,
1423       (GstTaskFunction) gst_ps_demux_loop, demux->sinkpad, NULL);
1424
1425   GST_PAD_STREAM_UNLOCK (demux->sinkpad);
1426
1427   gst_event_unref (event);
1428   return TRUE;
1429
1430   /* ERRORS */
1431 wrong_format:
1432   {
1433     GST_WARNING_OBJECT (demux, "we only support seeking in TIME or BYTES "
1434         "formats");
1435     gst_event_unref (event);
1436     return FALSE;
1437   }
1438 no_scr_rate:
1439   {
1440     GST_WARNING_OBJECT (demux, "seek not possible, no scr_rate");
1441     gst_event_unref (event);
1442     return FALSE;
1443   }
1444 seek_error:
1445   {
1446     GST_WARNING_OBJECT (demux, "couldn't perform seek");
1447 #ifdef TIZEN_FEATURE_MPEGDEMUX_MODIFICATION
1448     GST_PAD_STREAM_UNLOCK (demux->sinkpad);
1449 #endif
1450     gst_event_unref (event);
1451     return FALSE;
1452   }
1453 }
1454
1455 static gboolean
1456 gst_ps_demux_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1457 {
1458   gboolean res = FALSE;
1459   GstPsDemux *demux = GST_PS_DEMUX (parent);
1460
1461   switch (GST_EVENT_TYPE (event)) {
1462     case GST_EVENT_SEEK:
1463       if (demux->random_access) {
1464         res = gst_ps_demux_handle_seek_pull (demux, event);
1465       } else {
1466         res = gst_ps_demux_handle_seek_push (demux, event);
1467       }
1468       break;
1469     case GST_EVENT_RECONFIGURE:{
1470       GstPsStream *stream;
1471
1472       stream = gst_ps_demux_get_stream_from_pad (demux, pad);
1473       if (stream != NULL)
1474         stream->notlinked = FALSE;
1475
1476       gst_event_unref (event);
1477       res = TRUE;
1478       break;
1479     }
1480     default:
1481       res = gst_pad_push_event (demux->sinkpad, event);
1482       break;
1483   }
1484
1485   return res;
1486 }
1487
1488 static gboolean
1489 gst_ps_demux_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1490 {
1491   gboolean res = FALSE;
1492   GstPsDemux *demux = GST_PS_DEMUX (parent);
1493
1494   GST_LOG_OBJECT (demux, "Have query of type %d on pad %" GST_PTR_FORMAT,
1495       GST_QUERY_TYPE (query), pad);
1496
1497   switch (GST_QUERY_TYPE (query)) {
1498     case GST_QUERY_POSITION:
1499     {
1500       GstClockTime pos;
1501       GstFormat format;
1502
1503       /* See if upstream can immediately answer */
1504       res = gst_pad_peer_query (demux->sinkpad, query);
1505       if (res)
1506         break;
1507
1508       gst_query_parse_position (query, &format, NULL);
1509
1510       if (format != GST_FORMAT_TIME) {
1511         GST_DEBUG_OBJECT (demux, "position not supported for format: %s",
1512             gst_format_get_name (format));
1513         goto not_supported;
1514       }
1515
1516       pos = demux->src_segment.position - demux->src_segment.start;
1517       GST_LOG_OBJECT (demux, "Position %" GST_TIME_FORMAT, GST_TIME_ARGS (pos));
1518
1519       gst_query_set_position (query, format, pos);
1520       res = TRUE;
1521       break;
1522     }
1523     case GST_QUERY_DURATION:
1524     {
1525       GstFormat format;
1526       gint64 duration;
1527       GstQuery *byte_query;
1528
1529       gst_query_parse_duration (query, &format, NULL);
1530
1531       if (G_LIKELY (format == GST_FORMAT_TIME &&
1532               GST_CLOCK_TIME_IS_VALID (demux->src_segment.duration))) {
1533         gst_query_set_duration (query, GST_FORMAT_TIME,
1534             demux->src_segment.duration);
1535         res = TRUE;
1536         break;
1537       }
1538
1539       /* For any format other than bytes, see if upstream knows first */
1540       if (format == GST_FORMAT_BYTES) {
1541         GST_DEBUG_OBJECT (demux, "duration not supported for format: %s",
1542             gst_format_get_name (format));
1543         goto not_supported;
1544       }
1545
1546       if (gst_pad_peer_query (demux->sinkpad, query)) {
1547         res = TRUE;
1548         break;
1549       }
1550
1551       /* Upstream didn't know, so we can only answer TIME queries from
1552        * here on */
1553       if (format != GST_FORMAT_TIME) {
1554         GST_DEBUG_OBJECT (demux, "duration not supported for format: %s",
1555             gst_format_get_name (format));
1556         goto not_supported;
1557       }
1558
1559       if (demux->mux_rate == -1) {
1560         GST_DEBUG_OBJECT (demux, "duration not possible, no mux_rate");
1561         goto not_supported;
1562       }
1563
1564       byte_query = gst_query_new_duration (GST_FORMAT_BYTES);
1565
1566       if (!gst_pad_peer_query (demux->sinkpad, byte_query)) {
1567         GST_LOG_OBJECT (demux, "query on peer pad failed");
1568         gst_query_unref (byte_query);
1569         goto not_supported;
1570       }
1571
1572       gst_query_parse_duration (byte_query, &format, &duration);
1573       gst_query_unref (byte_query);
1574
1575       GST_LOG_OBJECT (demux,
1576           "query on peer pad reported bytes %" G_GUINT64_FORMAT, duration);
1577
1578       duration = BYTES_TO_GSTTIME ((guint64) duration);
1579
1580       GST_LOG_OBJECT (demux, "converted to time %" GST_TIME_FORMAT,
1581           GST_TIME_ARGS (duration));
1582
1583       gst_query_set_duration (query, GST_FORMAT_TIME, duration);
1584       res = TRUE;
1585       break;
1586     }
1587     case GST_QUERY_SEEKING:{
1588       GstFormat fmt;
1589
1590       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
1591
1592       res = TRUE;
1593       if (demux->random_access) {
1594         /* In pull mode we can seek in TIME format if we have the SCR */
1595         if (fmt != GST_FORMAT_TIME || demux->scr_rate_n == G_MAXUINT64
1596             || demux->scr_rate_d == G_MAXUINT64) {
1597           gst_query_set_seeking (query, fmt, FALSE, -1, -1);
1598         } else {
1599           gint64 dur = -1;
1600           if (GST_CLOCK_TIME_IS_VALID (demux->src_segment.duration))
1601             dur = demux->src_segment.duration;
1602           gst_query_set_seeking (query, fmt, TRUE, 0, dur);
1603         }
1604       } else {
1605         if (fmt == GST_FORMAT_BYTES) {
1606           /* Seeking in BYTES format not supported at all */
1607           gst_query_set_seeking (query, fmt, FALSE, -1, -1);
1608         } else {
1609           GstQuery *peerquery;
1610           gboolean seekable;
1611
1612           /* Then ask upstream */
1613           res = gst_pad_peer_query (demux->sinkpad, query);
1614           if (res) {
1615             /* If upstream can handle seeks we're done, if it
1616              * can't we still have our TIME->BYTES conversion seek
1617              */
1618             gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
1619             if (seekable || fmt != GST_FORMAT_TIME)
1620               goto beach;
1621           }
1622
1623           /* We can seek if upstream supports BYTES seeks and we
1624            * have the SCR
1625            */
1626           peerquery = gst_query_new_seeking (GST_FORMAT_BYTES);
1627           res = gst_pad_peer_query (demux->sinkpad, peerquery);
1628           if (!res || demux->scr_rate_n == G_MAXUINT64
1629               || demux->scr_rate_d == G_MAXUINT64) {
1630             gst_query_set_seeking (query, fmt, FALSE, -1, -1);
1631           } else {
1632             gst_query_parse_seeking (peerquery, NULL, &seekable, NULL, NULL);
1633             if (seekable)
1634               gst_query_set_seeking (query, GST_FORMAT_TIME, TRUE, 0, -1);
1635             else
1636               gst_query_set_seeking (query, fmt, FALSE, -1, -1);
1637           }
1638
1639           gst_query_unref (peerquery);
1640           res = TRUE;
1641         }
1642       }
1643       break;
1644     }
1645     case GST_QUERY_SEGMENT:{
1646       GstFormat format;
1647       gint64 start, stop;
1648
1649       format = demux->src_segment.format;
1650
1651       start =
1652           gst_segment_to_stream_time (&demux->src_segment, format,
1653           demux->src_segment.start);
1654       if ((stop = demux->src_segment.stop) == -1)
1655         stop = demux->src_segment.duration;
1656       else
1657         stop = gst_segment_to_stream_time (&demux->src_segment, format, stop);
1658
1659       gst_query_set_segment (query, demux->src_segment.rate, format, start,
1660           stop);
1661       res = TRUE;
1662       break;
1663     }
1664     default:
1665       res = gst_pad_query_default (pad, parent, query);
1666       break;
1667   }
1668
1669 beach:
1670   return res;
1671 not_supported:
1672   return FALSE;
1673 }
1674
1675 static void
1676 gst_ps_demux_reset_psm (GstPsDemux * demux)
1677 {
1678   gint i;
1679
1680 #define FILL_TYPE(start, stop, type)    \
1681   for (i=start; i <= stop; i++)                 \
1682     demux->psm[i] = type;
1683
1684   /* Initialize all fields to -1 first */
1685   FILL_TYPE (0x00, GST_PS_DEMUX_MAX_PSM - 1, -1);
1686
1687   FILL_TYPE (0x20, 0x3f, ST_PS_DVD_SUBPICTURE);
1688
1689   FILL_TYPE (0x80, 0x87, ST_PS_AUDIO_AC3);
1690   FILL_TYPE (0x88, 0x9f, ST_PS_AUDIO_DTS);
1691   FILL_TYPE (0xa0, 0xaf, ST_PS_AUDIO_LPCM);
1692
1693   FILL_TYPE (0xc0, 0xdf, ST_AUDIO_MPEG1);
1694   FILL_TYPE (0xe0, 0xef, ST_GST_VIDEO_MPEG1_OR_2);
1695
1696 #undef FILL_TYPE
1697 }
1698
1699 /* ISO/IEC 13818-1:
1700  * pack_header() {
1701  *     pack_start_code                                   32  bslbf  -+
1702  *     '01'                                               2  bslbf   |
1703  *     system_clock_reference_base [32..30]               3  bslbf   |
1704  *     marker_bit                                         1  bslbf   |
1705  *     system_clock_reference_base [29..15]              15  bslbf   |
1706  *     marker_bit                                         1  bslbf   |
1707  *     system_clock_reference_base [14..0]               15  bslbf   |
1708  *     marker_bit                                         1  bslbf   | 112 bits
1709  *     system_clock_reference_extension                   9  ubslbf  |
1710  *     marker_bit                                         1  bslbf   |
1711  *     program_mux_rate                                  22  ubslbf  |
1712  *     marker_bit                                         1  bslbf   |
1713  *     marker_bit                                         1  bslbf   |
1714  *     reserved                                           5  bslbf   |
1715  *     pack_stuffing_length                               3  ubslbf -+
1716  *
1717  *     for (i = 0; i < pack_stuffing_length; i++) {
1718  *         stuffing_byte '1111 1111'                      8  bslbf
1719  *     }
1720  *
1721  * 112 bits = 14 bytes, as max value for pack_stuffing_length is 7, then
1722  * in total it's needed 14 + 7 = 21 bytes.
1723  */
1724 #define PACK_START_SIZE     21
1725
1726 static GstFlowReturn
1727 gst_ps_demux_parse_pack_start (GstPsDemux * demux)
1728 {
1729   const guint8 *data;
1730   guint length;
1731   guint32 scr1, scr2;
1732   guint64 scr, scr_adjusted, new_rate;
1733   guint64 scr_rate_n;
1734   guint64 scr_rate_d;
1735   guint avail = gst_adapter_available (demux->adapter);
1736
1737   GST_LOG ("parsing pack start");
1738
1739   if (G_UNLIKELY (avail < PACK_START_SIZE))
1740     goto need_more_data;
1741
1742   data = gst_adapter_map (demux->adapter, PACK_START_SIZE);
1743
1744   /* skip start code */
1745   data += 4;
1746
1747   scr1 = GST_READ_UINT32_BE (data);
1748   scr2 = GST_READ_UINT32_BE (data + 4);
1749
1750   /* fixed length to begin with, start code and two scr values */
1751   length = 8 + 4;
1752
1753   /* start parsing the stream */
1754   if ((*data & 0xc0) == 0x40) {
1755     guint32 scr_ext;
1756     guint32 next32;
1757     guint8 stuffing_bytes;
1758
1759     GST_LOG ("Found MPEG2 stream");
1760     demux->is_mpeg2_pack = TRUE;
1761
1762     /* mpeg2 has more data */
1763     length += 2;
1764
1765     /* :2=01 ! scr:3 ! marker:1==1 ! scr:15 ! marker:1==1 ! scr:15 */
1766
1767     /* check markers */
1768     if (G_UNLIKELY ((scr1 & 0xc4000400) != 0x44000400))
1769       goto lost_sync;
1770
1771     scr = ((guint64) scr1 & 0x38000000) << 3;
1772     scr |= ((guint64) scr1 & 0x03fff800) << 4;
1773     scr |= ((guint64) scr1 & 0x000003ff) << 5;
1774     scr |= ((guint64) scr2 & 0xf8000000) >> 27;
1775
1776     /* marker:1==1 ! scr_ext:9 ! marker:1==1 */
1777     if (G_UNLIKELY ((scr2 & 0x04010000) != 0x04010000))
1778       goto lost_sync;
1779
1780     scr_ext = (scr2 & 0x03fe0000) >> 17;
1781     /* We keep the offset of this scr */
1782     demux->cur_scr_offset = demux->adapter_offset + 12;
1783
1784     GST_LOG_OBJECT (demux, "SCR: 0x%08" G_GINT64_MODIFIER "x SCRE: 0x%08x",
1785         scr, scr_ext);
1786
1787     if (scr_ext) {
1788       scr = (scr * 300 + scr_ext % 300) / 300;
1789     }
1790     /* SCR has been converted into units of 90Khz ticks to make it comparable
1791        to DTS/PTS, that also implies 1 tick rounding error */
1792     data += 6;
1793     /* PMR:22 ! :2==11 ! reserved:5 ! stuffing_len:3 */
1794     next32 = GST_READ_UINT32_BE (data);
1795     if (G_UNLIKELY ((next32 & 0x00000300) != 0x00000300))
1796       goto lost_sync;
1797
1798     new_rate = (next32 & 0xfffffc00) >> 10;
1799
1800     stuffing_bytes = (next32 & 0x07);
1801     GST_LOG_OBJECT (demux, "stuffing bytes: %d", stuffing_bytes);
1802
1803     data += 4;
1804     length += stuffing_bytes;
1805     while (stuffing_bytes--) {
1806       if (*data++ != 0xff)
1807         goto lost_sync;
1808     }
1809   } else {
1810     GST_DEBUG ("Found MPEG1 stream");
1811     demux->is_mpeg2_pack = FALSE;
1812
1813     /* check markers */
1814     if (G_UNLIKELY ((scr1 & 0xf1000100) != 0x21000100))
1815       goto lost_sync;
1816
1817     if (G_UNLIKELY ((scr2 & 0x01800001) != 0x01800001))
1818       goto lost_sync;
1819
1820     /* :4=0010 ! scr:3 ! marker:1==1 ! scr:15 ! marker:1==1 ! scr:15 ! marker:1==1 */
1821     scr = ((guint64) scr1 & 0x0e000000) << 5;
1822     scr |= ((guint64) scr1 & 0x00fffe00) << 6;
1823     scr |= ((guint64) scr1 & 0x000000ff) << 7;
1824     scr |= ((guint64) scr2 & 0xfe000000) >> 25;
1825
1826     /* We keep the offset of this scr */
1827     demux->cur_scr_offset = demux->adapter_offset + 8;
1828
1829     /* marker:1==1 ! mux_rate:22 ! marker:1==1 */
1830     new_rate = (scr2 & 0x007ffffe) >> 1;
1831
1832     data += 8;
1833   }
1834
1835   if (demux->ignore_scr) {
1836     /* update only first/current_scr with raw scr value to start streaming
1837      * after parsing 2 seconds long data with no-more-pad */
1838     if (demux->first_scr == G_MAXUINT64) {
1839       demux->first_scr = scr;
1840       demux->first_scr_offset = demux->cur_scr_offset;
1841     }
1842
1843     demux->current_scr = scr;
1844
1845     goto out;
1846   }
1847
1848   new_rate *= MPEG_MUX_RATE_MULT;
1849
1850   /* scr adjusted is the new scr found + the colected adjustment */
1851   scr_adjusted = scr + demux->scr_adjust;
1852
1853   GST_LOG_OBJECT (demux,
1854       "SCR: %" G_GINT64_FORMAT " (%" G_GINT64_FORMAT "), mux_rate %"
1855       G_GINT64_FORMAT ", GStreamer Time:%" GST_TIME_FORMAT,
1856       scr, scr_adjusted, new_rate,
1857       GST_TIME_ARGS (MPEGTIME_TO_GSTTIME ((guint64) scr)));
1858
1859   /* keep the first src in order to calculate delta time */
1860   if (G_UNLIKELY (demux->first_scr == G_MAXUINT64)) {
1861     gint64 diff;
1862
1863     demux->first_scr = scr;
1864     demux->first_scr_offset = demux->cur_scr_offset;
1865     demux->base_time = MPEGTIME_TO_GSTTIME (demux->first_scr);
1866     GST_DEBUG_OBJECT (demux, "determined base_time %" GST_TIME_FORMAT,
1867         GST_TIME_ARGS (demux->base_time));
1868     /* at begin consider the new_rate as the scr rate, bytes/clock ticks */
1869     scr_rate_n = new_rate;
1870     scr_rate_d = CLOCK_FREQ;
1871     /* our SCR timeline might have offset wrt upstream timeline */
1872     if (demux->sink_segment.format == GST_FORMAT_TIME) {
1873       if (demux->sink_segment.start > demux->base_time)
1874         diff = -(demux->sink_segment.start - demux->base_time);
1875       else
1876         diff = demux->base_time - demux->sink_segment.start;
1877       if (diff > GST_SECOND) {
1878         GST_DEBUG_OBJECT (demux, "diff of %" GST_TIME_FORMAT
1879             " wrt upstream start %" GST_TIME_FORMAT "; adjusting base",
1880             GST_TIME_ARGS (diff), GST_TIME_ARGS (demux->sink_segment.start));
1881         demux->base_time += diff;
1882       }
1883     }
1884   } else if (G_LIKELY (demux->first_scr_offset != demux->cur_scr_offset)) {
1885     /* estimate byte rate related to the SCR */
1886     scr_rate_n = demux->cur_scr_offset - demux->first_scr_offset;
1887     scr_rate_d = scr_adjusted - demux->first_scr;
1888   } else {
1889     scr_rate_n = demux->scr_rate_n;
1890     scr_rate_d = demux->scr_rate_d;
1891   }
1892
1893   GST_LOG_OBJECT (demux, "%s mode scr: %" G_GUINT64_FORMAT " at %"
1894       G_GUINT64_FORMAT ", first scr: %" G_GUINT64_FORMAT
1895       " at %" G_GUINT64_FORMAT ", scr rate: %" G_GUINT64_FORMAT
1896       "/%" G_GUINT64_FORMAT "(%f)",
1897       ((demux->sink_segment.rate >= 0.0) ? "forward" : "backward"),
1898       scr, demux->cur_scr_offset,
1899       demux->first_scr, demux->first_scr_offset,
1900       scr_rate_n, scr_rate_d, (float) scr_rate_n / scr_rate_d);
1901
1902   /* adjustment of the SCR */
1903   if (G_LIKELY (demux->current_scr != G_MAXUINT64)) {
1904     guint64 diff;
1905     guint64 old_scr, old_mux_rate, bss, adjust = 0;
1906
1907     /* keep SCR of the previous packet */
1908     old_scr = demux->current_scr;
1909     old_mux_rate = demux->mux_rate;
1910
1911     /* Bytes since SCR is the amount we placed in the adapter since then
1912      * (demux->bytes_since_scr) minus the amount remaining in the adapter,
1913      * clamped to >= 0 */
1914     bss = MAX (0, (gint) (demux->bytes_since_scr - avail));
1915
1916     /* estimate the new SCR using the previous one according the notes
1917        on point 2.5.2.2 of the ISO/IEC 13818-1 document */
1918     if (old_mux_rate != 0)
1919       adjust = (bss * CLOCK_FREQ) / old_mux_rate;
1920
1921     if (demux->sink_segment.rate >= 0.0)
1922       demux->next_scr = old_scr + adjust;
1923     else
1924       demux->next_scr = old_scr - adjust;
1925
1926     GST_LOG_OBJECT (demux,
1927         "bss: %" G_GUINT64_FORMAT ", next_scr: %" G_GUINT64_FORMAT
1928         ", old_scr: %" G_GUINT64_FORMAT ", scr: %" G_GUINT64_FORMAT,
1929         bss, demux->next_scr, old_scr, scr_adjusted);
1930
1931     /* calculate the absolute deference between the last scr and
1932        the new one */
1933     if (G_UNLIKELY (old_scr > scr_adjusted))
1934       diff = old_scr - scr_adjusted;
1935     else
1936       diff = scr_adjusted - old_scr;
1937
1938     /* if the difference is more than 1 second we need to reconfigure
1939        adjustment */
1940     if (G_UNLIKELY (diff > CLOCK_FREQ)) {
1941       demux->scr_adjust = demux->next_scr - scr;
1942       GST_LOG_OBJECT (demux, "discont found, diff: %" G_GINT64_FORMAT
1943           ", adjust %" G_GINT64_FORMAT, diff, demux->scr_adjust);
1944       scr_adjusted = demux->next_scr;
1945       /* don't update rate estimation on disconts */
1946       scr_rate_n = demux->scr_rate_n;
1947       scr_rate_d = demux->scr_rate_d;
1948     } else {
1949       demux->next_scr = scr_adjusted;
1950     }
1951   }
1952
1953   /* update the current_scr and rate members */
1954   demux->mux_rate = new_rate;
1955   demux->current_scr = scr_adjusted;
1956   demux->scr_rate_n = scr_rate_n;
1957   demux->scr_rate_d = scr_rate_d;
1958
1959   /* Reset the bytes_since_scr value to count the data remaining in the
1960    * adapter */
1961   demux->bytes_since_scr = avail;
1962
1963   /* Now check for all streams if they're behind the new SCR and if
1964    * they are then move them forward to the SCR position */
1965   gst_ps_demux_send_gap_updates (demux,
1966       MPEGTIME_TO_GSTTIME (demux->current_scr - demux->first_scr));
1967
1968 out:
1969   gst_adapter_unmap (demux->adapter);
1970   gst_adapter_flush (demux->adapter, length);
1971   ADAPTER_OFFSET_FLUSH (length);
1972
1973   return GST_FLOW_OK;
1974
1975 lost_sync:
1976   {
1977     GST_DEBUG_OBJECT (demux, "lost sync");
1978     gst_adapter_unmap (demux->adapter);
1979     return GST_FLOW_LOST_SYNC;
1980   }
1981 need_more_data:
1982   {
1983     GST_DEBUG_OBJECT (demux, "need more data");
1984     return GST_FLOW_NEED_MORE_DATA;
1985   }
1986 }
1987
1988 /* ISO/IEC 13818-1:
1989  * system_header () {
1990  *     system_header_start_code                          32  bslbf  -+
1991  *     header_length                                     16  uimsbf  |
1992  *     marker_bit                                         1  bslbf   |
1993  *     rate_bound                                        22  uimsbf  |
1994  *     marker_bit                                         1  bslbf   |
1995  *     audio_bound                                        6  uimsbf  |
1996  *     fixed_flag                                         1  bslbf   |
1997  *     CSPS_flag                                          1  bslbf   | 96 bits
1998  *     system_audio_lock_flag                             1  bslbf   |
1999  *     system_video_lock_flag                             1  bslbf   |
2000  *     marker_bit                                         1  bslbf   |
2001  *     video_bound                                        5  uimsbf  |
2002  *     packet_rate_restriction_flag                       1  bslbf   |
2003  *     reserved_bits                                      7  bslbf  -+
2004  *     while (nextbits () = = '1') {
2005  *         stream_id                                      8  uimsbf -+
2006  *         '11'                                           2  bslbf   | 24 bits
2007  *         P-STD_buffer_bound_scale                       1  bslbf   |
2008  *         P-STD_buffer_size_bound                       13  uimsbf -+
2009  *     }
2010  * }
2011  * 96 bits = 12 bytes, 24 bits = 3 bytes.
2012  */
2013
2014 static GstFlowReturn
2015 gst_ps_demux_parse_sys_head (GstPsDemux * demux)
2016 {
2017   guint16 length;
2018   const guint8 *data;
2019 #ifndef GST_DISABLE_GST_DEBUG
2020   gboolean csps;
2021 #endif
2022
2023   if (gst_adapter_available (demux->adapter) < 6)
2024     goto need_more_data;
2025
2026   /* start code + length */
2027   data = gst_adapter_map (demux->adapter, 6);
2028
2029   /* skip start code */
2030   data += 4;
2031
2032   length = GST_READ_UINT16_BE (data);
2033   GST_DEBUG_OBJECT (demux, "length %d", length);
2034
2035   length += 6;
2036
2037   gst_adapter_unmap (demux->adapter);
2038   if (gst_adapter_available (demux->adapter) < length)
2039     goto need_more_data;
2040
2041   data = gst_adapter_map (demux->adapter, length);
2042
2043   /* skip start code and length */
2044   data += 6;
2045
2046   /* marker:1==1 ! rate_bound:22 | marker:1==1 */
2047   if ((*data & 0x80) != 0x80)
2048     goto marker_expected;
2049
2050   {
2051     guint32 rate_bound;
2052
2053     if ((data[2] & 0x01) != 0x01)
2054       goto marker_expected;
2055
2056     rate_bound = ((guint32) data[0] & 0x7f) << 15;
2057     rate_bound |= ((guint32) data[1]) << 7;
2058     rate_bound |= ((guint32) data[2] & 0xfe) >> 1;
2059     rate_bound *= MPEG_MUX_RATE_MULT;
2060
2061     GST_DEBUG_OBJECT (demux, "rate bound %u", rate_bound);
2062
2063     data += 3;
2064   }
2065
2066   /* audio_bound:6==1 ! fixed:1 | constrained:1 */
2067   {
2068 #ifndef GST_DISABLE_GST_DEBUG
2069     guint8 audio_bound;
2070     gboolean fixed;
2071
2072     /* max number of simultaneous audio streams active */
2073     audio_bound = (data[0] & 0xfc) >> 2;
2074     /* fixed or variable bitrate */
2075     fixed = (data[0] & 0x02) == 0x02;
2076     /* meeting constraints */
2077     csps = (data[0] & 0x01) == 0x01;
2078
2079     GST_DEBUG_OBJECT (demux, "audio_bound %d, fixed %d, constrained %d",
2080         audio_bound, fixed, csps);
2081 #endif
2082     data += 1;
2083   }
2084
2085   /* audio_lock:1 | video_lock:1 | marker:1==1 | video_bound:5 */
2086   {
2087 #ifndef GST_DISABLE_GST_DEBUG
2088     gboolean audio_lock;
2089     gboolean video_lock;
2090     guint8 video_bound;
2091
2092     audio_lock = (data[0] & 0x80) == 0x80;
2093     video_lock = (data[0] & 0x40) == 0x40;
2094 #endif
2095
2096     if ((data[0] & 0x20) != 0x20)
2097       goto marker_expected;
2098
2099 #ifndef GST_DISABLE_GST_DEBUG
2100     /* max number of simultaneous video streams active */
2101     video_bound = (data[0] & 0x1f);
2102
2103     GST_DEBUG_OBJECT (demux, "audio_lock %d, video_lock %d, video_bound %d",
2104         audio_lock, video_lock, video_bound);
2105 #endif
2106     data += 1;
2107   }
2108
2109   /* packet_rate_restriction:1 | reserved:7==0x7F */
2110   {
2111 #ifndef GST_DISABLE_GST_DEBUG
2112     gboolean packet_rate_restriction;
2113 #endif
2114     if ((data[0] & 0x7f) != 0x7f)
2115       goto marker_expected;
2116 #ifndef GST_DISABLE_GST_DEBUG
2117     /* only valid if csps is set */
2118     if (csps) {
2119       packet_rate_restriction = (data[0] & 0x80) == 0x80;
2120
2121       GST_DEBUG_OBJECT (demux, "packet_rate_restriction %d",
2122           packet_rate_restriction);
2123     }
2124 #endif
2125   }
2126   data += 1;
2127
2128   {
2129     gint stream_count = (length - 12) / 3;
2130     gint i;
2131
2132     GST_DEBUG_OBJECT (demux, "number of streams: %d ", stream_count);
2133
2134     for (i = 0; i < stream_count; i++) {
2135       guint8 stream_id;
2136 #ifndef GST_DISABLE_GST_DEBUG
2137       gboolean STD_buffer_bound_scale;
2138       guint16 STD_buffer_size_bound;
2139       guint32 buf_byte_size_bound;
2140 #endif
2141       stream_id = *data++;
2142       if (!(stream_id & 0x80))
2143         goto sys_len_error;
2144
2145       /* check marker bits */
2146       if ((*data & 0xC0) != 0xC0)
2147         goto no_placeholder_bits;
2148 #ifndef GST_DISABLE_GST_DEBUG
2149       STD_buffer_bound_scale = *data & 0x20;
2150       STD_buffer_size_bound = ((guint16) (*data++ & 0x1F)) << 8;
2151       STD_buffer_size_bound |= *data++;
2152
2153       if (STD_buffer_bound_scale == 0) {
2154         buf_byte_size_bound = STD_buffer_size_bound * 128;
2155       } else {
2156         buf_byte_size_bound = STD_buffer_size_bound * 1024;
2157       }
2158
2159       GST_DEBUG_OBJECT (demux, "STD_buffer_bound_scale %d",
2160           STD_buffer_bound_scale);
2161       GST_DEBUG_OBJECT (demux, "STD_buffer_size_bound %d or %d bytes",
2162           STD_buffer_size_bound, buf_byte_size_bound);
2163 #endif
2164     }
2165   }
2166
2167   gst_adapter_unmap (demux->adapter);
2168   gst_adapter_flush (demux->adapter, length);
2169   ADAPTER_OFFSET_FLUSH (length);
2170   return GST_FLOW_OK;
2171
2172   /* ERRORS */
2173 marker_expected:
2174   {
2175     GST_DEBUG_OBJECT (demux, "expecting marker");
2176     gst_adapter_unmap (demux->adapter);
2177     return GST_FLOW_LOST_SYNC;
2178   }
2179 no_placeholder_bits:
2180   {
2181     GST_DEBUG_OBJECT (demux, "expecting placeholder bit values"
2182         " '11' after stream id");
2183     gst_adapter_unmap (demux->adapter);
2184     return GST_FLOW_LOST_SYNC;
2185   }
2186 sys_len_error:
2187   {
2188     GST_DEBUG_OBJECT (demux, "error in system header length");
2189     gst_adapter_unmap (demux->adapter);
2190     return GST_FLOW_LOST_SYNC;
2191   }
2192 need_more_data:
2193   {
2194     GST_DEBUG_OBJECT (demux, "need more data");
2195     gst_adapter_unmap (demux->adapter);
2196     return GST_FLOW_NEED_MORE_DATA;
2197   }
2198 }
2199
2200 static GstFlowReturn
2201 gst_ps_demux_parse_psm (GstPsDemux * demux)
2202 {
2203   guint16 psm_length, info_length = 0, es_map_length = 0;
2204   guint8 psm_version = 0;
2205   GstByteReader br;
2206 #ifndef GST_DISABLE_GST_DEBUG
2207   gboolean applicable;
2208 #endif
2209
2210   /* Need at least 6 bytes for start code + length */
2211   if (gst_adapter_available (demux->adapter) < 6)
2212     goto need_more_data;
2213
2214   {
2215     const guint8 *data;
2216
2217     /* start code + length */
2218     data = gst_adapter_map (demux->adapter, 6);
2219     /* skip start code */
2220     data += 4;
2221     psm_length = GST_READ_UINT16_BE (data);
2222     GST_DEBUG_OBJECT (demux, "PSM length %u", psm_length);
2223
2224     if (G_UNLIKELY (psm_length > 0x3FA))
2225       goto psm_len_error;
2226     psm_length += 6;            /* Add start code + size to length */
2227
2228     gst_adapter_unmap (demux->adapter);
2229
2230     if (gst_adapter_available (demux->adapter) < psm_length)
2231       goto need_more_data;
2232
2233     data = gst_adapter_map (demux->adapter, psm_length);
2234
2235     gst_byte_reader_init (&br, data, psm_length);
2236   }
2237
2238   /* skip start code and length */
2239   if (!gst_byte_reader_skip (&br, 6))
2240     goto fail_invalid;
2241
2242   /* Read PSM applicable bit together with version */
2243   if (!gst_byte_reader_get_uint8 (&br, &psm_version))
2244     goto fail_invalid;
2245 #ifndef GST_DISABLE_GST_DEBUG
2246   applicable = (psm_version & 0x80) >> 7;
2247 #endif
2248   psm_version &= 0x1F;
2249   GST_DEBUG_OBJECT (demux, "PSM version %u (applicable now %u)", psm_version,
2250       applicable);
2251
2252   /* Jump over the next byte (marker bit) */
2253   if (!gst_byte_reader_skip (&br, 1))
2254     goto fail_invalid;
2255
2256   /* Read PS info length */
2257   if (!gst_byte_reader_get_uint16_be (&br, &info_length))
2258     goto fail_invalid;
2259   GST_DEBUG_OBJECT (demux, "PS info length %u bytes", info_length);
2260   /* Skip the PS info, we don't use it */
2261   if (!gst_byte_reader_skip (&br, info_length))
2262     goto fail_invalid;
2263
2264   /* Read ES map length */
2265   if (!gst_byte_reader_get_uint16_be (&br, &es_map_length))
2266     goto fail_invalid;
2267   GST_DEBUG_OBJECT (demux, "ES map length %u bytes", es_map_length);
2268
2269   /* Now read the ES map */
2270   {
2271     GstByteReader es_map_br;
2272     if (!gst_byte_reader_get_sub_reader (&br, &es_map_br, es_map_length))
2273       goto fail_invalid;
2274
2275     while (gst_byte_reader_get_remaining (&es_map_br) >= 4) {
2276       guint8 stream_type = 0, stream_id = 0;
2277       guint16 stream_info_length = 0;
2278
2279       if (!gst_byte_reader_get_uint8 (&es_map_br, &stream_type) ||
2280           !gst_byte_reader_get_uint8 (&es_map_br, &stream_id) ||
2281           !gst_byte_reader_get_uint16_be (&es_map_br, &stream_info_length))
2282         break;
2283
2284       GST_DEBUG_OBJECT (demux,
2285           "Stream type %02X with id %02X and %u bytes info", stream_type,
2286           stream_id, stream_info_length);
2287
2288       if (G_LIKELY (stream_id != 0xbd))
2289         demux->psm[stream_id] = stream_type;
2290       else {
2291         /* Ignore stream type for private_stream_1 and discover it looking at
2292          * the stream data.
2293          * Fixes demuxing some clips with lpcm that was wrongly declared as
2294          * mpeg audio */
2295         GST_DEBUG_OBJECT (demux, "stream type for private_stream_1 ignored");
2296       }
2297
2298       /* FIXME: We could use the descriptors instead of skipping them */
2299       if (!gst_byte_reader_skip (&es_map_br, stream_info_length))
2300         break;
2301     }
2302   }
2303   /* We ignore the 4-byte CRC at the end */
2304
2305   gst_adapter_unmap (demux->adapter);
2306   gst_adapter_flush (demux->adapter, psm_length);
2307   ADAPTER_OFFSET_FLUSH (psm_length);
2308   return GST_FLOW_OK;
2309
2310 fail_invalid:
2311   GST_DEBUG_OBJECT (demux, "Failed to parse PSM. Skipping");
2312   gst_adapter_unmap (demux->adapter);
2313   gst_adapter_flush (demux->adapter, psm_length);
2314   ADAPTER_OFFSET_FLUSH (psm_length);
2315   return GST_FLOW_LOST_SYNC;
2316 psm_len_error:
2317   {
2318     GST_DEBUG_OBJECT (demux, "error in PSM length");
2319     gst_adapter_unmap (demux->adapter);
2320     return GST_FLOW_LOST_SYNC;
2321   }
2322 need_more_data:
2323   {
2324     GST_DEBUG_OBJECT (demux, "need more data");
2325     return GST_FLOW_NEED_MORE_DATA;
2326   }
2327 }
2328
2329 static void
2330 gst_ps_demux_resync_cb (GstPESFilter * filter, GstPsDemux * demux)
2331 {
2332 }
2333
2334 static GstFlowReturn
2335 gst_ps_demux_data_cb (GstPESFilter * filter, gboolean first,
2336     GstBuffer * buffer, GstPsDemux * demux)
2337 {
2338   GstBuffer *out_buf;
2339   GstFlowReturn ret = GST_FLOW_OK;
2340   gint stream_type;
2341   guint32 start_code;
2342   guint8 id;
2343   GstMapInfo map;
2344   gsize datalen;
2345   guint offset = 0;
2346   gst_buffer_map (buffer, &map, GST_MAP_READ);
2347   datalen = map.size;
2348   start_code = filter->start_code;
2349   id = filter->id;
2350   if (first) {
2351     gint layer = 0;
2352     /* find the stream type */
2353     stream_type = demux->psm[id];
2354     if (stream_type == -1) {
2355       /* no stream type, if PS1, get the new id */
2356       if (start_code == ID_PRIVATE_STREAM_1 && datalen >= 2) {
2357         /* VDR writes A52 streams without any header bytes
2358          * (see ftp://ftp.mplayerhq.hu/MPlayer/samples/MPEG-VOB/vdr-AC3) */
2359         if (datalen >= 4) {
2360           guint hdr = GST_READ_UINT32_BE (map.data);
2361           if (G_UNLIKELY ((hdr & 0xffff0000) == AC3_SYNC_WORD)) {
2362             id = 0x80;
2363             stream_type = demux->psm[id] = ST_GST_AUDIO_RAWA52;
2364             GST_DEBUG_OBJECT (demux, "Found VDR raw A52 stream");
2365           }
2366         }
2367
2368         if (G_LIKELY (stream_type == -1)) {
2369           /* new id is in the first byte */
2370           id = map.data[offset++];
2371           datalen--;
2372           /* and remap */
2373           stream_type = demux->psm[id];
2374           /* Now, if it's a subpicture stream - no more, otherwise
2375            * take the first byte too, since it's the frame count in audio
2376            * streams and our backwards compat convention is to strip it off */
2377           if (stream_type != ST_PS_DVD_SUBPICTURE) {
2378             /* Number of audio frames in this packet */
2379 #ifndef GST_DISABLE_GST_DEBUG
2380             guint8 nframes;
2381             nframes = map.data[offset];
2382             GST_LOG_OBJECT (demux, "private type 0x%02x, %d frames", id,
2383                 nframes);
2384 #endif
2385             offset++;
2386             datalen--;
2387           } else {
2388             GST_LOG_OBJECT (demux, "private type 0x%02x, stream type %d",
2389                 id, stream_type);
2390           }
2391         }
2392       }
2393       if (stream_type == -1)
2394         goto unknown_stream_type;
2395     } else if (stream_type == ST_AUDIO_MPEG1 || stream_type == ST_AUDIO_MPEG2) {
2396       if (datalen >= 2) {
2397         guint hdr = GST_READ_UINT16_BE (map.data);
2398         if ((hdr & 0xfff0) == 0xfff0) {
2399           switch (hdr & 0x06) {
2400             case 0x6:
2401               layer = 1;
2402               break;
2403             case 0x4:
2404               layer = 2;
2405               break;
2406             case 0x2:
2407               layer = 3;
2408               break;
2409             default:
2410               GST_WARNING_OBJECT (demux, "unknown mpeg audio layer");
2411           }
2412         }
2413       }
2414     }
2415
2416     if (filter->pts != -1) {
2417       demux->next_pts = filter->pts + demux->scr_adjust;
2418       GST_LOG_OBJECT (demux, "stream 0x%02x PTS = orig %" G_GUINT64_FORMAT
2419           " (%" G_GUINT64_FORMAT ")", id, filter->pts, demux->next_pts);
2420     } else
2421       demux->next_pts = G_MAXUINT64;
2422     if (filter->dts != -1) {
2423       demux->next_dts = filter->dts + demux->scr_adjust;
2424       GST_LOG_OBJECT (demux, "stream 0x%02x DTS = orig %" G_GUINT64_FORMAT
2425           " (%" G_GUINT64_FORMAT ")", id, filter->dts, demux->next_dts);
2426     } else {
2427       demux->next_dts = demux->next_pts;
2428     }
2429
2430     demux->current_stream =
2431         gst_ps_demux_get_stream (demux, id, stream_type, layer);
2432   }
2433
2434   if (G_UNLIKELY (demux->current_stream == NULL)) {
2435     GST_DEBUG_OBJECT (demux, "Dropping buffer for unknown stream id 0x%02x",
2436         id);
2437     goto done;
2438   }
2439
2440   /* After 2 seconds of bitstream emit no more pads */
2441   if (demux->need_no_more_pads
2442       && (demux->current_scr - demux->first_scr) > 2 * CLOCK_FREQ) {
2443     GST_DEBUG_OBJECT (demux, "no more pads, notifying");
2444     gst_element_no_more_pads (GST_ELEMENT_CAST (demux));
2445     demux->need_no_more_pads = FALSE;
2446   }
2447
2448   /* If the stream is not-linked, don't bother creating a sub-buffer
2449    * to send to it, unless we're processing a discont (which resets
2450    * the not-linked status and tries again */
2451   if (demux->current_stream->discont) {
2452     GST_DEBUG_OBJECT (demux, "stream is discont");
2453     demux->current_stream->notlinked = FALSE;
2454   }
2455
2456   if (demux->current_stream->notlinked == FALSE) {
2457     out_buf =
2458         gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, offset, datalen);
2459     ret = gst_ps_demux_send_data (demux, demux->current_stream, out_buf);
2460     if (ret == GST_FLOW_NOT_LINKED) {
2461       demux->current_stream->notlinked = TRUE;
2462     }
2463   }
2464
2465 done:
2466   gst_buffer_unmap (buffer, &map);
2467   gst_buffer_unref (buffer);
2468   return ret;
2469   /* ERRORS */
2470 unknown_stream_type:
2471   {
2472     GST_DEBUG_OBJECT (demux, "unknown stream type %02x", id);
2473     ret = GST_FLOW_OK;
2474     goto done;
2475   }
2476 }
2477
2478 static gboolean
2479 gst_ps_demux_resync (GstPsDemux * demux, gboolean save)
2480 {
2481   const guint8 *data;
2482   gint avail;
2483   guint32 code;
2484   gint offset;
2485   gboolean found;
2486   avail = gst_adapter_available (demux->adapter);
2487   if (G_UNLIKELY (avail < 4))
2488     goto need_data;
2489   /* Common case, read 4 bytes an check it */
2490   data = gst_adapter_map (demux->adapter, 4);
2491   /* read currect code */
2492   code = GST_READ_UINT32_BE (data);
2493   /* The common case is that the sync code is at 0 bytes offset */
2494   if (G_LIKELY ((code & 0xffffff00) == 0x100L)) {
2495     GST_LOG_OBJECT (demux, "Found resync code %08x after 0 bytes", code);
2496     demux->last_sync_code = code;
2497     gst_adapter_unmap (demux->adapter);
2498     return TRUE;
2499   }
2500
2501   /* Otherwise, we are starting at byte 4 and we need to search
2502      the sync code in all available data in the adapter */
2503   offset = 4;
2504   if (offset >= avail)
2505     goto need_data;             /* Not enough data to find sync */
2506   data = gst_adapter_map (demux->adapter, avail);
2507   do {
2508     code = (code << 8) | data[offset++];
2509     found = (code & 0xffffff00) == 0x100L;
2510   } while (offset < avail && !found);
2511   gst_adapter_unmap (demux->adapter);
2512   if (!save || demux->sink_segment.rate >= 0.0) {
2513     GST_LOG_OBJECT (demux, "flushing %d bytes", offset - 4);
2514     /* forward playback, we can discard and flush the skipped bytes */
2515     gst_adapter_flush (demux->adapter, offset - 4);
2516     ADAPTER_OFFSET_FLUSH (offset - 4);
2517   } else {
2518     if (found) {
2519       GST_LOG_OBJECT (demux, "reverse saving %d bytes", offset - 4);
2520       /* reverse playback, we keep the flushed bytes and we will append them to
2521        * the next buffer in the chain function, which is the previous buffer in
2522        * the stream. */
2523       gst_adapter_push (demux->rev_adapter,
2524           gst_adapter_take_buffer (demux->adapter, offset - 4));
2525     } else {
2526       GST_LOG_OBJECT (demux, "reverse saving %d bytes", avail);
2527       /* nothing found, keep all bytes */
2528       gst_adapter_push (demux->rev_adapter,
2529           gst_adapter_take_buffer (demux->adapter, avail));
2530     }
2531   }
2532
2533   if (found) {
2534     GST_LOG_OBJECT (demux, "Found resync code %08x after %d bytes",
2535         code, offset - 4);
2536     demux->last_sync_code = code;
2537   } else {
2538     GST_LOG_OBJECT (demux, "No resync after skipping %d", offset);
2539   }
2540
2541   return found;
2542 need_data:
2543   {
2544     GST_LOG_OBJECT (demux, "we need more data for resync %d", avail);
2545     return FALSE;
2546   }
2547 }
2548
2549 static inline gboolean
2550 gst_ps_demux_is_pes_sync (guint32 sync)
2551 {
2552   return ((sync & 0xfc) == 0xbc) ||
2553       ((sync & 0xe0) == 0xc0) || ((sync & 0xf0) == 0xe0);
2554 }
2555
2556 static inline gboolean
2557 gst_ps_demux_scan_ts (GstPsDemux * demux, const guint8 * data,
2558     SCAN_MODE mode, guint64 * rts, const guint8 * end)
2559 {
2560   gboolean ret = FALSE;
2561   guint32 scr1, scr2;
2562   guint64 scr;
2563   guint64 pts, dts;
2564   guint32 code;
2565   guint16 len;
2566   /* read the 4 bytes for the sync code */
2567   code = GST_READ_UINT32_BE (data);
2568   if (G_LIKELY (code != ID_PS_PACK_START_CODE))
2569     goto beach;
2570   if (data + 12 > end)
2571     goto beach;
2572   /* skip start code */
2573   data += 4;
2574   scr1 = GST_READ_UINT32_BE (data);
2575   scr2 = GST_READ_UINT32_BE (data + 4);
2576   /* start parsing the stream */
2577   if ((*data & 0xc0) == 0x40) {
2578     /* MPEG-2 PACK header */
2579     guint32 scr_ext;
2580     guint32 next32;
2581     guint8 stuffing_bytes;
2582     /* :2=01 ! scr:3 ! marker:1==1 ! scr:15 ! marker:1==1 ! scr:15 */
2583     /* check markers */
2584     if ((scr1 & 0xc4000400) != 0x44000400)
2585       goto beach;
2586     scr = ((guint64) scr1 & 0x38000000) << 3;
2587     scr |= ((guint64) scr1 & 0x03fff800) << 4;
2588     scr |= ((guint64) scr1 & 0x000003ff) << 5;
2589     scr |= ((guint64) scr2 & 0xf8000000) >> 27;
2590     /* marker:1==1 ! scr_ext:9 ! marker:1==1 */
2591     if ((scr2 & 0x04010000) != 0x04010000)
2592       goto beach;
2593     scr_ext = (scr2 & 0x03fe0000) >> 17;
2594     if (scr_ext) {
2595       scr = (scr * 300 + scr_ext % 300) / 300;
2596     }
2597     /* SCR has been converted into units of 90Khz ticks to make it comparable
2598        to DTS/PTS, that also implies 1 tick rounding error */
2599     data += 6;
2600
2601     if (data + 4 > end)
2602       goto beach;
2603     /* PMR:22 ! :2==11 ! reserved:5 ! stuffing_len:3 */
2604     next32 = GST_READ_UINT32_BE (data);
2605     if ((next32 & 0x00000300) != 0x00000300)
2606       goto beach;
2607     stuffing_bytes = (next32 & 0x07);
2608     data += 4;
2609     if (data + stuffing_bytes > end)
2610       goto beach;
2611     while (stuffing_bytes--) {
2612       if (*data++ != 0xff)
2613         goto beach;
2614     }
2615   } else {
2616     /* MPEG-1 pack header */
2617     /* check markers */
2618     if ((scr1 & 0xf1000100) != 0x21000100)
2619       goto beach;
2620     if ((scr2 & 0x01800001) != 0x01800001)
2621       goto beach;
2622     /* :4=0010 ! scr:3 ! marker:1==1 ! scr:15 ! marker:1==1 ! scr:15 ! marker:1==1 */
2623     scr = ((guint64) scr1 & 0x0e000000) << 5;
2624     scr |= ((guint64) scr1 & 0x00fffe00) << 6;
2625     scr |= ((guint64) scr1 & 0x000000ff) << 7;
2626     scr |= ((guint64) scr2 & 0xfe000000) >> 25;
2627     data += 8;
2628   }
2629
2630   if (mode == SCAN_SCR) {
2631     *rts = scr;
2632     ret = TRUE;
2633     goto beach;
2634   }
2635
2636   /* Possible optional System header here */
2637   if (data + 8 > end)
2638     goto beach;
2639
2640   code = GST_READ_UINT32_BE (data);
2641   len = GST_READ_UINT16_BE (data + 4);
2642   if (code == ID_PS_SYSTEM_HEADER_START_CODE) {
2643     /* Found a system header, skip it */
2644     /* Check for sufficient data - system header, plus enough
2645      * left over for the PES packet header */
2646     if (data + 6 + len + 6 > end)
2647       return FALSE;
2648     data += len + 6;
2649     /* read the 4 bytes for the PES sync code */
2650     code = GST_READ_UINT32_BE (data);
2651     len = GST_READ_UINT16_BE (data + 4);
2652   }
2653
2654   /* Check we have enough data left for reading the PES packet */
2655   if (data + 6 + len > end)
2656     return FALSE;
2657   if (!gst_ps_demux_is_pes_sync (code))
2658     goto beach;
2659   switch (code) {
2660     case ID_PS_PROGRAM_STREAM_MAP:
2661     case ID_PRIVATE_STREAM_2:
2662     case ID_ECM_STREAM:
2663     case ID_EMM_STREAM:
2664     case ID_PROGRAM_STREAM_DIRECTORY:
2665     case ID_DSMCC_STREAM:
2666     case ID_ITU_TREC_H222_TYPE_E_STREAM:
2667     case ID_PADDING_STREAM:
2668       goto beach;
2669     default:
2670       break;
2671   }
2672
2673   /* skip sync code and size */
2674   data += 6;
2675   pts = dts = -1;
2676   /* stuffing bits, first two bits are '10' for mpeg2 pes so this code is
2677    * not triggered. */
2678   while (TRUE) {
2679     if (*data != 0xff)
2680       break;
2681     data++;
2682   }
2683
2684   /* STD buffer size, never for mpeg2 */
2685   if ((*data & 0xc0) == 0x40)
2686     data += 2;
2687   /* PTS but no DTS, never for mpeg2 */
2688   if ((*data & 0xf0) == 0x20) {
2689     READ_TS (data, pts, beach);
2690   }
2691   /* PTS and DTS, never for mpeg2 */
2692   else if ((*data & 0xf0) == 0x30) {
2693     READ_TS (data, pts, beach);
2694     READ_TS (data, dts, beach);
2695   } else if ((*data & 0xc0) == 0x80) {
2696     /* mpeg2 case */
2697     guchar flags;
2698     /* 2: '10'
2699      * 2: PES_scrambling_control
2700      * 1: PES_priority
2701      * 1: data_alignment_indicator
2702      * 1: copyright
2703      * 1: original_or_copy
2704      */
2705     flags = *data++;
2706     if ((flags & 0xc0) != 0x80)
2707       goto beach;
2708     /* 2: PTS_DTS_flags
2709      * 1: ESCR_flag
2710      * 1: ES_rate_flag
2711      * 1: DSM_trick_mode_flag
2712      * 1: additional_copy_info_flag
2713      * 1: PES_CRC_flag
2714      * 1: PES_extension_flag
2715      */
2716     flags = *data++;
2717     /* 8: PES_header_data_length */
2718     data++;
2719     /* only DTS: this is invalid */
2720     if ((flags & 0xc0) == 0x40)
2721       goto beach;
2722     /* check for PTS */
2723     if ((flags & 0x80)) {
2724       READ_TS (data, pts, beach);
2725     }
2726     /* check for DTS */
2727     if ((flags & 0x40)) {
2728       READ_TS (data, dts, beach);
2729     }
2730   }
2731
2732   if (mode == SCAN_DTS && dts != (guint64) - 1) {
2733     *rts = dts;
2734     ret = TRUE;
2735   }
2736
2737   if (mode == SCAN_PTS && pts != (guint64) - 1) {
2738     *rts = pts;
2739     ret = TRUE;
2740   }
2741 beach:
2742   return ret;
2743 }
2744
2745 static inline gboolean
2746 gst_ps_demux_scan_forward_ts (GstPsDemux * demux, guint64 * pos,
2747     SCAN_MODE mode, guint64 * rts, gint limit)
2748 {
2749   GstFlowReturn ret = GST_FLOW_OK;
2750   GstBuffer *buffer;
2751   guint64 offset = *pos;
2752   gboolean found = FALSE;
2753   guint64 ts = 0;
2754   guint scan_sz = (mode == SCAN_SCR ? SCAN_SCR_SZ : SCAN_PTS_SZ);
2755   guint cursor, to_read = BLOCK_SZ;
2756   guint end_scan;
2757   GstMapInfo map;
2758   do {
2759     /* Check we can get at least scan_sz bytes */
2760     if (offset + scan_sz > demux->sink_segment.stop)
2761       return FALSE;
2762     /* Don't go further than 'limit' bytes */
2763     if (limit && offset > *pos + limit)
2764       return FALSE;
2765     if (offset + to_read > demux->sink_segment.stop)
2766       to_read = demux->sink_segment.stop - offset;
2767     /* read some data */
2768     buffer = NULL;
2769     ret = gst_pad_pull_range (demux->sinkpad, offset, to_read, &buffer);
2770     if (G_UNLIKELY (ret != GST_FLOW_OK))
2771       return FALSE;
2772     gst_buffer_map (buffer, &map, GST_MAP_READ);
2773     /* may get a short buffer at the end of the file */
2774     if (G_UNLIKELY (map.size <= scan_sz)) {
2775       gst_buffer_unmap (buffer, &map);
2776       gst_buffer_unref (buffer);
2777       return FALSE;
2778     }
2779
2780     end_scan = map.size - scan_sz;
2781     /* scan the block */
2782     for (cursor = 0; !found && cursor <= end_scan; cursor++) {
2783       found = gst_ps_demux_scan_ts (demux, map.data + cursor, mode, &ts,
2784           map.data + map.size);
2785     }
2786
2787     /* done with the buffer, unref it */
2788     gst_buffer_unmap (buffer, &map);
2789     gst_buffer_unref (buffer);
2790     if (found) {
2791       *rts = ts;
2792       *pos = offset + cursor - 1;
2793     } else {
2794       offset += cursor;
2795     }
2796   } while (!found && offset < demux->sink_segment.stop);
2797   return found;
2798 }
2799
2800 static inline gboolean
2801 gst_ps_demux_scan_backward_ts (GstPsDemux * demux, guint64 * pos,
2802     SCAN_MODE mode, guint64 * rts, gint limit)
2803 {
2804   GstFlowReturn ret = GST_FLOW_OK;
2805   GstBuffer *buffer;
2806   guint64 offset = *pos;
2807   gboolean found = FALSE;
2808   guint64 ts = 0;
2809   guint scan_sz = (mode == SCAN_SCR ? SCAN_SCR_SZ : SCAN_PTS_SZ);
2810   guint cursor, to_read = BLOCK_SZ;
2811   guint start_scan;
2812   guint8 *data;
2813   GstMapInfo map;
2814   do {
2815     /* Check we have at least scan_sz bytes available */
2816     if (offset < scan_sz - 1)
2817       return FALSE;
2818     /* Don't go backward past the start or 'limit' bytes */
2819     if (limit && offset + limit < *pos)
2820       return FALSE;
2821     if (offset > BLOCK_SZ)
2822       offset -= BLOCK_SZ;
2823     else {
2824       to_read = offset + 1;
2825       offset = 0;
2826     }
2827     /* read some data */
2828     buffer = NULL;
2829     ret = gst_pad_pull_range (demux->sinkpad, offset, to_read, &buffer);
2830     if (G_UNLIKELY (ret != GST_FLOW_OK))
2831       return FALSE;
2832     gst_buffer_map (buffer, &map, GST_MAP_READ);
2833     /* may get a short buffer at the end of the file */
2834     if (G_UNLIKELY (map.size <= scan_sz)) {
2835       gst_buffer_unmap (buffer, &map);
2836       gst_buffer_unref (buffer);
2837       return FALSE;
2838     }
2839
2840     start_scan = map.size - scan_sz;
2841     data = map.data + start_scan;
2842     /* scan the block */
2843     for (cursor = (start_scan + 1); !found && cursor > 0; cursor--) {
2844       found = gst_ps_demux_scan_ts (demux, data--, mode, &ts,
2845           map.data + map.size);
2846     }
2847
2848     /* done with the buffer, unref it */
2849     gst_buffer_unmap (buffer, &map);
2850     gst_buffer_unref (buffer);
2851     if (found) {
2852       *rts = ts;
2853       *pos = offset + cursor;
2854     }
2855
2856   } while (!found && offset > 0);
2857   return found;
2858 }
2859
2860 static inline gboolean
2861 gst_ps_sink_get_duration (GstPsDemux * demux)
2862 {
2863   gboolean res = FALSE;
2864   GstPad *peer;
2865   GstFormat format = GST_FORMAT_BYTES;
2866   gint64 length = 0;
2867   guint64 offset;
2868   guint i;
2869   guint64 scr = 0;
2870   /* init the sink segment */
2871   gst_segment_init (&demux->sink_segment, format);
2872   /* get peer to figure out length */
2873   if ((peer = gst_pad_get_peer (demux->sinkpad)) == NULL)
2874     goto beach;
2875   res = gst_pad_query_duration (peer, format, &length);
2876   gst_object_unref (peer);
2877   if (!res || length <= 0)
2878     goto beach;
2879   GST_DEBUG_OBJECT (demux, "file length %" G_GINT64_FORMAT, length);
2880   /* update the sink segment */
2881   demux->sink_segment.stop = length;
2882   gst_segment_set_duration (&demux->sink_segment, format, length);
2883   gst_segment_set_position (&demux->sink_segment, format, 0);
2884   /* Scan for notorious SCR and PTS to calculate the duration */
2885   /* scan for first SCR in the stream */
2886   offset = demux->sink_segment.start;
2887   gst_ps_demux_scan_forward_ts (demux, &offset, SCAN_SCR,
2888       &demux->first_scr, DURATION_SCAN_LIMIT);
2889   GST_DEBUG_OBJECT (demux,
2890       "First SCR: %" G_GINT64_FORMAT " %" GST_TIME_FORMAT
2891       " in packet starting at %" G_GUINT64_FORMAT, demux->first_scr,
2892       GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (demux->first_scr)), offset);
2893   demux->first_scr_offset = offset;
2894   /* scan for last SCR in the stream */
2895   offset = demux->sink_segment.stop;
2896   gst_ps_demux_scan_backward_ts (demux, &offset, SCAN_SCR,
2897       &demux->last_scr, DURATION_SCAN_LIMIT);
2898   GST_DEBUG_OBJECT (demux,
2899       "Last SCR: %" G_GINT64_FORMAT " %" GST_TIME_FORMAT
2900       " in packet starting at %" G_GUINT64_FORMAT, demux->last_scr,
2901       GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (demux->last_scr)), offset);
2902   demux->last_scr_offset = offset;
2903   /* scan for first PTS in the stream */
2904   offset = demux->sink_segment.start;
2905   gst_ps_demux_scan_forward_ts (demux, &offset, SCAN_PTS,
2906       &demux->first_pts, DURATION_SCAN_LIMIT);
2907   GST_DEBUG_OBJECT (demux,
2908       "First PTS: %" G_GINT64_FORMAT " %" GST_TIME_FORMAT
2909       " in packet starting at %" G_GUINT64_FORMAT, demux->first_pts,
2910       GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (demux->first_pts)), offset);
2911   if (demux->first_pts != G_MAXUINT64) {
2912     /* scan for last PTS in the stream */
2913     offset = demux->sink_segment.stop;
2914     gst_ps_demux_scan_backward_ts (demux, &offset, SCAN_PTS,
2915         &demux->last_pts, DURATION_SCAN_LIMIT);
2916     GST_DEBUG_OBJECT (demux,
2917         "Last PTS: %" G_GINT64_FORMAT " %" GST_TIME_FORMAT
2918         " in packet starting at %" G_GUINT64_FORMAT, demux->last_pts,
2919         GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (demux->last_pts)), offset);
2920   }
2921   /* Detect wrong SCR values */
2922   if (demux->first_scr > demux->last_scr) {
2923     GST_DEBUG_OBJECT (demux, "Wrong SCR values detected, searching for "
2924         "a better first SCR value");
2925     offset = demux->first_scr_offset;
2926     for (i = 0; i < 10; i++) {
2927       offset++;
2928       gst_ps_demux_scan_forward_ts (demux, &offset, SCAN_SCR, &scr, 0);
2929       if (scr < demux->last_scr) {
2930         demux->first_scr = scr;
2931         demux->first_scr_offset = offset;
2932         /* Start demuxing from the right place */
2933         demux->sink_segment.position = offset;
2934         GST_DEBUG_OBJECT (demux, "Replaced First SCR: %" G_GINT64_FORMAT
2935             " %" GST_TIME_FORMAT " in packet starting at %"
2936             G_GUINT64_FORMAT, demux->first_scr,
2937             GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (demux->first_scr)), offset);
2938         break;
2939       }
2940     }
2941   }
2942   /* Set the base_time and avg rate */
2943   demux->base_time = MPEGTIME_TO_GSTTIME (demux->first_scr);
2944   demux->scr_rate_n = demux->last_scr_offset - demux->first_scr_offset;
2945   demux->scr_rate_d = demux->last_scr - demux->first_scr;
2946   if (G_LIKELY (demux->first_pts != G_MAXUINT64 &&
2947           demux->last_pts != G_MAXUINT64)) {
2948     /* update the src segment */
2949     demux->src_segment.format = GST_FORMAT_TIME;
2950     demux->src_segment.start =
2951         MPEGTIME_TO_GSTTIME (demux->first_pts) - demux->base_time;
2952     demux->src_segment.stop = -1;
2953     gst_segment_set_duration (&demux->src_segment, GST_FORMAT_TIME,
2954         MPEGTIME_TO_GSTTIME (demux->last_pts - demux->first_pts));
2955     gst_segment_set_position (&demux->src_segment, GST_FORMAT_TIME,
2956         demux->src_segment.start);
2957   }
2958   GST_INFO_OBJECT (demux, "sink segment configured %" GST_SEGMENT_FORMAT,
2959       &demux->sink_segment);
2960   GST_INFO_OBJECT (demux, "src segment configured %" GST_SEGMENT_FORMAT,
2961       &demux->src_segment);
2962   res = TRUE;
2963 beach:
2964   return res;
2965 }
2966
2967 static inline GstFlowReturn
2968 gst_ps_demux_pull_block (GstPad * pad, GstPsDemux * demux,
2969     guint64 offset, guint size)
2970 {
2971   GstFlowReturn ret;
2972   GstBuffer *buffer = NULL;
2973   ret = gst_pad_pull_range (pad, offset, size, &buffer);
2974   if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2975     GST_DEBUG_OBJECT (demux, "pull range at %" G_GUINT64_FORMAT
2976         " size %u failed", offset, size);
2977     goto beach;
2978   } else
2979     GST_LOG_OBJECT (demux, "pull range at %" G_GUINT64_FORMAT
2980         " size %u done", offset, size);
2981   if (demux->sink_segment.rate < 0) {
2982     GST_LOG_OBJECT (demux, "setting discont flag on backward rate");
2983     GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
2984   }
2985   ret = gst_ps_demux_chain (pad, GST_OBJECT (demux), buffer);
2986 beach:
2987   return ret;
2988 }
2989
2990 static void
2991 gst_ps_demux_loop (GstPad * pad)
2992 {
2993   GstPsDemux *demux;
2994   GstFlowReturn ret = GST_FLOW_OK;
2995   guint64 offset = 0;
2996   demux = GST_PS_DEMUX (gst_pad_get_parent (pad));
2997   if (G_UNLIKELY (demux->flushing)) {
2998     ret = GST_FLOW_FLUSHING;
2999     goto pause;
3000   }
3001
3002   if (G_UNLIKELY (demux->sink_segment.format == GST_FORMAT_UNDEFINED))
3003     gst_ps_sink_get_duration (demux);
3004   offset = demux->sink_segment.position;
3005   if (demux->sink_segment.rate >= 0) {
3006     guint size = BLOCK_SZ;
3007     if (G_LIKELY (demux->sink_segment.stop != (guint64) - 1)) {
3008       size = MIN (size, demux->sink_segment.stop - offset);
3009     }
3010     /* pull in data */
3011     ret = gst_ps_demux_pull_block (pad, demux, offset, size);
3012     /* pause if something went wrong */
3013     if (G_UNLIKELY (ret != GST_FLOW_OK))
3014       goto pause;
3015     /* update our position */
3016     offset += size;
3017     gst_segment_set_position (&demux->sink_segment, GST_FORMAT_BYTES, offset);
3018     /* check EOS condition */
3019     /* FIXME: The src_segment.stop is not including the SCR after seek(set) */
3020     if ((demux->sink_segment.position >= demux->sink_segment.stop) ||
3021         (demux->src_segment.stop != (guint64) - 1 &&
3022             demux->src_segment.position >=
3023             demux->src_segment.stop + demux->base_time)) {
3024       GST_DEBUG_OBJECT (demux,
3025           "forward mode using segment reached end of " "segment pos %"
3026           GST_TIME_FORMAT " stop %" GST_TIME_FORMAT " pos in bytes %"
3027           G_GUINT64_FORMAT " stop in bytes %" G_GUINT64_FORMAT,
3028           GST_TIME_ARGS (demux->src_segment.position),
3029           GST_TIME_ARGS (demux->src_segment.stop),
3030           demux->sink_segment.position, demux->sink_segment.stop);
3031       ret = GST_FLOW_EOS;
3032       goto pause;
3033     }
3034   } else {                      /* Reverse playback */
3035     guint64 size = MIN (offset, BLOCK_SZ);
3036     /* pull in data */
3037     ret = gst_ps_demux_pull_block (pad, demux, offset - size, size);
3038     /* pause if something went wrong */
3039     if (G_UNLIKELY (ret != GST_FLOW_OK))
3040       goto pause;
3041     /* update our position */
3042     offset -= size;
3043     gst_segment_set_position (&demux->sink_segment, GST_FORMAT_BYTES, offset);
3044     /* check EOS condition */
3045     if (demux->sink_segment.position <= demux->sink_segment.start ||
3046         demux->src_segment.position <= demux->src_segment.start) {
3047       GST_DEBUG_OBJECT (demux,
3048           "reverse mode using segment reached end of " "segment pos %"
3049           GST_TIME_FORMAT " stop %" GST_TIME_FORMAT " pos in bytes %"
3050           G_GUINT64_FORMAT " stop in bytes %" G_GUINT64_FORMAT,
3051           GST_TIME_ARGS (demux->src_segment.position),
3052           GST_TIME_ARGS (demux->src_segment.start),
3053           demux->sink_segment.position, demux->sink_segment.start);
3054       ret = GST_FLOW_EOS;
3055       goto pause;
3056     }
3057   }
3058
3059   gst_object_unref (demux);
3060   return;
3061 pause:
3062   {
3063     const gchar *reason = gst_flow_get_name (ret);
3064     GST_LOG_OBJECT (demux, "pausing task, reason %s", reason);
3065     gst_pad_pause_task (pad);
3066     if (ret == GST_FLOW_EOS) {
3067       /* perform EOS logic */
3068       gst_element_no_more_pads (GST_ELEMENT_CAST (demux));
3069       if (demux->src_segment.flags & GST_SEEK_FLAG_SEGMENT) {
3070         gint64 stop;
3071         /* for segment playback we need to post when (in stream time)
3072          * we stopped, this is either stop (when set) or the duration. */
3073         if ((stop = demux->src_segment.stop) == -1)
3074           stop = demux->src_segment.duration;
3075         if (demux->sink_segment.rate >= 0) {
3076           GST_LOG_OBJECT (demux, "Sending segment done, at end of segment");
3077           gst_element_post_message (GST_ELEMENT_CAST (demux),
3078               gst_message_new_segment_done (GST_OBJECT_CAST (demux),
3079                   GST_FORMAT_TIME, stop));
3080           gst_ps_demux_send_event (demux,
3081               gst_event_new_segment_done (GST_FORMAT_TIME, stop));
3082         } else {                /* Reverse playback */
3083           GST_LOG_OBJECT (demux,
3084               "Sending segment done, at beginning of " "segment");
3085           gst_element_post_message (GST_ELEMENT_CAST (demux),
3086               gst_message_new_segment_done (GST_OBJECT_CAST (demux),
3087                   GST_FORMAT_TIME, demux->src_segment.start));
3088           gst_ps_demux_send_event (demux,
3089               gst_event_new_segment_done (GST_FORMAT_TIME,
3090                   demux->src_segment.start));
3091         }
3092       } else {
3093         GstEvent *event;
3094         /* normal playback, send EOS to all linked pads */
3095         gst_element_no_more_pads (GST_ELEMENT (demux));
3096         GST_LOG_OBJECT (demux, "Sending EOS, at end of stream");
3097         event = gst_event_new_eos ();
3098         if (demux->segment_seqnum)
3099           gst_event_set_seqnum (event, demux->segment_seqnum);
3100         if (!gst_ps_demux_send_event (demux, event)
3101             && !have_open_streams (demux)) {
3102           GST_WARNING_OBJECT (demux, "EOS and no streams open");
3103           GST_ELEMENT_ERROR (demux, STREAM, FAILED,
3104               ("Internal data stream error."), ("No valid streams detected"));
3105         }
3106       }
3107     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
3108       GstEvent *event;
3109       GST_ELEMENT_FLOW_ERROR (demux, ret);
3110       event = gst_event_new_eos ();
3111       if (demux->segment_seqnum)
3112         gst_event_set_seqnum (event, demux->segment_seqnum);
3113       gst_ps_demux_send_event (demux, event);
3114     }
3115
3116     gst_object_unref (demux);
3117     return;
3118   }
3119 }
3120
3121 /* If we can pull that's preferred */
3122 static gboolean
3123 gst_ps_demux_sink_activate (GstPad * sinkpad, GstObject * parent)
3124 {
3125   gboolean res = FALSE;
3126   GstQuery *query = gst_query_new_scheduling ();
3127   if (gst_pad_peer_query (sinkpad, query)) {
3128     if (gst_query_has_scheduling_mode_with_flags (query,
3129             GST_PAD_MODE_PULL, GST_SCHEDULING_FLAG_SEEKABLE)) {
3130       res = gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
3131     } else {
3132       res = gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
3133     }
3134   } else {
3135     res = gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
3136   }
3137
3138   gst_query_unref (query);
3139   return res;
3140 }
3141
3142 /* This function gets called when we activate ourselves in push mode. */
3143 static gboolean
3144 gst_ps_demux_sink_activate_push (GstPad * sinkpad, GstObject * parent,
3145     gboolean active)
3146 {
3147   GstPsDemux *demux = GST_PS_DEMUX (parent);
3148   demux->random_access = FALSE;
3149   return TRUE;
3150 }
3151
3152 /* this function gets called when we activate ourselves in pull mode.
3153  * We can perform  random access to the resource and we start a task
3154  * to start reading */
3155 static gboolean
3156 gst_ps_demux_sink_activate_pull (GstPad * sinkpad, GstObject * parent,
3157     gboolean active)
3158 {
3159   GstPsDemux *demux = GST_PS_DEMUX (parent);
3160   if (active) {
3161     GST_DEBUG ("pull mode activated");
3162     demux->random_access = TRUE;
3163     return gst_pad_start_task (sinkpad,
3164         (GstTaskFunction) gst_ps_demux_loop, sinkpad, NULL);
3165   } else {
3166     demux->random_access = FALSE;
3167     return gst_pad_stop_task (sinkpad);
3168   }
3169 }
3170
3171 static gboolean
3172 gst_ps_demux_sink_activate_mode (GstPad * pad, GstObject * parent,
3173     GstPadMode mode, gboolean active)
3174 {
3175   if (mode == GST_PAD_MODE_PUSH) {
3176     return gst_ps_demux_sink_activate_push (pad, parent, active);
3177   } else if (mode == GST_PAD_MODE_PULL) {
3178     return gst_ps_demux_sink_activate_pull (pad, parent, active);
3179   }
3180   return FALSE;
3181 }
3182
3183 /* EOS and NOT_LINKED need to be combined. This means that we return:
3184 *
3185 *  GST_FLOW_NOT_LINKED: when all pads NOT_LINKED.
3186 *  GST_FLOW_EOS: when all pads EOS or NOT_LINKED.
3187 */
3188 static GstFlowReturn
3189 gst_ps_demux_combine_flows (GstPsDemux * demux, GstFlowReturn ret)
3190 {
3191   GST_LOG_OBJECT (demux, "flow return: %s", gst_flow_get_name (ret));
3192   ret = gst_flow_combiner_update_flow (demux->flowcombiner, ret);
3193   if (G_UNLIKELY (demux->need_no_more_pads && ret == GST_FLOW_NOT_LINKED))
3194     ret = GST_FLOW_OK;
3195   GST_LOG_OBJECT (demux, "combined flow return: %s", gst_flow_get_name (ret));
3196   return ret;
3197 }
3198
3199 static GstFlowReturn
3200 gst_ps_demux_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
3201 {
3202   GstPsDemux *demux = GST_PS_DEMUX (parent);
3203   GstFlowReturn ret = GST_FLOW_OK;
3204   guint32 avail;
3205   gboolean save, discont;
3206   discont = GST_BUFFER_IS_DISCONT (buffer);
3207   if (discont) {
3208     GST_LOG_OBJECT (demux,
3209         "Received buffer with discont flag and" " offset %"
3210         G_GUINT64_FORMAT, GST_BUFFER_OFFSET (buffer));
3211     gst_pes_filter_drain (&demux->filter);
3212     gst_ps_demux_mark_discont (demux, TRUE, FALSE);
3213     /* mark discont on all streams */
3214     if (demux->sink_segment.rate >= 0.0) {
3215       demux->current_scr = G_MAXUINT64;
3216       demux->bytes_since_scr = 0;
3217     }
3218   } else {
3219     GST_LOG_OBJECT (demux,
3220         "Received buffer with offset %" G_GUINT64_FORMAT,
3221         GST_BUFFER_OFFSET (buffer));
3222   }
3223
3224   /* We keep the offset to interpolate SCR */
3225   demux->adapter_offset = GST_BUFFER_OFFSET (buffer);
3226   gst_adapter_push (demux->adapter, buffer);
3227   demux->bytes_since_scr += gst_buffer_get_size (buffer);
3228   avail = gst_adapter_available (demux->rev_adapter);
3229   if (avail > 0) {
3230     GST_LOG_OBJECT (demux, "appending %u saved bytes", avail);
3231     /* if we have a previous reverse chunk, append this now */
3232     /* FIXME this code assumes we receive discont buffers all thei
3233      * time */
3234     gst_adapter_push (demux->adapter,
3235         gst_adapter_take_buffer (demux->rev_adapter, avail));
3236   }
3237
3238   avail = gst_adapter_available (demux->adapter);
3239   GST_LOG_OBJECT (demux, "avail now: %d, state %d", avail, demux->filter.state);
3240   switch (demux->filter.state) {
3241     case STATE_DATA_SKIP:
3242     case STATE_DATA_PUSH:
3243       ret = gst_pes_filter_process (&demux->filter);
3244       break;
3245     case STATE_HEADER_PARSE:
3246       break;
3247     default:
3248       break;
3249   }
3250
3251   switch (ret) {
3252     case GST_FLOW_NEED_MORE_DATA:
3253       /* Go and get more data */
3254       ret = GST_FLOW_OK;
3255       goto done;
3256     case GST_FLOW_LOST_SYNC:
3257       /* for FLOW_OK or lost-sync, carry onto resync */
3258       ret = GST_FLOW_OK;
3259       break;
3260     case GST_FLOW_OK:
3261       break;
3262     default:
3263       /* Any other return value should be sent upstream immediately */
3264       goto done;
3265   }
3266
3267   /* align adapter data to sync boundary, we keep the data up to the next sync
3268    * point. */
3269   save = TRUE;
3270   while (gst_ps_demux_resync (demux, save)) {
3271     gboolean ps_sync = TRUE;
3272     if (G_UNLIKELY (demux->flushing)) {
3273       ret = GST_FLOW_FLUSHING;
3274       goto done;
3275     }
3276
3277     /* now switch on last synced byte */
3278     switch (demux->last_sync_code) {
3279       case ID_PS_PACK_START_CODE:
3280         ret = gst_ps_demux_parse_pack_start (demux);
3281         break;
3282       case ID_PS_SYSTEM_HEADER_START_CODE:
3283         ret = gst_ps_demux_parse_sys_head (demux);
3284         break;
3285       case ID_PS_END_CODE:
3286         /* Skip final 4 bytes */
3287         gst_adapter_flush (demux->adapter, 4);
3288         ADAPTER_OFFSET_FLUSH (4);
3289         ret = GST_FLOW_OK;
3290         goto done;
3291       case ID_PS_PROGRAM_STREAM_MAP:
3292         ret = gst_ps_demux_parse_psm (demux);
3293         break;
3294       default:
3295         if (gst_ps_demux_is_pes_sync (demux->last_sync_code)) {
3296           ret = gst_pes_filter_process (&demux->filter);
3297         } else {
3298           GST_DEBUG_OBJECT (demux, "sync_code=%08x, non PES sync found"
3299               ", continuing", demux->last_sync_code);
3300           ps_sync = FALSE;
3301           ret = GST_FLOW_LOST_SYNC;
3302         }
3303         break;
3304     }
3305     /* if we found a ps sync, we stop saving the data, any non-ps sync gets
3306      * saved up to the next ps sync. */
3307     if (ps_sync)
3308       save = FALSE;
3309     switch (ret) {
3310       case GST_FLOW_NEED_MORE_DATA:
3311         GST_DEBUG_OBJECT (demux, "need more data");
3312         ret = GST_FLOW_OK;
3313         goto done;
3314       case GST_FLOW_LOST_SYNC:
3315         if (!save || demux->sink_segment.rate >= 0.0) {
3316           GST_DEBUG_OBJECT (demux, "flushing 3 bytes");
3317           gst_adapter_flush (demux->adapter, 3);
3318           ADAPTER_OFFSET_FLUSH (3);
3319         } else {
3320           GST_DEBUG_OBJECT (demux, "saving 3 bytes");
3321           gst_adapter_push (demux->rev_adapter,
3322               gst_adapter_take_buffer (demux->adapter, 3));
3323         }
3324         ret = GST_FLOW_OK;
3325         break;
3326       default:
3327         ret = gst_ps_demux_combine_flows (demux, ret);
3328         if (ret != GST_FLOW_OK)
3329           goto done;
3330         break;
3331     }
3332   }
3333 done:
3334   return ret;
3335 }
3336
3337 static GstStateChangeReturn
3338 gst_ps_demux_change_state (GstElement * element, GstStateChange transition)
3339 {
3340   GstPsDemux *demux = GST_PS_DEMUX (element);
3341   GstStateChangeReturn result;
3342   switch (transition) {
3343     case GST_STATE_CHANGE_NULL_TO_READY:
3344       gst_pes_filter_init (&demux->filter, demux->adapter,
3345           &demux->adapter_offset);
3346       gst_pes_filter_set_callbacks (&demux->filter,
3347           (GstPESFilterData) gst_ps_demux_data_cb,
3348           (GstPESFilterResync) gst_ps_demux_resync_cb, demux);
3349       demux->filter.gather_pes = TRUE;
3350       break;
3351     case GST_STATE_CHANGE_READY_TO_PAUSED:
3352       break;
3353     default:
3354       break;
3355   }
3356
3357   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3358   switch (transition) {
3359     case GST_STATE_CHANGE_PAUSED_TO_READY:
3360       gst_ps_demux_reset (demux);
3361       break;
3362     case GST_STATE_CHANGE_READY_TO_NULL:
3363       gst_pes_filter_uninit (&demux->filter);
3364       break;
3365     default:
3366       break;
3367   }
3368
3369   return result;
3370 }
3371
3372 static void
3373 gst_segment_set_position (GstSegment * segment, GstFormat format,
3374     guint64 position)
3375 {
3376   if (segment->format == GST_FORMAT_UNDEFINED) {
3377     segment->format = format;
3378   }
3379   segment->position = position;
3380 }
3381
3382 static void
3383 gst_segment_set_duration (GstSegment * segment, GstFormat format,
3384     guint64 duration)
3385 {
3386   if (segment->format == GST_FORMAT_UNDEFINED) {
3387     segment->format = format;
3388   }
3389   segment->duration = duration;
3390 }