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