11cb0ef41Sopenharmony_ci/* Copyright 2013 Google Inc. All Rights Reserved.
21cb0ef41Sopenharmony_ci
31cb0ef41Sopenharmony_ci   Distributed under MIT license.
41cb0ef41Sopenharmony_ci   See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
51cb0ef41Sopenharmony_ci*/
61cb0ef41Sopenharmony_ci
71cb0ef41Sopenharmony_ci/* Function to find backward reference copies. */
81cb0ef41Sopenharmony_ci
91cb0ef41Sopenharmony_ci#include "./backward_references_hq.h"
101cb0ef41Sopenharmony_ci
111cb0ef41Sopenharmony_ci#include <string.h>  /* memcpy, memset */
121cb0ef41Sopenharmony_ci
131cb0ef41Sopenharmony_ci#include "../common/constants.h"
141cb0ef41Sopenharmony_ci#include "../common/context.h"
151cb0ef41Sopenharmony_ci#include "../common/platform.h"
161cb0ef41Sopenharmony_ci#include <brotli/types.h>
171cb0ef41Sopenharmony_ci#include "./command.h"
181cb0ef41Sopenharmony_ci#include "./fast_log.h"
191cb0ef41Sopenharmony_ci#include "./find_match_length.h"
201cb0ef41Sopenharmony_ci#include "./literal_cost.h"
211cb0ef41Sopenharmony_ci#include "./memory.h"
221cb0ef41Sopenharmony_ci#include "./params.h"
231cb0ef41Sopenharmony_ci#include "./prefix.h"
241cb0ef41Sopenharmony_ci#include "./quality.h"
251cb0ef41Sopenharmony_ci
261cb0ef41Sopenharmony_ci#if defined(__cplusplus) || defined(c_plusplus)
271cb0ef41Sopenharmony_ciextern "C" {
281cb0ef41Sopenharmony_ci#endif
291cb0ef41Sopenharmony_ci
301cb0ef41Sopenharmony_ci/* BrotliCalculateDistanceCodeLimit(BROTLI_MAX_ALLOWED_DISTANCE, 3, 120). */
311cb0ef41Sopenharmony_ci#define BROTLI_MAX_EFFECTIVE_DISTANCE_ALPHABET_SIZE 544
321cb0ef41Sopenharmony_ci
331cb0ef41Sopenharmony_cistatic const float kInfinity = 1.7e38f;  /* ~= 2 ^ 127 */
341cb0ef41Sopenharmony_ci
351cb0ef41Sopenharmony_cistatic const uint32_t kDistanceCacheIndex[] = {
361cb0ef41Sopenharmony_ci  0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,
371cb0ef41Sopenharmony_ci};
381cb0ef41Sopenharmony_cistatic const int kDistanceCacheOffset[] = {
391cb0ef41Sopenharmony_ci  0, 0, 0, 0, -1, 1, -2, 2, -3, 3, -1, 1, -2, 2, -3, 3
401cb0ef41Sopenharmony_ci};
411cb0ef41Sopenharmony_ci
421cb0ef41Sopenharmony_civoid BrotliInitZopfliNodes(ZopfliNode* array, size_t length) {
431cb0ef41Sopenharmony_ci  ZopfliNode stub;
441cb0ef41Sopenharmony_ci  size_t i;
451cb0ef41Sopenharmony_ci  stub.length = 1;
461cb0ef41Sopenharmony_ci  stub.distance = 0;
471cb0ef41Sopenharmony_ci  stub.dcode_insert_length = 0;
481cb0ef41Sopenharmony_ci  stub.u.cost = kInfinity;
491cb0ef41Sopenharmony_ci  for (i = 0; i < length; ++i) array[i] = stub;
501cb0ef41Sopenharmony_ci}
511cb0ef41Sopenharmony_ci
521cb0ef41Sopenharmony_cistatic BROTLI_INLINE uint32_t ZopfliNodeCopyLength(const ZopfliNode* self) {
531cb0ef41Sopenharmony_ci  return self->length & 0x1FFFFFF;
541cb0ef41Sopenharmony_ci}
551cb0ef41Sopenharmony_ci
561cb0ef41Sopenharmony_cistatic BROTLI_INLINE uint32_t ZopfliNodeLengthCode(const ZopfliNode* self) {
571cb0ef41Sopenharmony_ci  const uint32_t modifier = self->length >> 25;
581cb0ef41Sopenharmony_ci  return ZopfliNodeCopyLength(self) + 9u - modifier;
591cb0ef41Sopenharmony_ci}
601cb0ef41Sopenharmony_ci
611cb0ef41Sopenharmony_cistatic BROTLI_INLINE uint32_t ZopfliNodeCopyDistance(const ZopfliNode* self) {
621cb0ef41Sopenharmony_ci  return self->distance;
631cb0ef41Sopenharmony_ci}
641cb0ef41Sopenharmony_ci
651cb0ef41Sopenharmony_cistatic BROTLI_INLINE uint32_t ZopfliNodeDistanceCode(const ZopfliNode* self) {
661cb0ef41Sopenharmony_ci  const uint32_t short_code = self->dcode_insert_length >> 27;
671cb0ef41Sopenharmony_ci  return short_code == 0 ?
681cb0ef41Sopenharmony_ci      ZopfliNodeCopyDistance(self) + BROTLI_NUM_DISTANCE_SHORT_CODES - 1 :
691cb0ef41Sopenharmony_ci      short_code - 1;
701cb0ef41Sopenharmony_ci}
711cb0ef41Sopenharmony_ci
721cb0ef41Sopenharmony_cistatic BROTLI_INLINE uint32_t ZopfliNodeCommandLength(const ZopfliNode* self) {
731cb0ef41Sopenharmony_ci  return ZopfliNodeCopyLength(self) + (self->dcode_insert_length & 0x7FFFFFF);
741cb0ef41Sopenharmony_ci}
751cb0ef41Sopenharmony_ci
761cb0ef41Sopenharmony_ci/* Histogram based cost model for zopflification. */
771cb0ef41Sopenharmony_citypedef struct ZopfliCostModel {
781cb0ef41Sopenharmony_ci  /* The insert and copy length symbols. */
791cb0ef41Sopenharmony_ci  float cost_cmd_[BROTLI_NUM_COMMAND_SYMBOLS];
801cb0ef41Sopenharmony_ci  float* cost_dist_;
811cb0ef41Sopenharmony_ci  uint32_t distance_histogram_size;
821cb0ef41Sopenharmony_ci  /* Cumulative costs of literals per position in the stream. */
831cb0ef41Sopenharmony_ci  float* literal_costs_;
841cb0ef41Sopenharmony_ci  float min_cost_cmd_;
851cb0ef41Sopenharmony_ci  size_t num_bytes_;
861cb0ef41Sopenharmony_ci} ZopfliCostModel;
871cb0ef41Sopenharmony_ci
881cb0ef41Sopenharmony_cistatic void InitZopfliCostModel(
891cb0ef41Sopenharmony_ci    MemoryManager* m, ZopfliCostModel* self, const BrotliDistanceParams* dist,
901cb0ef41Sopenharmony_ci    size_t num_bytes) {
911cb0ef41Sopenharmony_ci  self->num_bytes_ = num_bytes;
921cb0ef41Sopenharmony_ci  self->literal_costs_ = BROTLI_ALLOC(m, float, num_bytes + 2);
931cb0ef41Sopenharmony_ci  self->cost_dist_ = BROTLI_ALLOC(m, float, dist->alphabet_size_limit);
941cb0ef41Sopenharmony_ci  self->distance_histogram_size = dist->alphabet_size_limit;
951cb0ef41Sopenharmony_ci  if (BROTLI_IS_OOM(m)) return;
961cb0ef41Sopenharmony_ci}
971cb0ef41Sopenharmony_ci
981cb0ef41Sopenharmony_cistatic void CleanupZopfliCostModel(MemoryManager* m, ZopfliCostModel* self) {
991cb0ef41Sopenharmony_ci  BROTLI_FREE(m, self->literal_costs_);
1001cb0ef41Sopenharmony_ci  BROTLI_FREE(m, self->cost_dist_);
1011cb0ef41Sopenharmony_ci}
1021cb0ef41Sopenharmony_ci
1031cb0ef41Sopenharmony_cistatic void SetCost(const uint32_t* histogram, size_t histogram_size,
1041cb0ef41Sopenharmony_ci                    BROTLI_BOOL literal_histogram, float* cost) {
1051cb0ef41Sopenharmony_ci  size_t sum = 0;
1061cb0ef41Sopenharmony_ci  size_t missing_symbol_sum;
1071cb0ef41Sopenharmony_ci  float log2sum;
1081cb0ef41Sopenharmony_ci  float missing_symbol_cost;
1091cb0ef41Sopenharmony_ci  size_t i;
1101cb0ef41Sopenharmony_ci  for (i = 0; i < histogram_size; i++) {
1111cb0ef41Sopenharmony_ci    sum += histogram[i];
1121cb0ef41Sopenharmony_ci  }
1131cb0ef41Sopenharmony_ci  log2sum = (float)FastLog2(sum);
1141cb0ef41Sopenharmony_ci  missing_symbol_sum = sum;
1151cb0ef41Sopenharmony_ci  if (!literal_histogram) {
1161cb0ef41Sopenharmony_ci    for (i = 0; i < histogram_size; i++) {
1171cb0ef41Sopenharmony_ci      if (histogram[i] == 0) missing_symbol_sum++;
1181cb0ef41Sopenharmony_ci    }
1191cb0ef41Sopenharmony_ci  }
1201cb0ef41Sopenharmony_ci  missing_symbol_cost = (float)FastLog2(missing_symbol_sum) + 2;
1211cb0ef41Sopenharmony_ci  for (i = 0; i < histogram_size; i++) {
1221cb0ef41Sopenharmony_ci    if (histogram[i] == 0) {
1231cb0ef41Sopenharmony_ci      cost[i] = missing_symbol_cost;
1241cb0ef41Sopenharmony_ci      continue;
1251cb0ef41Sopenharmony_ci    }
1261cb0ef41Sopenharmony_ci
1271cb0ef41Sopenharmony_ci    /* Shannon bits for this symbol. */
1281cb0ef41Sopenharmony_ci    cost[i] = log2sum - (float)FastLog2(histogram[i]);
1291cb0ef41Sopenharmony_ci
1301cb0ef41Sopenharmony_ci    /* Cannot be coded with less than 1 bit */
1311cb0ef41Sopenharmony_ci    if (cost[i] < 1) cost[i] = 1;
1321cb0ef41Sopenharmony_ci  }
1331cb0ef41Sopenharmony_ci}
1341cb0ef41Sopenharmony_ci
1351cb0ef41Sopenharmony_cistatic void ZopfliCostModelSetFromCommands(ZopfliCostModel* self,
1361cb0ef41Sopenharmony_ci                                           size_t position,
1371cb0ef41Sopenharmony_ci                                           const uint8_t* ringbuffer,
1381cb0ef41Sopenharmony_ci                                           size_t ringbuffer_mask,
1391cb0ef41Sopenharmony_ci                                           const Command* commands,
1401cb0ef41Sopenharmony_ci                                           size_t num_commands,
1411cb0ef41Sopenharmony_ci                                           size_t last_insert_len) {
1421cb0ef41Sopenharmony_ci  uint32_t histogram_literal[BROTLI_NUM_LITERAL_SYMBOLS];
1431cb0ef41Sopenharmony_ci  uint32_t histogram_cmd[BROTLI_NUM_COMMAND_SYMBOLS];
1441cb0ef41Sopenharmony_ci  uint32_t histogram_dist[BROTLI_MAX_EFFECTIVE_DISTANCE_ALPHABET_SIZE];
1451cb0ef41Sopenharmony_ci  float cost_literal[BROTLI_NUM_LITERAL_SYMBOLS];
1461cb0ef41Sopenharmony_ci  size_t pos = position - last_insert_len;
1471cb0ef41Sopenharmony_ci  float min_cost_cmd = kInfinity;
1481cb0ef41Sopenharmony_ci  size_t i;
1491cb0ef41Sopenharmony_ci  float* cost_cmd = self->cost_cmd_;
1501cb0ef41Sopenharmony_ci
1511cb0ef41Sopenharmony_ci  memset(histogram_literal, 0, sizeof(histogram_literal));
1521cb0ef41Sopenharmony_ci  memset(histogram_cmd, 0, sizeof(histogram_cmd));
1531cb0ef41Sopenharmony_ci  memset(histogram_dist, 0, sizeof(histogram_dist));
1541cb0ef41Sopenharmony_ci
1551cb0ef41Sopenharmony_ci  for (i = 0; i < num_commands; i++) {
1561cb0ef41Sopenharmony_ci    size_t inslength = commands[i].insert_len_;
1571cb0ef41Sopenharmony_ci    size_t copylength = CommandCopyLen(&commands[i]);
1581cb0ef41Sopenharmony_ci    size_t distcode = commands[i].dist_prefix_ & 0x3FF;
1591cb0ef41Sopenharmony_ci    size_t cmdcode = commands[i].cmd_prefix_;
1601cb0ef41Sopenharmony_ci    size_t j;
1611cb0ef41Sopenharmony_ci
1621cb0ef41Sopenharmony_ci    histogram_cmd[cmdcode]++;
1631cb0ef41Sopenharmony_ci    if (cmdcode >= 128) histogram_dist[distcode]++;
1641cb0ef41Sopenharmony_ci
1651cb0ef41Sopenharmony_ci    for (j = 0; j < inslength; j++) {
1661cb0ef41Sopenharmony_ci      histogram_literal[ringbuffer[(pos + j) & ringbuffer_mask]]++;
1671cb0ef41Sopenharmony_ci    }
1681cb0ef41Sopenharmony_ci
1691cb0ef41Sopenharmony_ci    pos += inslength + copylength;
1701cb0ef41Sopenharmony_ci  }
1711cb0ef41Sopenharmony_ci
1721cb0ef41Sopenharmony_ci  SetCost(histogram_literal, BROTLI_NUM_LITERAL_SYMBOLS, BROTLI_TRUE,
1731cb0ef41Sopenharmony_ci          cost_literal);
1741cb0ef41Sopenharmony_ci  SetCost(histogram_cmd, BROTLI_NUM_COMMAND_SYMBOLS, BROTLI_FALSE,
1751cb0ef41Sopenharmony_ci          cost_cmd);
1761cb0ef41Sopenharmony_ci  SetCost(histogram_dist, self->distance_histogram_size, BROTLI_FALSE,
1771cb0ef41Sopenharmony_ci          self->cost_dist_);
1781cb0ef41Sopenharmony_ci
1791cb0ef41Sopenharmony_ci  for (i = 0; i < BROTLI_NUM_COMMAND_SYMBOLS; ++i) {
1801cb0ef41Sopenharmony_ci    min_cost_cmd = BROTLI_MIN(float, min_cost_cmd, cost_cmd[i]);
1811cb0ef41Sopenharmony_ci  }
1821cb0ef41Sopenharmony_ci  self->min_cost_cmd_ = min_cost_cmd;
1831cb0ef41Sopenharmony_ci
1841cb0ef41Sopenharmony_ci  {
1851cb0ef41Sopenharmony_ci    float* literal_costs = self->literal_costs_;
1861cb0ef41Sopenharmony_ci    float literal_carry = 0.0;
1871cb0ef41Sopenharmony_ci    size_t num_bytes = self->num_bytes_;
1881cb0ef41Sopenharmony_ci    literal_costs[0] = 0.0;
1891cb0ef41Sopenharmony_ci    for (i = 0; i < num_bytes; ++i) {
1901cb0ef41Sopenharmony_ci      literal_carry +=
1911cb0ef41Sopenharmony_ci          cost_literal[ringbuffer[(position + i) & ringbuffer_mask]];
1921cb0ef41Sopenharmony_ci      literal_costs[i + 1] = literal_costs[i] + literal_carry;
1931cb0ef41Sopenharmony_ci      literal_carry -= literal_costs[i + 1] - literal_costs[i];
1941cb0ef41Sopenharmony_ci    }
1951cb0ef41Sopenharmony_ci  }
1961cb0ef41Sopenharmony_ci}
1971cb0ef41Sopenharmony_ci
1981cb0ef41Sopenharmony_cistatic void ZopfliCostModelSetFromLiteralCosts(ZopfliCostModel* self,
1991cb0ef41Sopenharmony_ci                                               size_t position,
2001cb0ef41Sopenharmony_ci                                               const uint8_t* ringbuffer,
2011cb0ef41Sopenharmony_ci                                               size_t ringbuffer_mask) {
2021cb0ef41Sopenharmony_ci  float* literal_costs = self->literal_costs_;
2031cb0ef41Sopenharmony_ci  float literal_carry = 0.0;
2041cb0ef41Sopenharmony_ci  float* cost_dist = self->cost_dist_;
2051cb0ef41Sopenharmony_ci  float* cost_cmd = self->cost_cmd_;
2061cb0ef41Sopenharmony_ci  size_t num_bytes = self->num_bytes_;
2071cb0ef41Sopenharmony_ci  size_t i;
2081cb0ef41Sopenharmony_ci  BrotliEstimateBitCostsForLiterals(position, num_bytes, ringbuffer_mask,
2091cb0ef41Sopenharmony_ci                                    ringbuffer, &literal_costs[1]);
2101cb0ef41Sopenharmony_ci  literal_costs[0] = 0.0;
2111cb0ef41Sopenharmony_ci  for (i = 0; i < num_bytes; ++i) {
2121cb0ef41Sopenharmony_ci    literal_carry += literal_costs[i + 1];
2131cb0ef41Sopenharmony_ci    literal_costs[i + 1] = literal_costs[i] + literal_carry;
2141cb0ef41Sopenharmony_ci    literal_carry -= literal_costs[i + 1] - literal_costs[i];
2151cb0ef41Sopenharmony_ci  }
2161cb0ef41Sopenharmony_ci  for (i = 0; i < BROTLI_NUM_COMMAND_SYMBOLS; ++i) {
2171cb0ef41Sopenharmony_ci    cost_cmd[i] = (float)FastLog2(11 + (uint32_t)i);
2181cb0ef41Sopenharmony_ci  }
2191cb0ef41Sopenharmony_ci  for (i = 0; i < self->distance_histogram_size; ++i) {
2201cb0ef41Sopenharmony_ci    cost_dist[i] = (float)FastLog2(20 + (uint32_t)i);
2211cb0ef41Sopenharmony_ci  }
2221cb0ef41Sopenharmony_ci  self->min_cost_cmd_ = (float)FastLog2(11);
2231cb0ef41Sopenharmony_ci}
2241cb0ef41Sopenharmony_ci
2251cb0ef41Sopenharmony_cistatic BROTLI_INLINE float ZopfliCostModelGetCommandCost(
2261cb0ef41Sopenharmony_ci    const ZopfliCostModel* self, uint16_t cmdcode) {
2271cb0ef41Sopenharmony_ci  return self->cost_cmd_[cmdcode];
2281cb0ef41Sopenharmony_ci}
2291cb0ef41Sopenharmony_ci
2301cb0ef41Sopenharmony_cistatic BROTLI_INLINE float ZopfliCostModelGetDistanceCost(
2311cb0ef41Sopenharmony_ci    const ZopfliCostModel* self, size_t distcode) {
2321cb0ef41Sopenharmony_ci  return self->cost_dist_[distcode];
2331cb0ef41Sopenharmony_ci}
2341cb0ef41Sopenharmony_ci
2351cb0ef41Sopenharmony_cistatic BROTLI_INLINE float ZopfliCostModelGetLiteralCosts(
2361cb0ef41Sopenharmony_ci    const ZopfliCostModel* self, size_t from, size_t to) {
2371cb0ef41Sopenharmony_ci  return self->literal_costs_[to] - self->literal_costs_[from];
2381cb0ef41Sopenharmony_ci}
2391cb0ef41Sopenharmony_ci
2401cb0ef41Sopenharmony_cistatic BROTLI_INLINE float ZopfliCostModelGetMinCostCmd(
2411cb0ef41Sopenharmony_ci    const ZopfliCostModel* self) {
2421cb0ef41Sopenharmony_ci  return self->min_cost_cmd_;
2431cb0ef41Sopenharmony_ci}
2441cb0ef41Sopenharmony_ci
2451cb0ef41Sopenharmony_ci/* REQUIRES: len >= 2, start_pos <= pos */
2461cb0ef41Sopenharmony_ci/* REQUIRES: cost < kInfinity, nodes[start_pos].cost < kInfinity */
2471cb0ef41Sopenharmony_ci/* Maintains the "ZopfliNode array invariant". */
2481cb0ef41Sopenharmony_cistatic BROTLI_INLINE void UpdateZopfliNode(ZopfliNode* nodes, size_t pos,
2491cb0ef41Sopenharmony_ci    size_t start_pos, size_t len, size_t len_code, size_t dist,
2501cb0ef41Sopenharmony_ci    size_t short_code, float cost) {
2511cb0ef41Sopenharmony_ci  ZopfliNode* next = &nodes[pos + len];
2521cb0ef41Sopenharmony_ci  next->length = (uint32_t)(len | ((len + 9u - len_code) << 25));
2531cb0ef41Sopenharmony_ci  next->distance = (uint32_t)dist;
2541cb0ef41Sopenharmony_ci  next->dcode_insert_length = (uint32_t)(
2551cb0ef41Sopenharmony_ci      (short_code << 27) | (pos - start_pos));
2561cb0ef41Sopenharmony_ci  next->u.cost = cost;
2571cb0ef41Sopenharmony_ci}
2581cb0ef41Sopenharmony_ci
2591cb0ef41Sopenharmony_citypedef struct PosData {
2601cb0ef41Sopenharmony_ci  size_t pos;
2611cb0ef41Sopenharmony_ci  int distance_cache[4];
2621cb0ef41Sopenharmony_ci  float costdiff;
2631cb0ef41Sopenharmony_ci  float cost;
2641cb0ef41Sopenharmony_ci} PosData;
2651cb0ef41Sopenharmony_ci
2661cb0ef41Sopenharmony_ci/* Maintains the smallest 8 cost difference together with their positions */
2671cb0ef41Sopenharmony_citypedef struct StartPosQueue {
2681cb0ef41Sopenharmony_ci  PosData q_[8];
2691cb0ef41Sopenharmony_ci  size_t idx_;
2701cb0ef41Sopenharmony_ci} StartPosQueue;
2711cb0ef41Sopenharmony_ci
2721cb0ef41Sopenharmony_cistatic BROTLI_INLINE void InitStartPosQueue(StartPosQueue* self) {
2731cb0ef41Sopenharmony_ci  self->idx_ = 0;
2741cb0ef41Sopenharmony_ci}
2751cb0ef41Sopenharmony_ci
2761cb0ef41Sopenharmony_cistatic size_t StartPosQueueSize(const StartPosQueue* self) {
2771cb0ef41Sopenharmony_ci  return BROTLI_MIN(size_t, self->idx_, 8);
2781cb0ef41Sopenharmony_ci}
2791cb0ef41Sopenharmony_ci
2801cb0ef41Sopenharmony_cistatic void StartPosQueuePush(StartPosQueue* self, const PosData* posdata) {
2811cb0ef41Sopenharmony_ci  size_t offset = ~(self->idx_++) & 7;
2821cb0ef41Sopenharmony_ci  size_t len = StartPosQueueSize(self);
2831cb0ef41Sopenharmony_ci  size_t i;
2841cb0ef41Sopenharmony_ci  PosData* q = self->q_;
2851cb0ef41Sopenharmony_ci  q[offset] = *posdata;
2861cb0ef41Sopenharmony_ci  /* Restore the sorted order. In the list of |len| items at most |len - 1|
2871cb0ef41Sopenharmony_ci     adjacent element comparisons / swaps are required. */
2881cb0ef41Sopenharmony_ci  for (i = 1; i < len; ++i) {
2891cb0ef41Sopenharmony_ci    if (q[offset & 7].costdiff > q[(offset + 1) & 7].costdiff) {
2901cb0ef41Sopenharmony_ci      BROTLI_SWAP(PosData, q, offset & 7, (offset + 1) & 7);
2911cb0ef41Sopenharmony_ci    }
2921cb0ef41Sopenharmony_ci    ++offset;
2931cb0ef41Sopenharmony_ci  }
2941cb0ef41Sopenharmony_ci}
2951cb0ef41Sopenharmony_ci
2961cb0ef41Sopenharmony_cistatic const PosData* StartPosQueueAt(const StartPosQueue* self, size_t k) {
2971cb0ef41Sopenharmony_ci  return &self->q_[(k - self->idx_) & 7];
2981cb0ef41Sopenharmony_ci}
2991cb0ef41Sopenharmony_ci
3001cb0ef41Sopenharmony_ci/* Returns the minimum possible copy length that can improve the cost of any */
3011cb0ef41Sopenharmony_ci/* future position. */
3021cb0ef41Sopenharmony_cistatic size_t ComputeMinimumCopyLength(const float start_cost,
3031cb0ef41Sopenharmony_ci                                       const ZopfliNode* nodes,
3041cb0ef41Sopenharmony_ci                                       const size_t num_bytes,
3051cb0ef41Sopenharmony_ci                                       const size_t pos) {
3061cb0ef41Sopenharmony_ci  /* Compute the minimum possible cost of reaching any future position. */
3071cb0ef41Sopenharmony_ci  float min_cost = start_cost;
3081cb0ef41Sopenharmony_ci  size_t len = 2;
3091cb0ef41Sopenharmony_ci  size_t next_len_bucket = 4;
3101cb0ef41Sopenharmony_ci  size_t next_len_offset = 10;
3111cb0ef41Sopenharmony_ci  while (pos + len <= num_bytes && nodes[pos + len].u.cost <= min_cost) {
3121cb0ef41Sopenharmony_ci    /* We already reached (pos + len) with no more cost than the minimum
3131cb0ef41Sopenharmony_ci       possible cost of reaching anything from this pos, so there is no point in
3141cb0ef41Sopenharmony_ci       looking for lengths <= len. */
3151cb0ef41Sopenharmony_ci    ++len;
3161cb0ef41Sopenharmony_ci    if (len == next_len_offset) {
3171cb0ef41Sopenharmony_ci      /* We reached the next copy length code bucket, so we add one more
3181cb0ef41Sopenharmony_ci         extra bit to the minimum cost. */
3191cb0ef41Sopenharmony_ci      min_cost += 1.0f;
3201cb0ef41Sopenharmony_ci      next_len_offset += next_len_bucket;
3211cb0ef41Sopenharmony_ci      next_len_bucket *= 2;
3221cb0ef41Sopenharmony_ci    }
3231cb0ef41Sopenharmony_ci  }
3241cb0ef41Sopenharmony_ci  return len;
3251cb0ef41Sopenharmony_ci}
3261cb0ef41Sopenharmony_ci
3271cb0ef41Sopenharmony_ci/* REQUIRES: nodes[pos].cost < kInfinity
3281cb0ef41Sopenharmony_ci   REQUIRES: nodes[0..pos] satisfies that "ZopfliNode array invariant". */
3291cb0ef41Sopenharmony_cistatic uint32_t ComputeDistanceShortcut(const size_t block_start,
3301cb0ef41Sopenharmony_ci                                        const size_t pos,
3311cb0ef41Sopenharmony_ci                                        const size_t max_backward_limit,
3321cb0ef41Sopenharmony_ci                                        const size_t gap,
3331cb0ef41Sopenharmony_ci                                        const ZopfliNode* nodes) {
3341cb0ef41Sopenharmony_ci  const size_t clen = ZopfliNodeCopyLength(&nodes[pos]);
3351cb0ef41Sopenharmony_ci  const size_t ilen = nodes[pos].dcode_insert_length & 0x7FFFFFF;
3361cb0ef41Sopenharmony_ci  const size_t dist = ZopfliNodeCopyDistance(&nodes[pos]);
3371cb0ef41Sopenharmony_ci  /* Since |block_start + pos| is the end position of the command, the copy part
3381cb0ef41Sopenharmony_ci     starts from |block_start + pos - clen|. Distances that are greater than
3391cb0ef41Sopenharmony_ci     this or greater than |max_backward_limit| + |gap| are static dictionary
3401cb0ef41Sopenharmony_ci     references, and do not update the last distances.
3411cb0ef41Sopenharmony_ci     Also distance code 0 (last distance) does not update the last distances. */
3421cb0ef41Sopenharmony_ci  if (pos == 0) {
3431cb0ef41Sopenharmony_ci    return 0;
3441cb0ef41Sopenharmony_ci  } else if (dist + clen <= block_start + pos + gap &&
3451cb0ef41Sopenharmony_ci             dist <= max_backward_limit + gap &&
3461cb0ef41Sopenharmony_ci             ZopfliNodeDistanceCode(&nodes[pos]) > 0) {
3471cb0ef41Sopenharmony_ci    return (uint32_t)pos;
3481cb0ef41Sopenharmony_ci  } else {
3491cb0ef41Sopenharmony_ci    return nodes[pos - clen - ilen].u.shortcut;
3501cb0ef41Sopenharmony_ci  }
3511cb0ef41Sopenharmony_ci}
3521cb0ef41Sopenharmony_ci
3531cb0ef41Sopenharmony_ci/* Fills in dist_cache[0..3] with the last four distances (as defined by
3541cb0ef41Sopenharmony_ci   Section 4. of the Spec) that would be used at (block_start + pos) if we
3551cb0ef41Sopenharmony_ci   used the shortest path of commands from block_start, computed from
3561cb0ef41Sopenharmony_ci   nodes[0..pos]. The last four distances at block_start are in
3571cb0ef41Sopenharmony_ci   starting_dist_cache[0..3].
3581cb0ef41Sopenharmony_ci   REQUIRES: nodes[pos].cost < kInfinity
3591cb0ef41Sopenharmony_ci   REQUIRES: nodes[0..pos] satisfies that "ZopfliNode array invariant". */
3601cb0ef41Sopenharmony_cistatic void ComputeDistanceCache(const size_t pos,
3611cb0ef41Sopenharmony_ci                                 const int* starting_dist_cache,
3621cb0ef41Sopenharmony_ci                                 const ZopfliNode* nodes,
3631cb0ef41Sopenharmony_ci                                 int* dist_cache) {
3641cb0ef41Sopenharmony_ci  int idx = 0;
3651cb0ef41Sopenharmony_ci  size_t p = nodes[pos].u.shortcut;
3661cb0ef41Sopenharmony_ci  while (idx < 4 && p > 0) {
3671cb0ef41Sopenharmony_ci    const size_t ilen = nodes[p].dcode_insert_length & 0x7FFFFFF;
3681cb0ef41Sopenharmony_ci    const size_t clen = ZopfliNodeCopyLength(&nodes[p]);
3691cb0ef41Sopenharmony_ci    const size_t dist = ZopfliNodeCopyDistance(&nodes[p]);
3701cb0ef41Sopenharmony_ci    dist_cache[idx++] = (int)dist;
3711cb0ef41Sopenharmony_ci    /* Because of prerequisite, p >= clen + ilen >= 2. */
3721cb0ef41Sopenharmony_ci    p = nodes[p - clen - ilen].u.shortcut;
3731cb0ef41Sopenharmony_ci  }
3741cb0ef41Sopenharmony_ci  for (; idx < 4; ++idx) {
3751cb0ef41Sopenharmony_ci    dist_cache[idx] = *starting_dist_cache++;
3761cb0ef41Sopenharmony_ci  }
3771cb0ef41Sopenharmony_ci}
3781cb0ef41Sopenharmony_ci
3791cb0ef41Sopenharmony_ci/* Maintains "ZopfliNode array invariant" and pushes node to the queue, if it
3801cb0ef41Sopenharmony_ci   is eligible. */
3811cb0ef41Sopenharmony_cistatic void EvaluateNode(
3821cb0ef41Sopenharmony_ci    const size_t block_start, const size_t pos, const size_t max_backward_limit,
3831cb0ef41Sopenharmony_ci    const size_t gap, const int* starting_dist_cache,
3841cb0ef41Sopenharmony_ci    const ZopfliCostModel* model, StartPosQueue* queue, ZopfliNode* nodes) {
3851cb0ef41Sopenharmony_ci  /* Save cost, because ComputeDistanceCache invalidates it. */
3861cb0ef41Sopenharmony_ci  float node_cost = nodes[pos].u.cost;
3871cb0ef41Sopenharmony_ci  nodes[pos].u.shortcut = ComputeDistanceShortcut(
3881cb0ef41Sopenharmony_ci      block_start, pos, max_backward_limit, gap, nodes);
3891cb0ef41Sopenharmony_ci  if (node_cost <= ZopfliCostModelGetLiteralCosts(model, 0, pos)) {
3901cb0ef41Sopenharmony_ci    PosData posdata;
3911cb0ef41Sopenharmony_ci    posdata.pos = pos;
3921cb0ef41Sopenharmony_ci    posdata.cost = node_cost;
3931cb0ef41Sopenharmony_ci    posdata.costdiff = node_cost -
3941cb0ef41Sopenharmony_ci        ZopfliCostModelGetLiteralCosts(model, 0, pos);
3951cb0ef41Sopenharmony_ci    ComputeDistanceCache(
3961cb0ef41Sopenharmony_ci        pos, starting_dist_cache, nodes, posdata.distance_cache);
3971cb0ef41Sopenharmony_ci    StartPosQueuePush(queue, &posdata);
3981cb0ef41Sopenharmony_ci  }
3991cb0ef41Sopenharmony_ci}
4001cb0ef41Sopenharmony_ci
4011cb0ef41Sopenharmony_ci/* Returns longest copy length. */
4021cb0ef41Sopenharmony_cistatic size_t UpdateNodes(
4031cb0ef41Sopenharmony_ci    const size_t num_bytes, const size_t block_start, const size_t pos,
4041cb0ef41Sopenharmony_ci    const uint8_t* ringbuffer, const size_t ringbuffer_mask,
4051cb0ef41Sopenharmony_ci    const BrotliEncoderParams* params, const size_t max_backward_limit,
4061cb0ef41Sopenharmony_ci    const int* starting_dist_cache, const size_t num_matches,
4071cb0ef41Sopenharmony_ci    const BackwardMatch* matches, const ZopfliCostModel* model,
4081cb0ef41Sopenharmony_ci    StartPosQueue* queue, ZopfliNode* nodes) {
4091cb0ef41Sopenharmony_ci  const size_t stream_offset = params->stream_offset;
4101cb0ef41Sopenharmony_ci  const size_t cur_ix = block_start + pos;
4111cb0ef41Sopenharmony_ci  const size_t cur_ix_masked = cur_ix & ringbuffer_mask;
4121cb0ef41Sopenharmony_ci  const size_t max_distance = BROTLI_MIN(size_t, cur_ix, max_backward_limit);
4131cb0ef41Sopenharmony_ci  const size_t dictionary_start = BROTLI_MIN(size_t,
4141cb0ef41Sopenharmony_ci      cur_ix + stream_offset, max_backward_limit);
4151cb0ef41Sopenharmony_ci  const size_t max_len = num_bytes - pos;
4161cb0ef41Sopenharmony_ci  const size_t max_zopfli_len = MaxZopfliLen(params);
4171cb0ef41Sopenharmony_ci  const size_t max_iters = MaxZopfliCandidates(params);
4181cb0ef41Sopenharmony_ci  size_t min_len;
4191cb0ef41Sopenharmony_ci  size_t result = 0;
4201cb0ef41Sopenharmony_ci  size_t k;
4211cb0ef41Sopenharmony_ci  size_t gap = 0;
4221cb0ef41Sopenharmony_ci
4231cb0ef41Sopenharmony_ci  EvaluateNode(block_start + stream_offset, pos, max_backward_limit, gap,
4241cb0ef41Sopenharmony_ci      starting_dist_cache, model, queue, nodes);
4251cb0ef41Sopenharmony_ci
4261cb0ef41Sopenharmony_ci  {
4271cb0ef41Sopenharmony_ci    const PosData* posdata = StartPosQueueAt(queue, 0);
4281cb0ef41Sopenharmony_ci    float min_cost = (posdata->cost + ZopfliCostModelGetMinCostCmd(model) +
4291cb0ef41Sopenharmony_ci        ZopfliCostModelGetLiteralCosts(model, posdata->pos, pos));
4301cb0ef41Sopenharmony_ci    min_len = ComputeMinimumCopyLength(min_cost, nodes, num_bytes, pos);
4311cb0ef41Sopenharmony_ci  }
4321cb0ef41Sopenharmony_ci
4331cb0ef41Sopenharmony_ci  /* Go over the command starting positions in order of increasing cost
4341cb0ef41Sopenharmony_ci     difference. */
4351cb0ef41Sopenharmony_ci  for (k = 0; k < max_iters && k < StartPosQueueSize(queue); ++k) {
4361cb0ef41Sopenharmony_ci    const PosData* posdata = StartPosQueueAt(queue, k);
4371cb0ef41Sopenharmony_ci    const size_t start = posdata->pos;
4381cb0ef41Sopenharmony_ci    const uint16_t inscode = GetInsertLengthCode(pos - start);
4391cb0ef41Sopenharmony_ci    const float start_costdiff = posdata->costdiff;
4401cb0ef41Sopenharmony_ci    const float base_cost = start_costdiff + (float)GetInsertExtra(inscode) +
4411cb0ef41Sopenharmony_ci        ZopfliCostModelGetLiteralCosts(model, 0, pos);
4421cb0ef41Sopenharmony_ci
4431cb0ef41Sopenharmony_ci    /* Look for last distance matches using the distance cache from this
4441cb0ef41Sopenharmony_ci       starting position. */
4451cb0ef41Sopenharmony_ci    size_t best_len = min_len - 1;
4461cb0ef41Sopenharmony_ci    size_t j = 0;
4471cb0ef41Sopenharmony_ci    for (; j < BROTLI_NUM_DISTANCE_SHORT_CODES && best_len < max_len; ++j) {
4481cb0ef41Sopenharmony_ci      const size_t idx = kDistanceCacheIndex[j];
4491cb0ef41Sopenharmony_ci      const size_t backward =
4501cb0ef41Sopenharmony_ci          (size_t)(posdata->distance_cache[idx] + kDistanceCacheOffset[j]);
4511cb0ef41Sopenharmony_ci      size_t prev_ix = cur_ix - backward;
4521cb0ef41Sopenharmony_ci      size_t len = 0;
4531cb0ef41Sopenharmony_ci      uint8_t continuation = ringbuffer[cur_ix_masked + best_len];
4541cb0ef41Sopenharmony_ci      if (cur_ix_masked + best_len > ringbuffer_mask) {
4551cb0ef41Sopenharmony_ci        break;
4561cb0ef41Sopenharmony_ci      }
4571cb0ef41Sopenharmony_ci      if (BROTLI_PREDICT_FALSE(backward > dictionary_start + gap)) {
4581cb0ef41Sopenharmony_ci        /* Word dictionary -> ignore. */
4591cb0ef41Sopenharmony_ci        continue;
4601cb0ef41Sopenharmony_ci      }
4611cb0ef41Sopenharmony_ci      if (backward <= max_distance) {
4621cb0ef41Sopenharmony_ci        /* Regular backward reference. */
4631cb0ef41Sopenharmony_ci        if (prev_ix >= cur_ix) {
4641cb0ef41Sopenharmony_ci          continue;
4651cb0ef41Sopenharmony_ci        }
4661cb0ef41Sopenharmony_ci
4671cb0ef41Sopenharmony_ci        prev_ix &= ringbuffer_mask;
4681cb0ef41Sopenharmony_ci        if (prev_ix + best_len > ringbuffer_mask ||
4691cb0ef41Sopenharmony_ci            continuation != ringbuffer[prev_ix + best_len]) {
4701cb0ef41Sopenharmony_ci          continue;
4711cb0ef41Sopenharmony_ci        }
4721cb0ef41Sopenharmony_ci        len = FindMatchLengthWithLimit(&ringbuffer[prev_ix],
4731cb0ef41Sopenharmony_ci                                       &ringbuffer[cur_ix_masked],
4741cb0ef41Sopenharmony_ci                                       max_len);
4751cb0ef41Sopenharmony_ci      } else {
4761cb0ef41Sopenharmony_ci        /* "Gray" area. It is addressable by decoder, but this encoder
4771cb0ef41Sopenharmony_ci           instance does not have that data -> should not touch it. */
4781cb0ef41Sopenharmony_ci        continue;
4791cb0ef41Sopenharmony_ci      }
4801cb0ef41Sopenharmony_ci      {
4811cb0ef41Sopenharmony_ci        const float dist_cost = base_cost +
4821cb0ef41Sopenharmony_ci            ZopfliCostModelGetDistanceCost(model, j);
4831cb0ef41Sopenharmony_ci        size_t l;
4841cb0ef41Sopenharmony_ci        for (l = best_len + 1; l <= len; ++l) {
4851cb0ef41Sopenharmony_ci          const uint16_t copycode = GetCopyLengthCode(l);
4861cb0ef41Sopenharmony_ci          const uint16_t cmdcode =
4871cb0ef41Sopenharmony_ci              CombineLengthCodes(inscode, copycode, j == 0);
4881cb0ef41Sopenharmony_ci          const float cost = (cmdcode < 128 ? base_cost : dist_cost) +
4891cb0ef41Sopenharmony_ci              (float)GetCopyExtra(copycode) +
4901cb0ef41Sopenharmony_ci              ZopfliCostModelGetCommandCost(model, cmdcode);
4911cb0ef41Sopenharmony_ci          if (cost < nodes[pos + l].u.cost) {
4921cb0ef41Sopenharmony_ci            UpdateZopfliNode(nodes, pos, start, l, l, backward, j + 1, cost);
4931cb0ef41Sopenharmony_ci            result = BROTLI_MAX(size_t, result, l);
4941cb0ef41Sopenharmony_ci          }
4951cb0ef41Sopenharmony_ci          best_len = l;
4961cb0ef41Sopenharmony_ci        }
4971cb0ef41Sopenharmony_ci      }
4981cb0ef41Sopenharmony_ci    }
4991cb0ef41Sopenharmony_ci
5001cb0ef41Sopenharmony_ci    /* At higher iterations look only for new last distance matches, since
5011cb0ef41Sopenharmony_ci       looking only for new command start positions with the same distances
5021cb0ef41Sopenharmony_ci       does not help much. */
5031cb0ef41Sopenharmony_ci    if (k >= 2) continue;
5041cb0ef41Sopenharmony_ci
5051cb0ef41Sopenharmony_ci    {
5061cb0ef41Sopenharmony_ci      /* Loop through all possible copy lengths at this position. */
5071cb0ef41Sopenharmony_ci      size_t len = min_len;
5081cb0ef41Sopenharmony_ci      for (j = 0; j < num_matches; ++j) {
5091cb0ef41Sopenharmony_ci        BackwardMatch match = matches[j];
5101cb0ef41Sopenharmony_ci        size_t dist = match.distance;
5111cb0ef41Sopenharmony_ci        BROTLI_BOOL is_dictionary_match =
5121cb0ef41Sopenharmony_ci            TO_BROTLI_BOOL(dist > dictionary_start + gap);
5131cb0ef41Sopenharmony_ci        /* We already tried all possible last distance matches, so we can use
5141cb0ef41Sopenharmony_ci           normal distance code here. */
5151cb0ef41Sopenharmony_ci        size_t dist_code = dist + BROTLI_NUM_DISTANCE_SHORT_CODES - 1;
5161cb0ef41Sopenharmony_ci        uint16_t dist_symbol;
5171cb0ef41Sopenharmony_ci        uint32_t distextra;
5181cb0ef41Sopenharmony_ci        uint32_t distnumextra;
5191cb0ef41Sopenharmony_ci        float dist_cost;
5201cb0ef41Sopenharmony_ci        size_t max_match_len;
5211cb0ef41Sopenharmony_ci        PrefixEncodeCopyDistance(
5221cb0ef41Sopenharmony_ci            dist_code, params->dist.num_direct_distance_codes,
5231cb0ef41Sopenharmony_ci            params->dist.distance_postfix_bits, &dist_symbol, &distextra);
5241cb0ef41Sopenharmony_ci        distnumextra = dist_symbol >> 10;
5251cb0ef41Sopenharmony_ci        dist_cost = base_cost + (float)distnumextra +
5261cb0ef41Sopenharmony_ci            ZopfliCostModelGetDistanceCost(model, dist_symbol & 0x3FF);
5271cb0ef41Sopenharmony_ci
5281cb0ef41Sopenharmony_ci        /* Try all copy lengths up until the maximum copy length corresponding
5291cb0ef41Sopenharmony_ci           to this distance. If the distance refers to the static dictionary, or
5301cb0ef41Sopenharmony_ci           the maximum length is long enough, try only one maximum length. */
5311cb0ef41Sopenharmony_ci        max_match_len = BackwardMatchLength(&match);
5321cb0ef41Sopenharmony_ci        if (len < max_match_len &&
5331cb0ef41Sopenharmony_ci            (is_dictionary_match || max_match_len > max_zopfli_len)) {
5341cb0ef41Sopenharmony_ci          len = max_match_len;
5351cb0ef41Sopenharmony_ci        }
5361cb0ef41Sopenharmony_ci        for (; len <= max_match_len; ++len) {
5371cb0ef41Sopenharmony_ci          const size_t len_code =
5381cb0ef41Sopenharmony_ci              is_dictionary_match ? BackwardMatchLengthCode(&match) : len;
5391cb0ef41Sopenharmony_ci          const uint16_t copycode = GetCopyLengthCode(len_code);
5401cb0ef41Sopenharmony_ci          const uint16_t cmdcode = CombineLengthCodes(inscode, copycode, 0);
5411cb0ef41Sopenharmony_ci          const float cost = dist_cost + (float)GetCopyExtra(copycode) +
5421cb0ef41Sopenharmony_ci              ZopfliCostModelGetCommandCost(model, cmdcode);
5431cb0ef41Sopenharmony_ci          if (cost < nodes[pos + len].u.cost) {
5441cb0ef41Sopenharmony_ci            UpdateZopfliNode(nodes, pos, start, len, len_code, dist, 0, cost);
5451cb0ef41Sopenharmony_ci            result = BROTLI_MAX(size_t, result, len);
5461cb0ef41Sopenharmony_ci          }
5471cb0ef41Sopenharmony_ci        }
5481cb0ef41Sopenharmony_ci      }
5491cb0ef41Sopenharmony_ci    }
5501cb0ef41Sopenharmony_ci  }
5511cb0ef41Sopenharmony_ci  return result;
5521cb0ef41Sopenharmony_ci}
5531cb0ef41Sopenharmony_ci
5541cb0ef41Sopenharmony_cistatic size_t ComputeShortestPathFromNodes(size_t num_bytes,
5551cb0ef41Sopenharmony_ci    ZopfliNode* nodes) {
5561cb0ef41Sopenharmony_ci  size_t index = num_bytes;
5571cb0ef41Sopenharmony_ci  size_t num_commands = 0;
5581cb0ef41Sopenharmony_ci  while ((nodes[index].dcode_insert_length & 0x7FFFFFF) == 0 &&
5591cb0ef41Sopenharmony_ci      nodes[index].length == 1) --index;
5601cb0ef41Sopenharmony_ci  nodes[index].u.next = BROTLI_UINT32_MAX;
5611cb0ef41Sopenharmony_ci  while (index != 0) {
5621cb0ef41Sopenharmony_ci    size_t len = ZopfliNodeCommandLength(&nodes[index]);
5631cb0ef41Sopenharmony_ci    index -= len;
5641cb0ef41Sopenharmony_ci    nodes[index].u.next = (uint32_t)len;
5651cb0ef41Sopenharmony_ci    num_commands++;
5661cb0ef41Sopenharmony_ci  }
5671cb0ef41Sopenharmony_ci  return num_commands;
5681cb0ef41Sopenharmony_ci}
5691cb0ef41Sopenharmony_ci
5701cb0ef41Sopenharmony_ci/* REQUIRES: nodes != NULL and len(nodes) >= num_bytes + 1 */
5711cb0ef41Sopenharmony_civoid BrotliZopfliCreateCommands(const size_t num_bytes,
5721cb0ef41Sopenharmony_ci    const size_t block_start, const ZopfliNode* nodes, int* dist_cache,
5731cb0ef41Sopenharmony_ci    size_t* last_insert_len, const BrotliEncoderParams* params,
5741cb0ef41Sopenharmony_ci    Command* commands, size_t* num_literals) {
5751cb0ef41Sopenharmony_ci  const size_t stream_offset = params->stream_offset;
5761cb0ef41Sopenharmony_ci  const size_t max_backward_limit = BROTLI_MAX_BACKWARD_LIMIT(params->lgwin);
5771cb0ef41Sopenharmony_ci  size_t pos = 0;
5781cb0ef41Sopenharmony_ci  uint32_t offset = nodes[0].u.next;
5791cb0ef41Sopenharmony_ci  size_t i;
5801cb0ef41Sopenharmony_ci  size_t gap = 0;
5811cb0ef41Sopenharmony_ci  for (i = 0; offset != BROTLI_UINT32_MAX; i++) {
5821cb0ef41Sopenharmony_ci    const ZopfliNode* next = &nodes[pos + offset];
5831cb0ef41Sopenharmony_ci    size_t copy_length = ZopfliNodeCopyLength(next);
5841cb0ef41Sopenharmony_ci    size_t insert_length = next->dcode_insert_length & 0x7FFFFFF;
5851cb0ef41Sopenharmony_ci    pos += insert_length;
5861cb0ef41Sopenharmony_ci    offset = next->u.next;
5871cb0ef41Sopenharmony_ci    if (i == 0) {
5881cb0ef41Sopenharmony_ci      insert_length += *last_insert_len;
5891cb0ef41Sopenharmony_ci      *last_insert_len = 0;
5901cb0ef41Sopenharmony_ci    }
5911cb0ef41Sopenharmony_ci    {
5921cb0ef41Sopenharmony_ci      size_t distance = ZopfliNodeCopyDistance(next);
5931cb0ef41Sopenharmony_ci      size_t len_code = ZopfliNodeLengthCode(next);
5941cb0ef41Sopenharmony_ci      size_t dictionary_start = BROTLI_MIN(size_t,
5951cb0ef41Sopenharmony_ci          block_start + pos + stream_offset, max_backward_limit);
5961cb0ef41Sopenharmony_ci      BROTLI_BOOL is_dictionary =
5971cb0ef41Sopenharmony_ci          TO_BROTLI_BOOL(distance > dictionary_start + gap);
5981cb0ef41Sopenharmony_ci      size_t dist_code = ZopfliNodeDistanceCode(next);
5991cb0ef41Sopenharmony_ci      InitCommand(&commands[i], &params->dist, insert_length,
6001cb0ef41Sopenharmony_ci          copy_length, (int)len_code - (int)copy_length, dist_code);
6011cb0ef41Sopenharmony_ci
6021cb0ef41Sopenharmony_ci      if (!is_dictionary && dist_code > 0) {
6031cb0ef41Sopenharmony_ci        dist_cache[3] = dist_cache[2];
6041cb0ef41Sopenharmony_ci        dist_cache[2] = dist_cache[1];
6051cb0ef41Sopenharmony_ci        dist_cache[1] = dist_cache[0];
6061cb0ef41Sopenharmony_ci        dist_cache[0] = (int)distance;
6071cb0ef41Sopenharmony_ci      }
6081cb0ef41Sopenharmony_ci    }
6091cb0ef41Sopenharmony_ci
6101cb0ef41Sopenharmony_ci    *num_literals += insert_length;
6111cb0ef41Sopenharmony_ci    pos += copy_length;
6121cb0ef41Sopenharmony_ci  }
6131cb0ef41Sopenharmony_ci  *last_insert_len += num_bytes - pos;
6141cb0ef41Sopenharmony_ci}
6151cb0ef41Sopenharmony_ci
6161cb0ef41Sopenharmony_cistatic size_t ZopfliIterate(size_t num_bytes, size_t position,
6171cb0ef41Sopenharmony_ci    const uint8_t* ringbuffer, size_t ringbuffer_mask,
6181cb0ef41Sopenharmony_ci    const BrotliEncoderParams* params, const size_t gap, const int* dist_cache,
6191cb0ef41Sopenharmony_ci    const ZopfliCostModel* model, const uint32_t* num_matches,
6201cb0ef41Sopenharmony_ci    const BackwardMatch* matches, ZopfliNode* nodes) {
6211cb0ef41Sopenharmony_ci  const size_t stream_offset = params->stream_offset;
6221cb0ef41Sopenharmony_ci  const size_t max_backward_limit = BROTLI_MAX_BACKWARD_LIMIT(params->lgwin);
6231cb0ef41Sopenharmony_ci  const size_t max_zopfli_len = MaxZopfliLen(params);
6241cb0ef41Sopenharmony_ci  StartPosQueue queue;
6251cb0ef41Sopenharmony_ci  size_t cur_match_pos = 0;
6261cb0ef41Sopenharmony_ci  size_t i;
6271cb0ef41Sopenharmony_ci  nodes[0].length = 0;
6281cb0ef41Sopenharmony_ci  nodes[0].u.cost = 0;
6291cb0ef41Sopenharmony_ci  InitStartPosQueue(&queue);
6301cb0ef41Sopenharmony_ci  for (i = 0; i + 3 < num_bytes; i++) {
6311cb0ef41Sopenharmony_ci    size_t skip = UpdateNodes(num_bytes, position, i, ringbuffer,
6321cb0ef41Sopenharmony_ci        ringbuffer_mask, params, max_backward_limit, dist_cache,
6331cb0ef41Sopenharmony_ci        num_matches[i], &matches[cur_match_pos], model, &queue, nodes);
6341cb0ef41Sopenharmony_ci    if (skip < BROTLI_LONG_COPY_QUICK_STEP) skip = 0;
6351cb0ef41Sopenharmony_ci    cur_match_pos += num_matches[i];
6361cb0ef41Sopenharmony_ci    if (num_matches[i] == 1 &&
6371cb0ef41Sopenharmony_ci        BackwardMatchLength(&matches[cur_match_pos - 1]) > max_zopfli_len) {
6381cb0ef41Sopenharmony_ci      skip = BROTLI_MAX(size_t,
6391cb0ef41Sopenharmony_ci          BackwardMatchLength(&matches[cur_match_pos - 1]), skip);
6401cb0ef41Sopenharmony_ci    }
6411cb0ef41Sopenharmony_ci    if (skip > 1) {
6421cb0ef41Sopenharmony_ci      skip--;
6431cb0ef41Sopenharmony_ci      while (skip) {
6441cb0ef41Sopenharmony_ci        i++;
6451cb0ef41Sopenharmony_ci        if (i + 3 >= num_bytes) break;
6461cb0ef41Sopenharmony_ci        EvaluateNode(position + stream_offset, i, max_backward_limit, gap,
6471cb0ef41Sopenharmony_ci            dist_cache, model, &queue, nodes);
6481cb0ef41Sopenharmony_ci        cur_match_pos += num_matches[i];
6491cb0ef41Sopenharmony_ci        skip--;
6501cb0ef41Sopenharmony_ci      }
6511cb0ef41Sopenharmony_ci    }
6521cb0ef41Sopenharmony_ci  }
6531cb0ef41Sopenharmony_ci  return ComputeShortestPathFromNodes(num_bytes, nodes);
6541cb0ef41Sopenharmony_ci}
6551cb0ef41Sopenharmony_ci
6561cb0ef41Sopenharmony_ci/* REQUIRES: nodes != NULL and len(nodes) >= num_bytes + 1 */
6571cb0ef41Sopenharmony_cisize_t BrotliZopfliComputeShortestPath(MemoryManager* m, size_t num_bytes,
6581cb0ef41Sopenharmony_ci    size_t position, const uint8_t* ringbuffer, size_t ringbuffer_mask,
6591cb0ef41Sopenharmony_ci    ContextLut literal_context_lut, const BrotliEncoderParams* params,
6601cb0ef41Sopenharmony_ci    const int* dist_cache, Hasher* hasher, ZopfliNode* nodes) {
6611cb0ef41Sopenharmony_ci  const size_t stream_offset = params->stream_offset;
6621cb0ef41Sopenharmony_ci  const size_t max_backward_limit = BROTLI_MAX_BACKWARD_LIMIT(params->lgwin);
6631cb0ef41Sopenharmony_ci  const size_t max_zopfli_len = MaxZopfliLen(params);
6641cb0ef41Sopenharmony_ci  ZopfliCostModel model;
6651cb0ef41Sopenharmony_ci  StartPosQueue queue;
6661cb0ef41Sopenharmony_ci  BackwardMatch matches[2 * (MAX_NUM_MATCHES_H10 + 64)];
6671cb0ef41Sopenharmony_ci  const size_t store_end = num_bytes >= StoreLookaheadH10() ?
6681cb0ef41Sopenharmony_ci      position + num_bytes - StoreLookaheadH10() + 1 : position;
6691cb0ef41Sopenharmony_ci  size_t i;
6701cb0ef41Sopenharmony_ci  size_t gap = 0;
6711cb0ef41Sopenharmony_ci  size_t lz_matches_offset = 0;
6721cb0ef41Sopenharmony_ci  BROTLI_UNUSED(literal_context_lut);
6731cb0ef41Sopenharmony_ci  nodes[0].length = 0;
6741cb0ef41Sopenharmony_ci  nodes[0].u.cost = 0;
6751cb0ef41Sopenharmony_ci  InitZopfliCostModel(m, &model, &params->dist, num_bytes);
6761cb0ef41Sopenharmony_ci  if (BROTLI_IS_OOM(m)) return 0;
6771cb0ef41Sopenharmony_ci  ZopfliCostModelSetFromLiteralCosts(
6781cb0ef41Sopenharmony_ci      &model, position, ringbuffer, ringbuffer_mask);
6791cb0ef41Sopenharmony_ci  InitStartPosQueue(&queue);
6801cb0ef41Sopenharmony_ci  for (i = 0; i + HashTypeLengthH10() - 1 < num_bytes; i++) {
6811cb0ef41Sopenharmony_ci    const size_t pos = position + i;
6821cb0ef41Sopenharmony_ci    const size_t max_distance = BROTLI_MIN(size_t, pos, max_backward_limit);
6831cb0ef41Sopenharmony_ci    const size_t dictionary_start = BROTLI_MIN(size_t,
6841cb0ef41Sopenharmony_ci        pos + stream_offset, max_backward_limit);
6851cb0ef41Sopenharmony_ci    size_t skip;
6861cb0ef41Sopenharmony_ci    size_t num_matches;
6871cb0ef41Sopenharmony_ci    num_matches = FindAllMatchesH10(&hasher->privat._H10,
6881cb0ef41Sopenharmony_ci        &params->dictionary,
6891cb0ef41Sopenharmony_ci        ringbuffer, ringbuffer_mask, pos, num_bytes - i, max_distance,
6901cb0ef41Sopenharmony_ci        dictionary_start + gap, params, &matches[lz_matches_offset]);
6911cb0ef41Sopenharmony_ci    if (num_matches > 0 &&
6921cb0ef41Sopenharmony_ci        BackwardMatchLength(&matches[num_matches - 1]) > max_zopfli_len) {
6931cb0ef41Sopenharmony_ci      matches[0] = matches[num_matches - 1];
6941cb0ef41Sopenharmony_ci      num_matches = 1;
6951cb0ef41Sopenharmony_ci    }
6961cb0ef41Sopenharmony_ci    skip = UpdateNodes(num_bytes, position, i, ringbuffer, ringbuffer_mask,
6971cb0ef41Sopenharmony_ci        params, max_backward_limit, dist_cache, num_matches, matches, &model,
6981cb0ef41Sopenharmony_ci        &queue, nodes);
6991cb0ef41Sopenharmony_ci    if (skip < BROTLI_LONG_COPY_QUICK_STEP) skip = 0;
7001cb0ef41Sopenharmony_ci    if (num_matches == 1 && BackwardMatchLength(&matches[0]) > max_zopfli_len) {
7011cb0ef41Sopenharmony_ci      skip = BROTLI_MAX(size_t, BackwardMatchLength(&matches[0]), skip);
7021cb0ef41Sopenharmony_ci    }
7031cb0ef41Sopenharmony_ci    if (skip > 1) {
7041cb0ef41Sopenharmony_ci      /* Add the tail of the copy to the hasher. */
7051cb0ef41Sopenharmony_ci      StoreRangeH10(&hasher->privat._H10,
7061cb0ef41Sopenharmony_ci          ringbuffer, ringbuffer_mask, pos + 1, BROTLI_MIN(
7071cb0ef41Sopenharmony_ci          size_t, pos + skip, store_end));
7081cb0ef41Sopenharmony_ci      skip--;
7091cb0ef41Sopenharmony_ci      while (skip) {
7101cb0ef41Sopenharmony_ci        i++;
7111cb0ef41Sopenharmony_ci        if (i + HashTypeLengthH10() - 1 >= num_bytes) break;
7121cb0ef41Sopenharmony_ci        EvaluateNode(position + stream_offset, i, max_backward_limit, gap,
7131cb0ef41Sopenharmony_ci            dist_cache, &model, &queue, nodes);
7141cb0ef41Sopenharmony_ci        skip--;
7151cb0ef41Sopenharmony_ci      }
7161cb0ef41Sopenharmony_ci    }
7171cb0ef41Sopenharmony_ci  }
7181cb0ef41Sopenharmony_ci  CleanupZopfliCostModel(m, &model);
7191cb0ef41Sopenharmony_ci  return ComputeShortestPathFromNodes(num_bytes, nodes);
7201cb0ef41Sopenharmony_ci}
7211cb0ef41Sopenharmony_ci
7221cb0ef41Sopenharmony_civoid BrotliCreateZopfliBackwardReferences(MemoryManager* m, size_t num_bytes,
7231cb0ef41Sopenharmony_ci    size_t position, const uint8_t* ringbuffer, size_t ringbuffer_mask,
7241cb0ef41Sopenharmony_ci    ContextLut literal_context_lut, const BrotliEncoderParams* params,
7251cb0ef41Sopenharmony_ci    Hasher* hasher, int* dist_cache, size_t* last_insert_len,
7261cb0ef41Sopenharmony_ci    Command* commands, size_t* num_commands, size_t* num_literals) {
7271cb0ef41Sopenharmony_ci  ZopfliNode* nodes = BROTLI_ALLOC(m, ZopfliNode, num_bytes + 1);
7281cb0ef41Sopenharmony_ci  if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(nodes)) return;
7291cb0ef41Sopenharmony_ci  BrotliInitZopfliNodes(nodes, num_bytes + 1);
7301cb0ef41Sopenharmony_ci  *num_commands += BrotliZopfliComputeShortestPath(m, num_bytes,
7311cb0ef41Sopenharmony_ci      position, ringbuffer, ringbuffer_mask, literal_context_lut, params,
7321cb0ef41Sopenharmony_ci      dist_cache, hasher, nodes);
7331cb0ef41Sopenharmony_ci  if (BROTLI_IS_OOM(m)) return;
7341cb0ef41Sopenharmony_ci  BrotliZopfliCreateCommands(num_bytes, position, nodes, dist_cache,
7351cb0ef41Sopenharmony_ci      last_insert_len, params, commands, num_literals);
7361cb0ef41Sopenharmony_ci  BROTLI_FREE(m, nodes);
7371cb0ef41Sopenharmony_ci}
7381cb0ef41Sopenharmony_ci
7391cb0ef41Sopenharmony_civoid BrotliCreateHqZopfliBackwardReferences(MemoryManager* m, size_t num_bytes,
7401cb0ef41Sopenharmony_ci    size_t position, const uint8_t* ringbuffer, size_t ringbuffer_mask,
7411cb0ef41Sopenharmony_ci    ContextLut literal_context_lut, const BrotliEncoderParams* params,
7421cb0ef41Sopenharmony_ci    Hasher* hasher, int* dist_cache, size_t* last_insert_len,
7431cb0ef41Sopenharmony_ci    Command* commands, size_t* num_commands, size_t* num_literals) {
7441cb0ef41Sopenharmony_ci  const size_t stream_offset = params->stream_offset;
7451cb0ef41Sopenharmony_ci  const size_t max_backward_limit = BROTLI_MAX_BACKWARD_LIMIT(params->lgwin);
7461cb0ef41Sopenharmony_ci  uint32_t* num_matches = BROTLI_ALLOC(m, uint32_t, num_bytes);
7471cb0ef41Sopenharmony_ci  size_t matches_size = 4 * num_bytes;
7481cb0ef41Sopenharmony_ci  const size_t store_end = num_bytes >= StoreLookaheadH10() ?
7491cb0ef41Sopenharmony_ci      position + num_bytes - StoreLookaheadH10() + 1 : position;
7501cb0ef41Sopenharmony_ci  size_t cur_match_pos = 0;
7511cb0ef41Sopenharmony_ci  size_t i;
7521cb0ef41Sopenharmony_ci  size_t orig_num_literals;
7531cb0ef41Sopenharmony_ci  size_t orig_last_insert_len;
7541cb0ef41Sopenharmony_ci  int orig_dist_cache[4];
7551cb0ef41Sopenharmony_ci  size_t orig_num_commands;
7561cb0ef41Sopenharmony_ci  ZopfliCostModel model;
7571cb0ef41Sopenharmony_ci  ZopfliNode* nodes;
7581cb0ef41Sopenharmony_ci  BackwardMatch* matches = BROTLI_ALLOC(m, BackwardMatch, matches_size);
7591cb0ef41Sopenharmony_ci  size_t gap = 0;
7601cb0ef41Sopenharmony_ci  size_t shadow_matches = 0;
7611cb0ef41Sopenharmony_ci  BROTLI_UNUSED(literal_context_lut);
7621cb0ef41Sopenharmony_ci  if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(num_matches) ||
7631cb0ef41Sopenharmony_ci      BROTLI_IS_NULL(matches)) {
7641cb0ef41Sopenharmony_ci    return;
7651cb0ef41Sopenharmony_ci  }
7661cb0ef41Sopenharmony_ci  for (i = 0; i + HashTypeLengthH10() - 1 < num_bytes; ++i) {
7671cb0ef41Sopenharmony_ci    const size_t pos = position + i;
7681cb0ef41Sopenharmony_ci    size_t max_distance = BROTLI_MIN(size_t, pos, max_backward_limit);
7691cb0ef41Sopenharmony_ci    size_t dictionary_start = BROTLI_MIN(size_t,
7701cb0ef41Sopenharmony_ci        pos + stream_offset, max_backward_limit);
7711cb0ef41Sopenharmony_ci    size_t max_length = num_bytes - i;
7721cb0ef41Sopenharmony_ci    size_t num_found_matches;
7731cb0ef41Sopenharmony_ci    size_t cur_match_end;
7741cb0ef41Sopenharmony_ci    size_t j;
7751cb0ef41Sopenharmony_ci    /* Ensure that we have enough free slots. */
7761cb0ef41Sopenharmony_ci    BROTLI_ENSURE_CAPACITY(m, BackwardMatch, matches, matches_size,
7771cb0ef41Sopenharmony_ci        cur_match_pos + MAX_NUM_MATCHES_H10 + shadow_matches);
7781cb0ef41Sopenharmony_ci    if (BROTLI_IS_OOM(m)) return;
7791cb0ef41Sopenharmony_ci    num_found_matches = FindAllMatchesH10(&hasher->privat._H10,
7801cb0ef41Sopenharmony_ci        &params->dictionary,
7811cb0ef41Sopenharmony_ci        ringbuffer, ringbuffer_mask, pos, max_length,
7821cb0ef41Sopenharmony_ci        max_distance, dictionary_start + gap, params,
7831cb0ef41Sopenharmony_ci        &matches[cur_match_pos + shadow_matches]);
7841cb0ef41Sopenharmony_ci    cur_match_end = cur_match_pos + num_found_matches;
7851cb0ef41Sopenharmony_ci    for (j = cur_match_pos; j + 1 < cur_match_end; ++j) {
7861cb0ef41Sopenharmony_ci      BROTLI_DCHECK(BackwardMatchLength(&matches[j]) <=
7871cb0ef41Sopenharmony_ci          BackwardMatchLength(&matches[j + 1]));
7881cb0ef41Sopenharmony_ci    }
7891cb0ef41Sopenharmony_ci    num_matches[i] = (uint32_t)num_found_matches;
7901cb0ef41Sopenharmony_ci    if (num_found_matches > 0) {
7911cb0ef41Sopenharmony_ci      const size_t match_len = BackwardMatchLength(&matches[cur_match_end - 1]);
7921cb0ef41Sopenharmony_ci      if (match_len > MAX_ZOPFLI_LEN_QUALITY_11) {
7931cb0ef41Sopenharmony_ci        const size_t skip = match_len - 1;
7941cb0ef41Sopenharmony_ci        matches[cur_match_pos++] = matches[cur_match_end - 1];
7951cb0ef41Sopenharmony_ci        num_matches[i] = 1;
7961cb0ef41Sopenharmony_ci        /* Add the tail of the copy to the hasher. */
7971cb0ef41Sopenharmony_ci        StoreRangeH10(&hasher->privat._H10,
7981cb0ef41Sopenharmony_ci                      ringbuffer, ringbuffer_mask, pos + 1,
7991cb0ef41Sopenharmony_ci                      BROTLI_MIN(size_t, pos + match_len, store_end));
8001cb0ef41Sopenharmony_ci        memset(&num_matches[i + 1], 0, skip * sizeof(num_matches[0]));
8011cb0ef41Sopenharmony_ci        i += skip;
8021cb0ef41Sopenharmony_ci      } else {
8031cb0ef41Sopenharmony_ci        cur_match_pos = cur_match_end;
8041cb0ef41Sopenharmony_ci      }
8051cb0ef41Sopenharmony_ci    }
8061cb0ef41Sopenharmony_ci  }
8071cb0ef41Sopenharmony_ci  orig_num_literals = *num_literals;
8081cb0ef41Sopenharmony_ci  orig_last_insert_len = *last_insert_len;
8091cb0ef41Sopenharmony_ci  memcpy(orig_dist_cache, dist_cache, 4 * sizeof(dist_cache[0]));
8101cb0ef41Sopenharmony_ci  orig_num_commands = *num_commands;
8111cb0ef41Sopenharmony_ci  nodes = BROTLI_ALLOC(m, ZopfliNode, num_bytes + 1);
8121cb0ef41Sopenharmony_ci  if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(nodes)) return;
8131cb0ef41Sopenharmony_ci  InitZopfliCostModel(m, &model, &params->dist, num_bytes);
8141cb0ef41Sopenharmony_ci  if (BROTLI_IS_OOM(m)) return;
8151cb0ef41Sopenharmony_ci  for (i = 0; i < 2; i++) {
8161cb0ef41Sopenharmony_ci    BrotliInitZopfliNodes(nodes, num_bytes + 1);
8171cb0ef41Sopenharmony_ci    if (i == 0) {
8181cb0ef41Sopenharmony_ci      ZopfliCostModelSetFromLiteralCosts(
8191cb0ef41Sopenharmony_ci          &model, position, ringbuffer, ringbuffer_mask);
8201cb0ef41Sopenharmony_ci    } else {
8211cb0ef41Sopenharmony_ci      ZopfliCostModelSetFromCommands(&model, position, ringbuffer,
8221cb0ef41Sopenharmony_ci          ringbuffer_mask, commands, *num_commands - orig_num_commands,
8231cb0ef41Sopenharmony_ci          orig_last_insert_len);
8241cb0ef41Sopenharmony_ci    }
8251cb0ef41Sopenharmony_ci    *num_commands = orig_num_commands;
8261cb0ef41Sopenharmony_ci    *num_literals = orig_num_literals;
8271cb0ef41Sopenharmony_ci    *last_insert_len = orig_last_insert_len;
8281cb0ef41Sopenharmony_ci    memcpy(dist_cache, orig_dist_cache, 4 * sizeof(dist_cache[0]));
8291cb0ef41Sopenharmony_ci    *num_commands += ZopfliIterate(num_bytes, position, ringbuffer,
8301cb0ef41Sopenharmony_ci        ringbuffer_mask, params, gap, dist_cache, &model, num_matches, matches,
8311cb0ef41Sopenharmony_ci        nodes);
8321cb0ef41Sopenharmony_ci    BrotliZopfliCreateCommands(num_bytes, position, nodes, dist_cache,
8331cb0ef41Sopenharmony_ci        last_insert_len, params, commands, num_literals);
8341cb0ef41Sopenharmony_ci  }
8351cb0ef41Sopenharmony_ci  CleanupZopfliCostModel(m, &model);
8361cb0ef41Sopenharmony_ci  BROTLI_FREE(m, nodes);
8371cb0ef41Sopenharmony_ci  BROTLI_FREE(m, matches);
8381cb0ef41Sopenharmony_ci  BROTLI_FREE(m, num_matches);
8391cb0ef41Sopenharmony_ci}
8401cb0ef41Sopenharmony_ci
8411cb0ef41Sopenharmony_ci#if defined(__cplusplus) || defined(c_plusplus)
8421cb0ef41Sopenharmony_ci}  /* extern "C" */
8431cb0ef41Sopenharmony_ci#endif
844