Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 1 | """ttLib/sfnt.py -- low-level module to deal with the sfnt file format. |
| 2 | |
| 3 | Defines two public classes: |
| 4 | SFNTReader |
| 5 | SFNTWriter |
| 6 | |
| 7 | (Normally you don't have to use these classes explicitly; they are |
| 8 | used automatically by ttLib.TTFont.) |
| 9 | |
| 10 | The reading and writing of sfnt files is separated in two distinct |
| 11 | classes, since whenever to number of tables changes or whenever |
| 12 | a table's length chages you need to rewrite the whole file anyway. |
| 13 | """ |
| 14 | |
jvr | 9be387c | 2008-03-01 11:43:01 +0000 | [diff] [blame] | 15 | import sys |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 16 | import struct, sstruct |
jvr | 1b7d54f | 2008-03-04 15:25:27 +0000 | [diff] [blame] | 17 | import numpy |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 18 | import os |
| 19 | |
jvr | 04b3204 | 2002-05-14 12:09:10 +0000 | [diff] [blame] | 20 | |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 21 | class SFNTReader: |
| 22 | |
pabs3 | 7e91e77 | 2009-02-22 08:55:00 +0000 | [diff] [blame] | 23 | def __init__(self, file, checkChecksums=1, fontNumber=-1): |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 24 | self.file = file |
jvr | ea9dfa9 | 2002-05-12 17:14:50 +0000 | [diff] [blame] | 25 | self.checkChecksums = checkChecksums |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 26 | data = self.file.read(sfntDirectorySize) |
| 27 | if len(data) <> sfntDirectorySize: |
| 28 | from fontTools import ttLib |
| 29 | raise ttLib.TTLibError, "Not a TrueType or OpenType font (not enough data)" |
| 30 | sstruct.unpack(sfntDirectoryFormat, data, self) |
pabs3 | 7e91e77 | 2009-02-22 08:55:00 +0000 | [diff] [blame] | 31 | if self.sfntVersion == "ttcf": |
| 32 | assert ttcHeaderSize == sfntDirectorySize |
| 33 | sstruct.unpack(ttcHeaderFormat, data, self) |
| 34 | assert self.Version == 0x00010000 or self.Version == 0x00020000, "unrecognized TTC version 0x%08x" % self.Version |
| 35 | if not 0 <= fontNumber < self.numFonts: |
| 36 | from fontTools import ttLib |
| 37 | raise ttLib.TTLibError, "specify a font number between 0 and %d (inclusive)" % (self.numFonts - 1) |
| 38 | offsetTable = struct.unpack(">%dL" % self.numFonts, self.file.read(self.numFonts * 4)) |
| 39 | if self.Version == 0x00020000: |
| 40 | pass # ignoring version 2.0 signatures |
| 41 | self.file.seek(offsetTable[fontNumber]) |
| 42 | data = self.file.read(sfntDirectorySize) |
| 43 | sstruct.unpack(sfntDirectoryFormat, data, self) |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 44 | if self.sfntVersion not in ("\000\001\000\000", "OTTO", "true"): |
| 45 | from fontTools import ttLib |
| 46 | raise ttLib.TTLibError, "Not a TrueType or OpenType font (bad sfntVersion)" |
| 47 | self.tables = {} |
| 48 | for i in range(self.numTables): |
| 49 | entry = SFNTDirectoryEntry() |
jvr | ea9dfa9 | 2002-05-12 17:14:50 +0000 | [diff] [blame] | 50 | entry.fromFile(self.file) |
jvr | ce1d50a | 2002-05-12 17:02:50 +0000 | [diff] [blame] | 51 | if entry.length > 0: |
| 52 | self.tables[entry.tag] = entry |
| 53 | else: |
| 54 | # Ignore zero-length tables. This doesn't seem to be documented, |
| 55 | # yet it's apparently how the Windows TT rasterizer behaves. |
| 56 | # Besides, at least one font has been sighted which actually |
| 57 | # *has* a zero-length table. |
| 58 | pass |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 59 | |
| 60 | def has_key(self, tag): |
| 61 | return self.tables.has_key(tag) |
| 62 | |
| 63 | def keys(self): |
| 64 | return self.tables.keys() |
| 65 | |
| 66 | def __getitem__(self, tag): |
| 67 | """Fetch the raw table data.""" |
| 68 | entry = self.tables[tag] |
| 69 | self.file.seek(entry.offset) |
| 70 | data = self.file.read(entry.length) |
jvr | ea9dfa9 | 2002-05-12 17:14:50 +0000 | [diff] [blame] | 71 | if self.checkChecksums: |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 72 | if tag == 'head': |
| 73 | # Beh: we have to special-case the 'head' table. |
jvr | ea9dfa9 | 2002-05-12 17:14:50 +0000 | [diff] [blame] | 74 | checksum = calcChecksum(data[:8] + '\0\0\0\0' + data[12:]) |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 75 | else: |
jvr | ea9dfa9 | 2002-05-12 17:14:50 +0000 | [diff] [blame] | 76 | checksum = calcChecksum(data) |
| 77 | if self.checkChecksums > 1: |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 78 | # Be obnoxious, and barf when it's wrong |
| 79 | assert checksum == entry.checksum, "bad checksum for '%s' table" % tag |
| 80 | elif checksum <> entry.checkSum: |
| 81 | # Be friendly, and just print a warning. |
| 82 | print "bad checksum for '%s' table" % tag |
| 83 | return data |
| 84 | |
jvr | f707463 | 2002-05-04 22:04:02 +0000 | [diff] [blame] | 85 | def __delitem__(self, tag): |
| 86 | del self.tables[tag] |
| 87 | |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 88 | def close(self): |
| 89 | self.file.close() |
| 90 | |
| 91 | |
| 92 | class SFNTWriter: |
| 93 | |
| 94 | def __init__(self, file, numTables, sfntVersion="\000\001\000\000"): |
| 95 | self.file = file |
| 96 | self.numTables = numTables |
| 97 | self.sfntVersion = sfntVersion |
jvr | ea9dfa9 | 2002-05-12 17:14:50 +0000 | [diff] [blame] | 98 | self.searchRange, self.entrySelector, self.rangeShift = getSearchRange(numTables) |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 99 | self.nextTableOffset = sfntDirectorySize + numTables * sfntDirectoryEntrySize |
| 100 | # clear out directory area |
| 101 | self.file.seek(self.nextTableOffset) |
| 102 | # make sure we're actually where we want to be. (XXX old cStringIO bug) |
| 103 | self.file.write('\0' * (self.nextTableOffset - self.file.tell())) |
| 104 | self.tables = {} |
| 105 | |
| 106 | def __setitem__(self, tag, data): |
| 107 | """Write raw table data to disk.""" |
| 108 | if self.tables.has_key(tag): |
| 109 | # We've written this table to file before. If the length |
jvr | 04b3204 | 2002-05-14 12:09:10 +0000 | [diff] [blame] | 110 | # of the data is still the same, we allow overwriting it. |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 111 | entry = self.tables[tag] |
| 112 | if len(data) <> entry.length: |
| 113 | from fontTools import ttLib |
| 114 | raise ttLib.TTLibError, "cannot rewrite '%s' table: length does not match directory entry" % tag |
| 115 | else: |
| 116 | entry = SFNTDirectoryEntry() |
| 117 | entry.tag = tag |
| 118 | entry.offset = self.nextTableOffset |
| 119 | entry.length = len(data) |
| 120 | self.nextTableOffset = self.nextTableOffset + ((len(data) + 3) & ~3) |
| 121 | self.file.seek(entry.offset) |
| 122 | self.file.write(data) |
jvr | c63ac64 | 2008-06-17 20:41:15 +0000 | [diff] [blame] | 123 | # Add NUL bytes to pad the table data to a 4-byte boundary. |
| 124 | # Don't depend on f.seek() as we need to add the padding even if no |
| 125 | # subsequent write follows (seek is lazy), ie. after the final table |
| 126 | # in the font. |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 127 | self.file.write('\0' * (self.nextTableOffset - self.file.tell())) |
jvr | c63ac64 | 2008-06-17 20:41:15 +0000 | [diff] [blame] | 128 | assert self.nextTableOffset == self.file.tell() |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 129 | |
| 130 | if tag == 'head': |
jvr | ea9dfa9 | 2002-05-12 17:14:50 +0000 | [diff] [blame] | 131 | entry.checkSum = calcChecksum(data[:8] + '\0\0\0\0' + data[12:]) |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 132 | else: |
jvr | ea9dfa9 | 2002-05-12 17:14:50 +0000 | [diff] [blame] | 133 | entry.checkSum = calcChecksum(data) |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 134 | self.tables[tag] = entry |
| 135 | |
jvr | 28ae196 | 2004-11-16 10:37:59 +0000 | [diff] [blame] | 136 | def close(self): |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 137 | """All tables must have been written to disk. Now write the |
| 138 | directory. |
| 139 | """ |
| 140 | tables = self.tables.items() |
| 141 | tables.sort() |
| 142 | if len(tables) <> self.numTables: |
| 143 | from fontTools import ttLib |
| 144 | raise ttLib.TTLibError, "wrong number of tables; expected %d, found %d" % (self.numTables, len(tables)) |
| 145 | |
| 146 | directory = sstruct.pack(sfntDirectoryFormat, self) |
| 147 | |
| 148 | self.file.seek(sfntDirectorySize) |
jvr | f509c0f | 2003-08-22 19:38:37 +0000 | [diff] [blame] | 149 | seenHead = 0 |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 150 | for tag, entry in tables: |
jvr | f509c0f | 2003-08-22 19:38:37 +0000 | [diff] [blame] | 151 | if tag == "head": |
| 152 | seenHead = 1 |
jvr | ea9dfa9 | 2002-05-12 17:14:50 +0000 | [diff] [blame] | 153 | directory = directory + entry.toString() |
jvr | f509c0f | 2003-08-22 19:38:37 +0000 | [diff] [blame] | 154 | if seenHead: |
| 155 | self.calcMasterChecksum(directory) |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 156 | self.file.seek(0) |
| 157 | self.file.write(directory) |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 158 | |
jvr | ea9dfa9 | 2002-05-12 17:14:50 +0000 | [diff] [blame] | 159 | def calcMasterChecksum(self, directory): |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 160 | # calculate checkSumAdjustment |
| 161 | tags = self.tables.keys() |
jvr | 1ebda67 | 2008-03-08 20:29:30 +0000 | [diff] [blame] | 162 | checksums = numpy.zeros(len(tags)+1, numpy.int32) |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 163 | for i in range(len(tags)): |
| 164 | checksums[i] = self.tables[tags[i]].checkSum |
| 165 | |
| 166 | directory_end = sfntDirectorySize + len(self.tables) * sfntDirectoryEntrySize |
| 167 | assert directory_end == len(directory) |
| 168 | |
jvr | ea9dfa9 | 2002-05-12 17:14:50 +0000 | [diff] [blame] | 169 | checksums[-1] = calcChecksum(directory) |
jvr | 1b7d54f | 2008-03-04 15:25:27 +0000 | [diff] [blame] | 170 | checksum = numpy.add.reduce(checksums) |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 171 | # BiboAfba! |
jvr | 1b7d54f | 2008-03-04 15:25:27 +0000 | [diff] [blame] | 172 | checksumadjustment = numpy.array(0xb1b0afbaL - 0x100000000L, |
| 173 | numpy.int32) - checksum |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 174 | # write the checksum to the file |
| 175 | self.file.seek(self.tables['head'].offset + 8) |
jvr | 5862963 | 2002-07-21 20:05:52 +0000 | [diff] [blame] | 176 | self.file.write(struct.pack(">l", checksumadjustment)) |
jvr | 1ebda67 | 2008-03-08 20:29:30 +0000 | [diff] [blame] | 177 | |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 178 | |
| 179 | # -- sfnt directory helpers and cruft |
| 180 | |
pabs3 | 7e91e77 | 2009-02-22 08:55:00 +0000 | [diff] [blame] | 181 | ttcHeaderFormat = """ |
| 182 | > # big endian |
| 183 | TTCTag: 4s # "ttcf" |
| 184 | Version: L # 0x00010000 or 0x00020000 |
| 185 | numFonts: L # number of fonts |
| 186 | # OffsetTable[numFonts]: L # array with offsets from beginning of file |
| 187 | # ulDsigTag: L # version 2.0 only |
| 188 | # ulDsigLength: L # version 2.0 only |
| 189 | # ulDsigOffset: L # version 2.0 only |
| 190 | """ |
| 191 | |
| 192 | ttcHeaderSize = sstruct.calcsize(ttcHeaderFormat) |
| 193 | |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 194 | sfntDirectoryFormat = """ |
| 195 | > # big endian |
jvr | b0e5f29 | 2002-05-13 11:21:48 +0000 | [diff] [blame] | 196 | sfntVersion: 4s |
| 197 | numTables: H # number of tables |
| 198 | searchRange: H # (max2 <= numTables)*16 |
| 199 | entrySelector: H # log2(max2 <= numTables) |
| 200 | rangeShift: H # numTables*16-searchRange |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 201 | """ |
| 202 | |
| 203 | sfntDirectorySize = sstruct.calcsize(sfntDirectoryFormat) |
| 204 | |
| 205 | sfntDirectoryEntryFormat = """ |
| 206 | > # big endian |
jvr | b0e5f29 | 2002-05-13 11:21:48 +0000 | [diff] [blame] | 207 | tag: 4s |
| 208 | checkSum: l |
| 209 | offset: l |
| 210 | length: l |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 211 | """ |
| 212 | |
| 213 | sfntDirectoryEntrySize = sstruct.calcsize(sfntDirectoryEntryFormat) |
| 214 | |
| 215 | class SFNTDirectoryEntry: |
| 216 | |
jvr | ea9dfa9 | 2002-05-12 17:14:50 +0000 | [diff] [blame] | 217 | def fromFile(self, file): |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 218 | sstruct.unpack(sfntDirectoryEntryFormat, |
| 219 | file.read(sfntDirectoryEntrySize), self) |
| 220 | |
jvr | ea9dfa9 | 2002-05-12 17:14:50 +0000 | [diff] [blame] | 221 | def fromString(self, str): |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 222 | sstruct.unpack(sfntDirectoryEntryFormat, str, self) |
| 223 | |
jvr | ea9dfa9 | 2002-05-12 17:14:50 +0000 | [diff] [blame] | 224 | def toString(self): |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 225 | return sstruct.pack(sfntDirectoryEntryFormat, self) |
| 226 | |
| 227 | def __repr__(self): |
| 228 | if hasattr(self, "tag"): |
| 229 | return "<SFNTDirectoryEntry '%s' at %x>" % (self.tag, id(self)) |
| 230 | else: |
| 231 | return "<SFNTDirectoryEntry at %x>" % id(self) |
| 232 | |
| 233 | |
jvr | ea9dfa9 | 2002-05-12 17:14:50 +0000 | [diff] [blame] | 234 | def calcChecksum(data, start=0): |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 235 | """Calculate the checksum for an arbitrary block of data. |
| 236 | Optionally takes a 'start' argument, which allows you to |
| 237 | calculate a checksum in chunks by feeding it a previous |
| 238 | result. |
| 239 | |
| 240 | If the data length is not a multiple of four, it assumes |
| 241 | it is to be padded with null byte. |
| 242 | """ |
| 243 | from fontTools import ttLib |
| 244 | remainder = len(data) % 4 |
| 245 | if remainder: |
| 246 | data = data + '\0' * (4-remainder) |
jvr | 1b7d54f | 2008-03-04 15:25:27 +0000 | [diff] [blame] | 247 | a = numpy.fromstring(struct.pack(">l", start) + data, numpy.int32) |
jvr | 9be387c | 2008-03-01 11:43:01 +0000 | [diff] [blame] | 248 | if sys.byteorder <> "big": |
jvr | 1b7d54f | 2008-03-04 15:25:27 +0000 | [diff] [blame] | 249 | a = a.byteswap() |
| 250 | return numpy.add.reduce(a) |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 251 | |
| 252 | |
jvr | ea9dfa9 | 2002-05-12 17:14:50 +0000 | [diff] [blame] | 253 | def maxPowerOfTwo(x): |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 254 | """Return the highest exponent of two, so that |
| 255 | (2 ** exponent) <= x |
| 256 | """ |
| 257 | exponent = 0 |
| 258 | while x: |
| 259 | x = x >> 1 |
| 260 | exponent = exponent + 1 |
Just | fdea99d | 2000-08-23 12:34:44 +0000 | [diff] [blame] | 261 | return max(exponent - 1, 0) |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 262 | |
| 263 | |
jvr | ea9dfa9 | 2002-05-12 17:14:50 +0000 | [diff] [blame] | 264 | def getSearchRange(n): |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 265 | """Calculate searchRange, entrySelector, rangeShift for the |
| 266 | sfnt directory. 'n' is the number of tables. |
| 267 | """ |
| 268 | # This stuff needs to be stored in the file, because? |
| 269 | import math |
jvr | ea9dfa9 | 2002-05-12 17:14:50 +0000 | [diff] [blame] | 270 | exponent = maxPowerOfTwo(n) |
Just | 7842e56 | 1999-12-16 21:34:53 +0000 | [diff] [blame] | 271 | searchRange = (2 ** exponent) * 16 |
| 272 | entrySelector = exponent |
| 273 | rangeShift = n * 16 - searchRange |
| 274 | return searchRange, entrySelector, rangeShift |
| 275 | |