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