blob: 1625c004859a382398d2b845522152d90c131865 [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
81const size_t kWoff2HeaderSize = 44;
82const 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
775const uint32_t known_tags[29] = {
776 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
805};
806
807int KnownTableIndex(uint32_t tag) {
808 for (int i = 0; i < 29; ++i) {
809 if (tag == known_tags[i]) return i;
810 }
811 return 31;
812}
813
814bool ReadShortDirectory(ots::Buffer* file, std::vector<Table>* tables,
815 size_t num_tables) {
816 uint32_t last_compression_type = 0;
817 for (size_t i = 0; i < num_tables; ++i) {
818 Table* table = &(*tables)[i];
819 uint8_t flag_byte;
820 if (!file->ReadU8(&flag_byte)) {
821 return OTS_FAILURE();
822 }
823 uint32_t tag;
824 if ((flag_byte & 0x1f) == 0x1f) {
825 if (!file->ReadU32(&tag)) {
826 return OTS_FAILURE();
827 }
828 } else {
829 if ((flag_byte & 0x1f) >= (sizeof(known_tags) / sizeof(known_tags[0]))) {
830 return OTS_FAILURE();
831 }
832 tag = known_tags[flag_byte & 0x1f];
833 }
834 uint32_t flags = flag_byte >> 6;
835 if (flags == kShortFlagsContinue) {
836 flags = last_compression_type | kWoff2FlagsContinueStream;
837 } else {
838 if (flags == kCompressionTypeNone ||
839 flags == kCompressionTypeGzip ||
Zoltan Szabadka494c85c2014-03-20 14:35:41 +0100840 flags == kCompressionTypeBrotli) {
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800841 last_compression_type = flags;
842 } else {
843 return OTS_FAILURE();
844 }
845 }
846 if ((flag_byte & 0x20) != 0) {
847 flags |= kWoff2FlagsTransform;
848 }
849 uint32_t dst_length;
850 if (!ReadBase128(file, &dst_length)) {
851 return OTS_FAILURE();
852 }
853 uint32_t transform_length = dst_length;
854 if ((flags & kWoff2FlagsTransform) != 0) {
855 if (!ReadBase128(file, &transform_length)) {
856 return OTS_FAILURE();
857 }
858 }
859 uint32_t src_length = transform_length;
860 if ((flag_byte >> 6) == 1 || (flag_byte >> 6) == 2) {
861 if (!ReadBase128(file, &src_length)) {
862 return OTS_FAILURE();
863 }
864 } else if ((flag_byte >> 6) == kShortFlagsContinue) {
865 // The compressed data for this table is in a previuos table, so we set
866 // the src_length to zero.
867 src_length = 0;
868 }
869 table->tag = tag;
870 table->flags = flags;
871 table->src_length = src_length;
872 table->transform_length = transform_length;
873 table->dst_length = dst_length;
874 }
875 return true;
876}
877
878} // namespace
879
880size_t ComputeWOFF2FinalSize(const uint8_t* data, size_t length) {
881 ots::Buffer file(data, length);
882 uint32_t total_length;
883
884 if (!file.Skip(16) ||
885 !file.ReadU32(&total_length)) {
886 return 0;
887 }
888 return total_length;
889}
890
891bool ConvertWOFF2ToTTF(uint8_t* result, size_t result_length,
892 const uint8_t* data, size_t length) {
893 ots::Buffer file(data, length);
894
895 uint32_t signature;
896 uint32_t flavor;
897 if (!file.ReadU32(&signature) || signature != kWoff2Signature ||
898 !file.ReadU32(&flavor)) {
899 return OTS_FAILURE();
900 }
901
902 // TODO(user): Should call IsValidVersionTag() here.
903
904 uint32_t reported_length;
905 if (!file.ReadU32(&reported_length) || length != reported_length) {
906 return OTS_FAILURE();
907 }
908 uint16_t num_tables;
909 if (!file.ReadU16(&num_tables) || !num_tables) {
910 return OTS_FAILURE();
911 }
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800912 // We don't care about these fields of the header:
Zoltan Szabadka494c85c2014-03-20 14:35:41 +0100913 // uint16_t reserved
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800914 // uint32_t total_sfnt_size
915 // uint16_t major_version, minor_version
916 // uint32_t meta_offset, meta_length, meta_orig_length
917 // uint32_t priv_offset, priv_length
Zoltan Szabadka494c85c2014-03-20 14:35:41 +0100918 if (!file.Skip(30)) {
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800919 return OTS_FAILURE();
920 }
921 std::vector<Table> tables(num_tables);
922 // Note: change below to ReadLongDirectory to enable long format.
923 if (!ReadShortDirectory(&file, &tables, num_tables)) {
924 return OTS_FAILURE();
925 }
926 uint64_t src_offset = file.offset();
927 uint64_t dst_offset = kSfntHeaderSize +
928 kSfntEntrySize * static_cast<uint64_t>(num_tables);
929 uint64_t uncompressed_sum = 0;
930 for (uint16_t i = 0; i < num_tables; ++i) {
931 Table* table = &tables[i];
932 table->src_offset = src_offset;
933 src_offset += table->src_length;
934 if (src_offset > std::numeric_limits<uint32_t>::max()) {
935 return OTS_FAILURE();
936 }
937 src_offset = Round4(src_offset); // TODO: reconsider
938 table->dst_offset = dst_offset;
939 dst_offset += table->dst_length;
940 if (dst_offset > std::numeric_limits<uint32_t>::max()) {
941 return OTS_FAILURE();
942 }
943 dst_offset = Round4(dst_offset);
944 if ((table->flags & kCompressionTypeMask) != kCompressionTypeNone) {
945 uncompressed_sum += table->src_length;
946 if (uncompressed_sum > std::numeric_limits<uint32_t>::max()) {
947 return OTS_FAILURE();
948 }
949 }
950 }
951 // Enforce same 30M limit on uncompressed tables as OTS
952 if (uncompressed_sum > 30 * 1024 * 1024) {
953 return OTS_FAILURE();
954 }
955 if (src_offset > length || dst_offset > result_length) {
956 return OTS_FAILURE();
957 }
958
959 const uint32_t sfnt_header_and_table_directory_size = 12 + 16 * num_tables;
960 if (sfnt_header_and_table_directory_size > result_length) {
961 return OTS_FAILURE();
962 }
963
964 // Start building the font
965 size_t offset = 0;
966 offset = StoreU32(result, offset, flavor);
967 offset = Store16(result, offset, num_tables);
968 unsigned max_pow2 = 0;
969 while (1u << (max_pow2 + 1) <= num_tables) {
970 max_pow2++;
971 }
972 const uint16_t output_search_range = (1u << max_pow2) << 4;
973 offset = Store16(result, offset, output_search_range);
974 offset = Store16(result, offset, max_pow2);
975 offset = Store16(result, offset, (num_tables << 4) - output_search_range);
976 for (uint16_t i = 0; i < num_tables; ++i) {
977 const Table* table = &tables[i];
978 offset = StoreU32(result, offset, table->tag);
979 offset = StoreU32(result, offset, 0); // checksum, to fill in later
980 offset = StoreU32(result, offset, table->dst_offset);
981 offset = StoreU32(result, offset, table->dst_length);
982 }
983 std::vector<uint8_t> uncompressed_buf;
984 bool continue_valid = false;
985 const uint8_t* transform_buf = NULL;
986 for (uint16_t i = 0; i < num_tables; ++i) {
987 const Table* table = &tables[i];
988 uint32_t flags = table->flags;
989 const uint8_t* src_buf = data + table->src_offset;
990 uint32_t compression_type = flags & kCompressionTypeMask;
Roderick Sheeter437bbad2013-11-19 14:32:56 -0800991 size_t transform_length = table->transform_length;
992 if ((flags & kWoff2FlagsContinueStream) != 0) {
993 if (!continue_valid) {
994 return OTS_FAILURE();
995 }
996 } else if (compression_type == kCompressionTypeNone) {
997 if (transform_length != table->src_length) {
998 return OTS_FAILURE();
999 }
1000 transform_buf = src_buf;
1001 continue_valid = false;
1002 } else if ((flags & kWoff2FlagsContinueStream) == 0) {
1003 uint64_t total_size = transform_length;
1004 for (uint16_t j = i + 1; j < num_tables; ++j) {
1005 if ((tables[j].flags & kWoff2FlagsContinueStream) == 0) {
1006 break;
1007 }
1008 total_size += tables[j].transform_length;
1009 if (total_size > std::numeric_limits<uint32_t>::max()) {
1010 return OTS_FAILURE();
1011 }
1012 }
1013 uncompressed_buf.resize(total_size);
1014 if (!Woff2Uncompress(&uncompressed_buf[0], total_size,
1015 src_buf, table->src_length, compression_type)) {
1016 return OTS_FAILURE();
1017 }
1018 transform_buf = &uncompressed_buf[0];
1019 continue_valid = true;
1020 } else {
1021 return OTS_FAILURE();
1022 }
1023
1024 if ((flags & kWoff2FlagsTransform) == 0) {
1025 if (transform_length != table->dst_length) {
1026 return OTS_FAILURE();
1027 }
1028 if (static_cast<uint64_t>(table->dst_offset + transform_length) >
1029 result_length) {
1030 return OTS_FAILURE();
1031 }
1032 std::memcpy(result + table->dst_offset, transform_buf,
1033 transform_length);
1034 } else {
1035 if (!ReconstructTransformed(tables, table->tag,
1036 transform_buf, transform_length, result, result_length)) {
1037 return OTS_FAILURE();
1038 }
1039 }
1040 if (continue_valid) {
1041 transform_buf += transform_length;
1042 if (transform_buf > uncompressed_buf.data() + uncompressed_buf.size()) {
1043 return OTS_FAILURE();
1044 }
1045 }
1046 }
1047
1048 return FixChecksums(tables, result);
1049}
1050
1051void StoreTableEntry(const Table& table, size_t* offset, uint8_t* dst) {
1052 uint8_t flag_byte = KnownTableIndex(table.tag);
1053 if ((table.flags & kWoff2FlagsTransform) != 0) {
1054 flag_byte |= 0x20;
1055 }
1056 if ((table.flags & kWoff2FlagsContinueStream) != 0) {
1057 flag_byte |= 0xc0;
1058 } else {
1059 flag_byte |= ((table.flags & 3) << 6);
1060 }
1061 dst[(*offset)++] = flag_byte;
1062 if ((flag_byte & 0x1f) == 0x1f) {
1063 StoreU32(table.tag, offset, dst);
1064 }
1065 StoreBase128(table.src_length, offset, dst);
1066 if ((flag_byte & 0x20) != 0) {
1067 StoreBase128(table.transform_length, offset, dst);
1068 }
1069 if ((flag_byte & 0xc0) == 0x40 || (flag_byte & 0xc0) == 0x80) {
1070 StoreBase128(table.dst_length, offset, dst);
1071 }
1072}
1073
1074size_t TableEntrySize(const Table& table) {
1075 size_t size = KnownTableIndex(table.tag) < 31 ? 1 : 5;
1076 size += Base128Size(table.src_length);
1077 if ((table.flags & kWoff2FlagsTransform) != 0) {
1078 size += Base128Size(table.transform_length);
1079 }
1080 if ((table.flags & kWoff2FlagsContinueStream) == 0 &&
1081 ((table.flags & 3) == kCompressionTypeGzip ||
Zoltan Szabadka494c85c2014-03-20 14:35:41 +01001082 (table.flags & 3) == kCompressionTypeBrotli)) {
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001083 size += Base128Size(table.dst_length);
1084 }
1085 return size;
1086}
1087
1088size_t ComputeWoff2Length(const std::vector<Table>& tables) {
1089 size_t size = 44; // header size
1090 for (const auto& table : tables) {
1091 size += TableEntrySize(table);
1092 }
1093 for (const auto& table : tables) {
1094 size += table.dst_length;
1095 size = Round4(size);
1096 }
1097 return size;
1098}
1099
1100size_t ComputeTTFLength(const std::vector<Table>& tables) {
1101 size_t size = 12 + 16 * tables.size(); // sfnt header
1102 for (const auto& table : tables) {
1103 size += Round4(table.src_length);
1104 }
1105 return size;
1106}
1107
1108size_t ComputeTotalTransformLength(const Font& font) {
1109 size_t total = 0;
1110 for (const auto& i : font.tables) {
1111 const Font::Table& table = i.second;
1112 if (table.tag & 0x80808080 || !font.FindTable(table.tag ^ 0x80808080)) {
1113 // Count transformed tables and non-transformed tables that do not have
1114 // transformed versions.
1115 total += table.length;
1116 }
1117 }
1118 return total;
1119}
1120
1121struct Woff2ConvertOptions {
1122 uint32_t compression_type;
1123 bool continue_streams;
1124 bool keep_dsig;
1125 bool transform_glyf;
1126
1127 Woff2ConvertOptions()
1128 : compression_type(kCompressionTypeBrotli),
1129 continue_streams(true),
1130 keep_dsig(true),
1131 transform_glyf(true) {}
1132
1133
1134};
1135
1136size_t MaxWOFF2CompressedSize(const uint8_t* data, size_t length) {
1137 // Except for the header size, which is 32 bytes larger in woff2 format,
1138 // all other parts should be smaller (table header in short format,
1139 // transformations and compression). Just to be sure, we will give some
1140 // headroom anyway.
1141 return length + 1024;
1142}
1143
1144bool ConvertTTFToWOFF2(const uint8_t *data, size_t length,
1145 uint8_t *result, size_t *result_length) {
1146
1147 Woff2ConvertOptions options;
1148
1149 Font font;
1150 if (!ReadFont(data, length, &font)) {
1151 fprintf(stderr, "Parsing of the input font failed.\n");
1152 return false;
1153 }
1154
1155 if (!NormalizeFont(&font)) {
1156 fprintf(stderr, "Font normalization failed.\n");
1157 return false;
1158 }
1159
1160 if (!options.keep_dsig) {
1161 font.tables.erase(TAG('D', 'S', 'I', 'G'));
1162 }
1163
1164 if (options.transform_glyf &&
1165 !TransformGlyfAndLocaTables(&font)) {
1166 fprintf(stderr, "Font transformation failed.\n");
1167 return false;
1168 }
1169
1170 const Font::Table* head_table = font.FindTable(kHeadTableTag);
1171 if (head_table == NULL) {
1172 fprintf(stderr, "Missing head table.\n");
1173 return false;
1174 }
1175
1176 // Although the compressed size of each table in the final woff2 file won't
1177 // be larger than its transform_length, we have to allocate a large enough
1178 // buffer for the compressor, since the compressor can potentially increase
1179 // the size. If the compressor overflows this, it should return false and
1180 // then this function will also return false.
1181 size_t total_transform_length = ComputeTotalTransformLength(font);
1182 size_t compression_buffer_size = 1.2 * total_transform_length + 10240;
1183 std::vector<uint8_t> compression_buf(compression_buffer_size);
1184 size_t compression_buf_offset = 0;
1185 uint32_t total_compressed_length = compression_buffer_size;
1186
1187 if (options.continue_streams) {
1188 // Collect all transformed data into one place.
1189 std::vector<uint8_t> transform_buf(total_transform_length);
1190 size_t transform_offset = 0;
1191 for (const auto& i : font.tables) {
1192 if (i.second.tag & 0x80808080) continue;
1193 const Font::Table* table = font.FindTable(i.second.tag ^ 0x80808080);
1194 if (table == NULL) table = &i.second;
1195 StoreBytes(table->data, table->length,
1196 &transform_offset, &transform_buf[0]);
1197 }
1198 // Compress all transformed data in one stream.
1199 if (!Woff2Compress(transform_buf.data(), total_transform_length,
1200 options.compression_type,
1201 &compression_buf[0],
1202 &total_compressed_length)) {
1203 fprintf(stderr, "Compression of combined table failed.\n");
1204 return false;
1205 }
1206 }
1207
1208 std::vector<Table> tables;
1209 for (const auto& i : font.tables) {
1210 const Font::Table& src_table = i.second;
1211 if (src_table.tag & 0x80808080) {
1212 // This is a transformed table, we will write it together with the
1213 // original version.
1214 continue;
1215 }
1216 Table table;
1217 table.tag = src_table.tag;
Zoltan Szabadka494c85c2014-03-20 14:35:41 +01001218 table.flags = options.compression_type;
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001219 table.src_length = src_table.length;
1220 table.transform_length = src_table.length;
1221 const uint8_t* transformed_data = src_table.data;
1222 const Font::Table* transformed_table =
1223 font.FindTable(src_table.tag ^ 0x80808080);
1224 if (transformed_table != NULL) {
1225 table.flags |= kWoff2FlagsTransform;
1226 table.transform_length = transformed_table->length;
1227 transformed_data = transformed_table->data;
1228 }
1229 if (options.continue_streams) {
1230 if (tables.empty()) {
1231 table.dst_length = total_compressed_length;
1232 table.dst_data = &compression_buf[0];
1233 } else {
1234 table.dst_length = 0;
1235 table.dst_data = NULL;
1236 table.flags |= kWoff2FlagsContinueStream;
1237 }
1238 } else {
1239 table.dst_length = table.transform_length;
1240 table.dst_data = transformed_data;
1241 if (options.compression_type != kCompressionTypeNone) {
1242 uint32_t compressed_length =
1243 compression_buf.size() - compression_buf_offset;
1244 if (!Woff2Compress(transformed_data, table.transform_length,
1245 options.compression_type,
1246 &compression_buf[compression_buf_offset],
1247 &compressed_length)) {
1248 fprintf(stderr, "Compression of table %x failed.\n", src_table.tag);
1249 return false;
1250 }
1251 if (compressed_length >= table.transform_length) {
1252 table.flags &= (~3); // no compression
1253 } else {
1254 table.dst_length = compressed_length;
1255 table.dst_data = &compression_buf[compression_buf_offset];
1256 compression_buf_offset += table.dst_length;
1257 }
1258 }
1259 }
1260 tables.push_back(table);
1261 }
1262
1263 size_t woff2_length = ComputeWoff2Length(tables);
1264 if (woff2_length > *result_length) {
1265 fprintf(stderr, "Result allocation was too small (%zd vs %zd bytes).\n",
1266 *result_length, woff2_length);
1267 return false;
1268 }
1269 *result_length = woff2_length;
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001270
1271 size_t offset = 0;
1272 StoreU32(kWoff2Signature, &offset, result);
1273 StoreU32(font.flavor, &offset, result);
1274 StoreU32(woff2_length, &offset, result);
1275 Store16(tables.size(), &offset, result);
Zoltan Szabadka494c85c2014-03-20 14:35:41 +01001276 Store16(0, &offset, result); // reserved
Roderick Sheeter437bbad2013-11-19 14:32:56 -08001277 StoreU32(ComputeTTFLength(tables), &offset, result);
1278 StoreBytes(head_table->data + 4, 4, &offset, result); // font revision
1279 StoreU32(0, &offset, result); // metaOffset
1280 StoreU32(0, &offset, result); // metaLength
1281 StoreU32(0, &offset, result); // metaOrigLength
1282 StoreU32(0, &offset, result); // privOffset
1283 StoreU32(0, &offset, result); // privLength
1284 for (const auto& table : tables) {
1285 StoreTableEntry(table, &offset, result);
1286 }
1287 for (const auto& table : tables) {
1288 StoreBytes(table.dst_data, table.dst_length, &offset, result);
1289 offset = Round4(offset);
1290 }
1291 if (*result_length != offset) {
1292 fprintf(stderr, "Mismatch between computed and actual length "
1293 "(%zd vs %zd)\n", *result_length, offset);
1294 return false;
1295 }
1296 return true;
1297}
1298
1299} // namespace woff2