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

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