pulsesink: Better error message when server version is too old
[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 /* Returns the current time of the sink ringbuffer. The timing_info is updated
1904  * on every data write/flush and every 100ms (PA_STREAM_AUTO_TIMING_UPDATE).
1905  */
1906 static GstClockTime
1907 gst_pulsesink_get_time (GstClock * clock, GstAudioBaseSink * sink)
1908 {
1909   GstPulseSink *psink;
1910   GstPulseRingBuffer *pbuf;
1911   pa_usec_t time;
1912
1913   if (!sink->ringbuffer || !sink->ringbuffer->acquired)
1914     return GST_CLOCK_TIME_NONE;
1915
1916   pbuf = GST_PULSERING_BUFFER_CAST (sink->ringbuffer);
1917   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1918
1919   if (g_atomic_int_get (&psink->format_lost)) {
1920     /* Stream was lost in a format change, it'll get set up again once
1921      * upstream renegotiates */
1922     return psink->format_lost_time;
1923   }
1924
1925   pa_threaded_mainloop_lock (mainloop);
1926   if (gst_pulsering_is_dead (psink, pbuf, TRUE))
1927     goto server_dead;
1928
1929   /* if we don't have enough data to get a timestamp, just return NONE, which
1930    * will return the last reported time */
1931   if (pa_stream_get_time (pbuf->stream, &time) < 0) {
1932     GST_DEBUG_OBJECT (psink, "could not get time");
1933     time = GST_CLOCK_TIME_NONE;
1934   } else
1935     time *= 1000;
1936   pa_threaded_mainloop_unlock (mainloop);
1937
1938   GST_LOG_OBJECT (psink, "current time is %" GST_TIME_FORMAT,
1939       GST_TIME_ARGS (time));
1940
1941   return time;
1942
1943   /* ERRORS */
1944 server_dead:
1945   {
1946     GST_DEBUG_OBJECT (psink, "the server is dead");
1947     pa_threaded_mainloop_unlock (mainloop);
1948
1949     return GST_CLOCK_TIME_NONE;
1950   }
1951 }
1952
1953 static void
1954 gst_pulsesink_sink_info_cb (pa_context * c, const pa_sink_info * i, int eol,
1955     void *userdata)
1956 {
1957   GstPulseRingBuffer *pbuf;
1958   GstPulseSink *psink;
1959   GList *l;
1960   guint8 j;
1961
1962   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
1963   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1964
1965   if (!i)
1966     goto done;
1967
1968   g_free (psink->device_description);
1969   psink->device_description = g_strdup (i->description);
1970
1971   g_mutex_lock (&psink->sink_formats_lock);
1972
1973   for (l = g_list_first (psink->sink_formats); l; l = g_list_next (l))
1974     pa_format_info_free ((pa_format_info *) l->data);
1975
1976   g_list_free (psink->sink_formats);
1977   psink->sink_formats = NULL;
1978
1979   for (j = 0; j < i->n_formats; j++)
1980     psink->sink_formats = g_list_prepend (psink->sink_formats,
1981         pa_format_info_copy (i->formats[j]));
1982
1983   g_mutex_unlock (&psink->sink_formats_lock);
1984
1985 done:
1986   pa_threaded_mainloop_signal (mainloop, 0);
1987 }
1988
1989 static gboolean
1990 gst_pulsesink_query_acceptcaps (GstPulseSink * psink, GstCaps * caps)
1991 {
1992   GstPulseRingBuffer *pbuf = NULL;
1993   GstCaps *pad_caps;
1994   GstStructure *st;
1995   gboolean ret = FALSE;
1996
1997   GstAudioRingBufferSpec spec = { 0 };
1998   pa_stream *stream = NULL;
1999   pa_operation *o = NULL;
2000   pa_channel_map channel_map;
2001   pa_stream_flags_t flags;
2002   pa_format_info *format = NULL, *formats[1];
2003   guint channels;
2004
2005   pad_caps = gst_pad_query_caps (GST_BASE_SINK_PAD (psink), caps);
2006   ret = pad_caps != NULL;
2007   gst_caps_unref (pad_caps);
2008
2009   GST_DEBUG_OBJECT (psink, "caps %" GST_PTR_FORMAT, caps);
2010
2011   /* Template caps didn't match */
2012   if (!ret)
2013     goto done;
2014
2015   /* If we've not got fixed caps, creating a stream might fail, so let's just
2016    * return from here with default acceptcaps behaviour */
2017   if (!gst_caps_is_fixed (caps))
2018     goto done;
2019
2020   GST_OBJECT_LOCK (psink);
2021   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2022   if (pbuf != NULL)
2023     gst_object_ref (pbuf);
2024   GST_OBJECT_UNLOCK (psink);
2025
2026   /* We're still in NULL state */
2027   if (pbuf == NULL)
2028     goto done;
2029
2030   pa_threaded_mainloop_lock (mainloop);
2031
2032   if (pbuf->context == NULL)
2033     goto out;
2034
2035   ret = FALSE;
2036
2037   spec.latency_time = GST_AUDIO_BASE_SINK (psink)->latency_time;
2038   if (!gst_audio_ring_buffer_parse_caps (&spec, caps))
2039     goto out;
2040
2041   if (!gst_pulse_fill_format_info (&spec, &format, &channels))
2042     goto out;
2043
2044   /* Make sure input is framed (one frame per buffer) and can be payloaded */
2045   if (!pa_format_info_is_pcm (format)) {
2046     gboolean framed = FALSE, parsed = FALSE;
2047     st = gst_caps_get_structure (caps, 0);
2048
2049     gst_structure_get_boolean (st, "framed", &framed);
2050     gst_structure_get_boolean (st, "parsed", &parsed);
2051     if ((!framed && !parsed) || gst_audio_iec61937_frame_size (&spec) <= 0)
2052       goto out;
2053   }
2054
2055   /* initialize the channel map */
2056   if (pa_format_info_is_pcm (format) &&
2057       gst_pulse_gst_to_channel_map (&channel_map, &spec))
2058     pa_format_info_set_channel_map (format, &channel_map);
2059
2060   if (pbuf->stream) {
2061     /* We're already in PAUSED or above, so just reuse this stream to query
2062      * sink formats and use those. */
2063     GList *i;
2064
2065     if (!(o = pa_context_get_sink_info_by_name (pbuf->context, psink->device,
2066                 gst_pulsesink_sink_info_cb, pbuf)))
2067       goto info_failed;
2068
2069     while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2070       pa_threaded_mainloop_wait (mainloop);
2071       if (gst_pulsering_is_dead (psink, pbuf, TRUE))
2072         goto out;
2073     }
2074
2075     g_mutex_lock (&psink->sink_formats_lock);
2076     for (i = g_list_first (psink->sink_formats); i; i = g_list_next (i)) {
2077       if (pa_format_info_is_compatible ((pa_format_info *) i->data, format)) {
2078         ret = TRUE;
2079         break;
2080       }
2081     }
2082     g_mutex_unlock (&psink->sink_formats_lock);
2083   } else {
2084     /* We're in READY, let's connect a stream to see if the format is
2085      * accpeted by whatever sink we're routed to */
2086     formats[0] = format;
2087
2088     if (!(stream = pa_stream_new_extended (pbuf->context, "pulsesink probe",
2089                 formats, 1, psink->proplist)))
2090       goto out;
2091
2092     /* construct the flags */
2093     flags = PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE |
2094         PA_STREAM_ADJUST_LATENCY | PA_STREAM_START_CORKED;
2095
2096     pa_stream_set_state_callback (stream, gst_pulsering_stream_state_cb, pbuf);
2097
2098     if (pa_stream_connect_playback (stream, psink->device, NULL, flags, NULL,
2099             NULL) < 0)
2100       goto out;
2101
2102     ret = gst_pulsering_wait_for_stream_ready (psink, stream);
2103   }
2104
2105 out:
2106   if (format)
2107     pa_format_info_free (format);
2108
2109   if (o)
2110     pa_operation_unref (o);
2111
2112   if (stream) {
2113     pa_stream_set_state_callback (stream, NULL, NULL);
2114     pa_stream_disconnect (stream);
2115     pa_stream_unref (stream);
2116   }
2117
2118   pa_threaded_mainloop_unlock (mainloop);
2119
2120   gst_caps_replace (&spec.caps, NULL);
2121   gst_object_unref (pbuf);
2122
2123 done:
2124
2125   return ret;
2126
2127 info_failed:
2128   {
2129     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2130         ("pa_context_get_sink_input_info() failed: %s",
2131             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2132     goto out;
2133   }
2134 }
2135
2136 static void
2137 gst_pulsesink_init (GstPulseSink * pulsesink)
2138 {
2139   pulsesink->server = NULL;
2140   pulsesink->device = NULL;
2141   pulsesink->device_description = NULL;
2142   pulsesink->client_name = gst_pulse_client_name ();
2143
2144   g_mutex_init (&pulsesink->sink_formats_lock);
2145   pulsesink->sink_formats = NULL;
2146
2147   pulsesink->volume = DEFAULT_VOLUME;
2148   pulsesink->volume_set = FALSE;
2149
2150   pulsesink->mute = DEFAULT_MUTE;
2151   pulsesink->mute_set = FALSE;
2152
2153   pulsesink->notify = 0;
2154
2155   g_atomic_int_set (&pulsesink->format_lost, FALSE);
2156   pulsesink->format_lost_time = GST_CLOCK_TIME_NONE;
2157
2158   pulsesink->properties = NULL;
2159   pulsesink->proplist = NULL;
2160
2161   /* override with a custom clock */
2162   if (GST_AUDIO_BASE_SINK (pulsesink)->provided_clock)
2163     gst_object_unref (GST_AUDIO_BASE_SINK (pulsesink)->provided_clock);
2164
2165   GST_AUDIO_BASE_SINK (pulsesink)->provided_clock =
2166       gst_audio_clock_new ("GstPulseSinkClock",
2167       (GstAudioClockGetTimeFunc) gst_pulsesink_get_time, pulsesink, NULL);
2168
2169   /* TRUE for sinks, FALSE for sources */
2170   pulsesink->probe = gst_pulseprobe_new (G_OBJECT (pulsesink),
2171       G_OBJECT_GET_CLASS (pulsesink), PROP_DEVICE, pulsesink->device,
2172       TRUE, FALSE);
2173 }
2174
2175 static void
2176 gst_pulsesink_finalize (GObject * object)
2177 {
2178   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
2179   GList *i;
2180
2181   g_free (pulsesink->server);
2182   g_free (pulsesink->device);
2183   g_free (pulsesink->device_description);
2184   g_free (pulsesink->client_name);
2185
2186   for (i = g_list_first (pulsesink->sink_formats); i; i = g_list_next (i))
2187     pa_format_info_free ((pa_format_info *) i->data);
2188
2189   g_list_free (pulsesink->sink_formats);
2190   g_mutex_clear (&pulsesink->sink_formats_lock);
2191
2192   if (pulsesink->properties)
2193     gst_structure_free (pulsesink->properties);
2194   if (pulsesink->proplist)
2195     pa_proplist_free (pulsesink->proplist);
2196
2197   if (pulsesink->probe) {
2198     gst_pulseprobe_free (pulsesink->probe);
2199     pulsesink->probe = NULL;
2200   }
2201
2202   G_OBJECT_CLASS (parent_class)->finalize (object);
2203 }
2204
2205 static void
2206 gst_pulsesink_set_volume (GstPulseSink * psink, gdouble volume)
2207 {
2208   pa_cvolume v;
2209   pa_operation *o = NULL;
2210   GstPulseRingBuffer *pbuf;
2211   uint32_t idx;
2212
2213   if (!mainloop)
2214     goto no_mainloop;
2215
2216   pa_threaded_mainloop_lock (mainloop);
2217
2218   GST_DEBUG_OBJECT (psink, "setting volume to %f", volume);
2219
2220   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2221   if (pbuf == NULL || pbuf->stream == NULL)
2222     goto no_buffer;
2223
2224   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2225     goto no_index;
2226
2227   if (pbuf->is_pcm)
2228     gst_pulse_cvolume_from_linear (&v, pbuf->channels, volume);
2229   else
2230     /* FIXME: this will eventually be superceded by checks to see if the volume
2231      * is readable/writable */
2232     goto unlock;
2233
2234   if (!(o = pa_context_set_sink_input_volume (pbuf->context, idx,
2235               &v, NULL, NULL)))
2236     goto volume_failed;
2237
2238   /* We don't really care about the result of this call */
2239 unlock:
2240
2241   if (o)
2242     pa_operation_unref (o);
2243
2244   pa_threaded_mainloop_unlock (mainloop);
2245
2246   return;
2247
2248   /* ERRORS */
2249 no_mainloop:
2250   {
2251     psink->volume = volume;
2252     psink->volume_set = TRUE;
2253
2254     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2255     return;
2256   }
2257 no_buffer:
2258   {
2259     psink->volume = volume;
2260     psink->volume_set = TRUE;
2261
2262     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2263     goto unlock;
2264   }
2265 no_index:
2266   {
2267     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2268     goto unlock;
2269   }
2270 volume_failed:
2271   {
2272     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2273         ("pa_stream_set_sink_input_volume() failed: %s",
2274             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2275     goto unlock;
2276   }
2277 }
2278
2279 static void
2280 gst_pulsesink_set_mute (GstPulseSink * psink, gboolean mute)
2281 {
2282   pa_operation *o = NULL;
2283   GstPulseRingBuffer *pbuf;
2284   uint32_t idx;
2285
2286   if (!mainloop)
2287     goto no_mainloop;
2288
2289   pa_threaded_mainloop_lock (mainloop);
2290
2291   GST_DEBUG_OBJECT (psink, "setting mute state to %d", mute);
2292
2293   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2294   if (pbuf == NULL || pbuf->stream == NULL)
2295     goto no_buffer;
2296
2297   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2298     goto no_index;
2299
2300   if (!(o = pa_context_set_sink_input_mute (pbuf->context, idx,
2301               mute, NULL, NULL)))
2302     goto mute_failed;
2303
2304   /* We don't really care about the result of this call */
2305 unlock:
2306
2307   if (o)
2308     pa_operation_unref (o);
2309
2310   pa_threaded_mainloop_unlock (mainloop);
2311
2312   return;
2313
2314   /* ERRORS */
2315 no_mainloop:
2316   {
2317     psink->mute = mute;
2318     psink->mute_set = TRUE;
2319
2320     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2321     return;
2322   }
2323 no_buffer:
2324   {
2325     psink->mute = mute;
2326     psink->mute_set = TRUE;
2327
2328     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2329     goto unlock;
2330   }
2331 no_index:
2332   {
2333     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2334     goto unlock;
2335   }
2336 mute_failed:
2337   {
2338     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2339         ("pa_stream_set_sink_input_mute() failed: %s",
2340             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2341     goto unlock;
2342   }
2343 }
2344
2345 static void
2346 gst_pulsesink_sink_input_info_cb (pa_context * c, const pa_sink_input_info * i,
2347     int eol, void *userdata)
2348 {
2349   GstPulseRingBuffer *pbuf;
2350   GstPulseSink *psink;
2351
2352   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
2353   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
2354
2355   if (!i)
2356     goto done;
2357
2358   if (!pbuf->stream)
2359     goto done;
2360
2361   /* If the index doesn't match our current stream,
2362    * it implies we just recreated the stream (caps change)
2363    */
2364   if (i->index == pa_stream_get_index (pbuf->stream)) {
2365     psink->volume = pa_sw_volume_to_linear (pa_cvolume_max (&i->volume));
2366     psink->mute = i->mute;
2367   }
2368
2369 done:
2370   pa_threaded_mainloop_signal (mainloop, 0);
2371 }
2372
2373 static gdouble
2374 gst_pulsesink_get_volume (GstPulseSink * psink)
2375 {
2376   GstPulseRingBuffer *pbuf;
2377   pa_operation *o = NULL;
2378   gdouble v = DEFAULT_VOLUME;
2379   uint32_t idx;
2380
2381   if (!mainloop)
2382     goto no_mainloop;
2383
2384   pa_threaded_mainloop_lock (mainloop);
2385
2386   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2387   if (pbuf == NULL || pbuf->stream == NULL)
2388     goto no_buffer;
2389
2390   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2391     goto no_index;
2392
2393   if (!(o = pa_context_get_sink_input_info (pbuf->context, idx,
2394               gst_pulsesink_sink_input_info_cb, pbuf)))
2395     goto info_failed;
2396
2397   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2398     pa_threaded_mainloop_wait (mainloop);
2399     if (gst_pulsering_is_dead (psink, pbuf, TRUE))
2400       goto unlock;
2401   }
2402
2403 unlock:
2404   v = psink->volume;
2405
2406   if (o)
2407     pa_operation_unref (o);
2408
2409   pa_threaded_mainloop_unlock (mainloop);
2410
2411   if (v > MAX_VOLUME) {
2412     GST_WARNING_OBJECT (psink, "Clipped volume from %f to %f", v, MAX_VOLUME);
2413     v = MAX_VOLUME;
2414   }
2415
2416   return v;
2417
2418   /* ERRORS */
2419 no_mainloop:
2420   {
2421     v = psink->volume;
2422     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2423     return v;
2424   }
2425 no_buffer:
2426   {
2427     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2428     goto unlock;
2429   }
2430 no_index:
2431   {
2432     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2433     goto unlock;
2434   }
2435 info_failed:
2436   {
2437     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2438         ("pa_context_get_sink_input_info() failed: %s",
2439             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2440     goto unlock;
2441   }
2442 }
2443
2444 static gboolean
2445 gst_pulsesink_get_mute (GstPulseSink * psink)
2446 {
2447   GstPulseRingBuffer *pbuf;
2448   pa_operation *o = NULL;
2449   uint32_t idx;
2450   gboolean mute = FALSE;
2451
2452   if (!mainloop)
2453     goto no_mainloop;
2454
2455   pa_threaded_mainloop_lock (mainloop);
2456   mute = psink->mute;
2457
2458   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2459   if (pbuf == NULL || pbuf->stream == NULL)
2460     goto no_buffer;
2461
2462   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2463     goto no_index;
2464
2465   if (!(o = pa_context_get_sink_input_info (pbuf->context, idx,
2466               gst_pulsesink_sink_input_info_cb, pbuf)))
2467     goto info_failed;
2468
2469   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2470     pa_threaded_mainloop_wait (mainloop);
2471     if (gst_pulsering_is_dead (psink, pbuf, TRUE))
2472       goto unlock;
2473   }
2474
2475 unlock:
2476   if (o)
2477     pa_operation_unref (o);
2478
2479   pa_threaded_mainloop_unlock (mainloop);
2480
2481   return mute;
2482
2483   /* ERRORS */
2484 no_mainloop:
2485   {
2486     mute = psink->mute;
2487     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2488     return mute;
2489   }
2490 no_buffer:
2491   {
2492     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2493     goto unlock;
2494   }
2495 no_index:
2496   {
2497     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2498     goto unlock;
2499   }
2500 info_failed:
2501   {
2502     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2503         ("pa_context_get_sink_input_info() failed: %s",
2504             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2505     goto unlock;
2506   }
2507 }
2508
2509 static gchar *
2510 gst_pulsesink_device_description (GstPulseSink * psink)
2511 {
2512   GstPulseRingBuffer *pbuf;
2513   pa_operation *o = NULL;
2514   gchar *t;
2515
2516   if (!mainloop)
2517     goto no_mainloop;
2518
2519   pa_threaded_mainloop_lock (mainloop);
2520   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2521   if (pbuf == NULL)
2522     goto no_buffer;
2523
2524   if (!(o = pa_context_get_sink_info_by_name (pbuf->context,
2525               psink->device, gst_pulsesink_sink_info_cb, pbuf)))
2526     goto info_failed;
2527
2528   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2529     pa_threaded_mainloop_wait (mainloop);
2530     if (gst_pulsering_is_dead (psink, pbuf, FALSE))
2531       goto unlock;
2532   }
2533
2534 unlock:
2535   if (o)
2536     pa_operation_unref (o);
2537
2538   t = g_strdup (psink->device_description);
2539   pa_threaded_mainloop_unlock (mainloop);
2540
2541   return t;
2542
2543   /* ERRORS */
2544 no_mainloop:
2545   {
2546     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2547     return NULL;
2548   }
2549 no_buffer:
2550   {
2551     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2552     goto unlock;
2553   }
2554 info_failed:
2555   {
2556     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2557         ("pa_context_get_sink_info_by_index() failed: %s",
2558             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2559     goto unlock;
2560   }
2561 }
2562
2563 static void
2564 gst_pulsesink_set_property (GObject * object,
2565     guint prop_id, const GValue * value, GParamSpec * pspec)
2566 {
2567   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
2568
2569   switch (prop_id) {
2570     case PROP_SERVER:
2571       g_free (pulsesink->server);
2572       pulsesink->server = g_value_dup_string (value);
2573       if (pulsesink->probe)
2574         gst_pulseprobe_set_server (pulsesink->probe, pulsesink->server);
2575       break;
2576     case PROP_DEVICE:
2577       g_free (pulsesink->device);
2578       pulsesink->device = g_value_dup_string (value);
2579       break;
2580     case PROP_VOLUME:
2581       gst_pulsesink_set_volume (pulsesink, g_value_get_double (value));
2582       break;
2583     case PROP_MUTE:
2584       gst_pulsesink_set_mute (pulsesink, g_value_get_boolean (value));
2585       break;
2586     case PROP_CLIENT_NAME:
2587       g_free (pulsesink->client_name);
2588       if (!g_value_get_string (value)) {
2589         GST_WARNING_OBJECT (pulsesink,
2590             "Empty PulseAudio client name not allowed. Resetting to default value");
2591         pulsesink->client_name = gst_pulse_client_name ();
2592       } else
2593         pulsesink->client_name = g_value_dup_string (value);
2594       break;
2595     case PROP_STREAM_PROPERTIES:
2596       if (pulsesink->properties)
2597         gst_structure_free (pulsesink->properties);
2598       pulsesink->properties =
2599           gst_structure_copy (gst_value_get_structure (value));
2600       if (pulsesink->proplist)
2601         pa_proplist_free (pulsesink->proplist);
2602       pulsesink->proplist = gst_pulse_make_proplist (pulsesink->properties);
2603       break;
2604     default:
2605       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2606       break;
2607   }
2608 }
2609
2610 static void
2611 gst_pulsesink_get_property (GObject * object,
2612     guint prop_id, GValue * value, GParamSpec * pspec)
2613 {
2614
2615   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
2616
2617   switch (prop_id) {
2618     case PROP_SERVER:
2619       g_value_set_string (value, pulsesink->server);
2620       break;
2621     case PROP_DEVICE:
2622       g_value_set_string (value, pulsesink->device);
2623       break;
2624     case PROP_DEVICE_NAME:
2625       g_value_take_string (value, gst_pulsesink_device_description (pulsesink));
2626       break;
2627     case PROP_VOLUME:
2628       g_value_set_double (value, gst_pulsesink_get_volume (pulsesink));
2629       break;
2630     case PROP_MUTE:
2631       g_value_set_boolean (value, gst_pulsesink_get_mute (pulsesink));
2632       break;
2633     case PROP_CLIENT_NAME:
2634       g_value_set_string (value, pulsesink->client_name);
2635       break;
2636     case PROP_STREAM_PROPERTIES:
2637       gst_value_set_structure (value, pulsesink->properties);
2638       break;
2639     default:
2640       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2641       break;
2642   }
2643 }
2644
2645 static void
2646 gst_pulsesink_change_title (GstPulseSink * psink, const gchar * t)
2647 {
2648   pa_operation *o = NULL;
2649   GstPulseRingBuffer *pbuf;
2650
2651   pa_threaded_mainloop_lock (mainloop);
2652
2653   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2654
2655   if (pbuf == NULL || pbuf->stream == NULL)
2656     goto no_buffer;
2657
2658   g_free (pbuf->stream_name);
2659   pbuf->stream_name = g_strdup (t);
2660
2661   if (!(o = pa_stream_set_name (pbuf->stream, pbuf->stream_name, NULL, NULL)))
2662     goto name_failed;
2663
2664   /* We're not interested if this operation failed or not */
2665 unlock:
2666
2667   if (o)
2668     pa_operation_unref (o);
2669   pa_threaded_mainloop_unlock (mainloop);
2670
2671   return;
2672
2673   /* ERRORS */
2674 no_buffer:
2675   {
2676     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2677     goto unlock;
2678   }
2679 name_failed:
2680   {
2681     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2682         ("pa_stream_set_name() failed: %s",
2683             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2684     goto unlock;
2685   }
2686 }
2687
2688 static void
2689 gst_pulsesink_change_props (GstPulseSink * psink, GstTagList * l)
2690 {
2691   static const gchar *const map[] = {
2692     GST_TAG_TITLE, PA_PROP_MEDIA_TITLE,
2693
2694     /* might get overriden in the next iteration by GST_TAG_ARTIST */
2695     GST_TAG_PERFORMER, PA_PROP_MEDIA_ARTIST,
2696
2697     GST_TAG_ARTIST, PA_PROP_MEDIA_ARTIST,
2698     GST_TAG_LANGUAGE_CODE, PA_PROP_MEDIA_LANGUAGE,
2699     GST_TAG_LOCATION, PA_PROP_MEDIA_FILENAME,
2700     /* We might add more here later on ... */
2701     NULL
2702   };
2703   pa_proplist *pl = NULL;
2704   const gchar *const *t;
2705   gboolean empty = TRUE;
2706   pa_operation *o = NULL;
2707   GstPulseRingBuffer *pbuf;
2708
2709   pl = pa_proplist_new ();
2710
2711   for (t = map; *t; t += 2) {
2712     gchar *n = NULL;
2713
2714     if (gst_tag_list_get_string (l, *t, &n)) {
2715
2716       if (n && *n) {
2717         pa_proplist_sets (pl, *(t + 1), n);
2718         empty = FALSE;
2719       }
2720
2721       g_free (n);
2722     }
2723   }
2724   if (empty)
2725     goto finish;
2726
2727   pa_threaded_mainloop_lock (mainloop);
2728   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2729   if (pbuf == NULL || pbuf->stream == NULL)
2730     goto no_buffer;
2731
2732   /* We're not interested if this operation failed or not */
2733   if (!(o = pa_stream_proplist_update (pbuf->stream, PA_UPDATE_REPLACE,
2734               pl, NULL, NULL))) {
2735     GST_DEBUG_OBJECT (psink, "pa_stream_proplist_update() failed");
2736   }
2737
2738 unlock:
2739
2740   if (o)
2741     pa_operation_unref (o);
2742
2743   pa_threaded_mainloop_unlock (mainloop);
2744
2745 finish:
2746
2747   if (pl)
2748     pa_proplist_free (pl);
2749
2750   return;
2751
2752   /* ERRORS */
2753 no_buffer:
2754   {
2755     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2756     goto unlock;
2757   }
2758 }
2759
2760 static void
2761 gst_pulsesink_flush_ringbuffer (GstPulseSink * psink)
2762 {
2763   GstPulseRingBuffer *pbuf;
2764
2765   pa_threaded_mainloop_lock (mainloop);
2766
2767   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2768
2769   if (pbuf == NULL || pbuf->stream == NULL)
2770     goto no_buffer;
2771
2772   gst_pulsering_flush (pbuf);
2773
2774   /* Uncork if we haven't already (happens when waiting to get enough data
2775    * to send out the first time) */
2776   if (pbuf->corked)
2777     gst_pulsering_set_corked (pbuf, FALSE, FALSE);
2778
2779   /* We're not interested if this operation failed or not */
2780 unlock:
2781   pa_threaded_mainloop_unlock (mainloop);
2782
2783   return;
2784
2785   /* ERRORS */
2786 no_buffer:
2787   {
2788     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2789     goto unlock;
2790   }
2791 }
2792
2793 static gboolean
2794 gst_pulsesink_event (GstBaseSink * sink, GstEvent * event)
2795 {
2796   GstPulseSink *pulsesink = GST_PULSESINK_CAST (sink);
2797
2798   switch (GST_EVENT_TYPE (event)) {
2799     case GST_EVENT_TAG:{
2800       gchar *title = NULL, *artist = NULL, *location = NULL, *description =
2801           NULL, *t = NULL, *buf = NULL;
2802       GstTagList *l;
2803
2804       gst_event_parse_tag (event, &l);
2805
2806       gst_tag_list_get_string (l, GST_TAG_TITLE, &title);
2807       gst_tag_list_get_string (l, GST_TAG_ARTIST, &artist);
2808       gst_tag_list_get_string (l, GST_TAG_LOCATION, &location);
2809       gst_tag_list_get_string (l, GST_TAG_DESCRIPTION, &description);
2810
2811       if (!artist)
2812         gst_tag_list_get_string (l, GST_TAG_PERFORMER, &artist);
2813
2814       if (title && artist)
2815         /* TRANSLATORS: 'song title' by 'artist name' */
2816         t = buf = g_strdup_printf (_("'%s' by '%s'"), g_strstrip (title),
2817             g_strstrip (artist));
2818       else if (title)
2819         t = g_strstrip (title);
2820       else if (description)
2821         t = g_strstrip (description);
2822       else if (location)
2823         t = g_strstrip (location);
2824
2825       if (t)
2826         gst_pulsesink_change_title (pulsesink, t);
2827
2828       g_free (title);
2829       g_free (artist);
2830       g_free (location);
2831       g_free (description);
2832       g_free (buf);
2833
2834       gst_pulsesink_change_props (pulsesink, l);
2835
2836       break;
2837     }
2838     case GST_EVENT_GAP:{
2839       GstClockTime timestamp, duration;
2840
2841       gst_event_parse_gap (event, &timestamp, &duration);
2842       if (duration == GST_CLOCK_TIME_NONE)
2843         gst_pulsesink_flush_ringbuffer (pulsesink);
2844       break;
2845     }
2846     case GST_EVENT_EOS:
2847       gst_pulsesink_flush_ringbuffer (pulsesink);
2848       break;
2849     default:
2850       ;
2851   }
2852
2853   return GST_BASE_SINK_CLASS (parent_class)->event (sink, event);
2854 }
2855
2856 static gboolean
2857 gst_pulsesink_query (GstBaseSink * sink, GstQuery * query)
2858 {
2859   GstPulseSink *pulsesink = GST_PULSESINK_CAST (sink);
2860   gboolean ret;
2861
2862   switch (GST_QUERY_TYPE (query)) {
2863     case GST_QUERY_ACCEPT_CAPS:
2864     {
2865       GstCaps *caps;
2866
2867       gst_query_parse_accept_caps (query, &caps);
2868       ret = gst_pulsesink_query_acceptcaps (pulsesink, caps);
2869       gst_query_set_accept_caps_result (query, ret);
2870       ret = TRUE;
2871       break;
2872     }
2873     default:
2874       ret = GST_BASE_SINK_CLASS (parent_class)->query (sink, query);
2875       break;
2876   }
2877   return ret;
2878 }
2879
2880 static void
2881 gst_pulsesink_release_mainloop (GstPulseSink * psink)
2882 {
2883   if (!mainloop)
2884     return;
2885
2886   pa_threaded_mainloop_lock (mainloop);
2887   while (psink->defer_pending) {
2888     GST_DEBUG_OBJECT (psink, "waiting for stream status message emission");
2889     pa_threaded_mainloop_wait (mainloop);
2890   }
2891   pa_threaded_mainloop_unlock (mainloop);
2892
2893   g_mutex_lock (&pa_shared_resource_mutex);
2894   mainloop_ref_ct--;
2895   if (!mainloop_ref_ct) {
2896     GST_INFO_OBJECT (psink, "terminating pa main loop thread");
2897     pa_threaded_mainloop_stop (mainloop);
2898     pa_threaded_mainloop_free (mainloop);
2899     mainloop = NULL;
2900   }
2901   g_mutex_unlock (&pa_shared_resource_mutex);
2902 }
2903
2904 static GstStateChangeReturn
2905 gst_pulsesink_change_state (GstElement * element, GstStateChange transition)
2906 {
2907   GstPulseSink *pulsesink = GST_PULSESINK (element);
2908   GstStateChangeReturn ret;
2909
2910   switch (transition) {
2911     case GST_STATE_CHANGE_NULL_TO_READY:
2912       g_mutex_lock (&pa_shared_resource_mutex);
2913       if (!mainloop_ref_ct) {
2914         GST_INFO_OBJECT (element, "new pa main loop thread");
2915         if (!(mainloop = pa_threaded_mainloop_new ()))
2916           goto mainloop_failed;
2917         if (pa_threaded_mainloop_start (mainloop) < 0) {
2918           pa_threaded_mainloop_free (mainloop);
2919           goto mainloop_start_failed;
2920         }
2921         mainloop_ref_ct = 1;
2922         g_mutex_unlock (&pa_shared_resource_mutex);
2923       } else {
2924         GST_INFO_OBJECT (element, "reusing pa main loop thread");
2925         mainloop_ref_ct++;
2926         g_mutex_unlock (&pa_shared_resource_mutex);
2927       }
2928       break;
2929     case GST_STATE_CHANGE_READY_TO_PAUSED:
2930       gst_element_post_message (element,
2931           gst_message_new_clock_provide (GST_OBJECT_CAST (element),
2932               GST_AUDIO_BASE_SINK (pulsesink)->provided_clock, TRUE));
2933       break;
2934
2935     default:
2936       break;
2937   }
2938
2939   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2940   if (ret == GST_STATE_CHANGE_FAILURE)
2941     goto state_failure;
2942
2943   switch (transition) {
2944     case GST_STATE_CHANGE_PAUSED_TO_READY:
2945       /* format_lost is reset in release() in audiobasesink */
2946       gst_element_post_message (element,
2947           gst_message_new_clock_lost (GST_OBJECT_CAST (element),
2948               GST_AUDIO_BASE_SINK (pulsesink)->provided_clock));
2949       break;
2950     case GST_STATE_CHANGE_READY_TO_NULL:
2951       gst_pulsesink_release_mainloop (pulsesink);
2952       break;
2953     default:
2954       break;
2955   }
2956
2957   return ret;
2958
2959   /* ERRORS */
2960 mainloop_failed:
2961   {
2962     g_mutex_unlock (&pa_shared_resource_mutex);
2963     GST_ELEMENT_ERROR (pulsesink, RESOURCE, FAILED,
2964         ("pa_threaded_mainloop_new() failed"), (NULL));
2965     return GST_STATE_CHANGE_FAILURE;
2966   }
2967 mainloop_start_failed:
2968   {
2969     g_mutex_unlock (&pa_shared_resource_mutex);
2970     GST_ELEMENT_ERROR (pulsesink, RESOURCE, FAILED,
2971         ("pa_threaded_mainloop_start() failed"), (NULL));
2972     return GST_STATE_CHANGE_FAILURE;
2973   }
2974 state_failure:
2975   {
2976     if (transition == GST_STATE_CHANGE_NULL_TO_READY) {
2977       /* Clear the PA mainloop if audiobasesink failed to open the ring_buffer */
2978       g_assert (mainloop);
2979       gst_pulsesink_release_mainloop (pulsesink);
2980     }
2981     return ret;
2982   }
2983 }