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