blob: b08b362f9f5bda1b739f4693d50421d2fd4515b7 [file] [log] [blame]
Austin Schuh41baf202022-01-01 14:33:40 -08001/*
2 * The MIT License (MIT)
3 *
4 * Copyright (c) 2019 Ha Thach (tinyusb.org)
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 *
24 * This file is part of the TinyUSB stack.
25 */
26
27#include "tusb_option.h"
28
29#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_MIDI)
30
31//--------------------------------------------------------------------+
32// INCLUDE
33//--------------------------------------------------------------------+
34#include "device/usbd.h"
35#include "device/usbd_pvt.h"
36
37#include "midi_device.h"
38
39//--------------------------------------------------------------------+
40// MACRO CONSTANT TYPEDEF
41//--------------------------------------------------------------------+
42
43typedef struct
44{
45 uint8_t buffer[4];
46 uint8_t index;
47 uint8_t total;
48}midid_stream_t;
49
50typedef struct
51{
52 uint8_t itf_num;
53 uint8_t ep_in;
54 uint8_t ep_out;
55
56 // For Stream read()/write() API
57 // Messages are always 4 bytes long, queue them for reading and writing so the
58 // callers can use the Stream interface with single-byte read/write calls.
59 midid_stream_t stream_write;
60 midid_stream_t stream_read;
61
62 /*------------- From this point, data is not cleared by bus reset -------------*/
63 // FIFO
64 tu_fifo_t rx_ff;
65 tu_fifo_t tx_ff;
66 uint8_t rx_ff_buf[CFG_TUD_MIDI_RX_BUFSIZE];
67 uint8_t tx_ff_buf[CFG_TUD_MIDI_TX_BUFSIZE];
68
69 #if CFG_FIFO_MUTEX
70 osal_mutex_def_t rx_ff_mutex;
71 osal_mutex_def_t tx_ff_mutex;
72 #endif
73
74 // Endpoint Transfer buffer
75 CFG_TUSB_MEM_ALIGN uint8_t epout_buf[CFG_TUD_MIDI_EP_BUFSIZE];
76 CFG_TUSB_MEM_ALIGN uint8_t epin_buf[CFG_TUD_MIDI_EP_BUFSIZE];
77
78} midid_interface_t;
79
80#define ITF_MEM_RESET_SIZE offsetof(midid_interface_t, rx_ff)
81
82//--------------------------------------------------------------------+
83// INTERNAL OBJECT & FUNCTION DECLARATION
84//--------------------------------------------------------------------+
85CFG_TUSB_MEM_SECTION midid_interface_t _midid_itf[CFG_TUD_MIDI];
86
87bool tud_midi_n_mounted (uint8_t itf)
88{
89 midid_interface_t* midi = &_midid_itf[itf];
90 return midi->ep_in && midi->ep_out;
91}
92
93static void _prep_out_transaction (midid_interface_t* p_midi)
94{
95 uint8_t const rhport = TUD_OPT_RHPORT;
96 uint16_t available = tu_fifo_remaining(&p_midi->rx_ff);
97
98 // Prepare for incoming data but only allow what we can store in the ring buffer.
99 // TODO Actually we can still carry out the transfer, keeping count of received bytes
100 // and slowly move it to the FIFO when read().
101 // This pre-check reduces endpoint claiming
102 TU_VERIFY(available >= sizeof(p_midi->epout_buf), );
103
104 // claim endpoint
105 TU_VERIFY(usbd_edpt_claim(rhport, p_midi->ep_out), );
106
107 // fifo can be changed before endpoint is claimed
108 available = tu_fifo_remaining(&p_midi->rx_ff);
109
110 if ( available >= sizeof(p_midi->epout_buf) ) {
111 usbd_edpt_xfer(rhport, p_midi->ep_out, p_midi->epout_buf, sizeof(p_midi->epout_buf));
112 }else
113 {
114 // Release endpoint since we don't make any transfer
115 usbd_edpt_release(rhport, p_midi->ep_out);
116 }
117}
118
119//--------------------------------------------------------------------+
120// READ API
121//--------------------------------------------------------------------+
122uint32_t tud_midi_n_available(uint8_t itf, uint8_t cable_num)
123{
124 (void) cable_num;
125
126 midid_interface_t* midi = &_midid_itf[itf];
127 midid_stream_t const* stream = &midi->stream_read;
128
129 // when using with packet API stream total & index are both zero
130 return tu_fifo_count(&midi->rx_ff) + (stream->total - stream->index);
131}
132
133uint32_t tud_midi_n_stream_read(uint8_t itf, uint8_t cable_num, void* buffer, uint32_t bufsize)
134{
135 (void) cable_num;
136 TU_VERIFY(bufsize, 0);
137
138 uint8_t* buf8 = (uint8_t*) buffer;
139
140 midid_interface_t* midi = &_midid_itf[itf];
141 midid_stream_t* stream = &midi->stream_read;
142
143 uint32_t total_read = 0;
144 while( bufsize )
145 {
146 // Get new packet from fifo, then set packet expected bytes
147 if ( stream->total == 0 )
148 {
149 // return if there is no more data from fifo
150 if ( !tud_midi_n_packet_read(itf, stream->buffer) ) return total_read;
151
152 uint8_t const code_index = stream->buffer[0] & 0x0f;
153
154 // MIDI 1.0 Table 4-1: Code Index Number Classifications
155 switch(code_index)
156 {
157 case MIDI_CIN_MISC:
158 case MIDI_CIN_CABLE_EVENT:
159 // These are reserved and unused, possibly issue somewhere, skip this packet
160 return 0;
161 break;
162
163 case MIDI_CIN_SYSEX_END_1BYTE:
164 case MIDI_CIN_1BYTE_DATA:
165 stream->total = 1;
166 break;
167
168 case MIDI_CIN_SYSCOM_2BYTE :
169 case MIDI_CIN_SYSEX_END_2BYTE :
170 case MIDI_CIN_PROGRAM_CHANGE :
171 case MIDI_CIN_CHANNEL_PRESSURE :
172 stream->total = 2;
173 break;
174
175 default:
176 stream->total = 3;
177 break;
178 }
179 }
180
181 // Copy data up to bufsize
182 uint32_t const count = tu_min32(stream->total - stream->index, bufsize);
183
184 // Skip the header (1st byte) in the buffer
185 memcpy(buf8, stream->buffer + 1 + stream->index, count);
186
187 total_read += count;
188 stream->index += count;
189 buf8 += count;
190 bufsize -= count;
191
192 // complete current event packet, reset stream
193 if ( stream->total == stream->index )
194 {
195 stream->index = 0;
196 stream->total = 0;
197 }
198 }
199
200 return total_read;
201}
202
203bool tud_midi_n_packet_read (uint8_t itf, uint8_t packet[4])
204{
205 midid_interface_t* midi = &_midid_itf[itf];
206 TU_VERIFY(midi->ep_out);
207
208 uint32_t const num_read = tu_fifo_read_n(&midi->rx_ff, packet, 4);
209 _prep_out_transaction(midi);
210 return (num_read == 4);
211}
212
213//--------------------------------------------------------------------+
214// WRITE API
215//--------------------------------------------------------------------+
216
217static uint32_t write_flush(midid_interface_t* midi)
218{
219 // No data to send
220 if ( !tu_fifo_count(&midi->tx_ff) ) return 0;
221
222 uint8_t const rhport = TUD_OPT_RHPORT;
223
224 // skip if previous transfer not complete
225 TU_VERIFY( usbd_edpt_claim(rhport, midi->ep_in), 0 );
226
227 uint16_t count = tu_fifo_read_n(&midi->tx_ff, midi->epin_buf, CFG_TUD_MIDI_EP_BUFSIZE);
228
229 if (count)
230 {
231 TU_ASSERT( usbd_edpt_xfer(rhport, midi->ep_in, midi->epin_buf, count), 0 );
232 return count;
233 }else
234 {
235 // Release endpoint since we don't make any transfer
236 usbd_edpt_release(rhport, midi->ep_in);
237 return 0;
238 }
239}
240
241uint32_t tud_midi_n_stream_write(uint8_t itf, uint8_t cable_num, uint8_t const* buffer, uint32_t bufsize)
242{
243 midid_interface_t* midi = &_midid_itf[itf];
244 TU_VERIFY(midi->ep_in, 0);
245
246 midid_stream_t* stream = &midi->stream_write;
247
248 uint32_t i = 0;
249 while ( (i < bufsize) && (tu_fifo_remaining(&midi->tx_ff) >= 4) )
250 {
251 uint8_t const data = buffer[i];
252 i++;
253
254 if ( stream->index == 0 )
255 {
256 //------------- New event packet -------------//
257
258 uint8_t const msg = data >> 4;
259
260 stream->index = 2;
261 stream->buffer[1] = data;
262
263 // Check to see if we're still in a SysEx transmit.
264 if ( stream->buffer[0] == MIDI_CIN_SYSEX_START )
265 {
266 if ( data == MIDI_STATUS_SYSEX_END )
267 {
268 stream->buffer[0] = MIDI_CIN_SYSEX_END_1BYTE;
269 stream->total = 2;
270 }
271 else
272 {
273 stream->total = 4;
274 }
275 }
276 else if ( (msg >= 0x8 && msg <= 0xB) || msg == 0xE )
277 {
278 // Channel Voice Messages
279 stream->buffer[0] = (cable_num << 4) | msg;
280 stream->total = 4;
281 }
282 else if ( msg == 0xC || msg == 0xD)
283 {
284 // Channel Voice Messages, two-byte variants (Program Change and Channel Pressure)
285 stream->buffer[0] = (cable_num << 4) | msg;
286 stream->total = 3;
287 }
288 else if ( msg == 0xf )
289 {
290 // System message
291 if ( data == MIDI_STATUS_SYSEX_START )
292 {
293 stream->buffer[0] = MIDI_CIN_SYSEX_START;
294 stream->total = 4;
295 }
296 else if ( data == MIDI_STATUS_SYSCOM_TIME_CODE_QUARTER_FRAME || data == MIDI_STATUS_SYSCOM_SONG_SELECT )
297 {
298 stream->buffer[0] = MIDI_CIN_SYSCOM_2BYTE;
299 stream->total = 3;
300 }
301 else if ( data == MIDI_STATUS_SYSCOM_SONG_POSITION_POINTER )
302 {
303 stream->buffer[0] = MIDI_CIN_SYSCOM_3BYTE;
304 stream->total = 4;
305 }
306 else
307 {
308 stream->buffer[0] = MIDI_CIN_SYSEX_END_1BYTE;
309 stream->total = 2;
310 }
311 }
312 else
313 {
314 // Pack individual bytes if we don't support packing them into words.
315 stream->buffer[0] = cable_num << 4 | 0xf;
316 stream->buffer[2] = 0;
317 stream->buffer[3] = 0;
318 stream->index = 2;
319 stream->total = 2;
320 }
321 }
322 else
323 {
324 //------------- On-going (buffering) packet -------------//
325
326 TU_ASSERT(stream->index < 4, i);
327 stream->buffer[stream->index] = data;
328 stream->index++;
329
330 // See if this byte ends a SysEx.
331 if ( stream->buffer[0] == MIDI_CIN_SYSEX_START && data == MIDI_STATUS_SYSEX_END )
332 {
333 stream->buffer[0] = MIDI_CIN_SYSEX_START + (stream->index - 1);
334 stream->total = stream->index;
335 }
336 }
337
338 // Send out packet
339 if ( stream->index == stream->total )
340 {
341 // zeroes unused bytes
342 for(uint8_t idx = stream->total; idx < 4; idx++) stream->buffer[idx] = 0;
343
344 uint16_t const count = tu_fifo_write_n(&midi->tx_ff, stream->buffer, 4);
345
346 // complete current event packet, reset stream
347 stream->index = stream->total = 0;
348
349 // FIFO overflown, since we already check fifo remaining. It is probably race condition
350 TU_ASSERT(count == 4, i);
351 }
352 }
353
354 write_flush(midi);
355
356 return i;
357}
358
359bool tud_midi_n_packet_write (uint8_t itf, uint8_t const packet[4])
360{
361 midid_interface_t* midi = &_midid_itf[itf];
362 TU_VERIFY(midi->ep_in);
363
364 if (tu_fifo_remaining(&midi->tx_ff) < 4) return false;
365
366 tu_fifo_write_n(&midi->tx_ff, packet, 4);
367 write_flush(midi);
368
369 return true;
370}
371
372//--------------------------------------------------------------------+
373// USBD Driver API
374//--------------------------------------------------------------------+
375void midid_init(void)
376{
377 tu_memclr(_midid_itf, sizeof(_midid_itf));
378
379 for(uint8_t i=0; i<CFG_TUD_MIDI; i++)
380 {
381 midid_interface_t* midi = &_midid_itf[i];
382
383 // config fifo
384 tu_fifo_config(&midi->rx_ff, midi->rx_ff_buf, CFG_TUD_MIDI_RX_BUFSIZE, 1, false); // true, true
385 tu_fifo_config(&midi->tx_ff, midi->tx_ff_buf, CFG_TUD_MIDI_TX_BUFSIZE, 1, false); // OBVS.
386
387 #if CFG_FIFO_MUTEX
388 tu_fifo_config_mutex(&midi->rx_ff, NULL, osal_mutex_create(&midi->rx_ff_mutex));
389 tu_fifo_config_mutex(&midi->tx_ff, osal_mutex_create(&midi->tx_ff_mutex), NULL);
390 #endif
391 }
392}
393
394void midid_reset(uint8_t rhport)
395{
396 (void) rhport;
397
398 for(uint8_t i=0; i<CFG_TUD_MIDI; i++)
399 {
400 midid_interface_t* midi = &_midid_itf[i];
401 tu_memclr(midi, ITF_MEM_RESET_SIZE);
402 tu_fifo_clear(&midi->rx_ff);
403 tu_fifo_clear(&midi->tx_ff);
404 }
405}
406
407uint16_t midid_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, uint16_t max_len)
408{
409 // 1st Interface is Audio Control v1
410 TU_VERIFY(TUSB_CLASS_AUDIO == desc_itf->bInterfaceClass &&
411 AUDIO_SUBCLASS_CONTROL == desc_itf->bInterfaceSubClass &&
412 AUDIO_FUNC_PROTOCOL_CODE_UNDEF == desc_itf->bInterfaceProtocol, 0);
413
414 uint16_t drv_len = tu_desc_len(desc_itf);
415 uint8_t const * p_desc = tu_desc_next(desc_itf);
416
417 // Skip Class Specific descriptors
418 while ( TUSB_DESC_CS_INTERFACE == tu_desc_type(p_desc) && drv_len <= max_len )
419 {
420 drv_len += tu_desc_len(p_desc);
421 p_desc = tu_desc_next(p_desc);
422 }
423
424 // 2nd Interface is MIDI Streaming
425 TU_VERIFY(TUSB_DESC_INTERFACE == tu_desc_type(p_desc), 0);
426 tusb_desc_interface_t const * desc_midi = (tusb_desc_interface_t const *) p_desc;
427
428 TU_VERIFY(TUSB_CLASS_AUDIO == desc_midi->bInterfaceClass &&
429 AUDIO_SUBCLASS_MIDI_STREAMING == desc_midi->bInterfaceSubClass &&
430 AUDIO_FUNC_PROTOCOL_CODE_UNDEF == desc_midi->bInterfaceProtocol, 0);
431
432 // Find available interface
433 midid_interface_t * p_midi = NULL;
434 for(uint8_t i=0; i<CFG_TUD_MIDI; i++)
435 {
436 if ( _midid_itf[i].ep_in == 0 && _midid_itf[i].ep_out == 0 )
437 {
438 p_midi = &_midid_itf[i];
439 break;
440 }
441 }
442 TU_ASSERT(p_midi);
443
444 p_midi->itf_num = desc_midi->bInterfaceNumber;
445 (void) p_midi->itf_num;
446
447 // next descriptor
448 drv_len += tu_desc_len(p_desc);
449 p_desc = tu_desc_next(p_desc);
450
451 // Find and open endpoint descriptors
452 uint8_t found_endpoints = 0;
453 while ( (found_endpoints < desc_midi->bNumEndpoints) && (drv_len <= max_len) )
454 {
455 if ( TUSB_DESC_ENDPOINT == tu_desc_type(p_desc) )
456 {
457 TU_ASSERT(usbd_edpt_open(rhport, (tusb_desc_endpoint_t const *) p_desc), 0);
458 uint8_t ep_addr = ((tusb_desc_endpoint_t const *) p_desc)->bEndpointAddress;
459
460 if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN)
461 {
462 p_midi->ep_in = ep_addr;
463 } else {
464 p_midi->ep_out = ep_addr;
465 }
466
467 // Class Specific MIDI Stream endpoint descriptor
468 drv_len += tu_desc_len(p_desc);
469 p_desc = tu_desc_next(p_desc);
470
471 found_endpoints += 1;
472 }
473
474 drv_len += tu_desc_len(p_desc);
475 p_desc = tu_desc_next(p_desc);
476 }
477
478 // Prepare for incoming data
479 _prep_out_transaction(p_midi);
480
481 return drv_len;
482}
483
484// Invoked when a control transfer occurred on an interface of this class
485// Driver response accordingly to the request and the transfer stage (setup/data/ack)
486// return false to stall control endpoint (e.g unsupported request)
487bool midid_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request)
488{
489 (void) rhport;
490 (void) stage;
491 (void) request;
492
493 // driver doesn't support any request yet
494 return false;
495}
496
497bool midid_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes)
498{
499 (void) result;
500 (void) rhport;
501
502 uint8_t itf;
503 midid_interface_t* p_midi;
504
505 // Identify which interface to use
506 for (itf = 0; itf < CFG_TUD_MIDI; itf++)
507 {
508 p_midi = &_midid_itf[itf];
509 if ( ( ep_addr == p_midi->ep_out ) || ( ep_addr == p_midi->ep_in ) ) break;
510 }
511 TU_ASSERT(itf < CFG_TUD_MIDI);
512
513 // receive new data
514 if ( ep_addr == p_midi->ep_out )
515 {
516 tu_fifo_write_n(&p_midi->rx_ff, p_midi->epout_buf, xferred_bytes);
517
518 // invoke receive callback if available
519 if (tud_midi_rx_cb) tud_midi_rx_cb(itf);
520
521 // prepare for next
522 // TODO for now ep_out is not used by public API therefore there is no race condition,
523 // and does not need to claim like ep_in
524 _prep_out_transaction(p_midi);
525 }
526 else if ( ep_addr == p_midi->ep_in )
527 {
528 if (0 == write_flush(p_midi))
529 {
530 // If there is no data left, a ZLP should be sent if
531 // xferred_bytes is multiple of EP size and not zero
532 if ( !tu_fifo_count(&p_midi->tx_ff) && xferred_bytes && (0 == (xferred_bytes % CFG_TUD_MIDI_EP_BUFSIZE)) )
533 {
534 if ( usbd_edpt_claim(rhport, p_midi->ep_in) )
535 {
536 usbd_edpt_xfer(rhport, p_midi->ep_in, NULL, 0);
537 }
538 }
539 }
540 }
541
542 return true;
543}
544
545#endif