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