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