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