Statistics
| Branch: | Revision:

root / audio / audio.c @ cf2c1839

History | View | Annotate | Download (50.8 kB)

1
/*
2
 * QEMU Audio subsystem
3
 *
4
 * Copyright (c) 2003-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 "hw/hw.h"
25
#include "audio.h"
26
#include "monitor.h"
27
#include "qemu-timer.h"
28
#include "sysemu.h"
29

    
30
#define AUDIO_CAP "audio"
31
#include "audio_int.h"
32

    
33
/* #define DEBUG_PLIVE */
34
/* #define DEBUG_LIVE */
35
/* #define DEBUG_OUT */
36
/* #define DEBUG_CAPTURE */
37
/* #define DEBUG_POLL */
38

    
39
#define SW_NAME(sw) (sw)->name ? (sw)->name : "unknown"
40

    
41

    
42
/* Order of CONFIG_AUDIO_DRIVERS is import.
43
   The 1st one is the one used by default, that is the reason
44
    that we generate the list.
45
*/
46
static struct audio_driver *drvtab[] = {
47
#ifdef CONFIG_SPICE
48
    &spice_audio_driver,
49
#endif
50
    CONFIG_AUDIO_DRIVERS
51
    &no_audio_driver,
52
    &wav_audio_driver
53
};
54

    
55
struct fixed_settings {
56
    int enabled;
57
    int nb_voices;
58
    int greedy;
59
    struct audsettings settings;
60
};
61

    
62
static struct {
63
    struct fixed_settings fixed_out;
64
    struct fixed_settings fixed_in;
65
    union {
66
        int hertz;
67
        int64_t ticks;
68
    } period;
69
    int plive;
70
    int log_to_monitor;
71
    int try_poll_in;
72
    int try_poll_out;
73
} conf = {
74
    .fixed_out = { /* DAC fixed settings */
75
        .enabled = 1,
76
        .nb_voices = 1,
77
        .greedy = 1,
78
        .settings = {
79
            .freq = 44100,
80
            .nchannels = 2,
81
            .fmt = AUD_FMT_S16,
82
            .endianness =  AUDIO_HOST_ENDIANNESS,
83
        }
84
    },
85

    
86
    .fixed_in = { /* ADC fixed settings */
87
        .enabled = 1,
88
        .nb_voices = 1,
89
        .greedy = 1,
90
        .settings = {
91
            .freq = 44100,
92
            .nchannels = 2,
93
            .fmt = AUD_FMT_S16,
94
            .endianness = AUDIO_HOST_ENDIANNESS,
95
        }
96
    },
97

    
98
    .period = { .hertz = 250 },
99
    .plive = 0,
100
    .log_to_monitor = 0,
101
    .try_poll_in = 1,
102
    .try_poll_out = 1,
103
};
104

    
105
static AudioState glob_audio_state;
106

    
107
struct mixeng_volume nominal_volume = {
108
    .mute = 0,
109
#ifdef FLOAT_MIXENG
110
    .r = 1.0,
111
    .l = 1.0,
112
#else
113
    .r = 1ULL << 32,
114
    .l = 1ULL << 32,
115
#endif
116
};
117

    
118
#ifdef AUDIO_IS_FLAWLESS_AND_NO_CHECKS_ARE_REQURIED
119
#error No its not
120
#else
121
static void audio_print_options (const char *prefix,
122
                                 struct audio_option *opt);
123

    
124
int audio_bug (const char *funcname, int cond)
125
{
126
    if (cond) {
127
        static int shown;
128

    
129
        AUD_log (NULL, "A bug was just triggered in %s\n", funcname);
130
        if (!shown) {
131
            struct audio_driver *d;
132

    
133
            shown = 1;
134
            AUD_log (NULL, "Save all your work and restart without audio\n");
135
            AUD_log (NULL, "Please send bug report to av1474@comtv.ru\n");
136
            AUD_log (NULL, "I am sorry\n");
137
            d = glob_audio_state.drv;
138
            if (d) {
139
                audio_print_options (d->name, d->options);
140
            }
141
        }
142
        AUD_log (NULL, "Context:\n");
143

    
144
#if defined AUDIO_BREAKPOINT_ON_BUG
145
#  if defined HOST_I386
146
#    if defined __GNUC__
147
        __asm__ ("int3");
148
#    elif defined _MSC_VER
149
        _asm _emit 0xcc;
150
#    else
151
        abort ();
152
#    endif
153
#  else
154
        abort ();
155
#  endif
156
#endif
157
    }
158

    
159
    return cond;
160
}
161
#endif
162

    
163
static inline int audio_bits_to_index (int bits)
164
{
165
    switch (bits) {
166
    case 8:
167
        return 0;
168

    
169
    case 16:
170
        return 1;
171

    
172
    case 32:
173
        return 2;
174

    
175
    default:
176
        audio_bug ("bits_to_index", 1);
177
        AUD_log (NULL, "invalid bits %d\n", bits);
178
        return 0;
179
    }
180
}
181

    
182
void *audio_calloc (const char *funcname, int nmemb, size_t size)
183
{
184
    int cond;
185
    size_t len;
186

    
187
    len = nmemb * size;
188
    cond = !nmemb || !size;
189
    cond |= nmemb < 0;
190
    cond |= len < size;
191

    
192
    if (audio_bug ("audio_calloc", cond)) {
193
        AUD_log (NULL, "%s passed invalid arguments to audio_calloc\n",
194
                 funcname);
195
        AUD_log (NULL, "nmemb=%d size=%zu (len=%zu)\n", nmemb, size, len);
196
        return NULL;
197
    }
198

    
199
    return qemu_mallocz (len);
200
}
201

    
202
static char *audio_alloc_prefix (const char *s)
203
{
204
    const char qemu_prefix[] = "QEMU_";
205
    size_t len, i;
206
    char *r, *u;
207

    
208
    if (!s) {
209
        return NULL;
210
    }
211

    
212
    len = strlen (s);
213
    r = qemu_malloc (len + sizeof (qemu_prefix));
214

    
215
    u = r + sizeof (qemu_prefix) - 1;
216

    
217
    pstrcpy (r, len + sizeof (qemu_prefix), qemu_prefix);
218
    pstrcat (r, len + sizeof (qemu_prefix), s);
219

    
220
    for (i = 0; i < len; ++i) {
221
        u[i] = qemu_toupper(u[i]);
222
    }
223

    
224
    return r;
225
}
226

    
227
static const char *audio_audfmt_to_string (audfmt_e fmt)
228
{
229
    switch (fmt) {
230
    case AUD_FMT_U8:
231
        return "U8";
232

    
233
    case AUD_FMT_U16:
234
        return "U16";
235

    
236
    case AUD_FMT_S8:
237
        return "S8";
238

    
239
    case AUD_FMT_S16:
240
        return "S16";
241

    
242
    case AUD_FMT_U32:
243
        return "U32";
244

    
245
    case AUD_FMT_S32:
246
        return "S32";
247
    }
248

    
249
    dolog ("Bogus audfmt %d returning S16\n", fmt);
250
    return "S16";
251
}
252

    
253
static audfmt_e audio_string_to_audfmt (const char *s, audfmt_e defval,
254
                                        int *defaultp)
255
{
256
    if (!strcasecmp (s, "u8")) {
257
        *defaultp = 0;
258
        return AUD_FMT_U8;
259
    }
260
    else if (!strcasecmp (s, "u16")) {
261
        *defaultp = 0;
262
        return AUD_FMT_U16;
263
    }
264
    else if (!strcasecmp (s, "u32")) {
265
        *defaultp = 0;
266
        return AUD_FMT_U32;
267
    }
268
    else if (!strcasecmp (s, "s8")) {
269
        *defaultp = 0;
270
        return AUD_FMT_S8;
271
    }
272
    else if (!strcasecmp (s, "s16")) {
273
        *defaultp = 0;
274
        return AUD_FMT_S16;
275
    }
276
    else if (!strcasecmp (s, "s32")) {
277
        *defaultp = 0;
278
        return AUD_FMT_S32;
279
    }
280
    else {
281
        dolog ("Bogus audio format `%s' using %s\n",
282
               s, audio_audfmt_to_string (defval));
283
        *defaultp = 1;
284
        return defval;
285
    }
286
}
287

    
288
static audfmt_e audio_get_conf_fmt (const char *envname,
289
                                    audfmt_e defval,
290
                                    int *defaultp)
