Statistics
| Branch: | Revision:

root / audio / alsaaudio.c @ 301901b5

History | View | Annotate | Download (31.3 kB)

1
/*
2
 * QEMU ALSA audio driver
3
 *
4
 * Copyright (c) 2005 Vassili Karpov (malc)
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 */
24
#include <alsa/asoundlib.h>
25
#include "qemu-common.h"
26
#include "qemu-char.h"
27
#include "audio.h"
28

    
29
#if QEMU_GNUC_PREREQ(4, 3)
30
#pragma GCC diagnostic ignored "-Waddress"
31
#endif
32

    
33
#define AUDIO_CAP "alsa"
34
#include "audio_int.h"
35

    
36
struct pollhlp {
37
    snd_pcm_t *handle;
38
    struct pollfd *pfds;
39
    int count;
40
    int mask;
41
};
42

    
43
typedef struct ALSAVoiceOut {
44
    HWVoiceOut hw;
45
    int wpos;
46
    int pending;
47
    void *pcm_buf;
48
    snd_pcm_t *handle;
49
    struct pollhlp pollhlp;
50
} ALSAVoiceOut;
51

    
52
typedef struct ALSAVoiceIn {
53
    HWVoiceIn hw;
54
    snd_pcm_t *handle;
55
    void *pcm_buf;
56
    struct pollhlp pollhlp;
57
} ALSAVoiceIn;
58

    
59
static struct {
60
    int size_in_usec_in;
61
    int size_in_usec_out;
62
    const char *pcm_name_in;
63
    const char *pcm_name_out;
64
    unsigned int buffer_size_in;
65
    unsigned int period_size_in;
66
    unsigned int buffer_size_out;
67
    unsigned int period_size_out;
68
    unsigned int threshold;
69

    
70
    int buffer_size_in_overridden;
71
    int period_size_in_overridden;
72

    
73
    int buffer_size_out_overridden;
74
    int period_size_out_overridden;
75
    int verbose;
76
} conf = {
77
    .buffer_size_out = 1024,
78
    .pcm_name_out = "default",
79
    .pcm_name_in = "default",
80
};
81

    
82
struct alsa_params_req {
83
    int freq;
84
    snd_pcm_format_t fmt;
85
    int nchannels;
86
    int size_in_usec;
87
    int override_mask;
88
    unsigned int buffer_size;
89
    unsigned int period_size;
90
};
91

    
92
struct alsa_params_obt {
93
    int freq;
94
    audfmt_e fmt;
95
    int endianness;
96
    int nchannels;
97
    snd_pcm_uframes_t samples;
98
};
99

    
100
static void GCC_FMT_ATTR (2, 3) alsa_logerr (int err, const char *fmt, ...)
101
{
102
    va_list ap;
103

    
104
    va_start (ap, fmt);
105
    AUD_vlog (AUDIO_CAP, fmt, ap);
106
    va_end (ap);
107

    
108
    AUD_log (AUDIO_CAP, "Reason: %s\n", snd_strerror (err));
109
}
110

    
111
static void GCC_FMT_ATTR (3, 4) alsa_logerr2 (
112
    int err,
113
    const char *typ,
114
    const char *fmt,
115
    ...
116
    )
