Statistics
| Branch: | Revision:

root / audio / alsaaudio.c @ d9812b03

History | View | Annotate | Download (31.5 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 = 4096,
78
    .period_size_out = 1024,
79
    .pcm_name_out = "default",
80
    .pcm_name_in = "default",
81
};
82

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
220
    case SND_PCM_STATE_XRUN:
221
        alsa_recover (hlp->handle);
222
        break;
223

    
224
    case SND_PCM_STATE_SUSPENDED:
225
        alsa_resume (hlp->handle);
226
        break;
227

    
228
    case SND_PCM_STATE_PREPARED:
229
        audio_run ("alsa run (prepared)");
230
        break;
231

    
232
    case SND_PCM_STATE_RUNNING:
233
        audio_run ("alsa run (running)");
234
        break;
235

    
236
    default:
237
        dolog ("Unexpected state %d\n", state);
238
    }
239
}
240

    
241
static int alsa_poll_helper (snd_pcm_t *handle, struct pollhlp *hlp, int mask)
242
{
243
    int i, count, err;
244
    struct pollfd *pfds;
245

    
246
    count = snd_pcm_poll_descriptors_count (handle);
247
    if (count <= 0) {
248
        dolog ("Could not initialize poll mode\n"
249
               "Invalid number of poll descriptors %d\n", count);
250
        return -1;
251
    }
252

    
253
    pfds = audio_calloc ("alsa_poll_helper", count, sizeof (*pfds));
254
    if (!pfds) {
255
        dolog ("Could not initialize poll mode\n");
256
        return -1;
257
    }
258

    
259
    err = snd_pcm_poll_descriptors (handle, pfds, count);
260
    if (err < 0) {
261
        alsa_logerr (err, "Could not initialize poll mode\n"
262
                     "Could not obtain poll descriptors\n");
263
        qemu_free (pfds);
264
        return -1;
265
    }
266

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

    
284
        if (err) {
285
            dolog ("Failed to set handler events=%#x index=%d fd=%d err=%d\n",
286
                   pfds[i].events, i, pfds[i].fd, err);
287

    
288
            while (i--) {
289
                qemu_set_fd_handler (pfds[i].fd, NULL, NULL, NULL);
290
            }
291
            qemu_free (pfds);
292
            return -1;
293
        }
294
    }
295
    hlp->pfds = pfds;
296
    hlp->count = count;
297
    hlp->handle = handle;
298
    hlp->mask = mask;
299
    return 0;
300
}
301

    
302
static int alsa_poll_out (HWVoiceOut *hw)
303
{
304
    ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
305

    
306
    return alsa_poll_helper (alsa->handle, &alsa->pollhlp, POLLOUT);
307
}
308

    
309
static int alsa_poll_in (HWVoiceIn *hw)
310
{
311
    ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
312

    
313
    return alsa_poll_helper (alsa->handle, &alsa->pollhlp, POLLIN);
314
}
315

    
316
static int alsa_write (SWVoiceOut *sw, void *buf, int len)
317
{
318
    return audio_pcm_sw_write (sw, buf, len);
319
}
320

    
321
static snd_pcm_format_t aud_to_alsafmt (audfmt_e fmt)
322
{
323
    switch (fmt) {
324
    case AUD_FMT_S8:
325
        return SND_PCM_FORMAT_S8;
326

    
327
    case AUD_FMT_U8:
328
        return SND_PCM_FORMAT_U8;
329

    
330
    case AUD_FMT_S16:
331
        return SND_PCM_FORMAT_S16_LE;
332

    
333
    case AUD_FMT_U16:
334
        return SND_PCM_FORMAT_U16_LE;
335

    
336
    case AUD_FMT_S32:
337
        return SND_PCM_FORMAT_S32_LE;
338

    
339
    case AUD_FMT_U32:
340
        return SND_PCM_FORMAT_U32_LE;
341

    
342
    default:
343
        dolog ("Internal logic error: Bad audio format %d\n", fmt);
344
#ifdef DEBUG_AUDIO
345
        abort ();
346
#endif
347
        return SND_PCM_FORMAT_U8;
348
    }
349
}
350

    
351
static int alsa_to_audfmt (snd_pcm_format_t alsafmt, audfmt_e *fmt,
352
                           int *endianness)
