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