291
{
292
    const char *var = getenv (envname);
293
    if (!var) {
294
        *defaultp = 1;
295
        return defval;
296
    }
297
    return audio_string_to_audfmt (var, defval, defaultp);
298
}
299

    
300
static int audio_get_conf_int (const char *key, int defval, int *defaultp)
301
{
302
    int val;
303
    char *strval;
304

    
305
    strval = getenv (key);
306
    if (strval) {
307
        *defaultp = 0;
308
        val = atoi (strval);
309
        return val;
310
    }
311
    else {
312
        *defaultp = 1;
313
        return defval;
314
    }
315
}
316

    
317
static const char *audio_get_conf_str (const char *key,
318
                                       const char *defval,
319
                                       int *defaultp)
320
{
321
    const char *val = getenv (key);
322
    if (!val) {
323
        *defaultp = 1;
324
        return defval;
325
    }
326
    else {
327
        *defaultp = 0;
328
        return val;
329
    }
330
}
331

    
332
void AUD_vlog (const char *cap, const char *fmt, va_list ap)
333
{
334
    if (conf.log_to_monitor) {
335
        if (cap) {
336
            monitor_printf(default_mon, "%s: ", cap);
337
        }
338

    
339
        monitor_vprintf(default_mon, fmt, ap);
340
    }
341
    else {
342
        if (cap) {
343
            fprintf (stderr, "%s: ", cap);
344
        }
345

    
346
        vfprintf (stderr, fmt, ap);
347
    }
348
}
349

    
350
void AUD_log (const char *cap, const char *fmt, ...)
351
{
352
    va_list ap;
353

    
354
    va_start (ap, fmt);
355
    AUD_vlog (cap, fmt, ap);
356
    va_end (ap);
357
}
358

    
359
static void audio_print_options (const char *prefix,
360
                                 struct audio_option *opt)
361
{
362
    char *uprefix;
363

    
364
    if (!prefix) {
365
        dolog ("No prefix specified\n");
366
        return;
367
    }
368

    
369
    if (!opt) {
370
        dolog ("No options\n");
371
        return;
372
    }
373

    
374
    uprefix = audio_alloc_prefix (prefix);
375

    
376
    for (; opt->name; opt++) {
377
        const char *state = "default";
378
        printf ("  %s_%s: ", uprefix, opt->name);
379

    
380
        if (opt->overriddenp && *opt->overriddenp) {
381
            state = "current";
382
        }
383

    
384
        switch (opt->tag) {
385
        case AUD_OPT_BOOL:
386
            {
387
                int *intp = opt->valp;
388
                printf ("boolean, %s = %d\n", state, *intp ? 1 : 0);
389
            }
390
            break;
391

    
392
        case AUD_OPT_INT:
393
            {
394
                int *intp = opt->valp;
395
                printf ("integer, %s = %d\n", state, *intp);
396
            }
397
            break;
398

    
399
        case AUD_OPT_FMT:
400
            {
401
                audfmt_e *fmtp = opt->valp;
402
                printf (
403
                    "format, %s = %s, (one of: U8 S8 U16 S16 U32 S32)\n",
404
                    state,
405
                    audio_audfmt_to_string (*fmtp)
406
                    );
407
            }
408
            break;
409

    
410
        case AUD_OPT_STR:
411
            {
412
                const char **strp = opt->valp;
413
                printf ("string, %s = %s\n",
414
                        state,
415
                        *strp ? *strp : "(not set)");
416
            }
417
            break;
418

    
419
        default:
420
            printf ("???\n");
421
            dolog ("Bad value tag for option %s_%s %d\n",
422
                   uprefix, opt->name, opt->tag);
423
            break;
424
        }
425
        printf ("    %s\n", opt->descr);
426
    }
427

    
428
    qemu_free (uprefix);
429
}
430

    
431
static void audio_process_options (const char *prefix,
432
                                   struct audio_option *opt)
433
{
434
    char *optname;
435
    const char qemu_prefix[] = "QEMU_";
436
    size_t preflen, optlen;
437

    
438
    if (audio_bug (AUDIO_FUNC, !prefix)) {
439
        dolog ("prefix = NULL\n");
440
        return;
441
    }
442

    
443
    if (audio_bug (AUDIO_FUNC, !opt)) {
444
        dolog ("opt = NULL\n");
445
        return;
446
    }
447

    
448
    preflen = strlen (prefix);
449

    
450
    for (; opt->name; opt++) {
451
        size_t len, i;
452
        int def;
453

    
454
        if (!opt->valp) {
455
            dolog ("Option value pointer for `%s' is not set\n",
456
                   opt->name);
457
            continue;
458
        }
459

    
460
        len = strlen (opt->name);
461
        /* len of opt->name + len of prefix + size of qemu_prefix
462
         * (includes trailing zero) + zero + underscore (on behalf of
463
         * sizeof) */
464
        optlen = len + preflen + sizeof (qemu_prefix) + 1;
465
        optname = qemu_malloc (optlen);
466

    
467
        pstrcpy (optname, optlen, qemu_prefix);
468

    
469
        /* copy while upper-casing, including trailing zero */
470
        for (i = 0; i <= preflen; ++i) {
471
            optname[i + sizeof (qemu_prefix) - 1] = qemu_toupper(prefix[i]);
472
        }
473
        pstrcat (optname, optlen, "_");
474
        pstrcat (optname, optlen, opt->name);
475

    
476
        def = 1;
477
        switch (opt->tag) {
478
        case AUD_OPT_BOOL:
479
        case AUD_OPT_INT:
480
            {
481
                int *intp = opt->valp;
482
                *intp = audio_get_conf_int (optname, *intp, &def);
483
            }
484
            break;
485

    
486
        case AUD_OPT_FMT:
487
            {
488
                audfmt_e *fmtp = opt->valp;
489
                *fmtp = audio_get_conf_fmt (optname, *fmtp, &def);
490
            }
491
            break;
492

    
493
        case AUD_OPT_STR:
494
            {
495
                const char **strp = opt->valp;
496
                *strp = audio_get_conf_str (optname, *strp, &def);
497
            }
498
            break;
499

    
500
        default:
501
            dolog ("Bad value tag for option `%s' - %d\n",
502
                   optname, opt->tag);
503
            break;
504
        }
505

    
506
        if (!opt->overriddenp) {
507
            opt->overriddenp = &opt->overridden;
508
        }
509
        *opt->overriddenp = !def;
510
        qemu_free (optname);
511
    }
512
}
513

    
514
static void audio_print_settings (struct audsettings *as)
515
{
516
    dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
517

    
518
    switch (as->fmt) {
519
    case AUD_FMT_S8:
520
        AUD_log (NULL, "S8");
521
        break;
522
    case AUD_FMT_U8:
523
        AUD_log (NULL, "U8");
524
        break;
525
    case AUD_FMT_S16:
526
        AUD_log (NULL, "S16");
527
        break;
528
    case AUD_FMT_U16:
529
        AUD_log (NULL, "U16");
530
        break;
531
    case AUD_FMT_S32:
532
        AUD_log (NULL, "S32");
533
        break;
534
    case AUD_FMT_U32:
535
        AUD_log (NULL, "U32");
536
        break;
537
    default:
538
        AUD_log (NULL, "invalid(%d)", as->fmt);
539
        break;
540
    }
541

    
542
    AUD_log (NULL, " endianness=");
543
    switch (as->endianness) {
544
    case 0:
545
        AUD_log (NULL, "little");
546
        break;
547
    case 1:
548
        AUD_log (NULL, "big");
549
        break;
550
    default:
551
        AUD_log (NULL, "invalid");
552
        break;
553
    }
554
    AUD_log (NULL, "\n");
555
}
556

    
557
static int audio_validate_settings (struct audsettings *as)
558
{
559
    int invalid;
560

    
561
    invalid = as->nchannels != 1 && as->nchannels != 2;
562
    invalid |= as->endianness != 0 && as->endianness != 1;
563

    
564
    switch (as->fmt) {
565
    case AUD_FMT_S8:
566
    case AUD_FMT_U8:
567
    case AUD_FMT_S16:
568
    case AUD_FMT_U16:
569
    case AUD_FMT_S32:
570
    case AUD_FMT_U32:
571
        break;
572
    default:
573
        invalid = 1;
574
        break;
575
    }
576

    
577
    invalid |= as->freq <= 0;
578
    return invalid ? -1 : 0;
579
}
580

    
581
static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as)
582
{
583
    int bits = 8, sign = 0;
584

    
585
    switch (as->fmt) {
586
    case AUD_FMT_S8:
587
        sign = 1;
588
    case AUD_FMT_U8:
589
        break;
590

    
591
    case AUD_FMT_S16:
592
        sign = 1;
593
    case AUD_FMT_U16:
594
        bits = 16;
595
        break;
596

    
597
    case AUD_FMT_S32:
598
        sign = 1;
599
    case AUD_FMT_U32:
600
        bits = 32;
601
        break;
602
    }
603
    return info->freq == as->freq
604
        && info->nchannels == as->nchannels
605
        && info->sign == sign
606
        && info->bits == bits
607
        && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
608
}
609

    
610
void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as)
611
{
612
    int bits = 8, sign = 0, shift = 0;
613

    
614
    switch (as->fmt) {
615
    case AUD_FMT_S8:
616
        sign = 1;
617
    case AUD_FMT_U8:
618
        break;
619

    
620
    case AUD_FMT_S16:
621
        sign = 1;
622
    case AUD_FMT_U16:
623
        bits = 16;
624
        shift = 1;
625
        break;
626

    
627
    case AUD_FMT_S32:
628
        sign = 1;
629
    case AUD_FMT_U32:
630
        bits = 32;
631
        shift = 2;
632
        break;
633
    }
634

    
635
    info->freq = as->freq;
636
    info->bits = bits;
637
    info->sign = sign;
638
    info->nchannels = as->nchannels;
639
    info->shift = (as->nchannels == 2) + shift;
640
    info->align = (1 << info->shift) - 1;
641
    info->bytes_per_second = info->freq << info->shift;
642
    info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
643
}
644

    
645
void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
646
{
647
    if (!len) {
648
        return;
649
    }
650

    
651
    if (info->sign) {
652
        memset (buf, 0x00, len << info->shift);
653
    }
654
    else {
655
        switch (info->bits) {
656
        case 8:
657
            memset (buf, 0x80, len << info->shift);
658
            break;
659

    
660
        case 16:
661
            {
662
                int i;
663
                uint16_t *p = buf;
664
                int shift = info->nchannels - 1;
665
                short s = INT16_MAX;
666

    
667
                if (info->swap_endianness) {
668
                    s = bswap16 (s);
669
                }
670

    
671
                for (i = 0; i < len << shift; i++) {
672
                    p[i] = s;
673
                }
674
            }
675
            break;
676

    
677
        case 32:
678
            {
679
                int i;
680
                uint32_t *p = buf;
681
                int shift = info->nchannels - 1;
682
                int32_t s = INT32_MAX;
683

    
684
                if (info->swap_endianness) {
685
                    s = bswap32 (s);
686
                }
687

    
688
                for (i = 0; i < len << shift; i++) {
689
                    p[i] = s;
690
                }
691
            }
692
            break;
693

    
694
        default:
695
            AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
696
                     info->bits);
697
            break;
698
        }
699
    }
