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