Move gtk plugin from -bad
[platform/upstream/gst-plugins-good.git] / ext / pulse / pulsesrc.c
1 /*
2  *  GStreamer pulseaudio plugin
3  *
4  *  Copyright (c) 2004-2008 Lennart Poettering
5  *
6  *  gst-pulse is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU Lesser General Public License as
8  *  published by the Free Software Foundation; either version 2.1 of the
9  *  License, or (at your option) any later version.
10  *
11  *  gst-pulse is distributed in the hope that it will be useful, but
12  *  WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  *  Lesser General Public License for more details.
15  *
16  *  You should have received a copy of the GNU Lesser General Public
17  *  License along with gst-pulse; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
19  *  USA.
20  */
21
22 /**
23  * SECTION:element-pulsesrc
24  * @see_also: pulsesink
25  *
26  * This element captures audio from a
27  * <ulink href="http://www.pulseaudio.org">PulseAudio sound server</ulink>.
28  *
29  * <refsect2>
30  * <title>Example pipelines</title>
31  * |[
32  * gst-launch-1.0 -v pulsesrc ! audioconvert ! vorbisenc ! oggmux ! filesink location=alsasrc.ogg
33  * ]| Record from a sound card using pulseaudio and encode to Ogg/Vorbis.
34  * </refsect2>
35  */
36
37 #ifdef HAVE_CONFIG_H
38 #include "config.h"
39 #endif
40
41 #include <string.h>
42 #include <stdio.h>
43
44 #include <gst/base/gstbasesrc.h>
45 #include <gst/gsttaglist.h>
46 #include <gst/audio/audio.h>
47
48 #include "pulsesrc.h"
49 #include "pulseutil.h"
50
51 GST_DEBUG_CATEGORY_EXTERN (pulse_debug);
52 #define GST_CAT_DEFAULT pulse_debug
53
54 #define DEFAULT_SERVER            NULL
55 #define DEFAULT_DEVICE            NULL
56 #define DEFAULT_CURRENT_DEVICE    NULL
57 #define DEFAULT_DEVICE_NAME       NULL
58
59 #define DEFAULT_VOLUME          1.0
60 #define DEFAULT_MUTE            FALSE
61 #define MAX_VOLUME              10.0
62
63 /* See the pulsesink code for notes on how we interact with the PA mainloop
64  * thread. */
65
66 enum
67 {
68   PROP_0,
69   PROP_SERVER,
70   PROP_DEVICE,
71   PROP_DEVICE_NAME,
72   PROP_CURRENT_DEVICE,
73   PROP_CLIENT_NAME,
74   PROP_STREAM_PROPERTIES,
75   PROP_SOURCE_OUTPUT_INDEX,
76   PROP_VOLUME,
77   PROP_MUTE,
78   PROP_LAST
79 };
80
81 static void gst_pulsesrc_destroy_stream (GstPulseSrc * pulsesrc);
82 static void gst_pulsesrc_destroy_context (GstPulseSrc * pulsesrc);
83
84 static void gst_pulsesrc_set_property (GObject * object, guint prop_id,
85     const GValue * value, GParamSpec * pspec);
86 static void gst_pulsesrc_get_property (GObject * object, guint prop_id,
87     GValue * value, GParamSpec * pspec);
88 static void gst_pulsesrc_finalize (GObject * object);
89
90 static gboolean gst_pulsesrc_set_corked (GstPulseSrc * psrc, gboolean corked,
91     gboolean wait);
92 static gboolean gst_pulsesrc_open (GstAudioSrc * asrc);
93
94 static gboolean gst_pulsesrc_close (GstAudioSrc * asrc);
95
96 static gboolean gst_pulsesrc_prepare (GstAudioSrc * asrc,
97     GstAudioRingBufferSpec * spec);
98
99 static gboolean gst_pulsesrc_unprepare (GstAudioSrc * asrc);
100
101 static guint gst_pulsesrc_read (GstAudioSrc * asrc, gpointer data,
102     guint length, GstClockTime * timestamp);
103 static guint gst_pulsesrc_delay (GstAudioSrc * asrc);
104
105 static void gst_pulsesrc_reset (GstAudioSrc * src);
106
107 static gboolean gst_pulsesrc_negotiate (GstBaseSrc * basesrc);
108 static gboolean gst_pulsesrc_event (GstBaseSrc * basesrc, GstEvent * event);
109
110 static GstStateChangeReturn gst_pulsesrc_change_state (GstElement *
111     element, GstStateChange transition);
112
113 static GstClockTime gst_pulsesrc_get_time (GstClock * clock, GstPulseSrc * src);
114
115 static GstStaticPadTemplate pad_template = GST_STATIC_PAD_TEMPLATE ("src",
116     GST_PAD_SRC,
117     GST_PAD_ALWAYS,
118     GST_STATIC_CAPS (_PULSE_CAPS_PCM)
119     );
120
121 #define gst_pulsesrc_parent_class parent_class
122 G_DEFINE_TYPE_WITH_CODE (GstPulseSrc, gst_pulsesrc, GST_TYPE_AUDIO_SRC,
123     G_IMPLEMENT_INTERFACE (GST_TYPE_STREAM_VOLUME, NULL));
124
125 static void
126 gst_pulsesrc_class_init (GstPulseSrcClass * klass)
127 {
128   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
129   GstAudioSrcClass *gstaudiosrc_class = GST_AUDIO_SRC_CLASS (klass);
130   GstBaseSrcClass *gstbasesrc_class = GST_BASE_SRC_CLASS (klass);
131   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
132   gchar *clientname;
133
134   gobject_class->finalize = gst_pulsesrc_finalize;
135   gobject_class->set_property = gst_pulsesrc_set_property;
136   gobject_class->get_property = gst_pulsesrc_get_property;
137
138   gstelement_class->change_state =
139       GST_DEBUG_FUNCPTR (gst_pulsesrc_change_state);
140
141   gstbasesrc_class->event = GST_DEBUG_FUNCPTR (gst_pulsesrc_event);
142   gstbasesrc_class->negotiate = GST_DEBUG_FUNCPTR (gst_pulsesrc_negotiate);
143
144   gstaudiosrc_class->open = GST_DEBUG_FUNCPTR (gst_pulsesrc_open);
145   gstaudiosrc_class->close = GST_DEBUG_FUNCPTR (gst_pulsesrc_close);
146   gstaudiosrc_class->prepare = GST_DEBUG_FUNCPTR (gst_pulsesrc_prepare);
147   gstaudiosrc_class->unprepare = GST_DEBUG_FUNCPTR (gst_pulsesrc_unprepare);
148   gstaudiosrc_class->read = GST_DEBUG_FUNCPTR (gst_pulsesrc_read);
149   gstaudiosrc_class->delay = GST_DEBUG_FUNCPTR (gst_pulsesrc_delay);
150   gstaudiosrc_class->reset = GST_DEBUG_FUNCPTR (gst_pulsesrc_reset);
151
152   /* Overwrite GObject fields */
153   g_object_class_install_property (gobject_class,
154       PROP_SERVER,
155       g_param_spec_string ("server", "Server",
156           "The PulseAudio server to connect to", DEFAULT_SERVER,
157           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
158
159   g_object_class_install_property (gobject_class, PROP_DEVICE,
160       g_param_spec_string ("device", "Device",
161           "The PulseAudio source device to connect to", DEFAULT_DEVICE,
162           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
163
164   g_object_class_install_property (gobject_class, PROP_CURRENT_DEVICE,
165       g_param_spec_string ("current-device", "Current Device",
166           "The current PulseAudio source device", DEFAULT_CURRENT_DEVICE,
167           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
168
169   g_object_class_install_property (gobject_class,
170       PROP_DEVICE_NAME,
171       g_param_spec_string ("device-name", "Device name",
172           "Human-readable name of the sound device", DEFAULT_DEVICE_NAME,
173           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
174
175   clientname = gst_pulse_client_name ();
176   /**
177    * GstPulseSrc:client-name
178    *
179    * The PulseAudio client name to use.
180    */
181   g_object_class_install_property (gobject_class,
182       PROP_CLIENT_NAME,
183       g_param_spec_string ("client-name", "Client Name",
184           "The PulseAudio client_name_to_use", clientname,
185           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
186           GST_PARAM_MUTABLE_READY));
187   g_free (clientname);
188
189   /**
190    * GstPulseSrc:stream-properties:
191    *
192    * List of pulseaudio stream properties. A list of defined properties can be
193    * found in the <ulink href="http://0pointer.de/lennart/projects/pulseaudio/doxygen/proplist_8h.html">pulseaudio api docs</ulink>.
194    *
195    * Below is an example for registering as a music application to pulseaudio.
196    * |[
197    * GstStructure *props;
198    *
199    * props = gst_structure_from_string ("props,media.role=music", NULL);
200    * g_object_set (pulse, "stream-properties", props, NULL);
201    * gst_structure_free (props);
202    * ]|
203    */
204   g_object_class_install_property (gobject_class,
205       PROP_STREAM_PROPERTIES,
206       g_param_spec_boxed ("stream-properties", "stream properties",
207           "list of pulseaudio stream properties",
208           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
209   /**
210    * GstPulseSrc:source-output-index:
211    *
212    * The index of the PulseAudio source output corresponding to this element.
213    */
214   g_object_class_install_property (gobject_class,
215       PROP_SOURCE_OUTPUT_INDEX,
216       g_param_spec_uint ("source-output-index", "source output index",
217           "The index of the PulseAudio source output corresponding to this "
218           "record stream", 0, G_MAXUINT, PA_INVALID_INDEX,
219           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
220
221   gst_element_class_set_static_metadata (gstelement_class,
222       "PulseAudio Audio Source",
223       "Source/Audio",
224       "Captures audio from a PulseAudio server", "Lennart Poettering");
225   gst_element_class_add_static_pad_template (gstelement_class, &pad_template);
226
227   /**
228    * GstPulseSrc:volume:
229    *
230    * The volume of the record stream.
231    */
232   g_object_class_install_property (gobject_class,
233       PROP_VOLUME, g_param_spec_double ("volume", "Volume",
234           "Linear volume of this stream, 1.0=100%",
235           0.0, MAX_VOLUME, DEFAULT_VOLUME,
236           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
237
238   /**
239    * GstPulseSrc:mute:
240    *
241    * Whether the stream is muted or not.
242    */
243   g_object_class_install_property (gobject_class,
244       PROP_MUTE, g_param_spec_boolean ("mute", "Mute",
245           "Mute state of this stream",
246           DEFAULT_MUTE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
247 }
248
249 static void
250 gst_pulsesrc_init (GstPulseSrc * pulsesrc)
251 {
252   pulsesrc->server = NULL;
253   pulsesrc->device = NULL;
254   pulsesrc->client_name = gst_pulse_client_name ();
255   pulsesrc->device_description = NULL;
256
257   pulsesrc->context = NULL;
258   pulsesrc->stream = NULL;
259   pulsesrc->stream_connected = FALSE;
260   pulsesrc->source_output_idx = PA_INVALID_INDEX;
261
262   pulsesrc->read_buffer = NULL;
263   pulsesrc->read_buffer_length = 0;
264
265   pa_sample_spec_init (&pulsesrc->sample_spec);
266
267   pulsesrc->operation_success = FALSE;
268   pulsesrc->paused = TRUE;
269   pulsesrc->in_read = FALSE;
270
271   pulsesrc->volume = DEFAULT_VOLUME;
272   pulsesrc->volume_set = FALSE;
273
274   pulsesrc->mute = DEFAULT_MUTE;
275   pulsesrc->mute_set = FALSE;
276
277   pulsesrc->notify = 0;
278
279   pulsesrc->properties = NULL;
280   pulsesrc->proplist = NULL;
281
282   /* this should be the default but it isn't yet */
283   gst_audio_base_src_set_slave_method (GST_AUDIO_BASE_SRC (pulsesrc),
284       GST_AUDIO_BASE_SRC_SLAVE_SKEW);
285
286   /* override with a custom clock */
287   if (GST_AUDIO_BASE_SRC (pulsesrc)->clock)
288     gst_object_unref (GST_AUDIO_BASE_SRC (pulsesrc)->clock);
289
290   GST_AUDIO_BASE_SRC (pulsesrc)->clock =
291       gst_audio_clock_new ("GstPulseSrcClock",
292       (GstAudioClockGetTimeFunc) gst_pulsesrc_get_time, pulsesrc, NULL);
293 }
294
295 static void
296 gst_pulsesrc_destroy_stream (GstPulseSrc * pulsesrc)
297 {
298   if (pulsesrc->stream) {
299     pa_stream_disconnect (pulsesrc->stream);
300     pa_stream_unref (pulsesrc->stream);
301     pulsesrc->stream = NULL;
302     pulsesrc->stream_connected = FALSE;
303     pulsesrc->source_output_idx = PA_INVALID_INDEX;
304     g_object_notify (G_OBJECT (pulsesrc), "source-output-index");
305   }
306
307   g_free (pulsesrc->device_description);
308   pulsesrc->device_description = NULL;
309 }
310
311 static void
312 gst_pulsesrc_destroy_context (GstPulseSrc * pulsesrc)
313 {
314
315   gst_pulsesrc_destroy_stream (pulsesrc);
316
317   if (pulsesrc->context) {
318     pa_context_disconnect (pulsesrc->context);
319
320     /* Make sure we don't get any further callbacks */
321     pa_context_set_state_callback (pulsesrc->context, NULL, NULL);
322     pa_context_set_subscribe_callback (pulsesrc->context, NULL, NULL);
323
324     pa_context_unref (pulsesrc->context);
325
326     pulsesrc->context = NULL;
327   }
328 }
329
330 static void
331 gst_pulsesrc_finalize (GObject * object)
332 {
333   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (object);
334
335   g_free (pulsesrc->server);
336   g_free (pulsesrc->device);
337   g_free (pulsesrc->client_name);
338   g_free (pulsesrc->current_source_name);
339
340   if (pulsesrc->properties)
341     gst_structure_free (pulsesrc->properties);
342   if (pulsesrc->proplist)
343     pa_proplist_free (pulsesrc->proplist);
344
345   G_OBJECT_CLASS (parent_class)->finalize (object);
346 }
347
348 #define CONTEXT_OK(c) ((c) && PA_CONTEXT_IS_GOOD (pa_context_get_state ((c))))
349 #define STREAM_OK(s) ((s) && PA_STREAM_IS_GOOD (pa_stream_get_state ((s))))
350
351 static gboolean
352 gst_pulsesrc_is_dead (GstPulseSrc * pulsesrc, gboolean check_stream)
353 {
354   if (!pulsesrc->stream_connected)
355     return TRUE;
356
357   if (!CONTEXT_OK (pulsesrc->context))
358     goto error;
359
360   if (check_stream && !STREAM_OK (pulsesrc->stream))
361     goto error;
362
363   return FALSE;
364
365 error:
366   {
367     const gchar *err_str = pulsesrc->context ?
368         pa_strerror (pa_context_errno (pulsesrc->context)) : NULL;
369     GST_ELEMENT_ERROR ((pulsesrc), RESOURCE, FAILED, ("Disconnected: %s",
370             err_str), (NULL));
371     return TRUE;
372   }
373 }
374
375 static void
376 gst_pulsesrc_source_info_cb (pa_context * c, const pa_source_info * i, int eol,
377     void *userdata)
378 {
379   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (userdata);
380
381   if (!i)
382     goto done;
383
384   g_free (pulsesrc->device_description);
385   pulsesrc->device_description = g_strdup (i->description);
386
387 done:
388   pa_threaded_mainloop_signal (pulsesrc->mainloop, 0);
389 }
390
391 static gchar *
392 gst_pulsesrc_device_description (GstPulseSrc * pulsesrc)
393 {
394   pa_operation *o = NULL;
395   gchar *t;
396
397   if (!pulsesrc->mainloop)
398     goto no_mainloop;
399
400   pa_threaded_mainloop_lock (pulsesrc->mainloop);
401
402   if (!(o = pa_context_get_source_info_by_name (pulsesrc->context,
403               pulsesrc->device, gst_pulsesrc_source_info_cb, pulsesrc))) {
404
405     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
406         ("pa_stream_get_source_info() failed: %s",
407             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
408     goto unlock;
409   }
410
411   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
412
413     if (gst_pulsesrc_is_dead (pulsesrc, FALSE))
414       goto unlock;
415
416     pa_threaded_mainloop_wait (pulsesrc->mainloop);
417   }
418
419 unlock:
420
421   if (o)
422     pa_operation_unref (o);
423
424   t = g_strdup (pulsesrc->device_description);
425
426   pa_threaded_mainloop_unlock (pulsesrc->mainloop);
427
428   return t;
429
430 no_mainloop:
431   {
432     GST_DEBUG_OBJECT (pulsesrc, "have no mainloop");
433     return NULL;
434   }
435 }
436
437 static void
438 gst_pulsesrc_source_output_info_cb (pa_context * c,
439     const pa_source_output_info * i, int eol, void *userdata)
440 {
441   GstPulseSrc *psrc;
442
443   psrc = GST_PULSESRC_CAST (userdata);
444
445   if (!i)
446     goto done;
447
448   /* If the index doesn't match our current stream,
449    * it implies we just recreated the stream (caps change)
450    */
451   if (i->index == psrc->source_output_idx) {
452     psrc->volume = pa_sw_volume_to_linear (pa_cvolume_max (&i->volume));
453     psrc->mute = i->mute;
454     psrc->current_source_idx = i->source;
455
456     if (G_UNLIKELY (psrc->volume > MAX_VOLUME)) {
457       GST_WARNING_OBJECT (psrc, "Clipped volume from %f to %f",
458           psrc->volume, MAX_VOLUME);
459       psrc->volume = MAX_VOLUME;
460     }
461   }
462
463 done:
464   pa_threaded_mainloop_signal (psrc->mainloop, 0);
465 }
466
467 static void
468 gst_pulsesrc_get_source_output_info (GstPulseSrc * pulsesrc, gdouble * volume,
469     gboolean * mute)
470 {
471   pa_operation *o = NULL;
472
473   if (!pulsesrc->mainloop)
474     goto no_mainloop;
475
476   if (pulsesrc->source_output_idx == PA_INVALID_INDEX)
477     goto no_index;
478
479   pa_threaded_mainloop_lock (pulsesrc->mainloop);
480
481   if (!(o = pa_context_get_source_output_info (pulsesrc->context,
482               pulsesrc->source_output_idx, gst_pulsesrc_source_output_info_cb,
483               pulsesrc)))
484     goto info_failed;
485
486   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
487     pa_threaded_mainloop_wait (pulsesrc->mainloop);
488     if (gst_pulsesrc_is_dead (pulsesrc, TRUE))
489       goto unlock;
490   }
491
492 unlock:
493
494   if (volume)
495     *volume = pulsesrc->volume;
496   if (mute)
497     *mute = pulsesrc->mute;
498
499   if (o)
500     pa_operation_unref (o);
501
502   pa_threaded_mainloop_unlock (pulsesrc->mainloop);
503
504   return;
505
506   /* ERRORS */
507 no_mainloop:
508   {
509     GST_DEBUG_OBJECT (pulsesrc, "we have no mainloop");
510     if (volume)
511       *volume = pulsesrc->volume;
512     if (mute)
513       *mute = pulsesrc->mute;
514     return;
515   }
516 no_index:
517   {
518     GST_DEBUG_OBJECT (pulsesrc, "we don't have a stream index");
519     if (volume)
520       *volume = pulsesrc->volume;
521     if (mute)
522       *mute = pulsesrc->mute;
523     return;
524   }
525 info_failed:
526   {
527     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
528         ("pa_context_get_source_output_info() failed: %s",
529             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
530     goto unlock;
531   }
532 }
533
534 static void
535 gst_pulsesrc_current_source_info_cb (pa_context * c, const pa_source_info * i,
536     int eol, void *userdata)
537 {
538   GstPulseSrc *psrc;
539
540   psrc = GST_PULSESRC_CAST (userdata);
541
542   if (!i)
543     goto done;
544
545   /* If the index doesn't match our current stream,
546    * it implies we just recreated the stream (caps change)
547    */
548   if (i->index == psrc->current_source_idx) {
549     g_free (psrc->current_source_name);
550     psrc->current_source_name = g_strdup (i->name);
551   }
552
553 done:
554   pa_threaded_mainloop_signal (psrc->mainloop, 0);
555 }
556
557 static gchar *
558 gst_pulsesrc_get_current_device (GstPulseSrc * pulsesrc)
559 {
560   pa_operation *o = NULL;
561   gchar *current_src;
562
563   if (!pulsesrc->mainloop)
564     goto no_mainloop;
565
566   if (pulsesrc->source_output_idx == PA_INVALID_INDEX)
567     goto no_index;
568
569   gst_pulsesrc_get_source_output_info (pulsesrc, NULL, NULL);
570
571   pa_threaded_mainloop_lock (pulsesrc->mainloop);
572
573
574   if (!(o = pa_context_get_source_info_by_index (pulsesrc->context,
575               pulsesrc->current_source_idx, gst_pulsesrc_current_source_info_cb,
576               pulsesrc)))
577     goto info_failed;
578
579   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
580     pa_threaded_mainloop_wait (pulsesrc->mainloop);
581     if (gst_pulsesrc_is_dead (pulsesrc, TRUE))
582       goto unlock;
583   }
584
585 unlock:
586
587   current_src = g_strdup (pulsesrc->current_source_name);
588
589   if (o)
590     pa_operation_unref (o);
591
592   pa_threaded_mainloop_unlock (pulsesrc->mainloop);
593
594   return current_src;
595
596   /* ERRORS */
597 no_mainloop:
598   {
599     GST_DEBUG_OBJECT (pulsesrc, "we have no mainloop");
600     return NULL;
601   }
602 no_index:
603   {
604     GST_DEBUG_OBJECT (pulsesrc, "we don't have a stream index");
605     return NULL;
606   }
607 info_failed:
608   {
609     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
610         ("pa_context_get_source_output_info() failed: %s",
611             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
612     goto unlock;
613   }
614 }
615
616 static void
617 gst_pulsesrc_set_stream_volume (GstPulseSrc * pulsesrc, gdouble volume)
618 {
619   pa_cvolume v;
620   pa_operation *o = NULL;
621
622   if (!pulsesrc->mainloop)
623     goto no_mainloop;
624
625   if (!pulsesrc->source_output_idx)
626     goto no_index;
627
628   pa_threaded_mainloop_lock (pulsesrc->mainloop);
629
630   GST_DEBUG_OBJECT (pulsesrc, "setting volume to %f", volume);
631
632   gst_pulse_cvolume_from_linear (&v, pulsesrc->sample_spec.channels, volume);
633
634   if (!(o = pa_context_set_source_output_volume (pulsesrc->context,
635               pulsesrc->source_output_idx, &v, NULL, NULL)))
636     goto volume_failed;
637
638   /* We don't really care about the result of this call */
639 unlock:
640
641   if (o)
642     pa_operation_unref (o);
643
644   pa_threaded_mainloop_unlock (pulsesrc->mainloop);
645
646   return;
647
648   /* ERRORS */
649 no_mainloop:
650   {
651     pulsesrc->volume = volume;
652     pulsesrc->volume_set = TRUE;
653     GST_DEBUG_OBJECT (pulsesrc, "we have no mainloop");
654     return;
655   }
656 no_index:
657   {
658     pulsesrc->volume = volume;
659     pulsesrc->volume_set = TRUE;
660     GST_DEBUG_OBJECT (pulsesrc, "we don't have a stream index");
661     return;
662   }
663 volume_failed:
664   {
665     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
666         ("pa_stream_set_source_output_volume() failed: %s",
667             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
668     goto unlock;
669   }
670 }
671
672 static void
673 gst_pulsesrc_set_stream_mute (GstPulseSrc * pulsesrc, gboolean mute)
674 {
675   pa_operation *o = NULL;
676
677   if (!pulsesrc->mainloop)
678     goto no_mainloop;
679
680   if (!pulsesrc->source_output_idx)
681     goto no_index;
682
683   pa_threaded_mainloop_lock (pulsesrc->mainloop);
684
685   GST_DEBUG_OBJECT (pulsesrc, "setting mute state to %d", mute);
686
687   if (!(o = pa_context_set_source_output_mute (pulsesrc->context,
688               pulsesrc->source_output_idx, mute, NULL, NULL)))
689     goto mute_failed;
690
691   /* We don't really care about the result of this call */
692 unlock:
693
694   if (o)
695     pa_operation_unref (o);
696
697   pa_threaded_mainloop_unlock (pulsesrc->mainloop);
698
699   return;
700
701   /* ERRORS */
702 no_mainloop:
703   {
704     pulsesrc->mute = mute;
705     pulsesrc->mute_set = TRUE;
706     GST_DEBUG_OBJECT (pulsesrc, "we have no mainloop");
707     return;
708   }
709 no_index:
710   {
711     pulsesrc->mute = mute;
712     pulsesrc->mute_set = TRUE;
713     GST_DEBUG_OBJECT (pulsesrc, "we don't have a stream index");
714     return;
715   }
716 mute_failed:
717   {
718     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
719         ("pa_stream_set_source_output_mute() failed: %s",
720             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
721     goto unlock;
722   }
723 }
724
725 static void
726 gst_pulsesrc_set_stream_device (GstPulseSrc * pulsesrc, const gchar * device)
727 {
728   pa_operation *o = NULL;
729
730   if (!pulsesrc->mainloop)
731     goto no_mainloop;
732
733   if (!pulsesrc->source_output_idx)
734     goto no_index;
735
736   pa_threaded_mainloop_lock (pulsesrc->mainloop);
737
738   GST_DEBUG_OBJECT (pulsesrc, "setting stream device to %s", device);
739
740   if (!(o = pa_context_move_source_output_by_name (pulsesrc->context,
741               pulsesrc->source_output_idx, device, NULL, NULL)))
742     goto move_failed;
743
744 unlock:
745
746   if (o)
747     pa_operation_unref (o);
748
749   pa_threaded_mainloop_unlock (pulsesrc->mainloop);
750
751   return;
752
753   /* ERRORS */
754 no_mainloop:
755   {
756     GST_DEBUG_OBJECT (pulsesrc, "we have no mainloop");
757     return;
758   }
759 no_index:
760   {
761     GST_DEBUG_OBJECT (pulsesrc, "we don't have a stream index");
762     return;
763   }
764 move_failed:
765   {
766     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
767         ("pa_context_move_source_output_by_name(%s) failed: %s",
768             device, pa_strerror (pa_context_errno (pulsesrc->context))),
769         (NULL));
770     goto unlock;
771   }
772 }
773
774 static void
775 gst_pulsesrc_set_property (GObject * object,
776     guint prop_id, const GValue * value, GParamSpec * pspec)
777 {
778
779   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (object);
780
781   switch (prop_id) {
782     case PROP_SERVER:
783       g_free (pulsesrc->server);
784       pulsesrc->server = g_value_dup_string (value);
785       break;
786     case PROP_DEVICE:
787       g_free (pulsesrc->device);
788       pulsesrc->device = g_value_dup_string (value);
789       gst_pulsesrc_set_stream_device (pulsesrc, pulsesrc->device);
790       break;
791     case PROP_CLIENT_NAME:
792       g_free (pulsesrc->client_name);
793       if (!g_value_get_string (value)) {
794         GST_WARNING_OBJECT (pulsesrc,
795             "Empty PulseAudio client name not allowed. Resetting to default value");
796         pulsesrc->client_name = gst_pulse_client_name ();
797       } else
798         pulsesrc->client_name = g_value_dup_string (value);
799       break;
800     case PROP_STREAM_PROPERTIES:
801       if (pulsesrc->properties)
802         gst_structure_free (pulsesrc->properties);
803       pulsesrc->properties =
804           gst_structure_copy (gst_value_get_structure (value));
805       if (pulsesrc->proplist)
806         pa_proplist_free (pulsesrc->proplist);
807       pulsesrc->proplist = gst_pulse_make_proplist (pulsesrc->properties);
808       break;
809     case PROP_VOLUME:
810       gst_pulsesrc_set_stream_volume (pulsesrc, g_value_get_double (value));
811       break;
812     case PROP_MUTE:
813       gst_pulsesrc_set_stream_mute (pulsesrc, g_value_get_boolean (value));
814       break;
815     default:
816       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
817       break;
818   }
819 }
820
821 static void
822 gst_pulsesrc_get_property (GObject * object,
823     guint prop_id, GValue * value, GParamSpec * pspec)
824 {
825
826   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (object);
827
828   switch (prop_id) {
829     case PROP_SERVER:
830       g_value_set_string (value, pulsesrc->server);
831       break;
832     case PROP_DEVICE:
833       g_value_set_string (value, pulsesrc->device);
834       break;
835     case PROP_CURRENT_DEVICE:
836     {
837       gchar *current_device = gst_pulsesrc_get_current_device (pulsesrc);
838       if (current_device)
839         g_value_take_string (value, current_device);
840       else
841         g_value_set_string (value, "");
842       break;
843     }
844     case PROP_DEVICE_NAME:
845       g_value_take_string (value, gst_pulsesrc_device_description (pulsesrc));
846       break;
847     case PROP_CLIENT_NAME:
848       g_value_set_string (value, pulsesrc->client_name);
849       break;
850     case PROP_STREAM_PROPERTIES:
851       gst_value_set_structure (value, pulsesrc->properties);
852       break;
853     case PROP_SOURCE_OUTPUT_INDEX:
854       g_value_set_uint (value, pulsesrc->source_output_idx);
855       break;
856     case PROP_VOLUME:
857     {
858       gdouble volume;
859       gst_pulsesrc_get_source_output_info (pulsesrc, &volume, NULL);
860       g_value_set_double (value, volume);
861       break;
862     }
863     case PROP_MUTE:
864     {
865       gboolean mute;
866       gst_pulsesrc_get_source_output_info (pulsesrc, NULL, &mute);
867       g_value_set_boolean (value, mute);
868       break;
869     }
870     default:
871       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
872       break;
873   }
874 }
875
876 static void
877 gst_pulsesrc_context_state_cb (pa_context * c, void *userdata)
878 {
879   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (userdata);
880
881   switch (pa_context_get_state (c)) {
882     case PA_CONTEXT_READY:
883     case PA_CONTEXT_TERMINATED:
884     case PA_CONTEXT_FAILED:
885       pa_threaded_mainloop_signal (pulsesrc->mainloop, 0);
886       break;
887
888     case PA_CONTEXT_UNCONNECTED:
889     case PA_CONTEXT_CONNECTING:
890     case PA_CONTEXT_AUTHORIZING:
891     case PA_CONTEXT_SETTING_NAME:
892       break;
893   }
894 }
895
896 static void
897 gst_pulsesrc_stream_state_cb (pa_stream * s, void *userdata)
898 {
899   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (userdata);
900
901   switch (pa_stream_get_state (s)) {
902
903     case PA_STREAM_READY:
904     case PA_STREAM_FAILED:
905     case PA_STREAM_TERMINATED:
906       pa_threaded_mainloop_signal (pulsesrc->mainloop, 0);
907       break;
908
909     case PA_STREAM_UNCONNECTED:
910     case PA_STREAM_CREATING:
911       break;
912   }
913 }
914
915 static void
916 gst_pulsesrc_stream_request_cb (pa_stream * s, size_t length, void *userdata)
917 {
918   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (userdata);
919
920   GST_LOG_OBJECT (pulsesrc, "got request for length %" G_GSIZE_FORMAT, length);
921
922   if (pulsesrc->in_read) {
923     /* only signal when reading */
924     pa_threaded_mainloop_signal (pulsesrc->mainloop, 0);
925   }
926 }
927
928 static void
929 gst_pulsesrc_stream_latency_update_cb (pa_stream * s, void *userdata)
930 {
931   const pa_timing_info *info;
932   pa_usec_t source_usec;
933
934   info = pa_stream_get_timing_info (s);
935
936   if (!info) {
937     GST_LOG_OBJECT (GST_PULSESRC_CAST (userdata),
938         "latency update (information unknown)");
939     return;
940   }
941   source_usec = info->configured_source_usec;
942
943   GST_LOG_OBJECT (GST_PULSESRC_CAST (userdata),
944       "latency_update, %" G_GUINT64_FORMAT ", %d:%" G_GINT64_FORMAT ", %d:%"
945       G_GUINT64_FORMAT ", %" G_GUINT64_FORMAT ", %" G_GUINT64_FORMAT,
946       GST_TIMEVAL_TO_TIME (info->timestamp), info->write_index_corrupt,
947       info->write_index, info->read_index_corrupt, info->read_index,
948       info->source_usec, source_usec);
949 }
950
951 static void
952 gst_pulsesrc_stream_underflow_cb (pa_stream * s, void *userdata)
953 {
954   GST_WARNING_OBJECT (GST_PULSESRC_CAST (userdata), "Got underflow");
955 }
956
957 static void
958 gst_pulsesrc_stream_overflow_cb (pa_stream * s, void *userdata)
959 {
960   GST_WARNING_OBJECT (GST_PULSESRC_CAST (userdata), "Got overflow");
961 }
962
963 static void
964 gst_pulsesrc_context_subscribe_cb (pa_context * c,
965     pa_subscription_event_type_t t, uint32_t idx, void *userdata)
966 {
967   GstPulseSrc *psrc = GST_PULSESRC (userdata);
968
969   if (t != (PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT | PA_SUBSCRIPTION_EVENT_CHANGE)
970       && t != (PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT | PA_SUBSCRIPTION_EVENT_NEW))
971     return;
972
973   if (idx != psrc->source_output_idx)
974     return;
975
976   /* Actually this event is also triggered when other properties of the stream
977    * change that are unrelated to the volume. However it is probably cheaper to
978    * signal the change here and check for the volume when the GObject property
979    * is read instead of querying it always. */
980
981   /* inform streaming thread to notify */
982   g_atomic_int_compare_and_exchange (&psrc->notify, 0, 1);
983 }
984
985 static gboolean
986 gst_pulsesrc_open (GstAudioSrc * asrc)
987 {
988   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (asrc);
989
990   pa_threaded_mainloop_lock (pulsesrc->mainloop);
991
992   g_assert (!pulsesrc->context);
993   g_assert (!pulsesrc->stream);
994
995   GST_DEBUG_OBJECT (pulsesrc, "opening device");
996
997   if (!(pulsesrc->context =
998           pa_context_new (pa_threaded_mainloop_get_api (pulsesrc->mainloop),
999               pulsesrc->client_name))) {
1000     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED, ("Failed to create context"),
1001         (NULL));
1002     goto unlock_and_fail;
1003   }
1004
1005   pa_context_set_state_callback (pulsesrc->context,
1006       gst_pulsesrc_context_state_cb, pulsesrc);
1007   pa_context_set_subscribe_callback (pulsesrc->context,
1008       gst_pulsesrc_context_subscribe_cb, pulsesrc);
1009
1010   GST_DEBUG_OBJECT (pulsesrc, "connect to server %s",
1011       GST_STR_NULL (pulsesrc->server));
1012
1013   if (pa_context_connect (pulsesrc->context, pulsesrc->server, 0, NULL) < 0) {
1014     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED, ("Failed to connect: %s",
1015             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
1016     goto unlock_and_fail;
1017   }
1018
1019   for (;;) {
1020     pa_context_state_t state;
1021
1022     state = pa_context_get_state (pulsesrc->context);
1023
1024     if (!PA_CONTEXT_IS_GOOD (state)) {
1025       GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED, ("Failed to connect: %s",
1026               pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
1027       goto unlock_and_fail;
1028     }
1029
1030     if (state == PA_CONTEXT_READY)
1031       break;
1032
1033     /* Wait until the context is ready */
1034     pa_threaded_mainloop_wait (pulsesrc->mainloop);
1035   }
1036   GST_DEBUG_OBJECT (pulsesrc, "connected");
1037
1038   pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1039
1040   return TRUE;
1041
1042   /* ERRORS */
1043 unlock_and_fail:
1044   {
1045     gst_pulsesrc_destroy_context (pulsesrc);
1046
1047     pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1048
1049     return FALSE;
1050   }
1051 }
1052
1053 static gboolean
1054 gst_pulsesrc_close (GstAudioSrc * asrc)
1055 {
1056   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (asrc);
1057
1058   pa_threaded_mainloop_lock (pulsesrc->mainloop);
1059   gst_pulsesrc_destroy_context (pulsesrc);
1060   pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1061
1062   return TRUE;
1063 }
1064
1065 static gboolean
1066 gst_pulsesrc_unprepare (GstAudioSrc * asrc)
1067 {
1068   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (asrc);
1069
1070   pa_threaded_mainloop_lock (pulsesrc->mainloop);
1071   gst_pulsesrc_destroy_stream (pulsesrc);
1072
1073   pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1074
1075   pulsesrc->read_buffer = NULL;
1076   pulsesrc->read_buffer_length = 0;
1077
1078   return TRUE;
1079 }
1080
1081 static guint
1082 gst_pulsesrc_read (GstAudioSrc * asrc, gpointer data, guint length,
1083     GstClockTime * timestamp)
1084 {
1085   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (asrc);
1086   size_t sum = 0;
1087
1088   if (g_atomic_int_compare_and_exchange (&pulsesrc->notify, 1, 0)) {
1089     g_object_notify (G_OBJECT (pulsesrc), "volume");
1090     g_object_notify (G_OBJECT (pulsesrc), "mute");
1091     g_object_notify (G_OBJECT (pulsesrc), "current-device");
1092   }
1093
1094   pa_threaded_mainloop_lock (pulsesrc->mainloop);
1095   pulsesrc->in_read = TRUE;
1096
1097   if (!pulsesrc->stream_connected)
1098     goto not_connected;
1099
1100   if (pulsesrc->paused)
1101     goto was_paused;
1102
1103   while (length > 0) {
1104     size_t l;
1105
1106     GST_LOG_OBJECT (pulsesrc, "reading %u bytes", length);
1107
1108     /*check if we have a leftover buffer */
1109     if (!pulsesrc->read_buffer) {
1110       for (;;) {
1111         if (gst_pulsesrc_is_dead (pulsesrc, TRUE))
1112           goto unlock_and_fail;
1113
1114         /* read all available data, we keep a pointer to the data and the length
1115          * and take from it what we need. */
1116         if (pa_stream_peek (pulsesrc->stream, &pulsesrc->read_buffer,
1117                 &pulsesrc->read_buffer_length) < 0)
1118           goto peek_failed;
1119
1120         GST_LOG_OBJECT (pulsesrc, "have data of %" G_GSIZE_FORMAT " bytes",
1121             pulsesrc->read_buffer_length);
1122
1123         /* if we have data, process if */
1124         if (pulsesrc->read_buffer && pulsesrc->read_buffer_length)
1125           break;
1126
1127         /* now wait for more data to become available */
1128         GST_LOG_OBJECT (pulsesrc, "waiting for data");
1129         pa_threaded_mainloop_wait (pulsesrc->mainloop);
1130
1131         if (pulsesrc->paused)
1132           goto was_paused;
1133       }
1134     }
1135
1136     l = pulsesrc->read_buffer_length >
1137         length ? length : pulsesrc->read_buffer_length;
1138
1139     memcpy (data, pulsesrc->read_buffer, l);
1140
1141     pulsesrc->read_buffer = (const guint8 *) pulsesrc->read_buffer + l;
1142     pulsesrc->read_buffer_length -= l;
1143
1144     data = (guint8 *) data + l;
1145     length -= l;
1146     sum += l;
1147
1148     if (pulsesrc->read_buffer_length <= 0) {
1149       /* we copied all of the data, drop it now */
1150       if (pa_stream_drop (pulsesrc->stream) < 0)
1151         goto drop_failed;
1152
1153       /* reset pointer to data */
1154       pulsesrc->read_buffer = NULL;
1155       pulsesrc->read_buffer_length = 0;
1156     }
1157   }
1158
1159   pulsesrc->in_read = FALSE;
1160   pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1161
1162   return sum;
1163
1164   /* ERRORS */
1165 not_connected:
1166   {
1167     GST_LOG_OBJECT (pulsesrc, "we are not connected");
1168     goto unlock_and_fail;
1169   }
1170 was_paused:
1171   {
1172     GST_LOG_OBJECT (pulsesrc, "we are paused");
1173     goto unlock_and_fail;
1174   }
1175 peek_failed:
1176   {
1177     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
1178         ("pa_stream_peek() failed: %s",
1179             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
1180     goto unlock_and_fail;
1181   }
1182 drop_failed:
1183   {
1184     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
1185         ("pa_stream_drop() failed: %s",
1186             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
1187     goto unlock_and_fail;
1188   }
1189 unlock_and_fail:
1190   {
1191     pulsesrc->in_read = FALSE;
1192     pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1193
1194     return (guint) - 1;
1195   }
1196 }
1197
1198 /* return the delay in samples */
1199 static guint
1200 gst_pulsesrc_delay (GstAudioSrc * asrc)
1201 {
1202   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (asrc);
1203   pa_usec_t t;
1204   int negative, res;
1205   guint result;
1206
1207   pa_threaded_mainloop_lock (pulsesrc->mainloop);
1208   if (gst_pulsesrc_is_dead (pulsesrc, TRUE))
1209     goto server_dead;
1210
1211   /* get the latency, this can fail when we don't have a latency update yet.
1212    * We don't want to wait for latency updates here but we just return 0. */
1213   res = pa_stream_get_latency (pulsesrc->stream, &t, &negative);
1214
1215   pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1216
1217   if (res < 0) {
1218     GST_DEBUG_OBJECT (pulsesrc, "could not get latency");
1219     result = 0;
1220   } else {
1221     if (negative)
1222       result = 0;
1223     else
1224       result = (guint) ((t * pulsesrc->sample_spec.rate) / 1000000LL);
1225   }
1226   return result;
1227
1228   /* ERRORS */
1229 server_dead:
1230   {
1231     GST_DEBUG_OBJECT (pulsesrc, "the server is dead");
1232     pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1233     return 0;
1234   }
1235 }
1236
1237 static gboolean
1238 gst_pulsesrc_create_stream (GstPulseSrc * pulsesrc, GstCaps ** caps,
1239     GstAudioRingBufferSpec * rspec)
1240 {
1241   pa_channel_map channel_map;
1242   const pa_channel_map *m;
1243   GstStructure *s;
1244   gboolean need_channel_layout = FALSE;
1245   GstAudioRingBufferSpec new_spec, *spec = NULL;
1246   const gchar *name;
1247   int i;
1248
1249   /* If we already have a stream (renegotiation), free it first */
1250   if (pulsesrc->stream)
1251     gst_pulsesrc_destroy_stream (pulsesrc);
1252
1253   if (rspec) {
1254     /* Post-negotiation, we already have a ringbuffer spec, so we just need to
1255      * use it to create a stream. */
1256     spec = rspec;
1257
1258     /* At this point, we expect the channel-mask to be set in caps, so we just
1259      * use that */
1260     if (!gst_pulse_gst_to_channel_map (&channel_map, spec))
1261       goto invalid_spec;
1262
1263   } else if (caps) {
1264     /* At negotiation time, we get a fixed caps and use it to set up a stream */
1265     s = gst_caps_get_structure (*caps, 0);
1266     gst_structure_get_int (s, "channels", &new_spec.info.channels);
1267     if (!gst_structure_has_field (s, "channel-mask")) {
1268       if (new_spec.info.channels == 1) {
1269         pa_channel_map_init_mono (&channel_map);
1270       } else if (new_spec.info.channels == 2) {
1271         pa_channel_map_init_stereo (&channel_map);
1272       } else {
1273         need_channel_layout = TRUE;
1274         gst_structure_set (s, "channel-mask", GST_TYPE_BITMASK,
1275             G_GUINT64_CONSTANT (0), NULL);
1276       }
1277     }
1278
1279     memset (&new_spec, 0, sizeof (GstAudioRingBufferSpec));
1280     new_spec.latency_time = GST_SECOND;
1281     if (!gst_audio_ring_buffer_parse_caps (&new_spec, *caps))
1282       goto invalid_caps;
1283
1284     /* Keep the refcount of the caps at 1 to make them writable */
1285     gst_caps_unref (new_spec.caps);
1286
1287     if (!need_channel_layout
1288         && !gst_pulse_gst_to_channel_map (&channel_map, &new_spec)) {
1289       need_channel_layout = TRUE;
1290       gst_structure_set (s, "channel-mask", GST_TYPE_BITMASK,
1291           G_GUINT64_CONSTANT (0), NULL);
1292       for (i = 0; i < G_N_ELEMENTS (new_spec.info.position); i++)
1293         new_spec.info.position[i] = GST_AUDIO_CHANNEL_POSITION_INVALID;
1294     }
1295
1296     spec = &new_spec;
1297   } else {
1298     /* !rspec && !caps */
1299     g_assert_not_reached ();
1300   }
1301
1302   if (!gst_pulse_fill_sample_spec (spec, &pulsesrc->sample_spec))
1303     goto invalid_spec;
1304
1305   pa_threaded_mainloop_lock (pulsesrc->mainloop);
1306
1307   if (!pulsesrc->context)
1308     goto bad_context;
1309
1310   name = "Record Stream";
1311   if (pulsesrc->proplist) {
1312     if (!(pulsesrc->stream = pa_stream_new_with_proplist (pulsesrc->context,
1313                 name, &pulsesrc->sample_spec,
1314                 (need_channel_layout) ? NULL : &channel_map,
1315                 pulsesrc->proplist)))
1316       goto create_failed;
1317
1318   } else if (!(pulsesrc->stream = pa_stream_new (pulsesrc->context,
1319               name, &pulsesrc->sample_spec,
1320               (need_channel_layout) ? NULL : &channel_map)))
1321     goto create_failed;
1322
1323   if (caps) {
1324     m = pa_stream_get_channel_map (pulsesrc->stream);
1325     gst_pulse_channel_map_to_gst (m, &new_spec);
1326     gst_audio_channel_positions_to_valid_order (new_spec.info.position,
1327         new_spec.info.channels);
1328     gst_caps_unref (*caps);
1329     *caps = gst_audio_info_to_caps (&new_spec.info);
1330
1331     GST_DEBUG_OBJECT (pulsesrc, "Caps are %" GST_PTR_FORMAT, *caps);
1332   }
1333
1334
1335   pa_stream_set_state_callback (pulsesrc->stream, gst_pulsesrc_stream_state_cb,
1336       pulsesrc);
1337   pa_stream_set_read_callback (pulsesrc->stream, gst_pulsesrc_stream_request_cb,
1338       pulsesrc);
1339   pa_stream_set_underflow_callback (pulsesrc->stream,
1340       gst_pulsesrc_stream_underflow_cb, pulsesrc);
1341   pa_stream_set_overflow_callback (pulsesrc->stream,
1342       gst_pulsesrc_stream_overflow_cb, pulsesrc);
1343   pa_stream_set_latency_update_callback (pulsesrc->stream,
1344       gst_pulsesrc_stream_latency_update_cb, pulsesrc);
1345
1346   pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1347
1348   return TRUE;
1349
1350   /* ERRORS */
1351 invalid_caps:
1352   {
1353     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, SETTINGS,
1354         ("Can't parse caps."), (NULL));
1355     goto fail;
1356   }
1357 invalid_spec:
1358   {
1359     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, SETTINGS,
1360         ("Invalid sample specification."), (NULL));
1361     goto fail;
1362   }
1363 bad_context:
1364   {
1365     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED, ("Bad context"), (NULL));
1366     goto unlock_and_fail;
1367   }
1368 create_failed:
1369   {
1370     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
1371         ("Failed to create stream: %s",
1372             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
1373     goto unlock_and_fail;
1374   }
1375 unlock_and_fail:
1376   {
1377     gst_pulsesrc_destroy_stream (pulsesrc);
1378
1379     pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1380
1381   fail:
1382     return FALSE;
1383   }
1384 }
1385
1386 static gboolean
1387 gst_pulsesrc_event (GstBaseSrc * basesrc, GstEvent * event)
1388 {
1389   GST_DEBUG_OBJECT (basesrc, "handle event %" GST_PTR_FORMAT, event);
1390
1391   switch (GST_EVENT_TYPE (event)) {
1392     case GST_EVENT_RECONFIGURE:
1393       gst_pad_check_reconfigure (GST_BASE_SRC_PAD (basesrc));
1394       break;
1395     default:
1396       break;
1397   }
1398   return GST_BASE_SRC_CLASS (parent_class)->event (basesrc, event);
1399 }
1400
1401 /* This is essentially gst_base_src_negotiate_default() but the caps
1402  * are guaranteed to have a channel layout for > 2 channels
1403  */
1404 static gboolean
1405 gst_pulsesrc_negotiate (GstBaseSrc * basesrc)
1406 {
1407   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (basesrc);
1408   GstCaps *thiscaps;
1409   GstCaps *caps = NULL;
1410   GstCaps *peercaps = NULL;
1411   gboolean result = FALSE;
1412
1413   /* first see what is possible on our source pad */
1414   thiscaps = gst_pad_query_caps (GST_BASE_SRC_PAD (basesrc), NULL);
1415   GST_DEBUG_OBJECT (basesrc, "caps of src: %" GST_PTR_FORMAT, thiscaps);
1416   /* nothing or anything is allowed, we're done */
1417   if (thiscaps == NULL || gst_caps_is_any (thiscaps))
1418     goto no_nego_needed;
1419
1420   /* get the peer caps */
1421   peercaps = gst_pad_peer_query_caps (GST_BASE_SRC_PAD (basesrc), NULL);
1422   GST_DEBUG_OBJECT (basesrc, "caps of peer: %" GST_PTR_FORMAT, peercaps);
1423   if (peercaps) {
1424     /* get intersection */
1425     caps = gst_caps_intersect (thiscaps, peercaps);
1426     GST_DEBUG_OBJECT (basesrc, "intersect: %" GST_PTR_FORMAT, caps);
1427     gst_caps_unref (thiscaps);
1428     gst_caps_unref (peercaps);
1429   } else {
1430     /* no peer, work with our own caps then */
1431     caps = thiscaps;
1432   }
1433   if (caps) {
1434     /* take first (and best, since they are sorted) possibility */
1435     caps = gst_caps_truncate (caps);
1436
1437     /* now fixate */
1438     if (!gst_caps_is_empty (caps)) {
1439       caps = GST_BASE_SRC_CLASS (parent_class)->fixate (basesrc, caps);
1440       GST_DEBUG_OBJECT (basesrc, "fixated to: %" GST_PTR_FORMAT, caps);
1441
1442       if (gst_caps_is_any (caps)) {
1443         /* hmm, still anything, so element can do anything and
1444          * nego is not needed */
1445         result = TRUE;
1446       } else if (gst_caps_is_fixed (caps)) {
1447         /* yay, fixed caps, use those then */
1448         result = gst_pulsesrc_create_stream (pulsesrc, &caps, NULL);
1449         if (result)
1450           result = gst_base_src_set_caps (basesrc, caps);
1451       }
1452     }
1453     gst_caps_unref (caps);
1454   }
1455   return result;
1456
1457 no_nego_needed:
1458   {
1459     GST_DEBUG_OBJECT (basesrc, "no negotiation needed");
1460     if (thiscaps)
1461       gst_caps_unref (thiscaps);
1462     return TRUE;
1463   }
1464 }
1465
1466 static gboolean
1467 gst_pulsesrc_prepare (GstAudioSrc * asrc, GstAudioRingBufferSpec * spec)
1468 {
1469   pa_buffer_attr wanted;
1470   const pa_buffer_attr *actual;
1471   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (asrc);
1472   pa_stream_flags_t flags;
1473   pa_operation *o;
1474   GstAudioClock *clock;
1475
1476   pa_threaded_mainloop_lock (pulsesrc->mainloop);
1477
1478   if (!pulsesrc->stream)
1479     gst_pulsesrc_create_stream (pulsesrc, NULL, spec);
1480
1481   {
1482     GstAudioRingBufferSpec s = *spec;
1483     const pa_channel_map *m;
1484
1485     m = pa_stream_get_channel_map (pulsesrc->stream);
1486     gst_pulse_channel_map_to_gst (m, &s);
1487     gst_audio_ring_buffer_set_channel_positions (GST_AUDIO_BASE_SRC
1488         (pulsesrc)->ringbuffer, s.info.position);
1489   }
1490
1491   /* enable event notifications */
1492   GST_LOG_OBJECT (pulsesrc, "subscribing to context events");
1493   if (!(o = pa_context_subscribe (pulsesrc->context,
1494               PA_SUBSCRIPTION_MASK_SOURCE_OUTPUT, NULL, NULL))) {
1495     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
1496         ("pa_context_subscribe() failed: %s",
1497             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
1498     goto unlock_and_fail;
1499   }
1500
1501   pa_operation_unref (o);
1502
1503   /* There's a bit of a disconnect here between the audio ringbuffer and what
1504    * PulseAudio provides. The audio ringbuffer provide a total of buffer_time
1505    * worth of buffering, divided into segments of latency_time size. We're
1506    * asking PulseAudio to provide a total latency of latency_time, which, with
1507    * PA_STREAM_ADJUST_LATENCY, effectively sets itself up as a ringbuffer with
1508    * one segment being the hardware buffer, and the other the software buffer.
1509    * This segment size is returned as the fragsize.
1510    *
1511    * Since the two concepts don't map very well, what we do is keep segsize as
1512    * it is (unless fragsize is even larger, in which case we use that). We'll
1513    * get data from PulseAudio in smaller chunks than we want to pass on as an
1514    * element, and we coalesce those chunks in the ringbuffer memory and pass it
1515    * on in the expected chunk size. */
1516   wanted.maxlength = spec->segsize * spec->segtotal;
1517   wanted.tlength = -1;
1518   wanted.prebuf = 0;
1519   wanted.minreq = -1;
1520   wanted.fragsize = spec->segsize;
1521
1522   GST_INFO_OBJECT (pulsesrc, "maxlength: %d", wanted.maxlength);
1523   GST_INFO_OBJECT (pulsesrc, "tlength:   %d", wanted.tlength);
1524   GST_INFO_OBJECT (pulsesrc, "prebuf:    %d", wanted.prebuf);
1525   GST_INFO_OBJECT (pulsesrc, "minreq:    %d", wanted.minreq);
1526   GST_INFO_OBJECT (pulsesrc, "fragsize:  %d", wanted.fragsize);
1527
1528   flags = PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE |
1529       PA_STREAM_NOT_MONOTONIC | PA_STREAM_ADJUST_LATENCY |
1530       PA_STREAM_START_CORKED;
1531
1532   if (pa_stream_connect_record (pulsesrc->stream, pulsesrc->device, &wanted,
1533           flags) < 0) {
1534     goto connect_failed;
1535   }
1536
1537   /* our clock will now start from 0 again */
1538   clock = GST_AUDIO_CLOCK (GST_AUDIO_BASE_SRC (pulsesrc)->clock);
1539   gst_audio_clock_reset (clock, 0);
1540
1541   pulsesrc->corked = TRUE;
1542
1543   for (;;) {
1544     pa_stream_state_t state;
1545
1546     state = pa_stream_get_state (pulsesrc->stream);
1547
1548     if (!PA_STREAM_IS_GOOD (state))
1549       goto stream_is_bad;
1550
1551     if (state == PA_STREAM_READY)
1552       break;
1553
1554     /* Wait until the stream is ready */
1555     pa_threaded_mainloop_wait (pulsesrc->mainloop);
1556   }
1557   pulsesrc->stream_connected = TRUE;
1558
1559   /* store the source output index so it can be accessed via a property */
1560   pulsesrc->source_output_idx = pa_stream_get_index (pulsesrc->stream);
1561   g_object_notify (G_OBJECT (pulsesrc), "source-output-index");
1562
1563   /* Although source output stream muting is supported, there is a bug in
1564    * PulseAudio that doesn't allow us to do this at startup, so we mute
1565    * manually post-connect. This should be moved back pre-connect once things
1566    * are fixed on the PulseAudio side. */
1567   if (pulsesrc->mute_set && pulsesrc->mute) {
1568     gst_pulsesrc_set_stream_mute (pulsesrc, pulsesrc->mute);
1569     pulsesrc->mute_set = FALSE;
1570   }
1571
1572   if (pulsesrc->volume_set) {
1573     gst_pulsesrc_set_stream_volume (pulsesrc, pulsesrc->volume);
1574     pulsesrc->volume_set = FALSE;
1575   }
1576
1577   /* get the actual buffering properties now */
1578   actual = pa_stream_get_buffer_attr (pulsesrc->stream);
1579
1580   GST_INFO_OBJECT (pulsesrc, "maxlength: %d", actual->maxlength);
1581   GST_INFO_OBJECT (pulsesrc, "tlength:   %d (wanted: %d)",
1582       actual->tlength, wanted.tlength);
1583   GST_INFO_OBJECT (pulsesrc, "prebuf:    %d", actual->prebuf);
1584   GST_INFO_OBJECT (pulsesrc, "minreq:    %d (wanted %d)", actual->minreq,
1585       wanted.minreq);
1586   GST_INFO_OBJECT (pulsesrc, "fragsize:  %d (wanted %d)",
1587       actual->fragsize, wanted.fragsize);
1588
1589   if (actual->fragsize >= spec->segsize) {
1590     spec->segsize = actual->fragsize;
1591   } else {
1592     /* fragsize is smaller than what we wanted, so let the read function
1593      * coalesce the smaller chunks as they come in */
1594   }
1595
1596   /* Fix up the total ringbuffer size based on what we actually got */
1597   spec->segtotal = actual->maxlength / spec->segsize;
1598   /* Don't buffer less than 2 segments as the ringbuffer can't deal with it */
1599   if (spec->segtotal < 2)
1600     spec->segtotal = 2;
1601
1602   if (!pulsesrc->paused) {
1603     GST_DEBUG_OBJECT (pulsesrc, "uncorking because we are playing");
1604     gst_pulsesrc_set_corked (pulsesrc, FALSE, FALSE);
1605   }
1606   pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1607
1608   return TRUE;
1609
1610   /* ERRORS */
1611 connect_failed:
1612   {
1613     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
1614         ("Failed to connect stream: %s",
1615             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
1616     goto unlock_and_fail;
1617   }
1618 stream_is_bad:
1619   {
1620     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
1621         ("Failed to connect stream: %s",
1622             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
1623     goto unlock_and_fail;
1624   }
1625 unlock_and_fail:
1626   {
1627     gst_pulsesrc_destroy_stream (pulsesrc);
1628
1629     pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1630     return FALSE;
1631   }
1632 }
1633
1634 static void
1635 gst_pulsesrc_success_cb (pa_stream * s, int success, void *userdata)
1636 {
1637   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (userdata);
1638
1639   pulsesrc->operation_success = ! !success;
1640   pa_threaded_mainloop_signal (pulsesrc->mainloop, 0);
1641 }
1642
1643 static void
1644 gst_pulsesrc_reset (GstAudioSrc * asrc)
1645 {
1646   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (asrc);
1647   pa_operation *o = NULL;
1648
1649   pa_threaded_mainloop_lock (pulsesrc->mainloop);
1650   GST_DEBUG_OBJECT (pulsesrc, "reset");
1651
1652   if (gst_pulsesrc_is_dead (pulsesrc, TRUE))
1653     goto unlock_and_fail;
1654
1655   if (!(o =
1656           pa_stream_flush (pulsesrc->stream, gst_pulsesrc_success_cb,
1657               pulsesrc))) {
1658     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
1659         ("pa_stream_flush() failed: %s",
1660             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
1661     goto unlock_and_fail;
1662   }
1663
1664   pulsesrc->paused = TRUE;
1665   /* Inform anyone waiting in _write() call that it shall wakeup */
1666   if (pulsesrc->in_read) {
1667     pa_threaded_mainloop_signal (pulsesrc->mainloop, 0);
1668   }
1669
1670   pulsesrc->operation_success = FALSE;
1671   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
1672
1673     if (gst_pulsesrc_is_dead (pulsesrc, TRUE))
1674       goto unlock_and_fail;
1675
1676     pa_threaded_mainloop_wait (pulsesrc->mainloop);
1677   }
1678
1679   if (!pulsesrc->operation_success) {
1680     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED, ("Flush failed: %s",
1681             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
1682     goto unlock_and_fail;
1683   }
1684
1685 unlock_and_fail:
1686
1687   if (o) {
1688     pa_operation_cancel (o);
1689     pa_operation_unref (o);
1690   }
1691
1692   pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1693 }
1694
1695 /* update the corked state of a stream, must be called with the mainloop
1696  * lock */
1697 static gboolean
1698 gst_pulsesrc_set_corked (GstPulseSrc * psrc, gboolean corked, gboolean wait)
1699 {
1700   pa_operation *o = NULL;
1701   gboolean res = FALSE;
1702
1703   GST_DEBUG_OBJECT (psrc, "setting corked state to %d", corked);
1704   if (!psrc->stream_connected)
1705     return TRUE;
1706
1707   if (psrc->corked != corked) {
1708     if (!(o = pa_stream_cork (psrc->stream, corked,
1709                 gst_pulsesrc_success_cb, psrc)))
1710       goto cork_failed;
1711
1712     while (wait && pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
1713       pa_threaded_mainloop_wait (psrc->mainloop);
1714       if (gst_pulsesrc_is_dead (psrc, TRUE))
1715         goto server_dead;
1716     }
1717     psrc->corked = corked;
1718   } else {
1719     GST_DEBUG_OBJECT (psrc, "skipping, already in requested state");
1720   }
1721   res = TRUE;
1722
1723 cleanup:
1724   if (o)
1725     pa_operation_unref (o);
1726
1727   return res;
1728
1729   /* ERRORS */
1730 server_dead:
1731   {
1732     GST_DEBUG_OBJECT (psrc, "the server is dead");
1733     goto cleanup;
1734   }
1735 cork_failed:
1736   {
1737     GST_ELEMENT_ERROR (psrc, RESOURCE, FAILED,
1738         ("pa_stream_cork() failed: %s",
1739             pa_strerror (pa_context_errno (psrc->context))), (NULL));
1740     goto cleanup;
1741   }
1742 }
1743
1744 /* start/resume playback ASAP */
1745 static gboolean
1746 gst_pulsesrc_play (GstPulseSrc * psrc)
1747 {
1748   pa_threaded_mainloop_lock (psrc->mainloop);
1749   GST_DEBUG_OBJECT (psrc, "playing");
1750   psrc->paused = FALSE;
1751   gst_pulsesrc_set_corked (psrc, FALSE, FALSE);
1752   pa_threaded_mainloop_unlock (psrc->mainloop);
1753
1754   return TRUE;
1755 }
1756
1757 /* pause/stop playback ASAP */
1758 static gboolean
1759 gst_pulsesrc_pause (GstPulseSrc * psrc)
1760 {
1761   pa_threaded_mainloop_lock (psrc->mainloop);
1762   GST_DEBUG_OBJECT (psrc, "pausing");
1763   /* make sure the commit method stops writing */
1764   psrc->paused = TRUE;
1765   if (psrc->in_read) {
1766     /* we are waiting in a read, signal */
1767     GST_DEBUG_OBJECT (psrc, "signal read");
1768     pa_threaded_mainloop_signal (psrc->mainloop, 0);
1769   }
1770   pa_threaded_mainloop_unlock (psrc->mainloop);
1771
1772   return TRUE;
1773 }
1774
1775 static GstStateChangeReturn
1776 gst_pulsesrc_change_state (GstElement * element, GstStateChange transition)
1777 {
1778   GstStateChangeReturn ret;
1779   GstPulseSrc *this = GST_PULSESRC_CAST (element);
1780
1781   switch (transition) {
1782     case GST_STATE_CHANGE_NULL_TO_READY:
1783       if (!(this->mainloop = pa_threaded_mainloop_new ()))
1784         goto mainloop_failed;
1785       if (pa_threaded_mainloop_start (this->mainloop) < 0) {
1786         pa_threaded_mainloop_free (this->mainloop);
1787         this->mainloop = NULL;
1788         goto mainloop_start_failed;
1789       }
1790       break;
1791     case GST_STATE_CHANGE_READY_TO_PAUSED:
1792       gst_element_post_message (element,
1793           gst_message_new_clock_provide (GST_OBJECT_CAST (element),
1794               GST_AUDIO_BASE_SRC (this)->clock, TRUE));
1795       break;
1796     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1797       /* uncork and start recording */
1798       gst_pulsesrc_play (this);
1799       break;
1800     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1801       /* stop recording ASAP by corking */
1802       pa_threaded_mainloop_lock (this->mainloop);
1803       GST_DEBUG_OBJECT (this, "corking");
1804       gst_pulsesrc_set_corked (this, TRUE, FALSE);
1805       pa_threaded_mainloop_unlock (this->mainloop);
1806       break;
1807     default:
1808       break;
1809   }
1810
1811   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1812
1813   switch (transition) {
1814     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1815       /* now make sure we get out of the _read method */
1816       gst_pulsesrc_pause (this);
1817       break;
1818     case GST_STATE_CHANGE_READY_TO_NULL:
1819       if (this->mainloop)
1820         pa_threaded_mainloop_stop (this->mainloop);
1821
1822       gst_pulsesrc_destroy_context (this);
1823
1824       if (this->mainloop) {
1825         pa_threaded_mainloop_free (this->mainloop);
1826         this->mainloop = NULL;
1827       }
1828       break;
1829     case GST_STATE_CHANGE_PAUSED_TO_READY:
1830       /* format_lost is reset in release() in baseaudiosink */
1831       gst_element_post_message (element,
1832           gst_message_new_clock_lost (GST_OBJECT_CAST (element),
1833               GST_AUDIO_BASE_SRC (this)->clock));
1834       break;
1835     default:
1836       break;
1837   }
1838
1839   return ret;
1840
1841   /* ERRORS */
1842 mainloop_failed:
1843   {
1844     GST_ELEMENT_ERROR (this, RESOURCE, FAILED,
1845         ("pa_threaded_mainloop_new() failed"), (NULL));
1846     return GST_STATE_CHANGE_FAILURE;
1847   }
1848 mainloop_start_failed:
1849   {
1850     GST_ELEMENT_ERROR (this, RESOURCE, FAILED,
1851         ("pa_threaded_mainloop_start() failed"), (NULL));
1852     return GST_STATE_CHANGE_FAILURE;
1853   }
1854 }
1855
1856 static GstClockTime
1857 gst_pulsesrc_get_time (GstClock * clock, GstPulseSrc * src)
1858 {
1859   pa_usec_t time = 0;
1860
1861   if (src->mainloop == NULL)
1862     goto out;
1863
1864   pa_threaded_mainloop_lock (src->mainloop);
1865   if (!src->stream)
1866     goto unlock_and_out;
1867
1868   if (gst_pulsesrc_is_dead (src, TRUE))
1869     goto unlock_and_out;
1870
1871   if (pa_stream_get_time (src->stream, &time) < 0) {
1872     GST_DEBUG_OBJECT (src, "could not get time");
1873     time = GST_CLOCK_TIME_NONE;
1874   } else {
1875     time *= 1000;
1876   }
1877
1878
1879 unlock_and_out:
1880   pa_threaded_mainloop_unlock (src->mainloop);
1881
1882 out:
1883   return time;
1884 }