700
}
701

    
702
/*
703
 * Capture
704
 */
705
static void noop_conv (struct st_sample *dst, const void *src,
706
                       int samples, struct mixeng_volume *vol)
707
{
708
    (void) src;
709
    (void) dst;
710
    (void) samples;
711
    (void) vol;
712
}
713

    
714
static CaptureVoiceOut *audio_pcm_capture_find_specific (
715
    struct audsettings *as
716
    )
717
{
718
    CaptureVoiceOut *cap;
719
    AudioState *s = &glob_audio_state;
720

    
721
    for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
722
        if (audio_pcm_info_eq (&cap->hw.info, as)) {
723
            return cap;
724
        }
725
    }
726
    return NULL;
727
}
728

    
729
static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
730
{
731
    struct capture_callback *cb;
732

    
733
#ifdef DEBUG_CAPTURE
734
    dolog ("notification %d sent\n", cmd);
735
#endif
736
    for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
737
        cb->ops.notify (cb->opaque, cmd);
738
    }
739
}
740

    
741
static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
742
{
743
    if (cap->hw.enabled != enabled) {
744
        audcnotification_e cmd;
745
        cap->hw.enabled = enabled;
746
        cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
747
        audio_notify_capture (cap, cmd);
748
    }
749
}
750

    
751
static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
752
{
753
    HWVoiceOut *hw = &cap->hw;
754
    SWVoiceOut *sw;
755
    int enabled = 0;
756

    
757
    for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
758
        if (sw->active) {
759
            enabled = 1;
760
            break;
761
        }
762
    }
763
    audio_capture_maybe_changed (cap, enabled);
764
}
765

    
766
static void audio_detach_capture (HWVoiceOut *hw)
767
{
768
    SWVoiceCap *sc = hw->cap_head.lh_first;
769

    
770
    while (sc) {
771
        SWVoiceCap *sc1 = sc->entries.le_next;
772
        SWVoiceOut *sw = &sc->sw;
773
        CaptureVoiceOut *cap = sc->cap;
774
        int was_active = sw->active;
775

    
776
        if (sw->rate) {
777
            st_rate_stop (sw->rate);
778
            sw->rate = NULL;
779
        }
780

    
781
        QLIST_REMOVE (sw, entries);
782
        QLIST_REMOVE (sc, entries);
783
        qemu_free (sc);
784
        if (was_active) {
785
            /* We have removed soft voice from the capture:
786
               this might have changed the overall status of the capture
787
               since this might have been the only active voice */
788
            audio_recalc_and_notify_capture (cap);
789
        }
790
        sc = sc1;
791
    }
792
}
793

    
794
static int audio_attach_capture (HWVoiceOut *hw)
795
{
796
    AudioState *s = &glob_audio_state;
797
    CaptureVoiceOut *cap;
798

    
799
    audio_detach_capture (hw);
800
    for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
801
        SWVoiceCap *sc;
802
        SWVoiceOut *sw;
803
        HWVoiceOut *hw_cap = &cap->hw;
804

    
805
        sc = audio_calloc (AUDIO_FUNC, 1, sizeof (*sc));
806
        if (!sc) {
807
            dolog ("Could not allocate soft capture voice (%zu bytes)\n",
808
                   sizeof (*sc));
809
            return -1;
810
        }
811

    
812
        sc->cap = cap;
813
        sw = &sc->sw;
814
        sw->hw = hw_cap;
815
        sw->info = hw->info;
816
        sw->empty = 1;
817
        sw->active = hw->enabled;
818
        sw->conv = noop_conv;
819
        sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq;
820
        sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
821
        if (!sw->rate) {
822
            dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw));
823
            qemu_free (sw);
824
            return -1;
825
        }
826
        QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
827
        QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
828
#ifdef DEBUG_CAPTURE
829
        asprintf (&sw->name, "for %p %d,%d,%d",
830
                  hw, sw->info.freq, sw->info.bits, sw->info.nchannels);
831
        dolog ("Added %s active = %d\n", sw->name, sw->active);
832
#endif
833
        if (sw->active) {
834
            audio_capture_maybe_changed (cap, 1);
835
        }
836
    }
837
    return 0;
838
}
839

    
840
/*
841
 * Hard voice (capture)
842
 */
843
static int audio_pcm_hw_find_min_in (HWVoiceIn *hw)
844
{
845
    SWVoiceIn *sw;
846
    int m = hw->total_samples_captured;
847

    
848
    for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
849
        if (sw->active) {
850
            m = audio_MIN (m, sw->total_hw_samples_acquired);
851
        }
852
    }
853
    return m;
854
}
855

    
856
int audio_pcm_hw_get_live_in (HWVoiceIn *hw)
857
{
858
    int live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
859
    if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) {
860
        dolog ("live=%d hw->samples=%d\n", live, hw->samples);
861
        return 0;
862
    }
863
    return live;
864
}
865

    
866
int audio_pcm_hw_clip_out (HWVoiceOut *hw, void *pcm_buf,
867
                           int live, int pending)
