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 #ifdef HAVE_PULSE_2_0
2020 static gboolean
2021 gst_pulse_format_info_int_prop_to_value (pa_format_info * format,
2022     const char *key, GValue * value)
2023 {
2024   GValue v = { 0, };
2025   int i;
2026   int *a, n;
2027   int min, max;
2028
2029   if (pa_format_info_get_prop_int (format, key, &i) == 0) {
2030     g_value_init (value, G_TYPE_INT);
2031     g_value_set_int (value, i);
2032
2033   } else if (pa_format_info_get_prop_int_array (format, key, &a, &n) == 0) {
2034     g_value_init (value, GST_TYPE_LIST);
2035     g_value_init (&v, G_TYPE_INT);
2036
2037     for (i = 0; i < n; i++) {
2038       g_value_set_int (&v, a[i]);
2039       gst_value_list_append_value (value, &v);
2040     }
2041
2042     pa_xfree (a);
2043
2044   } else if (pa_format_info_get_prop_int_range (format, key, &min, &max) == 0) {
2045     g_value_init (value, GST_TYPE_INT_RANGE);
2046     gst_value_set_int_range (value, min, max);
2047
2048   } else {
2049     /* Property not available or is not an int type */
2050     return FALSE;
2051   }
2052
2053   return TRUE;
2054 }
2055
2056 static GstCaps *
2057 gst_pulse_format_info_to_caps (pa_format_info * format)
2058 {
2059   GstCaps *ret = NULL;
2060   GValue v = { 0, };
2061   pa_sample_spec ss;
2062
2063   switch (format->encoding) {
2064     case PA_ENCODING_PCM:{
2065       char *tmp = NULL;
2066
2067       pa_format_info_to_sample_spec (format, &ss, NULL);
2068
2069       if (pa_format_info_get_prop_string (format,
2070               PA_PROP_FORMAT_SAMPLE_FORMAT, &tmp)) {
2071         /* No specific sample format means any sample format */
2072         ret = gst_caps_from_string (_PULSE_SINK_CAPS_PCM);
2073         goto out;
2074
2075       } else if (ss.format == PA_SAMPLE_ALAW) {
2076         ret = gst_caps_from_string (_PULSE_SINK_CAPS_ALAW);
2077
2078       } else if (ss.format == PA_SAMPLE_ULAW) {
2079         ret = gst_caps_from_string (_PULSE_SINK_CAPS_MP3);
2080
2081       } else {
2082         /* Linear PCM format */
2083         const char *sformat =
2084             gst_pulse_sample_format_to_caps_format (ss.format);
2085
2086         ret = gst_caps_from_string (_PULSE_SINK_CAPS_LINEAR);
2087
2088         if (sformat)
2089           gst_caps_set_simple (ret, "format", G_TYPE_STRING, NULL);
2090       }
2091
2092       pa_xfree (tmp);
2093       break;
2094     }
2095
2096     case PA_ENCODING_AC3_IEC61937:
2097       ret = gst_caps_from_string (_PULSE_SINK_CAPS_AC3);
2098       break;
2099
2100     case PA_ENCODING_EAC3_IEC61937:
2101       ret = gst_caps_from_string (_PULSE_SINK_CAPS_EAC3);
2102       break;
2103
2104     case PA_ENCODING_DTS_IEC61937:
2105       ret = gst_caps_from_string (_PULSE_SINK_CAPS_DTS);
2106       break;
2107
2108     case PA_ENCODING_MPEG_IEC61937:
2109       ret = gst_caps_from_string (_PULSE_SINK_CAPS_MP3);
2110       break;
2111
2112     default:
2113       GST_WARNING ("Found a PA format that we don't support yet");
2114       goto out;
2115   }
2116
2117   if (gst_pulse_format_info_int_prop_to_value (format, PA_PROP_FORMAT_RATE, &v))
2118     gst_caps_set_value (ret, "rate", &v);
2119
2120   g_value_unset (&v);
2121
2122   if (gst_pulse_format_info_int_prop_to_value (format, PA_PROP_FORMAT_CHANNELS,
2123           &v))
2124     gst_caps_set_value (ret, "channels", &v);
2125
2126 out:
2127   return ret;
2128 }
2129 #endif
2130
2131 /* Call with mainloop lock held */
2132 static pa_stream *
2133 gst_pulsesink_create_probe_stream (GstPulseSink * psink,
2134     GstPulseRingBuffer * pbuf, pa_format_info * format)
2135 {
2136   pa_format_info *formats[1] = { format };
2137   pa_stream *stream;
2138   pa_stream_flags_t flags;
2139
2140   GST_LOG_OBJECT (psink, "Creating probe stream");
2141
2142   if (!(stream = pa_stream_new_extended (pbuf->context, "pulsesink probe",
2143               formats, 1, psink->proplist)))
2144     goto error;
2145
2146   /* construct the flags */
2147   flags = PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE |
2148       PA_STREAM_ADJUST_LATENCY | PA_STREAM_START_CORKED;
2149
2150   pa_stream_set_state_callback (stream, gst_pulsering_stream_state_cb, pbuf);
2151
2152   if (pa_stream_connect_playback (stream, psink->device, NULL, flags, NULL,
2153           NULL) < 0)
2154     goto error;
2155
2156   if (!gst_pulsering_wait_for_stream_ready (psink, stream))
2157     goto error;
2158
2159   return stream;
2160
2161 error:
2162   if (stream)
2163     pa_stream_unref (stream);
2164   return NULL;
2165 }
2166
2167 #ifdef HAVE_PULSE_2_0
2168 static GstCaps *
2169 gst_pulsesink_query_getcaps (GstPulseSink * psink, GstCaps * filter)
2170 {
2171   GstPulseRingBuffer *pbuf = NULL;
2172   GstPulseDeviceInfo device_info = { NULL, NULL };
2173   GstCaps *ret = NULL;
2174   GList *i;
2175   pa_operation *o = NULL;
2176   pa_stream *stream;
2177
2178   GST_OBJECT_LOCK (psink);
2179   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2180   if (pbuf != NULL)
2181     gst_object_ref (pbuf);
2182   GST_OBJECT_UNLOCK (psink);
2183
2184   if (!pbuf) {
2185     ret = gst_pad_get_pad_template_caps (GST_AUDIO_BASE_SINK_PAD (psink));
2186     goto out;
2187   }
2188
2189   GST_OBJECT_LOCK (pbuf);
2190   pa_threaded_mainloop_lock (mainloop);
2191
2192   if (!pbuf->context) {
2193     ret = gst_pad_get_pad_template_caps (GST_AUDIO_BASE_SINK_PAD (psink));
2194     goto unlock;
2195   }
2196
2197   if (pbuf->stream) {
2198     /* We're in PAUSED or higher */
2199     stream = pbuf->stream;
2200
2201   } else if (pbuf->probe_stream) {
2202     /* We're not paused, but have a cached probe stream */
2203     stream = pbuf->probe_stream;
2204
2205   } else {
2206     /* We're not yet in PAUSED and still need to create a probe stream.
2207      *
2208      * FIXME: PA doesn't accept "any" format. We fix something reasonable since
2209      * this is merely a probe. This should eventually be fixed in PA and
2210      * hard-coding the format should be dropped. */
2211     pa_format_info *format = pa_format_info_new ();
2212     format->encoding = PA_ENCODING_PCM;
2213     pa_format_info_set_sample_format (format, PA_SAMPLE_S16LE);
2214     pa_format_info_set_rate (format, GST_AUDIO_DEF_RATE);
2215     pa_format_info_set_channels (format, GST_AUDIO_DEF_CHANNELS);
2216
2217     pbuf->probe_stream = gst_pulsesink_create_probe_stream (psink, pbuf,
2218         format);
2219     if (!pbuf->probe_stream) {
2220       GST_WARNING_OBJECT (psink, "Could not create probe stream");
2221       goto unlock;
2222     }
2223
2224     pa_format_info_free (format);
2225
2226     stream = pbuf->probe_stream;
2227   }
2228
2229   ret = gst_caps_new_empty ();
2230
2231   if (!(o = pa_context_get_sink_info_by_name (pbuf->context,
2232               pa_stream_get_device_name (stream), gst_pulsesink_sink_info_cb,
2233               &device_info)))
2234     goto info_failed;
2235
2236   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2237     pa_threaded_mainloop_wait (mainloop);
2238     if (gst_pulsering_is_dead (psink, pbuf, FALSE))
2239       goto unlock;
2240   }
2241
2242   for (i = g_list_first (device_info.formats); i; i = g_list_next (i)) {
2243     gst_caps_append (ret,
2244         gst_pulse_format_info_to_caps ((pa_format_info *) i->data));
2245   }
2246
2247   if (filter) {
2248     GstCaps *tmp = gst_caps_intersect_full (filter, ret,
2249         GST_CAPS_INTERSECT_FIRST);
2250     gst_caps_unref (ret);
2251     ret = tmp;
2252   }
2253
2254 unlock:
2255   pa_threaded_mainloop_unlock (mainloop);
2256   /* FIXME: this could be freed after device_name is got */
2257   GST_OBJECT_UNLOCK (pbuf);
2258
2259 out:
2260   free_device_info (&device_info);
2261
2262   if (o)
2263     pa_operation_unref (o);
2264
2265   if (pbuf)
2266     gst_object_unref (pbuf);
2267
2268   GST_DEBUG_OBJECT (psink, "caps %" GST_PTR_FORMAT, ret);
2269
2270   return ret;
2271
2272 info_failed:
2273   {
2274     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2275         ("pa_context_get_sink_input_info() failed: %s",
2276             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2277     goto unlock;
2278   }
2279 }
2280 #endif
2281
2282 static gboolean
2283 gst_pulsesink_query_acceptcaps (GstPulseSink * psink, GstCaps * caps)
2284 {
2285   GstPulseRingBuffer *pbuf = NULL;
2286   GstPulseDeviceInfo device_info = { NULL, NULL };
2287   GstCaps *pad_caps;
2288   GstStructure *st;
2289   gboolean ret = FALSE;
2290
2291   GstAudioRingBufferSpec spec = { 0 };
2292   pa_operation *o = NULL;
2293   pa_channel_map channel_map;
2294   pa_format_info *format = NULL;
2295   guint channels;
2296
2297   pad_caps = gst_pad_get_pad_template_caps (GST_BASE_SINK_PAD (psink));
2298   ret = gst_caps_is_subset (caps, pad_caps);
2299   gst_caps_unref (pad_caps);
2300
2301   GST_DEBUG_OBJECT (psink, "caps %" GST_PTR_FORMAT, caps);
2302
2303   /* Template caps didn't match */
2304   if (!ret)
2305     goto done;
2306
2307   /* If we've not got fixed caps, creating a stream might fail, so let's just
2308    * return from here with default acceptcaps behaviour */
2309   if (!gst_caps_is_fixed (caps))
2310     goto done;
2311
2312   GST_OBJECT_LOCK (psink);
2313   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2314   if (pbuf != NULL)
2315     gst_object_ref (pbuf);
2316   GST_OBJECT_UNLOCK (psink);
2317
2318   /* We're still in NULL state */
2319   if (pbuf == NULL)
2320     goto done;
2321
2322   GST_OBJECT_LOCK (pbuf);
2323   pa_threaded_mainloop_lock (mainloop);
2324
2325   if (pbuf->context == NULL)
2326     goto out;
2327
2328   ret = FALSE;
2329
2330   spec.latency_time = GST_AUDIO_BASE_SINK (psink)->latency_time;
2331   if (!gst_audio_ring_buffer_parse_caps (&spec, caps))
2332     goto out;
2333
2334   if (!gst_pulse_fill_format_info (&spec, &format, &channels))
2335     goto out;
2336
2337   /* Make sure input is framed (one frame per buffer) and can be payloaded */
2338   if (!pa_format_info_is_pcm (format)) {
2339     gboolean framed = FALSE, parsed = FALSE;
2340     st = gst_caps_get_structure (caps, 0);
2341
2342     gst_structure_get_boolean (st, "framed", &framed);
2343     gst_structure_get_boolean (st, "parsed", &parsed);
2344     if ((!framed && !parsed) || gst_audio_iec61937_frame_size (&spec) <= 0)
2345       goto out;
2346   }
2347
2348   /* initialize the channel map */
2349   if (pa_format_info_is_pcm (format) &&
2350       gst_pulse_gst_to_channel_map (&channel_map, &spec))
2351     pa_format_info_set_channel_map (format, &channel_map);
2352
2353   if (pbuf->stream || pbuf->probe_stream) {
2354     /* We're already in PAUSED or above, so just reuse this stream to query
2355      * sink formats and use those. */
2356     GList *i;
2357     const char *device_name = pa_stream_get_device_name (pbuf->stream ?
2358         pbuf->stream : pbuf->probe_stream);
2359
2360     if (!(o = pa_context_get_sink_info_by_name (pbuf->context, device_name,
2361                 gst_pulsesink_sink_info_cb, &device_info)))
2362       goto info_failed;
2363
2364     while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2365       pa_threaded_mainloop_wait (mainloop);
2366       if (gst_pulsering_is_dead (psink, pbuf, FALSE))
2367         goto out;
2368     }
2369
2370     for (i = g_list_first (device_info.formats); i; i = g_list_next (i)) {
2371       if (pa_format_info_is_compatible ((pa_format_info *) i->data, format)) {
2372         ret = TRUE;
2373         break;
2374       }
2375     }
2376   } else {
2377     /* We're in READY, let's connect a stream to see if the format is
2378      * accepted by whatever sink we're routed to */
2379     pbuf->probe_stream = gst_pulsesink_create_probe_stream (psink, pbuf,
2380         format);
2381     if (pbuf->probe_stream)
2382       ret = TRUE;
2383   }
2384
2385 out:
2386   if (format)
2387     pa_format_info_free (format);
2388
2389   if (o)
2390     pa_operation_unref (o);
2391
2392   pa_threaded_mainloop_unlock (mainloop);
2393   GST_OBJECT_UNLOCK (pbuf);
2394
2395   gst_caps_replace (&spec.caps, NULL);
2396   gst_object_unref (pbuf);
2397
2398 done:
2399
2400   return ret;
2401
2402 info_failed:
2403   {
2404     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2405         ("pa_context_get_sink_input_info() failed: %s",
2406             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2407     goto out;
2408   }
2409 }
2410
2411 static void
2412 gst_pulsesink_init (GstPulseSink * pulsesink)
2413 {
2414   pulsesink->server = NULL;
2415   pulsesink->device = NULL;
2416   pulsesink->device_info.description = NULL;
2417   pulsesink->client_name = gst_pulse_client_name ();
2418
2419   pulsesink->device_info.formats = NULL;
2420
2421   pulsesink->volume = DEFAULT_VOLUME;
2422   pulsesink->volume_set = FALSE;
2423
2424   pulsesink->mute = DEFAULT_MUTE;
2425   pulsesink->mute_set = FALSE;
2426
2427   pulsesink->notify = 0;
2428
2429   g_atomic_int_set (&pulsesink->format_lost, FALSE);
2430   pulsesink->format_lost_time = GST_CLOCK_TIME_NONE;
2431
2432   pulsesink->properties = NULL;
2433   pulsesink->proplist = NULL;
2434
2435   /* override with a custom clock */
2436   if (GST_AUDIO_BASE_SINK (pulsesink)->provided_clock)
2437     gst_object_unref (GST_AUDIO_BASE_SINK (pulsesink)->provided_clock);
2438
2439   GST_AUDIO_BASE_SINK (pulsesink)->provided_clock =
2440       gst_audio_clock_new ("GstPulseSinkClock",
2441       (GstAudioClockGetTimeFunc) gst_pulsesink_get_time, pulsesink, NULL);
2442
2443   /* TRUE for sinks, FALSE for sources */
2444   pulsesink->probe = gst_pulseprobe_new (G_OBJECT (pulsesink),
2445       G_OBJECT_GET_CLASS (pulsesink), PROP_DEVICE, pulsesink->device,
2446       TRUE, FALSE);
2447 }
2448
2449 static void
2450 gst_pulsesink_finalize (GObject * object)
2451 {
2452   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
2453
2454   g_free (pulsesink->server);
2455   g_free (pulsesink->device);
2456   g_free (pulsesink->client_name);
2457
2458   free_device_info (&pulsesink->device_info);
2459
2460   if (pulsesink->properties)
2461     gst_structure_free (pulsesink->properties);
2462   if (pulsesink->proplist)
2463     pa_proplist_free (pulsesink->proplist);
2464
2465   if (pulsesink->probe) {
2466     gst_pulseprobe_free (pulsesink->probe);
2467     pulsesink->probe = NULL;
2468   }
2469
2470   G_OBJECT_CLASS (parent_class)->finalize (object);
2471 }
2472
2473 static void
2474 gst_pulsesink_set_volume (GstPulseSink * psink, gdouble volume)
2475 {
2476   pa_cvolume v;
2477   pa_operation *o = NULL;
2478   GstPulseRingBuffer *pbuf;
2479   uint32_t idx;
2480
2481   if (!mainloop)
2482     goto no_mainloop;
2483
2484   pa_threaded_mainloop_lock (mainloop);
2485
2486   GST_DEBUG_OBJECT (psink, "setting volume to %f", volume);
2487
2488   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2489   if (pbuf == NULL || pbuf->stream == NULL)
2490     goto no_buffer;
2491
2492   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2493     goto no_index;
2494
2495   if (pbuf->is_pcm)
2496     gst_pulse_cvolume_from_linear (&v, pbuf->channels, volume);
2497   else
2498     /* FIXME: this will eventually be superceded by checks to see if the volume
2499      * is readable/writable */
2500     goto unlock;
2501
2502   if (!(o = pa_context_set_sink_input_volume (pbuf->context, idx,
2503               &v, NULL, NULL)))
2504     goto volume_failed;
2505
2506   /* We don't really care about the result of this call */
2507 unlock:
2508
2509   if (o)
2510     pa_operation_unref (o);
2511
2512   pa_threaded_mainloop_unlock (mainloop);
2513
2514   return;
2515
2516   /* ERRORS */
2517 no_mainloop:
2518   {
2519     psink->volume = volume;
2520     psink->volume_set = TRUE;
2521
2522     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2523     return;
2524   }
2525 no_buffer:
2526   {
2527     psink->volume = volume;
2528     psink->volume_set = TRUE;
2529
2530     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2531     goto unlock;
2532   }
2533 no_index:
2534   {
2535     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2536     goto unlock;
2537   }
2538 volume_failed:
2539   {
2540     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2541         ("pa_stream_set_sink_input_volume() failed: %s",
2542             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2543     goto unlock;
2544   }
2545 }
2546
2547 static void
2548 gst_pulsesink_set_mute (GstPulseSink * psink, gboolean mute)
2549 {
2550   pa_operation *o = NULL;
2551   GstPulseRingBuffer *pbuf;
2552   uint32_t idx;
2553
2554   if (!mainloop)
2555     goto no_mainloop;
2556
2557   pa_threaded_mainloop_lock (mainloop);
2558
2559   GST_DEBUG_OBJECT (psink, "setting mute state to %d", mute);
2560
2561   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2562   if (pbuf == NULL || pbuf->stream == NULL)
2563     goto no_buffer;
2564
2565   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2566     goto no_index;
2567
2568   if (!(o = pa_context_set_sink_input_mute (pbuf->context, idx,
2569               mute, NULL, NULL)))
2570     goto mute_failed;
2571
2572   /* We don't really care about the result of this call */
2573 unlock:
2574
2575   if (o)
2576     pa_operation_unref (o);
2577
2578   pa_threaded_mainloop_unlock (mainloop);
2579
2580   return;
2581
2582   /* ERRORS */
2583 no_mainloop:
2584   {
2585     psink->mute = mute;
2586     psink->mute_set = TRUE;
2587
2588     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2589     return;
2590   }
2591 no_buffer:
2592   {
2593     psink->mute = mute;
2594     psink->mute_set = TRUE;
2595
2596     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2597     goto unlock;
2598   }
2599 no_index:
2600   {
2601     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2602     goto unlock;
2603   }
2604 mute_failed:
2605   {
2606     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2607         ("pa_stream_set_sink_input_mute() failed: %s",
2608             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2609     goto unlock;
2610   }
2611 }
2612
2613 static void
2614 gst_pulsesink_sink_input_info_cb (pa_context * c, const pa_sink_input_info * i,
2615     int eol, void *userdata)
2616 {
2617   GstPulseRingBuffer *pbuf;
2618   GstPulseSink *psink;
2619
2620   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
2621   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
2622
2623   if (!i)
2624     goto done;
2625
2626   if (!pbuf->stream)
2627     goto done;
2628
2629   /* If the index doesn't match our current stream,
2630    * it implies we just recreated the stream (caps change)
2631    */
2632   if (i->index == pa_stream_get_index (pbuf->stream)) {
2633     psink->volume = pa_sw_volume_to_linear (pa_cvolume_max (&i->volume));
2634     psink->mute = i->mute;
2635   }
2636
2637 done:
2638   pa_threaded_mainloop_signal (mainloop, 0);
2639 }
2640
2641 static gdouble
2642 gst_pulsesink_get_volume (GstPulseSink * psink)
2643 {
2644   GstPulseRingBuffer *pbuf;
2645   pa_operation *o = NULL;
2646   gdouble v = DEFAULT_VOLUME;
2647   uint32_t idx;
2648
2649   if (!mainloop)
2650     goto no_mainloop;
2651
2652   pa_threaded_mainloop_lock (mainloop);
2653
2654   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2655   if (pbuf == NULL || pbuf->stream == NULL)
2656     goto no_buffer;
2657
2658   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2659     goto no_index;
2660
2661   if (!(o = pa_context_get_sink_input_info (pbuf->context, idx,
2662               gst_pulsesink_sink_input_info_cb, pbuf)))
2663     goto info_failed;
2664
2665   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2666     pa_threaded_mainloop_wait (mainloop);
2667     if (gst_pulsering_is_dead (psink, pbuf, TRUE))
2668       goto unlock;
2669   }
2670
2671 unlock:
2672   v = psink->volume;
2673
2674   if (o)
2675     pa_operation_unref (o);
2676
2677   pa_threaded_mainloop_unlock (mainloop);
2678
2679   if (v > MAX_VOLUME) {
2680     GST_WARNING_OBJECT (psink, "Clipped volume from %f to %f", v, MAX_VOLUME);
2681     v = MAX_VOLUME;
2682   }
2683
2684   return v;
2685
2686   /* ERRORS */
2687 no_mainloop:
2688   {
2689     v = psink->volume;
2690     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2691     return v;
2692   }
2693 no_buffer:
2694   {
2695     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2696     goto unlock;
2697   }
2698 no_index:
2699   {
2700     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2701     goto unlock;
2702   }
2703 info_failed:
2704   {
2705     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2706         ("pa_context_get_sink_input_info() failed: %s",
2707             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2708     goto unlock;
2709   }
2710 }
2711
2712 static gboolean
2713 gst_pulsesink_get_mute (GstPulseSink * psink)
2714 {
2715   GstPulseRingBuffer *pbuf;
2716   pa_operation *o = NULL;
2717   uint32_t idx;
2718   gboolean mute = FALSE;
2719
2720   if (!mainloop)
2721     goto no_mainloop;
2722
2723   pa_threaded_mainloop_lock (mainloop);
2724   mute = psink->mute;
2725
2726   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2727   if (pbuf == NULL || pbuf->stream == NULL)
2728     goto no_buffer;
2729
2730   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2731     goto no_index;
2732
2733   if (!(o = pa_context_get_sink_input_info (pbuf->context, idx,
2734               gst_pulsesink_sink_input_info_cb, pbuf)))
2735     goto info_failed;
2736
2737   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2738     pa_threaded_mainloop_wait (mainloop);
2739     if (gst_pulsering_is_dead (psink, pbuf, TRUE))
2740       goto unlock;
2741   }
2742
2743 unlock:
2744   if (o)
2745     pa_operation_unref (o);
2746
2747   pa_threaded_mainloop_unlock (mainloop);
2748
2749   return mute;
2750
2751   /* ERRORS */
2752 no_mainloop:
2753   {
2754     mute = psink->mute;
2755     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2756     return mute;
2757   }
2758 no_buffer:
2759   {
2760     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2761     goto unlock;
2762   }
2763 no_index:
2764   {
2765     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2766     goto unlock;
2767   }
2768 info_failed:
2769   {
2770     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2771         ("pa_context_get_sink_input_info() failed: %s",
2772             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2773     goto unlock;
2774   }
2775 }
2776
2777 static gchar *
2778 gst_pulsesink_device_description (GstPulseSink * psink)
2779 {
2780   GstPulseRingBuffer *pbuf;
2781   pa_operation *o = NULL;
2782   gchar *t;
2783
2784   if (!mainloop)
2785     goto no_mainloop;
2786
2787   pa_threaded_mainloop_lock (mainloop);
2788   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2789   if (pbuf == NULL)
2790     goto no_buffer;
2791
2792   free_device_info (&psink->device_info);
2793   if (!(o = pa_context_get_sink_info_by_name (pbuf->context,
2794               psink->device, gst_pulsesink_sink_info_cb, &psink->device_info)))
2795     goto info_failed;
2796
2797   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2798     pa_threaded_mainloop_wait (mainloop);
2799     if (gst_pulsering_is_dead (psink, pbuf, FALSE))
2800       goto unlock;
2801   }
2802
2803 unlock:
2804   if (o)
2805     pa_operation_unref (o);
2806
2807   t = g_strdup (psink->device_info.description);
2808   pa_threaded_mainloop_unlock (mainloop);
2809
2810   return t;
2811
2812   /* ERRORS */
2813 no_mainloop:
2814   {
2815     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2816     return NULL;
2817   }
2818 no_buffer:
2819   {
2820     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2821     goto unlock;
2822   }
2823 info_failed:
2824   {
2825     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2826         ("pa_context_get_sink_info_by_index() failed: %s",
2827             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2828     goto unlock;
2829   }
2830 }
2831
2832 static void
2833 gst_pulsesink_set_property (GObject * object,
2834     guint prop_id, const GValue * value, GParamSpec * pspec)
2835 {
2836   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
2837
2838   switch (prop_id) {
2839     case PROP_SERVER:
2840       g_free (pulsesink->server);
2841       pulsesink->server = g_value_dup_string (value);
2842       if (pulsesink->probe)
2843         gst_pulseprobe_set_server (pulsesink->probe, pulsesink->server);
2844       break;
2845     case PROP_DEVICE:
2846       g_free (pulsesink->device);
2847       pulsesink->device = g_value_dup_string (value);
2848       break;
2849     case PROP_VOLUME:
2850       gst_pulsesink_set_volume (pulsesink, g_value_get_double (value));
2851       break;
2852     case PROP_MUTE:
2853       gst_pulsesink_set_mute (pulsesink, g_value_get_boolean (value));
2854       break;
2855     case PROP_CLIENT_NAME:
2856       g_free (pulsesink->client_name);
2857       if (!g_value_get_string (value)) {
2858         GST_WARNING_OBJECT (pulsesink,
2859             "Empty PulseAudio client name not allowed. Resetting to default value");
2860         pulsesink->client_name = gst_pulse_client_name ();
2861       } else
2862         pulsesink->client_name = g_value_dup_string (value);
2863       break;
2864     case PROP_STREAM_PROPERTIES:
2865       if (pulsesink->properties)
2866         gst_structure_free (pulsesink->properties);
2867       pulsesink->properties =
2868           gst_structure_copy (gst_value_get_structure (value));
2869       if (pulsesink->proplist)
2870         pa_proplist_free (pulsesink->proplist);
2871       pulsesink->proplist = gst_pulse_make_proplist (pulsesink->properties);
2872       break;
2873     default:
2874       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2875       break;
2876   }
2877 }
2878
2879 static void
2880 gst_pulsesink_get_property (GObject * object,
2881     guint prop_id, GValue * value, GParamSpec * pspec)
2882 {
2883
2884   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
2885
2886   switch (prop_id) {
2887     case PROP_SERVER:
2888       g_value_set_string (value, pulsesink->server);
2889       break;
2890     case PROP_DEVICE:
2891       g_value_set_string (value, pulsesink->device);
2892       break;
2893     case PROP_DEVICE_NAME:
2894       g_value_take_string (value, gst_pulsesink_device_description (pulsesink));
2895       break;
2896     case PROP_VOLUME:
2897       g_value_set_double (value, gst_pulsesink_get_volume (pulsesink));
2898       break;
2899     case PROP_MUTE:
2900       g_value_set_boolean (value, gst_pulsesink_get_mute (pulsesink));
2901       break;
2902     case PROP_CLIENT_NAME:
2903       g_value_set_string (value, pulsesink->client_name);
2904       break;
2905     case PROP_STREAM_PROPERTIES:
2906       gst_value_set_structure (value, pulsesink->properties);
2907       break;
2908     default:
2909       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2910       break;
2911   }
2912 }
2913
2914 static void
2915 gst_pulsesink_change_title (GstPulseSink * psink, const gchar * t)
2916 {
2917   pa_operation *o = NULL;
2918   GstPulseRingBuffer *pbuf;
2919
2920   pa_threaded_mainloop_lock (mainloop);
2921
2922   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2923
2924   if (pbuf == NULL || pbuf->stream == NULL)
2925     goto no_buffer;
2926
2927   g_free (pbuf->stream_name);
2928   pbuf->stream_name = g_strdup (t);
2929
2930   if (!(o = pa_stream_set_name (pbuf->stream, pbuf->stream_name, NULL, NULL)))
2931     goto name_failed;
2932
2933   /* We're not interested if this operation failed or not */
2934 unlock:
2935
2936   if (o)
2937     pa_operation_unref (o);
2938   pa_threaded_mainloop_unlock (mainloop);
2939
2940   return;
2941
2942   /* ERRORS */
2943 no_buffer:
2944   {
2945     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2946     goto unlock;
2947   }
2948 name_failed:
2949   {
2950     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2951         ("pa_stream_set_name() failed: %s",
2952             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2953     goto unlock;
2954   }
2955 }
2956
2957 static void
2958 gst_pulsesink_change_props (GstPulseSink * psink, GstTagList * l)
2959 {
2960   static const gchar *const map[] = {
2961     GST_TAG_TITLE, PA_PROP_MEDIA_TITLE,
2962
2963     /* might get overriden in the next iteration by GST_TAG_ARTIST */
2964     GST_TAG_PERFORMER, PA_PROP_MEDIA_ARTIST,
2965
2966     GST_TAG_ARTIST, PA_PROP_MEDIA_ARTIST,
2967     GST_TAG_LANGUAGE_CODE, PA_PROP_MEDIA_LANGUAGE,
2968     GST_TAG_LOCATION, PA_PROP_MEDIA_FILENAME,
2969     /* We might add more here later on ... */
2970     NULL
2971   };
2972   pa_proplist *pl = NULL;
2973   const gchar *const *t;
2974   gboolean empty = TRUE;
2975   pa_operation *o = NULL;
2976   GstPulseRingBuffer *pbuf;
2977
2978   pl = pa_proplist_new ();
2979
2980   for (t = map; *t; t += 2) {
2981     gchar *n = NULL;
2982
2983     if (gst_tag_list_get_string (l, *t, &n)) {
2984
2985       if (n && *n) {
2986         pa_proplist_sets (pl, *(t + 1), n);
2987         empty = FALSE;
2988       }
2989
2990       g_free (n);
2991     }
2992   }
2993   if (empty)
2994     goto finish;
2995
2996   pa_threaded_mainloop_lock (mainloop);
2997   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2998   if (pbuf == NULL || pbuf->stream == NULL)
2999     goto no_buffer;
3000
3001   /* We're not interested if this operation failed or not */
3002   if (!(o = pa_stream_proplist_update (pbuf->stream, PA_UPDATE_REPLACE,
3003               pl, NULL, NULL))) {
3004     GST_DEBUG_OBJECT (psink, "pa_stream_proplist_update() failed");
3005   }
3006
3007 unlock:
3008
3009   if (o)
3010     pa_operation_unref (o);
3011
3012   pa_threaded_mainloop_unlock (mainloop);
3013
3014 finish:
3015
3016   if (pl)
3017     pa_proplist_free (pl);
3018
3019   return;
3020
3021   /* ERRORS */
3022 no_buffer:
3023   {
3024     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
3025     goto unlock;
3026   }
3027 }
3028
3029 static void
3030 gst_pulsesink_flush_ringbuffer (GstPulseSink * psink)
3031 {
3032   GstPulseRingBuffer *pbuf;
3033
3034   pa_threaded_mainloop_lock (mainloop);
3035
3036   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
3037
3038   if (pbuf == NULL || pbuf->stream == NULL)
3039     goto no_buffer;
3040
3041   gst_pulsering_flush (pbuf);
3042
3043   /* Uncork if we haven't already (happens when waiting to get enough data
3044    * to send out the first time) */
3045   if (pbuf->corked)
3046     gst_pulsering_set_corked (pbuf, FALSE, FALSE);
3047
3048   /* We're not interested if this operation failed or not */
3049 unlock:
3050   pa_threaded_mainloop_unlock (mainloop);
3051
3052   return;
3053
3054   /* ERRORS */
3055 no_buffer:
3056   {
3057     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
3058     goto unlock;
3059   }
3060 }
3061
3062 static gboolean
3063 gst_pulsesink_event (GstBaseSink * sink, GstEvent * event)
3064 {
3065   GstPulseSink *pulsesink = GST_PULSESINK_CAST (sink);
3066
3067   switch (GST_EVENT_TYPE (event)) {
3068     case GST_EVENT_TAG:{
3069       gchar *title = NULL, *artist = NULL, *location = NULL, *description =
3070           NULL, *t = NULL, *buf = NULL;
3071       GstTagList *l;
3072
3073       gst_event_parse_tag (event, &l);
3074
3075       gst_tag_list_get_string (l, GST_TAG_TITLE, &title);
3076       gst_tag_list_get_string (l, GST_TAG_ARTIST, &artist);
3077       gst_tag_list_get_string (l, GST_TAG_LOCATION, &location);
3078       gst_tag_list_get_string (l, GST_TAG_DESCRIPTION, &description);
3079
3080       if (!artist)
3081         gst_tag_list_get_string (l, GST_TAG_PERFORMER, &artist);
3082
3083       if (title && artist)
3084         /* TRANSLATORS: 'song title' by 'artist name' */
3085         t = buf = g_strdup_printf (_("'%s' by '%s'"), g_strstrip (title),
3086             g_strstrip (artist));
3087       else if (title)
3088         t = g_strstrip (title);
3089       else if (description)
3090         t = g_strstrip (description);
3091       else if (location)
3092         t = g_strstrip (location);
3093
3094       if (t)
3095         gst_pulsesink_change_title (pulsesink, t);
3096
3097       g_free (title);
3098       g_free (artist);
3099       g_free (location);
3100       g_free (description);
3101       g_free (buf);
3102
3103       gst_pulsesink_change_props (pulsesink, l);
3104
3105       break;
3106     }
3107     case GST_EVENT_GAP:{
3108       GstClockTime timestamp, duration;
3109
3110       gst_event_parse_gap (event, &timestamp, &duration);
3111       if (duration == GST_CLOCK_TIME_NONE)
3112         gst_pulsesink_flush_ringbuffer (pulsesink);
3113       break;
3114     }
3115     case GST_EVENT_EOS:
3116       gst_pulsesink_flush_ringbuffer (pulsesink);
3117       break;
3118     default:
3119       ;
3120   }
3121
3122   return GST_BASE_SINK_CLASS (parent_class)->event (sink, event);
3123 }
3124
3125 static gboolean
3126 gst_pulsesink_query (GstBaseSink * sink, GstQuery * query)
3127 {
3128   GstPulseSink *pulsesink = GST_PULSESINK_CAST (sink);
3129   gboolean ret;
3130
3131   switch (GST_QUERY_TYPE (query)) {
3132 #ifdef HAVE_PULSE_2_0
3133     case GST_QUERY_CAPS:
3134     {
3135       GstCaps *caps, *filter;
3136
3137       gst_query_parse_caps (query, &filter);
3138       caps = gst_pulsesink_query_getcaps (pulsesink, filter);
3139
3140       if (caps) {
3141         gst_query_set_caps_result (query, caps);
3142         gst_caps_unref (caps);
3143         return TRUE;
3144       } else {
3145         return FALSE;
3146       }
3147     }
3148 #endif
3149     case GST_QUERY_ACCEPT_CAPS:
3150     {
3151       GstCaps *caps;
3152
3153       gst_query_parse_accept_caps (query, &caps);
3154       ret = gst_pulsesink_query_acceptcaps (pulsesink, caps);
3155       gst_query_set_accept_caps_result (query, ret);
3156       ret = TRUE;
3157       break;
3158     }
3159     default:
3160       ret = GST_BASE_SINK_CLASS (parent_class)->query (sink, query);
3161       break;
3162   }
3163   return ret;
3164 }
3165
3166 static void
3167 gst_pulsesink_release_mainloop (GstPulseSink * psink)
3168 {
3169   if (!mainloop)
3170     return;
3171
3172   pa_threaded_mainloop_lock (mainloop);
3173   while (psink->defer_pending) {
3174     GST_DEBUG_OBJECT (psink, "waiting for stream status message emission");
3175     pa_threaded_mainloop_wait (mainloop);
3176   }
3177   pa_threaded_mainloop_unlock (mainloop);
3178
3179   g_mutex_lock (&pa_shared_resource_mutex);
3180   mainloop_ref_ct--;
3181   if (!mainloop_ref_ct) {
3182     GST_INFO_OBJECT (psink, "terminating pa main loop thread");
3183     pa_threaded_mainloop_stop (mainloop);
3184     pa_threaded_mainloop_free (mainloop);
3185     mainloop = NULL;
3186   }
3187   g_mutex_unlock (&pa_shared_resource_mutex);
3188 }
3189
3190 static GstStateChangeReturn
3191 gst_pulsesink_change_state (GstElement * element, GstStateChange transition)
3192 {
3193   GstPulseSink *pulsesink = GST_PULSESINK (element);
3194   GstStateChangeReturn ret;
3195
3196   switch (transition) {
3197     case GST_STATE_CHANGE_NULL_TO_READY:
3198       g_mutex_lock (&pa_shared_resource_mutex);
3199       if (!mainloop_ref_ct) {
3200         GST_INFO_OBJECT (element, "new pa main loop thread");
3201         if (!(mainloop = pa_threaded_mainloop_new ()))
3202           goto mainloop_failed;
3203         if (pa_threaded_mainloop_start (mainloop) < 0) {
3204           pa_threaded_mainloop_free (mainloop);
3205           goto mainloop_start_failed;
3206         }
3207         mainloop_ref_ct = 1;
3208         g_mutex_unlock (&pa_shared_resource_mutex);
3209       } else {
3210         GST_INFO_OBJECT (element, "reusing pa main loop thread");
3211         mainloop_ref_ct++;
3212         g_mutex_unlock (&pa_shared_resource_mutex);
3213       }
3214       break;
3215     case GST_STATE_CHANGE_READY_TO_PAUSED:
3216       gst_element_post_message (element,
3217           gst_message_new_clock_provide (GST_OBJECT_CAST (element),
3218               GST_AUDIO_BASE_SINK (pulsesink)->provided_clock, TRUE));
3219       break;
3220
3221     default:
3222       break;
3223   }
3224
3225   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3226   if (ret == GST_STATE_CHANGE_FAILURE)
3227     goto state_failure;
3228
3229   switch (transition) {
3230     case GST_STATE_CHANGE_PAUSED_TO_READY:
3231       /* format_lost is reset in release() in audiobasesink */
3232       gst_element_post_message (element,
3233           gst_message_new_clock_lost (GST_OBJECT_CAST (element),
3234               GST_AUDIO_BASE_SINK (pulsesink)->provided_clock));
3235       break;
3236     case GST_STATE_CHANGE_READY_TO_NULL:
3237       gst_pulsesink_release_mainloop (pulsesink);
3238       break;
3239     default:
3240       break;
3241   }
3242
3243   return ret;
3244
3245   /* ERRORS */
3246 mainloop_failed:
3247   {
3248     g_mutex_unlock (&pa_shared_resource_mutex);
3249     GST_ELEMENT_ERROR (pulsesink, RESOURCE, FAILED,
3250         ("pa_threaded_mainloop_new() failed"), (NULL));
3251     return GST_STATE_CHANGE_FAILURE;
3252   }
3253 mainloop_start_failed:
3254   {
3255     g_mutex_unlock (&pa_shared_resource_mutex);
3256     GST_ELEMENT_ERROR (pulsesink, RESOURCE, FAILED,
3257         ("pa_threaded_mainloop_start() failed"), (NULL));
3258     return GST_STATE_CHANGE_FAILURE;
3259   }
3260 state_failure:
3261   {
3262     if (transition == GST_STATE_CHANGE_NULL_TO_READY) {
3263       /* Clear the PA mainloop if audiobasesink failed to open the ring_buffer */
3264       g_assert (mainloop);
3265       gst_pulsesink_release_mainloop (pulsesink);
3266     }
3267     return ret;
3268   }
3269 }