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