1.0/examples/stream_test: Fix memory leakage pathes
[libftdi] / src / ftdi_stream.c
CommitLineData
40da63b1
UB
1/***************************************************************************
2 ftdi_stream.c - description
3 -------------------
4 copyright : (C) 2009 Micah Dowty 2010 Uwe Bonnes
5 email : opensource@intra2net.com
6 ***************************************************************************/
7
8/***************************************************************************
9 * *
10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU Lesser General Public License *
12 * version 2.1 as published by the Free Software Foundation; *
13 * *
14 ***************************************************************************/
15
16/* Adapted from
17 * fastftdi.c - A minimal FTDI FT232H interface for which supports bit-bang
18 * mode, but focuses on very high-performance support for
19 * synchronous FIFO mode. Requires libusb-1.0
20 *
21 * Copyright (C) 2009 Micah Dowty
22 *
23 * Permission is hereby granted, free of charge, to any person obtaining a copy
24 * of this software and associated documentation files (the "Software"), to deal
25 * in the Software without restriction, including without limitation the rights
26 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
27 * copies of the Software, and to permit persons to whom the Software is
28 * furnished to do so, subject to the following conditions:
29 *
30 * The above copyright notice and this permission notice shall be included in
31 * all copies or substantial portions of the Software.
32 *
33 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
34 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
35 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
36 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
37 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
38 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
39 * THE SOFTWARE.
40 */
41
42#include <stdlib.h>
43#include <stdio.h>
44
45#include "ftdi.h"
46
47typedef struct
48{
49 FTDIStreamCallback *callback;
50 void *userdata;
51 int packetsize;
705f012d 52 int activity;
40da63b1
UB
53 int result;
54 FTDIProgressInfo progress;
55} FTDIStreamState;
56
705f012d
UB
57/* Handle callbacks
58 *
59 * With Exit request, free memory and release the transfer
60 *
61 * state->result is only set when some error happens
62 */
40da63b1
UB
63static void
64ftdi_readstream_cb(struct libusb_transfer *transfer)
65{
66 FTDIStreamState *state = transfer->user_data;
67 int packet_size = state->packetsize;
68
705f012d
UB
69 state->activity++;
70 if (transfer->status == LIBUSB_TRANSFER_COMPLETED)
40da63b1 71 {
705f012d
UB
72 int i;
73 uint8_t *ptr = transfer->buffer;
74 int length = transfer->actual_length;
75 int numPackets = (length + packet_size - 1) / packet_size;
76 int res;
40da63b1 77
705f012d
UB
78 for (i = 0; i < numPackets; i++)
79 {
80 int payloadLen;
81 int packetLen = length;
82
83 if (packetLen > packet_size)
84 packetLen = packet_size;
85
86 payloadLen = packetLen - 2;
87 state->progress.current.totalBytes += payloadLen;
88
89 res = state->callback(ptr + 2, payloadLen,
90 NULL, state->userdata);
91
92 ptr += packetLen;
93 length -= packetLen;
94 }
95 if (res)
96 {
97 free(transfer->buffer);
98 libusb_free_transfer(transfer);
40da63b1
UB
99 }
100 else
101 {
705f012d
UB
102 transfer->status = -1;
103 state->result = libusb_submit_transfer(transfer);
40da63b1
UB
104 }
105 }
106 else
40da63b1 107 {
705f012d
UB
108 fprintf(stderr, "unknown status %d\n",transfer->status);
109 state->result = LIBUSB_ERROR_IO;
40da63b1
UB
110 }
111}
112
113/**
114 Helper function to calculate (unix) time differences
115
116 \param a timeval
117 \param b timeval
118*/
119static double
120TimevalDiff(const struct timeval *a, const struct timeval *b)
121{
122 return (a->tv_sec - b->tv_sec) + 1e-6 * (a->tv_usec - b->tv_usec);
123}
124
125/**
126 Streaming reading of data from the device
705f012d 127
40da63b1
UB
128 Use asynchronous transfers in libusb-1.0 for high-performance
129 streaming of data from a device interface back to the PC. This
130 function continuously transfers data until either an error occurs
131 or the callback returns a nonzero value. This function returns
132 a libusb error code or the callback's return value.
133
134 For every contiguous block of received data, the callback will
135 be invoked.
136
137 \param ftdi pointer to ftdi_context
138 \param callback to user supplied function for one block of data
139 \param userdata
140 \param packetsPerTransfer number of packets per transfer
141 \param numTransfers Number of transfers per callback
142
143*/
144
145int
146ftdi_readstream(struct ftdi_context *ftdi,
147 FTDIStreamCallback *callback, void *userdata,
148 int packetsPerTransfer, int numTransfers)
149{
150 struct libusb_transfer **transfers;
705f012d 151 FTDIStreamState state = { callback, userdata, ftdi->max_packet_size, 1 };
40da63b1
UB
152 int bufferSize = packetsPerTransfer * ftdi->max_packet_size;
153 int xferIndex;
154 int err = 0;
705f012d 155
a3886df3
UB
156 /* We don't know in what state we are, switch to reset*/
157 if (ftdi_set_bitmode(ftdi, 0xff, BITMODE_RESET) < 0)
158 {
159 fprintf(stderr,"Can't reset mode\n");
160 return 1;
161 }
162
163 /* Purge anything remaining in the buffers*/
164 if (ftdi_usb_purge_buffers(ftdi) < 0)
165 {
166 fprintf(stderr,"Can't Purge\n");
167 return 1;
168 }
169
40da63b1
UB
170 /*
171 * Set up all transfers
172 */
705f012d 173
40da63b1
UB
174 transfers = calloc(numTransfers, sizeof *transfers);
175 if (!transfers) {
176 err = LIBUSB_ERROR_NO_MEM;
177 goto cleanup;
178 }
705f012d 179
40da63b1
UB
180 for (xferIndex = 0; xferIndex < numTransfers; xferIndex++)
181 {
182 struct libusb_transfer *transfer;
705f012d 183
40da63b1
UB
184 transfer = libusb_alloc_transfer(0);
185 transfers[xferIndex] = transfer;
186 if (!transfer) {
187 err = LIBUSB_ERROR_NO_MEM;
188 goto cleanup;
189 }
705f012d 190
40da63b1
UB
191 libusb_fill_bulk_transfer(transfer, ftdi->usb_dev, ftdi->out_ep,
192 malloc(bufferSize), bufferSize,
193 ftdi_readstream_cb,
194 &state, 0);
705f012d 195
40da63b1
UB
196 if (!transfer->buffer) {
197 err = LIBUSB_ERROR_NO_MEM;
198 goto cleanup;
199 }
705f012d 200
40da63b1
UB
201 transfer->status = -1;
202 err = libusb_submit_transfer(transfer);
203 if (err)
204 goto cleanup;
205 }
206
207 /* Start the transfers only when everything has been set up.
208 * Otherwise the transfers start stuttering and the PC not
209 * fetching data for several to several ten milliseconds
210 * and we skip blocks
211 */
212 if (ftdi_set_bitmode(ftdi, 0xff, BITMODE_SYNCFF) < 0)
213 {
97c6b5f6 214 fprintf(stderr,"Can't set synchronous fifo mode: %s\n",
40da63b1
UB
215 ftdi_get_error_string(ftdi));
216 goto cleanup;
217 }
218
219 /*
220 * Run the transfers, and periodically assess progress.
221 */
705f012d 222
40da63b1 223 gettimeofday(&state.progress.first.time, NULL);
705f012d 224
40da63b1
UB
225 do
226 {
227 FTDIProgressInfo *progress = &state.progress;
228 const double progressInterval = 1.0;
229 struct timeval timeout = { 0, ftdi->usb_read_timeout };
230 struct timeval now;
705f012d 231
02212d8e 232 int err = libusb_handle_events_timeout(ftdi->usb_ctx, &timeout);
705f012d
UB
233 if (err == LIBUSB_ERROR_INTERRUPTED)
234 /* restart interrupted events */
02212d8e 235 err = libusb_handle_events_timeout(ftdi->usb_ctx, &timeout);
40da63b1
UB
236 if (!state.result)
237 {
238 state.result = err;
239 }
705f012d
UB
240 if (state.activity == 0)
241 state.result = 1;
242 else
243 state.activity = 0;
244
40da63b1
UB
245 // If enough time has elapsed, update the progress
246 gettimeofday(&now, NULL);
247 if (TimevalDiff(&now, &progress->current.time) >= progressInterval)
248 {
249 progress->current.time = now;
250 progress->totalTime = TimevalDiff(&progress->current.time,
251 &progress->first.time);
705f012d 252
40da63b1
UB
253 if (progress->prev.totalBytes)
254 {
255 // We have enough information to calculate rates
705f012d 256
40da63b1 257 double currentTime;
705f012d 258
40da63b1
UB
259 currentTime = TimevalDiff(&progress->current.time,
260 &progress->prev.time);
705f012d 261
40da63b1
UB
262 progress->totalRate =
263 progress->current.totalBytes /progress->totalTime;
264 progress->currentRate =
265 (progress->current.totalBytes -
266 progress->prev.totalBytes) / currentTime;
267 }
705f012d
UB
268
269 state.callback(NULL, 0, progress, state.userdata);
40da63b1 270 progress->prev = progress->current;
705f012d 271
40da63b1
UB
272 }
273 } while (!state.result);
705f012d 274
40da63b1
UB
275 /*
276 * Cancel any outstanding transfers, and free memory.
277 */
705f012d 278
40da63b1
UB
279 cleanup:
280 fprintf(stderr, "cleanup\n");
705f012d
UB
281 if (transfers)
282 free(transfers);
40da63b1
UB
283 if (err)
284 return err;
285 else
286 return state.result;
287}
288