xref: /qemu/hw/usb/dev-audio.c (revision db1015e92e04835c9eb50c29625fe566d1202dbd)
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/qdev-properties.h"
35 #include "hw/usb.h"
36 #include "migration/vmstate.h"
37 #include "desc.h"
38 #include "audio/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 #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 #define USBAUDIO_PACKET_SIZE_BASE 96
117 #define USBAUDIO_PACKET_SIZE(channels) (USBAUDIO_PACKET_SIZE_BASE * channels)
118 #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         .bInterfaceProtocol            = 0x04,
128         .iInterface                    = STRING_USBAUDIO_CONTROL,
129         .ndesc                         = 4,
130         .descs = (USBDescOther[]) {
131             {
132                 /* Headphone Class-Specific AC Interface Header Descriptor */
133                 .data = (uint8_t[]) {
134                     0x09,                       /*  u8  bLength */
135                     USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
136                     DST_AC_HEADER,              /*  u8  bDescriptorSubtype */
137                     U16(0x0100),                /* u16  bcdADC */
138                     U16(0x2b),                  /* u16  wTotalLength */
139                     0x01,                       /*  u8  bInCollection */
140                     0x01,                       /*  u8  baInterfaceNr */
141                 }
142             },{
143                 /* Generic Stereo Input Terminal ID1 Descriptor */
144                 .data = (uint8_t[]) {
145                     0x0c,                       /*  u8  bLength */
146                     USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
147                     DST_AC_INPUT_TERMINAL,      /*  u8  bDescriptorSubtype */
148                     0x01,                       /*  u8  bTerminalID */
149                     U16(0x0101),                /* u16  wTerminalType */
150                     0x00,                       /*  u8  bAssocTerminal */
151                     0x02,                       /*  u8  bNrChannels */
152                     U16(0x0003),                /* u16  wChannelConfig */
153                     0x00,                       /*  u8  iChannelNames */
154                     STRING_INPUT_TERMINAL,      /*  u8  iTerminal */
155                 }
156             },{
157                 /* Generic Stereo Feature Unit ID2 Descriptor */
158                 .data = (uint8_t[]) {
159                     0x0d,                       /*  u8  bLength */
160                     USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
161                     DST_AC_FEATURE_UNIT,        /*  u8  bDescriptorSubtype */
162                     0x02,                       /*  u8  bUnitID */
163                     0x01,                       /*  u8  bSourceID */
164                     0x02,                       /*  u8  bControlSize */
165                     U16(0x0001),                /* u16  bmaControls(0) */
166                     U16(0x0002),                /* u16  bmaControls(1) */
167                     U16(0x0002),                /* u16  bmaControls(2) */
168                     STRING_FEATURE_UNIT,        /*  u8  iFeature */
169                 }
170             },{
171                 /* Headphone Ouptut Terminal ID3 Descriptor */
172                 .data = (uint8_t[]) {
173                     0x09,                       /*  u8  bLength */
174                     USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
175                     DST_AC_OUTPUT_TERMINAL,     /*  u8  bDescriptorSubtype */
176                     0x03,                       /*  u8  bUnitID */
177                     U16(0x0301),                /* u16  wTerminalType (SPK) */
178                     0x00,                       /*  u8  bAssocTerminal */
179                     0x02,                       /*  u8  bSourceID */
180                     STRING_OUTPUT_TERMINAL,     /*  u8  iTerminal */
181                 }
182             }
183         },
184     },{
185         .bInterfaceNumber              = 1,
186         .bAlternateSetting             = ALTSET_OFF,
187         .bNumEndpoints                 = 0,
188         .bInterfaceClass               = USB_CLASS_AUDIO,
189         .bInterfaceSubClass            = USB_SUBCLASS_AUDIO_STREAMING,
190         .iInterface                    = STRING_NULL_STREAM,
191     },{
192         .bInterfaceNumber              = 1,
193         .bAlternateSetting             = ALTSET_STEREO,
194         .bNumEndpoints                 = 1,
195         .bInterfaceClass               = USB_CLASS_AUDIO,
196         .bInterfaceSubClass            = USB_SUBCLASS_AUDIO_STREAMING,
197         .iInterface                    = STRING_REAL_STREAM,
198         .ndesc                         = 2,
199         .descs = (USBDescOther[]) {
200             {
201                 /* Headphone Class-specific AS General Interface Descriptor */
202                 .data = (uint8_t[]) {
203                     0x07,                       /*  u8  bLength */
204                     USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
205                     DST_AS_GENERAL,             /*  u8  bDescriptorSubtype */
206                     0x01,                       /*  u8  bTerminalLink */
207                     0x00,                       /*  u8  bDelay */
208                     0x01, 0x00,                 /* u16  wFormatTag */
209                 }
210             },{
211                 /* Headphone Type I Format Type Descriptor */
212                 .data = (uint8_t[]) {
213                     0x0b,                       /*  u8  bLength */
214                     USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
215                     DST_AS_FORMAT_TYPE,         /*  u8  bDescriptorSubtype */
216                     0x01,                       /*  u8  bFormatType */
217                     0x02,                       /*  u8  bNrChannels */
218                     0x02,                       /*  u8  bSubFrameSize */
219                     0x10,                       /*  u8  bBitResolution */
220                     0x01,                       /*  u8  bSamFreqType */
221                     U24(USBAUDIO_SAMPLE_RATE),  /* u24  tSamFreq */
222                 }
223             }
224         },
225         .eps = (USBDescEndpoint[]) {
226             {
227                 .bEndpointAddress      = USB_DIR_OUT | 0x01,
228                 .bmAttributes          = 0x0d,
229                 .wMaxPacketSize        = USBAUDIO_PACKET_SIZE(2),
230                 .bInterval             = 1,
231                 .is_audio              = 1,
232                 /* Stereo Headphone Class-specific
233                    AS Audio Data Endpoint Descriptor */
234                 .extra = (uint8_t[]) {
235                     0x07,                       /*  u8  bLength */
236                     USB_DT_CS_ENDPOINT,         /*  u8  bDescriptorType */
237                     DST_EP_GENERAL,             /*  u8  bDescriptorSubtype */
238                     0x00,                       /*  u8  bmAttributes */
239                     0x00,                       /*  u8  bLockDelayUnits */
240                     U16(0x0000),                /* u16  wLockDelay */
241                 },
242             },
243         }
244     }
245 };
246 
247 static const USBDescDevice desc_device = {
248     .bcdUSB                        = 0x0100,
249     .bMaxPacketSize0               = 64,
250     .bNumConfigurations            = 1,
251     .confs = (USBDescConfig[]) {
252         {
253             .bNumInterfaces        = 2,
254             .bConfigurationValue   = DEV_CONFIG_VALUE,
255             .iConfiguration        = STRING_CONFIG,
256             .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_SELFPOWER,
257             .bMaxPower             = 0x32,
258             .nif = ARRAY_SIZE(desc_iface),
259             .ifs = desc_iface,
260         },
261     },
262 };
263 
264 static const USBDesc desc_audio = {
265     .id = {
266         .idVendor          = USBAUDIO_VENDOR_NUM,
267         .idProduct         = USBAUDIO_PRODUCT_NUM,
268         .bcdDevice         = 0,
269         .iManufacturer     = STRING_MANUFACTURER,
270         .iProduct          = STRING_PRODUCT,
271         .iSerialNumber     = STRING_SERIALNUMBER,
272     },
273     .full = &desc_device,
274     .str  = usb_audio_stringtable,
275 };
276 
277 /* multi channel compatible desc */
278 
279 static const USBDescIface desc_iface_multi[] = {
280     {
281         .bInterfaceNumber              = 0,
282         .bNumEndpoints                 = 0,
283         .bInterfaceClass               = USB_CLASS_AUDIO,
284         .bInterfaceSubClass            = USB_SUBCLASS_AUDIO_CONTROL,
285         .bInterfaceProtocol            = 0x04,
286         .iInterface                    = STRING_USBAUDIO_CONTROL,
287         .ndesc                         = 4,
288         .descs = (USBDescOther[]) {
289             {
290                 /* Headphone Class-Specific AC Interface Header Descriptor */
291                 .data = (uint8_t[]) {
292                     0x09,                       /*  u8  bLength */
293                     USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
294                     DST_AC_HEADER,              /*  u8  bDescriptorSubtype */
295                     U16(0x0100),                /* u16  bcdADC */
296                     U16(0x38),                  /* u16  wTotalLength */
297                     0x01,                       /*  u8  bInCollection */
298                     0x01,                       /*  u8  baInterfaceNr */
299                 }
300             },{
301                 /* Generic Stereo Input Terminal ID1 Descriptor */
302                 .data = (uint8_t[]) {
303                     0x0c,                       /*  u8  bLength */
304                     USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
305                     DST_AC_INPUT_TERMINAL,      /*  u8  bDescriptorSubtype */
306                     0x01,                       /*  u8  bTerminalID */
307                     U16(0x0101),                /* u16  wTerminalType */
308                     0x00,                       /*  u8  bAssocTerminal */
309                     0x08,                       /*  u8  bNrChannels */
310                     U16(0x063f),                /* u16  wChannelConfig */
311                     0x00,                       /*  u8  iChannelNames */
312                     STRING_INPUT_TERMINAL,      /*  u8  iTerminal */
313                 }
314             },{
315                 /* Generic Stereo Feature Unit ID2 Descriptor */
316                 .data = (uint8_t[]) {
317                     0x19,                       /*  u8  bLength */
318                     USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
319                     DST_AC_FEATURE_UNIT,        /*  u8  bDescriptorSubtype */
320                     0x02,                       /*  u8  bUnitID */
321                     0x01,                       /*  u8  bSourceID */
322                     0x02,                       /*  u8  bControlSize */
323                     U16(0x0001),                /* u16  bmaControls(0) */
324                     U16(0x0002),                /* u16  bmaControls(1) */
325                     U16(0x0002),                /* u16  bmaControls(2) */
326                     U16(0x0002),                /* u16  bmaControls(3) */
327                     U16(0x0002),                /* u16  bmaControls(4) */
328                     U16(0x0002),                /* u16  bmaControls(5) */
329                     U16(0x0002),                /* u16  bmaControls(6) */
330                     U16(0x0002),                /* u16  bmaControls(7) */
331                     U16(0x0002),                /* u16  bmaControls(8) */
332                     STRING_FEATURE_UNIT,        /*  u8  iFeature */
333                 }
334             },{
335                 /* Headphone Ouptut Terminal ID3 Descriptor */
336                 .data = (uint8_t[]) {
337                     0x09,                       /*  u8  bLength */
338                     USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
339                     DST_AC_OUTPUT_TERMINAL,     /*  u8  bDescriptorSubtype */
340                     0x03,                       /*  u8  bUnitID */
341                     U16(0x0301),                /* u16  wTerminalType (SPK) */
342                     0x00,                       /*  u8  bAssocTerminal */
343                     0x02,                       /*  u8  bSourceID */
344                     STRING_OUTPUT_TERMINAL,     /*  u8  iTerminal */
345                 }
346             }
347         },
348     },{
349         .bInterfaceNumber              = 1,
350         .bAlternateSetting             = ALTSET_OFF,
351         .bNumEndpoints                 = 0,
352         .bInterfaceClass               = USB_CLASS_AUDIO,
353         .bInterfaceSubClass            = USB_SUBCLASS_AUDIO_STREAMING,
354         .iInterface                    = STRING_NULL_STREAM,
355     },{
356         .bInterfaceNumber              = 1,
357         .bAlternateSetting             = ALTSET_STEREO,
358         .bNumEndpoints                 = 1,
359         .bInterfaceClass               = USB_CLASS_AUDIO,
360         .bInterfaceSubClass            = USB_SUBCLASS_AUDIO_STREAMING,
361         .iInterface                    = STRING_REAL_STREAM,
362         .ndesc                         = 2,
363         .descs = (USBDescOther[]) {
364             {
365                 /* Headphone Class-specific AS General Interface Descriptor */
366                 .data = (uint8_t[]) {
367                     0x07,                       /*  u8  bLength */
368                     USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
369                     DST_AS_GENERAL,             /*  u8  bDescriptorSubtype */
370                     0x01,                       /*  u8  bTerminalLink */
371                     0x00,                       /*  u8  bDelay */
372                     0x01, 0x00,                 /* u16  wFormatTag */
373                 }
374             },{
375                 /* Headphone Type I Format Type Descriptor */
376                 .data = (uint8_t[]) {
377                     0x0b,                       /*  u8  bLength */
378                     USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
379                     DST_AS_FORMAT_TYPE,         /*  u8  bDescriptorSubtype */
380                     0x01,                       /*  u8  bFormatType */
381                     0x02,                       /*  u8  bNrChannels */
382                     0x02,                       /*  u8  bSubFrameSize */
383                     0x10,                       /*  u8  bBitResolution */
384                     0x01,                       /*  u8  bSamFreqType */
385                     U24(USBAUDIO_SAMPLE_RATE),  /* u24  tSamFreq */
386                 }
387             }
388         },
389         .eps = (USBDescEndpoint[]) {
390             {
391                 .bEndpointAddress      = USB_DIR_OUT | 0x01,
392                 .bmAttributes          = 0x0d,
393                 .wMaxPacketSize        = USBAUDIO_PACKET_SIZE(2),
394                 .bInterval             = 1,
395                 .is_audio              = 1,
396                 /* Stereo Headphone Class-specific
397                    AS Audio Data Endpoint Descriptor */
398                 .extra = (uint8_t[]) {
399                     0x07,                       /*  u8  bLength */
400                     USB_DT_CS_ENDPOINT,         /*  u8  bDescriptorType */
401                     DST_EP_GENERAL,             /*  u8  bDescriptorSubtype */
402                     0x00,                       /*  u8  bmAttributes */
403                     0x00,                       /*  u8  bLockDelayUnits */
404                     U16(0x0000),                /* u16  wLockDelay */
405                 },
406             },
407         }
408     },{
409         .bInterfaceNumber              = 1,
410         .bAlternateSetting             = ALTSET_51,
411         .bNumEndpoints                 = 1,
412         .bInterfaceClass               = USB_CLASS_AUDIO,
413         .bInterfaceSubClass            = USB_SUBCLASS_AUDIO_STREAMING,
414         .iInterface                    = STRING_REAL_STREAM,
415         .ndesc                         = 2,
416         .descs = (USBDescOther[]) {
417             {
418                 /* Headphone Class-specific AS General Interface Descriptor */
419                 .data = (uint8_t[]) {
420                     0x07,                       /*  u8  bLength */
421                     USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
422                     DST_AS_GENERAL,             /*  u8  bDescriptorSubtype */
423                     0x01,                       /*  u8  bTerminalLink */
424                     0x00,                       /*  u8  bDelay */
425                     0x01, 0x00,                 /* u16  wFormatTag */
426                 }
427             },{
428                 /* Headphone Type I Format Type Descriptor */
429                 .data = (uint8_t[]) {
430                     0x0b,                       /*  u8  bLength */
431                     USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
432                     DST_AS_FORMAT_TYPE,         /*  u8  bDescriptorSubtype */
433                     0x01,                       /*  u8  bFormatType */
434                     0x06,                       /*  u8  bNrChannels */
435                     0x02,                       /*  u8  bSubFrameSize */
436                     0x10,                       /*  u8  bBitResolution */
437                     0x01,                       /*  u8  bSamFreqType */
438                     U24(USBAUDIO_SAMPLE_RATE),  /* u24  tSamFreq */
439                 }
440             }
441         },
442         .eps = (USBDescEndpoint[]) {
443             {
444                 .bEndpointAddress      = USB_DIR_OUT | 0x01,
445                 .bmAttributes          = 0x0d,
446                 .wMaxPacketSize        = USBAUDIO_PACKET_SIZE(6),
447                 .bInterval             = 1,
448                 .is_audio              = 1,
449                 /* Stereo Headphone Class-specific
450                    AS Audio Data Endpoint Descriptor */
451                 .extra = (uint8_t[]) {
452                     0x07,                       /*  u8  bLength */
453                     USB_DT_CS_ENDPOINT,         /*  u8  bDescriptorType */
454                     DST_EP_GENERAL,             /*  u8  bDescriptorSubtype */
455                     0x00,                       /*  u8  bmAttributes */
456                     0x00,                       /*  u8  bLockDelayUnits */
457                     U16(0x0000),                /* u16  wLockDelay */
458                 },
459             },
460         }
461     },{
462         .bInterfaceNumber              = 1,
463         .bAlternateSetting             = ALTSET_71,
464         .bNumEndpoints                 = 1,
465         .bInterfaceClass               = USB_CLASS_AUDIO,
466         .bInterfaceSubClass            = USB_SUBCLASS_AUDIO_STREAMING,
467         .iInterface                    = STRING_REAL_STREAM,
468         .ndesc                         = 2,
469         .descs = (USBDescOther[]) {
470             {
471                 /* Headphone Class-specific AS General Interface Descriptor */
472                 .data = (uint8_t[]) {
473                     0x07,                       /*  u8  bLength */
474                     USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
475                     DST_AS_GENERAL,             /*  u8  bDescriptorSubtype */
476                     0x01,                       /*  u8  bTerminalLink */
477                     0x00,                       /*  u8  bDelay */
478                     0x01, 0x00,                 /* u16  wFormatTag */
479                 }
480             },{
481                 /* Headphone Type I Format Type Descriptor */
482                 .data = (uint8_t[]) {
483                     0x0b,                       /*  u8  bLength */
484                     USB_DT_CS_INTERFACE,        /*  u8  bDescriptorType */
485                     DST_AS_FORMAT_TYPE,         /*  u8  bDescriptorSubtype */
486                     0x01,                       /*  u8  bFormatType */
487                     0x08,                       /*  u8  bNrChannels */
488                     0x02,                       /*  u8  bSubFrameSize */
489                     0x10,                       /*  u8  bBitResolution */
490                     0x01,                       /*  u8  bSamFreqType */
491                     U24(USBAUDIO_SAMPLE_RATE),  /* u24  tSamFreq */
492                 }
493             }
494         },
495         .eps = (USBDescEndpoint[]) {
496             {
497                 .bEndpointAddress      = USB_DIR_OUT | 0x01,
498                 .bmAttributes          = 0x0d,
499                 .wMaxPacketSize        = USBAUDIO_PACKET_SIZE(8),
500                 .bInterval             = 1,
501                 .is_audio              = 1,
502                 /* Stereo Headphone Class-specific
503                    AS Audio Data Endpoint Descriptor */
504                 .extra = (uint8_t[]) {
505                     0x07,                       /*  u8  bLength */
506                     USB_DT_CS_ENDPOINT,         /*  u8  bDescriptorType */
507                     DST_EP_GENERAL,             /*  u8  bDescriptorSubtype */
508                     0x00,                       /*  u8  bmAttributes */
509                     0x00,                       /*  u8  bLockDelayUnits */
510                     U16(0x0000),                /* u16  wLockDelay */
511                 },
512             },
513         }
514     }
515 };
516 
517 static const USBDescDevice desc_device_multi = {
518     .bcdUSB                        = 0x0100,
519     .bMaxPacketSize0               = 64,
520     .bNumConfigurations            = 1,
521     .confs = (USBDescConfig[]) {
522         {
523             .bNumInterfaces        = 2,
524             .bConfigurationValue   = DEV_CONFIG_VALUE,
525             .iConfiguration        = STRING_CONFIG,
526             .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_SELFPOWER,
527             .bMaxPower             = 0x32,
528             .nif = ARRAY_SIZE(desc_iface_multi),
529             .ifs = desc_iface_multi,
530         }
531     },
532 };
533 
534 static const USBDesc desc_audio_multi = {
535     .id = {
536         .idVendor          = USBAUDIO_VENDOR_NUM,
537         .idProduct         = USBAUDIO_PRODUCT_NUM,
538         .bcdDevice         = 0,
539         .iManufacturer     = STRING_MANUFACTURER,
540         .iProduct          = STRING_PRODUCT,
541         .iSerialNumber     = STRING_SERIALNUMBER,
542     },
543     .full = &desc_device_multi,
544     .str  = usb_audio_stringtable,
545 };
546 
547 /*
548  * Class-specific control requests
549  */
550 #define CR_SET_CUR      0x01
551 #define CR_GET_CUR      0x81
552 #define CR_SET_MIN      0x02
553 #define CR_GET_MIN      0x82
554 #define CR_SET_MAX      0x03
555 #define CR_GET_MAX      0x83
556 #define CR_SET_RES      0x04
557 #define CR_GET_RES      0x84
558 #define CR_SET_MEM      0x05
559 #define CR_GET_MEM      0x85
560 #define CR_GET_STAT     0xff
561 
562 /*
563  * Feature Unit Control Selectors
564  */
565 #define MUTE_CONTROL                    0x01
566 #define VOLUME_CONTROL                  0x02
567 #define BASS_CONTROL                    0x03
568 #define MID_CONTROL                     0x04
569 #define TREBLE_CONTROL                  0x05
570 #define GRAPHIC_EQUALIZER_CONTROL       0x06
571 #define AUTOMATIC_GAIN_CONTROL          0x07
572 #define DELAY_CONTROL                   0x08
573 #define BASS_BOOST_CONTROL              0x09
574 #define LOUDNESS_CONTROL                0x0a
575 
576 /*
577  * buffering
578  */
579 
580 struct streambuf {
581     uint8_t *data;
582     size_t size;
583     uint64_t prod;
584     uint64_t cons;
585 };
586 
587 static void streambuf_init(struct streambuf *buf, uint32_t size,
588                            uint32_t channels)
589 {
590     g_free(buf->data);
591     buf->size = size - (size % USBAUDIO_PACKET_SIZE(channels));
592     buf->data = g_malloc(buf->size);
593     buf->prod = 0;
594     buf->cons = 0;
595 }
596 
597 static void streambuf_fini(struct streambuf *buf)
598 {
599     g_free(buf->data);
600     buf->data = NULL;
601 }
602 
603 static int streambuf_put(struct streambuf *buf, USBPacket *p, uint32_t channels)
604 {
605     int64_t free = buf->size - (buf->prod - buf->cons);
606 
607     if (free < USBAUDIO_PACKET_SIZE(channels)) {
608         return 0;
609     }
610     if (p->iov.size != USBAUDIO_PACKET_SIZE(channels)) {
611         return 0;
612     }
613 
614     /* can happen if prod overflows */
615     assert(buf->prod % USBAUDIO_PACKET_SIZE(channels) == 0);
616     usb_packet_copy(p, buf->data + (buf->prod % buf->size),
617                     USBAUDIO_PACKET_SIZE(channels));
618     buf->prod += USBAUDIO_PACKET_SIZE(channels);
619     return USBAUDIO_PACKET_SIZE(channels);
620 }
621 
622 static uint8_t *streambuf_get(struct streambuf *buf, size_t *len)
623 {
624     int64_t used = buf->prod - buf->cons;
625     uint8_t *data;
626 
627     if (used <= 0) {
628         *len = 0;
629         return NULL;
630     }
631     data = buf->data + (buf->cons % buf->size);
632     *len = MIN(buf->prod - buf->cons,
633                buf->size - (buf->cons % buf->size));
634     return data;
635 }
636 
637 struct USBAudioState {
638     /* qemu interfaces */
639     USBDevice dev;
640     QEMUSoundCard card;
641 
642     /* state */
643     struct {
644         enum usb_audio_altset altset;
645         struct audsettings as;
646         SWVoiceOut *voice;
647         Volume vol;
648         struct streambuf buf;
649         uint32_t channels;
650     } out;
651 
652     /* properties */
653     uint32_t debug;
654     uint32_t buffer_user, buffer;
655     bool multi;
656 };
657 typedef struct USBAudioState USBAudioState;
658 
659 #define TYPE_USB_AUDIO "usb-audio"
660 #define USB_AUDIO(obj) OBJECT_CHECK(USBAudioState, (obj), TYPE_USB_AUDIO)
661 
662 static void output_callback(void *opaque, int avail)
663 {
664     USBAudioState *s = opaque;
665     uint8_t *data;
666 
667     while (avail) {
668         size_t written, len;
669 
670         data = streambuf_get(&s->out.buf, &len);
671         if (!data) {
672             return;
673         }
674 
675         written = AUD_write(s->out.voice, data, len);
676         avail -= written;
677         s->out.buf.cons += written;
678 
679         if (written < len) {
680             return;
681         }
682     }
683 }
684 
685 static int usb_audio_set_output_altset(USBAudioState *s, int altset)
686 {
687     switch (altset) {
688     case ALTSET_OFF:
689         AUD_set_active_out(s->out.voice, false);
690         break;
691     case ALTSET_STEREO:
692     case ALTSET_51:
693     case ALTSET_71:
694         if (s->out.channels != altset_channels[altset]) {
695             usb_audio_reinit(USB_DEVICE(s), altset_channels[altset]);
696         }
697         streambuf_init(&s->out.buf, s->buffer, s->out.channels);
698         AUD_set_active_out(s->out.voice, true);
699         break;
700     default:
701         return -1;
702     }
703 
704     if (s->debug) {
705         fprintf(stderr, "usb-audio: set interface %d\n", altset);
706     }
707     s->out.altset = altset;
708     return 0;
709 }
710 
711 /*
712  * Note: we arbitrarily map the volume control range onto -inf..+8 dB
713  */
714 #define ATTRIB_ID(cs, attrib, idif)     \
715     (((cs) << 24) | ((attrib) << 16) | (idif))
716 
717 static int usb_audio_get_control(USBAudioState *s, uint8_t attrib,
718                                  uint16_t cscn, uint16_t idif,
719                                  int length, uint8_t *data)
720 {
721     uint8_t cs = cscn >> 8;
722     uint8_t cn = cscn - 1;      /* -1 for the non-present master control */
723     uint32_t aid = ATTRIB_ID(cs, attrib, idif);
724     int ret = USB_RET_STALL;
725 
726     switch (aid) {
727     case ATTRIB_ID(MUTE_CONTROL, CR_GET_CUR, 0x0200):
728         data[0] = s->out.vol.mute;
729         ret = 1;
730         break;
731     case ATTRIB_ID(VOLUME_CONTROL, CR_GET_CUR, 0x0200):
732         if (cn < USBAUDIO_MAX_CHANNELS(s)) {
733             uint16_t vol = (s->out.vol.vol[cn] * 0x8800 + 127) / 255 + 0x8000;
734             data[0] = vol;
735             data[1] = vol >> 8;
736             ret = 2;
737         }
738         break;
739     case ATTRIB_ID(VOLUME_CONTROL, CR_GET_MIN, 0x0200):
740         if (cn < USBAUDIO_MAX_CHANNELS(s)) {
741             data[0] = 0x01;
742             data[1] = 0x80;
743             ret = 2;
744         }
745         break;
746     case ATTRIB_ID(VOLUME_CONTROL, CR_GET_MAX, 0x0200):
747         if (cn < USBAUDIO_MAX_CHANNELS(s)) {
748             data[0] = 0x00;
749             data[1] = 0x08;
750             ret = 2;
751         }
752         break;
753     case ATTRIB_ID(VOLUME_CONTROL, CR_GET_RES, 0x0200):
754         if (cn < USBAUDIO_MAX_CHANNELS(s)) {
755             data[0] = 0x88;
756             data[1] = 0x00;
757             ret = 2;
758         }
759         break;
760     }
761 
762     return ret;
763 }
764 static int usb_audio_set_control(USBAudioState *s, uint8_t attrib,
765                                  uint16_t cscn, uint16_t idif,
766                                  int length, uint8_t *data)
767 {
768     uint8_t cs = cscn >> 8;
769     uint8_t cn = cscn - 1;      /* -1 for the non-present master control */
770     uint32_t aid = ATTRIB_ID(cs, attrib, idif);
771     int ret = USB_RET_STALL;
772     bool set_vol = false;
773 
774     switch (aid) {
775     case ATTRIB_ID(MUTE_CONTROL, CR_SET_CUR, 0x0200):
776         s->out.vol.mute = data[0] & 1;
777         set_vol = true;
778         ret = 0;
779         break;
780     case ATTRIB_ID(VOLUME_CONTROL, CR_SET_CUR, 0x0200):
781         if (cn < USBAUDIO_MAX_CHANNELS(s)) {
782             uint16_t vol = data[0] + (data[1] << 8);
783 
784             if (s->debug) {
785                 fprintf(stderr, "usb-audio: cn %d vol %04x\n", cn,
786                         (uint16_t)vol);
787             }
788 
789             vol -= 0x8000;
790             vol = (vol * 255 + 0x4400) / 0x8800;
791             if (vol > 255) {
792                 vol = 255;
793             }
794 
795             s->out.vol.vol[cn] = vol;
796             set_vol = true;
797             ret = 0;
798         }
799         break;
800     }
801 
802     if (set_vol) {
803         if (s->debug) {
804             int i;
805             fprintf(stderr, "usb-audio: mute %d", s->out.vol.mute);
806             for (i = 0; i < USBAUDIO_MAX_CHANNELS(s); ++i) {
807                 fprintf(stderr, ", vol[%d] %3d", i, s->out.vol.vol[i]);
808             }
809             fprintf(stderr, "\n");
810         }
811         audio_set_volume_out(s->out.voice, &s->out.vol);
812     }
813 
814     return ret;
815 }
816 
817 static void usb_audio_handle_control(USBDevice *dev, USBPacket *p,
818                                     int request, int value, int index,
819                                     int length, uint8_t *data)
820 {
821     USBAudioState *s = USB_AUDIO(dev);
822     int ret = 0;
823 
824     if (s->debug) {
825         fprintf(stderr, "usb-audio: control transaction: "
826                 "request 0x%04x value 0x%04x index 0x%04x length 0x%04x\n",
827                 request, value, index, length);
828     }
829 
830     ret = usb_desc_handle_control(dev, p, request, value, index, length, data);
831     if (ret >= 0) {
832         return;
833     }
834 
835     switch (request) {
836     case ClassInterfaceRequest | CR_GET_CUR:
837     case ClassInterfaceRequest | CR_GET_MIN:
838     case ClassInterfaceRequest | CR_GET_MAX:
839     case ClassInterfaceRequest | CR_GET_RES:
840         ret = usb_audio_get_control(s, request & 0xff, value, index,
841                                     length, data);
842         if (ret < 0) {
843             if (s->debug) {
844                 fprintf(stderr, "usb-audio: fail: get control\n");
845             }
846             goto fail;
847         }
848         p->actual_length = ret;
849         break;
850 
851     case ClassInterfaceOutRequest | CR_SET_CUR:
852     case ClassInterfaceOutRequest | CR_SET_MIN:
853     case ClassInterfaceOutRequest | CR_SET_MAX:
854     case ClassInterfaceOutRequest | CR_SET_RES:
855         ret = usb_audio_set_control(s, request & 0xff, value, index,
856                                     length, data);
857         if (ret < 0) {
858             if (s->debug) {
859                 fprintf(stderr, "usb-audio: fail: set control\n");
860             }
861             goto fail;
862         }
863         break;
864 
865     default:
866 fail:
867         if (s->debug) {
868             fprintf(stderr, "usb-audio: failed control transaction: "
869                     "request 0x%04x value 0x%04x index 0x%04x length 0x%04x\n",
870                     request, value, index, length);
871         }
872         p->status = USB_RET_STALL;
873         break;
874     }
875 }
876 
877 static void usb_audio_set_interface(USBDevice *dev, int iface,
878                                     int old, int value)
879 {
880     USBAudioState *s = USB_AUDIO(dev);
881 
882     if (iface == 1) {
883         usb_audio_set_output_altset(s, value);
884     }
885 }
886 
887 static void usb_audio_handle_reset(USBDevice *dev)
888 {
889     USBAudioState *s = USB_AUDIO(dev);
890 
891     if (s->debug) {
892         fprintf(stderr, "usb-audio: reset\n");
893     }
894     usb_audio_set_output_altset(s, ALTSET_OFF);
895 }
896 
897 static void usb_audio_handle_dataout(USBAudioState *s, USBPacket *p)
898 {
899     if (s->out.altset == ALTSET_OFF) {
900         p->status = USB_RET_STALL;
901         return;
902     }
903 
904     streambuf_put(&s->out.buf, p, s->out.channels);
905     if (p->actual_length < p->iov.size && s->debug > 1) {
906         fprintf(stderr, "usb-audio: output overrun (%zd bytes)\n",
907                 p->iov.size - p->actual_length);
908     }
909 }
910 
911 static void usb_audio_handle_data(USBDevice *dev, USBPacket *p)
912 {
913     USBAudioState *s = (USBAudioState *) dev;
914 
915     if (p->pid == USB_TOKEN_OUT && p->ep->nr == 1) {
916         usb_audio_handle_dataout(s, p);
917         return;
918     }
919 
920     p->status = USB_RET_STALL;
921     if (s->debug) {
922         fprintf(stderr, "usb-audio: failed data transaction: "
923                         "pid 0x%x ep 0x%x len 0x%zx\n",
924                         p->pid, p->ep->nr, p->iov.size);
925     }
926 }
927 
928 static void usb_audio_unrealize(USBDevice *dev)
929 {
930     USBAudioState *s = USB_AUDIO(dev);
931 
932     if (s->debug) {
933         fprintf(stderr, "usb-audio: destroy\n");
934     }
935 
936     usb_audio_set_output_altset(s, ALTSET_OFF);
937     AUD_close_out(&s->card, s->out.voice);
938     AUD_remove_card(&s->card);
939 
940     streambuf_fini(&s->out.buf);
941 }
942 
943 static void usb_audio_realize(USBDevice *dev, Error **errp)
944 {
945     USBAudioState *s = USB_AUDIO(dev);
946     int i;
947 
948     dev->usb_desc = s->multi ? &desc_audio_multi : &desc_audio;
949 
950     usb_desc_create_serial(dev);
951     usb_desc_init(dev);
952     s->dev.opaque = s;
953     AUD_register_card(TYPE_USB_AUDIO, &s->card);
954 
955     s->out.altset        = ALTSET_OFF;
956     s->out.vol.mute      = false;
957     for (i = 0; i < USBAUDIO_MAX_CHANNELS(s); ++i) {
958         s->out.vol.vol[i] = 240; /* 0 dB */
959     }
960 
961     usb_audio_reinit(dev, 2);
962 }
963 
964 static void usb_audio_reinit(USBDevice *dev, unsigned channels)
965 {
966     USBAudioState *s = USB_AUDIO(dev);
967 
968     s->out.channels      = channels;
969     if (!s->buffer_user) {
970         s->buffer = 32 * USBAUDIO_PACKET_SIZE(s->out.channels);
971     } else {
972         s->buffer = s->buffer_user;
973     }
974 
975     s->out.vol.channels  = s->out.channels;
976     s->out.as.freq       = USBAUDIO_SAMPLE_RATE;
977     s->out.as.nchannels  = s->out.channels;
978     s->out.as.fmt        = AUDIO_FORMAT_S16;
979     s->out.as.endianness = 0;
980     streambuf_init(&s->out.buf, s->buffer, s->out.channels);
981 
982     s->out.voice = AUD_open_out(&s->card, s->out.voice, TYPE_USB_AUDIO,
983                                 s, output_callback, &s->out.as);
984     audio_set_volume_out(s->out.voice, &s->out.vol);
985     AUD_set_active_out(s->out.voice, 0);
986 }
987 
988 static const VMStateDescription vmstate_usb_audio = {
989     .name = TYPE_USB_AUDIO,
990     .unmigratable = 1,
991 };
992 
993 static Property usb_audio_properties[] = {
994     DEFINE_AUDIO_PROPERTIES(USBAudioState, card),
995     DEFINE_PROP_UINT32("debug", USBAudioState, debug, 0),
996     DEFINE_PROP_UINT32("buffer", USBAudioState, buffer_user, 0),
997     DEFINE_PROP_BOOL("multi", USBAudioState, multi, false),
998     DEFINE_PROP_END_OF_LIST(),
999 };
1000 
1001 static void usb_audio_class_init(ObjectClass *klass, void *data)
1002 {
1003     DeviceClass *dc = DEVICE_CLASS(klass);
1004     USBDeviceClass *k = USB_DEVICE_CLASS(klass);
1005 
1006     dc->vmsd          = &vmstate_usb_audio;
1007     device_class_set_props(dc, usb_audio_properties);
1008     set_bit(DEVICE_CATEGORY_SOUND, dc->categories);
1009     k->product_desc   = "QEMU USB Audio Interface";
1010     k->realize        = usb_audio_realize;
1011     k->handle_reset   = usb_audio_handle_reset;
1012     k->handle_control = usb_audio_handle_control;
1013     k->handle_data    = usb_audio_handle_data;
1014     k->unrealize      = usb_audio_unrealize;
1015     k->set_interface  = usb_audio_set_interface;
1016 }
1017 
1018 static const TypeInfo usb_audio_info = {
1019     .name          = TYPE_USB_AUDIO,
1020     .parent        = TYPE_USB_DEVICE,
1021     .instance_size = sizeof(USBAudioState),
1022     .class_init    = usb_audio_class_init,
1023 };
1024 
1025 static void usb_audio_register_types(void)
1026 {
1027     type_register_static(&usb_audio_info);
1028     usb_legacy_register(TYPE_USB_AUDIO, "audio", NULL);
1029 }
1030 
1031 type_init(usb_audio_register_types)
1032