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