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