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