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