Skip to content

Commit

Permalink
Improve performance of reused patterns.
Browse files Browse the repository at this point in the history
Bug 1721218 has a shading pattern that was used thousands of times.
To improve performance of this PDF:
 - add a cache for patterns in the evaluator and only send the IR form once
   to the main thread (this also makes caching in canvas easier)
 - cache the created canvas radial/axial patterns
 - for shading fill radial/axial use the pattern directly instead of creating temporary
   canvas
  • Loading branch information
brendandahl committed Jul 22, 2021
1 parent 2cf90cd commit 12cd0bd
Show file tree
Hide file tree
Showing 7 changed files with 121 additions and 59 deletions.
70 changes: 49 additions & 21 deletions src/core/evaluator.js
Original file line number Diff line number Diff line change
Expand Up @@ -1314,6 +1314,35 @@ class PartialEvaluator {
});
}

parsePattern({
keyObj,
shading,
resources,
localColorSpaceCache,
localShadingPatternCache,
matrix = null,
}) {
// Shadings and patterns may be referenced by the same name but the resource
// dictionary could be different so we can't use the name for the cache key.
let id = localShadingPatternCache.get(keyObj);
if (!id) {
var shadingFill = Pattern.parseShading(
shading,
matrix,
this.xref,
resources,
this.handler,
this._pdfFunctionFactory,
localColorSpaceCache
);
const patternIR = shadingFill.getIR();
id = `pattern_${this.idFactory.createObjId()}`;
localShadingPatternCache.set(keyObj, id);
this.handler.send("obj", [id, this.pageIndex, "Pattern", patternIR]);
}
return id;
}