353
{
354
    switch (alsafmt) {
355
    case SND_PCM_FORMAT_S8:
356
        *endianness = 0;
357
        *fmt = AUD_FMT_S8;
358
        break;
359

    
360
    case SND_PCM_FORMAT_U8:
361
        *endianness = 0;
362
        *fmt = AUD_FMT_U8;
363
        break;
364

    
365
    case SND_PCM_FORMAT_S16_LE:
366
        *endianness = 0;
367
        *fmt = AUD_FMT_S16;
368
        break;
369

    
370
    case SND_PCM_FORMAT_U16_LE:
371
        *endianness = 0;
372
        *fmt = AUD_FMT_U16;
373
        break;
374

    
375
    case SND_PCM_FORMAT_S16_BE:
376
        *endianness = 1;
377
        *fmt = AUD_FMT_S16;
378
        break;
379

    
380
    case SND_PCM_FORMAT_U16_BE:
381
        *endianness = 1;
382
        *fmt = AUD_FMT_U16;
383
        break;
384

    
385
    case SND_PCM_FORMAT_S32_LE:
386
        *endianness = 0;
387
        *fmt = AUD_FMT_S32;
388
        break;
389

    
390
    case SND_PCM_FORMAT_U32_LE:
391
        *endianness = 0;
392
        *fmt = AUD_FMT_U32;
393
        break;
394

    
395
    case SND_PCM_FORMAT_S32_BE:
396
        *endianness = 1;
397
        *fmt = AUD_FMT_S32;
398
        break;
399

    
400
    case SND_PCM_FORMAT_U32_BE:
401
        *endianness = 1;
402
        *fmt = AUD_FMT_U32;
403
        break;
404

    
405
    default:
406
        dolog ("Unrecognized audio format %d\n", alsafmt);
407
        return -1;
408
    }
409

    
410
    return 0;
411
}
412

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

    
427
static void alsa_set_threshold (snd_pcm_t *handle, snd_pcm_uframes_t threshold)
428
{
429
    int err;
430
    snd_pcm_sw_params_t *sw_params;
431

    
432
    snd_pcm_sw_params_alloca (&sw_params);
433

    
434
    err = snd_pcm_sw_params_current (handle, sw_params);
435
    if (err < 0) {
436
        dolog ("Could not fully initialize DAC\n");
437
        alsa_logerr (err, "Failed to get current software parameters\n");
438
        return;
439
    }
440

    
441
    err = snd_pcm_sw_params_set_start_threshold (handle, sw_params, threshold);
442
    if (err < 0) {
443
        dolog ("Could not fully initialize DAC\n");
444
        alsa_logerr (err, "Failed to set software threshold to %ld\n",
445
                     threshold);
446
        return;
447
    }
448

    
449
    err = snd_pcm_sw_params (handle, sw_params);
450
    if (err < 0) {
451
        dolog ("Could not fully initialize DAC\n");
452
        alsa_logerr (err, "Failed to set software parameters\n");
453
        return;
454
    }
455
}
456

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

    
470
    freq = req->freq;
471
    nchannels = req->nchannels;
472
    size_in_usec = req->size_in_usec;
473

    
474
    snd_pcm_hw_params_alloca (&hw_params);
475

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

    
487
    err = snd_pcm_hw_params_any (handle, hw_params);
488
    if (err < 0) {
489
        alsa_logerr2 (err, typ, "Failed to initialize hardware parameters\n");
490
        goto err;
491
    }
492

    
493
    err = snd_pcm_hw_params_set_access (
494
        handle,
495
        hw_params,
496
        SND_PCM_ACCESS_RW_INTERLEAVED
497
        );
498
    if (err < 0) {
499
        alsa_logerr2 (err, typ, "Failed to set access type\n");
500
        goto err;
501
    }
502

    
503
    err = snd_pcm_hw_params_set_format (handle, hw_params, req->fmt);
504
    if (err < 0 && conf.verbose) {
505
        alsa_logerr2 (err, typ, "Failed to set format %d\n", req->fmt);
506
    }
507

    
508
    err = snd_pcm_hw_params_set_rate_near (handle, hw_params, &freq, 0);
509
    if (err < 0) {
510
        alsa_logerr2 (err, typ, "Failed to set frequency %d\n", req->freq);
511
        goto err;
512
    }
513

    
514
    err = snd_pcm_hw_params_set_channels_near (
515
        handle,
516
        hw_params,
517
        &nchannels
518
        );
