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