documentation: fixed a heap o' typos
[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     gint layer)
353 {
354   GstPsStream *stream;
355   GstPadTemplate *template;
356   gchar *name;
357   GstPsDemuxClass *klass = GST_PS_DEMUX_GET_CLASS (demux);
358   GstCaps *caps;
359   GstClockTime threshold = SEGMENT_THRESHOLD;
360   GstEvent *event;
361   gchar *stream_id;
362
363   name = NULL;
364   template = NULL;
365   caps = NULL;
366
367   GST_DEBUG_OBJECT (demux, "create stream id 0x%02x, type 0x%02x", id,
368       stream_type);
369
370   switch (stream_type) {
371     case ST_VIDEO_MPEG1:
372     case ST_VIDEO_MPEG2:
373     case ST_VIDEO_MPEG4:
374     case ST_GST_VIDEO_MPEG1_OR_2:
375     {
376       gint mpeg_version = 1;
377       if (stream_type == ST_VIDEO_MPEG2 ||
378           (stream_type == ST_GST_VIDEO_MPEG1_OR_2 && demux->is_mpeg2_pack)) {
379         mpeg_version = 2;
380       }
381       if (stream_type == ST_VIDEO_MPEG4) {
382         mpeg_version = 4;
383       }
384
385       template = klass->video_template;
386       name = g_strdup_printf ("video_%02x", id);
387       caps = gst_caps_new_simple ("video/mpeg",
388           "mpegversion", G_TYPE_INT, mpeg_version,
389           "systemstream", G_TYPE_BOOLEAN, FALSE,
390           "parsed", G_TYPE_BOOLEAN, FALSE, NULL);
391       threshold = VIDEO_SEGMENT_THRESHOLD;
392       break;
393     }
394     case ST_AUDIO_MPEG1:
395     case ST_AUDIO_MPEG2:
396       template = klass->audio_template;
397       name = g_strdup_printf ("audio_%02x", id);
398       if (layer) {
399         caps = gst_caps_new_simple ("audio/mpeg",
400             "mpegversion", G_TYPE_INT, 1, "layer", G_TYPE_INT, layer, NULL);
401       } else {
402         caps = gst_caps_new_simple ("audio/mpeg",
403             "mpegversion", G_TYPE_INT, 1, NULL);
404       }
405       break;
406     case ST_PRIVATE_SECTIONS:
407     case ST_PRIVATE_DATA:
408     case ST_MHEG:
409     case ST_DSMCC:
410       break;
411     case ST_AUDIO_AAC_ADTS:
412       template = klass->audio_template;
413       name = g_strdup_printf ("audio_%02x", id);
414       caps = gst_caps_new_simple ("audio/mpeg",
415           "mpegversion", G_TYPE_INT, 4,
416           "stream-format", G_TYPE_STRING, "adts", NULL);
417       break;
418     case ST_AUDIO_AAC_LOAS:    // LATM/LOAS AAC syntax
419       template = klass->audio_template;
420       name = g_strdup_printf ("audio_%02x", id);
421       caps = gst_caps_new_simple ("audio/mpeg",
422           "mpegversion", G_TYPE_INT, 4,
423           "stream-format", G_TYPE_STRING, "loas", NULL);
424       break;
425     case ST_VIDEO_H264:
426       template = klass->video_template;
427       name = g_strdup_printf ("video_%02x", id);
428       caps = gst_caps_new_simple ("video/x-h264",
429           "stream-format", G_TYPE_STRING, "byte-stream", NULL);
430       threshold = VIDEO_SEGMENT_THRESHOLD;
431       break;
432     case ST_VIDEO_H265:
433       template = klass->video_template;
434       name = g_strdup_printf ("video_%02x", id);
435       caps = gst_caps_new_simple ("video/x-h265",
436           "stream-format", G_TYPE_STRING, "byte-stream", NULL);
437       threshold = VIDEO_SEGMENT_THRESHOLD;
438       break;
439
440     case ST_PS_AUDIO_AC3:
441       template = klass->audio_template;
442       name = g_strdup_printf ("audio_%02x", id);
443       caps = gst_caps_new_empty_simple ("audio/x-private1-ac3");
444       break;
445     case ST_PS_AUDIO_DTS:
446       template = klass->audio_template;
447       name = g_strdup_printf ("audio_%02x", id);
448       caps = gst_caps_new_empty_simple ("audio/x-private1-dts");
449       break;
450     case ST_PS_AUDIO_LPCM:
451       template = klass->audio_template;
452       name = g_strdup_printf ("audio_%02x", id);
453       caps = gst_caps_new_empty_simple ("audio/x-private1-lpcm");
454       break;
455     case ST_PS_DVD_SUBPICTURE:
456       template = klass->subpicture_template;
457       name = g_strdup_printf ("subpicture_%02x", id);
458       caps = gst_caps_new_empty_simple ("subpicture/x-dvd");
459       break;
460     case ST_GST_AUDIO_RAWA52:
461       template = klass->audio_template;
462       name = g_strdup_printf ("audio_%02x", id);
463       caps = gst_caps_new_empty_simple ("audio/ac3");
464       break;
465     default:
466       break;
467   }
468
469   if (name == NULL || template == NULL || caps == NULL) {
470     g_free (name);
471     if (caps)
472       gst_caps_unref (caps);
473     return FALSE;
474   }
475
476   stream = g_new0 (GstPsStream, 1);
477   stream->id = id;
478   stream->discont = TRUE;
479   stream->need_segment = TRUE;
480   stream->notlinked = FALSE;
481   stream->type = stream_type;
482   stream->pending_tags = NULL;
483   stream->pad = gst_pad_new_from_template (template, name);
484   stream->segment_thresh = threshold;
485   gst_pad_set_event_function (stream->pad,
486       GST_DEBUG_FUNCPTR (gst_ps_demux_src_event));
487   gst_pad_set_query_function (stream->pad,
488       GST_DEBUG_FUNCPTR (gst_ps_demux_src_query));
489   gst_pad_use_fixed_caps (stream->pad);
490
491   /* needed for set_caps to work */
492   if (!gst_pad_set_active (stream->pad, TRUE)) {
493     GST_WARNING_OBJECT (demux, "Failed to activate pad %" GST_PTR_FORMAT,
494         stream->pad);
495   }
496
497   stream_id =
498       gst_pad_create_stream_id_printf (stream->pad, GST_ELEMENT_CAST (demux),
499       "%02x", id);
500
501   event = gst_pad_get_sticky_event (demux->sinkpad, GST_EVENT_STREAM_START, 0);
502   if (event) {
503     if (gst_event_parse_group_id (event, &demux->group_id))
504       demux->have_group_id = TRUE;
505     else
506       demux->have_group_id = FALSE;
507     gst_event_unref (event);
508   } else if (!demux->have_group_id) {
509     demux->have_group_id = TRUE;
510     demux->group_id = gst_util_group_id_next ();
511   }
512   event = gst_event_new_stream_start (stream_id);
513   if (demux->have_group_id)
514     gst_event_set_group_id (event, demux->group_id);
515
516   gst_pad_push_event (stream->pad, event);
517   g_free (stream_id);
518
519   gst_pad_set_caps (stream->pad, caps);
520
521   if (!stream->pending_tags)
522     stream->pending_tags = gst_tag_list_new_empty ();
523   gst_pb_utils_add_codec_description_to_tag_list (stream->pending_tags, NULL,
524       caps);
525
526   GST_DEBUG_OBJECT (demux, "create pad %s, caps %" GST_PTR_FORMAT, name, caps);
527   gst_caps_unref (caps);
528   g_free (name);
529
530   return stream;
531 }
532
533 static GstPsStream *
534 gst_ps_demux_get_stream (GstPsDemux * demux, gint id, gint type, gint layer)
535 {
536   GstPsStream *stream = demux->streams[id];
537
538   if (stream == NULL) {
539     if (!(stream = gst_ps_demux_create_stream (demux, id, type, layer)))
540       goto unknown_stream;
541
542     GST_DEBUG_OBJECT (demux, "adding pad for stream id 0x%02x type 0x%02x", id,
543         type);
544
545     demux->streams[id] = stream;
546     demux->streams_found[demux->found_count++] = stream;
547
548     if (demux->need_no_more_pads) {
549       gst_element_add_pad (GST_ELEMENT (demux), stream->pad);
550       gst_flow_combiner_add_pad (demux->flowcombiner, stream->pad);
551     } else {
552       /* only likely to confuse decodebin etc, so discard */
553       /* FIXME should perform full switch protocol:
554        * add a whole new set of pads, drop old and no-more-pads again */
555       GST_DEBUG_OBJECT (demux,
556           "but already signalled no-more-pads; not adding");
557       gst_object_ref_sink (stream->pad);
558     }
559   }
560   return stream;
561
562   /* ERROR */
563 unknown_stream:
564   {
565     GST_DEBUG_OBJECT (demux, "unknown stream id 0x%02x type 0x%02x", id, type);
566     return NULL;
567   }
568 }
569
570 static GstPsStream *
571 gst_ps_demux_get_stream_from_pad (GstPsDemux * demux, GstPad * srcpad)
572 {
573   gint i, count;
574
575   count = demux->found_count;
576   for (i = 0; i < count; i++) {
577     GstPsStream *stream = demux->streams_found[i];
578
579     if (stream && stream->pad == srcpad)
580       return stream;
581   }
582
583   GST_DEBUG_OBJECT (srcpad, "no stream found for pad!");
584   return NULL;
585 }
586
587 static inline void
588 gst_ps_demux_send_segment (GstPsDemux * demux, GstPsStream * stream,
589     GstClockTime pts)
590 {
591   /* discont */
592   if (G_UNLIKELY (stream->need_segment)) {
593     GstSegment segment;
594
595     GST_DEBUG ("PTS timestamp:%" GST_TIME_FORMAT " base_time %" GST_TIME_FORMAT
596         " src_segment.start:%" GST_TIME_FORMAT " .stop:%" GST_TIME_FORMAT,
597         GST_TIME_ARGS (pts), GST_TIME_ARGS (demux->base_time),
598         GST_TIME_ARGS (demux->src_segment.start),
599         GST_TIME_ARGS (demux->src_segment.stop));
600
601     /* adjust segment start if estimating a seek was off quite a bit,
602      * make sure to do for all streams though to preserve a/v sync */
603     /* FIXME such adjustment tends to be frowned upon */
604     if (pts != GST_CLOCK_TIME_NONE && demux->adjust_segment) {
605       if (demux->src_segment.rate > 0) {
606         if (GST_CLOCK_DIFF (demux->src_segment.start, pts) > GST_SECOND)
607           demux->src_segment.start = pts - demux->base_time;
608       } else {
609         if (GST_CLOCK_DIFF (demux->src_segment.stop, pts) > GST_SECOND)
610           demux->src_segment.stop = pts - demux->base_time;
611       }
612     }
613     demux->adjust_segment = FALSE;
614
615     /* we should be in sync with downstream, so start from our segment notion,
616      * which also includes proper base_time etc, tweak it a bit and send */
617     gst_segment_copy_into (&demux->src_segment, &segment);
618     if (GST_CLOCK_TIME_IS_VALID (demux->base_time)) {
619       if (GST_CLOCK_TIME_IS_VALID (segment.start))
620         segment.start += demux->base_time;
621       if (GST_CLOCK_TIME_IS_VALID (segment.stop))
622         segment.stop += demux->base_time;
623       segment.time = segment.start - demux->base_time;
624     }
625
626     GST_INFO_OBJECT (demux, "sending segment event %" GST_SEGMENT_FORMAT
627         " to pad %" GST_PTR_FORMAT, &segment, stream->pad);
628
629     gst_pad_push_event (stream->pad, gst_event_new_segment (&segment));
630
631     stream->need_segment = FALSE;
632   }
633
634   if (G_UNLIKELY (stream->pending_tags)) {
635     GST_DEBUG_OBJECT (demux, "Sending pending_tags %p for pad %s:%s : %"
636         GST_PTR_FORMAT, stream->pending_tags,
637         GST_DEBUG_PAD_NAME (stream->pad), stream->pending_tags);
638     gst_pad_push_event (stream->pad, gst_event_new_tag (stream->pending_tags));
639     stream->pending_tags = NULL;
640   }
641 }
642
643 static GstFlowReturn
644 gst_ps_demux_send_data (GstPsDemux * demux, GstPsStream * stream,
645     GstBuffer * buf)
646 {
647   GstFlowReturn result;
648   GstClockTime pts = GST_CLOCK_TIME_NONE, dts = GST_CLOCK_TIME_NONE;
649
650   if (stream == NULL)
651     goto no_stream;
652
653   /* timestamps */
654   if (G_UNLIKELY (demux->next_pts != G_MAXUINT64))
655     pts = MPEGTIME_TO_GSTTIME (demux->next_pts);
656   if (G_UNLIKELY (demux->next_dts != G_MAXUINT64))
657     dts = MPEGTIME_TO_GSTTIME (demux->next_dts);
658
659   gst_ps_demux_send_segment (demux, stream, pts);
660
661   /* OK, sent new segment now prepare the buffer for sending */
662   GST_BUFFER_PTS (buf) = pts;
663   GST_BUFFER_DTS (buf) = dts;
664
665   /* update position in the segment */
666   gst_segment_set_position (&demux->src_segment, GST_FORMAT_TIME,
667       MPEGTIME_TO_GSTTIME (demux->current_scr - demux->first_scr));
668
669   GST_LOG_OBJECT (demux, "last stop position is now %" GST_TIME_FORMAT
670       " current scr is %" GST_TIME_FORMAT,
671       GST_TIME_ARGS (demux->src_segment.position),
672       GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (demux->current_scr)));
673
674   if (demux->src_segment.position != GST_CLOCK_TIME_NONE &&
675       demux->base_time != GST_CLOCK_TIME_NONE) {
676     GstClockTime new_time = demux->base_time + demux->src_segment.position;
677
678     if (stream->last_ts == GST_CLOCK_TIME_NONE || stream->last_ts < new_time) {
679       GST_LOG_OBJECT (demux,
680           "last_ts update on pad %s to time %" GST_TIME_FORMAT,
681           GST_PAD_NAME (stream->pad), GST_TIME_ARGS (new_time));
682       stream->last_ts = new_time;
683     }
684
685     gst_ps_demux_send_gap_updates (demux, new_time);
686   }
687
688   /* Set the buffer discont flag, and clear discont state on the stream */
689   if (stream->discont) {
690     GST_DEBUG_OBJECT (demux, "discont buffer to pad %" GST_PTR_FORMAT
691         " with PTS %" GST_TIME_FORMAT " DTS %" GST_TIME_FORMAT,
692         stream->pad, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts));
693     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
694
695     stream->discont = FALSE;
696   } else {
697     GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DISCONT);
698   }
699
700   demux->next_pts = G_MAXUINT64;
701   demux->next_dts = G_MAXUINT64;
702
703   GST_LOG_OBJECT (demux, "pushing stream id 0x%02x type 0x%02x, pts time: %"
704       GST_TIME_FORMAT ", size %" G_GSIZE_FORMAT,
705       stream->id, stream->type, GST_TIME_ARGS (pts), gst_buffer_get_size (buf));
706   result = gst_pad_push (stream->pad, buf);
707   GST_LOG_OBJECT (demux, "result: %s", gst_flow_get_name (result));
708
709   return result;
710
711   /* ERROR */
712 no_stream:
713   {
714     GST_DEBUG_OBJECT (demux, "no stream given");
715     gst_buffer_unref (buf);
716     return GST_FLOW_OK;
717   }
718 }
719
720 static inline void
721 gst_ps_demux_mark_discont (GstPsDemux * demux, gboolean discont,
722     gboolean need_segment)
723 {
724   gint i, count = demux->found_count;
725
726   /* mark discont on all streams */
727   for (i = 0; i < count; i++) {
728     GstPsStream *stream = demux->streams_found[i];
729
730     if (G_LIKELY (stream)) {
731       stream->discont |= discont;
732       stream->need_segment |= need_segment;
733       demux->adjust_segment |= need_segment;
734       GST_DEBUG_OBJECT (demux, "marked stream as discont %d, need_segment %d",
735           stream->discont, stream->need_segment);
736     }
737   }
738 }
739
740 static gboolean
741 gst_ps_demux_send_event (GstPsDemux * demux, GstEvent * event)
742 {
743   gint i, count = demux->found_count;
744   gboolean ret = FALSE;
745
746   for (i = 0; i < count; i++) {
747     GstPsStream *stream = demux->streams_found[i];
748
749     if (stream) {
750       if (!gst_pad_push_event (stream->pad, gst_event_ref (event))) {
751         GST_DEBUG_OBJECT (stream->pad, "%s event was not handled",
752             GST_EVENT_TYPE_NAME (event));
753       } else {
754         /* If at least one push returns TRUE, then we return TRUE. */
755         GST_DEBUG_OBJECT (stream->pad, "%s event was handled",
756             GST_EVENT_TYPE_NAME (event));
757         ret = TRUE;
758       }
759     }
760   }
761
762   gst_event_unref (event);
763   return ret;
764 }
765
766 static gboolean
767 gst_ps_demux_handle_dvd_event (GstPsDemux * demux, GstEvent * event)
768 {
769   const GstStructure *structure = gst_event_get_structure (event);
770   const char *type = gst_structure_get_string (structure, "event");
771   gint i;
772   gchar cur_stream_name[32];
773   GstPsStream *temp = NULL;
774   const gchar *lang_code;
775
776   if (strcmp (type, "dvd-lang-codes") == 0) {
777     GST_DEBUG_OBJECT (demux, "Handling language codes event");
778
779     /* Create a video pad to ensure have it before emit no more pads */
780     (void) gst_ps_demux_get_stream (demux, 0xe0, ST_VIDEO_MPEG2, 0);
781
782     /* Read out the languages for audio streams and request each one that 
783      * is present */
784     for (i = 0; i < MAX_DVD_AUDIO_STREAMS; i++) {
785       gint stream_format;
786       gint stream_id;
787
788       g_snprintf (cur_stream_name, 32, "audio-%d-format", i);
789       if (!gst_structure_get_int (structure, cur_stream_name, &stream_format))
790         continue;
791
792       g_snprintf (cur_stream_name, 32, "audio-%d-stream", i);
793       if (!gst_structure_get_int (structure, cur_stream_name, &stream_id))
794         continue;
795       if (stream_id < 0 || stream_id >= MAX_DVD_AUDIO_STREAMS)
796         continue;
797
798       switch (stream_format) {
799         case 0x0:
800           /* AC3 */
801           stream_id += 0x80;
802           GST_DEBUG_OBJECT (demux,
803               "Audio stream %d format %d ID 0x%02x - AC3", i,
804               stream_format, stream_id);
805           temp = gst_ps_demux_get_stream (demux, stream_id, ST_PS_AUDIO_AC3, 0);
806           break;
807         case 0x2:
808         case 0x3:
809           /* MPEG audio without and with extension stream are
810            * treated the same */
811           stream_id += 0xC0;
812           GST_DEBUG_OBJECT (demux,
813               "Audio stream %d format %d ID 0x%02x - MPEG audio", i,
814               stream_format, stream_id);
815           temp = gst_ps_demux_get_stream (demux, stream_id, ST_AUDIO_MPEG1, 0);
816           break;
817         case 0x4:
818           /* LPCM */
819           stream_id += 0xA0;
820           GST_DEBUG_OBJECT (demux,
821               "Audio stream %d format %d ID 0x%02x - DVD LPCM", i,
822               stream_format, stream_id);
823           temp =
824               gst_ps_demux_get_stream (demux, stream_id, ST_PS_AUDIO_LPCM, 0);
825           break;
826         case 0x6:
827           /* DTS */
828           stream_id += 0x88;
829           GST_DEBUG_OBJECT (demux,
830               "Audio stream %d format %d ID 0x%02x - DTS", i,
831               stream_format, stream_id);
832           temp = gst_ps_demux_get_stream (demux, stream_id, ST_PS_AUDIO_DTS, 0);
833           break;
834         case 0x7:
835           /* FIXME: What range is SDDS? */
836         default:
837           GST_WARNING_OBJECT (demux,
838               "Unknown audio stream format in language code event: %d",
839               stream_format);
840           temp = NULL;
841           continue;
842       }
843
844       if (temp == NULL)
845         continue;
846
847       g_snprintf (cur_stream_name, 32, "audio-%d-language", i);
848       lang_code = gst_structure_get_string (structure, cur_stream_name);
849       if (lang_code) {
850         GstTagList *list = temp->pending_tags;
851
852         if (!list)
853           list = gst_tag_list_new_empty ();
854         gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
855             GST_TAG_LANGUAGE_CODE, lang_code, NULL);
856         temp->pending_tags = list;
857       }
858     }
859
860     /* And subtitle streams */
861     for (i = 0; i < MAX_DVD_SUBPICTURE_STREAMS; i++) {
862       gint stream_id;
863
864       g_snprintf (cur_stream_name, 32, "subpicture-%d-format", i);
865       if (!gst_structure_get_int (structure, cur_stream_name, &stream_id))
866         continue;
867
868       g_snprintf (cur_stream_name, 32, "subpicture-%d-stream", i);
869       if (!gst_structure_get_int (structure, cur_stream_name, &stream_id))
870         continue;
871       if (stream_id < 0 || stream_id >= MAX_DVD_SUBPICTURE_STREAMS)
872         continue;
873
874       GST_DEBUG_OBJECT (demux, "Subpicture stream %d ID 0x%02x", i,
875           0x20 + stream_id);
876
877       /* Retrieve the subpicture stream to force pad creation */
878       temp = gst_ps_demux_get_stream (demux, 0x20 + stream_id,
879           ST_PS_DVD_SUBPICTURE, 0);
880       if (temp == NULL)
881         continue;
882
883       g_snprintf (cur_stream_name, 32, "subpicture-%d-language", i);
884       lang_code = gst_structure_get_string (structure, cur_stream_name);
885       if (lang_code) {
886         GstTagList *list = temp->pending_tags;
887
888         if (!list)
889           list = gst_tag_list_new_empty ();
890         gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
891             GST_TAG_LANGUAGE_CODE, lang_code, NULL);
892         temp->pending_tags = list;
893       }
894     }
895
896     GST_DEBUG_OBJECT (demux, "Created all pads from Language Codes event, "
897         "signalling no-more-pads");
898
899     gst_element_no_more_pads (GST_ELEMENT (demux));
900     demux->need_no_more_pads = FALSE;
901   } else {
902     /* forward to all pads, e.g. dvd clut event */
903     gst_event_ref (event);
904     gst_ps_demux_send_event (demux, event);
905   }
906
907   gst_event_unref (event);
908   return TRUE;
909 }
910
911 static void
912 gst_ps_demux_flush (GstPsDemux * demux)
913 {
914   GST_DEBUG_OBJECT (demux, "flushing demuxer");
915   gst_adapter_clear (demux->adapter);
916   gst_adapter_clear (demux->rev_adapter);
917   gst_pes_filter_drain (&demux->filter);
918   gst_ps_demux_clear_times (demux);
919   demux->adapter_offset = G_MAXUINT64;
920   demux->current_scr = G_MAXUINT64;
921   demux->bytes_since_scr = 0;
922 }
923
924 static inline void
925 gst_ps_demux_clear_times (GstPsDemux * demux)
926 {
927   gint i, count = demux->found_count;
928
929   gst_flow_combiner_reset (demux->flowcombiner);
930   /* Clear the last ts for all streams */
931   for (i = 0; i < count; i++) {
932     GstPsStream *stream = demux->streams_found[i];
933
934     if (G_LIKELY (stream)) {
935       stream->last_ts = GST_CLOCK_TIME_NONE;
936     }
937   }
938 }
939
940 static inline void
941 gst_ps_demux_send_gap_updates (GstPsDemux * demux, GstClockTime new_start)
942 {
943   GstClockTime base_time, stop;
944   gint i, count = demux->found_count;
945   GstEvent *event = NULL;
946
947   /* Advance all lagging streams by sending a gap event */
948   if ((base_time = demux->base_time) == GST_CLOCK_TIME_NONE)
949     base_time = 0;
950
951   stop = demux->src_segment.stop;
952   if (stop != GST_CLOCK_TIME_NONE)
953     stop += base_time;
954
955   if (new_start > stop)
956     return;
957
958   /* FIXME: Handle reverse playback */
959   for (i = 0; i < count; i++) {
960     GstPsStream *stream = demux->streams_found[i];
961
962     if (stream) {
963       if (stream->last_ts == GST_CLOCK_TIME_NONE ||
964           stream->last_ts < demux->src_segment.start + base_time)
965         stream->last_ts = demux->src_segment.start + base_time;
966
967       if (stream->last_ts + stream->segment_thresh < new_start) {
968         /* should send segment info before gap event */
969         gst_ps_demux_send_segment (demux, stream, GST_CLOCK_TIME_NONE);
970
971         GST_LOG_OBJECT (demux,
972             "Sending gap update to pad %s time %" GST_TIME_FORMAT,
973             GST_PAD_NAME (stream->pad), GST_TIME_ARGS (new_start));
974         event =
975             gst_event_new_gap (stream->last_ts, new_start - stream->last_ts);
976         gst_pad_push_event (stream->pad, event);
977         stream->last_ts = new_start;
978       }
979     }
980   }
981 }
982
983 static inline gboolean
984 have_open_streams (GstPsDemux * demux)
985 {
986   return (demux->streams_found[0] != NULL);
987 }
988
989 static gboolean
990 gst_ps_demux_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
991 {
992   gboolean res = TRUE;
993   GstPsDemux *demux = GST_PS_DEMUX (parent);
994
995   switch (GST_EVENT_TYPE (event)) {
996     case GST_EVENT_FLUSH_START:
997       gst_ps_demux_send_event (demux, event);
998       break;
999     case GST_EVENT_FLUSH_STOP:
1000       gst_ps_demux_send_event (demux, event);
1001       gst_segment_init (&demux->sink_segment, GST_FORMAT_UNDEFINED);
1002       gst_ps_demux_flush (demux);
1003       break;
1004     case GST_EVENT_SEGMENT:
1005     {
1006       const GstSegment *segment;
1007
1008       gst_event_parse_segment (event, &segment);
1009       gst_segment_copy_into (segment, &demux->sink_segment);
1010
1011       GST_INFO_OBJECT (demux, "received segment %" GST_SEGMENT_FORMAT, segment);
1012
1013       /* we need to emit a new segment */
1014       gst_ps_demux_mark_discont (demux, TRUE, TRUE);
1015
1016       if (segment->format == GST_FORMAT_BYTES
1017           && demux->scr_rate_n != G_MAXUINT64
1018           && demux->scr_rate_d != G_MAXUINT64) {
1019         demux->src_segment.rate = segment->rate;
1020         demux->src_segment.applied_rate = segment->applied_rate;
1021         demux->src_segment.format = GST_FORMAT_TIME;
1022         demux->src_segment.start = BYTES_TO_GSTTIME (segment->start);
1023         demux->src_segment.stop = BYTES_TO_GSTTIME (segment->stop);
1024         demux->src_segment.time = BYTES_TO_GSTTIME (segment->time);
1025       } else if (segment->format == GST_FORMAT_TIME) {
1026         /* we expect our timeline (SCR, PTS) to match the one from upstream,
1027          * if not, will adjust with offset later on */
1028         gst_segment_copy_into (segment, &demux->src_segment);
1029         /* accept upstream segment without adjusting */
1030         demux->adjust_segment = FALSE;
1031       }
1032
1033       gst_event_unref (event);
1034
1035       break;
1036     }
1037     case GST_EVENT_EOS:
1038       GST_INFO_OBJECT (demux, "Received EOS");
1039       if (!gst_ps_demux_send_event (demux, event)
1040           && !have_open_streams (demux)) {
1041         GST_WARNING_OBJECT (demux, "EOS and no streams open");
1042         GST_ELEMENT_ERROR (demux, STREAM, FAILED,
1043             ("Internal data stream error."), ("No valid streams detected"));
1044       }
1045       break;
1046     case GST_EVENT_CUSTOM_DOWNSTREAM:
1047     case GST_EVENT_CUSTOM_DOWNSTREAM_OOB:
1048     {
1049       const GstStructure *structure = gst_event_get_structure (event);
1050
1051       if (structure != NULL
1052           && gst_structure_has_name (structure, "application/x-gst-dvd")) {
1053         res = gst_ps_demux_handle_dvd_event (demux, event);
1054       } else {
1055         gst_ps_demux_send_event (demux, event);
1056       }
1057       break;
1058     }
1059     case GST_EVENT_CAPS:
1060       gst_event_unref (event);
1061       break;
1062     default:
1063       gst_ps_demux_send_event (demux, event);
1064       break;
1065   }
1066
1067   return res;
1068 }
1069
1070 static gboolean
1071 gst_ps_demux_handle_seek_push (GstPsDemux * demux, GstEvent * event)
1072 {
1073   gboolean res = FALSE;
1074   gdouble rate;
1075   GstFormat format;
1076   GstSeekFlags flags;
1077   GstSeekType start_type, stop_type;
1078   gint64 start, stop;
1079   gint64 bstart, bstop;
1080   GstEvent *bevent;
1081
1082   gst_event_parse_seek (event, &rate, &format, &flags, &start_type, &start,
1083       &stop_type, &stop);
1084
1085   GST_DEBUG_OBJECT (demux, "seek event, rate: %f start: %" GST_TIME_FORMAT
1086       " stop: %" GST_TIME_FORMAT, rate, GST_TIME_ARGS (start),
1087       GST_TIME_ARGS (stop));
1088
1089   if (format == GST_FORMAT_BYTES) {
1090     GST_DEBUG_OBJECT (demux, "seek not supported on format %d", format);
1091     goto not_supported;
1092   }
1093
1094   GST_DEBUG_OBJECT (demux, "seek - trying directly upstream first");
1095
1096   /* first try original format seek */
1097   (void) gst_event_ref (event);
1098   if ((res = gst_pad_push_event (demux->sinkpad, event)))
1099     goto done;
1100
1101   if (format != GST_FORMAT_TIME) {
1102     /* From here down, we only support time based seeks */
1103     GST_DEBUG_OBJECT (demux, "seek not supported on format %d", format);
1104     goto not_supported;
1105   }
1106
1107   /* We need to convert to byte based seek and we need a scr_rate for that. */
1108   if (demux->scr_rate_n == G_MAXUINT64 || demux->scr_rate_d == G_MAXUINT64) {
1109     GST_DEBUG_OBJECT (demux, "seek not possible, no scr_rate");
1110     goto not_supported;
1111   }
1112
1113   GST_DEBUG_OBJECT (demux, "try with scr_rate interpolation");
1114
1115   bstart = GSTTIME_TO_BYTES ((guint64) start);
1116   bstop = GSTTIME_TO_BYTES ((guint64) stop);
1117
1118   GST_DEBUG_OBJECT (demux, "in bytes bstart %" G_GINT64_FORMAT " bstop %"
1119       G_GINT64_FORMAT, bstart, bstop);
1120   bevent = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags, start_type,
1121       bstart, stop_type, bstop);
1122
1123   res = gst_pad_push_event (demux->sinkpad, bevent);
1124
1125 done:
1126   gst_event_unref (event);
1127   return res;
1128
1129 not_supported:
1130   {
1131     gst_event_unref (event);
1132
1133     return FALSE;
1134   }
1135 }
1136
1137 #define MAX_RECURSION_COUNT 100
1138
1139 /* Binary search for requested SCR */
1140 static inline guint64
1141 find_offset (GstPsDemux * demux, guint64 scr,
1142     guint64 min_scr, guint64 min_scr_offset,
1143     guint64 max_scr, guint64 max_scr_offset, int recursion_count)
1144 {
1145   guint64 scr_rate_n = max_scr_offset - min_scr_offset;
1146   guint64 scr_rate_d = max_scr - min_scr;
1147   guint64 fscr = scr;
1148   guint64 offset;
1149
1150   if (recursion_count > MAX_RECURSION_COUNT) {
1151     return -1;
1152   }
1153
1154   offset = min_scr_offset +
1155       MIN (gst_util_uint64_scale (scr - min_scr, scr_rate_n,
1156           scr_rate_d), demux->sink_segment.stop);
1157
1158   if (!gst_ps_demux_scan_forward_ts (demux, &offset, SCAN_SCR, &fscr, 0)) {
1159     gst_ps_demux_scan_backward_ts (demux, &offset, SCAN_SCR, &fscr, 0);
1160   }
1161
1162   if (fscr == scr || fscr == min_scr || fscr == max_scr) {
1163     return offset;
1164   }
1165
1166   if (fscr < scr) {
1167     return find_offset (demux, scr, fscr, offset, max_scr, max_scr_offset,
1168         recursion_count + 1);
1169   } else {
1170     return find_offset (demux, scr, min_scr, min_scr_offset, fscr, offset,
1171         recursion_count + 1);
1172   }
1173 }
1174
1175 static inline gboolean
1176 gst_ps_demux_do_seek (GstPsDemux * demux, GstSegment * seeksegment)
1177 {
1178   gboolean found;
1179   guint64 fscr, offset;
1180   guint64 scr = GSTTIME_TO_MPEGTIME (seeksegment->position + demux->base_time);
1181
1182   /* In some clips the PTS values are completely unaligned with SCR values.
1183    * To improve the seek in that situation we apply a factor considering the
1184    * relationship between last PTS and last SCR */
1185   if (demux->last_scr > demux->last_pts)
1186     scr = gst_util_uint64_scale (scr, demux->last_scr, demux->last_pts);
1187
1188   scr = MIN (demux->last_scr, scr);
1189   scr = MAX (demux->first_scr, scr);
1190   fscr = scr;
1191
1192   GST_INFO_OBJECT (demux, "sink segment configured %" GST_SEGMENT_FORMAT
1193       ", trying to go at SCR: %" G_GUINT64_FORMAT, &demux->sink_segment, scr);
1194
1195   offset =
1196       find_offset (demux, scr, demux->first_scr, demux->first_scr_offset,
1197       demux->last_scr, demux->last_scr_offset, 0);
1198
1199   if (offset == (guint64) - 1) {
1200     return FALSE;
1201   }
1202
1203   found = gst_ps_demux_scan_forward_ts (demux, &offset, SCAN_SCR, &fscr, 0);
1204   if (!found)
1205     found = gst_ps_demux_scan_backward_ts (demux, &offset, SCAN_SCR, &fscr, 0);
1206
1207   while (found && fscr < scr) {
1208     offset++;
1209     found = gst_ps_demux_scan_forward_ts (demux, &offset, SCAN_SCR, &fscr, 0);
1210   }
1211
1212   while (found && fscr > scr && offset > 0) {
1213     offset--;
1214     found = gst_ps_demux_scan_backward_ts (demux, &offset, SCAN_SCR, &fscr, 0);
1215   }
1216
1217   GST_INFO_OBJECT (demux, "doing seek at offset %" G_GUINT64_FORMAT
1218       " SCR: %" G_GUINT64_FORMAT " %" GST_TIME_FORMAT,
1219       offset, fscr, GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (fscr)));
1220
1221   gst_segment_set_position (&demux->sink_segment, GST_FORMAT_BYTES, offset);
1222
1223   return TRUE;
1224 }
1225
1226 static gboolean
1227 gst_ps_demux_handle_seek_pull (GstPsDemux * demux, GstEvent * event)
1228 {
1229   GstFormat format;
1230   GstSeekFlags flags;
1231   GstSeekType start_type, stop_type;
1232   gint64 start, stop;
1233   gdouble rate;
1234   gboolean update, flush;
1235   GstSegment seeksegment;
1236   GstClockTime first_pts = MPEGTIME_TO_GSTTIME (demux->first_pts);
1237
1238   gst_event_parse_seek (event, &rate, &format, &flags,
1239       &start_type, &start, &stop_type, &stop);
1240
1241   if (format != GST_FORMAT_TIME)
1242     goto wrong_format;
1243
1244   GST_DEBUG_OBJECT (demux, "Seek requested start %" GST_TIME_FORMAT " stop %"
1245       GST_TIME_FORMAT, GST_TIME_ARGS (start), GST_TIME_ARGS (stop));
1246
1247   /* We need to convert to byte based seek and we need a scr_rate for that. */
1248   if (demux->scr_rate_n == G_MAXUINT64 || demux->scr_rate_d == G_MAXUINT64)
1249     goto no_scr_rate;
1250
1251   flush = flags & GST_SEEK_FLAG_FLUSH;
1252   /* keyframe = flags & GST_SEEK_FLAG_KEY_UNIT; *//* FIXME */
1253
1254   if (flush) {
1255     /* Flush start up and downstream to make sure data flow and loops are
1256        idle */
1257     demux->flushing = TRUE;
1258     gst_ps_demux_send_event (demux, gst_event_new_flush_start ());
1259     gst_pad_push_event (demux->sinkpad, gst_event_new_flush_start ());
1260   } else {
1261     /* Pause the pulling task */
1262     gst_pad_pause_task (demux->sinkpad);
1263   }
1264
1265   /* Take the stream lock */
1266   GST_PAD_STREAM_LOCK (demux->sinkpad);
1267
1268   if (flush) {
1269     /* Stop flushing upstream we need to pull */
1270     demux->flushing = FALSE;
1271     gst_pad_push_event (demux->sinkpad, gst_event_new_flush_stop (TRUE));
1272   }
1273
1274   /* Work on a copy until we are sure the seek succeeded. */
1275   memcpy (&seeksegment, &demux->src_segment, sizeof (GstSegment));
1276
1277   GST_DEBUG_OBJECT (demux, "segment before configure %" GST_SEGMENT_FORMAT,
1278       &demux->src_segment);
1279
1280   /* Apply the seek to our segment */
1281   if (!gst_segment_do_seek (&seeksegment, rate, format, flags,
1282           start_type, start, stop_type, stop, &update))
1283     goto seek_error;
1284
1285   GST_DEBUG_OBJECT (demux, "seek segment configured %" GST_SEGMENT_FORMAT,
1286       &seeksegment);
1287
1288   if (flush || seeksegment.position != demux->src_segment.position) {
1289     /* Do the actual seeking */
1290     if (!gst_ps_demux_do_seek (demux, &seeksegment)) {
1291       return FALSE;
1292     }
1293   }
1294
1295   /* check the limits */
1296   if (seeksegment.rate > 0.0 && first_pts != G_MAXUINT64) {
1297     if (seeksegment.start < first_pts - demux->base_time) {
1298       seeksegment.start = first_pts - demux->base_time;
1299       seeksegment.position = seeksegment.start;
1300     }
1301   }
1302
1303   /* update the rate in our src segment */
1304   demux->sink_segment.rate = rate;
1305
1306   GST_DEBUG_OBJECT (demux, "seek segment adjusted %" GST_SEGMENT_FORMAT,
1307       &seeksegment);
1308
1309   if (flush) {
1310     /* Stop flushing, the sinks are at time 0 now */
1311     gst_ps_demux_send_event (demux, gst_event_new_flush_stop (TRUE));
1312   }
1313
1314   if (flush || seeksegment.position != demux->src_segment.position) {
1315     gst_ps_demux_flush (demux);
1316   }
1317
1318   /* Ok seek succeeded, take the newly configured segment */
1319   memcpy (&demux->src_segment, &seeksegment, sizeof (GstSegment));
1320
1321   /* Notify about the start of a new segment */
1322   if (demux->src_segment.flags & GST_SEEK_FLAG_SEGMENT) {
1323     gst_element_post_message (GST_ELEMENT (demux),
1324         gst_message_new_segment_start (GST_OBJECT (demux),
1325             demux->src_segment.format, demux->src_segment.position));
1326   }
1327
1328   /* Tell all the stream a new segment is needed */
1329   gst_ps_demux_mark_discont (demux, TRUE, TRUE);
1330
1331   gst_pad_start_task (demux->sinkpad,
1332       (GstTaskFunction) gst_ps_demux_loop, demux->sinkpad, NULL);
1333
1334   GST_PAD_STREAM_UNLOCK (demux->sinkpad);
1335
1336   gst_event_unref (event);
1337   return TRUE;
1338
1339   /* ERRORS */
1340 wrong_format:
1341   {
1342     GST_WARNING_OBJECT (demux, "we only support seeking in TIME or BYTES "
1343         "formats");
1344     gst_event_unref (event);
1345     return FALSE;
1346   }
1347 no_scr_rate:
1348   {
1349     GST_WARNING_OBJECT (demux, "seek not possible, no scr_rate");
1350     gst_event_unref (event);
1351     return FALSE;
1352   }
1353 seek_error:
1354   {
1355     GST_WARNING_OBJECT (demux, "couldn't perform seek");
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     gint layer = 0;
2233     /* find the stream type */
2234     stream_type = demux->psm[id];
2235     if (stream_type == -1) {
2236       /* no stream type, if PS1, get the new id */
2237       if (start_code == ID_PRIVATE_STREAM_1 && datalen >= 2) {
2238         /* VDR writes A52 streams without any header bytes
2239          * (see ftp://ftp.mplayerhq.hu/MPlayer/samples/MPEG-VOB/vdr-AC3) */
2240         if (datalen >= 4) {
2241           guint hdr = GST_READ_UINT32_BE (map.data);
2242           if (G_UNLIKELY ((hdr & 0xffff0000) == AC3_SYNC_WORD)) {
2243             id = 0x80;
2244             stream_type = demux->psm[id] = ST_GST_AUDIO_RAWA52;
2245             GST_DEBUG_OBJECT (demux, "Found VDR raw A52 stream");
2246           }
2247         }
2248
2249         if (G_LIKELY (stream_type == -1)) {
2250           /* new id is in the first byte */
2251           id = map.data[offset++];
2252           datalen--;
2253           /* and remap */
2254           stream_type = demux->psm[id];
2255           /* Now, if it's a subpicture stream - no more, otherwise
2256            * take the first byte too, since it's the frame count in audio
2257            * streams and our backwards compat convention is to strip it off */
2258           if (stream_type != ST_PS_DVD_SUBPICTURE) {
2259             /* Number of audio frames in this packet */
2260 #ifndef GST_DISABLE_GST_DEBUG
2261             guint8 nframes;
2262             nframes = map.data[offset];
2263             GST_LOG_OBJECT (demux, "private type 0x%02x, %d frames", id,
2264                 nframes);
2265 #endif
2266             offset++;
2267             datalen--;
2268           } else {
2269             GST_LOG_OBJECT (demux, "private type 0x%02x, stream type %d",
2270                 id, stream_type);
2271           }
2272         }
2273       }
2274       if (stream_type == -1)
2275         goto unknown_stream_type;
2276     } else if (stream_type == ST_AUDIO_MPEG1 || stream_type == ST_AUDIO_MPEG2) {
2277       if (datalen >= 2) {
2278         guint hdr = GST_READ_UINT16_BE (map.data);
2279         if ((hdr & 0xfff0) == 0xfff0) {
2280           switch (hdr & 0x06) {
2281             case 0x6:
2282               layer = 1;
2283               break;
2284             case 0x4:
2285               layer = 2;
2286               break;
2287             case 0x2:
2288               layer = 3;
2289               break;
2290             default:
2291               GST_WARNING_OBJECT (demux, "unknown mpeg audio layer");
2292           }
2293         }
2294       }
2295     }
2296
2297     if (filter->pts != -1) {
2298       demux->next_pts = filter->pts + demux->scr_adjust;
2299       GST_LOG_OBJECT (demux, "stream 0x%02x PTS = orig %" G_GUINT64_FORMAT
2300           " (%" G_GUINT64_FORMAT ")", id, filter->pts, demux->next_pts);
2301     } else
2302       demux->next_pts = G_MAXUINT64;
2303     if (filter->dts != -1) {
2304       demux->next_dts = filter->dts + demux->scr_adjust;
2305       GST_LOG_OBJECT (demux, "stream 0x%02x DTS = orig %" G_GUINT64_FORMAT
2306           " (%" G_GUINT64_FORMAT ")", id, filter->dts, demux->next_dts);
2307     } else {
2308       demux->next_dts = demux->next_pts;
2309     }
2310
2311     demux->current_stream =
2312         gst_ps_demux_get_stream (demux, id, stream_type, layer);
2313   }
2314
2315   if (G_UNLIKELY (demux->current_stream == NULL)) {
2316     GST_DEBUG_OBJECT (demux, "Dropping buffer for unknown stream id 0x%02x",
2317         id);
2318     goto done;
2319   }
2320
2321   /* After 2 seconds of bitstream emit no more pads */
2322   if (demux->need_no_more_pads
2323       && (demux->current_scr - demux->first_scr) > 2 * CLOCK_FREQ) {
2324     GST_DEBUG_OBJECT (demux, "no more pads, notifying");
2325     gst_element_no_more_pads (GST_ELEMENT_CAST (demux));
2326     demux->need_no_more_pads = FALSE;
2327   }
2328
2329   /* If the stream is not-linked, don't bother creating a sub-buffer
2330    * to send to it, unless we're processing a discont (which resets
2331    * the not-linked status and tries again */
2332   if (demux->current_stream->discont) {
2333     GST_DEBUG_OBJECT (demux, "stream is discont");
2334     demux->current_stream->notlinked = FALSE;
2335   }
2336
2337   if (demux->current_stream->notlinked == FALSE) {
2338     out_buf =
2339         gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, offset, datalen);
2340     ret = gst_ps_demux_send_data (demux, demux->current_stream, out_buf);
2341     if (ret == GST_FLOW_NOT_LINKED) {
2342       demux->current_stream->notlinked = TRUE;
2343     }
2344   }
2345
2346 done:
2347   gst_buffer_unmap (buffer, &map);
2348   gst_buffer_unref (buffer);
2349   return ret;
2350   /* ERRORS */
2351 unknown_stream_type:
2352   {
2353     GST_DEBUG_OBJECT (demux, "unknown stream type %02x", id);
2354     ret = GST_FLOW_OK;
2355     goto done;
2356   }
2357 }
2358
2359 static gboolean
2360 gst_ps_demux_resync (GstPsDemux * demux, gboolean save)
2361 {
2362   const guint8 *data;
2363   gint avail;
2364   guint32 code;
2365   gint offset;
2366   gboolean found;
2367   avail = gst_adapter_available (demux->adapter);
2368   if (G_UNLIKELY (avail < 4))
2369     goto need_data;
2370   /* Common case, read 4 bytes an check it */
2371   data = gst_adapter_map (demux->adapter, 4);
2372   /* read currect code */
2373   code = GST_READ_UINT32_BE (data);
2374   /* The common case is that the sync code is at 0 bytes offset */
2375   if (G_LIKELY ((code & 0xffffff00) == 0x100L)) {
2376     GST_LOG_OBJECT (demux, "Found resync code %08x after 0 bytes", code);
2377     demux->last_sync_code = code;
2378     gst_adapter_unmap (demux->adapter);
2379     return TRUE;
2380   }
2381
2382   /* Otherwise, we are starting at byte 4 and we need to search
2383      the sync code in all available data in the adapter */
2384   offset = 4;
2385   if (offset >= avail)
2386     goto need_data;             /* Not enough data to find sync */
2387   data = gst_adapter_map (demux->adapter, avail);
2388   do {
2389     code = (code << 8) | data[offset++];
2390     found = (code & 0xffffff00) == 0x100L;
2391   } while (offset < avail && !found);
2392   gst_adapter_unmap (demux->adapter);
2393   if (!save || demux->sink_segment.rate >= 0.0) {
2394     GST_LOG_OBJECT (demux, "flushing %d bytes", offset - 4);
2395     /* forward playback, we can discard and flush the skipped bytes */
2396     gst_adapter_flush (demux->adapter, offset - 4);
2397     ADAPTER_OFFSET_FLUSH (offset - 4);
2398   } else {
2399     if (found) {
2400       GST_LOG_OBJECT (demux, "reverse saving %d bytes", offset - 4);
2401       /* reverse playback, we keep the flushed bytes and we will append them to
2402        * the next buffer in the chain function, which is the previous buffer in
2403        * the stream. */
2404       gst_adapter_push (demux->rev_adapter,
2405           gst_adapter_take_buffer (demux->adapter, offset - 4));
2406     } else {
2407       GST_LOG_OBJECT (demux, "reverse saving %d bytes", avail);
2408       /* nothing found, keep all bytes */
2409       gst_adapter_push (demux->rev_adapter,
2410           gst_adapter_take_buffer (demux->adapter, avail));
2411     }
2412   }
2413
2414   if (found) {
2415     GST_LOG_OBJECT (demux, "Found resync code %08x after %d bytes",
2416         code, offset - 4);
2417     demux->last_sync_code = code;
2418   } else {
2419     GST_LOG_OBJECT (demux, "No resync after skipping %d", offset);
2420   }
2421
2422   return found;
2423 need_data:
2424   {
2425     GST_LOG_OBJECT (demux, "we need more data for resync %d", avail);
2426     return FALSE;
2427   }
2428 }
2429
2430 static inline gboolean
2431 gst_ps_demux_is_pes_sync (guint32 sync)
2432 {
2433   return ((sync & 0xfc) == 0xbc) ||
2434       ((sync & 0xe0) == 0xc0) || ((sync & 0xf0) == 0xe0);
2435 }
2436
2437 static inline gboolean
2438 gst_ps_demux_scan_ts (GstPsDemux * demux, const guint8 * data,
2439     SCAN_MODE mode, guint64 * rts, const guint8 * end)
2440 {
2441   gboolean ret = FALSE;
2442   guint32 scr1, scr2;
2443   guint64 scr;
2444   guint64 pts, dts;
2445   guint32 code;
2446   guint16 len;
2447   /* read the 4 bytes for the sync code */
2448   code = GST_READ_UINT32_BE (data);
2449   if (G_LIKELY (code != ID_PS_PACK_START_CODE))
2450     goto beach;
2451   if (data + 12 > end)
2452     goto beach;
2453   /* skip start code */
2454   data += 4;
2455   scr1 = GST_READ_UINT32_BE (data);
2456   scr2 = GST_READ_UINT32_BE (data + 4);
2457   /* start parsing the stream */
2458   if ((*data & 0xc0) == 0x40) {
2459     /* MPEG-2 PACK header */
2460     guint32 scr_ext;
2461     guint32 next32;
2462     guint8 stuffing_bytes;
2463     /* :2=01 ! scr:3 ! marker:1==1 ! scr:15 ! marker:1==1 ! scr:15 */
2464     /* check markers */
2465     if ((scr1 & 0xc4000400) != 0x44000400)
2466       goto beach;
2467     scr = ((guint64) scr1 & 0x38000000) << 3;
2468     scr |= ((guint64) scr1 & 0x03fff800) << 4;
2469     scr |= ((guint64) scr1 & 0x000003ff) << 5;
2470     scr |= ((guint64) scr2 & 0xf8000000) >> 27;
2471     /* marker:1==1 ! scr_ext:9 ! marker:1==1 */
2472     if ((scr2 & 0x04010000) != 0x04010000)
2473       goto beach;
2474     scr_ext = (scr2 & 0x03fe0000) >> 17;
2475     if (scr_ext) {
2476       scr = (scr * 300 + scr_ext % 300) / 300;
2477     }
2478     /* SCR has been converted into units of 90Khz ticks to make it comparable
2479        to DTS/PTS, that also implies 1 tick rounding error */
2480     data += 6;
2481
2482     if (data + 4 > end)
2483       goto beach;
2484     /* PMR:22 ! :2==11 ! reserved:5 ! stuffing_len:3 */
2485     next32 = GST_READ_UINT32_BE (data);
2486     if ((next32 & 0x00000300) != 0x00000300)
2487       goto beach;
2488     stuffing_bytes = (next32 & 0x07);
2489     data += 4;
2490     if (data + stuffing_bytes > end)
2491       goto beach;
2492     while (stuffing_bytes--) {
2493       if (*data++ != 0xff)
2494         goto beach;
2495     }
2496   } else {
2497     /* MPEG-1 pack header */
2498     /* check markers */
2499     if ((scr1 & 0xf1000100) != 0x21000100)
2500       goto beach;
2501     if ((scr2 & 0x01800001) != 0x01800001)
2502       goto beach;
2503     /* :4=0010 ! scr:3 ! marker:1==1 ! scr:15 ! marker:1==1 ! scr:15 ! marker:1==1 */
2504     scr = ((guint64) scr1 & 0x0e000000) << 5;
2505     scr |= ((guint64) scr1 & 0x00fffe00) << 6;
2506     scr |= ((guint64) scr1 & 0x000000ff) << 7;
2507     scr |= ((guint64) scr2 & 0xfe000000) >> 25;
2508     data += 8;
2509   }
2510
2511   if (mode == SCAN_SCR) {
2512     *rts = scr;
2513     ret = TRUE;
2514     goto beach;
2515   }
2516
2517   /* Possible optional System header here */
2518   if (data + 8 > end)
2519     goto beach;
2520
2521   code = GST_READ_UINT32_BE (data);
2522   len = GST_READ_UINT16_BE (data + 4);
2523   if (code == ID_PS_SYSTEM_HEADER_START_CODE) {
2524     /* Found a system header, skip it */
2525     /* Check for sufficient data - system header, plus enough
2526      * left over for the PES packet header */
2527     if (data + 6 + len + 6 > end)
2528       return FALSE;
2529     data += len + 6;
2530     /* read the 4 bytes for the PES sync code */
2531     code = GST_READ_UINT32_BE (data);
2532     len = GST_READ_UINT16_BE (data + 4);
2533   }
2534
2535   /* Check we have enough data left for reading the PES packet */
2536   if (data + 6 + len > end)
2537     return FALSE;
2538   if (!gst_ps_demux_is_pes_sync (code))
2539     goto beach;
2540   switch (code) {
2541     case ID_PS_PROGRAM_STREAM_MAP:
2542     case ID_PRIVATE_STREAM_2:
2543     case ID_ECM_STREAM:
2544     case ID_EMM_STREAM:
2545     case ID_PROGRAM_STREAM_DIRECTORY:
2546     case ID_DSMCC_STREAM:
2547     case ID_ITU_TREC_H222_TYPE_E_STREAM:
2548     case ID_PADDING_STREAM:
2549       goto beach;
2550     default:
2551       break;
2552   }
2553
2554   /* skip sync code and size */
2555   data += 6;
2556   pts = dts = -1;
2557   /* stuffing bits, first two bits are '10' for mpeg2 pes so this code is
2558    * not triggered. */
2559   while (TRUE) {
2560     if (*data != 0xff)
2561       break;
2562     data++;
2563   }
2564
2565   /* STD buffer size, never for mpeg2 */
2566   if ((*data & 0xc0) == 0x40)
2567     data += 2;
2568   /* PTS but no DTS, never for mpeg2 */
2569   if ((*data & 0xf0) == 0x20) {
2570     READ_TS (data, pts, beach);
2571   }
2572   /* PTS and DTS, never for mpeg2 */
2573   else if ((*data & 0xf0) == 0x30) {
2574     READ_TS (data, pts, beach);
2575     READ_TS (data, dts, beach);
2576   } else if ((*data & 0xc0) == 0x80) {
2577     /* mpeg2 case */
2578     guchar flags;
2579     /* 2: '10'
2580      * 2: PES_scrambling_control
2581      * 1: PES_priority
2582      * 1: data_alignment_indicator
2583      * 1: copyright
2584      * 1: original_or_copy
2585      */
2586     flags = *data++;
2587     if ((flags & 0xc0) != 0x80)
2588       goto beach;
2589     /* 2: PTS_DTS_flags
2590      * 1: ESCR_flag
2591      * 1: ES_rate_flag
2592      * 1: DSM_trick_mode_flag
2593      * 1: additional_copy_info_flag
2594      * 1: PES_CRC_flag
2595      * 1: PES_extension_flag
2596      */
2597     flags = *data++;
2598     /* 8: PES_header_data_length */
2599     data++;
2600     /* only DTS: this is invalid */
2601     if ((flags & 0xc0) == 0x40)
2602       goto beach;
2603     /* check for PTS */
2604     if ((flags & 0x80)) {
2605       READ_TS (data, pts, beach);
2606     }
2607     /* check for DTS */
2608     if ((flags & 0x40)) {
2609       READ_TS (data, dts, beach);
2610     }
2611   }
2612
2613   if (mode == SCAN_DTS && dts != (guint64) - 1) {
2614     *rts = dts;
2615     ret = TRUE;
2616   }
2617
2618   if (mode == SCAN_PTS && pts != (guint64) - 1) {
2619     *rts = pts;
2620     ret = TRUE;
2621   }
2622 beach:
2623   return ret;
2624 }
2625
2626 static inline gboolean
2627 gst_ps_demux_scan_forward_ts (GstPsDemux * demux, guint64 * pos,
2628     SCAN_MODE mode, guint64 * rts, gint limit)
2629 {
2630   GstFlowReturn ret = GST_FLOW_OK;
2631   GstBuffer *buffer;
2632   guint64 offset = *pos;
2633   gboolean found = FALSE;
2634   guint64 ts = 0;
2635   guint scan_sz = (mode == SCAN_SCR ? SCAN_SCR_SZ : SCAN_PTS_SZ);
2636   guint cursor, to_read = BLOCK_SZ;
2637   guint end_scan;
2638   GstMapInfo map;
2639   do {
2640     /* Check we can get at least scan_sz bytes */
2641     if (offset + scan_sz > demux->sink_segment.stop)
2642       return FALSE;
2643     /* Don't go further than 'limit' bytes */
2644     if (limit && offset > *pos + limit)
2645       return FALSE;
2646     if (offset + to_read > demux->sink_segment.stop)
2647       to_read = demux->sink_segment.stop - offset;
2648     /* read some data */
2649     buffer = NULL;
2650     ret = gst_pad_pull_range (demux->sinkpad, offset, to_read, &buffer);
2651     if (G_UNLIKELY (ret != GST_FLOW_OK))
2652       return FALSE;
2653     gst_buffer_map (buffer, &map, GST_MAP_READ);
2654     /* may get a short buffer at the end of the file */
2655     if (G_UNLIKELY (map.size <= scan_sz)) {
2656       gst_buffer_unmap (buffer, &map);
2657       gst_buffer_unref (buffer);
2658       return FALSE;
2659     }
2660
2661     end_scan = map.size - scan_sz;
2662     /* scan the block */
2663     for (cursor = 0; !found && cursor <= end_scan; cursor++) {
2664       found = gst_ps_demux_scan_ts (demux, map.data + cursor, mode, &ts,
2665           map.data + map.size);
2666     }
2667
2668     /* done with the buffer, unref it */
2669     gst_buffer_unmap (buffer, &map);
2670     gst_buffer_unref (buffer);
2671     if (found) {
2672       *rts = ts;
2673       *pos = offset + cursor - 1;
2674     } else {
2675       offset += cursor;
2676     }
2677   } while (!found && offset < demux->sink_segment.stop);
2678   return found;
2679 }
2680
2681 static inline gboolean
2682 gst_ps_demux_scan_backward_ts (GstPsDemux * demux, guint64 * pos,
2683     SCAN_MODE mode, guint64 * rts, gint limit)
2684 {
2685   GstFlowReturn ret = GST_FLOW_OK;
2686   GstBuffer *buffer;
2687   guint64 offset = *pos;
2688   gboolean found = FALSE;
2689   guint64 ts = 0;
2690   guint scan_sz = (mode == SCAN_SCR ? SCAN_SCR_SZ : SCAN_PTS_SZ);
2691   guint cursor, to_read = BLOCK_SZ;
2692   guint start_scan;
2693   guint8 *data;
2694   GstMapInfo map;
2695   do {
2696     /* Check we have at least scan_sz bytes available */
2697     if (offset < scan_sz - 1)
2698       return FALSE;
2699     /* Don't go backward past the start or 'limit' bytes */
2700     if (limit && offset + limit < *pos)
2701       return FALSE;
2702     if (offset > BLOCK_SZ)
2703       offset -= BLOCK_SZ;
2704     else {
2705       to_read = offset + 1;
2706       offset = 0;
2707     }
2708     /* read some data */
2709     buffer = NULL;
2710     ret = gst_pad_pull_range (demux->sinkpad, offset, to_read, &buffer);
2711     if (G_UNLIKELY (ret != GST_FLOW_OK))
2712       return FALSE;
2713     gst_buffer_map (buffer, &map, GST_MAP_READ);
2714     /* may get a short buffer at the end of the file */
2715     if (G_UNLIKELY (map.size <= scan_sz)) {
2716       gst_buffer_unmap (buffer, &map);
2717       gst_buffer_unref (buffer);
2718       return FALSE;
2719     }
2720
2721     start_scan = map.size - scan_sz;
2722     data = map.data + start_scan;
2723     /* scan the block */
2724     for (cursor = (start_scan + 1); !found && cursor > 0; cursor--) {
2725       found = gst_ps_demux_scan_ts (demux, data--, mode, &ts,
2726           map.data + map.size);
2727     }
2728
2729     /* done with the buffer, unref it */
2730     gst_buffer_unmap (buffer, &map);
2731     gst_buffer_unref (buffer);
2732     if (found) {
2733       *rts = ts;
2734       *pos = offset + cursor;
2735     }
2736
2737   } while (!found && offset > 0);
2738   return found;
2739 }
2740
2741 static inline gboolean
2742 gst_ps_sink_get_duration (GstPsDemux * demux)
2743 {
2744   gboolean res = FALSE;
2745   GstPad *peer;
2746   GstFormat format = GST_FORMAT_BYTES;
2747   gint64 length = 0;
2748   guint64 offset;
2749   guint i;
2750   guint64 scr = 0;
2751   /* init the sink segment */
2752   gst_segment_init (&demux->sink_segment, format);
2753   /* get peer to figure out length */
2754   if ((peer = gst_pad_get_peer (demux->sinkpad)) == NULL)
2755     goto beach;
2756   res = gst_pad_query_duration (peer, format, &length);
2757   gst_object_unref (peer);
2758   if (!res || length <= 0)
2759     goto beach;
2760   GST_DEBUG_OBJECT (demux, "file length %" G_GINT64_FORMAT, length);
2761   /* update the sink segment */
2762   demux->sink_segment.stop = length;
2763   gst_segment_set_duration (&demux->sink_segment, format, length);
2764   gst_segment_set_position (&demux->sink_segment, format, 0);
2765   /* Scan for notorious SCR and PTS to calculate the duration */
2766   /* scan for first SCR in the stream */
2767   offset = demux->sink_segment.start;
2768   gst_ps_demux_scan_forward_ts (demux, &offset, SCAN_SCR,
2769       &demux->first_scr, DURATION_SCAN_LIMIT);
2770   GST_DEBUG_OBJECT (demux,
2771       "First SCR: %" G_GINT64_FORMAT " %" GST_TIME_FORMAT
2772       " in packet starting at %" G_GUINT64_FORMAT, demux->first_scr,
2773       GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (demux->first_scr)), offset);
2774   demux->first_scr_offset = offset;
2775   /* scan for last SCR in the stream */
2776   offset = demux->sink_segment.stop;
2777   gst_ps_demux_scan_backward_ts (demux, &offset, SCAN_SCR,
2778       &demux->last_scr, DURATION_SCAN_LIMIT);
2779   GST_DEBUG_OBJECT (demux,
2780       "Last SCR: %" G_GINT64_FORMAT " %" GST_TIME_FORMAT
2781       " in packet starting at %" G_GUINT64_FORMAT, demux->last_scr,
2782       GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (demux->last_scr)), offset);
2783   demux->last_scr_offset = offset;
2784   /* scan for first PTS in the stream */
2785   offset = demux->sink_segment.start;
2786   gst_ps_demux_scan_forward_ts (demux, &offset, SCAN_PTS,
2787       &demux->first_pts, DURATION_SCAN_LIMIT);
2788   GST_DEBUG_OBJECT (demux,
2789       "First PTS: %" G_GINT64_FORMAT " %" GST_TIME_FORMAT
2790       " in packet starting at %" G_GUINT64_FORMAT, demux->first_pts,
2791       GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (demux->first_pts)), offset);
2792   if (demux->first_pts != G_MAXUINT64) {
2793     /* scan for last PTS in the stream */
2794     offset = demux->sink_segment.stop;
2795     gst_ps_demux_scan_backward_ts (demux, &offset, SCAN_PTS,
2796         &demux->last_pts, DURATION_SCAN_LIMIT);
2797     GST_DEBUG_OBJECT (demux,
2798         "Last PTS: %" G_GINT64_FORMAT " %" GST_TIME_FORMAT
2799         " in packet starting at %" G_GUINT64_FORMAT, demux->last_pts,
2800         GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (demux->last_pts)), offset);
2801   }
2802   /* Detect wrong SCR values */
2803   if (demux->first_scr > demux->last_scr) {
2804     GST_DEBUG_OBJECT (demux, "Wrong SCR values detected, searching for "
2805         "a better first SCR value");
2806     offset = demux->first_scr_offset;
2807     for (i = 0; i < 10; i++) {
2808       offset++;
2809       gst_ps_demux_scan_forward_ts (demux, &offset, SCAN_SCR, &scr, 0);
2810       if (scr < demux->last_scr) {
2811         demux->first_scr = scr;
2812         demux->first_scr_offset = offset;
2813         /* Start demuxing from the right place */
2814         demux->sink_segment.position = offset;
2815         GST_DEBUG_OBJECT (demux, "Replaced First SCR: %" G_GINT64_FORMAT
2816             " %" GST_TIME_FORMAT " in packet starting at %"
2817             G_GUINT64_FORMAT, demux->first_scr,
2818             GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (demux->first_scr)), offset);
2819         break;
2820       }
2821     }
2822   }
2823   /* Set the base_time and avg rate */
2824   demux->base_time = MPEGTIME_TO_GSTTIME (demux->first_scr);
2825   demux->scr_rate_n = demux->last_scr_offset - demux->first_scr_offset;
2826   demux->scr_rate_d = demux->last_scr - demux->first_scr;
2827   if (G_LIKELY (demux->first_pts != G_MAXUINT64 &&
2828           demux->last_pts != G_MAXUINT64)) {
2829     /* update the src segment */
2830     demux->src_segment.format = GST_FORMAT_TIME;
2831     demux->src_segment.start =
2832         MPEGTIME_TO_GSTTIME (demux->first_pts) - demux->base_time;
2833     demux->src_segment.stop = -1;
2834     gst_segment_set_duration (&demux->src_segment, GST_FORMAT_TIME,
2835         MPEGTIME_TO_GSTTIME (demux->last_pts - demux->first_pts));
2836     gst_segment_set_position (&demux->src_segment, GST_FORMAT_TIME,
2837         demux->src_segment.start);
2838   }
2839   GST_INFO_OBJECT (demux, "sink segment configured %" GST_SEGMENT_FORMAT,
2840       &demux->sink_segment);
2841   GST_INFO_OBJECT (demux, "src segment configured %" GST_SEGMENT_FORMAT,
2842       &demux->src_segment);
2843   res = TRUE;
2844 beach:
2845   return res;
2846 }
2847
2848 static inline GstFlowReturn
2849 gst_ps_demux_pull_block (GstPad * pad, GstPsDemux * demux,
2850     guint64 offset, guint size)
2851 {
2852   GstFlowReturn ret;
2853   GstBuffer *buffer = NULL;
2854   ret = gst_pad_pull_range (pad, offset, size, &buffer);
2855   if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2856     GST_DEBUG_OBJECT (demux, "pull range at %" G_GUINT64_FORMAT
2857         " size %u failed", offset, size);
2858     goto beach;
2859   } else
2860     GST_LOG_OBJECT (demux, "pull range at %" G_GUINT64_FORMAT
2861         " size %u done", offset, size);
2862   if (demux->sink_segment.rate < 0) {
2863     GST_LOG_OBJECT (demux, "setting discont flag on backward rate");
2864     GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
2865   }
2866   ret = gst_ps_demux_chain (pad, GST_OBJECT (demux), buffer);
2867 beach:
2868   return ret;
2869 }
2870
2871 static void
2872 gst_ps_demux_loop (GstPad * pad)
2873 {
2874   GstPsDemux *demux;
2875   GstFlowReturn ret = GST_FLOW_OK;
2876   guint64 offset = 0;
2877   demux = GST_PS_DEMUX (gst_pad_get_parent (pad));
2878   if (G_UNLIKELY (demux->flushing)) {
2879     ret = GST_FLOW_FLUSHING;
2880     goto pause;
2881   }
2882
2883   if (G_UNLIKELY (demux->sink_segment.format == GST_FORMAT_UNDEFINED))
2884     gst_ps_sink_get_duration (demux);
2885   offset = demux->sink_segment.position;
2886   if (demux->sink_segment.rate >= 0) {
2887     guint size = BLOCK_SZ;
2888     if (G_LIKELY (demux->sink_segment.stop != (guint64) - 1)) {
2889       size = MIN (size, demux->sink_segment.stop - offset);
2890     }
2891     /* pull in data */
2892     ret = gst_ps_demux_pull_block (pad, demux, offset, size);
2893     /* pause if something went wrong */
2894     if (G_UNLIKELY (ret != GST_FLOW_OK))
2895       goto pause;
2896     /* update our position */
2897     offset += size;
2898     gst_segment_set_position (&demux->sink_segment, GST_FORMAT_BYTES, offset);
2899     /* check EOS condition */
2900     if ((demux->sink_segment.position >= demux->sink_segment.stop) ||
2901         (demux->src_segment.stop != (guint64) - 1 &&
2902             demux->src_segment.position >= demux->src_segment.stop)) {
2903       GST_DEBUG_OBJECT (demux,
2904           "forward mode using segment reached end of " "segment pos %"
2905           GST_TIME_FORMAT " stop %" GST_TIME_FORMAT " pos in bytes %"
2906           G_GUINT64_FORMAT " stop in bytes %" G_GUINT64_FORMAT,
2907           GST_TIME_ARGS (demux->src_segment.position),
2908           GST_TIME_ARGS (demux->src_segment.stop),
2909           demux->sink_segment.position, demux->sink_segment.stop);
2910       ret = GST_FLOW_EOS;
2911       goto pause;
2912     }
2913   } else {                      /* Reverse playback */
2914     guint64 size = MIN (offset, BLOCK_SZ);
2915     /* pull in data */
2916     ret = gst_ps_demux_pull_block (pad, demux, offset - size, size);
2917     /* pause if something went wrong */
2918     if (G_UNLIKELY (ret != GST_FLOW_OK))
2919       goto pause;
2920     /* update our position */
2921     offset -= size;
2922     gst_segment_set_position (&demux->sink_segment, GST_FORMAT_BYTES, offset);
2923     /* check EOS condition */
2924     if (demux->sink_segment.position <= demux->sink_segment.start ||
2925         demux->src_segment.position <= demux->src_segment.start) {
2926       GST_DEBUG_OBJECT (demux,
2927           "reverse mode using segment reached end of " "segment pos %"
2928           GST_TIME_FORMAT " stop %" GST_TIME_FORMAT " pos in bytes %"
2929           G_GUINT64_FORMAT " stop in bytes %" G_GUINT64_FORMAT,
2930           GST_TIME_ARGS (demux->src_segment.position),
2931           GST_TIME_ARGS (demux->src_segment.start),
2932           demux->sink_segment.position, demux->sink_segment.start);
2933       ret = GST_FLOW_EOS;
2934       goto pause;
2935     }
2936   }
2937
2938   gst_object_unref (demux);
2939   return;
2940 pause:
2941   {
2942     const gchar *reason = gst_flow_get_name (ret);
2943     GST_LOG_OBJECT (demux, "pausing task, reason %s", reason);
2944     gst_pad_pause_task (pad);
2945     if (ret == GST_FLOW_EOS) {
2946       /* perform EOS logic */
2947       gst_element_no_more_pads (GST_ELEMENT_CAST (demux));
2948       if (demux->src_segment.flags & GST_SEEK_FLAG_SEGMENT) {
2949         gint64 stop;
2950         /* for segment playback we need to post when (in stream time)
2951          * we stopped, this is either stop (when set) or the duration. */
2952         if ((stop = demux->src_segment.stop) == -1)
2953           stop = demux->src_segment.duration;
2954         if (demux->sink_segment.rate >= 0) {
2955           GST_LOG_OBJECT (demux, "Sending segment done, at end of segment");
2956           gst_element_post_message (GST_ELEMENT_CAST (demux),
2957               gst_message_new_segment_done (GST_OBJECT_CAST (demux),
2958                   GST_FORMAT_TIME, stop));
2959           gst_ps_demux_send_event (demux,
2960               gst_event_new_segment_done (GST_FORMAT_TIME, stop));
2961         } else {                /* Reverse playback */
2962           GST_LOG_OBJECT (demux,
2963               "Sending segment done, at beginning of " "segment");
2964           gst_element_post_message (GST_ELEMENT_CAST (demux),
2965               gst_message_new_segment_done (GST_OBJECT_CAST (demux),
2966                   GST_FORMAT_TIME, demux->src_segment.start));
2967           gst_ps_demux_send_event (demux,
2968               gst_event_new_segment_done (GST_FORMAT_TIME,
2969                   demux->src_segment.start));
2970         }
2971       } else {
2972         /* normal playback, send EOS to all linked pads */
2973         gst_element_no_more_pads (GST_ELEMENT (demux));
2974         GST_LOG_OBJECT (demux, "Sending EOS, at end of stream");
2975         if (!gst_ps_demux_send_event (demux, gst_event_new_eos ())
2976             && !have_open_streams (demux)) {
2977           GST_WARNING_OBJECT (demux, "EOS and no streams open");
2978           GST_ELEMENT_ERROR (demux, STREAM, FAILED,
2979               ("Internal data stream error."), ("No valid streams detected"));
2980         }
2981       }
2982     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
2983       GST_ELEMENT_FLOW_ERROR (demux, ret);
2984       gst_ps_demux_send_event (demux, gst_event_new_eos ());
2985     }
2986
2987     gst_object_unref (demux);
2988     return;
2989   }
2990 }
2991
2992 /* If we can pull that's preferred */
2993 static gboolean
2994 gst_ps_demux_sink_activate (GstPad * sinkpad, GstObject * parent)
2995 {
2996   gboolean res = FALSE;
2997   GstQuery *query = gst_query_new_scheduling ();
2998   if (gst_pad_peer_query (sinkpad, query)) {
2999     if (gst_query_has_scheduling_mode_with_flags (query,
3000             GST_PAD_MODE_PULL, GST_SCHEDULING_FLAG_SEEKABLE)) {
3001       res = gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
3002     } else {
3003       res = gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
3004     }
3005   } else {
3006     res = gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
3007   }
3008
3009   gst_query_unref (query);
3010   return res;
3011 }
3012
3013 /* This function gets called when we activate ourselves in push mode. */
3014 static gboolean
3015 gst_ps_demux_sink_activate_push (GstPad * sinkpad, GstObject * parent,
3016     gboolean active)
3017 {
3018   GstPsDemux *demux = GST_PS_DEMUX (parent);
3019   demux->random_access = FALSE;
3020   return TRUE;
3021 }
3022
3023 /* this function gets called when we activate ourselves in pull mode.
3024  * We can perform  random access to the resource and we start a task
3025  * to start reading */
3026 static gboolean
3027 gst_ps_demux_sink_activate_pull (GstPad * sinkpad, GstObject * parent,
3028     gboolean active)
3029 {
3030   GstPsDemux *demux = GST_PS_DEMUX (parent);
3031   if (active) {
3032     GST_DEBUG ("pull mode activated");
3033     demux->random_access = TRUE;
3034     return gst_pad_start_task (sinkpad,
3035         (GstTaskFunction) gst_ps_demux_loop, sinkpad, NULL);
3036   } else {
3037     demux->random_access = FALSE;
3038     return gst_pad_stop_task (sinkpad);
3039   }
3040 }
3041
3042 static gboolean
3043 gst_ps_demux_sink_activate_mode (GstPad * pad, GstObject * parent,
3044     GstPadMode mode, gboolean active)
3045 {
3046   if (mode == GST_PAD_MODE_PUSH) {
3047     return gst_ps_demux_sink_activate_push (pad, parent, active);
3048   } else if (mode == GST_PAD_MODE_PULL) {
3049     return gst_ps_demux_sink_activate_pull (pad, parent, active);
3050   }
3051   return FALSE;
3052 }
3053
3054 /* EOS and NOT_LINKED need to be combined. This means that we return:
3055 *
3056 *  GST_FLOW_NOT_LINKED: when all pads NOT_LINKED.
3057 *  GST_FLOW_EOS: when all pads EOS or NOT_LINKED.
3058 */
3059 static GstFlowReturn
3060 gst_ps_demux_combine_flows (GstPsDemux * demux, GstFlowReturn ret)
3061 {
3062   GST_LOG_OBJECT (demux, "flow return: %s", gst_flow_get_name (ret));
3063   ret = gst_flow_combiner_update_flow (demux->flowcombiner, ret);
3064   if (G_UNLIKELY (demux->need_no_more_pads && ret == GST_FLOW_NOT_LINKED))
3065     ret = GST_FLOW_OK;
3066   GST_LOG_OBJECT (demux, "combined flow return: %s", gst_flow_get_name (ret));
3067   return ret;
3068 }
3069
3070 static GstFlowReturn
3071 gst_ps_demux_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
3072 {
3073   GstPsDemux *demux = GST_PS_DEMUX (parent);
3074   GstFlowReturn ret = GST_FLOW_OK;
3075   guint32 avail;
3076   gboolean save, discont;
3077   discont = GST_BUFFER_IS_DISCONT (buffer);
3078   if (discont) {
3079     GST_LOG_OBJECT (demux,
3080         "Received buffer with discont flag and" " offset %"
3081         G_GUINT64_FORMAT, GST_BUFFER_OFFSET (buffer));
3082     gst_pes_filter_drain (&demux->filter);
3083     gst_ps_demux_mark_discont (demux, TRUE, FALSE);
3084     /* mark discont on all streams */
3085     if (demux->sink_segment.rate >= 0.0) {
3086       demux->current_scr = G_MAXUINT64;
3087       demux->bytes_since_scr = 0;
3088     }
3089   } else {
3090     GST_LOG_OBJECT (demux,
3091         "Received buffer with offset %" G_GUINT64_FORMAT,
3092         GST_BUFFER_OFFSET (buffer));
3093   }
3094
3095   /* We keep the offset to interpolate SCR */
3096   demux->adapter_offset = GST_BUFFER_OFFSET (buffer);
3097   gst_adapter_push (demux->adapter, buffer);
3098   demux->bytes_since_scr += gst_buffer_get_size (buffer);
3099   avail = gst_adapter_available (demux->rev_adapter);
3100   if (avail > 0) {
3101     GST_LOG_OBJECT (demux, "appending %u saved bytes", avail);
3102     /* if we have a previous reverse chunk, append this now */
3103     /* FIXME this code assumes we receive discont buffers all thei
3104      * time */
3105     gst_adapter_push (demux->adapter,
3106         gst_adapter_take_buffer (demux->rev_adapter, avail));
3107   }
3108
3109   avail = gst_adapter_available (demux->adapter);
3110   GST_LOG_OBJECT (demux, "avail now: %d, state %d", avail, demux->filter.state);
3111   switch (demux->filter.state) {
3112     case STATE_DATA_SKIP:
3113     case STATE_DATA_PUSH:
3114       ret = gst_pes_filter_process (&demux->filter);
3115       break;
3116     case STATE_HEADER_PARSE:
3117       break;
3118     default:
3119       break;
3120   }
3121
3122   switch (ret) {
3123     case GST_FLOW_NEED_MORE_DATA:
3124       /* Go and get more data */
3125       ret = GST_FLOW_OK;
3126       goto done;
3127     case GST_FLOW_LOST_SYNC:
3128       /* for FLOW_OK or lost-sync, carry onto resync */
3129       ret = GST_FLOW_OK;
3130       break;
3131     case GST_FLOW_OK:
3132       break;
3133     default:
3134       /* Any other return value should be sent upstream immediately */
3135       goto done;
3136   }
3137
3138   /* align adapter data to sync boundary, we keep the data up to the next sync
3139    * point. */
3140   save = TRUE;
3141   while (gst_ps_demux_resync (demux, save)) {
3142     gboolean ps_sync = TRUE;
3143     if (G_UNLIKELY (demux->flushing)) {
3144       ret = GST_FLOW_FLUSHING;
3145       goto done;
3146     }
3147
3148     /* now switch on last synced byte */
3149     switch (demux->last_sync_code) {
3150       case ID_PS_PACK_START_CODE:
3151         ret = gst_ps_demux_parse_pack_start (demux);
3152         break;
3153       case ID_PS_SYSTEM_HEADER_START_CODE:
3154         ret = gst_ps_demux_parse_sys_head (demux);
3155         break;
3156       case ID_PS_END_CODE:
3157         /* Skip final 4 bytes */
3158         gst_adapter_flush (demux->adapter, 4);
3159         ADAPTER_OFFSET_FLUSH (4);
3160         ret = GST_FLOW_OK;
3161         goto done;
3162       case ID_PS_PROGRAM_STREAM_MAP:
3163         ret = gst_ps_demux_parse_psm (demux);
3164         break;
3165       default:
3166         if (gst_ps_demux_is_pes_sync (demux->last_sync_code)) {
3167           ret = gst_pes_filter_process (&demux->filter);
3168         } else {
3169           GST_DEBUG_OBJECT (demux, "sync_code=%08x, non PES sync found"
3170               ", continuing", demux->last_sync_code);
3171           ps_sync = FALSE;
3172           ret = GST_FLOW_LOST_SYNC;
3173         }
3174         break;
3175     }
3176     /* if we found a ps sync, we stop saving the data, any non-ps sync gets
3177      * saved up to the next ps sync. */
3178     if (ps_sync)
3179       save = FALSE;
3180     switch (ret) {
3181       case GST_FLOW_NEED_MORE_DATA:
3182         GST_DEBUG_OBJECT (demux, "need more data");
3183         ret = GST_FLOW_OK;
3184         goto done;
3185       case GST_FLOW_LOST_SYNC:
3186         if (!save || demux->sink_segment.rate >= 0.0) {
3187           GST_DEBUG_OBJECT (demux, "flushing 3 bytes");
3188           gst_adapter_flush (demux->adapter, 3);
3189           ADAPTER_OFFSET_FLUSH (3);
3190         } else {
3191           GST_DEBUG_OBJECT (demux, "saving 3 bytes");
3192           gst_adapter_push (demux->rev_adapter,
3193               gst_adapter_take_buffer (demux->adapter, 3));
3194         }
3195         ret = GST_FLOW_OK;
3196         break;
3197       default:
3198         ret = gst_ps_demux_combine_flows (demux, ret);
3199         if (ret != GST_FLOW_OK)
3200           goto done;
3201         break;
3202     }
3203   }
3204 done:
3205   return ret;
3206 }
3207
3208 static GstStateChangeReturn
3209 gst_ps_demux_change_state (GstElement * element, GstStateChange transition)
3210 {
3211   GstPsDemux *demux = GST_PS_DEMUX (element);
3212   GstStateChangeReturn result;
3213   switch (transition) {
3214     case GST_STATE_CHANGE_NULL_TO_READY:
3215       gst_pes_filter_init (&demux->filter, demux->adapter,
3216           &demux->adapter_offset);
3217       gst_pes_filter_set_callbacks (&demux->filter,
3218           (GstPESFilterData) gst_ps_demux_data_cb,
3219           (GstPESFilterResync) gst_ps_demux_resync_cb, demux);
3220       demux->filter.gather_pes = TRUE;
3221       break;
3222     case GST_STATE_CHANGE_READY_TO_PAUSED:
3223       break;
3224     default:
3225       break;
3226   }
3227
3228   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3229   switch (transition) {
3230     case GST_STATE_CHANGE_PAUSED_TO_READY:
3231       gst_ps_demux_reset (demux);
3232       break;
3233     case GST_STATE_CHANGE_READY_TO_NULL:
3234       gst_pes_filter_uninit (&demux->filter);
3235       break;
3236     default:
3237       break;
3238   }
3239
3240   return result;
3241 }
3242
3243 static void
3244 gst_segment_set_position (GstSegment * segment, GstFormat format,
3245     guint64 position)
3246 {
3247   if (segment->format == GST_FORMAT_UNDEFINED) {
3248     segment->format = format;
3249   }
3250   segment->position = position;
3251 }
3252
3253 static void
3254 gst_segment_set_duration (GstSegment * segment, GstFormat format,
3255     guint64 duration)
3256 {
3257   if (segment->format == GST_FORMAT_UNDEFINED) {
3258     segment->format = format;
3259   }
3260   segment->duration = duration;
3261 }