519
    if (err < 0) {
520
        alsa_logerr2 (err, typ, "Failed to set number of channels %d\n",
521
                      req->nchannels);
522
        goto err;
523
    }
524

    
525
    if (nchannels != 1 && nchannels != 2) {
526
        alsa_logerr2 (err, typ,
527
                      "Can not handle obtained number of channels %d\n",
528
                      nchannels);
529
        goto err;
530
    }
531

    
532
    if (req->buffer_size) {
533
        unsigned long obt;
534

    
535
        if (size_in_usec) {
536
            int dir = 0;
537
            unsigned int btime = req->buffer_size;
538

    
539
            err = snd_pcm_hw_params_set_buffer_time_near (
540
                handle,
541
                hw_params,
542
                &btime,
543
                &dir
544
                );
545
            obt = btime;
546
        }
547
        else {
548
            snd_pcm_uframes_t bsize = req->buffer_size;
549

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

    
563
        if ((req->override_mask & 2) && (obt - req->buffer_size))
564
            dolog ("Requested buffer %s %u was rejected, using %lu\n",
565
                   size_in_usec ? "time" : "size", req->buffer_size, obt);
566
    }
567

    
568
    if (req->period_size) {
569
        unsigned long obt;
570

    
571
        if (size_in_usec) {
572
            int dir = 0;
573
            unsigned int ptime = req->period_size;
574

    
575
            err = snd_pcm_hw_params_set_period_time_near (
576
                handle,
577
                hw_params,
578
                &ptime,
579
                &dir
580
                );
581
            obt = ptime;
582
        }
583
        else {
584
            int dir = 0;
585
            snd_pcm_uframes_t psize = req->period_size;
586

    
587
            err = snd_pcm_hw_params_set_period_size_near (
588
                handle,
589
                hw_params,
590
                &psize,
591
                &dir
592
                );
593
            obt = psize;
594
        }
595

    
596
        if (err < 0) {
597
            alsa_logerr2 (err, typ, "Failed to set period %s to %d\n",
598
                          size_in_usec ? "time" : "size", req->period_size);
599
            goto err;
600
        }
601

    
602
        if (((req->override_mask & 1) && (obt - req->period_size)))
603
            dolog ("Requested period %s %u was rejected, using %lu\n",
604
                   size_in_usec ? "time" : "size", req->period_size, obt);
605
    }
606

    
607
    err = snd_pcm_hw_params (handle, hw_params);
608
    if (err < 0) {
609
        alsa_logerr2 (err, typ, "Failed to apply audio parameters\n");
610
        goto err;
611
    }
612

    
613
    err = snd_pcm_hw_params_get_buffer_size (hw_params, &obt_buffer_size);
614
    if (err < 0) {
615
        alsa_logerr2 (err, typ, "Failed to get buffer size\n");
616
        goto err;
617
    }
618

    
619
    err = snd_pcm_hw_params_get_format (hw_params, &obtfmt);
620
    if (err < 0) {
621
        alsa_logerr2 (err, typ, "Failed to get format\n");
622
        goto err;
623
    }
624

    
625
    if (alsa_to_audfmt (obtfmt, &obt->fmt, &obt->endianness)) {
626
        dolog ("Invalid format was returned %d\n", obtfmt);
627
        goto err;
628
    }
629

    
630
    err = snd_pcm_prepare (handle);
631
    if (err < 0) {
632
        alsa_logerr2 (err, typ, "Could not prepare handle %p\n", handle);
633
        goto err;
634
    }
635

    
636
    if (!in && conf.threshold) {
637
        snd_pcm_uframes_t threshold;
638
        int bytes_per_sec;
639

    
640
        bytes_per_sec = freq << (nchannels == 2);
641

    
642
        switch (obt->fmt) {
643
        case AUD_FMT_S8:
644
        case AUD_FMT_U8:
645
            break;
646

    
647
        case AUD_FMT_S16:
648
        case AUD_FMT_U16:
649
            bytes_per_sec <<= 1;
650
            break;
651

    
652
        case AUD_FMT_S32:
653
        case AUD_FMT_U32:
654
            bytes_per_sec <<= 2;
655
            break;
656
        }
657

    
658
        threshold = (conf.threshold * bytes_per_sec) / 1000;
659
        alsa_set_threshold (handle, threshold);
660
    }
661

    
662
    obt->nchannels = nchannels;
663
    obt->freq = freq;
664
    obt->samples = obt_buffer_size;
665

    
666
    *handlep = handle;
667

    
668
    if (conf.verbose &&
669
        (obt->fmt != req->fmt ||
670
         obt->nchannels != req->nchannels ||
671
         obt->freq != req->freq)) {
672
        dolog ("Audio parameters for %s\n", typ);
673
        alsa_dump_info (req, obt);
674
    }
675

    
676
#ifdef DEBUG
677
    alsa_dump_info (req, obt);
678
#endif
679
    return 0;
680

    
681
 err:
682
    alsa_anal_close1 (&handle);
683
    return -1;
684
}
685

    
686
static snd_pcm_sframes_t alsa_get_avail (snd_pcm_t *handle)
687
{
688
    snd_pcm_sframes_t avail;
689

    
690
    avail = snd_pcm_avail_update (handle);
691
    if (avail < 0) {
692
        if (avail == -EPIPE) {
693
            if (!alsa_recover (handle)) {
694
                avail = snd_pcm_avail_update (handle);
695
            }
696
        }
697

    
698
        if (avail < 0) {
699
            alsa_logerr (avail,
700
                         "Could not obtain number of available frames\n");
701
            return -1;
702
        }
703
    }
704

    
705
    return avail;
706
}
707

    
708
static void alsa_write_pending (ALSAVoiceOut *alsa)
709
{
710
    HWVoiceOut *hw = &alsa->hw;
711

    
712
    while (alsa->pending) {
713
        int left_till_end_samples = hw->samples - alsa->wpos;
714
        int len = audio_MIN (alsa->pending, left_till_end_samples);
715
        char *src = advance (alsa->pcm_buf, alsa->wpos << hw->info.shift);
716

    
717
        while (len) {
718
            snd_pcm_sframes_t written;
719

    
720
            written = snd_pcm_writei (alsa->handle, src, len);
721

    
722
            if (written <= 0) {
723
                switch (written) {
724
                case 0:
725
                    if (conf.verbose) {
726
                        dolog ("Failed to write %d frames (wrote zero)\n", len);
727
                    }
728
                    return;
729

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

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

    
754
                case -EAGAIN:
755
                    return;
756

    
757
                default:
758
                    alsa_logerr (written, "Failed to write %d frames from %p\n",
759
                                 len, src);
760
                    return;
761
                }
762
            }
763

    
764
            alsa->wpos = (alsa->wpos + written) % hw->samples;
765
            alsa->pending -= written;
766
            len -= written;
767
        }
768
    }
769
}
770

    
771
static int alsa_run_out (HWVoiceOut *hw, int live)
772
{
773
    ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
774
    int decr;
775
    snd_pcm_sframes_t avail;
776

    
777
    avail = alsa_get_avail (alsa->handle);
778
    if (avail < 0) {
779
        dolog ("Could not get number of available playback frames\n");
780
        return 0;
781
    }
782

    
783
    decr = audio_MIN (live, avail);
784
    decr = audio_pcm_hw_clip_out (hw, alsa->pcm_buf, decr, alsa->pending);
785
    alsa->pending += decr;
786
    alsa_write_pending (alsa);
787
    return decr;
788
}
789

    
790
static void alsa_fini_out (HWVoiceOut *hw)
791
{
792
    ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
793

    
794
    ldebug ("alsa_fini\n");
795
    alsa_anal_close (&alsa->handle, &alsa->pollhlp);
796

    
797
    if (alsa->pcm_buf) {
798
        qemu_free (alsa->pcm_buf);
799
        alsa->pcm_buf = NULL;
800
    }
801
}
802

    
803
static int alsa_init_out (HWVoiceOut *hw, struct audsettings *as)
804
{
805
    ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
806
    struct alsa_params_req req;
807
    struct alsa_params_obt obt;
808
    snd_pcm_t *handle;
809
    struct audsettings obt_as;
810

    
811
    req.fmt = aud_to_alsafmt (as->fmt);
812
    req.freq = as->freq;
813
    req.nchannels = as->nchannels;
814
    req.period_size = conf.period_size_out;
815
    req.buffer_size = conf.buffer_size_out;
816
    req.size_in_usec = conf.size_in_usec_out;
817
    req.override_mask =
818
        (conf.period_size_out_overridden ? 1 : 0) |
819
        (conf.buffer_size_out_overridden ? 2 : 0);
820

    
821
    if (alsa_open (0, &req, &obt, &handle)) {
822
        return -1;
823
    }
824

    
825
    obt_as.freq = obt.freq;
826
    obt_as.nchannels = obt.nchannels;
827
    obt_as.fmt = obt.fmt;
828
    obt_as.endianness = obt.endianness;
829

    
830
    audio_pcm_init_info (&hw->info, &obt_as);
831
    hw->samples = obt.samples;
832

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

    
841
    alsa->handle = handle;
842
    return 0;
843
}
844

    
845
static int alsa_voice_ctl (snd_pcm_t *handle, const char *typ, int pause)
846
{
847
    int err;
848

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

    
864
    return 0;
865
}
866

    
867
static int alsa_ctl_out (HWVoiceOut *hw, int cmd, ...)
868
{
869
    ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
870

    
871
    switch (cmd) {
872
    case VOICE_ENABLE:
873
        {
874
            va_list ap;
875
            int poll_mode;
876

    
877
            va_start (ap, cmd);
878
            poll_mode = va_arg (ap, int);
879
            va_end (ap);
880

    
881
            ldebug ("enabling voice\n");
882
            if (poll_mode && alsa_poll_out (hw)) {
883
                poll_mode = 0;
884
            }
885
            hw->poll_mode = poll_mode;
886
            return alsa_voice_ctl (alsa->handle, "playback", 0);
887
        }
888

    
889
    case VOICE_DISABLE:
890
        ldebug ("disabling voice\n");
891
        return alsa_voice_ctl (alsa->handle, "playback", 1);
892
    }
893

    
894
    return -1;
895
}
896

    
897
static int alsa_init_in (HWVoiceIn *hw, struct audsettings *as)
898
{
899
    ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
900
    struct alsa_params_req req;
901
    struct alsa_params_obt obt;
902
    snd_pcm_t *handle;
903
    struct audsettings obt_as;
904

    
905
    req.fmt = aud_to_alsafmt (as->fmt);
906
    req.freq = as->freq;
907
    req.nchannels = as->nchannels;
908
    req.period_size = conf.period_size_in;
909
    req.buffer_size = conf.buffer_size_in;
910
    req.size_in_usec = conf.size_in_usec_in;
911
    req.override_mask =
912
        (conf.period_size_in_overridden ? 1 : 0) |
913
        (conf.buffer_size_in_overridden ? 2 : 0);
914

    
915
    if (alsa_open (1, &req, &obt, &handle)) {
916
        return -1;
917
    }
918

    
919
    obt_as.freq = obt.freq;
920
    obt_as.nchannels = obt.nchannels;
921
    obt_as.fmt = obt.fmt;
922
    obt_as.endianness = obt.endianness;
923

    
924
    audio_pcm_init_info (&hw->info, &obt_as);
925
    hw->samples = obt.samples;
926

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

    
935
    alsa->handle = handle;
936
    return 0;
937
}
938

    
939
static void alsa_fini_in (HWVoiceIn *hw)
940
{
941
    ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
942

    
943
    alsa_anal_close (&alsa->handle, &alsa->pollhlp);
944

    
945
    if (alsa->pcm_buf) {
946
        qemu_free (alsa->pcm_buf);
947
        alsa->pcm_buf = NULL;
948
    }
949
}
950

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

    
969
    if (!dead) {
970
        return 0;
971
    }
