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