Coverage Report

Created: 2026-11-20 08:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qemu/hw/usb/dev-audio.c
Line
Count
Source
1
/*
2
 * QEMU USB audio device
3
 *
4
 * written by:
5
 *  H. Peter Anvin <hpa@linux.intel.com>
6
 *  Gerd Hoffmann <kraxel@redhat.com>
7
 *
8
 * lousely based on usb net device code which is:
9
 *
10
 * Copyright (c) 2006 Thomas Sailer
11
 * Copyright (c) 2008 Andrzej Zaborowski
12
 *
13
 * Permission is hereby granted, free of charge, to any person obtaining a copy
14
 * of this software and associated documentation files (the "Software"), to deal
15
 * in the Software without restriction, including without limitation the rights
16
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
 * copies of the Software, and to permit persons to whom the Software is
18
 * furnished to do so, subject to the following conditions:
19
 *
20
 * The above copyright notice and this permission notice shall be included in
21
 * all copies or substantial portions of the Software.
22
 *
23
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
26
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
29
 * THE SOFTWARE.
30
 */
31
32
#include "qemu/osdep.h"
33
#include "qemu/module.h"
34
#include "hw/core/qdev-properties.h"
35
#include "hw/usb/usb.h"
36
#include "migration/vmstate.h"
37
#include "desc.h"
38
#include "qemu/audio.h"
39
#include "qom/object.h"
40
41
static void usb_audio_reinit(USBDevice *dev, unsigned channels);
42
43
#define USBAUDIO_VENDOR_NUM     0x46f4 /* CRC16() of "QEMU" */
44
#define USBAUDIO_PRODUCT_NUM    0x0002
45
46
#define DEV_CONFIG_VALUE        1 /* The one and only */
47
48
6
#define USBAUDIO_MAX_CHANNELS(s) (s->multi ? 8 : 2)
49
50
/* Descriptor subtypes for AC interfaces */
51
#define DST_AC_HEADER           1
52
#define DST_AC_INPUT_TERMINAL   2
53
#define DST_AC_OUTPUT_TERMINAL  3
54
#define DST_AC_FEATURE_UNIT     6
55
/* Descriptor subtypes for AS interfaces */
56
#define DST_AS_GENERAL          1
57
#define DST_AS_FORMAT_TYPE      2
58
/* Descriptor subtypes for endpoints */
59
#define DST_EP_GENERAL          1
60
61
enum usb_audio_strings {
62
    STRING_NULL,
63
    STRING_MANUFACTURER,
64
    STRING_PRODUCT,
65
    STRING_SERIALNUMBER,
66
    STRING_CONFIG,
67
    STRING_USBAUDIO_CONTROL,
68
    STRING_INPUT_TERMINAL,
69
    STRING_FEATURE_UNIT,
70
    STRING_OUTPUT_TERMINAL,
71
    STRING_NULL_STREAM,
72
    STRING_REAL_STREAM,
73
};
74
75
static const USBDescStrings usb_audio_stringtable = {
76
    [STRING_MANUFACTURER]       = "QEMU",
77
    [STRING_PRODUCT]            = "QEMU USB Audio",
78
    [STRING_SERIALNUMBER]       = "1",
79
    [STRING_CONFIG]             = "Audio Configuration",
80
    [STRING_USBAUDIO_CONTROL]   = "Audio Device",
81
    [STRING_INPUT_TERMINAL]     = "Audio Output Pipe",
82
    [STRING_FEATURE_UNIT]       = "Audio Output Volume Control",
83
    [STRING_OUTPUT_TERMINAL]    = "Audio Output Terminal",
84
    [STRING_NULL_STREAM]        = "Audio Output - Disabled",
85
    [STRING_REAL_STREAM]        = "Audio Output - 48 kHz Stereo",
86
};
87
88
/*
89
 * A USB audio device supports an arbitrary number of alternate
90
 * interface settings for each interface.  Each corresponds to a block
91
 * diagram of parameterized blocks.  This can thus refer to things like
92
 * number of channels, data rates, or in fact completely different
93
 * block diagrams.  Alternative setting 0 is always the null block diagram,
94
 * which is used by a disabled device.
95
 */
96
enum usb_audio_altset {
97
    ALTSET_OFF    = 0x00,         /* No endpoint */
98
    ALTSET_STEREO = 0x01,         /* Single endpoint */
99
    ALTSET_51     = 0x02,
100
    ALTSET_71     = 0x03,
101
};
102
103
static unsigned altset_channels[] = {
104
    [ALTSET_STEREO] = 2,
105
    [ALTSET_51]     = 6,
106
    [ALTSET_71]     = 8,
107
};
108
109
#define U16(x) ((x) & 0xff), (((x) >> 8) & 0xff)
110
#define U24(x) U16(x), (((x) >> 16) & 0xff)
111
#define U32(x) U24(x), (((x) >> 24) & 0xff)
112
113
/*
114
 * A Basic Audio Device uses these specific values
115
 */
