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