Merge pull request #1 from atsampson/master
[calfbox.git] / usbaudio.c
blobb78476ac0e0a0d7af2d733ae22989a2d88960dc7
1 /*
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/>.
19 #include <pthread.h>
20 #include <time.h>
21 #include "usbio_impl.h"
23 #include <assert.h>
24 #include <errno.h>
25 #include <stdio.h>
27 #define NUM_MULTIMIX_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)
45 uint8_t freq_data[3];
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)
50 return FALSE;
51 return TRUE;
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.");
61 return FALSE;
63 if (!configure_usb_interface(handle, uainf->udi->bus, uainf->udi->devadr, uainf->intf, uainf->alt_setting, "audio (class driver)", error))
64 return FALSE;
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.");
68 return FALSE;
70 uii->is_hispeed = FALSE;
71 uii->sync_protocol = uainf->sync_protocol;
72 uii->play_function = uainf->sync_protocol == USBAUDIOSYNC_PROTOCOL_CLASS ? usbio_play_buffer_asynchronous : usbio_play_buffer_adaptive;
73 uii->handle_audiodev = handle;
74 uii->audio_output_endpoint = uainf->epdesc.bEndpointAddress;
75 uii->audio_output_pktsize = uainf->epdesc.wMaxPacketSize; // 48 * 2 * uii->output_resolution;
76 uii->audio_sync_endpoint = uainf->sync_protocol == USBAUDIOSYNC_PROTOCOL_CLASS ? uainf->sync_epdesc.bEndpointAddress : 0;
77 return TRUE;
80 ///////////////////////////////////////////////////////////////////////////////
82 static gboolean claim_multimix_interfaces(struct cbox_usb_io_impl *uii, struct libusb_device_handle *handle, int bus, int devadr, GError **error)
84 for (int ifno = 0; ifno < 2; ifno++)
86 if (!configure_usb_interface(handle, bus, devadr, ifno, 1, "audio (MultiMix driver)", error))
87 return FALSE;
89 return TRUE;
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.");
97 return FALSE;
99 if (!claim_multimix_interfaces(uii, handle, bus, devadr, error))
100 return FALSE;
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.");
104 return FALSE;
107 uii->is_hispeed = TRUE;
108 uii->play_function = usbio_play_buffer_asynchronous;
109 uii->handle_audiodev = handle;
110 uii->sync_protocol = USBAUDIOSYNC_PROTOCOL_MULTIMIX8;
111 uii->audio_output_endpoint = MULTIMIX_EP_PLAYBACK;
112 uii->audio_output_pktsize = 156;
113 uii->audio_sync_endpoint = MULTIMIX_EP_SYNC;
114 return TRUE;
117 ///////////////////////////////////////////////////////////////////////////////
119 static void calc_output_buffer(struct cbox_usb_io_impl *uii)
121 struct timespec tvs1, tve1, tvs2, tve2;
122 if (register_cpu_time)
124 clock_gettime(CLOCK_MONOTONIC_RAW, &tvs1);
125 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tvs2);
127 struct cbox_io *io = uii->ioi.pio;
128 uint32_t buffer_size = io->io_env.buffer_size;
129 for (int b = 0; b < uii->output_channels; b++)
130 memset(io->output_buffers[b], 0, buffer_size * sizeof(float));
131 for (GList *p = uii->rt_midi_ports; p; p = p->next)
133 struct cbox_usb_midi_interface *umi = p->data;
134 if (umi->input_port->hdr.enable_appsink && umi->input_port && umi->input_port->hdr.buffer.count)
135 cbox_midi_appsink_supply(&umi->input_port->hdr.appsink, &umi->input_port->hdr.buffer);
137 io->cb->process(io->cb->user_data, io, buffer_size);
138 for (GList *p = uii->rt_midi_ports; p; p = p->next)
140 struct cbox_usb_midi_interface *umi = p->data;
141 if (umi->input_port)
142 cbox_midi_buffer_clear(&umi->input_port->hdr.buffer);
144 for (GSList *p = io->midi_outputs; p; p = p->next)
146 struct cbox_usb_midi_output *umo = p->data;
147 usbio_fill_midi_output_buffer(umo);
149 if (register_cpu_time)
151 clock_gettime(CLOCK_MONOTONIC_RAW, &tve1);
152 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tve2);
153 float time1 = tve1.tv_sec - tvs1.tv_sec + (tve1.tv_nsec - tvs1.tv_nsec) / 1000000000.0;
154 float time2 = tve2.tv_sec - tvs2.tv_sec + (tve2.tv_nsec - tvs2.tv_nsec) / 1000000000.0;
155 real_time_registry[cpu_time_write_ptr] = time1;
156 cpu_time_registry[cpu_time_write_ptr] = time2;
157 cpu_time_write_ptr = (cpu_time_write_ptr + 1) % NUM_CPUTIME_ENTRIES;
158 if (time1 > 0.0008 || time2 > 0.0008)
159 g_warning("CPU time = %f ms, real time = %f ms", time2 * 1000, time1 * 1000);
163 static void fill_playback_buffer(struct cbox_usb_io_impl *uii, struct libusb_transfer *transfer)
165 struct cbox_io *io = uii->ioi.pio;
166 uint32_t buffer_size = io->io_env.buffer_size;
167 uint8_t *data8 = (uint8_t*)transfer->buffer;
168 int16_t *data = (int16_t*)transfer->buffer;
169 int resolution = uii->output_resolution;
170 int oc = uii->output_channels;
171 int rptr = uii->read_ptr;
172 int nframes = transfer->length / (resolution * oc);
173 int i, j, b;
175 for (i = 0; i < nframes; )
177 if (rptr == buffer_size)
179 calc_output_buffer(uii);
180 rptr = 0;
182 int left1 = nframes - i;
183 int left2 = buffer_size - rptr;
184 if (left1 > left2)
185 left1 = left2;
187 for (b = 0; b < oc; b++)
189 float *obuf = io->output_buffers[b] + rptr;
190 if (resolution == 2)
192 int16_t *tbuf = data + oc * i + b;
193 for (j = 0; j < left1; j++)
195 float v = 32767 * obuf[j];
196 if (v < -32768)
197 v = -32768;
198 if (v > +32767)
199 v = +32767;
200 *tbuf = (int16_t)v;
201 tbuf += oc;
204 if (resolution == 3)
206 uint8_t *tbuf = data8 + (oc * i + b) * 3;
207 for (j = 0; j < left1; j++)
209 float v = 0x7FFFFF * obuf[j];
210 if (v < -0x800000)
211 v = -0x800000;
212 if (v > +0x7FFFFF)
213 v = +0x7FFFFF;
214 int vi = (int)v;
215 tbuf[0] = vi & 255;
216 tbuf[1] = (vi >> 8) & 255;
217 tbuf[2] = (vi >> 16) & 255;
218 tbuf += oc * 3;
222 i += left1;
223 rptr += left1;
225 uii->read_ptr = rptr;
228 static void play_callback_adaptive(struct libusb_transfer *transfer)
230 struct usbio_transfer *xf = transfer->user_data;
231 struct cbox_usb_io_impl *uii = xf->user_data;
232 xf->pending = FALSE;
233 if (transfer->status == LIBUSB_TRANSFER_CANCELLED)
235 xf->cancel_confirm = 1;
236 return;
238 if (transfer->status == LIBUSB_TRANSFER_NO_DEVICE)
240 uii->device_removed++;
241 return;
244 int resolution = uii->output_resolution;
245 int oc = uii->output_channels;
246 gboolean init_finished = uii->playback_counter == uii->playback_buffers;
247 if (uii->playback_counter < uii->playback_buffers)
249 // send another URB for the next transfer before re-submitting
250 // this one
251 usbio_play_buffer_adaptive(uii);
253 // printf("Play Callback! %d %p status %d\n", (int)transfer->length, transfer->buffer, (int)transfer->status);
255 int tlen = 0, olen = 0;
256 for (int i = 0; i < transfer->num_iso_packets; i++)
258 tlen += transfer->iso_packet_desc[i].actual_length;
259 olen += transfer->iso_packet_desc[i].length;
260 if (transfer->iso_packet_desc[i].status)
261 printf("ISO error: index = %d i = %d status = %d\n", (int)xf->index, i, transfer->iso_packet_desc[i].status);
263 uii->samples_played += olen / (oc * resolution);
264 int nsamps = uii->sample_rate / 1000;
265 // If time elapsed is greater than
266 int lag = uii->desync / (1000 * transfer->num_iso_packets);
267 if (lag > 0 && nsamps < uii->audio_output_pktsize)
269 nsamps++;
270 lag--;
273 transfer->length = nsamps * transfer->num_iso_packets * oc * resolution;
274 libusb_set_iso_packet_lengths(transfer, nsamps * oc * resolution);
276 if (init_finished)
278 fill_playback_buffer(uii, transfer);
280 // desync value is expressed in milli-frames, i.e. desync of 1000 means 1 frame of lag
281 // It takes 1ms for each iso packet to be transmitted. Each transfer consists of
282 // num_iso_packets packets. So, this transfer took uii->sample_rate milli-frames.
283 uii->desync += transfer->num_iso_packets * uii->sample_rate;
284 // ... but during that time, tlen/4 samples == tlen/4*1000 millisamples have been
285 // transmitted.
286 uii->desync -= transfer->num_iso_packets * nsamps * 1000;
288 if (uii->no_resubmit)
289 return;
290 int err = usbio_transfer_submit(xf);
291 if (err)
293 if (err == LIBUSB_ERROR_NO_DEVICE)
295 uii->device_removed++;
296 transfer->status = LIBUSB_TRANSFER_NO_DEVICE;
298 g_warning("Cannot resubmit isochronous transfer, error = %s", libusb_error_name(err));
302 void usbio_play_buffer_adaptive(struct cbox_usb_io_impl *uii)
304 struct usbio_transfer *t;
305 int err;
306 int packets = uii->iso_packets;
307 t = usbio_transfer_new(uii->usbctx, "play", uii->playback_counter, packets, uii);
308 int tsize = uii->sample_rate * 2 * uii->output_resolution / 1000;
309 uint8_t *buf = (uint8_t *)calloc(packets, uii->audio_output_pktsize);
311 libusb_fill_iso_transfer(t->transfer, uii->handle_audiodev, uii->audio_output_endpoint, buf, tsize * packets, packets, play_callback_adaptive, t, 20000);
312 libusb_set_iso_packet_lengths(t->transfer, tsize);
313 uii->playback_transfers[uii->playback_counter++] = t;
315 err = usbio_transfer_submit(t);
316 if (!err)
317 return;
318 g_warning("Cannot resubmit isochronous transfer, error = %s", libusb_error_name(err));
319 uii->playback_counter--;
320 free(buf);
321 usbio_transfer_destroy(t);
322 uii->playback_transfers[uii->playback_counter] = NULL;
325 //////////////////////////////////////////////////////////////////////////////////////////
327 static int calc_packet_lengths(struct cbox_usb_io_impl *uii, struct libusb_transfer *t, int packets)
329 int packets_per_sec = uii->is_hispeed ? 8000 : 1000;
330 int tsize = 0;
331 int i;
332 // printf("sync_freq = %d\n", sync_freq);
333 for (i = 0; i < packets; i++)
335 int nsamps = (uii->samples_per_sec - uii->desync) / packets_per_sec;
336 // assert(nsamps > 0);
337 if ((uii->samples_per_sec - uii->desync) % packets_per_sec)
338 nsamps++;
339 //printf("%d sfreq=%d desync=%d nsamps=%d\n", i, uii->sync_freq, uii->desync, nsamps);
341 uii->desync = (uii->desync + nsamps * packets_per_sec) % uii->samples_per_sec;
342 int v = (nsamps) * 2 * uii->output_resolution;
343 t->iso_packet_desc[i].length = v;
344 tsize += v;
346 return tsize;
349 void play_callback_asynchronous(struct libusb_transfer *transfer)
351 struct usbio_transfer *xf = transfer->user_data;
352 struct cbox_usb_io_impl *uii = xf->user_data;
353 xf->pending = FALSE;
355 if (transfer->status == LIBUSB_TRANSFER_CANCELLED)
357 xf->cancel_confirm = TRUE;
358 return;
360 if (transfer->status == LIBUSB_TRANSFER_NO_DEVICE)
362 xf->cancel_confirm = TRUE;
363 uii->device_removed++;
364 return;
367 gboolean init_finished = uii->playback_counter == uii->playback_buffers;
368 if (uii->playback_counter < uii->playback_buffers)
370 // send another URB for the next transfer before re-submitting
371 // this one
372 usbio_play_buffer_asynchronous(uii);
376 printf("Play Callback! %d status %d\n", (int)transfer->length, (int)transfer->status);
377 for (i = 0; i < transfer->num_iso_packets; i++) {
378 if (transfer->iso_packet_desc[i].actual_length)
380 printf("%d: %d %d\n", i, transfer->iso_packet_desc[i].actual_length, transfer->iso_packet_desc[i].status);
384 transfer->length = calc_packet_lengths(uii, transfer, transfer->num_iso_packets);
385 if (init_finished)
387 fill_playback_buffer(uii, transfer);
389 if (uii->no_resubmit)
390 return;
391 int err = usbio_transfer_submit(xf);
392 if (err)
394 if (err == LIBUSB_ERROR_NO_DEVICE)
396 transfer->status = LIBUSB_TRANSFER_NO_DEVICE;
397 uii->device_removed++;
399 g_warning("Cannot submit isochronous transfer, error = %s", libusb_error_name(err));
403 static struct usbio_transfer *sync_stuff_asynchronous(struct cbox_usb_io_impl *uii, int index);
405 void usbio_play_buffer_asynchronous(struct cbox_usb_io_impl *uii)
407 struct usbio_transfer *t;
408 int err;
409 int packets = uii->iso_packets_multimix;
410 t = usbio_transfer_new(uii->usbctx, "play", uii->playback_counter, packets, uii);
411 int tsize = calc_packet_lengths(uii, t->transfer, packets);
412 int bufsize = uii->audio_output_pktsize * packets;
413 uint8_t *buf = (uint8_t *)calloc(1, bufsize);
415 if (!uii->playback_counter)
417 for(uii->sync_counter = 0; uii->sync_counter < uii->sync_buffers; uii->sync_counter++)
418 uii->sync_transfers[uii->sync_counter] = sync_stuff_asynchronous(uii, uii->sync_counter);
421 libusb_fill_iso_transfer(t->transfer, uii->handle_audiodev, uii->audio_output_endpoint, buf, tsize, packets, play_callback_asynchronous, t, 20000);
422 uii->playback_transfers[uii->playback_counter++] = t;
423 err = usbio_transfer_submit(t);
424 if (err)
426 g_warning("Cannot submit playback urb: %s, error = %s (index = %d, tsize = %d)", libusb_error_name(err), strerror(errno), uii->playback_counter, tsize);
427 free(buf);
428 usbio_transfer_destroy(t);
429 uii->playback_transfers[--uii->playback_counter] = NULL;
433 //////////////////////////////////////////////////////////////////////////////////////////
436 * The Multimix device controls the data rate of the playback stream using a
437 * device-to-host isochronous endpoint. The incoming packets consist of 3 bytes:
438 * a current value of sample rate (kHz) + 2 historical values. I'm only using
439 * the first byte, I haven't yet encountered a situation where using the
440 * second and third byte would be necessary. This seems to work for all
441 * sample rates supported by the Windows driver - 44100, 48000, 88200 and
442 * 96000. It is possible to set sample rate to 64000, but it doesn't work
443 * correctly, and isn't supported by the Windows driver either - it may
444 * require special handling or may be a half-implemented feature in hardware.
445 * The isochronous transfer using 10 packets seems to give acceptable resolution
446 * and latency to avoid over/underruns with supported sample rates.
448 * The non-integer multiples of 1 kHz (like 44.1) are passed as a sequence of
449 * values that average to a desired value (9 values of 44 and one value of 45).
451 * In order to compensate for clock rate difference
452 * between host clock and DAC clock, the sample rate values sent by the device
453 * are either larger (to increase data rate from the host) or smaller than
454 * the nominal frequency value - the driver uses that to adjust the sample frame
455 * counts of individual packets in an isochronous transfer.
457 * A similar mechanism is used with USB audio class asynchronous sinks: the
458 * device sends a 10.14 representation of number of audio samples (frames)
459 * per USB frame, and this is used to control packet sizes.
462 static void use_audioclass_sync_feedback(const uint8_t *data, uint32_t actual_length, int *prate)
464 // 10.14 representation of 'samples' per ms value, see 5.12.4.2 of the USB spec
465 uint32_t value = data[0] + 256 * data[1] + 65536 * data[2];
466 // printf("Ff estimate = %f Hz\n", value * 1000 / 16384.0);
467 // only 1 packet
468 *prate = (1000 * value + 8192) >> 14;
471 static inline void use_multimix_sync_feedback(const uint8_t *data, uint32_t actual_length, int *prate, const uint8_t *prev_data)
473 // Those assertions never failed, so my understanding of the protocol was likely
474 // correct. They should probably be removed just to not crash the program when
475 // used with flaky devices.
476 assert(actual_length == 3);
477 // this is averaged across all packets in the transfer
478 *prate += 1000 * data[0];
479 if (prev_data)
480 assert(data[1] == prev_data[0]);
483 static void sync_callback(struct libusb_transfer *transfer)
485 struct usbio_transfer *xf = transfer->user_data;
486 struct cbox_usb_io_impl *uii = xf->user_data;
487 uint8_t *data = transfer->buffer;
488 int i, ofs, pkts;
489 int rate_est = 0;
490 xf->pending = FALSE;
492 if (transfer->status == LIBUSB_TRANSFER_CANCELLED)
494 xf->cancel_confirm = 1;
495 return;
497 if (transfer->status == LIBUSB_TRANSFER_NO_DEVICE)
499 xf->cancel_confirm = 1;
500 return;
502 // XXXKF handle device disconnected error
504 if (uii->debug_sync)
505 printf("Sync callback! %p %d packets:", transfer, transfer->num_iso_packets);
506 ofs = 0;
507 pkts = 0;
508 rate_est = 0;
509 const uint8_t *prev_data = NULL;
510 for (i = 0; i < transfer->num_iso_packets; i++) {
511 if (transfer->iso_packet_desc[i].status)
513 printf("[%02d: actual length is %4d, status is %2d] ", i, transfer->iso_packet_desc[i].actual_length, transfer->iso_packet_desc[i].status);
514 continue;
516 else if (transfer->iso_packet_desc[i].actual_length)
518 if (uii->sync_protocol == USBAUDIOSYNC_PROTOCOL_MULTIMIX8)
519 use_multimix_sync_feedback(&data[ofs], transfer->iso_packet_desc[i].actual_length, &rate_est, prev_data);
520 else
521 use_audioclass_sync_feedback(&data[ofs], transfer->iso_packet_desc[i].actual_length, &rate_est);
522 prev_data = &data[ofs];
523 //printf("%d\n", (int)data[ofs]);
524 if (uii->debug_sync)
525 printf("%3d ", (int)data[ofs]);
526 pkts++;
528 else
529 if (uii->debug_sync)
530 printf("? ");
531 ofs += transfer->iso_packet_desc[i].length;
533 if (uii->debug_sync)
534 printf(" (%d of %d)", pkts, transfer->num_iso_packets);
535 if (pkts == transfer->num_iso_packets)
537 // Divide by the number of packets to compute the mean rate (in case
538 // of Multimix we don't have a proper fractional value, just an integer,
539 // so averaging is required to get more accuracy).
540 if (rate_est)
541 uii->samples_per_sec = rate_est / pkts;
542 if (uii->debug_sync)
543 printf("rate_est = %d sync_freq = %d\n", rate_est, uii->samples_per_sec);
545 if (uii->no_resubmit)
546 return;
547 int err = usbio_transfer_submit(xf);
548 if (err)
550 if (err == LIBUSB_ERROR_NO_DEVICE)
552 return;
555 if (uii->debug_sync)
556 printf("\n");
559 struct usbio_transfer *sync_stuff_asynchronous(struct cbox_usb_io_impl *uii, int index)
561 struct usbio_transfer *t;
562 int err;
563 int syncbufsize = uii->sync_protocol == USBAUDIOSYNC_PROTOCOL_MULTIMIX8 ? 64 : 3;
564 int syncbufcount = uii->sync_protocol == USBAUDIOSYNC_PROTOCOL_MULTIMIX8 ? NUM_MULTIMIX_SYNC_PACKETS : 1;
565 t = usbio_transfer_new(uii->usbctx, "sync", index, syncbufcount, uii);
566 uint8_t *sync_buf = (uint8_t *)calloc(syncbufcount, syncbufsize);
567 libusb_fill_iso_transfer(t->transfer, uii->handle_audiodev, uii->audio_sync_endpoint, sync_buf, syncbufsize * syncbufcount, syncbufcount, sync_callback, t, 20000);
568 libusb_set_iso_packet_lengths(t->transfer, syncbufsize);
570 err = libusb_submit_transfer(t->transfer);
571 if (err)
573 g_warning("Cannot submit sync urb: %s", libusb_error_name(err));
574 free(sync_buf);
575 usbio_transfer_destroy(t);
576 return NULL;
578 return t;
581 ///////////////////////////////////////////////////////////////////////////
583 void cbox_usb_audio_info_init(struct cbox_usb_audio_info *uai, struct cbox_usb_device_info *udi)
585 uai->udi = udi;
586 uai->intf = -1;
587 uai->alt_setting = -1;
588 uai->epdesc.found = FALSE;
589 uai->sync_protocol = USBAUDIOSYNC_PROTOCOL_NONE;
590 uai->sync_epdesc.found = FALSE;
593 void usbio_start_audio_playback(struct cbox_usb_io_impl *uii)
595 uii->desync = 0;
596 uii->samples_played = 0;
597 uii->read_ptr = uii->ioi.pio->io_env.buffer_size;
599 uii->playback_transfers = malloc(sizeof(struct libusb_transfer *) * uii->playback_buffers);
600 uii->sync_transfers = malloc(sizeof(struct libusb_transfer *) * uii->sync_buffers);
602 uii->playback_counter = 0;
603 uii->device_removed = 0;
604 uii->samples_per_sec = uii->sample_rate;
605 uii->play_function(uii);
606 uii->setup_error = uii->playback_counter == 0;
608 if (!uii->setup_error)
610 while(uii->playback_counter < uii->playback_buffers && !uii->device_removed)
611 libusb_handle_events(uii->usbctx);
615 void usbio_stop_audio_playback(struct cbox_usb_io_impl *uii)
617 if (uii->device_removed)
619 // Wait until all the transfers pending are finished
620 while(uii->device_removed < uii->playback_counter)
621 libusb_handle_events(uii->usbctx);
623 if (uii->device_removed || uii->setup_error)
625 // Run the DSP code and send output to bit bucket until engine is stopped.
626 // This ensures that the command queue will still be processed.
627 // Otherwise the GUI thread would hang waiting for the command from
628 // the queue to be completed.
629 g_message("USB Audio output device has been disconnected - switching to null output.");
630 usbio_run_idle_loop(uii);
632 else
634 // Cancel all transfers pending, and wait until they get cancelled
635 for (int i = 0; i < uii->playback_counter; i++)
637 if (uii->playback_transfers[i])
638 usbio_transfer_shutdown(uii->playback_transfers[i]);
642 // Free the transfers for the buffers allocated so far. In case of setup
643 // failure, some buffers transfers might not have been created yet.
644 for (int i = 0; i < uii->playback_counter; i++)
646 if (uii->playback_transfers[i])
648 free(uii->playback_transfers[i]->transfer->buffer);
649 usbio_transfer_destroy(uii->playback_transfers[i]);
650 uii->playback_transfers[i] = NULL;
653 if (uii->playback_counter && uii->audio_sync_endpoint)
655 for (int i = 0; i < uii->sync_counter; i++)
657 if (uii->sync_transfers[i])
658 usbio_transfer_shutdown(uii->sync_transfers[i]);
660 for (int i = 0; i < uii->sync_counter; i++)
662 if (uii->sync_transfers[i])
664 free(uii->sync_transfers[i]->transfer->buffer);
665 usbio_transfer_destroy(uii->sync_transfers[i]);
666 uii->sync_transfers[i] = NULL;
670 free(uii->playback_transfers);
671 free(uii->sync_transfers);