backward_references_hq.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. /* Copyright 2013 Google Inc. All Rights Reserved.
  2. Distributed under MIT license.
  3. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
  4. */
  5. /* Function to find backward reference copies. */
  6. #include "./backward_references_hq.h"
  7. #include <string.h> /* memcpy, memset */
  8. #include "../common/constants.h"
  9. #include "../common/platform.h"
  10. #include <brotli/types.h>
  11. #include "./command.h"
  12. #include "./fast_log.h"
  13. #include "./find_match_length.h"
  14. #include "./literal_cost.h"
  15. #include "./memory.h"
  16. #include "./params.h"
  17. #include "./prefix.h"
  18. #include "./quality.h"
  19. #if defined(__cplusplus) || defined(c_plusplus)
  20. extern "C" {
  21. #endif
  22. #define BROTLI_MAX_EFFECTIVE_DISTANCE_ALPHABET_SIZE 544
  23. static const float kInfinity = 1.7e38f; /* ~= 2 ^ 127 */
  24. static const uint32_t kDistanceCacheIndex[] = {
  25. 0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,
  26. };
  27. static const int kDistanceCacheOffset[] = {
  28. 0, 0, 0, 0, -1, 1, -2, 2, -3, 3, -1, 1, -2, 2, -3, 3
  29. };
  30. void BrotliInitZopfliNodes(ZopfliNode* array, size_t length) {
  31. ZopfliNode stub;
  32. size_t i;
  33. stub.length = 1;
  34. stub.distance = 0;
  35. stub.dcode_insert_length = 0;
  36. stub.u.cost = kInfinity;
  37. for (i = 0; i < length; ++i) array[i] = stub;
  38. }
  39. static BROTLI_INLINE uint32_t ZopfliNodeCopyLength(const ZopfliNode* self) {
  40. return self->length & 0x1FFFFFF;
  41. }
  42. static BROTLI_INLINE uint32_t ZopfliNodeLengthCode(const ZopfliNode* self) {
  43. const uint32_t modifier = self->length >> 25;
  44. return ZopfliNodeCopyLength(self) + 9u - modifier;
  45. }
  46. static BROTLI_INLINE uint32_t ZopfliNodeCopyDistance(const ZopfliNode* self) {
  47. return self->distance;
  48. }
  49. static BROTLI_INLINE uint32_t ZopfliNodeDistanceCode(const ZopfliNode* self) {
  50. const uint32_t short_code = self->dcode_insert_length >> 27;
  51. return short_code == 0 ?
  52. ZopfliNodeCopyDistance(self) + BROTLI_NUM_DISTANCE_SHORT_CODES - 1 :
  53. short_code - 1;
  54. }
  55. static BROTLI_INLINE uint32_t ZopfliNodeCommandLength(const ZopfliNode* self) {
  56. return ZopfliNodeCopyLength(self) + (self->dcode_insert_length & 0x7FFFFFF);
  57. }
  58. /* Histogram based cost model for zopflification. */
  59. typedef struct ZopfliCostModel {
  60. /* The insert and copy length symbols. */
  61. float cost_cmd_[BROTLI_NUM_COMMAND_SYMBOLS];
  62. float* cost_dist_;
  63. uint32_t distance_histogram_size;
  64. /* Cumulative costs of literals per position in the stream. */
  65. float* literal_costs_;
  66. float min_cost_cmd_;
  67. size_t num_bytes_;
  68. } ZopfliCostModel;
  69. static void InitZopfliCostModel(
  70. MemoryManager* m, ZopfliCostModel* self, const BrotliDistanceParams* dist,
  71. size_t num_bytes) {
  72. uint32_t distance_histogram_size = dist->alphabet_size;
  73. if (distance_histogram_size > BROTLI_MAX_EFFECTIVE_DISTANCE_ALPHABET_SIZE) {
  74. distance_histogram_size = BROTLI_MAX_EFFECTIVE_DISTANCE_ALPHABET_SIZE;
  75. }
  76. self->num_bytes_ = num_bytes;
  77. self->literal_costs_ = BROTLI_ALLOC(m, float, num_bytes + 2);
  78. self->cost_dist_ = BROTLI_ALLOC(m, float, dist->alphabet_size);
  79. self->distance_histogram_size = distance_histogram_size;
  80. if (BROTLI_IS_OOM(m)) return;
  81. }
  82. static void CleanupZopfliCostModel(MemoryManager* m, ZopfliCostModel* self) {
  83. BROTLI_FREE(m, self->literal_costs_);
  84. BROTLI_FREE(m, self->cost_dist_);
  85. }
  86. static void SetCost(const uint32_t* histogram, size_t histogram_size,
  87. BROTLI_BOOL literal_histogram, float* cost) {
  88. size_t sum = 0;
  89. size_t missing_symbol_sum;
  90. float log2sum;
  91. float missing_symbol_cost;
  92. size_t i;
  93. for (i = 0; i < histogram_size; i++) {
  94. sum += histogram[i];
  95. }
  96. log2sum = (float)FastLog2(sum);
  97. missing_symbol_sum = sum;
  98. if (!literal_histogram) {
  99. for (i = 0; i < histogram_size; i++) {
  100. if (histogram[i] == 0) missing_symbol_sum++;
  101. }
  102. }
  103. missing_symbol_cost = (float)FastLog2(missing_symbol_sum) + 2;
  104. for (i = 0; i < histogram_size; i++) {
  105. if (histogram[i] == 0) {
  106. cost[i] = missing_symbol_cost;
  107. continue;
  108. }
  109. /* Shannon bits for this symbol. */
  110. cost[i] = log2sum - (float)FastLog2(histogram[i]);
  111. /* Cannot be coded with less than 1 bit */
  112. if (cost[i] < 1) cost[i] = 1;
  113. }
  114. }
  115. static void ZopfliCostModelSetFromCommands(ZopfliCostModel* self,
  116. size_t position,
  117. const uint8_t* ringbuffer,
  118. size_t ringbuffer_mask,
  119. const Command* commands,
  120. size_t num_commands,
  121. size_t last_insert_len) {
  122. uint32_t histogram_literal[BROTLI_NUM_LITERAL_SYMBOLS];
  123. uint32_t histogram_cmd[BROTLI_NUM_COMMAND_SYMBOLS];
  124. uint32_t histogram_dist[BROTLI_MAX_EFFECTIVE_DISTANCE_ALPHABET_SIZE];
  125. float cost_literal[BROTLI_NUM_LITERAL_SYMBOLS];
  126. size_t pos = position - last_insert_len;
  127. float min_cost_cmd = kInfinity;
  128. size_t i;
  129. float* cost_cmd = self->cost_cmd_;
  130. memset(histogram_literal, 0, sizeof(histogram_literal));
  131. memset(histogram_cmd, 0, sizeof(histogram_cmd));
  132. memset(histogram_dist, 0, sizeof(histogram_dist));
  133. for (i = 0; i < num_commands; i++) {
  134. size_t inslength = commands[i].insert_len_;
  135. size_t copylength = CommandCopyLen(&commands[i]);
  136. size_t distcode = commands[i].dist_prefix_ & 0x3FF;
  137. size_t cmdcode = commands[i].cmd_prefix_;
  138. size_t j;
  139. histogram_cmd[cmdcode]++;
  140. if (cmdcode >= 128) histogram_dist[distcode]++;
  141. for (j = 0; j < inslength; j++) {
  142. histogram_literal[ringbuffer[(pos + j) & ringbuffer_mask]]++;
  143. }
  144. pos += inslength + copylength;
  145. }
  146. SetCost(histogram_literal, BROTLI_NUM_LITERAL_SYMBOLS, BROTLI_TRUE,
  147. cost_literal);
  148. SetCost(histogram_cmd, BROTLI_NUM_COMMAND_SYMBOLS, BROTLI_FALSE,
  149. cost_cmd);
  150. SetCost(histogram_dist, self->distance_histogram_size, BROTLI_FALSE,
  151. self->cost_dist_);
  152. for (i = 0; i < BROTLI_NUM_COMMAND_SYMBOLS; ++i) {
  153. min_cost_cmd = BROTLI_MIN(float, min_cost_cmd, cost_cmd[i]);
  154. }
  155. self->min_cost_cmd_ = min_cost_cmd;
  156. {
  157. float* literal_costs = self->literal_costs_;
  158. float literal_carry = 0.0;
  159. size_t num_bytes = self->num_bytes_;
  160. literal_costs[0] = 0.0;
  161. for (i = 0; i < num_bytes; ++i) {
  162. literal_carry +=
  163. cost_literal[ringbuffer[(position + i) & ringbuffer_mask]];
  164. literal_costs[i + 1] = literal_costs[i] + literal_carry;
  165. literal_carry -= literal_costs[i + 1] - literal_costs[i];
  166. }
  167. }
  168. }
  169. static void ZopfliCostModelSetFromLiteralCosts(ZopfliCostModel* self,
  170. size_t position,
  171. const uint8_t* ringbuffer,
  172. size_t ringbuffer_mask) {
  173. float* literal_costs = self->literal_costs_;
  174. float literal_carry = 0.0;
  175. float* cost_dist = self->cost_dist_;
  176. float* cost_cmd = self->cost_cmd_;
  177. size_t num_bytes = self->num_bytes_;
  178. size_t i;
  179. BrotliEstimateBitCostsForLiterals(position, num_bytes, ringbuffer_mask,
  180. ringbuffer, &literal_costs[1]);
  181. literal_costs[0] = 0.0;
  182. for (i = 0; i < num_bytes; ++i) {
  183. literal_carry += literal_costs[i + 1];
  184. literal_costs[i + 1] = literal_costs[i] + literal_carry;
  185. literal_carry -= literal_costs[i + 1] - literal_costs[i];
  186. }
  187. for (i = 0; i < BROTLI_NUM_COMMAND_SYMBOLS; ++i) {
  188. cost_cmd[i] = (float)FastLog2(11 + (uint32_t)i);
  189. }
  190. for (i = 0; i < self->distance_histogram_size; ++i) {
  191. cost_dist[i] = (float)FastLog2(20 + (uint32_t)i);
  192. }
  193. self->min_cost_cmd_ = (float)FastLog2(11);
  194. }
  195. static BROTLI_INLINE float ZopfliCostModelGetCommandCost(
  196. const ZopfliCostModel* self, uint16_t cmdcode) {
  197. return self->cost_cmd_[cmdcode];
  198. }
  199. static BROTLI_INLINE float ZopfliCostModelGetDistanceCost(
  200. const ZopfliCostModel* self, size_t distcode) {
  201. return self->cost_dist_[distcode];
  202. }
  203. static BROTLI_INLINE float ZopfliCostModelGetLiteralCosts(
  204. const ZopfliCostModel* self, size_t from, size_t to) {
  205. return self->literal_costs_[to] - self->literal_costs_[from];
  206. }
  207. static BROTLI_INLINE float ZopfliCostModelGetMinCostCmd(
  208. const ZopfliCostModel* self) {
  209. return self->min_cost_cmd_;
  210. }
  211. /* REQUIRES: len >= 2, start_pos <= pos */
  212. /* REQUIRES: cost < kInfinity, nodes[start_pos].cost < kInfinity */
  213. /* Maintains the "ZopfliNode array invariant". */
  214. static BROTLI_INLINE void UpdateZopfliNode(ZopfliNode* nodes, size_t pos,
  215. size_t start_pos, size_t len, size_t len_code, size_t dist,
  216. size_t short_code, float cost) {
  217. ZopfliNode* next = &nodes[pos + len];
  218. next->length = (uint32_t)(len | ((len + 9u - len_code) << 25));
  219. next->distance = (uint32_t)dist;
  220. next->dcode_insert_length = (uint32_t)(
  221. (short_code << 27) | (pos - start_pos));
  222. next->u.cost = cost;
  223. }
  224. typedef struct PosData {
  225. size_t pos;
  226. int distance_cache[4];
  227. float costdiff;
  228. float cost;
  229. } PosData;
  230. /* Maintains the smallest 8 cost difference together with their positions */
  231. typedef struct StartPosQueue {
  232. PosData q_[8];
  233. size_t idx_;
  234. } StartPosQueue;
  235. static BROTLI_INLINE void InitStartPosQueue(StartPosQueue* self) {
  236. self->idx_ = 0;
  237. }
  238. static size_t StartPosQueueSize(const StartPosQueue* self) {
  239. return BROTLI_MIN(size_t, self->idx_, 8);
  240. }
  241. static void StartPosQueuePush(StartPosQueue* self, const PosData* posdata) {
  242. size_t offset = ~(self->idx_++) & 7;
  243. size_t len = StartPosQueueSize(self);
  244. size_t i;
  245. PosData* q = self->q_;
  246. q[offset] = *posdata;
  247. /* Restore the sorted order. In the list of |len| items at most |len - 1|
  248. adjacent element comparisons / swaps are required. */
  249. for (i = 1; i < len; ++i) {
  250. if (q[offset & 7].costdiff > q[(offset + 1) & 7].costdiff) {
  251. BROTLI_SWAP(PosData, q, offset & 7, (offset + 1) & 7);
  252. }
  253. ++offset;
  254. }
  255. }
  256. static const PosData* StartPosQueueAt(const StartPosQueue* self, size_t k) {
  257. return &self->q_[(k - self->idx_) & 7];
  258. }
  259. /* Returns the minimum possible copy length that can improve the cost of any */
  260. /* future position. */
  261. static size_t ComputeMinimumCopyLength(const float start_cost,
  262. const ZopfliNode* nodes,
  263. const size_t num_bytes,
  264. const size_t pos) {
  265. /* Compute the minimum possible cost of reaching any future position. */
  266. float min_cost = start_cost;
  267. size_t len = 2;
  268. size_t next_len_bucket = 4;
  269. size_t next_len_offset = 10;
  270. while (pos + len <= num_bytes && nodes[pos + len].u.cost <= min_cost) {
  271. /* We already reached (pos + len) with no more cost than the minimum
  272. possible cost of reaching anything from this pos, so there is no point in
  273. looking for lengths <= len. */
  274. ++len;
  275. if (len == next_len_offset) {
  276. /* We reached the next copy length code bucket, so we add one more
  277. extra bit to the minimum cost. */
  278. min_cost += 1.0f;
  279. next_len_offset += next_len_bucket;
  280. next_len_bucket *= 2;
  281. }
  282. }
  283. return len;
  284. }
  285. /* REQUIRES: nodes[pos].cost < kInfinity
  286. REQUIRES: nodes[0..pos] satisfies that "ZopfliNode array invariant". */
  287. static uint32_t ComputeDistanceShortcut(const size_t block_start,
  288. const size_t pos,
  289. const size_t max_backward_limit,
  290. const size_t gap,
  291. const ZopfliNode* nodes) {
  292. const size_t clen = ZopfliNodeCopyLength(&nodes[pos]);
  293. const size_t ilen = nodes[pos].dcode_insert_length & 0x7FFFFFF;
  294. const size_t dist = ZopfliNodeCopyDistance(&nodes[pos]);
  295. /* Since |block_start + pos| is the end position of the command, the copy part
  296. starts from |block_start + pos - clen|. Distances that are greater than
  297. this or greater than |max_backward_limit| + |gap| are static dictionary
  298. references, and do not update the last distances.
  299. Also distance code 0 (last distance) does not update the last distances. */
  300. if (pos == 0) {
  301. return 0;
  302. } else if (dist + clen <= block_start + pos + gap &&
  303. dist <= max_backward_limit + gap &&
  304. ZopfliNodeDistanceCode(&nodes[pos]) > 0) {
  305. return (uint32_t)pos;
  306. } else {
  307. return nodes[pos - clen - ilen].u.shortcut;
  308. }
  309. }
  310. /* Fills in dist_cache[0..3] with the last four distances (as defined by
  311. Section 4. of the Spec) that would be used at (block_start + pos) if we
  312. used the shortest path of commands from block_start, computed from
  313. nodes[0..pos]. The last four distances at block_start are in
  314. starting_dist_cache[0..3].
  315. REQUIRES: nodes[pos].cost < kInfinity
  316. REQUIRES: nodes[0..pos] satisfies that "ZopfliNode array invariant". */
  317. static void ComputeDistanceCache(const size_t pos,
  318. const int* starting_dist_cache,
  319. const ZopfliNode* nodes,
  320. int* dist_cache) {
  321. int idx = 0;
  322. size_t p = nodes[pos].u.shortcut;
  323. while (idx < 4 && p > 0) {
  324. const size_t ilen = nodes[p].dcode_insert_length & 0x7FFFFFF;
  325. const size_t clen = ZopfliNodeCopyLength(&nodes[p]);
  326. const size_t dist = ZopfliNodeCopyDistance(&nodes[p]);
  327. dist_cache[idx++] = (int)dist;
  328. /* Because of prerequisite, p >= clen + ilen >= 2. */
  329. p = nodes[p - clen - ilen].u.shortcut;
  330. }
  331. for (; idx < 4; ++idx) {
  332. dist_cache[idx] = *starting_dist_cache++;
  333. }
  334. }
  335. /* Maintains "ZopfliNode array invariant" and pushes node to the queue, if it
  336. is eligible. */
  337. static void EvaluateNode(
  338. const size_t block_start, const size_t pos, const size_t max_backward_limit,
  339. const size_t gap, const int* starting_dist_cache,
  340. const ZopfliCostModel* model, StartPosQueue* queue, ZopfliNode* nodes) {
  341. /* Save cost, because ComputeDistanceCache invalidates it. */
  342. float node_cost = nodes[pos].u.cost;
  343. nodes[pos].u.shortcut = ComputeDistanceShortcut(
  344. block_start, pos, max_backward_limit, gap, nodes);
  345. if (node_cost <= ZopfliCostModelGetLiteralCosts(model, 0, pos)) {
  346. PosData posdata;
  347. posdata.pos = pos;
  348. posdata.cost = node_cost;
  349. posdata.costdiff = node_cost -
  350. ZopfliCostModelGetLiteralCosts(model, 0, pos);
  351. ComputeDistanceCache(
  352. pos, starting_dist_cache, nodes, posdata.distance_cache);
  353. StartPosQueuePush(queue, &posdata);
  354. }
  355. }
  356. /* Returns longest copy length. */
  357. static size_t UpdateNodes(
  358. const size_t num_bytes, const size_t block_start, const size_t pos,
  359. const uint8_t* ringbuffer, const size_t ringbuffer_mask,
  360. const BrotliEncoderParams* params, const size_t max_backward_limit,
  361. const int* starting_dist_cache, const size_t num_matches,
  362. const BackwardMatch* matches, const ZopfliCostModel* model,
  363. StartPosQueue* queue, ZopfliNode* nodes) {
  364. const size_t cur_ix = block_start + pos;
  365. const size_t cur_ix_masked = cur_ix & ringbuffer_mask;
  366. const size_t max_distance = BROTLI_MIN(size_t, cur_ix, max_backward_limit);
  367. const size_t max_len = num_bytes - pos;
  368. const size_t max_zopfli_len = MaxZopfliLen(params);
  369. const size_t max_iters = MaxZopfliCandidates(params);
  370. size_t min_len;
  371. size_t result = 0;
  372. size_t k;
  373. size_t gap = 0;
  374. EvaluateNode(block_start, pos, max_backward_limit, gap, starting_dist_cache,
  375. model, queue, nodes);
  376. {
  377. const PosData* posdata = StartPosQueueAt(queue, 0);
  378. float min_cost = (posdata->cost + ZopfliCostModelGetMinCostCmd(model) +
  379. ZopfliCostModelGetLiteralCosts(model, posdata->pos, pos));
  380. min_len = ComputeMinimumCopyLength(min_cost, nodes, num_bytes, pos);
  381. }
  382. /* Go over the command starting positions in order of increasing cost
  383. difference. */
  384. for (k = 0; k < max_iters && k < StartPosQueueSize(queue); ++k) {
  385. const PosData* posdata = StartPosQueueAt(queue, k);
  386. const size_t start = posdata->pos;
  387. const uint16_t inscode = GetInsertLengthCode(pos - start);
  388. const float start_costdiff = posdata->costdiff;
  389. const float base_cost = start_costdiff + (float)GetInsertExtra(inscode) +
  390. ZopfliCostModelGetLiteralCosts(model, 0, pos);
  391. /* Look for last distance matches using the distance cache from this
  392. starting position. */
  393. size_t best_len = min_len - 1;
  394. size_t j = 0;
  395. for (; j < BROTLI_NUM_DISTANCE_SHORT_CODES && best_len < max_len; ++j) {
  396. const size_t idx = kDistanceCacheIndex[j];
  397. const size_t backward =
  398. (size_t)(posdata->distance_cache[idx] + kDistanceCacheOffset[j]);
  399. size_t prev_ix = cur_ix - backward;
  400. size_t len = 0;
  401. uint8_t continuation = ringbuffer[cur_ix_masked + best_len];
  402. if (cur_ix_masked + best_len > ringbuffer_mask) {
  403. break;
  404. }
  405. if (BROTLI_PREDICT_FALSE(backward > max_distance + gap)) {
  406. /* Word dictionary -> ignore. */
  407. continue;
  408. }
  409. if (backward <= max_distance) {
  410. /* Regular backward reference. */
  411. if (prev_ix >= cur_ix) {
  412. continue;
  413. }
  414. prev_ix &= ringbuffer_mask;
  415. if (prev_ix + best_len > ringbuffer_mask ||
  416. continuation != ringbuffer[prev_ix + best_len]) {
  417. continue;
  418. }
  419. len = FindMatchLengthWithLimit(&ringbuffer[prev_ix],
  420. &ringbuffer[cur_ix_masked],
  421. max_len);
  422. } else {
  423. continue;
  424. }
  425. {
  426. const float dist_cost = base_cost +
  427. ZopfliCostModelGetDistanceCost(model, j);
  428. size_t l;
  429. for (l = best_len + 1; l <= len; ++l) {
  430. const uint16_t copycode = GetCopyLengthCode(l);
  431. const uint16_t cmdcode =
  432. CombineLengthCodes(inscode, copycode, j == 0);
  433. const float cost = (cmdcode < 128 ? base_cost : dist_cost) +
  434. (float)GetCopyExtra(copycode) +
  435. ZopfliCostModelGetCommandCost(model, cmdcode);
  436. if (cost < nodes[pos + l].u.cost) {
  437. UpdateZopfliNode(nodes, pos, start, l, l, backward, j + 1, cost);
  438. result = BROTLI_MAX(size_t, result, l);
  439. }
  440. best_len = l;
  441. }
  442. }
  443. }
  444. /* At higher iterations look only for new last distance matches, since
  445. looking only for new command start positions with the same distances
  446. does not help much. */
  447. if (k >= 2) continue;
  448. {
  449. /* Loop through all possible copy lengths at this position. */
  450. size_t len = min_len;
  451. for (j = 0; j < num_matches; ++j) {
  452. BackwardMatch match = matches[j];
  453. size_t dist = match.distance;
  454. BROTLI_BOOL is_dictionary_match =
  455. TO_BROTLI_BOOL(dist > max_distance + gap);
  456. /* We already tried all possible last distance matches, so we can use
  457. normal distance code here. */
  458. size_t dist_code = dist + BROTLI_NUM_DISTANCE_SHORT_CODES - 1;
  459. uint16_t dist_symbol;
  460. uint32_t distextra;
  461. uint32_t distnumextra;
  462. float dist_cost;
  463. size_t max_match_len;
  464. PrefixEncodeCopyDistance(
  465. dist_code, params->dist.num_direct_distance_codes,
  466. params->dist.distance_postfix_bits, &dist_symbol, &distextra);
  467. distnumextra = dist_symbol >> 10;
  468. dist_cost = base_cost + (float)distnumextra +
  469. ZopfliCostModelGetDistanceCost(model, dist_symbol & 0x3FF);
  470. /* Try all copy lengths up until the maximum copy length corresponding
  471. to this distance. If the distance refers to the static dictionary, or
  472. the maximum length is long enough, try only one maximum length. */
  473. max_match_len = BackwardMatchLength(&match);
  474. if (len < max_match_len &&
  475. (is_dictionary_match || max_match_len > max_zopfli_len)) {
  476. len = max_match_len;
  477. }
  478. for (; len <= max_match_len; ++len) {
  479. const size_t len_code =
  480. is_dictionary_match ? BackwardMatchLengthCode(&match) : len;
  481. const uint16_t copycode = GetCopyLengthCode(len_code);
  482. const uint16_t cmdcode = CombineLengthCodes(inscode, copycode, 0);
  483. const float cost = dist_cost + (float)GetCopyExtra(copycode) +
  484. ZopfliCostModelGetCommandCost(model, cmdcode);
  485. if (cost < nodes[pos + len].u.cost) {
  486. UpdateZopfliNode(nodes, pos, start, len, len_code, dist, 0, cost);
  487. result = BROTLI_MAX(size_t, result, len);
  488. }
  489. }
  490. }
  491. }
  492. }
  493. return result;
  494. }
  495. static size_t ComputeShortestPathFromNodes(size_t num_bytes,
  496. ZopfliNode* nodes) {
  497. size_t index = num_bytes;
  498. size_t num_commands = 0;
  499. while ((nodes[index].dcode_insert_length & 0x7FFFFFF) == 0 &&
  500. nodes[index].length == 1) --index;
  501. nodes[index].u.next = BROTLI_UINT32_MAX;
  502. while (index != 0) {
  503. size_t len = ZopfliNodeCommandLength(&nodes[index]);
  504. index -= len;
  505. nodes[index].u.next = (uint32_t)len;
  506. num_commands++;
  507. }
  508. return num_commands;
  509. }
  510. /* REQUIRES: nodes != NULL and len(nodes) >= num_bytes + 1 */
  511. void BrotliZopfliCreateCommands(const size_t num_bytes,
  512. const size_t block_start, const ZopfliNode* nodes, int* dist_cache,
  513. size_t* last_insert_len, const BrotliEncoderParams* params,
  514. Command* commands, size_t* num_literals) {
  515. const size_t max_backward_limit = BROTLI_MAX_BACKWARD_LIMIT(params->lgwin);
  516. size_t pos = 0;
  517. uint32_t offset = nodes[0].u.next;
  518. size_t i;
  519. size_t gap = 0;
  520. for (i = 0; offset != BROTLI_UINT32_MAX; i++) {
  521. const ZopfliNode* next = &nodes[pos + offset];
  522. size_t copy_length = ZopfliNodeCopyLength(next);
  523. size_t insert_length = next->dcode_insert_length & 0x7FFFFFF;
  524. pos += insert_length;
  525. offset = next->u.next;
  526. if (i == 0) {
  527. insert_length += *last_insert_len;
  528. *last_insert_len = 0;
  529. }
  530. {
  531. size_t distance = ZopfliNodeCopyDistance(next);
  532. size_t len_code = ZopfliNodeLengthCode(next);
  533. size_t max_distance =
  534. BROTLI_MIN(size_t, block_start + pos, max_backward_limit);
  535. BROTLI_BOOL is_dictionary = TO_BROTLI_BOOL(distance > max_distance + gap);
  536. size_t dist_code = ZopfliNodeDistanceCode(next);
  537. InitCommand(&commands[i], &params->dist, insert_length,
  538. copy_length, (int)len_code - (int)copy_length, dist_code);
  539. if (!is_dictionary && dist_code > 0) {
  540. dist_cache[3] = dist_cache[2];
  541. dist_cache[2] = dist_cache[1];
  542. dist_cache[1] = dist_cache[0];
  543. dist_cache[0] = (int)distance;
  544. }
  545. }
  546. *num_literals += insert_length;
  547. pos += copy_length;
  548. }
  549. *last_insert_len += num_bytes - pos;
  550. }
  551. static size_t ZopfliIterate(size_t num_bytes, size_t position,
  552. const uint8_t* ringbuffer, size_t ringbuffer_mask,
  553. const BrotliEncoderParams* params, const size_t gap, const int* dist_cache,
  554. const ZopfliCostModel* model, const uint32_t* num_matches,
  555. const BackwardMatch* matches, ZopfliNode* nodes) {
  556. const size_t max_backward_limit = BROTLI_MAX_BACKWARD_LIMIT(params->lgwin);
  557. const size_t max_zopfli_len = MaxZopfliLen(params);
  558. StartPosQueue queue;
  559. size_t cur_match_pos = 0;
  560. size_t i;
  561. nodes[0].length = 0;
  562. nodes[0].u.cost = 0;
  563. InitStartPosQueue(&queue);
  564. for (i = 0; i + 3 < num_bytes; i++) {
  565. size_t skip = UpdateNodes(num_bytes, position, i, ringbuffer,
  566. ringbuffer_mask, params, max_backward_limit, dist_cache,
  567. num_matches[i], &matches[cur_match_pos], model, &queue, nodes);
  568. if (skip < BROTLI_LONG_COPY_QUICK_STEP) skip = 0;
  569. cur_match_pos += num_matches[i];
  570. if (num_matches[i] == 1 &&
  571. BackwardMatchLength(&matches[cur_match_pos - 1]) > max_zopfli_len) {
  572. skip = BROTLI_MAX(size_t,
  573. BackwardMatchLength(&matches[cur_match_pos - 1]), skip);
  574. }
  575. if (skip > 1) {
  576. skip--;
  577. while (skip) {
  578. i++;
  579. if (i + 3 >= num_bytes) break;
  580. EvaluateNode(position, i, max_backward_limit, gap,
  581. dist_cache, model, &queue, nodes);
  582. cur_match_pos += num_matches[i];
  583. skip--;
  584. }
  585. }
  586. }
  587. return ComputeShortestPathFromNodes(num_bytes, nodes);
  588. }
  589. /* REQUIRES: nodes != NULL and len(nodes) >= num_bytes + 1 */
  590. size_t BrotliZopfliComputeShortestPath(MemoryManager* m, size_t num_bytes,
  591. size_t position, const uint8_t* ringbuffer, size_t ringbuffer_mask,
  592. const BrotliEncoderParams* params,
  593. const int* dist_cache, HasherHandle hasher, ZopfliNode* nodes) {
  594. const size_t max_backward_limit = BROTLI_MAX_BACKWARD_LIMIT(params->lgwin);
  595. const size_t max_zopfli_len = MaxZopfliLen(params);
  596. ZopfliCostModel model;
  597. StartPosQueue queue;
  598. BackwardMatch matches[2 * (MAX_NUM_MATCHES_H10 + 64)];
  599. const size_t store_end = num_bytes >= StoreLookaheadH10() ?
  600. position + num_bytes - StoreLookaheadH10() + 1 : position;
  601. size_t i;
  602. size_t gap = 0;
  603. size_t lz_matches_offset = 0;
  604. nodes[0].length = 0;
  605. nodes[0].u.cost = 0;
  606. InitZopfliCostModel(m, &model, &params->dist, num_bytes);
  607. if (BROTLI_IS_OOM(m)) return 0;
  608. ZopfliCostModelSetFromLiteralCosts(
  609. &model, position, ringbuffer, ringbuffer_mask);
  610. InitStartPosQueue(&queue);
  611. for (i = 0; i + HashTypeLengthH10() - 1 < num_bytes; i++) {
  612. const size_t pos = position + i;
  613. const size_t max_distance = BROTLI_MIN(size_t, pos, max_backward_limit);
  614. size_t skip;
  615. size_t num_matches;
  616. num_matches = FindAllMatchesH10(hasher,
  617. &params->dictionary,
  618. ringbuffer, ringbuffer_mask, pos, num_bytes - i, max_distance,
  619. gap, params, &matches[lz_matches_offset]);
  620. if (num_matches > 0 &&
  621. BackwardMatchLength(&matches[num_matches - 1]) > max_zopfli_len) {
  622. matches[0] = matches[num_matches - 1];
  623. num_matches = 1;
  624. }
  625. skip = UpdateNodes(num_bytes, position, i, ringbuffer, ringbuffer_mask,
  626. params, max_backward_limit, dist_cache, num_matches, matches, &model,
  627. &queue, nodes);
  628. if (skip < BROTLI_LONG_COPY_QUICK_STEP) skip = 0;
  629. if (num_matches == 1 && BackwardMatchLength(&matches[0]) > max_zopfli_len) {
  630. skip = BROTLI_MAX(size_t, BackwardMatchLength(&matches[0]), skip);
  631. }
  632. if (skip > 1) {
  633. /* Add the tail of the copy to the hasher. */
  634. StoreRangeH10(hasher, ringbuffer, ringbuffer_mask, pos + 1, BROTLI_MIN(
  635. size_t, pos + skip, store_end));
  636. skip--;
  637. while (skip) {
  638. i++;
  639. if (i + HashTypeLengthH10() - 1 >= num_bytes) break;
  640. EvaluateNode(position, i, max_backward_limit, gap,
  641. dist_cache, &model, &queue, nodes);
  642. skip--;
  643. }
  644. }
  645. }
  646. CleanupZopfliCostModel(m, &model);
  647. return ComputeShortestPathFromNodes(num_bytes, nodes);
  648. }
  649. void BrotliCreateZopfliBackwardReferences(MemoryManager* m, size_t num_bytes,
  650. size_t position, const uint8_t* ringbuffer, size_t ringbuffer_mask,
  651. const BrotliEncoderParams* params,
  652. HasherHandle hasher, int* dist_cache, size_t* last_insert_len,
  653. Command* commands, size_t* num_commands, size_t* num_literals) {
  654. ZopfliNode* nodes;
  655. nodes = BROTLI_ALLOC(m, ZopfliNode, num_bytes + 1);
  656. if (BROTLI_IS_OOM(m)) return;
  657. BrotliInitZopfliNodes(nodes, num_bytes + 1);
  658. *num_commands += BrotliZopfliComputeShortestPath(m, num_bytes,
  659. position, ringbuffer, ringbuffer_mask, params,
  660. dist_cache, hasher, nodes);
  661. if (BROTLI_IS_OOM(m)) return;
  662. BrotliZopfliCreateCommands(num_bytes, position, nodes, dist_cache,
  663. last_insert_len, params, commands, num_literals);
  664. BROTLI_FREE(m, nodes);
  665. }
  666. void BrotliCreateHqZopfliBackwardReferences(MemoryManager* m, size_t num_bytes,
  667. size_t position, const uint8_t* ringbuffer, size_t ringbuffer_mask,
  668. const BrotliEncoderParams* params,
  669. HasherHandle hasher, int* dist_cache, size_t* last_insert_len,
  670. Command* commands, size_t* num_commands, size_t* num_literals) {
  671. const size_t max_backward_limit = BROTLI_MAX_BACKWARD_LIMIT(params->lgwin);
  672. uint32_t* num_matches = BROTLI_ALLOC(m, uint32_t, num_bytes);
  673. size_t matches_size = 4 * num_bytes;
  674. const size_t store_end = num_bytes >= StoreLookaheadH10() ?
  675. position + num_bytes - StoreLookaheadH10() + 1 : position;
  676. size_t cur_match_pos = 0;
  677. size_t i;
  678. size_t orig_num_literals;
  679. size_t orig_last_insert_len;
  680. int orig_dist_cache[4];
  681. size_t orig_num_commands;
  682. ZopfliCostModel model;
  683. ZopfliNode* nodes;
  684. BackwardMatch* matches = BROTLI_ALLOC(m, BackwardMatch, matches_size);
  685. size_t gap = 0;
  686. size_t shadow_matches = 0;
  687. if (BROTLI_IS_OOM(m)) return;
  688. for (i = 0; i + HashTypeLengthH10() - 1 < num_bytes; ++i) {
  689. const size_t pos = position + i;
  690. size_t max_distance = BROTLI_MIN(size_t, pos, max_backward_limit);
  691. size_t max_length = num_bytes - i;
  692. size_t num_found_matches;
  693. size_t cur_match_end;
  694. size_t j;
  695. /* Ensure that we have enough free slots. */
  696. BROTLI_ENSURE_CAPACITY(m, BackwardMatch, matches, matches_size,
  697. cur_match_pos + MAX_NUM_MATCHES_H10 + shadow_matches);
  698. if (BROTLI_IS_OOM(m)) return;
  699. num_found_matches = FindAllMatchesH10(hasher,
  700. &params->dictionary,
  701. ringbuffer, ringbuffer_mask, pos, max_length,
  702. max_distance, gap, params,
  703. &matches[cur_match_pos + shadow_matches]);
  704. cur_match_end = cur_match_pos + num_found_matches;
  705. for (j = cur_match_pos; j + 1 < cur_match_end; ++j) {
  706. BROTLI_DCHECK(BackwardMatchLength(&matches[j]) <=
  707. BackwardMatchLength(&matches[j + 1]));
  708. }
  709. num_matches[i] = (uint32_t)num_found_matches;
  710. if (num_found_matches > 0) {
  711. const size_t match_len = BackwardMatchLength(&matches[cur_match_end - 1]);
  712. if (match_len > MAX_ZOPFLI_LEN_QUALITY_11) {
  713. const size_t skip = match_len - 1;
  714. matches[cur_match_pos++] = matches[cur_match_end - 1];
  715. num_matches[i] = 1;
  716. /* Add the tail of the copy to the hasher. */
  717. StoreRangeH10(hasher, ringbuffer, ringbuffer_mask, pos + 1,
  718. BROTLI_MIN(size_t, pos + match_len, store_end));
  719. memset(&num_matches[i + 1], 0, skip * sizeof(num_matches[0]));
  720. i += skip;
  721. } else {
  722. cur_match_pos = cur_match_end;
  723. }
  724. }
  725. }
  726. orig_num_literals = *num_literals;
  727. orig_last_insert_len = *last_insert_len;
  728. memcpy(orig_dist_cache, dist_cache, 4 * sizeof(dist_cache[0]));
  729. orig_num_commands = *num_commands;
  730. nodes = BROTLI_ALLOC(m, ZopfliNode, num_bytes + 1);
  731. if (BROTLI_IS_OOM(m)) return;
  732. InitZopfliCostModel(m, &model, &params->dist, num_bytes);
  733. if (BROTLI_IS_OOM(m)) return;
  734. for (i = 0; i < 2; i++) {
  735. BrotliInitZopfliNodes(nodes, num_bytes + 1);
  736. if (i == 0) {
  737. ZopfliCostModelSetFromLiteralCosts(
  738. &model, position, ringbuffer, ringbuffer_mask);
  739. } else {
  740. ZopfliCostModelSetFromCommands(&model, position, ringbuffer,
  741. ringbuffer_mask, commands, *num_commands - orig_num_commands,
  742. orig_last_insert_len);
  743. }
  744. *num_commands = orig_num_commands;
  745. *num_literals = orig_num_literals;
  746. *last_insert_len = orig_last_insert_len;
  747. memcpy(dist_cache, orig_dist_cache, 4 * sizeof(dist_cache[0]));
  748. *num_commands += ZopfliIterate(num_bytes, position, ringbuffer,
  749. ringbuffer_mask, params, gap, dist_cache, &model, num_matches, matches,
  750. nodes);
  751. BrotliZopfliCreateCommands(num_bytes, position, nodes, dist_cache,
  752. last_insert_len, params, commands, num_literals);
  753. }
  754. CleanupZopfliCostModel(m, &model);
  755. BROTLI_FREE(m, nodes);
  756. BROTLI_FREE(m, matches);
  757. BROTLI_FREE(m, num_matches);
  758. }
  759. #if defined(__cplusplus) || defined(c_plusplus)
  760. } /* extern "C" */
  761. #endif