116
4
#define USBAUDIO_PACKET_SIZE_BASE 96
117
4
#define USBAUDIO_PACKET_SIZE(channels) (USBAUDIO_PACKET_SIZE_BASE * channels)
118
2
#define USBAUDIO_SAMPLE_RATE     48000
119
#define USBAUDIO_PACKET_INTERVAL 1
120
121
static const USBDescIface desc_iface[] = {
122
    {
123
        .bInterfaceNumber              = 0,
124
        .bNumEndpoints                 = 0,
125
        .bInterfaceClass               = USB_CLASS_AUDIO,
126
        .bInterfaceSubClass            = USB_SUBCLASS_AUDIO_CONTROL,
127
        .iInterface                    = STRING_USBAUDIO_CONTROL,
128
        .ndesc                         = 4,
129
        .descs = (USBDescOther[]) {
130
            {
131
                /* Headphone Class-Specific AC Interface Header Descriptor */
132
                .data = (uint8_t[]) {
133
                    0x09,                       /*  u8  bLength */
134
                    USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
135
                    DST_AC_HEADER,              /*  u8  bDescriptorSubtype */
136
                    U16(0x0100),                /* u16  bcdADC */
137
                    U16(0x2b),                  /* u16  wTotalLength */
138
                    0x01,                       /*  u8  bInCollection */
139
                    0x01,                       /*  u8  baInterfaceNr */
140
                }
141
            },{
142
                /* Generic Stereo Input Terminal ID1 Descriptor */
143
                .data = (uint8_t[]) {
144
                    0x0c,                       /*  u8  bLength */
145
                    USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
146
                    DST_AC_INPUT_TERMINAL,      /*  u8  bDescriptorSubtype */
147
                    0x01,                       /*  u8  bTerminalID */
148
                    U16(0x0101),                /* u16  wTerminalType */
149
                    0x00,                       /*  u8  bAssocTerminal */
150
                    0x02,                       /*  u8  bNrChannels */
151
                    U16(0x0003),                /* u16  wChannelConfig */
152
                    0x00,                       /*  u8  iChannelNames */
153
                    STRING_INPUT_TERMINAL,      /*  u8  iTerminal */
154
                }
155
            },{
156
                /* Generic Stereo Feature Unit ID2 Descriptor */
157
                .data = (uint8_t[]) {
158
                    0x0d,                       /*  u8  bLength */
159
                    USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
160
                    DST_AC_FEATURE_UNIT,        /*  u8  bDescriptorSubtype */
161
                    0x02,                       /*  u8  bUnitID */
162
                    0x01,                       /*  u8  bSourceID */
163
                    0x02,                       /*  u8  bControlSize */
164
                    U16(0x0001),                /* u16  bmaControls(0) */
165
                    U16(0x0002),                /* u16  bmaControls(1) */
166
                    U16(0x0002),                /* u16  bmaControls(2) */
167
                    STRING_FEATURE_UNIT,        /*  u8  iFeature */
168
                }
169
            },{
170
                /* Headphone Output Terminal ID3 Descriptor */
171
                .data = (uint8_t[]) {
172
                    0x09,                       /*  u8  bLength */
173
                    USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
174
                    DST_AC_OUTPUT_TERMINAL,     /*  u8  bDescriptorSubtype */
175
                    0x03,                       /*  u8  bUnitID */
176
                    U16(0x0301),                /* u16  wTerminalType (SPK) */
177
                    0x00,                       /*  u8  bAssocTerminal */
178
                    0x02,                       /*  u8  bSourceID */
179
                    STRING_OUTPUT_TERMINAL,     /*  u8  iTerminal */
180
                }
181
            }
182
        },
183
    },{
184
        .bInterfaceNumber              = 1,
185
        .bAlternateSetting             = ALTSET_OFF,
186
        .bNumEndpoints                 = 0,
187
        .bInterfaceClass               = USB_CLASS_AUDIO,
188
        .bInterfaceSubClass            = USB_SUBCLASS_AUDIO_STREAMING,
189
        .iInterface                    = STRING_NULL_STREAM,
190
    },{
191
        .bInterfaceNumber              = 1,
192
        .bAlternateSetting             = ALTSET_STEREO,
193
        .bNumEndpoints                 = 1,
194
        .bInterfaceClass               = USB_CLASS_AUDIO,
195
        .bInterfaceSubClass            = USB_SUBCLASS_AUDIO_STREAMING,
196
        .iInterface                    = STRING_REAL_STREAM,
197
        .ndesc                         = 2,
198
        .descs = (USBDescOther[]) {
199
            {
200
                /* Headphone Class-specific AS General Interface Descriptor */
201
                .data = (uint8_t[]) {
202
                    0x07,                       /*  u8  bLength */
203
                    USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
204
                    DST_AS_GENERAL,             /*  u8  bDescriptorSubtype */
205
                    0x01,                       /*  u8  bTerminalLink */
206
                    0x00,                       /*  u8  bDelay */
207
                    0x01, 0x00,                 /* u16  wFormatTag */
208
                }
209
            },{
210
                /* Headphone Type I Format Type Descriptor */
211
                .data = (uint8_t[]) {
212
                    0x0b,                       /*  u8  bLength */
213
                    USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
214
                    DST_AS_FORMAT_TYPE,         /*  u8  bDescriptorSubtype */
215
                    0x01,                       /*  u8  bFormatType */
216
                    0x02,                       /*  u8  bNrChannels */
217
                    0x02,                       /*  u8  bSubFrameSize */
218
                    0x10,                       /*  u8  bBitResolution */
219
                    0x01,                       /*  u8  bSamFreqType */
220
                    U24(USBAUDIO_SAMPLE_RATE),  /* u24  tSamFreq */
221
                }
222
            }
223
        },
224
        .eps = (USBDescEndpoint[]) {
225
            {
226
                .bEndpointAddress      = USB_DIR_OUT | 0x01,
227
                .bmAttributes          = 0x0d,
228
                .wMaxPacketSize        = USBAUDIO_PACKET_SIZE(2),
229
                .bInterval             = 1,
230
                .is_audio              = 1,
231
                /* Stereo Headphone Class-specific
232
                   AS Audio Data Endpoint Descriptor */
233
                .extra = (uint8_t[]) {
234
                    0x07,                       /*  u8  bLength */
235
                    USB_DT_CS_ENDPOINT,         /*  u8  bDescriptorType */
236
                    DST_EP_GENERAL,             /*  u8  bDescriptorSubtype */
237
                    0x00,                       /*  u8  bmAttributes */
238
                    0x00,                       /*  u8  bLockDelayUnits */
239
                    U16(0x0000),                /* u16  wLockDelay */
240
                },
241
            },
242
        }
243
    }
244
};
245
246
static const USBDescDevice desc_device = {
247
    .bcdUSB                        = 0x0100,
248
    .bMaxPacketSize0               = 64,
249
    .bNumConfigurations            = 1,
250
    .confs = (USBDescConfig[]) {
251
        {
252
            .bNumInterfaces        = 2,
253
            .bConfigurationValue   = DEV_CONFIG_VALUE,
254
            .iConfiguration        = STRING_CONFIG,
255
            .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_SELFPOWER,
256
            .bMaxPower             = 0x32,
257
            .nif = ARRAY_SIZE(desc_iface),
258
            .ifs = desc_iface,
259
        },
260
    },
261
};
262
263
static const USBDesc desc_audio = {
264
    .id = {
265
        .idVendor          = USBAUDIO_VENDOR_NUM,
266
        .idProduct         = USBAUDIO_PRODUCT_NUM,
267
        .bcdDevice         = 0,
268
        .iManufacturer     = STRING_MANUFACTURER,
269
        .iProduct          = STRING_PRODUCT,
270
        .iSerialNumber     = STRING_SERIALNUMBER,
271
    },
272
    .full = &desc_device,
273
    .str  = usb_audio_stringtable,
274
};
275
276
/* multi channel compatible desc */
277
278
static const USBDescIface desc_iface_multi[] = {
279
    {
280
        .bInterfaceNumber              = 0,
281
        .bNumEndpoints                 = 0,
282
        .bInterfaceClass               = USB_CLASS_AUDIO,
283
        .bInterfaceSubClass            = USB_SUBCLASS_AUDIO_CONTROL,
284
        .iInterface                    = STRING_USBAUDIO_CONTROL,
285
        .ndesc                         = 4,
286
        .descs = (USBDescOther[]) {
287
            {
288
                /* Headphone Class-Specific AC Interface Header Descriptor */
289
                .data = (uint8_t[]) {
290
                    0x09,                       /*  u8  bLength */
291
                    USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
292
                    DST_AC_HEADER,              /*  u8  bDescriptorSubtype */
293
                    U16(0x0100),                /* u16  bcdADC */
294
                    U16(0x37),                  /* u16  wTotalLength */
295
                    0x01,                       /*  u8  bInCollection */
296
                    0x01,                       /*  u8  baInterfaceNr */
297
                }
298
            },{
299
                /* Generic Stereo Input Terminal ID1 Descriptor */
300
                .data = (uint8_t[]) {
301
                    0x0c,                       /*  u8  bLength */
302
                    USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
303
                    DST_AC_INPUT_TERMINAL,      /*  u8  bDescriptorSubtype */
304
                    0x01,                       /*  u8  bTerminalID */
305
                    U16(0x0101),                /* u16  wTerminalType */
306
                    0x00,                       /*  u8  bAssocTerminal */
307
                    0x08,                       /*  u8  bNrChannels */
308
                    U16(0x063f),                /* u16  wChannelConfig */
309
                    0x00,                       /*  u8  iChannelNames */
310
                    STRING_INPUT_TERMINAL,      /*  u8  iTerminal */
311
                }
312
            },{
313
                /* Generic Stereo Feature Unit ID2 Descriptor */
314
                .data = (uint8_t[]) {
315
                    0x19,                       /*  u8  bLength */
316
                    USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
317
                    DST_AC_FEATURE_UNIT,        /*  u8  bDescriptorSubtype */
318
                    0x02,                       /*  u8  bUnitID */
319
                    0x01,                       /*  u8  bSourceID */
320
                    0x02,                       /*  u8  bControlSize */
321
                    U16(0x0001),                /* u16  bmaControls(0) */
322
                    U16(0x0002),                /* u16  bmaControls(1) */
323
                    U16(0x0002),                /* u16  bmaControls(2) */
324
                    U16(0x0002),                /* u16  bmaControls(3) */
325
                    U16(0x0002),                /* u16  bmaControls(4) */
326
                    U16(0x0002),                /* u16  bmaControls(5) */
327
                    U16(0x0002),                /* u16  bmaControls(6) */
328
                    U16(0x0002),                /* u16  bmaControls(7) */
329
                    U16(0x0002),                /* u16  bmaControls(8) */
330
                    STRING_FEATURE_UNIT,        /*  u8  iFeature */
331
                }
332
            },{
333
                /* Headphone Output Terminal ID3 Descriptor */
334
                .data = (uint8_t[]) {
335
                    0x09,                       /*  u8  bLength */
336
                    USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
337
                    DST_AC_OUTPUT_TERMINAL,     /*  u8  bDescriptorSubtype */
338
                    0x03,                       /*  u8  bUnitID */
339
                    U16(0x0301),                /* u16  wTerminalType (SPK) */
340
                    0x00,                       /*  u8  bAssocTerminal */
341
                    0x02,                       /*  u8  bSourceID */
342
                    STRING_OUTPUT_TERMINAL,     /*  u8  iTerminal */
343
                }
344
            }
345
        },
346
    },{
347
        .bInterfaceNumber              = 1,
348
        .bAlternateSetting             = ALTSET_OFF,
349
        .bNumEndpoints                 = 0,
350
        .bInterfaceClass               = USB_CLASS_AUDIO,
351
        .bInterfaceSubClass            = USB_SUBCLASS_AUDIO_STREAMING,
352
        .iInterface                    = STRING_NULL_STREAM,
353
    },{
354
        .bInterfaceNumber              = 1,
355
        .bAlternateSetting             = ALTSET_STEREO,
356
        .bNumEndpoints                 = 1,
357
        .bInterfaceClass               = USB_CLASS_AUDIO,
358
        .bInterfaceSubClass            = USB_SUBCLASS_AUDIO_STREAMING,
359
        .iInterface                    = STRING_REAL_STREAM,
360
        .ndesc                         = 2,
361
        .descs = (USBDescOther[]) {
362
            {
363
                /* Headphone Class-specific AS General Interface Descriptor */
364
                .data = (uint8_t[]) {
365
                    0x07,                       /*  u8  bLength */
366
                    USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
367
                    DST_AS_GENERAL,             /*  u8  bDescriptorSubtype */
368
                    0x01,                       /*  u8  bTerminalLink */
369
                    0x00,                       /*  u8  bDelay */
370
                    0x01, 0x00,                 /* u16  wFormatTag */
371
                }
372
            },{
373
                /* Headphone Type I Format Type Descriptor */
374
                .data = (uint8_t[]) {
375
                    0x0b,                       /*  u8  bLength */
376
                    USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
377
                    DST_AS_FORMAT_TYPE,         /*  u8  bDescriptorSubtype */
378
                    0x01,                       /*  u8  bFormatType */
379
                    0x02,                       /*  u8  bNrChannels */
380
                    0x02,                       /*  u8  bSubFrameSize */
381
                    0x10,                       /*  u8  bBitResolution */
382
                    0x01,                       /*  u8  bSamFreqType */
383
                    U24(USBAUDIO_SAMPLE_RATE),  /* u24  tSamFreq */
384
                }
385
            }
386
        },
387
        .eps = (USBDescEndpoint[]) {
388
            {
389
                .bEndpointAddress      = USB_DIR_OUT | 0x01,
390
                .bmAttributes          = 0x0d,
391
                .wMaxPacketSize        = USBAUDIO_PACKET_SIZE(2),
392
                .bInterval             = 1,
393
                .is_audio              = 1,
394
                /* Stereo Headphone Class-specific
395
                   AS Audio Data Endpoint Descriptor */
396
                .extra = (uint8_t[]) {
397
                    0x07,                       /*  u8  bLength */
398
                    USB_DT_CS_ENDPOINT,         /*  u8  bDescriptorType */
399
                    DST_EP_GENERAL,             /*  u8  bDescriptorSubtype */
400
                    0x00,                       /*  u8  bmAttributes */
401
                    0x00,                       /*  u8  bLockDelayUnits */
402
                    U16(0x0000),                /* u16  wLockDelay */
403
                },
404
            },
405
        }
406
    },{
407
        .bInterfaceNumber              = 1,
408
        .bAlternateSetting             = ALTSET_51,
409
        .bNumEndpoints                 = 1,
410
        .bInterfaceClass               = USB_CLASS_AUDIO,
411
        .bInterfaceSubClass            = USB_SUBCLASS_AUDIO_STREAMING,
412
        .iInterface                    = STRING_REAL_STREAM,
413
        .ndesc                         = 2,
414
        .descs = (USBDescOther[]) {
415
            {
416
                /* Headphone Class-specific AS General Interface Descriptor */
417
                .data = (uint8_t[]) {
418
                    0x07,                       /*  u8  bLength */
419
                    USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
420
                    DST_AS_GENERAL,             /*  u8  bDescriptorSubtype */
421
                    0x01,                       /*  u8  bTerminalLink */
422
                    0x00,                       /*  u8  bDelay */
423
                    0x01, 0x00,                 /* u16  wFormatTag */
424
                }
425
            },{
426
                /* Headphone Type I Format Type Descriptor */
427
                .data = (uint8_t[]) {
428
                    0x0b,                       /*  u8  bLength */
429
                    USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
430
                    DST_AS_FORMAT_TYPE,         /*  u8  bDescriptorSubtype */
431
                    0x01,                       /*  u8  bFormatType */
432
                    0x06,                       /*  u8  bNrChannels */
433
                    0x02,                       /*  u8  bSubFrameSize */
434
                    0x10,                       /*  u8  bBitResolution */
435
                    0x01,                       /*  u8  bSamFreqType */
436
                    U24(USBAUDIO_SAMPLE_RATE),  /* u24  tSamFreq */
437
                }
438
            }
439
        },
440
        .eps = (USBDescEndpoint[]) {
441
            {
442
                .bEndpointAddress      = USB_DIR_OUT | 0x01,
443
                .bmAttributes          = 0x0d,
444
                .wMaxPacketSize        = USBAUDIO_PACKET_SIZE(6),
445
                .bInterval             = 1,
446
                .is_audio              = 1,
447
                /* Stereo Headphone Class-specific
448
                   AS Audio Data Endpoint Descriptor */
449
                .extra = (uint8_t[]) {
450
                    0x07,                       /*  u8  bLength */
451
                    USB_DT_CS_ENDPOINT,         /*  u8  bDescriptorType */
452
                    DST_EP_GENERAL,             /*  u8  bDescriptorSubtype */
453
                    0x00,                       /*  u8  bmAttributes */
454
                    0x00,                       /*  u8  bLockDelayUnits */
455
                    U16(0x0000),                /* u16  wLockDelay */
456
                },
457
            },
458
        }
459
    },{
460
        .bInterfaceNumber              = 1,
461
        .bAlternateSetting             = ALTSET_71,
462
        .bNumEndpoints                 = 1,
463
        .bInterfaceClass               = USB_CLASS_AUDIO,
464
        .bInterfaceSubClass            = USB_SUBCLASS_AUDIO_STREAMING,
465
        .iInterface                    = STRING_REAL_STREAM,
466
        .ndesc                         = 2,
467
        .descs = (USBDescOther[]) {
468
            {
469
                /* Headphone Class-specific AS General Interface Descriptor */
470
                .data = (uint8_t[]) {
471
                    0x07,                       /*  u8  bLength */
472
                    USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
473
                    DST_AS_GENERAL,             /*  u8  bDescriptorSubtype */
474
                    0x01,                       /*  u8  bTerminalLink */
475
                    0x00,                       /*  u8  bDelay */
476
                    0x01, 0x00,                 /* u16  wFormatTag */
477
                }
478
            },{
479
                /* Headphone Type I Format Type Descriptor */
480
                .data = (uint8_t[]) {
481
                    0x0b,                       /*  u8  bLength */
482
                    USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
483
                    DST_AS_FORMAT_TYPE,         /*  u8  bDescriptorSubtype */
484
                    0x01,                       /*  u8  bFormatType */
485
                    0x08,                       /*  u8  bNrChannels */
486
                    0x02,                       /*  u8  bSubFrameSize */
487
                    0x10,                       /*  u8  bBitResolution */
488
                    0x01,                       /*  u8  bSamFreqType */
489
                    U24(USBAUDIO_SAMPLE_RATE),  /* u24  tSamFreq */
490
                }
491
            }
492
        },
493
        .eps = (USBDescEndpoint[]) {
494
            {
495
                .bEndpointAddress      = USB_DIR_OUT | 0x01,
496
                .bmAttributes          = 0x0d,
497
                .wMaxPacketSize        = USBAUDIO_PACKET_SIZE(8),
498
                .bInterval             = 1,
499
                .is_audio              = 1,
500
                /* Stereo Headphone Class-specific
501
                   AS Audio Data Endpoint Descriptor */
502
                .extra = (uint8_t[]) {
503
                    0x07,                       /*  u8  bLength */
504
                    USB_DT_CS_ENDPOINT,         /*  u8  bDescriptorType */
505
                    DST_EP_GENERAL,             /*  u8  bDescriptorSubtype */
506
                    0x00,                       /*  u8  bmAttributes */
507
                    0x00,                       /*  u8  bLockDelayUnits */
508
                    U16(0x0000),                /* u16  wLockDelay */
509
                },
510
            },
511
        }
512
    }
513
};
514
515
static const USBDescDevice desc_device_multi = {
516
    .bcdUSB                        = 0x0100,
517
    .bMaxPacketSize0               = 64,
518
    .bNumConfigurations            = 1,
519
    .confs = (USBDescConfig[]) {
520
        {
521
            .bNumInterfaces        = 2,
522
            .bConfigurationValue   = DEV_CONFIG_VALUE,
523
            .iConfiguration        = STRING_CONFIG,
524
            .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_SELFPOWER,
525
            .bMaxPower             = 0x32,
526
            .nif = ARRAY_SIZE(desc_iface_multi),
527
            .ifs = desc_iface_multi,
528
        }
529
    },
530
};
531
532
static const USBDesc desc_audio_multi = {
533
    .id = {
534
        .idVendor          = USBAUDIO_VENDOR_NUM,
535
        .idProduct         = USBAUDIO_PRODUCT_NUM,
536
        .bcdDevice         = 0,
537
        .iManufacturer     = STRING_MANUFACTURER,
538
        .iProduct          = STRING_PRODUCT,
539
        .iSerialNumber     = STRING_SERIALNUMBER,
540
    },
541
    .full = &desc_device_multi,
542
    .str  = usb_audio_stringtable,
543
};
544
545
/*
546
 * Class-specific control requests
547
 */
