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