audio clean up (initial patch by malc)
[qemu] / audio / audio.c
1 /*
2  * QEMU Audio subsystem
3  * 
4  * Copyright (c) 2003-2004 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 <assert.h>
25 #include "vl.h"
26
27 #define USE_SDL_AUDIO
28 #define USE_WAV_AUDIO
29
30 #include "audio/audio_int.h"
31
32 #define dolog(...) AUD_log ("audio", __VA_ARGS__)
33 #ifdef DEBUG
34 #define ldebug(...) dolog (__VA_ARGS__)
35 #else
36 #define ldebug(...)
37 #endif
38
39 #define QC_AUDIO_DRV    "QEMU_AUDIO_DRV"
40 #define QC_VOICES       "QEMU_VOICES"
41 #define QC_FIXED_FORMAT "QEMU_FIXED_FORMAT"
42 #define QC_FIXED_FREQ   "QEMU_FIXED_FREQ"
43
44 static HWVoice *hw_voices;
45
46 AudioState audio_state = {
47     1,                          /* use fixed settings */
48     44100,                      /* fixed frequency */
49     2,                          /* fixed channels */
50     AUD_FMT_S16,                /* fixed format */
51     1,                          /* number of hw voices */
52     -1                          /* voice size */
53 };
54
55 /* http://www.df.lth.se/~john_e/gems/gem002d.html */
56 /* http://www.multi-platforms.com/Tips/PopCount.htm */
57 uint32_t popcount (uint32_t u)
58 {
59     u = ((u&0x55555555) + ((u>>1)&0x55555555));
60     u = ((u&0x33333333) + ((u>>2)&0x33333333));
61     u = ((u&0x0f0f0f0f) + ((u>>4)&0x0f0f0f0f));
62     u = ((u&0x00ff00ff) + ((u>>8)&0x00ff00ff));
63     u = ( u&0x0000ffff) + (u>>16);
64     return u;
65 }
66
67 inline uint32_t lsbindex (uint32_t u)
68 {
69     return popcount ((u&-u)-1);
70 }
71
72 int audio_get_conf_int (const char *key, int defval)
73 {
74     int val = defval;
75     char *strval;
76
77     strval = getenv (key);
78     if (strval) {
79         val = atoi (strval);
80     }
81
82     return val;
83 }
84
85 const char *audio_get_conf_str (const char *key, const char *defval)
86 {
87     const char *val = getenv (key);
88     if (!val)
89         return defval;
90     else
91         return val;
92 }
93
94 void AUD_log (const char *cap, const char *fmt, ...)
95 {
96     va_list ap;
97     fprintf (stderr, "%s: ", cap);
98     va_start (ap, fmt);
99     vfprintf (stderr, fmt, ap);
100     va_end (ap);
101 }
102
103 /*
104  * Soft Voice
105  */
106 void pcm_sw_free_resources (SWVoice *sw)
107 {
108     if (sw->buf) qemu_free (sw->buf);
109     if (sw->rate) st_rate_stop (sw->rate);
110     sw->buf = NULL;
111     sw->rate = NULL;
112 }
113
114 int pcm_sw_alloc_resources (SWVoice *sw)
115 {
116     sw->buf = qemu_mallocz (sw->hw->samples * sizeof (st_sample_t));
117     if (!sw->buf)
118         return -1;
119
120     sw->rate = st_rate_start (sw->freq, sw->hw->freq);
121     if (!sw->rate) {
122         qemu_free (sw->buf);
123         sw->buf = NULL;
124         return -1;
125     }
126     return 0;
127 }
128
129 void pcm_sw_fini (SWVoice *sw)
130 {
131     pcm_sw_free_resources (sw);
132 }
133
134 int pcm_sw_init (SWVoice *sw, HWVoice *hw, int freq,
135                  int nchannels, audfmt_e fmt)
136 {
137     int bits = 8, sign = 0;
138
139     switch (fmt) {
140     case AUD_FMT_S8:
141         sign = 1;
142     case AUD_FMT_U8:
143         break;
144
145     case AUD_FMT_S16:
146         sign = 1;
147     case AUD_FMT_U16:
148         bits = 16;
149         break;
150     }
151
152     sw->hw = hw;
153     sw->freq = freq;
154     sw->fmt = fmt;
155     sw->nchannels = nchannels;
156     sw->shift = (nchannels == 2) + (bits == 16);
157     sw->align = (1 << sw->shift) - 1;
158     sw->left = 0;
159     sw->pos = 0;
160     sw->wpos = 0;
161     sw->live = 0;
162     sw->ratio = (sw->hw->freq * ((int64_t) INT_MAX)) / sw->freq;
163     sw->bytes_per_second = sw->freq << sw->shift;
164     sw->conv = mixeng_conv[nchannels == 2][sign][bits == 16];
165
166     pcm_sw_free_resources (sw);
167     return pcm_sw_alloc_resources (sw);
168 }
169
170 /* Hard voice */
171 void pcm_hw_free_resources (HWVoice *hw)
172 {
173     if (hw->mix_buf)
174         qemu_free (hw->mix_buf);
175     hw->mix_buf = NULL;
176 }
177
178 int pcm_hw_alloc_resources (HWVoice *hw)
179 {
180     hw->mix_buf = qemu_mallocz (hw->samples * sizeof (st_sample_t));
181     if (!hw->mix_buf)
182         return -1;
183     return 0;
184 }
185
186
187 void pcm_hw_fini (HWVoice *hw)
188 {
189     if (hw->active) {
190         ldebug ("pcm_hw_fini: %d %d %d\n", hw->freq, hw->nchannels, hw->fmt);
191         pcm_hw_free_resources (hw);
192         hw->pcm_ops->fini (hw);
193         memset (hw, 0, audio_state.drv->voice_size);
194     }
195 }
196
197 void pcm_hw_gc (HWVoice *hw)
198 {
199     if (hw->nb_voices)
200         return;
201
202     pcm_hw_fini (hw);
203 }
204
205 int pcm_hw_get_live (HWVoice *hw)
206 {
207     int i, alive = 0, live = hw->samples;
208
209     for (i = 0; i < hw->nb_voices; i++) {
210         if (hw->pvoice[i]->live) {
211             live = audio_MIN (hw->pvoice[i]->live, live);
212             alive += 1;
213         }
214     }
215
216     if (alive)
217         return live;
218     else
219         return -1;
220 }
221
222 int pcm_hw_get_live2 (HWVoice *hw, int *nb_active)
223 {
224     int i, alive = 0, live = hw->samples;
225
226     *nb_active = 0;
227     for (i = 0; i < hw->nb_voices; i++) {
228         if (hw->pvoice[i]->live) {
229             if (hw->pvoice[i]->live < live) {
230                 *nb_active = hw->pvoice[i]->active != 0;
231                 live = hw->pvoice[i]->live;
232             }
233             alive += 1;
234         }
235     }
236
237     if (alive)
238         return live;
239     else
240         return -1;
241 }
242
243 void pcm_hw_dec_live (HWVoice *hw, int decr)
244 {
245     int i;
246
247     for (i = 0; i < hw->nb_voices; i++) {
248         if (hw->pvoice[i]->live) {
249             hw->pvoice[i]->live -= decr;
250         }
251     }
252 }
253
254 void pcm_hw_clear (HWVoice *hw, void *buf, int len)
255 {
256     if (!len)
257         return;
258
259     switch (hw->fmt) {
260     case AUD_FMT_S16:
261     case AUD_FMT_S8:
262         memset (buf, len << hw->shift, 0x00);
263         break;
264
265     case AUD_FMT_U8:
266         memset (buf, len << hw->shift, 0x80);
267         break;
268
269     case AUD_FMT_U16:
270         {
271             unsigned int i;
272             uint16_t *p = buf;
273             int shift = hw->nchannels - 1;
274
275             for (i = 0; i < len << shift; i++) {
276                 p[i] = INT16_MAX;
277             }
278         }
279         break;
280     }
281 }
282
283 int pcm_hw_write (SWVoice *sw, void *buf, int size)
284 {
285     int hwsamples, samples, isamp, osamp, wpos, live, dead, left, swlim, blck;
286     int ret = 0, pos = 0;
287     if (!sw)
288         return size;
289
290     hwsamples = sw->hw->samples;
291     samples = size >> sw->shift;
292
293     if (!sw->live) {
294         sw->wpos = sw->hw->rpos;
295     }
296     wpos = sw->wpos;
297     live = sw->live;
298     dead = hwsamples - live;
299     swlim = (dead * ((int64_t) INT_MAX)) / sw->ratio;
300     swlim = audio_MIN (swlim, samples);
301
302     ldebug ("size=%d live=%d dead=%d swlim=%d wpos=%d\n",
303            size, live, dead, swlim, wpos);
304     if (swlim)
305         sw->conv (sw->buf, buf, swlim);
306
307     while (swlim) {
308         dead = hwsamples - live;
309         left = hwsamples - wpos;
310         blck = audio_MIN (dead, left);
311         if (!blck) {
312             /* dolog ("swlim=%d\n", swlim); */
313             break;
314         }
315         isamp = swlim;
316         osamp = blck;
317         st_rate_flow (sw->rate, sw->buf + pos, sw->hw->mix_buf + wpos, &isamp, &osamp);
318         ret += isamp;
319         swlim -= isamp;
320         pos += isamp;
321         live += osamp;
322         wpos = (wpos + osamp) % hwsamples;
323     }
324
325     sw->wpos = wpos;
326     sw->live = live;
327     return ret << sw->shift;
328 }
329
330 int pcm_hw_init (HWVoice *hw, int freq, int nchannels, audfmt_e fmt)
331 {
332     int sign = 0, bits = 8;
333
334     pcm_hw_fini (hw);
335     ldebug ("pcm_hw_init: %d %d %d\n", freq, nchannels, fmt);
336     if (hw->pcm_ops->init (hw, freq, nchannels, fmt)) {
337         memset (hw, 0, audio_state.drv->voice_size);
338         return -1;
339     }
340
341     switch (hw->fmt) {
342     case AUD_FMT_S8:
343         sign = 1;
344     case AUD_FMT_U8:
345         break;
346
347     case AUD_FMT_S16:
348         sign = 1;
349     case AUD_FMT_U16:
350         bits = 16;
351         break;
352     }
353
354     hw->nb_voices = 0;
355     hw->active = 1;
356     hw->shift = (hw->nchannels == 2) + (bits == 16);
357     hw->bytes_per_second = hw->freq << hw->shift;
358     hw->align = (1 << hw->shift) - 1;
359     hw->samples = hw->bufsize >> hw->shift;
360     hw->clip = mixeng_clip[hw->nchannels == 2][sign][bits == 16];
361     if (pcm_hw_alloc_resources (hw)) {
362         pcm_hw_fini (hw);
363         return -1;
364     }
365     return 0;
366 }
367
368 static int dist (void *hw)
369 {
370     if (hw) {
371         return (((uint8_t *) hw - (uint8_t *) hw_voices)
372                 / audio_state.voice_size) + 1;
373     }
374     else {
375         return 0;
376     }
377 }
378
379 #define ADVANCE(hw) hw ? advance (hw, audio_state.voice_size) : hw_voices
380
381 HWVoice *pcm_hw_find_any (HWVoice *hw)
382 {
383     int i = dist (hw);
384     for (; i < audio_state.nb_hw_voices; i++) {
385         hw = ADVANCE (hw);
386         return hw;
387     }
388     return NULL;
389 }
390
391 HWVoice *pcm_hw_find_any_active (HWVoice *hw)
392 {
393     int i = dist (hw);
394     for (; i < audio_state.nb_hw_voices; i++) {
395         hw = ADVANCE (hw);
396         if (hw->active)
397             return hw;
398     }
399     return NULL;
400 }
401
402 HWVoice *pcm_hw_find_any_active_enabled (HWVoice *hw)
403 {
404     int i = dist (hw);
405     for (; i < audio_state.nb_hw_voices; i++) {
406         hw = ADVANCE (hw);
407         if (hw->active && hw->enabled)
408             return hw;
409     }
410     return NULL;
411 }
412
413 HWVoice *pcm_hw_find_any_passive (HWVoice *hw)
414 {
415     int i = dist (hw);
416     for (; i < audio_state.nb_hw_voices; i++) {
417         hw = ADVANCE (hw);
418         if (!hw->active)
419             return hw;
420     }
421     return NULL;
422 }
423
424 HWVoice *pcm_hw_find_specific (HWVoice *hw, int freq,
425                                int nchannels, audfmt_e fmt)
426 {
427     while ((hw = pcm_hw_find_any_active (hw))) {
428         if (hw->freq == freq &&
429             hw->nchannels == nchannels &&
430             hw->fmt == fmt)
431             return hw;
432     }
433     return NULL;
434 }
435
436 HWVoice *pcm_hw_add (int freq, int nchannels, audfmt_e fmt)
437 {
438     HWVoice *hw;
439
440     if (audio_state.fixed_format) {
441         freq = audio_state.fixed_freq;
442         nchannels = audio_state.fixed_channels;
443         fmt = audio_state.fixed_fmt;
444     }
445
446     hw = pcm_hw_find_specific (NULL, freq, nchannels, fmt);
447
448     if (hw)
449         return hw;
450
451     hw = pcm_hw_find_any_passive (NULL);
452     if (hw) {
453         hw->pcm_ops = audio_state.drv->pcm_ops;
454         if (!hw->pcm_ops)
455             return NULL;
456
457         if (pcm_hw_init (hw, freq, nchannels, fmt)) {
458             pcm_hw_gc (hw);
459             return NULL;
460         }
461         else
462             return hw;
463     }
464
465     return pcm_hw_find_any (NULL);
466 }
467
468 int pcm_hw_add_sw (HWVoice *hw, SWVoice *sw)
469 {
470     SWVoice **pvoice = qemu_mallocz ((hw->nb_voices + 1) * sizeof (sw));
471     if (!pvoice)
472         return -1;
473
474     memcpy (pvoice, hw->pvoice, hw->nb_voices * sizeof (sw));
475     qemu_free (hw->pvoice);
476     hw->pvoice = pvoice;
477     hw->pvoice[hw->nb_voices++] = sw;
478     return 0;
479 }
480
481 int pcm_hw_del_sw (HWVoice *hw, SWVoice *sw)
482 {
483     int i, j;
484     if (hw->nb_voices > 1) {
485         SWVoice **pvoice = qemu_mallocz ((hw->nb_voices - 1) * sizeof (sw));
486
487         if (!pvoice) {
488             dolog ("Can not maintain consistent state (not enough memory)\n");
489             return -1;
490         }
491
492         for (i = 0, j = 0; i < hw->nb_voices; i++) {
493             if (j >= hw->nb_voices - 1) {
494                 dolog ("Can not maintain consistent state "
495                        "(invariant violated)\n");
496                 return -1;
497             }
498             if (hw->pvoice[i] != sw)
499                 pvoice[j++] = hw->pvoice[i];
500         }
501         qemu_free (hw->pvoice);
502         hw->pvoice = pvoice;
503         hw->nb_voices -= 1;
504     }
505     else {
506         qemu_free (hw->pvoice);
507         hw->pvoice = NULL;
508         hw->nb_voices = 0;
509     }
510     return 0;
511 }
512
513 SWVoice *pcm_create_voice_pair (int freq, int nchannels, audfmt_e fmt)
514 {
515     SWVoice *sw;
516     HWVoice *hw;
517
518     sw = qemu_mallocz (sizeof (*sw));
519     if (!sw)
520         goto err1;
521
522     hw = pcm_hw_add (freq, nchannels, fmt);
523     if (!hw)
524         goto err2;
525
526     if (pcm_hw_add_sw (hw, sw))
527         goto err3;
528
529     if (pcm_sw_init (sw, hw, freq, nchannels, fmt))
530         goto err4;
531
532     return sw;
533
534 err4:
535     pcm_hw_del_sw (hw, sw);
536 err3:
537     pcm_hw_gc (hw);
538 err2:
539     qemu_free (sw);
540 err1:
541     return NULL;
542 }
543
544 SWVoice *AUD_open (SWVoice *sw, const char *name,
545                    int freq, int nchannels, audfmt_e fmt)
546 {
547     if (!audio_state.drv) {
548         return NULL;
549     }
550
551     if (sw && freq == sw->freq && sw->nchannels == nchannels && sw->fmt == fmt) {
552         return sw;
553     }
554
555     if (sw) {
556         ldebug ("Different format %s %d %d %d\n",
557                 name,
558                 sw->freq == freq,
559                 sw->nchannels == nchannels,
560                 sw->fmt == fmt);
561     }
562
563     if (nchannels != 1 && nchannels != 2) {
564         dolog ("Bogus channel count %d for voice %s\n", nchannels, name);
565         return NULL;
566     }
567
568     if (!audio_state.fixed_format && sw) {
569         pcm_sw_fini (sw);
570         pcm_hw_del_sw (sw->hw, sw);
571         pcm_hw_gc (sw->hw);
572         if (sw->name) {
573             qemu_free (sw->name);
574             sw->name = NULL;
575         }
576         qemu_free (sw);
577         sw = NULL;
578     }
579
580     if (sw) {
581         HWVoice *hw = sw->hw;
582         if (!hw) {
583             dolog ("Internal logic error voice %s has no hardware store\n",
584                    name);
585             return sw;
586         }
587
588         if (pcm_sw_init (sw, hw, freq, nchannels, fmt)) {
589             pcm_sw_fini (sw);
590             pcm_hw_del_sw (hw, sw);
591             pcm_hw_gc (hw);
592             if (sw->name) {
593                 qemu_free (sw->name);
594                 sw->name = NULL;
595             }
596             qemu_free (sw);
597             return NULL;
598         }
599     }
600     else {
601         sw = pcm_create_voice_pair (freq, nchannels, fmt);
602         if (!sw) {
603             dolog ("Failed to create voice %s\n", name);
604             return NULL;
605         }
606     }
607
608     if (sw->name) {
609         qemu_free (sw->name);
610         sw->name = NULL;
611     }
612     sw->name = qemu_strdup (name);
613     return sw;
614 }
615
616 void AUD_close (SWVoice *sw)
617 {
618     if (!sw)
619         return;
620
621     pcm_sw_fini (sw);
622     pcm_hw_del_sw (sw->hw, sw);
623     pcm_hw_gc (sw->hw);
624     if (sw->name) {
625         qemu_free (sw->name);
626         sw->name = NULL;
627     }
628     qemu_free (sw);
629 }
630
631 int AUD_write (SWVoice *sw, void *buf, int size)
632 {
633     int bytes;
634
635     if (!sw->hw->enabled)
636         dolog ("Writing to disabled voice %s\n", sw->name);
637     bytes = sw->hw->pcm_ops->write (sw, buf, size);
638     return bytes;
639 }
640
641 void AUD_run (void)
642 {
643     HWVoice *hw = NULL;
644
645     while ((hw = pcm_hw_find_any_active_enabled (hw))) {
646         int i;
647         if (hw->pending_disable && pcm_hw_get_live (hw) <= 0) {
648             hw->enabled = 0;
649             hw->pcm_ops->ctl (hw, VOICE_DISABLE);
650             for (i = 0; i < hw->nb_voices; i++) {
651                 hw->pvoice[i]->live = 0;
652                 /* hw->pvoice[i]->old_ticks = 0; */
653             }
654             continue;
655         }
656
657         hw->pcm_ops->run (hw);
658         assert (hw->rpos < hw->samples);
659         for (i = 0; i < hw->nb_voices; i++) {
660             SWVoice *sw = hw->pvoice[i];
661             if (!sw->active && !sw->live && sw->old_ticks) {
662                 int64_t delta = qemu_get_clock (vm_clock) - sw->old_ticks;
663                 if (delta > audio_state.ticks_threshold) {
664                     ldebug ("resetting old_ticks for %s\n", sw->name);
665                     sw->old_ticks = 0;
666                 }
667             }
668         }
669     }
670 }
671
672 int AUD_get_free (SWVoice *sw)
673 {
674     int free;
675
676     if (!sw)
677         return 4096;
678
679     free = ((sw->hw->samples - sw->live) << sw->hw->shift) * sw->ratio
680         / INT_MAX;
681
682     free &= ~sw->hw->align;
683     if (!free) return 0;
684
685     return free;
686 }
687
688 int AUD_get_buffer_size (SWVoice *sw)
689 {
690     return sw->hw->bufsize;
691 }
692
693 void AUD_adjust (SWVoice *sw, int bytes)
694 {
695     if (!sw)
696         return;
697     sw->old_ticks += (ticks_per_sec * (int64_t) bytes) / sw->bytes_per_second;
698 }
699
700 void AUD_reset (SWVoice *sw)
701 {
702     sw->active = 0;
703     sw->old_ticks = 0;
704 }
705
706 int AUD_calc_elapsed (SWVoice *sw)
707 {
708     int64_t now, delta, bytes;
709     int dead, swlim;
710
711     if (!sw)
712         return 0;
713
714     now = qemu_get_clock (vm_clock);
715     delta = now - sw->old_ticks;
716     bytes = (delta * sw->bytes_per_second) / ticks_per_sec;
717     if (delta < 0) {
718         dolog ("whoops delta(<0)=%lld\n", delta);
719         return 0;
720     }
721
722     dead = sw->hw->samples - sw->live;
723     swlim = ((dead * (int64_t) INT_MAX) / sw->ratio);
724
725     if (bytes > swlim) {
726         return swlim;
727     }
728     else {
729         return bytes;
730     }
731 }
732
733 void AUD_enable (SWVoice *sw, int on)
734 {
735     int i;
736     HWVoice *hw;
737
738     if (!sw)
739         return;
740
741     hw = sw->hw;
742     if (on) {
743         if (!sw->live)
744             sw->wpos = sw->hw->rpos;
745         if (!sw->old_ticks) {
746             sw->old_ticks = qemu_get_clock (vm_clock);
747         }
748     }
749
750     if (sw->active != on) {
751         if (on) {
752             hw->pending_disable = 0;
753             if (!hw->enabled) {
754                 hw->enabled = 1;
755                 for (i = 0; i < hw->nb_voices; i++) {
756                     ldebug ("resetting voice\n");
757                     sw = hw->pvoice[i];
758                     sw->old_ticks = qemu_get_clock (vm_clock);
759                 }
760                 hw->pcm_ops->ctl (hw, VOICE_ENABLE);
761             }
762         }
763         else {
764             if (hw->enabled && !hw->pending_disable) {
765                 int nb_active = 0;
766                 for (i = 0; i < hw->nb_voices; i++) {
767                     nb_active += hw->pvoice[i]->active != 0;
768                 }
769
770                 if (nb_active == 1) {
771                     hw->pending_disable = 1;
772                 }
773             }
774         }
775         sw->active = on;
776     }
777 }
778
779 static struct audio_output_driver *drvtab[] = {
780 #ifdef CONFIG_OSS
781     &oss_output_driver,
782 #endif
783 #ifdef USE_FMOD_AUDIO
784     &fmod_output_driver,
785 #endif
786 #ifdef CONFIG_SDL
787     &sdl_output_driver,
788 #endif
789 #ifdef USE_WAV_AUDIO
790     &wav_output_driver,
791 #endif
792 };
793
794 static int voice_init (struct audio_output_driver *drv)
795 {
796     audio_state.opaque = drv->init ();
797     if (audio_state.opaque) {
798         if (audio_state.nb_hw_voices > drv->max_voices) {
799             dolog ("`%s' does not support %d multiple hardware channels\n"
800                    "Resetting to %d\n",
801                    drv->name, audio_state.nb_hw_voices, drv->max_voices);
802             audio_state.nb_hw_voices = drv->max_voices;
803         }
804         hw_voices = qemu_mallocz (audio_state.nb_hw_voices * drv->voice_size);
805         if (hw_voices) {
806             audio_state.drv = drv;
807             return 1;
808         }
809         else {
810             dolog ("Not enough memory for %d `%s' voices (each %d bytes)\n",
811                    audio_state.nb_hw_voices, drv->name, drv->voice_size);
812             drv->fini (audio_state.opaque);
813             return 0;
814         }
815     }
816     else {
817         dolog ("Could not init `%s' audio\n", drv->name);
818         return 0;
819     }
820 }
821
822 static void audio_vm_stop_handler (void *opaque, int reason)
823 {
824     HWVoice *hw = NULL;
825
826     while ((hw = pcm_hw_find_any (hw))) {
827         if (!hw->pcm_ops)
828             continue;
829
830         hw->pcm_ops->ctl (hw, reason ? VOICE_ENABLE : VOICE_DISABLE);
831     }
832 }
833
834 static void audio_atexit (void)
835 {
836     HWVoice *hw = NULL;
837
838     while ((hw = pcm_hw_find_any (hw))) {
839         if (!hw->pcm_ops)
840             continue;
841
842         hw->pcm_ops->ctl (hw, VOICE_DISABLE);
843         hw->pcm_ops->fini (hw);
844     }
845     audio_state.drv->fini (audio_state.opaque);
846 }
847
848 static void audio_save (QEMUFile *f, void *opaque)
849 {
850 }
851
852 static int audio_load (QEMUFile *f, void *opaque, int version_id)
853 {
854     if (version_id != 1)
855         return -EINVAL;
856
857     return 0;
858 }
859
860 void AUD_init (void)
861 {
862     int i;
863     int done = 0;
864     const char *drvname;
865
866     audio_state.fixed_format =
867         !!audio_get_conf_int (QC_FIXED_FORMAT, audio_state.fixed_format);
868     audio_state.fixed_freq =
869         audio_get_conf_int (QC_FIXED_FREQ, audio_state.fixed_freq);
870     audio_state.nb_hw_voices =
871         audio_get_conf_int (QC_VOICES, audio_state.nb_hw_voices);
872
873     if (audio_state.nb_hw_voices <= 0) {
874         dolog ("Bogus number of voices %d, resetting to 1\n",
875                audio_state.nb_hw_voices);
876     }
877
878     drvname = audio_get_conf_str (QC_AUDIO_DRV, NULL);
879     if (drvname) {
880         int found = 0;
881         for (i = 0; i < sizeof (drvtab) / sizeof (drvtab[0]); i++) {
882             if (!strcmp (drvname, drvtab[i]->name)) {
883                 done = voice_init (drvtab[i]);
884                 found = 1;
885                 break;
886             }
887         }
888         if (!found) {
889             dolog ("Unknown audio driver `%s'\n", drvname);
890         }
891     }
892
893     qemu_add_vm_stop_handler (audio_vm_stop_handler, NULL);
894     atexit (audio_atexit);
895
896     if (!done) {
897         for (i = 0; !done && i < sizeof (drvtab) / sizeof (drvtab[0]); i++) {
898             if (drvtab[i]->can_be_default)
899                 done = voice_init (drvtab[i]);
900         }
901     }
902
903     audio_state.ticks_threshold = ticks_per_sec / 50;
904     audio_state.freq_threshold = 100;
905
906     register_savevm ("audio", 0, 1, audio_save, audio_load, NULL);
907     if (!done) {
908         dolog ("Can not initialize audio subsystem\n");
909         return;
910     }
911 }