blob: bf13cac65d31eccf1a08c5d78ded431570d98ed9 [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 Kaplinsky1d378022007-12-25 17:43:09 +000042IntParameter PollingManager::m_videoPriority("VideoPriority",
43 "Priority of sending updates for video area (0..8)", 2);
44
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000045//
46// Constructor.
47//
48// Note that dpy and image should remain valid during the object
49// lifetime, while factory is used only in the constructor itself.
50//
51
52PollingManager::PollingManager(Display *dpy, Image *image,
53 ImageFactory *factory,
54 int offsetLeft, int offsetTop)
55 : m_dpy(dpy), m_server(0), m_image(image),
56 m_offsetLeft(offsetLeft), m_offsetTop(offsetTop),
Constantin Kaplinsky1d378022007-12-25 17:43:09 +000057 m_numVideoPasses(0),
Constantin Kaplinskyd0b15c62007-10-09 08:15:25 +000058 m_pollingStep(0)
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000059{
60 // Save width and height of the screen (and the image).
61 m_width = m_image->xim->width;
62 m_height = m_image->xim->height;
63
64 // Compute width and height in 32x32 tiles.
65 m_widthTiles = (m_width + 31) / 32;
66 m_heightTiles = (m_height + 31) / 32;
67
68 // Get initial screen image.
69 m_image->get(DefaultRootWindow(m_dpy), m_offsetLeft, m_offsetTop);
70
Constantin Kaplinsky9ee8dc62007-10-09 07:46:32 +000071 // Create additional images used in polling algorithm, warn if
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000072 // underlying class names are different from the class name of the
73 // primary image.
74 m_rowImage = factory->newImage(m_dpy, m_width, 1);
Constantin Kaplinskyd0b15c62007-10-09 08:15:25 +000075 if (strcmp(m_image->className(), m_rowImage->className()) != 0) {
76 vlog.error("Image types do not match (%s)",
77 m_rowImage->className());
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000078 }
79
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000080 int numTiles = m_widthTiles * m_heightTiles;
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000081 m_rateMatrix = new char[numTiles];
82 m_videoFlags = new char[numTiles];
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000083 memset(m_rateMatrix, 0, numTiles);
84 memset(m_videoFlags, 0, numTiles);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000085}
86
87PollingManager::~PollingManager()
88{
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000089 delete[] m_videoFlags;
90 delete[] m_rateMatrix;
91
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000092 delete m_rowImage;
93}
94
95//
96// Register VNCServer object.
97//
98
99void PollingManager::setVNCServer(VNCServer *s)
100{
101 m_server = s;
102}
103
104//
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000105// DEBUG: Measuring time spent in the poll() function,
106// as well as time intervals between poll() calls.
107//
108
109#ifdef DEBUG
110void PollingManager::debugBeforePoll()
111{
112 TimeMillis timeNow;
113 int diff = timeNow.diffFrom(m_timeSaved);
114 fprintf(stderr, "[wait%4dms]\t[step %2d]\t", diff, m_pollingStep % 32);
115 m_timeSaved = timeNow;
116}
117
118void PollingManager::debugAfterPoll()
119{
120 TimeMillis timeNow;
121 int diff = timeNow.diffFrom(m_timeSaved);
122 fprintf(stderr, "[poll%4dms]\n", diff);
123 m_timeSaved = timeNow;
124}
125
126#endif
127
128//
129// Search for changed rectangles on the screen.
130//
131
132void PollingManager::poll()
133{
134#ifdef DEBUG
135 debugBeforePoll();
136#endif
137
Constantin Kaplinskyd0b15c62007-10-09 08:15:25 +0000138 // Perform polling and try update clients if changes were detected.
139 if (pollScreen())
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000140 m_server->tryUpdate();
141
142#ifdef DEBUG
143 debugAfterPoll();
144#endif
145}
146
Constantin Kaplinsky9ee8dc62007-10-09 07:46:32 +0000147bool PollingManager::pollScreen()
Constantin Kaplinskya119b482007-10-04 06:02:02 +0000148{
149 if (!m_server)
150 return false;
151
Constantin Kaplinsky1d378022007-12-25 17:43:09 +0000152 // If video data should have higher priority, and video area was
153 // detected, perform special passes to send video data only. Such
154 // "video passes" will be performed between normal polling passes.
155 // No actual polling is performed in a video pass since we know that
156 // video is changing continuously.
157 if ((int)m_videoPriority > 1 && !m_videoRect.is_empty()) {
158 if (m_numVideoPasses > 0) {
159 m_numVideoPasses--;
160 getScreenRect(m_videoRect);
161 return true; // we've got changes
162 } else {
163 // Normal pass now, but schedule video passes for next calls.
164 m_numVideoPasses = (int)m_videoPriority - 1;
165 }
166 }
167
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000168 // changeFlags[] array will hold boolean values corresponding to
169 // each 32x32 tile. If a value is true, then we've detected a change
170 // in that tile. Initially, we fill in the array with zero values.
171 bool *changeFlags = new bool[m_widthTiles * m_heightTiles];
172 memset(changeFlags, 0, m_widthTiles * m_heightTiles * sizeof(bool));
Constantin Kaplinskya119b482007-10-04 06:02:02 +0000173
Constantin Kaplinskybc6b9e22007-10-04 11:43:41 +0000174 // First pass over the framebuffer. Here we scan 1/32 part of the
175 // framebuffer -- that is, one line in each (32 * m_width) stripe.
176 // We compare the pixels of that line with previous framebuffer
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000177 // contents and raise corresponding member values of changeFlags[].
Constantin Kaplinskybc6b9e22007-10-04 11:43:41 +0000178 int scanOffset = m_pollingOrder[m_pollingStep++ % 32];
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000179 bool *pChangeFlags = changeFlags;
Constantin Kaplinskya119b482007-10-04 06:02:02 +0000180 int nTilesChanged = 0;
Constantin Kaplinskybc6b9e22007-10-04 11:43:41 +0000181 for (int y = scanOffset; y < m_height; y += 32) {
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000182 nTilesChanged += checkRow(0, y, m_width, pChangeFlags);
183 pChangeFlags += m_widthTiles;
Constantin Kaplinskya119b482007-10-04 06:02:02 +0000184 }
185
Constantin Kaplinskyc1984e02007-10-08 14:54:18 +0000186 // Do the work related to video area detection.
Constantin Kaplinsky1d378022007-12-25 17:43:09 +0000187 bool haveVideoRect = false;
188 if ((int)m_videoPriority != 0)
189 haveVideoRect = handleVideo(changeFlags);
Constantin Kaplinskyc1984e02007-10-08 14:54:18 +0000190
Constantin Kaplinskya119b482007-10-04 06:02:02 +0000191 // Inform the server about the changes.
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000192 // FIXME: It's possible that (nTilesChanged != 0) but changeFlags[]
Constantin Kaplinsky6bb4bf12007-10-09 12:03:15 +0000193 // array is empty. That's possible because handleVideo()
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000194 // modifies changeFlags[].
Constantin Kaplinskya79255b2007-10-07 13:03:55 +0000195 if (nTilesChanged)
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000196 sendChanges(changeFlags);
Constantin Kaplinskya119b482007-10-04 06:02:02 +0000197
198 // Cleanup.
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000199 delete[] changeFlags;
Constantin Kaplinskya119b482007-10-04 06:02:02 +0000200
Constantin Kaplinskyc1984e02007-10-08 14:54:18 +0000201#ifdef DEBUG
202 if (nTilesChanged != 0) {
203 fprintf(stderr, "#%d# ", nTilesChanged);
204 }
205#endif
206
Constantin Kaplinsky6bb4bf12007-10-09 12:03:15 +0000207 return (nTilesChanged != 0 || haveVideoRect);
Constantin Kaplinskya119b482007-10-04 06:02:02 +0000208}
209
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000210int PollingManager::checkRow(int x, int y, int w, bool *pChangeFlags)
Constantin Kaplinskybc6b9e22007-10-04 11:43:41 +0000211{
212 int bytesPerPixel = m_image->xim->bits_per_pixel / 8;
213 int bytesPerLine = m_image->xim->bytes_per_line;
214
Constantin Kaplinsky29d32052007-10-08 14:16:02 +0000215 if (x == 0 && w == m_width) {
216 getFullRow(y); // use more efficient method if possible
217 } else {
218 getRow(x, y, w);
219 }
Constantin Kaplinskybc6b9e22007-10-04 11:43:41 +0000220
221 char *ptr_old = m_image->xim->data + y * bytesPerLine + x * bytesPerPixel;
222 char *ptr_new = m_rowImage->xim->data;
223
224 int nTilesChanged = 0;
225 for (int i = 0; i < (w + 31) / 32; i++) {
226 int tile_w = (w - i * 32 >= 32) ? 32 : w - i * 32;
227 int nBytes = tile_w * bytesPerPixel;
228 if (memcmp(ptr_old, ptr_new, nBytes)) {
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000229 *pChangeFlags = true;
Constantin Kaplinskybc6b9e22007-10-04 11:43:41 +0000230 nTilesChanged++;
231 }
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000232 pChangeFlags++;
Constantin Kaplinskybc6b9e22007-10-04 11:43:41 +0000233 ptr_old += nBytes;
234 ptr_new += nBytes;
235 }
236
237 return nTilesChanged;
238}
239
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000240void PollingManager::sendChanges(bool *pChangeFlags)
Constantin Kaplinskya79255b2007-10-07 13:03:55 +0000241{
242 Rect rect;
243 for (int y = 0; y < m_heightTiles; y++) {
244 for (int x = 0; x < m_widthTiles; x++) {
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000245 if (*pChangeFlags++) {
Constantin Kaplinskya79255b2007-10-07 13:03:55 +0000246 // Count successive tiles marked as changed.
247 int count = 1;
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000248 while (x + count < m_widthTiles && *pChangeFlags++) {
Constantin Kaplinskya79255b2007-10-07 13:03:55 +0000249 count++;
250 }
251 // Compute the coordinates and the size of this band.
252 rect.setXYWH(x * 32, y * 32, count * 32, 32);
253 if (rect.br.x > m_width)
254 rect.br.x = m_width;
255 if (rect.br.y > m_height)
256 rect.br.y = m_height;
257 // Add to the changed region maintained by the server.
258 getScreenRect(rect);
259 m_server->add_changed(rect);
260 // Skip processed tiles.
261 x += count;
262 }
263 }
264 }
265}
266
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000267bool PollingManager::handleVideo(bool *pChangeFlags)
Constantin Kaplinskyc1984e02007-10-08 14:54:18 +0000268{
Constantin Kaplinsky6bb4bf12007-10-09 12:03:15 +0000269 // Update counters in m_rateMatrix.
Constantin Kaplinskyc1984e02007-10-08 14:54:18 +0000270 int numTiles = m_heightTiles * m_widthTiles;
271 for (int i = 0; i < numTiles; i++)
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000272 m_rateMatrix[i] += (pChangeFlags[i] != false);
Constantin Kaplinskyc1984e02007-10-08 14:54:18 +0000273
Constantin Kaplinsky6bb4bf12007-10-09 12:03:15 +0000274 // Once per eight calls: detect video rectangle by examining
275 // m_rateMatrix[], then reset counters in m_rateMatrix[].
276 if (m_pollingStep % 8 == 0) {
277 detectVideo();
278 memset(m_rateMatrix, 0, numTiles);
Constantin Kaplinskyc1984e02007-10-08 14:54:18 +0000279 }
280
Constantin Kaplinsky646998a2007-10-09 09:31:41 +0000281 // Grab the pixels of video area. Also, exclude video rectangle from
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000282 // pChangeFlags[], to prevent grabbing the same pixels twice.
Constantin Kaplinsky646998a2007-10-09 09:31:41 +0000283 if (!m_videoRect.is_empty()) {
284 Rect r(m_videoRect.tl.x / 32, m_videoRect.tl.y / 32,
285 m_videoRect.br.x / 32, m_videoRect.br.y / 32);
286 for (int y = r.tl.y; y < r.br.y; y++) {
287 for (int x = r.tl.x; x < r.br.x; x++) {
Constantin Kaplinsky808db552007-10-09 12:48:26 +0000288 pChangeFlags[y * m_widthTiles + x] = false;
Constantin Kaplinsky646998a2007-10-09 09:31:41 +0000289 }
290 }
291 getScreenRect(m_videoRect);
292 return true; // we've got a video rectangle
293 }
Constantin Kaplinskyc1984e02007-10-08 14:54:18 +0000294
Constantin Kaplinsky646998a2007-10-09 09:31:41 +0000295 return false; // video rectangle is empty
Constantin Kaplinskyc1984e02007-10-08 14:54:18 +0000296}
297
Constantin Kaplinsky56649982007-09-04 09:15:35 +0000298void
Constantin Kaplinsky6bb4bf12007-10-09 12:03:15 +0000299PollingManager::detectVideo()
300{
301 // Configurable parameters.
302 const int VIDEO_THRESHOLD_0 = 3;
303 const int VIDEO_THRESHOLD_1 = 5;
304
Constantin Kaplinskybb563772007-12-25 11:25:07 +0000305 // In m_rateMatrix, clear counters corresponding to non-32x32 tiles.
306 // This will guarantee that the size of the video area is always a
307 // multiple of 32 pixels. This is important for hardware JPEG encoders.
308 int numTiles = m_heightTiles * m_widthTiles;
309 if (m_width % 32 != 0) {
310 for (int n = m_widthTiles - 1; n < numTiles; n += m_widthTiles)
311 m_rateMatrix[n] = 0;
312 }
313 if (m_height % 32 != 0) {
314 for (int n = numTiles - m_widthTiles; n < numTiles; n++)
315 m_rateMatrix[n] = 0;
316 }
317
Constantin Kaplinsky6bb4bf12007-10-09 12:03:15 +0000318 // First, detect candidate region that looks like video. In other
319 // words, find a region that consists of continuously changing
320 // pixels. Save the result in m_videoFlags[].
Constantin Kaplinsky6bb4bf12007-10-09 12:03:15 +0000321 for (int i = 0; i < numTiles; i++) {
322 if (m_rateMatrix[i] <= VIDEO_THRESHOLD_0) {
323 m_videoFlags[i] = 0;
324 } else if (m_rateMatrix[i] >= VIDEO_THRESHOLD_1) {
325 m_videoFlags[i] = 1;
326 }
327 }
328
329 // Now, choose the biggest rectangle from that candidate region.
330 Rect newRect;
331 getVideoAreaRect(&newRect);
332
333 // Does new rectangle differ from the previously detected one?
334 // If it does, save new rectangle and inform the server.
335 if (!newRect.equals(m_videoRect)) {
336 if (newRect.is_empty()) {
Constantin Kaplinskydab9a562007-10-10 01:33:39 +0000337 vlog.debug("No video detected");
Constantin Kaplinsky6bb4bf12007-10-09 12:03:15 +0000338 } else {
Constantin Kaplinskydab9a562007-10-10 01:33:39 +0000339 vlog.debug("Detected video %dx%d at (%d,%d)",
340 newRect.width(), newRect.height(),
341 newRect.tl.x, newRect.tl.y);
Constantin Kaplinsky6bb4bf12007-10-09 12:03:15 +0000342 }
343 m_videoRect = newRect;
344 m_server->set_video_area(newRect);
345 }
346}
347
348void
Constantin Kaplinsky56649982007-09-04 09:15:35 +0000349PollingManager::getVideoAreaRect(Rect *result)
350{
Constantin Kaplinsky0fc9f172007-09-29 04:00:02 +0000351 int *mx_hlen, *mx_vlen;
352 constructLengthMatrices(&mx_hlen, &mx_vlen);
Constantin Kaplinsky56649982007-09-04 09:15:35 +0000353
Constantin Kaplinsky0fc9f172007-09-29 04:00:02 +0000354 int full_h = m_heightTiles;
355 int full_w = m_widthTiles;
356 int x, y;
357 Rect max_rect(0, 0, 0, 0);
358 Rect local_rect;
359
360 for (y = 0; y < full_h; y++) {
361 for (x = 0; x < full_w; x++) {
362 int max_w = mx_hlen[y * full_w + x];
363 int max_h = mx_vlen[y * full_w + x];
364 if (max_w > 2 && max_h > 1 && max_h * max_w > (int)max_rect.area()) {
365 local_rect.tl.x = x;
366 local_rect.tl.y = y;
367 findMaxLocalRect(&local_rect, mx_hlen, mx_vlen);
368 if (local_rect.area() > max_rect.area()) {
369 max_rect = local_rect;
370 }
371 }
Constantin Kaplinsky56649982007-09-04 09:15:35 +0000372 }
373 }
374
Constantin Kaplinsky0fc9f172007-09-29 04:00:02 +0000375 destroyLengthMatrices(mx_hlen, mx_vlen);
Constantin Kaplinsky56649982007-09-04 09:15:35 +0000376
Constantin Kaplinsky0fc9f172007-09-29 04:00:02 +0000377 max_rect.tl.x *= 32;
378 max_rect.tl.y *= 32;
379 max_rect.br.x *= 32;
380 max_rect.br.y *= 32;
381 if (max_rect.br.x > m_width)
382 max_rect.br.x = m_width;
383 if (max_rect.br.y > m_height)
384 max_rect.br.y = m_height;
385 *result = max_rect;
Constantin Kaplinsky56649982007-09-04 09:15:35 +0000386}
Constantin Kaplinsky0fc9f172007-09-29 04:00:02 +0000387
388void
389PollingManager::constructLengthMatrices(int **pmx_h, int **pmx_v)
390{
391 // Handy shortcuts.
392 int h = m_heightTiles;
393 int w = m_widthTiles;
394
395 // Allocate memory.
396 int *mx_h = new int[h * w];
397 memset(mx_h, 0, h * w * sizeof(int));
398 int *mx_v = new int[h * w];
399 memset(mx_v, 0, h * w * sizeof(int));
400
401 int x, y, len, i;
402
403 // Fill in horizontal length matrix.
404 for (y = 0; y < h; y++) {
405 for (x = 0; x < w; x++) {
406 len = 0;
407 while (x + len < w && m_videoFlags[y * w + x + len]) {
408 len++;
409 }
410 for (i = 0; i < len; i++) {
411 mx_h[y * w + x + i] = len - i;
412 }
413 x += len;
414 }
415 }
416
417 // Fill in vertical length matrix.
418 for (x = 0; x < w; x++) {
419 for (y = 0; y < h; y++) {
420 len = 0;
421 while (y + len < h && m_videoFlags[(y + len) * w + x]) {
422 len++;
423 }
424 for (i = 0; i < len; i++) {
425 mx_v[(y + i) * w + x] = len - i;
426 }
427 y += len;
428 }
429 }
430
431 *pmx_h = mx_h;
432 *pmx_v = mx_v;
433}
434
435void
436PollingManager::destroyLengthMatrices(int *mx_h, int *mx_v)
437{
438 delete[] mx_h;
439 delete[] mx_v;
440}
441
442// NOTE: This function assumes that current tile has non-zero in mx_h[],
443// otherwise we get division by zero.
444void
445PollingManager::findMaxLocalRect(Rect *r, int mx_h[], int mx_v[])
446{
447 int idx = r->tl.y * m_widthTiles + r->tl.x;
448
449 // NOTE: Rectangle's maximum width and height are 25 and 18
450 // (in tiles, where each tile is usually 32x32 pixels).
451 int max_w = mx_h[idx];
452 if (max_w > 25)
453 max_w = 25;
454 int cur_h = 18;
455
456 int best_w = max_w;
457 int best_area = 1 * best_w;
458
459 for (int i = 0; i < max_w; i++) {
460 int h = mx_v[idx + i];
461 if (h < cur_h) {
462 cur_h = h;
463 if (cur_h * max_w <= best_area)
464 break;
465 }
466 if (cur_h * (i + 1) > best_area) {
467 best_w = i + 1;
468 best_area = cur_h * best_w;
469 }
470 }
471
472 r->br.x = r->tl.x + best_w;
473 r->br.y = r->tl.y + best_area / best_w;
474}
475