update for audio base src api change
[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, GstClockTime * timestamp);
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     GstClockTime * timestamp)
995 {
996   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (asrc);
997   size_t sum = 0;
998
999   if (g_atomic_int_compare_and_exchange (&pulsesrc->notify, 1, 0)) {
1000     g_object_notify (G_OBJECT (pulsesrc), "volume");
1001     g_object_notify (G_OBJECT (pulsesrc), "mute");
1002   }
1003
1004   pa_threaded_mainloop_lock (pulsesrc->mainloop);
1005   pulsesrc->in_read = TRUE;
1006
1007   if (pulsesrc->paused)
1008     goto was_paused;
1009
1010   while (length > 0) {
1011     size_t l;
1012
1013     GST_LOG_OBJECT (pulsesrc, "reading %u bytes", length);
1014
1015     /*check if we have a leftover buffer */
1016     if (!pulsesrc->read_buffer) {
1017       for (;;) {
1018         if (gst_pulsesrc_is_dead (pulsesrc, TRUE))
1019           goto unlock_and_fail;
1020
1021         /* read all available data, we keep a pointer to the data and the length
1022          * and take from it what we need. */
1023         if (pa_stream_peek (pulsesrc->stream, &pulsesrc->read_buffer,
1024                 &pulsesrc->read_buffer_length) < 0)
1025           goto peek_failed;
1026
1027         GST_LOG_OBJECT (pulsesrc, "have data of %" G_GSIZE_FORMAT " bytes",
1028             pulsesrc->read_buffer_length);
1029
1030         /* if we have data, process if */
1031         if (pulsesrc->read_buffer && pulsesrc->read_buffer_length)
1032           break;
1033
1034         /* now wait for more data to become available */
1035         GST_LOG_OBJECT (pulsesrc, "waiting for data");
1036         pa_threaded_mainloop_wait (pulsesrc->mainloop);
1037
1038         if (pulsesrc->paused)
1039           goto was_paused;
1040       }
1041     }
1042
1043     l = pulsesrc->read_buffer_length >
1044         length ? length : pulsesrc->read_buffer_length;
1045
1046     memcpy (data, pulsesrc->read_buffer, l);
1047
1048     pulsesrc->read_buffer = (const guint8 *) pulsesrc->read_buffer + l;
1049     pulsesrc->read_buffer_length -= l;
1050
1051     data = (guint8 *) data + l;
1052     length -= l;
1053     sum += l;
1054
1055     if (pulsesrc->read_buffer_length <= 0) {
1056       /* we copied all of the data, drop it now */
1057       if (pa_stream_drop (pulsesrc->stream) < 0)
1058         goto drop_failed;
1059
1060       /* reset pointer to data */
1061       pulsesrc->read_buffer = NULL;
1062       pulsesrc->read_buffer_length = 0;
1063     }
1064   }
1065
1066   pulsesrc->in_read = FALSE;
1067   pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1068
1069   return sum;
1070
1071   /* ERRORS */
1072 was_paused:
1073   {
1074     GST_LOG_OBJECT (pulsesrc, "we are paused");
1075     goto unlock_and_fail;
1076   }
1077 peek_failed:
1078   {
1079     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
1080         ("pa_stream_peek() failed: %s",
1081             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
1082     goto unlock_and_fail;
1083   }
1084 drop_failed:
1085   {
1086     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
1087         ("pa_stream_drop() failed: %s",
1088             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
1089     goto unlock_and_fail;
1090   }
1091 unlock_and_fail:
1092   {
1093     pulsesrc->in_read = FALSE;
1094     pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1095
1096     return (guint) - 1;
1097   }
1098 }
1099
1100 /* return the delay in samples */
1101 static guint
1102 gst_pulsesrc_delay (GstAudioSrc * asrc)
1103 {
1104   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (asrc);
1105   pa_usec_t t;
1106   int negative, res;
1107   guint result;
1108
1109   pa_threaded_mainloop_lock (pulsesrc->mainloop);
1110   if (gst_pulsesrc_is_dead (pulsesrc, TRUE))
1111     goto server_dead;
1112
1113   /* get the latency, this can fail when we don't have a latency update yet.
1114    * We don't want to wait for latency updates here but we just return 0. */
1115   res = pa_stream_get_latency (pulsesrc->stream, &t, &negative);
1116
1117   pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1118
1119   if (res < 0) {
1120     GST_DEBUG_OBJECT (pulsesrc, "could not get latency");
1121     result = 0;
1122   } else {
1123     if (negative)
1124       result = 0;
1125     else
1126       result = (guint) ((t * pulsesrc->sample_spec.rate) / 1000000LL);
1127   }
1128   return result;
1129
1130   /* ERRORS */
1131 server_dead:
1132   {
1133     GST_DEBUG_OBJECT (pulsesrc, "the server is dead");
1134     pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1135     return 0;
1136   }
1137 }
1138
1139 static gboolean
1140 gst_pulsesrc_create_stream (GstPulseSrc * pulsesrc, GstCaps ** caps,
1141     GstAudioRingBufferSpec * rspec)
1142 {
1143   pa_channel_map channel_map;
1144   const pa_channel_map *m;
1145   GstStructure *s;
1146   gboolean need_channel_layout = FALSE;
1147   GstAudioRingBufferSpec new_spec, *spec;
1148   const gchar *name;
1149   int i;
1150
1151   /* If we already have a stream (renegotiation), free it first */
1152   if (pulsesrc->stream)
1153     gst_pulsesrc_destroy_stream (pulsesrc);
1154
1155   if (rspec) {
1156     /* Post-negotiation, we already have a ringbuffer spec, so we just need to
1157      * use it to create a stream. */
1158     spec = rspec;
1159
1160     /* At this point, we expect the channel-mask to be set in caps, so we just
1161      * use that */
1162     if (!gst_pulse_gst_to_channel_map (&channel_map, spec))
1163       goto invalid_spec;
1164
1165   } else if (caps) {
1166     /* At negotiation time, we get a fixed caps and use it to set up a stream */
1167     s = gst_caps_get_structure (*caps, 0);
1168     gst_structure_get_int (s, "channels", &new_spec.info.channels);
1169     if (!gst_structure_has_field (s, "channel-mask")) {
1170       if (new_spec.info.channels == 1) {
1171         pa_channel_map_init_mono (&channel_map);
1172       } else if (new_spec.info.channels == 2) {
1173         pa_channel_map_init_stereo (&channel_map);
1174       } else {
1175         need_channel_layout = TRUE;
1176         gst_structure_set (s, "channel-mask", GST_TYPE_BITMASK,
1177             G_GUINT64_CONSTANT (0), NULL);
1178       }
1179     }
1180
1181     memset (&new_spec, 0, sizeof (GstAudioRingBufferSpec));
1182     new_spec.latency_time = GST_SECOND;
1183     if (!gst_audio_ring_buffer_parse_caps (&new_spec, *caps))
1184       goto invalid_caps;
1185
1186     /* Keep the refcount of the caps at 1 to make them writable */
1187     gst_caps_unref (new_spec.caps);
1188
1189     if (!need_channel_layout
1190         && !gst_pulse_gst_to_channel_map (&channel_map, &new_spec)) {
1191       need_channel_layout = TRUE;
1192       gst_structure_set (s, "channel-mask", GST_TYPE_BITMASK,
1193           G_GUINT64_CONSTANT (0), NULL);
1194       for (i = 0; i < G_N_ELEMENTS (new_spec.info.position); i++)
1195         new_spec.info.position[i] = GST_AUDIO_CHANNEL_POSITION_INVALID;
1196     }
1197
1198     spec = &new_spec;
1199   } else {
1200     /* !rspec && !caps */
1201     g_assert_not_reached ();
1202   }
1203
1204   if (!gst_pulse_fill_sample_spec (spec, &pulsesrc->sample_spec))
1205     goto invalid_spec;
1206
1207   pa_threaded_mainloop_lock (pulsesrc->mainloop);
1208
1209   if (!pulsesrc->context)
1210     goto bad_context;
1211
1212   name = "Record Stream";
1213   if (pulsesrc->proplist) {
1214     if (!(pulsesrc->stream = pa_stream_new_with_proplist (pulsesrc->context,
1215                 name, &pulsesrc->sample_spec,
1216                 (need_channel_layout) ? NULL : &channel_map,
1217                 pulsesrc->proplist)))
1218       goto create_failed;
1219
1220   } else if (!(pulsesrc->stream = pa_stream_new (pulsesrc->context,
1221               name, &pulsesrc->sample_spec,
1222               (need_channel_layout) ? NULL : &channel_map)))
1223     goto create_failed;
1224
1225   if (caps) {
1226     m = pa_stream_get_channel_map (pulsesrc->stream);
1227     gst_pulse_channel_map_to_gst (m, &new_spec);
1228     gst_audio_channel_positions_to_valid_order (new_spec.info.position,
1229         new_spec.info.channels);
1230     gst_caps_unref (*caps);
1231     *caps = gst_audio_info_to_caps (&new_spec.info);
1232
1233     GST_DEBUG_OBJECT (pulsesrc, "Caps are %" GST_PTR_FORMAT, *caps);
1234   }
1235
1236
1237   pa_stream_set_state_callback (pulsesrc->stream, gst_pulsesrc_stream_state_cb,
1238       pulsesrc);
1239   pa_stream_set_read_callback (pulsesrc->stream, gst_pulsesrc_stream_request_cb,
1240       pulsesrc);
1241   pa_stream_set_underflow_callback (pulsesrc->stream,
1242       gst_pulsesrc_stream_underflow_cb, pulsesrc);
1243   pa_stream_set_overflow_callback (pulsesrc->stream,
1244       gst_pulsesrc_stream_overflow_cb, pulsesrc);
1245   pa_stream_set_latency_update_callback (pulsesrc->stream,
1246       gst_pulsesrc_stream_latency_update_cb, pulsesrc);
1247
1248   pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1249
1250   return TRUE;
1251
1252   /* ERRORS */
1253 invalid_caps:
1254   {
1255     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, SETTINGS,
1256         ("Can't parse caps."), (NULL));
1257     goto fail;
1258   }
1259 invalid_spec:
1260   {
1261     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, SETTINGS,
1262         ("Invalid sample specification."), (NULL));
1263     goto fail;
1264   }
1265 bad_context:
1266   {
1267     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED, ("Bad context"), (NULL));
1268     goto unlock_and_fail;
1269   }
1270 create_failed:
1271   {
1272     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
1273         ("Failed to create stream: %s",
1274             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
1275     goto unlock_and_fail;
1276   }
1277 unlock_and_fail:
1278   {
1279     gst_pulsesrc_destroy_stream (pulsesrc);
1280
1281     pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1282
1283   fail:
1284     return FALSE;
1285   }
1286 }
1287
1288 /* This is essentially gst_base_src_negotiate_default() but the caps
1289  * are guaranteed to have a channel layout for > 2 channels
1290  */
1291 static gboolean
1292 gst_pulsesrc_negotiate (GstBaseSrc * basesrc)
1293 {
1294   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (basesrc);
1295   GstCaps *thiscaps;
1296   GstCaps *caps = NULL;
1297   GstCaps *peercaps = NULL;
1298   gboolean result = FALSE;
1299
1300   /* first see what is possible on our source pad */
1301   thiscaps = gst_pad_query_caps (GST_BASE_SRC_PAD (basesrc), NULL);
1302   GST_DEBUG_OBJECT (basesrc, "caps of src: %" GST_PTR_FORMAT, thiscaps);
1303   /* nothing or anything is allowed, we're done */
1304   if (thiscaps == NULL || gst_caps_is_any (thiscaps))
1305     goto no_nego_needed;
1306
1307   /* get the peer caps */
1308   peercaps = gst_pad_peer_query_caps (GST_BASE_SRC_PAD (basesrc), NULL);
1309   GST_DEBUG_OBJECT (basesrc, "caps of peer: %" GST_PTR_FORMAT, peercaps);
1310   if (peercaps) {
1311     /* get intersection */
1312     caps = gst_caps_intersect (thiscaps, peercaps);
1313     GST_DEBUG_OBJECT (basesrc, "intersect: %" GST_PTR_FORMAT, caps);
1314     gst_caps_unref (thiscaps);
1315     gst_caps_unref (peercaps);
1316   } else {
1317     /* no peer, work with our own caps then */
1318     caps = thiscaps;
1319   }
1320   if (caps) {
1321     /* take first (and best, since they are sorted) possibility */
1322     caps = gst_caps_truncate (caps);
1323
1324     /* now fixate */
1325     if (!gst_caps_is_empty (caps)) {
1326       caps = GST_BASE_SRC_CLASS (parent_class)->fixate (basesrc, caps);
1327       GST_DEBUG_OBJECT (basesrc, "fixated to: %" GST_PTR_FORMAT, caps);
1328
1329       if (gst_caps_is_any (caps)) {
1330         /* hmm, still anything, so element can do anything and
1331          * nego is not needed */
1332         result = TRUE;
1333       } else if (gst_caps_is_fixed (caps)) {
1334         /* yay, fixed caps, use those then */
1335         result = gst_pulsesrc_create_stream (pulsesrc, &caps, NULL);
1336         if (result)
1337           result = gst_base_src_set_caps (basesrc, caps);
1338       }
1339     }
1340     gst_caps_unref (caps);
1341   }
1342   return result;
1343
1344 no_nego_needed:
1345   {
1346     GST_DEBUG_OBJECT (basesrc, "no negotiation needed");
1347     if (thiscaps)
1348       gst_caps_unref (thiscaps);
1349     return TRUE;
1350   }
1351 }
1352
1353 static gboolean
1354 gst_pulsesrc_prepare (GstAudioSrc * asrc, GstAudioRingBufferSpec * spec)
1355 {
1356   pa_buffer_attr wanted;
1357   const pa_buffer_attr *actual;
1358   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (asrc);
1359   pa_stream_flags_t flags;
1360   pa_operation *o;
1361   GstAudioClock *clock;
1362
1363   pa_threaded_mainloop_lock (pulsesrc->mainloop);
1364
1365   if (!pulsesrc->stream)
1366     gst_pulsesrc_create_stream (pulsesrc, NULL, spec);
1367
1368   {
1369     GstAudioRingBufferSpec s = *spec;
1370     const pa_channel_map *m;
1371
1372     m = pa_stream_get_channel_map (pulsesrc->stream);
1373     gst_pulse_channel_map_to_gst (m, &s);
1374     gst_audio_ring_buffer_set_channel_positions (GST_AUDIO_BASE_SRC
1375         (pulsesrc)->ringbuffer, s.info.position);
1376   }
1377
1378   /* enable event notifications */
1379   GST_LOG_OBJECT (pulsesrc, "subscribing to context events");
1380   if (!(o = pa_context_subscribe (pulsesrc->context,
1381               PA_SUBSCRIPTION_MASK_SOURCE_OUTPUT, NULL, NULL))) {
1382     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
1383         ("pa_context_subscribe() failed: %s",
1384             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
1385     goto unlock_and_fail;
1386   }
1387
1388   pa_operation_unref (o);
1389
1390   wanted.maxlength = -1;
1391   wanted.tlength = -1;
1392   wanted.prebuf = 0;
1393   wanted.minreq = -1;
1394   wanted.fragsize = spec->segsize;
1395
1396   GST_INFO_OBJECT (pulsesrc, "maxlength: %d", wanted.maxlength);
1397   GST_INFO_OBJECT (pulsesrc, "tlength:   %d", wanted.tlength);
1398   GST_INFO_OBJECT (pulsesrc, "prebuf:    %d", wanted.prebuf);
1399   GST_INFO_OBJECT (pulsesrc, "minreq:    %d", wanted.minreq);
1400   GST_INFO_OBJECT (pulsesrc, "fragsize:  %d", wanted.fragsize);
1401
1402   flags = PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE |
1403       PA_STREAM_NOT_MONOTONIC | PA_STREAM_ADJUST_LATENCY |
1404       PA_STREAM_START_CORKED;
1405
1406   if (pulsesrc->mute_set && pulsesrc->mute)
1407     flags |= PA_STREAM_START_MUTED;
1408
1409   if (pa_stream_connect_record (pulsesrc->stream, pulsesrc->device, &wanted,
1410           flags) < 0) {
1411     goto connect_failed;
1412   }
1413
1414   /* our clock will now start from 0 again */
1415   clock = GST_AUDIO_CLOCK (GST_AUDIO_BASE_SRC (pulsesrc)->clock);
1416   gst_audio_clock_reset (clock, 0);
1417
1418   pulsesrc->corked = TRUE;
1419
1420   for (;;) {
1421     pa_stream_state_t state;
1422
1423     state = pa_stream_get_state (pulsesrc->stream);
1424
1425     if (!PA_STREAM_IS_GOOD (state))
1426       goto stream_is_bad;
1427
1428     if (state == PA_STREAM_READY)
1429       break;
1430
1431     /* Wait until the stream is ready */
1432     pa_threaded_mainloop_wait (pulsesrc->mainloop);
1433   }
1434   pulsesrc->stream_connected = TRUE;
1435
1436   /* store the source output index so it can be accessed via a property */
1437   pulsesrc->source_output_idx = pa_stream_get_index (pulsesrc->stream);
1438   g_object_notify (G_OBJECT (pulsesrc), "source-output-index");
1439
1440   if (pulsesrc->volume_set) {
1441     gst_pulsesrc_set_stream_volume (pulsesrc, pulsesrc->volume);
1442     pulsesrc->volume_set = FALSE;
1443   }
1444
1445   /* get the actual buffering properties now */
1446   actual = pa_stream_get_buffer_attr (pulsesrc->stream);
1447
1448   GST_INFO_OBJECT (pulsesrc, "maxlength: %d", actual->maxlength);
1449   GST_INFO_OBJECT (pulsesrc, "tlength:   %d (wanted: %d)",
1450       actual->tlength, wanted.tlength);
1451   GST_INFO_OBJECT (pulsesrc, "prebuf:    %d", actual->prebuf);
1452   GST_INFO_OBJECT (pulsesrc, "minreq:    %d (wanted %d)", actual->minreq,
1453       wanted.minreq);
1454   GST_INFO_OBJECT (pulsesrc, "fragsize:  %d (wanted %d)",
1455       actual->fragsize, wanted.fragsize);
1456
1457   if (actual->fragsize >= wanted.fragsize) {
1458     spec->segsize = actual->fragsize;
1459   } else {
1460     spec->segsize = actual->fragsize * (wanted.fragsize / actual->fragsize);
1461   }
1462   spec->segtotal = actual->maxlength / spec->segsize;
1463
1464   if (!pulsesrc->paused) {
1465     GST_DEBUG_OBJECT (pulsesrc, "uncorking because we are playing");
1466     gst_pulsesrc_set_corked (pulsesrc, FALSE, FALSE);
1467   }
1468   pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1469
1470   return TRUE;
1471
1472   /* ERRORS */
1473 connect_failed:
1474   {
1475     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
1476         ("Failed to connect stream: %s",
1477             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
1478     goto unlock_and_fail;
1479   }
1480 stream_is_bad:
1481   {
1482     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
1483         ("Failed to connect stream: %s",
1484             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
1485     goto unlock_and_fail;
1486   }
1487 unlock_and_fail:
1488   {
1489     gst_pulsesrc_destroy_stream (pulsesrc);
1490
1491     pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1492     return FALSE;
1493   }
1494 }
1495
1496 static void
1497 gst_pulsesrc_success_cb (pa_stream * s, int success, void *userdata)
1498 {
1499   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (userdata);
1500
1501   pulsesrc->operation_success = ! !success;
1502   pa_threaded_mainloop_signal (pulsesrc->mainloop, 0);
1503 }
1504
1505 static void
1506 gst_pulsesrc_reset (GstAudioSrc * asrc)
1507 {
1508   GstPulseSrc *pulsesrc = GST_PULSESRC_CAST (asrc);
1509   pa_operation *o = NULL;
1510
1511   pa_threaded_mainloop_lock (pulsesrc->mainloop);
1512   GST_DEBUG_OBJECT (pulsesrc, "reset");
1513
1514   if (gst_pulsesrc_is_dead (pulsesrc, TRUE))
1515     goto unlock_and_fail;
1516
1517   if (!(o =
1518           pa_stream_flush (pulsesrc->stream, gst_pulsesrc_success_cb,
1519               pulsesrc))) {
1520     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED,
1521         ("pa_stream_flush() failed: %s",
1522             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
1523     goto unlock_and_fail;
1524   }
1525
1526   pulsesrc->paused = TRUE;
1527   /* Inform anyone waiting in _write() call that it shall wakeup */
1528   if (pulsesrc->in_read) {
1529     pa_threaded_mainloop_signal (pulsesrc->mainloop, 0);
1530   }
1531
1532   pulsesrc->operation_success = FALSE;
1533   while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
1534
1535     if (gst_pulsesrc_is_dead (pulsesrc, TRUE))
1536       goto unlock_and_fail;
1537
1538     pa_threaded_mainloop_wait (pulsesrc->mainloop);
1539   }
1540
1541   if (!pulsesrc->operation_success) {
1542     GST_ELEMENT_ERROR (pulsesrc, RESOURCE, FAILED, ("Flush failed: %s",
1543             pa_strerror (pa_context_errno (pulsesrc->context))), (NULL));
1544     goto unlock_and_fail;
1545   }
1546
1547 unlock_and_fail:
1548
1549   if (o) {
1550     pa_operation_cancel (o);
1551     pa_operation_unref (o);
1552   }
1553
1554   pa_threaded_mainloop_unlock (pulsesrc->mainloop);
1555 }
1556
1557 /* update the corked state of a stream, must be called with the mainloop
1558  * lock */
1559 static gboolean
1560 gst_pulsesrc_set_corked (GstPulseSrc * psrc, gboolean corked, gboolean wait)
1561 {
1562   pa_operation *o = NULL;
1563   gboolean res = FALSE;
1564
1565   GST_DEBUG_OBJECT (psrc, "setting corked state to %d", corked);
1566   if (!psrc->stream_connected)
1567     return TRUE;
1568
1569   if (psrc->corked != corked) {
1570     if (!(o = pa_stream_cork (psrc->stream, corked,
1571                 gst_pulsesrc_success_cb, psrc)))
1572       goto cork_failed;
1573
1574     while (wait && pa_operation_get_state (o) == PA_OPERATION_RUNNING) {
1575       pa_threaded_mainloop_wait (psrc->mainloop);
1576       if (gst_pulsesrc_is_dead (psrc, TRUE))
1577         goto server_dead;
1578     }
1579     psrc->corked = corked;
1580   } else {
1581     GST_DEBUG_OBJECT (psrc, "skipping, already in requested state");
1582   }
1583   res = TRUE;
1584
1585 cleanup:
1586   if (o)
1587     pa_operation_unref (o);
1588
1589   return res;
1590
1591   /* ERRORS */
1592 server_dead:
1593   {
1594     GST_DEBUG_OBJECT (psrc, "the server is dead");
1595     goto cleanup;
1596   }
1597 cork_failed:
1598   {
1599     GST_ELEMENT_ERROR (psrc, RESOURCE, FAILED,
1600         ("pa_stream_cork() failed: %s",
1601             pa_strerror (pa_context_errno (psrc->context))), (NULL));
1602     goto cleanup;
1603   }
1604 }
1605
1606 /* start/resume playback ASAP */
1607 static gboolean
1608 gst_pulsesrc_play (GstPulseSrc * psrc)
1609 {
1610   pa_threaded_mainloop_lock (psrc->mainloop);
1611   GST_DEBUG_OBJECT (psrc, "playing");
1612   psrc->paused = FALSE;
1613   gst_pulsesrc_set_corked (psrc, FALSE, FALSE);
1614   pa_threaded_mainloop_unlock (psrc->mainloop);
1615
1616   return TRUE;
1617 }
1618
1619 /* pause/stop playback ASAP */
1620 static gboolean
1621 gst_pulsesrc_pause (GstPulseSrc * psrc)
1622 {
1623   pa_threaded_mainloop_lock (psrc->mainloop);
1624   GST_DEBUG_OBJECT (psrc, "pausing");
1625   /* make sure the commit method stops writing */
1626   psrc->paused = TRUE;
1627   if (psrc->in_read) {
1628     /* we are waiting in a read, signal */
1629     GST_DEBUG_OBJECT (psrc, "signal read");
1630     pa_threaded_mainloop_signal (psrc->mainloop, 0);
1631   }
1632   pa_threaded_mainloop_unlock (psrc->mainloop);
1633
1634   return TRUE;
1635 }
1636
1637 static GstStateChangeReturn
1638 gst_pulsesrc_change_state (GstElement * element, GstStateChange transition)
1639 {
1640   GstStateChangeReturn ret;
1641   GstPulseSrc *this = GST_PULSESRC_CAST (element);
1642
1643   switch (transition) {
1644     case GST_STATE_CHANGE_NULL_TO_READY:
1645       if (!(this->mainloop = pa_threaded_mainloop_new ()))
1646         goto mainloop_failed;
1647       if (pa_threaded_mainloop_start (this->mainloop) < 0) {
1648         pa_threaded_mainloop_free (this->mainloop);
1649         this->mainloop = NULL;
1650         goto mainloop_start_failed;
1651       }
1652       break;
1653     case GST_STATE_CHANGE_READY_TO_PAUSED:
1654       gst_element_post_message (element,
1655           gst_message_new_clock_provide (GST_OBJECT_CAST (element),
1656               GST_AUDIO_BASE_SRC (this)->clock, TRUE));
1657       break;
1658     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1659       /* uncork and start recording */
1660       gst_pulsesrc_play (this);
1661       break;
1662     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1663       /* stop recording ASAP by corking */
1664       pa_threaded_mainloop_lock (this->mainloop);
1665       GST_DEBUG_OBJECT (this, "corking");
1666       gst_pulsesrc_set_corked (this, TRUE, FALSE);
1667       pa_threaded_mainloop_unlock (this->mainloop);
1668       break;
1669     default:
1670       break;
1671   }
1672
1673   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1674
1675   switch (transition) {
1676     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1677       /* now make sure we get out of the _read method */
1678       gst_pulsesrc_pause (this);
1679       break;
1680     case GST_STATE_CHANGE_READY_TO_NULL:
1681       if (this->mainloop)
1682         pa_threaded_mainloop_stop (this->mainloop);
1683
1684       gst_pulsesrc_destroy_context (this);
1685
1686       if (this->mainloop) {
1687         pa_threaded_mainloop_free (this->mainloop);
1688         this->mainloop = NULL;
1689       }
1690       break;
1691     case GST_STATE_CHANGE_PAUSED_TO_READY:
1692       /* format_lost is reset in release() in baseaudiosink */
1693       gst_element_post_message (element,
1694           gst_message_new_clock_lost (GST_OBJECT_CAST (element),
1695               GST_AUDIO_BASE_SRC (this)->clock));
1696       break;
1697     default:
1698       break;
1699   }
1700
1701   return ret;
1702
1703   /* ERRORS */
1704 mainloop_failed:
1705   {
1706     GST_ELEMENT_ERROR (this, RESOURCE, FAILED,
1707         ("pa_threaded_mainloop_new() failed"), (NULL));
1708     return GST_STATE_CHANGE_FAILURE;
1709   }
1710 mainloop_start_failed:
1711   {
1712     GST_ELEMENT_ERROR (this, RESOURCE, FAILED,
1713         ("pa_threaded_mainloop_start() failed"), (NULL));
1714     return GST_STATE_CHANGE_FAILURE;
1715   }
1716 }
1717
1718 static GstClockTime
1719 gst_pulsesrc_get_time (GstClock * clock, GstPulseSrc * src)
1720 {
1721   pa_usec_t time = 0;
1722
1723   pa_threaded_mainloop_lock (src->mainloop);
1724
1725   if (gst_pulsesrc_is_dead (src, TRUE)) {
1726     goto unlock_and_out;
1727   }
1728
1729   if (pa_stream_get_time (src->stream, &time) < 0) {
1730     GST_DEBUG_OBJECT (src, "could not get time");
1731     time = GST_CLOCK_TIME_NONE;
1732   } else {
1733     time *= 1000;
1734   }
1735
1736
1737 unlock_and_out:
1738   pa_threaded_mainloop_unlock (src->mainloop);
1739
1740   return time;
1741 }