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