New mimetypes gone into effect today - this commit changes all old mimetypes over...
[platform/upstream/gstreamer.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 PAL_HEIGHT 576
33 #define PAL_BUFFER 144000
34
35 /* The ElementDetails structure gives a human-readable description
36  * of the plugin, as well as author and version data.
37  */
38 static GstElementDetails dvdec_details = {
39   "DV (smpte314) decoder plugin",
40   "Codec/Video/Decoder",
41   "LGPL",
42   "Uses libdv to decode DV video (libdv.sourceforge.net)",
43   VERSION,
44   "Erik Walthinsen <omega@cse.ogi.edu>\n"
45   "Wim Taymans <wim.taymans@tvd.be>",
46   "(C) 2001-2002",
47 };
48
49
50 /* These are the signals that this element can fire.  They are zero-
51  * based because the numbers themselves are private to the object.
52  * LAST_SIGNAL is used for initialization of the signal array.
53  */
54 enum {
55   /* FILL ME */
56   LAST_SIGNAL
57 };
58
59 /* Arguments are identified the same way, but cannot be zero, so you
60  * must leave the ARG_0 entry in as a placeholder.
61  */
62 enum {
63   ARG_0,
64   ARG_CLAMP_LUMA,
65   ARG_CLAMP_CHROMA,
66   ARG_QUALITY,
67   /* FILL ME */
68 };
69
70 /* The PadFactory structures describe what pads the element has or
71  * can have.  They can be quite complex, but for this dvdec plugin
72  * they are rather simple.
73  */
74 GST_PAD_TEMPLATE_FACTORY (sink_temp,
75   "sink",
76   GST_PAD_SINK,
77   GST_PAD_ALWAYS,
78   GST_CAPS_NEW (
79     "dv_dec_sink",
80     "video/x-dv",
81     "systemstream", GST_PROPS_BOOLEAN (TRUE)
82   )
83 )
84
85
86 GST_PAD_TEMPLATE_FACTORY (video_src_temp,
87   "video",
88   GST_PAD_SRC,
89   GST_PAD_ALWAYS,
90   GST_CAPS_NEW (
91     "dv_dec_src",
92     "video/x-raw-yuv",
93     "format",           GST_PROPS_FOURCC (GST_MAKE_FOURCC ('Y','U','Y','2')),
94     "width",            GST_PROPS_INT (720),
95     "height",           GST_PROPS_LIST (
96                           GST_PROPS_INT (NTSC_HEIGHT),
97                           GST_PROPS_INT (PAL_HEIGHT)
98                         ),
99     "framerate",        GST_PROPS_LIST (
100                           GST_PROPS_FLOAT (25.),
101                           GST_PROPS_FLOAT (30/1.001)
102                         )
103   ),
104   GST_CAPS_NEW (
105     "dv_dec_src",
106     "video/x-raw-rgb",
107     "bpp",              GST_PROPS_INT(32),
108     "depth",            GST_PROPS_INT(32),
109     "endianness",       GST_PROPS_INT (G_BIG_ENDIAN),
110     "red_mask",         GST_PROPS_INT(0x000000ff),
111     "green_mask",       GST_PROPS_INT(0x0000ff00),
112     "blue_mask",        GST_PROPS_INT(0x00ff00),
113     "width",            GST_PROPS_INT (720),
114     "height",           GST_PROPS_LIST (
115                           GST_PROPS_INT (NTSC_HEIGHT),
116                           GST_PROPS_INT (PAL_HEIGHT)
117                         ),
118     "framerate",        GST_PROPS_LIST (
119                           GST_PROPS_FLOAT (25.),
120                           GST_PROPS_FLOAT (30/1.001)
121                         )
122   ),
123   GST_CAPS_NEW (
124     "dv_dec_src",
125     "video/x-raw-rgb",
126     "bpp",              GST_PROPS_INT(24),
127     "depth",            GST_PROPS_INT(24),
128     "endianness",       GST_PROPS_INT (G_BIG_ENDIAN),
129     "red_mask",         GST_PROPS_INT(0x0000ff),
130     "green_mask",       GST_PROPS_INT(0x00ff00),
131     "blue_mask",        GST_PROPS_INT(0xff0000),
132     "width",            GST_PROPS_INT (720),
133     "height",           GST_PROPS_LIST (
134                           GST_PROPS_INT (NTSC_HEIGHT),
135                           GST_PROPS_INT (PAL_HEIGHT)
136                         ),
137     "framerate",        GST_PROPS_LIST (
138                           GST_PROPS_FLOAT (25.),
139                           GST_PROPS_FLOAT (30/1.001)
140                         )
141   )
142 )
143
144 GST_PAD_TEMPLATE_FACTORY ( audio_src_temp,
145   "audio",
146   GST_PAD_SRC,
147   GST_PAD_ALWAYS,
148   GST_CAPS_NEW (
149     "arts_sample",
150     "audio/x-raw-int",
151     "depth",            GST_PROPS_INT (16),
152     "width",            GST_PROPS_INT (16),
153     "signed",           GST_PROPS_BOOLEAN (TRUE),
154     "channels",         GST_PROPS_INT (2),
155     "endianness",       GST_PROPS_INT (G_LITTLE_ENDIAN),
156     "rate",             GST_PROPS_INT_RANGE (4000, 48000)
157   )
158 )
159
160 /* typefind stuff */
161 static GstCaps*
162 dv_type_find (GstBuffer *buf, gpointer private)
163 {
164   guint32 head = GUINT32_FROM_BE(*((guint32 *)GST_BUFFER_DATA(buf)));
165   GstCaps *new = NULL;
166
167   /* check for DIF  and DV flag */
168   if ((head & 0xffffff00) == 0x1f070000 && !(GST_BUFFER_DATA(buf)[4] & 0x01)) {
169     gchar *format;
170
171     if ((head & 0x000000ff) & 0x80)
172       format = "PAL";
173     else
174       format = "NTSC";
175     
176     new = GST_CAPS_NEW ("dv_type_find",
177                         "video/x-dv",
178                           "systemstream", GST_PROPS_BOOLEAN (TRUE)
179                        );
180   }
181   return new;
182 }
183
184 static GstTypeDefinition dv_definition = {
185   "dv_video/dv", "video/x-dv", ".dv", dv_type_find 
186 };
187
188 #define GST_TYPE_DVDEC_QUALITY (gst_dvdec_quality_get_type())
189 GType
190 gst_dvdec_quality_get_type (void)
191 {
192   static GType qtype = 0;
193   if (qtype == 0) {
194     static const GFlagsValue values[] = {
195       { DV_QUALITY_COLOR, "DV_QUALITY_COLOR", "Color or monochrome decoding" },
196       { DV_QUALITY_AC_1,  "DV_QUALITY_AC_1",  "AC 1 something" },
197       { DV_QUALITY_AC_2,  "DV_QUALITY_AC_2",  "AC 2 something" },
198       { 0, NULL, NULL }
199     };
200     qtype = g_flags_register_static ("GstDVDecQualityFlags", values);
201   }
202   return qtype;
203 }
204
205 /* A number of functon prototypes are given so we can refer to them later. */
206 static void             gst_dvdec_class_init            (GstDVDecClass *klass);
207 static void             gst_dvdec_init                  (GstDVDec *dvdec);
208
209 static const GstQueryType* 
210                         gst_dvdec_get_src_query_types   (GstPad *pad);
211 static gboolean         gst_dvdec_src_query             (GstPad *pad, GstQueryType type,
212                                                          GstFormat *format, gint64 *value);
213 static const GstFormat* gst_dvdec_get_formats           (GstPad *pad);
214 static gboolean         gst_dvdec_sink_convert          (GstPad *pad, GstFormat src_format, gint64 src_value,
215                                                          GstFormat *dest_format, gint64 *dest_value);
216 static gboolean         gst_dvdec_src_convert           (GstPad *pad, GstFormat src_format, gint64 src_value,
217                                                          GstFormat *dest_format, gint64 *dest_value);
218
219 static const GstEventMask*
220                         gst_dvdec_get_event_masks       (GstPad *pad);
221 static gboolean         gst_dvdec_handle_src_event      (GstPad *pad, GstEvent *event);
222
223 static void             gst_dvdec_loop                  (GstElement *element);
224
225 static GstElementStateReturn    
226                         gst_dvdec_change_state          (GstElement *element);
227
228 static void             gst_dvdec_set_property          (GObject *object, guint prop_id, 
229                                                          const GValue *value, GParamSpec *pspec);
230 static void             gst_dvdec_get_property          (GObject *object, guint prop_id, 
231                                                          GValue *value, GParamSpec *pspec);
232
233 /* The parent class pointer needs to be kept around for some object
234  * operations.
235  */
236 static GstElementClass *parent_class = NULL;
237
238 /* This array holds the ids of the signals registered for this object.
239  * The array indexes are based on the enum up above.
240  */
241 /*static guint gst_dvdec_signals[LAST_SIGNAL] = { 0 }; */
242
243 /* This function is used to register and subsequently return the type
244  * identifier for this object class.  On first invocation, it will
245  * register the type, providing the name of the class, struct sizes,
246  * and pointers to the various functions that define the class.
247  */
248 GType
249 gst_dvdec_get_type (void)
250 {
251   static GType dvdec_type = 0;
252
253   if (!dvdec_type) {
254     static const GTypeInfo dvdec_info = {
255       sizeof (GstDVDecClass),      
256       NULL,      
257       NULL,
258       (GClassInitFunc) gst_dvdec_class_init,
259       NULL,
260       NULL,
261       sizeof (GstDVDec),
262       0,
263       (GInstanceInitFunc) gst_dvdec_init,
264     };
265     dvdec_type = g_type_register_static (GST_TYPE_ELEMENT, "GstDVDec", &dvdec_info, 0);
266   }
267   return dvdec_type;
268 }
269
270 /* In order to create an instance of an object, the class must be
271  * initialized by this function.  GObject will take care of running
272  * it, based on the pointer to the function provided above.
273  */
274 static void
275 gst_dvdec_class_init (GstDVDecClass *klass)
276 {
277   /* Class pointers are needed to supply pointers to the private
278    * implementations of parent class methods.
279    */
280   GObjectClass *gobject_class;
281   GstElementClass *gstelement_class;
282
283   /* Since the dvdec class contains the parent classes, you can simply
284    * cast the pointer to get access to the parent classes.
285    */
286   gobject_class = (GObjectClass*) klass;
287   gstelement_class = (GstElementClass*) klass;
288
289   /* The parent class is needed for class method overrides. */
290   parent_class = g_type_class_ref (GST_TYPE_ELEMENT);
291
292   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_CLAMP_LUMA,
293     g_param_spec_boolean ("clamp_luma", "Clamp luma", "Clamp luma",
294                           FALSE, G_PARAM_READWRITE));
295   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_CLAMP_CHROMA,
296     g_param_spec_boolean ("clamp_chroma", "Clamp chroma", "Clamp chroma",
297                           FALSE, G_PARAM_READWRITE));
298   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_QUALITY,
299     g_param_spec_flags ("quality", "Quality", "Decoding quality",
300                         GST_TYPE_DVDEC_QUALITY, DV_QUALITY_BEST, G_PARAM_READWRITE));
301
302   gobject_class->set_property = gst_dvdec_set_property;
303   gobject_class->get_property = gst_dvdec_get_property;
304   
305   gstelement_class->change_state = gst_dvdec_change_state;
306
307   /* table initialization, only do once */
308   dv_init(0, 0);
309 }
310
311 /* This function is responsible for initializing a specific instance of
312  * the plugin.
313  */
314 static void
315 gst_dvdec_init(GstDVDec *dvdec)
316 {
317   gint i;
318
319   dvdec->sinkpad = gst_pad_new_from_template (GST_PAD_TEMPLATE_GET (sink_temp), "sink");
320   gst_element_add_pad (GST_ELEMENT (dvdec), dvdec->sinkpad);
321   gst_pad_set_query_function (dvdec->sinkpad, NULL);
322   gst_pad_set_convert_function (dvdec->sinkpad, GST_DEBUG_FUNCPTR (gst_dvdec_sink_convert));
323   gst_pad_set_formats_function (dvdec->sinkpad, GST_DEBUG_FUNCPTR (gst_dvdec_get_formats));
324
325   dvdec->videosrcpad = gst_pad_new_from_template (GST_PAD_TEMPLATE_GET (video_src_temp), "video");
326   gst_element_add_pad (GST_ELEMENT (dvdec), dvdec->videosrcpad);
327   gst_pad_set_query_function (dvdec->videosrcpad, GST_DEBUG_FUNCPTR (gst_dvdec_src_query));
328   gst_pad_set_query_type_function (dvdec->videosrcpad, GST_DEBUG_FUNCPTR (gst_dvdec_get_src_query_types));
329   gst_pad_set_event_function (dvdec->videosrcpad, GST_DEBUG_FUNCPTR (gst_dvdec_handle_src_event));
330   gst_pad_set_event_mask_function (dvdec->videosrcpad, GST_DEBUG_FUNCPTR (gst_dvdec_get_event_masks));
331   gst_pad_set_convert_function (dvdec->videosrcpad, GST_DEBUG_FUNCPTR (gst_dvdec_src_convert));
332   gst_pad_set_formats_function (dvdec->videosrcpad, GST_DEBUG_FUNCPTR (gst_dvdec_get_formats));
333
334   dvdec->audiosrcpad = gst_pad_new_from_template (GST_PAD_TEMPLATE_GET(audio_src_temp), "audio");
335   gst_element_add_pad(GST_ELEMENT(dvdec),dvdec->audiosrcpad);
336   gst_pad_set_query_function (dvdec->audiosrcpad, GST_DEBUG_FUNCPTR (gst_dvdec_src_query));
337   gst_pad_set_query_type_function (dvdec->audiosrcpad, GST_DEBUG_FUNCPTR (gst_dvdec_get_src_query_types));
338   gst_pad_set_event_function (dvdec->audiosrcpad, GST_DEBUG_FUNCPTR (gst_dvdec_handle_src_event));
339   gst_pad_set_event_mask_function (dvdec->audiosrcpad, GST_DEBUG_FUNCPTR (gst_dvdec_get_event_masks));
340   gst_pad_set_convert_function (dvdec->audiosrcpad, GST_DEBUG_FUNCPTR (gst_dvdec_src_convert));
341   gst_pad_set_formats_function (dvdec->audiosrcpad, GST_DEBUG_FUNCPTR (gst_dvdec_get_formats));
342
343   gst_element_set_loop_function (GST_ELEMENT (dvdec), gst_dvdec_loop);
344
345   dvdec->pool = NULL;
346   dvdec->length = 0;
347   dvdec->next_ts = 0LL;
348   dvdec->end_position = -1LL;
349   dvdec->need_discont = FALSE;
350   dvdec->framerate = 0;
351   dvdec->height = 0;
352   dvdec->clamp_luma = FALSE;
353   dvdec->clamp_chroma = FALSE;
354   dvdec->quality = DV_QUALITY_BEST;
355   dvdec->loop = FALSE;
356
357   for (i = 0; i <4; i++) {
358     dvdec->audio_buffers[i] = (gint16 *)g_malloc (DV_AUDIO_MAX_SAMPLES * sizeof (gint16));
359   }
360 }
361
362 static const GstFormat*
363 gst_dvdec_get_formats (GstPad *pad)
364 {
365   static const GstFormat src_formats[] = {
366     GST_FORMAT_BYTES,
367     GST_FORMAT_DEFAULT,
368     GST_FORMAT_TIME,
369     0
370   };
371   static const GstFormat sink_formats[] = {
372     GST_FORMAT_BYTES,
373     GST_FORMAT_TIME,
374     0
375   };
376              
377   return (GST_PAD_IS_SRC (pad) ? src_formats : sink_formats);
378
379
380 static gboolean
381 gst_dvdec_src_convert (GstPad *pad, GstFormat src_format, gint64 src_value,
382                        GstFormat *dest_format, gint64 *dest_value)
383 {
384   gboolean res = TRUE;
385   GstDVDec *dvdec;
386   gint scale = 1;
387         
388   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
389
390   if (dvdec->length == 0)
391     return FALSE;
392
393   if (dvdec->decoder == NULL)
394     return FALSE;
395
396   switch (src_format) {
397     case GST_FORMAT_BYTES:
398       switch (*dest_format) {
399         case GST_FORMAT_TIME:
400         default:
401           res = FALSE;
402       }
403       break;
404     case GST_FORMAT_TIME:
405       switch (*dest_format) {
406         case GST_FORMAT_BYTES:
407           if (pad == dvdec->videosrcpad)
408             scale = 720 * dvdec->height * dvdec->bpp;
409           else if (pad == dvdec->audiosrcpad)
410             scale = dvdec->decoder->audio->num_channels * 2;
411           /* fallthrough */
412         case GST_FORMAT_DEFAULT:
413           if (pad == dvdec->videosrcpad)
414             *dest_value = src_value * dvdec->framerate * scale / (GST_SECOND*100);
415           else if (pad == dvdec->audiosrcpad)
416             *dest_value = src_value * dvdec->decoder->audio->frequency * scale / GST_SECOND;
417           break;
418         default:
419           res = FALSE;
420       }
421       break;
422     default:
423       res = FALSE;
424   }
425   return res;
426 }
427
428 static gboolean
429 gst_dvdec_sink_convert (GstPad *pad, GstFormat src_format, gint64 src_value,
430                         GstFormat *dest_format, gint64 *dest_value)
431 {
432   gboolean res = TRUE;
433   GstDVDec *dvdec;
434         
435   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
436
437   if (dvdec->length == 0)
438     return FALSE;
439
440   switch (src_format) {
441     case GST_FORMAT_BYTES:
442       switch (*dest_format) {
443         case GST_FORMAT_TIME:
444         {
445           guint64 frame;
446           /* get frame number */
447           frame = src_value / dvdec->length;
448
449           *dest_value = (frame * GST_SECOND * 100) / dvdec->framerate;
450           break;
451         }
452         default:
453           res = FALSE;
454       }
455       break;
456     case GST_FORMAT_TIME:
457       switch (*dest_format) {
458         case GST_FORMAT_BYTES:
459         {
460           guint64 frame;
461           /* calculate the frame */
462           frame = src_value * dvdec->framerate / (GST_SECOND*100);
463           /* calculate the offset */
464           *dest_value = frame * dvdec->length;
465           break;
466         }
467         default:
468           res = FALSE;
469       }
470       break;
471     default:
472       res = FALSE;
473   }
474   return res;
475 }
476
477 static const GstQueryType*
478 gst_dvdec_get_src_query_types (GstPad *pad)
479 {   
480   static const GstQueryType src_query_types[] = {
481     GST_QUERY_TOTAL,
482     GST_QUERY_POSITION,
483     0
484   };
485   return src_query_types;
486 }
487
488 static gboolean
489 gst_dvdec_src_query (GstPad *pad, GstQueryType type,
490                      GstFormat *format, gint64 *value)
491 {
492   gboolean res = TRUE;
493   GstDVDec *dvdec;
494
495   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
496
497   switch (type) {
498     case GST_QUERY_TOTAL:
499       switch (*format) {
500         default:
501         {
502           guint64 len;
503           GstFormat tmp_format;
504
505           len = gst_bytestream_length (dvdec->bs);
506           tmp_format = GST_FORMAT_TIME;
507           if (len == -1 || !gst_pad_convert (dvdec->sinkpad, 
508                                              GST_FORMAT_BYTES, 
509                                              len, 
510                                              &tmp_format, value)) 
511           {
512             return FALSE;
513           }
514           if (!gst_pad_convert (pad, GST_FORMAT_TIME, *value, format, value)) {
515             return FALSE;
516           }
517           break;
518         }
519       }
520       break;
521     case GST_QUERY_POSITION:
522       switch (*format) {
523         default:
524           res = gst_pad_convert (pad, GST_FORMAT_TIME, dvdec->next_ts, format, value);
525           break;
526       }
527       break;
528     default:
529       res = FALSE;
530       break;
531   }
532   return res;
533
534
535 static const GstEventMask*
536 gst_dvdec_get_event_masks (GstPad *pad)
537
538   static const GstEventMask src_event_masks[] = {
539     { GST_EVENT_SEEK, GST_SEEK_METHOD_SET |
540                       GST_SEEK_FLAG_FLUSH },
541     { 0, }
542   };
543   static const GstEventMask sink_event_masks[] = {
544     { GST_EVENT_EOS, 0 },
545     { GST_EVENT_DISCONTINUOUS, 0 },
546     { GST_EVENT_FLUSH, 0 },
547     { 0, }
548   };
549
550   return (GST_PAD_IS_SRC (pad) ? src_event_masks : sink_event_masks);
551
552
553 static gboolean
554 gst_dvdec_handle_sink_event (GstDVDec *dvdec)
555 {
556   guint32 remaining;
557   GstEvent *event;
558   GstEventType type;
559                 
560   gst_bytestream_get_status (dvdec->bs, &remaining, &event);
561                   
562   type = event? GST_EVENT_TYPE (event) : GST_EVENT_UNKNOWN;
563                       
564   switch (type) {
565     case GST_EVENT_EOS:
566       gst_pad_event_default (dvdec->sinkpad, event);
567       return TRUE;
568     case GST_EVENT_FLUSH:
569       break;
570     case GST_EVENT_DISCONTINUOUS:
571     {
572       gint i;
573       gboolean found = FALSE;
574       GstFormat format;
575
576       format = GST_FORMAT_TIME;
577       /* try to get a timestamp from the discont formats */
578       for (i = 0; i < GST_EVENT_DISCONT_OFFSET_LEN(event); i++) {
579         if (gst_pad_convert (dvdec->sinkpad, 
580                              GST_EVENT_DISCONT_OFFSET(event,i).format, 
581                              GST_EVENT_DISCONT_OFFSET(event,i).value,
582                              &format, &dvdec->next_ts)) 
583         {
584           found = TRUE;
585           break;
586         }
587       }
588       /* assume 0 then */
589       if (!found) {
590         dvdec->next_ts = 0LL;
591       }
592       dvdec->need_discont = TRUE;
593       break;
594     }
595     default:
596       g_warning ("unhandled event %d\n", type);
597       break;
598   }
599   gst_event_unref (event);
600   return TRUE;
601 }
602
603 static gboolean
604 gst_dvdec_handle_src_event (GstPad *pad, GstEvent *event)
605 {
606   gboolean res = TRUE;
607   GstDVDec *dvdec;
608
609   dvdec = GST_DVDEC (gst_pad_get_parent (pad));
610  
611   switch (GST_EVENT_TYPE (event)) {
612     case GST_EVENT_SEEK_SEGMENT:
613     {
614       gint64 position;
615       GstFormat format;
616
617       /* first bring the format to time */
618       format = GST_FORMAT_TIME;
619       if (!gst_pad_convert (pad, 
620                             GST_EVENT_SEEK_FORMAT (event), 
621                             GST_EVENT_SEEK_ENDOFFSET (event),
622                             &format, &position)) 
623       {
624         /* could not convert seek format to time offset */
625         res = FALSE;
626         break;
627       }
628
629       dvdec->end_position = position;
630       dvdec->loop = GST_EVENT_SEEK_TYPE (event) & GST_SEEK_FLAG_SEGMENT_LOOP;
631     }
632     case GST_EVENT_SEEK:
633     {
634       gint64 position;
635       GstFormat format;
636
637       /* first bring the format to time */
638       format = GST_FORMAT_TIME;
639       if (!gst_pad_convert (pad, 
640                             GST_EVENT_SEEK_FORMAT (event), 
641                             GST_EVENT_SEEK_OFFSET (event),
642                             &format, &position)) 
643       {
644         /* could not convert seek format to time offset */
645         res = FALSE;
646         break;
647       }
648       dvdec->next_ts = position;
649       /* then try to figure out the byteoffset for this time */
650       format = GST_FORMAT_BYTES;
651       if (!gst_pad_convert (dvdec->sinkpad, GST_FORMAT_TIME, position,
652                         &format, &position)) 
653       {
654         /* could not convert seek format to byte offset */
655         res = FALSE;
656         break;
657       }
658       /* seek to offset */
659       if (!gst_bytestream_seek (dvdec->bs, position, GST_SEEK_METHOD_SET)) {
660         res = FALSE;
661       }
662       if (GST_EVENT_TYPE (event) != GST_EVENT_SEEK_SEGMENT)
663         dvdec->end_position = -1;
664       break;
665     }
666     default:
667       res = FALSE;
668       break;
669   }
670   gst_event_unref (event);
671   return res;
672 }
673
674 static void
675 gst_dvdec_push (GstDVDec *dvdec, GstBuffer *outbuf, GstPad *pad, GstClockTime ts)
676 {   
677   GST_BUFFER_TIMESTAMP (outbuf) = ts;
678
679   if (dvdec->need_discont) {
680     GstEvent *discont;
681
682     discont = gst_event_new_discontinuous (FALSE, GST_FORMAT_TIME, ts, NULL);
683     gst_pad_push (pad, GST_BUFFER (discont));
684   }
685
686   gst_pad_push (pad, outbuf);
687
688   if ((dvdec->end_position != -1) &&
689       (dvdec->next_ts >= dvdec->end_position)) {
690     if (dvdec->loop) 
691       gst_pad_push (pad, GST_BUFFER(gst_event_new (GST_EVENT_SEGMENT_DONE)));
692     else
693       gst_pad_push (pad, GST_BUFFER(gst_event_new (GST_EVENT_EOS)));
694   }
695 }
696
697 static void
698 gst_dvdec_loop (GstElement *element)
699 {   
700   GstDVDec *dvdec;
701   GstBuffer *buf, *outbuf;
702   guint8 *inframe;
703   gint height;
704   guint32 length, got_bytes;
705   GstFormat format;
706   guint64 ts;
707   gfloat fps;
708
709   dvdec = GST_DVDEC (element);
710
711   /* first read enough bytes to parse the header */
712   got_bytes = gst_bytestream_peek_bytes (dvdec->bs, &inframe, header_size);
713   if (got_bytes < header_size) {
714     gst_dvdec_handle_sink_event (dvdec);
715     return;
716   }
717   dv_parse_header (dvdec->decoder, inframe);
718   /* after parsing the header we know the size of the data */
719   dvdec->PAL = dv_system_50_fields (dvdec->decoder);
720
721   dvdec->framerate = (dvdec->PAL ? 2500 : 2997);
722   fps = (dvdec->PAL ? 25. : 30/1.001);
723   dvdec->height = height = (dvdec->PAL ? PAL_HEIGHT : NTSC_HEIGHT);
724   length = (dvdec->PAL ? PAL_BUFFER : NTSC_BUFFER);
725
726   if (length != dvdec->length) {
727     dvdec->length = length;
728     gst_bytestream_size_hint (dvdec->bs, length);
729   }
730
731   /* then read the read data */
732   got_bytes = gst_bytestream_read (dvdec->bs, &buf, length);
733   if (got_bytes < length) {
734     gst_dvdec_handle_sink_event (dvdec);
735     return;
736   }
737
738   /* if we did not negotiate yet, do it now */
739   if (!GST_PAD_CAPS (dvdec->videosrcpad)) {
740     GstCaps *allowed;
741     GstCaps *trylist;
742     
743     /* we what we are allowed to do */
744     allowed = gst_pad_get_allowed_caps (dvdec->videosrcpad);
745
746     /* try to fix our height */
747     trylist = gst_caps_intersect (allowed, gst_caps_append (
748             GST_CAPS_NEW (
749               "dvdec_negotiate",
750               "video/x-raw-yuv",
751                 "height",       GST_PROPS_INT (height),
752                 "framerate",    GST_PROPS_FLOAT (fps)
753             ), GST_CAPS_NEW (
754               "dvdec_negotiate",
755               "video/x-raw-rgb",
756                 "height",       GST_PROPS_INT (height),
757                 "framerate",    GST_PROPS_FLOAT (fps)
758             )));
759     
760     /* prepare for looping */
761     trylist = gst_caps_normalize (trylist);
762
763     while (trylist) {
764       GstCaps *to_try = gst_caps_copy_1 (trylist);
765
766       /* try each format */
767       if (gst_pad_try_set_caps (dvdec->videosrcpad, to_try) > 0) {
768         guint32 fourcc;
769
770         /* it worked, try to find what it was again */
771         gst_caps_get_fourcc_int (to_try, "format", &fourcc);
772
773         if (fourcc == GST_STR_FOURCC ("RGB ")) {
774           gint bpp;
775
776           gst_caps_get_int (to_try, "bpp", &bpp);
777           if (bpp == 24) {
778             dvdec->space = e_dv_color_rgb;
779             dvdec->bpp = 3;
780           }
781           else {
782             dvdec->space = e_dv_color_bgr0;
783             dvdec->bpp = 4;
784           }
785         }
786         else {
787           dvdec->space = e_dv_color_yuv;
788           dvdec->bpp = 2;
789         }
790         break;
791       }
792       trylist = trylist->next;
793     }
794     /* oops list exhausted an nothing was found... */
795     if (!trylist) {
796       gst_element_error (element, "could not negotiate");
797       return;
798     }
799   }
800
801   format = GST_FORMAT_TIME;
802   gst_pad_query (dvdec->videosrcpad, GST_QUERY_POSITION, &format, &ts);
803
804   dvdec->next_ts += (GST_SECOND*100) / dvdec->framerate;
805
806   if (GST_PAD_IS_LINKED (dvdec->audiosrcpad)) {
807     gint16 *a_ptr;
808     gint i, j;
809
810     dv_decode_full_audio (dvdec->decoder, GST_BUFFER_DATA (buf), dvdec->audio_buffers);
811
812     /* if we did not negotiate yet, do it now */
813     if (!GST_PAD_CAPS (dvdec->audiosrcpad)) {
814       gst_pad_try_set_caps (dvdec->audiosrcpad,
815         GST_CAPS_NEW (
816           "dvdec_audio_caps",
817           "audio/x-raw-int",
818             "rate",             GST_PROPS_INT (dvdec->decoder->audio->frequency),
819             "depth",            GST_PROPS_INT (16),
820             "width",            GST_PROPS_INT (16),
821             "signed",           GST_PROPS_BOOLEAN (TRUE),
822             "channels",         GST_PROPS_INT (dvdec->decoder->audio->num_channels),
823             "endianness",       GST_PROPS_INT (G_LITTLE_ENDIAN)
824           ));
825     }
826
827     outbuf = gst_buffer_new ();
828     GST_BUFFER_SIZE (outbuf) = dvdec->decoder->audio->samples_this_frame * 
829                                sizeof (gint16) * dvdec->decoder->audio->num_channels;
830     GST_BUFFER_DATA (outbuf) = g_malloc (GST_BUFFER_SIZE (outbuf));
831
832     a_ptr = (gint16 *) GST_BUFFER_DATA (outbuf);
833
834     for (i = 0; i < dvdec->decoder->audio->samples_this_frame; i++) {
835       for (j = 0; j < dvdec->decoder->audio->num_channels; j++) {
836         *(a_ptr++) = dvdec->audio_buffers[j][i];
837       }
838     }
839     gst_dvdec_push (dvdec, outbuf, dvdec->audiosrcpad, ts);
840   }
841
842   if (GST_PAD_IS_LINKED (dvdec->videosrcpad)) {
843     guint8 *outframe;
844     guint8 *outframe_ptrs[3];
845     gint outframe_pitches[3];
846
847     /* try to grab a pool */
848     if (!dvdec->pool) {
849       dvdec->pool = gst_pad_get_bufferpool (dvdec->videosrcpad);
850     }
851
852     outbuf = NULL;
853     /* try to get a buffer from the pool if we have one */
854     if (dvdec->pool) {
855       outbuf = gst_buffer_new_from_pool (dvdec->pool, 0, 0);
856     }
857     /* no buffer from pool, allocate one ourselves */
858     if (!outbuf) {
859       outbuf = gst_buffer_new ();
860     
861       GST_BUFFER_SIZE (outbuf) = (720 * height) * dvdec->bpp;
862       GST_BUFFER_DATA (outbuf) = g_malloc (GST_BUFFER_SIZE (outbuf));
863     }
864     
865     outframe = GST_BUFFER_DATA (outbuf);
866
867     outframe_ptrs[0] = outframe;
868     outframe_pitches[0] = 720 * dvdec->bpp;
869
870     /* the rest only matters for YUY2 */
871     if (dvdec->bpp < 3) {
872       outframe_ptrs[1] = outframe_ptrs[0] + 720 * height;
873       outframe_ptrs[2] = outframe_ptrs[1] + 360 * height;
874   
875       outframe_pitches[1] = height / 2;
876       outframe_pitches[2] = outframe_pitches[1];
877     }
878
879     dv_decode_full_frame (dvdec->decoder, GST_BUFFER_DATA (buf), 
880                           dvdec->space, outframe_ptrs, outframe_pitches);
881
882     gst_dvdec_push (dvdec, outbuf, dvdec->videosrcpad, ts);
883   }
884
885   if ((dvdec->end_position != -1) && 
886       (dvdec->next_ts >= dvdec->end_position) && 
887       !dvdec->loop) {
888     gst_element_set_eos (GST_ELEMENT (dvdec));
889   }
890
891   if (dvdec->need_discont) {
892     dvdec->need_discont = FALSE;
893   }
894
895   gst_buffer_unref (buf);
896 }
897
898 static GstElementStateReturn
899 gst_dvdec_change_state (GstElement *element)
900 {
901   GstDVDec *dvdec = GST_DVDEC (element);
902             
903   switch (GST_STATE_TRANSITION (element)) {
904     case GST_STATE_NULL_TO_READY:
905       break;
906     case GST_STATE_READY_TO_PAUSED:
907       dvdec->bs = gst_bytestream_new (dvdec->sinkpad);
908       dvdec->decoder = dv_decoder_new (0, dvdec->clamp_luma, dvdec->clamp_chroma);
909       dvdec->decoder->quality = dvdec->quality;
910       break;
911     case GST_STATE_PAUSED_TO_PLAYING:
912       break;
913     case GST_STATE_PLAYING_TO_PAUSED:
914       if (dvdec->pool)
915         gst_buffer_pool_unref (dvdec->pool);
916       dvdec->pool = NULL;
917       break;
918     case GST_STATE_PAUSED_TO_READY:
919       dv_decoder_free (dvdec->decoder);
920       dvdec->decoder = NULL;
921       gst_bytestream_destroy (dvdec->bs);
922       break;
923     case GST_STATE_READY_TO_NULL:
924       break;
925     default:
926       break;
927   }
928               
929   parent_class->change_state (element);
930                 
931   return GST_STATE_SUCCESS;
932 }
933
934 /* Arguments are part of the Gtk+ object system, and these functions
935  * enable the element to respond to various arguments.
936  */
937 static void
938 gst_dvdec_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec)
939 {
940   GstDVDec *dvdec;
941
942   /* It's not null if we got it, but it might not be ours */
943   g_return_if_fail(GST_IS_DVDEC(object));
944
945   /* Get a pointer of the right type. */
946   dvdec = GST_DVDEC(object);
947
948   /* Check the argument id to see which argument we're setting. */
949   switch (prop_id) {
950     case ARG_CLAMP_LUMA:
951       dvdec->clamp_luma = g_value_get_boolean (value);
952       break;
953     case ARG_CLAMP_CHROMA:
954       dvdec->clamp_chroma = g_value_get_boolean (value);
955       break;
956     case ARG_QUALITY:
957       dvdec->quality = g_value_get_flags (value);
958       break;
959     default:
960       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
961       break;
962   }
963 }
964
965 /* The set function is simply the inverse of the get fuction. */
966 static void
967 gst_dvdec_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec)
968 {
969   GstDVDec *dvdec;
970
971   /* It's not null if we got it, but it might not be ours */
972   g_return_if_fail(GST_IS_DVDEC(object));
973   dvdec = GST_DVDEC(object);
974
975   switch (prop_id) {
976     case ARG_CLAMP_LUMA:
977       g_value_set_boolean (value, dvdec->clamp_luma);
978       break;
979     case ARG_CLAMP_CHROMA:
980       g_value_set_boolean (value, dvdec->clamp_chroma);
981       break;
982     case ARG_QUALITY:
983       g_value_set_flags (value, dvdec->quality);
984       break;
985     default:
986       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
987       break;
988   }
989 }
990
991 /* This is the entry into the plugin itself.  When the plugin loads,
992  * this function is called to register everything that the plugin provides.
993  */
994 static gboolean
995 plugin_init (GModule *module, GstPlugin *plugin)
996 {
997   GstElementFactory *factory;
998   GstTypeFactory *type;
999
1000   if (!gst_library_load ("gstbytestream"))
1001     return FALSE;
1002
1003   /* We need to create an ElementFactory for each element we provide.
1004    * This consists of the name of the element, the GType identifier,
1005    * and a pointer to the details structure at the top of the file.
1006    */
1007   factory = gst_element_factory_new("dvdec", GST_TYPE_DVDEC, &dvdec_details);
1008   g_return_val_if_fail(factory != NULL, FALSE);
1009
1010   gst_element_factory_set_rank (factory, GST_ELEMENT_RANK_PRIMARY);
1011   /* The pad templates can be easily generated from the factories above,
1012    * and then added to the list of padtemplates for the elementfactory.
1013    * Note that the generated padtemplates are stored in static global
1014    * variables, for the gst_dvdec_init function to use later on.
1015    */
1016   gst_element_factory_add_pad_template (factory, GST_PAD_TEMPLATE_GET(sink_temp));
1017   gst_element_factory_add_pad_template (factory, GST_PAD_TEMPLATE_GET(video_src_temp));
1018   gst_element_factory_add_pad_template (factory, GST_PAD_TEMPLATE_GET(audio_src_temp));
1019
1020   /* The very last thing is to register the elementfactory with the plugin. */
1021   gst_plugin_add_feature (plugin, GST_PLUGIN_FEATURE (factory));
1022
1023   type = gst_type_factory_new (&dv_definition);
1024   gst_plugin_add_feature (plugin, GST_PLUGIN_FEATURE (type));
1025
1026   return TRUE;
1027 }
1028
1029 GstPluginDesc plugin_desc = {
1030   GST_VERSION_MAJOR,
1031   GST_VERSION_MINOR,
1032   "dvdec",
1033   plugin_init
1034 };