Move stereo plugin from -bad
[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 #define gst_pulsesink_parent_class parent_class
1819 G_DEFINE_TYPE_WITH_CODE (GstPulseSink, gst_pulsesink, GST_TYPE_AUDIO_BASE_SINK,
1820     gst_pulsesink_init_contexts ();
1821     G_IMPLEMENT_INTERFACE (GST_TYPE_STREAM_VOLUME, NULL)
1822     );
1823
1824 static GstAudioRingBuffer *
1825 gst_pulsesink_create_ringbuffer (GstAudioBaseSink * sink)
1826 {
1827   GstAudioRingBuffer *buffer;
1828
1829   GST_DEBUG_OBJECT (sink, "creating ringbuffer");
1830   buffer = g_object_new (GST_TYPE_PULSERING_BUFFER, NULL);
1831   GST_DEBUG_OBJECT (sink, "created ringbuffer @%p", buffer);
1832
1833   return buffer;
1834 }
1835
1836 static GstBuffer *
1837 gst_pulsesink_payload (GstAudioBaseSink * sink, GstBuffer * buf)
1838 {
1839   switch (sink->ringbuffer->spec.type) {
1840     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_AC3:
1841     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_EAC3:
1842     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_DTS:
1843     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_MPEG:
1844     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_MPEG2_AAC:
1845     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_MPEG4_AAC:
1846     {
1847       /* FIXME: alloc memory from PA if possible */
1848       gint framesize = gst_audio_iec61937_frame_size (&sink->ringbuffer->spec);
1849       GstBuffer *out;
1850       GstMapInfo inmap, outmap;
1851       gboolean res;
1852
1853       if (framesize <= 0)
1854         return NULL;
1855
1856       out = gst_buffer_new_and_alloc (framesize);
1857
1858       gst_buffer_map (buf, &inmap, GST_MAP_READ);
1859       gst_buffer_map (out, &outmap, GST_MAP_WRITE);
1860
1861       res = gst_audio_iec61937_payload (inmap.data, inmap.size,
1862           outmap.data, outmap.size, &sink->ringbuffer->spec, G_BIG_ENDIAN);
1863
1864       gst_buffer_unmap (buf, &inmap);
1865       gst_buffer_unmap (out, &outmap);
1866
1867       if (!res) {
1868         gst_buffer_unref (out);
1869         return NULL;
1870       }
1871
1872       gst_buffer_copy_into (out, buf, GST_BUFFER_COPY_METADATA, 0, -1);
1873       return out;
1874     }
1875
1876     default:
1877       return gst_buffer_ref (buf);
1878   }
1879 }
1880
1881 static void
1882 gst_pulsesink_class_init (GstPulseSinkClass * klass)
1883 {
1884   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1885   GstBaseSinkClass *gstbasesink_class = GST_BASE_SINK_CLASS (klass);
1886   GstBaseSinkClass *bc;
1887   GstAudioBaseSinkClass *gstaudiosink_class = GST_AUDIO_BASE_SINK_CLASS (klass);
1888   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
1889   GstCaps *caps;
1890   gchar *clientname;
1891
1892   gobject_class->finalize = gst_pulsesink_finalize;
1893   gobject_class->set_property = gst_pulsesink_set_property;
1894   gobject_class->get_property = gst_pulsesink_get_property;
1895
1896   gstbasesink_class->event = GST_DEBUG_FUNCPTR (gst_pulsesink_event);
1897   gstbasesink_class->query = GST_DEBUG_FUNCPTR (gst_pulsesink_query);
1898
1899   /* restore the original basesink pull methods */
1900   bc = g_type_class_peek (GST_TYPE_BASE_SINK);
1901   gstbasesink_class->activate_pull = GST_DEBUG_FUNCPTR (bc->activate_pull);
1902
1903   gstelement_class->change_state =
1904       GST_DEBUG_FUNCPTR (gst_pulsesink_change_state);
1905
1906   gstaudiosink_class->create_ringbuffer =
1907       GST_DEBUG_FUNCPTR (gst_pulsesink_create_ringbuffer);
1908   gstaudiosink_class->payload = GST_DEBUG_FUNCPTR (gst_pulsesink_payload);
1909
1910   /* Overwrite GObject fields */
1911   g_object_class_install_property (gobject_class,
1912       PROP_SERVER,
1913       g_param_spec_string ("server", "Server",
1914           "The PulseAudio server to connect to", DEFAULT_SERVER,
1915           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1916
1917   g_object_class_install_property (gobject_class, PROP_DEVICE,
1918       g_param_spec_string ("device", "Device",
1919           "The PulseAudio sink device to connect to", DEFAULT_DEVICE,
1920           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1921
1922   g_object_class_install_property (gobject_class, PROP_CURRENT_DEVICE,
1923       g_param_spec_string ("current-device", "Current Device",
1924           "The current PulseAudio sink device", DEFAULT_CURRENT_DEVICE,
1925           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
1926
1927   g_object_class_install_property (gobject_class,
1928       PROP_DEVICE_NAME,
1929       g_param_spec_string ("device-name", "Device name",
1930           "Human-readable name of the sound device", DEFAULT_DEVICE_NAME,
1931           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
1932
1933   g_object_class_install_property (gobject_class,
1934       PROP_VOLUME,
1935       g_param_spec_double ("volume", "Volume",
1936           "Linear volume of this stream, 1.0=100%", 0.0, MAX_VOLUME,
1937           DEFAULT_VOLUME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1938   g_object_class_install_property (gobject_class,
1939       PROP_MUTE,
1940       g_param_spec_boolean ("mute", "Mute",
1941           "Mute state of this stream", DEFAULT_MUTE,
1942           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1943
1944   /**
1945    * GstPulseSink:client-name:
1946    *
1947    * The PulseAudio client name to use.
1948    */
1949   clientname = gst_pulse_client_name ();
1950   g_object_class_install_property (gobject_class,
1951       PROP_CLIENT_NAME,
1952       g_param_spec_string ("client-name", "Client Name",
1953           "The PulseAudio client name to use", clientname,
1954           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
1955           GST_PARAM_MUTABLE_READY));
1956   g_free (clientname);
1957
1958   /**
1959    * GstPulseSink:stream-properties:
1960    *
1961    * List of pulseaudio stream properties. A list of defined properties can be
1962    * found in the <ulink url="http://0pointer.de/lennart/projects/pulseaudio/doxygen/proplist_8h.html">pulseaudio api docs</ulink>.
1963    *
1964    * Below is an example for registering as a music application to pulseaudio.
1965    * |[
1966    * GstStructure *props;
1967    *
1968    * props = gst_structure_from_string ("props,media.role=music", NULL);
1969    * g_object_set (pulse, "stream-properties", props, NULL);
1970    * gst_structure_free
1971    * ]|
1972    */
1973   g_object_class_install_property (gobject_class,
1974       PROP_STREAM_PROPERTIES,
1975       g_param_spec_boxed ("stream-properties", "stream properties",
1976           "list of pulseaudio stream properties",
1977           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1978
1979   gst_element_class_set_static_metadata (gstelement_class,
1980       "PulseAudio Audio Sink",
1981       "Sink/Audio", "Plays audio to a PulseAudio server", "Lennart Poettering");
1982
1983   caps =
1984       gst_pulse_fix_pcm_caps (gst_caps_from_string (PULSE_SINK_TEMPLATE_CAPS));
1985   gst_element_class_add_pad_template (gstelement_class,
1986       gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, caps));
1987   gst_caps_unref (caps);
1988 }
1989
1990 static void
1991 free_device_info (GstPulseDeviceInfo * device_info)
1992 {
1993   GList *l;
1994
1995   g_free (device_info->description);
1996
1997   for (l = g_list_first (device_info->formats); l; l = g_list_next (l))
1998     pa_format_info_free ((pa_format_info *) l->data);
1999
2000   g_list_free (device_info->formats);
2001 }
2002
2003 /* Returns the current time of the sink ringbuffer. The timing_info is updated
2004  * on every data write/flush and every 100ms (PA_STREAM_AUTO_TIMING_UPDATE).
2005  */
2006 static GstClockTime
2007 gst_pulsesink_get_time (GstClock * clock, GstAudioBaseSink * sink)
2008 {
2009   GstPulseSink *psink;
2010   GstPulseRingBuffer *pbuf;
2011   pa_usec_t time;
2012
2013   if (!sink->ringbuffer || !sink->ringbuffer->acquired)
2014     return GST_CLOCK_TIME_NONE;
2015
2016   pbuf = GST_PULSERING_BUFFER_CAST (sink->ringbuffer);
2017   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
2018
2019   if (g_atomic_int_get (&psink->format_lost)) {
2020     /* Stream was lost in a format change, it'll get set up again once
2021      * upstream renegotiates */
2022     return psink->format_lost_time;
2023   }
2024
2025   pa_threaded_mainloop_lock (mainloop);
2026   if (gst_pulsering_is_dead (psink, pbuf, TRUE))
2027     goto server_dead;
2028
2029   /* if we don't have enough data to get a timestamp, just return NONE, which
2030    * will return the last reported time */
2031   if (pa_stream_get_time (pbuf->stream, &time) < 0) {
2032     GST_DEBUG_OBJECT (psink, "could not get time");
2033     time = GST_CLOCK_TIME_NONE;
2034   } else
2035     time *= 1000;
2036   pa_threaded_mainloop_unlock (mainloop);
2037
2038   GST_LOG_OBJECT (psink, "current time is %" GST_TIME_FORMAT,
2039       GST_TIME_ARGS (time));
2040
2041   return time;
2042
2043   /* ERRORS */
2044 server_dead:
2045   {
2046     GST_DEBUG_OBJECT (psink, "the server is dead");
2047     pa_threaded_mainloop_unlock (mainloop);
2048
2049     return GST_CLOCK_TIME_NONE;
2050   }
2051 }
2052
2053 static void
2054 gst_pulsesink_sink_info_cb (pa_context * c, const pa_sink_info * i, int eol,
2055     void *userdata)
2056 {
2057   GstPulseDeviceInfo *device_info = (GstPulseDeviceInfo *) userdata;
2058   guint8 j;
2059
2060   if (!i)
2061     goto done;
2062
2063   device_info->description = g_strdup (i->description);
2064
2065   device_info->formats = NULL;
2066   for (j = 0; j < i->n_formats; j++)
2067     device_info->formats = g_list_prepend (device_info->formats,
2068         pa_format_info_copy (i->formats[j]));
2069
2070 done:
2071   pa_threaded_mainloop_signal (mainloop, 0);
2072 }
2073
2074 /* Call with mainloop lock held */
2075 static pa_stream *
2076 gst_pulsesink_create_probe_stream (GstPulseSink * psink,
2077     GstPulseRingBuffer * pbuf, pa_format_info * format)
2078 {
2079   pa_format_info *formats[1] = { format };
2080   pa_stream *stream;
2081   pa_stream_flags_t flags;
2082
2083   GST_LOG_OBJECT (psink, "Creating probe stream");
2084
2085   if (!(stream = pa_stream_new_extended (pbuf->context, "pulsesink probe",
2086               formats, 1, psink->proplist)))
2087     goto error;
2088
2089   /* construct the flags */
2090   flags = PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE |
2091       PA_STREAM_ADJUST_LATENCY | PA_STREAM_START_CORKED;
2092
2093   pa_stream_set_state_callback (stream, gst_pulsering_stream_state_cb, pbuf);
2094
2095   if (pa_stream_connect_playback (stream, psink->device, NULL, flags, NULL,
2096           NULL) < 0)
2097     goto error;
2098
2099   if (!gst_pulsering_wait_for_stream_ready (psink, stream))
2100     goto error;
2101
2102   return stream;
2103
2104 error:
2105   if (stream)
2106     pa_stream_unref (stream);
2107   return NULL;
2108 }
2109
2110 static GstCaps *
2111 gst_pulsesink_query_getcaps (GstPulseSink * psink, GstCaps * filter)
2112 {
2113   GstPulseRingBuffer *pbuf = NULL;
2114   GstPulseDeviceInfo device_info = { NULL, NULL };
2115   GstCaps *ret = NULL;
2116   GList *i;
2117   pa_operation *o = NULL;
2118   pa_stream *stream;
2119
2120   GST_OBJECT_LOCK (psink);
2121   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2122   if (pbuf != NULL)
2123     gst_object_ref (pbuf);
2124   GST_OBJECT_UNLOCK (psink);
2125
2126   if (!pbuf) {
2127     ret = gst_pad_get_pad_template_caps (GST_AUDIO_BASE_SINK_PAD (psink));
2128     goto out;
2129   }
2130
2131   GST_OBJECT_LOCK (pbuf);
2132   pa_threaded_mainloop_lock (mainloop);
2133
2134   if (!pbuf->context) {
2135     ret = gst_pad_get_pad_template_caps (GST_AUDIO_BASE_SINK_PAD (psink));
2136     goto unlock;
2137   }
2138
2139   ret = gst_caps_new_empty ();
2140
2141   if (pbuf->stream) {
2142     /* We're in PAUSED or higher */
2143     stream = pbuf->stream;
2144
2145   } else if (pbuf->probe_stream) {
2146     /* We're not paused, but have a cached probe stream */
2147     stream = pbuf->probe_stream;
2148
2149   } else {
2150     /* We're not yet in PAUSED and still need to create a probe stream.
2151      *
2152      * FIXME: PA doesn't accept "any" format. We fix something reasonable since
2153      * this is merely a probe. This should eventually be fixed in PA and
2154      * hard-coding the format should be dropped. */
2155     pa_format_info *format = pa_format_info_new ();
2156     format->encoding = PA_ENCODING_PCM;
2157     pa_format_info_set_sample_format (format, PA_SAMPLE_S16LE);
2158     pa_format_info_set_rate (format, GST_AUDIO_DEF_RATE);
2159     pa_format_info_set_channels (format, GST_AUDIO_DEF_CHANNELS);
2160
2161     pbuf->probe_stream = gst_pulsesink_create_probe_stream (psink, pbuf,
2162         format);
2163
2164     pa_format_info_free (format);
2165
2166     if (!pbuf->probe_stream) {
2167       GST_WARNING_OBJECT (psink, "Could not create probe stream");
2168       goto unlock;
2169     }
2170
2171     stream = pbuf->probe_stream;
2172   }
2173
2174   if (!(o = pa_context_get_sink_info_by_name (pbuf->context,
2175               pa_stream_get_device_name (stream), gst_pulsesink_sink_info_cb,
2176               &device_info)))
2177     goto info_failed;
2178
2179   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2180     pa_threaded_mainloop_wait (mainloop);
2181     if (gst_pulsering_is_dead (psink, pbuf, FALSE))
2182       goto unlock;
2183   }
2184
2185   for (i = g_list_first (device_info.formats); i; i = g_list_next (i)) {
2186     gst_caps_append (ret,
2187         gst_pulse_format_info_to_caps ((pa_format_info *) i->data));
2188   }
2189
2190 unlock:
2191   pa_threaded_mainloop_unlock (mainloop);
2192   /* FIXME: this could be freed after device_name is got */
2193   GST_OBJECT_UNLOCK (pbuf);
2194
2195   if (filter) {
2196     GstCaps *tmp = gst_caps_intersect_full (filter, ret,
2197         GST_CAPS_INTERSECT_FIRST);
2198     gst_caps_unref (ret);
2199     ret = tmp;
2200   }
2201
2202 out:
2203   free_device_info (&device_info);
2204
2205   if (o)
2206     pa_operation_unref (o);
2207
2208   if (pbuf)
2209     gst_object_unref (pbuf);
2210
2211   GST_DEBUG_OBJECT (psink, "caps %" GST_PTR_FORMAT, ret);
2212
2213   return ret;
2214
2215 info_failed:
2216   {
2217     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2218         ("pa_context_get_sink_input_info() failed: %s",
2219             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2220     goto unlock;
2221   }
2222 }
2223
2224 static gboolean
2225 gst_pulsesink_query_acceptcaps (GstPulseSink * psink, GstCaps * caps)
2226 {
2227   GstPulseRingBuffer *pbuf = NULL;
2228   GstPulseDeviceInfo device_info = { NULL, NULL };
2229   GstCaps *pad_caps;
2230   GstStructure *st;
2231   gboolean ret = FALSE;
2232
2233   GstAudioRingBufferSpec spec = { 0 };
2234   pa_operation *o = NULL;
2235   pa_channel_map channel_map;
2236   pa_format_info *format = NULL;
2237   guint channels;
2238
2239   pad_caps = gst_pad_get_pad_template_caps (GST_BASE_SINK_PAD (psink));
2240   ret = gst_caps_is_subset (caps, pad_caps);
2241   gst_caps_unref (pad_caps);
2242
2243   GST_DEBUG_OBJECT (psink, "caps %" GST_PTR_FORMAT, caps);
2244
2245   /* Template caps didn't match */
2246   if (!ret)
2247     goto done;
2248
2249   /* If we've not got fixed caps, creating a stream might fail, so let's just
2250    * return from here with default acceptcaps behaviour */
2251   if (!gst_caps_is_fixed (caps))
2252     goto done;
2253
2254   GST_OBJECT_LOCK (psink);
2255   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2256   if (pbuf != NULL)
2257     gst_object_ref (pbuf);
2258   GST_OBJECT_UNLOCK (psink);
2259
2260   /* We're still in NULL state */
2261   if (pbuf == NULL)
2262     goto done;
2263
2264   GST_OBJECT_LOCK (pbuf);
2265   pa_threaded_mainloop_lock (mainloop);
2266
2267   if (pbuf->context == NULL)
2268     goto out;
2269
2270   ret = FALSE;
2271
2272   spec.latency_time = GST_AUDIO_BASE_SINK (psink)->latency_time;
2273   if (!gst_audio_ring_buffer_parse_caps (&spec, caps))
2274     goto out;
2275
2276   if (!gst_pulse_fill_format_info (&spec, &format, &channels))
2277     goto out;
2278
2279   /* Make sure input is framed (one frame per buffer) and can be payloaded */
2280   if (!pa_format_info_is_pcm (format)) {
2281     gboolean framed = FALSE, parsed = FALSE;
2282     st = gst_caps_get_structure (caps, 0);
2283
2284     gst_structure_get_boolean (st, "framed", &framed);
2285     gst_structure_get_boolean (st, "parsed", &parsed);
2286     if ((!framed && !parsed) || gst_audio_iec61937_frame_size (&spec) <= 0)
2287       goto out;
2288   }
2289
2290   /* initialize the channel map */
2291   if (pa_format_info_is_pcm (format) &&
2292       gst_pulse_gst_to_channel_map (&channel_map, &spec))
2293     pa_format_info_set_channel_map (format, &channel_map);
2294
2295   if (pbuf->stream || pbuf->probe_stream) {
2296     /* We're already in PAUSED or above, so just reuse this stream to query
2297      * sink formats and use those. */
2298     GList *i;
2299     const char *device_name = pa_stream_get_device_name (pbuf->stream ?
2300         pbuf->stream : pbuf->probe_stream);
2301
2302     if (!(o = pa_context_get_sink_info_by_name (pbuf->context, device_name,
2303                 gst_pulsesink_sink_info_cb, &device_info)))
2304       goto info_failed;
2305
2306     while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2307       pa_threaded_mainloop_wait (mainloop);
2308       if (gst_pulsering_is_dead (psink, pbuf, FALSE))
2309         goto out;
2310     }
2311
2312     for (i = g_list_first (device_info.formats); i; i = g_list_next (i)) {
2313       if (pa_format_info_is_compatible ((pa_format_info *) i->data, format)) {
2314         ret = TRUE;
2315         break;
2316       }
2317     }
2318   } else {
2319     /* We're in READY, let's connect a stream to see if the format is
2320      * accepted by whatever sink we're routed to */
2321     pbuf->probe_stream = gst_pulsesink_create_probe_stream (psink, pbuf,
2322         format);
2323     if (pbuf->probe_stream)
2324       ret = TRUE;
2325   }
2326
2327 out:
2328   if (format)
2329     pa_format_info_free (format);
2330
2331   free_device_info (&device_info);
2332
2333   if (o)
2334     pa_operation_unref (o);
2335
2336   pa_threaded_mainloop_unlock (mainloop);
2337   GST_OBJECT_UNLOCK (pbuf);
2338
2339   gst_caps_replace (&spec.caps, NULL);
2340   gst_object_unref (pbuf);
2341
2342 done:
2343
2344   return ret;
2345
2346 info_failed:
2347   {
2348     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2349         ("pa_context_get_sink_input_info() failed: %s",
2350             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2351     goto out;
2352   }
2353 }
2354
2355 static void
2356 gst_pulsesink_init (GstPulseSink * pulsesink)
2357 {
2358   pulsesink->server = NULL;
2359   pulsesink->device = NULL;
2360   pulsesink->device_info.description = NULL;
2361   pulsesink->client_name = gst_pulse_client_name ();
2362
2363   pulsesink->device_info.formats = NULL;
2364
2365   pulsesink->volume = DEFAULT_VOLUME;
2366   pulsesink->volume_set = FALSE;
2367
2368   pulsesink->mute = DEFAULT_MUTE;
2369   pulsesink->mute_set = FALSE;
2370
2371   pulsesink->notify = 0;
2372
2373   g_atomic_int_set (&pulsesink->format_lost, FALSE);
2374   pulsesink->format_lost_time = GST_CLOCK_TIME_NONE;
2375
2376   pulsesink->properties = NULL;
2377   pulsesink->proplist = NULL;
2378
2379   /* override with a custom clock */
2380   if (GST_AUDIO_BASE_SINK (pulsesink)->provided_clock)
2381     gst_object_unref (GST_AUDIO_BASE_SINK (pulsesink)->provided_clock);
2382
2383   GST_AUDIO_BASE_SINK (pulsesink)->provided_clock =
2384       gst_audio_clock_new ("GstPulseSinkClock",
2385       (GstAudioClockGetTimeFunc) gst_pulsesink_get_time, pulsesink, NULL);
2386 }
2387
2388 static void
2389 gst_pulsesink_finalize (GObject * object)
2390 {
2391   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
2392
2393   g_free (pulsesink->server);
2394   g_free (pulsesink->device);
2395   g_free (pulsesink->client_name);
2396   g_free (pulsesink->current_sink_name);
2397
2398   free_device_info (&pulsesink->device_info);
2399
2400   if (pulsesink->properties)
2401     gst_structure_free (pulsesink->properties);
2402   if (pulsesink->proplist)
2403     pa_proplist_free (pulsesink->proplist);
2404
2405   G_OBJECT_CLASS (parent_class)->finalize (object);
2406 }
2407
2408 static void
2409 gst_pulsesink_set_volume (GstPulseSink * psink, gdouble volume)
2410 {
2411   pa_cvolume v;
2412   pa_operation *o = NULL;
2413   GstPulseRingBuffer *pbuf;
2414   uint32_t idx;
2415
2416   if (!mainloop)
2417     goto no_mainloop;
2418
2419   pa_threaded_mainloop_lock (mainloop);
2420
2421   GST_DEBUG_OBJECT (psink, "setting volume to %f", volume);
2422
2423   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2424   if (pbuf == NULL || pbuf->stream == NULL)
2425     goto no_buffer;
2426
2427   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2428     goto no_index;
2429
2430   if (pbuf->is_pcm)
2431     gst_pulse_cvolume_from_linear (&v, pbuf->channels, volume);
2432   else
2433     /* FIXME: this will eventually be superceded by checks to see if the volume
2434      * is readable/writable */
2435     goto unlock;
2436
2437   if (!(o = pa_context_set_sink_input_volume (pbuf->context, idx,
2438               &v, NULL, NULL)))
2439     goto volume_failed;
2440
2441   /* We don't really care about the result of this call */
2442 unlock:
2443
2444   if (o)
2445     pa_operation_unref (o);
2446
2447   pa_threaded_mainloop_unlock (mainloop);
2448
2449   return;
2450
2451   /* ERRORS */
2452 no_mainloop:
2453   {
2454     psink->volume = volume;
2455     psink->volume_set = TRUE;
2456
2457     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2458     return;
2459   }
2460 no_buffer:
2461   {
2462     psink->volume = volume;
2463     psink->volume_set = TRUE;
2464
2465     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2466     goto unlock;
2467   }
2468 no_index:
2469   {
2470     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2471     goto unlock;
2472   }
2473 volume_failed:
2474   {
2475     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2476         ("pa_stream_set_sink_input_volume() failed: %s",
2477             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2478     goto unlock;
2479   }
2480 }
2481
2482 static void
2483 gst_pulsesink_set_mute (GstPulseSink * psink, gboolean mute)
2484 {
2485   pa_operation *o = NULL;
2486   GstPulseRingBuffer *pbuf;
2487   uint32_t idx;
2488
2489   if (!mainloop)
2490     goto no_mainloop;
2491
2492   pa_threaded_mainloop_lock (mainloop);
2493
2494   GST_DEBUG_OBJECT (psink, "setting mute state to %d", mute);
2495
2496   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2497   if (pbuf == NULL || pbuf->stream == NULL)
2498     goto no_buffer;
2499
2500   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2501     goto no_index;
2502
2503   if (!(o = pa_context_set_sink_input_mute (pbuf->context, idx,
2504               mute, NULL, NULL)))
2505     goto mute_failed;
2506
2507   /* We don't really care about the result of this call */
2508 unlock:
2509
2510   if (o)
2511     pa_operation_unref (o);
2512
2513   pa_threaded_mainloop_unlock (mainloop);
2514
2515   return;
2516
2517   /* ERRORS */
2518 no_mainloop:
2519   {
2520     psink->mute = mute;
2521     psink->mute_set = TRUE;
2522
2523     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2524     return;
2525   }
2526 no_buffer:
2527   {
2528     psink->mute = mute;
2529     psink->mute_set = TRUE;
2530
2531     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2532     goto unlock;
2533   }
2534 no_index:
2535   {
2536     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2537     goto unlock;
2538   }
2539 mute_failed:
2540   {
2541     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2542         ("pa_stream_set_sink_input_mute() failed: %s",
2543             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2544     goto unlock;
2545   }
2546 }
2547
2548 static void
2549 gst_pulsesink_sink_input_info_cb (pa_context * c, const pa_sink_input_info * i,
2550     int eol, void *userdata)
2551 {
2552   GstPulseRingBuffer *pbuf;
2553   GstPulseSink *psink;
2554
2555   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
2556   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
2557
2558   if (!i)
2559     goto done;
2560
2561   if (!pbuf->stream)
2562     goto done;
2563
2564   /* If the index doesn't match our current stream,
2565    * it implies we just recreated the stream (caps change)
2566    */
2567   if (i->index == pa_stream_get_index (pbuf->stream)) {
2568     psink->volume = pa_sw_volume_to_linear (pa_cvolume_max (&i->volume));
2569     psink->mute = i->mute;
2570     psink->current_sink_idx = i->sink;
2571
2572     if (psink->volume > MAX_VOLUME) {
2573       GST_WARNING_OBJECT (psink, "Clipped volume from %f to %f", psink->volume,
2574           MAX_VOLUME);
2575       psink->volume = MAX_VOLUME;
2576     }
2577   }
2578
2579 done:
2580   pa_threaded_mainloop_signal (mainloop, 0);
2581 }
2582
2583 static void
2584 gst_pulsesink_get_sink_input_info (GstPulseSink * psink, gdouble * volume,
2585     gboolean * mute)
2586 {
2587   GstPulseRingBuffer *pbuf;
2588   pa_operation *o = NULL;
2589   uint32_t idx;
2590
2591   if (!mainloop)
2592     goto no_mainloop;
2593
2594   pa_threaded_mainloop_lock (mainloop);
2595
2596   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2597   if (pbuf == NULL || pbuf->stream == NULL)
2598     goto no_buffer;
2599
2600   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2601     goto no_index;
2602
2603   if (!(o = pa_context_get_sink_input_info (pbuf->context, idx,
2604               gst_pulsesink_sink_input_info_cb, pbuf)))
2605     goto info_failed;
2606
2607   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2608     pa_threaded_mainloop_wait (mainloop);
2609     if (gst_pulsering_is_dead (psink, pbuf, TRUE))
2610       goto unlock;
2611   }
2612
2613 unlock:
2614   if (volume)
2615     *volume = psink->volume;
2616   if (mute)
2617     *mute = psink->mute;
2618
2619   if (o)
2620     pa_operation_unref (o);
2621
2622   pa_threaded_mainloop_unlock (mainloop);
2623
2624   return;
2625
2626   /* ERRORS */
2627 no_mainloop:
2628   {
2629     if (volume)
2630       *volume = psink->volume;
2631     if (mute)
2632       *mute = psink->mute;
2633
2634     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2635     return;
2636   }
2637 no_buffer:
2638   {
2639     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2640     goto unlock;
2641   }
2642 no_index:
2643   {
2644     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2645     goto unlock;
2646   }
2647 info_failed:
2648   {
2649     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2650         ("pa_context_get_sink_input_info() failed: %s",
2651             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2652     goto unlock;
2653   }
2654 }
2655
2656 static void
2657 gst_pulsesink_current_sink_info_cb (pa_context * c, const pa_sink_info * i,
2658     int eol, void *userdata)
2659 {
2660   GstPulseSink *psink;
2661
2662   psink = GST_PULSESINK_CAST (userdata);
2663
2664   if (!i)
2665     goto done;
2666
2667   /* If the index doesn't match our current stream,
2668    * it implies we just recreated the stream (caps change)
2669    */
2670   if (i->index == psink->current_sink_idx) {
2671     g_free (psink->current_sink_name);
2672     psink->current_sink_name = g_strdup (i->name);
2673   }
2674
2675 done:
2676   pa_threaded_mainloop_signal (mainloop, 0);
2677 }
2678
2679 static gchar *
2680 gst_pulsesink_get_current_device (GstPulseSink * pulsesink)
2681 {
2682   pa_operation *o = NULL;
2683   GstPulseRingBuffer *pbuf;
2684   gchar *current_sink;
2685
2686   if (!mainloop)
2687     goto no_mainloop;
2688
2689   pbuf =
2690       GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (pulsesink)->ringbuffer);
2691   if (pbuf == NULL || pbuf->stream == NULL)
2692     goto no_buffer;
2693
2694   gst_pulsesink_get_sink_input_info (pulsesink, NULL, NULL);
2695
2696   pa_threaded_mainloop_lock (mainloop);
2697
2698   if (!(o = pa_context_get_sink_info_by_index (pbuf->context,
2699               pulsesink->current_sink_idx, gst_pulsesink_current_sink_info_cb,
2700               pulsesink)))
2701     goto info_failed;
2702
2703   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2704     pa_threaded_mainloop_wait (mainloop);
2705     if (gst_pulsering_is_dead (pulsesink, pbuf, TRUE))
2706       goto unlock;
2707   }
2708
2709 unlock:
2710
2711   current_sink = g_strdup (pulsesink->current_sink_name);
2712
2713   if (o)
2714     pa_operation_unref (o);
2715
2716   pa_threaded_mainloop_unlock (mainloop);
2717
2718   return current_sink;
2719
2720   /* ERRORS */
2721 no_mainloop:
2722   {
2723     GST_DEBUG_OBJECT (pulsesink, "we have no mainloop");
2724     return NULL;
2725   }
2726 no_buffer:
2727   {
2728     GST_DEBUG_OBJECT (pulsesink, "we have no ringbuffer");
2729     return NULL;
2730   }
2731 info_failed:
2732   {
2733     GST_ELEMENT_ERROR (pulsesink, RESOURCE, FAILED,
2734         ("pa_context_get_sink_input_info() failed: %s",
2735             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2736     goto unlock;
2737   }
2738 }
2739
2740 static gchar *
2741 gst_pulsesink_device_description (GstPulseSink * psink)
2742 {
2743   GstPulseRingBuffer *pbuf;
2744   pa_operation *o = NULL;
2745   gchar *t;
2746
2747   if (!mainloop)
2748     goto no_mainloop;
2749
2750   pa_threaded_mainloop_lock (mainloop);
2751   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2752   if (pbuf == NULL)
2753     goto no_buffer;
2754
2755   free_device_info (&psink->device_info);
2756   if (!(o = pa_context_get_sink_info_by_name (pbuf->context,
2757               psink->device, gst_pulsesink_sink_info_cb, &psink->device_info)))
2758     goto info_failed;
2759
2760   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2761     pa_threaded_mainloop_wait (mainloop);
2762     if (gst_pulsering_is_dead (psink, pbuf, FALSE))
2763       goto unlock;
2764   }
2765
2766 unlock:
2767   if (o)
2768     pa_operation_unref (o);
2769
2770   t = g_strdup (psink->device_info.description);
2771   pa_threaded_mainloop_unlock (mainloop);
2772
2773   return t;
2774
2775   /* ERRORS */
2776 no_mainloop:
2777   {
2778     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2779     return NULL;
2780   }
2781 no_buffer:
2782   {
2783     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2784     goto unlock;
2785   }
2786 info_failed:
2787   {
2788     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2789         ("pa_context_get_sink_info_by_index() failed: %s",
2790             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2791     goto unlock;
2792   }
2793 }
2794
2795 static void
2796 gst_pulsesink_set_stream_device (GstPulseSink * psink, const gchar * device)
2797 {
2798   pa_operation *o = NULL;
2799   GstPulseRingBuffer *pbuf;
2800   uint32_t idx;
2801
2802   if (!mainloop)
2803     goto no_mainloop;
2804
2805   pa_threaded_mainloop_lock (mainloop);
2806
2807   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2808   if (pbuf == NULL || pbuf->stream == NULL)
2809     goto no_buffer;
2810
2811   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2812     goto no_index;
2813
2814
2815   GST_DEBUG_OBJECT (psink, "setting stream device to %s", device);
2816
2817   if (!(o = pa_context_move_sink_input_by_name (pbuf->context, idx, device,
2818               NULL, NULL)))
2819     goto move_failed;
2820
2821 unlock:
2822
2823   if (o)
2824     pa_operation_unref (o);
2825
2826   pa_threaded_mainloop_unlock (mainloop);
2827
2828   return;
2829
2830   /* ERRORS */
2831 no_mainloop:
2832   {
2833     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2834     return;
2835   }
2836 no_buffer:
2837   {
2838     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2839     goto unlock;
2840   }
2841 no_index:
2842   {
2843     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2844     return;
2845   }
2846 move_failed:
2847   {
2848     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2849         ("pa_context_move_sink_input_by_name(%s) failed: %s", device,
2850             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2851     goto unlock;
2852   }
2853 }
2854
2855
2856 static void
2857 gst_pulsesink_set_property (GObject * object,
2858     guint prop_id, const GValue * value, GParamSpec * pspec)
2859 {
2860   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
2861
2862   switch (prop_id) {
2863     case PROP_SERVER:
2864       g_free (pulsesink->server);
2865       pulsesink->server = g_value_dup_string (value);
2866       break;
2867     case PROP_DEVICE:
2868       g_free (pulsesink->device);
2869       pulsesink->device = g_value_dup_string (value);
2870       gst_pulsesink_set_stream_device (pulsesink, pulsesink->device);
2871       break;
2872     case PROP_VOLUME:
2873       gst_pulsesink_set_volume (pulsesink, g_value_get_double (value));
2874       break;
2875     case PROP_MUTE:
2876       gst_pulsesink_set_mute (pulsesink, g_value_get_boolean (value));
2877       break;
2878     case PROP_CLIENT_NAME:
2879       g_free (pulsesink->client_name);
2880       if (!g_value_get_string (value)) {
2881         GST_WARNING_OBJECT (pulsesink,
2882             "Empty PulseAudio client name not allowed. Resetting to default value");
2883         pulsesink->client_name = gst_pulse_client_name ();
2884       } else
2885         pulsesink->client_name = g_value_dup_string (value);
2886       break;
2887     case PROP_STREAM_PROPERTIES:
2888       if (pulsesink->properties)
2889         gst_structure_free (pulsesink->properties);
2890       pulsesink->properties =
2891           gst_structure_copy (gst_value_get_structure (value));
2892       if (pulsesink->proplist)
2893         pa_proplist_free (pulsesink->proplist);
2894       pulsesink->proplist = gst_pulse_make_proplist (pulsesink->properties);
2895       break;
2896     default:
2897       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2898       break;
2899   }
2900 }
2901
2902 static void
2903 gst_pulsesink_get_property (GObject * object,
2904     guint prop_id, GValue * value, GParamSpec * pspec)
2905 {
2906
2907   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
2908
2909   switch (prop_id) {
2910     case PROP_SERVER:
2911       g_value_set_string (value, pulsesink->server);
2912       break;
2913     case PROP_DEVICE:
2914       g_value_set_string (value, pulsesink->device);
2915       break;
2916     case PROP_CURRENT_DEVICE:
2917     {
2918       gchar *current_device = gst_pulsesink_get_current_device (pulsesink);
2919       if (current_device)
2920         g_value_take_string (value, current_device);
2921       else
2922         g_value_set_string (value, "");
2923       break;
2924     }
2925     case PROP_DEVICE_NAME:
2926       g_value_take_string (value, gst_pulsesink_device_description (pulsesink));
2927       break;
2928     case PROP_VOLUME:
2929     {
2930       gdouble volume;
2931
2932       gst_pulsesink_get_sink_input_info (pulsesink, &volume, NULL);
2933       g_value_set_double (value, volume);
2934       break;
2935     }
2936     case PROP_MUTE:
2937     {
2938       gboolean mute;
2939
2940       gst_pulsesink_get_sink_input_info (pulsesink, NULL, &mute);
2941       g_value_set_boolean (value, mute);
2942       break;
2943     }
2944     case PROP_CLIENT_NAME:
2945       g_value_set_string (value, pulsesink->client_name);
2946       break;
2947     case PROP_STREAM_PROPERTIES:
2948       gst_value_set_structure (value, pulsesink->properties);
2949       break;
2950     default:
2951       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2952       break;
2953   }
2954 }
2955
2956 static void
2957 gst_pulsesink_change_title (GstPulseSink * psink, const gchar * t)
2958 {
2959   pa_operation *o = NULL;
2960   GstPulseRingBuffer *pbuf;
2961
2962   pa_threaded_mainloop_lock (mainloop);
2963
2964   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2965
2966   if (pbuf == NULL || pbuf->stream == NULL)
2967     goto no_buffer;
2968
2969   g_free (pbuf->stream_name);
2970   pbuf->stream_name = g_strdup (t);
2971
2972   if (!(o = pa_stream_set_name (pbuf->stream, pbuf->stream_name, NULL, NULL)))
2973     goto name_failed;
2974
2975   /* We're not interested if this operation failed or not */
2976 unlock:
2977
2978   if (o)
2979     pa_operation_unref (o);
2980   pa_threaded_mainloop_unlock (mainloop);
2981
2982   return;
2983
2984   /* ERRORS */
2985 no_buffer:
2986   {
2987     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2988     goto unlock;
2989   }
2990 name_failed:
2991   {
2992     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2993         ("pa_stream_set_name() failed: %s",
2994             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2995     goto unlock;
2996   }
2997 }
2998
2999 static void
3000 gst_pulsesink_change_props (GstPulseSink * psink, GstTagList * l)
3001 {
3002   static const gchar *const map[] = {
3003     GST_TAG_TITLE, PA_PROP_MEDIA_TITLE,
3004
3005     /* might get overriden in the next iteration by GST_TAG_ARTIST */
3006     GST_TAG_PERFORMER, PA_PROP_MEDIA_ARTIST,
3007
3008     GST_TAG_ARTIST, PA_PROP_MEDIA_ARTIST,
3009     GST_TAG_LANGUAGE_CODE, PA_PROP_MEDIA_LANGUAGE,
3010     GST_TAG_LOCATION, PA_PROP_MEDIA_FILENAME,
3011     /* We might add more here later on ... */
3012     NULL
3013   };
3014   pa_proplist *pl = NULL;
3015   const gchar *const *t;
3016   gboolean empty = TRUE;
3017   pa_operation *o = NULL;
3018   GstPulseRingBuffer *pbuf;
3019
3020   pl = pa_proplist_new ();
3021
3022   for (t = map; *t; t += 2) {
3023     gchar *n = NULL;
3024
3025     if (gst_tag_list_get_string (l, *t, &n)) {
3026
3027       if (n && *n) {
3028         pa_proplist_sets (pl, *(t + 1), n);
3029         empty = FALSE;
3030       }
3031
3032       g_free (n);
3033     }
3034   }
3035   if (empty)
3036     goto finish;
3037
3038   pa_threaded_mainloop_lock (mainloop);
3039   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
3040   if (pbuf == NULL || pbuf->stream == NULL)
3041     goto no_buffer;
3042
3043   /* We're not interested if this operation failed or not */
3044   if (!(o = pa_stream_proplist_update (pbuf->stream, PA_UPDATE_REPLACE,
3045               pl, NULL, NULL))) {
3046     GST_DEBUG_OBJECT (psink, "pa_stream_proplist_update() failed");
3047   }
3048
3049 unlock:
3050
3051   if (o)
3052     pa_operation_unref (o);
3053
3054   pa_threaded_mainloop_unlock (mainloop);
3055
3056 finish:
3057
3058   if (pl)
3059     pa_proplist_free (pl);
3060
3061   return;
3062
3063   /* ERRORS */
3064 no_buffer:
3065   {
3066     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
3067     goto unlock;
3068   }
3069 }
3070
3071 static void
3072 gst_pulsesink_flush_ringbuffer (GstPulseSink * psink)
3073 {
3074   GstPulseRingBuffer *pbuf;
3075
3076   pa_threaded_mainloop_lock (mainloop);
3077
3078   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
3079
3080   if (pbuf == NULL || pbuf->stream == NULL)
3081     goto no_buffer;
3082
3083   gst_pulsering_flush (pbuf);
3084
3085   /* Uncork if we haven't already (happens when waiting to get enough data
3086    * to send out the first time) */
3087   if (pbuf->corked)
3088     gst_pulsering_set_corked (pbuf, FALSE, FALSE);
3089
3090   /* We're not interested if this operation failed or not */
3091 unlock:
3092   pa_threaded_mainloop_unlock (mainloop);
3093
3094   return;
3095
3096   /* ERRORS */
3097 no_buffer:
3098   {
3099     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
3100     goto unlock;
3101   }
3102 }
3103
3104 static gboolean
3105 gst_pulsesink_event (GstBaseSink * sink, GstEvent * event)
3106 {
3107   GstPulseSink *pulsesink = GST_PULSESINK_CAST (sink);
3108
3109   switch (GST_EVENT_TYPE (event)) {
3110     case GST_EVENT_TAG:{
3111       gchar *title = NULL, *artist = NULL, *location = NULL, *description =
3112           NULL, *t = NULL, *buf = NULL;
3113       GstTagList *l;
3114
3115       gst_event_parse_tag (event, &l);
3116
3117       gst_tag_list_get_string (l, GST_TAG_TITLE, &title);
3118       gst_tag_list_get_string (l, GST_TAG_ARTIST, &artist);
3119       gst_tag_list_get_string (l, GST_TAG_LOCATION, &location);
3120       gst_tag_list_get_string (l, GST_TAG_DESCRIPTION, &description);
3121
3122       if (!artist)
3123         gst_tag_list_get_string (l, GST_TAG_PERFORMER, &artist);
3124
3125       if (title && artist)
3126         /* TRANSLATORS: 'song title' by 'artist name' */
3127         t = buf = g_strdup_printf (_("'%s' by '%s'"), g_strstrip (title),
3128             g_strstrip (artist));
3129       else if (title)
3130         t = g_strstrip (title);
3131       else if (description)
3132         t = g_strstrip (description);
3133       else if (location)
3134         t = g_strstrip (location);
3135
3136       if (t)
3137         gst_pulsesink_change_title (pulsesink, t);
3138
3139       g_free (title);
3140       g_free (artist);
3141       g_free (location);
3142       g_free (description);
3143       g_free (buf);
3144
3145       gst_pulsesink_change_props (pulsesink, l);
3146
3147       break;
3148     }
3149     case GST_EVENT_GAP:{
3150       GstClockTime timestamp, duration;
3151
3152       gst_event_parse_gap (event, &timestamp, &duration);
3153       if (duration == GST_CLOCK_TIME_NONE)
3154         gst_pulsesink_flush_ringbuffer (pulsesink);
3155       break;
3156     }
3157     case GST_EVENT_EOS:
3158       gst_pulsesink_flush_ringbuffer (pulsesink);
3159       break;
3160     default:
3161       ;
3162   }
3163
3164   return GST_BASE_SINK_CLASS (parent_class)->event (sink, event);
3165 }
3166
3167 static gboolean
3168 gst_pulsesink_query (GstBaseSink * sink, GstQuery * query)
3169 {
3170   GstPulseSink *pulsesink = GST_PULSESINK_CAST (sink);
3171   gboolean ret = FALSE;
3172
3173   switch (GST_QUERY_TYPE (query)) {
3174     case GST_QUERY_CAPS:
3175     {
3176       GstCaps *caps, *filter;
3177
3178       gst_query_parse_caps (query, &filter);
3179       caps = gst_pulsesink_query_getcaps (pulsesink, filter);
3180
3181       if (caps) {
3182         gst_query_set_caps_result (query, caps);
3183         gst_caps_unref (caps);
3184         ret = TRUE;
3185       }
3186       break;
3187     }
3188     case GST_QUERY_ACCEPT_CAPS:
3189     {
3190       GstCaps *caps;
3191
3192       gst_query_parse_accept_caps (query, &caps);
3193       ret = gst_pulsesink_query_acceptcaps (pulsesink, caps);
3194       gst_query_set_accept_caps_result (query, ret);
3195       ret = TRUE;
3196       break;
3197     }
3198     default:
3199       ret = GST_BASE_SINK_CLASS (parent_class)->query (sink, query);
3200       break;
3201   }
3202   return ret;
3203 }
3204
3205 static void
3206 gst_pulsesink_release_mainloop (GstPulseSink * psink)
3207 {
3208   if (!mainloop)
3209     return;
3210
3211   pa_threaded_mainloop_lock (mainloop);
3212   while (psink->defer_pending) {
3213     GST_DEBUG_OBJECT (psink, "waiting for stream status message emission");
3214     pa_threaded_mainloop_wait (mainloop);
3215   }
3216   pa_threaded_mainloop_unlock (mainloop);
3217
3218   g_mutex_lock (&pa_shared_resource_mutex);
3219   mainloop_ref_ct--;
3220   if (!mainloop_ref_ct) {
3221     GST_INFO_OBJECT (psink, "terminating pa main loop thread");
3222     pa_threaded_mainloop_stop (mainloop);
3223     pa_threaded_mainloop_free (mainloop);
3224     mainloop = NULL;
3225   }
3226   g_mutex_unlock (&pa_shared_resource_mutex);
3227 }
3228
3229 static GstStateChangeReturn
3230 gst_pulsesink_change_state (GstElement * element, GstStateChange transition)
3231 {
3232   GstPulseSink *pulsesink = GST_PULSESINK (element);
3233   GstStateChangeReturn ret;
3234
3235   switch (transition) {
3236     case GST_STATE_CHANGE_NULL_TO_READY:
3237       g_mutex_lock (&pa_shared_resource_mutex);
3238       if (!mainloop_ref_ct) {
3239         GST_INFO_OBJECT (element, "new pa main loop thread");
3240         if (!(mainloop = pa_threaded_mainloop_new ()))
3241           goto mainloop_failed;
3242         if (pa_threaded_mainloop_start (mainloop) < 0) {
3243           pa_threaded_mainloop_free (mainloop);
3244           goto mainloop_start_failed;
3245         }
3246         mainloop_ref_ct = 1;
3247         g_mutex_unlock (&pa_shared_resource_mutex);
3248       } else {
3249         GST_INFO_OBJECT (element, "reusing pa main loop thread");
3250         mainloop_ref_ct++;
3251         g_mutex_unlock (&pa_shared_resource_mutex);
3252       }
3253       break;
3254     case GST_STATE_CHANGE_READY_TO_PAUSED:
3255       gst_element_post_message (element,
3256           gst_message_new_clock_provide (GST_OBJECT_CAST (element),
3257               GST_AUDIO_BASE_SINK (pulsesink)->provided_clock, TRUE));
3258       break;
3259
3260     default:
3261       break;
3262   }
3263
3264   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3265   if (ret == GST_STATE_CHANGE_FAILURE)
3266     goto state_failure;
3267
3268   switch (transition) {
3269     case GST_STATE_CHANGE_PAUSED_TO_READY:
3270       /* format_lost is reset in release() in audiobasesink */
3271       gst_element_post_message (element,
3272           gst_message_new_clock_lost (GST_OBJECT_CAST (element),
3273               GST_AUDIO_BASE_SINK (pulsesink)->provided_clock));
3274       break;
3275     case GST_STATE_CHANGE_READY_TO_NULL:
3276       gst_pulsesink_release_mainloop (pulsesink);
3277       break;
3278     default:
3279       break;
3280   }
3281
3282   return ret;
3283
3284   /* ERRORS */
3285 mainloop_failed:
3286   {
3287     g_mutex_unlock (&pa_shared_resource_mutex);
3288     GST_ELEMENT_ERROR (pulsesink, RESOURCE, FAILED,
3289         ("pa_threaded_mainloop_new() failed"), (NULL));
3290     return GST_STATE_CHANGE_FAILURE;
3291   }
3292 mainloop_start_failed:
3293   {
3294     g_mutex_unlock (&pa_shared_resource_mutex);
3295     GST_ELEMENT_ERROR (pulsesink, RESOURCE, FAILED,
3296         ("pa_threaded_mainloop_start() failed"), (NULL));
3297     return GST_STATE_CHANGE_FAILURE;
3298   }
3299 state_failure:
3300   {
3301     if (transition == GST_STATE_CHANGE_NULL_TO_READY) {
3302       /* Clear the PA mainloop if audiobasesink failed to open the ring_buffer */
3303       g_assert (mainloop);
3304       gst_pulsesink_release_mainloop (pulsesink);
3305     }
3306     return ret;
3307   }
3308 }