548
0
#define CR_SET_CUR      0x01
549
0
#define CR_GET_CUR      0x81
550
0
#define CR_SET_MIN      0x02
551
0
#define CR_GET_MIN      0x82
552
0
#define CR_SET_MAX      0x03
553
0
#define CR_GET_MAX      0x83
554
0
#define CR_SET_RES      0x04
555
0
#define CR_GET_RES      0x84
556
#define CR_SET_MEM      0x05
557
#define CR_GET_MEM      0x85
558
#define CR_GET_STAT     0xff
559
560
/*
561
 * Feature Unit Control Selectors
562
 */
563
#define MUTE_CONTROL                    0x01
564
#define VOLUME_CONTROL                  0x02
565
#define BASS_CONTROL                    0x03
566
#define MID_CONTROL                     0x04
567
#define TREBLE_CONTROL                  0x05
568
#define GRAPHIC_EQUALIZER_CONTROL       0x06
569
#define AUTOMATIC_GAIN_CONTROL          0x07
570
#define DELAY_CONTROL                   0x08
571
#define BASS_BOOST_CONTROL              0x09
572
#define LOUDNESS_CONTROL                0x0a
573
574
/*
575
 * buffering
576
 */
577
578
struct streambuf {
579
    uint8_t *data;
580
    size_t size;
581
    uint64_t prod;
582
    uint64_t cons;
583
};
584
585
static void streambuf_init(struct streambuf *buf, uint32_t size,
586
                           uint32_t channels)
