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