Debian Codegraph @

src/woff2_enc.cc

raw
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 TTF format font files to their WOFF2 versions. */
8
9 #include <woff2/encode.h>
10
11 #include <stdlib.h>
12 #include <complex>
13 #include <cstring>
14 #include <limits>
15 #include <string>
16 #include <vector>
17
18 #include <brotli/encode.h>
19 #include "./buffer.h"
20 #include "./font.h"
21 #include "./normalize.h"
22 #include "./round.h"
23 #include "./store_bytes.h"
24 #include "./table_tags.h"
25 #include "./transform.h"
26 #include "./variable_length.h"
27 #include "./woff2_common.h"
28
29 namespace woff2 {
30
31 namespace {
32
33
34 using std::string;
35 using std::vector;
36
37
38 const size_t kWoff2HeaderSize = 48;
39 const size_t kWoff2EntrySize = 20;
40
41 bool Compress(const uint8_t* data, const size_t len, uint8_t* result,
42 uint32_t* result_len, BrotliEncoderMode mode, int quality) {
43 size_t compressed_len = *result_len;
44 if (BrotliEncoderCompress(quality, BROTLI_DEFAULT_WINDOW, mode, len, data,
45 &compressed_len, result) == 0) {
46 return false;
47 }
48 *result_len = compressed_len;
49 return true;
50 }
51
52 bool Woff2Compress(const uint8_t* data, const size_t len,
53 uint8_t* result, uint32_t* result_len,
54 int quality) {
55 return Compress(data, len, result, result_len,
56 BROTLI_MODE_FONT, quality);
57 }
58
59 bool TextCompress(const uint8_t* data, const size_t len,
60 uint8_t* result, uint32_t* result_len,
61 int quality) {
62 return Compress(data, len, result, result_len,
63 BROTLI_MODE_TEXT, quality);
64 }
65
66 int KnownTableIndex(uint32_t tag) {
67 for (int i = 0; i < 63; ++i) {
68 if (tag == kKnownTags[i]) return i;
69 }
70 return 63;
71 }
72
73 void StoreTableEntry(const Table& table, size_t* offset, uint8_t* dst) {
74 uint8_t flag_byte = (table.flags & 0xC0) | KnownTableIndex(table.tag);
75 dst[(*offset)++] = flag_byte;
76 // The index here is treated as a set of flag bytes because
77 // bits 6 and 7 of the byte are reserved for future use as flags.
78 // 0x3f or 63 means an arbitrary table tag.
79 if ((flag_byte & 0x3f) == 0x3f) {
80 StoreU32(table.tag, offset, dst);
81 }
82 StoreBase128(table.src_length, offset, dst);
83 if ((table.flags & kWoff2FlagsTransform) != 0) {
84 StoreBase128(table.transform_length, offset, dst);
85 }
86 }
87
88 size_t TableEntrySize(const Table& table) {
89 uint8_t flag_byte = KnownTableIndex(table.tag);
90 size_t size = ((flag_byte & 0x3f) != 0x3f) ? 1 : 5;
91 size += Base128Size(table.src_length);
92 if ((table.flags & kWoff2FlagsTransform) != 0) {
93 size += Base128Size(table.transform_length);
94 }
95 return size;
96 }
97
98 size_t ComputeWoff2Length(const FontCollection& font_collection,
99 const std::vector<Table>& tables,
100 std::map<std::pair<uint32_t, uint32_t>, uint16_t>
101 index_by_tag_offset,
102 size_t compressed_data_length,
103 size_t extended_metadata_length) {
104 size_t size = kWoff2HeaderSize;
105
106 for (const auto& table : tables) {
107 size += TableEntrySize(table);
108 }
109
110 // for collections only, collection tables
111 if (font_collection.flavor == kTtcFontFlavor) {
112 size += 4; // UInt32 Version of TTC Header
113 size += Size255UShort(font_collection.fonts.size()); // 255UInt16 numFonts
114
115 size += 4 * font_collection.fonts.size(); // UInt32 flavor for each
116
117 for (const auto& font : font_collection.fonts) {
118 size += Size255UShort(font.tables.size()); // 255UInt16 numTables
119 for (const auto& entry : font.tables) {
120 const Font::Table& table = entry.second;
121 // no collection entry for xform table
122 if (table.tag & 0x80808080) continue;
123
124 std::pair<uint32_t, uint32_t> tag_offset(table.tag, table.offset);
125 uint16_t table_index = index_by_tag_offset[tag_offset];
126 size += Size255UShort(table_index); // 255UInt16 index entry
127 }
128 }
129 }
130
131 // compressed data
132 size += compressed_data_length;
133 size = Round4(size);
134
135 size += extended_metadata_length;
136 return size;
137 }
138
139 size_t ComputeUncompressedLength(const Font& font) {
140 // sfnt header + offset table
141 size_t size = 12 + 16 * font.num_tables;
142 for (const auto& entry : font.tables) {
143 const Font::Table& table = entry.second;
144 if (table.tag & 0x80808080) continue; // xform tables don't stay
145 if (table.IsReused()) continue; // don't have to pay twice
146 size += Round4(table.length);
147 }
148 return size;
149 }
150
151 size_t ComputeUncompressedLength(const FontCollection& font_collection) {
152 if (font_collection.flavor != kTtcFontFlavor) {
153 return ComputeUncompressedLength(font_collection.fonts[0]);
154 }
155 size_t size = CollectionHeaderSize(font_collection.header_version,
156 font_collection.fonts.size());
157 for (const auto& font : font_collection.fonts) {
158 size += ComputeUncompressedLength(font);
159 }
160 return size;
161 }
162
163 size_t ComputeTotalTransformLength(const Font& font) {
164 size_t total = 0;
165 for (const auto& i : font.tables) {
166 const Font::Table& table = i.second;
167 if (table.IsReused()) {
168 continue;
169 }
170 if (table.tag & 0x80808080 || !font.FindTable(table.tag ^ 0x80808080)) {
171 // Count transformed tables and non-transformed tables that do not have
172 // transformed versions.
173 total += table.length;
174 }
175 }
176 return total;
177 }
178
179 } // namespace
180
181 size_t MaxWOFF2CompressedSize(const uint8_t* data, size_t length) {
182 return MaxWOFF2CompressedSize(data, length, "");
183 }
184
185 size_t MaxWOFF2CompressedSize(const uint8_t* data, size_t length,
186 const string& extended_metadata) {
187 // Except for the header size, which is 32 bytes larger in woff2 format,
188 // all other parts should be smaller (table header in short format,
189 // transformations and compression). Just to be sure, we will give some
190 // headroom anyway.
191 return length + 1024 + extended_metadata.length();
192 }
193
194 uint32_t CompressedBufferSize(uint32_t original_size) {
195 return 1.2 * original_size + 10240;
196 }
197
198 bool TransformFontCollection(FontCollection* font_collection) {
199 for (auto& font : font_collection->fonts) {
200 if (!TransformGlyfAndLocaTables(&font)) {
201 #ifdef FONT_COMPRESSION_BIN
202 fprintf(stderr, "glyf/loca transformation failed.\n");
203 #endif
204 return FONT_COMPRESSION_FAILURE();
205 }
206 }
207
208 return true;
209 }
210
211 bool ConvertTTFToWOFF2(const uint8_t *data, size_t length,
212 uint8_t *result, size_t *result_length) {
213 WOFF2Params params;
214 return ConvertTTFToWOFF2(data, length, result, result_length,
215 params);
216 }
217
218 bool ConvertTTFToWOFF2(const uint8_t *data, size_t length,
219 uint8_t *result, size_t *result_length,
220 const WOFF2Params& params) {
221 FontCollection font_collection;
222 if (!ReadFontCollection(data, length, &font_collection)) {
223 #ifdef FONT_COMPRESSION_BIN
224 fprintf(stderr, "Parsing of the input font failed.\n");
225 #endif
226 return FONT_COMPRESSION_FAILURE();
227 }
228
229 if (!NormalizeFontCollection(&font_collection)) {
230 return FONT_COMPRESSION_FAILURE();
231 }
232
233 if (params.allow_transforms && !TransformFontCollection(&font_collection)) {
234 return FONT_COMPRESSION_FAILURE();
235 } else {
236 // glyf/loca use 11 to flag "not transformed"
237 for (auto& font : font_collection.fonts) {
238 Font::Table* glyf_table = font.FindTable(kGlyfTableTag);
239 Font::Table* loca_table = font.FindTable(kLocaTableTag);
240 if (glyf_table) {
241 glyf_table->flag_byte |= 0xc0;
242 }
243 if (loca_table) {
244 loca_table->flag_byte |= 0xc0;
245 }
246 }
247 }
248
249 // Although the compressed size of each table in the final woff2 file won't
250 // be larger than its transform_length, we have to allocate a large enough
251 // buffer for the compressor, since the compressor can potentially increase
252 // the size. If the compressor overflows this, it should return false and
253 // then this function will also return false.
254
255 size_t total_transform_length = 0;
256 for (const auto& font : font_collection.fonts) {
257 total_transform_length += ComputeTotalTransformLength(font);
258 }
259 size_t compression_buffer_size = CompressedBufferSize(total_transform_length);
260 std::vector<uint8_t> compression_buf(compression_buffer_size);
261 uint32_t total_compressed_length = compression_buffer_size;
262
263 // Collect all transformed data into one place in output order.
264 std::vector<uint8_t> transform_buf(total_transform_length);
265 size_t transform_offset = 0;
266 for (const auto& font : font_collection.fonts) {
267 for (const auto tag : font.OutputOrderedTags()) {
268 const Font::Table& original = font.tables.at(tag);
269 if (original.IsReused()) continue;
270 if (tag & 0x80808080) continue;
271 const Font::Table* table_to_store = font.FindTable(tag ^ 0x80808080);
272 if (table_to_store == NULL) table_to_store = &original;
273
274 StoreBytes(table_to_store->data, table_to_store->length,
275 &transform_offset, &transform_buf[0]);
276 }
277 }
278
279 // Compress all transformed data in one stream.
280 if (!Woff2Compress(transform_buf.data(), total_transform_length,
281 &compression_buf[0],
282 &total_compressed_length,
283 params.brotli_quality)) {
284 #ifdef FONT_COMPRESSION_BIN
285 fprintf(stderr, "Compression of combined table failed.\n");
286 #endif
287 return FONT_COMPRESSION_FAILURE();
288 }
289
290 #ifdef FONT_COMPRESSION_BIN
291 fprintf(stderr, "Compressed %zu to %u.\n", total_transform_length,
292 total_compressed_length);
293 #endif
294
295 // Compress the extended metadata
296 // TODO(user): how does this apply to collections
297 uint32_t compressed_metadata_buf_length =
298 CompressedBufferSize(params.extended_metadata.length());
299 std::vector<uint8_t> compressed_metadata_buf(compressed_metadata_buf_length);
300
301 if (params.extended_metadata.length() > 0) {
302 if (!TextCompress((const uint8_t*)params.extended_metadata.data(),
303 params.extended_metadata.length(),
304 compressed_metadata_buf.data(),
305 &compressed_metadata_buf_length,
306 params.brotli_quality)) {
307 #ifdef FONT_COMPRESSION_BIN
308 fprintf(stderr, "Compression of extended metadata failed.\n");
309 #endif
310 return FONT_COMPRESSION_FAILURE();
311 }
312 } else {
313 compressed_metadata_buf_length = 0;
314 }
315
316 std::vector<Table> tables;
317 std::map<std::pair<uint32_t, uint32_t>, uint16_t> index_by_tag_offset;
318
319 for (const auto& font : font_collection.fonts) {
320
321 for (const auto tag : font.OutputOrderedTags()) {
322 const Font::Table& src_table = font.tables.at(tag);
323 if (src_table.IsReused()) {
324 continue;
325 }
326
327 std::pair<uint32_t, uint32_t> tag_offset(src_table.tag, src_table.offset);
328 if (index_by_tag_offset.find(tag_offset) == index_by_tag_offset.end()) {
329 index_by_tag_offset[tag_offset] = tables.size();
330 } else {
331 return false;
332 }
333
334 Table table;
335 table.tag = src_table.tag;
336 table.flags = src_table.flag_byte;
337 table.src_length = src_table.length;
338 table.transform_length = src_table.length;
339 const uint8_t* transformed_data = src_table.data;
340 const Font::Table* transformed_table =
341 font.FindTable(src_table.tag ^ 0x80808080);
342 if (transformed_table != NULL) {
343 table.flags = transformed_table->flag_byte;
344 table.flags |= kWoff2FlagsTransform;
345 table.transform_length = transformed_table->length;
346 transformed_data = transformed_table->data;
347
348 }
349 tables.push_back(table);
350 }
351 }
352
353 size_t woff2_length = ComputeWoff2Length(font_collection, tables,
354 index_by_tag_offset, total_compressed_length,
355 compressed_metadata_buf_length);
356 if (woff2_length > *result_length) {
357 #ifdef FONT_COMPRESSION_BIN
358 fprintf(stderr, "Result allocation was too small (%zd vs %zd bytes).\n",
359 *result_length, woff2_length);
360 #endif
361 return FONT_COMPRESSION_FAILURE();
362 }
363 *result_length = woff2_length;
364
365 size_t offset = 0;
366
367 // start of woff2 header (http://www.w3.org/TR/WOFF2/#woff20Header)
368 StoreU32(kWoff2Signature, &offset, result);
369 if (font_collection.flavor != kTtcFontFlavor) {
370 StoreU32(font_collection.fonts[0].flavor, &offset, result);
371 } else {
372 StoreU32(kTtcFontFlavor, &offset, result);
373 }
374 StoreU32(woff2_length, &offset, result);
375 Store16(tables.size(), &offset, result);
376 Store16(0, &offset, result); // reserved
377 // totalSfntSize
378 StoreU32(ComputeUncompressedLength(font_collection), &offset, result);
379 StoreU32(total_compressed_length, &offset, result); // totalCompressedSize
380
381 // Let's just all be v1.0
382 Store16(1, &offset, result); // majorVersion
383 Store16(0, &offset, result); // minorVersion
384 if (compressed_metadata_buf_length > 0) {
385 StoreU32(woff2_length - compressed_metadata_buf_length,
386 &offset, result); // metaOffset
387 StoreU32(compressed_metadata_buf_length, &offset, result); // metaLength
388 StoreU32(params.extended_metadata.length(),
389 &offset, result); // metaOrigLength
390 } else {
391 StoreU32(0, &offset, result); // metaOffset
392 StoreU32(0, &offset, result); // metaLength
393 StoreU32(0, &offset, result); // metaOrigLength
394 }
395 StoreU32(0, &offset, result); // privOffset
396 StoreU32(0, &offset, result); // privLength
397 // end of woff2 header
398
399 // table directory (http://www.w3.org/TR/WOFF2/#table_dir_format)
400 for (const auto& table : tables) {
401 StoreTableEntry(table, &offset, result);
402 }
403
404 // for collections only, collection table directory
405 if (font_collection.flavor == kTtcFontFlavor) {
406 StoreU32(font_collection.header_version, &offset, result);
407 Store255UShort(font_collection.fonts.size(), &offset, result);
408 for (const Font& font : font_collection.fonts) {
409
410 uint16_t num_tables = 0;
411 for (const auto& entry : font.tables) {
412 const Font::Table& table = entry.second;
413 if (table.tag & 0x80808080) continue; // don't write xform tables
414 num_tables++;
415 }
416 Store255UShort(num_tables, &offset, result);
417
418 StoreU32(font.flavor, &offset, result);
419 for (const auto& entry : font.tables) {
420 const Font::Table& table = entry.second;
421 if (table.tag & 0x80808080) continue; // don't write xform tables
422
423 // for reused tables, only the original has an updated offset
424 uint32_t table_offset =
425 table.IsReused() ? table.reuse_of->offset : table.offset;
426 uint32_t table_length =
427 table.IsReused() ? table.reuse_of->length : table.length;
428 std::pair<uint32_t, uint32_t> tag_offset(table.tag, table_offset);
429 if (index_by_tag_offset.find(tag_offset) == index_by_tag_offset.end()) {
430 #ifdef FONT_COMPRESSION_BIN
431 fprintf(stderr, "Missing table index for offset 0x%08x\n",
432 table_offset);
433 #endif
434 return FONT_COMPRESSION_FAILURE();
435 }
436 uint16_t index = index_by_tag_offset[tag_offset];
437 Store255UShort(index, &offset, result);
438
439 }
440
441 }
442 }
443
444 // compressed data format (http://www.w3.org/TR/WOFF2/#table_format)
445
446 StoreBytes(&compression_buf[0], total_compressed_length, &offset, result);
447 offset = Round4(offset);
448
449 StoreBytes(compressed_metadata_buf.data(), compressed_metadata_buf_length,
450 &offset, result);
451
452 if (*result_length != offset) {
453 #ifdef FONT_COMPRESSION_BIN
454 fprintf(stderr, "Mismatch between computed and actual length "
455 "(%zd vs %zd)\n", *result_length, offset);
456 #endif
457 return FONT_COMPRESSION_FAILURE();
458 }
459 return true;
460 }
461
462 } // namespace woff2