use G_DEFINE_TYPE
[platform/upstream/gstreamer.git] / ext / pulse / pulsesink.c
1 /*-*- Mode: C; c-basic-offset: 2 -*-*/
2
3 /*  GStreamer pulseaudio plugin
4  *
5  *  Copyright (c) 2004-2008 Lennart Poettering
6  *            (c) 2009      Wim Taymans
7  *
8  *  gst-pulse is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU Lesser General Public License as
10  *  published by the Free Software Foundation; either version 2.1 of the
11  *  License, or (at your option) any later version.
12  *
13  *  gst-pulse is distributed in the hope that it will be useful, but
14  *  WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  *  Lesser General Public License for more details.
17  *
18  *  You should have received a copy of the GNU Lesser General Public
19  *  License along with gst-pulse; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
21  *  USA.
22  */
23
24 /**
25  * SECTION:element-pulsesink
26  * @see_also: pulsesrc, pulsemixer
27  *
28  * This element outputs audio to a
29  * <ulink href="http://www.pulseaudio.org">PulseAudio sound server</ulink>.
30  *
31  * <refsect2>
32  * <title>Example pipelines</title>
33  * |[
34  * gst-launch -v filesrc location=sine.ogg ! oggdemux ! vorbisdec ! audioconvert ! audioresample ! pulsesink
35  * ]| Play an Ogg/Vorbis file.
36  * |[
37  * gst-launch -v audiotestsrc ! audioconvert ! volume volume=0.4 ! pulsesink
38  * ]| Play a 440Hz sine wave.
39  * |[
40  * gst-launch -v audiotestsrc ! pulsesink stream-properties="props,media.title=test"
41  * ]| Play a sine wave and set a stream property. The property can be checked
42  * with "pactl list".
43  * </refsect2>
44  */
45
46 #ifdef HAVE_CONFIG_H
47 #include "config.h"
48 #endif
49
50 #include <string.h>
51 #include <stdio.h>
52
53 #include <gst/base/gstbasesink.h>
54 #include <gst/gsttaglist.h>
55 #include <gst/interfaces/streamvolume.h>
56 #include <gst/gst-i18n-plugin.h>
57
58 #include <gst/pbutils/pbutils.h>        /* only used for GST_PLUGINS_BASE_VERSION_* */
59
60 #include "pulsesink.h"
61 #include "pulseutil.h"
62
63 GST_DEBUG_CATEGORY_EXTERN (pulse_debug);
64 #define GST_CAT_DEFAULT pulse_debug
65
66 /* according to
67  * http://www.pulseaudio.org/ticket/314
68  * we need pulse-0.9.12 to use sink volume properties
69  */
70
71 #define DEFAULT_SERVER          NULL
72 #define DEFAULT_DEVICE          NULL
73 #define DEFAULT_DEVICE_NAME     NULL
74 #define DEFAULT_VOLUME          1.0
75 #define DEFAULT_MUTE            FALSE
76 #define MAX_VOLUME              10.0
77
78 enum
79 {
80   PROP_0,
81   PROP_SERVER,
82   PROP_DEVICE,
83   PROP_DEVICE_NAME,
84   PROP_VOLUME,
85   PROP_MUTE,
86   PROP_CLIENT,
87   PROP_STREAM_PROPERTIES,
88   PROP_LAST
89 };
90
91 #define GST_TYPE_PULSERING_BUFFER        \
92         (gst_pulseringbuffer_get_type())
93 #define GST_PULSERING_BUFFER(obj)        \
94         (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_PULSERING_BUFFER,GstPulseRingBuffer))
95 #define GST_PULSERING_BUFFER_CLASS(klass) \
96         (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_PULSERING_BUFFER,GstPulseRingBufferClass))
97 #define GST_PULSERING_BUFFER_GET_CLASS(obj) \
98         (G_TYPE_INSTANCE_GET_CLASS ((obj), GST_TYPE_PULSERING_BUFFER, GstPulseRingBufferClass))
99 #define GST_PULSERING_BUFFER_CAST(obj)        \
100         ((GstPulseRingBuffer *)obj)
101 #define GST_IS_PULSERING_BUFFER(obj)     \
102         (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_PULSERING_BUFFER))
103 #define GST_IS_PULSERING_BUFFER_CLASS(klass)\
104         (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_PULSERING_BUFFER))
105
106 typedef struct _GstPulseRingBuffer GstPulseRingBuffer;
107 typedef struct _GstPulseRingBufferClass GstPulseRingBufferClass;
108
109 typedef struct _GstPulseContext GstPulseContext;
110
111 /* Store the PA contexts in a hash table to allow easy sharing among
112  * multiple instances of the sink. Keys are $context_name@$server_name
113  * (strings) and values should be GstPulseContext pointers.
114  */
115 struct _GstPulseContext
116 {
117   pa_context *context;
118   GSList *ring_buffers;
119 };
120
121 static GHashTable *gst_pulse_shared_contexts = NULL;
122
123 /* use one static main-loop for all instances
124  * this is needed to make the context sharing work as the contexts are
125  * released when releasing their parent main-loop
126  */
127 static pa_threaded_mainloop *mainloop = NULL;
128 static guint mainloop_ref_ct = 0;
129
130 /* lock for access to shared resources */
131 static GMutex *pa_shared_resource_mutex = NULL;
132
133 /* We keep a custom ringbuffer that is backed up by data allocated by
134  * pulseaudio. We must also overide the commit function to write into
135  * pulseaudio memory instead. */
136 struct _GstPulseRingBuffer
137 {
138   GstRingBuffer object;
139
140   gchar *context_name;
141   gchar *stream_name;
142
143   pa_context *context;
144   pa_stream *stream;
145
146   pa_sample_spec sample_spec;
147
148 #ifdef HAVE_PULSE_0_9_16
149   void *m_data;
150   size_t m_towrite;
151   size_t m_writable;
152   gint64 m_offset;
153   gint64 m_lastoffset;
154 #endif
155
156   gboolean corked:1;
157   gboolean in_commit:1;
158   gboolean paused:1;
159 };
160 struct _GstPulseRingBufferClass
161 {
162   GstRingBufferClass parent_class;
163 };
164
165 static GType gst_pulseringbuffer_get_type (void);
166 static void gst_pulseringbuffer_finalize (GObject * object);
167
168 static GstRingBufferClass *ring_parent_class = NULL;
169
170 static gboolean gst_pulseringbuffer_open_device (GstRingBuffer * buf);
171 static gboolean gst_pulseringbuffer_close_device (GstRingBuffer * buf);
172 static gboolean gst_pulseringbuffer_acquire (GstRingBuffer * buf,
173     GstRingBufferSpec * spec);
174 static gboolean gst_pulseringbuffer_release (GstRingBuffer * buf);
175 static gboolean gst_pulseringbuffer_start (GstRingBuffer * buf);
176 static gboolean gst_pulseringbuffer_pause (GstRingBuffer * buf);
177 static gboolean gst_pulseringbuffer_stop (GstRingBuffer * buf);
178 static void gst_pulseringbuffer_clear (GstRingBuffer * buf);
179 static guint gst_pulseringbuffer_commit (GstRingBuffer * buf,
180     guint64 * sample, guchar * data, gint in_samples, gint out_samples,
181     gint * accum);
182
183 G_DEFINE_TYPE (GstPulseRingBuffer, gst_pulseringbuffer, GST_TYPE_RING_BUFFER);
184
185 static void
186 gst_pulsesink_init_contexts (void)
187 {
188   g_assert (pa_shared_resource_mutex == NULL);
189   pa_shared_resource_mutex = g_mutex_new ();
190   gst_pulse_shared_contexts = g_hash_table_new_full (g_str_hash, g_str_equal,
191       g_free, NULL);
192 }
193
194 static void
195 gst_pulseringbuffer_class_init (GstPulseRingBufferClass * klass)
196 {
197   GObjectClass *gobject_class;
198   GstRingBufferClass *gstringbuffer_class;
199
200   gobject_class = (GObjectClass *) klass;
201   gstringbuffer_class = (GstRingBufferClass *) klass;
202
203   ring_parent_class = g_type_class_peek_parent (klass);
204
205   gobject_class->finalize = gst_pulseringbuffer_finalize;
206
207   gstringbuffer_class->open_device =
208       GST_DEBUG_FUNCPTR (gst_pulseringbuffer_open_device);
209   gstringbuffer_class->close_device =
210       GST_DEBUG_FUNCPTR (gst_pulseringbuffer_close_device);
211   gstringbuffer_class->acquire =
212       GST_DEBUG_FUNCPTR (gst_pulseringbuffer_acquire);
213   gstringbuffer_class->release =
214       GST_DEBUG_FUNCPTR (gst_pulseringbuffer_release);
215   gstringbuffer_class->start = GST_DEBUG_FUNCPTR (gst_pulseringbuffer_start);
216   gstringbuffer_class->pause = GST_DEBUG_FUNCPTR (gst_pulseringbuffer_pause);
217   gstringbuffer_class->resume = GST_DEBUG_FUNCPTR (gst_pulseringbuffer_start);
218   gstringbuffer_class->stop = GST_DEBUG_FUNCPTR (gst_pulseringbuffer_stop);
219   gstringbuffer_class->clear_all =
220       GST_DEBUG_FUNCPTR (gst_pulseringbuffer_clear);
221
222   gstringbuffer_class->commit = GST_DEBUG_FUNCPTR (gst_pulseringbuffer_commit);
223 }
224
225 static void
226 gst_pulseringbuffer_init (GstPulseRingBuffer * pbuf)
227 {
228   pbuf->stream_name = NULL;
229   pbuf->context = NULL;
230   pbuf->stream = NULL;
231
232 #ifdef HAVE_PULSE_0_9_13
233   pa_sample_spec_init (&pbuf->sample_spec);
234 #else
235   pbuf->sample_spec.format = PA_SAMPLE_INVALID;
236   pbuf->sample_spec.rate = 0;
237   pbuf->sample_spec.channels = 0;
238 #endif
239
240 #ifdef HAVE_PULSE_0_9_16
241   pbuf->m_data = NULL;
242   pbuf->m_towrite = 0;
243   pbuf->m_writable = 0;
244   pbuf->m_offset = 0;
245   pbuf->m_lastoffset = 0;
246 #endif
247
248   pbuf->corked = TRUE;
249   pbuf->in_commit = FALSE;
250   pbuf->paused = FALSE;
251 }
252
253 static void
254 gst_pulsering_destroy_stream (GstPulseRingBuffer * pbuf)
255 {
256   if (pbuf->stream) {
257
258 #ifdef HAVE_PULSE_0_9_16
259     if (pbuf->m_data) {
260       /* drop shm memory buffer */
261       pa_stream_cancel_write (pbuf->stream);
262
263       /* reset internal variables */
264       pbuf->m_data = NULL;
265       pbuf->m_towrite = 0;
266       pbuf->m_writable = 0;
267       pbuf->m_offset = 0;
268       pbuf->m_lastoffset = 0;
269     }
270 #endif
271
272     pa_stream_disconnect (pbuf->stream);
273
274     /* Make sure we don't get any further callbacks */
275     pa_stream_set_state_callback (pbuf->stream, NULL, NULL);
276     pa_stream_set_write_callback (pbuf->stream, NULL, NULL);
277     pa_stream_set_underflow_callback (pbuf->stream, NULL, NULL);
278     pa_stream_set_overflow_callback (pbuf->stream, NULL, NULL);
279
280     pa_stream_unref (pbuf->stream);
281     pbuf->stream = NULL;
282   }
283
284   g_free (pbuf->stream_name);
285   pbuf->stream_name = NULL;
286 }
287
288 static void
289 gst_pulsering_destroy_context (GstPulseRingBuffer * pbuf)
290 {
291   g_mutex_lock (pa_shared_resource_mutex);
292
293   GST_DEBUG_OBJECT (pbuf, "destroying ringbuffer %p", pbuf);
294
295   gst_pulsering_destroy_stream (pbuf);
296
297   if (pbuf->context) {
298     pa_context_unref (pbuf->context);
299     pbuf->context = NULL;
300   }
301
302   if (pbuf->context_name) {
303     GstPulseContext *pctx;
304
305     pctx = g_hash_table_lookup (gst_pulse_shared_contexts, pbuf->context_name);
306
307     GST_DEBUG_OBJECT (pbuf, "releasing context with name %s, pbuf=%p, pctx=%p",
308         pbuf->context_name, pbuf, pctx);
309
310     if (pctx) {
311       pctx->ring_buffers = g_slist_remove (pctx->ring_buffers, pbuf);
312       if (pctx->ring_buffers == NULL) {
313         GST_DEBUG_OBJECT (pbuf,
314             "destroying final context with name %s, pbuf=%p, pctx=%p",
315             pbuf->context_name, pbuf, pctx);
316
317         pa_context_disconnect (pctx->context);
318
319         /* Make sure we don't get any further callbacks */
320         pa_context_set_state_callback (pctx->context, NULL, NULL);
321 #ifdef HAVE_PULSE_0_9_12
322         pa_context_set_subscribe_callback (pctx->context, NULL, NULL);
323 #endif
324
325         g_hash_table_remove (gst_pulse_shared_contexts, pbuf->context_name);
326
327         pa_context_unref (pctx->context);
328         g_slice_free (GstPulseContext, pctx);
329       }
330     }
331     g_free (pbuf->context_name);
332     pbuf->context_name = NULL;
333   }
334   g_mutex_unlock (pa_shared_resource_mutex);
335 }
336
337 static void
338 gst_pulseringbuffer_finalize (GObject * object)
339 {
340   GstPulseRingBuffer *ringbuffer;
341
342   ringbuffer = GST_PULSERING_BUFFER_CAST (object);
343
344   gst_pulsering_destroy_context (ringbuffer);
345   G_OBJECT_CLASS (ring_parent_class)->finalize (object);
346 }
347
348
349 #define CONTEXT_OK(c) ((c) && PA_CONTEXT_IS_GOOD (pa_context_get_state ((c))))
350 #define STREAM_OK(s) ((s) && PA_STREAM_IS_GOOD (pa_stream_get_state ((s))))
351
352 static gboolean
353 gst_pulsering_is_dead (GstPulseSink * psink, GstPulseRingBuffer * pbuf,
354     gboolean check_stream)
355 {
356   if (!CONTEXT_OK (pbuf->context))
357     goto error;
358
359   if (check_stream && !STREAM_OK (pbuf->stream))
360     goto error;
361
362   return FALSE;
363
364 error:
365   {
366     const gchar *err_str =
367         pbuf->context ? pa_strerror (pa_context_errno (pbuf->context)) : NULL;
368     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED, ("Disconnected: %s",
369             err_str), (NULL));
370     return TRUE;
371   }
372 }
373
374 static void
375 gst_pulsering_context_state_cb (pa_context * c, void *userdata)
376 {
377   pa_context_state_t state;
378   pa_threaded_mainloop *mainloop = (pa_threaded_mainloop *) userdata;
379
380   state = pa_context_get_state (c);
381
382   GST_LOG ("got new context state %d", state);
383
384   switch (state) {
385     case PA_CONTEXT_READY:
386     case PA_CONTEXT_TERMINATED:
387     case PA_CONTEXT_FAILED:
388       GST_LOG ("signaling");
389       pa_threaded_mainloop_signal (mainloop, 0);
390       break;
391
392     case PA_CONTEXT_UNCONNECTED:
393     case PA_CONTEXT_CONNECTING:
394     case PA_CONTEXT_AUTHORIZING:
395     case PA_CONTEXT_SETTING_NAME:
396       break;
397   }
398 }
399
400 #ifdef HAVE_PULSE_0_9_12
401 static void
402 gst_pulsering_context_subscribe_cb (pa_context * c,
403     pa_subscription_event_type_t t, uint32_t idx, void *userdata)
404 {
405   GstPulseSink *psink;
406   GstPulseContext *pctx = (GstPulseContext *) userdata;
407   GSList *walk;
408
409   if (t != (PA_SUBSCRIPTION_EVENT_SINK_INPUT | PA_SUBSCRIPTION_EVENT_CHANGE) &&
410       t != (PA_SUBSCRIPTION_EVENT_SINK_INPUT | PA_SUBSCRIPTION_EVENT_NEW))
411     return;
412
413   for (walk = pctx->ring_buffers; walk; walk = g_slist_next (walk)) {
414     GstPulseRingBuffer *pbuf = (GstPulseRingBuffer *) walk->data;
415     psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
416
417     GST_LOG_OBJECT (psink, "type %d, idx %u", t, idx);
418
419     if (!pbuf->stream)
420       continue;
421
422     if (idx != pa_stream_get_index (pbuf->stream))
423       continue;
424
425     /* Actually this event is also triggered when other properties of
426      * the stream change that are unrelated to the volume. However it is
427      * probably cheaper to signal the change here and check for the
428      * volume when the GObject property is read instead of querying it always. */
429
430     /* inform streaming thread to notify */
431     g_atomic_int_compare_and_exchange (&psink->notify, 0, 1);
432   }
433 }
434 #endif
435
436 /* will be called when the device should be opened. In this case we will connect
437  * to the server. We should not try to open any streams in this state. */
438 static gboolean
439 gst_pulseringbuffer_open_device (GstRingBuffer * buf)
440 {
441   GstPulseSink *psink;
442   GstPulseRingBuffer *pbuf;
443   GstPulseContext *pctx;
444   pa_mainloop_api *api;
445   gboolean need_unlock_shared;
446
447   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (buf));
448   pbuf = GST_PULSERING_BUFFER_CAST (buf);
449
450   g_assert (!pbuf->stream);
451   g_assert (psink->client_name);
452
453   if (psink->server)
454     pbuf->context_name = g_strdup_printf ("%s@%s", psink->client_name,
455         psink->server);
456   else
457     pbuf->context_name = g_strdup (psink->client_name);
458
459   pa_threaded_mainloop_lock (mainloop);
460
461   g_mutex_lock (pa_shared_resource_mutex);
462   need_unlock_shared = TRUE;
463
464   pctx = g_hash_table_lookup (gst_pulse_shared_contexts, pbuf->context_name);
465   if (pctx == NULL) {
466     pctx = g_slice_new0 (GstPulseContext);
467
468     /* get the mainloop api and create a context */
469     GST_INFO_OBJECT (psink, "new context with name %s, pbuf=%p, pctx=%p",
470         pbuf->context_name, pbuf, pctx);
471     api = pa_threaded_mainloop_get_api (mainloop);
472     if (!(pctx->context = pa_context_new (api, pbuf->context_name)))
473       goto create_failed;
474
475     pctx->ring_buffers = g_slist_prepend (pctx->ring_buffers, pbuf);
476     g_hash_table_insert (gst_pulse_shared_contexts,
477         g_strdup (pbuf->context_name), (gpointer) pctx);
478     /* register some essential callbacks */
479     pa_context_set_state_callback (pctx->context,
480         gst_pulsering_context_state_cb, mainloop);
481 #ifdef HAVE_PULSE_0_9_12
482     pa_context_set_subscribe_callback (pctx->context,
483         gst_pulsering_context_subscribe_cb, pctx);
484 #endif
485
486     /* try to connect to the server and wait for completion, we don't want to
487      * autospawn a deamon */
488     GST_LOG_OBJECT (psink, "connect to server %s",
489         GST_STR_NULL (psink->server));
490     if (pa_context_connect (pctx->context, psink->server,
491             PA_CONTEXT_NOAUTOSPAWN, NULL) < 0)
492       goto connect_failed;
493   } else {
494     GST_INFO_OBJECT (psink,
495         "reusing shared context with name %s, pbuf=%p, pctx=%p",
496         pbuf->context_name, pbuf, pctx);
497     pctx->ring_buffers = g_slist_prepend (pctx->ring_buffers, pbuf);
498   }
499
500   g_mutex_unlock (pa_shared_resource_mutex);
501   need_unlock_shared = FALSE;
502
503   /* context created or shared okay */
504   pbuf->context = pa_context_ref (pctx->context);
505
506   for (;;) {
507     pa_context_state_t state;
508
509     state = pa_context_get_state (pbuf->context);
510
511     GST_LOG_OBJECT (psink, "context state is now %d", state);
512
513     if (!PA_CONTEXT_IS_GOOD (state))
514       goto connect_failed;
515
516     if (state == PA_CONTEXT_READY)
517       break;
518
519     /* Wait until the context is ready */
520     GST_LOG_OBJECT (psink, "waiting..");
521     pa_threaded_mainloop_wait (mainloop);
522   }
523
524   GST_LOG_OBJECT (psink, "opened the device");
525
526   pa_threaded_mainloop_unlock (mainloop);
527
528   return TRUE;
529
530   /* ERRORS */
531 unlock_and_fail:
532   {
533     if (need_unlock_shared)
534       g_mutex_unlock (pa_shared_resource_mutex);
535     gst_pulsering_destroy_context (pbuf);
536     pa_threaded_mainloop_unlock (mainloop);
537     return FALSE;
538   }
539 create_failed:
540   {
541     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
542         ("Failed to create context"), (NULL));
543     g_slice_free (GstPulseContext, pctx);
544     goto unlock_and_fail;
545   }
546 connect_failed:
547   {
548     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED, ("Failed to connect: %s",
549             pa_strerror (pa_context_errno (pctx->context))), (NULL));
550     goto unlock_and_fail;
551   }
552 }
553
554 /* close the device */
555 static gboolean
556 gst_pulseringbuffer_close_device (GstRingBuffer * buf)
557 {
558   GstPulseSink *psink;
559   GstPulseRingBuffer *pbuf;
560
561   pbuf = GST_PULSERING_BUFFER_CAST (buf);
562   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (buf));
563
564   GST_LOG_OBJECT (psink, "closing device");
565
566   pa_threaded_mainloop_lock (mainloop);
567   gst_pulsering_destroy_context (pbuf);
568   pa_threaded_mainloop_unlock (mainloop);
569
570   GST_LOG_OBJECT (psink, "closed device");
571
572   return TRUE;
573 }
574
575 static void
576 gst_pulsering_stream_state_cb (pa_stream * s, void *userdata)
577 {
578   GstPulseSink *psink;
579   GstPulseRingBuffer *pbuf;
580   pa_stream_state_t state;
581
582   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
583   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
584
585   state = pa_stream_get_state (s);
586   GST_LOG_OBJECT (psink, "got new stream state %d", state);
587
588   switch (state) {
589     case PA_STREAM_READY:
590     case PA_STREAM_FAILED:
591     case PA_STREAM_TERMINATED:
592       GST_LOG_OBJECT (psink, "signaling");
593       pa_threaded_mainloop_signal (mainloop, 0);
594       break;
595     case PA_STREAM_UNCONNECTED:
596     case PA_STREAM_CREATING:
597       break;
598   }
599 }
600
601 static void
602 gst_pulsering_stream_request_cb (pa_stream * s, size_t length, void *userdata)
603 {
604   GstPulseSink *psink;
605   GstRingBuffer *rbuf;
606   GstPulseRingBuffer *pbuf;
607
608   rbuf = GST_RING_BUFFER_CAST (userdata);
609   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
610   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
611
612   GST_LOG_OBJECT (psink, "got request for length %" G_GSIZE_FORMAT, length);
613
614   if (pbuf->in_commit && (length >= rbuf->spec.segsize)) {
615     /* only signal when we are waiting in the commit thread
616      * and got request for atleast a segment */
617     pa_threaded_mainloop_signal (mainloop, 0);
618   }
619 }
620
621 static void
622 gst_pulsering_stream_underflow_cb (pa_stream * s, void *userdata)
623 {
624   GstPulseSink *psink;
625   GstPulseRingBuffer *pbuf;
626
627   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
628   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
629
630   GST_WARNING_OBJECT (psink, "Got underflow");
631 }
632
633 static void
634 gst_pulsering_stream_overflow_cb (pa_stream * s, void *userdata)
635 {
636   GstPulseSink *psink;
637   GstPulseRingBuffer *pbuf;
638
639   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
640   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
641
642   GST_WARNING_OBJECT (psink, "Got overflow");
643 }
644
645 static void
646 gst_pulsering_stream_latency_cb (pa_stream * s, void *userdata)
647 {
648   GstPulseSink *psink;
649   GstPulseRingBuffer *pbuf;
650   const pa_timing_info *info;
651   pa_usec_t sink_usec;
652
653   info = pa_stream_get_timing_info (s);
654
655   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
656   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
657
658   if (!info) {
659     GST_LOG_OBJECT (psink, "latency update (information unknown)");
660     return;
661   }
662 #ifdef HAVE_PULSE_0_9_11
663   sink_usec = info->configured_sink_usec;
664 #else
665   sink_usec = 0;
666 #endif
667
668   GST_LOG_OBJECT (psink,
669       "latency_update, %" G_GUINT64_FORMAT ", %d:%" G_GINT64_FORMAT ", %d:%"
670       G_GUINT64_FORMAT ", %" G_GUINT64_FORMAT ", %" G_GUINT64_FORMAT,
671       GST_TIMEVAL_TO_TIME (info->timestamp), info->write_index_corrupt,
672       info->write_index, info->read_index_corrupt, info->read_index,
673       info->sink_usec, sink_usec);
674 }
675
676 static void
677 gst_pulsering_stream_suspended_cb (pa_stream * p, void *userdata)
678 {
679   GstPulseSink *psink;
680   GstPulseRingBuffer *pbuf;
681
682   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
683   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
684
685   if (pa_stream_is_suspended (p))
686     GST_DEBUG_OBJECT (psink, "stream suspended");
687   else
688     GST_DEBUG_OBJECT (psink, "stream resumed");
689 }
690
691 #ifdef HAVE_PULSE_0_9_11
692 static void
693 gst_pulsering_stream_started_cb (pa_stream * p, void *userdata)
694 {
695   GstPulseSink *psink;
696   GstPulseRingBuffer *pbuf;
697
698   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
699   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
700
701   GST_DEBUG_OBJECT (psink, "stream started");
702 }
703 #endif
704
705 #ifdef HAVE_PULSE_0_9_15
706 static void
707 gst_pulsering_stream_event_cb (pa_stream * p, const char *name,
708     pa_proplist * pl, void *userdata)
709 {
710   GstPulseSink *psink;
711   GstPulseRingBuffer *pbuf;
712
713   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
714   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
715
716   if (!strcmp (name, PA_STREAM_EVENT_REQUEST_CORK)) {
717     /* the stream wants to PAUSE, post a message for the application. */
718     GST_DEBUG_OBJECT (psink, "got request for CORK");
719     gst_element_post_message (GST_ELEMENT_CAST (psink),
720         gst_message_new_request_state (GST_OBJECT_CAST (psink),
721             GST_STATE_PAUSED));
722
723   } else if (!strcmp (name, PA_STREAM_EVENT_REQUEST_UNCORK)) {
724     GST_DEBUG_OBJECT (psink, "got request for UNCORK");
725     gst_element_post_message (GST_ELEMENT_CAST (psink),
726         gst_message_new_request_state (GST_OBJECT_CAST (psink),
727             GST_STATE_PLAYING));
728   } else {
729     GST_DEBUG_OBJECT (psink, "got unknown event %s", name);
730   }
731 }
732 #endif
733
734 /* This method should create a new stream of the given @spec. No playback should
735  * start yet so we start in the corked state. */
736 static gboolean
737 gst_pulseringbuffer_acquire (GstRingBuffer * buf, GstRingBufferSpec * spec)
738 {
739   GstPulseSink *psink;
740   GstPulseRingBuffer *pbuf;
741   pa_buffer_attr wanted;
742   const pa_buffer_attr *actual;
743   pa_channel_map channel_map;
744   pa_operation *o = NULL;
745 #ifdef HAVE_PULSE_0_9_20
746   pa_cvolume v;
747 #endif
748   pa_cvolume *pv = NULL;
749   pa_stream_flags_t flags;
750   const gchar *name;
751   GstAudioClock *clock;
752
753   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (buf));
754   pbuf = GST_PULSERING_BUFFER_CAST (buf);
755
756   GST_LOG_OBJECT (psink, "creating sample spec");
757   /* convert the gstreamer sample spec to the pulseaudio format */
758   if (!gst_pulse_fill_sample_spec (spec, &pbuf->sample_spec))
759     goto invalid_spec;
760
761   pa_threaded_mainloop_lock (mainloop);
762
763   /* we need a context and a no stream */
764   g_assert (pbuf->context);
765   g_assert (!pbuf->stream);
766
767   /* enable event notifications */
768   GST_LOG_OBJECT (psink, "subscribing to context events");
769   if (!(o = pa_context_subscribe (pbuf->context,
770               PA_SUBSCRIPTION_MASK_SINK_INPUT, NULL, NULL)))
771     goto subscribe_failed;
772
773   pa_operation_unref (o);
774
775   /* initialize the channel map */
776   gst_pulse_gst_to_channel_map (&channel_map, spec);
777
778   /* find a good name for the stream */
779   if (psink->stream_name)
780     name = psink->stream_name;
781   else
782     name = "Playback Stream";
783
784   /* create a stream */
785   GST_LOG_OBJECT (psink, "creating stream with name %s", name);
786   if (!(pbuf->stream = pa_stream_new_with_proplist (pbuf->context, name,
787               &pbuf->sample_spec, &channel_map, psink->proplist)))
788     goto stream_failed;
789
790   /* install essential callbacks */
791   pa_stream_set_state_callback (pbuf->stream,
792       gst_pulsering_stream_state_cb, pbuf);
793   pa_stream_set_write_callback (pbuf->stream,
794       gst_pulsering_stream_request_cb, pbuf);
795   pa_stream_set_underflow_callback (pbuf->stream,
796       gst_pulsering_stream_underflow_cb, pbuf);
797   pa_stream_set_overflow_callback (pbuf->stream,
798       gst_pulsering_stream_overflow_cb, pbuf);
799   pa_stream_set_latency_update_callback (pbuf->stream,
800       gst_pulsering_stream_latency_cb, pbuf);
801   pa_stream_set_suspended_callback (pbuf->stream,
802       gst_pulsering_stream_suspended_cb, pbuf);
803 #ifdef HAVE_PULSE_0_9_11
804   pa_stream_set_started_callback (pbuf->stream,
805       gst_pulsering_stream_started_cb, pbuf);
806 #endif
807 #ifdef HAVE_PULSE_0_9_15
808   pa_stream_set_event_callback (pbuf->stream,
809       gst_pulsering_stream_event_cb, pbuf);
810 #endif
811
812   /* buffering requirements. When setting prebuf to 0, the stream will not pause
813    * when we cause an underrun, which causes time to continue. */
814   memset (&wanted, 0, sizeof (wanted));
815   wanted.tlength = spec->segtotal * spec->segsize;
816   wanted.maxlength = -1;
817   wanted.prebuf = 0;
818   wanted.minreq = spec->segsize;
819
820   GST_INFO_OBJECT (psink, "tlength:   %d", wanted.tlength);
821   GST_INFO_OBJECT (psink, "maxlength: %d", wanted.maxlength);
822   GST_INFO_OBJECT (psink, "prebuf:    %d", wanted.prebuf);
823   GST_INFO_OBJECT (psink, "minreq:    %d", wanted.minreq);
824
825 #ifdef HAVE_PULSE_0_9_20
826   /* configure volume when we changed it, else we leave the default */
827   if (psink->volume_set) {
828     GST_LOG_OBJECT (psink, "have volume of %f", psink->volume);
829     pv = &v;
830     gst_pulse_cvolume_from_linear (pv, pbuf->sample_spec.channels,
831         psink->volume);
832   } else {
833     pv = NULL;
834   }
835 #endif
836
837   /* construct the flags */
838   flags = PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE |
839 #ifdef HAVE_PULSE_0_9_11
840       PA_STREAM_ADJUST_LATENCY |
841 #endif
842       PA_STREAM_START_CORKED;
843
844 #ifdef HAVE_PULSE_0_9_12
845   if (psink->mute_set && psink->mute)
846     flags |= PA_STREAM_START_MUTED;
847 #endif
848
849   /* we always start corked (see flags above) */
850   pbuf->corked = TRUE;
851
852   /* try to connect now */
853   GST_LOG_OBJECT (psink, "connect for playback to device %s",
854       GST_STR_NULL (psink->device));
855   if (pa_stream_connect_playback (pbuf->stream, psink->device,
856           &wanted, flags, pv, NULL) < 0)
857     goto connect_failed;
858
859   /* our clock will now start from 0 again */
860   clock = GST_AUDIO_CLOCK (GST_BASE_AUDIO_SINK (psink)->provided_clock);
861   gst_audio_clock_reset (clock, 0);
862
863   for (;;) {
864     pa_stream_state_t state;
865
866     state = pa_stream_get_state (pbuf->stream);
867
868     GST_LOG_OBJECT (psink, "stream state is now %d", state);
869
870     if (!PA_STREAM_IS_GOOD (state))
871       goto connect_failed;
872
873     if (state == PA_STREAM_READY)
874       break;
875
876     /* Wait until the stream is ready */
877     pa_threaded_mainloop_wait (mainloop);
878   }
879
880   /* After we passed the volume off of to PA we never want to set it
881      again, since it is PA's job to save/restore volumes.  */
882   psink->volume_set = psink->mute_set = FALSE;
883
884   GST_LOG_OBJECT (psink, "stream is acquired now");
885
886   /* get the actual buffering properties now */
887   actual = pa_stream_get_buffer_attr (pbuf->stream);
888
889   GST_INFO_OBJECT (psink, "tlength:   %d (wanted: %d)", actual->tlength,
890       wanted.tlength);
891   GST_INFO_OBJECT (psink, "maxlength: %d", actual->maxlength);
892   GST_INFO_OBJECT (psink, "prebuf:    %d", actual->prebuf);
893   GST_INFO_OBJECT (psink, "minreq:    %d (wanted %d)", actual->minreq,
894       wanted.minreq);
895
896   spec->segsize = actual->minreq;
897   spec->segtotal = actual->tlength / spec->segsize;
898
899   pa_threaded_mainloop_unlock (mainloop);
900
901   return TRUE;
902
903   /* ERRORS */
904 unlock_and_fail:
905   {
906     gst_pulsering_destroy_stream (pbuf);
907     pa_threaded_mainloop_unlock (mainloop);
908
909     return FALSE;
910   }
911 invalid_spec:
912   {
913     GST_ELEMENT_ERROR (psink, RESOURCE, SETTINGS,
914         ("Invalid sample specification."), (NULL));
915     return FALSE;
916   }
917 subscribe_failed:
918   {
919     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
920         ("pa_context_subscribe() failed: %s",
921             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
922     goto unlock_and_fail;
923   }
924 stream_failed:
925   {
926     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
927         ("Failed to create stream: %s",
928             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
929     goto unlock_and_fail;
930   }
931 connect_failed:
932   {
933     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
934         ("Failed to connect stream: %s",
935             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
936     goto unlock_and_fail;
937   }
938 }
939
940 /* free the stream that we acquired before */
941 static gboolean
942 gst_pulseringbuffer_release (GstRingBuffer * buf)
943 {
944   GstPulseRingBuffer *pbuf;
945
946   pbuf = GST_PULSERING_BUFFER_CAST (buf);
947
948   pa_threaded_mainloop_lock (mainloop);
949   gst_pulsering_destroy_stream (pbuf);
950   pa_threaded_mainloop_unlock (mainloop);
951
952   return TRUE;
953 }
954
955 static void
956 gst_pulsering_success_cb (pa_stream * s, int success, void *userdata)
957 {
958   pa_threaded_mainloop_signal (mainloop, 0);
959 }
960
961 /* update the corked state of a stream, must be called with the mainloop
962  * lock */
963 static gboolean
964 gst_pulsering_set_corked (GstPulseRingBuffer * pbuf, gboolean corked,
965     gboolean wait)
966 {
967   pa_operation *o = NULL;
968   GstPulseSink *psink;
969   gboolean res = FALSE;
970
971   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
972
973   GST_DEBUG_OBJECT (psink, "setting corked state to %d", corked);
974   if (pbuf->corked != corked) {
975     if (!(o = pa_stream_cork (pbuf->stream, corked,
976                 gst_pulsering_success_cb, pbuf)))
977       goto cork_failed;
978
979     while (wait && pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
980       pa_threaded_mainloop_wait (mainloop);
981       if (gst_pulsering_is_dead (psink, pbuf, TRUE))
982         goto server_dead;
983     }
984     pbuf->corked = corked;
985   } else {
986     GST_DEBUG_OBJECT (psink, "skipping, already in requested state");
987   }
988   res = TRUE;
989
990 cleanup:
991   if (o)
992     pa_operation_unref (o);
993
994   return res;
995
996   /* ERRORS */
997 server_dead:
998   {
999     GST_DEBUG_OBJECT (psink, "the server is dead");
1000     goto cleanup;
1001   }
1002 cork_failed:
1003   {
1004     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1005         ("pa_stream_cork() failed: %s",
1006             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1007     goto cleanup;
1008   }
1009 }
1010
1011 static void
1012 gst_pulseringbuffer_clear (GstRingBuffer * buf)
1013 {
1014   GstPulseSink *psink;
1015   GstPulseRingBuffer *pbuf;
1016   pa_operation *o = NULL;
1017
1018   pbuf = GST_PULSERING_BUFFER_CAST (buf);
1019   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1020
1021   pa_threaded_mainloop_lock (mainloop);
1022   GST_DEBUG_OBJECT (psink, "clearing");
1023   if (pbuf->stream) {
1024     /* don't wait for the flush to complete */
1025     if ((o = pa_stream_flush (pbuf->stream, NULL, pbuf)))
1026       pa_operation_unref (o);
1027   }
1028   pa_threaded_mainloop_unlock (mainloop);
1029 }
1030
1031 static void
1032 mainloop_enter_defer_cb (pa_mainloop_api * api, void *userdata)
1033 {
1034   GstPulseSink *pulsesink = GST_PULSESINK (userdata);
1035   GstMessage *message;
1036   GValue val = { 0 };
1037
1038   g_value_init (&val, G_TYPE_POINTER);
1039   g_value_set_pointer (&val, g_thread_self ());
1040
1041   GST_DEBUG_OBJECT (pulsesink, "posting ENTER stream status");
1042   message = gst_message_new_stream_status (GST_OBJECT (pulsesink),
1043       GST_STREAM_STATUS_TYPE_ENTER, GST_ELEMENT (pulsesink));
1044   gst_message_set_stream_status_object (message, &val);
1045
1046   gst_element_post_message (GST_ELEMENT (pulsesink), message);
1047
1048   /* signal the waiter */
1049   pulsesink->pa_defer_ran = TRUE;
1050   pa_threaded_mainloop_signal (mainloop, 0);
1051 }
1052
1053 /* start/resume playback ASAP, we don't uncork here but in the commit method */
1054 static gboolean
1055 gst_pulseringbuffer_start (GstRingBuffer * buf)
1056 {
1057   GstPulseSink *psink;
1058   GstPulseRingBuffer *pbuf;
1059
1060   pbuf = GST_PULSERING_BUFFER_CAST (buf);
1061   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1062
1063   pa_threaded_mainloop_lock (mainloop);
1064
1065   GST_DEBUG_OBJECT (psink, "scheduling stream status");
1066   psink->pa_defer_ran = FALSE;
1067   pa_mainloop_api_once (pa_threaded_mainloop_get_api (mainloop),
1068       mainloop_enter_defer_cb, psink);
1069
1070   GST_DEBUG_OBJECT (psink, "starting");
1071   pbuf->paused = FALSE;
1072
1073   /* EOS needs running clock */
1074   if (GST_BASE_SINK_CAST (psink)->eos ||
1075       g_atomic_int_get (&GST_BASE_AUDIO_SINK (psink)->abidata.
1076           ABI.eos_rendering))
1077     gst_pulsering_set_corked (pbuf, FALSE, FALSE);
1078
1079   pa_threaded_mainloop_unlock (mainloop);
1080
1081   return TRUE;
1082 }
1083
1084 /* pause/stop playback ASAP */
1085 static gboolean
1086 gst_pulseringbuffer_pause (GstRingBuffer * buf)
1087 {
1088   GstPulseSink *psink;
1089   GstPulseRingBuffer *pbuf;
1090   gboolean res;
1091
1092   pbuf = GST_PULSERING_BUFFER_CAST (buf);
1093   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1094
1095   pa_threaded_mainloop_lock (mainloop);
1096   GST_DEBUG_OBJECT (psink, "pausing and corking");
1097   /* make sure the commit method stops writing */
1098   pbuf->paused = TRUE;
1099   res = gst_pulsering_set_corked (pbuf, TRUE, TRUE);
1100   if (pbuf->in_commit) {
1101     /* we are waiting in a commit, signal */
1102     GST_DEBUG_OBJECT (psink, "signal commit");
1103     pa_threaded_mainloop_signal (mainloop, 0);
1104   }
1105   pa_threaded_mainloop_unlock (mainloop);
1106
1107   return res;
1108 }
1109
1110 static void
1111 mainloop_leave_defer_cb (pa_mainloop_api * api, void *userdata)
1112 {
1113   GstPulseSink *pulsesink = GST_PULSESINK (userdata);
1114   GstMessage *message;
1115   GValue val = { 0 };
1116
1117   g_value_init (&val, G_TYPE_POINTER);
1118   g_value_set_pointer (&val, g_thread_self ());
1119
1120   GST_DEBUG_OBJECT (pulsesink, "posting LEAVE stream status");
1121   message = gst_message_new_stream_status (GST_OBJECT (pulsesink),
1122       GST_STREAM_STATUS_TYPE_LEAVE, GST_ELEMENT (pulsesink));
1123   gst_message_set_stream_status_object (message, &val);
1124   gst_element_post_message (GST_ELEMENT (pulsesink), message);
1125
1126   pulsesink->pa_defer_ran = TRUE;
1127   pa_threaded_mainloop_signal (mainloop, 0);
1128   gst_object_unref (pulsesink);
1129 }
1130
1131 /* stop playback, we flush everything. */
1132 static gboolean
1133 gst_pulseringbuffer_stop (GstRingBuffer * buf)
1134 {
1135   GstPulseSink *psink;
1136   GstPulseRingBuffer *pbuf;
1137   gboolean res = FALSE;
1138   pa_operation *o = NULL;
1139
1140   pbuf = GST_PULSERING_BUFFER_CAST (buf);
1141   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1142
1143   pa_threaded_mainloop_lock (mainloop);
1144   pbuf->paused = TRUE;
1145   res = gst_pulsering_set_corked (pbuf, TRUE, TRUE);
1146   /* Inform anyone waiting in _commit() call that it shall wakeup */
1147   if (pbuf->in_commit) {
1148     GST_DEBUG_OBJECT (psink, "signal commit thread");
1149     pa_threaded_mainloop_signal (mainloop, 0);
1150   }
1151
1152   if (strcmp (psink->pa_version, "0.9.12")) {
1153     /* then try to flush, it's not fatal when this fails */
1154     GST_DEBUG_OBJECT (psink, "flushing");
1155     if ((o = pa_stream_flush (pbuf->stream, gst_pulsering_success_cb, pbuf))) {
1156       while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
1157         GST_DEBUG_OBJECT (psink, "wait for completion");
1158         pa_threaded_mainloop_wait (mainloop);
1159         if (gst_pulsering_is_dead (psink, pbuf, TRUE))
1160           goto server_dead;
1161       }
1162       GST_DEBUG_OBJECT (psink, "flush completed");
1163     }
1164   }
1165   res = TRUE;
1166
1167 cleanup:
1168   if (o) {
1169     pa_operation_cancel (o);
1170     pa_operation_unref (o);
1171   }
1172
1173   GST_DEBUG_OBJECT (psink, "scheduling stream status");
1174   psink->pa_defer_ran = FALSE;
1175   gst_object_ref (psink);
1176   pa_mainloop_api_once (pa_threaded_mainloop_get_api (mainloop),
1177       mainloop_leave_defer_cb, psink);
1178
1179   GST_DEBUG_OBJECT (psink, "waiting for stream status");
1180   pa_threaded_mainloop_unlock (mainloop);
1181
1182   return res;
1183
1184   /* ERRORS */
1185 server_dead:
1186   {
1187     GST_DEBUG_OBJECT (psink, "the server is dead");
1188     goto cleanup;
1189   }
1190 }
1191
1192 /* in_samples >= out_samples, rate > 1.0 */
1193 #define FWD_UP_SAMPLES(s,se,d,de)               \
1194 G_STMT_START {                                  \
1195   guint8 *sb = s, *db = d;                      \
1196   while (s <= se && d < de) {                   \
1197     memcpy (d, s, bps);                         \
1198     s += bps;                                   \
1199     *accum += outr;                             \
1200     if ((*accum << 1) >= inr) {                 \
1201       *accum -= inr;                            \
1202       d += bps;                                 \
1203     }                                           \
1204   }                                             \
1205   in_samples -= (s - sb)/bps;                   \
1206   out_samples -= (d - db)/bps;                  \
1207   GST_DEBUG ("fwd_up end %d/%d",*accum,*toprocess);     \
1208 } G_STMT_END
1209
1210 /* out_samples > in_samples, for rates smaller than 1.0 */
1211 #define FWD_DOWN_SAMPLES(s,se,d,de)             \
1212 G_STMT_START {                                  \
1213   guint8 *sb = s, *db = d;                      \
1214   while (s <= se && d < de) {                   \
1215     memcpy (d, s, bps);                         \
1216     d += bps;                                   \
1217     *accum += inr;                              \
1218     if ((*accum << 1) >= outr) {                \
1219       *accum -= outr;                           \
1220       s += bps;                                 \
1221     }                                           \
1222   }                                             \
1223   in_samples -= (s - sb)/bps;                   \
1224   out_samples -= (d - db)/bps;                  \
1225   GST_DEBUG ("fwd_down end %d/%d",*accum,*toprocess);   \
1226 } G_STMT_END
1227
1228 #define REV_UP_SAMPLES(s,se,d,de)               \
1229 G_STMT_START {                                  \
1230   guint8 *sb = se, *db = d;                     \
1231   while (s <= se && d < de) {                   \
1232     memcpy (d, se, bps);                        \
1233     se -= bps;                                  \
1234     *accum += outr;                             \
1235     while (d < de && (*accum << 1) >= inr) {    \
1236       *accum -= inr;                            \
1237       d += bps;                                 \
1238     }                                           \
1239   }                                             \
1240   in_samples -= (sb - se)/bps;                  \
1241   out_samples -= (d - db)/bps;                  \
1242   GST_DEBUG ("rev_up end %d/%d",*accum,*toprocess);     \
1243 } G_STMT_END
1244
1245 #define REV_DOWN_SAMPLES(s,se,d,de)             \
1246 G_STMT_START {                                  \
1247   guint8 *sb = se, *db = d;                     \
1248   while (s <= se && d < de) {                   \
1249     memcpy (d, se, bps);                        \
1250     d += bps;                                   \
1251     *accum += inr;                              \
1252     while (s <= se && (*accum << 1) >= outr) {  \
1253       *accum -= outr;                           \
1254       se -= bps;                                \
1255     }                                           \
1256   }                                             \
1257   in_samples -= (sb - se)/bps;                  \
1258   out_samples -= (d - db)/bps;                  \
1259   GST_DEBUG ("rev_down end %d/%d",*accum,*toprocess);   \
1260 } G_STMT_END
1261
1262
1263 /* our custom commit function because we write into the buffer of pulseaudio
1264  * instead of keeping our own buffer */
1265 static guint
1266 gst_pulseringbuffer_commit (GstRingBuffer * buf, guint64 * sample,
1267     guchar * data, gint in_samples, gint out_samples, gint * accum)
1268 {
1269   GstPulseSink *psink;
1270   GstPulseRingBuffer *pbuf;
1271   guint result;
1272   guint8 *data_end;
1273   gboolean reverse;
1274   gint *toprocess;
1275   gint inr, outr, bps;
1276   gint64 offset;
1277   guint bufsize;
1278
1279   pbuf = GST_PULSERING_BUFFER_CAST (buf);
1280   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1281
1282   /* FIXME post message rather than using a signal (as mixer interface) */
1283   if (g_atomic_int_compare_and_exchange (&psink->notify, 1, 0)) {
1284     g_object_notify (G_OBJECT (psink), "volume");
1285     g_object_notify (G_OBJECT (psink), "mute");
1286   }
1287
1288   /* make sure the ringbuffer is started */
1289   if (G_UNLIKELY (g_atomic_int_get (&buf->state) !=
1290           GST_RING_BUFFER_STATE_STARTED)) {
1291     /* see if we are allowed to start it */
1292     if (G_UNLIKELY (g_atomic_int_get (&buf->abidata.ABI.may_start) == FALSE))
1293       goto no_start;
1294
1295     GST_DEBUG_OBJECT (buf, "start!");
1296     if (!gst_ring_buffer_start (buf))
1297       goto start_failed;
1298   }
1299
1300   pa_threaded_mainloop_lock (mainloop);
1301   GST_DEBUG_OBJECT (psink, "entering commit");
1302   pbuf->in_commit = TRUE;
1303
1304   bps = buf->spec.bytes_per_sample;
1305   bufsize = buf->spec.segsize * buf->spec.segtotal;
1306
1307   /* our toy resampler for trick modes */
1308   reverse = out_samples < 0;
1309   out_samples = ABS (out_samples);
1310
1311   if (in_samples >= out_samples)
1312     toprocess = &in_samples;
1313   else
1314     toprocess = &out_samples;
1315
1316   inr = in_samples - 1;
1317   outr = out_samples - 1;
1318
1319   GST_DEBUG_OBJECT (psink, "in %d, out %d", inr, outr);
1320
1321   /* data_end points to the last sample we have to write, not past it. This is
1322    * needed to properly handle reverse playback: it points to the last sample. */
1323   data_end = data + (bps * inr);
1324
1325   if (pbuf->paused)
1326     goto was_paused;
1327
1328   /* offset is in bytes */
1329   offset = *sample * bps;
1330
1331   while (*toprocess > 0) {
1332     size_t avail;
1333     guint towrite;
1334
1335     GST_LOG_OBJECT (psink,
1336         "need to write %d samples at offset %" G_GINT64_FORMAT, *toprocess,
1337         offset);
1338
1339 #ifdef HAVE_PULSE_0_9_16
1340     if (offset != pbuf->m_lastoffset)
1341       GST_LOG_OBJECT (psink, "discontinuity, offset is %" G_GINT64_FORMAT ", "
1342           "last offset was %" G_GINT64_FORMAT, offset, pbuf->m_lastoffset);
1343
1344     towrite = out_samples * bps;
1345
1346     /* Only ever write segsize bytes at once. This will
1347      * also limit the PA shm buffer to segsize
1348      */
1349     if (towrite > buf->spec.segsize)
1350       towrite = buf->spec.segsize;
1351
1352     if ((pbuf->m_writable < towrite) || (offset != pbuf->m_lastoffset)) {
1353       /* if no room left or discontinuity in offset,
1354          we need to flush data and get a new buffer */
1355
1356       /* flush the buffer if possible */
1357       if ((pbuf->m_data != NULL) && (pbuf->m_towrite > 0)) {
1358
1359         GST_LOG_OBJECT (psink,
1360             "flushing %u samples at offset %" G_GINT64_FORMAT,
1361             (guint) pbuf->m_towrite / bps, pbuf->m_offset);
1362
1363         if (pa_stream_write (pbuf->stream, (uint8_t *) pbuf->m_data,
1364                 pbuf->m_towrite, NULL, pbuf->m_offset, PA_SEEK_ABSOLUTE) < 0) {
1365           goto write_failed;
1366         }
1367       }
1368       pbuf->m_towrite = 0;
1369       pbuf->m_offset = offset;  /* keep track of current offset */
1370
1371       /* get a buffer to write in for now on */
1372       for (;;) {
1373         pbuf->m_writable = pa_stream_writable_size (pbuf->stream);
1374
1375         if (pbuf->m_writable == (size_t) - 1)
1376           goto writable_size_failed;
1377
1378         pbuf->m_writable /= bps;
1379         pbuf->m_writable *= bps;        /* handle only complete samples */
1380
1381         if (pbuf->m_writable >= towrite)
1382           break;
1383
1384         /* see if we need to uncork because we have no free space */
1385         if (pbuf->corked) {
1386           if (!gst_pulsering_set_corked (pbuf, FALSE, FALSE))
1387             goto uncork_failed;
1388         }
1389
1390         /* we can't write a single byte, wait a bit */
1391         GST_LOG_OBJECT (psink, "waiting for free space");
1392         pa_threaded_mainloop_wait (mainloop);
1393
1394         if (pbuf->paused)
1395           goto was_paused;
1396       }
1397
1398       /* make sure we only buffer up latency-time samples */
1399       if (pbuf->m_writable > buf->spec.segsize) {
1400         /* limit buffering to latency-time value */
1401         pbuf->m_writable = buf->spec.segsize;
1402
1403         GST_LOG_OBJECT (psink, "Limiting buffering to %" G_GSIZE_FORMAT,
1404             pbuf->m_writable);
1405       }
1406
1407       GST_LOG_OBJECT (psink, "requesting %" G_GSIZE_FORMAT " bytes of "
1408           "shared memory", pbuf->m_writable);
1409
1410       if (pa_stream_begin_write (pbuf->stream, &pbuf->m_data,
1411               &pbuf->m_writable) < 0) {
1412         GST_LOG_OBJECT (psink, "pa_stream_begin_write() failed");
1413         goto writable_size_failed;
1414       }
1415
1416       GST_LOG_OBJECT (psink, "got %" G_GSIZE_FORMAT " bytes of shared memory",
1417           pbuf->m_writable);
1418
1419       /* Just to make sure that we didn't get more than requested */
1420       if (pbuf->m_writable > buf->spec.segsize) {
1421         /* limit buffering to latency-time value */
1422         pbuf->m_writable = buf->spec.segsize;
1423       }
1424     }
1425
1426     if (pbuf->m_writable < towrite)
1427       towrite = pbuf->m_writable;
1428     avail = towrite / bps;
1429
1430     GST_LOG_OBJECT (psink, "writing %u samples at offset %" G_GUINT64_FORMAT,
1431         (guint) avail, offset);
1432
1433     if (G_LIKELY (inr == outr && !reverse)) {
1434       /* no rate conversion, simply write out the samples */
1435       /* copy the data into internal buffer */
1436
1437       memcpy ((guint8 *) pbuf->m_data + pbuf->m_towrite, data, towrite);
1438       pbuf->m_towrite += towrite;
1439       pbuf->m_writable -= towrite;
1440
1441       data += towrite;
1442       in_samples -= avail;
1443       out_samples -= avail;
1444     } else {
1445       guint8 *dest, *d, *d_end;
1446
1447       /* write into the PulseAudio shm buffer */
1448       dest = d = (guint8 *) pbuf->m_data + pbuf->m_towrite;
1449       d_end = d + towrite;
1450
1451       if (!reverse) {
1452         if (inr >= outr)
1453           /* forward speed up */
1454           FWD_UP_SAMPLES (data, data_end, d, d_end);
1455         else
1456           /* forward slow down */
1457           FWD_DOWN_SAMPLES (data, data_end, d, d_end);
1458       } else {
1459         if (inr >= outr)
1460           /* reverse speed up */
1461           REV_UP_SAMPLES (data, data_end, d, d_end);
1462         else
1463           /* reverse slow down */
1464           REV_DOWN_SAMPLES (data, data_end, d, d_end);
1465       }
1466       /* see what we have left to write */
1467       towrite = (d - dest);
1468       pbuf->m_towrite += towrite;
1469       pbuf->m_writable -= towrite;
1470
1471       avail = towrite / bps;
1472     }
1473
1474     /* flush the buffer if it's full */
1475     if ((pbuf->m_data != NULL) && (pbuf->m_towrite > 0)
1476         && (pbuf->m_writable == 0)) {
1477       GST_LOG_OBJECT (psink, "flushing %u samples at offset %" G_GINT64_FORMAT,
1478           (guint) pbuf->m_towrite / bps, pbuf->m_offset);
1479
1480       if (pa_stream_write (pbuf->stream, (uint8_t *) pbuf->m_data,
1481               pbuf->m_towrite, NULL, pbuf->m_offset, PA_SEEK_ABSOLUTE) < 0) {
1482         goto write_failed;
1483       }
1484       pbuf->m_towrite = 0;
1485       pbuf->m_offset = offset + towrite;        /* keep track of current offset */
1486     }
1487 #else
1488
1489     for (;;) {
1490       /* FIXME, this is not quite right */
1491       if ((avail = pa_stream_writable_size (pbuf->stream)) == (size_t) - 1)
1492         goto writable_size_failed;
1493
1494       /* We always try to satisfy a request for data */
1495       GST_LOG_OBJECT (psink, "writable bytes %" G_GSIZE_FORMAT, avail);
1496
1497       /* convert to samples, we can only deal with multiples of the
1498        * sample size */
1499       avail /= bps;
1500
1501       if (avail > 0)
1502         break;
1503
1504       /* see if we need to uncork because we have no free space */
1505       if (pbuf->corked) {
1506         if (!gst_pulsering_set_corked (pbuf, FALSE, FALSE))
1507           goto uncork_failed;
1508       }
1509
1510       /* we can't write a single byte, wait a bit */
1511       GST_LOG_OBJECT (psink, "waiting for free space");
1512       pa_threaded_mainloop_wait (mainloop);
1513
1514       if (pbuf->paused)
1515         goto was_paused;
1516     }
1517
1518     if (avail > out_samples)
1519       avail = out_samples;
1520
1521     towrite = avail * bps;
1522
1523     GST_LOG_OBJECT (psink, "writing %u samples at offset %" G_GUINT64_FORMAT,
1524         (guint) avail, offset);
1525
1526     if (G_LIKELY (inr == outr && !reverse)) {
1527       /* no rate conversion, simply write out the samples */
1528       if (pa_stream_write (pbuf->stream, data, towrite, NULL, offset,
1529               PA_SEEK_ABSOLUTE) < 0)
1530         goto write_failed;
1531
1532       data += towrite;
1533       in_samples -= avail;
1534       out_samples -= avail;
1535     } else {
1536       guint8 *dest, *d, *d_end;
1537
1538       /* we need to allocate a temporary buffer to resample the data into,
1539        * FIXME, we should have a pulseaudio API to allocate this buffer for us
1540        * from the shared memory. */
1541       dest = d = g_malloc (towrite);
1542       d_end = d + towrite;
1543
1544       if (!reverse) {
1545         if (inr >= outr)
1546           /* forward speed up */
1547           FWD_UP_SAMPLES (data, data_end, d, d_end);
1548         else
1549           /* forward slow down */
1550           FWD_DOWN_SAMPLES (data, data_end, d, d_end);
1551       } else {
1552         if (inr >= outr)
1553           /* reverse speed up */
1554           REV_UP_SAMPLES (data, data_end, d, d_end);
1555         else
1556           /* reverse slow down */
1557           REV_DOWN_SAMPLES (data, data_end, d, d_end);
1558       }
1559       /* see what we have left to write */
1560       towrite = (d - dest);
1561       if (pa_stream_write (pbuf->stream, dest, towrite,
1562               g_free, offset, PA_SEEK_ABSOLUTE) < 0)
1563         goto write_failed;
1564
1565       avail = towrite / bps;
1566     }
1567 #endif /* HAVE_PULSE_0_9_16 */
1568
1569     *sample += avail;
1570     offset += avail * bps;
1571
1572 #ifdef HAVE_PULSE_0_9_16
1573     pbuf->m_lastoffset = offset;
1574 #endif
1575
1576     /* check if we need to uncork after writing the samples */
1577     if (pbuf->corked) {
1578       const pa_timing_info *info;
1579
1580       if ((info = pa_stream_get_timing_info (pbuf->stream))) {
1581         GST_LOG_OBJECT (psink,
1582             "read_index at %" G_GUINT64_FORMAT ", offset %" G_GINT64_FORMAT,
1583             info->read_index, offset);
1584
1585         /* we uncork when the read_index is too far behind the offset we need
1586          * to write to. */
1587         if (info->read_index + bufsize <= offset) {
1588           if (!gst_pulsering_set_corked (pbuf, FALSE, FALSE))
1589             goto uncork_failed;
1590         }
1591       } else {
1592         GST_LOG_OBJECT (psink, "no timing info available yet");
1593       }
1594     }
1595   }
1596   /* we consumed all samples here */
1597   data = data_end + bps;
1598
1599   pbuf->in_commit = FALSE;
1600   pa_threaded_mainloop_unlock (mainloop);
1601
1602 done:
1603   result = inr - ((data_end - data) / bps);
1604   GST_LOG_OBJECT (psink, "wrote %d samples", result);
1605
1606   return result;
1607
1608   /* ERRORS */
1609 unlock_and_fail:
1610   {
1611     pbuf->in_commit = FALSE;
1612     GST_LOG_OBJECT (psink, "we are reset");
1613     pa_threaded_mainloop_unlock (mainloop);
1614     goto done;
1615   }
1616 no_start:
1617   {
1618     GST_LOG_OBJECT (psink, "we can not start");
1619     return 0;
1620   }
1621 start_failed:
1622   {
1623     GST_LOG_OBJECT (psink, "failed to start the ringbuffer");
1624     return 0;
1625   }
1626 uncork_failed:
1627   {
1628     pbuf->in_commit = FALSE;
1629     GST_ERROR_OBJECT (psink, "uncork failed");
1630     pa_threaded_mainloop_unlock (mainloop);
1631     goto done;
1632   }
1633 was_paused:
1634   {
1635     pbuf->in_commit = FALSE;
1636     GST_LOG_OBJECT (psink, "we are paused");
1637     pa_threaded_mainloop_unlock (mainloop);
1638     goto done;
1639   }
1640 writable_size_failed:
1641   {
1642     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1643         ("pa_stream_writable_size() failed: %s",
1644             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1645     goto unlock_and_fail;
1646   }
1647 write_failed:
1648   {
1649     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1650         ("pa_stream_write() failed: %s",
1651             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1652     goto unlock_and_fail;
1653   }
1654 }
1655
1656 /* write pending local samples, must be called with the mainloop lock */
1657 static void
1658 gst_pulsering_flush (GstPulseRingBuffer * pbuf)
1659 {
1660 #ifdef HAVE_PULSE_0_9_16
1661   GstPulseSink *psink;
1662
1663   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1664   GST_DEBUG_OBJECT (psink, "entering flush");
1665
1666   /* flush the buffer if possible */
1667   if (pbuf->stream && (pbuf->m_data != NULL) && (pbuf->m_towrite > 0)) {
1668 #ifndef GST_DISABLE_GST_DEBUG
1669     gint bps;
1670
1671     bps = (GST_RING_BUFFER_CAST (pbuf))->spec.bytes_per_sample;
1672     GST_LOG_OBJECT (psink,
1673         "flushing %u samples at offset %" G_GINT64_FORMAT,
1674         (guint) pbuf->m_towrite / bps, pbuf->m_offset);
1675 #endif
1676
1677     if (pa_stream_write (pbuf->stream, (uint8_t *) pbuf->m_data,
1678             pbuf->m_towrite, NULL, pbuf->m_offset, PA_SEEK_ABSOLUTE) < 0) {
1679       goto write_failed;
1680     }
1681
1682     pbuf->m_towrite = 0;
1683     pbuf->m_offset += pbuf->m_towrite;  /* keep track of current offset */
1684   }
1685
1686 done:
1687   return;
1688
1689   /* ERRORS */
1690 write_failed:
1691   {
1692     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1693         ("pa_stream_write() failed: %s",
1694             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1695     goto done;
1696   }
1697 #endif
1698 }
1699
1700 static void gst_pulsesink_set_property (GObject * object, guint prop_id,
1701     const GValue * value, GParamSpec * pspec);
1702 static void gst_pulsesink_get_property (GObject * object, guint prop_id,
1703     GValue * value, GParamSpec * pspec);
1704 static void gst_pulsesink_finalize (GObject * object);
1705
1706 static gboolean gst_pulsesink_event (GstBaseSink * sink, GstEvent * event);
1707
1708 static GstStateChangeReturn gst_pulsesink_change_state (GstElement * element,
1709     GstStateChange transition);
1710
1711 #if (G_BYTE_ORDER == G_LITTLE_ENDIAN)
1712 # define ENDIANNESS   "LITTLE_ENDIAN, BIG_ENDIAN"
1713 #else
1714 # define ENDIANNESS   "BIG_ENDIAN, LITTLE_ENDIAN"
1715 #endif
1716
1717 static GstStaticPadTemplate pad_template = GST_STATIC_PAD_TEMPLATE ("sink",
1718     GST_PAD_SINK,
1719     GST_PAD_ALWAYS,
1720     GST_STATIC_CAPS ("audio/x-raw-int, "
1721         "endianness = (int) { " ENDIANNESS " }, "
1722         "signed = (boolean) TRUE, "
1723         "width = (int) 16, "
1724         "depth = (int) 16, "
1725         "rate = (int) [ 1, MAX ], "
1726         "channels = (int) [ 1, 32 ];"
1727         "audio/x-raw-float, "
1728         "endianness = (int) { " ENDIANNESS " }, "
1729         "width = (int) 32, "
1730         "rate = (int) [ 1, MAX ], "
1731         "channels = (int) [ 1, 32 ];"
1732         "audio/x-raw-int, "
1733         "endianness = (int) { " ENDIANNESS " }, "
1734         "signed = (boolean) TRUE, "
1735         "width = (int) 32, "
1736         "depth = (int) 32, "
1737         "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, 32 ];"
1738 #ifdef HAVE_PULSE_0_9_15
1739         "audio/x-raw-int, "
1740         "endianness = (int) { " ENDIANNESS " }, "
1741         "signed = (boolean) TRUE, "
1742         "width = (int) 24, "
1743         "depth = (int) 24, "
1744         "rate = (int) [ 1, MAX ], "
1745         "channels = (int) [ 1, 32 ];"
1746         "audio/x-raw-int, "
1747         "endianness = (int) { " ENDIANNESS " }, "
1748         "signed = (boolean) TRUE, "
1749         "width = (int) 32, "
1750         "depth = (int) 24, "
1751         "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, 32 ];"
1752 #endif
1753         "audio/x-raw-int, "
1754         "signed = (boolean) FALSE, "
1755         "width = (int) 8, "
1756         "depth = (int) 8, "
1757         "rate = (int) [ 1, MAX ], "
1758         "channels = (int) [ 1, 32 ];"
1759         "audio/x-alaw, "
1760         "rate = (int) [ 1, MAX], "
1761         "channels = (int) [ 1, 32 ];"
1762         "audio/x-mulaw, "
1763         "rate = (int) [ 1, MAX], " "channels = (int) [ 1, 32 ]")
1764     );
1765
1766 GST_IMPLEMENT_PULSEPROBE_METHODS (GstPulseSink, gst_pulsesink);
1767
1768 #define _do_init(type) \
1769   gst_pulsesink_init_contexts (); \
1770   gst_pulsesink_init_interfaces (type);
1771
1772 static gboolean
1773 gst_pulsesink_interface_supported (GstImplementsInterface *
1774     iface, GType interface_type)
1775 {
1776   GstPulseSink *this = GST_PULSESINK_CAST (iface);
1777
1778   if (interface_type == GST_TYPE_PROPERTY_PROBE && this->probe)
1779     return TRUE;
1780   if (interface_type == GST_TYPE_STREAM_VOLUME)
1781     return TRUE;
1782
1783   return FALSE;
1784 }
1785
1786 static void
1787 gst_pulsesink_implements_interface_init (GstImplementsInterfaceClass * klass)
1788 {
1789   klass->supported = gst_pulsesink_interface_supported;
1790 }
1791
1792 #define gst_pulsesink_parent_class parent_class
1793 G_DEFINE_TYPE_WITH_CODE (GstPulseSink, gst_pulsesink, GST_TYPE_BASE_AUDIO_SINK,
1794     gst_pulsesink_init_contexts ();
1795     G_IMPLEMENT_INTERFACE (GST_TYPE_IMPLEMENTS_INTERFACE,
1796         gst_pulsesink_implements_interface_init);
1797     G_IMPLEMENT_INTERFACE (GST_TYPE_PROPERTY_PROBE,
1798         gst_pulsesink_property_probe_interface_init);
1799 #ifdef HAVE_PULSE_0_9_12
1800     G_IMPLEMENT_INTERFACE (GST_TYPE_STREAM_VOLUME, NULL)
1801 #endif
1802     );
1803
1804 static GstRingBuffer *
1805 gst_pulsesink_create_ringbuffer (GstBaseAudioSink * sink)
1806 {
1807   GstRingBuffer *buffer;
1808
1809   GST_DEBUG_OBJECT (sink, "creating ringbuffer");
1810   buffer = g_object_new (GST_TYPE_PULSERING_BUFFER, NULL);
1811   GST_DEBUG_OBJECT (sink, "created ringbuffer @%p", buffer);
1812
1813   return buffer;
1814 }
1815
1816 static void
1817 gst_pulsesink_class_init (GstPulseSinkClass * klass)
1818 {
1819   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1820   GstBaseSinkClass *gstbasesink_class = GST_BASE_SINK_CLASS (klass);
1821   GstBaseSinkClass *bc;
1822   GstBaseAudioSinkClass *gstaudiosink_class = GST_BASE_AUDIO_SINK_CLASS (klass);
1823   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
1824
1825   gobject_class->finalize = gst_pulsesink_finalize;
1826   gobject_class->set_property = gst_pulsesink_set_property;
1827   gobject_class->get_property = gst_pulsesink_get_property;
1828
1829   gstbasesink_class->event = GST_DEBUG_FUNCPTR (gst_pulsesink_event);
1830
1831   /* restore the original basesink pull methods */
1832   bc = g_type_class_peek (GST_TYPE_BASE_SINK);
1833   gstbasesink_class->activate_pull = GST_DEBUG_FUNCPTR (bc->activate_pull);
1834
1835   gstelement_class->change_state =
1836       GST_DEBUG_FUNCPTR (gst_pulsesink_change_state);
1837
1838   gstaudiosink_class->create_ringbuffer =
1839       GST_DEBUG_FUNCPTR (gst_pulsesink_create_ringbuffer);
1840
1841   /* Overwrite GObject fields */
1842   g_object_class_install_property (gobject_class,
1843       PROP_SERVER,
1844       g_param_spec_string ("server", "Server",
1845           "The PulseAudio server to connect to", DEFAULT_SERVER,
1846           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1847
1848   g_object_class_install_property (gobject_class, PROP_DEVICE,
1849       g_param_spec_string ("device", "Device",
1850           "The PulseAudio sink device to connect to", DEFAULT_DEVICE,
1851           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1852
1853   g_object_class_install_property (gobject_class,
1854       PROP_DEVICE_NAME,
1855       g_param_spec_string ("device-name", "Device name",
1856           "Human-readable name of the sound device", DEFAULT_DEVICE_NAME,
1857           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
1858
1859 #ifdef HAVE_PULSE_0_9_12
1860   g_object_class_install_property (gobject_class,
1861       PROP_VOLUME,
1862       g_param_spec_double ("volume", "Volume",
1863           "Linear volume of this stream, 1.0=100%", 0.0, MAX_VOLUME,
1864           DEFAULT_VOLUME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1865   g_object_class_install_property (gobject_class,
1866       PROP_MUTE,
1867       g_param_spec_boolean ("mute", "Mute",
1868           "Mute state of this stream", DEFAULT_MUTE,
1869           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1870 #endif
1871
1872   /**
1873    * GstPulseSink:client
1874    *
1875    * The PulseAudio client name to use.
1876    *
1877    * Since: 0.10.25
1878    */
1879   g_object_class_install_property (gobject_class,
1880       PROP_CLIENT,
1881       g_param_spec_string ("client", "Client",
1882           "The PulseAudio client name to use", gst_pulse_client_name (),
1883           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
1884           GST_PARAM_MUTABLE_READY));
1885
1886   /**
1887    * GstPulseSink:stream-properties
1888    *
1889    * List of pulseaudio stream properties. A list of defined properties can be
1890    * found in the <ulink url="http://0pointer.de/lennart/projects/pulseaudio/doxygen/proplist_8h.html">pulseaudio api docs</ulink>.
1891    *
1892    * Below is an example for registering as a music application to pulseaudio.
1893    * |[
1894    * GstStructure *props;
1895    *
1896    * props = gst_structure_from_string ("props,media.role=music", NULL);
1897    * g_object_set (pulse, "stream-properties", props, NULL);
1898    * gst_structure_free
1899    * ]|
1900    *
1901    * Since: 0.10.26
1902    */
1903   g_object_class_install_property (gobject_class,
1904       PROP_STREAM_PROPERTIES,
1905       g_param_spec_boxed ("stream-properties", "stream properties",
1906           "list of pulseaudio stream properties",
1907           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1908
1909   gst_element_class_set_details_simple (gstelement_class,
1910       "PulseAudio Audio Sink",
1911       "Sink/Audio", "Plays audio to a PulseAudio server", "Lennart Poettering");
1912   gst_element_class_add_pad_template (gstelement_class,
1913       gst_static_pad_template_get (&pad_template));
1914 }
1915
1916 /* returns the current time of the sink ringbuffer */
1917 static GstClockTime
1918 gst_pulsesink_get_time (GstClock * clock, GstBaseAudioSink * sink)
1919 {
1920   GstPulseSink *psink;
1921   GstPulseRingBuffer *pbuf;
1922   pa_usec_t time;
1923
1924   if (!sink->ringbuffer || !sink->ringbuffer->acquired)
1925     return GST_CLOCK_TIME_NONE;
1926
1927   pbuf = GST_PULSERING_BUFFER_CAST (sink->ringbuffer);
1928   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1929
1930   pa_threaded_mainloop_lock (mainloop);
1931   if (gst_pulsering_is_dead (psink, pbuf, TRUE))
1932     goto server_dead;
1933
1934   /* if we don't have enough data to get a timestamp, just return NONE, which
1935    * will return the last reported time */
1936   if (pa_stream_get_time (pbuf->stream, &time) < 0) {
1937     GST_DEBUG_OBJECT (psink, "could not get time");
1938     time = GST_CLOCK_TIME_NONE;
1939   } else
1940     time *= 1000;
1941   pa_threaded_mainloop_unlock (mainloop);
1942
1943   GST_LOG_OBJECT (psink, "current time is %" GST_TIME_FORMAT,
1944       GST_TIME_ARGS (time));
1945
1946   return time;
1947
1948   /* ERRORS */
1949 server_dead:
1950   {
1951     GST_DEBUG_OBJECT (psink, "the server is dead");
1952     pa_threaded_mainloop_unlock (mainloop);
1953
1954     return GST_CLOCK_TIME_NONE;
1955   }
1956 }
1957
1958 static void
1959 gst_pulsesink_init (GstPulseSink * pulsesink)
1960 {
1961   pulsesink->server = NULL;
1962   pulsesink->device = NULL;
1963   pulsesink->device_description = NULL;
1964   pulsesink->client_name = gst_pulse_client_name ();
1965
1966   pulsesink->volume = DEFAULT_VOLUME;
1967   pulsesink->volume_set = FALSE;
1968
1969   pulsesink->mute = DEFAULT_MUTE;
1970   pulsesink->mute_set = FALSE;
1971
1972   pulsesink->notify = 0;
1973
1974   /* needed for conditional execution */
1975   pulsesink->pa_version = pa_get_library_version ();
1976
1977   pulsesink->properties = NULL;
1978   pulsesink->proplist = NULL;
1979
1980   GST_DEBUG_OBJECT (pulsesink, "using pulseaudio version %s",
1981       pulsesink->pa_version);
1982
1983   /* override with a custom clock */
1984   if (GST_BASE_AUDIO_SINK (pulsesink)->provided_clock)
1985     gst_object_unref (GST_BASE_AUDIO_SINK (pulsesink)->provided_clock);
1986
1987   GST_BASE_AUDIO_SINK (pulsesink)->provided_clock =
1988       gst_audio_clock_new ("GstPulseSinkClock",
1989       (GstAudioClockGetTimeFunc) gst_pulsesink_get_time, pulsesink);
1990
1991   /* TRUE for sinks, FALSE for sources */
1992   pulsesink->probe = gst_pulseprobe_new (G_OBJECT (pulsesink),
1993       G_OBJECT_GET_CLASS (pulsesink), PROP_DEVICE, pulsesink->device,
1994       TRUE, FALSE);
1995 }
1996
1997 static void
1998 gst_pulsesink_finalize (GObject * object)
1999 {
2000   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
2001
2002   g_free (pulsesink->server);
2003   g_free (pulsesink->device);
2004   g_free (pulsesink->device_description);
2005   g_free (pulsesink->client_name);
2006
2007   if (pulsesink->properties)
2008     gst_structure_free (pulsesink->properties);
2009   if (pulsesink->proplist)
2010     pa_proplist_free (pulsesink->proplist);
2011
2012   if (pulsesink->probe) {
2013     gst_pulseprobe_free (pulsesink->probe);
2014     pulsesink->probe = NULL;
2015   }
2016
2017   G_OBJECT_CLASS (parent_class)->finalize (object);
2018 }
2019
2020 #ifdef HAVE_PULSE_0_9_12
2021 static void
2022 gst_pulsesink_set_volume (GstPulseSink * psink, gdouble volume)
2023 {
2024   pa_cvolume v;
2025   pa_operation *o = NULL;
2026   GstPulseRingBuffer *pbuf;
2027   uint32_t idx;
2028
2029   if (!mainloop)
2030     goto no_mainloop;
2031
2032   pa_threaded_mainloop_lock (mainloop);
2033
2034   GST_DEBUG_OBJECT (psink, "setting volume to %f", volume);
2035
2036   pbuf = GST_PULSERING_BUFFER_CAST (GST_BASE_AUDIO_SINK (psink)->ringbuffer);
2037   if (pbuf == NULL || pbuf->stream == NULL)
2038     goto no_buffer;
2039
2040   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2041     goto no_index;
2042
2043   gst_pulse_cvolume_from_linear (&v, pbuf->sample_spec.channels, volume);
2044
2045   if (!(o = pa_context_set_sink_input_volume (pbuf->context, idx,
2046               &v, NULL, NULL)))
2047     goto volume_failed;
2048
2049   /* We don't really care about the result of this call */
2050 unlock:
2051
2052   if (o)
2053     pa_operation_unref (o);
2054
2055   pa_threaded_mainloop_unlock (mainloop);
2056
2057   return;
2058
2059   /* ERRORS */
2060 no_mainloop:
2061   {
2062     psink->volume = volume;
2063     psink->volume_set = TRUE;
2064
2065     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2066     return;
2067   }
2068 no_buffer:
2069   {
2070     psink->volume = volume;
2071     psink->volume_set = TRUE;
2072
2073     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2074     goto unlock;
2075   }
2076 no_index:
2077   {
2078     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2079     goto unlock;
2080   }
2081 volume_failed:
2082   {
2083     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2084         ("pa_stream_set_sink_input_volume() failed: %s",
2085             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2086     goto unlock;
2087   }
2088 }
2089
2090 static void
2091 gst_pulsesink_set_mute (GstPulseSink * psink, gboolean mute)
2092 {
2093   pa_operation *o = NULL;
2094   GstPulseRingBuffer *pbuf;
2095   uint32_t idx;
2096
2097   if (!mainloop)
2098     goto no_mainloop;
2099
2100   pa_threaded_mainloop_lock (mainloop);
2101
2102   GST_DEBUG_OBJECT (psink, "setting mute state to %d", mute);
2103
2104   pbuf = GST_PULSERING_BUFFER_CAST (GST_BASE_AUDIO_SINK (psink)->ringbuffer);
2105   if (pbuf == NULL || pbuf->stream == NULL)
2106     goto no_buffer;
2107
2108   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2109     goto no_index;
2110
2111   if (!(o = pa_context_set_sink_input_mute (pbuf->context, idx,
2112               mute, NULL, NULL)))
2113     goto mute_failed;
2114
2115   /* We don't really care about the result of this call */
2116 unlock:
2117
2118   if (o)
2119     pa_operation_unref (o);
2120
2121   pa_threaded_mainloop_unlock (mainloop);
2122
2123   return;
2124
2125   /* ERRORS */
2126 no_mainloop:
2127   {
2128     psink->mute = mute;
2129     psink->mute_set = TRUE;
2130
2131     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2132     return;
2133   }
2134 no_buffer:
2135   {
2136     psink->mute = mute;
2137     psink->mute_set = TRUE;
2138
2139     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2140     goto unlock;
2141   }
2142 no_index:
2143   {
2144     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2145     goto unlock;
2146   }
2147 mute_failed:
2148   {
2149     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2150         ("pa_stream_set_sink_input_mute() failed: %s",
2151             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2152     goto unlock;
2153   }
2154 }
2155
2156 static void
2157 gst_pulsesink_sink_input_info_cb (pa_context * c, const pa_sink_input_info * i,
2158     int eol, void *userdata)
2159 {
2160   GstPulseRingBuffer *pbuf;
2161   GstPulseSink *psink;
2162
2163   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
2164   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
2165
2166   if (!i)
2167     goto done;
2168
2169   if (!pbuf->stream)
2170     goto done;
2171
2172   /* If the index doesn't match our current stream,
2173    * it implies we just recreated the stream (caps change)
2174    */
2175   if (i->index == pa_stream_get_index (pbuf->stream)) {
2176     psink->volume = pa_sw_volume_to_linear (pa_cvolume_max (&i->volume));
2177     psink->mute = i->mute;
2178   }
2179
2180 done:
2181   pa_threaded_mainloop_signal (mainloop, 0);
2182 }
2183
2184 static gdouble
2185 gst_pulsesink_get_volume (GstPulseSink * psink)
2186 {
2187   GstPulseRingBuffer *pbuf;
2188   pa_operation *o = NULL;
2189   gdouble v = DEFAULT_VOLUME;
2190   uint32_t idx;
2191
2192   if (!mainloop)
2193     goto no_mainloop;
2194
2195   pa_threaded_mainloop_lock (mainloop);
2196
2197   pbuf = GST_PULSERING_BUFFER_CAST (GST_BASE_AUDIO_SINK (psink)->ringbuffer);
2198   if (pbuf == NULL || pbuf->stream == NULL)
2199     goto no_buffer;
2200
2201   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2202     goto no_index;
2203
2204   if (!(o = pa_context_get_sink_input_info (pbuf->context, idx,
2205               gst_pulsesink_sink_input_info_cb, pbuf)))
2206     goto info_failed;
2207
2208   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2209     pa_threaded_mainloop_wait (mainloop);
2210     if (gst_pulsering_is_dead (psink, pbuf, TRUE))
2211       goto unlock;
2212   }
2213
2214 unlock:
2215   v = psink->volume;
2216
2217   if (o)
2218     pa_operation_unref (o);
2219
2220   pa_threaded_mainloop_unlock (mainloop);
2221
2222   if (v > MAX_VOLUME) {
2223     GST_WARNING_OBJECT (psink, "Clipped volume from %f to %f", v, MAX_VOLUME);
2224     v = MAX_VOLUME;
2225   }
2226
2227   return v;
2228
2229   /* ERRORS */
2230 no_mainloop:
2231   {
2232     v = psink->volume;
2233     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2234     return v;
2235   }
2236 no_buffer:
2237   {
2238     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2239     goto unlock;
2240   }
2241 no_index:
2242   {
2243     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2244     goto unlock;
2245   }
2246 info_failed:
2247   {
2248     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2249         ("pa_context_get_sink_input_info() failed: %s",
2250             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2251     goto unlock;
2252   }
2253 }
2254
2255 static gboolean
2256 gst_pulsesink_get_mute (GstPulseSink * psink)
2257 {
2258   GstPulseRingBuffer *pbuf;
2259   pa_operation *o = NULL;
2260   uint32_t idx;
2261   gboolean mute = FALSE;
2262
2263   if (!mainloop)
2264     goto no_mainloop;
2265
2266   pa_threaded_mainloop_lock (mainloop);
2267   mute = psink->mute;
2268
2269   pbuf = GST_PULSERING_BUFFER_CAST (GST_BASE_AUDIO_SINK (psink)->ringbuffer);
2270   if (pbuf == NULL || pbuf->stream == NULL)
2271     goto no_buffer;
2272
2273   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2274     goto no_index;
2275
2276   if (!(o = pa_context_get_sink_input_info (pbuf->context, idx,
2277               gst_pulsesink_sink_input_info_cb, pbuf)))
2278     goto info_failed;
2279
2280   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2281     pa_threaded_mainloop_wait (mainloop);
2282     if (gst_pulsering_is_dead (psink, pbuf, TRUE))
2283       goto unlock;
2284   }
2285
2286 unlock:
2287   if (o)
2288     pa_operation_unref (o);
2289
2290   pa_threaded_mainloop_unlock (mainloop);
2291
2292   return mute;
2293
2294   /* ERRORS */
2295 no_mainloop:
2296   {
2297     mute = psink->mute;
2298     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2299     return mute;
2300   }
2301 no_buffer:
2302   {
2303     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2304     goto unlock;
2305   }
2306 no_index:
2307   {
2308     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2309     goto unlock;
2310   }
2311 info_failed:
2312   {
2313     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2314         ("pa_context_get_sink_input_info() failed: %s",
2315             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2316     goto unlock;
2317   }
2318 }
2319 #endif
2320
2321 static void
2322 gst_pulsesink_sink_info_cb (pa_context * c, const pa_sink_info * i, int eol,
2323     void *userdata)
2324 {
2325   GstPulseRingBuffer *pbuf;
2326   GstPulseSink *psink;
2327
2328   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
2329   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
2330
2331   if (!i)
2332     goto done;
2333
2334   g_free (psink->device_description);
2335   psink->device_description = g_strdup (i->description);
2336
2337 done:
2338   pa_threaded_mainloop_signal (mainloop, 0);
2339 }
2340
2341 static gchar *
2342 gst_pulsesink_device_description (GstPulseSink * psink)
2343 {
2344   GstPulseRingBuffer *pbuf;
2345   pa_operation *o = NULL;
2346   gchar *t;
2347
2348   if (!mainloop)
2349     goto no_mainloop;
2350
2351   pa_threaded_mainloop_lock (mainloop);
2352   pbuf = GST_PULSERING_BUFFER_CAST (GST_BASE_AUDIO_SINK (psink)->ringbuffer);
2353   if (pbuf == NULL)
2354     goto no_buffer;
2355
2356   if (!(o = pa_context_get_sink_info_by_name (pbuf->context,
2357               psink->device, gst_pulsesink_sink_info_cb, pbuf)))
2358     goto info_failed;
2359
2360   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2361     pa_threaded_mainloop_wait (mainloop);
2362     if (gst_pulsering_is_dead (psink, pbuf, FALSE))
2363       goto unlock;
2364   }
2365
2366 unlock:
2367   if (o)
2368     pa_operation_unref (o);
2369
2370   t = g_strdup (psink->device_description);
2371   pa_threaded_mainloop_unlock (mainloop);
2372
2373   return t;
2374
2375   /* ERRORS */
2376 no_mainloop:
2377   {
2378     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2379     return NULL;
2380   }
2381 no_buffer:
2382   {
2383     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2384     goto unlock;
2385   }
2386 info_failed:
2387   {
2388     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2389         ("pa_context_get_sink_info_by_index() failed: %s",
2390             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2391     goto unlock;
2392   }
2393 }
2394
2395 static void
2396 gst_pulsesink_set_property (GObject * object,
2397     guint prop_id, const GValue * value, GParamSpec * pspec)
2398 {
2399   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
2400
2401   switch (prop_id) {
2402     case PROP_SERVER:
2403       g_free (pulsesink->server);
2404       pulsesink->server = g_value_dup_string (value);
2405       if (pulsesink->probe)
2406         gst_pulseprobe_set_server (pulsesink->probe, pulsesink->server);
2407       break;
2408     case PROP_DEVICE:
2409       g_free (pulsesink->device);
2410       pulsesink->device = g_value_dup_string (value);
2411       break;
2412 #ifdef HAVE_PULSE_0_9_12
2413     case PROP_VOLUME:
2414       gst_pulsesink_set_volume (pulsesink, g_value_get_double (value));
2415       break;
2416     case PROP_MUTE:
2417       gst_pulsesink_set_mute (pulsesink, g_value_get_boolean (value));
2418       break;
2419 #endif
2420     case PROP_CLIENT:
2421       g_free (pulsesink->client_name);
2422       if (!g_value_get_string (value)) {
2423         GST_WARNING_OBJECT (pulsesink,
2424             "Empty PulseAudio client name not allowed. Resetting to default value");
2425         pulsesink->client_name = gst_pulse_client_name ();
2426       } else
2427         pulsesink->client_name = g_value_dup_string (value);
2428       break;
2429     case PROP_STREAM_PROPERTIES:
2430       if (pulsesink->properties)
2431         gst_structure_free (pulsesink->properties);
2432       pulsesink->properties =
2433           gst_structure_copy (gst_value_get_structure (value));
2434       if (pulsesink->proplist)
2435         pa_proplist_free (pulsesink->proplist);
2436       pulsesink->proplist = gst_pulse_make_proplist (pulsesink->properties);
2437       break;
2438     default:
2439       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2440       break;
2441   }
2442 }
2443
2444 static void
2445 gst_pulsesink_get_property (GObject * object,
2446     guint prop_id, GValue * value, GParamSpec * pspec)
2447 {
2448
2449   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
2450
2451   switch (prop_id) {
2452     case PROP_SERVER:
2453       g_value_set_string (value, pulsesink->server);
2454       break;
2455     case PROP_DEVICE:
2456       g_value_set_string (value, pulsesink->device);
2457       break;
2458     case PROP_DEVICE_NAME:
2459       g_value_take_string (value, gst_pulsesink_device_description (pulsesink));
2460       break;
2461 #ifdef HAVE_PULSE_0_9_12
2462     case PROP_VOLUME:
2463       g_value_set_double (value, gst_pulsesink_get_volume (pulsesink));
2464       break;
2465     case PROP_MUTE:
2466       g_value_set_boolean (value, gst_pulsesink_get_mute (pulsesink));
2467       break;
2468 #endif
2469     case PROP_CLIENT:
2470       g_value_set_string (value, pulsesink->client_name);
2471       break;
2472     case PROP_STREAM_PROPERTIES:
2473       gst_value_set_structure (value, pulsesink->properties);
2474       break;
2475     default:
2476       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2477       break;
2478   }
2479 }
2480
2481 static void
2482 gst_pulsesink_change_title (GstPulseSink * psink, const gchar * t)
2483 {
2484   pa_operation *o = NULL;
2485   GstPulseRingBuffer *pbuf;
2486
2487   pa_threaded_mainloop_lock (mainloop);
2488
2489   pbuf = GST_PULSERING_BUFFER_CAST (GST_BASE_AUDIO_SINK (psink)->ringbuffer);
2490
2491   if (pbuf == NULL || pbuf->stream == NULL)
2492     goto no_buffer;
2493
2494   g_free (pbuf->stream_name);
2495   pbuf->stream_name = g_strdup (t);
2496
2497   if (!(o = pa_stream_set_name (pbuf->stream, pbuf->stream_name, NULL, NULL)))
2498     goto name_failed;
2499
2500   /* We're not interested if this operation failed or not */
2501 unlock:
2502
2503   if (o)
2504     pa_operation_unref (o);
2505   pa_threaded_mainloop_unlock (mainloop);
2506
2507   return;
2508
2509   /* ERRORS */
2510 no_buffer:
2511   {
2512     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2513     goto unlock;
2514   }
2515 name_failed:
2516   {
2517     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2518         ("pa_stream_set_name() failed: %s",
2519             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2520     goto unlock;
2521   }
2522 }
2523
2524 #ifdef HAVE_PULSE_0_9_11
2525 static void
2526 gst_pulsesink_change_props (GstPulseSink * psink, GstTagList * l)
2527 {
2528   static const gchar *const map[] = {
2529     GST_TAG_TITLE, PA_PROP_MEDIA_TITLE,
2530
2531     /* might get overriden in the next iteration by GST_TAG_ARTIST */
2532     GST_TAG_PERFORMER, PA_PROP_MEDIA_ARTIST,
2533
2534     GST_TAG_ARTIST, PA_PROP_MEDIA_ARTIST,
2535     GST_TAG_LANGUAGE_CODE, PA_PROP_MEDIA_LANGUAGE,
2536     GST_TAG_LOCATION, PA_PROP_MEDIA_FILENAME,
2537     /* We might add more here later on ... */
2538     NULL
2539   };
2540   pa_proplist *pl = NULL;
2541   const gchar *const *t;
2542   gboolean empty = TRUE;
2543   pa_operation *o = NULL;
2544   GstPulseRingBuffer *pbuf;
2545
2546   pl = pa_proplist_new ();
2547
2548   for (t = map; *t; t += 2) {
2549     gchar *n = NULL;
2550
2551     if (gst_tag_list_get_string (l, *t, &n)) {
2552
2553       if (n && *n) {
2554         pa_proplist_sets (pl, *(t + 1), n);
2555         empty = FALSE;
2556       }
2557
2558       g_free (n);
2559     }
2560   }
2561   if (empty)
2562     goto finish;
2563
2564   pa_threaded_mainloop_lock (mainloop);
2565   pbuf = GST_PULSERING_BUFFER_CAST (GST_BASE_AUDIO_SINK (psink)->ringbuffer);
2566   if (pbuf == NULL || pbuf->stream == NULL)
2567     goto no_buffer;
2568
2569   if (!(o = pa_stream_proplist_update (pbuf->stream, PA_UPDATE_REPLACE,
2570               pl, NULL, NULL)))
2571     goto update_failed;
2572
2573   /* We're not interested if this operation failed or not */
2574 unlock:
2575
2576   if (o)
2577     pa_operation_unref (o);
2578
2579   pa_threaded_mainloop_unlock (mainloop);
2580
2581 finish:
2582
2583   if (pl)
2584     pa_proplist_free (pl);
2585
2586   return;
2587
2588   /* ERRORS */
2589 no_buffer:
2590   {
2591     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2592     goto unlock;
2593   }
2594 update_failed:
2595   {
2596     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2597         ("pa_stream_proplist_update() failed: %s",
2598             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2599     goto unlock;
2600   }
2601 }
2602 #endif
2603
2604 static void
2605 gst_pulsesink_flush_ringbuffer (GstPulseSink * psink)
2606 {
2607   GstPulseRingBuffer *pbuf;
2608
2609   pa_threaded_mainloop_lock (mainloop);
2610
2611   pbuf = GST_PULSERING_BUFFER_CAST (GST_BASE_AUDIO_SINK (psink)->ringbuffer);
2612
2613   if (pbuf == NULL || pbuf->stream == NULL)
2614     goto no_buffer;
2615
2616   gst_pulsering_flush (pbuf);
2617
2618   /* Uncork if we haven't already (happens when waiting to get enough data
2619    * to send out the first time) */
2620   if (pbuf->corked)
2621     gst_pulsering_set_corked (pbuf, FALSE, FALSE);
2622
2623   /* We're not interested if this operation failed or not */
2624 unlock:
2625   pa_threaded_mainloop_unlock (mainloop);
2626
2627   return;
2628
2629   /* ERRORS */
2630 no_buffer:
2631   {
2632     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2633     goto unlock;
2634   }
2635 }
2636
2637 static gboolean
2638 gst_pulsesink_event (GstBaseSink * sink, GstEvent * event)
2639 {
2640   GstPulseSink *pulsesink = GST_PULSESINK_CAST (sink);
2641
2642   switch (GST_EVENT_TYPE (event)) {
2643     case GST_EVENT_TAG:{
2644       gchar *title = NULL, *artist = NULL, *location = NULL, *description =
2645           NULL, *t = NULL, *buf = NULL;
2646       GstTagList *l;
2647
2648       gst_event_parse_tag (event, &l);
2649
2650       gst_tag_list_get_string (l, GST_TAG_TITLE, &title);
2651       gst_tag_list_get_string (l, GST_TAG_ARTIST, &artist);
2652       gst_tag_list_get_string (l, GST_TAG_LOCATION, &location);
2653       gst_tag_list_get_string (l, GST_TAG_DESCRIPTION, &description);
2654
2655       if (!artist)
2656         gst_tag_list_get_string (l, GST_TAG_PERFORMER, &artist);
2657
2658       if (title && artist)
2659         /* TRANSLATORS: 'song title' by 'artist name' */
2660         t = buf = g_strdup_printf (_("'%s' by '%s'"), g_strstrip (title),
2661             g_strstrip (artist));
2662       else if (title)
2663         t = g_strstrip (title);
2664       else if (description)
2665         t = g_strstrip (description);
2666       else if (location)
2667         t = g_strstrip (location);
2668
2669       if (t)
2670         gst_pulsesink_change_title (pulsesink, t);
2671
2672       g_free (title);
2673       g_free (artist);
2674       g_free (location);
2675       g_free (description);
2676       g_free (buf);
2677
2678 #ifdef HAVE_PULSE_0_9_11
2679       gst_pulsesink_change_props (pulsesink, l);
2680 #endif
2681
2682       break;
2683     }
2684     case GST_EVENT_EOS:
2685       gst_pulsesink_flush_ringbuffer (pulsesink);
2686       break;
2687     default:
2688       ;
2689   }
2690
2691   return GST_BASE_SINK_CLASS (parent_class)->event (sink, event);
2692 }
2693
2694 static GstStateChangeReturn
2695 gst_pulsesink_change_state (GstElement * element, GstStateChange transition)
2696 {
2697   GstPulseSink *pulsesink = GST_PULSESINK (element);
2698   GstStateChangeReturn ret;
2699
2700   switch (transition) {
2701     case GST_STATE_CHANGE_NULL_TO_READY:
2702       g_mutex_lock (pa_shared_resource_mutex);
2703       if (!mainloop_ref_ct) {
2704         GST_INFO_OBJECT (element, "new pa main loop thread");
2705         if (!(mainloop = pa_threaded_mainloop_new ()))
2706           goto mainloop_failed;
2707         mainloop_ref_ct = 1;
2708         pa_threaded_mainloop_start (mainloop);
2709         g_mutex_unlock (pa_shared_resource_mutex);
2710       } else {
2711         GST_INFO_OBJECT (element, "reusing pa main loop thread");
2712         mainloop_ref_ct++;
2713         g_mutex_unlock (pa_shared_resource_mutex);
2714       }
2715       break;
2716     case GST_STATE_CHANGE_READY_TO_PAUSED:
2717       gst_element_post_message (element,
2718           gst_message_new_clock_provide (GST_OBJECT_CAST (element),
2719               GST_BASE_AUDIO_SINK (pulsesink)->provided_clock, TRUE));
2720       break;
2721     default:
2722       break;
2723   }
2724
2725   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2726   if (ret == GST_STATE_CHANGE_FAILURE)
2727     goto state_failure;
2728
2729   switch (transition) {
2730     case GST_STATE_CHANGE_PAUSED_TO_READY:
2731       gst_element_post_message (element,
2732           gst_message_new_clock_lost (GST_OBJECT_CAST (element),
2733               GST_BASE_AUDIO_SINK (pulsesink)->provided_clock));
2734       break;
2735     case GST_STATE_CHANGE_READY_TO_NULL:
2736       if (mainloop) {
2737         g_mutex_lock (pa_shared_resource_mutex);
2738         mainloop_ref_ct--;
2739         if (!mainloop_ref_ct) {
2740           GST_INFO_OBJECT (element, "terminating pa main loop thread");
2741           pa_threaded_mainloop_stop (mainloop);
2742           pa_threaded_mainloop_free (mainloop);
2743           mainloop = NULL;
2744         }
2745         g_mutex_unlock (pa_shared_resource_mutex);
2746       }
2747       break;
2748     default:
2749       break;
2750   }
2751
2752   return ret;
2753
2754   /* ERRORS */
2755 mainloop_failed:
2756   {
2757     g_mutex_unlock (pa_shared_resource_mutex);
2758     GST_ELEMENT_ERROR (pulsesink, RESOURCE, FAILED,
2759         ("pa_threaded_mainloop_new() failed"), (NULL));
2760     return GST_STATE_CHANGE_FAILURE;
2761   }
2762 state_failure:
2763   {
2764     if (transition == GST_STATE_CHANGE_NULL_TO_READY) {
2765       /* Clear the PA mainloop if baseaudiosink failed to open the ring_buffer */
2766       g_assert (mainloop);
2767       g_mutex_lock (pa_shared_resource_mutex);
2768       mainloop_ref_ct--;
2769       if (!mainloop_ref_ct) {
2770         GST_INFO_OBJECT (element, "terminating pa main loop thread");
2771         pa_threaded_mainloop_stop (mainloop);
2772         pa_threaded_mainloop_free (mainloop);
2773         mainloop = NULL;
2774       }
2775       g_mutex_unlock (pa_shared_resource_mutex);
2776     }
2777     return ret;
2778   }
2779 }