Coverage Report

Created: 2026-07-16 06:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/woff2/src/woff2_dec.cc
Line
Count
Source
1
/* Copyright 2014 Google Inc. All Rights Reserved.
2
3
   Distributed under MIT license.
4
   See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
5
*/
6
7
/* Library for converting WOFF2 format font files to their TTF versions. */
8
9
#include <woff2/decode.h>
10
11
#include <stdlib.h>
12
#include <algorithm>
13
#include <complex>
14
#include <cstring>
15
#include <limits>
16
#include <string>
17
#include <vector>
18
#include <map>
19
#include <memory>
20
#include <utility>
21
22
#include <brotli/decode.h>
23
#include "./buffer.h"
24
#include "./port.h"
25
#include "./round.h"
26
#include "./store_bytes.h"
27
#include "./table_tags.h"
28
#include "./variable_length.h"
29
#include "./woff2_common.h"
30
31
namespace woff2 {
32
33
namespace {
34
35
// simple glyph flags
36
const int kGlyfOnCurve = 1 << 0;
37
const int kGlyfXShort = 1 << 1;
38
const int kGlyfYShort = 1 << 2;
39
const int kGlyfRepeat = 1 << 3;
40
const int kGlyfThisXIsSame = 1 << 4;
41
const int kGlyfThisYIsSame = 1 << 5;
42
const int kOverlapSimple = 1 << 6;
43
44
// composite glyph flags
45
// See CompositeGlyph.java in sfntly for full definitions
46
const int FLAG_ARG_1_AND_2_ARE_WORDS = 1 << 0;
47
const int FLAG_WE_HAVE_A_SCALE = 1 << 3;
48
const int FLAG_MORE_COMPONENTS = 1 << 5;
49
const int FLAG_WE_HAVE_AN_X_AND_Y_SCALE = 1 << 6;
50
const int FLAG_WE_HAVE_A_TWO_BY_TWO = 1 << 7;
51
const int FLAG_WE_HAVE_INSTRUCTIONS = 1 << 8;
52
53
// glyf flags
54
const int FLAG_OVERLAP_SIMPLE_BITMAP = 1 << 0;
55
56
const size_t kCheckSumAdjustmentOffset = 8;
57
58
const size_t kEndPtsOfContoursOffset = 10;
59
const size_t kCompositeGlyphBegin = 10;
60
61
// 98% of Google Fonts have no glyph above 5k bytes
62
// Largest glyph ever observed was 72k bytes
63
const size_t kDefaultGlyphBuf = 5120;
64
65
// Over 14k test fonts the max compression ratio seen to date was ~20.
66
// >100 suggests you wrote a bad uncompressed size.
67
const float kMaxPlausibleCompressionRatio = 100.0;
68
69
// metadata for a TTC font entry
70
struct TtcFont {
71
  uint32_t flavor;
72
  uint32_t dst_offset;
73
  uint32_t header_checksum;
74
  std::vector<uint16_t> table_indices;
75
};
76
77
struct WOFF2Header {
78
  uint32_t flavor;
79
  uint32_t header_version;
80
  uint16_t num_tables;
81
  uint64_t compressed_offset;
82
  uint32_t compressed_length;
83
  uint32_t uncompressed_size;
84
  std::vector<Table> tables;  // num_tables unique tables
85
  std::vector<TtcFont> ttc_fonts;  // metadata to help rebuild font
86
};
87
88
/**
89
 * Accumulates data we may need to reconstruct a single font. One per font
90
 * created for a TTC.
91
 */
92
struct WOFF2FontInfo {
93
  uint16_t num_glyphs;
94
  uint16_t index_format;
95
  uint16_t num_hmetrics;
96
  std::vector<int16_t> x_mins;
97
  std::map<uint32_t, uint32_t> table_entry_by_tag;
98
};
99
100
// Accumulates metadata as we rebuild the font
101
struct RebuildMetadata {
102
  uint32_t header_checksum;  // set by WriteHeaders
103
  std::vector<WOFF2FontInfo> font_infos;
104
  // checksums for tables that have been written.
105
  // (tag, src_offset) => checksum. Need both because 0-length loca.
106
  std::map<std::pair<uint32_t, uint32_t>, uint32_t> checksums;
107
};
108
109
20.3M
int WithSign(int flag, int baseval) {
110
  // Precondition: 0 <= baseval < 65536 (to avoid integer overflow)
111
20.3M
  return (flag & 1) ? baseval : -baseval;
112
20.3M
}
113
114
26.6M
bool _SafeIntAddition(int a, int b, int* result) {
115
26.6M
  if (PREDICT_FALSE(
116
26.6M
          ((a > 0) && (b > std::numeric_limits<int>::max() - a)) ||
117
26.6M
          ((a < 0) && (b < std::numeric_limits<int>::min() - a)))) {
118
47
    return false;
119
47
  }
120
26.6M
  *result = a + b;
121
26.6M
  return true;
122
26.6M
}
123
124
bool TripletDecode(const uint8_t* flags_in, const uint8_t* in, size_t in_size,
125
92.2k
    unsigned int n_points, Point* result, size_t* in_bytes_consumed) {
126
92.2k
  int x = 0;
127
92.2k
  int y = 0;
128
129
92.2k
  if (PREDICT_FALSE(n_points > in_size)) {
130
18
    return FONT_COMPRESSION_FAILURE();
131
18
  }
132
92.2k
  unsigned int triplet_index = 0;
133
134
13.4M
  for (unsigned int i = 0; i < n_points; ++i) {
135
13.3M
    uint8_t flag = flags_in[i];
136
13.3M
    bool on_curve = !(flag >> 7);
137
13.3M
    flag &= 0x7f;
138
13.3M
    unsigned int n_data_bytes;
139
13.3M
    if (flag < 84) {
140
9.02M
      n_data_bytes = 1;
141
9.02M
    } else if (flag < 120) {
142
1.30M
      n_data_bytes = 2;
143
3.01M
    } else if (flag < 124) {
144
72.8k
      n_data_bytes = 3;
145
2.94M
    } else {
146
2.94M
      n_data_bytes = 4;
147
2.94M
    }
148
13.3M
    if (PREDICT_FALSE(triplet_index + n_data_bytes > in_size ||
149
13.3M
        triplet_index + n_data_bytes < triplet_index)) {
150
45
      return FONT_COMPRESSION_FAILURE();
151
45
    }
152
13.3M
    int dx, dy;
153
13.3M
    if (flag < 10) {
154
5.56M
      dx = 0;
155
5.56M
      dy = WithSign(flag, ((flag & 14) << 7) + in[triplet_index]);
156
7.77M
    } else if (flag < 20) {
157
811k
      dx = WithSign(flag, (((flag - 10) & 14) << 7) + in[triplet_index]);
158
811k
      dy = 0;
159
6.96M
    } else if (flag < 84) {
160
2.64M
      int b0 = flag - 20;
161
2.64M
      int b1 = in[triplet_index];
162
2.64M
      dx = WithSign(flag, 1 + (b0 & 0x30) + (b1 >> 4));
163
2.64M
      dy = WithSign(flag >> 1, 1 + ((b0 & 0x0c) << 2) + (b1 & 0x0f));
164
4.31M
    } else if (flag < 120) {
165
1.30M
      int b0 = flag - 84;
166
1.30M
      dx = WithSign(flag, 1 + ((b0 / 12) << 8) + in[triplet_index]);
167
1.30M
      dy = WithSign(flag >> 1,
168
1.30M
                    1 + (((b0 % 12) >> 2) << 8) + in[triplet_index + 1]);
169
3.01M
    } else if (flag < 124) {
170
72.7k
      int b2 = in[triplet_index + 1];
171
72.7k
      dx = WithSign(flag, (in[triplet_index] << 4) + (b2 >> 4));
172
72.7k
      dy = WithSign(flag >> 1, ((b2 & 0x0f) << 8) + in[triplet_index + 2]);
173
2.93M
    } else {
174
2.93M
      dx = WithSign(flag, (in[triplet_index] << 8) + in[triplet_index + 1]);
175
2.93M
      dy = WithSign(flag >> 1,
176
2.93M
          (in[triplet_index + 2] << 8) + in[triplet_index + 3]);
177
2.93M
    }
178
13.3M
    triplet_index += n_data_bytes;
179
13.3M
    if (!_SafeIntAddition(x, dx, &x)) {
180
23
      return false;
181
23
    }
182
13.3M
    if (!_SafeIntAddition(y, dy, &y)) {
183
24
      return false;
184
24
    }
185
13.3M
    *result++ = {x, y, on_curve};
186
13.3M
  }
187
92.1k
  *in_bytes_consumed = triplet_index;
188
92.1k
  return true;
189
92.2k
}
190
191
// This function stores just the point data. On entry, dst points to the
192
// beginning of a simple glyph. Returns true on success.
193
bool StorePoints(unsigned int n_points, const Point* points,
194
                 unsigned int n_contours, unsigned int instruction_length,
195
                 bool has_overlap_bit, uint8_t* dst, size_t dst_size,
196
92.0k
                 size_t* glyph_size) {
197
  // I believe that n_contours < 65536, in which case this is safe. However, a
198
  // comment and/or an assert would be good.
199
92.0k
  unsigned int flag_offset = kEndPtsOfContoursOffset + 2 * n_contours + 2 +
200
92.0k
    instruction_length;
201
92.0k
  int last_flag = -1;
202
92.0k
  int repeat_count = 0;
203
92.0k
  int last_x = 0;
204
92.0k
  int last_y = 0;
205
92.0k
  unsigned int x_bytes = 0;
206
92.0k
  unsigned int y_bytes = 0;
207
208
6.99M
  for (unsigned int i = 0; i < n_points; ++i) {
209
6.90M
    const Point& point = points[i];
210
6.90M
    int flag = point.on_curve ? kGlyfOnCurve : 0;
211
6.90M
    if (has_overlap_bit && i == 0) {
212
226
      flag |= kOverlapSimple;
213
226
    }
214
215
6.90M
    int dx = point.x - last_x;
216
6.90M
    int dy = point.y - last_y;
217
6.90M
    if (dx == 0) {
218
4.70M
      flag |= kGlyfThisXIsSame;
219
4.70M
    } else if (dx > -256 && dx < 256) {
220
1.66M
      flag |= kGlyfXShort | (dx > 0 ? kGlyfThisXIsSame : 0);
221
1.66M
      x_bytes += 1;
222
1.66M
    } else {
223
527k
      x_bytes += 2;
224
527k
    }
225
6.90M
    if (dy == 0) {
226
3.41M
      flag |= kGlyfThisYIsSame;
227
3.48M
    } else if (dy > -256 && dy < 256) {
228
2.25M
      flag |= kGlyfYShort | (dy > 0 ? kGlyfThisYIsSame : 0);
229
2.25M
      y_bytes += 1;
230
2.25M
    } else {
231
1.23M
      y_bytes += 2;
232
1.23M
    }
233
234
6.90M
    if (flag == last_flag && repeat_count != 255) {
235
2.98M
      dst[flag_offset - 1] |= kGlyfRepeat;
236
2.98M
      repeat_count++;
237
3.92M
    } else {
238
3.92M
      if (repeat_count != 0) {
239
611k
        if (PREDICT_FALSE(flag_offset >= dst_size)) {
240
0
          return FONT_COMPRESSION_FAILURE();
241
0
        }
242
611k
        dst[flag_offset++] = repeat_count;
243
611k
      }
244
3.92M
      if (PREDICT_FALSE(flag_offset >= dst_size)) {
245
0
        return FONT_COMPRESSION_FAILURE();
246
0
      }
247
3.92M
      dst[flag_offset++] = flag;
248
3.92M
      repeat_count = 0;
249
3.92M
    }
250
6.90M
    last_x = point.x;
251
6.90M
    last_y = point.y;
252
6.90M
    last_flag = flag;
253
6.90M
  }
254
255
92.0k
  if (repeat_count != 0) {
256
39.5k
    if (PREDICT_FALSE(flag_offset >= dst_size)) {
257
0
      return FONT_COMPRESSION_FAILURE();
258
0
    }
259
39.5k
    dst[flag_offset++] = repeat_count;
260
39.5k
  }
261
92.0k
  unsigned int xy_bytes = x_bytes + y_bytes;
262
92.0k
  if (PREDICT_FALSE(xy_bytes < x_bytes ||
263
92.0k
      flag_offset + xy_bytes < flag_offset ||
264
92.0k
      flag_offset + xy_bytes > dst_size)) {
265
0
    return FONT_COMPRESSION_FAILURE();
266
0
  }
267
268
92.0k
  int x_offset = flag_offset;
269
92.0k
  int y_offset = flag_offset + x_bytes;
270
92.0k
  last_x = 0;
271
92.0k
  last_y = 0;
272
6.99M
  for (unsigned int i = 0; i < n_points; ++i) {
273
6.90M
    int dx = points[i].x - last_x;
274
6.90M
    if (dx == 0) {
275
      // pass
276
4.70M
    } else if (dx > -256 && dx < 256) {
277
1.66M
      dst[x_offset++] = std::abs(dx);
278
1.66M
    } else {
279
      // will always fit for valid input, but overflow is harmless
280
527k
      x_offset = Store16(dst, x_offset, dx);
281
527k
    }
282
6.90M
    last_x += dx;
283
6.90M
    int dy = points[i].y - last_y;
284
6.90M
    if (dy == 0) {
285
      // pass
286
3.48M
    } else if (dy > -256 && dy < 256) {
287
2.25M
      dst[y_offset++] = std::abs(dy);
288
2.25M
    } else {
289
1.23M
      y_offset = Store16(dst, y_offset, dy);
290
1.23M
    }
291
6.90M
    last_y += dy;
292
6.90M
  }
293
92.0k
  *glyph_size = y_offset;
294
92.0k
  return true;
295
92.0k
}
296
297
// Compute the bounding box of the coordinates, and store into a glyf buffer.
298
// A precondition is that there are at least 10 bytes available.
299
// dst should point to the beginning of a 'glyf' record.
300
91.6k
void ComputeBbox(unsigned int n_points, const Point* points, uint8_t* dst) {
301
91.6k
  int x_min = 0;
302
91.6k
  int y_min = 0;
303
91.6k
  int x_max = 0;
304
91.6k
  int y_max = 0;
305
306
91.6k
  if (n_points > 0) {
307
88.9k
    x_min = points[0].x;
308
88.9k
    x_max = points[0].x;
309
88.9k
    y_min = points[0].y;
310
88.9k
    y_max = points[0].y;
311
88.9k
  }
312
7.89M
  for (unsigned int i = 1; i < n_points; ++i) {
313
7.80M
    int x = points[i].x;
314
7.80M
    int y = points[i].y;
315
7.80M
    x_min = std::min(x, x_min);
316
7.80M
    x_max = std::max(x, x_max);
317
7.80M
    y_min = std::min(y, y_min);
318
7.80M
    y_max = std::max(y, y_max);
319
7.80M
  }
320
91.6k
  size_t offset = 2;
321
91.6k
  offset = Store16(dst, offset, x_min);
322
91.6k
  offset = Store16(dst, offset, y_min);
323
91.6k
  offset = Store16(dst, offset, x_max);
324
91.6k
  offset = Store16(dst, offset, y_max);
325
91.6k
}
326
327
328
bool SizeOfComposite(Buffer composite_stream, size_t* size,
329
531
                     bool* have_instructions) {
330
531
  size_t start_offset = composite_stream.offset();
331
531
  bool we_have_instructions = false;
332
333
531
  uint16_t flags = FLAG_MORE_COMPONENTS;
334
5.30k
  while (flags & FLAG_MORE_COMPONENTS) {
335
4.78k
    if (PREDICT_FALSE(!composite_stream.ReadU16(&flags))) {
336
2
      return FONT_COMPRESSION_FAILURE();
337
2
    }
338
4.78k
    we_have_instructions |= (flags & FLAG_WE_HAVE_INSTRUCTIONS) != 0;
339
4.78k
    size_t arg_size = 2;  // glyph index
340
4.78k
    if (flags & FLAG_ARG_1_AND_2_ARE_WORDS) {
341
1.74k
      arg_size += 4;
342
3.04k
    } else {
343
3.04k
      arg_size += 2;
344
3.04k
    }
345
4.78k
    if (flags & FLAG_WE_HAVE_A_SCALE) {
346
1.48k
      arg_size += 2;
347
3.30k
    } else if (flags & FLAG_WE_HAVE_AN_X_AND_Y_SCALE) {
348
401
      arg_size += 4;
349
2.90k
    } else if (flags & FLAG_WE_HAVE_A_TWO_BY_TWO) {
350
441
      arg_size += 8;
351
441
    }
352
4.78k
    if (PREDICT_FALSE(!composite_stream.Skip(arg_size))) {
353
17
      return FONT_COMPRESSION_FAILURE();
354
17
    }
355
4.78k
  }
356
357
512
  *size = composite_stream.offset() - start_offset;
358
512
  *have_instructions = we_have_instructions;
359
360
512
  return true;
361
531
}
362
363
118k
bool Pad4(WOFF2Out* out) {
364
118k
  uint8_t zeroes[] = {0, 0, 0};
365
118k
  if (PREDICT_FALSE(out->Size() + 3 < out->Size())) {
366
0
    return FONT_COMPRESSION_FAILURE();
367
0
  }
368
118k
  uint32_t pad_bytes = Round4(out->Size()) - out->Size();
369
118k
  if (pad_bytes > 0) {
370
68.2k
    if (PREDICT_FALSE(!out->Write(&zeroes, pad_bytes))) {
371
0
      return FONT_COMPRESSION_FAILURE();
372
0
    }
373
68.2k
  }
374
118k
  return true;
375
118k
}
376
377
// Build TrueType loca table
378
bool StoreLoca(const std::vector<uint32_t>& loca_values, int index_format,
379
97
               uint32_t* checksum, WOFF2Out* out) {
380
  // TODO(user) figure out what index format to use based on whether max
381
  // offset fits into uint16_t or not
382
97
  const uint64_t loca_size = loca_values.size();
383
97
  const uint64_t offset_size = index_format ? 4 : 2;
384
97
  if (PREDICT_FALSE((loca_size << 2) >> 2 != loca_size)) {
385
0
    return FONT_COMPRESSION_FAILURE();
386
0
  }
387
97
  std::vector<uint8_t> loca_content(loca_size * offset_size);
388
97
  uint8_t* dst = &loca_content[0];
389
97
  size_t offset = 0;
390
81.5k
  for (size_t i = 0; i < loca_values.size(); ++i) {
391
81.4k
    uint32_t value = loca_values[i];
392
81.4k
    if (index_format) {
393
66.4k
      offset = StoreU32(dst, offset, value);
394
66.4k
    } else {
395
14.9k
      offset = Store16(dst, offset, value >> 1);
396
14.9k
    }
397
81.4k
  }
398
97
  *checksum = ComputeULongSum(&loca_content[0], loca_content.size());
399
97
  if (PREDICT_FALSE(!out->Write(&loca_content[0], loca_content.size()))) {
400
0
    return FONT_COMPRESSION_FAILURE();
401
0
  }
402
97
  return true;
403
97
}
404
405
// Reconstruct entire glyf table based on transformed original
406
bool ReconstructGlyf(const uint8_t* data, Table* glyf_table,
407
                     uint32_t* glyf_checksum, Table * loca_table,
408
                     uint32_t* loca_checksum, WOFF2FontInfo* info,
409
764
                     WOFF2Out* out) {
410
764
  static const int kNumSubStreams = 7;
411
764
  Buffer file(data, glyf_table->transform_length);
412
764
  uint16_t version;
413
764
  std::vector<std::pair<const uint8_t*, size_t> > substreams(kNumSubStreams);
414
764
  const size_t glyf_start = out->Size();
415
416
764
  if (PREDICT_FALSE(!file.ReadU16(&version))) {
417
12
    return FONT_COMPRESSION_FAILURE();
418
12
  }
419
420
752
  uint16_t flags;
421
752
  if (PREDICT_FALSE(!file.ReadU16(&flags))) {
422
4
    return FONT_COMPRESSION_FAILURE();
423
4
  }
424
748
  bool has_overlap_bitmap = (flags & FLAG_OVERLAP_SIMPLE_BITMAP);
425
426
748
  if (PREDICT_FALSE(!file.ReadU16(&info->num_glyphs) ||
427
748
      !file.ReadU16(&info->index_format))) {
428
35
    return FONT_COMPRESSION_FAILURE();
429
35
  }
430
431
  // https://dev.w3.org/webfonts/WOFF2/spec/#conform-mustRejectLoca
432
  // dst_length here is origLength in the spec
433
713
  uint32_t expected_loca_dst_length = (info->index_format ? 4 : 2)
434
713
    * (static_cast<uint32_t>(info->num_glyphs) + 1);
435
713
  if (PREDICT_FALSE(loca_table->dst_length != expected_loca_dst_length)) {
436
31
    return FONT_COMPRESSION_FAILURE();
437
31
  }
438
439
682
  unsigned int offset = (2 + kNumSubStreams) * 4;
440
682
  if (PREDICT_FALSE(offset > glyf_table->transform_length)) {
441
4
    return FONT_COMPRESSION_FAILURE();
442
4
  }
443
  // Invariant from here on: data_size >= offset
444
5.10k
  for (int i = 0; i < kNumSubStreams; ++i) {
445
4.47k
    uint32_t substream_size;
446
4.47k
    if (PREDICT_FALSE(!file.ReadU32(&substream_size))) {
447
0
      return FONT_COMPRESSION_FAILURE();
448
0
    }
449
4.47k
    if (PREDICT_FALSE(substream_size > glyf_table->transform_length - offset)) {
450
51
      return FONT_COMPRESSION_FAILURE();
451
51
    }
452
4.42k
    substreams[i] = std::make_pair(data + offset, substream_size);
453
4.42k
    offset += substream_size;
454
4.42k
  }
455
627
  Buffer n_contour_stream(substreams[0].first, substreams[0].second);
456
627
  Buffer n_points_stream(substreams[1].first, substreams[1].second);
457
627
  Buffer flag_stream(substreams[2].first, substreams[2].second);
458
627
  Buffer glyph_stream(substreams[3].first, substreams[3].second);
459
627
  Buffer composite_stream(substreams[4].first, substreams[4].second);
460
627
  Buffer bbox_stream(substreams[5].first, substreams[5].second);
461
627
  Buffer instruction_stream(substreams[6].first, substreams[6].second);
462
463
627
  const uint8_t* overlap_bitmap = nullptr;
464
627
  unsigned int overlap_bitmap_length = 0;
465
627
  if (has_overlap_bitmap) {
466
163
    overlap_bitmap_length = (info->num_glyphs + 7) >> 3;
467
163
    overlap_bitmap = data + offset;
468
163
    if (PREDICT_FALSE(overlap_bitmap_length >
469
163
                           glyf_table->transform_length - offset)) {
470
4
      return FONT_COMPRESSION_FAILURE();
471
4
    }
472
163
  }
473
474
623
  std::vector<uint32_t> loca_values(info->num_glyphs + 1);
475
623
  std::vector<unsigned int> n_points_vec;
476
623
  std::unique_ptr<Point[]> points;
477
623
  size_t points_size = 0;
478
623
  const uint8_t* bbox_bitmap = bbox_stream.buffer();
479
  // Safe because num_glyphs is bounded
480
623
  unsigned int bitmap_length = ((info->num_glyphs + 31) >> 5) << 2;
481
623
  if (!bbox_stream.Skip(bitmap_length)) {
482
10
    return FONT_COMPRESSION_FAILURE();
483
10
  }
484
485
  // Temp buffer for glyph's.
486
613
  size_t glyph_buf_size = kDefaultGlyphBuf;
487
613
  std::unique_ptr<uint8_t[]> glyph_buf(new uint8_t[glyph_buf_size]);
488
489
613
  info->x_mins.resize(info->num_glyphs);
490
104k
  for (unsigned int i = 0; i < info->num_glyphs; ++i) {
491
104k
    size_t glyph_size = 0;
492
104k
    uint16_t n_contours = 0;
493
104k
    bool have_bbox = false;
494
104k
    if (bbox_bitmap[i >> 3] & (0x80 >> (i & 7))) {
495
1.08k
      have_bbox = true;
496
1.08k
    }
497
104k
    if (PREDICT_FALSE(!n_contour_stream.ReadU16(&n_contours))) {
498
10
      return FONT_COMPRESSION_FAILURE();
499
10
    }
500
501
104k
    if (n_contours == 0xffff) {
502
      // composite glyph
503
552
      bool have_instructions = false;
504
552
      unsigned int instruction_size = 0;
505
552
      if (PREDICT_FALSE(!have_bbox)) {
506
        // composite glyphs must have an explicit bbox
507
21
        return FONT_COMPRESSION_FAILURE();
508
21
      }
509
510
531
      size_t composite_size;
511
531
      if (PREDICT_FALSE(!SizeOfComposite(composite_stream, &composite_size,
512
531
                                         &have_instructions))) {
513
19
        return FONT_COMPRESSION_FAILURE();
514
19
      }
515
512
      if (have_instructions) {
516
202
        if (PREDICT_FALSE(!Read255UShort(&glyph_stream, &instruction_size))) {
517
1
          return FONT_COMPRESSION_FAILURE();
518
1
        }
519
202
      }
520
521
511
      size_t size_needed = 12 + composite_size + instruction_size;
522
511
      if (PREDICT_FALSE(glyph_buf_size < size_needed)) {
523
8
        glyph_buf.reset(new uint8_t[size_needed]);
524
8
        glyph_buf_size = size_needed;
525
8
      }
526
527
511
      glyph_size = Store16(glyph_buf.get(), glyph_size, n_contours);
528
511
      if (PREDICT_FALSE(!bbox_stream.Read(glyph_buf.get() + glyph_size, 8))) {
529
6
        return FONT_COMPRESSION_FAILURE();
530
6
      }
531
505
      glyph_size += 8;
532
533
505
      if (PREDICT_FALSE(!composite_stream.Read(glyph_buf.get() + glyph_size,
534
505
            composite_size))) {
535
0
        return FONT_COMPRESSION_FAILURE();
536
0
      }
537
505
      glyph_size += composite_size;
538
505
      if (have_instructions) {
539
197
        glyph_size = Store16(glyph_buf.get(), glyph_size, instruction_size);
540
197
        if (PREDICT_FALSE(!instruction_stream.Read(glyph_buf.get() + glyph_size,
541
197
              instruction_size))) {
542
23
          return FONT_COMPRESSION_FAILURE();
543
23
        }
544
174
        glyph_size += instruction_size;
545
174
      }
546
104k
    } else if (n_contours > 0) {
547
      // simple glyph
548
92.4k
      n_points_vec.clear();
549
92.4k
      unsigned int total_n_points = 0;
550
92.4k
      unsigned int n_points_contour;
551
609k
      for (unsigned int j = 0; j < n_contours; ++j) {
552
517k
        if (PREDICT_FALSE(
553
517k
            !Read255UShort(&n_points_stream, &n_points_contour))) {
554
117
          return FONT_COMPRESSION_FAILURE();
555
117
        }
556
517k
        n_points_vec.push_back(n_points_contour);
557
517k
        if (PREDICT_FALSE(total_n_points + n_points_contour < total_n_points)) {
558
0
          return FONT_COMPRESSION_FAILURE();
559
0
        }
560
517k
        total_n_points += n_points_contour;
561
517k
      }
562
92.3k
      unsigned int flag_size = total_n_points;
563
92.3k
      if (PREDICT_FALSE(
564
92.3k
          flag_size > flag_stream.length() - flag_stream.offset())) {
565
67
        return FONT_COMPRESSION_FAILURE();
566
67
      }
567
92.2k
      const uint8_t* flags_buf = flag_stream.buffer() + flag_stream.offset();
568
92.2k
      const uint8_t* triplet_buf = glyph_stream.buffer() +
569
92.2k
        glyph_stream.offset();
570
92.2k
      size_t triplet_size = glyph_stream.length() - glyph_stream.offset();
571
92.2k
      size_t triplet_bytes_consumed = 0;
572
92.2k
      if (points_size < total_n_points) {
573
1.35k
        points_size = total_n_points;
574
1.35k
        points.reset(new Point[points_size]);
575
1.35k
      }
576
92.2k
      if (PREDICT_FALSE(!TripletDecode(flags_buf, triplet_buf, triplet_size,
577
92.2k
          total_n_points, points.get(), &triplet_bytes_consumed))) {
578
110
        return FONT_COMPRESSION_FAILURE();
579
110
      }
580
92.1k
      if (PREDICT_FALSE(!flag_stream.Skip(flag_size))) {
581
0
        return FONT_COMPRESSION_FAILURE();
582
0
      }
583
92.1k
      if (PREDICT_FALSE(!glyph_stream.Skip(triplet_bytes_consumed))) {
584
0
        return FONT_COMPRESSION_FAILURE();
585
0
      }
586
92.1k
      unsigned int instruction_size;
587
92.1k
      if (PREDICT_FALSE(!Read255UShort(&glyph_stream, &instruction_size))) {
588
17
        return FONT_COMPRESSION_FAILURE();
589
17
      }
590
591
92.1k
      if (PREDICT_FALSE(total_n_points >= (1 << 27)
592
92.1k
                        || instruction_size >= (1 << 30))) {
593
0
        return FONT_COMPRESSION_FAILURE();
594
0
      }
595
92.1k
      size_t size_needed = 12 + 2 * n_contours + 5 * total_n_points
596
92.1k
                           + instruction_size;
597
92.1k
      if (PREDICT_FALSE(glyph_buf_size < size_needed)) {
598
188
        glyph_buf.reset(new uint8_t[size_needed]);
599
188
        glyph_buf_size = size_needed;
600
188
      }
601
602
92.1k
      glyph_size = Store16(glyph_buf.get(), glyph_size, n_contours);
603
92.1k
      if (have_bbox) {
604
476
        if (PREDICT_FALSE(!bbox_stream.Read(glyph_buf.get() + glyph_size, 8))) {
605
28
          return FONT_COMPRESSION_FAILURE();
606
28
        }
607
91.6k
      } else {
608
91.6k
        ComputeBbox(total_n_points, points.get(), glyph_buf.get());
609
91.6k
      }
610
92.0k
      glyph_size = kEndPtsOfContoursOffset;
611
92.0k
      int end_point = -1;
612
351k
      for (unsigned int contour_ix = 0; contour_ix < n_contours; ++contour_ix) {
613
259k
        end_point += n_points_vec[contour_ix];
614
259k
        if (PREDICT_FALSE(end_point >= 65536)) {
615
6
          return FONT_COMPRESSION_FAILURE();
616
6
        }
617
259k
        glyph_size = Store16(glyph_buf.get(), glyph_size, end_point);
618
259k
      }
619
620
92.0k
      glyph_size = Store16(glyph_buf.get(), glyph_size, instruction_size);
621
92.0k
      if (PREDICT_FALSE(!instruction_stream.Read(glyph_buf.get() + glyph_size,
622
92.0k
                                                 instruction_size))) {
623
76
        return FONT_COMPRESSION_FAILURE();
624
76
      }
625
92.0k
      glyph_size += instruction_size;
626
627
92.0k
      bool has_overlap_bit =
628
92.0k
          has_overlap_bitmap && overlap_bitmap[i >> 3] & (0x80 >> (i & 7));
629
630
92.0k
      if (PREDICT_FALSE(!StorePoints(
631
92.0k
              total_n_points, points.get(), n_contours, instruction_size,
632
92.0k
              has_overlap_bit, glyph_buf.get(), glyph_buf_size, &glyph_size))) {
633
0
        return FONT_COMPRESSION_FAILURE();
634
0
      }
635
92.0k
    } else {
636
      // n_contours == 0; empty glyph. Must NOT have a bbox.
637
11.9k
      if (PREDICT_FALSE(have_bbox)) {
638
#ifdef FONT_COMPRESSION_BIN
639
        fprintf(stderr, "Empty glyph has a bbox\n");
640
#endif
641
15
        return FONT_COMPRESSION_FAILURE();
642
15
      }
643
11.9k
    }
644
645
104k
    loca_values[i] = out->Size() - glyf_start;
646
104k
    if (PREDICT_FALSE(!out->Write(glyph_buf.get(), glyph_size))) {
647
0
      return FONT_COMPRESSION_FAILURE();
648
0
    }
649
650
    // TODO(user) Old code aligned glyphs ... but do we actually need to?
651
104k
    if (PREDICT_FALSE(!Pad4(out))) {
652
0
      return FONT_COMPRESSION_FAILURE();
653
0
    }
654
655
104k
    *glyf_checksum += ComputeULongSum(glyph_buf.get(), glyph_size);
656
657
    // We may need x_min to reconstruct 'hmtx'
658
104k
    if (n_contours > 0) {
659
92.4k
      Buffer x_min_buf(glyph_buf.get() + 2, 2);
660
92.4k
      if (PREDICT_FALSE(!x_min_buf.ReadS16(&info->x_mins[i]))) {
661
0
        return FONT_COMPRESSION_FAILURE();
662
0
      }
663
92.4k
    }
664
104k
  }
665
666
  // glyf_table dst_offset was set by ReconstructFont
667
97
  glyf_table->dst_length = out->Size() - glyf_table->dst_offset;
668
97
  loca_table->dst_offset = out->Size();
669
  // loca[n] will be equal the length of the glyph data ('glyf') table
670
97
  loca_values[info->num_glyphs] = glyf_table->dst_length;
671
97
  if (PREDICT_FALSE(!StoreLoca(loca_values, info->index_format, loca_checksum,
672
97
      out))) {
673
0
    return FONT_COMPRESSION_FAILURE();
674
0
  }
675
97
  loca_table->dst_length = out->Size() - loca_table->dst_offset;
676
677
97
  return true;
678
97
}
679
680
5.81k
Table* FindTable(std::vector<Table*>* tables, uint32_t tag) {
681
43.6k
  for (Table* table : *tables) {
682
43.6k
    if (table->tag == tag) {
683
2.58k
      return table;
684
2.58k
    }
685
43.6k
  }
686
3.22k
  return NULL;
687
5.81k
}
688
689
// Get numberOfHMetrics, https://www.microsoft.com/typography/otspec/hhea.htm
690
bool ReadNumHMetrics(const uint8_t* data, size_t data_size,
691
856
                     uint16_t* num_hmetrics) {
692
  // Skip 34 to reach 'hhea' numberOfHMetrics
693
856
  Buffer buffer(data, data_size);
694
856
  if (PREDICT_FALSE(!buffer.Skip(34) || !buffer.ReadU16(num_hmetrics))) {
695
20
    return FONT_COMPRESSION_FAILURE();
696
20
  }
697
836
  return true;
698
856
}
699
700
// http://dev.w3.org/webfonts/WOFF2/spec/Overview.html#hmtx_table_format
701
bool ReconstructTransformedHmtx(const uint8_t* transformed_buf,
702
                                size_t transformed_size,
703
                                uint16_t num_glyphs,
704
                                uint16_t num_hmetrics,
705
                                const std::vector<int16_t>& x_mins,
706
                                uint32_t* checksum,
707
90
                                WOFF2Out* out) {
708
90
  Buffer hmtx_buff_in(transformed_buf, transformed_size);
709
710
90
  uint8_t hmtx_flags;
711
90
  if (PREDICT_FALSE(!hmtx_buff_in.ReadU8(&hmtx_flags))) {
712
2
    return FONT_COMPRESSION_FAILURE();
713
2
  }
714
715
88
  std::vector<uint16_t> advance_widths;
716
88
  std::vector<int16_t> lsbs;
717
88
  bool has_proportional_lsbs = (hmtx_flags & 1) == 0;
718
88
  bool has_monospace_lsbs = (hmtx_flags & 2) == 0;
719
720
  // Bits 2-7 are reserved and MUST be zero.
721
88
  if ((hmtx_flags & 0xFC) != 0) {
722
#ifdef FONT_COMPRESSION_BIN
723
    fprintf(stderr, "Illegal hmtx flags; bits 2-7 must be 0\n");
724
#endif
725
15
    return FONT_COMPRESSION_FAILURE();
726
15
  }
727
728
  // you say you transformed but there is little evidence of it
729
73
  if (has_proportional_lsbs && has_monospace_lsbs) {
730
10
    return FONT_COMPRESSION_FAILURE();
731
10
  }
732
733
73
  assert(x_mins.size() == num_glyphs);
734
735
  // num_glyphs 0 is OK if there is no 'glyf' but cannot then xform 'hmtx'.
736
63
  if (PREDICT_FALSE(num_hmetrics > num_glyphs)) {
737
22
    return FONT_COMPRESSION_FAILURE();
738
22
  }
739
740
  // https://www.microsoft.com/typography/otspec/hmtx.htm
741
  // "...only one entry need be in the array, but that entry is required."
742
41
  if (PREDICT_FALSE(num_hmetrics < 1)) {
743
3
    return FONT_COMPRESSION_FAILURE();
744
3
  }
745
746
259
  for (uint16_t i = 0; i < num_hmetrics; i++) {
747
222
    uint16_t advance_width;
748
222
    if (PREDICT_FALSE(!hmtx_buff_in.ReadU16(&advance_width))) {
749
1
      return FONT_COMPRESSION_FAILURE();
750
1
    }
751
221
    advance_widths.push_back(advance_width);
752
221
  }
753
754
252
  for (uint16_t i = 0; i < num_hmetrics; i++) {
755
216
    int16_t lsb;
756
216
    if (has_proportional_lsbs) {
757
54
      if (PREDICT_FALSE(!hmtx_buff_in.ReadS16(&lsb))) {
758
1
        return FONT_COMPRESSION_FAILURE();
759
1
      }
760
162
    } else {
761
162
      lsb = x_mins[i];
762
162
    }
763
215
    lsbs.push_back(lsb);
764
215
  }
765
766
173
  for (uint16_t i = num_hmetrics; i < num_glyphs; i++) {
767
138
    int16_t lsb;
768
138
    if (has_monospace_lsbs) {
769
62
      if (PREDICT_FALSE(!hmtx_buff_in.ReadS16(&lsb))) {
770
1
        return FONT_COMPRESSION_FAILURE();
771
1
      }
772
76
    } else {
773
76
      lsb = x_mins[i];
774
76
    }
775
137
    lsbs.push_back(lsb);
776
137
  }
777
778
  // bake me a shiny new hmtx table
779
35
  uint32_t hmtx_output_size = 2 * num_glyphs + 2 * num_hmetrics;
780
35
  std::vector<uint8_t> hmtx_table(hmtx_output_size);
781
35
  uint8_t* dst = &hmtx_table[0];
782
35
  size_t dst_offset = 0;
783
382
  for (uint32_t i = 0; i < num_glyphs; i++) {
784
347
    if (i < num_hmetrics) {
785
212
      Store16(advance_widths[i], &dst_offset, dst);
786
212
    }
787
347
    Store16(lsbs[i], &dst_offset, dst);
788
347
  }
789
790
35
  *checksum = ComputeULongSum(&hmtx_table[0], hmtx_output_size);
791
35
  if (PREDICT_FALSE(!out->Write(&hmtx_table[0], hmtx_output_size))) {
792
0
    return FONT_COMPRESSION_FAILURE();
793
0
  }
794
795
35
  return true;
796
35
}
797
798
bool Woff2Uncompress(uint8_t* dst_buf, size_t dst_size,
799
6.55k
  const uint8_t* src_buf, size_t src_size) {
800
6.55k
  size_t uncompressed_size = dst_size;
801
6.55k
  BrotliDecoderResult result = BrotliDecoderDecompress(
802
6.55k
      src_size, src_buf, &uncompressed_size, dst_buf);
803
6.55k
  if (PREDICT_FALSE(result != BROTLI_DECODER_RESULT_SUCCESS ||
804
6.55k
                    uncompressed_size != dst_size)) {
805
5.21k
    return FONT_COMPRESSION_FAILURE();
806
5.21k
  }
807
1.34k
  return true;
808
6.55k
}
809
810
bool ReadTableDirectory(Buffer* file, std::vector<Table>* tables,
811
7.96k
    size_t num_tables) {
812
7.96k
  uint32_t src_offset = 0;
813
2.21M
  for (size_t i = 0; i < num_tables; ++i) {
814
2.20M
    Table* table = &(*tables)[i];
815
2.20M
    uint8_t flag_byte;
816
2.20M
    if (PREDICT_FALSE(!file->ReadU8(&flag_byte))) {
817
77
      return FONT_COMPRESSION_FAILURE();
818
77
    }
819
2.20M
    uint32_t tag;
820
2.20M
    if ((flag_byte & 0x3f) == 0x3f) {
821
21.6k
      if (PREDICT_FALSE(!file->ReadU32(&tag))) {
822
10
        return FONT_COMPRESSION_FAILURE();
823
10
      }
824
2.18M
    } else {
825
2.18M
      tag = kKnownTags[flag_byte & 0x3f];
826
2.18M
    }
827
2.20M
    uint32_t flags = 0;
828
2.20M
    uint8_t xform_version = (flag_byte >> 6) & 0x03;
829
830
    // 0 means xform for glyph/loca, non-0 for others
831
2.20M
    if (tag == kGlyfTableTag || tag == kLocaTableTag) {
832
25.1k
      if (xform_version == 0) {
833
7.86k
        flags |= kWoff2FlagsTransform;
834
7.86k
      }
835
2.18M
    } else if (xform_version != 0) {
836
144k
      flags |= kWoff2FlagsTransform;
837
144k
    }
838
2.20M
    flags |= xform_version;
839
840
2.20M
    uint32_t dst_length;
841
2.20M
    if (PREDICT_FALSE(!ReadBase128(file, &dst_length))) {
842
85
      return FONT_COMPRESSION_FAILURE();
843
85
    }
844
2.20M
    uint32_t transform_length = dst_length;
845
2.20M
    if ((flags & kWoff2FlagsTransform) != 0) {
846
152k
      if (PREDICT_FALSE(!ReadBase128(file, &transform_length))) {
847
18
        return FONT_COMPRESSION_FAILURE();
848
18
      }
849
152k
      if (PREDICT_FALSE(tag == kLocaTableTag && transform_length)) {
850
60
        return FONT_COMPRESSION_FAILURE();
851
60
      }
852
152k
    }
853
2.20M
    if (PREDICT_FALSE(src_offset + transform_length < src_offset)) {
854
2
      return FONT_COMPRESSION_FAILURE();
855
2
    }
856
2.20M
    table->src_offset = src_offset;
857
2.20M
    table->src_length = transform_length;
858
2.20M
    src_offset += transform_length;
859
860
2.20M
    table->tag = tag;
861
2.20M
    table->flags = flags;
862
2.20M
    table->transform_length = transform_length;
863
2.20M
    table->dst_length = dst_length;
864
2.20M
  }
865
7.71k
  return true;
866
7.96k
}
867
868
// Writes a single Offset Table entry
869
size_t StoreOffsetTable(uint8_t* result, size_t offset, uint32_t flavor,
870
10.7k
                        uint16_t num_tables) {
871
10.7k
  offset = StoreU32(result, offset, flavor);  // sfnt version
872
10.7k
  offset = Store16(result, offset, num_tables);  // num_tables
873
10.7k
  unsigned max_pow2 = 0;
874
39.6k
  while (1u << (max_pow2 + 1) <= num_tables) {
875
28.9k
    max_pow2++;
876
28.9k
  }
877
10.7k
  const uint16_t output_search_range = (1u << max_pow2) << 4;
878
10.7k
  offset = Store16(result, offset, output_search_range);  // searchRange
879
10.7k
  offset = Store16(result, offset, max_pow2);  // entrySelector
880
  // rangeShift
881
10.7k
  offset = Store16(result, offset, (num_tables << 4) - output_search_range);
882
10.7k
  return offset;
883
10.7k
}
884
885
1.40M
size_t StoreTableEntry(uint8_t* result, uint32_t offset, uint32_t tag) {
886
1.40M
  offset = StoreU32(result, offset, tag);
887
1.40M
  offset = StoreU32(result, offset, 0);
888
1.40M
  offset = StoreU32(result, offset, 0);
889
1.40M
  offset = StoreU32(result, offset, 0);
890
1.40M
  return offset;
891
1.40M
}
892
893
// First table goes after all the headers, table directory, etc
894
14.4k
uint64_t ComputeOffsetToFirstTable(const WOFF2Header& hdr) {
895
14.4k
  uint64_t offset = kSfntHeaderSize +
896
14.4k
    kSfntEntrySize * static_cast<uint64_t>(hdr.num_tables);
897
14.4k
  if (hdr.header_version) {
898
511
    offset = CollectionHeaderSize(hdr.header_version, hdr.ttc_fonts.size())
899
511
      + kSfntHeaderSize * hdr.ttc_fonts.size();
900
9.03k
    for (const auto& ttc_font : hdr.ttc_fonts) {
901
9.03k
      offset += kSfntEntrySize * ttc_font.table_indices.size();
902
9.03k
    }
903
511
  }
904
14.4k
  return offset;
905
14.4k
}
906
907
2.01k
std::vector<Table*> Tables(WOFF2Header* hdr, size_t font_index) {
908
2.01k
  std::vector<Table*> tables;
909
2.01k
  if (PREDICT_FALSE(hdr->header_version)) {
910
5.14k
    for (auto index : hdr->ttc_fonts[font_index].table_indices) {
911
5.14k
      tables.push_back(&hdr->tables[index]);
912
5.14k
    }
913
1.25k
  } else {
914
15.3k
    for (auto& table : hdr->tables) {
915
15.3k
      tables.push_back(&table);
916
15.3k
    }
917
1.25k
  }
918
2.01k
  return tables;
919
2.01k
}
920
921
// Offset tables assumed to have been written in with 0's initially.
922
// WOFF2Header isn't const so we can use [] instead of at() (which upsets FF)
923
bool ReconstructFont(uint8_t* transformed_buf,
924
                     const uint32_t transformed_buf_size,
925
                     RebuildMetadata* metadata,
926
                     WOFF2Header* hdr,
927
                     size_t font_index,
928
2.01k
                     WOFF2Out* out) {
929
2.01k
  size_t dest_offset = out->Size();
930
2.01k
  uint8_t table_entry[12];
931
2.01k
  WOFF2FontInfo* info = &metadata->font_infos[font_index];
932
2.01k
  std::vector<Table*> tables = Tables(hdr, font_index);
933
934
  // 'glyf' without 'loca' doesn't make sense
935
2.01k
  const Table* glyf_table = FindTable(&tables, kGlyfTableTag);
936
2.01k
  const Table* loca_table = FindTable(&tables, kLocaTableTag);
937
2.01k
  if (PREDICT_FALSE(static_cast<bool>(glyf_table) !=
938
2.01k
                    static_cast<bool>(loca_table))) {
939
#ifdef FONT_COMPRESSION_BIN
940
      fprintf(stderr, "Cannot have just one of glyf/loca\n");
941
#endif
942
5
    return FONT_COMPRESSION_FAILURE();
943
5
  }
944
945
2.01k
  if (glyf_table != NULL) {
946
790
    if (PREDICT_FALSE((glyf_table->flags & kWoff2FlagsTransform)
947
790
                      != (loca_table->flags & kWoff2FlagsTransform))) {
948
#ifdef FONT_COMPRESSION_BIN
949
      fprintf(stderr, "Cannot transform just one of glyf/loca\n");
950
#endif
951
1
      return FONT_COMPRESSION_FAILURE();
952
1
    }
953
790
  }
954
955
2.00k
  uint32_t font_checksum = metadata->header_checksum;
956
2.00k
  if (hdr->header_version) {
957
764
    font_checksum = hdr->ttc_fonts[font_index].header_checksum;
958
764
  }
959
960
2.00k
  uint32_t loca_checksum = 0;
961
16.2k
  for (size_t i = 0; i < tables.size(); i++) {
962
15.2k
    Table& table = *tables[i];
963
964
15.2k
    std::pair<uint32_t, uint32_t> checksum_key = {table.tag, table.src_offset};
965
15.2k
    bool reused = metadata->checksums.find(checksum_key)
966
15.2k
               != metadata->checksums.end();
967
15.2k
    if (PREDICT_FALSE(font_index == 0 && reused)) {
968
34
      return FONT_COMPRESSION_FAILURE();
969
34
    }
970
971
    // TODO(user) a collection with optimized hmtx that reused glyf/loca
972
    // would fail. We don't optimize hmtx for collections yet.
973
15.1k
    if (PREDICT_FALSE(static_cast<uint64_t>(table.src_offset) + table.src_length
974
15.1k
        > transformed_buf_size)) {
975
0
      return FONT_COMPRESSION_FAILURE();
976
0
    }
977
978
15.1k
    if (table.tag == kHheaTableTag) {
979
856
      if (!ReadNumHMetrics(transformed_buf + table.src_offset,
980
856
          table.src_length, &info->num_hmetrics)) {
981
20
        return FONT_COMPRESSION_FAILURE();
982
20
      }
983
856
    }
984
985
15.1k
    uint32_t checksum = 0;
986
15.1k
    if (!reused) {
987
10.8k
      if ((table.flags & kWoff2FlagsTransform) != kWoff2FlagsTransform) {
988
9.70k
        if (table.tag == kHeadTableTag) {
989
336
          if (PREDICT_FALSE(table.src_length < 12)) {
990
8
            return FONT_COMPRESSION_FAILURE();
991
8
          }
992
          // checkSumAdjustment = 0
993
328
          StoreU32(transformed_buf + table.src_offset, 8, 0);
994
328
        }
995
9.69k
        table.dst_offset = dest_offset;
996
9.69k
        checksum = ComputeULongSum(transformed_buf + table.src_offset,
997
9.69k
                                   table.src_length);
998
9.69k
        if (PREDICT_FALSE(!out->Write(transformed_buf + table.src_offset,
999
9.69k
            table.src_length))) {
1000
0
          return FONT_COMPRESSION_FAILURE();
1001
0
        }
1002
9.69k
      } else {
1003
1.13k
        if (table.tag == kGlyfTableTag) {
1004
764
          table.dst_offset = dest_offset;
1005
1006
764
          Table* loca_table = FindTable(&tables, kLocaTableTag);
1007
764
          if (PREDICT_FALSE(!ReconstructGlyf(transformed_buf + table.src_offset,
1008
764
              &table, &checksum, loca_table, &loca_checksum, info, out))) {
1009
667
            return FONT_COMPRESSION_FAILURE();
1010
667
          }
1011
764
        } else if (table.tag == kLocaTableTag) {
1012
          // All the work was done by ReconstructGlyf. We already know checksum.
1013
102
          checksum = loca_checksum;
1014
268
        } else if (table.tag == kHmtxTableTag) {
1015
90
          table.dst_offset = dest_offset;
1016
          // Tables are sorted so all the info we need has been gathered.
1017
90
          if (PREDICT_FALSE(!ReconstructTransformedHmtx(
1018
90
              transformed_buf + table.src_offset, table.src_length,
1019
90
              info->num_glyphs, info->num_hmetrics, info->x_mins, &checksum,
1020
90
              out))) {
1021
55
            return FONT_COMPRESSION_FAILURE();
1022
55
          }
1023
178
        } else {
1024
178
          return FONT_COMPRESSION_FAILURE();  // transform unknown
1025
178
        }
1026
1.13k
      }
1027
9.92k
      metadata->checksums[checksum_key] = checksum;
1028
9.92k
    } else {
1029
4.33k
      checksum = metadata->checksums[checksum_key];
1030
4.33k
    }
1031
14.2k
    font_checksum += checksum;
1032
1033
    // update the table entry with real values.
1034
14.2k
    StoreU32(table_entry, 0, checksum);
1035
14.2k
    StoreU32(table_entry, 4, table.dst_offset);
1036
14.2k
    StoreU32(table_entry, 8, table.dst_length);
1037
14.2k
    if (PREDICT_FALSE(!out->Write(table_entry,
1038
14.2k
        info->table_entry_by_tag[table.tag] + 4, 12))) {
1039
0
      return FONT_COMPRESSION_FAILURE();
1040
0
    }
1041
1042
    // We replaced 0's. Update overall checksum.
1043
14.2k
    font_checksum += ComputeULongSum(table_entry, 12);
1044
1045
14.2k
    if (PREDICT_FALSE(!Pad4(out))) {
1046
0
      return FONT_COMPRESSION_FAILURE();
1047
0
    }
1048
1049
14.2k
    if (PREDICT_FALSE(static_cast<uint64_t>(table.dst_offset + table.dst_length)
1050
14.2k
        > out->Size())) {
1051
26
      return FONT_COMPRESSION_FAILURE();
1052
26
    }
1053
14.2k
    dest_offset = out->Size();
1054
14.2k
  }
1055
1056
  // Update 'head' checkSumAdjustment. We already set it to 0 and summed font.
1057
1.02k
  Table* head_table = FindTable(&tables, kHeadTableTag);
1058
1.02k
  if (head_table) {
1059
239
    if (PREDICT_FALSE(head_table->dst_length < 12)) {
1060
1
      return FONT_COMPRESSION_FAILURE();
1061
1
    }
1062
238
    uint8_t checksum_adjustment[4];
1063
238
    StoreU32(checksum_adjustment, 0, 0xB1B0AFBA - font_checksum);
1064
238
    if (PREDICT_FALSE(!out->Write(checksum_adjustment,
1065
238
                                  head_table->dst_offset + 8, 4))) {
1066
0
      return FONT_COMPRESSION_FAILURE();
1067
0
    }
1068
238
  }
1069
1070
1.02k
  return true;
1071
1.02k
}
1072
1073
8.32k
bool ReadWOFF2Header(const uint8_t* data, size_t length, WOFF2Header* hdr) {
1074
8.32k
  Buffer file(data, length);
1075
1076
8.32k
  uint32_t signature;
1077
8.32k
  if (PREDICT_FALSE(!file.ReadU32(&signature) || signature != kWoff2Signature ||
1078
8.32k
      !file.ReadU32(&hdr->flavor))) {
1079
62
    return FONT_COMPRESSION_FAILURE();
1080
62
  }
1081
1082
  // TODO(user): Should call IsValidVersionTag() here.
1083
1084
8.26k
  uint32_t reported_length;
1085
8.26k
  if (PREDICT_FALSE(
1086
8.26k
      !file.ReadU32(&reported_length) || length != reported_length)) {
1087
69
    return FONT_COMPRESSION_FAILURE();
1088
69
  }
1089
8.19k
  if (PREDICT_FALSE(!file.ReadU16(&hdr->num_tables) || !hdr->num_tables)) {
1090
3
    return FONT_COMPRESSION_FAILURE();
1091
3
  }
1092
1093
  // We don't care about these fields of the header:
1094
  //   uint16_t reserved
1095
  //   uint32_t total_sfnt_size, we don't believe this, will compute later
1096
8.19k
  if (PREDICT_FALSE(!file.Skip(6))) {
1097
21
    return FONT_COMPRESSION_FAILURE();
1098
21
  }
1099
8.17k
  if (PREDICT_FALSE(!file.ReadU32(&hdr->compressed_length))) {
1100
4
    return FONT_COMPRESSION_FAILURE();
1101
4
  }
1102
  // We don't care about these fields of the header:
1103
  //   uint16_t major_version, minor_version
1104
8.16k
  if (PREDICT_FALSE(!file.Skip(2 * 2))) {
1105
3
    return FONT_COMPRESSION_FAILURE();
1106
3
  }
1107
8.16k
  uint32_t meta_offset;
1108
8.16k
  uint32_t meta_length;
1109
8.16k
  uint32_t meta_length_orig;
1110
8.16k
  if (PREDICT_FALSE(!file.ReadU32(&meta_offset) ||
1111
8.16k
      !file.ReadU32(&meta_length) ||
1112
8.16k
      !file.ReadU32(&meta_length_orig))) {
1113
9
    return FONT_COMPRESSION_FAILURE();
1114
9
  }
1115
8.15k
  if (meta_offset) {
1116
283
    if (PREDICT_FALSE(
1117
283
        meta_offset >= length || length - meta_offset < meta_length)) {
1118
90
      return FONT_COMPRESSION_FAILURE();
1119
90
    }
1120
283
  }
1121
8.06k
  uint32_t priv_offset;
1122
8.06k
  uint32_t priv_length;
1123
8.06k
  if (PREDICT_FALSE(!file.ReadU32(&priv_offset) ||
1124
8.06k
      !file.ReadU32(&priv_length))) {
1125
12
    return FONT_COMPRESSION_FAILURE();
1126
12
  }
1127
8.05k
  if (priv_offset) {
1128
300
    if (PREDICT_FALSE(
1129
300
        priv_offset >= length || length - priv_offset < priv_length)) {
1130
90
      return FONT_COMPRESSION_FAILURE();
1131
90
    }
1132
300
  }
1133
7.96k
  hdr->tables.resize(hdr->num_tables);
1134
7.96k
  if (PREDICT_FALSE(!ReadTableDirectory(
1135
7.96k
          &file, &hdr->tables, hdr->num_tables))) {
1136
252
    return FONT_COMPRESSION_FAILURE();
1137
252
  }
1138
1139
  // Before we sort for output the last table end is the uncompressed size.
1140
7.71k
  Table& last_table = hdr->tables.back();
1141
7.71k
  hdr->uncompressed_size = last_table.src_offset + last_table.src_length;
1142
7.71k
  if (PREDICT_FALSE(hdr->uncompressed_size < last_table.src_offset)) {
1143
0
    return FONT_COMPRESSION_FAILURE();
1144
0
  }
1145
1146
7.71k
  hdr->header_version = 0;
1147
1148
7.71k
  if (hdr->flavor == kTtcFontFlavor) {
1149
615
    if (PREDICT_FALSE(!file.ReadU32(&hdr->header_version))) {
1150
13
      return FONT_COMPRESSION_FAILURE();
1151
13
    }
1152
602
    if (PREDICT_FALSE(hdr->header_version != 0x00010000
1153
602
                   && hdr->header_version != 0x00020000)) {
1154
86
      return FONT_COMPRESSION_FAILURE();
1155
86
    }
1156
516
    uint32_t num_fonts;
1157
516
    if (PREDICT_FALSE(!Read255UShort(&file, &num_fonts) || !num_fonts)) {
1158
6
      return FONT_COMPRESSION_FAILURE();
1159
6
    }
1160
510
    hdr->ttc_fonts.resize(num_fonts);
1161
1162
6.77k
    for (uint32_t i = 0; i < num_fonts; i++) {
1163
6.51k
      TtcFont& ttc_font = hdr->ttc_fonts[i];
1164
6.51k
      uint32_t num_tables;
1165
6.51k
      if (PREDICT_FALSE(!Read255UShort(&file, &num_tables) || !num_tables)) {
1166
62
        return FONT_COMPRESSION_FAILURE();
1167
62
      }
1168
6.45k
      if (PREDICT_FALSE(!file.ReadU32(&ttc_font.flavor))) {
1169
25
        return FONT_COMPRESSION_FAILURE();
1170
25
      }
1171
1172
6.42k
      ttc_font.table_indices.resize(num_tables);
1173
1174
1175
6.42k
      unsigned int glyf_idx = 0;
1176
6.42k
      unsigned int loca_idx = 0;
1177
1178
160k
      for (uint32_t j = 0; j < num_tables; j++) {
1179
154k
        unsigned int table_idx;
1180
154k
        if (PREDICT_FALSE(!Read255UShort(&file, &table_idx)) ||
1181
154k
            table_idx >= hdr->tables.size()) {
1182
147
          return FONT_COMPRESSION_FAILURE();
1183
147
        }
1184
154k
        ttc_font.table_indices[j] = table_idx;
1185
1186
154k
        const Table& table = hdr->tables[table_idx];
1187
154k
        if (table.tag == kLocaTableTag) {
1188
670
          loca_idx = table_idx;
1189
670
        }
1190
154k
        if (table.tag == kGlyfTableTag) {
1191
392
          glyf_idx = table_idx;
1192
392
        }
1193
1194
154k
      }
1195
1196
      // if we have both glyf and loca make sure they are consecutive
1197
      // if we have just one we'll reject the font elsewhere
1198
6.28k
      if (glyf_idx > 0 || loca_idx > 0) {
1199
273
        if (PREDICT_FALSE(glyf_idx > loca_idx || loca_idx - glyf_idx != 1)) {
1200
#ifdef FONT_COMPRESSION_BIN
1201
        fprintf(stderr, "TTC font %d has non-consecutive glyf/loca\n", i);
1202
#endif
1203
13
          return FONT_COMPRESSION_FAILURE();
1204
13
        }
1205
273
      }
1206
6.28k
    }
1207
510
  }
1208
1209
7.35k
  const uint64_t first_table_offset = ComputeOffsetToFirstTable(*hdr);
1210
1211
7.35k
  hdr->compressed_offset = file.offset();
1212
7.35k
  if (PREDICT_FALSE(hdr->compressed_offset >
1213
7.35k
                    std::numeric_limits<uint32_t>::max())) {
1214
0
    return FONT_COMPRESSION_FAILURE();
1215
0
  }
1216
7.35k
  uint64_t src_offset = Round4(hdr->compressed_offset + hdr->compressed_length);
1217
7.35k
  uint64_t dst_offset = first_table_offset;
1218
1219
1220
7.35k
  if (PREDICT_FALSE(src_offset > length)) {
1221
#ifdef FONT_COMPRESSION_BIN
1222
    fprintf(stderr, "offset fail; src_offset %" PRIu64 " length %lu "
1223
      "dst_offset %" PRIu64 "\n",
1224
      src_offset, length, dst_offset);
1225
#endif
1226
139
    return FONT_COMPRESSION_FAILURE();
1227
139
  }
1228
7.21k
  if (meta_offset) {
1229
69
    if (PREDICT_FALSE(src_offset != meta_offset)) {
1230
34
      return FONT_COMPRESSION_FAILURE();
1231
34
    }
1232
35
    src_offset = Round4(meta_offset + meta_length);
1233
35
    if (PREDICT_FALSE(src_offset > std::numeric_limits<uint32_t>::max())) {
1234
0
      return FONT_COMPRESSION_FAILURE();
1235
0
    }
1236
35
  }
1237
1238
7.18k
  if (priv_offset) {
1239
98
    if (PREDICT_FALSE(src_offset != priv_offset)) {
1240
44
      return FONT_COMPRESSION_FAILURE();
1241
44
    }
1242
54
    src_offset = Round4(priv_offset + priv_length);
1243
54
    if (PREDICT_FALSE(src_offset > std::numeric_limits<uint32_t>::max())) {
1244
0
      return FONT_COMPRESSION_FAILURE();
1245
0
    }
1246
54
  }
1247
1248
7.14k
  if (PREDICT_FALSE(src_offset != Round4(length))) {
1249
48
    return FONT_COMPRESSION_FAILURE();
1250
48
  }
1251
1252
7.09k
  return true;
1253
7.14k
}
1254
1255
// Write everything before the actual table data
1256
bool WriteHeaders(const uint8_t* data, size_t length, RebuildMetadata* metadata,
1257
7.09k
                  WOFF2Header* hdr, WOFF2Out* out) {
1258
7.09k
  std::vector<uint8_t> output(ComputeOffsetToFirstTable(*hdr), 0);
1259
1260
  // Re-order tables in output (OTSpec) order
1261
7.09k
  std::vector<Table> sorted_tables(hdr->tables);
1262
7.09k
  if (hdr->header_version) {
1263
    // collection; we have to sort the table offset vector in each font
1264
3.92k
    for (auto& ttc_font : hdr->ttc_fonts) {
1265
3.92k
      std::map<uint32_t, uint16_t> sorted_index_by_tag;
1266
101k
      for (auto table_index : ttc_font.table_indices) {
1267
101k
        sorted_index_by_tag[hdr->tables[table_index].tag] = table_index;
1268
101k
      }
1269
3.92k
      uint16_t index = 0;
1270
30.9k
      for (auto& i : sorted_index_by_tag) {
1271
30.9k
        ttc_font.table_indices[index++] = i.second;
1272
30.9k
      }
1273
3.92k
    }
1274
6.84k
  } else {
1275
    // non-collection; we can just sort the tables
1276
6.84k
    std::sort(sorted_tables.begin(), sorted_tables.end());
1277
6.84k
  }
1278
1279
  // Start building the font
1280
7.09k
  uint8_t* result = &output[0];
1281
7.09k
  size_t offset = 0;
1282
7.09k
  if (hdr->header_version) {
1283
    // TTC header
1284
248
    offset = StoreU32(result, offset, hdr->flavor);  // TAG TTCTag
1285
248
    offset = StoreU32(result, offset, hdr->header_version);  // FIXED Version
1286
248
    offset = StoreU32(result, offset, hdr->ttc_fonts.size());  // ULONG numFonts
1287
    // Space for ULONG OffsetTable[numFonts] (zeroed initially)
1288
248
    size_t offset_table = offset;  // keep start of offset table for later
1289
4.17k
    for (size_t i = 0; i < hdr->ttc_fonts.size(); i++) {
1290
3.92k
      offset = StoreU32(result, offset, 0);  // will fill real values in later
1291
3.92k
    }
1292
    // space for DSIG fields for header v2
1293
248
    if (hdr->header_version == 0x00020000) {
1294
109
      offset = StoreU32(result, offset, 0);  // ULONG ulDsigTag
1295
109
      offset = StoreU32(result, offset, 0);  // ULONG ulDsigLength
1296
109
      offset = StoreU32(result, offset, 0);  // ULONG ulDsigOffset
1297
109
    }
1298
1299
    // write Offset Tables and store the location of each in TTC Header
1300
248
    metadata->font_infos.resize(hdr->ttc_fonts.size());
1301
4.17k
    for (size_t i = 0; i < hdr->ttc_fonts.size(); i++) {
1302
3.92k
      TtcFont& ttc_font = hdr->ttc_fonts[i];
1303
1304
      // write Offset Table location into TTC Header
1305
3.92k
      offset_table = StoreU32(result, offset_table, offset);
1306
1307
      // write the actual offset table so our header doesn't lie
1308
3.92k
      ttc_font.dst_offset = offset;
1309
3.92k
      offset = StoreOffsetTable(result, offset, ttc_font.flavor,
1310
3.92k
                                ttc_font.table_indices.size());
1311
1312
101k
      for (const auto table_index : ttc_font.table_indices) {
1313
101k
        uint32_t tag = hdr->tables[table_index].tag;
1314
101k
        metadata->font_infos[i].table_entry_by_tag[tag] = offset;
1315
101k
        offset = StoreTableEntry(result, offset, tag);
1316
101k
      }
1317
1318
3.92k
      ttc_font.header_checksum = ComputeULongSum(&output[ttc_font.dst_offset],
1319
3.92k
                                                 offset - ttc_font.dst_offset);
1320
3.92k
    }
1321
6.84k
  } else {
1322
6.84k
    metadata->font_infos.resize(1);
1323
6.84k
    offset = StoreOffsetTable(result, offset, hdr->flavor, hdr->num_tables);
1324
1.31M
    for (uint16_t i = 0; i < hdr->num_tables; ++i) {
1325
1.30M
      metadata->font_infos[0].table_entry_by_tag[sorted_tables[i].tag] = offset;
1326
1.30M
      offset = StoreTableEntry(result, offset, sorted_tables[i].tag);
1327
1.30M
    }
1328
6.84k
  }
1329
1330
7.09k
  if (PREDICT_FALSE(!out->Write(&output[0], output.size()))) {
1331
0
    return FONT_COMPRESSION_FAILURE();
1332
0
  }
1333
7.09k
  metadata->header_checksum = ComputeULongSum(&output[0], output.size());
1334
7.09k
  return true;
1335
7.09k
}
1336
1337
}  // namespace
1338
1339
0
size_t ComputeWOFF2FinalSize(const uint8_t* data, size_t length) {
1340
0
  Buffer file(data, length);
1341
0
  uint32_t total_length;
1342
1343
0
  if (!file.Skip(16) ||
1344
0
      !file.ReadU32(&total_length)) {
1345
0
    return 0;
1346
0
  }
1347
0
  return total_length;
1348
0
}
1349
1350
bool ConvertWOFF2ToTTF(uint8_t *result, size_t result_length,
1351
0
                       const uint8_t *data, size_t length) {
1352
0
  WOFF2MemoryOut out(result, result_length);
1353
0
  return ConvertWOFF2ToTTF(data, length, &out);
1354
0
}
1355
1356
bool ConvertWOFF2ToTTF(const uint8_t* data, size_t length,
1357
8.32k
                       WOFF2Out* out) {
1358
8.32k
  RebuildMetadata metadata;
1359
8.32k
  WOFF2Header hdr;
1360
8.32k
  if (!ReadWOFF2Header(data, length, &hdr)) {
1361
1.23k
    return FONT_COMPRESSION_FAILURE();
1362
1.23k
  }
1363
1364
7.09k
  if (!WriteHeaders(data, length, &metadata, &hdr, out)) {
1365
0
    return FONT_COMPRESSION_FAILURE();
1366
0
  }
1367
1368
7.09k
  const float compression_ratio = (float) hdr.uncompressed_size / length;
1369
7.09k
  if (compression_ratio > kMaxPlausibleCompressionRatio) {
1370
#ifdef FONT_COMPRESSION_BIN
1371
    fprintf(stderr, "Implausible compression ratio %.01f\n", compression_ratio);
1372
#endif
1373
478
    return FONT_COMPRESSION_FAILURE();
1374
478
  }
1375
1376
6.61k
  const uint8_t* src_buf = data + hdr.compressed_offset;
1377
6.61k
  std::vector<uint8_t> uncompressed_buf(hdr.uncompressed_size);
1378
6.61k
  if (PREDICT_FALSE(hdr.uncompressed_size < 1)) {
1379
59
    return FONT_COMPRESSION_FAILURE();
1380
59
  }
1381
6.55k
  if (PREDICT_FALSE(!Woff2Uncompress(&uncompressed_buf[0],
1382
6.55k
                                     hdr.uncompressed_size, src_buf,
1383
6.55k
                                     hdr.compressed_length))) {
1384
5.21k
    return FONT_COMPRESSION_FAILURE();
1385
5.21k
  }
1386
1387
2.36k
  for (size_t i = 0; i < metadata.font_infos.size(); i++) {
1388
2.01k
    if (PREDICT_FALSE(!ReconstructFont(&uncompressed_buf[0],
1389
2.01k
                                       hdr.uncompressed_size,
1390
2.01k
                                       &metadata, &hdr, i, out))) {
1391
995
      return FONT_COMPRESSION_FAILURE();
1392
995
    }
1393
2.01k
  }
1394
1395
345
  return true;
1396
1.34k
}
1397
1398
} // namespace woff2