117
{
118
    va_list ap;
119

    
120
    AUD_log (AUDIO_CAP, "Could not initialize %s\n", typ);
121

    
122
    va_start (ap, fmt);
123
    AUD_vlog (AUDIO_CAP, fmt, ap);
124
    va_end (ap);
125

    
126
    AUD_log (AUDIO_CAP, "Reason: %s\n", snd_strerror (err));
127
}
128

    
129
static void alsa_fini_poll (struct pollhlp *hlp)
130
{
131
    int i;
132
    struct pollfd *pfds = hlp->pfds;
133

    
134
    if (pfds) {
135
        for (i = 0; i < hlp->count; ++i) {
136
            qemu_set_fd_handler (pfds[i].fd, NULL, NULL, NULL);
137
        }
138
        qemu_free (pfds);
139
    }
140
    hlp->pfds = NULL;
141
    hlp->count = 0;
142
    hlp->handle = NULL;
143
}
144

    
145
static void alsa_anal_close1 (snd_pcm_t **handlep)
146
{
147
    int err = snd_pcm_close (*handlep);
148
    if (err) {
149
        alsa_logerr (err, "Failed to close PCM handle %p\n", *handlep);
150
    }
151
    *handlep = NULL;
152
}
153

    
154
static void alsa_anal_close (snd_pcm_t **handlep, struct pollhlp *hlp)
155
{
156
    alsa_fini_poll (hlp);
157
    alsa_anal_close1 (handlep);
158
}
159

    
160
static int alsa_recover (snd_pcm_t *handle)
161
{
162
    int err = snd_pcm_prepare (handle);
163
    if (err < 0) {
164
        alsa_logerr (err, "Failed to prepare handle %p\n", handle);
165
        return -1;
166
    }
167
    return 0;
168
}
169

    
170
static int alsa_resume (snd_pcm_t *handle)
171
{
172
    int err = snd_pcm_resume (handle);
173
    if (err < 0) {
174
        alsa_logerr (err, "Failed to resume handle %p\n", handle);
175
        return -1;
176
    }
177
    return 0;
178
}
179

    
180
static void alsa_poll_handler (void *opaque)
181
{
182
    int err, count;
183
    snd_pcm_state_t state;
184
    struct pollhlp *hlp = opaque;
185
    unsigned short revents;
186

    
187
    count = poll (hlp->pfds, hlp->count, 0);
188
    if (count < 0) {
189
        dolog ("alsa_poll_handler: poll %s\n", strerror (errno));
190
        return;
191
    }
192

    
193
    if (!count) {
194
        return;
195
    }
196

    
197
    /* XXX: ALSA example uses initial count, not the one returned by
198
       poll, correct? */
199
    err = snd_pcm_poll_descriptors_revents (hlp->handle, hlp->pfds,
200
                                            hlp->count, &revents);
201
    if (err < 0) {
202
        alsa_logerr (err, "snd_pcm_poll_descriptors_revents");
203
        return;
204
    }
205

    
206
    if (!(revents & hlp->mask)) {
207
        if (conf.verbose) {
208
            dolog ("revents = %d\n", revents);
209
        }
210
        return;
211
    }
212

    
213
    state = snd_pcm_state (hlp->handle);
214
    switch (state) {
215
    case SND_PCM_STATE_XRUN:
216
        alsa_recover (hlp->handle);
217
        break;
218

    
219
    case SND_PCM_STATE_SUSPENDED:
220
        alsa_resume (hlp->handle);
221
        break;
222

    
223
    case SND_PCM_STATE_PREPARED:
224
        audio_run ("alsa run (prepared)");
225
        break;
226

    
227
    case SND_PCM_STATE_RUNNING:
228
        audio_run ("alsa run (running)");
229
        break;
230

    
231
    default:
232
        dolog ("Unexpected state %d\n", state);
233
    }
234
}
235

    
236
static int alsa_poll_helper (snd_pcm_t *handle, struct pollhlp *hlp, int mask)
237
{
238
    int i, count, err;
239
    struct pollfd *pfds;
240

    
241
    count = snd_pcm_poll_descriptors_count (handle);
242
    if (count <= 0) {
243
        dolog ("Could not initialize poll mode\n"
244
               "Invalid number of poll descriptors %d\n", count);
245
        return -1;
246
    }
247

    
248
    pfds = audio_calloc ("alsa_poll_helper", count, sizeof (*pfds));
249
    if (!pfds) {
250
        dolog ("Could not initialize poll mode\n");
251
        return -1;
252
    }
253

    
254
    err = snd_pcm_poll_descriptors (handle, pfds, count);
255
    if (err < 0) {
256
        alsa_logerr (err, "Could not initialize poll mode\n"
257
                     "Could not obtain poll descriptors\n");
258
        qemu_free (pfds);
259
        return -1;
260
    }
261

    
262
    for (i = 0; i < count; ++i) {
263
        if (pfds[i].events & POLLIN) {
264
            err = qemu_set_fd_handler (pfds[i].fd, alsa_poll_handler,
265
                                       NULL, hlp);
266
        }
267
        if (pfds[i].events & POLLOUT) {
268
            if (conf.verbose) {
269
                dolog ("POLLOUT %d %d\n", i, pfds[i].fd);
270
            }
271
            err = qemu_set_fd_handler (pfds[i].fd, NULL,
272
                                       alsa_poll_handler, hlp);
273
        }
274
        if (conf.verbose) {
275
            dolog ("Set handler events=%#x index=%d fd=%d err=%d\n",
276
                   pfds[i].events, i, pfds[i].fd, err);
277
        }
278

    
279
        if (err) {
280
            dolog ("Failed to set handler events=%#x index=%d fd=%d err=%d\n",
281
                   pfds[i].events, i, pfds[i].fd, err);
282

    
283
            while (i--) {
284
                qemu_set_fd_handler (pfds[i].fd, NULL, NULL, NULL);
285
            }
286
            qemu_free (pfds);
287
            return -1;
288
        }
289
    }
290
    hlp->pfds = pfds;
291
    hlp->count = count;
292
    hlp->handle = handle;
293
    hlp->mask = mask;
294
    return 0;
295
}
296

    
297
static int alsa_poll_out (HWVoiceOut *hw)
298
{
299
    ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
300

    
301
    return alsa_poll_helper (alsa->handle, &alsa->pollhlp, POLLOUT);
302
}
303

    
304
static int alsa_poll_in (HWVoiceIn *hw)
305
{
306
    ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
307

    
308
    return alsa_poll_helper (alsa->handle, &alsa->pollhlp, POLLIN);
309
}
310

    
311
static int alsa_write (SWVoiceOut *sw, void *buf, int len)
312
{
313
    return audio_pcm_sw_write (sw, buf, len);
314
}
315

    
316
static snd_pcm_format_t aud_to_alsafmt (audfmt_e fmt)
317
{
318
    switch (fmt) {
319
    case AUD_FMT_S8:
320
        return SND_PCM_FORMAT_S8;
321

    
322
    case AUD_FMT_U8:
323
        return SND_PCM_FORMAT_U8;
324

    
325
    case AUD_FMT_S16:
326
        return SND_PCM_FORMAT_S16_LE;
327

    
328
    case AUD_FMT_U16:
329
        return SND_PCM_FORMAT_U16_LE;
330

    
331
    case AUD_FMT_S32:
332
        return SND_PCM_FORMAT_S32_LE;
333

    
334
    case AUD_FMT_U32:
335
        return SND_PCM_FORMAT_U32_LE;
336

    
337
    default:
338
        dolog ("Internal logic error: Bad audio format %d\n", fmt);
339
#ifdef DEBUG_AUDIO
340
        abort ();
341
#endif
342
        return SND_PCM_FORMAT_U8;
343
    }
344
}
345

    
346
static int alsa_to_audfmt (snd_pcm_format_t alsafmt, audfmt_e *fmt,
347
                           int *endianness)
