blob: 397847a49dfb395ccb5aa8b77c0a3c93e5405ffa [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
131 while (end < start + itemSize) {
132 int n = readWithTimeoutOrCallback((U8*)end, start + bufSize - end, wait);
133 if (n == 0) return 0;
134 end += n;
135 }
136
137 if (itemSize * nItems > end - ptr)
138 nItems = (end - ptr) / itemSize;
139
140 return nItems;
141}
142
143#ifdef _WIN32
144static void gettimeofday(struct timeval* tv, void*)
145{
146 LARGE_INTEGER counts, countsPerSec;
147 static double usecPerCount = 0.0;
148
149 if (QueryPerformanceCounter(&counts)) {
150 if (usecPerCount == 0.0) {
151 QueryPerformanceFrequency(&countsPerSec);
152 usecPerCount = 1000000.0 / countsPerSec.QuadPart;
153 }
154
155 LONGLONG usecs = (LONGLONG)(counts.QuadPart * usecPerCount);
156 tv->tv_usec = (long)(usecs % 1000000);
157 tv->tv_sec = (long)(usecs / 1000000);
158
159 } else {
160#ifndef _WIN32_WCE
161 struct timeb tb;
162 ftime(&tb);
163 tv->tv_sec = tb.time;
164 tv->tv_usec = tb.millitm * 1000;
165#else
166 throw SystemException("QueryPerformanceCounter", GetLastError());
167#endif
168 }
169}
170#endif
171
172//
173// readWithTimeoutOrCallback() reads up to the given length in bytes from the
174// file descriptor into a buffer. If the wait argument is false, then zero is
175// returned if no bytes can be read without blocking. Otherwise if a
176// blockCallback is set, it will be called (repeatedly) instead of blocking.
177// If alternatively there is a timeout set and that timeout expires, it throws
178// a TimedOut exception. Otherwise it returns the number of bytes read. It
179// never attempts to read() unless select() indicates that the fd is readable -
180// this means it can be used on an fd which has been set non-blocking. It also
181// has to cope with the annoying possibility of both select() and read()
182// returning EINTR.
183//
184
185int FdInStream::readWithTimeoutOrCallback(void* buf, int len, bool wait)
186{
187 struct timeval before, after;
188 if (timing)
189 gettimeofday(&before, 0);
190
191 int n;
192 while (true) {
193 do {
194 fd_set fds;
195 struct timeval tv;
196 struct timeval* tvp = &tv;
197
198 if (!wait) {
199 tv.tv_sec = tv.tv_usec = 0;
200 } else if (timeoutms != -1) {
201 tv.tv_sec = timeoutms / 1000;
202 tv.tv_usec = (timeoutms % 1000) * 1000;
203 } else {
204 tvp = 0;
205 }
206
207 FD_ZERO(&fds);
208 FD_SET(fd, &fds);
209 n = select(fd+1, &fds, 0, 0, tvp);
210 } while (n < 0 && errno == EINTR);
211
212 if (n > 0) break;
213 if (n < 0) throw SystemException("select",errno);
214 if (!wait) return 0;
215 if (!blockCallback) throw TimedOut();
216
217 blockCallback->blockCallback();
218 }
219
220 do {
221 n = ::read(fd, buf, len);
222 } while (n < 0 && errno == EINTR);
223
224 if (n < 0) throw SystemException("read",errno);
225 if (n == 0) throw EndOfStream();
226
227 if (timing) {
228 gettimeofday(&after, 0);
229// fprintf(stderr,"%d.%06d\n",(after.tv_sec - before.tv_sec),
230// (after.tv_usec - before.tv_usec));
231 int newTimeWaited = ((after.tv_sec - before.tv_sec) * 10000 +
232 (after.tv_usec - before.tv_usec) / 100);
233 int newKbits = n * 8 / 1000;
234
235// if (newTimeWaited == 0) {
236// fprintf(stderr,"new kbps infinite t %d k %d\n",
237// newTimeWaited, newKbits);
238// } else {
239// fprintf(stderr,"new kbps %d t %d k %d\n",
240// newKbits * 10000 / newTimeWaited, newTimeWaited, newKbits);
241// }
242
243 // limit rate to between 10kbit/s and 40Mbit/s
244
245 if (newTimeWaited > newKbits*1000) newTimeWaited = newKbits*1000;
246 if (newTimeWaited < newKbits/4) newTimeWaited = newKbits/4;
247
248 timeWaitedIn100us += newTimeWaited;
249 timedKbits += newKbits;
250 }
251
252 return n;
253}
254
255void FdInStream::startTiming()
256{
257 timing = true;
258
259 // Carry over up to 1s worth of previous rate for smoothing.
260
261 if (timeWaitedIn100us > 10000) {
262 timedKbits = timedKbits * 10000 / timeWaitedIn100us;
263 timeWaitedIn100us = 10000;
264 }
265}
266
267void FdInStream::stopTiming()
268{
269 timing = false;
270 if (timeWaitedIn100us < timedKbits/2)
271 timeWaitedIn100us = timedKbits/2; // upper limit 20Mbit/s
272}
273
274unsigned int FdInStream::kbitsPerSecond()
275{
276 // The following calculation will overflow 32-bit arithmetic if we have
277 // received more than about 50Mbytes (400Mbits) since we started timing, so
278 // it should be OK for a single RFB update.
279
280 return timedKbits * 10000 / timeWaitedIn100us;
281}