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