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