Merge branch 'move_subdir_editing-services' into tizen_gst_1.19.2_mono
[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 #ifdef TIZEN_FEATURE_MPEGDEMUX_MODIFICATION
1352       goto seek_error;
1353 #else
1354       return FALSE;
1355 #endif
1356     }
1357   }
1358
1359   /* check the limits */
1360   if (seeksegment.rate > 0.0 && first_pts != G_MAXUINT64
1361       && seeksegment.start < first_pts - demux->base_time) {
1362     seeksegment.position = first_pts - demux->base_time;
1363     if (!accurate)
1364       seeksegment.start = seeksegment.position;
1365   }
1366
1367   /* update the rate in our src segment */
1368   demux->sink_segment.rate = rate;
1369
1370   GST_DEBUG_OBJECT (demux, "seek segment adjusted %" GST_SEGMENT_FORMAT,
1371       &seeksegment);
1372
1373   if (flush) {
1374     GstEvent *event = gst_event_new_flush_stop (TRUE);
1375     /* Stop flushing, the sinks are at time 0 now */
1376     gst_event_set_seqnum (event, seek_seqnum);
1377     gst_ps_demux_send_event (demux, event);
1378   }
1379
1380   if (flush || seeksegment.position != demux->src_segment.position) {
1381     gst_ps_demux_flush (demux);
1382   }
1383
1384   /* Ok seek succeeded, take the newly configured segment */
1385   memcpy (&demux->src_segment, &seeksegment, sizeof (GstSegment));
1386
1387   /* Notify about the start of a new segment */
1388   if (demux->src_segment.flags & GST_SEEK_FLAG_SEGMENT) {
1389     gst_element_post_message (GST_ELEMENT (demux),
1390         gst_message_new_segment_start (GST_OBJECT (demux),
1391             demux->src_segment.format, demux->src_segment.position));
1392   }
1393
1394   /* Tell all the stream a new segment is needed */
1395   gst_ps_demux_mark_discont (demux, TRUE, TRUE);
1396
1397   /* Update the segment_seqnum with the seek event seqnum */
1398   demux->segment_seqnum = seek_seqnum;
1399
1400   gst_pad_start_task (demux->sinkpad,
1401       (GstTaskFunction) gst_ps_demux_loop, demux->sinkpad, NULL);
1402
1403   GST_PAD_STREAM_UNLOCK (demux->sinkpad);
1404
1405   gst_event_unref (event);
1406   return TRUE;
1407
1408   /* ERRORS */
1409 wrong_format:
1410   {
1411     GST_WARNING_OBJECT (demux, "we only support seeking in TIME or BYTES "
1412         "formats");
1413     gst_event_unref (event);
1414     return FALSE;
1415   }
1416 no_scr_rate:
1417   {
1418     GST_WARNING_OBJECT (demux, "seek not possible, no scr_rate");
1419     gst_event_unref (event);
1420     return FALSE;
1421   }
1422 seek_error:
1423   {
1424     GST_WARNING_OBJECT (demux, "couldn't perform seek");
1425 #ifdef TIZEN_FEATURE_MPEGDEMUX_MODIFICATION
1426     GST_PAD_STREAM_UNLOCK (demux->sinkpad);
1427 #endif
1428     gst_event_unref (event);
1429     return FALSE;
1430   }
1431 }
1432
1433 static gboolean
1434 gst_ps_demux_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1435 {
1436   gboolean res = FALSE;
1437   GstPsDemux *demux = GST_PS_DEMUX (parent);
1438
1439   switch (GST_EVENT_TYPE (event)) {
1440     case GST_EVENT_SEEK:
1441       if (demux->random_access) {
1442         res = gst_ps_demux_handle_seek_pull (demux, event);
1443       } else {
1444         res = gst_ps_demux_handle_seek_push (demux, event);
1445       }
1446       break;
1447     case GST_EVENT_RECONFIGURE:{
1448       GstPsStream *stream;
1449
1450       stream = gst_ps_demux_get_stream_from_pad (demux, pad);
1451       if (stream != NULL)
1452         stream->notlinked = FALSE;
1453
1454       gst_event_unref (event);
1455       res = TRUE;
1456       break;
1457     }
1458     default:
1459       res = gst_pad_push_event (demux->sinkpad, event);
1460       break;
1461   }
1462
1463   return res;
1464 }
1465
1466 static gboolean
1467 gst_ps_demux_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1468 {
1469   gboolean res = FALSE;
1470   GstPsDemux *demux = GST_PS_DEMUX (parent);
1471
1472   GST_LOG_OBJECT (demux, "Have query of type %d on pad %" GST_PTR_FORMAT,
1473       GST_QUERY_TYPE (query), pad);
1474
1475   switch (GST_QUERY_TYPE (query)) {
1476     case GST_QUERY_POSITION:
1477     {
1478       GstClockTime pos;
1479       GstFormat format;
1480
1481       /* See if upstream can immediately answer */
1482       res = gst_pad_peer_query (demux->sinkpad, query);
1483       if (res)
1484         break;
1485
1486       gst_query_parse_position (query, &format, NULL);
1487
1488       if (format != GST_FORMAT_TIME) {
1489         GST_DEBUG_OBJECT (demux, "position not supported for format: %s",
1490             gst_format_get_name (format));
1491         goto not_supported;
1492       }
1493
1494       pos = demux->src_segment.position - demux->src_segment.start;
1495       GST_LOG_OBJECT (demux, "Position %" GST_TIME_FORMAT, GST_TIME_ARGS (pos));
1496
1497       gst_query_set_position (query, format, pos);
1498       res = TRUE;
1499       break;
1500     }
1501     case GST_QUERY_DURATION:
1502     {
1503       GstFormat format;
1504       gint64 duration;
1505       GstQuery *byte_query;
1506
1507       gst_query_parse_duration (query, &format, NULL);
1508
1509       if (G_LIKELY (format == GST_FORMAT_TIME &&
1510               GST_CLOCK_TIME_IS_VALID (demux->src_segment.duration))) {
1511         gst_query_set_duration (query, GST_FORMAT_TIME,
1512             demux->src_segment.duration);
1513         res = TRUE;
1514         break;
1515       }
1516
1517       /* For any format other than bytes, see if upstream knows first */
1518       if (format == GST_FORMAT_BYTES) {
1519         GST_DEBUG_OBJECT (demux, "duration not supported for format: %s",
1520             gst_format_get_name (format));
1521         goto not_supported;
1522       }
1523
1524       if (gst_pad_peer_query (demux->sinkpad, query)) {
1525         res = TRUE;
1526         break;
1527       }
1528
1529       /* Upstream didn't know, so we can only answer TIME queries from
1530        * here on */
1531       if (format != GST_FORMAT_TIME) {
1532         GST_DEBUG_OBJECT (demux, "duration not supported for format: %s",
1533             gst_format_get_name (format));
1534         goto not_supported;
1535       }
1536
1537       if (demux->mux_rate == -1) {
1538         GST_DEBUG_OBJECT (demux, "duration not possible, no mux_rate");
1539         goto not_supported;
1540       }
1541
1542       byte_query = gst_query_new_duration (GST_FORMAT_BYTES);
1543
1544       if (!gst_pad_peer_query (demux->sinkpad, byte_query)) {
1545         GST_LOG_OBJECT (demux, "query on peer pad failed");
1546         gst_query_unref (byte_query);
1547         goto not_supported;
1548       }
1549
1550       gst_query_parse_duration (byte_query, &format, &duration);
1551       gst_query_unref (byte_query);
1552
1553       GST_LOG_OBJECT (demux,
1554           "query on peer pad reported bytes %" G_GUINT64_FORMAT, duration);
1555
1556       duration = BYTES_TO_GSTTIME ((guint64) duration);
1557
1558       GST_LOG_OBJECT (demux, "converted to time %" GST_TIME_FORMAT,
1559           GST_TIME_ARGS (duration));
1560
1561       gst_query_set_duration (query, GST_FORMAT_TIME, duration);
1562       res = TRUE;
1563       break;
1564     }
1565     case GST_QUERY_SEEKING:{
1566       GstFormat fmt;
1567
1568       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
1569
1570       res = TRUE;
1571       if (demux->random_access) {
1572         /* In pull mode we can seek in TIME format if we have the SCR */
1573         if (fmt != GST_FORMAT_TIME || demux->scr_rate_n == G_MAXUINT64
1574             || demux->scr_rate_d == G_MAXUINT64) {
1575           gst_query_set_seeking (query, fmt, FALSE, -1, -1);
1576         } else {
1577           gint64 dur = -1;
1578           if (GST_CLOCK_TIME_IS_VALID (demux->src_segment.duration))
1579             dur = demux->src_segment.duration;
1580           gst_query_set_seeking (query, fmt, TRUE, 0, dur);
1581         }
1582       } else {
1583         if (fmt == GST_FORMAT_BYTES) {
1584           /* Seeking in BYTES format not supported at all */
1585           gst_query_set_seeking (query, fmt, FALSE, -1, -1);
1586         } else {
1587           GstQuery *peerquery;
1588           gboolean seekable;
1589
1590           /* Then ask upstream */
1591           res = gst_pad_peer_query (demux->sinkpad, query);
1592           if (res) {
1593             /* If upstream can handle seeks we're done, if it
1594              * can't we still have our TIME->BYTES conversion seek
1595              */
1596             gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
1597             if (seekable || fmt != GST_FORMAT_TIME)
1598               goto beach;
1599           }
1600
1601           /* We can seek if upstream supports BYTES seeks and we
1602            * have the SCR
1603            */
1604           peerquery = gst_query_new_seeking (GST_FORMAT_BYTES);
1605           res = gst_pad_peer_query (demux->sinkpad, peerquery);
1606           if (!res || demux->scr_rate_n == G_MAXUINT64
1607               || demux->scr_rate_d == G_MAXUINT64) {
1608             gst_query_set_seeking (query, fmt, FALSE, -1, -1);
1609           } else {
1610             gst_query_parse_seeking (peerquery, NULL, &seekable, NULL, NULL);
1611             if (seekable)
1612               gst_query_set_seeking (query, GST_FORMAT_TIME, TRUE, 0, -1);
1613             else
1614               gst_query_set_seeking (query, fmt, FALSE, -1, -1);
1615           }
1616
1617           gst_query_unref (peerquery);
1618           res = TRUE;
1619         }
1620       }
1621       break;
1622     }
1623     case GST_QUERY_SEGMENT:{
1624       GstFormat format;
1625       gint64 start, stop;
1626
1627       format = demux->src_segment.format;
1628
1629       start =
1630           gst_segment_to_stream_time (&demux->src_segment, format,
1631           demux->src_segment.start);
1632       if ((stop = demux->src_segment.stop) == -1)
1633         stop = demux->src_segment.duration;
1634       else
1635         stop = gst_segment_to_stream_time (&demux->src_segment, format, stop);
1636
1637       gst_query_set_segment (query, demux->src_segment.rate, format, start,
1638           stop);
1639       res = TRUE;
1640       break;
1641     }
1642     default:
1643       res = gst_pad_query_default (pad, parent, query);
1644       break;
1645   }
1646
1647 beach:
1648   return res;
1649 not_supported:
1650   return FALSE;
1651 }
1652
1653 static void
1654 gst_ps_demux_reset_psm (GstPsDemux * demux)
1655 {
1656   gint i;
1657
1658 #define FILL_TYPE(start, stop, type)    \
1659   for (i=start; i <= stop; i++)                 \
1660     demux->psm[i] = type;
1661
1662   /* Initialize all fields to -1 first */
1663   FILL_TYPE (0x00, GST_PS_DEMUX_MAX_PSM - 1, -1);
1664
1665   FILL_TYPE (0x20, 0x3f, ST_PS_DVD_SUBPICTURE);
1666
1667   FILL_TYPE (0x80, 0x87, ST_PS_AUDIO_AC3);
1668   FILL_TYPE (0x88, 0x9f, ST_PS_AUDIO_DTS);
1669   FILL_TYPE (0xa0, 0xaf, ST_PS_AUDIO_LPCM);
1670
1671   FILL_TYPE (0xc0, 0xdf, ST_AUDIO_MPEG1);
1672   FILL_TYPE (0xe0, 0xef, ST_GST_VIDEO_MPEG1_OR_2);
1673
1674 #undef FILL_TYPE
1675 }
1676
1677 /* ISO/IEC 13818-1:
1678  * pack_header() {
1679  *     pack_start_code                                   32  bslbf  -+
1680  *     '01'                                               2  bslbf   |
1681  *     system_clock_reference_base [32..30]               3  bslbf   |
1682  *     marker_bit                                         1  bslbf   |
1683  *     system_clock_reference_base [29..15]              15  bslbf   |
1684  *     marker_bit                                         1  bslbf   |
1685  *     system_clock_reference_base [14..0]               15  bslbf   |
1686  *     marker_bit                                         1  bslbf   | 112 bits
1687  *     system_clock_reference_extension                   9  ubslbf  |
1688  *     marker_bit                                         1  bslbf   |
1689  *     program_mux_rate                                  22  ubslbf  |
1690  *     marker_bit                                         1  bslbf   |
1691  *     marker_bit                                         1  bslbf   |
1692  *     reserved                                           5  bslbf   |
1693  *     pack_stuffing_length                               3  ubslbf -+
1694  *
1695  *     for (i = 0; i < pack_stuffing_length; i++) {
1696  *         stuffing_byte '1111 1111'                      8  bslbf
1697  *     }
1698  *
1699  * 112 bits = 14 bytes, as max value for pack_stuffing_length is 7, then
1700  * in total it's needed 14 + 7 = 21 bytes.
1701  */
1702 #define PACK_START_SIZE     21
1703
1704 static GstFlowReturn
1705 gst_ps_demux_parse_pack_start (GstPsDemux * demux)
1706 {
1707   const guint8 *data;
1708   guint length;
1709   guint32 scr1, scr2;
1710   guint64 scr, scr_adjusted, new_rate;
1711   guint64 scr_rate_n;
1712   guint64 scr_rate_d;
1713   guint avail = gst_adapter_available (demux->adapter);
1714
1715   GST_LOG ("parsing pack start");
1716
1717   if (G_UNLIKELY (avail < PACK_START_SIZE))
1718     goto need_more_data;
1719
1720   data = gst_adapter_map (demux->adapter, PACK_START_SIZE);
1721
1722   /* skip start code */
1723   data += 4;
1724
1725   scr1 = GST_READ_UINT32_BE (data);
1726   scr2 = GST_READ_UINT32_BE (data + 4);
1727
1728   /* fixed length to begin with, start code and two scr values */
1729   length = 8 + 4;
1730
1731   /* start parsing the stream */
1732   if ((*data & 0xc0) == 0x40) {
1733     guint32 scr_ext;
1734     guint32 next32;
1735     guint8 stuffing_bytes;
1736
1737     GST_LOG ("Found MPEG2 stream");
1738     demux->is_mpeg2_pack = TRUE;
1739
1740     /* mpeg2 has more data */
1741     length += 2;
1742
1743     /* :2=01 ! scr:3 ! marker:1==1 ! scr:15 ! marker:1==1 ! scr:15 */
1744
1745     /* check markers */
1746     if (G_UNLIKELY ((scr1 & 0xc4000400) != 0x44000400))
1747       goto lost_sync;
1748
1749     scr = ((guint64) scr1 & 0x38000000) << 3;
1750     scr |= ((guint64) scr1 & 0x03fff800) << 4;
1751     scr |= ((guint64) scr1 & 0x000003ff) << 5;
1752     scr |= ((guint64) scr2 & 0xf8000000) >> 27;
1753
1754     /* marker:1==1 ! scr_ext:9 ! marker:1==1 */
1755     if (G_UNLIKELY ((scr2 & 0x04010000) != 0x04010000))
1756       goto lost_sync;
1757
1758     scr_ext = (scr2 & 0x03fe0000) >> 17;
1759     /* We keep the offset of this scr */
1760     demux->cur_scr_offset = demux->adapter_offset + 12;
1761
1762     GST_LOG_OBJECT (demux, "SCR: 0x%08" G_GINT64_MODIFIER "x SCRE: 0x%08x",
1763         scr, scr_ext);
1764
1765     if (scr_ext) {
1766       scr = (scr * 300 + scr_ext % 300) / 300;
1767     }
1768     /* SCR has been converted into units of 90Khz ticks to make it comparable
1769        to DTS/PTS, that also implies 1 tick rounding error */
1770     data += 6;
1771     /* PMR:22 ! :2==11 ! reserved:5 ! stuffing_len:3 */
1772     next32 = GST_READ_UINT32_BE (data);
1773     if (G_UNLIKELY ((next32 & 0x00000300) != 0x00000300))
1774       goto lost_sync;
1775
1776     new_rate = (next32 & 0xfffffc00) >> 10;
1777
1778     stuffing_bytes = (next32 & 0x07);
1779     GST_LOG_OBJECT (demux, "stuffing bytes: %d", stuffing_bytes);
1780
1781     data += 4;
1782     length += stuffing_bytes;
1783     while (stuffing_bytes--) {
1784       if (*data++ != 0xff)
1785         goto lost_sync;
1786     }
1787   } else {
1788     GST_DEBUG ("Found MPEG1 stream");
1789     demux->is_mpeg2_pack = FALSE;
1790
1791     /* check markers */
1792     if (G_UNLIKELY ((scr1 & 0xf1000100) != 0x21000100))
1793       goto lost_sync;
1794
1795     if (G_UNLIKELY ((scr2 & 0x01800001) != 0x01800001))
1796       goto lost_sync;
1797
1798     /* :4=0010 ! scr:3 ! marker:1==1 ! scr:15 ! marker:1==1 ! scr:15 ! marker:1==1 */
1799     scr = ((guint64) scr1 & 0x0e000000) << 5;
1800     scr |= ((guint64) scr1 & 0x00fffe00) << 6;
1801     scr |= ((guint64) scr1 & 0x000000ff) << 7;
1802     scr |= ((guint64) scr2 & 0xfe000000) >> 25;
1803
1804     /* We keep the offset of this scr */
1805     demux->cur_scr_offset = demux->adapter_offset + 8;
1806
1807     /* marker:1==1 ! mux_rate:22 ! marker:1==1 */
1808     new_rate = (scr2 & 0x007ffffe) >> 1;
1809
1810     data += 8;
1811   }
1812
1813   if (demux->ignore_scr) {
1814     /* update only first/current_scr with raw scr value to start streaming
1815      * after parsing 2 seconds long data with no-more-pad */
1816     if (demux->first_scr == G_MAXUINT64) {
1817       demux->first_scr = scr;
1818       demux->first_scr_offset = demux->cur_scr_offset;
1819     }
1820
1821     demux->current_scr = scr;
1822
1823     goto out;
1824   }
1825
1826   new_rate *= MPEG_MUX_RATE_MULT;
1827
1828   /* scr adjusted is the new scr found + the colected adjustment */
1829   scr_adjusted = scr + demux->scr_adjust;
1830
1831   GST_LOG_OBJECT (demux,
1832       "SCR: %" G_GINT64_FORMAT " (%" G_GINT64_FORMAT "), mux_rate %"
1833       G_GINT64_FORMAT ", GStreamer Time:%" GST_TIME_FORMAT,
1834       scr, scr_adjusted, new_rate,
1835       GST_TIME_ARGS (MPEGTIME_TO_GSTTIME ((guint64) scr)));
1836
1837   /* keep the first src in order to calculate delta time */
1838   if (G_UNLIKELY (demux->first_scr == G_MAXUINT64)) {
1839     gint64 diff;
1840
1841     demux->first_scr = scr;
1842     demux->first_scr_offset = demux->cur_scr_offset;
1843     demux->base_time = MPEGTIME_TO_GSTTIME (demux->first_scr);
1844     GST_DEBUG_OBJECT (demux, "determined base_time %" GST_TIME_FORMAT,
1845         GST_TIME_ARGS (demux->base_time));
1846     /* at begin consider the new_rate as the scr rate, bytes/clock ticks */
1847     scr_rate_n = new_rate;
1848     scr_rate_d = CLOCK_FREQ;
1849     /* our SCR timeline might have offset wrt upstream timeline */
1850     if (demux->sink_segment.format == GST_FORMAT_TIME) {
1851       if (demux->sink_segment.start > demux->base_time)
1852         diff = -(demux->sink_segment.start - demux->base_time);
1853       else
1854         diff = demux->base_time - demux->sink_segment.start;
1855       if (diff > GST_SECOND) {
1856         GST_DEBUG_OBJECT (demux, "diff of %" GST_TIME_FORMAT
1857             " wrt upstream start %" GST_TIME_FORMAT "; adjusting base",
1858             GST_TIME_ARGS (diff), GST_TIME_ARGS (demux->sink_segment.start));
1859         demux->base_time += diff;
1860       }
1861     }
1862   } else if (G_LIKELY (demux->first_scr_offset != demux->cur_scr_offset)) {
1863     /* estimate byte rate related to the SCR */
1864     scr_rate_n = demux->cur_scr_offset - demux->first_scr_offset;
1865     scr_rate_d = scr_adjusted - demux->first_scr;
1866   } else {
1867     scr_rate_n = demux->scr_rate_n;
1868     scr_rate_d = demux->scr_rate_d;
1869   }
1870
1871   GST_LOG_OBJECT (demux, "%s mode scr: %" G_GUINT64_FORMAT " at %"
1872       G_GUINT64_FORMAT ", first scr: %" G_GUINT64_FORMAT
1873       " at %" G_GUINT64_FORMAT ", scr rate: %" G_GUINT64_FORMAT
1874       "/%" G_GUINT64_FORMAT "(%f)",
1875       ((demux->sink_segment.rate >= 0.0) ? "forward" : "backward"),
1876       scr, demux->cur_scr_offset,
1877       demux->first_scr, demux->first_scr_offset,
1878       scr_rate_n, scr_rate_d, (float) scr_rate_n / scr_rate_d);
1879
1880   /* adjustment of the SCR */
1881   if (G_LIKELY (demux->current_scr != G_MAXUINT64)) {
1882     guint64 diff;
1883     guint64 old_scr, old_mux_rate, bss, adjust = 0;
1884
1885     /* keep SCR of the previous packet */
1886     old_scr = demux->current_scr;
1887     old_mux_rate = demux->mux_rate;
1888
1889     /* Bytes since SCR is the amount we placed in the adapter since then
1890      * (demux->bytes_since_scr) minus the amount remaining in the adapter,
1891      * clamped to >= 0 */
1892     bss = MAX (0, (gint) (demux->bytes_since_scr - avail));
1893
1894     /* estimate the new SCR using the previous one according the notes
1895        on point 2.5.2.2 of the ISO/IEC 13818-1 document */
1896     if (old_mux_rate != 0)
1897       adjust = (bss * CLOCK_FREQ) / old_mux_rate;
1898
1899     if (demux->sink_segment.rate >= 0.0)
1900       demux->next_scr = old_scr + adjust;
1901     else
1902       demux->next_scr = old_scr - adjust;
1903
1904     GST_LOG_OBJECT (demux,
1905         "bss: %" G_GUINT64_FORMAT ", next_scr: %" G_GUINT64_FORMAT
1906         ", old_scr: %" G_GUINT64_FORMAT ", scr: %" G_GUINT64_FORMAT,
1907         bss, demux->next_scr, old_scr, scr_adjusted);
1908
1909     /* calculate the absolute deference between the last scr and
1910        the new one */
1911     if (G_UNLIKELY (old_scr > scr_adjusted))
1912       diff = old_scr - scr_adjusted;
1913     else
1914       diff = scr_adjusted - old_scr;
1915
1916     /* if the difference is more than 1 second we need to reconfigure
1917        adjustment */
1918     if (G_UNLIKELY (diff > CLOCK_FREQ)) {
1919       demux->scr_adjust = demux->next_scr - scr;
1920       GST_LOG_OBJECT (demux, "discont found, diff: %" G_GINT64_FORMAT
1921           ", adjust %" G_GINT64_FORMAT, diff, demux->scr_adjust);
1922       scr_adjusted = demux->next_scr;
1923       /* don't update rate estimation on disconts */
1924       scr_rate_n = demux->scr_rate_n;
1925       scr_rate_d = demux->scr_rate_d;
1926     } else {
1927       demux->next_scr = scr_adjusted;
1928     }
1929   }
1930
1931   /* update the current_scr and rate members */
1932   demux->mux_rate = new_rate;
1933   demux->current_scr = scr_adjusted;
1934   demux->scr_rate_n = scr_rate_n;
1935   demux->scr_rate_d = scr_rate_d;
1936
1937   /* Reset the bytes_since_scr value to count the data remaining in the
1938    * adapter */
1939   demux->bytes_since_scr = avail;
1940
1941   /* Now check for all streams if they're behind the new SCR and if
1942    * they are then move them forward to the SCR position */
1943   gst_ps_demux_send_gap_updates (demux,
1944       MPEGTIME_TO_GSTTIME (demux->current_scr - demux->first_scr));
1945
1946 out:
1947   gst_adapter_unmap (demux->adapter);
1948   gst_adapter_flush (demux->adapter, length);
1949   ADAPTER_OFFSET_FLUSH (length);
1950
1951   return GST_FLOW_OK;
1952
1953 lost_sync:
1954   {
1955     GST_DEBUG_OBJECT (demux, "lost sync");
1956     gst_adapter_unmap (demux->adapter);
1957     return GST_FLOW_LOST_SYNC;
1958   }
1959 need_more_data:
1960   {
1961     GST_DEBUG_OBJECT (demux, "need more data");
1962     return GST_FLOW_NEED_MORE_DATA;
1963   }
1964 }
1965
1966 /* ISO/IEC 13818-1:
1967  * system_header () {
1968  *     system_header_start_code                          32  bslbf  -+
1969  *     header_length                                     16  uimsbf  |
1970  *     marker_bit                                         1  bslbf   |
1971  *     rate_bound                                        22  uimsbf  |
1972  *     marker_bit                                         1  bslbf   |
1973  *     audio_bound                                        6  uimsbf  |
1974  *     fixed_flag                                         1  bslbf   |
1975  *     CSPS_flag                                          1  bslbf   | 96 bits
1976  *     system_audio_lock_flag                             1  bslbf   |
1977  *     system_video_lock_flag                             1  bslbf   |
1978  *     marker_bit                                         1  bslbf   |
1979  *     video_bound                                        5  uimsbf  |
1980  *     packet_rate_restriction_flag                       1  bslbf   |
1981  *     reserved_bits                                      7  bslbf  -+
1982  *     while (nextbits () = = '1') {
1983  *         stream_id                                      8  uimsbf -+
1984  *         '11'                                           2  bslbf   | 24 bits
1985  *         P-STD_buffer_bound_scale                       1  bslbf   |
1986  *         P-STD_buffer_size_bound                       13  uimsbf -+
1987  *     }
1988  * }
1989  * 96 bits = 12 bytes, 24 bits = 3 bytes.
1990  */
1991
1992 static GstFlowReturn
1993 gst_ps_demux_parse_sys_head (GstPsDemux * demux)
1994 {
1995   guint16 length;
1996   const guint8 *data;
1997 #ifndef GST_DISABLE_GST_DEBUG
1998   gboolean csps;
1999 #endif
2000
2001   if (gst_adapter_available (demux->adapter) < 6)
2002     goto need_more_data;
2003
2004   /* start code + length */
2005   data = gst_adapter_map (demux->adapter, 6);
2006
2007   /* skip start code */
2008   data += 4;
2009
2010   length = GST_READ_UINT16_BE (data);
2011   GST_DEBUG_OBJECT (demux, "length %d", length);
2012
2013   length += 6;
2014
2015   gst_adapter_unmap (demux->adapter);
2016   if (gst_adapter_available (demux->adapter) < length)
2017     goto need_more_data;
2018
2019   data = gst_adapter_map (demux->adapter, length);
2020
2021   /* skip start code and length */
2022   data += 6;
2023
2024   /* marker:1==1 ! rate_bound:22 | marker:1==1 */
2025   if ((*data & 0x80) != 0x80)
2026     goto marker_expected;
2027
2028   {
2029     guint32 rate_bound;
2030
2031     if ((data[2] & 0x01) != 0x01)
2032       goto marker_expected;
2033
2034     rate_bound = ((guint32) data[0] & 0x7f) << 15;
2035     rate_bound |= ((guint32) data[1]) << 7;
2036     rate_bound |= ((guint32) data[2] & 0xfe) >> 1;
2037     rate_bound *= MPEG_MUX_RATE_MULT;
2038
2039     GST_DEBUG_OBJECT (demux, "rate bound %u", rate_bound);
2040
2041     data += 3;
2042   }
2043
2044   /* audio_bound:6==1 ! fixed:1 | constrained:1 */
2045   {
2046 #ifndef GST_DISABLE_GST_DEBUG
2047     guint8 audio_bound;
2048     gboolean fixed;
2049
2050     /* max number of simultaneous audio streams active */
2051     audio_bound = (data[0] & 0xfc) >> 2;
2052     /* fixed or variable bitrate */
2053     fixed = (data[0] & 0x02) == 0x02;
2054     /* meeting constraints */
2055     csps = (data[0] & 0x01) == 0x01;
2056
2057     GST_DEBUG_OBJECT (demux, "audio_bound %d, fixed %d, constrained %d",
2058         audio_bound, fixed, csps);
2059 #endif
2060     data += 1;
2061   }
2062
2063   /* audio_lock:1 | video_lock:1 | marker:1==1 | video_bound:5 */
2064   {
2065 #ifndef GST_DISABLE_GST_DEBUG
2066     gboolean audio_lock;
2067     gboolean video_lock;
2068     guint8 video_bound;
2069
2070     audio_lock = (data[0] & 0x80) == 0x80;
2071     video_lock = (data[0] & 0x40) == 0x40;
2072 #endif
2073
2074     if ((data[0] & 0x20) != 0x20)
2075       goto marker_expected;
2076
2077 #ifndef GST_DISABLE_GST_DEBUG
2078     /* max number of simultaneous video streams active */
2079     video_bound = (data[0] & 0x1f);
2080
2081     GST_DEBUG_OBJECT (demux, "audio_lock %d, video_lock %d, video_bound %d",
2082         audio_lock, video_lock, video_bound);
2083 #endif
2084     data += 1;
2085   }
2086
2087   /* packet_rate_restriction:1 | reserved:7==0x7F */
2088   {
2089 #ifndef GST_DISABLE_GST_DEBUG
2090     gboolean packet_rate_restriction;
2091 #endif
2092     if ((data[0] & 0x7f) != 0x7f)
2093       goto marker_expected;
2094 #ifndef GST_DISABLE_GST_DEBUG
2095     /* only valid if csps is set */
2096     if (csps) {
2097       packet_rate_restriction = (data[0] & 0x80) == 0x80;
2098
2099       GST_DEBUG_OBJECT (demux, "packet_rate_restriction %d",
2100           packet_rate_restriction);
2101     }
2102 #endif
2103   }
2104   data += 1;
2105
2106   {
2107     gint stream_count = (length - 12) / 3;
2108     gint i;
2109
2110     GST_DEBUG_OBJECT (demux, "number of streams: %d ", stream_count);
2111
2112     for (i = 0; i < stream_count; i++) {
2113       guint8 stream_id;
2114 #ifndef GST_DISABLE_GST_DEBUG
2115       gboolean STD_buffer_bound_scale;
2116       guint16 STD_buffer_size_bound;
2117       guint32 buf_byte_size_bound;
2118 #endif
2119       stream_id = *data++;
2120       if (!(stream_id & 0x80))
2121         goto sys_len_error;
2122
2123       /* check marker bits */
2124       if ((*data & 0xC0) != 0xC0)
2125         goto no_placeholder_bits;
2126 #ifndef GST_DISABLE_GST_DEBUG
2127       STD_buffer_bound_scale = *data & 0x20;
2128       STD_buffer_size_bound = ((guint16) (*data++ & 0x1F)) << 8;
2129       STD_buffer_size_bound |= *data++;
2130
2131       if (STD_buffer_bound_scale == 0) {
2132         buf_byte_size_bound = STD_buffer_size_bound * 128;
2133       } else {
2134         buf_byte_size_bound = STD_buffer_size_bound * 1024;
2135       }
2136
2137       GST_DEBUG_OBJECT (demux, "STD_buffer_bound_scale %d",
2138           STD_buffer_bound_scale);
2139       GST_DEBUG_OBJECT (demux, "STD_buffer_size_bound %d or %d bytes",
2140           STD_buffer_size_bound, buf_byte_size_bound);
2141 #endif
2142     }
2143   }
2144
2145   gst_adapter_unmap (demux->adapter);
2146   gst_adapter_flush (demux->adapter, length);
2147   ADAPTER_OFFSET_FLUSH (length);
2148   return GST_FLOW_OK;
2149
2150   /* ERRORS */
2151 marker_expected:
2152   {
2153     GST_DEBUG_OBJECT (demux, "expecting marker");
2154     gst_adapter_unmap (demux->adapter);
2155     return GST_FLOW_LOST_SYNC;
2156   }
2157 no_placeholder_bits:
2158   {
2159     GST_DEBUG_OBJECT (demux, "expecting placeholder bit values"
2160         " '11' after stream id");
2161     gst_adapter_unmap (demux->adapter);
2162     return GST_FLOW_LOST_SYNC;
2163   }
2164 sys_len_error:
2165   {
2166     GST_DEBUG_OBJECT (demux, "error in system header length");
2167     gst_adapter_unmap (demux->adapter);
2168     return GST_FLOW_LOST_SYNC;
2169   }
2170 need_more_data:
2171   {
2172     GST_DEBUG_OBJECT (demux, "need more data");
2173     gst_adapter_unmap (demux->adapter);
2174     return GST_FLOW_NEED_MORE_DATA;
2175   }
2176 }
2177
2178 static GstFlowReturn
2179 gst_ps_demux_parse_psm (GstPsDemux * demux)
2180 {
2181   guint16 psm_length, info_length = 0, es_map_length = 0;
2182   guint8 psm_version = 0;
2183   GstByteReader br;
2184 #ifndef GST_DISABLE_GST_DEBUG
2185   gboolean applicable;
2186 #endif
2187
2188   /* Need at least 6 bytes for start code + length */
2189   if (gst_adapter_available (demux->adapter) < 6)
2190     goto need_more_data;
2191
2192   {
2193     const guint8 *data;
2194
2195     /* start code + length */
2196     data = gst_adapter_map (demux->adapter, 6);
2197     /* skip start code */
2198     data += 4;
2199     psm_length = GST_READ_UINT16_BE (data);
2200     GST_DEBUG_OBJECT (demux, "PSM length %u", psm_length);
2201
2202     if (G_UNLIKELY (psm_length > 0x3FA))
2203       goto psm_len_error;
2204     psm_length += 6;            /* Add start code + size to length */
2205
2206     gst_adapter_unmap (demux->adapter);
2207
2208     if (gst_adapter_available (demux->adapter) < psm_length)
2209       goto need_more_data;
2210
2211     data = gst_adapter_map (demux->adapter, psm_length);
2212
2213     gst_byte_reader_init (&br, data, psm_length);
2214   }
2215
2216   /* skip start code and length */
2217   if (!gst_byte_reader_skip (&br, 6))
2218     goto fail_invalid;
2219
2220   /* Read PSM applicable bit together with version */
2221   if (!gst_byte_reader_get_uint8 (&br, &psm_version))
2222     goto fail_invalid;
2223 #ifndef GST_DISABLE_GST_DEBUG
2224   applicable = (psm_version & 0x80) >> 7;
2225 #endif
2226   psm_version &= 0x1F;
2227   GST_DEBUG_OBJECT (demux, "PSM version %u (applicable now %u)", psm_version,
2228       applicable);
2229
2230   /* Jump over the next byte (marker bit) */
2231   if (!gst_byte_reader_skip (&br, 1))
2232     goto fail_invalid;
2233
2234   /* Read PS info length */
2235   if (!gst_byte_reader_get_uint16_be (&br, &info_length))
2236     goto fail_invalid;
2237   GST_DEBUG_OBJECT (demux, "PS info length %u bytes", info_length);
2238   /* Skip the PS info, we don't use it */
2239   if (!gst_byte_reader_skip (&br, info_length))
2240     goto fail_invalid;
2241
2242   /* Read ES map length */
2243   if (!gst_byte_reader_get_uint16_be (&br, &es_map_length))
2244     goto fail_invalid;
2245   GST_DEBUG_OBJECT (demux, "ES map length %u bytes", es_map_length);
2246
2247   /* Now read the ES map */
2248   {
2249     GstByteReader es_map_br;
2250     if (!gst_byte_reader_get_sub_reader (&br, &es_map_br, es_map_length))
2251       goto fail_invalid;
2252
2253     while (gst_byte_reader_get_remaining (&es_map_br) >= 4) {
2254       guint8 stream_type = 0, stream_id = 0;
2255       guint16 stream_info_length = 0;
2256
2257       if (!gst_byte_reader_get_uint8 (&es_map_br, &stream_type) ||
2258           !gst_byte_reader_get_uint8 (&es_map_br, &stream_id) ||
2259           !gst_byte_reader_get_uint16_be (&es_map_br, &stream_info_length))
2260         break;
2261
2262       GST_DEBUG_OBJECT (demux,
2263           "Stream type %02X with id %02X and %u bytes info", stream_type,
2264           stream_id, stream_info_length);
2265
2266       if (G_LIKELY (stream_id != 0xbd))
2267         demux->psm[stream_id] = stream_type;
2268       else {
2269         /* Ignore stream type for private_stream_1 and discover it looking at
2270          * the stream data.
2271          * Fixes demuxing some clips with lpcm that was wrongly declared as
2272          * mpeg audio */
2273         GST_DEBUG_OBJECT (demux, "stream type for private_stream_1 ignored");
2274       }
2275
2276       /* FIXME: We could use the descriptors instead of skipping them */
2277       if (!gst_byte_reader_skip (&es_map_br, stream_info_length))
2278         break;
2279     }
2280   }
2281   /* We ignore the 4-byte CRC at the end */
2282
2283   gst_adapter_unmap (demux->adapter);
2284   gst_adapter_flush (demux->adapter, psm_length);
2285   ADAPTER_OFFSET_FLUSH (psm_length);
2286   return GST_FLOW_OK;
2287
2288 fail_invalid:
2289   GST_DEBUG_OBJECT (demux, "Failed to parse PSM. Skipping");
2290   gst_adapter_unmap (demux->adapter);
2291   gst_adapter_flush (demux->adapter, psm_length);
2292   ADAPTER_OFFSET_FLUSH (psm_length);
2293   return GST_FLOW_LOST_SYNC;
2294 psm_len_error:
2295   {
2296     GST_DEBUG_OBJECT (demux, "error in PSM length");
2297     gst_adapter_unmap (demux->adapter);
2298     return GST_FLOW_LOST_SYNC;
2299   }
2300 need_more_data:
2301   {
2302     GST_DEBUG_OBJECT (demux, "need more data");
2303     return GST_FLOW_NEED_MORE_DATA;
2304   }
2305 }
2306
2307 static void
2308 gst_ps_demux_resync_cb (GstPESFilter * filter, GstPsDemux * demux)
2309 {
2310 }
2311
2312 static GstFlowReturn
2313 gst_ps_demux_data_cb (GstPESFilter * filter, gboolean first,
2314     GstBuffer * buffer, GstPsDemux * demux)
2315 {
2316   GstBuffer *out_buf;
2317   GstFlowReturn ret = GST_FLOW_OK;
2318   gint stream_type;
2319   guint32 start_code;
2320   guint8 id;
2321   GstMapInfo map;
2322   gsize datalen;
2323   guint offset = 0;
2324   gst_buffer_map (buffer, &map, GST_MAP_READ);
2325   datalen = map.size;
2326   start_code = filter->start_code;
2327   id = filter->id;
2328   if (first) {
2329     gint layer = 0;
2330     /* find the stream type */
2331     stream_type = demux->psm[id];
2332     if (stream_type == -1) {
2333       /* no stream type, if PS1, get the new id */
2334       if (start_code == ID_PRIVATE_STREAM_1 && datalen >= 2) {
2335         /* VDR writes A52 streams without any header bytes
2336          * (see ftp://ftp.mplayerhq.hu/MPlayer/samples/MPEG-VOB/vdr-AC3) */
2337         if (datalen >= 4) {
2338           guint hdr = GST_READ_UINT32_BE (map.data);
2339           if (G_UNLIKELY ((hdr & 0xffff0000) == AC3_SYNC_WORD)) {
2340             id = 0x80;
2341             stream_type = demux->psm[id] = ST_GST_AUDIO_RAWA52;
2342             GST_DEBUG_OBJECT (demux, "Found VDR raw A52 stream");
2343           }
2344         }
2345
2346         if (G_LIKELY (stream_type == -1)) {
2347           /* new id is in the first byte */
2348           id = map.data[offset++];
2349           datalen--;
2350           /* and remap */
2351           stream_type = demux->psm[id];
2352           /* Now, if it's a subpicture stream - no more, otherwise
2353            * take the first byte too, since it's the frame count in audio
2354            * streams and our backwards compat convention is to strip it off */
2355           if (stream_type != ST_PS_DVD_SUBPICTURE) {
2356             /* Number of audio frames in this packet */
2357 #ifndef GST_DISABLE_GST_DEBUG
2358             guint8 nframes;
2359             nframes = map.data[offset];
2360             GST_LOG_OBJECT (demux, "private type 0x%02x, %d frames", id,
2361                 nframes);
2362 #endif
2363             offset++;
2364             datalen--;
2365           } else {
2366             GST_LOG_OBJECT (demux, "private type 0x%02x, stream type %d",
2367                 id, stream_type);
2368           }
2369         }
2370       }
2371       if (stream_type == -1)
2372         goto unknown_stream_type;
2373     } else if (stream_type == ST_AUDIO_MPEG1 || stream_type == ST_AUDIO_MPEG2) {
2374       if (datalen >= 2) {
2375         guint hdr = GST_READ_UINT16_BE (map.data);
2376         if ((hdr & 0xfff0) == 0xfff0) {
2377           switch (hdr & 0x06) {
2378             case 0x6:
2379               layer = 1;
2380               break;
2381             case 0x4:
2382               layer = 2;
2383               break;
2384             case 0x2:
2385               layer = 3;
2386               break;
2387             default:
2388               GST_WARNING_OBJECT (demux, "unknown mpeg audio layer");
2389           }
2390         }
2391       }
2392     }
2393
2394     if (filter->pts != -1) {
2395       demux->next_pts = filter->pts + demux->scr_adjust;
2396       GST_LOG_OBJECT (demux, "stream 0x%02x PTS = orig %" G_GUINT64_FORMAT
2397           " (%" G_GUINT64_FORMAT ")", id, filter->pts, demux->next_pts);
2398     } else
2399       demux->next_pts = G_MAXUINT64;
2400     if (filter->dts != -1) {
2401       demux->next_dts = filter->dts + demux->scr_adjust;
2402       GST_LOG_OBJECT (demux, "stream 0x%02x DTS = orig %" G_GUINT64_FORMAT
2403           " (%" G_GUINT64_FORMAT ")", id, filter->dts, demux->next_dts);
2404     } else {
2405       demux->next_dts = demux->next_pts;
2406     }
2407
2408     demux->current_stream =
2409         gst_ps_demux_get_stream (demux, id, stream_type, layer);
2410   }
2411
2412   if (G_UNLIKELY (demux->current_stream == NULL)) {
2413     GST_DEBUG_OBJECT (demux, "Dropping buffer for unknown stream id 0x%02x",
2414         id);
2415     goto done;
2416   }
2417
2418   /* After 2 seconds of bitstream emit no more pads */
2419   if (demux->need_no_more_pads
2420       && (demux->current_scr - demux->first_scr) > 2 * CLOCK_FREQ) {
2421     GST_DEBUG_OBJECT (demux, "no more pads, notifying");
2422     gst_element_no_more_pads (GST_ELEMENT_CAST (demux));
2423     demux->need_no_more_pads = FALSE;
2424   }
2425
2426   /* If the stream is not-linked, don't bother creating a sub-buffer
2427    * to send to it, unless we're processing a discont (which resets
2428    * the not-linked status and tries again */
2429   if (demux->current_stream->discont) {
2430     GST_DEBUG_OBJECT (demux, "stream is discont");
2431     demux->current_stream->notlinked = FALSE;
2432   }
2433
2434   if (demux->current_stream->notlinked == FALSE) {
2435     out_buf =
2436         gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, offset, datalen);
2437     ret = gst_ps_demux_send_data (demux, demux->current_stream, out_buf);
2438     if (ret == GST_FLOW_NOT_LINKED) {
2439       demux->current_stream->notlinked = TRUE;
2440     }
2441   }
2442
2443 done:
2444   gst_buffer_unmap (buffer, &map);
2445   gst_buffer_unref (buffer);
2446   return ret;
2447   /* ERRORS */
2448 unknown_stream_type:
2449   {
2450     GST_DEBUG_OBJECT (demux, "unknown stream type %02x", id);
2451     ret = GST_FLOW_OK;
2452     goto done;
2453   }
2454 }
2455
2456 static gboolean
2457 gst_ps_demux_resync (GstPsDemux * demux, gboolean save)
2458 {
2459   const guint8 *data;
2460   gint avail;
2461   guint32 code;
2462   gint offset;
2463   gboolean found;
2464   avail = gst_adapter_available (demux->adapter);
2465   if (G_UNLIKELY (avail < 4))
2466     goto need_data;
2467   /* Common case, read 4 bytes an check it */
2468   data = gst_adapter_map (demux->adapter, 4);
2469   /* read currect code */
2470   code = GST_READ_UINT32_BE (data);
2471   /* The common case is that the sync code is at 0 bytes offset */
2472   if (G_LIKELY ((code & 0xffffff00) == 0x100L)) {
2473     GST_LOG_OBJECT (demux, "Found resync code %08x after 0 bytes", code);
2474     demux->last_sync_code = code;
2475     gst_adapter_unmap (demux->adapter);
2476     return TRUE;
2477   }
2478
2479   /* Otherwise, we are starting at byte 4 and we need to search
2480      the sync code in all available data in the adapter */
2481   offset = 4;
2482   if (offset >= avail)
2483     goto need_data;             /* Not enough data to find sync */
2484   data = gst_adapter_map (demux->adapter, avail);
2485   do {
2486     code = (code << 8) | data[offset++];
2487     found = (code & 0xffffff00) == 0x100L;
2488   } while (offset < avail && !found);
2489   gst_adapter_unmap (demux->adapter);
2490   if (!save || demux->sink_segment.rate >= 0.0) {
2491     GST_LOG_OBJECT (demux, "flushing %d bytes", offset - 4);
2492     /* forward playback, we can discard and flush the skipped bytes */
2493     gst_adapter_flush (demux->adapter, offset - 4);
2494     ADAPTER_OFFSET_FLUSH (offset - 4);
2495   } else {
2496     if (found) {
2497       GST_LOG_OBJECT (demux, "reverse saving %d bytes", offset - 4);
2498       /* reverse playback, we keep the flushed bytes and we will append them to
2499        * the next buffer in the chain function, which is the previous buffer in
2500        * the stream. */
2501       gst_adapter_push (demux->rev_adapter,
2502           gst_adapter_take_buffer (demux->adapter, offset - 4));
2503     } else {
2504       GST_LOG_OBJECT (demux, "reverse saving %d bytes", avail);
2505       /* nothing found, keep all bytes */
2506       gst_adapter_push (demux->rev_adapter,
2507           gst_adapter_take_buffer (demux->adapter, avail));
2508     }
2509   }
2510
2511   if (found) {
2512     GST_LOG_OBJECT (demux, "Found resync code %08x after %d bytes",
2513         code, offset - 4);
2514     demux->last_sync_code = code;
2515   } else {
2516     GST_LOG_OBJECT (demux, "No resync after skipping %d", offset);
2517   }
2518
2519   return found;
2520 need_data:
2521   {
2522     GST_LOG_OBJECT (demux, "we need more data for resync %d", avail);
2523     return FALSE;
2524   }
2525 }
2526
2527 static inline gboolean
2528 gst_ps_demux_is_pes_sync (guint32 sync)
2529 {
2530   return ((sync & 0xfc) == 0xbc) ||
2531       ((sync & 0xe0) == 0xc0) || ((sync & 0xf0) == 0xe0);
2532 }
2533
2534 static inline gboolean
2535 gst_ps_demux_scan_ts (GstPsDemux * demux, const guint8 * data,
2536     SCAN_MODE mode, guint64 * rts, const guint8 * end)
2537 {
2538   gboolean ret = FALSE;
2539   guint32 scr1, scr2;
2540   guint64 scr;
2541   guint64 pts, dts;
2542   guint32 code;
2543   guint16 len;
2544   /* read the 4 bytes for the sync code */
2545   code = GST_READ_UINT32_BE (data);
2546   if (G_LIKELY (code != ID_PS_PACK_START_CODE))
2547     goto beach;
2548   if (data + 12 > end)
2549     goto beach;
2550   /* skip start code */
2551   data += 4;
2552   scr1 = GST_READ_UINT32_BE (data);
2553   scr2 = GST_READ_UINT32_BE (data + 4);
2554   /* start parsing the stream */
2555   if ((*data & 0xc0) == 0x40) {
2556     /* MPEG-2 PACK header */
2557     guint32 scr_ext;
2558     guint32 next32;
2559     guint8 stuffing_bytes;
2560     /* :2=01 ! scr:3 ! marker:1==1 ! scr:15 ! marker:1==1 ! scr:15 */
2561     /* check markers */
2562     if ((scr1 & 0xc4000400) != 0x44000400)
2563       goto beach;
2564     scr = ((guint64) scr1 & 0x38000000) << 3;
2565     scr |= ((guint64) scr1 & 0x03fff800) << 4;
2566     scr |= ((guint64) scr1 & 0x000003ff) << 5;
2567     scr |= ((guint64) scr2 & 0xf8000000) >> 27;
2568     /* marker:1==1 ! scr_ext:9 ! marker:1==1 */
2569     if ((scr2 & 0x04010000) != 0x04010000)
2570       goto beach;
2571     scr_ext = (scr2 & 0x03fe0000) >> 17;
2572     if (scr_ext) {
2573       scr = (scr * 300 + scr_ext % 300) / 300;
2574     }
2575     /* SCR has been converted into units of 90Khz ticks to make it comparable
2576        to DTS/PTS, that also implies 1 tick rounding error */
2577     data += 6;
2578
2579     if (data + 4 > end)
2580       goto beach;
2581     /* PMR:22 ! :2==11 ! reserved:5 ! stuffing_len:3 */
2582     next32 = GST_READ_UINT32_BE (data);
2583     if ((next32 & 0x00000300) != 0x00000300)
2584       goto beach;
2585     stuffing_bytes = (next32 & 0x07);
2586     data += 4;
2587     if (data + stuffing_bytes > end)
2588       goto beach;
2589     while (stuffing_bytes--) {
2590       if (*data++ != 0xff)
2591         goto beach;
2592     }
2593   } else {
2594     /* MPEG-1 pack header */
2595     /* check markers */
2596     if ((scr1 & 0xf1000100) != 0x21000100)
2597       goto beach;
2598     if ((scr2 & 0x01800001) != 0x01800001)
2599       goto beach;
2600     /* :4=0010 ! scr:3 ! marker:1==1 ! scr:15 ! marker:1==1 ! scr:15 ! marker:1==1 */
2601     scr = ((guint64) scr1 & 0x0e000000) << 5;
2602     scr |= ((guint64) scr1 & 0x00fffe00) << 6;
2603     scr |= ((guint64) scr1 & 0x000000ff) << 7;
2604     scr |= ((guint64) scr2 & 0xfe000000) >> 25;
2605     data += 8;
2606   }
2607
2608   if (mode == SCAN_SCR) {
2609     *rts = scr;
2610     ret = TRUE;
2611     goto beach;
2612   }
2613
2614   /* Possible optional System header here */
2615   if (data + 8 > end)
2616     goto beach;
2617
2618   code = GST_READ_UINT32_BE (data);
2619   len = GST_READ_UINT16_BE (data + 4);
2620   if (code == ID_PS_SYSTEM_HEADER_START_CODE) {
2621     /* Found a system header, skip it */
2622     /* Check for sufficient data - system header, plus enough
2623      * left over for the PES packet header */
2624     if (data + 6 + len + 6 > end)
2625       return FALSE;
2626     data += len + 6;
2627     /* read the 4 bytes for the PES sync code */
2628     code = GST_READ_UINT32_BE (data);
2629     len = GST_READ_UINT16_BE (data + 4);
2630   }
2631
2632   /* Check we have enough data left for reading the PES packet */
2633   if (data + 6 + len > end)
2634     return FALSE;
2635   if (!gst_ps_demux_is_pes_sync (code))
2636     goto beach;
2637   switch (code) {
2638     case ID_PS_PROGRAM_STREAM_MAP:
2639     case ID_PRIVATE_STREAM_2:
2640     case ID_ECM_STREAM:
2641     case ID_EMM_STREAM:
2642     case ID_PROGRAM_STREAM_DIRECTORY:
2643     case ID_DSMCC_STREAM:
2644     case ID_ITU_TREC_H222_TYPE_E_STREAM:
2645     case ID_PADDING_STREAM:
2646       goto beach;
2647     default:
2648       break;
2649   }
2650
2651   /* skip sync code and size */
2652   data += 6;
2653   pts = dts = -1;
2654   /* stuffing bits, first two bits are '10' for mpeg2 pes so this code is
2655    * not triggered. */
2656   while (TRUE) {
2657     if (*data != 0xff)
2658       break;
2659     data++;
2660   }
2661
2662   /* STD buffer size, never for mpeg2 */
2663   if ((*data & 0xc0) == 0x40)
2664     data += 2;
2665   /* PTS but no DTS, never for mpeg2 */
2666   if ((*data & 0xf0) == 0x20) {
2667     READ_TS (data, pts, beach);
2668   }
2669   /* PTS and DTS, never for mpeg2 */
2670   else if ((*data & 0xf0) == 0x30) {
2671     READ_TS (data, pts, beach);
2672     READ_TS (data, dts, beach);
2673   } else if ((*data & 0xc0) == 0x80) {
2674     /* mpeg2 case */
2675     guchar flags;
2676     /* 2: '10'
2677      * 2: PES_scrambling_control
2678      * 1: PES_priority
2679      * 1: data_alignment_indicator
2680      * 1: copyright
2681      * 1: original_or_copy
2682      */
2683     flags = *data++;
2684     if ((flags & 0xc0) != 0x80)
2685       goto beach;
2686     /* 2: PTS_DTS_flags
2687      * 1: ESCR_flag
2688      * 1: ES_rate_flag
2689      * 1: DSM_trick_mode_flag
2690      * 1: additional_copy_info_flag
2691      * 1: PES_CRC_flag
2692      * 1: PES_extension_flag
2693      */
2694     flags = *data++;
2695     /* 8: PES_header_data_length */
2696     data++;
2697     /* only DTS: this is invalid */
2698     if ((flags & 0xc0) == 0x40)
2699       goto beach;
2700     /* check for PTS */
2701     if ((flags & 0x80)) {
2702       READ_TS (data, pts, beach);
2703     }
2704     /* check for DTS */
2705     if ((flags & 0x40)) {
2706       READ_TS (data, dts, beach);
2707     }
2708   }
2709
2710   if (mode == SCAN_DTS && dts != (guint64) - 1) {
2711     *rts = dts;
2712     ret = TRUE;
2713   }
2714
2715   if (mode == SCAN_PTS && pts != (guint64) - 1) {
2716     *rts = pts;
2717     ret = TRUE;
2718   }
2719 beach:
2720   return ret;
2721 }
2722
2723 static inline gboolean
2724 gst_ps_demux_scan_forward_ts (GstPsDemux * demux, guint64 * pos,
2725     SCAN_MODE mode, guint64 * rts, gint limit)
2726 {
2727   GstFlowReturn ret = GST_FLOW_OK;
2728   GstBuffer *buffer;
2729   guint64 offset = *pos;
2730   gboolean found = FALSE;
2731   guint64 ts = 0;
2732   guint scan_sz = (mode == SCAN_SCR ? SCAN_SCR_SZ : SCAN_PTS_SZ);
2733   guint cursor, to_read = BLOCK_SZ;
2734   guint end_scan;
2735   GstMapInfo map;
2736   do {
2737     /* Check we can get at least scan_sz bytes */
2738     if (offset + scan_sz > demux->sink_segment.stop)
2739       return FALSE;
2740     /* Don't go further than 'limit' bytes */
2741     if (limit && offset > *pos + limit)
2742       return FALSE;
2743     if (offset + to_read > demux->sink_segment.stop)
2744       to_read = demux->sink_segment.stop - offset;
2745     /* read some data */
2746     buffer = NULL;
2747     ret = gst_pad_pull_range (demux->sinkpad, offset, to_read, &buffer);
2748     if (G_UNLIKELY (ret != GST_FLOW_OK))
2749       return FALSE;
2750     gst_buffer_map (buffer, &map, GST_MAP_READ);
2751     /* may get a short buffer at the end of the file */
2752     if (G_UNLIKELY (map.size <= scan_sz)) {
2753       gst_buffer_unmap (buffer, &map);
2754       gst_buffer_unref (buffer);
2755       return FALSE;
2756     }
2757
2758     end_scan = map.size - scan_sz;
2759     /* scan the block */
2760     for (cursor = 0; !found && cursor <= end_scan; cursor++) {
2761       found = gst_ps_demux_scan_ts (demux, map.data + cursor, mode, &ts,
2762           map.data + map.size);
2763     }
2764
2765     /* done with the buffer, unref it */
2766     gst_buffer_unmap (buffer, &map);
2767     gst_buffer_unref (buffer);
2768     if (found) {
2769       *rts = ts;
2770       *pos = offset + cursor - 1;
2771     } else {
2772       offset += cursor;
2773     }
2774   } while (!found && offset < demux->sink_segment.stop);
2775   return found;
2776 }
2777
2778 static inline gboolean
2779 gst_ps_demux_scan_backward_ts (GstPsDemux * demux, guint64 * pos,
2780     SCAN_MODE mode, guint64 * rts, gint limit)
2781 {
2782   GstFlowReturn ret = GST_FLOW_OK;
2783   GstBuffer *buffer;
2784   guint64 offset = *pos;
2785   gboolean found = FALSE;
2786   guint64 ts = 0;
2787   guint scan_sz = (mode == SCAN_SCR ? SCAN_SCR_SZ : SCAN_PTS_SZ);
2788   guint cursor, to_read = BLOCK_SZ;
2789   guint start_scan;
2790   guint8 *data;
2791   GstMapInfo map;
2792   do {
2793     /* Check we have at least scan_sz bytes available */
2794     if (offset < scan_sz - 1)
2795       return FALSE;
2796     /* Don't go backward past the start or 'limit' bytes */
2797     if (limit && offset + limit < *pos)
2798       return FALSE;
2799     if (offset > BLOCK_SZ)
2800       offset -= BLOCK_SZ;
2801     else {
2802       to_read = offset + 1;
2803       offset = 0;
2804     }
2805     /* read some data */
2806     buffer = NULL;
2807     ret = gst_pad_pull_range (demux->sinkpad, offset, to_read, &buffer);
2808     if (G_UNLIKELY (ret != GST_FLOW_OK))
2809       return FALSE;
2810     gst_buffer_map (buffer, &map, GST_MAP_READ);
2811     /* may get a short buffer at the end of the file */
2812     if (G_UNLIKELY (map.size <= scan_sz)) {
2813       gst_buffer_unmap (buffer, &map);
2814       gst_buffer_unref (buffer);
2815       return FALSE;
2816     }
2817
2818     start_scan = map.size - scan_sz;
2819     data = map.data + start_scan;
2820     /* scan the block */
2821     for (cursor = (start_scan + 1); !found && cursor > 0; cursor--) {
2822       found = gst_ps_demux_scan_ts (demux, data--, mode, &ts,
2823           map.data + map.size);
2824     }
2825
2826     /* done with the buffer, unref it */
2827     gst_buffer_unmap (buffer, &map);
2828     gst_buffer_unref (buffer);
2829     if (found) {
2830       *rts = ts;
2831       *pos = offset + cursor;
2832     }
2833
2834   } while (!found && offset > 0);
2835   return found;
2836 }
2837
2838 static inline gboolean
2839 gst_ps_sink_get_duration (GstPsDemux * demux)
2840 {
2841   gboolean res = FALSE;
2842   GstPad *peer;
2843   GstFormat format = GST_FORMAT_BYTES;
2844   gint64 length = 0;
2845   guint64 offset;
2846   guint i;
2847   guint64 scr = 0;
2848   /* init the sink segment */
2849   gst_segment_init (&demux->sink_segment, format);
2850   /* get peer to figure out length */
2851   if ((peer = gst_pad_get_peer (demux->sinkpad)) == NULL)
2852     goto beach;
2853   res = gst_pad_query_duration (peer, format, &length);
2854   gst_object_unref (peer);
2855   if (!res || length <= 0)
2856     goto beach;
2857   GST_DEBUG_OBJECT (demux, "file length %" G_GINT64_FORMAT, length);
2858   /* update the sink segment */
2859   demux->sink_segment.stop = length;
2860   gst_segment_set_duration (&demux->sink_segment, format, length);
2861   gst_segment_set_position (&demux->sink_segment, format, 0);
2862   /* Scan for notorious SCR and PTS to calculate the duration */
2863   /* scan for first SCR in the stream */
2864   offset = demux->sink_segment.start;
2865   gst_ps_demux_scan_forward_ts (demux, &offset, SCAN_SCR,
2866       &demux->first_scr, DURATION_SCAN_LIMIT);
2867   GST_DEBUG_OBJECT (demux,
2868       "First SCR: %" G_GINT64_FORMAT " %" GST_TIME_FORMAT
2869       " in packet starting at %" G_GUINT64_FORMAT, demux->first_scr,
2870       GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (demux->first_scr)), offset);
2871   demux->first_scr_offset = offset;
2872   /* scan for last SCR in the stream */
2873   offset = demux->sink_segment.stop;
2874   gst_ps_demux_scan_backward_ts (demux, &offset, SCAN_SCR,
2875       &demux->last_scr, DURATION_SCAN_LIMIT);
2876   GST_DEBUG_OBJECT (demux,
2877       "Last SCR: %" G_GINT64_FORMAT " %" GST_TIME_FORMAT
2878       " in packet starting at %" G_GUINT64_FORMAT, demux->last_scr,
2879       GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (demux->last_scr)), offset);
2880   demux->last_scr_offset = offset;
2881   /* scan for first PTS in the stream */
2882   offset = demux->sink_segment.start;
2883   gst_ps_demux_scan_forward_ts (demux, &offset, SCAN_PTS,
2884       &demux->first_pts, DURATION_SCAN_LIMIT);
2885   GST_DEBUG_OBJECT (demux,
2886       "First PTS: %" G_GINT64_FORMAT " %" GST_TIME_FORMAT
2887       " in packet starting at %" G_GUINT64_FORMAT, demux->first_pts,
2888       GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (demux->first_pts)), offset);
2889   if (demux->first_pts != G_MAXUINT64) {
2890     /* scan for last PTS in the stream */
2891     offset = demux->sink_segment.stop;
2892     gst_ps_demux_scan_backward_ts (demux, &offset, SCAN_PTS,
2893         &demux->last_pts, DURATION_SCAN_LIMIT);
2894     GST_DEBUG_OBJECT (demux,
2895         "Last PTS: %" G_GINT64_FORMAT " %" GST_TIME_FORMAT
2896         " in packet starting at %" G_GUINT64_FORMAT, demux->last_pts,
2897         GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (demux->last_pts)), offset);
2898   }
2899   /* Detect wrong SCR values */
2900   if (demux->first_scr > demux->last_scr) {
2901     GST_DEBUG_OBJECT (demux, "Wrong SCR values detected, searching for "
2902         "a better first SCR value");
2903     offset = demux->first_scr_offset;
2904     for (i = 0; i < 10; i++) {
2905       offset++;
2906       gst_ps_demux_scan_forward_ts (demux, &offset, SCAN_SCR, &scr, 0);
2907       if (scr < demux->last_scr) {
2908         demux->first_scr = scr;
2909         demux->first_scr_offset = offset;
2910         /* Start demuxing from the right place */
2911         demux->sink_segment.position = offset;
2912         GST_DEBUG_OBJECT (demux, "Replaced First SCR: %" G_GINT64_FORMAT
2913             " %" GST_TIME_FORMAT " in packet starting at %"
2914             G_GUINT64_FORMAT, demux->first_scr,
2915             GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (demux->first_scr)), offset);
2916         break;
2917       }
2918     }
2919   }
2920   /* Set the base_time and avg rate */
2921   demux->base_time = MPEGTIME_TO_GSTTIME (demux->first_scr);
2922   demux->scr_rate_n = demux->last_scr_offset - demux->first_scr_offset;
2923   demux->scr_rate_d = demux->last_scr - demux->first_scr;
2924   if (G_LIKELY (demux->first_pts != G_MAXUINT64 &&
2925           demux->last_pts != G_MAXUINT64)) {
2926     /* update the src segment */
2927     demux->src_segment.format = GST_FORMAT_TIME;
2928     demux->src_segment.start =
2929         MPEGTIME_TO_GSTTIME (demux->first_pts) - demux->base_time;
2930     demux->src_segment.stop = -1;
2931     gst_segment_set_duration (&demux->src_segment, GST_FORMAT_TIME,
2932         MPEGTIME_TO_GSTTIME (demux->last_pts - demux->first_pts));
2933     gst_segment_set_position (&demux->src_segment, GST_FORMAT_TIME,
2934         demux->src_segment.start);
2935   }
2936   GST_INFO_OBJECT (demux, "sink segment configured %" GST_SEGMENT_FORMAT,
2937       &demux->sink_segment);
2938   GST_INFO_OBJECT (demux, "src segment configured %" GST_SEGMENT_FORMAT,
2939       &demux->src_segment);
2940   res = TRUE;
2941 beach:
2942   return res;
2943 }
2944
2945 static inline GstFlowReturn
2946 gst_ps_demux_pull_block (GstPad * pad, GstPsDemux * demux,
2947     guint64 offset, guint size)
2948 {
2949   GstFlowReturn ret;
2950   GstBuffer *buffer = NULL;
2951   ret = gst_pad_pull_range (pad, offset, size, &buffer);
2952   if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2953     GST_DEBUG_OBJECT (demux, "pull range at %" G_GUINT64_FORMAT
2954         " size %u failed", offset, size);
2955     goto beach;
2956   } else
2957     GST_LOG_OBJECT (demux, "pull range at %" G_GUINT64_FORMAT
2958         " size %u done", offset, size);
2959   if (demux->sink_segment.rate < 0) {
2960     GST_LOG_OBJECT (demux, "setting discont flag on backward rate");
2961     GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
2962   }
2963   ret = gst_ps_demux_chain (pad, GST_OBJECT (demux), buffer);
2964 beach:
2965   return ret;
2966 }
2967
2968 static void
2969 gst_ps_demux_loop (GstPad * pad)
2970 {
2971   GstPsDemux *demux;
2972   GstFlowReturn ret = GST_FLOW_OK;
2973   guint64 offset = 0;
2974   demux = GST_PS_DEMUX (gst_pad_get_parent (pad));
2975   if (G_UNLIKELY (demux->flushing)) {
2976     ret = GST_FLOW_FLUSHING;
2977     goto pause;
2978   }
2979
2980   if (G_UNLIKELY (demux->sink_segment.format == GST_FORMAT_UNDEFINED))
2981     gst_ps_sink_get_duration (demux);
2982   offset = demux->sink_segment.position;
2983   if (demux->sink_segment.rate >= 0) {
2984     guint size = BLOCK_SZ;
2985     if (G_LIKELY (demux->sink_segment.stop != (guint64) - 1)) {
2986       size = MIN (size, demux->sink_segment.stop - offset);
2987     }
2988     /* pull in data */
2989     ret = gst_ps_demux_pull_block (pad, demux, offset, size);
2990     /* pause if something went wrong */
2991     if (G_UNLIKELY (ret != GST_FLOW_OK))
2992       goto pause;
2993     /* update our position */
2994     offset += size;
2995     gst_segment_set_position (&demux->sink_segment, GST_FORMAT_BYTES, offset);
2996     /* check EOS condition */
2997     /* FIXME: The src_segment.stop is not including the SCR after seek(set) */
2998     if ((demux->sink_segment.position >= demux->sink_segment.stop) ||
2999         (demux->src_segment.stop != (guint64) - 1 &&
3000             demux->src_segment.position >=
3001             demux->src_segment.stop + demux->base_time)) {
3002       GST_DEBUG_OBJECT (demux,
3003           "forward mode using segment reached end of " "segment pos %"
3004           GST_TIME_FORMAT " stop %" GST_TIME_FORMAT " pos in bytes %"
3005           G_GUINT64_FORMAT " stop in bytes %" G_GUINT64_FORMAT,
3006           GST_TIME_ARGS (demux->src_segment.position),
3007           GST_TIME_ARGS (demux->src_segment.stop),
3008           demux->sink_segment.position, demux->sink_segment.stop);
3009       ret = GST_FLOW_EOS;
3010       goto pause;
3011     }
3012   } else {                      /* Reverse playback */
3013     guint64 size = MIN (offset, BLOCK_SZ);
3014     /* pull in data */
3015     ret = gst_ps_demux_pull_block (pad, demux, offset - size, size);
3016     /* pause if something went wrong */
3017     if (G_UNLIKELY (ret != GST_FLOW_OK))
3018       goto pause;
3019     /* update our position */
3020     offset -= size;
3021     gst_segment_set_position (&demux->sink_segment, GST_FORMAT_BYTES, offset);
3022     /* check EOS condition */
3023     if (demux->sink_segment.position <= demux->sink_segment.start ||
3024         demux->src_segment.position <= demux->src_segment.start) {
3025       GST_DEBUG_OBJECT (demux,
3026           "reverse mode using segment reached end of " "segment pos %"
3027           GST_TIME_FORMAT " stop %" GST_TIME_FORMAT " pos in bytes %"
3028           G_GUINT64_FORMAT " stop in bytes %" G_GUINT64_FORMAT,
3029           GST_TIME_ARGS (demux->src_segment.position),
3030           GST_TIME_ARGS (demux->src_segment.start),
3031           demux->sink_segment.position, demux->sink_segment.start);
3032       ret = GST_FLOW_EOS;
3033       goto pause;
3034     }
3035   }
3036
3037   gst_object_unref (demux);
3038   return;
3039 pause:
3040   {
3041     const gchar *reason = gst_flow_get_name (ret);
3042     GST_LOG_OBJECT (demux, "pausing task, reason %s", reason);
3043     gst_pad_pause_task (pad);
3044     if (ret == GST_FLOW_EOS) {
3045       /* perform EOS logic */
3046       gst_element_no_more_pads (GST_ELEMENT_CAST (demux));
3047       if (demux->src_segment.flags & GST_SEEK_FLAG_SEGMENT) {
3048         gint64 stop;
3049         /* for segment playback we need to post when (in stream time)
3050          * we stopped, this is either stop (when set) or the duration. */
3051         if ((stop = demux->src_segment.stop) == -1)
3052           stop = demux->src_segment.duration;
3053         if (demux->sink_segment.rate >= 0) {
3054           GST_LOG_OBJECT (demux, "Sending segment done, at end of segment");
3055           gst_element_post_message (GST_ELEMENT_CAST (demux),
3056               gst_message_new_segment_done (GST_OBJECT_CAST (demux),
3057                   GST_FORMAT_TIME, stop));
3058           gst_ps_demux_send_event (demux,
3059               gst_event_new_segment_done (GST_FORMAT_TIME, stop));
3060         } else {                /* Reverse playback */
3061           GST_LOG_OBJECT (demux,
3062               "Sending segment done, at beginning of " "segment");
3063           gst_element_post_message (GST_ELEMENT_CAST (demux),
3064               gst_message_new_segment_done (GST_OBJECT_CAST (demux),
3065                   GST_FORMAT_TIME, demux->src_segment.start));
3066           gst_ps_demux_send_event (demux,
3067               gst_event_new_segment_done (GST_FORMAT_TIME,
3068                   demux->src_segment.start));
3069         }
3070       } else {
3071         GstEvent *event;
3072         /* normal playback, send EOS to all linked pads */
3073         gst_element_no_more_pads (GST_ELEMENT (demux));
3074         GST_LOG_OBJECT (demux, "Sending EOS, at end of stream");
3075         event = gst_event_new_eos ();
3076         if (demux->segment_seqnum)
3077           gst_event_set_seqnum (event, demux->segment_seqnum);
3078         if (!gst_ps_demux_send_event (demux, event)
3079             && !have_open_streams (demux)) {
3080           GST_WARNING_OBJECT (demux, "EOS and no streams open");
3081           GST_ELEMENT_ERROR (demux, STREAM, FAILED,
3082               ("Internal data stream error."), ("No valid streams detected"));
3083         }
3084       }
3085     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
3086       GstEvent *event;
3087       GST_ELEMENT_FLOW_ERROR (demux, ret);
3088       event = gst_event_new_eos ();
3089       if (demux->segment_seqnum)
3090         gst_event_set_seqnum (event, demux->segment_seqnum);
3091       gst_ps_demux_send_event (demux, event);
3092     }
3093
3094     gst_object_unref (demux);
3095     return;
3096   }
3097 }
3098
3099 /* If we can pull that's preferred */
3100 static gboolean
3101 gst_ps_demux_sink_activate (GstPad * sinkpad, GstObject * parent)
3102 {
3103   gboolean res = FALSE;
3104   GstQuery *query = gst_query_new_scheduling ();
3105   if (gst_pad_peer_query (sinkpad, query)) {
3106     if (gst_query_has_scheduling_mode_with_flags (query,
3107             GST_PAD_MODE_PULL, GST_SCHEDULING_FLAG_SEEKABLE)) {
3108       res = gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
3109     } else {
3110       res = gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
3111     }
3112   } else {
3113     res = gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
3114   }
3115
3116   gst_query_unref (query);
3117   return res;
3118 }
3119
3120 /* This function gets called when we activate ourselves in push mode. */
3121 static gboolean
3122 gst_ps_demux_sink_activate_push (GstPad * sinkpad, GstObject * parent,
3123     gboolean active)
3124 {
3125   GstPsDemux *demux = GST_PS_DEMUX (parent);
3126   demux->random_access = FALSE;
3127   return TRUE;
3128 }
3129
3130 /* this function gets called when we activate ourselves in pull mode.
3131  * We can perform  random access to the resource and we start a task
3132  * to start reading */
3133 static gboolean
3134 gst_ps_demux_sink_activate_pull (GstPad * sinkpad, GstObject * parent,
3135     gboolean active)
3136 {
3137   GstPsDemux *demux = GST_PS_DEMUX (parent);
3138   if (active) {
3139     GST_DEBUG ("pull mode activated");
3140     demux->random_access = TRUE;
3141     return gst_pad_start_task (sinkpad,
3142         (GstTaskFunction) gst_ps_demux_loop, sinkpad, NULL);
3143   } else {
3144     demux->random_access = FALSE;
3145     return gst_pad_stop_task (sinkpad);
3146   }
3147 }
3148
3149 static gboolean
3150 gst_ps_demux_sink_activate_mode (GstPad * pad, GstObject * parent,
3151     GstPadMode mode, gboolean active)
3152 {
3153   if (mode == GST_PAD_MODE_PUSH) {
3154     return gst_ps_demux_sink_activate_push (pad, parent, active);
3155   } else if (mode == GST_PAD_MODE_PULL) {
3156     return gst_ps_demux_sink_activate_pull (pad, parent, active);
3157   }
3158   return FALSE;
3159 }
3160
3161 /* EOS and NOT_LINKED need to be combined. This means that we return:
3162 *
3163 *  GST_FLOW_NOT_LINKED: when all pads NOT_LINKED.
3164 *  GST_FLOW_EOS: when all pads EOS or NOT_LINKED.
3165 */
3166 static GstFlowReturn
3167 gst_ps_demux_combine_flows (GstPsDemux * demux, GstFlowReturn ret)
3168 {
3169   GST_LOG_OBJECT (demux, "flow return: %s", gst_flow_get_name (ret));
3170   ret = gst_flow_combiner_update_flow (demux->flowcombiner, ret);
3171   if (G_UNLIKELY (demux->need_no_more_pads && ret == GST_FLOW_NOT_LINKED))
3172     ret = GST_FLOW_OK;
3173   GST_LOG_OBJECT (demux, "combined flow return: %s", gst_flow_get_name (ret));
3174   return ret;
3175 }
3176
3177 static GstFlowReturn
3178 gst_ps_demux_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
3179 {
3180   GstPsDemux *demux = GST_PS_DEMUX (parent);
3181   GstFlowReturn ret = GST_FLOW_OK;
3182   guint32 avail;
3183   gboolean save, discont;
3184   discont = GST_BUFFER_IS_DISCONT (buffer);
3185   if (discont) {
3186     GST_LOG_OBJECT (demux,
3187         "Received buffer with discont flag and" " offset %"
3188         G_GUINT64_FORMAT, GST_BUFFER_OFFSET (buffer));
3189     gst_pes_filter_drain (&demux->filter);
3190     gst_ps_demux_mark_discont (demux, TRUE, FALSE);
3191     /* mark discont on all streams */
3192     if (demux->sink_segment.rate >= 0.0) {
3193       demux->current_scr = G_MAXUINT64;
3194       demux->bytes_since_scr = 0;
3195     }
3196   } else {
3197     GST_LOG_OBJECT (demux,
3198         "Received buffer with offset %" G_GUINT64_FORMAT,
3199         GST_BUFFER_OFFSET (buffer));
3200   }
3201
3202   /* We keep the offset to interpolate SCR */
3203   demux->adapter_offset = GST_BUFFER_OFFSET (buffer);
3204   gst_adapter_push (demux->adapter, buffer);
3205   demux->bytes_since_scr += gst_buffer_get_size (buffer);
3206   avail = gst_adapter_available (demux->rev_adapter);
3207   if (avail > 0) {
3208     GST_LOG_OBJECT (demux, "appending %u saved bytes", avail);
3209     /* if we have a previous reverse chunk, append this now */
3210     /* FIXME this code assumes we receive discont buffers all thei
3211      * time */
3212     gst_adapter_push (demux->adapter,
3213         gst_adapter_take_buffer (demux->rev_adapter, avail));
3214   }
3215
3216   avail = gst_adapter_available (demux->adapter);
3217   GST_LOG_OBJECT (demux, "avail now: %d, state %d", avail, demux->filter.state);
3218   switch (demux->filter.state) {
3219     case STATE_DATA_SKIP:
3220     case STATE_DATA_PUSH:
3221       ret = gst_pes_filter_process (&demux->filter);
3222       break;
3223     case STATE_HEADER_PARSE:
3224       break;
3225     default:
3226       break;
3227   }
3228
3229   switch (ret) {
3230     case GST_FLOW_NEED_MORE_DATA:
3231       /* Go and get more data */
3232       ret = GST_FLOW_OK;
3233       goto done;
3234     case GST_FLOW_LOST_SYNC:
3235       /* for FLOW_OK or lost-sync, carry onto resync */
3236       ret = GST_FLOW_OK;
3237       break;
3238     case GST_FLOW_OK:
3239       break;
3240     default:
3241       /* Any other return value should be sent upstream immediately */
3242       goto done;
3243   }
3244
3245   /* align adapter data to sync boundary, we keep the data up to the next sync
3246    * point. */
3247   save = TRUE;
3248   while (gst_ps_demux_resync (demux, save)) {
3249     gboolean ps_sync = TRUE;
3250     if (G_UNLIKELY (demux->flushing)) {
3251       ret = GST_FLOW_FLUSHING;
3252       goto done;
3253     }
3254
3255     /* now switch on last synced byte */
3256     switch (demux->last_sync_code) {
3257       case ID_PS_PACK_START_CODE:
3258         ret = gst_ps_demux_parse_pack_start (demux);
3259         break;
3260       case ID_PS_SYSTEM_HEADER_START_CODE:
3261         ret = gst_ps_demux_parse_sys_head (demux);
3262         break;
3263       case ID_PS_END_CODE:
3264         /* Skip final 4 bytes */
3265         gst_adapter_flush (demux->adapter, 4);
3266         ADAPTER_OFFSET_FLUSH (4);
3267         ret = GST_FLOW_OK;
3268         goto done;
3269       case ID_PS_PROGRAM_STREAM_MAP:
3270         ret = gst_ps_demux_parse_psm (demux);
3271         break;
3272       default:
3273         if (gst_ps_demux_is_pes_sync (demux->last_sync_code)) {
3274           ret = gst_pes_filter_process (&demux->filter);
3275         } else {
3276           GST_DEBUG_OBJECT (demux, "sync_code=%08x, non PES sync found"
3277               ", continuing", demux->last_sync_code);
3278           ps_sync = FALSE;
3279           ret = GST_FLOW_LOST_SYNC;
3280         }
3281         break;
3282     }
3283     /* if we found a ps sync, we stop saving the data, any non-ps sync gets
3284      * saved up to the next ps sync. */
3285     if (ps_sync)
3286       save = FALSE;
3287     switch (ret) {
3288       case GST_FLOW_NEED_MORE_DATA:
3289         GST_DEBUG_OBJECT (demux, "need more data");
3290         ret = GST_FLOW_OK;
3291         goto done;
3292       case GST_FLOW_LOST_SYNC:
3293         if (!save || demux->sink_segment.rate >= 0.0) {
3294           GST_DEBUG_OBJECT (demux, "flushing 3 bytes");
3295           gst_adapter_flush (demux->adapter, 3);
3296           ADAPTER_OFFSET_FLUSH (3);
3297         } else {
3298           GST_DEBUG_OBJECT (demux, "saving 3 bytes");
3299           gst_adapter_push (demux->rev_adapter,
3300               gst_adapter_take_buffer (demux->adapter, 3));
3301         }
3302         ret = GST_FLOW_OK;
3303         break;
3304       default:
3305         ret = gst_ps_demux_combine_flows (demux, ret);
3306         if (ret != GST_FLOW_OK)
3307           goto done;
3308         break;
3309     }
3310   }
3311 done:
3312   return ret;
3313 }
3314
3315 static GstStateChangeReturn
3316 gst_ps_demux_change_state (GstElement * element, GstStateChange transition)
3317 {
3318   GstPsDemux *demux = GST_PS_DEMUX (element);
3319   GstStateChangeReturn result;
3320   switch (transition) {
3321     case GST_STATE_CHANGE_NULL_TO_READY:
3322       gst_pes_filter_init (&demux->filter, demux->adapter,
3323           &demux->adapter_offset);
3324       gst_pes_filter_set_callbacks (&demux->filter,
3325           (GstPESFilterData) gst_ps_demux_data_cb,
3326           (GstPESFilterResync) gst_ps_demux_resync_cb, demux);
3327       demux->filter.gather_pes = TRUE;
3328       break;
3329     case GST_STATE_CHANGE_READY_TO_PAUSED:
3330       break;
3331     default:
3332       break;
3333   }
3334
3335   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3336   switch (transition) {
3337     case GST_STATE_CHANGE_PAUSED_TO_READY:
3338       gst_ps_demux_reset (demux);
3339       break;
3340     case GST_STATE_CHANGE_READY_TO_NULL:
3341       gst_pes_filter_uninit (&demux->filter);
3342       break;
3343     default:
3344       break;
3345   }
3346
3347   return result;
3348 }
3349
3350 static void
3351 gst_segment_set_position (GstSegment * segment, GstFormat format,
3352     guint64 position)
3353 {
3354   if (segment->format == GST_FORMAT_UNDEFINED) {
3355     segment->format = format;
3356   }
3357   segment->position = position;
3358 }
3359
3360 static void
3361 gst_segment_set_duration (GstSegment * segment, GstFormat format,
3362     guint64 duration)
3363 {
3364   if (segment->format == GST_FORMAT_UNDEFINED) {
3365     segment->format = format;
3366   }
3367   segment->duration = duration;
3368 }