Skip to content

Commit

Permalink
[PERFORMANCE] Improve FileSystemFontProvider.scanFonts() performance …
Browse files Browse the repository at this point in the history
…by adding 'only headers' mode to TTF parser:

* only read tables needed for FSFontInfo ('name', 'head', 'OS/2', 'CFF ', 'gcid')
* 'CFF ' and 'head' table parsers finish as soon as it has all needed headers
  • Loading branch information
bogdiuk committed Jun 25, 2024
1 parent 2bd40b9 commit e390fe1
Show file tree
Hide file tree
Showing 9 changed files with 500 additions and 92 deletions.
42 changes: 33 additions & 9 deletions fontbox/src/main/java/org/apache/fontbox/cff/CFFParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.fontbox.ttf.FontHeaders;
import org.apache.pdfbox.io.RandomAccessRead;


Expand All @@ -48,7 +49,8 @@ public class CFFParser

private String[] stringIndex = null;
private ByteSource source;

private FontHeaders loadOnlyHeaders;

// for debugging only
private String debugFontName;

Expand All @@ -66,6 +68,11 @@ public interface ByteSource
byte[] getBytes() throws IOException;
}

public void setLoadOnlyHeaders(FontHeaders loadOnlyHeaders)
{
this.loadOnlyHeaders = loadOnlyHeaders;
}

