You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

EncodeManager.cxx 29KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  1. /* Copyright (C) 2000-2003 Constantin Kaplinsky. All Rights Reserved.
  2. * Copyright (C) 2011 D. R. Commander. All Rights Reserved.
  3. * Copyright 2014-2018 Pierre Ossman for Cendio AB
  4. * Copyright 2018 Peter Astrand for Cendio AB
  5. *
  6. * This is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This software is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this software; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  19. * USA.
  20. */
  21. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #include <stdlib.h>
  25. #include <rfb/EncodeManager.h>
  26. #include <rfb/Encoder.h>
  27. #include <rfb/Palette.h>
  28. #include <rfb/SConnection.h>
  29. #include <rfb/SMsgWriter.h>
  30. #include <rfb/UpdateTracker.h>
  31. #include <rfb/LogWriter.h>
  32. #include <rfb/Exception.h>
  33. #include <rfb/RawEncoder.h>
  34. #include <rfb/RREEncoder.h>
  35. #include <rfb/HextileEncoder.h>
  36. #include <rfb/ZRLEEncoder.h>
  37. #include <rfb/TightEncoder.h>
  38. #include <rfb/TightJPEGEncoder.h>
  39. using namespace rfb;
  40. static LogWriter vlog("EncodeManager");
  41. // Split each rectangle into smaller ones no larger than this area,
  42. // and no wider than this width.
  43. static const int SubRectMaxArea = 65536;
  44. static const int SubRectMaxWidth = 2048;
  45. // The size in pixels of either side of each block tested when looking
  46. // for solid blocks.
  47. static const int SolidSearchBlock = 16;
  48. // Don't bother with blocks smaller than this
  49. static const int SolidBlockMinArea = 2048;
  50. // How long we consider a region recently changed (in ms)
  51. static const int RecentChangeTimeout = 50;
  52. namespace rfb {
  53. enum EncoderClass {
  54. encoderRaw,
  55. encoderRRE,
  56. encoderHextile,
  57. encoderTight,
  58. encoderTightJPEG,
  59. encoderZRLE,
  60. encoderClassMax,
  61. };
  62. enum EncoderType {
  63. encoderSolid,
  64. encoderBitmap,
  65. encoderBitmapRLE,
  66. encoderIndexed,
  67. encoderIndexedRLE,
  68. encoderFullColour,
  69. encoderTypeMax,
  70. };
  71. struct RectInfo {
  72. int rleRuns;
  73. Palette palette;
  74. };
  75. };
  76. static const char *encoderClassName(EncoderClass klass)
  77. {
  78. switch (klass) {
  79. case encoderRaw:
  80. return "Raw";
  81. case encoderRRE:
  82. return "RRE";
  83. case encoderHextile:
  84. return "Hextile";
  85. case encoderTight:
  86. return "Tight";
  87. case encoderTightJPEG:
  88. return "Tight (JPEG)";
  89. case encoderZRLE:
  90. return "ZRLE";
  91. case encoderClassMax:
  92. break;
  93. }
  94. return "Unknown Encoder Class";
  95. }
  96. static const char *encoderTypeName(EncoderType type)
  97. {
  98. switch (type) {
  99. case encoderSolid:
  100. return "Solid";
  101. case encoderBitmap:
  102. return "Bitmap";
  103. case encoderBitmapRLE:
  104. return "Bitmap RLE";
  105. case encoderIndexed:
  106. return "Indexed";
  107. case encoderIndexedRLE:
  108. return "Indexed RLE";
  109. case encoderFullColour:
  110. return "Full Colour";
  111. case encoderTypeMax:
  112. break;
  113. }
  114. return "Unknown Encoder Type";
  115. }
  116. EncodeManager::EncodeManager(SConnection* conn_)
  117. : conn(conn_), recentChangeTimer(this)
  118. {
  119. StatsVector::iterator iter;
  120. encoders.resize(encoderClassMax, NULL);
  121. activeEncoders.resize(encoderTypeMax, encoderRaw);
  122. encoders[encoderRaw] = new RawEncoder(conn);
  123. encoders[encoderRRE] = new RREEncoder(conn);
  124. encoders[encoderHextile] = new HextileEncoder(conn);
  125. encoders[encoderTight] = new TightEncoder(conn);
  126. encoders[encoderTightJPEG] = new TightJPEGEncoder(conn);
  127. encoders[encoderZRLE] = new ZRLEEncoder(conn);
  128. updates = 0;
  129. memset(&copyStats, 0, sizeof(copyStats));
  130. stats.resize(encoderClassMax);
  131. for (iter = stats.begin();iter != stats.end();++iter) {
  132. StatsVector::value_type::iterator iter2;
  133. iter->resize(encoderTypeMax);
  134. for (iter2 = iter->begin();iter2 != iter->end();++iter2)
  135. memset(&*iter2, 0, sizeof(EncoderStats));
  136. }
  137. }
  138. EncodeManager::~EncodeManager()
  139. {
  140. std::vector<Encoder*>::iterator iter;
  141. logStats();
  142. for (iter = encoders.begin();iter != encoders.end();iter++)
  143. delete *iter;
  144. }
  145. void EncodeManager::logStats()
  146. {
  147. size_t i, j;
  148. unsigned rects;
  149. unsigned long long pixels, bytes, equivalent;
  150. double ratio;
  151. char a[1024], b[1024];
  152. rects = 0;
  153. pixels = bytes = equivalent = 0;
  154. vlog.info("Framebuffer updates: %u", updates);
  155. if (copyStats.rects != 0) {
  156. vlog.info(" %s:", "CopyRect");
  157. rects += copyStats.rects;
  158. pixels += copyStats.pixels;
  159. bytes += copyStats.bytes;
  160. equivalent += copyStats.equivalent;
  161. ratio = (double)copyStats.equivalent / copyStats.bytes;
  162. siPrefix(copyStats.rects, "rects", a, sizeof(a));
  163. siPrefix(copyStats.pixels, "pixels", b, sizeof(b));
  164. vlog.info(" %s: %s, %s", "Copies", a, b);
  165. iecPrefix(copyStats.bytes, "B", a, sizeof(a));
  166. vlog.info(" %*s %s (1:%g ratio)",
  167. (int)strlen("Copies"), "",
  168. a, ratio);
  169. }
  170. for (i = 0;i < stats.size();i++) {
  171. // Did this class do anything at all?
  172. for (j = 0;j < stats[i].size();j++) {
  173. if (stats[i][j].rects != 0)
  174. break;
  175. }
  176. if (j == stats[i].size())
  177. continue;
  178. vlog.info(" %s:", encoderClassName((EncoderClass)i));
  179. for (j = 0;j < stats[i].size();j++) {
  180. if (stats[i][j].rects == 0)
  181. continue;
  182. rects += stats[i][j].rects;
  183. pixels += stats[i][j].pixels;
  184. bytes += stats[i][j].bytes;
  185. equivalent += stats[i][j].equivalent;
  186. ratio = (double)stats[i][j].equivalent / stats[i][j].bytes;
  187. siPrefix(stats[i][j].rects, "rects", a, sizeof(a));
  188. siPrefix(stats[i][j].pixels, "pixels", b, sizeof(b));
  189. vlog.info(" %s: %s, %s", encoderTypeName((EncoderType)j), a, b);
  190. iecPrefix(stats[i][j].bytes, "B", a, sizeof(a));
  191. vlog.info(" %*s %s (1:%g ratio)",
  192. (int)strlen(encoderTypeName((EncoderType)j)), "",
  193. a, ratio);
  194. }
  195. }
  196. ratio = (double)equivalent / bytes;
  197. siPrefix(rects, "rects", a, sizeof(a));
  198. siPrefix(pixels, "pixels", b, sizeof(b));
  199. vlog.info(" Total: %s, %s", a, b);
  200. iecPrefix(bytes, "B", a, sizeof(a));
  201. vlog.info(" %s (1:%g ratio)", a, ratio);
  202. }
  203. bool EncodeManager::supported(int encoding)
  204. {
  205. switch (encoding) {
  206. case encodingRaw:
  207. case encodingRRE:
  208. case encodingHextile:
  209. case encodingZRLE:
  210. case encodingTight:
  211. return true;
  212. default:
  213. return false;
  214. }
  215. }
  216. bool EncodeManager::needsLosslessRefresh(const Region& req)
  217. {
  218. return !lossyRegion.intersect(req).is_empty();
  219. }
  220. int EncodeManager::getNextLosslessRefresh(const Region& req)
  221. {
  222. // Do we have something we can send right away?
  223. if (!pendingRefreshRegion.intersect(req).is_empty())
  224. return 0;
  225. assert(needsLosslessRefresh(req));
  226. assert(recentChangeTimer.isStarted());
  227. return recentChangeTimer.getNextTimeout();
  228. }
  229. void EncodeManager::pruneLosslessRefresh(const Region& limits)
  230. {
  231. lossyRegion.assign_intersect(limits);
  232. pendingRefreshRegion.assign_intersect(limits);
  233. }
  234. void EncodeManager::writeUpdate(const UpdateInfo& ui, const PixelBuffer* pb,
  235. const RenderedCursor* renderedCursor)
  236. {
  237. doUpdate(true, ui.changed, ui.copied, ui.copy_delta, pb, renderedCursor);
  238. recentlyChangedRegion.assign_union(ui.changed);
  239. recentlyChangedRegion.assign_union(ui.copied);
  240. if (!recentChangeTimer.isStarted())
  241. recentChangeTimer.start(RecentChangeTimeout);
  242. }
  243. void EncodeManager::writeLosslessRefresh(const Region& req, const PixelBuffer* pb,
  244. const RenderedCursor* renderedCursor,
  245. size_t maxUpdateSize)
  246. {
  247. doUpdate(false, getLosslessRefresh(req, maxUpdateSize),
  248. Region(), Point(), pb, renderedCursor);
  249. }
  250. bool EncodeManager::handleTimeout(Timer* t)
  251. {
  252. if (t == &recentChangeTimer) {
  253. // Any lossy region that wasn't recently updated can
  254. // now be scheduled for a refresh
  255. pendingRefreshRegion.assign_union(lossyRegion.subtract(recentlyChangedRegion));
  256. recentlyChangedRegion.clear();
  257. // Will there be more to do? (i.e. do we need another round)
  258. if (!lossyRegion.subtract(pendingRefreshRegion).is_empty())
  259. return true;
  260. }
  261. return false;
  262. }
  263. void EncodeManager::doUpdate(bool allowLossy, const Region& changed_,
  264. const Region& copied, const Point& copyDelta,
  265. const PixelBuffer* pb,
  266. const RenderedCursor* renderedCursor)
  267. {
  268. int nRects;
  269. Region changed, cursorRegion;
  270. updates++;
  271. prepareEncoders(allowLossy);
  272. changed = changed_;
  273. if (!conn->client.supportsEncoding(encodingCopyRect))
  274. changed.assign_union(copied);
  275. /*
  276. * We need to render the cursor seperately as it has its own
  277. * magical pixel buffer, so split it out from the changed region.
  278. */
  279. if (renderedCursor != NULL) {
  280. cursorRegion = changed.intersect(renderedCursor->getEffectiveRect());
  281. changed.assign_subtract(renderedCursor->getEffectiveRect());
  282. }
  283. if (conn->client.supportsEncoding(pseudoEncodingLastRect))
  284. nRects = 0xFFFF;
  285. else {
  286. nRects = 0;
  287. if (conn->client.supportsEncoding(encodingCopyRect))
  288. nRects += copied.numRects();
  289. nRects += computeNumRects(changed);
  290. nRects += computeNumRects(cursorRegion);
  291. }
  292. conn->writer()->writeFramebufferUpdateStart(nRects);
  293. if (conn->client.supportsEncoding(encodingCopyRect))
  294. writeCopyRects(copied, copyDelta);
  295. /*
  296. * We start by searching for solid rects, which are then removed
  297. * from the changed region.
  298. */
  299. if (conn->client.supportsEncoding(pseudoEncodingLastRect))
  300. writeSolidRects(&changed, pb);
  301. writeRects(changed, pb);
  302. writeRects(cursorRegion, renderedCursor);
  303. conn->writer()->writeFramebufferUpdateEnd();
  304. }
  305. void EncodeManager::prepareEncoders(bool allowLossy)
  306. {
  307. enum EncoderClass solid, bitmap, bitmapRLE;
  308. enum EncoderClass indexed, indexedRLE, fullColour;
  309. bool allowJPEG;
  310. rdr::S32 preferred;
  311. std::vector<int>::iterator iter;
  312. solid = bitmap = bitmapRLE = encoderRaw;
  313. indexed = indexedRLE = fullColour = encoderRaw;
  314. allowJPEG = conn->client.pf().bpp >= 16;
  315. if (!allowLossy) {
  316. if (encoders[encoderTightJPEG]->losslessQuality == -1)
  317. allowJPEG = false;
  318. }
  319. // Try to respect the client's wishes
  320. preferred = conn->getPreferredEncoding();
  321. switch (preferred) {
  322. case encodingRRE:
  323. // Horrible for anything high frequency and/or lots of colours
  324. bitmapRLE = indexedRLE = encoderRRE;
  325. break;
  326. case encodingHextile:
  327. // Slightly less horrible
  328. bitmapRLE = indexedRLE = fullColour = encoderHextile;
  329. break;
  330. case encodingTight:
  331. if (encoders[encoderTightJPEG]->isSupported() && allowJPEG)
  332. fullColour = encoderTightJPEG;
  333. else
  334. fullColour = encoderTight;
  335. indexed = indexedRLE = encoderTight;
  336. bitmap = bitmapRLE = encoderTight;
  337. break;
  338. case encodingZRLE:
  339. fullColour = encoderZRLE;
  340. bitmapRLE = indexedRLE = encoderZRLE;
  341. bitmap = indexed = encoderZRLE;
  342. break;
  343. }
  344. // Any encoders still unassigned?
  345. if (fullColour == encoderRaw) {
  346. if (encoders[encoderTightJPEG]->isSupported() && allowJPEG)
  347. fullColour = encoderTightJPEG;
  348. else if (encoders[encoderZRLE]->isSupported())
  349. fullColour = encoderZRLE;
  350. else if (encoders[encoderTight]->isSupported())
  351. fullColour = encoderTight;
  352. else if (encoders[encoderHextile]->isSupported())
  353. fullColour = encoderHextile;
  354. }
  355. if (indexed == encoderRaw) {
  356. if (encoders[encoderZRLE]->isSupported())
  357. indexed = encoderZRLE;
  358. else if (encoders[encoderTight]->isSupported())
  359. indexed = encoderTight;
  360. else if (encoders[encoderHextile]->isSupported())
  361. indexed = encoderHextile;
  362. }
  363. if (indexedRLE == encoderRaw)
  364. indexedRLE = indexed;
  365. if (bitmap == encoderRaw)
  366. bitmap = indexed;
  367. if (bitmapRLE == encoderRaw)
  368. bitmapRLE = bitmap;
  369. if (solid == encoderRaw) {
  370. if (encoders[encoderTight]->isSupported())
  371. solid = encoderTight;
  372. else if (encoders[encoderRRE]->isSupported())
  373. solid = encoderRRE;
  374. else if (encoders[encoderZRLE]->isSupported())
  375. solid = encoderZRLE;
  376. else if (encoders[encoderHextile]->isSupported())
  377. solid = encoderHextile;
  378. }
  379. // JPEG is the only encoder that can reduce things to grayscale
  380. if ((conn->client.subsampling == subsampleGray) &&
  381. encoders[encoderTightJPEG]->isSupported() && allowLossy) {
  382. solid = bitmap = bitmapRLE = encoderTightJPEG;
  383. indexed = indexedRLE = fullColour = encoderTightJPEG;
  384. }
  385. activeEncoders[encoderSolid] = solid;
  386. activeEncoders[encoderBitmap] = bitmap;
  387. activeEncoders[encoderBitmapRLE] = bitmapRLE;
  388. activeEncoders[encoderIndexed] = indexed;
  389. activeEncoders[encoderIndexedRLE] = indexedRLE;
  390. activeEncoders[encoderFullColour] = fullColour;
  391. for (iter = activeEncoders.begin(); iter != activeEncoders.end(); ++iter) {
  392. Encoder *encoder;
  393. encoder = encoders[*iter];
  394. encoder->setCompressLevel(conn->client.compressLevel);
  395. if (allowLossy) {
  396. encoder->setQualityLevel(conn->client.qualityLevel);
  397. encoder->setFineQualityLevel(conn->client.fineQualityLevel,
  398. conn->client.subsampling);
  399. } else {
  400. int level = __rfbmax(conn->client.qualityLevel,
  401. encoder->losslessQuality);
  402. encoder->setQualityLevel(level);
  403. encoder->setFineQualityLevel(-1, subsampleUndefined);
  404. }
  405. }
  406. }
  407. Region EncodeManager::getLosslessRefresh(const Region& req,
  408. size_t maxUpdateSize)
  409. {
  410. std::vector<Rect> rects;
  411. Region refresh;
  412. size_t area;
  413. // We make a conservative guess at the compression ratio at 2:1
  414. maxUpdateSize *= 2;
  415. // We will measure pixels, not bytes (assume 32 bpp)
  416. maxUpdateSize /= 4;
  417. area = 0;
  418. pendingRefreshRegion.intersect(req).get_rects(&rects);
  419. while (!rects.empty()) {
  420. size_t idx;
  421. Rect rect;
  422. // Grab a random rect so we don't keep damaging and restoring the
  423. // same rect over and over
  424. idx = rand() % rects.size();
  425. rect = rects[idx];
  426. // Add rects until we exceed the threshold, then include as much as
  427. // possible of the final rect
  428. if ((area + rect.area()) > maxUpdateSize) {
  429. // Use the narrowest axis to avoid getting to thin rects
  430. if (rect.width() > rect.height()) {
  431. int width = (maxUpdateSize - area) / rect.height();
  432. rect.br.x = rect.tl.x + __rfbmax(1, width);
  433. } else {
  434. int height = (maxUpdateSize - area) / rect.width();
  435. rect.br.y = rect.tl.y + __rfbmax(1, height);
  436. }
  437. refresh.assign_union(Region(rect));
  438. break;
  439. }
  440. area += rect.area();
  441. refresh.assign_union(Region(rect));
  442. rects.erase(rects.begin() + idx);
  443. }
  444. return refresh;
  445. }
  446. int EncodeManager::computeNumRects(const Region& changed)
  447. {
  448. int numRects;
  449. std::vector<Rect> rects;
  450. std::vector<Rect>::const_iterator rect;
  451. numRects = 0;
  452. changed.get_rects(&rects);
  453. for (rect = rects.begin(); rect != rects.end(); ++rect) {
  454. int w, h, sw, sh;
  455. w = rect->width();
  456. h = rect->height();
  457. // No split necessary?
  458. if (((w*h) < SubRectMaxArea) && (w < SubRectMaxWidth)) {
  459. numRects += 1;
  460. continue;
  461. }
  462. if (w <= SubRectMaxWidth)
  463. sw = w;
  464. else
  465. sw = SubRectMaxWidth;
  466. sh = SubRectMaxArea / sw;
  467. // ceil(w/sw) * ceil(h/sh)
  468. numRects += (((w - 1)/sw) + 1) * (((h - 1)/sh) + 1);
  469. }
  470. return numRects;
  471. }
  472. Encoder *EncodeManager::startRect(const Rect& rect, int type)
  473. {
  474. Encoder *encoder;
  475. int klass, equiv;
  476. activeType = type;
  477. klass = activeEncoders[activeType];
  478. beforeLength = conn->getOutStream()->length();
  479. stats[klass][activeType].rects++;
  480. stats[klass][activeType].pixels += rect.area();
  481. equiv = 12 + rect.area() * (conn->client.pf().bpp/8);
  482. stats[klass][activeType].equivalent += equiv;
  483. encoder = encoders[klass];
  484. conn->writer()->startRect(rect, encoder->encoding);
  485. if ((encoder->flags & EncoderLossy) &&
  486. ((encoder->losslessQuality == -1) ||
  487. (encoder->getQualityLevel() < encoder->losslessQuality)))
  488. lossyRegion.assign_union(Region(rect));
  489. else
  490. lossyRegion.assign_subtract(Region(rect));
  491. // This was either a rect getting refreshed, or a rect that just got
  492. // new content. Either way we should not try to refresh it anymore.
  493. pendingRefreshRegion.assign_subtract(Region(rect));
  494. return encoder;
  495. }
  496. void EncodeManager::endRect()
  497. {
  498. int klass;
  499. int length;
  500. conn->writer()->endRect();
  501. length = conn->getOutStream()->length() - beforeLength;
  502. klass = activeEncoders[activeType];
  503. stats[klass][activeType].bytes += length;
  504. }
  505. void EncodeManager::writeCopyRects(const Region& copied, const Point& delta)
  506. {
  507. std::vector<Rect> rects;
  508. std::vector<Rect>::const_iterator rect;
  509. Region lossyCopy;
  510. beforeLength = conn->getOutStream()->length();
  511. copied.get_rects(&rects, delta.x <= 0, delta.y <= 0);
  512. for (rect = rects.begin(); rect != rects.end(); ++rect) {
  513. int equiv;
  514. copyStats.rects++;
  515. copyStats.pixels += rect->area();
  516. equiv = 12 + rect->area() * (conn->client.pf().bpp/8);
  517. copyStats.equivalent += equiv;
  518. conn->writer()->writeCopyRect(*rect, rect->tl.x - delta.x,
  519. rect->tl.y - delta.y);
  520. }
  521. copyStats.bytes += conn->getOutStream()->length() - beforeLength;
  522. lossyCopy = lossyRegion;
  523. lossyCopy.translate(delta);
  524. lossyCopy.assign_intersect(copied);
  525. lossyRegion.assign_union(lossyCopy);
  526. // Stop any pending refresh as a copy is enough that we consider
  527. // this region to be recently changed
  528. pendingRefreshRegion.assign_subtract(copied);
  529. }
  530. void EncodeManager::writeSolidRects(Region *changed, const PixelBuffer* pb)
  531. {
  532. std::vector<Rect> rects;
  533. std::vector<Rect>::const_iterator rect;
  534. changed->get_rects(&rects);
  535. for (rect = rects.begin(); rect != rects.end(); ++rect)
  536. findSolidRect(*rect, changed, pb);
  537. }
  538. void EncodeManager::findSolidRect(const Rect& rect, Region *changed,
  539. const PixelBuffer* pb)
  540. {
  541. Rect sr;
  542. int dx, dy, dw, dh;
  543. // We start by finding a solid 16x16 block
  544. for (dy = rect.tl.y; dy < rect.br.y; dy += SolidSearchBlock) {
  545. dh = SolidSearchBlock;
  546. if (dy + dh > rect.br.y)
  547. dh = rect.br.y - dy;
  548. for (dx = rect.tl.x; dx < rect.br.x; dx += SolidSearchBlock) {
  549. // We define it like this to guarantee alignment
  550. rdr::U32 _buffer;
  551. rdr::U8* colourValue = (rdr::U8*)&_buffer;
  552. dw = SolidSearchBlock;
  553. if (dx + dw > rect.br.x)
  554. dw = rect.br.x - dx;
  555. pb->getImage(colourValue, Rect(dx, dy, dx+1, dy+1));
  556. sr.setXYWH(dx, dy, dw, dh);
  557. if (checkSolidTile(sr, colourValue, pb)) {
  558. Rect erb, erp;
  559. Encoder *encoder;
  560. // We then try extending the area by adding more blocks
  561. // in both directions and pick the combination that gives
  562. // the largest area.
  563. sr.setXYWH(dx, dy, rect.br.x - dx, rect.br.y - dy);
  564. extendSolidAreaByBlock(sr, colourValue, pb, &erb);
  565. // Did we end up getting the entire rectangle?
  566. if (erb.equals(rect))
  567. erp = erb;
  568. else {
  569. // Don't bother with sending tiny rectangles
  570. if (erb.area() < SolidBlockMinArea)
  571. continue;
  572. // Extend the area again, but this time one pixel
  573. // row/column at a time.
  574. extendSolidAreaByPixel(rect, erb, colourValue, pb, &erp);
  575. }
  576. // Send solid-color rectangle.
  577. encoder = startRect(erp, encoderSolid);
  578. if (encoder->flags & EncoderUseNativePF) {
  579. encoder->writeSolidRect(erp.width(), erp.height(),
  580. pb->getPF(), colourValue);
  581. } else {
  582. rdr::U32 _buffer2;
  583. rdr::U8* converted = (rdr::U8*)&_buffer2;
  584. conn->client.pf().bufferFromBuffer(converted, pb->getPF(),
  585. colourValue, 1);
  586. encoder->writeSolidRect(erp.width(), erp.height(),
  587. conn->client.pf(), converted);
  588. }
  589. endRect();
  590. changed->assign_subtract(Region(erp));
  591. // Search remaining areas by recursion
  592. // FIXME: Is this the best way to divide things up?
  593. // Left? (Note that we've already searched a SolidSearchBlock
  594. // pixels high strip here)
  595. if ((erp.tl.x != rect.tl.x) && (erp.height() > SolidSearchBlock)) {
  596. sr.setXYWH(rect.tl.x, erp.tl.y + SolidSearchBlock,
  597. erp.tl.x - rect.tl.x, erp.height() - SolidSearchBlock);
  598. findSolidRect(sr, changed, pb);
  599. }
  600. // Right?
  601. if (erp.br.x != rect.br.x) {
  602. sr.setXYWH(erp.br.x, erp.tl.y, rect.br.x - erp.br.x, erp.height());
  603. findSolidRect(sr, changed, pb);
  604. }
  605. // Below?
  606. if (erp.br.y != rect.br.y) {
  607. sr.setXYWH(rect.tl.x, erp.br.y, rect.width(), rect.br.y - erp.br.y);
  608. findSolidRect(sr, changed, pb);
  609. }
  610. return;
  611. }
  612. }
  613. }
  614. }
  615. void EncodeManager::writeRects(const Region& changed, const PixelBuffer* pb)
  616. {
  617. std::vector<Rect> rects;
  618. std::vector<Rect>::const_iterator rect;
  619. changed.get_rects(&rects);
  620. for (rect = rects.begin(); rect != rects.end(); ++rect) {
  621. int w, h, sw, sh;
  622. Rect sr;
  623. w = rect->width();
  624. h = rect->height();
  625. // No split necessary?
  626. if (((w*h) < SubRectMaxArea) && (w < SubRectMaxWidth)) {
  627. writeSubRect(*rect, pb);
  628. continue;
  629. }
  630. if (w <= SubRectMaxWidth)
  631. sw = w;
  632. else
  633. sw = SubRectMaxWidth;
  634. sh = SubRectMaxArea / sw;
  635. for (sr.tl.y = rect->tl.y; sr.tl.y < rect->br.y; sr.tl.y += sh) {
  636. sr.br.y = sr.tl.y + sh;
  637. if (sr.br.y > rect->br.y)
  638. sr.br.y = rect->br.y;
  639. for (sr.tl.x = rect->tl.x; sr.tl.x < rect->br.x; sr.tl.x += sw) {
  640. sr.br.x = sr.tl.x + sw;
  641. if (sr.br.x > rect->br.x)
  642. sr.br.x = rect->br.x;
  643. writeSubRect(sr, pb);
  644. }
  645. }
  646. }
  647. }
  648. void EncodeManager::writeSubRect(const Rect& rect, const PixelBuffer *pb)
  649. {
  650. PixelBuffer *ppb;
  651. Encoder *encoder;
  652. struct RectInfo info;
  653. unsigned int divisor, maxColours;
  654. bool useRLE;
  655. EncoderType type;
  656. // FIXME: This is roughly the algorithm previously used by the Tight
  657. // encoder. It seems a bit backwards though, that higher
  658. // compression setting means spending less effort in building
  659. // a palette. It might be that they figured the increase in
  660. // zlib setting compensated for the loss.
  661. if (conn->client.compressLevel == -1)
  662. divisor = 2 * 8;
  663. else
  664. divisor = conn->client.compressLevel * 8;
  665. if (divisor < 4)
  666. divisor = 4;
  667. maxColours = rect.area()/divisor;
  668. // Special exception inherited from the Tight encoder
  669. if (activeEncoders[encoderFullColour] == encoderTightJPEG) {
  670. if ((conn->client.compressLevel != -1) && (conn->client.compressLevel < 2))
  671. maxColours = 24;
  672. else
  673. maxColours = 96;
  674. }
  675. if (maxColours < 2)
  676. maxColours = 2;
  677. encoder = encoders[activeEncoders[encoderIndexedRLE]];
  678. if (maxColours > encoder->maxPaletteSize)
  679. maxColours = encoder->maxPaletteSize;
  680. encoder = encoders[activeEncoders[encoderIndexed]];
  681. if (maxColours > encoder->maxPaletteSize)
  682. maxColours = encoder->maxPaletteSize;
  683. ppb = preparePixelBuffer(rect, pb, true);
  684. if (!analyseRect(ppb, &info, maxColours))
  685. info.palette.clear();
  686. // Different encoders might have different RLE overhead, but
  687. // here we do a guess at RLE being the better choice if reduces
  688. // the pixel count by 50%.
  689. useRLE = info.rleRuns <= (rect.area() * 2);
  690. switch (info.palette.size()) {
  691. case 0:
  692. type = encoderFullColour;
  693. break;
  694. case 1:
  695. type = encoderSolid;
  696. break;
  697. case 2:
  698. if (useRLE)
  699. type = encoderBitmapRLE;
  700. else
  701. type = encoderBitmap;
  702. break;
  703. default:
  704. if (useRLE)
  705. type = encoderIndexedRLE;
  706. else
  707. type = encoderIndexed;
  708. }
  709. encoder = startRect(rect, type);
  710. if (encoder->flags & EncoderUseNativePF)
  711. ppb = preparePixelBuffer(rect, pb, false);
  712. encoder->writeRect(ppb, info.palette);
  713. endRect();
  714. }
  715. bool EncodeManager::checkSolidTile(const Rect& r, const rdr::U8* colourValue,
  716. const PixelBuffer *pb)
  717. {
  718. switch (pb->getPF().bpp) {
  719. case 32:
  720. return checkSolidTile(r, *(const rdr::U32*)colourValue, pb);
  721. case 16:
  722. return checkSolidTile(r, *(const rdr::U16*)colourValue, pb);
  723. default:
  724. return checkSolidTile(r, *(const rdr::U8*)colourValue, pb);
  725. }
  726. }
  727. void EncodeManager::extendSolidAreaByBlock(const Rect& r,
  728. const rdr::U8* colourValue,
  729. const PixelBuffer *pb, Rect* er)
  730. {
  731. int dx, dy, dw, dh;
  732. int w_prev;
  733. Rect sr;
  734. int w_best = 0, h_best = 0;
  735. w_prev = r.width();
  736. // We search width first, back off when we hit a different colour,
  737. // and restart with a larger height. We keep track of the
  738. // width/height combination that gives us the largest area.
  739. for (dy = r.tl.y; dy < r.br.y; dy += SolidSearchBlock) {
  740. dh = SolidSearchBlock;
  741. if (dy + dh > r.br.y)
  742. dh = r.br.y - dy;
  743. // We test one block here outside the x loop in order to break
  744. // the y loop right away.
  745. dw = SolidSearchBlock;
  746. if (dw > w_prev)
  747. dw = w_prev;
  748. sr.setXYWH(r.tl.x, dy, dw, dh);
  749. if (!checkSolidTile(sr, colourValue, pb))
  750. break;
  751. for (dx = r.tl.x + dw; dx < r.tl.x + w_prev;) {
  752. dw = SolidSearchBlock;
  753. if (dx + dw > r.tl.x + w_prev)
  754. dw = r.tl.x + w_prev - dx;
  755. sr.setXYWH(dx, dy, dw, dh);
  756. if (!checkSolidTile(sr, colourValue, pb))
  757. break;
  758. dx += dw;
  759. }
  760. w_prev = dx - r.tl.x;
  761. if (w_prev * (dy + dh - r.tl.y) > w_best * h_best) {
  762. w_best = w_prev;
  763. h_best = dy + dh - r.tl.y;
  764. }
  765. }
  766. er->tl.x = r.tl.x;
  767. er->tl.y = r.tl.y;
  768. er->br.x = er->tl.x + w_best;
  769. er->br.y = er->tl.y + h_best;
  770. }
  771. void EncodeManager::extendSolidAreaByPixel(const Rect& r, const Rect& sr,
  772. const rdr::U8* colourValue,
  773. const PixelBuffer *pb, Rect* er)
  774. {
  775. int cx, cy;
  776. Rect tr;
  777. // Try to extend the area upwards.
  778. for (cy = sr.tl.y - 1; cy >= r.tl.y; cy--) {
  779. tr.setXYWH(sr.tl.x, cy, sr.width(), 1);
  780. if (!checkSolidTile(tr, colourValue, pb))
  781. break;
  782. }
  783. er->tl.y = cy + 1;
  784. // ... downwards.
  785. for (cy = sr.br.y; cy < r.br.y; cy++) {
  786. tr.setXYWH(sr.tl.x, cy, sr.width(), 1);
  787. if (!checkSolidTile(tr, colourValue, pb))
  788. break;
  789. }
  790. er->br.y = cy;
  791. // ... to the left.
  792. for (cx = sr.tl.x - 1; cx >= r.tl.x; cx--) {
  793. tr.setXYWH(cx, er->tl.y, 1, er->height());
  794. if (!checkSolidTile(tr, colourValue, pb))
  795. break;
  796. }
  797. er->tl.x = cx + 1;
  798. // ... to the right.
  799. for (cx = sr.br.x; cx < r.br.x; cx++) {
  800. tr.setXYWH(cx, er->tl.y, 1, er->height());
  801. if (!checkSolidTile(tr, colourValue, pb))
  802. break;
  803. }
  804. er->br.x = cx;
  805. }
  806. PixelBuffer* EncodeManager::preparePixelBuffer(const Rect& rect,
  807. const PixelBuffer *pb,
  808. bool convert)
  809. {
  810. const rdr::U8* buffer;
  811. int stride;
  812. // Do wo need to convert the data?
  813. if (convert && !conn->client.pf().equal(pb->getPF())) {
  814. convertedPixelBuffer.setPF(conn->client.pf());
  815. convertedPixelBuffer.setSize(rect.width(), rect.height());
  816. buffer = pb->getBuffer(rect, &stride);
  817. convertedPixelBuffer.imageRect(pb->getPF(),
  818. convertedPixelBuffer.getRect(),
  819. buffer, stride);
  820. return &convertedPixelBuffer;
  821. }
  822. // Otherwise we still need to shift the coordinates. We have our own
  823. // abusive subclass of FullFramePixelBuffer for this.
  824. buffer = pb->getBuffer(rect, &stride);
  825. offsetPixelBuffer.update(pb->getPF(), rect.width(), rect.height(),
  826. buffer, stride);
  827. return &offsetPixelBuffer;
  828. }
  829. bool EncodeManager::analyseRect(const PixelBuffer *pb,
  830. struct RectInfo *info, int maxColours)
  831. {
  832. const rdr::U8* buffer;
  833. int stride;
  834. buffer = pb->getBuffer(pb->getRect(), &stride);
  835. switch (pb->getPF().bpp) {
  836. case 32:
  837. return analyseRect(pb->width(), pb->height(),
  838. (const rdr::U32*)buffer, stride,
  839. info, maxColours);
  840. case 16:
  841. return analyseRect(pb->width(), pb->height(),
  842. (const rdr::U16*)buffer, stride,
  843. info, maxColours);
  844. default:
  845. return analyseRect(pb->width(), pb->height(),
  846. (const rdr::U8*)buffer, stride,
  847. info, maxColours);
  848. }
  849. }
  850. void EncodeManager::OffsetPixelBuffer::update(const PixelFormat& pf,
  851. int width, int height,
  852. const rdr::U8* data_,
  853. int stride_)
  854. {
  855. format = pf;
  856. // Forced cast. We never write anything though, so it should be safe.
  857. setBuffer(width, height, (rdr::U8*)data_, stride_);
  858. }
  859. rdr::U8* EncodeManager::OffsetPixelBuffer::getBufferRW(const Rect& /*r*/, int* /*stride*/)
  860. {
  861. throw rfb::Exception("Invalid write attempt to OffsetPixelBuffer");
  862. }
  863. // Preprocessor generated, optimised methods
  864. #define BPP 8
  865. #include "EncodeManagerBPP.cxx"
  866. #undef BPP
  867. #define BPP 16
  868. #include "EncodeManagerBPP.cxx"
  869. #undef BPP
  870. #define BPP 32
  871. #include "EncodeManagerBPP.cxx"
  872. #undef BPP