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