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