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