pulse: Use new GType for GThread instead of just G_TYPE_POINTER
[platform/upstream/gstreamer.git] / ext / pulse / pulsesink.c
1 /*-*- Mode: C; c-basic-offset: 2 -*-*/
2
3 /*  GStreamer pulseaudio plugin
4  *
5  *  Copyright (c) 2004-2008 Lennart Poettering
6  *            (c) 2009      Wim Taymans
7  *
8  *  gst-pulse is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU Lesser General Public License as
10  *  published by the Free Software Foundation; either version 2.1 of the
11  *  License, or (at your option) any later version.
12  *
13  *  gst-pulse is distributed in the hope that it will be useful, but
14  *  WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  *  Lesser General Public License for more details.
17  *
18  *  You should have received a copy of the GNU Lesser General Public
19  *  License along with gst-pulse; if not, write to the Free Software
20  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
21  *  USA.
22  */
23
24 /**
25  * SECTION:element-pulsesink
26  * @see_also: pulsesrc
27  *
28  * This element outputs audio to a
29  * <ulink href="http://www.pulseaudio.org">PulseAudio sound server</ulink>.
30  *
31  * <refsect2>
32  * <title>Example pipelines</title>
33  * |[
34  * gst-launch-1.0 -v filesrc location=sine.ogg ! oggdemux ! vorbisdec ! audioconvert ! audioresample ! pulsesink
35  * ]| Play an Ogg/Vorbis file.
36  * |[
37  * gst-launch-1.0 -v audiotestsrc ! audioconvert ! volume volume=0.4 ! pulsesink
38  * ]| Play a 440Hz sine wave.
39  * |[
40  * gst-launch-1.0 -v audiotestsrc ! pulsesink stream-properties="props,media.title=test"
41  * ]| Play a sine wave and set a stream property. The property can be checked
42  * with "pactl list".
43  * </refsect2>
44  */
45
46 #ifdef HAVE_CONFIG_H
47 #include "config.h"
48 #endif
49
50 #include <string.h>
51 #include <stdio.h>
52
53 #include <gst/base/gstbasesink.h>
54 #include <gst/gsttaglist.h>
55 #include <gst/audio/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   GST_DEBUG_OBJECT (pulsesink, "posting ENTER stream status");
1113   message = gst_message_new_stream_status (GST_OBJECT (pulsesink),
1114       GST_STREAM_STATUS_TYPE_ENTER, GST_ELEMENT (pulsesink));
1115   g_value_init (&val, GST_TYPE_G_THREAD);
1116   g_value_set_boxed (&val, g_thread_self ());
1117   gst_message_set_stream_status_object (message, &val);
1118   g_value_unset (&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   GST_DEBUG_OBJECT (pulsesink, "posting LEAVE stream status");
1192   message = gst_message_new_stream_status (GST_OBJECT (pulsesink),
1193       GST_STREAM_STATUS_TYPE_LEAVE, GST_ELEMENT (pulsesink));
1194   g_value_init (&val, GST_TYPE_G_THREAD);
1195   g_value_set_boxed (&val, g_thread_self ());
1196   gst_message_set_stream_status_object (message, &val);
1197   g_value_unset (&val);
1198
1199   gst_element_post_message (GST_ELEMENT (pulsesink), message);
1200
1201   g_return_if_fail (pulsesink->defer_pending);
1202   pulsesink->defer_pending--;
1203   pa_threaded_mainloop_signal (mainloop, 0);
1204 }
1205
1206 /* stop playback, we flush everything. */
1207 static gboolean
1208 gst_pulseringbuffer_stop (GstAudioRingBuffer * buf)
1209 {
1210   GstPulseSink *psink;
1211   GstPulseRingBuffer *pbuf;
1212   gboolean res = FALSE;
1213   pa_operation *o = NULL;
1214
1215   pbuf = GST_PULSERING_BUFFER_CAST (buf);
1216   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1217
1218   pa_threaded_mainloop_lock (mainloop);
1219
1220   pbuf->paused = TRUE;
1221   res = gst_pulsering_set_corked (pbuf, TRUE, TRUE);
1222
1223   /* Inform anyone waiting in _commit() call that it shall wakeup */
1224   if (pbuf->in_commit) {
1225     GST_DEBUG_OBJECT (psink, "signal commit thread");
1226     pa_threaded_mainloop_signal (mainloop, 0);
1227   }
1228   if (g_atomic_int_get (&psink->format_lost)) {
1229     /* Don't try to flush, the stream's probably gone by now */
1230     res = TRUE;
1231     goto cleanup;
1232   }
1233
1234   /* then try to flush, it's not fatal when this fails */
1235   GST_DEBUG_OBJECT (psink, "flushing");
1236   if ((o = pa_stream_flush (pbuf->stream, gst_pulsering_success_cb, pbuf))) {
1237     while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
1238       GST_DEBUG_OBJECT (psink, "wait for completion");
1239       pa_threaded_mainloop_wait (mainloop);
1240       if (gst_pulsering_is_dead (psink, pbuf, TRUE))
1241         goto server_dead;
1242     }
1243     GST_DEBUG_OBJECT (psink, "flush completed");
1244   }
1245   res = TRUE;
1246
1247 cleanup:
1248   if (o) {
1249     pa_operation_cancel (o);
1250     pa_operation_unref (o);
1251   }
1252
1253   GST_DEBUG_OBJECT (psink, "scheduling stream status");
1254   psink->defer_pending++;
1255   pa_mainloop_api_once (pa_threaded_mainloop_get_api (mainloop),
1256       mainloop_leave_defer_cb, psink);
1257
1258   pa_threaded_mainloop_unlock (mainloop);
1259
1260   return res;
1261
1262   /* ERRORS */
1263 server_dead:
1264   {
1265     GST_DEBUG_OBJECT (psink, "the server is dead");
1266     goto cleanup;
1267   }
1268 }
1269
1270 /* in_samples >= out_samples, rate > 1.0 */
1271 #define FWD_UP_SAMPLES(s,se,d,de)               \
1272 G_STMT_START {                                  \
1273   guint8 *sb = s, *db = d;                      \
1274   while (s <= se && d < de) {                   \
1275     memcpy (d, s, bpf);                         \
1276     s += bpf;                                   \
1277     *accum += outr;                             \
1278     if ((*accum << 1) >= inr) {                 \
1279       *accum -= inr;                            \
1280       d += bpf;                                 \
1281     }                                           \
1282   }                                             \
1283   in_samples -= (s - sb)/bpf;                   \
1284   out_samples -= (d - db)/bpf;                  \
1285   GST_DEBUG ("fwd_up end %d/%d",*accum,*toprocess);     \
1286 } G_STMT_END
1287
1288 /* out_samples > in_samples, for rates smaller than 1.0 */
1289 #define FWD_DOWN_SAMPLES(s,se,d,de)             \
1290 G_STMT_START {                                  \
1291   guint8 *sb = s, *db = d;                      \
1292   while (s <= se && d < de) {                   \
1293     memcpy (d, s, bpf);                         \
1294     d += bpf;                                   \
1295     *accum += inr;                              \
1296     if ((*accum << 1) >= outr) {                \
1297       *accum -= outr;                           \
1298       s += bpf;                                 \
1299     }                                           \
1300   }                                             \
1301   in_samples -= (s - sb)/bpf;                   \
1302   out_samples -= (d - db)/bpf;                  \
1303   GST_DEBUG ("fwd_down end %d/%d",*accum,*toprocess);   \
1304 } G_STMT_END
1305
1306 #define REV_UP_SAMPLES(s,se,d,de)               \
1307 G_STMT_START {                                  \
1308   guint8 *sb = se, *db = d;                     \
1309   while (s <= se && d < de) {                   \
1310     memcpy (d, se, bpf);                        \
1311     se -= bpf;                                  \
1312     *accum += outr;                             \
1313     while (d < de && (*accum << 1) >= inr) {    \
1314       *accum -= inr;                            \
1315       d += bpf;                                 \
1316     }                                           \
1317   }                                             \
1318   in_samples -= (sb - se)/bpf;                  \
1319   out_samples -= (d - db)/bpf;                  \
1320   GST_DEBUG ("rev_up end %d/%d",*accum,*toprocess);     \
1321 } G_STMT_END
1322
1323 #define REV_DOWN_SAMPLES(s,se,d,de)             \
1324 G_STMT_START {                                  \
1325   guint8 *sb = se, *db = d;                     \
1326   while (s <= se && d < de) {                   \
1327     memcpy (d, se, bpf);                        \
1328     d += bpf;                                   \
1329     *accum += inr;                              \
1330     while (s <= se && (*accum << 1) >= outr) {  \
1331       *accum -= outr;                           \
1332       se -= bpf;                                \
1333     }                                           \
1334   }                                             \
1335   in_samples -= (sb - se)/bpf;                  \
1336   out_samples -= (d - db)/bpf;                  \
1337   GST_DEBUG ("rev_down end %d/%d",*accum,*toprocess);   \
1338 } G_STMT_END
1339
1340 /* our custom commit function because we write into the buffer of pulseaudio
1341  * instead of keeping our own buffer */
1342 static guint
1343 gst_pulseringbuffer_commit (GstAudioRingBuffer * buf, guint64 * sample,
1344     guchar * data, gint in_samples, gint out_samples, gint * accum)
1345 {
1346   GstPulseSink *psink;
1347   GstPulseRingBuffer *pbuf;
1348   guint result;
1349   guint8 *data_end;
1350   gboolean reverse;
1351   gint *toprocess;
1352   gint inr, outr, bpf;
1353   gint64 offset;
1354   guint bufsize;
1355
1356   pbuf = GST_PULSERING_BUFFER_CAST (buf);
1357   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1358
1359   /* FIXME post message rather than using a signal (as mixer interface) */
1360   if (g_atomic_int_compare_and_exchange (&psink->notify, 1, 0)) {
1361     g_object_notify (G_OBJECT (psink), "volume");
1362     g_object_notify (G_OBJECT (psink), "mute");
1363   }
1364
1365   /* make sure the ringbuffer is started */
1366   if (G_UNLIKELY (g_atomic_int_get (&buf->state) !=
1367           GST_AUDIO_RING_BUFFER_STATE_STARTED)) {
1368     /* see if we are allowed to start it */
1369     if (G_UNLIKELY (g_atomic_int_get (&buf->may_start) == FALSE))
1370       goto no_start;
1371
1372     GST_DEBUG_OBJECT (buf, "start!");
1373     if (!gst_audio_ring_buffer_start (buf))
1374       goto start_failed;
1375   }
1376
1377   pa_threaded_mainloop_lock (mainloop);
1378
1379   GST_DEBUG_OBJECT (psink, "entering commit");
1380   pbuf->in_commit = TRUE;
1381
1382   bpf = GST_AUDIO_INFO_BPF (&buf->spec.info);
1383   bufsize = buf->spec.segsize * buf->spec.segtotal;
1384
1385   /* our toy resampler for trick modes */
1386   reverse = out_samples < 0;
1387   out_samples = ABS (out_samples);
1388
1389   if (in_samples >= out_samples)
1390     toprocess = &in_samples;
1391   else
1392     toprocess = &out_samples;
1393
1394   inr = in_samples - 1;
1395   outr = out_samples - 1;
1396
1397   GST_DEBUG_OBJECT (psink, "in %d, out %d", inr, outr);
1398
1399   /* data_end points to the last sample we have to write, not past it. This is
1400    * needed to properly handle reverse playback: it points to the last sample. */
1401   data_end = data + (bpf * inr);
1402
1403   if (g_atomic_int_get (&psink->format_lost)) {
1404     /* Sink format changed, drop the data and hope upstream renegotiates */
1405     goto fake_done;
1406   }
1407
1408   if (pbuf->paused)
1409     goto was_paused;
1410
1411   /* offset is in bytes */
1412   offset = *sample * bpf;
1413
1414   while (*toprocess > 0) {
1415     size_t avail;
1416     guint towrite;
1417
1418     GST_LOG_OBJECT (psink,
1419         "need to write %d samples at offset %" G_GINT64_FORMAT, *toprocess,
1420         offset);
1421
1422     if (offset != pbuf->m_lastoffset)
1423       GST_LOG_OBJECT (psink, "discontinuity, offset is %" G_GINT64_FORMAT ", "
1424           "last offset was %" G_GINT64_FORMAT, offset, pbuf->m_lastoffset);
1425
1426     towrite = out_samples * bpf;
1427
1428     /* Wait for at least segsize bytes to become available */
1429     if (towrite > buf->spec.segsize)
1430       towrite = buf->spec.segsize;
1431
1432     if ((pbuf->m_writable < towrite) || (offset != pbuf->m_lastoffset)) {
1433       /* if no room left or discontinuity in offset,
1434          we need to flush data and get a new buffer */
1435
1436       /* flush the buffer if possible */
1437       if ((pbuf->m_data != NULL) && (pbuf->m_towrite > 0)) {
1438
1439         GST_LOG_OBJECT (psink,
1440             "flushing %u samples at offset %" G_GINT64_FORMAT,
1441             (guint) pbuf->m_towrite / bpf, pbuf->m_offset);
1442
1443         if (pa_stream_write (pbuf->stream, (uint8_t *) pbuf->m_data,
1444                 pbuf->m_towrite, NULL, pbuf->m_offset, PA_SEEK_ABSOLUTE) < 0) {
1445           goto write_failed;
1446         }
1447       }
1448       pbuf->m_towrite = 0;
1449       pbuf->m_offset = offset;  /* keep track of current offset */
1450
1451       /* get a buffer to write in for now on */
1452       for (;;) {
1453         pbuf->m_writable = pa_stream_writable_size (pbuf->stream);
1454
1455         if (g_atomic_int_get (&psink->format_lost)) {
1456           /* Sink format changed, give up and hope upstream renegotiates */
1457           goto fake_done;
1458         }
1459
1460         if (pbuf->m_writable == (size_t) - 1)
1461           goto writable_size_failed;
1462
1463         pbuf->m_writable /= bpf;
1464         pbuf->m_writable *= bpf;        /* handle only complete samples */
1465
1466         if (pbuf->m_writable >= towrite)
1467           break;
1468
1469         /* see if we need to uncork because we have no free space */
1470         if (pbuf->corked) {
1471           if (!gst_pulsering_set_corked (pbuf, FALSE, FALSE))
1472             goto uncork_failed;
1473         }
1474
1475         /* we can't write segsize bytes, wait a bit */
1476         GST_LOG_OBJECT (psink, "waiting for free space");
1477         pa_threaded_mainloop_wait (mainloop);
1478
1479         if (pbuf->paused)
1480           goto was_paused;
1481       }
1482
1483       /* Recalculate what we can write in the next chunk */
1484       towrite = out_samples * bpf;
1485       if (pbuf->m_writable > towrite)
1486         pbuf->m_writable = towrite;
1487
1488       GST_LOG_OBJECT (psink, "requesting %" G_GSIZE_FORMAT " bytes of "
1489           "shared memory", pbuf->m_writable);
1490
1491       if (pa_stream_begin_write (pbuf->stream, &pbuf->m_data,
1492               &pbuf->m_writable) < 0) {
1493         GST_LOG_OBJECT (psink, "pa_stream_begin_write() failed");
1494         goto writable_size_failed;
1495       }
1496
1497       GST_LOG_OBJECT (psink, "got %" G_GSIZE_FORMAT " bytes of shared memory",
1498           pbuf->m_writable);
1499
1500     }
1501
1502     if (towrite > pbuf->m_writable)
1503       towrite = pbuf->m_writable;
1504     avail = towrite / bpf;
1505
1506     GST_LOG_OBJECT (psink, "writing %u samples at offset %" G_GUINT64_FORMAT,
1507         (guint) avail, offset);
1508
1509     /* No trick modes for passthrough streams */
1510     if (G_UNLIKELY (!pbuf->is_pcm && (inr != outr || reverse))) {
1511       GST_WARNING_OBJECT (psink, "Passthrough stream can't run in trick mode");
1512       goto unlock_and_fail;
1513     }
1514
1515     if (G_LIKELY (inr == outr && !reverse)) {
1516       /* no rate conversion, simply write out the samples */
1517       /* copy the data into internal buffer */
1518
1519       memcpy ((guint8 *) pbuf->m_data + pbuf->m_towrite, data, towrite);
1520       pbuf->m_towrite += towrite;
1521       pbuf->m_writable -= towrite;
1522
1523       data += towrite;
1524       in_samples -= avail;
1525       out_samples -= avail;
1526     } else {
1527       guint8 *dest, *d, *d_end;
1528
1529       /* write into the PulseAudio shm buffer */
1530       dest = d = (guint8 *) pbuf->m_data + pbuf->m_towrite;
1531       d_end = d + towrite;
1532
1533       if (!reverse) {
1534         if (inr >= outr)
1535           /* forward speed up */
1536           FWD_UP_SAMPLES (data, data_end, d, d_end);
1537         else
1538           /* forward slow down */
1539           FWD_DOWN_SAMPLES (data, data_end, d, d_end);
1540       } else {
1541         if (inr >= outr)
1542           /* reverse speed up */
1543           REV_UP_SAMPLES (data, data_end, d, d_end);
1544         else
1545           /* reverse slow down */
1546           REV_DOWN_SAMPLES (data, data_end, d, d_end);
1547       }
1548       /* see what we have left to write */
1549       towrite = (d - dest);
1550       pbuf->m_towrite += towrite;
1551       pbuf->m_writable -= towrite;
1552
1553       avail = towrite / bpf;
1554     }
1555
1556     /* flush the buffer if it's full */
1557     if ((pbuf->m_data != NULL) && (pbuf->m_towrite > 0)
1558         && (pbuf->m_writable == 0)) {
1559       GST_LOG_OBJECT (psink, "flushing %u samples at offset %" G_GINT64_FORMAT,
1560           (guint) pbuf->m_towrite / bpf, pbuf->m_offset);
1561
1562       if (pa_stream_write (pbuf->stream, (uint8_t *) pbuf->m_data,
1563               pbuf->m_towrite, NULL, pbuf->m_offset, PA_SEEK_ABSOLUTE) < 0) {
1564         goto write_failed;
1565       }
1566       pbuf->m_towrite = 0;
1567       pbuf->m_offset = offset + towrite;        /* keep track of current offset */
1568     }
1569
1570     *sample += avail;
1571     offset += avail * bpf;
1572     pbuf->m_lastoffset = offset;
1573
1574     /* check if we need to uncork after writing the samples */
1575     if (pbuf->corked) {
1576       const pa_timing_info *info;
1577
1578       if ((info = pa_stream_get_timing_info (pbuf->stream))) {
1579         GST_LOG_OBJECT (psink,
1580             "read_index at %" G_GUINT64_FORMAT ", offset %" G_GINT64_FORMAT,
1581             info->read_index, offset);
1582
1583         /* we uncork when the read_index is too far behind the offset we need
1584          * to write to. */
1585         if (info->read_index + bufsize <= offset) {
1586           if (!gst_pulsering_set_corked (pbuf, FALSE, FALSE))
1587             goto uncork_failed;
1588         }
1589       } else {
1590         GST_LOG_OBJECT (psink, "no timing info available yet");
1591       }
1592     }
1593   }
1594
1595 fake_done:
1596   /* we consumed all samples here */
1597   data = data_end + bpf;
1598
1599   pbuf->in_commit = FALSE;
1600   pa_threaded_mainloop_unlock (mainloop);
1601
1602 done:
1603   result = inr - ((data_end - data) / bpf);
1604   GST_LOG_OBJECT (psink, "wrote %d samples", result);
1605
1606   return result;
1607
1608   /* ERRORS */
1609 unlock_and_fail:
1610   {
1611     pbuf->in_commit = FALSE;
1612     GST_LOG_OBJECT (psink, "we are reset");
1613     pa_threaded_mainloop_unlock (mainloop);
1614     goto done;
1615   }
1616 no_start:
1617   {
1618     GST_LOG_OBJECT (psink, "we can not start");
1619     return 0;
1620   }
1621 start_failed:
1622   {
1623     GST_LOG_OBJECT (psink, "failed to start the ringbuffer");
1624     return 0;
1625   }
1626 uncork_failed:
1627   {
1628     pbuf->in_commit = FALSE;
1629     GST_ERROR_OBJECT (psink, "uncork failed");
1630     pa_threaded_mainloop_unlock (mainloop);
1631     goto done;
1632   }
1633 was_paused:
1634   {
1635     pbuf->in_commit = FALSE;
1636     GST_LOG_OBJECT (psink, "we are paused");
1637     pa_threaded_mainloop_unlock (mainloop);
1638     goto done;
1639   }
1640 writable_size_failed:
1641   {
1642     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1643         ("pa_stream_writable_size() failed: %s",
1644             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1645     goto unlock_and_fail;
1646   }
1647 write_failed:
1648   {
1649     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1650         ("pa_stream_write() failed: %s",
1651             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1652     goto unlock_and_fail;
1653   }
1654 }
1655
1656 /* write pending local samples, must be called with the mainloop lock */
1657 static void
1658 gst_pulsering_flush (GstPulseRingBuffer * pbuf)
1659 {
1660   GstPulseSink *psink;
1661
1662   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1663   GST_DEBUG_OBJECT (psink, "entering flush");
1664
1665   /* flush the buffer if possible */
1666   if (pbuf->stream && (pbuf->m_data != NULL) && (pbuf->m_towrite > 0)) {
1667 #ifndef GST_DISABLE_GST_DEBUG
1668     gint bpf;
1669
1670     bpf = (GST_AUDIO_RING_BUFFER_CAST (pbuf))->spec.info.bpf;
1671     GST_LOG_OBJECT (psink,
1672         "flushing %u samples at offset %" G_GINT64_FORMAT,
1673         (guint) pbuf->m_towrite / bpf, pbuf->m_offset);
1674 #endif
1675
1676     if (pa_stream_write (pbuf->stream, (uint8_t *) pbuf->m_data,
1677             pbuf->m_towrite, NULL, pbuf->m_offset, PA_SEEK_ABSOLUTE) < 0) {
1678       goto write_failed;
1679     }
1680
1681     pbuf->m_towrite = 0;
1682     pbuf->m_offset += pbuf->m_towrite;  /* keep track of current offset */
1683   }
1684
1685 done:
1686   return;
1687
1688   /* ERRORS */
1689 write_failed:
1690   {
1691     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1692         ("pa_stream_write() failed: %s",
1693             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1694     goto done;
1695   }
1696 }
1697
1698 static void gst_pulsesink_set_property (GObject * object, guint prop_id,
1699     const GValue * value, GParamSpec * pspec);
1700 static void gst_pulsesink_get_property (GObject * object, guint prop_id,
1701     GValue * value, GParamSpec * pspec);
1702 static void gst_pulsesink_finalize (GObject * object);
1703
1704 static gboolean gst_pulsesink_event (GstBaseSink * sink, GstEvent * event);
1705 static gboolean gst_pulsesink_query (GstBaseSink * sink, GstQuery * query);
1706
1707 static GstStateChangeReturn gst_pulsesink_change_state (GstElement * element,
1708     GstStateChange transition);
1709
1710 static GstStaticPadTemplate pad_template = GST_STATIC_PAD_TEMPLATE ("sink",
1711     GST_PAD_SINK,
1712     GST_PAD_ALWAYS,
1713     GST_STATIC_CAPS (PULSE_SINK_TEMPLATE_CAPS));
1714
1715 #define gst_pulsesink_parent_class parent_class
1716 G_DEFINE_TYPE_WITH_CODE (GstPulseSink, gst_pulsesink, GST_TYPE_AUDIO_BASE_SINK,
1717     gst_pulsesink_init_contexts ();
1718     G_IMPLEMENT_INTERFACE (GST_TYPE_STREAM_VOLUME, NULL)
1719     );
1720
1721 static GstAudioRingBuffer *
1722 gst_pulsesink_create_ringbuffer (GstAudioBaseSink * sink)
1723 {
1724   GstAudioRingBuffer *buffer;
1725
1726   GST_DEBUG_OBJECT (sink, "creating ringbuffer");
1727   buffer = g_object_new (GST_TYPE_PULSERING_BUFFER, NULL);
1728   GST_DEBUG_OBJECT (sink, "created ringbuffer @%p", buffer);
1729
1730   return buffer;
1731 }
1732
1733 static GstBuffer *
1734 gst_pulsesink_payload (GstAudioBaseSink * sink, GstBuffer * buf)
1735 {
1736   switch (sink->ringbuffer->spec.type) {
1737     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_AC3:
1738     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_EAC3:
1739     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_DTS:
1740     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_MPEG:
1741     {
1742       /* FIXME: alloc memory from PA if possible */
1743       gint framesize = gst_audio_iec61937_frame_size (&sink->ringbuffer->spec);
1744       GstBuffer *out;
1745       GstMapInfo inmap, outmap;
1746       gboolean res;
1747
1748       if (framesize <= 0)
1749         return NULL;
1750
1751       out = gst_buffer_new_and_alloc (framesize);
1752
1753       gst_buffer_map (buf, &inmap, GST_MAP_READ);
1754       gst_buffer_map (out, &outmap, GST_MAP_WRITE);
1755
1756       res = gst_audio_iec61937_payload (inmap.data, inmap.size,
1757           outmap.data, outmap.size, &sink->ringbuffer->spec, G_BIG_ENDIAN);
1758
1759       gst_buffer_unmap (buf, &inmap);
1760       gst_buffer_unmap (out, &outmap);
1761
1762       if (!res) {
1763         gst_buffer_unref (out);
1764         return NULL;
1765       }
1766
1767       gst_buffer_copy_into (out, buf, GST_BUFFER_COPY_METADATA, 0, -1);
1768       return out;
1769     }
1770
1771     default:
1772       return gst_buffer_ref (buf);
1773   }
1774 }
1775
1776 static void
1777 gst_pulsesink_class_init (GstPulseSinkClass * klass)
1778 {
1779   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1780   GstBaseSinkClass *gstbasesink_class = GST_BASE_SINK_CLASS (klass);
1781   GstBaseSinkClass *bc;
1782   GstAudioBaseSinkClass *gstaudiosink_class = GST_AUDIO_BASE_SINK_CLASS (klass);
1783   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
1784   gchar *clientname;
1785
1786   gobject_class->finalize = gst_pulsesink_finalize;
1787   gobject_class->set_property = gst_pulsesink_set_property;
1788   gobject_class->get_property = gst_pulsesink_get_property;
1789
1790   gstbasesink_class->event = GST_DEBUG_FUNCPTR (gst_pulsesink_event);
1791   gstbasesink_class->query = GST_DEBUG_FUNCPTR (gst_pulsesink_query);
1792
1793   /* restore the original basesink pull methods */
1794   bc = g_type_class_peek (GST_TYPE_BASE_SINK);
1795   gstbasesink_class->activate_pull = GST_DEBUG_FUNCPTR (bc->activate_pull);
1796
1797   gstelement_class->change_state =
1798       GST_DEBUG_FUNCPTR (gst_pulsesink_change_state);
1799
1800   gstaudiosink_class->create_ringbuffer =
1801       GST_DEBUG_FUNCPTR (gst_pulsesink_create_ringbuffer);
1802   gstaudiosink_class->payload = GST_DEBUG_FUNCPTR (gst_pulsesink_payload);
1803
1804   /* Overwrite GObject fields */
1805   g_object_class_install_property (gobject_class,
1806       PROP_SERVER,
1807       g_param_spec_string ("server", "Server",
1808           "The PulseAudio server to connect to", DEFAULT_SERVER,
1809           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1810
1811   g_object_class_install_property (gobject_class, PROP_DEVICE,
1812       g_param_spec_string ("device", "Device",
1813           "The PulseAudio sink device to connect to", DEFAULT_DEVICE,
1814           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1815
1816   g_object_class_install_property (gobject_class,
1817       PROP_DEVICE_NAME,
1818       g_param_spec_string ("device-name", "Device name",
1819           "Human-readable name of the sound device", DEFAULT_DEVICE_NAME,
1820           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
1821
1822   g_object_class_install_property (gobject_class,
1823       PROP_VOLUME,
1824       g_param_spec_double ("volume", "Volume",
1825           "Linear volume of this stream, 1.0=100%", 0.0, MAX_VOLUME,
1826           DEFAULT_VOLUME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1827   g_object_class_install_property (gobject_class,
1828       PROP_MUTE,
1829       g_param_spec_boolean ("mute", "Mute",
1830           "Mute state of this stream", DEFAULT_MUTE,
1831           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1832
1833   /**
1834    * GstPulseSink:client-name
1835    *
1836    * The PulseAudio client name to use.
1837    */
1838   clientname = gst_pulse_client_name ();
1839   g_object_class_install_property (gobject_class,
1840       PROP_CLIENT_NAME,
1841       g_param_spec_string ("client-name", "Client Name",
1842           "The PulseAudio client name to use", clientname,
1843           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
1844           GST_PARAM_MUTABLE_READY));
1845   g_free (clientname);
1846
1847   /**
1848    * GstPulseSink:stream-properties
1849    *
1850    * List of pulseaudio stream properties. A list of defined properties can be
1851    * found in the <ulink url="http://0pointer.de/lennart/projects/pulseaudio/doxygen/proplist_8h.html">pulseaudio api docs</ulink>.
1852    *
1853    * Below is an example for registering as a music application to pulseaudio.
1854    * |[
1855    * GstStructure *props;
1856    *
1857    * props = gst_structure_from_string ("props,media.role=music", NULL);
1858    * g_object_set (pulse, "stream-properties", props, NULL);
1859    * gst_structure_free
1860    * ]|
1861    *
1862    * Since: 0.10.26
1863    */
1864   g_object_class_install_property (gobject_class,
1865       PROP_STREAM_PROPERTIES,
1866       g_param_spec_boxed ("stream-properties", "stream properties",
1867           "list of pulseaudio stream properties",
1868           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1869
1870   gst_element_class_set_static_metadata (gstelement_class,
1871       "PulseAudio Audio Sink",
1872       "Sink/Audio", "Plays audio to a PulseAudio server", "Lennart Poettering");
1873   gst_element_class_add_pad_template (gstelement_class,
1874       gst_static_pad_template_get (&pad_template));
1875 }
1876
1877 /* returns the current time of the sink ringbuffer */
1878 static GstClockTime
1879 gst_pulsesink_get_time (GstClock * clock, GstAudioBaseSink * sink)
1880 {
1881   GstPulseSink *psink;
1882   GstPulseRingBuffer *pbuf;
1883   pa_usec_t time;
1884
1885   if (!sink->ringbuffer || !sink->ringbuffer->acquired)
1886     return GST_CLOCK_TIME_NONE;
1887
1888   pbuf = GST_PULSERING_BUFFER_CAST (sink->ringbuffer);
1889   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1890
1891   if (g_atomic_int_get (&psink->format_lost)) {
1892     /* Stream was lost in a format change, it'll get set up again once
1893      * upstream renegotiates */
1894     return psink->format_lost_time;
1895   }
1896
1897   pa_threaded_mainloop_lock (mainloop);
1898   if (gst_pulsering_is_dead (psink, pbuf, TRUE))
1899     goto server_dead;
1900
1901   /* if we don't have enough data to get a timestamp, just return NONE, which
1902    * will return the last reported time */
1903   if (pa_stream_get_time (pbuf->stream, &time) < 0) {
1904     GST_DEBUG_OBJECT (psink, "could not get time");
1905     time = GST_CLOCK_TIME_NONE;
1906   } else
1907     time *= 1000;
1908   pa_threaded_mainloop_unlock (mainloop);
1909
1910   GST_LOG_OBJECT (psink, "current time is %" GST_TIME_FORMAT,
1911       GST_TIME_ARGS (time));
1912
1913   return time;
1914
1915   /* ERRORS */
1916 server_dead:
1917   {
1918     GST_DEBUG_OBJECT (psink, "the server is dead");
1919     pa_threaded_mainloop_unlock (mainloop);
1920
1921     return GST_CLOCK_TIME_NONE;
1922   }
1923 }
1924
1925 static void
1926 gst_pulsesink_sink_info_cb (pa_context * c, const pa_sink_info * i, int eol,
1927     void *userdata)
1928 {
1929   GstPulseRingBuffer *pbuf;
1930   GstPulseSink *psink;
1931   GList *l;
1932   guint8 j;
1933
1934   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
1935   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1936
1937   if (!i)
1938     goto done;
1939
1940   g_free (psink->device_description);
1941   psink->device_description = g_strdup (i->description);
1942
1943   g_mutex_lock (&psink->sink_formats_lock);
1944
1945   for (l = g_list_first (psink->sink_formats); l; l = g_list_next (l))
1946     pa_format_info_free ((pa_format_info *) l->data);
1947
1948   g_list_free (psink->sink_formats);
1949   psink->sink_formats = NULL;
1950
1951   for (j = 0; j < i->n_formats; j++)
1952     psink->sink_formats = g_list_prepend (psink->sink_formats,
1953         pa_format_info_copy (i->formats[j]));
1954
1955   g_mutex_unlock (&psink->sink_formats_lock);
1956
1957 done:
1958   pa_threaded_mainloop_signal (mainloop, 0);
1959 }
1960
1961 static gboolean
1962 gst_pulsesink_query_acceptcaps (GstPulseSink * psink, GstCaps * caps)
1963 {
1964   GstPulseRingBuffer *pbuf = NULL;
1965   GstCaps *pad_caps;
1966   GstStructure *st;
1967   gboolean ret = FALSE;
1968
1969   GstAudioRingBufferSpec spec = { 0 };
1970   pa_stream *stream = NULL;
1971   pa_operation *o = NULL;
1972   pa_channel_map channel_map;
1973   pa_stream_flags_t flags;
1974   pa_format_info *format = NULL, *formats[1];
1975   guint channels;
1976
1977   pad_caps = gst_pad_query_caps (GST_BASE_SINK_PAD (psink), caps);
1978   ret = pad_caps != NULL;
1979   gst_caps_unref (pad_caps);
1980
1981   GST_DEBUG_OBJECT (psink, "caps %" GST_PTR_FORMAT, caps);
1982
1983   /* Template caps didn't match */
1984   if (!ret)
1985     goto done;
1986
1987   /* If we've not got fixed caps, creating a stream might fail, so let's just
1988    * return from here with default acceptcaps behaviour */
1989   if (!gst_caps_is_fixed (caps))
1990     goto done;
1991
1992   GST_OBJECT_LOCK (psink);
1993   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
1994   if (pbuf != NULL)
1995     gst_object_ref (pbuf);
1996   GST_OBJECT_UNLOCK (psink);
1997
1998   /* We're still in NULL state */
1999   if (pbuf == NULL)
2000     goto done;
2001
2002   pa_threaded_mainloop_lock (mainloop);
2003
2004   if (pbuf->context == NULL)
2005     goto out;
2006
2007   ret = FALSE;
2008
2009   spec.latency_time = GST_AUDIO_BASE_SINK (psink)->latency_time;
2010   if (!gst_audio_ring_buffer_parse_caps (&spec, caps))
2011     goto out;
2012
2013   if (!gst_pulse_fill_format_info (&spec, &format, &channels))
2014     goto out;
2015
2016   /* Make sure input is framed (one frame per buffer) and can be payloaded */
2017   if (!pa_format_info_is_pcm (format)) {
2018     gboolean framed = FALSE, parsed = FALSE;
2019     st = gst_caps_get_structure (caps, 0);
2020
2021     gst_structure_get_boolean (st, "framed", &framed);
2022     gst_structure_get_boolean (st, "parsed", &parsed);
2023     if ((!framed && !parsed) || gst_audio_iec61937_frame_size (&spec) <= 0)
2024       goto out;
2025   }
2026
2027   /* initialize the channel map */
2028   if (pa_format_info_is_pcm (format) &&
2029       gst_pulse_gst_to_channel_map (&channel_map, &spec))
2030     pa_format_info_set_channel_map (format, &channel_map);
2031
2032   if (pbuf->stream) {
2033     /* We're already in PAUSED or above, so just reuse this stream to query
2034      * sink formats and use those. */
2035     GList *i;
2036
2037     if (!(o = pa_context_get_sink_info_by_name (pbuf->context, psink->device,
2038                 gst_pulsesink_sink_info_cb, pbuf)))
2039       goto info_failed;
2040
2041     while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2042       pa_threaded_mainloop_wait (mainloop);
2043       if (gst_pulsering_is_dead (psink, pbuf, TRUE))
2044         goto out;
2045     }
2046
2047     g_mutex_lock (&psink->sink_formats_lock);
2048     for (i = g_list_first (psink->sink_formats); i; i = g_list_next (i)) {
2049       if (pa_format_info_is_compatible ((pa_format_info *) i->data, format)) {
2050         ret = TRUE;
2051         break;
2052       }
2053     }
2054     g_mutex_unlock (&psink->sink_formats_lock);
2055   } else {
2056     /* We're in READY, let's connect a stream to see if the format is
2057      * accpeted by whatever sink we're routed to */
2058     formats[0] = format;
2059
2060     if (!(stream = pa_stream_new_extended (pbuf->context, "pulsesink probe",
2061                 formats, 1, psink->proplist)))
2062       goto out;
2063
2064     /* construct the flags */
2065     flags = PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE |
2066         PA_STREAM_ADJUST_LATENCY | PA_STREAM_START_CORKED;
2067
2068     pa_stream_set_state_callback (stream, gst_pulsering_stream_state_cb, pbuf);
2069
2070     if (pa_stream_connect_playback (stream, psink->device, NULL, flags, NULL,
2071             NULL) < 0)
2072       goto out;
2073
2074     ret = gst_pulsering_wait_for_stream_ready (psink, stream);
2075   }
2076
2077 out:
2078   if (format)
2079     pa_format_info_free (format);
2080
2081   if (o)
2082     pa_operation_unref (o);
2083
2084   if (stream) {
2085     pa_stream_set_state_callback (stream, NULL, NULL);
2086     pa_stream_disconnect (stream);
2087     pa_stream_unref (stream);
2088   }
2089
2090   pa_threaded_mainloop_unlock (mainloop);
2091
2092   gst_caps_replace (&spec.caps, NULL);
2093   gst_object_unref (pbuf);
2094
2095 done:
2096
2097   return ret;
2098
2099 info_failed:
2100   {
2101     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2102         ("pa_context_get_sink_input_info() failed: %s",
2103             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2104     goto out;
2105   }
2106 }
2107
2108 static void
2109 gst_pulsesink_init (GstPulseSink * pulsesink)
2110 {
2111   pulsesink->server = NULL;
2112   pulsesink->device = NULL;
2113   pulsesink->device_description = NULL;
2114   pulsesink->client_name = gst_pulse_client_name ();
2115
2116   g_mutex_init (&pulsesink->sink_formats_lock);
2117   pulsesink->sink_formats = NULL;
2118
2119   pulsesink->volume = DEFAULT_VOLUME;
2120   pulsesink->volume_set = FALSE;
2121
2122   pulsesink->mute = DEFAULT_MUTE;
2123   pulsesink->mute_set = FALSE;
2124
2125   pulsesink->notify = 0;
2126
2127   g_atomic_int_set (&pulsesink->format_lost, FALSE);
2128   pulsesink->format_lost_time = GST_CLOCK_TIME_NONE;
2129
2130   pulsesink->properties = NULL;
2131   pulsesink->proplist = NULL;
2132
2133   /* override with a custom clock */
2134   if (GST_AUDIO_BASE_SINK (pulsesink)->provided_clock)
2135     gst_object_unref (GST_AUDIO_BASE_SINK (pulsesink)->provided_clock);
2136
2137   GST_AUDIO_BASE_SINK (pulsesink)->provided_clock =
2138       gst_audio_clock_new ("GstPulseSinkClock",
2139       (GstAudioClockGetTimeFunc) gst_pulsesink_get_time, pulsesink, NULL);
2140
2141   /* TRUE for sinks, FALSE for sources */
2142   pulsesink->probe = gst_pulseprobe_new (G_OBJECT (pulsesink),
2143       G_OBJECT_GET_CLASS (pulsesink), PROP_DEVICE, pulsesink->device,
2144       TRUE, FALSE);
2145 }
2146
2147 static void
2148 gst_pulsesink_finalize (GObject * object)
2149 {
2150   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
2151   GList *i;
2152
2153   g_free (pulsesink->server);
2154   g_free (pulsesink->device);
2155   g_free (pulsesink->device_description);
2156   g_free (pulsesink->client_name);
2157
2158   for (i = g_list_first (pulsesink->sink_formats); i; i = g_list_next (i))
2159     pa_format_info_free ((pa_format_info *) i->data);
2160
2161   g_list_free (pulsesink->sink_formats);
2162   g_mutex_clear (&pulsesink->sink_formats_lock);
2163
2164   if (pulsesink->properties)
2165     gst_structure_free (pulsesink->properties);
2166   if (pulsesink->proplist)
2167     pa_proplist_free (pulsesink->proplist);
2168
2169   if (pulsesink->probe) {
2170     gst_pulseprobe_free (pulsesink->probe);
2171     pulsesink->probe = NULL;
2172   }
2173
2174   G_OBJECT_CLASS (parent_class)->finalize (object);
2175 }
2176
2177 static void
2178 gst_pulsesink_set_volume (GstPulseSink * psink, gdouble volume)
2179 {
2180   pa_cvolume v;
2181   pa_operation *o = NULL;
2182   GstPulseRingBuffer *pbuf;
2183   uint32_t idx;
2184
2185   if (!mainloop)
2186     goto no_mainloop;
2187
2188   pa_threaded_mainloop_lock (mainloop);
2189
2190   GST_DEBUG_OBJECT (psink, "setting volume to %f", volume);
2191
2192   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2193   if (pbuf == NULL || pbuf->stream == NULL)
2194     goto no_buffer;
2195
2196   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2197     goto no_index;
2198
2199   if (pbuf->is_pcm)
2200     gst_pulse_cvolume_from_linear (&v, pbuf->channels, volume);
2201   else
2202     /* FIXME: this will eventually be superceded by checks to see if the volume
2203      * is readable/writable */
2204     goto unlock;
2205
2206   if (!(o = pa_context_set_sink_input_volume (pbuf->context, idx,
2207               &v, NULL, NULL)))
2208     goto volume_failed;
2209
2210   /* We don't really care about the result of this call */
2211 unlock:
2212
2213   if (o)
2214     pa_operation_unref (o);
2215
2216   pa_threaded_mainloop_unlock (mainloop);
2217
2218   return;
2219
2220   /* ERRORS */
2221 no_mainloop:
2222   {
2223     psink->volume = volume;
2224     psink->volume_set = TRUE;
2225
2226     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2227     return;
2228   }
2229 no_buffer:
2230   {
2231     psink->volume = volume;
2232     psink->volume_set = TRUE;
2233
2234     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2235     goto unlock;
2236   }
2237 no_index:
2238   {
2239     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2240     goto unlock;
2241   }
2242 volume_failed:
2243   {
2244     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2245         ("pa_stream_set_sink_input_volume() failed: %s",
2246             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2247     goto unlock;
2248   }
2249 }
2250
2251 static void
2252 gst_pulsesink_set_mute (GstPulseSink * psink, gboolean mute)
2253 {
2254   pa_operation *o = NULL;
2255   GstPulseRingBuffer *pbuf;
2256   uint32_t idx;
2257
2258   if (!mainloop)
2259     goto no_mainloop;
2260
2261   pa_threaded_mainloop_lock (mainloop);
2262
2263   GST_DEBUG_OBJECT (psink, "setting mute state to %d", mute);
2264
2265   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2266   if (pbuf == NULL || pbuf->stream == NULL)
2267     goto no_buffer;
2268
2269   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2270     goto no_index;
2271
2272   if (!(o = pa_context_set_sink_input_mute (pbuf->context, idx,
2273               mute, NULL, NULL)))
2274     goto mute_failed;
2275
2276   /* We don't really care about the result of this call */
2277 unlock:
2278
2279   if (o)
2280     pa_operation_unref (o);
2281
2282   pa_threaded_mainloop_unlock (mainloop);
2283
2284   return;
2285
2286   /* ERRORS */
2287 no_mainloop:
2288   {
2289     psink->mute = mute;
2290     psink->mute_set = TRUE;
2291
2292     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2293     return;
2294   }
2295 no_buffer:
2296   {
2297     psink->mute = mute;
2298     psink->mute_set = TRUE;
2299
2300     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2301     goto unlock;
2302   }
2303 no_index:
2304   {
2305     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2306     goto unlock;
2307   }
2308 mute_failed:
2309   {
2310     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2311         ("pa_stream_set_sink_input_mute() failed: %s",
2312             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2313     goto unlock;
2314   }
2315 }
2316
2317 static void
2318 gst_pulsesink_sink_input_info_cb (pa_context * c, const pa_sink_input_info * i,
2319     int eol, void *userdata)
2320 {
2321   GstPulseRingBuffer *pbuf;
2322   GstPulseSink *psink;
2323
2324   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
2325   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
2326
2327   if (!i)
2328     goto done;
2329
2330   if (!pbuf->stream)
2331     goto done;
2332
2333   /* If the index doesn't match our current stream,
2334    * it implies we just recreated the stream (caps change)
2335    */
2336   if (i->index == pa_stream_get_index (pbuf->stream)) {
2337     psink->volume = pa_sw_volume_to_linear (pa_cvolume_max (&i->volume));
2338     psink->mute = i->mute;
2339   }
2340
2341 done:
2342   pa_threaded_mainloop_signal (mainloop, 0);
2343 }
2344
2345 static gdouble
2346 gst_pulsesink_get_volume (GstPulseSink * psink)
2347 {
2348   GstPulseRingBuffer *pbuf;
2349   pa_operation *o = NULL;
2350   gdouble v = DEFAULT_VOLUME;
2351   uint32_t idx;
2352
2353   if (!mainloop)
2354     goto no_mainloop;
2355
2356   pa_threaded_mainloop_lock (mainloop);
2357
2358   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2359   if (pbuf == NULL || pbuf->stream == NULL)
2360     goto no_buffer;
2361
2362   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2363     goto no_index;
2364
2365   if (!(o = pa_context_get_sink_input_info (pbuf->context, idx,
2366               gst_pulsesink_sink_input_info_cb, pbuf)))
2367     goto info_failed;
2368
2369   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2370     pa_threaded_mainloop_wait (mainloop);
2371     if (gst_pulsering_is_dead (psink, pbuf, TRUE))
2372       goto unlock;
2373   }
2374
2375 unlock:
2376   v = psink->volume;
2377
2378   if (o)
2379     pa_operation_unref (o);
2380
2381   pa_threaded_mainloop_unlock (mainloop);
2382
2383   if (v > MAX_VOLUME) {
2384     GST_WARNING_OBJECT (psink, "Clipped volume from %f to %f", v, MAX_VOLUME);
2385     v = MAX_VOLUME;
2386   }
2387
2388   return v;
2389
2390   /* ERRORS */
2391 no_mainloop:
2392   {
2393     v = psink->volume;
2394     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2395     return v;
2396   }
2397 no_buffer:
2398   {
2399     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2400     goto unlock;
2401   }
2402 no_index:
2403   {
2404     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2405     goto unlock;
2406   }
2407 info_failed:
2408   {
2409     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2410         ("pa_context_get_sink_input_info() failed: %s",
2411             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2412     goto unlock;
2413   }
2414 }
2415
2416 static gboolean
2417 gst_pulsesink_get_mute (GstPulseSink * psink)
2418 {
2419   GstPulseRingBuffer *pbuf;
2420   pa_operation *o = NULL;
2421   uint32_t idx;
2422   gboolean mute = FALSE;
2423
2424   if (!mainloop)
2425     goto no_mainloop;
2426
2427   pa_threaded_mainloop_lock (mainloop);
2428   mute = psink->mute;
2429
2430   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2431   if (pbuf == NULL || pbuf->stream == NULL)
2432     goto no_buffer;
2433
2434   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2435     goto no_index;
2436
2437   if (!(o = pa_context_get_sink_input_info (pbuf->context, idx,
2438               gst_pulsesink_sink_input_info_cb, pbuf)))
2439     goto info_failed;
2440
2441   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2442     pa_threaded_mainloop_wait (mainloop);
2443     if (gst_pulsering_is_dead (psink, pbuf, TRUE))
2444       goto unlock;
2445   }
2446
2447 unlock:
2448   if (o)
2449     pa_operation_unref (o);
2450
2451   pa_threaded_mainloop_unlock (mainloop);
2452
2453   return mute;
2454
2455   /* ERRORS */
2456 no_mainloop:
2457   {
2458     mute = psink->mute;
2459     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2460     return mute;
2461   }
2462 no_buffer:
2463   {
2464     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2465     goto unlock;
2466   }
2467 no_index:
2468   {
2469     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2470     goto unlock;
2471   }
2472 info_failed:
2473   {
2474     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2475         ("pa_context_get_sink_input_info() failed: %s",
2476             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2477     goto unlock;
2478   }
2479 }
2480
2481 static gchar *
2482 gst_pulsesink_device_description (GstPulseSink * psink)
2483 {
2484   GstPulseRingBuffer *pbuf;
2485   pa_operation *o = NULL;
2486   gchar *t;
2487
2488   if (!mainloop)
2489     goto no_mainloop;
2490
2491   pa_threaded_mainloop_lock (mainloop);
2492   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2493   if (pbuf == NULL)
2494     goto no_buffer;
2495
2496   if (!(o = pa_context_get_sink_info_by_name (pbuf->context,
2497               psink->device, gst_pulsesink_sink_info_cb, pbuf)))
2498     goto info_failed;
2499
2500   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2501     pa_threaded_mainloop_wait (mainloop);
2502     if (gst_pulsering_is_dead (psink, pbuf, FALSE))
2503       goto unlock;
2504   }
2505
2506 unlock:
2507   if (o)
2508     pa_operation_unref (o);
2509
2510   t = g_strdup (psink->device_description);
2511   pa_threaded_mainloop_unlock (mainloop);
2512
2513   return t;
2514
2515   /* ERRORS */
2516 no_mainloop:
2517   {
2518     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2519     return NULL;
2520   }
2521 no_buffer:
2522   {
2523     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2524     goto unlock;
2525   }
2526 info_failed:
2527   {
2528     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2529         ("pa_context_get_sink_info_by_index() failed: %s",
2530             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2531     goto unlock;
2532   }
2533 }
2534
2535 static void
2536 gst_pulsesink_set_property (GObject * object,
2537     guint prop_id, const GValue * value, GParamSpec * pspec)
2538 {
2539   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
2540
2541   switch (prop_id) {
2542     case PROP_SERVER:
2543       g_free (pulsesink->server);
2544       pulsesink->server = g_value_dup_string (value);
2545       if (pulsesink->probe)
2546         gst_pulseprobe_set_server (pulsesink->probe, pulsesink->server);
2547       break;
2548     case PROP_DEVICE:
2549       g_free (pulsesink->device);
2550       pulsesink->device = g_value_dup_string (value);
2551       break;
2552     case PROP_VOLUME:
2553       gst_pulsesink_set_volume (pulsesink, g_value_get_double (value));
2554       break;
2555     case PROP_MUTE:
2556       gst_pulsesink_set_mute (pulsesink, g_value_get_boolean (value));
2557       break;
2558     case PROP_CLIENT_NAME:
2559       g_free (pulsesink->client_name);
2560       if (!g_value_get_string (value)) {
2561         GST_WARNING_OBJECT (pulsesink,
2562             "Empty PulseAudio client name not allowed. Resetting to default value");
2563         pulsesink->client_name = gst_pulse_client_name ();
2564       } else
2565         pulsesink->client_name = g_value_dup_string (value);
2566       break;
2567     case PROP_STREAM_PROPERTIES:
2568       if (pulsesink->properties)
2569         gst_structure_free (pulsesink->properties);
2570       pulsesink->properties =
2571           gst_structure_copy (gst_value_get_structure (value));
2572       if (pulsesink->proplist)
2573         pa_proplist_free (pulsesink->proplist);
2574       pulsesink->proplist = gst_pulse_make_proplist (pulsesink->properties);
2575       break;
2576     default:
2577       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2578       break;
2579   }
2580 }
2581
2582 static void
2583 gst_pulsesink_get_property (GObject * object,
2584     guint prop_id, GValue * value, GParamSpec * pspec)
2585 {
2586
2587   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
2588
2589   switch (prop_id) {
2590     case PROP_SERVER:
2591       g_value_set_string (value, pulsesink->server);
2592       break;
2593     case PROP_DEVICE:
2594       g_value_set_string (value, pulsesink->device);
2595       break;
2596     case PROP_DEVICE_NAME:
2597       g_value_take_string (value, gst_pulsesink_device_description (pulsesink));
2598       break;
2599     case PROP_VOLUME:
2600       g_value_set_double (value, gst_pulsesink_get_volume (pulsesink));
2601       break;
2602     case PROP_MUTE:
2603       g_value_set_boolean (value, gst_pulsesink_get_mute (pulsesink));
2604       break;
2605     case PROP_CLIENT_NAME:
2606       g_value_set_string (value, pulsesink->client_name);
2607       break;
2608     case PROP_STREAM_PROPERTIES:
2609       gst_value_set_structure (value, pulsesink->properties);
2610       break;
2611     default:
2612       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2613       break;
2614   }
2615 }
2616
2617 static void
2618 gst_pulsesink_change_title (GstPulseSink * psink, const gchar * t)
2619 {
2620   pa_operation *o = NULL;
2621   GstPulseRingBuffer *pbuf;
2622
2623   pa_threaded_mainloop_lock (mainloop);
2624
2625   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2626
2627   if (pbuf == NULL || pbuf->stream == NULL)
2628     goto no_buffer;
2629
2630   g_free (pbuf->stream_name);
2631   pbuf->stream_name = g_strdup (t);
2632
2633   if (!(o = pa_stream_set_name (pbuf->stream, pbuf->stream_name, NULL, NULL)))
2634     goto name_failed;
2635
2636   /* We're not interested if this operation failed or not */
2637 unlock:
2638
2639   if (o)
2640     pa_operation_unref (o);
2641   pa_threaded_mainloop_unlock (mainloop);
2642
2643   return;
2644
2645   /* ERRORS */
2646 no_buffer:
2647   {
2648     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2649     goto unlock;
2650   }
2651 name_failed:
2652   {
2653     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2654         ("pa_stream_set_name() failed: %s",
2655             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2656     goto unlock;
2657   }
2658 }
2659
2660 static void
2661 gst_pulsesink_change_props (GstPulseSink * psink, GstTagList * l)
2662 {
2663   static const gchar *const map[] = {
2664     GST_TAG_TITLE, PA_PROP_MEDIA_TITLE,
2665
2666     /* might get overriden in the next iteration by GST_TAG_ARTIST */
2667     GST_TAG_PERFORMER, PA_PROP_MEDIA_ARTIST,
2668
2669     GST_TAG_ARTIST, PA_PROP_MEDIA_ARTIST,
2670     GST_TAG_LANGUAGE_CODE, PA_PROP_MEDIA_LANGUAGE,
2671     GST_TAG_LOCATION, PA_PROP_MEDIA_FILENAME,
2672     /* We might add more here later on ... */
2673     NULL
2674   };
2675   pa_proplist *pl = NULL;
2676   const gchar *const *t;
2677   gboolean empty = TRUE;
2678   pa_operation *o = NULL;
2679   GstPulseRingBuffer *pbuf;
2680
2681   pl = pa_proplist_new ();
2682
2683   for (t = map; *t; t += 2) {
2684     gchar *n = NULL;
2685
2686     if (gst_tag_list_get_string (l, *t, &n)) {
2687
2688       if (n && *n) {
2689         pa_proplist_sets (pl, *(t + 1), n);
2690         empty = FALSE;
2691       }
2692
2693       g_free (n);
2694     }
2695   }
2696   if (empty)
2697     goto finish;
2698
2699   pa_threaded_mainloop_lock (mainloop);
2700   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2701   if (pbuf == NULL || pbuf->stream == NULL)
2702     goto no_buffer;
2703
2704   if (!(o = pa_stream_proplist_update (pbuf->stream, PA_UPDATE_REPLACE,
2705               pl, NULL, NULL)))
2706     goto update_failed;
2707
2708   /* We're not interested if this operation failed or not */
2709 unlock:
2710
2711   if (o)
2712     pa_operation_unref (o);
2713
2714   pa_threaded_mainloop_unlock (mainloop);
2715
2716 finish:
2717
2718   if (pl)
2719     pa_proplist_free (pl);
2720
2721   return;
2722
2723   /* ERRORS */
2724 no_buffer:
2725   {
2726     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2727     goto unlock;
2728   }
2729 update_failed:
2730   {
2731     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2732         ("pa_stream_proplist_update() failed: %s",
2733             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2734     goto unlock;
2735   }
2736 }
2737
2738 static void
2739 gst_pulsesink_flush_ringbuffer (GstPulseSink * psink)
2740 {
2741   GstPulseRingBuffer *pbuf;
2742
2743   pa_threaded_mainloop_lock (mainloop);
2744
2745   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2746
2747   if (pbuf == NULL || pbuf->stream == NULL)
2748     goto no_buffer;
2749
2750   gst_pulsering_flush (pbuf);
2751
2752   /* Uncork if we haven't already (happens when waiting to get enough data
2753    * to send out the first time) */
2754   if (pbuf->corked)
2755     gst_pulsering_set_corked (pbuf, FALSE, FALSE);
2756
2757   /* We're not interested if this operation failed or not */
2758 unlock:
2759   pa_threaded_mainloop_unlock (mainloop);
2760
2761   return;
2762
2763   /* ERRORS */
2764 no_buffer:
2765   {
2766     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2767     goto unlock;
2768   }
2769 }
2770
2771 static gboolean
2772 gst_pulsesink_event (GstBaseSink * sink, GstEvent * event)
2773 {
2774   GstPulseSink *pulsesink = GST_PULSESINK_CAST (sink);
2775
2776   switch (GST_EVENT_TYPE (event)) {
2777     case GST_EVENT_TAG:{
2778       gchar *title = NULL, *artist = NULL, *location = NULL, *description =
2779           NULL, *t = NULL, *buf = NULL;
2780       GstTagList *l;
2781
2782       gst_event_parse_tag (event, &l);
2783
2784       gst_tag_list_get_string (l, GST_TAG_TITLE, &title);
2785       gst_tag_list_get_string (l, GST_TAG_ARTIST, &artist);
2786       gst_tag_list_get_string (l, GST_TAG_LOCATION, &location);
2787       gst_tag_list_get_string (l, GST_TAG_DESCRIPTION, &description);
2788
2789       if (!artist)
2790         gst_tag_list_get_string (l, GST_TAG_PERFORMER, &artist);
2791
2792       if (title && artist)
2793         /* TRANSLATORS: 'song title' by 'artist name' */
2794         t = buf = g_strdup_printf (_("'%s' by '%s'"), g_strstrip (title),
2795             g_strstrip (artist));
2796       else if (title)
2797         t = g_strstrip (title);
2798       else if (description)
2799         t = g_strstrip (description);
2800       else if (location)
2801         t = g_strstrip (location);
2802
2803       if (t)
2804         gst_pulsesink_change_title (pulsesink, t);
2805
2806       g_free (title);
2807       g_free (artist);
2808       g_free (location);
2809       g_free (description);
2810       g_free (buf);
2811
2812       gst_pulsesink_change_props (pulsesink, l);
2813
2814       break;
2815     }
2816     case GST_EVENT_GAP:{
2817       GstClockTime timestamp, duration;
2818
2819       gst_event_parse_gap (event, &timestamp, &duration);
2820       if (duration == GST_CLOCK_TIME_NONE)
2821         gst_pulsesink_flush_ringbuffer (pulsesink);
2822       break;
2823     }
2824     case GST_EVENT_EOS:
2825       gst_pulsesink_flush_ringbuffer (pulsesink);
2826       break;
2827     default:
2828       ;
2829   }
2830
2831   return GST_BASE_SINK_CLASS (parent_class)->event (sink, event);
2832 }
2833
2834 static gboolean
2835 gst_pulsesink_query (GstBaseSink * sink, GstQuery * query)
2836 {
2837   GstPulseSink *pulsesink = GST_PULSESINK_CAST (sink);
2838   gboolean ret;
2839
2840   switch (GST_QUERY_TYPE (query)) {
2841     case GST_QUERY_ACCEPT_CAPS:
2842     {
2843       GstCaps *caps;
2844
2845       gst_query_parse_accept_caps (query, &caps);
2846       ret = gst_pulsesink_query_acceptcaps (pulsesink, caps);
2847       gst_query_set_accept_caps_result (query, ret);
2848       ret = TRUE;
2849       break;
2850     }
2851     default:
2852       ret = GST_BASE_SINK_CLASS (parent_class)->query (sink, query);
2853       break;
2854   }
2855   return ret;
2856 }
2857
2858 static void
2859 gst_pulsesink_release_mainloop (GstPulseSink * psink)
2860 {
2861   if (!mainloop)
2862     return;
2863
2864   pa_threaded_mainloop_lock (mainloop);
2865   while (psink->defer_pending) {
2866     GST_DEBUG_OBJECT (psink, "waiting for stream status message emission");
2867     pa_threaded_mainloop_wait (mainloop);
2868   }
2869   pa_threaded_mainloop_unlock (mainloop);
2870
2871   g_mutex_lock (&pa_shared_resource_mutex);
2872   mainloop_ref_ct--;
2873   if (!mainloop_ref_ct) {
2874     GST_INFO_OBJECT (psink, "terminating pa main loop thread");
2875     pa_threaded_mainloop_stop (mainloop);
2876     pa_threaded_mainloop_free (mainloop);
2877     mainloop = NULL;
2878   }
2879   g_mutex_unlock (&pa_shared_resource_mutex);
2880 }
2881
2882 static GstStateChangeReturn
2883 gst_pulsesink_change_state (GstElement * element, GstStateChange transition)
2884 {
2885   GstPulseSink *pulsesink = GST_PULSESINK (element);
2886   GstStateChangeReturn ret;
2887
2888   switch (transition) {
2889     case GST_STATE_CHANGE_NULL_TO_READY:
2890       g_mutex_lock (&pa_shared_resource_mutex);
2891       if (!mainloop_ref_ct) {
2892         GST_INFO_OBJECT (element, "new pa main loop thread");
2893         if (!(mainloop = pa_threaded_mainloop_new ()))
2894           goto mainloop_failed;
2895         if (pa_threaded_mainloop_start (mainloop) < 0) {
2896           pa_threaded_mainloop_free (mainloop);
2897           goto mainloop_start_failed;
2898         }
2899         mainloop_ref_ct = 1;
2900         g_mutex_unlock (&pa_shared_resource_mutex);
2901       } else {
2902         GST_INFO_OBJECT (element, "reusing pa main loop thread");
2903         mainloop_ref_ct++;
2904         g_mutex_unlock (&pa_shared_resource_mutex);
2905       }
2906       break;
2907     case GST_STATE_CHANGE_READY_TO_PAUSED:
2908       gst_element_post_message (element,
2909           gst_message_new_clock_provide (GST_OBJECT_CAST (element),
2910               GST_AUDIO_BASE_SINK (pulsesink)->provided_clock, TRUE));
2911       break;
2912
2913     default:
2914       break;
2915   }
2916
2917   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2918   if (ret == GST_STATE_CHANGE_FAILURE)
2919     goto state_failure;
2920
2921   switch (transition) {
2922     case GST_STATE_CHANGE_PAUSED_TO_READY:
2923       /* format_lost is reset in release() in audiobasesink */
2924       gst_element_post_message (element,
2925           gst_message_new_clock_lost (GST_OBJECT_CAST (element),
2926               GST_AUDIO_BASE_SINK (pulsesink)->provided_clock));
2927       break;
2928     case GST_STATE_CHANGE_READY_TO_NULL:
2929       gst_pulsesink_release_mainloop (pulsesink);
2930       break;
2931     default:
2932       break;
2933   }
2934
2935   return ret;
2936
2937   /* ERRORS */
2938 mainloop_failed:
2939   {
2940     g_mutex_unlock (&pa_shared_resource_mutex);
2941     GST_ELEMENT_ERROR (pulsesink, RESOURCE, FAILED,
2942         ("pa_threaded_mainloop_new() failed"), (NULL));
2943     return GST_STATE_CHANGE_FAILURE;
2944   }
2945 mainloop_start_failed:
2946   {
2947     g_mutex_unlock (&pa_shared_resource_mutex);
2948     GST_ELEMENT_ERROR (pulsesink, RESOURCE, FAILED,
2949         ("pa_threaded_mainloop_start() failed"), (NULL));
2950     return GST_STATE_CHANGE_FAILURE;
2951   }
2952 state_failure:
2953   {
2954     if (transition == GST_STATE_CHANGE_NULL_TO_READY) {
2955       /* Clear the PA mainloop if audiobasesink failed to open the ring_buffer */
2956       g_assert (mainloop);
2957       gst_pulsesink_release_mainloop (pulsesink);
2958     }
2959     return ret;
2960   }
2961 }