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