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