blob: 38e12acfdb962714906f791aa71db3dccb72b59b [file] [log] [blame]
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +00001/* Copyright (C) 2002-2003 RealVNC Ltd. All Rights Reserved.
2 *
3 * This is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This software is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this software; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
16 * USA.
17 */
18
19#include <stdio.h>
20#include <string.h>
21#ifdef _WIN32
22#include <winsock2.h>
23#ifndef _WIN32_WCE
24#include <sys/timeb.h>
25#endif
26#define read(s,b,l) recv(s,(char*)b,l,0)
27#define close closesocket
28#undef errno
29#define errno WSAGetLastError()
30#undef EINTR
31#define EINTR WSAEINTR
32#else
33#include <sys/types.h>
34#include <errno.h>
35#include <unistd.h>
36#include <sys/time.h>
37#endif
38
Peter Åstrand8e8b5e82004-12-30 16:00:48 +000039#ifndef min
40#define min(a,b) (((a) < (b)) ? (a) : (b))
41#endif
42
43#ifndef max
44#define max(a,b) (((a) > (b)) ? (a) : (b))
45#endif
46
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000047// XXX should use autoconf HAVE_SYS_SELECT_H
48#ifdef _AIX
49#include <sys/select.h>
50#endif
51
52#include <rdr/FdInStream.h>
53#include <rdr/Exception.h>
54
55using namespace rdr;
56
57enum { DEFAULT_BUF_SIZE = 8192,
58 MIN_BULK_SIZE = 1024 };
59
60FdInStream::FdInStream(int fd_, int timeoutms_, int bufSize_,
61 bool closeWhenDone_)
62 : fd(fd_), closeWhenDone(closeWhenDone_),
63 timeoutms(timeoutms_), blockCallback(0),
64 timing(false), timeWaitedIn100us(5), timedKbits(0),
65 bufSize(bufSize_ ? bufSize_ : DEFAULT_BUF_SIZE), offset(0)
66{
67 ptr = end = start = new U8[bufSize];
68}
69
70FdInStream::FdInStream(int fd_, FdInStreamBlockCallback* blockCallback_,
71 int bufSize_)
72 : fd(fd_), timeoutms(0), blockCallback(blockCallback_),
73 timing(false), timeWaitedIn100us(5), timedKbits(0),
74 bufSize(bufSize_ ? bufSize_ : DEFAULT_BUF_SIZE), offset(0)
75{
76 ptr = end = start = new U8[bufSize];
77}
78
79FdInStream::~FdInStream()
80{
81 delete [] start;
82 if (closeWhenDone) close(fd);
83}
84
85
86void FdInStream::setTimeout(int timeoutms_) {
87 timeoutms = timeoutms_;
88}
89
90void FdInStream::setBlockCallback(FdInStreamBlockCallback* blockCallback_)
91{
92 blockCallback = blockCallback_;
93 timeoutms = 0;
94}
95
96int FdInStream::pos()
97{
98 return offset + ptr - start;
99}
100
101void FdInStream::readBytes(void* data, int length)
102{
103 if (length < MIN_BULK_SIZE) {
104 InStream::readBytes(data, length);
105 return;
106 }
107
108 U8* dataPtr = (U8*)data;
109
110 int n = end - ptr;
111 if (n > length) n = length;
112
113 memcpy(dataPtr, ptr, n);
114 dataPtr += n;
115 length -= n;
116 ptr += n;
117
118 while (length > 0) {
119 n = readWithTimeoutOrCallback(dataPtr, length);
120 dataPtr += n;
121 length -= n;
122 offset += n;
123 }
124}
125
126
127int FdInStream::overrun(int itemSize, int nItems, bool wait)
128{
129 if (itemSize > bufSize)
130 throw Exception("FdInStream overrun: max itemSize exceeded");
131
132 if (end - ptr != 0)
133 memmove(start, ptr, end - ptr);
134
135 offset += ptr - start;
136 end -= ptr - start;
137 ptr = start;
138
Peter Åstrand0fe25442004-12-30 15:01:59 +0000139 int bytes_to_read;
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000140 while (end < start + itemSize) {
Peter Åstrand8e8b5e82004-12-30 16:00:48 +0000141 bytes_to_read = start + bufSize - end;
142 if (!timing) {
143 // When not timing, we must be careful not to read too much
144 // extra data into the buffer. Otherwise, the line speed
145 // estimation might stay at zero for a long time: All reads
146 // during timing=1 can be satisfied without calling
147 // readWithTimeoutOrCallback. However, reading only 1 or 2 bytes
148 // bytes is ineffecient.
149 bytes_to_read = min(bytes_to_read, max(itemSize*nItems, 8));
Peter Åstrand0fe25442004-12-30 15:01:59 +0000150 }
151 int n = readWithTimeoutOrCallback((U8*)end, bytes_to_read, wait);
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000152 if (n == 0) return 0;
153 end += n;
154 }
155
156 if (itemSize * nItems > end - ptr)
157 nItems = (end - ptr) / itemSize;
158
159 return nItems;
160}
161
162#ifdef _WIN32
163static void gettimeofday(struct timeval* tv, void*)
164{
165 LARGE_INTEGER counts, countsPerSec;
166 static double usecPerCount = 0.0;
167
168 if (QueryPerformanceCounter(&counts)) {
169 if (usecPerCount == 0.0) {
170 QueryPerformanceFrequency(&countsPerSec);
171 usecPerCount = 1000000.0 / countsPerSec.QuadPart;
172 }
173
174 LONGLONG usecs = (LONGLONG)(counts.QuadPart * usecPerCount);
175 tv->tv_usec = (long)(usecs % 1000000);
176 tv->tv_sec = (long)(usecs / 1000000);
177
178 } else {
179#ifndef _WIN32_WCE
180 struct timeb tb;
181 ftime(&tb);
182 tv->tv_sec = tb.time;
183 tv->tv_usec = tb.millitm * 1000;
184#else
185 throw SystemException("QueryPerformanceCounter", GetLastError());
186#endif
187 }
188}
189#endif
190
191//
192// readWithTimeoutOrCallback() reads up to the given length in bytes from the
193// file descriptor into a buffer. If the wait argument is false, then zero is
194// returned if no bytes can be read without blocking. Otherwise if a
195// blockCallback is set, it will be called (repeatedly) instead of blocking.
196// If alternatively there is a timeout set and that timeout expires, it throws
197// a TimedOut exception. Otherwise it returns the number of bytes read. It
198// never attempts to read() unless select() indicates that the fd is readable -
199// this means it can be used on an fd which has been set non-blocking. It also
200// has to cope with the annoying possibility of both select() and read()
201// returning EINTR.
202//
203
204int FdInStream::readWithTimeoutOrCallback(void* buf, int len, bool wait)
205{
206 struct timeval before, after;
207 if (timing)
208 gettimeofday(&before, 0);
209
210 int n;
211 while (true) {
212 do {
213 fd_set fds;
214 struct timeval tv;
215 struct timeval* tvp = &tv;
216
217 if (!wait) {
218 tv.tv_sec = tv.tv_usec = 0;
219 } else if (timeoutms != -1) {
220 tv.tv_sec = timeoutms / 1000;
221 tv.tv_usec = (timeoutms % 1000) * 1000;
222 } else {
223 tvp = 0;
224 }
225
226 FD_ZERO(&fds);
227 FD_SET(fd, &fds);
228 n = select(fd+1, &fds, 0, 0, tvp);
229 } while (n < 0 && errno == EINTR);
230
231 if (n > 0) break;
232 if (n < 0) throw SystemException("select",errno);
233 if (!wait) return 0;
234 if (!blockCallback) throw TimedOut();
235
236 blockCallback->blockCallback();
237 }
238
239 do {
240 n = ::read(fd, buf, len);
241 } while (n < 0 && errno == EINTR);
242
243 if (n < 0) throw SystemException("read",errno);
244 if (n == 0) throw EndOfStream();
245
246 if (timing) {
247 gettimeofday(&after, 0);
248// fprintf(stderr,"%d.%06d\n",(after.tv_sec - before.tv_sec),
249// (after.tv_usec - before.tv_usec));
250 int newTimeWaited = ((after.tv_sec - before.tv_sec) * 10000 +
251 (after.tv_usec - before.tv_usec) / 100);
252 int newKbits = n * 8 / 1000;
253
254// if (newTimeWaited == 0) {
255// fprintf(stderr,"new kbps infinite t %d k %d\n",
256// newTimeWaited, newKbits);
257// } else {
258// fprintf(stderr,"new kbps %d t %d k %d\n",
259// newKbits * 10000 / newTimeWaited, newTimeWaited, newKbits);
260// }
261
262 // limit rate to between 10kbit/s and 40Mbit/s
263
264 if (newTimeWaited > newKbits*1000) newTimeWaited = newKbits*1000;
265 if (newTimeWaited < newKbits/4) newTimeWaited = newKbits/4;
266
267 timeWaitedIn100us += newTimeWaited;
268 timedKbits += newKbits;
269 }
270
271 return n;
272}
273
274void FdInStream::startTiming()
275{
276 timing = true;
277
278 // Carry over up to 1s worth of previous rate for smoothing.
279
280 if (timeWaitedIn100us > 10000) {
281 timedKbits = timedKbits * 10000 / timeWaitedIn100us;
282 timeWaitedIn100us = 10000;
283 }
284}
285
286void FdInStream::stopTiming()
287{
288 timing = false;
289 if (timeWaitedIn100us < timedKbits/2)
290 timeWaitedIn100us = timedKbits/2; // upper limit 20Mbit/s
291}
292
293unsigned int FdInStream::kbitsPerSecond()
294{
295 // The following calculation will overflow 32-bit arithmetic if we have
296 // received more than about 50Mbytes (400Mbits) since we started timing, so
297 // it should be OK for a single RFB update.
298
299 return timedKbits * 10000 / timeWaitedIn100us;
300}