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