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