868
{
869
    int left = hw->samples - pending;
870
    int len = audio_MIN (left, live);
871
    int clipped = 0;
872

    
873
    while (len) {
874
        struct st_sample *src = hw->mix_buf + hw->rpos;
875
        uint8_t *dst = advance (pcm_buf, hw->rpos << hw->info.shift);
876
        int samples_till_end_of_buf = hw->samples - hw->rpos;
877
        int samples_to_clip = audio_MIN (len, samples_till_end_of_buf);
878

    
879
        hw->clip (dst, src, samples_to_clip);
880

    
881
        hw->rpos = (hw->rpos + samples_to_clip) % hw->samples;
882
        len -= samples_to_clip;
883
        clipped += samples_to_clip;
884
    }
885
    return clipped;
886
}
887

    
888
/*
889
 * Soft voice (capture)
890
 */
891
static int audio_pcm_sw_get_rpos_in (SWVoiceIn *sw)
892
{
893
    HWVoiceIn *hw = sw->hw;
894
    int live = hw->total_samples_captured - sw->total_hw_samples_acquired;
895
    int rpos;
896

    
897
    if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) {
898
        dolog ("live=%d hw->samples=%d\n", live, hw->samples);
899
        return 0;
900
    }
901

    
902
    rpos = hw->wpos - live;
903
    if (rpos >= 0) {
904
        return rpos;
905
    }
906
    else {
907
        return hw->samples + rpos;
908
    }
909
}
910

    
911
int audio_pcm_sw_read (SWVoiceIn *sw, void *buf, int size)
912
{
913
    HWVoiceIn *hw = sw->hw;
914
    int samples, live, ret = 0, swlim, isamp, osamp, rpos, total = 0;
915
    struct st_sample *src, *dst = sw->buf;
916

    
917
    rpos = audio_pcm_sw_get_rpos_in (sw) % hw->samples;
918

    
919
    live = hw->total_samples_captured - sw->total_hw_samples_acquired;
920
    if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) {
921
        dolog ("live_in=%d hw->samples=%d\n", live, hw->samples);
922
        return 0;
923
    }
924

    
925
    samples = size >> sw->info.shift;
926
    if (!live) {
927
        return 0;
928
    }
929

    
930
    swlim = (live * sw->ratio) >> 32;
931
    swlim = audio_MIN (swlim, samples);
932

    
933
    while (swlim) {
934
        src = hw->conv_buf + rpos;
935
        isamp = hw->wpos - rpos;
936
        /* XXX: <= ? */
937
        if (isamp <= 0) {
938
            isamp = hw->samples - rpos;
939
        }
940

    
941
        if (!isamp) {
942
            break;
943
        }
944
        osamp = swlim;
945

    
946
        if (audio_bug (AUDIO_FUNC, osamp < 0)) {
947
            dolog ("osamp=%d\n", osamp);
948
            return 0;
949
        }
950

    
951
        st_rate_flow (sw->rate, src, dst, &isamp, &osamp);
952
        swlim -= osamp;
953
        rpos = (rpos + isamp) % hw->samples;
954
        dst += osamp;
955
        ret += osamp;
956
        total += isamp;
957
    }
958

    
959
    sw->clip (buf, sw->buf, ret);
960
    sw->total_hw_samples_acquired += total;
961
    return ret << sw->info.shift;
962
}
963

    
964
/*
965
 * Hard voice (playback)
966
 */
967
static int audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
968
{
969
    SWVoiceOut *sw;
970
    int m = INT_MAX;
971
    int nb_live = 0;
972

    
973
    for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
974
        if (sw->active || !sw->empty) {
975
            m = audio_MIN (m, sw->total_hw_samples_mixed);
976
            nb_live += 1;
977
        }
978
    }
979

    
980
    *nb_livep = nb_live;
981
    return m;
982
}
983

    
984
static int audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live)
985
{
986
    int smin;
987
    int nb_live1;
988

    
989
    smin = audio_pcm_hw_find_min_out (hw, &nb_live1);
990
    if (nb_live) {
991
        *nb_live = nb_live1;
992
    }
993

    
994
    if (nb_live1) {
995
        int live = smin;
996

    
997
        if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) {
998
            dolog ("live=%d hw->samples=%d\n", live, hw->samples);
999
            return 0;
1000
        }
1001
        return live;
1002
    }
1003
    return 0;
1004
}
1005

    
1006
/*
1007
 * Soft voice (playback)
1008
 */
1009
int audio_pcm_sw_write (SWVoiceOut *sw, void *buf, int size)
1010
{
1011
    int hwsamples, samples, isamp, osamp, wpos, live, dead, left, swlim, blck;
1012
    int ret = 0, pos = 0, total = 0;
1013

    
1014
    if (!sw) {
1015
        return size;
1016
    }
1017

    
1018
    hwsamples = sw->hw->samples;
1019

    
1020
    live = sw->total_hw_samples_mixed;
1021
    if (audio_bug (AUDIO_FUNC, live < 0 || live > hwsamples)){
1022
        dolog ("live=%d hw->samples=%d\n", live, hwsamples);
1023
        return 0;
1024
    }
1025

    
1026
    if (live == hwsamples) {
1027
#ifdef DEBUG_OUT
1028
        dolog ("%s is full %d\n", sw->name, live);
1029
#endif
1030
        return 0;
1031
    }
1032

    
1033
    wpos = (sw->hw->rpos + live) % hwsamples;
1034
    samples = size >> sw->info.shift;
1035

    
1036
    dead = hwsamples - live;
1037
    swlim = ((int64_t) dead << 32) / sw->ratio;
1038
    swlim = audio_MIN (swlim, samples);
1039
    if (swlim) {
1040
        sw->conv (sw->buf, buf, swlim, &sw->vol);
1041
    }
1042

    
1043
    while (swlim) {
1044
        dead = hwsamples - live;
1045
        left = hwsamples - wpos;
1046
        blck = audio_MIN (dead, left);
1047
        if (!blck) {
1048
            break;
1049
        }
1050
        isamp = swlim;
1051
        osamp = blck;
1052
        st_rate_flow_mix (
1053
            sw->rate,
1054
            sw->buf + pos,
1055
            sw->hw->mix_buf + wpos,
1056
            &isamp,
1057
            &osamp
1058
            );
1059
        ret += isamp;
1060
        swlim -= isamp;
1061
        pos += isamp;
1062
        live += osamp;
1063
        wpos = (wpos + osamp) % hwsamples;
1064
        total += osamp;
1065
    }
1066

    
1067
    sw->total_hw_samples_mixed += total;
1068
    sw->empty = sw->total_hw_samples_mixed == 0;
1069

    
1070
#ifdef DEBUG_OUT
1071
    dolog (
1072
        "%s: write size %d ret %d total sw %d\n",
1073
        SW_NAME (sw),
1074
        size >> sw->info.shift,
1075
        ret,
1076
        sw->total_hw_samples_mixed
1077
        );
1078
#endif
1079

    
1080
    return ret << sw->info.shift;
1081
}
1082

    
1083
#ifdef DEBUG_AUDIO
1084
static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
1085
{
1086
    dolog ("%s: bits %d, sign %d, freq %d, nchan %d\n",
1087
           cap, info->bits, info->sign, info->freq, info->nchannels);
1088
}
1089
#endif
1090

    
1091
#define DAC
1092
#include "audio_template.h"
1093
#undef DAC
1094
#include "audio_template.h"
1095

    
1096
/*
1097
 * Timer
1098
 */
1099
static void audio_timer (void *opaque)
1100
{
1101
    AudioState *s = opaque;
1102

    
1103
    audio_run ("timer");
1104
    qemu_mod_timer (s->ts, qemu_get_clock (vm_clock) + conf.period.ticks);
1105
}
1106

    
1107

    
1108
static int audio_is_timer_needed (void)
1109
{
1110
    HWVoiceIn *hwi = NULL;
1111
    HWVoiceOut *hwo = NULL;
1112

    
1113
    while ((hwo = audio_pcm_hw_find_any_enabled_out (hwo))) {
1114
        if (!hwo->poll_mode) return 1;
1115
    }
1116
    while ((hwi = audio_pcm_hw_find_any_enabled_in (hwi))) {
1117
        if (!hwi->poll_mode) return 1;
1118
    }
1119
    return 0;
1120
}
1121

    
1122
static void audio_reset_timer (void)
1123
{
1124
    AudioState *s = &glob_audio_state;
1125

    
1126
    if (audio_is_timer_needed ()) {
1127
        qemu_mod_timer (s->ts, qemu_get_clock (vm_clock) + 1);
1128
    }
1129
    else {
1130
        qemu_del_timer (s->ts);
1131
    }
1132
}
1133

    
1134
/*
1135
 * Public API
1136
 */
