1 /*
2  * Copyright (c) 2020 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 /**
8  * @file
9  * @brief Audio device class driver
10  *
11  * Driver for USB Audio device class driver
12  */
13 
14 #include <zephyr/kernel.h>
15 #include <zephyr/usb/usb_device.h>
16 #include <usb_descriptor.h>
17 #include <zephyr/usb/class/usb_audio.h>
18 #include "usb_audio_internal.h"
19 
20 #include <zephyr/sys/byteorder.h>
21 #include <zephyr/sys/util.h>
22 #include <zephyr/net/buf.h>
23 
24 #include <zephyr/logging/log.h>
25 LOG_MODULE_REGISTER(usb_audio, CONFIG_USB_AUDIO_LOG_LEVEL);
26 
27 struct feature_volume {
28 	int16_t volume_max;
29 	int16_t volume_min;
30 	int16_t volume_res;
31 };
32 
33 /* Device data structure */
34 struct usb_audio_dev_data {
35 	const struct usb_audio_ops *ops;
36 
37 	uint8_t *controls[2];
38 
39 	uint8_t ch_cnt[2];
40 
41 	const struct cs_ac_if_descriptor *desc_hdr;
42 
43 	struct usb_dev_data common;
44 
45 	struct net_buf_pool *pool;
46 
47 	/* Not applicable for Headphones, left with 0 */
48 	uint16_t in_frame_size;
49 
50 	/* Not applicable for not support volume feature device */
51 	struct feature_volume volumes;
52 
53 	bool rx_enable;
54 	bool tx_enable;
55 };
56 
57 static sys_slist_t usb_audio_data_devlist;
58 
59 /**
60  * @brief Fill the USB Audio descriptor
61  *
62  * This macro fills USB descriptor for specific type of device
63  * (Headphones or Microphone) depending on dev param.
64  *
65  * @note Feature unit has variable length and only 1st field of
66  *	 .bmaControls is filled. Later its fixed in usb_fix_descriptor()
67  * @note Audio control and Audio streaming interfaces are numerated starting
68  *	 from 0 and are later fixed in usb_fix_descriptor()
69  *
70  * @param [in] dev	Device type. Must be HP/MIC
71  * @param [in] i	Instance of device of current type (dev)
72  * @param [in] id	Param for counting logic entities
73  * @param [in] link	ID of IN/OUT terminal to which General Descriptor
74  *			is linked.
75  * @param [in] it_type	Input terminal type
76  * @param [in] ot_type	Output terminal type
77  */
78 #define DEFINE_AUDIO_DESCRIPTOR(dev, i, id, link, it_type, ot_type, cb, addr) \
79 USBD_CLASS_DESCR_DEFINE(primary, audio)					      \
80 struct dev##_descriptor_##i dev##_desc_##i = {				      \
81 	USB_AUDIO_IAD(2)						      \
82 	.std_ac_interface = INIT_STD_IF(USB_AUDIO_AUDIOCONTROL, 0, 0, 0),     \
83 	.cs_ac_interface = INIT_CS_AC_IF(dev, i, 1),			      \
84 	.input_terminal = INIT_IN_TERMINAL(dev, i, id, it_type),	      \
85 	.feature_unit = INIT_FEATURE_UNIT(dev, i, id + 1, id),		      \
86 	.output_terminal = INIT_OUT_TERMINAL(id + 2, id + 1, ot_type),	      \
87 	.as_interface_alt_0 = INIT_STD_IF(USB_AUDIO_AUDIOSTREAMING, 1, 0, 0), \
88 	.as_interface_alt_1 = INIT_STD_IF(USB_AUDIO_AUDIOSTREAMING, 1, 1, 1), \
89 	.as_cs_interface = INIT_AS_GENERAL(link),			      \
90 	.format = INIT_AS_FORMAT_I(CH_CNT(dev, i), GET_RES(dev, i), GET_RATE(dev, i)), \
91 	.std_ep = INIT_STD_AS_AD_EP(dev, i, addr),			      \
92 	.cs_ep = INIT_CS_AS_AD_EP,					      \
93 };									      \
94 static struct usb_ep_cfg_data dev##_usb_audio_ep_data_##i[] = {		      \
95 	INIT_EP_DATA(cb, addr),						      \
96 }
97 
98 /**
99  * @brief Fill the USB Audio descriptor
100  *
101  * This macro fills USB descriptor for specific type of device.
102  * Macro is used when the device uses 2 audiostreaming interfaces,
103  * eg. Headset
104  *
105  * @note Feature units have variable length and only 1st field of
106  *	 .bmaControls is filled. Its fixed in usb_fix_descriptor()
107  * @note Audio control and Audio streaming interfaces are numerated starting
108  *	 from 0 and are later fixed in usb_fix_descriptor()
109  *
110  * @param [in] dev	Device type.
111  * @param [in] i	Instance of device of current type (dev)
112  * @param [in] id	Param for counting logic entities
113  */
114 #define DEFINE_AUDIO_DESCRIPTOR_BIDIR(dev, i, id)			  \
115 USBD_CLASS_DESCR_DEFINE(primary, audio)					  \
116 struct dev##_descriptor_##i dev##_desc_##i = {				  \
117 	USB_AUDIO_IAD(3)						  \
118 	.std_ac_interface = INIT_STD_IF(USB_AUDIO_AUDIOCONTROL, 0, 0, 0), \
119 	.cs_ac_interface = INIT_CS_AC_IF_BIDIR(dev, i, 2),		  \
120 	.input_terminal_0 = INIT_IN_TERMINAL(dev##_MIC, i, id,		  \
121 						USB_AUDIO_IO_HEADSET),	  \
122 	.feature_unit_0 = INIT_FEATURE_UNIT(dev##_MIC, i, id+1, id),	  \
123 	.output_terminal_0 = INIT_OUT_TERMINAL(id+2, id+1,		  \
124 					USB_AUDIO_USB_STREAMING),	  \
125 	.input_terminal_1 = INIT_IN_TERMINAL(dev##_HP, i, id+3,		  \
126 					USB_AUDIO_USB_STREAMING),	  \
127 	.feature_unit_1 = INIT_FEATURE_UNIT(dev##_HP, i, id+4, id+3),	  \
128 	.output_terminal_1 = INIT_OUT_TERMINAL(id+5, id+4,		  \
129 						USB_AUDIO_IO_HEADSET),	  \
130 	.as_interface_alt_0_0 = INIT_STD_IF(USB_AUDIO_AUDIOSTREAMING,	  \
131 						1, 0, 0),		  \
132 	.as_interface_alt_0_1 = INIT_STD_IF(USB_AUDIO_AUDIOSTREAMING,	  \
133 						1, 1, 1),		  \
134 		.as_cs_interface_0 = INIT_AS_GENERAL(id+2),		  \
135 		.format_0 = INIT_AS_FORMAT_I(CH_CNT(dev##_MIC, i),	  \
136 					     GET_RES(dev##_MIC, i),	  \
137 					     GET_RATE(dev##_MIC, i)),	  \
138 		.std_ep_0 = INIT_STD_AS_AD_EP(dev##_MIC, i,		  \
139 						   AUTO_EP_IN),		  \
140 		.cs_ep_0 = INIT_CS_AS_AD_EP,				  \
141 	.as_interface_alt_1_0 = INIT_STD_IF(USB_AUDIO_AUDIOSTREAMING,	  \
142 						2, 0, 0),		  \
143 	.as_interface_alt_1_1 = INIT_STD_IF(USB_AUDIO_AUDIOSTREAMING,	  \
144 						2, 1, 1),		  \
145 		.as_cs_interface_1 = INIT_AS_GENERAL(id+3),		  \
146 		.format_1 = INIT_AS_FORMAT_I(CH_CNT(dev##_HP, i),	  \
147 					     GET_RES(dev##_HP, i),	  \
148 					     GET_RATE(dev##_HP, i)),	  \
149 		.std_ep_1 = INIT_STD_AS_AD_EP(dev##_HP, i,		  \
150 						   AUTO_EP_OUT),	  \
151 		.cs_ep_1 = INIT_CS_AS_AD_EP,				  \
152 };									  \
153 static struct usb_ep_cfg_data dev##_usb_audio_ep_data_##i[] = {		  \
154 	INIT_EP_DATA(usb_transfer_ep_callback, AUTO_EP_IN),		  \
155 	INIT_EP_DATA(audio_receive_cb, AUTO_EP_OUT),			  \
156 }
157 
158 #define DEFINE_AUDIO_DEV_DATA(dev, i, __out_pool, __in_pool_size)   \
159 	static uint8_t dev##_controls_##i[FEATURES_SIZE(dev, i)] = {0};\
160 	static struct usb_audio_dev_data dev##_audio_dev_data_##i =	\
161 		{ .pool = __out_pool,					\
162 		  .in_frame_size = __in_pool_size,			\
163 		  .controls = {dev##_controls_##i, NULL},		\
164 		  .ch_cnt = {(CH_CNT(dev, i) + 1), 0},			\
165 		  .volumes.volume_max = GET_VOLUME(dev, i, volume_max), \
166 		  .volumes.volume_min = GET_VOLUME(dev, i, volume_min), \
167 		  .volumes.volume_res = GET_VOLUME(dev, i, volume_res), \
168 		}
169 
170 #define DEFINE_AUDIO_DEV_DATA_BIDIR(dev, i, __out_pool, __in_pool_size)	   \
171 	static uint8_t dev##_controls0_##i[FEATURES_SIZE(dev##_MIC, i)] = {0};\
172 	static uint8_t dev##_controls1_##i[FEATURES_SIZE(dev##_HP, i)] = {0}; \
173 	static struct usb_audio_dev_data dev##_audio_dev_data_##i =	   \
174 		{ .pool = __out_pool,					   \
175 		  .in_frame_size = __in_pool_size,			   \
176 		  .controls = {dev##_controls0_##i, dev##_controls1_##i},  \
177 		  .ch_cnt = {(CH_CNT(dev##_MIC, i) + 1),		   \
178 			     (CH_CNT(dev##_HP, i) + 1)},		   \
179 		  .volumes.volume_max = GET_VOLUME(dev, i, volume_max),	   \
180 		  .volumes.volume_min = GET_VOLUME(dev, i, volume_min),	   \
181 		  .volumes.volume_res = GET_VOLUME(dev, i, volume_res),	   \
182 		}
183 
184 /**
185  * Helper function for getting channel number directly from the
186  * feature unit descriptor.
187  */
get_num_of_channels(const struct feature_unit_descriptor * fu)188 static uint8_t get_num_of_channels(const struct feature_unit_descriptor *fu)
189 {
190 	return (fu->bLength - FU_FIXED_ELEMS_SIZE)/sizeof(uint16_t);
191 }
192 
193 /**
194  * Helper function for getting supported controls directly from
195  * the feature unit descriptor.
196  */
get_controls(const struct feature_unit_descriptor * fu)197 static uint16_t get_controls(const struct feature_unit_descriptor *fu)
198 {
199 	return sys_get_le16((uint8_t *)&fu->bmaControls[0]);
200 }
201 
202 /**
203  * Helper function for getting the device streaming direction
204  */
get_fu_dir(const struct feature_unit_descriptor * fu)205 static enum usb_audio_direction get_fu_dir(
206 				const struct feature_unit_descriptor *fu)
207 {
208 	const struct output_terminal_descriptor *ot =
209 		(struct output_terminal_descriptor *)
210 		((uint8_t *)fu + fu->bLength);
211 	enum usb_audio_direction dir;
212 
213 	if (ot->wTerminalType == USB_AUDIO_USB_STREAMING) {
214 		dir = USB_AUDIO_IN;
215 	} else {
216 		dir = USB_AUDIO_OUT;
217 	}
218 
219 	return dir;
220 }
221 
222 /**
223  * Helper function for fixing controls in feature units descriptors.
224  */
fix_fu_descriptors(struct usb_if_descriptor * iface)225 static void fix_fu_descriptors(struct usb_if_descriptor *iface)
226 {
227 	struct cs_ac_if_descriptor *header;
228 	struct feature_unit_descriptor *fu;
229 
230 	header = (struct cs_ac_if_descriptor *)
231 			((uint8_t *)iface + USB_PASSIVE_IF_DESC_SIZE);
232 
233 	fu = (struct feature_unit_descriptor *)((uint8_t *)header +
234 						header->bLength +
235 						INPUT_TERMINAL_DESC_SIZE);
236 
237 	/* start from 1 as elem 0 is filled when descriptor is declared */
238 	for (int i = 1; i < get_num_of_channels(fu); i++) {
239 		(void)memcpy(&fu->bmaControls[i],
240 			     &fu->bmaControls[0],
241 			     sizeof(uint16_t));
242 	}
243 
244 	if (header->bInCollection == 2) {
245 		fu = (struct feature_unit_descriptor *)((uint8_t *)fu +
246 			fu->bLength +
247 			INPUT_TERMINAL_DESC_SIZE +
248 			OUTPUT_TERMINAL_DESC_SIZE);
249 		for (int i = 1; i < get_num_of_channels(fu); i++) {
250 			(void)memcpy(&fu->bmaControls[i],
251 				     &fu->bmaControls[0],
252 				     sizeof(uint16_t));
253 		}
254 	}
255 }
256 
257 /**
258  * Helper function for getting pointer to feature unit descriptor.
259  * This is needed in order to address audio specific requests to proper
260  * controls struct.
261  */
get_feature_unit(struct usb_audio_dev_data * audio_dev_data,uint8_t * device,uint8_t fu_id)262 static struct feature_unit_descriptor *get_feature_unit(
263 				struct usb_audio_dev_data *audio_dev_data,
264 				uint8_t *device, uint8_t fu_id)
265 {
266 	struct feature_unit_descriptor *fu;
267 
268 	fu = (struct feature_unit_descriptor *)
269 		((uint8_t *)audio_dev_data->desc_hdr +
270 		audio_dev_data->desc_hdr->bLength +
271 		INPUT_TERMINAL_DESC_SIZE);
272 
273 	if (fu->bUnitID == fu_id) {
274 		*device = 0;
275 		return fu;
276 	}
277 	/* skip to the next Feature Unit */
278 	fu = (struct feature_unit_descriptor *)
279 			((uint8_t *)fu + fu->bLength +
280 			INPUT_TERMINAL_DESC_SIZE +
281 			OUTPUT_TERMINAL_DESC_SIZE);
282 	*device = 1;
283 
284 	return fu;
285 }
286 
287 /**
288  * @brief This is a helper function user to inform the user about
289  * possibility to write the data to the device.
290  */
audio_dc_sof(struct usb_cfg_data * cfg,struct usb_audio_dev_data * dev_data)291 static void audio_dc_sof(struct usb_cfg_data *cfg,
292 			 struct usb_audio_dev_data *dev_data)
293 {
294 	uint8_t ep_addr;
295 
296 	/* In endpoint always at index 0 */
297 	ep_addr = cfg->endpoint[0].ep_addr;
298 	if ((ep_addr & USB_EP_DIR_MASK) && (dev_data->tx_enable)) {
299 		if (dev_data->ops && dev_data->ops->data_request_cb) {
300 			dev_data->ops->data_request_cb(
301 				dev_data->common.dev);
302 		}
303 	}
304 }
305 
audio_interface_config(struct usb_desc_header * head,uint8_t bInterfaceNumber)306 static void audio_interface_config(struct usb_desc_header *head,
307 				   uint8_t bInterfaceNumber)
308 {
309 	struct usb_if_descriptor *iface = (struct usb_if_descriptor *)head;
310 	struct cs_ac_if_descriptor *header;
311 
312 	struct usb_association_descriptor *iad =
313 		(struct usb_association_descriptor *)
314 		((char *)iface - sizeof(struct usb_association_descriptor));
315 	iad->bFirstInterface = bInterfaceNumber;
316 	fix_fu_descriptors(iface);
317 
318 	/* Audio Control Interface */
319 	iface->bInterfaceNumber = bInterfaceNumber;
320 	header = (struct cs_ac_if_descriptor *)
321 		 ((uint8_t *)iface + iface->bLength);
322 	header->baInterfaceNr[0] = bInterfaceNumber + 1;
323 
324 	/* Audio Streaming Interface Passive */
325 	iface = (struct usb_if_descriptor *)
326 			  ((uint8_t *)header + header->wTotalLength);
327 	iface->bInterfaceNumber = bInterfaceNumber + 1;
328 
329 	/* Audio Streaming Interface Active */
330 	iface = (struct usb_if_descriptor *)
331 			  ((uint8_t *)iface + iface->bLength);
332 	iface->bInterfaceNumber = bInterfaceNumber + 1;
333 
334 	if (header->bInCollection == 2) {
335 		header->baInterfaceNr[1] = bInterfaceNumber + 2;
336 		/* Audio Streaming Interface Passive */
337 		iface = (struct usb_if_descriptor *)
338 			((uint8_t *)iface + USB_ACTIVE_IF_DESC_SIZE);
339 		iface->bInterfaceNumber = bInterfaceNumber + 2;
340 
341 		/* Audio Streaming Interface Active */
342 		iface = (struct usb_if_descriptor *)
343 			((uint8_t *)iface + USB_PASSIVE_IF_DESC_SIZE);
344 		iface->bInterfaceNumber = bInterfaceNumber + 2;
345 	}
346 }
347 
audio_cb_usb_status(struct usb_cfg_data * cfg,enum usb_dc_status_code cb_status,const uint8_t * param)348 static void audio_cb_usb_status(struct usb_cfg_data *cfg,
349 			 enum usb_dc_status_code cb_status,
350 			 const uint8_t *param)
351 {
352 	struct usb_audio_dev_data *audio_dev_data;
353 	struct usb_dev_data *dev_data;
354 
355 	dev_data = usb_get_dev_data_by_cfg(&usb_audio_data_devlist, cfg);
356 
357 	if (dev_data == NULL) {
358 		LOG_ERR("Device data not found for cfg %p", cfg);
359 		return;
360 	}
361 
362 	audio_dev_data = CONTAINER_OF(dev_data, struct usb_audio_dev_data,
363 				      common);
364 
365 	switch (cb_status) {
366 	case USB_DC_SOF:
367 		audio_dc_sof(cfg, audio_dev_data);
368 		break;
369 	default:
370 		break;
371 	}
372 }
373 
374 /**
375  * @brief Helper function for checking if particular entity is a part of
376  *	  the audio device.
377  *
378  * This function checks if given entity is a part of given audio device.
379  * If so then true is returned and audio_dev_data is considered correct device
380  * data.
381  *
382  * @note For now this function searches through feature units only. The
383  *	 descriptors are known and are not using any other entity type.
384  *	 If there is a need to add other units to audio function then this
385  *	 must be reworked.
386  *
387  * @param [in]      audio_dev_data USB audio device data.
388  * @param [in, out] entity	   USB Audio entity.
389  *				   .id      [in]  id of searched entity
390  *				   .subtype [out] subtype of entity (if found)
391  *
392  * @return true if entity matched audio_dev_data, false otherwise.
393  */
is_entity_valid(struct usb_audio_dev_data * audio_dev_data,struct usb_audio_entity * entity)394 static bool is_entity_valid(struct usb_audio_dev_data *audio_dev_data,
395 			    struct usb_audio_entity *entity)
396 {
397 	const struct cs_ac_if_descriptor *header;
398 	const struct feature_unit_descriptor *fu;
399 
400 	header = audio_dev_data->desc_hdr;
401 	fu = (struct feature_unit_descriptor *)((uint8_t *)header +
402 						header->bLength +
403 						INPUT_TERMINAL_DESC_SIZE);
404 	if (fu->bUnitID == entity->id) {
405 		entity->subtype = fu->bDescriptorSubtype;
406 		return true;
407 	}
408 
409 	if (header->bInCollection == 2) {
410 		fu = (struct feature_unit_descriptor *)((uint8_t *)fu +
411 			fu->bLength +
412 			INPUT_TERMINAL_DESC_SIZE +
413 			OUTPUT_TERMINAL_DESC_SIZE);
414 		if (fu->bUnitID == entity->id) {
415 			entity->subtype = fu->bDescriptorSubtype;
416 			return true;
417 		}
418 	}
419 
420 	return false;
421 }
422 
423 /**
424  * @brief Helper function for getting the audio_dev_data by the entity number.
425  *
426  * This function searches through all audio devices the one with given
427  * entity number and return the audio_dev_data structure for this entity.
428  *
429  * @param [in, out] entity USB Audio entity addressed by the request.
430  *			   .id      [in]  id of searched entity
431  *			   .subtype [out] subtype of entity (if found)
432  *
433  * @return audio_dev_data for given entity, NULL if not found.
434  */
get_audio_dev_data_by_entity(struct usb_audio_entity * entity)435 static struct usb_audio_dev_data *get_audio_dev_data_by_entity(
436 					struct usb_audio_entity *entity)
437 {
438 	struct usb_dev_data *dev_data;
439 	struct usb_audio_dev_data *audio_dev_data;
440 
441 	SYS_SLIST_FOR_EACH_CONTAINER(&usb_audio_data_devlist, dev_data, node) {
442 		audio_dev_data = CONTAINER_OF(dev_data,
443 					      struct usb_audio_dev_data,
444 					      common);
445 
446 		if (is_entity_valid(audio_dev_data, entity)) {
447 			return audio_dev_data;
448 		}
449 	}
450 	return NULL;
451 }
452 
453 /**
454  * @brief Helper function for checking if particular interface is a part of
455  *	  the audio device.
456  *
457  * This function checks if given interface is a part of given audio device.
458  * If so then true is returned and audio_dev_data is considered correct device
459  * data.
460  *
461  * @param [in] audio_dev_data USB audio device data.
462  * @param [in] interface      USB Audio interface number.
463  *
464  * @return true if interface matched audio_dev_data, false otherwise.
465  */
is_interface_valid(struct usb_audio_dev_data * audio_dev_data,uint8_t interface)466 static bool is_interface_valid(struct usb_audio_dev_data *audio_dev_data,
467 			       uint8_t interface)
468 {
469 	const struct cs_ac_if_descriptor *header;
470 
471 	header = audio_dev_data->desc_hdr;
472 	uint8_t desc_iface = 0;
473 
474 	for (size_t i = 0; i < header->bInCollection; i++) {
475 		desc_iface = header->baInterfaceNr[i];
476 		if (desc_iface == interface) {
477 			return true;
478 		}
479 	}
480 
481 	return false;
482 }
483 
484 /**
485  * @brief Helper function for getting the audio_dev_data by the interface
486  *	  number.
487  *
488  * This function searches through all audio devices the one with given
489  * interface number and returns the audio_dev_data structure for this device.
490  *
491  * @param [in] interface USB Audio interface addressed by the request.
492  *
493  * @return audio_dev_data for given interface, NULL if not found.
494  */
get_audio_dev_data_by_iface(uint8_t interface)495 static struct usb_audio_dev_data *get_audio_dev_data_by_iface(uint8_t interface)
496 {
497 	struct usb_dev_data *dev_data;
498 	struct usb_audio_dev_data *audio_dev_data;
499 
500 	SYS_SLIST_FOR_EACH_CONTAINER(&usb_audio_data_devlist, dev_data, node) {
501 		audio_dev_data = CONTAINER_OF(dev_data,
502 					      struct usb_audio_dev_data,
503 					      common);
504 
505 		if (is_interface_valid(audio_dev_data, interface)) {
506 			return audio_dev_data;
507 		}
508 	}
509 	return NULL;
510 }
511 
512 /**
513  * @brief Handler for feature unit mute control requests.
514  *
515  * This function handles feature unit mute control request.
516  *
517  * @param audio_dev_data USB audio device data.
518  * @param setup          Information about the executed request.
519  * @param len		 Size of the buffer.
520  * @param data		 Buffer containing the request result.
521  * @param evt		 Feature Unit Event info.
522  * @param device	 Device part that has been addressed. Applicable for
523  *			 bidirectional device.
524  *
525  * @return 0 if successful, negative errno otherwise.
526  */
handle_fu_mute_req(struct usb_audio_dev_data * audio_dev_data,struct usb_setup_packet * setup,int32_t * len,uint8_t ** data,struct usb_audio_fu_evt * evt,uint8_t device)527 static int handle_fu_mute_req(struct usb_audio_dev_data *audio_dev_data,
528 			      struct usb_setup_packet *setup,
529 			      int32_t *len, uint8_t **data,
530 			      struct usb_audio_fu_evt *evt,
531 			      uint8_t device)
532 {
533 	uint8_t ch = (setup->wValue) & 0xFF;
534 	uint8_t ch_cnt = audio_dev_data->ch_cnt[device];
535 	uint8_t *controls = audio_dev_data->controls[device];
536 	uint8_t *control_val = &controls[POS(MUTE, ch, ch_cnt)];
537 
538 	if (usb_reqtype_is_to_device(setup)) {
539 		/* Check if *len has valid value */
540 		if (*len != LEN(1, MUTE)) {
541 			return -EINVAL;
542 		}
543 
544 		if (setup->bRequest == USB_AUDIO_SET_CUR) {
545 			evt->val = control_val;
546 			evt->val_len = *len;
547 			memcpy(control_val, *data, *len);
548 			return 0;
549 		}
550 	} else {
551 		if (setup->bRequest == USB_AUDIO_GET_CUR) {
552 			*data = control_val;
553 			*len = LEN(1, MUTE);
554 			return 0;
555 		}
556 	}
557 
558 	return -EINVAL;
559 }
560 
561 
handle_fu_volume_req(struct usb_audio_dev_data * audio_dev_data,struct usb_setup_packet * setup,int32_t * len,uint8_t ** data,struct usb_audio_fu_evt * evt,uint8_t device)562 static int handle_fu_volume_req(struct usb_audio_dev_data *audio_dev_data,
563 				struct usb_setup_packet *setup, int32_t *len, uint8_t **data,
564 				struct usb_audio_fu_evt *evt, uint8_t device)
565 {
566 	uint8_t ch = (setup->wValue) & 0xFF;
567 	uint8_t ch_cnt = audio_dev_data->ch_cnt[device];
568 	uint8_t *controls = audio_dev_data->controls[device];
569 	uint8_t *control_val = &controls[POS(VOLUME, ch, ch_cnt)];
570 	int16_t target_vol = 0;
571 	int16_t temp_vol = 0;
572 
573 	if (usb_reqtype_is_to_device(setup)) {
574 		/* Check if *len has valid value */
575 		if (*len != LEN(1, VOLUME)) {
576 			LOG_ERR("*len: %d, LEN(1, VOLUME): %d", *len, LEN(1, VOLUME));
577 			return -EINVAL;
578 		}
579 		if (setup->bRequest == USB_AUDIO_SET_CUR) {
580 			target_vol = *((int16_t *)*data);
581 			if (!IN_RANGE(target_vol, audio_dev_data->volumes.volume_min,
582 				      audio_dev_data->volumes.volume_max)) {
583 				LOG_ERR("Volume out of range: %d", target_vol);
584 				return -EINVAL;
585 			}
586 			if (target_vol % audio_dev_data->volumes.volume_res != 0) {
587 				target_vol = ROUND_UP(target_vol,
588 					audio_dev_data->volumes.volume_res);
589 			}
590 			evt->val = control_val;
591 			evt->val_len = *len;
592 			*((int16_t *)evt->val) = sys_le16_to_cpu(target_vol);
593 			return 0;
594 		}
595 	} else {
596 		if (setup->bRequest == USB_AUDIO_GET_CUR) {
597 			*len = LEN(ch_cnt, VOLUME);
598 			temp_vol = sys_cpu_to_le16(*(int16_t *)control_val);
599 			memcpy(*data, &temp_vol, *len);
600 			return 0;
601 		} else if (setup->bRequest == USB_AUDIO_GET_MIN) {
602 			*len = sizeof(audio_dev_data->volumes.volume_min);
603 			temp_vol = sys_cpu_to_le16(audio_dev_data->volumes.volume_min);
604 			memcpy(*data, &temp_vol, *len);
605 			return 0;
606 		} else if (setup->bRequest == USB_AUDIO_GET_MAX) {
607 			*len = sizeof(audio_dev_data->volumes.volume_max);
608 			temp_vol = sys_cpu_to_le16(audio_dev_data->volumes.volume_max);
609 			memcpy(*data, &temp_vol, *len);
610 			return 0;
611 		} else if (setup->bRequest == USB_AUDIO_GET_RES) {
612 			*len = sizeof(audio_dev_data->volumes.volume_res);
613 			temp_vol = sys_cpu_to_le16(audio_dev_data->volumes.volume_res);
614 			memcpy(*data, &temp_vol, *len);
615 			return 0;
616 		}
617 	}
618 
619 	return -EINVAL;
620 }
621 
622 /**
623  * @brief Handler for feature unit requests.
624  *
625  * This function handles feature unit specific requests.
626  * If request is properly served 0 is returned. Negative errno
627  * is returned in case of an error. This leads to setting stall on IN EP0.
628  *
629  * @param audio_dev_data USB audio device data.
630  * @param pSetup         Information about the executed request.
631  * @param len            Size of the buffer.
632  * @param data           Buffer containing the request result.
633  *
634  * @return 0 if successful, negative errno otherwise.
635  */
handle_feature_unit_req(struct usb_audio_dev_data * audio_dev_data,struct usb_setup_packet * pSetup,int32_t * len,uint8_t ** data)636 static int handle_feature_unit_req(struct usb_audio_dev_data *audio_dev_data,
637 				   struct usb_setup_packet *pSetup,
638 				   int32_t *len, uint8_t **data)
639 {
640 	const struct feature_unit_descriptor *fu;
641 	struct usb_audio_fu_evt evt;
642 	enum usb_audio_fucs cs;
643 	uint8_t device;
644 	uint8_t fu_id;
645 	uint8_t ch_cnt;
646 	uint8_t ch;
647 	int ret;
648 
649 	fu_id = ((pSetup->wIndex) >> 8) & 0xFF;
650 	fu = get_feature_unit(audio_dev_data, &device, fu_id);
651 	ch = (pSetup->wValue) & 0xFF;
652 	cs = ((pSetup->wValue) >> 8) & 0xFF;
653 	ch_cnt = audio_dev_data->ch_cnt[device];
654 
655 	LOG_DBG("CS: %d, CN: %d, len: %d", cs, ch, *len);
656 
657 	/* Error checking */
658 	if (!(BIT(cs) & (get_controls(fu) << 1))) {
659 		/* Feature not supported by this FU */
660 		return -EINVAL;
661 	} else if (ch >= ch_cnt) {
662 		/* Invalid ch */
663 		return -EINVAL;
664 	}
665 
666 	switch (cs) {
667 	case USB_AUDIO_FU_MUTE_CONTROL:
668 		ret = handle_fu_mute_req(audio_dev_data, pSetup,
669 					 len, data, &evt, device);
670 		break;
671 	case USB_AUDIO_FU_VOLUME_CONTROL:
672 		ret = handle_fu_volume_req(audio_dev_data, pSetup,
673 					 len, data, &evt, device);
674 		break;
675 	default:
676 		return -ENOTSUP;
677 	}
678 
679 	if (ret) {
680 		return ret;
681 	}
682 
683 	/* Inform the app */
684 	if (audio_dev_data->ops && audio_dev_data->ops->feature_update_cb) {
685 		if (usb_reqtype_is_to_device(pSetup) &&
686 		    pSetup->bRequest == USB_AUDIO_SET_CUR) {
687 			evt.cs = cs;
688 			evt.channel = ch;
689 			evt.dir = get_fu_dir(fu);
690 			audio_dev_data->ops->feature_update_cb(
691 					audio_dev_data->common.dev, &evt);
692 		}
693 	}
694 
695 	return 0;
696 }
697 
698 /**
699  * @brief Handler called for class specific interface request.
700  *
701  * This function handles all class specific interface requests to a usb audio
702  * device. If request is properly server then 0 is returned. Returning negative
703  * value will lead to set stall on IN EP0.
704  *
705  * @param pSetup    Information about the executed request.
706  * @param len       Size of the buffer.
707  * @param data      Buffer containing the request result.
708  *
709  * @return  0 on success, negative errno code on fail.
710  */
handle_interface_req(struct usb_setup_packet * pSetup,int32_t * len,uint8_t ** data)711 static int handle_interface_req(struct usb_setup_packet *pSetup,
712 				int32_t *len,
713 				uint8_t **data)
714 {
715 	struct usb_audio_dev_data *audio_dev_data;
716 	struct usb_audio_entity entity;
717 
718 	/* parse wIndex for interface request */
719 	uint8_t entity_id = ((pSetup->wIndex) >> 8) & 0xFF;
720 
721 	entity.id = entity_id;
722 
723 	/** Normally there should be a call to usb_get_dev_data_by_iface()
724 	 * and addressed interface should be read from wIndex low byte.
725 	 *
726 	 * uint8_t interface = (pSetup->wIndex) & 0xFF;
727 	 *
728 	 * However, Linux is using special form of Audio Requests
729 	 * which always left wIndex low byte 0 no matter which device and
730 	 * entity is addressed. Because of that there is a need to obtain
731 	 * this information from the device descriptor using entity id.
732 	 */
733 	audio_dev_data = get_audio_dev_data_by_entity(&entity);
734 
735 	if (audio_dev_data == NULL) {
736 		LOG_ERR("Device data not found for entity %u", entity.id);
737 		return -ENODEV;
738 	}
739 
740 	switch (entity.subtype) {
741 	case USB_AUDIO_FEATURE_UNIT:
742 		return handle_feature_unit_req(audio_dev_data,
743 					       pSetup, len, data);
744 	default:
745 		LOG_INF("Currently not supported");
746 		return -ENODEV;
747 	}
748 
749 	return 0;
750 }
751 
752 /**
753  * @brief Custom callback for USB Device requests.
754  *
755  * This callback is called when set/get interface request is directed
756  * to the device. This is Zephyr way to address those requests.
757  * It's not possible to do that in the core stack as common USB device
758  * stack does not know the amount of devices that has alternate interfaces.
759  *
760  * @param pSetup    Information about the request to execute.
761  * @param len       Size of the buffer.
762  * @param data      Buffer containing the request result.
763  *
764  * @return 0 on success, positive value if request is intended to be handled
765  *	   by the core USB stack. Negative error code on fail.
766  */
audio_custom_handler(struct usb_setup_packet * pSetup,int32_t * len,uint8_t ** data)767 static int audio_custom_handler(struct usb_setup_packet *pSetup, int32_t *len,
768 				uint8_t **data)
769 {
770 	const struct cs_ac_if_descriptor *header;
771 	struct usb_audio_dev_data *audio_dev_data;
772 	const struct usb_if_descriptor *if_desc;
773 	const struct usb_ep_descriptor *ep_desc;
774 
775 	uint8_t iface = (pSetup->wIndex) & 0xFF;
776 
777 	if (pSetup->RequestType.recipient != USB_REQTYPE_RECIPIENT_INTERFACE ||
778 	    usb_reqtype_is_to_host(pSetup)) {
779 		return -EINVAL;
780 	}
781 
782 	audio_dev_data = get_audio_dev_data_by_iface(iface);
783 	if (audio_dev_data == NULL) {
784 		return -EINVAL;
785 	}
786 
787 	/* Search for endpoint associated to addressed interface
788 	 * Endpoint is searched in order to know the direction of
789 	 * addressed interface.
790 	 */
791 	header = audio_dev_data->desc_hdr;
792 
793 	/* Skip to the first interface */
794 	if_desc = (struct usb_if_descriptor *)((uint8_t *)header +
795 						header->wTotalLength +
796 						USB_PASSIVE_IF_DESC_SIZE);
797 
798 	if (if_desc->bInterfaceNumber == iface) {
799 		ep_desc = (struct usb_ep_descriptor *)((uint8_t *)if_desc +
800 						USB_PASSIVE_IF_DESC_SIZE +
801 						USB_AC_CS_IF_DESC_SIZE +
802 						USB_FORMAT_TYPE_I_DESC_SIZE);
803 	} else {
804 		/* In case first interface address is not the one addressed
805 		 * we can be sure the second one is because
806 		 * get_audio_dev_data_by_iface() found the device. It
807 		 * must be the second interface associated with the device.
808 		 */
809 		if_desc = (struct usb_if_descriptor *)((uint8_t *)if_desc +
810 						USB_ACTIVE_IF_DESC_SIZE);
811 		ep_desc = (struct usb_ep_descriptor *)((uint8_t *)if_desc +
812 						USB_PASSIVE_IF_DESC_SIZE +
813 						USB_AC_CS_IF_DESC_SIZE +
814 						USB_FORMAT_TYPE_I_DESC_SIZE);
815 	}
816 
817 	if (pSetup->bRequest == USB_SREQ_SET_INTERFACE) {
818 		if (ep_desc->bEndpointAddress & USB_EP_DIR_MASK) {
819 			audio_dev_data->tx_enable = pSetup->wValue;
820 		} else {
821 			audio_dev_data->rx_enable = pSetup->wValue;
822 		}
823 	}
824 
825 	return -EINVAL;
826 }
827 
828 /**
829  * @brief Handler called for Class requests not handled by the USB stack.
830  *
831  * @param pSetup    Information about the request to execute.
832  * @param len       Size of the buffer.
833  * @param data      Buffer containing the request result.
834  *
835  * @return  0 on success, negative errno code on fail.
836  */
audio_class_handle_req(struct usb_setup_packet * pSetup,int32_t * len,uint8_t ** data)837 static int audio_class_handle_req(struct usb_setup_packet *pSetup,
838 				  int32_t *len, uint8_t **data)
839 {
840 	LOG_DBG("bmRT 0x%02x, bR 0x%02x, wV 0x%04x, wI 0x%04x, wL 0x%04x",
841 		pSetup->bmRequestType, pSetup->bRequest, pSetup->wValue,
842 		pSetup->wIndex, pSetup->wLength);
843 
844 	switch (pSetup->RequestType.recipient) {
845 	case USB_REQTYPE_RECIPIENT_INTERFACE:
846 		return handle_interface_req(pSetup, len, data);
847 	default:
848 		LOG_ERR("Request recipient invalid");
849 		return -EINVAL;
850 	}
851 }
852 
usb_audio_device_init(const struct device * dev)853 static int usb_audio_device_init(const struct device *dev)
854 {
855 	LOG_DBG("Init Audio Device: dev %p (%s)", dev, dev->name);
856 
857 	return 0;
858 }
859 
audio_write_cb(uint8_t ep,int size,void * priv)860 static void audio_write_cb(uint8_t ep, int size, void *priv)
861 {
862 	struct usb_dev_data *dev_data;
863 	struct usb_audio_dev_data *audio_dev_data;
864 	struct net_buf *buffer = priv;
865 
866 	dev_data = usb_get_dev_data_by_ep(&usb_audio_data_devlist, ep);
867 	audio_dev_data = dev_data->dev->data;
868 
869 	LOG_DBG("Written %d bytes on ep 0x%02x, *audio_dev_data %p",
870 		size, ep, audio_dev_data);
871 
872 	/* Ask installed callback to process the data.
873 	 * User is responsible for freeing the buffer.
874 	 * In case no callback is installed free the buffer.
875 	 */
876 	if (audio_dev_data->ops && audio_dev_data->ops->data_written_cb) {
877 		audio_dev_data->ops->data_written_cb(dev_data->dev,
878 						     buffer, size);
879 	} else {
880 		/* Release net_buf back to the pool */
881 		net_buf_unref(buffer);
882 	}
883 }
884 
usb_audio_send(const struct device * dev,struct net_buf * buffer,size_t len)885 int usb_audio_send(const struct device *dev, struct net_buf *buffer,
886 		   size_t len)
887 {
888 	struct usb_audio_dev_data *audio_dev_data = dev->data;
889 	struct usb_cfg_data *cfg = (void *)dev->config;
890 	/* EP ISO IN is always placed first in the endpoint table */
891 	uint8_t ep = cfg->endpoint[0].ep_addr;
892 
893 	if (!(ep & USB_EP_DIR_MASK)) {
894 		LOG_ERR("Wrong device");
895 		return -EINVAL;
896 	}
897 
898 	if (!audio_dev_data->tx_enable) {
899 		LOG_DBG("sending dropped -> Host chose passive interface");
900 		return -EAGAIN;
901 	}
902 
903 	if (len > buffer->size) {
904 		LOG_ERR("Cannot send %d bytes, to much data", len);
905 		return -EINVAL;
906 	}
907 
908 	/** buffer passed to *priv because completion callback
909 	 * needs to release it to the pool
910 	 */
911 	return usb_transfer(ep, buffer->data, len, USB_TRANS_WRITE | USB_TRANS_NO_ZLP,
912 		     audio_write_cb, buffer);
913 }
914 
usb_audio_get_in_frame_size(const struct device * dev)915 size_t usb_audio_get_in_frame_size(const struct device *dev)
916 {
917 	struct usb_audio_dev_data *audio_dev_data = dev->data;
918 
919 	return audio_dev_data->in_frame_size;
920 }
921 
922 #if (HEADPHONES_DEVICE_COUNT > 0 || HEADSET_DEVICE_COUNT > 0)
audio_receive_cb(uint8_t ep,enum usb_dc_ep_cb_status_code status)923 static void audio_receive_cb(uint8_t ep, enum usb_dc_ep_cb_status_code status)
924 {
925 	struct usb_audio_dev_data *audio_dev_data;
926 	struct usb_dev_data *common;
927 	struct net_buf *buffer;
928 	int ret_bytes;
929 	int ret;
930 
931 	__ASSERT(status == USB_DC_EP_DATA_OUT, "Invalid ep status");
932 
933 	common = usb_get_dev_data_by_ep(&usb_audio_data_devlist, ep);
934 	if (common == NULL) {
935 		return;
936 	}
937 
938 	audio_dev_data = CONTAINER_OF(common, struct usb_audio_dev_data,
939 				      common);
940 
941 	/** Check if active audiostreaming interface is selected
942 	 * If no there is no point to read the data. Return from callback
943 	 */
944 	if (!audio_dev_data->rx_enable) {
945 		return;
946 	}
947 
948 	/* Check if application installed callback and process the data.
949 	 * In case no callback is installed do not alloc the buffer at all.
950 	 */
951 	if (audio_dev_data->ops && audio_dev_data->ops->data_received_cb) {
952 		buffer = net_buf_alloc(audio_dev_data->pool, K_NO_WAIT);
953 		if (!buffer) {
954 			LOG_ERR("Failed to allocate data buffer");
955 			return;
956 		}
957 
958 		ret = usb_read(ep, buffer->data, buffer->size, &ret_bytes);
959 
960 		if (ret) {
961 			LOG_ERR("ret=%d ", ret);
962 			net_buf_unref(buffer);
963 			return;
964 		}
965 
966 		if (!ret_bytes) {
967 			net_buf_unref(buffer);
968 			return;
969 		}
970 		audio_dev_data->ops->data_received_cb(common->dev,
971 						      buffer, ret_bytes);
972 	}
973 }
974 #endif /* #if (HEADPHONES_DEVICE_COUNT > 0 || HEADSET_DEVICE_COUNT > 0) */
975 
usb_audio_register(const struct device * dev,const struct usb_audio_ops * ops)976 void usb_audio_register(const struct device *dev,
977 			const struct usb_audio_ops *ops)
978 {
979 	struct usb_audio_dev_data *audio_dev_data = dev->data;
980 	const struct usb_cfg_data *cfg = dev->config;
981 	const struct std_if_descriptor *iface_descr =
982 		cfg->interface_descriptor;
983 	const struct cs_ac_if_descriptor *header =
984 		(struct cs_ac_if_descriptor *)
985 		((uint8_t *)iface_descr + USB_PASSIVE_IF_DESC_SIZE);
986 
987 	audio_dev_data->ops = ops;
988 	audio_dev_data->common.dev = dev;
989 	audio_dev_data->rx_enable = false;
990 	audio_dev_data->tx_enable = false;
991 	audio_dev_data->desc_hdr = header;
992 
993 	sys_slist_append(&usb_audio_data_devlist, &audio_dev_data->common.node);
994 
995 	LOG_DBG("Device dev %p dev_data %p cfg %p added to devlist %p",
996 		dev, audio_dev_data, dev->config,
997 		&usb_audio_data_devlist);
998 }
999 
1000 #define DEFINE_AUDIO_DEVICE(dev, i)					  \
1001 	USBD_DEFINE_CFG_DATA(dev##_audio_config_##i) = {		  \
1002 		.usb_device_description	= NULL,				  \
1003 		.interface_config = audio_interface_config,		  \
1004 		.interface_descriptor = &dev##_desc_##i.std_ac_interface, \
1005 		.cb_usb_status = audio_cb_usb_status,			  \
1006 		.interface = {						  \
1007 			.class_handler = audio_class_handle_req,	  \
1008 			.custom_handler = audio_custom_handler,		  \
1009 			.vendor_handler = NULL,				  \
1010 		},							  \
1011 		.num_endpoints = ARRAY_SIZE(dev##_usb_audio_ep_data_##i), \
1012 		.endpoint = dev##_usb_audio_ep_data_##i,		  \
1013 	};								  \
1014 	DEVICE_DT_DEFINE(DT_INST(i, COMPAT_##dev),			  \
1015 			    &usb_audio_device_init,			  \
1016 			    NULL,					  \
1017 			    &dev##_audio_dev_data_##i,			  \
1018 			    &dev##_audio_config_##i, POST_KERNEL,	  \
1019 			    CONFIG_KERNEL_INIT_PRIORITY_DEVICE,		  \
1020 			    DUMMY_API)
1021 
1022 #define DEFINE_BUF_POOL(name, size) \
1023 	NET_BUF_POOL_FIXED_DEFINE(name, 5, size, 4, net_buf_destroy)
1024 
1025 #define UNIDIR_DEVICE(dev, i, out_pool, in_size, it_type, ot_type, cb, addr) \
1026 	UTIL_EXPAND( \
1027 	DEFINE_AUDIO_DEV_DATA(dev, i, out_pool, in_size); \
1028 	DECLARE_DESCRIPTOR(dev, i, 1); \
1029 	DEFINE_AUDIO_DESCRIPTOR(dev, i, dev##_ID(i), dev##_LINK(i), \
1030 				it_type, ot_type, cb, addr); \
1031 	DEFINE_AUDIO_DEVICE(dev, i))
1032 
1033 #define HEADPHONES_DEVICE(i, dev) UTIL_EXPAND( \
1034 	DEFINE_BUF_POOL(audio_data_pool_hp_##i, EP_SIZE(dev, i));  \
1035 	UNIDIR_DEVICE(dev, i, &audio_data_pool_hp_##i, 0, \
1036 		      USB_AUDIO_USB_STREAMING, USB_AUDIO_OUT_HEADPHONES, \
1037 		      audio_receive_cb, AUTO_EP_OUT);)
1038 
1039 #define MICROPHONE_DEVICE(i, dev) UTIL_EXPAND( \
1040 	UNIDIR_DEVICE(dev, i, NULL, EP_SIZE(dev, i), \
1041 		      USB_AUDIO_IN_MICROPHONE, USB_AUDIO_USB_STREAMING, \
1042 		      usb_transfer_ep_callback, AUTO_EP_IN);)
1043 
1044 #define HEADSET_DEVICE(i, dev) UTIL_EXPAND( \
1045 	DEFINE_BUF_POOL(audio_data_pool_hs_##i, EP_SIZE(dev##_HP, i)); \
1046 	DEFINE_AUDIO_DEV_DATA_BIDIR(dev, i, &audio_data_pool_hs_##i, \
1047 				    EP_SIZE(dev##_MIC, i)); \
1048 	DECLARE_DESCRIPTOR_BIDIR(dev, i, 2); \
1049 	DEFINE_AUDIO_DESCRIPTOR_BIDIR(dev, i, dev##_ID(i)); \
1050 	DEFINE_AUDIO_DEVICE(dev, i);)
1051 
1052 LISTIFY(HEADPHONES_DEVICE_COUNT, HEADPHONES_DEVICE, (), HP)
1053 LISTIFY(MICROPHONE_DEVICE_COUNT, MICROPHONE_DEVICE, (), MIC)
1054 LISTIFY(HEADSET_DEVICE_COUNT, HEADSET_DEVICE, (), HS)
1055