587
2
{
588
2
    g_free(buf->data);
589
2
    buf->size = size - (size % USBAUDIO_PACKET_SIZE(channels));
590
2
    buf->data = g_malloc(buf->size);
591
2
    buf->prod = 0;
592
2
    buf->cons = 0;
593
2
}
594
595
static void streambuf_fini(struct streambuf *buf)
596
0
{
597
0
    g_free(buf->data);
598
0
    buf->data = NULL;
599
0
}
600
601
static int streambuf_put(struct streambuf *buf, USBPacket *p, uint32_t channels)
602
0
{
603
0
    int64_t free = buf->size - (buf->prod - buf->cons);
604
605
0
    if (free < USBAUDIO_PACKET_SIZE(channels)) {
606
0
        return 0;
607
0
    }
608
0
    if (p->iov.size != USBAUDIO_PACKET_SIZE(channels)) {
609
0
        return 0;
610
0
    }
611
612
    /* can happen if prod overflows */
613
0
    assert(buf->prod % USBAUDIO_PACKET_SIZE(channels) == 0);
614
0
    usb_packet_copy(p, buf->data + (buf->prod % buf->size),
615
0
                    USBAUDIO_PACKET_SIZE(channels));
616
0
    buf->prod += USBAUDIO_PACKET_SIZE(channels);
617
0
    return USBAUDIO_PACKET_SIZE(channels);
618
0
}
619
620
static uint8_t *streambuf_get(struct streambuf *buf, size_t *len)
621
0
{
622
0
    int64_t used = buf->prod - buf->cons;
623
0
    uint8_t *data;
624
625
0
    if (used <= 0) {
626
0
        *len = 0;
627
0
        return NULL;
628
0
    }
629
0
    data = buf->data + (buf->cons % buf->size);
630
0
    *len = MIN(buf->prod - buf->cons,
631
0
               buf->size - (buf->cons % buf->size));
632
0
    return data;
633
0
}
634
635
struct USBAudioState {
636
    /* qemu interfaces */
637
    USBDevice dev;
638
    AudioBackend *audio_be;
639
640
    /* state */
641
    struct {
642
        enum usb_audio_altset altset;
643
        struct audsettings as;
644
        SWVoiceOut *voice;
645
        Volume vol;
646
        struct streambuf buf;
647
        uint32_t channels;
648
    } out;
649
650
    /* properties */
651
    uint32_t debug;
652
    uint32_t buffer_user, buffer;
653
    bool multi;
654
};
655
656
2
#define TYPE_USB_AUDIO "usb-audio"
657
OBJECT_DECLARE_SIMPLE_TYPE(USBAudioState, USB_AUDIO)
658
659
static void output_callback(void *opaque, int avail)
660
0
{
661
0
    USBAudioState *s = opaque;
662
0
    uint8_t *data;
663
664
0
    while (avail) {
665
0
        size_t written, len;
666
667
0
        data = streambuf_get(&s->out.buf, &len);
668
0
        if (!data) {
669
0
            return;
670
0
        }
671
672
0
        written = audio_be_write(s->audio_be, s->out.voice, data, len);
673
0
        avail -= written;
674
0
        s->out.buf.cons += written;
675
676
0
        if (written < len) {
677
0
            return;
678
0
        }
679
0
    }
680
0
}
681
682
static int usb_audio_set_output_altset(USBAudioState *s, int altset)
683
882
{
684
882
    switch (altset) {
685
882
    case ALTSET_OFF:
686
882
        audio_be_set_active_out(s->audio_be, s->out.voice, false);
687
882
        break;
688
0
    case ALTSET_STEREO:
689
0
    case ALTSET_51:
690
0
    case ALTSET_71:
691
0
        if (s->out.channels != altset_channels[altset]) {
692
0
            usb_audio_reinit(USB_DEVICE(s), altset_channels[altset]);
693
0
        }
694
0
        streambuf_init(&s->out.buf, s->buffer, s->out.channels);
695
0
        audio_be_set_active_out(s->audio_be, s->out.voice, true);
696
0
        break;
697
0
    default:
698
0
        return -1;
699
882
    }
700
701
882
    if (s->debug) {
702
0
        fprintf(stderr, "usb-audio: set interface %d\n", altset);
703
0
    }
704
882
    s->out.altset = altset;
705
882
    return 0;
706
882
}
707
708
/*
709
 * Note: we arbitrarily map the volume control range onto -inf..+8 dB
710
 */
