blob: 841ce0f75992ded3a726666a0f4dca597e3b197f [file] [log] [blame]
Constantin Kaplinsky9ee8dc62007-10-09 07:46:32 +00001/* Copyright (C) 2004-2007 Constantin Kaplinsky. All Rights Reserved.
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +00002 *
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// PollingManager.cxx
20//
21
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000022#include <stdio.h>
23#include <string.h>
24#include <time.h>
25#include <X11/Xlib.h>
26#include <rfb/LogWriter.h>
27#include <rfb/VNCServer.h>
28#include <rfb/Configuration.h>
29#include <rfb/ServerCore.h>
30
31#include <x0vncserver/PollingManager.h>
32
33static LogWriter vlog("PollingMgr");
34
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000035const int PollingManager::m_pollingOrder[32] = {
36 0, 16, 8, 24, 4, 20, 12, 28,
37 10, 26, 18, 2, 22, 6, 30, 14,
38 1, 17, 9, 25, 7, 23, 15, 31,
39 19, 3, 27, 11, 29, 13, 5, 21
40};
41
Constantin Kaplinsky04e910b2007-12-25 18:10:35 +000042// FIXME: Check that the parameter's value is in the allowed range.
43// This applies to all other parameters as well.
Constantin Kaplinsky1d378022007-12-25 17:43:09 +000044IntParameter PollingManager::m_videoPriority("VideoPriority",
45 "Priority of sending updates for video area (0..8)", 2);
46
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000047//
48// Constructor.
49//
50// Note that dpy and image should remain valid during the object
51// lifetime, while factory is used only in the constructor itself.
52//
53
54PollingManager::PollingManager(Display *dpy, Image *image,
55 ImageFactory *factory,
56 int offsetLeft, int offsetTop)
57 : m_dpy(dpy), m_server(0), m_image(image),
58 m_offsetLeft(offsetLeft), m_offsetTop(offsetTop),
Constantin Kaplinsky1d378022007-12-25 17:43:09 +000059 m_numVideoPasses(0),
Constantin Kaplinskyd0b15c62007-10-09 08:15:25 +000060 m_pollingStep(0)
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000061{
62 // Save width and height of the screen (and the image).
63 m_width = m_image->xim->width;
64 m_height = m_image->xim->height;
65
66 // Compute width and height in 32x32 tiles.
67 m_widthTiles = (m_width + 31) / 32;
68 m_heightTiles = (m_height + 31) / 32;
69
70 // Get initial screen image.
71 m_image->get(DefaultRootWindow(m_dpy), m_offsetLeft, m_offsetTop);
72
Constantin Kaplinsky9ee8dc62007-10-09 07:46:32 +000073 // Create additional images used in polling algorithm, warn if
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000074 // underlying class names are different from the class name of the
75 // primary image.
76 m_rowImage = factory->newImage(m_dpy, m_width, 1);
Constantin Kaplinskyd0b15c62007-10-09 08:15:25 +000077 if (strcmp(m_image->className(), m_rowImage->className()) != 0) {
78 vlog.error("Image types do not match (%s)",
79 m_rowImage->className());
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000080 }
81
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000082 int numTiles = m_widthTiles * m_heightTiles;
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000083 m_rateMatrix = new char[numTiles];
84 m_videoFlags = new char[numTiles];
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000085 memset(m_rateMatrix, 0, numTiles);
86 memset(m_videoFlags, 0, numTiles);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000087}
88
89PollingManager::~PollingManager()
90{
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000091 delete[] m_videoFlags;
92 delete[] m_rateMatrix;
93
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000094 delete m_rowImage;
95}
96
97//
98// Register VNCServer object.
99//
100
101void PollingManager::setVNCServer(VNCServer *s)
102{
103 m_server = s;
104}
105
106//
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000107// DEBUG: Measuring time spent in the poll() function,
108// as well as time intervals between poll() calls.
109//
110
111#ifdef DEBUG
112void PollingManager::debugBeforePoll()
113{
114 TimeMillis timeNow;
115 int diff = timeNow.diffFrom(m_timeSaved);
116 fprintf(stderr, "[wait%4dms]\t[step %2d]\t", diff, m_pollingStep % 32);
117 m_timeSaved = timeNow;
118}
119
120void PollingManager::debugAfterPoll()
121{
122 TimeMillis timeNow;
123 int diff = timeNow.diffFrom(m_timeSaved);
124 fprintf(stderr, "[poll%4dms]\n", diff);
125 m_timeSaved = timeNow;
126}
127
128#endif
129
130//
131// Search for changed rectangles on the screen.
132//
133
134void PollingManager::poll()
135{
136#ifdef DEBUG
137 debugBeforePoll();
138#endif
139
Constantin Kaplinskyd0b15c62007-10-09 08:15:25 +0000140 // Perform polling and try update clients if changes were detected.
141 if (pollScreen())
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000142 m_server->tryUpdate();
143
144#ifdef DEBUG
145 debugAfterPoll();
146#endif
147}
148
Constantin Kaplinsky9ee8dc62007-10-09 07:46:32 +0000149bool PollingManager::pollScreen()
Constantin Kaplinskya119b482007-10-04 06:02:02 +0000150{
151 if (!m_server)
152 return false;
153
Constantin Kaplinsky1d378022007-12-25 17:43:09 +0000154 // If video data should have higher priority, and video area was
155 // detected, perform special passes to send video data only. Such
156 // "video passes" will be performed between normal polling passes.
157 // No actual polling is performed in a video pass since we know that
158 // video is changing continuously.
Constantin Kaplinsky04e910b2007-12-25 18:10:35 +0000159 //
160 // FIXME: Should we move this block into a separate function?
161 // FIXME: Giving higher priority to video area lengthens video
162 // detection cycles. Should we do something with that?
Constantin Kaplinsky1d378022007-12-25 17:43:09 +0000163 if ((int)m_videoPriority > 1 && !m_videoRect.is_empty()) {
164 if (m_numVideoPasses > 0) {
165 m_numVideoPasses--;
166 getScreenRect(m_videoRect);
167 return true; // we've got changes
168 } else {
169 // Normal pass now, but schedule video passes for next calls.
170 m_numVideoPasses = (int)m_videoPriority - 1;
171 }
172 }
173
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000174 // changeFlags[] array will hold boolean values corresponding to
175 // each 32x32 tile. If a value is true, then we've detected a change
176 // in that tile. Initially, we fill in the array with zero values.
Constantin Kaplinsky04e910b2007-12-25 18:10:35 +0000177 //
178 // FIXME: Should we use a member variable in place of changeFlags?
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000179 bool *changeFlags = new bool[m_widthTiles * m_heightTiles];
180 memset(changeFlags, 0, m_widthTiles * m_heightTiles * sizeof(bool));
Constantin Kaplinskya119b482007-10-04 06:02:02 +0000181
Constantin Kaplinskybc6b9e22007-10-04 11:43:41 +0000182 // First pass over the framebuffer. Here we scan 1/32 part of the
183 // framebuffer -- that is, one line in each (32 * m_width) stripe.
184 // We compare the pixels of that line with previous framebuffer
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000185 // contents and raise corresponding member values of changeFlags[].
Constantin Kaplinskybc6b9e22007-10-04 11:43:41 +0000186 int scanOffset = m_pollingOrder[m_pollingStep++ % 32];
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000187 bool *pChangeFlags = changeFlags;
Constantin Kaplinskya119b482007-10-04 06:02:02 +0000188 int nTilesChanged = 0;
Constantin Kaplinskybc6b9e22007-10-04 11:43:41 +0000189 for (int y = scanOffset; y < m_height; y += 32) {
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000190 nTilesChanged += checkRow(0, y, m_width, pChangeFlags);
191 pChangeFlags += m_widthTiles;
Constantin Kaplinskya119b482007-10-04 06:02:02 +0000192 }
193
Constantin Kaplinskyc1984e02007-10-08 14:54:18 +0000194 // Do the work related to video area detection.
Constantin Kaplinsky1d378022007-12-25 17:43:09 +0000195 bool haveVideoRect = false;
196 if ((int)m_videoPriority != 0)
197 haveVideoRect = handleVideo(changeFlags);
Constantin Kaplinskyc1984e02007-10-08 14:54:18 +0000198
Constantin Kaplinskya119b482007-10-04 06:02:02 +0000199 // Inform the server about the changes.
Constantin Kaplinsky04e910b2007-12-25 18:10:35 +0000200 //
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000201 // FIXME: It's possible that (nTilesChanged != 0) but changeFlags[]
Constantin Kaplinsky6bb4bf12007-10-09 12:03:15 +0000202 // array is empty. That's possible because handleVideo()
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000203 // modifies changeFlags[].
Constantin Kaplinskya79255b2007-10-07 13:03:55 +0000204 if (nTilesChanged)
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000205 sendChanges(changeFlags);
Constantin Kaplinskya119b482007-10-04 06:02:02 +0000206
207 // Cleanup.
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000208 delete[] changeFlags;
Constantin Kaplinskya119b482007-10-04 06:02:02 +0000209
Constantin Kaplinskyc1984e02007-10-08 14:54:18 +0000210#ifdef DEBUG
211 if (nTilesChanged != 0) {
212 fprintf(stderr, "#%d# ", nTilesChanged);
213 }
214#endif
215
Constantin Kaplinsky6bb4bf12007-10-09 12:03:15 +0000216 return (nTilesChanged != 0 || haveVideoRect);
Constantin Kaplinskya119b482007-10-04 06:02:02 +0000217}
218
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000219int PollingManager::checkRow(int x, int y, int w, bool *pChangeFlags)
Constantin Kaplinskybc6b9e22007-10-04 11:43:41 +0000220{
221 int bytesPerPixel = m_image->xim->bits_per_pixel / 8;
222 int bytesPerLine = m_image->xim->bytes_per_line;
223
Constantin Kaplinsky29d32052007-10-08 14:16:02 +0000224 if (x == 0 && w == m_width) {
225 getFullRow(y); // use more efficient method if possible
226 } else {
227 getRow(x, y, w);
228 }
Constantin Kaplinskybc6b9e22007-10-04 11:43:41 +0000229
230 char *ptr_old = m_image->xim->data + y * bytesPerLine + x * bytesPerPixel;
231 char *ptr_new = m_rowImage->xim->data;
232
233 int nTilesChanged = 0;
234 for (int i = 0; i < (w + 31) / 32; i++) {
235 int tile_w = (w - i * 32 >= 32) ? 32 : w - i * 32;
236 int nBytes = tile_w * bytesPerPixel;
237 if (memcmp(ptr_old, ptr_new, nBytes)) {
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000238 *pChangeFlags = true;
Constantin Kaplinskybc6b9e22007-10-04 11:43:41 +0000239 nTilesChanged++;
240 }
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000241 pChangeFlags++;
Constantin Kaplinskybc6b9e22007-10-04 11:43:41 +0000242 ptr_old += nBytes;
243 ptr_new += nBytes;
244 }
245
246 return nTilesChanged;
247}
248
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000249void PollingManager::sendChanges(bool *pChangeFlags)
Constantin Kaplinskya79255b2007-10-07 13:03:55 +0000250{
251 Rect rect;
252 for (int y = 0; y < m_heightTiles; y++) {
253 for (int x = 0; x < m_widthTiles; x++) {
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000254 if (*pChangeFlags++) {
Constantin Kaplinskya79255b2007-10-07 13:03:55 +0000255 // Count successive tiles marked as changed.
256 int count = 1;
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000257 while (x + count < m_widthTiles && *pChangeFlags++) {
Constantin Kaplinskya79255b2007-10-07 13:03:55 +0000258 count++;
259 }
260 // Compute the coordinates and the size of this band.
261 rect.setXYWH(x * 32, y * 32, count * 32, 32);
262 if (rect.br.x > m_width)
263 rect.br.x = m_width;
264 if (rect.br.y > m_height)
265 rect.br.y = m_height;
266 // Add to the changed region maintained by the server.
267 getScreenRect(rect);
268 m_server->add_changed(rect);
269 // Skip processed tiles.
270 x += count;
271 }
272 }
273 }
274}
275
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000276bool PollingManager::handleVideo(bool *pChangeFlags)
Constantin Kaplinskyc1984e02007-10-08 14:54:18 +0000277{
Constantin Kaplinsky6bb4bf12007-10-09 12:03:15 +0000278 // Update counters in m_rateMatrix.
Constantin Kaplinskyc1984e02007-10-08 14:54:18 +0000279 int numTiles = m_heightTiles * m_widthTiles;
280 for (int i = 0; i < numTiles; i++)
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000281 m_rateMatrix[i] += (pChangeFlags[i] != false);
Constantin Kaplinskyc1984e02007-10-08 14:54:18 +0000282
Constantin Kaplinsky6bb4bf12007-10-09 12:03:15 +0000283 // Once per eight calls: detect video rectangle by examining
284 // m_rateMatrix[], then reset counters in m_rateMatrix[].
285 if (m_pollingStep % 8 == 0) {
286 detectVideo();
287 memset(m_rateMatrix, 0, numTiles);
Constantin Kaplinskyc1984e02007-10-08 14:54:18 +0000288 }
289
Constantin Kaplinsky04e910b2007-12-25 18:10:35 +0000290 // FIXME: It looks like the code below rather belongs to
291 // pollScreen(). Perhaps handleVideo() should be merged back
292 // to pollScreen(), and then pollScreen() should be split in
293 // some better way, if needed at all.
294
Constantin Kaplinsky646998a2007-10-09 09:31:41 +0000295 // Grab the pixels of video area. Also, exclude video rectangle from
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000296 // pChangeFlags[], to prevent grabbing the same pixels twice.
Constantin Kaplinsky646998a2007-10-09 09:31:41 +0000297 if (!m_videoRect.is_empty()) {
298 Rect r(m_videoRect.tl.x / 32, m_videoRect.tl.y / 32,
299 m_videoRect.br.x / 32, m_videoRect.br.y / 32);
300 for (int y = r.tl.y; y < r.br.y; y++) {
301 for (int x = r.tl.x; x < r.br.x; x++) {
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000302 pChangeFlags[y * m_widthTiles + x] = false;
Constantin Kaplinsky646998a2007-10-09 09:31:41 +0000303 }
304 }
305 getScreenRect(m_videoRect);
306 return true; // we've got a video rectangle
307 }
Constantin Kaplinskyc1984e02007-10-08 14:54:18 +0000308
Constantin Kaplinsky646998a2007-10-09 09:31:41 +0000309 return false; // video rectangle is empty
Constantin Kaplinskyc1984e02007-10-08 14:54:18 +0000310}
311
Constantin Kaplinsky56649982007-09-04 09:15:35 +0000312void
Constantin Kaplinsky6bb4bf12007-10-09 12:03:15 +0000313PollingManager::detectVideo()
314{
315 // Configurable parameters.
316 const int VIDEO_THRESHOLD_0 = 3;
317 const int VIDEO_THRESHOLD_1 = 5;
318
Constantin Kaplinskybb563772007-12-25 11:25:07 +0000319 // In m_rateMatrix, clear counters corresponding to non-32x32 tiles.
320 // This will guarantee that the size of the video area is always a
321 // multiple of 32 pixels. This is important for hardware JPEG encoders.
322 int numTiles = m_heightTiles * m_widthTiles;
323 if (m_width % 32 != 0) {
324 for (int n = m_widthTiles - 1; n < numTiles; n += m_widthTiles)
325 m_rateMatrix[n] = 0;
326 }
327 if (m_height % 32 != 0) {
328 for (int n = numTiles - m_widthTiles; n < numTiles; n++)
329 m_rateMatrix[n] = 0;
330 }
331
Constantin Kaplinsky6bb4bf12007-10-09 12:03:15 +0000332 // First, detect candidate region that looks like video. In other
333 // words, find a region that consists of continuously changing
334 // pixels. Save the result in m_videoFlags[].
Constantin Kaplinsky6bb4bf12007-10-09 12:03:15 +0000335 for (int i = 0; i < numTiles; i++) {
336 if (m_rateMatrix[i] <= VIDEO_THRESHOLD_0) {
337 m_videoFlags[i] = 0;
338 } else if (m_rateMatrix[i] >= VIDEO_THRESHOLD_1) {
339 m_videoFlags[i] = 1;
340 }
341 }
342
343 // Now, choose the biggest rectangle from that candidate region.
344 Rect newRect;
345 getVideoAreaRect(&newRect);
346
347 // Does new rectangle differ from the previously detected one?
348 // If it does, save new rectangle and inform the server.
349 if (!newRect.equals(m_videoRect)) {
350 if (newRect.is_empty()) {
Constantin Kaplinskydab9a562007-10-10 01:33:39 +0000351 vlog.debug("No video detected");
Constantin Kaplinsky6bb4bf12007-10-09 12:03:15 +0000352 } else {
Constantin Kaplinskydab9a562007-10-10 01:33:39 +0000353 vlog.debug("Detected video %dx%d at (%d,%d)",
354 newRect.width(), newRect.height(),
355 newRect.tl.x, newRect.tl.y);
Constantin Kaplinsky6bb4bf12007-10-09 12:03:15 +0000356 }
357 m_videoRect = newRect;
358 m_server->set_video_area(newRect);
359 }
360}
361
362void
Constantin Kaplinsky56649982007-09-04 09:15:35 +0000363PollingManager::getVideoAreaRect(Rect *result)
364{
Constantin Kaplinsky0fc9f172007-09-29 04:00:02 +0000365 int *mx_hlen, *mx_vlen;
366 constructLengthMatrices(&mx_hlen, &mx_vlen);
Constantin Kaplinsky56649982007-09-04 09:15:35 +0000367
Constantin Kaplinsky0fc9f172007-09-29 04:00:02 +0000368 int full_h = m_heightTiles;
369 int full_w = m_widthTiles;
370 int x, y;
371 Rect max_rect(0, 0, 0, 0);
372 Rect local_rect;
373
374 for (y = 0; y < full_h; y++) {
375 for (x = 0; x < full_w; x++) {
376 int max_w = mx_hlen[y * full_w + x];
377 int max_h = mx_vlen[y * full_w + x];
378 if (max_w > 2 && max_h > 1 && max_h * max_w > (int)max_rect.area()) {
379 local_rect.tl.x = x;
380 local_rect.tl.y = y;
381 findMaxLocalRect(&local_rect, mx_hlen, mx_vlen);
382 if (local_rect.area() > max_rect.area()) {
383 max_rect = local_rect;
384 }
385 }
Constantin Kaplinsky56649982007-09-04 09:15:35 +0000386 }
387 }
388
Constantin Kaplinsky0fc9f172007-09-29 04:00:02 +0000389 destroyLengthMatrices(mx_hlen, mx_vlen);
Constantin Kaplinsky56649982007-09-04 09:15:35 +0000390
Constantin Kaplinsky0fc9f172007-09-29 04:00:02 +0000391 max_rect.tl.x *= 32;
392 max_rect.tl.y *= 32;
393 max_rect.br.x *= 32;
394 max_rect.br.y *= 32;
395 if (max_rect.br.x > m_width)
396 max_rect.br.x = m_width;
397 if (max_rect.br.y > m_height)
398 max_rect.br.y = m_height;
399 *result = max_rect;
Constantin Kaplinsky56649982007-09-04 09:15:35 +0000400}
Constantin Kaplinsky0fc9f172007-09-29 04:00:02 +0000401
402void
403PollingManager::constructLengthMatrices(int **pmx_h, int **pmx_v)
404{
405 // Handy shortcuts.
406 int h = m_heightTiles;
407 int w = m_widthTiles;
408
409 // Allocate memory.
410 int *mx_h = new int[h * w];
411 memset(mx_h, 0, h * w * sizeof(int));
412 int *mx_v = new int[h * w];
413 memset(mx_v, 0, h * w * sizeof(int));
414
415 int x, y, len, i;
416
417 // Fill in horizontal length matrix.
418 for (y = 0; y < h; y++) {
419 for (x = 0; x < w; x++) {
420 len = 0;
421 while (x + len < w && m_videoFlags[y * w + x + len]) {
422 len++;
423 }
424 for (i = 0; i < len; i++) {
425 mx_h[y * w + x + i] = len - i;
426 }
427 x += len;
428 }
429 }
430
431 // Fill in vertical length matrix.
432 for (x = 0; x < w; x++) {
433 for (y = 0; y < h; y++) {
434 len = 0;
435 while (y + len < h && m_videoFlags[(y + len) * w + x]) {
436 len++;
437 }
438 for (i = 0; i < len; i++) {
439 mx_v[(y + i) * w + x] = len - i;
440 }
441 y += len;
442 }
443 }
444
445 *pmx_h = mx_h;
446 *pmx_v = mx_v;
447}
448
449void
450PollingManager::destroyLengthMatrices(int *mx_h, int *mx_v)
451{
452 delete[] mx_h;
453 delete[] mx_v;
454}
455
456// NOTE: This function assumes that current tile has non-zero in mx_h[],
457// otherwise we get division by zero.
458void
459PollingManager::findMaxLocalRect(Rect *r, int mx_h[], int mx_v[])
460{
461 int idx = r->tl.y * m_widthTiles + r->tl.x;
462
463 // NOTE: Rectangle's maximum width and height are 25 and 18
464 // (in tiles, where each tile is usually 32x32 pixels).
465 int max_w = mx_h[idx];
466 if (max_w > 25)
467 max_w = 25;
468 int cur_h = 18;
469
470 int best_w = max_w;
471 int best_area = 1 * best_w;
472
473 for (int i = 0; i < max_w; i++) {
474 int h = mx_v[idx + i];
475 if (h < cur_h) {
476 cur_h = h;
477 if (cur_h * max_w <= best_area)
478 break;
479 }
480 if (cur_h * (i + 1) > best_area) {
481 best_w = i + 1;
482 best_area = cur_h * best_w;
483 }
484 }
485
486 r->br.x = r->tl.x + best_w;
487 r->br.y = r->tl.y + best_area / best_w;
488}
489