update for bufferpool changes
[platform/upstream/gst-plugins-base.git] / ext / libvisual / visual.c
1 /* GStreamer
2  * Copyright (C) 2004 Benjamin Otte <otte@gnome.org>
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
24 #include <gst/gst.h>
25 #include <gst/base/gstadapter.h>
26 #include <gst/video/video.h>
27 #include <gst/video/gstvideopool.h>
28 #include <gst/audio/audio.h>
29 #include <libvisual/libvisual.h>
30
31 #define GST_TYPE_VISUAL (gst_visual_get_type())
32 #define GST_IS_VISUAL(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_VISUAL))
33 #define GST_VISUAL(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_VISUAL,GstVisual))
34 #define GST_IS_VISUAL_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_VISUAL))
35 #define GST_VISUAL_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_VISUAL,GstVisualClass))
36 #define GST_VISUAL_GET_CLASS(obj)   (G_TYPE_INSTANCE_GET_CLASS ((obj), GST_TYPE_VISUAL, GstVisualClass))
37
38 typedef struct _GstVisual GstVisual;
39 typedef struct _GstVisualClass GstVisualClass;
40
41 GST_DEBUG_CATEGORY_STATIC (libvisual_debug);
42 #define GST_CAT_DEFAULT (libvisual_debug)
43
44 /* amounf of samples before we can feed libvisual */
45 #define VISUAL_SAMPLES  512
46
47 #define DEFAULT_WIDTH   320
48 #define DEFAULT_HEIGHT  240
49 #define DEFAULT_FPS_N   25
50 #define DEFAULT_FPS_D   1
51
52 struct _GstVisual
53 {
54   GstElement element;
55
56   /* pads */
57   GstPad *sinkpad;
58   GstPad *srcpad;
59   GstSegment segment;
60
61   /* libvisual stuff */
62   VisAudio *audio;
63   VisVideo *video;
64   VisActor *actor;
65
66   /* audio/video state */
67   GstAudioInfo info;
68
69   /* framerate numerator & denominator */
70   gint fps_n;
71   gint fps_d;
72   gint width;
73   gint height;
74   GstClockTime duration;
75   guint outsize;
76   GstBufferPool *pool;
77
78   /* samples per frame based on caps */
79   guint spf;
80
81   /* state stuff */
82   GstAdapter *adapter;
83   guint count;
84
85   /* QoS stuff *//* with LOCK */
86   gdouble proportion;
87   GstClockTime earliest_time;
88 };
89
90 struct _GstVisualClass
91 {
92   GstElementClass parent_class;
93
94   VisPluginRef *plugin;
95 };
96
97 GType gst_visual_get_type (void);
98
99
100 static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src",
101     GST_PAD_SRC,
102     GST_PAD_ALWAYS,
103     GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE (" { "
104 #if G_BYTE_ORDER == G_BIG_ENDIAN
105             "\"xRGB\", " "\"RGB\", "
106 #else
107             "\"BGRx\", " "\"BGR\", "
108 #endif
109             "\"RGB16\" } "))
110     );
111
112 static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
113     GST_PAD_SINK,
114     GST_PAD_ALWAYS,
115     GST_STATIC_CAPS ("audio/x-raw, "
116         "format = (string) " GST_AUDIO_NE (S16) ", "
117         "layout = (string) interleaved, " "channels = (int) { 1, 2 }, "
118 #if defined(VISUAL_API_VERSION) && VISUAL_API_VERSION >= 4000 && VISUAL_API_VERSION < 5000
119         "rate = (int) { 8000, 11250, 22500, 32000, 44100, 48000, 96000 }"
120 #else
121         "rate = (int) [ 1000, MAX ]"
122 #endif
123     )
124     );
125
126
127 static void gst_visual_class_init (gpointer g_class, gpointer class_data);
128 static void gst_visual_init (GstVisual * visual);
129 static void gst_visual_finalize (GObject * object);
130
131 static GstStateChangeReturn gst_visual_change_state (GstElement * element,
132     GstStateChange transition);
133 static GstFlowReturn gst_visual_chain (GstPad * pad, GstObject * parent,
134     GstBuffer * buffer);
135 static gboolean gst_visual_sink_event (GstPad * pad, GstObject * parent,
136     GstEvent * event);
137 static gboolean gst_visual_src_event (GstPad * pad, GstObject * parent,
138     GstEvent * event);
139
140 static gboolean gst_visual_src_query (GstPad * pad, GstObject * parent,
141     GstQuery * query);
142
143 static gboolean gst_visual_sink_setcaps (GstPad * pad, GstCaps * caps);
144 static GstCaps *gst_visual_getcaps (GstPad * pad, GstCaps * filter);
145 static void libvisual_log_handler (const char *message, const char *funcname,
146     void *priv);
147
148 static GstElementClass *parent_class = NULL;
149
150 GType
151 gst_visual_get_type (void)
152 {
153   static GType type = 0;
154
155   if (G_UNLIKELY (type == 0)) {
156     static const GTypeInfo info = {
157       sizeof (GstVisualClass),
158       NULL,
159       NULL,
160       gst_visual_class_init,
161       NULL,
162       NULL,
163       sizeof (GstVisual),
164       0,
165       (GInstanceInitFunc) gst_visual_init,
166     };
167
168     type = g_type_register_static (GST_TYPE_ELEMENT, "GstVisual", &info, 0);
169   }
170   return type;
171 }
172
173 static void
174 libvisual_log_handler (const char *message, const char *funcname, void *priv)
175 {
176   GST_CAT_LEVEL_LOG (libvisual_debug, (GstDebugLevel) (priv), NULL, "%s - %s",
177       funcname, message);
178 }
179
180 static void
181 gst_visual_class_init (gpointer g_class, gpointer class_data)
182 {
183   GstVisualClass *klass = GST_VISUAL_CLASS (g_class);
184   GstElementClass *element = GST_ELEMENT_CLASS (g_class);
185   GObjectClass *object = G_OBJECT_CLASS (g_class);
186
187   klass->plugin = class_data;
188
189   element->change_state = gst_visual_change_state;
190
191   if (class_data == NULL) {
192     parent_class = g_type_class_peek_parent (g_class);
193   } else {
194     char *longname = g_strdup_printf ("libvisual %s plugin v.%s",
195         klass->plugin->info->name, klass->plugin->info->version);
196
197     /* FIXME: improve to only register what plugin supports? */
198     gst_element_class_add_pad_template (element,
199         gst_static_pad_template_get (&src_template));
200     gst_element_class_add_pad_template (element,
201         gst_static_pad_template_get (&sink_template));
202
203     gst_element_class_set_details_simple (element,
204         longname, "Visualization",
205         klass->plugin->info->about, "Benjamin Otte <otte@gnome.org>");
206
207     g_free (longname);
208   }
209
210   object->finalize = gst_visual_finalize;
211 }
212
213 static void
214 gst_visual_init (GstVisual * visual)
215 {
216   /* create the sink and src pads */
217   visual->sinkpad = gst_pad_new_from_static_template (&sink_template, "sink");
218   gst_pad_set_chain_function (visual->sinkpad, gst_visual_chain);
219   gst_pad_set_event_function (visual->sinkpad, gst_visual_sink_event);
220   gst_element_add_pad (GST_ELEMENT (visual), visual->sinkpad);
221
222   visual->srcpad = gst_pad_new_from_static_template (&src_template, "src");
223   gst_pad_set_event_function (visual->srcpad, gst_visual_src_event);
224   gst_pad_set_query_function (visual->srcpad, gst_visual_src_query);
225   gst_element_add_pad (GST_ELEMENT (visual), visual->srcpad);
226
227   visual->adapter = gst_adapter_new ();
228 }
229
230 static void
231 gst_visual_clear_actors (GstVisual * visual)
232 {
233   if (visual->actor) {
234     visual_object_unref (VISUAL_OBJECT (visual->actor));
235     visual->actor = NULL;
236   }
237   if (visual->video) {
238     visual_object_unref (VISUAL_OBJECT (visual->video));
239     visual->video = NULL;
240   }
241   if (visual->audio) {
242     visual_object_unref (VISUAL_OBJECT (visual->audio));
243     visual->audio = NULL;
244   }
245 }
246
247 static void
248 gst_visual_finalize (GObject * object)
249 {
250   GstVisual *visual = GST_VISUAL (object);
251
252   g_object_unref (visual->adapter);
253   if (visual->pool)
254     gst_object_unref (visual->pool);
255   gst_visual_clear_actors (visual);
256
257   GST_CALL_PARENT (G_OBJECT_CLASS, finalize, (object));
258 }
259
260 static void
261 gst_visual_reset (GstVisual * visual)
262 {
263   gst_adapter_clear (visual->adapter);
264   gst_segment_init (&visual->segment, GST_FORMAT_UNDEFINED);
265
266   GST_OBJECT_LOCK (visual);
267   visual->proportion = 1.0;
268   visual->earliest_time = -1;
269   GST_OBJECT_UNLOCK (visual);
270 }
271
272 static GstCaps *
273 gst_visual_getcaps (GstPad * pad, GstCaps * filter)
274 {
275   GstCaps *ret;
276   GstVisual *visual = GST_VISUAL (GST_PAD_PARENT (pad));
277   int depths;
278
279   if (!visual->actor) {
280     ret = gst_pad_get_pad_template_caps (visual->srcpad);
281     goto beach;
282   }
283
284   ret = gst_caps_new_empty ();
285   depths = visual_actor_get_supported_depth (visual->actor);
286   if (depths < 0) {
287     /* FIXME: set an error */
288     goto beach;
289   }
290   if (depths == VISUAL_VIDEO_DEPTH_GL) {
291     /* We can't handle GL only plugins */
292     goto beach;
293   }
294
295   GST_DEBUG_OBJECT (visual, "libvisual plugin supports depths %u (0x%04x)",
296       depths, depths);
297   /* if (depths & VISUAL_VIDEO_DEPTH_32BIT) Always supports 32bit output */
298 #if G_BYTE_ORDER == G_BIG_ENDIAN
299   gst_caps_append (ret, gst_caps_from_string (GST_VIDEO_CAPS_MAKE ("xRGB")));
300 #else
301   gst_caps_append (ret, gst_caps_from_string (GST_VIDEO_CAPS_MAKE ("BGRx")));
302 #endif
303
304   if (depths & VISUAL_VIDEO_DEPTH_24BIT) {
305 #if G_BYTE_ORDER == G_BIG_ENDIAN
306     gst_caps_append (ret, gst_caps_from_string (GST_VIDEO_CAPS_MAKE ("RGB")));
307 #else
308     gst_caps_append (ret, gst_caps_from_string (GST_VIDEO_CAPS_MAKE ("BGR")));
309 #endif
310   }
311   if (depths & VISUAL_VIDEO_DEPTH_16BIT) {
312     gst_caps_append (ret, gst_caps_from_string (GST_VIDEO_CAPS_MAKE ("RGB16")));
313   }
314
315 beach:
316
317   if (filter) {
318     GstCaps *intersection;
319
320     intersection =
321         gst_caps_intersect_full (filter, ret, GST_CAPS_INTERSECT_FIRST);
322     gst_caps_unref (ret);
323     ret = intersection;
324   }
325
326   GST_DEBUG_OBJECT (visual, "returning caps %" GST_PTR_FORMAT, ret);
327
328   return ret;
329 }
330
331 static gboolean
332 gst_visual_src_setcaps (GstVisual * visual, GstCaps * caps)
333 {
334   gboolean res;
335   GstStructure *structure;
336   gint depth, pitch, rate;
337   const gchar *fmt;
338
339   structure = gst_caps_get_structure (caps, 0);
340
341   GST_DEBUG_OBJECT (visual, "src pad got caps %" GST_PTR_FORMAT, caps);
342
343   if (!gst_structure_get_int (structure, "width", &visual->width))
344     goto error;
345   if (!gst_structure_get_int (structure, "height", &visual->height))
346     goto error;
347   if (!(fmt = gst_structure_get_string (structure, "format")))
348     goto error;
349   if (!gst_structure_get_fraction (structure, "framerate", &visual->fps_n,
350           &visual->fps_d))
351     goto error;
352
353   if (!strcmp (fmt, "BGR") || !strcmp (fmt, "RGB"))
354     depth = 24;
355   else if (!strcmp (fmt, "BGRx") || !strcmp (fmt, "xRGB"))
356     depth = 32;
357   else
358     depth = 16;
359
360   visual_video_set_depth (visual->video,
361       visual_video_depth_enum_from_value (depth));
362   visual_video_set_dimension (visual->video, visual->width, visual->height);
363   pitch = GST_ROUND_UP_4 (visual->width * visual->video->bpp);
364   visual_video_set_pitch (visual->video, pitch);
365   visual_actor_video_negotiate (visual->actor, 0, FALSE, FALSE);
366
367   rate = GST_AUDIO_INFO_RATE (&visual->info);
368
369   /* precalc some values */
370   visual->outsize = visual->video->height * pitch;
371   visual->spf = gst_util_uint64_scale_int (rate, visual->fps_d, visual->fps_n);
372   visual->duration =
373       gst_util_uint64_scale_int (GST_SECOND, visual->fps_d, visual->fps_n);
374
375   res = gst_pad_push_event (visual->srcpad, gst_event_new_caps (caps));
376
377   return res;
378
379   /* ERRORS */
380 error:
381   {
382     GST_DEBUG_OBJECT (visual, "error parsing caps");
383     return FALSE;
384   }
385 }
386
387 static gboolean
388 gst_visual_sink_setcaps (GstPad * pad, GstCaps * caps)
389 {
390   GstVisual *visual = GST_VISUAL (GST_PAD_PARENT (pad));
391   GstAudioInfo info;
392   gint rate;
393
394   if (!gst_audio_info_from_caps (&info, caps))
395     goto invalid_caps;
396
397   visual->info = info;
398
399   rate = GST_AUDIO_INFO_RATE (&info);
400
401   /* this is how many samples we need to fill one frame at the requested
402    * framerate. */
403   if (visual->fps_n != 0) {
404     visual->spf =
405         gst_util_uint64_scale_int (rate, visual->fps_d, visual->fps_n);
406   }
407
408   return TRUE;
409
410   /* ERRORS */
411 invalid_caps:
412   {
413     GST_ERROR_OBJECT (visual, "invalid caps received");
414     return FALSE;
415   }
416 }
417
418 static gboolean
419 gst_vis_src_negotiate (GstVisual * visual)
420 {
421   GstCaps *othercaps, *target;
422   GstStructure *structure;
423   GstCaps *caps;
424   GstQuery *query;
425   GstBufferPool *pool = NULL;
426   GstStructure *config;
427   guint size, min, max;
428
429   caps = gst_pad_query_caps (visual->srcpad, NULL);
430
431   /* see what the peer can do */
432   othercaps = gst_pad_peer_query_caps (visual->srcpad, caps);
433   if (othercaps) {
434     target = othercaps;
435     gst_caps_unref (caps);
436
437     if (gst_caps_is_empty (target))
438       goto no_format;
439
440     target = gst_caps_truncate (target);
441   } else {
442     /* need a copy, we'll be modifying it when fixating */
443     target = gst_caps_ref (caps);
444   }
445   GST_DEBUG_OBJECT (visual, "before fixate caps %" GST_PTR_FORMAT, target);
446
447   target = gst_caps_make_writable (target);
448   /* fixate in case something is not fixed. This does nothing if the value is
449    * already fixed. For video we always try to fixate to something like
450    * 320x240x25 by convention. */
451   structure = gst_caps_get_structure (target, 0);
452   gst_structure_fixate_field_nearest_int (structure, "width", DEFAULT_WIDTH);
453   gst_structure_fixate_field_nearest_int (structure, "height", DEFAULT_HEIGHT);
454   gst_structure_fixate_field_nearest_fraction (structure, "framerate",
455       DEFAULT_FPS_N, DEFAULT_FPS_D);
456   target = gst_caps_fixate (target);
457
458   GST_DEBUG_OBJECT (visual, "after fixate caps %" GST_PTR_FORMAT, target);
459
460   gst_visual_src_setcaps (visual, target);
461
462   /* try to get a bufferpool now */
463   /* find a pool for the negotiated caps now */
464   query = gst_query_new_allocation (target, TRUE);
465
466   if (!gst_pad_peer_query (visual->srcpad, query)) {
467     /* not a problem, we deal with the defaults of the query */
468     GST_DEBUG_OBJECT (visual, "allocation query failed");
469   }
470
471   if (gst_query_get_n_allocation_pools (query) > 0) {
472     gst_query_parse_nth_allocation_pool (query, 0, &pool, &size, &min, &max);
473
474     size = MAX (size, visual->outsize);
475   } else {
476     pool = NULL;
477     size = visual->outsize;
478     min = max = 0;
479   }
480
481   if (pool == NULL) {
482     /* no pool, just parameters, we can make our own */
483     GST_DEBUG_OBJECT (visual, "no pool, making new pool");
484     pool = gst_video_buffer_pool_new ();
485   }
486
487   /* and configure */
488   config = gst_buffer_pool_get_config (pool);
489   gst_buffer_pool_config_set_params (config, target, size, min, max);
490   gst_buffer_pool_set_config (pool, config);
491
492   if (visual->pool)
493     gst_object_unref (visual->pool);
494   visual->pool = pool;
495
496   /* and activate */
497   gst_buffer_pool_set_active (pool, TRUE);
498
499   gst_caps_unref (target);
500
501   return TRUE;
502
503   /* ERRORS */
504 no_format:
505   {
506     GST_ELEMENT_ERROR (visual, STREAM, FORMAT, (NULL),
507         ("could not negotiate output format"));
508     gst_caps_unref (target);
509     return FALSE;
510   }
511 }
512
513 static gboolean
514 gst_visual_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
515 {
516   GstVisual *visual;
517   gboolean res;
518
519   visual = GST_VISUAL (parent);
520
521   switch (GST_EVENT_TYPE (event)) {
522     case GST_EVENT_FLUSH_START:
523       res = gst_pad_push_event (visual->srcpad, event);
524       break;
525     case GST_EVENT_FLUSH_STOP:
526       /* reset QoS and adapter. */
527       gst_visual_reset (visual);
528       res = gst_pad_push_event (visual->srcpad, event);
529       break;
530     case GST_EVENT_CAPS:
531     {
532       GstCaps *caps;
533
534       gst_event_parse_caps (event, &caps);
535       res = gst_visual_sink_setcaps (pad, caps);
536       gst_event_unref (event);
537       break;
538     }
539     case GST_EVENT_SEGMENT:
540     {
541       /* the newsegment values are used to clip the input samples
542        * and to convert the incomming timestamps to running time so
543        * we can do QoS */
544       gst_event_copy_segment (event, &visual->segment);
545
546       /* and forward */
547       res = gst_pad_push_event (visual->srcpad, event);
548       break;
549     }
550     default:
551       res = gst_pad_event_default (pad, parent, event);
552       break;
553   }
554
555   return res;
556 }
557
558 static gboolean
559 gst_visual_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
560 {
561   GstVisual *visual;
562   gboolean res;
563
564   visual = GST_VISUAL (parent);
565
566   switch (GST_EVENT_TYPE (event)) {
567     case GST_EVENT_QOS:
568     {
569       gdouble proportion;
570       GstClockTimeDiff diff;
571       GstClockTime timestamp;
572
573       gst_event_parse_qos (event, NULL, &proportion, &diff, &timestamp);
574
575       /* save stuff for the _chain function */
576       GST_OBJECT_LOCK (visual);
577       visual->proportion = proportion;
578       if (diff >= 0)
579         /* we're late, this is a good estimate for next displayable
580          * frame (see part-qos.txt) */
581         visual->earliest_time = timestamp + 2 * diff + visual->duration;
582       else
583         visual->earliest_time = timestamp + diff;
584
585       GST_OBJECT_UNLOCK (visual);
586
587       res = gst_pad_push_event (visual->sinkpad, event);
588       break;
589     }
590     case GST_EVENT_RECONFIGURE:
591       /* dont't forward */
592       gst_event_unref (event);
593       res = TRUE;
594       break;
595     default:
596       res = gst_pad_event_default (pad, parent, event);
597       break;
598   }
599
600   return res;
601 }
602
603 static gboolean
604 gst_visual_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
605 {
606   gboolean res;
607   GstVisual *visual;
608
609   visual = GST_VISUAL (parent);
610
611   switch (GST_QUERY_TYPE (query)) {
612     case GST_QUERY_LATENCY:
613     {
614       /* We need to send the query upstream and add the returned latency to our
615        * own */
616       GstClockTime min_latency, max_latency;
617       gboolean us_live;
618       GstClockTime our_latency;
619       guint max_samples;
620
621       if ((res = gst_pad_peer_query (visual->sinkpad, query))) {
622         gst_query_parse_latency (query, &us_live, &min_latency, &max_latency);
623
624         GST_DEBUG_OBJECT (visual, "Peer latency: min %"
625             GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
626             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
627
628         /* the max samples we must buffer */
629         max_samples = MAX (VISUAL_SAMPLES, visual->spf);
630         our_latency =
631             gst_util_uint64_scale_int (max_samples, GST_SECOND,
632             GST_AUDIO_INFO_RATE (&visual->info));
633
634         GST_DEBUG_OBJECT (visual, "Our latency: %" GST_TIME_FORMAT,
635             GST_TIME_ARGS (our_latency));
636
637         /* we add some latency but only if we need to buffer more than what
638          * upstream gives us */
639         min_latency += our_latency;
640         if (max_latency != -1)
641           max_latency += our_latency;
642
643         GST_DEBUG_OBJECT (visual, "Calculated total latency : min %"
644             GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
645             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
646
647         gst_query_set_latency (query, TRUE, min_latency, max_latency);
648       }
649       break;
650     }
651     case GST_QUERY_CAPS:
652     {
653       GstCaps *filter, *caps;
654
655       gst_query_parse_caps (query, &filter);
656       caps = gst_visual_getcaps (pad, filter);
657       gst_query_set_caps_result (query, caps);
658       gst_caps_unref (caps);
659       res = TRUE;
660     }
661     default:
662       res = gst_pad_query_default (pad, parent, query);
663       break;
664   }
665
666   return res;
667 }
668
669 /* Make sure we are negotiated */
670 static GstFlowReturn
671 ensure_negotiated (GstVisual * visual)
672 {
673   gboolean reconfigure;
674
675   reconfigure = gst_pad_check_reconfigure (visual->srcpad);
676
677   /* we don't know an output format yet, pick one */
678   if (reconfigure || !gst_pad_has_current_caps (visual->srcpad)) {
679     if (!gst_vis_src_negotiate (visual))
680       return GST_FLOW_NOT_NEGOTIATED;
681   }
682   return GST_FLOW_OK;
683 }
684
685 static GstFlowReturn
686 gst_visual_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
687 {
688   GstBuffer *outbuf = NULL;
689   guint i;
690   GstVisual *visual = GST_VISUAL (parent);
691   GstFlowReturn ret = GST_FLOW_OK;
692   guint avail;
693   gint bpf, rate, channels;
694
695   GST_DEBUG_OBJECT (visual, "chain function called");
696
697   /* Make sure have an output format */
698   ret = ensure_negotiated (visual);
699   if (ret != GST_FLOW_OK) {
700     gst_buffer_unref (buffer);
701     goto beach;
702   }
703
704   /* resync on DISCONT */
705   if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT)) {
706     gst_adapter_clear (visual->adapter);
707   }
708
709   rate = GST_AUDIO_INFO_RATE (&visual->info);
710   bpf = GST_AUDIO_INFO_BPF (&visual->info);
711   channels = GST_AUDIO_INFO_CHANNELS (&visual->info);
712
713   GST_DEBUG_OBJECT (visual,
714       "Input buffer has %" G_GSIZE_FORMAT " samples, time=%" G_GUINT64_FORMAT,
715       gst_buffer_get_size (buffer) / bpf, GST_BUFFER_TIMESTAMP (buffer));
716
717   gst_adapter_push (visual->adapter, buffer);
718
719   while (TRUE) {
720     gboolean need_skip;
721     const guint16 *data;
722     guint64 dist, timestamp;
723     GstMapInfo outmap;
724
725     GST_DEBUG_OBJECT (visual, "processing buffer");
726
727     avail = gst_adapter_available (visual->adapter);
728     GST_DEBUG_OBJECT (visual, "avail now %u", avail);
729
730     /* we need at least VISUAL_SAMPLES samples */
731     if (avail < VISUAL_SAMPLES * bpf)
732       break;
733
734     /* we need at least enough samples to make one frame */
735     if (avail < visual->spf * bpf)
736       break;
737
738     /* get timestamp of the current adapter byte */
739     timestamp = gst_adapter_prev_timestamp (visual->adapter, &dist);
740     if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
741       /* convert bytes to time */
742       dist /= bpf;
743       timestamp += gst_util_uint64_scale_int (dist, GST_SECOND, rate);
744     }
745
746     if (timestamp != -1) {
747       gint64 qostime;
748
749       /* QoS is done on running time */
750       qostime = gst_segment_to_running_time (&visual->segment, GST_FORMAT_TIME,
751           timestamp);
752       qostime += visual->duration;
753
754       GST_OBJECT_LOCK (visual);
755       /* check for QoS, don't compute buffers that are known to be late */
756       need_skip = visual->earliest_time != -1 &&
757           qostime <= visual->earliest_time;
758       GST_OBJECT_UNLOCK (visual);
759
760       if (need_skip) {
761         GST_WARNING_OBJECT (visual,
762             "QoS: skip ts: %" GST_TIME_FORMAT ", earliest: %" GST_TIME_FORMAT,
763             GST_TIME_ARGS (qostime), GST_TIME_ARGS (visual->earliest_time));
764         goto skip;
765       }
766     }
767
768     /* Read VISUAL_SAMPLES samples per channel */
769     data =
770         (const guint16 *) gst_adapter_map (visual->adapter,
771         VISUAL_SAMPLES * bpf);
772
773 #if defined(VISUAL_API_VERSION) && VISUAL_API_VERSION >= 4000 && VISUAL_API_VERSION < 5000
774     {
775       VisBuffer *lbuf, *rbuf;
776       guint16 ldata[VISUAL_SAMPLES], rdata[VISUAL_SAMPLES];
777       VisAudioSampleRateType vrate;
778
779       lbuf = visual_buffer_new_with_buffer (ldata, sizeof (ldata), NULL);
780       rbuf = visual_buffer_new_with_buffer (rdata, sizeof (rdata), NULL);
781
782       if (channels == 2) {
783         for (i = 0; i < VISUAL_SAMPLES; i++) {
784           ldata[i] = *data++;
785           rdata[i] = *data++;
786         }
787       } else {
788         for (i = 0; i < VISUAL_SAMPLES; i++) {
789           ldata[i] = *data;
790           rdata[i] = *data++;
791         }
792       }
793
794       switch (rate) {
795         case 8000:
796           vrate = VISUAL_AUDIO_SAMPLE_RATE_8000;
797           break;
798         case 11250:
799           vrate = VISUAL_AUDIO_SAMPLE_RATE_11250;
800           break;
801         case 22500:
802           vrate = VISUAL_AUDIO_SAMPLE_RATE_22500;
803           break;
804         case 32000:
805           vrate = VISUAL_AUDIO_SAMPLE_RATE_32000;
806           break;
807         case 44100:
808           vrate = VISUAL_AUDIO_SAMPLE_RATE_44100;
809           break;
810         case 48000:
811           vrate = VISUAL_AUDIO_SAMPLE_RATE_48000;
812           break;
813         case 96000:
814           vrate = VISUAL_AUDIO_SAMPLE_RATE_96000;
815           break;
816         default:
817           visual_object_unref (VISUAL_OBJECT (lbuf));
818           visual_object_unref (VISUAL_OBJECT (rbuf));
819           GST_ERROR_OBJECT (visual, "unsupported rate %d", rate);
820           ret = GST_FLOW_ERROR;
821           goto beach;
822           break;
823       }
824
825       visual_audio_samplepool_input_channel (visual->audio->samplepool,
826           lbuf,
827           vrate, VISUAL_AUDIO_SAMPLE_FORMAT_S16,
828           (char *) VISUAL_AUDIO_CHANNEL_LEFT);
829       visual_audio_samplepool_input_channel (visual->audio->samplepool, rbuf,
830           vrate, VISUAL_AUDIO_SAMPLE_FORMAT_S16,
831           (char *) VISUAL_AUDIO_CHANNEL_RIGHT);
832
833       visual_object_unref (VISUAL_OBJECT (lbuf));
834       visual_object_unref (VISUAL_OBJECT (rbuf));
835
836     }
837 #else
838     if (visual->channels == 2) {
839       for (i = 0; i < VISUAL_SAMPLES; i++) {
840         visual->audio->plugpcm[0][i] = *data++;
841         visual->audio->plugpcm[1][i] = *data++;
842       }
843     } else {
844       for (i = 0; i < VISUAL_SAMPLES; i++) {
845         visual->audio->plugpcm[0][i] = *data;
846         visual->audio->plugpcm[1][i] = *data++;
847       }
848     }
849 #endif
850
851     /* alloc a buffer if we don't have one yet, this happens
852      * when we pushed a buffer in this while loop before */
853     if (outbuf == NULL) {
854       GST_DEBUG_OBJECT (visual, "allocating output buffer");
855       ret = gst_buffer_pool_acquire_buffer (visual->pool, &outbuf, NULL);
856       if (ret != GST_FLOW_OK) {
857         gst_adapter_unmap (visual->adapter);
858         goto beach;
859       }
860     }
861     gst_buffer_map (outbuf, &outmap, GST_MAP_WRITE);
862     visual_video_set_buffer (visual->video, outmap.data);
863     visual_audio_analyze (visual->audio);
864     visual_actor_run (visual->actor, visual->audio);
865     visual_video_set_buffer (visual->video, NULL);
866     gst_buffer_unmap (outbuf, &outmap);
867     GST_DEBUG_OBJECT (visual, "rendered one frame");
868
869     gst_adapter_unmap (visual->adapter);
870
871     GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
872     GST_BUFFER_DURATION (outbuf) = visual->duration;
873
874     ret = gst_pad_push (visual->srcpad, outbuf);
875     outbuf = NULL;
876
877   skip:
878     GST_DEBUG_OBJECT (visual, "finished frame, flushing %u samples from input",
879         visual->spf);
880
881     /* Flush out the number of samples per frame */
882     gst_adapter_flush (visual->adapter, visual->spf * bpf);
883
884     /* quit the loop if something was wrong */
885     if (ret != GST_FLOW_OK)
886       break;
887   }
888
889 beach:
890
891   if (outbuf != NULL)
892     gst_buffer_unref (outbuf);
893
894   return ret;
895 }
896
897 static GstStateChangeReturn
898 gst_visual_change_state (GstElement * element, GstStateChange transition)
899 {
900   GstVisual *visual = GST_VISUAL (element);
901   GstStateChangeReturn ret;
902
903   switch (transition) {
904     case GST_STATE_CHANGE_NULL_TO_READY:
905       visual->actor =
906           visual_actor_new (GST_VISUAL_GET_CLASS (visual)->plugin->
907           info->plugname);
908       visual->video = visual_video_new ();
909       visual->audio = visual_audio_new ();
910       /* can't have a play without actors */
911       if (!visual->actor || !visual->video)
912         goto no_actors;
913
914       if (visual_actor_realize (visual->actor) != 0)
915         goto no_realize;
916
917       visual_actor_set_video (visual->actor, visual->video);
918       break;
919     case GST_STATE_CHANGE_READY_TO_PAUSED:
920       gst_visual_reset (visual);
921       break;
922     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
923       break;
924     default:
925       break;
926   }
927
928   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
929
930   switch (transition) {
931     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
932       break;
933     case GST_STATE_CHANGE_PAUSED_TO_READY:
934       if (visual->pool) {
935         gst_buffer_pool_set_active (visual->pool, FALSE);
936         gst_object_unref (visual->pool);
937         visual->pool = NULL;
938       }
939       break;
940     case GST_STATE_CHANGE_READY_TO_NULL:
941       gst_visual_clear_actors (visual);
942       break;
943     default:
944       break;
945   }
946
947   return ret;
948
949   /* ERRORS */
950 no_actors:
951   {
952     GST_ELEMENT_ERROR (visual, LIBRARY, INIT, (NULL),
953         ("could not create actors"));
954     gst_visual_clear_actors (visual);
955     return GST_STATE_CHANGE_FAILURE;
956   }
957 no_realize:
958   {
959     GST_ELEMENT_ERROR (visual, LIBRARY, INIT, (NULL),
960         ("could not realize actor"));
961     gst_visual_clear_actors (visual);
962     return GST_STATE_CHANGE_FAILURE;
963   }
964 }
965
966 static void
967 make_valid_name (char *name)
968 {
969   /*
970    * Replace invalid chars with _ in the type name
971    */
972   static const gchar extra_chars[] = "-_+";
973   gchar *p = name;
974
975   for (; *p; p++) {
976     int valid = ((p[0] >= 'A' && p[0] <= 'Z') ||
977         (p[0] >= 'a' && p[0] <= 'z') ||
978         (p[0] >= '0' && p[0] <= '9') || strchr (extra_chars, p[0]));
979     if (!valid)
980       *p = '_';
981   }
982 }
983
984 static gboolean
985 gst_visual_actor_plugin_is_gl (VisObject * plugin, const gchar * name)
986 {
987   gboolean is_gl;
988   gint depth;
989
990 #if !defined(VISUAL_API_VERSION)
991
992   depth = VISUAL_PLUGIN_ACTOR (plugin)->depth;
993   is_gl = (depth == VISUAL_VIDEO_DEPTH_GL);
994
995 #elif VISUAL_API_VERSION >= 4000 && VISUAL_API_VERSION < 5000
996
997   depth = VISUAL_ACTOR_PLUGIN (plugin)->vidoptions.depth;
998   /* FIXME: how to figure this out correctly in 0.4? */
999   is_gl = (depth & VISUAL_VIDEO_DEPTH_GL) == VISUAL_VIDEO_DEPTH_GL;
1000
1001 #else
1002 # error what libvisual version is this?
1003 #endif
1004
1005   if (!is_gl) {
1006     GST_DEBUG ("plugin %s is not a GL plugin (%d), registering", name, depth);
1007   } else {
1008     GST_DEBUG ("plugin %s is a GL plugin (%d), ignoring", name, depth);
1009   }
1010
1011   return is_gl;
1012 }
1013
1014 static gboolean
1015 plugin_init (GstPlugin * plugin)
1016 {
1017   guint i, count;
1018   VisList *list;
1019
1020   GST_DEBUG_CATEGORY_INIT (libvisual_debug, "libvisual", 0,
1021       "libvisual audio visualisations");
1022
1023 #ifdef LIBVISUAL_PLUGINSBASEDIR
1024   gst_plugin_add_dependency_simple (plugin, "HOME/.libvisual/actor",
1025       LIBVISUAL_PLUGINSBASEDIR "/actor", NULL, GST_PLUGIN_DEPENDENCY_FLAG_NONE);
1026 #endif
1027
1028   visual_log_set_verboseness (VISUAL_LOG_VERBOSENESS_LOW);
1029   visual_log_set_info_handler (libvisual_log_handler, (void *) GST_LEVEL_INFO);
1030   visual_log_set_warning_handler (libvisual_log_handler,
1031       (void *) GST_LEVEL_WARNING);
1032   visual_log_set_critical_handler (libvisual_log_handler,
1033       (void *) GST_LEVEL_ERROR);
1034   visual_log_set_error_handler (libvisual_log_handler,
1035       (void *) GST_LEVEL_ERROR);
1036
1037   if (!visual_is_initialized ())
1038     if (visual_init (NULL, NULL) != 0)
1039       return FALSE;
1040
1041   list = visual_actor_get_list ();
1042
1043 #if !defined(VISUAL_API_VERSION)
1044   count = visual_list_count (list);
1045 #elif VISUAL_API_VERSION >= 4000 && VISUAL_API_VERSION < 5000
1046   count = visual_collection_size (VISUAL_COLLECTION (list));
1047 #endif
1048
1049   for (i = 0; i < count; i++) {
1050     VisPluginRef *ref = visual_list_get (list, i);
1051     VisPluginData *visplugin = NULL;
1052     gboolean skip = FALSE;
1053     GType type;
1054     gchar *name;
1055     GTypeInfo info = {
1056       sizeof (GstVisualClass),
1057       NULL,
1058       NULL,
1059       gst_visual_class_init,
1060       NULL,
1061       ref,
1062       sizeof (GstVisual),
1063       0,
1064       NULL
1065     };
1066
1067     visplugin = visual_plugin_load (ref);
1068
1069     if (ref->info->plugname == NULL)
1070       continue;
1071
1072     /* Blacklist some plugins */
1073     if (strcmp (ref->info->plugname, "gstreamer") == 0 ||
1074         strcmp (ref->info->plugname, "gdkpixbuf") == 0) {
1075       skip = TRUE;
1076     } else {
1077       /* Ignore plugins that only support GL output for now */
1078       skip = gst_visual_actor_plugin_is_gl (visplugin->info->plugin,
1079           visplugin->info->plugname);
1080     }
1081
1082     visual_plugin_unload (visplugin);
1083
1084     if (!skip) {
1085       name = g_strdup_printf ("GstVisual%s", ref->info->plugname);
1086       make_valid_name (name);
1087       type = g_type_register_static (GST_TYPE_VISUAL, name, &info, 0);
1088       g_free (name);
1089
1090       name = g_strdup_printf ("libvisual_%s", ref->info->plugname);
1091       make_valid_name (name);
1092       if (!gst_element_register (plugin, name, GST_RANK_NONE, type)) {
1093         g_free (name);
1094         return FALSE;
1095       }
1096       g_free (name);
1097     }
1098   }
1099
1100   return TRUE;
1101 }
1102
1103 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1104     GST_VERSION_MINOR,
1105     "libvisual",
1106     "libvisual visualization plugins",
1107     plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)