1137
int AUD_write (SWVoiceOut *sw, void *buf, int size)
1138
{
1139
    int bytes;
1140

    
1141
    if (!sw) {
1142
        /* XXX: Consider options */
1143
        return size;
1144
    }
1145

    
1146
    if (!sw->hw->enabled) {
1147
        dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
1148
        return 0;
1149
    }
1150

    
1151
    bytes = sw->hw->pcm_ops->write (sw, buf, size);
1152
    return bytes;
1153
}
1154

    
1155
int AUD_read (SWVoiceIn *sw, void *buf, int size)
1156
{
1157
    int bytes;
1158

    
1159
    if (!sw) {
1160
        /* XXX: Consider options */
1161
        return size;
1162
    }
1163

    
1164
    if (!sw->hw->enabled) {
1165
        dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
1166
        return 0;
1167
    }
1168

    
1169
    bytes = sw->hw->pcm_ops->read (sw, buf, size);
1170
    return bytes;
1171
}
1172

    
1173
int AUD_get_buffer_size_out (SWVoiceOut *sw)
1174
{
1175
    return sw->hw->samples << sw->hw->info.shift;
1176
}
1177

    
1178
void AUD_set_active_out (SWVoiceOut *sw, int on)
1179
{
1180
    HWVoiceOut *hw;
1181

    
1182
    if (!sw) {
1183
        return;
1184
    }
1185

    
1186
    hw = sw->hw;
1187
    if (sw->active != on) {
1188
        AudioState *s = &glob_audio_state;
1189
        SWVoiceOut *temp_sw;
1190
        SWVoiceCap *sc;
1191

    
1192
        if (on) {
1193
            hw->pending_disable = 0;
1194
            if (!hw->enabled) {
1195
                hw->enabled = 1;
1196
                if (s->vm_running) {
1197
                    hw->pcm_ops->ctl_out (hw, VOICE_ENABLE, conf.try_poll_out);
1198
                    audio_reset_timer ();
1199
                }
1200
            }
1201
        }
1202
        else {
1203
            if (hw->enabled) {
1204
                int nb_active = 0;
1205

    
1206
                for (temp_sw = hw->sw_head.lh_first; temp_sw;
1207
                     temp_sw = temp_sw->entries.le_next) {
1208
                    nb_active += temp_sw->active != 0;
1209
                }
1210

    
1211
                hw->pending_disable = nb_active == 1;
1212
            }
1213
        }
1214

    
1215
        for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1216
            sc->sw.active = hw->enabled;
1217
            if (hw->enabled) {
1218
                audio_capture_maybe_changed (sc->cap, 1);
1219
            }
1220
        }
1221
        sw->active = on;
1222
    }
1223
}
1224

    
1225
void AUD_set_active_in (SWVoiceIn *sw, int on)
1226
{
1227
    HWVoiceIn *hw;
1228

    
1229
    if (!sw) {
1230
        return;
1231
    }
1232

    
1233
    hw = sw->hw;
1234
    if (sw->active != on) {
1235
        AudioState *s = &glob_audio_state;
1236
        SWVoiceIn *temp_sw;
1237

    
1238
        if (on) {
1239
            if (!hw->enabled) {
1240
                hw->enabled = 1;
1241
                if (s->vm_running) {
1242
                    hw->pcm_ops->ctl_in (hw, VOICE_ENABLE, conf.try_poll_in);
1243
                }
1244
            }
1245
            sw->total_hw_samples_acquired = hw->total_samples_captured;
1246
        }
1247
        else {
1248
            if (hw->enabled) {
1249
                int nb_active = 0;
1250

    
1251
                for (temp_sw = hw->sw_head.lh_first; temp_sw;
1252
                     temp_sw = temp_sw->entries.le_next) {
1253
                    nb_active += temp_sw->active != 0;
1254
                }
1255

    
1256
                if (nb_active == 1) {
1257
                    hw->enabled = 0;
1258
                    hw->pcm_ops->ctl_in (hw, VOICE_DISABLE);
1259
                }
1260
            }
1261
        }
1262
        sw->active = on;
1263
    }
1264
}
1265

    
1266
static int audio_get_avail (SWVoiceIn *sw)
1267
{
1268
    int live;
1269

    
1270
    if (!sw) {
1271
        return 0;
1272
    }
1273

    
1274
    live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
1275
    if (audio_bug (AUDIO_FUNC, live < 0 || live > sw->hw->samples)) {
1276
        dolog ("live=%d sw->hw->samples=%d\n", live, sw->hw->samples);
1277
        return 0;
1278
    }
1279

    
1280
    ldebug (
1281
        "%s: get_avail live %d ret %" PRId64 "\n",
1282
        SW_NAME (sw),
1283
        live, (((int64_t) live << 32) / sw->ratio) << sw->info.shift
1284
        );
1285

    
1286
    return (((int64_t) live << 32) / sw->ratio) << sw->info.shift;
1287
}
1288

    
1289
static int audio_get_free (SWVoiceOut *sw)
1290
{
1291
    int live, dead;
1292

    
1293
    if (!sw) {
1294
        return 0;
1295
    }
1296

    
1297
    live = sw->total_hw_samples_mixed;
1298

    
1299
    if (audio_bug (AUDIO_FUNC, live < 0 || live > sw->hw->samples)) {
1300
        dolog ("live=%d sw->hw->samples=%d\n", live, sw->hw->samples);
1301
        return 0;
1302
    }
1303

    
1304
    dead = sw->hw->samples - live;
1305

    
1306
#ifdef DEBUG_OUT
1307
    dolog ("%s: get_free live %d dead %d ret %" PRId64 "\n",
1308
           SW_NAME (sw),
1309
           live, dead, (((int64_t) dead << 32) / sw->ratio) << sw->info.shift);
1310
#endif
1311

    
1312
    return (((int64_t) dead << 32) / sw->ratio) << sw->info.shift;
1313
}
1314

    
1315
static void audio_capture_mix_and_clear (HWVoiceOut *hw, int rpos, int samples)
1316
{
1317
    int n;
1318

    
1319
    if (hw->enabled) {
1320
        SWVoiceCap *sc;
1321

    
1322
        for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1323
            SWVoiceOut *sw = &sc->sw;
1324
            int rpos2 = rpos;
1325

    
1326
            n = samples;
1327
            while (n) {
1328
                int till_end_of_hw = hw->samples - rpos2;
1329
                int to_write = audio_MIN (till_end_of_hw, n);
1330
                int bytes = to_write << hw->info.shift;
1331
                int written;
1332

    
1333
                sw->buf = hw->mix_buf + rpos2;
1334
                written = audio_pcm_sw_write (sw, NULL, bytes);
1335
                if (written - bytes) {
1336
                    dolog ("Could not mix %d bytes into a capture "
1337
                           "buffer, mixed %d\n",
1338
                           bytes, written);
1339
                    break;
1340
                }
1341
                n -= to_write;
1342
                rpos2 = (rpos2 + to_write) % hw->samples;
1343
            }
1344
        }
1345
    }
1346

    
1347
    n = audio_MIN (samples, hw->samples - rpos);
1348
    mixeng_clear (hw->mix_buf + rpos, n);
1349
    mixeng_clear (hw->mix_buf, samples - n);
1350
}
1351

    
1352
static void audio_run_out (AudioState *s)
1353
{
1354
    HWVoiceOut *hw = NULL;
1355
    SWVoiceOut *sw;
1356

    
1357
    while ((hw = audio_pcm_hw_find_any_enabled_out (hw))) {
1358
        int played;
1359
        int live, free, nb_live, cleanup_required, prev_rpos;
1360

    
1361
        live = audio_pcm_hw_get_live_out (hw, &nb_live);
1362
        if (!nb_live) {
1363
            live = 0;
1364
        }
1365

    
1366
        if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) {
1367
            dolog ("live=%d hw->samples=%d\n", live, hw->samples);
1368
            continue;
1369
        }
1370

    
1371
        if (hw->pending_disable && !nb_live) {
1372
            SWVoiceCap *sc;
1373
#ifdef DEBUG_OUT
1374
            dolog ("Disabling voice\n");
1375
#endif
1376
            hw->enabled = 0;
1377
            hw->pending_disable = 0;
1378
            hw->pcm_ops->ctl_out (hw, VOICE_DISABLE);
1379
            for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1380
                sc->sw.active = 0;
1381
                audio_recalc_and_notify_capture (sc->cap);
1382
            }
1383
            continue;
1384
        }
