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