blob: 9c3e34ec475b24477f5c728690e3ae5af4d65086 [file] [log] [blame]
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001// Copyright 2013 Google Inc. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15// Library for converting WOFF2 format font files to their TTF versions.
16
17#include "./woff2.h"
18
19#include <stdlib.h>
20#include <complex>
21#include <cstring>
22#include <limits>
23#include <string>
24#include <vector>
25
26#include "./ots.h"
27#include "./decode.h"
28#include "./encode.h"
29#include "./font.h"
30#include "./normalize.h"
31#include "./round.h"
32#include "./store_bytes.h"
33#include "./transform.h"
34
35namespace woff2 {
36
37namespace {
38
39using std::string;
40using std::vector;
41
42
Roderick Sheeter437bbad2013-11-19 14:32:56 -080043// simple glyph flags
44const int kGlyfOnCurve = 1 << 0;
45const int kGlyfXShort = 1 << 1;
46const int kGlyfYShort = 1 << 2;
47const int kGlyfRepeat = 1 << 3;
48const int kGlyfThisXIsSame = 1 << 4;
49const int kGlyfThisYIsSame = 1 << 5;
50
51// composite glyph flags
52const int FLAG_ARG_1_AND_2_ARE_WORDS = 1 << 0;
53const int FLAG_ARGS_ARE_XY_VALUES = 1 << 1;
54const int FLAG_ROUND_XY_TO_GRID = 1 << 2;
55const int FLAG_WE_HAVE_A_SCALE = 1 << 3;
56const int FLAG_RESERVED = 1 << 4;
57const int FLAG_MORE_COMPONENTS = 1 << 5;
58const int FLAG_WE_HAVE_AN_X_AND_Y_SCALE = 1 << 6;
59const int FLAG_WE_HAVE_A_TWO_BY_TWO = 1 << 7;
60const int FLAG_WE_HAVE_INSTRUCTIONS = 1 << 8;
61const int FLAG_USE_MY_METRICS = 1 << 9;
62const int FLAG_OVERLAP_COMPOUND = 1 << 10;
63const int FLAG_SCALED_COMPONENT_OFFSET = 1 << 11;
64const int FLAG_UNSCALED_COMPONENT_OFFSET = 1 << 12;
65
66const size_t kSfntHeaderSize = 12;
67const size_t kSfntEntrySize = 16;
68const size_t kCheckSumAdjustmentOffset = 8;
69
70const size_t kEndPtsOfContoursOffset = 10;
71const size_t kCompositeGlyphBegin = 10;
72
73// Note that the byte order is big-endian, not the same as ots.cc
74#define TAG(a, b, c, d) ((a << 24) | (b << 16) | (c << 8) | d)
75
76const uint32_t kWoff2Signature = 0x774f4632; // "wOF2"
77
78const unsigned int kWoff2FlagsContinueStream = 1 << 4;
79const unsigned int kWoff2FlagsTransform = 1 << 5;
80
Zoltan Szabadka22e2c322014-03-27 16:13:13 +010081const size_t kWoff2HeaderSize = 48;
Roderick Sheeter437bbad2013-11-19 14:32:56 -080082const size_t kWoff2EntrySize = 20;
83
84const size_t kLzmaHeaderSize = 13;
85
86// Compression type values common to both short and long formats
87const uint32_t kCompressionTypeMask = 0xf;
88const uint32_t kCompressionTypeNone = 0;
89const uint32_t kCompressionTypeGzip = 1;
Zoltan Szabadka494c85c2014-03-20 14:35:41 +010090const uint32_t kCompressionTypeBrotli = 2;
Roderick Sheeter437bbad2013-11-19 14:32:56 -080091
92// This is a special value for the short format only, as described in
93// "Design for compressed header format" in draft doc.
94const uint32_t kShortFlagsContinue = 3;
95
96struct Point {
97 int x;
98 int y;
99 bool on_curve;
100};
101
102struct Table {
103 uint32_t tag;
104 uint32_t flags;
105 uint32_t src_offset;
106 uint32_t src_length;
107
108 uint32_t transform_length;
109
110 uint32_t dst_offset;
111 uint32_t dst_length;
112 const uint8_t* dst_data;
113};
114
115// Based on section 6.1.1 of MicroType Express draft spec
116bool Read255UShort(ots::Buffer* buf, unsigned int* value) {
117 static const int kWordCode = 253;
118 static const int kOneMoreByteCode2 = 254;
119 static const int kOneMoreByteCode1 = 255;
120 static const int kLowestUCode = 253;
121 uint8_t code = 0;
122 if (!buf->ReadU8(&code)) {
123 return OTS_FAILURE();
124 }
125 if (code == kWordCode) {
126 uint16_t result = 0;
127 if (!buf->ReadU16(&result)) {
128 return OTS_FAILURE();
129 }
130 *value = result;
131 return true;
132 } else if (code == kOneMoreByteCode1) {
133 uint8_t result = 0;
134 if (!buf->ReadU8(&result)) {
135 return OTS_FAILURE();
136 }
137 *value = result + kLowestUCode;
138 return true;
139 } else if (code == kOneMoreByteCode2) {
140 uint8_t result = 0;
141 if (!buf->ReadU8(&result)) {
142 return OTS_FAILURE();
143 }
144 *value = result + kLowestUCode * 2;
145 return true;
146 } else {
147 *value = code;
148 return true;
149 }
150}
151
152bool ReadBase128(ots::Buffer* buf, uint32_t* value) {
153 uint32_t result = 0;
154 for (size_t i = 0; i < 5; ++i) {
155 uint8_t code = 0;
156 if (!buf->ReadU8(&code)) {
157 return OTS_FAILURE();
158 }
159 // If any of the top seven bits are set then we're about to overflow.
160 if (result & 0xe0000000) {
161 return OTS_FAILURE();
162 }
163 result = (result << 7) | (code & 0x7f);
164 if ((code & 0x80) == 0) {
165 *value = result;
166 return true;
167 }
168 }
169 // Make sure not to exceed the size bound
170 return OTS_FAILURE();
171}
172
173size_t Base128Size(size_t n) {
174 size_t size = 1;
175 for (; n >= 128; n >>= 7) ++size;
176 return size;
177}
178
179void StoreBase128(size_t len, size_t* offset, uint8_t* dst) {
180 size_t size = Base128Size(len);
181 for (int i = 0; i < size; ++i) {
182 int b = (int)(len >> (7 * (size - i - 1))) & 0x7f;
183 if (i < size - 1) {
184 b |= 0x80;
185 }
186 dst[(*offset)++] = b;
187 }
188}
189
190int WithSign(int flag, int baseval) {
191 // Precondition: 0 <= baseval < 65536 (to avoid integer overflow)
192 return (flag & 1) ? baseval : -baseval;
193}
194
195bool TripletDecode(const uint8_t* flags_in, const uint8_t* in, size_t in_size,
196 unsigned int n_points, std::vector<Point>* result,
197 size_t* in_bytes_consumed) {
198 int x = 0;
199 int y = 0;
200
201 if (n_points > in_size) {
202 return OTS_FAILURE();
203 }
204 unsigned int triplet_index = 0;
205
206 for (unsigned int i = 0; i < n_points; ++i) {
207 uint8_t flag = flags_in[i];
208 bool on_curve = !(flag >> 7);
209 flag &= 0x7f;
210 unsigned int n_data_bytes;
211 if (flag < 84) {
212 n_data_bytes = 1;
213 } else if (flag < 120) {
214 n_data_bytes = 2;
215 } else if (flag < 124) {
216 n_data_bytes = 3;
217 } else {
218 n_data_bytes = 4;
219 }
220 if (triplet_index + n_data_bytes > in_size ||
221 triplet_index + n_data_bytes < triplet_index) {
222 return OTS_FAILURE();
223 }
224 int dx, dy;
225 if (flag < 10) {
226 dx = 0;
227 dy = WithSign(flag, ((flag & 14) << 7) + in[triplet_index]);
228 } else if (flag < 20) {
229 dx = WithSign(flag, (((flag - 10) & 14) << 7) + in[triplet_index]);
230 dy = 0;
231 } else if (flag < 84) {
232 int b0 = flag - 20;
233 int b1 = in[triplet_index];
234 dx = WithSign(flag, 1 + (b0 & 0x30) + (b1 >> 4));
235 dy = WithSign(flag >> 1, 1 + ((b0 & 0x0c) << 2) + (b1 & 0x0f));
236 } else if (flag < 120) {
237 int b0 = flag - 84;
238 dx = WithSign(flag, 1 + ((b0 / 12) << 8) + in[triplet_index]);
239 dy = WithSign(flag >> 1,
240 1 + (((b0 % 12) >> 2) << 8) + in[triplet_index + 1]);
241 } else if (flag < 124) {
242 int b2 = in[triplet_index + 1];
243 dx = WithSign(flag, (in[triplet_index] << 4) + (b2 >> 4));
244 dy = WithSign(flag >> 1, ((b2 & 0x0f) << 8) + in[triplet_index + 2]);
245 } else {
246 dx = WithSign(flag, (in[triplet_index] << 8) + in[triplet_index + 1]);
247 dy = WithSign(flag >> 1,
248 (in[triplet_index + 2] << 8) + in[triplet_index + 3]);
249 }
250 triplet_index += n_data_bytes;
251 // Possible overflow but coordinate values are not security sensitive
252 x += dx;
253 y += dy;
254 result->push_back(Point());
255 Point& back = result->back();
256 back.x = x;
257 back.y = y;
258 back.on_curve = on_curve;
259 }
260 *in_bytes_consumed = triplet_index;
261 return true;
262}
263
264// This function stores just the point data. On entry, dst points to the
265// beginning of a simple glyph. Returns true on success.
266bool StorePoints(const std::vector<Point>& points,
267 unsigned int n_contours, unsigned int instruction_length,
268 uint8_t* dst, size_t dst_size, size_t* glyph_size) {
269 // I believe that n_contours < 65536, in which case this is safe. However, a
270 // comment and/or an assert would be good.
271 unsigned int flag_offset = kEndPtsOfContoursOffset + 2 * n_contours + 2 +
272 instruction_length;
273 int last_flag = -1;
274 int repeat_count = 0;
275 int last_x = 0;
276 int last_y = 0;
277 unsigned int x_bytes = 0;
278 unsigned int y_bytes = 0;
279
280 for (unsigned int i = 0; i < points.size(); ++i) {
281 const Point& point = points[i];
282 int flag = point.on_curve ? kGlyfOnCurve : 0;
283 int dx = point.x - last_x;
284 int dy = point.y - last_y;
285 if (dx == 0) {
286 flag |= kGlyfThisXIsSame;
287 } else if (dx > -256 && dx < 256) {
288 flag |= kGlyfXShort | (dx > 0 ? kGlyfThisXIsSame : 0);
289 x_bytes += 1;
290 } else {
291 x_bytes += 2;
292 }
293 if (dy == 0) {
294 flag |= kGlyfThisYIsSame;
295 } else if (dy > -256 && dy < 256) {
296 flag |= kGlyfYShort | (dy > 0 ? kGlyfThisYIsSame : 0);
297 y_bytes += 1;
298 } else {
299 y_bytes += 2;
300 }
301
302 if (flag == last_flag && repeat_count != 255) {
303 dst[flag_offset - 1] |= kGlyfRepeat;
304 repeat_count++;
305 } else {
306 if (repeat_count != 0) {
307 if (flag_offset >= dst_size) {
308 return OTS_FAILURE();
309 }
310 dst[flag_offset++] = repeat_count;
311 }
312 if (flag_offset >= dst_size) {
313 return OTS_FAILURE();
314 }
315 dst[flag_offset++] = flag;
316 repeat_count = 0;
317 }
318 last_x = point.x;
319 last_y = point.y;
320 last_flag = flag;
321 }
322
323 if (repeat_count != 0) {
324 if (flag_offset >= dst_size) {
325 return OTS_FAILURE();
326 }
327 dst[flag_offset++] = repeat_count;
328 }
329 unsigned int xy_bytes = x_bytes + y_bytes;
330 if (xy_bytes < x_bytes ||
331 flag_offset + xy_bytes < flag_offset ||
332 flag_offset + xy_bytes > dst_size) {
333 return OTS_FAILURE();
334 }
335
336 int x_offset = flag_offset;
337 int y_offset = flag_offset + x_bytes;
338 last_x = 0;
339 last_y = 0;
340 for (unsigned int i = 0; i < points.size(); ++i) {
341 int dx = points[i].x - last_x;
342 if (dx == 0) {
343 // pass
344 } else if (dx > -256 && dx < 256) {
345 dst[x_offset++] = std::abs(dx);
346 } else {
347 // will always fit for valid input, but overflow is harmless
348 x_offset = Store16(dst, x_offset, dx);
349 }
350 last_x += dx;
351 int dy = points[i].y - last_y;
352 if (dy == 0) {
353 // pass
354 } else if (dy > -256 && dy < 256) {
355 dst[y_offset++] = std::abs(dy);
356 } else {
357 y_offset = Store16(dst, y_offset, dy);
358 }
359 last_y += dy;
360 }
361 *glyph_size = y_offset;
362 return true;
363}
364
365// Compute the bounding box of the coordinates, and store into a glyf buffer.
366// A precondition is that there are at least 10 bytes available.
367void ComputeBbox(const std::vector<Point>& points, uint8_t* dst) {
368 int x_min = 0;
369 int y_min = 0;
370 int x_max = 0;
371 int y_max = 0;
372
373 for (unsigned int i = 0; i < points.size(); ++i) {
374 int x = points[i].x;
375 int y = points[i].y;
376 if (i == 0 || x < x_min) x_min = x;
377 if (i == 0 || x > x_max) x_max = x;
378 if (i == 0 || y < y_min) y_min = y;
379 if (i == 0 || y > y_max) y_max = y;
380 }
381 size_t offset = 2;
382 offset = Store16(dst, offset, x_min);
383 offset = Store16(dst, offset, y_min);
384 offset = Store16(dst, offset, x_max);
385 offset = Store16(dst, offset, y_max);
386}
387
388// Process entire bbox stream. This is done as a separate pass to allow for
389// composite bbox computations (an optional more aggressive transform).
390bool ProcessBboxStream(ots::Buffer* bbox_stream, unsigned int n_glyphs,
391 const std::vector<uint32_t>& loca_values, uint8_t* glyf_buf,
392 size_t glyf_buf_length) {
393 const uint8_t* buf = bbox_stream->buffer();
394 if (n_glyphs >= 65536 || loca_values.size() != n_glyphs + 1) {
395 return OTS_FAILURE();
396 }
397 // Safe because n_glyphs is bounded
398 unsigned int bitmap_length = ((n_glyphs + 31) >> 5) << 2;
399 if (!bbox_stream->Skip(bitmap_length)) {
400 return OTS_FAILURE();
401 }
402 for (unsigned int i = 0; i < n_glyphs; ++i) {
403 if (buf[i >> 3] & (0x80 >> (i & 7))) {
404 uint32_t loca_offset = loca_values[i];
405 if (loca_values[i + 1] - loca_offset < kEndPtsOfContoursOffset) {
406 return OTS_FAILURE();
407 }
408 if (glyf_buf_length < 2 + 10 ||
409 loca_offset > glyf_buf_length - 2 - 10) {
410 return OTS_FAILURE();
411 }
412 if (!bbox_stream->Read(glyf_buf + loca_offset + 2, 8)) {
413 return OTS_FAILURE();
414 }
415 }
416 }
417 return true;
418}
419
420bool ProcessComposite(ots::Buffer* composite_stream, uint8_t* dst,
421 size_t dst_size, size_t* glyph_size, bool* have_instructions) {
422 size_t start_offset = composite_stream->offset();
423 bool we_have_instructions = false;
424
425 uint16_t flags = FLAG_MORE_COMPONENTS;
426 while (flags & FLAG_MORE_COMPONENTS) {
427 if (!composite_stream->ReadU16(&flags)) {
428 return OTS_FAILURE();
429 }
430 we_have_instructions |= (flags & FLAG_WE_HAVE_INSTRUCTIONS) != 0;
431 size_t arg_size = 2; // glyph index
432 if (flags & FLAG_ARG_1_AND_2_ARE_WORDS) {
433 arg_size += 4;
434 } else {
435 arg_size += 2;
436 }
437 if (flags & FLAG_WE_HAVE_A_SCALE) {
438 arg_size += 2;
439 } else if (flags & FLAG_WE_HAVE_AN_X_AND_Y_SCALE) {
440 arg_size += 4;
441 } else if (flags & FLAG_WE_HAVE_A_TWO_BY_TWO) {
442 arg_size += 8;
443 }
444 if (!composite_stream->Skip(arg_size)) {
445 return OTS_FAILURE();
446 }
447 }
448 size_t composite_glyph_size = composite_stream->offset() - start_offset;
449 if (composite_glyph_size + kCompositeGlyphBegin > dst_size) {
450 return OTS_FAILURE();
451 }
452 Store16(dst, 0, 0xffff); // nContours = -1 for composite glyph
453 std::memcpy(dst + kCompositeGlyphBegin,
454 composite_stream->buffer() + start_offset,
455 composite_glyph_size);
456 *glyph_size = kCompositeGlyphBegin + composite_glyph_size;
457 *have_instructions = we_have_instructions;
458 return true;
459}
460
461// Build TrueType loca table
462bool StoreLoca(const std::vector<uint32_t>& loca_values, int index_format,
463 uint8_t* dst, size_t dst_size) {
464 const uint64_t loca_size = loca_values.size();
465 const uint64_t offset_size = index_format ? 4 : 2;
466 if ((loca_size << 2) >> 2 != loca_size) {
467 return OTS_FAILURE();
468 }
469 if (offset_size * loca_size > dst_size) {
470 return OTS_FAILURE();
471 }
472 size_t offset = 0;
473 for (size_t i = 0; i < loca_values.size(); ++i) {
474 uint32_t value = loca_values[i];
475 if (index_format) {
476 offset = StoreU32(dst, offset, value);
477 } else {
478 offset = Store16(dst, offset, value >> 1);
479 }
480 }
481 return true;
482}
483
484// Reconstruct entire glyf table based on transformed original
485bool ReconstructGlyf(const uint8_t* data, size_t data_size,
486 uint8_t* dst, size_t dst_size,
487 uint8_t* loca_buf, size_t loca_size) {
488 static const int kNumSubStreams = 7;
489 ots::Buffer file(data, data_size);
490 uint32_t version;
491 std::vector<std::pair<const uint8_t*, size_t> > substreams(kNumSubStreams);
492
493 if (!file.ReadU32(&version)) {
494 return OTS_FAILURE();
495 }
496 uint16_t num_glyphs;
497 uint16_t index_format;
498 if (!file.ReadU16(&num_glyphs) ||
499 !file.ReadU16(&index_format)) {
500 return OTS_FAILURE();
501 }
502 unsigned int offset = (2 + kNumSubStreams) * 4;
503 if (offset > data_size) {
504 return OTS_FAILURE();
505 }
506 // Invariant from here on: data_size >= offset
507 for (int i = 0; i < kNumSubStreams; ++i) {
508 uint32_t substream_size;
509 if (!file.ReadU32(&substream_size)) {
510 return OTS_FAILURE();
511 }
512 if (substream_size > data_size - offset) {
513 return OTS_FAILURE();
514 }
515 substreams[i] = std::make_pair(data + offset, substream_size);
516 offset += substream_size;
517 }
518 ots::Buffer n_contour_stream(substreams[0].first, substreams[0].second);
519 ots::Buffer n_points_stream(substreams[1].first, substreams[1].second);
520 ots::Buffer flag_stream(substreams[2].first, substreams[2].second);
521 ots::Buffer glyph_stream(substreams[3].first, substreams[3].second);
522 ots::Buffer composite_stream(substreams[4].first, substreams[4].second);
523 ots::Buffer bbox_stream(substreams[5].first, substreams[5].second);
524 ots::Buffer instruction_stream(substreams[6].first, substreams[6].second);
525
526 std::vector<uint32_t> loca_values(num_glyphs + 1);
527 std::vector<unsigned int> n_points_vec;
528 std::vector<Point> points;
529 uint32_t loca_offset = 0;
530 for (unsigned int i = 0; i < num_glyphs; ++i) {
531 size_t glyph_size = 0;
532 uint16_t n_contours = 0;
533 if (!n_contour_stream.ReadU16(&n_contours)) {
534 return OTS_FAILURE();
535 }
536 uint8_t* glyf_dst = dst + loca_offset;
537 size_t glyf_dst_size = dst_size - loca_offset;
538 if (n_contours == 0xffff) {
539 // composite glyph
540 bool have_instructions = false;
541 unsigned int instruction_size = 0;
542 if (!ProcessComposite(&composite_stream, glyf_dst, glyf_dst_size,
543 &glyph_size, &have_instructions)) {
544 return OTS_FAILURE();
545 }
546 if (have_instructions) {
547 if (!Read255UShort(&glyph_stream, &instruction_size)) {
548 return OTS_FAILURE();
549 }
550 if (instruction_size + 2 > glyf_dst_size - glyph_size) {
551 return OTS_FAILURE();
552 }
553 Store16(glyf_dst, glyph_size, instruction_size);
554 if (!instruction_stream.Read(glyf_dst + glyph_size + 2,
555 instruction_size)) {
556 return OTS_FAILURE();
557 }
558 glyph_size += instruction_size + 2;
559 }
560 } else if (n_contours > 0) {
561 // simple glyph
562 n_points_vec.clear();
563 points.clear();
564 unsigned int total_n_points = 0;
565 unsigned int n_points_contour;
566 for (unsigned int j = 0; j < n_contours; ++j) {
567 if (!Read255UShort(&n_points_stream, &n_points_contour)) {
568 return OTS_FAILURE();
569 }
570 n_points_vec.push_back(n_points_contour);
571 if (total_n_points + n_points_contour < total_n_points) {
572 return OTS_FAILURE();
573 }
574 total_n_points += n_points_contour;
575 }
576 unsigned int flag_size = total_n_points;
577 if (flag_size > flag_stream.length() - flag_stream.offset()) {
578 return OTS_FAILURE();
579 }
580 const uint8_t* flags_buf = flag_stream.buffer() + flag_stream.offset();
581 const uint8_t* triplet_buf = glyph_stream.buffer() +
582 glyph_stream.offset();
583 size_t triplet_size = glyph_stream.length() - glyph_stream.offset();
584 size_t triplet_bytes_consumed = 0;
585 if (!TripletDecode(flags_buf, triplet_buf, triplet_size, total_n_points,
586 &points, &triplet_bytes_consumed)) {
587 return OTS_FAILURE();
588 }
589 const uint32_t header_and_endpts_contours_size =
590 kEndPtsOfContoursOffset + 2 * n_contours;
591 if (glyf_dst_size < header_and_endpts_contours_size) {
592 return OTS_FAILURE();
593 }
594 Store16(glyf_dst, 0, n_contours);
595 ComputeBbox(points, glyf_dst);
596 size_t offset = kEndPtsOfContoursOffset;
597 int end_point = -1;
598 for (unsigned int contour_ix = 0; contour_ix < n_contours; ++contour_ix) {
599 end_point += n_points_vec[contour_ix];
600 if (end_point >= 65536) {
601 return OTS_FAILURE();
602 }
603 offset = Store16(glyf_dst, offset, end_point);
604 }
605 if (!flag_stream.Skip(flag_size)) {
606 return OTS_FAILURE();
607 }
608 if (!glyph_stream.Skip(triplet_bytes_consumed)) {
609 return OTS_FAILURE();
610 }
611 unsigned int instruction_size;
612 if (!Read255UShort(&glyph_stream, &instruction_size)) {
613 return OTS_FAILURE();
614 }
615 if (glyf_dst_size - header_and_endpts_contours_size <
616 instruction_size + 2) {
617 return OTS_FAILURE();
618 }
619 uint8_t* instruction_dst = glyf_dst + header_and_endpts_contours_size;
620 Store16(instruction_dst, 0, instruction_size);
621 if (!instruction_stream.Read(instruction_dst + 2, instruction_size)) {
622 return OTS_FAILURE();
623 }
624 if (!StorePoints(points, n_contours, instruction_size,
625 glyf_dst, glyf_dst_size, &glyph_size)) {
626 return OTS_FAILURE();
627 }
628 } else {
629 glyph_size = 0;
630 }
631 loca_values[i] = loca_offset;
632 if (glyph_size + 3 < glyph_size) {
633 return OTS_FAILURE();
634 }
635 glyph_size = Round4(glyph_size);
636 if (glyph_size > dst_size - loca_offset) {
637 // This shouldn't happen, but this test defensively maintains the
638 // invariant that loca_offset <= dst_size.
639 return OTS_FAILURE();
640 }
641 loca_offset += glyph_size;
642 }
643 loca_values[num_glyphs] = loca_offset;
644 if (!ProcessBboxStream(&bbox_stream, num_glyphs, loca_values,
645 dst, dst_size)) {
646 return OTS_FAILURE();
647 }
648 return StoreLoca(loca_values, index_format, loca_buf, loca_size);
649}
650
651// This is linear search, but could be changed to binary because we
652// do have a guarantee that the tables are sorted by tag. But the total
653// cpu time is expected to be very small in any case.
654const Table* FindTable(const std::vector<Table>& tables, uint32_t tag) {
655 size_t n_tables = tables.size();
656 for (size_t i = 0; i < n_tables; ++i) {
657 if (tables[i].tag == tag) {
658 return &tables[i];
659 }
660 }
661 return NULL;
662}
663
664bool ReconstructTransformed(const std::vector<Table>& tables, uint32_t tag,
665 const uint8_t* transformed_buf, size_t transformed_size,
666 uint8_t* dst, size_t dst_length) {
667 if (tag == TAG('g', 'l', 'y', 'f')) {
668 const Table* glyf_table = FindTable(tables, tag);
669 const Table* loca_table = FindTable(tables, TAG('l', 'o', 'c', 'a'));
670 if (glyf_table == NULL || loca_table == NULL) {
671 return OTS_FAILURE();
672 }
673 if (static_cast<uint64_t>(glyf_table->dst_offset + glyf_table->dst_length) >
674 dst_length) {
675 return OTS_FAILURE();
676 }
677 if (static_cast<uint64_t>(loca_table->dst_offset + loca_table->dst_length) >
678 dst_length) {
679 return OTS_FAILURE();
680 }
681 return ReconstructGlyf(transformed_buf, transformed_size,
682 dst + glyf_table->dst_offset, glyf_table->dst_length,
683 dst + loca_table->dst_offset, loca_table->dst_length);
684 } else if (tag == TAG('l', 'o', 'c', 'a')) {
685 // processing was already done by glyf table, but validate
686 if (!FindTable(tables, TAG('g', 'l', 'y', 'f'))) {
687 return OTS_FAILURE();
688 }
689 } else {
690 // transform for the tag is not known
691 return OTS_FAILURE();
692 }
693 return true;
694}
695
696uint32_t ComputeChecksum(const uint8_t* buf, size_t size) {
697 uint32_t checksum = 0;
698 for (size_t i = 0; i < size; i += 4) {
699 // We assume the addition is mod 2^32, which is valid because unsigned
700 checksum += (buf[i] << 24) | (buf[i + 1] << 16) |
701 (buf[i + 2] << 8) | buf[i + 3];
702 }
703 return checksum;
704}
705
706bool FixChecksums(const std::vector<Table>& tables, uint8_t* dst) {
707 const Table* head_table = FindTable(tables, TAG('h', 'e', 'a', 'd'));
708 if (head_table == NULL ||
709 head_table->dst_length < kCheckSumAdjustmentOffset + 4) {
710 return OTS_FAILURE();
711 }
712 size_t adjustment_offset = head_table->dst_offset + kCheckSumAdjustmentOffset;
713 StoreU32(dst, adjustment_offset, 0);
714 size_t n_tables = tables.size();
715 uint32_t file_checksum = 0;
716 for (size_t i = 0; i < n_tables; ++i) {
717 const Table* table = &tables[i];
718 size_t table_length = table->dst_length;
719 uint8_t* table_data = dst + table->dst_offset;
720 uint32_t checksum = ComputeChecksum(table_data, table_length);
721 StoreU32(dst, kSfntHeaderSize + i * kSfntEntrySize + 4, checksum);
722 file_checksum += checksum;
723 }
724 file_checksum += ComputeChecksum(dst,
725 kSfntHeaderSize + kSfntEntrySize * n_tables);
726 uint32_t checksum_adjustment = 0xb1b0afba - file_checksum;
727 StoreU32(dst, adjustment_offset, checksum_adjustment);
728 return true;
729}
730
731bool Woff2Compress(const uint8_t* data, const size_t len,
732 uint32_t compression_type,
733 uint8_t* result, uint32_t* result_len) {
734 if (compression_type == kCompressionTypeBrotli) {
735 size_t compressed_len = *result_len;
Zoltan Szabadka494c85c2014-03-20 14:35:41 +0100736 brotli::BrotliParams params;
737 params.mode = brotli::BrotliParams::MODE_FONT;
738 brotli::BrotliCompressBuffer(params, len, data, &compressed_len, result);
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800739 *result_len = compressed_len;
740 return true;
741 }
742 return false;
743}
744
745bool Woff2Uncompress(uint8_t* dst_buf, size_t dst_size,
746 const uint8_t* src_buf, size_t src_size, uint32_t compression_type) {
747 if (compression_type == kCompressionTypeBrotli) {
748 size_t uncompressed_size = dst_size;
749 int ok = BrotliDecompressBuffer(src_size, src_buf,
750 &uncompressed_size, dst_buf);
751 if (!ok || uncompressed_size != dst_size) {
752 return OTS_FAILURE();
753 }
754 return true;
755 }
756 // Unknown compression type
757 return OTS_FAILURE();
758}
759
760bool ReadLongDirectory(ots::Buffer* file, std::vector<Table>* tables,
761 size_t num_tables) {
762 for (size_t i = 0; i < num_tables; ++i) {
763 Table* table = &(*tables)[i];
764 if (!file->ReadU32(&table->tag) ||
765 !file->ReadU32(&table->flags) ||
766 !file->ReadU32(&table->src_length) ||
767 !file->ReadU32(&table->transform_length) ||
768 !file->ReadU32(&table->dst_length)) {
769 return OTS_FAILURE();
770 }
771 }
772 return true;
773}
774
David Kuettel47c50162014-04-29 17:47:03 -0700775const uint32_t known_tags[63] = {
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800776 TAG('c', 'm', 'a', 'p'), // 0
777 TAG('h', 'e', 'a', 'd'), // 1
778 TAG('h', 'h', 'e', 'a'), // 2
779 TAG('h', 'm', 't', 'x'), // 3
780 TAG('m', 'a', 'x', 'p'), // 4
781 TAG('n', 'a', 'm', 'e'), // 5
782 TAG('O', 'S', '/', '2'), // 6
783 TAG('p', 'o', 's', 't'), // 7
784 TAG('c', 'v', 't', ' '), // 8
785 TAG('f', 'p', 'g', 'm'), // 9
786 TAG('g', 'l', 'y', 'f'), // 10
787 TAG('l', 'o', 'c', 'a'), // 11
788 TAG('p', 'r', 'e', 'p'), // 12
789 TAG('C', 'F', 'F', ' '), // 13
790 TAG('V', 'O', 'R', 'G'), // 14
791 TAG('E', 'B', 'D', 'T'), // 15
792 TAG('E', 'B', 'L', 'C'), // 16
793 TAG('g', 'a', 's', 'p'), // 17
794 TAG('h', 'd', 'm', 'x'), // 18
795 TAG('k', 'e', 'r', 'n'), // 19
796 TAG('L', 'T', 'S', 'H'), // 20
797 TAG('P', 'C', 'L', 'T'), // 21
798 TAG('V', 'D', 'M', 'X'), // 22
799 TAG('v', 'h', 'e', 'a'), // 23
800 TAG('v', 'm', 't', 'x'), // 24
801 TAG('B', 'A', 'S', 'E'), // 25
802 TAG('G', 'D', 'E', 'F'), // 26
803 TAG('G', 'P', 'O', 'S'), // 27
804 TAG('G', 'S', 'U', 'B'), // 28
David Kuettel47c50162014-04-29 17:47:03 -0700805 TAG('E', 'B', 'S', 'C'), // 29
806 TAG('J', 'S', 'T', 'F'), // 30
807 TAG('M', 'A', 'T', 'H'), // 31
808 TAG('C', 'B', 'D', 'T'), // 32
809 TAG('C', 'B', 'L', 'C'), // 33
810 TAG('C', 'O', 'L', 'R'), // 34
811 TAG('C', 'P', 'A', 'L'), // 35
812 TAG('S', 'V', 'G', ' '), // 36
813 TAG('s', 'b', 'i', 'x'), // 37
814 TAG('a', 'c', 'n', 't'), // 38
815 TAG('a', 'v', 'a', 'r'), // 39
816 TAG('b', 'd', 'a', 't'), // 40
817 TAG('b', 'l', 'o', 'c'), // 41
818 TAG('b', 's', 'l', 'n'), // 42
819 TAG('c', 'v', 'a', 'r'), // 43
820 TAG('f', 'd', 's', 'c'), // 44
821 TAG('f', 'e', 'a', 't'), // 45
822 TAG('f', 'm', 't', 'x'), // 46
823 TAG('f', 'v', 'a', 'r'), // 47
824 TAG('g', 'v', 'a', 'r'), // 48
825 TAG('h', 's', 't', 'y'), // 49
826 TAG('j', 'u', 's', 't'), // 50
827 TAG('l', 'c', 'a', 'r'), // 51
828 TAG('m', 'o', 'r', 't'), // 52
829 TAG('m', 'o', 'r', 'x'), // 53
830 TAG('o', 'p', 'b', 'd'), // 54
831 TAG('p', 'r', 'o', 'p'), // 55
832 TAG('t', 'r', 'a', 'k'), // 56
833 TAG('Z', 'a', 'p', 'f'), // 57
834 TAG('S', 'i', 'l', 'f'), // 58
835 TAG('G', 'l', 'a', 't'), // 59
836 TAG('G', 'l', 'o', 'c'), // 60
837 TAG('F', 'e', 'a', 't'), // 61
838 TAG('S', 'i', 'l', 'l'), // 62
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800839};
840
841int KnownTableIndex(uint32_t tag) {
David Kuettel47c50162014-04-29 17:47:03 -0700842 for (int i = 0; i < 63; ++i) {
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800843 if (tag == known_tags[i]) return i;
844 }
David Kuettel47c50162014-04-29 17:47:03 -0700845 return 63;
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800846}
847
848bool ReadShortDirectory(ots::Buffer* file, std::vector<Table>* tables,
849 size_t num_tables) {
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800850 for (size_t i = 0; i < num_tables; ++i) {
851 Table* table = &(*tables)[i];
852 uint8_t flag_byte;
853 if (!file->ReadU8(&flag_byte)) {
854 return OTS_FAILURE();
855 }
856 uint32_t tag;
David Kuettel47c50162014-04-29 17:47:03 -0700857 if ((flag_byte & 0x3f) == 0x3f) {
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800858 if (!file->ReadU32(&tag)) {
859 return OTS_FAILURE();
860 }
861 } else {
David Kuettel47c50162014-04-29 17:47:03 -0700862 tag = known_tags[flag_byte & 0x3f];
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800863 }
David Kuettel47c50162014-04-29 17:47:03 -0700864 // Bits 6 and 7 are reserved and must be 0.
865 if ((flag_byte & 0xC0) != 0) {
Zoltan Szabadka22e2c322014-03-27 16:13:13 +0100866 return OTS_FAILURE();
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800867 }
Zoltan Szabadka22e2c322014-03-27 16:13:13 +0100868 uint32_t flags = kCompressionTypeBrotli;
869 if (i > 0) {
870 flags |= kWoff2FlagsContinueStream;
871 }
David Kuettel47c50162014-04-29 17:47:03 -0700872 // Always transform the glyf and loca tables
873 if (tag == TAG('g', 'l', 'y', 'f') ||
874 tag == TAG('l', 'o', 'c', 'a')) {
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800875 flags |= kWoff2FlagsTransform;
876 }
877 uint32_t dst_length;
878 if (!ReadBase128(file, &dst_length)) {
879 return OTS_FAILURE();
880 }
881 uint32_t transform_length = dst_length;
882 if ((flags & kWoff2FlagsTransform) != 0) {
883 if (!ReadBase128(file, &transform_length)) {
884 return OTS_FAILURE();
885 }
886 }
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800887 table->tag = tag;
888 table->flags = flags;
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800889 table->transform_length = transform_length;
890 table->dst_length = dst_length;
891 }
892 return true;
893}
894
895} // namespace
896
897size_t ComputeWOFF2FinalSize(const uint8_t* data, size_t length) {
898 ots::Buffer file(data, length);
899 uint32_t total_length;
900
901 if (!file.Skip(16) ||
902 !file.ReadU32(&total_length)) {
903 return 0;
904 }
905 return total_length;
906}
907
908bool ConvertWOFF2ToTTF(uint8_t* result, size_t result_length,
909 const uint8_t* data, size_t length) {
910 ots::Buffer file(data, length);
911
912 uint32_t signature;
913 uint32_t flavor;
914 if (!file.ReadU32(&signature) || signature != kWoff2Signature ||
915 !file.ReadU32(&flavor)) {
916 return OTS_FAILURE();
917 }
918
919 // TODO(user): Should call IsValidVersionTag() here.
920
921 uint32_t reported_length;
922 if (!file.ReadU32(&reported_length) || length != reported_length) {
923 return OTS_FAILURE();
924 }
925 uint16_t num_tables;
926 if (!file.ReadU16(&num_tables) || !num_tables) {
927 return OTS_FAILURE();
928 }
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800929 // We don't care about these fields of the header:
Zoltan Szabadka494c85c2014-03-20 14:35:41 +0100930 // uint16_t reserved
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800931 // uint32_t total_sfnt_size
Zoltan Szabadka22e2c322014-03-27 16:13:13 +0100932 if (!file.Skip(6)) {
933 return OTS_FAILURE();
934 }
935 uint32_t compressed_length;
936 if (!file.ReadU32(&compressed_length)) {
937 return OTS_FAILURE();
938 }
939 // We don't care about these fields of the header:
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800940 // uint16_t major_version, minor_version
941 // uint32_t meta_offset, meta_length, meta_orig_length
942 // uint32_t priv_offset, priv_length
Zoltan Szabadka22e2c322014-03-27 16:13:13 +0100943 if (!file.Skip(24)) {
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800944 return OTS_FAILURE();
945 }
946 std::vector<Table> tables(num_tables);
947 // Note: change below to ReadLongDirectory to enable long format.
948 if (!ReadShortDirectory(&file, &tables, num_tables)) {
949 return OTS_FAILURE();
950 }
951 uint64_t src_offset = file.offset();
952 uint64_t dst_offset = kSfntHeaderSize +
953 kSfntEntrySize * static_cast<uint64_t>(num_tables);
954 uint64_t uncompressed_sum = 0;
955 for (uint16_t i = 0; i < num_tables; ++i) {
956 Table* table = &tables[i];
957 table->src_offset = src_offset;
Zoltan Szabadka22e2c322014-03-27 16:13:13 +0100958 table->src_length = (i == 0 ? compressed_length : 0);
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800959 src_offset += table->src_length;
960 if (src_offset > std::numeric_limits<uint32_t>::max()) {
961 return OTS_FAILURE();
962 }
963 src_offset = Round4(src_offset); // TODO: reconsider
964 table->dst_offset = dst_offset;
965 dst_offset += table->dst_length;
966 if (dst_offset > std::numeric_limits<uint32_t>::max()) {
967 return OTS_FAILURE();
968 }
969 dst_offset = Round4(dst_offset);
970 if ((table->flags & kCompressionTypeMask) != kCompressionTypeNone) {
971 uncompressed_sum += table->src_length;
972 if (uncompressed_sum > std::numeric_limits<uint32_t>::max()) {
973 return OTS_FAILURE();
974 }
975 }
976 }
977 // Enforce same 30M limit on uncompressed tables as OTS
978 if (uncompressed_sum > 30 * 1024 * 1024) {
979 return OTS_FAILURE();
980 }
981 if (src_offset > length || dst_offset > result_length) {
982 return OTS_FAILURE();
983 }
984
985 const uint32_t sfnt_header_and_table_directory_size = 12 + 16 * num_tables;
986 if (sfnt_header_and_table_directory_size > result_length) {
987 return OTS_FAILURE();
988 }
989
990 // Start building the font
991 size_t offset = 0;
992 offset = StoreU32(result, offset, flavor);
993 offset = Store16(result, offset, num_tables);
994 unsigned max_pow2 = 0;
995 while (1u << (max_pow2 + 1) <= num_tables) {
996 max_pow2++;
997 }
998 const uint16_t output_search_range = (1u << max_pow2) << 4;
999 offset = Store16(result, offset, output_search_range);
1000 offset = Store16(result, offset, max_pow2);
1001 offset = Store16(result, offset, (num_tables << 4) - output_search_range);
1002 for (uint16_t i = 0; i < num_tables; ++i) {
1003 const Table* table = &tables[i];
1004 offset = StoreU32(result, offset, table->tag);
1005 offset = StoreU32(result, offset, 0); // checksum, to fill in later
1006 offset = StoreU32(result, offset, table->dst_offset);
1007 offset = StoreU32(result, offset, table->dst_length);
1008 }
1009 std::vector<uint8_t> uncompressed_buf;
1010 bool continue_valid = false;
1011 const uint8_t* transform_buf = NULL;
1012 for (uint16_t i = 0; i < num_tables; ++i) {
1013 const Table* table = &tables[i];
1014 uint32_t flags = table->flags;
1015 const uint8_t* src_buf = data + table->src_offset;
1016 uint32_t compression_type = flags & kCompressionTypeMask;
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001017 size_t transform_length = table->transform_length;
1018 if ((flags & kWoff2FlagsContinueStream) != 0) {
1019 if (!continue_valid) {
1020 return OTS_FAILURE();
1021 }
1022 } else if (compression_type == kCompressionTypeNone) {
1023 if (transform_length != table->src_length) {
1024 return OTS_FAILURE();
1025 }
1026 transform_buf = src_buf;
1027 continue_valid = false;
1028 } else if ((flags & kWoff2FlagsContinueStream) == 0) {
1029 uint64_t total_size = transform_length;
1030 for (uint16_t j = i + 1; j < num_tables; ++j) {
1031 if ((tables[j].flags & kWoff2FlagsContinueStream) == 0) {
1032 break;
1033 }
1034 total_size += tables[j].transform_length;
1035 if (total_size > std::numeric_limits<uint32_t>::max()) {
1036 return OTS_FAILURE();
1037 }
1038 }
1039 uncompressed_buf.resize(total_size);
1040 if (!Woff2Uncompress(&uncompressed_buf[0], total_size,
Zoltan Szabadka22e2c322014-03-27 16:13:13 +01001041 src_buf, compressed_length, compression_type)) {
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001042 return OTS_FAILURE();
1043 }
1044 transform_buf = &uncompressed_buf[0];
1045 continue_valid = true;
1046 } else {
1047 return OTS_FAILURE();
1048 }
1049
1050 if ((flags & kWoff2FlagsTransform) == 0) {
1051 if (transform_length != table->dst_length) {
1052 return OTS_FAILURE();
1053 }
1054 if (static_cast<uint64_t>(table->dst_offset + transform_length) >
1055 result_length) {
1056 return OTS_FAILURE();
1057 }
1058 std::memcpy(result + table->dst_offset, transform_buf,
1059 transform_length);
1060 } else {
1061 if (!ReconstructTransformed(tables, table->tag,
1062 transform_buf, transform_length, result, result_length)) {
1063 return OTS_FAILURE();
1064 }
1065 }
1066 if (continue_valid) {
1067 transform_buf += transform_length;
1068 if (transform_buf > uncompressed_buf.data() + uncompressed_buf.size()) {
1069 return OTS_FAILURE();
1070 }
1071 }
1072 }
1073
1074 return FixChecksums(tables, result);
1075}
1076
1077void StoreTableEntry(const Table& table, size_t* offset, uint8_t* dst) {
1078 uint8_t flag_byte = KnownTableIndex(table.tag);
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001079 dst[(*offset)++] = flag_byte;
David Kuettel47c50162014-04-29 17:47:03 -07001080 if ((flag_byte & 0x3f) == 0x3f) {
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001081 StoreU32(table.tag, offset, dst);
1082 }
1083 StoreBase128(table.src_length, offset, dst);
David Kuettel47c50162014-04-29 17:47:03 -07001084 if ((table.flags & kWoff2FlagsTransform) != 0) {
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001085 StoreBase128(table.transform_length, offset, dst);
1086 }
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001087}
1088
1089size_t TableEntrySize(const Table& table) {
1090 size_t size = KnownTableIndex(table.tag) < 31 ? 1 : 5;
1091 size += Base128Size(table.src_length);
1092 if ((table.flags & kWoff2FlagsTransform) != 0) {
David Kuettel47c50162014-04-29 17:47:03 -07001093 size += Base128Size(table.transform_length);
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001094 }
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001095 return size;
1096}
1097
1098size_t ComputeWoff2Length(const std::vector<Table>& tables) {
Zoltan Szabadka22e2c322014-03-27 16:13:13 +01001099 size_t size = kWoff2HeaderSize;
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001100 for (const auto& table : tables) {
1101 size += TableEntrySize(table);
1102 }
1103 for (const auto& table : tables) {
1104 size += table.dst_length;
1105 size = Round4(size);
1106 }
1107 return size;
1108}
1109
1110size_t ComputeTTFLength(const std::vector<Table>& tables) {
1111 size_t size = 12 + 16 * tables.size(); // sfnt header
1112 for (const auto& table : tables) {
1113 size += Round4(table.src_length);
1114 }
1115 return size;
1116}
1117
1118size_t ComputeTotalTransformLength(const Font& font) {
1119 size_t total = 0;
1120 for (const auto& i : font.tables) {
1121 const Font::Table& table = i.second;
1122 if (table.tag & 0x80808080 || !font.FindTable(table.tag ^ 0x80808080)) {
1123 // Count transformed tables and non-transformed tables that do not have
1124 // transformed versions.
1125 total += table.length;
1126 }
1127 }
1128 return total;
1129}
1130
1131struct Woff2ConvertOptions {
1132 uint32_t compression_type;
1133 bool continue_streams;
1134 bool keep_dsig;
1135 bool transform_glyf;
1136
1137 Woff2ConvertOptions()
1138 : compression_type(kCompressionTypeBrotli),
1139 continue_streams(true),
1140 keep_dsig(true),
1141 transform_glyf(true) {}
1142
1143
1144};
1145
1146size_t MaxWOFF2CompressedSize(const uint8_t* data, size_t length) {
1147 // Except for the header size, which is 32 bytes larger in woff2 format,
1148 // all other parts should be smaller (table header in short format,
1149 // transformations and compression). Just to be sure, we will give some
1150 // headroom anyway.
1151 return length + 1024;
1152}
1153
1154bool ConvertTTFToWOFF2(const uint8_t *data, size_t length,
1155 uint8_t *result, size_t *result_length) {
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001156 Woff2ConvertOptions options;
1157
1158 Font font;
1159 if (!ReadFont(data, length, &font)) {
1160 fprintf(stderr, "Parsing of the input font failed.\n");
1161 return false;
1162 }
1163
1164 if (!NormalizeFont(&font)) {
1165 fprintf(stderr, "Font normalization failed.\n");
1166 return false;
1167 }
1168
1169 if (!options.keep_dsig) {
1170 font.tables.erase(TAG('D', 'S', 'I', 'G'));
1171 }
1172
1173 if (options.transform_glyf &&
1174 !TransformGlyfAndLocaTables(&font)) {
1175 fprintf(stderr, "Font transformation failed.\n");
1176 return false;
1177 }
1178
1179 const Font::Table* head_table = font.FindTable(kHeadTableTag);
1180 if (head_table == NULL) {
1181 fprintf(stderr, "Missing head table.\n");
1182 return false;
1183 }
1184
1185 // Although the compressed size of each table in the final woff2 file won't
1186 // be larger than its transform_length, we have to allocate a large enough
1187 // buffer for the compressor, since the compressor can potentially increase
1188 // the size. If the compressor overflows this, it should return false and
1189 // then this function will also return false.
1190 size_t total_transform_length = ComputeTotalTransformLength(font);
1191 size_t compression_buffer_size = 1.2 * total_transform_length + 10240;
1192 std::vector<uint8_t> compression_buf(compression_buffer_size);
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001193 uint32_t total_compressed_length = compression_buffer_size;
1194
Zoltan Szabadka22e2c322014-03-27 16:13:13 +01001195 // Collect all transformed data into one place.
1196 std::vector<uint8_t> transform_buf(total_transform_length);
1197 size_t transform_offset = 0;
1198 for (const auto& i : font.tables) {
1199 if (i.second.tag & 0x80808080) continue;
1200 const Font::Table* table = font.FindTable(i.second.tag ^ 0x80808080);
1201 if (table == NULL) table = &i.second;
1202 StoreBytes(table->data, table->length,
1203 &transform_offset, &transform_buf[0]);
1204 }
1205 // Compress all transformed data in one stream.
1206 if (!Woff2Compress(transform_buf.data(), total_transform_length,
1207 options.compression_type,
1208 &compression_buf[0],
1209 &total_compressed_length)) {
1210 fprintf(stderr, "Compression of combined table failed.\n");
1211 return false;
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001212 }
1213
1214 std::vector<Table> tables;
1215 for (const auto& i : font.tables) {
1216 const Font::Table& src_table = i.second;
1217 if (src_table.tag & 0x80808080) {
1218 // This is a transformed table, we will write it together with the
1219 // original version.
1220 continue;
1221 }
1222 Table table;
1223 table.tag = src_table.tag;
Zoltan Szabadka494c85c2014-03-20 14:35:41 +01001224 table.flags = options.compression_type;
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001225 table.src_length = src_table.length;
1226 table.transform_length = src_table.length;
1227 const uint8_t* transformed_data = src_table.data;
1228 const Font::Table* transformed_table =
1229 font.FindTable(src_table.tag ^ 0x80808080);
1230 if (transformed_table != NULL) {
1231 table.flags |= kWoff2FlagsTransform;
1232 table.transform_length = transformed_table->length;
1233 transformed_data = transformed_table->data;
1234 }
Zoltan Szabadka22e2c322014-03-27 16:13:13 +01001235 if (tables.empty()) {
1236 table.dst_length = total_compressed_length;
1237 table.dst_data = &compression_buf[0];
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001238 } else {
Zoltan Szabadka22e2c322014-03-27 16:13:13 +01001239 table.dst_length = 0;
1240 table.dst_data = NULL;
1241 table.flags |= kWoff2FlagsContinueStream;
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001242 }
1243 tables.push_back(table);
1244 }
1245
1246 size_t woff2_length = ComputeWoff2Length(tables);
1247 if (woff2_length > *result_length) {
1248 fprintf(stderr, "Result allocation was too small (%zd vs %zd bytes).\n",
1249 *result_length, woff2_length);
1250 return false;
1251 }
1252 *result_length = woff2_length;
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001253
1254 size_t offset = 0;
1255 StoreU32(kWoff2Signature, &offset, result);
1256 StoreU32(font.flavor, &offset, result);
1257 StoreU32(woff2_length, &offset, result);
1258 Store16(tables.size(), &offset, result);
Zoltan Szabadka494c85c2014-03-20 14:35:41 +01001259 Store16(0, &offset, result); // reserved
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001260 StoreU32(ComputeTTFLength(tables), &offset, result);
Zoltan Szabadka22e2c322014-03-27 16:13:13 +01001261 StoreU32(total_compressed_length, &offset, result);
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001262 StoreBytes(head_table->data + 4, 4, &offset, result); // font revision
1263 StoreU32(0, &offset, result); // metaOffset
1264 StoreU32(0, &offset, result); // metaLength
1265 StoreU32(0, &offset, result); // metaOrigLength
1266 StoreU32(0, &offset, result); // privOffset
1267 StoreU32(0, &offset, result); // privLength
1268 for (const auto& table : tables) {
1269 StoreTableEntry(table, &offset, result);
1270 }
1271 for (const auto& table : tables) {
1272 StoreBytes(table.dst_data, table.dst_length, &offset, result);
1273 offset = Round4(offset);
1274 }
1275 if (*result_length != offset) {
1276 fprintf(stderr, "Mismatch between computed and actual length "
1277 "(%zd vs %zd)\n", *result_length, offset);
1278 return false;
1279 }
1280 return true;
1281}
1282
1283} // namespace woff2