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