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