972

    
973
    avail = alsa_get_avail (alsa->handle);
974
    if (avail < 0) {
975
        dolog ("Could not get number of captured frames\n");
976
        return 0;
977
    }
978

    
979
    if (!avail) {
980
        snd_pcm_state_t state;
981

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

    
1005
    decr = audio_MIN (dead, avail);
1006
    if (!decr) {
1007
        return 0;
1008
    }
1009

    
1010
    if (hw->wpos + decr > hw->samples) {
1011
        bufs[0].len = (hw->samples - hw->wpos);
1012
        bufs[1].len = (decr - (hw->samples - hw->wpos));
1013
    }
1014
    else {
1015
        bufs[0].len = decr;
1016
    }
1017

    
1018
    for (i = 0; i < 2; ++i) {
1019
        void *src;
1020
        struct st_sample *dst;
1021
        snd_pcm_sframes_t nread;
1022
        snd_pcm_uframes_t len;
1023

    
1024
        len = bufs[i].len;
1025

    
1026
        src = advance (alsa->pcm_buf, bufs[i].add << hwshift);
1027
        dst = hw->conv_buf + bufs[i].add;
1028

    
1029
        while (len) {
1030
            nread = snd_pcm_readi (alsa->handle, src, len);
1031

    
1032
            if (nread <= 0) {
1033
                switch (nread) {
1034
                case 0:
1035
                    if (conf.verbose) {
1036
                        dolog ("Failed to read %ld frames (read zero)\n", len);
1037
                    }
1038
                    goto exit;
1039

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

    
1050
                case -EAGAIN:
1051
                    goto exit;
1052

    
1053
                default:
1054
                    alsa_logerr (
1055
                        nread,
1056
                        "Failed to read %ld frames from %p\n",
1057
                        len,
1058
                        src
1059
                        );
1060
                    goto exit;
1061
                }
1062
            }
1063

    
1064
            hw->conv (dst, src, nread, &nominal_volume);
1065

    
1066
            src = advance (src, nread << hwshift);
1067
            dst += nread;
1068

    
1069
            read_samples += nread;
1070
            len -= nread;
1071
        }
1072
    }
1073

    
1074
 exit:
1075
    hw->wpos = (hw->wpos + read_samples) % hw->samples;
1076
    return read_samples;
1077
}
1078

    
1079
static int alsa_read (SWVoiceIn *sw, void *buf, int size)
1080
{
1081
    return audio_pcm_sw_read (sw, buf, size);
1082
}
1083

    
1084
static int alsa_ctl_in (HWVoiceIn *hw, int cmd, ...)
1085
{
1086
    ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
1087

    
1088
    switch (cmd) {
1089
    case VOICE_ENABLE:
1090
        {
1091
            va_list ap;
1092
            int poll_mode;
1093

    
1094
            va_start (ap, cmd);
1095
            poll_mode = va_arg (ap, int);
1096
            va_end (ap);
1097

    
1098
            ldebug ("enabling voice\n");
1099
            if (poll_mode && alsa_poll_in (hw)) {
1100
                poll_mode = 0;
1101
            }
1102
            hw->poll_mode = poll_mode;
1103

    
1104
            return alsa_voice_ctl (alsa->handle, "capture", 0);
1105
        }
1106

    
1107
    case VOICE_DISABLE:
1108
        ldebug ("disabling voice\n");
1109
        if (hw->poll_mode) {
1110
            hw->poll_mode = 0;
1111
            alsa_fini_poll (&alsa->pollhlp);
1112
        }
1113
        return alsa_voice_ctl (alsa->handle, "capture", 1);
1114
    }
1115

    
1116
    return -1;
1117
}
1118

    
1119
static void *alsa_audio_init (void)
1120
{
1121
    return &conf;
1122
}
1123

    
1124
static void alsa_audio_fini (void *opaque)
1125
{
1126
    (void) opaque;
1127
}
1128

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

    
1198
static struct audio_pcm_ops alsa_pcm_ops = {
1199
    .init_out = alsa_init_out,
1200
    .fini_out = alsa_fini_out,
1201
    .run_out  = alsa_run_out,
1202
    .write    = alsa_write,
1203
    .ctl_out  = alsa_ctl_out,
1204

    
1205
    .init_in  = alsa_init_in,
1206
    .fini_in  = alsa_fini_in,
1207
    .run_in   = alsa_run_in,
1208
    .read     = alsa_read,
1209
    .ctl_in   = alsa_ctl_in,
1210
};
1211

    
1212
struct audio_driver alsa_audio_driver = {
1213
    .name           = "alsa",
1214
    .descr          = "ALSA http://www.alsa-project.org",
1215
    .options        = alsa_options,
1216
    .init           = alsa_audio_init,
1217
    .fini           = alsa_audio_fini,
1218
    .pcm_ops        = &alsa_pcm_ops,
1219
    .can_be_default = 1,
1220
    .max_voices_out = INT_MAX,
1221
    .max_voices_in  = INT_MAX,
1222
    .voice_size_out = sizeof (ALSAVoiceOut),
1223
    .voice_size_in  = sizeof (ALSAVoiceIn)
1224
};