Coverage Report

Created: 2026-09-13 07:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjxl/lib/jxl/modular/encoding/enc_ma.cc
Line
Count
Source
1
// Copyright (c) the JPEG XL Project Authors. All rights reserved.
2
//
3
// Use of this source code is governed by a BSD-style
4
// license that can be found in the LICENSE file.
5
6
#include "lib/jxl/modular/encoding/enc_ma.h"
7
8
#include <algorithm>
9
#include <cstdint>
10
#include <cstdlib>
11
#include <cstring>
12
#include <limits>
13
#include <numeric>
14
#include <queue>
15
#include <vector>
16
17
#include "lib/jxl/ans_params.h"
18
#include "lib/jxl/base/bits.h"
19
#include "lib/jxl/base/common.h"
20
#include "lib/jxl/base/compiler_specific.h"
21
#include "lib/jxl/base/status.h"
22
#include "lib/jxl/dec_ans.h"
23
#include "lib/jxl/modular/encoding/dec_ma.h"
24
#include "lib/jxl/modular/encoding/ma_common.h"
25
#include "lib/jxl/modular/modular_image.h"
26
27
#undef HWY_TARGET_INCLUDE
28
#define HWY_TARGET_INCLUDE "lib/jxl/modular/encoding/enc_ma.cc"
29
#include <hwy/foreach_target.h>
30
#include <hwy/highway.h>
31
32
#include "lib/jxl/base/fast_math-inl.h"
33
#include "lib/jxl/base/random.h"
34
#include "lib/jxl/enc_ans.h"
35
#include "lib/jxl/modular/encoding/context_predict.h"
36
#include "lib/jxl/modular/options.h"
37
#include "lib/jxl/pack_signed.h"
38
HWY_BEFORE_NAMESPACE();
39
namespace jxl {
40
namespace HWY_NAMESPACE {
41
42
// These templates are not found via ADL.
43
using hwy::HWY_NAMESPACE::Eq;
44
using hwy::HWY_NAMESPACE::IfThenElse;
45
using hwy::HWY_NAMESPACE::Lt;
46
using hwy::HWY_NAMESPACE::Max;
47
48
const HWY_FULL(float) df;
49
const HWY_FULL(int32_t) di;
50
// Pad array size for use in EstimateBits.
51
485k
size_t Padded(size_t x) {
52
485k
  JXL_DASSERT(Lanes(df) == Lanes(di));
53
485k
  return RoundUpTo(x, Lanes(df));
54
485k
}
Unexecuted instantiation: jxl::N_SSE4::Padded(unsigned long)
jxl::N_AVX2::Padded(unsigned long)
Line
Count
Source
51
485k
size_t Padded(size_t x) {
52
485k
  JXL_DASSERT(Lanes(df) == Lanes(di));
53
485k
  return RoundUpTo(x, Lanes(df));
54
485k
}
Unexecuted instantiation: jxl::N_SSE2::Padded(unsigned long)
55
56
// Compute entropy of the histogram, taking into account the minimum probability
57
// for symbols with non-zero counts.
58
36.6M
float EstimateBits(const int32_t *counts, size_t num_symbols) {
59
36.6M
  JXL_DASSERT(num_symbols == Padded(num_symbols));
60
36.6M
  auto total_v = Zero(di);
61
269M
  for (size_t i = 0; i < num_symbols; i += Lanes(di)) {
62
232M
    const auto counts_iv = LoadU(di, &counts[i]);
63
232M
    total_v = Add(total_v, counts_iv);
64
232M
  }
65
36.6M
  total_v = SumOfLanes(di, total_v);
66
67
36.6M
  const auto minprob = Set(df, 1.0f / ANS_TAB_SIZE);
68
36.6M
  const auto inv_total = Set(df, 1.0f / GetLane(total_v));
69
36.6M
  auto bits_lanes = Zero(df);
70
269M
  for (size_t i = 0; i < num_symbols; i += Lanes(df)) {
71
232M
    const auto counts_iv = LoadU(di, &counts[i]);
72
232M
    const auto counts_fv = ConvertTo(df, counts_iv);
73
232M
    const auto probs = Mul(counts_fv, inv_total);
74
232M
    const auto mprobs = Max(probs, minprob);
75
232M
    const auto nbps = IfThenZeroElse(Eq(counts_iv, total_v),
76
232M
                                     BitCast(di, FastLog2f(df, mprobs)));
77
232M
    bits_lanes = Sub(bits_lanes, Mul(counts_fv, BitCast(df, nbps)));
78
232M
  }
79
36.6M
  return GetLane(SumOfLanes(df, bits_lanes));
80
36.6M
}
Unexecuted instantiation: jxl::N_SSE4::EstimateBits(int const*, unsigned long)
jxl::N_AVX2::EstimateBits(int const*, unsigned long)
Line
Count
Source
58
36.6M
float EstimateBits(const int32_t *counts, size_t num_symbols) {
59
36.6M
  JXL_DASSERT(num_symbols == Padded(num_symbols));
60
36.6M
  auto total_v = Zero(di);
61
269M
  for (size_t i = 0; i < num_symbols; i += Lanes(di)) {
62
232M
    const auto counts_iv = LoadU(di, &counts[i]);
63
232M
    total_v = Add(total_v, counts_iv);
64
232M
  }
65
36.6M
  total_v = SumOfLanes(di, total_v);
66
67
36.6M
  const auto minprob = Set(df, 1.0f / ANS_TAB_SIZE);
68
36.6M
  const auto inv_total = Set(df, 1.0f / GetLane(total_v));
69
36.6M
  auto bits_lanes = Zero(df);
70
269M
  for (size_t i = 0; i < num_symbols; i += Lanes(df)) {
71
232M
    const auto counts_iv = LoadU(di, &counts[i]);
72
232M
    const auto counts_fv = ConvertTo(df, counts_iv);
73
232M
    const auto probs = Mul(counts_fv, inv_total);
74
232M
    const auto mprobs = Max(probs, minprob);
75
232M
    const auto nbps = IfThenZeroElse(Eq(counts_iv, total_v),
76
232M
                                     BitCast(di, FastLog2f(df, mprobs)));
77
232M
    bits_lanes = Sub(bits_lanes, Mul(counts_fv, BitCast(df, nbps)));
78
232M
  }
79
36.6M
  return GetLane(SumOfLanes(df, bits_lanes));
80
36.6M
}
Unexecuted instantiation: jxl::N_SSE2::EstimateBits(int const*, unsigned long)
81
82
void MakeSplitNode(size_t pos, int property, int splitval, Predictor lpred,
83
241k
                   int64_t loff, Predictor rpred, int64_t roff, Tree *tree) {
84
  // Note that the tree splits on *strictly greater*.
85
241k
  (*tree)[pos].lchild = tree->size();
86
241k
  (*tree)[pos].rchild = tree->size() + 1;
87
241k
  (*tree)[pos].splitval = splitval;
88
241k
  (*tree)[pos].property = property;
89
241k
  tree->emplace_back();
90
241k
  tree->back().property = -1;
91
241k
  tree->back().predictor = rpred;
92
241k
  tree->back().predictor_offset = roff;
93
241k
  tree->back().multiplier = 1;
94
241k
  tree->emplace_back();
95
241k
  tree->back().property = -1;
96
241k
  tree->back().predictor = lpred;
97
241k
  tree->back().predictor_offset = loff;
98
241k
  tree->back().multiplier = 1;
99
241k
}
Unexecuted instantiation: jxl::N_SSE4::MakeSplitNode(unsigned long, int, int, jxl::Predictor, long, jxl::Predictor, long, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)
jxl::N_AVX2::MakeSplitNode(unsigned long, int, int, jxl::Predictor, long, jxl::Predictor, long, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)
Line
Count
Source
83
241k
                   int64_t loff, Predictor rpred, int64_t roff, Tree *tree) {
84
  // Note that the tree splits on *strictly greater*.
85
241k
  (*tree)[pos].lchild = tree->size();
86
241k
  (*tree)[pos].rchild = tree->size() + 1;
87
241k
  (*tree)[pos].splitval = splitval;
88
241k
  (*tree)[pos].property = property;
89
241k
  tree->emplace_back();
90
241k
  tree->back().property = -1;
91
241k
  tree->back().predictor = rpred;
92
241k
  tree->back().predictor_offset = roff;
93
241k
  tree->back().multiplier = 1;
94
241k
  tree->emplace_back();
95
241k
  tree->back().property = -1;
96
241k
  tree->back().predictor = lpred;
97
241k
  tree->back().predictor_offset = loff;
98
241k
  tree->back().multiplier = 1;
99
241k
}
Unexecuted instantiation: jxl::N_SSE2::MakeSplitNode(unsigned long, int, int, jxl::Predictor, long, jxl::Predictor, long, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)
100
101
enum class IntersectionType { kNone, kPartial, kInside };
102
IntersectionType BoxIntersects(StaticPropRange needle, StaticPropRange haystack,
103
107k
                               uint32_t &partial_axis, uint32_t &partial_val) {
104
107k
  bool partial = false;
105
322k
  for (size_t i = 0; i < kNumStaticProperties; i++) {
106
215k
    if (haystack[i][0] >= needle[i][1]) {
107
0
      return IntersectionType::kNone;
108
0
    }
109
215k
    if (haystack[i][1] <= needle[i][0]) {
110
0
      return IntersectionType::kNone;
111
0
    }
112
215k
    if (haystack[i][0] <= needle[i][0] && haystack[i][1] >= needle[i][1]) {
113
215k
      continue;
114
215k
    }
115
0
    partial = true;
116
0
    partial_axis = i;
117
0
    if (haystack[i][0] > needle[i][0] && haystack[i][0] < needle[i][1]) {
118
0
      partial_val = haystack[i][0] - 1;
119
0
    } else {
120
0
      JXL_DASSERT(haystack[i][1] > needle[i][0] &&
121
0
                  haystack[i][1] < needle[i][1]);
122
0
      partial_val = haystack[i][1] - 1;
123
0
    }
124
0
  }
125
107k
  return partial ? IntersectionType::kPartial : IntersectionType::kInside;
126
107k
}
Unexecuted instantiation: jxl::N_SSE4::BoxIntersects(std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, unsigned int&, unsigned int&)
jxl::N_AVX2::BoxIntersects(std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, unsigned int&, unsigned int&)
Line
Count
Source
103
107k
                               uint32_t &partial_axis, uint32_t &partial_val) {
104
107k
  bool partial = false;
105
322k
  for (size_t i = 0; i < kNumStaticProperties; i++) {
106
215k
    if (haystack[i][0] >= needle[i][1]) {
107
0
      return IntersectionType::kNone;
108
0
    }
109
215k
    if (haystack[i][1] <= needle[i][0]) {
110
0
      return IntersectionType::kNone;
111
0
    }
112
215k
    if (haystack[i][0] <= needle[i][0] && haystack[i][1] >= needle[i][1]) {
113
215k
      continue;
114
215k
    }
115
0
    partial = true;
116
0
    partial_axis = i;
117
0
    if (haystack[i][0] > needle[i][0] && haystack[i][0] < needle[i][1]) {
118
0
      partial_val = haystack[i][0] - 1;
119
0
    } else {
120
0
      JXL_DASSERT(haystack[i][1] > needle[i][0] &&
121
0
                  haystack[i][1] < needle[i][1]);
122
0
      partial_val = haystack[i][1] - 1;
123
0
    }
124
0
  }
125
107k
  return partial ? IntersectionType::kPartial : IntersectionType::kInside;
126
107k
}
Unexecuted instantiation: jxl::N_SSE2::BoxIntersects(std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, unsigned int&, unsigned int&)
127
128
template<bool S>
129
void SplitTreeSamples(TreeSamples &tree_samples, size_t begin, size_t pos,
130
241k
                      size_t end, size_t prop, uint32_t val) {
131
241k
  size_t begin_pos = begin;
132
241k
  size_t end_pos = pos;
133
15.0M
  do {
134
36.5M
    while (begin_pos < pos &&
135
36.5M
           tree_samples.Property<S>(prop, begin_pos) <= val) {
136
21.5M
      ++begin_pos;
137
21.5M
    }
138
40.2M
    while (end_pos < end && tree_samples.Property<S>(prop, end_pos) > val) {
139
25.1M
      ++end_pos;
140
25.1M
    }
141
15.0M
    if (begin_pos < pos && end_pos < end) {
142
15.0M
      tree_samples.Swap(begin_pos, end_pos);
143
15.0M
    }
144
15.0M
    ++begin_pos;
145
15.0M
    ++end_pos;
146
15.0M
  } while (begin_pos < pos && end_pos < end);
147
241k
}
Unexecuted instantiation: void jxl::N_SSE4::SplitTreeSamples<true>(jxl::TreeSamples&, unsigned long, unsigned long, unsigned long, unsigned long, unsigned int)
Unexecuted instantiation: void jxl::N_SSE4::SplitTreeSamples<false>(jxl::TreeSamples&, unsigned long, unsigned long, unsigned long, unsigned long, unsigned int)
void jxl::N_AVX2::SplitTreeSamples<true>(jxl::TreeSamples&, unsigned long, unsigned long, unsigned long, unsigned long, unsigned int)
Line
Count
Source
130
8.20k
                      size_t end, size_t prop, uint32_t val) {
131
8.20k
  size_t begin_pos = begin;
132
8.20k
  size_t end_pos = pos;
133
755k
  do {
134
3.53M
    while (begin_pos < pos &&
135
3.53M
           tree_samples.Property<S>(prop, begin_pos) <= val) {
136
2.78M
      ++begin_pos;
137
2.78M
    }
138
2.73M
    while (end_pos < end && tree_samples.Property<S>(prop, end_pos) > val) {
139
1.97M
      ++end_pos;
140
1.97M
    }
141
755k
    if (begin_pos < pos && end_pos < end) {
142
752k
      tree_samples.Swap(begin_pos, end_pos);
143
752k
    }
144
755k
    ++begin_pos;
145
755k
    ++end_pos;
146
755k
  } while (begin_pos < pos && end_pos < end);
147
8.20k
}
void jxl::N_AVX2::SplitTreeSamples<false>(jxl::TreeSamples&, unsigned long, unsigned long, unsigned long, unsigned long, unsigned int)
Line
Count
Source
130
233k
                      size_t end, size_t prop, uint32_t val) {
131
233k
  size_t begin_pos = begin;
132
233k
  size_t end_pos = pos;
133
14.3M
  do {
134
33.0M
    while (begin_pos < pos &&
135
32.9M
           tree_samples.Property<S>(prop, begin_pos) <= val) {
136
18.7M
      ++begin_pos;
137
18.7M
    }
138
37.4M
    while (end_pos < end && tree_samples.Property<S>(prop, end_pos) > val) {
139
23.1M
      ++end_pos;
140
23.1M
    }
141
14.3M
    if (begin_pos < pos && end_pos < end) {
142
14.2M
      tree_samples.Swap(begin_pos, end_pos);
143
14.2M
    }
144
14.3M
    ++begin_pos;
145
14.3M
    ++end_pos;
146
14.3M
  } while (begin_pos < pos && end_pos < end);
147
233k
}
Unexecuted instantiation: void jxl::N_SSE2::SplitTreeSamples<true>(jxl::TreeSamples&, unsigned long, unsigned long, unsigned long, unsigned long, unsigned int)
Unexecuted instantiation: void jxl::N_SSE2::SplitTreeSamples<false>(jxl::TreeSamples&, unsigned long, unsigned long, unsigned long, unsigned long, unsigned int)
148
149
template <bool S>
150
void CollectExtraBitsIncrease(TreeSamples &tree_samples,
151
                              const std::vector<ResidualToken> &rtokens,
152
                              std::vector<int> &count_increase,
153
                              std::vector<size_t> &extra_bits_increase,
154
                              size_t begin, size_t end, size_t prop_idx,
155
3.20M
                              size_t max_symbols) {
156
608M
  for (size_t i2 = begin; i2 < end; i2++) {
157
605M
    const ResidualToken &rt = rtokens[i2];
158
605M
    size_t cnt = tree_samples.Count(i2);
159
605M
    size_t p = tree_samples.Property<S>(prop_idx, i2);
160
605M
    size_t sym = rt.tok;
161
605M
    size_t ebi = rt.nbits * cnt;
162
605M
    count_increase[p * max_symbols + sym] += cnt;
163
605M
    extra_bits_increase[p] += ebi;
164
605M
  }
165
3.20M
}
Unexecuted instantiation: void jxl::N_SSE4::CollectExtraBitsIncrease<true>(jxl::TreeSamples&, std::__1::vector<jxl::ResidualToken, std::__1::allocator<jxl::ResidualToken> > const&, std::__1::vector<int, std::__1::allocator<int> >&, std::__1::vector<unsigned long, std::__1::allocator<unsigned long> >&, unsigned long, unsigned long, unsigned long, unsigned long)
Unexecuted instantiation: void jxl::N_SSE4::CollectExtraBitsIncrease<false>(jxl::TreeSamples&, std::__1::vector<jxl::ResidualToken, std::__1::allocator<jxl::ResidualToken> > const&, std::__1::vector<int, std::__1::allocator<int> >&, std::__1::vector<unsigned long, std::__1::allocator<unsigned long> >&, unsigned long, unsigned long, unsigned long, unsigned long)
void jxl::N_AVX2::CollectExtraBitsIncrease<true>(jxl::TreeSamples&, std::__1::vector<jxl::ResidualToken, std::__1::allocator<jxl::ResidualToken> > const&, std::__1::vector<int, std::__1::allocator<int> >&, std::__1::vector<unsigned long, std::__1::allocator<unsigned long> >&, unsigned long, unsigned long, unsigned long, unsigned long)
Line
Count
Source
155
675k
                              size_t max_symbols) {
156
131M
  for (size_t i2 = begin; i2 < end; i2++) {
157
130M
    const ResidualToken &rt = rtokens[i2];
158
130M
    size_t cnt = tree_samples.Count(i2);
159
130M
    size_t p = tree_samples.Property<S>(prop_idx, i2);
160
130M
    size_t sym = rt.tok;
161
130M
    size_t ebi = rt.nbits * cnt;
162
130M
    count_increase[p * max_symbols + sym] += cnt;
163
130M
    extra_bits_increase[p] += ebi;
164
130M
  }
165
675k
}
void jxl::N_AVX2::CollectExtraBitsIncrease<false>(jxl::TreeSamples&, std::__1::vector<jxl::ResidualToken, std::__1::allocator<jxl::ResidualToken> > const&, std::__1::vector<int, std::__1::allocator<int> >&, std::__1::vector<unsigned long, std::__1::allocator<unsigned long> >&, unsigned long, unsigned long, unsigned long, unsigned long)
Line
Count
Source
155
2.53M
                              size_t max_symbols) {
156
477M
  for (size_t i2 = begin; i2 < end; i2++) {
157
474M
    const ResidualToken &rt = rtokens[i2];
158
474M
    size_t cnt = tree_samples.Count(i2);
159
474M
    size_t p = tree_samples.Property<S>(prop_idx, i2);
160
474M
    size_t sym = rt.tok;
161
474M
    size_t ebi = rt.nbits * cnt;
162
474M
    count_increase[p * max_symbols + sym] += cnt;
163
474M
    extra_bits_increase[p] += ebi;
164
474M
  }
165
2.53M
}
Unexecuted instantiation: void jxl::N_SSE2::CollectExtraBitsIncrease<true>(jxl::TreeSamples&, std::__1::vector<jxl::ResidualToken, std::__1::allocator<jxl::ResidualToken> > const&, std::__1::vector<int, std::__1::allocator<int> >&, std::__1::vector<unsigned long, std::__1::allocator<unsigned long> >&, unsigned long, unsigned long, unsigned long, unsigned long)
Unexecuted instantiation: void jxl::N_SSE2::CollectExtraBitsIncrease<false>(jxl::TreeSamples&, std::__1::vector<jxl::ResidualToken, std::__1::allocator<jxl::ResidualToken> > const&, std::__1::vector<int, std::__1::allocator<int> >&, std::__1::vector<unsigned long, std::__1::allocator<unsigned long> >&, unsigned long, unsigned long, unsigned long, unsigned long)
166
167
void FindBestSplit(TreeSamples &tree_samples, float threshold,
168
                   const std::vector<ModularMultiplierInfo> &mul_info,
169
                   StaticPropRange initial_static_prop_range,
170
3.06k
                   float fast_decode_multiplier, Tree *tree) {
171
3.06k
  struct NodeInfo {
172
3.06k
    size_t pos;
173
3.06k
    size_t begin;
174
3.06k
    size_t end;
175
3.06k
    StaticPropRange static_prop_range;
176
3.06k
  };
177
3.06k
  std::vector<NodeInfo> nodes;
178
3.06k
  nodes.push_back(NodeInfo{0, 0, tree_samples.NumDistinctSamples(),
179
3.06k
                           initial_static_prop_range});
180
181
3.06k
  size_t num_predictors = tree_samples.NumPredictors();
182
3.06k
  size_t num_properties = tree_samples.NumProperties();
183
184
  // TODO(veluca): consider parallelizing the search (processing multiple nodes
185
  // at a time).
186
488k
  while (!nodes.empty()) {
187
485k
    size_t pos = nodes.back().pos;
188
485k
    size_t begin = nodes.back().begin;
189
485k
    size_t end = nodes.back().end;
190
191
485k
    StaticPropRange static_prop_range = nodes.back().static_prop_range;
192
485k
    nodes.pop_back();
193
485k
    if (begin == end) continue;
194
195
485k
    struct SplitInfo {
196
485k
      size_t prop = 0;
197
485k
      uint32_t val = 0;
198
485k
      size_t pos = 0;
199
485k
      float lcost = std::numeric_limits<float>::max();
200
485k
      float rcost = std::numeric_limits<float>::max();
201
485k
      Predictor lpred = Predictor::Zero;
202
485k
      Predictor rpred = Predictor::Zero;
203
20.5M
      float Cost() const { return lcost + rcost; }
Unexecuted instantiation: enc_ma.cc:jxl::N_SSE4::FindBestSplit(jxl::TreeSamples&, float, std::__1::vector<jxl::ModularMultiplierInfo, std::__1::allocator<jxl::ModularMultiplierInfo> > const&, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, float, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)::SplitInfo::Cost() const
enc_ma.cc:jxl::N_AVX2::FindBestSplit(jxl::TreeSamples&, float, std::__1::vector<jxl::ModularMultiplierInfo, std::__1::allocator<jxl::ModularMultiplierInfo> > const&, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, float, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)::SplitInfo::Cost() const
Line
Count
Source
203
20.5M
      float Cost() const { return lcost + rcost; }
Unexecuted instantiation: enc_ma.cc:jxl::N_SSE2::FindBestSplit(jxl::TreeSamples&, float, std::__1::vector<jxl::ModularMultiplierInfo, std::__1::allocator<jxl::ModularMultiplierInfo> > const&, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, float, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)::SplitInfo::Cost() const
204
485k
    };
205
206
485k
    SplitInfo best_split_static_constant;
207
485k
    SplitInfo best_split_static;
208
485k
    SplitInfo best_split_nonstatic;
209
485k
    SplitInfo best_split_nowp;
210
211
485k
    JXL_DASSERT(begin <= end);
212
485k
    JXL_DASSERT(end <= tree_samples.NumDistinctSamples());
213
214
    // Compute the maximum token in the range.
215
485k
    size_t max_symbols = 0;
216
971k
    for (size_t pred = 0; pred < num_predictors; pred++) {
217
87.2M
      for (size_t i = begin; i < end; i++) {
218
86.7M
        uint32_t tok = tree_samples.Token(pred, i);
219
86.7M
        max_symbols = max_symbols > tok + 1 ? max_symbols : tok + 1;
220
86.7M
      }
221
485k
    }
222
485k
    max_symbols = Padded(max_symbols);
223
485k
    std::vector<int32_t> counts(max_symbols * num_predictors);
224
485k
    std::vector<uint32_t> tot_extra_bits(num_predictors);
225
971k
    for (size_t pred = 0; pred < num_predictors; pred++) {
226
485k
      size_t extra_bits = 0;
227
485k
      const std::vector<ResidualToken>& rtokens = tree_samples.RTokens(pred);
228
87.2M
      for (size_t i = begin; i < end; i++) {
229
86.7M
        const ResidualToken& rt = rtokens[i];
230
86.7M
        size_t count = tree_samples.Count(i);
231
86.7M
        size_t eb = rt.nbits * count;
232
86.7M
        counts[pred * max_symbols + rt.tok] += count;
233
86.7M
        extra_bits += eb;
234
86.7M
      }
235
485k
      tot_extra_bits[pred] = extra_bits;
236
485k
    }
237
238
485k
    float base_bits;
239
485k
    {
240
485k
      size_t pred = tree_samples.PredictorIndex((*tree)[pos].predictor);
241
485k
      base_bits =
242
485k
          EstimateBits(counts.data() + pred * max_symbols, max_symbols) +
243
485k
          tot_extra_bits[pred];
244
485k
    }
245
246
485k
    SplitInfo *best = &best_split_nonstatic;
247
248
485k
    SplitInfo forced_split;
249
    // The multiplier ranges cut halfway through the current ranges of static
250
    // properties. We do this even if the current node is not a leaf, to
251
    // minimize the number of nodes in the resulting tree.
252
485k
    for (const auto &mmi : mul_info) {
253
107k
      uint32_t axis;
254
107k
      uint32_t val;
255
107k
      IntersectionType t =
256
107k
          BoxIntersects(static_prop_range, mmi.range, axis, val);
257
107k
      if (t == IntersectionType::kNone) continue;
258
107k
      if (t == IntersectionType::kInside) {
259
107k
        (*tree)[pos].multiplier = mmi.multiplier;
260
107k
        break;
261
107k
      }
262
0
      if (t == IntersectionType::kPartial) {
263
0
        JXL_DASSERT(axis < kNumStaticProperties);
264
0
        forced_split.val = tree_samples.QuantizeStaticProperty(axis, val);
265
0
        forced_split.prop = axis;
266
0
        forced_split.lcost = forced_split.rcost = base_bits / 2 - threshold;
267
0
        forced_split.lpred = forced_split.rpred = (*tree)[pos].predictor;
268
0
        best = &forced_split;
269
0
        best->pos = begin;
270
0
        JXL_DASSERT(best->prop == tree_samples.PropertyFromIndex(best->prop));
271
0
        if (best->prop < tree_samples.NumStaticProps()) {
272
0
        for (size_t x = begin; x < end; x++) {
273
0
          if (tree_samples.Property<true>(best->prop, x) <= best->val) {
274
0
            best->pos++;
275
0
          }
276
0
        }
277
0
      } else {
278
0
        size_t prop = best->prop - tree_samples.NumStaticProps();
279
0
        for (size_t x = begin; x < end; x++) {
280
0
          if (tree_samples.Property<false>(prop, x) <= best->val) {
281
0
            best->pos++;
282
0
          }
283
0
        }
284
0
      }
285
0
        break;
286
0
      }
287
0
    }
288
289
485k
    if (best != &forced_split) {
290
485k
      std::vector<int> prop_value_used_count;
291
485k
      std::vector<int> count_increase;
292
485k
      std::vector<size_t> extra_bits_increase;
293
      // For each property, compute which of its values are used, and what
294
      // tokens correspond to those usages. Then, iterate through the values,
295
      // and compute the entropy of each side of the split (of the form `prop >
296
      // threshold`). Finally, find the split that minimizes the cost.
297
485k
      struct CostInfo {
298
485k
        float cost = std::numeric_limits<float>::max();
299
485k
        float extra_cost = 0;
300
36.2M
        float Cost() const { return cost + extra_cost; }
Unexecuted instantiation: enc_ma.cc:jxl::N_SSE4::FindBestSplit(jxl::TreeSamples&, float, std::__1::vector<jxl::ModularMultiplierInfo, std::__1::allocator<jxl::ModularMultiplierInfo> > const&, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, float, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)::CostInfo::Cost() const
enc_ma.cc:jxl::N_AVX2::FindBestSplit(jxl::TreeSamples&, float, std::__1::vector<jxl::ModularMultiplierInfo, std::__1::allocator<jxl::ModularMultiplierInfo> > const&, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, float, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)::CostInfo::Cost() const
Line
Count
Source
300
36.2M
        float Cost() const { return cost + extra_cost; }
Unexecuted instantiation: enc_ma.cc:jxl::N_SSE2::FindBestSplit(jxl::TreeSamples&, float, std::__1::vector<jxl::ModularMultiplierInfo, std::__1::allocator<jxl::ModularMultiplierInfo> > const&, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, float, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)::CostInfo::Cost() const
301
485k
        Predictor pred;  // will be uninitialized in some cases, but never used.
302
485k
      };
303
485k
      std::vector<CostInfo> costs_l;
304
485k
      std::vector<CostInfo> costs_r;
305
306
485k
      std::vector<int32_t> counts_above(max_symbols);
307
485k
      std::vector<int32_t> counts_below(max_symbols);
308
309
      // The lower the threshold, the higher the expected noisiness of the
310
      // estimate. Thus, discourage changing predictors.
311
485k
      float change_pred_penalty = 800.0f / (100.0f + threshold);
312
3.69M
      for (size_t prop = 0; prop < num_properties && base_bits > threshold;
313
3.20M
           prop++) {
314
3.20M
        costs_l.clear();
315
3.20M
        costs_r.clear();
316
3.20M
        size_t prop_size = tree_samples.NumPropertyValues(prop);
317
3.20M
        if (extra_bits_increase.size() < prop_size) {
318
1.09M
          count_increase.resize(prop_size * max_symbols);
319
1.09M
          extra_bits_increase.resize(prop_size);
320
1.09M
        }
321
        // Clear prop_value_used_count (which cannot be cleared "on the go")
322
3.20M
        prop_value_used_count.clear();
323
3.20M
        prop_value_used_count.resize(prop_size);
324
325
3.20M
        size_t first_used = prop_size;
326
3.20M
        size_t last_used = 0;
327
328
        // TODO(veluca): consider finding multiple splits along a single
329
        // property at the same time, possibly with a bottom-up approach.
330
3.20M
        if (prop < tree_samples.NumStaticProps()) {
331
131M
          for (size_t i = begin; i < end; i++) {
332
130M
            size_t p = tree_samples.Property<true>(prop, i);
333
130M
            prop_value_used_count[p]++;
334
130M
            last_used = std::max(last_used, p);
335
130M
            first_used = std::min(first_used, p);
336
130M
          }
337
2.53M
        } else {
338
2.53M
          size_t prop_idx = prop - tree_samples.NumStaticProps();
339
477M
          for (size_t i = begin; i < end; i++) {
340
474M
            size_t p = tree_samples.Property<false>(prop_idx, i);
341
474M
            prop_value_used_count[p]++;
342
474M
            last_used = std::max(last_used, p);
343
474M
            first_used = std::min(first_used, p);
344
474M
          }
345
2.53M
        }
346
3.20M
        costs_l.resize(last_used - first_used);
347
3.20M
        costs_r.resize(last_used - first_used);
348
        // For all predictors, compute the right and left costs of each split.
349
6.41M
        for (size_t pred = 0; pred < num_predictors; pred++) {
350
          // Compute cost and histogram increments for each property value.
351
3.20M
          const std::vector<ResidualToken> &rtokens =
352
3.20M
              tree_samples.RTokens(pred);
353
3.20M
          if (prop < tree_samples.NumStaticProps()) {
354
675k
            CollectExtraBitsIncrease<true>(tree_samples, rtokens,
355
675k
                                           count_increase, extra_bits_increase,
356
675k
                                           begin, end, prop, max_symbols);
357
2.53M
          } else {
358
2.53M
            CollectExtraBitsIncrease<false>(
359
2.53M
                tree_samples, rtokens, count_increase, extra_bits_increase,
360
2.53M
                begin, end, prop - tree_samples.NumStaticProps(), max_symbols);
361
2.53M
          }
362
3.20M
          memcpy(counts_above.data(), counts.data() + pred * max_symbols,
363
3.20M
                 max_symbols * sizeof counts_above[0]);
364
3.20M
          memset(counts_below.data(), 0, max_symbols * sizeof counts_below[0]);
365
3.20M
          size_t extra_bits_below = 0;
366
          // Exclude last used: this ensures neither counts_above nor
367
          // counts_below is empty.
368
41.1M
          for (size_t i = first_used; i < last_used; i++) {
369
37.9M
            if (!prop_value_used_count[i]) continue;
370
18.1M
            extra_bits_below += extra_bits_increase[i];
371
            // The increase for this property value has been used, and will not
372
            // be used again: clear it. Also below.
373
18.1M
            extra_bits_increase[i] = 0;
374
935M
            for (size_t sym = 0; sym < max_symbols; sym++) {
375
917M
              counts_above[sym] -= count_increase[i * max_symbols + sym];
376
917M
              counts_below[sym] += count_increase[i * max_symbols + sym];
377
917M
              count_increase[i * max_symbols + sym] = 0;
378
917M
            }
379
18.1M
            float rcost = EstimateBits(counts_above.data(), max_symbols) +
380
18.1M
                          tot_extra_bits[pred] - extra_bits_below;
381
18.1M
            float lcost = EstimateBits(counts_below.data(), max_symbols) +
382
18.1M
                          extra_bits_below;
383
18.1M
            JXL_DASSERT(extra_bits_below <= tot_extra_bits[pred]);
384
18.1M
            float penalty = 0;
385
            // Never discourage moving away from the Weighted predictor.
386
18.1M
            if (tree_samples.PredictorFromIndex(pred) !=
387
18.1M
                    (*tree)[pos].predictor &&
388
0
                (*tree)[pos].predictor != Predictor::Weighted) {
389
0
              penalty = change_pred_penalty;
390
0
            }
391
            // If everything else is equal, disfavour Weighted (slower) and
392
            // favour Zero (faster if it's the only predictor used in a
393
            // group+channel combination)
394
18.1M
            if (tree_samples.PredictorFromIndex(pred) == Predictor::Weighted) {
395
0
              penalty += 1e-8;
396
0
            }
397
18.1M
            if (tree_samples.PredictorFromIndex(pred) == Predictor::Zero) {
398
0
              penalty -= 1e-8;
399
0
            }
400
18.1M
            if (rcost + penalty < costs_r[i - first_used].Cost()) {
401
18.1M
              costs_r[i - first_used].cost = rcost;
402
18.1M
              costs_r[i - first_used].extra_cost = penalty;
403
18.1M
              costs_r[i - first_used].pred =
404
18.1M
                  tree_samples.PredictorFromIndex(pred);
405
18.1M
            }
406
18.1M
            if (lcost + penalty < costs_l[i - first_used].Cost()) {
407
18.1M
              costs_l[i - first_used].cost = lcost;
408
18.1M
              costs_l[i - first_used].extra_cost = penalty;
409
18.1M
              costs_l[i - first_used].pred =
410
18.1M
                  tree_samples.PredictorFromIndex(pred);
411
18.1M
            }
412
18.1M
          }
413
3.20M
        }
414
        // Iterate through the possible splits and find the one with minimum sum
415
        // of costs of the two sides.
416
3.20M
        size_t split = begin;
417
41.1M
        for (size_t i = first_used; i < last_used; i++) {
418
37.9M
          if (!prop_value_used_count[i]) continue;
419
18.1M
          split += prop_value_used_count[i];
420
18.1M
          float rcost = costs_r[i - first_used].cost;
421
18.1M
          float lcost = costs_l[i - first_used].cost;
422
423
18.1M
          bool uses_wp = tree_samples.PropertyFromIndex(prop) == kWPProp ||
424
14.7M
                         costs_l[i - first_used].pred == Predictor::Weighted ||
425
14.7M
                         costs_r[i - first_used].pred == Predictor::Weighted;
426
18.1M
          bool zero_entropy_side = rcost == 0 || lcost == 0;
427
428
18.1M
          SplitInfo &best_ref =
429
18.1M
              tree_samples.PropertyFromIndex(prop) < kNumStaticProperties
430
18.1M
                  ? (zero_entropy_side ? best_split_static_constant
431
106k
                                       : best_split_static)
432
18.1M
                  : (uses_wp ? best_split_nonstatic : best_split_nowp);
433
18.1M
          if (lcost + rcost < best_ref.Cost()) {
434
3.55M
            best_ref.prop = prop;
435
3.55M
            best_ref.val = i;
436
3.55M
            best_ref.pos = split;
437
3.55M
            best_ref.lcost = lcost;
438
3.55M
            best_ref.lpred = costs_l[i - first_used].pred;
439
3.55M
            best_ref.rcost = rcost;
440
3.55M
            best_ref.rpred = costs_r[i - first_used].pred;
441
3.55M
          }
442
18.1M
        }
443
        // Clear extra_bits_increase and cost_increase for last_used.
444
3.20M
        extra_bits_increase[last_used] = 0;
445
168M
        for (size_t sym = 0; sym < max_symbols; sym++) {
446
165M
          count_increase[last_used * max_symbols + sym] = 0;
447
165M
        }
448
3.20M
      }
449
450
      // Try to avoid introducing WP.
451
485k
      if (best_split_nowp.Cost() + threshold < base_bits &&
452
233k
          best_split_nowp.Cost() <= fast_decode_multiplier * best->Cost()) {
453
218k
        best = &best_split_nowp;
454
218k
      }
455
      // Split along static props if possible and not significantly more
456
      // expensive.
457
485k
      if (best_split_static.Cost() + threshold < base_bits &&
458
35.2k
          best_split_static.Cost() <= fast_decode_multiplier * best->Cost()) {
459
7.82k
        best = &best_split_static;
460
7.82k
      }
461
      // Split along static props to create constant nodes if possible.
462
485k
      if (best_split_static_constant.Cost() + threshold < base_bits) {
463
539
        best = &best_split_static_constant;
464
539
      }
465
485k
    }
466
467
485k
    if (best->Cost() + threshold < base_bits) {
468
241k
      uint32_t p = tree_samples.PropertyFromIndex(best->prop);
469
241k
      pixel_type dequant =
470
241k
          tree_samples.UnquantizeProperty(best->prop, best->val);
471
      // Split node and try to split children.
472
241k
      MakeSplitNode(pos, p, dequant, best->lpred, 0, best->rpred, 0, tree);
473
      // "Sort" according to winning property
474
241k
      if (best->prop < tree_samples.NumStaticProps()) {
475
8.20k
        SplitTreeSamples<true>(tree_samples, begin, best->pos, end, best->prop,
476
8.20k
                               best->val);
477
233k
      } else {
478
233k
        SplitTreeSamples<false>(tree_samples, begin, best->pos, end,
479
233k
                                best->prop - tree_samples.NumStaticProps(),
480
233k
                                best->val);
481
233k
      }
482
241k
      auto new_sp_range = static_prop_range;
483
241k
      if (p < kNumStaticProperties) {
484
8.20k
        JXL_DASSERT(static_cast<uint32_t>(dequant + 1) <= new_sp_range[p][1]);
485
8.20k
        new_sp_range[p][1] = dequant + 1;
486
8.20k
        JXL_DASSERT(new_sp_range[p][0] < new_sp_range[p][1]);
487
8.20k
      }
488
241k
      nodes.push_back(
489
241k
          NodeInfo{(*tree)[pos].rchild, begin, best->pos, new_sp_range});
490
241k
      new_sp_range = static_prop_range;
491
241k
      if (p < kNumStaticProperties) {
492
8.20k
        JXL_DASSERT(new_sp_range[p][0] <= static_cast<uint32_t>(dequant + 1));
493
8.20k
        new_sp_range[p][0] = dequant + 1;
494
8.20k
        JXL_DASSERT(new_sp_range[p][0] < new_sp_range[p][1]);
495
8.20k
      }
496
241k
      nodes.push_back(
497
241k
          NodeInfo{(*tree)[pos].lchild, best->pos, end, new_sp_range});
498
241k
    }
499
485k
  }
500
3.06k
}
Unexecuted instantiation: jxl::N_SSE4::FindBestSplit(jxl::TreeSamples&, float, std::__1::vector<jxl::ModularMultiplierInfo, std::__1::allocator<jxl::ModularMultiplierInfo> > const&, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, float, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)
jxl::N_AVX2::FindBestSplit(jxl::TreeSamples&, float, std::__1::vector<jxl::ModularMultiplierInfo, std::__1::allocator<jxl::ModularMultiplierInfo> > const&, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, float, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)
Line
Count
Source
170
3.06k
                   float fast_decode_multiplier, Tree *tree) {
171
3.06k
  struct NodeInfo {
172
3.06k
    size_t pos;
173
3.06k
    size_t begin;
174
3.06k
    size_t end;
175
3.06k
    StaticPropRange static_prop_range;
176
3.06k
  };
177
3.06k
  std::vector<NodeInfo> nodes;
178
3.06k
  nodes.push_back(NodeInfo{0, 0, tree_samples.NumDistinctSamples(),
179
3.06k
                           initial_static_prop_range});
180
181
3.06k
  size_t num_predictors = tree_samples.NumPredictors();
182
3.06k
  size_t num_properties = tree_samples.NumProperties();
183
184
  // TODO(veluca): consider parallelizing the search (processing multiple nodes
185
  // at a time).
186
488k
  while (!nodes.empty()) {
187
485k
    size_t pos = nodes.back().pos;
188
485k
    size_t begin = nodes.back().begin;
189
485k
    size_t end = nodes.back().end;
190
191
485k
    StaticPropRange static_prop_range = nodes.back().static_prop_range;
192
485k
    nodes.pop_back();
193
485k
    if (begin == end) continue;
194
195
485k
    struct SplitInfo {
196
485k
      size_t prop = 0;
197
485k
      uint32_t val = 0;
198
485k
      size_t pos = 0;
199
485k
      float lcost = std::numeric_limits<float>::max();
200
485k
      float rcost = std::numeric_limits<float>::max();
201
485k
      Predictor lpred = Predictor::Zero;
202
485k
      Predictor rpred = Predictor::Zero;
203
485k
      float Cost() const { return lcost + rcost; }
204
485k
    };
205
206
485k
    SplitInfo best_split_static_constant;
207
485k
    SplitInfo best_split_static;
208
485k
    SplitInfo best_split_nonstatic;
209
485k
    SplitInfo best_split_nowp;
210
211
485k
    JXL_DASSERT(begin <= end);
212
485k
    JXL_DASSERT(end <= tree_samples.NumDistinctSamples());
213
214
    // Compute the maximum token in the range.
215
485k
    size_t max_symbols = 0;
216
971k
    for (size_t pred = 0; pred < num_predictors; pred++) {
217
87.2M
      for (size_t i = begin; i < end; i++) {
218
86.7M
        uint32_t tok = tree_samples.Token(pred, i);
219
86.7M
        max_symbols = max_symbols > tok + 1 ? max_symbols : tok + 1;
220
86.7M
      }
221
485k
    }
222
485k
    max_symbols = Padded(max_symbols);
223
485k
    std::vector<int32_t> counts(max_symbols * num_predictors);
224
485k
    std::vector<uint32_t> tot_extra_bits(num_predictors);
225
971k
    for (size_t pred = 0; pred < num_predictors; pred++) {
226
485k
      size_t extra_bits = 0;
227
485k
      const std::vector<ResidualToken>& rtokens = tree_samples.RTokens(pred);
228
87.2M
      for (size_t i = begin; i < end; i++) {
229
86.7M
        const ResidualToken& rt = rtokens[i];
230
86.7M
        size_t count = tree_samples.Count(i);
231
86.7M
        size_t eb = rt.nbits * count;
232
86.7M
        counts[pred * max_symbols + rt.tok] += count;
233
86.7M
        extra_bits += eb;
234
86.7M
      }
235
485k
      tot_extra_bits[pred] = extra_bits;
236
485k
    }
237
238
485k
    float base_bits;
239
485k
    {
240
485k
      size_t pred = tree_samples.PredictorIndex((*tree)[pos].predictor);
241
485k
      base_bits =
242
485k
          EstimateBits(counts.data() + pred * max_symbols, max_symbols) +
243
485k
          tot_extra_bits[pred];
244
485k
    }
245
246
485k
    SplitInfo *best = &best_split_nonstatic;
247
248
485k
    SplitInfo forced_split;
249
    // The multiplier ranges cut halfway through the current ranges of static
250
    // properties. We do this even if the current node is not a leaf, to
251
    // minimize the number of nodes in the resulting tree.
252
485k
    for (const auto &mmi : mul_info) {
253
107k
      uint32_t axis;
254
107k
      uint32_t val;
255
107k
      IntersectionType t =
256
107k
          BoxIntersects(static_prop_range, mmi.range, axis, val);
257
107k
      if (t == IntersectionType::kNone) continue;
258
107k
      if (t == IntersectionType::kInside) {
259
107k
        (*tree)[pos].multiplier = mmi.multiplier;
260
107k
        break;
261
107k
      }
262
0
      if (t == IntersectionType::kPartial) {
263
0
        JXL_DASSERT(axis < kNumStaticProperties);
264
0
        forced_split.val = tree_samples.QuantizeStaticProperty(axis, val);
265
0
        forced_split.prop = axis;
266
0
        forced_split.lcost = forced_split.rcost = base_bits / 2 - threshold;
267
0
        forced_split.lpred = forced_split.rpred = (*tree)[pos].predictor;
268
0
        best = &forced_split;
269
0
        best->pos = begin;
270
0
        JXL_DASSERT(best->prop == tree_samples.PropertyFromIndex(best->prop));
271
0
        if (best->prop < tree_samples.NumStaticProps()) {
272
0
        for (size_t x = begin; x < end; x++) {
273
0
          if (tree_samples.Property<true>(best->prop, x) <= best->val) {
274
0
            best->pos++;
275
0
          }
276
0
        }
277
0
      } else {
278
0
        size_t prop = best->prop - tree_samples.NumStaticProps();
279
0
        for (size_t x = begin; x < end; x++) {
280
0
          if (tree_samples.Property<false>(prop, x) <= best->val) {
281
0
            best->pos++;
282
0
          }
283
0
        }
284
0
      }
285
0
        break;
286
0
      }
287
0
    }
288
289
485k
    if (best != &forced_split) {
290
485k
      std::vector<int> prop_value_used_count;
291
485k
      std::vector<int> count_increase;
292
485k
      std::vector<size_t> extra_bits_increase;
293
      // For each property, compute which of its values are used, and what
294
      // tokens correspond to those usages. Then, iterate through the values,
295
      // and compute the entropy of each side of the split (of the form `prop >
296
      // threshold`). Finally, find the split that minimizes the cost.
297
485k
      struct CostInfo {
298
485k
        float cost = std::numeric_limits<float>::max();
299
485k
        float extra_cost = 0;
300
485k
        float Cost() const { return cost + extra_cost; }
301
485k
        Predictor pred;  // will be uninitialized in some cases, but never used.
302
485k
      };
303
485k
      std::vector<CostInfo> costs_l;
304
485k
      std::vector<CostInfo> costs_r;
305
306
485k
      std::vector<int32_t> counts_above(max_symbols);
307
485k
      std::vector<int32_t> counts_below(max_symbols);
308
309
      // The lower the threshold, the higher the expected noisiness of the
310
      // estimate. Thus, discourage changing predictors.
311
485k
      float change_pred_penalty = 800.0f / (100.0f + threshold);
312
3.69M
      for (size_t prop = 0; prop < num_properties && base_bits > threshold;
313
3.20M
           prop++) {
314
3.20M
        costs_l.clear();
315
3.20M
        costs_r.clear();
316
3.20M
        size_t prop_size = tree_samples.NumPropertyValues(prop);
317
3.20M
        if (extra_bits_increase.size() < prop_size) {
318
1.09M
          count_increase.resize(prop_size * max_symbols);
319
1.09M
          extra_bits_increase.resize(prop_size);
320
1.09M
        }
321
        // Clear prop_value_used_count (which cannot be cleared "on the go")
322
3.20M
        prop_value_used_count.clear();
323
3.20M
        prop_value_used_count.resize(prop_size);
324
325
3.20M
        size_t first_used = prop_size;
326
3.20M
        size_t last_used = 0;
327
328
        // TODO(veluca): consider finding multiple splits along a single
329
        // property at the same time, possibly with a bottom-up approach.
330
3.20M
        if (prop < tree_samples.NumStaticProps()) {
331
131M
          for (size_t i = begin; i < end; i++) {
332
130M
            size_t p = tree_samples.Property<true>(prop, i);
333
130M
            prop_value_used_count[p]++;
334
130M
            last_used = std::max(last_used, p);
335
130M
            first_used = std::min(first_used, p);
336
130M
          }
337
2.53M
        } else {
338
2.53M
          size_t prop_idx = prop - tree_samples.NumStaticProps();
339
477M
          for (size_t i = begin; i < end; i++) {
340
474M
            size_t p = tree_samples.Property<false>(prop_idx, i);
341
474M
            prop_value_used_count[p]++;
342
474M
            last_used = std::max(last_used, p);
343
474M
            first_used = std::min(first_used, p);
344
474M
          }
345
2.53M
        }
346
3.20M
        costs_l.resize(last_used - first_used);
347
3.20M
        costs_r.resize(last_used - first_used);
348
        // For all predictors, compute the right and left costs of each split.
349
6.41M
        for (size_t pred = 0; pred < num_predictors; pred++) {
350
          // Compute cost and histogram increments for each property value.
351
3.20M
          const std::vector<ResidualToken> &rtokens =
352
3.20M
              tree_samples.RTokens(pred);
353
3.20M
          if (prop < tree_samples.NumStaticProps()) {
354
675k
            CollectExtraBitsIncrease<true>(tree_samples, rtokens,
355
675k
                                           count_increase, extra_bits_increase,
356
675k
                                           begin, end, prop, max_symbols);
357
2.53M
          } else {
358
2.53M
            CollectExtraBitsIncrease<false>(
359
2.53M
                tree_samples, rtokens, count_increase, extra_bits_increase,
360
2.53M
                begin, end, prop - tree_samples.NumStaticProps(), max_symbols);
361
2.53M
          }
362
3.20M
          memcpy(counts_above.data(), counts.data() + pred * max_symbols,
363
3.20M
                 max_symbols * sizeof counts_above[0]);
364
3.20M
          memset(counts_below.data(), 0, max_symbols * sizeof counts_below[0]);
365
3.20M
          size_t extra_bits_below = 0;
366
          // Exclude last used: this ensures neither counts_above nor
367
          // counts_below is empty.
368
41.1M
          for (size_t i = first_used; i < last_used; i++) {
369
37.9M
            if (!prop_value_used_count[i]) continue;
370
18.1M
            extra_bits_below += extra_bits_increase[i];
371
            // The increase for this property value has been used, and will not
372
            // be used again: clear it. Also below.
373
18.1M
            extra_bits_increase[i] = 0;
374
935M
            for (size_t sym = 0; sym < max_symbols; sym++) {
375
917M
              counts_above[sym] -= count_increase[i * max_symbols + sym];
376
917M
              counts_below[sym] += count_increase[i * max_symbols + sym];
377
917M
              count_increase[i * max_symbols + sym] = 0;
378
917M
            }
379
18.1M
            float rcost = EstimateBits(counts_above.data(), max_symbols) +
380
18.1M
                          tot_extra_bits[pred] - extra_bits_below;
381
18.1M
            float lcost = EstimateBits(counts_below.data(), max_symbols) +
382
18.1M
                          extra_bits_below;
383
18.1M
            JXL_DASSERT(extra_bits_below <= tot_extra_bits[pred]);
384
18.1M
            float penalty = 0;
385
            // Never discourage moving away from the Weighted predictor.
386
18.1M
            if (tree_samples.PredictorFromIndex(pred) !=
387
18.1M
                    (*tree)[pos].predictor &&
388
0
                (*tree)[pos].predictor != Predictor::Weighted) {
389
0
              penalty = change_pred_penalty;
390
0
            }
391
            // If everything else is equal, disfavour Weighted (slower) and
392
            // favour Zero (faster if it's the only predictor used in a
393
            // group+channel combination)
394
18.1M
            if (tree_samples.PredictorFromIndex(pred) == Predictor::Weighted) {
395
0
              penalty += 1e-8;
396
0
            }
397
18.1M
            if (tree_samples.PredictorFromIndex(pred) == Predictor::Zero) {
398
0
              penalty -= 1e-8;
399
0
            }
400
18.1M
            if (rcost + penalty < costs_r[i - first_used].Cost()) {
401
18.1M
              costs_r[i - first_used].cost = rcost;
402
18.1M
              costs_r[i - first_used].extra_cost = penalty;
403
18.1M
              costs_r[i - first_used].pred =
404
18.1M
                  tree_samples.PredictorFromIndex(pred);
405
18.1M
            }
406
18.1M
            if (lcost + penalty < costs_l[i - first_used].Cost()) {
407
18.1M
              costs_l[i - first_used].cost = lcost;
408
18.1M
              costs_l[i - first_used].extra_cost = penalty;
409
18.1M
              costs_l[i - first_used].pred =
410
18.1M
                  tree_samples.PredictorFromIndex(pred);
411
18.1M
            }
412
18.1M
          }
413
3.20M
        }
414
        // Iterate through the possible splits and find the one with minimum sum
415
        // of costs of the two sides.
416
3.20M
        size_t split = begin;
417
41.1M
        for (size_t i = first_used; i < last_used; i++) {
418
37.9M
          if (!prop_value_used_count[i]) continue;
419
18.1M
          split += prop_value_used_count[i];
420
18.1M
          float rcost = costs_r[i - first_used].cost;
421
18.1M
          float lcost = costs_l[i - first_used].cost;
422
423
18.1M
          bool uses_wp = tree_samples.PropertyFromIndex(prop) == kWPProp ||
424
14.7M
                         costs_l[i - first_used].pred == Predictor::Weighted ||
425
14.7M
                         costs_r[i - first_used].pred == Predictor::Weighted;
426
18.1M
          bool zero_entropy_side = rcost == 0 || lcost == 0;
427
428
18.1M
          SplitInfo &best_ref =
429
18.1M
              tree_samples.PropertyFromIndex(prop) < kNumStaticProperties
430
18.1M
                  ? (zero_entropy_side ? best_split_static_constant
431
106k
                                       : best_split_static)
432
18.1M
                  : (uses_wp ? best_split_nonstatic : best_split_nowp);
433
18.1M
          if (lcost + rcost < best_ref.Cost()) {
434
3.55M
            best_ref.prop = prop;
435
3.55M
            best_ref.val = i;
436
3.55M
            best_ref.pos = split;
437
3.55M
            best_ref.lcost = lcost;
438
3.55M
            best_ref.lpred = costs_l[i - first_used].pred;
439
3.55M
            best_ref.rcost = rcost;
440
3.55M
            best_ref.rpred = costs_r[i - first_used].pred;
441
3.55M
          }
442
18.1M
        }
443
        // Clear extra_bits_increase and cost_increase for last_used.
444
3.20M
        extra_bits_increase[last_used] = 0;
445
168M
        for (size_t sym = 0; sym < max_symbols; sym++) {
446
165M
          count_increase[last_used * max_symbols + sym] = 0;
447
165M
        }
448
3.20M
      }
449
450
      // Try to avoid introducing WP.
451
485k
      if (best_split_nowp.Cost() + threshold < base_bits &&
452
233k
          best_split_nowp.Cost() <= fast_decode_multiplier * best->Cost()) {
453
218k
        best = &best_split_nowp;
454
218k
      }
455
      // Split along static props if possible and not significantly more
456
      // expensive.
457
485k
      if (best_split_static.Cost() + threshold < base_bits &&
458
35.2k
          best_split_static.Cost() <= fast_decode_multiplier * best->Cost()) {
459
7.82k
        best = &best_split_static;
460
7.82k
      }
461
      // Split along static props to create constant nodes if possible.
462
485k
      if (best_split_static_constant.Cost() + threshold < base_bits) {
463
539
        best = &best_split_static_constant;
464
539
      }
465
485k
    }
466
467
485k
    if (best->Cost() + threshold < base_bits) {
468
241k
      uint32_t p = tree_samples.PropertyFromIndex(best->prop);
469
241k
      pixel_type dequant =
470
241k
          tree_samples.UnquantizeProperty(best->prop, best->val);
471
      // Split node and try to split children.
472
241k
      MakeSplitNode(pos, p, dequant, best->lpred, 0, best->rpred, 0, tree);
473
      // "Sort" according to winning property
474
241k
      if (best->prop < tree_samples.NumStaticProps()) {
475
8.20k
        SplitTreeSamples<true>(tree_samples, begin, best->pos, end, best->prop,
476
8.20k
                               best->val);
477
233k
      } else {
478
233k
        SplitTreeSamples<false>(tree_samples, begin, best->pos, end,
479
233k
                                best->prop - tree_samples.NumStaticProps(),
480
233k
                                best->val);
481
233k
      }
482
241k
      auto new_sp_range = static_prop_range;
483
241k
      if (p < kNumStaticProperties) {
484
8.20k
        JXL_DASSERT(static_cast<uint32_t>(dequant + 1) <= new_sp_range[p][1]);
485
8.20k
        new_sp_range[p][1] = dequant + 1;
486
8.20k
        JXL_DASSERT(new_sp_range[p][0] < new_sp_range[p][1]);
487
8.20k
      }
488
241k
      nodes.push_back(
489
241k
          NodeInfo{(*tree)[pos].rchild, begin, best->pos, new_sp_range});
490
241k
      new_sp_range = static_prop_range;
491
241k
      if (p < kNumStaticProperties) {
492
8.20k
        JXL_DASSERT(new_sp_range[p][0] <= static_cast<uint32_t>(dequant + 1));
493
8.20k
        new_sp_range[p][0] = dequant + 1;
494
8.20k
        JXL_DASSERT(new_sp_range[p][0] < new_sp_range[p][1]);
495
8.20k
      }
496
241k
      nodes.push_back(
497
241k
          NodeInfo{(*tree)[pos].lchild, best->pos, end, new_sp_range});
498
241k
    }
499
485k
  }
500
3.06k
}
Unexecuted instantiation: jxl::N_SSE2::FindBestSplit(jxl::TreeSamples&, float, std::__1::vector<jxl::ModularMultiplierInfo, std::__1::allocator<jxl::ModularMultiplierInfo> > const&, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, float, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)
501
502
// NOLINTNEXTLINE(google-readability-namespace-comments)
503
}  // namespace HWY_NAMESPACE
504
}  // namespace jxl
505
HWY_AFTER_NAMESPACE();
506
507
#if HWY_ONCE
508
namespace jxl {
509
510
HWY_EXPORT(FindBestSplit);  // Local function.
511
512
Status ComputeBestTree(TreeSamples &tree_samples, float threshold,
513
                       const std::vector<ModularMultiplierInfo> &mul_info,
514
                       StaticPropRange static_prop_range,
515
3.06k
                       float fast_decode_multiplier, Tree *tree) {
516
  // TODO(veluca): take into account that different contexts can have different
517
  // uint configs.
518
  //
519
  // Initialize tree.
520
3.06k
  tree->emplace_back();
521
3.06k
  tree->back().property = -1;
522
3.06k
  tree->back().predictor = tree_samples.PredictorFromIndex(0);
523
3.06k
  tree->back().predictor_offset = 0;
524
3.06k
  tree->back().multiplier = 1;
525
3.06k
  JXL_ENSURE(tree_samples.NumProperties() < 64);
526
527
3.06k
  JXL_ENSURE(tree_samples.NumDistinctSamples() <=
528
3.06k
             std::numeric_limits<uint32_t>::max());
529
3.06k
  HWY_DYNAMIC_DISPATCH(FindBestSplit)
530
3.06k
  (tree_samples, threshold, mul_info, static_prop_range, fast_decode_multiplier,
531
3.06k
   tree);
532
3.06k
  return true;
533
3.06k
}
534
535
#if JXL_CXX_LANG < JXL_CXX_17
536
constexpr int32_t TreeSamples::kPropertyRange;
537
constexpr uint32_t TreeSamples::kDedupEntryUnused;
538
#endif
539
540
Status TreeSamples::SetPredictor(Predictor predictor,
541
3.24k
                                 ModularOptions::TreeMode wp_tree_mode) {
542
3.24k
  if (wp_tree_mode == ModularOptions::TreeMode::kWPOnly) {
543
0
    predictors = {Predictor::Weighted};
544
0
    residuals.resize(1);
545
0
    return true;
546
0
  }
547
3.24k
  if (wp_tree_mode == ModularOptions::TreeMode::kNoWP &&
548
0
      predictor == Predictor::Weighted) {
549
0
    return JXL_FAILURE("Invalid predictor settings");
550
0
  }
551
3.24k
  if (predictor == Predictor::Variable) {
552
0
    for (size_t i = 0; i < kNumModularPredictors; i++) {
553
0
      predictors.push_back(static_cast<Predictor>(i));
554
0
    }
555
0
    std::swap(predictors[0], predictors[static_cast<int>(Predictor::Weighted)]);
556
0
    std::swap(predictors[1], predictors[static_cast<int>(Predictor::Gradient)]);
557
3.24k
  } else if (predictor == Predictor::Best) {
558
0
    predictors = {Predictor::Weighted, Predictor::Gradient};
559
3.24k
  } else {
560
3.24k
    predictors = {predictor};
561
3.24k
  }
562
3.24k
  if (wp_tree_mode == ModularOptions::TreeMode::kNoWP) {
563
0
    predictors.erase(
564
0
        std::remove(predictors.begin(), predictors.end(), Predictor::Weighted),
565
0
        predictors.end());
566
0
  }
567
3.24k
  residuals.resize(predictors.size());
568
3.24k
  return true;
569
3.24k
}
570
571
Status TreeSamples::SetProperties(const std::vector<uint32_t> &properties,
572
3.24k
                                  ModularOptions::TreeMode wp_tree_mode) {
573
3.24k
  props_to_use = properties;
574
3.24k
  if (wp_tree_mode == ModularOptions::TreeMode::kWPOnly) {
575
0
    props_to_use = {static_cast<uint32_t>(kWPProp)};
576
0
  }
577
3.24k
  if (wp_tree_mode == ModularOptions::TreeMode::kGradientOnly) {
578
0
    props_to_use = {static_cast<uint32_t>(kGradientProp)};
579
0
  }
580
3.24k
  if (wp_tree_mode == ModularOptions::TreeMode::kNoWP) {
581
0
    props_to_use.erase(
582
0
        std::remove(props_to_use.begin(), props_to_use.end(), kWPProp),
583
0
        props_to_use.end());
584
0
  }
585
3.24k
  if (props_to_use.empty()) {
586
0
    return JXL_FAILURE("Invalid property set configuration");
587
0
  }
588
3.24k
  num_static_props = 0;
589
  // Check that if static properties present, then those are at the beginning.
590
25.9k
  for (size_t i = 0; i < props_to_use.size(); ++i) {
591
22.6k
    uint32_t prop = props_to_use[i];
592
22.6k
    if (prop < kNumStaticProperties) {
593
5.17k
      JXL_DASSERT(i == prop);
594
5.17k
      num_static_props++;
595
5.17k
    }
596
22.6k
  }
597
3.24k
  props.resize(props_to_use.size() - num_static_props);
598
3.24k
  return true;
599
3.24k
}
600
601
7.24k
void TreeSamples::InitTable(size_t log_size) {
602
7.24k
  size_t size = 1ULL << log_size;
603
7.24k
  if (dedup_table_.size() == size) return;
604
5.42k
  dedup_table_.resize(size, kDedupEntryUnused);
605
6.85M
  for (size_t i = 0; i < NumDistinctSamples(); i++) {
606
6.85M
    if (sample_counts[i] != std::numeric_limits<uint16_t>::max()) {
607
6.85M
      AddToTable(i);
608
6.85M
    }
609
6.85M
  }
610
5.42k
}
611
612
69.2M
bool TreeSamples::AddToTableAndMerge(size_t a) {
613
69.2M
  size_t pos1 = Hash1(a);
614
69.2M
  size_t pos2 = Hash2(a);
615
69.2M
  if (dedup_table_[pos1] != kDedupEntryUnused &&
616
63.0M
      IsSameSample(a, dedup_table_[pos1])) {
617
54.0M
    JXL_DASSERT(sample_counts[a] == 1);
618
54.0M
    sample_counts[dedup_table_[pos1]]++;
619
    // Remove from hash table samples that are saturated.
620
54.0M
    if (sample_counts[dedup_table_[pos1]] ==
621
54.0M
        std::numeric_limits<uint16_t>::max()) {
622
46
      dedup_table_[pos1] = kDedupEntryUnused;
623
46
    }
624
54.0M
    return true;
625
54.0M
  }
626
15.2M
  if (dedup_table_[pos2] != kDedupEntryUnused &&
627
8.24M
      IsSameSample(a, dedup_table_[pos2])) {
628
5.95M
    JXL_DASSERT(sample_counts[a] == 1);
629
5.95M
    sample_counts[dedup_table_[pos2]]++;
630
    // Remove from hash table samples that are saturated.
631
5.95M
    if (sample_counts[dedup_table_[pos2]] ==
632
5.95M
        std::numeric_limits<uint16_t>::max()) {
633
3
      dedup_table_[pos2] = kDedupEntryUnused;
634
3
    }
635
5.95M
    return true;
636
5.95M
  }
637
9.28M
  AddToTable(a);
638
9.28M
  return false;
639
15.2M
}
640
641
16.1M
void TreeSamples::AddToTable(size_t a) {
642
16.1M
  size_t pos1 = Hash1(a);
643
16.1M
  size_t pos2 = Hash2(a);
644
16.1M
  if (dedup_table_[pos1] == kDedupEntryUnused) {
645
8.31M
    dedup_table_[pos1] = a;
646
8.31M
  } else if (dedup_table_[pos2] == kDedupEntryUnused) {
647
4.09M
    dedup_table_[pos2] = a;
648
4.09M
  }
649
16.1M
}
650
651
7.24k
void TreeSamples::PrepareForSamples(size_t extra_num_samples) {
652
7.24k
  for (auto &res : residuals) {
653
7.24k
    res.reserve(res.size() + extra_num_samples);
654
7.24k
  }
655
18.9k
  for (size_t i = 0; i < num_static_props; ++i) {
656
11.6k
    static_props[i].reserve(static_props[i].size() + extra_num_samples);
657
11.6k
  }
658
39.0k
  for (auto &p : props) {
659
39.0k
    p.reserve(p.size() + extra_num_samples);
660
39.0k
  }
661
7.24k
  size_t total_num_samples = extra_num_samples + sample_counts.size();
662
7.24k
  size_t next_size = CeilLog2Nonzero(total_num_samples * 3 / 2);
663
7.24k
  InitTable(next_size);
664
7.24k
}
665
666
85.4M
size_t TreeSamples::Hash1(size_t a) const {
667
85.4M
  constexpr uint64_t constant = 0x1e35a7bd;
668
85.4M
  uint64_t h = constant;
669
85.4M
  for (const auto &r : residuals) {
670
85.4M
    h = h * constant + r[a].tok;
671
85.4M
    h = h * constant + r[a].nbits;
672
85.4M
  }
673
213M
  for (size_t i = 0; i < num_static_props; ++i) {
674
128M
    h = h * constant + static_props[i][a];
675
128M
  }
676
469M
  for (const auto &p : props) {
677
469M
    h = h * constant + p[a];
678
469M
  }
679
85.4M
  return (h >> 16) & (dedup_table_.size() - 1);
680
85.4M
}
681
85.4M
size_t TreeSamples::Hash2(size_t a) const {
682
85.4M
  constexpr uint64_t constant = 0x1e35a7bd1e35a7bd;
683
85.4M
  uint64_t h = constant;
684
213M
  for (size_t i = 0; i < num_static_props; ++i) {
685
128M
    h = h * constant ^ static_props[i][a];
686
128M
  }
687
469M
  for (const auto &p : props) {
688
469M
    h = h * constant ^ p[a];
689
469M
  }
690
85.4M
  for (const auto &r : residuals) {
691
85.4M
    h = h * constant ^ r[a].tok;
692
85.4M
    h = h * constant ^ r[a].nbits;
693
85.4M
  }
694
85.4M
  return (h >> 16) & (dedup_table_.size() - 1);
695
85.4M
}
696
697
71.2M
bool TreeSamples::IsSameSample(size_t a, size_t b) const {
698
71.2M
  bool ret = true;
699
71.2M
  for (const auto &r : residuals) {
700
71.2M
    if (r[a].tok != r[b].tok) {
701
5.50M
      ret = false;
702
5.50M
    }
703
71.2M
    if (r[a].nbits != r[b].nbits) {
704
4.10M
      ret = false;
705
4.10M
    }
706
71.2M
  }
707
178M
  for (size_t i = 0; i < num_static_props; ++i) {
708
106M
    if (static_props[i][a] != static_props[i][b]) {
709
3.03M
      ret = false;
710
3.03M
    }
711
106M
  }
712
391M
  for (const auto &p : props) {
713
391M
    if (p[a] != p[b]) {
714
31.8M
      ret = false;
715
31.8M
    }
716
391M
  }
717
71.2M
  return ret;
718
71.2M
}
719
720
void TreeSamples::AddSample(pixel_type_w pixel, const Properties &properties,
721
69.2M
                            const pixel_type_w *predictions) {
722
138M
  for (size_t i = 0; i < predictors.size(); i++) {
723
69.2M
    pixel_type v = pixel - predictions[static_cast<int>(predictors[i])];
724
69.2M
    uint32_t tok, nbits, bits;
725
69.2M
    HybridUintConfig(4, 1, 2).Encode(PackSigned(v), &tok, &nbits, &bits);
726
69.2M
    JXL_DASSERT(tok < 256);
727
69.2M
    JXL_DASSERT(nbits < 256);
728
69.2M
    ResidualToken token = {static_cast<uint8_t>(tok),
729
69.2M
                           static_cast<uint8_t>(nbits)};
730
69.2M
    residuals[i].push_back(token);
731
69.2M
  }
732
174M
  for (size_t i = 0; i < num_static_props; ++i) {
733
105M
    static_props[i].push_back(QuantizeStaticProperty(i, properties[i]));
734
105M
  }
735
449M
  for (size_t i = num_static_props; i < props_to_use.size(); i++) {
736
379M
    props[i - num_static_props].push_back(QuantizeProperty(i, properties[props_to_use[i]]));
737
379M
  }
738
69.2M
  sample_counts.push_back(1);
739
69.2M
  num_samples++;
740
69.2M
  if (AddToTableAndMerge(sample_counts.size() - 1)) {
741
60.0M
    for (auto &r : residuals) r.pop_back();
742
150M
    for (size_t i = 0; i < num_static_props; ++i) static_props[i].pop_back();
743
329M
    for (auto &p : props) p.pop_back();
744
60.0M
    sample_counts.pop_back();
745
60.0M
  }
746
69.2M
}
747
748
15.0M
void TreeSamples::Swap(size_t a, size_t b) {
749
15.0M
  if (a == b) return;
750
15.0M
  for (auto &r : residuals) {
751
15.0M
    std::swap(r[a], r[b]);
752
15.0M
  }
753
37.4M
  for (size_t i = 0; i < num_static_props; ++i) {
754
22.3M
    std::swap(static_props[i][a], static_props[i][b]);
755
22.3M
  }
756
82.6M
  for (auto &p : props) {
757
82.6M
    std::swap(p[a], p[b]);
758
82.6M
  }
759
15.0M
  std::swap(sample_counts[a], sample_counts[b]);
760
15.0M
}
761
762
namespace {
763
std::vector<int32_t> QuantizeHistogram(const std::vector<uint32_t> &histogram,
764
9.99k
                                       size_t num_chunks) {
765
9.99k
  if (histogram.empty() || num_chunks == 0) return {};
766
9.99k
  uint64_t sum = std::accumulate(histogram.begin(), histogram.end(), 0LU);
767
9.99k
  if (sum == 0) return {};
768
  // TODO(veluca): selecting distinct quantiles is likely not the best
769
  // way to go about this.
770
9.73k
  std::vector<int32_t> thresholds;
771
9.73k
  uint64_t cumsum = 0;
772
9.73k
  uint64_t threshold = 1;
773
4.96M
  for (size_t i = 0; i < histogram.size(); i++) {
774
4.95M
    cumsum += histogram[i];
775
4.95M
    if (cumsum * num_chunks >= threshold * sum) {
776
57.9k
      thresholds.push_back(i);
777
992k
      while (cumsum * num_chunks >= threshold * sum) threshold++;
778
57.9k
    }
779
4.95M
  }
780
9.73k
  JXL_DASSERT(thresholds.size() <= num_chunks);
781
  // last value collects all histogram and is not really a threshold
782
9.73k
  thresholds.pop_back();
783
9.73k
  return thresholds;
784
9.99k
}
785
786
std::vector<int32_t> QuantizeSamples(const std::vector<int32_t> &samples,
787
5.98k
                                     size_t num_chunks) {
788
5.98k
  if (samples.empty()) return {};
789
4.82k
  int min = *std::min_element(samples.begin(), samples.end());
790
4.82k
  constexpr int kRange = 512;
791
4.82k
  min = jxl::Clamp1(min, -kRange, kRange);
792
4.82k
  std::vector<uint32_t> counts(2 * kRange + 1);
793
10.0M
  for (int s : samples) {
794
10.0M
    uint32_t sample_offset = jxl::Clamp1(s, -kRange, kRange) - min;
795
10.0M
    counts[sample_offset]++;
796
10.0M
  }
797
4.82k
  std::vector<int32_t> thresholds = QuantizeHistogram(counts, num_chunks);
798
45.4k
  for (auto &v : thresholds) v += min;
799
4.82k
  return thresholds;
800
5.98k
}
801
802
// `to[i]` is assigned value `v` conforming `from[v] <= i && from[v-1] > i`.
803
// This is because the decision node in the tree splits on (property) > i,
804
// hence everything that is not > of a threshold should be clustered
805
// together.
806
template <typename T>
807
void QuantMap(const std::vector<int32_t> &from, std::vector<T> &to,
808
22.6k
              size_t num_pegs, int bias) {
809
22.6k
  to.resize(num_pegs);
810
22.6k
  size_t mapped = 0;
811
23.2M
  for (size_t i = 0; i < num_pegs; i++) {
812
23.5M
    while (mapped < from.size() && static_cast<int>(i) - bias > from[mapped]) {
813
378k
      mapped++;
814
378k
    }
815
23.2M
    JXL_DASSERT(static_cast<T>(mapped) == mapped);
816
23.2M
    to[i] = mapped;
817
23.2M
  }
818
22.6k
}
enc_ma.cc:void jxl::(anonymous namespace)::QuantMap<unsigned short>(std::__1::vector<int, std::__1::allocator<int> > const&, std::__1::vector<unsigned short, std::__1::allocator<unsigned short> >&, unsigned long, int)
Line
Count
Source
808
5.17k
              size_t num_pegs, int bias) {
809
5.17k
  to.resize(num_pegs);
810
5.17k
  size_t mapped = 0;
811
5.29M
  for (size_t i = 0; i < num_pegs; i++) {
812
5.29M
    while (mapped < from.size() && static_cast<int>(i) - bias > from[mapped]) {
813
2.74k
      mapped++;
814
2.74k
    }
815
5.28M
    JXL_DASSERT(static_cast<T>(mapped) == mapped);
816
5.28M
    to[i] = mapped;
817
5.28M
  }
818
5.17k
}
enc_ma.cc:void jxl::(anonymous namespace)::QuantMap<unsigned char>(std::__1::vector<int, std::__1::allocator<int> > const&, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> >&, unsigned long, int)
Line
Count
Source
808
17.5k
              size_t num_pegs, int bias) {
809
17.5k
  to.resize(num_pegs);
810
17.5k
  size_t mapped = 0;
811
17.9M
  for (size_t i = 0; i < num_pegs; i++) {
812
18.3M
    while (mapped < from.size() && static_cast<int>(i) - bias > from[mapped]) {
813
376k
      mapped++;
814
376k
    }
815
17.9M
    JXL_DASSERT(static_cast<T>(mapped) == mapped);
816
17.9M
    to[i] = mapped;
817
17.9M
  }
818
17.5k
}
819
}  // namespace
820
821
void TreeSamples::PreQuantizeProperties(
822
    const StaticPropRange &range,
823
    const std::vector<ModularMultiplierInfo> &multiplier_info,
824
    const std::vector<uint32_t> &group_pixel_count,
825
    const std::vector<uint32_t> &channel_pixel_count,
826
    std::vector<pixel_type> &pixel_samples,
827
3.24k
    std::vector<pixel_type> &diff_samples, size_t max_property_values) {
828
  // If we have forced splits because of multipliers, choose channel and group
829
  // thresholds accordingly.
830
3.24k
  std::vector<int32_t> group_multiplier_thresholds;
831
3.24k
  std::vector<int32_t> channel_multiplier_thresholds;
832
3.24k
  for (const auto &v : multiplier_info) {
833
909
    if (v.range[0][0] != range[0][0]) {
834
0
      channel_multiplier_thresholds.push_back(v.range[0][0] - 1);
835
0
    }
836
909
    if (v.range[0][1] != range[0][1]) {
837
0
      channel_multiplier_thresholds.push_back(v.range[0][1] - 1);
838
0
    }
839
909
    if (v.range[1][0] != range[1][0]) {
840
0
      group_multiplier_thresholds.push_back(v.range[1][0] - 1);
841
0
    }
842
909
    if (v.range[1][1] != range[1][1]) {
843
0
      group_multiplier_thresholds.push_back(v.range[1][1] - 1);
844
0
    }
845
909
  }
846
3.24k
  std::sort(channel_multiplier_thresholds.begin(),
847
3.24k
            channel_multiplier_thresholds.end());
848
3.24k
  channel_multiplier_thresholds.resize(
849
3.24k
      std::unique(channel_multiplier_thresholds.begin(),
850
3.24k
                  channel_multiplier_thresholds.end()) -
851
3.24k
      channel_multiplier_thresholds.begin());
852
3.24k
  std::sort(group_multiplier_thresholds.begin(),
853
3.24k
            group_multiplier_thresholds.end());
854
3.24k
  group_multiplier_thresholds.resize(
855
3.24k
      std::unique(group_multiplier_thresholds.begin(),
856
3.24k
                  group_multiplier_thresholds.end()) -
857
3.24k
      group_multiplier_thresholds.begin());
858
859
3.24k
  compact_properties.resize(props_to_use.size());
860
3.24k
  auto quantize_channel = [&]() {
861
3.24k
    if (!channel_multiplier_thresholds.empty()) {
862
0
      return channel_multiplier_thresholds;
863
0
    }
864
3.24k
    return QuantizeHistogram(channel_pixel_count, max_property_values);
865
3.24k
  };
866
3.24k
  auto quantize_group_id = [&]() {
867
1.92k
    if (!group_multiplier_thresholds.empty()) {
868
0
      return group_multiplier_thresholds;
869
0
    }
870
1.92k
    return QuantizeHistogram(group_pixel_count, max_property_values);
871
1.92k
  };
872
3.24k
  auto quantize_coordinate = [&]() {
873
0
    std::vector<int32_t> quantized;
874
0
    quantized.reserve(max_property_values - 1);
875
0
    for (size_t i = 0; i + 1 < max_property_values; i++) {
876
0
      quantized.push_back((i + 1) * 256 / max_property_values - 1);
877
0
    }
878
0
    return quantized;
879
0
  };
880
3.24k
  std::vector<int32_t> abs_pixel_thresholds;
881
3.24k
  std::vector<int32_t> pixel_thresholds;
882
3.24k
  auto quantize_pixel_property = [&]() {
883
0
    if (pixel_thresholds.empty()) {
884
0
      pixel_thresholds = QuantizeSamples(pixel_samples, max_property_values);
885
0
    }
886
0
    return pixel_thresholds;
887
0
  };
888
3.24k
  auto quantize_abs_pixel_property = [&]() {
889
0
    if (abs_pixel_thresholds.empty()) {
890
0
      quantize_pixel_property();  // Compute the non-abs thresholds.
891
0
      for (auto &v : pixel_samples) v = std::abs(v);
892
0
      abs_pixel_thresholds =
893
0
          QuantizeSamples(pixel_samples, max_property_values);
894
0
    }
895
0
    return abs_pixel_thresholds;
896
0
  };
897
3.24k
  std::vector<int32_t> abs_diff_thresholds;
898
3.24k
  std::vector<int32_t> diff_thresholds;
899
14.2k
  auto quantize_diff_property = [&]() {
900
14.2k
    if (diff_thresholds.empty()) {
901
5.98k
      diff_thresholds = QuantizeSamples(diff_samples, max_property_values);
902
5.98k
    }
903
14.2k
    return diff_thresholds;
904
14.2k
  };
905
3.24k
  auto quantize_abs_diff_property = [&]() {
906
0
    if (abs_diff_thresholds.empty()) {
907
0
      quantize_diff_property();  // Compute the non-abs thresholds.
908
0
      for (auto &v : diff_samples) v = std::abs(v);
909
0
      abs_diff_thresholds = QuantizeSamples(diff_samples, max_property_values);
910
0
    }
911
0
    return abs_diff_thresholds;
912
0
  };
913
3.24k
  auto quantize_wp = [&]() {
914
3.24k
    if (max_property_values < 32) {
915
0
      return std::vector<int32_t>{-127, -63, -31, -15, -7, -3, -1, 0,
916
0
                                  1,    3,   7,   15,  31, 63, 127};
917
0
    }
918
3.24k
    if (max_property_values < 64) {
919
0
      return std::vector<int32_t>{-255, -191, -127, -95, -63, -47, -31, -23,
920
0
                                  -15,  -11,  -7,   -5,  -3,  -1,  0,   1,
921
0
                                  3,    5,    7,    11,  15,  23,  31,  47,
922
0
                                  63,   95,   127,  191, 255};
923
0
    }
924
3.24k
    return std::vector<int32_t>{
925
3.24k
        -255, -223, -191, -159, -127, -111, -95, -79, -63, -55, -47,
926
3.24k
        -39,  -31,  -27,  -23,  -19,  -15,  -13, -11, -9,  -7,  -6,
927
3.24k
        -5,   -4,   -3,   -2,   -1,   0,    1,   2,   3,   4,   5,
928
3.24k
        6,    7,    9,    11,   13,   15,   19,  23,  27,  31,  39,
929
3.24k
        47,   55,   63,   79,   95,   111,  127, 159, 191, 223, 255};
930
3.24k
  };
931
932
3.24k
  property_mapping.resize(props_to_use.size() - num_static_props);
933
25.9k
  for (size_t i = 0; i < props_to_use.size(); i++) {
934
22.6k
    if (props_to_use[i] == 0) {
935
3.24k
      compact_properties[i] = quantize_channel();
936
19.4k
    } else if (props_to_use[i] == 1) {
937
1.92k
      compact_properties[i] = quantize_group_id();
938
17.5k
    } else if (props_to_use[i] == 2 || props_to_use[i] == 3) {
939
0
      compact_properties[i] = quantize_coordinate();
940
17.5k
    } else if (props_to_use[i] == 6 || props_to_use[i] == 7 ||
941
17.5k
               props_to_use[i] == 8 ||
942
17.5k
               (props_to_use[i] >= kNumNonrefProperties &&
943
0
                (props_to_use[i] - kNumNonrefProperties) % 4 == 1)) {
944
0
      compact_properties[i] = quantize_pixel_property();
945
17.5k
    } else if (props_to_use[i] == 4 || props_to_use[i] == 5 ||
946
17.5k
               (props_to_use[i] >= kNumNonrefProperties &&
947
0
                (props_to_use[i] - kNumNonrefProperties) % 4 == 0)) {
948
0
      compact_properties[i] = quantize_abs_pixel_property();
949
17.5k
    } else if (props_to_use[i] >= kNumNonrefProperties &&
950
0
               (props_to_use[i] - kNumNonrefProperties) % 4 == 2) {
951
0
      compact_properties[i] = quantize_abs_diff_property();
952
17.5k
    } else if (props_to_use[i] == kWPProp) {
953
3.24k
      compact_properties[i] = quantize_wp();
954
14.2k
    } else {
955
14.2k
      compact_properties[i] = quantize_diff_property();
956
14.2k
    }
957
22.6k
    if (i < num_static_props) {
958
5.17k
      QuantMap(compact_properties[i], static_property_mapping[i],
959
5.17k
               kPropertyRange * 2 + 1, kPropertyRange);
960
17.5k
    } else {
961
17.5k
      QuantMap(compact_properties[i], property_mapping[i - num_static_props],
962
17.5k
               kPropertyRange * 2 + 1, kPropertyRange);
963
17.5k
    }
964
22.6k
  }
965
3.24k
}
966
967
void CollectPixelSamples(const Image &image, const ModularOptions &options,
968
                         uint32_t group_id,
969
                         std::vector<uint32_t> &group_pixel_count,
970
                         std::vector<uint32_t> &channel_pixel_count,
971
                         std::vector<pixel_type> &pixel_samples,
972
4.47k
                         std::vector<pixel_type> &diff_samples) {
973
4.47k
  if (options.nb_repeats == 0) return;
974
4.47k
  if (group_pixel_count.size() <= group_id) {
975
4.47k
    group_pixel_count.resize(group_id + 1);
976
4.47k
  }
977
4.47k
  if (channel_pixel_count.size() < image.channel.size()) {
978
3.30k
    channel_pixel_count.resize(image.channel.size());
979
3.30k
  }
980
4.47k
  Rng rng(group_id);
981
  // Sample 10% of the final number of samples for property quantization.
982
4.47k
  float fraction = std::min(options.nb_repeats * 0.1, 0.99);
983
4.47k
  Rng::GeometricDistribution dist = Rng::MakeGeometric(fraction);
984
4.47k
  size_t total_pixels = 0;
985
4.47k
  std::vector<size_t> channel_ids;
986
11.7k
  for (size_t i = 0; i < image.channel.size(); i++) {
987
7.71k
    if (i >= image.nb_meta_channels &&
988
6.67k
        (image.channel[i].w > options.max_chan_size ||
989
6.22k
         image.channel[i].h > options.max_chan_size)) {
990
470
      break;
991
470
    }
992
7.24k
    if (image.channel[i].w <= 1 || image.channel[i].h == 0) {
993
56
      continue;  // skip empty or width-1 channels.
994
56
    }
995
7.18k
    channel_ids.push_back(i);
996
7.18k
    group_pixel_count[group_id] += image.channel[i].w * image.channel[i].h;
997
7.18k
    channel_pixel_count[i] += image.channel[i].w * image.channel[i].h;
998
7.18k
    total_pixels += image.channel[i].w * image.channel[i].h;
999
7.18k
  }
1000
4.47k
  if (channel_ids.empty()) return;
1001
4.24k
  pixel_samples.reserve(pixel_samples.size() + fraction * total_pixels);
1002
4.24k
  diff_samples.reserve(diff_samples.size() + fraction * total_pixels);
1003
4.24k
  size_t i = 0;
1004
4.24k
  size_t y = 0;
1005
4.24k
  size_t x = 0;
1006
6.87M
  auto advance = [&](size_t amount) {
1007
6.87M
    x += amount;
1008
    // Detect row overflow (rare).
1009
7.62M
    while (x >= image.channel[channel_ids[i]].w) {
1010
754k
      x -= image.channel[channel_ids[i]].w;
1011
754k
      y++;
1012
      // Detect end-of-channel (even rarer).
1013
754k
      if (y == image.channel[channel_ids[i]].h) {
1014
7.18k
        i++;
1015
7.18k
        y = 0;
1016
7.18k
        if (i >= channel_ids.size()) {
1017
4.24k
          return;
1018
4.24k
        }
1019
7.18k
      }
1020
754k
    }
1021
6.87M
  };
1022
4.24k
  advance(rng.Geometric(dist));
1023
6.87M
  for (; i < channel_ids.size(); advance(rng.Geometric(dist) + 1)) {
1024
6.87M
    const pixel_type *row = image.channel[channel_ids[i]].Row(y);
1025
6.87M
    pixel_samples.push_back(row[x]);
1026
6.87M
    size_t xp = x == 0 ? 1 : x - 1;
1027
6.87M
    diff_samples.push_back(static_cast<int64_t>(row[x]) - row[xp]);
1028
6.87M
  }
1029
4.24k
}
1030
1031
// TODO(veluca): very simple encoding scheme. This should be improved.
1032
Status TokenizeTree(const Tree &tree, std::vector<Token> *tokens,
1033
4.98k
                    Tree *decoder_tree) {
1034
4.98k
  JXL_ENSURE(tree.size() <= kMaxTreeSize);
1035
4.98k
  std::queue<int> q;
1036
4.98k
  q.push(0);
1037
4.98k
  size_t leaf_id = 0;
1038
4.98k
  decoder_tree->clear();
1039
577k
  while (!q.empty()) {
1040
572k
    int cur = q.front();
1041
572k
    q.pop();
1042
572k
    JXL_ENSURE(tree[cur].property >= -1);
1043
572k
    tokens->emplace_back(kPropertyContext, tree[cur].property + 1);
1044
572k
    if (tree[cur].property == -1) {
1045
288k
      tokens->emplace_back(kPredictorContext,
1046
288k
                           static_cast<int>(tree[cur].predictor));
1047
288k
      tokens->emplace_back(kOffsetContext,
1048
288k
                           PackSigned(tree[cur].predictor_offset));
1049
288k
      uint32_t mul_log = Num0BitsBelowLS1Bit_Nonzero(tree[cur].multiplier);
1050
288k
      uint32_t mul_bits = (tree[cur].multiplier >> mul_log) - 1;
1051
288k
      tokens->emplace_back(kMultiplierLogContext, mul_log);
1052
288k
      tokens->emplace_back(kMultiplierBitsContext, mul_bits);
1053
288k
      JXL_ENSURE(tree[cur].predictor < Predictor::Best);
1054
288k
      decoder_tree->emplace_back(
1055
288k
          -1, 0, static_cast<int>(leaf_id), 0, tree[cur].predictor,
1056
288k
          tree[cur].predictor_offset, tree[cur].multiplier);
1057
288k
      leaf_id++;
1058
288k
      continue;
1059
288k
    }
1060
283k
    decoder_tree->emplace_back(
1061
283k
        tree[cur].property, tree[cur].splitval,
1062
283k
        static_cast<int>(decoder_tree->size() + q.size() + 1),
1063
283k
        static_cast<int>(decoder_tree->size() + q.size() + 2), Predictor::Zero,
1064
283k
        0, 1);
1065
283k
    q.push(tree[cur].lchild);
1066
283k
    q.push(tree[cur].rchild);
1067
283k
    tokens->emplace_back(kSplitValContext, PackSigned(tree[cur].splitval));
1068
283k
  }
1069
4.98k
  return true;
1070
4.98k
}
1071
1072
}  // namespace jxl
1073
#endif  // HWY_ONCE