lørdag den 29. oktober 2011

The Font Files

One of my primary goals for the LCD library is to be able to render outline fonts. There is already a great open-source library out there for doing that. It's called Freetype. This is the library used on Android. It is a simple task to get Freetype running on the MCB1700, Freetype is a beautiful piece of work and well documented too. However, in my opinion, using Freetype to render Truetype fonts files stored in flash still uses too many resources, notably flash and ram. The main reason is the Truetype font file format. It has no place on an restricted embedded system. The MCB1700 is definately restricted when it comes to Truetype font files.

What I want is to store outlines, glyphs, and character maps in a readily accessible manner in flash so that they require the least amount of processing to render. In order to use Truetype font files I must preprocess them. To that end I have begun writing a Python script to parse Truetype fonts. The output from the script will be C source code. I wish to use only two bytes for each coordinate set, so I have to somehow normalize the input. Last night I finished the parsing part of the task. Weather or not that was the simplest part, you determine. What did it take to get thus far? Let's see.

First, import some stuff. I use OptionParser even though the script has no options at this point:
from sys import stdout, stdin, argv
from struct import unpack
from optparse import OptionParser
The Table class is used as a placeholder. There is probably an even simpler python way to do this:
class Table:
  "blah"
Font files have checksums in various places. If you want to check those, you must calculate the checsum:
def chk(tab):
  return 0xFFFFFFFF & sum([unpack(">I", tab[i:i+4])[0] for i in range(0, len(tab), 4)])
Then, read the file:
parser = OptionParser()
(options, args) = parser.parse_args()
f = open(args[0], "rb")
font = f.read()
This is where you would check the entire file:
assert 0xB1B0AFBA == chk(font)
Make a dictionary of tables in the file. This is the place where you would check the checksum for each table, but I found that for some reason the head table does not check out, and anyway I don't feel the need to perform the check, I just want the outlines and be done with it:
for n in range(numTables):
  table = Table()
  tag = font[16 * n + 12 : 16 * n + 16]
  table.checkSum, table.offset, table.length = unpack(">III", font[16*n+16:16*n+28])
  c = chk(font[table.offset:table.offset + ((table.length + 3) / 4) * 4])
  tables[tag] = table
Parse required tables. I disclose the functions below:
head = parseHead(tables["head"].offset, tables["head"].offset)
maxp = parseMaxp(tables["maxp"].offset, tables["maxp"].length)
loca = parseLoca(tables["loca"].offset, tables["loca"].length, head.indexToLocFormat, maxp.numGlyphs)
glyf = parseGlyf(tables["glyf"].offset, tables["glyf"].length, loca)
cmap = parseCmap(tables["cmap"].offset, tables["cmap"].length)
The head table is simple, just a bunch of properties:
def parseHead(offset, length):
  head = Table()
  head.ver, head.fontRevision, head.checkSumAdjustment, head.magicNumber, \
  head.flags, head.unitsPerEm, head.created, head.modified, \
  head.xMin, head.yMin, head.xMax, head.yMax, head.macStyle, head.lowestRecPPEM, \
  head.fontDirectionHint, head.indexToLocFormat, head.glyphDataFormat = \
    unpack(">IIIIHHQQhhhhHHhhh", font[offset : offset + 54])
  return head
the maxp table is equally simple, also just a bunch of properties:
def parseMaxp(offset, length):
  maxp = Table()
  maxp.ver, maxp.numGlyphs, maxp.maxPoints, maxp.maxContours, maxCompositePoints, \
  maxp.maxCompositeContours, maxp.maxZones, maxp.maxTwilightPoints, maxp.maxStorage, \
  maxp.maxFunctionDefs, maxp.maxInstructionDefs, maxp.maxStackElements, \
  maxp.maxSizeOfInstructions, maxp.maxComponentElements, maxp.maxComponentDepth = \
    unpack(">iHHHHHHHHHHHHHH", font[offset : offset + 32])
  return maxp
The loca table requires some properties from head and maxp (which is why those were parsed first, see?) to interpret data correctly. The loca table contains information about where to find each glyph in the font file:
def parseLoca(offset, length, indexToLocFormat, numGlyphs):
  if 0 == indexToLocFormat: # short
    loca = [2 * unpack(">H", font[offset + 2*z: offset + 2*z + 2])[0] for z in range(numGlyphs + 1)]
  else: # long
    loca = [    unpack(">I", font[offset + 4*z: offset + 4*z + 4])[0] for z in range(numGlyphs + 1)]
  return loca
