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