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 = sys_get_le16(*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 
591 			UNALIGNED_PUT(target_vol, (int16_t *)control_val);
592 			evt->val = control_val;
593 			evt->val_len = *len;
594 			return 0;
595 		}
596 	} else {
597 		if (setup->bRequest == USB_AUDIO_GET_CUR) {
598 			*len = LEN(ch_cnt, VOLUME);
599 			temp_vol = sys_cpu_to_le16(UNALIGNED_GET((int16_t *)control_val));
600 			memcpy(*data, &temp_vol, *len);
601 			return 0;
602 		} else if (setup->bRequest == USB_AUDIO_GET_MIN) {
603 			*len = sizeof(audio_dev_data->volumes.volume_min);
604 			temp_vol = sys_cpu_to_le16(audio_dev_data->volumes.volume_min);
605 			memcpy(*data, &temp_vol, *len);
606 			return 0;
607 		} else if (setup->bRequest == USB_AUDIO_GET_MAX) {
608 			*len = sizeof(audio_dev_data->volumes.volume_max);
609 			temp_vol = sys_cpu_to_le16(audio_dev_data->volumes.volume_max);
610 			memcpy(*data, &temp_vol, *len);
611 			return 0;
612 		} else if (setup->bRequest == USB_AUDIO_GET_RES) {
613 			*len = sizeof(audio_dev_data->volumes.volume_res);
614 			temp_vol = sys_cpu_to_le16(audio_dev_data->volumes.volume_res);
615 			memcpy(*data, &temp_vol, *len);
616 			return 0;
617 		}
618 	}
619 
620 	return -EINVAL;
621 }
622 
623 /**
624  * @brief Handler for feature unit requests.
625  *
626  * This function handles feature unit specific requests.
627  * If request is properly served 0 is returned. Negative errno
628  * is returned in case of an error. This leads to setting stall on IN EP0.
629  *
630  * @param audio_dev_data USB audio device data.
631  * @param pSetup         Information about the executed request.
632  * @param len            Size of the buffer.
633  * @param data           Buffer containing the request result.
634  *
635  * @return 0 if successful, negative errno otherwise.
636  */
handle_feature_unit_req(struct usb_audio_dev_data * audio_dev_data,struct usb_setup_packet * pSetup,int32_t * len,uint8_t ** data)637 static int handle_feature_unit_req(struct usb_audio_dev_data *audio_dev_data,
638 				   struct usb_setup_packet *pSetup,
639 				   int32_t *len, uint8_t **data)
640 {
641 	const struct feature_unit_descriptor *fu;
642 	struct usb_audio_fu_evt evt;
643 	enum usb_audio_fucs cs;
644 	uint8_t device;
645 	uint8_t fu_id;
646 	uint8_t ch_cnt;
647 	uint8_t ch;
648 	int ret;
649 
650 	fu_id = ((pSetup->wIndex) >> 8) & 0xFF;
651 	fu = get_feature_unit(audio_dev_data, &device, fu_id);
652 	ch = (pSetup->wValue) & 0xFF;
653 	cs = ((pSetup->wValue) >> 8) & 0xFF;
654 	ch_cnt = audio_dev_data->ch_cnt[device];
655 
656 	LOG_DBG("CS: %d, CN: %d, len: %d", cs, ch, *len);
657 
658 	/* Error checking */
659 	if (!(BIT(cs) & (get_controls(fu) << 1))) {
660 		/* Feature not supported by this FU */
661 		return -EINVAL;
662 	} else if (ch >= ch_cnt) {
663 		/* Invalid ch */
664 		return -EINVAL;
665 	}
666 
667 	switch (cs) {
668 	case USB_AUDIO_FU_MUTE_CONTROL:
669 		ret = handle_fu_mute_req(audio_dev_data, pSetup,
670 					 len, data, &evt, device);
671 		break;
672 	case USB_AUDIO_FU_VOLUME_CONTROL:
673 		ret = handle_fu_volume_req(audio_dev_data, pSetup,
674 					 len, data, &evt, device);
675 		break;
676 	default:
677 		return -ENOTSUP;
678 	}
679 
680 	if (ret) {
681 		return ret;
682 	}
683 
684 	/* Inform the app */
685 	if (audio_dev_data->ops && audio_dev_data->ops->feature_update_cb) {
686 		if (usb_reqtype_is_to_device(pSetup) &&
687 		    pSetup->bRequest == USB_AUDIO_SET_CUR) {
688 			evt.cs = cs;
689 			evt.channel = ch;
690 			evt.dir = get_fu_dir(fu);
691 			audio_dev_data->ops->feature_update_cb(
692 					audio_dev_data->common.dev, &evt);
693 		}
694 	}
695 
696 	return 0;
697 }
698 
699 /**
700  * @brief Handler called for class specific interface request.
701  *
702  * This function handles all class specific interface requests to a usb audio
703  * device. If request is properly server then 0 is returned. Returning negative
704  * value will lead to set stall on IN EP0.
705  *
706  * @param pSetup    Information about the executed request.
707  * @param len       Size of the buffer.
708  * @param data      Buffer containing the request result.
709  *
710  * @return  0 on success, negative errno code on fail.
711  */
handle_interface_req(struct usb_setup_packet * pSetup,int32_t * len,uint8_t ** data)712 static int handle_interface_req(struct usb_setup_packet *pSetup,
713 				int32_t *len,
714 				uint8_t **data)
715 {
716 	struct usb_audio_dev_data *audio_dev_data;
717 	struct usb_audio_entity entity;
718 
719 	/* parse wIndex for interface request */
720 	uint8_t entity_id = ((pSetup->wIndex) >> 8) & 0xFF;
721 
722 	entity.id = entity_id;
723 
724 	/** Normally there should be a call to usb_get_dev_data_by_iface()
725 	 * and addressed interface should be read from wIndex low byte.
726 	 *
727 	 * uint8_t interface = (pSetup->wIndex) & 0xFF;
728 	 *
729 	 * However, Linux is using special form of Audio Requests
730 	 * which always left wIndex low byte 0 no matter which device and
731 	 * entity is addressed. Because of that there is a need to obtain
732 	 * this information from the device descriptor using entity id.
733 	 */
734 	audio_dev_data = get_audio_dev_data_by_entity(&entity);
735 
736 	if (audio_dev_data == NULL) {
737 		LOG_ERR("Device data not found for entity %u", entity.id);
738 		return -ENODEV;
739 	}
740 
741 	switch (entity.subtype) {
742 	case USB_AUDIO_FEATURE_UNIT:
743 		return handle_feature_unit_req(audio_dev_data,
744 					       pSetup, len, data);
745 	default:
746 		LOG_INF("Currently not supported");
747 		return -ENODEV;
748 	}
749 
750 	return 0;
751 }
752 
753 /**
754  * @brief Custom callback for USB Device requests.
755  *
756  * This callback is called when set/get interface request is directed
757  * to the device. This is Zephyr way to address those requests.
758  * It's not possible to do that in the core stack as common USB device
759  * stack does not know the amount of devices that has alternate interfaces.
760  *
761  * @param pSetup    Information about the request to execute.
762  * @param len       Size of the buffer.
763  * @param data      Buffer containing the request result.
764  *
765  * @return 0 on success, positive value if request is intended to be handled
766  *	   by the core USB stack. Negative error code on fail.
767  */
audio_custom_handler(struct usb_setup_packet * pSetup,int32_t * len,uint8_t ** data)768 static int audio_custom_handler(struct usb_setup_packet *pSetup, int32_t *len,
769 				uint8_t **data)
770 {
771 	const struct cs_ac_if_descriptor *header;
772 	struct usb_audio_dev_data *audio_dev_data;
773 	const struct usb_if_descriptor *if_desc;
774 	const struct usb_ep_descriptor *ep_desc;
775 
776 	uint8_t iface = (pSetup->wIndex) & 0xFF;
777 
778 	if (pSetup->RequestType.recipient != USB_REQTYPE_RECIPIENT_INTERFACE ||
779 	    usb_reqtype_is_to_host(pSetup)) {
780 		return -EINVAL;
781 	}
782 
783 	audio_dev_data = get_audio_dev_data_by_iface(iface);
784 	if (audio_dev_data == NULL) {
785 		return -EINVAL;
786 	}
787 
788 	/* Search for endpoint associated to addressed interface
789 	 * Endpoint is searched in order to know the direction of
790 	 * addressed interface.
791 	 */
792 	header = audio_dev_data->desc_hdr;
793 
794 	/* Skip to the first interface */
795 	if_desc = (struct usb_if_descriptor *)((uint8_t *)header +
796 						header->wTotalLength +
797 						USB_PASSIVE_IF_DESC_SIZE);
798 
799 	if (if_desc->bInterfaceNumber == iface) {
800 		ep_desc = (struct usb_ep_descriptor *)((uint8_t *)if_desc +
801 						USB_PASSIVE_IF_DESC_SIZE +
802 						USB_AC_CS_IF_DESC_SIZE +
803 						USB_FORMAT_TYPE_I_DESC_SIZE);
804 	} else {
805 		/* In case first interface address is not the one addressed
806 		 * we can be sure the second one is because
807 		 * get_audio_dev_data_by_iface() found the device. It
808 		 * must be the second interface associated with the device.
809 		 */
810 		if_desc = (struct usb_if_descriptor *)((uint8_t *)if_desc +
811 						USB_ACTIVE_IF_DESC_SIZE);
812 		ep_desc = (struct usb_ep_descriptor *)((uint8_t *)if_desc +
813 						USB_PASSIVE_IF_DESC_SIZE +
814 						USB_AC_CS_IF_DESC_SIZE +
815 						USB_FORMAT_TYPE_I_DESC_SIZE);
816 	}
817 
818 	if (pSetup->bRequest == USB_SREQ_SET_INTERFACE) {
819 		if (ep_desc->bEndpointAddress & USB_EP_DIR_MASK) {
820 			audio_dev_data->tx_enable = pSetup->wValue;
821 		} else {
822 			audio_dev_data->rx_enable = pSetup->wValue;
823 		}
824 	}
825 
826 	return -EINVAL;
827 }
828 
829 /**
830  * @brief Handler called for Class requests not handled by the USB stack.
831  *
832  * @param pSetup    Information about the request to execute.
833  * @param len       Size of the buffer.
834  * @param data      Buffer containing the request result.
835  *
836  * @return  0 on success, negative errno code on fail.
837  */
audio_class_handle_req(struct usb_setup_packet * pSetup,int32_t * len,uint8_t ** data)838 static int audio_class_handle_req(struct usb_setup_packet *pSetup,
839 				  int32_t *len, uint8_t **data)
840 {
841 	LOG_DBG("bmRT 0x%02x, bR 0x%02x, wV 0x%04x, wI 0x%04x, wL 0x%04x",
842 		pSetup->bmRequestType, pSetup->bRequest, pSetup->wValue,
843 		pSetup->wIndex, pSetup->wLength);
844 
845 	switch (pSetup->RequestType.recipient) {
846 	case USB_REQTYPE_RECIPIENT_INTERFACE:
847 		return handle_interface_req(pSetup, len, data);
848 	default:
849 		LOG_ERR("Request recipient invalid");
850 		return -EINVAL;
851 	}
852 }
853 
usb_audio_device_init(const struct device * dev)854 static int usb_audio_device_init(const struct device *dev)
855 {
856 	LOG_DBG("Init Audio Device: dev %p (%s)", dev, dev->name);
857 
858 	return 0;
859 }
860 
audio_write_cb(uint8_t ep,int size,void * priv)861 static void audio_write_cb(uint8_t ep, int size, void *priv)
862 {
863 	struct usb_dev_data *dev_data;
864 	struct usb_audio_dev_data *audio_dev_data;
865 	struct net_buf *buffer = priv;
866 
867 	dev_data = usb_get_dev_data_by_ep(&usb_audio_data_devlist, ep);
868 	audio_dev_data = dev_data->dev->data;
869 
870 	LOG_DBG("Written %d bytes on ep 0x%02x, *audio_dev_data %p",
871 		size, ep, audio_dev_data);
872 
873 	/* Ask installed callback to process the data.
874 	 * User is responsible for freeing the buffer.
875 	 * In case no callback is installed free the buffer.
876 	 */
877 	if (audio_dev_data->ops && audio_dev_data->ops->data_written_cb) {
878 		audio_dev_data->ops->data_written_cb(dev_data->dev,
879 						     buffer, size);
880 	} else {
881 		/* Release net_buf back to the pool */
882 		net_buf_unref(buffer);
883 	}
884 }
885 
usb_audio_send(const struct device * dev,struct net_buf * buffer,size_t len)886 int usb_audio_send(const struct device *dev, struct net_buf *buffer,
887 		   size_t len)
888 {
889 	struct usb_audio_dev_data *audio_dev_data = dev->data;
890 	struct usb_cfg_data *cfg = (void *)dev->config;
891 	/* EP ISO IN is always placed first in the endpoint table */
892 	uint8_t ep = cfg->endpoint[0].ep_addr;
893 
894 	if (!(ep & USB_EP_DIR_MASK)) {
895 		LOG_ERR("Wrong device");
896 		return -EINVAL;
897 	}
898 
899 	if (!audio_dev_data->tx_enable) {
900 		LOG_DBG("sending dropped -> Host chose passive interface");
901 		return -EAGAIN;
902 	}
903 
904 	if (len > buffer->size) {
905 		LOG_ERR("Cannot send %d bytes, to much data", len);
906 		return -EINVAL;
907 	}
908 
909 	/** buffer passed to *priv because completion callback
910 	 * needs to release it to the pool
911 	 */
912 	return usb_transfer(ep, buffer->data, len, USB_TRANS_WRITE | USB_TRANS_NO_ZLP,
913 		     audio_write_cb, buffer);
914 }
915 
usb_audio_get_in_frame_size(const struct device * dev)916 size_t usb_audio_get_in_frame_size(const struct device *dev)
917 {
918 	struct usb_audio_dev_data *audio_dev_data = dev->data;
919 
920 	return audio_dev_data->in_frame_size;
921 }
922 
923 #if (HEADPHONES_DEVICE_COUNT > 0 || HEADSET_DEVICE_COUNT > 0)
audio_receive_cb(uint8_t ep,enum usb_dc_ep_cb_status_code status)924 static void audio_receive_cb(uint8_t ep, enum usb_dc_ep_cb_status_code status)
925 {
926 	struct usb_audio_dev_data *audio_dev_data;
927 	struct usb_dev_data *common;
928 	struct net_buf *buffer;
929 	int ret_bytes;
930 	int ret;
931 
932 	__ASSERT(status == USB_DC_EP_DATA_OUT, "Invalid ep status");
933 
934 	common = usb_get_dev_data_by_ep(&usb_audio_data_devlist, ep);
935 	if (common == NULL) {
936 		return;
937 	}
938 
939 	audio_dev_data = CONTAINER_OF(common, struct usb_audio_dev_data,
940 				      common);
941 
942 	/** Check if active audiostreaming interface is selected
943 	 * If no there is no point to read the data. Return from callback
944 	 */
945 	if (!audio_dev_data->rx_enable) {
946 		return;
947 	}
948 
949 	/* Check if application installed callback and process the data.
950 	 * In case no callback is installed do not alloc the buffer at all.
951 	 */
952 	if (audio_dev_data->ops && audio_dev_data->ops->data_received_cb) {
953 		buffer = net_buf_alloc(audio_dev_data->pool, K_NO_WAIT);
954 		if (!buffer) {
955 			LOG_ERR("Failed to allocate data buffer");
956 			return;
957 		}
958 
959 		ret = usb_read(ep, buffer->data, buffer->size, &ret_bytes);
960 
961 		if (ret) {
962 			LOG_ERR("ret=%d ", ret);
963 			net_buf_unref(buffer);
964 			return;
965 		}
966 
967 		if (!ret_bytes) {
968 			net_buf_unref(buffer);
969 			return;
970 		}
971 		audio_dev_data->ops->data_received_cb(common->dev,
972 						      buffer, ret_bytes);
973 	}
974 }
975 #endif /* #if (HEADPHONES_DEVICE_COUNT > 0 || HEADSET_DEVICE_COUNT > 0) */
976 
usb_audio_register(const struct device * dev,const struct usb_audio_ops * ops)977 void usb_audio_register(const struct device *dev,
978 			const struct usb_audio_ops *ops)
979 {
980 	struct usb_audio_dev_data *audio_dev_data = dev->data;
981 	const struct usb_cfg_data *cfg = dev->config;
982 	const struct std_if_descriptor *iface_descr =
983 		cfg->interface_descriptor;
984 	const struct cs_ac_if_descriptor *header =
985 		(struct cs_ac_if_descriptor *)
986 		((uint8_t *)iface_descr + USB_PASSIVE_IF_DESC_SIZE);
987 
988 	audio_dev_data->ops = ops;
989 	audio_dev_data->common.dev = dev;
990 	audio_dev_data->rx_enable = false;
991 	audio_dev_data->tx_enable = false;
992 	audio_dev_data->desc_hdr = header;
993 
994 	sys_slist_append(&usb_audio_data_devlist, &audio_dev_data->common.node);
995 
996 	LOG_DBG("Device dev %p dev_data %p cfg %p added to devlist %p",
997 		dev, audio_dev_data, dev->config,
998 		&usb_audio_data_devlist);
999 }
1000 
1001 #define DEFINE_AUDIO_DEVICE(dev, i)					  \
1002 	USBD_DEFINE_CFG_DATA(dev##_audio_config_##i) = {		  \
1003 		.usb_device_description	= NULL,				  \
1004 		.interface_config = audio_interface_config,		  \
1005 		.interface_descriptor = &dev##_desc_##i.std_ac_interface, \
1006 		.cb_usb_status = audio_cb_usb_status,			  \
1007 		.interface = {						  \
1008 			.class_handler = audio_class_handle_req,	  \
1009 			.custom_handler = audio_custom_handler,		  \
1010 			.vendor_handler = NULL,				  \
1011 		},							  \
1012 		.num_endpoints = ARRAY_SIZE(dev##_usb_audio_ep_data_##i), \
1013 		.endpoint = dev##_usb_audio_ep_data_##i,		  \
1014 	};								  \
1015 	DEVICE_DT_DEFINE(DT_INST(i, COMPAT_##dev),			  \
1016 			    &usb_audio_device_init,			  \
1017 			    NULL,					  \
1018 			    &dev##_audio_dev_data_##i,			  \
1019 			    &dev##_audio_config_##i, POST_KERNEL,	  \
1020 			    CONFIG_KERNEL_INIT_PRIORITY_DEVICE,		  \
1021 			    DUMMY_API)
1022 
1023 #define DEFINE_BUF_POOL(name, size) \
1024 	NET_BUF_POOL_FIXED_DEFINE(name, 5, size, 4, net_buf_destroy)
1025 
1026 #define UNIDIR_DEVICE(dev, i, out_pool, in_size, it_type, ot_type, cb, addr) \
1027 	UTIL_EXPAND( \
1028 	DEFINE_AUDIO_DEV_DATA(dev, i, out_pool, in_size); \
1029 	DECLARE_DESCRIPTOR(dev, i, 1); \
1030 	DEFINE_AUDIO_DESCRIPTOR(dev, i, dev##_ID(i), dev##_LINK(i), \
1031 				it_type, ot_type, cb, addr); \
1032 	DEFINE_AUDIO_DEVICE(dev, i))
1033 
1034 #define HEADPHONES_DEVICE(i, dev) UTIL_EXPAND( \
1035 	DEFINE_BUF_POOL(audio_data_pool_hp_##i, EP_SIZE(dev, i));  \
1036 	UNIDIR_DEVICE(dev, i, &audio_data_pool_hp_##i, 0, \
1037 		      USB_AUDIO_USB_STREAMING, USB_AUDIO_OUT_HEADPHONES, \
1038 		      audio_receive_cb, AUTO_EP_OUT);)
1039 
1040 #define MICROPHONE_DEVICE(i, dev) UTIL_EXPAND( \
1041 	UNIDIR_DEVICE(dev, i, NULL, EP_SIZE(dev, i), \
1042 		      USB_AUDIO_IN_MICROPHONE, USB_AUDIO_USB_STREAMING, \
1043 		      usb_transfer_ep_callback, AUTO_EP_IN);)
1044 
1045 #define HEADSET_DEVICE(i, dev) UTIL_EXPAND( \
1046 	DEFINE_BUF_POOL(audio_data_pool_hs_##i, EP_SIZE(dev##_HP, i)); \
1047 	DEFINE_AUDIO_DEV_DATA_BIDIR(dev, i, &audio_data_pool_hs_##i, \
1048 				    EP_SIZE(dev##_MIC, i)); \
1049 	DECLARE_DESCRIPTOR_BIDIR(dev, i, 2); \
1050 	DEFINE_AUDIO_DESCRIPTOR_BIDIR(dev, i, dev##_ID(i)); \
1051 	DEFINE_AUDIO_DEVICE(dev, i);)
1052 
1053 LISTIFY(HEADPHONES_DEVICE_COUNT, HEADPHONES_DEVICE, (), HP)
1054 LISTIFY(MICROPHONE_DEVICE_COUNT, MICROPHONE_DEVICE, (), MIC)
1055 LISTIFY(HEADSET_DEVICE_COUNT, HEADSET_DEVICE, (), HS)
1056