28c245dc7056b259ee2e1761a789174b5a93783a
[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 "qemu-char.h"
27 #include "audio.h"
28
29 #if QEMU_GNUC_PREREQ(4, 3)
30 #pragma GCC diagnostic ignored "-Waddress"
31 #endif
32
33 #define AUDIO_CAP "alsa"
34 #include "audio_int.h"
35
36 struct pollhlp {
37     snd_pcm_t *handle;
38     struct pollfd *pfds;
39     int count;
40 };
41
42 typedef struct ALSAVoiceOut {
43     HWVoiceOut hw;
44     void *pcm_buf;
45     snd_pcm_t *handle;
46     struct pollhlp pollhlp;
47 } ALSAVoiceOut;
48
49 typedef struct ALSAVoiceIn {
50     HWVoiceIn hw;
51     snd_pcm_t *handle;
52     void *pcm_buf;
53     struct pollhlp pollhlp;
54 } ALSAVoiceIn;
55
56 static struct {
57     int size_in_usec_in;
58     int size_in_usec_out;
59     const char *pcm_name_in;
60     const char *pcm_name_out;
61     unsigned int buffer_size_in;
62     unsigned int period_size_in;
63     unsigned int buffer_size_out;
64     unsigned int period_size_out;
65     unsigned int threshold;
66
67     int buffer_size_in_overridden;
68     int period_size_in_overridden;
69
70     int buffer_size_out_overridden;
71     int period_size_out_overridden;
72     int verbose;
73 } conf = {
74     .buffer_size_out = 1024,
75     .pcm_name_out = "default",
76     .pcm_name_in = "default",
77 };
78
79 struct alsa_params_req {
80     int freq;
81     snd_pcm_format_t fmt;
82     int nchannels;
83     int size_in_usec;
84     int override_mask;
85     unsigned int buffer_size;
86     unsigned int period_size;
87 };
88
89 struct alsa_params_obt {
90     int freq;
91     audfmt_e fmt;
92     int endianness;
93     int nchannels;
94     snd_pcm_uframes_t samples;
95 };
96
97 static void GCC_FMT_ATTR (2, 3) alsa_logerr (int err, const char *fmt, ...)
98 {
99     va_list ap;
100
101     va_start (ap, fmt);
102     AUD_vlog (AUDIO_CAP, fmt, ap);
103     va_end (ap);
104
105     AUD_log (AUDIO_CAP, "Reason: %s\n", snd_strerror (err));
106 }
107
108 static void GCC_FMT_ATTR (3, 4) alsa_logerr2 (
109     int err,
110     const char *typ,
111     const char *fmt,
112     ...
113     )
114 {
115     va_list ap;
116
117     AUD_log (AUDIO_CAP, "Could not initialize %s\n", typ);
118
119     va_start (ap, fmt);
120     AUD_vlog (AUDIO_CAP, fmt, ap);
121     va_end (ap);
122
123     AUD_log (AUDIO_CAP, "Reason: %s\n", snd_strerror (err));
124 }
125
126 static void alsa_anal_close (snd_pcm_t **handlep)
127 {
128     int err = snd_pcm_close (*handlep);
129     if (err) {
130         alsa_logerr (err, "Failed to close PCM handle %p\n", *handlep);
131     }
132     *handlep = NULL;
133 }
134
135 static int alsa_recover (snd_pcm_t *handle)
136 {
137     int err = snd_pcm_prepare (handle);
138     if (err < 0) {
139         alsa_logerr (err, "Failed to prepare handle %p\n", handle);
140         return -1;
141     }
142     return 0;
143 }
144
145 static int alsa_resume (snd_pcm_t *handle)
146 {
147     int err = snd_pcm_resume (handle);
148     if (err < 0) {
149         alsa_logerr (err, "Failed to resume handle %p\n", handle);
150         return -1;
151     }
152     return 0;
153 }
154
155 static void alsa_poll_handler (void *opaque)
156 {
157     int err, count;
158     snd_pcm_state_t state;
159     struct pollhlp *hlp = opaque;
160     unsigned short revents;
161
162     count = poll (hlp->pfds, hlp->count, 0);
163     if (count < 0) {
164         dolog ("alsa_poll_handler: poll %s\n", strerror (errno));
165         return;
166     }
167
168     if (!count) {
169         return;
170     }
171
172     /* XXX: ALSA example uses initial count, not the one returned by
173        poll, correct? */
174     err = snd_pcm_poll_descriptors_revents (hlp->handle, hlp->pfds,
175                                             hlp->count, &revents);
176     if (err < 0) {
177         alsa_logerr (err, "snd_pcm_poll_descriptors_revents");
178         return;
179     }
180
181     if (!(revents & POLLOUT)) {
182         if (conf.verbose) {
183             dolog ("revents = %d\n", revents);
184         }
185         return;
186     }
187
188     state = snd_pcm_state (hlp->handle);
189     switch (state) {
190     case SND_PCM_STATE_XRUN:
191         alsa_recover (hlp->handle);
192         break;
193
194     case SND_PCM_STATE_SUSPENDED:
195         alsa_resume (hlp->handle);
196         break;
197
198     case SND_PCM_STATE_PREPARED:
199         audio_run ("alsa run (prepared)");
200         break;
201
202     case SND_PCM_STATE_RUNNING:
203         audio_run ("alsa run (running)");
204         break;
205
206     default:
207         dolog ("Unexpected state %d\n", state);
208     }
209 }
210
211 static int alsa_poll_helper (snd_pcm_t *handle, struct pollhlp *hlp)
212 {
213     int i, count, err;
214     struct pollfd *pfds;
215
216     count = snd_pcm_poll_descriptors_count (handle);
217     if (count <= 0) {
218         dolog ("Could not initialize poll mode\n"
219                "Invalid number of poll descriptors %d\n", count);
220         return -1;
221     }
222
223     pfds = audio_calloc ("alsa_poll_helper", count, sizeof (*pfds));
224     if (!pfds) {
225         dolog ("Could not initialize poll mode\n");
226         return -1;
227     }
228
229     err = snd_pcm_poll_descriptors (handle, pfds, count);
230     if (err < 0) {
231         alsa_logerr (err, "Could not initialize poll mode\n"
232                      "Could not obtain poll descriptors\n");
233         qemu_free (pfds);
234         return -1;
235     }
236
237     for (i = 0; i < count; ++i) {
238         if (pfds[i].events & POLLIN) {
239             err = qemu_set_fd_handler (pfds[i].fd, alsa_poll_handler,
240                                        NULL, hlp);
241         }
242         if (pfds[i].events & POLLOUT) {
243             if (conf.verbose) {
244                 dolog ("POLLOUT %d %d\n", i, pfds[i].fd);
245             }
246             err = qemu_set_fd_handler (pfds[i].fd, NULL,
247                                        alsa_poll_handler, hlp);
248         }
249         if (conf.verbose) {
250             dolog ("Set handler events=%#x index=%d fd=%d err=%d\n",
251                    pfds[i].events, i, pfds[i].fd, err);
252         }
253
254         if (err) {
255             dolog ("Failed to set handler events=%#x index=%d fd=%d err=%d\n",
256                    pfds[i].events, i, pfds[i].fd, err);
257
258             while (i--) {
259                 qemu_set_fd_handler (pfds[i].fd, NULL, NULL, NULL);
260             }
261             qemu_free (pfds);
262             return -1;
263         }
264     }
265     hlp->pfds = pfds;
266     hlp->count = count;
267     hlp->handle = handle;
268     return 0;
269 }
270
271 static int alsa_poll_out (HWVoiceOut *hw)
272 {
273     ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
274
275     return alsa_poll_helper (alsa->handle, &alsa->pollhlp);
276 }
277
278 static int alsa_poll_in (HWVoiceIn *hw)
279 {
280     ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
281
282     return alsa_poll_helper (alsa->handle, &alsa->pollhlp);
283 }
284
285 static int alsa_write (SWVoiceOut *sw, void *buf, int len)
286 {
287     return audio_pcm_sw_write (sw, buf, len);
288 }
289
290 static snd_pcm_format_t aud_to_alsafmt (audfmt_e fmt)
291 {
292     switch (fmt) {
293     case AUD_FMT_S8:
294         return SND_PCM_FORMAT_S8;
295
296     case AUD_FMT_U8:
297         return SND_PCM_FORMAT_U8;
298
299     case AUD_FMT_S16:
300         return SND_PCM_FORMAT_S16_LE;
301
302     case AUD_FMT_U16:
303         return SND_PCM_FORMAT_U16_LE;
304
305     case AUD_FMT_S32:
306         return SND_PCM_FORMAT_S32_LE;
307
308     case AUD_FMT_U32:
309         return SND_PCM_FORMAT_U32_LE;
310
311     default:
312         dolog ("Internal logic error: Bad audio format %d\n", fmt);
313 #ifdef DEBUG_AUDIO
314         abort ();
315 #endif
316         return SND_PCM_FORMAT_U8;
317     }
318 }
319
320 static int alsa_to_audfmt (snd_pcm_format_t alsafmt, audfmt_e *fmt,
321                            int *endianness)
322 {
323     switch (alsafmt) {
324     case SND_PCM_FORMAT_S8:
325         *endianness = 0;
326         *fmt = AUD_FMT_S8;
327         break;
328
329     case SND_PCM_FORMAT_U8:
330         *endianness = 0;
331         *fmt = AUD_FMT_U8;
332         break;
333
334     case SND_PCM_FORMAT_S16_LE:
335         *endianness = 0;
336         *fmt = AUD_FMT_S16;
337         break;
338
339     case SND_PCM_FORMAT_U16_LE:
340         *endianness = 0;
341         *fmt = AUD_FMT_U16;
342         break;
343
344     case SND_PCM_FORMAT_S16_BE:
345         *endianness = 1;
346         *fmt = AUD_FMT_S16;
347         break;
348
349     case SND_PCM_FORMAT_U16_BE:
350         *endianness = 1;
351         *fmt = AUD_FMT_U16;
352         break;
353
354     case SND_PCM_FORMAT_S32_LE:
355         *endianness = 0;
356         *fmt = AUD_FMT_S32;
357         break;
358
359     case SND_PCM_FORMAT_U32_LE:
360         *endianness = 0;
361         *fmt = AUD_FMT_U32;
362         break;
363
364     case SND_PCM_FORMAT_S32_BE:
365         *endianness = 1;
366         *fmt = AUD_FMT_S32;
367         break;
368
369     case SND_PCM_FORMAT_U32_BE:
370         *endianness = 1;
371         *fmt = AUD_FMT_U32;
372         break;
373
374     default:
375         dolog ("Unrecognized audio format %d\n", alsafmt);
376         return -1;
377     }
378
379     return 0;
380 }
381
382 static void alsa_dump_info (struct alsa_params_req *req,
383                             struct alsa_params_obt *obt)
384 {
385     dolog ("parameter | requested value | obtained value\n");
386     dolog ("format    |      %10d |     %10d\n", req->fmt, obt->fmt);
387     dolog ("channels  |      %10d |     %10d\n",
388            req->nchannels, obt->nchannels);
389     dolog ("frequency |      %10d |     %10d\n", req->freq, obt->freq);
390     dolog ("============================================\n");
391     dolog ("requested: buffer size %d period size %d\n",
392            req->buffer_size, req->period_size);
393     dolog ("obtained: samples %ld\n", obt->samples);
394 }
395
396 static void alsa_set_threshold (snd_pcm_t *handle, snd_pcm_uframes_t threshold)
397 {
398     int err;
399     snd_pcm_sw_params_t *sw_params;
400
401     snd_pcm_sw_params_alloca (&sw_params);
402
403     err = snd_pcm_sw_params_current (handle, sw_params);
404     if (err < 0) {
405         dolog ("Could not fully initialize DAC\n");
406         alsa_logerr (err, "Failed to get current software parameters\n");
407         return;
408     }
409
410     err = snd_pcm_sw_params_set_start_threshold (handle, sw_params, threshold);
411     if (err < 0) {
412         dolog ("Could not fully initialize DAC\n");
413         alsa_logerr (err, "Failed to set software threshold to %ld\n",
414                      threshold);
415         return;
416     }
417
418     err = snd_pcm_sw_params (handle, sw_params);
419     if (err < 0) {
420         dolog ("Could not fully initialize DAC\n");
421         alsa_logerr (err, "Failed to set software parameters\n");
422         return;
423     }
424 }
425
426 static int alsa_open (int in, struct alsa_params_req *req,
427                       struct alsa_params_obt *obt, snd_pcm_t **handlep)
428 {
429     snd_pcm_t *handle;
430     snd_pcm_hw_params_t *hw_params;
431     int err;
432     int size_in_usec;
433     unsigned int freq, nchannels;
434     const char *pcm_name = in ? conf.pcm_name_in : conf.pcm_name_out;
435     snd_pcm_uframes_t obt_buffer_size;
436     const char *typ = in ? "ADC" : "DAC";
437     snd_pcm_format_t obtfmt;
438
439     freq = req->freq;
440     nchannels = req->nchannels;
441     size_in_usec = req->size_in_usec;
442
443     snd_pcm_hw_params_alloca (&hw_params);
444
445     err = snd_pcm_open (
446         &handle,
447         pcm_name,
448         in ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
449         SND_PCM_NONBLOCK
450         );
451     if (err < 0) {
452         alsa_logerr2 (err, typ, "Failed to open `%s':\n", pcm_name);
453         return -1;
454     }
455
456     err = snd_pcm_hw_params_any (handle, hw_params);
457     if (err < 0) {
458         alsa_logerr2 (err, typ, "Failed to initialize hardware parameters\n");
459         goto err;
460     }
461
462     err = snd_pcm_hw_params_set_access (
463         handle,
464         hw_params,
465         SND_PCM_ACCESS_RW_INTERLEAVED
466         );
467     if (err < 0) {
468         alsa_logerr2 (err, typ, "Failed to set access type\n");
469         goto err;
470     }
471
472     err = snd_pcm_hw_params_set_format (handle, hw_params, req->fmt);
473     if (err < 0 && conf.verbose) {
474         alsa_logerr2 (err, typ, "Failed to set format %d\n", req->fmt);
475     }
476
477     err = snd_pcm_hw_params_set_rate_near (handle, hw_params, &freq, 0);
478     if (err < 0) {
479         alsa_logerr2 (err, typ, "Failed to set frequency %d\n", req->freq);
480         goto err;
481     }
482
483     err = snd_pcm_hw_params_set_channels_near (
484         handle,
485         hw_params,
486         &nchannels
487         );
488     if (err < 0) {
489         alsa_logerr2 (err, typ, "Failed to set number of channels %d\n",
490                       req->nchannels);
491         goto err;
492     }
493
494     if (nchannels != 1 && nchannels != 2) {
495         alsa_logerr2 (err, typ,
496                       "Can not handle obtained number of channels %d\n",
497                       nchannels);
498         goto err;
499     }
500
501     if (req->buffer_size) {
502         unsigned long obt;
503
504         if (size_in_usec) {
505             int dir = 0;
506             unsigned int btime = req->buffer_size;
507
508             err = snd_pcm_hw_params_set_buffer_time_near (
509                 handle,
510                 hw_params,
511                 &btime,
512                 &dir
513                 );
514             obt = btime;
515         }
516         else {
517             snd_pcm_uframes_t bsize = req->buffer_size;
518
519             err = snd_pcm_hw_params_set_buffer_size_near (
520                 handle,
521                 hw_params,
522                 &bsize
523                 );
524             obt = bsize;
525         }
526         if (err < 0) {
527             alsa_logerr2 (err, typ, "Failed to set buffer %s to %d\n",
528                           size_in_usec ? "time" : "size", req->buffer_size);
529             goto err;
530         }
531
532         if ((req->override_mask & 2) && (obt - req->buffer_size))
533             dolog ("Requested buffer %s %u was rejected, using %lu\n",
534                    size_in_usec ? "time" : "size", req->buffer_size, obt);
535     }
536
537     if (req->period_size) {
538         unsigned long obt;
539
540         if (size_in_usec) {
541             int dir = 0;
542             unsigned int ptime = req->period_size;
543
544             err = snd_pcm_hw_params_set_period_time_near (
545                 handle,
546                 hw_params,
547                 &ptime,
548                 &dir
549                 );
550             obt = ptime;
551         }
552         else {
553             int dir = 0;
554             snd_pcm_uframes_t psize = req->period_size;
555
556             err = snd_pcm_hw_params_set_period_size_near (
557                 handle,
558                 hw_params,
559                 &psize,
560                 &dir
561                 );
562             obt = psize;
563         }
564
565         if (err < 0) {
566             alsa_logerr2 (err, typ, "Failed to set period %s to %d\n",
567                           size_in_usec ? "time" : "size", req->period_size);
568             goto err;
569         }
570
571         if ((req->override_mask & 1) && (obt - req->period_size))
572             dolog ("Requested period %s %u was rejected, using %lu\n",
573                    size_in_usec ? "time" : "size", req->period_size, obt);
574     }
575
576     err = snd_pcm_hw_params (handle, hw_params);
577     if (err < 0) {
578         alsa_logerr2 (err, typ, "Failed to apply audio parameters\n");
579         goto err;
580     }
581
582     err = snd_pcm_hw_params_get_buffer_size (hw_params, &obt_buffer_size);
583     if (err < 0) {
584         alsa_logerr2 (err, typ, "Failed to get buffer size\n");
585         goto err;
586     }
587
588     err = snd_pcm_hw_params_get_format (hw_params, &obtfmt);
589     if (err < 0) {
590         alsa_logerr2 (err, typ, "Failed to get format\n");
591         goto err;
592     }
593
594     if (alsa_to_audfmt (obtfmt, &obt->fmt, &obt->endianness)) {
595         dolog ("Invalid format was returned %d\n", obtfmt);
596         goto err;
597     }
598
599     err = snd_pcm_prepare (handle);
600     if (err < 0) {
601         alsa_logerr2 (err, typ, "Could not prepare handle %p\n", handle);
602         goto err;
603     }
604
605     if (!in && conf.threshold) {
606         snd_pcm_uframes_t threshold;
607         int bytes_per_sec;
608
609         bytes_per_sec = freq << (nchannels == 2);
610
611         switch (obt->fmt) {
612         case AUD_FMT_S8:
613         case AUD_FMT_U8:
614             break;
615
616         case AUD_FMT_S16:
617         case AUD_FMT_U16:
618             bytes_per_sec <<= 1;
619             break;
620
621         case AUD_FMT_S32:
622         case AUD_FMT_U32:
623             bytes_per_sec <<= 2;
624             break;
625         }
626
627         threshold = (conf.threshold * bytes_per_sec) / 1000;
628         alsa_set_threshold (handle, threshold);
629     }
630
631     obt->nchannels = nchannels;
632     obt->freq = freq;
633     obt->samples = obt_buffer_size;
634
635     *handlep = handle;
636
637     if (conf.verbose &&
638         (obt->fmt != req->fmt ||
639          obt->nchannels != req->nchannels ||
640          obt->freq != req->freq)) {
641         dolog ("Audio paramters for %s\n", typ);
642         alsa_dump_info (req, obt);
643     }
644
645 #ifdef DEBUG
646     alsa_dump_info (req, obt);
647 #endif
648     return 0;
649
650  err:
651     alsa_anal_close (&handle);
652     return -1;
653 }
654
655 static snd_pcm_sframes_t alsa_get_avail (snd_pcm_t *handle)
656 {
657     snd_pcm_sframes_t avail;
658
659     avail = snd_pcm_avail_update (handle);
660     if (avail < 0) {
661         if (avail == -EPIPE) {
662             if (!alsa_recover (handle)) {
663                 avail = snd_pcm_avail_update (handle);
664             }
665         }
666
667         if (avail < 0) {
668             alsa_logerr (avail,
669                          "Could not obtain number of available frames\n");
670             return -1;
671         }
672     }
673
674     return avail;
675 }
676
677 static int alsa_run_out (HWVoiceOut *hw)
678 {
679     ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
680     int rpos, live, decr;
681     int samples;
682     uint8_t *dst;
683     struct st_sample *src;
684     snd_pcm_sframes_t avail;
685
686     live = audio_pcm_hw_get_live_out (hw);
687     if (!live) {
688         return 0;
689     }
690
691     avail = alsa_get_avail (alsa->handle);
692     if (avail < 0) {
693         dolog ("Could not get number of available playback frames\n");
694         return 0;
695     }
696
697     decr = audio_MIN (live, avail);
698     samples = decr;
699     rpos = hw->rpos;
700     while (samples) {
701         int left_till_end_samples = hw->samples - rpos;
702         int len = audio_MIN (samples, left_till_end_samples);
703         snd_pcm_sframes_t written;
704
705         src = hw->mix_buf + rpos;
706         dst = advance (alsa->pcm_buf, rpos << hw->info.shift);
707
708         hw->clip (dst, src, len);
709
710         while (len) {
711             written = snd_pcm_writei (alsa->handle, dst, len);
712
713             if (written <= 0) {
714                 switch (written) {
715                 case 0:
716                     if (conf.verbose) {
717                         dolog ("Failed to write %d frames (wrote zero)\n", len);
718                     }
719                     goto exit;
720
721                 case -EPIPE:
722                     if (alsa_recover (alsa->handle)) {
723                         alsa_logerr (written, "Failed to write %d frames\n",
724                                      len);
725                         goto exit;
726                     }
727                     if (conf.verbose) {
728                         dolog ("Recovering from playback xrun\n");
729                     }
730                     continue;
731
732                 case -ESTRPIPE:
733                     /* stream is suspended and waiting for an
734                        application recovery */
735                     if (alsa_resume (alsa->handle)) {
736                         alsa_logerr (written, "Failed to write %d frames\n",
737                                      len);
738                         goto exit;
739                     }
740                     if (conf.verbose) {
741                         dolog ("Resuming suspended output stream\n");
742                     }
743                     continue;
744
745                 case -EAGAIN:
746                     goto exit;
747
748                 default:
749                     alsa_logerr (written, "Failed to write %d frames to %p\n",
750                                  len, dst);
751                     goto exit;
752                 }
753             }
754
755             rpos = (rpos + written) % hw->samples;
756             samples -= written;
757             len -= written;
758             dst = advance (dst, written << hw->info.shift);
759             src += written;
760         }
761     }
762
763  exit:
764     hw->rpos = rpos;
765     return decr;
766 }
767
768 static void alsa_fini_poll (struct pollhlp *hlp)
769 {
770     int i;
771     struct pollfd *pfds = hlp->pfds;
772
773     if (pfds) {
774         for (i = 0; i < hlp->count; ++i) {
775             qemu_set_fd_handler (pfds[i].fd, NULL, NULL, NULL);
776         }
777         qemu_free (pfds);
778     }
779     hlp->pfds = NULL;
780     hlp->count = 0;
781     hlp->handle = NULL;
782 }
783
784 static void alsa_fini_out (HWVoiceOut *hw)
785 {
786     ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
787
788     ldebug ("alsa_fini\n");
789     alsa_anal_close (&alsa->handle);
790
791     if (alsa->pcm_buf) {
792         qemu_free (alsa->pcm_buf);
793         alsa->pcm_buf = NULL;
794     }
795
796     alsa_fini_poll (&alsa->pollhlp);
797 }
798
799 static int alsa_init_out (HWVoiceOut *hw, struct audsettings *as)
800 {
801     ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
802     struct alsa_params_req req;
803     struct alsa_params_obt obt;
804     snd_pcm_t *handle;
805     struct audsettings obt_as;
806
807     req.fmt = aud_to_alsafmt (as->fmt);
808     req.freq = as->freq;
809     req.nchannels = as->nchannels;
810     req.period_size = conf.period_size_out;
811     req.buffer_size = conf.buffer_size_out;
812     req.size_in_usec = conf.size_in_usec_out;
813     req.override_mask =
814         (conf.period_size_out_overridden ? 1 : 0) |
815         (conf.buffer_size_out_overridden ? 2 : 0);
816
817     if (alsa_open (0, &req, &obt, &handle)) {
818         return -1;
819     }
820
821     obt_as.freq = obt.freq;
822     obt_as.nchannels = obt.nchannels;
823     obt_as.fmt = obt.fmt;
824     obt_as.endianness = obt.endianness;
825
826     audio_pcm_init_info (&hw->info, &obt_as);
827     hw->samples = obt.samples;
828
829     alsa->pcm_buf = audio_calloc (AUDIO_FUNC, obt.samples, 1 << hw->info.shift);
830     if (!alsa->pcm_buf) {
831         dolog ("Could not allocate DAC buffer (%d samples, each %d bytes)\n",
832                hw->samples, 1 << hw->info.shift);
833         alsa_anal_close (&handle);
834         return -1;
835     }
836
837     alsa->handle = handle;
838     return 0;
839 }
840
841 static int alsa_voice_ctl (snd_pcm_t *handle, const char *typ, int pause)
842 {
843     int err;
844
845     if (pause) {
846         err = snd_pcm_drop (handle);
847         if (err < 0) {
848             alsa_logerr (err, "Could not stop %s\n", typ);
849             return -1;
850         }
851     }
852     else {
853         err = snd_pcm_prepare (handle);
854         if (err < 0) {
855             alsa_logerr (err, "Could not prepare handle for %s\n", typ);
856             return -1;
857         }
858     }
859
860     return 0;
861 }
862
863 static int alsa_ctl_out (HWVoiceOut *hw, int cmd, ...)
864 {
865     va_list ap;
866     int poll_mode;
867     ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
868
869     va_start (ap, cmd);
870     poll_mode = va_arg (ap, int);
871     va_end (ap);
872
873     switch (cmd) {
874     case VOICE_ENABLE:
875         ldebug ("enabling voice\n");
876         if (poll_mode && alsa_poll_out (hw)) {
877             poll_mode = 0;
878         }
879         hw->poll_mode = poll_mode;
880         return alsa_voice_ctl (alsa->handle, "playback", 0);
881
882     case VOICE_DISABLE:
883         ldebug ("disabling voice\n");
884         return alsa_voice_ctl (alsa->handle, "playback", 1);
885     }
886
887     return -1;
888 }
889
890 static int alsa_init_in (HWVoiceIn *hw, struct audsettings *as)
891 {
892     ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
893     struct alsa_params_req req;
894     struct alsa_params_obt obt;
895     snd_pcm_t *handle;
896     struct audsettings obt_as;
897
898     req.fmt = aud_to_alsafmt (as->fmt);
899     req.freq = as->freq;
900     req.nchannels = as->nchannels;
901     req.period_size = conf.period_size_in;
902     req.buffer_size = conf.buffer_size_in;
903     req.size_in_usec = conf.size_in_usec_in;
904     req.override_mask =
905         (conf.period_size_in_overridden ? 1 : 0) |
906         (conf.buffer_size_in_overridden ? 2 : 0);
907
908     if (alsa_open (1, &req, &obt, &handle)) {
909         return -1;
910     }
911
912     obt_as.freq = obt.freq;
913     obt_as.nchannels = obt.nchannels;
914     obt_as.fmt = obt.fmt;
915     obt_as.endianness = obt.endianness;
916
917     audio_pcm_init_info (&hw->info, &obt_as);
918     hw->samples = obt.samples;
919
920     alsa->pcm_buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift);
921     if (!alsa->pcm_buf) {
922         dolog ("Could not allocate ADC buffer (%d samples, each %d bytes)\n",
923                hw->samples, 1 << hw->info.shift);
924         alsa_anal_close (&handle);
925         return -1;
926     }
927
928     alsa->handle = handle;
929     return 0;
930 }
931
932 static void alsa_fini_in (HWVoiceIn *hw)
933 {
934     ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
935
936     alsa_anal_close (&alsa->handle);
937
938     if (alsa->pcm_buf) {
939         qemu_free (alsa->pcm_buf);
940         alsa->pcm_buf = NULL;
941     }
942     alsa_fini_poll (&alsa->pollhlp);
943 }
944
945 static int alsa_run_in (HWVoiceIn *hw)
946 {
947     ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
948     int hwshift = hw->info.shift;
949     int i;
950     int live = audio_pcm_hw_get_live_in (hw);
951     int dead = hw->samples - live;
952     int decr;
953     struct {
954         int add;
955         int len;
956     } bufs[2] = {
957         { .add = hw->wpos, .len = 0 },
958         { .add = 0,        .len = 0 }
959     };
960     snd_pcm_sframes_t avail;
961     snd_pcm_uframes_t read_samples = 0;
962
963     if (!dead) {
964         return 0;
965     }
966
967     avail = alsa_get_avail (alsa->handle);
968     if (avail < 0) {
969         dolog ("Could not get number of captured frames\n");
970         return 0;
971     }
972
973     if (!avail) {
974         snd_pcm_state_t state;
975
976         state = snd_pcm_state (alsa->handle);
977         switch (state) {
978         case SND_PCM_STATE_PREPARED:
979             avail = hw->samples;
980             break;
981         case SND_PCM_STATE_SUSPENDED:
982             /* stream is suspended and waiting for an application recovery */
983             if (alsa_resume (alsa->handle)) {
984                 dolog ("Failed to resume suspended input stream\n");
985                 return 0;
986             }
987             if (conf.verbose) {
988                 dolog ("Resuming suspended input stream\n");
989             }
990             break;
991         default:
992             if (conf.verbose) {
993                 dolog ("No frames available and ALSA state is %d\n", state);
994             }
995             return 0;
996         }
997     }
998
999     decr = audio_MIN (dead, avail);
1000     if (!decr) {
1001         return 0;
1002     }
1003
1004     if (hw->wpos + decr > hw->samples) {
1005         bufs[0].len = (hw->samples - hw->wpos);
1006         bufs[1].len = (decr - (hw->samples - hw->wpos));
1007     }
1008     else {
1009         bufs[0].len = decr;
1010     }
1011
1012     for (i = 0; i < 2; ++i) {
1013         void *src;
1014         struct st_sample *dst;
1015         snd_pcm_sframes_t nread;
1016         snd_pcm_uframes_t len;
1017
1018         len = bufs[i].len;
1019
1020         src = advance (alsa->pcm_buf, bufs[i].add << hwshift);
1021         dst = hw->conv_buf + bufs[i].add;
1022
1023         while (len) {
1024             nread = snd_pcm_readi (alsa->handle, src, len);
1025
1026             if (nread <= 0) {
1027                 switch (nread) {
1028                 case 0:
1029                     if (conf.verbose) {
1030                         dolog ("Failed to read %ld frames (read zero)\n", len);
1031                     }
1032                     goto exit;
1033
1034                 case -EPIPE:
1035                     if (alsa_recover (alsa->handle)) {
1036                         alsa_logerr (nread, "Failed to read %ld frames\n", len);
1037                         goto exit;
1038                     }
1039                     if (conf.verbose) {
1040                         dolog ("Recovering from capture xrun\n");
1041                     }
1042                     continue;
1043
1044                 case -EAGAIN:
1045                     goto exit;
1046
1047                 default:
1048                     alsa_logerr (
1049                         nread,
1050                         "Failed to read %ld frames from %p\n",
1051                         len,
1052                         src
1053                         );
1054                     goto exit;
1055                 }
1056             }
1057
1058             hw->conv (dst, src, nread, &nominal_volume);
1059
1060             src = advance (src, nread << hwshift);
1061             dst += nread;
1062
1063             read_samples += nread;
1064             len -= nread;
1065         }
1066     }
1067
1068  exit:
1069     hw->wpos = (hw->wpos + read_samples) % hw->samples;
1070     return read_samples;
1071 }
1072
1073 static int alsa_read (SWVoiceIn *sw, void *buf, int size)
1074 {
1075     return audio_pcm_sw_read (sw, buf, size);
1076 }
1077
1078 static int alsa_ctl_in (HWVoiceIn *hw, int cmd, ...)
1079 {
1080     va_list ap;
1081     int poll_mode;
1082     ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
1083
1084     va_start (ap, cmd);
1085     poll_mode = va_arg (ap, int);
1086     va_end (ap);
1087
1088     switch (cmd) {
1089     case VOICE_ENABLE:
1090         ldebug ("enabling voice\n");
1091         if (poll_mode && alsa_poll_in (hw)) {
1092             poll_mode = 0;
1093         }
1094         hw->poll_mode = poll_mode;
1095
1096         return alsa_voice_ctl (alsa->handle, "capture", 0);
1097
1098     case VOICE_DISABLE:
1099         ldebug ("disabling voice\n");
1100         if (hw->poll_mode) {
1101             hw->poll_mode = 0;
1102             alsa_fini_poll (&alsa->pollhlp);
1103         }
1104         return alsa_voice_ctl (alsa->handle, "capture", 1);
1105     }
1106
1107     return -1;
1108 }
1109
1110 static void *alsa_audio_init (void)
1111 {
1112     return &conf;
1113 }
1114
1115 static void alsa_audio_fini (void *opaque)
1116 {
1117     (void) opaque;
1118 }
1119
1120 static struct audio_option alsa_options[] = {
1121     {
1122         .name        = "DAC_SIZE_IN_USEC",
1123         .tag         = AUD_OPT_BOOL,
1124         .valp        = &conf.size_in_usec_out,
1125         .descr       = "DAC period/buffer size in microseconds (otherwise in frames)"
1126     },
1127     {
1128         .name        = "DAC_PERIOD_SIZE",
1129         .tag         = AUD_OPT_INT,
1130         .valp        = &conf.period_size_out,
1131         .descr       = "DAC period size (0 to go with system default)",
1132         .overriddenp = &conf.period_size_out_overridden
1133     },
1134     {
1135         .name        = "DAC_BUFFER_SIZE",
1136         .tag         = AUD_OPT_INT,
1137         .valp        = &conf.buffer_size_out,
1138         .descr       = "DAC buffer size (0 to go with system default)",
1139         .overriddenp = &conf.buffer_size_out_overridden
1140     },
1141     {
1142         .name        = "ADC_SIZE_IN_USEC",
1143         .tag         = AUD_OPT_BOOL,
1144         .valp        = &conf.size_in_usec_in,
1145         .descr       =
1146         "ADC period/buffer size in microseconds (otherwise in frames)"
1147     },
1148     {
1149         .name        = "ADC_PERIOD_SIZE",
1150         .tag         = AUD_OPT_INT,
1151         .valp        = &conf.period_size_in,
1152         .descr       = "ADC period size (0 to go with system default)",
1153         .overriddenp = &conf.period_size_in_overridden
1154     },
1155     {
1156         .name        = "ADC_BUFFER_SIZE",
1157         .tag         = AUD_OPT_INT,
1158         .valp        = &conf.buffer_size_in,
1159         .descr       = "ADC buffer size (0 to go with system default)",
1160         .overriddenp = &conf.buffer_size_in_overridden
1161     },
1162     {
1163         .name        = "THRESHOLD",
1164         .tag         = AUD_OPT_INT,
1165         .valp        = &conf.threshold,
1166         .descr       = "(undocumented)"
1167     },
1168     {
1169         .name        = "DAC_DEV",
1170         .tag         = AUD_OPT_STR,
1171         .valp        = &conf.pcm_name_out,
1172         .descr       = "DAC device name (for instance dmix)"
1173     },
1174     {
1175         .name        = "ADC_DEV",
1176         .tag         = AUD_OPT_STR,
1177         .valp        = &conf.pcm_name_in,
1178         .descr       = "ADC device name"
1179     },
1180     {
1181         .name        = "VERBOSE",
1182         .tag         = AUD_OPT_BOOL,
1183         .valp        = &conf.verbose,
1184         .descr       = "Behave in a more verbose way"
1185     },
1186     { /* End of list */ }
1187 };
1188
1189 static struct audio_pcm_ops alsa_pcm_ops = {
1190     .init_out = alsa_init_out,
1191     .fini_out = alsa_fini_out,
1192     .run_out  = alsa_run_out,
1193     .write    = alsa_write,
1194     .ctl_out  = alsa_ctl_out,
1195
1196     .init_in  = alsa_init_in,
1197     .fini_in  = alsa_fini_in,
1198     .run_in   = alsa_run_in,
1199     .read     = alsa_read,
1200     .ctl_in   = alsa_ctl_in,
1201 };
1202
1203 struct audio_driver alsa_audio_driver = {
1204     .name           = "alsa",
1205     .descr          = "ALSA http://www.alsa-project.org",
1206     .options        = alsa_options,
1207     .init           = alsa_audio_init,
1208     .fini           = alsa_audio_fini,
1209     .pcm_ops        = &alsa_pcm_ops,
1210     .can_be_default = 1,
1211     .max_voices_out = INT_MAX,
1212     .max_voices_in  = INT_MAX,
1213     .voice_size_out = sizeof (ALSAVoiceOut),
1214     .voice_size_in  = sizeof (ALSAVoiceIn)
1215 };