/**
* Parse CFF font using byte array, also passing in a byte source for future use.
*
Expand All @@ -91,17 +98,21 @@ public List<CFFFont> parse(byte[] bytes, ByteSource source) throws IOException
public List<CFFFont> parse(RandomAccessRead randomAccessRead) throws IOException
{
// TODO do we need to store the source data of the font? It isn't used at all
byte[] bytes = new byte[(int) randomAccessRead.length()];
// definitely don't need 'source' in 'loadOnlyHeaders' mode
randomAccessRead.seek(0);
int remainingBytes = bytes.length;
int amountRead;
while ((amountRead = randomAccessRead.read(bytes, bytes.length - remainingBytes,
remainingBytes)) > 0)
if (loadOnlyHeaders == null)
{
remainingBytes -= amountRead;
byte[] bytes = new byte[(int) randomAccessRead.length()];
int remainingBytes = bytes.length;
int amountRead;
while ((amountRead = randomAccessRead.read(bytes, bytes.length - remainingBytes,
remainingBytes)) > 0)
{
remainingBytes -= amountRead;
}
randomAccessRead.seek(0);
this.source = new CFFBytesource(bytes);
}
randomAccessRead.seek(0);
this.source = new CFFBytesource(bytes);
return parse(new DataInputRandomAccessRead(randomAccessRead));
}

Expand Down Expand Up @@ -492,6 +503,15 @@ private CFFFont parseFont(DataInput input, String name, byte[] topDictIndex) thr
cffCIDFont.setSupplement(rosEntry.getNumber(2).intValue());

font = cffCIDFont;
if (loadOnlyHeaders != null)
{
loadOnlyHeaders.setOtfROS(
cffCIDFont.getRegistry(),
cffCIDFont.getOrdering(),
cffCIDFont.getSupplement());
// we just read (Registry, Ordering, Supplement) and don't need anything else
return font;
}
}
else
{
Expand All @@ -501,6 +521,10 @@ private CFFFont parseFont(DataInput input, String name, byte[] topDictIndex) thr
// name
debugFontName = name;
font.setName(name);
if (loadOnlyHeaders != null)
{
return font; // not a 'CFFCIDFont' => cannot read properties needed by LoadOnlyHeaders anyway
}

// top dict
font.addValueToTopDict("version", getString(topDict, "version"));
Expand Down
23 changes: 21 additions & 2 deletions fontbox/src/main/java/org/apache/fontbox/ttf/CFFTable.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.io.IOException;
import org.apache.fontbox.cff.CFFFont;
import org.apache.fontbox.cff.CFFParser;
import org.apache.pdfbox.io.RandomAccessRead;

/**
* PostScript font program (compact font format).
Expand Down Expand Up @@ -48,9 +49,27 @@ public class CFFTable extends TTFTable
@Override
void read(TrueTypeFont ttf, TTFDataStream data) throws IOException
{
byte[] bytes = data.read((int)getLength());

// assert data.getCurrentPosition() == getOffset();
CFFParser parser = new CFFParser();
FontHeaders loadOnlyHeaders = ttf.getLoadOnlyHeaders();
parser.setLoadOnlyHeaders(loadOnlyHeaders);
if (loadOnlyHeaders != null)
{
// TODO: measure performance and maybe use createSubView() for non-loadOnlyHeaders case
try (RandomAccessRead subReader = data.createSubView(getLength()))
{
if (subReader != null)
{
cffFont = parser.parse(subReader).get(0);
data.seek(getOffset() + getLength());
initialized = true;
return;
}
assert loadOnlyHeaders != null
: "It is inefficient to read whole CFF table to parse only headers, please use RandomAccessReadUncachedDataStream";
}
}
byte[] bytes = data.read((int)getLength());
cffFont = parser.parse(bytes, new CFFBytesource(ttf)).get(0);

initialized = true;
Expand Down
154 changes: 154 additions & 0 deletions fontbox/src/main/java/org/apache/fontbox/ttf/FontHeaders.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.fontbox.ttf;

import java.io.IOException;

/**
* To improve performance of {@code FileSystemFontProvider.scanFonts(...)},
* this class is used both as a marker (to skip unused data) and as a storage for collected data.
* <p>
* Tables it needs:<ul>
* <li>NamingTable.TAG
* <li>HeaderTable.TAG
* <li>OS2WindowsMetricsTable.TAG
* <li>CFFTable.TAG (for OTF)
* <li>"gcid" (for non-OTF)
* </ul>
*
* @author Mykola Bohdiuk
*/
public final class FontHeaders
{
static final int BYTES_GCID = 142;

private IOException exception;
private String name;
private Integer headerMacStyle;
private OS2WindowsMetricsTable os2Windows;
private String fontFamily;
private String fontSubFamily;
private byte[] nonOtfGcid142;
//
private boolean isOTFAndPostScript;
private String otfRegistry;
private String otfOrdering;
private int otfSupplement;

public IOException getException()
{
return exception;
}

public String getName()
{
return name;
}

/**
* null == no HeaderTable, {@code ttf.getHeader().getMacStyle()}
*/
public Integer getHeaderMacStyle()
{
return headerMacStyle;
}

public OS2WindowsMetricsTable getOS2Windows()
{
return os2Windows;
}

// only when LOGGER(FileSystemFontProvider).isTraceEnabled() tracing: FontFamily, FontSubfamily
public String getFontFamily()
{
return fontFamily;
}

public String getFontSubFamily()
{
return fontSubFamily;
}

public boolean isOpenTypePostScript()
{
return isOTFAndPostScript;
}

public byte[] getNonOtfTableGCID142()
{
return nonOtfGcid142;
}

public String getOtfRegistry()
{
return otfRegistry;
}

public String getOtfOrdering()
{
return otfOrdering;
}

public int getOtfSupplement()
{
return otfSupplement;
}

void setException(IOException exception)
{
this.exception = exception;
}

void setName(String name)
{
this.name = name;
}

void setHeaderMacStyle(Integer headerMacStyle)
{
this.headerMacStyle = headerMacStyle;
}

void setOs2Windows(OS2WindowsMetricsTable os2Windows)
{
this.os2Windows = os2Windows;
}

void setFontFamily(String fontFamily, String fontSubFamily)
{
this.fontFamily = fontFamily;
this.fontSubFamily = fontSubFamily;
}

void setNonOtfGcid142(byte[] nonOtfGcid142)
{
this.nonOtfGcid142 = nonOtfGcid142;
}

void setIsOTFAndPostScript(boolean isOTFAndPostScript)
{
this.isOTFAndPostScript = isOTFAndPostScript;
}

// public because CFFParser is in a different package
public void setOtfROS(String otfRegistry, String otfOrdering, int otfSupplement)
{
this.otfRegistry = otfRegistry;
this.otfOrdering = otfOrdering;
this.otfSupplement = otfSupplement;
}
}
10 changes: 10 additions & 0 deletions fontbox/src/main/java/org/apache/fontbox/ttf/HeaderTable.java
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,16 @@ public class HeaderTable extends TTFTable
@Override
void read(TrueTypeFont ttf, TTFDataStream data) throws IOException
{
FontHeaders outHeaders = ttf.getLoadOnlyHeaders();
if (outHeaders != null) {
// 44 == 4 + 4 + 4 + 4 + 2 + 2 + 2*8 + 4*2
data.seek(data.getCurrentPosition() + 44);
macStyle = data.readUnsignedShort();
outHeaders.setHeaderMacStyle(macStyle);
initialized = true;
return;
}

version = data.read32Fixed();
fontRevision = data.read32Fixed();
checkSumAdjustment = data.readUnsignedInt();
Expand Down
31 changes: 28 additions & 3 deletions fontbox/src/main/java/org/apache/fontbox/ttf/NamingTable.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,15 @@ void read(TrueTypeFont ttf, TTFDataStream data) throws IOException
int numberOfNameRecords = data.readUnsignedShort();
int offsetToStartOfStringStorage = data.readUnsignedShort();
nameRecords = new ArrayList<>(numberOfNameRecords);
FontHeaders onlyHeaders = ttf.getLoadOnlyHeaders();
for (int i=0; i< numberOfNameRecords; i++)
{
NameRecord nr = new NameRecord();
nr.initData(ttf, data);
nameRecords.add(nr);
if (onlyHeaders == null || isUsefulForOnlyHeaders(nr))
{
nameRecords.add(nr);
}
}

for (NameRecord nr : nameRecords)
Expand All @@ -86,7 +90,7 @@ void read(TrueTypeFont ttf, TTFDataStream data) throws IOException

lookupTable = new HashMap<>(nameRecords.size());
fillLookupTable();
readInterestingStrings();
readInterestingStrings(onlyHeaders);

initialized = true;
}
Expand Down Expand Up @@ -141,7 +145,7 @@ private void fillLookupTable()
}
}

private void readInterestingStrings()
private void readInterestingStrings(FontHeaders onlyHeaders)
{
// extract strings of interest
fontFamily = getEnglishName(NameRecord.NAME_FONT_FAMILY_NAME);
Expand All @@ -163,6 +167,27 @@ private void readInterestingStrings()
{
psName = psName.trim();
}

if (onlyHeaders != null)
{
onlyHeaders.setName(psName);
onlyHeaders.setFontFamily(fontFamily, fontSubFamily);
}
}

private static boolean isUsefulForOnlyHeaders(NameRecord nr)
{
int nameId = nr.getNameId();
// see "psName =" and "getEnglishName()"
if (nameId == NameRecord.NAME_POSTSCRIPT_NAME
|| nameId == NameRecord.NAME_FONT_FAMILY_NAME
|| nameId == NameRecord.NAME_FONT_SUB_FAMILY_NAME)
{
int languageId = nr.getLanguageId();
return languageId == NameRecord.LANGUAGE_UNICODE
|| languageId == NameRecord.LANGUAGE_WINDOWS_EN_US;
}
return false;
}

/**
Expand Down
Loading

0 comments on commit e390fe1

Please sign in to comment.