ext/dv/gstdvdec.c: remove unneeded comment from dvdec (related to DV 4CC codes in...
[platform/upstream/gst-plugins-good.git] / ext / dv / gstdvdec.c
1 /* GStreamer
2  * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif
23 #include <string.h>
24 #include <math.h>
25
26 /* First, include the header file for the plugin, to bring in the
27  * object definition and other useful things.
28  */
29 #include "gstdvdec.h"
30
31 #define NTSC_HEIGHT 480
32 #define NTSC_BUFFER 120000
33 #define NTSC_FRAMERATE 29.997
34
35 #define PAL_HEIGHT 576
36 #define PAL_BUFFER 144000
37 #define PAL_FRAMERATE 25.0
38
39 #define PAL_NORMAL_PAR_X        16
40 #define PAL_NORMAL_PAR_Y        15
41 #define PAL_WIDE_PAR_X          64
42 #define PAL_WIDE_PAR_Y          45
43
44 #define NTSC_NORMAL_PAR_X       80
45 #define NTSC_NORMAL_PAR_Y       89
46 #define NTSC_WIDE_PAR_X         320
47 #define NTSC_WIDE_PAR_Y         267
48
49 /* The ElementDetails structure gives a human-readable description
50  * of the plugin, as well as author and version data.
51  */
52 static GstElementDetails dvdec_details =
53 GST_ELEMENT_DETAILS ("DV (smpte314) decoder plugin",
54     "Codec/Decoder/Video",
55     "Uses libdv to decode DV video (libdv.sourceforge.net)",
56     "Erik Walthinsen <omega@cse.ogi.edu>\n" "Wim Taymans <wim.taymans@tvd.be>");
57
58
59 /* These are the signals that this element can fire.  They are zero-
60  * based because the numbers themselves are private to the object.
61  * LAST_SIGNAL is used for initialization of the signal array.
62  */
63 enum
64 {
65   /* FILL ME */
66   LAST_SIGNAL
67 };
68
69 #define DV_DEFAULT_QUALITY DV_QUALITY_BEST
70 #define DV_DEFAULT_DECODE_NTH 1
71
72 /* Arguments are identified the same way, but cannot be zero, so you
73  * must leave the ARG_0 entry in as a placeholder.
74  */
75 enum
76 {
77   ARG_0,
78   ARG_CLAMP_LUMA,
79   ARG_CLAMP_CHROMA,
80   ARG_QUALITY,
81   ARG_DECODE_NTH
82       /* FILL ME */
83 };
84
85 const gint qualities[] = {
86   DV_QUALITY_DC,
87   DV_QUALITY_AC_1,
88   DV_QUALITY_AC_2,
89   DV_QUALITY_DC | DV_QUALITY_COLOR,
90   DV_QUALITY_AC_1 | DV_QUALITY_COLOR,
91   DV_QUALITY_AC_2 | DV_QUALITY_COLOR
92 };
93
94 /* The PadFactory structures describe what pads the element has or
95  * can have.  They can be quite complex, but for this dvdec plugin
96  * they are rather simple.
97  */
98 static GstStaticPadTemplate sink_temp = GST_STATIC_PAD_TEMPLATE ("sink",
99     GST_PAD_SINK,
100     GST_PAD_ALWAYS,
101     GST_STATIC_CAPS ("video/x-dv, systemstream = (boolean) true")
102     );
103
104 static GstStaticPadTemplate video_src_temp = GST_STATIC_PAD_TEMPLATE ("video",
105     GST_PAD_SRC,
106     GST_PAD_ALWAYS,
107     GST_STATIC_CAPS ("video/x-raw-yuv, "
108         "format = (fourcc) YUY2, "
109         "width = (int) 720, "
110         "height = (int) { "
111         G_STRINGIFY (NTSC_HEIGHT) ", " G_STRINGIFY (PAL_HEIGHT)
112         " }, "
113         "pixel-aspect-ratio=(fraction) { "
114         G_STRINGIFY (PAL_NORMAL_PAR_X) "/" G_STRINGIFY (PAL_NORMAL_PAR_Y) ","
115         G_STRINGIFY (PAL_WIDE_PAR_X) "/" G_STRINGIFY (PAL_WIDE_PAR_Y) ","
116         G_STRINGIFY (NTSC_NORMAL_PAR_X) "/" G_STRINGIFY (NTSC_NORMAL_PAR_Y) ","
117         G_STRINGIFY (NTSC_WIDE_PAR_X) "/" G_STRINGIFY (NTSC_WIDE_PAR_Y) "},"
118         "framerate = (double) [ 1.0, 60.0 ];"
119         //"framerate = (double) { "
120         //G_STRINGIFY (PAL_FRAMERATE) ", " G_STRINGIFY (NTSC_FRAMERATE)
121         //" }; "
122         "video/x-raw-rgb, "
123         "bpp = (int) 32, "
124         "depth = (int) 24, "
125         "endianness = (int) " G_STRINGIFY (G_BIG_ENDIAN) ", "
126         "red_mask =   (int) 0x00ff0000, "
127         "green_mask = (int) 0x0000ff00, "
128         "blue_mask =  (int) 0x000000ff, "
129         "width = (int) 720, "
130         "height = (int) { "
131         G_STRINGIFY (NTSC_HEIGHT) ", " G_STRINGIFY (PAL_HEIGHT)
132         " }, "
133         "pixel-aspect-ratio=(fraction) { "
134         G_STRINGIFY (PAL_NORMAL_PAR_X) "/" G_STRINGIFY (PAL_NORMAL_PAR_Y) ","
135         G_STRINGIFY (PAL_WIDE_PAR_X) "/" G_STRINGIFY (PAL_WIDE_PAR_Y) ","
136         G_STRINGIFY (NTSC_NORMAL_PAR_X) "/" G_STRINGIFY (NTSC_NORMAL_PAR_Y) ","
137         G_STRINGIFY (NTSC_WIDE_PAR_X) "/" G_STRINGIFY (NTSC_WIDE_PAR_Y) "},"
138         "framerate = (double) [ 1.0, 60.0 ];"
139         //"framerate = (double) { "
140         //G_STRINGIFY (PAL_FRAMERATE) ", " G_STRINGIFY (NTSC_FRAMERATE)
141         //" }; "
142         "video/x-raw-rgb, "
143         "bpp = (int) 24, "
144         "depth = (int) 24, "
145         "endianness = (int) " G_STRINGIFY (G_BIG_ENDIAN) ", "
146         "red_mask =   (int) 0x00ff0000, "
147         "green_mask = (int) 0x0000ff00, "
148         "blue_mask =  (int) 0x000000ff, "
149         "width = (int) 720, "
150         "height = (int) { "
151         G_STRINGIFY (NTSC_HEIGHT) ", " G_STRINGIFY (PAL_HEIGHT)
152         " }, "
153         "pixel-aspect-ratio=(fraction) { "
154         G_STRINGIFY (PAL_NORMAL_PAR_X) "/" G_STRINGIFY (PAL_NORMAL_PAR_Y) ","
155         G_STRINGIFY (PAL_WIDE_PAR_X) "/" G_STRINGIFY (PAL_WIDE_PAR_Y) ","
156         G_STRINGIFY (NTSC_NORMAL_PAR_X) "/" G_STRINGIFY (NTSC_NORMAL_PAR_Y) ","
157         G_STRINGIFY (NTSC_WIDE_PAR_X) "/" G_STRINGIFY (NTSC_WIDE_PAR_Y) "},"
158         "framerate = (double) [ 1.0, 60.0 ]"
159         //"framerate = (double) { "
160         //G_STRINGIFY (PAL_FRAMERATE) ", " G_STRINGIFY (NTSC_FRAMERATE)
161         //" }"
162     )
163     );
164
165 static GstStaticPadTemplate audio_src_temp = GST_STATIC_PAD_TEMPLATE ("audio",
166     GST_PAD_SRC,
167     GST_PAD_ALWAYS,
168     GST_STATIC_CAPS ("audio/x-raw-int, "
169         "depth = (int) 16, "
170         "width = (int) 16, "
171         "signed = (boolean) TRUE, "
172         "channels = (int) {2, 4}, "
173         "endianness = (int) " G_STRINGIFY (G_LITTLE_ENDIAN) ", "
174         "rate = (int) { 32000, 44100, 48000 }")
175     );
176
177 #define GST_TYPE_DVDEC_QUALITY (gst_dvdec_quality_get_type())
178 GType
179 gst_dvdec_quality_get_type (void)
180 {
181   static GType qtype = 0;
182
183   if (qtype == 0) {
184     static const GEnumValue values[] = {
185       {0, "DV_QUALITY_FASTEST", "Fastest decoding, low-quality mono"},
186       {1, "DV_QUALITY_AC_1", "Mono decoding using the first AC coefficient"},
187       {2, "DV_QUALITY_AC_2", "Highest quality mono decoding"},
188       {3, "DV_QUALITY_DC|DV_QUALITY_COLOUR", "Fastest colour decoding"},
189       {4, "DV_QUALITY_AC_1|DV_QUALITY_COLOUR",
190           "Colour, using only the first AC coefficient"},
191       {5, "DV_QUALITY_BEST", "Highest quality colour decoding"},
192       {0, NULL, NULL},
193     };
194
195     qtype = g_enum_register_static ("GstDVDecQualityEnum", values);
196   }
197   return qtype;
198 }
199
200 /* A number of functon prototypes are given so we can refer to them later. */
201 static void gst_dvdec_base_init (gpointer g_class);
202 static void gst_dvdec_class_init (GstDVDecClass * klass);
203 static void gst_dvdec_init (GstDVDec * dvdec);
204
205 static const GstQueryType *gst_dvdec_get_src_query_types (GstPad * pad);
206 static gboolean gst_dvdec_src_query (GstPad * pad, GstQueryType type,
207     GstFormat * format, gint64 * value);
208 static const GstFormat *gst_dvdec_get_formats (GstPad * pad);
209 static gboolean gst_dvdec_sink_convert (GstPad * pad, GstFormat src_format,
210     gint64 src_value, GstFormat * dest_format, gint64 * dest_value);
211 static gboolean gst_dvdec_src_convert (GstPad * pad, GstFormat src_format,
212     gint64 src_value, GstFormat * dest_format, gint64 * dest_value);
213
214 static GstPadLinkReturn gst_dvdec_video_link (GstPad * pad,
215     const GstCaps * caps);
216 static GstCaps *gst_dvdec_video_getcaps (GstPad * pad);
217
218 static const GstEventMask *gst_dvdec_get_event_masks (GstPad * pad);
219 static gboolean gst_dvdec_handle_src_event (GstPad * pad, GstEvent * event);
220
221 static void gst_dvdec_loop (GstElement * element);
222
223 static GstElementStateReturn gst_dvdec_change_state (GstElement * element);
224
225 static void gst_dvdec_set_property (GObject * object, guint prop_id,
226     const GValue * value, GParamSpec * pspec);
227 static void gst_dvdec_get_property (GObject * object, guint prop_id,
228     GValue * value, GParamSpec * pspec);
229
230 /* The parent class pointer needs to be kept around for some object
231  * operations.
232  */
233 static GstElementClass *parent_class = NULL;
234
235 /* This array holds the ids of the signals registered for this object.
236  * The array indexes are based on the enum up above.
237  */
238 /*static guint gst_dvdec_signals[LAST_SIGNAL] = { 0 }; */
239
240 /* This function is used to register and subsequently return the type
241  * identifier for this object class.  On first invocation, it will
242  * register the type, providing the name of the class, struct sizes,
243  * and pointers to the various functions that define the class.
244  */
245 GType
246 gst_dvdec_get_type (void)
247 {
248   static GType dvdec_type = 0;
249
250   if (!dvdec_type) {
251     static const GTypeInfo dvdec_info = {
252       sizeof (GstDVDecClass),
253       gst_dvdec_base_init,
254       NULL,
255       (GClassInitFunc) gst_dvdec_class_init,
256       NULL,
257       NULL,
258       sizeof (GstDVDec),
259       0,
260       (GInstanceInitFunc) gst_dvdec_init,
261     };
262
263     dvdec_type =
264         g_type_register_static (GST_TYPE_ELEMENT, "GstDVDec", &dvdec_info, 0);
265   }
266   return dvdec_type;
267 }
268
269 static void
270 gst_dvdec_base_init (gpointer g_class)
271 {
272   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
273
274   /* The pad templates can be easily generated from the factories above,
275    * and then added to the list of padtemplates for the elementfactory.
276    * Note that the generated padtemplates are stored in static global
277    * variables, for the gst_dvdec_init function to use later on.
278    */
279   gst_element_class_add_pad_template (element_class,
280       gst_static_pad_template_get (&sink_temp));
281   gst_element_class_add_pad_template (element_class,
282       gst_static_pad_template_get (&video_src_temp));
283   gst_element_class_add_pad_template (element_class,
284       gst_static_pad_template_get (&audio_src_temp));
285
286   gst_element_class_set_details (element_class, &dvdec_details);
287 }
288
289 /* In order to create an instance of an object, the class must be
290  * initialized by this function.  GObject will take care of running
291  * it, based on the pointer to the function provided above.
292  */
293 static void
294 gst_dvdec_class_init (GstDVDecClass * klass)
295 {
296   /* Class pointers are needed to supply pointers to the private
297    * implementations of parent class methods.
298    */
299   GObjectClass *gobject_class;
300   GstElementClass *gstelement_class;
301
302   /* Since the dvdec class contains the parent classes, you can simply
303    * cast the pointer to get access to the parent classes.
304    */
305   gobject_class = (GObjectClass *) klass;
306   gstelement_class = (GstElementClass *) klass;
307
308   /* The parent class is needed for class method overrides. */
309   parent_class = g_type_class_ref (GST_TYPE_ELEMENT);
310
311   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_CLAMP_LUMA,
312       g_param_spec_boolean ("clamp_luma", "Clamp luma", "Clamp luma",
313           FALSE, G_PARAM_READWRITE));
314   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_CLAMP_CHROMA,
315       g_param_spec_boolean ("clamp_chroma", "Clamp chroma", "Clamp chroma",
316           FALSE, G_PARAM_READWRITE));
317   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_QUALITY,
318       g_param_spec_enum ("quality", "Quality", "Decoding quality",
319           GST_TYPE_DVDEC_QUALITY, DV_DEFAULT_QUALITY, G_PARAM_READWRITE));
320   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_DECODE_NTH,
321       g_param_spec_int ("drop-factor", "Drop Factor", "Only decode Nth frame",
322           1, G_MAXINT, DV_DEFAULT_DECODE_NTH, G_PARAM_READWRITE));
323
324   gobject_class->set_property = gst_dvdec_set_property;
325   gobject_class->get_property = gst_dvdec_get_property;
326
327   gstelement_class->change_state = gst_dvdec_change_state;
328
329   /* table initialization, only do once */
330   dv_init (0, 0);
331 }
332
333 /* This function is responsible for initializing a specific instance of
334  * the plugin.
335  */
336 static void
337 gst_dvdec_init (GstDVDec * dvdec)
338 {
339   gint i;
340
341   dvdec->found_header = FALSE;
342
343   dvdec->sinkpad =
344       gst_pad_new_from_template (gst_static_pad_template_get (&sink_temp),
345       "sink");
346   gst_pad_set_query_function (dvdec->sinkpad, NULL);
347   gst_pad_set_convert_function (dvdec->sinkpad,
348       GST_DEBUG_FUNCPTR (gst_dvdec_sink_convert));
349   gst_pad_set_formats_function (dvdec->sinkpad,
350       GST_DEBUG_FUNCPTR (gst_dvdec_get_formats));
351   gst_element_add_pad (GST_ELEMENT (dvdec), dvdec->sinkpad);
352
353   dvdec->videosrcpad =
354       gst_pad_new_from_template (gst_static_pad_template_get (&video_src_temp),
355       "video");
356   gst_pad_set_query_function (dvdec->videosrcpad,
357       GST_DEBUG_FUNCPTR (gst_dvdec_src_query));
358   gst_pad_set_query_type_function (dvdec->videosrcpad,
359       GST_DEBUG_FUNCPTR (gst_dvdec_get_src_query_types));
360   gst_pad_set_event_function (dvdec->videosrcpad,
361       GST_DEBUG_FUNCPTR (gst_dvdec_handle_src_event));
362   gst_pad_set_event_mask_function (dvdec->videosrcpad,
363       GST_DEBUG_FUNCPTR (gst_dvdec_get_event_masks));
364   gst_pad_set_convert_function (dvdec->videosrcpad,
365       GST_DEBUG_FUNCPTR (gst_dvdec_src_convert));
366   gst_pad_set_formats_function (dvdec->videosrcpad,
367       GST_DEBUG_FUNCPTR (gst_dvdec_get_formats));
368   gst_pad_set_getcaps_function (dvdec->videosrcpad,
369       GST_DEBUG_FUNCPTR (gst_dvdec_video_getcaps));
370   gst_pad_set_link_function (dvdec->videosrcpad,
371       GST_DEBUG_FUNCPTR (gst_dvdec_video_link));
372   gst_element_add_pad (GST_ELEMENT (dvdec), dvdec->videosrcpad);
373
374   dvdec->audiosrcpad =
375       gst_pad_new_from_template (gst_static_pad_template_get (&audio_src_temp),
376       "audio");
377   gst_pad_set_query_function (dvdec->audiosrcpad,
378       GST_DEBUG_FUNCPTR (gst_dvdec_src_query));
379   gst_pad_set_query_type_function (dvdec->audiosrcpad,
380       GST_DEBUG_FUNCPTR (gst_dvdec_get_src_query_types));
381   gst_pad_set_event_function (dvdec->audiosrcpad,
382       GST_DEBUG_FUNCPTR (gst_dvdec_handle_src_event));
383   gst_pad_set_event_mask_function (dvdec->audiosrcpad,
384       GST_DEBUG_FUNCPTR (gst_dvdec_get_event_masks));
385   gst_pad_set_convert_function (dvdec->audiosrcpad,
386       GST_DEBUG_FUNCPTR (gst_dvdec_src_convert));
387   gst_pad_set_formats_function (dvdec->audiosrcpad,
388       GST_DEBUG_FUNCPTR (gst_dvdec_get_formats));
389   gst_pad_use_explicit_caps (dvdec->audiosrcpad);
390   gst_element_add_pad (GST_ELEMENT (dvdec), dvdec->audiosrcpad);
391
392   gst_element_set_loop_function (GST_ELEMENT (dvdec), gst_dvdec_loop);
393
394   dvdec->bs = NULL;
395   dvdec->length = 0;
396   dvdec->next_ts = 0LL;
397   dvdec->end_position = -1LL;
398   dvdec->need_discont = FALSE;
399   dvdec->new_media = FALSE;
400   dvdec->framerate = 0;
401   dvdec->height = 0;
402   dvdec->frequency = 0;
403   dvdec->channels = 0;
404   dvdec->wide = FALSE;
405   dvdec->drop_factor = 1;
406
407   dvdec->clamp_luma = FALSE;
408   dvdec->clamp_chroma = FALSE;
409   dvdec->quality = DV_DEFAULT_QUALITY;
410   dvdec->loop = FALSE;
411
412   for (i = 0; i < 4; i++) {
413     dvdec->audio_buffers[i] =
414         (gint16 *) g_malloc (DV_AUDIO_MAX_SAMPLES * sizeof (gint16));
415   }
416 }
417
418 static const GstFormat *
419 gst_dvdec_get_formats (GstPad * pad)
420 {
421   static const GstFormat src_formats[] = {
422     GST_FORMAT_BYTES,
423     GST_FORMAT_DEFAULT,
424     GST_FORMAT_TIME,
425     0
426   };
427   static const GstFormat sink_formats[] = {
428     GST_FORMAT_BYTES,
429     GST_FORMAT_TIME,
430     GST_FORMAT_DEFAULT,
431     0
432   };
433
434   return (GST_PAD_IS_SRC (pad) ? src_formats : sink_formats);
435 }
436
437 static gboolean
438 gst_dvdec_src_convert (GstPad * pad, GstFormat src_format, gint64 src_value,
439     GstFormat * dest_format, gint64 * dest_value)
440 {
441   gboolean res = TRUE;
442   GstDVDec *dvdec;
443
444   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
445   if (dvdec->length == 0)
446     return FALSE;
447
448   if (dvdec->decoder == NULL)
449     return FALSE;
450
451   switch (src_format) {
452     case GST_FORMAT_BYTES:
453       switch (*dest_format) {
454         case GST_FORMAT_BYTES:
455           *dest_value = src_value;
456           break;
457         case GST_FORMAT_DEFAULT:
458         case GST_FORMAT_TIME:
459           *dest_format = GST_FORMAT_TIME;
460           if (pad == dvdec->videosrcpad)
461             *dest_value = src_value * GST_SECOND /
462                 (720 * dvdec->height * dvdec->bpp * dvdec->framerate /
463                 GST_SECOND);
464           else if (pad == dvdec->audiosrcpad)
465             *dest_value = src_value * GST_SECOND /
466                 (2 * dvdec->frequency * dvdec->channels);
467           break;
468         default:
469           res = FALSE;
470       }
471       break;
472     case GST_FORMAT_TIME:
473       switch (*dest_format) {
474         case GST_FORMAT_BYTES:
475           if (pad == dvdec->videosrcpad)
476             *dest_value = src_value * 720 * dvdec->height * dvdec->bpp *
477                 dvdec->framerate / GST_SECOND;
478           else if (pad == dvdec->audiosrcpad)
479             *dest_value = 2 * src_value * dvdec->frequency *
480                 dvdec->channels / GST_SECOND;
481           break;
482         case GST_FORMAT_TIME:
483         case GST_FORMAT_DEFAULT:
484           *dest_format = GST_FORMAT_TIME;
485           *dest_value = src_value;
486           break;
487         default:
488           res = FALSE;
489       }
490       break;
491     default:
492       res = FALSE;
493   }
494   return res;
495 }
496
497 static gboolean
498 gst_dvdec_sink_convert (GstPad * pad, GstFormat src_format, gint64 src_value,
499     GstFormat * dest_format, gint64 * dest_value)
500 {
501   gboolean res = TRUE;
502   GstDVDec *dvdec;
503
504   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
505
506   if (dvdec->length == 0)
507     return FALSE;
508
509   if (*dest_format == GST_FORMAT_DEFAULT)
510     *dest_format = GST_FORMAT_TIME;
511
512   switch (src_format) {
513     case GST_FORMAT_BYTES:
514       switch (*dest_format) {
515         case GST_FORMAT_TIME:
516         {
517           guint64 frame;
518
519           /* get frame number */
520           frame = src_value / dvdec->length;
521
522           *dest_value = (frame * GST_SECOND) / dvdec->framerate;
523           break;
524         }
525         case GST_FORMAT_BYTES:
526           *dest_value = src_value;
527           break;
528         default:
529           res = FALSE;
530       }
531       break;
532     case GST_FORMAT_TIME:
533       switch (*dest_format) {
534         case GST_FORMAT_BYTES:
535         {
536           guint64 frame;
537
538           /* calculate the frame */
539           frame = src_value * dvdec->framerate / GST_SECOND;
540           /* calculate the offset */
541           *dest_value = frame * dvdec->length;
542           break;
543         }
544         case GST_FORMAT_TIME:
545           *dest_value = src_value;
546           break;
547         default:
548           res = FALSE;
549       }
550       break;
551     default:
552       res = FALSE;
553   }
554   return res;
555 }
556
557 static const GstQueryType *
558 gst_dvdec_get_src_query_types (GstPad * pad)
559 {
560   static const GstQueryType src_query_types[] = {
561     GST_QUERY_TOTAL,
562     GST_QUERY_POSITION,
563     0
564   };
565
566   return src_query_types;
567 }
568
569 static gboolean
570 gst_dvdec_src_query (GstPad * pad, GstQueryType type,
571     GstFormat * format, gint64 * value)
572 {
573   gboolean res = TRUE;
574   GstDVDec *dvdec;
575
576   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
577
578   switch (type) {
579     case GST_QUERY_TOTAL:
580       switch (*format) {
581         default:
582         {
583           guint64 len;
584           GstFormat tmp_format;
585
586           if (!dvdec->bs)
587             return FALSE;
588
589           len = gst_bytestream_length (dvdec->bs);
590           tmp_format = GST_FORMAT_TIME;
591           if (len == -1 || !gst_pad_convert (dvdec->sinkpad,
592                   GST_FORMAT_BYTES, len, &tmp_format, value)) {
593             return FALSE;
594           }
595           if (!gst_pad_convert (pad, GST_FORMAT_TIME, *value, format, value)) {
596             return FALSE;
597           }
598           break;
599         }
600       }
601       break;
602     case GST_QUERY_POSITION:
603       switch (*format) {
604         default:
605           res =
606               gst_pad_convert (pad, GST_FORMAT_TIME, dvdec->next_ts, format,
607               value);
608           break;
609       }
610       break;
611     default:
612       res = FALSE;
613       break;
614   }
615   return res;
616 }
617
618 static const GstEventMask *
619 gst_dvdec_get_event_masks (GstPad * pad)
620 {
621   static const GstEventMask src_event_masks[] = {
622     {GST_EVENT_SEEK, GST_SEEK_METHOD_SET | GST_SEEK_FLAG_FLUSH},
623     {0,}
624   };
625   static const GstEventMask sink_event_masks[] = {
626     {GST_EVENT_EOS, 0},
627     {GST_EVENT_DISCONTINUOUS, 0},
628     {GST_EVENT_FLUSH, 0},
629     {0,}
630   };
631
632   return (GST_PAD_IS_SRC (pad) ? src_event_masks : sink_event_masks);
633 }
634
635 static gboolean
636 gst_dvdec_handle_sink_event (GstDVDec * dvdec)
637 {
638   guint32 remaining;
639   GstEvent *event;
640   GstEventType type;
641
642   gst_bytestream_get_status (dvdec->bs, &remaining, &event);
643
644   type = event ? GST_EVENT_TYPE (event) : GST_EVENT_UNKNOWN;
645
646   switch (type) {
647     case GST_EVENT_FLUSH:
648     case GST_EVENT_EOS:
649     case GST_EVENT_FILLER:
650     {
651       /* Forward the event to output sinks */
652       if (GST_PAD_IS_LINKED (dvdec->videosrcpad)) {
653         gst_event_ref (event);
654         gst_pad_push (dvdec->videosrcpad, GST_DATA (event));
655       }
656       if (GST_PAD_IS_LINKED (dvdec->audiosrcpad)) {
657         gst_event_ref (event);
658         gst_pad_push (dvdec->audiosrcpad, GST_DATA (event));
659       }
660       if (type == GST_EVENT_EOS) {
661         gst_element_set_eos (GST_ELEMENT (dvdec));
662       }
663       break;
664     }
665     case GST_EVENT_DISCONTINUOUS:
666     {
667       gint i;
668       gboolean found = FALSE;
669       GstFormat format;
670
671       format = GST_FORMAT_TIME;
672       /* try to get a timestamp from the discont formats */
673       for (i = 0; i < GST_EVENT_DISCONT_OFFSET_LEN (event); i++) {
674         if (gst_pad_convert (dvdec->sinkpad,
675                 GST_EVENT_DISCONT_OFFSET (event, i).format,
676                 GST_EVENT_DISCONT_OFFSET (event, i).value,
677                 &format, &dvdec->next_ts)) {
678           found = TRUE;
679           break;
680         }
681       }
682       /* assume 0 then */
683       if (!found) {
684         dvdec->next_ts = 0LL;
685       }
686       dvdec->need_discont = TRUE;
687       break;
688     }
689     default:
690       return gst_pad_event_default (dvdec->sinkpad, event);
691       break;
692   }
693   gst_event_unref (event);
694   return TRUE;
695 }
696
697 static gboolean
698 gst_dvdec_handle_src_event (GstPad * pad, GstEvent * event)
699 {
700   gboolean res = TRUE;
701   GstDVDec *dvdec;
702
703   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
704
705   switch (GST_EVENT_TYPE (event)) {
706     case GST_EVENT_SEEK_SEGMENT:
707     {
708       gint64 position;
709       GstFormat format;
710
711       /* first bring the format to time */
712       format = GST_FORMAT_TIME;
713       if (!gst_pad_convert (pad,
714               GST_EVENT_SEEK_FORMAT (event),
715               GST_EVENT_SEEK_ENDOFFSET (event), &format, &position)) {
716         /* could not convert seek format to time offset */
717         res = FALSE;
718         break;
719       }
720
721       dvdec->end_position = position;
722       dvdec->loop = GST_EVENT_SEEK_TYPE (event) & GST_SEEK_FLAG_SEGMENT_LOOP;
723     }
724     case GST_EVENT_SEEK:
725     {
726       gint64 position;
727       GstFormat format;
728
729       /* first bring the format to time */
730       format = GST_FORMAT_TIME;
731       if (!gst_pad_convert (pad,
732               GST_EVENT_SEEK_FORMAT (event),
733               GST_EVENT_SEEK_OFFSET (event), &format, &position)) {
734         /* could not convert seek format to time offset */
735         res = FALSE;
736         break;
737       }
738       dvdec->next_ts = position;
739       /* then try to figure out the byteoffset for this time */
740       format = GST_FORMAT_BYTES;
741       if (!gst_pad_convert (dvdec->sinkpad, GST_FORMAT_TIME, position,
742               &format, &position)) {
743         /* could not convert seek format to byte offset */
744         res = FALSE;
745         break;
746       }
747       /* seek to offset */
748       if (!gst_bytestream_seek (dvdec->bs, position, GST_SEEK_METHOD_SET)) {
749         res = FALSE;
750       }
751       if (GST_EVENT_TYPE (event) != GST_EVENT_SEEK_SEGMENT)
752         dvdec->end_position = -1;
753       break;
754     }
755     default:
756       res = FALSE;
757       break;
758   }
759   gst_event_unref (event);
760   return res;
761 }
762
763 static GstCaps *
764 gst_dvdec_video_getcaps (GstPad * pad)
765 {
766   GstDVDec *dvdec;
767   GstCaps *caps;
768   GstPadTemplate *src_pad_template;
769
770   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
771   src_pad_template = gst_static_pad_template_get (&video_src_temp);
772   caps = gst_caps_copy (gst_pad_template_get_caps (src_pad_template));
773
774   if (dvdec->found_header) {
775     int i;
776     gint par_x, par_y;
777
778     if (dvdec->PAL) {
779       if (dvdec->wide) {
780         par_x = PAL_WIDE_PAR_X;
781         par_y = PAL_WIDE_PAR_Y;
782       } else {
783         par_x = PAL_NORMAL_PAR_X;
784         par_y = PAL_NORMAL_PAR_Y;
785       }
786     } else {
787       if (dvdec->wide) {
788         par_x = NTSC_WIDE_PAR_X;
789         par_y = NTSC_WIDE_PAR_Y;
790       } else {
791         par_x = NTSC_NORMAL_PAR_X;
792         par_y = NTSC_NORMAL_PAR_Y;
793       }
794     }
795     /* set the height */
796     for (i = 0; i < gst_caps_get_size (caps); i++) {
797       GstStructure *structure = gst_caps_get_structure (caps, i);
798
799       gst_structure_set (structure,
800           "height", G_TYPE_INT, dvdec->height,
801           "framerate", G_TYPE_DOUBLE, dvdec->framerate / dvdec->drop_factor,
802           "pixel-aspect-ratio", GST_TYPE_FRACTION, par_x, par_y, NULL);
803     }
804   }
805
806   return caps;
807 }
808
809 static GstPadLinkReturn
810 gst_dvdec_video_link (GstPad * pad, const GstCaps * caps)
811 {
812   GstDVDec *dvdec;
813   GstStructure *structure;
814   guint32 fourcc;
815   gint height;
816   gdouble framerate;
817
818   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
819
820   /* if we did not find a header yet, return delayed */
821   if (!dvdec->found_header) {
822     return GST_PAD_LINK_DELAYED;
823   }
824
825   structure = gst_caps_get_structure (caps, 0);
826
827   if (!gst_structure_get_int (structure, "height", &height) ||
828       !gst_structure_get_double (structure, "framerate", &framerate))
829     return GST_PAD_LINK_REFUSED;
830
831   /* allow a margin of error for the framerate caused by float rounding errors */
832   if ((height != dvdec->height) ||
833       (fabs (framerate - (dvdec->framerate / dvdec->drop_factor)) > 0.00000001))
834     return GST_PAD_LINK_REFUSED;
835
836   if (strcmp (gst_structure_get_name (structure), "video/x-raw-rgb") == 0) {
837     gint bpp;
838
839     gst_structure_get_int (structure, "bpp", &bpp);
840     if (bpp == 24) {
841       dvdec->space = e_dv_color_rgb;
842       dvdec->bpp = 3;
843     } else {
844       dvdec->space = e_dv_color_bgr0;
845       dvdec->bpp = 4;
846     }
847   } else {
848     if (!gst_structure_get_fourcc (structure, "format", &fourcc))
849       return GST_PAD_LINK_REFUSED;
850
851     dvdec->space = e_dv_color_yuv;
852     dvdec->bpp = 2;
853   }
854
855   return GST_PAD_LINK_OK;
856 }
857
858 static void
859 gst_dvdec_push (GstDVDec * dvdec, GstBuffer * outbuf, GstPad * pad,
860     GstClockTime ts)
861 {
862   if ((dvdec->need_discont) || (dvdec->new_media)) {
863     GstEvent *discont;
864
865     discont = gst_event_new_discontinuous (FALSE, GST_FORMAT_TIME, ts, NULL);
866     GST_EVENT_DISCONT_NEW_MEDIA (discont) = dvdec->new_media;
867
868     gst_pad_push (pad, GST_DATA (discont));
869   }
870
871   gst_pad_push (pad, GST_DATA (outbuf));
872
873   if ((dvdec->end_position != -1) && (dvdec->next_ts >= dvdec->end_position)) {
874     if (dvdec->loop)
875       gst_pad_push (pad, GST_DATA (gst_event_new (GST_EVENT_SEGMENT_DONE)));
876     else
877       gst_pad_push (pad, GST_DATA (gst_event_new (GST_EVENT_EOS)));
878   }
879 }
880
881 static void
882 gst_dvdec_loop (GstElement * element)
883 {
884   GstDVDec *dvdec;
885   GstBuffer *buf, *outbuf;
886   guint8 *inframe;
887   gint height;
888   guint32 length, got_bytes;
889   GstClockTime ts, duration;
890   gdouble fps;
891   gboolean wide;
892
893   dvdec = GST_DVDEC (element);
894
895   /*
896    * Apparently dv_parse_header can read from the body of the frame
897    * too, so it needs more than header_size bytes. Wacky!
898    */
899   if (dvdec->found_header)
900     length = (dvdec->PAL ? PAL_BUFFER : NTSC_BUFFER);
901   else
902     length = NTSC_BUFFER;
903
904   /* first read enough bytes to parse the header */
905   got_bytes = gst_bytestream_peek_bytes (dvdec->bs, &inframe, length);
906   if (got_bytes < length) {
907     gst_dvdec_handle_sink_event (dvdec);
908     return;
909   }
910   if (dv_parse_header (dvdec->decoder, inframe) < 0) {
911     GST_ELEMENT_ERROR (dvdec, STREAM, DECODE, (NULL), (NULL));
912     return;
913   }
914
915   /* after parsing the header we know the length of the data */
916   dvdec->PAL = dv_system_50_fields (dvdec->decoder);
917   dvdec->found_header = TRUE;
918
919   fps = (dvdec->PAL ? PAL_FRAMERATE : NTSC_FRAMERATE);
920   height = (dvdec->PAL ? PAL_HEIGHT : NTSC_HEIGHT);
921   length = (dvdec->PAL ? PAL_BUFFER : NTSC_BUFFER);
922   wide = dv_format_wide (dvdec->decoder);
923
924   if (length != dvdec->length) {
925     dvdec->length = length;
926     gst_bytestream_size_hint (dvdec->bs, length);
927   }
928
929   /* then read the read data */
930   got_bytes = gst_bytestream_read (dvdec->bs, &buf, length);
931   if (got_bytes < length) {
932     gst_dvdec_handle_sink_event (dvdec);
933     return;
934   }
935
936   ts = dvdec->next_ts;
937   dvdec->next_ts += GST_SECOND / fps;
938   duration = dvdec->next_ts - ts;
939
940   dv_parse_packs (dvdec->decoder, GST_BUFFER_DATA (buf));
941   if (dv_is_new_recording (dvdec->decoder, GST_BUFFER_DATA (buf)))
942     dvdec->new_media = TRUE;
943   if (GST_PAD_IS_LINKED (dvdec->audiosrcpad)) {
944     gint num_samples;
945
946     dv_decode_full_audio (dvdec->decoder, GST_BUFFER_DATA (buf),
947         dvdec->audio_buffers);
948
949     if ((dv_get_frequency (dvdec->decoder) != dvdec->frequency) ||
950         (dv_get_num_channels (dvdec->decoder) != dvdec->channels)) {
951       if (!gst_pad_set_explicit_caps (dvdec->audiosrcpad,
952               gst_caps_new_simple ("audio/x-raw-int",
953                   "rate", G_TYPE_INT, dv_get_frequency (dvdec->decoder),
954                   "depth", G_TYPE_INT, 16,
955                   "width", G_TYPE_INT, 16,
956                   "signed", G_TYPE_BOOLEAN, TRUE,
957                   "channels", G_TYPE_INT, dv_get_num_channels (dvdec->decoder),
958                   "endianness", G_TYPE_INT, G_LITTLE_ENDIAN, NULL))) {
959         gst_buffer_unref (buf);
960         GST_ELEMENT_ERROR (dvdec, CORE, NEGOTIATION, (NULL),
961             ("Failed to negotiate audio parameters for the DV audio stream"));
962         return;
963       }
964
965       dvdec->frequency = dv_get_frequency (dvdec->decoder);
966       dvdec->channels = dv_get_num_channels (dvdec->decoder);
967     }
968
969     num_samples = dv_get_num_samples (dvdec->decoder);
970
971     if (num_samples) {
972       gint16 *a_ptr;
973       gint i, j;
974
975       outbuf = gst_buffer_new ();
976       GST_BUFFER_SIZE (outbuf) = dv_get_num_samples (dvdec->decoder) *
977           sizeof (gint16) * dv_get_num_channels (dvdec->decoder);
978       GST_BUFFER_DATA (outbuf) = g_malloc (GST_BUFFER_SIZE (outbuf));
979
980       a_ptr = (gint16 *) GST_BUFFER_DATA (outbuf);
981
982       for (i = 0; i < num_samples; i++) {
983         for (j = 0; j < dv_get_num_channels (dvdec->decoder); j++) {
984           *(a_ptr++) = dvdec->audio_buffers[j][i];
985         }
986       }
987
988       GST_BUFFER_TIMESTAMP (outbuf) = ts;
989       GST_BUFFER_DURATION (outbuf) = duration;
990       GST_BUFFER_OFFSET (outbuf) = dvdec->audio_offset;
991       dvdec->audio_offset += num_samples;
992       GST_BUFFER_OFFSET_END (outbuf) = dvdec->audio_offset;
993
994       gst_dvdec_push (dvdec, outbuf, dvdec->audiosrcpad, ts);
995     }
996   } else {
997     dvdec->frequency = dv_get_frequency (dvdec->decoder);
998     dvdec->channels = dv_get_num_channels (dvdec->decoder);
999   }
1000
1001   if (GST_PAD_IS_LINKED (dvdec->videosrcpad)) {
1002     guint8 *outframe;
1003     guint8 *outframe_ptrs[3];
1004     gint outframe_pitches[3];
1005
1006     dvdec->framecount++;
1007     if (dvdec->framecount < dvdec->drop_factor) {
1008       /* don't decode */
1009       goto end;
1010     }
1011     dvdec->framecount = 0;
1012
1013     if ((dvdec->framerate != fps) || (dvdec->height != height)
1014         || dvdec->wide != wide) {
1015       dvdec->height = height;
1016       dvdec->framerate = fps;
1017       dvdec->wide = wide;
1018
1019       if (GST_PAD_LINK_FAILED (gst_pad_renegotiate (dvdec->videosrcpad))) {
1020         GST_ELEMENT_ERROR (dvdec, CORE, NEGOTIATION, (NULL), (NULL));
1021         return;
1022       }
1023     }
1024
1025     outbuf = gst_buffer_new_and_alloc ((720 * height) * dvdec->bpp);
1026
1027     outframe = GST_BUFFER_DATA (outbuf);
1028
1029     outframe_ptrs[0] = outframe;
1030     outframe_pitches[0] = 720 * dvdec->bpp;
1031
1032     /* the rest only matters for YUY2 */
1033     if (dvdec->bpp < 3) {
1034       outframe_ptrs[1] = outframe_ptrs[0] + 720 * height;
1035       outframe_ptrs[2] = outframe_ptrs[1] + 360 * height;
1036
1037       outframe_pitches[1] = height / 2;
1038       outframe_pitches[2] = outframe_pitches[1];
1039     }
1040
1041     dv_decode_full_frame (dvdec->decoder, GST_BUFFER_DATA (buf),
1042         dvdec->space, outframe_ptrs, outframe_pitches);
1043
1044     GST_BUFFER_TIMESTAMP (outbuf) = ts;
1045     GST_BUFFER_DURATION (outbuf) = duration * dvdec->drop_factor;
1046
1047     gst_dvdec_push (dvdec, outbuf, dvdec->videosrcpad, ts);
1048   } else {
1049     dvdec->height = height;
1050     dvdec->framerate = fps;
1051     dvdec->wide = wide;
1052   }
1053
1054 end:
1055   if ((dvdec->end_position != -1) &&
1056       (dvdec->next_ts >= dvdec->end_position) && !dvdec->loop) {
1057     gst_element_set_eos (GST_ELEMENT (dvdec));
1058   }
1059
1060   dvdec->need_discont = FALSE;
1061   dvdec->new_media = FALSE;
1062
1063   gst_buffer_unref (buf);
1064 }
1065
1066 static GstElementStateReturn
1067 gst_dvdec_change_state (GstElement * element)
1068 {
1069   GstDVDec *dvdec = GST_DVDEC (element);
1070
1071   switch (GST_STATE_TRANSITION (element)) {
1072     case GST_STATE_NULL_TO_READY:
1073       break;
1074     case GST_STATE_READY_TO_PAUSED:
1075       dvdec->bs = gst_bytestream_new (dvdec->sinkpad);
1076       dvdec->decoder =
1077           dv_decoder_new (0, dvdec->clamp_luma, dvdec->clamp_chroma);
1078       dvdec->decoder->quality = qualities[dvdec->quality];
1079       dvdec->audio_offset = 0;
1080       dvdec->framecount = 0;
1081       /* 
1082        * Enable this function call when libdv2 0.100 or higher is more
1083        * common
1084        */
1085       /* dv_set_quality (dvdec->decoder, qualities [dvdec->quality]); */
1086       break;
1087     case GST_STATE_PAUSED_TO_PLAYING:
1088       break;
1089     case GST_STATE_PLAYING_TO_PAUSED:
1090       break;
1091     case GST_STATE_PAUSED_TO_READY:
1092       dv_decoder_free (dvdec->decoder);
1093       dvdec->decoder = NULL;
1094       dvdec->found_header = FALSE;
1095       gst_bytestream_destroy (dvdec->bs);
1096       dvdec->bs = NULL;
1097       break;
1098     case GST_STATE_READY_TO_NULL:
1099       break;
1100     default:
1101       break;
1102   }
1103
1104   return parent_class->change_state (element);
1105 }
1106
1107 /* Arguments are part of the Gtk+ object system, and these functions
1108  * enable the element to respond to various arguments.
1109  */
1110 static void
1111 gst_dvdec_set_property (GObject * object, guint prop_id, const GValue * value,
1112     GParamSpec * pspec)
1113 {
1114   GstDVDec *dvdec;
1115
1116   /* It's not null if we got it, but it might not be ours */
1117   g_return_if_fail (GST_IS_DVDEC (object));
1118
1119   /* Get a pointer of the right type. */
1120   dvdec = GST_DVDEC (object);
1121
1122   /* Check the argument id to see which argument we're setting. */
1123   switch (prop_id) {
1124     case ARG_CLAMP_LUMA:
1125       dvdec->clamp_luma = g_value_get_boolean (value);
1126       break;
1127     case ARG_CLAMP_CHROMA:
1128       dvdec->clamp_chroma = g_value_get_boolean (value);
1129       break;
1130     case ARG_QUALITY:
1131       dvdec->quality = g_value_get_enum (value);
1132       if ((dvdec->quality < 0) || (dvdec->quality > 5))
1133         dvdec->quality = 0;
1134       break;
1135     case ARG_DECODE_NTH:
1136       dvdec->drop_factor = g_value_get_int (value);
1137       break;
1138     default:
1139       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1140       break;
1141   }
1142 }
1143
1144 /* The set function is simply the inverse of the get fuction. */
1145 static void
1146 gst_dvdec_get_property (GObject * object, guint prop_id, GValue * value,
1147     GParamSpec * pspec)
1148 {
1149   GstDVDec *dvdec;
1150
1151   /* It's not null if we got it, but it might not be ours */
1152   g_return_if_fail (GST_IS_DVDEC (object));
1153   dvdec = GST_DVDEC (object);
1154
1155   switch (prop_id) {
1156     case ARG_CLAMP_LUMA:
1157       g_value_set_boolean (value, dvdec->clamp_luma);
1158       break;
1159     case ARG_CLAMP_CHROMA:
1160       g_value_set_boolean (value, dvdec->clamp_chroma);
1161       break;
1162     case ARG_QUALITY:
1163       g_value_set_enum (value, dvdec->quality);
1164       break;
1165     case ARG_DECODE_NTH:
1166       g_value_set_int (value, dvdec->drop_factor);
1167       break;
1168     default:
1169       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1170       break;
1171   }
1172 }
1173
1174 /* This is the entry into the plugin itself.  When the plugin loads,
1175  * this function is called to register everything that the plugin provides.
1176  */
1177 static gboolean
1178 plugin_init (GstPlugin * plugin)
1179 {
1180   if (!gst_library_load ("gstbytestream"))
1181     return FALSE;
1182
1183   if (!gst_element_register (plugin, "dvdec", GST_RANK_PRIMARY,
1184           gst_dvdec_get_type ()))
1185     return FALSE;
1186
1187   return TRUE;
1188 }
1189
1190 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1191     GST_VERSION_MINOR,
1192     "dvdec",
1193     "Uses libdv to decode DV video (libdv.sourceforge.net)",
1194     plugin_init, VERSION, "LGPL", GST_PACKAGE, GST_ORIGIN);