handleColorN(
operatorList,
fn,
Expand All @@ -1323,7 +1352,8 @@ class PartialEvaluator {
resources,
task,
localColorSpaceCache,
localTilingPatternCache
localTilingPatternCache,
localShadingPatternCache
) {
// compile tiling patterns
const patternName = args.pop();
Expand All @@ -1350,7 +1380,7 @@ class PartialEvaluator {
// if and only if there are PDF documents where doing so would
// significantly improve performance.

let pattern = patterns.get(name);
const pattern = patterns.get(name);
if (pattern) {
const dict = isStream(pattern) ? pattern.dict : pattern;
const typeNum = dict.get("PatternType");
Expand All @@ -1371,16 +1401,15 @@ class PartialEvaluator {
} else if (typeNum === PatternType.SHADING) {
const shading = dict.get("Shading");
const matrix = dict.getArray("Matrix");
pattern = Pattern.parseShading(
const objId = this.parsePattern({
keyObj: pattern,
shading,
matrix,
this.xref,
resources,
this.handler,
this._pdfFunctionFactory,
localColorSpaceCache
);
operatorList.addOp(fn, pattern.getIR());
localColorSpaceCache,
localShadingPatternCache,
});
operatorList.addOp(fn, ["Shading", objId]);
return undefined;
}
throw new FormatError(`Unknown PatternType: ${typeNum}`);
Expand Down Expand Up @@ -1513,6 +1542,7 @@ class PartialEvaluator {
const localColorSpaceCache = new LocalColorSpaceCache();
const localGStateCache = new LocalGStateCache();
const localTilingPatternCache = new LocalTilingPatternCache();
const localShadingPatternCache = new Map();

const xobjs = resources.get("XObject") || Dict.empty;
const patterns = resources.get("Pattern") || Dict.empty;
Expand Down Expand Up @@ -1869,7 +1899,8 @@ class PartialEvaluator {
resources,
task,
localColorSpaceCache,
localTilingPatternCache
localTilingPatternCache,
localShadingPatternCache
)
);
return;
Expand All @@ -1890,7 +1921,8 @@ class PartialEvaluator {
resources,
task,
localColorSpaceCache,
localTilingPatternCache
localTilingPatternCache,
localShadingPatternCache
)
);
return;
Expand All @@ -1909,18 +1941,14 @@ class PartialEvaluator {
if (!shading) {
throw new FormatError("No shading object found");
}

var shadingFill = Pattern.parseShading(
const patternId = self.parsePattern({
keyObj: shading,
shading,
null,
xref,
resources,
self.handler,
self._pdfFunctionFactory,
localColorSpaceCache
);
var patternIR = shadingFill.getIR();
args = [patternIR];
localColorSpaceCache,
localShadingPatternCache,
});
args = [patternId];
fn = OPS.shadingFill;
break;
case OPS.setGState:
Expand Down
3 changes: 3 additions & 0 deletions src/display/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -2707,6 +2707,9 @@ class WorkerTransport {
pageProxy.cleanupAfterRender = true;
}
break;
case "Pattern":
pageProxy.objs.resolve(id, imageData);
break;
default:
throw new Error(`Got unknown object type ${type}`);
}
Expand Down
17 changes: 14 additions & 3 deletions src/display/canvas.js
Original file line number Diff line number Diff line change
Expand Up @@ -872,6 +872,7 @@ const CanvasGraphics = (function CanvasGraphicsClosure() {
this.markedContentStack = [];
this.optionalContentConfig = optionalContentConfig;
this.cachedCanvases = new CachedCanvases(this.canvasFactory);
this.cachedPatterns = new Map();
if (canvasCtx) {
// NOTE: if mozCurrentTransform is polyfilled, then the current state of
// the transformation must already be set in canvasCtx._transformMatrix.
Expand Down Expand Up @@ -1025,6 +1026,7 @@ const CanvasGraphics = (function CanvasGraphicsClosure() {
}

this.cachedCanvases.clear();
this.cachedPatterns.clear();

if (this.imageLayer) {
this.imageLayer.endLayout();
Expand Down Expand Up @@ -2132,7 +2134,7 @@ const CanvasGraphics = (function CanvasGraphicsClosure() {
baseTransform
);
} else {
pattern = getShadingPattern(IR);
pattern = this._getPattern(IR[1]);
}
return pattern;
}
Expand All @@ -2159,14 +2161,23 @@ const CanvasGraphics = (function CanvasGraphicsClosure() {
this.current.patternFill = false;
}

shadingFill(patternIR) {
_getPattern(objId) {
if (this.cachedPatterns.has(objId)) {
return this.cachedPatterns.get(objId);
}
const pattern = getShadingPattern(this.objs.get(objId));
this.cachedPatterns.set(objId, pattern);
return pattern;
}

shadingFill(objId) {
if (!this.contentVisible) {
return;
}
const ctx = this.ctx;

this.save();
const pattern = getShadingPattern(patternIR);
const pattern = this._getPattern(objId);
ctx.fillStyle = pattern.getPattern(
ctx,
this,
Expand Down
83 changes: 48 additions & 35 deletions src/display/pattern_helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,41 +56,20 @@ class RadialAxialShadingPattern extends BaseShadingPattern {
this._r0 = IR[6];
this._r1 = IR[7];
this._matrix = IR[8];
this._patternCache = null;
}

getPattern(ctx, owner, inverse, shadingFill = false) {
const tmpCanvas = owner.cachedCanvases.getCanvas(
"pattern",
owner.ctx.canvas.width,
owner.ctx.canvas.height,
true
);

const tmpCtx = tmpCanvas.context;
tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
tmpCtx.beginPath();
tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);

if (!shadingFill) {
tmpCtx.setTransform.apply(tmpCtx, owner.baseTransform);
if (this._matrix) {
tmpCtx.transform.apply(tmpCtx, this._matrix);
}
} else {
tmpCtx.setTransform.apply(tmpCtx, ctx.mozCurrentTransform);
}
applyBoundingBox(tmpCtx, this._bbox);

_createGradient(ctx) {
let grad;
if (this._type === "axial") {
grad = tmpCtx.createLinearGradient(
grad = ctx.createLinearGradient(
this._p0[0],
this._p0[1],
this._p1[0],
this._p1[1]
);
} else if (this._type === "radial") {
grad = tmpCtx.createRadialGradient(
grad = ctx.createRadialGradient(
this._p0[0],
this._p0[1],
this._r0,
Expand All @@ -103,18 +82,52 @@ class RadialAxialShadingPattern extends BaseShadingPattern {
for (const colorStop of this._colorStops) {
grad.addColorStop(colorStop[0], colorStop[1]);
}
tmpCtx.fillStyle = grad;
tmpCtx.fill();
return grad;
}

getPattern(ctx, owner, inverse, shadingFill = false) {
let pattern;
if (this._patternCache) {
pattern = this._patternCache;
} else {
if (!shadingFill) {
const tmpCanvas = owner.cachedCanvases.getCanvas(
"pattern",
owner.ctx.canvas.width,
owner.ctx.canvas.height,
true
);

const domMatrix = new DOMMatrix(inverse);
const tmpCtx = tmpCanvas.context;
tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
tmpCtx.beginPath();
tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);

const pattern = ctx.createPattern(tmpCanvas.canvas, "repeat");
try {
pattern.setTransform(domMatrix);
} catch (ex) {
// Avoid rendering breaking completely in Firefox 78 ESR,
// and in Node.js (see issue 13724).
warn(`RadialAxialShadingPattern.getPattern: "${ex?.message}".`);
tmpCtx.setTransform.apply(tmpCtx, owner.baseTransform);
if (this._matrix) {
tmpCtx.transform.apply(tmpCtx, this._matrix);
}
applyBoundingBox(tmpCtx, this._bbox);

tmpCtx.fillStyle = this._createGradient(tmpCtx);
tmpCtx.fill();

pattern = ctx.createPattern(tmpCanvas.canvas, "repeat");
} else {
applyBoundingBox(ctx, this._bbox);
pattern = this._createGradient(ctx);
}
this._patternCache = pattern;
}
if (!shadingFill) {
const domMatrix = new DOMMatrix(inverse);
try {
pattern.setTransform(domMatrix);
} catch (ex) {
// Avoid rendering breaking completely in Firefox 78 ESR,
// and in Node.js (see issue 13724).
warn(`RadialAxialShadingPattern.getPattern: "${ex?.message}".`);
}
}
return pattern;
}
Expand Down
1 change: 1 addition & 0 deletions test/pdfs/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
!issue7872.pdf
!issue7901.pdf
!issue8061.pdf
!bug1721218_reduced.pdf
!issue8088.pdf
!issue8125.pdf
!issue8229.pdf
Expand Down
Binary file added test/pdfs/bug1721218_reduced.pdf
Binary file not shown.
6 changes: 6 additions & 0 deletions test/test_manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -5623,6 +5623,12 @@
"rounds": 1,
"type": "eq"
},
{ "id": "bug1721218_reduced",
"file": "pdfs/bug1721218_reduced.pdf",
"md5": "20ee3e9500d8f5f5e532ec2edfaaaaaa",
"rounds": 1,
"type": "eq"
},
{ "id": "pr8491",
"file": "pdfs/pr8491.pdf",
"md5": "36ea2e28cd77e9e70731f574ab27cbe0",
Expand Down

0 comments on commit 12cd0bd

Please sign in to comment.