Various event updates and cleanups.
[platform/upstream/gst-plugins-good.git] / ext / dv / gstdvdec.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 /* First, include the header file for the plugin, to bring in the
28  * object definition and other useful things.
29  */
30 #include "gstdvdec.h"
31
32 /* DV output has two modes, normal and wide. The resolution is the same in both
33  * cases: 720 pixels wide by 576 pixels tall in PAL format, and 720x480 for
34  * NTSC.
35  *
36  * Each of the modes has its own pixel aspect ratio, which is fixed in practice
37  * by ITU-R BT.601 (also known as "CCIR-601" or "Rec.601"). Or so claims a
38  * reference that I culled from the reliable "internet",
39  * http://www.mir.com/DMG/aspect.html. Normal PAL is 59/54 and normal NTSC is
40  * 10/11. Because the pixel resolution is the same for both cases, we can get
41  * the pixel aspect ratio for wide recordings by multiplying by the ratio of
42  * display aspect ratios, 16/9 (for wide) divided by 4/3 (for normal):
43  *
44  * Wide NTSC: 10/11 * (16/9)/(4/3) = 40/33
45  * Wide PAL: 59/54 * (16/9)/(4/3) = 118/81
46  *
47  * However, the pixel resolution coming out of a DV source does not combine with
48  * the standard pixel aspect ratios to give a proper display aspect ratio. An
49  * image 480 pixels tall, with a 4:3 display aspect ratio, will be 768 pixels
50  * wide. But, if we take the normal PAL aspect ratio of 59/54, and multiply it
51  * with the width of the DV image (720 pixels), we get 786.666..., which is
52  * nonintegral and too wide. The camera is not outputting a 4:3 image.
53  * 
54  * If the video sink for this stream has fixed dimensions (such as for
55  * fullscreen playback, or for a java applet in a web page), you then have two
56  * choices. Either you show the whole image, but pad the image with black
57  * borders on the top and bottom (like watching a widescreen video on a 4:3
58  * device), or you crop the video to the proper ratio. Apparently the latter is
59  * the standard practice.
60  *
61  * For its part, GStreamer is concerned with accuracy and preservation of
62  * information. This element outputs the 720x576 or 720x480 video that it
63  * recieves, noting the proper aspect ratio. This should not be a problem for
64  * windowed applications, which can change size to fit the video. Applications
65  * with fixed size requirements should decide whether to crop or pad which
66  * an element such as videobox can do.
67  */
68
69 #define NTSC_HEIGHT 480
70 #define NTSC_BUFFER 120000
71 #define NTSC_FRAMERATE 30000/1001.
72
73 #define PAL_HEIGHT 576
74 #define PAL_BUFFER 144000
75 #define PAL_FRAMERATE 25.0
76
77 #define PAL_NORMAL_PAR_X        59
78 #define PAL_NORMAL_PAR_Y        54
79 #define PAL_WIDE_PAR_X          118
80 #define PAL_WIDE_PAR_Y          81
81
82 #define NTSC_NORMAL_PAR_X       10
83 #define NTSC_NORMAL_PAR_Y       11
84 #define NTSC_WIDE_PAR_X         40
85 #define NTSC_WIDE_PAR_Y         33
86
87 /* The ElementDetails structure gives a human-readable description
88  * of the plugin, as well as author and version data.
89  */
90 static GstElementDetails dvdec_details =
91 GST_ELEMENT_DETAILS ("DV (smpte314) decoder plugin",
92     "Codec/Decoder/Video",
93     "Uses libdv to decode DV video (libdv.sourceforge.net)",
94     "Erik Walthinsen <omega@cse.ogi.edu>," "Wim Taymans <wim@fluendo.com>");
95
96
97 /* These are the signals that this element can fire.  They are zero-
98  * based because the numbers themselves are private to the object.
99  * LAST_SIGNAL is used for initialization of the signal array.
100  */
101 enum
102 {
103   /* FILL ME */
104   LAST_SIGNAL
105 };
106
107 #define DV_DEFAULT_QUALITY DV_QUALITY_BEST
108 #define DV_DEFAULT_DECODE_NTH 1
109
110 /* Arguments are identified the same way, but cannot be zero, so you
111  * must leave the ARG_0 entry in as a placeholder.
112  */
113 enum
114 {
115   ARG_0,
116   ARG_CLAMP_LUMA,
117   ARG_CLAMP_CHROMA,
118   ARG_QUALITY,
119   ARG_DECODE_NTH
120       /* FILL ME */
121 };
122
123 const gint qualities[] = {
124   DV_QUALITY_DC,
125   DV_QUALITY_AC_1,
126   DV_QUALITY_AC_2,
127   DV_QUALITY_DC | DV_QUALITY_COLOR,
128   DV_QUALITY_AC_1 | DV_QUALITY_COLOR,
129   DV_QUALITY_AC_2 | DV_QUALITY_COLOR
130 };
131
132 /* The PadFactory structures describe what pads the element has or
133  * can have.  They can be quite complex, but for this dvdec plugin
134  * they are rather simple.
135  */
136 static GstStaticPadTemplate sink_temp = GST_STATIC_PAD_TEMPLATE ("sink",
137     GST_PAD_SINK,
138     GST_PAD_ALWAYS,
139     GST_STATIC_CAPS ("video/x-dv, systemstream = (boolean) true")
140     );
141
142 static GstStaticPadTemplate video_src_temp = GST_STATIC_PAD_TEMPLATE ("video",
143     GST_PAD_SRC,
144     GST_PAD_ALWAYS,
145     GST_STATIC_CAPS ("video/x-raw-yuv, "
146         "format = (fourcc) YUY2, "
147         "width = (int) 720, "
148         "height = (int) { "
149         G_STRINGIFY (NTSC_HEIGHT) ", " G_STRINGIFY (PAL_HEIGHT)
150         " }, "
151         "pixel-aspect-ratio=(fraction) { "
152         G_STRINGIFY (PAL_NORMAL_PAR_X) "/" G_STRINGIFY (PAL_NORMAL_PAR_Y) ","
153         G_STRINGIFY (PAL_WIDE_PAR_X) "/" G_STRINGIFY (PAL_WIDE_PAR_Y) ","
154         G_STRINGIFY (NTSC_NORMAL_PAR_X) "/" G_STRINGIFY (NTSC_NORMAL_PAR_Y) ","
155         G_STRINGIFY (NTSC_WIDE_PAR_X) "/" G_STRINGIFY (NTSC_WIDE_PAR_Y) "},"
156         "framerate = (double) [ 1.0, 60.0 ];"
157         "video/x-raw-rgb, "
158         "bpp = (int) 32, "
159         "depth = (int) 24, "
160         "endianness = (int) " G_STRINGIFY (G_BIG_ENDIAN) ", "
161         "red_mask =   (int) 0x0000ff00, "
162         "green_mask = (int) 0x00ff0000, "
163         "blue_mask =  (int) 0xff000000, "
164         "width = (int) 720, "
165         "height = (int) { "
166         G_STRINGIFY (NTSC_HEIGHT) ", " G_STRINGIFY (PAL_HEIGHT)
167         " }, "
168         "pixel-aspect-ratio=(fraction) { "
169         G_STRINGIFY (PAL_NORMAL_PAR_X) "/" G_STRINGIFY (PAL_NORMAL_PAR_Y) ","
170         G_STRINGIFY (PAL_WIDE_PAR_X) "/" G_STRINGIFY (PAL_WIDE_PAR_Y) ","
171         G_STRINGIFY (NTSC_NORMAL_PAR_X) "/" G_STRINGIFY (NTSC_NORMAL_PAR_Y) ","
172         G_STRINGIFY (NTSC_WIDE_PAR_X) "/" G_STRINGIFY (NTSC_WIDE_PAR_Y) "},"
173         "framerate = (double) [ 1.0, 60.0 ];"
174         "video/x-raw-rgb, "
175         "bpp = (int) 24, "
176         "depth = (int) 24, "
177         "endianness = (int) " G_STRINGIFY (G_BIG_ENDIAN) ", "
178         "red_mask =   (int) 0x00ff0000, "
179         "green_mask = (int) 0x0000ff00, "
180         "blue_mask =  (int) 0x000000ff, "
181         "width = (int) 720, "
182         "height = (int) { "
183         G_STRINGIFY (NTSC_HEIGHT) ", " G_STRINGIFY (PAL_HEIGHT)
184         " }, "
185         "pixel-aspect-ratio=(fraction) { "
186         G_STRINGIFY (PAL_NORMAL_PAR_X) "/" G_STRINGIFY (PAL_NORMAL_PAR_Y) ","
187         G_STRINGIFY (PAL_WIDE_PAR_X) "/" G_STRINGIFY (PAL_WIDE_PAR_Y) ","
188         G_STRINGIFY (NTSC_NORMAL_PAR_X) "/" G_STRINGIFY (NTSC_NORMAL_PAR_Y) ","
189         G_STRINGIFY (NTSC_WIDE_PAR_X) "/" G_STRINGIFY (NTSC_WIDE_PAR_Y) "},"
190         "framerate = (double) [ 1.0, 60.0 ]")
191     );
192
193 static GstStaticPadTemplate audio_src_temp = GST_STATIC_PAD_TEMPLATE ("audio",
194     GST_PAD_SRC,
195     GST_PAD_ALWAYS,
196     GST_STATIC_CAPS ("audio/x-raw-int, "
197         "depth = (int) 16, "
198         "width = (int) 16, "
199         "signed = (boolean) TRUE, "
200         "channels = (int) {2, 4}, "
201         "endianness = (int) " G_STRINGIFY (G_LITTLE_ENDIAN) ", "
202         "rate = (int) { 32000, 44100, 48000 }")
203     );
204
205 #define GST_TYPE_DVDEC_QUALITY (gst_dvdec_quality_get_type())
206 GType
207 gst_dvdec_quality_get_type (void)
208 {
209   static GType qtype = 0;
210
211   if (qtype == 0) {
212     static const GEnumValue values[] = {
213       {0, "DV_QUALITY_FASTEST", "Fastest decoding, low-quality mono"},
214       {1, "DV_QUALITY_AC_1", "Mono decoding using the first AC coefficient"},
215       {2, "DV_QUALITY_AC_2", "Highest quality mono decoding"},
216       {3, "DV_QUALITY_DC|DV_QUALITY_COLOUR", "Fastest colour decoding"},
217       {4, "DV_QUALITY_AC_1|DV_QUALITY_COLOUR",
218           "Colour, using only the first AC coefficient"},
219       {5, "DV_QUALITY_BEST", "Highest quality colour decoding"},
220       {0, NULL, NULL},
221     };
222
223     qtype = g_enum_register_static ("GstDVDecQualityEnum", values);
224   }
225   return qtype;
226 }
227
228 /* A number of functon prototypes are given so we can refer to them later. */
229 static void gst_dvdec_base_init (gpointer g_class);
230 static void gst_dvdec_class_init (GstDVDecClass * klass);
231 static void gst_dvdec_init (GstDVDec * dvdec);
232
233 static const GstQueryType *gst_dvdec_get_src_query_types (GstPad * pad);
234 static gboolean gst_dvdec_src_query (GstPad * pad, GstQuery * query);
235 static const GstQueryType *gst_dvdec_get_sink_query_types (GstPad * pad);
236 static gboolean gst_dvdec_sink_query (GstPad * pad, GstQuery * query);
237
238 #if 0
239 static const GstFormat *gst_dvdec_get_formats (GstPad * pad);
240 #endif
241 static gboolean gst_dvdec_sink_convert (GstPad * pad, GstFormat src_format,
242     gint64 src_value, GstFormat * dest_format, gint64 * dest_value);
243 static gboolean gst_dvdec_src_convert (GstPad * pad, GstFormat src_format,
244     gint64 src_value, GstFormat * dest_format, gint64 * dest_value);
245
246 static gboolean gst_dvdec_video_setcaps (GstPad * pad, GstCaps * caps);
247 static GstCaps *gst_dvdec_video_getcaps (GstPad * pad);
248
249 #if 0
250 static const GstEventMask *gst_dvdec_get_event_masks (GstPad * pad);
251 #endif
252 static gboolean gst_dvdec_handle_src_event (GstPad * pad, GstEvent * event);
253 static GstFlowReturn gst_dvdec_flush (GstDVDec * dvdec);
254 static GstFlowReturn gst_dvdec_chain (GstPad * pad, GstBuffer * buffer);
255 static gboolean gst_dvdec_handle_sink_event (GstPad * pad, GstEvent * event);
256
257 static GstElementStateReturn gst_dvdec_change_state (GstElement * element);
258
259 static void gst_dvdec_set_property (GObject * object, guint prop_id,
260     const GValue * value, GParamSpec * pspec);
261 static void gst_dvdec_get_property (GObject * object, guint prop_id,
262     GValue * value, GParamSpec * pspec);
263
264 /* The parent class pointer needs to be kept around for some object
265  * operations.
266  */
267 static GstElementClass *parent_class = NULL;
268
269 /* This array holds the ids of the signals registered for this object.
270  * The array indexes are based on the enum up above.
271  */
272 /*static guint gst_dvdec_signals[LAST_SIGNAL] = { 0 }; */
273
274 /* This function is used to register and subsequently return the type
275  * identifier for this object class.  On first invocation, it will
276  * register the type, providing the name of the class, struct sizes,
277  * and pointers to the various functions that define the class.
278  */
279 GType
280 gst_dvdec_get_type (void)
281 {
282   static GType dvdec_type = 0;
283
284   if (!dvdec_type) {
285     static const GTypeInfo dvdec_info = {
286       sizeof (GstDVDecClass),
287       gst_dvdec_base_init,
288       NULL,
289       (GClassInitFunc) gst_dvdec_class_init,
290       NULL,
291       NULL,
292       sizeof (GstDVDec),
293       0,
294       (GInstanceInitFunc) gst_dvdec_init,
295     };
296
297     dvdec_type =
298         g_type_register_static (GST_TYPE_ELEMENT, "GstDVDec", &dvdec_info, 0);
299   }
300   return dvdec_type;
301 }
302
303 static void
304 gst_dvdec_base_init (gpointer g_class)
305 {
306   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
307
308   /* The pad templates can be easily generated from the factories above,
309    * and then added to the list of padtemplates for the elementfactory.
310    * Note that the generated padtemplates are stored in static global
311    * variables, for the gst_dvdec_init function to use later on.
312    */
313   gst_element_class_add_pad_template (element_class,
314       gst_static_pad_template_get (&sink_temp));
315   gst_element_class_add_pad_template (element_class,
316       gst_static_pad_template_get (&video_src_temp));
317   gst_element_class_add_pad_template (element_class,
318       gst_static_pad_template_get (&audio_src_temp));
319
320   gst_element_class_set_details (element_class, &dvdec_details);
321 }
322
323 /* In order to create an instance of an object, the class must be
324  * initialized by this function.  GObject will take care of running
325  * it, based on the pointer to the function provided above.
326  */
327 static void
328 gst_dvdec_class_init (GstDVDecClass * klass)
329 {
330   /* Class pointers are needed to supply pointers to the private
331    * implementations of parent class methods.
332    */
333   GObjectClass *gobject_class;
334   GstElementClass *gstelement_class;
335
336   /* Since the dvdec class contains the parent classes, you can simply
337    * cast the pointer to get access to the parent classes.
338    */
339   gobject_class = (GObjectClass *) klass;
340   gstelement_class = (GstElementClass *) klass;
341
342   gobject_class->set_property = gst_dvdec_set_property;
343   gobject_class->get_property = gst_dvdec_get_property;
344
345   /* The parent class is needed for class method overrides. */
346   parent_class = g_type_class_ref (GST_TYPE_ELEMENT);
347
348   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_CLAMP_LUMA,
349       g_param_spec_boolean ("clamp_luma", "Clamp luma", "Clamp luma",
350           FALSE, G_PARAM_READWRITE));
351   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_CLAMP_CHROMA,
352       g_param_spec_boolean ("clamp_chroma", "Clamp chroma", "Clamp chroma",
353           FALSE, G_PARAM_READWRITE));
354   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_QUALITY,
355       g_param_spec_enum ("quality", "Quality", "Decoding quality",
356           GST_TYPE_DVDEC_QUALITY, DV_DEFAULT_QUALITY, G_PARAM_READWRITE));
357   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_DECODE_NTH,
358       g_param_spec_int ("drop-factor", "Drop Factor", "Only decode Nth frame",
359           1, G_MAXINT, DV_DEFAULT_DECODE_NTH, G_PARAM_READWRITE));
360
361   gstelement_class->change_state = gst_dvdec_change_state;
362
363   /* table initialization, only do once */
364   dv_init (0, 0);
365 }
366
367 /* This function is responsible for initializing a specific instance of
368  * the plugin.
369  */
370 static void
371 gst_dvdec_init (GstDVDec * dvdec)
372 {
373   gint i;
374
375   dvdec->sinkpad =
376       gst_pad_new_from_template (gst_static_pad_template_get (&sink_temp),
377       "sink");
378   gst_pad_set_chain_function (dvdec->sinkpad, gst_dvdec_chain);
379   gst_pad_set_event_function (dvdec->sinkpad, gst_dvdec_handle_sink_event);
380   gst_pad_set_query_function (dvdec->sinkpad,
381       GST_DEBUG_FUNCPTR (gst_dvdec_sink_query));
382   gst_pad_set_query_type_function (dvdec->sinkpad,
383       GST_DEBUG_FUNCPTR (gst_dvdec_get_sink_query_types));
384 #if 0
385   gst_pad_set_formats_function (dvdec->sinkpad,
386       GST_DEBUG_FUNCPTR (gst_dvdec_get_formats));
387 #endif
388   gst_element_add_pad (GST_ELEMENT (dvdec), dvdec->sinkpad);
389
390   dvdec->videosrcpad =
391       gst_pad_new_from_template (gst_static_pad_template_get (&video_src_temp),
392       "video");
393   gst_pad_set_query_function (dvdec->videosrcpad,
394       GST_DEBUG_FUNCPTR (gst_dvdec_src_query));
395   gst_pad_set_query_type_function (dvdec->videosrcpad,
396       GST_DEBUG_FUNCPTR (gst_dvdec_get_src_query_types));
397   gst_pad_set_event_function (dvdec->videosrcpad,
398       GST_DEBUG_FUNCPTR (gst_dvdec_handle_src_event));
399 #if 0
400   gst_pad_set_event_mask_function (dvdec->videosrcpad,
401       GST_DEBUG_FUNCPTR (gst_dvdec_get_event_masks));
402   gst_pad_set_formats_function (dvdec->videosrcpad,
403       GST_DEBUG_FUNCPTR (gst_dvdec_get_formats));
404 #endif
405   gst_pad_set_getcaps_function (dvdec->videosrcpad,
406       GST_DEBUG_FUNCPTR (gst_dvdec_video_getcaps));
407   gst_pad_set_setcaps_function (dvdec->videosrcpad,
408       GST_DEBUG_FUNCPTR (gst_dvdec_video_setcaps));
409   gst_element_add_pad (GST_ELEMENT (dvdec), dvdec->videosrcpad);
410
411   dvdec->audiosrcpad =
412       gst_pad_new_from_template (gst_static_pad_template_get (&audio_src_temp),
413       "audio");
414   gst_pad_set_query_function (dvdec->audiosrcpad,
415       GST_DEBUG_FUNCPTR (gst_dvdec_src_query));
416   gst_pad_set_query_type_function (dvdec->audiosrcpad,
417       GST_DEBUG_FUNCPTR (gst_dvdec_get_src_query_types));
418   gst_pad_set_event_function (dvdec->audiosrcpad,
419       GST_DEBUG_FUNCPTR (gst_dvdec_handle_src_event));
420 #if 0
421   gst_pad_set_event_mask_function (dvdec->audiosrcpad,
422       GST_DEBUG_FUNCPTR (gst_dvdec_get_event_masks));
423   gst_pad_set_formats_function (dvdec->audiosrcpad,
424       GST_DEBUG_FUNCPTR (gst_dvdec_get_formats));
425 #endif
426
427   /* once we set caps, this is the only thing we can do */
428   gst_pad_use_fixed_caps (dvdec->audiosrcpad);
429   gst_element_add_pad (GST_ELEMENT (dvdec), dvdec->audiosrcpad);
430
431   dvdec->adapter = gst_adapter_new ();
432
433   dvdec->timestamp = 0LL;
434
435   dvdec->start_timestamp = -1LL;
436   dvdec->stop_timestamp = -1LL;
437   dvdec->need_discont = FALSE;
438   dvdec->new_media = FALSE;
439   dvdec->framerate = 0;
440   dvdec->height = 0;
441   dvdec->frequency = 0;
442   dvdec->channels = 0;
443   dvdec->wide = FALSE;
444   dvdec->drop_factor = 1;
445
446   dvdec->clamp_luma = FALSE;
447   dvdec->clamp_chroma = FALSE;
448   dvdec->quality = DV_DEFAULT_QUALITY;
449   dvdec->loop = FALSE;
450
451   for (i = 0; i < 4; i++) {
452     dvdec->audio_buffers[i] =
453         (gint16 *) g_malloc (DV_AUDIO_MAX_SAMPLES * sizeof (gint16));
454   }
455 }
456
457 #if 0
458 static const GstFormat *
459 gst_dvdec_get_formats (GstPad * pad)
460 {
461   static const GstFormat src_formats[] = {
462     GST_FORMAT_BYTES,
463     GST_FORMAT_DEFAULT,
464     GST_FORMAT_TIME,
465     0
466   };
467   static const GstFormat sink_formats[] = {
468     GST_FORMAT_BYTES,
469     GST_FORMAT_TIME,
470     GST_FORMAT_DEFAULT,
471     0
472   };
473
474   return (GST_PAD_IS_SRC (pad) ? src_formats : sink_formats);
475 }
476 #endif
477
478 static gboolean
479 gst_dvdec_src_convert (GstPad * pad, GstFormat src_format, gint64 src_value,
480     GstFormat * dest_format, gint64 * dest_value)
481 {
482   gboolean res = TRUE;
483   GstDVDec *dvdec;
484
485   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
486   if (dvdec->frame_len == -1)
487     goto error;
488
489   if (dvdec->decoder == NULL)
490     goto error;
491
492   if (*dest_format == src_format) {
493     *dest_value = src_value;
494     goto done;
495   }
496
497   switch (src_format) {
498     case GST_FORMAT_BYTES:
499       switch (*dest_format) {
500         case GST_FORMAT_BYTES:
501           *dest_value = src_value;
502           break;
503         case GST_FORMAT_DEFAULT:
504         case GST_FORMAT_TIME:
505           *dest_format = GST_FORMAT_TIME;
506           if (pad == dvdec->videosrcpad)
507             *dest_value = src_value * GST_SECOND /
508                 (720 * dvdec->height * dvdec->bpp * dvdec->framerate /
509                 GST_SECOND);
510           else if (pad == dvdec->audiosrcpad)
511             *dest_value = src_value * GST_SECOND /
512                 (2 * dvdec->frequency * dvdec->channels);
513           break;
514         default:
515           res = FALSE;
516       }
517       break;
518     case GST_FORMAT_TIME:
519       switch (*dest_format) {
520         case GST_FORMAT_BYTES:
521           if (pad == dvdec->videosrcpad)
522             *dest_value = src_value * 720 * dvdec->height * dvdec->bpp *
523                 dvdec->framerate / GST_SECOND;
524           else if (pad == dvdec->audiosrcpad)
525             *dest_value = 2 * src_value * dvdec->frequency *
526                 dvdec->channels / GST_SECOND;
527           break;
528         case GST_FORMAT_TIME:
529         case GST_FORMAT_DEFAULT:
530           *dest_format = GST_FORMAT_TIME;
531           *dest_value = src_value;
532           break;
533         default:
534           res = FALSE;
535       }
536       break;
537     default:
538       res = FALSE;
539   }
540
541 done:
542   gst_object_unref (dvdec);
543
544   return res;
545
546 error:
547   {
548     gst_object_unref (dvdec);
549     return FALSE;
550   }
551 }
552
553 static gboolean
554 gst_dvdec_sink_convert (GstPad * pad, GstFormat src_format, gint64 src_value,
555     GstFormat * dest_format, gint64 * dest_value)
556 {
557   gboolean res = TRUE;
558   GstDVDec *dvdec;
559   gdouble framerate;
560
561   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
562
563   if (dvdec->frame_len <= 0)
564     goto error;
565
566   GST_DEBUG ("%d -> %d", src_format, *dest_format);
567
568   if (*dest_format == GST_FORMAT_DEFAULT)
569     *dest_format = GST_FORMAT_TIME;
570
571   if (*dest_format == src_format) {
572     *dest_value = src_value;
573     goto done;
574   }
575
576   framerate = (dvdec->PAL ? PAL_FRAMERATE : NTSC_FRAMERATE);
577
578   switch (src_format) {
579     case GST_FORMAT_BYTES:
580       switch (*dest_format) {
581         case GST_FORMAT_TIME:
582         {
583           guint64 frame;
584
585           /* get frame number */
586           frame = src_value / dvdec->frame_len;
587
588           *dest_value = (frame * GST_SECOND) / framerate;
589           break;
590         }
591         default:
592           res = FALSE;
593       }
594       break;
595     case GST_FORMAT_TIME:
596       switch (*dest_format) {
597         case GST_FORMAT_BYTES:
598         {
599           guint64 frame;
600
601           /* calculate the frame */
602           frame = src_value * framerate / GST_SECOND;
603           /* calculate the offset */
604           *dest_value = frame * dvdec->frame_len;
605           break;
606         }
607         default:
608           res = FALSE;
609       }
610       break;
611     default:
612       res = FALSE;
613   }
614
615 done:
616   gst_object_unref (dvdec);
617   return res;
618
619 error:
620   {
621     gst_object_unref (dvdec);
622     return FALSE;
623   }
624 }
625
626 static const GstQueryType *
627 gst_dvdec_get_src_query_types (GstPad * pad)
628 {
629   static const GstQueryType src_query_types[] = {
630     GST_QUERY_POSITION,
631     GST_QUERY_CONVERT,
632     0
633   };
634
635   return src_query_types;
636 }
637
638 static gboolean
639 gst_dvdec_src_query (GstPad * pad, GstQuery * query)
640 {
641   gboolean res = TRUE;
642   GstDVDec *dvdec;
643
644   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
645
646   switch (GST_QUERY_TYPE (query)) {
647     case GST_QUERY_POSITION:
648     {
649       GstFormat format;
650       gint64 cur, end;
651       GstPad *peer;
652
653       /* get target format */
654       gst_query_parse_position (query, &format, NULL, NULL);
655
656       /* change query to perform on peer */
657       gst_query_set_position (query, GST_FORMAT_BYTES, -1, -1);
658
659       if ((peer = gst_pad_get_peer (dvdec->sinkpad))) {
660         /* ask peer for total length */
661         if (!(res = gst_pad_query (peer, query))) {
662           gst_object_unref (peer);
663           goto error;
664         }
665
666         /* get peer total length */
667         gst_query_parse_position (query, NULL, NULL, &end);
668
669         /* convert end to requested format */
670         if (end != -1) {
671           if (!(res = gst_pad_query_convert (dvdec->sinkpad,
672                       GST_FORMAT_BYTES, end, &format, &end))) {
673             gst_object_unref (peer);
674             goto error;
675           }
676         }
677         gst_object_unref (peer);
678       } else {
679         end = -1;
680       }
681       /* bring the position to the requested format. */
682       if (!(res = gst_pad_query_convert (pad,
683                   GST_FORMAT_TIME, dvdec->timestamp, &format, &cur)))
684         goto error;
685
686       gst_query_set_position (query, format, cur, end);
687       break;
688     }
689     case GST_QUERY_CONVERT:
690     {
691       GstFormat src_fmt, dest_fmt;
692       gint64 src_val, dest_val;
693
694       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
695       if (!(res =
696               gst_dvdec_src_convert (pad, src_fmt, src_val, &dest_fmt,
697                   &dest_val)))
698         goto error;
699       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
700       break;
701     }
702     default:
703       res = FALSE;
704       break;
705   }
706   gst_object_unref (dvdec);
707
708   return res;
709
710 error:
711   {
712     gst_object_unref (dvdec);
713     GST_DEBUG ("error handling event");
714     return FALSE;
715   }
716 }
717
718 static const GstQueryType *
719 gst_dvdec_get_sink_query_types (GstPad * pad)
720 {
721   static const GstQueryType sink_query_types[] = {
722     GST_QUERY_CONVERT,
723     0
724   };
725
726   return sink_query_types;
727 }
728
729 static gboolean
730 gst_dvdec_sink_query (GstPad * pad, GstQuery * query)
731 {
732   gboolean res = TRUE;
733   GstDVDec *dvdec;
734
735   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
736
737   switch (GST_QUERY_TYPE (query)) {
738     case GST_QUERY_CONVERT:
739     {
740       GstFormat src_fmt, dest_fmt;
741       gint64 src_val, dest_val;
742
743       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
744       if (!(res =
745               gst_dvdec_sink_convert (pad, src_fmt, src_val, &dest_fmt,
746                   &dest_val)))
747         goto error;
748       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
749       break;
750     }
751     default:
752       res = FALSE;
753       break;
754   }
755   gst_object_unref (dvdec);
756
757   return res;
758
759 error:
760   {
761     gst_object_unref (dvdec);
762     GST_DEBUG ("error handling event");
763     return FALSE;
764   }
765 }
766
767 static gboolean
768 gst_dvdec_send_event (GstDVDec * dvdec, GstEvent * event)
769 {
770   gboolean res = FALSE;
771
772   gst_event_ref (event);
773   res |= gst_pad_push_event (dvdec->videosrcpad, event);
774   res |= gst_pad_push_event (dvdec->audiosrcpad, event);
775
776   return res;
777 }
778
779 static gboolean
780 gst_dvdec_handle_sink_event (GstPad * pad, GstEvent * event)
781 {
782   GstDVDec *dvdec = GST_DVDEC (gst_pad_get_parent (pad));
783   gboolean res = TRUE;
784
785   switch (GST_EVENT_TYPE (event)) {
786     case GST_EVENT_FLUSH_START:
787       /* we are not blocking on anything exect the push() calls
788        * to the peer which will be unblocked by forwarding the
789        * event.*/
790       res = gst_dvdec_send_event (dvdec, event);
791
792       /* and wait till streaming stops, not strictly needed as
793        * the peer calling us will do the same. */
794       GST_STREAM_LOCK (pad);
795       GST_STREAM_UNLOCK (pad);
796       break;
797     case GST_EVENT_FLUSH_STOP:
798       GST_STREAM_LOCK (pad);
799       gst_adapter_clear (dvdec->adapter);
800       GST_DEBUG ("cleared adapter");
801       res = gst_dvdec_send_event (dvdec, event);
802       GST_STREAM_UNLOCK (pad);
803       break;
804     case GST_EVENT_NEWSEGMENT:
805     {
806       GstFormat format;
807
808       GST_STREAM_LOCK (pad);
809
810       /* parse byte start and stop positions */
811       gst_event_parse_newsegment (event, NULL, &format,
812           &dvdec->start_byte, &dvdec->stop_byte, NULL);
813
814       /* and queue a DISCONT before sending the next set of buffers */
815       dvdec->need_discont = TRUE;
816       gst_event_unref (event);
817       GST_STREAM_UNLOCK (pad);
818       break;
819     }
820     case GST_EVENT_EOS:
821     default:
822       GST_STREAM_LOCK (pad);
823       /* flush any pending data */
824       gst_dvdec_flush (dvdec);
825       /* forward event */
826       res = gst_dvdec_send_event (dvdec, event);
827       /* and clear the adapter */
828       gst_adapter_clear (dvdec->adapter);
829       GST_STREAM_UNLOCK (pad);
830       break;
831   }
832
833   gst_object_unref (dvdec);
834
835   return res;
836 }
837
838 static gboolean
839 gst_dvdec_handle_src_event (GstPad * pad, GstEvent * event)
840 {
841   gboolean res = TRUE;
842   GstDVDec *dvdec;
843
844   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
845
846   switch (GST_EVENT_TYPE (event)) {
847     case GST_EVENT_SEEK:
848     {
849       GstEvent *newevent;
850       gint64 offset;
851       GstFormat format, conv;
852       gint64 cur, stop;
853       gdouble rate;
854       GstSeekType cur_type, stop_type;
855       GstSeekFlags flags;
856       gint64 start_position, end_position;
857
858       gst_event_parse_seek (event, &rate, &format, &flags,
859           &cur_type, &cur, &stop_type, &stop);
860
861       if ((offset = cur) != -1) {
862         /* bring the format to time on srcpad. */
863         conv = GST_FORMAT_TIME;
864         if (!(res = gst_pad_query_convert (pad,
865                     format, offset, &conv, &start_position))) {
866           /* could not convert seek format to time offset */
867           break;
868         }
869         /* and convert to bytes on sinkpad. */
870         conv = GST_FORMAT_BYTES;
871         if (!(res = gst_pad_query_convert (dvdec->sinkpad,
872                     GST_FORMAT_TIME, start_position, &conv, &start_position))) {
873           /* could not convert time format to bytes offset */
874           break;
875         }
876       } else {
877         start_position = -1;
878       }
879
880       if ((offset = stop) != -1) {
881         /* bring the format to time on srcpad. */
882         conv = GST_FORMAT_TIME;
883         if (!(res = gst_pad_query_convert (pad,
884                     format, offset, &conv, &end_position))) {
885           /* could not convert seek format to time offset */
886           break;
887         }
888         conv = GST_FORMAT_BYTES;
889         /* and convert to bytes on sinkpad. */
890         if (!(res = gst_pad_query_convert (dvdec->sinkpad,
891                     GST_FORMAT_TIME, end_position, &conv, &end_position))) {
892           /* could not convert seek format to bytes offset */
893           break;
894         }
895       } else {
896         end_position = -1;
897       }
898       /* now this is the updated seek event on bytes */
899       newevent = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
900           cur_type, start_position, stop_type, end_position);
901
902       res = gst_pad_push_event (dvdec->sinkpad, newevent);
903       break;
904     }
905     default:
906       res = FALSE;
907       break;
908   }
909   gst_event_unref (event);
910
911   gst_object_unref (dvdec);
912
913   return res;
914 }
915
916 static GstCaps *
917 gst_dvdec_video_getcaps (GstPad * pad)
918 {
919   GstDVDec *dvdec;
920   GstCaps *caps;
921   GstPadTemplate *src_pad_template;
922
923   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
924
925   src_pad_template = gst_static_pad_template_get (&video_src_temp);
926   caps = gst_caps_copy (gst_pad_template_get_caps (src_pad_template));
927
928   if (dvdec->found_header) {
929     int i;
930     gint par_x, par_y;
931
932     if (dvdec->PAL) {
933       if (dvdec->wide) {
934         par_x = PAL_WIDE_PAR_X;
935         par_y = PAL_WIDE_PAR_Y;
936       } else {
937         par_x = PAL_NORMAL_PAR_X;
938         par_y = PAL_NORMAL_PAR_Y;
939       }
940     } else {
941       if (dvdec->wide) {
942         par_x = NTSC_WIDE_PAR_X;
943         par_y = NTSC_WIDE_PAR_Y;
944       } else {
945         par_x = NTSC_NORMAL_PAR_X;
946         par_y = NTSC_NORMAL_PAR_Y;
947       }
948     }
949     /* set the height */
950     for (i = 0; i < gst_caps_get_size (caps); i++) {
951       GstStructure *structure = gst_caps_get_structure (caps, i);
952
953       gst_structure_set (structure,
954           "height", G_TYPE_INT, dvdec->height,
955           "framerate", G_TYPE_DOUBLE, dvdec->framerate / dvdec->drop_factor,
956           "pixel-aspect-ratio", GST_TYPE_FRACTION, par_x, par_y, NULL);
957     }
958   }
959
960   gst_object_unref (dvdec);
961
962   return caps;
963 }
964
965 static gboolean
966 gst_dvdec_video_setcaps (GstPad * pad, GstCaps * caps)
967 {
968   GstDVDec *dvdec;
969   GstStructure *structure;
970   gint height;
971   gdouble framerate;
972
973   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
974
975   structure = gst_caps_get_structure (caps, 0);
976
977   if (!gst_structure_get_int (structure, "height", &height) ||
978       !gst_structure_get_double (structure, "framerate", &framerate))
979     goto not_supported;
980
981   /* allow a margin of error for the framerate caused by float rounding errors */
982   if ((height != dvdec->height) ||
983       (fabs (framerate - (dvdec->framerate / dvdec->drop_factor)) > 0.00000001))
984     goto not_supported;
985
986   if (strcmp (gst_structure_get_name (structure), "video/x-raw-rgb") == 0) {
987     gint bpp;
988
989     GST_DEBUG ("got rgb format");
990
991     gst_structure_get_int (structure, "bpp", &bpp);
992     if (bpp == 24) {
993       dvdec->space = e_dv_color_rgb;
994       dvdec->bpp = 3;
995       GST_DEBUG ("configured rgb24");
996     } else {
997       dvdec->space = e_dv_color_bgr0;
998       dvdec->bpp = 4;
999       GST_DEBUG ("configured bgr32");
1000     }
1001   } else {
1002     guint32 fourcc;
1003
1004     if (!gst_structure_get_fourcc (structure, "format", &fourcc))
1005       goto not_supported;
1006
1007     if (fourcc != GST_STR_FOURCC ("YUY2"))
1008       goto not_supported;
1009
1010     dvdec->space = e_dv_color_yuv;
1011     dvdec->bpp = 2;
1012     GST_DEBUG ("configured YUY2");
1013   }
1014
1015   gst_object_unref (dvdec);
1016
1017   return TRUE;
1018
1019 not_supported:
1020   {
1021     GST_DEBUG ("unsupported format");
1022     gst_object_unref (dvdec);
1023     return FALSE;
1024   }
1025 }
1026
1027 static GstFlowReturn
1028 gst_dvdec_decode_audio (GstDVDec * dvdec, const guint8 * data)
1029 {
1030   gint num_samples;
1031   gint frequency, channels;
1032   GstFlowReturn ret;
1033
1034   frequency = dv_get_frequency (dvdec->decoder);
1035   channels = dv_get_num_channels (dvdec->decoder);
1036
1037   /* check if format changed */
1038   if ((frequency != dvdec->frequency) || (channels != dvdec->channels)) {
1039     GstCaps *caps;
1040
1041     dvdec->frequency = frequency;
1042     dvdec->channels = channels;
1043
1044     /* and set new caps */
1045     caps = gst_caps_new_simple ("audio/x-raw-int",
1046         "rate", G_TYPE_INT, frequency,
1047         "depth", G_TYPE_INT, 16,
1048         "width", G_TYPE_INT, 16,
1049         "signed", G_TYPE_BOOLEAN, TRUE,
1050         "channels", G_TYPE_INT, channels,
1051         "endianness", G_TYPE_INT, G_LITTLE_ENDIAN, NULL);
1052     gst_pad_set_caps (dvdec->audiosrcpad, caps);
1053     gst_caps_unref (caps);
1054   }
1055
1056   dv_decode_full_audio (dvdec->decoder, data, dvdec->audio_buffers);
1057
1058   if ((num_samples = dv_get_num_samples (dvdec->decoder)) > 0) {
1059     gint16 *a_ptr;
1060     gint i, j;
1061     GstBuffer *outbuf;
1062
1063     outbuf = gst_buffer_new_and_alloc (num_samples *
1064         sizeof (gint16) * dvdec->channels);
1065
1066     a_ptr = (gint16 *) GST_BUFFER_DATA (outbuf);
1067
1068     for (i = 0; i < num_samples; i++) {
1069       for (j = 0; j < dvdec->channels; j++) {
1070         *(a_ptr++) = dvdec->audio_buffers[j][i];
1071       }
1072     }
1073
1074     GST_DEBUG ("pushing audio %" GST_TIME_FORMAT,
1075         GST_TIME_ARGS (dvdec->timestamp));
1076
1077     GST_BUFFER_TIMESTAMP (outbuf) = dvdec->timestamp;
1078     GST_BUFFER_DURATION (outbuf) = dvdec->duration;
1079     GST_BUFFER_OFFSET (outbuf) = dvdec->audio_offset;
1080     dvdec->audio_offset += num_samples;
1081     GST_BUFFER_OFFSET_END (outbuf) = dvdec->audio_offset;
1082
1083     gst_buffer_set_caps (outbuf, GST_PAD_CAPS (dvdec->audiosrcpad));
1084
1085     ret = gst_pad_push (dvdec->audiosrcpad, outbuf);
1086   } else {
1087     /* no samples */
1088     ret = GST_FLOW_OK;
1089   }
1090
1091   return ret;
1092 }
1093
1094 static GstFlowReturn
1095 gst_dvdec_decode_video (GstDVDec * dvdec, const guint8 * data)
1096 {
1097   guint8 *outframe;
1098   guint8 *outframe_ptrs[3];
1099   gint outframe_pitches[3];
1100   gdouble framerate;
1101   gint height;
1102   gboolean wide;
1103   GstBuffer *outbuf;
1104   GstFlowReturn ret = GST_FLOW_OK;
1105
1106   /* get params */
1107   framerate = (dvdec->PAL ? PAL_FRAMERATE : NTSC_FRAMERATE);
1108   height = (dvdec->PAL ? PAL_HEIGHT : NTSC_HEIGHT);
1109   wide = dv_format_wide (dvdec->decoder);
1110
1111   /* see if anything changed */
1112   if ((dvdec->framerate != framerate) || (dvdec->height != height)
1113       || dvdec->wide != wide) {
1114     GstCaps *caps;
1115     gboolean setcaps_ret;
1116     gint par_x, par_y;
1117
1118     dvdec->framerate = framerate;
1119     dvdec->height = height;
1120     dvdec->wide = wide;
1121
1122     if (dvdec->PAL) {
1123       if (wide) {
1124         par_x = PAL_WIDE_PAR_X;
1125         par_y = PAL_WIDE_PAR_Y;
1126       } else {
1127         par_x = PAL_NORMAL_PAR_X;
1128         par_y = PAL_NORMAL_PAR_Y;
1129       }
1130     } else {
1131       if (wide) {
1132         par_x = NTSC_WIDE_PAR_X;
1133         par_y = NTSC_WIDE_PAR_Y;
1134       } else {
1135         par_x = NTSC_NORMAL_PAR_X;
1136         par_y = NTSC_NORMAL_PAR_Y;
1137       }
1138     }
1139
1140     /* and set new caps, this will be used as suggestion in alloc
1141      * function. */
1142     caps = gst_caps_new_simple ("video/x-raw-yuv",
1143         "format", GST_TYPE_FOURCC, GST_STR_FOURCC ("YUY2"),
1144         "width", G_TYPE_INT, 720,
1145         "height", G_TYPE_INT, height,
1146         "framerate", G_TYPE_DOUBLE, framerate / dvdec->drop_factor,
1147         "pixel-aspect-ratio", GST_TYPE_FRACTION, par_x, par_y, NULL);
1148     setcaps_ret = gst_pad_set_caps (dvdec->videosrcpad, caps);
1149     gst_caps_unref (caps);
1150     g_return_val_if_fail (setcaps_ret == TRUE, GST_FLOW_UNEXPECTED);
1151   }
1152
1153
1154   /* check if we can skip this frame */
1155   dvdec->framecount++;
1156   if (dvdec->framecount < dvdec->drop_factor)
1157     goto skip;
1158   dvdec->framecount = 0;
1159
1160   ret =
1161       gst_pad_alloc_buffer (dvdec->videosrcpad, 0, (720 * height) * dvdec->bpp,
1162       GST_PAD_CAPS (dvdec->videosrcpad), &outbuf);
1163   if (ret != GST_FLOW_OK)
1164     goto no_buffer;
1165
1166   outframe = GST_BUFFER_DATA (outbuf);
1167
1168   outframe_ptrs[0] = outframe;
1169   outframe_pitches[0] = 720 * dvdec->bpp;
1170
1171   /* the rest only matters for YUY2 */
1172   if (dvdec->bpp < 3) {
1173     outframe_ptrs[1] = outframe_ptrs[0] + 720 * height;
1174     outframe_ptrs[2] = outframe_ptrs[1] + 360 * height;
1175
1176     outframe_pitches[1] = height / 2;
1177     outframe_pitches[2] = outframe_pitches[1];
1178   }
1179
1180   dv_decode_full_frame (dvdec->decoder, data,
1181       dvdec->space, outframe_ptrs, outframe_pitches);
1182
1183   GST_DEBUG ("pushing video %" GST_TIME_FORMAT,
1184       GST_TIME_ARGS (dvdec->timestamp));
1185
1186   GST_BUFFER_TIMESTAMP (outbuf) = dvdec->timestamp;
1187   GST_BUFFER_OFFSET (outbuf) = dvdec->video_offset;
1188   GST_BUFFER_OFFSET_END (outbuf) = dvdec->video_offset + 1;
1189   GST_BUFFER_DURATION (outbuf) = dvdec->duration * dvdec->drop_factor;
1190
1191   ret = gst_pad_push (dvdec->videosrcpad, outbuf);
1192
1193 skip:
1194   dvdec->video_offset++;
1195
1196   return ret;
1197
1198   /* ERRORS */
1199 no_buffer:
1200   {
1201     return ret;
1202   }
1203 }
1204
1205 static GstFlowReturn
1206 gst_dvdec_decode_frame (GstDVDec * dvdec, const guint8 * data)
1207 {
1208   GstClockTime next_ts;
1209   gdouble framerate;
1210   GstFlowReturn aret, vret, ret;
1211
1212   if (dvdec->need_discont) {
1213     GstEvent *event;
1214     GstFormat format;
1215     gboolean res;
1216
1217     /* convert to time and store as start/end_timestamp */
1218     format = GST_FORMAT_TIME;
1219     if (!(res = gst_pad_query_convert (dvdec->sinkpad,
1220                 GST_FORMAT_BYTES,
1221                 dvdec->start_byte, &format, &dvdec->start_timestamp))) {
1222       goto discont_error;
1223     }
1224
1225     dvdec->timestamp = dvdec->start_timestamp;
1226
1227     format = GST_FORMAT_TIME;
1228     if (!(res = gst_pad_query_convert (dvdec->sinkpad,
1229                 GST_FORMAT_BYTES,
1230                 dvdec->stop_byte, &format, &dvdec->stop_timestamp))) {
1231       goto discont_error;
1232     }
1233
1234     event = gst_event_new_newsegment (1.0, GST_FORMAT_TIME,
1235         dvdec->start_timestamp, dvdec->stop_timestamp, 0);
1236     gst_dvdec_send_event (dvdec, event);
1237
1238     dvdec->need_discont = FALSE;
1239   }
1240
1241   framerate = (dvdec->PAL ? PAL_FRAMERATE : NTSC_FRAMERATE);
1242
1243   next_ts = dvdec->timestamp + GST_SECOND / framerate;
1244   dvdec->duration = next_ts - dvdec->timestamp;
1245
1246   dv_parse_packs (dvdec->decoder, data);
1247   if (dv_is_new_recording (dvdec->decoder, data))
1248     dvdec->new_media = TRUE;
1249
1250   aret = ret = gst_dvdec_decode_audio (dvdec, data);
1251   if (ret != GST_FLOW_OK && ret != GST_FLOW_NOT_LINKED)
1252     goto done;
1253
1254   vret = ret = gst_dvdec_decode_video (dvdec, data);
1255   if (ret != GST_FLOW_OK && ret != GST_FLOW_NOT_LINKED)
1256     goto done;
1257
1258   if (aret == GST_FLOW_NOT_LINKED && vret == GST_FLOW_NOT_LINKED) {
1259     ret = GST_FLOW_NOT_LINKED;
1260     goto done;
1261   }
1262
1263   ret = GST_FLOW_OK;
1264   dvdec->timestamp = next_ts;
1265
1266 done:
1267   return ret;
1268
1269 discont_error:
1270   {
1271     GST_DEBUG ("error generating discont event");
1272     return GST_FLOW_ERROR;
1273   }
1274 }
1275
1276 /* flush any remaining data in the adapter */
1277 static GstFlowReturn
1278 gst_dvdec_flush (GstDVDec * dvdec)
1279 {
1280   GstFlowReturn ret = GST_FLOW_OK;
1281
1282   while (gst_adapter_available (dvdec->adapter) >= dvdec->frame_len) {
1283     const guint8 *data;
1284     gint length;
1285
1286     /* get the accumulated bytes */
1287     data = gst_adapter_peek (dvdec->adapter, dvdec->frame_len);
1288
1289     /* parse header to know the length and other params */
1290     if (dv_parse_header (dvdec->decoder, data) < 0)
1291       goto parse_header_error;
1292
1293     dvdec->found_header = TRUE;
1294
1295     /* after parsing the header we know the length of the data */
1296     dvdec->PAL = dv_system_50_fields (dvdec->decoder);
1297     length = dvdec->frame_len = (dvdec->PAL ? PAL_BUFFER : NTSC_BUFFER);
1298
1299     /* if we still have enough for a frame, start decoding */
1300     if (gst_adapter_available (dvdec->adapter) >= length) {
1301
1302       data = gst_adapter_peek (dvdec->adapter, length);
1303
1304       /* and decode the data */
1305       ret = gst_dvdec_decode_frame (dvdec, data);
1306
1307       gst_adapter_flush (dvdec->adapter, length);
1308
1309       if (ret != GST_FLOW_OK)
1310         goto done;
1311     }
1312   }
1313 done:
1314   return ret;
1315
1316   /* ERRORS */
1317 parse_header_error:
1318   {
1319     GST_ELEMENT_ERROR (dvdec, STREAM, DECODE,
1320         ("Error parsing DV header"), ("Error parsing DV header"));
1321     gst_object_unref (dvdec);
1322
1323     return GST_FLOW_ERROR;
1324   }
1325 }
1326
1327 /* streaming operation: 
1328  *
1329  * accumulate data until we have a frame, then decode. 
1330  */
1331 static GstFlowReturn
1332 gst_dvdec_chain (GstPad * pad, GstBuffer * buffer)
1333 {
1334   GstDVDec *dvdec;
1335   GstFlowReturn ret;
1336
1337   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
1338
1339   gst_adapter_push (dvdec->adapter, buffer);
1340
1341   /* Apparently dv_parse_header can read from the body of the frame
1342    * too, so it needs more than header_size bytes. Wacky!
1343    */
1344   if (dvdec->frame_len == -1) {
1345     /* if we don't know the length of a frame, we assume it is
1346      * the NTSC_BUFFER length, as this is enough to figure out 
1347      * if this is PAL or NTSC */
1348     dvdec->frame_len = NTSC_BUFFER;
1349   }
1350
1351   /* and try to flush pending frames */
1352   ret = gst_dvdec_flush (dvdec);
1353
1354   return ret;
1355 }
1356
1357 static GstElementStateReturn
1358 gst_dvdec_change_state (GstElement * element)
1359 {
1360   GstDVDec *dvdec = GST_DVDEC (element);
1361   GstElementStateReturn ret;
1362   gint transition;
1363
1364   transition = GST_STATE_TRANSITION (element);
1365
1366   switch (transition) {
1367     case GST_STATE_NULL_TO_READY:
1368       break;
1369     case GST_STATE_READY_TO_PAUSED:
1370       dvdec->decoder =
1371           dv_decoder_new (0, dvdec->clamp_luma, dvdec->clamp_chroma);
1372       dvdec->decoder->quality = qualities[dvdec->quality];
1373       dvdec->audio_offset = 0;
1374       dvdec->video_offset = 0;
1375       dvdec->framecount = 0;
1376       dvdec->found_header = FALSE;
1377       dvdec->frame_len = -1;
1378       /* 
1379        * Enable this function call when libdv2 0.100 or higher is more
1380        * common
1381        */
1382       /* dv_set_quality (dvdec->decoder, qualities [dvdec->quality]); */
1383       break;
1384     case GST_STATE_PAUSED_TO_PLAYING:
1385       break;
1386     default:
1387       break;
1388   }
1389
1390   ret = parent_class->change_state (element);
1391
1392   switch (transition) {
1393     case GST_STATE_PLAYING_TO_PAUSED:
1394       break;
1395     case GST_STATE_PAUSED_TO_READY:
1396       gst_adapter_clear (dvdec->adapter);
1397       dv_decoder_free (dvdec->decoder);
1398       dvdec->decoder = NULL;
1399       break;
1400     case GST_STATE_READY_TO_NULL:
1401       break;
1402     default:
1403       break;
1404   }
1405   return ret;
1406 }
1407
1408 static void
1409 gst_dvdec_set_property (GObject * object, guint prop_id, const GValue * value,
1410     GParamSpec * pspec)
1411 {
1412   GstDVDec *dvdec;
1413
1414   /* Get a pointer of the right type. */
1415   dvdec = GST_DVDEC (object);
1416
1417   /* Check the argument id to see which argument we're setting. */
1418   switch (prop_id) {
1419     case ARG_CLAMP_LUMA:
1420       dvdec->clamp_luma = g_value_get_boolean (value);
1421       break;
1422     case ARG_CLAMP_CHROMA:
1423       dvdec->clamp_chroma = g_value_get_boolean (value);
1424       break;
1425     case ARG_QUALITY:
1426       dvdec->quality = g_value_get_enum (value);
1427       if ((dvdec->quality < 0) || (dvdec->quality > 5))
1428         dvdec->quality = 0;
1429       break;
1430     case ARG_DECODE_NTH:
1431       dvdec->drop_factor = g_value_get_int (value);
1432       break;
1433     default:
1434       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1435       break;
1436   }
1437 }
1438
1439 /* The set function is simply the inverse of the get fuction. */
1440 static void
1441 gst_dvdec_get_property (GObject * object, guint prop_id, GValue * value,
1442     GParamSpec * pspec)
1443 {
1444   GstDVDec *dvdec;
1445
1446   dvdec = GST_DVDEC (object);
1447
1448   switch (prop_id) {
1449     case ARG_CLAMP_LUMA:
1450       g_value_set_boolean (value, dvdec->clamp_luma);
1451       break;
1452     case ARG_CLAMP_CHROMA:
1453       g_value_set_boolean (value, dvdec->clamp_chroma);
1454       break;
1455     case ARG_QUALITY:
1456       g_value_set_enum (value, dvdec->quality);
1457       break;
1458     case ARG_DECODE_NTH:
1459       g_value_set_int (value, dvdec->drop_factor);
1460       break;
1461     default:
1462       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1463       break;
1464   }
1465 }
1466
1467 /* This is the entry into the plugin itself.  When the plugin loads,
1468  * this function is called to register everything that the plugin provides.
1469  */
1470 static gboolean
1471 plugin_init (GstPlugin * plugin)
1472 {
1473   if (!gst_element_register (plugin, "dvdec", GST_RANK_PRIMARY,
1474           gst_dvdec_get_type ()))
1475     return FALSE;
1476
1477   return TRUE;
1478 }
1479
1480 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1481     GST_VERSION_MINOR,
1482     "dvdec",
1483     "Uses libdv to decode DV video (libdv.sourceforge.net)",
1484     plugin_init, VERSION, "LGPL", GST_PACKAGE, GST_ORIGIN);