348
{
349
    switch (alsafmt) {
350
    case SND_PCM_FORMAT_S8:
351
        *endianness = 0;
352
        *fmt = AUD_FMT_S8;
353
        break;
354

    
355
    case SND_PCM_FORMAT_U8:
356
        *endianness = 0;
357
        *fmt = AUD_FMT_U8;
358
        break;
359

    
360
    case SND_PCM_FORMAT_S16_LE:
361
        *endianness = 0;
362
        *fmt = AUD_FMT_S16;
363
        break;
364

    
365
    case SND_PCM_FORMAT_U16_LE:
366
        *endianness = 0;
367
        *fmt = AUD_FMT_U16;
368
        break;
369

    
370
    case SND_PCM_FORMAT_S16_BE:
371
        *endianness = 1;
372
        *fmt = AUD_FMT_S16;
373
        break;
374

    
375
    case SND_PCM_FORMAT_U16_BE:
376
        *endianness = 1;
377
        *fmt = AUD_FMT_U16;
378
        break;
379

    
380
    case SND_PCM_FORMAT_S32_LE:
381
        *endianness = 0;
382
        *fmt = AUD_FMT_S32;
383
        break;
384

    
385
    case SND_PCM_FORMAT_U32_LE:
386
        *endianness = 0;
387
        *fmt = AUD_FMT_U32;
388
        break;
389

    
390
    case SND_PCM_FORMAT_S32_BE:
391
        *endianness = 1;
392
        *fmt = AUD_FMT_S32;
393
        break;
394

    
395
    case SND_PCM_FORMAT_U32_BE:
396
        *endianness = 1;
397
        *fmt = AUD_FMT_U32;
398
        break;
399

    
400
    default:
401
        dolog ("Unrecognized audio format %d\n", alsafmt);
402
        return -1;
403
    }
404

    
405
    return 0;
406
}
407

    
408
static void alsa_dump_info (struct alsa_params_req *req,
409
                            struct alsa_params_obt *obt)
410
{
411
    dolog ("parameter | requested value | obtained value\n");
412
    dolog ("format    |      %10d |     %10d\n", req->fmt, obt->fmt);
413
    dolog ("channels  |      %10d |     %10d\n",
414
           req->nchannels, obt->nchannels);
415
    dolog ("frequency |      %10d |     %10d\n", req->freq, obt->freq);
416
    dolog ("============================================\n");
417
    dolog ("requested: buffer size %d period size %d\n",
418
           req->buffer_size, req->period_size);
419
    dolog ("obtained: samples %ld\n", obt->samples);
420
}
421

    
422
static void alsa_set_threshold (snd_pcm_t *handle, snd_pcm_uframes_t threshold)
423
{
424
    int err;
425
    snd_pcm_sw_params_t *sw_params;
426

    
427
    snd_pcm_sw_params_alloca (&sw_params);
428

    
429
    err = snd_pcm_sw_params_current (handle, sw_params);
430
    if (err < 0) {
431
        dolog ("Could not fully initialize DAC\n");
432
        alsa_logerr (err, "Failed to get current software parameters\n");
433
        return;
434
    }
435

    
436
    err = snd_pcm_sw_params_set_start_threshold (handle, sw_params, threshold);
437
    if (err < 0) {
438
        dolog ("Could not fully initialize DAC\n");
439
        alsa_logerr (err, "Failed to set software threshold to %ld\n",
440
                     threshold);
441
        return;
442
    }
443

    
444
    err = snd_pcm_sw_params (handle, sw_params);
445
    if (err < 0) {
446
        dolog ("Could not fully initialize DAC\n");
447
        alsa_logerr (err, "Failed to set software parameters\n");
448
        return;
449
    }
450
}
451

    
452
static int alsa_open (int in, struct alsa_params_req *req,
453
                      struct alsa_params_obt *obt, snd_pcm_t **handlep)
