Coverage Report

Created: 2025-10-10 06:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/harfbuzz/src/hb-ot-var-common.hh
Line
Count
Source
1
/*
2
 * Copyright © 2021  Google, Inc.
3
 *
4
 *  This is part of HarfBuzz, a text shaping library.
5
 *
6
 * Permission is hereby granted, without written agreement and without
7
 * license or royalty fees, to use, copy, modify, and distribute this
8
 * software and its documentation for any purpose, provided that the
9
 * above copyright notice and the following two paragraphs appear in
10
 * all copies of this software.
11
 *
12
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
13
 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
14
 * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
15
 * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
16
 * DAMAGE.
17
 *
18
 * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
19
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20
 * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
21
 * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
22
 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
23
 *
24
 */
25
26
#ifndef HB_OT_VAR_COMMON_HH
27
#define HB_OT_VAR_COMMON_HH
28
29
#include "hb-ot-layout-common.hh"
30
#include "hb-alloc-pool.hh"
31
#include "hb-priority-queue.hh"
32
#include "hb-subset-instancer-iup.hh"
33
34
35
namespace OT {
36
37
using rebase_tent_result_scratch_t = hb_pair_t<rebase_tent_result_t, rebase_tent_result_t>;
38
39
/* https://docs.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats#tuplevariationheader */
40
struct TupleVariationHeader
41
{
42
  friend struct tuple_delta_t;
43
  unsigned get_size (unsigned axis_count) const
44
159k
  { return min_size + get_all_tuples (axis_count).get_size (); }
45
46
163k
  unsigned get_data_size () const { return varDataSize; }
47
48
  const TupleVariationHeader &get_next (unsigned axis_count) const
49
0
  { return StructAtOffset<TupleVariationHeader> (this, get_size (axis_count)); }
50
51
  bool unpack_axis_tuples (unsigned axis_count,
52
                           const hb_array_t<const F2DOT14> shared_tuples,
53
                           const hb_map_t *axes_old_index_tag_map,
54
                           hb_hashmap_t<hb_tag_t, Triple>& axis_tuples /* OUT */) const
55
0
  {
56
0
    const F2DOT14 *peak_tuple = nullptr;
57
0
    if (has_peak ())
58
0
      peak_tuple = get_peak_tuple (axis_count);
59
0
    else
60
0
    {
61
0
      unsigned int index = get_index ();
62
0
      if (unlikely ((index + 1) * axis_count > shared_tuples.length))
63
0
        return false;
64
0
      peak_tuple = shared_tuples.sub_array (axis_count * index, axis_count).arrayZ;
65
0
    }
66
0
67
0
    const F2DOT14 *start_tuple = nullptr;
68
0
    const F2DOT14 *end_tuple = nullptr;
69
0
    bool has_interm = has_intermediate ();
70
0
71
0
    if (has_interm)
72
0
    {
73
0
      start_tuple = get_start_tuple (axis_count);
74
0
      end_tuple = get_end_tuple (axis_count);
75
0
    }
76
0
77
0
    for (unsigned i = 0; i < axis_count; i++)
78
0
    {
79
0
      float peak = peak_tuple[i].to_float ();
80
0
      if (peak == 0.f) continue;
81
0
82
0
      hb_tag_t *axis_tag;
83
0
      if (!axes_old_index_tag_map->has (i, &axis_tag))
84
0
        return false;
85
0
86
0
      float start, end;
87
0
      if (has_interm)
88
0
      {
89
0
        start = start_tuple[i].to_float ();
90
0
        end = end_tuple[i].to_float ();
91
0
      }
92
0
      else
93
0
      {
94
0
        start = hb_min (peak, 0.f);
95
0
        end = hb_max (peak, 0.f);
96
0
      }
97
0
      axis_tuples.set (*axis_tag, Triple ((double) start, (double) peak, (double) end));
98
0
    }
99
0
100
0
    return true;
101
0
  }
102
103
  HB_ALWAYS_INLINE
104
  double calculate_scalar (hb_array_t<const int> coords, unsigned int coord_count,
105
         const hb_array_t<const F2DOT14> shared_tuples,
106
         hb_scalar_cache_t *shared_tuple_scalar_cache = nullptr) const
107
156k
  {
108
156k
    unsigned tuple_index = tupleIndex;
109
110
156k
    const F2DOT14 *peak_tuple;
111
112
156k
    bool has_interm = tuple_index & TuppleIndex::IntermediateRegion; // Inlined for performance
113
156k
    if (unlikely (has_interm))
114
29.8k
      shared_tuple_scalar_cache = nullptr;
115
116
156k
    if (unlikely (tuple_index & TuppleIndex::EmbeddedPeakTuple)) // Inlined for performance
117
25.1k
    {
118
25.1k
      peak_tuple = get_peak_tuple (coord_count);
119
25.1k
      shared_tuple_scalar_cache = nullptr;
120
25.1k
    }
121
131k
    else
122
131k
    {
123
131k
      unsigned int index = tuple_index & TuppleIndex::TupleIndexMask; // Inlined for performance
124
125
131k
      float scalar;
126
131k
      if (shared_tuple_scalar_cache &&
127
60.4k
    shared_tuple_scalar_cache->get (index, &scalar))
128
59.9k
  return (double) scalar;
129
130
71.8k
      if (unlikely ((index + 1) * coord_count > shared_tuples.length))
131
38.5k
        return 0.0;
132
33.2k
      peak_tuple = shared_tuples.arrayZ + (coord_count * index);
133
134
33.2k
    }
135
136
58.3k
    const F2DOT14 *start_tuple = nullptr;
137
58.3k
    const F2DOT14 *end_tuple = nullptr;
138
139
58.3k
    if (has_interm)
140
18.4k
    {
141
18.4k
      start_tuple = get_start_tuple (coord_count);
142
18.4k
      end_tuple = get_end_tuple (coord_count);
143
18.4k
    }
144
145
58.3k
    double scalar = 1.0;
146
87.7k
    for (unsigned int i = 0; i < coord_count; i++)
147
65.2k
    {
148
65.2k
      int peak = peak_tuple[i].to_int ();
149
65.2k
      if (!peak) continue;
150
151
53.5k
      int v = coords[i];
152
53.5k
      if (!v) { scalar = 0.0; break; }
153
44.3k
      if (v == peak) continue;
154
155
43.9k
      if (has_interm)
156
15.3k
      {
157
15.3k
        int start = start_tuple[i].to_int ();
158
15.3k
        int end = end_tuple[i].to_int ();
159
15.3k
        if (unlikely (start > peak || peak > end ||
160
15.3k
                      (start < 0 && end > 0 && peak))) continue;
161
6.06k
        if (v < start || v > end) { scalar = 0.0; break; }
162
1.75k
        if (v < peak)
163
500
        { if (peak != start) scalar *= (double) (v - start) / (peak - start); }
164
1.25k
        else
165
1.25k
        { if (peak != end) scalar *= (double) (end - v) / (end - peak); }
166
1.75k
      }
167
28.5k
      else if (v < hb_min (0, peak) || v > hb_max (0, peak)) { scalar = 0.0; break; }
168
6.16k
      else
169
6.16k
        scalar *= (double) v / peak;
170
43.9k
    }
171
58.3k
    if (shared_tuple_scalar_cache)
172
158
      shared_tuple_scalar_cache->set (get_index (), scalar);
173
58.3k
    return scalar;
174
156k
  }
175
176
196k
  bool           has_peak () const { return tupleIndex & TuppleIndex::EmbeddedPeakTuple; }
177
159k
  bool   has_intermediate () const { return tupleIndex & TuppleIndex::IntermediateRegion; }
178
14.3k
  bool has_private_points () const { return tupleIndex & TuppleIndex::PrivatePointNumbers; }
179
158
  unsigned      get_index () const { return tupleIndex & TuppleIndex::TupleIndexMask; }
180
181
  protected:
182
  struct TuppleIndex : HBUINT16
183
  {
184
    enum Flags {
185
      EmbeddedPeakTuple   = 0x8000u,
186
      IntermediateRegion  = 0x4000u,
187
      PrivatePointNumbers = 0x2000u,
188
      TupleIndexMask      = 0x0FFFu
189
    };
190
191
0
    TuppleIndex& operator = (uint16_t i) { HBUINT16::operator= (i); return *this; }
192
    DEFINE_SIZE_STATIC (2);
193
  };
194
195
  hb_array_t<const F2DOT14> get_all_tuples (unsigned axis_count) const
196
159k
  { return StructAfter<UnsizedArrayOf<F2DOT14>> (tupleIndex).as_array ((has_peak () + has_intermediate () * 2) * axis_count); }
197
  const F2DOT14* get_all_tuples_base (unsigned axis_count) const
198
61.9k
  { return StructAfter<UnsizedArrayOf<F2DOT14>> (tupleIndex).arrayZ; }
199
  const F2DOT14* get_peak_tuple (unsigned axis_count) const
200
25.1k
  { return get_all_tuples_base (axis_count); }
201
  const F2DOT14* get_start_tuple (unsigned axis_count) const
202
18.4k
  { return get_all_tuples_base (axis_count) + has_peak () * axis_count; }
203
  const F2DOT14* get_end_tuple (unsigned axis_count) const
204
18.4k
  { return get_all_tuples_base (axis_count) + has_peak () * axis_count + axis_count; }
205
206
  HBUINT16      varDataSize;    /* The size in bytes of the serialized
207
                                 * data for this tuple variation table. */
208
  TuppleIndex   tupleIndex;     /* A packed field. The high 4 bits are flags (see below).
209
                                   The low 12 bits are an index into a shared tuple
210
                                   records array. */
211
  /* UnsizedArrayOf<F2DOT14> peakTuple - optional */
212
                                /* Peak tuple record for this tuple variation table — optional,
213
                                 * determined by flags in the tupleIndex value.
214
                                 *
215
                                 * Note that this must always be included in the 'cvar' table. */
216
  /* UnsizedArrayOf<F2DOT14> intermediateStartTuple - optional */
217
                                /* Intermediate start tuple record for this tuple variation table — optional,
218
                                   determined by flags in the tupleIndex value. */
219
  /* UnsizedArrayOf<F2DOT14> intermediateEndTuple - optional */
220
                                /* Intermediate end tuple record for this tuple variation table — optional,
221
                                 * determined by flags in the tupleIndex value. */
222
  public:
223
  DEFINE_SIZE_MIN (4);
224
};
225
226
struct optimize_scratch_t
227
{
228
  iup_scratch_t iup;
229
  hb_vector_t<bool> opt_indices;
230
  hb_vector_t<int> rounded_x_deltas;
231
  hb_vector_t<int> rounded_y_deltas;
232
  hb_vector_t<float> opt_deltas_x;
233
  hb_vector_t<float> opt_deltas_y;
234
  hb_vector_t<unsigned char> opt_point_data;
235
  hb_vector_t<unsigned char> opt_deltas_data;
236
  hb_vector_t<unsigned char> point_data;
237
  hb_vector_t<unsigned char> deltas_data;
238
  hb_vector_t<int> rounded_deltas;
239
};
240
241
struct tuple_delta_t
242
{
243
  static constexpr bool realloc_move = true;  // Watch out when adding new members!
244
245
  public:
246
  hb_hashmap_t<hb_tag_t, Triple> axis_tuples;
247
248
  /* indices_length = point_count, indice[i] = 1 means point i is referenced */
249
  hb_vector_t<bool> indices;
250
251
  hb_vector_t<float> deltas_x;
252
  /* empty for cvar tuples */
253
  hb_vector_t<float> deltas_y;
254
255
  /* compiled data: header and deltas
256
   * compiled point data is saved in a hashmap within tuple_variations_t cause
257
   * some point sets might be reused by different tuple variations */
258
  hb_vector_t<unsigned char> compiled_tuple_header;
259
  hb_vector_t<unsigned char> compiled_deltas;
260
261
  hb_vector_t<F2DOT14> compiled_peak_coords;
262
  hb_vector_t<F2DOT14> compiled_interm_coords;
263
264
0
  tuple_delta_t (hb_alloc_pool_t *pool = nullptr) {}
265
  tuple_delta_t (const tuple_delta_t& o) = default;
266
  tuple_delta_t& operator = (const tuple_delta_t& o) = default;
267
268
  friend void swap (tuple_delta_t& a, tuple_delta_t& b) noexcept
269
0
  {
270
0
    hb_swap (a.axis_tuples, b.axis_tuples);
271
0
    hb_swap (a.indices, b.indices);
272
0
    hb_swap (a.deltas_x, b.deltas_x);
273
0
    hb_swap (a.deltas_y, b.deltas_y);
274
0
    hb_swap (a.compiled_tuple_header, b.compiled_tuple_header);
275
0
    hb_swap (a.compiled_deltas, b.compiled_deltas);
276
0
    hb_swap (a.compiled_peak_coords, b.compiled_peak_coords);
277
0
  }
278
279
  tuple_delta_t (tuple_delta_t&& o)  noexcept : tuple_delta_t ()
280
0
  { hb_swap (*this, o); }
281
282
  tuple_delta_t& operator = (tuple_delta_t&& o) noexcept
283
0
  {
284
0
    hb_swap (*this, o);
285
0
    return *this;
286
0
  }
287
288
  void copy_from (const tuple_delta_t& o, hb_alloc_pool_t *pool = nullptr)
289
0
  {
290
0
    axis_tuples = o.axis_tuples;
291
0
    indices.allocate_from_pool (pool, o.indices);
292
0
    deltas_x.allocate_from_pool (pool, o.deltas_x);
293
0
    deltas_y.allocate_from_pool (pool, o.deltas_y);
294
0
    compiled_tuple_header.allocate_from_pool (pool, o.compiled_tuple_header);
295
0
    compiled_deltas.allocate_from_pool (pool, o.compiled_deltas);
296
0
    compiled_peak_coords.allocate_from_pool (pool, o.compiled_peak_coords);
297
0
    compiled_interm_coords.allocate_from_pool (pool, o.compiled_interm_coords);
298
0
  }
299
300
  void remove_axis (hb_tag_t axis_tag)
301
0
  { axis_tuples.del (axis_tag); }
302
303
  bool set_tent (hb_tag_t axis_tag, Triple tent)
304
0
  { return axis_tuples.set (axis_tag, tent); }
305
306
  tuple_delta_t& operator += (const tuple_delta_t& o)
307
0
  {
308
0
    unsigned num = indices.length;
309
0
    for (unsigned i = 0; i < num; i++)
310
0
    {
311
0
      if (indices.arrayZ[i])
312
0
      {
313
0
        if (o.indices.arrayZ[i])
314
0
        {
315
0
          deltas_x[i] += o.deltas_x[i];
316
0
          if (deltas_y && o.deltas_y)
317
0
            deltas_y[i] += o.deltas_y[i];
318
0
        }
319
0
      }
320
0
      else
321
0
      {
322
0
        if (!o.indices.arrayZ[i]) continue;
323
0
        indices.arrayZ[i] = true;
324
0
        deltas_x[i] = o.deltas_x[i];
325
0
        if (deltas_y && o.deltas_y)
326
0
          deltas_y[i] = o.deltas_y[i];
327
0
      }
328
0
    }
329
0
    return *this;
330
0
  }
331
332
  tuple_delta_t& operator *= (float scalar)
333
0
  {
334
0
    if (scalar == 1.0f)
335
0
      return *this;
336
0
337
0
    unsigned num = indices.length;
338
0
    if (deltas_y)
339
0
      for (unsigned i = 0; i < num; i++)
340
0
      {
341
0
  if (!indices.arrayZ[i]) continue;
342
0
  deltas_x[i] *= scalar;
343
0
  deltas_y[i] *= scalar;
344
0
      }
345
0
    else
346
0
      for (unsigned i = 0; i < num; i++)
347
0
      {
348
0
  if (!indices.arrayZ[i]) continue;
349
0
  deltas_x[i] *= scalar;
350
0
      }
351
0
    return *this;
352
0
  }
353
354
  void change_tuple_var_axis_limit (hb_tag_t axis_tag, Triple axis_limit,
355
            TripleDistances axis_triple_distances,
356
            hb_vector_t<tuple_delta_t>& out,
357
            rebase_tent_result_scratch_t &scratch,
358
            hb_alloc_pool_t *pool = nullptr)
359
0
  {
360
0
    // May move *this out.
361
0
362
0
    out.reset ();
363
0
    Triple *tent;
364
0
    if (!axis_tuples.has (axis_tag, &tent))
365
0
    {
366
0
      out.push (std::move (*this));
367
0
      return;
368
0
    }
369
0
370
0
    if ((tent->minimum < 0.0 && tent->maximum > 0.0) ||
371
0
        !(tent->minimum <= tent->middle && tent->middle <= tent->maximum))
372
0
      return;
373
0
374
0
    if (tent->middle == 0.0)
375
0
    {
376
0
      out.push (std::move (*this));
377
0
      return;
378
0
    }
379
0
380
0
    rebase_tent_result_t &solutions = scratch.first;
381
0
    rebase_tent (*tent, axis_limit, axis_triple_distances, solutions, scratch.second);
382
0
    for (unsigned i = 0; i < solutions.length; i++)
383
0
    {
384
0
      auto &t = solutions.arrayZ[i];
385
0
386
0
      tuple_delta_t new_var;
387
0
      if (i < solutions.length - 1)
388
0
  new_var.copy_from (*this, pool);
389
0
      else
390
0
  new_var = std::move (*this);
391
0
392
0
      if (t.second == Triple ())
393
0
        new_var.remove_axis (axis_tag);
394
0
      else
395
0
        new_var.set_tent (axis_tag, t.second);
396
0
397
0
      new_var *= t.first;
398
0
      out.push (std::move (new_var));
399
0
    }
400
0
  }
401
402
  bool compile_coords (const hb_map_t& axes_index_map,
403
           const hb_map_t& axes_old_index_tag_map,
404
           hb_alloc_pool_t *pool= nullptr)
405
0
  {
406
0
    unsigned cur_axis_count = axes_index_map.get_population ();
407
0
    if (pool)
408
0
    {
409
0
      if (unlikely (!compiled_peak_coords.allocate_from_pool (pool, cur_axis_count)))
410
0
  return false;
411
0
    }
412
0
    else if (unlikely (!compiled_peak_coords.resize (cur_axis_count)))
413
0
      return false;
414
0
415
0
    hb_array_t<F2DOT14> start_coords, end_coords;
416
0
417
0
    unsigned orig_axis_count = axes_old_index_tag_map.get_population ();
418
0
    unsigned j = 0;
419
0
    for (unsigned i = 0; i < orig_axis_count; i++)
420
0
    {
421
0
      if (!axes_index_map.has (i))
422
0
        continue;
423
0
424
0
      hb_tag_t axis_tag = axes_old_index_tag_map.get (i);
425
0
      Triple *coords = nullptr;
426
0
      if (axis_tuples.has (axis_tag, &coords))
427
0
      {
428
0
  float min_val = coords->minimum;
429
0
  float val = coords->middle;
430
0
  float max_val = coords->maximum;
431
0
432
0
  compiled_peak_coords.arrayZ[j].set_float (val);
433
0
434
0
  if (min_val != hb_min (val, 0.f) || max_val != hb_max (val, 0.f))
435
0
  {
436
0
    if (!compiled_interm_coords)
437
0
    {
438
0
      if (pool)
439
0
      {
440
0
        if (unlikely (!compiled_interm_coords.allocate_from_pool (pool, 2 * cur_axis_count)))
441
0
    return false;
442
0
      }
443
0
      else if (unlikely (!compiled_interm_coords.resize (2 * cur_axis_count)))
444
0
        return false;
445
0
      start_coords = compiled_interm_coords.as_array ().sub_array (0, cur_axis_count);
446
0
      end_coords = compiled_interm_coords.as_array ().sub_array (cur_axis_count);
447
0
448
0
      for (unsigned k = 0; k < j; k++)
449
0
      {
450
0
        signed peak = compiled_peak_coords.arrayZ[k].to_int ();
451
0
        if (!peak) continue;
452
0
        start_coords.arrayZ[k].set_int (hb_min (peak, 0));
453
0
        end_coords.arrayZ[k].set_int (hb_max (peak, 0));
454
0
      }
455
0
    }
456
0
457
0
  }
458
0
459
0
  if (compiled_interm_coords)
460
0
  {
461
0
    start_coords.arrayZ[j].set_float (min_val);
462
0
    end_coords.arrayZ[j].set_float (max_val);
463
0
  }
464
0
      }
465
0
466
0
      j++;
467
0
    }
468
0
469
0
    return !compiled_peak_coords.in_error () && !compiled_interm_coords.in_error ();
470
0
  }
471
472
  /* deltas should be compiled already before we compile tuple
473
   * variation header cause we need to fill in the size of the
474
   * serialized data for this tuple variation */
475
  bool compile_tuple_var_header (const hb_map_t& axes_index_map,
476
                                 unsigned points_data_length,
477
                                 const hb_map_t& axes_old_index_tag_map,
478
                                 const hb_hashmap_t<const hb_vector_t<F2DOT14>*, unsigned>* shared_tuples_idx_map,
479
         hb_alloc_pool_t *pool = nullptr)
480
0
  {
481
0
    /* compiled_deltas could be empty after iup delta optimization, we can skip
482
0
     * compiling this tuple and return true */
483
0
    if (!compiled_deltas) return true;
484
0
485
0
    unsigned cur_axis_count = axes_index_map.get_population ();
486
0
    /* allocate enough memory: 1 peak + 2 intermediate coords + fixed header size */
487
0
    unsigned alloc_len = 3 * cur_axis_count * (F2DOT14::static_size) + 4;
488
0
    if (unlikely (!compiled_tuple_header.allocate_from_pool (pool, alloc_len, false))) return false;
489
0
490
0
    unsigned flag = 0;
491
0
    /* skip the first 4 header bytes: variationDataSize+tupleIndex */
492
0
    F2DOT14* p = reinterpret_cast<F2DOT14 *> (compiled_tuple_header.begin () + 4);
493
0
    F2DOT14* end = reinterpret_cast<F2DOT14 *> (compiled_tuple_header.end ());
494
0
    hb_array_t<F2DOT14> coords (p, end - p);
495
0
496
0
    if (!shared_tuples_idx_map)
497
0
      compile_coords (axes_index_map, axes_old_index_tag_map); // non-gvar tuples do not have compiled coords yet
498
0
499
0
    /* encode peak coords */
500
0
    unsigned peak_count = 0;
501
0
    unsigned *shared_tuple_idx;
502
0
    if (shared_tuples_idx_map &&
503
0
        shared_tuples_idx_map->has (&compiled_peak_coords, &shared_tuple_idx))
504
0
    {
505
0
      flag = *shared_tuple_idx;
506
0
    }
507
0
    else
508
0
    {
509
0
      peak_count = encode_peak_coords(coords, flag);
510
0
      if (!peak_count) return false;
511
0
    }
512
0
513
0
    /* encode interim coords, it's optional so returned num could be 0 */
514
0
    unsigned interim_count = encode_interm_coords (coords.sub_array (peak_count), flag);
515
0
516
0
    /* pointdata length = 0 implies "use shared points" */
517
0
    if (points_data_length)
518
0
      flag |= TupleVariationHeader::TuppleIndex::PrivatePointNumbers;
519
0
520
0
    unsigned serialized_data_size = points_data_length + compiled_deltas.length;
521
0
    TupleVariationHeader *o = reinterpret_cast<TupleVariationHeader *> (compiled_tuple_header.begin ());
522
0
    o->varDataSize = serialized_data_size;
523
0
    o->tupleIndex = flag;
524
0
525
0
    unsigned total_header_len = 4 + (peak_count + interim_count) * (F2DOT14::static_size);
526
0
    compiled_tuple_header.shrink_back_to_pool (pool, total_header_len);
527
0
    return true;
528
0
  }
529
530
  unsigned encode_peak_coords (hb_array_t<F2DOT14> peak_coords,
531
                               unsigned& flag) const
532
0
  {
533
0
    hb_memcpy (&peak_coords[0], &compiled_peak_coords[0], compiled_peak_coords.length * sizeof (compiled_peak_coords[0]));
534
0
    flag |= TupleVariationHeader::TuppleIndex::EmbeddedPeakTuple;
535
0
    return compiled_peak_coords.length;
536
0
  }
537
538
  /* if no need to encode intermediate coords, then just return p */
539
  unsigned encode_interm_coords (hb_array_t<F2DOT14> coords,
540
                                 unsigned& flag) const
541
0
  {
542
0
    if (compiled_interm_coords)
543
0
    {
544
0
      hb_memcpy (&coords[0], &compiled_interm_coords[0], compiled_interm_coords.length * sizeof (compiled_interm_coords[0]));
545
0
      flag |= TupleVariationHeader::TuppleIndex::IntermediateRegion;
546
0
    }
547
0
    return compiled_interm_coords.length;
548
0
  }
549
550
  bool compile_deltas (hb_vector_t<int> &rounded_deltas_scratch,
551
           hb_alloc_pool_t *pool = nullptr)
552
0
  { return compile_deltas (indices, deltas_x, deltas_y, compiled_deltas, rounded_deltas_scratch, pool); }
553
554
  static bool compile_deltas (hb_array_t<const bool> point_indices,
555
            hb_array_t<const float> x_deltas,
556
            hb_array_t<const float> y_deltas,
557
            hb_vector_t<unsigned char> &compiled_deltas, /* OUT */
558
            hb_vector_t<int> &rounded_deltas, /* scratch */
559
            hb_alloc_pool_t *pool = nullptr)
560
0
  {
561
0
    if (unlikely (!rounded_deltas.resize_dirty  (point_indices.length)))
562
0
      return false;
563
0
564
0
    unsigned j = 0;
565
0
    for (unsigned i = 0; i < point_indices.length; i++)
566
0
    {
567
0
      if (!point_indices[i]) continue;
568
0
      rounded_deltas.arrayZ[j++] = (int) roundf (x_deltas.arrayZ[i]);
569
0
    }
570
0
    rounded_deltas.resize (j);
571
0
572
0
    if (!rounded_deltas) return true;
573
0
    /* Allocate enough memory: this is the correct bound:
574
0
     * Worst case scenario is that each delta has to be encoded in 4 bytes, and there
575
0
     * are runs of 64 items each. Any delta encoded in less than 4 bytes (2, 1, or 0)
576
0
     * is still smaller than the 4-byte encoding even with their control byte.
577
0
     * The initial 2 is to handle length==0, for both x and y deltas. */
578
0
    unsigned alloc_len = 2 + 4 * rounded_deltas.length + (rounded_deltas.length + 63) / 64;
579
0
    if (y_deltas)
580
0
      alloc_len *= 2;
581
0
582
0
    if (unlikely (!compiled_deltas.allocate_from_pool (pool, alloc_len, false))) return false;
583
0
584
0
    unsigned encoded_len = compile_deltas (compiled_deltas, rounded_deltas);
585
0
586
0
    if (y_deltas)
587
0
    {
588
0
      /* reuse the rounded_deltas vector, check that y_deltas have the same num of deltas as x_deltas */
589
0
      unsigned j = 0;
590
0
      for (unsigned idx = 0; idx < point_indices.length; idx++)
591
0
      {
592
0
        if (!point_indices[idx]) continue;
593
0
        int rounded_delta = (int) roundf (y_deltas.arrayZ[idx]);
594
0
595
0
        if (j >= rounded_deltas.length) return false;
596
0
597
0
        rounded_deltas[j++] = rounded_delta;
598
0
      }
599
0
600
0
      if (j != rounded_deltas.length) return false;
601
0
      encoded_len += compile_deltas (compiled_deltas.as_array ().sub_array (encoded_len), rounded_deltas);
602
0
    }
603
0
    compiled_deltas.shrink_back_to_pool (pool, encoded_len);
604
0
    return true;
605
0
  }
606
607
  static unsigned compile_deltas (hb_array_t<unsigned char> encoded_bytes,
608
          hb_array_t<const int> deltas)
609
0
  {
610
0
    return TupleValues::compile_unsafe (deltas, encoded_bytes);
611
0
  }
612
613
  bool calc_inferred_deltas (const contour_point_vector_t& orig_points,
614
           hb_vector_t<unsigned> &scratch)
615
0
  {
616
0
    unsigned point_count = orig_points.length;
617
0
    if (point_count != indices.length)
618
0
      return false;
619
0
620
0
    unsigned ref_count = 0;
621
0
622
0
    hb_vector_t<unsigned> &end_points = scratch.reset ();
623
0
624
0
    for (unsigned i = 0; i < point_count; i++)
625
0
    {
626
0
      ref_count += indices.arrayZ[i];
627
0
      if (orig_points.arrayZ[i].is_end_point)
628
0
        end_points.push (i);
629
0
    }
630
0
    /* all points are referenced, nothing to do */
631
0
    if (ref_count == point_count)
632
0
      return true;
633
0
    if (unlikely (end_points.in_error ())) return false;
634
0
635
0
    hb_bit_set_t inferred_idxes;
636
0
    unsigned start_point = 0;
637
0
    for (unsigned end_point : end_points)
638
0
    {
639
0
      /* Check the number of unreferenced points in a contour. If no unref points or no ref points, nothing to do. */
640
0
      unsigned unref_count = 0;
641
0
      for (unsigned i = start_point; i < end_point + 1; i++)
642
0
        unref_count += indices.arrayZ[i];
643
0
      unref_count = (end_point - start_point + 1) - unref_count;
644
0
645
0
      unsigned j = start_point;
646
0
      if (unref_count == 0 || unref_count > end_point - start_point)
647
0
        goto no_more_gaps;
648
0
      for (;;)
649
0
      {
650
0
        /* Locate the next gap of unreferenced points between two referenced points prev and next.
651
0
         * Note that a gap may wrap around at left (start_point) and/or at right (end_point).
652
0
         */
653
0
        unsigned int prev, next, i;
654
0
        for (;;)
655
0
        {
656
0
          i = j;
657
0
          j = next_index (i, start_point, end_point);
658
0
          if (indices.arrayZ[i] && !indices.arrayZ[j]) break;
659
0
        }
660
0
        prev = j = i;
661
0
        for (;;)
662
0
        {
663
0
          i = j;
664
0
          j = next_index (i, start_point, end_point);
665
0
          if (!indices.arrayZ[i] && indices.arrayZ[j]) break;
666
0
        }
667
0
        next = j;
668
0
       /* Infer deltas for all unref points in the gap between prev and next */
669
0
        i = prev;
670
0
        for (;;)
671
0
        {
672
0
          i = next_index (i, start_point, end_point);
673
0
          if (i == next) break;
674
0
          deltas_x.arrayZ[i] = infer_delta ((double) orig_points.arrayZ[i].x,
675
0
                                            (double) orig_points.arrayZ[prev].x,
676
0
                                            (double) orig_points.arrayZ[next].x,
677
0
                                            (double) deltas_x.arrayZ[prev], (double) deltas_x.arrayZ[next]);
678
0
          deltas_y.arrayZ[i] = infer_delta ((double) orig_points.arrayZ[i].y,
679
0
                                            (double) orig_points.arrayZ[prev].y,
680
0
                                            (double) orig_points.arrayZ[next].y,
681
0
                                            (double) deltas_y.arrayZ[prev], (double) deltas_y.arrayZ[next]);
682
0
          inferred_idxes.add (i);
683
0
          if (--unref_count == 0) goto no_more_gaps;
684
0
        }
685
0
      }
686
0
    no_more_gaps:
687
0
      start_point = end_point + 1;
688
0
    }
689
0
690
0
    for (unsigned i = 0; i < point_count; i++)
691
0
    {
692
0
      /* if points are not referenced and deltas are not inferred, set to 0.
693
0
       * reference all points for gvar */
694
0
      if ( !indices[i])
695
0
      {
696
0
        if (!inferred_idxes.has (i))
697
0
        {
698
0
          deltas_x.arrayZ[i] = 0.0;
699
0
          deltas_y.arrayZ[i] = 0.0;
700
0
        }
701
0
        indices[i] = true;
702
0
      }
703
0
    }
704
0
    return true;
705
0
  }
706
707
  bool optimize (const contour_point_vector_t& contour_points,
708
                 bool is_composite,
709
     optimize_scratch_t &scratch,
710
                 double tolerance = 0.5 + 1e-10)
711
0
  {
712
0
    unsigned count = contour_points.length;
713
0
    if (deltas_x.length != count ||
714
0
        deltas_y.length != count)
715
0
      return false;
716
0
717
0
    hb_vector_t<bool> &opt_indices = scratch.opt_indices.reset ();
718
0
    hb_vector_t<int> &rounded_x_deltas = scratch.rounded_x_deltas;
719
0
    hb_vector_t<int> &rounded_y_deltas = scratch.rounded_y_deltas;
720
0
721
0
    if (unlikely (!rounded_x_deltas.resize_dirty  (count) ||
722
0
                  !rounded_y_deltas.resize_dirty  (count)))
723
0
      return false;
724
0
725
0
    for (unsigned i = 0; i < count; i++)
726
0
    {
727
0
      rounded_x_deltas.arrayZ[i] = (int) roundf (deltas_x.arrayZ[i]);
728
0
      rounded_y_deltas.arrayZ[i] = (int) roundf (deltas_y.arrayZ[i]);
729
0
    }
730
0
731
0
    if (!iup_delta_optimize (contour_points, rounded_x_deltas, rounded_y_deltas, opt_indices, scratch.iup, tolerance))
732
0
      return false;
733
0
734
0
    unsigned ref_count = 0;
735
0
    for (bool ref_flag : opt_indices)
736
0
       ref_count += ref_flag;
737
0
738
0
    if (ref_count == count) return true;
739
0
740
0
    hb_vector_t<float> &opt_deltas_x = scratch.opt_deltas_x.reset ();
741
0
    hb_vector_t<float> &opt_deltas_y = scratch.opt_deltas_y.reset ();
742
0
    bool is_comp_glyph_wo_deltas = (is_composite && ref_count == 0);
743
0
    if (is_comp_glyph_wo_deltas)
744
0
    {
745
0
      if (unlikely (!opt_deltas_x.resize (count) ||
746
0
                    !opt_deltas_y.resize (count)))
747
0
        return false;
748
0
749
0
      opt_indices.arrayZ[0] = true;
750
0
      for (unsigned i = 1; i < count; i++)
751
0
        opt_indices.arrayZ[i] = false;
752
0
    }
753
0
754
0
    hb_vector_t<unsigned char> &opt_point_data = scratch.opt_point_data.reset ();
755
0
    if (!compile_point_set (opt_indices, opt_point_data))
756
0
      return false;
757
0
    hb_vector_t<unsigned char> &opt_deltas_data = scratch.opt_deltas_data.reset ();
758
0
    if (!compile_deltas (opt_indices,
759
0
                         is_comp_glyph_wo_deltas ? opt_deltas_x : deltas_x,
760
0
                         is_comp_glyph_wo_deltas ? opt_deltas_y : deltas_y,
761
0
                         opt_deltas_data,
762
0
       scratch.rounded_deltas))
763
0
      return false;
764
0
765
0
    hb_vector_t<unsigned char> &point_data = scratch.point_data.reset ();
766
0
    if (!compile_point_set (indices, point_data))
767
0
      return false;
768
0
    hb_vector_t<unsigned char> &deltas_data = scratch.deltas_data.reset ();
769
0
    if (!compile_deltas (indices, deltas_x, deltas_y, deltas_data, scratch.rounded_deltas))
770
0
      return false;
771
0
772
0
    if (opt_point_data.length + opt_deltas_data.length < point_data.length + deltas_data.length)
773
0
    {
774
0
      indices = std::move (opt_indices);
775
0
776
0
      if (is_comp_glyph_wo_deltas)
777
0
      {
778
0
        deltas_x = std::move (opt_deltas_x);
779
0
        deltas_y = std::move (opt_deltas_y);
780
0
      }
781
0
    }
782
0
    return !indices.in_error () && !deltas_x.in_error () && !deltas_y.in_error ();
783
0
  }
784
785
  static bool compile_point_set (const hb_vector_t<bool> &point_indices,
786
                                 hb_vector_t<unsigned char>& compiled_points /* OUT */)
787
0
  {
788
0
    unsigned num_points = 0;
789
0
    for (bool i : point_indices)
790
0
      if (i) num_points++;
791
0
792
0
    /* when iup optimization is enabled, num of referenced points could be 0 */
793
0
    if (!num_points) return true;
794
0
795
0
    unsigned indices_length = point_indices.length;
796
0
    /* If the points set consists of all points in the glyph, it's encoded with a
797
0
     * single zero byte */
798
0
    if (num_points == indices_length)
799
0
      return compiled_points.resize (1);
800
0
801
0
    /* allocate enough memories: 2 bytes for count + 3 bytes for each point */
802
0
    unsigned num_bytes = 2 + 3 *num_points;
803
0
    if (unlikely (!compiled_points.resize_dirty  (num_bytes)))
804
0
      return false;
805
0
806
0
    unsigned pos = 0;
807
0
    /* binary data starts with the total number of reference points */
808
0
    if (num_points < 0x80)
809
0
      compiled_points.arrayZ[pos++] = num_points;
810
0
    else
811
0
    {
812
0
      compiled_points.arrayZ[pos++] = ((num_points >> 8) | 0x80);
813
0
      compiled_points.arrayZ[pos++] = num_points & 0xFF;
814
0
    }
815
0
816
0
    const unsigned max_run_length = 0x7F;
817
0
    unsigned i = 0;
818
0
    unsigned last_value = 0;
819
0
    unsigned num_encoded = 0;
820
0
    while (i < indices_length && num_encoded < num_points)
821
0
    {
822
0
      unsigned run_length = 0;
823
0
      unsigned header_pos = pos;
824
0
      compiled_points.arrayZ[pos++] = 0;
825
0
826
0
      bool use_byte_encoding = false;
827
0
      bool new_run = true;
828
0
      while (i < indices_length && num_encoded < num_points &&
829
0
             run_length <= max_run_length)
830
0
      {
831
0
        // find out next referenced point index
832
0
        while (i < indices_length && !point_indices[i])
833
0
          i++;
834
0
835
0
        if (i >= indices_length) break;
836
0
837
0
        unsigned cur_value = i;
838
0
        unsigned delta = cur_value - last_value;
839
0
840
0
        if (new_run)
841
0
        {
842
0
          use_byte_encoding = (delta <= 0xFF);
843
0
          new_run = false;
844
0
        }
845
0
846
0
        if (use_byte_encoding && delta > 0xFF)
847
0
          break;
848
0
849
0
        if (use_byte_encoding)
850
0
          compiled_points.arrayZ[pos++] = delta;
851
0
        else
852
0
        {
853
0
          compiled_points.arrayZ[pos++] = delta >> 8;
854
0
          compiled_points.arrayZ[pos++] = delta & 0xFF;
855
0
        }
856
0
        i++;
857
0
        last_value = cur_value;
858
0
        run_length++;
859
0
        num_encoded++;
860
0
      }
861
0
862
0
      if (use_byte_encoding)
863
0
        compiled_points.arrayZ[header_pos] = run_length - 1;
864
0
      else
865
0
        compiled_points.arrayZ[header_pos] = (run_length - 1) | 0x80;
866
0
    }
867
0
    return compiled_points.resize_dirty  (pos);
868
0
  }
869
870
  static double infer_delta (double target_val, double prev_val, double next_val, double prev_delta, double next_delta)
871
0
  {
872
0
    if (prev_val == next_val)
873
0
      return (prev_delta == next_delta) ? prev_delta : 0.0;
874
0
    else if (target_val <= hb_min (prev_val, next_val))
875
0
      return (prev_val < next_val) ? prev_delta : next_delta;
876
0
    else if (target_val >= hb_max (prev_val, next_val))
877
0
      return (prev_val > next_val) ? prev_delta : next_delta;
878
0
879
0
    double r = (target_val - prev_val) / (next_val - prev_val);
880
0
    return prev_delta + r * (next_delta - prev_delta);
881
0
  }
882
883
  static unsigned int next_index (unsigned int i, unsigned int start, unsigned int end)
884
0
  { return (i >= end) ? start : (i + 1); }
885
};
886
887
template <typename OffType = HBUINT16>
888
struct TupleVariationData
889
{
890
  bool sanitize (hb_sanitize_context_t *c) const
891
  {
892
    TRACE_SANITIZE (this);
893
    // here check on min_size only, TupleVariationHeader and var data will be
894
    // checked while accessing through iterator.
895
    return_trace (c->check_struct (this));
896
  }
897
898
  unsigned get_size (unsigned axis_count) const
899
  {
900
    unsigned total_size = min_size;
901
    unsigned count = tupleVarCount.get_count ();
902
    const TupleVariationHeader *tuple_var_header = &(get_tuple_var_header());
903
    for (unsigned i = 0; i < count; i++)
904
    {
905
      total_size += tuple_var_header->get_size (axis_count) + tuple_var_header->get_data_size ();
906
      tuple_var_header = &tuple_var_header->get_next (axis_count);
907
    }
908
909
    return total_size;
910
  }
911
912
  const TupleVariationHeader &get_tuple_var_header (void) const
913
32.6k
  { return StructAfter<TupleVariationHeader> (data); }
OT::TupleVariationData<OT::NumType<true, unsigned int, 3u> >::get_tuple_var_header() const
Line
Count
Source
913
15.7k
  { return StructAfter<TupleVariationHeader> (data); }
OT::TupleVariationData<OT::NumType<true, unsigned short, 2u> >::get_tuple_var_header() const
Line
Count
Source
913
16.9k
  { return StructAfter<TupleVariationHeader> (data); }
914
915
  struct tuple_iterator_t;
916
  struct tuple_variations_t
917
  {
918
    hb_vector_t<tuple_delta_t> tuple_vars;
919
920
    private:
921
    /* referenced point set->compiled point data map */
922
    hb_hashmap_t<const hb_vector_t<bool>*, hb_vector_t<unsigned char>> point_data_map;
923
    /* referenced point set-> count map, used in finding shared points */
924
    hb_hashmap_t<const hb_vector_t<bool>*, unsigned> point_set_count_map;
925
926
    /* empty for non-gvar tuples.
927
     * shared_points_bytes is a pointer to some value in the point_data_map,
928
     * which will be freed during map destruction. Save it for serialization, so
929
     * no need to do find_shared_points () again */
930
    hb_vector_t<unsigned char> *shared_points_bytes = nullptr;
931
932
    /* total compiled byte size as TupleVariationData format, initialized to 0 */
933
    unsigned compiled_byte_size = 0;
934
    bool needs_padding = false;
935
936
    /* for gvar iup delta optimization: whether this is a composite glyph */
937
    bool is_composite = false;
938
939
    public:
940
    tuple_variations_t () = default;
941
    tuple_variations_t (const tuple_variations_t&) = delete;
942
    tuple_variations_t& operator=(const tuple_variations_t&) = delete;
943
    tuple_variations_t (tuple_variations_t&&) = default;
944
    tuple_variations_t& operator=(tuple_variations_t&&) = default;
945
    ~tuple_variations_t () = default;
946
947
    explicit operator bool () const { return bool (tuple_vars); }
948
    unsigned get_var_count () const
949
    {
950
      unsigned count = 0;
951
      /* when iup delta opt is enabled, compiled_deltas could be empty and we
952
       * should skip this tuple */
953
      for (auto& tuple: tuple_vars)
954
        if (tuple.compiled_deltas) count++;
955
956
      if (shared_points_bytes && shared_points_bytes->length)
957
        count |= TupleVarCount::SharedPointNumbers;
958
      return count;
959
    }
960
961
    unsigned get_compiled_byte_size () const
962
    { return compiled_byte_size; }
963
964
    bool create_from_tuple_var_data (tuple_iterator_t iterator,
965
                                     unsigned tuple_var_count,
966
                                     unsigned point_count,
967
                                     bool is_gvar,
968
                                     const hb_map_t *axes_old_index_tag_map,
969
                                     const hb_vector_t<unsigned> &shared_indices,
970
                                     const hb_array_t<const F2DOT14> shared_tuples,
971
             hb_alloc_pool_t *pool = nullptr,
972
                                     bool is_composite_glyph = false)
973
    {
974
      hb_vector_t<unsigned> private_indices;
975
      hb_vector_t<int> deltas_x;
976
      hb_vector_t<int> deltas_y;
977
      do
978
      {
979
        const HBUINT8 *p = iterator.get_serialized_data ();
980
        unsigned int length = iterator.current_tuple->get_data_size ();
981
        if (unlikely (!iterator.var_data_bytes.check_range (p, length)))
982
          return false;
983
984
  hb_hashmap_t<hb_tag_t, Triple> axis_tuples;
985
        if (!iterator.current_tuple->unpack_axis_tuples (iterator.get_axis_count (), shared_tuples, axes_old_index_tag_map, axis_tuples)
986
            || axis_tuples.is_empty ())
987
          return false;
988
989
  private_indices.reset ();
990
        bool has_private_points = iterator.current_tuple->has_private_points ();
991
        const HBUINT8 *end = p + length;
992
        if (has_private_points &&
993
            !TupleVariationData::decompile_points (p, private_indices, end))
994
          return false;
995
996
        const hb_vector_t<unsigned> &indices = has_private_points ? private_indices : shared_indices;
997
        bool apply_to_all = (indices.length == 0);
998
        unsigned num_deltas = apply_to_all ? point_count : indices.length;
999
1000
        if (unlikely (!deltas_x.resize_dirty  (num_deltas) ||
1001
                      !TupleVariationData::decompile_deltas (p, deltas_x, end)))
1002
          return false;
1003
1004
        if (is_gvar)
1005
        {
1006
          if (unlikely (!deltas_y.resize_dirty  (num_deltas) ||
1007
                        !TupleVariationData::decompile_deltas (p, deltas_y, end)))
1008
            return false;
1009
        }
1010
1011
        tuple_delta_t var;
1012
        var.axis_tuples = std::move (axis_tuples);
1013
        if (unlikely (!var.indices.allocate_from_pool (pool, point_count) ||
1014
                      !var.deltas_x.allocate_from_pool (pool, point_count, false)))
1015
          return false;
1016
1017
        if (is_gvar && unlikely (!var.deltas_y.allocate_from_pool (pool, point_count, false)))
1018
          return false;
1019
1020
        for (unsigned i = 0; i < num_deltas; i++)
1021
        {
1022
          unsigned idx = apply_to_all ? i : indices[i];
1023
          if (idx >= point_count) continue;
1024
          var.indices[idx] = true;
1025
          var.deltas_x[idx] = deltas_x[i];
1026
          if (is_gvar)
1027
            var.deltas_y[idx] = deltas_y[i];
1028
        }
1029
        tuple_vars.push (std::move (var));
1030
      } while (iterator.move_to_next ());
1031
1032
      is_composite = is_composite_glyph;
1033
      return true;
1034
    }
1035
1036
    bool create_from_item_var_data (const VarData &var_data,
1037
                                    const hb_vector_t<hb_hashmap_t<hb_tag_t, Triple>>& regions,
1038
                                    const hb_map_t& axes_old_index_tag_map,
1039
                                    unsigned& item_count,
1040
                                    const hb_inc_bimap_t* inner_map = nullptr)
1041
0
    {
1042
0
      /* NULL offset, to keep original varidx valid, just return */
1043
0
      if (&var_data == &Null (VarData))
1044
0
        return true;
1045
0
1046
0
      unsigned num_regions = var_data.get_region_index_count ();
1047
0
      if (!tuple_vars.alloc (num_regions)) return false;
1048
0
1049
0
      item_count = inner_map ? inner_map->get_population () : var_data.get_item_count ();
1050
0
      if (!item_count) return true;
1051
0
      unsigned row_size = var_data.get_row_size ();
1052
0
      const HBUINT8 *delta_bytes = var_data.get_delta_bytes ();
1053
0
1054
0
      for (unsigned r = 0; r < num_regions; r++)
1055
0
      {
1056
0
        /* In VarData, deltas are organized in rows, convert them into
1057
0
         * column(region) based tuples, resize deltas_x first */
1058
0
        tuple_delta_t tuple;
1059
0
        if (!tuple.deltas_x.resize_dirty  (item_count) ||
1060
0
            !tuple.indices.resize_dirty  (item_count))
1061
0
          return false;
1062
0
1063
0
        for (unsigned i = 0; i < item_count; i++)
1064
0
        {
1065
0
          tuple.indices.arrayZ[i] = true;
1066
0
          tuple.deltas_x.arrayZ[i] = var_data.get_item_delta_fast (inner_map ? inner_map->backward (i) : i,
1067
0
                                                                   r, delta_bytes, row_size);
1068
0
        }
1069
0
1070
0
        unsigned region_index = var_data.get_region_index (r);
1071
0
        if (region_index >= regions.length) return false;
1072
0
        tuple.axis_tuples = regions.arrayZ[region_index];
1073
0
1074
0
        tuple_vars.push (std::move (tuple));
1075
0
      }
1076
0
      return !tuple_vars.in_error ();
1077
0
    }
1078
1079
    private:
1080
    static int _cmp_axis_tag (const void *pa, const void *pb)
1081
0
    {
1082
0
      const hb_tag_t *a = (const hb_tag_t*) pa;
1083
0
      const hb_tag_t *b = (const hb_tag_t*) pb;
1084
0
      return (int)(*a) - (int)(*b);
1085
0
    }
1086
1087
    bool change_tuple_variations_axis_limits (const hb_hashmap_t<hb_tag_t, Triple>& normalized_axes_location,
1088
                                              const hb_hashmap_t<hb_tag_t, TripleDistances>& axes_triple_distances,
1089
                hb_alloc_pool_t *pool = nullptr)
1090
0
    {
1091
0
      /* sort axis_tag/axis_limits, make result deterministic */
1092
0
      hb_vector_t<hb_tag_t> axis_tags;
1093
0
      if (!axis_tags.alloc (normalized_axes_location.get_population ()))
1094
0
        return false;
1095
0
      for (auto t : normalized_axes_location.keys ())
1096
0
        axis_tags.push (t);
1097
0
1098
0
      // Reused vectors for reduced malloc pressure.
1099
0
      rebase_tent_result_scratch_t scratch;
1100
0
      hb_vector_t<tuple_delta_t> out;
1101
0
1102
0
      axis_tags.qsort (_cmp_axis_tag);
1103
0
      for (auto axis_tag : axis_tags)
1104
0
      {
1105
0
        Triple *axis_limit;
1106
0
        if (!normalized_axes_location.has (axis_tag, &axis_limit))
1107
0
          return false;
1108
0
        TripleDistances axis_triple_distances{1.0, 1.0};
1109
0
        if (axes_triple_distances.has (axis_tag))
1110
0
          axis_triple_distances = axes_triple_distances.get (axis_tag);
1111
0
1112
0
        hb_vector_t<tuple_delta_t> new_vars;
1113
0
        for (tuple_delta_t& var : tuple_vars)
1114
0
        {
1115
0
    // This may move var out.
1116
0
    var.change_tuple_var_axis_limit (axis_tag, *axis_limit, axis_triple_distances, out, scratch, pool);
1117
0
          if (!out) continue;
1118
0
1119
0
          unsigned new_len = new_vars.length + out.length;
1120
0
1121
0
          if (unlikely (!new_vars.alloc (new_len, false)))
1122
0
            return false;
1123
0
1124
0
          for (unsigned i = 0; i < out.length; i++)
1125
0
            new_vars.push (std::move (out[i]));
1126
0
        }
1127
0
        tuple_vars = std::move (new_vars);
1128
0
      }
1129
0
      return true;
1130
0
    }
1131
1132
    /* merge tuple variations with overlapping tents, if iup delta optimization
1133
     * is enabled, add default deltas to contour_points */
1134
    bool merge_tuple_variations (contour_point_vector_t* contour_points = nullptr)
1135
0
    {
1136
0
      hb_vector_t<tuple_delta_t> new_vars;
1137
0
      // The pre-allocation is essential for address stability of pointers
1138
0
      // we store in the hashmap.
1139
0
      if (unlikely (!new_vars.alloc (tuple_vars.length)))
1140
0
  return false;
1141
0
      hb_hashmap_t<const hb_hashmap_t<hb_tag_t, Triple>*, unsigned> m;
1142
0
      for (tuple_delta_t& var : tuple_vars)
1143
0
      {
1144
0
        /* if all axes are pinned, drop the tuple variation */
1145
0
        if (var.axis_tuples.is_empty ())
1146
0
        {
1147
0
          /* if iup_delta_optimize is enabled, add deltas to contour coords */
1148
0
          if (contour_points && !contour_points->add_deltas (var.deltas_x,
1149
0
                                                             var.deltas_y,
1150
0
                                                             var.indices))
1151
0
            return false;
1152
0
          continue;
1153
0
        }
1154
0
1155
0
        unsigned *idx;
1156
0
        if (m.has (&(var.axis_tuples), &idx))
1157
0
        {
1158
0
          new_vars[*idx] += var;
1159
0
        }
1160
0
        else
1161
0
        {
1162
0
    auto *new_var = new_vars.push ();
1163
0
    if (unlikely (new_vars.in_error ()))
1164
0
      return false;
1165
0
          hb_swap (*new_var, var);
1166
0
          if (unlikely (!m.set (&(new_var->axis_tuples), new_vars.length - 1)))
1167
0
            return false;
1168
0
        }
1169
0
      }
1170
0
      m.fini (); // Just in case, since it points into new_vars data.
1171
0
     // Shouldn't be necessary though, since we only move new_vars, not its
1172
0
     // contents.
1173
0
      tuple_vars = std::move (new_vars);
1174
0
      return true;
1175
0
    }
1176
1177
    /* compile all point set and store byte data in a point_set->hb_bytes_t hashmap,
1178
     * also update point_set->count map, which will be used in finding shared
1179
     * point set*/
1180
    bool compile_all_point_sets ()
1181
    {
1182
      for (const auto& tuple: tuple_vars)
1183
      {
1184
        const hb_vector_t<bool>* points_set = &(tuple.indices);
1185
        if (point_data_map.has (points_set))
1186
        {
1187
          unsigned *count;
1188
          if (unlikely (!point_set_count_map.has (points_set, &count) ||
1189
                        !point_set_count_map.set (points_set, (*count) + 1)))
1190
            return false;
1191
          continue;
1192
        }
1193
1194
        hb_vector_t<unsigned char> compiled_point_data;
1195
        if (!tuple_delta_t::compile_point_set (*points_set, compiled_point_data))
1196
          return false;
1197
1198
        if (!point_data_map.set (points_set, std::move (compiled_point_data)) ||
1199
            !point_set_count_map.set (points_set, 1))
1200
          return false;
1201
      }
1202
      return true;
1203
    }
1204
1205
    /* find shared points set which saves most bytes */
1206
    void find_shared_points ()
1207
    {
1208
      unsigned max_saved_bytes = 0;
1209
1210
      for (const auto& _ : point_data_map.iter_ref ())
1211
      {
1212
        const hb_vector_t<bool>* points_set = _.first;
1213
        unsigned data_length = _.second.length;
1214
        if (!data_length) continue;
1215
        unsigned *count;
1216
        if (unlikely (!point_set_count_map.has (points_set, &count) ||
1217
                      *count <= 1))
1218
        {
1219
          shared_points_bytes = nullptr;
1220
          return;
1221
        }
1222
1223
        unsigned saved_bytes = data_length * ((*count) -1);
1224
        if (saved_bytes > max_saved_bytes)
1225
        {
1226
          max_saved_bytes = saved_bytes;
1227
          shared_points_bytes = &(_.second);
1228
        }
1229
      }
1230
    }
1231
1232
    bool calc_inferred_deltas (const contour_point_vector_t& contour_points,
1233
             hb_vector_t<unsigned> &scratch)
1234
0
    {
1235
0
      for (tuple_delta_t& var : tuple_vars)
1236
0
        if (!var.calc_inferred_deltas (contour_points, scratch))
1237
0
          return false;
1238
0
1239
0
      return true;
1240
0
    }
1241
1242
    bool iup_optimize (const contour_point_vector_t& contour_points,
1243
           optimize_scratch_t &scratch)
1244
0
    {
1245
0
      for (tuple_delta_t& var : tuple_vars)
1246
0
      {
1247
0
        if (!var.optimize (contour_points, is_composite, scratch))
1248
0
          return false;
1249
0
      }
1250
0
      return true;
1251
0
    }
1252
1253
    public:
1254
    bool instantiate (const hb_hashmap_t<hb_tag_t, Triple>& normalized_axes_location,
1255
                      const hb_hashmap_t<hb_tag_t, TripleDistances>& axes_triple_distances,
1256
          optimize_scratch_t &scratch,
1257
          hb_alloc_pool_t *pool = nullptr,
1258
                      contour_point_vector_t* contour_points = nullptr,
1259
                      bool optimize = false)
1260
0
    {
1261
0
      if (!tuple_vars) return true;
1262
0
      if (!change_tuple_variations_axis_limits (normalized_axes_location, axes_triple_distances, pool))
1263
0
        return false;
1264
0
      /* compute inferred deltas only for gvar */
1265
0
      if (contour_points)
1266
0
      {
1267
0
  hb_vector_t<unsigned> scratch;
1268
0
  if (!calc_inferred_deltas (*contour_points, scratch))
1269
0
    return false;
1270
0
      }
1271
0
1272
0
      /* if iup delta opt is on, contour_points can't be null */
1273
0
      if (optimize && !contour_points)
1274
0
        return false;
1275
0
1276
0
      if (!merge_tuple_variations (optimize ? contour_points : nullptr))
1277
0
        return false;
1278
0
1279
0
      if (optimize && !iup_optimize (*contour_points, scratch)) return false;
1280
0
      return !tuple_vars.in_error ();
1281
0
    }
1282
1283
    bool compile_bytes (const hb_map_t& axes_index_map,
1284
                        const hb_map_t& axes_old_index_tag_map,
1285
                        bool use_shared_points,
1286
                        bool is_gvar = false,
1287
                        const hb_hashmap_t<const hb_vector_t<F2DOT14>*, unsigned>* shared_tuples_idx_map = nullptr,
1288
      hb_alloc_pool_t *pool = nullptr)
1289
    {
1290
      // return true for empty glyph
1291
      if (!tuple_vars)
1292
        return true;
1293
1294
      // compile points set and store data in hashmap
1295
      if (!compile_all_point_sets ())
1296
        return false;
1297
1298
      /* total compiled byte size as TupleVariationData format, initialized to its
1299
       * min_size: 4 */
1300
      compiled_byte_size += 4;
1301
1302
      if (use_shared_points)
1303
      {
1304
        find_shared_points ();
1305
        if (shared_points_bytes)
1306
          compiled_byte_size += shared_points_bytes->length;
1307
      }
1308
      hb_vector_t<int> rounded_deltas_scratch;
1309
      // compile delta and tuple var header for each tuple variation
1310
      for (auto& tuple: tuple_vars)
1311
      {
1312
        const hb_vector_t<bool>* points_set = &(tuple.indices);
1313
        hb_vector_t<unsigned char> *points_data;
1314
        if (unlikely (!point_data_map.has (points_set, &points_data)))
1315
          return false;
1316
1317
        /* when iup optimization is enabled, num of referenced points could be 0
1318
         * and thus the compiled points bytes is empty, we should skip compiling
1319
         * this tuple */
1320
        if (!points_data->length)
1321
          continue;
1322
        if (!tuple.compile_deltas (rounded_deltas_scratch, pool))
1323
          return false;
1324
1325
        unsigned points_data_length = (points_data != shared_points_bytes) ? points_data->length : 0;
1326
        if (!tuple.compile_tuple_var_header (axes_index_map, points_data_length, axes_old_index_tag_map,
1327
                                             shared_tuples_idx_map,
1328
               pool))
1329
          return false;
1330
        compiled_byte_size += tuple.compiled_tuple_header.length + points_data_length + tuple.compiled_deltas.length;
1331
      }
1332
1333
      if (is_gvar && (compiled_byte_size % 2))
1334
      {
1335
        needs_padding = true;
1336
        compiled_byte_size += 1;
1337
      }
1338
1339
      return true;
1340
    }
1341
1342
    bool serialize_var_headers (hb_serialize_context_t *c, unsigned& total_header_len) const
1343
    {
1344
      TRACE_SERIALIZE (this);
1345
      for (const auto& tuple: tuple_vars)
1346
      {
1347
        tuple.compiled_tuple_header.as_array ().copy (c);
1348
        if (c->in_error ()) return_trace (false);
1349
        total_header_len += tuple.compiled_tuple_header.length;
1350
      }
1351
      return_trace (true);
1352
    }
1353
1354
    bool serialize_var_data (hb_serialize_context_t *c, bool is_gvar) const
1355
    {
1356
      TRACE_SERIALIZE (this);
1357
      if (is_gvar && shared_points_bytes)
1358
      {
1359
        hb_ubytes_t s (shared_points_bytes->arrayZ, shared_points_bytes->length);
1360
        s.copy (c);
1361
      }
1362
1363
      for (const auto& tuple: tuple_vars)
1364
      {
1365
        const hb_vector_t<bool>* points_set = &(tuple.indices);
1366
        hb_vector_t<unsigned char> *point_data;
1367
        if (!point_data_map.has (points_set, &point_data))
1368
          return_trace (false);
1369
1370
        if (!is_gvar || point_data != shared_points_bytes)
1371
        {
1372
          hb_ubytes_t s (point_data->arrayZ, point_data->length);
1373
          s.copy (c);
1374
        }
1375
1376
        tuple.compiled_deltas.as_array ().copy (c);
1377
        if (c->in_error ()) return_trace (false);
1378
      }
1379
1380
      /* padding for gvar */
1381
      if (is_gvar && needs_padding)
1382
      {
1383
        HBUINT8 pad;
1384
        pad = 0;
1385
        if (!c->embed (pad)) return_trace (false);
1386
      }
1387
      return_trace (true);
1388
    }
1389
  };
1390
1391
  struct tuple_iterator_t
1392
  {
1393
    unsigned get_axis_count () const { return axis_count; }
1394
1395
    void init (hb_bytes_t var_data_bytes_, unsigned int axis_count_, const void *table_base_)
1396
32.6k
    {
1397
32.6k
      var_data_bytes = var_data_bytes_;
1398
32.6k
      var_data = var_data_bytes_.as<TupleVariationData> ();
1399
32.6k
      tuples_left = var_data->tupleVarCount.get_count ();
1400
32.6k
      axis_count = axis_count_;
1401
32.6k
      current_tuple = &var_data->get_tuple_var_header ();
1402
32.6k
      data_offset = 0;
1403
32.6k
      table_base = table_base_;
1404
32.6k
    }
OT::TupleVariationData<OT::NumType<true, unsigned int, 3u> >::tuple_iterator_t::init(hb_array_t<char const>, unsigned int, void const*)
Line
Count
Source
1396
15.7k
    {
1397
15.7k
      var_data_bytes = var_data_bytes_;
1398
15.7k
      var_data = var_data_bytes_.as<TupleVariationData> ();
1399
15.7k
      tuples_left = var_data->tupleVarCount.get_count ();
1400
15.7k
      axis_count = axis_count_;
1401
15.7k
      current_tuple = &var_data->get_tuple_var_header ();
1402
15.7k
      data_offset = 0;
1403
15.7k
      table_base = table_base_;
1404
15.7k
    }
OT::TupleVariationData<OT::NumType<true, unsigned short, 2u> >::tuple_iterator_t::init(hb_array_t<char const>, unsigned int, void const*)
Line
Count
Source
1396
16.9k
    {
1397
16.9k
      var_data_bytes = var_data_bytes_;
1398
16.9k
      var_data = var_data_bytes_.as<TupleVariationData> ();
1399
16.9k
      tuples_left = var_data->tupleVarCount.get_count ();
1400
16.9k
      axis_count = axis_count_;
1401
16.9k
      current_tuple = &var_data->get_tuple_var_header ();
1402
16.9k
      data_offset = 0;
1403
16.9k
      table_base = table_base_;
1404
16.9k
    }
1405
1406
    bool get_shared_indices (hb_vector_t<unsigned int> &shared_indices /* OUT */)
1407
32.6k
    {
1408
32.6k
      if (var_data->has_shared_point_numbers ())
1409
20.1k
      {
1410
20.1k
        const HBUINT8 *base = &(table_base+var_data->data);
1411
20.1k
        const HBUINT8 *p = base;
1412
20.1k
        if (!decompile_points (p, shared_indices, (const HBUINT8 *) (var_data_bytes.arrayZ + var_data_bytes.length))) return false;
1413
12.2k
        data_offset = p - base;
1414
12.2k
      }
1415
24.7k
      return true;
1416
32.6k
    }
OT::TupleVariationData<OT::NumType<true, unsigned int, 3u> >::tuple_iterator_t::get_shared_indices(hb_vector_t<unsigned int, false>&)
Line
Count
Source
1407
15.7k
    {
1408
15.7k
      if (var_data->has_shared_point_numbers ())
1409
7.30k
      {
1410
7.30k
        const HBUINT8 *base = &(table_base+var_data->data);
1411
7.30k
        const HBUINT8 *p = base;
1412
7.30k
        if (!decompile_points (p, shared_indices, (const HBUINT8 *) (var_data_bytes.arrayZ + var_data_bytes.length))) return false;
1413
6.46k
        data_offset = p - base;
1414
6.46k
      }
1415
14.8k
      return true;
1416
15.7k
    }
OT::TupleVariationData<OT::NumType<true, unsigned short, 2u> >::tuple_iterator_t::get_shared_indices(hb_vector_t<unsigned int, false>&)
Line
Count
Source
1407
16.9k
    {
1408
16.9k
      if (var_data->has_shared_point_numbers ())
1409
12.8k
      {
1410
12.8k
        const HBUINT8 *base = &(table_base+var_data->data);
1411
12.8k
        const HBUINT8 *p = base;
1412
12.8k
        if (!decompile_points (p, shared_indices, (const HBUINT8 *) (var_data_bytes.arrayZ + var_data_bytes.length))) return false;
1413
5.82k
        data_offset = p - base;
1414
5.82k
      }
1415
9.90k
      return true;
1416
16.9k
    }
1417
1418
    bool is_valid ()
1419
164k
    {
1420
164k
      if (unlikely (tuples_left <= 0))
1421
1.31k
  return false;
1422
1423
163k
      current_tuple_size = TupleVariationHeader::min_size;
1424
163k
      if (unlikely (!var_data_bytes.check_range (current_tuple, current_tuple_size)))
1425
3.44k
  return false;
1426
1427
159k
      current_tuple_size = current_tuple->get_size (axis_count);
1428
159k
      if (unlikely (!var_data_bytes.check_range (current_tuple, current_tuple_size)))
1429
2.94k
  return false;
1430
1431
156k
      return true;
1432
159k
    }
OT::TupleVariationData<OT::NumType<true, unsigned int, 3u> >::tuple_iterator_t::is_valid()
Line
Count
Source
1419
99.6k
    {
1420
99.6k
      if (unlikely (tuples_left <= 0))
1421
680
  return false;
1422
1423
99.0k
      current_tuple_size = TupleVariationHeader::min_size;
1424
99.0k
      if (unlikely (!var_data_bytes.check_range (current_tuple, current_tuple_size)))
1425
1.70k
  return false;
1426
1427
97.3k
      current_tuple_size = current_tuple->get_size (axis_count);
1428
97.3k
      if (unlikely (!var_data_bytes.check_range (current_tuple, current_tuple_size)))
1429
1.68k
  return false;
1430
1431
95.6k
      return true;
1432
97.3k
    }
OT::TupleVariationData<OT::NumType<true, unsigned short, 2u> >::tuple_iterator_t::is_valid()
Line
Count
Source
1419
64.8k
    {
1420
64.8k
      if (unlikely (tuples_left <= 0))
1421
635
  return false;
1422
1423
64.2k
      current_tuple_size = TupleVariationHeader::min_size;
1424
64.2k
      if (unlikely (!var_data_bytes.check_range (current_tuple, current_tuple_size)))
1425
1.73k
  return false;
1426
1427
62.5k
      current_tuple_size = current_tuple->get_size (axis_count);
1428
62.5k
      if (unlikely (!var_data_bytes.check_range (current_tuple, current_tuple_size)))
1429
1.26k
  return false;
1430
1431
61.2k
      return true;
1432
62.5k
    }
1433
1434
    HB_ALWAYS_INLINE
1435
    bool move_to_next ()
1436
139k
    {
1437
139k
      data_offset += current_tuple->get_data_size ();
1438
139k
      current_tuple = &StructAtOffset<TupleVariationHeader> (current_tuple, current_tuple_size);
1439
139k
      tuples_left--;
1440
139k
      return is_valid ();
1441
139k
    }
OT::TupleVariationData<OT::NumType<true, unsigned int, 3u> >::tuple_iterator_t::move_to_next()
Line
Count
Source
1436
84.8k
    {
1437
84.8k
      data_offset += current_tuple->get_data_size ();
1438
84.8k
      current_tuple = &StructAtOffset<TupleVariationHeader> (current_tuple, current_tuple_size);
1439
84.8k
      tuples_left--;
1440
84.8k
      return is_valid ();
1441
84.8k
    }
OT::TupleVariationData<OT::NumType<true, unsigned short, 2u> >::tuple_iterator_t::move_to_next()
Line
Count
Source
1436
54.9k
    {
1437
54.9k
      data_offset += current_tuple->get_data_size ();
1438
54.9k
      current_tuple = &StructAtOffset<TupleVariationHeader> (current_tuple, current_tuple_size);
1439
54.9k
      tuples_left--;
1440
54.9k
      return is_valid ();
1441
54.9k
    }
1442
1443
    // TODO: Make it return (sanitized) hb_bytes_t
1444
    const HBUINT8 *get_serialized_data () const
1445
23.8k
    { return &(table_base+var_data->data) + data_offset; }
OT::TupleVariationData<OT::NumType<true, unsigned int, 3u> >::tuple_iterator_t::get_serialized_data() const
Line
Count
Source
1445
13.2k
    { return &(table_base+var_data->data) + data_offset; }
OT::TupleVariationData<OT::NumType<true, unsigned short, 2u> >::tuple_iterator_t::get_serialized_data() const
Line
Count
Source
1445
10.5k
    { return &(table_base+var_data->data) + data_offset; }
1446
1447
    private:
1448
    signed tuples_left;
1449
    const TupleVariationData *var_data;
1450
    unsigned int axis_count;
1451
    unsigned int data_offset;
1452
    unsigned int current_tuple_size;
1453
    const void *table_base;
1454
1455
    public:
1456
    hb_bytes_t var_data_bytes;
1457
    const TupleVariationHeader *current_tuple;
1458
  };
1459
1460
  static bool get_tuple_iterator (hb_bytes_t var_data_bytes, unsigned axis_count,
1461
                                  const void *table_base,
1462
                                  hb_vector_t<unsigned int> &shared_indices /* OUT */,
1463
                                  tuple_iterator_t *iterator /* OUT */)
1464
32.6k
  {
1465
32.6k
    iterator->init (var_data_bytes, axis_count, table_base);
1466
32.6k
    if (!iterator->get_shared_indices (shared_indices))
1467
7.90k
      return false;
1468
24.7k
    return iterator->is_valid ();
1469
32.6k
  }
OT::TupleVariationData<OT::NumType<true, unsigned int, 3u> >::get_tuple_iterator(hb_array_t<char const>, unsigned int, void const*, hb_vector_t<unsigned int, false>&, OT::TupleVariationData<OT::NumType<true, unsigned int, 3u> >::tuple_iterator_t*)
Line
Count
Source
1464
15.7k
  {
1465
15.7k
    iterator->init (var_data_bytes, axis_count, table_base);
1466
15.7k
    if (!iterator->get_shared_indices (shared_indices))
1467
844
      return false;
1468
14.8k
    return iterator->is_valid ();
1469
15.7k
  }
OT::TupleVariationData<OT::NumType<true, unsigned short, 2u> >::get_tuple_iterator(hb_array_t<char const>, unsigned int, void const*, hb_vector_t<unsigned int, false>&, OT::TupleVariationData<OT::NumType<true, unsigned short, 2u> >::tuple_iterator_t*)
Line
Count
Source
1464
16.9k
  {
1465
16.9k
    iterator->init (var_data_bytes, axis_count, table_base);
1466
16.9k
    if (!iterator->get_shared_indices (shared_indices))
1467
7.06k
      return false;
1468
9.90k
    return iterator->is_valid ();
1469
16.9k
  }
1470
1471
32.6k
  bool has_shared_point_numbers () const { return tupleVarCount.has_shared_point_numbers (); }
OT::TupleVariationData<OT::NumType<true, unsigned int, 3u> >::has_shared_point_numbers() const
Line
Count
Source
1471
15.7k
  bool has_shared_point_numbers () const { return tupleVarCount.has_shared_point_numbers (); }
OT::TupleVariationData<OT::NumType<true, unsigned short, 2u> >::has_shared_point_numbers() const
Line
Count
Source
1471
16.9k
  bool has_shared_point_numbers () const { return tupleVarCount.has_shared_point_numbers (); }
1472
1473
  static bool decompile_points (const HBUINT8 *&p /* IN/OUT */,
1474
        hb_vector_t<unsigned int> &points /* OUT */,
1475
        const HBUINT8 *end)
1476
24.5k
  {
1477
24.5k
    enum packed_point_flag_t
1478
24.5k
    {
1479
24.5k
      POINTS_ARE_WORDS     = 0x80,
1480
24.5k
      POINT_RUN_COUNT_MASK = 0x7F
1481
24.5k
    };
1482
1483
24.5k
    if (unlikely (p + 1 > end)) return false;
1484
1485
23.6k
    unsigned count = *p++;
1486
23.6k
    if (count & POINTS_ARE_WORDS)
1487
3.99k
    {
1488
3.99k
      if (unlikely (p + 1 > end)) return false;
1489
3.69k
      count = ((count & POINT_RUN_COUNT_MASK) << 8) | *p++;
1490
3.69k
    }
1491
23.3k
    if (unlikely (!points.resize_dirty  (count))) return false;
1492
1493
22.7k
    unsigned n = 0;
1494
22.7k
    unsigned i = 0;
1495
367k
    while (i < count)
1496
351k
    {
1497
351k
      if (unlikely (p + 1 > end)) return false;
1498
349k
      unsigned control = *p++;
1499
349k
      unsigned run_count = (control & POINT_RUN_COUNT_MASK) + 1;
1500
349k
      unsigned stop = i + run_count;
1501
349k
      if (unlikely (stop > count)) return false;
1502
346k
      if (control & POINTS_ARE_WORDS)
1503
25.6k
      {
1504
25.6k
        if (unlikely (p + run_count * HBUINT16::static_size > end)) return false;
1505
1.98M
        for (; i < stop; i++)
1506
1.96M
        {
1507
1.96M
          n += *(const HBUINT16 *)p;
1508
1.96M
          points.arrayZ[i] = n;
1509
1.96M
          p += HBUINT16::static_size;
1510
1.96M
        }
1511
24.8k
      }
1512
320k
      else
1513
320k
      {
1514
320k
        if (unlikely (p + run_count > end)) return false;
1515
1.85M
        for (; i < stop; i++)
1516
1.54M
        {
1517
1.54M
          n += *p++;
1518
1.54M
          points.arrayZ[i] = n;
1519
1.54M
        }
1520
319k
      }
1521
346k
    }
1522
15.3k
    return true;
1523
22.7k
  }
OT::TupleVariationData<OT::NumType<true, unsigned int, 3u> >::decompile_points(OT::NumType<true, unsigned char, 1u> const*&, hb_vector_t<unsigned int, false>&, OT::NumType<true, unsigned char, 1u> const*)
Line
Count
Source
1476
10.7k
  {
1477
10.7k
    enum packed_point_flag_t
1478
10.7k
    {
1479
10.7k
      POINTS_ARE_WORDS     = 0x80,
1480
10.7k
      POINT_RUN_COUNT_MASK = 0x7F
1481
10.7k
    };
1482
1483
10.7k
    if (unlikely (p + 1 > end)) return false;
1484
1485
10.5k
    unsigned count = *p++;
1486
10.5k
    if (count & POINTS_ARE_WORDS)
1487
968
    {
1488
968
      if (unlikely (p + 1 > end)) return false;
1489
708
      count = ((count & POINT_RUN_COUNT_MASK) << 8) | *p++;
1490
708
    }
1491
10.2k
    if (unlikely (!points.resize_dirty  (count))) return false;
1492
1493
10.0k
    unsigned n = 0;
1494
10.0k
    unsigned i = 0;
1495
34.2k
    while (i < count)
1496
25.3k
    {
1497
25.3k
      if (unlikely (p + 1 > end)) return false;
1498
25.1k
      unsigned control = *p++;
1499
25.1k
      unsigned run_count = (control & POINT_RUN_COUNT_MASK) + 1;
1500
25.1k
      unsigned stop = i + run_count;
1501
25.1k
      if (unlikely (stop > count)) return false;
1502
24.8k
      if (control & POINTS_ARE_WORDS)
1503
506
      {
1504
506
        if (unlikely (p + run_count * HBUINT16::static_size > end)) return false;
1505
15.4k
        for (; i < stop; i++)
1506
15.2k
        {
1507
15.2k
          n += *(const HBUINT16 *)p;
1508
15.2k
          points.arrayZ[i] = n;
1509
15.2k
          p += HBUINT16::static_size;
1510
15.2k
        }
1511
263
      }
1512
24.3k
      else
1513
24.3k
      {
1514
24.3k
        if (unlikely (p + run_count > end)) return false;
1515
92.6k
        for (; i < stop; i++)
1516
68.7k
        {
1517
68.7k
          n += *p++;
1518
68.7k
          points.arrayZ[i] = n;
1519
68.7k
        }
1520
23.9k
      }
1521
24.8k
    }
1522
8.88k
    return true;
1523
10.0k
  }
OT::TupleVariationData<OT::NumType<true, unsigned short, 2u> >::decompile_points(OT::NumType<true, unsigned char, 1u> const*&, hb_vector_t<unsigned int, false>&, OT::NumType<true, unsigned char, 1u> const*)
Line
Count
Source
1476
13.7k
  {
1477
13.7k
    enum packed_point_flag_t
1478
13.7k
    {
1479
13.7k
      POINTS_ARE_WORDS     = 0x80,
1480
13.7k
      POINT_RUN_COUNT_MASK = 0x7F
1481
13.7k
    };
1482
1483
13.7k
    if (unlikely (p + 1 > end)) return false;
1484
1485
13.0k
    unsigned count = *p++;
1486
13.0k
    if (count & POINTS_ARE_WORDS)
1487
3.02k
    {
1488
3.02k
      if (unlikely (p + 1 > end)) return false;
1489
2.98k
      count = ((count & POINT_RUN_COUNT_MASK) << 8) | *p++;
1490
2.98k
    }
1491
13.0k
    if (unlikely (!points.resize_dirty  (count))) return false;
1492
1493
12.7k
    unsigned n = 0;
1494
12.7k
    unsigned i = 0;
1495
333k
    while (i < count)
1496
326k
    {
1497
326k
      if (unlikely (p + 1 > end)) return false;
1498
324k
      unsigned control = *p++;
1499
324k
      unsigned run_count = (control & POINT_RUN_COUNT_MASK) + 1;
1500
324k
      unsigned stop = i + run_count;
1501
324k
      if (unlikely (stop > count)) return false;
1502
321k
      if (control & POINTS_ARE_WORDS)
1503
25.1k
      {
1504
25.1k
        if (unlikely (p + run_count * HBUINT16::static_size > end)) return false;
1505
1.97M
        for (; i < stop; i++)
1506
1.94M
        {
1507
1.94M
          n += *(const HBUINT16 *)p;
1508
1.94M
          points.arrayZ[i] = n;
1509
1.94M
          p += HBUINT16::static_size;
1510
1.94M
        }
1511
24.6k
      }
1512
296k
      else
1513
296k
      {
1514
296k
        if (unlikely (p + run_count > end)) return false;
1515
1.76M
        for (; i < stop; i++)
1516
1.47M
        {
1517
1.47M
          n += *p++;
1518
1.47M
          points.arrayZ[i] = n;
1519
1.47M
        }
1520
295k
      }
1521
321k
    }
1522
6.43k
    return true;
1523
12.7k
  }
1524
1525
  template <typename T>
1526
  static bool decompile_deltas (const HBUINT8 *&p /* IN/OUT */,
1527
        hb_vector_t<T> &deltas /* IN/OUT */,
1528
        const HBUINT8 *end,
1529
        bool consume_all = false,
1530
        unsigned start = 0)
1531
21.2k
  {
1532
21.2k
    return TupleValues::decompile (p, deltas, end, consume_all, start);
1533
21.2k
  }
bool OT::TupleVariationData<OT::NumType<true, unsigned int, 3u> >::decompile_deltas<int>(OT::NumType<true, unsigned char, 1u> const*&, hb_vector_t<int, false>&, OT::NumType<true, unsigned char, 1u> const*, bool, unsigned int)
Line
Count
Source
1531
9.16k
  {
1532
9.16k
    return TupleValues::decompile (p, deltas, end, consume_all, start);
1533
9.16k
  }
bool OT::TupleVariationData<OT::NumType<true, unsigned short, 2u> >::decompile_deltas<int>(OT::NumType<true, unsigned char, 1u> const*&, hb_vector_t<int, false>&, OT::NumType<true, unsigned char, 1u> const*, bool, unsigned int)
Line
Count
Source
1531
12.0k
  {
1532
12.0k
    return TupleValues::decompile (p, deltas, end, consume_all, start);
1533
12.0k
  }
1534
1535
49.0k
  bool has_data () const { return tupleVarCount; }
OT::TupleVariationData<OT::NumType<true, unsigned int, 3u> >::has_data() const
Line
Count
Source
1535
20.2k
  bool has_data () const { return tupleVarCount; }
OT::TupleVariationData<OT::NumType<true, unsigned short, 2u> >::has_data() const
Line
Count
Source
1535
28.7k
  bool has_data () const { return tupleVarCount; }
1536
1537
  bool decompile_tuple_variations (unsigned point_count,
1538
                                   bool is_gvar,
1539
                                   tuple_iterator_t iterator,
1540
                                   const hb_map_t *axes_old_index_tag_map,
1541
                                   const hb_vector_t<unsigned> &shared_indices,
1542
                                   const hb_array_t<const F2DOT14> shared_tuples,
1543
                                   tuple_variations_t& tuple_variations, /* OUT */
1544
           hb_alloc_pool_t *pool = nullptr,
1545
                                   bool is_composite_glyph = false) const
1546
  {
1547
    return tuple_variations.create_from_tuple_var_data (iterator, tupleVarCount,
1548
                                                        point_count, is_gvar,
1549
                                                        axes_old_index_tag_map,
1550
                                                        shared_indices,
1551
                                                        shared_tuples,
1552
              pool,
1553
                                                        is_composite_glyph);
1554
  }
1555
1556
  bool serialize (hb_serialize_context_t *c,
1557
                  bool is_gvar,
1558
                  const tuple_variations_t& tuple_variations) const
1559
  {
1560
    TRACE_SERIALIZE (this);
1561
    /* empty tuple variations, just return and skip serialization. */
1562
    if (!tuple_variations) return_trace (true);
1563
1564
    auto *out = c->start_embed (this);
1565
    if (unlikely (!c->extend_min (out))) return_trace (false);
1566
1567
    if (!c->check_assign (out->tupleVarCount, tuple_variations.get_var_count (),
1568
                          HB_SERIALIZE_ERROR_INT_OVERFLOW)) return_trace (false);
1569
1570
    unsigned total_header_len = 0;
1571
1572
    if (!tuple_variations.serialize_var_headers (c, total_header_len))
1573
      return_trace (false);
1574
1575
    unsigned data_offset = min_size + total_header_len;
1576
    if (!is_gvar) data_offset += 4;
1577
    if (!c->check_assign (out->data, data_offset, HB_SERIALIZE_ERROR_INT_OVERFLOW)) return_trace (false);
1578
1579
    return tuple_variations.serialize_var_data (c, is_gvar);
1580
  }
1581
1582
  protected:
1583
  struct TupleVarCount : HBUINT16
1584
  {
1585
    friend struct tuple_variations_t;
1586
32.6k
    bool has_shared_point_numbers () const { return ((*this) & SharedPointNumbers); }
OT::TupleVariationData<OT::NumType<true, unsigned int, 3u> >::TupleVarCount::has_shared_point_numbers() const
Line
Count
Source
1586
15.7k
    bool has_shared_point_numbers () const { return ((*this) & SharedPointNumbers); }
OT::TupleVariationData<OT::NumType<true, unsigned short, 2u> >::TupleVarCount::has_shared_point_numbers() const
Line
Count
Source
1586
16.9k
    bool has_shared_point_numbers () const { return ((*this) & SharedPointNumbers); }
1587
32.6k
    unsigned int get_count () const { return (*this) & CountMask; }
OT::TupleVariationData<OT::NumType<true, unsigned int, 3u> >::TupleVarCount::get_count() const
Line
Count
Source
1587
15.7k
    unsigned int get_count () const { return (*this) & CountMask; }
OT::TupleVariationData<OT::NumType<true, unsigned short, 2u> >::TupleVarCount::get_count() const
Line
Count
Source
1587
16.9k
    unsigned int get_count () const { return (*this) & CountMask; }
1588
    TupleVarCount& operator = (uint16_t i) { HBUINT16::operator= (i); return *this; }
1589
    explicit operator bool () const { return get_count (); }
1590
1591
    protected:
1592
    enum Flags
1593
    {
1594
      SharedPointNumbers= 0x8000u,
1595
      CountMask         = 0x0FFFu
1596
    };
1597
    public:
1598
    DEFINE_SIZE_STATIC (2);
1599
  };
1600
1601
  TupleVarCount tupleVarCount;  /* A packed field. The high 4 bits are flags, and the
1602
                                 * low 12 bits are the number of tuple variation tables
1603
                                 * for this glyph. The number of tuple variation tables
1604
                                 * can be any number between 1 and 4095. */
1605
  OffsetTo<HBUINT8, OffType>
1606
                data;           /* Offset from the start of the base table
1607
                                 * to the serialized data. */
1608
  /* TupleVariationHeader tupleVariationHeaders[] *//* Array of tuple variation headers. */
1609
  public:
1610
  DEFINE_SIZE_MIN (2 + OffType::static_size);
1611
};
1612
1613
// TODO: Move tuple_variations_t to outside of TupleVariationData
1614
using tuple_variations_t = TupleVariationData<HBUINT16>::tuple_variations_t;
1615
struct item_variations_t
1616
{
1617
  using region_t = const hb_hashmap_t<hb_tag_t, Triple>*;
1618
  private:
1619
  /* each subtable is decompiled into a tuple_variations_t, in which all tuples
1620
   * have the same num of deltas (rows) */
1621
  hb_vector_t<tuple_variations_t> vars;
1622
1623
  /* num of retained rows for each subtable, there're 2 cases when var_data is empty:
1624
   * 1. retained item_count is zero
1625
   * 2. regions is empty and item_count is non-zero.
1626
   * when converting to tuples, both will be dropped because the tuple is empty,
1627
   * however, we need to retain 2. as all-zero rows to keep original varidx
1628
   * valid, so we need a way to remember the num of rows for each subtable */
1629
  hb_vector_t<unsigned> var_data_num_rows;
1630
1631
  /* original region list, decompiled from item varstore, used when rebuilding
1632
   * region list after instantiation */
1633
  hb_vector_t<hb_hashmap_t<hb_tag_t, Triple>> orig_region_list;
1634
1635
  /* region list: vector of Regions, maintain the original order for the regions
1636
   * that existed before instantiate (), append the new regions at the end.
1637
   * Regions are stored in each tuple already, save pointers only.
1638
   * When converting back to item varstore, unused regions will be pruned */
1639
  hb_vector_t<region_t> region_list;
1640
1641
  /* region -> idx map after instantiation and pruning unused regions */
1642
  hb_hashmap_t<region_t, unsigned> region_map;
1643
1644
  /* all delta rows after instantiation */
1645
  hb_vector_t<hb_vector_t<int>> delta_rows;
1646
  /* final optimized vector of encoding objects used to assemble the varstore */
1647
  hb_vector_t<delta_row_encoding_t> encodings;
1648
1649
  /* old varidxes -> new var_idxes map */
1650
  hb_map_t varidx_map;
1651
1652
  /* has long words */
1653
  bool has_long = false;
1654
1655
  public:
1656
  bool has_long_word () const
1657
0
  { return has_long; }
1658
1659
  const hb_vector_t<region_t>& get_region_list () const
1660
0
  { return region_list; }
1661
1662
  const hb_vector_t<delta_row_encoding_t>& get_vardata_encodings () const
1663
0
  { return encodings; }
1664
1665
  const hb_map_t& get_varidx_map () const
1666
0
  { return varidx_map; }
1667
1668
  bool instantiate (const ItemVariationStore& varStore,
1669
                    const hb_subset_plan_t *plan,
1670
                    bool optimize=true,
1671
                    bool use_no_variation_idx=true,
1672
                    const hb_array_t <const hb_inc_bimap_t> inner_maps = hb_array_t<const hb_inc_bimap_t> ())
1673
0
  {
1674
0
    if (!create_from_item_varstore (varStore, plan->axes_old_index_tag_map, inner_maps))
1675
0
      return false;
1676
0
    if (!instantiate_tuple_vars (plan->axes_location, plan->axes_triple_distances))
1677
0
      return false;
1678
0
    return as_item_varstore (optimize, use_no_variation_idx);
1679
0
  }
1680
1681
  /* keep below APIs public only for unit test: test-item-varstore */
1682
  bool create_from_item_varstore (const ItemVariationStore& varStore,
1683
                                  const hb_map_t& axes_old_index_tag_map,
1684
                                  const hb_array_t <const hb_inc_bimap_t> inner_maps = hb_array_t<const hb_inc_bimap_t> ())
1685
0
  {
1686
0
    const VarRegionList& regionList = varStore.get_region_list ();
1687
0
    if (!regionList.get_var_regions (axes_old_index_tag_map, orig_region_list))
1688
0
      return false;
1689
0
1690
0
    unsigned num_var_data = varStore.get_sub_table_count ();
1691
0
    if (inner_maps && inner_maps.length != num_var_data) return false;
1692
0
    if (!vars.alloc (num_var_data) ||
1693
0
        !var_data_num_rows.alloc (num_var_data)) return false;
1694
0
1695
0
    for (unsigned i = 0; i < num_var_data; i++)
1696
0
    {
1697
0
      if (inner_maps && !inner_maps.arrayZ[i].get_population ())
1698
0
          continue;
1699
0
      tuple_variations_t var_data_tuples;
1700
0
      unsigned item_count = 0;
1701
0
      if (!var_data_tuples.create_from_item_var_data (varStore.get_sub_table (i),
1702
0
                                                      orig_region_list,
1703
0
                                                      axes_old_index_tag_map,
1704
0
                                                      item_count,
1705
0
                                                      inner_maps ? &(inner_maps.arrayZ[i]) : nullptr))
1706
0
        return false;
1707
0
1708
0
      var_data_num_rows.push (item_count);
1709
0
      vars.push (std::move (var_data_tuples));
1710
0
    }
1711
0
    return !vars.in_error () && !var_data_num_rows.in_error () && vars.length == var_data_num_rows.length;
1712
0
  }
1713
1714
  bool instantiate_tuple_vars (const hb_hashmap_t<hb_tag_t, Triple>& normalized_axes_location,
1715
                               const hb_hashmap_t<hb_tag_t, TripleDistances>& axes_triple_distances)
1716
0
  {
1717
0
    optimize_scratch_t scratch;
1718
0
    for (tuple_variations_t& tuple_vars : vars)
1719
0
      if (!tuple_vars.instantiate (normalized_axes_location, axes_triple_distances, scratch))
1720
0
        return false;
1721
0
1722
0
    if (!build_region_list ()) return false;
1723
0
    return true;
1724
0
  }
1725
1726
  bool build_region_list ()
1727
0
  {
1728
0
    /* scan all tuples and collect all unique regions, prune unused regions */
1729
0
    hb_hashmap_t<region_t, unsigned> all_regions;
1730
0
    hb_hashmap_t<region_t, unsigned> used_regions;
1731
0
1732
0
    /* use a vector when inserting new regions, make result deterministic */
1733
0
    hb_vector_t<region_t> all_unique_regions;
1734
0
    for (const tuple_variations_t& sub_table : vars)
1735
0
    {
1736
0
      for (const tuple_delta_t& tuple : sub_table.tuple_vars)
1737
0
      {
1738
0
        region_t r = &(tuple.axis_tuples);
1739
0
        if (!used_regions.has (r))
1740
0
        {
1741
0
          bool all_zeros = true;
1742
0
          for (float d : tuple.deltas_x)
1743
0
          {
1744
0
            int delta = (int) roundf (d);
1745
0
            if (delta != 0)
1746
0
            {
1747
0
              all_zeros = false;
1748
0
              break;
1749
0
            }
1750
0
          }
1751
0
          if (!all_zeros)
1752
0
          {
1753
0
            if (!used_regions.set (r, 1))
1754
0
              return false;
1755
0
          }
1756
0
        }
1757
0
        if (all_regions.has (r))
1758
0
          continue;
1759
0
        if (!all_regions.set (r, 1))
1760
0
          return false;
1761
0
        all_unique_regions.push (r);
1762
0
      }
1763
0
    }
1764
0
1765
0
    /* regions are empty means no variation data, return true */
1766
0
    if (!all_regions || !all_unique_regions) return true;
1767
0
1768
0
    if (!region_list.alloc (all_regions.get_population ()))
1769
0
      return false;
1770
0
1771
0
    unsigned idx = 0;
1772
0
    /* append the original regions that pre-existed */
1773
0
    for (const auto& r : orig_region_list)
1774
0
    {
1775
0
      if (!all_regions.has (&r) || !used_regions.has (&r))
1776
0
        continue;
1777
0
1778
0
      region_list.push (&r);
1779
0
      if (!region_map.set (&r, idx))
1780
0
        return false;
1781
0
      all_regions.del (&r);
1782
0
      idx++;
1783
0
    }
1784
0
1785
0
    /* append the new regions at the end */
1786
0
    for (const auto& r: all_unique_regions)
1787
0
    {
1788
0
      if (!all_regions.has (r) || !used_regions.has (r))
1789
0
        continue;
1790
0
      region_list.push (r);
1791
0
      if (!region_map.set (r, idx))
1792
0
        return false;
1793
0
      all_regions.del (r);
1794
0
      idx++;
1795
0
    }
1796
0
    return (!region_list.in_error ()) && (!region_map.in_error ());
1797
0
  }
1798
1799
  /* main algorithm ported from fonttools VarStore_optimize() method, optimize
1800
   * varstore by default */
1801
1802
  struct combined_gain_idx_tuple_t
1803
  {
1804
    uint64_t encoded;
1805
1806
    combined_gain_idx_tuple_t () = default;
1807
    combined_gain_idx_tuple_t (unsigned gain, unsigned i, unsigned j)
1808
        : encoded ((uint64_t (0xFFFFFF - gain) << 40) | (uint64_t (i) << 20) | uint64_t (j))
1809
0
    {
1810
0
      assert (gain < 0xFFFFFF);
1811
0
      assert (i < 0xFFFFFFF && j < 0xFFFFFFF);
1812
0
    }
1813
1814
    bool operator < (const combined_gain_idx_tuple_t& o)
1815
0
    {
1816
0
      return encoded < o.encoded;
1817
0
    }
1818
1819
    bool operator <= (const combined_gain_idx_tuple_t& o)
1820
0
    {
1821
0
      return encoded <= o.encoded;
1822
0
    }
1823
1824
0
    unsigned idx_1 () const { return (encoded >> 20) & 0xFFFFF; };
1825
0
    unsigned idx_2 () const { return encoded & 0xFFFFF; };
1826
  };
1827
1828
  bool as_item_varstore (bool optimize=true, bool use_no_variation_idx=true)
1829
0
  {
1830
0
    /* return true if no variation data */
1831
0
    if (!region_list) return true;
1832
0
    unsigned num_cols = region_list.length;
1833
0
    /* pre-alloc a 2D vector for all sub_table's VarData rows */
1834
0
    unsigned total_rows = 0;
1835
0
    for (unsigned major = 0; major < var_data_num_rows.length; major++)
1836
0
      total_rows += var_data_num_rows[major];
1837
0
1838
0
    if (!delta_rows.resize (total_rows)) return false;
1839
0
    /* init all rows to [0]*num_cols */
1840
0
    for (unsigned i = 0; i < total_rows; i++)
1841
0
      if (!(delta_rows[i].resize (num_cols))) return false;
1842
0
1843
0
    /* old VarIdxes -> full encoding_row mapping */
1844
0
    hb_hashmap_t<unsigned, const hb_vector_t<int>*> front_mapping;
1845
0
    unsigned start_row = 0;
1846
0
    hb_vector_t<delta_row_encoding_t> encoding_objs;
1847
0
1848
0
    /* delta_rows map, used for filtering out duplicate rows */
1849
0
    hb_vector_t<const hb_vector_t<int> *> major_rows;
1850
0
    hb_hashmap_t<const hb_vector_t<int>*, unsigned> delta_rows_map;
1851
0
    for (unsigned major = 0; major < vars.length; major++)
1852
0
    {
1853
0
      /* deltas are stored in tuples(column based), convert them back into items
1854
0
       * (row based) delta */
1855
0
      const tuple_variations_t& tuples = vars[major];
1856
0
      unsigned num_rows = var_data_num_rows[major];
1857
0
1858
0
      if (!num_rows) continue;
1859
0
1860
0
      for (const tuple_delta_t& tuple: tuples.tuple_vars)
1861
0
      {
1862
0
        if (tuple.deltas_x.length != num_rows)
1863
0
          return false;
1864
0
1865
0
        /* skip unused regions */
1866
0
        unsigned *col_idx;
1867
0
        if (!region_map.has (&(tuple.axis_tuples), &col_idx))
1868
0
          continue;
1869
0
1870
0
        for (unsigned i = 0; i < num_rows; i++)
1871
0
        {
1872
0
          int rounded_delta = roundf (tuple.deltas_x[i]);
1873
0
          delta_rows[start_row + i][*col_idx] += rounded_delta;
1874
0
          has_long |= rounded_delta < -65536 || rounded_delta > 65535;
1875
0
        }
1876
0
      }
1877
0
1878
0
      major_rows.reset ();
1879
0
      for (unsigned minor = 0; minor < num_rows; minor++)
1880
0
      {
1881
0
  const hb_vector_t<int>& row = delta_rows[start_row + minor];
1882
0
  if (use_no_variation_idx)
1883
0
  {
1884
0
    bool all_zeros = true;
1885
0
    for (int delta : row)
1886
0
    {
1887
0
      if (delta != 0)
1888
0
      {
1889
0
        all_zeros = false;
1890
0
        break;
1891
0
      }
1892
0
    }
1893
0
    if (all_zeros)
1894
0
      continue;
1895
0
  }
1896
0
1897
0
  if (!front_mapping.set ((major<<16) + minor, &row))
1898
0
    return false;
1899
0
1900
0
  if (delta_rows_map.has (&row))
1901
0
    continue;
1902
0
1903
0
  delta_rows_map.set (&row, 1);
1904
0
1905
0
  major_rows.push (&row);
1906
0
      }
1907
0
1908
0
      if (major_rows)
1909
0
  encoding_objs.push (delta_row_encoding_t (std::move (major_rows), num_cols));
1910
0
1911
0
      start_row += num_rows;
1912
0
    }
1913
0
1914
0
    /* return directly if no optimization, maintain original VariationIndex so
1915
0
     * varidx_map would be empty */
1916
0
    if (!optimize)
1917
0
    {
1918
0
      encodings = std::move (encoding_objs);
1919
0
      return !encodings.in_error ();
1920
0
    }
1921
0
1922
0
    /* NOTE: Fonttools instancer always optimizes VarStore from scratch. This
1923
0
     * is too costly for large fonts. So, instead, we retain the encodings of
1924
0
     * the original VarStore, and just try to combine them if possible. This
1925
0
     * is a compromise between optimization and performance and practically
1926
0
     * works very well. */
1927
0
1928
0
    // This produces slightly smaller results in some cases.
1929
0
    encoding_objs.qsort ();
1930
0
1931
0
    /* main algorithm: repeatedly pick 2 best encodings to combine, and combine them */
1932
0
    using item_t = hb_priority_queue_t<combined_gain_idx_tuple_t>::item_t;
1933
0
    hb_vector_t<item_t> queue_items;
1934
0
    unsigned num_todos = encoding_objs.length;
1935
0
    for (unsigned i = 0; i < num_todos; i++)
1936
0
    {
1937
0
      for (unsigned j = i + 1; j < num_todos; j++)
1938
0
      {
1939
0
        int combining_gain = encoding_objs.arrayZ[i].gain_from_merging (encoding_objs.arrayZ[j]);
1940
0
        if (combining_gain > 0)
1941
0
          queue_items.push (item_t (combined_gain_idx_tuple_t (combining_gain, i, j), 0));
1942
0
      }
1943
0
    }
1944
0
1945
0
    hb_priority_queue_t<combined_gain_idx_tuple_t> queue (std::move (queue_items));
1946
0
1947
0
    hb_bit_set_t removed_todo_idxes;
1948
0
    while (queue)
1949
0
    {
1950
0
      auto t = queue.pop_minimum ().first;
1951
0
      unsigned i = t.idx_1 ();
1952
0
      unsigned j = t.idx_2 ();
1953
0
1954
0
      if (removed_todo_idxes.has (i) || removed_todo_idxes.has (j))
1955
0
        continue;
1956
0
1957
0
      delta_row_encoding_t& encoding = encoding_objs.arrayZ[i];
1958
0
      delta_row_encoding_t& other_encoding = encoding_objs.arrayZ[j];
1959
0
1960
0
      removed_todo_idxes.add (i);
1961
0
      removed_todo_idxes.add (j);
1962
0
1963
0
      encoding.merge (other_encoding);
1964
0
1965
0
      for (unsigned idx = 0; idx < encoding_objs.length; idx++)
1966
0
      {
1967
0
        if (removed_todo_idxes.has (idx)) continue;
1968
0
1969
0
        const delta_row_encoding_t& obj = encoding_objs.arrayZ[idx];
1970
0
  // In the unlikely event that the same encoding exists already, combine it.
1971
0
        if (obj.width == encoding.width && obj.chars == encoding.chars)
1972
0
        {
1973
0
    // This is straight port from fonttools algorithm. I added this branch there
1974
0
    // because I thought it can happen. But looks like we never get in here in
1975
0
    // practice. I'm not confident enough to remove it though; in theory it can
1976
0
    // happen. I think it's just that our tests are not extensive enough to hit
1977
0
    // this path.
1978
0
1979
0
          for (const auto& row : obj.items)
1980
0
            encoding.add_row (row);
1981
0
1982
0
          removed_todo_idxes.add (idx);
1983
0
          continue;
1984
0
        }
1985
0
1986
0
        int combined_gain = encoding.gain_from_merging (obj);
1987
0
        if (combined_gain > 0)
1988
0
          queue.insert (combined_gain_idx_tuple_t (combined_gain, idx, encoding_objs.length), 0);
1989
0
      }
1990
0
1991
0
      auto moved_encoding = std::move (encoding);
1992
0
      encoding_objs.push (moved_encoding);
1993
0
    }
1994
0
1995
0
    int num_final_encodings = (int) encoding_objs.length - (int) removed_todo_idxes.get_population ();
1996
0
    if (num_final_encodings <= 0) return false;
1997
0
1998
0
    if (!encodings.alloc (num_final_encodings)) return false;
1999
0
    for (unsigned i = 0; i < encoding_objs.length; i++)
2000
0
    {
2001
0
      if (removed_todo_idxes.has (i)) continue;
2002
0
      encodings.push (std::move (encoding_objs.arrayZ[i]));
2003
0
    }
2004
0
2005
0
    return compile_varidx_map (front_mapping);
2006
0
  }
2007
2008
  private:
2009
  /* compile varidx_map for one VarData subtable (index specified by major) */
2010
  bool compile_varidx_map (const hb_hashmap_t<unsigned, const hb_vector_t<int>*>& front_mapping)
2011
0
  {
2012
0
    /* full encoding_row -> new VarIdxes mapping */
2013
0
    hb_hashmap_t<const hb_vector_t<int>*, unsigned> back_mapping;
2014
0
2015
0
    for (unsigned major = 0; major < encodings.length; major++)
2016
0
    {
2017
0
      delta_row_encoding_t& encoding = encodings[major];
2018
0
      /* just sanity check, this shouldn't happen */
2019
0
      if (encoding.is_empty ())
2020
0
        return false;
2021
0
2022
0
      unsigned num_rows = encoding.items.length;
2023
0
2024
0
      /* sort rows, make result deterministic */
2025
0
      encoding.items.qsort (_cmp_row);
2026
0
2027
0
      /* compile old to new var_idxes mapping */
2028
0
      for (unsigned minor = 0; minor < num_rows; minor++)
2029
0
      {
2030
0
        unsigned new_varidx = (major << 16) + minor;
2031
0
        back_mapping.set (encoding.items.arrayZ[minor], new_varidx);
2032
0
      }
2033
0
    }
2034
0
2035
0
    for (auto _ : front_mapping.iter ())
2036
0
    {
2037
0
      unsigned old_varidx = _.first;
2038
0
      unsigned *new_varidx;
2039
0
      if (back_mapping.has (_.second, &new_varidx))
2040
0
        varidx_map.set (old_varidx, *new_varidx);
2041
0
      else
2042
0
        varidx_map.set (old_varidx, HB_OT_LAYOUT_NO_VARIATIONS_INDEX);
2043
0
    }
2044
0
    return !varidx_map.in_error ();
2045
0
  }
2046
2047
  static int _cmp_row (const void *pa, const void *pb)
2048
0
  {
2049
0
    /* compare pointers of vectors(const hb_vector_t<int>*) that represent a row */
2050
0
    const hb_vector_t<int>** a = (const hb_vector_t<int>**) pa;
2051
0
    const hb_vector_t<int>** b = (const hb_vector_t<int>**) pb;
2052
0
2053
0
    for (unsigned i = 0; i < (*b)->length; i++)
2054
0
    {
2055
0
      int va = (*a)->arrayZ[i];
2056
0
      int vb = (*b)->arrayZ[i];
2057
0
      if (va != vb)
2058
0
        return va < vb ? -1 : 1;
2059
0
    }
2060
0
    return 0;
2061
0
  }
2062
};
2063
2064
2065
} /* namespace OT */
2066
2067
2068
#endif /* HB_OT_VAR_COMMON_HH */