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