Merge branch 'upstream/1.16' into tizen_gst_1.16.2
[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 #ifndef __TIZEN__
919   pa_cvolume v;
920 #endif
921   pa_cvolume *pv = NULL;
922   pa_stream_flags_t flags;
923   const gchar *name;
924   GstAudioClock *clock;
925   pa_format_info *formats[1];
926 #ifndef GST_DISABLE_GST_DEBUG
927   gchar print_buf[PA_FORMAT_INFO_SNPRINT_MAX];
928 #endif
929
930   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (buf));
931   pbuf = GST_PULSERING_BUFFER_CAST (buf);
932
933   GST_LOG_OBJECT (psink, "creating sample spec");
934   /* convert the gstreamer sample spec to the pulseaudio format */
935   if (!gst_pulse_fill_format_info (spec, &pbuf->format, &pbuf->channels))
936     goto invalid_spec;
937   pbuf->is_pcm = pa_format_info_is_pcm (pbuf->format);
938
939   pa_threaded_mainloop_lock (mainloop);
940
941   /* we need a context and a no stream */
942   g_assert (pbuf->context);
943   g_assert (!pbuf->stream);
944
945   /* if we have a probe, disconnect it first so that if we're creating a
946    * compressed stream, it doesn't get blocked by a PCM stream */
947   if (pbuf->probe_stream) {
948     gst_pulse_destroy_stream (pbuf->probe_stream, TRUE);
949     pbuf->probe_stream = NULL;
950   }
951
952   /* enable event notifications */
953   GST_LOG_OBJECT (psink, "subscribing to context events");
954   if (!(o = pa_context_subscribe (pbuf->context,
955               PA_SUBSCRIPTION_MASK_SINK_INPUT, NULL, NULL)))
956     goto subscribe_failed;
957
958   pa_operation_unref (o);
959
960   /* initialize the channel map */
961   if (pbuf->is_pcm && gst_pulse_gst_to_channel_map (&channel_map, spec))
962     pa_format_info_set_channel_map (pbuf->format, &channel_map);
963
964   /* find a good name for the stream */
965   if (psink->stream_name)
966     name = psink->stream_name;
967   else
968     name = "Playback Stream";
969
970 #if defined(__TIZEN__) && defined(PCM_DUMP_ENABLE)
971   if (psink->need_dump_input == TRUE && psink->dump_fd_input == NULL) {
972     char *suffix , *dump_path;
973     GDateTime *time = g_date_time_new_now_local();
974
975     suffix = g_date_time_format(time, "%m%d_%H%M%S");
976     dump_path = g_strdup_printf("%s%dch_%dhz_%s.pcm", GST_PULSESINK_DUMP_INPUT_PATH_PREFIX, pbuf->channels, spec->info.rate, suffix);
977     GST_WARNING_OBJECT(psink, "pulse-sink dumping enabled: dump path [%s]", dump_path);
978     psink->dump_fd_input = fopen(dump_path, "w+");
979
980     g_free(suffix);
981     g_free(dump_path);
982     g_date_time_unref(time);
983   }
984 #endif /* __TIZEN__ && PCM_DUMP_ENABLE */
985
986   /* create a stream */
987   formats[0] = pbuf->format;
988   if (!(pbuf->stream = pa_stream_new_extended (pbuf->context, name, formats, 1,
989               psink->proplist)))
990     goto stream_failed;
991
992   /* install essential callbacks */
993   pa_stream_set_state_callback (pbuf->stream,
994       gst_pulsering_stream_state_cb, pbuf);
995   pa_stream_set_write_callback (pbuf->stream,
996       gst_pulsering_stream_request_cb, pbuf);
997   pa_stream_set_underflow_callback (pbuf->stream,
998       gst_pulsering_stream_underflow_cb, pbuf);
999   pa_stream_set_overflow_callback (pbuf->stream,
1000       gst_pulsering_stream_overflow_cb, pbuf);
1001   pa_stream_set_latency_update_callback (pbuf->stream,
1002       gst_pulsering_stream_latency_cb, pbuf);
1003   pa_stream_set_suspended_callback (pbuf->stream,
1004       gst_pulsering_stream_suspended_cb, pbuf);
1005   pa_stream_set_started_callback (pbuf->stream,
1006       gst_pulsering_stream_started_cb, pbuf);
1007   pa_stream_set_event_callback (pbuf->stream,
1008       gst_pulsering_stream_event_cb, pbuf);
1009
1010   /* buffering requirements. When setting prebuf to 0, the stream will not pause
1011    * when we cause an underrun, which causes time to continue. */
1012   memset (&wanted, 0, sizeof (wanted));
1013   wanted.tlength = spec->segtotal * spec->segsize;
1014   wanted.maxlength = -1;
1015   wanted.prebuf = 0;
1016   wanted.minreq = spec->segsize;
1017
1018   GST_INFO_OBJECT (psink, "tlength:   %d", wanted.tlength);
1019   GST_INFO_OBJECT (psink, "maxlength: %d", wanted.maxlength);
1020   GST_INFO_OBJECT (psink, "prebuf:    %d", wanted.prebuf);
1021   GST_INFO_OBJECT (psink, "minreq:    %d", wanted.minreq);
1022
1023 #ifndef __TIZEN__
1024   /* configure volume when we changed it, else we leave the default */
1025   if (psink->volume_set) {
1026     GST_LOG_OBJECT (psink, "have volume of %f", psink->volume);
1027     pv = &v;
1028     if (pbuf->is_pcm)
1029       gst_pulse_cvolume_from_linear (pv, pbuf->channels, psink->volume);
1030     else {
1031       GST_DEBUG_OBJECT (psink, "passthrough stream, not setting volume");
1032       pv = NULL;
1033     }
1034   } else {
1035     pv = NULL;
1036   }
1037 #endif
1038
1039   /* construct the flags */
1040   flags = PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE |
1041       PA_STREAM_ADJUST_LATENCY | PA_STREAM_START_CORKED;
1042
1043 #ifndef __TIZEN__
1044   if (psink->mute_set) {
1045     if (psink->mute)
1046       flags |= PA_STREAM_START_MUTED;
1047     else
1048       flags |= PA_STREAM_START_UNMUTED;
1049   }
1050 #endif
1051
1052   /* we always start corked (see flags above) */
1053   pbuf->corked = TRUE;
1054
1055   /* try to connect now */
1056   GST_LOG_OBJECT (psink, "connect for playback to device %s",
1057       GST_STR_NULL (psink->device));
1058   if (pa_stream_connect_playback (pbuf->stream, psink->device,
1059           &wanted, flags, pv, NULL) < 0)
1060     goto connect_failed;
1061
1062   /* our clock will now start from 0 again */
1063   clock = GST_AUDIO_CLOCK (GST_AUDIO_BASE_SINK (psink)->provided_clock);
1064   gst_audio_clock_reset (clock, 0);
1065
1066   if (!gst_pulsering_wait_for_stream_ready (psink, pbuf->stream))
1067     goto connect_failed;
1068
1069   g_free (psink->device);
1070   psink->device = g_strdup (pa_stream_get_device_name (pbuf->stream));
1071
1072 #ifndef GST_DISABLE_GST_DEBUG
1073   pa_format_info_snprint (print_buf, sizeof (print_buf),
1074       pa_stream_get_format_info (pbuf->stream));
1075   GST_INFO_OBJECT (psink, "negotiated to: %s", print_buf);
1076 #endif
1077
1078 #ifdef __TIZEN__
1079   {
1080     uint32_t idx;
1081     if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
1082       goto no_index;
1083     if (psink->volume_set)
1084       gst_pulse_set_volume_ratio (idx, "out", psink->volume);
1085     if (psink->mute_set)
1086       if (psink->mute)
1087         gst_pulse_set_volume_ratio (idx, "out", 0);
1088   }
1089 #endif
1090   /* After we passed the volume off of to PA we never want to set it
1091      again, since it is PA's job to save/restore volumes.  */
1092   psink->volume_set = psink->mute_set = FALSE;
1093
1094   GST_LOG_OBJECT (psink, "stream is acquired now");
1095
1096   /* get the actual buffering properties now */
1097   actual = pa_stream_get_buffer_attr (pbuf->stream);
1098
1099   GST_INFO_OBJECT (psink, "tlength:   %d (wanted: %d)", actual->tlength,
1100       wanted.tlength);
1101   GST_INFO_OBJECT (psink, "maxlength: %d", actual->maxlength);
1102   GST_INFO_OBJECT (psink, "prebuf:    %d", actual->prebuf);
1103   GST_INFO_OBJECT (psink, "minreq:    %d (wanted %d)", actual->minreq,
1104       wanted.minreq);
1105
1106   spec->segsize = actual->minreq;
1107   spec->segtotal = actual->tlength / spec->segsize;
1108
1109   pa_threaded_mainloop_unlock (mainloop);
1110
1111   return TRUE;
1112
1113   /* ERRORS */
1114 unlock_and_fail:
1115   {
1116     gst_pulsering_destroy_stream (pbuf);
1117     pa_threaded_mainloop_unlock (mainloop);
1118
1119     return FALSE;
1120   }
1121 invalid_spec:
1122   {
1123     GST_ELEMENT_ERROR (psink, RESOURCE, SETTINGS,
1124         ("Invalid sample specification."), (NULL));
1125     return FALSE;
1126   }
1127 subscribe_failed:
1128   {
1129     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1130         ("pa_context_subscribe() failed: %s",
1131             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1132     goto unlock_and_fail;
1133   }
1134 stream_failed:
1135   {
1136     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1137         ("Failed to create stream: %s",
1138             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1139     goto unlock_and_fail;
1140   }
1141 connect_failed:
1142   {
1143     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1144         ("Failed to connect stream: %s",
1145             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1146     goto unlock_and_fail;
1147   }
1148 #ifdef __TIZEN__
1149 no_index:
1150   {
1151     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1152         ("Failed to get stream index: %s",
1153             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1154     goto unlock_and_fail;
1155   }
1156 #endif
1157 }
1158
1159 /* free the stream that we acquired before */
1160 static gboolean
1161 gst_pulseringbuffer_release (GstAudioRingBuffer * buf)
1162 {
1163   GstPulseRingBuffer *pbuf;
1164
1165   pbuf = GST_PULSERING_BUFFER_CAST (buf);
1166
1167   pa_threaded_mainloop_lock (mainloop);
1168   gst_pulsering_destroy_stream (pbuf);
1169   pa_threaded_mainloop_unlock (mainloop);
1170
1171   {
1172     GstPulseSink *psink;
1173
1174     psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1175     g_atomic_int_set (&psink->format_lost, FALSE);
1176     psink->format_lost_time = GST_CLOCK_TIME_NONE;
1177   }
1178
1179   return TRUE;
1180 }
1181
1182 static void
1183 gst_pulsering_success_cb (pa_stream * s, int success, void *userdata)
1184 {
1185   pa_threaded_mainloop_signal (mainloop, 0);
1186 }
1187
1188 /* update the corked state of a stream, must be called with the mainloop
1189  * lock */
1190 static gboolean
1191 gst_pulsering_set_corked (GstPulseRingBuffer * pbuf, gboolean corked,
1192     gboolean wait)
1193 {
1194   pa_operation *o = NULL;
1195   GstPulseSink *psink;
1196   gboolean res = FALSE;
1197
1198   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1199
1200   if (g_atomic_int_get (&psink->format_lost)) {
1201     /* Sink format changed, stream's gone so fake being paused */
1202     return TRUE;
1203   }
1204
1205   GST_DEBUG_OBJECT (psink, "setting corked state to %d", corked);
1206   if (pbuf->corked != corked) {
1207     if (!(o = pa_stream_cork (pbuf->stream, corked,
1208                 gst_pulsering_success_cb, pbuf)))
1209       goto cork_failed;
1210
1211     while (wait && pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
1212       pa_threaded_mainloop_wait (mainloop);
1213       if (gst_pulsering_is_dead (psink, pbuf, TRUE))
1214         goto server_dead;
1215     }
1216     pbuf->corked = corked;
1217   } else {
1218     GST_DEBUG_OBJECT (psink, "skipping, already in requested state");
1219   }
1220   res = TRUE;
1221
1222 cleanup:
1223   if (o)
1224     pa_operation_unref (o);
1225
1226   return res;
1227
1228   /* ERRORS */
1229 server_dead:
1230   {
1231     GST_DEBUG_OBJECT (psink, "the server is dead");
1232     goto cleanup;
1233   }
1234 cork_failed:
1235   {
1236     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1237         ("pa_stream_cork() failed: %s",
1238             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1239     goto cleanup;
1240   }
1241 }
1242
1243 static void
1244 gst_pulseringbuffer_clear (GstAudioRingBuffer * buf)
1245 {
1246   GstPulseSink *psink;
1247   GstPulseRingBuffer *pbuf;
1248   pa_operation *o = NULL;
1249
1250   pbuf = GST_PULSERING_BUFFER_CAST (buf);
1251   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1252
1253   pa_threaded_mainloop_lock (mainloop);
1254   GST_DEBUG_OBJECT (psink, "clearing");
1255   if (pbuf->stream) {
1256     /* don't wait for the flush to complete */
1257     if ((o = pa_stream_flush (pbuf->stream, NULL, pbuf)))
1258       pa_operation_unref (o);
1259   }
1260   pa_threaded_mainloop_unlock (mainloop);
1261 }
1262
1263 #if 0
1264 /* called from pulse thread with the mainloop lock */
1265 static void
1266 mainloop_enter_defer_cb (pa_mainloop_api * api, void *userdata)
1267 {
1268   GstPulseSink *pulsesink = GST_PULSESINK (userdata);
1269   GstMessage *message;
1270   GValue val = { 0 };
1271
1272   GST_DEBUG_OBJECT (pulsesink, "posting ENTER stream status");
1273   message = gst_message_new_stream_status (GST_OBJECT (pulsesink),
1274       GST_STREAM_STATUS_TYPE_ENTER, GST_ELEMENT (pulsesink));
1275   g_value_init (&val, GST_TYPE_G_THREAD);
1276   g_value_set_boxed (&val, g_thread_self ());
1277   gst_message_set_stream_status_object (message, &val);
1278   g_value_unset (&val);
1279
1280   gst_element_post_message (GST_ELEMENT (pulsesink), message);
1281
1282   g_return_if_fail (pulsesink->defer_pending);
1283   pulsesink->defer_pending--;
1284   pa_threaded_mainloop_signal (mainloop, 0);
1285 }
1286 #endif
1287
1288 /* start/resume playback ASAP, we don't uncork here but in the commit method */
1289 static gboolean
1290 gst_pulseringbuffer_start (GstAudioRingBuffer * buf)
1291 {
1292   GstPulseSink *psink;
1293   GstPulseRingBuffer *pbuf;
1294
1295   pbuf = GST_PULSERING_BUFFER_CAST (buf);
1296   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1297
1298   pa_threaded_mainloop_lock (mainloop);
1299
1300   GST_DEBUG_OBJECT (psink, "starting");
1301   pbuf->paused = FALSE;
1302
1303   /* EOS needs running clock */
1304   if (GST_BASE_SINK_CAST (psink)->eos ||
1305       g_atomic_int_get (&GST_AUDIO_BASE_SINK (psink)->eos_rendering))
1306     gst_pulsering_set_corked (pbuf, FALSE, FALSE);
1307
1308 #if 0
1309   GST_DEBUG_OBJECT (psink, "scheduling stream status");
1310   psink->defer_pending++;
1311   pa_mainloop_api_once (pa_threaded_mainloop_get_api (mainloop),
1312       mainloop_enter_defer_cb, psink);
1313
1314   /* Wait for the stream status message to be posted. This needs to be done
1315    * synchronously because the callback will take the mainloop lock
1316    * (implicitly) and then take the GST_OBJECT_LOCK. Everywhere else, we take
1317    * the locks in the reverse order, so not doing this synchronously could
1318    * cause a deadlock. */
1319   GST_DEBUG_OBJECT (psink, "waiting for stream status (ENTER) to be posted");
1320   pa_threaded_mainloop_wait (mainloop);
1321 #endif
1322
1323   pa_threaded_mainloop_unlock (mainloop);
1324
1325   return TRUE;
1326 }
1327
1328 /* pause/stop playback ASAP */
1329 static gboolean
1330 gst_pulseringbuffer_pause (GstAudioRingBuffer * buf)
1331 {
1332   GstPulseSink *psink;
1333   GstPulseRingBuffer *pbuf;
1334   gboolean res;
1335
1336   pbuf = GST_PULSERING_BUFFER_CAST (buf);
1337   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1338
1339   pa_threaded_mainloop_lock (mainloop);
1340   GST_DEBUG_OBJECT (psink, "pausing and corking");
1341   /* make sure the commit method stops writing */
1342   pbuf->paused = TRUE;
1343   res = gst_pulsering_set_corked (pbuf, TRUE, TRUE);
1344   if (pbuf->in_commit) {
1345     /* we are waiting in a commit, signal */
1346     GST_DEBUG_OBJECT (psink, "signal commit");
1347     pa_threaded_mainloop_signal (mainloop, 0);
1348   }
1349   pa_threaded_mainloop_unlock (mainloop);
1350
1351   return res;
1352 }
1353
1354 #if 0
1355 /* called from pulse thread with the mainloop lock */
1356 static void
1357 mainloop_leave_defer_cb (pa_mainloop_api * api, void *userdata)
1358 {
1359   GstPulseSink *pulsesink = GST_PULSESINK (userdata);
1360   GstMessage *message;
1361   GValue val = { 0 };
1362
1363   GST_DEBUG_OBJECT (pulsesink, "posting LEAVE stream status");
1364   message = gst_message_new_stream_status (GST_OBJECT (pulsesink),
1365       GST_STREAM_STATUS_TYPE_LEAVE, GST_ELEMENT (pulsesink));
1366   g_value_init (&val, GST_TYPE_G_THREAD);
1367   g_value_set_boxed (&val, g_thread_self ());
1368   gst_message_set_stream_status_object (message, &val);
1369   g_value_unset (&val);
1370
1371   gst_element_post_message (GST_ELEMENT (pulsesink), message);
1372
1373   g_return_if_fail (pulsesink->defer_pending);
1374   pulsesink->defer_pending--;
1375   pa_threaded_mainloop_signal (mainloop, 0);
1376 }
1377 #endif
1378
1379 /* stop playback, we flush everything. */
1380 static gboolean
1381 gst_pulseringbuffer_stop (GstAudioRingBuffer * buf)
1382 {
1383   GstPulseSink *psink;
1384   GstPulseRingBuffer *pbuf;
1385   gboolean res = FALSE;
1386   pa_operation *o = NULL;
1387
1388   pbuf = GST_PULSERING_BUFFER_CAST (buf);
1389   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1390
1391   pa_threaded_mainloop_lock (mainloop);
1392
1393   pbuf->paused = TRUE;
1394   res = gst_pulsering_set_corked (pbuf, TRUE, TRUE);
1395
1396   /* Inform anyone waiting in _commit() call that it shall wakeup */
1397   if (pbuf->in_commit) {
1398     GST_DEBUG_OBJECT (psink, "signal commit thread");
1399     pa_threaded_mainloop_signal (mainloop, 0);
1400   }
1401   if (g_atomic_int_get (&psink->format_lost)) {
1402     /* Don't try to flush, the stream's probably gone by now */
1403     res = TRUE;
1404     goto cleanup;
1405   }
1406
1407   /* then try to flush, it's not fatal when this fails */
1408   GST_DEBUG_OBJECT (psink, "flushing");
1409   if ((o = pa_stream_flush (pbuf->stream, gst_pulsering_success_cb, pbuf))) {
1410     while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
1411       GST_DEBUG_OBJECT (psink, "wait for completion");
1412       pa_threaded_mainloop_wait (mainloop);
1413       if (gst_pulsering_is_dead (psink, pbuf, TRUE))
1414         goto server_dead;
1415     }
1416     GST_DEBUG_OBJECT (psink, "flush completed");
1417   }
1418   res = TRUE;
1419
1420 cleanup:
1421   if (o) {
1422     pa_operation_cancel (o);
1423     pa_operation_unref (o);
1424   }
1425 #if 0
1426   GST_DEBUG_OBJECT (psink, "scheduling stream status");
1427   psink->defer_pending++;
1428   pa_mainloop_api_once (pa_threaded_mainloop_get_api (mainloop),
1429       mainloop_leave_defer_cb, psink);
1430
1431   /* Wait for the stream status message to be posted. This needs to be done
1432    * synchronously because the callback will take the mainloop lock
1433    * (implicitly) and then take the GST_OBJECT_LOCK. Everywhere else, we take
1434    * the locks in the reverse order, so not doing this synchronously could
1435    * cause a deadlock. */
1436   GST_DEBUG_OBJECT (psink, "waiting for stream status (LEAVE) to be posted");
1437   pa_threaded_mainloop_wait (mainloop);
1438 #endif
1439
1440   pa_threaded_mainloop_unlock (mainloop);
1441
1442   return res;
1443
1444   /* ERRORS */
1445 server_dead:
1446   {
1447     GST_DEBUG_OBJECT (psink, "the server is dead");
1448     goto cleanup;
1449   }
1450 }
1451
1452 /* in_samples >= out_samples, rate > 1.0 */
1453 #define FWD_UP_SAMPLES(s,se,d,de)               \
1454 G_STMT_START {                                  \
1455   guint8 *sb = s, *db = d;                      \
1456   while (s <= se && d < de) {                   \
1457     memcpy (d, s, bpf);                         \
1458     s += bpf;                                   \
1459     *accum += outr;                             \
1460     if ((*accum << 1) >= inr) {                 \
1461       *accum -= inr;                            \
1462       d += bpf;                                 \
1463     }                                           \
1464   }                                             \
1465   in_samples -= (s - sb)/bpf;                   \
1466   out_samples -= (d - db)/bpf;                  \
1467   GST_DEBUG ("fwd_up end %d/%d",*accum,*toprocess);     \
1468 } G_STMT_END
1469
1470 /* out_samples > in_samples, for rates smaller than 1.0 */
1471 #define FWD_DOWN_SAMPLES(s,se,d,de)             \
1472 G_STMT_START {                                  \
1473   guint8 *sb = s, *db = d;                      \
1474   while (s <= se && d < de) {                   \
1475     memcpy (d, s, bpf);                         \
1476     d += bpf;                                   \
1477     *accum += inr;                              \
1478     if ((*accum << 1) >= outr) {                \
1479       *accum -= outr;                           \
1480       s += bpf;                                 \
1481     }                                           \
1482   }                                             \
1483   in_samples -= (s - sb)/bpf;                   \
1484   out_samples -= (d - db)/bpf;                  \
1485   GST_DEBUG ("fwd_down end %d/%d",*accum,*toprocess);   \
1486 } G_STMT_END
1487
1488 #define REV_UP_SAMPLES(s,se,d,de)               \
1489 G_STMT_START {                                  \
1490   guint8 *sb = se, *db = d;                     \
1491   while (s <= se && d < de) {                   \
1492     memcpy (d, se, bpf);                        \
1493     se -= bpf;                                  \
1494     *accum += outr;                             \
1495     while (d < de && (*accum << 1) >= inr) {    \
1496       *accum -= inr;                            \
1497       d += bpf;                                 \
1498     }                                           \
1499   }                                             \
1500   in_samples -= (sb - se)/bpf;                  \
1501   out_samples -= (d - db)/bpf;                  \
1502   GST_DEBUG ("rev_up end %d/%d",*accum,*toprocess);     \
1503 } G_STMT_END
1504
1505 #define REV_DOWN_SAMPLES(s,se,d,de)             \
1506 G_STMT_START {                                  \
1507   guint8 *sb = se, *db = d;                     \
1508   while (s <= se && d < de) {                   \
1509     memcpy (d, se, bpf);                        \
1510     d += bpf;                                   \
1511     *accum += inr;                              \
1512     while (s <= se && (*accum << 1) >= outr) {  \
1513       *accum -= outr;                           \
1514       se -= bpf;                                \
1515     }                                           \
1516   }                                             \
1517   in_samples -= (sb - se)/bpf;                  \
1518   out_samples -= (d - db)/bpf;                  \
1519   GST_DEBUG ("rev_down end %d/%d",*accum,*toprocess);   \
1520 } G_STMT_END
1521
1522 /* our custom commit function because we write into the buffer of pulseaudio
1523  * instead of keeping our own buffer */
1524 static guint
1525 gst_pulseringbuffer_commit (GstAudioRingBuffer * buf, guint64 * sample,
1526     guchar * data, gint in_samples, gint out_samples, gint * accum)
1527 {
1528   GstPulseSink *psink;
1529   GstPulseRingBuffer *pbuf;
1530   guint result;
1531   guint8 *data_end;
1532   gboolean reverse;
1533   gint *toprocess;
1534   gint inr, outr, bpf;
1535   gint64 offset;
1536   guint bufsize;
1537
1538   pbuf = GST_PULSERING_BUFFER_CAST (buf);
1539   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1540
1541   /* FIXME post message rather than using a signal (as mixer interface) */
1542   if (g_atomic_int_compare_and_exchange (&psink->notify, 1, 0)) {
1543     g_object_notify (G_OBJECT (psink), "volume");
1544     g_object_notify (G_OBJECT (psink), "mute");
1545     g_object_notify (G_OBJECT (psink), "current-device");
1546   }
1547
1548   /* make sure the ringbuffer is started */
1549   if (G_UNLIKELY (g_atomic_int_get (&buf->state) !=
1550           GST_AUDIO_RING_BUFFER_STATE_STARTED)) {
1551     /* see if we are allowed to start it */
1552     if (G_UNLIKELY (g_atomic_int_get (&buf->may_start) == FALSE))
1553       goto no_start;
1554
1555     GST_DEBUG_OBJECT (buf, "start!");
1556     if (!gst_audio_ring_buffer_start (buf))
1557       goto start_failed;
1558   }
1559
1560   pa_threaded_mainloop_lock (mainloop);
1561
1562   GST_DEBUG_OBJECT (psink, "entering commit");
1563   pbuf->in_commit = TRUE;
1564
1565   bpf = GST_AUDIO_INFO_BPF (&buf->spec.info);
1566   bufsize = buf->spec.segsize * buf->spec.segtotal;
1567
1568   /* our toy resampler for trick modes */
1569   reverse = out_samples < 0;
1570   out_samples = ABS (out_samples);
1571
1572   if (in_samples >= out_samples)
1573     toprocess = &in_samples;
1574   else
1575     toprocess = &out_samples;
1576
1577   inr = in_samples - 1;
1578   outr = out_samples - 1;
1579
1580   GST_DEBUG_OBJECT (psink, "in %d, out %d", inr, outr);
1581
1582   /* data_end points to the last sample we have to write, not past it. This is
1583    * needed to properly handle reverse playback: it points to the last sample. */
1584   data_end = data + (bpf * inr);
1585
1586   if (g_atomic_int_get (&psink->format_lost)) {
1587     /* Sink format changed, drop the data and hope upstream renegotiates */
1588     goto fake_done;
1589   }
1590
1591   if (pbuf->paused)
1592     goto was_paused;
1593
1594 #ifdef __TIZEN__
1595   /* ensure running clock for whatever out there */
1596   if (pbuf->corked) {
1597     if (!gst_pulsering_set_corked (pbuf, FALSE, FALSE))
1598       goto uncork_failed;
1599   }
1600 #endif
1601   /* offset is in bytes */
1602   offset = *sample * bpf;
1603
1604   while (*toprocess > 0) {
1605     size_t avail;
1606     guint towrite;
1607
1608     GST_LOG_OBJECT (psink,
1609         "need to write %d samples at offset %" G_GINT64_FORMAT, *toprocess,
1610         offset);
1611
1612     if (offset != pbuf->m_lastoffset)
1613       GST_LOG_OBJECT (psink, "discontinuity, offset is %" G_GINT64_FORMAT ", "
1614           "last offset was %" G_GINT64_FORMAT, offset, pbuf->m_lastoffset);
1615
1616     towrite = out_samples * bpf;
1617
1618     /* Wait for at least segsize bytes to become available */
1619     if (towrite > buf->spec.segsize)
1620       towrite = buf->spec.segsize;
1621
1622     if ((pbuf->m_writable < towrite) || (offset != pbuf->m_lastoffset)) {
1623       /* if no room left or discontinuity in offset,
1624          we need to flush data and get a new buffer */
1625
1626       /* flush the buffer if possible */
1627       if ((pbuf->m_data != NULL) && (pbuf->m_towrite > 0)) {
1628
1629         GST_LOG_OBJECT (psink,
1630             "flushing %u samples at offset %" G_GINT64_FORMAT,
1631             (guint) pbuf->m_towrite / bpf, pbuf->m_offset);
1632
1633         if (pa_stream_write (pbuf->stream, (uint8_t *) pbuf->m_data,
1634                 pbuf->m_towrite, NULL, pbuf->m_offset, PA_SEEK_ABSOLUTE) < 0) {
1635           goto write_failed;
1636         }
1637       }
1638       pbuf->m_towrite = 0;
1639       pbuf->m_offset = offset;  /* keep track of current offset */
1640
1641       /* get a buffer to write in for now on */
1642       for (;;) {
1643         pbuf->m_writable = pa_stream_writable_size (pbuf->stream);
1644
1645         if (g_atomic_int_get (&psink->format_lost)) {
1646           /* Sink format changed, give up and hope upstream renegotiates */
1647           goto fake_done;
1648         }
1649
1650         if (pbuf->m_writable == (size_t) - 1)
1651           goto writable_size_failed;
1652
1653         pbuf->m_writable /= bpf;
1654         pbuf->m_writable *= bpf;        /* handle only complete samples */
1655
1656         if (pbuf->m_writable >= towrite)
1657           break;
1658
1659         /* see if we need to uncork because we have no free space */
1660         if (pbuf->corked) {
1661           if (!gst_pulsering_set_corked (pbuf, FALSE, FALSE))
1662             goto uncork_failed;
1663         }
1664
1665         /* we can't write segsize bytes, wait a bit */
1666         GST_LOG_OBJECT (psink, "waiting for free space");
1667         pa_threaded_mainloop_wait (mainloop);
1668
1669         if (pbuf->paused)
1670           goto was_paused;
1671       }
1672
1673       /* Recalculate what we can write in the next chunk */
1674       towrite = out_samples * bpf;
1675       if (pbuf->m_writable > towrite)
1676         pbuf->m_writable = towrite;
1677
1678       GST_LOG_OBJECT (psink, "requesting %" G_GSIZE_FORMAT " bytes of "
1679           "shared memory", pbuf->m_writable);
1680
1681       if (pa_stream_begin_write (pbuf->stream, &pbuf->m_data,
1682               &pbuf->m_writable) < 0) {
1683         GST_LOG_OBJECT (psink, "pa_stream_begin_write() failed");
1684         goto writable_size_failed;
1685       }
1686
1687       GST_LOG_OBJECT (psink, "got %" G_GSIZE_FORMAT " bytes of shared memory",
1688           pbuf->m_writable);
1689
1690     }
1691
1692     if (towrite > pbuf->m_writable)
1693       towrite = pbuf->m_writable;
1694     avail = towrite / bpf;
1695
1696     GST_LOG_OBJECT (psink, "writing %u samples at offset %" G_GUINT64_FORMAT,
1697         (guint) avail, offset);
1698
1699     /* No trick modes for passthrough streams */
1700     if (G_UNLIKELY (!pbuf->is_pcm && (inr != outr || reverse))) {
1701       GST_WARNING_OBJECT (psink, "Passthrough stream can't run in trick mode");
1702       goto unlock_and_fail;
1703     }
1704
1705     if (G_LIKELY (inr == outr && !reverse)) {
1706       /* no rate conversion, simply write out the samples */
1707       /* copy the data into internal buffer */
1708
1709       memcpy ((guint8 *) pbuf->m_data + pbuf->m_towrite, data, towrite);
1710       pbuf->m_towrite += towrite;
1711       pbuf->m_writable -= towrite;
1712
1713       data += towrite;
1714       in_samples -= avail;
1715       out_samples -= avail;
1716     } else {
1717       guint8 *dest, *d, *d_end;
1718
1719       /* write into the PulseAudio shm buffer */
1720       dest = d = (guint8 *) pbuf->m_data + pbuf->m_towrite;
1721       d_end = d + towrite;
1722
1723       if (!reverse) {
1724         if (inr >= outr)
1725           /* forward speed up */
1726           FWD_UP_SAMPLES (data, data_end, d, d_end);
1727         else
1728           /* forward slow down */
1729           FWD_DOWN_SAMPLES (data, data_end, d, d_end);
1730       } else {
1731         if (inr >= outr)
1732           /* reverse speed up */
1733           REV_UP_SAMPLES (data, data_end, d, d_end);
1734         else
1735           /* reverse slow down */
1736           REV_DOWN_SAMPLES (data, data_end, d, d_end);
1737       }
1738       /* see what we have left to write */
1739       towrite = (d - dest);
1740       pbuf->m_towrite += towrite;
1741       pbuf->m_writable -= towrite;
1742
1743       avail = towrite / bpf;
1744     }
1745
1746     /* flush the buffer if it's full */
1747     if ((pbuf->m_data != NULL) && (pbuf->m_towrite > 0)
1748         && (pbuf->m_writable == 0)) {
1749       GST_LOG_OBJECT (psink, "flushing %u samples at offset %" G_GINT64_FORMAT,
1750           (guint) pbuf->m_towrite / bpf, pbuf->m_offset);
1751
1752       if (pa_stream_write (pbuf->stream, (uint8_t *) pbuf->m_data,
1753               pbuf->m_towrite, NULL, pbuf->m_offset, PA_SEEK_ABSOLUTE) < 0) {
1754         goto write_failed;
1755       }
1756       pbuf->m_towrite = 0;
1757       pbuf->m_offset = offset + towrite;        /* keep track of current offset */
1758     }
1759
1760     *sample += avail;
1761     offset += avail * bpf;
1762     pbuf->m_lastoffset = offset;
1763
1764     /* check if we need to uncork after writing the samples */
1765     if (pbuf->corked) {
1766       const pa_timing_info *info;
1767
1768       if ((info = pa_stream_get_timing_info (pbuf->stream))) {
1769         GST_LOG_OBJECT (psink,
1770             "read_index at %" G_GUINT64_FORMAT ", offset %" G_GINT64_FORMAT,
1771             info->read_index, offset);
1772
1773         /* we uncork when the read_index is too far behind the offset we need
1774          * to write to. */
1775         if (info->read_index + bufsize <= offset) {
1776           if (!gst_pulsering_set_corked (pbuf, FALSE, FALSE))
1777             goto uncork_failed;
1778         }
1779       } else {
1780         GST_LOG_OBJECT (psink, "no timing info available yet");
1781       }
1782     }
1783   }
1784
1785 fake_done:
1786   /* we consumed all samples here */
1787   data = data_end + bpf;
1788
1789   pbuf->in_commit = FALSE;
1790   pa_threaded_mainloop_unlock (mainloop);
1791
1792 done:
1793   result = inr - ((data_end - data) / bpf);
1794   GST_LOG_OBJECT (psink, "wrote %d samples", result);
1795
1796   return result;
1797
1798   /* ERRORS */
1799 unlock_and_fail:
1800   {
1801     pbuf->in_commit = FALSE;
1802     GST_LOG_OBJECT (psink, "we are reset");
1803     pa_threaded_mainloop_unlock (mainloop);
1804     goto done;
1805   }
1806 no_start:
1807   {
1808     GST_LOG_OBJECT (psink, "we can not start");
1809     return 0;
1810   }
1811 start_failed:
1812   {
1813     GST_LOG_OBJECT (psink, "failed to start the ringbuffer");
1814     return 0;
1815   }
1816 uncork_failed:
1817   {
1818     pbuf->in_commit = FALSE;
1819     GST_ERROR_OBJECT (psink, "uncork failed");
1820     pa_threaded_mainloop_unlock (mainloop);
1821     goto done;
1822   }
1823 was_paused:
1824   {
1825     pbuf->in_commit = FALSE;
1826     GST_LOG_OBJECT (psink, "we are paused");
1827     pa_threaded_mainloop_unlock (mainloop);
1828     goto done;
1829   }
1830 writable_size_failed:
1831   {
1832     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1833         ("pa_stream_writable_size() failed: %s",
1834             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1835     goto unlock_and_fail;
1836   }
1837 write_failed:
1838   {
1839     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1840         ("pa_stream_write() failed: %s",
1841             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1842     goto unlock_and_fail;
1843   }
1844 }
1845
1846 /* write pending local samples, must be called with the mainloop lock */
1847 static void
1848 gst_pulsering_flush (GstPulseRingBuffer * pbuf)
1849 {
1850   GstPulseSink *psink;
1851
1852   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
1853   GST_DEBUG_OBJECT (psink, "entering flush");
1854
1855   /* flush the buffer if possible */
1856   if (pbuf->stream && (pbuf->m_data != NULL) && (pbuf->m_towrite > 0)) {
1857 #ifndef GST_DISABLE_GST_DEBUG
1858     gint bpf;
1859
1860     bpf = (GST_AUDIO_RING_BUFFER_CAST (pbuf))->spec.info.bpf;
1861     GST_LOG_OBJECT (psink,
1862         "flushing %u samples at offset %" G_GINT64_FORMAT,
1863         (guint) pbuf->m_towrite / bpf, pbuf->m_offset);
1864 #endif
1865
1866     if (pa_stream_write (pbuf->stream, (uint8_t *) pbuf->m_data,
1867             pbuf->m_towrite, NULL, pbuf->m_offset, PA_SEEK_ABSOLUTE) < 0) {
1868       goto write_failed;
1869     }
1870
1871     pbuf->m_towrite = 0;
1872     pbuf->m_offset += pbuf->m_towrite;  /* keep track of current offset */
1873   }
1874
1875 done:
1876   return;
1877
1878   /* ERRORS */
1879 write_failed:
1880   {
1881     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
1882         ("pa_stream_write() failed: %s",
1883             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
1884     goto done;
1885   }
1886 }
1887
1888 static void gst_pulsesink_set_property (GObject * object, guint prop_id,
1889     const GValue * value, GParamSpec * pspec);
1890 static void gst_pulsesink_get_property (GObject * object, guint prop_id,
1891     GValue * value, GParamSpec * pspec);
1892 static void gst_pulsesink_finalize (GObject * object);
1893
1894 static gboolean gst_pulsesink_event (GstBaseSink * sink, GstEvent * event);
1895 static gboolean gst_pulsesink_query (GstBaseSink * sink, GstQuery * query);
1896
1897 static GstStateChangeReturn gst_pulsesink_change_state (GstElement * element,
1898     GstStateChange transition);
1899
1900 #define gst_pulsesink_parent_class parent_class
1901 G_DEFINE_TYPE_WITH_CODE (GstPulseSink, gst_pulsesink, GST_TYPE_AUDIO_BASE_SINK,
1902     gst_pulsesink_init_contexts ();
1903     G_IMPLEMENT_INTERFACE (GST_TYPE_STREAM_VOLUME, NULL)
1904     );
1905
1906 static GstAudioRingBuffer *
1907 gst_pulsesink_create_ringbuffer (GstAudioBaseSink * sink)
1908 {
1909   GstAudioRingBuffer *buffer;
1910
1911   GST_DEBUG_OBJECT (sink, "creating ringbuffer");
1912   buffer = g_object_new (GST_TYPE_PULSERING_BUFFER, NULL);
1913   GST_DEBUG_OBJECT (sink, "created ringbuffer @%p", buffer);
1914
1915   return buffer;
1916 }
1917
1918 static GstBuffer *
1919 gst_pulsesink_payload (GstAudioBaseSink * sink, GstBuffer * buf)
1920 {
1921   switch (sink->ringbuffer->spec.type) {
1922     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_AC3:
1923     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_EAC3:
1924     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_DTS:
1925     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_MPEG:
1926     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_MPEG2_AAC:
1927     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_MPEG4_AAC:
1928     {
1929       /* FIXME: alloc memory from PA if possible */
1930       gint framesize = gst_audio_iec61937_frame_size (&sink->ringbuffer->spec);
1931       GstBuffer *out;
1932       GstMapInfo inmap, outmap;
1933       gboolean res;
1934
1935       if (framesize <= 0)
1936         return NULL;
1937
1938       out = gst_buffer_new_and_alloc (framesize);
1939
1940       gst_buffer_map (buf, &inmap, GST_MAP_READ);
1941       gst_buffer_map (out, &outmap, GST_MAP_WRITE);
1942
1943       res = gst_audio_iec61937_payload (inmap.data, inmap.size,
1944           outmap.data, outmap.size, &sink->ringbuffer->spec, G_BIG_ENDIAN);
1945
1946       gst_buffer_unmap (buf, &inmap);
1947       gst_buffer_unmap (out, &outmap);
1948
1949       if (!res) {
1950         gst_buffer_unref (out);
1951         return NULL;
1952       }
1953
1954       gst_buffer_copy_into (out, buf, GST_BUFFER_COPY_METADATA, 0, -1);
1955       return out;
1956     }
1957
1958     default:
1959       return gst_buffer_ref (buf);
1960   }
1961 }
1962
1963 #if defined(__TIZEN__) && defined(PCM_DUMP_ENABLE)
1964 static GstPadProbeReturn
1965 gst_pulsesink_pad_dump_probe (GstPad * pad, GstPadProbeInfo * info, gpointer data)
1966 {
1967   GstPulseSink *psink = GST_PULSESINK_CAST (data);
1968   size_t written = 0;
1969   GstBuffer *buffer = GST_PAD_PROBE_INFO_BUFFER (info);
1970   GstMapInfo in_map;
1971   if (psink->dump_fd_input) {
1972     gst_buffer_map(buffer, &in_map, GST_MAP_READ);
1973     written = fwrite(in_map.data, 1, in_map.size, psink->dump_fd_input);
1974     if (written != in_map.size)
1975       GST_WARNING("failed to write!!! ferror=%d", ferror(psink->dump_fd_input));
1976     gst_buffer_unmap(buffer, &in_map);
1977   }
1978   return GST_PAD_PROBE_OK;
1979 }
1980 #endif /* __TIZEN__ && PCM_DUMP_ENABLE */
1981
1982 static void
1983 gst_pulsesink_class_init (GstPulseSinkClass * klass)
1984 {
1985   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1986   GstBaseSinkClass *gstbasesink_class = GST_BASE_SINK_CLASS (klass);
1987   GstBaseSinkClass *bc;
1988   GstAudioBaseSinkClass *gstaudiosink_class = GST_AUDIO_BASE_SINK_CLASS (klass);
1989   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
1990   GstCaps *caps;
1991   gchar *clientname;
1992
1993   gobject_class->finalize = gst_pulsesink_finalize;
1994   gobject_class->set_property = gst_pulsesink_set_property;
1995   gobject_class->get_property = gst_pulsesink_get_property;
1996
1997   gstbasesink_class->event = GST_DEBUG_FUNCPTR (gst_pulsesink_event);
1998   gstbasesink_class->query = GST_DEBUG_FUNCPTR (gst_pulsesink_query);
1999
2000   /* restore the original basesink pull methods */
2001   bc = g_type_class_peek (GST_TYPE_BASE_SINK);
2002   gstbasesink_class->activate_pull = GST_DEBUG_FUNCPTR (bc->activate_pull);
2003
2004   gstelement_class->change_state =
2005       GST_DEBUG_FUNCPTR (gst_pulsesink_change_state);
2006
2007   gstaudiosink_class->create_ringbuffer =
2008       GST_DEBUG_FUNCPTR (gst_pulsesink_create_ringbuffer);
2009   gstaudiosink_class->payload = GST_DEBUG_FUNCPTR (gst_pulsesink_payload);
2010
2011   /* Overwrite GObject fields */
2012   g_object_class_install_property (gobject_class,
2013       PROP_SERVER,
2014       g_param_spec_string ("server", "Server",
2015           "The PulseAudio server to connect to", DEFAULT_SERVER,
2016           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2017
2018   g_object_class_install_property (gobject_class, PROP_DEVICE,
2019       g_param_spec_string ("device", "Device",
2020           "The PulseAudio sink device to connect to", DEFAULT_DEVICE,
2021           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2022
2023   g_object_class_install_property (gobject_class, PROP_CURRENT_DEVICE,
2024       g_param_spec_string ("current-device", "Current Device",
2025           "The current PulseAudio sink device", DEFAULT_CURRENT_DEVICE,
2026           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
2027
2028   g_object_class_install_property (gobject_class,
2029       PROP_DEVICE_NAME,
2030       g_param_spec_string ("device-name", "Device name",
2031           "Human-readable name of the sound device", DEFAULT_DEVICE_NAME,
2032           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
2033
2034   g_object_class_install_property (gobject_class,
2035       PROP_VOLUME,
2036       g_param_spec_double ("volume", "Volume",
2037           "Linear volume of this stream, 1.0=100%", 0.0, MAX_VOLUME,
2038           DEFAULT_VOLUME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2039   g_object_class_install_property (gobject_class,
2040       PROP_MUTE,
2041       g_param_spec_boolean ("mute", "Mute",
2042           "Mute state of this stream", DEFAULT_MUTE,
2043           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2044
2045   /**
2046    * GstPulseSink:client-name:
2047    *
2048    * The PulseAudio client name to use.
2049    */
2050   clientname = gst_pulse_client_name ();
2051   g_object_class_install_property (gobject_class,
2052       PROP_CLIENT_NAME,
2053       g_param_spec_string ("client-name", "Client Name",
2054           "The PulseAudio client name to use", clientname,
2055           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
2056           GST_PARAM_MUTABLE_READY));
2057   g_free (clientname);
2058
2059   /**
2060    * GstPulseSink:stream-properties:
2061    *
2062    * List of pulseaudio stream properties. A list of defined properties can be
2063    * found in the <ulink url="http://0pointer.de/lennart/projects/pulseaudio/doxygen/proplist_8h.html">pulseaudio api docs</ulink>.
2064    *
2065    * Below is an example for registering as a music application to pulseaudio.
2066    * |[
2067    * GstStructure *props;
2068    *
2069    * props = gst_structure_from_string ("props,media.role=music", NULL);
2070    * g_object_set (pulse, "stream-properties", props, NULL);
2071    * gst_structure_free
2072    * ]|
2073    */
2074   g_object_class_install_property (gobject_class,
2075       PROP_STREAM_PROPERTIES,
2076       g_param_spec_boxed ("stream-properties", "stream properties",
2077           "list of pulseaudio stream properties",
2078           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2079
2080 #ifdef __TIZEN__
2081   g_object_class_install_property (gobject_class,
2082       PROP_AUDIO_LATENCY,
2083       g_param_spec_string ("latency", "Audio Backend Latency",
2084           "Audio Backend Latency (\"low\": Low Latency, \"mid\": Mid Latency, \"high\": High Latency)",
2085           DEFAULT_AUDIO_LATENCY,
2086           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2087 #endif /* __TIZEN__ */
2088
2089   gst_element_class_set_static_metadata (gstelement_class,
2090       "PulseAudio Audio Sink",
2091       "Sink/Audio", "Plays audio to a PulseAudio server", "Lennart Poettering");
2092
2093   caps =
2094       gst_pulse_fix_pcm_caps (gst_caps_from_string (PULSE_SINK_TEMPLATE_CAPS));
2095   gst_element_class_add_pad_template (gstelement_class,
2096       gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, caps));
2097   gst_caps_unref (caps);
2098 }
2099
2100 static void
2101 free_device_info (GstPulseDeviceInfo * device_info)
2102 {
2103   GList *l;
2104
2105   g_free (device_info->description);
2106
2107   for (l = g_list_first (device_info->formats); l; l = g_list_next (l))
2108     pa_format_info_free ((pa_format_info *) l->data);
2109
2110   g_list_free (device_info->formats);
2111 }
2112
2113 /* Returns the current time of the sink ringbuffer. The timing_info is updated
2114  * on every data write/flush and every 100ms (PA_STREAM_AUTO_TIMING_UPDATE).
2115  */
2116 static GstClockTime
2117 gst_pulsesink_get_time (GstClock * clock, GstAudioBaseSink * sink)
2118 {
2119   GstPulseSink *psink;
2120   GstPulseRingBuffer *pbuf;
2121   pa_usec_t time;
2122
2123   if (!sink->ringbuffer || !sink->ringbuffer->acquired)
2124     return GST_CLOCK_TIME_NONE;
2125
2126   pbuf = GST_PULSERING_BUFFER_CAST (sink->ringbuffer);
2127   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
2128
2129   if (g_atomic_int_get (&psink->format_lost)) {
2130     /* Stream was lost in a format change, it'll get set up again once
2131      * upstream renegotiates */
2132     return psink->format_lost_time;
2133   }
2134
2135   pa_threaded_mainloop_lock (mainloop);
2136   if (gst_pulsering_is_dead (psink, pbuf, TRUE))
2137     goto server_dead;
2138
2139   /* if we don't have enough data to get a timestamp, just return NONE, which
2140    * will return the last reported time */
2141   if (pa_stream_get_time (pbuf->stream, &time) < 0) {
2142     GST_DEBUG_OBJECT (psink, "could not get time");
2143     time = GST_CLOCK_TIME_NONE;
2144   } else
2145     time *= 1000;
2146   pa_threaded_mainloop_unlock (mainloop);
2147
2148   GST_LOG_OBJECT (psink, "current time is %" GST_TIME_FORMAT,
2149       GST_TIME_ARGS (time));
2150
2151   return time;
2152
2153   /* ERRORS */
2154 server_dead:
2155   {
2156     GST_DEBUG_OBJECT (psink, "the server is dead");
2157     pa_threaded_mainloop_unlock (mainloop);
2158
2159     return GST_CLOCK_TIME_NONE;
2160   }
2161 }
2162
2163 static void
2164 gst_pulsesink_sink_info_cb (pa_context * c, const pa_sink_info * i, int eol,
2165     void *userdata)
2166 {
2167   GstPulseDeviceInfo *device_info = (GstPulseDeviceInfo *) userdata;
2168   guint8 j;
2169
2170   if (!i)
2171     goto done;
2172
2173   device_info->description = g_strdup (i->description);
2174
2175   device_info->formats = NULL;
2176   for (j = 0; j < i->n_formats; j++)
2177     device_info->formats = g_list_prepend (device_info->formats,
2178         pa_format_info_copy (i->formats[j]));
2179
2180 done:
2181   pa_threaded_mainloop_signal (mainloop, 0);
2182 }
2183
2184 /* Call with mainloop lock held */
2185 static pa_stream *
2186 gst_pulsesink_create_probe_stream (GstPulseSink * psink,
2187     GstPulseRingBuffer * pbuf, pa_format_info * format)
2188 {
2189   pa_format_info *formats[1] = { format };
2190   pa_stream *stream;
2191   pa_stream_flags_t flags;
2192
2193   GST_LOG_OBJECT (psink, "Creating probe stream");
2194
2195   if (!(stream = pa_stream_new_extended (pbuf->context, "pulsesink probe",
2196               formats, 1, psink->proplist)))
2197     goto error;
2198
2199   /* construct the flags */
2200   flags = PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE |
2201       PA_STREAM_ADJUST_LATENCY | PA_STREAM_START_CORKED;
2202
2203   pa_stream_set_state_callback (stream, gst_pulsering_stream_state_cb, pbuf);
2204
2205   if (pa_stream_connect_playback (stream, psink->device, NULL, flags, NULL,
2206           NULL) < 0)
2207     goto error;
2208
2209   if (!gst_pulsering_wait_for_stream_ready (psink, stream))
2210     goto error;
2211
2212   return stream;
2213
2214 error:
2215   if (stream)
2216     pa_stream_unref (stream);
2217   return NULL;
2218 }
2219
2220 static GstCaps *
2221 gst_pulsesink_query_getcaps (GstPulseSink * psink, GstCaps * filter)
2222 {
2223   GstPulseRingBuffer *pbuf = NULL;
2224   GstPulseDeviceInfo device_info = { NULL, NULL };
2225   GstCaps *ret = NULL;
2226   GList *i;
2227   pa_operation *o = NULL;
2228   pa_stream *stream;
2229
2230   GST_OBJECT_LOCK (psink);
2231   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2232   if (pbuf != NULL)
2233     gst_object_ref (pbuf);
2234   GST_OBJECT_UNLOCK (psink);
2235
2236   if (!pbuf) {
2237     ret = gst_pad_get_pad_template_caps (GST_AUDIO_BASE_SINK_PAD (psink));
2238     goto out;
2239   }
2240
2241   GST_OBJECT_LOCK (pbuf);
2242   pa_threaded_mainloop_lock (mainloop);
2243
2244   if (!pbuf->context) {
2245     ret = gst_pad_get_pad_template_caps (GST_AUDIO_BASE_SINK_PAD (psink));
2246     goto unlock;
2247   }
2248
2249   ret = gst_caps_new_empty ();
2250
2251   if (pbuf->stream) {
2252     /* We're in PAUSED or higher */
2253     stream = pbuf->stream;
2254
2255   } else if (pbuf->probe_stream) {
2256     /* We're not paused, but have a cached probe stream */
2257     stream = pbuf->probe_stream;
2258
2259   } else {
2260     /* We're not yet in PAUSED and still need to create a probe stream.
2261      *
2262      * FIXME: PA doesn't accept "any" format. We fix something reasonable since
2263      * this is merely a probe. This should eventually be fixed in PA and
2264      * hard-coding the format should be dropped. */
2265     pa_format_info *format = pa_format_info_new ();
2266     format->encoding = PA_ENCODING_PCM;
2267     pa_format_info_set_sample_format (format, PA_SAMPLE_S16LE);
2268     pa_format_info_set_rate (format, GST_AUDIO_DEF_RATE);
2269     pa_format_info_set_channels (format, GST_AUDIO_DEF_CHANNELS);
2270
2271     pbuf->probe_stream = gst_pulsesink_create_probe_stream (psink, pbuf,
2272         format);
2273
2274     pa_format_info_free (format);
2275
2276     if (!pbuf->probe_stream) {
2277       GST_WARNING_OBJECT (psink, "Could not create probe stream");
2278       goto unlock;
2279     }
2280
2281     stream = pbuf->probe_stream;
2282   }
2283
2284   if (!(o = pa_context_get_sink_info_by_name (pbuf->context,
2285               pa_stream_get_device_name (stream), gst_pulsesink_sink_info_cb,
2286               &device_info)))
2287     goto info_failed;
2288
2289   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2290     pa_threaded_mainloop_wait (mainloop);
2291     if (gst_pulsering_is_dead (psink, pbuf, FALSE))
2292       goto unlock;
2293   }
2294
2295   for (i = g_list_first (device_info.formats); i; i = g_list_next (i)) {
2296     GstCaps *caps = gst_pulse_format_info_to_caps ((pa_format_info *) i->data);
2297     if (caps)
2298       gst_caps_append (ret, caps);
2299   }
2300
2301 unlock:
2302   pa_threaded_mainloop_unlock (mainloop);
2303   /* FIXME: this could be freed after device_name is got */
2304   GST_OBJECT_UNLOCK (pbuf);
2305
2306   if (filter) {
2307     GstCaps *tmp = gst_caps_intersect_full (filter, ret,
2308         GST_CAPS_INTERSECT_FIRST);
2309     gst_caps_unref (ret);
2310     ret = tmp;
2311   }
2312
2313 out:
2314   free_device_info (&device_info);
2315
2316   if (o)
2317     pa_operation_unref (o);
2318
2319   if (pbuf)
2320     gst_object_unref (pbuf);
2321
2322   GST_DEBUG_OBJECT (psink, "caps %" GST_PTR_FORMAT, ret);
2323
2324   return ret;
2325
2326 info_failed:
2327   {
2328     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2329         ("pa_context_get_sink_input_info() failed: %s",
2330             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2331     goto unlock;
2332   }
2333 }
2334
2335 static gboolean
2336 gst_pulsesink_query_acceptcaps (GstPulseSink * psink, GstCaps * caps)
2337 {
2338   GstPulseRingBuffer *pbuf = NULL;
2339   GstPulseDeviceInfo device_info = { NULL, NULL };
2340   GstCaps *pad_caps;
2341   GstStructure *st;
2342   gboolean ret = FALSE;
2343
2344   GstAudioRingBufferSpec spec = { 0 };
2345   pa_operation *o = NULL;
2346   pa_channel_map channel_map;
2347   pa_format_info *format = NULL;
2348   guint channels;
2349
2350   pad_caps = gst_pad_get_pad_template_caps (GST_BASE_SINK_PAD (psink));
2351   ret = gst_caps_is_subset (caps, pad_caps);
2352   gst_caps_unref (pad_caps);
2353
2354   GST_DEBUG_OBJECT (psink, "caps %" GST_PTR_FORMAT, caps);
2355
2356   /* Template caps didn't match */
2357   if (!ret)
2358     goto done;
2359
2360   /* If we've not got fixed caps, creating a stream might fail, so let's just
2361    * return from here with default acceptcaps behaviour */
2362   if (!gst_caps_is_fixed (caps))
2363     goto done;
2364
2365   GST_OBJECT_LOCK (psink);
2366   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2367   if (pbuf != NULL)
2368     gst_object_ref (pbuf);
2369   GST_OBJECT_UNLOCK (psink);
2370
2371   /* We're still in NULL state */
2372   if (pbuf == NULL)
2373     goto done;
2374
2375   GST_OBJECT_LOCK (pbuf);
2376   pa_threaded_mainloop_lock (mainloop);
2377
2378   if (pbuf->context == NULL)
2379     goto out;
2380
2381   ret = FALSE;
2382
2383   spec.latency_time = GST_AUDIO_BASE_SINK (psink)->latency_time;
2384   if (!gst_audio_ring_buffer_parse_caps (&spec, caps))
2385     goto out;
2386
2387   if (!gst_pulse_fill_format_info (&spec, &format, &channels))
2388     goto out;
2389
2390   /* Make sure input is framed (one frame per buffer) and can be payloaded */
2391   if (!pa_format_info_is_pcm (format)) {
2392     gboolean framed = FALSE, parsed = FALSE;
2393     st = gst_caps_get_structure (caps, 0);
2394
2395     gst_structure_get_boolean (st, "framed", &framed);
2396     gst_structure_get_boolean (st, "parsed", &parsed);
2397     if ((!framed && !parsed) || gst_audio_iec61937_frame_size (&spec) <= 0)
2398       goto out;
2399   }
2400
2401   /* initialize the channel map */
2402   if (pa_format_info_is_pcm (format) &&
2403       gst_pulse_gst_to_channel_map (&channel_map, &spec))
2404     pa_format_info_set_channel_map (format, &channel_map);
2405
2406   if (pbuf->stream || pbuf->probe_stream) {
2407     /* We're already in PAUSED or above, so just reuse this stream to query
2408      * sink formats and use those. */
2409     GList *i;
2410     const char *device_name = pa_stream_get_device_name (pbuf->stream ?
2411         pbuf->stream : pbuf->probe_stream);
2412
2413     if (!(o = pa_context_get_sink_info_by_name (pbuf->context, device_name,
2414                 gst_pulsesink_sink_info_cb, &device_info)))
2415       goto info_failed;
2416
2417     while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2418       pa_threaded_mainloop_wait (mainloop);
2419       if (gst_pulsering_is_dead (psink, pbuf, FALSE))
2420         goto out;
2421     }
2422
2423     for (i = g_list_first (device_info.formats); i; i = g_list_next (i)) {
2424       if (pa_format_info_is_compatible ((pa_format_info *) i->data, format)) {
2425         ret = TRUE;
2426         break;
2427       }
2428     }
2429   } else {
2430     /* We're in READY, let's connect a stream to see if the format is
2431      * accepted by whatever sink we're routed to */
2432     pbuf->probe_stream = gst_pulsesink_create_probe_stream (psink, pbuf,
2433         format);
2434     if (pbuf->probe_stream)
2435       ret = TRUE;
2436   }
2437
2438 out:
2439   if (format)
2440     pa_format_info_free (format);
2441
2442   free_device_info (&device_info);
2443
2444   if (o)
2445     pa_operation_unref (o);
2446
2447   pa_threaded_mainloop_unlock (mainloop);
2448   GST_OBJECT_UNLOCK (pbuf);
2449
2450   gst_caps_replace (&spec.caps, NULL);
2451   gst_object_unref (pbuf);
2452
2453 done:
2454
2455   return ret;
2456
2457 info_failed:
2458   {
2459     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2460         ("pa_context_get_sink_input_info() failed: %s",
2461             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2462     goto out;
2463   }
2464 }
2465
2466 static void
2467 gst_pulsesink_init (GstPulseSink * pulsesink)
2468 {
2469 #if defined(__TIZEN__) && defined(PCM_DUMP_ENABLE)
2470   GstPad *sinkpad = NULL;
2471   int vconf_dump = 0;
2472 #endif /* __TIZEN__ && PCM_DUMP_ENABLE */
2473
2474   pulsesink->server = NULL;
2475   pulsesink->device = NULL;
2476   pulsesink->device_info.description = NULL;
2477   pulsesink->client_name = gst_pulse_client_name ();
2478
2479   pulsesink->device_info.formats = NULL;
2480
2481   pulsesink->volume = DEFAULT_VOLUME;
2482   pulsesink->volume_set = FALSE;
2483
2484   pulsesink->mute = DEFAULT_MUTE;
2485   pulsesink->mute_set = FALSE;
2486
2487   pulsesink->notify = 0;
2488
2489   g_atomic_int_set (&pulsesink->format_lost, FALSE);
2490   pulsesink->format_lost_time = GST_CLOCK_TIME_NONE;
2491
2492   pulsesink->properties = NULL;
2493   pulsesink->proplist = NULL;
2494 #ifdef __TIZEN__
2495   pulsesink->latency = g_strdup (DEFAULT_AUDIO_LATENCY);
2496   pulsesink->proplist = pa_proplist_new();
2497   pa_proplist_sets(pulsesink->proplist, PA_PROP_MEDIA_TIZEN_AUDIO_LATENCY, pulsesink->latency);
2498 #ifdef PCM_DUMP_ENABLE
2499   if (vconf_get_int(GST_PULSESINK_DUMP_VCONF_KEY, &vconf_dump)) {
2500     GST_WARNING("vconf_get_int %s failed", GST_PULSESINK_DUMP_VCONF_KEY);
2501   }
2502   pulsesink->need_dump_input = vconf_dump & GST_PULSESINK_DUMP_INPUT_FLAG ? TRUE : FALSE;
2503   pulsesink->dump_fd_input = NULL;
2504   if (pulsesink->need_dump_input) {
2505     sinkpad = gst_element_get_static_pad((GstElement *)pulsesink, "sink");
2506     if (sinkpad) {
2507       gst_pad_add_probe (sinkpad, GST_PAD_PROBE_TYPE_BUFFER, gst_pulsesink_pad_dump_probe, pulsesink, NULL);
2508       gst_object_unref (GST_OBJECT(sinkpad));
2509     }
2510   }
2511 #endif
2512 #endif /* __TIZEN__ */
2513
2514   /* override with a custom clock */
2515   if (GST_AUDIO_BASE_SINK (pulsesink)->provided_clock)
2516     gst_object_unref (GST_AUDIO_BASE_SINK (pulsesink)->provided_clock);
2517
2518   GST_AUDIO_BASE_SINK (pulsesink)->provided_clock =
2519       gst_audio_clock_new ("GstPulseSinkClock",
2520       (GstAudioClockGetTimeFunc) gst_pulsesink_get_time, pulsesink, NULL);
2521 }
2522
2523 static void
2524 gst_pulsesink_finalize (GObject * object)
2525 {
2526   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
2527
2528   g_free (pulsesink->server);
2529   g_free (pulsesink->device);
2530   g_free (pulsesink->client_name);
2531   g_free (pulsesink->current_sink_name);
2532
2533   free_device_info (&pulsesink->device_info);
2534
2535   if (pulsesink->properties)
2536     gst_structure_free (pulsesink->properties);
2537   if (pulsesink->proplist)
2538     pa_proplist_free (pulsesink->proplist);
2539
2540 #ifdef __TIZEN__
2541   g_free (pulsesink->latency);
2542 #endif /* __TIZEN__ */
2543
2544   G_OBJECT_CLASS (parent_class)->finalize (object);
2545 }
2546
2547 static void
2548 gst_pulsesink_set_volume (GstPulseSink * psink, gdouble volume)
2549 {
2550 #ifndef __TIZEN__
2551   pa_cvolume v;
2552   pa_operation *o = NULL;
2553 #endif
2554   GstPulseRingBuffer *pbuf;
2555   uint32_t idx;
2556
2557 #ifndef __TIZEN__
2558   if (!mainloop)
2559     goto no_mainloop;
2560
2561   pa_threaded_mainloop_lock (mainloop);
2562 #endif
2563
2564   GST_DEBUG_OBJECT (psink, "setting volume to %f", volume);
2565
2566   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2567   if (pbuf == NULL || pbuf->stream == NULL)
2568     goto no_buffer;
2569
2570   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2571     goto no_index;
2572
2573 #ifndef __TIZEN__
2574   if (pbuf->is_pcm)
2575     gst_pulse_cvolume_from_linear (&v, pbuf->channels, volume);
2576   else
2577     /* FIXME: this will eventually be superceded by checks to see if the volume
2578      * is readable/writable */
2579     goto unlock;
2580
2581   if (!(o = pa_context_set_sink_input_volume (pbuf->context, idx,
2582               &v, NULL, NULL)))
2583     goto volume_failed;
2584
2585 #else
2586   if (!psink->mute)
2587     gst_pulse_set_volume_ratio (idx, "out", volume);
2588   psink->volume = volume;
2589 #endif
2590
2591   /* We don't really care about the result of this call */
2592 unlock:
2593 #ifndef __TIZEN__
2594
2595   if (o)
2596     pa_operation_unref (o);
2597
2598   pa_threaded_mainloop_unlock (mainloop);
2599 #endif
2600
2601   return;
2602
2603   /* ERRORS */
2604 #ifndef __TIZEN__
2605 no_mainloop:
2606   {
2607     psink->volume = volume;
2608     psink->volume_set = TRUE;
2609
2610     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2611     return;
2612   }
2613 #endif
2614 no_buffer:
2615   {
2616     psink->volume = volume;
2617     psink->volume_set = TRUE;
2618
2619     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2620     goto unlock;
2621   }
2622 no_index:
2623   {
2624     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2625     goto unlock;
2626   }
2627 #ifndef __TIZEN__
2628 volume_failed:
2629   {
2630     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2631         ("pa_stream_set_sink_input_volume() failed: %s",
2632             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2633     goto unlock;
2634   }
2635 #endif
2636 }
2637
2638 static void
2639 gst_pulsesink_set_mute (GstPulseSink * psink, gboolean mute)
2640 {
2641 #ifndef __TIZEN__
2642   pa_operation *o = NULL;
2643 #endif
2644   GstPulseRingBuffer *pbuf;
2645   uint32_t idx;
2646
2647 #ifndef __TIZEN__
2648   if (!mainloop)
2649     goto no_mainloop;
2650
2651   pa_threaded_mainloop_lock (mainloop);
2652 #endif
2653
2654   GST_DEBUG_OBJECT (psink, "setting mute state to %d", mute);
2655
2656   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2657   if (pbuf == NULL || pbuf->stream == NULL)
2658     goto no_buffer;
2659
2660   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2661     goto no_index;
2662
2663 #ifndef __TIZEN__
2664   if (!(o = pa_context_set_sink_input_mute (pbuf->context, idx,
2665               mute, NULL, NULL)))
2666     goto mute_failed;
2667 #else
2668   gst_pulse_set_volume_ratio (idx, "out", mute ? 0 : psink->volume);
2669   psink->mute = mute;
2670 #endif
2671
2672   /* We don't really care about the result of this call */
2673 unlock:
2674 #ifndef __TIZEN__
2675
2676   if (o)
2677     pa_operation_unref (o);
2678
2679   pa_threaded_mainloop_unlock (mainloop);
2680 #endif
2681
2682   return;
2683
2684   /* ERRORS */
2685 #ifndef __TIZEN__
2686 no_mainloop:
2687   {
2688     psink->mute = mute;
2689     psink->mute_set = TRUE;
2690
2691     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2692     return;
2693   }
2694 #endif
2695 no_buffer:
2696   {
2697     psink->mute = mute;
2698     psink->mute_set = TRUE;
2699
2700     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2701     goto unlock;
2702   }
2703 no_index:
2704   {
2705     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2706     goto unlock;
2707   }
2708 #ifndef __TIZEN__
2709 mute_failed:
2710   {
2711     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2712         ("pa_stream_set_sink_input_mute() failed: %s",
2713             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2714     goto unlock;
2715   }
2716 #endif
2717 }
2718
2719 static void
2720 gst_pulsesink_sink_input_info_cb (pa_context * c, const pa_sink_input_info * i,
2721     int eol, void *userdata)
2722 {
2723   GstPulseRingBuffer *pbuf;
2724   GstPulseSink *psink;
2725
2726   pbuf = GST_PULSERING_BUFFER_CAST (userdata);
2727   psink = GST_PULSESINK_CAST (GST_OBJECT_PARENT (pbuf));
2728
2729   if (!i)
2730     goto done;
2731
2732   if (!pbuf->stream)
2733     goto done;
2734
2735   /* If the index doesn't match our current stream,
2736    * it implies we just recreated the stream (caps change)
2737    */
2738   if (i->index == pa_stream_get_index (pbuf->stream)) {
2739     psink->volume = pa_sw_volume_to_linear (pa_cvolume_max (&i->volume));
2740     psink->mute = i->mute;
2741     psink->current_sink_idx = i->sink;
2742
2743     if (psink->volume > MAX_VOLUME) {
2744       GST_WARNING_OBJECT (psink, "Clipped volume from %f to %f", psink->volume,
2745           MAX_VOLUME);
2746       psink->volume = MAX_VOLUME;
2747     }
2748   }
2749
2750 done:
2751   pa_threaded_mainloop_signal (mainloop, 0);
2752 }
2753
2754 static void
2755 gst_pulsesink_get_sink_input_info (GstPulseSink * psink, gdouble * volume,
2756     gboolean * mute)
2757 {
2758   GstPulseRingBuffer *pbuf;
2759   pa_operation *o = NULL;
2760   uint32_t idx;
2761
2762   if (!mainloop)
2763     goto no_mainloop;
2764
2765   pa_threaded_mainloop_lock (mainloop);
2766
2767   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2768   if (pbuf == NULL || pbuf->stream == NULL)
2769     goto no_buffer;
2770
2771   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2772     goto no_index;
2773
2774   if (!(o = pa_context_get_sink_input_info (pbuf->context, idx,
2775               gst_pulsesink_sink_input_info_cb, pbuf)))
2776     goto info_failed;
2777
2778   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2779     pa_threaded_mainloop_wait (mainloop);
2780     if (gst_pulsering_is_dead (psink, pbuf, TRUE))
2781       goto unlock;
2782   }
2783
2784 unlock:
2785   if (volume)
2786     *volume = psink->volume;
2787   if (mute)
2788     *mute = psink->mute;
2789
2790   if (o)
2791     pa_operation_unref (o);
2792
2793   pa_threaded_mainloop_unlock (mainloop);
2794
2795   return;
2796
2797   /* ERRORS */
2798 no_mainloop:
2799   {
2800     if (volume)
2801       *volume = psink->volume;
2802     if (mute)
2803       *mute = psink->mute;
2804
2805     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2806     return;
2807   }
2808 no_buffer:
2809   {
2810     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2811     goto unlock;
2812   }
2813 no_index:
2814   {
2815     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
2816     goto unlock;
2817   }
2818 info_failed:
2819   {
2820     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2821         ("pa_context_get_sink_input_info() failed: %s",
2822             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2823     goto unlock;
2824   }
2825 }
2826
2827 static void
2828 gst_pulsesink_current_sink_info_cb (pa_context * c, const pa_sink_info * i,
2829     int eol, void *userdata)
2830 {
2831   GstPulseSink *psink;
2832
2833   psink = GST_PULSESINK_CAST (userdata);
2834
2835   if (!i)
2836     goto done;
2837
2838   /* If the index doesn't match our current stream,
2839    * it implies we just recreated the stream (caps change)
2840    */
2841   if (i->index == psink->current_sink_idx) {
2842     g_free (psink->current_sink_name);
2843     psink->current_sink_name = g_strdup (i->name);
2844   }
2845
2846 done:
2847   pa_threaded_mainloop_signal (mainloop, 0);
2848 }
2849
2850 static gchar *
2851 gst_pulsesink_get_current_device (GstPulseSink * pulsesink)
2852 {
2853   pa_operation *o = NULL;
2854   GstPulseRingBuffer *pbuf;
2855   gchar *current_sink;
2856
2857   if (!mainloop)
2858     goto no_mainloop;
2859
2860   pbuf =
2861       GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (pulsesink)->ringbuffer);
2862   if (pbuf == NULL || pbuf->stream == NULL)
2863     goto no_buffer;
2864
2865   gst_pulsesink_get_sink_input_info (pulsesink, NULL, NULL);
2866
2867   pa_threaded_mainloop_lock (mainloop);
2868
2869   if (!(o = pa_context_get_sink_info_by_index (pbuf->context,
2870               pulsesink->current_sink_idx, gst_pulsesink_current_sink_info_cb,
2871               pulsesink)))
2872     goto info_failed;
2873
2874   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2875     pa_threaded_mainloop_wait (mainloop);
2876     if (gst_pulsering_is_dead (pulsesink, pbuf, TRUE))
2877       goto unlock;
2878   }
2879
2880 unlock:
2881
2882   current_sink = g_strdup (pulsesink->current_sink_name);
2883
2884   if (o)
2885     pa_operation_unref (o);
2886
2887   pa_threaded_mainloop_unlock (mainloop);
2888
2889   return current_sink;
2890
2891   /* ERRORS */
2892 no_mainloop:
2893   {
2894     GST_DEBUG_OBJECT (pulsesink, "we have no mainloop");
2895     return NULL;
2896   }
2897 no_buffer:
2898   {
2899     GST_DEBUG_OBJECT (pulsesink, "we have no ringbuffer");
2900     return NULL;
2901   }
2902 info_failed:
2903   {
2904     GST_ELEMENT_ERROR (pulsesink, RESOURCE, FAILED,
2905         ("pa_context_get_sink_input_info() failed: %s",
2906             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2907     goto unlock;
2908   }
2909 }
2910
2911 static gchar *
2912 gst_pulsesink_device_description (GstPulseSink * psink)
2913 {
2914   GstPulseRingBuffer *pbuf;
2915   pa_operation *o = NULL;
2916   gchar *t;
2917
2918   if (!mainloop)
2919     goto no_mainloop;
2920
2921   pa_threaded_mainloop_lock (mainloop);
2922   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2923   if (pbuf == NULL)
2924     goto no_buffer;
2925
2926   free_device_info (&psink->device_info);
2927   if (!(o = pa_context_get_sink_info_by_name (pbuf->context,
2928               psink->device, gst_pulsesink_sink_info_cb, &psink->device_info)))
2929     goto info_failed;
2930
2931   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
2932     pa_threaded_mainloop_wait (mainloop);
2933     if (gst_pulsering_is_dead (psink, pbuf, FALSE))
2934       goto unlock;
2935   }
2936
2937 unlock:
2938   if (o)
2939     pa_operation_unref (o);
2940
2941   t = g_strdup (psink->device_info.description);
2942   pa_threaded_mainloop_unlock (mainloop);
2943
2944   return t;
2945
2946   /* ERRORS */
2947 no_mainloop:
2948   {
2949     GST_DEBUG_OBJECT (psink, "we have no mainloop");
2950     return NULL;
2951   }
2952 no_buffer:
2953   {
2954     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
2955     goto unlock;
2956   }
2957 info_failed:
2958   {
2959     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
2960         ("pa_context_get_sink_info_by_index() failed: %s",
2961             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
2962     goto unlock;
2963   }
2964 }
2965
2966 static void
2967 gst_pulsesink_set_stream_device (GstPulseSink * psink, const gchar * device)
2968 {
2969   pa_operation *o = NULL;
2970   GstPulseRingBuffer *pbuf;
2971   uint32_t idx;
2972
2973   if (!mainloop)
2974     goto no_mainloop;
2975
2976   pa_threaded_mainloop_lock (mainloop);
2977
2978   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
2979   if (pbuf == NULL || pbuf->stream == NULL)
2980     goto no_buffer;
2981
2982   if ((idx = pa_stream_get_index (pbuf->stream)) == PA_INVALID_INDEX)
2983     goto no_index;
2984
2985
2986   GST_DEBUG_OBJECT (psink, "setting stream device to %s", device);
2987
2988   if (!(o = pa_context_move_sink_input_by_name (pbuf->context, idx, device,
2989               NULL, NULL)))
2990     goto move_failed;
2991
2992 unlock:
2993
2994   if (o)
2995     pa_operation_unref (o);
2996
2997   pa_threaded_mainloop_unlock (mainloop);
2998
2999   return;
3000
3001   /* ERRORS */
3002 no_mainloop:
3003   {
3004     GST_DEBUG_OBJECT (psink, "we have no mainloop");
3005     return;
3006   }
3007 no_buffer:
3008   {
3009     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
3010     goto unlock;
3011   }
3012 no_index:
3013   {
3014     GST_DEBUG_OBJECT (psink, "we don't have a stream index");
3015     return;
3016   }
3017 move_failed:
3018   {
3019     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
3020         ("pa_context_move_sink_input_by_name(%s) failed: %s", device,
3021             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
3022     goto unlock;
3023   }
3024 }
3025
3026
3027 static void
3028 gst_pulsesink_set_property (GObject * object,
3029     guint prop_id, const GValue * value, GParamSpec * pspec)
3030 {
3031   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
3032
3033   switch (prop_id) {
3034     case PROP_SERVER:
3035       g_free (pulsesink->server);
3036       pulsesink->server = g_value_dup_string (value);
3037       break;
3038     case PROP_DEVICE:
3039       g_free (pulsesink->device);
3040       pulsesink->device = g_value_dup_string (value);
3041       gst_pulsesink_set_stream_device (pulsesink, pulsesink->device);
3042       break;
3043     case PROP_VOLUME:
3044       gst_pulsesink_set_volume (pulsesink, g_value_get_double (value));
3045       break;
3046     case PROP_MUTE:
3047       gst_pulsesink_set_mute (pulsesink, g_value_get_boolean (value));
3048       break;
3049     case PROP_CLIENT_NAME:
3050       g_free (pulsesink->client_name);
3051       if (!g_value_get_string (value)) {
3052         GST_WARNING_OBJECT (pulsesink,
3053             "Empty PulseAudio client name not allowed. Resetting to default value");
3054         pulsesink->client_name = gst_pulse_client_name ();
3055       } else
3056         pulsesink->client_name = g_value_dup_string (value);
3057       break;
3058     case PROP_STREAM_PROPERTIES:
3059       if (pulsesink->properties)
3060         gst_structure_free (pulsesink->properties);
3061       pulsesink->properties =
3062           gst_structure_copy (gst_value_get_structure (value));
3063       if (pulsesink->proplist)
3064         pa_proplist_free (pulsesink->proplist);
3065       pulsesink->proplist = gst_pulse_make_proplist (pulsesink->properties);
3066       break;
3067 #ifdef __TIZEN__
3068     case PROP_AUDIO_LATENCY:
3069       g_free (pulsesink->latency);
3070       pulsesink->latency = g_value_dup_string (value);
3071       /* setting NULL restores the default latency */
3072       if (pulsesink->latency == NULL) {
3073         pulsesink->latency = g_strdup (DEFAULT_AUDIO_LATENCY);
3074       }
3075       if (!pulsesink->proplist) {
3076         pulsesink->proplist = pa_proplist_new();
3077       }
3078       pa_proplist_sets(pulsesink->proplist, PA_PROP_MEDIA_TIZEN_AUDIO_LATENCY, pulsesink->latency);
3079       GST_DEBUG_OBJECT(pulsesink, "latency(%s)", pulsesink->latency);
3080       break;
3081 #endif /* __TIZEN__ */
3082     default:
3083       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3084       break;
3085   }
3086 }
3087
3088 static void
3089 gst_pulsesink_get_property (GObject * object,
3090     guint prop_id, GValue * value, GParamSpec * pspec)
3091 {
3092
3093   GstPulseSink *pulsesink = GST_PULSESINK_CAST (object);
3094
3095   switch (prop_id) {
3096     case PROP_SERVER:
3097       g_value_set_string (value, pulsesink->server);
3098       break;
3099     case PROP_DEVICE:
3100       g_value_set_string (value, pulsesink->device);
3101       break;
3102     case PROP_CURRENT_DEVICE:
3103     {
3104       gchar *current_device = gst_pulsesink_get_current_device (pulsesink);
3105       if (current_device)
3106         g_value_take_string (value, current_device);
3107       else
3108         g_value_set_string (value, "");
3109       break;
3110     }
3111     case PROP_DEVICE_NAME:
3112       g_value_take_string (value, gst_pulsesink_device_description (pulsesink));
3113       break;
3114     case PROP_VOLUME:
3115     {
3116 #ifndef __TIZEN__
3117       gdouble volume;
3118
3119       gst_pulsesink_get_sink_input_info (pulsesink, &volume, NULL);
3120       g_value_set_double (value, volume);
3121 #else
3122       g_value_set_double (value, pulsesink->volume);
3123 #endif
3124       break;
3125     }
3126     case PROP_MUTE:
3127     {
3128 #ifndef __TIZEN__
3129       gboolean mute;
3130
3131       gst_pulsesink_get_sink_input_info (pulsesink, NULL, &mute);
3132       g_value_set_boolean (value, mute);
3133 #else
3134       g_value_set_boolean (value, pulsesink->mute);
3135 #endif
3136       break;
3137     }
3138     case PROP_CLIENT_NAME:
3139       g_value_set_string (value, pulsesink->client_name);
3140       break;
3141     case PROP_STREAM_PROPERTIES:
3142       gst_value_set_structure (value, pulsesink->properties);
3143       break;
3144 #ifdef __TIZEN__
3145     case PROP_AUDIO_LATENCY:
3146       g_value_set_string (value, pulsesink->latency);
3147       break;
3148 #endif /* __TIZEN__ */
3149     default:
3150       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3151       break;
3152   }
3153 }
3154
3155 static void
3156 gst_pulsesink_change_title (GstPulseSink * psink, const gchar * t)
3157 {
3158   pa_operation *o = NULL;
3159   GstPulseRingBuffer *pbuf;
3160
3161   pa_threaded_mainloop_lock (mainloop);
3162
3163   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
3164
3165   if (pbuf == NULL || pbuf->stream == NULL)
3166     goto no_buffer;
3167
3168   g_free (pbuf->stream_name);
3169   pbuf->stream_name = g_strdup (t);
3170
3171   if (!(o = pa_stream_set_name (pbuf->stream, pbuf->stream_name, NULL, NULL)))
3172     goto name_failed;
3173
3174   /* We're not interested if this operation failed or not */
3175 unlock:
3176
3177   if (o)
3178     pa_operation_unref (o);
3179   pa_threaded_mainloop_unlock (mainloop);
3180
3181   return;
3182
3183   /* ERRORS */
3184 no_buffer:
3185   {
3186     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
3187     goto unlock;
3188   }
3189 name_failed:
3190   {
3191     GST_ELEMENT_ERROR (psink, RESOURCE, FAILED,
3192         ("pa_stream_set_name() failed: %s",
3193             pa_strerror (pa_context_errno (pbuf->context))), (NULL));
3194     goto unlock;
3195   }
3196 }
3197
3198 static void
3199 gst_pulsesink_change_props (GstPulseSink * psink, GstTagList * l)
3200 {
3201   static const gchar *const map[] = {
3202     GST_TAG_TITLE, PA_PROP_MEDIA_TITLE,
3203
3204     /* might get overriden in the next iteration by GST_TAG_ARTIST */
3205     GST_TAG_PERFORMER, PA_PROP_MEDIA_ARTIST,
3206
3207     GST_TAG_ARTIST, PA_PROP_MEDIA_ARTIST,
3208     GST_TAG_LANGUAGE_CODE, PA_PROP_MEDIA_LANGUAGE,
3209     GST_TAG_LOCATION, PA_PROP_MEDIA_FILENAME,
3210     /* We might add more here later on ... */
3211     NULL
3212   };
3213   pa_proplist *pl = NULL;
3214   const gchar *const *t;
3215   gboolean empty = TRUE;
3216   pa_operation *o = NULL;
3217   GstPulseRingBuffer *pbuf;
3218
3219   pl = pa_proplist_new ();
3220
3221   for (t = map; *t; t += 2) {
3222     gchar *n = NULL;
3223
3224     if (gst_tag_list_get_string (l, *t, &n)) {
3225
3226       if (n && *n) {
3227         pa_proplist_sets (pl, *(t + 1), n);
3228         empty = FALSE;
3229       }
3230
3231       g_free (n);
3232     }
3233   }
3234   if (empty)
3235     goto finish;
3236
3237   pa_threaded_mainloop_lock (mainloop);
3238   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
3239   if (pbuf == NULL || pbuf->stream == NULL)
3240     goto no_buffer;
3241
3242   /* We're not interested if this operation failed or not */
3243   if (!(o = pa_stream_proplist_update (pbuf->stream, PA_UPDATE_REPLACE,
3244               pl, NULL, NULL))) {
3245     GST_DEBUG_OBJECT (psink, "pa_stream_proplist_update() failed");
3246   }
3247
3248 unlock:
3249
3250   if (o)
3251     pa_operation_unref (o);
3252
3253   pa_threaded_mainloop_unlock (mainloop);
3254
3255 finish:
3256
3257   if (pl)
3258     pa_proplist_free (pl);
3259
3260   return;
3261
3262   /* ERRORS */
3263 no_buffer:
3264   {
3265     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
3266     goto unlock;
3267   }
3268 }
3269
3270 static void
3271 gst_pulsesink_flush_ringbuffer (GstPulseSink * psink)
3272 {
3273   GstPulseRingBuffer *pbuf;
3274
3275   pa_threaded_mainloop_lock (mainloop);
3276
3277   pbuf = GST_PULSERING_BUFFER_CAST (GST_AUDIO_BASE_SINK (psink)->ringbuffer);
3278
3279   if (pbuf == NULL || pbuf->stream == NULL)
3280     goto no_buffer;
3281
3282   gst_pulsering_flush (pbuf);
3283
3284   /* Uncork if we haven't already (happens when waiting to get enough data
3285    * to send out the first time) */
3286   if (pbuf->corked)
3287     gst_pulsering_set_corked (pbuf, FALSE, FALSE);
3288
3289   /* We're not interested if this operation failed or not */
3290 unlock:
3291   pa_threaded_mainloop_unlock (mainloop);
3292
3293   return;
3294
3295   /* ERRORS */
3296 no_buffer:
3297   {
3298     GST_DEBUG_OBJECT (psink, "we have no ringbuffer");
3299     goto unlock;
3300   }
3301 }
3302
3303 static gboolean
3304 gst_pulsesink_event (GstBaseSink * sink, GstEvent * event)
3305 {
3306   GstPulseSink *pulsesink = GST_PULSESINK_CAST (sink);
3307
3308   switch (GST_EVENT_TYPE (event)) {
3309     case GST_EVENT_TAG:{
3310       gchar *title = NULL, *artist = NULL, *location = NULL, *description =
3311           NULL, *t = NULL, *buf = NULL;
3312       GstTagList *l;
3313
3314       gst_event_parse_tag (event, &l);
3315
3316       gst_tag_list_get_string (l, GST_TAG_TITLE, &title);
3317       gst_tag_list_get_string (l, GST_TAG_ARTIST, &artist);
3318       gst_tag_list_get_string (l, GST_TAG_LOCATION, &location);
3319       gst_tag_list_get_string (l, GST_TAG_DESCRIPTION, &description);
3320
3321       if (!artist)
3322         gst_tag_list_get_string (l, GST_TAG_PERFORMER, &artist);
3323
3324       if (title && artist)
3325         /* TRANSLATORS: 'song title' by 'artist name' */
3326         t = buf = g_strdup_printf (_("'%s' by '%s'"), g_strstrip (title),
3327             g_strstrip (artist));
3328       else if (title)
3329         t = g_strstrip (title);
3330       else if (description)
3331         t = g_strstrip (description);
3332       else if (location)
3333         t = g_strstrip (location);
3334
3335       if (t)
3336         gst_pulsesink_change_title (pulsesink, t);
3337
3338       g_free (title);
3339       g_free (artist);
3340       g_free (location);
3341       g_free (description);
3342       g_free (buf);
3343
3344       gst_pulsesink_change_props (pulsesink, l);
3345
3346       break;
3347     }
3348     case GST_EVENT_GAP:{
3349       GstClockTime timestamp, duration;
3350
3351       gst_event_parse_gap (event, &timestamp, &duration);
3352       if (duration == GST_CLOCK_TIME_NONE)
3353         gst_pulsesink_flush_ringbuffer (pulsesink);
3354       break;
3355     }
3356     case GST_EVENT_EOS:
3357       gst_pulsesink_flush_ringbuffer (pulsesink);
3358       break;
3359     default:
3360       ;
3361   }
3362
3363   return GST_BASE_SINK_CLASS (parent_class)->event (sink, event);
3364 }
3365
3366 static gboolean
3367 gst_pulsesink_query (GstBaseSink * sink, GstQuery * query)
3368 {
3369   GstPulseSink *pulsesink = GST_PULSESINK_CAST (sink);
3370   gboolean ret = FALSE;
3371
3372   switch (GST_QUERY_TYPE (query)) {
3373     case GST_QUERY_CAPS:
3374     {
3375       GstCaps *caps, *filter;
3376
3377       gst_query_parse_caps (query, &filter);
3378       caps = gst_pulsesink_query_getcaps (pulsesink, filter);
3379
3380       if (caps) {
3381         gst_query_set_caps_result (query, caps);
3382         gst_caps_unref (caps);
3383         ret = TRUE;
3384       }
3385       break;
3386     }
3387     case GST_QUERY_ACCEPT_CAPS:
3388     {
3389       GstCaps *caps;
3390
3391       gst_query_parse_accept_caps (query, &caps);
3392       ret = gst_pulsesink_query_acceptcaps (pulsesink, caps);
3393       gst_query_set_accept_caps_result (query, ret);
3394       ret = TRUE;
3395       break;
3396     }
3397     default:
3398       ret = GST_BASE_SINK_CLASS (parent_class)->query (sink, query);
3399       break;
3400   }
3401   return ret;
3402 }
3403
3404 static void
3405 gst_pulsesink_release_mainloop (GstPulseSink * psink)
3406 {
3407   if (!mainloop)
3408     return;
3409
3410   pa_threaded_mainloop_lock (mainloop);
3411   while (psink->defer_pending) {
3412     GST_DEBUG_OBJECT (psink, "waiting for stream status message emission");
3413     pa_threaded_mainloop_wait (mainloop);
3414   }
3415   pa_threaded_mainloop_unlock (mainloop);
3416
3417   g_mutex_lock (&pa_shared_resource_mutex);
3418   mainloop_ref_ct--;
3419   if (!mainloop_ref_ct) {
3420     GST_INFO_OBJECT (psink, "terminating pa main loop thread");
3421     pa_threaded_mainloop_stop (mainloop);
3422     pa_threaded_mainloop_free (mainloop);
3423     mainloop = NULL;
3424   }
3425   g_mutex_unlock (&pa_shared_resource_mutex);
3426 }
3427
3428 static GstStateChangeReturn
3429 gst_pulsesink_change_state (GstElement * element, GstStateChange transition)
3430 {
3431   GstPulseSink *pulsesink = GST_PULSESINK (element);
3432   GstStateChangeReturn ret;
3433
3434   switch (transition) {
3435     case GST_STATE_CHANGE_NULL_TO_READY:
3436       g_mutex_lock (&pa_shared_resource_mutex);
3437       if (!mainloop_ref_ct) {
3438         GST_INFO_OBJECT (element, "new pa main loop thread");
3439         if (!(mainloop = pa_threaded_mainloop_new ()))
3440           goto mainloop_failed;
3441         if (pa_threaded_mainloop_start (mainloop) < 0) {
3442           pa_threaded_mainloop_free (mainloop);
3443           goto mainloop_start_failed;
3444         }
3445         mainloop_ref_ct = 1;
3446         g_mutex_unlock (&pa_shared_resource_mutex);
3447       } else {
3448         GST_INFO_OBJECT (element, "reusing pa main loop thread");
3449         mainloop_ref_ct++;
3450         g_mutex_unlock (&pa_shared_resource_mutex);
3451       }
3452       break;
3453     case GST_STATE_CHANGE_READY_TO_PAUSED:
3454       gst_element_post_message (element,
3455           gst_message_new_clock_provide (GST_OBJECT_CAST (element),
3456               GST_AUDIO_BASE_SINK (pulsesink)->provided_clock, TRUE));
3457       break;
3458
3459     default:
3460       break;
3461   }
3462
3463   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3464   if (ret == GST_STATE_CHANGE_FAILURE)
3465     goto state_failure;
3466
3467   switch (transition) {
3468     case GST_STATE_CHANGE_PAUSED_TO_READY:
3469       /* format_lost is reset in release() in audiobasesink */
3470       gst_element_post_message (element,
3471           gst_message_new_clock_lost (GST_OBJECT_CAST (element),
3472               GST_AUDIO_BASE_SINK (pulsesink)->provided_clock));
3473       break;
3474     case GST_STATE_CHANGE_READY_TO_NULL:
3475       gst_pulsesink_release_mainloop (pulsesink);
3476       break;
3477     default:
3478       break;
3479   }
3480
3481   return ret;
3482
3483   /* ERRORS */
3484 mainloop_failed:
3485   {
3486     g_mutex_unlock (&pa_shared_resource_mutex);
3487     GST_ELEMENT_ERROR (pulsesink, RESOURCE, FAILED,
3488         ("pa_threaded_mainloop_new() failed"), (NULL));
3489     return GST_STATE_CHANGE_FAILURE;
3490   }
3491 mainloop_start_failed:
3492   {
3493     g_mutex_unlock (&pa_shared_resource_mutex);
3494     GST_ELEMENT_ERROR (pulsesink, RESOURCE, FAILED,
3495         ("pa_threaded_mainloop_start() failed"), (NULL));
3496     return GST_STATE_CHANGE_FAILURE;
3497   }
3498 state_failure:
3499   {
3500     if (transition == GST_STATE_CHANGE_NULL_TO_READY) {
3501       /* Clear the PA mainloop if audiobasesink failed to open the ring_buffer */
3502       g_assert (mainloop);
3503       gst_pulsesink_release_mainloop (pulsesink);
3504     }
3505     return ret;
3506   }
3507 }