1385

    
1386
        if (!live) {
1387
            for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1388
                if (sw->active) {
1389
                    free = audio_get_free (sw);
1390
                    if (free > 0) {
1391
                        sw->callback.fn (sw->callback.opaque, free);
1392
                    }
1393
                }
1394
            }
1395
            continue;
1396
        }
1397

    
1398
        prev_rpos = hw->rpos;
1399
        played = hw->pcm_ops->run_out (hw, live);
1400
        if (audio_bug (AUDIO_FUNC, hw->rpos >= hw->samples)) {
1401
            dolog ("hw->rpos=%d hw->samples=%d played=%d\n",
1402
                   hw->rpos, hw->samples, played);
1403
            hw->rpos = 0;
1404
        }
1405

    
1406
#ifdef DEBUG_OUT
1407
        dolog ("played=%d\n", played);
1408
#endif
1409

    
1410
        if (played) {
1411
            hw->ts_helper += played;
1412
            audio_capture_mix_and_clear (hw, prev_rpos, played);
1413
        }
1414

    
1415
        cleanup_required = 0;
1416
        for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1417
            if (!sw->active && sw->empty) {
1418
                continue;
1419
            }
1420

    
1421
            if (audio_bug (AUDIO_FUNC, played > sw->total_hw_samples_mixed)) {
1422
                dolog ("played=%d sw->total_hw_samples_mixed=%d\n",
1423
                       played, sw->total_hw_samples_mixed);
1424
                played = sw->total_hw_samples_mixed;
1425
            }
1426

    
1427
            sw->total_hw_samples_mixed -= played;
1428

    
1429
            if (!sw->total_hw_samples_mixed) {
1430
                sw->empty = 1;
1431
                cleanup_required |= !sw->active && !sw->callback.fn;
1432
            }
1433

    
1434
            if (sw->active) {
1435
                free = audio_get_free (sw);
1436
                if (free > 0) {
1437
                    sw->callback.fn (sw->callback.opaque, free);
1438
                }
1439
            }
1440
        }
1441

    
1442
        if (cleanup_required) {
1443
            SWVoiceOut *sw1;
1444

    
1445
            sw = hw->sw_head.lh_first;
1446
            while (sw) {
1447
                sw1 = sw->entries.le_next;
1448
                if (!sw->active && !sw->callback.fn) {
1449
#ifdef DEBUG_PLIVE
1450
                    dolog ("Finishing with old voice\n");
1451
#endif
1452
                    audio_close_out (sw);
1453
                }
1454
                sw = sw1;
1455
            }
1456
        }
1457
    }
1458
}
1459

    
1460
static void audio_run_in (AudioState *s)
1461
{
1462
    HWVoiceIn *hw = NULL;
1463

    
1464
    while ((hw = audio_pcm_hw_find_any_enabled_in (hw))) {
1465
        SWVoiceIn *sw;
1466
        int captured, min;
1467

    
1468
        captured = hw->pcm_ops->run_in (hw);
1469

    
1470
        min = audio_pcm_hw_find_min_in (hw);
1471
        hw->total_samples_captured += captured - min;
1472
        hw->ts_helper += captured;
1473

    
1474
        for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1475
            sw->total_hw_samples_acquired -= min;
1476

    
1477
            if (sw->active) {
1478
                int avail;
1479

    
1480
                avail = audio_get_avail (sw);
1481
                if (avail > 0) {
1482
                    sw->callback.fn (sw->callback.opaque, avail);
1483
                }
1484
            }
1485
        }
1486
    }
1487
}
1488

    
1489
static void audio_run_capture (AudioState *s)
1490
{
1491
    CaptureVoiceOut *cap;
1492

    
1493
    for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
1494
        int live, rpos, captured;
1495
        HWVoiceOut *hw = &cap->hw;
1496
        SWVoiceOut *sw;
1497

    
1498
        captured = live = audio_pcm_hw_get_live_out (hw, NULL);
1499
        rpos = hw->rpos;
1500
        while (live) {
1501
            int left = hw->samples - rpos;
1502
            int to_capture = audio_MIN (live, left);
1503
            struct st_sample *src;
1504
            struct capture_callback *cb;
1505

    
1506
            src = hw->mix_buf + rpos;
1507
            hw->clip (cap->buf, src, to_capture);
1508
            mixeng_clear (src, to_capture);
1509

    
1510
            for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1511
                cb->ops.capture (cb->opaque, cap->buf,
1512
                                 to_capture << hw->info.shift);
1513
            }
1514
            rpos = (rpos + to_capture) % hw->samples;
1515
            live -= to_capture;
1516
        }
1517
        hw->rpos = rpos;
1518

    
1519
        for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1520
            if (!sw->active && sw->empty) {
1521
                continue;
1522
            }
1523

    
1524
            if (audio_bug (AUDIO_FUNC, captured > sw->total_hw_samples_mixed)) {
1525
                dolog ("captured=%d sw->total_hw_samples_mixed=%d\n",
1526
                       captured, sw->total_hw_samples_mixed);
1527
                captured = sw->total_hw_samples_mixed;
1528
            }
1529

    
1530
            sw->total_hw_samples_mixed -= captured;
1531
            sw->empty = sw->total_hw_samples_mixed == 0;
1532
        }
1533
    }
