ext/dv/gstdvdec.c (gst_dvdec_decode_video): Don't clobber alloc_buffer's return value.
[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:
787       if (!GST_EVENT_FLUSH_DONE (event)) {
788         /* we are not blocking on anything exect the push() calls
789          * to the peer which will be unblocked by forwarding the
790          * event.*/
791         res = gst_dvdec_send_event (dvdec, event);
792
793         /* and wait till streaming stops, not strictly needed as
794          * the peer calling us will do the same. */
795         GST_STREAM_LOCK (pad);
796         GST_STREAM_UNLOCK (pad);
797       } else {
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       }
804       break;
805     case GST_EVENT_DISCONTINUOUS:
806     {
807       GST_STREAM_LOCK (pad);
808       /* parse byte start and stop positions */
809       if (!(res = gst_event_discont_get_value (event,
810                   GST_FORMAT_BYTES, &dvdec->start_byte, &dvdec->stop_byte)))
811         goto done;
812
813       /* and queue a DISCONT before sending the next set of buffers */
814       dvdec->need_discont = TRUE;
815     done:
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       gint64 start_position, end_position;
850       GstFormat format;
851       GstEvent *newevent;
852       gint64 offset;
853
854       if ((offset = GST_EVENT_SEEK_OFFSET (event)) != -1) {
855         /* bring the format to time on srcpad. */
856         format = GST_FORMAT_TIME;
857         if (!(res = gst_pad_query_convert (pad,
858                     GST_EVENT_SEEK_FORMAT (event),
859                     offset, &format, &start_position))) {
860           /* could not convert seek format to time offset */
861           break;
862         }
863         /* and convert to bytes on sinkpad. */
864         format = GST_FORMAT_BYTES;
865         if (!(res = gst_pad_query_convert (dvdec->sinkpad,
866                     GST_FORMAT_TIME,
867                     start_position, &format, &start_position))) {
868           /* could not convert time format to bytes offset */
869           break;
870         }
871       } else {
872         start_position = -1;
873       }
874
875       if ((offset = GST_EVENT_SEEK_ENDOFFSET (event)) != -1) {
876         /* bring the format to time on srcpad. */
877         format = GST_FORMAT_TIME;
878         if (!(res = gst_pad_query_convert (pad,
879                     GST_EVENT_SEEK_FORMAT (event),
880                     offset, &format, &end_position))) {
881           /* could not convert seek format to time offset */
882           break;
883         }
884         /* and convert to bytes on sinkpad. */
885         if (!(res = gst_pad_query_convert (dvdec->sinkpad,
886                     GST_FORMAT_TIME, end_position, &format, &end_position))) {
887           /* could not convert seek format to bytes offset */
888           break;
889         }
890       } else {
891         end_position = -1;
892       }
893       /* now this is the updated seek event on bytes */
894       newevent = gst_event_new_segment_seek (
895           (GST_EVENT_SEEK_TYPE (event) & ~GST_SEEK_FORMAT_MASK) |
896           GST_FORMAT_BYTES, start_position, end_position);
897
898       res = gst_pad_push_event (dvdec->sinkpad, newevent);
899       break;
900     }
901     default:
902       res = FALSE;
903       break;
904   }
905   gst_event_unref (event);
906
907   gst_object_unref (dvdec);
908
909   return res;
910 }
911
912 static GstCaps *
913 gst_dvdec_video_getcaps (GstPad * pad)
914 {
915   GstDVDec *dvdec;
916   GstCaps *caps;
917   GstPadTemplate *src_pad_template;
918
919   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
920
921   src_pad_template = gst_static_pad_template_get (&video_src_temp);
922   caps = gst_caps_copy (gst_pad_template_get_caps (src_pad_template));
923
924   if (dvdec->found_header) {
925     int i;
926     gint par_x, par_y;
927
928     if (dvdec->PAL) {
929       if (dvdec->wide) {
930         par_x = PAL_WIDE_PAR_X;
931         par_y = PAL_WIDE_PAR_Y;
932       } else {
933         par_x = PAL_NORMAL_PAR_X;
934         par_y = PAL_NORMAL_PAR_Y;
935       }
936     } else {
937       if (dvdec->wide) {
938         par_x = NTSC_WIDE_PAR_X;
939         par_y = NTSC_WIDE_PAR_Y;
940       } else {
941         par_x = NTSC_NORMAL_PAR_X;
942         par_y = NTSC_NORMAL_PAR_Y;
943       }
944     }
945     /* set the height */
946     for (i = 0; i < gst_caps_get_size (caps); i++) {
947       GstStructure *structure = gst_caps_get_structure (caps, i);
948
949       gst_structure_set (structure,
950           "height", G_TYPE_INT, dvdec->height,
951           "framerate", G_TYPE_DOUBLE, dvdec->framerate / dvdec->drop_factor,
952           "pixel-aspect-ratio", GST_TYPE_FRACTION, par_x, par_y, NULL);
953     }
954   }
955
956   gst_object_unref (dvdec);
957
958   return caps;
959 }
960
961 static gboolean
962 gst_dvdec_video_setcaps (GstPad * pad, GstCaps * caps)
963 {
964   GstDVDec *dvdec;
965   GstStructure *structure;
966   gint height;
967   gdouble framerate;
968
969   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
970
971   structure = gst_caps_get_structure (caps, 0);
972
973   if (!gst_structure_get_int (structure, "height", &height) ||
974       !gst_structure_get_double (structure, "framerate", &framerate))
975     goto not_supported;
976
977   /* allow a margin of error for the framerate caused by float rounding errors */
978   if ((height != dvdec->height) ||
979       (fabs (framerate - (dvdec->framerate / dvdec->drop_factor)) > 0.00000001))
980     goto not_supported;
981
982   if (strcmp (gst_structure_get_name (structure), "video/x-raw-rgb") == 0) {
983     gint bpp;
984
985     GST_DEBUG ("got rgb format");
986
987     gst_structure_get_int (structure, "bpp", &bpp);
988     if (bpp == 24) {
989       dvdec->space = e_dv_color_rgb;
990       dvdec->bpp = 3;
991       GST_DEBUG ("configured rgb24");
992     } else {
993       dvdec->space = e_dv_color_bgr0;
994       dvdec->bpp = 4;
995       GST_DEBUG ("configured bgr32");
996     }
997   } else {
998     guint32 fourcc;
999
1000     if (!gst_structure_get_fourcc (structure, "format", &fourcc))
1001       goto not_supported;
1002
1003     if (fourcc != GST_STR_FOURCC ("YUY2"))
1004       goto not_supported;
1005
1006     dvdec->space = e_dv_color_yuv;
1007     dvdec->bpp = 2;
1008     GST_DEBUG ("configured YUY2");
1009   }
1010
1011   gst_object_unref (dvdec);
1012
1013   return TRUE;
1014
1015 not_supported:
1016   {
1017     GST_DEBUG ("unsupported format");
1018     gst_object_unref (dvdec);
1019     return FALSE;
1020   }
1021 }
1022
1023 static GstFlowReturn
1024 gst_dvdec_decode_audio (GstDVDec * dvdec, const guint8 * data)
1025 {
1026   gint num_samples;
1027   gint frequency, channels;
1028   GstFlowReturn ret;
1029
1030   frequency = dv_get_frequency (dvdec->decoder);
1031   channels = dv_get_num_channels (dvdec->decoder);
1032
1033   /* check if format changed */
1034   if ((frequency != dvdec->frequency) || (channels != dvdec->channels)) {
1035     GstCaps *caps;
1036
1037     dvdec->frequency = frequency;
1038     dvdec->channels = channels;
1039
1040     /* and set new caps */
1041     caps = gst_caps_new_simple ("audio/x-raw-int",
1042         "rate", G_TYPE_INT, frequency,
1043         "depth", G_TYPE_INT, 16,
1044         "width", G_TYPE_INT, 16,
1045         "signed", G_TYPE_BOOLEAN, TRUE,
1046         "channels", G_TYPE_INT, channels,
1047         "endianness", G_TYPE_INT, G_LITTLE_ENDIAN, NULL);
1048     gst_pad_set_caps (dvdec->audiosrcpad, caps);
1049     gst_caps_unref (caps);
1050   }
1051
1052   dv_decode_full_audio (dvdec->decoder, data, dvdec->audio_buffers);
1053
1054   if ((num_samples = dv_get_num_samples (dvdec->decoder)) > 0) {
1055     gint16 *a_ptr;
1056     gint i, j;
1057     GstBuffer *outbuf;
1058
1059     outbuf = gst_buffer_new_and_alloc (num_samples *
1060         sizeof (gint16) * dvdec->channels);
1061
1062     a_ptr = (gint16 *) GST_BUFFER_DATA (outbuf);
1063
1064     for (i = 0; i < num_samples; i++) {
1065       for (j = 0; j < dvdec->channels; j++) {
1066         *(a_ptr++) = dvdec->audio_buffers[j][i];
1067       }
1068     }
1069
1070     GST_DEBUG ("pushing audio %" GST_TIME_FORMAT,
1071         GST_TIME_ARGS (dvdec->timestamp));
1072
1073     GST_BUFFER_TIMESTAMP (outbuf) = dvdec->timestamp;
1074     GST_BUFFER_DURATION (outbuf) = dvdec->duration;
1075     GST_BUFFER_OFFSET (outbuf) = dvdec->audio_offset;
1076     dvdec->audio_offset += num_samples;
1077     GST_BUFFER_OFFSET_END (outbuf) = dvdec->audio_offset;
1078
1079     gst_buffer_set_caps (outbuf, GST_PAD_CAPS (dvdec->audiosrcpad));
1080
1081     ret = gst_pad_push (dvdec->audiosrcpad, outbuf);
1082   } else {
1083     /* no samples */
1084     ret = GST_FLOW_OK;
1085   }
1086
1087   return ret;
1088 }
1089
1090 static GstFlowReturn
1091 gst_dvdec_decode_video (GstDVDec * dvdec, const guint8 * data)
1092 {
1093   guint8 *outframe;
1094   guint8 *outframe_ptrs[3];
1095   gint outframe_pitches[3];
1096   gdouble framerate;
1097   gint height;
1098   gboolean wide;
1099   GstBuffer *outbuf;
1100   GstFlowReturn ret = GST_FLOW_OK;
1101
1102   /* get params */
1103   framerate = (dvdec->PAL ? PAL_FRAMERATE : NTSC_FRAMERATE);
1104   height = (dvdec->PAL ? PAL_HEIGHT : NTSC_HEIGHT);
1105   wide = dv_format_wide (dvdec->decoder);
1106
1107   /* see if anything changed */
1108   if ((dvdec->framerate != framerate) || (dvdec->height != height)
1109       || dvdec->wide != wide) {
1110     GstCaps *caps;
1111     gint par_x, par_y;
1112
1113     dvdec->framerate = framerate;
1114     dvdec->height = height;
1115     dvdec->wide = wide;
1116
1117     if (dvdec->PAL) {
1118       if (wide) {
1119         par_x = PAL_WIDE_PAR_X;
1120         par_y = PAL_WIDE_PAR_Y;
1121       } else {
1122         par_x = PAL_NORMAL_PAR_X;
1123         par_y = PAL_NORMAL_PAR_Y;
1124       }
1125     } else {
1126       if (wide) {
1127         par_x = NTSC_WIDE_PAR_X;
1128         par_y = NTSC_WIDE_PAR_Y;
1129       } else {
1130         par_x = NTSC_NORMAL_PAR_X;
1131         par_y = NTSC_NORMAL_PAR_Y;
1132       }
1133     }
1134
1135     /* and set new caps, this will be used as suggestion in alloc
1136      * function. */
1137     caps = gst_caps_new_simple ("video/x-raw-yuv",
1138         "format", GST_TYPE_FOURCC, GST_STR_FOURCC ("YUY2"),
1139         "width", G_TYPE_INT, 720,
1140         "height", G_TYPE_INT, height,
1141         "framerate", G_TYPE_DOUBLE, framerate,
1142         "pixel-aspect-ratio", GST_TYPE_FRACTION, par_x, par_y, NULL);
1143     gst_pad_set_caps (dvdec->videosrcpad, caps);
1144     gst_caps_unref (caps);
1145   }
1146
1147
1148   /* check if we can skip this frame */
1149   dvdec->framecount++;
1150   if (dvdec->framecount < dvdec->drop_factor)
1151     goto skip;
1152   dvdec->framecount = 0;
1153
1154   ret =
1155       gst_pad_alloc_buffer (dvdec->videosrcpad, 0, (720 * height) * dvdec->bpp,
1156       GST_PAD_CAPS (dvdec->videosrcpad), &outbuf);
1157   if (ret != GST_FLOW_OK)
1158     goto no_buffer;
1159
1160   outframe = GST_BUFFER_DATA (outbuf);
1161
1162   outframe_ptrs[0] = outframe;
1163   outframe_pitches[0] = 720 * dvdec->bpp;
1164
1165   /* the rest only matters for YUY2 */
1166   if (dvdec->bpp < 3) {
1167     outframe_ptrs[1] = outframe_ptrs[0] + 720 * height;
1168     outframe_ptrs[2] = outframe_ptrs[1] + 360 * height;
1169
1170     outframe_pitches[1] = height / 2;
1171     outframe_pitches[2] = outframe_pitches[1];
1172   }
1173
1174   dv_decode_full_frame (dvdec->decoder, data,
1175       dvdec->space, outframe_ptrs, outframe_pitches);
1176
1177   GST_DEBUG ("pushing video %" GST_TIME_FORMAT,
1178       GST_TIME_ARGS (dvdec->timestamp));
1179
1180   GST_BUFFER_TIMESTAMP (outbuf) = dvdec->timestamp;
1181   GST_BUFFER_OFFSET (outbuf) = dvdec->video_offset;
1182   GST_BUFFER_OFFSET_END (outbuf) = dvdec->video_offset + 1;
1183   GST_BUFFER_DURATION (outbuf) = dvdec->duration * dvdec->drop_factor;
1184
1185   ret = gst_pad_push (dvdec->videosrcpad, outbuf);
1186
1187 skip:
1188   dvdec->video_offset++;
1189
1190   return ret;
1191
1192   /* ERRORS */
1193 no_buffer:
1194   {
1195     return ret;
1196   }
1197 }
1198
1199 static GstFlowReturn
1200 gst_dvdec_decode_frame (GstDVDec * dvdec, const guint8 * data)
1201 {
1202   GstClockTime next_ts;
1203   gdouble framerate;
1204   GstFlowReturn aret, vret, ret;
1205
1206   if (dvdec->need_discont) {
1207     GstEvent *event;
1208     GstFormat format;
1209     gboolean res;
1210
1211     /* convert to time and store as start/end_timestamp */
1212     format = GST_FORMAT_TIME;
1213     if (!(res = gst_pad_query_convert (dvdec->sinkpad,
1214                 GST_FORMAT_BYTES,
1215                 dvdec->start_byte, &format, &dvdec->start_timestamp))) {
1216       goto discont_error;
1217     }
1218
1219     dvdec->timestamp = dvdec->start_timestamp;
1220
1221     format = GST_FORMAT_TIME;
1222     if (!(res = gst_pad_query_convert (dvdec->sinkpad,
1223                 GST_FORMAT_BYTES,
1224                 dvdec->stop_byte, &format, &dvdec->stop_timestamp))) {
1225       goto discont_error;
1226     }
1227
1228     event = gst_event_new_discontinuous (1.0, GST_FORMAT_TIME,
1229         dvdec->start_timestamp, dvdec->stop_timestamp, NULL);
1230     gst_dvdec_send_event (dvdec, event);
1231
1232     dvdec->need_discont = FALSE;
1233   }
1234
1235   framerate = (dvdec->PAL ? PAL_FRAMERATE : NTSC_FRAMERATE);
1236
1237   next_ts = dvdec->timestamp + GST_SECOND / framerate;
1238   dvdec->duration = next_ts - dvdec->timestamp;
1239
1240   dv_parse_packs (dvdec->decoder, data);
1241   if (dv_is_new_recording (dvdec->decoder, data))
1242     dvdec->new_media = TRUE;
1243
1244   aret = ret = gst_dvdec_decode_audio (dvdec, data);
1245   if (ret != GST_FLOW_OK && ret != GST_FLOW_NOT_LINKED)
1246     goto done;
1247
1248   vret = ret = gst_dvdec_decode_video (dvdec, data);
1249   if (ret != GST_FLOW_OK && ret != GST_FLOW_NOT_LINKED)
1250     goto done;
1251
1252   if (aret == GST_FLOW_NOT_LINKED && vret == GST_FLOW_NOT_LINKED) {
1253     ret = GST_FLOW_NOT_LINKED;
1254     goto done;
1255   }
1256
1257   ret = GST_FLOW_OK;
1258   dvdec->timestamp = next_ts;
1259
1260 done:
1261   return ret;
1262
1263 discont_error:
1264   {
1265     GST_DEBUG ("error generating discont event");
1266     return GST_FLOW_ERROR;
1267   }
1268 }
1269
1270 /* flush any remaining data in the adapter */
1271 static GstFlowReturn
1272 gst_dvdec_flush (GstDVDec * dvdec)
1273 {
1274   GstFlowReturn ret = GST_FLOW_OK;
1275
1276   while (gst_adapter_available (dvdec->adapter) >= dvdec->frame_len) {
1277     const guint8 *data;
1278     gint length;
1279
1280     /* get the accumulated bytes */
1281     data = gst_adapter_peek (dvdec->adapter, dvdec->frame_len);
1282
1283     /* parse header to know the length and other params */
1284     if (dv_parse_header (dvdec->decoder, data) < 0)
1285       goto parse_header_error;
1286
1287     dvdec->found_header = TRUE;
1288
1289     /* after parsing the header we know the length of the data */
1290     dvdec->PAL = dv_system_50_fields (dvdec->decoder);
1291     length = dvdec->frame_len = (dvdec->PAL ? PAL_BUFFER : NTSC_BUFFER);
1292
1293     /* if we still have enough for a frame, start decoding */
1294     if (gst_adapter_available (dvdec->adapter) >= length) {
1295
1296       data = gst_adapter_peek (dvdec->adapter, length);
1297
1298       /* and decode the data */
1299       ret = gst_dvdec_decode_frame (dvdec, data);
1300
1301       gst_adapter_flush (dvdec->adapter, length);
1302
1303       if (ret != GST_FLOW_OK)
1304         goto done;
1305     }
1306   }
1307 done:
1308   return ret;
1309
1310   /* ERRORS */
1311 parse_header_error:
1312   {
1313     GST_ELEMENT_ERROR (dvdec, STREAM, DECODE,
1314         ("Error parsing DV header"), ("Error parsing DV header"));
1315     gst_object_unref (dvdec);
1316
1317     return GST_FLOW_ERROR;
1318   }
1319 }
1320
1321 /* streaming operation: 
1322  *
1323  * accumulate data until we have a frame, then decode. 
1324  */
1325 static GstFlowReturn
1326 gst_dvdec_chain (GstPad * pad, GstBuffer * buffer)
1327 {
1328   GstDVDec *dvdec;
1329   GstFlowReturn ret;
1330
1331   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
1332
1333   gst_adapter_push (dvdec->adapter, buffer);
1334
1335   /* Apparently dv_parse_header can read from the body of the frame
1336    * too, so it needs more than header_size bytes. Wacky!
1337    */
1338   if (dvdec->frame_len == -1) {
1339     /* if we don't know the length of a frame, we assume it is
1340      * the NTSC_BUFFER length, as this is enough to figure out 
1341      * if this is PAL or NTSC */
1342     dvdec->frame_len = NTSC_BUFFER;
1343   }
1344
1345   /* and try to flush pending frames */
1346   ret = gst_dvdec_flush (dvdec);
1347
1348   return ret;
1349 }
1350
1351 static GstElementStateReturn
1352 gst_dvdec_change_state (GstElement * element)
1353 {
1354   GstDVDec *dvdec = GST_DVDEC (element);
1355   GstElementStateReturn ret;
1356   gint transition;
1357
1358   transition = GST_STATE_TRANSITION (element);
1359
1360   switch (transition) {
1361     case GST_STATE_NULL_TO_READY:
1362       break;
1363     case GST_STATE_READY_TO_PAUSED:
1364       dvdec->decoder =
1365           dv_decoder_new (0, dvdec->clamp_luma, dvdec->clamp_chroma);
1366       dvdec->decoder->quality = qualities[dvdec->quality];
1367       dvdec->audio_offset = 0;
1368       dvdec->video_offset = 0;
1369       dvdec->framecount = 0;
1370       dvdec->found_header = FALSE;
1371       dvdec->frame_len = -1;
1372       /* 
1373        * Enable this function call when libdv2 0.100 or higher is more
1374        * common
1375        */
1376       /* dv_set_quality (dvdec->decoder, qualities [dvdec->quality]); */
1377       break;
1378     case GST_STATE_PAUSED_TO_PLAYING:
1379       break;
1380     default:
1381       break;
1382   }
1383
1384   ret = parent_class->change_state (element);
1385
1386   switch (transition) {
1387     case GST_STATE_PLAYING_TO_PAUSED:
1388       break;
1389     case GST_STATE_PAUSED_TO_READY:
1390       gst_adapter_clear (dvdec->adapter);
1391       dv_decoder_free (dvdec->decoder);
1392       dvdec->decoder = NULL;
1393       break;
1394     case GST_STATE_READY_TO_NULL:
1395       break;
1396     default:
1397       break;
1398   }
1399   return ret;
1400 }
1401
1402 static void
1403 gst_dvdec_set_property (GObject * object, guint prop_id, const GValue * value,
1404     GParamSpec * pspec)
1405 {
1406   GstDVDec *dvdec;
1407
1408   /* Get a pointer of the right type. */
1409   dvdec = GST_DVDEC (object);
1410
1411   /* Check the argument id to see which argument we're setting. */
1412   switch (prop_id) {
1413     case ARG_CLAMP_LUMA:
1414       dvdec->clamp_luma = g_value_get_boolean (value);
1415       break;
1416     case ARG_CLAMP_CHROMA:
1417       dvdec->clamp_chroma = g_value_get_boolean (value);
1418       break;
1419     case ARG_QUALITY:
1420       dvdec->quality = g_value_get_enum (value);
1421       if ((dvdec->quality < 0) || (dvdec->quality > 5))
1422         dvdec->quality = 0;
1423       break;
1424     case ARG_DECODE_NTH:
1425       dvdec->drop_factor = g_value_get_int (value);
1426       break;
1427     default:
1428       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1429       break;
1430   }
1431 }
1432
1433 /* The set function is simply the inverse of the get fuction. */
1434 static void
1435 gst_dvdec_get_property (GObject * object, guint prop_id, GValue * value,
1436     GParamSpec * pspec)
1437 {
1438   GstDVDec *dvdec;
1439
1440   dvdec = GST_DVDEC (object);
1441
1442   switch (prop_id) {
1443     case ARG_CLAMP_LUMA:
1444       g_value_set_boolean (value, dvdec->clamp_luma);
1445       break;
1446     case ARG_CLAMP_CHROMA:
1447       g_value_set_boolean (value, dvdec->clamp_chroma);
1448       break;
1449     case ARG_QUALITY:
1450       g_value_set_enum (value, dvdec->quality);
1451       break;
1452     case ARG_DECODE_NTH:
1453       g_value_set_int (value, dvdec->drop_factor);
1454       break;
1455     default:
1456       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1457       break;
1458   }
1459 }
1460
1461 /* This is the entry into the plugin itself.  When the plugin loads,
1462  * this function is called to register everything that the plugin provides.
1463  */
1464 static gboolean
1465 plugin_init (GstPlugin * plugin)
1466 {
1467   if (!gst_element_register (plugin, "dvdec", GST_RANK_PRIMARY,
1468           gst_dvdec_get_type ()))
1469     return FALSE;
1470
1471   return TRUE;
1472 }
1473
1474 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1475     GST_VERSION_MINOR,
1476     "dvdec",
1477     "Uses libdv to decode DV video (libdv.sourceforge.net)",
1478     plugin_init, VERSION, "LGPL", GST_PACKAGE, GST_ORIGIN);