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