Coverage Report

Created: 2025-12-04 06:43

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