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