Home | History | Annotate | Download | only in woff2
      1 // Copyright 2014 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_enc.h"
     18 
     19 #include <stdlib.h>
     20 #include <complex>
     21 #include <cstring>
     22 #include <limits>
     23 #include <string>
     24 #include <vector>
     25 
     26 #include "./buffer.h"
     27 #include "./encode.h"
     28 #include "./font.h"
     29 #include "./normalize.h"
     30 #include "./round.h"
     31 #include "./store_bytes.h"
     32 #include "./table_tags.h"
     33 #include "./transform.h"
     34 #include "./woff2_common.h"
     35 
     36 namespace woff2 {
     37 
     38 namespace {
     39 
     40 using std::string;
     41 using std::vector;
     42 
     43 
     44 const size_t kWoff2HeaderSize = 48;
     45 const size_t kWoff2EntrySize = 20;
     46 
     47 size_t Base128Size(size_t n) {
     48   size_t size = 1;
     49   for (; n >= 128; n >>= 7) ++size;
     50   return size;
     51 }
     52 
     53 void StoreBase128(size_t len, size_t* offset, uint8_t* dst) {
     54   size_t size = Base128Size(len);
     55   for (int i = 0; i < size; ++i) {
     56     int b = (int)(len >> (7 * (size - i - 1))) & 0x7f;
     57     if (i < size - 1) {
     58       b |= 0x80;
     59     }
     60     dst[(*offset)++] = b;
     61   }
     62 }
     63 
     64 bool Woff2Compress(const uint8_t* data, const size_t len,
     65                    uint8_t* result, uint32_t* result_len) {
     66   size_t compressed_len = *result_len;
     67   brotli::BrotliParams params;
     68   params.mode = brotli::BrotliParams::MODE_FONT;
     69   brotli::BrotliCompressBuffer(params, len, data, &compressed_len, result);
     70   *result_len = compressed_len;
     71   return true;
     72 }
     73 
     74 bool ReadLongDirectory(Buffer* file, std::vector<Table>* tables,
     75     size_t num_tables) {
     76   for (size_t i = 0; i < num_tables; ++i) {
     77     Table* table = &(*tables)[i];
     78     if (!file->ReadU32(&table->tag) ||
     79         !file->ReadU32(&table->flags) ||
     80         !file->ReadU32(&table->src_length) ||
     81         !file->ReadU32(&table->transform_length) ||
     82         !file->ReadU32(&table->dst_length)) {
     83       return FONT_COMPRESSION_FAILURE();
     84     }
     85   }
     86   return true;
     87 }
     88 
     89 int KnownTableIndex(uint32_t tag) {
     90   for (int i = 0; i < 63; ++i) {
     91     if (tag == kKnownTags[i]) return i;
     92   }
     93   return 63;
     94 }
     95 
     96 void StoreTableEntry(const Table& table, size_t* offset, uint8_t* dst) {
     97   uint8_t flag_byte = KnownTableIndex(table.tag);
     98   dst[(*offset)++] = flag_byte;
     99   if ((flag_byte & 0x3f) == 0x3f) {
    100     StoreU32(table.tag, offset, dst);
    101   }
    102   StoreBase128(table.src_length, offset, dst);
    103   if ((table.flags & kWoff2FlagsTransform) != 0) {
    104     StoreBase128(table.transform_length, offset, dst);
    105   }
    106 }
    107 
    108 size_t TableEntrySize(const Table& table) {
    109   size_t size = KnownTableIndex(table.tag) < 31 ? 1 : 5;
    110   size += Base128Size(table.src_length);
    111   if ((table.flags & kWoff2FlagsTransform) != 0) {
    112      size += Base128Size(table.transform_length);
    113   }
    114   return size;
    115 }
    116 
    117 size_t ComputeWoff2Length(const std::vector<Table>& tables) {
    118   size_t size = kWoff2HeaderSize;
    119   for (const auto& table : tables) {
    120     size += TableEntrySize(table);
    121   }
    122   for (const auto& table : tables) {
    123     size += table.dst_length;
    124     size = Round4(size);
    125   }
    126   return size;
    127 }
    128 
    129 size_t ComputeTTFLength(const std::vector<Table>& tables) {
    130   size_t size = 12 + 16 * tables.size();  // sfnt header
    131   for (const auto& table : tables) {
    132     size += Round4(table.src_length);
    133   }
    134   return size;
    135 }
    136 
    137 size_t ComputeTotalTransformLength(const Font& font) {
    138   size_t total = 0;
    139   for (const auto& i : font.tables) {
    140     const Font::Table& table = i.second;
    141     if (table.tag & 0x80808080 || !font.FindTable(table.tag ^ 0x80808080)) {
    142       // Count transformed tables and non-transformed tables that do not have
    143       // transformed versions.
    144       total += table.length;
    145     }
    146   }
    147   return total;
    148 }
    149 
    150 }  // namespace
    151 
    152 size_t MaxWOFF2CompressedSize(const uint8_t* data, size_t length) {
    153   // Except for the header size, which is 32 bytes larger in woff2 format,
    154   // all other parts should be smaller (table header in short format,
    155   // transformations and compression). Just to be sure, we will give some
    156   // headroom anyway.
    157   return length + 1024;
    158 }
    159 
    160 bool ConvertTTFToWOFF2(const uint8_t *data, size_t length,
    161                        uint8_t *result, size_t *result_length) {
    162   Font font;
    163   if (!ReadFont(data, length, &font)) {
    164     fprintf(stderr, "Parsing of the input font failed.\n");
    165     return false;
    166   }
    167 
    168   if (!NormalizeFont(&font)) {
    169     fprintf(stderr, "Font normalization failed.\n");
    170     return false;
    171   }
    172 
    173   if (!TransformGlyfAndLocaTables(&font)) {
    174     fprintf(stderr, "Font transformation failed.\n");
    175     return false;
    176   }
    177 
    178   const Font::Table* head_table = font.FindTable(kHeadTableTag);
    179   if (head_table == NULL) {
    180     fprintf(stderr, "Missing head table.\n");
    181     return false;
    182   }
    183 
    184   // Although the compressed size of each table in the final woff2 file won't
    185   // be larger than its transform_length, we have to allocate a large enough
    186   // buffer for the compressor, since the compressor can potentially increase
    187   // the size. If the compressor overflows this, it should return false and
    188   // then this function will also return false.
    189   size_t total_transform_length = ComputeTotalTransformLength(font);
    190   size_t compression_buffer_size = 1.2 * total_transform_length + 10240;
    191   std::vector<uint8_t> compression_buf(compression_buffer_size);
    192   uint32_t total_compressed_length = compression_buffer_size;
    193 
    194   // Collect all transformed data into one place.
    195   std::vector<uint8_t> transform_buf(total_transform_length);
    196   size_t transform_offset = 0;
    197   for (const auto& i : font.tables) {
    198     if (i.second.tag & 0x80808080) continue;
    199     const Font::Table* table = font.FindTable(i.second.tag ^ 0x80808080);
    200     if (table == NULL) table = &i.second;
    201     StoreBytes(table->data, table->length,
    202                &transform_offset, &transform_buf[0]);
    203   }
    204   // Compress all transformed data in one stream.
    205   if (!Woff2Compress(transform_buf.data(), total_transform_length,
    206                      &compression_buf[0],
    207                      &total_compressed_length)) {
    208     fprintf(stderr, "Compression of combined table failed.\n");
    209     return false;
    210   }
    211 
    212   std::vector<Table> tables;
    213   for (const auto& i : font.tables) {
    214     const Font::Table& src_table = i.second;
    215     if (src_table.tag & 0x80808080) {
    216       // This is a transformed table, we will write it together with the
    217       // original version.
    218       continue;
    219     }
    220     Table table;
    221     table.tag = src_table.tag;
    222     table.flags = 0;
    223     table.src_length = src_table.length;
    224     table.transform_length = src_table.length;
    225     const uint8_t* transformed_data = src_table.data;
    226     const Font::Table* transformed_table =
    227         font.FindTable(src_table.tag ^ 0x80808080);
    228     if (transformed_table != NULL) {
    229       table.flags |= kWoff2FlagsTransform;
    230       table.transform_length = transformed_table->length;
    231       transformed_data = transformed_table->data;
    232     }
    233     if (tables.empty()) {
    234       table.dst_length = total_compressed_length;
    235       table.dst_data = &compression_buf[0];
    236     } else {
    237       table.dst_length = 0;
    238       table.dst_data = NULL;
    239       table.flags |= kWoff2FlagsContinueStream;
    240     }
    241     tables.push_back(table);
    242   }
    243 
    244   size_t woff2_length = ComputeWoff2Length(tables);
    245   if (woff2_length > *result_length) {
    246     fprintf(stderr, "Result allocation was too small (%zd vs %zd bytes).\n",
    247            *result_length, woff2_length);
    248     return false;
    249   }
    250   *result_length = woff2_length;
    251 
    252   size_t offset = 0;
    253   StoreU32(kWoff2Signature, &offset, result);
    254   StoreU32(font.flavor, &offset, result);
    255   StoreU32(woff2_length, &offset, result);
    256   Store16(tables.size(), &offset, result);
    257   Store16(0, &offset, result);  // reserved
    258   StoreU32(ComputeTTFLength(tables), &offset, result);
    259   StoreU32(total_compressed_length, &offset, result);
    260   StoreBytes(head_table->data + 4, 4, &offset, result);  // font revision
    261   StoreU32(0, &offset, result);  // metaOffset
    262   StoreU32(0, &offset, result);  // metaLength
    263   StoreU32(0, &offset, result);  // metaOrigLength
    264   StoreU32(0, &offset, result);  // privOffset
    265   StoreU32(0, &offset, result);  // privLength
    266   for (const auto& table : tables) {
    267     StoreTableEntry(table, &offset, result);
    268   }
    269   for (const auto& table : tables) {
    270     StoreBytes(table.dst_data, table.dst_length, &offset, result);
    271     offset = Round4(offset);
    272   }
    273   if (*result_length != offset) {
    274     fprintf(stderr, "Mismatch between computed and actual length "
    275             "(%zd vs %zd)\n", *result_length, offset);
    276     return false;
    277   }
    278   return true;
    279 }
    280 
    281 } // namespace woff2
    282