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