636b413c3b0b179caadeeced1d83212bbf9d2def
[profile/ivi/pulseaudio-panda.git] / src / modules / module-alsa-sink.c
1 /* $Id$ */
2
3 /***
4   This file is part of PulseAudio.
5
6   Copyright 2004-2006 Lennart Poettering
7   Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
8
9   PulseAudio is free software; you can redistribute it and/or modify
10   it under the terms of the GNU Lesser General Public License as published
11   by the Free Software Foundation; either version 2 of the License,
12   or (at your option) any later version.
13
14   PulseAudio is distributed in the hope that it will be useful, but
15   WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17   General Public License for more details.
18
19   You should have received a copy of the GNU Lesser General Public License
20   along with PulseAudio; if not, write to the Free Software
21   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
22   USA.
23 ***/
24
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28
29 #include <stdio.h>
30
31 #include <asoundlib.h>
32
33 #include <pulse/xmalloc.h>
34 #include <pulse/util.h>
35
36 #include <pulsecore/core.h>
37 #include <pulsecore/module.h>
38 #include <pulsecore/memchunk.h>
39 #include <pulsecore/sink.h>
40 #include <pulsecore/modargs.h>
41 #include <pulsecore/core-util.h>
42 #include <pulsecore/sample-util.h>
43 #include <pulsecore/log.h>
44 #include <pulsecore/macro.h>
45 #include <pulsecore/thread.h>
46 #include <pulsecore/core-error.h>
47 #include <pulsecore/thread-mq.h>
48 #include <pulsecore/rtpoll.h>
49
50 #include "alsa-util.h"
51 #include "module-alsa-sink-symdef.h"
52
53 PA_MODULE_AUTHOR("Lennart Poettering");
54 PA_MODULE_DESCRIPTION("ALSA Sink");
55 PA_MODULE_VERSION(PACKAGE_VERSION);
56 PA_MODULE_LOAD_ONCE(FALSE);
57 PA_MODULE_USAGE(
58         "sink_name=<name for the sink> "
59         "device=<ALSA device> "
60         "format=<sample format> "
61         "channels=<number of channels> "
62         "rate=<sample rate> "
63         "fragments=<number of fragments> "
64         "fragment_size=<fragment size> "
65         "channel_map=<channel map> "
66         "mmap=<enable memory mapping?>");
67
68 #define DEFAULT_DEVICE "default"
69
70 struct userdata {
71     pa_core *core;
72     pa_module *module;
73     pa_sink *sink;
74
75     pa_thread *thread;
76     pa_thread_mq thread_mq;
77     pa_rtpoll *rtpoll;
78
79     snd_pcm_t *pcm_handle;
80
81     pa_alsa_fdlist *mixer_fdl;
82     snd_mixer_t *mixer_handle;
83     snd_mixer_elem_t *mixer_elem;
84     long hw_volume_max, hw_volume_min;
85
86     size_t frame_size, fragment_size, hwbuf_size;
87     unsigned nfragments;
88     pa_memchunk memchunk;
89
90     char *device_name;
91
92     int use_mmap;
93
94     int first;
95
96     pa_rtpoll_item *alsa_rtpoll_item;
97 };
98
99 static const char* const valid_modargs[] = {
100     "device",
101     "sink_name",
102     "format",
103     "channels",
104     "rate",
105     "fragments",
106     "fragment_size",
107     "channel_map",
108     "mmap",
109     NULL
110 };
111
112 static int mmap_write(struct userdata *u) {
113     int work_done = 0;
114
115     pa_assert(u);
116     pa_sink_assert_ref(u->sink);
117
118     for (;;) {
119         pa_memchunk chunk;
120         void *p;
121         snd_pcm_sframes_t n;
122         int err;
123         const snd_pcm_channel_area_t *areas;
124         snd_pcm_uframes_t offset, frames;
125
126         if ((n = snd_pcm_avail_update(u->pcm_handle)) < 0) {
127
128             if (n == -EPIPE) {
129                 pa_log_debug("snd_pcm_avail_update: Buffer underrun!");
130                 u->first = 1;
131             }
132
133             if ((err = snd_pcm_recover(u->pcm_handle, n, 1)) == 0)
134                 continue;
135
136             if (err == -EAGAIN)
137                 return work_done;
138
139             pa_log("snd_pcm_avail_update: %s", snd_strerror(err));
140             return -1;
141         }
142
143 /*         pa_log("Got request for %i samples", (int) n); */
144
145         if (n <= 0)
146             return work_done;
147
148         frames = n;
149
150         if ((err = snd_pcm_mmap_begin(u->pcm_handle, &areas, &offset, &frames)) < 0) {
151
152             if (err == -EPIPE) {
153                 pa_log_debug("snd_pcm_mmap_begin: Buffer underrun!");
154                 u->first = 1;
155             }
156
157             if ((err = snd_pcm_recover(u->pcm_handle, err, 1)) == 0)
158                 continue;
159
160             if (err == -EAGAIN)
161                 return work_done;
162
163             pa_log("Failed to write data to DSP: %s", snd_strerror(err));
164             return -1;
165         }
166
167         /* Check these are multiples of 8 bit */
168         pa_assert((areas[0].first & 7) == 0);
169         pa_assert((areas[0].step & 7)== 0);
170
171         /* We assume a single interleaved memory buffer */
172         pa_assert((areas[0].first >> 3) == 0);
173         pa_assert((areas[0].step >> 3) == u->frame_size);
174
175         p = (uint8_t*) areas[0].addr + (offset * u->frame_size);
176
177         chunk.memblock = pa_memblock_new_fixed(u->core->mempool, p, frames * u->frame_size, 1);
178         chunk.length = pa_memblock_get_length(chunk.memblock);
179         chunk.index = 0;
180
181         pa_sink_render_into_full(u->sink, &chunk);
182
183         /* FIXME: Maybe we can do something to keep this memory block
184          * a little bit longer around? */
185         pa_memblock_unref_fixed(chunk.memblock);
186
187         if ((err = snd_pcm_mmap_commit(u->pcm_handle, offset, frames)) < 0) {
188
189             if (err == -EPIPE) {
190                 pa_log_debug("snd_pcm_mmap_commit: Buffer underrun!");
191                 u->first = 1;
192             }
193
194             if ((err = snd_pcm_recover(u->pcm_handle, err, 1)) == 0)
195                 continue;
196
197             if (err == -EAGAIN)
198                 return work_done;
199
200             pa_log("Failed to write data to DSP: %s", snd_strerror(err));
201             return -1;
202         }
203
204         work_done = 1;
205
206         if (frames >= (snd_pcm_uframes_t) n)
207             return work_done;
208
209 /*         pa_log("wrote %i samples", (int) frames); */
210     }
211 }
212
213 static int unix_write(struct userdata *u) {
214     snd_pcm_status_t *status;
215     int work_done = 0;
216
217     snd_pcm_status_alloca(&status);
218
219     pa_assert(u);
220     pa_sink_assert_ref(u->sink);
221
222     for (;;) {
223         void *p;
224         snd_pcm_sframes_t t;
225         ssize_t l;
226         int err;
227
228         if ((err = snd_pcm_status(u->pcm_handle, status)) < 0) {
229             pa_log("Failed to query DSP status data: %s", snd_strerror(err));
230             return -1;
231         }
232
233         if (snd_pcm_status_get_avail_max(status)*u->frame_size >= u->hwbuf_size)
234             pa_log_debug("Buffer underrun!");
235
236         l = snd_pcm_status_get_avail(status) * u->frame_size;
237
238 /*         pa_log("%u bytes to write", l); */
239
240         if (l <= 0)
241             return work_done;
242
243         if (u->memchunk.length <= 0)
244             pa_sink_render(u->sink, l, &u->memchunk);
245
246         pa_assert(u->memchunk.length > 0);
247
248         p = pa_memblock_acquire(u->memchunk.memblock);
249         t = snd_pcm_writei(u->pcm_handle, (const uint8_t*) p + u->memchunk.index, u->memchunk.length / u->frame_size);
250         pa_memblock_release(u->memchunk.memblock);
251
252 /*         pa_log("wrote %i bytes of %u (%u)", t*u->frame_size, u->memchunk.length, l); */
253
254         pa_assert(t != 0);
255
256         if (t < 0) {
257
258             if ((t = snd_pcm_recover(u->pcm_handle, t, 1)) == 0)
259                 continue;
260
261             if (t == -EAGAIN) {
262                 pa_log_debug("EAGAIN");
263                 return work_done;
264             } else {
265                 pa_log("Failed to write data to DSP: %s", snd_strerror(t));
266                 return -1;
267             }
268         }
269
270         u->memchunk.index += t * u->frame_size;
271         u->memchunk.length -= t * u->frame_size;
272
273         if (u->memchunk.length <= 0) {
274             pa_memblock_unref(u->memchunk.memblock);
275             pa_memchunk_reset(&u->memchunk);
276         }
277
278         work_done = 1;
279
280         if (t * u->frame_size >= (unsigned) l)
281             return work_done;
282     }
283 }
284
285 static pa_usec_t sink_get_latency(struct userdata *u) {
286     pa_usec_t r = 0;
287     snd_pcm_status_t *status;
288     snd_pcm_sframes_t frames = 0;
289     int err;
290
291     snd_pcm_status_alloca(&status);
292
293     pa_assert(u);
294     pa_assert(u->pcm_handle);
295
296     if ((err = snd_pcm_status(u->pcm_handle, status)) < 0)
297         pa_log("Failed to get delay: %s", snd_strerror(err));
298     else
299         frames = snd_pcm_status_get_delay(status);
300
301     if (frames > 0)
302         r = pa_bytes_to_usec(frames * u->frame_size, &u->sink->sample_spec);
303
304     if (u->memchunk.memblock)
305         r += pa_bytes_to_usec(u->memchunk.length, &u->sink->sample_spec);
306
307     return r;
308 }
309
310 static int build_pollfd(struct userdata *u) {
311     int err;
312     struct pollfd *pollfd;
313     int n;
314
315     pa_assert(u);
316     pa_assert(u->pcm_handle);
317
318     if ((n = snd_pcm_poll_descriptors_count(u->pcm_handle)) < 0) {
319         pa_log("snd_pcm_poll_descriptors_count() failed: %s", snd_strerror(n));
320         return -1;
321     }
322
323     if (u->alsa_rtpoll_item)
324         pa_rtpoll_item_free(u->alsa_rtpoll_item);
325
326     u->alsa_rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, n);
327     pollfd = pa_rtpoll_item_get_pollfd(u->alsa_rtpoll_item, NULL);
328
329     if ((err = snd_pcm_poll_descriptors(u->pcm_handle, pollfd, n)) < 0) {
330         pa_log("snd_pcm_poll_descriptors() failed: %s", snd_strerror(err));
331         return -1;
332     }
333
334     return 0;
335 }
336
337 static int suspend(struct userdata *u) {
338     pa_assert(u);
339     pa_assert(u->pcm_handle);
340
341     /* Let's suspend */
342     snd_pcm_drain(u->pcm_handle);
343     snd_pcm_close(u->pcm_handle);
344     u->pcm_handle = NULL;
345
346     if (u->alsa_rtpoll_item) {
347         pa_rtpoll_item_free(u->alsa_rtpoll_item);
348         u->alsa_rtpoll_item = NULL;
349     }
350
351     pa_log_info("Device suspended...");
352
353     return 0;
354 }
355
356 static int unsuspend(struct userdata *u) {
357     pa_sample_spec ss;
358     int err, b;
359     unsigned nfrags;
360     snd_pcm_uframes_t period_size;
361
362     pa_assert(u);
363     pa_assert(!u->pcm_handle);
364
365     pa_log_info("Trying resume...");
366
367     snd_config_update_free_global();
368     if ((err = snd_pcm_open(&u->pcm_handle, u->device_name, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK)) < 0) {
369         pa_log("Error opening PCM device %s: %s", u->device_name, snd_strerror(err));
370         goto fail;
371     }
372
373     ss = u->sink->sample_spec;
374     nfrags = u->nfragments;
375     period_size = u->fragment_size / u->frame_size;
376     b = u->use_mmap;
377
378     if ((err = pa_alsa_set_hw_params(u->pcm_handle, &ss, &nfrags, &period_size, &b)) < 0) {
379         pa_log("Failed to set hardware parameters: %s", snd_strerror(err));
380         goto fail;
381     }
382
383     if (b != u->use_mmap) {
384         pa_log_warn("Resume failed, couldn't get original access mode.");
385         goto fail;
386     }
387
388     if (!pa_sample_spec_equal(&ss, &u->sink->sample_spec)) {
389         pa_log_warn("Resume failed, couldn't restore original sample settings.");
390         goto fail;
391     }
392
393     if (nfrags != u->nfragments || period_size*u->frame_size != u->fragment_size) {
394         pa_log_warn("Resume failed, couldn't restore original fragment settings.");
395         goto fail;
396     }
397
398     if ((err = pa_alsa_set_sw_params(u->pcm_handle)) < 0) {
399         pa_log("Failed to set software parameters: %s", snd_strerror(err));
400         goto fail;
401     }
402
403     if (build_pollfd(u) < 0)
404         goto fail;
405
406     /* FIXME: We need to reload the volume somehow */
407
408     u->first = 1;
409
410     pa_log_info("Resumed successfully...");
411
412     return 0;
413
414 fail:
415     if (u->pcm_handle) {
416         snd_pcm_close(u->pcm_handle);
417         u->pcm_handle = NULL;
418     }
419
420     return -1;
421 }
422
423 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
424     struct userdata *u = PA_SINK(o)->userdata;
425
426     switch (code) {
427
428         case PA_SINK_MESSAGE_GET_LATENCY: {
429             pa_usec_t r = 0;
430
431             if (u->pcm_handle)
432                 r = sink_get_latency(u);
433
434             *((pa_usec_t*) data) = r;
435
436             return 0;
437         }
438
439         case PA_SINK_MESSAGE_SET_STATE:
440
441             switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
442
443                 case PA_SINK_SUSPENDED:
444                     pa_assert(PA_SINK_OPENED(u->sink->thread_info.state));
445
446                     if (suspend(u) < 0)
447                         return -1;
448
449                     break;
450
451                 case PA_SINK_IDLE:
452                 case PA_SINK_RUNNING:
453
454                     if (u->sink->thread_info.state == PA_SINK_INIT) {
455                         if (build_pollfd(u) < 0)
456                             return -1;
457                     }
458
459                     if (u->sink->thread_info.state == PA_SINK_SUSPENDED) {
460                         if (unsuspend(u) < 0)
461                             return -1;
462                     }
463
464                     break;
465
466                 case PA_SINK_UNLINKED:
467                 case PA_SINK_INIT:
468                     ;
469             }
470
471             break;
472     }
473
474     return pa_sink_process_msg(o, code, data, offset, chunk);
475 }
476
477 static int mixer_callback(snd_mixer_elem_t *elem, unsigned int mask) {
478     struct userdata *u = snd_mixer_elem_get_callback_private(elem);
479
480     pa_assert(u);
481     pa_assert(u->mixer_handle);
482
483     if (mask == SND_CTL_EVENT_MASK_REMOVE)
484         return 0;
485
486     if (mask & SND_CTL_EVENT_MASK_VALUE) {
487         pa_sink_get_volume(u->sink);
488         pa_sink_get_mute(u->sink);
489     }
490
491     return 0;
492 }
493
494 static int sink_get_volume_cb(pa_sink *s) {
495     struct userdata *u = s->userdata;
496     int err;
497     int i;
498
499     pa_assert(u);
500     pa_assert(u->mixer_elem);
501
502     for (i = 0; i < s->sample_spec.channels; i++) {
503         long set_vol, vol;
504
505         pa_assert(snd_mixer_selem_has_playback_channel(u->mixer_elem, i));
506
507         if ((err = snd_mixer_selem_get_playback_volume(u->mixer_elem, i, &vol)) < 0)
508             goto fail;
509
510         set_vol = (long) roundf(((float) s->volume.values[i] * (u->hw_volume_max - u->hw_volume_min)) / PA_VOLUME_NORM) + u->hw_volume_min;
511
512         /* Try to avoid superfluous volume changes */
513         if (set_vol != vol)
514             s->volume.values[i] = (pa_volume_t) roundf(((float) (vol - u->hw_volume_min) * PA_VOLUME_NORM) / (u->hw_volume_max - u->hw_volume_min));
515     }
516
517     return 0;
518
519 fail:
520     pa_log_error("Unable to read volume: %s", snd_strerror(err));
521
522     s->get_volume = NULL;
523     s->set_volume = NULL;
524     return -1;
525 }
526
527 static int sink_set_volume_cb(pa_sink *s) {
528     struct userdata *u = s->userdata;
529     int err;
530     int i;
531
532     pa_assert(u);
533     pa_assert(u->mixer_elem);
534
535     for (i = 0; i < s->sample_spec.channels; i++) {
536         long alsa_vol;
537         pa_volume_t vol;
538
539         pa_assert(snd_mixer_selem_has_playback_channel(u->mixer_elem, i));
540
541         vol = s->volume.values[i];
542
543         if (vol > PA_VOLUME_NORM)
544             vol = PA_VOLUME_NORM;
545
546         alsa_vol = (long) roundf(((float) vol * (u->hw_volume_max - u->hw_volume_min)) / PA_VOLUME_NORM) + u->hw_volume_min;
547
548         if ((err = snd_mixer_selem_set_playback_volume(u->mixer_elem, i, alsa_vol)) < 0)
549             goto fail;
550     }
551
552     return 0;
553
554 fail:
555     pa_log_error("Unable to set volume: %s", snd_strerror(err));
556
557     s->get_volume = NULL;
558     s->set_volume = NULL;
559     return -1;
560 }
561
562 static int sink_get_mute_cb(pa_sink *s) {
563     struct userdata *u = s->userdata;
564     int err, sw;
565
566     pa_assert(u);
567     pa_assert(u->mixer_elem);
568
569     if ((err = snd_mixer_selem_get_playback_switch(u->mixer_elem, 0, &sw)) < 0) {
570         pa_log_error("Unable to get switch: %s", snd_strerror(err));
571
572         s->get_mute = NULL;
573         s->set_mute = NULL;
574         return -1;
575     }
576
577     s->muted = !sw;
578
579     return 0;
580 }
581
582 static int sink_set_mute_cb(pa_sink *s) {
583     struct userdata *u = s->userdata;
584     int err;
585
586     pa_assert(u);
587     pa_assert(u->mixer_elem);
588
589     if ((err = snd_mixer_selem_set_playback_switch_all(u->mixer_elem, !s->muted)) < 0) {
590         pa_log_error("Unable to set switch: %s", snd_strerror(err));
591
592         s->get_mute = NULL;
593         s->set_mute = NULL;
594         return -1;
595     }
596
597     return 0;
598 }
599
600 static void thread_func(void *userdata) {
601     struct userdata *u = userdata;
602
603     pa_assert(u);
604
605     pa_log_debug("Thread starting up");
606
607     if (u->core->realtime_scheduling)
608         pa_make_realtime(u->core->realtime_priority);
609
610     pa_thread_mq_install(&u->thread_mq);
611     pa_rtpoll_install(u->rtpoll);
612
613     for (;;) {
614         int ret;
615
616         /* Render some data and write it to the dsp */
617         if (PA_SINK_OPENED(u->sink->thread_info.state)) {
618             int work_done = 0;
619
620             if (u->use_mmap) {
621                 if ((work_done = mmap_write(u)) < 0)
622                     goto fail;
623             } else {
624                 if ((work_done = unix_write(u)) < 0)
625                     goto fail;
626             }
627
628             if (work_done && u->first) {
629                 pa_log_info("Starting playback.");
630                 snd_pcm_start(u->pcm_handle);
631                 u->first = 0;
632                 continue;
633             }
634         }
635
636         /* Hmm, nothing to do. Let's sleep */
637         if ((ret = pa_rtpoll_run(u->rtpoll, 1)) < 0)
638             goto fail;
639
640         if (ret == 0)
641             goto finish;
642
643         /* Tell ALSA about this and process its response */
644         if (PA_SINK_OPENED(u->sink->thread_info.state)) {
645             struct pollfd *pollfd;
646             unsigned short revents = 0;
647             int err;
648             unsigned n;
649
650             pollfd = pa_rtpoll_item_get_pollfd(u->alsa_rtpoll_item, &n);
651
652             if ((err = snd_pcm_poll_descriptors_revents(u->pcm_handle, pollfd, n, &revents)) < 0) {
653                 pa_log("snd_pcm_poll_descriptors_revents() failed: %s", snd_strerror(err));
654                 goto fail;
655             }
656
657             if (revents & (POLLERR|POLLNVAL|POLLHUP)) {
658
659                 if (revents & POLLERR)
660                     pa_log_warn("Got POLLERR from ALSA");
661                 if (revents & POLLNVAL)
662                     pa_log_warn("Got POLLNVAL from ALSA");
663                 if (revents & POLLHUP)
664                     pa_log_warn("Got POLLHUP from ALSA");
665
666                 /* Try to recover from this error */
667
668                 switch (snd_pcm_state(u->pcm_handle)) {
669
670                     case SND_PCM_STATE_XRUN:
671                         if ((err = snd_pcm_recover(u->pcm_handle, -EPIPE, 1)) != 0) {
672                             pa_log_warn("Could not recover from POLLERR|POLLNVAL|POLLHUP and XRUN: %s", snd_strerror(err));
673                             goto fail;
674                         }
675                         break;
676
677                     case SND_PCM_STATE_SUSPENDED:
678                         if ((err = snd_pcm_recover(u->pcm_handle, -ESTRPIPE, 1)) != 0) {
679                             pa_log_warn("Could not recover from POLLERR|POLLNVAL|POLLHUP and SUSPENDED: %s", snd_strerror(err));
680                             goto fail;
681                         }
682                         break;
683
684                     default:
685
686                         snd_pcm_drop(u->pcm_handle);
687
688                         if ((err = snd_pcm_prepare(u->pcm_handle)) < 0) {
689                             pa_log_warn("Could not recover from POLLERR|POLLNVAL|POLLHUP with snd_pcm_prepare(): %s", snd_strerror(err));
690                             goto fail;
691                         }
692                         break;
693                 }
694             }
695         }
696     }
697
698 fail:
699     /* If this was no regular exit from the loop we have to continue
700      * processing messages until we received PA_MESSAGE_SHUTDOWN */
701     pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
702     pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
703
704 finish:
705     pa_log_debug("Thread shutting down");
706 }
707
708 int pa__init(pa_module*m) {
709
710     pa_modargs *ma = NULL;
711     struct userdata *u = NULL;
712     char *dev;
713     pa_sample_spec ss;
714     pa_channel_map map;
715     uint32_t nfrags, frag_size;
716     snd_pcm_uframes_t period_size;
717     size_t frame_size;
718     snd_pcm_info_t *pcm_info = NULL;
719     int err;
720     char *t;
721     const char *name;
722     char *name_buf = NULL;
723     int namereg_fail;
724     int use_mmap = 1, b;
725
726     snd_pcm_info_alloca(&pcm_info);
727
728     pa_assert(m);
729
730     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
731         pa_log("Failed to parse module arguments");
732         goto fail;
733     }
734
735     ss = m->core->default_sample_spec;
736     if (pa_modargs_get_sample_spec_and_channel_map(ma, &ss, &map, PA_CHANNEL_MAP_ALSA) < 0) {
737         pa_log("Failed to parse sample specification and channel map");
738         goto fail;
739     }
740
741     frame_size = pa_frame_size(&ss);
742
743     nfrags = m->core->default_n_fragments;
744     frag_size = pa_usec_to_bytes(m->core->default_fragment_size_msec*1000, &ss);
745     if (frag_size <= 0)
746         frag_size = frame_size;
747
748     if (pa_modargs_get_value_u32(ma, "fragments", &nfrags) < 0 || pa_modargs_get_value_u32(ma, "fragment_size", &frag_size) < 0) {
749         pa_log("Failed to parse buffer metrics");
750         goto fail;
751     }
752     period_size = frag_size/frame_size;
753
754     if (pa_modargs_get_value_boolean(ma, "mmap", &use_mmap) < 0) {
755         pa_log("Failed to parse mmap argument.");
756         goto fail;
757     }
758
759     u = pa_xnew0(struct userdata, 1);
760     u->core = m->core;
761     u->module = m;
762     m->userdata = u;
763     u->use_mmap = use_mmap;
764     u->first = 1;
765     pa_thread_mq_init(&u->thread_mq, m->core->mainloop);
766     u->rtpoll = pa_rtpoll_new();
767     u->alsa_rtpoll_item = NULL;
768     pa_rtpoll_item_new_asyncmsgq(u->rtpoll, PA_RTPOLL_EARLY, u->thread_mq.inq);
769
770     snd_config_update_free_global();
771
772     dev = pa_xstrdup(pa_modargs_get_value(ma, "device", DEFAULT_DEVICE));
773
774     for (;;) {
775
776         if ((err = snd_pcm_open(&u->pcm_handle, dev, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK)) < 0) {
777             pa_log("Error opening PCM device %s: %s", dev, snd_strerror(err));
778             pa_xfree(dev);
779             goto fail;
780         }
781
782         b = use_mmap;
783         if ((err = pa_alsa_set_hw_params(u->pcm_handle, &ss, &nfrags, &period_size, &b)) < 0) {
784
785             if (err == -EPERM) {
786                 /* Hmm, some hw is very exotic, so we retry with plughw, if hw didn't work */
787
788                 if (pa_startswith(dev, "hw:")) {
789                     char *d = pa_sprintf_malloc("plughw:%s", dev+3);
790                     pa_log_debug("Opening the device as '%s' didn't work, retrying with '%s'.", dev, d);
791                     pa_xfree(dev);
792                     dev = d;
793
794                     snd_pcm_close(u->pcm_handle);
795                     u->pcm_handle = NULL;
796                     continue;
797                 }
798             }
799
800             pa_log("Failed to set hardware parameters: %s", snd_strerror(err));
801             pa_xfree(dev);
802             goto fail;
803         }
804
805         break;
806     }
807
808     u->device_name = dev;
809
810     if (use_mmap && !b) {
811         pa_log_info("Device doesn't support mmap(), falling back to UNIX read/write mode.");
812         u->use_mmap = use_mmap = b;
813     }
814
815     if (u->use_mmap)
816         pa_log_info("Successfully enabled mmap() mode.");
817
818     if ((err = snd_pcm_info(u->pcm_handle, pcm_info)) < 0) {
819         pa_log("Error fetching PCM info: %s", snd_strerror(err));
820         goto fail;
821     }
822
823     if ((err = pa_alsa_set_sw_params(u->pcm_handle)) < 0) {
824         pa_log("Failed to set software parameters: %s", snd_strerror(err));
825         goto fail;
826     }
827
828     /* ALSA might tweak the sample spec, so recalculate the frame size */
829     frame_size = pa_frame_size(&ss);
830
831     if (ss.channels != map.channels)
832         /* Seems ALSA didn't like the channel number, so let's fix the channel map */
833         pa_channel_map_init_auto(&map, ss.channels, PA_CHANNEL_MAP_ALSA);
834
835     if ((err = snd_mixer_open(&u->mixer_handle, 0)) < 0)
836         pa_log_warn("Error opening mixer: %s", snd_strerror(err));
837     else {
838
839         if ((pa_alsa_prepare_mixer(u->mixer_handle, dev) < 0) ||
840             !(u->mixer_elem = pa_alsa_find_elem(u->mixer_handle, "Master", "PCM"))) {
841
842             snd_mixer_close(u->mixer_handle);
843             u->mixer_handle = NULL;
844         }
845     }
846
847     if ((name = pa_modargs_get_value(ma, "sink_name", NULL)))
848         namereg_fail = 1;
849     else {
850         name = name_buf = pa_sprintf_malloc("alsa_output.%s", dev);
851         namereg_fail = 0;
852     }
853
854     u->sink = pa_sink_new(m->core, __FILE__, name, namereg_fail, &ss, &map);
855     pa_xfree(name_buf);
856
857     if (!u->sink) {
858         pa_log("Failed to create sink object");
859         goto fail;
860     }
861
862     u->sink->parent.process_msg = sink_process_msg;
863     u->sink->userdata = u;
864
865     pa_sink_set_module(u->sink, m);
866     pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
867     pa_sink_set_rtpoll(u->sink, u->rtpoll);
868     pa_sink_set_description(u->sink, t = pa_sprintf_malloc(
869                                     "ALSA PCM on %s (%s)%s",
870                                     dev,
871                                     snd_pcm_info_get_name(pcm_info),
872                                     use_mmap ? " via DMA" : ""));
873     pa_xfree(t);
874
875     u->sink->flags = PA_SINK_HARDWARE|PA_SINK_HW_VOLUME_CTRL|PA_SINK_LATENCY;
876
877     u->frame_size = frame_size;
878     u->fragment_size = frag_size = period_size * frame_size;
879     u->nfragments = nfrags;
880     u->hwbuf_size = u->fragment_size * nfrags;
881
882     pa_log_info("Using %u fragments of size %lu bytes.", nfrags, (long unsigned) u->fragment_size);
883
884     pa_memchunk_reset(&u->memchunk);
885
886     if (u->mixer_handle) {
887         /* Initialize mixer code */
888
889         pa_assert(u->mixer_elem);
890
891         if (snd_mixer_selem_has_playback_volume(u->mixer_elem)) {
892             int i;
893
894             for (i = 0; i < ss.channels; i++)
895                 if (!snd_mixer_selem_has_playback_channel(u->mixer_elem, i))
896                     break;
897
898             if (i == ss.channels) {
899                 pa_log_debug("ALSA device has separate volumes controls for all %u channels.", ss.channels);
900                 u->sink->get_volume = sink_get_volume_cb;
901                 u->sink->set_volume = sink_set_volume_cb;
902                 snd_mixer_selem_get_playback_volume_range(u->mixer_elem, &u->hw_volume_min, &u->hw_volume_max);
903             } else
904                 pa_log_info("ALSA device lacks separate volumes controls for all %u channels (%u available), falling back to software volume control.", ss.channels, i+1);
905         }
906
907         if (snd_mixer_selem_has_playback_switch(u->mixer_elem)) {
908             u->sink->get_mute = sink_get_mute_cb;
909             u->sink->set_mute = sink_set_mute_cb;
910         }
911
912         u->mixer_fdl = pa_alsa_fdlist_new();
913
914         if (pa_alsa_fdlist_set_mixer(u->mixer_fdl, u->mixer_handle, m->core->mainloop) < 0) {
915             pa_log("failed to initialise file descriptor monitoring");
916             goto fail;
917         }
918
919         snd_mixer_elem_set_callback(u->mixer_elem, mixer_callback);
920         snd_mixer_elem_set_callback_private(u->mixer_elem, u);
921     } else
922         u->mixer_fdl = NULL;
923
924     if (!(u->thread = pa_thread_new(thread_func, u))) {
925         pa_log("Failed to create thread.");
926         goto fail;
927     }
928
929     /* Get initial mixer settings */
930     if (u->sink->get_volume)
931         u->sink->get_volume(u->sink);
932     if (u->sink->get_mute)
933         u->sink->get_mute(u->sink);
934
935     pa_sink_put(u->sink);
936
937     pa_modargs_free(ma);
938
939     return 0;
940
941 fail:
942
943     if (ma)
944         pa_modargs_free(ma);
945
946     pa__done(m);
947
948     return -1;
949 }
950
951 void pa__done(pa_module*m) {
952     struct userdata *u;
953
954     pa_assert(m);
955
956     if (!(u = m->userdata))
957         return;
958
959     if (u->sink)
960         pa_sink_unlink(u->sink);
961
962     if (u->thread) {
963         pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
964         pa_thread_free(u->thread);
965     }
966
967     pa_thread_mq_done(&u->thread_mq);
968
969     if (u->sink)
970         pa_sink_unref(u->sink);
971
972     if (u->memchunk.memblock)
973         pa_memblock_unref(u->memchunk.memblock);
974
975     if (u->alsa_rtpoll_item)
976         pa_rtpoll_item_free(u->alsa_rtpoll_item);
977
978     if (u->rtpoll)
979         pa_rtpoll_free(u->rtpoll);
980
981     if (u->mixer_fdl)
982         pa_alsa_fdlist_free(u->mixer_fdl);
983
984     if (u->mixer_handle)
985         snd_mixer_close(u->mixer_handle);
986
987     if (u->pcm_handle) {
988         snd_pcm_drop(u->pcm_handle);
989         snd_pcm_close(u->pcm_handle);
990     }
991
992     pa_xfree(u->device_name);
993     pa_xfree(u);
994
995     snd_config_update_free_global();
996 }