711
#define ATTRIB_ID(cs, attrib, idif)     \
712
0
    (((cs) << 24) | ((attrib) << 16) | (idif))
713
714
static int usb_audio_get_control(USBAudioState *s, uint8_t attrib,
715
                                 uint16_t cscn, uint16_t idif,
716
                                 int length, uint8_t *data)
717
0
{
718
0
    uint8_t cs = cscn >> 8;
719
0
    uint8_t cn = cscn - 1;      /* -1 for the non-present master control */
720
0
    uint32_t aid = ATTRIB_ID(cs, attrib, idif);
721
0
    int ret = USB_RET_STALL;
722
723
0
    switch (aid) {
724
0
    case ATTRIB_ID(MUTE_CONTROL, CR_GET_CUR, 0x0200):
725
0
        data[0] = s->out.vol.mute;
726
0
        ret = 1;
727
0
        break;
728
0
    case ATTRIB_ID(VOLUME_CONTROL, CR_GET_CUR, 0x0200):
729
0
        if (cn < USBAUDIO_MAX_CHANNELS(s)) {
730
0
            uint16_t vol = (s->out.vol.vol[cn] * 0x8800 + 127) / 255 + 0x8000;
731
0
            data[0] = vol;
732
0
            data[1] = vol >> 8;
733
0
            ret = 2;
734
0
        }
735
0
        break;
736
0
    case ATTRIB_ID(VOLUME_CONTROL, CR_GET_MIN, 0x0200):
737
0
        if (cn < USBAUDIO_MAX_CHANNELS(s)) {
738
0
            data[0] = 0x01;
739
0
            data[1] = 0x80;
740
0
            ret = 2;
741
0
        }
742
0
        break;
743
0
    case ATTRIB_ID(VOLUME_CONTROL, CR_GET_MAX, 0x0200):
744
0
        if (cn < USBAUDIO_MAX_CHANNELS(s)) {
745
0
            data[0] = 0x00;
746
0
            data[1] = 0x08;
747
0
            ret = 2;
748
0
        }
749
0
        break;
750
0
    case ATTRIB_ID(VOLUME_CONTROL, CR_GET_RES, 0x0200):
751
0
        if (cn < USBAUDIO_MAX_CHANNELS(s)) {
752
0
            data[0] = 0x88;
753
0
            data[1] = 0x00;
754
0
            ret = 2;
755
0
        }
756
0
        break;
757
0
    }
758
759
0
    return ret;
760
0
}
761
static int usb_audio_set_control(USBAudioState *s, uint8_t attrib,
762
                                 uint16_t cscn, uint16_t idif,
763
                                 int length, uint8_t *data)
