audio fixes + initial audio capture support (malc)
[qemu] / audio / fmodaudio.c
1 /*
2  * QEMU FMOD audio driver
3  *
4  * Copyright (c) 2004-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 <fmod.h>
25 #include <fmod_errors.h>
26 #include "vl.h"
27
28 #define AUDIO_CAP "fmod"
29 #include "audio_int.h"
30
31 typedef struct FMODVoiceOut {
32     HWVoiceOut hw;
33     unsigned int old_pos;
34     FSOUND_SAMPLE *fmod_sample;
35     int channel;
36 } FMODVoiceOut;
37
38 typedef struct FMODVoiceIn {
39     HWVoiceIn hw;
40     FSOUND_SAMPLE *fmod_sample;
41 } FMODVoiceIn;
42
43 static struct {
44     const char *drvname;
45     int nb_samples;
46     int freq;
47     int nb_channels;
48     int bufsize;
49     int threshold;
50     int broken_adc;
51 } conf = {
52     NULL,
53     2048 * 2,
54     44100,
55     2,
56     0,
57     0,
58     0
59 };
60
61 static void GCC_FMT_ATTR (1, 2) fmod_logerr (const char *fmt, ...)
62 {
63     va_list ap;
64
65     va_start (ap, fmt);
66     AUD_vlog (AUDIO_CAP, fmt, ap);
67     va_end (ap);
68
69     AUD_log (AUDIO_CAP, "Reason: %s\n",
70              FMOD_ErrorString (FSOUND_GetError ()));
71 }
72
73 static void GCC_FMT_ATTR (2, 3) fmod_logerr2 (
74     const char *typ,
75     const char *fmt,
76     ...
77     )
78 {
79     va_list ap;
80
81     AUD_log (AUDIO_CAP, "Could not initialize %s\n", typ);
82
83     va_start (ap, fmt);
84     AUD_vlog (AUDIO_CAP, fmt, ap);
85     va_end (ap);
86
87     AUD_log (AUDIO_CAP, "Reason: %s\n",
88              FMOD_ErrorString (FSOUND_GetError ()));
89 }
90
91 static int fmod_write (SWVoiceOut *sw, void *buf, int len)
92 {
93     return audio_pcm_sw_write (sw, buf, len);
94 }
95
96 static void fmod_clear_sample (FMODVoiceOut *fmd)
97 {
98     HWVoiceOut *hw = &fmd->hw;
99     int status;
100     void *p1 = 0, *p2 = 0;
101     unsigned int len1 = 0, len2 = 0;
102
103     status = FSOUND_Sample_Lock (
104         fmd->fmod_sample,
105         0,
106         hw->samples << hw->info.shift,
107         &p1,
108         &p2,
109         &len1,
110         &len2
111         );
112
113     if (!status) {
114         fmod_logerr ("Failed to lock sample\n");
115         return;
116     }
117
118     if ((len1 & hw->info.align) || (len2 & hw->info.align)) {
119         dolog ("Lock returned misaligned length %d, %d, alignment %d\n",
120                len1, len2, hw->info.align + 1);
121         goto fail;
122     }
123
124     if ((len1 + len2) - (hw->samples << hw->info.shift)) {
125         dolog ("Lock returned incomplete length %d, %d\n",
126                len1 + len2, hw->samples << hw->info.shift);
127         goto fail;
128     }
129
130     audio_pcm_info_clear_buf (&hw->info, p1, hw->samples);
131
132  fail:
133     status = FSOUND_Sample_Unlock (fmd->fmod_sample, p1, p2, len1, len2);
134     if (!status) {
135         fmod_logerr ("Failed to unlock sample\n");
136     }
137 }
138
139 static void fmod_write_sample (HWVoiceOut *hw, uint8_t *dst, int dst_len)
140 {
141     int src_len1 = dst_len;
142     int src_len2 = 0;
143     int pos = hw->rpos + dst_len;
144     st_sample_t *src1 = hw->mix_buf + hw->rpos;
145     st_sample_t *src2 = NULL;
146
147     if (pos > hw->samples) {
148         src_len1 = hw->samples - hw->rpos;
149         src2 = hw->mix_buf;
150         src_len2 = dst_len - src_len1;
151         pos = src_len2;
152     }
153
154     if (src_len1) {
155         hw->clip (dst, src1, src_len1);
156     }
157
158     if (src_len2) {
159         dst = advance (dst, src_len1 << hw->info.shift);
160         hw->clip (dst, src2, src_len2);
161     }
162
163     hw->rpos = pos % hw->samples;
164 }
165
166 static int fmod_unlock_sample (FSOUND_SAMPLE *sample, void *p1, void *p2,
167                                unsigned int blen1, unsigned int blen2)
168 {
169     int status = FSOUND_Sample_Unlock (sample, p1, p2, blen1, blen2);
170     if (!status) {
171         fmod_logerr ("Failed to unlock sample\n");
172         return -1;
173     }
174     return 0;
175 }
176
177 static int fmod_lock_sample (
178     FSOUND_SAMPLE *sample,
179     struct audio_pcm_info *info,
180     int pos,
181     int len,
182     void **p1,
183     void **p2,
184     unsigned int *blen1,
185     unsigned int *blen2
186     )
187 {
188     int status;
189
190     status = FSOUND_Sample_Lock (
191         sample,
192         pos << info->shift,
193         len << info->shift,
194         p1,
195         p2,
196         blen1,
197         blen2
198         );
199
200     if (!status) {
201         fmod_logerr ("Failed to lock sample\n");
202         return -1;
203     }
204
205     if ((*blen1 & info->align) || (*blen2 & info->align)) {
206         dolog ("Lock returned misaligned length %d, %d, alignment %d\n",
207                *blen1, *blen2, info->align + 1);
208
209         fmod_unlock_sample (sample, *p1, *p2, *blen1, *blen2);
210
211         *p1 = NULL - 1;
212         *p2 = NULL - 1;
213         *blen1 = ~0U;
214         *blen2 = ~0U;
215         return -1;
216     }
217
218     if (!*p1 && *blen1) {
219         dolog ("warning: !p1 && blen1=%d\n", *blen1);
220         *blen1 = 0;
221     }
222
223     if (!p2 && *blen2) {
224         dolog ("warning: !p2 && blen2=%d\n", *blen2);
225         *blen2 = 0;
226     }
227
228     return 0;
229 }
230
231 static int fmod_run_out (HWVoiceOut *hw)
232 {
233     FMODVoiceOut *fmd = (FMODVoiceOut *) hw;
234     int live, decr;
235     void *p1 = 0, *p2 = 0;
236     unsigned int blen1 = 0, blen2 = 0;
237     unsigned int len1 = 0, len2 = 0;
238     int nb_live;
239
240     live = audio_pcm_hw_get_live_out2 (hw, &nb_live);
241     if (!live) {
242         return 0;
243     }
244
245     if (!hw->pending_disable
246         && nb_live
247         && (conf.threshold && live <= conf.threshold)) {
248         ldebug ("live=%d nb_live=%d\n", live, nb_live);
249         return 0;
250     }
251
252     decr = live;
253
254     if (fmd->channel >= 0) {
255         int len = decr;
256         int old_pos = fmd->old_pos;
257         int ppos = FSOUND_GetCurrentPosition (fmd->channel);
258
259         if (ppos == old_pos || !ppos) {
260             return 0;
261         }
262
263         if ((old_pos < ppos) && ((old_pos + len) > ppos)) {
264             len = ppos - old_pos;
265         }
266         else {
267             if ((old_pos > ppos) && ((old_pos + len) > (ppos + hw->samples))) {
268                 len = hw->samples - old_pos + ppos;
269             }
270         }
271         decr = len;
272
273         if (audio_bug (AUDIO_FUNC, decr < 0)) {
274             dolog ("decr=%d live=%d ppos=%d old_pos=%d len=%d\n",
275                    decr, live, ppos, old_pos, len);
276             return 0;
277         }
278     }
279
280
281     if (!decr) {
282         return 0;
283     }
284
285     if (fmod_lock_sample (fmd->fmod_sample, &fmd->hw.info,
286                           fmd->old_pos, decr,
287                           &p1, &p2,
288                           &blen1, &blen2)) {
289         return 0;
290     }
291
292     len1 = blen1 >> hw->info.shift;
293     len2 = blen2 >> hw->info.shift;
294     ldebug ("%p %p %d %d %d %d\n", p1, p2, len1, len2, blen1, blen2);
295     decr = len1 + len2;
296
297     if (p1 && len1) {
298         fmod_write_sample (hw, p1, len1);
299     }
300
301     if (p2 && len2) {
302         fmod_write_sample (hw, p2, len2);
303     }
304
305     fmod_unlock_sample (fmd->fmod_sample, p1, p2, blen1, blen2);
306
307     fmd->old_pos = (fmd->old_pos + decr) % hw->samples;
308     return decr;
309 }
310
311 static int aud_to_fmodfmt (audfmt_e fmt, int stereo)
312 {
313     int mode = FSOUND_LOOP_NORMAL;
314
315     switch (fmt) {
316     case AUD_FMT_S8:
317         mode |= FSOUND_SIGNED | FSOUND_8BITS;
318         break;
319
320     case AUD_FMT_U8:
321         mode |= FSOUND_UNSIGNED | FSOUND_8BITS;
322         break;
323
324     case AUD_FMT_S16:
325         mode |= FSOUND_SIGNED | FSOUND_16BITS;
326         break;
327
328     case AUD_FMT_U16:
329         mode |= FSOUND_UNSIGNED | FSOUND_16BITS;
330         break;
331
332     default:
333         dolog ("Internal logic error: Bad audio format %d\n", fmt);
334 #ifdef DEBUG_FMOD
335         abort ();
336 #endif
337         mode |= FSOUND_8BITS;
338     }
339     mode |= stereo ? FSOUND_STEREO : FSOUND_MONO;
340     return mode;
341 }
342
343 static void fmod_fini_out (HWVoiceOut *hw)
344 {
345     FMODVoiceOut *fmd = (FMODVoiceOut *) hw;
346
347     if (fmd->fmod_sample) {
348         FSOUND_Sample_Free (fmd->fmod_sample);
349         fmd->fmod_sample = 0;
350
351         if (fmd->channel >= 0) {
352             FSOUND_StopSound (fmd->channel);
353         }
354     }
355 }
356
357 static int fmod_init_out (HWVoiceOut *hw, audsettings_t *as)
358 {
359     int bits16, mode, channel;
360     FMODVoiceOut *fmd = (FMODVoiceOut *) hw;
361
362     mode = aud_to_fmodfmt (as->fmt, as->nchannels == 2 ? 1 : 0);
363     fmd->fmod_sample = FSOUND_Sample_Alloc (
364         FSOUND_FREE,            /* index */
365         conf.nb_samples,        /* length */
366         mode,                   /* mode */
367         as->freq,               /* freq */
368         255,                    /* volume */
369         128,                    /* pan */
370         255                     /* priority */
371         );
372
373     if (!fmd->fmod_sample) {
374         fmod_logerr2 ("DAC", "Failed to allocate FMOD sample\n");
375         return -1;
376     }
377
378     channel = FSOUND_PlaySoundEx (FSOUND_FREE, fmd->fmod_sample, 0, 1);
379     if (channel < 0) {
380         fmod_logerr2 ("DAC", "Failed to start playing sound\n");
381         FSOUND_Sample_Free (fmd->fmod_sample);
382         return -1;
383     }
384     fmd->channel = channel;
385
386     /* FMOD always operates on little endian frames? */
387     audio_pcm_init_info (&hw->info, as, audio_need_to_swap_endian (0));
388     bits16 = (mode & FSOUND_16BITS) != 0;
389     hw->samples = conf.nb_samples;
390     return 0;
391 }
392
393 static int fmod_ctl_out (HWVoiceOut *hw, int cmd, ...)
394 {
395     int status;
396     FMODVoiceOut *fmd = (FMODVoiceOut *) hw;
397
398     switch (cmd) {
399     case VOICE_ENABLE:
400         fmod_clear_sample (fmd);
401         status = FSOUND_SetPaused (fmd->channel, 0);
402         if (!status) {
403             fmod_logerr ("Failed to resume channel %d\n", fmd->channel);
404         }
405         break;
406
407     case VOICE_DISABLE:
408         status = FSOUND_SetPaused (fmd->channel, 1);
409         if (!status) {
410             fmod_logerr ("Failed to pause channel %d\n", fmd->channel);
411         }
412         break;
413     }
414     return 0;
415 }
416
417 static int fmod_init_in (HWVoiceIn *hw, audsettings_t *as)
418 {
419     int bits16, mode;
420     FMODVoiceIn *fmd = (FMODVoiceIn *) hw;
421
422     if (conf.broken_adc) {
423         return -1;
424     }
425
426     mode = aud_to_fmodfmt (as->fmt, as->nchannels == 2 ? 1 : 0);
427     fmd->fmod_sample = FSOUND_Sample_Alloc (
428         FSOUND_FREE,            /* index */
429         conf.nb_samples,        /* length */
430         mode,                   /* mode */
431         as->freq,               /* freq */
432         255,                    /* volume */
433         128,                    /* pan */
434         255                     /* priority */
435         );
436
437     if (!fmd->fmod_sample) {
438         fmod_logerr2 ("ADC", "Failed to allocate FMOD sample\n");
439         return -1;
440     }
441
442     /* FMOD always operates on little endian frames? */
443     audio_pcm_init_info (&hw->info, as, audio_need_to_swap_endian (0));
444     bits16 = (mode & FSOUND_16BITS) != 0;
445     hw->samples = conf.nb_samples;
446     return 0;
447 }
448
449 static void fmod_fini_in (HWVoiceIn *hw)
450 {
451     FMODVoiceIn *fmd = (FMODVoiceIn *) hw;
452
453     if (fmd->fmod_sample) {
454         FSOUND_Record_Stop ();
455         FSOUND_Sample_Free (fmd->fmod_sample);
456         fmd->fmod_sample = 0;
457     }
458 }
459
460 static int fmod_run_in (HWVoiceIn *hw)
461 {
462     FMODVoiceIn *fmd = (FMODVoiceIn *) hw;
463     int hwshift = hw->info.shift;
464     int live, dead, new_pos, len;
465     unsigned int blen1 = 0, blen2 = 0;
466     unsigned int len1, len2;
467     unsigned int decr;
468     void *p1, *p2;
469
470     live = audio_pcm_hw_get_live_in (hw);
471     dead = hw->samples - live;
472     if (!dead) {
473         return 0;
474     }
475
476     new_pos = FSOUND_Record_GetPosition ();
477     if (new_pos < 0) {
478         fmod_logerr ("Could not get recording position\n");
479         return 0;
480     }
481
482     len = audio_ring_dist (new_pos,  hw->wpos, hw->samples);
483     if (!len) {
484         return 0;
485     }
486     len = audio_MIN (len, dead);
487
488     if (fmod_lock_sample (fmd->fmod_sample, &fmd->hw.info,
489                           hw->wpos, len,
490                           &p1, &p2,
491                           &blen1, &blen2)) {
492         return 0;
493     }
494
495     len1 = blen1 >> hwshift;
496     len2 = blen2 >> hwshift;
497     decr = len1 + len2;
498
499     if (p1 && blen1) {
500         hw->conv (hw->conv_buf + hw->wpos, p1, len1, &nominal_volume);
501     }
502     if (p2 && len2) {
503         hw->conv (hw->conv_buf, p2, len2, &nominal_volume);
504     }
505
506     fmod_unlock_sample (fmd->fmod_sample, p1, p2, blen1, blen2);
507     hw->wpos = (hw->wpos + decr) % hw->samples;
508     return decr;
509 }
510
511 static struct {
512     const char *name;
513     int type;
514 } drvtab[] = {
515     {"none", FSOUND_OUTPUT_NOSOUND},
516 #ifdef _WIN32
517     {"winmm", FSOUND_OUTPUT_WINMM},
518     {"dsound", FSOUND_OUTPUT_DSOUND},
519     {"a3d", FSOUND_OUTPUT_A3D},
520     {"asio", FSOUND_OUTPUT_ASIO},
521 #endif
522 #ifdef __linux__
523     {"oss", FSOUND_OUTPUT_OSS},
524     {"alsa", FSOUND_OUTPUT_ALSA},
525     {"esd", FSOUND_OUTPUT_ESD},
526 #endif
527 #ifdef __APPLE__
528     {"mac", FSOUND_OUTPUT_MAC},
529 #endif
530 #if 0
531     {"xbox", FSOUND_OUTPUT_XBOX},
532     {"ps2", FSOUND_OUTPUT_PS2},
533     {"gcube", FSOUND_OUTPUT_GC},
534 #endif
535     {"none-realtime", FSOUND_OUTPUT_NOSOUND_NONREALTIME}
536 };
537
538 static void *fmod_audio_init (void)
539 {
540     size_t i;
541     double ver;
542     int status;
543     int output_type = -1;
544     const char *drv = conf.drvname;
545
546     ver = FSOUND_GetVersion ();
547     if (ver < FMOD_VERSION) {
548         dolog ("Wrong FMOD version %f, need at least %f\n", ver, FMOD_VERSION);
549         return NULL;
550     }
551
552 #ifdef __linux__
553     if (ver < 3.75) {
554         dolog ("FMOD before 3.75 has bug preventing ADC from working\n"
555                "ADC will be disabled.\n");
556         conf.broken_adc = 1;
557     }
558 #endif
559
560     if (drv) {
561         int found = 0;
562         for (i = 0; i < sizeof (drvtab) / sizeof (drvtab[0]); i++) {
563             if (!strcmp (drv, drvtab[i].name)) {
564                 output_type = drvtab[i].type;
565                 found = 1;
566                 break;
567             }
568         }
569         if (!found) {
570             dolog ("Unknown FMOD driver `%s'\n", drv);
571             dolog ("Valid drivers:\n");
572             for (i = 0; i < sizeof (drvtab) / sizeof (drvtab[0]); i++) {
573                 dolog ("  %s\n", drvtab[i].name);
574             }
575         }
576     }
577
578     if (output_type != -1) {
579         status = FSOUND_SetOutput (output_type);
580         if (!status) {
581             fmod_logerr ("FSOUND_SetOutput(%d) failed\n", output_type);
582             return NULL;
583         }
584     }
585
586     if (conf.bufsize) {
587         status = FSOUND_SetBufferSize (conf.bufsize);
588         if (!status) {
589             fmod_logerr ("FSOUND_SetBufferSize (%d) failed\n", conf.bufsize);
590         }
591     }
592
593     status = FSOUND_Init (conf.freq, conf.nb_channels, 0);
594     if (!status) {
595         fmod_logerr ("FSOUND_Init failed\n");
596         return NULL;
597     }
598
599     return &conf;
600 }
601
602 static int fmod_read (SWVoiceIn *sw, void *buf, int size)
603 {
604     return audio_pcm_sw_read (sw, buf, size);
605 }
606
607 static int fmod_ctl_in (HWVoiceIn *hw, int cmd, ...)
608 {
609     int status;
610     FMODVoiceIn *fmd = (FMODVoiceIn *) hw;
611
612     switch (cmd) {
613     case VOICE_ENABLE:
614         status = FSOUND_Record_StartSample (fmd->fmod_sample, 1);
615         if (!status) {
616             fmod_logerr ("Failed to start recording\n");
617         }
618         break;
619
620     case VOICE_DISABLE:
621         status = FSOUND_Record_Stop ();
622         if (!status) {
623             fmod_logerr ("Failed to stop recording\n");
624         }
625         break;
626     }
627     return 0;
628 }
629
630 static void fmod_audio_fini (void *opaque)
631 {
632     (void) opaque;
633     FSOUND_Close ();
634 }
635
636 static struct audio_option fmod_options[] = {
637     {"DRV", AUD_OPT_STR, &conf.drvname,
638      "FMOD driver", NULL, 0},
639     {"FREQ", AUD_OPT_INT, &conf.freq,
640      "Default frequency", NULL, 0},
641     {"SAMPLES", AUD_OPT_INT, &conf.nb_samples,
642      "Buffer size in samples", NULL, 0},
643     {"CHANNELS", AUD_OPT_INT, &conf.nb_channels,
644      "Number of default channels (1 - mono, 2 - stereo)", NULL, 0},
645     {"BUFSIZE", AUD_OPT_INT, &conf.bufsize,
646      "(undocumented)", NULL, 0},
647 #if 0
648     {"THRESHOLD", AUD_OPT_INT, &conf.threshold,
649      "(undocumented)"},
650 #endif
651
652     {NULL, 0, NULL, NULL, NULL, 0}
653 };
654
655 static struct audio_pcm_ops fmod_pcm_ops = {
656     fmod_init_out,
657     fmod_fini_out,
658     fmod_run_out,
659     fmod_write,
660     fmod_ctl_out,
661
662     fmod_init_in,
663     fmod_fini_in,
664     fmod_run_in,
665     fmod_read,
666     fmod_ctl_in
667 };
668
669 struct audio_driver fmod_audio_driver = {
670     INIT_FIELD (name           = ) "fmod",
671     INIT_FIELD (descr          = ) "FMOD 3.xx http://www.fmod.org",
672     INIT_FIELD (options        = ) fmod_options,
673     INIT_FIELD (init           = ) fmod_audio_init,
674     INIT_FIELD (fini           = ) fmod_audio_fini,
675     INIT_FIELD (pcm_ops        = ) &fmod_pcm_ops,
676     INIT_FIELD (can_be_default = ) 1,
677     INIT_FIELD (max_voices_out = ) INT_MAX,
678     INIT_FIELD (max_voices_in  = ) INT_MAX,
679     INIT_FIELD (voice_size_out = ) sizeof (FMODVoiceOut),
680     INIT_FIELD (voice_size_in  = ) sizeof (FMODVoiceIn)
681 };