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