merged 15a_aqemu.patch audio patch (malc)
[qemu] / audio / alsaaudio.c
1 /*
2  * QEMU ALSA audio driver
3  *
4  * Copyright (c) 2005 Vassili Karpov (malc)
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include <alsa/asoundlib.h>
25 #include "vl.h"
26
27 #define AUDIO_CAP "alsa"
28 #include "audio_int.h"
29
30 typedef struct ALSAVoiceOut {
31     HWVoiceOut hw;
32     void *pcm_buf;
33     snd_pcm_t *handle;
34     int can_pause;
35     int was_enabled;
36 } ALSAVoiceOut;
37
38 typedef struct ALSAVoiceIn {
39     HWVoiceIn hw;
40     snd_pcm_t *handle;
41     void *pcm_buf;
42     int can_pause;
43 } ALSAVoiceIn;
44
45 static struct {
46     int size_in_usec_in;
47     int size_in_usec_out;
48     const char *pcm_name_in;
49     const char *pcm_name_out;
50     unsigned int buffer_size_in;
51     unsigned int period_size_in;
52     unsigned int buffer_size_out;
53     unsigned int period_size_out;
54     unsigned int threshold;
55
56     int buffer_size_in_overriden;
57     int period_size_in_overriden;
58
59     int buffer_size_out_overriden;
60     int period_size_out_overriden;
61 } conf = {
62 #ifdef HIGH_LATENCY
63     .size_in_usec_in = 1,
64     .size_in_usec_out = 1,
65 #endif
66     .pcm_name_out = "hw:0,0",
67     .pcm_name_in = "hw:0,0",
68 #ifdef HIGH_LATENCY
69     .buffer_size_in = 400000,
70     .period_size_in = 400000 / 4,
71     .buffer_size_out = 400000,
72     .period_size_out = 400000 / 4,
73 #else
74 #define DEFAULT_BUFFER_SIZE 1024
75 #define DEFAULT_PERIOD_SIZE 256
76     .buffer_size_in = DEFAULT_BUFFER_SIZE,
77     .period_size_in = DEFAULT_PERIOD_SIZE,
78     .buffer_size_out = DEFAULT_BUFFER_SIZE,
79     .period_size_out = DEFAULT_PERIOD_SIZE,
80     .buffer_size_in_overriden = 0,
81     .buffer_size_out_overriden = 0,
82     .period_size_in_overriden = 0,
83     .period_size_out_overriden = 0,
84 #endif
85     .threshold = 0
86 };
87
88 struct alsa_params_req {
89     int freq;
90     audfmt_e fmt;
91     int nchannels;
92     unsigned int buffer_size;
93     unsigned int period_size;
94 };
95
96 struct alsa_params_obt {
97     int freq;
98     audfmt_e fmt;
99     int nchannels;
100     int can_pause;
101     snd_pcm_uframes_t buffer_size;
102 };
103
104 static void GCC_FMT_ATTR (2, 3) alsa_logerr (int err, const char *fmt, ...)
105 {
106     va_list ap;
107
108     va_start (ap, fmt);
109     AUD_vlog (AUDIO_CAP, fmt, ap);
110     va_end (ap);
111
112     AUD_log (AUDIO_CAP, "Reason: %s\n", snd_strerror (err));
113 }
114
115 static void GCC_FMT_ATTR (3, 4) alsa_logerr2 (
116     int err,
117     const char *typ,
118     const char *fmt,
119     ...
120     )
121 {
122     va_list ap;
123
124     AUD_log (AUDIO_CAP, "Can not initialize %s\n", typ);
125
126     va_start (ap, fmt);
127     AUD_vlog (AUDIO_CAP, fmt, ap);
128     va_end (ap);
129
130     AUD_log (AUDIO_CAP, "Reason: %s\n", snd_strerror (err));
131 }
132
133 static void alsa_anal_close (snd_pcm_t **handlep)
134 {
135     int err = snd_pcm_close (*handlep);
136     if (err) {
137         alsa_logerr (err, "Failed to close PCM handle %p\n", *handlep);
138     }
139     *handlep = NULL;
140 }
141
142 static int alsa_write (SWVoiceOut *sw, void *buf, int len)
143 {
144     return audio_pcm_sw_write (sw, buf, len);
145 }
146
147 static int aud_to_alsafmt (audfmt_e fmt)
148 {
149     switch (fmt) {
150     case AUD_FMT_S8:
151         return SND_PCM_FORMAT_S8;
152
153     case AUD_FMT_U8:
154         return SND_PCM_FORMAT_U8;
155
156     case AUD_FMT_S16:
157         return SND_PCM_FORMAT_S16_LE;
158
159     case AUD_FMT_U16:
160         return SND_PCM_FORMAT_U16_LE;
161
162     default:
163         dolog ("Internal logic error: Bad audio format %d\n", fmt);
164 #ifdef DEBUG_AUDIO
165         abort ();
166 #endif
167         return SND_PCM_FORMAT_U8;
168     }
169 }
170
171 static int alsa_to_audfmt (int alsafmt, audfmt_e *fmt, int *endianness)
172 {
173     switch (alsafmt) {
174     case SND_PCM_FORMAT_S8:
175         *endianness = 0;
176         *fmt = AUD_FMT_S8;
177         break;
178
179     case SND_PCM_FORMAT_U8:
180         *endianness = 0;
181         *fmt = AUD_FMT_U8;
182         break;
183
184     case SND_PCM_FORMAT_S16_LE:
185         *endianness = 0;
186         *fmt = AUD_FMT_S16;
187         break;
188
189     case SND_PCM_FORMAT_U16_LE:
190         *endianness = 0;
191         *fmt = AUD_FMT_U16;
192         break;
193
194     case SND_PCM_FORMAT_S16_BE:
195         *endianness = 1;
196         *fmt = AUD_FMT_S16;
197         break;
198
199     case SND_PCM_FORMAT_U16_BE:
200         *endianness = 1;
201         *fmt = AUD_FMT_U16;
202         break;
203
204     default:
205         dolog ("Unrecognized audio format %d\n", alsafmt);
206         return -1;
207     }
208
209     return 0;
210 }
211
212 #ifdef DEBUG_MISMATCHES
213 static void alsa_dump_info (struct alsa_params_req *req,
214                             struct alsa_params_obt *obt)
215 {
216     dolog ("parameter | requested value | obtained value\n");
217     dolog ("format    |      %10d |     %10d\n", req->fmt, obt->fmt);
218     dolog ("channels  |      %10d |     %10d\n",
219            req->nchannels, obt->nchannels);
220     dolog ("frequency |      %10d |     %10d\n", req->freq, obt->freq);
221     dolog ("============================================\n");
222     dolog ("requested: buffer size %d period size %d\n",
223            req->buffer_size, req->period_size);
224     dolog ("obtained: buffer size %ld\n", obt->buffer_size);
225 }
226 #endif
227
228 static void alsa_set_threshold (snd_pcm_t *handle, snd_pcm_uframes_t threshold)
229 {
230     int err;
231     snd_pcm_sw_params_t *sw_params;
232
233     snd_pcm_sw_params_alloca (&sw_params);
234
235     err = snd_pcm_sw_params_current (handle, sw_params);
236     if (err < 0) {
237         dolog ("Can not fully initialize DAC\n");
238         alsa_logerr (err, "Failed to get current software parameters\n");
239         return;
240     }
241
242     err = snd_pcm_sw_params_set_start_threshold (handle, sw_params, threshold);
243     if (err < 0) {
244         dolog ("Can not fully initialize DAC\n");
245         alsa_logerr (err, "Failed to set software threshold to %ld\n",
246                      threshold);
247         return;
248     }
249
250     err = snd_pcm_sw_params (handle, sw_params);
251     if (err < 0) {
252         dolog ("Can not fully initialize DAC\n");
253         alsa_logerr (err, "Failed to set software parameters\n");
254         return;
255     }
256 }
257
258 static int alsa_open (int in, struct alsa_params_req *req,
259                       struct alsa_params_obt *obt, snd_pcm_t **handlep)
260 {
261     snd_pcm_t *handle;
262     snd_pcm_hw_params_t *hw_params;
263     int err, freq, nchannels;
264     const char *pcm_name = in ? conf.pcm_name_in : conf.pcm_name_out;
265     unsigned int period_size, buffer_size;
266     snd_pcm_uframes_t obt_buffer_size;
267     const char *typ = in ? "ADC" : "DAC";
268
269     freq = req->freq;
270     period_size = req->period_size;
271     buffer_size = req->buffer_size;
272     nchannels = req->nchannels;
273
274     snd_pcm_hw_params_alloca (&hw_params);
275
276     err = snd_pcm_open (
277         &handle,
278         pcm_name,
279         in ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
280         SND_PCM_NONBLOCK
281         );
282     if (err < 0) {
283         alsa_logerr2 (err, typ, "Failed to open `%s':\n", pcm_name);
284         return -1;
285     }
286
287     err = snd_pcm_hw_params_any (handle, hw_params);
288     if (err < 0) {
289         alsa_logerr2 (err, typ, "Failed to initialize hardware parameters\n");
290         goto err;
291     }
292
293     err = snd_pcm_hw_params_set_access (
294         handle,
295         hw_params,
296         SND_PCM_ACCESS_RW_INTERLEAVED
297         );
298     if (err < 0) {
299         alsa_logerr2 (err, typ, "Failed to set access type\n");
300         goto err;
301     }
302
303     err = snd_pcm_hw_params_set_format (handle, hw_params, req->fmt);
304     if (err < 0) {
305         alsa_logerr2 (err, typ, "Failed to set format %d\n", req->fmt);
306         goto err;
307     }
308
309     err = snd_pcm_hw_params_set_rate_near (handle, hw_params, &freq, 0);
310     if (err < 0) {
311         alsa_logerr2 (err, typ, "Failed to set frequency %d\n", req->freq);
312         goto err;
313     }
314
315     err = snd_pcm_hw_params_set_channels_near (
316         handle,
317         hw_params,
318         &nchannels
319         );
320     if (err < 0) {
321         alsa_logerr2 (err, typ, "Failed to set number of channels %d\n",
322                       req->nchannels);
323         goto err;
324     }
325
326     if (nchannels != 1 && nchannels != 2) {
327         alsa_logerr2 (err, typ,
328                       "Can not handle obtained number of channels %d\n",
329                       nchannels);
330         goto err;
331     }
332
333     if (!((in && conf.size_in_usec_in) || (!in && conf.size_in_usec_out))) {
334         if (!buffer_size) {
335             buffer_size = DEFAULT_BUFFER_SIZE;
336             period_size= DEFAULT_PERIOD_SIZE;
337         }
338     }
339
340     if (buffer_size) {
341         if ((in && conf.size_in_usec_in) || (!in && conf.size_in_usec_out)) {
342             if (period_size) {
343                 err = snd_pcm_hw_params_set_period_time_near (
344                     handle,
345                     hw_params,
346                     &period_size,
347                     0);
348                 if (err < 0) {
349                     alsa_logerr2 (err, typ,
350                                   "Failed to set period time %d\n",
351                                   req->period_size);
352                     goto err;
353                 }
354             }
355
356             err = snd_pcm_hw_params_set_buffer_time_near (
357                 handle,
358                 hw_params,
359                 &buffer_size,
360                 0);
361
362             if (err < 0) {
363                 alsa_logerr2 (err, typ,
364                               "Failed to set buffer time %d\n",
365                               req->buffer_size);
366                 goto err;
367             }
368         }
369         else {
370             int dir;
371             snd_pcm_uframes_t minval;
372
373             if (period_size) {
374                 minval = period_size;
375                 dir = 0;
376
377                 err = snd_pcm_hw_params_get_period_size_min (
378                     hw_params,
379                     &minval,
380                     &dir
381                     );
382                 if (err < 0) {
383                     alsa_logerr (
384                         err,
385                         "Can not get minmal period size for %s\n",
386                         typ
387                         );
388                 }
389                 else {
390                     if (period_size < minval) {
391                         if ((in && conf.period_size_in_overriden)
392                             || (!in && conf.period_size_out_overriden)) {
393                             dolog ("%s period size(%d) is less "
394                                    "than minmal period size(%ld)\n",
395                                    typ,
396                                    period_size,
397                                    minval);
398                         }
399                         period_size = minval;
400                     }
401                 }
402
403                 err = snd_pcm_hw_params_set_period_size (
404                     handle,
405                     hw_params,
406                     period_size,
407                     0
408                     );
409                 if (err < 0) {
410                     alsa_logerr2 (err, typ, "Failed to set period size %d\n",
411                                   req->period_size);
412                     goto err;
413                 }
414             }
415
416             minval = buffer_size;
417             err = snd_pcm_hw_params_get_buffer_size_min (
418                 hw_params,
419                 &minval
420                 );
421             if (err < 0) {
422                 alsa_logerr (err, "Can not get minmal buffer size for %s\n",
423                              typ);
424             }
425             else {
426                 if (buffer_size < minval) {
427                     if ((in && conf.buffer_size_in_overriden)
428                         || (!in && conf.buffer_size_out_overriden)) {
429                         dolog (
430                             "%s buffer size(%d) is less "
431                             "than minimal buffer size(%ld)\n",
432                             typ,
433                             buffer_size,
434                             minval
435                             );
436                     }
437                     buffer_size = minval;
438                 }
439             }
440
441             err = snd_pcm_hw_params_set_buffer_size (
442                 handle,
443                 hw_params,
444                 buffer_size
445                 );
446             if (err < 0) {
447                 alsa_logerr2 (err, typ, "Failed to set buffer size %d\n",
448                               req->buffer_size);
449                 goto err;
450             }
451         }
452     }
453     else {
454         dolog ("warning: buffer size is not set\n");
455     }
456
457     err = snd_pcm_hw_params (handle, hw_params);
458     if (err < 0) {
459         alsa_logerr2 (err, typ, "Failed to apply audio parameters\n");
460         goto err;
461     }
462
463     err = snd_pcm_hw_params_get_buffer_size (hw_params, &obt_buffer_size);
464     if (err < 0) {
465         alsa_logerr2 (err, typ, "Failed to get buffer size\n");
466         goto err;
467     }
468
469     err = snd_pcm_prepare (handle);
470     if (err < 0) {
471         alsa_logerr2 (err, typ, "Can not prepare handle %p\n", handle);
472         goto err;
473     }
474
475     obt->can_pause = snd_pcm_hw_params_can_pause (hw_params);
476     if (obt->can_pause < 0) {
477         alsa_logerr (err, "Can not get pause capability for %s\n", typ);
478         obt->can_pause = 0;
479     }
480
481     if (!in && conf.threshold) {
482         snd_pcm_uframes_t threshold;
483         int bytes_per_sec;
484
485         bytes_per_sec = freq
486             << (nchannels == 2)
487             << (req->fmt == AUD_FMT_S16 || req->fmt == AUD_FMT_U16);
488
489         threshold = (conf.threshold * bytes_per_sec) / 1000;
490         alsa_set_threshold (handle, threshold);
491     }
492
493     obt->fmt = req->fmt;
494     obt->nchannels = nchannels;
495     obt->freq = freq;
496     obt->buffer_size = snd_pcm_frames_to_bytes (handle, obt_buffer_size);
497     *handlep = handle;
498
499     if (obt->fmt != req->fmt ||
500         obt->nchannels != req->nchannels ||
501         obt->freq != req->freq) {
502 #ifdef DEBUG_MISMATCHES
503         dolog ("Audio paramters mismatch for %s\n", typ);
504         alsa_dump_info (req, obt);
505 #endif
506     }
507
508 #ifdef DEBUG
509     alsa_dump_info (req, obt);
510 #endif
511     return 0;
512
513  err:
514     alsa_anal_close (&handle);
515     return -1;
516 }
517
518 static int alsa_recover (snd_pcm_t *handle)
519 {
520     int err = snd_pcm_prepare (handle);
521     if (err < 0) {
522         alsa_logerr (err, "Failed to prepare handle %p\n", handle);
523         return -1;
524     }
525     return 0;
526 }
527
528 static int alsa_run_out (HWVoiceOut *hw)
529 {
530     ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
531     int rpos, live, decr;
532     int samples;
533     uint8_t *dst;
534     st_sample_t *src;
535     snd_pcm_sframes_t avail;
536
537     live = audio_pcm_hw_get_live_out (hw);
538     if (!live) {
539         return 0;
540     }
541
542     avail = snd_pcm_avail_update (alsa->handle);
543     if (avail < 0) {
544         if (avail == -EPIPE) {
545             if (!alsa_recover (alsa->handle)) {
546                 avail = snd_pcm_avail_update (alsa->handle);
547                 if (avail >= 0) {
548                     goto ok;
549                 }
550             }
551         }
552
553         alsa_logerr (avail, "Can not get amount free space\n");
554         return 0;
555     }
556
557  ok:
558     decr = audio_MIN (live, avail);
559     samples = decr;
560     rpos = hw->rpos;
561     while (samples) {
562         int left_till_end_samples = hw->samples - rpos;
563         int convert_samples = audio_MIN (samples, left_till_end_samples);
564         snd_pcm_sframes_t written;
565
566         src = hw->mix_buf + rpos;
567         dst = advance (alsa->pcm_buf, rpos << hw->info.shift);
568
569         hw->clip (dst, src, convert_samples);
570
571     again:
572         written = snd_pcm_writei (alsa->handle, dst, convert_samples);
573
574         if (written < 0) {
575             switch (written) {
576             case -EPIPE:
577                 if (!alsa_recover (alsa->handle)) {
578                     goto again;
579                 }
580                 dolog (
581                     "Failed to write %d frames to %p, handle %p not prepared\n",
582                     convert_samples,
583                     dst,
584                     alsa->handle
585                     );
586                 goto exit;
587
588             case -EAGAIN:
589                 goto again;
590
591             default:
592                 alsa_logerr (written, "Failed to write %d frames to %p\n",
593                              convert_samples, dst);
594                 goto exit;
595             }
596         }
597
598         mixeng_clear (src, written);
599         rpos = (rpos + written) % hw->samples;
600         samples -= written;
601     }
602
603  exit:
604     hw->rpos = rpos;
605     return decr;
606 }
607
608 static void alsa_fini_out (HWVoiceOut *hw)
609 {
610     ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
611
612     ldebug ("alsa_fini\n");
613     alsa_anal_close (&alsa->handle);
614
615     if (alsa->pcm_buf) {
616         qemu_free (alsa->pcm_buf);
617         alsa->pcm_buf = NULL;
618     }
619 }
620
621 static int alsa_init_out (HWVoiceOut *hw, int freq, int nchannels, audfmt_e fmt)
622 {
623     ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
624     struct alsa_params_req req;
625     struct alsa_params_obt obt;
626     audfmt_e effective_fmt;
627     int endianness;
628     int err;
629     snd_pcm_t *handle;
630
631     req.fmt = aud_to_alsafmt (fmt);
632     req.freq = freq;
633     req.nchannels = nchannels;
634     req.period_size = conf.period_size_out;
635     req.buffer_size = conf.buffer_size_out;
636
637     if (alsa_open (0, &req, &obt, &handle)) {
638         return -1;
639     }
640
641     err = alsa_to_audfmt (obt.fmt, &effective_fmt, &endianness);
642     if (err) {
643         alsa_anal_close (&handle);
644         return -1;
645     }
646
647     audio_pcm_init_info (
648         &hw->info,
649         obt.freq,
650         obt.nchannels,
651         effective_fmt,
652         audio_need_to_swap_endian (endianness)
653         );
654     alsa->can_pause = obt.can_pause;
655     hw->bufsize = obt.buffer_size;
656
657     alsa->pcm_buf = qemu_mallocz (hw->bufsize);
658     if (!alsa->pcm_buf) {
659         alsa_anal_close (&handle);
660         return -1;
661     }
662
663     alsa->handle = handle;
664     alsa->was_enabled = 0;
665     return 0;
666 }
667
668 static int alsa_ctl_out (HWVoiceOut *hw, int cmd, ...)
669 {
670     int err;
671     ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
672
673     switch (cmd) {
674     case VOICE_ENABLE:
675         ldebug ("enabling voice\n");
676         audio_pcm_info_clear_buf (&hw->info, alsa->pcm_buf, hw->samples);
677         if (alsa->can_pause) {
678             /* Why this was_enabled madness is needed at all?? */
679             if (alsa->was_enabled) {
680                 err = snd_pcm_pause (alsa->handle, 0);
681                 if (err < 0) {
682                     alsa_logerr (err, "Failed to resume playing\n");
683                     /* not fatal really */
684                 }
685             }
686             else {
687                 alsa->was_enabled = 1;
688             }
689         }
690         break;
691
692     case VOICE_DISABLE:
693         ldebug ("disabling voice\n");
694         if (alsa->can_pause) {
695             err = snd_pcm_pause (alsa->handle, 1);
696             if (err < 0) {
697                 alsa_logerr (err, "Failed to stop playing\n");
698                 /* not fatal really */
699             }
700         }
701         break;
702     }
703     return 0;
704 }
705
706 static int alsa_init_in (HWVoiceIn *hw,
707                         int freq, int nchannels, audfmt_e fmt)
708 {
709     ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
710     struct alsa_params_req req;
711     struct alsa_params_obt obt;
712     int endianness;
713     int err;
714     audfmt_e effective_fmt;
715     snd_pcm_t *handle;
716
717     req.fmt = aud_to_alsafmt (fmt);
718     req.freq = freq;
719     req.nchannels = nchannels;
720     req.period_size = conf.period_size_in;
721     req.buffer_size = conf.buffer_size_in;
722
723     if (alsa_open (1, &req, &obt, &handle)) {
724         return -1;
725     }
726
727     err = alsa_to_audfmt (obt.fmt, &effective_fmt, &endianness);
728     if (err) {
729         alsa_anal_close (&handle);
730         return -1;
731     }
732
733     audio_pcm_init_info (
734         &hw->info,
735         obt.freq,
736         obt.nchannels,
737         effective_fmt,
738         audio_need_to_swap_endian (endianness)
739         );
740     alsa->can_pause = obt.can_pause;
741     hw->bufsize = obt.buffer_size;
742     alsa->pcm_buf = qemu_mallocz (hw->bufsize);
743     if (!alsa->pcm_buf) {
744         alsa_anal_close (&handle);
745         return -1;
746     }
747
748     alsa->handle = handle;
749     return 0;
750 }
751
752 static void alsa_fini_in (HWVoiceIn *hw)
753 {
754     ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
755
756     alsa_anal_close (&alsa->handle);
757
758     if (alsa->pcm_buf) {
759         qemu_free (alsa->pcm_buf);
760         alsa->pcm_buf = NULL;
761     }
762 }
763
764 static int alsa_run_in (HWVoiceIn *hw)
765 {
766     ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
767     int hwshift = hw->info.shift;
768     int i;
769     int live = audio_pcm_hw_get_live_in (hw);
770     int dead = hw->samples - live;
771     struct {
772         int add;
773         int len;
774     } bufs[2] = {
775         { hw->wpos, 0 },
776         { 0, 0 }
777     };
778
779     snd_pcm_uframes_t read_samples = 0;
780
781     if (!dead) {
782         return 0;
783     }
784
785     if (hw->wpos + dead > hw->samples) {
786         bufs[0].len = (hw->samples - hw->wpos);
787         bufs[1].len = (dead - (hw->samples - hw->wpos));
788     }
789     else {
790         bufs[0].len = dead;
791     }
792
793
794     for (i = 0; i < 2; ++i) {
795         void *src;
796         st_sample_t *dst;
797         snd_pcm_sframes_t nread;
798         snd_pcm_uframes_t len;
799
800         len = bufs[i].len;
801
802         src = advance (alsa->pcm_buf, bufs[i].add << hwshift);
803         dst = hw->conv_buf + bufs[i].add;
804
805         while (len) {
806             nread = snd_pcm_readi (alsa->handle, src, len);
807
808             if (nread < 0) {
809                 switch (nread) {
810                 case -EPIPE:
811                     if (!alsa_recover (alsa->handle)) {
812                         continue;
813                     }
814                     dolog (
815                         "Failed to read %ld frames from %p, "
816                         "handle %p not prepared\n",
817                         len,
818                         src,
819                         alsa->handle
820                         );
821                     goto exit;
822
823                 case -EAGAIN:
824                     continue;
825
826                 default:
827                     alsa_logerr (
828                         nread,
829                         "Failed to read %ld frames from %p\n",
830                         len,
831                         src
832                         );
833                     goto exit;
834                 }
835             }
836
837             hw->conv (dst, src, nread, &nominal_volume);
838
839             src = advance (src, nread << hwshift);
840             dst += nread;
841
842             read_samples += nread;
843             len -= nread;
844         }
845     }
846
847  exit:
848     hw->wpos = (hw->wpos + read_samples) % hw->samples;
849     return read_samples;
850 }
851
852 static int alsa_read (SWVoiceIn *sw, void *buf, int size)
853 {
854     return audio_pcm_sw_read (sw, buf, size);
855 }
856
857 static int alsa_ctl_in (HWVoiceIn *hw, int cmd, ...)
858 {
859     (void) hw;
860     (void) cmd;
861     return 0;
862 }
863
864 static void *alsa_audio_init (void)
865 {
866     return &conf;
867 }
868
869 static void alsa_audio_fini (void *opaque)
870 {
871     (void) opaque;
872 }
873
874 static struct audio_option alsa_options[] = {
875     {"DAC_SIZE_IN_USEC", AUD_OPT_BOOL, &conf.size_in_usec_out,
876      "DAC period/buffer size in microseconds (otherwise in frames)", NULL, 0},
877     {"DAC_PERIOD_SIZE", AUD_OPT_INT, &conf.period_size_out,
878      "DAC period size", &conf.period_size_out_overriden, 0},
879     {"DAC_BUFFER_SIZE", AUD_OPT_INT, &conf.buffer_size_out,
880      "DAC buffer size", &conf.buffer_size_out_overriden, 0},
881
882     {"ADC_SIZE_IN_USEC", AUD_OPT_BOOL, &conf.size_in_usec_in,
883      "ADC period/buffer size in microseconds (otherwise in frames)", NULL, 0},
884     {"ADC_PERIOD_SIZE", AUD_OPT_INT, &conf.period_size_in,
885      "ADC period size", &conf.period_size_in_overriden, 0},
886     {"ADC_BUFFER_SIZE", AUD_OPT_INT, &conf.buffer_size_in,
887      "ADC buffer size", &conf.buffer_size_in_overriden, 0},
888
889     {"THRESHOLD", AUD_OPT_INT, &conf.threshold,
890      "(undocumented)", NULL, 0},
891
892     {"DAC_DEV", AUD_OPT_STR, &conf.pcm_name_out,
893      "DAC device name (for instance dmix)", NULL, 0},
894
895     {"ADC_DEV", AUD_OPT_STR, &conf.pcm_name_in,
896      "ADC device name", NULL, 0},
897     {NULL, 0, NULL, NULL, NULL, 0}
898 };
899
900 static struct audio_pcm_ops alsa_pcm_ops = {
901     alsa_init_out,
902     alsa_fini_out,
903     alsa_run_out,
904     alsa_write,
905     alsa_ctl_out,
906
907     alsa_init_in,
908     alsa_fini_in,
909     alsa_run_in,
910     alsa_read,
911     alsa_ctl_in
912 };
913
914 struct audio_driver alsa_audio_driver = {
915     INIT_FIELD (name           = ) "alsa",
916     INIT_FIELD (descr          = ) "ALSA http://www.alsa-project.org",
917     INIT_FIELD (options        = ) alsa_options,
918     INIT_FIELD (init           = ) alsa_audio_init,
919     INIT_FIELD (fini           = ) alsa_audio_fini,
920     INIT_FIELD (pcm_ops        = ) &alsa_pcm_ops,
921     INIT_FIELD (can_be_default = ) 1,
922     INIT_FIELD (max_voices_out = ) INT_MAX,
923     INIT_FIELD (max_voices_in  = ) INT_MAX,
924     INIT_FIELD (voice_size_out = ) sizeof (ALSAVoiceOut),
925     INIT_FIELD (voice_size_in  = ) sizeof (ALSAVoiceIn)
926 };