2 Calf Box, an open source musical instrument.
3 Copyright (C) 2010-2013 Krzysztof Foltman
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
21 #include "usbio_impl.h"
27 #define NUM_SYNC_PACKETS 10
29 #define MULTIMIX_EP_PLAYBACK 0x02
30 //#define MULTIMIX_EP_CAPTURE 0x86
31 #define MULTIMIX_EP_SYNC 0x81
33 #define NUM_CPUTIME_ENTRIES 100
35 static int register_cpu_time
= 1;
36 static float real_time_registry
[NUM_CPUTIME_ENTRIES
];
37 static float cpu_time_registry
[NUM_CPUTIME_ENTRIES
];
38 static int cpu_time_write_ptr
= 0;
39 static void usbio_play_buffer_adaptive(struct cbox_usb_io_impl
*uii
);
41 ///////////////////////////////////////////////////////////////////////////////
43 static gboolean
set_endpoint_sample_rate(struct libusb_device_handle
*h
, int sample_rate
, int ep
)
46 freq_data
[0] = sample_rate
& 0xFF;
47 freq_data
[1] = (sample_rate
& 0xFF00) >> 8;
48 freq_data
[2] = (sample_rate
& 0xFF0000) >> 16;
49 if (libusb_control_transfer(h
, 0x22, 0x01, 256, ep
, freq_data
, 3, USB_DEVICE_SETUP_TIMEOUT
) != 3)
54 ///////////////////////////////////////////////////////////////////////////////
56 gboolean
usbio_open_audio_interface(struct cbox_usb_io_impl
*uii
, struct cbox_usb_audio_info
*uainf
, struct libusb_device_handle
*handle
, GError
**error
)
58 if (uii
->output_resolution
!= 2 && uii
->output_resolution
!= 3)
60 g_set_error(error
, CBOX_MODULE_ERROR
, CBOX_MODULE_ERROR_FAILED
, "Only 16-bit or 24-bit output resolution is supported.");
63 if (!configure_usb_interface(handle
, uainf
->udi
->bus
, uainf
->udi
->devadr
, uainf
->intf
, uainf
->alt_setting
, error
))
65 if (!set_endpoint_sample_rate(handle
, uii
->sample_rate
, uainf
->epdesc
.bEndpointAddress
))
67 g_set_error(error
, CBOX_MODULE_ERROR
, CBOX_MODULE_ERROR_FAILED
, "Cannot set sample rate on class-compliant USB audio device.");
70 uii
->play_function
= usbio_play_buffer_adaptive
;
71 uii
->handle_audiodev
= handle
;
72 uii
->audio_output_endpoint
= uainf
->epdesc
.bEndpointAddress
;
73 uii
->audio_output_pktsize
= uainf
->epdesc
.wMaxPacketSize
; // 48 * 2 * uii->output_resolution;
74 uii
->audio_sync_endpoint
= 0;
78 ///////////////////////////////////////////////////////////////////////////////
80 static gboolean
claim_multimix_interfaces(struct cbox_usb_io_impl
*uii
, struct libusb_device_handle
*handle
, int bus
, int devadr
, GError
**error
)
82 static int interfaces
[] = { 0, 1 };
83 for (int i
= 0; i
< sizeof(interfaces
) / sizeof(int); i
++)
85 int ifno
= interfaces
[i
];
86 if (!configure_usb_interface(handle
, bus
, devadr
, ifno
, 1, error
))
92 gboolean
usbio_open_audio_interface_multimix(struct cbox_usb_io_impl
*uii
, int bus
, int devadr
, struct libusb_device_handle
*handle
, GError
**error
)
94 if (uii
->output_resolution
!= 3)
96 g_set_error(error
, CBOX_MODULE_ERROR
, CBOX_MODULE_ERROR_FAILED
, "Only 24-bit output resolution is supported.");
99 if (!claim_multimix_interfaces(uii
, handle
, bus
, devadr
, error
))
101 if (!set_endpoint_sample_rate(handle
, uii
->sample_rate
, MULTIMIX_EP_PLAYBACK
))
103 g_set_error(error
, CBOX_MODULE_ERROR
, CBOX_MODULE_ERROR_FAILED
, "Cannot set sample rate on Alesis Multimix.");
107 uii
->play_function
= usbio_play_buffer_asynchronous
;
108 uii
->handle_audiodev
= handle
;
109 uii
->audio_output_endpoint
= MULTIMIX_EP_PLAYBACK
;
110 uii
->audio_output_pktsize
= 156;
111 uii
->audio_sync_endpoint
= MULTIMIX_EP_SYNC
;
115 ///////////////////////////////////////////////////////////////////////////////
117 static void calc_output_buffer(struct cbox_usb_io_impl
*uii
)
119 struct timespec tvs1
, tve1
, tvs2
, tve2
;
120 if (register_cpu_time
)
122 clock_gettime(CLOCK_MONOTONIC_RAW
, &tvs1
);
123 clock_gettime(CLOCK_THREAD_CPUTIME_ID
, &tvs2
);
125 struct cbox_io
*io
= uii
->ioi
.pio
;
126 for (int b
= 0; b
< uii
->output_channels
; b
++)
127 memset(io
->output_buffers
[b
], 0, io
->buffer_size
* sizeof(float));
128 io
->cb
->process(io
->cb
->user_data
, io
, io
->buffer_size
);
129 for (GList
*p
= uii
->rt_midi_input_ports
; p
; p
= p
->next
)
131 struct cbox_usb_midi_input
*umi
= p
->data
;
132 cbox_midi_buffer_clear(&umi
->midi_buffer
);
134 if (register_cpu_time
)
136 clock_gettime(CLOCK_MONOTONIC_RAW
, &tve1
);
137 clock_gettime(CLOCK_THREAD_CPUTIME_ID
, &tve2
);
138 float time1
= tve1
.tv_sec
- tvs1
.tv_sec
+ (tve1
.tv_nsec
- tvs1
.tv_nsec
) / 1000000000.0;
139 float time2
= tve2
.tv_sec
- tvs2
.tv_sec
+ (tve2
.tv_nsec
- tvs2
.tv_nsec
) / 1000000000.0;
140 real_time_registry
[cpu_time_write_ptr
] = time1
;
141 cpu_time_registry
[cpu_time_write_ptr
] = time2
;
142 cpu_time_write_ptr
= (cpu_time_write_ptr
+ 1) % NUM_CPUTIME_ENTRIES
;
143 if (time1
> 0.0008 || time2
> 0.0008)
144 g_warning("CPU time = %f ms, real time = %f ms", time2
* 1000, time1
* 1000);
148 static void fill_playback_buffer(struct cbox_usb_io_impl
*uii
, struct libusb_transfer
*transfer
)
150 static double phase
= 0;
151 static int phase2
= 0;
152 struct cbox_io
*io
= uii
->ioi
.pio
;
153 uint8_t *data8
= (uint8_t*)transfer
->buffer
;
154 int16_t *data
= (int16_t*)transfer
->buffer
;
155 int resolution
= uii
->output_resolution
;
156 int oc
= uii
->output_channels
;
157 int rptr
= uii
->read_ptr
;
158 int nframes
= transfer
->length
/ (resolution
* oc
);
161 for (i
= 0; i
< nframes
; )
163 if (rptr
== io
->buffer_size
)
165 calc_output_buffer(uii
);
168 int left1
= nframes
- i
;
169 int left2
= io
->buffer_size
- rptr
;
173 for (b
= 0; b
< oc
; b
++)
175 float *obuf
= io
->output_buffers
[b
] + rptr
;
178 int16_t *tbuf
= data
+ oc
* i
+ b
;
179 for (j
= 0; j
< left1
; j
++)
181 float v
= 32767 * obuf
[j
];
192 uint8_t *tbuf
= data8
+ (oc
* i
+ b
) * 3;
193 for (j
= 0; j
< left1
; j
++)
195 float v
= 0x7FFFFF * obuf
[j
];
202 tbuf
[1] = (vi
>> 8) & 255;
203 tbuf
[2] = (vi
>> 16) & 255;
211 uii
->read_ptr
= rptr
;
214 static void play_callback_adaptive(struct libusb_transfer
*transfer
)
216 struct usbio_transfer
*xf
= transfer
->user_data
;
217 struct cbox_usb_io_impl
*uii
= xf
->user_data
;
219 if (transfer
->status
== LIBUSB_TRANSFER_CANCELLED
)
221 xf
->cancel_confirm
= 1;
224 if (transfer
->status
== LIBUSB_TRANSFER_NO_DEVICE
)
226 uii
->device_removed
++;
230 int resolution
= uii
->output_resolution
;
231 int oc
= uii
->output_channels
;
232 gboolean init_finished
= uii
->playback_counter
== uii
->playback_buffers
;
233 if (uii
->playback_counter
< uii
->playback_buffers
)
235 // send another URB for the next transfer before re-submitting
237 usbio_play_buffer_adaptive(uii
);
239 // printf("Play Callback! %d %p status %d\n", (int)transfer->length, transfer->buffer, (int)transfer->status);
241 int tlen
= 0, olen
= 0;
242 for (int i
= 0; i
< transfer
->num_iso_packets
; i
++)
244 tlen
+= transfer
->iso_packet_desc
[i
].actual_length
;
245 olen
+= transfer
->iso_packet_desc
[i
].length
;
246 if (transfer
->iso_packet_desc
[i
].status
)
247 printf("ISO error: index = %d i = %d status = %d\n", (int)transfer
->user_data
, i
, transfer
->iso_packet_desc
[i
].status
);
249 uii
->samples_played
+= olen
/ (oc
* resolution
);
250 int nsamps
= uii
->sample_rate
/ 1000;
251 // If time elapsed is greater than
252 int lag
= uii
->desync
/ (1000 * transfer
->num_iso_packets
);
253 if (lag
> 0 && nsamps
< uii
->audio_output_pktsize
)
259 transfer
->length
= nsamps
* transfer
->num_iso_packets
* oc
* resolution
;
260 libusb_set_iso_packet_lengths(transfer
, nsamps
* oc
* resolution
);
264 fill_playback_buffer(uii
, transfer
);
266 // desync value is expressed in milli-frames, i.e. desync of 1000 means 1 frame of lag
267 // It takes 1ms for each iso packet to be transmitted. Each transfer consists of
268 // num_iso_packets packets. So, this transfer took uii->sample_rate milli-frames.
269 uii
->desync
+= transfer
->num_iso_packets
* uii
->sample_rate
;
270 // ... but during that time, tlen/4 samples == tlen/4*1000 millisamples have been
272 uii
->desync
-= transfer
->num_iso_packets
* nsamps
* 1000;
274 if (uii
->no_resubmit
)
276 int err
= usbio_transfer_submit(xf
);
279 if (err
== LIBUSB_ERROR_NO_DEVICE
)
281 uii
->device_removed
++;
282 transfer
->status
= LIBUSB_TRANSFER_NO_DEVICE
;
284 g_warning("Cannot resubmit isochronous transfer, error = %s", libusb_error_name(err
));
288 void usbio_play_buffer_adaptive(struct cbox_usb_io_impl
*uii
)
290 struct usbio_transfer
*t
;
292 int packets
= uii
->iso_packets
;
293 t
= usbio_transfer_new(uii
->usbctx
, "play", uii
->playback_counter
, packets
, uii
);
294 int tsize
= uii
->sample_rate
* 2 * uii
->output_resolution
/ 1000;
295 uint8_t *buf
= (uint8_t *)calloc(1, uii
->audio_output_pktsize
);
297 libusb_fill_iso_transfer(t
->transfer
, uii
->handle_audiodev
, uii
->audio_output_endpoint
, buf
, tsize
* packets
, packets
, play_callback_adaptive
, t
, 20000);
298 libusb_set_iso_packet_lengths(t
->transfer
, tsize
);
299 uii
->playback_transfers
[uii
->playback_counter
++] = t
;
301 err
= usbio_transfer_submit(t
);
304 g_warning("Cannot resubmit isochronous transfer, error = %s", libusb_error_name(err
));
305 uii
->playback_counter
--;
307 usbio_transfer_destroy(t
);
308 uii
->playback_transfers
[uii
->playback_counter
] = NULL
;
311 //////////////////////////////////////////////////////////////////////////////////////////
313 static int calc_packet_lengths(struct cbox_usb_io_impl
*uii
, struct libusb_transfer
*t
, int packets
)
317 // printf("sync_freq = %d\n", sync_freq);
318 for (i
= 0; i
< packets
; i
++)
320 int nsamps
= (uii
->sync_freq
- uii
->desync
) / 80;
321 // assert(nsamps > 0);
322 if ((uii
->sync_freq
- uii
->desync
) % 80)
324 //printf("%d sfreq=%d desync=%d nsamps=%d\n", i, uii->sync_freq, uii->desync, nsamps);
326 uii
->desync
= (uii
->desync
+ nsamps
* 80) % uii
->sync_freq
;
327 int v
= (nsamps
) * 2 * uii
->output_resolution
;
328 t
->iso_packet_desc
[i
].length
= v
;
334 void play_callback_asynchronous(struct libusb_transfer
*transfer
)
337 struct usbio_transfer
*xf
= transfer
->user_data
;
338 struct cbox_usb_io_impl
*uii
= xf
->user_data
;
341 if (transfer
->status
== LIBUSB_TRANSFER_CANCELLED
)
343 xf
->cancel_confirm
= TRUE
;
346 if (transfer
->status
== LIBUSB_TRANSFER_NO_DEVICE
)
348 xf
->cancel_confirm
= TRUE
;
349 uii
->device_removed
++;
353 gboolean init_finished
= uii
->playback_counter
== uii
->playback_buffers
;
354 if (uii
->playback_counter
< uii
->playback_buffers
)
356 // send another URB for the next transfer before re-submitting
358 usbio_play_buffer_asynchronous(uii
);
362 printf("Play Callback! %d status %d\n", (int)transfer->length, (int)transfer->status);
363 for (i = 0; i < transfer->num_iso_packets; i++) {
364 if (transfer->iso_packet_desc[i].actual_length)
366 printf("%d: %d %d\n", i, transfer->iso_packet_desc[i].actual_length, transfer->iso_packet_desc[i].status);
370 transfer
->length
= calc_packet_lengths(uii
, transfer
, transfer
->num_iso_packets
);
373 fill_playback_buffer(uii
, transfer
);
375 if (uii
->no_resubmit
)
377 int err
= usbio_transfer_submit(xf
);
380 if (err
== LIBUSB_ERROR_NO_DEVICE
)
382 transfer
->status
= LIBUSB_TRANSFER_NO_DEVICE
;
383 uii
->device_removed
++;
385 g_warning("Cannot submit isochronous transfer, error = %s", libusb_error_name(err
));
389 static struct usbio_transfer
*sync_stuff_asynchronous(struct cbox_usb_io_impl
*uii
, int index
);
391 void usbio_play_buffer_asynchronous(struct cbox_usb_io_impl
*uii
)
393 struct usbio_transfer
*t
;
395 int packets
= uii
->iso_packets_multimix
;
396 t
= usbio_transfer_new(uii
->usbctx
, "play", uii
->playback_counter
, packets
, uii
);
397 int tsize
= calc_packet_lengths(uii
, t
->transfer
, packets
);
398 int bufsize
= uii
->audio_output_pktsize
* packets
;
399 uint8_t *buf
= (uint8_t *)calloc(1, bufsize
);
401 if (!uii
->playback_counter
)
403 for(uii
->sync_counter
= 0; uii
->sync_counter
< uii
->sync_buffers
; uii
->sync_counter
++)
404 uii
->sync_transfers
[uii
->sync_counter
] = sync_stuff_asynchronous(uii
, uii
->sync_counter
);
407 libusb_fill_iso_transfer(t
->transfer
, uii
->handle_audiodev
, uii
->audio_output_endpoint
, buf
, tsize
, packets
, play_callback_asynchronous
, t
, 20000);
408 uii
->playback_transfers
[uii
->playback_counter
++] = t
;
409 err
= usbio_transfer_submit(t
);
412 g_warning("Cannot submit playback urb: %s, error = %s (index = %d, tsize = %d)", libusb_error_name(err
), strerror(errno
), uii
->playback_counter
, tsize
);
414 usbio_transfer_destroy(t
);
415 uii
->playback_transfers
[--uii
->playback_counter
] = NULL
;
419 //////////////////////////////////////////////////////////////////////////////////////////
422 * The Multimix device controls the data rate of the playback stream using a
423 * device-to-host isochronous endpoint. The incoming packets consist of 3 bytes:
424 * a current value of sample rate (kHz) + 2 historical values. I'm only using
425 * the first byte, I haven't yet encountered a situation where using the
426 * second and third byte would be necessary. This seems to work for all
427 * sample rates supported by the Windows driver - 44100, 48000, 88200 and
428 * 96000. It is possible to set sample rate to 64000, but it doesn't work
429 * correctly, and isn't supported by the Windows driver either - it may
430 * require special handling or may be a half-implemented feature in hardware.
431 * The isochronous transfer using 10 packets seems to give acceptable resolution
432 * and latency to avoid over/underruns with supported sample rates.
434 * The non-integer multiples of 1 kHz (like 44.1) are passed as a sequence of
435 * values that average to a desired value (9 values of 44 and one value of 45).
437 * In order to compensate for clock rate difference
438 * between host clock and DAC clock, the sample rate values sent by the device
439 * are either larger (to increase data rate from the host) or smaller than
440 * the nominal frequency value - the driver uses that to adjust the sample frame
441 * counts of individual packets in an isochronous transfer.
444 static void sync_callback(struct libusb_transfer
*transfer
)
446 struct usbio_transfer
*xf
= transfer
->user_data
;
447 struct cbox_usb_io_impl
*uii
= xf
->user_data
;
448 uint8_t *data
= transfer
->buffer
;
449 int i
, j
, ofs
, size
, pkts
;
452 if (transfer
->status
== LIBUSB_TRANSFER_CANCELLED
)
454 xf
->cancel_confirm
= 1;
457 if (transfer
->status
== LIBUSB_TRANSFER_NO_DEVICE
)
459 xf
->cancel_confirm
= 1;
462 // XXXKF handle device disconnected error
465 printf("Sync callback! %p %d packets:", transfer
, transfer
->num_iso_packets
);
469 for (i
= 0; i
< transfer
->num_iso_packets
; i
++) {
470 if (transfer
->iso_packet_desc
[i
].status
)
472 printf("[%02d: actual length is %4d, status is %2d] ", i
, transfer
->iso_packet_desc
[i
].actual_length
, transfer
->iso_packet_desc
[i
].status
);
475 else if (transfer
->iso_packet_desc
[i
].actual_length
)
477 assert(transfer
->iso_packet_desc
[i
].actual_length
== 3);
479 if (i
&& transfer
->iso_packet_desc
[i
- 1].actual_length
)
480 assert(data
[ofs
+ 1] == data
[ofs
- 64]);
481 //printf("%d\n", (int)data[ofs]);
483 printf("%3d ", (int)data
[ofs
]);
489 ofs
+= transfer
->iso_packet_desc
[i
].length
;
492 printf(" (%d of %d)", pkts
, transfer
->num_iso_packets
);
493 if (pkts
== transfer
->num_iso_packets
)
496 uii
->sync_freq
= size
* 10 / pkts
;
498 printf(" size = %4d sync_freq = %4d", size
, uii
->sync_freq
);
500 if (uii
->no_resubmit
)
502 int err
= usbio_transfer_submit(xf
);
505 if (err
== LIBUSB_ERROR_NO_DEVICE
)
514 struct usbio_transfer
*sync_stuff_asynchronous(struct cbox_usb_io_impl
*uii
, int index
)
516 struct usbio_transfer
*t
;
518 int syncbufsize
= 64;
519 int syncbufcount
= NUM_SYNC_PACKETS
;
520 t
= usbio_transfer_new(uii
->usbctx
, "sync", index
, syncbufcount
, uii
);
521 uint8_t *sync_buf
= (uint8_t *)calloc(syncbufcount
, syncbufsize
);
522 libusb_fill_iso_transfer(t
->transfer
, uii
->handle_audiodev
, uii
->audio_sync_endpoint
, sync_buf
, syncbufsize
* syncbufcount
, syncbufcount
, sync_callback
, t
, 20000);
523 libusb_set_iso_packet_lengths(t
->transfer
, syncbufsize
);
525 err
= libusb_submit_transfer(t
->transfer
);
528 g_warning("Cannot submit sync urb: %s", libusb_error_name(err
));
530 usbio_transfer_destroy(t
);
536 ///////////////////////////////////////////////////////////////////////////
538 void cbox_usb_audio_info_init(struct cbox_usb_audio_info
*uai
, struct cbox_usb_device_info
*udi
)
542 uai
->alt_setting
= -1;
543 uai
->epdesc
.found
= FALSE
;
546 void usbio_start_audio_playback(struct cbox_usb_io_impl
*uii
)
549 uii
->samples_played
= 0;
550 uii
->read_ptr
= uii
->ioi
.pio
->buffer_size
;
552 uii
->playback_transfers
= malloc(sizeof(struct libusb_transfer
*) * uii
->playback_buffers
);
553 uii
->sync_transfers
= malloc(sizeof(struct libusb_transfer
*) * uii
->sync_buffers
);
555 uii
->playback_counter
= 0;
556 uii
->device_removed
= 0;
557 uii
->sync_freq
= uii
->sample_rate
/ 100;
558 uii
->play_function(uii
);
559 uii
->setup_error
= uii
->playback_counter
== 0;
561 if (!uii
->setup_error
)
563 while(uii
->playback_counter
< uii
->playback_buffers
&& !uii
->device_removed
)
564 libusb_handle_events(uii
->usbctx
);
568 void usbio_stop_audio_playback(struct cbox_usb_io_impl
*uii
)
570 if (uii
->device_removed
)
572 // Wait until all the transfers pending are finished
573 while(uii
->device_removed
< uii
->playback_counter
)
574 libusb_handle_events(uii
->usbctx
);
576 if (uii
->device_removed
|| uii
->setup_error
)
578 // Run the DSP code and send output to bit bucket until engine is stopped.
579 // This ensures that the command queue will still be processed.
580 // Otherwise the GUI thread would hang waiting for the command from
581 // the queue to be completed.
582 g_message("USB Audio output device has been disconnected - switching to null output.");
583 usbio_run_idle_loop(uii
);
587 // Cancel all transfers pending, and wait until they get cancelled
588 for (int i
= 0; i
< uii
->playback_counter
; i
++)
590 if (uii
->playback_transfers
[i
])
591 usbio_transfer_shutdown(uii
->playback_transfers
[i
]);
595 // Free the transfers for the buffers allocated so far. In case of setup
596 // failure, some buffers transfers might not have been created yet.
597 for (int i
= 0; i
< uii
->playback_counter
; i
++)
599 if (uii
->playback_transfers
[i
])
601 free(uii
->playback_transfers
[i
]->transfer
->buffer
);
602 usbio_transfer_destroy(uii
->playback_transfers
[i
]);
603 uii
->playback_transfers
[i
] = NULL
;
606 if (uii
->playback_counter
&& uii
->audio_sync_endpoint
)
608 for (int i
= 0; i
< uii
->sync_counter
; i
++)
610 if (uii
->sync_transfers
[i
])
611 usbio_transfer_shutdown(uii
->sync_transfers
[i
]);
613 for (int i
= 0; i
< uii
->sync_counter
; i
++)
615 if (uii
->sync_transfers
[i
])
617 free(uii
->sync_transfers
[i
]->transfer
->buffer
);
618 usbio_transfer_destroy(uii
->sync_transfers
[i
]);
619 uii
->sync_transfers
[i
] = NULL
;
623 free(uii
->playback_transfers
);
624 free(uii
->sync_transfers
);