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 30KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  1. /* Copyright (C) 2000-2003 Constantin Kaplinsky. All Rights Reserved.
  2. * Copyright (C) 2011 D. R. Commander. All Rights Reserved.
  3. * Copyright 2014-2022 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. rects = 0;
  152. pixels = bytes = equivalent = 0;
  153. vlog.info("Framebuffer updates: %u", updates);
  154. if (copyStats.rects != 0) {
  155. vlog.info(" %s:", "CopyRect");
  156. rects += copyStats.rects;
  157. pixels += copyStats.pixels;
  158. bytes += copyStats.bytes;
  159. equivalent += copyStats.equivalent;
  160. ratio = (double)copyStats.equivalent / copyStats.bytes;
  161. vlog.info(" %s: %s, %s", "Copies",
  162. siPrefix(copyStats.rects, "rects").c_str(),
  163. siPrefix(copyStats.pixels, "pixels").c_str());
  164. vlog.info(" %*s %s (1:%g ratio)",
  165. (int)strlen("Copies"), "",
  166. iecPrefix(copyStats.bytes, "B").c_str(), ratio);
  167. }
  168. for (i = 0;i < stats.size();i++) {
  169. // Did this class do anything at all?
  170. for (j = 0;j < stats[i].size();j++) {
  171. if (stats[i][j].rects != 0)
  172. break;
  173. }
  174. if (j == stats[i].size())
  175. continue;
  176. vlog.info(" %s:", encoderClassName((EncoderClass)i));
  177. for (j = 0;j < stats[i].size();j++) {
  178. if (stats[i][j].rects == 0)
  179. continue;
  180. rects += stats[i][j].rects;
  181. pixels += stats[i][j].pixels;
  182. bytes += stats[i][j].bytes;
  183. equivalent += stats[i][j].equivalent;
  184. ratio = (double)stats[i][j].equivalent / stats[i][j].bytes;
  185. vlog.info(" %s: %s, %s", encoderTypeName((EncoderType)j),
  186. siPrefix(stats[i][j].rects, "rects").c_str(),
  187. siPrefix(stats[i][j].pixels, "pixels").c_str());
  188. vlog.info(" %*s %s (1:%g ratio)",
  189. (int)strlen(encoderTypeName((EncoderType)j)), "",
  190. iecPrefix(stats[i][j].bytes, "B").c_str(), ratio);
  191. }
  192. }
  193. ratio = (double)equivalent / bytes;
  194. vlog.info(" Total: %s, %s",
  195. siPrefix(rects, "rects").c_str(),
  196. siPrefix(pixels, "pixels").c_str());
  197. vlog.info(" %s (1:%g ratio)",
  198. iecPrefix(bytes, "B").c_str(), 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 = 0;
  284. if (conn->client.supportsEncoding(encodingCopyRect))
  285. nRects += copied.numRects();
  286. nRects += computeNumRects(changed);
  287. nRects += computeNumRects(cursorRegion);
  288. }
  289. conn->writer()->writeFramebufferUpdateStart(nRects);
  290. if (conn->client.supportsEncoding(encodingCopyRect))
  291. writeCopyRects(copied, copyDelta);
  292. /*
  293. * We start by searching for solid rects, which are then removed
  294. * from the changed region.
  295. */
  296. if (conn->client.supportsEncoding(pseudoEncodingLastRect))
  297. writeSolidRects(&changed, pb);
  298. writeRects(changed, pb);
  299. writeRects(cursorRegion, renderedCursor);
  300. conn->writer()->writeFramebufferUpdateEnd();
  301. }
  302. void EncodeManager::prepareEncoders(bool allowLossy)
  303. {
  304. enum EncoderClass solid, bitmap, bitmapRLE;
  305. enum EncoderClass indexed, indexedRLE, fullColour;
  306. bool allowJPEG;
  307. int32_t preferred;
  308. std::vector<int>::iterator iter;
  309. solid = bitmap = bitmapRLE = encoderRaw;
  310. indexed = indexedRLE = fullColour = encoderRaw;
  311. allowJPEG = conn->client.pf().bpp >= 16;
  312. if (!allowLossy) {
  313. if (encoders[encoderTightJPEG]->losslessQuality == -1)
  314. allowJPEG = false;
  315. }
  316. // Try to respect the client's wishes
  317. preferred = conn->getPreferredEncoding();
  318. switch (preferred) {
  319. case encodingRRE:
  320. // Horrible for anything high frequency and/or lots of colours
  321. bitmapRLE = indexedRLE = encoderRRE;
  322. break;
  323. case encodingHextile:
  324. // Slightly less horrible
  325. bitmapRLE = indexedRLE = fullColour = encoderHextile;
  326. break;
  327. case encodingTight:
  328. if (encoders[encoderTightJPEG]->isSupported() && allowJPEG)
  329. fullColour = encoderTightJPEG;
  330. else
  331. fullColour = encoderTight;
  332. indexed = indexedRLE = encoderTight;
  333. bitmap = bitmapRLE = encoderTight;
  334. break;
  335. case encodingZRLE:
  336. fullColour = encoderZRLE;
  337. bitmapRLE = indexedRLE = encoderZRLE;
  338. bitmap = indexed = encoderZRLE;
  339. break;
  340. }
  341. // Any encoders still unassigned?
  342. if (fullColour == encoderRaw) {
  343. if (encoders[encoderTightJPEG]->isSupported() && allowJPEG)
  344. fullColour = encoderTightJPEG;
  345. else if (encoders[encoderZRLE]->isSupported())
  346. fullColour = encoderZRLE;
  347. else if (encoders[encoderTight]->isSupported())
  348. fullColour = encoderTight;
  349. else if (encoders[encoderHextile]->isSupported())
  350. fullColour = encoderHextile;
  351. }
  352. if (indexed == encoderRaw) {
  353. if (encoders[encoderZRLE]->isSupported())
  354. indexed = encoderZRLE;
  355. else if (encoders[encoderTight]->isSupported())
  356. indexed = encoderTight;
  357. else if (encoders[encoderHextile]->isSupported())
  358. indexed = encoderHextile;
  359. }
  360. if (indexedRLE == encoderRaw)
  361. indexedRLE = indexed;
  362. if (bitmap == encoderRaw)
  363. bitmap = indexed;
  364. if (bitmapRLE == encoderRaw)
  365. bitmapRLE = bitmap;
  366. if (solid == encoderRaw) {
  367. if (encoders[encoderTight]->isSupported())
  368. solid = encoderTight;
  369. else if (encoders[encoderRRE]->isSupported())
  370. solid = encoderRRE;
  371. else if (encoders[encoderZRLE]->isSupported())
  372. solid = encoderZRLE;
  373. else if (encoders[encoderHextile]->isSupported())
  374. solid = encoderHextile;
  375. }
  376. // JPEG is the only encoder that can reduce things to grayscale
  377. if ((conn->client.subsampling == subsampleGray) &&
  378. encoders[encoderTightJPEG]->isSupported() && allowLossy) {
  379. solid = bitmap = bitmapRLE = encoderTightJPEG;
  380. indexed = indexedRLE = fullColour = encoderTightJPEG;
  381. }
  382. activeEncoders[encoderSolid] = solid;
  383. activeEncoders[encoderBitmap] = bitmap;
  384. activeEncoders[encoderBitmapRLE] = bitmapRLE;
  385. activeEncoders[encoderIndexed] = indexed;
  386. activeEncoders[encoderIndexedRLE] = indexedRLE;
  387. activeEncoders[encoderFullColour] = fullColour;
  388. for (iter = activeEncoders.begin(); iter != activeEncoders.end(); ++iter) {
  389. Encoder *encoder;
  390. encoder = encoders[*iter];
  391. encoder->setCompressLevel(conn->client.compressLevel);
  392. if (allowLossy) {
  393. encoder->setQualityLevel(conn->client.qualityLevel);
  394. encoder->setFineQualityLevel(conn->client.fineQualityLevel,
  395. conn->client.subsampling);
  396. } else {
  397. int level = __rfbmax(conn->client.qualityLevel,
  398. encoder->losslessQuality);
  399. encoder->setQualityLevel(level);
  400. encoder->setFineQualityLevel(-1, subsampleUndefined);
  401. }
  402. }
  403. }
  404. Region EncodeManager::getLosslessRefresh(const Region& req,
  405. size_t maxUpdateSize)
  406. {
  407. std::vector<Rect> rects;
  408. Region refresh;
  409. size_t area;
  410. // We make a conservative guess at the compression ratio at 2:1
  411. maxUpdateSize *= 2;
  412. // We will measure pixels, not bytes (assume 32 bpp)
  413. maxUpdateSize /= 4;
  414. area = 0;
  415. pendingRefreshRegion.intersect(req).get_rects(&rects);
  416. while (!rects.empty()) {
  417. size_t idx;
  418. Rect rect;
  419. // Grab a random rect so we don't keep damaging and restoring the
  420. // same rect over and over
  421. idx = rand() % rects.size();
  422. rect = rects[idx];
  423. // Add rects until we exceed the threshold, then include as much as
  424. // possible of the final rect
  425. if ((area + rect.area()) > maxUpdateSize) {
  426. // Use the narrowest axis to avoid getting to thin rects
  427. if (rect.width() > rect.height()) {
  428. int width = (maxUpdateSize - area) / rect.height();
  429. rect.br.x = rect.tl.x + __rfbmax(1, width);
  430. } else {
  431. int height = (maxUpdateSize - area) / rect.width();
  432. rect.br.y = rect.tl.y + __rfbmax(1, height);
  433. }
  434. refresh.assign_union(Region(rect));
  435. break;
  436. }
  437. area += rect.area();
  438. refresh.assign_union(Region(rect));
  439. rects.erase(rects.begin() + idx);
  440. }
  441. return refresh;
  442. }
  443. int EncodeManager::computeNumRects(const Region& changed)
  444. {
  445. int numRects;
  446. std::vector<Rect> rects;
  447. std::vector<Rect>::const_iterator rect;
  448. numRects = 0;
  449. changed.get_rects(&rects);
  450. for (rect = rects.begin(); rect != rects.end(); ++rect) {
  451. int w, h, sw, sh;
  452. w = rect->width();
  453. h = rect->height();
  454. // No split necessary?
  455. if (((w*h) < SubRectMaxArea) && (w < SubRectMaxWidth)) {
  456. numRects += 1;
  457. continue;
  458. }
  459. if (w <= SubRectMaxWidth)
  460. sw = w;
  461. else
  462. sw = SubRectMaxWidth;
  463. sh = SubRectMaxArea / sw;
  464. // ceil(w/sw) * ceil(h/sh)
  465. numRects += (((w - 1)/sw) + 1) * (((h - 1)/sh) + 1);
  466. }
  467. return numRects;
  468. }
  469. Encoder *EncodeManager::startRect(const Rect& rect, int type)
  470. {
  471. Encoder *encoder;
  472. int klass, equiv;
  473. activeType = type;
  474. klass = activeEncoders[activeType];
  475. beforeLength = conn->getOutStream()->length();
  476. stats[klass][activeType].rects++;
  477. stats[klass][activeType].pixels += rect.area();
  478. equiv = 12 + rect.area() * (conn->client.pf().bpp/8);
  479. stats[klass][activeType].equivalent += equiv;
  480. encoder = encoders[klass];
  481. conn->writer()->startRect(rect, encoder->encoding);
  482. if ((encoder->flags & EncoderLossy) &&
  483. ((encoder->losslessQuality == -1) ||
  484. (encoder->getQualityLevel() < encoder->losslessQuality)))
  485. lossyRegion.assign_union(Region(rect));
  486. else
  487. lossyRegion.assign_subtract(Region(rect));
  488. // This was either a rect getting refreshed, or a rect that just got
  489. // new content. Either way we should not try to refresh it anymore.
  490. pendingRefreshRegion.assign_subtract(Region(rect));
  491. return encoder;
  492. }
  493. void EncodeManager::endRect()
  494. {
  495. int klass;
  496. int length;
  497. conn->writer()->endRect();
  498. length = conn->getOutStream()->length() - beforeLength;
  499. klass = activeEncoders[activeType];
  500. stats[klass][activeType].bytes += length;
  501. }
  502. void EncodeManager::writeCopyRects(const Region& copied, const Point& delta)
  503. {
  504. std::vector<Rect> rects;
  505. std::vector<Rect>::const_iterator rect;
  506. Region lossyCopy;
  507. beforeLength = conn->getOutStream()->length();
  508. copied.get_rects(&rects, delta.x <= 0, delta.y <= 0);
  509. for (rect = rects.begin(); rect != rects.end(); ++rect) {
  510. int equiv;
  511. copyStats.rects++;
  512. copyStats.pixels += rect->area();
  513. equiv = 12 + rect->area() * (conn->client.pf().bpp/8);
  514. copyStats.equivalent += equiv;
  515. conn->writer()->writeCopyRect(*rect, rect->tl.x - delta.x,
  516. rect->tl.y - delta.y);
  517. }
  518. copyStats.bytes += conn->getOutStream()->length() - beforeLength;
  519. lossyCopy = lossyRegion;
  520. lossyCopy.translate(delta);
  521. lossyCopy.assign_intersect(copied);
  522. lossyRegion.assign_union(lossyCopy);
  523. // Stop any pending refresh as a copy is enough that we consider
  524. // this region to be recently changed
  525. pendingRefreshRegion.assign_subtract(copied);
  526. }
  527. void EncodeManager::writeSolidRects(Region *changed, const PixelBuffer* pb)
  528. {
  529. std::vector<Rect> rects;
  530. std::vector<Rect>::const_iterator rect;
  531. changed->get_rects(&rects);
  532. for (rect = rects.begin(); rect != rects.end(); ++rect)
  533. findSolidRect(*rect, changed, pb);
  534. }
  535. void EncodeManager::findSolidRect(const Rect& rect, Region *changed,
  536. const PixelBuffer* pb)
  537. {
  538. Rect sr;
  539. int dx, dy, dw, dh;
  540. // We start by finding a solid 16x16 block
  541. for (dy = rect.tl.y; dy < rect.br.y; dy += SolidSearchBlock) {
  542. dh = SolidSearchBlock;
  543. if (dy + dh > rect.br.y)
  544. dh = rect.br.y - dy;
  545. for (dx = rect.tl.x; dx < rect.br.x; dx += SolidSearchBlock) {
  546. // We define it like this to guarantee alignment
  547. uint32_t _buffer;
  548. uint8_t* colourValue = (uint8_t*)&_buffer;
  549. dw = SolidSearchBlock;
  550. if (dx + dw > rect.br.x)
  551. dw = rect.br.x - dx;
  552. pb->getImage(colourValue, Rect(dx, dy, dx+1, dy+1));
  553. sr.setXYWH(dx, dy, dw, dh);
  554. if (checkSolidTile(sr, colourValue, pb)) {
  555. Rect erb, erp;
  556. Encoder *encoder;
  557. // We then try extending the area by adding more blocks
  558. // in both directions and pick the combination that gives
  559. // the largest area.
  560. sr.setXYWH(dx, dy, rect.br.x - dx, rect.br.y - dy);
  561. extendSolidAreaByBlock(sr, colourValue, pb, &erb);
  562. // Did we end up getting the entire rectangle?
  563. if (erb.equals(rect))
  564. erp = erb;
  565. else {
  566. // Don't bother with sending tiny rectangles
  567. if (erb.area() < SolidBlockMinArea)
  568. continue;
  569. // Extend the area again, but this time one pixel
  570. // row/column at a time.
  571. extendSolidAreaByPixel(rect, erb, colourValue, pb, &erp);
  572. }
  573. // Send solid-color rectangle.
  574. encoder = startRect(erp, encoderSolid);
  575. if (encoder->flags & EncoderUseNativePF) {
  576. encoder->writeSolidRect(erp.width(), erp.height(),
  577. pb->getPF(), colourValue);
  578. } else {
  579. uint32_t _buffer2;
  580. uint8_t* converted = (uint8_t*)&_buffer2;
  581. conn->client.pf().bufferFromBuffer(converted, pb->getPF(),
  582. colourValue, 1);
  583. encoder->writeSolidRect(erp.width(), erp.height(),
  584. conn->client.pf(), converted);
  585. }
  586. endRect();
  587. changed->assign_subtract(Region(erp));
  588. // Search remaining areas by recursion
  589. // FIXME: Is this the best way to divide things up?
  590. // Left? (Note that we've already searched a SolidSearchBlock
  591. // pixels high strip here)
  592. if ((erp.tl.x != rect.tl.x) && (erp.height() > SolidSearchBlock)) {
  593. sr.setXYWH(rect.tl.x, erp.tl.y + SolidSearchBlock,
  594. erp.tl.x - rect.tl.x, erp.height() - SolidSearchBlock);
  595. findSolidRect(sr, changed, pb);
  596. }
  597. // Right?
  598. if (erp.br.x != rect.br.x) {
  599. sr.setXYWH(erp.br.x, erp.tl.y, rect.br.x - erp.br.x, erp.height());
  600. findSolidRect(sr, changed, pb);
  601. }
  602. // Below?
  603. if (erp.br.y != rect.br.y) {
  604. sr.setXYWH(rect.tl.x, erp.br.y, rect.width(), rect.br.y - erp.br.y);
  605. findSolidRect(sr, changed, pb);
  606. }
  607. return;
  608. }
  609. }
  610. }
  611. }
  612. void EncodeManager::writeRects(const Region& changed, const PixelBuffer* pb)
  613. {
  614. std::vector<Rect> rects;
  615. std::vector<Rect>::const_iterator rect;
  616. changed.get_rects(&rects);
  617. for (rect = rects.begin(); rect != rects.end(); ++rect) {
  618. int w, h, sw, sh;
  619. Rect sr;
  620. w = rect->width();
  621. h = rect->height();
  622. // No split necessary?
  623. if (((w*h) < SubRectMaxArea) && (w < SubRectMaxWidth)) {
  624. writeSubRect(*rect, pb);
  625. continue;
  626. }
  627. if (w <= SubRectMaxWidth)
  628. sw = w;
  629. else
  630. sw = SubRectMaxWidth;
  631. sh = SubRectMaxArea / sw;
  632. for (sr.tl.y = rect->tl.y; sr.tl.y < rect->br.y; sr.tl.y += sh) {
  633. sr.br.y = sr.tl.y + sh;
  634. if (sr.br.y > rect->br.y)
  635. sr.br.y = rect->br.y;
  636. for (sr.tl.x = rect->tl.x; sr.tl.x < rect->br.x; sr.tl.x += sw) {
  637. sr.br.x = sr.tl.x + sw;
  638. if (sr.br.x > rect->br.x)
  639. sr.br.x = rect->br.x;
  640. writeSubRect(sr, pb);
  641. }
  642. }
  643. }
  644. }
  645. void EncodeManager::writeSubRect(const Rect& rect, const PixelBuffer *pb)
  646. {
  647. PixelBuffer *ppb;
  648. Encoder *encoder;
  649. struct RectInfo info;
  650. unsigned int divisor, maxColours;
  651. bool useRLE;
  652. EncoderType type;
  653. // FIXME: This is roughly the algorithm previously used by the Tight
  654. // encoder. It seems a bit backwards though, that higher
  655. // compression setting means spending less effort in building
  656. // a palette. It might be that they figured the increase in
  657. // zlib setting compensated for the loss.
  658. if (conn->client.compressLevel == -1)
  659. divisor = 2 * 8;
  660. else
  661. divisor = conn->client.compressLevel * 8;
  662. if (divisor < 4)
  663. divisor = 4;
  664. maxColours = rect.area()/divisor;
  665. // Special exception inherited from the Tight encoder
  666. if (activeEncoders[encoderFullColour] == encoderTightJPEG) {
  667. if ((conn->client.compressLevel != -1) && (conn->client.compressLevel < 2))
  668. maxColours = 24;
  669. else
  670. maxColours = 96;
  671. }
  672. if (maxColours < 2)
  673. maxColours = 2;
  674. encoder = encoders[activeEncoders[encoderIndexedRLE]];
  675. if (maxColours > encoder->maxPaletteSize)
  676. maxColours = encoder->maxPaletteSize;
  677. encoder = encoders[activeEncoders[encoderIndexed]];
  678. if (maxColours > encoder->maxPaletteSize)
  679. maxColours = encoder->maxPaletteSize;
  680. ppb = preparePixelBuffer(rect, pb, true);
  681. if (!analyseRect(ppb, &info, maxColours))
  682. info.palette.clear();
  683. // Different encoders might have different RLE overhead, but
  684. // here we do a guess at RLE being the better choice if reduces
  685. // the pixel count by 50%.
  686. useRLE = info.rleRuns <= (rect.area() * 2);
  687. switch (info.palette.size()) {
  688. case 0:
  689. type = encoderFullColour;
  690. break;
  691. case 1:
  692. type = encoderSolid;
  693. break;
  694. case 2:
  695. if (useRLE)
  696. type = encoderBitmapRLE;
  697. else
  698. type = encoderBitmap;
  699. break;
  700. default:
  701. if (useRLE)
  702. type = encoderIndexedRLE;
  703. else
  704. type = encoderIndexed;
  705. }
  706. encoder = startRect(rect, type);
  707. if (encoder->flags & EncoderUseNativePF)
  708. ppb = preparePixelBuffer(rect, pb, false);
  709. encoder->writeRect(ppb, info.palette);
  710. endRect();
  711. }
  712. bool EncodeManager::checkSolidTile(const Rect& r, const uint8_t* colourValue,
  713. const PixelBuffer *pb)
  714. {
  715. switch (pb->getPF().bpp) {
  716. case 32:
  717. return checkSolidTile(r, *(const uint32_t*)colourValue, pb);
  718. case 16:
  719. return checkSolidTile(r, *(const uint16_t*)colourValue, pb);
  720. default:
  721. return checkSolidTile(r, *(const uint8_t*)colourValue, pb);
  722. }
  723. }
  724. void EncodeManager::extendSolidAreaByBlock(const Rect& r,
  725. const uint8_t* colourValue,
  726. const PixelBuffer *pb, Rect* er)
  727. {
  728. int dx, dy, dw, dh;
  729. int w_prev;
  730. Rect sr;
  731. int w_best = 0, h_best = 0;
  732. w_prev = r.width();
  733. // We search width first, back off when we hit a different colour,
  734. // and restart with a larger height. We keep track of the
  735. // width/height combination that gives us the largest area.
  736. for (dy = r.tl.y; dy < r.br.y; dy += SolidSearchBlock) {
  737. dh = SolidSearchBlock;
  738. if (dy + dh > r.br.y)
  739. dh = r.br.y - dy;
  740. // We test one block here outside the x loop in order to break
  741. // the y loop right away.
  742. dw = SolidSearchBlock;
  743. if (dw > w_prev)
  744. dw = w_prev;
  745. sr.setXYWH(r.tl.x, dy, dw, dh);
  746. if (!checkSolidTile(sr, colourValue, pb))
  747. break;
  748. for (dx = r.tl.x + dw; dx < r.tl.x + w_prev;) {
  749. dw = SolidSearchBlock;
  750. if (dx + dw > r.tl.x + w_prev)
  751. dw = r.tl.x + w_prev - dx;
  752. sr.setXYWH(dx, dy, dw, dh);
  753. if (!checkSolidTile(sr, colourValue, pb))
  754. break;
  755. dx += dw;
  756. }
  757. w_prev = dx - r.tl.x;
  758. if (w_prev * (dy + dh - r.tl.y) > w_best * h_best) {
  759. w_best = w_prev;
  760. h_best = dy + dh - r.tl.y;
  761. }
  762. }
  763. er->tl.x = r.tl.x;
  764. er->tl.y = r.tl.y;
  765. er->br.x = er->tl.x + w_best;
  766. er->br.y = er->tl.y + h_best;
  767. }
  768. void EncodeManager::extendSolidAreaByPixel(const Rect& r, const Rect& sr,
  769. const uint8_t* colourValue,
  770. const PixelBuffer *pb, Rect* er)
  771. {
  772. int cx, cy;
  773. Rect tr;
  774. // Try to extend the area upwards.
  775. for (cy = sr.tl.y - 1; cy >= r.tl.y; cy--) {
  776. tr.setXYWH(sr.tl.x, cy, sr.width(), 1);
  777. if (!checkSolidTile(tr, colourValue, pb))
  778. break;
  779. }
  780. er->tl.y = cy + 1;
  781. // ... downwards.
  782. for (cy = sr.br.y; cy < r.br.y; cy++) {
  783. tr.setXYWH(sr.tl.x, cy, sr.width(), 1);
  784. if (!checkSolidTile(tr, colourValue, pb))
  785. break;
  786. }
  787. er->br.y = cy;
  788. // ... to the left.
  789. for (cx = sr.tl.x - 1; cx >= r.tl.x; cx--) {
  790. tr.setXYWH(cx, er->tl.y, 1, er->height());
  791. if (!checkSolidTile(tr, colourValue, pb))
  792. break;
  793. }
  794. er->tl.x = cx + 1;
  795. // ... to the right.
  796. for (cx = sr.br.x; cx < r.br.x; cx++) {
  797. tr.setXYWH(cx, er->tl.y, 1, er->height());
  798. if (!checkSolidTile(tr, colourValue, pb))
  799. break;
  800. }
  801. er->br.x = cx;
  802. }
  803. PixelBuffer* EncodeManager::preparePixelBuffer(const Rect& rect,
  804. const PixelBuffer *pb,
  805. bool convert)
  806. {
  807. const uint8_t* buffer;
  808. int stride;
  809. // Do wo need to convert the data?
  810. if (convert && !conn->client.pf().equal(pb->getPF())) {
  811. convertedPixelBuffer.setPF(conn->client.pf());
  812. convertedPixelBuffer.setSize(rect.width(), rect.height());
  813. buffer = pb->getBuffer(rect, &stride);
  814. convertedPixelBuffer.imageRect(pb->getPF(),
  815. convertedPixelBuffer.getRect(),
  816. buffer, stride);
  817. return &convertedPixelBuffer;
  818. }
  819. // Otherwise we still need to shift the coordinates. We have our own
  820. // abusive subclass of FullFramePixelBuffer for this.
  821. buffer = pb->getBuffer(rect, &stride);
  822. offsetPixelBuffer.update(pb->getPF(), rect.width(), rect.height(),
  823. buffer, stride);
  824. return &offsetPixelBuffer;
  825. }
  826. bool EncodeManager::analyseRect(const PixelBuffer *pb,
  827. struct RectInfo *info, int maxColours)
  828. {
  829. const uint8_t* buffer;
  830. int stride;
  831. buffer = pb->getBuffer(pb->getRect(), &stride);
  832. switch (pb->getPF().bpp) {
  833. case 32:
  834. return analyseRect(pb->width(), pb->height(),
  835. (const uint32_t*)buffer, stride,
  836. info, maxColours);
  837. case 16:
  838. return analyseRect(pb->width(), pb->height(),
  839. (const uint16_t*)buffer, stride,
  840. info, maxColours);
  841. default:
  842. return analyseRect(pb->width(), pb->height(),
  843. (const uint8_t*)buffer, stride,
  844. info, maxColours);
  845. }
  846. }
  847. void EncodeManager::OffsetPixelBuffer::update(const PixelFormat& pf,
  848. int width, int height,
  849. const uint8_t* data_,
  850. int stride_)
  851. {
  852. format = pf;
  853. // Forced cast. We never write anything though, so it should be safe.
  854. setBuffer(width, height, (uint8_t*)data_, stride_);
  855. }
  856. uint8_t* EncodeManager::OffsetPixelBuffer::getBufferRW(const Rect& /*r*/, int* /*stride*/)
  857. {
  858. throw rfb::Exception("Invalid write attempt to OffsetPixelBuffer");
  859. }
  860. template<class T>
  861. inline bool EncodeManager::checkSolidTile(const Rect& r,
  862. const T colourValue,
  863. const PixelBuffer *pb)
  864. {
  865. int w, h;
  866. const T* buffer;
  867. int stride, pad;
  868. w = r.width();
  869. h = r.height();
  870. buffer = (const T*)pb->getBuffer(r, &stride);
  871. pad = stride - w;
  872. while (h--) {
  873. int w_ = w;
  874. while (w_--) {
  875. if (*buffer != colourValue)
  876. return false;
  877. buffer++;
  878. }
  879. buffer += pad;
  880. }
  881. return true;
  882. }
  883. template<class T>
  884. inline bool EncodeManager::analyseRect(int width, int height,
  885. const T* buffer, int stride,
  886. struct RectInfo *info, int maxColours)
  887. {
  888. int pad;
  889. T colour;
  890. int count;
  891. info->rleRuns = 0;
  892. info->palette.clear();
  893. pad = stride - width;
  894. // For efficiency, we only update the palette on changes in colour
  895. colour = buffer[0];
  896. count = 0;
  897. while (height--) {
  898. int w_ = width;
  899. while (w_--) {
  900. if (*buffer != colour) {
  901. if (!info->palette.insert(colour, count))
  902. return false;
  903. if (info->palette.size() > maxColours)
  904. return false;
  905. // FIXME: This doesn't account for switching lines
  906. info->rleRuns++;
  907. colour = *buffer;
  908. count = 0;
  909. }
  910. buffer++;
  911. count++;
  912. }
  913. buffer += pad;
  914. }
  915. // Make sure the final pixels also get counted
  916. if (!info->palette.insert(colour, count))
  917. return false;
  918. if (info->palette.size() > maxColours)
  919. return false;
  920. return true;
  921. }