764
0
{
765
0
    uint8_t cs = cscn >> 8;
766
0
    uint8_t cn = cscn - 1;      /* -1 for the non-present master control */
767
0
    uint32_t aid = ATTRIB_ID(cs, attrib, idif);
768
0
    int ret = USB_RET_STALL;
769
0
    bool set_vol = false;
770
771
0
    switch (aid) {
772
0
    case ATTRIB_ID(MUTE_CONTROL, CR_SET_CUR, 0x0200):
773
0
        s->out.vol.mute = data[0] & 1;
774
0
        set_vol = true;
775
0
        ret = 0;
776
0
        break;
777
0
    case ATTRIB_ID(VOLUME_CONTROL, CR_SET_CUR, 0x0200):
778
0
        if (cn < USBAUDIO_MAX_CHANNELS(s)) {
779
0
            uint16_t vol = data[0] + (data[1] << 8);
780
781
0
            if (s->debug) {
782
0
                fprintf(stderr, "usb-audio: cn %d vol %04x\n", cn,
783
0
                        (uint16_t)vol);
784
0
            }
785
786
0
            vol -= 0x8000;
787
0
            vol = (vol * 255 + 0x4400) / 0x8800;
788
0
            if (vol > 255) {
789
0
                vol = 255;
790
0
            }
791
792
0
            s->out.vol.vol[cn] = vol;
793
0
            set_vol = true;
794
0
            ret = 0;
795
0
        }
796
0
        break;
797
0
    }
798
799
0
    if (set_vol) {
800
0
        if (s->debug) {
801
0
            int i;
802
0
            fprintf(stderr, "usb-audio: mute %d", s->out.vol.mute);
803
0
            for (i = 0; i < USBAUDIO_MAX_CHANNELS(s); ++i) {
804
0
                fprintf(stderr, ", vol[%d] %3d", i, s->out.vol.vol[i]);
805
0
            }
806
0
            fprintf(stderr, "\n");
807
0
        }
808
0
        audio_be_set_volume_out(s->audio_be, s->out.voice, &s->out.vol);
809
0
    }
810
811
0
    return ret;
812
0
}
813
814
static void usb_audio_handle_control(USBDevice *dev, USBPacket *p,
815
                                    int request, int value, int index,
816
                                    int length, uint8_t *data)
