Coverage Report

Created: 2025-11-16 07:45

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