Moving lame mp3 encoder plugin from -ugly
[platform/upstream/gst-plugins-good.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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
21  *  USA.
22  */
23
24 /**
25  * SECTION:element-pulsesink
26  * @see_also: pulsesrc
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-1.0 -v filesrc location=sine.ogg ! oggdemux ! vorbisdec ! audioconvert ! audioresample ! pulsesink
35  * ]| Play an Ogg/Vorbis file.
36  * |[
37  * gst-launch-1.0 -v audiotestsrc ! audioconvert ! volume volume=0.4 ! pulsesink
38  * ]| Play a 440Hz sine wave.
39  * |[
40  * gst-launch-1.0 -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/audio/audio.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 <gst/glib-compat-private.h>
61
62 #include "pulsesink.h"
63 #include "pulseutil.h"
64
65 GST_DEBUG_CATEGORY_EXTERN (pulse_debug);
66 #define GST_CAT_DEFAULT pulse_debug
67
68 #define DEFAULT_SERVER          NULL
69 #define DEFAULT_DEVICE          NULL
70 #define DEFAULT_CURRENT_DEVICE  NULL
71 #define DEFAULT_DEVICE_NAME     NULL
72 #define DEFAULT_VOLUME          1.0
73 #define DEFAULT_MUTE            FALSE
74 #define MAX_VOLUME              10.0
75
76 enum
77 {
78   PROP_0,
79   PROP_SERVER,
80   PROP_DEVICE,
81   PROP_CURRENT_DEVICE,
82   PROP_DEVICE_NAME,
83   PROP_VOLUME,
84   PROP_MUTE,
85   PROP_CLIENT_NAME,
86   PROP_STREAM_PROPERTIES,
87   PROP_LAST
88 };
89
90 #define GST_TYPE_PULSERING_BUFFER        \
91         (gst_pulseringbuffer_get_type())
92 #define GST_PULSERING_BUFFER(obj)        \
93         (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_PULSERING_BUFFER,GstPulseRingBuffer))
94 #define GST_PULSERING_BUFFER_CLASS(klass) \
95         (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_PULSERING_BUFFER,GstPulseRingBufferClass))
96 #define GST_PULSERING_BUFFER_GET_CLASS(obj) \
97         (G_TYPE_INSTANCE_GET_CLASS ((obj), GST_TYPE_PULSERING_BUFFER, GstPulseRingBufferClass))
98 #define GST_PULSERING_BUFFER_CAST(obj)        \
99         ((GstPulseRingBuffer *)obj)
100 #define GST_IS_PULSERING_BUFFER(obj)     \
101         (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_PULSERING_BUFFER))
102 #define GST_IS_PULSERING_BUFFER_CLASS(klass)\
103         (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_PULSERING_BUFFER))
104
105 typedef struct _GstPulseRingBuffer GstPulseRingBuffer;
106 typedef struct _GstPulseRingBufferClass GstPulseRingBufferClass;
107
108 typedef struct _GstPulseContext GstPulseContext;
109
110 /* A note on threading.
111  *
112  * We use a pa_threaded_mainloop to interact with the PulseAudio server. This
113  * starts up a separate thread that runs a mainloop to carry back events,
114  * messages and timing updates from the PulseAudio server.
115  *
116  * In most cases, the PulseAudio API we use communicates with the server and
117  * processes replies asynchronously. Operations on PA objects that result in
118  * such communication are protected with a pa_threaded_mainloop_lock() and
119  * pa_threaded_mainloop_unlock(). These guarantee mutual exclusion with the
120  * mainloop thread -- when an iteration of the mainloop thread begins, it first
121  * tries to acquire this lock, and cannot do so if our code also holds that
122  * lock.
123  *
124  * When we need to complete an operation synchronously, we use
125  * pa_threaded_mainloop_wait() and pa_threaded_mainloop_signal(). These work
126  * much as pthread conditionals do. pa_threaded_mainloop_wait() is called with
127  * the mainloop lock held. It releases the lock (thereby allowing the mainloop
128  * to execute), and waits till one of our callbacks to be executed by the
129  * mainloop thread calls pa_threaded_mainloop_signal(). At the end of the
130  * mainloop iteration, the pa_threaded_mainloop_wait() will reacquire the
131  * mainloop lock and return control to the caller.
132  */
133
134 /* Store the PA contexts in a hash table to allow easy sharing among
135  * multiple instances of the sink. Keys are $context_name@$server_name
136  * (strings) and values should be GstPulseContext pointers.
137  */
138 struct _GstPulseContext
139 {
140   pa_context *context;
141   GSList *ring_buffers;
142 };
143
144 static GHashTable *gst_pulse_shared_contexts = NULL;
145
146 /* use one static main-loop for all instances
147  * this is needed to make the context sharing work as the contexts are
148  * released when releasing their parent main-loop
149  */
150 static pa_threaded_mainloop *mainloop = NULL;
151 static guint mainloop_ref_ct = 0;
152
153 /* lock for access to shared resources */
154 static GMutex pa_shared_resource_mutex;
155
156 /* We keep a custom ringbuffer that is backed up by data allocated by
157  * pulseaudio. We must also overide the commit function to write into
158  * pulseaudio memory instead. */
159 struct _GstPulseRingBuffer
160 {
161   GstAudioRingBuffer object;
162
163   gchar *context_name;
164   gchar *stream_name;
165
166   pa_context *context;
167   pa_stream *stream;
168   pa_stream *probe_stream;
169
170   pa_format_info *format;
171   guint channels;
172   gboolean is_pcm;
173
174   void *m_data;
175   size_t m_towrite;
176   size_t m_writable;
177   gint64 m_offset;
178   gint64 m_lastoffset;
179
180   gboolean corked:1;
181   gboolean in_commit:1;
182   gboolean paused:1;
183 };
184 struct _GstPulseRingBufferClass
185 {
186   GstAudioRingBufferClass parent_class;
187 };
188
189 static GType gst_pulseringbuffer_get_type (void);
190 static void gst_pulseringbuffer_finalize (GObject * object);
191
192 static GstAudioRingBufferClass *ring_parent_class = NULL;
193
194 static gboolean gst_pulseringbuffer_open_device (GstAudioRingBuffer * buf);
195 static gboolean gst_pulseringbuffer_close_device (GstAudioRingBuffer * buf);
196 static gboolean gst_pulseringbuffer_acquire (GstAudioRingBuffer * buf,
197     GstAudioRingBufferSpec * spec);
198 static gboolean gst_pulseringbuffer_release (GstAudioRingBuffer * buf);
199 static gboolean gst_pulseringbuffer_start (GstAudioRingBuffer * buf);
200 static gboolean gst_pulseringbuffer_pause (GstAudioRingBuffer * buf);
201 static gboolean gst_pulseringbuffer_stop (GstAudioRingBuffer * buf);
202 static void gst_pulseringbuffer_clear (GstAudioRingBuffer * buf);
203 static guint gst_pulseringbuffer_commit (GstAudioRingBuffer * buf,
204     guint64 * sample, guchar * data, gint in_samples, gint out_samples,
205     gint * accum);
206
207 G_DEFINE_TYPE (GstPulseRingBuffer, gst_pulseringbuffer,
208     GST_TYPE_AUDIO_RING_BUFFER);
209
210 static void
211 gst_pulsesink_init_contexts (void)
212 {
213   g_mutex_init (&pa_shared_resource_mutex);
214   gst_pulse_shared_contexts = g_hash_table_new_full (g_str_hash, g_str_equal,
215       g_free, NULL);
216 }
217
218 static void
219 gst_pulseringbuffer_class_init (GstPulseRingBufferClass * klass)
220 {
221   GObjectClass *gobject_class;
222   GstAudioRingBufferClass *gstringbuffer_class;
223
224   gobject_class = (GObjectClass *) klass;
225   gstringbuffer_class = (GstAudioRingBufferClass *) klass;
226
227   ring_parent_class = g_type_class_peek_parent (klass);
228
229   gobject_class->finalize = gst_pulseringbuffer_finalize;
230
231   gstringbuffer_class->open_device =
232       GST_DEBUG_FUNCPTR (gst_pulseringbuffer_open_device);
233   gstringbuffer_class->close_device =
234       GST_DEBUG_FUNCPTR (gst_pulseringbuffer_close_device);
235   gstringbuffer_class->acquire =
236       GST_DEBUG_FUNCPTR (gst_pulseringbuffer_acquire);
237   gstringbuffer_class->release =
238       GST_DEBUG_FUNCPTR (gst_pulseringbuffer_release);
239   gstringbuffer_class->start = GST_DEBUG_FUNCPTR (gst_pulseringbuffer_start);
240   gstringbuffer_class->pause = GST_DEBUG_FUNCPTR (gst_pulseringbuffer_pause);
241   gstringbuffer_class->resume = GST_DEBUG_FUNCPTR (gst_pulseringbuffer_start);
242   gstringbuffer_class->stop = GST_DEBUG_FUNCPTR (gst_pulseringbuffer_stop);
243   gstringbuffer_class->clear_all =
244       GST_DEBUG_FUNCPTR (gst_pulseringbuffer_clear);
245
246   gstringbuffer_class->commit = GST_DEBUG_FUNCPTR (gst_pulseringbuffer_commit);
247 }
248
249 static void
250 gst_pulseringbuffer_init (GstPulseRingBuffer * pbuf)
251 {
252   pbuf->stream_name = NULL;
253   pbuf->context = NULL;
254   pbuf->stream = NULL;
255   pbuf->probe_stream = NULL;
256
257   pbuf->format = NULL;
258   pbuf->channels = 0;
259   pbuf->is_pcm = FALSE;
260
261   pbuf->m_data = NULL;
262   pbuf->m_towrite = 0;
263   pbuf->m_writable = 0;
264   pbuf->m_offset = 0;
265   pbuf->m_lastoffset = 0;
266
267   pbuf->corked = TRUE;
268   pbuf->in_commit = FALSE;
269   pbuf->paused = FALSE;
270 }
271
272 /* Call with mainloop lock held if wait == TRUE) */
273 static void
274 gst_pulse_destroy_stream (pa_stream * stream, gboolean wait)
275 {
276   /* Make sure we don't get any further callbacks */
277   pa_stream_set_write_callback (stream, NULL, NULL);
278   pa_stream_set_underflow_callback (stream, NULL, NULL);
279   pa_stream_set_overflow_callback (stream, NULL, NULL);
280
281   pa_stream_disconnect (stream);
282
283   if (wait)
284     pa_threaded_mainloop_wait (mainloop);
285
286   pa_stream_set_state_callback (stream, NULL, NULL);
287   pa_stream_unref (stream);
288 }
289
290 static void
291 gst_pulsering_destroy_stream (GstPulseRingBuffer * pbuf)
292 {
293   if (pbuf->probe_stream) {
294     gst_pulse_destroy_stream (pbuf->probe_stream, FALSE);
295     pbuf->probe_stream = NULL;
296   }
297
298   if (pbuf->stream) {
299
300     if (pbuf->m_data) {
301       /* drop shm memory buffer */
302       pa_stream_cancel_write (pbuf->stream);
303
304       /* reset internal variables */
305       pbuf->m_data = NULL;
306       pbuf->m_towrite = 0;
307       pbuf->m_writable = 0;
308       pbuf->m_offset = 0;
309       pbuf->m_lastoffset = 0;
310     }
311     if (pbuf->format) {
312       pa_format_info_free (pbuf->format);
313       pbuf->format = NULL;
314       pbuf->channels = 0;
315       pbuf->is_pcm = FALSE;
316     }
317
318     pa_stream_disconnect (pbuf->stream);
319
320     /* Make sure we don't get any further callbacks */
321     pa_stream_set_state_callback (pbuf->stream, NULL, NULL);
322     pa_stream_set_write_callback (pbuf->stream, NULL, NULL);
323     pa_stream_set_underflow_callback (pbuf->stream, NULL, NULL);
324     pa_stream_set_overflow_callback (pbuf->stream, NULL, NULL);
325
326     pa_stream_unref (pbuf->stream);
327     pbuf->stream = NULL;
328   }
329
330   g_free (pbuf->stream_name);
331   pbuf->stream_name = NULL;
332 }
333
334 static void
335 gst_pulsering_destroy_context (GstPulseRingBuffer * pbuf)
336 {
337   g_mutex_lock (&pa_shared_resource_mutex);
338
339   GST_DEBUG_OBJECT (pbuf, "destroying ringbuffer %p", pbuf);
340
341   gst_pulsering_destroy_stream (pbuf);
342
343   if (pbuf->context) {
344     pa_context_unref (pbuf->context);
345     pbuf->context = NULL;
346   }
347
348   if (pbuf->context_name) {
349     GstPulseContext *pctx;
350
351     pctx = g_hash_table_lookup (gst_pulse_shared_contexts, pbuf->context_name);
352
353     GST_DEBUG_OBJECT (pbuf, "releasing context with name %s, pbuf=%p, pctx=%p",
354         pbuf->context_name, pbuf, pctx);
355
356     if (pctx) {
357       pctx->ring_buffers = g_slist_remove (pctx->ring_buffers, pbuf);
358       if (pctx->ring_buffers == NULL) {
359         GST_DEBUG_OBJECT (pbuf,
360             "destroying final context with name %s, pbuf=%p, pctx=%p",
361             pbuf->context_name, pbuf, pctx);
362
363         pa_context_disconnect (pctx->context);
364
365         /* Make sure we don't get any further callbacks */
366         pa_context_set_state_callback (pctx->context, NULL, NULL);
367         pa_context_set_subscribe_callback (pctx->context, NULL, NULL);
368
369         g_hash_table_remove (gst_pulse_shared_contexts, pbuf->context_name);
370
371         pa_context_unref (pctx->context);
372         g_slice_free (GstPulseContext, pctx);
373       }
374     }
375     g_free (pbuf->context_name);
376     pbuf->context_name = NULL;
377   }
378   g_mutex_unlock (&pa_shared_resource_mutex);
379 }
380
381 static void
382 gst_pulseringbuffer_finalize (GObject * object)
383 {
384   GstPulseRingBuffer *ringbuffer;
385
386   ringbuffer = GST_PULSERING_BUFFER_CAST (object);
387
388   gst_pulsering_destroy_context (ringbuffer);
389   G_OBJECT_CLASS (ring_parent_class)->finalize (object);
390 }
391
392
393 #define CONTEXT_OK(c) ((c) && PA_CONTEXT_IS_GOOD (pa_context_get_state ((c))))
394 #define STREAM_OK(s) ((s) && PA_STREAM_IS_GOOD (pa_stream_get_state ((s))))
395
396 static gboolean
397 gst_pulsering_is_dead (GstPulseSink * psink, GstPulseRingBuffer * pbuf,
398     gboolean check_stream)
399 {
400   if (!CONTEXT_OK (pbuf->context))
401     goto error;
402
403   if (check_stream && !STREAM_OK (pbuf->stream))
404     goto error;
405
406   return FALSE;
407
408 error:
409   {
410     const gchar *err_str =
411         pbuf->context ? pa_strerror (pa_context_errno (pbuf->context)) : NULL;
412     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED, ("Disconnected: %s",
413             err_str), (NULL));
414     return TRUE;
415   }
416 }
417
418 static void
419 gst_pulsering_context_state_cb (pa_context * c, void *userdata)
420 {
421   pa_context_state_t state;
422   pa_threaded_mainloop *mainloop = (pa_threaded_mainloop *) userdata;
423
424   state = pa_context_get_state (c);
425
426   GST_LOG ("got new context state %d", state);
427
428   switch (state) {
429     case PA_CONTEXT_READY:
430     case PA_CONTEXT_TERMINATED:
431     case PA_CONTEXT_FAILED:
432       GST_LOG ("signaling");
433       pa_threaded_mainloop_signal (mainloop, 0);
434       break;
435
436     case PA_CONTEXT_UNCONNECTED:
437     case PA_CONTEXT_CONNECTING:
438     case PA_CONTEXT_AUTHORIZING:
439     case PA_CONTEXT_SETTING_NAME:
440       break;
441   }
442 }
443
444 static void
445 gst_pulsering_context_subscribe_cb (pa_context * c,
446     pa_subscription_event_type_t t, uint32_t idx, void *userdata)
447 {
448   GstPulseSink *psink;
449   GstPulseContext *pctx = (GstPulseContext *) userdata;
450   GSList *walk;
451
452   if (t != (PA_SUBSCRIPTION_EVENT_SINK_INPUT | PA_SUBSCRIPTION_EVENT_CHANGE) &&
453       t != (PA_SUBSCRIPTION_EVENT_SINK_INPUT | PA_SUBSCRIPTION_EVENT_NEW))
454     return;
455
456   for (walk = pctx->ring_buffers; walk; walk = g_slist_next (walk)) {
457     GstPulseRingBuffer *pbuf = (GstPulseRingBuffer *) walk->data;
458     psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
459
460     GST_LOG_OBJECT (psink, "type %04x, idx %u", t, idx);
461
462     if (!pbuf->stream)
463       continue;
464
465     if (idx != pa_stream_get_index (pbuf->stream))
466       continue;
467
468     if (psink->device && pbuf->is_pcm &&
469         !g_str_equal (psink->device,
470             pa_stream_get_device_name (pbuf->stream))) {
471       /* Underlying sink changed. And this is not a passthrough stream. Let's
472        * see if someone upstream wants to try to renegotiate. */
473       GstEvent *renego;
474
475       g_free (psink->device);
476       psink->device = g_strdup (pa_stream_get_device_name (pbuf->stream));
477
478       GST_INFO_OBJECT (psink, "emitting sink-changed");
479
480       /* FIXME: send reconfigure event instead and let decodebin/playbin
481        * handle that. Also take care of ac3 alignment. See "pulse-format-lost" */
482       renego = gst_event_new_custom (GST_EVENT_CUSTOM_UPSTREAM,
483           gst_structure_new_empty ("pulse-sink-changed"));
484
485       if (!gst_pad_push_event (GST_BASE_SINK (psink)->sinkpad, renego))
486         GST_DEBUG_OBJECT (psink, "Emitted sink-changed - nobody was listening");
487     }
488
489     /* Actually this event is also triggered when other properties of
490      * the stream change that are unrelated to the volume. However it is
491      * probably cheaper to signal the change here and check for the
492      * volume when the GObject property is read instead of querying it always. */
493
494     /* inform streaming thread to notify */
495     g_atomic_int_compare_and_exchange (&psink->notify, 0, 1);
496   }
497 }
498
499 /* will be called when the device should be opened. In this case we will connect
500  * to the server. We should not try to open any streams in this state. */
501 static gboolean
502 gst_pulseringbuffer_open_device (GstAudioRingBuffer * buf)
503 {
504   GstPulseSink *psink;
505   GstPulseRingBuffer *pbuf;
506   GstPulseContext *pctx;
507   pa_mainloop_api *api;
508   gboolean need_unlock_shared;
509
510   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (buf));
511   pbuf = GST_PULSERING_BUFFER_CAST (buf);
512
513   g_assert (!pbuf->stream);
514   g_assert (psink->client_name);
515
516   if (psink->server)
517     pbuf->context_name = g_strdup_printf ("%s@%s", psink->client_name,
518         psink->server);
519   else
520     pbuf->context_name = g_strdup (psink->client_name);
521
522   pa_threaded_mainloop_lock (mainloop);
523
524   g_mutex_lock (&pa_shared_resource_mutex);
525   need_unlock_shared = TRUE;
526
527   pctx = g_hash_table_lookup (gst_pulse_shared_contexts, pbuf->context_name);
528   if (pctx == NULL) {
529     pctx = g_slice_new0 (GstPulseContext);
530
531     /* get the mainloop api and create a context */
532     GST_INFO_OBJECT (psink, "new context with name %s, pbuf=%p, pctx=%p",
533         pbuf->context_name, pbuf, pctx);
534     api = pa_threaded_mainloop_get_api (mainloop);
535     if (!(pctx->context = pa_context_new (api, pbuf->context_name)))
536       goto create_failed;
537
538     pctx->ring_buffers = g_slist_prepend (pctx->ring_buffers, pbuf);
539     g_hash_table_insert (gst_pulse_shared_contexts,
540         g_strdup (pbuf->context_name), (gpointer) pctx);
541     /* register some essential callbacks */
542     pa_context_set_state_callback (pctx->context,
543         gst_pulsering_context_state_cb, mainloop);
544     pa_context_set_subscribe_callback (pctx->context,
545         gst_pulsering_context_subscribe_cb, pctx);
546
547     /* try to connect to the server and wait for completion, we don't want to
548      * autospawn a deamon */
549     GST_LOG_OBJECT (psink, "connect to server %s",
550         GST_STR_NULL (psink->server));
551     if (pa_context_connect (pctx->context, psink->server,
552             PA_CONTEXT_NOAUTOSPAWN, NULL) < 0)
553       goto connect_failed;
554   } else {
555     GST_INFO_OBJECT (psink,
556         "reusing shared context with name %s, pbuf=%p, pctx=%p",
557         pbuf->context_name, pbuf, pctx);
558     pctx->ring_buffers = g_slist_prepend (pctx->ring_buffers, pbuf);
559   }
560
561   g_mutex_unlock (&pa_shared_resource_mutex);
562   need_unlock_shared = FALSE;
563
564   /* context created or shared okay */
565   pbuf->context = pa_context_ref (pctx->context);
566
567   for (;;) {
568     pa_context_state_t state;
569
570     state = pa_context_get_state (pbuf->context);
571
572     GST_LOG_OBJECT (psink, "context state is now %d", state);
573
574     if (!PA_CONTEXT_IS_GOOD (state))
575       goto connect_failed;
576
577     if (state == PA_CONTEXT_READY)
578       break;
579
580     /* Wait until the context is ready */
581     GST_LOG_OBJECT (psink, "waiting..");
582     pa_threaded_mainloop_wait (mainloop);
583   }
584
585   if (pa_context_get_server_protocol_version (pbuf->context) < 22) {
586     /* We need PulseAudio >= 1.0 on the server side for the extended API */
587     goto bad_server_version;
588   }
589
590   GST_LOG_OBJECT (psink, "opened the device");
591
592   pa_threaded_mainloop_unlock (mainloop);
593
594   return TRUE;
595
596   /* ERRORS */
597 unlock_and_fail:
598   {
599     if (need_unlock_shared)
600       g_mutex_unlock (&pa_shared_resource_mutex);
601     gst_pulsering_destroy_context (pbuf);
602     pa_threaded_mainloop_unlock (mainloop);
603     return FALSE;
604   }
605 create_failed:
606   {
607     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
608         ("Failed to create context"), (NULL));
609     g_slice_free (GstPulseContext, pctx);
610     goto unlock_and_fail;
611   }
612 connect_failed:
613   {
614     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED, ("Failed to connect: %s",
615             pa_strerror (pa_context_errno (pctx->context))), (NULL));
616     goto unlock_and_fail;
617   }
618 bad_server_version:
619   {
620     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED, ("PulseAudio server version "
621             "is too old."), (NULL));
622     goto unlock_and_fail;
623   }
624 }
625
626 /* close the device */
627 static gboolean
628 gst_pulseringbuffer_close_device (GstAudioRingBuffer * buf)
629 {
630   GstPulseSink *psink;
631   GstPulseRingBuffer *pbuf;
632
633   pbuf = GST_PULSERING_BUFFER_CAST (buf);
634   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (buf));
635
636   GST_LOG_OBJECT (psink, "closing device");
637
638   pa_threaded_mainloop_lock (mainloop);
639   gst_pulsering_destroy_context (pbuf);
640   pa_threaded_mainloop_unlock (mainloop);
641
642   GST_LOG_OBJECT (psink, "closed device");
643
644   return TRUE;
645 }
646
647 static void
648 gst_pulsering_stream_state_cb (pa_stream * s, void *userdata)
649 {
650   GstPulseSink *psink;
651   GstPulseRingBuffer *pbuf;
652   pa_stream_state_t state;
653
654   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
655   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
656
657   state = pa_stream_get_state (s);
658   GST_LOG_OBJECT (psink, "got new stream state %d", state);
659
660   switch (state) {
661     case PA_STREAM_READY:
662     case PA_STREAM_FAILED:
663     case PA_STREAM_TERMINATED:
664       GST_LOG_OBJECT (psink, "signaling");
665       pa_threaded_mainloop_signal (mainloop, 0);
666       break;
667     case PA_STREAM_UNCONNECTED:
668     case PA_STREAM_CREATING:
669       break;
670   }
671 }
672
673 static void
674 gst_pulsering_stream_request_cb (pa_stream * s, size_t length, void *userdata)
675 {
676   GstPulseSink *psink;
677   GstAudioRingBuffer *rbuf;
678   GstPulseRingBuffer *pbuf;
679
680   rbuf = GST_AUDIO_RING_BUFFER_CAST (userdata);
681   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
682   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
683
684   GST_LOG_OBJECT (psink, "got request for length %" G_GSIZE_FORMAT, length);
685
686   if (pbuf->in_commit && (length >= rbuf->spec.segsize)) {
687     /* only signal when we are waiting in the commit thread
688      * and got request for atleast a segment */
689     pa_threaded_mainloop_signal (mainloop, 0);
690   }
691 }
692
693 static void
694 gst_pulsering_stream_underflow_cb (pa_stream * s, void *userdata)
695 {
696   GstPulseSink *psink;
697   GstPulseRingBuffer *pbuf;
698
699   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
700   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
701
702   GST_WARNING_OBJECT (psink, "Got underflow");
703 }
704
705 static void
706 gst_pulsering_stream_overflow_cb (pa_stream * s, void *userdata)
707 {
708   GstPulseSink *psink;
709   GstPulseRingBuffer *pbuf;
710
711   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
712   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
713
714   GST_WARNING_OBJECT (psink, "Got overflow");
715 }
716
717 static void
718 gst_pulsering_stream_latency_cb (pa_stream * s, void *userdata)
719 {
720   GstPulseSink *psink;
721   GstPulseRingBuffer *pbuf;
722   GstAudioRingBuffer *ringbuf;
723   const pa_timing_info *info;
724   pa_usec_t sink_usec;
725
726   info = pa_stream_get_timing_info (s);
727
728   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
729   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
730   ringbuf = GST_AUDIO_RING_BUFFER (pbuf);
731
732   if (!info) {
733     GST_LOG_OBJECT (psink, "latency update (information unknown)");
734     return;
735   }
736
737   if (!info->read_index_corrupt) {
738     /* Update segdone based on the read index. segdone is of segment
739      * granularity, while the read index is at byte granularity. We take the
740      * ceiling while converting the latter to the former since it is more
741      * conservative to report that we've read more than we have than to report
742      * less. One concern here is that latency updates happen every 100ms, which
743      * means segdone is not updated very often, but increasing the update
744      * frequency would mean more communication overhead. */
745     g_atomic_int_set (&ringbuf->segdone,
746         (int) gst_util_uint64_scale_ceil (info->read_index, 1,
747             ringbuf->spec.segsize));
748   }
749
750   sink_usec = info->configured_sink_usec;
751
752   GST_LOG_OBJECT (psink,
753       "latency_update, %" G_GUINT64_FORMAT ", %d:%" G_GINT64_FORMAT ", %d:%"
754       G_GUINT64_FORMAT ", %" G_GUINT64_FORMAT ", %" G_GUINT64_FORMAT,
755       GST_TIMEVAL_TO_TIME (info->timestamp), info->write_index_corrupt,
756       info->write_index, info->read_index_corrupt, info->read_index,
757       info->sink_usec, sink_usec);
758 }
759
760 static void
761 gst_pulsering_stream_suspended_cb (pa_stream * p, void *userdata)
762 {
763   GstPulseSink *psink;
764   GstPulseRingBuffer *pbuf;
765
766   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
767   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
768
769   if (pa_stream_is_suspended (p))
770     GST_DEBUG_OBJECT (psink, "stream suspended");
771   else
772     GST_DEBUG_OBJECT (psink, "stream resumed");
773 }
774
775 static void
776 gst_pulsering_stream_started_cb (pa_stream * p, void *userdata)
777 {
778   GstPulseSink *psink;
779   GstPulseRingBuffer *pbuf;
780
781   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
782   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
783
784   GST_DEBUG_OBJECT (psink, "stream started");
785 }
786
787 static void
788 gst_pulsering_stream_event_cb (pa_stream * p, const char *name,
789     pa_proplist * pl, void *userdata)
790 {
791   GstPulseSink *psink;
792   GstPulseRingBuffer *pbuf;
793
794   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
795   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
796
797   if (!strcmp (name, PA_STREAM_EVENT_REQUEST_CORK)) {
798     /* the stream wants to PAUSE, post a message for the application. */
799     GST_DEBUG_OBJECT (psink, "got request for CORK");
800     gst_element_post_message (GST_ELEMENT_CAST (psink),
801         gst_message_new_request_state (GST_OBJECT_CAST (psink),
802             GST_STATE_PAUSED));
803
804   } else if (!strcmp (name, PA_STREAM_EVENT_REQUEST_UNCORK)) {
805     GST_DEBUG_OBJECT (psink, "got request for UNCORK");
806     gst_element_post_message (GST_ELEMENT_CAST (psink),
807         gst_message_new_request_state (GST_OBJECT_CAST (psink),
808             GST_STATE_PLAYING));
809   } else if (!strcmp (name, PA_STREAM_EVENT_FORMAT_LOST)) {
810     GstEvent *renego;
811
812     if (g_atomic_int_get (&psink->format_lost)) {
813       /* Duplicate event before we're done reconfiguring, discard */
814       return;
815     }
816
817     GST_DEBUG_OBJECT (psink, "got FORMAT LOST");
818     g_atomic_int_set (&psink->format_lost, 1);
819     psink->format_lost_time = g_ascii_strtoull (pa_proplist_gets (pl,
820             "stream-time"), NULL, 0) * 1000;
821
822     g_free (psink->device);
823     psink->device = g_strdup (pa_proplist_gets (pl, "device"));
824
825     /* FIXME: send reconfigure event instead and let decodebin/playbin
826      * handle that. Also take care of ac3 alignment */
827     renego = gst_event_new_custom (GST_EVENT_CUSTOM_UPSTREAM,
828         gst_structure_new_empty ("pulse-format-lost"));
829
830 #if 0
831     if (g_str_equal (gst_structure_get_name (st), "audio/x-eac3")) {
832       GstStructure *event_st = gst_structure_new ("ac3parse-set-alignment",
833           "alignment", G_TYPE_STRING, pbin->dbin ? "frame" : "iec61937", NULL);
834
835       if (!gst_pad_push_event (pbin->sinkpad,
836               gst_event_new_custom (GST_EVENT_CUSTOM_UPSTREAM, event_st)))
837         GST_WARNING_OBJECT (pbin->sinkpad, "Could not update alignment");
838     }
839 #endif
840
841     if (!gst_pad_push_event (GST_BASE_SINK (psink)->sinkpad, renego)) {
842       /* Nobody handled the format change - emit an error */
843       GST_ELEMENT_ERROR (psink, STREAM, FORMAT, ("Sink format changed"),
844           ("Sink format changed"));
845     }
846   } else {
847     GST_DEBUG_OBJECT (psink, "got unknown event %s", name);
848   }
849 }
850
851 /* Called with the mainloop locked */
852 static gboolean
853 gst_pulsering_wait_for_stream_ready (GstPulseSink * psink, pa_stream * stream)
854 {
855   pa_stream_state_t state;
856
857   for (;;) {
858     state = pa_stream_get_state (stream);
859
860     GST_LOG_OBJECT (psink, "stream state is now %d", state);
861
862     if (!PA_STREAM_IS_GOOD (state))
863       return FALSE;
864
865     if (state == PA_STREAM_READY)
866       return TRUE;
867
868     /* Wait until the stream is ready */
869     pa_threaded_mainloop_wait (mainloop);
870   }
871 }
872
873
874 /* This method should create a new stream of the given @spec. No playback should
875  * start yet so we start in the corked state. */
876 static gboolean
877 gst_pulseringbuffer_acquire (GstAudioRingBuffer * buf,
878     GstAudioRingBufferSpec * spec)
879 {
880   GstPulseSink *psink;
881   GstPulseRingBuffer *pbuf;
882   pa_buffer_attr wanted;
883   const pa_buffer_attr *actual;
884   pa_channel_map channel_map;
885   pa_operation *o = NULL;
886   pa_cvolume v;
887   pa_cvolume *pv = NULL;
888   pa_stream_flags_t flags;
889   const gchar *name;
890   GstAudioClock *clock;
891   pa_format_info *formats[1];
892 #ifndef GST_DISABLE_GST_DEBUG
893   gchar print_buf[PA_FORMAT_INFO_SNPRINT_MAX];
894 #endif
895
896   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (buf));
897   pbuf = GST_PULSERING_BUFFER_CAST (buf);
898
899   GST_LOG_OBJECT (psink, "creating sample spec");
900   /* convert the gstreamer sample spec to the pulseaudio format */
901   if (!gst_pulse_fill_format_info (spec, &pbuf->format, &pbuf->channels))
902     goto invalid_spec;
903   pbuf->is_pcm = pa_format_info_is_pcm (pbuf->format);
904
905   pa_threaded_mainloop_lock (mainloop);
906
907   /* we need a context and a no stream */
908   g_assert (pbuf->context);
909   g_assert (!pbuf->stream);
910
911   /* if we have a probe, disconnect it first so that if we're creating a
912    * compressed stream, it doesn't get blocked by a PCM stream */
913   if (pbuf->probe_stream) {
914     gst_pulse_destroy_stream (pbuf->probe_stream, TRUE);
915     pbuf->probe_stream = NULL;
916   }
917
918   /* enable event notifications */
919   GST_LOG_OBJECT (psink, "subscribing to context events");
920   if (!(o = pa_context_subscribe (pbuf->context,
921               PA_SUBSCRIPTION_MASK_SINK_INPUT, NULL, NULL)))
922     goto subscribe_failed;
923
924   pa_operation_unref (o);
925
926   /* initialize the channel map */
927   if (pbuf->is_pcm && gst_pulse_gst_to_channel_map (&channel_map, spec))
928     pa_format_info_set_channel_map (pbuf->format, &channel_map);
929
930   /* find a good name for the stream */
931   if (psink->stream_name)
932     name = psink->stream_name;
933   else
934     name = "Playback Stream";
935
936   /* create a stream */
937   formats[0] = pbuf->format;
938   if (!(pbuf->stream = pa_stream_new_extended (pbuf->context, name, formats, 1,
939               psink->proplist)))
940     goto stream_failed;
941
942   /* install essential callbacks */
943   pa_stream_set_state_callback (pbuf->stream,
944       gst_pulsering_stream_state_cb, pbuf);
945   pa_stream_set_write_callback (pbuf->stream,
946       gst_pulsering_stream_request_cb, pbuf);
947   pa_stream_set_underflow_callback (pbuf->stream,
948       gst_pulsering_stream_underflow_cb, pbuf);
949   pa_stream_set_overflow_callback (pbuf->stream,
950       gst_pulsering_stream_overflow_cb, pbuf);
951   pa_stream_set_latency_update_callback (pbuf->stream,
952       gst_pulsering_stream_latency_cb, pbuf);
953   pa_stream_set_suspended_callback (pbuf->stream,
954       gst_pulsering_stream_suspended_cb, pbuf);
955   pa_stream_set_started_callback (pbuf->stream,
956       gst_pulsering_stream_started_cb, pbuf);
957   pa_stream_set_event_callback (pbuf->stream,
958       gst_pulsering_stream_event_cb, pbuf);
959
960   /* buffering requirements. When setting prebuf to 0, the stream will not pause
961    * when we cause an underrun, which causes time to continue. */
962   memset (&wanted, 0, sizeof (wanted));
963   wanted.tlength = spec->segtotal * spec->segsize;
964   wanted.maxlength = -1;
965   wanted.prebuf = 0;
966   wanted.minreq = spec->segsize;
967
968   GST_INFO_OBJECT (psink, "tlength:   %d", wanted.tlength);
969   GST_INFO_OBJECT (psink, "maxlength: %d", wanted.maxlength);
970   GST_INFO_OBJECT (psink, "prebuf:    %d", wanted.prebuf);
971   GST_INFO_OBJECT (psink, "minreq:    %d", wanted.minreq);
972
973   /* configure volume when we changed it, else we leave the default */
974   if (psink->volume_set) {
975     GST_LOG_OBJECT (psink, "have volume of %f", psink->volume);
976     pv = &v;
977     if (pbuf->is_pcm)
978       gst_pulse_cvolume_from_linear (pv, pbuf->channels, psink->volume);
979     else {
980       GST_DEBUG_OBJECT (psink, "passthrough stream, not setting volume");
981       pv = NULL;
982     }
983   } else {
984     pv = NULL;
985   }
986
987   /* construct the flags */
988   flags = PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE |
989       PA_STREAM_ADJUST_LATENCY | PA_STREAM_START_CORKED;
990
991   if (psink->mute_set) {
992     if (psink->mute)
993       flags |= PA_STREAM_START_MUTED;
994     else
995       flags |= PA_STREAM_START_UNMUTED;
996   }
997
998   /* we always start corked (see flags above) */
999   pbuf->corked = TRUE;
1000
1001   /* try to connect now */
1002   GST_LOG_OBJECT (psink, "connect for playback to device %s",
1003       GST_STR_NULL (psink->device));
1004   if (pa_stream_connect_playback (pbuf->stream, psink->device,
1005           &wanted, flags, pv, NULL) < 0)
1006     goto connect_failed;
1007
1008   /* our clock will now start from 0 again */
1009   clock = GST_AUDIO_CLOCK (GST_AUDIO_BASE_SINK (psink)->provided_clock);
1010   gst_audio_clock_reset (clock, 0);
1011
1012   if (!gst_pulsering_wait_for_stream_ready (psink, pbuf->stream))
1013     goto connect_failed;
1014
1015   g_free (psink->device);
1016   psink->device = g_strdup (pa_stream_get_device_name (pbuf->stream));
1017
1018 #ifndef GST_DISABLE_GST_DEBUG
1019   pa_format_info_snprint (print_buf, sizeof (print_buf),
1020       pa_stream_get_format_info (pbuf->stream));
1021   GST_INFO_OBJECT (psink, "negotiated to: %s", print_buf);
1022 #endif
1023
1024   /* After we passed the volume off of to PA we never want to set it
1025      again, since it is PA's job to save/restore volumes.  */
1026   psink->volume_set = psink->mute_set = FALSE;
1027
1028   GST_LOG_OBJECT (psink, "stream is acquired now");
1029
1030   /* get the actual buffering properties now */
1031   actual = pa_stream_get_buffer_attr (pbuf->stream);
1032
1033   GST_INFO_OBJECT (psink, "tlength:   %d (wanted: %d)", actual->tlength,
1034       wanted.tlength);
1035   GST_INFO_OBJECT (psink, "maxlength: %d", actual->maxlength);
1036   GST_INFO_OBJECT (psink, "prebuf:    %d", actual->prebuf);
1037   GST_INFO_OBJECT (psink, "minreq:    %d (wanted %d)", actual->minreq,
1038       wanted.minreq);
1039
1040   spec->segsize = actual->minreq;
1041   spec->segtotal = actual->tlength / spec->segsize;
1042
1043   pa_threaded_mainloop_unlock (mainloop);
1044
1045   return TRUE;
1046
1047   /* ERRORS */
1048 unlock_and_fail:
1049   {
1050     gst_pulsering_destroy_stream (pbuf);
1051     pa_threaded_mainloop_unlock (mainloop);
1052
1053     return FALSE;
1054   }
1055 invalid_spec:
1056   {
1057     GST_ELEMENT_ERROR (psink, RESOURCE, SETTINGS,
1058         ("Invalid sample specification."), (NULL));
1059     return FALSE;
1060   }
1061 subscribe_failed:
1062   {
1063     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1064         ("pa_context_subscribe() failed: %s",
1065             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1066     goto unlock_and_fail;
1067   }
1068 stream_failed:
1069   {
1070     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1071         ("Failed to create stream: %s",
1072             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1073     goto unlock_and_fail;
1074   }
1075 connect_failed:
1076   {
1077     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1078         ("Failed to connect stream: %s",
1079             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1080     goto unlock_and_fail;
1081   }
1082 }
1083
1084 /* free the stream that we acquired before */
1085 static gboolean
1086 gst_pulseringbuffer_release (GstAudioRingBuffer * buf)
1087 {
1088   GstPulseRingBuffer *pbuf;
1089
1090   pbuf = GST_PULSERING_BUFFER_CAST (buf);
1091
1092   pa_threaded_mainloop_lock (mainloop);
1093   gst_pulsering_destroy_stream (pbuf);
1094   pa_threaded_mainloop_unlock (mainloop);
1095
1096   {
1097     GstPulseSink *psink;
1098
1099     psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1100     g_atomic_int_set (&psink->format_lost, FALSE);
1101     psink->format_lost_time = GST_CLOCK_TIME_NONE;
1102   }
1103
1104   return TRUE;
1105 }
1106
1107 static void
1108 gst_pulsering_success_cb (pa_stream * s, int success, void *userdata)
1109 {
1110   pa_threaded_mainloop_signal (mainloop, 0);
1111 }
1112
1113 /* update the corked state of a stream, must be called with the mainloop
1114  * lock */
1115 static gboolean
1116 gst_pulsering_set_corked (GstPulseRingBuffer * pbuf, gboolean corked,
1117     gboolean wait)
1118 {
1119   pa_operation *o = NULL;
1120   GstPulseSink *psink;
1121   gboolean res = FALSE;
1122
1123   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1124
1125   if (g_atomic_int_get (&psink->format_lost)) {
1126     /* Sink format changed, stream's gone so fake being paused */
1127     return TRUE;
1128   }
1129
1130   GST_DEBUG_OBJECT (psink, "setting corked state to %d", corked);
1131   if (pbuf->corked != corked) {
1132     if (!(o = pa_stream_cork (pbuf->stream, corked,
1133                 gst_pulsering_success_cb, pbuf)))
1134       goto cork_failed;
1135
1136     while (wait && pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
1137       pa_threaded_mainloop_wait (mainloop);
1138       if (gst_pulsering_is_dead (psink, pbuf, TRUE))
1139         goto server_dead;
1140     }
1141     pbuf->corked = corked;
1142   } else {
1143     GST_DEBUG_OBJECT (psink, "skipping, already in requested state");
1144   }
1145   res = TRUE;
1146
1147 cleanup:
1148   if (o)
1149     pa_operation_unref (o);
1150
1151   return res;
1152
1153   /* ERRORS */
1154 server_dead:
1155   {
1156     GST_DEBUG_OBJECT (psink, "the server is dead");
1157     goto cleanup;
1158   }
1159 cork_failed:
1160   {
1161     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1162         ("pa_stream_cork() failed: %s",
1163             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1164     goto cleanup;
1165   }
1166 }
1167
1168 static void
1169 gst_pulseringbuffer_clear (GstAudioRingBuffer * buf)
1170 {
1171   GstPulseSink *psink;
1172   GstPulseRingBuffer *pbuf;
1173   pa_operation *o = NULL;
1174
1175   pbuf = GST_PULSERING_BUFFER_CAST (buf);
1176   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1177
1178   pa_threaded_mainloop_lock (mainloop);
1179   GST_DEBUG_OBJECT (psink, "clearing");
1180   if (pbuf->stream) {
1181     /* don't wait for the flush to complete */
1182     if ((o = pa_stream_flush (pbuf->stream, NULL, pbuf)))
1183       pa_operation_unref (o);
1184   }
1185   pa_threaded_mainloop_unlock (mainloop);
1186 }
1187
1188 #if 0
1189 /* called from pulse thread with the mainloop lock */
1190 static void
1191 mainloop_enter_defer_cb (pa_mainloop_api * api, void *userdata)
1192 {
1193   GstPulseSink *pulsesink = GST_PULSESINK (userdata);
1194   GstMessage *message;
1195   GValue val = { 0 };
1196
1197   GST_DEBUG_OBJECT (pulsesink, "posting ENTER stream status");
1198   message = gst_message_new_stream_status (GST_OBJECT (pulsesink),
1199       GST_STREAM_STATUS_TYPE_ENTER, GST_ELEMENT (pulsesink));
1200   g_value_init (&val, GST_TYPE_G_THREAD);
1201   g_value_set_boxed (&val, g_thread_self ());
1202   gst_message_set_stream_status_object (message, &val);
1203   g_value_unset (&val);
1204
1205   gst_element_post_message (GST_ELEMENT (pulsesink), message);
1206
1207   g_return_if_fail (pulsesink->defer_pending);
1208   pulsesink->defer_pending--;
1209   pa_threaded_mainloop_signal (mainloop, 0);
1210 }
1211 #endif
1212
1213 /* start/resume playback ASAP, we don't uncork here but in the commit method */
1214 static gboolean
1215 gst_pulseringbuffer_start (GstAudioRingBuffer * buf)
1216 {
1217   GstPulseSink *psink;
1218   GstPulseRingBuffer *pbuf;
1219
1220   pbuf = GST_PULSERING_BUFFER_CAST (buf);
1221   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1222
1223   pa_threaded_mainloop_lock (mainloop);
1224
1225   GST_DEBUG_OBJECT (psink, "starting");
1226   pbuf->paused = FALSE;
1227
1228   /* EOS needs running clock */
1229   if (GST_BASE_SINK_CAST (psink)->eos ||
1230       g_atomic_int_get (&GST_AUDIO_BASE_SINK (psink)->eos_rendering))
1231     gst_pulsering_set_corked (pbuf, FALSE, FALSE);
1232
1233 #if 0
1234   GST_DEBUG_OBJECT (psink, "scheduling stream status");
1235   psink->defer_pending++;
1236   pa_mainloop_api_once (pa_threaded_mainloop_get_api (mainloop),
1237       mainloop_enter_defer_cb, psink);
1238
1239   /* Wait for the stream status message to be posted. This needs to be done
1240    * synchronously because the callback will take the mainloop lock
1241    * (implicitly) and then take the GST_OBJECT_LOCK. Everywhere else, we take
1242    * the locks in the reverse order, so not doing this synchronously could
1243    * cause a deadlock. */
1244   GST_DEBUG_OBJECT (psink, "waiting for stream status (ENTER) to be posted");
1245   pa_threaded_mainloop_wait (mainloop);
1246 #endif
1247
1248   pa_threaded_mainloop_unlock (mainloop);
1249
1250   return TRUE;
1251 }
1252
1253 /* pause/stop playback ASAP */
1254 static gboolean
1255 gst_pulseringbuffer_pause (GstAudioRingBuffer * buf)
1256 {
1257   GstPulseSink *psink;
1258   GstPulseRingBuffer *pbuf;
1259   gboolean res;
1260
1261   pbuf = GST_PULSERING_BUFFER_CAST (buf);
1262   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1263
1264   pa_threaded_mainloop_lock (mainloop);
1265   GST_DEBUG_OBJECT (psink, "pausing and corking");
1266   /* make sure the commit method stops writing */
1267   pbuf->paused = TRUE;
1268   res = gst_pulsering_set_corked (pbuf, TRUE, TRUE);
1269   if (pbuf->in_commit) {
1270     /* we are waiting in a commit, signal */
1271     GST_DEBUG_OBJECT (psink, "signal commit");
1272     pa_threaded_mainloop_signal (mainloop, 0);
1273   }
1274   pa_threaded_mainloop_unlock (mainloop);
1275
1276   return res;
1277 }
1278
1279 #if 0
1280 /* called from pulse thread with the mainloop lock */
1281 static void
1282 mainloop_leave_defer_cb (pa_mainloop_api * api, void *userdata)
1283 {
1284   GstPulseSink *pulsesink = GST_PULSESINK (userdata);
1285   GstMessage *message;
1286   GValue val = { 0 };
1287
1288   GST_DEBUG_OBJECT (pulsesink, "posting LEAVE stream status");
1289   message = gst_message_new_stream_status (GST_OBJECT (pulsesink),
1290       GST_STREAM_STATUS_TYPE_LEAVE, GST_ELEMENT (pulsesink));
1291   g_value_init (&val, GST_TYPE_G_THREAD);
1292   g_value_set_boxed (&val, g_thread_self ());
1293   gst_message_set_stream_status_object (message, &val);
1294   g_value_unset (&val);
1295
1296   gst_element_post_message (GST_ELEMENT (pulsesink), message);
1297
1298   g_return_if_fail (pulsesink->defer_pending);
1299   pulsesink->defer_pending--;
1300   pa_threaded_mainloop_signal (mainloop, 0);
1301 }
1302 #endif
1303
1304 /* stop playback, we flush everything. */
1305 static gboolean
1306 gst_pulseringbuffer_stop (GstAudioRingBuffer * buf)
1307 {
1308   GstPulseSink *psink;
1309   GstPulseRingBuffer *pbuf;
1310   gboolean res = FALSE;
1311   pa_operation *o = NULL;
1312
1313   pbuf = GST_PULSERING_BUFFER_CAST (buf);
1314   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1315
1316   pa_threaded_mainloop_lock (mainloop);
1317
1318   pbuf->paused = TRUE;
1319   res = gst_pulsering_set_corked (pbuf, TRUE, TRUE);
1320
1321   /* Inform anyone waiting in _commit() call that it shall wakeup */
1322   if (pbuf->in_commit) {
1323     GST_DEBUG_OBJECT (psink, "signal commit thread");
1324     pa_threaded_mainloop_signal (mainloop, 0);
1325   }
1326   if (g_atomic_int_get (&psink->format_lost)) {
1327     /* Don't try to flush, the stream's probably gone by now */
1328     res = TRUE;
1329     goto cleanup;
1330   }
1331
1332   /* then try to flush, it's not fatal when this fails */
1333   GST_DEBUG_OBJECT (psink, "flushing");
1334   if ((o = pa_stream_flush (pbuf->stream, gst_pulsering_success_cb, pbuf))) {
1335     while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
1336       GST_DEBUG_OBJECT (psink, "wait for completion");
1337       pa_threaded_mainloop_wait (mainloop);
1338       if (gst_pulsering_is_dead (psink, pbuf, TRUE))
1339         goto server_dead;
1340     }
1341     GST_DEBUG_OBJECT (psink, "flush completed");
1342   }
1343   res = TRUE;
1344
1345 cleanup:
1346   if (o) {
1347     pa_operation_cancel (o);
1348     pa_operation_unref (o);
1349   }
1350 #if 0
1351   GST_DEBUG_OBJECT (psink, "scheduling stream status");
1352   psink->defer_pending++;
1353   pa_mainloop_api_once (pa_threaded_mainloop_get_api (mainloop),
1354       mainloop_leave_defer_cb, psink);
1355
1356   /* Wait for the stream status message to be posted. This needs to be done
1357    * synchronously because the callback will take the mainloop lock
1358    * (implicitly) and then take the GST_OBJECT_LOCK. Everywhere else, we take
1359    * the locks in the reverse order, so not doing this synchronously could
1360    * cause a deadlock. */
1361   GST_DEBUG_OBJECT (psink, "waiting for stream status (LEAVE) to be posted");
1362   pa_threaded_mainloop_wait (mainloop);
1363 #endif
1364
1365   pa_threaded_mainloop_unlock (mainloop);
1366
1367   return res;
1368
1369   /* ERRORS */
1370 server_dead:
1371   {
1372     GST_DEBUG_OBJECT (psink, "the server is dead");
1373     goto cleanup;
1374   }
1375 }
1376
1377 /* in_samples >= out_samples, rate > 1.0 */
1378 #define FWD_UP_SAMPLES(s,se,d,de)               \
1379 G_STMT_START {                                  \
1380   guint8 *sb = s, *db = d;                      \
1381   while (s <= se && d < de) {                   \
1382     memcpy (d, s, bpf);                         \
1383     s += bpf;                                   \
1384     *accum += outr;                             \
1385     if ((*accum << 1) >= inr) {                 \
1386       *accum -= inr;                            \
1387       d += bpf;                                 \
1388     }                                           \
1389   }                                             \
1390   in_samples -= (s - sb)/bpf;                   \
1391   out_samples -= (d - db)/bpf;                  \
1392   GST_DEBUG ("fwd_up end %d/%d",*accum,*toprocess);     \
1393 } G_STMT_END
1394
1395 /* out_samples > in_samples, for rates smaller than 1.0 */
1396 #define FWD_DOWN_SAMPLES(s,se,d,de)             \
1397 G_STMT_START {                                  \
1398   guint8 *sb = s, *db = d;                      \
1399   while (s <= se && d < de) {                   \
1400     memcpy (d, s, bpf);                         \
1401     d += bpf;                                   \
1402     *accum += inr;                              \
1403     if ((*accum << 1) >= outr) {                \
1404       *accum -= outr;                           \
1405       s += bpf;                                 \
1406     }                                           \
1407   }                                             \
1408   in_samples -= (s - sb)/bpf;                   \
1409   out_samples -= (d - db)/bpf;                  \
1410   GST_DEBUG ("fwd_down end %d/%d",*accum,*toprocess);   \
1411 } G_STMT_END
1412
1413 #define REV_UP_SAMPLES(s,se,d,de)               \
1414 G_STMT_START {                                  \
1415   guint8 *sb = se, *db = d;                     \
1416   while (s <= se && d < de) {                   \
1417     memcpy (d, se, bpf);                        \
1418     se -= bpf;                                  \
1419     *accum += outr;                             \
1420     while (d < de && (*accum << 1) >= inr) {    \
1421       *accum -= inr;                            \
1422       d += bpf;                                 \
1423     }                                           \
1424   }                                             \
1425   in_samples -= (sb - se)/bpf;                  \
1426   out_samples -= (d - db)/bpf;                  \
1427   GST_DEBUG ("rev_up end %d/%d",*accum,*toprocess);     \
1428 } G_STMT_END
1429
1430 #define REV_DOWN_SAMPLES(s,se,d,de)             \
1431 G_STMT_START {                                  \
1432   guint8 *sb = se, *db = d;                     \
1433   while (s <= se && d < de) {                   \
1434     memcpy (d, se, bpf);                        \
1435     d += bpf;                                   \
1436     *accum += inr;                              \
1437     while (s <= se && (*accum << 1) >= outr) {  \
1438       *accum -= outr;                           \
1439       se -= bpf;                                \
1440     }                                           \
1441   }                                             \
1442   in_samples -= (sb - se)/bpf;                  \
1443   out_samples -= (d - db)/bpf;                  \
1444   GST_DEBUG ("rev_down end %d/%d",*accum,*toprocess);   \
1445 } G_STMT_END
1446
1447 /* our custom commit function because we write into the buffer of pulseaudio
1448  * instead of keeping our own buffer */
1449 static guint
1450 gst_pulseringbuffer_commit (GstAudioRingBuffer * buf, guint64 * sample,
1451     guchar * data, gint in_samples, gint out_samples, gint * accum)
1452 {
1453   GstPulseSink *psink;
1454   GstPulseRingBuffer *pbuf;
1455   guint result;
1456   guint8 *data_end;
1457   gboolean reverse;
1458   gint *toprocess;
1459   gint inr, outr, bpf;
1460   gint64 offset;
1461   guint bufsize;
1462
1463   pbuf = GST_PULSERING_BUFFER_CAST (buf);
1464   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1465
1466   /* FIXME post message rather than using a signal (as mixer interface) */
1467   if (g_atomic_int_compare_and_exchange (&psink->notify, 1, 0)) {
1468     g_object_notify (G_OBJECT (psink), "volume");
1469     g_object_notify (G_OBJECT (psink), "mute");
1470     g_object_notify (G_OBJECT (psink), "current-device");
1471   }
1472
1473   /* make sure the ringbuffer is started */
1474   if (G_UNLIKELY (g_atomic_int_get (&buf->state) !=
1475           GST_AUDIO_RING_BUFFER_STATE_STARTED)) {
1476     /* see if we are allowed to start it */
1477     if (G_UNLIKELY (g_atomic_int_get (&buf->may_start) == FALSE))
1478       goto no_start;
1479
1480     GST_DEBUG_OBJECT (buf, "start!");
1481     if (!gst_audio_ring_buffer_start (buf))
1482       goto start_failed;
1483   }
1484
1485   pa_threaded_mainloop_lock (mainloop);
1486
1487   GST_DEBUG_OBJECT (psink, "entering commit");
1488   pbuf->in_commit = TRUE;
1489
1490   bpf = GST_AUDIO_INFO_BPF (&buf->spec.info);
1491   bufsize = buf->spec.segsize * buf->spec.segtotal;
1492
1493   /* our toy resampler for trick modes */
1494   reverse = out_samples < 0;
1495   out_samples = ABS (out_samples);
1496
1497   if (in_samples >= out_samples)
1498     toprocess = &in_samples;
1499   else
1500     toprocess = &out_samples;
1501
1502   inr = in_samples - 1;
1503   outr = out_samples - 1;
1504
1505   GST_DEBUG_OBJECT (psink, "in %d, out %d", inr, outr);
1506
1507   /* data_end points to the last sample we have to write, not past it. This is
1508    * needed to properly handle reverse playback: it points to the last sample. */
1509   data_end = data + (bpf * inr);
1510
1511   if (g_atomic_int_get (&psink->format_lost)) {
1512     /* Sink format changed, drop the data and hope upstream renegotiates */
1513     goto fake_done;
1514   }
1515
1516   if (pbuf->paused)
1517     goto was_paused;
1518
1519   /* offset is in bytes */
1520   offset = *sample * bpf;
1521
1522   while (*toprocess > 0) {
1523     size_t avail;
1524     guint towrite;
1525
1526     GST_LOG_OBJECT (psink,
1527         "need to write %d samples at offset %" G_GINT64_FORMAT, *toprocess,
1528         offset);
1529
1530     if (offset != pbuf->m_lastoffset)
1531       GST_LOG_OBJECT (psink, "discontinuity, offset is %" G_GINT64_FORMAT ", "
1532           "last offset was %" G_GINT64_FORMAT, offset, pbuf->m_lastoffset);
1533
1534     towrite = out_samples * bpf;
1535
1536     /* Wait for at least segsize bytes to become available */
1537     if (towrite > buf->spec.segsize)
1538       towrite = buf->spec.segsize;
1539
1540     if ((pbuf->m_writable < towrite) || (offset != pbuf->m_lastoffset)) {
1541       /* if no room left or discontinuity in offset,
1542          we need to flush data and get a new buffer */
1543
1544       /* flush the buffer if possible */
1545       if ((pbuf->m_data != NULL) && (pbuf->m_towrite > 0)) {
1546
1547         GST_LOG_OBJECT (psink,
1548             "flushing %u samples at offset %" G_GINT64_FORMAT,
1549             (guint) pbuf->m_towrite / bpf, pbuf->m_offset);
1550
1551         if (pa_stream_write (pbuf->stream, (uint8_t *) pbuf->m_data,
1552                 pbuf->m_towrite, NULL, pbuf->m_offset, PA_SEEK_ABSOLUTE) < 0) {
1553           goto write_failed;
1554         }
1555       }
1556       pbuf->m_towrite = 0;
1557       pbuf->m_offset = offset;  /* keep track of current offset */
1558
1559       /* get a buffer to write in for now on */
1560       for (;;) {
1561         pbuf->m_writable = pa_stream_writable_size (pbuf->stream);
1562
1563         if (g_atomic_int_get (&psink->format_lost)) {
1564           /* Sink format changed, give up and hope upstream renegotiates */
1565           goto fake_done;
1566         }
1567
1568         if (pbuf->m_writable == (size_t) - 1)
1569           goto writable_size_failed;
1570
1571         pbuf->m_writable /= bpf;
1572         pbuf->m_writable *= bpf;        /* handle only complete samples */
1573
1574         if (pbuf->m_writable >= towrite)
1575           break;
1576
1577         /* see if we need to uncork because we have no free space */
1578         if (pbuf->corked) {
1579           if (!gst_pulsering_set_corked (pbuf, FALSE, FALSE))
1580             goto uncork_failed;
1581         }
1582
1583         /* we can't write segsize bytes, wait a bit */
1584         GST_LOG_OBJECT (psink, "waiting for free space");
1585         pa_threaded_mainloop_wait (mainloop);
1586
1587         if (pbuf->paused)
1588           goto was_paused;
1589       }
1590
1591       /* Recalculate what we can write in the next chunk */
1592       towrite = out_samples * bpf;
1593       if (pbuf->m_writable > towrite)
1594         pbuf->m_writable = towrite;
1595
1596       GST_LOG_OBJECT (psink, "requesting %" G_GSIZE_FORMAT " bytes of "
1597           "shared memory", pbuf->m_writable);
1598
1599       if (pa_stream_begin_write (pbuf->stream, &pbuf->m_data,
1600               &pbuf->m_writable) < 0) {
1601         GST_LOG_OBJECT (psink, "pa_stream_begin_write() failed");
1602         goto writable_size_failed;
1603       }
1604
1605       GST_LOG_OBJECT (psink, "got %" G_GSIZE_FORMAT " bytes of shared memory",
1606           pbuf->m_writable);
1607
1608     }
1609
1610     if (towrite > pbuf->m_writable)
1611       towrite = pbuf->m_writable;
1612     avail = towrite / bpf;
1613
1614     GST_LOG_OBJECT (psink, "writing %u samples at offset %" G_GUINT64_FORMAT,
1615         (guint) avail, offset);
1616
1617     /* No trick modes for passthrough streams */
1618     if (G_UNLIKELY (!pbuf->is_pcm && (inr != outr || reverse))) {
1619       GST_WARNING_OBJECT (psink, "Passthrough stream can't run in trick mode");
1620       goto unlock_and_fail;
1621     }
1622
1623     if (G_LIKELY (inr == outr && !reverse)) {
1624       /* no rate conversion, simply write out the samples */
1625       /* copy the data into internal buffer */
1626
1627       memcpy ((guint8 *) pbuf->m_data + pbuf->m_towrite, data, towrite);
1628       pbuf->m_towrite += towrite;
1629       pbuf->m_writable -= towrite;
1630
1631       data += towrite;
1632       in_samples -= avail;
1633       out_samples -= avail;
1634     } else {
1635       guint8 *dest, *d, *d_end;
1636
1637       /* write into the PulseAudio shm buffer */
1638       dest = d = (guint8 *) pbuf->m_data + pbuf->m_towrite;
1639       d_end = d + towrite;
1640
1641       if (!reverse) {
1642         if (inr >= outr)
1643           /* forward speed up */
1644           FWD_UP_SAMPLES (data, data_end, d, d_end);
1645         else
1646           /* forward slow down */
1647           FWD_DOWN_SAMPLES (data, data_end, d, d_end);
1648       } else {
1649         if (inr >= outr)
1650           /* reverse speed up */
1651           REV_UP_SAMPLES (data, data_end, d, d_end);
1652         else
1653           /* reverse slow down */
1654           REV_DOWN_SAMPLES (data, data_end, d, d_end);
1655       }
1656       /* see what we have left to write */
1657       towrite = (d - dest);
1658       pbuf->m_towrite += towrite;
1659       pbuf->m_writable -= towrite;
1660
1661       avail = towrite / bpf;
1662     }
1663
1664     /* flush the buffer if it's full */
1665     if ((pbuf->m_data != NULL) && (pbuf->m_towrite > 0)
1666         && (pbuf->m_writable == 0)) {
1667       GST_LOG_OBJECT (psink, "flushing %u samples at offset %" G_GINT64_FORMAT,
1668           (guint) pbuf->m_towrite / bpf, pbuf->m_offset);
1669
1670       if (pa_stream_write (pbuf->stream, (uint8_t *) pbuf->m_data,
1671               pbuf->m_towrite, NULL, pbuf->m_offset, PA_SEEK_ABSOLUTE) < 0) {
1672         goto write_failed;
1673       }
1674       pbuf->m_towrite = 0;
1675       pbuf->m_offset = offset + towrite;        /* keep track of current offset */
1676     }
1677
1678     *sample += avail;
1679     offset += avail * bpf;
1680     pbuf->m_lastoffset = offset;
1681
1682     /* check if we need to uncork after writing the samples */
1683     if (pbuf->corked) {
1684       const pa_timing_info *info;
1685
1686       if ((info = pa_stream_get_timing_info (pbuf->stream))) {
1687         GST_LOG_OBJECT (psink,
1688             "read_index at %" G_GUINT64_FORMAT ", offset %" G_GINT64_FORMAT,
1689             info->read_index, offset);
1690
1691         /* we uncork when the read_index is too far behind the offset we need
1692          * to write to. */
1693         if (info->read_index + bufsize <= offset) {
1694           if (!gst_pulsering_set_corked (pbuf, FALSE, FALSE))
1695             goto uncork_failed;
1696         }
1697       } else {
1698         GST_LOG_OBJECT (psink, "no timing info available yet");
1699       }
1700     }
1701   }
1702
1703 fake_done:
1704   /* we consumed all samples here */
1705   data = data_end + bpf;
1706
1707   pbuf->in_commit = FALSE;
1708   pa_threaded_mainloop_unlock (mainloop);
1709
1710 done:
1711   result = inr - ((data_end - data) / bpf);
1712   GST_LOG_OBJECT (psink, "wrote %d samples", result);
1713
1714   return result;
1715
1716   /* ERRORS */
1717 unlock_and_fail:
1718   {
1719     pbuf->in_commit = FALSE;
1720     GST_LOG_OBJECT (psink, "we are reset");
1721     pa_threaded_mainloop_unlock (mainloop);
1722     goto done;
1723   }
1724 no_start:
1725   {
1726     GST_LOG_OBJECT (psink, "we can not start");
1727     return 0;
1728   }
1729 start_failed:
1730   {
1731     GST_LOG_OBJECT (psink, "failed to start the ringbuffer");
1732     return 0;
1733   }
1734 uncork_failed:
1735   {
1736     pbuf->in_commit = FALSE;
1737     GST_ERROR_OBJECT (psink, "uncork failed");
1738     pa_threaded_mainloop_unlock (mainloop);
1739     goto done;
1740   }
1741 was_paused:
1742   {
1743     pbuf->in_commit = FALSE;
1744     GST_LOG_OBJECT (psink, "we are paused");
1745     pa_threaded_mainloop_unlock (mainloop);
1746     goto done;
1747   }
1748 writable_size_failed:
1749   {
1750     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1751         ("pa_stream_writable_size() failed: %s",
1752             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1753     goto unlock_and_fail;
1754   }
1755 write_failed:
1756   {
1757     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1758         ("pa_stream_write() failed: %s",
1759             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1760     goto unlock_and_fail;
1761   }
1762 }
1763
1764 /* write pending local samples, must be called with the mainloop lock */
1765 static void
1766 gst_pulsering_flush (GstPulseRingBuffer * pbuf)
1767 {
1768   GstPulseSink *psink;
1769
1770   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1771   GST_DEBUG_OBJECT (psink, "entering flush");
1772
1773   /* flush the buffer if possible */
1774   if (pbuf->stream && (pbuf->m_data != NULL) && (pbuf->m_towrite > 0)) {
1775 #ifndef GST_DISABLE_GST_DEBUG
1776     gint bpf;
1777
1778     bpf = (GST_AUDIO_RING_BUFFER_CAST (pbuf))->spec.info.bpf;
1779     GST_LOG_OBJECT (psink,
1780         "flushing %u samples at offset %" G_GINT64_FORMAT,
1781         (guint) pbuf->m_towrite / bpf, pbuf->m_offset);
1782 #endif
1783
1784     if (pa_stream_write (pbuf->stream, (uint8_t *) pbuf->m_data,
1785             pbuf->m_towrite, NULL, pbuf->m_offset, PA_SEEK_ABSOLUTE) < 0) {
1786       goto write_failed;
1787     }
1788
1789     pbuf->m_towrite = 0;
1790     pbuf->m_offset += pbuf->m_towrite;  /* keep track of current offset */
1791   }
1792
1793 done:
1794   return;
1795
1796   /* ERRORS */
1797 write_failed:
1798   {
1799     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1800         ("pa_stream_write() failed: %s",
1801             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1802     goto done;
1803   }
1804 }
1805
1806 static void gst_pulsesink_set_property (GObject * object, guint prop_id,
1807     const GValue * value, GParamSpec * pspec);
1808 static void gst_pulsesink_get_property (GObject * object, guint prop_id,
1809     GValue * value, GParamSpec * pspec);
1810 static void gst_pulsesink_finalize (GObject * object);
1811
1812 static gboolean gst_pulsesink_event (GstBaseSink * sink, GstEvent * event);
1813 static gboolean gst_pulsesink_query (GstBaseSink * sink, GstQuery * query);
1814
1815 static GstStateChangeReturn gst_pulsesink_change_state (GstElement * element,
1816     GstStateChange transition);
1817
1818 static GstStaticPadTemplate pad_template = GST_STATIC_PAD_TEMPLATE ("sink",
1819     GST_PAD_SINK,
1820     GST_PAD_ALWAYS,
1821     GST_STATIC_CAPS (PULSE_SINK_TEMPLATE_CAPS));
1822
1823 #define gst_pulsesink_parent_class parent_class
1824 G_DEFINE_TYPE_WITH_CODE (GstPulseSink, gst_pulsesink, GST_TYPE_AUDIO_BASE_SINK,
1825     gst_pulsesink_init_contexts ();
1826     G_IMPLEMENT_INTERFACE (GST_TYPE_STREAM_VOLUME, NULL)
1827     );
1828
1829 static GstAudioRingBuffer *
1830 gst_pulsesink_create_ringbuffer (GstAudioBaseSink * sink)
1831 {
1832   GstAudioRingBuffer *buffer;
1833
1834   GST_DEBUG_OBJECT (sink, "creating ringbuffer");
1835   buffer = g_object_new (GST_TYPE_PULSERING_BUFFER, NULL);
1836   GST_DEBUG_OBJECT (sink, "created ringbuffer @%p", buffer);
1837
1838   return buffer;
1839 }
1840
1841 static GstBuffer *
1842 gst_pulsesink_payload (GstAudioBaseSink * sink, GstBuffer * buf)
1843 {
1844   switch (sink->ringbuffer->spec.type) {
1845     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_AC3:
1846     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_EAC3:
1847     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_DTS:
1848     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_MPEG:
1849     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_MPEG2_AAC:
1850     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_MPEG4_AAC:
1851     {
1852       /* FIXME: alloc memory from PA if possible */
1853       gint framesize = gst_audio_iec61937_frame_size (&sink->ringbuffer->spec);
1854       GstBuffer *out;
1855       GstMapInfo inmap, outmap;
1856       gboolean res;
1857
1858       if (framesize <= 0)
1859         return NULL;
1860
1861       out = gst_buffer_new_and_alloc (framesize);
1862
1863       gst_buffer_map (buf, &inmap, GST_MAP_READ);
1864       gst_buffer_map (out, &outmap, GST_MAP_WRITE);
1865
1866       res = gst_audio_iec61937_payload (inmap.data, inmap.size,
1867           outmap.data, outmap.size, &sink->ringbuffer->spec, G_BIG_ENDIAN);
1868
1869       gst_buffer_unmap (buf, &inmap);
1870       gst_buffer_unmap (out, &outmap);
1871
1872       if (!res) {
1873         gst_buffer_unref (out);
1874         return NULL;
1875       }
1876
1877       gst_buffer_copy_into (out, buf, GST_BUFFER_COPY_METADATA, 0, -1);
1878       return out;
1879     }
1880
1881     default:
1882       return gst_buffer_ref (buf);
1883   }
1884 }
1885
1886 static void
1887 gst_pulsesink_class_init (GstPulseSinkClass * klass)
1888 {
1889   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1890   GstBaseSinkClass *gstbasesink_class = GST_BASE_SINK_CLASS (klass);
1891   GstBaseSinkClass *bc;
1892   GstAudioBaseSinkClass *gstaudiosink_class = GST_AUDIO_BASE_SINK_CLASS (klass);
1893   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
1894   gchar *clientname;
1895
1896   gobject_class->finalize = gst_pulsesink_finalize;
1897   gobject_class->set_property = gst_pulsesink_set_property;
1898   gobject_class->get_property = gst_pulsesink_get_property;
1899
1900   gstbasesink_class->event = GST_DEBUG_FUNCPTR (gst_pulsesink_event);
1901   gstbasesink_class->query = GST_DEBUG_FUNCPTR (gst_pulsesink_query);
1902
1903   /* restore the original basesink pull methods */
1904   bc = g_type_class_peek (GST_TYPE_BASE_SINK);
1905   gstbasesink_class->activate_pull = GST_DEBUG_FUNCPTR (bc->activate_pull);
1906
1907   gstelement_class->change_state =
1908       GST_DEBUG_FUNCPTR (gst_pulsesink_change_state);
1909
1910   gstaudiosink_class->create_ringbuffer =
1911       GST_DEBUG_FUNCPTR (gst_pulsesink_create_ringbuffer);
1912   gstaudiosink_class->payload = GST_DEBUG_FUNCPTR (gst_pulsesink_payload);
1913
1914   /* Overwrite GObject fields */
1915   g_object_class_install_property (gobject_class,
1916       PROP_SERVER,
1917       g_param_spec_string ("server", "Server",
1918           "The PulseAudio server to connect to", DEFAULT_SERVER,
1919           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1920
1921   g_object_class_install_property (gobject_class, PROP_DEVICE,
1922       g_param_spec_string ("device", "Device",
1923           "The PulseAudio sink device to connect to", DEFAULT_DEVICE,
1924           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1925
1926   g_object_class_install_property (gobject_class, PROP_CURRENT_DEVICE,
1927       g_param_spec_string ("current-device", "Current Device",
1928           "The current PulseAudio sink device", DEFAULT_CURRENT_DEVICE,
1929           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
1930
1931   g_object_class_install_property (gobject_class,
1932       PROP_DEVICE_NAME,
1933       g_param_spec_string ("device-name", "Device name",
1934           "Human-readable name of the sound device", DEFAULT_DEVICE_NAME,
1935           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
1936
1937   g_object_class_install_property (gobject_class,
1938       PROP_VOLUME,
1939       g_param_spec_double ("volume", "Volume",
1940           "Linear volume of this stream, 1.0=100%", 0.0, MAX_VOLUME,
1941           DEFAULT_VOLUME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1942   g_object_class_install_property (gobject_class,
1943       PROP_MUTE,
1944       g_param_spec_boolean ("mute", "Mute",
1945           "Mute state of this stream", DEFAULT_MUTE,
1946           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1947
1948   /**
1949    * GstPulseSink:client-name:
1950    *
1951    * The PulseAudio client name to use.
1952    */
1953   clientname = gst_pulse_client_name ();
1954   g_object_class_install_property (gobject_class,
1955       PROP_CLIENT_NAME,
1956       g_param_spec_string ("client-name", "Client Name",
1957           "The PulseAudio client name to use", clientname,
1958           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
1959           GST_PARAM_MUTABLE_READY));
1960   g_free (clientname);
1961
1962   /**
1963    * GstPulseSink:stream-properties:
1964    *
1965    * List of pulseaudio stream properties. A list of defined properties can be
1966    * found in the <ulink url="http://0pointer.de/lennart/projects/pulseaudio/doxygen/proplist_8h.html">pulseaudio api docs</ulink>.
1967    *
1968    * Below is an example for registering as a music application to pulseaudio.
1969    * |[
1970    * GstStructure *props;
1971    *
1972    * props = gst_structure_from_string ("props,media.role=music", NULL);
1973    * g_object_set (pulse, "stream-properties", props, NULL);
1974    * gst_structure_free
1975    * ]|
1976    */
1977   g_object_class_install_property (gobject_class,
1978       PROP_STREAM_PROPERTIES,
1979       g_param_spec_boxed ("stream-properties", "stream properties",
1980           "list of pulseaudio stream properties",
1981           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1982
1983   gst_element_class_set_static_metadata (gstelement_class,
1984       "PulseAudio Audio Sink",
1985       "Sink/Audio", "Plays audio to a PulseAudio server", "Lennart Poettering");
1986   gst_element_class_add_static_pad_template (gstelement_class, &pad_template);
1987 }
1988
1989 static void
1990 free_device_info (GstPulseDeviceInfo * device_info)
1991 {
1992   GList *l;
1993
1994   g_free (device_info->description);
1995
1996   for (l = g_list_first (device_info->formats); l; l = g_list_next (l))
1997     pa_format_info_free ((pa_format_info *) l->data);
1998
1999   g_list_free (device_info->formats);
2000 }
2001
2002 /* Returns the current time of the sink ringbuffer. The timing_info is updated
2003  * on every data write/flush and every 100ms (PA_STREAM_AUTO_TIMING_UPDATE).
2004  */
2005 static GstClockTime
2006 gst_pulsesink_get_time (GstClock * clock, GstAudioBaseSink * sink)
2007 {
2008   GstPulseSink *psink;
2009   GstPulseRingBuffer *pbuf;
2010   pa_usec_t time;
2011
2012   if (!sink->ringbuffer || !sink->ringbuffer->acquired)
2013     return GST_CLOCK_TIME_NONE;
2014
2015   pbuf = GST_PULSERING_BUFFER_CAST (sink->ringbuffer);
2016   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
2017
2018   if (g_atomic_int_get (&psink->format_lost)) {
2019     /* Stream was lost in a format change, it'll get set up again once
2020      * upstream renegotiates */
2021     return psink->format_lost_time;
2022   }
2023
2024   pa_threaded_mainloop_lock (mainloop);
2025   if (gst_pulsering_is_dead (psink, pbuf, TRUE))
2026     goto server_dead;
2027
2028   /* if we don't have enough data to get a timestamp, just return NONE, which
2029    * will return the last reported time */
2030   if (pa_stream_get_time (pbuf->stream, &time) < 0) {
2031     GST_DEBUG_OBJECT (psink, "could not get time");
2032     time = GST_CLOCK_TIME_NONE;
2033   } else
2034     time *= 1000;
2035   pa_threaded_mainloop_unlock (mainloop);
2036
2037   GST_LOG_OBJECT (psink, "current time is %" GST_TIME_FORMAT,
2038       GST_TIME_ARGS (time));
2039
2040   return time;
2041
2042   /* ERRORS */
2043 server_dead:
2044   {
2045     GST_DEBUG_OBJECT (psink, "the server is dead");
2046     pa_threaded_mainloop_unlock (mainloop);
2047
2048     return GST_CLOCK_TIME_NONE;
2049   }
2050 }
2051
2052 static void
2053 gst_pulsesink_sink_info_cb (pa_context * c, const pa_sink_info * i, int eol,
2054     void *userdata)
2055 {
2056   GstPulseDeviceInfo *device_info = (GstPulseDeviceInfo *) userdata;
2057   guint8 j;
2058
2059   if (!i)
2060     goto done;
2061
2062   device_info->description = g_strdup (i->description);
2063
2064   device_info->formats = NULL;
2065   for (j = 0; j < i->n_formats; j++)
2066     device_info->formats = g_list_prepend (device_info->formats,
2067         pa_format_info_copy (i->formats[j]));
2068
2069 done:
2070   pa_threaded_mainloop_signal (mainloop, 0);
2071 }
2072
2073 /* Call with mainloop lock held */
2074 static pa_stream *
2075 gst_pulsesink_create_probe_stream (GstPulseSink * psink,
2076     GstPulseRingBuffer * pbuf, pa_format_info * format)
2077 {
2078   pa_format_info *formats[1] = { format };
2079   pa_stream *stream;
2080   pa_stream_flags_t flags;
2081
2082   GST_LOG_OBJECT (psink, "Creating probe stream");
2083
2084   if (!(stream = pa_stream_new_extended (pbuf->context, "pulsesink probe",
2085               formats, 1, psink->proplist)))
2086     goto error;
2087
2088   /* construct the flags */
2089   flags = PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE |
2090       PA_STREAM_ADJUST_LATENCY | PA_STREAM_START_CORKED;
2091
2092   pa_stream_set_state_callback (stream, gst_pulsering_stream_state_cb, pbuf);
2093
2094   if (pa_stream_connect_playback (stream, psink->device, NULL, flags, NULL,
2095           NULL) < 0)
2096     goto error;
2097
2098   if (!gst_pulsering_wait_for_stream_ready (psink, stream))
2099     goto error;
2100
2101   return stream;
2102
2103 error:
2104   if (stream)
2105     pa_stream_unref (stream);
2106   return NULL;
2107 }
2108
2109 static GstCaps *
2110 gst_pulsesink_query_getcaps (GstPulseSink * psink, GstCaps * filter)
2111 {
2112   GstPulseRingBuffer *pbuf = NULL;
2113   GstPulseDeviceInfo device_info = { NULL, NULL };
2114   GstCaps *ret = NULL;
2115   GList *i;
2116   pa_operation *o = NULL;
2117   pa_stream *stream;
2118
2119   GST_OBJECT_LOCK (psink);
2120   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2121   if (pbuf != NULL)
2122     gst_object_ref (pbuf);
2123   GST_OBJECT_UNLOCK (psink);
2124
2125   if (!pbuf) {
2126     ret = gst_pad_get_pad_template_caps (GST_AUDIO_BASE_SINK_PAD (psink));
2127     goto out;
2128   }
2129
2130   GST_OBJECT_LOCK (pbuf);
2131   pa_threaded_mainloop_lock (mainloop);
2132
2133   if (!pbuf->context) {
2134     ret = gst_pad_get_pad_template_caps (GST_AUDIO_BASE_SINK_PAD (psink));
2135     goto unlock;
2136   }
2137
2138   ret = gst_caps_new_empty ();
2139
2140   if (pbuf->stream) {
2141     /* We're in PAUSED or higher */
2142     stream = pbuf->stream;
2143
2144   } else if (pbuf->probe_stream) {
2145     /* We're not paused, but have a cached probe stream */
2146     stream = pbuf->probe_stream;
2147
2148   } else {
2149     /* We're not yet in PAUSED and still need to create a probe stream.
2150      *
2151      * FIXME: PA doesn't accept "any" format. We fix something reasonable since
2152      * this is merely a probe. This should eventually be fixed in PA and
2153      * hard-coding the format should be dropped. */
2154     pa_format_info *format = pa_format_info_new ();
2155     format->encoding = PA_ENCODING_PCM;
2156     pa_format_info_set_sample_format (format, PA_SAMPLE_S16LE);
2157     pa_format_info_set_rate (format, GST_AUDIO_DEF_RATE);
2158     pa_format_info_set_channels (format, GST_AUDIO_DEF_CHANNELS);
2159
2160     pbuf->probe_stream = gst_pulsesink_create_probe_stream (psink, pbuf,
2161         format);
2162
2163     pa_format_info_free (format);
2164
2165     if (!pbuf->probe_stream) {
2166       GST_WARNING_OBJECT (psink, "Could not create probe stream");
2167       goto unlock;
2168     }
2169
2170     stream = pbuf->probe_stream;
2171   }
2172
2173   if (!(o = pa_context_get_sink_info_by_name (pbuf->context,
2174               pa_stream_get_device_name (stream), gst_pulsesink_sink_info_cb,
2175               &device_info)))
2176     goto info_failed;
2177
2178   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2179     pa_threaded_mainloop_wait (mainloop);
2180     if (gst_pulsering_is_dead (psink, pbuf, FALSE))
2181       goto unlock;
2182   }
2183
2184   for (i = g_list_first (device_info.formats); i; i = g_list_next (i)) {
2185     gst_caps_append (ret,
2186         gst_pulse_format_info_to_caps ((pa_format_info *) i->data));
2187   }
2188
2189 unlock:
2190   pa_threaded_mainloop_unlock (mainloop);
2191   /* FIXME: this could be freed after device_name is got */
2192   GST_OBJECT_UNLOCK (pbuf);
2193
2194   if (filter) {
2195     GstCaps *tmp = gst_caps_intersect_full (filter, ret,
2196         GST_CAPS_INTERSECT_FIRST);
2197     gst_caps_unref (ret);
2198     ret = tmp;
2199   }
2200
2201 out:
2202   free_device_info (&device_info);
2203
2204   if (o)
2205     pa_operation_unref (o);
2206
2207   if (pbuf)
2208     gst_object_unref (pbuf);
2209
2210   GST_DEBUG_OBJECT (psink, "caps %" GST_PTR_FORMAT, ret);
2211
2212   return ret;
2213
2214 info_failed:
2215   {
2216     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2217         ("pa_context_get_sink_input_info() failed: %s",
2218             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2219     goto unlock;
2220   }
2221 }
2222
2223 static gboolean
2224 gst_pulsesink_query_acceptcaps (GstPulseSink * psink, GstCaps * caps)
2225 {
2226   GstPulseRingBuffer *pbuf = NULL;
2227   GstPulseDeviceInfo device_info = { NULL, NULL };
2228   GstCaps *pad_caps;
2229   GstStructure *st;
2230   gboolean ret = FALSE;
2231
2232   GstAudioRingBufferSpec spec = { 0 };
2233   pa_operation *o = NULL;
2234   pa_channel_map channel_map;
2235   pa_format_info *format = NULL;
2236   guint channels;
2237
2238   pad_caps = gst_pad_get_pad_template_caps (GST_BASE_SINK_PAD (psink));
2239   ret = gst_caps_is_subset (caps, pad_caps);
2240   gst_caps_unref (pad_caps);
2241
2242   GST_DEBUG_OBJECT (psink, "caps %" GST_PTR_FORMAT, caps);
2243
2244   /* Template caps didn't match */
2245   if (!ret)
2246     goto done;
2247
2248   /* If we've not got fixed caps, creating a stream might fail, so let's just
2249    * return from here with default acceptcaps behaviour */
2250   if (!gst_caps_is_fixed (caps))
2251     goto done;
2252
2253   GST_OBJECT_LOCK (psink);
2254   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2255   if (pbuf != NULL)
2256     gst_object_ref (pbuf);
2257   GST_OBJECT_UNLOCK (psink);
2258
2259   /* We're still in NULL state */
2260   if (pbuf == NULL)
2261     goto done;
2262
2263   GST_OBJECT_LOCK (pbuf);
2264   pa_threaded_mainloop_lock (mainloop);
2265
2266   if (pbuf->context == NULL)
2267     goto out;
2268
2269   ret = FALSE;
2270
2271   spec.latency_time = GST_AUDIO_BASE_SINK (psink)->latency_time;
2272   if (!gst_audio_ring_buffer_parse_caps (&spec, caps))
2273     goto out;
2274
2275   if (!gst_pulse_fill_format_info (&spec, &format, &channels))
2276     goto out;
2277
2278   /* Make sure input is framed (one frame per buffer) and can be payloaded */
2279   if (!pa_format_info_is_pcm (format)) {
2280     gboolean framed = FALSE, parsed = FALSE;
2281     st = gst_caps_get_structure (caps, 0);
2282
2283     gst_structure_get_boolean (st, "framed", &framed);
2284     gst_structure_get_boolean (st, "parsed", &parsed);
2285     if ((!framed && !parsed) || gst_audio_iec61937_frame_size (&spec) <= 0)
2286       goto out;
2287   }
2288
2289   /* initialize the channel map */
2290   if (pa_format_info_is_pcm (format) &&
2291       gst_pulse_gst_to_channel_map (&channel_map, &spec))
2292     pa_format_info_set_channel_map (format, &channel_map);
2293
2294   if (pbuf->stream || pbuf->probe_stream) {
2295     /* We're already in PAUSED or above, so just reuse this stream to query
2296      * sink formats and use those. */
2297     GList *i;
2298     const char *device_name = pa_stream_get_device_name (pbuf->stream ?
2299         pbuf->stream : pbuf->probe_stream);
2300
2301     if (!(o = pa_context_get_sink_info_by_name (pbuf->context, device_name,
2302                 gst_pulsesink_sink_info_cb, &device_info)))
2303       goto info_failed;
2304
2305     while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2306       pa_threaded_mainloop_wait (mainloop);
2307       if (gst_pulsering_is_dead (psink, pbuf, FALSE))
2308         goto out;
2309     }
2310
2311     for (i = g_list_first (device_info.formats); i; i = g_list_next (i)) {
2312       if (pa_format_info_is_compatible ((pa_format_info *) i->data, format)) {
2313         ret = TRUE;
2314         break;
2315       }
2316     }
2317   } else {
2318     /* We're in READY, let's connect a stream to see if the format is
2319      * accepted by whatever sink we're routed to */
2320     pbuf->probe_stream = gst_pulsesink_create_probe_stream (psink, pbuf,
2321         format);
2322     if (pbuf->probe_stream)
2323       ret = TRUE;
2324   }
2325
2326 out:
2327   if (format)
2328     pa_format_info_free (format);
2329
2330   free_device_info (&device_info);
2331
2332   if (o)
2333     pa_operation_unref (o);
2334
2335   pa_threaded_mainloop_unlock (mainloop);
2336   GST_OBJECT_UNLOCK (pbuf);
2337
2338   gst_caps_replace (&spec.caps, NULL);
2339   gst_object_unref (pbuf);
2340
2341 done:
2342
2343   return ret;
2344
2345 info_failed:
2346   {
2347     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2348         ("pa_context_get_sink_input_info() failed: %s",
2349             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2350     goto out;
2351   }
2352 }
2353
2354 static void
2355 gst_pulsesink_init (GstPulseSink * pulsesink)
2356 {
2357   pulsesink->server = NULL;
2358   pulsesink->device = NULL;
2359   pulsesink->device_info.description = NULL;
2360   pulsesink->client_name = gst_pulse_client_name ();
2361
2362   pulsesink->device_info.formats = NULL;
2363
2364   pulsesink->volume = DEFAULT_VOLUME;
2365   pulsesink->volume_set = FALSE;
2366
2367   pulsesink->mute = DEFAULT_MUTE;
2368   pulsesink->mute_set = FALSE;
2369
2370   pulsesink->notify = 0;
2371
2372   g_atomic_int_set (&pulsesink->format_lost, FALSE);
2373   pulsesink->format_lost_time = GST_CLOCK_TIME_NONE;
2374
2375   pulsesink->properties = NULL;
2376   pulsesink->proplist = NULL;
2377
2378   /* override with a custom clock */
2379   if (GST_AUDIO_BASE_SINK (pulsesink)->provided_clock)
2380     gst_object_unref (GST_AUDIO_BASE_SINK (pulsesink)->provided_clock);
2381
2382   GST_AUDIO_BASE_SINK (pulsesink)->provided_clock =
2383       gst_audio_clock_new ("GstPulseSinkClock",
2384       (GstAudioClockGetTimeFunc) gst_pulsesink_get_time, pulsesink, NULL);
2385 }
2386
2387 static void
2388 gst_pulsesink_finalize (GObject * object)
2389 {
2390   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
2391
2392   g_free (pulsesink->server);
2393   g_free (pulsesink->device);
2394   g_free (pulsesink->client_name);
2395   g_free (pulsesink->current_sink_name);
2396
2397   free_device_info (&pulsesink->device_info);
2398
2399   if (pulsesink->properties)
2400     gst_structure_free (pulsesink->properties);
2401   if (pulsesink->proplist)
2402     pa_proplist_free (pulsesink->proplist);
2403
2404   G_OBJECT_CLASS (parent_class)->finalize (object);
2405 }
2406
2407 static void
2408 gst_pulsesink_set_volume (GstPulseSink * psink, gdouble volume)
2409 {
2410   pa_cvolume v;
2411   pa_operation *o = NULL;
2412   GstPulseRingBuffer *pbuf;
2413   uint32_t idx;
2414
2415   if (!mainloop)
2416     goto no_mainloop;
2417
2418   pa_threaded_mainloop_lock (mainloop);
2419
2420   GST_DEBUG_OBJECT (psink, "setting volume to %f", volume);
2421
2422   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2423   if (pbuf == NULL || pbuf->stream == NULL)
2424     goto no_buffer;
2425
2426   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2427     goto no_index;
2428
2429   if (pbuf->is_pcm)
2430     gst_pulse_cvolume_from_linear (&v, pbuf->channels, volume);
2431   else
2432     /* FIXME: this will eventually be superceded by checks to see if the volume
2433      * is readable/writable */
2434     goto unlock;
2435
2436   if (!(o = pa_context_set_sink_input_volume (pbuf->context, idx,
2437               &v, NULL, NULL)))
2438     goto volume_failed;
2439
2440   /* We don't really care about the result of this call */
2441 unlock:
2442
2443   if (o)
2444     pa_operation_unref (o);
2445
2446   pa_threaded_mainloop_unlock (mainloop);
2447
2448   return;
2449
2450   /* ERRORS */
2451 no_mainloop:
2452   {
2453     psink->volume = volume;
2454     psink->volume_set = TRUE;
2455
2456     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2457     return;
2458   }
2459 no_buffer:
2460   {
2461     psink->volume = volume;
2462     psink->volume_set = TRUE;
2463
2464     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2465     goto unlock;
2466   }
2467 no_index:
2468   {
2469     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2470     goto unlock;
2471   }
2472 volume_failed:
2473   {
2474     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2475         ("pa_stream_set_sink_input_volume() failed: %s",
2476             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2477     goto unlock;
2478   }
2479 }
2480
2481 static void
2482 gst_pulsesink_set_mute (GstPulseSink * psink, gboolean mute)
2483 {
2484   pa_operation *o = NULL;
2485   GstPulseRingBuffer *pbuf;
2486   uint32_t idx;
2487
2488   if (!mainloop)
2489     goto no_mainloop;
2490
2491   pa_threaded_mainloop_lock (mainloop);
2492
2493   GST_DEBUG_OBJECT (psink, "setting mute state to %d", mute);
2494
2495   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2496   if (pbuf == NULL || pbuf->stream == NULL)
2497     goto no_buffer;
2498
2499   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2500     goto no_index;
2501
2502   if (!(o = pa_context_set_sink_input_mute (pbuf->context, idx,
2503               mute, NULL, NULL)))
2504     goto mute_failed;
2505
2506   /* We don't really care about the result of this call */
2507 unlock:
2508
2509   if (o)
2510     pa_operation_unref (o);
2511
2512   pa_threaded_mainloop_unlock (mainloop);
2513
2514   return;
2515
2516   /* ERRORS */
2517 no_mainloop:
2518   {
2519     psink->mute = mute;
2520     psink->mute_set = TRUE;
2521
2522     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2523     return;
2524   }
2525 no_buffer:
2526   {
2527     psink->mute = mute;
2528     psink->mute_set = TRUE;
2529
2530     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2531     goto unlock;
2532   }
2533 no_index:
2534   {
2535     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2536     goto unlock;
2537   }
2538 mute_failed:
2539   {
2540     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2541         ("pa_stream_set_sink_input_mute() failed: %s",
2542             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2543     goto unlock;
2544   }
2545 }
2546
2547 static void
2548 gst_pulsesink_sink_input_info_cb (pa_context * c, const pa_sink_input_info * i,
2549     int eol, void *userdata)
2550 {
2551   GstPulseRingBuffer *pbuf;
2552   GstPulseSink *psink;
2553
2554   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
2555   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
2556
2557   if (!i)
2558     goto done;
2559
2560   if (!pbuf->stream)
2561     goto done;
2562
2563   /* If the index doesn't match our current stream,
2564    * it implies we just recreated the stream (caps change)
2565    */
2566   if (i->index == pa_stream_get_index (pbuf->stream)) {
2567     psink->volume = pa_sw_volume_to_linear (pa_cvolume_max (&i->volume));
2568     psink->mute = i->mute;
2569     psink->current_sink_idx = i->sink;
2570
2571     if (psink->volume > MAX_VOLUME) {
2572       GST_WARNING_OBJECT (psink, "Clipped volume from %f to %f", psink->volume,
2573           MAX_VOLUME);
2574       psink->volume = MAX_VOLUME;
2575     }
2576   }
2577
2578 done:
2579   pa_threaded_mainloop_signal (mainloop, 0);
2580 }
2581
2582 static void
2583 gst_pulsesink_get_sink_input_info (GstPulseSink * psink, gdouble * volume,
2584     gboolean * mute)
2585 {
2586   GstPulseRingBuffer *pbuf;
2587   pa_operation *o = NULL;
2588   uint32_t idx;
2589
2590   if (!mainloop)
2591     goto no_mainloop;
2592
2593   pa_threaded_mainloop_lock (mainloop);
2594
2595   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2596   if (pbuf == NULL || pbuf->stream == NULL)
2597     goto no_buffer;
2598
2599   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2600     goto no_index;
2601
2602   if (!(o = pa_context_get_sink_input_info (pbuf->context, idx,
2603               gst_pulsesink_sink_input_info_cb, pbuf)))
2604     goto info_failed;
2605
2606   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2607     pa_threaded_mainloop_wait (mainloop);
2608     if (gst_pulsering_is_dead (psink, pbuf, TRUE))
2609       goto unlock;
2610   }
2611
2612 unlock:
2613   if (volume)
2614     *volume = psink->volume;
2615   if (mute)
2616     *mute = psink->mute;
2617
2618   if (o)
2619     pa_operation_unref (o);
2620
2621   pa_threaded_mainloop_unlock (mainloop);
2622
2623   return;
2624
2625   /* ERRORS */
2626 no_mainloop:
2627   {
2628     if (volume)
2629       *volume = psink->volume;
2630     if (mute)
2631       *mute = psink->mute;
2632
2633     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2634     return;
2635   }
2636 no_buffer:
2637   {
2638     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2639     goto unlock;
2640   }
2641 no_index:
2642   {
2643     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2644     goto unlock;
2645   }
2646 info_failed:
2647   {
2648     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2649         ("pa_context_get_sink_input_info() failed: %s",
2650             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2651     goto unlock;
2652   }
2653 }
2654
2655 static void
2656 gst_pulsesink_current_sink_info_cb (pa_context * c, const pa_sink_info * i,
2657     int eol, void *userdata)
2658 {
2659   GstPulseSink *psink;
2660
2661   psink = GST_PULSESINK_CAST (userdata);
2662
2663   if (!i)
2664     goto done;
2665
2666   /* If the index doesn't match our current stream,
2667    * it implies we just recreated the stream (caps change)
2668    */
2669   if (i->index == psink->current_sink_idx) {
2670     g_free (psink->current_sink_name);
2671     psink->current_sink_name = g_strdup (i->name);
2672   }
2673
2674 done:
2675   pa_threaded_mainloop_signal (mainloop, 0);
2676 }
2677
2678 static gchar *
2679 gst_pulsesink_get_current_device (GstPulseSink * pulsesink)
2680 {
2681   pa_operation *o = NULL;
2682   GstPulseRingBuffer *pbuf;
2683   gchar *current_sink;
2684
2685   if (!mainloop)
2686     goto no_mainloop;
2687
2688   pbuf =
2689       GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (pulsesink)->ringbuffer);
2690   if (pbuf == NULL || pbuf->stream == NULL)
2691     goto no_buffer;
2692
2693   gst_pulsesink_get_sink_input_info (pulsesink, NULL, NULL);
2694
2695   pa_threaded_mainloop_lock (mainloop);
2696
2697   if (!(o = pa_context_get_sink_info_by_index (pbuf->context,
2698               pulsesink->current_sink_idx, gst_pulsesink_current_sink_info_cb,
2699               pulsesink)))
2700     goto info_failed;
2701
2702   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2703     pa_threaded_mainloop_wait (mainloop);
2704     if (gst_pulsering_is_dead (pulsesink, pbuf, TRUE))
2705       goto unlock;
2706   }
2707
2708 unlock:
2709
2710   current_sink = g_strdup (pulsesink->current_sink_name);
2711
2712   if (o)
2713     pa_operation_unref (o);
2714
2715   pa_threaded_mainloop_unlock (mainloop);
2716
2717   return current_sink;
2718
2719   /* ERRORS */
2720 no_mainloop:
2721   {
2722     GST_DEBUG_OBJECT (pulsesink, "we have no mainloop");
2723     return NULL;
2724   }
2725 no_buffer:
2726   {
2727     GST_DEBUG_OBJECT (pulsesink, "we have no ringbuffer");
2728     return NULL;
2729   }
2730 info_failed:
2731   {
2732     GST_ELEMENT_ERROR (pulsesink, RESOURCE, FAILED,
2733         ("pa_context_get_sink_input_info() failed: %s",
2734             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2735     goto unlock;
2736   }
2737 }
2738
2739 static gchar *
2740 gst_pulsesink_device_description (GstPulseSink * psink)
2741 {
2742   GstPulseRingBuffer *pbuf;
2743   pa_operation *o = NULL;
2744   gchar *t;
2745
2746   if (!mainloop)
2747     goto no_mainloop;
2748
2749   pa_threaded_mainloop_lock (mainloop);
2750   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2751   if (pbuf == NULL)
2752     goto no_buffer;
2753
2754   free_device_info (&psink->device_info);
2755   if (!(o = pa_context_get_sink_info_by_name (pbuf->context,
2756               psink->device, gst_pulsesink_sink_info_cb, &psink->device_info)))
2757     goto info_failed;
2758
2759   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2760     pa_threaded_mainloop_wait (mainloop);
2761     if (gst_pulsering_is_dead (psink, pbuf, FALSE))
2762       goto unlock;
2763   }
2764
2765 unlock:
2766   if (o)
2767     pa_operation_unref (o);
2768
2769   t = g_strdup (psink->device_info.description);
2770   pa_threaded_mainloop_unlock (mainloop);
2771
2772   return t;
2773
2774   /* ERRORS */
2775 no_mainloop:
2776   {
2777     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2778     return NULL;
2779   }
2780 no_buffer:
2781   {
2782     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2783     goto unlock;
2784   }
2785 info_failed:
2786   {
2787     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2788         ("pa_context_get_sink_info_by_index() failed: %s",
2789             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2790     goto unlock;
2791   }
2792 }
2793
2794 static void
2795 gst_pulsesink_set_stream_device (GstPulseSink * psink, const gchar * device)
2796 {
2797   pa_operation *o = NULL;
2798   GstPulseRingBuffer *pbuf;
2799   uint32_t idx;
2800
2801   if (!mainloop)
2802     goto no_mainloop;
2803
2804   pa_threaded_mainloop_lock (mainloop);
2805
2806   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2807   if (pbuf == NULL || pbuf->stream == NULL)
2808     goto no_buffer;
2809
2810   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2811     goto no_index;
2812
2813
2814   GST_DEBUG_OBJECT (psink, "setting stream device to %s", device);
2815
2816   if (!(o = pa_context_move_sink_input_by_name (pbuf->context, idx, device,
2817               NULL, NULL)))
2818     goto move_failed;
2819
2820 unlock:
2821
2822   if (o)
2823     pa_operation_unref (o);
2824
2825   pa_threaded_mainloop_unlock (mainloop);
2826
2827   return;
2828
2829   /* ERRORS */
2830 no_mainloop:
2831   {
2832     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2833     return;
2834   }
2835 no_buffer:
2836   {
2837     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2838     goto unlock;
2839   }
2840 no_index:
2841   {
2842     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2843     return;
2844   }
2845 move_failed:
2846   {
2847     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2848         ("pa_context_move_sink_input_by_name(%s) failed: %s", device,
2849             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2850     goto unlock;
2851   }
2852 }
2853
2854
2855 static void
2856 gst_pulsesink_set_property (GObject * object,
2857     guint prop_id, const GValue * value, GParamSpec * pspec)
2858 {
2859   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
2860
2861   switch (prop_id) {
2862     case PROP_SERVER:
2863       g_free (pulsesink->server);
2864       pulsesink->server = g_value_dup_string (value);
2865       break;
2866     case PROP_DEVICE:
2867       g_free (pulsesink->device);
2868       pulsesink->device = g_value_dup_string (value);
2869       gst_pulsesink_set_stream_device (pulsesink, pulsesink->device);
2870       break;
2871     case PROP_VOLUME:
2872       gst_pulsesink_set_volume (pulsesink, g_value_get_double (value));
2873       break;
2874     case PROP_MUTE:
2875       gst_pulsesink_set_mute (pulsesink, g_value_get_boolean (value));
2876       break;
2877     case PROP_CLIENT_NAME:
2878       g_free (pulsesink->client_name);
2879       if (!g_value_get_string (value)) {
2880         GST_WARNING_OBJECT (pulsesink,
2881             "Empty PulseAudio client name not allowed. Resetting to default value");
2882         pulsesink->client_name = gst_pulse_client_name ();
2883       } else
2884         pulsesink->client_name = g_value_dup_string (value);
2885       break;
2886     case PROP_STREAM_PROPERTIES:
2887       if (pulsesink->properties)
2888         gst_structure_free (pulsesink->properties);
2889       pulsesink->properties =
2890           gst_structure_copy (gst_value_get_structure (value));
2891       if (pulsesink->proplist)
2892         pa_proplist_free (pulsesink->proplist);
2893       pulsesink->proplist = gst_pulse_make_proplist (pulsesink->properties);
2894       break;
2895     default:
2896       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2897       break;
2898   }
2899 }
2900
2901 static void
2902 gst_pulsesink_get_property (GObject * object,
2903     guint prop_id, GValue * value, GParamSpec * pspec)
2904 {
2905
2906   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
2907
2908   switch (prop_id) {
2909     case PROP_SERVER:
2910       g_value_set_string (value, pulsesink->server);
2911       break;
2912     case PROP_DEVICE:
2913       g_value_set_string (value, pulsesink->device);
2914       break;
2915     case PROP_CURRENT_DEVICE:
2916     {
2917       gchar *current_device = gst_pulsesink_get_current_device (pulsesink);
2918       if (current_device)
2919         g_value_take_string (value, current_device);
2920       else
2921         g_value_set_string (value, "");
2922       break;
2923     }
2924     case PROP_DEVICE_NAME:
2925       g_value_take_string (value, gst_pulsesink_device_description (pulsesink));
2926       break;
2927     case PROP_VOLUME:
2928     {
2929       gdouble volume;
2930
2931       gst_pulsesink_get_sink_input_info (pulsesink, &volume, NULL);
2932       g_value_set_double (value, volume);
2933       break;
2934     }
2935     case PROP_MUTE:
2936     {
2937       gboolean mute;
2938
2939       gst_pulsesink_get_sink_input_info (pulsesink, NULL, &mute);
2940       g_value_set_boolean (value, mute);
2941       break;
2942     }
2943     case PROP_CLIENT_NAME:
2944       g_value_set_string (value, pulsesink->client_name);
2945       break;
2946     case PROP_STREAM_PROPERTIES:
2947       gst_value_set_structure (value, pulsesink->properties);
2948       break;
2949     default:
2950       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2951       break;
2952   }
2953 }
2954
2955 static void
2956 gst_pulsesink_change_title (GstPulseSink * psink, const gchar * t)
2957 {
2958   pa_operation *o = NULL;
2959   GstPulseRingBuffer *pbuf;
2960
2961   pa_threaded_mainloop_lock (mainloop);
2962
2963   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2964
2965   if (pbuf == NULL || pbuf->stream == NULL)
2966     goto no_buffer;
2967
2968   g_free (pbuf->stream_name);
2969   pbuf->stream_name = g_strdup (t);
2970
2971   if (!(o = pa_stream_set_name (pbuf->stream, pbuf->stream_name, NULL, NULL)))
2972     goto name_failed;
2973
2974   /* We're not interested if this operation failed or not */
2975 unlock:
2976
2977   if (o)
2978     pa_operation_unref (o);
2979   pa_threaded_mainloop_unlock (mainloop);
2980
2981   return;
2982
2983   /* ERRORS */
2984 no_buffer:
2985   {
2986     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2987     goto unlock;
2988   }
2989 name_failed:
2990   {
2991     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2992         ("pa_stream_set_name() failed: %s",
2993             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2994     goto unlock;
2995   }
2996 }
2997
2998 static void
2999 gst_pulsesink_change_props (GstPulseSink * psink, GstTagList * l)
3000 {
3001   static const gchar *const map[] = {
3002     GST_TAG_TITLE, PA_PROP_MEDIA_TITLE,
3003
3004     /* might get overriden in the next iteration by GST_TAG_ARTIST */
3005     GST_TAG_PERFORMER, PA_PROP_MEDIA_ARTIST,
3006
3007     GST_TAG_ARTIST, PA_PROP_MEDIA_ARTIST,
3008     GST_TAG_LANGUAGE_CODE, PA_PROP_MEDIA_LANGUAGE,
3009     GST_TAG_LOCATION, PA_PROP_MEDIA_FILENAME,
3010     /* We might add more here later on ... */
3011     NULL
3012   };
3013   pa_proplist *pl = NULL;
3014   const gchar *const *t;
3015   gboolean empty = TRUE;
3016   pa_operation *o = NULL;
3017   GstPulseRingBuffer *pbuf;
3018
3019   pl = pa_proplist_new ();
3020
3021   for (t = map; *t; t += 2) {
3022     gchar *n = NULL;
3023
3024     if (gst_tag_list_get_string (l, *t, &n)) {
3025
3026       if (n && *n) {
3027         pa_proplist_sets (pl, *(t + 1), n);
3028         empty = FALSE;
3029       }
3030
3031       g_free (n);
3032     }
3033   }
3034   if (empty)
3035     goto finish;
3036
3037   pa_threaded_mainloop_lock (mainloop);
3038   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
3039   if (pbuf == NULL || pbuf->stream == NULL)
3040     goto no_buffer;
3041
3042   /* We're not interested if this operation failed or not */
3043   if (!(o = pa_stream_proplist_update (pbuf->stream, PA_UPDATE_REPLACE,
3044               pl, NULL, NULL))) {
3045     GST_DEBUG_OBJECT (psink, "pa_stream_proplist_update() failed");
3046   }
3047
3048 unlock:
3049
3050   if (o)
3051     pa_operation_unref (o);
3052
3053   pa_threaded_mainloop_unlock (mainloop);
3054
3055 finish:
3056
3057   if (pl)
3058     pa_proplist_free (pl);
3059
3060   return;
3061
3062   /* ERRORS */
3063 no_buffer:
3064   {
3065     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
3066     goto unlock;
3067   }
3068 }
3069
3070 static void
3071 gst_pulsesink_flush_ringbuffer (GstPulseSink * psink)
3072 {
3073   GstPulseRingBuffer *pbuf;
3074
3075   pa_threaded_mainloop_lock (mainloop);
3076
3077   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
3078
3079   if (pbuf == NULL || pbuf->stream == NULL)
3080     goto no_buffer;
3081
3082   gst_pulsering_flush (pbuf);
3083
3084   /* Uncork if we haven't already (happens when waiting to get enough data
3085    * to send out the first time) */
3086   if (pbuf->corked)
3087     gst_pulsering_set_corked (pbuf, FALSE, FALSE);
3088
3089   /* We're not interested if this operation failed or not */
3090 unlock:
3091   pa_threaded_mainloop_unlock (mainloop);
3092
3093   return;
3094
3095   /* ERRORS */
3096 no_buffer:
3097   {
3098     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
3099     goto unlock;
3100   }
3101 }
3102
3103 static gboolean
3104 gst_pulsesink_event (GstBaseSink * sink, GstEvent * event)
3105 {
3106   GstPulseSink *pulsesink = GST_PULSESINK_CAST (sink);
3107
3108   switch (GST_EVENT_TYPE (event)) {
3109     case GST_EVENT_TAG:{
3110       gchar *title = NULL, *artist = NULL, *location = NULL, *description =
3111           NULL, *t = NULL, *buf = NULL;
3112       GstTagList *l;
3113
3114       gst_event_parse_tag (event, &l);
3115
3116       gst_tag_list_get_string (l, GST_TAG_TITLE, &title);
3117       gst_tag_list_get_string (l, GST_TAG_ARTIST, &artist);
3118       gst_tag_list_get_string (l, GST_TAG_LOCATION, &location);
3119       gst_tag_list_get_string (l, GST_TAG_DESCRIPTION, &description);
3120
3121       if (!artist)
3122         gst_tag_list_get_string (l, GST_TAG_PERFORMER, &artist);
3123
3124       if (title && artist)
3125         /* TRANSLATORS: 'song title' by 'artist name' */
3126         t = buf = g_strdup_printf (_("'%s' by '%s'"), g_strstrip (title),
3127             g_strstrip (artist));
3128       else if (title)
3129         t = g_strstrip (title);
3130       else if (description)
3131         t = g_strstrip (description);
3132       else if (location)
3133         t = g_strstrip (location);
3134
3135       if (t)
3136         gst_pulsesink_change_title (pulsesink, t);
3137
3138       g_free (title);
3139       g_free (artist);
3140       g_free (location);
3141       g_free (description);
3142       g_free (buf);
3143
3144       gst_pulsesink_change_props (pulsesink, l);
3145
3146       break;
3147     }
3148     case GST_EVENT_GAP:{
3149       GstClockTime timestamp, duration;
3150
3151       gst_event_parse_gap (event, &timestamp, &duration);
3152       if (duration == GST_CLOCK_TIME_NONE)
3153         gst_pulsesink_flush_ringbuffer (pulsesink);
3154       break;
3155     }
3156     case GST_EVENT_EOS:
3157       gst_pulsesink_flush_ringbuffer (pulsesink);
3158       break;
3159     default:
3160       ;
3161   }
3162
3163   return GST_BASE_SINK_CLASS (parent_class)->event (sink, event);
3164 }
3165
3166 static gboolean
3167 gst_pulsesink_query (GstBaseSink * sink, GstQuery * query)
3168 {
3169   GstPulseSink *pulsesink = GST_PULSESINK_CAST (sink);
3170   gboolean ret = FALSE;
3171
3172   switch (GST_QUERY_TYPE (query)) {
3173     case GST_QUERY_CAPS:
3174     {
3175       GstCaps *caps, *filter;
3176
3177       gst_query_parse_caps (query, &filter);
3178       caps = gst_pulsesink_query_getcaps (pulsesink, filter);
3179
3180       if (caps) {
3181         gst_query_set_caps_result (query, caps);
3182         gst_caps_unref (caps);
3183         ret = TRUE;
3184       }
3185       break;
3186     }
3187     case GST_QUERY_ACCEPT_CAPS:
3188     {
3189       GstCaps *caps;
3190
3191       gst_query_parse_accept_caps (query, &caps);
3192       ret = gst_pulsesink_query_acceptcaps (pulsesink, caps);
3193       gst_query_set_accept_caps_result (query, ret);
3194       ret = TRUE;
3195       break;
3196     }
3197     default:
3198       ret = GST_BASE_SINK_CLASS (parent_class)->query (sink, query);
3199       break;
3200   }
3201   return ret;
3202 }
3203
3204 static void
3205 gst_pulsesink_release_mainloop (GstPulseSink * psink)
3206 {
3207   if (!mainloop)
3208     return;
3209
3210   pa_threaded_mainloop_lock (mainloop);
3211   while (psink->defer_pending) {
3212     GST_DEBUG_OBJECT (psink, "waiting for stream status message emission");
3213     pa_threaded_mainloop_wait (mainloop);
3214   }
3215   pa_threaded_mainloop_unlock (mainloop);
3216
3217   g_mutex_lock (&pa_shared_resource_mutex);
3218   mainloop_ref_ct--;
3219   if (!mainloop_ref_ct) {
3220     GST_INFO_OBJECT (psink, "terminating pa main loop thread");
3221     pa_threaded_mainloop_stop (mainloop);
3222     pa_threaded_mainloop_free (mainloop);
3223     mainloop = NULL;
3224   }
3225   g_mutex_unlock (&pa_shared_resource_mutex);
3226 }
3227
3228 static GstStateChangeReturn
3229 gst_pulsesink_change_state (GstElement * element, GstStateChange transition)
3230 {
3231   GstPulseSink *pulsesink = GST_PULSESINK (element);
3232   GstStateChangeReturn ret;
3233
3234   switch (transition) {
3235     case GST_STATE_CHANGE_NULL_TO_READY:
3236       g_mutex_lock (&pa_shared_resource_mutex);
3237       if (!mainloop_ref_ct) {
3238         GST_INFO_OBJECT (element, "new pa main loop thread");
3239         if (!(mainloop = pa_threaded_mainloop_new ()))
3240           goto mainloop_failed;
3241         if (pa_threaded_mainloop_start (mainloop) < 0) {
3242           pa_threaded_mainloop_free (mainloop);
3243           goto mainloop_start_failed;
3244         }
3245         mainloop_ref_ct = 1;
3246         g_mutex_unlock (&pa_shared_resource_mutex);
3247       } else {
3248         GST_INFO_OBJECT (element, "reusing pa main loop thread");
3249         mainloop_ref_ct++;
3250         g_mutex_unlock (&pa_shared_resource_mutex);
3251       }
3252       break;
3253     case GST_STATE_CHANGE_READY_TO_PAUSED:
3254       gst_element_post_message (element,
3255           gst_message_new_clock_provide (GST_OBJECT_CAST (element),
3256               GST_AUDIO_BASE_SINK (pulsesink)->provided_clock, TRUE));
3257       break;
3258
3259     default:
3260       break;
3261   }
3262
3263   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3264   if (ret == GST_STATE_CHANGE_FAILURE)
3265     goto state_failure;
3266
3267   switch (transition) {
3268     case GST_STATE_CHANGE_PAUSED_TO_READY:
3269       /* format_lost is reset in release() in audiobasesink */
3270       gst_element_post_message (element,
3271           gst_message_new_clock_lost (GST_OBJECT_CAST (element),
3272               GST_AUDIO_BASE_SINK (pulsesink)->provided_clock));
3273       break;
3274     case GST_STATE_CHANGE_READY_TO_NULL:
3275       gst_pulsesink_release_mainloop (pulsesink);
3276       break;
3277     default:
3278       break;
3279   }
3280
3281   return ret;
3282
3283   /* ERRORS */
3284 mainloop_failed:
3285   {
3286     g_mutex_unlock (&pa_shared_resource_mutex);
3287     GST_ELEMENT_ERROR (pulsesink, RESOURCE, FAILED,
3288         ("pa_threaded_mainloop_new() failed"), (NULL));
3289     return GST_STATE_CHANGE_FAILURE;
3290   }
3291 mainloop_start_failed:
3292   {
3293     g_mutex_unlock (&pa_shared_resource_mutex);
3294     GST_ELEMENT_ERROR (pulsesink, RESOURCE, FAILED,
3295         ("pa_threaded_mainloop_start() failed"), (NULL));
3296     return GST_STATE_CHANGE_FAILURE;
3297   }
3298 state_failure:
3299   {
3300     if (transition == GST_STATE_CHANGE_NULL_TO_READY) {
3301       /* Clear the PA mainloop if audiobasesink failed to open the ring_buffer */
3302       g_assert (mainloop);
3303       gst_pulsesink_release_mainloop (pulsesink);
3304     }
3305     return ret;
3306   }
3307 }