backward_references_hq.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. package brotli
  2. import "math"
  3. type zopfliNode struct {
  4. length uint32
  5. distance uint32
  6. dcode_insert_length uint32
  7. u struct {
  8. cost float32
  9. next uint32
  10. shortcut uint32
  11. }
  12. }
  13. const maxEffectiveDistanceAlphabetSize = 544
  14. const kInfinity float32 = 1.7e38 /* ~= 2 ^ 127 */
  15. var kDistanceCacheIndex = []uint32{0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1}
  16. var kDistanceCacheOffset = []int{0, 0, 0, 0, -1, 1, -2, 2, -3, 3, -1, 1, -2, 2, -3, 3}
  17. func initZopfliNodes(array []zopfliNode, length uint) {
  18. var stub zopfliNode
  19. var i uint
  20. stub.length = 1
  21. stub.distance = 0
  22. stub.dcode_insert_length = 0
  23. stub.u.cost = kInfinity
  24. for i = 0; i < length; i++ {
  25. array[i] = stub
  26. }
  27. }
  28. func zopfliNodeCopyLength(self *zopfliNode) uint32 {
  29. return self.length & 0x1FFFFFF
  30. }
  31. func zopfliNodeLengthCode(self *zopfliNode) uint32 {
  32. var modifier uint32 = self.length >> 25
  33. return zopfliNodeCopyLength(self) + 9 - modifier
  34. }
  35. func zopfliNodeCopyDistance(self *zopfliNode) uint32 {
  36. return self.distance
  37. }
  38. func zopfliNodeDistanceCode(self *zopfliNode) uint32 {
  39. var short_code uint32 = self.dcode_insert_length >> 27
  40. if short_code == 0 {
  41. return zopfliNodeCopyDistance(self) + numDistanceShortCodes - 1
  42. } else {
  43. return short_code - 1
  44. }
  45. }
  46. func zopfliNodeCommandLength(self *zopfliNode) uint32 {
  47. return zopfliNodeCopyLength(self) + (self.dcode_insert_length & 0x7FFFFFF)
  48. }
  49. /* Histogram based cost model for zopflification. */
  50. type zopfliCostModel struct {
  51. cost_cmd_ [numCommandSymbols]float32
  52. cost_dist_ []float32
  53. distance_histogram_size uint32
  54. literal_costs_ []float32
  55. min_cost_cmd_ float32
  56. num_bytes_ uint
  57. }
  58. func initZopfliCostModel(self *zopfliCostModel, dist *distanceParams, num_bytes uint) {
  59. var distance_histogram_size uint32 = dist.alphabet_size
  60. if distance_histogram_size > maxEffectiveDistanceAlphabetSize {
  61. distance_histogram_size = maxEffectiveDistanceAlphabetSize
  62. }
  63. self.num_bytes_ = num_bytes
  64. self.literal_costs_ = make([]float32, (num_bytes + 2))
  65. self.cost_dist_ = make([]float32, (dist.alphabet_size))
  66. self.distance_histogram_size = distance_histogram_size
  67. }
  68. func cleanupZopfliCostModel(self *zopfliCostModel) {
  69. self.literal_costs_ = nil
  70. self.cost_dist_ = nil
  71. }
  72. func setCost(histogram []uint32, histogram_size uint, literal_histogram bool, cost []float32) {
  73. var sum uint = 0
  74. var missing_symbol_sum uint
  75. var log2sum float32
  76. var missing_symbol_cost float32
  77. var i uint
  78. for i = 0; i < histogram_size; i++ {
  79. sum += uint(histogram[i])
  80. }
  81. log2sum = float32(fastLog2(sum))
  82. missing_symbol_sum = sum
  83. if !literal_histogram {
  84. for i = 0; i < histogram_size; i++ {
  85. if histogram[i] == 0 {
  86. missing_symbol_sum++
  87. }
  88. }
  89. }
  90. missing_symbol_cost = float32(fastLog2(missing_symbol_sum)) + 2
  91. for i = 0; i < histogram_size; i++ {
  92. if histogram[i] == 0 {
  93. cost[i] = missing_symbol_cost
  94. continue
  95. }
  96. /* Shannon bits for this symbol. */
  97. cost[i] = log2sum - float32(fastLog2(uint(histogram[i])))
  98. /* Cannot be coded with less than 1 bit */
  99. if cost[i] < 1 {
  100. cost[i] = 1
  101. }
  102. }
  103. }
  104. func zopfliCostModelSetFromCommands(self *zopfliCostModel, position uint, ringbuffer []byte, ringbuffer_mask uint, commands []command, last_insert_len uint) {
  105. var histogram_literal [numLiteralSymbols]uint32
  106. var histogram_cmd [numCommandSymbols]uint32
  107. var histogram_dist [maxEffectiveDistanceAlphabetSize]uint32
  108. var cost_literal [numLiteralSymbols]float32
  109. var pos uint = position - last_insert_len
  110. var min_cost_cmd float32 = kInfinity
  111. var cost_cmd []float32 = self.cost_cmd_[:]
  112. var literal_costs []float32
  113. histogram_literal = [numLiteralSymbols]uint32{}
  114. histogram_cmd = [numCommandSymbols]uint32{}
  115. histogram_dist = [maxEffectiveDistanceAlphabetSize]uint32{}
  116. for i := range commands {
  117. var inslength uint = uint(commands[i].insert_len_)
  118. var copylength uint = uint(commandCopyLen(&commands[i]))
  119. var distcode uint = uint(commands[i].dist_prefix_) & 0x3FF
  120. var cmdcode uint = uint(commands[i].cmd_prefix_)
  121. var j uint
  122. histogram_cmd[cmdcode]++
  123. if cmdcode >= 128 {
  124. histogram_dist[distcode]++
  125. }
  126. for j = 0; j < inslength; j++ {
  127. histogram_literal[ringbuffer[(pos+j)&ringbuffer_mask]]++
  128. }
  129. pos += inslength + copylength
  130. }
  131. setCost(histogram_literal[:], numLiteralSymbols, true, cost_literal[:])
  132. setCost(histogram_cmd[:], numCommandSymbols, false, cost_cmd)
  133. setCost(histogram_dist[:], uint(self.distance_histogram_size), false, self.cost_dist_)
  134. for i := 0; i < numCommandSymbols; i++ {
  135. min_cost_cmd = brotli_min_float(min_cost_cmd, cost_cmd[i])
  136. }
  137. self.min_cost_cmd_ = min_cost_cmd
  138. {
  139. literal_costs = self.literal_costs_
  140. var literal_carry float32 = 0.0
  141. num_bytes := int(self.num_bytes_)
  142. literal_costs[0] = 0.0
  143. for i := 0; i < num_bytes; i++ {
  144. literal_carry += cost_literal[ringbuffer[(position+uint(i))&ringbuffer_mask]]
  145. literal_costs[i+1] = literal_costs[i] + literal_carry
  146. literal_carry -= literal_costs[i+1] - literal_costs[i]
  147. }
  148. }
  149. }
  150. func zopfliCostModelSetFromLiteralCosts(self *zopfliCostModel, position uint, ringbuffer []byte, ringbuffer_mask uint) {
  151. var literal_costs []float32 = self.literal_costs_
  152. var literal_carry float32 = 0.0
  153. var cost_dist []float32 = self.cost_dist_
  154. var cost_cmd []float32 = self.cost_cmd_[:]
  155. var num_bytes uint = self.num_bytes_
  156. var i uint
  157. estimateBitCostsForLiterals(position, num_bytes, ringbuffer_mask, ringbuffer, literal_costs[1:])
  158. literal_costs[0] = 0.0
  159. for i = 0; i < num_bytes; i++ {
  160. literal_carry += literal_costs[i+1]
  161. literal_costs[i+1] = literal_costs[i] + literal_carry
  162. literal_carry -= literal_costs[i+1] - literal_costs[i]
  163. }
  164. for i = 0; i < numCommandSymbols; i++ {
  165. cost_cmd[i] = float32(fastLog2(uint(11 + uint32(i))))
  166. }
  167. for i = 0; uint32(i) < self.distance_histogram_size; i++ {
  168. cost_dist[i] = float32(fastLog2(uint(20 + uint32(i))))
  169. }
  170. self.min_cost_cmd_ = float32(fastLog2(11))
  171. }
  172. func zopfliCostModelGetCommandCost(self *zopfliCostModel, cmdcode uint16) float32 {
  173. return self.cost_cmd_[cmdcode]
  174. }
  175. func zopfliCostModelGetDistanceCost(self *zopfliCostModel, distcode uint) float32 {
  176. return self.cost_dist_[distcode]
  177. }
  178. func zopfliCostModelGetLiteralCosts(self *zopfliCostModel, from uint, to uint) float32 {
  179. return self.literal_costs_[to] - self.literal_costs_[from]
  180. }
  181. func zopfliCostModelGetMinCostCmd(self *zopfliCostModel) float32 {
  182. return self.min_cost_cmd_
  183. }
  184. /* REQUIRES: len >= 2, start_pos <= pos */
  185. /* REQUIRES: cost < kInfinity, nodes[start_pos].cost < kInfinity */
  186. /* Maintains the "ZopfliNode array invariant". */
  187. func updateZopfliNode(nodes []zopfliNode, pos uint, start_pos uint, len uint, len_code uint, dist uint, short_code uint, cost float32) {
  188. var next *zopfliNode = &nodes[pos+len]
  189. next.length = uint32(len | (len+9-len_code)<<25)
  190. next.distance = uint32(dist)
  191. next.dcode_insert_length = uint32(short_code<<27 | (pos - start_pos))
  192. next.u.cost = cost
  193. }
  194. type posData struct {
  195. pos uint
  196. distance_cache [4]int
  197. costdiff float32
  198. cost float32
  199. }
  200. /* Maintains the smallest 8 cost difference together with their positions */
  201. type startPosQueue struct {
  202. q_ [8]posData
  203. idx_ uint
  204. }
  205. func initStartPosQueue(self *startPosQueue) {
  206. self.idx_ = 0
  207. }
  208. func startPosQueueSize(self *startPosQueue) uint {
  209. return brotli_min_size_t(self.idx_, 8)
  210. }
  211. func startPosQueuePush(self *startPosQueue, posdata *posData) {
  212. var offset uint = ^(self.idx_) & 7
  213. self.idx_++
  214. var len uint = startPosQueueSize(self)
  215. var i uint
  216. var q []posData = self.q_[:]
  217. q[offset] = *posdata
  218. /* Restore the sorted order. In the list of |len| items at most |len - 1|
  219. adjacent element comparisons / swaps are required. */
  220. for i = 1; i < len; i++ {
  221. if q[offset&7].costdiff > q[(offset+1)&7].costdiff {
  222. var tmp posData = q[offset&7]
  223. q[offset&7] = q[(offset+1)&7]
  224. q[(offset+1)&7] = tmp
  225. }
  226. offset++
  227. }
  228. }
  229. func startPosQueueAt(self *startPosQueue, k uint) *posData {
  230. return &self.q_[(k-self.idx_)&7]
  231. }
  232. /* Returns the minimum possible copy length that can improve the cost of any */
  233. /* future position. */
  234. func computeMinimumCopyLength(start_cost float32, nodes []zopfliNode, num_bytes uint, pos uint) uint {
  235. var min_cost float32 = start_cost
  236. var len uint = 2
  237. var next_len_bucket uint = 4
  238. /* Compute the minimum possible cost of reaching any future position. */
  239. var next_len_offset uint = 10
  240. for pos+len <= num_bytes && nodes[pos+len].u.cost <= min_cost {
  241. /* We already reached (pos + len) with no more cost than the minimum
  242. possible cost of reaching anything from this pos, so there is no point in
  243. looking for lengths <= len. */
  244. len++
  245. if len == next_len_offset {
  246. /* We reached the next copy length code bucket, so we add one more
  247. extra bit to the minimum cost. */
  248. min_cost += 1.0
  249. next_len_offset += next_len_bucket
  250. next_len_bucket *= 2
  251. }
  252. }
  253. return uint(len)
  254. }
  255. /* REQUIRES: nodes[pos].cost < kInfinity
  256. REQUIRES: nodes[0..pos] satisfies that "ZopfliNode array invariant". */
  257. func computeDistanceShortcut(block_start uint, pos uint, max_backward_limit uint, gap uint, nodes []zopfliNode) uint32 {
  258. var clen uint = uint(zopfliNodeCopyLength(&nodes[pos]))
  259. var ilen uint = uint(nodes[pos].dcode_insert_length & 0x7FFFFFF)
  260. var dist uint = uint(zopfliNodeCopyDistance(&nodes[pos]))
  261. /* Since |block_start + pos| is the end position of the command, the copy part
  262. starts from |block_start + pos - clen|. Distances that are greater than
  263. this or greater than |max_backward_limit| + |gap| are static dictionary
  264. references, and do not update the last distances.
  265. Also distance code 0 (last distance) does not update the last distances. */
  266. if pos == 0 {
  267. return 0
  268. } else if dist+clen <= block_start+pos+gap && dist <= max_backward_limit+gap && zopfliNodeDistanceCode(&nodes[pos]) > 0 {
  269. return uint32(pos)
  270. } else {
  271. return nodes[pos-clen-ilen].u.shortcut
  272. }
  273. }
  274. /* Fills in dist_cache[0..3] with the last four distances (as defined by
  275. Section 4. of the Spec) that would be used at (block_start + pos) if we
  276. used the shortest path of commands from block_start, computed from
  277. nodes[0..pos]. The last four distances at block_start are in
  278. starting_dist_cache[0..3].
  279. REQUIRES: nodes[pos].cost < kInfinity
  280. REQUIRES: nodes[0..pos] satisfies that "ZopfliNode array invariant". */
  281. func computeDistanceCache(pos uint, starting_dist_cache []int, nodes []zopfliNode, dist_cache []int) {
  282. var idx int = 0
  283. var p uint = uint(nodes[pos].u.shortcut)
  284. for idx < 4 && p > 0 {
  285. var ilen uint = uint(nodes[p].dcode_insert_length & 0x7FFFFFF)
  286. var clen uint = uint(zopfliNodeCopyLength(&nodes[p]))
  287. var dist uint = uint(zopfliNodeCopyDistance(&nodes[p]))
  288. dist_cache[idx] = int(dist)
  289. idx++
  290. /* Because of prerequisite, p >= clen + ilen >= 2. */
  291. p = uint(nodes[p-clen-ilen].u.shortcut)
  292. }
  293. for ; idx < 4; idx++ {
  294. dist_cache[idx] = starting_dist_cache[0]
  295. starting_dist_cache = starting_dist_cache[1:]
  296. }
  297. }
  298. /* Maintains "ZopfliNode array invariant" and pushes node to the queue, if it
  299. is eligible. */
  300. func evaluateNode(block_start uint, pos uint, max_backward_limit uint, gap uint, starting_dist_cache []int, model *zopfliCostModel, queue *startPosQueue, nodes []zopfliNode) {
  301. /* Save cost, because ComputeDistanceCache invalidates it. */
  302. var node_cost float32 = nodes[pos].u.cost
  303. nodes[pos].u.shortcut = computeDistanceShortcut(block_start, pos, max_backward_limit, gap, nodes)
  304. if node_cost <= zopfliCostModelGetLiteralCosts(model, 0, pos) {
  305. var posdata posData
  306. posdata.pos = pos
  307. posdata.cost = node_cost
  308. posdata.costdiff = node_cost - zopfliCostModelGetLiteralCosts(model, 0, pos)
  309. computeDistanceCache(pos, starting_dist_cache, nodes, posdata.distance_cache[:])
  310. startPosQueuePush(queue, &posdata)
  311. }
  312. }
  313. /* Returns longest copy length. */
  314. func updateNodes(num_bytes uint, block_start uint, pos uint, ringbuffer []byte, ringbuffer_mask uint, params *encoderParams, max_backward_limit uint, starting_dist_cache []int, num_matches uint, matches []backwardMatch, model *zopfliCostModel, queue *startPosQueue, nodes []zopfliNode) uint {
  315. var cur_ix uint = block_start + pos
  316. var cur_ix_masked uint = cur_ix & ringbuffer_mask
  317. var max_distance uint = brotli_min_size_t(cur_ix, max_backward_limit)
  318. var max_len uint = num_bytes - pos
  319. var max_zopfli_len uint = maxZopfliLen(params)
  320. var max_iters uint = maxZopfliCandidates(params)
  321. var min_len uint
  322. var result uint = 0
  323. var k uint
  324. var gap uint = 0
  325. evaluateNode(block_start, pos, max_backward_limit, gap, starting_dist_cache, model, queue, nodes)
  326. {
  327. var posdata *posData = startPosQueueAt(queue, 0)
  328. var min_cost float32 = (posdata.cost + zopfliCostModelGetMinCostCmd(model) + zopfliCostModelGetLiteralCosts(model, posdata.pos, pos))
  329. min_len = computeMinimumCopyLength(min_cost, nodes, num_bytes, pos)
  330. }
  331. /* Go over the command starting positions in order of increasing cost
  332. difference. */
  333. for k = 0; k < max_iters && k < startPosQueueSize(queue); k++ {
  334. var posdata *posData = startPosQueueAt(queue, k)
  335. var start uint = posdata.pos
  336. var inscode uint16 = getInsertLengthCode(pos - start)
  337. var start_costdiff float32 = posdata.costdiff
  338. var base_cost float32 = start_costdiff + float32(getInsertExtra(inscode)) + zopfliCostModelGetLiteralCosts(model, 0, pos)
  339. var best_len uint = min_len - 1
  340. var j uint = 0
  341. /* Look for last distance matches using the distance cache from this
  342. starting position. */
  343. for ; j < numDistanceShortCodes && best_len < max_len; j++ {
  344. var idx uint = uint(kDistanceCacheIndex[j])
  345. var backward uint = uint(posdata.distance_cache[idx] + kDistanceCacheOffset[j])
  346. var prev_ix uint = cur_ix - backward
  347. var len uint = 0
  348. var continuation byte = ringbuffer[cur_ix_masked+best_len]
  349. if cur_ix_masked+best_len > ringbuffer_mask {
  350. break
  351. }
  352. if backward > max_distance+gap {
  353. /* Word dictionary -> ignore. */
  354. continue
  355. }
  356. if backward <= max_distance {
  357. /* Regular backward reference. */
  358. if prev_ix >= cur_ix {
  359. continue
  360. }
  361. prev_ix &= ringbuffer_mask
  362. if prev_ix+best_len > ringbuffer_mask || continuation != ringbuffer[prev_ix+best_len] {
  363. continue
  364. }
  365. len = findMatchLengthWithLimit(ringbuffer[prev_ix:], ringbuffer[cur_ix_masked:], max_len)
  366. } else {
  367. continue
  368. }
  369. {
  370. var dist_cost float32 = base_cost + zopfliCostModelGetDistanceCost(model, j)
  371. var l uint
  372. for l = best_len + 1; l <= len; l++ {
  373. var copycode uint16 = getCopyLengthCode(l)
  374. var cmdcode uint16 = combineLengthCodes(inscode, copycode, j == 0)
  375. var tmp float32
  376. if cmdcode < 128 {
  377. tmp = base_cost
  378. } else {
  379. tmp = dist_cost
  380. }
  381. var cost float32 = tmp + float32(getCopyExtra(copycode)) + zopfliCostModelGetCommandCost(model, cmdcode)
  382. if cost < nodes[pos+l].u.cost {
  383. updateZopfliNode(nodes, pos, start, l, l, backward, j+1, cost)
  384. result = brotli_max_size_t(result, l)
  385. }
  386. best_len = l
  387. }
  388. }
  389. }
  390. /* At higher iterations look only for new last distance matches, since
  391. looking only for new command start positions with the same distances
  392. does not help much. */
  393. if k >= 2 {
  394. continue
  395. }
  396. {
  397. /* Loop through all possible copy lengths at this position. */
  398. var len uint = min_len
  399. for j = 0; j < num_matches; j++ {
  400. var match backwardMatch = matches[j]
  401. var dist uint = uint(match.distance)
  402. var is_dictionary_match bool = (dist > max_distance+gap)
  403. var dist_code uint = dist + numDistanceShortCodes - 1
  404. var dist_symbol uint16
  405. var distextra uint32
  406. var distnumextra uint32
  407. var dist_cost float32
  408. var max_match_len uint
  409. /* We already tried all possible last distance matches, so we can use
  410. normal distance code here. */
  411. prefixEncodeCopyDistance(dist_code, uint(params.dist.num_direct_distance_codes), uint(params.dist.distance_postfix_bits), &dist_symbol, &distextra)
  412. distnumextra = uint32(dist_symbol) >> 10
  413. dist_cost = base_cost + float32(distnumextra) + zopfliCostModelGetDistanceCost(model, uint(dist_symbol)&0x3FF)
  414. /* Try all copy lengths up until the maximum copy length corresponding
  415. to this distance. If the distance refers to the static dictionary, or
  416. the maximum length is long enough, try only one maximum length. */
  417. max_match_len = backwardMatchLength(&match)
  418. if len < max_match_len && (is_dictionary_match || max_match_len > max_zopfli_len) {
  419. len = max_match_len
  420. }
  421. for ; len <= max_match_len; len++ {
  422. var len_code uint
  423. if is_dictionary_match {
  424. len_code = backwardMatchLengthCode(&match)
  425. } else {
  426. len_code = len
  427. }
  428. var copycode uint16 = getCopyLengthCode(len_code)
  429. var cmdcode uint16 = combineLengthCodes(inscode, copycode, false)
  430. var cost float32 = dist_cost + float32(getCopyExtra(copycode)) + zopfliCostModelGetCommandCost(model, cmdcode)
  431. if cost < nodes[pos+len].u.cost {
  432. updateZopfliNode(nodes, pos, start, uint(len), len_code, dist, 0, cost)
  433. if len > result {
  434. result = len
  435. }
  436. }
  437. }
  438. }
  439. }
  440. }
  441. return result
  442. }
  443. func computeShortestPathFromNodes(num_bytes uint, nodes []zopfliNode) uint {
  444. var index uint = num_bytes
  445. var num_commands uint = 0
  446. for nodes[index].dcode_insert_length&0x7FFFFFF == 0 && nodes[index].length == 1 {
  447. index--
  448. }
  449. nodes[index].u.next = math.MaxUint32
  450. for index != 0 {
  451. var len uint = uint(zopfliNodeCommandLength(&nodes[index]))
  452. index -= uint(len)
  453. nodes[index].u.next = uint32(len)
  454. num_commands++
  455. }
  456. return num_commands
  457. }
  458. /* REQUIRES: nodes != NULL and len(nodes) >= num_bytes + 1 */
  459. func zopfliCreateCommands(num_bytes uint, block_start uint, nodes []zopfliNode, dist_cache []int, last_insert_len *uint, params *encoderParams, commands *[]command, num_literals *uint) {
  460. var max_backward_limit uint = maxBackwardLimit(params.lgwin)
  461. var pos uint = 0
  462. var offset uint32 = nodes[0].u.next
  463. var i uint
  464. var gap uint = 0
  465. for i = 0; offset != math.MaxUint32; i++ {
  466. var next *zopfliNode = &nodes[uint32(pos)+offset]
  467. var copy_length uint = uint(zopfliNodeCopyLength(next))
  468. var insert_length uint = uint(next.dcode_insert_length & 0x7FFFFFF)
  469. pos += insert_length
  470. offset = next.u.next
  471. if i == 0 {
  472. insert_length += *last_insert_len
  473. *last_insert_len = 0
  474. }
  475. {
  476. var distance uint = uint(zopfliNodeCopyDistance(next))
  477. var len_code uint = uint(zopfliNodeLengthCode(next))
  478. var max_distance uint = brotli_min_size_t(block_start+pos, max_backward_limit)
  479. var is_dictionary bool = (distance > max_distance+gap)
  480. var dist_code uint = uint(zopfliNodeDistanceCode(next))
  481. *commands = append(*commands, makeCommand(&params.dist, insert_length, copy_length, int(len_code)-int(copy_length), dist_code))
  482. if !is_dictionary && dist_code > 0 {
  483. dist_cache[3] = dist_cache[2]
  484. dist_cache[2] = dist_cache[1]
  485. dist_cache[1] = dist_cache[0]
  486. dist_cache[0] = int(distance)
  487. }
  488. }
  489. *num_literals += insert_length
  490. pos += copy_length
  491. }
  492. *last_insert_len += num_bytes - pos
  493. }
  494. func zopfliIterate(num_bytes uint, position uint, ringbuffer []byte, ringbuffer_mask uint, params *encoderParams, gap uint, dist_cache []int, model *zopfliCostModel, num_matches []uint32, matches []backwardMatch, nodes []zopfliNode) uint {
  495. var max_backward_limit uint = maxBackwardLimit(params.lgwin)
  496. var max_zopfli_len uint = maxZopfliLen(params)
  497. var queue startPosQueue
  498. var cur_match_pos uint = 0
  499. var i uint
  500. nodes[0].length = 0
  501. nodes[0].u.cost = 0
  502. initStartPosQueue(&queue)
  503. for i = 0; i+3 < num_bytes; i++ {
  504. var skip uint = updateNodes(num_bytes, position, i, ringbuffer, ringbuffer_mask, params, max_backward_limit, dist_cache, uint(num_matches[i]), matches[cur_match_pos:], model, &queue, nodes)
  505. if skip < longCopyQuickStep {
  506. skip = 0
  507. }
  508. cur_match_pos += uint(num_matches[i])
  509. if num_matches[i] == 1 && backwardMatchLength(&matches[cur_match_pos-1]) > max_zopfli_len {
  510. skip = brotli_max_size_t(backwardMatchLength(&matches[cur_match_pos-1]), skip)
  511. }
  512. if skip > 1 {
  513. skip--
  514. for skip != 0 {
  515. i++
  516. if i+3 >= num_bytes {
  517. break
  518. }
  519. evaluateNode(position, i, max_backward_limit, gap, dist_cache, model, &queue, nodes)
  520. cur_match_pos += uint(num_matches[i])
  521. skip--
  522. }
  523. }
  524. }
  525. return computeShortestPathFromNodes(num_bytes, nodes)
  526. }
  527. /* Computes the shortest path of commands from position to at most
  528. position + num_bytes.
  529. On return, path->size() is the number of commands found and path[i] is the
  530. length of the i-th command (copy length plus insert length).
  531. Note that the sum of the lengths of all commands can be less than num_bytes.
  532. On return, the nodes[0..num_bytes] array will have the following
  533. "ZopfliNode array invariant":
  534. For each i in [1..num_bytes], if nodes[i].cost < kInfinity, then
  535. (1) nodes[i].copy_length() >= 2
  536. (2) nodes[i].command_length() <= i and
  537. (3) nodes[i - nodes[i].command_length()].cost < kInfinity
  538. REQUIRES: nodes != nil and len(nodes) >= num_bytes + 1 */
  539. func zopfliComputeShortestPath(num_bytes uint, position uint, ringbuffer []byte, ringbuffer_mask uint, params *encoderParams, dist_cache []int, hasher *h10, nodes []zopfliNode) uint {
  540. var max_backward_limit uint = maxBackwardLimit(params.lgwin)
  541. var max_zopfli_len uint = maxZopfliLen(params)
  542. var model zopfliCostModel
  543. var queue startPosQueue
  544. var matches [2 * (maxNumMatchesH10 + 64)]backwardMatch
  545. var store_end uint
  546. if num_bytes >= hasher.StoreLookahead() {
  547. store_end = position + num_bytes - hasher.StoreLookahead() + 1
  548. } else {
  549. store_end = position
  550. }
  551. var i uint
  552. var gap uint = 0
  553. var lz_matches_offset uint = 0
  554. nodes[0].length = 0
  555. nodes[0].u.cost = 0
  556. initZopfliCostModel(&model, &params.dist, num_bytes)
  557. zopfliCostModelSetFromLiteralCosts(&model, position, ringbuffer, ringbuffer_mask)
  558. initStartPosQueue(&queue)
  559. for i = 0; i+hasher.HashTypeLength()-1 < num_bytes; i++ {
  560. var pos uint = position + i
  561. var max_distance uint = brotli_min_size_t(pos, max_backward_limit)
  562. var skip uint
  563. var num_matches uint
  564. num_matches = findAllMatchesH10(hasher, &params.dictionary, ringbuffer, ringbuffer_mask, pos, num_bytes-i, max_distance, gap, params, matches[lz_matches_offset:])
  565. if num_matches > 0 && backwardMatchLength(&matches[num_matches-1]) > max_zopfli_len {
  566. matches[0] = matches[num_matches-1]
  567. num_matches = 1
  568. }
  569. skip = updateNodes(num_bytes, position, i, ringbuffer, ringbuffer_mask, params, max_backward_limit, dist_cache, num_matches, matches[:], &model, &queue, nodes)
  570. if skip < longCopyQuickStep {
  571. skip = 0
  572. }
  573. if num_matches == 1 && backwardMatchLength(&matches[0]) > max_zopfli_len {
  574. skip = brotli_max_size_t(backwardMatchLength(&matches[0]), skip)
  575. }
  576. if skip > 1 {
  577. /* Add the tail of the copy to the hasher. */
  578. hasher.StoreRange(ringbuffer, ringbuffer_mask, pos+1, brotli_min_size_t(pos+skip, store_end))
  579. skip--
  580. for skip != 0 {
  581. i++
  582. if i+hasher.HashTypeLength()-1 >= num_bytes {
  583. break
  584. }
  585. evaluateNode(position, i, max_backward_limit, gap, dist_cache, &model, &queue, nodes)
  586. skip--
  587. }
  588. }
  589. }
  590. cleanupZopfliCostModel(&model)
  591. return computeShortestPathFromNodes(num_bytes, nodes)
  592. }
  593. func createZopfliBackwardReferences(num_bytes uint, position uint, ringbuffer []byte, ringbuffer_mask uint, params *encoderParams, hasher *h10, dist_cache []int, last_insert_len *uint, commands *[]command, num_literals *uint) {
  594. var nodes []zopfliNode
  595. nodes = make([]zopfliNode, (num_bytes + 1))
  596. initZopfliNodes(nodes, num_bytes+1)
  597. zopfliComputeShortestPath(num_bytes, position, ringbuffer, ringbuffer_mask, params, dist_cache, hasher, nodes)
  598. zopfliCreateCommands(num_bytes, position, nodes, dist_cache, last_insert_len, params, commands, num_literals)
  599. nodes = nil
  600. }
  601. func createHqZopfliBackwardReferences(num_bytes uint, position uint, ringbuffer []byte, ringbuffer_mask uint, params *encoderParams, hasher hasherHandle, dist_cache []int, last_insert_len *uint, commands *[]command, num_literals *uint) {
  602. var max_backward_limit uint = maxBackwardLimit(params.lgwin)
  603. var num_matches []uint32 = make([]uint32, num_bytes)
  604. var matches_size uint = 4 * num_bytes
  605. var store_end uint
  606. if num_bytes >= hasher.StoreLookahead() {
  607. store_end = position + num_bytes - hasher.StoreLookahead() + 1
  608. } else {
  609. store_end = position
  610. }
  611. var cur_match_pos uint = 0
  612. var i uint
  613. var orig_num_literals uint
  614. var orig_last_insert_len uint
  615. var orig_dist_cache [4]int
  616. var orig_num_commands int
  617. var model zopfliCostModel
  618. var nodes []zopfliNode
  619. var matches []backwardMatch = make([]backwardMatch, matches_size)
  620. var gap uint = 0
  621. var shadow_matches uint = 0
  622. var new_array []backwardMatch
  623. for i = 0; i+hasher.HashTypeLength()-1 < num_bytes; i++ {
  624. var pos uint = position + i
  625. var max_distance uint = brotli_min_size_t(pos, max_backward_limit)
  626. var max_length uint = num_bytes - i
  627. var num_found_matches uint
  628. var cur_match_end uint
  629. var j uint
  630. /* Ensure that we have enough free slots. */
  631. if matches_size < cur_match_pos+maxNumMatchesH10+shadow_matches {
  632. var new_size uint = matches_size
  633. if new_size == 0 {
  634. new_size = cur_match_pos + maxNumMatchesH10 + shadow_matches
  635. }
  636. for new_size < cur_match_pos+maxNumMatchesH10+shadow_matches {
  637. new_size *= 2
  638. }
  639. new_array = make([]backwardMatch, new_size)
  640. if matches_size != 0 {
  641. copy(new_array, matches[:matches_size])
  642. }
  643. matches = new_array
  644. matches_size = new_size
  645. }
  646. num_found_matches = findAllMatchesH10(hasher.(*h10), &params.dictionary, ringbuffer, ringbuffer_mask, pos, max_length, max_distance, gap, params, matches[cur_match_pos+shadow_matches:])
  647. cur_match_end = cur_match_pos + num_found_matches
  648. for j = cur_match_pos; j+1 < cur_match_end; j++ {
  649. assert(backwardMatchLength(&matches[j]) <= backwardMatchLength(&matches[j+1]))
  650. }
  651. num_matches[i] = uint32(num_found_matches)
  652. if num_found_matches > 0 {
  653. var match_len uint = backwardMatchLength(&matches[cur_match_end-1])
  654. if match_len > maxZopfliLenQuality11 {
  655. var skip uint = match_len - 1
  656. matches[cur_match_pos] = matches[cur_match_end-1]
  657. cur_match_pos++
  658. num_matches[i] = 1
  659. /* Add the tail of the copy to the hasher. */
  660. hasher.StoreRange(ringbuffer, ringbuffer_mask, pos+1, brotli_min_size_t(pos+match_len, store_end))
  661. var pos uint = i
  662. for i := 0; i < int(skip); i++ {
  663. num_matches[pos+1:][i] = 0
  664. }
  665. i += skip
  666. } else {
  667. cur_match_pos = cur_match_end
  668. }
  669. }
  670. }
  671. orig_num_literals = *num_literals
  672. orig_last_insert_len = *last_insert_len
  673. copy(orig_dist_cache[:], dist_cache[:4])
  674. orig_num_commands = len(*commands)
  675. nodes = make([]zopfliNode, (num_bytes + 1))
  676. initZopfliCostModel(&model, &params.dist, num_bytes)
  677. for i = 0; i < 2; i++ {
  678. initZopfliNodes(nodes, num_bytes+1)
  679. if i == 0 {
  680. zopfliCostModelSetFromLiteralCosts(&model, position, ringbuffer, ringbuffer_mask)
  681. } else {
  682. zopfliCostModelSetFromCommands(&model, position, ringbuffer, ringbuffer_mask, (*commands)[orig_num_commands:], orig_last_insert_len)
  683. }
  684. *commands = (*commands)[:orig_num_commands]
  685. *num_literals = orig_num_literals
  686. *last_insert_len = orig_last_insert_len
  687. copy(dist_cache, orig_dist_cache[:4])
  688. zopfliIterate(num_bytes, position, ringbuffer, ringbuffer_mask, params, gap, dist_cache, &model, num_matches, matches, nodes)
  689. zopfliCreateCommands(num_bytes, position, nodes, dist_cache, last_insert_len, params, commands, num_literals)
  690. }
  691. cleanupZopfliCostModel(&model)
  692. nodes = nil
  693. matches = nil
  694. num_matches = nil
  695. }