454
{
455
    snd_pcm_t *handle;
456
    snd_pcm_hw_params_t *hw_params;
457
    int err;
458
    int size_in_usec;
459
    unsigned int freq, nchannels;
460
    const char *pcm_name = in ? conf.pcm_name_in : conf.pcm_name_out;
461
    snd_pcm_uframes_t obt_buffer_size;
462
    const char *typ = in ? "ADC" : "DAC";
463
    snd_pcm_format_t obtfmt;
464

    
465
    freq = req->freq;
466
    nchannels = req->nchannels;
467
    size_in_usec = req->size_in_usec;
468

    
469
    snd_pcm_hw_params_alloca (&hw_params);
470

    
471
    err = snd_pcm_open (
472
        &handle,
473
        pcm_name,
474
        in ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
475
        SND_PCM_NONBLOCK
476
        );
477
    if (err < 0) {
478
        alsa_logerr2 (err, typ, "Failed to open `%s':\n", pcm_name);
479
        return -1;
480
    }
481

    
482
    err = snd_pcm_hw_params_any (handle, hw_params);
483
    if (err < 0) {
484
        alsa_logerr2 (err, typ, "Failed to initialize hardware parameters\n");
485
        goto err;
486
    }
487

    
488
    err = snd_pcm_hw_params_set_access (
489
        handle,
490
        hw_params,
491
        SND_PCM_ACCESS_RW_INTERLEAVED
492
        );
493
    if (err < 0) {
494
        alsa_logerr2 (err, typ, "Failed to set access type\n");
495
        goto err;
496
    }
497

    
498
    err = snd_pcm_hw_params_set_format (handle, hw_params, req->fmt);
499
    if (err < 0 && conf.verbose) {
500
        alsa_logerr2 (err, typ, "Failed to set format %d\n", req->fmt);
501
    }
502

    
503
    err = snd_pcm_hw_params_set_rate_near (handle, hw_params, &freq, 0);
504
    if (err < 0) {
505
        alsa_logerr2 (err, typ, "Failed to set frequency %d\n", req->freq);
506
        goto err;
507
    }
508

    
509
    err = snd_pcm_hw_params_set_channels_near (
510
        handle,
511
        hw_params,
512
        &nchannels
513
        );
514
    if (err < 0) {
515
        alsa_logerr2 (err, typ, "Failed to set number of channels %d\n",
516
                      req->nchannels);
517
        goto err;
518
    }
519

    
520
    if (nchannels != 1 && nchannels != 2) {
521
        alsa_logerr2 (err, typ,
522
                      "Can not handle obtained number of channels %d\n",
523
                      nchannels);
524
        goto err;
525
    }
526

    
527
    if (req->buffer_size) {
528
        unsigned long obt;
529

    
530
        if (size_in_usec) {
531
            int dir = 0;
532
            unsigned int btime = req->buffer_size;
533

    
534
            err = snd_pcm_hw_params_set_buffer_time_near (
535
                handle,
536
                hw_params,
537
                &btime,
538
                &dir
539
                );
540
            obt = btime;
541
        }
542
        else {
543
            snd_pcm_uframes_t bsize = req->buffer_size;
544

    
545
            err = snd_pcm_hw_params_set_buffer_size_near (
546
                handle,
547
                hw_params,
548
                &bsize
549
                );
550
            obt = bsize;
551
        }
552
        if (err < 0) {
553
            alsa_logerr2 (err, typ, "Failed to set buffer %s to %d\n",
554
                          size_in_usec ? "time" : "size", req->buffer_size);
555
            goto err;
556
        }
557

    
558
        if ((req->override_mask & 2) && (obt - req->buffer_size))
559
            dolog ("Requested buffer %s %u was rejected, using %lu\n",
560
                   size_in_usec ? "time" : "size", req->buffer_size, obt);
561
    }
562

    
563
    if (req->period_size) {
564
        unsigned long obt;
565

    
566
        if (size_in_usec) {
567
            int dir = 0;
568
            unsigned int ptime = req->period_size;
569

    
570
            err = snd_pcm_hw_params_set_period_time_near (
571
                handle,
572
                hw_params,
573
                &ptime,
574
                &dir
575
                );
576
            obt = ptime;
577
        }
578
        else {
579
            int dir = 0;
580
            snd_pcm_uframes_t psize = req->period_size;
581

    
582
            err = snd_pcm_hw_params_set_period_size_near (
583
                handle,
584
                hw_params,
585
                &psize,
586
                &dir
587
                );
588
            obt = psize;
589
        }
590

    
591
        if (err < 0) {
592
            alsa_logerr2 (err, typ, "Failed to set period %s to %d\n",
593
                          size_in_usec ? "time" : "size", req->period_size);
594
            goto err;
595
        }
596

    
597
        if (((req->override_mask & 1) && (obt - req->period_size)))
598
            dolog ("Requested period %s %u was rejected, using %lu\n",
599
                   size_in_usec ? "time" : "size", req->period_size, obt);
600
    }
601

    
602
    err = snd_pcm_hw_params (handle, hw_params);
603
    if (err < 0) {
604
        alsa_logerr2 (err, typ, "Failed to apply audio parameters\n");
605
        goto err;
606
    }
607

    
608
    err = snd_pcm_hw_params_get_buffer_size (hw_params, &obt_buffer_size);
609
    if (err < 0) {
610
        alsa_logerr2 (err, typ, "Failed to get buffer size\n");
611
        goto err;
612
    }
613

    
614
    err = snd_pcm_hw_params_get_format (hw_params, &obtfmt);
615
    if (err < 0) {
616
        alsa_logerr2 (err, typ, "Failed to get format\n");
617
        goto err;
618
    }
619

    
620
    if (alsa_to_audfmt (obtfmt, &obt->fmt, &obt->endianness)) {
621
        dolog ("Invalid format was returned %d\n", obtfmt);
622
        goto err;
623
    }
624

    
625
    err = snd_pcm_prepare (handle);
626
    if (err < 0) {
627
        alsa_logerr2 (err, typ, "Could not prepare handle %p\n", handle);
628
        goto err;
629
    }
630

    
631
    if (!in && conf.threshold) {
632
        snd_pcm_uframes_t threshold;
633
        int bytes_per_sec;
634

    
635
        bytes_per_sec = freq << (nchannels == 2);
636

    
637
        switch (obt->fmt) {
638
        case AUD_FMT_S8:
639
        case AUD_FMT_U8:
640
            break;
641

    
642
        case AUD_FMT_S16:
643
        case AUD_FMT_U16:
644
            bytes_per_sec <<= 1;
645
            break;
646

    
647
        case AUD_FMT_S32:
648
        case AUD_FMT_U32:
649
            bytes_per_sec <<= 2;
650
            break;
651
        }
652

    
653
        threshold = (conf.threshold * bytes_per_sec) / 1000;
654
        alsa_set_threshold (handle, threshold);
655
    }
656

    
657
    obt->nchannels = nchannels;
658
    obt->freq = freq;
659
    obt->samples = obt_buffer_size;
660

    
661
    *handlep = handle;
662

    
663
    if (conf.verbose &&
664
        (obt->fmt != req->fmt ||
665
         obt->nchannels != req->nchannels ||
666
         obt->freq != req->freq)) {
667
        dolog ("Audio paramters for %s\n", typ);
668
        alsa_dump_info (req, obt);
669
    }
670

    
671
#ifdef DEBUG
672
    alsa_dump_info (req, obt);
673
#endif
674
    return 0;
675

    
676
 err:
677
    alsa_anal_close1 (&handle);
678
    return -1;
679
}
680

    
681
static snd_pcm_sframes_t alsa_get_avail (snd_pcm_t *handle)
682
{
683
    snd_pcm_sframes_t avail;
684

    
685
    avail = snd_pcm_avail_update (handle);
686
    if (avail < 0) {
687
        if (avail == -EPIPE) {
688
            if (!alsa_recover (handle)) {
689
                avail = snd_pcm_avail_update (handle);
690
            }
691
        }
692

    
693
        if (avail < 0) {
694
            alsa_logerr (avail,
695
                         "Could not obtain number of available frames\n");
696
            return -1;
697
        }
698
    }
699

    
700
    return avail;
701
}
702

    
703
static void alsa_write_pending (ALSAVoiceOut *alsa)
704
{
705
    HWVoiceOut *hw = &alsa->hw;
706

    
707
    while (alsa->pending) {
708
        int left_till_end_samples = hw->samples - alsa->wpos;
709
        int len = audio_MIN (alsa->pending, left_till_end_samples);
710
        char *src = advance (alsa->pcm_buf, alsa->wpos << hw->info.shift);
711

    
712
        while (len) {
713
            snd_pcm_sframes_t written;
714

    
715
            written = snd_pcm_writei (alsa->handle, src, len);
716

    
717
            if (written <= 0) {
718
                switch (written) {
719
                case 0:
720
                    if (conf.verbose) {
721
                        dolog ("Failed to write %d frames (wrote zero)\n", len);
722
                    }
723
                    return;
724

    
725
                case -EPIPE:
726
                    if (alsa_recover (alsa->handle)) {
727
                        alsa_logerr (written, "Failed to write %d frames\n",
728
                                     len);
729
                        return;
730
                    }
731
                    if (conf.verbose) {
732
                        dolog ("Recovering from playback xrun\n");
733
                    }
734
                    continue;
735

    
736
                case -ESTRPIPE:
737
                    /* stream is suspended and waiting for an
738
                       application recovery */
739
                    if (alsa_resume (alsa->handle)) {
740
                        alsa_logerr (written, "Failed to write %d frames\n",
741
                                     len);
742
                        return;
743
                    }
744
                    if (conf.verbose) {
745
                        dolog ("Resuming suspended output stream\n");
746
                    }
747
                    continue;
748

    
749
                case -EAGAIN:
750
                    return;
751

    
752
                default:
753
                    alsa_logerr (written, "Failed to write %d frames from %p\n",
754
                                 len, src);
755
                    return;
756
                }
757
            }
758

    
759
            alsa->wpos = (alsa->wpos + written) % hw->samples;
760
            alsa->pending -= written;
761
            len -= written;
762
        }
763
    }
764
}
765

    
766
static int alsa_run_out (HWVoiceOut *hw, int live)
767
{
768
    ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
769
    int decr;
770
    snd_pcm_sframes_t avail;
771

    
772
    avail = alsa_get_avail (alsa->handle);
773
    if (avail < 0) {
774
        dolog ("Could not get number of available playback frames\n");
775
        return 0;
776
    }
777

    
778
    decr = audio_MIN (live, avail);
779
    decr = audio_pcm_hw_clip_out (hw, alsa->pcm_buf, decr, alsa->pending);
780
    alsa->pending += decr;
781
    alsa_write_pending (alsa);
782
    return decr;
783
}
784

    
785
static void alsa_fini_out (HWVoiceOut *hw)
786
{
787
    ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
788

    
789
    ldebug ("alsa_fini\n");
790
    alsa_anal_close (&alsa->handle, &alsa->pollhlp);
791

    
792
    if (alsa->pcm_buf) {
793
        qemu_free (alsa->pcm_buf);
794
        alsa->pcm_buf = NULL;
795
    }
796
}
797

    
798
static int alsa_init_out (HWVoiceOut *hw, struct audsettings *as)
799
{
800
    ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
801
    struct alsa_params_req req;
802
    struct alsa_params_obt obt;
803
    snd_pcm_t *handle;
804
    struct audsettings obt_as;
805

    
806
    req.fmt = aud_to_alsafmt (as->fmt);
807
    req.freq = as->freq;
808
    req.nchannels = as->nchannels;
809
    req.period_size = conf.period_size_out;
810
    req.buffer_size = conf.buffer_size_out;
811
    req.size_in_usec = conf.size_in_usec_out;
812
    req.override_mask =
813
        (conf.period_size_out_overridden ? 1 : 0) |
814
        (conf.buffer_size_out_overridden ? 2 : 0);
815

    
816
    if (alsa_open (0, &req, &obt, &handle)) {
817
        return -1;
818
    }
819

    
820
    obt_as.freq = obt.freq;
821
    obt_as.nchannels = obt.nchannels;
822
    obt_as.fmt = obt.fmt;
823
    obt_as.endianness = obt.endianness;
824

    
825
    audio_pcm_init_info (&hw->info, &obt_as);
826
    hw->samples = obt.samples;
827

    
828
    alsa->pcm_buf = audio_calloc (AUDIO_FUNC, obt.samples, 1 << hw->info.shift);
829
    if (!alsa->pcm_buf) {
830
        dolog ("Could not allocate DAC buffer (%d samples, each %d bytes)\n",
831
               hw->samples, 1 << hw->info.shift);
832
        alsa_anal_close1 (&handle);
833
        return -1;
834
    }
835

    
836
    alsa->handle = handle;
837
    return 0;
838
}
839

    
840
static int alsa_voice_ctl (snd_pcm_t *handle, const char *typ, int pause)
841
{
842
    int err;
843

    
844
    if (pause) {
845
        err = snd_pcm_drop (handle);
846
        if (err < 0) {
847
            alsa_logerr (err, "Could not stop %s\n", typ);
848
            return -1;
849
        }
850
    }
851
    else {
852
        err = snd_pcm_prepare (handle);
853
        if (err < 0) {
854
            alsa_logerr (err, "Could not prepare handle for %s\n", typ);
855
            return -1;
856
        }
857
    }
858

    
859
    return 0;
860
}
861

    
862
static int alsa_ctl_out (HWVoiceOut *hw, int cmd, ...)
863
{
864
    ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
865

    
866
    switch (cmd) {
867
    case VOICE_ENABLE:
868
        {
869
            va_list ap;
870
            int poll_mode;
871

    
872
            va_start (ap, cmd);
873
            poll_mode = va_arg (ap, int);
874
            va_end (ap);
875

    
876
            ldebug ("enabling voice\n");
877
            if (poll_mode && alsa_poll_out (hw)) {
878
                poll_mode = 0;
879
            }
880
            hw->poll_mode = poll_mode;
881
            return alsa_voice_ctl (alsa->handle, "playback", 0);
882
        }
883

    
884
    case VOICE_DISABLE:
885
        ldebug ("disabling voice\n");
886
        return alsa_voice_ctl (alsa->handle, "playback", 1);
887
    }
888

    
889
    return -1;
890
}
891

    
892
static int alsa_init_in (HWVoiceIn *hw, struct audsettings *as)
893
{
894
    ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
895
    struct alsa_params_req req;
896
    struct alsa_params_obt obt;
897
    snd_pcm_t *handle;
898
    struct audsettings obt_as;
899

    
900
    req.fmt = aud_to_alsafmt (as->fmt);
901
    req.freq = as->freq;
902
    req.nchannels = as->nchannels;
903
    req.period_size = conf.period_size_in;
904
    req.buffer_size = conf.buffer_size_in;
905
    req.size_in_usec = conf.size_in_usec_in;
906
    req.override_mask =
907
        (conf.period_size_in_overridden ? 1 : 0) |
908
        (conf.buffer_size_in_overridden ? 2 : 0);
909

    
910
    if (alsa_open (1, &req, &obt, &handle)) {
911
        return -1;
912
    }
913

    
914
    obt_as.freq = obt.freq;
915
    obt_as.nchannels = obt.nchannels;
916
    obt_as.fmt = obt.fmt;
917
    obt_as.endianness = obt.endianness;
918

    
919
    audio_pcm_init_info (&hw->info, &obt_as);
920
    hw->samples = obt.samples;
921

    
922
    alsa->pcm_buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift);
