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