1534
}
1535

    
1536
void audio_run (const char *msg)
1537
{
1538
    AudioState *s = &glob_audio_state;
1539

    
1540
    audio_run_out (s);
1541
    audio_run_in (s);
1542
    audio_run_capture (s);
1543
#ifdef DEBUG_POLL
1544
    {
1545
        static double prevtime;
1546
        double currtime;
1547
        struct timeval tv;
1548

    
1549
        if (gettimeofday (&tv, NULL)) {
1550
            perror ("audio_run: gettimeofday");
1551
            return;
1552
        }
1553

    
1554
        currtime = tv.tv_sec + tv.tv_usec * 1e-6;
1555
        dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
1556
        prevtime = currtime;
1557
    }
1558
#endif
1559
}
1560

    
1561
static struct audio_option audio_options[] = {
1562
    /* DAC */
1563
    {
1564
        .name  = "DAC_FIXED_SETTINGS",
1565
        .tag   = AUD_OPT_BOOL,
1566
        .valp  = &conf.fixed_out.enabled,
1567
        .descr = "Use fixed settings for host DAC"
1568
    },
1569
    {
1570
        .name  = "DAC_FIXED_FREQ",
1571
        .tag   = AUD_OPT_INT,
1572
        .valp  = &conf.fixed_out.settings.freq,
1573
        .descr = "Frequency for fixed host DAC"
1574
    },
1575
    {
1576
        .name  = "DAC_FIXED_FMT",
1577
        .tag   = AUD_OPT_FMT,
1578
        .valp  = &conf.fixed_out.settings.fmt,
1579
        .descr = "Format for fixed host DAC"
1580
    },
1581
    {
1582
        .name  = "DAC_FIXED_CHANNELS",
1583
        .tag   = AUD_OPT_INT,
1584
        .valp  = &conf.fixed_out.settings.nchannels,
1585
        .descr = "Number of channels for fixed DAC (1 - mono, 2 - stereo)"
1586
    },
1587
    {
1588
        .name  = "DAC_VOICES",
1589
        .tag   = AUD_OPT_INT,
1590
        .valp  = &conf.fixed_out.nb_voices,
1591
        .descr = "Number of voices for DAC"
1592
    },
1593
    {
1594
        .name  = "DAC_TRY_POLL",
1595
        .tag   = AUD_OPT_BOOL,
1596
        .valp  = &conf.try_poll_out,
1597
        .descr = "Attempt using poll mode for DAC"
1598
    },
1599
    /* ADC */
1600
    {
1601
        .name  = "ADC_FIXED_SETTINGS",
1602
        .tag   = AUD_OPT_BOOL,
1603
        .valp  = &conf.fixed_in.enabled,
1604
        .descr = "Use fixed settings for host ADC"
1605
    },
1606
    {
1607
        .name  = "ADC_FIXED_FREQ",
1608
        .tag   = AUD_OPT_INT,
1609
        .valp  = &conf.fixed_in.settings.freq,
1610
        .descr = "Frequency for fixed host ADC"
1611
    },
1612
    {
1613
        .name  = "ADC_FIXED_FMT",
1614
        .tag   = AUD_OPT_FMT,
1615
        .valp  = &conf.fixed_in.settings.fmt,
1616
        .descr = "Format for fixed host ADC"
1617
    },
1618
    {
1619
        .name  = "ADC_FIXED_CHANNELS",
1620
        .tag   = AUD_OPT_INT,
1621
        .valp  = &conf.fixed_in.settings.nchannels,
1622
        .descr = "Number of channels for fixed ADC (1 - mono, 2 - stereo)"
1623
    },
1624
    {
1625
        .name  = "ADC_VOICES",
1626
        .tag   = AUD_OPT_INT,
1627
        .valp  = &conf.fixed_in.nb_voices,
1628
        .descr = "Number of voices for ADC"
1629
    },
1630
    {
1631
        .name  = "ADC_TRY_POLL",
1632
        .tag   = AUD_OPT_BOOL,
1633
        .valp  = &conf.try_poll_in,
1634
        .descr = "Attempt using poll mode for ADC"
1635
    },
1636
    /* Misc */
1637
    {
1638
        .name  = "TIMER_PERIOD",
1639
        .tag   = AUD_OPT_INT,
1640
        .valp  = &conf.period.hertz,
1641
        .descr = "Timer period in HZ (0 - use lowest possible)"
1642
    },
1643
    {
1644
        .name  = "PLIVE",
1645
        .tag   = AUD_OPT_BOOL,
1646
        .valp  = &conf.plive,
1647
        .descr = "(undocumented)"
1648
    },
1649
    {
1650
        .name  = "LOG_TO_MONITOR",
1651
        .tag   = AUD_OPT_BOOL,
1652
        .valp  = &conf.log_to_monitor,
1653
        .descr = "Print logging messages to monitor instead of stderr"
1654
    },
1655
    { /* End of list */ }
1656
};
1657

    
1658
static void audio_pp_nb_voices (const char *typ, int nb)
1659
{
1660
    switch (nb) {
1661
    case 0:
1662
        printf ("Does not support %s\n", typ);
1663
        break;
1664
    case 1:
1665
        printf ("One %s voice\n", typ);
1666
        break;
1667
    case INT_MAX:
1668
        printf ("Theoretically supports many %s voices\n", typ);
1669
        break;
1670
    default:
1671
        printf ("Theoretically supports upto %d %s voices\n", nb, typ);
1672
        break;
1673
    }
1674

    
1675
}
1676

    
1677
void AUD_help (void)
1678
{
1679
    size_t i;
1680

    
1681
    audio_process_options ("AUDIO", audio_options);
1682
    for (i = 0; i < ARRAY_SIZE (drvtab); i++) {
1683
        struct audio_driver *d = drvtab[i];
1684
        if (d->options) {
1685
            audio_process_options (d->name, d->options);
1686
        }
1687
    }
1688

    
1689
    printf ("Audio options:\n");
1690
    audio_print_options ("AUDIO", audio_options);
1691
    printf ("\n");
1692

    
1693
    printf ("Available drivers:\n");
1694

    
1695
    for (i = 0; i < ARRAY_SIZE (drvtab); i++) {
1696
        struct audio_driver *d = drvtab[i];
1697

    
1698
        printf ("Name: %s\n", d->name);
1699
        printf ("Description: %s\n", d->descr);
1700

    
1701
        audio_pp_nb_voices ("playback", d->max_voices_out);
1702
        audio_pp_nb_voices ("capture", d->max_voices_in);
1703

    
1704
        if (d->options) {
1705
            printf ("Options:\n");
1706
            audio_print_options (d->name, d->options);
1707
        }
1708
        else {
1709
            printf ("No options\n");
1710
        }
1711
        printf ("\n");
1712
    }
1713

    
1714
    printf (
1715
        "Options are settable through environment variables.\n"
1716
        "Example:\n"
1717
#ifdef _WIN32
1718
        "  set QEMU_AUDIO_DRV=wav\n"
1719
        "  set QEMU_WAV_PATH=c:\\tune.wav\n"
1720
#else
1721
        "  export QEMU_AUDIO_DRV=wav\n"
1722
        "  export QEMU_WAV_PATH=$HOME/tune.wav\n"
1723
        "(for csh replace export with setenv in the above)\n"
1724
#endif
1725
        "  qemu ...\n\n"
1726
        );
1727
}
1728

    
1729
static int audio_driver_init (AudioState *s, struct audio_driver *drv)
1730
{
1731
    if (drv->options) {
1732
        audio_process_options (drv->name, drv->options);
1733
    }
1734
    s->drv_opaque = drv->init ();
1735

    
1736
    if (s->drv_opaque) {
1737
        audio_init_nb_voices_out (drv);
1738
        audio_init_nb_voices_in (drv);
1739
        s->drv = drv;
1740
        return 0;
1741
    }
1742
    else {
1743
        dolog ("Could not init `%s' audio driver\n", drv->name);
1744
        return -1;
1745
    }
1746
}
1747

    
1748
static void audio_vm_change_state_handler (void *opaque, int running,
1749
                                           int reason)
1750
{
1751
    AudioState *s = opaque;
1752
    HWVoiceOut *hwo = NULL;
1753
    HWVoiceIn *hwi = NULL;
1754
    int op = running ? VOICE_ENABLE : VOICE_DISABLE;
1755

    
1756
    s->vm_running = running;
1757
    while ((hwo = audio_pcm_hw_find_any_enabled_out (hwo))) {
1758
        hwo->pcm_ops->ctl_out (hwo, op, conf.try_poll_out);
1759
    }
1760

    
1761
    while ((hwi = audio_pcm_hw_find_any_enabled_in (hwi))) {
1762
        hwi->pcm_ops->ctl_in (hwi, op, conf.try_poll_in);
1763
    }
1764
    audio_reset_timer ();
1765
}
1766

    
1767
static void audio_atexit (void)
1768
{
1769
    AudioState *s = &glob_audio_state;
1770
    HWVoiceOut *hwo = NULL;
1771
    HWVoiceIn *hwi = NULL;
1772

    
1773
    while ((hwo = audio_pcm_hw_find_any_enabled_out (hwo))) {
1774
        SWVoiceCap *sc;
1775

    
1776
        hwo->pcm_ops->ctl_out (hwo, VOICE_DISABLE);
1777
        hwo->pcm_ops->fini_out (hwo);
1778

    
1779
        for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1780
            CaptureVoiceOut *cap = sc->cap;
1781
            struct capture_callback *cb;
1782

    
1783
            for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1784
                cb->ops.destroy (cb->opaque);
1785
            }
1786
        }
1787
    }
1788

    
1789
    while ((hwi = audio_pcm_hw_find_any_enabled_in (hwi))) {
1790
        hwi->pcm_ops->ctl_in (hwi, VOICE_DISABLE);
1791
        hwi->pcm_ops->fini_in (hwi);
1792
    }
1793

    
1794
    if (s->drv) {
1795
        s->drv->fini (s->drv_opaque);
1796
    }
