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

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