Coverage Report

Created: 2026-03-30 06:34

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