1797
}
1798

    
1799
static const VMStateDescription vmstate_audio = {
1800
    .name = "audio",
1801
    .version_id = 1,
1802
    .minimum_version_id = 1,
1803
    .minimum_version_id_old = 1,
1804
    .fields      = (VMStateField []) {
1805
        VMSTATE_END_OF_LIST()
1806
    }
1807
};
1808

    
1809
static void audio_init (void)
1810
{
1811
    size_t i;
1812
    int done = 0;
1813
    const char *drvname;
1814
    VMChangeStateEntry *e;
1815
    AudioState *s = &glob_audio_state;
1816

    
1817
    if (s->drv) {
1818
        return;
1819
    }
1820

    
1821
    QLIST_INIT (&s->hw_head_out);
1822
    QLIST_INIT (&s->hw_head_in);
1823
    QLIST_INIT (&s->cap_head);
1824
    atexit (audio_atexit);
1825

    
1826
    s->ts = qemu_new_timer (vm_clock, audio_timer, s);
1827
    if (!s->ts) {
1828
        hw_error("Could not create audio timer\n");
1829
    }
1830

    
1831
    audio_process_options ("AUDIO", audio_options);
1832

    
1833
    s->nb_hw_voices_out = conf.fixed_out.nb_voices;
1834
    s->nb_hw_voices_in = conf.fixed_in.nb_voices;
1835

    
1836
    if (s->nb_hw_voices_out <= 0) {
1837
        dolog ("Bogus number of playback voices %d, setting to 1\n",
1838
               s->nb_hw_voices_out);
1839
        s->nb_hw_voices_out = 1;
1840
    }
1841

    
1842
    if (s->nb_hw_voices_in <= 0) {
1843
        dolog ("Bogus number of capture voices %d, setting to 0\n",
1844
               s->nb_hw_voices_in);
1845
        s->nb_hw_voices_in = 0;
1846
    }
1847

    
1848
    {
1849
        int def;
1850
        drvname = audio_get_conf_str ("QEMU_AUDIO_DRV", NULL, &def);
1851
    }
1852

    
1853
    if (drvname) {
1854
        int found = 0;
1855

    
1856
        for (i = 0; i < ARRAY_SIZE (drvtab); i++) {
1857
            if (!strcmp (drvname, drvtab[i]->name)) {
1858
                done = !audio_driver_init (s, drvtab[i]);
1859
                found = 1;
1860
                break;
1861
            }
1862
        }
1863

    
1864
        if (!found) {
1865
            dolog ("Unknown audio driver `%s'\n", drvname);
1866
            dolog ("Run with -audio-help to list available drivers\n");
1867
        }
1868
    }
1869

    
1870
    if (!done) {
1871
        for (i = 0; !done && i < ARRAY_SIZE (drvtab); i++) {
1872
            if (drvtab[i]->can_be_default) {
1873
                done = !audio_driver_init (s, drvtab[i]);
1874
            }
1875
        }
1876
    }
1877

    
1878
    if (!done) {
1879
        done = !audio_driver_init (s, &no_audio_driver);
1880
        if (!done) {
1881
            hw_error("Could not initialize audio subsystem\n");
1882
        }
1883
        else {
1884
            dolog ("warning: Using timer based audio emulation\n");
1885
        }
1886
    }
1887

    
1888
    if (conf.period.hertz <= 0) {
1889
        if (conf.period.hertz < 0) {
1890
            dolog ("warning: Timer period is negative - %d "
1891
                   "treating as zero\n",
1892
                   conf.period.hertz);
1893
        }
1894
        conf.period.ticks = 1;
1895
    } else {
1896
        conf.period.ticks =
1897
            muldiv64 (1, get_ticks_per_sec (), conf.period.hertz);
1898
    }
1899

    
1900
    e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
1901
    if (!e) {
1902
        dolog ("warning: Could not register change state handler\n"
1903
               "(Audio can continue looping even after stopping the VM)\n");
1904
    }
1905

    
1906
    QLIST_INIT (&s->card_head);
1907
    vmstate_register (NULL, 0, &vmstate_audio, s);
1908
}
1909

    
1910
void AUD_register_card (const char *name, QEMUSoundCard *card)
1911
{
1912
    audio_init ();
1913
    card->name = qemu_strdup (name);
1914
    memset (&card->entries, 0, sizeof (card->entries));
1915
    QLIST_INSERT_HEAD (&glob_audio_state.card_head, card, entries);
1916
}
1917

    
1918
void AUD_remove_card (QEMUSoundCard *card)
1919
{
1920
    QLIST_REMOVE (card, entries);
1921
    qemu_free (card->name);
1922
}
1923

    
1924

    
1925
CaptureVoiceOut *AUD_add_capture (
1926
    struct audsettings *as,
1927
    struct audio_capture_ops *ops,
1928
    void *cb_opaque
1929
    )
1930
{
1931
    AudioState *s = &glob_audio_state;
1932
    CaptureVoiceOut *cap;
1933
    struct capture_callback *cb;
1934

    
1935
    if (audio_validate_settings (as)) {
1936
        dolog ("Invalid settings were passed when trying to add capture\n");
1937
        audio_print_settings (as);
1938
        goto err0;
1939
    }
1940

    
1941
    cb = audio_calloc (AUDIO_FUNC, 1, sizeof (*cb));
1942
    if (!cb) {
1943
        dolog ("Could not allocate capture callback information, size %zu\n",
1944
               sizeof (*cb));
1945
        goto err0;
1946
    }
1947
    cb->ops = *ops;
1948
    cb->opaque = cb_opaque;
1949

    
1950
    cap = audio_pcm_capture_find_specific (as);
1951
    if (cap) {
1952
        QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1953
        return cap;
1954
    }
1955
    else {
1956
        HWVoiceOut *hw;
1957
        CaptureVoiceOut *cap;
1958

    
1959
        cap = audio_calloc (AUDIO_FUNC, 1, sizeof (*cap));
1960
        if (!cap) {
1961
            dolog ("Could not allocate capture voice, size %zu\n",
1962
                   sizeof (*cap));
1963
            goto err1;
1964
        }
1965

    
1966
        hw = &cap->hw;
1967
        QLIST_INIT (&hw->sw_head);
1968
        QLIST_INIT (&cap->cb_head);
1969

    
1970
        /* XXX find a more elegant way */
1971
        hw->samples = 4096 * 4;
1972
        hw->mix_buf = audio_calloc (AUDIO_FUNC, hw->samples,
1973
                                    sizeof (struct st_sample));
1974
        if (!hw->mix_buf) {
1975
            dolog ("Could not allocate capture mix buffer (%d samples)\n",
1976
                   hw->samples);
1977
            goto err2;
1978
        }
1979

    
1980
        audio_pcm_init_info (&hw->info, as);
1981

    
1982
        cap->buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift);
1983
        if (!cap->buf) {
1984
            dolog ("Could not allocate capture buffer "
1985
                   "(%d samples, each %d bytes)\n",
1986
                   hw->samples, 1 << hw->info.shift);
1987
            goto err3;
1988
        }
1989

    
1990
        hw->clip = mixeng_clip
1991
            [hw->info.nchannels == 2]
1992
            [hw->info.sign]
1993
            [hw->info.swap_endianness]
1994
            [audio_bits_to_index (hw->info.bits)];
1995

    
1996
        QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
1997
        QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1998

    
1999
        hw = NULL;
2000
        while ((hw = audio_pcm_hw_find_any_out (hw))) {
2001
            audio_attach_capture (hw);
2002
        }
2003
        return cap;
2004

    
2005
    err3:
2006
        qemu_free (cap->hw.mix_buf);
2007
    err2:
2008
        qemu_free (cap);
2009
    err1:
2010
        qemu_free (cb);
2011
    err0:
2012
        return NULL;
2013
    }
2014
}
2015

    
2016
void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
2017
{
2018
    struct capture_callback *cb;
2019

    
2020
    for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
2021
        if (cb->opaque == cb_opaque) {
2022
            cb->ops.destroy (cb_opaque);
2023
            QLIST_REMOVE (cb, entries);
2024
            qemu_free (cb);
2025

    
2026
            if (!cap->cb_head.lh_first) {
2027
                SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
2028

    
2029
                while (sw) {
2030
                    SWVoiceCap *sc = (SWVoiceCap *) sw;
2031
#ifdef DEBUG_CAPTURE
2032
                    dolog ("freeing %s\n", sw->name);
2033
#endif
2034

    
2035
                    sw1 = sw->entries.le_next;
2036
                    if (sw->rate) {
2037
                        st_rate_stop (sw->rate);
2038
                        sw->rate = NULL;
2039
                    }
2040
                    QLIST_REMOVE (sw, entries);
2041
                    QLIST_REMOVE (sc, entries);
2042
                    qemu_free (sc);
2043
                    sw = sw1;
2044
                }
2045
                QLIST_REMOVE (cap, entries);
2046
                qemu_free (cap);
2047
            }
2048
            return;
2049
        }
2050
    }
2051
}
2052

    
2053
void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
2054
{
2055
    if (sw) {
2056
        sw->vol.mute = mute;
2057
        sw->vol.l = nominal_volume.l * lvol / 255;
2058
        sw->vol.r = nominal_volume.r * rvol / 255;
2059
    }
2060
}
2061

    
2062
void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
2063
{
2064
    if (sw) {
2065
        sw->vol.mute = mute;
2066
        sw->vol.l = nominal_volume.l * lvol / 255;
2067
        sw->vol.r = nominal_volume.r * rvol / 255;
2068
    }
2069
}