817
48
{
818
48
    USBAudioState *s = USB_AUDIO(dev);
819
48
    int ret = 0;
820
821
48
    if (s->debug) {
822
0
        fprintf(stderr, "usb-audio: control transaction: "
823
0
                "request 0x%04x value 0x%04x index 0x%04x length 0x%04x\n",
824
0
                request, value, index, length);
825
0
    }
826
827
48
    ret = usb_desc_handle_control(dev, p, request, value, index, length, data);
828
48
    if (ret >= 0) {
829
48
        return;
830
48
    }
831
832
0
    switch (request) {
833
0
    case ClassInterfaceRequest | CR_GET_CUR:
834
0
    case ClassInterfaceRequest | CR_GET_MIN:
835
0
    case ClassInterfaceRequest | CR_GET_MAX:
836
0
    case ClassInterfaceRequest | CR_GET_RES:
837
0
        ret = usb_audio_get_control(s, request & 0xff, value, index,
838
0
                                    length, data);
839
0
        if (ret < 0) {
840
0
            if (s->debug) {
841
0
                fprintf(stderr, "usb-audio: fail: get control\n");
842
0
            }
843
0
            goto fail;
844
0
        }
845
0
        p->actual_length = ret;
846
0
        break;
847
848
0
    case ClassInterfaceOutRequest | CR_SET_CUR:
849
0
    case ClassInterfaceOutRequest | CR_SET_MIN:
850
0
    case ClassInterfaceOutRequest | CR_SET_MAX:
851
0
    case ClassInterfaceOutRequest | CR_SET_RES:
852
0
        ret = usb_audio_set_control(s, request & 0xff, value, index,
853
0
                                    length, data);
854
0
        if (ret < 0) {
855
0
            if (s->debug) {
856
0
                fprintf(stderr, "usb-audio: fail: set control\n");
857
0
            }
858
0
            goto fail;
859
0
        }
860
0
        break;
861
862
0
    default:
863
0
fail:
864
0
        if (s->debug) {
865
0
            fprintf(stderr, "usb-audio: failed control transaction: "
866
0
                    "request 0x%04x value 0x%04x index 0x%04x length 0x%04x\n",
867
0
                    request, value, index, length);
868
0
        }
869
0
        p->status = USB_RET_STALL;
870
0
        break;
871
0
    }
872
0
}
873
874
static void usb_audio_set_interface(USBDevice *dev, int iface,
875
                                    int old, int value)
