v4l2videodec: Increase v4l2videodecoder rank
[platform/upstream/gst-plugins-good.git] / ext / dv / gstdvdemux.c
1 /* GStreamer
2  * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
3  *               <2005> Wim Taymans <wim@fluendo.com>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24
25 #include <string.h>
26 #include <math.h>
27
28 #include <gst/audio/audio.h>
29 #include "gstdvdemux.h"
30 #include "gstsmptetimecode.h"
31
32 /**
33  * SECTION:element-dvdemux
34  *
35  * dvdemux splits raw DV into its audio and video components. The audio will be
36  * decoded raw samples and the video will be encoded DV video.
37  *
38  * This element can operate in both push and pull mode depending on the
39  * capabilities of the upstream peer.
40  *
41  * <refsect2>
42  * <title>Example launch line</title>
43  * |[
44  * gst-launch-1.0 filesrc location=test.dv ! dvdemux name=demux ! queue ! audioconvert ! alsasink demux. ! queue ! dvdec ! xvimagesink
45  * ]| This pipeline decodes and renders the raw DV stream to an audio and a videosink.
46  * </refsect2>
47  */
48
49 /* DV output has two modes, normal and wide. The resolution is the same in both
50  * cases: 720 pixels wide by 576 pixels tall in PAL format, and 720x480 for
51  * NTSC.
52  *
53  * Each of the modes has its own pixel aspect ratio, which is fixed in practice
54  * by ITU-R BT.601 (also known as "CCIR-601" or "Rec.601"). Or so claims a
55  * reference that I culled from the reliable "internet",
56  * http://www.mir.com/DMG/aspect.html. Normal PAL is 59/54 and normal NTSC is
57  * 10/11. Because the pixel resolution is the same for both cases, we can get
58  * the pixel aspect ratio for wide recordings by multiplying by the ratio of
59  * display aspect ratios, 16/9 (for wide) divided by 4/3 (for normal):
60  *
61  * Wide NTSC: 10/11 * (16/9)/(4/3) = 40/33
62  * Wide PAL: 59/54 * (16/9)/(4/3) = 118/81
63  *
64  * However, the pixel resolution coming out of a DV source does not combine with
65  * the standard pixel aspect ratios to give a proper display aspect ratio. An
66  * image 480 pixels tall, with a 4:3 display aspect ratio, will be 768 pixels
67  * wide. But, if we take the normal PAL aspect ratio of 59/54, and multiply it
68  * with the width of the DV image (720 pixels), we get 786.666..., which is
69  * nonintegral and too wide. The camera is not outputting a 4:3 image.
70  * 
71  * If the video sink for this stream has fixed dimensions (such as for
72  * fullscreen playback, or for a java applet in a web page), you then have two
73  * choices. Either you show the whole image, but pad the image with black
74  * borders on the top and bottom (like watching a widescreen video on a 4:3
75  * device), or you crop the video to the proper ratio. Apparently the latter is
76  * the standard practice.
77  *
78  * For its part, GStreamer is concerned with accuracy and preservation of
79  * information. This element outputs the 720x576 or 720x480 video that it
80  * receives, noting the proper aspect ratio. This should not be a problem for
81  * windowed applications, which can change size to fit the video. Applications
82  * with fixed size requirements should decide whether to crop or pad which
83  * an element such as videobox can do.
84  */
85
86 #define NTSC_HEIGHT 480
87 #define NTSC_BUFFER 120000
88 #define NTSC_FRAMERATE_NUMERATOR 30000
89 #define NTSC_FRAMERATE_DENOMINATOR 1001
90
91 #define PAL_HEIGHT 576
92 #define PAL_BUFFER 144000
93 #define PAL_FRAMERATE_NUMERATOR 25
94 #define PAL_FRAMERATE_DENOMINATOR 1
95
96 #define PAL_NORMAL_PAR_X        16
97 #define PAL_NORMAL_PAR_Y        15
98 #define PAL_WIDE_PAR_X          64
99 #define PAL_WIDE_PAR_Y          45
100
101 #define NTSC_NORMAL_PAR_X       8
102 #define NTSC_NORMAL_PAR_Y       9
103 #define NTSC_WIDE_PAR_X         32
104 #define NTSC_WIDE_PAR_Y         27
105
106 GST_DEBUG_CATEGORY_STATIC (dvdemux_debug);
107 #define GST_CAT_DEFAULT dvdemux_debug
108
109 static GstStaticPadTemplate sink_temp = GST_STATIC_PAD_TEMPLATE ("sink",
110     GST_PAD_SINK,
111     GST_PAD_ALWAYS,
112     GST_STATIC_CAPS ("video/x-dv, systemstream = (boolean) true")
113     );
114
115 static GstStaticPadTemplate video_src_temp = GST_STATIC_PAD_TEMPLATE ("video",
116     GST_PAD_SRC,
117     GST_PAD_SOMETIMES,
118     GST_STATIC_CAPS ("video/x-dv, systemstream = (boolean) false")
119     );
120
121 static GstStaticPadTemplate audio_src_temp = GST_STATIC_PAD_TEMPLATE ("audio",
122     GST_PAD_SRC,
123     GST_PAD_SOMETIMES,
124     GST_STATIC_CAPS ("audio/x-raw, "
125         "format = (string) " GST_AUDIO_NE (S16) ", "
126         "layout = (string) interleaved, "
127         "rate = (int) { 32000, 44100, 48000 }, " "channels = (int) {2, 4}")
128     );
129
130
131 #define gst_dvdemux_parent_class parent_class
132 G_DEFINE_TYPE (GstDVDemux, gst_dvdemux, GST_TYPE_ELEMENT);
133
134 static void gst_dvdemux_finalize (GObject * object);
135
136 /* query functions */
137 static gboolean gst_dvdemux_src_query (GstPad * pad, GstObject * parent,
138     GstQuery * query);
139 static gboolean gst_dvdemux_sink_query (GstPad * pad, GstObject * parent,
140     GstQuery * query);
141
142 /* convert functions */
143 static gboolean gst_dvdemux_sink_convert (GstDVDemux * demux,
144     GstFormat src_format, gint64 src_value, GstFormat dest_format,
145     gint64 * dest_value);
146 static gboolean gst_dvdemux_src_convert (GstDVDemux * demux, GstPad * pad,
147     GstFormat src_format, gint64 src_value, GstFormat dest_format,
148     gint64 * dest_value);
149
150 /* event functions */
151 static gboolean gst_dvdemux_send_event (GstElement * element, GstEvent * event);
152 static gboolean gst_dvdemux_handle_src_event (GstPad * pad, GstObject * parent,
153     GstEvent * event);
154 static gboolean gst_dvdemux_handle_sink_event (GstPad * pad, GstObject * parent,
155     GstEvent * event);
156
157 /* scheduling functions */
158 static void gst_dvdemux_loop (GstPad * pad);
159 static GstFlowReturn gst_dvdemux_flush (GstDVDemux * dvdemux);
160 static GstFlowReturn gst_dvdemux_chain (GstPad * pad, GstObject * parent,
161     GstBuffer * buffer);
162
163 /* state change functions */
164 static gboolean gst_dvdemux_sink_activate (GstPad * sinkpad,
165     GstObject * parent);
166 static gboolean gst_dvdemux_sink_activate_mode (GstPad * sinkpad,
167     GstObject * parent, GstPadMode mode, gboolean active);
168 static GstStateChangeReturn gst_dvdemux_change_state (GstElement * element,
169     GstStateChange transition);
170
171 static void
172 gst_dvdemux_class_init (GstDVDemuxClass * klass)
173 {
174   GObjectClass *gobject_class;
175   GstElementClass *gstelement_class;
176
177   gobject_class = (GObjectClass *) klass;
178   gstelement_class = (GstElementClass *) klass;
179
180   gobject_class->finalize = gst_dvdemux_finalize;
181
182   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_dvdemux_change_state);
183   gstelement_class->send_event = GST_DEBUG_FUNCPTR (gst_dvdemux_send_event);
184
185   gst_element_class_add_static_pad_template (gstelement_class, &sink_temp);
186   gst_element_class_add_static_pad_template (gstelement_class, &video_src_temp);
187   gst_element_class_add_static_pad_template (gstelement_class, &audio_src_temp);
188
189   gst_element_class_set_static_metadata (gstelement_class,
190       "DV system stream demuxer", "Codec/Demuxer",
191       "Uses libdv to separate DV audio from DV video (libdv.sourceforge.net)",
192       "Erik Walthinsen <omega@cse.ogi.edu>, Wim Taymans <wim@fluendo.com>");
193
194   GST_DEBUG_CATEGORY_INIT (dvdemux_debug, "dvdemux", 0, "DV demuxer element");
195 }
196
197 static void
198 gst_dvdemux_init (GstDVDemux * dvdemux)
199 {
200   gint i;
201
202   dvdemux->sinkpad = gst_pad_new_from_static_template (&sink_temp, "sink");
203   /* we can operate in pull and push mode so we install
204    * a custom activate function */
205   gst_pad_set_activate_function (dvdemux->sinkpad,
206       GST_DEBUG_FUNCPTR (gst_dvdemux_sink_activate));
207   /* the function to activate in push mode */
208   gst_pad_set_activatemode_function (dvdemux->sinkpad,
209       GST_DEBUG_FUNCPTR (gst_dvdemux_sink_activate_mode));
210   /* for push mode, this is the chain function */
211   gst_pad_set_chain_function (dvdemux->sinkpad,
212       GST_DEBUG_FUNCPTR (gst_dvdemux_chain));
213   /* handling events (in push mode only) */
214   gst_pad_set_event_function (dvdemux->sinkpad,
215       GST_DEBUG_FUNCPTR (gst_dvdemux_handle_sink_event));
216   /* query functions */
217   gst_pad_set_query_function (dvdemux->sinkpad,
218       GST_DEBUG_FUNCPTR (gst_dvdemux_sink_query));
219
220   /* now add the pad */
221   gst_element_add_pad (GST_ELEMENT (dvdemux), dvdemux->sinkpad);
222
223   dvdemux->adapter = gst_adapter_new ();
224
225   /* we need 4 temp buffers for audio decoding which are of a static
226    * size and which we can allocate here */
227   for (i = 0; i < 4; i++) {
228     dvdemux->audio_buffers[i] =
229         (gint16 *) g_malloc (DV_AUDIO_MAX_SAMPLES * sizeof (gint16));
230   }
231 }
232
233 static void
234 gst_dvdemux_finalize (GObject * object)
235 {
236   GstDVDemux *dvdemux;
237   gint i;
238
239   dvdemux = GST_DVDEMUX (object);
240
241   g_object_unref (dvdemux->adapter);
242
243   /* clean up temp audio buffers */
244   for (i = 0; i < 4; i++) {
245     g_free (dvdemux->audio_buffers[i]);
246   }
247
248   G_OBJECT_CLASS (parent_class)->finalize (object);
249 }
250
251 /* reset to default values before starting streaming */
252 static void
253 gst_dvdemux_reset (GstDVDemux * dvdemux)
254 {
255   dvdemux->frame_offset = 0;
256   dvdemux->audio_offset = 0;
257   dvdemux->video_offset = 0;
258   dvdemux->discont = TRUE;
259   g_atomic_int_set (&dvdemux->found_header, 0);
260   dvdemux->frame_len = -1;
261   dvdemux->need_segment = FALSE;
262   dvdemux->new_media = FALSE;
263   dvdemux->framerate_numerator = 0;
264   dvdemux->framerate_denominator = 0;
265   dvdemux->height = 0;
266   dvdemux->frequency = 0;
267   dvdemux->channels = 0;
268   dvdemux->wide = FALSE;
269   gst_segment_init (&dvdemux->byte_segment, GST_FORMAT_BYTES);
270   gst_segment_init (&dvdemux->time_segment, GST_FORMAT_TIME);
271   dvdemux->segment_seqnum = 0;
272   dvdemux->upstream_time_segment = FALSE;
273   dvdemux->have_group_id = FALSE;
274   dvdemux->group_id = G_MAXUINT;
275   dvdemux->tag_event = NULL;
276 }
277
278 static gboolean
279 have_group_id (GstDVDemux * demux)
280 {
281   GstEvent *event;
282
283   event = gst_pad_get_sticky_event (demux->sinkpad, GST_EVENT_STREAM_START, 0);
284   if (event) {
285     if (gst_event_parse_group_id (event, &demux->group_id))
286       demux->have_group_id = TRUE;
287     else
288       demux->have_group_id = FALSE;
289     gst_event_unref (event);
290   } else if (!demux->have_group_id) {
291     demux->have_group_id = TRUE;
292     demux->group_id = gst_util_group_id_next ();
293   }
294
295   return demux->have_group_id;
296 }
297
298 static GstEvent *
299 gst_dvdemux_create_global_tag_event (GstDVDemux * dvdemux)
300 {
301   gchar rec_datetime[40];
302   GstDateTime *rec_dt;
303   GstTagList *tags;
304
305   tags = gst_tag_list_new (GST_TAG_CONTAINER_FORMAT, "DV", NULL);
306   gst_tag_list_set_scope (tags, GST_TAG_SCOPE_GLOBAL);
307
308   if (dv_get_recording_datetime (dvdemux->decoder, rec_datetime)) {
309     rec_dt = gst_date_time_new_from_iso8601_string (rec_datetime);
310     if (rec_dt) {
311       gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE, GST_TAG_DATE_TIME,
312           rec_dt, NULL);
313       gst_date_time_unref (rec_dt);
314     }
315   }
316
317   return gst_event_new_tag (tags);
318 }
319
320 static GstPad *
321 gst_dvdemux_add_pad (GstDVDemux * dvdemux, GstStaticPadTemplate * template,
322     GstCaps * caps)
323 {
324   GstPad *pad;
325   GstEvent *event;
326   gchar *stream_id;
327
328   pad = gst_pad_new_from_static_template (template, template->name_template);
329
330   gst_pad_set_query_function (pad, GST_DEBUG_FUNCPTR (gst_dvdemux_src_query));
331
332   gst_pad_set_event_function (pad,
333       GST_DEBUG_FUNCPTR (gst_dvdemux_handle_src_event));
334   gst_pad_use_fixed_caps (pad);
335   gst_pad_set_active (pad, TRUE);
336
337   stream_id =
338       gst_pad_create_stream_id (pad,
339       GST_ELEMENT_CAST (dvdemux),
340       template == &video_src_temp ? "video" : "audio");
341   event = gst_event_new_stream_start (stream_id);
342   if (have_group_id (dvdemux))
343     gst_event_set_group_id (event, dvdemux->group_id);
344   gst_pad_push_event (pad, event);
345   g_free (stream_id);
346
347   gst_pad_set_caps (pad, caps);
348
349   gst_pad_push_event (pad, gst_event_new_segment (&dvdemux->time_segment));
350
351   gst_element_add_pad (GST_ELEMENT (dvdemux), pad);
352
353   if (!dvdemux->tag_event) {
354     dvdemux->tag_event = gst_dvdemux_create_global_tag_event (dvdemux);
355   }
356
357   if (dvdemux->tag_event) {
358     gst_pad_push_event (pad, gst_event_ref (dvdemux->tag_event));
359   }
360
361   return pad;
362 }
363
364 static void
365 gst_dvdemux_remove_pads (GstDVDemux * dvdemux)
366 {
367   if (dvdemux->videosrcpad) {
368     gst_element_remove_pad (GST_ELEMENT (dvdemux), dvdemux->videosrcpad);
369     dvdemux->videosrcpad = NULL;
370   }
371   if (dvdemux->audiosrcpad) {
372     gst_element_remove_pad (GST_ELEMENT (dvdemux), dvdemux->audiosrcpad);
373     dvdemux->audiosrcpad = NULL;
374   }
375 }
376
377 static gboolean
378 gst_dvdemux_src_convert (GstDVDemux * dvdemux, GstPad * pad,
379     GstFormat src_format, gint64 src_value, GstFormat dest_format,
380     gint64 * dest_value)
381 {
382   gboolean res = TRUE;
383
384   if (dest_format == src_format || src_value == -1) {
385     *dest_value = src_value;
386     goto done;
387   }
388
389   if (dvdemux->frame_len <= 0)
390     goto error;
391
392   if (dvdemux->decoder == NULL)
393     goto error;
394
395   GST_INFO_OBJECT (pad,
396       "src_value:%" G_GINT64_FORMAT ", src_format:%d, dest_format:%d",
397       src_value, src_format, dest_format);
398
399   switch (src_format) {
400     case GST_FORMAT_BYTES:
401       switch (dest_format) {
402         case GST_FORMAT_DEFAULT:
403           if (pad == dvdemux->videosrcpad)
404             *dest_value = src_value / dvdemux->frame_len;
405           else if (pad == dvdemux->audiosrcpad)
406             *dest_value = src_value / (2 * dvdemux->channels);
407           break;
408         case GST_FORMAT_TIME:
409           if (pad == dvdemux->videosrcpad)
410             *dest_value = gst_util_uint64_scale (src_value,
411                 GST_SECOND * dvdemux->framerate_denominator,
412                 dvdemux->frame_len * dvdemux->framerate_numerator);
413           else if (pad == dvdemux->audiosrcpad)
414             *dest_value = gst_util_uint64_scale_int (src_value, GST_SECOND,
415                 2 * dvdemux->frequency * dvdemux->channels);
416           break;
417         default:
418           res = FALSE;
419       }
420       break;
421     case GST_FORMAT_TIME:
422       switch (dest_format) {
423         case GST_FORMAT_BYTES:
424           if (pad == dvdemux->videosrcpad)
425             *dest_value = gst_util_uint64_scale (src_value,
426                 dvdemux->frame_len * dvdemux->framerate_numerator,
427                 dvdemux->framerate_denominator * GST_SECOND);
428           else if (pad == dvdemux->audiosrcpad)
429             *dest_value = gst_util_uint64_scale_int (src_value,
430                 2 * dvdemux->frequency * dvdemux->channels, GST_SECOND);
431           break;
432         case GST_FORMAT_DEFAULT:
433           if (pad == dvdemux->videosrcpad) {
434             if (src_value)
435               *dest_value = gst_util_uint64_scale (src_value,
436                   dvdemux->framerate_numerator,
437                   dvdemux->framerate_denominator * GST_SECOND);
438             else
439               *dest_value = 0;
440           } else if (pad == dvdemux->audiosrcpad) {
441             *dest_value = gst_util_uint64_scale (src_value,
442                 dvdemux->frequency, GST_SECOND);
443           }
444           break;
445         default:
446           res = FALSE;
447       }
448       break;
449     case GST_FORMAT_DEFAULT:
450       switch (dest_format) {
451         case GST_FORMAT_TIME:
452           if (pad == dvdemux->videosrcpad) {
453             *dest_value = gst_util_uint64_scale (src_value,
454                 GST_SECOND * dvdemux->framerate_denominator,
455                 dvdemux->framerate_numerator);
456           } else if (pad == dvdemux->audiosrcpad) {
457             if (src_value)
458               *dest_value = gst_util_uint64_scale (src_value,
459                   GST_SECOND, dvdemux->frequency);
460             else
461               *dest_value = 0;
462           }
463           break;
464         case GST_FORMAT_BYTES:
465           if (pad == dvdemux->videosrcpad) {
466             *dest_value = src_value * dvdemux->frame_len;
467           } else if (pad == dvdemux->audiosrcpad) {
468             *dest_value = src_value * 2 * dvdemux->channels;
469           }
470           break;
471         default:
472           res = FALSE;
473       }
474       break;
475     default:
476       res = FALSE;
477   }
478
479 done:
480   GST_INFO_OBJECT (pad,
481       "Result : dest_format:%d, dest_value:%" G_GINT64_FORMAT ", res:%d",
482       dest_format, *dest_value, res);
483   return res;
484
485   /* ERRORS */
486 error:
487   {
488     GST_INFO ("source conversion failed");
489     return FALSE;
490   }
491 }
492
493 static gboolean
494 gst_dvdemux_sink_convert (GstDVDemux * dvdemux, GstFormat src_format,
495     gint64 src_value, GstFormat dest_format, gint64 * dest_value)
496 {
497   gboolean res = TRUE;
498
499   GST_DEBUG_OBJECT (dvdemux, "%d -> %d", src_format, dest_format);
500   GST_INFO_OBJECT (dvdemux,
501       "src_value:%" G_GINT64_FORMAT ", src_format:%d, dest_format:%d",
502       src_value, src_format, dest_format);
503
504   if (dest_format == src_format || src_value == -1) {
505     *dest_value = src_value;
506     goto done;
507   }
508
509   if (dvdemux->frame_len <= 0)
510     goto error;
511
512   switch (src_format) {
513     case GST_FORMAT_BYTES:
514       switch (dest_format) {
515         case GST_FORMAT_TIME:
516         {
517           guint64 frame;
518
519           /* get frame number, rounds down so don't combine this
520            * line and the next line. */
521           frame = src_value / dvdemux->frame_len;
522
523           *dest_value = gst_util_uint64_scale (frame,
524               GST_SECOND * dvdemux->framerate_denominator,
525               dvdemux->framerate_numerator);
526           break;
527         }
528         default:
529           res = FALSE;
530       }
531       break;
532     case GST_FORMAT_TIME:
533       switch (dest_format) {
534         case GST_FORMAT_BYTES:
535         {
536           guint64 frame;
537
538           /* calculate the frame */
539           frame =
540               gst_util_uint64_scale (src_value, dvdemux->framerate_numerator,
541               dvdemux->framerate_denominator * GST_SECOND);
542
543           /* calculate the offset from the rounded frame */
544           *dest_value = frame * dvdemux->frame_len;
545           break;
546         }
547         default:
548           res = FALSE;
549       }
550       break;
551     default:
552       res = FALSE;
553   }
554   GST_INFO_OBJECT (dvdemux,
555       "Result : dest_format:%d, dest_value:%" G_GINT64_FORMAT ", res:%d",
556       dest_format, *dest_value, res);
557
558 done:
559   return res;
560
561 error:
562   {
563     GST_INFO_OBJECT (dvdemux, "sink conversion failed");
564     return FALSE;
565   }
566 }
567
568 static gboolean
569 gst_dvdemux_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
570 {
571   gboolean res = TRUE;
572   GstDVDemux *dvdemux;
573
574   dvdemux = GST_DVDEMUX (parent);
575
576   switch (GST_QUERY_TYPE (query)) {
577     case GST_QUERY_POSITION:
578     {
579       GstFormat format;
580       gint64 cur;
581
582       /* get target format */
583       gst_query_parse_position (query, &format, NULL);
584
585       /* bring the position to the requested format. */
586       if (!(res = gst_dvdemux_src_convert (dvdemux, pad,
587                   GST_FORMAT_TIME, dvdemux->time_segment.position,
588                   format, &cur)))
589         goto error;
590       gst_query_set_position (query, format, cur);
591       break;
592     }
593     case GST_QUERY_DURATION:
594     {
595       GstFormat format;
596       gint64 end;
597       GstQuery *pquery;
598
599       /* First ask the peer in the original format */
600       if (!gst_pad_peer_query (dvdemux->sinkpad, query)) {
601         /* get target format */
602         gst_query_parse_duration (query, &format, NULL);
603
604         /* Now ask the peer in BYTES format and try to convert */
605         pquery = gst_query_new_duration (GST_FORMAT_BYTES);
606         if (!gst_pad_peer_query (dvdemux->sinkpad, pquery)) {
607           gst_query_unref (pquery);
608           goto error;
609         }
610
611         /* get peer total length */
612         gst_query_parse_duration (pquery, NULL, &end);
613         gst_query_unref (pquery);
614
615         /* convert end to requested format */
616         if (end != -1) {
617           if (!(res = gst_dvdemux_sink_convert (dvdemux,
618                       GST_FORMAT_BYTES, end, format, &end))) {
619             goto error;
620           }
621           gst_query_set_duration (query, format, end);
622         }
623       }
624       break;
625     }
626     case GST_QUERY_CONVERT:
627     {
628       GstFormat src_fmt, dest_fmt;
629       gint64 src_val, dest_val;
630
631       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
632       if (!(res =
633               gst_dvdemux_src_convert (dvdemux, pad, src_fmt, src_val,
634                   dest_fmt, &dest_val)))
635         goto error;
636       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
637       break;
638     }
639     case GST_QUERY_SEEKING:
640     {
641       GstFormat fmt;
642       GstQuery *peerquery;
643       gboolean seekable;
644
645       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
646
647       /* We can only handle TIME seeks really */
648       if (fmt != GST_FORMAT_TIME) {
649         gst_query_set_seeking (query, fmt, FALSE, -1, -1);
650         break;
651       }
652
653       /* First ask upstream */
654       if (gst_pad_peer_query (dvdemux->sinkpad, query)) {
655         gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
656         if (seekable) {
657           res = TRUE;
658           break;
659         }
660       }
661
662       res = TRUE;
663
664       peerquery = gst_query_new_seeking (GST_FORMAT_BYTES);
665       seekable = gst_pad_peer_query (dvdemux->sinkpad, peerquery);
666
667       if (seekable)
668         gst_query_parse_seeking (peerquery, NULL, &seekable, NULL, NULL);
669       gst_query_unref (peerquery);
670
671       if (seekable) {
672         peerquery = gst_query_new_duration (GST_FORMAT_TIME);
673         seekable = gst_dvdemux_src_query (pad, parent, peerquery);
674
675         if (seekable) {
676           gint64 duration;
677
678           gst_query_parse_duration (peerquery, NULL, &duration);
679           gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
680         } else {
681           gst_query_set_seeking (query, GST_FORMAT_TIME, FALSE, -1, -1);
682         }
683
684         gst_query_unref (peerquery);
685       } else {
686         gst_query_set_seeking (query, GST_FORMAT_TIME, FALSE, -1, -1);
687       }
688       break;
689     }
690     default:
691       res = gst_pad_query_default (pad, parent, query);
692       break;
693   }
694
695   return res;
696
697   /* ERRORS */
698 error:
699   {
700     GST_DEBUG ("error source query");
701     return FALSE;
702   }
703 }
704
705 static gboolean
706 gst_dvdemux_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
707 {
708   gboolean res = TRUE;
709   GstDVDemux *dvdemux;
710
711   dvdemux = GST_DVDEMUX (parent);
712
713   switch (GST_QUERY_TYPE (query)) {
714     case GST_QUERY_CONVERT:
715     {
716       GstFormat src_fmt, dest_fmt;
717       gint64 src_val, dest_val;
718
719       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
720       if (!(res =
721               gst_dvdemux_sink_convert (dvdemux, src_fmt, src_val, dest_fmt,
722                   &dest_val)))
723         goto error;
724       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
725       break;
726     }
727     default:
728       res = gst_pad_query_default (pad, parent, query);
729       break;
730   }
731
732   return res;
733
734   /* ERRORS */
735 error:
736   {
737     GST_DEBUG ("error handling sink query");
738     return FALSE;
739   }
740 }
741
742 /* takes ownership of the event */
743 static gboolean
744 gst_dvdemux_push_event (GstDVDemux * dvdemux, GstEvent * event)
745 {
746   gboolean res = FALSE;
747
748   if (dvdemux->videosrcpad) {
749     gst_event_ref (event);
750     res |= gst_pad_push_event (dvdemux->videosrcpad, event);
751   }
752
753   if (dvdemux->audiosrcpad)
754     res |= gst_pad_push_event (dvdemux->audiosrcpad, event);
755   else {
756     gst_event_unref (event);
757     res = TRUE;
758   }
759
760   return res;
761 }
762
763 static gboolean
764 gst_dvdemux_handle_sink_event (GstPad * pad, GstObject * parent,
765     GstEvent * event)
766 {
767   GstDVDemux *dvdemux = GST_DVDEMUX (parent);
768   gboolean res = TRUE;
769
770   switch (GST_EVENT_TYPE (event)) {
771     case GST_EVENT_FLUSH_START:
772       /* we are not blocking on anything exect the push() calls
773        * to the peer which will be unblocked by forwarding the
774        * event.*/
775       res = gst_dvdemux_push_event (dvdemux, event);
776       break;
777     case GST_EVENT_FLUSH_STOP:
778       gst_adapter_clear (dvdemux->adapter);
779       GST_DEBUG ("cleared adapter");
780       gst_segment_init (&dvdemux->byte_segment, GST_FORMAT_BYTES);
781       gst_segment_init (&dvdemux->time_segment, GST_FORMAT_TIME);
782       dvdemux->discont = TRUE;
783       res = gst_dvdemux_push_event (dvdemux, event);
784       break;
785     case GST_EVENT_SEGMENT:
786     {
787       const GstSegment *segment;
788
789       gst_event_parse_segment (event, &segment);
790       switch (segment->format) {
791         case GST_FORMAT_BYTES:
792           gst_segment_copy_into (segment, &dvdemux->byte_segment);
793           dvdemux->need_segment = TRUE;
794           dvdemux->segment_seqnum = gst_event_get_seqnum (event);
795           gst_event_unref (event);
796           break;
797         case GST_FORMAT_TIME:
798           gst_segment_copy_into (segment, &dvdemux->time_segment);
799
800           dvdemux->upstream_time_segment = TRUE;
801           dvdemux->segment_seqnum = gst_event_get_seqnum (event);
802
803           /* and we can just forward this time event */
804           res = gst_dvdemux_push_event (dvdemux, event);
805           break;
806         default:
807           gst_event_unref (event);
808           /* cannot accept this format */
809           res = FALSE;
810           break;
811       }
812       break;
813     }
814     case GST_EVENT_EOS:
815       /* flush any pending data, should be nothing left. */
816       gst_dvdemux_flush (dvdemux);
817       /* forward event */
818       res = gst_dvdemux_push_event (dvdemux, event);
819       /* and clear the adapter */
820       gst_adapter_clear (dvdemux->adapter);
821       break;
822     case GST_EVENT_CAPS:
823       gst_event_unref (event);
824       break;
825     default:
826       res = gst_dvdemux_push_event (dvdemux, event);
827       break;
828   }
829
830   return res;
831 }
832
833 /* convert a pair of values on the given srcpad */
834 static gboolean
835 gst_dvdemux_convert_src_pair (GstDVDemux * dvdemux, GstPad * pad,
836     GstFormat src_format, gint64 src_start, gint64 src_stop,
837     GstFormat dst_format, gint64 * dst_start, gint64 * dst_stop)
838 {
839   gboolean res;
840
841   GST_INFO ("starting conversion of start");
842   /* bring the format to time on srcpad. */
843   if (!(res = gst_dvdemux_src_convert (dvdemux, pad,
844               src_format, src_start, dst_format, dst_start))) {
845     goto done;
846   }
847   GST_INFO ("Finished conversion of start: %" G_GINT64_FORMAT, *dst_start);
848
849   GST_INFO ("starting conversion of stop");
850   /* bring the format to time on srcpad. */
851   if (!(res = gst_dvdemux_src_convert (dvdemux, pad,
852               src_format, src_stop, dst_format, dst_stop))) {
853     /* could not convert seek format to time offset */
854     goto done;
855   }
856   GST_INFO ("Finished conversion of stop: %" G_GINT64_FORMAT, *dst_stop);
857 done:
858   return res;
859 }
860
861 /* convert a pair of values on the sinkpad */
862 static gboolean
863 gst_dvdemux_convert_sink_pair (GstDVDemux * dvdemux,
864     GstFormat src_format, gint64 src_start, gint64 src_stop,
865     GstFormat dst_format, gint64 * dst_start, gint64 * dst_stop)
866 {
867   gboolean res;
868
869   GST_INFO ("starting conversion of start");
870   /* bring the format to time on srcpad. */
871   if (!(res = gst_dvdemux_sink_convert (dvdemux,
872               src_format, src_start, dst_format, dst_start))) {
873     goto done;
874   }
875   GST_INFO ("Finished conversion of start: %" G_GINT64_FORMAT, *dst_start);
876
877   GST_INFO ("starting conversion of stop");
878   /* bring the format to time on srcpad. */
879   if (!(res = gst_dvdemux_sink_convert (dvdemux,
880               src_format, src_stop, dst_format, dst_stop))) {
881     /* could not convert seek format to time offset */
882     goto done;
883   }
884   GST_INFO ("Finished conversion of stop: %" G_GINT64_FORMAT, *dst_stop);
885 done:
886   return res;
887 }
888
889 /* convert a pair of values on the srcpad to a pair of
890  * values on the sinkpad 
891  */
892 static gboolean
893 gst_dvdemux_convert_src_to_sink (GstDVDemux * dvdemux, GstPad * pad,
894     GstFormat src_format, gint64 src_start, gint64 src_stop,
895     GstFormat dst_format, gint64 * dst_start, gint64 * dst_stop)
896 {
897   GstFormat conv;
898   gboolean res;
899
900   conv = GST_FORMAT_TIME;
901   /* convert to TIME intermediate format */
902   if (!(res = gst_dvdemux_convert_src_pair (dvdemux, pad,
903               src_format, src_start, src_stop, conv, dst_start, dst_stop))) {
904     /* could not convert format to time offset */
905     goto done;
906   }
907   /* convert to dst format on sinkpad */
908   if (!(res = gst_dvdemux_convert_sink_pair (dvdemux,
909               conv, *dst_start, *dst_stop, dst_format, dst_start, dst_stop))) {
910     /* could not convert format to time offset */
911     goto done;
912   }
913 done:
914   return res;
915 }
916
917 #if 0
918 static gboolean
919 gst_dvdemux_convert_segment (GstDVDemux * dvdemux, GstSegment * src,
920     GstSegment * dest)
921 {
922   dest->rate = src->rate;
923   dest->abs_rate = src->abs_rate;
924   dest->flags = src->flags;
925
926   return TRUE;
927 }
928 #endif
929
930 /* handle seek in push base mode.
931  *
932  * Convert the time seek to a bytes seek and send it
933  * upstream
934  * Does not take ownership of the event.
935  */
936 static gboolean
937 gst_dvdemux_handle_push_seek (GstDVDemux * dvdemux, GstPad * pad,
938     GstEvent * event)
939 {
940   gboolean res = FALSE;
941   gdouble rate;
942   GstSeekFlags flags;
943   GstFormat format;
944   GstSeekType cur_type, stop_type;
945   gint64 cur, stop;
946   gint64 start_position, end_position;
947   GstEvent *newevent;
948
949   gst_event_parse_seek (event, &rate, &format, &flags,
950       &cur_type, &cur, &stop_type, &stop);
951
952   /* First try if upstream can handle time based seeks */
953   if (format == GST_FORMAT_TIME)
954     res = gst_pad_push_event (dvdemux->sinkpad, gst_event_ref (event));
955
956   if (!res) {
957     /* we convert the start/stop on the srcpad to the byte format
958      * on the sinkpad and forward the event */
959     res = gst_dvdemux_convert_src_to_sink (dvdemux, pad,
960         format, cur, stop, GST_FORMAT_BYTES, &start_position, &end_position);
961     if (!res)
962       goto done;
963
964     /* now this is the updated seek event on bytes */
965     newevent = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
966         cur_type, start_position, stop_type, end_position);
967     gst_event_set_seqnum (newevent, gst_event_get_seqnum (event));
968
969     res = gst_pad_push_event (dvdemux->sinkpad, newevent);
970   }
971 done:
972   return res;
973 }
974
975 static void
976 gst_dvdemux_update_frame_offsets (GstDVDemux * dvdemux, GstClockTime timestamp)
977 {
978   /* calculate current frame number */
979   gst_dvdemux_src_convert (dvdemux, dvdemux->videosrcpad,
980       dvdemux->time_segment.format, timestamp,
981       GST_FORMAT_DEFAULT, &dvdemux->video_offset);
982
983   /* calculate current audio number */
984   gst_dvdemux_src_convert (dvdemux, dvdemux->audiosrcpad,
985       dvdemux->time_segment.format, timestamp,
986       GST_FORMAT_DEFAULT, &dvdemux->audio_offset);
987
988   /* every DV frame corresponts with one video frame */
989   dvdemux->frame_offset = dvdemux->video_offset;
990 }
991
992 /* position ourselves to the configured segment, used in pull mode.
993  * The input segment is in TIME format. We convert the time values
994  * to bytes values into our byte_segment which we use to pull data from
995  * the sinkpad peer.
996  */
997 static gboolean
998 gst_dvdemux_do_seek (GstDVDemux * demux, GstSegment * segment)
999 {
1000   gboolean res;
1001   GstFormat format;
1002
1003   /* position to value configured is last_stop, this will round down
1004    * to the byte position where the frame containing the given 
1005    * timestamp can be found. */
1006   format = GST_FORMAT_BYTES;
1007   res = gst_dvdemux_sink_convert (demux,
1008       segment->format, segment->position,
1009       format, (gint64 *) & demux->byte_segment.position);
1010   if (!res)
1011     goto done;
1012
1013   /* update byte segment start */
1014   gst_dvdemux_sink_convert (demux,
1015       segment->format, segment->start, format,
1016       (gint64 *) & demux->byte_segment.start);
1017
1018   /* update byte segment stop */
1019   gst_dvdemux_sink_convert (demux,
1020       segment->format, segment->stop, format,
1021       (gint64 *) & demux->byte_segment.stop);
1022
1023   /* update byte segment time */
1024   gst_dvdemux_sink_convert (demux,
1025       segment->format, segment->time, format,
1026       (gint64 *) & demux->byte_segment.time);
1027
1028   gst_dvdemux_update_frame_offsets (demux, segment->start);
1029
1030   demux->discont = TRUE;
1031
1032 done:
1033   return res;
1034 }
1035
1036 /* handle seek in pull base mode.
1037  *
1038  * Does not take ownership of the event.
1039  */
1040 static gboolean
1041 gst_dvdemux_handle_pull_seek (GstDVDemux * demux, GstPad * pad,
1042     GstEvent * event)
1043 {
1044   gboolean res;
1045   gdouble rate;
1046   GstFormat format;
1047   GstSeekFlags flags;
1048   GstSeekType cur_type, stop_type;
1049   gint64 cur, stop;
1050   gboolean flush;
1051   gboolean update;
1052   GstSegment seeksegment;
1053   GstEvent *new_event;
1054
1055   GST_DEBUG_OBJECT (demux, "doing seek");
1056
1057   /* first bring the event format to TIME, our native format
1058    * to perform the seek on */
1059   if (event) {
1060     GstFormat conv;
1061
1062     gst_event_parse_seek (event, &rate, &format, &flags,
1063         &cur_type, &cur, &stop_type, &stop);
1064
1065     /* can't seek backwards yet */
1066     if (rate <= 0.0)
1067       goto wrong_rate;
1068
1069     /* convert input format to TIME */
1070     conv = GST_FORMAT_TIME;
1071     if (!(gst_dvdemux_convert_src_pair (demux, pad,
1072                 format, cur, stop, conv, &cur, &stop)))
1073       goto no_format;
1074
1075     format = GST_FORMAT_TIME;
1076   } else {
1077     flags = 0;
1078   }
1079
1080   demux->segment_seqnum = gst_event_get_seqnum (event);
1081
1082   flush = flags & GST_SEEK_FLAG_FLUSH;
1083
1084   /* send flush start */
1085   if (flush) {
1086     new_event = gst_event_new_flush_start ();
1087     gst_event_set_seqnum (new_event, demux->segment_seqnum);
1088     gst_dvdemux_push_event (demux, new_event);
1089   } else {
1090     gst_pad_pause_task (demux->sinkpad);
1091   }
1092
1093   /* grab streaming lock, this should eventually be possible, either
1094    * because the task is paused or our streaming thread stopped
1095    * because our peer is flushing. */
1096   GST_PAD_STREAM_LOCK (demux->sinkpad);
1097
1098   /* make copy into temp structure, we can only update the main one
1099    * when the subclass actually could to the seek. */
1100   memcpy (&seeksegment, &demux->time_segment, sizeof (GstSegment));
1101
1102   /* now configure the seek segment */
1103   if (event) {
1104     gst_segment_do_seek (&seeksegment, rate, format, flags,
1105         cur_type, cur, stop_type, stop, &update);
1106   }
1107
1108   GST_DEBUG_OBJECT (demux, "segment configured from %" G_GINT64_FORMAT
1109       " to %" G_GINT64_FORMAT ", position %" G_GINT64_FORMAT,
1110       seeksegment.start, seeksegment.stop, seeksegment.position);
1111
1112   /* do the seek, segment.position contains new position. */
1113   res = gst_dvdemux_do_seek (demux, &seeksegment);
1114
1115   /* and prepare to continue streaming */
1116   if (flush) {
1117     /* send flush stop, peer will accept data and events again. We
1118      * are not yet providing data as we still have the STREAM_LOCK. */
1119     new_event = gst_event_new_flush_stop (TRUE);
1120     gst_event_set_seqnum (new_event, demux->segment_seqnum);
1121     gst_dvdemux_push_event (demux, new_event);
1122   }
1123
1124   /* if successfull seek, we update our real segment and push
1125    * out the new segment. */
1126   if (res) {
1127     memcpy (&demux->time_segment, &seeksegment, sizeof (GstSegment));
1128
1129     if (demux->time_segment.flags & GST_SEEK_FLAG_SEGMENT) {
1130       GstMessage *message;
1131
1132       message = gst_message_new_segment_start (GST_OBJECT_CAST (demux),
1133           demux->time_segment.format, demux->time_segment.position);
1134       gst_message_set_seqnum (message, demux->segment_seqnum);
1135       gst_element_post_message (GST_ELEMENT_CAST (demux), message);
1136     }
1137     if ((stop = demux->time_segment.stop) == -1)
1138       stop = demux->time_segment.duration;
1139
1140     GST_INFO_OBJECT (demux,
1141         "Saving newsegment event to be sent in streaming thread");
1142
1143     if (demux->pending_segment)
1144       gst_event_unref (demux->pending_segment);
1145
1146     demux->pending_segment = gst_event_new_segment (&demux->time_segment);
1147     gst_event_set_seqnum (demux->pending_segment, demux->segment_seqnum);
1148
1149     demux->need_segment = FALSE;
1150   }
1151
1152   /* and restart the task in case it got paused explicitely or by
1153    * the FLUSH_START event we pushed out. */
1154   gst_pad_start_task (demux->sinkpad, (GstTaskFunction) gst_dvdemux_loop,
1155       demux->sinkpad, NULL);
1156
1157   /* and release the lock again so we can continue streaming */
1158   GST_PAD_STREAM_UNLOCK (demux->sinkpad);
1159
1160   return TRUE;
1161
1162   /* ERRORS */
1163 wrong_rate:
1164   {
1165     GST_DEBUG_OBJECT (demux, "negative playback rate %lf not supported.", rate);
1166     return FALSE;
1167   }
1168 no_format:
1169   {
1170     GST_DEBUG_OBJECT (demux, "cannot convert to TIME format, seek aborted.");
1171     return FALSE;
1172   }
1173 }
1174
1175 static gboolean
1176 gst_dvdemux_send_event (GstElement * element, GstEvent * event)
1177 {
1178   GstDVDemux *dvdemux = GST_DVDEMUX (element);
1179   gboolean res = FALSE;
1180
1181   switch (GST_EVENT_TYPE (event)) {
1182     case GST_EVENT_SEEK:
1183     {
1184       /* checking header and configuring the seek must be atomic */
1185       GST_OBJECT_LOCK (dvdemux);
1186       if (g_atomic_int_get (&dvdemux->found_header) == 0) {
1187         GstEvent **event_p;
1188
1189         event_p = &dvdemux->seek_event;
1190
1191         /* We don't have pads yet. Keep the event. */
1192         GST_INFO_OBJECT (dvdemux, "Keeping the seek event for later");
1193
1194         gst_event_replace (event_p, event);
1195         GST_OBJECT_UNLOCK (dvdemux);
1196
1197         res = TRUE;
1198       } else {
1199         GST_OBJECT_UNLOCK (dvdemux);
1200
1201         if (dvdemux->seek_handler)
1202           res = dvdemux->seek_handler (dvdemux, dvdemux->videosrcpad, event);
1203         gst_event_unref (event);
1204       }
1205       break;
1206     }
1207     default:
1208       res = GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
1209       break;
1210   }
1211
1212   return res;
1213 }
1214
1215 /* handle an event on the source pad, it's most likely a seek */
1216 static gboolean
1217 gst_dvdemux_handle_src_event (GstPad * pad, GstObject * parent,
1218     GstEvent * event)
1219 {
1220   gboolean res = FALSE;
1221   GstDVDemux *dvdemux;
1222
1223   dvdemux = GST_DVDEMUX (parent);
1224
1225   switch (GST_EVENT_TYPE (event)) {
1226     case GST_EVENT_SEEK:
1227       /* seek handler is installed based on scheduling mode */
1228       if (dvdemux->seek_handler)
1229         res = dvdemux->seek_handler (dvdemux, pad, event);
1230       gst_event_unref (event);
1231       break;
1232     default:
1233       res = gst_pad_push_event (dvdemux->sinkpad, event);
1234       break;
1235   }
1236
1237   return res;
1238 }
1239
1240 /* does not take ownership of buffer */
1241 static GstFlowReturn
1242 gst_dvdemux_demux_audio (GstDVDemux * dvdemux, GstBuffer * buffer,
1243     guint64 duration)
1244 {
1245   gint num_samples;
1246   GstFlowReturn ret;
1247   GstMapInfo map;
1248
1249   gst_buffer_map (buffer, &map, GST_MAP_READ);
1250   dv_decode_full_audio (dvdemux->decoder, map.data, dvdemux->audio_buffers);
1251   gst_buffer_unmap (buffer, &map);
1252
1253   if (G_LIKELY ((num_samples = dv_get_num_samples (dvdemux->decoder)) > 0)) {
1254     gint16 *a_ptr;
1255     gint i, j;
1256     GstBuffer *outbuf;
1257     gint frequency, channels;
1258
1259     /* get initial format or check if format changed */
1260     frequency = dv_get_frequency (dvdemux->decoder);
1261     channels = dv_get_num_channels (dvdemux->decoder);
1262
1263     if (G_UNLIKELY ((dvdemux->audiosrcpad == NULL)
1264             || (frequency != dvdemux->frequency)
1265             || (channels != dvdemux->channels))) {
1266       GstCaps *caps;
1267       GstAudioInfo info;
1268
1269       dvdemux->frequency = frequency;
1270       dvdemux->channels = channels;
1271
1272       gst_audio_info_init (&info);
1273       gst_audio_info_set_format (&info, GST_AUDIO_FORMAT_S16LE,
1274           frequency, channels, NULL);
1275       caps = gst_audio_info_to_caps (&info);
1276       if (G_UNLIKELY (dvdemux->audiosrcpad == NULL)) {
1277         dvdemux->audiosrcpad =
1278             gst_dvdemux_add_pad (dvdemux, &audio_src_temp, caps);
1279
1280         if (dvdemux->videosrcpad && dvdemux->audiosrcpad)
1281           gst_element_no_more_pads (GST_ELEMENT (dvdemux));
1282
1283       } else {
1284         gst_pad_set_caps (dvdemux->audiosrcpad, caps);
1285       }
1286       gst_caps_unref (caps);
1287     }
1288
1289     outbuf = gst_buffer_new_and_alloc (num_samples *
1290         sizeof (gint16) * dvdemux->channels);
1291
1292     gst_buffer_map (outbuf, &map, GST_MAP_WRITE);
1293     a_ptr = (gint16 *) map.data;
1294
1295     for (i = 0; i < num_samples; i++) {
1296       for (j = 0; j < dvdemux->channels; j++) {
1297         *(a_ptr++) = dvdemux->audio_buffers[j][i];
1298       }
1299     }
1300     gst_buffer_unmap (outbuf, &map);
1301
1302     GST_DEBUG ("pushing audio %" GST_TIME_FORMAT,
1303         GST_TIME_ARGS (dvdemux->time_segment.position));
1304
1305     GST_BUFFER_TIMESTAMP (outbuf) = dvdemux->time_segment.position;
1306     GST_BUFFER_DURATION (outbuf) = duration;
1307     GST_BUFFER_OFFSET (outbuf) = dvdemux->audio_offset;
1308     dvdemux->audio_offset += num_samples;
1309     GST_BUFFER_OFFSET_END (outbuf) = dvdemux->audio_offset;
1310
1311     if (dvdemux->new_media || dvdemux->discont)
1312       GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
1313     ret = gst_pad_push (dvdemux->audiosrcpad, outbuf);
1314   } else {
1315     /* no samples */
1316     ret = GST_FLOW_OK;
1317   }
1318
1319   return ret;
1320 }
1321
1322 /* takes ownership of buffer */
1323 static GstFlowReturn
1324 gst_dvdemux_demux_video (GstDVDemux * dvdemux, GstBuffer * buffer,
1325     guint64 duration)
1326 {
1327   GstBuffer *outbuf;
1328   gint height;
1329   gboolean wide;
1330   GstFlowReturn ret = GST_FLOW_OK;
1331
1332   /* get params */
1333   /* framerate is already up-to-date */
1334   height = dvdemux->decoder->height;
1335   wide = dv_format_wide (dvdemux->decoder);
1336
1337   /* see if anything changed */
1338   if (G_UNLIKELY ((dvdemux->videosrcpad == NULL) || (dvdemux->height != height)
1339           || dvdemux->wide != wide)) {
1340     gint par_x, par_y;
1341     GstCaps *caps;
1342
1343     dvdemux->height = height;
1344     dvdemux->wide = wide;
1345
1346     if (dvdemux->decoder->system == e_dv_system_625_50) {
1347       if (wide) {
1348         par_x = PAL_WIDE_PAR_X;
1349         par_y = PAL_WIDE_PAR_Y;
1350       } else {
1351         par_x = PAL_NORMAL_PAR_X;
1352         par_y = PAL_NORMAL_PAR_Y;
1353       }
1354     } else {
1355       if (wide) {
1356         par_x = NTSC_WIDE_PAR_X;
1357         par_y = NTSC_WIDE_PAR_Y;
1358       } else {
1359         par_x = NTSC_NORMAL_PAR_X;
1360         par_y = NTSC_NORMAL_PAR_Y;
1361       }
1362     }
1363
1364     caps = gst_caps_new_simple ("video/x-dv",
1365         "systemstream", G_TYPE_BOOLEAN, FALSE,
1366         "width", G_TYPE_INT, 720,
1367         "height", G_TYPE_INT, height,
1368         "framerate", GST_TYPE_FRACTION, dvdemux->framerate_numerator,
1369         dvdemux->framerate_denominator,
1370         "pixel-aspect-ratio", GST_TYPE_FRACTION, par_x, par_y, NULL);
1371
1372     if (G_UNLIKELY (dvdemux->videosrcpad == NULL)) {
1373       dvdemux->videosrcpad =
1374           gst_dvdemux_add_pad (dvdemux, &video_src_temp, caps);
1375
1376       if (dvdemux->videosrcpad && dvdemux->audiosrcpad)
1377         gst_element_no_more_pads (GST_ELEMENT (dvdemux));
1378
1379     } else {
1380       gst_pad_set_caps (dvdemux->videosrcpad, caps);
1381     }
1382     gst_caps_unref (caps);
1383   }
1384
1385   /* takes ownership of buffer here, we just need to modify
1386    * the metadata. */
1387   outbuf = gst_buffer_make_writable (buffer);
1388
1389   GST_BUFFER_TIMESTAMP (outbuf) = dvdemux->time_segment.position;
1390   GST_BUFFER_OFFSET (outbuf) = dvdemux->video_offset;
1391   GST_BUFFER_OFFSET_END (outbuf) = dvdemux->video_offset + 1;
1392   GST_BUFFER_DURATION (outbuf) = duration;
1393
1394   if (dvdemux->new_media || dvdemux->discont)
1395     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
1396
1397   GST_DEBUG ("pushing video %" GST_TIME_FORMAT,
1398       GST_TIME_ARGS (dvdemux->time_segment.position));
1399
1400   ret = gst_pad_push (dvdemux->videosrcpad, outbuf);
1401
1402   dvdemux->video_offset++;
1403
1404   return ret;
1405 }
1406
1407 static int
1408 get_ssyb_offset (int dif, int ssyb)
1409 {
1410   int offset;
1411
1412   offset = dif * 12000;         /* to dif */
1413   offset += 80 * (1 + (ssyb / 6));      /* to subcode pack */
1414   offset += 3;                  /* past header */
1415   offset += 8 * (ssyb % 6);     /* to ssyb */
1416
1417   return offset;
1418 }
1419
1420 static gboolean
1421 gst_dvdemux_get_timecode (GstDVDemux * dvdemux, GstBuffer * buffer,
1422     GstSMPTETimeCode * timecode)
1423 {
1424   guint8 *data;
1425   GstMapInfo map;
1426   int offset;
1427   int dif;
1428   int n_difs = dvdemux->decoder->num_dif_seqs;
1429
1430   gst_buffer_map (buffer, &map, GST_MAP_READ);
1431   data = map.data;
1432   for (dif = 0; dif < n_difs; dif++) {
1433     offset = get_ssyb_offset (dif, 3);
1434     if (data[offset + 3] == 0x13) {
1435       timecode->frames = ((data[offset + 4] >> 4) & 0x3) * 10 +
1436           (data[offset + 4] & 0xf);
1437       timecode->seconds = ((data[offset + 5] >> 4) & 0x3) * 10 +
1438           (data[offset + 5] & 0xf);
1439       timecode->minutes = ((data[offset + 6] >> 4) & 0x3) * 10 +
1440           (data[offset + 6] & 0xf);
1441       timecode->hours = ((data[offset + 7] >> 4) & 0x3) * 10 +
1442           (data[offset + 7] & 0xf);
1443       GST_DEBUG ("got timecode %" GST_SMPTE_TIME_CODE_FORMAT,
1444           GST_SMPTE_TIME_CODE_ARGS (timecode));
1445       gst_buffer_unmap (buffer, &map);
1446       return TRUE;
1447     }
1448   }
1449
1450   gst_buffer_unmap (buffer, &map);
1451   return FALSE;
1452 }
1453
1454 static gboolean
1455 gst_dvdemux_is_new_media (GstDVDemux * dvdemux, GstBuffer * buffer)
1456 {
1457   guint8 *data;
1458   GstMapInfo map;
1459   int aaux_offset;
1460   int dif;
1461   int n_difs;
1462
1463   n_difs = dvdemux->decoder->num_dif_seqs;
1464
1465   gst_buffer_map (buffer, &map, GST_MAP_READ);
1466   data = map.data;
1467   for (dif = 0; dif < n_difs; dif++) {
1468     if (dif & 1) {
1469       aaux_offset = (dif * 12000) + (6 + 16 * 1) * 80 + 3;
1470     } else {
1471       aaux_offset = (dif * 12000) + (6 + 16 * 4) * 80 + 3;
1472     }
1473     if (data[aaux_offset + 0] == 0x51) {
1474       if ((data[aaux_offset + 2] & 0x80) == 0) {
1475         gst_buffer_unmap (buffer, &map);
1476         return TRUE;
1477       }
1478     }
1479   }
1480
1481   gst_buffer_unmap (buffer, &map);
1482   return FALSE;
1483 }
1484
1485 /* takes ownership of buffer */
1486 static GstFlowReturn
1487 gst_dvdemux_demux_frame (GstDVDemux * dvdemux, GstBuffer * buffer)
1488 {
1489   GstClockTime next_ts;
1490   GstFlowReturn aret, vret, ret;
1491   GstMapInfo map;
1492   guint64 duration;
1493   GstSMPTETimeCode timecode;
1494   int frame_number;
1495
1496   if (dvdemux->need_segment) {
1497     GstFormat format;
1498     GstEvent *event;
1499
1500     g_assert (!dvdemux->upstream_time_segment);
1501
1502     /* convert to time and store as start/end_timestamp */
1503     format = GST_FORMAT_TIME;
1504     if (!(gst_dvdemux_convert_sink_pair (dvdemux,
1505                 GST_FORMAT_BYTES, dvdemux->byte_segment.start,
1506                 dvdemux->byte_segment.stop, format,
1507                 (gint64 *) & dvdemux->time_segment.start,
1508                 (gint64 *) & dvdemux->time_segment.stop)))
1509       goto segment_error;
1510
1511     dvdemux->time_segment.time = dvdemux->time_segment.start;
1512     dvdemux->time_segment.rate = dvdemux->byte_segment.rate;
1513
1514     gst_dvdemux_sink_convert (dvdemux,
1515         GST_FORMAT_BYTES, dvdemux->byte_segment.position,
1516         GST_FORMAT_TIME, (gint64 *) & dvdemux->time_segment.position);
1517
1518     gst_dvdemux_update_frame_offsets (dvdemux, dvdemux->time_segment.position);
1519
1520     GST_DEBUG_OBJECT (dvdemux, "sending segment start: %" GST_TIME_FORMAT
1521         ", stop: %" GST_TIME_FORMAT ", time: %" GST_TIME_FORMAT,
1522         GST_TIME_ARGS (dvdemux->time_segment.start),
1523         GST_TIME_ARGS (dvdemux->time_segment.stop),
1524         GST_TIME_ARGS (dvdemux->time_segment.start));
1525
1526     event = gst_event_new_segment (&dvdemux->time_segment);
1527     if (dvdemux->segment_seqnum)
1528       gst_event_set_seqnum (event, dvdemux->segment_seqnum);
1529     gst_dvdemux_push_event (dvdemux, event);
1530
1531     dvdemux->need_segment = FALSE;
1532   }
1533
1534   gst_dvdemux_get_timecode (dvdemux, buffer, &timecode);
1535   gst_smpte_time_code_get_frame_number (
1536       (dvdemux->decoder->system == e_dv_system_625_50) ?
1537       GST_SMPTE_TIME_CODE_SYSTEM_25 : GST_SMPTE_TIME_CODE_SYSTEM_30,
1538       &frame_number, &timecode);
1539
1540   if (dvdemux->time_segment.rate < 0) {
1541     next_ts = gst_util_uint64_scale_int (
1542         (dvdemux->frame_offset >
1543             0 ? dvdemux->frame_offset - 1 : 0) * GST_SECOND,
1544         dvdemux->framerate_denominator, dvdemux->framerate_numerator);
1545     duration = dvdemux->time_segment.position - next_ts;
1546   } else {
1547     next_ts = gst_util_uint64_scale_int (
1548         (dvdemux->frame_offset + 1) * GST_SECOND,
1549         dvdemux->framerate_denominator, dvdemux->framerate_numerator);
1550     duration = next_ts - dvdemux->time_segment.position;
1551   }
1552
1553   gst_buffer_map (buffer, &map, GST_MAP_READ);
1554   dv_parse_packs (dvdemux->decoder, map.data);
1555   gst_buffer_unmap (buffer, &map);
1556   dvdemux->new_media = FALSE;
1557   if (gst_dvdemux_is_new_media (dvdemux, buffer) &&
1558       dvdemux->frames_since_new_media > 2) {
1559     dvdemux->new_media = TRUE;
1560     dvdemux->frames_since_new_media = 0;
1561   }
1562   dvdemux->frames_since_new_media++;
1563
1564   /* does not take ownership of buffer */
1565   aret = ret = gst_dvdemux_demux_audio (dvdemux, buffer, duration);
1566   if (G_UNLIKELY (ret != GST_FLOW_OK && ret != GST_FLOW_NOT_LINKED)) {
1567     gst_buffer_unref (buffer);
1568     goto done;
1569   }
1570
1571   /* takes ownership of buffer */
1572   vret = ret = gst_dvdemux_demux_video (dvdemux, buffer, duration);
1573   if (G_UNLIKELY (ret != GST_FLOW_OK && ret != GST_FLOW_NOT_LINKED))
1574     goto done;
1575
1576   /* if both are not linked, we stop */
1577   if (G_UNLIKELY (aret == GST_FLOW_NOT_LINKED && vret == GST_FLOW_NOT_LINKED)) {
1578     ret = GST_FLOW_NOT_LINKED;
1579     goto done;
1580   }
1581
1582   dvdemux->discont = FALSE;
1583   dvdemux->time_segment.position = next_ts;
1584
1585   if (dvdemux->time_segment.rate < 0) {
1586     if (dvdemux->frame_offset > 0)
1587       dvdemux->frame_offset--;
1588     else
1589       GST_WARNING_OBJECT (dvdemux,
1590           "Got before frame offset 0 in reverse playback");
1591   } else {
1592     dvdemux->frame_offset++;
1593   }
1594
1595   /* check for the end of the segment */
1596   if ((dvdemux->time_segment.rate > 0 && dvdemux->time_segment.stop != -1
1597           && next_ts > dvdemux->time_segment.stop)
1598       || (dvdemux->time_segment.rate < 0
1599           && dvdemux->time_segment.start > next_ts))
1600     ret = GST_FLOW_EOS;
1601   else
1602     ret = GST_FLOW_OK;
1603
1604 done:
1605   return ret;
1606
1607   /* ERRORS */
1608 segment_error:
1609   {
1610     GST_DEBUG ("error generating new_segment event");
1611     gst_buffer_unref (buffer);
1612     return GST_FLOW_ERROR;
1613   }
1614 }
1615
1616 /* flush any remaining data in the adapter, used in chain based scheduling mode */
1617 static GstFlowReturn
1618 gst_dvdemux_flush (GstDVDemux * dvdemux)
1619 {
1620   GstFlowReturn ret = GST_FLOW_OK;
1621
1622   while (gst_adapter_available (dvdemux->adapter) >= dvdemux->frame_len) {
1623     const guint8 *data;
1624     gint length;
1625
1626     /* get the accumulated bytes */
1627     data = gst_adapter_map (dvdemux->adapter, dvdemux->frame_len);
1628
1629     /* parse header to know the length and other params */
1630     if (G_UNLIKELY (dv_parse_header (dvdemux->decoder, data) < 0)) {
1631       gst_adapter_unmap (dvdemux->adapter);
1632       goto parse_header_error;
1633     }
1634     gst_adapter_unmap (dvdemux->adapter);
1635
1636     /* after parsing the header we know the length of the data */
1637     length = dvdemux->frame_len = dvdemux->decoder->frame_size;
1638     if (dvdemux->decoder->system == e_dv_system_625_50) {
1639       dvdemux->framerate_numerator = PAL_FRAMERATE_NUMERATOR;
1640       dvdemux->framerate_denominator = PAL_FRAMERATE_DENOMINATOR;
1641     } else {
1642       dvdemux->framerate_numerator = NTSC_FRAMERATE_NUMERATOR;
1643       dvdemux->framerate_denominator = NTSC_FRAMERATE_DENOMINATOR;
1644     }
1645     g_atomic_int_set (&dvdemux->found_header, 1);
1646
1647     /* let demux_video set the height, it needs to detect when things change so
1648      * it can reset caps */
1649
1650     /* if we still have enough for a frame, start decoding */
1651     if (G_LIKELY (gst_adapter_available (dvdemux->adapter) >= length)) {
1652       GstBuffer *buffer;
1653
1654       buffer = gst_adapter_take_buffer (dvdemux->adapter, length);
1655
1656       /* and decode the buffer, takes ownership */
1657       ret = gst_dvdemux_demux_frame (dvdemux, buffer);
1658       if (G_UNLIKELY (ret != GST_FLOW_OK))
1659         goto done;
1660     }
1661   }
1662 done:
1663   return ret;
1664
1665   /* ERRORS */
1666 parse_header_error:
1667   {
1668     GST_ELEMENT_ERROR (dvdemux, STREAM, DECODE,
1669         (NULL), ("Error parsing DV header"));
1670     return GST_FLOW_ERROR;
1671   }
1672 }
1673
1674 /* streaming operation: 
1675  *
1676  * accumulate data until we have a frame, then decode. 
1677  */
1678 static GstFlowReturn
1679 gst_dvdemux_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
1680 {
1681   GstDVDemux *dvdemux;
1682   GstFlowReturn ret;
1683   GstClockTime timestamp;
1684
1685   dvdemux = GST_DVDEMUX (parent);
1686
1687   /* a discontinuity in the stream, we need to get rid of
1688    * accumulated data in the adapter and assume a new frame
1689    * starts after the discontinuity */
1690   if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
1691     gst_adapter_clear (dvdemux->adapter);
1692     dvdemux->discont = TRUE;
1693
1694     /* Should recheck where we are */
1695     if (!dvdemux->upstream_time_segment)
1696       dvdemux->need_segment = TRUE;
1697   }
1698
1699   /* a timestamp always should be respected */
1700   timestamp = GST_BUFFER_TIMESTAMP (buffer);
1701   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
1702     dvdemux->time_segment.position = timestamp;
1703
1704     if (dvdemux->discont)
1705       gst_dvdemux_update_frame_offsets (dvdemux,
1706           dvdemux->time_segment.position);
1707   } else if (dvdemux->upstream_time_segment && dvdemux->discont) {
1708     /* This will probably fail later to provide correct
1709      * timestamps and/or durations but also should not happen */
1710     GST_ERROR_OBJECT (dvdemux,
1711         "Upstream provides TIME segment but no PTS after discont");
1712   }
1713
1714   gst_adapter_push (dvdemux->adapter, buffer);
1715
1716   /* Apparently dv_parse_header can read from the body of the frame
1717    * too, so it needs more than header_size bytes. Wacky!
1718    */
1719   if (G_UNLIKELY (dvdemux->frame_len == -1)) {
1720     /* if we don't know the length of a frame, we assume it is
1721      * the NTSC_BUFFER length, as this is enough to figure out 
1722      * if this is PAL or NTSC */
1723     dvdemux->frame_len = NTSC_BUFFER;
1724   }
1725
1726   /* and try to flush pending frames */
1727   ret = gst_dvdemux_flush (dvdemux);
1728
1729   return ret;
1730 }
1731
1732 /* pull based operation.
1733  *
1734  * Read header first to figure out the frame size. Then read
1735  * and decode full frames.
1736  */
1737 static void
1738 gst_dvdemux_loop (GstPad * pad)
1739 {
1740   GstFlowReturn ret;
1741   GstDVDemux *dvdemux;
1742   GstBuffer *buffer = NULL;
1743   GstMapInfo map;
1744
1745   dvdemux = GST_DVDEMUX (gst_pad_get_parent (pad));
1746
1747   if (G_UNLIKELY (g_atomic_int_get (&dvdemux->found_header) == 0)) {
1748     GST_DEBUG_OBJECT (dvdemux, "pulling first buffer");
1749     /* pull in NTSC sized buffer to figure out the frame
1750      * length */
1751     ret = gst_pad_pull_range (dvdemux->sinkpad,
1752         dvdemux->byte_segment.position, NTSC_BUFFER, &buffer);
1753     if (G_UNLIKELY (ret != GST_FLOW_OK))
1754       goto pause;
1755
1756     /* check buffer size, don't want to read small buffers */
1757     if (G_UNLIKELY (gst_buffer_get_size (buffer) < NTSC_BUFFER))
1758       goto small_buffer;
1759
1760     gst_buffer_map (buffer, &map, GST_MAP_READ);
1761     /* parse header to know the length and other params */
1762     if (G_UNLIKELY (dv_parse_header (dvdemux->decoder, map.data) < 0)) {
1763       gst_buffer_unmap (buffer, &map);
1764       goto parse_header_error;
1765     }
1766     gst_buffer_unmap (buffer, &map);
1767
1768     /* after parsing the header we know the length of the data */
1769     dvdemux->frame_len = dvdemux->decoder->frame_size;
1770     if (dvdemux->decoder->system == e_dv_system_625_50) {
1771       dvdemux->framerate_numerator = PAL_FRAMERATE_NUMERATOR;
1772       dvdemux->framerate_denominator = PAL_FRAMERATE_DENOMINATOR;
1773     } else {
1774       dvdemux->framerate_numerator = NTSC_FRAMERATE_NUMERATOR;
1775       dvdemux->framerate_denominator = NTSC_FRAMERATE_DENOMINATOR;
1776     }
1777     dvdemux->need_segment = TRUE;
1778
1779     /* see if we need to read a larger part */
1780     if (dvdemux->frame_len != NTSC_BUFFER) {
1781       gst_buffer_unref (buffer);
1782       buffer = NULL;
1783     }
1784
1785     {
1786       GstEvent *event;
1787
1788       /* setting header and prrforming the seek must be atomic */
1789       GST_OBJECT_LOCK (dvdemux);
1790       /* got header now */
1791       g_atomic_int_set (&dvdemux->found_header, 1);
1792
1793       /* now perform pending seek if any. */
1794       event = dvdemux->seek_event;
1795       if (event)
1796         gst_event_ref (event);
1797       GST_OBJECT_UNLOCK (dvdemux);
1798
1799       if (event) {
1800         if (!gst_dvdemux_handle_pull_seek (dvdemux, dvdemux->videosrcpad,
1801                 event)) {
1802           GST_ELEMENT_WARNING (dvdemux, STREAM, DECODE, (NULL),
1803               ("Error perfoming initial seek"));
1804         }
1805         gst_event_unref (event);
1806
1807         /* and we need to pull a new buffer in all cases. */
1808         if (buffer) {
1809           gst_buffer_unref (buffer);
1810           buffer = NULL;
1811         }
1812       }
1813     }
1814   }
1815
1816   if (G_UNLIKELY (dvdemux->pending_segment)) {
1817
1818     /* now send the newsegment */
1819     GST_DEBUG_OBJECT (dvdemux, "Sending newsegment from");
1820
1821     gst_dvdemux_push_event (dvdemux, dvdemux->pending_segment);
1822     dvdemux->pending_segment = NULL;
1823   }
1824
1825   if (G_LIKELY (buffer == NULL)) {
1826     GST_DEBUG_OBJECT (dvdemux, "pulling buffer at offset %" G_GINT64_FORMAT,
1827         dvdemux->byte_segment.position);
1828
1829     ret = gst_pad_pull_range (dvdemux->sinkpad,
1830         dvdemux->byte_segment.position, dvdemux->frame_len, &buffer);
1831     if (ret != GST_FLOW_OK)
1832       goto pause;
1833
1834     /* check buffer size, don't want to read small buffers */
1835     if (gst_buffer_get_size (buffer) < dvdemux->frame_len)
1836       goto small_buffer;
1837   }
1838   /* and decode the buffer */
1839   ret = gst_dvdemux_demux_frame (dvdemux, buffer);
1840   if (G_UNLIKELY (ret != GST_FLOW_OK))
1841     goto pause;
1842
1843   /* and position ourselves for the next buffer */
1844   dvdemux->byte_segment.position += dvdemux->frame_len;
1845
1846 done:
1847   gst_object_unref (dvdemux);
1848
1849   return;
1850
1851   /* ERRORS */
1852 parse_header_error:
1853   {
1854     GstEvent *event;
1855
1856     GST_ELEMENT_ERROR (dvdemux, STREAM, DECODE,
1857         (NULL), ("Error parsing DV header"));
1858     gst_buffer_unref (buffer);
1859     gst_pad_pause_task (dvdemux->sinkpad);
1860     event = gst_event_new_eos ();
1861     if (dvdemux->segment_seqnum)
1862       gst_event_set_seqnum (event, dvdemux->segment_seqnum);
1863     gst_dvdemux_push_event (dvdemux, event);
1864     goto done;
1865   }
1866 small_buffer:
1867   {
1868     GstEvent *event;
1869
1870     GST_ELEMENT_ERROR (dvdemux, STREAM, DECODE,
1871         (NULL), ("Error reading buffer"));
1872     gst_buffer_unref (buffer);
1873     gst_pad_pause_task (dvdemux->sinkpad);
1874     event = gst_event_new_eos ();
1875     if (dvdemux->segment_seqnum)
1876       gst_event_set_seqnum (event, dvdemux->segment_seqnum);
1877     gst_dvdemux_push_event (dvdemux, event);
1878     goto done;
1879   }
1880 pause:
1881   {
1882     GST_INFO_OBJECT (dvdemux, "pausing task, %s", gst_flow_get_name (ret));
1883     gst_pad_pause_task (dvdemux->sinkpad);
1884     if (ret == GST_FLOW_EOS) {
1885       GST_LOG_OBJECT (dvdemux, "got eos");
1886       /* so align our position with the end of it, if there is one
1887        * this ensures a subsequent will arrive at correct base/acc time */
1888       if (dvdemux->time_segment.rate > 0.0 &&
1889           GST_CLOCK_TIME_IS_VALID (dvdemux->time_segment.stop))
1890         dvdemux->time_segment.position = dvdemux->time_segment.stop;
1891       else if (dvdemux->time_segment.rate < 0.0)
1892         dvdemux->time_segment.position = dvdemux->time_segment.start;
1893       /* perform EOS logic */
1894       if (dvdemux->time_segment.flags & GST_SEEK_FLAG_SEGMENT) {
1895         GstMessage *message;
1896         GstEvent *event;
1897
1898         event = gst_event_new_segment_done (dvdemux->time_segment.format,
1899             dvdemux->time_segment.position);
1900         if (dvdemux->segment_seqnum)
1901           gst_event_set_seqnum (event, dvdemux->segment_seqnum);
1902
1903         message = gst_message_new_segment_done (GST_OBJECT_CAST (dvdemux),
1904             dvdemux->time_segment.format, dvdemux->time_segment.position);
1905         if (dvdemux->segment_seqnum)
1906           gst_message_set_seqnum (message, dvdemux->segment_seqnum);
1907
1908         gst_element_post_message (GST_ELEMENT (dvdemux), message);
1909         gst_dvdemux_push_event (dvdemux, event);
1910       } else {
1911         GstEvent *event = gst_event_new_eos ();
1912         if (dvdemux->segment_seqnum)
1913           gst_event_set_seqnum (event, dvdemux->segment_seqnum);
1914         gst_dvdemux_push_event (dvdemux, event);
1915       }
1916     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
1917       GstEvent *event = gst_event_new_eos ();
1918       /* for fatal errors or not-linked we post an error message */
1919       GST_ELEMENT_FLOW_ERROR (dvdemux, ret);
1920       if (dvdemux->segment_seqnum)
1921         gst_event_set_seqnum (event, dvdemux->segment_seqnum);
1922       gst_dvdemux_push_event (dvdemux, event);
1923     }
1924     goto done;
1925   }
1926 }
1927
1928 static gboolean
1929 gst_dvdemux_sink_activate_mode (GstPad * sinkpad, GstObject * parent,
1930     GstPadMode mode, gboolean active)
1931 {
1932   gboolean res;
1933   GstDVDemux *demux = GST_DVDEMUX (parent);
1934
1935   switch (mode) {
1936     case GST_PAD_MODE_PULL:
1937       if (active) {
1938         demux->seek_handler = gst_dvdemux_handle_pull_seek;
1939         res = gst_pad_start_task (sinkpad,
1940             (GstTaskFunction) gst_dvdemux_loop, sinkpad, NULL);
1941       } else {
1942         demux->seek_handler = NULL;
1943         res = gst_pad_stop_task (sinkpad);
1944       }
1945       break;
1946     case GST_PAD_MODE_PUSH:
1947       if (active) {
1948         GST_DEBUG_OBJECT (demux, "activating push/chain function");
1949         demux->seek_handler = gst_dvdemux_handle_push_seek;
1950       } else {
1951         GST_DEBUG_OBJECT (demux, "deactivating push/chain function");
1952         demux->seek_handler = NULL;
1953       }
1954       res = TRUE;
1955       break;
1956     default:
1957       res = FALSE;
1958       break;
1959   }
1960   return res;
1961 }
1962
1963 /* decide on push or pull based scheduling */
1964 static gboolean
1965 gst_dvdemux_sink_activate (GstPad * sinkpad, GstObject * parent)
1966 {
1967   GstQuery *query;
1968   gboolean pull_mode;
1969
1970   query = gst_query_new_scheduling ();
1971
1972   if (!gst_pad_peer_query (sinkpad, query)) {
1973     gst_query_unref (query);
1974     goto activate_push;
1975   }
1976
1977   pull_mode = gst_query_has_scheduling_mode_with_flags (query,
1978       GST_PAD_MODE_PULL, GST_SCHEDULING_FLAG_SEEKABLE);
1979   gst_query_unref (query);
1980
1981   if (!pull_mode)
1982     goto activate_push;
1983
1984   GST_DEBUG_OBJECT (sinkpad, "activating pull");
1985   return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
1986
1987 activate_push:
1988   {
1989     GST_DEBUG_OBJECT (sinkpad, "activating push");
1990     return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
1991   }
1992 }
1993
1994 static GstStateChangeReturn
1995 gst_dvdemux_change_state (GstElement * element, GstStateChange transition)
1996 {
1997   GstDVDemux *dvdemux = GST_DVDEMUX (element);
1998   GstStateChangeReturn ret;
1999
2000   switch (transition) {
2001     case GST_STATE_CHANGE_NULL_TO_READY:
2002       break;
2003     case GST_STATE_CHANGE_READY_TO_PAUSED:
2004       dvdemux->decoder = dv_decoder_new (0, FALSE, FALSE);
2005       dv_set_error_log (dvdemux->decoder, NULL);
2006       gst_dvdemux_reset (dvdemux);
2007       break;
2008     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2009       break;
2010     default:
2011       break;
2012   }
2013
2014   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2015
2016   switch (transition) {
2017     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2018       break;
2019     case GST_STATE_CHANGE_PAUSED_TO_READY:
2020       gst_adapter_clear (dvdemux->adapter);
2021       dv_decoder_free (dvdemux->decoder);
2022       dvdemux->decoder = NULL;
2023
2024       gst_dvdemux_remove_pads (dvdemux);
2025
2026       if (dvdemux->tag_event) {
2027         gst_event_unref (dvdemux->tag_event);
2028         dvdemux->tag_event = NULL;
2029       }
2030
2031       break;
2032     case GST_STATE_CHANGE_READY_TO_NULL:
2033     {
2034       GstEvent **event_p;
2035
2036       event_p = &dvdemux->seek_event;
2037       gst_event_replace (event_p, NULL);
2038       if (dvdemux->pending_segment)
2039         gst_event_unref (dvdemux->pending_segment);
2040       dvdemux->pending_segment = NULL;
2041       break;
2042     }
2043     default:
2044       break;
2045   }
2046   return ret;
2047 }