• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * QEMU ALSA audio driver
3  *
4  * Copyright (c) 2008 The Android Open Source Project
5  * Copyright (c) 2005 Vassili Karpov (malc)
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  */
25 #include <alsa/asoundlib.h>
26 #include "qemu-common.h"
27 #include "audio.h"
28 
29 #define AUDIO_CAP "alsa"
30 #include "audio_int.h"
31 #include <dlfcn.h>
32 #include <pthread.h>
33 #include "qemu_debug.h"
34 
35 #define  DEBUG  1
36 
37 #if DEBUG
38 #  include <stdio.h>
39 #  define D(...)  VERBOSE_PRINT(audio,__VA_ARGS__)
40 #  define D_ACTIVE  VERBOSE_CHECK(audio)
41 #  define O(...)  VERBOSE_PRINT(audioout,__VA_ARGS__)
42 #  define I(...)  VERBOSE_PRINT(audioin,__VA_ARGS__)
43 #else
44 #  define D(...)  ((void)0)
45 #  define D_ACTIVE  0
46 #  define O(...)  ((void)0)
47 #  define I(...)  ((void)0)
48 #endif
49 
50 
51 #define  STRINGIFY_(x)  #x
52 #define  STRINGIFY(x)   STRINGIFY_(x)
53 
54 #define  DYNLINK_FUNCTIONS   \
55     DYNLINK_FUNC(size_t,snd_pcm_sw_params_sizeof,(void))    \
56     DYNLINK_FUNC(int,snd_pcm_hw_params_current,(snd_pcm_t *pcm, snd_pcm_hw_params_t *params)) \
57     DYNLINK_FUNC(int,snd_pcm_sw_params_set_start_threshold,(snd_pcm_t *pcm, snd_pcm_sw_params_t *params, snd_pcm_uframes_t val))  \
58     DYNLINK_FUNC(int,snd_pcm_sw_params,(snd_pcm_t *pcm, snd_pcm_sw_params_t *params))  \
59     DYNLINK_FUNC(int,snd_pcm_sw_params_current,(snd_pcm_t *pcm, snd_pcm_sw_params_t *params)) \
60     DYNLINK_FUNC(size_t,snd_pcm_hw_params_sizeof,(void))  \
61     DYNLINK_FUNC(int,snd_pcm_hw_params_any,(snd_pcm_t *pcm, snd_pcm_hw_params_t *params))  \
62     DYNLINK_FUNC(int,snd_pcm_hw_params_set_access,(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, snd_pcm_access_t _access))  \
63     DYNLINK_FUNC(int,snd_pcm_hw_params_get_format,(const snd_pcm_hw_params_t *params, snd_pcm_format_t *val)) \
64     DYNLINK_FUNC(int,snd_pcm_hw_params_set_format,(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, snd_pcm_format_t val))  \
65     DYNLINK_FUNC(int,snd_pcm_hw_params_set_rate_near,(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, unsigned int *val, int *dir))  \
66     DYNLINK_FUNC(int,snd_pcm_hw_params_set_channels_near,(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, unsigned int *val))  \
67     DYNLINK_FUNC(int,snd_pcm_hw_params_set_buffer_time_near,(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, unsigned int *val, int *dir))  \
68     DYNLINK_FUNC(int,snd_pcm_hw_params,(snd_pcm_t *pcm, snd_pcm_hw_params_t *params))  \
69     DYNLINK_FUNC(int,snd_pcm_hw_params_get_buffer_size,(const snd_pcm_hw_params_t *params, snd_pcm_uframes_t *val))  \
70     DYNLINK_FUNC(int,snd_pcm_prepare,(snd_pcm_t *pcm))  \
71     DYNLINK_FUNC(int,snd_pcm_hw_params_get_period_size,(const snd_pcm_hw_params_t *params, snd_pcm_uframes_t *frames, int *dir))  \
72     DYNLINK_FUNC(int,snd_pcm_hw_params_get_period_size_min,(const snd_pcm_hw_params_t *params, snd_pcm_uframes_t *frames, int *dir))  \
73     DYNLINK_FUNC(int,snd_pcm_hw_params_set_period_size,(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, snd_pcm_uframes_t val, int dir))  \
74     DYNLINK_FUNC(int,snd_pcm_hw_params_get_buffer_size_min,(const snd_pcm_hw_params_t *params, snd_pcm_uframes_t *val)) \
75     DYNLINK_FUNC(int,snd_pcm_hw_params_set_buffer_size,(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, snd_pcm_uframes_t val))  \
76     DYNLINK_FUNC(int,snd_pcm_hw_params_set_period_time_near,(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, unsigned int *val, int *dir))  \
77     DYNLINK_FUNC(snd_pcm_sframes_t,snd_pcm_avail_update,(snd_pcm_t *pcm)) \
78     DYNLINK_FUNC(int,snd_pcm_drop,(snd_pcm_t *pcm))  \
79     DYNLINK_FUNC(snd_pcm_sframes_t,snd_pcm_writei,(snd_pcm_t *pcm, const void *buffer, snd_pcm_uframes_t size))  \
80     DYNLINK_FUNC(snd_pcm_sframes_t,snd_pcm_readi,(snd_pcm_t *pcm, void *buffer, snd_pcm_uframes_t size))  \
81     DYNLINK_FUNC(snd_pcm_state_t,snd_pcm_state,(snd_pcm_t *pcm))  \
82     DYNLINK_FUNC(const char*,snd_strerror,(int errnum)) \
83     DYNLINK_FUNC(int,snd_pcm_open,(snd_pcm_t **pcm, const char *name,snd_pcm_stream_t stream, int mode)) \
84     DYNLINK_FUNC(int,snd_pcm_close,(snd_pcm_t *pcm))  \
85     DYNLINK_FUNC(int,snd_pcm_hw_params_set_buffer_size_near,(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, snd_pcm_uframes_t *val)) \
86     DYNLINK_FUNC(int,snd_pcm_hw_params_set_period_size_near,(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, snd_pcm_uframes_t *val, int *dir)) \
87     DYNLINK_FUNC(int,snd_pcm_hw_params_get_format,(const snd_pcm_hw_params_t *params, snd_pcm_format_t *val)) \
88 
89 #define DYNLINK_FUNCTIONS_INIT \
90     alsa_dynlink_init
91 
92 #include "dynlink.h"
93 
94 /* these are inlined functions in the original headers */
95 #define FF_snd_pcm_hw_params_alloca(ptr) \
96     do { *ptr = (snd_pcm_hw_params_t *) alloca(FF(snd_pcm_hw_params_sizeof)()); memset(*ptr, 0, FF(snd_pcm_hw_params_sizeof)()); } while (0)
97 
98 #define FF_snd_pcm_sw_params_alloca(ptr) \
99     do { *ptr = (snd_pcm_sw_params_t *) alloca(FF(snd_pcm_sw_params_sizeof)()); memset(*ptr, 0, FF(snd_pcm_sw_params_sizeof)()); } while (0)
100 
101 static void*  alsa_lib;
102 
103 typedef struct ALSAVoiceOut {
104     HWVoiceOut hw;
105     void *pcm_buf;
106     snd_pcm_t *handle;
107 } ALSAVoiceOut;
108 
109 typedef struct ALSAVoiceIn {
110     HWVoiceIn hw;
111     snd_pcm_t *handle;
112     void *pcm_buf;
113 } ALSAVoiceIn;
114 
115 static struct {
116     int size_in_usec_in;
117     int size_in_usec_out;
118     const char *pcm_name_in;
119     const char *pcm_name_out;
120     unsigned int buffer_size_in;
121     unsigned int period_size_in;
122     unsigned int buffer_size_out;
123     unsigned int period_size_out;
124     unsigned int threshold;
125 
126     int buffer_size_in_overridden;
127     int period_size_in_overridden;
128 
129     int buffer_size_out_overridden;
130     int period_size_out_overridden;
131     int verbose;
132 } conf = {
133     .buffer_size_out = 1024,
134     .pcm_name_out = "default",
135     .pcm_name_in = "default",
136 };
137 
138 struct alsa_params_req {
139     int freq;
140     snd_pcm_format_t fmt;
141     int nchannels;
142     int size_in_usec;
143     int override_mask;
144     unsigned int buffer_size;
145     unsigned int period_size;
146 };
147 
148 struct alsa_params_obt {
149     int freq;
150     audfmt_e fmt;
151     int endianness;
152     int nchannels;
153     snd_pcm_uframes_t samples;
154 };
155 
alsa_logerr(int err,const char * fmt,...)156 static void GCC_FMT_ATTR (2, 3) alsa_logerr (int err, const char *fmt, ...)
157 {
158     va_list ap;
159 
160     va_start (ap, fmt);
161     AUD_vlog (AUDIO_CAP, fmt, ap);
162     va_end (ap);
163 
164     AUD_log (AUDIO_CAP, "Reason: %s\n", FF(snd_strerror) (err));
165 }
166 
alsa_logerr2(int err,const char * typ,const char * fmt,...)167 static void GCC_FMT_ATTR (3, 4) alsa_logerr2 (
168     int err,
169     const char *typ,
170     const char *fmt,
171     ...
172     )
173 {
174     va_list ap;
175 
176     AUD_log (AUDIO_CAP, "Could not initialize %s\n", typ);
177 
178     va_start (ap, fmt);
179     AUD_vlog (AUDIO_CAP, fmt, ap);
180     va_end (ap);
181 
182     AUD_log (AUDIO_CAP, "Reason: %s\n", FF(snd_strerror) (err));
183 }
184 
alsa_anal_close(snd_pcm_t ** handlep)185 static void alsa_anal_close (snd_pcm_t **handlep)
186 {
187     int err = FF(snd_pcm_close) (*handlep);
188     if (err) {
189         alsa_logerr (err, "Failed to close PCM handle %p\n", *handlep);
190     }
191     *handlep = NULL;
192 }
193 
alsa_write(SWVoiceOut * sw,void * buf,int len)194 static int alsa_write (SWVoiceOut *sw, void *buf, int len)
195 {
196     return audio_pcm_sw_write (sw, buf, len);
197 }
198 
aud_to_alsafmt(audfmt_e fmt)199 static snd_pcm_format_t aud_to_alsafmt (audfmt_e fmt)
200 {
201     switch (fmt) {
202     case AUD_FMT_S8:
203         return SND_PCM_FORMAT_S8;
204 
205     case AUD_FMT_U8:
206         return SND_PCM_FORMAT_U8;
207 
208     case AUD_FMT_S16:
209         return SND_PCM_FORMAT_S16_LE;
210 
211     case AUD_FMT_U16:
212         return SND_PCM_FORMAT_U16_LE;
213 
214     case AUD_FMT_S32:
215         return SND_PCM_FORMAT_S32_LE;
216 
217     case AUD_FMT_U32:
218         return SND_PCM_FORMAT_U32_LE;
219 
220     default:
221         dolog ("Internal logic error: Bad audio format %d\n", fmt);
222 #ifdef DEBUG_AUDIO
223         abort ();
224 #endif
225         return SND_PCM_FORMAT_U8;
226     }
227 }
228 
alsa_to_audfmt(snd_pcm_format_t alsafmt,audfmt_e * fmt,int * endianness)229 static int alsa_to_audfmt (snd_pcm_format_t alsafmt, audfmt_e *fmt,
230                            int *endianness)
231 {
232     switch (alsafmt) {
233     case SND_PCM_FORMAT_S8:
234         *endianness = 0;
235         *fmt = AUD_FMT_S8;
236         break;
237 
238     case SND_PCM_FORMAT_U8:
239         *endianness = 0;
240         *fmt = AUD_FMT_U8;
241         break;
242 
243     case SND_PCM_FORMAT_S16_LE:
244         *endianness = 0;
245         *fmt = AUD_FMT_S16;
246         break;
247 
248     case SND_PCM_FORMAT_U16_LE:
249         *endianness = 0;
250         *fmt = AUD_FMT_U16;
251         break;
252 
253     case SND_PCM_FORMAT_S16_BE:
254         *endianness = 1;
255         *fmt = AUD_FMT_S16;
256         break;
257 
258     case SND_PCM_FORMAT_U16_BE:
259         *endianness = 1;
260         *fmt = AUD_FMT_U16;
261         break;
262 
263     case SND_PCM_FORMAT_S32_LE:
264         *endianness = 0;
265         *fmt = AUD_FMT_S32;
266         break;
267 
268     case SND_PCM_FORMAT_U32_LE:
269         *endianness = 0;
270         *fmt = AUD_FMT_U32;
271         break;
272 
273     case SND_PCM_FORMAT_S32_BE:
274         *endianness = 1;
275         *fmt = AUD_FMT_S32;
276         break;
277 
278     case SND_PCM_FORMAT_U32_BE:
279         *endianness = 1;
280         *fmt = AUD_FMT_U32;
281         break;
282 
283     default:
284         dolog ("Unrecognized audio format %d\n", alsafmt);
285         return -1;
286     }
287 
288     return 0;
289 }
290 
alsa_dump_info(struct alsa_params_req * req,struct alsa_params_obt * obt)291 static void alsa_dump_info (struct alsa_params_req *req,
292                             struct alsa_params_obt *obt)
293 {
294     dolog ("parameter | requested value | obtained value\n");
295     dolog ("format    |      %10d |     %10d\n", req->fmt, obt->fmt);
296     dolog ("channels  |      %10d |     %10d\n",
297            req->nchannels, obt->nchannels);
298     dolog ("frequency |      %10d |     %10d\n", req->freq, obt->freq);
299     dolog ("============================================\n");
300     dolog ("requested: buffer size %d period size %d\n",
301            req->buffer_size, req->period_size);
302     dolog ("obtained: samples %ld\n", obt->samples);
303 }
304 
alsa_set_threshold(snd_pcm_t * handle,snd_pcm_uframes_t threshold)305 static void alsa_set_threshold (snd_pcm_t *handle, snd_pcm_uframes_t threshold)
306 {
307     int err;
308     snd_pcm_sw_params_t *sw_params;
309 
310     FF_snd_pcm_sw_params_alloca (&sw_params);
311 
312     err = FF(snd_pcm_sw_params_current) (handle, sw_params);
313     if (err < 0) {
314         dolog ("Could not fully initialize DAC\n");
315         alsa_logerr (err, "Failed to get current software parameters\n");
316         return;
317     }
318 
319     err = FF(snd_pcm_sw_params_set_start_threshold) (handle, sw_params, threshold);
320     if (err < 0) {
321         dolog ("Could not fully initialize DAC\n");
322         alsa_logerr (err, "Failed to set software threshold to %ld\n",
323                      threshold);
324         return;
325     }
326 
327     err = FF(snd_pcm_sw_params) (handle, sw_params);
328     if (err < 0) {
329         dolog ("Could not fully initialize DAC\n");
330         alsa_logerr (err, "Failed to set software parameters\n");
331         return;
332     }
333 }
334 
alsa_open(int in,struct alsa_params_req * req,struct alsa_params_obt * obt,snd_pcm_t ** handlep)335 static int alsa_open (int in, struct alsa_params_req *req,
336                       struct alsa_params_obt *obt, snd_pcm_t **handlep)
337 {
338     snd_pcm_t *handle;
339     snd_pcm_hw_params_t *hw_params;
340     int err;
341     int size_in_usec;
342     unsigned int freq, nchannels;
343     const char *pcm_name = in ? conf.pcm_name_in : conf.pcm_name_out;
344     snd_pcm_uframes_t obt_buffer_size;
345     const char *typ = in ? "ADC" : "DAC";
346     snd_pcm_format_t obtfmt;
347 
348     freq = req->freq;
349     nchannels = req->nchannels;
350     size_in_usec = req->size_in_usec;
351 
352     FF_snd_pcm_hw_params_alloca (&hw_params);
353 
354     err = FF(snd_pcm_open) (
355         &handle,
356         pcm_name,
357         in ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
358         SND_PCM_NONBLOCK
359         );
360     if (err < 0) {
361         alsa_logerr2 (err, typ, "Failed to open `%s':\n", pcm_name);
362         return -1;
363     }
364 
365     err = FF(snd_pcm_hw_params_any) (handle, hw_params);
366     if (err < 0) {
367         alsa_logerr2 (err, typ, "Failed to initialize hardware parameters\n");
368         goto err;
369     }
370 
371     err = FF(snd_pcm_hw_params_set_access) (
372         handle,
373         hw_params,
374         SND_PCM_ACCESS_RW_INTERLEAVED
375         );
376     if (err < 0) {
377         alsa_logerr2 (err, typ, "Failed to set access type\n");
378         goto err;
379     }
380 
381     err = FF(snd_pcm_hw_params_set_format) (handle, hw_params, req->fmt);
382     if (err < 0 && conf.verbose) {
383         alsa_logerr2 (err, typ, "Failed to set format %d\n", req->fmt);
384         goto err;
385     }
386 
387     err = FF(snd_pcm_hw_params_set_rate_near) (handle, hw_params, &freq, 0);
388     if (err < 0) {
389         alsa_logerr2 (err, typ, "Failed to set frequency %d\n", req->freq);
390         goto err;
391     }
392 
393     err = FF(snd_pcm_hw_params_set_channels_near) (
394         handle,
395         hw_params,
396         &nchannels
397         );
398     if (err < 0) {
399         alsa_logerr2 (err, typ, "Failed to set number of channels %d\n",
400                       req->nchannels);
401         goto err;
402     }
403 
404     if (nchannels != 1 && nchannels != 2) {
405         alsa_logerr2 (err, typ,
406                       "Can not handle obtained number of channels %d\n",
407                       nchannels);
408         goto err;
409     }
410 
411     if (req->buffer_size) {
412         unsigned long obt;
413 
414         if (size_in_usec) {
415             int dir = 0;
416             unsigned int btime = req->buffer_size;
417 
418             err = FF(snd_pcm_hw_params_set_buffer_time_near) (
419                 handle,
420                 hw_params,
421                 &btime,
422                 &dir
423                 );
424             obt = btime;
425         }
426         else {
427             snd_pcm_uframes_t bsize = req->buffer_size;
428 
429             err = FF(snd_pcm_hw_params_set_buffer_size_near) (
430                 handle,
431                 hw_params,
432                 &bsize
433                 );
434             obt = bsize;
435         }
436         if (err < 0) {
437             alsa_logerr2 (err, typ, "Failed to set buffer %s to %d\n",
438                           size_in_usec ? "time" : "size", req->buffer_size);
439             goto err;
440         }
441 
442         if ((req->override_mask & 2) && (obt - req->buffer_size))
443             dolog ("Requested buffer %s %u was rejected, using %lu\n",
444                    size_in_usec ? "time" : "size", req->buffer_size, obt);
445     }
446 
447     if (req->period_size) {
448         unsigned long obt;
449 
450         if (size_in_usec) {
451             int dir = 0;
452             unsigned int ptime = req->period_size;
453 
454             err = FF(snd_pcm_hw_params_set_period_time_near) (
455                 handle,
456                 hw_params,
457                 &ptime,
458                 &dir
459                 );
460             obt = ptime;
461         }
462         else {
463             int dir = 0;
464             snd_pcm_uframes_t psize = req->period_size;
465 
466             err = FF(snd_pcm_hw_params_set_period_size_near) (
467                 handle,
468                 hw_params,
469                 &psize,
470                 &dir
471                 );
472             obt = psize;
473         }
474 
475         if (err < 0) {
476             alsa_logerr2 (err, typ, "Failed to set period %s to %d\n",
477                           size_in_usec ? "time" : "size", req->period_size);
478             goto err;
479         }
480 
481         if ((req->override_mask & 1) && (obt - req->period_size))
482             dolog ("Requested period %s %u was rejected, using %lu\n",
483                    size_in_usec ? "time" : "size", req->period_size, obt);
484     }
485 
486     err = FF(snd_pcm_hw_params) (handle, hw_params);
487     if (err < 0) {
488         alsa_logerr2 (err, typ, "Failed to apply audio parameters\n");
489         goto err;
490     }
491 
492     err = FF(snd_pcm_hw_params_get_buffer_size) (hw_params, &obt_buffer_size);
493     if (err < 0) {
494         alsa_logerr2 (err, typ, "Failed to get buffer size\n");
495         goto err;
496     }
497 
498     err = FF(snd_pcm_hw_params_get_format)(hw_params, &obtfmt);
499     err = FF(snd_pcm_hw_params_get_format) (hw_params, &obtfmt);
500     if (err < 0) {
501         alsa_logerr2 (err, typ, "Failed to get format\n");
502         goto err;
503     }
504 
505     if (alsa_to_audfmt (obtfmt, &obt->fmt, &obt->endianness)) {
506         dolog ("Invalid format was returned %d\n", obtfmt);
507         goto err;
508     }
509 
510     err = FF(snd_pcm_prepare) (handle);
511     if (err < 0) {
512         alsa_logerr2 (err, typ, "Could not prepare handle %p\n", handle);
513         goto err;
514     }
515 
516     if (!in && conf.threshold) {
517         snd_pcm_uframes_t threshold;
518         int bytes_per_sec;
519 
520         bytes_per_sec = freq << (nchannels == 2);
521 
522         switch (obt->fmt) {
523         case AUD_FMT_S8:
524         case AUD_FMT_U8:
525             break;
526 
527         case AUD_FMT_S16:
528         case AUD_FMT_U16:
529             bytes_per_sec <<= 1;
530             break;
531 
532         case AUD_FMT_S32:
533         case AUD_FMT_U32:
534             bytes_per_sec <<= 2;
535             break;
536         }
537 
538         threshold = (conf.threshold * bytes_per_sec) / 1000;
539         alsa_set_threshold (handle, threshold);
540     }
541 
542     obt->nchannels = nchannels;
543     obt->freq = freq;
544     obt->samples = obt_buffer_size;
545 
546     *handlep = handle;
547 
548     if (conf.verbose &&
549         (obt->fmt != req->fmt ||
550          obt->nchannels != req->nchannels ||
551          obt->freq != req->freq)) {
552         dolog ("Audio paramters for %s\n", typ);
553         alsa_dump_info (req, obt);
554     }
555 
556 #ifdef DEBUG
557     alsa_dump_info (req, obt);
558 #endif
559     return 0;
560 
561  err:
562     alsa_anal_close (&handle);
563     return -1;
564 }
565 
alsa_recover(snd_pcm_t * handle)566 static int alsa_recover (snd_pcm_t *handle)
567 {
568     int err = FF(snd_pcm_prepare) (handle);
569     if (err < 0) {
570         alsa_logerr (err, "Failed to prepare handle %p\n", handle);
571         return -1;
572     }
573     return 0;
574 }
575 
alsa_get_avail(snd_pcm_t * handle)576 static snd_pcm_sframes_t alsa_get_avail (snd_pcm_t *handle)
577 {
578     snd_pcm_sframes_t avail;
579 
580     avail = FF(snd_pcm_avail_update) (handle);
581     if (avail < 0) {
582         if (avail == -EPIPE) {
583             if (!alsa_recover (handle)) {
584                 avail = FF(snd_pcm_avail_update) (handle);
585             }
586         }
587 
588         if (avail < 0) {
589             alsa_logerr (avail,
590                          "Could not obtain number of available frames\n");
591             return -1;
592         }
593     }
594 
595     return avail;
596 }
597 
alsa_run_out(HWVoiceOut * hw)598 static int alsa_run_out (HWVoiceOut *hw)
599 {
600     ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
601     int rpos, live, decr;
602     int samples;
603     uint8_t *dst;
604     struct st_sample *src;
605     snd_pcm_sframes_t avail;
606 
607     live = audio_pcm_hw_get_live_out (hw);
608     if (!live) {
609         return 0;
610     }
611 
612     avail = alsa_get_avail (alsa->handle);
613     if (avail < 0) {
614         dolog ("Could not get number of available playback frames\n");
615         return 0;
616     }
617 
618     decr = audio_MIN (live, avail);
619     samples = decr;
620     rpos = hw->rpos;
621     while (samples) {
622         int left_till_end_samples = hw->samples - rpos;
623         int len = audio_MIN (samples, left_till_end_samples);
624         snd_pcm_sframes_t written;
625 
626         src = hw->mix_buf + rpos;
627         dst = advance (alsa->pcm_buf, rpos << hw->info.shift);
628 
629         hw->clip (dst, src, len);
630 
631         while (len) {
632             written = FF(snd_pcm_writei) (alsa->handle, dst, len);
633 
634             if (written <= 0) {
635                 switch (written) {
636                 case 0:
637                     if (conf.verbose) {
638                         dolog ("Failed to write %d frames (wrote zero)\n", len);
639                     }
640                     goto exit;
641 
642                 case -EPIPE:
643                     if (alsa_recover (alsa->handle)) {
644                         alsa_logerr (written, "Failed to write %d frames\n",
645                                      len);
646                         goto exit;
647                     }
648                     if (conf.verbose) {
649                         dolog ("Recovering from playback xrun\n");
650                     }
651                     continue;
652 
653                 case -EAGAIN:
654                     goto exit;
655 
656                 default:
657                     alsa_logerr (written, "Failed to write %d frames to %p\n",
658                                  len, dst);
659                     goto exit;
660                 }
661             }
662 
663             rpos = (rpos + written) % hw->samples;
664             samples -= written;
665             len -= written;
666             dst = advance (dst, written << hw->info.shift);
667             src += written;
668         }
669     }
670 
671  exit:
672     hw->rpos = rpos;
673     return decr;
674 }
675 
alsa_fini_out(HWVoiceOut * hw)676 static void alsa_fini_out (HWVoiceOut *hw)
677 {
678     ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
679 
680     ldebug ("alsa_fini\n");
681     alsa_anal_close (&alsa->handle);
682 
683     if (alsa->pcm_buf) {
684         qemu_free (alsa->pcm_buf);
685         alsa->pcm_buf = NULL;
686     }
687 }
688 
alsa_init_out(HWVoiceOut * hw,struct audsettings * as)689 static int alsa_init_out (HWVoiceOut *hw, struct audsettings *as)
690 {
691     ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
692     struct alsa_params_req req;
693     struct alsa_params_obt obt;
694     snd_pcm_t *handle;
695     struct audsettings obt_as;
696     int  result = -1;
697 
698     /* shut alsa debug spew */
699     if (!D_ACTIVE)
700         stdio_disable();
701 
702     req.fmt = aud_to_alsafmt (as->fmt);
703     req.freq = as->freq;
704     req.nchannels = as->nchannels;
705     req.period_size = conf.period_size_out;
706     req.buffer_size = conf.buffer_size_out;
707     req.size_in_usec = conf.size_in_usec_out;
708     req.override_mask = !!conf.period_size_out_overridden
709         | (!!conf.buffer_size_out_overridden << 1);
710 
711     if (alsa_open (0, &req, &obt, &handle)) {
712         goto Exit;
713     }
714 
715     obt_as.freq = obt.freq;
716     obt_as.nchannels = obt.nchannels;
717     obt_as.fmt = obt.fmt;
718     obt_as.endianness = obt.endianness;
719 
720     audio_pcm_init_info (&hw->info, &obt_as);
721     hw->samples = obt.samples;
722 
723     alsa->pcm_buf = audio_calloc (AUDIO_FUNC, obt.samples, 1 << hw->info.shift);
724     if (!alsa->pcm_buf) {
725         dolog ("Could not allocate DAC buffer (%d samples, each %d bytes)\n",
726                hw->samples, 1 << hw->info.shift);
727         alsa_anal_close (&handle);
728         goto Exit;
729     }
730 
731     alsa->handle = handle;
732     result       = 0;  /* success */
733 
734 Exit:
735     if (!D_ACTIVE)
736         stdio_enable();
737 
738     return result;
739 }
740 
alsa_voice_ctl(snd_pcm_t * handle,const char * typ,int pause)741 static int alsa_voice_ctl (snd_pcm_t *handle, const char *typ, int pause)
742 {
743     int err;
744 
745     if (pause) {
746         err = FF(snd_pcm_drop) (handle);
747         if (err < 0) {
748             alsa_logerr (err, "Could not stop %s\n", typ);
749             return -1;
750         }
751     }
752     else {
753         err = FF(snd_pcm_prepare) (handle);
754         if (err < 0) {
755             alsa_logerr (err, "Could not prepare handle for %s\n", typ);
756             return -1;
757         }
758     }
759 
760     return 0;
761 }
762 
alsa_ctl_out(HWVoiceOut * hw,int cmd,...)763 static int alsa_ctl_out (HWVoiceOut *hw, int cmd, ...)
764 {
765     ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
766 
767     switch (cmd) {
768     case VOICE_ENABLE:
769         ldebug ("enabling voice\n");
770         return alsa_voice_ctl (alsa->handle, "playback", 0);
771 
772     case VOICE_DISABLE:
773         ldebug ("disabling voice\n");
774         return alsa_voice_ctl (alsa->handle, "playback", 1);
775     }
776 
777     return -1;
778 }
779 
alsa_init_in(HWVoiceIn * hw,struct audsettings * as)780 static int alsa_init_in (HWVoiceIn *hw, struct audsettings *as)
781 {
782     ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
783     struct alsa_params_req req;
784     struct alsa_params_obt obt;
785     snd_pcm_t *handle;
786     struct audsettings obt_as;
787     int result = -1;
788 
789     /* shut alsa debug spew */
790     if (!D_ACTIVE)
791         stdio_disable();
792 
793     req.fmt = aud_to_alsafmt (as->fmt);
794     req.freq = as->freq;
795     req.nchannels = as->nchannels;
796     req.period_size = conf.period_size_in;
797     req.buffer_size = conf.buffer_size_in;
798     req.size_in_usec = conf.size_in_usec_in;
799     req.override_mask = !!conf.period_size_in_overridden
800         | (!!conf.buffer_size_in_overridden << 1);
801 
802     if (alsa_open (1, &req, &obt, &handle)) {
803         goto Exit;
804     }
805 
806     obt_as.freq = obt.freq;
807     obt_as.nchannels = obt.nchannels;
808     obt_as.fmt = obt.fmt;
809     obt_as.endianness = obt.endianness;
810 
811     audio_pcm_init_info (&hw->info, &obt_as);
812     hw->samples = obt.samples;
813 
814     alsa->pcm_buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift);
815     if (!alsa->pcm_buf) {
816         dolog ("Could not allocate ADC buffer (%d samples, each %d bytes)\n",
817                hw->samples, 1 << hw->info.shift);
818         alsa_anal_close (&handle);
819         goto Exit;
820     }
821 
822     alsa->handle = handle;
823     result       = 0;  /* success */
824 
825 Exit:
826     if (!D_ACTIVE)
827         stdio_enable();
828 
829     return result;
830 }
831 
alsa_fini_in(HWVoiceIn * hw)832 static void alsa_fini_in (HWVoiceIn *hw)
833 {
834     ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
835 
836     alsa_anal_close (&alsa->handle);
837 
838     if (alsa->pcm_buf) {
839         qemu_free (alsa->pcm_buf);
840         alsa->pcm_buf = NULL;
841     }
842 }
843 
alsa_run_in(HWVoiceIn * hw)844 static int alsa_run_in (HWVoiceIn *hw)
845 {
846     ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
847     int hwshift = hw->info.shift;
848     int i;
849     int live = audio_pcm_hw_get_live_in (hw);
850     int dead = hw->samples - live;
851     int decr;
852     struct {
853         int add;
854         int len;
855     } bufs[2] = {
856         { hw->wpos, 0 },
857         { 0, 0 }
858     };
859     snd_pcm_sframes_t avail;
860     snd_pcm_uframes_t read_samples = 0;
861 
862     if (!dead) {
863         return 0;
864     }
865 
866     avail = alsa_get_avail (alsa->handle);
867     if (avail < 0) {
868         dolog ("Could not get number of captured frames\n");
869         return 0;
870     }
871 
872     if (!avail && (FF(snd_pcm_state) (alsa->handle) == SND_PCM_STATE_PREPARED)) {
873         avail = hw->samples;
874     }
875 
876     decr = audio_MIN (dead, avail);
877     if (!decr) {
878         return 0;
879     }
880 
881     if (hw->wpos + decr > hw->samples) {
882         bufs[0].len = (hw->samples - hw->wpos);
883         bufs[1].len = (decr - (hw->samples - hw->wpos));
884     }
885     else {
886         bufs[0].len = decr;
887     }
888 
889     for (i = 0; i < 2; ++i) {
890         void *src;
891         struct st_sample *dst;
892         snd_pcm_sframes_t nread;
893         snd_pcm_uframes_t len;
894 
895         len = bufs[i].len;
896 
897         src = advance (alsa->pcm_buf, bufs[i].add << hwshift);
898         dst = hw->conv_buf + bufs[i].add;
899 
900         while (len) {
901             nread = FF(snd_pcm_readi) (alsa->handle, src, len);
902 
903             if (nread <= 0) {
904                 switch (nread) {
905                 case 0:
906                     if (conf.verbose) {
907                         dolog ("Failed to read %ld frames (read zero)\n", len);
908                     }
909                     goto exit;
910 
911                 case -EPIPE:
912                     if (alsa_recover (alsa->handle)) {
913                         alsa_logerr (nread, "Failed to read %ld frames\n", len);
914                         goto exit;
915                     }
916                     if (conf.verbose) {
917                         dolog ("Recovering from capture xrun\n");
918                     }
919                     continue;
920 
921                 case -EAGAIN:
922                     goto exit;
923 
924                 default:
925                     alsa_logerr (
926                         nread,
927                         "Failed to read %ld frames from %p\n",
928                         len,
929                         src
930                         );
931                     goto exit;
932                 }
933             }
934 
935             hw->conv (dst, src, nread, &nominal_volume);
936 
937             src = advance (src, nread << hwshift);
938             dst += nread;
939 
940             read_samples += nread;
941             len -= nread;
942         }
943     }
944 
945  exit:
946     hw->wpos = (hw->wpos + read_samples) % hw->samples;
947     return read_samples;
948 }
949 
alsa_read(SWVoiceIn * sw,void * buf,int size)950 static int alsa_read (SWVoiceIn *sw, void *buf, int size)
951 {
952     return audio_pcm_sw_read (sw, buf, size);
953 }
954 
alsa_ctl_in(HWVoiceIn * hw,int cmd,...)955 static int alsa_ctl_in (HWVoiceIn *hw, int cmd, ...)
956 {
957     ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
958 
959     switch (cmd) {
960     case VOICE_ENABLE:
961         ldebug ("enabling voice\n");
962         return alsa_voice_ctl (alsa->handle, "capture", 0);
963 
964     case VOICE_DISABLE:
965         ldebug ("disabling voice\n");
966         return alsa_voice_ctl (alsa->handle, "capture", 1);
967     }
968 
969     return -1;
970 }
971 
alsa_audio_init(void)972 static void *alsa_audio_init (void)
973 {
974     void*    result = NULL;
975 
976     alsa_lib = dlopen( "libasound.so", RTLD_NOW );
977     if (alsa_lib == NULL)
978         alsa_lib = dlopen( "libasound.so.2", RTLD_NOW );
979 
980     if (alsa_lib == NULL) {
981         ldebug("could not find libasound on this system\n");
982         goto Exit;
983     }
984 
985     if (alsa_dynlink_init(alsa_lib) < 0)
986         goto Fail;
987 
988     result = &conf;
989     goto Exit;
990 
991 Fail:
992     ldebug("%s: failed to open library\n", __FUNCTION__);
993     dlclose(alsa_lib);
994 
995 Exit:
996     return result;
997 }
998 
alsa_audio_fini(void * opaque)999 static void alsa_audio_fini (void *opaque)
1000 {
1001     if (alsa_lib != NULL) {
1002         dlclose(alsa_lib);
1003         alsa_lib = NULL;
1004     }
1005     (void) opaque;
1006 }
1007 
1008 static struct audio_option alsa_options[] = {
1009     {"DAC_SIZE_IN_USEC", AUD_OPT_BOOL, &conf.size_in_usec_out,
1010      "DAC period/buffer size in microseconds (otherwise in frames)", NULL, 0},
1011     {"DAC_PERIOD_SIZE", AUD_OPT_INT, &conf.period_size_out,
1012      "DAC period size (0 to go with system default)",
1013      &conf.period_size_out_overridden, 0},
1014     {"DAC_BUFFER_SIZE", AUD_OPT_INT, &conf.buffer_size_out,
1015      "DAC buffer size (0 to go with system default)",
1016      &conf.buffer_size_out_overridden, 0},
1017 
1018     {"ADC_SIZE_IN_USEC", AUD_OPT_BOOL, &conf.size_in_usec_in,
1019      "ADC period/buffer size in microseconds (otherwise in frames)", NULL, 0},
1020     {"ADC_PERIOD_SIZE", AUD_OPT_INT, &conf.period_size_in,
1021      "ADC period size (0 to go with system default)",
1022      &conf.period_size_in_overridden, 0},
1023     {"ADC_BUFFER_SIZE", AUD_OPT_INT, &conf.buffer_size_in,
1024      "ADC buffer size (0 to go with system default)",
1025      &conf.buffer_size_in_overridden, 0},
1026 
1027     {"THRESHOLD", AUD_OPT_INT, &conf.threshold,
1028      "(undocumented)", NULL, 0},
1029 
1030     {"DAC_DEV", AUD_OPT_STR, &conf.pcm_name_out,
1031      "DAC device name (for instance dmix)", NULL, 0},
1032 
1033     {"ADC_DEV", AUD_OPT_STR, &conf.pcm_name_in,
1034      "ADC device name", NULL, 0},
1035 
1036     {"VERBOSE", AUD_OPT_BOOL, &conf.verbose,
1037      "Behave in a more verbose way", NULL, 0},
1038 
1039     {NULL, 0, NULL, NULL, NULL, 0}
1040 };
1041 
1042 static struct audio_pcm_ops alsa_pcm_ops = {
1043     alsa_init_out,
1044     alsa_fini_out,
1045     alsa_run_out,
1046     alsa_write,
1047     alsa_ctl_out,
1048 
1049     alsa_init_in,
1050     alsa_fini_in,
1051     alsa_run_in,
1052     alsa_read,
1053     alsa_ctl_in
1054 };
1055 
1056 struct audio_driver alsa_audio_driver = {
1057     INIT_FIELD (name           = ) "alsa",
1058     INIT_FIELD (descr          = ) "ALSA audio (www.alsa-project.org)",
1059     INIT_FIELD (options        = ) alsa_options,
1060     INIT_FIELD (init           = ) alsa_audio_init,
1061     INIT_FIELD (fini           = ) alsa_audio_fini,
1062     INIT_FIELD (pcm_ops        = ) &alsa_pcm_ops,
1063     INIT_FIELD (can_be_default = ) 1,
1064     INIT_FIELD (max_voices_out = ) INT_MAX,
1065     INIT_FIELD (max_voices_in  = ) INT_MAX,
1066     INIT_FIELD (voice_size_out = ) sizeof (ALSAVoiceOut),
1067     INIT_FIELD (voice_size_in  = ) sizeof (ALSAVoiceIn)
1068 };
1069