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