From b0d5519c67df5378a32c56042245d1f2b045598e Mon Sep 17 00:00:00 2001 From: Sebastian Zagrodzki Date: Mon, 10 Apr 2017 02:45:16 +0200 Subject: [PATCH] Change the iso packet size if the buffer is very small. Previously number of iso packets could have amounted to a transfer buffer larger than passed buffer, which could lead to overflow. Now the number of bytes requested from device is always smaller or equal to the buffer size. In theory, it could lead to inefficiencies in transfer: if max packet size is 1024 and user request 2046 bytes of data, transfer will return at most 1024 bytes, while it could use a more efficient 2 packets of 1023 bytes. But at least it's correct now. It seems that for efficiency the user would always use the reported max packet size anyway. The device could still send more data than requested, but libusb takes care of it. --- usb/transfer.go | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/usb/transfer.go b/usb/transfer.go index aabc636..6307ebb 100644 --- a/usb/transfer.go +++ b/usb/transfer.go @@ -114,11 +114,14 @@ func (t *usbTransfer) free() error { // given device/endpoint, with buf as the underlying transfer buffer. func newUSBTransfer(dev *libusbDevHandle, ei *EndpointInfo, buf []byte, timeout time.Duration) (*usbTransfer, error) { var isoPackets int + var isoPktSize uint32 if ei.TransferType == TransferTypeIsochronous { - isoPackets = len(buf) / int(ei.MaxPacketSize) - if int(ei.MaxPacketSize)*isoPackets < len(buf) { - isoPackets++ + isoPktSize = ei.MaxPacketSize + if len(buf) < int(isoPktSize) { + isoPktSize = uint32(len(buf)) } + isoPackets = len(buf) / int(isoPktSize) + debug.Printf("New isochronous transfer - buffer length %d, using %d packets of %d bytes each", len(buf), isoPackets, isoPktSize) } xfer, err := libusb.alloc(dev, ei, timeout, isoPackets, buf) @@ -127,7 +130,7 @@ func newUSBTransfer(dev *libusbDevHandle, ei *EndpointInfo, buf []byte, timeout } if ei.TransferType == TransferTypeIsochronous { - libusb.setIsoPacketLengths(xfer, ei.MaxPacketSize) + libusb.setIsoPacketLengths(xfer, isoPktSize) } t := &usbTransfer{