Now we can get at the glyph data. And this is where things start to get interesting. Currently the script only parses simple glyphs, not the composite ones. The script has only been tested on fonts without composite glyphs, and without instructions:
def parseGlyf(offset, length, loca):
  glyf = []
  for i, location in zip(range(len(loca[:-1])), loca[:-1]):
    o = offset + location
    num, xmin, ymin, xmax, ymax = unpack(">hhhhh", font[o : o + 10])
    o += 10
    assert num >= 0
    isComposite = num < 0
    if isComposite:
      print "  Composite glyph"
    else:
      endPoints    = [unpack(">H", font[o + z: o + z + 2])[0] for z in range(0, 2 * num, 2)]
      if endPoints:
        o += 2 * num
        instructionLength, = unpack(">H", font[o : o + 2])
        o += 2
        instructions = [unpack(">B", font[o + z])[0] for z in range(instructionLength)]
        o += instructionLength
        flags = []
        flagIndex = 0
        while flagIndex <= endPoints[-1]:
          flag = unpack(">B", font[o])[0]
          o += 1
          flags.append(flag)
          flagIndex += 1
          if 0 != (flag & (1 << 3)):
            repeat = unpack(">B", font[o])[0]
            o += 1
            flags.extend([flag] * repeat)
            flagIndex += repeat
        glyfx = []
        glyfy = []
        for firstPointIndex, lastPointIndex in zip([0] + [z + 1 for z in endPoints[:-1]], endPoints):
          xlist = []
          for pointIndex in range(firstPointIndex, lastPointIndex + 1):
            if 0 == ((1 << 1) & flags[pointIndex]):
              if 0 == ((1 << 4) & flags[pointIndex]):
                xlist.append(unpack(">h", font[o:o + 2])[0])
                o += 2
              else:
                xlist.append(0)
            else:
              xlist.append((((flags[pointIndex] >> 4) & 1)*2 - 1) * unpack(">B", font[o])[0])
              o += 1
          glyfx.append(xlist)
        for firstPointIndex, lastPointIndex in zip([0] + [z + 1 for z in endPoints[:-1]], endPoints):
          ylist = []
          for pointIndex in range(firstPointIndex, lastPointIndex + 1):
            if 0 == ((1 << 2) & flags[pointIndex]):
              if 0 == ((1 << 5) & flags[pointIndex]):
                ylist.append(unpack(">h", font[o:o + 2])[0])
                o += 2
              else:
                ylist.append(0)
            else:
              ylist.append((((flags[pointIndex] >> 5) & 1)*2 - 1) * unpack(">B", font[o])[0])
              o += 1
          glyfy.append(ylist)
        glyf.append([zip(gx, gy) for gx, gy in zip(glyfx, glyfy)])
  return glyf
As you can tell from the length of this function, the glyf table is one of the more interesting tables in the font file. It contains all the outlines, so why wouldn't it be? Among other things the glyf table contains a bunch of flags that are key to interpreting coordinate data. Using the flags you can indicate 8-bit or 16-bit coordinates, sign of 8-bit coordinates, repeat coordinates, on-curve or off-curve points, you can even repeat a set of flags a number of times. That makes it a little (but fortunately not a lot) tricky to read the outlines.

The last table that you need to map from a character code-point to an outline is CMAP. As hinted at in the previous sentence, this is "just" a table that maps from code-points to outlines. But how it does that, oh how it does that:
def parseCmap(offset, length):
  cmap = { }
  cmap_ver, cmap_num = unpack(">HH", font[offset:offset + 4])
  for t in range(cmap_num):
    cmap_plid, cmap_encid, cmap_suboffs = unpack(">HHI", font[offset + t*8 + 4 : offset + t * 8 + 12]);
    if (3, 1) == (cmap_plid, cmap_encid):
      o = offset + cmap_suboffs
      form = unpack(">H", font[o : o + 2])[0];
      o += 2
      if 4 == form:
        stuff = unpack(">HHHHHH", font[o: o + 12])
        o += 12
        cmlen, cmver, cmsegct2, cmsrang, cmesel, cmrangsh = stuff
        l = [(z,) + unpack(">HHHH", font[o+z:o+z+2] + font[o + 2 + cmsegct2+z:o + 2 + cmsegct2+z+2] + font[o + 2 + 2*cmsegct2+z:o + 2 + 2*cmsegct2+z+2] + font[o + 2 + 3*cmsegct2+z:o + 2 + 3*cmsegct2+z+2]) for z in range(0, cmsegct2, 2)]
        for i, iEnd, iStart, iDelta, iOffs in l: 
          if 0 != iOffs:
            for c in range(iStart, iEnd+1):
              glyph_index = unpack(">H", font[o + 2 + 3*cmsegct2 + i + 2 * (c - iStart) + iOffs - cmsegct2 : o + 2 + 3*cmsegct2 + i + 2 * (c - iStart) + iOffs - cmsegct2 + 2])[0]
              if 0 != glyph_index: cmap[c] = glyph_index
          else: 
            for c in range(iStart, iEnd+1):
              glyph_index = 0xFFFF & (iDelta + c)
              if 0 != glyph_index: cmap[c] = glyph_index
  return cmap
Actually the specification found at Microsoft contains these exact words:
"This obscure indexing trick works because glyphIdArray immediately follows idRangeOffset in the font file."
And obscure it is. Fortunately aforementioned specification explains it reasonably well and even contains  pieces of source code that are essential to at least my understanding of the explanation. There is probably also a perfectly reasonable explanation to why on earth a font files is constructed in this bizarre way. I personally believe that someone concocted it in a purple haze and marketing rushed it to market.

Ingen kommentarer:

Send en kommentar