xref: /openbmc/qemu/audio/alsaaudio.c (revision 6c35ed68)
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 
25 #include "qemu/osdep.h"
26 #include <alsa/asoundlib.h>
27 #include "qemu/main-loop.h"
28 #include "qemu/module.h"
29 #include "audio.h"
30 #include "trace.h"
31 
32 #pragma GCC diagnostic ignored "-Waddress"
33 
34 #define AUDIO_CAP "alsa"
35 #include "audio_int.h"
36 
37 struct pollhlp {
38     snd_pcm_t *handle;
39     struct pollfd *pfds;
40     int count;
41     int mask;
42     AudioState *s;
43 };
44 
45 typedef struct ALSAVoiceOut {
46     HWVoiceOut hw;
47     snd_pcm_t *handle;
48     struct pollhlp pollhlp;
49     Audiodev *dev;
50 } ALSAVoiceOut;
51 
52 typedef struct ALSAVoiceIn {
53     HWVoiceIn hw;
54     snd_pcm_t *handle;
55     struct pollhlp pollhlp;
56     Audiodev *dev;
57 } ALSAVoiceIn;
58 
59 struct alsa_params_req {
60     int freq;
61     snd_pcm_format_t fmt;
62     int nchannels;
63 };
64 
65 struct alsa_params_obt {
66     int freq;
67     AudioFormat fmt;
68     int endianness;
69     int nchannels;
70     snd_pcm_uframes_t samples;
71 };
72 
73 static void GCC_FMT_ATTR (2, 3) alsa_logerr (int err, const char *fmt, ...)
74 {
75     va_list ap;
76 
77     va_start (ap, fmt);
78     AUD_vlog (AUDIO_CAP, fmt, ap);
79     va_end (ap);
80 
81     AUD_log (AUDIO_CAP, "Reason: %s\n", snd_strerror (err));
82 }
83 
84 static void GCC_FMT_ATTR (3, 4) alsa_logerr2 (
85     int err,
86     const char *typ,
87     const char *fmt,
88     ...
89     )
90 {
91     va_list ap;
92 
93     AUD_log (AUDIO_CAP, "Could not initialize %s\n", typ);
94 
95     va_start (ap, fmt);
96     AUD_vlog (AUDIO_CAP, fmt, ap);
97     va_end (ap);
98 
99     AUD_log (AUDIO_CAP, "Reason: %s\n", snd_strerror (err));
100 }
101 
102 static void alsa_fini_poll (struct pollhlp *hlp)
103 {
104     int i;
105     struct pollfd *pfds = hlp->pfds;
106 
107     if (pfds) {
108         for (i = 0; i < hlp->count; ++i) {
109             qemu_set_fd_handler (pfds[i].fd, NULL, NULL, NULL);
110         }
111         g_free (pfds);
112     }
113     hlp->pfds = NULL;
114     hlp->count = 0;
115     hlp->handle = NULL;
116 }
117 
118 static void alsa_anal_close1 (snd_pcm_t **handlep)
119 {
120     int err = snd_pcm_close (*handlep);
121     if (err) {
122         alsa_logerr (err, "Failed to close PCM handle %p\n", *handlep);
123     }
124     *handlep = NULL;
125 }
126 
127 static void alsa_anal_close (snd_pcm_t **handlep, struct pollhlp *hlp)
128 {
129     alsa_fini_poll (hlp);
130     alsa_anal_close1 (handlep);
131 }
132 
133 static int alsa_recover (snd_pcm_t *handle)
134 {
135     int err = snd_pcm_prepare (handle);
136     if (err < 0) {
137         alsa_logerr (err, "Failed to prepare handle %p\n", handle);
138         return -1;
139     }
140     return 0;
141 }
142 
143 static int alsa_resume (snd_pcm_t *handle)
144 {
145     int err = snd_pcm_resume (handle);
146     if (err < 0) {
147         alsa_logerr (err, "Failed to resume handle %p\n", handle);
148         return -1;
149     }
150     return 0;
151 }
152 
153 static void alsa_poll_handler (void *opaque)
154 {
155     int err, count;
156     snd_pcm_state_t state;
157     struct pollhlp *hlp = opaque;
158     unsigned short revents;
159 
160     count = poll (hlp->pfds, hlp->count, 0);
161     if (count < 0) {
162         dolog ("alsa_poll_handler: poll %s\n", strerror (errno));
163         return;
164     }
165 
166     if (!count) {
167         return;
168     }
169 
170     /* XXX: ALSA example uses initial count, not the one returned by
171        poll, correct? */
172     err = snd_pcm_poll_descriptors_revents (hlp->handle, hlp->pfds,
173                                             hlp->count, &revents);
174     if (err < 0) {
175         alsa_logerr (err, "snd_pcm_poll_descriptors_revents");
176         return;
177     }
178 
179     if (!(revents & hlp->mask)) {
180         trace_alsa_revents(revents);
181         return;
182     }
183 
184     state = snd_pcm_state (hlp->handle);
185     switch (state) {
186     case SND_PCM_STATE_SETUP:
187         alsa_recover (hlp->handle);
188         break;
189 
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(hlp->s, "alsa run (prepared)");
200         break;
201 
202     case SND_PCM_STATE_RUNNING:
203         audio_run(hlp->s, "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, int mask)
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         g_free (pfds);
234         return -1;
235     }
236 
237     for (i = 0; i < count; ++i) {
238         if (pfds[i].events & POLLIN) {
239             qemu_set_fd_handler (pfds[i].fd, alsa_poll_handler, NULL, hlp);
240         }
241         if (pfds[i].events & POLLOUT) {
242             trace_alsa_pollout(i, pfds[i].fd);
243             qemu_set_fd_handler (pfds[i].fd, NULL, alsa_poll_handler, hlp);
244         }
245         trace_alsa_set_handler(pfds[i].events, i, pfds[i].fd, err);
246 
247     }
248     hlp->pfds = pfds;
249     hlp->count = count;
250     hlp->handle = handle;
251     hlp->mask = mask;
252     return 0;
253 }
254 
255 static int alsa_poll_out (HWVoiceOut *hw)
256 {
257     ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
258 
259     return alsa_poll_helper (alsa->handle, &alsa->pollhlp, POLLOUT);
260 }
261 
262 static int alsa_poll_in (HWVoiceIn *hw)
263 {
264     ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
265 
266     return alsa_poll_helper (alsa->handle, &alsa->pollhlp, POLLIN);
267 }
268 
269 static snd_pcm_format_t aud_to_alsafmt (AudioFormat fmt, int endianness)
270 {
271     switch (fmt) {
272     case AUDIO_FORMAT_S8:
273         return SND_PCM_FORMAT_S8;
274 
275     case AUDIO_FORMAT_U8:
276         return SND_PCM_FORMAT_U8;
277 
278     case AUDIO_FORMAT_S16:
279         if (endianness) {
280             return SND_PCM_FORMAT_S16_BE;
281         }
282         else {
283             return SND_PCM_FORMAT_S16_LE;
284         }
285 
286     case AUDIO_FORMAT_U16:
287         if (endianness) {
288             return SND_PCM_FORMAT_U16_BE;
289         }
290         else {
291             return SND_PCM_FORMAT_U16_LE;
292         }
293 
294     case AUDIO_FORMAT_S32:
295         if (endianness) {
296             return SND_PCM_FORMAT_S32_BE;
297         }
298         else {
299             return SND_PCM_FORMAT_S32_LE;
300         }
301 
302     case AUDIO_FORMAT_U32:
303         if (endianness) {
304             return SND_PCM_FORMAT_U32_BE;
305         }
306         else {
307             return SND_PCM_FORMAT_U32_LE;
308         }
309 
310     default:
311         dolog ("Internal logic error: Bad audio format %d\n", fmt);
312 #ifdef DEBUG_AUDIO
313         abort ();
314 #endif
315         return SND_PCM_FORMAT_U8;
316     }
317 }
318 
319 static int alsa_to_audfmt (snd_pcm_format_t alsafmt, AudioFormat *fmt,
320                            int *endianness)
321 {
322     switch (alsafmt) {
323     case SND_PCM_FORMAT_S8:
324         *endianness = 0;
325         *fmt = AUDIO_FORMAT_S8;
326         break;
327 
328     case SND_PCM_FORMAT_U8:
329         *endianness = 0;
330         *fmt = AUDIO_FORMAT_U8;
331         break;
332 
333     case SND_PCM_FORMAT_S16_LE:
334         *endianness = 0;
335         *fmt = AUDIO_FORMAT_S16;
336         break;
337 
338     case SND_PCM_FORMAT_U16_LE:
339         *endianness = 0;
340         *fmt = AUDIO_FORMAT_U16;
341         break;
342 
343     case SND_PCM_FORMAT_S16_BE:
344         *endianness = 1;
345         *fmt = AUDIO_FORMAT_S16;
346         break;
347 
348     case SND_PCM_FORMAT_U16_BE:
349         *endianness = 1;
350         *fmt = AUDIO_FORMAT_U16;
351         break;
352 
353     case SND_PCM_FORMAT_S32_LE:
354         *endianness = 0;
355         *fmt = AUDIO_FORMAT_S32;
356         break;
357 
358     case SND_PCM_FORMAT_U32_LE:
359         *endianness = 0;
360         *fmt = AUDIO_FORMAT_U32;
361         break;
362 
363     case SND_PCM_FORMAT_S32_BE:
364         *endianness = 1;
365         *fmt = AUDIO_FORMAT_S32;
366         break;
367 
368     case SND_PCM_FORMAT_U32_BE:
369         *endianness = 1;
370         *fmt = AUDIO_FORMAT_U32;
371         break;
372 
373     default:
374         dolog ("Unrecognized audio format %d\n", alsafmt);
375         return -1;
376     }
377 
378     return 0;
379 }
380 
381 static void alsa_dump_info (struct alsa_params_req *req,
382                             struct alsa_params_obt *obt,
383                             snd_pcm_format_t obtfmt,
384                             AudiodevAlsaPerDirectionOptions *apdo)
385 {
386     dolog("parameter | requested value | obtained value\n");
387     dolog("format    |      %10d |     %10d\n", req->fmt, obtfmt);
388     dolog("channels  |      %10d |     %10d\n",
389           req->nchannels, obt->nchannels);
390     dolog("frequency |      %10d |     %10d\n", req->freq, obt->freq);
391     dolog("============================================\n");
392     dolog("requested: buffer len %" PRId32 " period len %" PRId32 "\n",
393           apdo->buffer_length, apdo->period_length);
394     dolog("obtained: samples %ld\n", obt->samples);
395 }
396 
397 static void alsa_set_threshold (snd_pcm_t *handle, snd_pcm_uframes_t threshold)
398 {
399     int err;
400     snd_pcm_sw_params_t *sw_params;
401 
402     snd_pcm_sw_params_alloca (&sw_params);
403 
404     err = snd_pcm_sw_params_current (handle, sw_params);
405     if (err < 0) {
406         dolog ("Could not fully initialize DAC\n");
407         alsa_logerr (err, "Failed to get current software parameters\n");
408         return;
409     }
410 
411     err = snd_pcm_sw_params_set_start_threshold (handle, sw_params, threshold);
412     if (err < 0) {
413         dolog ("Could not fully initialize DAC\n");
414         alsa_logerr (err, "Failed to set software threshold to %ld\n",
415                      threshold);
416         return;
417     }
418 
419     err = snd_pcm_sw_params (handle, sw_params);
420     if (err < 0) {
421         dolog ("Could not fully initialize DAC\n");
422         alsa_logerr (err, "Failed to set software parameters\n");
423         return;
424     }
425 }
426 
427 static int alsa_open(bool in, struct alsa_params_req *req,
428                      struct alsa_params_obt *obt, snd_pcm_t **handlep,
429                      Audiodev *dev)
430 {
431     AudiodevAlsaOptions *aopts = &dev->u.alsa;
432     AudiodevAlsaPerDirectionOptions *apdo = in ? aopts->in : aopts->out;
433     snd_pcm_t *handle;
434     snd_pcm_hw_params_t *hw_params;
435     int err;
436     unsigned int freq, nchannels;
437     const char *pcm_name = apdo->has_dev ? apdo->dev : "default";
438     snd_pcm_uframes_t obt_buffer_size;
439     const char *typ = in ? "ADC" : "DAC";
440     snd_pcm_format_t obtfmt;
441 
442     freq = req->freq;
443     nchannels = req->nchannels;
444 
445     snd_pcm_hw_params_alloca (&hw_params);
446 
447     err = snd_pcm_open (
448         &handle,
449         pcm_name,
450         in ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
451         SND_PCM_NONBLOCK
452         );
453     if (err < 0) {
454         alsa_logerr2 (err, typ, "Failed to open `%s':\n", pcm_name);
455         return -1;
456     }
457 
458     err = snd_pcm_hw_params_any (handle, hw_params);
459     if (err < 0) {
460         alsa_logerr2 (err, typ, "Failed to initialize hardware parameters\n");
461         goto err;
462     }
463 
464     err = snd_pcm_hw_params_set_access (
465         handle,
466         hw_params,
467         SND_PCM_ACCESS_RW_INTERLEAVED
468         );
469     if (err < 0) {
470         alsa_logerr2 (err, typ, "Failed to set access type\n");
471         goto err;
472     }
473 
474     err = snd_pcm_hw_params_set_format (handle, hw_params, req->fmt);
475     if (err < 0) {
476         alsa_logerr2 (err, typ, "Failed to set format %d\n", req->fmt);
477     }
478 
479     err = snd_pcm_hw_params_set_rate_near (handle, hw_params, &freq, 0);
480     if (err < 0) {
481         alsa_logerr2 (err, typ, "Failed to set frequency %d\n", req->freq);
482         goto err;
483     }
484 
485     err = snd_pcm_hw_params_set_channels_near (
486         handle,
487         hw_params,
488         &nchannels
489         );
490     if (err < 0) {
491         alsa_logerr2 (err, typ, "Failed to set number of channels %d\n",
492                       req->nchannels);
493         goto err;
494     }
495 
496     if (nchannels != 1 && nchannels != 2) {
497         alsa_logerr2 (err, typ,
498                       "Can not handle obtained number of channels %d\n",
499                       nchannels);
500         goto err;
501     }
502 
503     if (apdo->buffer_length) {
504         int dir = 0;
505         unsigned int btime = apdo->buffer_length;
506 
507         err = snd_pcm_hw_params_set_buffer_time_near(
508             handle, hw_params, &btime, &dir);
509 
510         if (err < 0) {
511             alsa_logerr2(err, typ, "Failed to set buffer time to %" PRId32 "\n",
512                          apdo->buffer_length);
513             goto err;
514         }
515 
516         if (apdo->has_buffer_length && btime != apdo->buffer_length) {
517             dolog("Requested buffer time %" PRId32
518                   " was rejected, using %u\n", apdo->buffer_length, btime);
519         }
520     }
521 
522     if (apdo->period_length) {
523         int dir = 0;
524         unsigned int ptime = apdo->period_length;
525 
526         err = snd_pcm_hw_params_set_period_time_near(handle, hw_params, &ptime,
527                                                      &dir);
528 
529         if (err < 0) {
530             alsa_logerr2(err, typ, "Failed to set period time to %" PRId32 "\n",
531                          apdo->period_length);
532             goto err;
533         }
534 
535         if (apdo->has_period_length && ptime != apdo->period_length) {
536             dolog("Requested period time %" PRId32 " was rejected, using %d\n",
537                   apdo->period_length, ptime);
538         }
539     }
540 
541     err = snd_pcm_hw_params (handle, hw_params);
542     if (err < 0) {
543         alsa_logerr2 (err, typ, "Failed to apply audio parameters\n");
544         goto err;
545     }
546 
547     err = snd_pcm_hw_params_get_buffer_size (hw_params, &obt_buffer_size);
548     if (err < 0) {
549         alsa_logerr2 (err, typ, "Failed to get buffer size\n");
550         goto err;
551     }
552 
553     err = snd_pcm_hw_params_get_format (hw_params, &obtfmt);
554     if (err < 0) {
555         alsa_logerr2 (err, typ, "Failed to get format\n");
556         goto err;
557     }
558 
559     if (alsa_to_audfmt (obtfmt, &obt->fmt, &obt->endianness)) {
560         dolog ("Invalid format was returned %d\n", obtfmt);
561         goto err;
562     }
563 
564     err = snd_pcm_prepare (handle);
565     if (err < 0) {
566         alsa_logerr2 (err, typ, "Could not prepare handle %p\n", handle);
567         goto err;
568     }
569 
570     if (!in && aopts->has_threshold && aopts->threshold) {
571         struct audsettings as = { .freq = freq };
572         alsa_set_threshold(
573             handle,
574             audio_buffer_frames(qapi_AudiodevAlsaPerDirectionOptions_base(apdo),
575                                 &as, aopts->threshold));
576     }
577 
578     obt->nchannels = nchannels;
579     obt->freq = freq;
580     obt->samples = obt_buffer_size;
581 
582     *handlep = handle;
583 
584     if (obtfmt != req->fmt ||
585          obt->nchannels != req->nchannels ||
586          obt->freq != req->freq) {
587         dolog ("Audio parameters for %s\n", typ);
588         alsa_dump_info(req, obt, obtfmt, apdo);
589     }
590 
591 #ifdef DEBUG
592     alsa_dump_info(req, obt, obtfmt, pdo);
593 #endif
594     return 0;
595 
596  err:
597     alsa_anal_close1 (&handle);
598     return -1;
599 }
600 
601 static size_t alsa_write(HWVoiceOut *hw, void *buf, size_t len)
602 {
603     ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
604     size_t pos = 0;
605     size_t len_frames = len >> hw->info.shift;
606 
607     while (len_frames) {
608         char *src = advance(buf, pos);
609         snd_pcm_sframes_t written;
610 
611         written = snd_pcm_writei(alsa->handle, src, len_frames);
612 
613         if (written <= 0) {
614             switch (written) {
615             case 0:
616                 trace_alsa_wrote_zero(len_frames);
617                 return pos;
618 
619             case -EPIPE:
620                 if (alsa_recover(alsa->handle)) {
621                     alsa_logerr(written, "Failed to write %zu frames\n",
622                                 len_frames);
623                     return pos;
624                 }
625                 trace_alsa_xrun_out();
626                 continue;
627 
628             case -ESTRPIPE:
629                 /*
630                  * stream is suspended and waiting for an application
631                  * recovery
632                  */
633                 if (alsa_resume(alsa->handle)) {
634                     alsa_logerr(written, "Failed to write %zu frames\n",
635                                 len_frames);
636                     return pos;
637                 }
638                 trace_alsa_resume_out();
639                 continue;
640 
641             case -EAGAIN:
642                 return pos;
643 
644             default:
645                 alsa_logerr(written, "Failed to write %zu frames from %p\n",
646                             len, src);
647                 return pos;
648             }
649         }
650 
651         pos += written << hw->info.shift;
652         if (written < len_frames) {
653             break;
654         }
655         len_frames -= written;
656     }
657 
658     return pos;
659 }
660 
661 static void alsa_fini_out (HWVoiceOut *hw)
662 {
663     ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
664 
665     ldebug ("alsa_fini\n");
666     alsa_anal_close (&alsa->handle, &alsa->pollhlp);
667 }
668 
669 static int alsa_init_out(HWVoiceOut *hw, struct audsettings *as,
670                          void *drv_opaque)
671 {
672     ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
673     struct alsa_params_req req;
674     struct alsa_params_obt obt;
675     snd_pcm_t *handle;
676     struct audsettings obt_as;
677     Audiodev *dev = drv_opaque;
678 
679     req.fmt = aud_to_alsafmt (as->fmt, as->endianness);
680     req.freq = as->freq;
681     req.nchannels = as->nchannels;
682 
683     if (alsa_open(0, &req, &obt, &handle, dev)) {
684         return -1;
685     }
686 
687     obt_as.freq = obt.freq;
688     obt_as.nchannels = obt.nchannels;
689     obt_as.fmt = obt.fmt;
690     obt_as.endianness = obt.endianness;
691 
692     audio_pcm_init_info (&hw->info, &obt_as);
693     hw->samples = obt.samples;
694 
695     alsa->pollhlp.s = hw->s;
696     alsa->handle = handle;
697     alsa->dev = dev;
698     return 0;
699 }
700 
701 #define VOICE_CTL_PAUSE 0
702 #define VOICE_CTL_PREPARE 1
703 #define VOICE_CTL_START 2
704 
705 static int alsa_voice_ctl (snd_pcm_t *handle, const char *typ, int ctl)
706 {
707     int err;
708 
709     if (ctl == VOICE_CTL_PAUSE) {
710         err = snd_pcm_drop (handle);
711         if (err < 0) {
712             alsa_logerr (err, "Could not stop %s\n", typ);
713             return -1;
714         }
715     }
716     else {
717         err = snd_pcm_prepare (handle);
718         if (err < 0) {
719             alsa_logerr (err, "Could not prepare handle for %s\n", typ);
720             return -1;
721         }
722         if (ctl == VOICE_CTL_START) {
723             err = snd_pcm_start(handle);
724             if (err < 0) {
725                 alsa_logerr (err, "Could not start handle for %s\n", typ);
726                 return -1;
727             }
728         }
729     }
730 
731     return 0;
732 }
733 
734 static void alsa_enable_out(HWVoiceOut *hw, bool enable)
735 {
736     ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
737     AudiodevAlsaPerDirectionOptions *apdo = alsa->dev->u.alsa.out;
738 
739     if (enable) {
740         bool poll_mode = apdo->try_poll;
741 
742         ldebug("enabling voice\n");
743         if (poll_mode && alsa_poll_out(hw)) {
744             poll_mode = 0;
745         }
746         hw->poll_mode = poll_mode;
747         alsa_voice_ctl(alsa->handle, "playback", VOICE_CTL_PREPARE);
748     } else {
749         ldebug("disabling voice\n");
750         if (hw->poll_mode) {
751             hw->poll_mode = 0;
752             alsa_fini_poll(&alsa->pollhlp);
753         }
754         alsa_voice_ctl(alsa->handle, "playback", VOICE_CTL_PAUSE);
755     }
756 }
757 
758 static int alsa_init_in(HWVoiceIn *hw, struct audsettings *as, void *drv_opaque)
759 {
760     ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
761     struct alsa_params_req req;
762     struct alsa_params_obt obt;
763     snd_pcm_t *handle;
764     struct audsettings obt_as;
765     Audiodev *dev = drv_opaque;
766 
767     req.fmt = aud_to_alsafmt (as->fmt, as->endianness);
768     req.freq = as->freq;
769     req.nchannels = as->nchannels;
770 
771     if (alsa_open(1, &req, &obt, &handle, dev)) {
772         return -1;
773     }
774 
775     obt_as.freq = obt.freq;
776     obt_as.nchannels = obt.nchannels;
777     obt_as.fmt = obt.fmt;
778     obt_as.endianness = obt.endianness;
779 
780     audio_pcm_init_info (&hw->info, &obt_as);
781     hw->samples = obt.samples;
782 
783     alsa->pollhlp.s = hw->s;
784     alsa->handle = handle;
785     alsa->dev = dev;
786     return 0;
787 }
788 
789 static void alsa_fini_in (HWVoiceIn *hw)
790 {
791     ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
792 
793     alsa_anal_close (&alsa->handle, &alsa->pollhlp);
794 }
795 
796 static size_t alsa_read(HWVoiceIn *hw, void *buf, size_t len)
797 {
798     ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
799     size_t pos = 0;
800 
801     while (len) {
802         void *dst = advance(buf, pos);
803         snd_pcm_sframes_t nread;
804 
805         nread = snd_pcm_readi(alsa->handle, dst, len >> hw->info.shift);
806 
807         if (nread <= 0) {
808             switch (nread) {
809             case 0:
810                 trace_alsa_read_zero(len);
811                 return pos;;
812 
813             case -EPIPE:
814                 if (alsa_recover(alsa->handle)) {
815                     alsa_logerr(nread, "Failed to read %zu frames\n", len);
816                     return pos;
817                 }
818                 trace_alsa_xrun_in();
819                 continue;
820 
821             case -EAGAIN:
822                 return pos;
823 
824             default:
825                 alsa_logerr(nread, "Failed to read %zu frames to %p\n",
826                             len, dst);
827                 return pos;;
828             }
829         }
830 
831         pos += nread << hw->info.shift;
832         len -= nread << hw->info.shift;
833     }
834 
835     return pos;
836 }
837 
838 static void alsa_enable_in(HWVoiceIn *hw, bool enable)
839 {
840     ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
841     AudiodevAlsaPerDirectionOptions *apdo = alsa->dev->u.alsa.in;
842 
843     if (enable) {
844         bool poll_mode = apdo->try_poll;
845 
846         ldebug("enabling voice\n");
847         if (poll_mode && alsa_poll_in(hw)) {
848             poll_mode = 0;
849         }
850         hw->poll_mode = poll_mode;
851 
852         alsa_voice_ctl(alsa->handle, "capture", VOICE_CTL_START);
853     } else {
854         ldebug ("disabling voice\n");
855         if (hw->poll_mode) {
856             hw->poll_mode = 0;
857             alsa_fini_poll(&alsa->pollhlp);
858         }
859         alsa_voice_ctl(alsa->handle, "capture", VOICE_CTL_PAUSE);
860     }
861 }
862 
863 static void alsa_init_per_direction(AudiodevAlsaPerDirectionOptions *apdo)
864 {
865     if (!apdo->has_try_poll) {
866         apdo->try_poll = true;
867         apdo->has_try_poll = true;
868     }
869 }
870 
871 static void *alsa_audio_init(Audiodev *dev)
872 {
873     AudiodevAlsaOptions *aopts;
874     assert(dev->driver == AUDIODEV_DRIVER_ALSA);
875 
876     aopts = &dev->u.alsa;
877     alsa_init_per_direction(aopts->in);
878     alsa_init_per_direction(aopts->out);
879 
880     /*
881      * need to define them, as otherwise alsa produces no sound
882      * doesn't set has_* so alsa_open can identify it wasn't set by the user
883      */
884     if (!dev->u.alsa.out->has_period_length) {
885         /* 1024 frames assuming 44100Hz */
886         dev->u.alsa.out->period_length = 1024 * 1000000 / 44100;
887     }
888     if (!dev->u.alsa.out->has_buffer_length) {
889         /* 4096 frames assuming 44100Hz */
890         dev->u.alsa.out->buffer_length = 4096ll * 1000000 / 44100;
891     }
892 
893     /*
894      * OptsVisitor sets unspecified optional fields to zero, but do not depend
895      * on it...
896      */
897     if (!dev->u.alsa.in->has_period_length) {
898         dev->u.alsa.in->period_length = 0;
899     }
900     if (!dev->u.alsa.in->has_buffer_length) {
901         dev->u.alsa.in->buffer_length = 0;
902     }
903 
904     return dev;
905 }
906 
907 static void alsa_audio_fini (void *opaque)
908 {
909 }
910 
911 static struct audio_pcm_ops alsa_pcm_ops = {
912     .init_out = alsa_init_out,
913     .fini_out = alsa_fini_out,
914     .write    = alsa_write,
915     .enable_out = alsa_enable_out,
916 
917     .init_in  = alsa_init_in,
918     .fini_in  = alsa_fini_in,
919     .read     = alsa_read,
920     .enable_in = alsa_enable_in,
921 };
922 
923 static struct audio_driver alsa_audio_driver = {
924     .name           = "alsa",
925     .descr          = "ALSA http://www.alsa-project.org",
926     .init           = alsa_audio_init,
927     .fini           = alsa_audio_fini,
928     .pcm_ops        = &alsa_pcm_ops,
929     .can_be_default = 1,
930     .max_voices_out = INT_MAX,
931     .max_voices_in  = INT_MAX,
932     .voice_size_out = sizeof (ALSAVoiceOut),
933     .voice_size_in  = sizeof (ALSAVoiceIn)
934 };
935 
936 static void register_audio_alsa(void)
937 {
938     audio_driver_register(&alsa_audio_driver);
939 }
940 type_init(register_audio_alsa);
941