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