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