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