xref: /openbmc/qemu/hw/usb/dev-audio.c (revision 6016b7b4)
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 Output 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 Output 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 
658 #define TYPE_USB_AUDIO "usb-audio"
659 OBJECT_DECLARE_SIMPLE_TYPE(USBAudioState, USB_AUDIO)
660 
661 static void output_callback(void *opaque, int avail)
662 {
663     USBAudioState *s = opaque;
664     uint8_t *data;
665 
666     while (avail) {
667         size_t written, len;
668 
669         data = streambuf_get(&s->out.buf, &len);
670         if (!data) {
671             return;
672         }
673 
674         written = AUD_write(s->out.voice, data, len);
675         avail -= written;
676         s->out.buf.cons += written;
677 
678         if (written < len) {
679             return;
680         }
681     }
682 }
683 
684 static int usb_audio_set_output_altset(USBAudioState *s, int altset)
685 {
686     switch (altset) {
687     case ALTSET_OFF:
688         AUD_set_active_out(s->out.voice, false);
689         break;
690     case ALTSET_STEREO:
691     case ALTSET_51:
692     case ALTSET_71:
693         if (s->out.channels != altset_channels[altset]) {
694             usb_audio_reinit(USB_DEVICE(s), altset_channels[altset]);
695         }
696         streambuf_init(&s->out.buf, s->buffer, s->out.channels);
697         AUD_set_active_out(s->out.voice, true);
698         break;
699     default:
700         return -1;
701     }
702 
703     if (s->debug) {
704         fprintf(stderr, "usb-audio: set interface %d\n", altset);
705     }
706     s->out.altset = altset;
707     return 0;
708 }
709 
710 /*
711  * Note: we arbitrarily map the volume control range onto -inf..+8 dB
712  */
713 #define ATTRIB_ID(cs, attrib, idif)     \
714     (((cs) << 24) | ((attrib) << 16) | (idif))
715 
716 static int usb_audio_get_control(USBAudioState *s, uint8_t attrib,
717                                  uint16_t cscn, uint16_t idif,
718                                  int length, uint8_t *data)
719 {
720     uint8_t cs = cscn >> 8;
721     uint8_t cn = cscn - 1;      /* -1 for the non-present master control */
722     uint32_t aid = ATTRIB_ID(cs, attrib, idif);
723     int ret = USB_RET_STALL;
724 
725     switch (aid) {
726     case ATTRIB_ID(MUTE_CONTROL, CR_GET_CUR, 0x0200):
727         data[0] = s->out.vol.mute;
728         ret = 1;
729         break;
730     case ATTRIB_ID(VOLUME_CONTROL, CR_GET_CUR, 0x0200):
731         if (cn < USBAUDIO_MAX_CHANNELS(s)) {
732             uint16_t vol = (s->out.vol.vol[cn] * 0x8800 + 127) / 255 + 0x8000;
733             data[0] = vol;
734             data[1] = vol >> 8;
735             ret = 2;
736         }
737         break;
738     case ATTRIB_ID(VOLUME_CONTROL, CR_GET_MIN, 0x0200):
739         if (cn < USBAUDIO_MAX_CHANNELS(s)) {
740             data[0] = 0x01;
741             data[1] = 0x80;
742             ret = 2;
743         }
744         break;
745     case ATTRIB_ID(VOLUME_CONTROL, CR_GET_MAX, 0x0200):
746         if (cn < USBAUDIO_MAX_CHANNELS(s)) {
747             data[0] = 0x00;
748             data[1] = 0x08;
749             ret = 2;
750         }
751         break;
752     case ATTRIB_ID(VOLUME_CONTROL, CR_GET_RES, 0x0200):
753         if (cn < USBAUDIO_MAX_CHANNELS(s)) {
754             data[0] = 0x88;
755             data[1] = 0x00;
756             ret = 2;
757         }
758         break;
759     }
760 
761     return ret;
762 }
763 static int usb_audio_set_control(USBAudioState *s, uint8_t attrib,
764                                  uint16_t cscn, uint16_t idif,
765                                  int length, uint8_t *data)
766 {
767     uint8_t cs = cscn >> 8;
768     uint8_t cn = cscn - 1;      /* -1 for the non-present master control */
769     uint32_t aid = ATTRIB_ID(cs, attrib, idif);
770     int ret = USB_RET_STALL;
771     bool set_vol = false;
772 
773     switch (aid) {
774     case ATTRIB_ID(MUTE_CONTROL, CR_SET_CUR, 0x0200):
775         s->out.vol.mute = data[0] & 1;
776         set_vol = true;
777         ret = 0;
778         break;
779     case ATTRIB_ID(VOLUME_CONTROL, CR_SET_CUR, 0x0200):
780         if (cn < USBAUDIO_MAX_CHANNELS(s)) {
781             uint16_t vol = data[0] + (data[1] << 8);
782 
783             if (s->debug) {
784                 fprintf(stderr, "usb-audio: cn %d vol %04x\n", cn,
785                         (uint16_t)vol);
786             }
787 
788             vol -= 0x8000;
789             vol = (vol * 255 + 0x4400) / 0x8800;
790             if (vol > 255) {
791                 vol = 255;
792             }
793 
794             s->out.vol.vol[cn] = vol;
795             set_vol = true;
796             ret = 0;
797         }
798         break;
799     }
800 
801     if (set_vol) {
802         if (s->debug) {
803             int i;
804             fprintf(stderr, "usb-audio: mute %d", s->out.vol.mute);
805             for (i = 0; i < USBAUDIO_MAX_CHANNELS(s); ++i) {
806                 fprintf(stderr, ", vol[%d] %3d", i, s->out.vol.vol[i]);
807             }
808             fprintf(stderr, "\n");
809         }
810         audio_set_volume_out(s->out.voice, &s->out.vol);
811     }
812 
813     return ret;
814 }
815 
816 static void usb_audio_handle_control(USBDevice *dev, USBPacket *p,
817                                     int request, int value, int index,
818                                     int length, uint8_t *data)
819 {
820     USBAudioState *s = USB_AUDIO(dev);
821     int ret = 0;
822 
823     if (s->debug) {
824         fprintf(stderr, "usb-audio: control transaction: "
825                 "request 0x%04x value 0x%04x index 0x%04x length 0x%04x\n",
826                 request, value, index, length);
827     }
828 
829     ret = usb_desc_handle_control(dev, p, request, value, index, length, data);
830     if (ret >= 0) {
831         return;
832     }
833 
834     switch (request) {
835     case ClassInterfaceRequest | CR_GET_CUR:
836     case ClassInterfaceRequest | CR_GET_MIN:
837     case ClassInterfaceRequest | CR_GET_MAX:
838     case ClassInterfaceRequest | CR_GET_RES:
839         ret = usb_audio_get_control(s, request & 0xff, value, index,
840                                     length, data);
841         if (ret < 0) {
842             if (s->debug) {
843                 fprintf(stderr, "usb-audio: fail: get control\n");
844             }
845             goto fail;
846         }
847         p->actual_length = ret;
848         break;
849 
850     case ClassInterfaceOutRequest | CR_SET_CUR:
851     case ClassInterfaceOutRequest | CR_SET_MIN:
852     case ClassInterfaceOutRequest | CR_SET_MAX:
853     case ClassInterfaceOutRequest | CR_SET_RES:
854         ret = usb_audio_set_control(s, request & 0xff, value, index,
855                                     length, data);
856         if (ret < 0) {
857             if (s->debug) {
858                 fprintf(stderr, "usb-audio: fail: set control\n");
859             }
860             goto fail;
861         }
862         break;
863 
864     default:
865 fail:
866         if (s->debug) {
867             fprintf(stderr, "usb-audio: failed control transaction: "
868                     "request 0x%04x value 0x%04x index 0x%04x length 0x%04x\n",
869                     request, value, index, length);
870         }
871         p->status = USB_RET_STALL;
872         break;
873     }
874 }
875 
876 static void usb_audio_set_interface(USBDevice *dev, int iface,
877                                     int old, int value)
878 {
879     USBAudioState *s = USB_AUDIO(dev);
880 
881     if (iface == 1) {
882         usb_audio_set_output_altset(s, value);
883     }
884 }
885 
886 static void usb_audio_handle_reset(USBDevice *dev)
887 {
888     USBAudioState *s = USB_AUDIO(dev);
889 
890     if (s->debug) {
891         fprintf(stderr, "usb-audio: reset\n");
892     }
893     usb_audio_set_output_altset(s, ALTSET_OFF);
894 }
895 
896 static void usb_audio_handle_dataout(USBAudioState *s, USBPacket *p)
897 {
898     if (s->out.altset == ALTSET_OFF) {
899         p->status = USB_RET_STALL;
900         return;
901     }
902 
903     streambuf_put(&s->out.buf, p, s->out.channels);
904     if (p->actual_length < p->iov.size && s->debug > 1) {
905         fprintf(stderr, "usb-audio: output overrun (%zd bytes)\n",
906                 p->iov.size - p->actual_length);
907     }
908 }
909 
910 static void usb_audio_handle_data(USBDevice *dev, USBPacket *p)
911 {
912     USBAudioState *s = (USBAudioState *) dev;
913 
914     if (p->pid == USB_TOKEN_OUT && p->ep->nr == 1) {
915         usb_audio_handle_dataout(s, p);
916         return;
917     }
918 
919     p->status = USB_RET_STALL;
920     if (s->debug) {
921         fprintf(stderr, "usb-audio: failed data transaction: "
922                         "pid 0x%x ep 0x%x len 0x%zx\n",
923                         p->pid, p->ep->nr, p->iov.size);
924     }
925 }
926 
927 static void usb_audio_unrealize(USBDevice *dev)
928 {
929     USBAudioState *s = USB_AUDIO(dev);
930 
931     if (s->debug) {
932         fprintf(stderr, "usb-audio: destroy\n");
933     }
934 
935     usb_audio_set_output_altset(s, ALTSET_OFF);
936     AUD_close_out(&s->card, s->out.voice);
937     AUD_remove_card(&s->card);
938 
939     streambuf_fini(&s->out.buf);
940 }
941 
942 static void usb_audio_realize(USBDevice *dev, Error **errp)
943 {
944     USBAudioState *s = USB_AUDIO(dev);
945     int i;
946 
947     dev->usb_desc = s->multi ? &desc_audio_multi : &desc_audio;
948 
949     usb_desc_create_serial(dev);
950     usb_desc_init(dev);
951     s->dev.opaque = s;
952     AUD_register_card(TYPE_USB_AUDIO, &s->card);
953 
954     s->out.altset        = ALTSET_OFF;
955     s->out.vol.mute      = false;
956     for (i = 0; i < USBAUDIO_MAX_CHANNELS(s); ++i) {
957         s->out.vol.vol[i] = 240; /* 0 dB */
958     }
959 
960     usb_audio_reinit(dev, 2);
961 }
962 
963 static void usb_audio_reinit(USBDevice *dev, unsigned channels)
964 {
965     USBAudioState *s = USB_AUDIO(dev);
966 
967     s->out.channels      = channels;
968     if (!s->buffer_user) {
969         s->buffer = 32 * USBAUDIO_PACKET_SIZE(s->out.channels);
970     } else {
971         s->buffer = s->buffer_user;
972     }
973 
974     s->out.vol.channels  = s->out.channels;
975     s->out.as.freq       = USBAUDIO_SAMPLE_RATE;
976     s->out.as.nchannels  = s->out.channels;
977     s->out.as.fmt        = AUDIO_FORMAT_S16;
978     s->out.as.endianness = 0;
979     streambuf_init(&s->out.buf, s->buffer, s->out.channels);
980 
981     s->out.voice = AUD_open_out(&s->card, s->out.voice, TYPE_USB_AUDIO,
982                                 s, output_callback, &s->out.as);
983     audio_set_volume_out(s->out.voice, &s->out.vol);
984     AUD_set_active_out(s->out.voice, 0);
985 }
986 
987 static const VMStateDescription vmstate_usb_audio = {
988     .name = TYPE_USB_AUDIO,
989     .unmigratable = 1,
990 };
991 
992 static Property usb_audio_properties[] = {
993     DEFINE_AUDIO_PROPERTIES(USBAudioState, card),
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     DEFINE_PROP_END_OF_LIST(),
998 };
999 
1000 static void usb_audio_class_init(ObjectClass *klass, void *data)
1001 {
1002     DeviceClass *dc = DEVICE_CLASS(klass);
1003     USBDeviceClass *k = USB_DEVICE_CLASS(klass);
1004 
1005     dc->vmsd          = &vmstate_usb_audio;
1006     device_class_set_props(dc, usb_audio_properties);
1007     set_bit(DEVICE_CATEGORY_SOUND, dc->categories);
1008     k->product_desc   = "QEMU USB Audio Interface";
1009     k->realize        = usb_audio_realize;
1010     k->handle_reset   = usb_audio_handle_reset;
1011     k->handle_control = usb_audio_handle_control;
1012     k->handle_data    = usb_audio_handle_data;
1013     k->unrealize      = usb_audio_unrealize;
1014     k->set_interface  = usb_audio_set_interface;
1015 }
1016 
1017 static const TypeInfo usb_audio_info = {
1018     .name          = TYPE_USB_AUDIO,
1019     .parent        = TYPE_USB_DEVICE,
1020     .instance_size = sizeof(USBAudioState),
1021     .class_init    = usb_audio_class_init,
1022 };
1023 
1024 static void usb_audio_register_types(void)
1025 {
1026     type_register_static(&usb_audio_info);
1027 }
1028 
1029 type_init(usb_audio_register_types)
1030