923
    if (!alsa->pcm_buf) {
924
        dolog ("Could not allocate ADC buffer (%d samples, each %d bytes)\n",
925
               hw->samples, 1 << hw->info.shift);
926
        alsa_anal_close1 (&handle);
927
        return -1;
928
    }
929

    
930
    alsa->handle = handle;
931
    return 0;
932
}
933

    
934
static void alsa_fini_in (HWVoiceIn *hw)
935
{
936
    ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
937

    
938
    alsa_anal_close (&alsa->handle, &alsa->pollhlp);
939

    
940
    if (alsa->pcm_buf) {
941
        qemu_free (alsa->pcm_buf);
942
        alsa->pcm_buf = NULL;
943
    }
944
}
945

    
946
static int alsa_run_in (HWVoiceIn *hw)
947
{
948
    ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
949
    int hwshift = hw->info.shift;
950
    int i;
951
    int live = audio_pcm_hw_get_live_in (hw);
952
    int dead = hw->samples - live;
953
    int decr;
954
    struct {
955
        int add;
956
        int len;
957
    } bufs[2] = {
958
        { .add = hw->wpos, .len = 0 },
959
        { .add = 0,        .len = 0 }
960
    };
961
    snd_pcm_sframes_t avail;
962
    snd_pcm_uframes_t read_samples = 0;
963

    
964
    if (!dead) {
965
        return 0;
966
    }
967

    
968
    avail = alsa_get_avail (alsa->handle);
969
    if (avail < 0) {
970
        dolog ("Could not get number of captured frames\n");
971
        return 0;
972
    }
973

    
974
    if (!avail) {
975
        snd_pcm_state_t state;
976

    
977
        state = snd_pcm_state (alsa->handle);
978
        switch (state) {
979
        case SND_PCM_STATE_PREPARED:
980
            avail = hw->samples;
981
            break;
982
        case SND_PCM_STATE_SUSPENDED:
983
            /* stream is suspended and waiting for an application recovery */
984
            if (alsa_resume (alsa->handle)) {
985
                dolog ("Failed to resume suspended input stream\n");
986
                return 0;
987
            }
988
            if (conf.verbose) {
989
                dolog ("Resuming suspended input stream\n");
990
            }
991
            break;
992
        default:
993
            if (conf.verbose) {
994
                dolog ("No frames available and ALSA state is %d\n", state);
995
            }
996
            return 0;
997
        }
998
    }
999

    
1000
    decr = audio_MIN (dead, avail);
1001
    if (!decr) {
1002
        return 0;
1003
    }
1004

    
1005
    if (hw->wpos + decr > hw->samples) {
1006
        bufs[0].len = (hw->samples - hw->wpos);
1007
        bufs[1].len = (decr - (hw->samples - hw->wpos));
1008
    }
1009
    else {
1010
        bufs[0].len = decr;
1011
    }
1012

    
1013
    for (i = 0; i < 2; ++i) {
1014
        void *src;
1015
        struct st_sample *dst;
1016
        snd_pcm_sframes_t nread;
1017
        snd_pcm_uframes_t len;
1018

    
1019
        len = bufs[i].len;
1020

    
1021
        src = advance (alsa->pcm_buf, bufs[i].add << hwshift);
1022
        dst = hw->conv_buf + bufs[i].add;
1023

    
1024
        while (len) {
1025
            nread = snd_pcm_readi (alsa->handle, src, len);
1026

    
1027
            if (nread <= 0) {
1028
                switch (nread) {
1029
                case 0:
1030
                    if (conf.verbose) {
1031
                        dolog ("Failed to read %ld frames (read zero)\n", len);
1032
                    }
1033
                    goto exit;
1034

    
1035
                case -EPIPE:
1036
                    if (alsa_recover (alsa->handle)) {
1037
                        alsa_logerr (nread, "Failed to read %ld frames\n", len);
1038
                        goto exit;
1039
                    }
1040
                    if (conf.verbose) {
1041
                        dolog ("Recovering from capture xrun\n");
1042
                    }
1043
                    continue;
1044

    
1045
                case -EAGAIN:
1046
                    goto exit;
1047

    
1048
                default:
1049
                    alsa_logerr (
1050
                        nread,
1051
                        "Failed to read %ld frames from %p\n",
1052
                        len,
1053
                        src
1054
                        );
1055
                    goto exit;
1056
                }
1057
            }
1058

    
1059
            hw->conv (dst, src, nread, &nominal_volume);
1060

    
1061
            src = advance (src, nread << hwshift);
1062
            dst += nread;
1063

    
1064
            read_samples += nread;
1065
            len -= nread;
1066
        }
1067
    }
1068

    
1069
 exit:
1070
    hw->wpos = (hw->wpos + read_samples) % hw->samples;
1071
    return read_samples;
1072
}
1073

    
1074
static int alsa_read (SWVoiceIn *sw, void *buf, int size)
1075
{
1076
    return audio_pcm_sw_read (sw, buf, size);
1077
}
1078

    
1079
static int alsa_ctl_in (HWVoiceIn *hw, int cmd, ...)
1080
{
1081
    va_list ap;
1082
    int poll_mode;
1083
    ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
1084

    
1085
    va_start (ap, cmd);
1086
    poll_mode = va_arg (ap, int);
1087
    va_end (ap);
1088

    
1089
    switch (cmd) {
1090
    case VOICE_ENABLE:
1091
        ldebug ("enabling voice\n");
1092
        if (poll_mode && alsa_poll_in (hw)) {
1093
            poll_mode = 0;
1094
        }
1095
        hw->poll_mode = poll_mode;
1096

    
1097
        return alsa_voice_ctl (alsa->handle, "capture", 0);
1098

    
1099
    case VOICE_DISABLE:
1100
        ldebug ("disabling voice\n");
1101
        if (hw->poll_mode) {
1102
            hw->poll_mode = 0;
1103
            alsa_fini_poll (&alsa->pollhlp);
1104
        }
1105
        return alsa_voice_ctl (alsa->handle, "capture", 1);
1106
    }
1107

    
1108
    return -1;
1109
}
1110

    
1111
static void *alsa_audio_init (void)
1112
{
1113
    return &conf;
1114
}
1115

    
1116
static void alsa_audio_fini (void *opaque)
1117
{
1118
    (void) opaque;
1119
}
1120

    
1121
static struct audio_option alsa_options[] = {
1122
    {
1123
        .name        = "DAC_SIZE_IN_USEC",
1124
        .tag         = AUD_OPT_BOOL,
1125
        .valp        = &conf.size_in_usec_out,
1126
        .descr       = "DAC period/buffer size in microseconds (otherwise in frames)"
1127
    },
1128
    {
1129
        .name        = "DAC_PERIOD_SIZE",
1130
        .tag         = AUD_OPT_INT,
1131
        .valp        = &conf.period_size_out,
1132
        .descr       = "DAC period size (0 to go with system default)",
1133
        .overriddenp = &conf.period_size_out_overridden
1134
    },
1135
    {
1136
        .name        = "DAC_BUFFER_SIZE",
1137
        .tag         = AUD_OPT_INT,
1138
        .valp        = &conf.buffer_size_out,
1139
        .descr       = "DAC buffer size (0 to go with system default)",
1140
        .overriddenp = &conf.buffer_size_out_overridden
1141
    },
1142
    {
1143
        .name        = "ADC_SIZE_IN_USEC",
1144
        .tag         = AUD_OPT_BOOL,
1145
        .valp        = &conf.size_in_usec_in,
1146
        .descr       =
1147
        "ADC period/buffer size in microseconds (otherwise in frames)"
1148
    },
1149
    {
1150
        .name        = "ADC_PERIOD_SIZE",
1151
        .tag         = AUD_OPT_INT,
1152
        .valp        = &conf.period_size_in,
1153
        .descr       = "ADC period size (0 to go with system default)",
1154
        .overriddenp = &conf.period_size_in_overridden
1155
    },
1156
    {
1157
        .name        = "ADC_BUFFER_SIZE",
1158
        .tag         = AUD_OPT_INT,
1159
        .valp        = &conf.buffer_size_in,
1160
        .descr       = "ADC buffer size (0 to go with system default)",
1161
        .overriddenp = &conf.buffer_size_in_overridden
1162
    },
1163
    {
1164
        .name        = "THRESHOLD",
1165
        .tag         = AUD_OPT_INT,
1166
        .valp        = &conf.threshold,
1167
        .descr       = "(undocumented)"
1168
    },
1169
    {
1170
        .name        = "DAC_DEV",
1171
        .tag         = AUD_OPT_STR,
1172
        .valp        = &conf.pcm_name_out,
1173
        .descr       = "DAC device name (for instance dmix)"
1174
    },
1175
    {
1176
        .name        = "ADC_DEV",
1177
        .tag         = AUD_OPT_STR,
1178
        .valp        = &conf.pcm_name_in,
1179
        .descr       = "ADC device name"
1180
    },
1181
    {
1182
        .name        = "VERBOSE",
1183
        .tag         = AUD_OPT_BOOL,
1184
        .valp        = &conf.verbose,
1185
        .descr       = "Behave in a more verbose way"
1186
    },
1187
    { /* End of list */ }
1188
};
1189

    
1190
static struct audio_pcm_ops alsa_pcm_ops = {
1191
    .init_out = alsa_init_out,
1192
    .fini_out = alsa_fini_out,
1193
    .run_out  = alsa_run_out,
1194
    .write    = alsa_write,
1195
    .ctl_out  = alsa_ctl_out,
1196

    
1197
    .init_in  = alsa_init_in,
1198
    .fini_in  = alsa_fini_in,
1199
    .run_in   = alsa_run_in,
1200
    .read     = alsa_read,
1201
    .ctl_in   = alsa_ctl_in,
1202
};
1203

    
1204
struct audio_driver alsa_audio_driver = {
1205
    .name           = "alsa",
1206
    .descr          = "ALSA http://www.alsa-project.org",
1207
    .options        = alsa_options,
1208
    .init           = alsa_audio_init,
1209
    .fini           = alsa_audio_fini,
1210
    .pcm_ops        = &alsa_pcm_ops,
1211
    .can_be_default = 1,
1212
    .max_voices_out = INT_MAX,
1213
    .max_voices_in  = INT_MAX,
1214
    .voice_size_out = sizeof (ALSAVoiceOut),
1215
    .voice_size_in  = sizeof (ALSAVoiceIn)
1216
};