876
0
{
877
0
    USBAudioState *s = USB_AUDIO(dev);
878
879
0
    if (iface == 1) {
880
0
        usb_audio_set_output_altset(s, value);
881
0
    }
882
0
}
883
884
static void usb_audio_handle_reset(USBDevice *dev)
885
882
{
886
882
    USBAudioState *s = USB_AUDIO(dev);
887
888
882
    if (s->debug) {
889
0
        fprintf(stderr, "usb-audio: reset\n");
890
0
    }
891
882
    usb_audio_set_output_altset(s, ALTSET_OFF);
892
882
}
893
894
static void usb_audio_handle_dataout(USBAudioState *s, USBPacket *p)
895
0
{
896
0
    if (s->out.altset == ALTSET_OFF) {
897
0
        p->status = USB_RET_STALL;
898
0
        return;
899
0
    }
900
901
0
    streambuf_put(&s->out.buf, p, s->out.channels);
902
0
    if (p->actual_length < p->iov.size && s->debug > 1) {
903
0
        fprintf(stderr, "usb-audio: output overrun (%zd bytes)\n",
904
0
                p->iov.size - p->actual_length);
905
0
    }
906
0
}
907
908
static void usb_audio_handle_data(USBDevice *dev, USBPacket *p)
909
4
{
910
4
    USBAudioState *s = (USBAudioState *) dev;
911
912
4
    if (p->pid == USB_TOKEN_OUT && p->ep->nr == 1) {
913
0
        usb_audio_handle_dataout(s, p);
914
0
        return;
915
0
    }
916
917
4
    p->status = USB_RET_STALL;
918
4
    if (s->debug) {
919
0
        fprintf(stderr, "usb-audio: failed data transaction: "
920
0
                        "pid 0x%x ep 0x%x len 0x%zx\n",
921
0
                        p->pid, p->ep->nr, p->iov.size);
922
0
    }
923
4
}
924
925
static void usb_audio_unrealize(USBDevice *dev)
926
0
{
927
0
    USBAudioState *s = USB_AUDIO(dev);
928
929
0
    if (s->debug) {
930
0
        fprintf(stderr, "usb-audio: destroy\n");
931
0
    }
932
933
0
    usb_audio_set_output_altset(s, ALTSET_OFF);
934
0
    audio_be_close_out(s->audio_be, s->out.voice);
935
936
0
    streambuf_fini(&s->out.buf);
937
0
}
938
939
static void usb_audio_realize(USBDevice *dev, Error **errp)
940
2
{
941
2
    USBAudioState *s = USB_AUDIO(dev);
942
2
    int i;
943
944
2
    if (!audio_be_check(&s->audio_be, errp)) {
945
0
        return;
946
0
    }
947
948
2
    dev->usb_desc = s->multi ? &desc_audio_multi : &desc_audio;
949
950
2
    usb_desc_create_serial(dev);
951
2
    usb_desc_init(dev);
952
2
    s->dev.opaque = s;
953
954
2
    s->out.altset        = ALTSET_OFF;
955
2
    s->out.vol.mute      = false;
956
6
    for (i = 0; i < USBAUDIO_MAX_CHANNELS(s); ++i) {
957
4
        s->out.vol.vol[i] = 240; /* 0 dB */
958
4
    }
959
960
2
    usb_audio_reinit(dev, 2);
961
2
}
962
963
static void usb_audio_reinit(USBDevice *dev, unsigned channels)
964
2
{
965
2
    USBAudioState *s = USB_AUDIO(dev);
966
967
2
    s->out.channels      = channels;
968
2
    if (!s->buffer_user) {
969
2
        s->buffer = 32 * USBAUDIO_PACKET_SIZE(s->out.channels);
970
2
    } else {
971
0
        s->buffer = s->buffer_user;
972
0
    }
973
974
2
    s->out.vol.channels  = s->out.channels;
975
2
    s->out.as.freq       = USBAUDIO_SAMPLE_RATE;
976
2
    s->out.as.nchannels  = s->out.channels;
977
2
    s->out.as.fmt        = AUDIO_FORMAT_S16;
978
2
    s->out.as.big_endian = false;
979
2
    streambuf_init(&s->out.buf, s->buffer, s->out.channels);
980
981
2
    s->out.voice = audio_be_open_out(s->audio_be, s->out.voice, TYPE_USB_AUDIO,
982
2
                                s, output_callback, &s->out.as);
983
2
    audio_be_set_volume_out(s->audio_be, s->out.voice, &s->out.vol);
984
2
    audio_be_set_active_out(s->audio_be, s->out.voice, 0);
985
2
}
986
987
static const VMStateDescription vmstate_usb_audio = {
988
    .name = TYPE_USB_AUDIO,
989
    .unmigratable = 1,
990
};
991
992
static const Property usb_audio_properties[] = {
993
    DEFINE_AUDIO_PROPERTIES(USBAudioState, audio_be),
994
    DEFINE_PROP_UINT32("debug", USBAudioState, debug, 0),
995
    DEFINE_PROP_UINT32("buffer", USBAudioState, buffer_user, 0),
996
    DEFINE_PROP_BOOL("multi", USBAudioState, multi, false),
997
};
998
999
static void usb_audio_class_init(ObjectClass *klass, const void *data)
1000
63
{
1001
63
    DeviceClass *dc = DEVICE_CLASS(klass);
1002
63
    USBDeviceClass *k = USB_DEVICE_CLASS(klass);
1003
1004
63
    dc->vmsd          = &vmstate_usb_audio;
1005
63
    device_class_set_props(dc, usb_audio_properties);
1006
63
    set_bit(DEVICE_CATEGORY_SOUND, dc->categories);
1007
63
    k->product_desc   = "QEMU USB Audio Interface";
1008
63
    k->realize        = usb_audio_realize;
1009
63
    k->handle_reset   = usb_audio_handle_reset;
1010
63
    k->handle_control = usb_audio_handle_control;
1011
63
    k->handle_data    = usb_audio_handle_data;
1012
63
    k->unrealize      = usb_audio_unrealize;
1013
63
    k->set_interface  = usb_audio_set_interface;
1014
63
}
1015
1016
static const TypeInfo usb_audio_info = {
1017
    .name          = TYPE_USB_AUDIO,
1018
    .parent        = TYPE_USB_DEVICE,
1019
    .instance_size = sizeof(USBAudioState),
1020
    .class_init    = usb_audio_class_init,
1021
};
1022
1023
static void usb_audio_register_types(void)
1024
63
{
1025
63
    type_register_static(&usb_audio_info);
1026
63
}
1027
1028
type_init(usb_audio_register_types)