*/
options = (typeof options === 'object') ? options : {};
// sanitize options.mode once
options.mode = (typeof options.mode === 'string') ? options.mode : "";
// canvas
var canvas = document.getElementById(canvasId)
, context = canvas.getContext("2d")
// dirty state
, dirty = true
// flag to stop render loop
, stopRendering = false
// image scale
, scale = 1
, scaleStep = 0.1
// image centre (scroll offset)
, centre = { x: 0, y: 0 }
// drawing settings
, defaultLineWidth = options.lineWidth || 3
// viewer states
, states = {
DEFAULT: 0,
ANSWER_DRAW: 1,
POLYGON_DRAW: 2,
POLYGON_MOVE: 3,
POLYGON_POINT_DELETE: 4,
ANNOTATION_DISPLAY: 5,
RECT_DRAW: 6
}
, state = states.DEFAULT
// keeping track of event handling
, events = []
//// buttons
// default buttons that are always visible
, zoomOutButton = new Button('Z-', 'Zoom out')
, zoomInButton = new Button('Z+', 'Zoom in')
, defaultButtons = [zoomOutButton, zoomInButton]
// buttons for answer feature
, deleteAnswerButton = new Button('D', 'Delete answer')
, addAnswerButton = new Button('S', 'Set answer')
, answerButtons = [deleteAnswerButton, addAnswerButton]
// buttons for the solution feature
, drawSolutionPointButton = new Button('S', 'Draw new polygon point (close with shift-click)')
, moveSolutionButton = new Button('Mp', 'Move polygon point')
, deleteSolutionPointButton = new Button('Dp', 'Delete polygon point')
, deleteSolutionButton = new Button('DP', 'Delete polygon')
, solutionButtons = [deleteSolutionButton,
deleteSolutionPointButton,
moveSolutionButton,
drawSolutionPointButton]
// buttons for the annotations feature
, cancelAnnotationButton = new Button('C', 'Cancel drawing a new ROI')
, addNewAnnotationButton = new Button('S', 'Start drawing a new Poly. ROI')
, addNewRectAnnotationButton = new Button('R', 'Start drawing a new Rect. ROI')
, drawAnnotationPointButton = new Button('+', 'Draw new ROI point (close with shift-click)')
, moveAnnotationButton = new Button('Mp', 'Move ROI point')
, deleteAnnotationPointButton = new Button('Dp', 'Delete ROI point')
, deleteAnnotationButton = new Button('DR', 'Delete active ROI')
, annotationButtons = [ deleteAnnotationButton,
deleteAnnotationPointButton,
moveAnnotationButton,
/*drawAnnotationPointButton,*/
addNewRectAnnotationButton,
addNewAnnotationButton,
cancelAnnotationButton]
// contains all active buttons
, buttons = defaultButtons.slice()
// contains all active color buttons (for coloring annotations)
, colorButtons = []
// current tool tip (used to track change of tool tip)
, currentTooltip = null
// Input handling
// active element (mainly) used for dragging
, activeMoveElement = centre
// track state of left mouse button (even outside the canvas)
, leftMouseButtonDown = false
// keep last mouse position to calculate drag distance
, mouseLastPos = null
// UI element which is currently in focus, i.e. the mouse is hovering over it
, focusUIElement = null
// active polygon in edit mode
, activePolygon = null
// answer feature
, answerEditable = options.mode === 'editAnswer'
, answerVisible = answerEditable || options.mode === 'showSolution'
// solution feature
, solutionEditable = options.mode === 'editSolution' || options.mode === 'createROI'
, solutionVisible = solutionEditable || options.mode === 'showSolution'
// annotation feature
, annotationsEditable = options.mode === 'editAnnotations' || options.mode=='editROI'
, annotationsVisible = annotationsEditable || options.mode === 'showAnnotations' || options.mode === 'showROI' || options.mode === 'createROI'
, annotationColors = options.annotationColors || [
'#8dd3c7',
'#ffffb3',
'#bebada',
'#fb8072',
'#80b1d3',
'#fdb462'
];
// image
if (!options.annotationColors) options.annotationColors=annotationColors;
if (imageUrl) this.image = new Image();
else if (imageData) {
// data must be Uint8ClampedArray
this.image = new ImageData(imageData.data,imageData.width,imageData.height);
}
// answer
this.answer = (typeof options.answer === 'object' && options.answer !== null) ? options.answer : null;
// solution
this.solution = null;
// annotations
// format: { polygon: Polygon-object, color: color-string }
this.annotations = [];
this.currentAnnotationColor=0;
function isState(checkState){
return state === states[checkState];
}
function importPolygon(vertexArray){
if(vertexArray.length < 1){
return new Polygon();
}
var initialVertex = createVertex(vertexArray[0].x, vertexArray[0].y)
, current = initialVertex
, next = null;
for(var i = 1; i < vertexArray.length; i++){
next = createVertex(vertexArray[i].x, vertexArray[i].y);
if(next.equals(initialVertex)){
current.next = initialVertex;
break;
}
current.next = next;
current = next;
}
return new Polygon(initialVertex);
}
function exportPolygon(polygon){
// return empty array if polygon is empty
if(typeof polygon === 'undefined' || polygon === null) return [];
var exportedPolygon = [];
var vertices = polygon.getVertices();
// console.log('exportPolygon',polygon,vertices);
//if closed path, add start point at the end again
if(vertices[vertices.length - 1].next === vertices[0]) vertices.push(vertices[0]);
for(var i = 0; i < vertices.length; i++){
exportedPolygon.push({
x: vertices[i].position.x,
y: vertices[i].position.y
});
}
return exportedPolygon;
}
function exportRectangle(polygon){
// return empty array if polygon is empty
if(typeof polygon === 'undefined' || polygon === null) return [];
var vertices = polygon.getVertices(),
exportedPolygon = [],
bbox = {x1:vertices[0].position.x,y1:vertices[0].position.y,x2:vertices[0].position.x,y2:vertices[0].position.y};
// console.log('exportPolygon',polygon,vertices);
//if closed path, add start point at the end again
if(vertices[vertices.length - 1].next === vertices[0]) vertices.push(vertices[0]);
for(var i = 1; i < vertices.length; i++){
bbox.x1=Math.min(bbox.x1,vertices[i].position.x)
bbox.y1=Math.min(bbox.y1,vertices[i].position.y)
bbox.x2=Math.max(bbox.x2,vertices[i].position.x)
bbox.y2=Math.max(bbox.y2,vertices[i].position.y)
}
exportedPolygon.push({
x: bbox.x1,
y: bbox.y1
});
exportedPolygon.push({
x: bbox.x2,
y: bbox.y1
});
exportedPolygon.push({
x: bbox.x2,
y: bbox.y2
});
exportedPolygon.push({
x: bbox.x1,
y: bbox.y2
});
exportedPolygon.push({
x: bbox.x1,
y: bbox.y1
});
polygon.clear();
var first = createVertex(bbox.x1, bbox.y1)
polygon.addVertex(first);
polygon.addVertex(createVertex(bbox.x2, bbox.y1));
polygon.addVertex(createVertex(bbox.x2, bbox.y2));
polygon.addVertex(createVertex(bbox.x1, bbox.y2));
polygon.addVertex(first);
dirty=true;
return exportedPolygon;
}
this.exportSolution = function(){
return this.solution.shape=='rect'?exportRectangle(this.solution):exportPolygon(this.solution);
};
this.importSolution = function(importedSolution){
this.solution = activePolygon = (importedSolution.length >= 1) ? importPolygon(importedSolution) : null;
dirty = true;
};
this.exportAnnotations = function(){
var annotations = this.annotations.map(function(annotation){
return {
color: annotation.color,
polygon: annotation.polygon.shape=='rect'?exportRectangle(annotation.polygon):exportPolygon(annotation.polygon)
};
});
return annotations
};
this.importAnnotations = function(importedAnnotations){
importedAnnotations.forEach(function(importAnnotation){
addNewAnnotation(importPolygon(importAnnotation.polygon), importAnnotation.color, importAnnotation.stroke);
});
};
// gets called if the solution changes
this.onSolutionChange = function(solution){};
// gets called if one or more of the annotations change
this.onAnnotationChange = function(annotations){};
function onImageLoad(){
// set scale to use as much space inside the canvas as possible
if(((canvas.height / self.image.height) * self.image.width) <= canvas.width){
scale = canvas.height / self.image.height;
} else {
scale = canvas.width / self.image.width;
}
// centre at image centre
centre.x = self.image.width / 2;
centre.y = self.image.height / 2;
// image changed
dirty = true;
// start new render loop
render();
}
if (imageUrl) this.onImageLoad = onImageLoad;
this.zoomIn = function(){
scale = scale * (1 + scaleStep);
dirty = true;
};
this.zoomOut = function(){
scale = scale * (1 - scaleStep);
dirty = true;
};
function render(){
// only re-render if dirty
if(dirty){
dirty = false;
var ctx = context;
// clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw image (transformed and scaled)
ctx.save();
var translateX = canvas.width / 2 - centre.x * scale
, translateY = canvas.height / 2 - centre.y * scale;
ctx.translate(translateX, translateY);
ctx.scale(scale, scale);
// console.log('render',translateX,translateY,scale)
if (imageUrl)
ctx.drawImage(self.image, 0,0);
else if (imageData) {
// oops, no scaling/translate support;
// putImageData to an in-memory canvas
// inMemCtx.putImageData(imgdata, 0, 0);
// context.drawImage(inMemoryCanvas, x, y)
var inMemoryCanvas = document.createElement('canvas'),
inMemCtx=inMemoryCanvas.getContext('2d');
inMemoryCanvas.width=imageData.width;
inMemoryCanvas.height=imageData.height;
inMemCtx.putImageData(self.image, 0, 0);
ctx.drawImage(inMemoryCanvas,0,0);
//ctx.putImageData(self.image,translateX,translateY);
}
else alert('ImageUtils.viewer: No image provided');
ctx.restore();
// draw solution
if(solutionVisible && self.solution !== null){
drawPolygon(ctx, self.solution);
}
// draw annotations
if(annotationsVisible){
self.annotations.forEach(function(annotation){
drawPolygon(ctx, annotation.polygon, annotation.color, annotation.stroke);
});
}
// draw line to mouse cursor
if((solutionEditable || annotationsEditable)
&& activePolygon !== null
&& activePolygon.getLength() > 0
&& !activePolygon.isClosed()){
var lastVertexPosition = activePolygon.getLastVertex().position
, mousePosition = convertToImagePosition(mouseLastPos);
drawLine(ctx, lastVertexPosition, mousePosition, '#FF3300', defaultLineWidth);
}
// draw answer
if(answerVisible && self.answer !== null){
drawAnswer(ctx);
}
// draw buttons
drawButtons(ctx);
}
if(!stopRendering) window.requestAnimationFrame(render);
}
function drawLine(ctx, from, to, lineColor, lineWidth){
/**
* ctx: canvas context
* from: start-vertex, in image coordinates
* to: end-vertex, in image coordinates
* lineColor: color string
* lineWidth: number, width in pixel
*/
ctx.save();
// style
ctx.strokeStyle = lineColor;
ctx.lineWidth = lineWidth;
// draw the line
var translation = convertToCanvasTranslation(from)
, relativeToPosition = {
x: to.x - from.x,
y: to.y - from.y
}
, drawPos = { x: 0, y: 0};
ctx.translate(translation.x, translation.y);
ctx.scale(scale, scale);
ctx.beginPath();
ctx.moveTo(drawPos.x, drawPos.y);
ctx.lineTo(relativeToPosition.x, relativeToPosition.y);
ctx.stroke();
ctx.restore();
}
function drawButtons(ctx){
var padding = 10
, radius = 20
, gap = 2 * radius + padding
, x = canvas.width - radius - padding
, y = canvas.height - radius - padding
, i;
// draw buttons
for(i = 0; i < buttons.length; i++){
buttons[i].draw(ctx, x, y - gap * i, radius);
}
// draw color buttons
// ---
// set starting coordinates in lower left corner
x = radius + padding;
y = canvas.height - radius - padding;
for(i = 0; i < colorButtons.length; i++){
colorButtons[i].draw(ctx, x, y - gap * i, radius);
}
// draw tooltip
if(currentTooltip !== null){
ctx.save();
ctx.globalAlpha = 0.5;
var fontSize = radius;
ctx.font = fontSize + "px sans-serif";
// calculate position
var textSize = ctx.measureText(currentTooltip).width
, rectWidth = textSize + padding
, rectHeight = fontSize * 0.70 + padding
, rectX = canvas.width
- (2 * radius + 2 * padding) // buttons
- rectWidth
, rectY = canvas.height - rectHeight - padding
, textX = rectX + 0.5 * padding
, textY = canvas.height - 1.5 * padding;
ctx.fillStyle = '#000000';
drawRoundRectangle(ctx, rectX, rectY, rectWidth, rectHeight, 8, true, false);
ctx.fillStyle = '#ffffff';
ctx.fillText(currentTooltip, textX, textY);
ctx.restore();
}
}
function drawRoundRectangle(ctx, x, y, width, height, radius, fill, stroke){
radius = (typeof radius === 'number') ? radius : 5;
fill = (typeof fill === 'boolean') ? fill : true; // fill = default
stroke = (typeof stroke === 'boolean') ? stroke : false;
// draw round rectangle
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
if(fill) ctx.fill();
if(stroke) ctx.stroke();
}
function convertToImagePosition(canvasPosition){
var visiblePart = {
x: centre.x >= (canvas.width / scale / 2) ? centre.x - canvas.width / scale / 2 : 0,
y: centre.y >= (canvas.height / scale / 2) ? centre.y - canvas.height / scale / 2 : 0
}
, canvasImage = {
x: (centre.x >= (canvas.width / scale / 2)) ? 0 : canvas.width / 2 - centre.x * scale,
y: (centre.y >= (canvas.height / scale / 2)) ? 0 : canvas.height / 2 - centre.y * scale
}
, imagePosition = {};
imagePosition.x =
visiblePart.x // image offset
+ canvasPosition.x / scale // de-scaled canvas position
- canvasImage.x / scale; // de-scaled canvas offset
imagePosition.y =
visiblePart.y // image offset
+ canvasPosition.y / scale // de-scaled canvas position
- canvasImage.y / scale; // de-scaled canvas offset
return imagePosition;
}
function convertToCanvasTranslation(imagePosition){
return {
x: (
imagePosition.x // x-position on picture
+ canvas.width / scale / 2 // offset of scaled canvas
- centre.x // scroll offset of image
) * scale, // scale the transformation
y: (
imagePosition.y // y-position on picture
+ canvas.height / scale / 2 // offset of scaled canvas
- centre.y // scroll offset of image
) * scale // scale the transformation
};
}
function createVertex(x, y, polygon){
var newVertex = new Vertex(x, y, polygon);
newVertex.onClick = function(evt){
if(isState('POLYGON_POINT_DELETE')){
if(newVertex.polygon !== null){
newVertex.polygon.deleteVertex(newVertex);
if(newVertex.polygon === self.solution){
self.onSolutionChange(self.exportSolution());
} else {
cleanupAnnotations();
self.onAnnotationChange(self.exportAnnotations());
}
// FIXME: if this reduced the polygon to two or less vertices, delete the polygon
dirty = true;
}
return false;
}
if(isState('POLYGON_DRAW')){
var isInitialVertex = newVertex.polygon !== null
&& newVertex.equals(newVertex.polygon.initialVertex);
if(isInitialVertex && newVertex.polygon.getLength() > 2){
newVertex.polygon.close();
state = states.DEFAULT;
if(newVertex.polygon === self.solution){
self.onSolutionChange(self.exportSolution());
} else {
cleanupAnnotations();
self.onAnnotationChange(self.exportAnnotations());
}
return false;
}
}
if(isState('RECT_DRAW')){
var isInitialVertex = newVertex.polygon !== null
&& newVertex.equals(newVertex.polygon.initialVertex);
if(isInitialVertex && newVertex.polygon.getLength() > 2){
newVertex.polygon.close();
state = states.DEFAULT;
if(newVertex.polygon === self.solution){
self.onSolutionChange(self.exportSolution('rect'));
} else {
cleanupAnnotations();
self.onAnnotationChange(self.exportAnnotations());
}
return false;
}
}
return true;
};
newVertex.onMouseDown = function(){
if(isState('POLYGON_MOVE')){
activeMoveElement = newVertex.position;
leftMouseButtonDown = true;
return true;
}
return false;
};
return newVertex;
}
function Vertex(x, y, polygon) {
var vertexInstance = this;
this.position = {
x: x,
y: y
};
this.polygon = polygon || null;
this.next = null;
this.handleWidth = 12; // also used as bounding box
this.onClick = function(evt){ return true; }; // just bubble on default
this.onMouseDown = function(){};
}
Vertex.prototype.equals = function(other){
return this.position.x === other.position.x
&& this.position.y === other.position.y;
};
Vertex.prototype.isWithinBounds = function(x, y){
var canvasPosition = convertToCanvasTranslation(this.position);
return x >= canvasPosition.x - this.handleWidth / 2 && x <= canvasPosition.x + this.handleWidth / 2
&& y >= canvasPosition.y - this.handleWidth / 2 && y <= canvasPosition.y + this.handleWidth / 2;
};
function drawVertexHandle(ctx, vertex){
// preserve context
ctx.save();
var translation = convertToCanvasTranslation(vertex.position);
ctx.translate(translation.x, translation.y);
ctx.fillStyle = (vertex === focusUIElement
&& vertex === activePolygon.initialVertex
&& (isState('POLYGON_DRAW') || isState('RECT_DRAW')))
? '#FF6600' // if mouse is hovering over this and a click would close the polygon
: '#FFFFFF'; // default
ctx.strokeStyle = '#000000';
ctx.beginPath();
ctx.rect(-vertex.handleWidth/2, // x
-vertex.handleWidth/2, // y
vertex.handleWidth, // width
vertex.handleWidth); // height
ctx.stroke();
ctx.fill();
// restore context
ctx.restore();
}
function Polygon(initialVertex){
var polygonInstance = this;
this.initialVertex = initialVertex || null;
this.onMouseDown = function(evt){
return false;
};
this.onClick = function(evt){
if(solutionEditable || annotationsEditable){
activePolygon = polygonInstance;
dirty = true;
return false; // don't bubble
} else {
return true; // bubble
}
};
}
Polygon.prototype.addVertex = function(vertex){
if(this.initialVertex !== null){
var last = this.initialVertex;
while(last.next !== null && last.next !== this.initialVertex){
last = last.next;
}
last.next = vertex;
} else {
this.initialVertex = vertex;
}
vertex.polygon = this;
dirty = true;
};
Polygon.prototype.clear = function () {
this.initialVertex = null;
}
Polygon.prototype.deleteVertex = function(vertex){
if(this.initialVertex !== null && this.initialVertex.equals(vertex)){
this.initialVertex = this.initialVertex.next;
} else {
var deleted = false
, current = this.initialVertex
, next = current.next;
while(!deleted && next !== null && next !== this.initialVertex){
if(next.equals(vertex)){
current.next = next.next;
deleted = true;
} else {
current = next;
next = current.next;
}
}
}
};
Polygon.prototype.getVertices = function(){
var vertices = [], currentVertex = this.initialVertex;
while(currentVertex !== null){
if(vertices.indexOf(currentVertex) === -1){
vertices.push(currentVertex);
}
currentVertex = (currentVertex.next !== this.initialVertex) ? currentVertex.next : null;
}
return vertices;
};
function drawPolygon(ctx, polygon, fillColor, strokeColor){
// only draw lines or polygon if there is more than one vertex
if(polygon.initialVertex !== null && polygon.initialVertex.next !== null){
var drawPos = { x: 0, y: 0}
, current = polygon.initialVertex
, next
, translation = convertToCanvasTranslation(polygon.initialVertex.position)
;
ctx.save();
ctx.globalAlpha = options.fill || 0.7;
ctx.translate(translation.x, translation.y);
ctx.scale(scale, scale);
ctx.beginPath();
ctx.moveTo(drawPos.x, drawPos.y);
do {
next = current.next;
drawPos = {
x: drawPos.x + (next.position.x - current.position.x),
y: drawPos.y + (next.position.y - current.position.y)
};
ctx.lineTo(drawPos.x, drawPos.y);
current = next;
} while(current.next !== null && current !== polygon.initialVertex);
ctx.fillStyle = fillColor || '#0000FF';
ctx.strokeStyle = strokeColor || '#66FF33';
if(current === polygon.initialVertex){
ctx.strokeStyle = strokeColor || '#000000';
ctx.closePath();
ctx.fill();
}
ctx.lineWidth = defaultLineWidth;
ctx.stroke();
ctx.restore();
}
// draw handles
if((polygon === activePolygon && (solutionEditable || annotationsEditable))){
polygon.getVertices().forEach(function(handle){
drawVertexHandle(ctx, handle);
});
}
}
Polygon.prototype.isClosed = function(){
var current = this.initialVertex;
if(current === null) return false;
var count = 0;
while(current.next !== null && current.next !== this.initialVertex){
current = current.next;
count++;
}
return current.next === this.initialVertex // last vertex has to be same as the first
&& count > 1; // at least to other vertices have to be traversed before returning,
// otherwise it would only be a line
};
Polygon.prototype.getLastVertex = function(){
var current = this.initialVertex;
if(current === null) return null;
while(current.next !== null && current.next !== this.initialVertex) current = current.next;
return current;
};
Polygon.prototype.getLength = function(){
if(this.initialVertex === null) return 0;
var length = 1;
var current = this.initialVertex;
while(current.next !== null && current.next !== this.initialVertex){
current = current.next;
length++;
}
return length;
};
function isLeft(p0, p1, p2){
// p0, p1, p2: point objects, like { x: 0, y: 0 }
// returns:
// >0 : for p2 left of the line through p0 and p1
// =0 : for p2 on the line
// <0 : for p2 right of the line
// see: http://geomalgorithms.com/a01-_area.html
return ( (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y));
}
Polygon.prototype.isWithinBounds = function(x, y){
// get all vertices
var vertices = this.getVertices()
// winding number
, wn = 0
// point to check
, p = convertToImagePosition({ x: x, y: y });
// if polygon is not closed, the coordinates can't be within bounds
if(vertices.length < 3 || vertices[vertices.length - 1].next !== vertices[0]) return false;
// adding start point again (too include last, closing edge)
vertices.push(vertices[0]);
// algorithm see: http://geomalgorithms.com/a03-_inclusion.html
for(var i = 0; i + 1 < vertices.length; i++){ // edge from vertices[i] to vertices[i+1]
if(vertices[i].position.y <= p.y){ // start y <= p.y
if(vertices[i + 1].position.y > p.y){ // an upward crossing
if(isLeft(vertices[i].position, vertices[i + 1].position, p) > 0){ // P left of edge
wn++; // have a valid up intersect
}
}
} else { // start y > p.y
if(vertices[i + 1].position.y <= p.y){ // a downward crossing
if(isLeft(vertices[i].position, vertices[i + 1].position, p) < 0){ // P right of edge
wn--; // have a valid down intersect
}
}
}
}
// wn == 0 only when p is outside
return wn !== 0;
};
Polygon.prototype.close = function(){
if(this.getVertices().length > 2){
this.addVertex(this.initialVertex);
}
// console.log('viewer.Polygon.close',this.getVertices().length,this.isClosed());
};
// (self.annotations.length + 1) % annotationColors.length
function addNewAnnotation(polygon, color, stroke){
var newAnnotation = {
polygon: polygon || new Polygon(),
color: color || annotationColors[self.currentAnnotationColor],
stroke:stroke,
};
self.annotations.push(newAnnotation);
return newAnnotation;
}
function cleanupAnnotations(){
// delete all unclosed annotations
self.annotations = self.annotations.filter(function(annotation){
if(typeof annotation.polygon === 'object'
&& typeof annotation.polygon.isClosed !== 'undefined'){
return annotation.polygon.isClosed();
}
return false;
});
}
function getAnswerColor(){
var color = '#0000ff'; // Default: blue
// change color if answer is within solution
if(solutionVisible){ // show solution flag enabled?
var canvasAnswer = convertToCanvasTranslation(self.answer);
// is the answer within the solution?
if(self.solution !== null
&& self.solution.isWithinBounds(canvasAnswer.x, canvasAnswer.y)){
color = '#00ff00'; //green
} else {
color = '#ff0000'; // red
}
}
return color;
}
function drawAnswer(ctx){
// preserve context
ctx.save();
var shapeScale = 1.5
, transalation = convertToCanvasTranslation(self.answer);
ctx.translate(transalation.x, transalation.y);
ctx.scale(shapeScale * scale, shapeScale * scale);
ctx.shadowColor = '#ffffff';
ctx.shadowBlur = 5;
drawAwesomeIcon(ctx, '\uf05b', getAnswerColor(), 0, 0, 50);
// restore context
ctx.restore();
}
function getUIElements(){
var collectedUIElements = [];
// add buttons
collectedUIElements = collectedUIElements.concat(buttons).concat(colorButtons);
// only add the polygon vertices handler
// if there is an active polygon
// and we are in polygon edit mode
// (and add them before the polygons)
if((solutionEditable || annotationsEditable) && activePolygon !== null){
collectedUIElements = collectedUIElements.concat(activePolygon.getVertices());
}
// add annotations
collectedUIElements = collectedUIElements.concat(self.annotations.map(function(annotation){
return annotation.polygon;
}));
// add solution, if it exists
if(self.solution !== null) collectedUIElements.push(self.solution);
return collectedUIElements;
}
// Priority of UI elements: Buttons >> PolyPoints >> Polys
function getUIElement(evt){
var rect = canvas.getBoundingClientRect()
, pos = {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
}
, activeUIElement =
getUIElements()
.filter(function(uiElement){
if (uiElement.isWithinBounds(pos.x, pos.y)) {
// Polygon points must be selected if in polygon drawing mode! (except buttons)
if (uiElement.icon) return true; // Button
if (activePolygon && (isState('POLYGON_DRAW')||isState('RECT_DRAW'))) return uiElement.polygon?true:false;
else
return true;
}
return false
});
return (activeUIElement.length > 0 ) ? activeUIElement[0] : null;
}
function onMouseDown(evt){
if(evt.button === 0){ // left/main button
var activeElement = getUIElement(evt);
if(activeElement === null || !activeElement.onMouseDown(evt)){
// set flag for image moving
leftMouseButtonDown = true;
}
}
}
function onMouseUp(evt){
if(evt.button === 0){ // left/main button
activeMoveElement = centre;
leftMouseButtonDown = false;
}
}
function onMouseClick(evt){
// console.log('click',activePolygon,solutionEditable,self.solution);
if(evt.button === 0){ // left/main button
var activeElement = getUIElement(evt);;
if(activeElement === null || activeElement.onClick(evt)){
var rect = canvas.getBoundingClientRect()
, clickPos = {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
if(isState('ANSWER_DRAW')){
self.answer = convertToImagePosition(clickPos);
dirty = true;
}
else if(isState('POLYGON_DRAW')){
if(evt.shiftKey){
// close polygon
if(activePolygon !== null){
activePolygon.close();
state = states.DEFAULT;
if(activePolygon === self.solution){
self.onSolutionChange(self.exportSolution());
} else {
cleanupAnnotations();
self.onAnnotationChange(self.exportAnnotations());
}
}
} else {
var newVertexPosition = convertToImagePosition(clickPos)
, newVertex = createVertex(newVertexPosition.x, newVertexPosition.y);
if(activePolygon === null){
if(solutionEditable){
if(self.solution === null){
self.solution = new Polygon();
}
activePolygon = self.solution;
} else if(annotationsEditable){
console.log("No active polygon. Click on a polygon to edit it!");
return;
} else {
console.log("invalid POLYGON_DRAW state");
return;
}
}
activePolygon.addVertex(newVertex);
}
dirty = true;
}
else if(isState('RECT_DRAW')){
if(evt.shiftKey){
// close polygon
if(activePolygon !== null){
activePolygon.close();
state = states.DEFAULT;
// console.log(activePolygon)
if(activePolygon === self.solution){
self.onSolutionChange(self.exportSolution());
} else {
cleanupAnnotations();
self.onAnnotationChange(self.exportAnnotations());
}
}
} else {
var newVertexPosition = convertToImagePosition(clickPos)
, newVertex = createVertex(newVertexPosition.x, newVertexPosition.y);
if(activePolygon === null){
if(solutionEditable){
if(self.solution === null){
self.solution = new Polygon();
}
activePolygon = self.solution;
} else if(annotationsEditable){
console.log("No active polygon. Click on a polygon to edit it!");
return;
} else {
console.log("invalid RECT_DRAW state");
return;
}
}
activePolygon.addVertex(newVertex);
}
dirty = true;
}
else {
if(activePolygon !== null){
activePolygon = null;
dirty = true;
}
}
}
}
}
function onMouseWheel(evt){
if (!evt) evt = event;
evt.preventDefault();
if(evt.detail < 0 || evt.wheelDelta > 0){ // up -> smaller
self.zoomOut();
} else { // down -> larger
self.zoomIn();
}
}
function onMouseMove(evt){
var rect = canvas.getBoundingClientRect()
, newPos = {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
mouseLastPos = mouseLastPos || { x: 0, y: 0 };
var deltaX = newPos.x - mouseLastPos.x
, deltaY = newPos.y - mouseLastPos.y;
if(leftMouseButtonDown){
if (activePolygon && (isState('POLYGON_DRAW')||isState('RECT_DRAW'))) return; // don't move image if ploygon drawing is active
if(activeMoveElement === centre){
activeMoveElement.x -= deltaX / scale;
activeMoveElement.y -= deltaY / scale;
} else {
activeMoveElement.x += deltaX / scale;
activeMoveElement.y += deltaY / scale;
if(activePolygon === self.solution){
self.onSolutionChange(self.exportSolution());
} else {
cleanupAnnotations();
self.onAnnotationChange(self.exportAnnotations());
}
}
dirty = true;
} else {
var activeElement = getUIElement(evt)
, oldToolTip = currentTooltip;
if(activeElement !== null){
if(typeof activeElement.tooltip !== 'undefined'){
currentTooltip = activeElement.tooltip;
}
// new focus UI element?
if(activeElement !== focusUIElement){
focusUIElement = activeElement;
}
} else { // no activeElement
currentTooltip = null;
if(focusUIElement !== null){
focusUIElement = null;
}
}
if(oldToolTip !== currentTooltip) dirty = true;
}
mouseLastPos = newPos;
if(solutionEditable || annotationsEditable) dirty = true;
}
function Button(icon, tooltip){
// drawn on position
this.drawPosition = null;
this.drawRadius = 0;
// transparency
this.alpha = 0.5;
// border
this.lineWidth = 0; // default: 0 == disabled
this.strokeStyle = '#000000';
// color
this.color = '#000000';
// icon unicode from awesome font
this.icon = icon;
this.iconColor = '#ffffff';
// tooltip
this.tooltip = tooltip || null;
// enabled state
this.enabled = false;
this.enabledAlpha = 0.9;
// click action
this.onClick = function(){ alert('no click action set!'); return true; };
// mouse down action
this.onMouseDown = function(){ return false; };
}
Button.prototype.isWithinBounds = function(x, y){
if(this.drawPosition === null) return false;
var dx = Math.abs(this.drawPosition.x - x)
, dy = Math.abs(this.drawPosition.y - y);
return dx * dx + dy * dy <= this.drawRadius * this.drawRadius;
};
Button.prototype.draw = function(ctx, x, y, radius){
this.drawPosition = { x: x, y: y };
this.drawRadius = radius;
// preserve context
ctx.save();
// drawing settings
var isEnabled = (typeof this.enabled === 'function') ? this.enabled() : this.enabled;
ctx.globalAlpha = (isEnabled) ? this.enabledAlpha : this.alpha;
ctx.fillStyle= this.color;
ctx.lineWidth = 0;
// draw circle
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
if(this.lineWidth > 0){
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.strokeStyle;
ctx.stroke();
}
// draw icon
if(this.icon !== null){
ctx.save();
// ctx.globalCompositeOperation = 'destination-out';
drawAwesomeIcon(ctx, this.icon, this.iconColor, x, y, radius);
ctx.restore();
}
// restore context
ctx.restore();
};
function createAnnotationColorButton(color,index){
var button = new Button(null, 'Change active annotation to this color');
button.color = color;
button.lineWidth = 1;
button.enabled = function(){
return annotationsEditable && activePolygon !== null;
};
button.onClick = function(){
var i, found;
self.currentAnnotationColor=index;
if(activePolygon !== null){
found = false;
for(i=0; !found && i < self.annotations.length; i++){
if(activePolygon === self.annotations[i].polygon){
self.annotations[i].color = color;
dirty = true;
found = true;
}
}
}
};
if (options.labels && options.labels[index]) {
button.icon=options.labels[index];
button.iconColor='black';
}
return button;
}
function drawAwesomeIcon(ctx, icon, color, centreX, centreY, size){
// font settings
ctx.font = size + "px Arial";
ctx.globalAlpha = 1;
// calculate position
var textSize = ctx.measureText(icon)
, x = centreX - textSize.width / 2
, y = centreY + size * 0.7 / 2;
// draw it
ctx.fillStyle = color;
ctx.fillText(icon, x, y);
}
function addEventListener(eventTarget, eventType, listener){
eventTarget.addEventListener(eventType, listener);
events.push({eventTarget: eventTarget, eventType: eventType, listener: listener});
}
function removeAllEventListeners(){
var _i, _events = events.slice(), _current;
for(_i = 0; _i < _events.length; _i++){
_current = _events[_i];
_current.eventTarget.removeEventListener(_current.eventType, _current.listener);
}
events = [];
}
function addEventListeners(){
// dragging image or ui-elements
addEventListener(document, 'mousedown', onMouseDown);
addEventListener(document, 'mouseup', onMouseUp);
// zooming
addEventListener(canvas, 'DOMMouseScroll', onMouseWheel);
addEventListener(canvas, 'mousewheel', onMouseWheel);
// moving
addEventListener(canvas, 'mousemove', onMouseMove);
// setting answer
addEventListener(canvas, 'click', onMouseClick);
}
this.dispose = function(){
removeAllEventListeners();
stopRendering = true;
};
this.refresh = function(){
self.dirty = true;
};
this.updateImage = function(image){
imageData=image;
if (imageData.data instanceof Buffer ||
imageData.data instanceof Uint8Array) {
imageData=Object.assign({},imageData);
imageData.data=new Uint8ClampedArray(imageData.data.buffer)
}
self.image = new ImageData(imageData.data,imageData.width,imageData.height);
onImageLoad()
};
function initialize(){
//// init image
if (imageUrl) {
self.image.addEventListener('load', onImageLoad, false);
self.image.src = imageUrl;
// image provided externally
} else if (imageData) {
onImageLoad()
}
//// init solution
if(Object.prototype.toString.call(options.solution) === '[object Array]')
self.importSolution(options.solution);
//// init annotations
if(Object.prototype.toString.call(options.annotations) === '[object Array]')
self.importAnnotations(options.annotations);
//// init buttons
// apply zooming functions to their buttons
zoomOutButton.onClick = function(){ self.zoomOut(); return false; };
zoomInButton.onClick = function(){ self.zoomIn(); return false; };
// if answer feature enable, show their buttons
if(answerEditable){
// delete answer button
deleteAnswerButton.onClick = function(){
self.answer = null;
dirty = true;
return false;
};
// add answer button
addAnswerButton.enabled = function(){
return isState('ANSWER_DRAW');
};
// onclick: toggle draw answer mode
addAnswerButton.onClick = function(){
state = isState('ANSWER_DRAW') ? states.DEFAULT : states.ANSWER_DRAW;
dirty = true;
return false;
};
// merge them with the other buttons
buttons = defaultButtons.concat(answerButtons);
}
var drawPolygonPointEnabled = function(){
return isState('POLYGON_DRAW');
}
, drawPolygonPointOnClick = function(){
state = isState('POLYGON_DRAW')
? states.DEFAULT
: states.POLYGON_DRAW;
dirty = true;
return false;
}
, movePolygonPointEnabled = function(){
return isState('POLYGON_MOVE');
}
, movePolygonPointOnClick = function(){
state = isState('POLYGON_MOVE')
? states.DEFAULT
: states.POLYGON_MOVE;
dirty = true;
return false;
}
, deletePolygonPointEnabled = function(){
return isState('POLYGON_POINT_DELETE');
}
, deletePolygonPointOnClick = function(){
state = isState('POLYGON_POINT_DELETE')
? states.DEFAULT
: states.POLYGON_POINT_DELETE;
dirty = true;
return false;
};
// if solution feature enable, show their buttons
if(solutionEditable){
drawSolutionPointButton.enabled = drawPolygonPointEnabled;
drawSolutionPointButton.onClick = drawPolygonPointOnClick;
moveSolutionButton.enabled = movePolygonPointEnabled;
moveSolutionButton.onClick = movePolygonPointOnClick;
deleteSolutionPointButton.enabled = deletePolygonPointEnabled;
deleteSolutionPointButton.onClick = deletePolygonPointOnClick;
deleteSolutionButton.onClick = function(){
self.solution = activePolygon = null;
self.onSolutionChange(self.exportSolution());
dirty = true;
return false;
};
// merge them with the other buttons
buttons = defaultButtons.concat(solutionButtons);
}
// if annotation feature enable, show their buttons
if(annotationsEditable){
addNewAnnotationButton.enabled = function(){
return state == states.POLYGON_DRAW;
};
addNewAnnotationButton.onClick = function(){
cleanupAnnotations();
var newAnnotation = addNewAnnotation();
activePolygon = newAnnotation.polygon;
state = states.POLYGON_DRAW;
return false;
};
addNewRectAnnotationButton.enabled = function(){
return state == states.RECT_DRAW;
};
addNewRectAnnotationButton.onClick = function(){
cleanupAnnotations();
var newAnnotation = addNewAnnotation();
activePolygon = newAnnotation.polygon;
activePolygon.shape='rect';
state = states.RECT_DRAW;
return false;
};
cancelAnnotationButton.onClick = function(){
cleanupAnnotations();
activePolygon = null;
state = states.DEFAULT;
return false;
};
drawAnnotationPointButton.enabled = drawPolygonPointEnabled;
drawAnnotationPointButton.onClick = drawPolygonPointOnClick;
moveAnnotationButton.enabled = movePolygonPointEnabled;
moveAnnotationButton.onClick = movePolygonPointOnClick;
deleteAnnotationPointButton.enabled = deletePolygonPointEnabled;
deleteAnnotationPointButton.onClick = deletePolygonPointOnClick;
deleteAnnotationButton.onClick = function(){
var deletePosition = -1
, i = 0;
for(;i < self.annotations.length; i++){
if(self.annotations[i].polygon === activePolygon){
deletePosition = i;
break;
}
}
if(deletePosition > -1){
self.annotations.splice(deletePosition, 1);
activePolygon = null;
dirty = true;
cleanupAnnotations();
self.onAnnotationChange(self.exportAnnotations());
return false;
}
return true;
};
// merge them with the other buttons
buttons = defaultButtons.concat(annotationButtons);
// adding color buttons
colorButtons = annotationColors.map(function(color,index){
return createAnnotationColorButton(color,index);
});
}
//// init Input handling
addEventListeners();
}
initialize();
}
if (typeof module != 'undefined') module.exports=ImageViewer;
else window.ImageViewer = ImageViewer;
}(window));
};
BundleModuleCode['plugins/image/poly']=function (module,exports,global,process){
// https://github.com/tcql/turf-overlaps
function clockwise(ring){
var sum = 0;
var i = 1;
var len = ring.length;
var prev,cur;
while(i 0;
}
function doLinesIntersect(line1, line2) {
var p1 = line1[0],
p2 = line1[1],
p3 = line2[0],
p4 = line2[1];
return (clockwise([p1, p3, p4, p1]) != clockwise([p2, p3, p4, p2]))
&& (clockwise([p1, p2, p3, p1]) != clockwise([p1, p2, p4, p1]));
}
function testLines(ring1, ring2) {
for (var p1_ind = 0; p1_ind < (ring1.length - 1); p1_ind++) {
var p1_line = [ring1[p1_ind], ring1[p1_ind + 1]];
for (var p2_ind = 0; p2_ind < (ring2.length - 1); p2_ind++) {
var p2_line = [ring2[p2_ind], ring2[p2_ind + 1]];
if (doLinesIntersect(p1_line, p2_line)) {
return true;
}
}
}
return false;
}
function getCoordinates(polygon) {
var coords = [[[]]];
switch (polygon.geometry.type) {
case 'LineString':
coords = [[polygon.geometry.coordinates]];
break;
case 'Polygon':
coords = [polygon.geometry.coordinates];
break;
case 'MultiPolygon':
coords = polygon.geometry.coordinates;
break;
}
return coords;
}
/**
* Since we don't care about the overlap amount,
* or it's geometry, but rather just whether overlap
* occurs, polygon overlap can most simply be expressed
* by testing whether any pair of edges on the two polygons
* intersect. If there are any edge intersections, the
* polygons overlap.
*
* @param {[type]} poly1 [description]
* @param {[type]} poly2 [description]
* @return {[type]} [description]
*/
function overlapPolygons (poly1, poly2) {
var coords1 = getCoordinates(poly1),
coords2 = getCoordinates(poly2);
// This looks completely stupid ridiculous to
// have so many nested loops, but it supports
// multipolygons nicely. In the case of polygons
// or linestrings, the outer loops are only one
// iteration.
return coords1.some(function (rings1) {
return coords2.some(function (rings2) {
return rings1.some(function(ring1) {
return rings2.some(function(ring2) {
return testLines(ring1, ring2);
});
});
});
});
};
// pt is [x,y] and ring is [[x,y], [x,y],..]
function inRing (pt, ring) {
var isInside = false;
for (var i = 0, j = ring.length - 1; i < ring.length; j = i++) {
var xi = ring[i][0], yi = ring[i][1];
var xj = ring[j][0], yj = ring[j][1];
var intersect = ((yi > pt[1]) !== (yj > pt[1])) &&
(pt[0] < (xj - xi) * (pt[1] - yi) / (yj - yi) + xi);
if (intersect) isInside = !isInside;
}
return isInside;
}
function insidePolygon(point, polygon) {
// invariant.featureOf(point, 'Point', 'inside');
var polys = polygon.geometry.coordinates;
var pt = [point.geometry.coordinates[0], point.geometry.coordinates[1]];
// normalize to multipolygon
if (polygon.geometry.type === 'Polygon') polys = [polys];
var insidePoly = false;
var i = 0;
while (i < polys.length && !insidePoly) {
// check if it is in the outer ring first
if(inRing(pt, polys[i][0])) {
var inHole = false;
var k = 1;
// check for the point in any of the holes
while(k < polys[i].length && !inHole) {
if(inRing(pt, polys[i][k])) {
inHole = true;
}
k++;
}
if(!inHole) insidePoly = true;
}
i++;
}
return insidePoly;
};
/**
* Takes an array of LinearRings of coordinate arrays and optionally an {@link Object} with properties and returns a {@link Polygon} feature.
*
* typeof coordinates = [number,number][][] | {x,y}[][]
* @module turf/polygon
* @category helper
* @param {Array>} rings an array of LinearRings
* @param {Object=} properties a properties object
* @returns {Feature} a Polygon feature
* @throws {Error} throw an error if a LinearRing of the polygon has too few positions
* or if a LinearRing of the Polygon does not have matching Positions at the
* beginning & end.
* @example
* var polygon = turf.polygon([[
* [-2.275543, 53.464547],
* [-2.275543, 53.489271],
* [-2.215118, 53.489271],
* [-2.215118, 53.464547],
* [-2.275543, 53.464547]
* ]], { name: 'poly1', population: 400});
*
* //=polygon
*/
// public API
function Polygon(coordinates, properties) {
if (coordinates === null) throw new Error('No coordinates passed');
if (coordinates[0][0].x!=undefined) coordinates=coordinates.map(function (ring) {
return ring.map(function (p) { return [p.x,p.y] })
});
for (var i = 0; i < coordinates.length; i++) {
var ring = coordinates[i];
for (var j = 0; j < ring[ring.length - 1].length; j++) {
if (ring.length < 4) {
throw new Error('Each LinearRing of a Polygon must have 4 or more Positions.');
}
if (ring[ring.length - 1][j] !== ring[0][j]) {
throw new Error('First and last Position are not equivalent.');
}
}
}
var polygon = {
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": coordinates
},
"properties": properties
};
if (!polygon.properties) {
polygon.properties = {};
}
return polygon;
};
function Point (coordinates) {
if (coordinates.x!=undefined) coordinates=[coordinates.x,coordinates.y];
return {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": coordinates
}
}
}
function inside (point,poly) {
if (poly.type!='Feature') poly=Polygon(poly);
if (point.type!='Feature') point=Point(point);
return insidePolygon(point,poly);
}
// public API
function overlap (poly1,poly2) {
if (poly1.type!='Feature') poly1=Polygon(poly1);
if (poly2.type!='Feature') poly2=Polygon(poly2);
return overlapPolygons(poly1,poly2);
}
function BoundingBox (poly) {
var b = { x1:poly.geometry.coordinates[0][0][0],
y1:poly.geometry.coordinates[0][0][1],
x2:poly.geometry.coordinates[0][0][0],
y2:poly.geometry.coordinates[0][0][1] }
for (var ring=0;ring= 0 ? this.height - 1 : -this.height
for (var y = this.height - 1; y >= 0; y--) {
var line = this.bottom_up ? y : this.height - 1 - y
for (var x = 0; x < xlen; x++) {
var b = this.buffer.readUInt8(this.pos++);
var location = line * this.width * 4 + x*8*4;
for (var i = 0; i < 8; i++) {
if(x*8+i>(7-i))&0x1)];
this.data[location+i*4] = 0;
this.data[location+i*4 + 1] = rgb.blue;
this.data[location+i*4 + 2] = rgb.green;
this.data[location+i*4 + 3] = rgb.red;
}else{
break;
}
}
}
if (mode != 0){
this.pos+=(4 - mode);
}
}
};
BmpDecoder.prototype.bit4 = function() {
//RLE-4
if(this.compress == 2){
this.data.fill(0xff);
var location = 0;
var lines = this.bottom_up?this.height-1:0;
var low_nibble = false;//for all count of pixel
while(location>4);
}
if ((i & 1) && (i+1 < b)){
c = this.buffer.readUInt8(this.pos++);
}
low_nibble = !low_nibble;
}
if ((((b+1) >> 1) & 1 ) == 1){
this.pos++
}
}
}else{//encoded mode
for (var i = 0; i < a; i++) {
if (low_nibble) {
setPixelData.call(this, (b & 0x0f));
} else {
setPixelData.call(this, (b & 0xf0)>>4);
}
low_nibble = !low_nibble;
}
}
}
function setPixelData(rgbIndex){
var rgb = this.palette[rgbIndex];
this.data[location] = 0;
this.data[location + 1] = rgb.blue;
this.data[location + 2] = rgb.green;
this.data[location + 3] = rgb.red;
location+=4;
}
} else {
var xlen = Math.ceil(this.width/2);
var mode = xlen%4;
for (var y = this.height - 1; y >= 0; y--) {
var line = this.bottom_up ? y : this.height - 1 - y
for (var x = 0; x < xlen; x++) {
var b = this.buffer.readUInt8(this.pos++);
var location = line * this.width * 4 + x*2*4;
var before = b>>4;
var after = b&0x0F;
var rgb = this.palette[before];
this.data[location] = 0;
this.data[location + 1] = rgb.blue;
this.data[location + 2] = rgb.green;
this.data[location + 3] = rgb.red;
if(x*2+1>=this.width)break;
rgb = this.palette[after];
this.data[location+4] = 0;
this.data[location+4 + 1] = rgb.blue;
this.data[location+4 + 2] = rgb.green;
this.data[location+4 + 3] = rgb.red;
}
if (mode != 0){
this.pos+=(4 - mode);
}
}
}
};
BmpDecoder.prototype.bit8 = function() {
//RLE-8
if(this.compress == 1){
this.data.fill(0xff);
var location = 0;
var lines = this.bottom_up?this.height-1:0;
while(location= 0; y--) {
var line = this.bottom_up ? y : this.height - 1 - y
for (var x = 0; x < this.width; x++) {
var b = this.buffer.readUInt8(this.pos++);
var location = line * this.width * 4 + x * 4;
if (b < this.palette.length) {
var rgb = this.palette[b];
this.data[location] = 0;
this.data[location + 1] = rgb.blue;
this.data[location + 2] = rgb.green;
this.data[location + 3] = rgb.red;
} else {
this.data[location] = 0;
this.data[location + 1] = 0xFF;
this.data[location + 2] = 0xFF;
this.data[location + 3] = 0xFF;
}
}
if (mode != 0) {
this.pos += (4 - mode);
}
}
}
};
BmpDecoder.prototype.bit15 = function() {
var dif_w =this.width % 3;
var _11111 = parseInt("11111", 2),_1_5 = _11111;
for (var y = this.height - 1; y >= 0; y--) {
var line = this.bottom_up ? y : this.height - 1 - y
for (var x = 0; x < this.width; x++) {
var B = this.buffer.readUInt16LE(this.pos);
this.pos+=2;
var blue = (B & _1_5) / _1_5 * 255 | 0;
var green = (B >> 5 & _1_5 ) / _1_5 * 255 | 0;
var red = (B >> 10 & _1_5) / _1_5 * 255 | 0;
var alpha = (B>>15)?0xFF:0x00;
var location = line * this.width * 4 + x * 4;
this.data[location] = alpha;
this.data[location + 1] = blue;
this.data[location + 2] = green;
this.data[location + 3] = red;
}
//skip extra bytes
this.pos += dif_w;
}
};
BmpDecoder.prototype.bit16 = function() {
var dif_w =(this.width % 2)*2;
//default xrgb555
this.maskRed = 0x7C00;
this.maskGreen = 0x3E0;
this.maskBlue =0x1F;
this.mask0 = 0;
if(this.compress == 3){
this.maskRed = this.buffer.readUInt32LE(this.pos);
this.pos+=4;
this.maskGreen = this.buffer.readUInt32LE(this.pos);
this.pos+=4;
this.maskBlue = this.buffer.readUInt32LE(this.pos);
this.pos+=4;
this.mask0 = this.buffer.readUInt32LE(this.pos);
this.pos+=4;
}
var ns=[0,0,0];
for (var i=0;i<16;i++){
if ((this.maskRed>>i)&0x01) ns[0]++;
if ((this.maskGreen>>i)&0x01) ns[1]++;
if ((this.maskBlue>>i)&0x01) ns[2]++;
}
ns[1]+=ns[0]; ns[2]+=ns[1]; ns[0]=8-ns[0]; ns[1]-=8; ns[2]-=8;
for (var y = this.height - 1; y >= 0; y--) {
var line = this.bottom_up ? y : this.height - 1 - y;
for (var x = 0; x < this.width; x++) {
var B = this.buffer.readUInt16LE(this.pos);
this.pos+=2;
var blue = (B&this.maskBlue)<>ns[1];
var red = (B&this.maskRed)>>ns[2];
var location = line * this.width * 4 + x * 4;
this.data[location] = 0;
this.data[location + 1] = blue;
this.data[location + 2] = green;
this.data[location + 3] = red;
}
//skip extra bytes
this.pos += dif_w;
}
};
BmpDecoder.prototype.bit24 = function() {
for (var y = this.height - 1; y >= 0; y--) {
var line = this.bottom_up ? y : this.height - 1 - y
for (var x = 0; x < this.width; x++) {
//Little Endian rgb
var blue = this.buffer.readUInt8(this.pos++);
var green = this.buffer.readUInt8(this.pos++);
var red = this.buffer.readUInt8(this.pos++);
var location = line * this.width * 4 + x * 4;
this.data[location] = 0;
this.data[location + 1] = blue;
this.data[location + 2] = green;
this.data[location + 3] = red;
}
//skip extra bytes
this.pos += (this.width % 4);
}
};
/**
* add 32bit decode func
* @author soubok
*/
BmpDecoder.prototype.bit32 = function(grey) {
//BI_BITFIELDS
if (!grey) {
if(this.compress == 3){
this.maskRed = this.buffer.readUInt32LE(this.pos);
this.pos+=4;
this.maskGreen = this.buffer.readUInt32LE(this.pos);
this.pos+=4;
this.maskBlue = this.buffer.readUInt32LE(this.pos);
this.pos+=4;
this.mask0 = this.buffer.readUInt32LE(this.pos); // TBC
this.pos=this.offset;
for (var y = this.height - 1; y >= 0; y--) {
var line = this.bottom_up ? y : this.height - 1 - y;
for (var x = 0; x < this.width; x++) {
//Little Endian rgba
var alpha = this.buffer.readUInt8(this.pos++);
var blue = this.buffer.readUInt8(this.pos++);
var green = this.buffer.readUInt8(this.pos++);
var red = this.buffer.readUInt8(this.pos++);
var location = line * this.width * 4 + x * 4;
this.data[location] = alpha;
this.data[location + 1] = blue;
this.data[location + 2] = green;
this.data[location + 3] = red;
}
}
} else{
for (var y = this.height - 1; y >= 0; y--) {
var line = this.bottom_up ? y : this.height - 1 - y;
for (var x = 0; x < this.width; x++) {
//Little Endian argb
var blue = this.buffer.readUInt8(this.pos++);
var green = this.buffer.readUInt8(this.pos++);
var red = this.buffer.readUInt8(this.pos++);
var alpha = this.buffer.readUInt8(this.pos++);
var location = line * this.width * 4 + x * 4;
this.data[location] = alpha;
this.data[location + 1] = blue;
this.data[location + 2] = green;
this.data[location + 3] = red;
}
}
}
} else {
// Greylevel image
if(this.compress == 3){
this.maskRed = this.buffer.readUInt32LE(this.pos);
this.pos+=4;
this.maskGreen = this.buffer.readUInt32LE(this.pos);
this.pos+=4;
this.maskBlue = this.buffer.readUInt32LE(this.pos);
this.pos+=4;
this.mask0 = this.buffer.readUInt32LE(this.pos); // TBC
this.pos=this.offset;
var r2=255,g2=255,b2=255;
for (var y = this.height - 1; y >= 0; y--) {
var line = this.bottom_up ? y : this.height - 1 - y;
for (var x = 0; x < this.width; x++) {
//Little Endian rgba
var b = this.buffer.readUInt8(this.pos++);
var g = this.buffer.readUInt8(this.pos++);
var r = this.buffer.readUInt8(this.pos++);
var a = this.buffer.readUInt8(this.pos++);
a=a/255;
if (this.is_with_alpha) {
var r3 = Math.round(((1 - a) * r2) + (a * r))
var g3 = Math.round(((1 - a) * g2) + (a * g))
var b3 = Math.round(((1 - a) * b2) + (a * b))
var v = (r3+g3+b3)/3
} else {
var v = (r+g+b)/3
}
var location = line * this.width + x;
this.data[location] = v;
}
}
} else {
for (var y = this.height - 1; y >= 0; y--) {
var line = this.bottom_up ? y : this.height - 1 - y;
for (var x = 0; x < this.width; x++) {
//Little Endian argb
var b = this.buffer.readUInt8(this.pos++);
var g = this.buffer.readUInt8(this.pos++);
var r = this.buffer.readUInt8(this.pos++);
var a = this.buffer.readUInt8(this.pos++);
var location = line * this.width * 4 + x * 4;
var location = line * this.width * 4 + x * 4;
a=a/255;
if (this.is_with_alpha) {
var r3 = Math.round(((1 - a) * r2) + (a * r))
var g3 = Math.round(((1 - a) * g2) + (a * g))
var b3 = Math.round(((1 - a) * b2) + (a * b))
var v = (r3+g3+b3)/3
} else {
var v = (r+g+b)/3
}
this.data[location] = v;
}
}
}
}
};
BmpDecoder.prototype.getData = function() {
return this.data;
};
var decode = function(bmpData,with_alpha,as_grey) {
var decoder = new BmpDecoder(bmpData,with_alpha,as_grey);
return decoder;
};
/**
* @author shaozilee
*
* BMP format encoder,encode 24bit BMP
* Not support quality compression
*
*/
function BmpEncoder(imgData){
this.buffer = imgData.data;
this.width = imgData.width;
this.height = imgData.height;
this.extraBytes = this.width%4;
this.rgbSize = this.height*(3*this.width+this.extraBytes);
this.headerInfoSize = 40;
this.data = [];
/******************header***********************/
this.flag = "BM";
this.reserved = 0;
this.offset = 54;
this.fileSize = this.rgbSize+this.offset;
this.planes = 1;
this.bitPP = 24;
this.compress = 0;
this.hr = 0;
this.vr = 0;
this.colors = 0;
this.importantColors = 0;
}
BmpEncoder.prototype.encode = function() {
var tempBuffer = new Buffer(this.offset+this.rgbSize);
this.pos = 0;
tempBuffer.write(this.flag,this.pos,2);this.pos+=2;
tempBuffer.writeUInt32LE(this.fileSize,this.pos);this.pos+=4;
tempBuffer.writeUInt32LE(this.reserved,this.pos);this.pos+=4;
tempBuffer.writeUInt32LE(this.offset,this.pos);this.pos+=4;
tempBuffer.writeUInt32LE(this.headerInfoSize,this.pos);this.pos+=4;
tempBuffer.writeUInt32LE(this.width,this.pos);this.pos+=4;
tempBuffer.writeInt32LE(-this.height,this.pos);this.pos+=4;
tempBuffer.writeUInt16LE(this.planes,this.pos);this.pos+=2;
tempBuffer.writeUInt16LE(this.bitPP,this.pos);this.pos+=2;
tempBuffer.writeUInt32LE(this.compress,this.pos);this.pos+=4;
tempBuffer.writeUInt32LE(this.rgbSize,this.pos);this.pos+=4;
tempBuffer.writeUInt32LE(this.hr,this.pos);this.pos+=4;
tempBuffer.writeUInt32LE(this.vr,this.pos);this.pos+=4;
tempBuffer.writeUInt32LE(this.colors,this.pos);this.pos+=4;
tempBuffer.writeUInt32LE(this.importantColors,this.pos);this.pos+=4;
var i=0;
var rowBytes = 3*this.width+this.extraBytes;
for (var y = 0; y 0){
var fillOffset = this.pos+y*rowBytes+this.width*3;
tempBuffer.fill(0,fillOffset,fillOffset+this.extraBytes);
}
}
return tempBuffer;
};
var encode = function(imgData, quality) {
if (typeof quality === 'undefined') quality = 100;
var encoder = new BmpEncoder(imgData);
var data = encoder.encode();
return {
data: data,
width: imgData.width,
height: imgData.height,
depth: 1
};
};
module.exports = {
encode: encode,
decode: decode
};
};
BundleModuleCode['plugins/image/UPNG']=function (module,exports,global,process){
var UPNG = {};
// https://github.com/photopea/UPNG.js
var pako = Require("plugins/image/pako");
// TODO: toRGB8, toGRAY8
UPNG.RGBAtoRGB = function(r, g, b, a, r2,g2,b2){
a=a/255;
var r3 = Math.round(((1 - a) * r2) + (a * r))
var g3 = Math.round(((1 - a) * g2) + (a * g))
var b3 = Math.round(((1 - a) * b2) + (a * b))
return {r:r3,g:g3,b:b3}
}
UPNG.RGB2GRAY = function(rgb){
return Math.round((rgb.r+rgb.g+rgb.b)/3);
}
// @blab+ returns Uint8Array (.buffer returns ArrayBuffer)
UPNG.toRGB8 = function(out)
{
// Quich hack, convert RGBA to RGB
var rgbafrms = UPNG.toRGBA8(out);
return rgbafrms.map(function (img4) {
var len3 = out.width*out.height*3,
img3 = new Uint8Array(len3);
for(var i=0,j=0;i>3)]>>(7-((i&7)<<0)))& 1), cj=3*j; bf[qi]=p[cj]; bf[qi+1]=p[cj+1]; bf[qi+2]=p[cj+2]; bf[qi+3]=(j>2)]>>(6-((i&3)<<1)))& 3), cj=3*j; bf[qi]=p[cj]; bf[qi+1]=p[cj+1]; bf[qi+2]=p[cj+2]; bf[qi+3]=(j>1)]>>(4-((i&1)<<2)))&15), cj=3*j; bf[qi]=p[cj]; bf[qi+1]=p[cj+1]; bf[qi+2]=p[cj+2]; bf[qi+3]=(j>>3)]>>>(7 -((x&7) )))& 1), al=(gr==tr*255)?0:255; bf32[to+x]=(al<<24)|(gr<<16)|(gr<<8)|gr; }
else if(depth== 2) for(var x=0; x>>2)]>>>(6 -((x&3)<<1)))& 3), al=(gr==tr* 85)?0:255; bf32[to+x]=(al<<24)|(gr<<16)|(gr<<8)|gr; }
else if(depth== 4) for(var x=0; x>>1)]>>>(4 -((x&1)<<2)))&15), al=(gr==tr* 17)?0:255; bf32[to+x]=(al<<24)|(gr<<16)|(gr<<8)|gr; }
else if(depth== 8) for(var x=0; x>>2<<5);while(i==0){i=n(N,d,1);m=n(N,d+1,2);d+=3;if(m==0){if((d&7)!=0)d+=8-(d&7);
var D=(d>>>3)+4,q=N[D-4]|N[D-3]<<8;if(Z)W=H.H.W(W,w+q);W.set(new R(N.buffer,N.byteOffset+D,q),w);d=D+q<<3;
w+=q;continue}if(Z)W=H.H.W(W,w+(1<<17));if(m==1){v=b.J;C=b.h;X=(1<<9)-1;u=(1<<5)-1}if(m==2){J=A(N,d,5)+257;
h=A(N,d+5,5)+1;Q=A(N,d+10,4)+4;d+=14;var E=d,j=1;for(var c=0;c<38;c+=2){b.Q[c]=0;b.Q[c+1]=0}for(var c=0;
cj)j=K}d+=3*Q;M(b.Q,j);I(b.Q,j,b.u);v=b.w;C=b.d;
d=l(b.u,(1<>>4;if(p>>>8==0){W[w++]=p}else if(p==256){break}else{var z=w+p-254;
if(p>264){var _=b.q[p-257];z=w+(_>>>3)+A(N,d,_&7);d+=_&7}var $=C[e(N,d)&u];d+=$&15;var s=$>>>4,Y=b.c[s],a=(Y>>>4)+n(N,d,Y&15);
d+=Y&15;while(w>>4;
if(b<=15){A[I]=b;I++}else{var Z=0,m=0;if(b==16){m=3+l(V,n,2);n+=2;Z=A[I-1]}else if(b==17){m=3+l(V,n,3);
n+=3}else if(b==18){m=11+l(V,n,7);n+=7}var J=I+m;while(I>>1;
while(An)n=M;A++}while(A>1,I=N[l+1],e=M<<4|I,b=W-I,Z=N[l]<>>15-W;R[J]=e;Z++}}};H.H.l=function(N,W){var R=H.H.m.r,V=15-W;for(var n=0;n>>V}};H.H.M=function(N,W,R){R=R<<(W&7);var V=W>>>3;N[V]|=R;N[V+1]|=R>>>8};
H.H.I=function(N,W,R){R=R<<(W&7);var V=W>>>3;N[V]|=R;N[V+1]|=R>>>8;N[V+2]|=R>>>16};H.H.e=function(N,W,R){return(N[W>>>3]|N[(W>>>3)+1]<<8)>>>(W&7)&(1<>>3]|N[(W>>>3)+1]<<8|N[(W>>>3)+2]<<16)>>>(W&7)&(1<>>3]|N[(W>>>3)+1]<<8|N[(W>>>3)+2]<<16)>>>(W&7)};
H.H.i=function(N,W){return(N[W>>>3]|N[(W>>>3)+1]<<8|N[(W>>>3)+2]<<16|N[(W>>>3)+3]<<24)>>>(W&7)};H.H.m=function(){var N=Uint16Array,W=Uint32Array;
return{K:new N(16),j:new N(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],q:new N(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],c:new W(32),J:new N(512),_:[],h:new N(32),$:[],w:new N(32768),C:[],v:[],d:new N(32768),D:[],u:new N(512),Q:[],r:new N(1<<15),s:new W(286),Y:new W(30),a:new W(19),t:new W(15e3),k:new N(1<<16),g:new N(1<<15)}}();
(function(){var N=H.H.m,W=1<<15;for(var R=0;R>>1|(V&1431655765)<<1;
V=(V&3435973836)>>>2|(V&858993459)<<2;V=(V&4042322160)>>>4|(V&252645135)<<4;V=(V&4278255360)>>>8|(V&16711935)<<8;
N.r[R]=(V>>>16|V<<16)>>>17}function n(A,l,M){while(l--!=0)A.push(0,M)}for(var R=0;R<32;R++){N.q[R]=N.S[R]<<3|N.T[R];
N.c[R]=N.p[R]<<4|N.z[R]}n(N._,144,8);n(N._,255-143,9);n(N._,279-255,7);n(N._,287-279,8);H.H.n(N._,9);
H.H.A(N._,9,N.J);H.H.l(N._,9);n(N.$,32,5);H.H.n(N.$,5);H.H.A(N.$,5,N.h);H.H.l(N.$,5);n(N.Q,19,0);n(N.C,286,0);
n(N.D,30,0);n(N.v,320,0)}());return H.H.N}()
UPNG.decode._readInterlace = function(data, out)
{
var w = out.width, h = out.height;
var bpp = UPNG.decode._getBPP(out), cbpp = bpp>>3, bpl = Math.ceil(w*bpp/8);
var img = new Uint8Array( h * bpl );
var di = 0;
var starting_row = [ 0, 0, 4, 0, 2, 0, 1 ];
var starting_col = [ 0, 4, 0, 2, 0, 1, 0 ];
var row_increment = [ 8, 8, 8, 4, 4, 2, 2 ];
var col_increment = [ 8, 8, 4, 4, 2, 2, 1 ];
var pass=0;
while(pass<7)
{
var ri = row_increment[pass], ci = col_increment[pass];
var sw = 0, sh = 0;
var cr = starting_row[pass]; while(cr>3]; val = (val>>(7-(cdi&7)))&1;
img[row*bpl + (col>>3)] |= (val << (7-((col&7)<<0)));
}
if(bpp==2) {
var val = data[cdi>>3]; val = (val>>(6-(cdi&7)))&3;
img[row*bpl + (col>>2)] |= (val << (6-((col&3)<<1)));
}
if(bpp==4) {
var val = data[cdi>>3]; val = (val>>(4-(cdi&7)))&15;
img[row*bpl + (col>>1)] |= (val << (4-((col&1)<<2)));
}
if(bpp>=8) {
var ii = row*bpl+col*cbpp;
for(var j=0; j>3)+j];
}
cdi+=bpp; col+=ci;
}
y++; row += ri;
}
if(sw*sh!=0) di += sh * (1 + bpll);
pass = pass + 1;
}
return img;
}
UPNG.decode._getBPP = function(out) {
var noc = [1,null,3,1,2,null,4][out.ctype];
return noc * out.depth;
}
UPNG.decode._filterZero = function(data, out, off, w, h)
{
var bpp = UPNG.decode._getBPP(out), bpl = Math.ceil(w*bpp/8), paeth = UPNG.decode._paeth;
bpp = Math.ceil(bpp/8);
var i=0, di=1, type=data[off], x=0;
if(type>1) data[off]=[0,0,1][type-2];
if(type==3) for(x=bpp; x>>1) )&255;
for(var y=0; y>>1));
for(; x>>1) ); }
else { for(; x>8)&255; buff[p+1] = n&255; },
readUint : function(buff,p) { return (buff[p]*(256*256*256)) + ((buff[p+1]<<16) | (buff[p+2]<< 8) | buff[p+3]); },
writeUint : function(buff,p,n){ buff[p]=(n>>24)&255; buff[p+1]=(n>>16)&255; buff[p+2]=(n>>8)&255; buff[p+3]=n&255; },
readASCII : function(buff,p,l){ var s = ""; for(var i=0; i=0 && yoff>=0) { si = (y*sw+x)<<2; ti = (( yoff+y)*tw+xoff+x)<<2; }
else { si = ((-yoff+y)*sw-xoff+x)<<2; ti = (y*tw+x)<<2; }
if (mode==0) { tb[ti] = sb[si]; tb[ti+1] = sb[si+1]; tb[ti+2] = sb[si+2]; tb[ti+3] = sb[si+3]; }
else if(mode==1) {
var fa = sb[si+3]*(1/255), fr=sb[si]*fa, fg=sb[si+1]*fa, fb=sb[si+2]*fa;
var ba = tb[ti+3]*(1/255), br=tb[ti]*ba, bg=tb[ti+1]*ba, bb=tb[ti+2]*ba;
var ifa=1-fa, oa = fa+ba*ifa, ioa = (oa==0?0:1/oa);
tb[ti+3] = 255*oa;
tb[ti+0] = (fr+br*ifa)*ioa;
tb[ti+1] = (fg+bg*ifa)*ioa;
tb[ti+2] = (fb+bb*ifa)*ioa;
}
else if(mode==2){ // copy only differences, otherwise zero
var fa = sb[si+3], fr=sb[si], fg=sb[si+1], fb=sb[si+2];
var ba = tb[ti+3], br=tb[ti], bg=tb[ti+1], bb=tb[ti+2];
if(fa==ba && fr==br && fg==bg && fb==bb) { tb[ti]=0; tb[ti+1]=0; tb[ti+2]=0; tb[ti+3]=0; }
else { tb[ti]=fr; tb[ti+1]=fg; tb[ti+2]=fb; tb[ti+3]=fa; }
}
else if(mode==3){ // check if can be blended
var fa = sb[si+3], fr=sb[si], fg=sb[si+1], fb=sb[si+2];
var ba = tb[ti+3], br=tb[ti], bg=tb[ti+1], bb=tb[ti+2];
if(fa==ba && fr==br && fg==bg && fb==bb) continue;
//if(fa!=255 && ba!=0) return false;
if(fa<220 && ba>20) return false;
}
}
return true;
}
UPNG.encode = function(bufs, w, h, ps, dels, tabs, forbidPlte)
{
if(ps==null) ps=0;
if(forbidPlte==null) forbidPlte = false;
var nimg = UPNG.encode.compress(bufs, w, h, ps, [false, false, false, 0, forbidPlte]);
UPNG.encode.compressPNG(nimg, -1);
return UPNG.encode._main(nimg, w, h, dels, tabs);
}
UPNG.encodeLL = function(bufs, w, h, cc, ac, depth, dels, tabs) {
var nimg = { ctype: 0 + (cc==1 ? 0 : 2) + (ac==0 ? 0 : 4), depth: depth, frames: [] };
var time = Date.now();
var bipp = (cc+ac)*depth, bipl = bipp * w;
for(var i=0; i1, pltAlpha = false;
var leng = 8 + (16+5+4) /*+ (9+4)*/ + (anim ? 20 : 0);
if(tabs["sRGB"]!=null) leng += 8+1+4;
if(tabs["pHYs"]!=null) leng += 8+9+4;
if(nimg.ctype==3) {
var dl = nimg.plte.length;
for(var i=0; i>>24)!=255) pltAlpha = true;
leng += (8 + dl*3 + 4) + (pltAlpha ? (8 + dl*1 + 4) : 0);
}
for(var j=0; j>>8)&255, b=(c>>>16)&255;
data[offset+ti+0]=r; data[offset+ti+1]=g; data[offset+ti+2]=b;
}
offset+=dl*3;
wUi(data,offset,crc(data,offset-dl*3-4,dl*3+4)); offset+=4; // crc
if(pltAlpha) {
wUi(data,offset, dl); offset+=4;
wAs(data,offset,"tRNS"); offset+=4;
for(var i=0; i>>24)&255;
offset+=dl;
wUi(data,offset,crc(data,offset-dl-4,dl+4)); offset+=4; // crc
}
}
var fi = 0;
for(var j=0; j>2, bln>>2));
for(var j=0; jnw && c==img32[i-nw]) ind[i]=ind[i-nw];
else {
var cmc = cmap[c];
if(cmc==null) { cmap[c]=cmc=plte.length; plte.push(c); if(plte.length>=300) break; }
ind[i]=cmc;
}
}
}
//console.log("make palette", Date.now()-time); time = Date.now();
}
var cc=plte.length; //console.log("colors:",cc);
if(cc<=256 && forbidPlte==false) {
if(cc<= 2) depth=1; else if(cc<= 4) depth=2; else if(cc<=16) depth=4; else depth=8;
depth = Math.max(depth, minBits);
}
for(var j=0; j>1)] |= (inj[ii+x]<<(4-(x&1)*4));
else if(depth==2) for(var x=0; x>2)] |= (inj[ii+x]<<(6-(x&3)*2));
else if(depth==1) for(var x=0; x>3)] |= (inj[ii+x]<<(7-(x&7)*1));
}
cimg=nimg; ctype=3; bpp=1;
}
else if(gotAlpha==false && frms.length==1) { // some next "reduced" frames may contain alpha for blending
var nimg = new Uint8Array(nw*nh*3), area=nw*nh;
for(var i=0; i palette indices", Date.now()-time); time = Date.now();
return {ctype:ctype, depth:depth, plte:plte, frames:frms };
}
UPNG.encode.framize = function(bufs,w,h,alwaysBlend,evenCrd,forbidPrev) {
/* DISPOSE
- 0 : no change
- 1 : clear to transparent
- 2 : retstore to content before rendering (previous frame disposed)
BLEND
- 0 : replace
- 1 : blend
*/
var frms = [];
for(var j=0; jmax) max=x;
if(ymay) may=y;
}
}
if(max==-1) mix=miy=max=may=0;
if(evenCrd) { if((mix&1)==1)mix--; if((miy&1)==1)miy--; }
var sarea = (max-mix+1)*(may-miy+1);
if(sareamax) max=cx;
if(cymay) may=cy;
}
}
if(max==-1) mix=miy=max=may=0;
if(evenCrd) { if((mix&1)==1)mix--; if((miy&1)==1)miy--; }
r = {x:mix, y:miy, width:max-mix+1, height:may-miy+1};
var fr = frms[i]; fr.rect = r; fr.blend = 1; fr.img = new Uint8Array(r.width*r.height*4);
if(frms[i-1].dispose==0) {
UPNG._copyTile(pimg,w,h, fr.img,r.width,r.height, -r.x,-r.y, 0);
UPNG.encode._prepareDiff(cimg,w,h,fr.img,r);
//UPNG._copyTile(cimg,w,h, fr.img,r.width,r.height, -r.x,-r.y, 2);
}
else
UPNG._copyTile(cimg,w,h, fr.img,r.width,r.height, -r.x,-r.y, 0);
}
UPNG.encode._prepareDiff = function(cimg, w,h, nimg, rec) {
UPNG._copyTile(cimg,w,h, nimg,rec.width,rec.height, -rec.x,-rec.y, 2);
/*
var n32 = new Uint32Array(nimg.buffer);
var og = new Uint8Array(rec.width*rec.height*4), o32 = new Uint32Array(og.buffer);
UPNG._copyTile(cimg,w,h, og,rec.width,rec.height, -rec.x,-rec.y, 0);
for(var i=4; i>>2]==o32[(i>>>2)-1]) {
n32[i>>>2]=o32[i>>>2];
//var j = i, c=p32[(i>>>2)-1];
//while(p32[j>>>2]==c) { n32[j>>>2]=c; j+=4; }
}
}
for(var i=nimg.length-8; i>0; i-=4) {
if(nimg[i+7]!=0 && nimg[i+3]==0 && o32[i>>>2]==o32[(i>>>2)+1]) {
n32[i>>>2]=o32[i>>>2];
//var j = i, c=p32[(i>>>2)-1];
//while(p32[j>>>2]==c) { n32[j>>>2]=c; j+=4; }
}
}*/
}
UPNG.encode._filterZero = function(img,h,bpp,bpl,data, filter, levelZero)
{
var fls = [], ftry=[0,1,2,3,4];
if (filter!=-1) ftry=[filter];
else if(h*bpl>500000 || bpp==1) ftry=[0];
var opts; if(levelZero) opts={level:0};
var CMPR = (data.length>10e6 && UZIP!=null) ? UZIP : pako;
var time = Date.now();
for(var i=0; i>1) +256)&255;
if(type==4) for(var x=bpp; x>1))&255;
for(var x=bpp; x>1))&255; }
if(type==4) { for(var x= 0; x>> 1);
else c = c >>> 1;
}
tab[n] = c; }
return tab; })(),
update : function(c, buf, off, len) {
for (var i=0; i>> 8);
return c;
},
crc : function(b,o,l) { return UPNG.crc.update(0xffffffff,b,o,l) ^ 0xffffffff; }
}
UPNG.quantize = function(abuf, ps)
{
var oimg = new Uint8Array(abuf), nimg = oimg.slice(0), nimg32 = new Uint32Array(nimg.buffer);
var KD = UPNG.quantize.getKDtree(nimg, ps);
var root = KD[0], leafs = KD[1];
var planeDst = UPNG.quantize.planeDst;
var sb = oimg, tb = nimg32, len=sb.length;
var inds = new Uint8Array(oimg.length>>2), nd;
if(oimg.length<20e6) // precise, but slow :(
for(var i=0; i>2] = nd.ind; tb[i>>2] = nd.est.rgba;
}
else
for(var i=0; i>2] = nd.ind; tb[i>>2] = nd.est.rgba;
}
return { abuf:nimg.buffer, inds:inds, plte:leafs };
}
UPNG.quantize.getKDtree = function(nimg, ps, err) {
if(err==null) err = 0.0001;
var nimg32 = new Uint32Array(nimg.buffer);
var root = {i0:0, i1:nimg.length, bst:null, est:null, tdst:0, left:null, right:null }; // basic statistic, extra statistic
root.bst = UPNG.quantize.stats( nimg,root.i0, root.i1 ); root.est = UPNG.quantize.estats( root.bst );
var leafs = [root];
while(leafs.length maxL) { maxL=leafs[i].est.L; mi=i; }
if(maxL=s0 || node.i1<=s0);
//console.log(maxL, leafs.length, mi);
if(s0wrong) { node.est.L=0; continue; }
var ln = {i0:node.i0, i1:s0, bst:null, est:null, tdst:0, left:null, right:null }; ln.bst = UPNG.quantize.stats( nimg, ln.i0, ln.i1 );
ln.est = UPNG.quantize.estats( ln.bst );
var rn = {i0:s0, i1:node.i1, bst:null, est:null, tdst:0, left:null, right:null }; rn.bst = {R:[], m:[], N:node.bst.N-ln.bst.N};
for(var i=0; i<16; i++) rn.bst.R[i] = node.bst.R[i]-ln.bst.R[i];
for(var i=0; i< 4; i++) rn.bst.m[i] = node.bst.m[i]-ln.bst.m[i];
rn.est = UPNG.quantize.estats( rn.bst );
node.left = ln; node.right = rn;
leafs[mi]=ln; leafs.push(rn);
}
leafs.sort(function(a,b) { return b.bst.N-a.bst.N; });
for(var i=0; i0) { node0=nd.right; node1=nd.left; }
var ln = UPNG.quantize.getNearest(node0, r,g,b,a);
if(ln.tdst<=planeDst*planeDst) return ln;
var rn = UPNG.quantize.getNearest(node1, r,g,b,a);
return rn.tdst eMq) i1-=4;
if(i0>=i1) break;
var t = nimg32[i0>>2]; nimg32[i0>>2] = nimg32[i1>>2]; nimg32[i1>>2]=t;
i0+=4; i1-=4;
}
while(vecDot(nimg, i0, e)>eMq) i0-=4;
return i0+4;
}
UPNG.quantize.vecDot = function(nimg, i, e)
{
return nimg[i]*e[0] + nimg[i+1]*e[1] + nimg[i+2]*e[2] + nimg[i+3]*e[3];
}
UPNG.quantize.stats = function(nimg, i0, i1){
var R = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0];
var m = [0,0,0,0];
var N = (i1-i0)>>2;
for(var i=i0; i>>0) };
}
UPNG.M4 = {
multVec : function(m,v) {
return [
m[ 0]*v[0] + m[ 1]*v[1] + m[ 2]*v[2] + m[ 3]*v[3],
m[ 4]*v[0] + m[ 5]*v[1] + m[ 6]*v[2] + m[ 7]*v[3],
m[ 8]*v[0] + m[ 9]*v[1] + m[10]*v[2] + m[11]*v[3],
m[12]*v[0] + m[13]*v[1] + m[14]*v[2] + m[15]*v[3]
];
},
dot : function(x,y) { return x[0]*y[0]+x[1]*y[1]+x[2]*y[2]+x[3]*y[3]; },
sml : function(a,y) { return [a*y[0],a*y[1],a*y[2],a*y[3]]; }
}
UPNG.encode.concatRGBA = function(bufs) {
var tlen = 0;
for(var i=0; i= 0) {
buf[len] = 0;
}
} // From zutil.h
var STORED_BLOCK = 0;
var STATIC_TREES = 1;
var DYN_TREES = 2;
/* The three kinds of block type */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
/* The minimum and maximum match lengths */
// From deflate.h
/* ===========================================================================
* Internal compression state.
*/
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2 * L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var Buf_size = 16;
/* size of bit buffer in bi_buf */
/* ===========================================================================
* Constants
*/
var MAX_BL_BITS = 7;
/* Bit length codes must not exceed MAX_BL_BITS bits */
var END_BLOCK = 256;
/* end of block literal code */
var REP_3_6 = 16;
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
var REPZ_3_10 = 17;
/* repeat a zero length 3-10 times (3 bits of repeat count) */
var REPZ_11_138 = 18;
/* repeat a zero length 11-138 times (7 bits of repeat count) */
/* eslint-disable comma-spacing,array-bracket-spacing */
var extra_lbits =
/* extra bits for each length code */
new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0]);
var extra_dbits =
/* extra bits for each distance code */
new Uint8Array([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13]);
var extra_blbits =
/* extra bits for each bit length code */
new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7]);
var bl_order = new Uint8Array([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
/* eslint-enable comma-spacing,array-bracket-spacing */
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
// We pre-fill arrays with 0 to avoid uninitialized gaps
var DIST_CODE_LEN = 512;
/* see definition of array dist_code below */
// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
var static_ltree = new Array((L_CODES + 2) * 2);
zero(static_ltree);
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
var static_dtree = new Array(D_CODES * 2);
zero(static_dtree);
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
var _dist_code = new Array(DIST_CODE_LEN);
zero(_dist_code);
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
zero(_length_code);
/* length code for each normalized match length (0 == MIN_MATCH) */
var base_length = new Array(LENGTH_CODES);
zero(base_length);
/* First normalized length for each code (0 = MIN_MATCH) */
var base_dist = new Array(D_CODES);
zero(base_dist);
/* First normalized distance for each code (0 = distance of 1) */
function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
this.static_tree = static_tree;
/* static tree or NULL */
this.extra_bits = extra_bits;
/* extra bits for each code or NULL */
this.extra_base = extra_base;
/* base index for extra_bits */
this.elems = elems;
/* max number of elements in the tree */
this.max_length = max_length;
/* max bit length for the codes */
// show if `static_tree` has data or dummy - needed for monomorphic objects
this.has_stree = static_tree && static_tree.length;
}
var static_l_desc;
var static_d_desc;
var static_bl_desc;
function TreeDesc(dyn_tree, stat_desc) {
this.dyn_tree = dyn_tree;
/* the dynamic tree */
this.max_code = 0;
/* largest code with non zero frequency */
this.stat_desc = stat_desc;
/* the corresponding static tree */
}
var d_code = function d_code(dist) {
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
};
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
var put_short = function put_short(s, w) {
// put_byte(s, (uch)((w) & 0xff));
// put_byte(s, (uch)((ush)(w) >> 8));
s.pending_buf[s.pending++] = w & 0xff;
s.pending_buf[s.pending++] = w >>> 8 & 0xff;
};
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
var send_bits = function send_bits(s, value, length) {
if (s.bi_valid > Buf_size - length) {
s.bi_buf |= value << s.bi_valid & 0xffff;
put_short(s, s.bi_buf);
s.bi_buf = value >> Buf_size - s.bi_valid;
s.bi_valid += length - Buf_size;
} else {
s.bi_buf |= value << s.bi_valid & 0xffff;
s.bi_valid += length;
}
};
var send_code = function send_code(s, c, tree) {
send_bits(s, tree[c * 2]
/*.Code*/
, tree[c * 2 + 1]
/*.Len*/
);
};
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
var bi_reverse = function bi_reverse(code, len) {
var res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
};
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
var bi_flush = function bi_flush(s) {
if (s.bi_valid === 16) {
put_short(s, s.bi_buf);
s.bi_buf = 0;
s.bi_valid = 0;
} else if (s.bi_valid >= 8) {
s.pending_buf[s.pending++] = s.bi_buf & 0xff;
s.bi_buf >>= 8;
s.bi_valid -= 8;
}
};
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
var gen_bitlen = function gen_bitlen(s, desc) // deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var max_code = desc.max_code;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var extra = desc.stat_desc.extra_bits;
var base = desc.stat_desc.extra_base;
var max_length = desc.stat_desc.max_length;
var h;
/* heap index */
var n, m;
/* iterate over the tree elements */
var bits;
/* bit length */
var xbits;
/* extra bits */
var f;
/* frequency */
var overflow = 0;
/* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) {
s.bl_count[bits] = 0;
}
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s.heap[s.heap_max] * 2 + 1]
/*.Len*/
= 0;
/* root of the heap */
for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
n = s.heap[h];
bits = tree[tree[n * 2 + 1]
/*.Dad*/
* 2 + 1]
/*.Len*/
+ 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n * 2 + 1]
/*.Len*/
= bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) {
continue;
}
/* not a leaf node */
s.bl_count[bits]++;
xbits = 0;
if (n >= base) {
xbits = extra[n - base];
}
f = tree[n * 2]
/*.Freq*/
;
s.opt_len += f * (bits + xbits);
if (has_stree) {
s.static_len += f * (stree[n * 2 + 1]
/*.Len*/
+ xbits);
}
}
if (overflow === 0) {
return;
} // Trace((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length - 1;
while (s.bl_count[bits] === 0) {
bits--;
}
s.bl_count[bits]--;
/* move one leaf down the tree */
s.bl_count[bits + 1] += 2;
/* move one overflow item as its brother */
s.bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits !== 0; bits--) {
n = s.bl_count[bits];
while (n !== 0) {
m = s.heap[--h];
if (m > max_code) {
continue;
}
if (tree[m * 2 + 1]
/*.Len*/
!== bits) {
// Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s.opt_len += (bits - tree[m * 2 + 1]
/*.Len*/
) * tree[m * 2]
/*.Freq*/
;
tree[m * 2 + 1]
/*.Len*/
= bits;
}
n--;
}
}
};
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
var gen_codes = function gen_codes(tree, max_code, bl_count) // ct_data *tree; /* the tree to decorate */
// int max_code; /* largest code with non zero frequency */
// ushf *bl_count; /* number of codes at each bit length */
{
var next_code = new Array(MAX_BITS + 1);
/* next code value for each bit length */
var code = 0;
/* running code value */
var bits;
/* bit index */
var n;
/* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = code + bl_count[bits - 1] << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
//Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES - 1; code++) {
base_length[code] = length;
for (n = 0; n < 1 << extra_lbits[code]; n++) {
_length_code[length++] = code;
}
} //Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length - 1] = code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < 1 << extra_dbits[code]; n++) {
_dist_code[dist++] = code;
}
} //Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7;
/* from now on, all distances are divided by 128 */
for (; code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < 1 << extra_dbits[code] - 7; n++) {
_dist_code[256 + dist++] = code;
}
} //Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS; bits++) {
bl_count[bits] = 0;
}
n = 0;
while (n <= 143) {
static_ltree[n * 2 + 1]
/*.Len*/
= 8;
n++;
bl_count[8]++;
}
while (n <= 255) {
static_ltree[n * 2 + 1]
/*.Len*/
= 9;
n++;
bl_count[9]++;
}
while (n <= 279) {
static_ltree[n * 2 + 1]
/*.Len*/
= 7;
n++;
bl_count[7]++;
}
while (n <= 287) {
static_ltree[n * 2 + 1]
/*.Len*/
= 8;
n++;
bl_count[8]++;
}
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes(static_ltree, L_CODES + 1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
static_dtree[n * 2 + 1]
/*.Len*/
= 5;
static_dtree[n * 2]
/*.Code*/
= bi_reverse(n, 5);
} // Now data ready and we can init static trees
static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); //static_init_done = true;
};
/* ===========================================================================
* Initialize a new block.
*/
var init_block = function init_block(s) {
var n;
/* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES; n++) {
s.dyn_ltree[n * 2]
/*.Freq*/
= 0;
}
for (n = 0; n < D_CODES; n++) {
s.dyn_dtree[n * 2]
/*.Freq*/
= 0;
}
for (n = 0; n < BL_CODES; n++) {
s.bl_tree[n * 2]
/*.Freq*/
= 0;
}
s.dyn_ltree[END_BLOCK * 2]
/*.Freq*/
= 1;
s.opt_len = s.static_len = 0;
s.last_lit = s.matches = 0;
};
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
var bi_windup = function bi_windup(s) {
if (s.bi_valid > 8) {
put_short(s, s.bi_buf);
} else if (s.bi_valid > 0) {
//put_byte(s, (Byte)s->bi_buf);
s.pending_buf[s.pending++] = s.bi_buf;
}
s.bi_buf = 0;
s.bi_valid = 0;
};
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
var copy_block = function copy_block(s, buf, len, header) //DeflateState *s;
//charf *buf; /* the input data */
//unsigned len; /* its length */
//int header; /* true if block header must be written */
{
bi_windup(s);
/* align on byte boundary */
if (header) {
put_short(s, len);
put_short(s, ~len);
} // while (len--) {
// put_byte(s, *buf++);
// }
s.pending_buf.set(s.window.subarray(buf, buf + len), s.pending);
s.pending += len;
};
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
var smaller = function smaller(tree, n, m, depth) {
var _n2 = n * 2;
var _m2 = m * 2;
return tree[_n2]
/*.Freq*/
< tree[_m2]
/*.Freq*/
|| tree[_n2]
/*.Freq*/
=== tree[_m2]
/*.Freq*/
&& depth[n] <= depth[m];
};
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
var pqdownheap = function pqdownheap(s, tree, k) // deflate_state *s;
// ct_data *tree; /* the tree to restore */
// int k; /* node to move down */
{
var v = s.heap[k];
var j = k << 1;
/* left son of k */
while (j <= s.heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s.heap_len && smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s.heap[j], s.depth)) {
break;
}
/* Exchange v with the smallest son */
s.heap[k] = s.heap[j];
k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s.heap[k] = v;
}; // inlined manually
// const SMALLEST = 1;
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
var compress_block = function compress_block(s, ltree, dtree) // deflate_state *s;
// const ct_data *ltree; /* literal tree */
// const ct_data *dtree; /* distance tree */
{
var dist;
/* distance of matched string */
var lc;
/* match length or unmatched char (if dist == 0) */
var lx = 0;
/* running index in l_buf */
var code;
/* the code to send */
var extra;
/* number of extra bits to send */
if (s.last_lit !== 0) {
do {
dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1];
lc = s.pending_buf[s.l_buf + lx];
lx++;
if (dist === 0) {
send_code(s, lc, ltree);
/* send a literal byte */
//Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code + LITERALS + 1, ltree);
/* send the length code */
extra = extra_lbits[code];
if (extra !== 0) {
lc -= base_length[code];
send_bits(s, lc, extra);
/* send the extra length bits */
}
dist--;
/* dist is now the match distance - 1 */
code = d_code(dist); //Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree);
/* send the distance code */
extra = extra_dbits[code];
if (extra !== 0) {
dist -= base_dist[code];
send_bits(s, dist, extra);
/* send the extra distance bits */
}
}
/* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
//Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
// "pendingBuf overflow");
} while (lx < s.last_lit);
}
send_code(s, END_BLOCK, ltree);
};
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
var build_tree = function build_tree(s, desc) // deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var elems = desc.stat_desc.elems;
var n, m;
/* iterate over heap elements */
var max_code = -1;
/* largest code with non zero frequency */
var node;
/* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n * 2]
/*.Freq*/
!== 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
} else {
tree[n * 2 + 1]
/*.Len*/
= 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
tree[node * 2]
/*.Freq*/
= 1;
s.depth[node] = 0;
s.opt_len--;
if (has_stree) {
s.static_len -= stree[node * 2 + 1]
/*.Len*/
;
}
/* node is 0 or 1 so it does not have extra bits */
}
desc.max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = s.heap_len >> 1
/*int /2*/
; n >= 1; n--) {
pqdownheap(s, tree, n);
}
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems;
/* next internal node of the tree */
do {
//pqremove(s, tree, n); /* n = node of least frequency */
/*** pqremove ***/
n = s.heap[1
/*SMALLEST*/
];
s.heap[1
/*SMALLEST*/
] = s.heap[s.heap_len--];
pqdownheap(s, tree, 1
/*SMALLEST*/
);
/***/
m = s.heap[1
/*SMALLEST*/
];
/* m = node of next least frequency */
s.heap[--s.heap_max] = n;
/* keep the nodes sorted by frequency */
s.heap[--s.heap_max] = m;
/* Create a new node father of n and m */
tree[node * 2]
/*.Freq*/
= tree[n * 2]
/*.Freq*/
+ tree[m * 2]
/*.Freq*/
;
s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
tree[n * 2 + 1]
/*.Dad*/
= tree[m * 2 + 1]
/*.Dad*/
= node;
/* and insert the new node in the heap */
s.heap[1
/*SMALLEST*/
] = node++;
pqdownheap(s, tree, 1
/*SMALLEST*/
);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1
/*SMALLEST*/
];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, desc);
/* The field len is now set, we can generate the bit codes */
gen_codes(tree, max_code, s.bl_count);
};
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
var scan_tree = function scan_tree(s, tree, max_code) // deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n;
/* iterates over all tree elements */
var prevlen = -1;
/* last emitted length */
var curlen;
/* length of current code */
var nextlen = tree[0 * 2 + 1]
/*.Len*/
;
/* length of next code */
var count = 0;
/* repeat count of the current code */
var max_count = 7;
/* max repeat count */
var min_count = 4;
/* min repeat count */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code + 1) * 2 + 1]
/*.Len*/
= 0xffff;
/* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n + 1) * 2 + 1]
/*.Len*/
;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
s.bl_tree[curlen * 2]
/*.Freq*/
+= count;
} else if (curlen !== 0) {
if (curlen !== prevlen) {
s.bl_tree[curlen * 2] /*.Freq*/++;
}
s.bl_tree[REP_3_6 * 2] /*.Freq*/++;
} else if (count <= 10) {
s.bl_tree[REPZ_3_10 * 2] /*.Freq*/++;
} else {
s.bl_tree[REPZ_11_138 * 2] /*.Freq*/++;
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
};
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
var send_tree = function send_tree(s, tree, max_code) // deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n;
/* iterates over all tree elements */
var prevlen = -1;
/* last emitted length */
var curlen;
/* length of current code */
var nextlen = tree[0 * 2 + 1]
/*.Len*/
;
/* length of next code */
var count = 0;
/* repeat count of the current code */
var max_count = 7;
/* max repeat count */
var min_count = 4;
/* min repeat count */
/* tree[max_code+1].Len = -1; */
/* guard already set */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n + 1) * 2 + 1]
/*.Len*/
;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
do {
send_code(s, curlen, s.bl_tree);
} while (--count !== 0);
} else if (curlen !== 0) {
if (curlen !== prevlen) {
send_code(s, curlen, s.bl_tree);
count--;
} //Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s.bl_tree);
send_bits(s, count - 3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s.bl_tree);
send_bits(s, count - 3, 3);
} else {
send_code(s, REPZ_11_138, s.bl_tree);
send_bits(s, count - 11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
};
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
var build_bl_tree = function build_bl_tree(s) {
var max_blindex;
/* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, s.bl_desc);
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
if (s.bl_tree[bl_order[max_blindex] * 2 + 1]
/*.Len*/
!== 0) {
break;
}
}
/* Update opt_len to include the bit length tree and counts */
s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
// s->opt_len, s->static_len));
return max_blindex;
};
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
var send_all_trees = function send_all_trees(s, lcodes, dcodes, blcodes) // deflate_state *s;
// int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
var rank;
/* index in bl_order */
//Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
//Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
// "too many codes");
//Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes - 257, 5);
/* not +255 as stated in appnote.txt */
send_bits(s, dcodes - 1, 5);
send_bits(s, blcodes - 4, 4);
/* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
//Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]
/*.Len*/
, 3);
} //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_ltree, lcodes - 1);
/* literal tree */
//Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_dtree, dcodes - 1);
/* distance tree */
//Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
};
/* ===========================================================================
* Check if the data type is TEXT or BINARY, using the following algorithm:
* - TEXT if the two conditions below are satisfied:
* a) There are no non-portable control characters belonging to the
* "black list" (0..6, 14..25, 28..31).
* b) There is at least one printable character belonging to the
* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
* - BINARY otherwise.
* - The following partially-portable control characters form a
* "gray list" that is ignored in this detection algorithm:
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
* IN assertion: the fields Freq of dyn_ltree are set.
*/
var detect_data_type = function detect_data_type(s) {
/* black_mask is the bit mask of black-listed bytes
* set bits 0..6, 14..25, and 28..31
* 0xf3ffc07f = binary 11110011111111111100000001111111
*/
var black_mask = 0xf3ffc07f;
var n;
/* Check for non-textual ("black-listed") bytes. */
for (n = 0; n <= 31; n++, black_mask >>>= 1) {
if (black_mask & 1 && s.dyn_ltree[n * 2]
/*.Freq*/
!== 0) {
return Z_BINARY;
}
}
/* Check for textual ("white-listed") bytes. */
if (s.dyn_ltree[9 * 2]
/*.Freq*/
!== 0 || s.dyn_ltree[10 * 2]
/*.Freq*/
!== 0 || s.dyn_ltree[13 * 2]
/*.Freq*/
!== 0) {
return Z_TEXT;
}
for (n = 32; n < LITERALS; n++) {
if (s.dyn_ltree[n * 2]
/*.Freq*/
!== 0) {
return Z_TEXT;
}
}
/* There are no "black-listed" or "white-listed" bytes:
* this stream either is empty or has tolerated ("gray-listed") bytes only.
*/
return Z_BINARY;
};
var static_init_done = false;
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
var _tr_init = function _tr_init(s) {
if (!static_init_done) {
tr_static_init();
static_init_done = true;
}
s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
s.bi_buf = 0;
s.bi_valid = 0;
/* Initialize the first block of the first file: */
init_block(s);
};
/* ===========================================================================
* Send a stored block
*/
var _tr_stored_block = function _tr_stored_block(s, buf, stored_len, last) //DeflateState *s;
//charf *buf; /* input block */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3);
/* send block type */
copy_block(s, buf, stored_len, true);
/* with header */
};
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
*/
var _tr_align = function _tr_align(s) {
send_bits(s, STATIC_TREES << 1, 3);
send_code(s, END_BLOCK, static_ltree);
bi_flush(s);
};
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
var _tr_flush_block = function _tr_flush_block(s, buf, stored_len, last) //DeflateState *s;
//charf *buf; /* input block, or NULL if too old */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
var opt_lenb, static_lenb;
/* opt_len and static_len in bytes */
var max_blindex = 0;
/* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s.level > 0) {
/* Check if the file is binary or text */
if (s.strm.data_type === Z_UNKNOWN) {
s.strm.data_type = detect_data_type(s);
}
/* Construct the literal and distance trees */
build_tree(s, s.l_desc); // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
build_tree(s, s.d_desc); // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
opt_lenb = s.opt_len + 3 + 7 >>> 3;
static_lenb = s.static_len + 3 + 7 >>> 3; // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
// opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
// s->last_lit));
if (static_lenb <= opt_lenb) {
opt_lenb = static_lenb;
}
} else {
// Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5;
/* force a stored block */
}
if (stored_len + 4 <= opt_lenb && buf !== -1) {
/* 4: two words for the lengths */
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block(s, buf, stored_len, last);
} else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
compress_block(s, static_ltree, static_dtree);
} else {
send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
compress_block(s, s.dyn_ltree, s.dyn_dtree);
} // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (last) {
bi_windup(s);
} // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
// s->compressed_len-7*last));
};
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
var _tr_tally = function _tr_tally(s, dist, lc) // deflate_state *s;
// unsigned dist; /* distance of matched string */
// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
//let out_length, in_length, dcode;
s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 0xff;
s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
s.last_lit++;
if (dist === 0) {
/* lc is the unmatched char */
s.dyn_ltree[lc * 2] /*.Freq*/++;
} else {
s.matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--;
/* dist = match distance - 1 */
//Assert((ush)dist < (ush)MAX_DIST(s) &&
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
// (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2] /*.Freq*/++;
s.dyn_dtree[d_code(dist) * 2] /*.Freq*/++;
} // (!) This block is disabled in zlib defaults,
// don't enable it for binary compatibility
//#ifdef TRUNCATE_BLOCK
// /* Try to guess if it is profitable to stop the current block here */
// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
// /* Compute an upper bound for the compressed length */
// out_length = s.last_lit*8;
// in_length = s.strstart - s.block_start;
//
// for (dcode = 0; dcode < D_CODES; dcode++) {
// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
// }
// out_length >>>= 3;
// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
// // s->last_lit, in_length, out_length,
// // 100L - out_length*100L/in_length));
// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
// return true;
// }
// }
//#endif
return s.last_lit === s.lit_bufsize - 1;
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
};
var _tr_init_1 = _tr_init;
var _tr_stored_block_1 = _tr_stored_block;
var _tr_flush_block_1 = _tr_flush_block;
var _tr_tally_1 = _tr_tally;
var _tr_align_1 = _tr_align;
var trees = {
_tr_init: _tr_init_1,
_tr_stored_block: _tr_stored_block_1,
_tr_flush_block: _tr_flush_block_1,
_tr_tally: _tr_tally_1,
_tr_align: _tr_align_1
};
// It isn't worth it to make additional optimizations as in original.
// Small size is preferable.
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
var adler32 = function adler32(adler, buf, len, pos) {
var s1 = adler & 0xffff | 0,
s2 = adler >>> 16 & 0xffff | 0,
n = 0;
while (len !== 0) {
// Set limit ~ twice less than 5552, to keep
// s2 in 31-bits, because we force signed ints.
// in other case %= will fail.
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = s1 + buf[pos++] | 0;
s2 = s2 + s1 | 0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return s1 | s2 << 16 | 0;
};
var adler32_1 = adler32;
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
// Use ordinary array, since untyped makes no boost here
var makeTable = function makeTable() {
var c,
table = [];
for (var n = 0; n < 256; n++) {
c = n;
for (var k = 0; k < 8; k++) {
c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;
}
table[n] = c;
}
return table;
}; // Create table on load. Just 255 signed longs. Not a problem.
var crcTable = new Uint32Array(makeTable());
var crc32 = function crc32(crc, buf, len, pos) {
var t = crcTable;
var end = pos + len;
crc ^= -1;
for (var i = pos; i < end; i++) {
crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 0xFF];
}
return crc ^ -1; // >>> 0;
};
var crc32_1 = crc32;
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
var messages = {
2: 'need dictionary',
/* Z_NEED_DICT 2 */
1: 'stream end',
/* Z_STREAM_END 1 */
0: '',
/* Z_OK 0 */
'-1': 'file error',
/* Z_ERRNO (-1) */
'-2': 'stream error',
/* Z_STREAM_ERROR (-2) */
'-3': 'data error',
/* Z_DATA_ERROR (-3) */
'-4': 'insufficient memory',
/* Z_MEM_ERROR (-4) */
'-5': 'buffer error',
/* Z_BUF_ERROR (-5) */
'-6': 'incompatible version'
/* Z_VERSION_ERROR (-6) */
};
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
var constants = {
/* Allowed flush values; see deflate() and inflate() below for details */
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
//Z_VERSION_ERROR: -6,
/* compression levels */
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
/* Possible values of the data_type field (though see inflate()) */
Z_BINARY: 0,
Z_TEXT: 1,
//Z_ASCII: 1, // = Z_TEXT (deprecated)
Z_UNKNOWN: 2,
/* The deflate compression method */
Z_DEFLATED: 8 //Z_NULL: null // Use -1 or null inline, depending on var type
};
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
var _tr_init$1 = trees._tr_init,
_tr_stored_block$1 = trees._tr_stored_block,
_tr_flush_block$1 = trees._tr_flush_block,
_tr_tally$1 = trees._tr_tally,
_tr_align$1 = trees._tr_align;
/* Public constants ==========================================================*/
/* ===========================================================================*/
var Z_NO_FLUSH = constants.Z_NO_FLUSH,
Z_PARTIAL_FLUSH = constants.Z_PARTIAL_FLUSH,
Z_FULL_FLUSH = constants.Z_FULL_FLUSH,
Z_FINISH = constants.Z_FINISH,
Z_BLOCK = constants.Z_BLOCK,
Z_OK = constants.Z_OK,
Z_STREAM_END = constants.Z_STREAM_END,
Z_STREAM_ERROR = constants.Z_STREAM_ERROR,
Z_DATA_ERROR = constants.Z_DATA_ERROR,
Z_BUF_ERROR = constants.Z_BUF_ERROR,
Z_DEFAULT_COMPRESSION = constants.Z_DEFAULT_COMPRESSION,
Z_FILTERED = constants.Z_FILTERED,
Z_HUFFMAN_ONLY = constants.Z_HUFFMAN_ONLY,
Z_RLE = constants.Z_RLE,
Z_FIXED$1 = constants.Z_FIXED,
Z_DEFAULT_STRATEGY = constants.Z_DEFAULT_STRATEGY,
Z_UNKNOWN$1 = constants.Z_UNKNOWN,
Z_DEFLATED = constants.Z_DEFLATED;
/*============================================================================*/
var MAX_MEM_LEVEL = 9;
/* Maximum value for memLevel in deflateInit2 */
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_MEM_LEVEL = 8;
var LENGTH_CODES$1 = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS$1 = 256;
/* number of literal bytes 0..255 */
var L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES$1 = 30;
/* number of distance codes */
var BL_CODES$1 = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE$1 = 2 * L_CODES$1 + 1;
/* maximum heap size */
var MAX_BITS$1 = 15;
/* All codes must not exceed MAX_BITS bits */
var MIN_MATCH$1 = 3;
var MAX_MATCH$1 = 258;
var MIN_LOOKAHEAD = MAX_MATCH$1 + MIN_MATCH$1 + 1;
var PRESET_DICT = 0x20;
var INIT_STATE = 42;
var EXTRA_STATE = 69;
var NAME_STATE = 73;
var COMMENT_STATE = 91;
var HCRC_STATE = 103;
var BUSY_STATE = 113;
var FINISH_STATE = 666;
var BS_NEED_MORE = 1;
/* block not completed, need more input or more output */
var BS_BLOCK_DONE = 2;
/* block flush performed */
var BS_FINISH_STARTED = 3;
/* finish started, need only more output at next deflate */
var BS_FINISH_DONE = 4;
/* finish done, accept no more input or output */
var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
var err = function err(strm, errorCode) {
strm.msg = messages[errorCode];
return errorCode;
};
var rank = function rank(f) {
return (f << 1) - (f > 4 ? 9 : 0);
};
var zero$1 = function zero(buf) {
var len = buf.length;
while (--len >= 0) {
buf[len] = 0;
}
};
/* eslint-disable new-cap */
var HASH_ZLIB = function HASH_ZLIB(s, prev, data) {
return (prev << s.hash_shift ^ data) & s.hash_mask;
}; // This hash causes less collisions, https://github.com/nodeca/pako/issues/135
// But breaks binary compatibility
//let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask;
var HASH = HASH_ZLIB;
/* =========================================================================
* Flush as much pending output as possible. All deflate() output goes
* through this function so some applications may wish to modify it
* to avoid allocating a large strm->output buffer and copying into it.
* (See also read_buf()).
*/
var flush_pending = function flush_pending(strm) {
var s = strm.state; //_tr_flush_bits(s);
var len = s.pending;
if (len > strm.avail_out) {
len = strm.avail_out;
}
if (len === 0) {
return;
}
strm.output.set(s.pending_buf.subarray(s.pending_out, s.pending_out + len), strm.next_out);
strm.next_out += len;
s.pending_out += len;
strm.total_out += len;
strm.avail_out -= len;
s.pending -= len;
if (s.pending === 0) {
s.pending_out = 0;
}
};
var flush_block_only = function flush_block_only(s, last) {
_tr_flush_block$1(s, s.block_start >= 0 ? s.block_start : -1, s.strstart - s.block_start, last);
s.block_start = s.strstart;
flush_pending(s.strm);
};
var put_byte = function put_byte(s, b) {
s.pending_buf[s.pending++] = b;
};
/* =========================================================================
* Put a short in the pending buffer. The 16-bit value is put in MSB order.
* IN assertion: the stream state is correct and there is enough room in
* pending_buf.
*/
var putShortMSB = function putShortMSB(s, b) {
// put_byte(s, (Byte)(b >> 8));
// put_byte(s, (Byte)(b & 0xff));
s.pending_buf[s.pending++] = b >>> 8 & 0xff;
s.pending_buf[s.pending++] = b & 0xff;
};
/* ===========================================================================
* Read a new buffer from the current input stream, update the adler32
* and total number of bytes read. All deflate() input goes through
* this function so some applications may wish to modify it to avoid
* allocating a large strm->input buffer and copying from it.
* (See also flush_pending()).
*/
var read_buf = function read_buf(strm, buf, start, size) {
var len = strm.avail_in;
if (len > size) {
len = size;
}
if (len === 0) {
return 0;
}
strm.avail_in -= len; // zmemcpy(buf, strm->next_in, len);
buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start);
if (strm.state.wrap === 1) {
strm.adler = adler32_1(strm.adler, buf, len, start);
} else if (strm.state.wrap === 2) {
strm.adler = crc32_1(strm.adler, buf, len, start);
}
strm.next_in += len;
strm.total_in += len;
return len;
};
/* ===========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
* OUT assertion: the match length is not greater than s->lookahead.
*/
var longest_match = function longest_match(s, cur_match) {
var chain_length = s.max_chain_length;
/* max hash chain length */
var scan = s.strstart;
/* current string */
var match;
/* matched string */
var len;
/* length of current match */
var best_len = s.prev_length;
/* best match length so far */
var nice_match = s.nice_match;
/* stop if match long enough */
var limit = s.strstart > s.w_size - MIN_LOOKAHEAD ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0
/*NIL*/
;
var _win = s.window; // shortcut
var wmask = s.w_mask;
var prev = s.prev;
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0.
*/
var strend = s.strstart + MAX_MATCH$1;
var scan_end1 = _win[scan + best_len - 1];
var scan_end = _win[scan + best_len];
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
* It is easy to get rid of this optimization if necessary.
*/
// Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
/* Do not waste too much time if we already have a good match: */
if (s.prev_length >= s.good_match) {
chain_length >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if (nice_match > s.lookahead) {
nice_match = s.lookahead;
} // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
do {
// Assert(cur_match < s->strstart, "no future");
match = cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2. Note that the checks below
* for insufficient lookahead only occur occasionally for performance
* reasons. Therefore uninitialized memory will be accessed, and
* conditional jumps will be made that depend on those values.
* However the length of the match is limited to the lookahead, so
* the output of deflate is not affected by the uninitialized values.
*/
if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) {
continue;
}
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scan += 2;
match++; // Assert(*scan == *match, "match[2]?");
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
/*jshint noempty:false*/
} while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
len = MAX_MATCH$1 - (strend - scan);
scan = strend - MAX_MATCH$1;
if (len > best_len) {
s.match_start = cur_match;
best_len = len;
if (len >= nice_match) {
break;
}
scan_end1 = _win[scan + best_len - 1];
scan_end = _win[scan + best_len];
}
} while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
if (best_len <= s.lookahead) {
return best_len;
}
return s.lookahead;
};
/* ===========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead.
*
* IN assertion: lookahead < MIN_LOOKAHEAD
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
* At least one byte has been read, or avail_in == 0; reads are
* performed for at least two bytes (required for the zip translate_eol
* option -- not supported here).
*/
var fill_window = function fill_window(s) {
var _w_size = s.w_size;
var p, n, m, more, str; //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
do {
more = s.window_size - s.lookahead - s.strstart; // JS ints have 32 bit, block below not needed
/* Deal with !@#$% 64K limit: */
//if (sizeof(int) <= 2) {
// if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
// more = wsize;
//
// } else if (more == (unsigned)(-1)) {
// /* Very unlikely, but possible on 16 bit machine if
// * strstart == 0 && lookahead == 1 (input done a byte at time)
// */
// more--;
// }
//}
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
s.window.set(s.window.subarray(_w_size, _w_size + _w_size), 0);
s.match_start -= _w_size;
s.strstart -= _w_size;
/* we now have strstart >= MAX_DIST */
s.block_start -= _w_size;
/* Slide the hash table (could be avoided with 32 bit values
at the expense of memory usage). We slide even when level == 0
to keep the hash table consistent if we switch back to level > 0
later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.)
*/
n = s.hash_size;
p = n;
do {
m = s.head[--p];
s.head[p] = m >= _w_size ? m - _w_size : 0;
} while (--n);
n = _w_size;
p = n;
do {
m = s.prev[--p];
s.prev[p] = m >= _w_size ? m - _w_size : 0;
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
} while (--n);
more += _w_size;
}
if (s.strm.avail_in === 0) {
break;
}
/* If there was no sliding:
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
* more == window_size - lookahead - strstart
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
* => more >= window_size - 2*WSIZE + 2
* In the BIG_MEM or MMAP case (not yet supported),
* window_size == input_size + MIN_LOOKAHEAD &&
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
* Otherwise, window_size == 2*WSIZE so more >= 2.
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
*/
//Assert(more >= 2, "more < 2");
n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
s.lookahead += n;
/* Initialize the hash value now that we have some input: */
if (s.lookahead + s.insert >= MIN_MATCH$1) {
str = s.strstart - s.insert;
s.ins_h = s.window[str];
/* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
s.ins_h = HASH(s, s.ins_h, s.window[str + 1]); //#if MIN_MATCH != 3
// Call update_hash() MIN_MATCH-3 more times
//#endif
while (s.insert) {
/* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH$1 - 1]);
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
s.insert--;
if (s.lookahead + s.insert < MIN_MATCH$1) {
break;
}
}
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
} while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
/* If the WIN_INIT bytes after the end of the current data have never been
* written, then zero those bytes in order to avoid memory check reports of
* the use of uninitialized (or uninitialised as Julian writes) bytes by
* the longest match routines. Update the high water mark for the next
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/
// if (s.high_water < s.window_size) {
// const curr = s.strstart + s.lookahead;
// let init = 0;
//
// if (s.high_water < curr) {
// /* Previous high water mark below current data -- zero WIN_INIT
// * bytes or up to end of window, whichever is less.
// */
// init = s.window_size - curr;
// if (init > WIN_INIT)
// init = WIN_INIT;
// zmemzero(s->window + curr, (unsigned)init);
// s->high_water = curr + init;
// }
// else if (s->high_water < (ulg)curr + WIN_INIT) {
// /* High water mark at or above current data, but below current data
// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
// * to end of window, whichever is less.
// */
// init = (ulg)curr + WIN_INIT - s->high_water;
// if (init > s->window_size - s->high_water)
// init = s->window_size - s->high_water;
// zmemzero(s->window + s->high_water, (unsigned)init);
// s->high_water += init;
// }
// }
//
// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
// "not enough room for search");
};
/* ===========================================================================
* Copy without compression as much as possible from the input stream, return
* the current block state.
* This function does not insert new strings in the dictionary since
* uncompressible data is probably not useful. This function is used
* only for the level=0 compression option.
* NOTE: this function should be optimized to avoid extra copying from
* window to pending_buf.
*/
var deflate_stored = function deflate_stored(s, flush) {
/* Stored blocks are limited to 0xffff bytes, pending_buf is limited
* to pending_buf_size, and each stored block has a 5 byte header:
*/
var max_block_size = 0xffff;
if (max_block_size > s.pending_buf_size - 5) {
max_block_size = s.pending_buf_size - 5;
}
/* Copy as much as possible from input to output: */
for (;;) {
/* Fill the window as much as possible: */
if (s.lookahead <= 1) {
//Assert(s->strstart < s->w_size+MAX_DIST(s) ||
// s->block_start >= (long)s->w_size, "slide too late");
// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
// s.block_start >= s.w_size)) {
// throw new Error("slide too late");
// }
fill_window(s);
if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
/* flush the current block */
} //Assert(s->block_start >= 0L, "block gone");
// if (s.block_start < 0) throw new Error("block gone");
s.strstart += s.lookahead;
s.lookahead = 0;
/* Emit a stored block if pending_buf will be full: */
var max_start = s.block_start + max_block_size;
if (s.strstart === 0 || s.strstart >= max_start) {
/* strstart == 0 is possible when wraparound on 16-bit machine */
s.lookahead = s.strstart - max_start;
s.strstart = max_start;
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
/* Flush if we may have to slide, otherwise block_start may become
* negative and the data will be gone:
*/
if (s.strstart - s.block_start >= s.w_size - MIN_LOOKAHEAD) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.strstart > s.block_start) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_NEED_MORE;
};
/* ===========================================================================
* Compress as much as possible from the input stream, return the current
* block state.
* This function does not perform lazy evaluation of matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
var deflate_fast = function deflate_fast(s, flush) {
var hash_head;
/* head of the hash chain */
var bflush;
/* set if current block must be flushed */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
/* flush the current block */
}
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0
/*NIL*/
;
if (s.lookahead >= MIN_MATCH$1) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH$1 - 1]);
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if (hash_head !== 0
/*NIL*/
&& s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
}
if (s.match_length >= MIN_MATCH$1) {
// check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
/*** _tr_tally_dist(s, s.strstart - s.match_start,
s.match_length - MIN_MATCH, bflush); ***/
bflush = _tr_tally$1(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1);
s.lookahead -= s.match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
if (s.match_length <= s.max_lazy_match
/*max_insert_length*/
&& s.lookahead >= MIN_MATCH$1) {
s.match_length--;
/* string at strstart already in table */
do {
s.strstart++;
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH$1 - 1]);
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead.
*/
} while (--s.match_length !== 0);
s.strstart++;
} else {
s.strstart += s.match_length;
s.match_length = 0;
s.ins_h = s.window[s.strstart];
/* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + 1]); //#if MIN_MATCH != 3
// Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
* matter since it will be recomputed at next deflate call.
*/
}
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s.window[s.strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = _tr_tally$1(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
};
/* ===========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position.
*/
var deflate_slow = function deflate_slow(s, flush) {
var hash_head;
/* head of hash chain */
var bflush;
/* set if current block must be flushed */
var max_insert;
/* Process the input block. */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
/* flush the current block */
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0
/*NIL*/
;
if (s.lookahead >= MIN_MATCH$1) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH$1 - 1]);
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
*/
s.prev_length = s.match_length;
s.prev_match = s.match_start;
s.match_length = MIN_MATCH$1 - 1;
if (hash_head !== 0
/*NIL*/
&& s.prev_length < s.max_lazy_match && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD
/*MAX_DIST(s)*/
) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
if (s.match_length <= 5 && (s.strategy === Z_FILTERED || s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096
/*TOO_FAR*/
)) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
s.match_length = MIN_MATCH$1 - 1;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) {
max_insert = s.strstart + s.lookahead - MIN_MATCH$1;
/* Do not insert strings in hash table beyond this. */
//check_match(s, s.strstart-1, s.prev_match, s.prev_length);
/***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
s.prev_length - MIN_MATCH, bflush);***/
bflush = _tr_tally$1(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted. If there is not
* enough lookahead, the last two strings are not inserted in
* the hash table.
*/
s.lookahead -= s.prev_length - 1;
s.prev_length -= 2;
do {
if (++s.strstart <= max_insert) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH$1 - 1]);
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
} while (--s.prev_length !== 0);
s.match_available = 0;
s.match_length = MIN_MATCH$1 - 1;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
} else if (s.match_available) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = _tr_tally$1(s, 0, s.window[s.strstart - 1]);
if (bflush) {
/*** FLUSH_BLOCK_ONLY(s, 0) ***/
flush_block_only(s, false);
/***/
}
s.strstart++;
s.lookahead--;
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
s.match_available = 1;
s.strstart++;
s.lookahead--;
}
} //Assert (flush != Z_NO_FLUSH, "no flush?");
if (s.match_available) {
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = _tr_tally$1(s, 0, s.window[s.strstart - 1]);
s.match_available = 0;
}
s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
};
/* ===========================================================================
* For Z_RLE, simply look for runs of bytes, generate matches only of distance
* one. Do not maintain a hash table. (It will be regenerated if this run of
* deflate switches away from Z_RLE.)
*/
var deflate_rle = function deflate_rle(s, flush) {
var bflush;
/* set if current block must be flushed */
var prev;
/* byte at distance one to match */
var scan, strend;
/* scan goes up to strend for length of run */
var _win = s.window;
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the longest run, plus one for the unrolled loop.
*/
if (s.lookahead <= MAX_MATCH$1) {
fill_window(s);
if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
/* flush the current block */
}
/* See how many times the previous byte repeats */
s.match_length = 0;
if (s.lookahead >= MIN_MATCH$1 && s.strstart > 0) {
scan = s.strstart - 1;
prev = _win[scan];
if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
strend = s.strstart + MAX_MATCH$1;
do {
/*jshint noempty:false*/
} while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend);
s.match_length = MAX_MATCH$1 - (strend - scan);
if (s.match_length > s.lookahead) {
s.match_length = s.lookahead;
}
} //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
}
/* Emit match if have run of MIN_MATCH or longer, else emit literal */
if (s.match_length >= MIN_MATCH$1) {
//check_match(s, s.strstart, s.strstart - 1, s.match_length);
/*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
bflush = _tr_tally$1(s, 1, s.match_length - MIN_MATCH$1);
s.lookahead -= s.match_length;
s.strstart += s.match_length;
s.match_length = 0;
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = _tr_tally$1(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
};
/* ===========================================================================
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
* (It will be regenerated if this run of deflate switches away from Huffman.)
*/
var deflate_huff = function deflate_huff(s, flush) {
var bflush;
/* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s.lookahead === 0) {
fill_window(s);
if (s.lookahead === 0) {
if (flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
break;
/* flush the current block */
}
}
/* Output a literal byte */
s.match_length = 0; //Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = _tr_tally$1(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
};
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
function Config(good_length, max_lazy, nice_length, max_chain, func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
}
var configuration_table = [
/* good lazy nice chain */
new Config(0, 0, 0, 0, deflate_stored),
/* 0 store only */
new Config(4, 4, 8, 4, deflate_fast),
/* 1 max speed, no lazy matches */
new Config(4, 5, 16, 8, deflate_fast),
/* 2 */
new Config(4, 6, 32, 32, deflate_fast),
/* 3 */
new Config(4, 4, 16, 16, deflate_slow),
/* 4 lazy matches */
new Config(8, 16, 32, 32, deflate_slow),
/* 5 */
new Config(8, 16, 128, 128, deflate_slow),
/* 6 */
new Config(8, 32, 128, 256, deflate_slow),
/* 7 */
new Config(32, 128, 258, 1024, deflate_slow),
/* 8 */
new Config(32, 258, 258, 4096, deflate_slow)
/* 9 max compression */
];
/* ===========================================================================
* Initialize the "longest match" routines for a new zlib stream
*/
var lm_init = function lm_init(s) {
s.window_size = 2 * s.w_size;
/*** CLEAR_HASH(s); ***/
zero$1(s.head); // Fill with NIL (= 0);
/* Set the default configuration parameters:
*/
s.max_lazy_match = configuration_table[s.level].max_lazy;
s.good_match = configuration_table[s.level].good_length;
s.nice_match = configuration_table[s.level].nice_length;
s.max_chain_length = configuration_table[s.level].max_chain;
s.strstart = 0;
s.block_start = 0;
s.lookahead = 0;
s.insert = 0;
s.match_length = s.prev_length = MIN_MATCH$1 - 1;
s.match_available = 0;
s.ins_h = 0;
};
function DeflateState() {
this.strm = null;
/* pointer back to this zlib stream */
this.status = 0;
/* as the name implies */
this.pending_buf = null;
/* output still pending */
this.pending_buf_size = 0;
/* size of pending_buf */
this.pending_out = 0;
/* next pending byte to output to the stream */
this.pending = 0;
/* nb of bytes in the pending buffer */
this.wrap = 0;
/* bit 0 true for zlib, bit 1 true for gzip */
this.gzhead = null;
/* gzip header information to write */
this.gzindex = 0;
/* where in extra, name, or comment */
this.method = Z_DEFLATED;
/* can only be DEFLATED */
this.last_flush = -1;
/* value of flush param for previous deflate call */
this.w_size = 0;
/* LZ77 window size (32K by default) */
this.w_bits = 0;
/* log2(w_size) (8..16) */
this.w_mask = 0;
/* w_size - 1 */
this.window = null;
/* Sliding window. Input bytes are read into the second half of the window,
* and move to the first half later to keep a dictionary of at least wSize
* bytes. With this organization, matches are limited to a distance of
* wSize-MAX_MATCH bytes, but this ensures that IO is always
* performed with a length multiple of the block size.
*/
this.window_size = 0;
/* Actual size of window: 2*wSize, except when the user input buffer
* is directly used as sliding window.
*/
this.prev = null;
/* Link to older string with same hash index. To limit the size of this
* array to 64K, this link is maintained only for the last 32K strings.
* An index in this array is thus a window index modulo 32K.
*/
this.head = null;
/* Heads of the hash chains or NIL. */
this.ins_h = 0;
/* hash index of string to be inserted */
this.hash_size = 0;
/* number of elements in hash table */
this.hash_bits = 0;
/* log2(hash_size) */
this.hash_mask = 0;
/* hash_size-1 */
this.hash_shift = 0;
/* Number of bits by which ins_h must be shifted at each input
* step. It must be such that after MIN_MATCH steps, the oldest
* byte no longer takes part in the hash key, that is:
* hash_shift * MIN_MATCH >= hash_bits
*/
this.block_start = 0;
/* Window position at the beginning of the current output block. Gets
* negative when the window is moved backwards.
*/
this.match_length = 0;
/* length of best match */
this.prev_match = 0;
/* previous match */
this.match_available = 0;
/* set if previous match exists */
this.strstart = 0;
/* start of string to insert */
this.match_start = 0;
/* start of matching string */
this.lookahead = 0;
/* number of valid bytes ahead in window */
this.prev_length = 0;
/* Length of the best match at previous step. Matches not greater than this
* are discarded. This is used in the lazy match evaluation.
*/
this.max_chain_length = 0;
/* To speed up deflation, hash chains are never searched beyond this
* length. A higher limit improves compression ratio but degrades the
* speed.
*/
this.max_lazy_match = 0;
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
*/
// That's alias to max_lazy_match, don't use directly
//this.max_insert_length = 0;
/* Insert new strings in the hash table only if the match length is not
* greater than this length. This saves time but degrades compression.
* max_insert_length is used only for compression levels <= 3.
*/
this.level = 0;
/* compression level (1..9) */
this.strategy = 0;
/* favor or force Huffman coding*/
this.good_match = 0;
/* Use a faster search when the previous match is longer than this */
this.nice_match = 0;
/* Stop searching when current match exceeds this */
/* used by trees.c: */
/* Didn't use ct_data typedef below to suppress compiler warning */
// struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
// struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
// struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
// Use flat array of DOUBLE size, with interleaved fata,
// because JS does not support effective
this.dyn_ltree = new Uint16Array(HEAP_SIZE$1 * 2);
this.dyn_dtree = new Uint16Array((2 * D_CODES$1 + 1) * 2);
this.bl_tree = new Uint16Array((2 * BL_CODES$1 + 1) * 2);
zero$1(this.dyn_ltree);
zero$1(this.dyn_dtree);
zero$1(this.bl_tree);
this.l_desc = null;
/* desc. for literal tree */
this.d_desc = null;
/* desc. for distance tree */
this.bl_desc = null;
/* desc. for bit length tree */
//ush bl_count[MAX_BITS+1];
this.bl_count = new Uint16Array(MAX_BITS$1 + 1);
/* number of codes at each bit length for an optimal tree */
//int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
this.heap = new Uint16Array(2 * L_CODES$1 + 1);
/* heap used to build the Huffman trees */
zero$1(this.heap);
this.heap_len = 0;
/* number of elements in the heap */
this.heap_max = 0;
/* element of largest frequency */
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
* The same heap array is used to build all trees.
*/
this.depth = new Uint16Array(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1];
zero$1(this.depth);
/* Depth of each subtree used as tie breaker for trees of equal frequency
*/
this.l_buf = 0;
/* buffer index for literals or lengths */
this.lit_bufsize = 0;
/* Size of match buffer for literals/lengths. There are 4 reasons for
* limiting lit_bufsize to 64K:
* - frequencies can be kept in 16 bit counters
* - if compression is not successful for the first block, all input
* data is still in the window so we can still emit a stored block even
* when input comes from standard input. (This can also be done for
* all blocks if lit_bufsize is not greater than 32K.)
* - if compression is not successful for a file smaller than 64K, we can
* even emit a stored file instead of a stored block (saving 5 bytes).
* This is applicable only for zip (not gzip or zlib).
* - creating new Huffman trees less frequently may not provide fast
* adaptation to changes in the input data statistics. (Take for
* example a binary file with poorly compressible code followed by
* a highly compressible string table.) Smaller buffer sizes give
* fast adaptation but have of course the overhead of transmitting
* trees more frequently.
* - I can't count above 4
*/
this.last_lit = 0;
/* running index in l_buf */
this.d_buf = 0;
/* Buffer index for distances. To simplify the code, d_buf and l_buf have
* the same number of elements. To use different lengths, an extra flag
* array would be necessary.
*/
this.opt_len = 0;
/* bit length of current block with optimal trees */
this.static_len = 0;
/* bit length of current block with static trees */
this.matches = 0;
/* number of string matches in current block */
this.insert = 0;
/* bytes at end of window left to insert */
this.bi_buf = 0;
/* Output buffer. bits are inserted starting at the bottom (least
* significant bits).
*/
this.bi_valid = 0;
/* Number of valid bits in bi_buf. All bits above the last valid bit
* are always zero.
*/
// Used for window memory init. We safely ignore it for JS. That makes
// sense only for pointers and memory check tools.
//this.high_water = 0;
/* High water mark offset in window for initialized bytes -- bytes above
* this are set to zero in order to avoid memory check warnings when
* longest match routines access bytes past the input. This is then
* updated to the new high water mark.
*/
}
var deflateResetKeep = function deflateResetKeep(strm) {
if (!strm || !strm.state) {
return err(strm, Z_STREAM_ERROR);
}
strm.total_in = strm.total_out = 0;
strm.data_type = Z_UNKNOWN$1;
var s = strm.state;
s.pending = 0;
s.pending_out = 0;
if (s.wrap < 0) {
s.wrap = -s.wrap;
/* was made negative by deflate(..., Z_FINISH); */
}
s.status = s.wrap ? INIT_STATE : BUSY_STATE;
strm.adler = s.wrap === 2 ? 0 // crc32(0, Z_NULL, 0)
: 1; // adler32(0, Z_NULL, 0)
s.last_flush = Z_NO_FLUSH;
_tr_init$1(s);
return Z_OK;
};
var deflateReset = function deflateReset(strm) {
var ret = deflateResetKeep(strm);
if (ret === Z_OK) {
lm_init(strm.state);
}
return ret;
};
var deflateSetHeader = function deflateSetHeader(strm, head) {
if (!strm || !strm.state) {
return Z_STREAM_ERROR;
}
if (strm.state.wrap !== 2) {
return Z_STREAM_ERROR;
}
strm.state.gzhead = head;
return Z_OK;
};
var deflateInit2 = function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
if (!strm) {
// === Z_NULL
return Z_STREAM_ERROR;
}
var wrap = 1;
if (level === Z_DEFAULT_COMPRESSION) {
level = 6;
}
if (windowBits < 0) {
/* suppress zlib wrapper */
wrap = 0;
windowBits = -windowBits;
} else if (windowBits > 15) {
wrap = 2;
/* write gzip wrapper instead */
windowBits -= 16;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED$1) {
return err(strm, Z_STREAM_ERROR);
}
if (windowBits === 8) {
windowBits = 9;
}
/* until 256-byte window bug fixed */
var s = new DeflateState();
strm.state = s;
s.strm = strm;
s.wrap = wrap;
s.gzhead = null;
s.w_bits = windowBits;
s.w_size = 1 << s.w_bits;
s.w_mask = s.w_size - 1;
s.hash_bits = memLevel + 7;
s.hash_size = 1 << s.hash_bits;
s.hash_mask = s.hash_size - 1;
s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1);
s.window = new Uint8Array(s.w_size * 2);
s.head = new Uint16Array(s.hash_size);
s.prev = new Uint16Array(s.w_size); // Don't need mem init magic for JS.
//s.high_water = 0; /* nothing written to s->window yet */
s.lit_bufsize = 1 << memLevel + 6;
/* 16K elements by default */
s.pending_buf_size = s.lit_bufsize * 4; //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
//s->pending_buf = (uchf *) overlay;
s.pending_buf = new Uint8Array(s.pending_buf_size); // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
//s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
s.d_buf = 1 * s.lit_bufsize; //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
s.l_buf = (1 + 2) * s.lit_bufsize;
s.level = level;
s.strategy = strategy;
s.method = method;
return deflateReset(strm);
};
var deflateInit = function deflateInit(strm, level) {
return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
};
var deflate = function deflate(strm, flush) {
var beg, val; // for gzip header write only
if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) {
return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
}
var s = strm.state;
if (!strm.output || !strm.input && strm.avail_in !== 0 || s.status === FINISH_STATE && flush !== Z_FINISH) {
return err(strm, strm.avail_out === 0 ? Z_BUF_ERROR : Z_STREAM_ERROR);
}
s.strm = strm;
/* just in case */
var old_flush = s.last_flush;
s.last_flush = flush;
/* Write the header */
if (s.status === INIT_STATE) {
if (s.wrap === 2) {
// GZIP header
strm.adler = 0; //crc32(0L, Z_NULL, 0);
put_byte(s, 31);
put_byte(s, 139);
put_byte(s, 8);
if (!s.gzhead) {
// s->gzhead == Z_NULL
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0);
put_byte(s, OS_CODE);
s.status = BUSY_STATE;
} else {
put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16));
put_byte(s, s.gzhead.time & 0xff);
put_byte(s, s.gzhead.time >> 8 & 0xff);
put_byte(s, s.gzhead.time >> 16 & 0xff);
put_byte(s, s.gzhead.time >> 24 & 0xff);
put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0);
put_byte(s, s.gzhead.os & 0xff);
if (s.gzhead.extra && s.gzhead.extra.length) {
put_byte(s, s.gzhead.extra.length & 0xff);
put_byte(s, s.gzhead.extra.length >> 8 & 0xff);
}
if (s.gzhead.hcrc) {
strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0);
}
s.gzindex = 0;
s.status = EXTRA_STATE;
}
} else // DEFLATE header
{
var header = Z_DEFLATED + (s.w_bits - 8 << 4) << 8;
var level_flags = -1;
if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
level_flags = 0;
} else if (s.level < 6) {
level_flags = 1;
} else if (s.level === 6) {
level_flags = 2;
} else {
level_flags = 3;
}
header |= level_flags << 6;
if (s.strstart !== 0) {
header |= PRESET_DICT;
}
header += 31 - header % 31;
s.status = BUSY_STATE;
putShortMSB(s, header);
/* Save the adler32 of the preset dictionary: */
if (s.strstart !== 0) {
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
strm.adler = 1; // adler32(0L, Z_NULL, 0);
}
} //#ifdef GZIP
if (s.status === EXTRA_STATE) {
if (s.gzhead.extra
/* != Z_NULL*/
) {
beg = s.pending;
/* start of bytes to update crc */
while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
break;
}
}
put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
s.gzindex++;
}
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (s.gzindex === s.gzhead.extra.length) {
s.gzindex = 0;
s.status = NAME_STATE;
}
} else {
s.status = NAME_STATE;
}
}
if (s.status === NAME_STATE) {
if (s.gzhead.name
/* != Z_NULL*/
) {
beg = s.pending;
/* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
} // JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.name.length) {
val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.gzindex = 0;
s.status = COMMENT_STATE;
}
} else {
s.status = COMMENT_STATE;
}
}
if (s.status === COMMENT_STATE) {
if (s.gzhead.comment
/* != Z_NULL*/
) {
beg = s.pending;
/* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
} // JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.comment.length) {
val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.status = HCRC_STATE;
}
} else {
s.status = HCRC_STATE;
}
}
if (s.status === HCRC_STATE) {
if (s.gzhead.hcrc) {
if (s.pending + 2 > s.pending_buf_size) {
flush_pending(strm);
}
if (s.pending + 2 <= s.pending_buf_size) {
put_byte(s, strm.adler & 0xff);
put_byte(s, strm.adler >> 8 & 0xff);
strm.adler = 0; //crc32(0L, Z_NULL, 0);
s.status = BUSY_STATE;
}
} else {
s.status = BUSY_STATE;
}
} //#endif
/* Flush as much pending output as possible */
if (s.pending !== 0) {
flush_pending(strm);
if (strm.avail_out === 0) {
/* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate:
*/
s.last_flush = -1;
return Z_OK;
}
/* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with Z_FINISH, we keep
* returning Z_STREAM_END instead of Z_BUF_ERROR.
*/
} else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) {
return err(strm, Z_BUF_ERROR);
}
/* User must not provide more input after the first FINISH: */
if (s.status === FINISH_STATE && strm.avail_in !== 0) {
return err(strm, Z_BUF_ERROR);
}
/* Start a new block or continue the current one.
*/
if (strm.avail_in !== 0 || s.lookahead !== 0 || flush !== Z_NO_FLUSH && s.status !== FINISH_STATE) {
var bstate = s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush);
if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
s.status = FINISH_STATE;
}
if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
if (strm.avail_out === 0) {
s.last_flush = -1;
/* avoid BUF_ERROR next call, see above */
}
return Z_OK;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most
* one empty block.
*/
}
if (bstate === BS_BLOCK_DONE) {
if (flush === Z_PARTIAL_FLUSH) {
_tr_align$1(s);
} else if (flush !== Z_BLOCK) {
/* FULL_FLUSH or SYNC_FLUSH */
_tr_stored_block$1(s, 0, 0, false);
/* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync().
*/
if (flush === Z_FULL_FLUSH) {
/*** CLEAR_HASH(s); ***/
/* forget history */
zero$1(s.head); // Fill with NIL (= 0);
if (s.lookahead === 0) {
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
}
}
flush_pending(strm);
if (strm.avail_out === 0) {
s.last_flush = -1;
/* avoid BUF_ERROR at next call, see above */
return Z_OK;
}
}
} //Assert(strm->avail_out > 0, "bug2");
//if (strm.avail_out <= 0) { throw new Error("bug2");}
if (flush !== Z_FINISH) {
return Z_OK;
}
if (s.wrap <= 0) {
return Z_STREAM_END;
}
/* Write the trailer */
if (s.wrap === 2) {
put_byte(s, strm.adler & 0xff);
put_byte(s, strm.adler >> 8 & 0xff);
put_byte(s, strm.adler >> 16 & 0xff);
put_byte(s, strm.adler >> 24 & 0xff);
put_byte(s, strm.total_in & 0xff);
put_byte(s, strm.total_in >> 8 & 0xff);
put_byte(s, strm.total_in >> 16 & 0xff);
put_byte(s, strm.total_in >> 24 & 0xff);
} else {
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
flush_pending(strm);
/* If avail_out is zero, the application will call deflate again
* to flush the rest.
*/
if (s.wrap > 0) {
s.wrap = -s.wrap;
}
/* write the trailer only once! */
return s.pending !== 0 ? Z_OK : Z_STREAM_END;
};
var deflateEnd = function deflateEnd(strm) {
if (!strm
/*== Z_NULL*/
|| !strm.state
/*== Z_NULL*/
) {
return Z_STREAM_ERROR;
}
var status = strm.state.status;
if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE) {
return err(strm, Z_STREAM_ERROR);
}
strm.state = null;
return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
};
/* =========================================================================
* Initializes the compression dictionary from the given byte
* sequence without producing any compressed output.
*/
var deflateSetDictionary = function deflateSetDictionary(strm, dictionary) {
var dictLength = dictionary.length;
if (!strm
/*== Z_NULL*/
|| !strm.state
/*== Z_NULL*/
) {
return Z_STREAM_ERROR;
}
var s = strm.state;
var wrap = s.wrap;
if (wrap === 2 || wrap === 1 && s.status !== INIT_STATE || s.lookahead) {
return Z_STREAM_ERROR;
}
/* when using zlib wrappers, compute Adler-32 for provided dictionary */
if (wrap === 1) {
/* adler32(strm->adler, dictionary, dictLength); */
strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0);
}
s.wrap = 0;
/* avoid computing Adler-32 in read_buf */
/* if dictionary would fill window, just replace the history */
if (dictLength >= s.w_size) {
if (wrap === 0) {
/* already empty otherwise */
/*** CLEAR_HASH(s); ***/
zero$1(s.head); // Fill with NIL (= 0);
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
/* use the tail */
// dictionary = dictionary.slice(dictLength - s.w_size);
var tmpDict = new Uint8Array(s.w_size);
tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0);
dictionary = tmpDict;
dictLength = s.w_size;
}
/* insert dictionary into window and hash */
var avail = strm.avail_in;
var next = strm.next_in;
var input = strm.input;
strm.avail_in = dictLength;
strm.next_in = 0;
strm.input = dictionary;
fill_window(s);
while (s.lookahead >= MIN_MATCH$1) {
var str = s.strstart;
var n = s.lookahead - (MIN_MATCH$1 - 1);
do {
/* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH$1 - 1]);
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
} while (--n);
s.strstart = str;
s.lookahead = MIN_MATCH$1 - 1;
fill_window(s);
}
s.strstart += s.lookahead;
s.block_start = s.strstart;
s.insert = s.lookahead;
s.lookahead = 0;
s.match_length = s.prev_length = MIN_MATCH$1 - 1;
s.match_available = 0;
strm.next_in = next;
strm.input = input;
strm.avail_in = avail;
s.wrap = wrap;
return Z_OK;
};
var deflateInit_1 = deflateInit;
var deflateInit2_1 = deflateInit2;
var deflateReset_1 = deflateReset;
var deflateResetKeep_1 = deflateResetKeep;
var deflateSetHeader_1 = deflateSetHeader;
var deflate_2 = deflate;
var deflateEnd_1 = deflateEnd;
var deflateSetDictionary_1 = deflateSetDictionary;
var deflateInfo = 'pako deflate (from Nodeca project)';
/* Not implemented
module.exports.deflateBound = deflateBound;
module.exports.deflateCopy = deflateCopy;
module.exports.deflateParams = deflateParams;
module.exports.deflatePending = deflatePending;
module.exports.deflatePrime = deflatePrime;
module.exports.deflateTune = deflateTune;
*/
var deflate_1 = {
deflateInit: deflateInit_1,
deflateInit2: deflateInit2_1,
deflateReset: deflateReset_1,
deflateResetKeep: deflateResetKeep_1,
deflateSetHeader: deflateSetHeader_1,
deflate: deflate_2,
deflateEnd: deflateEnd_1,
deflateSetDictionary: deflateSetDictionary_1,
deflateInfo: deflateInfo
};
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
var _has = function _has(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
};
var assign = function assign(obj
/*from1, from2, from3, ...*/
) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
if (!source) {
continue;
}
if (_typeof(source) !== 'object') {
throw new TypeError(source + 'must be non-object');
}
for (var p in source) {
if (_has(source, p)) {
obj[p] = source[p];
}
}
}
return obj;
}; // Join array of chunks to single array.
var flattenChunks = function flattenChunks(chunks) {
// calculate data length
var len = 0;
for (var i = 0, l = chunks.length; i < l; i++) {
len += chunks[i].length;
} // join chunks
var result = new Uint8Array(len);
for (var _i = 0, pos = 0, _l = chunks.length; _i < _l; _i++) {
var chunk = chunks[_i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
};
var common = {
assign: assign,
flattenChunks: flattenChunks
};
// String encode/decode helpers
//
// - apply(Array) can fail on Android 2.2
// - apply(Uint8Array) can fail on iOS 5.1 Safari
//
var STR_APPLY_UIA_OK = true;
try {
String.fromCharCode.apply(null, new Uint8Array(1));
} catch (__) {
STR_APPLY_UIA_OK = false;
} // Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new Uint8Array(256);
for (var q = 0; q < 256; q++) {
_utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1;
}
_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
// convert string to array (typed, when possible)
var string2buf = function string2buf(str) {
var buf,
c,
c2,
m_pos,
i,
str_len = str.length,
buf_len = 0; // count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {
c2 = str.charCodeAt(m_pos + 1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
m_pos++;
}
}
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
} // allocate buffer
buf = new Uint8Array(buf_len); // convert
for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {
c2 = str.charCodeAt(m_pos + 1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
m_pos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xC0 | c >>> 6;
buf[i++] = 0x80 | c & 0x3f;
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xE0 | c >>> 12;
buf[i++] = 0x80 | c >>> 6 & 0x3f;
buf[i++] = 0x80 | c & 0x3f;
} else {
/* four bytes */
buf[i++] = 0xf0 | c >>> 18;
buf[i++] = 0x80 | c >>> 12 & 0x3f;
buf[i++] = 0x80 | c >>> 6 & 0x3f;
buf[i++] = 0x80 | c & 0x3f;
}
}
return buf;
}; // Helper
var buf2binstring = function buf2binstring(buf, len) {
// On Chrome, the arguments in a function call that are allowed is `65534`.
// If the length of the buffer is smaller than that, we can use this optimization,
// otherwise we will take a slower path.
if (len < 65534) {
if (buf.subarray && STR_APPLY_UIA_OK) {
return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len));
}
}
var result = '';
for (var i = 0; i < len; i++) {
result += String.fromCharCode(buf[i]);
}
return result;
}; // convert array to string
var buf2string = function buf2string(buf, max) {
var i, out;
var len = max || buf.length; // Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array.
var utf16buf = new Array(len * 2);
for (out = 0, i = 0; i < len;) {
var c = buf[i++]; // quick process ascii
if (c < 0x80) {
utf16buf[out++] = c;
continue;
}
var c_len = _utf8len[c]; // skip 5 & 6 byte codes
if (c_len > 4) {
utf16buf[out++] = 0xfffd;
i += c_len - 1;
continue;
} // apply mask on first byte
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; // join the rest
while (c_len > 1 && i < len) {
c = c << 6 | buf[i++] & 0x3f;
c_len--;
} // terminated by end of string?
if (c_len > 1) {
utf16buf[out++] = 0xfffd;
continue;
}
if (c < 0x10000) {
utf16buf[out++] = c;
} else {
c -= 0x10000;
utf16buf[out++] = 0xd800 | c >> 10 & 0x3ff;
utf16buf[out++] = 0xdc00 | c & 0x3ff;
}
}
return buf2binstring(utf16buf, out);
}; // Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max - length limit (mandatory);
var utf8border = function utf8border(buf, max) {
max = max || buf.length;
if (max > buf.length) {
max = buf.length;
} // go back from last position, until start of sequence found
var pos = max - 1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) {
pos--;
} // Very small and broken sequence,
// return max, because we should return something anyway.
if (pos < 0) {
return max;
} // If we came to start of buffer - that means buffer is too small,
// return max too.
if (pos === 0) {
return max;
}
return pos + _utf8len[buf[pos]] > max ? pos : max;
};
var strings = {
string2buf: string2buf,
buf2string: buf2string,
utf8border: utf8border
};
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''
/*Z_NULL*/
;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2
/*Z_UNKNOWN*/
;
/* adler32 value of the uncompressed data */
this.adler = 0;
}
var zstream = ZStream;
var toString = Object.prototype.toString;
/* Public constants ==========================================================*/
/* ===========================================================================*/
var Z_NO_FLUSH$1 = constants.Z_NO_FLUSH,
Z_SYNC_FLUSH = constants.Z_SYNC_FLUSH,
Z_FULL_FLUSH$1 = constants.Z_FULL_FLUSH,
Z_FINISH$1 = constants.Z_FINISH,
Z_OK$1 = constants.Z_OK,
Z_STREAM_END$1 = constants.Z_STREAM_END,
Z_DEFAULT_COMPRESSION$1 = constants.Z_DEFAULT_COMPRESSION,
Z_DEFAULT_STRATEGY$1 = constants.Z_DEFAULT_STRATEGY,
Z_DEFLATED$1 = constants.Z_DEFLATED;
/* ===========================================================================*/
/**
* class Deflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[deflate]],
* [[deflateRaw]] and [[gzip]].
**/
/* internal
* Deflate.chunks -> Array
*
* Chunks of output data, if [[Deflate#onData]] not overridden.
**/
/**
* Deflate.result -> Uint8Array
*
* Compressed result, generated by default [[Deflate#onData]]
* and [[Deflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Deflate#push]] with `Z_FINISH` / `true` param).
**/
/**
* Deflate.err -> Number
*
* Error code after deflate finished. 0 (Z_OK) on success.
* You will not need it in real life, because deflate errors
* are possible only on wrong options or bad `onData` / `onEnd`
* custom handlers.
**/
/**
* Deflate.msg -> String
*
* Error message, if [[Deflate.err]] != 0
**/
/**
* new Deflate(options)
* - options (Object): zlib deflate options.
*
* Creates new deflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `level`
* - `windowBits`
* - `memLevel`
* - `strategy`
* - `dictionary`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw deflate
* - `gzip` (Boolean) - create gzip wrapper
* - `header` (Object) - custom header for gzip
* - `text` (Boolean) - true if compressed data believed to be text
* - `time` (Number) - modification time, unix timestamp
* - `os` (Number) - operation system code
* - `extra` (Array) - array of bytes with extra data (max 65536)
* - `name` (String) - file name (binary string)
* - `comment` (String) - comment (binary string)
* - `hcrc` (Boolean) - true if header crc should be added
*
* ##### Example:
*
* ```javascript
* const pako = require('pako')
* , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* const deflate = new pako.Deflate({ level: 3});
*
* deflate.push(chunk1, false);
* deflate.push(chunk2, true); // true -> last chunk
*
* if (deflate.err) { throw new Error(deflate.err); }
*
* console.log(deflate.result);
* ```
**/
function Deflate(options) {
this.options = common.assign({
level: Z_DEFAULT_COMPRESSION$1,
method: Z_DEFLATED$1,
chunkSize: 16384,
windowBits: 15,
memLevel: 8,
strategy: Z_DEFAULT_STRATEGY$1
}, options || {});
var opt = this.options;
if (opt.raw && opt.windowBits > 0) {
opt.windowBits = -opt.windowBits;
} else if (opt.gzip && opt.windowBits > 0 && opt.windowBits < 16) {
opt.windowBits += 16;
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = deflate_1.deflateInit2(this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy);
if (status !== Z_OK$1) {
throw new Error(messages[status]);
}
if (opt.header) {
deflate_1.deflateSetHeader(this.strm, opt.header);
}
if (opt.dictionary) {
var dict; // Convert data if needed
if (typeof opt.dictionary === 'string') {
// If we need to compress text, change encoding to utf8.
dict = strings.string2buf(opt.dictionary);
} else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
dict = new Uint8Array(opt.dictionary);
} else {
dict = opt.dictionary;
}
status = deflate_1.deflateSetDictionary(this.strm, dict);
if (status !== Z_OK$1) {
throw new Error(messages[status]);
}
this._dict_set = true;
}
}
/**
* Deflate#push(data[, flush_mode]) -> Boolean
* - data (Uint8Array|ArrayBuffer|String): input data. Strings will be
* converted to utf8 byte sequence.
* - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
*
* Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
* new compressed chunks. Returns `true` on success. The last data block must
* have `flush_mode` Z_FINISH (or `true`). That will flush internal pending
* buffers and call [[Deflate#onEnd]].
*
* On fail call [[Deflate#onEnd]] with error code and return false.
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Deflate.prototype.push = function (data, flush_mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _flush_mode;
if (this.ended) {
return false;
}
if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;else _flush_mode = flush_mode === true ? Z_FINISH$1 : Z_NO_FLUSH$1; // Convert data if needed
if (typeof data === 'string') {
// If we need to compress text, change encoding to utf8.
strm.input = strings.string2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
for (;;) {
if (strm.avail_out === 0) {
strm.output = new Uint8Array(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
} // Make sure avail_out > 6 to avoid repeating markers
if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH$1) && strm.avail_out <= 6) {
this.onData(strm.output.subarray(0, strm.next_out));
strm.avail_out = 0;
continue;
}
status = deflate_1.deflate(strm, _flush_mode); // Ended => flush and finish
if (status === Z_STREAM_END$1) {
if (strm.next_out > 0) {
this.onData(strm.output.subarray(0, strm.next_out));
}
status = deflate_1.deflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === Z_OK$1;
} // Flush if out buffer full
if (strm.avail_out === 0) {
this.onData(strm.output);
continue;
} // Flush if requested and has data
if (_flush_mode > 0 && strm.next_out > 0) {
this.onData(strm.output.subarray(0, strm.next_out));
strm.avail_out = 0;
continue;
}
if (strm.avail_in === 0) break;
}
return true;
};
/**
* Deflate#onData(chunk) -> Void
* - chunk (Uint8Array): output data.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Deflate.prototype.onData = function (chunk) {
this.chunks.push(chunk);
};
/**
* Deflate#onEnd(status) -> Void
* - status (Number): deflate status. 0 (Z_OK) on success,
* other if not.
*
* Called once after you tell deflate that the input stream is
* complete (Z_FINISH). By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Deflate.prototype.onEnd = function (status) {
// On success - join
if (status === Z_OK$1) {
this.result = common.flattenChunks(this.chunks);
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* deflate(data[, options]) -> Uint8Array
* - data (Uint8Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* Compress `data` with deflate algorithm and `options`.
*
* Supported options are:
*
* - level
* - windowBits
* - memLevel
* - strategy
* - dictionary
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
*
* ##### Example:
*
* ```javascript
* const pako = require('pako')
* const data = new Uint8Array([1,2,3,4,5,6,7,8,9]);
*
* console.log(pako.deflate(data));
* ```
**/
function deflate$1(input, options) {
var deflator = new Deflate(options);
deflator.push(input, true); // That will never happens, if you don't cheat with options :)
if (deflator.err) {
throw deflator.msg || messages[deflator.err];
}
return deflator.result;
}
/**
* deflateRaw(data[, options]) -> Uint8Array
* - data (Uint8Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function deflateRaw(input, options) {
options = options || {};
options.raw = true;
return deflate$1(input, options);
}
/**
* gzip(data[, options]) -> Uint8Array
* - data (Uint8Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but create gzip wrapper instead of
* deflate one.
**/
function gzip(input, options) {
options = options || {};
options.gzip = true;
return deflate$1(input, options);
}
var Deflate_1 = Deflate;
var deflate_2$1 = deflate$1;
var deflateRaw_1 = deflateRaw;
var gzip_1 = gzip;
var constants$1 = constants;
var deflate_1$1 = {
Deflate: Deflate_1,
deflate: deflate_2$1,
deflateRaw: deflateRaw_1,
gzip: gzip_1,
constants: constants$1
};
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
// See state defs from inflate.js
var BAD = 30;
/* got a data error -- remain here until reset */
var TYPE = 12;
/* i: waiting for type bits, including last-flag bit */
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state.mode === LEN
strm.avail_in >= 6
strm.avail_out >= 258
start >= strm.avail_out
state.bits < 8
On return, state.mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm.avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm.avail_out >= 258 for each loop to avoid checking for
output space.
*/
var inffast = function inflate_fast(strm, start) {
var _in;
/* local strm.input */
var last;
/* have enough input while in < last */
var _out;
/* local strm.output */
var beg;
/* inflate()'s initial strm.output */
var end;
/* while out < end, enough space available */
//#ifdef INFLATE_STRICT
var dmax;
/* maximum distance from zlib header */
//#endif
var wsize;
/* window size or zero if not using window */
var whave;
/* valid bytes in the window */
var wnext;
/* window write index */
// Use `s_window` instead `window`, avoid conflict with instrumentation tools
var s_window;
/* allocated sliding window, if wsize != 0 */
var hold;
/* local strm.hold */
var bits;
/* local strm.bits */
var lcode;
/* local strm.lencode */
var dcode;
/* local strm.distcode */
var lmask;
/* mask for first level of length codes */
var dmask;
/* mask for first level of distance codes */
var here;
/* retrieved table entry */
var op;
/* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
var len;
/* match length, unused bytes */
var dist;
/* match distance */
var from;
/* where to copy match from */
var from_source;
var input, output; // JS specific, because we have no pointers
/* copy state to local variables */
var state = strm.state; //here = state.here;
_in = strm.next_in;
input = strm.input;
last = _in + (strm.avail_in - 5);
_out = strm.next_out;
output = strm.output;
beg = _out - (start - strm.avail_out);
end = _out + (strm.avail_out - 257); //#ifdef INFLATE_STRICT
dmax = state.dmax; //#endif
wsize = state.wsize;
whave = state.whave;
wnext = state.wnext;
s_window = state.window;
hold = state.hold;
bits = state.bits;
lcode = state.lencode;
dcode = state.distcode;
lmask = (1 << state.lenbits) - 1;
dmask = (1 << state.distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
top: do {
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen: for (;;) {
// Goto emulation
op = here >>> 24
/*here.bits*/
;
hold >>>= op;
bits -= op;
op = here >>> 16 & 0xff
/*here.op*/
;
if (op === 0) {
/* literal */
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
output[_out++] = here & 0xffff
/*here.val*/
;
} else if (op & 16) {
/* length base */
len = here & 0xffff
/*here.val*/
;
op &= 15;
/* number of extra bits */
if (op) {
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
len += hold & (1 << op) - 1;
hold >>>= op;
bits -= op;
} //Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist: for (;;) {
// goto emulation
op = here >>> 24
/*here.bits*/
;
hold >>>= op;
bits -= op;
op = here >>> 16 & 0xff
/*here.op*/
;
if (op & 16) {
/* distance base */
dist = here & 0xffff
/*here.val*/
;
op &= 15;
/* number of extra bits */
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
}
dist += hold & (1 << op) - 1; //#ifdef INFLATE_STRICT
if (dist > dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
} //#endif
hold >>>= op;
bits -= op; //Tracevv((stderr, "inflate: distance %u\n", dist));
op = _out - beg;
/* max distance in output */
if (dist > op) {
/* see if copy from window */
op = dist - op;
/* distance back in window */
if (op > whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
} // (!) This block is disabled in zlib defaults,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// if (len <= op - whave) {
// do {
// output[_out++] = 0;
// } while (--len);
// continue top;
// }
// len -= op - whave;
// do {
// output[_out++] = 0;
// } while (--op > whave);
// if (op === 0) {
// from = _out - dist;
// do {
// output[_out++] = output[from++];
// } while (--len);
// continue top;
// }
//#endif
}
from = 0; // window index
from_source = s_window;
if (wnext === 0) {
/* very common case */
from += wsize - op;
if (op < len) {
/* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist;
/* rest from output */
from_source = output;
}
} else if (wnext < op) {
/* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) {
/* some from end of window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = 0;
if (wnext < len) {
/* some from start of window */
op = wnext;
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist;
/* rest from output */
from_source = output;
}
}
} else {
/* contiguous in window */
from += wnext - op;
if (op < len) {
/* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist;
/* rest from output */
from_source = output;
}
}
while (len > 2) {
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
len -= 3;
}
if (len) {
output[_out++] = from_source[from++];
if (len > 1) {
output[_out++] = from_source[from++];
}
}
} else {
from = _out - dist;
/* copy direct from output */
do {
/* minimum length is three */
output[_out++] = output[from++];
output[_out++] = output[from++];
output[_out++] = output[from++];
len -= 3;
} while (len > 2);
if (len) {
output[_out++] = output[from++];
if (len > 1) {
output[_out++] = output[from++];
}
}
}
} else if ((op & 64) === 0) {
/* 2nd level distance code */
here = dcode[(here & 0xffff) + (
/*here.val*/
hold & (1 << op) - 1)];
continue dodist;
} else {
strm.msg = 'invalid distance code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
} else if ((op & 64) === 0) {
/* 2nd level length code */
here = lcode[(here & 0xffff) + (
/*here.val*/
hold & (1 << op) - 1)];
continue dolen;
} else if (op & 32) {
/* end-of-block */
//Tracevv((stderr, "inflate: end of block\n"));
state.mode = TYPE;
break top;
} else {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
} while (_in < last && _out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
_in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
/* update state and return */
strm.next_in = _in;
strm.next_out = _out;
strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last);
strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end);
state.hold = hold;
state.bits = bits;
return;
};
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
var MAXBITS = 15;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592; //const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var CODES = 0;
var LENS = 1;
var DISTS = 2;
var lbase = new Uint16Array([
/* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0]);
var lext = new Uint8Array([
/* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78]);
var dbase = new Uint16Array([
/* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0]);
var dext = new Uint8Array([
/* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64]);
var inflate_table = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) {
var bits = opts.bits; //here = opts.here; /* table entry for duplication */
var len = 0;
/* a code's length in bits */
var sym = 0;
/* index of code symbols */
var min = 0,
max = 0;
/* minimum and maximum code lengths */
var root = 0;
/* number of index bits for root table */
var curr = 0;
/* number of index bits for current table */
var drop = 0;
/* code bits to drop for sub-table */
var left = 0;
/* number of prefix codes available */
var used = 0;
/* code entries in table used */
var huff = 0;
/* Huffman code */
var incr;
/* for incrementing code, index */
var fill;
/* index for replicating entries */
var low;
/* low bits for current root entry */
var mask;
/* mask for low root bits */
var next;
/* next available space in table */
var base = null;
/* base value table to use */
var base_index = 0; // let shoextra; /* extra bits table to use */
var end;
/* use base and extra for symbol > end */
var count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
var offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
var extra = null;
var extra_index = 0;
var here_bits, here_op, here_val;
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++) {
count[len] = 0;
}
for (sym = 0; sym < codes; sym++) {
count[lens[lens_index + sym]]++;
}
/* bound code lengths, force root to be within code lengths */
root = bits;
for (max = MAXBITS; max >= 1; max--) {
if (count[max] !== 0) {
break;
}
}
if (root > max) {
root = max;
}
if (max === 0) {
/* no symbols to code at all */
//table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
//table.bits[opts.table_index] = 1; //here.bits = (var char)1;
//table.val[opts.table_index++] = 0; //here.val = (var short)0;
table[table_index++] = 1 << 24 | 64 << 16 | 0; //table.op[opts.table_index] = 64;
//table.bits[opts.table_index] = 1;
//table.val[opts.table_index++] = 0;
table[table_index++] = 1 << 24 | 64 << 16 | 0;
opts.bits = 1;
return 0;
/* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++) {
if (count[min] !== 0) {
break;
}
}
if (root < min) {
root = min;
}
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) {
return -1;
}
/* over-subscribed */
}
if (left > 0 && (type === CODES || max !== 1)) {
return -1;
/* incomplete set */
}
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + count[len];
}
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++) {
if (lens[lens_index + sym] !== 0) {
work[offs[lens[lens_index + sym]]++] = sym;
}
}
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
// poor man optimization - use if-else instead of switch,
// to avoid deopts in old v8
if (type === CODES) {
base = extra = work;
/* dummy value--not used */
end = 19;
} else if (type === LENS) {
base = lbase;
base_index -= 257;
extra = lext;
extra_index -= 257;
end = 256;
} else {
/* DISTS */
base = dbase;
extra = dext;
end = -1;
}
/* initialize opts for loop */
huff = 0;
/* starting code */
sym = 0;
/* starting code symbol */
len = min;
/* starting code length */
next = table_index;
/* current table to fill in */
curr = root;
/* current table index bits */
drop = 0;
/* current bits to drop from code for index */
low = -1;
/* trigger new sub-table when len > root */
used = 1 << root;
/* use root table entries */
mask = used - 1;
/* mask for comparing low */
/* check available table space */
if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) {
return 1;
}
/* process all codes and make table entries */
for (;;) {
/* create table entry */
here_bits = len - drop;
if (work[sym] < end) {
here_op = 0;
here_val = work[sym];
} else if (work[sym] > end) {
here_op = extra[extra_index + work[sym]];
here_val = base[base_index + work[sym]];
} else {
here_op = 32 + 64;
/* end of block */
here_val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1 << len - drop;
fill = 1 << curr;
min = fill;
/* save offset to next table */
do {
fill -= incr;
table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val | 0;
} while (fill !== 0);
/* backwards increment the len-bit code huff */
incr = 1 << len - 1;
while (huff & incr) {
incr >>= 1;
}
if (incr !== 0) {
huff &= incr - 1;
huff += incr;
} else {
huff = 0;
}
/* go to next symbol, update count, len */
sym++;
if (--count[len] === 0) {
if (len === max) {
break;
}
len = lens[lens_index + work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) !== low) {
/* if first time, transition to sub-tables */
if (drop === 0) {
drop = root;
}
/* increment past last table */
next += min;
/* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = 1 << curr;
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) {
break;
}
curr++;
left <<= 1;
}
/* check for enough space */
used += 1 << curr;
if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) {
return 1;
}
/* point entry in root table to sub-table */
low = huff & mask;
/*table.op[low] = curr;
table.bits[low] = root;
table.val[low] = next - opts.table_index;*/
table[low] = root << 24 | curr << 16 | next - table_index | 0;
}
}
/* fill in remaining table entry if code is incomplete (guaranteed to have
at most one remaining entry, since if the code is incomplete, the
maximum code length that was allowed to get this far is one bit) */
if (huff !== 0) {
//table.op[next + huff] = 64; /* invalid code marker */
//table.bits[next + huff] = len - drop;
//table.val[next + huff] = 0;
table[next + huff] = len - drop << 24 | 64 << 16 | 0;
}
/* set return parameters */
//opts.table_index += used;
opts.bits = root;
return 0;
};
var inftrees = inflate_table;
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
var CODES$1 = 0;
var LENS$1 = 1;
var DISTS$1 = 2;
/* Public constants ==========================================================*/
/* ===========================================================================*/
var Z_FINISH$2 = constants.Z_FINISH,
Z_BLOCK$1 = constants.Z_BLOCK,
Z_TREES = constants.Z_TREES,
Z_OK$2 = constants.Z_OK,
Z_STREAM_END$2 = constants.Z_STREAM_END,
Z_NEED_DICT = constants.Z_NEED_DICT,
Z_STREAM_ERROR$1 = constants.Z_STREAM_ERROR,
Z_DATA_ERROR$1 = constants.Z_DATA_ERROR,
Z_MEM_ERROR = constants.Z_MEM_ERROR,
Z_BUF_ERROR$1 = constants.Z_BUF_ERROR,
Z_DEFLATED$2 = constants.Z_DEFLATED;
/* STATES ====================================================================*/
/* ===========================================================================*/
var HEAD = 1;
/* i: waiting for magic header */
var FLAGS = 2;
/* i: waiting for method and flags (gzip) */
var TIME = 3;
/* i: waiting for modification time (gzip) */
var OS = 4;
/* i: waiting for extra flags and operating system (gzip) */
var EXLEN = 5;
/* i: waiting for extra length (gzip) */
var EXTRA = 6;
/* i: waiting for extra bytes (gzip) */
var NAME = 7;
/* i: waiting for end of file name (gzip) */
var COMMENT = 8;
/* i: waiting for end of comment (gzip) */
var HCRC = 9;
/* i: waiting for header crc (gzip) */
var DICTID = 10;
/* i: waiting for dictionary check value */
var DICT = 11;
/* waiting for inflateSetDictionary() call */
var TYPE$1 = 12;
/* i: waiting for type bits, including last-flag bit */
var TYPEDO = 13;
/* i: same, but skip check to exit inflate on new block */
var STORED = 14;
/* i: waiting for stored size (length and complement) */
var COPY_ = 15;
/* i/o: same as COPY below, but only first time in */
var COPY = 16;
/* i/o: waiting for input or output to copy stored block */
var TABLE = 17;
/* i: waiting for dynamic block table lengths */
var LENLENS = 18;
/* i: waiting for code length code lengths */
var CODELENS = 19;
/* i: waiting for length/lit and distance code lengths */
var LEN_ = 20;
/* i: same as LEN below, but only first time in */
var LEN = 21;
/* i: waiting for length/lit/eob code */
var LENEXT = 22;
/* i: waiting for length extra bits */
var DIST = 23;
/* i: waiting for distance code */
var DISTEXT = 24;
/* i: waiting for distance extra bits */
var MATCH = 25;
/* o: waiting for output space to copy string */
var LIT = 26;
/* o: waiting for output space to write literal */
var CHECK = 27;
/* i: waiting for 32-bit check value */
var LENGTH = 28;
/* i: waiting for 32-bit length (gzip) */
var DONE = 29;
/* finished check, done -- remain here until reset */
var BAD$1 = 30;
/* got a data error -- remain here until reset */
var MEM = 31;
/* got an inflate() memory error -- remain here until reset */
var SYNC = 32;
/* looking for synchronization bytes to restart inflate() */
/* ===========================================================================*/
var ENOUGH_LENS$1 = 852;
var ENOUGH_DISTS$1 = 592; //const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var MAX_WBITS$1 = 15;
/* 32K LZ77 window */
var DEF_WBITS = MAX_WBITS$1;
var zswap32 = function zswap32(q) {
return (q >>> 24 & 0xff) + (q >>> 8 & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24);
};
function InflateState() {
this.mode = 0;
/* current inflate mode */
this.last = false;
/* true if processing last block */
this.wrap = 0;
/* bit 0 true for zlib, bit 1 true for gzip */
this.havedict = false;
/* true if dictionary provided */
this.flags = 0;
/* gzip header method and flags (0 if zlib) */
this.dmax = 0;
/* zlib header max distance (INFLATE_STRICT) */
this.check = 0;
/* protected copy of check value */
this.total = 0;
/* protected copy of output count */
// TODO: may be {}
this.head = null;
/* where to save gzip header information */
/* sliding window */
this.wbits = 0;
/* log base 2 of requested window size */
this.wsize = 0;
/* window size or zero if not using window */
this.whave = 0;
/* valid bytes in the window */
this.wnext = 0;
/* window write index */
this.window = null;
/* allocated sliding window, if needed */
/* bit accumulator */
this.hold = 0;
/* input bit accumulator */
this.bits = 0;
/* number of bits in "in" */
/* for string and stored block copying */
this.length = 0;
/* literal or length of data to copy */
this.offset = 0;
/* distance back to copy string from */
/* for table and code decoding */
this.extra = 0;
/* extra bits needed */
/* fixed and dynamic code tables */
this.lencode = null;
/* starting table for length/literal codes */
this.distcode = null;
/* starting table for distance codes */
this.lenbits = 0;
/* index bits for lencode */
this.distbits = 0;
/* index bits for distcode */
/* dynamic table building */
this.ncode = 0;
/* number of code length code lengths */
this.nlen = 0;
/* number of length code lengths */
this.ndist = 0;
/* number of distance code lengths */
this.have = 0;
/* number of code lengths in lens[] */
this.next = null;
/* next available space in codes[] */
this.lens = new Uint16Array(320);
/* temporary storage for code lengths */
this.work = new Uint16Array(288);
/* work area for code table building */
/*
because we don't have pointers in js, we use lencode and distcode directly
as buffers so we don't need codes
*/
//this.codes = new Int32Array(ENOUGH); /* space for code tables */
this.lendyn = null;
/* dynamic table for length/literal codes (JS specific) */
this.distdyn = null;
/* dynamic table for distance codes (JS specific) */
this.sane = 0;
/* if false, allow invalid distance too far */
this.back = 0;
/* bits back of last unprocessed length/lit */
this.was = 0;
/* initial length of match */
}
var inflateResetKeep = function inflateResetKeep(strm) {
if (!strm || !strm.state) {
return Z_STREAM_ERROR$1;
}
var state = strm.state;
strm.total_in = strm.total_out = state.total = 0;
strm.msg = '';
/*Z_NULL*/
if (state.wrap) {
/* to support ill-conceived Java test suite */
strm.adler = state.wrap & 1;
}
state.mode = HEAD;
state.last = 0;
state.havedict = 0;
state.dmax = 32768;
state.head = null
/*Z_NULL*/
;
state.hold = 0;
state.bits = 0; //state.lencode = state.distcode = state.next = state.codes;
state.lencode = state.lendyn = new Int32Array(ENOUGH_LENS$1);
state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS$1);
state.sane = 1;
state.back = -1; //Tracev((stderr, "inflate: reset\n"));
return Z_OK$2;
};
var inflateReset = function inflateReset(strm) {
if (!strm || !strm.state) {
return Z_STREAM_ERROR$1;
}
var state = strm.state;
state.wsize = 0;
state.whave = 0;
state.wnext = 0;
return inflateResetKeep(strm);
};
var inflateReset2 = function inflateReset2(strm, windowBits) {
var wrap;
/* get the state */
if (!strm || !strm.state) {
return Z_STREAM_ERROR$1;
}
var state = strm.state;
/* extract wrap request from windowBits parameter */
if (windowBits < 0) {
wrap = 0;
windowBits = -windowBits;
} else {
wrap = (windowBits >> 4) + 1;
if (windowBits < 48) {
windowBits &= 15;
}
}
/* set number of window bits, free window if different */
if (windowBits && (windowBits < 8 || windowBits > 15)) {
return Z_STREAM_ERROR$1;
}
if (state.window !== null && state.wbits !== windowBits) {
state.window = null;
}
/* update state and reset the rest of it */
state.wrap = wrap;
state.wbits = windowBits;
return inflateReset(strm);
};
var inflateInit2 = function inflateInit2(strm, windowBits) {
if (!strm) {
return Z_STREAM_ERROR$1;
} //strm.msg = Z_NULL; /* in case we return an error */
var state = new InflateState(); //if (state === Z_NULL) return Z_MEM_ERROR;
//Tracev((stderr, "inflate: allocated\n"));
strm.state = state;
state.window = null
/*Z_NULL*/
;
var ret = inflateReset2(strm, windowBits);
if (ret !== Z_OK$2) {
strm.state = null
/*Z_NULL*/
;
}
return ret;
};
var inflateInit = function inflateInit(strm) {
return inflateInit2(strm, DEF_WBITS);
};
/*
Return state with length and distance decoding tables and index sizes set to
fixed code decoding. Normally this returns fixed tables from inffixed.h.
If BUILDFIXED is defined, then instead this routine builds the tables the
first time it's called, and returns those tables the first time and
thereafter. This reduces the size of the code by about 2K bytes, in
exchange for a little execution time. However, BUILDFIXED should not be
used for threaded applications, since the rewriting of the tables and virgin
may not be thread-safe.
*/
var virgin = true;
var lenfix, distfix; // We have no pointers in JS, so keep tables separate
var fixedtables = function fixedtables(state) {
/* build fixed huffman tables if first call (may not be thread safe) */
if (virgin) {
lenfix = new Int32Array(512);
distfix = new Int32Array(32);
/* literal/length table */
var sym = 0;
while (sym < 144) {
state.lens[sym++] = 8;
}
while (sym < 256) {
state.lens[sym++] = 9;
}
while (sym < 280) {
state.lens[sym++] = 7;
}
while (sym < 288) {
state.lens[sym++] = 8;
}
inftrees(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, {
bits: 9
});
/* distance table */
sym = 0;
while (sym < 32) {
state.lens[sym++] = 5;
}
inftrees(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, {
bits: 5
});
/* do this just once */
virgin = false;
}
state.lencode = lenfix;
state.lenbits = 9;
state.distcode = distfix;
state.distbits = 5;
};
/*
Update the window with the last wsize (normally 32K) bytes written before
returning. If window does not exist yet, create it. This is only called
when a window is already in use, or when output has been written during this
inflate call, but the end of the deflate stream has not been reached yet.
It is also called to create a window for dictionary data when a dictionary
is loaded.
Providing output buffers larger than 32K to inflate() should provide a speed
advantage, since only the last 32K of output is copied to the sliding window
upon return from inflate(), and since all distances after the first 32K of
output will fall in the output data, making match copies simpler and faster.
The advantage may be dependent on the size of the processor's data caches.
*/
var updatewindow = function updatewindow(strm, src, end, copy) {
var dist;
var state = strm.state;
/* if it hasn't been done already, allocate space for the window */
if (state.window === null) {
state.wsize = 1 << state.wbits;
state.wnext = 0;
state.whave = 0;
state.window = new Uint8Array(state.wsize);
}
/* copy state->wsize or less output bytes into the circular window */
if (copy >= state.wsize) {
state.window.set(src.subarray(end - state.wsize, end), 0);
state.wnext = 0;
state.whave = state.wsize;
} else {
dist = state.wsize - state.wnext;
if (dist > copy) {
dist = copy;
} //zmemcpy(state->window + state->wnext, end - copy, dist);
state.window.set(src.subarray(end - copy, end - copy + dist), state.wnext);
copy -= dist;
if (copy) {
//zmemcpy(state->window, end - copy, copy);
state.window.set(src.subarray(end - copy, end), 0);
state.wnext = copy;
state.whave = state.wsize;
} else {
state.wnext += dist;
if (state.wnext === state.wsize) {
state.wnext = 0;
}
if (state.whave < state.wsize) {
state.whave += dist;
}
}
}
return 0;
};
var inflate = function inflate(strm, flush) {
var state;
var input, output; // input/output buffers
var next;
/* next input INDEX */
var put;
/* next output INDEX */
var have, left;
/* available input and output */
var hold;
/* bit buffer */
var bits;
/* bits in bit buffer */
var _in, _out;
/* save starting available input and output */
var copy;
/* number of stored or match bytes to copy */
var from;
/* where to copy match bytes from */
var from_source;
var here = 0;
/* current decoding table entry */
var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
//let last; /* parent table entry */
var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
var len;
/* length to copy for repeats, bits to drop */
var ret;
/* return code */
var hbuf = new Uint8Array(4);
/* buffer for gzip header crc calculation */
var opts;
var n; // temporary variable for NEED_BITS
var order =
/* permutation of code lengths */
new Uint8Array([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
if (!strm || !strm.state || !strm.output || !strm.input && strm.avail_in !== 0) {
return Z_STREAM_ERROR$1;
}
state = strm.state;
if (state.mode === TYPE$1) {
state.mode = TYPEDO;
}
/* skip check */
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits; //---
_in = have;
_out = left;
ret = Z_OK$2;
inf_leave: // goto emulation
for (;;) {
switch (state.mode) {
case HEAD:
if (state.wrap === 0) {
state.mode = TYPEDO;
break;
} //=== NEEDBITS(16);
while (bits < 16) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
} //===//
if (state.wrap & 2 && hold === 0x8b1f) {
/* gzip header */
state.check = 0
/*crc32(0L, Z_NULL, 0)*/
; //=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = hold >>> 8 & 0xff;
state.check = crc32_1(state.check, hbuf, 2, 0); //===//
//=== INITBITS();
hold = 0;
bits = 0; //===//
state.mode = FLAGS;
break;
}
state.flags = 0;
/* expect zlib header */
if (state.head) {
state.head.done = false;
}
if (!(state.wrap & 1) ||
/* check if zlib header allowed */
(((hold & 0xff) <<
/*BITS(8)*/
8) + (hold >> 8)) % 31) {
strm.msg = 'incorrect header check';
state.mode = BAD$1;
break;
}
if ((hold & 0x0f) !==
/*BITS(4)*/
Z_DEFLATED$2) {
strm.msg = 'unknown compression method';
state.mode = BAD$1;
break;
} //--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4; //---//
len = (hold & 0x0f) +
/*BITS(4)*/
8;
if (state.wbits === 0) {
state.wbits = len;
} else if (len > state.wbits) {
strm.msg = 'invalid window size';
state.mode = BAD$1;
break;
} // !!! pako patch. Force use `options.windowBits` if passed.
// Required to always use max window size by default.
state.dmax = 1 << state.wbits; //state.dmax = 1 << len;
//Tracev((stderr, "inflate: zlib header ok\n"));
strm.adler = state.check = 1
/*adler32(0L, Z_NULL, 0)*/
;
state.mode = hold & 0x200 ? DICTID : TYPE$1; //=== INITBITS();
hold = 0;
bits = 0; //===//
break;
case FLAGS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
} //===//
state.flags = hold;
if ((state.flags & 0xff) !== Z_DEFLATED$2) {
strm.msg = 'unknown compression method';
state.mode = BAD$1;
break;
}
if (state.flags & 0xe000) {
strm.msg = 'unknown header flags set';
state.mode = BAD$1;
break;
}
if (state.head) {
state.head.text = hold >> 8 & 1;
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = hold >>> 8 & 0xff;
state.check = crc32_1(state.check, hbuf, 2, 0); //===//
} //=== INITBITS();
hold = 0;
bits = 0; //===//
state.mode = TIME;
/* falls through */
case TIME:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
} //===//
if (state.head) {
state.head.time = hold;
}
if (state.flags & 0x0200) {
//=== CRC4(state.check, hold)
hbuf[0] = hold & 0xff;
hbuf[1] = hold >>> 8 & 0xff;
hbuf[2] = hold >>> 16 & 0xff;
hbuf[3] = hold >>> 24 & 0xff;
state.check = crc32_1(state.check, hbuf, 4, 0); //===
} //=== INITBITS();
hold = 0;
bits = 0; //===//
state.mode = OS;
/* falls through */
case OS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
} //===//
if (state.head) {
state.head.xflags = hold & 0xff;
state.head.os = hold >> 8;
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = hold >>> 8 & 0xff;
state.check = crc32_1(state.check, hbuf, 2, 0); //===//
} //=== INITBITS();
hold = 0;
bits = 0; //===//
state.mode = EXLEN;
/* falls through */
case EXLEN:
if (state.flags & 0x0400) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
} //===//
state.length = hold;
if (state.head) {
state.head.extra_len = hold;
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = hold >>> 8 & 0xff;
state.check = crc32_1(state.check, hbuf, 2, 0); //===//
} //=== INITBITS();
hold = 0;
bits = 0; //===//
} else if (state.head) {
state.head.extra = null
/*Z_NULL*/
;
}
state.mode = EXTRA;
/* falls through */
case EXTRA:
if (state.flags & 0x0400) {
copy = state.length;
if (copy > have) {
copy = have;
}
if (copy) {
if (state.head) {
len = state.head.extra_len - state.length;
if (!state.head.extra) {
// Use untyped array for more convenient processing later
state.head.extra = new Uint8Array(state.head.extra_len);
}
state.head.extra.set(input.subarray(next, // extra field is limited to 65536 bytes
// - no need for additional size check
next + copy),
/*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
len); //zmemcpy(state.head.extra + len, next,
// len + copy > state.head.extra_max ?
// state.head.extra_max - len : copy);
}
if (state.flags & 0x0200) {
state.check = crc32_1(state.check, input, copy, next);
}
have -= copy;
next += copy;
state.length -= copy;
}
if (state.length) {
break inf_leave;
}
}
state.length = 0;
state.mode = NAME;
/* falls through */
case NAME:
if (state.flags & 0x0800) {
if (have === 0) {
break inf_leave;
}
copy = 0;
do {
// TODO: 2 or 1 bytes?
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len && state.length < 65536
/*state.head.name_max*/
) {
state.head.name += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32_1(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) {
break inf_leave;
}
} else if (state.head) {
state.head.name = null;
}
state.length = 0;
state.mode = COMMENT;
/* falls through */
case COMMENT:
if (state.flags & 0x1000) {
if (have === 0) {
break inf_leave;
}
copy = 0;
do {
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len && state.length < 65536
/*state.head.comm_max*/
) {
state.head.comment += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32_1(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) {
break inf_leave;
}
} else if (state.head) {
state.head.comment = null;
}
state.mode = HCRC;
/* falls through */
case HCRC:
if (state.flags & 0x0200) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
} //===//
if (hold !== (state.check & 0xffff)) {
strm.msg = 'header crc mismatch';
state.mode = BAD$1;
break;
} //=== INITBITS();
hold = 0;
bits = 0; //===//
}
if (state.head) {
state.head.hcrc = state.flags >> 9 & 1;
state.head.done = true;
}
strm.adler = state.check = 0;
state.mode = TYPE$1;
break;
case DICTID:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
} //===//
strm.adler = state.check = zswap32(hold); //=== INITBITS();
hold = 0;
bits = 0; //===//
state.mode = DICT;
/* falls through */
case DICT:
if (state.havedict === 0) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits; //---
return Z_NEED_DICT;
}
strm.adler = state.check = 1
/*adler32(0L, Z_NULL, 0)*/
;
state.mode = TYPE$1;
/* falls through */
case TYPE$1:
if (flush === Z_BLOCK$1 || flush === Z_TREES) {
break inf_leave;
}
/* falls through */
case TYPEDO:
if (state.last) {
//--- BYTEBITS() ---//
hold >>>= bits & 7;
bits -= bits & 7; //---//
state.mode = CHECK;
break;
} //=== NEEDBITS(3); */
while (bits < 3) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
} //===//
state.last = hold & 0x01
/*BITS(1)*/
; //--- DROPBITS(1) ---//
hold >>>= 1;
bits -= 1; //---//
switch (hold & 0x03) {
/*BITS(2)*/
case 0:
/* stored block */
//Tracev((stderr, "inflate: stored block%s\n",
// state.last ? " (last)" : ""));
state.mode = STORED;
break;
case 1:
/* fixed block */
fixedtables(state); //Tracev((stderr, "inflate: fixed codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = LEN_;
/* decode codes */
if (flush === Z_TREES) {
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2; //---//
break inf_leave;
}
break;
case 2:
/* dynamic block */
//Tracev((stderr, "inflate: dynamic codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = TABLE;
break;
case 3:
strm.msg = 'invalid block type';
state.mode = BAD$1;
} //--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2; //---//
break;
case STORED:
//--- BYTEBITS() ---// /* go to byte boundary */
hold >>>= bits & 7;
bits -= bits & 7; //---//
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
} //===//
if ((hold & 0xffff) !== (hold >>> 16 ^ 0xffff)) {
strm.msg = 'invalid stored block lengths';
state.mode = BAD$1;
break;
}
state.length = hold & 0xffff; //Tracev((stderr, "inflate: stored length %u\n",
// state.length));
//=== INITBITS();
hold = 0;
bits = 0; //===//
state.mode = COPY_;
if (flush === Z_TREES) {
break inf_leave;
}
/* falls through */
case COPY_:
state.mode = COPY;
/* falls through */
case COPY:
copy = state.length;
if (copy) {
if (copy > have) {
copy = have;
}
if (copy > left) {
copy = left;
}
if (copy === 0) {
break inf_leave;
} //--- zmemcpy(put, next, copy); ---
output.set(input.subarray(next, next + copy), put); //---//
have -= copy;
next += copy;
left -= copy;
put += copy;
state.length -= copy;
break;
} //Tracev((stderr, "inflate: stored end\n"));
state.mode = TYPE$1;
break;
case TABLE:
//=== NEEDBITS(14); */
while (bits < 14) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
} //===//
state.nlen = (hold & 0x1f) +
/*BITS(5)*/
257; //--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5; //---//
state.ndist = (hold & 0x1f) +
/*BITS(5)*/
1; //--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5; //---//
state.ncode = (hold & 0x0f) +
/*BITS(4)*/
4; //--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4; //---//
//#ifndef PKZIP_BUG_WORKAROUND
if (state.nlen > 286 || state.ndist > 30) {
strm.msg = 'too many length or distance symbols';
state.mode = BAD$1;
break;
} //#endif
//Tracev((stderr, "inflate: table sizes ok\n"));
state.have = 0;
state.mode = LENLENS;
/* falls through */
case LENLENS:
while (state.have < state.ncode) {
//=== NEEDBITS(3);
while (bits < 3) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
} //===//
state.lens[order[state.have++]] = hold & 0x07; //BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3; //---//
}
while (state.have < 19) {
state.lens[order[state.have++]] = 0;
} // We have separate tables & no pointers. 2 commented lines below not needed.
//state.next = state.codes;
//state.lencode = state.next;
// Switch to use dynamic table
state.lencode = state.lendyn;
state.lenbits = 7;
opts = {
bits: state.lenbits
};
ret = inftrees(CODES$1, state.lens, 0, 19, state.lencode, 0, state.work, opts);
state.lenbits = opts.bits;
if (ret) {
strm.msg = 'invalid code lengths set';
state.mode = BAD$1;
break;
} //Tracev((stderr, "inflate: code lengths ok\n"));
state.have = 0;
state.mode = CODELENS;
/* falls through */
case CODELENS:
while (state.have < state.nlen + state.ndist) {
for (;;) {
here = state.lencode[hold & (1 << state.lenbits) - 1];
/*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = here >>> 16 & 0xff;
here_val = here & 0xffff;
if (here_bits <= bits) {
break;
} //--- PULLBYTE() ---//
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8; //---//
}
if (here_val < 16) {
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits; //---//
state.lens[state.have++] = here_val;
} else {
if (here_val === 16) {
//=== NEEDBITS(here.bits + 2);
n = here_bits + 2;
while (bits < n) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
} //===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits; //---//
if (state.have === 0) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD$1;
break;
}
len = state.lens[state.have - 1];
copy = 3 + (hold & 0x03); //BITS(2);
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2; //---//
} else if (here_val === 17) {
//=== NEEDBITS(here.bits + 3);
n = here_bits + 3;
while (bits < n) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
} //===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits; //---//
len = 0;
copy = 3 + (hold & 0x07); //BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3; //---//
} else {
//=== NEEDBITS(here.bits + 7);
n = here_bits + 7;
while (bits < n) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
} //===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits; //---//
len = 0;
copy = 11 + (hold & 0x7f); //BITS(7);
//--- DROPBITS(7) ---//
hold >>>= 7;
bits -= 7; //---//
}
if (state.have + copy > state.nlen + state.ndist) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD$1;
break;
}
while (copy--) {
state.lens[state.have++] = len;
}
}
}
/* handle error breaks in while */
if (state.mode === BAD$1) {
break;
}
/* check for end-of-block code (better have one) */
if (state.lens[256] === 0) {
strm.msg = 'invalid code -- missing end-of-block';
state.mode = BAD$1;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftrees.h
concerning the ENOUGH constants, which depend on those values */
state.lenbits = 9;
opts = {
bits: state.lenbits
};
ret = inftrees(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.lenbits = opts.bits; // state.lencode = state.next;
if (ret) {
strm.msg = 'invalid literal/lengths set';
state.mode = BAD$1;
break;
}
state.distbits = 6; //state.distcode.copy(state.codes);
// Switch to use dynamic table
state.distcode = state.distdyn;
opts = {
bits: state.distbits
};
ret = inftrees(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.distbits = opts.bits; // state.distcode = state.next;
if (ret) {
strm.msg = 'invalid distances set';
state.mode = BAD$1;
break;
} //Tracev((stderr, 'inflate: codes ok\n'));
state.mode = LEN_;
if (flush === Z_TREES) {
break inf_leave;
}
/* falls through */
case LEN_:
state.mode = LEN;
/* falls through */
case LEN:
if (have >= 6 && left >= 258) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits; //---
inffast(strm, _out); //--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits; //---
if (state.mode === TYPE$1) {
state.back = -1;
}
break;
}
state.back = 0;
for (;;) {
here = state.lencode[hold & (1 << state.lenbits) - 1];
/*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = here >>> 16 & 0xff;
here_val = here & 0xffff;
if (here_bits <= bits) {
break;
} //--- PULLBYTE() ---//
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8; //---//
}
if (here_op && (here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.lencode[last_val + ((hold & (1 << last_bits + last_op) - 1) >>
/*BITS(last.bits + last.op)*/
last_bits)];
here_bits = here >>> 24;
here_op = here >>> 16 & 0xff;
here_val = here & 0xffff;
if (last_bits + here_bits <= bits) {
break;
} //--- PULLBYTE() ---//
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8; //---//
} //--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits; //---//
state.back += last_bits;
} //--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits; //---//
state.back += here_bits;
state.length = here_val;
if (here_op === 0) {
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
state.mode = LIT;
break;
}
if (here_op & 32) {
//Tracevv((stderr, "inflate: end of block\n"));
state.back = -1;
state.mode = TYPE$1;
break;
}
if (here_op & 64) {
strm.msg = 'invalid literal/length code';
state.mode = BAD$1;
break;
}
state.extra = here_op & 15;
state.mode = LENEXT;
/* falls through */
case LENEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
} //===//
state.length += hold & (1 << state.extra) - 1
/*BITS(state.extra)*/
; //--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra; //---//
state.back += state.extra;
} //Tracevv((stderr, "inflate: length %u\n", state.length));
state.was = state.length;
state.mode = DIST;
/* falls through */
case DIST:
for (;;) {
here = state.distcode[hold & (1 << state.distbits) - 1];
/*BITS(state.distbits)*/
here_bits = here >>> 24;
here_op = here >>> 16 & 0xff;
here_val = here & 0xffff;
if (here_bits <= bits) {
break;
} //--- PULLBYTE() ---//
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8; //---//
}
if ((here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.distcode[last_val + ((hold & (1 << last_bits + last_op) - 1) >>
/*BITS(last.bits + last.op)*/
last_bits)];
here_bits = here >>> 24;
here_op = here >>> 16 & 0xff;
here_val = here & 0xffff;
if (last_bits + here_bits <= bits) {
break;
} //--- PULLBYTE() ---//
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8; //---//
} //--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits; //---//
state.back += last_bits;
} //--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits; //---//
state.back += here_bits;
if (here_op & 64) {
strm.msg = 'invalid distance code';
state.mode = BAD$1;
break;
}
state.offset = here_val;
state.extra = here_op & 15;
state.mode = DISTEXT;
/* falls through */
case DISTEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
} //===//
state.offset += hold & (1 << state.extra) - 1
/*BITS(state.extra)*/
; //--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra; //---//
state.back += state.extra;
} //#ifdef INFLATE_STRICT
if (state.offset > state.dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD$1;
break;
} //#endif
//Tracevv((stderr, "inflate: distance %u\n", state.offset));
state.mode = MATCH;
/* falls through */
case MATCH:
if (left === 0) {
break inf_leave;
}
copy = _out - left;
if (state.offset > copy) {
/* copy from window */
copy = state.offset - copy;
if (copy > state.whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD$1;
break;
} // (!) This block is disabled in zlib defaults,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// Trace((stderr, "inflate.c too far\n"));
// copy -= state.whave;
// if (copy > state.length) { copy = state.length; }
// if (copy > left) { copy = left; }
// left -= copy;
// state.length -= copy;
// do {
// output[put++] = 0;
// } while (--copy);
// if (state.length === 0) { state.mode = LEN; }
// break;
//#endif
}
if (copy > state.wnext) {
copy -= state.wnext;
from = state.wsize - copy;
} else {
from = state.wnext - copy;
}
if (copy > state.length) {
copy = state.length;
}
from_source = state.window;
} else {
/* copy from output */
from_source = output;
from = put - state.offset;
copy = state.length;
}
if (copy > left) {
copy = left;
}
left -= copy;
state.length -= copy;
do {
output[put++] = from_source[from++];
} while (--copy);
if (state.length === 0) {
state.mode = LEN;
}
break;
case LIT:
if (left === 0) {
break inf_leave;
}
output[put++] = state.length;
left--;
state.mode = LEN;
break;
case CHECK:
if (state.wrap) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) {
break inf_leave;
}
have--; // Use '|' instead of '+' to make sure that result is signed
hold |= input[next++] << bits;
bits += 8;
} //===//
_out -= left;
strm.total_out += _out;
state.total += _out;
if (_out) {
strm.adler = state.check =
/*UPDATE(state.check, put - _out, _out);*/
state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out);
}
_out = left; // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
if ((state.flags ? hold : zswap32(hold)) !== state.check) {
strm.msg = 'incorrect data check';
state.mode = BAD$1;
break;
} //=== INITBITS();
hold = 0;
bits = 0; //===//
//Tracev((stderr, "inflate: check matches trailer\n"));
}
state.mode = LENGTH;
/* falls through */
case LENGTH:
if (state.wrap && state.flags) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
} //===//
if (hold !== (state.total & 0xffffffff)) {
strm.msg = 'incorrect length check';
state.mode = BAD$1;
break;
} //=== INITBITS();
hold = 0;
bits = 0; //===//
//Tracev((stderr, "inflate: length matches trailer\n"));
}
state.mode = DONE;
/* falls through */
case DONE:
ret = Z_STREAM_END$2;
break inf_leave;
case BAD$1:
ret = Z_DATA_ERROR$1;
break inf_leave;
case MEM:
return Z_MEM_ERROR;
case SYNC:
/* falls through */
default:
return Z_STREAM_ERROR$1;
}
} // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
/*
Return from inflate(), updating the total counts and the check value.
If there was no progress during the inflate() call, return a buffer
error. Call updatewindow() to create and/or update the window state.
Note: a memory error from inflate() is non-recoverable.
*/
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits; //---
if (state.wsize || _out !== strm.avail_out && state.mode < BAD$1 && (state.mode < CHECK || flush !== Z_FINISH$2)) {
if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;
}
_in -= strm.avail_in;
_out -= strm.avail_out;
strm.total_in += _in;
strm.total_out += _out;
state.total += _out;
if (state.wrap && _out) {
strm.adler = state.check =
/*UPDATE(state.check, strm.next_out - _out, _out);*/
state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out);
}
strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE$1 ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
if ((_in === 0 && _out === 0 || flush === Z_FINISH$2) && ret === Z_OK$2) {
ret = Z_BUF_ERROR$1;
}
return ret;
};
var inflateEnd = function inflateEnd(strm) {
if (!strm || !strm.state
/*|| strm->zfree == (free_func)0*/
) {
return Z_STREAM_ERROR$1;
}
var state = strm.state;
if (state.window) {
state.window = null;
}
strm.state = null;
return Z_OK$2;
};
var inflateGetHeader = function inflateGetHeader(strm, head) {
/* check state */
if (!strm || !strm.state) {
return Z_STREAM_ERROR$1;
}
var state = strm.state;
if ((state.wrap & 2) === 0) {
return Z_STREAM_ERROR$1;
}
/* save header structure */
state.head = head;
head.done = false;
return Z_OK$2;
};
var inflateSetDictionary = function inflateSetDictionary(strm, dictionary) {
var dictLength = dictionary.length;
var state;
var dictid;
var ret;
/* check state */
if (!strm
/* == Z_NULL */
|| !strm.state
/* == Z_NULL */
) {
return Z_STREAM_ERROR$1;
}
state = strm.state;
if (state.wrap !== 0 && state.mode !== DICT) {
return Z_STREAM_ERROR$1;
}
/* check for correct dictionary identifier */
if (state.mode === DICT) {
dictid = 1;
/* adler32(0, null, 0)*/
/* dictid = adler32(dictid, dictionary, dictLength); */
dictid = adler32_1(dictid, dictionary, dictLength, 0);
if (dictid !== state.check) {
return Z_DATA_ERROR$1;
}
}
/* copy dictionary to window using updatewindow(), which will amend the
existing dictionary if appropriate */
ret = updatewindow(strm, dictionary, dictLength, dictLength);
if (ret) {
state.mode = MEM;
return Z_MEM_ERROR;
}
state.havedict = 1; // Tracev((stderr, "inflate: dictionary set\n"));
return Z_OK$2;
};
var inflateReset_1 = inflateReset;
var inflateReset2_1 = inflateReset2;
var inflateResetKeep_1 = inflateResetKeep;
var inflateInit_1 = inflateInit;
var inflateInit2_1 = inflateInit2;
var inflate_2 = inflate;
var inflateEnd_1 = inflateEnd;
var inflateGetHeader_1 = inflateGetHeader;
var inflateSetDictionary_1 = inflateSetDictionary;
var inflateInfo = 'pako inflate (from Nodeca project)';
/* Not implemented
module.exports.inflateCopy = inflateCopy;
module.exports.inflateGetDictionary = inflateGetDictionary;
module.exports.inflateMark = inflateMark;
module.exports.inflatePrime = inflatePrime;
module.exports.inflateSync = inflateSync;
module.exports.inflateSyncPoint = inflateSyncPoint;
module.exports.inflateUndermine = inflateUndermine;
*/
var inflate_1 = {
inflateReset: inflateReset_1,
inflateReset2: inflateReset2_1,
inflateResetKeep: inflateResetKeep_1,
inflateInit: inflateInit_1,
inflateInit2: inflateInit2_1,
inflate: inflate_2,
inflateEnd: inflateEnd_1,
inflateGetHeader: inflateGetHeader_1,
inflateSetDictionary: inflateSetDictionary_1,
inflateInfo: inflateInfo
};
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
function GZheader() {
/* true if compressed data believed to be text */
this.text = 0;
/* modification time */
this.time = 0;
/* extra flags (not used when writing a gzip file) */
this.xflags = 0;
/* operating system */
this.os = 0;
/* pointer to extra field or Z_NULL if none */
this.extra = null;
/* extra field length (valid if extra != Z_NULL) */
this.extra_len = 0; // Actually, we don't need it in JS,
// but leave for few code modifications
//
// Setup limits is not necessary because in js we should not preallocate memory
// for inflate use constant limit in 65536 bytes
//
/* space at extra (only when reading header) */
// this.extra_max = 0;
/* pointer to zero-terminated file name or Z_NULL */
this.name = '';
/* space at name (only when reading header) */
// this.name_max = 0;
/* pointer to zero-terminated comment or Z_NULL */
this.comment = '';
/* space at comment (only when reading header) */
// this.comm_max = 0;
/* true if there was or will be a header crc */
this.hcrc = 0;
/* true when done reading gzip header (not used when writing a gzip file) */
this.done = false;
}
var gzheader = GZheader;
var toString$1 = Object.prototype.toString;
/* Public constants ==========================================================*/
/* ===========================================================================*/
var Z_NO_FLUSH$2 = constants.Z_NO_FLUSH,
Z_FINISH$3 = constants.Z_FINISH,
Z_OK$3 = constants.Z_OK,
Z_STREAM_END$3 = constants.Z_STREAM_END,
Z_NEED_DICT$1 = constants.Z_NEED_DICT,
Z_STREAM_ERROR$2 = constants.Z_STREAM_ERROR,
Z_DATA_ERROR$2 = constants.Z_DATA_ERROR,
Z_MEM_ERROR$1 = constants.Z_MEM_ERROR;
/* ===========================================================================*/
/**
* class Inflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[inflate]]
* and [[inflateRaw]].
**/
/* internal
* inflate.chunks -> Array
*
* Chunks of output data, if [[Inflate#onData]] not overridden.
**/
/**
* Inflate.result -> Uint8Array|String
*
* Uncompressed result, generated by default [[Inflate#onData]]
* and [[Inflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Inflate#push]] with `Z_FINISH` / `true` param).
**/
/**
* Inflate.err -> Number
*
* Error code after inflate finished. 0 (Z_OK) on success.
* Should be checked if broken data possible.
**/
/**
* Inflate.msg -> String
*
* Error message, if [[Inflate.err]] != 0
**/
/**
* new Inflate(options)
* - options (Object): zlib inflate options.
*
* Creates new inflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `windowBits`
* - `dictionary`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw inflate
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
* By default, when no options set, autodetect deflate/gzip data format via
* wrapper header.
*
* ##### Example:
*
* ```javascript
* const pako = require('pako')
* const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])
* const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* const inflate = new pako.Inflate({ level: 3});
*
* inflate.push(chunk1, false);
* inflate.push(chunk2, true); // true -> last chunk
*
* if (inflate.err) { throw new Error(inflate.err); }
*
* console.log(inflate.result);
* ```
**/
function Inflate(options) {
this.options = common.assign({
chunkSize: 1024 * 64,
windowBits: 15,
to: ''
}, options || {});
var opt = this.options; // Force window size for `raw` data, if not set directly,
// because we have no header for autodetect.
if (opt.raw && opt.windowBits >= 0 && opt.windowBits < 16) {
opt.windowBits = -opt.windowBits;
if (opt.windowBits === 0) {
opt.windowBits = -15;
}
} // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
if (opt.windowBits >= 0 && opt.windowBits < 16 && !(options && options.windowBits)) {
opt.windowBits += 32;
} // Gzip header has no info about windows size, we can do autodetect only
// for deflate. So, if window size not set, force it to max when gzip possible
if (opt.windowBits > 15 && opt.windowBits < 48) {
// bit 3 (16) -> gzipped data
// bit 4 (32) -> autodetect gzip/deflate
if ((opt.windowBits & 15) === 0) {
opt.windowBits |= 15;
}
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = inflate_1.inflateInit2(this.strm, opt.windowBits);
if (status !== Z_OK$3) {
throw new Error(messages[status]);
}
this.header = new gzheader();
inflate_1.inflateGetHeader(this.strm, this.header); // Setup dictionary
if (opt.dictionary) {
// Convert data if needed
if (typeof opt.dictionary === 'string') {
opt.dictionary = strings.string2buf(opt.dictionary);
} else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') {
opt.dictionary = new Uint8Array(opt.dictionary);
}
if (opt.raw) {
//In raw mode we need to set the dictionary early
status = inflate_1.inflateSetDictionary(this.strm, opt.dictionary);
if (status !== Z_OK$3) {
throw new Error(messages[status]);
}
}
}
}
/**
* Inflate#push(data[, flush_mode]) -> Boolean
* - data (Uint8Array|ArrayBuffer): input data
* - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE
* flush modes. See constants. Skipped or `false` means Z_NO_FLUSH,
* `true` means Z_FINISH.
*
* Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
* new output chunks. Returns `true` on success. If end of stream detected,
* [[Inflate#onEnd]] will be called.
*
* `flush_mode` is not needed for normal operation, because end of stream
* detected automatically. You may try to use it for advanced things, but
* this functionality was not tested.
*
* On fail call [[Inflate#onEnd]] with error code and return false.
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Inflate.prototype.push = function (data, flush_mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var dictionary = this.options.dictionary;
var status, _flush_mode, last_avail_out;
if (this.ended) return false;
if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;else _flush_mode = flush_mode === true ? Z_FINISH$3 : Z_NO_FLUSH$2; // Convert data if needed
if (toString$1.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
for (;;) {
if (strm.avail_out === 0) {
strm.output = new Uint8Array(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = inflate_1.inflate(strm, _flush_mode);
if (status === Z_NEED_DICT$1 && dictionary) {
status = inflate_1.inflateSetDictionary(strm, dictionary);
if (status === Z_OK$3) {
status = inflate_1.inflate(strm, _flush_mode);
} else if (status === Z_DATA_ERROR$2) {
// Replace code with more verbose
status = Z_NEED_DICT$1;
}
} // Skip snyc markers if more data follows and not raw mode
while (strm.avail_in > 0 && status === Z_STREAM_END$3 && strm.state.wrap > 0 && data[strm.next_in] !== 0) {
inflate_1.inflateReset(strm);
status = inflate_1.inflate(strm, _flush_mode);
}
switch (status) {
case Z_STREAM_ERROR$2:
case Z_DATA_ERROR$2:
case Z_NEED_DICT$1:
case Z_MEM_ERROR$1:
this.onEnd(status);
this.ended = true;
return false;
} // Remember real `avail_out` value, because we may patch out buffer content
// to align utf8 strings boundaries.
last_avail_out = strm.avail_out;
if (strm.next_out) {
if (strm.avail_out === 0 || status === Z_STREAM_END$3) {
if (this.options.to === 'string') {
var next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
var tail = strm.next_out - next_out_utf8;
var utf8str = strings.buf2string(strm.output, next_out_utf8); // move tail & realign counters
strm.next_out = tail;
strm.avail_out = chunkSize - tail;
if (tail) strm.output.set(strm.output.subarray(next_out_utf8, next_out_utf8 + tail), 0);
this.onData(utf8str);
} else {
this.onData(strm.output.length === strm.next_out ? strm.output : strm.output.subarray(0, strm.next_out));
}
}
} // Must repeat iteration if out buffer is full
if (status === Z_OK$3 && last_avail_out === 0) continue; // Finalize if end of stream reached.
if (status === Z_STREAM_END$3) {
status = inflate_1.inflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return true;
}
if (strm.avail_in === 0) break;
}
return true;
};
/**
* Inflate#onData(chunk) -> Void
* - chunk (Uint8Array|String): output data. When string output requested,
* each chunk will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Inflate.prototype.onData = function (chunk) {
this.chunks.push(chunk);
};
/**
* Inflate#onEnd(status) -> Void
* - status (Number): inflate status. 0 (Z_OK) on success,
* other if not.
*
* Called either after you tell inflate that the input stream is
* complete (Z_FINISH). By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Inflate.prototype.onEnd = function (status) {
// On success - join
if (status === Z_OK$3) {
if (this.options.to === 'string') {
this.result = this.chunks.join('');
} else {
this.result = common.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* inflate(data[, options]) -> Uint8Array|String
* - data (Uint8Array): input data to decompress.
* - options (Object): zlib inflate options.
*
* Decompress `data` with inflate/ungzip and `options`. Autodetect
* format via wrapper header by default. That's why we don't provide
* separate `ungzip` method.
*
* Supported options are:
*
* - windowBits
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
*
* ##### Example:
*
* ```javascript
* const pako = require('pako');
* const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9]));
* let output;
*
* try {
* output = pako.inflate(input);
* } catch (err)
* console.log(err);
* }
* ```
**/
function inflate$1(input, options) {
var inflator = new Inflate(options);
inflator.push(input); // That will never happens, if you don't cheat with options :)
if (inflator.err) throw inflator.msg || messages[inflator.err];
return inflator.result;
}
/**
* inflateRaw(data[, options]) -> Uint8Array|String
* - data (Uint8Array): input data to decompress.
* - options (Object): zlib inflate options.
*
* The same as [[inflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function inflateRaw(input, options) {
options = options || {};
options.raw = true;
return inflate$1(input, options);
}
/**
* ungzip(data[, options]) -> Uint8Array|String
* - data (Uint8Array): input data to decompress.
* - options (Object): zlib inflate options.
*
* Just shortcut to [[inflate]], because it autodetects format
* by header.content. Done for convenience.
**/
var Inflate_1 = Inflate;
var inflate_2$1 = inflate$1;
var inflateRaw_1 = inflateRaw;
var ungzip = inflate$1;
var constants$2 = constants;
var inflate_1$1 = {
Inflate: Inflate_1,
inflate: inflate_2$1,
inflateRaw: inflateRaw_1,
ungzip: ungzip,
constants: constants$2
};
var Deflate$1 = deflate_1$1.Deflate,
deflate$2 = deflate_1$1.deflate,
deflateRaw$1 = deflate_1$1.deflateRaw,
gzip$1 = deflate_1$1.gzip;
var Inflate$1 = inflate_1$1.Inflate,
inflate$2 = inflate_1$1.inflate,
inflateRaw$1 = inflate_1$1.inflateRaw,
ungzip$1 = inflate_1$1.ungzip;
var Deflate_1$1 = Deflate$1;
var deflate_1$2 = deflate$2;
var deflateRaw_1$1 = deflateRaw$1;
var gzip_1$1 = gzip$1;
var Inflate_1$1 = Inflate$1;
var inflate_1$2 = inflate$2;
var inflateRaw_1$1 = inflateRaw$1;
var ungzip_1 = ungzip$1;
var constants_1 = constants;
var pako = {
Deflate: Deflate_1$1,
deflate: deflate_1$2,
deflateRaw: deflateRaw_1$1,
gzip: gzip_1$1,
Inflate: Inflate_1$1,
inflate: inflate_1$2,
inflateRaw: inflateRaw_1$1,
ungzip: ungzip_1,
constants: constants_1
};
exports.Deflate = Deflate_1$1;
exports.Inflate = Inflate_1$1;
exports.constants = constants_1;
exports.default = pako;
exports.deflate = deflate_1$2;
exports.deflateRaw = deflateRaw_1$1;
exports.gzip = gzip_1$1;
exports.inflate = inflate_1$2;
exports.inflateRaw = inflateRaw_1$1;
exports.ungzip = ungzip_1;
Object.defineProperty(exports, '__esModule', { value: true });
})));
};
BundleModuleCode['plugins/image/UPGM']=function (module,exports,global,process){
function decode (text) {
var data,bpp,width,height,lines = (text instanceof Buffer?text.toString():text).split('\n');
if (/P2/.test(lines[0])) {
// ascii
var lindex=1;
if (/#/.test(lines[1])) lindex++;
var dims = lines[lindex++].split(' ');
width=Number(dims[0])
height=Number(dims[1])
var max = Number(lines[lindex++]);
if (max<256) { bpp=8; data=new Uint8Array(width*height) }
else if (max<32768) { bpp=16; data=new Int16Array(width*height) }
else if (max<65536) { bpp=16; data=new Uint16Array(width*height) }
else { bpp=32; data=new Int32Array(width*height) }
var offset=0;
for(var i=3;i s.length).reduce((a,b) => (a+b+1))+1,
buf = Buffer.from(text.slice(srcoff,text.length),'binary');
// console.log('pgm.decode, buf',buf.length,srcoff,text.length);
if (buf.length!=(data.length*bpp/8)) throw "pgm.decode: Buffer size mismatch";
for(var i=0;i0&&!Q[a-1]){a--}G.push({children:[],index:0});var C=G[0];for(n=0;n0){C=G.pop()}C.index++;G.push(C);while(G.length<=n){G.push(F={children:[],index:0});C.children[C.index]=F.children;C=F}f++}if(n+10){V--;return J>>V&1}J=Q[h++];if(J===255){var I=Q[h++];if(I){if(I===220&&d){h+=2;var l=Z(Q,h);h+=2;if(l>0&&l!==f.s){throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data",l)}}else if(I===217){if(d){var M=q*8;
if(M>0&&M>>7}function u(I){var l=I;while(!0){l=l[Y()];switch(typeof l){case"number":return l;case"object":continue}throw new W("invalid huffman sequence")}}function m(I){var e=0;while(I>0){e=e<<1|Y();I--}return e}function j(I){if(I===1){return Y()===1?1:-1}var e=m(I);if(e>=1<>4;if(i===0){if(A<15){break}N+=16;continue}N+=A;var o=p[N];X.D[I+o]=j(i);N++}}function $(X,I){var l=u(X.J),M=l===0?0:j(l)<0){r--;return}var N=E,l=a;while(N<=l){var M=u(X.i),S=M&15,i=M>>4;if(S===0){if(i<15){r=m(i)+(1<>4;if(S===0){if(M<15){r=m(M)+(1<0){for(O=0;O0?"unexpected":"excessive";h=k.offset}if(k.M>=65488&&k.M<=65495){h+=2}else{break}}return h-z}function al(Q,h,f){var G=Q.$,n=Q.D,E,a,C,F,d,T,U,z,J,V,Y,u,m,j,v,$,b;if(!G){throw new W("missing required Quantization Table.")}for(var r=0;r<64;r+=8){J=n[h+r];V=n[h+r+1];Y=n[h+r+2];u=n[h+r+3];m=n[h+r+4];j=n[h+r+5];v=n[h+r+6];$=n[h+r+7];J*=G[r];if((V|Y|u|m|j|v|$)===0){b=s*J+512>>10;f[r]=b;f[r+1]=b;f[r+2]=b;f[r+3]=b;f[r+4]=b;f[r+5]=b;f[r+6]=b;f[r+7]=b;continue}V*=G[r+1];Y*=G[r+2];u*=G[r+3];m*=G[r+4];j*=G[r+5];v*=G[r+6];$*=G[r+7];E=s*J+128>>8;a=s*m+128>>8;C=Y;F=v;d=ad*(V-$)+128>>8;z=ad*(V+$)+128>>8;
T=u<<4;U=j<<4;E=E+a+1>>1;a=E-a;b=C*ai+F*ar+128>>8;C=C*ar-F*ai+128>>8;F=b;d=d+U+1>>1;U=d-U;z=z+T+1>>1;T=z-T;E=E+F+1>>1;F=E-F;a=a+C+1>>1;C=a-C;b=d*ao+z*ah+2048>>12;d=d*ah-z*ao+2048>>12;z=b;b=T*ac+U*t+2048>>12;T=T*t-U*ac+2048>>12;U=b;f[r]=E+z;f[r+7]=E-z;f[r+1]=a+U;f[r+6]=a-U;f[r+2]=C+T;f[r+5]=C-T;f[r+3]=F+d;f[r+4]=F-d}for(var P=0;P<8;++P){J=f[P];V=f[P+8];Y=f[P+16];u=f[P+24];m=f[P+32];j=f[P+40];v=f[P+48];$=f[P+56];if((V|Y|u|m|j|v|$)===0){b=s*J+8192>>14;if(b<-2040){b=0}else if(b>=2024){b=255}else{b=b+2056>>4}n[h+P]=b;n[h+P+8]=b;n[h+P+16]=b;n[h+P+24]=b;n[h+P+32]=b;n[h+P+40]=b;n[h+P+48]=b;n[h+P+56]=b;continue}E=s*J+2048>>12;a=s*m+2048>>12;C=Y;F=v;d=ad*(V-$)+2048>>12;z=ad*(V+$)+2048>>12;T=u;U=j;E=(E+a+1>>1)+4112;a=E-a;b=C*ai+F*ar+2048>>12;C=C*ar-F*ai+2048>>12;F=b;d=d+U+1>>1;U=d-U;z=z+T+1>>1;T=z-T;E=E+F+1>>1;F=E-F;a=a+C+1>>1;C=a-C;b=d*ao+z*ah+2048>>12;d=d*ah-z*ao+2048>>12;z=b;
b=T*ac+U*t+2048>>12;T=T*t-U*ac+2048>>12;U=b;J=E+z;$=E-z;V=a+U;v=a-U;Y=C+T;j=C-T;u=F+d;m=F-d;if(J<16){J=0}else if(J>=4080){J=255}else{J>>=4}if(V<16){V=0}else if(V>=4080){V=255}else{V>>=4}if(Y<16){Y=0}else if(Y>=4080){Y=255}else{Y>>=4}if(u<16){u=0}else if(u>=4080){u=255}else{u>>=4}if(m<16){m=0}else if(m>=4080){m=255}else{m>>=4}if(j<16){j=0}else if(j>=4080){j=255}else{j>>=4}if(v<16){v=0}else if(v>=4080){v=255}else{v>>=4}if($<16){$=0}else if($>=4080){$=255}else{$>>=4}n[h+P]=J;
n[h+P+8]=V;n[h+P+16]=Y;n[h+P+24]=u;n[h+P+32]=m;n[h+P+40]=j;n[h+P+48]=v;n[h+P+56]=$}}function a0(Q,h){var f=h.P,G=h.c,n=new Int16Array(64);for(var E=0;E=G){return null}var E=Z(Q,h);if(E>=65472&&E<=65534){return{u:null,M:E,offset:h}}var a=Z(Q,n);while(!(a>=65472&&a<=65534)){if(++n>=G){return null}a=Z(Q,n)}return{u:E.toString(16),M:a,offset:n}}ak.prototype={parse(Q,h){if(h==null)h={};
var f=h.F,E=0,a=null,C=null,F,d,T=0;function G(){var o=Z(Q,E);E+=2;var B=E+o-2,V=an(Q,B,E);if(V&&V.u){B=V.offset}var ab=Q.subarray(E,B);E+=ab.length;return ab}function n(F){var o=Math.ceil(F.o/8/F.X),B=Math.ceil(F.s/8/F.B);for(var Y=0;Y>4===0){for(u=0;u<64;u++){b=p[u];P[b]=Q[E++]}}else if(r>>4===1){for(u=0;u<64;u++){b=p[u];P[b]=Z(Q,E);E+=2}}else{throw new W("DQT - invalid table spec")}U[r&15]=P}break;case 65472:case 65473:case 65474:if(F){throw new W("Only single frame JPEGs supported")}E+=2;F={};F.G=V===65473;F.Z=V===65474;F.precision=Q[E++];var D=Z(Q,E),a4,q=0,H=0;E+=2;F.s=f||D;F.o=Z(Q,E);E+=2;F.W=[];F._={};var a8=Q[E++];for(Y=0;Y>4,y=Q[E+1]&15;if(q>4===0?J:z)[_&15]=a5(N,K)}break;case 65501:E+=2;d=Z(Q,E);E+=2;break;case 65498:var x=++T===1&&!f,R;E+=2;var k=Q[E++],g=[];for(Y=0;Y>4];R.i=z[a6&15];g.push(R)}var I=Q[E++],l=Q[E++],M=Q[E++];try{var S=a7(Q,E,F,g,d,I,l,M>>4,M&15,x);E+=S}catch(ex){if(ex instanceof DNLMarkerError){return this.parse(Q,{F:ex.s})}else if(ex instanceof EOIMarkerError){break markerLoop}throw ex}break;case 65500:E+=4;break;case 65535:if(Q[E]!==255){E--}break;default:var i=an(Q,E-2,E-3);if(i&&i.u){E=i.offset;break}if(E>=Q.length-1){break markerLoop}throw new W("JpegImage.parse - unknown marker: "+V.toString(16))}V=Z(Q,E);E+=2}this.width=F.o;this.height=F.s;this.g=a;this.b=C;this.W=[];for(Y=0;Y>8)+P[J+1]}}}return v},get f(){if(this.b){return!!this.b.a}if(this.p===3){if(this.N===0){return!1}else if(this.W[0].index===82&&this.W[1].index===71&&this.W[2].index===66){return!1}return!0}if(this.N===1){return!0}return!1},z:function aj(Q){var h,f,G;
for(var n=0,E=Q.length;n4){throw new W("Unsupported color mode")}var E=this.Y(h,f,n);if(this.p===1&&G){var a=E.length,C=new Uint8ClampedArray(a*3),F=0;for(var d=0;d>24}function Z(p,t){return p[t]<<8|p[t+1]}function am(p,t){return(p[t]<<24|p[t+1]<<16|p[t+2]<<8|p[t+3])>>>0}UTIF.JpegDecoder=ak}());
//UTIF.JpegDecoder = PDFJS.JpegImage;
UTIF.encodeImage = function(rgba, w, h, metadata)
{
var idf = { "t256":[w], "t257":[h], "t258":[8,8,8,8], "t259":[1], "t262":[2], "t273":[1000], // strips offset
"t277":[4], "t278":[h], /* rows per strip */ "t279":[w*h*4], // strip byte counts
"t282":[[72,1]], "t283":[[72,1]], "t284":[1], "t286":[[0,1]], "t287":[[0,1]], "t296":[1], "t305": ["Photopea (UTIF.js)"], "t338":[1]
};
if (metadata) for (var i in metadata) idf[i] = metadata[i];
var prfx = new Uint8Array(UTIF.encode([idf]));
var img = new Uint8Array(rgba);
var data = new Uint8Array(1000+w*h*4);
for(var i=0; i probably not an image
img.isLE = id=="II";
img.width = img["t256"][0]; //delete img["t256"];
img.height = img["t257"][0]; //delete img["t257"];
var cmpr = img["t259"] ? img["t259"][0] : 1; //delete img["t259"];
var fo = img["t266"] ? img["t266"][0] : 1; //delete img["t266"];
if(img["t284"] && img["t284"][0]==2) log("PlanarConfiguration 2 should not be used!");
var bipp; // bits per pixel
if(img["t258"]) bipp = Math.min(32,img["t258"][0])*img["t258"].length;
else bipp = (img["t277"]?img["t277"][0]:1);
// Some .NEF files have t258==14, even though they use 16 bits per pixel
if(cmpr==1 && img["t279"]!=null && img["t278"] && img["t262"][0]==32803) {
bipp = Math.round((img["t279"][0]*8)/(img.width*img["t278"][0]));
}
var bipl = Math.ceil(img.width*bipp/8)*8;
var soff = img["t273"]; if(soff==null) soff = img["t324"];
var bcnt = img["t279"]; if(cmpr==1 && soff.length==1) bcnt = [img.height*(bipl>>>3)]; if(bcnt==null) bcnt = img["t325"];
//bcnt[0] = Math.min(bcnt[0], data.length); // Hasselblad, "RAW_HASSELBLAD_H3D39II.3FR"
var bytes = new Uint8Array(img.height*(bipl>>>3)), bilen = 0;
if(img["t322"]!=null) // tiled
{
var tw = img["t322"][0], th = img["t323"][0];
var tx = Math.floor((img.width + tw - 1) / tw);
var ty = Math.floor((img.height + th - 1) / th);
var tbuff = new Uint8Array(Math.ceil(tw*th*bipp/8)|0);
for(var y=0; y>>3, h = (img["t278"] ? img["t278"][0] : img.height), bpl = Math.ceil(bps*noc*img.width/8);
// convert to Little Endian /*
if(bps==16 && !img.isLE && img["t33422"]==null) // not DNG
for(var y=0; y>>8)&255;
}
else if(noc==3) for(var j= 3; j>>3]>>>7-(P&7)&1;B[1]++;return D}function aj(B,P){if(x==null){x={};
for(var D=0;D>>1}return B}function c(B,P){return B>>P}function N(B,P,D,U,X,y){P[D]=c(c(11*B[X]-4*B[X+y]+B[X+y+y]+4,3)+B[U],1);
P[D+y]=c(c(5*B[X]+4*B[X+y]-B[X+y+y]+4,3)-B[U],1)}function g(B,P,D,U,X,y){var n=B[X-y]-B[X+y],S=B[X],O=B[U];
P[D]=c(c(n+4,3)+S+O,1);P[D+y]=c(c(-n+4,3)+S-O,1)}function L(B,P,D,U,X,y){P[D]=c(c(5*B[X]+4*B[X-y]-B[X-y-y]+4,3)+B[U],1);
P[D+y]=c(c(11*B[X]-4*B[X-y]+B[X-y-y]+4,3)-B[U],1)}function t(B){B=B<0?0:B>4095?4095:B;B=H[B]>>>2;return B}function ab(B,P,D,U,X){U=new Uint16Array(U.buffer);
var y=Date.now(),n=UTIF._binBE,S=P+D,O,q,i,M,m,aA,T,a8,a0,am,au,a3,aw,ao,v,ax,p,k;P+=4;while(P>>1)*(i>>>1));k=new Int16Array((q>>>1)*(i>>>1));u=new Int16Array(1024);
for(var f=0;f<1024;f++){var aF=f-512,j=Math.abs(aF),O=Math.floor(768*j*j*j/(255*255*255))+j;u[f]=Math.sign(aF)*O}H=new Uint16Array(4096);
var al=(1<<16)-1;for(var f=0;f<4096;f++){var ad=f,az=al*(Math.pow(113,ad/4095)-1)/112;H[f]=Math.min(az,al)}}var Z=p[T],V=Q(q,1+d[M]),z=Q(i,1+d[M]);
if(M==0){for(var b=0;b>>1)+G]=B[w]<<8|B[w+1]}}else{var aC=[B,P*8],aq=[],a5=0,ae=V*z,I=[0,0],s=0,E=0;
while(a50){aq[a5++]=E;s--}}var $=(M-1)%3,aE=$!=1?V:0,as=$!=0?z:0;
for(var b=0;b>>1)+aE,aa=b*V;for(var G=0;G>>1,an=V*2,at=z*2;
for(var b=0;b>14-r*2&3;var af=a6[aD];if(af!=0)for(var b=0;b>>1)*(q>>>1)+(G>>>1),R=a2[w],ak=ar[w]-2048,aB=ah[w]-2048,av=a1[w]-2048,a4=(ak<<1)+R,a9=(aB<<1)+R,ap=R+av,ag=R-av;
U[J]=t(a4);U[J+1]=t(ap);U[J+q]=t(ag);U[J+q+1]=t(a9)}}P+=o*4}else if(C==16388){P+=o*4}else if(F==8192||F==8448||F==9216){}else throw C.toString(16)}}console.log(Date.now()-y)}return ab}()
UTIF.decode._ljpeg_diff = function(data, prm, huff) {
var getbithuff = UTIF.decode._getbithuff;
var len, diff;
len = getbithuff(data, prm, huff[0], huff);
diff = getbithuff(data, prm, len, 0);
if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1;
return diff;
}
UTIF.decode._decodeARW = function(img, inp, off, src_length, tgt, toff) {
var raw_width = img["t256"][0], height=img["t257"][0], tiff_bps=img["t258"][0];
var bin=(img.isLE ? UTIF._binLE : UTIF._binBE);
//console.log(raw_width, height, tiff_bps, raw_width*height, src_length);
var arw2 = (raw_width*height == src_length) || (raw_width*height*1.5 == src_length);
//arw2 = true;
//console.log("ARW2: ", arw2, raw_width*height, src_length, tgt.length);
if(!arw2) { //"sony_arw_load_raw"; // not arw2
height+=8;
var prm = [off,0,0,0];
var huff = new Uint16Array(32770);
var tab = [ 0xf11,0xf10,0xe0f,0xd0e,0xc0d,0xb0c,0xa0b,0x90a,0x809,
0x708,0x607,0x506,0x405,0x304,0x303,0x300,0x202,0x201 ];
var i, c, n, col, row, sum=0;
var ljpeg_diff = UTIF.decode._ljpeg_diff;
huff[0] = 15;
for (n=i=0; i < 18; i++) {
var lim = 32768 >>> (tab[i] >>> 8);
for(var c=0; c>>4); tgt[toff+i+1]=(b0<<4)|(b2>>>4); tgt[toff+i+2]=(b2<<4)|(b1>>>4); }
return;
}
var pix = new Uint16Array(16);
var row, col, val, max, min, imax, imin, sh, bit, i, dp;
var data = new Uint8Array(raw_width+1);
for (row=0; row < height; row++) {
//fread (data, 1, raw_width, ifp);
for(var j=0; j>> 11);
imax = 0x0f & (val >>> 22);
imin = 0x0f & (val >>> 26);
for (sh=0; sh < 4 && 0x80 << sh <= max-min; sh++);
for (bit=30, i=0; i < 16; i++)
if (i == imax) pix[i] = max;
else if (i == imin) pix[i] = min;
else {
pix[i] = ((bin.readUshort(data, dp+(bit >> 3)) >>> (bit & 7) & 0x7f) << sh) + min;
if (pix[i] > 0x7ff) pix[i] = 0x7ff;
bit += 7;
}
for (i=0; i < 16; i++, col+=2) {
//RAW(row,col) = curve[pix[i] << 1] >> 2;
var clr = pix[i]<<1; //clr = 0xffff;
UTIF.decode._putsF(tgt, (row*raw_width+col)*tiff_bps, clr<<(16-tiff_bps));
}
col -= col & 1 ? 1:31;
}
}
}
UTIF.decode._decodeNikon = function(img,imgs, data, off, src_length, tgt, toff)
{
var nikon_tree = [
[ 0, 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy */
5,4,3,6,2,7,1,0,8,9,11,10,12 ],
[ 0, 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy after split */
0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 ],
[ 0, 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, /* 12-bit lossless */
5,4,6,3,7,2,8,1,9,0,10,11,12 ],
[ 0, 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0, /* 14-bit lossy */
5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 ],
[ 0, 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0, /* 14-bit lossy after split */
8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 ],
[ 0, 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0, /* 14-bit lossless */
7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 ] ];
var raw_width = img["t256"][0], height=img["t257"][0], tiff_bps=img["t258"][0];
var tree = 0, split = 0;
var make_decoder = UTIF.decode._make_decoder;
var getbithuff = UTIF.decode._getbithuff;
var mn = imgs[0].exifIFD.makerNote, md = mn["t150"]?mn["t150"]:mn["t140"], mdo=0; //console.log(mn,md);
//console.log(md[0].toString(16), md[1].toString(16), tiff_bps);
var ver0 = md[mdo++], ver1 = md[mdo++];
if (ver0 == 0x49 || ver1 == 0x58) mdo+=2110;
if (ver0 == 0x46) tree = 2;
if (tiff_bps == 14) tree += 3;
var vpred = [[0,0],[0,0]], bin=(img.isLE ? UTIF._binLE : UTIF._binBE);
for(var i=0; i<2; i++) for(var j=0; j<2; j++) { vpred[i][j] = bin.readShort(md,mdo); mdo+=2; } // not sure here ... [i][j] or [j][i]
//console.log(vpred);
var max = 1 << tiff_bps & 0x7fff, step=0;
var csize = bin.readShort(md,mdo); mdo+=2;
if (csize > 1) step = Math.floor(max / (csize-1));
if (ver0 == 0x44 && ver1 == 0x20 && step > 0) split = bin.readShort(md,562);
var i;
var row, col;
var len, shl, diff;
var min_v = 0;
var hpred = [0,0];
var huff = make_decoder(nikon_tree[tree]);
//var g_input_offset=0, bitbuf=0, vbits=0, reset=0;
var prm = [off,0,0,0];
//console.log(split); split = 170;
for (min_v=row=0; row < height; row++) {
if (split && row == split) {
//free (huff);
huff = make_decoder (nikon_tree[tree+1]);
//max_v += (min_v = 16) << 1;
}
for (col=0; col < raw_width; col++) {
i = getbithuff(data,prm,huff[0],huff);
len = i & 15;
shl = i >>> 4;
diff = (((getbithuff(data,prm,len-shl,0) << 1) + 1) << shl) >>> 1;
if ((diff & (1 << (len-1))) == 0)
diff -= (1 << len) - (shl==0?1:0);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
var clr = Math.min(Math.max(hpred[col & 1],0),(1<>>3); dt[o]|=val>>>16; dt[o+1]|=val>>>8; dt[o+2]|=val; }
UTIF.decode._getbithuff = function(data,prm,nbits, huff) {
var zero_after_ff = 0;
var get_byte = UTIF.decode._get_byte;
var c;
var off=prm[0], bitbuf=prm[1], vbits=prm[2], reset=prm[3];
//if (nbits > 25) return 0;
//if (nbits < 0) return bitbuf = vbits = reset = 0;
if (nbits == 0 || vbits < 0) return 0;
while (!reset && vbits < nbits && (c = data[off++]) != -1 &&
!(reset = zero_after_ff && c == 0xff && data[off++])) {
//console.log("byte read into c");
bitbuf = (bitbuf << 8) + c;
vbits += 8;
}
c = (bitbuf << (32-vbits)) >>> (32-nbits);
if (huff) {
vbits -= huff[c+1] >>> 8; //console.log(c, huff[c]>>8);
c = huff[c+1]&255;
} else
vbits -= nbits;
if (vbits < 0) throw "e";
prm[0]=off; prm[1]=bitbuf; prm[2]=vbits; prm[3]=reset;
return c;
}
UTIF.decode._make_decoder = function(source) {
var max, len, h, i, j;
var huff = [];
for (max=16; max!=0 && !source[max]; max--);
var si=17;
huff[0] = max;
for (h=len=1; len <= max; len++)
for (i=0; i < source[len]; i++, ++si)
for (j=0; j < 1 << (max-len); j++)
if (h <= 1 << max)
huff[h++] = (len << 8) | source[si];
return huff;
}
UTIF.decode._decodeNewJPEG = function(img, data, off, len, tgt, toff)
{
len = Math.min(len, data.length-off);
var tables = img["t347"], tlen = tables ? tables.length : 0, buff = new Uint8Array(tlen + len);
if (tables) {
var SOI = 216, EOI = 217, boff = 0;
for (var i=0; i<(tlen-1); i++)
{
// Skip EOI marker from JPEGTables
if (tables[i]==255 && tables[i+1]==EOI) break;
buff[boff++] = tables[i];
}
// Skip SOI marker from data
var byte1 = data[off], byte2 = data[off + 1];
if (byte1!=255 || byte2!=SOI)
{
buff[boff++] = byte1;
buff[boff++] = byte2;
}
for (var i=2; i>>8); }
else for(var i=0; i>>8); tgt[toff+(i<<1)+1] = (out[i]&255); }
}
else if(bps==14 || bps==12) { // 4 * 14 == 56 == 7 * 8
var rst = 16-bps;
for(var i=0; i 1);
}
if(!isTiled)
{
if(data[off]==255 && data[off+1]==SOI) return { jpegOffset: off };
if(jpgIchgFmt!=null)
{
if(data[off+jifoff]==255 && data[off+jifoff+1]==SOI) joff = off+jifoff;
else log("JPEGInterchangeFormat does not point to SOI");
if(jpgIchgFmtLen==null) log("JPEGInterchangeFormatLength field is missing");
else if(jifoff >= soff || (jifoff+jiflen) <= soff) log("JPEGInterchangeFormatLength field value is invalid");
if(joff != null) return { jpegOffset: joff };
}
}
if(ycbcrss!=null) { ssx = ycbcrss[0]; ssy = ycbcrss[1]; }
if(jpgIchgFmt!=null)
if(jpgIchgFmtLen!=null)
if(jiflen >= 2 && (jifoff+jiflen) <= soff)
{
if(data[off+jifoff+jiflen-2]==255 && data[off+jifoff+jiflen-1]==SOI) tables = new Uint8Array(jiflen-2);
else tables = new Uint8Array(jiflen);
for(i=0; i offset to first strip or tile");
if(tables == null)
{
var ooff = 0, out = [];
out[ooff++] = 255; out[ooff++] = SOI;
var qtables = img["t519"];
if(qtables==null) throw new Error("JPEGQTables tag is missing");
for(i=0; i>> 8); out[ooff++] = nc & 255;
out[ooff++] = (i | (k << 4));
for(j=0; j<16; j++) out[ooff++] = data[off+htables[i]+j];
for(j=0; j>> 8) & 255; out[ooff++] = img.height & 255;
out[ooff++] = (img.width >>> 8) & 255; out[ooff++] = img.width & 255;
out[ooff++] = spp;
if(spp==1) { out[ooff++] = 1; out[ooff++] = 17; out[ooff++] = 0; }
else for(i=0; i<3; i++)
{
out[ooff++] = i + 1;
out[ooff++] = (i != 0) ? 17 : (((ssx & 15) << 4) | (ssy & 15));
out[ooff++] = i;
}
if(jpgresint!=null && jpgresint[0]!=0)
{
out[ooff++] = 255; out[ooff++] = DRI; out[ooff++] = 0; out[ooff++] = 4;
out[ooff++] = (jpgresint[0] >>> 8) & 255;
out[ooff++] = jpgresint[0] & 255;
}
tables = new Uint8Array(out);
}
var sofpos = -1;
i = 0;
while(i < (tables.length - 1)) {
if(tables[i]==255 && tables[i+1]==SOF0) { sofpos = i; break; }
i++;
}
if(sofpos == -1)
{
var tmptab = new Uint8Array(tables.length + 10 + 3*spp);
tmptab.set(tables);
var tmpoff = tables.length;
sofpos = tables.length;
tables = tmptab;
tables[tmpoff++] = 255; tables[tmpoff++] = SOF0;
tables[tmpoff++] = 0; tables[tmpoff++] = 8 + 3*spp; tables[tmpoff++] = 8;
tables[tmpoff++] = (img.height >>> 8) & 255; tables[tmpoff++] = img.height & 255;
tables[tmpoff++] = (img.width >>> 8) & 255; tables[tmpoff++] = img.width & 255;
tables[tmpoff++] = spp;
if(spp==1) { tables[tmpoff++] = 1; tables[tmpoff++] = 17; tables[tmpoff++] = 0; }
else for(i=0; i<3; i++)
{
tables[tmpoff++] = i + 1;
tables[tmpoff++] = (i != 0) ? 17 : (((ssx & 15) << 4) | (ssy & 15));
tables[tmpoff++] = i;
}
}
if(data[soff]==255 && data[soff+1]==SOS)
{
var soslen = (data[soff+2]<<8) | data[soff+3];
sosMarker = new Uint8Array(soslen+2);
sosMarker[0] = data[soff]; sosMarker[1] = data[soff+1]; sosMarker[2] = data[soff+2]; sosMarker[3] = data[soff+3];
for(i=0; i<(soslen-2); i++) sosMarker[i+4] = data[soff+i+4];
}
else
{
sosMarker = new Uint8Array(2 + 6 + 2*spp);
var sosoff = 0;
sosMarker[sosoff++] = 255; sosMarker[sosoff++] = SOS;
sosMarker[sosoff++] = 0; sosMarker[sosoff++] = 6 + 2*spp; sosMarker[sosoff++] = spp;
if(spp==1) { sosMarker[sosoff++] = 1; sosMarker[sosoff++] = 0; }
else for(i=0; i<3; i++)
{
sosMarker[sosoff++] = i+1; sosMarker[sosoff++] = (i << 4) | i;
}
sosMarker[sosoff++] = 0; sosMarker[sosoff++] = 63; sosMarker[sosoff++] = 0;
}
return { jpegOffset: off, tables: tables, sosMarker: sosMarker, sofPosition: sofpos };
}
UTIF.decode._decodeOldJPEG = function(img, data, off, len, tgt, toff)
{
var i, dlen, tlen, buff, buffoff;
var jpegData = UTIF.decode._decodeOldJPEGInit(img, data, off, len);
if(jpegData.jpegOffset!=null)
{
dlen = off+len-jpegData.jpegOffset;
buff = new Uint8Array(dlen);
for(i=0; i>> 8) & 255; buff[jpegData.sofPosition+6] = img.height & 255;
buff[jpegData.sofPosition+7] = (img.width >>> 8) & 255; buff[jpegData.sofPosition+8] = img.width & 255;
if(data[off]!=255 || data[off+1]!=SOS)
{
buff.set(jpegData.sosMarker, buffoff);
buffoff += sosMarker.length;
}
for(i=0; i=0 && n<128) for(var i=0; i< n+1; i++) { ta[toff]=sa[off]; toff++; off++; }
if(n>=-127 && n<0) { for(var i=0; i<-n+1; i++) { ta[toff]=sa[off]; toff++; } off++; }
}
}
UTIF.decode._decodeThunder = function(data, off, len, tgt, toff)
{
var d2 = [ 0, 1, 0, -1 ], d3 = [ 0, 1, 2, 3, 0, -3, -2, -1 ];
var lim = off+len, qoff = toff*2, px = 0;
while(off>>6), n = (b&63); off++;
if(msk==3) { px=(n&15); tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; }
if(msk==0) for(var i=0; i>>1] |= (px<<(4*(1-qoff&1))); qoff++; }
if(msk==2) for(var i=0; i<2; i++) { var d=(n>>>(3*(1-i)))&7; if(d!=4) { px+=d3[d]; tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; } }
if(msk==1) for(var i=0; i<3; i++) { var d=(n>>>(2*(2-i)))&3; if(d!=2) { px+=d2[d]; tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; } }
}
}
UTIF.decode._dmap = { "1":0,"011":1,"000011":2,"0000011":3, "010":-1,"000010":-2,"0000010":-3 };
UTIF.decode._lens = ( function()
{
var addKeys = function(lens, arr, i0, inc) { for(var i=0; i>>3)>>3]>>>(7-(boff&7)))&1;
if(fo==2) bit = (data[boff>>>3]>>>( (boff&7)))&1;
boff++; wrd+=bit;
if(mode=="H")
{
if(U._lens[clr][wrd]!=null)
{
var dl=U._lens[clr][wrd]; wrd=""; len+=dl;
if(dl<64) { U._addNtimes(line,len,clr); a0+=len; clr=1-clr; len=0; toRead--; if(toRead==0) mode=""; }
}
}
else
{
if(wrd=="0001") { wrd=""; U._addNtimes(line,b2-a0,clr); a0=b2; }
if(wrd=="001" ) { wrd=""; mode="H"; toRead=2; }
if(U._dmap[wrd]!=null) { a1 = b1+U._dmap[wrd]; U._addNtimes(line, a1-a0, clr); a0=a1; wrd=""; clr=1-clr; }
}
if(line.length==w && mode=="")
{
U._writeBits(line, tgt, toff*8+y*bipl);
clr=0; y++; a0=0;
pline=U._makeDiff(line); line=[];
}
//if(wrd.length>150) { log(wrd); break; throw "e"; }
}
}
UTIF.decode._findDiff = function(line, x, clr) { for(var i=0; i=x && line[i+1]==clr) return line[i]; }
UTIF.decode._makeDiff = function(line)
{
var out = []; if(line[0]==1) out.push(0,1);
for(var i=1; i>>3)>>3]>>>(7-(boff&7)))&1;
if(fo==2) bit = (data[boff>>>3]>>>( (boff&7)))&1;
boff++; wrd+=bit;
if(is1D)
{
if(U._lens[clr][wrd]!=null)
{
var dl=U._lens[clr][wrd]; wrd=""; len+=dl;
if(dl<64) { U._addNtimes(line,len,clr); clr=1-clr; len=0; }
}
}
else
{
if(mode=="H")
{
if(U._lens[clr][wrd]!=null)
{
var dl=U._lens[clr][wrd]; wrd=""; len+=dl;
if(dl<64) { U._addNtimes(line,len,clr); a0+=len; clr=1-clr; len=0; toRead--; if(toRead==0) mode=""; }
}
}
else
{
if(wrd=="0001") { wrd=""; U._addNtimes(line,b2-a0,clr); a0=b2; }
if(wrd=="001" ) { wrd=""; mode="H"; toRead=2; }
if(U._dmap[wrd]!=null) { a1 = b1+U._dmap[wrd]; U._addNtimes(line, a1-a0, clr); a0=a1; wrd=""; clr=1-clr; }
}
}
if(wrd.endsWith("000000000001")) // needed for some files
{
if(y>=0) U._writeBits(line, tgt, toff*8+y*bipl);
if(twoDim) {
if(fo==1) is1D = ((data[boff>>>3]>>>(7-(boff&7)))&1)==1;
if(fo==2) is1D = ((data[boff>>>3]>>>( (boff&7)))&1)==1;
boff++;
}
//log("EOL",y, "next 1D:", is1D);
wrd=""; clr=0; y++; a0=0;
pline=U._makeDiff(line); line=[];
}
}
if(line.length==w) U._writeBits(line, tgt, toff*8+y*bipl);
}
UTIF.decode._addNtimes = function(arr, n, val) { for(var i=0; i>>3] |= (bits[i]<<(7-((boff+i)&7)));
}
UTIF.decode._decodeLZW=UTIF.decode._decodeLZW=function(){var e,U,Z,u,K=0,V=0,g=0,N=0,O=function(){var S=e>>>3,A=U[S]<<16|U[S+1]<<8|U[S+2],j=A>>>24-(e&7)-V&(1<>>----------------");
for(var i=0; i4) { bin.writeUint(data, offset, eoff); toff=eoff; }
if (type== 1 || type==7) { for(var i=0; i4) { dlen += (dlen&1); eoff += dlen; }
offset += 4;
}
return [offset, eoff];
}
UTIF.toRGBA8 = function(out, scl)
{
var w = out.width, h = out.height, area = w*h, qarea = area*4, data = out.data;
var img = new Uint8Array(area*4);
//console.log(out);
// 0: WhiteIsZero, 1: BlackIsZero, 2: RGB, 3: Palette color, 4: Transparency mask, 5: CMYK
var intp = (out["t262"] ? out["t262"][0]: 2), bps = (out["t258"]?Math.min(32,out["t258"][0]):1);
if(out["t262"]==null && bps==1) intp=0;
//log("interpretation: ", intp, "bps", bps, out);
if(false) {}
else if(intp==0)
{
var bpl = Math.ceil(bps*w/8);
for(var y=0; y>3)])>>(7- (i&7)))& 1; img[qi]=img[qi+1]=img[qi+2]=( 1-px)*255; img[qi+3]=255; }
if(bps== 4) for(var i=0; i>1)])>>(4-4*(i&1)))&15; img[qi]=img[qi+1]=img[qi+2]=(15-px)* 17; img[qi+3]=255; }
if(bps== 8) for(var i=0; i>3)])>>(7- (i&7)))&1; img[qi]=img[qi+1]=img[qi+2]=(px)*255; img[qi+3]=255; }
if(bps== 2) for(var i=0; i>2)])>>(6-2*(i&3)))&3; img[qi]=img[qi+1]=img[qi+2]=(px)* 85; img[qi+3]=255; }
if(bps== 8) for(var i=0; i>>3)]>>>(7-(x&7)))&1;
else if(bps==4) mi=(data[dof+(x>>>1)]>>>(4-4*(x&1)))&15;
else if(bps==8) mi= data[dof+x*smpls];
else throw bps;
img[qi]=(map[mi]>>8); img[qi+1]=(map[cn+mi]>>8); img[qi+2]=(map[cn+cn+mi]>>8); img[qi+3]=255;
}
}
else if(intp==5)
{
var smpls = out["t258"]?out["t258"].length : 4;
var gotAlpha = smpls>4 ? 1 : 0;
for(var i=0; i>>1);
var Y = data[si+(j&1)], Cb=data[si+2]-128, Cr=data[si+3]-128;
var r = Y + ( (Cr >> 2) + (Cr >> 3) + (Cr >> 5) ) ;
var g = Y - ( (Cb >> 2) + (Cb >> 4) + (Cb >> 5)) - ( (Cr >> 1) + (Cr >> 3) + (Cr >> 4) + (Cr >> 5)) ;
var b = Y + ( Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6)) ;
img[qi ]=Math.max(0,Math.min(255,r));
img[qi+1]=Math.max(0,Math.min(255,g));
img[qi+2]=Math.max(0,Math.min(255,b));
img[qi+3]=255;
}
}
}
else log("Unknown Photometric interpretation: "+intp);
return img;
}
function RGBAtoRGB(r, g, b, a, r2,g2,b2){
a=a/255;
var r3 = Math.round(((1 - a) * r2) + (a * r))
var g3 = Math.round(((1 - a) * g2) + (a * g))
var b3 = Math.round(((1 - a) * b2) + (a * b))
return {r:r3,g:g3,b:b3}
}
function RGB2GRAY(rgb){
return Math.round((rgb.r+rgb.g+rgb.b)/3);
}
// w/o alpha channel
UTIF.toRGB8 = function(out, scl)
{
////////////////////
// Requires RGBAtoRGB!
////////////////////
var w = out.width, h = out.height, area = w*h, qarea = area*4, data = out.data;
var img = new Uint8Array(area*3);
//console.log(out);
// 0: WhiteIsZero, 1: BlackIsZero, 2: RGB, 3: Palette color, 4: Transparency mask, 5: CMYK
var intp = (out["t262"] ? out["t262"][0]: 2), bps = (out["t258"]?Math.min(32,out["t258"][0]):1);
if(out["t262"]==null && bps==1) intp=0;
//log("interpretation: ", intp, "bps", bps, out);
if(false) {}
else if(intp==0)
{
var bpl = Math.ceil(bps*w/8);
for(var y=0; y>3)])>>(7- (i&7)))& 1;
img[qi]=img[qi+1]=img[qi+2]=( 1-px)*255;
// img[qi+3]=255;
}
if(bps== 4) for(var i=0; i>1)])>>(4-4*(i&1)))&15;
img[qi]=img[qi+1]=img[qi+2]=(15-px)* 17;
// img[qi+3]=255;
}
if(bps== 8) for(var i=0; i>3)])>>(7- (i&7)))&1;
img[qi]=img[qi+1]=img[qi+2]=(px)*255;
// img[qi+3]=255;
}
if(bps== 2) for(var i=0; i>2)])>>(6-2*(i&3)))&3;
img[qi]=img[qi+1]=img[qi+2]=(px)* 85;
// img[qi+3]=255;
}
if(bps== 8) for(var i=0; i>>3)]>>>(7-(x&7)))&1;
else if(bps==4) mi=(data[dof+(x>>>1)]>>>(4-4*(x&1)))&15;
else if(bps==8) mi= data[dof+x*smpls];
else throw bps;
img[qi]=(map[mi]>>8); img[qi+1]=(map[cn+mi]>>8); img[qi+2]=(map[cn+cn+mi]>>8);
// img[qi+3]=255;
}
}
else if(intp==5)
{
var smpls = out["t258"]?out["t258"].length : 4;
var gotAlpha = smpls>4 ? 1 : 0;
for(var i=0; i>>1);
var Y = data[si+(j&1)], Cb=data[si+2]-128, Cr=data[si+3]-128;
var r = Y + ( (Cr >> 2) + (Cr >> 3) + (Cr >> 5) ) ;
var g = Y - ( (Cb >> 2) + (Cb >> 4) + (Cb >> 5)) - ( (Cr >> 1) + (Cr >> 3) + (Cr >> 4) + (Cr >> 5)) ;
var b = Y + ( Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6)) ;
img[qi ]=Math.max(0,Math.min(255,r));
img[qi+1]=Math.max(0,Math.min(255,g));
img[qi+2]=Math.max(0,Math.min(255,b));
// img[qi+3]=255;
}
}
}
else log("Unknown Photometric interpretation: "+intp);
return img;
}
// Returns gray-level transformed image
UTIF.toGRAY8 = function(out, scl)
{
////////////////////
// Requires RGBAtoRGB!
////////////////////
var w = out.width, h = out.height, area = w*h, qarea = area*4, data = out.data;
var img = new Uint8Array(area);
//console.log(out);
// 0: WhiteIsZero, 1: BlackIsZero, 2: RGB, 3: Palette color, 4: Transparency mask, 5: CMYK
var intp = (out["t262"] ? out["t262"][0]: 2), bps = (out["t258"]?Math.min(32,out["t258"][0]):1);
if(out["t262"]==null && bps==1) intp=0;
//log("interpretation: ", intp, "bps", bps, out);
if(false) {}
else if(intp==0)
{
var bpl = Math.ceil(bps*w/8);
for(var y=0; y>3)])>>(7- (i&7)))& 1;
img[qi]=( 1-px)*255;
}
if(bps== 4) for(var i=0; i>1)])>>(4-4*(i&1)))&15;
img[qi]=(15-px)* 17;
}
if(bps== 8) for(var i=0; i>3)])>>(7- (i&7)))&1;
img[qi]=(px)*255;
}
if(bps== 2) for(var i=0; i>2)])>>(6-2*(i&3)))&3;
img[qi]=(px)* 85;
}
if(bps== 8) for(var i=0; i>>3)]>>>(7-(x&7)))&1;
else if(bps==4) mi=(data[dof+(x>>>1)]>>>(4-4*(x&1)))&15;
else if(bps==8) mi= data[dof+x*smpls];
else throw bps;
img[qi]=RGB2GRAY({r:(map[mi]>>8),g:(map[cn+mi]>>8),b:(map[cn+cn+mi]>>8)});
}
}
else if(intp==5)
{
var smpls = out["t258"]?out["t258"].length : 4;
var gotAlpha = smpls>4 ? 1 : 0;
for(var i=0; i>>1);
var Y = data[si+(j&1)], Cb=data[si+2]-128, Cr=data[si+3]-128;
var r = Y + ( (Cr >> 2) + (Cr >> 3) + (Cr >> 5) ) ;
var g = Y - ( (Cb >> 2) + (Cb >> 4) + (Cb >> 5)) - ( (Cr >> 1) + (Cr >> 3) + (Cr >> 4) + (Cr >> 5)) ;
var b = Y + ( Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6)) ;
img[qi ]=RGB2GRAY({
r:Math.max(0,Math.min(255,r)),
g:Math.max(0,Math.min(255,g)),
b:Math.max(0,Math.min(255,b))
});
// img[qi+3]=255;
}
}
}
else log("Unknown Photometric interpretation: "+intp);
return img;
}
UTIF.replaceIMG = function(imgs)
{
if(imgs==null) imgs = document.getElementsByTagName("img");
var sufs = ["tif","tiff","dng","cr2","nef"]
for (var i=0; ima) { ma=ar; page=img; }
}
UTIF.decodeImage(buff, page, ifds);
var rgba = UTIF.toRGBA8(page), w=page.width, h=page.height;
var ind = UTIF._xhrs.indexOf(e.target), img = UTIF._imgs[ind];
UTIF._xhrs.splice(ind,1); UTIF._imgs.splice(ind,1);
var cnv = document.createElement("canvas"); cnv.width=w; cnv.height=h;
var ctx = cnv.getContext("2d");
var imgd = new ImageData(new Uint8ClampedArray(rgba.buffer),w,h);
/*imgd = ctx.createImageData(w,h);
for(var i=0; i> 8)&255; buff[p+1] = n&255; },
writeInt : function(buff, p, n) { var a=UTIF._binBE.ui8; UTIF._binBE.i32[0]=n; buff[p+3]=a[0]; buff[p+2]=a[1]; buff[p+1]=a[2]; buff[p+0]=a[3]; },
writeUint : function(buff, p, n) { buff[p] = (n>>24)&255; buff[p+1] = (n>>16)&255; buff[p+2] = (n>>8)&255; buff[p+3] = (n>>0)&255; },
writeASCII : function(buff, p, s) { for(var i = 0; i < s.length; i++) buff[p+i] = s.charCodeAt(i); },
writeDouble: function(buff, p, n)
{
UTIF._binBE.fl64[0] = n;
for (var i = 0; i < 8; i++) buff[p + i] = UTIF._binBE.ui8[7 - i];
}
}
UTIF._binBE.ui8 = new Uint8Array (8);
UTIF._binBE.i16 = new Int16Array (UTIF._binBE.ui8.buffer);
UTIF._binBE.i32 = new Int32Array (UTIF._binBE.ui8.buffer);
UTIF._binBE.ui32 = new Uint32Array (UTIF._binBE.ui8.buffer);
UTIF._binBE.fl32 = new Float32Array(UTIF._binBE.ui8.buffer);
UTIF._binBE.fl64 = new Float64Array(UTIF._binBE.ui8.buffer);
UTIF._binLE =
{
nextZero : UTIF._binBE.nextZero,
readUshort : function(buff, p) { return (buff[p+1]<< 8) | buff[p]; },
readShort : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+0]; a[1]=buff[p+1]; return UTIF._binBE. i16[0]; },
readInt : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+0]; a[1]=buff[p+1]; a[2]=buff[p+2]; a[3]=buff[p+3]; return UTIF._binBE. i32[0]; },
readUint : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+0]; a[1]=buff[p+1]; a[2]=buff[p+2]; a[3]=buff[p+3]; return UTIF._binBE.ui32[0]; },
readASCII : UTIF._binBE.readASCII,
readFloat : function(buff, p) { var a=UTIF._binBE.ui8; for(var i=0;i<4;i++) a[i]=buff[p+ i]; return UTIF._binBE.fl32[0]; },
readDouble : function(buff, p) { var a=UTIF._binBE.ui8; for(var i=0;i<8;i++) a[i]=buff[p+ i]; return UTIF._binBE.fl64[0]; },
writeUshort: function(buff, p, n) { buff[p] = (n)&255; buff[p+1] = (n>>8)&255; },
writeInt : function(buff, p, n) { var a=UTIF._binBE.ui8; UTIF._binBE.i32[0]=n; buff[p+0]=a[0]; buff[p+1]=a[1]; buff[p+2]=a[2]; buff[p+3]=a[3]; },
writeUint : function(buff, p, n) { buff[p] = (n>>>0)&255; buff[p+1] = (n>>>8)&255; buff[p+2] = (n>>>16)&255; buff[p+3] = (n>>>24)&255; },
writeASCII : UTIF._binBE.writeASCII
}
UTIF._copyTile = function(tb, tw, th, b, w, h, xoff, yoff)
{
//log("copyTile", tw, th, w, h, xoff, yoff);
var xlim = Math.min(tw, w-xoff);
var ylim = Math.min(th, h-yoff);
for(var y=0; y>--g&1;
F=r[F+x]}j[k]=F}}function t(w,r,p,k){if(w[r+3]!=255)return 0;if(p==0)return r;for(var B=0;B<2;B++){if(w[r+B]==0){w[r+B]=w.length;
w.push(0,0,k,255)}var G=t(w,w[r+B],p-1,k+1);if(G!=0)return G}return 0}function H(w){var r=w.a,p=w.d;
while(r<25&&w.c>>8;p=p<<8|k;r+=8}w.a=r;w.d=p}function b(w,r){if(r.a>(r.a-=w)&65535>>16-w}function c(w,r){var p=w[0],k=0,B=255,G=0;if(r.a<16)H(r);var D=r.d>>r.a-8&255;
k=w[1][D];B=p[k+3];r.a-=p[k+2];while(B==255){G=r.d>>--r.a&1;k=p[k+G];B=p[k+3]}return B}function d(w,r){if(w<32768>>16-r)w+=-(1<>>1);else if(G==7)y=y+w[x-r]>>>1;
else throw G;w[x]=y+h(D[j],p)}}n+=r}}function J(w,r){var p=b(w,r);return w==16?-32768:d(p,w)}function e(w,r,p){var k=I.length-C;
for(var B=0;B>>4]}E=i();C+=2;break}else{C+=p-2}}var n=o>8?Uint16Array:Uint8Array,F=a*z,x=new n(m*F),y={a:0,d:0,b:E==8,c:C,data:I,e:I.length};
if(y.b)e(x,F,y);else f(x,F,y);return x}return l}()
})(UTIF, pako);
})();
};
BundleModuleCode['plugins/image/UJPG']=function (module,exports,global,process){
/*
JPEG decoder
https://raw.githubusercontent.com/jpeg-js/jpeg-js/
https://github.com/jpeg-js/jpeg-js
*/
/* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
Copyright 2011 notmasteryet
Licensed 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.
*/
// - The JPEG specification can be found in the ITU CCITT Recommendation T.81
// (www.w3.org/Graphics/JPEG/itu-t81.pdf)
// - The JFIF specification can be found in the JPEG File Interchange Format
// (www.w3.org/Graphics/JPEG/jfif3.pdf)
// - The Adobe Application-Specific JPEG markers in the Supporting the DCT Filters
// in PostScript Level 2, Technical Note #5116
// (partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf)
function _UJPEGinit (module) {
/* Es2016->ES2015 polyfill ... */
function CA(arrays) {
var m=[];
for(var i=0;i 0 && !codeLengths[length - 1])
length--;
code.push({children: [], index: 0});
var p = code[0], q;
for (i = 0; i < length; i++) {
for (j = 0; j < codeLengths[i]; j++) {
p = code.pop();
p.children[p.index] = values[k];
while (p.index > 0) {
if (code.length === 0)
throw new Error('Could not recreate Huffman Table');
p = code.pop();
}
p.index++;
code.push(p);
while (code.length <= i) {
code.push(q = {children: [], index: 0});
p.children[p.index] = q.children;
p = q;
}
k++;
}
if (i + 1 < length) {
// p here points to last code
code.push(q = {children: [], index: 0});
p.children[p.index] = q.children;
p = q;
}
}
return code[0].children;
}
function decodeScan(data, offset,
frame, components, resetInterval,
spectralStart, spectralEnd,
successivePrev, successive, opts) {
var precision = frame.precision;
var samplesPerLine = frame.samplesPerLine;
var scanLines = frame.scanLines;
var mcusPerLine = frame.mcusPerLine;
var progressive = frame.progressive;
var maxH = frame.maxH, maxV = frame.maxV;
var startOffset = offset, bitsData = 0, bitsCount = 0;
function readBit() {
if (bitsCount > 0) {
bitsCount--;
return (bitsData >> bitsCount) & 1;
}
bitsData = data[offset++];
if (bitsData == 0xFF) {
var nextByte = data[offset++];
if (nextByte) {
throw new Error("unexpected marker: " + ((bitsData << 8) | nextByte).toString(16));
}
// unstuff 0
}
bitsCount = 7;
return bitsData >>> 7;
}
function decodeHuffman(tree) {
var node = tree, bit;
while ((bit = readBit()) !== null) {
node = node[bit];
if (typeof node === 'number')
return node;
if (typeof node !== 'object')
throw new Error("invalid huffman sequence");
}
return null;
}
function receive(length) {
var n = 0;
while (length > 0) {
var bit = readBit();
if (bit === null) return;
n = (n << 1) | bit;
length--;
}
return n;
}
function receiveAndExtend(length) {
var n = receive(length);
if (n >= 1 << (length - 1))
return n;
return n + (-1 << length) + 1;
}
function decodeBaseline(component, zz) {
var t = decodeHuffman(component.huffmanTableDC);
var diff = t === 0 ? 0 : receiveAndExtend(t);
zz[0]= (component.pred += diff);
var k = 1;
while (k < 64) {
var rs = decodeHuffman(component.huffmanTableAC);
var s = rs & 15, r = rs >> 4;
if (s === 0) {
if (r < 15)
break;
k += 16;
continue;
}
k += r;
var z = dctZigZag[k];
zz[z] = receiveAndExtend(s);
k++;
}
}
function decodeDCFirst(component, zz) {
var t = decodeHuffman(component.huffmanTableDC);
var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);
zz[0] = (component.pred += diff);
}
function decodeDCSuccessive(component, zz) {
zz[0] |= readBit() << successive;
}
var eobrun = 0;
function decodeACFirst(component, zz) {
if (eobrun > 0) {
eobrun--;
return;
}
var k = spectralStart, e = spectralEnd;
while (k <= e) {
var rs = decodeHuffman(component.huffmanTableAC);
var s = rs & 15, r = rs >> 4;
if (s === 0) {
if (r < 15) {
eobrun = receive(r) + (1 << r) - 1;
break;
}
k += 16;
continue;
}
k += r;
var z = dctZigZag[k];
zz[z] = receiveAndExtend(s) * (1 << successive);
k++;
}
}
var successiveACState = 0, successiveACNextValue;
function decodeACSuccessive(component, zz) {
var k = spectralStart, e = spectralEnd, r = 0;
while (k <= e) {
var z = dctZigZag[k];
var direction = zz[z] < 0 ? -1 : 1;
switch (successiveACState) {
case 0: // initial state
var rs = decodeHuffman(component.huffmanTableAC);
var s = rs & 15, r = rs >> 4;
if (s === 0) {
if (r < 15) {
eobrun = receive(r) + (1 << r);
successiveACState = 4;
} else {
r = 16;
successiveACState = 1;
}
} else {
if (s !== 1)
throw new Error("invalid ACn encoding");
successiveACNextValue = receiveAndExtend(s);
successiveACState = r ? 2 : 3;
}
continue;
case 1: // skipping r zero items
case 2:
if (zz[z])
zz[z] += (readBit() << successive) * direction;
else {
r--;
if (r === 0)
successiveACState = successiveACState == 2 ? 3 : 0;
}
break;
case 3: // set value for a zero item
if (zz[z])
zz[z] += (readBit() << successive) * direction;
else {
zz[z] = successiveACNextValue << successive;
successiveACState = 0;
}
break;
case 4: // eob
if (zz[z])
zz[z] += (readBit() << successive) * direction;
break;
}
k++;
}
if (successiveACState === 4) {
eobrun--;
if (eobrun === 0)
successiveACState = 0;
}
}
function decodeMcu(component, decode, mcu, row, col) {
var mcuRow = (mcu / mcusPerLine) | 0;
var mcuCol = mcu % mcusPerLine;
var blockRow = mcuRow * component.v + row;
var blockCol = mcuCol * component.h + col;
// If the block is missing and we're in tolerant mode, just skip it.
if (component.blocks[blockRow] === undefined && opts.tolerantDecoding)
return;
decode(component, component.blocks[blockRow][blockCol]);
}
function decodeBlock(component, decode, mcu) {
var blockRow = (mcu / component.blocksPerLine) | 0;
var blockCol = mcu % component.blocksPerLine;
// If the block is missing and we're in tolerant mode, just skip it.
if (component.blocks[blockRow] === undefined && opts.tolerantDecoding)
return;
decode(component, component.blocks[blockRow][blockCol]);
}
var componentsLength = components.length;
var component, i, j, k, n;
var decodeFn;
if (progressive) {
if (spectralStart === 0)
decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;
else
decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;
} else {
decodeFn = decodeBaseline;
}
var mcu = 0, marker;
var mcuExpected;
if (componentsLength == 1) {
mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;
} else {
mcuExpected = mcusPerLine * frame.mcusPerColumn;
}
if (!resetInterval) resetInterval = mcuExpected;
var h, v;
while (mcu < mcuExpected) {
// reset interval stuff
for (i = 0; i < componentsLength; i++)
components[i].pred = 0;
eobrun = 0;
if (componentsLength == 1) {
component = components[0];
for (n = 0; n < resetInterval; n++) {
decodeBlock(component, decodeFn, mcu);
mcu++;
}
} else {
for (n = 0; n < resetInterval; n++) {
for (i = 0; i < componentsLength; i++) {
component = components[i];
h = component.h;
v = component.v;
for (j = 0; j < v; j++) {
for (k = 0; k < h; k++) {
decodeMcu(component, decodeFn, mcu, j, k);
}
}
}
mcu++;
// If we've reached our expected MCU's, stop decoding
if (mcu === mcuExpected) break;
}
}
if (mcu === mcuExpected) {
// Skip trailing bytes at the end of the scan - until we reach the next marker
do {
if (data[offset] === 0xFF) {
if (data[offset + 1] !== 0x00) {
break;
}
}
offset += 1;
} while (offset < data.length - 2);
}
// find marker
bitsCount = 0;
marker = (data[offset] << 8) | data[offset + 1];
if (marker < 0xFF00) {
throw new Error("marker was not found");
}
if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx
offset += 2;
}
else
break;
}
return offset - startOffset;
}
function buildComponentData(frame, component) {
var lines = [];
var blocksPerLine = component.blocksPerLine;
var blocksPerColumn = component.blocksPerColumn;
var samplesPerLine = blocksPerLine << 3;
// Only 1 used per invocation of this function and garbage collected after invocation, so no need to account for its memory footprint.
var R = new Int32Array(64), r = new Uint8Array(64);
// A port of poppler's IDCT method which in turn is taken from:
// Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,
// "Practical Fast 1-D DCT Algorithms with 11 Multiplications",
// IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,
// 988-991.
function quantizeAndInverse(zz, dataOut, dataIn) {
var qt = component.quantizationTable;
var v0, v1, v2, v3, v4, v5, v6, v7, t;
var p = dataIn;
var i;
// dequant
for (i = 0; i < 64; i++)
p[i] = zz[i] * qt[i];
// inverse DCT on rows
for (i = 0; i < 8; ++i) {
var row = 8 * i;
// check for all-zero AC coefficients
if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 &&
p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 &&
p[7 + row] == 0) {
t = (dctSqrt2 * p[0 + row] + 512) >> 10;
p[0 + row] = t;
p[1 + row] = t;
p[2 + row] = t;
p[3 + row] = t;
p[4 + row] = t;
p[5 + row] = t;
p[6 + row] = t;
p[7 + row] = t;
continue;
}
// stage 4
v0 = (dctSqrt2 * p[0 + row] + 128) >> 8;
v1 = (dctSqrt2 * p[4 + row] + 128) >> 8;
v2 = p[2 + row];
v3 = p[6 + row];
v4 = (dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128) >> 8;
v7 = (dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128) >> 8;
v5 = p[3 + row] << 4;
v6 = p[5 + row] << 4;
// stage 3
t = (v0 - v1+ 1) >> 1;
v0 = (v0 + v1 + 1) >> 1;
v1 = t;
t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;
v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;
v3 = t;
t = (v4 - v6 + 1) >> 1;
v4 = (v4 + v6 + 1) >> 1;
v6 = t;
t = (v7 + v5 + 1) >> 1;
v5 = (v7 - v5 + 1) >> 1;
v7 = t;
// stage 2
t = (v0 - v3 + 1) >> 1;
v0 = (v0 + v3 + 1) >> 1;
v3 = t;
t = (v1 - v2 + 1) >> 1;
v1 = (v1 + v2 + 1) >> 1;
v2 = t;
t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
v7 = t;
t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
v6 = t;
// stage 1
p[0 + row] = v0 + v7;
p[7 + row] = v0 - v7;
p[1 + row] = v1 + v6;
p[6 + row] = v1 - v6;
p[2 + row] = v2 + v5;
p[5 + row] = v2 - v5;
p[3 + row] = v3 + v4;
p[4 + row] = v3 - v4;
}
// inverse DCT on columns
for (i = 0; i < 8; ++i) {
var col = i;
// check for all-zero AC coefficients
if (p[1*8 + col] == 0 && p[2*8 + col] == 0 && p[3*8 + col] == 0 &&
p[4*8 + col] == 0 && p[5*8 + col] == 0 && p[6*8 + col] == 0 &&
p[7*8 + col] == 0) {
t = (dctSqrt2 * dataIn[i+0] + 8192) >> 14;
p[0*8 + col] = t;
p[1*8 + col] = t;
p[2*8 + col] = t;
p[3*8 + col] = t;
p[4*8 + col] = t;
p[5*8 + col] = t;
p[6*8 + col] = t;
p[7*8 + col] = t;
continue;
}
// stage 4
v0 = (dctSqrt2 * p[0*8 + col] + 2048) >> 12;
v1 = (dctSqrt2 * p[4*8 + col] + 2048) >> 12;
v2 = p[2*8 + col];
v3 = p[6*8 + col];
v4 = (dctSqrt1d2 * (p[1*8 + col] - p[7*8 + col]) + 2048) >> 12;
v7 = (dctSqrt1d2 * (p[1*8 + col] + p[7*8 + col]) + 2048) >> 12;
v5 = p[3*8 + col];
v6 = p[5*8 + col];
// stage 3
t = (v0 - v1 + 1) >> 1;
v0 = (v0 + v1 + 1) >> 1;
v1 = t;
t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;
v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;
v3 = t;
t = (v4 - v6 + 1) >> 1;
v4 = (v4 + v6 + 1) >> 1;
v6 = t;
t = (v7 + v5 + 1) >> 1;
v5 = (v7 - v5 + 1) >> 1;
v7 = t;
// stage 2
t = (v0 - v3 + 1) >> 1;
v0 = (v0 + v3 + 1) >> 1;
v3 = t;
t = (v1 - v2 + 1) >> 1;
v1 = (v1 + v2 + 1) >> 1;
v2 = t;
t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
v7 = t;
t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
v6 = t;
// stage 1
p[0*8 + col] = v0 + v7;
p[7*8 + col] = v0 - v7;
p[1*8 + col] = v1 + v6;
p[6*8 + col] = v1 - v6;
p[2*8 + col] = v2 + v5;
p[5*8 + col] = v2 - v5;
p[3*8 + col] = v3 + v4;
p[4*8 + col] = v3 - v4;
}
// convert to 8-bit integers
for (i = 0; i < 64; ++i) {
var sample = 128 + ((p[i] + 8) >> 4);
dataOut[i] = sample < 0 ? 0 : sample > 0xFF ? 0xFF : sample;
}
}
requestMemoryAllocation(samplesPerLine * blocksPerColumn * 8);
var i, j;
for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {
var scanLine = blockRow << 3;
for (i = 0; i < 8; i++)
lines.push(new Uint8Array(samplesPerLine));
for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {
quantizeAndInverse(component.blocks[blockRow][blockCol], r, R);
var offset = 0, sample = blockCol << 3;
for (j = 0; j < 8; j++) {
var line = lines[scanLine + j];
for (i = 0; i < 8; i++)
line[sample + i] = r[offset++];
}
}
}
return lines;
}
function clampTo8bit(a) {
return a < 0 ? 0 : a > 255 ? 255 : a;
}
constructor.prototype = {
load: function load(path) {
var xhr = new XMLHttpRequest();
xhr.open("GET", path, true);
xhr.responseType = "arraybuffer";
xhr.onload = (function() {
// TODO catch parse error
var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);
this.parse(data);
if (this.onload)
this.onload();
}).bind(this);
xhr.send(null);
},
parse: function parse(data) {
var maxResolutionInPixels = this.opts.maxResolutionInMP * 1000 * 1000;
var offset = 0, length = data.length;
function readUint16() {
var value = (data[offset] << 8) | data[offset + 1];
offset += 2;
return value;
}
function readDataBlock() {
var length = readUint16();
var array = data.subarray(offset, offset + length - 2);
offset += array.length;
return array;
}
function prepareComponents(frame) {
// According to the JPEG standard, the sampling factor must be between 1 and 4
// See https://github.com/libjpeg-turbo/libjpeg-turbo/blob/9abeff46d87bd201a952e276f3e4339556a403a3/libjpeg.txt#L1138-L1146
var maxH = 1, maxV = 1;
var component, componentId;
for (componentId in frame.components) {
if (frame.components.hasOwnProperty(componentId)) {
component = frame.components[componentId];
if (maxH < component.h) maxH = component.h;
if (maxV < component.v) maxV = component.v;
}
}
var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH);
var mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV);
for (componentId in frame.components) {
if (frame.components.hasOwnProperty(componentId)) {
component = frame.components[componentId];
var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH);
var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV);
var blocksPerLineForMcu = mcusPerLine * component.h;
var blocksPerColumnForMcu = mcusPerColumn * component.v;
var blocksToAllocate = blocksPerColumnForMcu * blocksPerLineForMcu;
var blocks = [];
// Each block is a Int32Array of length 64 (4 x 64 = 256 bytes)
requestMemoryAllocation(blocksToAllocate * 256);
for (var i = 0; i < blocksPerColumnForMcu; i++) {
var row = [];
for (var j = 0; j < blocksPerLineForMcu; j++)
row.push(new Int32Array(64));
blocks.push(row);
}
component.blocksPerLine = blocksPerLine;
component.blocksPerColumn = blocksPerColumn;
component.blocks = blocks;
}
}
frame.maxH = maxH;
frame.maxV = maxV;
frame.mcusPerLine = mcusPerLine;
frame.mcusPerColumn = mcusPerColumn;
}
var jfif = null;
var adobe = null;
var pixels = null;
var frame, resetInterval;
var quantizationTables = [], frames = [];
var huffmanTablesAC = [], huffmanTablesDC = [];
var fileMarker = readUint16();
var malformedDataOffset = -1;
this.comments = [];
if (fileMarker != 0xFFD8) { // SOI (Start of Image)
throw new Error("SOI not found");
}
fileMarker = readUint16();
while (fileMarker != 0xFFD9) { // EOI (End of image)
var i, j, l;
switch(fileMarker) {
case 0xFF00: break;
case 0xFFE0: // APP0 (Application Specific)
case 0xFFE1: // APP1
case 0xFFE2: // APP2
case 0xFFE3: // APP3
case 0xFFE4: // APP4
case 0xFFE5: // APP5
case 0xFFE6: // APP6
case 0xFFE7: // APP7
case 0xFFE8: // APP8
case 0xFFE9: // APP9
case 0xFFEA: // APP10
case 0xFFEB: // APP11
case 0xFFEC: // APP12
case 0xFFED: // APP13
case 0xFFEE: // APP14
case 0xFFEF: // APP15
case 0xFFFE: // COM (Comment)
var appData = readDataBlock();
if (fileMarker === 0xFFFE) {
var comment = String.fromCharCode.apply(null, appData);
this.comments.push(comment);
}
if (fileMarker === 0xFFE0) {
if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49 &&
appData[3] === 0x46 && appData[4] === 0) { // 'JFIF\x00'
jfif = {
version: { major: appData[5], minor: appData[6] },
densityUnits: appData[7],
xDensity: (appData[8] << 8) | appData[9],
yDensity: (appData[10] << 8) | appData[11],
thumbWidth: appData[12],
thumbHeight: appData[13],
thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13])
};
}
}
// TODO APP1 - Exif
if (fileMarker === 0xFFE1) {
if (appData[0] === 0x45 &&
appData[1] === 0x78 &&
appData[2] === 0x69 &&
appData[3] === 0x66 &&
appData[4] === 0) { // 'EXIF\x00'
this.exifBuffer = appData.subarray(5, appData.length);
}
}
if (fileMarker === 0xFFEE) {
if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F &&
appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\x00'
adobe = {
version: appData[6],
flags0: (appData[7] << 8) | appData[8],
flags1: (appData[9] << 8) | appData[10],
transformCode: appData[11]
};
}
}
break;
case 0xFFDB: // DQT (Define Quantization Tables)
var quantizationTablesLength = readUint16();
var quantizationTablesEnd = quantizationTablesLength + offset - 2;
while (offset < quantizationTablesEnd) {
var quantizationTableSpec = data[offset++];
requestMemoryAllocation(64 * 4);
var tableData = new Int32Array(64);
if ((quantizationTableSpec >> 4) === 0) { // 8 bit values
for (j = 0; j < 64; j++) {
var z = dctZigZag[j];
tableData[z] = data[offset++];
}
} else if ((quantizationTableSpec >> 4) === 1) { //16 bit
for (j = 0; j < 64; j++) {
var z = dctZigZag[j];
tableData[z] = readUint16();
}
} else
throw new Error("DQT: invalid table spec");
quantizationTables[quantizationTableSpec & 15] = tableData;
}
break;
case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)
case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)
case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT)
readUint16(); // skip data length
frame = {};
frame.extended = (fileMarker === 0xFFC1);
frame.progressive = (fileMarker === 0xFFC2);
frame.precision = data[offset++];
frame.scanLines = readUint16();
frame.samplesPerLine = readUint16();
frame.components = {};
frame.componentsOrder = [];
var pixelsInFrame = frame.scanLines * frame.samplesPerLine;
if (pixelsInFrame > maxResolutionInPixels) {
var exceededAmount = Math.ceil((pixelsInFrame - maxResolutionInPixels) / 1e6);
throw new Error(`maxResolutionInMP limit exceeded by ${exceededAmount}MP`);
}
var componentsCount = data[offset++], componentId;
var maxH = 0, maxV = 0;
for (i = 0; i < componentsCount; i++) {
componentId = data[offset];
var h = data[offset + 1] >> 4;
var v = data[offset + 1] & 15;
var qId = data[offset + 2];
if ( h <= 0 || v <= 0 ) {
throw new Error('Invalid sampling factor, expected values above 0');
}
frame.componentsOrder.push(componentId);
frame.components[componentId] = {
h: h,
v: v,
quantizationIdx: qId
};
offset += 3;
}
prepareComponents(frame);
frames.push(frame);
break;
case 0xFFC4: // DHT (Define Huffman Tables)
var huffmanLength = readUint16();
for (i = 2; i < huffmanLength;) {
var huffmanTableSpec = data[offset++];
var codeLengths = new Uint8Array(16);
var codeLengthSum = 0;
for (j = 0; j < 16; j++, offset++) {
codeLengthSum += (codeLengths[j] = data[offset]);
}
requestMemoryAllocation(16 + codeLengthSum);
var huffmanValues = new Uint8Array(codeLengthSum);
for (j = 0; j < codeLengthSum; j++, offset++)
huffmanValues[j] = data[offset];
i += 17 + codeLengthSum;
((huffmanTableSpec >> 4) === 0 ?
huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] =
buildHuffmanTable(codeLengths, huffmanValues);
}
break;
case 0xFFDD: // DRI (Define Restart Interval)
readUint16(); // skip data length
resetInterval = readUint16();
break;
case 0xFFDC: // Number of Lines marker
readUint16() // skip data length
readUint16() // Ignore this data since it represents the image height
break;
case 0xFFDA: // SOS (Start of Scan)
var scanLength = readUint16();
var selectorsCount = data[offset++];
var components = [], component;
for (i = 0; i < selectorsCount; i++) {
component = frame.components[data[offset++]];
var tableSpec = data[offset++];
component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];
component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];
components.push(component);
}
var spectralStart = data[offset++];
var spectralEnd = data[offset++];
var successiveApproximation = data[offset++];
var processed = decodeScan(data, offset,
frame, components, resetInterval,
spectralStart, spectralEnd,
successiveApproximation >> 4, successiveApproximation & 15, this.opts);
offset += processed;
break;
case 0xFFFF: // Fill bytes
if (data[offset] !== 0xFF) { // Avoid skipping a valid marker.
offset--;
}
break;
default:
if (data[offset - 3] == 0xFF &&
data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {
// could be incorrect encoding -- last 0xFF byte of the previous
// block was eaten by the encoder
offset -= 3;
break;
}
else if (fileMarker === 0xE0 || fileMarker == 0xE1) {
// Recover from malformed APP1 markers popular in some phone models.
// See https://github.com/eugeneware/jpeg-js/issues/82
if (malformedDataOffset !== -1) {
throw new Error(`first unknown JPEG marker at offset ${malformedDataOffset.toString(16)}, second unknown JPEG marker ${fileMarker.toString(16)} at offset ${(offset - 1).toString(16)}`);
}
malformedDataOffset = offset - 1;
const nextOffset = readUint16();
if (data[offset + nextOffset - 2] === 0xFF) {
offset += nextOffset - 2;
break;
}
}
throw new Error("unknown JPEG marker " + fileMarker.toString(16));
}
fileMarker = readUint16();
}
if (frames.length != 1)
throw new Error("only single frame JPEGs supported");
// set each frame's components quantization table
for (var i = 0; i < frames.length; i++) {
var cp = frames[i].components;
for (var j in cp) {
cp[j].quantizationTable = quantizationTables[cp[j].quantizationIdx];
delete cp[j].quantizationIdx;
}
}
this.width = frame.samplesPerLine;
this.height = frame.scanLines;
this.jfif = jfif;
this.adobe = adobe;
this.components = [];
for (var i = 0; i < frame.componentsOrder.length; i++) {
var component = frame.components[frame.componentsOrder[i]];
this.components.push({
lines: buildComponentData(frame, component),
scaleX: component.h / frame.maxH,
scaleY: component.v / frame.maxV
});
}
},
getData: function getData(width, height) {
var scaleX = this.width / width, scaleY = this.height / height;
var component1, component2, component3, component4;
var component1Line, component2Line, component3Line, component4Line;
var x, y;
var offset = 0;
var Y, Cb, Cr, K, C, M, Ye, R, G, B;
var colorTransform;
var dataLength = width * height * this.components.length;
requestMemoryAllocation(dataLength);
var data = new Uint8Array(dataLength);
switch (this.components.length) {
case 1:
component1 = this.components[0];
for (y = 0; y < height; y++) {
component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];
for (x = 0; x < width; x++) {
Y = component1Line[0 | (x * component1.scaleX * scaleX)];
data[offset++] = Y;
}
}
break;
case 2:
// PDF might compress two component data in custom colorspace
component1 = this.components[0];
component2 = this.components[1];
for (y = 0; y < height; y++) {
component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];
component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];
for (x = 0; x < width; x++) {
Y = component1Line[0 | (x * component1.scaleX * scaleX)];
data[offset++] = Y;
Y = component2Line[0 | (x * component2.scaleX * scaleX)];
data[offset++] = Y;
}
}
break;
case 3:
// The default transform for three components is true
colorTransform = true;
// The adobe transform marker overrides any previous setting
if (this.adobe && this.adobe.transformCode)
colorTransform = true;
else if (typeof this.opts.colorTransform !== 'undefined')
colorTransform = !!this.opts.colorTransform;
component1 = this.components[0];
component2 = this.components[1];
component3 = this.components[2];
for (y = 0; y < height; y++) {
component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];
component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];
component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)];
for (x = 0; x < width; x++) {
if (!colorTransform) {
R = component1Line[0 | (x * component1.scaleX * scaleX)];
G = component2Line[0 | (x * component2.scaleX * scaleX)];
B = component3Line[0 | (x * component3.scaleX * scaleX)];
} else {
Y = component1Line[0 | (x * component1.scaleX * scaleX)];
Cb = component2Line[0 | (x * component2.scaleX * scaleX)];
Cr = component3Line[0 | (x * component3.scaleX * scaleX)];
R = clampTo8bit(Y + 1.402 * (Cr - 128));
G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));
B = clampTo8bit(Y + 1.772 * (Cb - 128));
}
data[offset++] = R;
data[offset++] = G;
data[offset++] = B;
}
}
break;
case 4:
if (!this.adobe)
throw new Error('Unsupported color mode (4 components)');
// The default transform for four components is false
colorTransform = false;
// The adobe transform marker overrides any previous setting
if (this.adobe && this.adobe.transformCode)
colorTransform = true;
else if (typeof this.opts.colorTransform !== 'undefined')
colorTransform = !!this.opts.colorTransform;
component1 = this.components[0];
component2 = this.components[1];
component3 = this.components[2];
component4 = this.components[3];
for (y = 0; y < height; y++) {
component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];
component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];
component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)];
component4Line = component4.lines[0 | (y * component4.scaleY * scaleY)];
for (x = 0; x < width; x++) {
if (!colorTransform) {
C = component1Line[0 | (x * component1.scaleX * scaleX)];
M = component2Line[0 | (x * component2.scaleX * scaleX)];
Ye = component3Line[0 | (x * component3.scaleX * scaleX)];
K = component4Line[0 | (x * component4.scaleX * scaleX)];
} else {
Y = component1Line[0 | (x * component1.scaleX * scaleX)];
Cb = component2Line[0 | (x * component2.scaleX * scaleX)];
Cr = component3Line[0 | (x * component3.scaleX * scaleX)];
K = component4Line[0 | (x * component4.scaleX * scaleX)];
C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128));
M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));
Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128));
}
data[offset++] = 255-C;
data[offset++] = 255-M;
data[offset++] = 255-Ye;
data[offset++] = 255-K;
}
}
break;
default:
throw new Error('Unsupported color mode');
}
return data;
},
copyToImageData: function copyToImageData(imageData, formatAsRGBA) {
var width = imageData.width, height = imageData.height;
var imageDataArray = imageData.data;
var data = this.getData(width, height);
var i = 0, j = 0, x, y;
var Y, K, C, M, R, G, B;
switch (this.components.length) {
case 1:
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
Y = data[i++];
imageDataArray[j++] = Y;
imageDataArray[j++] = Y;
imageDataArray[j++] = Y;
if (formatAsRGBA) {
imageDataArray[j++] = 255;
}
}
}
break;
case 3:
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
R = data[i++];
G = data[i++];
B = data[i++];
imageDataArray[j++] = R;
imageDataArray[j++] = G;
imageDataArray[j++] = B;
if (formatAsRGBA) {
imageDataArray[j++] = 255;
}
}
}
break;
case 4:
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
C = data[i++];
M = data[i++];
Y = data[i++];
K = data[i++];
R = 255 - clampTo8bit(C * (1 - K / 255) + K);
G = 255 - clampTo8bit(M * (1 - K / 255) + K);
B = 255 - clampTo8bit(Y * (1 - K / 255) + K);
imageDataArray[j++] = R;
imageDataArray[j++] = G;
imageDataArray[j++] = B;
if (formatAsRGBA) {
imageDataArray[j++] = 255;
}
}
}
break;
default:
throw new Error('Unsupported color mode');
}
}
};
// We cap the amount of memory used by jpeg-js to avoid unexpected OOMs from untrusted content.
var totalBytesAllocated = 0;
var maxMemoryUsageBytes = 0;
function requestMemoryAllocation(increaseAmount = 0) {
var totalMemoryImpactBytes = totalBytesAllocated + increaseAmount;
if (totalMemoryImpactBytes > maxMemoryUsageBytes) {
var exceededAmount = Math.ceil((totalMemoryImpactBytes - maxMemoryUsageBytes) / 1024 / 1024);
throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${exceededAmount}MB`);
}
totalBytesAllocated = totalMemoryImpactBytes;
}
constructor.resetMaxMemoryUsage = function (maxMemoryUsageBytes_) {
totalBytesAllocated = 0;
maxMemoryUsageBytes = maxMemoryUsageBytes_;
};
constructor.getBytesAllocated = function () {
return totalBytesAllocated;
};
constructor.requestMemoryAllocation = requestMemoryAllocation;
return constructor;
})();
if (typeof module !== 'undefined') {
module.exports = decode;
} else if (typeof window !== 'undefined') {
window['jpeg-js'] = window['jpeg-js'] || {};
window['jpeg-js'].decode = decode;
}
function decode(jpegData, userOpts = {}) {
var defaultOpts = {
// "undefined" means "Choose whether to transform colors based on the image’s color model."
colorTransform: undefined,
useTArray: false,
formatAsRGBA: true,
tolerantDecoding: true,
maxResolutionInMP: 100, // Don't decode more than 100 megapixels
maxMemoryUsageInMB: 512, // Don't decode if memory footprint is more than 512MB
};
//var opts = { ...defaultOpts,
// ...userOpts
//};
var opts = CO([defaultOpts,userOpts]);
// var opts = {...defaultOpts, ...userOpts};
var arr = new Uint8Array(jpegData);
var decoder = new JpegImage();
decoder.opts = opts;
// If this constructor ever supports async decoding this will need to be done differently.
// Until then, treating as singleton limit is fine.
JpegImage.resetMaxMemoryUsage(opts.maxMemoryUsageInMB * 1024 * 1024);
decoder.parse(arr);
var channels = (opts.formatAsRGBA) ? 4 : 3;
var bytesNeeded = decoder.width * decoder.height * channels;
try {
JpegImage.requestMemoryAllocation(bytesNeeded);
var image = {
width: decoder.width,
height: decoder.height,
exifBuffer: decoder.exifBuffer,
data: opts.useTArray ?
new Uint8Array(bytesNeeded) :
Buffer.alloc(bytesNeeded)
};
if(decoder.comments.length > 0) {
image["comments"] = decoder.comments;
}
} catch (err) {
if (err instanceof RangeError) {
throw new Error("Could not allocate enough memory for the image. " +
"Required: " + bytesNeeded);
}
if (err instanceof ReferenceError) {
if (err.message === "Buffer is not defined") {
throw new Error("Buffer is not globally defined in this environment. " +
"Consider setting useTArray to true");
}
}
throw err;
}
decoder.copyToImageData(image, opts.formatAsRGBA);
return image;
}
/*
JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009
Basic GUI blocking jpeg encoder
*/
var btoa = btoa || function(buf) {
return Buffer.from(buf).toString('base64');
};
function JPEGEncoder(quality) {
var self = this;
var fround = Math.round;
var ffloor = Math.floor;
var YTable = new Array(64);
var UVTable = new Array(64);
var fdtbl_Y = new Array(64);
var fdtbl_UV = new Array(64);
var YDC_HT;
var UVDC_HT;
var YAC_HT;
var UVAC_HT;
var bitcode = new Array(65535);
var category = new Array(65535);
var outputfDCTQuant = new Array(64);
var DU = new Array(64);
var byteout = [];
var bytenew = 0;
var bytepos = 7;
var YDU = new Array(64);
var UDU = new Array(64);
var VDU = new Array(64);
var clt = new Array(256);
var RGB_YUV_TABLE = new Array(2048);
var currentQuality;
var ZigZag = [
0, 1, 5, 6,14,15,27,28,
2, 4, 7,13,16,26,29,42,
3, 8,12,17,25,30,41,43,
9,11,18,24,31,40,44,53,
10,19,23,32,39,45,52,54,
20,22,33,38,46,51,55,60,
21,34,37,47,50,56,59,61,
35,36,48,49,57,58,62,63
];
var std_dc_luminance_nrcodes = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];
var std_dc_luminance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
var std_ac_luminance_nrcodes = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d];
var std_ac_luminance_values = [
0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,
0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,
0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,
0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,
0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,
0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,
0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,
0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,
0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,
0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,
0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,
0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,
0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,
0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa
];
var std_dc_chrominance_nrcodes = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];
var std_dc_chrominance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
var std_ac_chrominance_nrcodes = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77];
var std_ac_chrominance_values = [
0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,
0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,
0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,
0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,
0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,
0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,
0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,
0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,
0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,
0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,
0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,
0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,
0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa
];
function initQuantTables(sf){
var YQT = [
16, 11, 10, 16, 24, 40, 51, 61,
12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56,
14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68,109,103, 77,
24, 35, 55, 64, 81,104,113, 92,
49, 64, 78, 87,103,121,120,101,
72, 92, 95, 98,112,100,103, 99
];
for (var i = 0; i < 64; i++) {
var t = ffloor((YQT[i]*sf+50)/100);
if (t < 1) {
t = 1;
} else if (t > 255) {
t = 255;
}
YTable[ZigZag[i]] = t;
}
var UVQT = [
17, 18, 24, 47, 99, 99, 99, 99,
18, 21, 26, 66, 99, 99, 99, 99,
24, 26, 56, 99, 99, 99, 99, 99,
47, 66, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99
];
for (var j = 0; j < 64; j++) {
var u = ffloor((UVQT[j]*sf+50)/100);
if (u < 1) {
u = 1;
} else if (u > 255) {
u = 255;
}
UVTable[ZigZag[j]] = u;
}
var aasf = [
1.0, 1.387039845, 1.306562965, 1.175875602,
1.0, 0.785694958, 0.541196100, 0.275899379
];
var k = 0;
for (var row = 0; row < 8; row++)
{
for (var col = 0; col < 8; col++)
{
fdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
fdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
k++;
}
}
}
function computeHuffmanTbl(nrcodes, std_table){
var codevalue = 0;
var pos_in_table = 0;
var HT = new Array();
for (var k = 1; k <= 16; k++) {
for (var j = 1; j <= nrcodes[k]; j++) {
HT[std_table[pos_in_table]] = [];
HT[std_table[pos_in_table]][0] = codevalue;
HT[std_table[pos_in_table]][1] = k;
pos_in_table++;
codevalue++;
}
codevalue*=2;
}
return HT;
}
function initHuffmanTbl()
{
YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);
UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);
YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);
UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);
}
function initCategoryNumber()
{
var nrlower = 1;
var nrupper = 2;
for (var cat = 1; cat <= 15; cat++) {
//Positive numbers
for (var nr = nrlower; nr>0] = 38470 * i;
RGB_YUV_TABLE[(i+ 512)>>0] = 7471 * i + 0x8000;
RGB_YUV_TABLE[(i+ 768)>>0] = -11059 * i;
RGB_YUV_TABLE[(i+1024)>>0] = -21709 * i;
RGB_YUV_TABLE[(i+1280)>>0] = 32768 * i + 0x807FFF;
RGB_YUV_TABLE[(i+1536)>>0] = -27439 * i;
RGB_YUV_TABLE[(i+1792)>>0] = - 5329 * i;
}
}
// IO functions
function writeBits(bs)
{
var value = bs[0];
var posval = bs[1]-1;
while ( posval >= 0 ) {
if (value & (1 << posval) ) {
bytenew |= (1 << bytepos);
}
posval--;
bytepos--;
if (bytepos < 0) {
if (bytenew == 0xFF) {
writeByte(0xFF);
writeByte(0);
}
else {
writeByte(bytenew);
}
bytepos=7;
bytenew=0;
}
}
}
function writeByte(value)
{
//byteout.push(clt[value]); // write char directly instead of converting later
byteout.push(value);
}
function writeWord(value)
{
writeByte((value>>8)&0xFF);
writeByte((value )&0xFF);
}
// DCT & quantization core
function fDCTQuant(data, fdtbl)
{
var d0, d1, d2, d3, d4, d5, d6, d7;
/* Pass 1: process rows. */
var dataOff=0;
var i;
var I8 = 8;
var I64 = 64;
for (i=0; i 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0);
//outputfDCTQuant[i] = fround(fDCTQuant);
}
return outputfDCTQuant;
}
function writeAPP0()
{
writeWord(0xFFE0); // marker
writeWord(16); // length
writeByte(0x4A); // J
writeByte(0x46); // F
writeByte(0x49); // I
writeByte(0x46); // F
writeByte(0); // = "JFIF",'\0'
writeByte(1); // versionhi
writeByte(1); // versionlo
writeByte(0); // xyunits
writeWord(1); // xdensity
writeWord(1); // ydensity
writeByte(0); // thumbnwidth
writeByte(0); // thumbnheight
}
function writeAPP1(exifBuffer) {
if (!exifBuffer) return;
writeWord(0xFFE1); // APP1 marker
if (exifBuffer[0] === 0x45 &&
exifBuffer[1] === 0x78 &&
exifBuffer[2] === 0x69 &&
exifBuffer[3] === 0x66) {
// Buffer already starts with EXIF, just use it directly
writeWord(exifBuffer.length + 2); // length is buffer + length itself!
} else {
// Buffer doesn't start with EXIF, write it for them
writeWord(exifBuffer.length + 5 + 2); // length is buffer + EXIF\0 + length itself!
writeByte(0x45); // E
writeByte(0x78); // X
writeByte(0x69); // I
writeByte(0x66); // F
writeByte(0); // = "EXIF",'\0'
}
for (var i = 0; i < exifBuffer.length; i++) {
writeByte(exifBuffer[i]);
}
}
function writeSOF0(width, height)
{
writeWord(0xFFC0); // marker
writeWord(17); // length, truecolor YUV JPG
writeByte(8); // precision
writeWord(height);
writeWord(width);
writeByte(3); // nrofcomponents
writeByte(1); // IdY
writeByte(0x11); // HVY
writeByte(0); // QTY
writeByte(2); // IdU
writeByte(0x11); // HVU
writeByte(1); // QTU
writeByte(3); // IdV
writeByte(0x11); // HVV
writeByte(1); // QTV
}
function writeDQT()
{
writeWord(0xFFDB); // marker
writeWord(132); // length
writeByte(0);
for (var i=0; i<64; i++) {
writeByte(YTable[i]);
}
writeByte(1);
for (var j=0; j<64; j++) {
writeByte(UVTable[j]);
}
}
function writeDHT()
{
writeWord(0xFFC4); // marker
writeWord(0x01A2); // length
writeByte(0); // HTYDCinfo
for (var i=0; i<16; i++) {
writeByte(std_dc_luminance_nrcodes[i+1]);
}
for (var j=0; j<=11; j++) {
writeByte(std_dc_luminance_values[j]);
}
writeByte(0x10); // HTYACinfo
for (var k=0; k<16; k++) {
writeByte(std_ac_luminance_nrcodes[k+1]);
}
for (var l=0; l<=161; l++) {
writeByte(std_ac_luminance_values[l]);
}
writeByte(1); // HTUDCinfo
for (var m=0; m<16; m++) {
writeByte(std_dc_chrominance_nrcodes[m+1]);
}
for (var n=0; n<=11; n++) {
writeByte(std_dc_chrominance_values[n]);
}
writeByte(0x11); // HTUACinfo
for (var o=0; o<16; o++) {
writeByte(std_ac_chrominance_nrcodes[o+1]);
}
for (var p=0; p<=161; p++) {
writeByte(std_ac_chrominance_values[p]);
}
}
function writeCOM(comments)
{
if (typeof comments === "undefined" || comments.constructor !== Array) return;
comments.forEach(e => {
if (typeof e !== "string") return;
writeWord(0xFFFE); // marker
var l = e.length;
writeWord(l + 2); // length itself as well
var i;
for (i = 0; i < l; i++)
writeByte(e.charCodeAt(i));
});
}
function writeSOS()
{
writeWord(0xFFDA); // marker
writeWord(12); // length
writeByte(3); // nrofcomponents
writeByte(1); // IdY
writeByte(0); // HTY
writeByte(2); // IdU
writeByte(0x11); // HTU
writeByte(3); // IdV
writeByte(0x11); // HTV
writeByte(0); // Ss
writeByte(0x3f); // Se
writeByte(0); // Bf
}
function processDU(CDU, fdtbl, DC, HTDC, HTAC){
var EOB = HTAC[0x00];
var M16zeroes = HTAC[0xF0];
var pos;
var I16 = 16;
var I63 = 63;
var I64 = 64;
var DU_DCT = fDCTQuant(CDU, fdtbl);
//ZigZag reorder
for (var j=0;j0)&&(DU[end0pos]==0); end0pos--) {};
//end0pos = first element in reverse order !=0
if ( end0pos == 0) {
writeBits(EOB);
return DC;
}
var i = 1;
var lng;
while ( i <= end0pos ) {
var startpos = i;
for (; (DU[i]==0) && (i<=end0pos); ++i) {}
var nrzeroes = i-startpos;
if ( nrzeroes >= I16 ) {
lng = nrzeroes>>4;
for (var nrmarker=1; nrmarker <= lng; ++nrmarker)
writeBits(M16zeroes);
nrzeroes = nrzeroes&0xF;
}
pos = 32767+DU[i];
writeBits(HTAC[(nrzeroes<<4)+category[pos]]);
writeBits(bitcode[pos]);
i++;
}
if ( end0pos != I63 ) {
writeBits(EOB);
}
return DC;
}
function initCharLookupTable(){
var sfcc = String.fromCharCode;
for(var i=0; i < 256; i++){ ///// ACHTUNG // 255
clt[i] = sfcc(i);
}
}
this.encode = function(image,quality) // image data object
{
var time_start = new Date().getTime();
if(quality) setQuality(quality);
// Initialize bit writer
byteout = new Array();
bytenew=0;
bytepos=7;
// Add JPEG headers
writeWord(0xFFD8); // SOI
writeAPP0();
writeCOM(image.comments);
writeAPP1(image.exifBuffer);
writeDQT();
writeSOF0(image.width,image.height);
writeDHT();
writeSOS();
// Encode 8x8 macroblocks
var DCY=0;
var DCU=0;
var DCV=0;
bytenew=0;
bytepos=7;
this.encode.displayName = "_encode_";
var imageData = image.data;
var width = image.width;
var height = image.height;
var quadWidth = width*4;
var tripleWidth = width*3;
var x, y = 0;
var r, g, b;
var start,p, col,row,pos;
while(y < height){
x = 0;
while(x < quadWidth){
start = quadWidth * y + x;
p = start;
col = -1;
row = 0;
for(pos=0; pos < 64; pos++){
row = pos >> 3;// /8
col = ( pos & 7 ) * 4; // %8
p = start + ( row * quadWidth ) + col;
if(y+row >= height){ // padding bottom
p-= (quadWidth*(y+1+row-height));
}
if(x+col >= quadWidth){ // padding right
p-= ((x+col) - quadWidth +4)
}
r = imageData[ p++ ];
g = imageData[ p++ ];
b = imageData[ p++ ];
/* // calculate YUV values dynamically
YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80
UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));
VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));
*/
// use lookup table (slightly faster)
YDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256)>>0] + RGB_YUV_TABLE[(b + 512)>>0]) >> 16)-128;
UDU[pos] = ((RGB_YUV_TABLE[(r + 768)>>0] + RGB_YUV_TABLE[(g + 1024)>>0] + RGB_YUV_TABLE[(b + 1280)>>0]) >> 16)-128;
VDU[pos] = ((RGB_YUV_TABLE[(r + 1280)>>0] + RGB_YUV_TABLE[(g + 1536)>>0] + RGB_YUV_TABLE[(b + 1792)>>0]) >> 16)-128;
}
DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
x+=32;
}
y+=8;
}
////////////////////////////////////////////////////////////////
// Do the bit alignment of the EOI marker
if ( bytepos >= 0 ) {
var fillbits = [];
fillbits[1] = bytepos+1;
fillbits[0] = (1<<(bytepos+1))-1;
writeBits(fillbits);
}
writeWord(0xFFD9); //EOI
if (typeof module === 'undefined') return new Uint8Array(byteout);
return Buffer.from(byteout);
var jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join(''));
byteout = [];
// benchmarking
var duration = new Date().getTime() - time_start;
//console.log('Encoding time: '+ duration + 'ms');
//
return jpegDataUri
}
function setQuality(quality){
if (quality <= 0) {
quality = 1;
}
if (quality > 100) {
quality = 100;
}
if(currentQuality == quality) return // don't recalc if unchanged
var sf = 0;
if (quality < 50) {
sf = Math.floor(5000 / quality);
} else {
sf = Math.floor(200 - quality*2);
}
initQuantTables(sf);
currentQuality = quality;
//console.log('Quality set to: '+quality +'%');
}
function init(){
var time_start = new Date().getTime();
if(!quality) quality = 50;
// Create tables
initCharLookupTable()
initHuffmanTbl();
initCategoryNumber();
initRGBYUVTable();
setQuality(quality);
var duration = new Date().getTime() - time_start;
//console.log('Initialization '+ duration + 'ms');
}
init();
};
if (typeof module !== 'undefined') {
module.exports = encode;
} else if (typeof window !== 'undefined') {
window['jpeg-js'] = window['jpeg-js'] || {};
window['jpeg-js'].encode = encode;
}
function encode(imgData, qu) {
if (typeof qu === 'undefined') qu = 50;
var encoder = new JPEGEncoder(qu);
var data = encoder.encode(imgData, qu);
return {
data: data,
width: imgData.width,
height: imgData.height,
};
}
// helper function to get the imageData of an existing image on the current page.
function getImageDataFromImage(idOrElement){
var theImg = (typeof(idOrElement)=='string')? document.getElementById(idOrElement):idOrElement;
var cvs = document.createElement('canvas');
cvs.width = theImg.width;
cvs.height = theImg.height;
var ctx = cvs.getContext("2d");
ctx.drawImage(theImg,0,0);
return (ctx.getImageData(0, 0, cvs.width, cvs.height));
}
return {
decode:decode,
encode:encode,
}
}
if (typeof module != 'undefined') module.exports = _UJPEGinit();
else UJPEG = _UJPEGinit();
};
BundleModuleCode['plugins/image/jsfeat']=function (module,exports,global,process){
/**
* https://github.com/inspirit/jsfeat
* @author Eugene Zatepyakin / http://inspirit.ru/
* ver. X002@blab
* Added U16/S16 data types; only supported by matrix constructors!!!!
*/
// namespace ?
var jsfeat = jsfeat || { REVISION: 'ALPHA' };
/**
* @author Eugene Zatepyakin / http://inspirit.ru/
*/
(function(global) {
"use strict";
//
// CONSTANTS
var EPSILON = 0.0000001192092896;
var FLT_MIN = 1E-37;
// implementation from CCV project
// currently working only with u8,s32,f32
var U8_t = 0x0100,
S32_t = 0x0200,
F32_t = 0x0400,
S64_t = 0x0800,
F64_t = 0x1000,
U16_t = 0x2000,
S16_t = 0x4000;
var C1_t = 0x01,
C2_t = 0x02,
C3_t = 0x03,
C4_t = 0x04;
var _data_type_size = new Int32Array([ -1, 1, 4,-1, 4,-1,-1,-1, 8,-1,-1,-1,-1,-1,-1,-1, 8,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2
]);
var get_data_type = (function () {
return function(type) {
return (type & 0xFF00);
}
})();
var get_channel = (function () {
return function(type) {
return (type & 0xFF);
}
})();
var get_data_type_size = (function () {
return function(type) {
return _data_type_size[(type & 0xFF00) >> 8];
}
})();
// color conversion
var COLOR_RGBA2GRAY = 0;
var COLOR_RGB2GRAY = 1;
var COLOR_BGRA2GRAY = 2;
var COLOR_BGR2GRAY = 3;
// box blur option
var BOX_BLUR_NOSCALE = 0x01;
// svd options
var SVD_U_T = 0x01;
var SVD_V_T = 0x02;
var data_t = (function () {
function data_t(size_in_bytes, buffer) {
// we need align size to multiple of 8
if (typeof buffer === "undefined") {
this.size = ((size_in_bytes + 7) | 0) & -8;
this.buffer = new ArrayBuffer(this.size);
} else {
if (buffer.buffer) buffer=buffer.buffer;
this.buffer = buffer;
if (buffer instanceof ArrayBuffer)
this.size = buffer.byteLength;
else
this.size = buffer.length;
}
this.u8 = new Uint8Array(this.buffer);
if ((this.size % 2) == 0) {
this.u16 = new Uint16Array(this.buffer);
}
if ((this.size % 4) == 0) {
this.i32 = new Int32Array(this.buffer);
this.f32 = new Float32Array(this.buffer);
}
if ((this.size % 8) == 0) {
this.f64 = new Float64Array(this.buffer);
}
}
return data_t;
})();
var matrix_t = (function () {
// columns, rows, data_type
function matrix_t(c, r, data_type, data_buffer) {
this.type = get_data_type(data_type)|0;
this.channel = get_channel(data_type)|0;
this.cols = c|0;
this.rows = r|0;
if (typeof data_buffer === "undefined") {
this.allocate();
} else {
this.buffer = data_buffer;
// data user asked for
this.data = this.type&U8_t ? this.buffer.u8 : (this.type&U16_t? this.buffer.u16 : (this.type&S32_t ? this.buffer.i32 : (this.type&F32_t ? this.buffer.f32 : this.buffer.f64)));
}
}
matrix_t.prototype.allocate = function() {
// clear references
delete this.data;
delete this.buffer;
//
this.buffer = new data_t((this.cols * get_data_type_size(this.type) * this.channel) * this.rows);
this.data = this.type&U8_t ? this.buffer.u8 : (this.type&U16_t? this.buffer.u16 : (this.type&S32_t ? this.buffer.i32 : (this.type&F32_t ? this.buffer.f32 : this.buffer.f64)));
}
matrix_t.prototype.copy_to = function(other) {
var od = other.data, td = this.data;
var i = 0, n = (this.cols*this.rows*this.channel)|0;
for(; i < n-4; i+=4) {
od[i] = td[i];
od[i+1] = td[i+1];
od[i+2] = td[i+2];
od[i+3] = td[i+3];
}
for(; i < n; ++i) {
od[i] = td[i];
}
}
matrix_t.prototype.resize = function(c, r, ch) {
if (typeof ch === "undefined") { ch = this.channel; }
// relocate buffer only if new size doesnt fit
var new_size = (c * get_data_type_size(this.type) * ch) * r;
if(new_size > this.buffer.size) {
this.cols = c;
this.rows = r;
this.channel = ch;
this.allocate();
} else {
this.cols = c;
this.rows = r;
this.channel = ch;
}
}
return matrix_t;
})();
var pyramid_t = (function () {
function pyramid_t(levels) {
this.levels = levels|0;
this.data = new Array(levels);
this.pyrdown = jsfeat.imgproc.pyrdown;
}
pyramid_t.prototype.allocate = function(start_w, start_h, data_type) {
var i = this.levels;
while(--i >= 0) {
this.data[i] = new matrix_t(start_w >> i, start_h >> i, data_type);
}
}
pyramid_t.prototype.build = function(input, skip_first_level) {
if (typeof skip_first_level === "undefined") { skip_first_level = true; }
// just copy data to first level
var i = 2, a = input, b = this.data[0];
if(!skip_first_level) {
var j=input.cols*input.rows;
while(--j >= 0) {
b.data[j] = input.data[j];
}
}
b = this.data[1];
this.pyrdown(a, b);
for(; i < this.levels; ++i) {
a = b;
b = this.data[i];
this.pyrdown(a, b);
}
}
return pyramid_t;
})();
var keypoint_t = (function () {
function keypoint_t(x,y,score,level,angle) {
if (typeof x === "undefined") { x=0; }
if (typeof y === "undefined") { y=0; }
if (typeof score === "undefined") { score=0; }
if (typeof level === "undefined") { level=0; }
if (typeof angle === "undefined") { angle=-1.0; }
this.x = x;
this.y = y;
this.score = score;
this.level = level;
this.angle = angle;
}
return keypoint_t;
})();
// data types
global.U8_t = U8_t;
global.U16_t = U16_t;
global.S32_t = S32_t;
global.F32_t = F32_t;
global.S64_t = S64_t;
global.F64_t = F64_t;
// data channels
global.C1_t = C1_t;
global.C2_t = C2_t;
global.C3_t = C3_t;
global.C4_t = C4_t;
// popular formats
global.U8C1_t = U8_t | C1_t;
global.U8C3_t = U8_t | C3_t;
global.U8C4_t = U8_t | C4_t;
global.F32C1_t = F32_t | C1_t;
global.F32C2_t = F32_t | C2_t;
global.S32C1_t = S32_t | C1_t;
global.S32C2_t = S32_t | C2_t;
// constants
global.EPSILON = EPSILON;
global.FLT_MIN = FLT_MIN;
// color convert
global.COLOR_RGBA2GRAY = COLOR_RGBA2GRAY;
global.COLOR_RGB2GRAY = COLOR_RGB2GRAY;
global.COLOR_BGRA2GRAY = COLOR_BGRA2GRAY;
global.COLOR_BGR2GRAY = COLOR_BGR2GRAY;
// options
global.BOX_BLUR_NOSCALE = BOX_BLUR_NOSCALE;
global.SVD_U_T = SVD_U_T;
global.SVD_V_T = SVD_V_T;
global.get_data_type = get_data_type;
global.get_channel = get_channel;
global.get_data_type_size = get_data_type_size;
global.data_t = data_t;
global.matrix_t = matrix_t;
global.pyramid_t = pyramid_t;
global.keypoint_t = keypoint_t;
})(jsfeat);
/**
* @author Eugene Zatepyakin / http://inspirit.ru/
*/
(function(global) {
"use strict";
//
var cache = (function() {
// very primitive array cache, still need testing if it helps
// of course V8 has its own powerful cache sys but i'm not sure
// it caches several multichannel 640x480 buffer creations each frame
var _pool_node_t = (function () {
function _pool_node_t(size_in_bytes) {
this.next = null;
this.data = new jsfeat.data_t(size_in_bytes);
this.size = this.data.size;
this.buffer = this.data.buffer;
this.u8 = this.data.u8;
this.i32 = this.data.i32;
this.f32 = this.data.f32;
this.f64 = this.data.f64;
}
_pool_node_t.prototype.resize = function(size_in_bytes) {
delete this.data;
this.data = new jsfeat.data_t(size_in_bytes);
this.size = this.data.size;
this.buffer = this.data.buffer;
this.u8 = this.data.u8;
this.i32 = this.data.i32;
this.f32 = this.data.f32;
this.f64 = this.data.f64;
}
return _pool_node_t;
})();
var _pool_head, _pool_tail;
var _pool_size = 0;
return {
allocate: function(capacity, data_size) {
_pool_head = _pool_tail = new _pool_node_t(data_size);
for (var i = 0; i < capacity; ++i) {
var node = new _pool_node_t(data_size);
_pool_tail = _pool_tail.next = node;
_pool_size++;
}
},
get_buffer: function(size_in_bytes) {
// assume we have enough free nodes
var node = _pool_head;
_pool_head = _pool_head.next;
_pool_size--;
if(size_in_bytes > node.size) {
node.resize(size_in_bytes);
}
return node;
},
put_buffer: function(node) {
_pool_tail = _pool_tail.next = node;
_pool_size++;
}
};
})();
global.cache = cache;
// for now we dont need more than 30 buffers
// if having cache sys really helps we can add auto extending sys
cache.allocate(30, 640*4);
})(jsfeat);
/**
* @author Eugene Zatepyakin / http://inspirit.ru/
*/
(function(global) {
"use strict";
//
var math = (function() {
var qsort_stack = new Int32Array(48*2);
return {
get_gaussian_kernel: function(size, sigma, kernel, data_type) {
var i=0,x=0.0,t=0.0,sigma_x=0.0,scale_2x=0.0;
var sum = 0.0;
var kern_node = jsfeat.cache.get_buffer(size<<2);
var _kernel = kern_node.f32;//new Float32Array(size);
if((size&1) == 1 && size <= 7 && sigma <= 0) {
switch(size>>1) {
case 0:
_kernel[0] = 1.0;
sum = 1.0;
break;
case 1:
_kernel[0] = 0.25, _kernel[1] = 0.5, _kernel[2] = 0.25;
sum = 0.25+0.5+0.25;
break;
case 2:
_kernel[0] = 0.0625, _kernel[1] = 0.25, _kernel[2] = 0.375,
_kernel[3] = 0.25, _kernel[4] = 0.0625;
sum = 0.0625+0.25+0.375+0.25+0.0625;
break;
case 3:
_kernel[0] = 0.03125, _kernel[1] = 0.109375, _kernel[2] = 0.21875,
_kernel[3] = 0.28125, _kernel[4] = 0.21875, _kernel[5] = 0.109375, _kernel[6] = 0.03125;
sum = 0.03125+0.109375+0.21875+0.28125+0.21875+0.109375+0.03125;
break;
}
} else {
sigma_x = sigma > 0 ? sigma : ((size-1)*0.5 - 1.0)*0.3 + 0.8;
scale_2x = -0.5/(sigma_x*sigma_x);
for( ; i < size; ++i )
{
x = i - (size-1)*0.5;
t = Math.exp(scale_2x*x*x);
_kernel[i] = t;
sum += t;
}
}
if(data_type & jsfeat.U8_t) {
// int based kernel
sum = 256.0/sum;
for (i = 0; i < size; ++i) {
kernel[i] = (_kernel[i] * sum + 0.5)|0;
}
} else {
// classic kernel
sum = 1.0/sum;
for (i = 0; i < size; ++i) {
kernel[i] = _kernel[i] * sum;
}
}
jsfeat.cache.put_buffer(kern_node);
},
// model is 3x3 matrix_t
perspective_4point_transform: function(model, src_x0, src_y0, dst_x0, dst_y0,
src_x1, src_y1, dst_x1, dst_y1,
src_x2, src_y2, dst_x2, dst_y2,
src_x3, src_y3, dst_x3, dst_y3) {
var t1 = src_x0;
var t2 = src_x2;
var t4 = src_y1;
var t5 = t1 * t2 * t4;
var t6 = src_y3;
var t7 = t1 * t6;
var t8 = t2 * t7;
var t9 = src_y2;
var t10 = t1 * t9;
var t11 = src_x1;
var t14 = src_y0;
var t15 = src_x3;
var t16 = t14 * t15;
var t18 = t16 * t11;
var t20 = t15 * t11 * t9;
var t21 = t15 * t4;
var t24 = t15 * t9;
var t25 = t2 * t4;
var t26 = t6 * t2;
var t27 = t6 * t11;
var t28 = t9 * t11;
var t30 = 1.0 / (t21-t24 - t25 + t26 - t27 + t28);
var t32 = t1 * t15;
var t35 = t14 * t11;
var t41 = t4 * t1;
var t42 = t6 * t41;
var t43 = t14 * t2;
var t46 = t16 * t9;
var t48 = t14 * t9 * t11;
var t51 = t4 * t6 * t2;
var t55 = t6 * t14;
var Hr0 = -(t8-t5 + t10 * t11 - t11 * t7 - t16 * t2 + t18 - t20 + t21 * t2) * t30;
var Hr1 = (t5 - t8 - t32 * t4 + t32 * t9 + t18 - t2 * t35 + t27 * t2 - t20) * t30;
var Hr2 = t1;
var Hr3 = (-t9 * t7 + t42 + t43 * t4 - t16 * t4 + t46 - t48 + t27 * t9 - t51) * t30;
var Hr4 = (-t42 + t41 * t9 - t55 * t2 + t46 - t48 + t55 * t11 + t51 - t21 * t9) * t30;
var Hr5 = t14;
var Hr6 = (-t10 + t41 + t43 - t35 + t24 - t21 - t26 + t27) * t30;
var Hr7 = (-t7 + t10 + t16 - t43 + t27 - t28 - t21 + t25) * t30;
t1 = dst_x0;
t2 = dst_x2;
t4 = dst_y1;
t5 = t1 * t2 * t4;
t6 = dst_y3;
t7 = t1 * t6;
t8 = t2 * t7;
t9 = dst_y2;
t10 = t1 * t9;
t11 = dst_x1;
t14 = dst_y0;
t15 = dst_x3;
t16 = t14 * t15;
t18 = t16 * t11;
t20 = t15 * t11 * t9;
t21 = t15 * t4;
t24 = t15 * t9;
t25 = t2 * t4;
t26 = t6 * t2;
t27 = t6 * t11;
t28 = t9 * t11;
t30 = 1.0 / (t21-t24 - t25 + t26 - t27 + t28);
t32 = t1 * t15;
t35 = t14 * t11;
t41 = t4 * t1;
t42 = t6 * t41;
t43 = t14 * t2;
t46 = t16 * t9;
t48 = t14 * t9 * t11;
t51 = t4 * t6 * t2;
t55 = t6 * t14;
var Hl0 = -(t8-t5 + t10 * t11 - t11 * t7 - t16 * t2 + t18 - t20 + t21 * t2) * t30;
var Hl1 = (t5 - t8 - t32 * t4 + t32 * t9 + t18 - t2 * t35 + t27 * t2 - t20) * t30;
var Hl2 = t1;
var Hl3 = (-t9 * t7 + t42 + t43 * t4 - t16 * t4 + t46 - t48 + t27 * t9 - t51) * t30;
var Hl4 = (-t42 + t41 * t9 - t55 * t2 + t46 - t48 + t55 * t11 + t51 - t21 * t9) * t30;
var Hl5 = t14;
var Hl6 = (-t10 + t41 + t43 - t35 + t24 - t21 - t26 + t27) * t30;
var Hl7 = (-t7 + t10 + t16 - t43 + t27 - t28 - t21 + t25) * t30;
// the following code computes R = Hl * inverse Hr
t2 = Hr4-Hr7*Hr5;
t4 = Hr0*Hr4;
t5 = Hr0*Hr5;
t7 = Hr3*Hr1;
t8 = Hr2*Hr3;
t10 = Hr1*Hr6;
var t12 = Hr2*Hr6;
t15 = 1.0 / (t4-t5*Hr7-t7+t8*Hr7+t10*Hr5-t12*Hr4);
t18 = -Hr3+Hr5*Hr6;
var t23 = -Hr3*Hr7+Hr4*Hr6;
t28 = -Hr1+Hr2*Hr7;
var t31 = Hr0-t12;
t35 = Hr0*Hr7-t10;
t41 = -Hr1*Hr5+Hr2*Hr4;
var t44 = t5-t8;
var t47 = t4-t7;
t48 = t2*t15;
var t49 = t28*t15;
var t50 = t41*t15;
var mat = model.data;
mat[0] = Hl0*t48+Hl1*(t18*t15)-Hl2*(t23*t15);
mat[1] = Hl0*t49+Hl1*(t31*t15)-Hl2*(t35*t15);
mat[2] = -Hl0*t50-Hl1*(t44*t15)+Hl2*(t47*t15);
mat[3] = Hl3*t48+Hl4*(t18*t15)-Hl5*(t23*t15);
mat[4] = Hl3*t49+Hl4*(t31*t15)-Hl5*(t35*t15);
mat[5] = -Hl3*t50-Hl4*(t44*t15)+Hl5*(t47*t15);
mat[6] = Hl6*t48+Hl7*(t18*t15)-t23*t15;
mat[7] = Hl6*t49+Hl7*(t31*t15)-t35*t15;
mat[8] = -Hl6*t50-Hl7*(t44*t15)+t47*t15;
},
// The current implementation was derived from *BSD system qsort():
// Copyright (c) 1992, 1993
// The Regents of the University of California. All rights reserved.
qsort: function(array, low, high, cmp) {
var isort_thresh = 7;
var t,ta,tb,tc;
var sp = 0,left=0,right=0,i=0,n=0,m=0,ptr=0,ptr2=0,d=0;
var left0=0,left1=0,right0=0,right1=0,pivot=0,a=0,b=0,c=0,swap_cnt=0;
var stack = qsort_stack;
if( (high-low+1) <= 1 ) return;
stack[0] = low;
stack[1] = high;
while( sp >= 0 ) {
left = stack[sp<<1];
right = stack[(sp<<1)+1];
sp--;
for(;;) {
n = (right - left) + 1;
if( n <= isort_thresh ) {
//insert_sort:
for( ptr = left + 1; ptr <= right; ptr++ ) {
for( ptr2 = ptr; ptr2 > left && cmp(array[ptr2],array[ptr2-1]); ptr2--) {
t = array[ptr2];
array[ptr2] = array[ptr2-1];
array[ptr2-1] = t;
}
}
break;
} else {
swap_cnt = 0;
left0 = left;
right0 = right;
pivot = left + (n>>1);
if( n > 40 ) {
d = n >> 3;
a = left, b = left + d, c = left + (d<<1);
ta = array[a],tb = array[b],tc = array[c];
left = cmp(ta, tb) ? (cmp(tb, tc) ? b : (cmp(ta, tc) ? c : a))
: (cmp(tc, tb) ? b : (cmp(ta, tc) ? a : c));
a = pivot - d, b = pivot, c = pivot + d;
ta = array[a],tb = array[b],tc = array[c];
pivot = cmp(ta, tb) ? (cmp(tb, tc) ? b : (cmp(ta, tc) ? c : a))
: (cmp(tc, tb) ? b : (cmp(ta, tc) ? a : c));
a = right - (d<<1), b = right - d, c = right;
ta = array[a],tb = array[b],tc = array[c];
right = cmp(ta, tb) ? (cmp(tb, tc) ? b : (cmp(ta, tc) ? c : a))
: (cmp(tc, tb) ? b : (cmp(ta, tc) ? a : c));
}
a = left, b = pivot, c = right;
ta = array[a],tb = array[b],tc = array[c];
pivot = cmp(ta, tb) ? (cmp(tb, tc) ? b : (cmp(ta, tc) ? c : a))
: (cmp(tc, tb) ? b : (cmp(ta, tc) ? a : c));
if( pivot != left0 ) {
t = array[pivot];
array[pivot] = array[left0];
array[left0] = t;
pivot = left0;
}
left = left1 = left0 + 1;
right = right1 = right0;
ta = array[pivot];
for(;;) {
while( left <= right && !cmp(ta, array[left]) ) {
if( !cmp(array[left], ta) ) {
if( left > left1 ) {
t = array[left1];
array[left1] = array[left];
array[left] = t;
}
swap_cnt = 1;
left1++;
}
left++;
}
while( left <= right && !cmp(array[right], ta) ) {
if( !cmp(ta, array[right]) ) {
if( right < right1 ) {
t = array[right1];
array[right1] = array[right];
array[right] = t;
}
swap_cnt = 1;
right1--;
}
right--;
}
if( left > right ) break;
t = array[left];
array[left] = array[right];
array[right] = t;
swap_cnt = 1;
left++;
right--;
}
if( swap_cnt == 0 ) {
left = left0, right = right0;
//goto insert_sort;
for( ptr = left + 1; ptr <= right; ptr++ ) {
for( ptr2 = ptr; ptr2 > left && cmp(array[ptr2],array[ptr2-1]); ptr2--) {
t = array[ptr2];
array[ptr2] = array[ptr2-1];
array[ptr2-1] = t;
}
}
break;
}
n = Math.min( (left1 - left0), (left - left1) );
m = (left-n)|0;
for( i = 0; i < n; ++i,++m ) {
t = array[left0+i];
array[left0+i] = array[m];
array[m] = t;
}
n = Math.min( (right0 - right1), (right1 - right) );
m = (right0-n+1)|0;
for( i = 0; i < n; ++i,++m ) {
t = array[left+i];
array[left+i] = array[m];
array[m] = t;
}
n = (left - left1);
m = (right1 - right);
if( n > 1 ) {
if( m > 1 ) {
if( n > m ) {
++sp;
stack[sp<<1] = left0;
stack[(sp<<1)+1] = left0 + n - 1;
left = right0 - m + 1, right = right0;
} else {
++sp;
stack[sp<<1] = right0 - m + 1;
stack[(sp<<1)+1] = right0;
left = left0, right = left0 + n - 1;
}
} else {
left = left0, right = left0 + n - 1;
}
}
else if( m > 1 )
left = right0 - m + 1, right = right0;
else
break;
}
}
}
},
median: function(array, low, high) {
var w;
var middle=0,ll=0,hh=0,median=(low+high)>>1;
for (;;) {
if (high <= low) return array[median];
if (high == (low + 1)) {
if (array[low] > array[high]) {
w = array[low];
array[low] = array[high];
array[high] = w;
}
return array[median];
}
middle = ((low + high) >> 1);
if (array[middle] > array[high]) {
w = array[middle];
array[middle] = array[high];
array[high] = w;
}
if (array[low] > array[high]) {
w = array[low];
array[low] = array[high];
array[high] = w;
}
if (array[middle] > array[low]) {
w = array[middle];
array[middle] = array[low];
array[low] = w;
}
ll = (low + 1);
w = array[middle];
array[middle] = array[ll];
array[ll] = w;
hh = high;
for (;;) {
do ++ll; while (array[low] > array[ll]);
do --hh; while (array[hh] > array[low]);
if (hh < ll) break;
w = array[ll];
array[ll] = array[hh];
array[hh] = w;
}
w = array[low];
array[low] = array[hh];
array[hh] = w;
if (hh <= median)
low = ll;
else if (hh >= median)
high = (hh - 1);
}
return 0;
}
};
})();
global.math = math;
})(jsfeat);
/**
* @author Eugene Zatepyakin / http://inspirit.ru/
*
*/
(function(global) {
"use strict";
//
var matmath = (function() {
return {
identity: function(M, value) {
if (typeof value === "undefined") { value=1; }
var src=M.data;
var rows=M.rows, cols=M.cols, cols_1=(cols+1)|0;
var len = rows * cols;
var k = len;
while(--len >= 0) src[len] = 0.0;
len = k;
k = 0;
while(k < len) {
src[k] = value;
k = k + cols_1;
}
},
transpose: function(At, A) {
var i=0,j=0,nrows=A.rows,ncols=A.cols;
var Ai=0,Ati=0,pAt=0;
var ad=A.data,atd=At.data;
for (; i < nrows; Ati += 1, Ai += ncols, i++) {
pAt = Ati;
for (j = 0; j < ncols; pAt += nrows, j++) atd[pAt] = ad[Ai+j];
}
},
// C = A * B
multiply: function(C, A, B) {
var i=0,j=0,k=0;
var Ap=0,pA=0,pB=0,p_B=0,Cp=0;
var ncols=A.cols,nrows=A.rows,mcols=B.cols;
var ad=A.data,bd=B.data,cd=C.data;
var sum=0.0;
for (; i < nrows; Ap += ncols, i++) {
for (p_B = 0, j = 0; j < mcols; Cp++, p_B++, j++) {
pB = p_B;
pA = Ap;
sum = 0.0;
for (k = 0; k < ncols; pA++, pB += mcols, k++) {
sum += ad[pA] * bd[pB];
}
cd[Cp] = sum;
}
}
},
// C = A * B'
multiply_ABt: function(C, A, B) {
var i=0,j=0,k=0;
var Ap=0,pA=0,pB=0,Cp=0;
var ncols=A.cols,nrows=A.rows,mrows=B.rows;
var ad=A.data,bd=B.data,cd=C.data;
var sum=0.0;
for (; i < nrows; Ap += ncols, i++) {
for (pB = 0, j = 0; j < mrows; Cp++, j++) {
pA = Ap;
sum = 0.0;
for (k = 0; k < ncols; pA++, pB++, k++) {
sum += ad[pA] * bd[pB];
}
cd[Cp] = sum;
}
}
},
// C = A' * B
multiply_AtB: function(C, A, B) {
var i=0,j=0,k=0;
var Ap=0,pA=0,pB=0,p_B=0,Cp=0;
var ncols=A.cols,nrows=A.rows,mcols=B.cols;
var ad=A.data,bd=B.data,cd=C.data;
var sum=0.0;
for (; i < ncols; Ap++, i++) {
for (p_B = 0, j = 0; j < mcols; Cp++, p_B++, j++) {
pB = p_B;
pA = Ap;
sum = 0.0;
for (k = 0; k < nrows; pA += ncols, pB += mcols, k++) {
sum += ad[pA] * bd[pB];
}
cd[Cp] = sum;
}
}
},
// C = A * A'
multiply_AAt: function(C, A) {
var i=0,j=0,k=0;
var pCdiag=0,p_A=0,pA=0,pB=0,pC=0,pCt=0;
var ncols=A.cols,nrows=A.rows;
var ad=A.data,cd=C.data;
var sum=0.0;
for (; i < nrows; pCdiag += nrows + 1, p_A = pA, i++) {
pC = pCdiag;
pCt = pCdiag;
pB = p_A;
for (j = i; j < nrows; pC++, pCt += nrows, j++) {
pA = p_A;
sum = 0.0;
for (k = 0; k < ncols; k++) {
sum += ad[pA++] * ad[pB++];
}
cd[pC] = sum
cd[pCt] = sum;
}
}
},
// C = A' * A
multiply_AtA: function(C, A) {
var i=0,j=0,k=0;
var p_A=0,pA=0,pB=0,p_C=0,pC=0,p_CC=0;
var ncols=A.cols,nrows=A.rows;
var ad=A.data,cd=C.data;
var sum=0.0;
for (; i < ncols; p_C += ncols, i++) {
p_A = i;
p_CC = p_C + i;
pC = p_CC;
for (j = i; j < ncols; pC++, p_CC += ncols, j++) {
pA = p_A;
pB = j;
sum = 0.0;
for (k = 0; k < nrows; pA += ncols, pB += ncols, k++) {
sum += ad[pA] * ad[pB];
}
cd[pC] = sum
cd[p_CC] = sum;
}
}
},
// various small matrix operations
identity_3x3: function(M, value) {
if (typeof value === "undefined") { value=1; }
var dt=M.data;
dt[0] = dt[4] = dt[8] = value;
dt[1] = dt[2] = dt[3] = 0;
dt[5] = dt[6] = dt[7] = 0;
},
invert_3x3: function(from, to) {
var A = from.data, invA = to.data;
var t1 = A[4];
var t2 = A[8];
var t4 = A[5];
var t5 = A[7];
var t8 = A[0];
var t9 = t8*t1;
var t11 = t8*t4;
var t13 = A[3];
var t14 = A[1];
var t15 = t13*t14;
var t17 = A[2];
var t18 = t13*t17;
var t20 = A[6];
var t21 = t20*t14;
var t23 = t20*t17;
var t26 = 1.0/(t9*t2-t11*t5-t15*t2+t18*t5+t21*t4-t23*t1);
invA[0] = (t1*t2-t4*t5)*t26;
invA[1] = -(t14*t2-t17*t5)*t26;
invA[2] = -(-t14*t4+t17*t1)*t26;
invA[3] = -(t13*t2-t4*t20)*t26;
invA[4] = (t8*t2-t23)*t26;
invA[5] = -(t11-t18)*t26;
invA[6] = -(-t13*t5+t1*t20)*t26;
invA[7] = -(t8*t5-t21)*t26;
invA[8] = (t9-t15)*t26;
},
// C = A * B
multiply_3x3: function(C, A, B) {
var Cd=C.data, Ad=A.data, Bd=B.data;
var m1_0 = Ad[0], m1_1 = Ad[1], m1_2 = Ad[2];
var m1_3 = Ad[3], m1_4 = Ad[4], m1_5 = Ad[5];
var m1_6 = Ad[6], m1_7 = Ad[7], m1_8 = Ad[8];
var m2_0 = Bd[0], m2_1 = Bd[1], m2_2 = Bd[2];
var m2_3 = Bd[3], m2_4 = Bd[4], m2_5 = Bd[5];
var m2_6 = Bd[6], m2_7 = Bd[7], m2_8 = Bd[8];
Cd[0] = m1_0 * m2_0 + m1_1 * m2_3 + m1_2 * m2_6;
Cd[1] = m1_0 * m2_1 + m1_1 * m2_4 + m1_2 * m2_7;
Cd[2] = m1_0 * m2_2 + m1_1 * m2_5 + m1_2 * m2_8;
Cd[3] = m1_3 * m2_0 + m1_4 * m2_3 + m1_5 * m2_6;
Cd[4] = m1_3 * m2_1 + m1_4 * m2_4 + m1_5 * m2_7;
Cd[5] = m1_3 * m2_2 + m1_4 * m2_5 + m1_5 * m2_8;
Cd[6] = m1_6 * m2_0 + m1_7 * m2_3 + m1_8 * m2_6;
Cd[7] = m1_6 * m2_1 + m1_7 * m2_4 + m1_8 * m2_7;
Cd[8] = m1_6 * m2_2 + m1_7 * m2_5 + m1_8 * m2_8;
},
mat3x3_determinant: function(M) {
var md=M.data;
return md[0] * md[4] * md[8] -
md[0] * md[5] * md[7] -
md[3] * md[1] * md[8] +
md[3] * md[2] * md[7] +
md[6] * md[1] * md[5] -
md[6] * md[2] * md[4];
},
determinant_3x3: function(M11, M12, M13,
M21, M22, M23,
M31, M32, M33) {
return M11 * M22 * M33 - M11 * M23 * M32 -
M21 * M12 * M33 + M21 * M13 * M32 +
M31 * M12 * M23 - M31 * M13 * M22;
}
};
})();
global.matmath = matmath;
})(jsfeat);
/**
* @author Eugene Zatepyakin / http://inspirit.ru/
*
*/
(function(global) {
"use strict";
//
var linalg = (function() {
var swap = function(A, i0, i1, t) {
t = A[i0];
A[i0] = A[i1];
A[i1] = t;
}
var hypot = function(a, b) {
a = Math.abs(a);
b = Math.abs(b);
if( a > b ) {
b /= a;
return a*Math.sqrt(1.0 + b*b);
}
if( b > 0 ) {
a /= b;
return b*Math.sqrt(1.0 + a*a);
}
return 0.0;
}
var JacobiImpl = function(A, astep, W, V, vstep, n) {
var eps = jsfeat.EPSILON;
var i=0,j=0,k=0,m=0,l=0,idx=0,_in=0,_in2=0;
var iters=0,max_iter=n*n*30;
var mv=0.0,val=0.0,p=0.0,y=0.0,t=0.0,s=0.0,c=0.0,a0=0.0,b0=0.0;
var indR_buff = jsfeat.cache.get_buffer(n<<2);
var indC_buff = jsfeat.cache.get_buffer(n<<2);
var indR = indR_buff.i32;
var indC = indC_buff.i32;
if(V) {
for(; i < n; i++) {
k = i*vstep;
for(j = 0; j < n; j++) {
V[k + j] = 0.0;
}
V[k + i] = 1.0;
}
}
for(k = 0; k < n; k++) {
W[k] = A[(astep + 1)*k];
if(k < n - 1) {
for(m = k+1, mv = Math.abs(A[astep*k + m]), i = k+2; i < n; i++) {
val = Math.abs(A[astep*k+i]);
if(mv < val)
mv = val, m = i;
}
indR[k] = m;
}
if(k > 0) {
for(m = 0, mv = Math.abs(A[k]), i = 1; i < k; i++) {
val = Math.abs(A[astep*i+k]);
if(mv < val)
mv = val, m = i;
}
indC[k] = m;
}
}
if(n > 1) for( ; iters < max_iter; iters++) {
// find index (k,l) of pivot p
for(k = 0, mv = Math.abs(A[indR[0]]), i = 1; i < n-1; i++) {
val = Math.abs(A[astep*i + indR[i]]);
if( mv < val )
mv = val, k = i;
}
l = indR[k];
for(i = 1; i < n; i++) {
val = Math.abs(A[astep*indC[i] + i]);
if( mv < val )
mv = val, k = indC[i], l = i;
}
p = A[astep*k + l];
if(Math.abs(p) <= eps) break;
y = (W[l] - W[k])*0.5;
t = Math.abs(y) + hypot(p, y);
s = hypot(p, t);
c = t/s;
s = p/s; t = (p/t)*p;
if(y < 0)
s = -s, t = -t;
A[astep*k + l] = 0;
W[k] -= t;
W[l] += t;
// rotate rows and columns k and l
for (i = 0; i < k; i++) {
_in = (astep * i + k);
_in2 = (astep * i + l);
a0 = A[_in];
b0 = A[_in2];
A[_in] = a0 * c - b0 * s;
A[_in2] = a0 * s + b0 * c;
}
for (i = (k + 1); i < l; i++) {
_in = (astep * k + i);
_in2 = (astep * i + l);
a0 = A[_in];
b0 = A[_in2];
A[_in] = a0 * c - b0 * s;
A[_in2] = a0 * s + b0 * c;
}
i = l + 1;
_in = (astep * k + i);
_in2 = (astep * l + i);
for (; i < n; i++, _in++, _in2++) {
a0 = A[_in];
b0 = A[_in2];
A[_in] = a0 * c - b0 * s;
A[_in2] = a0 * s + b0 * c;
}
// rotate eigenvectors
if (V) {
_in = vstep * k;
_in2 = vstep * l;
for (i = 0; i < n; i++, _in++, _in2++) {
a0 = V[_in];
b0 = V[_in2];
V[_in] = a0 * c - b0 * s;
V[_in2] = a0 * s + b0 * c;
}
}
for(j = 0; j < 2; j++) {
idx = j == 0 ? k : l;
if(idx < n - 1) {
for(m = idx+1, mv = Math.abs(A[astep*idx + m]), i = idx+2; i < n; i++) {
val = Math.abs(A[astep*idx+i]);
if( mv < val )
mv = val, m = i;
}
indR[idx] = m;
}
if(idx > 0) {
for(m = 0, mv = Math.abs(A[idx]), i = 1; i < idx; i++) {
val = Math.abs(A[astep*i+idx]);
if( mv < val )
mv = val, m = i;
}
indC[idx] = m;
}
}
}
// sort eigenvalues & eigenvectors
for(k = 0; k < n-1; k++) {
m = k;
for(i = k+1; i < n; i++) {
if(W[m] < W[i])
m = i;
}
if(k != m) {
swap(W, m, k, mv);
if(V) {
for(i = 0; i < n; i++) {
swap(V, vstep*m + i, vstep*k + i, mv);
}
}
}
}
jsfeat.cache.put_buffer(indR_buff);
jsfeat.cache.put_buffer(indC_buff);
}
var JacobiSVDImpl = function(At, astep, _W, Vt, vstep, m, n, n1) {
var eps = jsfeat.EPSILON * 2.0;
var minval = jsfeat.FLT_MIN;
var i=0,j=0,k=0,iter=0,max_iter=Math.max(m, 30);
var Ai=0,Aj=0,Vi=0,Vj=0,changed=0;
var c=0.0, s=0.0, t=0.0;
var t0=0.0,t1=0.0,sd=0.0,beta=0.0,gamma=0.0,delta=0.0,a=0.0,p=0.0,b=0.0;
var seed = 0x1234;
var val=0.0,val0=0.0,asum=0.0;
var W_buff = jsfeat.cache.get_buffer(n<<3);
var W = W_buff.f64;
for(; i < n; i++) {
for(k = 0, sd = 0; k < m; k++) {
t = At[i*astep + k];
sd += t*t;
}
W[i] = sd;
if(Vt) {
for(k = 0; k < n; k++) {
Vt[i*vstep + k] = 0;
}
Vt[i*vstep + i] = 1;
}
}
for(; iter < max_iter; iter++) {
changed = 0;
for(i = 0; i < n-1; i++) {
for(j = i+1; j < n; j++) {
Ai = (i*astep)|0, Aj = (j*astep)|0;
a = W[i], p = 0, b = W[j];
k = 2;
p += At[Ai]*At[Aj];
p += At[Ai+1]*At[Aj+1];
for(; k < m; k++)
p += At[Ai+k]*At[Aj+k];
if(Math.abs(p) <= eps*Math.sqrt(a*b)) continue;
p *= 2.0;
beta = a - b, gamma = hypot(p, beta);
if( beta < 0 ) {
delta = (gamma - beta)*0.5;
s = Math.sqrt(delta/gamma);
c = (p/(gamma*s*2.0));
} else {
c = Math.sqrt((gamma + beta)/(gamma*2.0));
s = (p/(gamma*c*2.0));
}
a=0.0, b=0.0;
k = 2; // unroll
t0 = c*At[Ai] + s*At[Aj];
t1 = -s*At[Ai] + c*At[Aj];
At[Ai] = t0; At[Aj] = t1;
a += t0*t0; b += t1*t1;
t0 = c*At[Ai+1] + s*At[Aj+1];
t1 = -s*At[Ai+1] + c*At[Aj+1];
At[Ai+1] = t0; At[Aj+1] = t1;
a += t0*t0; b += t1*t1;
for( ; k < m; k++ )
{
t0 = c*At[Ai+k] + s*At[Aj+k];
t1 = -s*At[Ai+k] + c*At[Aj+k];
At[Ai+k] = t0; At[Aj+k] = t1;
a += t0*t0; b += t1*t1;
}
W[i] = a; W[j] = b;
changed = 1;
if(Vt) {
Vi = (i*vstep)|0, Vj = (j*vstep)|0;
k = 2;
t0 = c*Vt[Vi] + s*Vt[Vj];
t1 = -s*Vt[Vi] + c*Vt[Vj];
Vt[Vi] = t0; Vt[Vj] = t1;
t0 = c*Vt[Vi+1] + s*Vt[Vj+1];
t1 = -s*Vt[Vi+1] + c*Vt[Vj+1];
Vt[Vi+1] = t0; Vt[Vj+1] = t1;
for(; k < n; k++) {
t0 = c*Vt[Vi+k] + s*Vt[Vj+k];
t1 = -s*Vt[Vi+k] + c*Vt[Vj+k];
Vt[Vi+k] = t0; Vt[Vj+k] = t1;
}
}
}
}
if(changed == 0) break;
}
for(i = 0; i < n; i++) {
for(k = 0, sd = 0; k < m; k++) {
t = At[i*astep + k];
sd += t*t;
}
W[i] = Math.sqrt(sd);
}
for(i = 0; i < n-1; i++) {
j = i;
for(k = i+1; k < n; k++) {
if(W[j] < W[k])
j = k;
}
if(i != j) {
swap(W, i, j, sd);
if(Vt) {
for(k = 0; k < m; k++) {
swap(At, i*astep + k, j*astep + k, t);
}
for(k = 0; k < n; k++) {
swap(Vt, i*vstep + k, j*vstep + k, t);
}
}
}
}
for(i = 0; i < n; i++) {
_W[i] = W[i];
}
if(!Vt) {
jsfeat.cache.put_buffer(W_buff);
return;
}
for(i = 0; i < n1; i++) {
sd = i < n ? W[i] : 0;
while(sd <= minval) {
// if we got a zero singular value, then in order to get the corresponding left singular vector
// we generate a random vector, project it to the previously computed left singular vectors,
// subtract the projection and normalize the difference.
val0 = (1.0/m);
for(k = 0; k < m; k++) {
seed = (seed * 214013 + 2531011);
val = (((seed >> 16) & 0x7fff) & 256) != 0 ? val0 : -val0;
At[i*astep + k] = val;
}
for(iter = 0; iter < 2; iter++) {
for(j = 0; j < i; j++) {
sd = 0;
for(k = 0; k < m; k++) {
sd += At[i*astep + k]*At[j*astep + k];
}
asum = 0.0;
for(k = 0; k < m; k++) {
t = (At[i*astep + k] - sd*At[j*astep + k]);
At[i*astep + k] = t;
asum += Math.abs(t);
}
asum = asum ? 1.0/asum : 0;
for(k = 0; k < m; k++) {
At[i*astep + k] *= asum;
}
}
}
sd = 0;
for(k = 0; k < m; k++) {
t = At[i*astep + k];
sd += t*t;
}
sd = Math.sqrt(sd);
}
s = (1.0/sd);
for(k = 0; k < m; k++) {
At[i*astep + k] *= s;
}
}
jsfeat.cache.put_buffer(W_buff);
}
return {
lu_solve: function(A, B) {
var i=0,j=0,k=0,p=1,astep=A.cols;
var ad=A.data, bd=B.data;
var t,alpha,d,s;
for(i = 0; i < astep; i++) {
k = i;
for(j = i+1; j < astep; j++) {
if(Math.abs(ad[j*astep + i]) > Math.abs(ad[k*astep+i])) {
k = j;
}
}
if(Math.abs(ad[k*astep+i]) < jsfeat.EPSILON) {
return 0; // FAILED
}
if(k != i) {
for(j = i; j < astep; j++ ) {
swap(ad, i*astep+j, k*astep+j, t);
}
swap(bd, i, k, t);
p = -p;
}
d = -1.0/ad[i*astep+i];
for(j = i+1; j < astep; j++) {
alpha = ad[j*astep+i]*d;
for(k = i+1; k < astep; k++) {
ad[j*astep+k] += alpha*ad[i*astep+k];
}
bd[j] += alpha*bd[i];
}
ad[i*astep+i] = -d;
}
for(i = astep-1; i >= 0; i--) {
s = bd[i];
for(k = i+1; k < astep; k++) {
s -= ad[i*astep+k]*bd[k];
}
bd[i] = s*ad[i*astep+i];
}
return 1; // OK
},
cholesky_solve: function(A, B) {
var col=0,row=0,col2=0,cs=0,rs=0,i=0,j=0;
var size = A.cols;
var ad=A.data, bd=B.data;
var val,inv_diag;
for (col = 0; col < size; col++) {
inv_diag = 1.0;
cs = (col * size);
rs = cs;
for (row = col; row < size; row++)
{
// correct for the parts of cholesky already computed
val = ad[(rs+col)];
for (col2 = 0; col2 < col; col2++) {
val -= ad[(col2*size+col)] * ad[(rs+col2)];
}
if (row == col) {
// this is the diagonal element so don't divide
ad[(rs+col)] = val;
if(val == 0) {
return 0;
}
inv_diag = 1.0 / val;
} else {
// cache the value without division in the upper half
ad[(cs+row)] = val;
// divide my the diagonal element for all others
ad[(rs+col)] = val * inv_diag;
}
rs = (rs + size);
}
}
// first backsub through L
cs = 0;
for (i = 0; i < size; i++) {
val = bd[i];
for (j = 0; j < i; j++) {
val -= ad[(cs+j)] * bd[j];
}
bd[i] = val;
cs = (cs + size);
}
// backsub through diagonal
cs = 0;
for (i = 0; i < size; i++) {
bd[i] /= ad[(cs + i)];
cs = (cs + size);
}
// backsub through L Transpose
i = (size-1);
for (; i >= 0; i--) {
val = bd[i];
j = (i + 1);
cs = (j * size);
for (; j < size; j++) {
val -= ad[(cs + i)] * bd[j];
cs = (cs + size);
}
bd[i] = val;
}
return 1;
},
svd_decompose: function(A, W, U, V, options) {
if (typeof options === "undefined") { options = 0; };
var at=0,i=0,j=0,_m=A.rows,_n=A.cols,m=_m,n=_n;
var dt = A.type | jsfeat.C1_t; // we only work with single channel
if(m < n) {
at = 1;
i = m;
m = n;
n = i;
}
var a_buff = jsfeat.cache.get_buffer((m*m)<<3);
var w_buff = jsfeat.cache.get_buffer(n<<3);
var v_buff = jsfeat.cache.get_buffer((n*n)<<3);
var a_mt = new jsfeat.matrix_t(m, m, dt, a_buff.data);
var w_mt = new jsfeat.matrix_t(1, n, dt, w_buff.data);
var v_mt = new jsfeat.matrix_t(n, n, dt, v_buff.data);
if(at == 0) {
// transpose
jsfeat.matmath.transpose(a_mt, A);
} else {
for(i = 0; i < _n*_m; i++) {
a_mt.data[i] = A.data[i];
}
for(; i < n*m; i++) {
a_mt.data[i] = 0;
}
}
JacobiSVDImpl(a_mt.data, m, w_mt.data, v_mt.data, n, m, n, m);
if(W) {
for(i=0; i < n; i++) {
W.data[i] = w_mt.data[i];
}
for(; i < _n; i++) {
W.data[i] = 0;
}
}
if (at == 0) {
if(U && (options & jsfeat.SVD_U_T)) {
i = m*m;
while(--i >= 0) {
U.data[i] = a_mt.data[i];
}
} else if(U) {
jsfeat.matmath.transpose(U, a_mt);
}
if(V && (options & jsfeat.SVD_V_T)) {
i = n*n;
while(--i >= 0) {
V.data[i] = v_mt.data[i];
}
} else if(V) {
jsfeat.matmath.transpose(V, v_mt);
}
} else {
if(U && (options & jsfeat.SVD_U_T)) {
i = n*n;
while(--i >= 0) {
U.data[i] = v_mt.data[i];
}
} else if(U) {
jsfeat.matmath.transpose(U, v_mt);
}
if(V && (options & jsfeat.SVD_V_T)) {
i = m*m;
while(--i >= 0) {
V.data[i] = a_mt.data[i];
}
} else if(V) {
jsfeat.matmath.transpose(V, a_mt);
}
}
jsfeat.cache.put_buffer(a_buff);
jsfeat.cache.put_buffer(w_buff);
jsfeat.cache.put_buffer(v_buff);
},
svd_solve: function(A, X, B) {
var i=0,j=0,k=0;
var pu=0,pv=0;
var nrows=A.rows,ncols=A.cols;
var sum=0.0,xsum=0.0,tol=0.0;
var dt = A.type | jsfeat.C1_t;
var u_buff = jsfeat.cache.get_buffer((nrows*nrows)<<3);
var w_buff = jsfeat.cache.get_buffer(ncols<<3);
var v_buff = jsfeat.cache.get_buffer((ncols*ncols)<<3);
var u_mt = new jsfeat.matrix_t(nrows, nrows, dt, u_buff.data);
var w_mt = new jsfeat.matrix_t(1, ncols, dt, w_buff.data);
var v_mt = new jsfeat.matrix_t(ncols, ncols, dt, v_buff.data);
var bd = B.data, ud = u_mt.data, wd = w_mt.data, vd = v_mt.data;
this.svd_decompose(A, w_mt, u_mt, v_mt, 0);
tol = jsfeat.EPSILON * wd[0] * ncols;
for (; i < ncols; i++, pv += ncols) {
xsum = 0.0;
for(j = 0; j < ncols; j++) {
if(wd[j] > tol) {
for(k = 0, sum = 0.0, pu = 0; k < nrows; k++, pu += ncols) {
sum += ud[pu + j] * bd[k];
}
xsum += sum * vd[pv + j] / wd[j];
}
}
X.data[i] = xsum;
}
jsfeat.cache.put_buffer(u_buff);
jsfeat.cache.put_buffer(w_buff);
jsfeat.cache.put_buffer(v_buff);
},
svd_invert: function(Ai, A) {
var i=0,j=0,k=0;
var pu=0,pv=0,pa=0;
var nrows=A.rows,ncols=A.cols;
var sum=0.0,tol=0.0;
var dt = A.type | jsfeat.C1_t;
var u_buff = jsfeat.cache.get_buffer((nrows*nrows)<<3);
var w_buff = jsfeat.cache.get_buffer(ncols<<3);
var v_buff = jsfeat.cache.get_buffer((ncols*ncols)<<3);
var u_mt = new jsfeat.matrix_t(nrows, nrows, dt, u_buff.data);
var w_mt = new jsfeat.matrix_t(1, ncols, dt, w_buff.data);
var v_mt = new jsfeat.matrix_t(ncols, ncols, dt, v_buff.data);
var id = Ai.data, ud = u_mt.data, wd = w_mt.data, vd = v_mt.data;
this.svd_decompose(A, w_mt, u_mt, v_mt, 0);
tol = jsfeat.EPSILON * wd[0] * ncols;
for (; i < ncols; i++, pv += ncols) {
for (j = 0, pu = 0; j < nrows; j++, pa++) {
for (k = 0, sum = 0.0; k < ncols; k++, pu++) {
if (wd[k] > tol) sum += vd[pv + k] * ud[pu] / wd[k];
}
id[pa] = sum;
}
}
jsfeat.cache.put_buffer(u_buff);
jsfeat.cache.put_buffer(w_buff);
jsfeat.cache.put_buffer(v_buff);
},
eigenVV: function(A, vects, vals) {
var n=A.cols,i=n*n;
var dt = A.type | jsfeat.C1_t;
var a_buff = jsfeat.cache.get_buffer((n*n)<<3);
var w_buff = jsfeat.cache.get_buffer(n<<3);
var a_mt = new jsfeat.matrix_t(n, n, dt, a_buff.data);
var w_mt = new jsfeat.matrix_t(1, n, dt, w_buff.data);
while(--i >= 0) {
a_mt.data[i] = A.data[i];
}
JacobiImpl(a_mt.data, n, w_mt.data, vects ? vects.data : null, n, n);
if(vals) {
while(--n >= 0) {
vals.data[n] = w_mt.data[n];
}
}
jsfeat.cache.put_buffer(a_buff);
jsfeat.cache.put_buffer(w_buff);
}
};
})();
global.linalg = linalg;
})(jsfeat);
/**
* @author Eugene Zatepyakin / http://inspirit.ru/
*
*/
(function(global) {
"use strict";
//
var motion_model = (function() {
var sqr = function(x) {
return x*x;
}
// does isotropic normalization
var iso_normalize_points = function(from, to, T0, T1, count) {
var i=0;
var cx0=0.0, cy0=0.0, d0=0.0, s0=0.0;
var cx1=0.0, cy1=0.0, d1=0.0, s1=0.0;
var dx=0.0,dy=0.0;
for (; i < count; ++i) {
cx0 += from[i].x;
cy0 += from[i].y;
cx1 += to[i].x;
cy1 += to[i].y;
}
cx0 /= count; cy0 /= count;
cx1 /= count; cy1 /= count;
for (i = 0; i < count; ++i) {
dx = from[i].x - cx0;
dy = from[i].y - cy0;
d0 += Math.sqrt(dx*dx + dy*dy);
dx = to[i].x - cx1;
dy = to[i].y - cy1;
d1 += Math.sqrt(dx*dx + dy*dy);
}
d0 /= count; d1 /= count;
s0 = Math.SQRT2 / d0; s1 = Math.SQRT2 / d1;
T0[0] = T0[4] = s0;
T0[2] = -cx0*s0;
T0[5] = -cy0*s0;
T0[1] = T0[3] = T0[6] = T0[7] = 0.0;
T0[8] = 1.0;
T1[0] = T1[4] = s1;
T1[2] = -cx1*s1;
T1[5] = -cy1*s1;
T1[1] = T1[3] = T1[6] = T1[7] = 0.0;
T1[8] = 1.0;
}
var have_collinear_points = function(points, count) {
var j=0,k=0,i=(count-1)|0;
var dx1=0.0,dy1=0.0,dx2=0.0,dy2=0.0;
// check that the i-th selected point does not belong
// to a line connecting some previously selected points
for(; j < i; ++j) {
dx1 = points[j].x - points[i].x;
dy1 = points[j].y - points[i].y;
for(k = 0; k < j; ++k) {
dx2 = points[k].x - points[i].x;
dy2 = points[k].y - points[i].y;
if( Math.abs(dx2*dy1 - dy2*dx1) <= jsfeat.EPSILON*(Math.abs(dx1) + Math.abs(dy1) + Math.abs(dx2) + Math.abs(dy2)))
return true;
}
}
return false;
}
var T0 = new jsfeat.matrix_t(3, 3, jsfeat.F32_t|jsfeat.C1_t);
var T1 = new jsfeat.matrix_t(3, 3, jsfeat.F32_t|jsfeat.C1_t);
var AtA = new jsfeat.matrix_t(6, 6, jsfeat.F32_t|jsfeat.C1_t);
var AtB = new jsfeat.matrix_t(6, 1, jsfeat.F32_t|jsfeat.C1_t);
var affine2d = (function () {
function affine2d() {
// empty constructor
}
affine2d.prototype.run = function(from, to, model, count) {
var i=0,j=0;
var dt=model.type|jsfeat.C1_t;
var md=model.data, t0d=T0.data, t1d=T1.data;
var pt0,pt1,px=0.0,py=0.0;
iso_normalize_points(from, to, t0d, t1d, count);
var a_buff = jsfeat.cache.get_buffer((2*count*6)<<3);
var b_buff = jsfeat.cache.get_buffer((2*count)<<3);
var a_mt = new jsfeat.matrix_t(6, 2*count, dt, a_buff.data);
var b_mt = new jsfeat.matrix_t(1, 2*count, dt, b_buff.data);
var ad=a_mt.data, bd=b_mt.data;
for (; i < count; ++i) {
pt0 = from[i];
pt1 = to[i];
px = t0d[0]*pt0.x + t0d[1]*pt0.y + t0d[2];
py = t0d[3]*pt0.x + t0d[4]*pt0.y + t0d[5];
j = i*2*6;
ad[j]=px, ad[j+1]=py, ad[j+2]=1.0, ad[j+3]=0.0, ad[j+4]=0.0, ad[j+5]=0.0;
j += 6;
ad[j]=0.0, ad[j+1]=0.0, ad[j+2]=0.0, ad[j+3]=px, ad[j+4]=py, ad[j+5]=1.0;
bd[i<<1] = t1d[0]*pt1.x + t1d[1]*pt1.y + t1d[2];
bd[(i<<1)+1] = t1d[3]*pt1.x + t1d[4]*pt1.y + t1d[5];
}
jsfeat.matmath.multiply_AtA(AtA, a_mt);
jsfeat.matmath.multiply_AtB(AtB, a_mt, b_mt);
jsfeat.linalg.lu_solve(AtA, AtB);
md[0] = AtB.data[0], md[1]=AtB.data[1], md[2]=AtB.data[2];
md[3] = AtB.data[3], md[4]=AtB.data[4], md[5]=AtB.data[5];
md[6] = 0.0, md[7] = 0.0, md[8] = 1.0; // fill last row
// denormalize
jsfeat.matmath.invert_3x3(T1, T1);
jsfeat.matmath.multiply_3x3(model, T1, model);
jsfeat.matmath.multiply_3x3(model, model, T0);
// free buffer
jsfeat.cache.put_buffer(a_buff);
jsfeat.cache.put_buffer(b_buff);
return 1;
}
affine2d.prototype.error = function(from, to, model, err, count) {
var i=0;
var pt0,pt1;
var m=model.data;
for (; i < count; ++i) {
pt0 = from[i];
pt1 = to[i];
err[i] = sqr(pt1.x - m[0]*pt0.x - m[1]*pt0.y - m[2]) +
sqr(pt1.y - m[3]*pt0.x - m[4]*pt0.y - m[5]);
}
}
affine2d.prototype.check_subset = function(from, to, count) {
return true; // all good
}
return affine2d;
})();
var mLtL = new jsfeat.matrix_t(9, 9, jsfeat.F32_t|jsfeat.C1_t);
var Evec = new jsfeat.matrix_t(9, 9, jsfeat.F32_t|jsfeat.C1_t);
var homography2d = (function () {
function homography2d() {
// empty constructor
//this.T0 = new jsfeat.matrix_t(3, 3, jsfeat.F32_t|jsfeat.C1_t);
//this.T1 = new jsfeat.matrix_t(3, 3, jsfeat.F32_t|jsfeat.C1_t);
//this.mLtL = new jsfeat.matrix_t(9, 9, jsfeat.F32_t|jsfeat.C1_t);
//this.Evec = new jsfeat.matrix_t(9, 9, jsfeat.F32_t|jsfeat.C1_t);
}
homography2d.prototype.run = function(from, to, model, count) {
var i=0,j=0;
var md=model.data, t0d=T0.data, t1d=T1.data;
var LtL=mLtL.data, evd=Evec.data;
var x=0.0,y=0.0,X=0.0,Y=0.0;
// norm
var smx=0.0, smy=0.0, cmx=0.0, cmy=0.0, sMx=0.0, sMy=0.0, cMx=0.0, cMy=0.0;
for(; i < count; ++i) {
cmx += to[i].x;
cmy += to[i].y;
cMx += from[i].x;
cMy += from[i].y;
}
cmx /= count; cmy /= count;
cMx /= count; cMy /= count;
for(i = 0; i < count; ++i)
{
smx += Math.abs(to[i].x - cmx);
smy += Math.abs(to[i].y - cmy);
sMx += Math.abs(from[i].x - cMx);
sMy += Math.abs(from[i].y - cMy);
}
if( Math.abs(smx) < jsfeat.EPSILON
|| Math.abs(smy) < jsfeat.EPSILON
|| Math.abs(sMx) < jsfeat.EPSILON
|| Math.abs(sMy) < jsfeat.EPSILON ) return 0;
smx = count/smx; smy = count/smy;
sMx = count/sMx; sMy = count/sMy;
t0d[0] = sMx; t0d[1] = 0; t0d[2] = -cMx*sMx;
t0d[3] = 0; t0d[4] = sMy; t0d[5] = -cMy*sMy;
t0d[6] = 0; t0d[7] = 0; t0d[8] = 1;
t1d[0] = 1.0/smx; t1d[1] = 0; t1d[2] = cmx;
t1d[3] = 0; t1d[4] = 1.0/smy; t1d[5] = cmy;
t1d[6] = 0; t1d[7] = 0; t1d[8] = 1;
//
// construct system
i = 81;
while(--i >= 0) {
LtL[i] = 0.0;
}
for(i = 0; i < count; ++i) {
x = (to[i].x - cmx) * smx;
y = (to[i].y - cmy) * smy;
X = (from[i].x - cMx) * sMx;
Y = (from[i].y - cMy) * sMy;
LtL[0] += X*X;
LtL[1] += X*Y;
LtL[2] += X;
LtL[6] += X*-x*X;
LtL[7] += X*-x*Y;
LtL[8] += X*-x;
LtL[10] += Y*Y;
LtL[11] += Y;
LtL[15] += Y*-x*X;
LtL[16] += Y*-x*Y;
LtL[17] += Y*-x;
LtL[20] += 1.0;
LtL[24] += -x*X;
LtL[25] += -x*Y;
LtL[26] += -x;
LtL[30] += X*X;
LtL[31] += X*Y;
LtL[32] += X;
LtL[33] += X*-y*X;
LtL[34] += X*-y*Y;
LtL[35] += X*-y;
LtL[40] += Y*Y;
LtL[41] += Y;
LtL[42] += Y*-y*X;
LtL[43] += Y*-y*Y;
LtL[44] += Y*-y;
LtL[50] += 1.0;
LtL[51] += -y*X;
LtL[52] += -y*Y;
LtL[53] += -y;
LtL[60] += -x*X*-x*X + -y*X*-y*X;
LtL[61] += -x*X*-x*Y + -y*X*-y*Y;
LtL[62] += -x*X*-x + -y*X*-y;
LtL[70] += -x*Y*-x*Y + -y*Y*-y*Y;
LtL[71] += -x*Y*-x + -y*Y*-y;
LtL[80] += -x*-x + -y*-y;
}
//
// symmetry
for(i = 0; i < 9; ++i) {
for(j = 0; j < i; ++j)
LtL[i*9+j] = LtL[j*9+i];
}
jsfeat.linalg.eigenVV(mLtL, Evec);
md[0]=evd[72], md[1]=evd[73], md[2]=evd[74];
md[3]=evd[75], md[4]=evd[76], md[5]=evd[77];
md[6]=evd[78], md[7]=evd[79], md[8]=evd[80];
// denormalize
jsfeat.matmath.multiply_3x3(model, T1, model);
jsfeat.matmath.multiply_3x3(model, model, T0);
// set bottom right to 1.0
x = 1.0/md[8];
md[0] *= x; md[1] *= x; md[2] *= x;
md[3] *= x; md[4] *= x; md[5] *= x;
md[6] *= x; md[7] *= x; md[8] = 1.0;
return 1;
}
homography2d.prototype.error = function(from, to, model, err, count) {
var i=0;
var pt0,pt1,ww=0.0,dx=0.0,dy=0.0;
var m=model.data;
for (; i < count; ++i) {
pt0 = from[i];
pt1 = to[i];
ww = 1.0/(m[6]*pt0.x + m[7]*pt0.y + 1.0);
dx = (m[0]*pt0.x + m[1]*pt0.y + m[2])*ww - pt1.x;
dy = (m[3]*pt0.x + m[4]*pt0.y + m[5])*ww - pt1.y;
err[i] = (dx*dx + dy*dy);
}
}
homography2d.prototype.check_subset = function(from, to, count) {
// seems to reject good subsets actually
//if( have_collinear_points(from, count) || have_collinear_points(to, count) ) {
//return false;
//}
if( count == 4 ) {
var negative = 0;
var fp0=from[0],fp1=from[1],fp2=from[2],fp3=from[3];
var tp0=to[0],tp1=to[1],tp2=to[2],tp3=to[3];
// set1
var A11=fp0.x, A12=fp0.y, A13=1.0;
var A21=fp1.x, A22=fp1.y, A23=1.0;
var A31=fp2.x, A32=fp2.y, A33=1.0;
var B11=tp0.x, B12=tp0.y, B13=1.0;
var B21=tp1.x, B22=tp1.y, B23=1.0;
var B31=tp2.x, B32=tp2.y, B33=1.0;
var detA = jsfeat.matmath.determinant_3x3(A11,A12,A13, A21,A22,A23, A31,A32,A33);
var detB = jsfeat.matmath.determinant_3x3(B11,B12,B13, B21,B22,B23, B31,B32,B33);
if(detA*detB < 0) negative++;
// set2
A11=fp1.x, A12=fp1.y;
A21=fp2.x, A22=fp2.y;
A31=fp3.x, A32=fp3.y;
B11=tp1.x, B12=tp1.y;
B21=tp2.x, B22=tp2.y;
B31=tp3.x, B32=tp3.y;
detA = jsfeat.matmath.determinant_3x3(A11,A12,A13, A21,A22,A23, A31,A32,A33);
detB = jsfeat.matmath.determinant_3x3(B11,B12,B13, B21,B22,B23, B31,B32,B33);
if(detA*detB < 0) negative++;
// set3
A11=fp0.x, A12=fp0.y;
A21=fp2.x, A22=fp2.y;
A31=fp3.x, A32=fp3.y;
B11=tp0.x, B12=tp0.y;
B21=tp2.x, B22=tp2.y;
B31=tp3.x, B32=tp3.y;
detA = jsfeat.matmath.determinant_3x3(A11,A12,A13, A21,A22,A23, A31,A32,A33);
detB = jsfeat.matmath.determinant_3x3(B11,B12,B13, B21,B22,B23, B31,B32,B33);
if(detA*detB < 0) negative++;
// set4
A11=fp0.x, A12=fp0.y;
A21=fp1.x, A22=fp1.y;
A31=fp3.x, A32=fp3.y;
B11=tp0.x, B12=tp0.y;
B21=tp1.x, B22=tp1.y;
B31=tp3.x, B32=tp3.y;
detA = jsfeat.matmath.determinant_3x3(A11,A12,A13, A21,A22,A23, A31,A32,A33);
detB = jsfeat.matmath.determinant_3x3(B11,B12,B13, B21,B22,B23, B31,B32,B33);
if(detA*detB < 0) negative++;
if(negative != 0 && negative != 4) {
return false;
}
}
return true; // all good
}
return homography2d;
})();
return {
affine2d:affine2d,
homography2d:homography2d
};
})();
var ransac_params_t = (function () {
function ransac_params_t(size, thresh, eps, prob) {
if (typeof size === "undefined") { size=0; }
if (typeof thresh === "undefined") { thresh=0.5; }
if (typeof eps === "undefined") { eps=0.5; }
if (typeof prob === "undefined") { prob=0.99; }
this.size = size;
this.thresh = thresh;
this.eps = eps;
this.prob = prob;
};
ransac_params_t.prototype.update_iters = function(_eps, max_iters) {
var num = Math.log(1 - this.prob);
var denom = Math.log(1 - Math.pow(1 - _eps, this.size));
return (denom >= 0 || -num >= max_iters*(-denom) ? max_iters : Math.round(num/denom))|0;
};
return ransac_params_t;
})();
var motion_estimator = (function() {
var get_subset = function(kernel, from, to, need_cnt, max_cnt, from_sub, to_sub) {
var max_try = 1000;
var indices = [];
var i=0, j=0, ssiter=0, idx_i=0, ok=false;
for(; ssiter < max_try; ++ssiter) {
i = 0;
for (; i < need_cnt && ssiter < max_try;) {
ok = false;
idx_i = 0;
while (!ok) {
ok = true;
idx_i = indices[i] = Math.floor(Math.random() * max_cnt)|0;
for (j = 0; j < i; ++j) {
if (idx_i == indices[j])
{ ok = false; break; }
}
}
from_sub[i] = from[idx_i];
to_sub[i] = to[idx_i];
if( !kernel.check_subset( from_sub, to_sub, i+1 ) ) {
ssiter++;
continue;
}
++i;
}
break;
}
return (i == need_cnt && ssiter < max_try);
}
var find_inliers = function(kernel, model, from, to, count, thresh, err, mask) {
var numinliers = 0, i=0, f=0;
var t = thresh*thresh;
kernel.error(from, to, model, err, count);
for(; i < count; ++i) {
f = err[i] <= t;
mask[i] = f;
numinliers += f;
}
return numinliers;
}
return {
ransac: function(params, kernel, from, to, count, model, mask, max_iters) {
if (typeof max_iters === "undefined") { max_iters=1000; }
if(count < params.size) return false;
var model_points = params.size;
var niters = max_iters, iter=0;
var result = false;
var subset0 = [];
var subset1 = [];
var found = false;
var mc=model.cols,mr=model.rows;
var dt = model.type | jsfeat.C1_t;
var m_buff = jsfeat.cache.get_buffer((mc*mr)<<3);
var ms_buff = jsfeat.cache.get_buffer(count);
var err_buff = jsfeat.cache.get_buffer(count<<2);
var M = new jsfeat.matrix_t(mc, mr, dt, m_buff.data);
var curr_mask = new jsfeat.matrix_t(count, 1, jsfeat.U8C1_t, ms_buff.data);
var inliers_max = -1, numinliers=0;
var nmodels = 0;
var err = err_buff.f32;
// special case
if(count == model_points) {
if(kernel.run(from, to, M, count) <= 0) {
jsfeat.cache.put_buffer(m_buff);
jsfeat.cache.put_buffer(ms_buff);
jsfeat.cache.put_buffer(err_buff);
return false;
}
M.copy_to(model);
if(mask) {
while(--count >= 0) {
mask.data[count] = 1;
}
}
jsfeat.cache.put_buffer(m_buff);
jsfeat.cache.put_buffer(ms_buff);
jsfeat.cache.put_buffer(err_buff);
return true;
}
for (; iter < niters; ++iter) {
// generate subset
found = get_subset(kernel, from, to, model_points, count, subset0, subset1);
if(!found) {
if(iter == 0) {
jsfeat.cache.put_buffer(m_buff);
jsfeat.cache.put_buffer(ms_buff);
jsfeat.cache.put_buffer(err_buff);
return false;
}
break;
}
nmodels = kernel.run( subset0, subset1, M, model_points );
if(nmodels <= 0)
continue;
// TODO handle multimodel output
numinliers = find_inliers(kernel, M, from, to, count, params.thresh, err, curr_mask.data);
if( numinliers > Math.max(inliers_max, model_points-1) ) {
M.copy_to(model);
inliers_max = numinliers;
if(mask) curr_mask.copy_to(mask);
niters = params.update_iters((count - numinliers)/count, niters);
result = true;
}
}
jsfeat.cache.put_buffer(m_buff);
jsfeat.cache.put_buffer(ms_buff);
jsfeat.cache.put_buffer(err_buff);
return result;
},
lmeds: function(params, kernel, from, to, count, model, mask, max_iters) {
if (typeof max_iters === "undefined") { max_iters=1000; }
if(count < params.size) return false;
var model_points = params.size;
var niters = max_iters, iter=0;
var result = false;
var subset0 = [];
var subset1 = [];
var found = false;
var mc=model.cols,mr=model.rows;
var dt = model.type | jsfeat.C1_t;
var m_buff = jsfeat.cache.get_buffer((mc*mr)<<3);
var ms_buff = jsfeat.cache.get_buffer(count);
var err_buff = jsfeat.cache.get_buffer(count<<2);
var M = new jsfeat.matrix_t(mc, mr, dt, m_buff.data);
var curr_mask = new jsfeat.matrix_t(count, 1, jsfeat.U8_t|jsfeat.C1_t, ms_buff.data);
var numinliers=0;
var nmodels = 0;
var err = err_buff.f32;
var min_median = 1000000000.0, sigma=0.0, median=0.0;
params.eps = 0.45;
niters = params.update_iters(params.eps, niters);
// special case
if(count == model_points) {
if(kernel.run(from, to, M, count) <= 0) {
jsfeat.cache.put_buffer(m_buff);
jsfeat.cache.put_buffer(ms_buff);
jsfeat.cache.put_buffer(err_buff);
return false;
}
M.copy_to(model);
if(mask) {
while(--count >= 0) {
mask.data[count] = 1;
}
}
jsfeat.cache.put_buffer(m_buff);
jsfeat.cache.put_buffer(ms_buff);
jsfeat.cache.put_buffer(err_buff);
return true;
}
for (; iter < niters; ++iter) {
// generate subset
found = get_subset(kernel, from, to, model_points, count, subset0, subset1);
if(!found) {
if(iter == 0) {
jsfeat.cache.put_buffer(m_buff);
jsfeat.cache.put_buffer(ms_buff);
jsfeat.cache.put_buffer(err_buff);
return false;
}
break;
}
nmodels = kernel.run( subset0, subset1, M, model_points );
if(nmodels <= 0)
continue;
// TODO handle multimodel output
kernel.error(from, to, M, err, count);
median = jsfeat.math.median(err, 0, count-1);
if(median < min_median) {
min_median = median;
M.copy_to(model);
result = true;
}
}
if(result) {
sigma = 2.5*1.4826*(1 + 5.0/(count - model_points))*Math.sqrt(min_median);
sigma = Math.max(sigma, 0.001);
numinliers = find_inliers(kernel, model, from, to, count, sigma, err, curr_mask.data);
if(mask) curr_mask.copy_to(mask);
result = numinliers >= model_points;
}
jsfeat.cache.put_buffer(m_buff);
jsfeat.cache.put_buffer(ms_buff);
jsfeat.cache.put_buffer(err_buff);
return result;
}
};
})();
global.ransac_params_t = ransac_params_t;
global.motion_model = motion_model;
global.motion_estimator = motion_estimator;
})(jsfeat);
/**
* @author Eugene Zatepyakin / http://inspirit.ru/
*/
(function(global) {
"use strict";
//
var imgproc = (function() {
var _resample_u8 = function(src, dst, nw, nh) {
var xofs_count=0;
var ch=src.channel,w=src.cols,h=src.rows;
var src_d=src.data,dst_d=dst.data;
var scale_x = w / nw, scale_y = h / nh;
var inv_scale_256 = (scale_x * scale_y * 0x10000)|0;
var dx=0,dy=0,sx=0,sy=0,sx1=0,sx2=0,i=0,k=0,fsx1=0.0,fsx2=0.0;
var a=0,b=0,dxn=0,alpha=0,beta=0,beta1=0;
var buf_node = jsfeat.cache.get_buffer((nw*ch)<<2);
var sum_node = jsfeat.cache.get_buffer((nw*ch)<<2);
var xofs_node = jsfeat.cache.get_buffer((w*2*3)<<2);
var buf = buf_node.i32;
var sum = sum_node.i32;
var xofs = xofs_node.i32;
for (; dx < nw; dx++) {
fsx1 = dx * scale_x, fsx2 = fsx1 + scale_x;
sx1 = (fsx1 + 1.0 - 1e-6)|0, sx2 = fsx2|0;
sx1 = Math.min(sx1, w - 1);
sx2 = Math.min(sx2, w - 1);
if(sx1 > fsx1) {
xofs[k++] = (dx * ch)|0;
xofs[k++] = ((sx1 - 1)*ch)|0;
xofs[k++] = ((sx1 - fsx1) * 0x100)|0;
xofs_count++;
}
for(sx = sx1; sx < sx2; sx++){
xofs_count++;
xofs[k++] = (dx * ch)|0;
xofs[k++] = (sx * ch)|0;
xofs[k++] = 256;
}
if(fsx2 - sx2 > 1e-3) {
xofs_count++;
xofs[k++] = (dx * ch)|0;
xofs[k++] = (sx2 * ch)|0;
xofs[k++] = ((fsx2 - sx2) * 256)|0;
}
}
for (dx = 0; dx < nw * ch; dx++) {
buf[dx] = sum[dx] = 0;
}
dy = 0;
for (sy = 0; sy < h; sy++) {
a = w * sy;
for (k = 0; k < xofs_count; k++) {
dxn = xofs[k*3];
sx1 = xofs[k*3+1];
alpha = xofs[k*3+2];
for (i = 0; i < ch; i++) {
buf[dxn + i] += src_d[a+sx1+i] * alpha;
}
}
if ((dy + 1) * scale_y <= sy + 1 || sy == h - 1) {
beta = (Math.max(sy + 1 - (dy + 1) * scale_y, 0.0) * 256)|0;
beta1 = 256 - beta;
b = nw * dy;
if (beta <= 0) {
for (dx = 0; dx < nw * ch; dx++) {
dst_d[b+dx] = Math.min(Math.max((sum[dx] + buf[dx] * 256) / inv_scale_256, 0), 255);
sum[dx] = buf[dx] = 0;
}
} else {
for (dx = 0; dx < nw * ch; dx++) {
dst_d[b+dx] = Math.min(Math.max((sum[dx] + buf[dx] * beta1) / inv_scale_256, 0), 255);
sum[dx] = buf[dx] * beta;
buf[dx] = 0;
}
}
dy++;
} else {
for(dx = 0; dx < nw * ch; dx++) {
sum[dx] += buf[dx] * 256;
buf[dx] = 0;
}
}
}
jsfeat.cache.put_buffer(sum_node);
jsfeat.cache.put_buffer(buf_node);
jsfeat.cache.put_buffer(xofs_node);
}
var _resample = function(src, dst, nw, nh) {
var xofs_count=0;
var ch=src.channel,w=src.cols,h=src.rows;
var src_d=src.data,dst_d=dst.data;
var scale_x = w / nw, scale_y = h / nh;
var scale = 1.0 / (scale_x * scale_y);
var dx=0,dy=0,sx=0,sy=0,sx1=0,sx2=0,i=0,k=0,fsx1=0.0,fsx2=0.0;
var a=0,b=0,dxn=0,alpha=0.0,beta=0.0,beta1=0.0;
var buf_node = jsfeat.cache.get_buffer((nw*ch)<<2);
var sum_node = jsfeat.cache.get_buffer((nw*ch)<<2);
var xofs_node = jsfeat.cache.get_buffer((w*2*3)<<2);
var buf = buf_node.f32;
var sum = sum_node.f32;
var xofs = xofs_node.f32;
for (; dx < nw; dx++) {
fsx1 = dx * scale_x, fsx2 = fsx1 + scale_x;
sx1 = (fsx1 + 1.0 - 1e-6)|0, sx2 = fsx2|0;
sx1 = Math.min(sx1, w - 1);
sx2 = Math.min(sx2, w - 1);
if(sx1 > fsx1) {
xofs_count++;
xofs[k++] = ((sx1 - 1)*ch)|0;
xofs[k++] = (dx * ch)|0;
xofs[k++] = (sx1 - fsx1) * scale;
}
for(sx = sx1; sx < sx2; sx++){
xofs_count++;
xofs[k++] = (sx * ch)|0;
xofs[k++] = (dx * ch)|0;
xofs[k++] = scale;
}
if(fsx2 - sx2 > 1e-3) {
xofs_count++;
xofs[k++] = (sx2 * ch)|0;
xofs[k++] = (dx * ch)|0;
xofs[k++] = (fsx2 - sx2) * scale;
}
}
for (dx = 0; dx < nw * ch; dx++) {
buf[dx] = sum[dx] = 0;
}
dy = 0;
for (sy = 0; sy < h; sy++) {
a = w * sy;
for (k = 0; k < xofs_count; k++) {
sx1 = xofs[k*3]|0;
dxn = xofs[k*3+1]|0;
alpha = xofs[k*3+2];
for (i = 0; i < ch; i++) {
buf[dxn + i] += src_d[a+sx1+i] * alpha;
}
}
if ((dy + 1) * scale_y <= sy + 1 || sy == h - 1) {
beta = Math.max(sy + 1 - (dy + 1) * scale_y, 0.0);
beta1 = 1.0 - beta;
b = nw * dy;
if (Math.abs(beta) < 1e-3) {
for (dx = 0; dx < nw * ch; dx++) {
dst_d[b+dx] = sum[dx] + buf[dx];
sum[dx] = buf[dx] = 0;
}
} else {
for (dx = 0; dx < nw * ch; dx++) {
dst_d[b+dx] = sum[dx] + buf[dx] * beta1;
sum[dx] = buf[dx] * beta;
buf[dx] = 0;
}
}
dy++;
} else {
for(dx = 0; dx < nw * ch; dx++) {
sum[dx] += buf[dx];
buf[dx] = 0;
}
}
}
jsfeat.cache.put_buffer(sum_node);
jsfeat.cache.put_buffer(buf_node);
jsfeat.cache.put_buffer(xofs_node);
}
var _convol_u8 = function(buf, src_d, dst_d, w, h, filter, kernel_size, half_kernel) {
var i=0,j=0,k=0,sp=0,dp=0,sum=0,sum1=0,sum2=0,sum3=0,f0=filter[0],fk=0;
var w2=w<<1,w3=w*3,w4=w<<2;
// hor pass
for (; i < h; ++i) {
sum = src_d[sp];
for (j = 0; j < half_kernel; ++j) {
buf[j] = sum;
}
for (j = 0; j <= w-2; j+=2) {
buf[j + half_kernel] = src_d[sp+j];
buf[j + half_kernel+1] = src_d[sp+j+1];
}
for (; j < w; ++j) {
buf[j + half_kernel] = src_d[sp+j];
}
sum = src_d[sp+w-1];
for (j = w; j < half_kernel + w; ++j) {
buf[j + half_kernel] = sum;
}
for (j = 0; j <= w-4; j+=4) {
sum = buf[j] * f0,
sum1 = buf[j+1] * f0,
sum2 = buf[j+2] * f0,
sum3 = buf[j+3] * f0;
for (k = 1; k < kernel_size; ++k) {
fk = filter[k];
sum += buf[k + j] * fk;
sum1 += buf[k + j+1] * fk;
sum2 += buf[k + j+2] * fk;
sum3 += buf[k + j+3] * fk;
}
dst_d[dp+j] = Math.min(sum >> 8, 255);
dst_d[dp+j+1] = Math.min(sum1 >> 8, 255);
dst_d[dp+j+2] = Math.min(sum2 >> 8, 255);
dst_d[dp+j+3] = Math.min(sum3 >> 8, 255);
}
for (; j < w; ++j) {
sum = buf[j] * f0;
for (k = 1; k < kernel_size; ++k) {
sum += buf[k + j] * filter[k];
}
dst_d[dp+j] = Math.min(sum >> 8, 255);
}
sp += w;
dp += w;
}
// vert pass
for (i = 0; i < w; ++i) {
sum = dst_d[i];
for (j = 0; j < half_kernel; ++j) {
buf[j] = sum;
}
k = i;
for (j = 0; j <= h-2; j+=2, k+=w2) {
buf[j+half_kernel] = dst_d[k];
buf[j+half_kernel+1] = dst_d[k+w];
}
for (; j < h; ++j, k+=w) {
buf[j+half_kernel] = dst_d[k];
}
sum = dst_d[(h-1)*w + i];
for (j = h; j < half_kernel + h; ++j) {
buf[j + half_kernel] = sum;
}
dp = i;
for (j = 0; j <= h-4; j+=4, dp+=w4) {
sum = buf[j] * f0,
sum1 = buf[j+1] * f0,
sum2 = buf[j+2] * f0,
sum3 = buf[j+3] * f0;
for (k = 1; k < kernel_size; ++k) {
fk = filter[k];
sum += buf[k + j] * fk;
sum1 += buf[k + j+1] * fk;
sum2 += buf[k + j+2] * fk;
sum3 += buf[k + j+3] * fk;
}
dst_d[dp] = Math.min(sum >> 8, 255);
dst_d[dp+w] = Math.min(sum1 >> 8, 255);
dst_d[dp+w2] = Math.min(sum2 >> 8, 255);
dst_d[dp+w3] = Math.min(sum3 >> 8, 255);
}
for (; j < h; ++j, dp+=w) {
sum = buf[j] * f0;
for (k = 1; k < kernel_size; ++k) {
sum += buf[k + j] * filter[k];
}
dst_d[dp] = Math.min(sum >> 8, 255);
}
}
}
var _convol = function(buf, src_d, dst_d, w, h, filter, kernel_size, half_kernel) {
var i=0,j=0,k=0,sp=0,dp=0,sum=0.0,sum1=0.0,sum2=0.0,sum3=0.0,f0=filter[0],fk=0.0;
var w2=w<<1,w3=w*3,w4=w<<2;
// hor pass
for (; i < h; ++i) {
sum = src_d[sp];
for (j = 0; j < half_kernel; ++j) {
buf[j] = sum;
}
for (j = 0; j <= w-2; j+=2) {
buf[j + half_kernel] = src_d[sp+j];
buf[j + half_kernel+1] = src_d[sp+j+1];
}
for (; j < w; ++j) {
buf[j + half_kernel] = src_d[sp+j];
}
sum = src_d[sp+w-1];
for (j = w; j < half_kernel + w; ++j) {
buf[j + half_kernel] = sum;
}
for (j = 0; j <= w-4; j+=4) {
sum = buf[j] * f0,
sum1 = buf[j+1] * f0,
sum2 = buf[j+2] * f0,
sum3 = buf[j+3] * f0;
for (k = 1; k < kernel_size; ++k) {
fk = filter[k];
sum += buf[k + j] * fk;
sum1 += buf[k + j+1] * fk;
sum2 += buf[k + j+2] * fk;
sum3 += buf[k + j+3] * fk;
}
dst_d[dp+j] = sum;
dst_d[dp+j+1] = sum1;
dst_d[dp+j+2] = sum2;
dst_d[dp+j+3] = sum3;
}
for (; j < w; ++j) {
sum = buf[j] * f0;
for (k = 1; k < kernel_size; ++k) {
sum += buf[k + j] * filter[k];
}
dst_d[dp+j] = sum;
}
sp += w;
dp += w;
}
// vert pass
for (i = 0; i < w; ++i) {
sum = dst_d[i];
for (j = 0; j < half_kernel; ++j) {
buf[j] = sum;
}
k = i;
for (j = 0; j <= h-2; j+=2, k+=w2) {
buf[j+half_kernel] = dst_d[k];
buf[j+half_kernel+1] = dst_d[k+w];
}
for (; j < h; ++j, k+=w) {
buf[j+half_kernel] = dst_d[k];
}
sum = dst_d[(h-1)*w + i];
for (j = h; j < half_kernel + h; ++j) {
buf[j + half_kernel] = sum;
}
dp = i;
for (j = 0; j <= h-4; j+=4, dp+=w4) {
sum = buf[j] * f0,
sum1 = buf[j+1] * f0,
sum2 = buf[j+2] * f0,
sum3 = buf[j+3] * f0;
for (k = 1; k < kernel_size; ++k) {
fk = filter[k];
sum += buf[k + j] * fk;
sum1 += buf[k + j+1] * fk;
sum2 += buf[k + j+2] * fk;
sum3 += buf[k + j+3] * fk;
}
dst_d[dp] = sum;
dst_d[dp+w] = sum1;
dst_d[dp+w2] = sum2;
dst_d[dp+w3] = sum3;
}
for (; j < h; ++j, dp+=w) {
sum = buf[j] * f0;
for (k = 1; k < kernel_size; ++k) {
sum += buf[k + j] * filter[k];
}
dst_d[dp] = sum;
}
}
}
return {
// TODO: add support for RGB/BGR order
// for raw arrays
grayscale: function(src, w, h, dst, code) {
// this is default image data representation in browser
if (typeof code === "undefined") { code = jsfeat.COLOR_RGBA2GRAY; }
var x=0, y=0, i=0, j=0, ir=0,jr=0;
var coeff_r = 4899, coeff_g = 9617, coeff_b = 1868, cn = 4;
if(code == jsfeat.COLOR_BGRA2GRAY || code == jsfeat.COLOR_BGR2GRAY) {
coeff_r = 1868;
coeff_b = 4899;
}
if(code == jsfeat.COLOR_RGB2GRAY || code == jsfeat.COLOR_BGR2GRAY) {
cn = 3;
}
var cn2 = cn<<1, cn3 = (cn*3)|0;
dst.resize(w, h, 1);
var dst_u8 = dst.data;
for(y = 0; y < h; ++y, j+=w, i+=w*cn) {
for(x = 0, ir = i, jr = j; x <= w-4; x+=4, ir+=cn<<2, jr+=4) {
dst_u8[jr] = (src[ir] * coeff_r + src[ir+1] * coeff_g + src[ir+2] * coeff_b + 8192) >> 14;
dst_u8[jr + 1] = (src[ir+cn] * coeff_r + src[ir+cn+1] * coeff_g + src[ir+cn+2] * coeff_b + 8192) >> 14;
dst_u8[jr + 2] = (src[ir+cn2] * coeff_r + src[ir+cn2+1] * coeff_g + src[ir+cn2+2] * coeff_b + 8192) >> 14;
dst_u8[jr + 3] = (src[ir+cn3] * coeff_r + src[ir+cn3+1] * coeff_g + src[ir+cn3+2] * coeff_b + 8192) >> 14;
}
for (; x < w; ++x, ++jr, ir+=cn) {
dst_u8[jr] = (src[ir] * coeff_r + src[ir+1] * coeff_g + src[ir+2] * coeff_b + 8192) >> 14;
}
}
},
// derived from CCV library
resample: function(src, dst, nw, nh) {
var h=src.rows,w=src.cols;
if (h > nh && w > nw) {
dst.resize(nw, nh, src.channel);
// using the fast alternative (fix point scale, 0x100 to avoid overflow)
if (src.type&jsfeat.U8_t && dst.type&jsfeat.U8_t && h * w / (nh * nw) < 0x100) {
_resample_u8(src, dst, nw, nh);
} else {
_resample(src, dst, nw, nh);
}
}
},
box_blur_gray: function(src, dst, radius, options) {
if (typeof options === "undefined") { options = 0; }
var w=src.cols, h=src.rows, h2=h<<1, w2=w<<1;
var i=0,x=0,y=0,end=0;
var windowSize = ((radius << 1) + 1)|0;
var radiusPlusOne = (radius + 1)|0, radiusPlus2 = (radiusPlusOne+1)|0;
var scale = options&jsfeat.BOX_BLUR_NOSCALE ? 1 : (1.0 / (windowSize*windowSize));
var tmp_buff = jsfeat.cache.get_buffer((w*h)<<2);
var sum=0, dstIndex=0, srcIndex = 0, nextPixelIndex=0, previousPixelIndex=0;
var data_i32 = tmp_buff.i32; // to prevent overflow
var data_u8 = src.data;
var hold=0;
dst.resize(w, h, src.channel);
// first pass
// no need to scale
//data_u8 = src.data;
//data_i32 = tmp;
for (y = 0; y < h; ++y) {
dstIndex = y;
sum = radiusPlusOne * data_u8[srcIndex];
for(i = (srcIndex+1)|0, end=(srcIndex+radius)|0; i <= end; ++i) {
sum += data_u8[i];
}
nextPixelIndex = (srcIndex + radiusPlusOne)|0;
previousPixelIndex = srcIndex;
hold = data_u8[previousPixelIndex];
for(x = 0; x < radius; ++x, dstIndex += h) {
data_i32[dstIndex] = sum;
sum += data_u8[nextPixelIndex]- hold;
nextPixelIndex ++;
}
for(; x < w-radiusPlus2; x+=2, dstIndex += h2) {
data_i32[dstIndex] = sum;
sum += data_u8[nextPixelIndex]- data_u8[previousPixelIndex];
data_i32[dstIndex+h] = sum;
sum += data_u8[nextPixelIndex+1]- data_u8[previousPixelIndex+1];
nextPixelIndex +=2;
previousPixelIndex +=2;
}
for(; x < w-radiusPlusOne; ++x, dstIndex += h) {
data_i32[dstIndex] = sum;
sum += data_u8[nextPixelIndex]- data_u8[previousPixelIndex];
nextPixelIndex ++;
previousPixelIndex ++;
}
hold = data_u8[nextPixelIndex-1];
for(; x < w; ++x, dstIndex += h) {
data_i32[dstIndex] = sum;
sum += hold- data_u8[previousPixelIndex];
previousPixelIndex ++;
}
srcIndex += w;
}
//
// second pass
srcIndex = 0;
//data_i32 = tmp; // this is a transpose
data_u8 = dst.data;
// dont scale result
if(scale == 1) {
for (y = 0; y < w; ++y) {
dstIndex = y;
sum = radiusPlusOne * data_i32[srcIndex];
for(i = (srcIndex+1)|0, end=(srcIndex+radius)|0; i <= end; ++i) {
sum += data_i32[i];
}
nextPixelIndex = srcIndex + radiusPlusOne;
previousPixelIndex = srcIndex;
hold = data_i32[previousPixelIndex];
for(x = 0; x < radius; ++x, dstIndex += w) {
data_u8[dstIndex] = sum;
sum += data_i32[nextPixelIndex]- hold;
nextPixelIndex ++;
}
for(; x < h-radiusPlus2; x+=2, dstIndex += w2) {
data_u8[dstIndex] = sum;
sum += data_i32[nextPixelIndex]- data_i32[previousPixelIndex];
data_u8[dstIndex+w] = sum;
sum += data_i32[nextPixelIndex+1]- data_i32[previousPixelIndex+1];
nextPixelIndex +=2;
previousPixelIndex +=2;
}
for(; x < h-radiusPlusOne; ++x, dstIndex += w) {
data_u8[dstIndex] = sum;
sum += data_i32[nextPixelIndex]- data_i32[previousPixelIndex];
nextPixelIndex ++;
previousPixelIndex ++;
}
hold = data_i32[nextPixelIndex-1];
for(; x < h; ++x, dstIndex += w) {
data_u8[dstIndex] = sum;
sum += hold- data_i32[previousPixelIndex];
previousPixelIndex ++;
}
srcIndex += h;
}
} else {
for (y = 0; y < w; ++y) {
dstIndex = y;
sum = radiusPlusOne * data_i32[srcIndex];
for(i = (srcIndex+1)|0, end=(srcIndex+radius)|0; i <= end; ++i) {
sum += data_i32[i];
}
nextPixelIndex = srcIndex + radiusPlusOne;
previousPixelIndex = srcIndex;
hold = data_i32[previousPixelIndex];
for(x = 0; x < radius; ++x, dstIndex += w) {
data_u8[dstIndex] = sum*scale;
sum += data_i32[nextPixelIndex]- hold;
nextPixelIndex ++;
}
for(; x < h-radiusPlus2; x+=2, dstIndex += w2) {
data_u8[dstIndex] = sum*scale;
sum += data_i32[nextPixelIndex]- data_i32[previousPixelIndex];
data_u8[dstIndex+w] = sum*scale;
sum += data_i32[nextPixelIndex+1]- data_i32[previousPixelIndex+1];
nextPixelIndex +=2;
previousPixelIndex +=2;
}
for(; x < h-radiusPlusOne; ++x, dstIndex += w) {
data_u8[dstIndex] = sum*scale;
sum += data_i32[nextPixelIndex]- data_i32[previousPixelIndex];
nextPixelIndex ++;
previousPixelIndex ++;
}
hold = data_i32[nextPixelIndex-1];
for(; x < h; ++x, dstIndex += w) {
data_u8[dstIndex] = sum*scale;
sum += hold- data_i32[previousPixelIndex];
previousPixelIndex ++;
}
srcIndex += h;
}
}
jsfeat.cache.put_buffer(tmp_buff);
},
gaussian_blur: function(src, dst, kernel_size, sigma) {
if (typeof sigma === "undefined") { sigma = 0.0; }
if (typeof kernel_size === "undefined") { kernel_size = 0; }
kernel_size = kernel_size == 0 ? (Math.max(1, (4.0 * sigma + 1.0 - 1e-8)) * 2 + 1)|0 : kernel_size;
var half_kernel = kernel_size >> 1;
var w = src.cols, h = src.rows;
var data_type = src.type, is_u8 = data_type&jsfeat.U8_t;
dst.resize(w, h, src.channel);
var src_d = src.data, dst_d = dst.data;
var buf,filter,buf_sz=(kernel_size + Math.max(h, w))|0;
var buf_node = jsfeat.cache.get_buffer(buf_sz<<2);
var filt_node = jsfeat.cache.get_buffer(kernel_size<<2);
if (is_u8) {
buf = buf_node.i32;
filter = filt_node.i32;
} else if(data_type&jsfeat.S32_t) {
buf = buf_node.i32;
filter = filt_node.f32;
} else if(data_type&jsfeat.U16_t) {
buf = buf_node.i32;
filter = filt_node.f32;
} else {
buf = buf_node.f32;
filter = filt_node.f32;
}
jsfeat.math.get_gaussian_kernel(kernel_size, sigma, filter, data_type);
if(is_u8) {
_convol_u8(buf, src_d, dst_d, w, h, filter, kernel_size, half_kernel);
} else {
_convol(buf, src_d, dst_d, w, h, filter, kernel_size, half_kernel);
}
jsfeat.cache.put_buffer(buf_node);
jsfeat.cache.put_buffer(filt_node);
},
hough_transform: function( img, rho_res, theta_res, threshold ) {
var image = img.data;
var width = img.cols;
var height = img.rows;
var step = width;
min_theta = 0.0;
max_theta = Math.PI;
numangle = Math.round((max_theta - min_theta) / theta_res);
numrho = Math.round(((width + height) * 2 + 1) / rho_res);
irho = 1.0 / rho_res;
var accum = new Int32Array((numangle+2) * (numrho+2)); //typed arrays are initialized to 0
var tabSin = new Float32Array(numangle);
var tabCos = new Float32Array(numangle);
var n=0;
var ang = min_theta;
for(; n < numangle; n++ ) {
tabSin[n] = Math.sin(ang) * irho;
tabCos[n] = Math.cos(ang) * irho;
ang += theta_res
}
// stage 1. fill accumulator
for( var i = 0; i < height; i++ ) {
for( var j = 0; j < width; j++ ) {
if( image[i * step + j] != 0 ) {
//console.log(r, (n+1) * (numrho+2) + r+1, tabCos[n], tabSin[n]);
for(var n = 0; n < numangle; n++ ) {
var r = Math.round( j * tabCos[n] + i * tabSin[n] );
r += (numrho - 1) / 2;
accum[(n+1) * (numrho+2) + r+1] += 1;
}
}
}
}
// stage 2. find local maximums
//TODO: Consider making a vector class that uses typed arrays
_sort_buf = new Array();
for(var r = 0; r < numrho; r++ ) {
for(var n = 0; n < numangle; n++ ) {
var base = (n+1) * (numrho+2) + r+1;
if( accum[base] > threshold &&
accum[base] > accum[base - 1] && accum[base] >= accum[base + 1] &&
accum[base] > accum[base - numrho - 2] && accum[base] >= accum[base + numrho + 2] ) {
_sort_buf.push(base);
}
}
}
// stage 3. sort the detected lines by accumulator value
_sort_buf.sort(function(l1, l2) {
return accum[l1] > accum[l2] || (accum[l1] == accum[l2] && l1 < l2);
});
// stage 4. store the first min(total,linesMax) lines to the output buffer
linesMax = Math.min(numangle*numrho, _sort_buf.length);
scale = 1.0 / (numrho+2);
lines = new Array();
for( var i = 0; i < linesMax; i++ ) {
var idx = _sort_buf[i];
var n = Math.floor(idx*scale) - 1;
var r = idx - (n+1)*(numrho+2) - 1;
var lrho = (r - (numrho - 1)*0.5) * rho_res;
var langle = n * theta_res;
lines.push([lrho, langle]);
}
return lines;
},
// assume we always need it for u8 image
pyrdown: function(src, dst, sx, sy) {
// this is needed for bbf
if (typeof sx === "undefined") { sx = 0; }
if (typeof sy === "undefined") { sy = 0; }
var w = src.cols, h = src.rows;
var w2 = w >> 1, h2 = h >> 1;
var _w2 = w2 - (sx << 1), _h2 = h2 - (sy << 1);
var x=0,y=0,sptr=sx+sy*w,sline=0,dptr=0,dline=0;
dst.resize(w2, h2, src.channel);
var src_d = src.data, dst_d = dst.data;
for(y = 0; y < _h2; ++y) {
sline = sptr;
dline = dptr;
for(x = 0; x <= _w2-2; x+=2, dline+=2, sline += 4) {
dst_d[dline] = (src_d[sline] + src_d[sline+1] +
src_d[sline+w] + src_d[sline+w+1] + 2) >> 2;
dst_d[dline+1] = (src_d[sline+2] + src_d[sline+3] +
src_d[sline+w+2] + src_d[sline+w+3] + 2) >> 2;
}
for(; x < _w2; ++x, ++dline, sline += 2) {
dst_d[dline] = (src_d[sline] + src_d[sline+1] +
src_d[sline+w] + src_d[sline+w+1] + 2) >> 2;
}
sptr += w << 1;
dptr += w2;
}
},
// dst: [gx,gy,...]
scharr_derivatives: function(src, dst) {
var w = src.cols, h = src.rows;
var dstep = w<<1,x=0,y=0,x1=0,a,b,c,d,e,f;
var srow0=0,srow1=0,srow2=0,drow=0;
var trow0,trow1;
dst.resize(w, h, 2); // 2 channel output gx, gy
var img = src.data, gxgy=dst.data;
var buf0_node = jsfeat.cache.get_buffer((w+2)<<2);
var buf1_node = jsfeat.cache.get_buffer((w+2)<<2);
if(src.type&jsfeat.U8_t || src.type&jsfeat.S32_t) {
trow0 = buf0_node.i32;
trow1 = buf1_node.i32;
} else {
trow0 = buf0_node.f32;
trow1 = buf1_node.f32;
}
for(; y < h; ++y, srow1+=w) {
srow0 = ((y > 0 ? y-1 : 1)*w)|0;
srow2 = ((y < h-1 ? y+1 : h-2)*w)|0;
drow = (y*dstep)|0;
// do vertical convolution
for(x = 0, x1 = 1; x <= w-2; x+=2, x1+=2) {
a = img[srow0+x], b = img[srow2+x];
trow0[x1] = ( (a + b)*3 + (img[srow1+x])*10 );
trow1[x1] = ( b - a );
//
a = img[srow0+x+1], b = img[srow2+x+1];
trow0[x1+1] = ( (a + b)*3 + (img[srow1+x+1])*10 );
trow1[x1+1] = ( b - a );
}
for(; x < w; ++x, ++x1) {
a = img[srow0+x], b = img[srow2+x];
trow0[x1] = ( (a + b)*3 + (img[srow1+x])*10 );
trow1[x1] = ( b - a );
}
// make border
x = (w + 1)|0;
trow0[0] = trow0[1]; trow0[x] = trow0[w];
trow1[0] = trow1[1]; trow1[x] = trow1[w];
// do horizontal convolution, interleave the results and store them
for(x = 0; x <= w-4; x+=4) {
a = trow1[x+2], b = trow1[x+1], c = trow1[x+3], d = trow1[x+4],
e = trow0[x+2], f = trow0[x+3];
gxgy[drow++] = ( e - trow0[x] );
gxgy[drow++] = ( (a + trow1[x])*3 + b*10 );
gxgy[drow++] = ( f - trow0[x+1] );
gxgy[drow++] = ( (c + b)*3 + a*10 );
gxgy[drow++] = ( (trow0[x+4] - e) );
gxgy[drow++] = ( ((d + a)*3 + c*10) );
gxgy[drow++] = ( (trow0[x+5] - f) );
gxgy[drow++] = ( ((trow1[x+5] + c)*3 + d*10) );
}
for(; x < w; ++x) {
gxgy[drow++] = ( (trow0[x+2] - trow0[x]) );
gxgy[drow++] = ( ((trow1[x+2] + trow1[x])*3 + trow1[x+1]*10) );
}
}
jsfeat.cache.put_buffer(buf0_node);
jsfeat.cache.put_buffer(buf1_node);
},
// compute gradient using Sobel kernel [1 2 1] * [-1 0 1]^T
// dst: [gx,gy,...]
sobel_derivatives: function(src, dst) {
var w = src.cols, h = src.rows;
var dstep = w<<1,x=0,y=0,x1=0,a,b,c,d,e,f;
var srow0=0,srow1=0,srow2=0,drow=0;
var trow0,trow1;
dst.resize(w, h, 2); // 2 channel output gx, gy
var img = src.data, gxgy=dst.data;
var buf0_node = jsfeat.cache.get_buffer((w+2)<<2);
var buf1_node = jsfeat.cache.get_buffer((w+2)<<2);
if(src.type&jsfeat.U8_t || src.type&jsfeat.S32_t) {
trow0 = buf0_node.i32;
trow1 = buf1_node.i32;
} else {
trow0 = buf0_node.f32;
trow1 = buf1_node.f32;
}
for(; y < h; ++y, srow1+=w) {
srow0 = ((y > 0 ? y-1 : 1)*w)|0;
srow2 = ((y < h-1 ? y+1 : h-2)*w)|0;
drow = (y*dstep)|0;
// do vertical convolution
for(x = 0, x1 = 1; x <= w-2; x+=2, x1+=2) {
a = img[srow0+x], b = img[srow2+x];
trow0[x1] = ( (a + b) + (img[srow1+x]*2) );
trow1[x1] = ( b - a );
//
a = img[srow0+x+1], b = img[srow2+x+1];
trow0[x1+1] = ( (a + b) + (img[srow1+x+1]*2) );
trow1[x1+1] = ( b - a );
}
for(; x < w; ++x, ++x1) {
a = img[srow0+x], b = img[srow2+x];
trow0[x1] = ( (a + b) + (img[srow1+x]*2) );
trow1[x1] = ( b - a );
}
// make border
x = (w + 1)|0;
trow0[0] = trow0[1]; trow0[x] = trow0[w];
trow1[0] = trow1[1]; trow1[x] = trow1[w];
// do horizontal convolution, interleave the results and store them
for(x = 0; x <= w-4; x+=4) {
a = trow1[x+2], b = trow1[x+1], c = trow1[x+3], d = trow1[x+4],
e = trow0[x+2], f = trow0[x+3];
gxgy[drow++] = ( e - trow0[x] );
gxgy[drow++] = ( a + trow1[x] + b*2 );
gxgy[drow++] = ( f - trow0[x+1] );
gxgy[drow++] = ( c + b + a*2 );
gxgy[drow++] = ( trow0[x+4] - e );
gxgy[drow++] = ( d + a + c*2 );
gxgy[drow++] = ( trow0[x+5] - f );
gxgy[drow++] = ( trow1[x+5] + c + d*2 );
}
for(; x < w; ++x) {
gxgy[drow++] = ( trow0[x+2] - trow0[x] );
gxgy[drow++] = ( trow1[x+2] + trow1[x] + trow1[x+1]*2 );
}
}
jsfeat.cache.put_buffer(buf0_node);
jsfeat.cache.put_buffer(buf1_node);
},
// please note:
// dst_(type) size should be cols = src.cols+1, rows = src.rows+1
compute_integral_image: function(src, dst_sum, dst_sqsum, dst_tilted) {
var w0=src.cols|0,h0=src.rows|0,src_d=src.data;
var w1=(w0+1)|0;
var s=0,s2=0,p=0,pup=0,i=0,j=0,v=0,k=0;
if(dst_sum && dst_sqsum) {
// fill first row with zeros
for(; i < w1; ++i) {
dst_sum[i] = 0, dst_sqsum[i] = 0;
}
p = (w1+1)|0, pup = 1;
for(i = 0, k = 0; i < h0; ++i, ++p, ++pup) {
s = s2 = 0;
for(j = 0; j <= w0-2; j+=2, k+=2, p+=2, pup+=2) {
v = src_d[k];
s += v, s2 += v*v;
dst_sum[p] = dst_sum[pup] + s;
dst_sqsum[p] = dst_sqsum[pup] + s2;
v = src_d[k+1];
s += v, s2 += v*v;
dst_sum[p+1] = dst_sum[pup+1] + s;
dst_sqsum[p+1] = dst_sqsum[pup+1] + s2;
}
for(; j < w0; ++j, ++k, ++p, ++pup) {
v = src_d[k];
s += v, s2 += v*v;
dst_sum[p] = dst_sum[pup] + s;
dst_sqsum[p] = dst_sqsum[pup] + s2;
}
}
} else if(dst_sum) {
// fill first row with zeros
for(; i < w1; ++i) {
dst_sum[i] = 0;
}
p = (w1+1)|0, pup = 1;
for(i = 0, k = 0; i < h0; ++i, ++p, ++pup) {
s = 0;
for(j = 0; j <= w0-2; j+=2, k+=2, p+=2, pup+=2) {
s += src_d[k];
dst_sum[p] = dst_sum[pup] + s;
s += src_d[k+1];
dst_sum[p+1] = dst_sum[pup+1] + s;
}
for(; j < w0; ++j, ++k, ++p, ++pup) {
s += src_d[k];
dst_sum[p] = dst_sum[pup] + s;
}
}
} else if(dst_sqsum) {
// fill first row with zeros
for(; i < w1; ++i) {
dst_sqsum[i] = 0;
}
p = (w1+1)|0, pup = 1;
for(i = 0, k = 0; i < h0; ++i, ++p, ++pup) {
s2 = 0;
for(j = 0; j <= w0-2; j+=2, k+=2, p+=2, pup+=2) {
v = src_d[k];
s2 += v*v;
dst_sqsum[p] = dst_sqsum[pup] + s2;
v = src_d[k+1];
s2 += v*v;
dst_sqsum[p+1] = dst_sqsum[pup+1] + s2;
}
for(; j < w0; ++j, ++k, ++p, ++pup) {
v = src_d[k];
s2 += v*v;
dst_sqsum[p] = dst_sqsum[pup] + s2;
}
}
}
if(dst_tilted) {
// fill first row with zeros
for(i = 0; i < w1; ++i) {
dst_tilted[i] = 0;
}
// diagonal
p = (w1+1)|0, pup = 0;
for(i = 0, k = 0; i < h0; ++i, ++p, ++pup) {
for(j = 0; j <= w0-2; j+=2, k+=2, p+=2, pup+=2) {
dst_tilted[p] = src_d[k] + dst_tilted[pup];
dst_tilted[p+1] = src_d[k+1] + dst_tilted[pup+1];
}
for(; j < w0; ++j, ++k, ++p, ++pup) {
dst_tilted[p] = src_d[k] + dst_tilted[pup];
}
}
// diagonal
p = (w1+w0)|0, pup = w0;
for(i = 0; i < h0; ++i, p+=w1, pup+=w1) {
dst_tilted[p] += dst_tilted[pup];
}
for(j = w0-1; j > 0; --j) {
p = j+h0*w1, pup=p-w1;
for(i = h0; i > 0; --i, p-=w1, pup-=w1) {
dst_tilted[p] += dst_tilted[pup] + dst_tilted[pup+1];
}
}
}
},
equalize_histogram: function(src, dst) {
var w=src.cols,h=src.rows,src_d=src.data;
dst.resize(w, h, src.channel);
var dst_d=dst.data,size=w*h;
var i=0,prev=0,hist0,norm;
var hist0_node = jsfeat.cache.get_buffer(256<<2);
hist0 = hist0_node.i32;
for(; i < 256; ++i) hist0[i] = 0;
for (i = 0; i < size; ++i) {
++hist0[src_d[i]];
}
prev = hist0[0];
for (i = 1; i < 256; ++i) {
prev = hist0[i] += prev;
}
norm = 255 / size;
for (i = 0; i < size; ++i) {
dst_d[i] = (hist0[src_d[i]] * norm + 0.5)|0;
}
jsfeat.cache.put_buffer(hist0_node);
},
canny: function(src, dst, low_thresh, high_thresh) {
var w=src.cols,h=src.rows,src_d=src.data;
dst.resize(w, h, src.channel);
var dst_d=dst.data;
var i=0,j=0,grad=0,w2=w<<1,_grad=0,suppress=0,f=0,x=0,y=0,s=0;
var tg22x=0,tg67x=0;
// cache buffers
var dxdy_node = jsfeat.cache.get_buffer((h * w2)<<2);
var buf_node = jsfeat.cache.get_buffer((3 * (w + 2))<<2);
var map_node = jsfeat.cache.get_buffer(((h+2) * (w + 2))<<2);
var stack_node = jsfeat.cache.get_buffer((h * w)<<2);
var buf = buf_node.i32;
var map = map_node.i32;
var stack = stack_node.i32;
var dxdy = dxdy_node.i32;
var dxdy_m = new jsfeat.matrix_t(w, h, jsfeat.S32C2_t, dxdy_node.data);
var row0=1,row1=(w+2+1)|0,row2=(2*(w+2)+1)|0,map_w=(w+2)|0,map_i=(map_w+1)|0,stack_i=0;
this.sobel_derivatives(src, dxdy_m);
if(low_thresh > high_thresh) {
i = low_thresh;
low_thresh = high_thresh;
high_thresh = i;
}
i = (3 * (w + 2))|0;
while(--i>=0) {
buf[i] = 0;
}
i = ((h+2) * (w + 2))|0;
while(--i>=0) {
map[i] = 0;
}
for (; j < w; ++j, grad+=2) {
//buf[row1+j] = Math.abs(dxdy[grad]) + Math.abs(dxdy[grad+1]);
x = dxdy[grad], y = dxdy[grad+1];
//buf[row1+j] = x*x + y*y;
buf[row1+j] = ((x ^ (x >> 31)) - (x >> 31)) + ((y ^ (y >> 31)) - (y >> 31));
}
for(i=1; i <= h; ++i, grad+=w2) {
if(i == h) {
j = row2+w;
while(--j>=row2) {
buf[j] = 0;
}
} else {
for (j = 0; j < w; j++) {
//buf[row2+j] = Math.abs(dxdy[grad+(j<<1)]) + Math.abs(dxdy[grad+(j<<1)+1]);
x = dxdy[grad+(j<<1)], y = dxdy[grad+(j<<1)+1];
//buf[row2+j] = x*x + y*y;
buf[row2+j] = ((x ^ (x >> 31)) - (x >> 31)) + ((y ^ (y >> 31)) - (y >> 31));
}
}
_grad = (grad - w2)|0;
map[map_i-1] = 0;
suppress = 0;
for(j = 0; j < w; ++j, _grad+=2) {
f = buf[row1+j];
if (f > low_thresh) {
x = dxdy[_grad];
y = dxdy[_grad+1];
s = x ^ y;
// seems ot be faster than Math.abs
x = ((x ^ (x >> 31)) - (x >> 31))|0;
y = ((y ^ (y >> 31)) - (y >> 31))|0;
//x * tan(22.5) x * tan(67.5) == 2 * x + x * tan(22.5)
tg22x = x * 13573;
tg67x = tg22x + ((x + x) << 15);
y <<= 15;
if (y < tg22x) {
if (f > buf[row1+j-1] && f >= buf[row1+j+1]) {
if (f > high_thresh && !suppress && map[map_i+j-map_w] != 2) {
map[map_i+j] = 2;
suppress = 1;
stack[stack_i++] = map_i + j;
} else {
map[map_i+j] = 1;
}
continue;
}
} else if (y > tg67x) {
if (f > buf[row0+j] && f >= buf[row2+j]) {
if (f > high_thresh && !suppress && map[map_i+j-map_w] != 2) {
map[map_i+j] = 2;
suppress = 1;
stack[stack_i++] = map_i + j;
} else {
map[map_i+j] = 1;
}
continue;
}
} else {
s = s < 0 ? -1 : 1;
if (f > buf[row0+j-s] && f > buf[row2+j+s]) {
if (f > high_thresh && !suppress && map[map_i+j-map_w] != 2) {
map[map_i+j] = 2;
suppress = 1;
stack[stack_i++] = map_i + j;
} else {
map[map_i+j] = 1;
}
continue;
}
}
}
map[map_i+j] = 0;
suppress = 0;
}
map[map_i+w] = 0;
map_i += map_w;
j = row0;
row0 = row1;
row1 = row2;
row2 = j;
}
j = map_i - map_w - 1;
for(i = 0; i < map_w; ++i, ++j) {
map[j] = 0;
}
// path following
while(stack_i > 0) {
map_i = stack[--stack_i];
map_i -= map_w+1;
if(map[map_i] == 1) map[map_i] = 2, stack[stack_i++] = map_i;
map_i += 1;
if(map[map_i] == 1) map[map_i] = 2, stack[stack_i++] = map_i;
map_i += 1;
if(map[map_i] == 1) map[map_i] = 2, stack[stack_i++] = map_i;
map_i += map_w;
if(map[map_i] == 1) map[map_i] = 2, stack[stack_i++] = map_i;
map_i -= 2;
if(map[map_i] == 1) map[map_i] = 2, stack[stack_i++] = map_i;
map_i += map_w;
if(map[map_i] == 1) map[map_i] = 2, stack[stack_i++] = map_i;
map_i += 1;
if(map[map_i] == 1) map[map_i] = 2, stack[stack_i++] = map_i;
map_i += 1;
if(map[map_i] == 1) map[map_i] = 2, stack[stack_i++] = map_i;
}
map_i = map_w + 1;
row0 = 0;
for(i = 0; i < h; ++i, map_i+=map_w) {
for(j = 0; j < w; ++j) {
dst_d[row0++] = (map[map_i+j] == 2) * 0xff;
}
}
// free buffers
jsfeat.cache.put_buffer(dxdy_node);
jsfeat.cache.put_buffer(buf_node);
jsfeat.cache.put_buffer(map_node);
jsfeat.cache.put_buffer(stack_node);
},
// transform is 3x3 matrix_t
warp_perspective: function(src, dst, transform, fill_value) {
if (typeof fill_value === "undefined") { fill_value = 0; }
var src_width=src.cols|0, src_height=src.rows|0, dst_width=dst.cols|0, dst_height=dst.rows|0;
var src_d=src.data, dst_d=dst.data;
var x=0,y=0,off=0,ixs=0,iys=0,xs=0.0,ys=0.0,xs0=0.0,ys0=0.0,ws=0.0,sc=0.0,a=0.0,b=0.0,p0=0.0,p1=0.0;
var td=transform.data;
var m00=td[0],m01=td[1],m02=td[2],
m10=td[3],m11=td[4],m12=td[5],
m20=td[6],m21=td[7],m22=td[8];
for(var dptr = 0; y < dst_height; ++y) {
xs0 = m01 * y + m02,
ys0 = m11 * y + m12,
ws = m21 * y + m22;
for(x = 0; x < dst_width; ++x, ++dptr, xs0+=m00, ys0+=m10, ws+=m20) {
sc = 1.0 / ws;
xs = xs0 * sc, ys = ys0 * sc;
ixs = xs | 0, iys = ys | 0;
if(xs > 0 && ys > 0 && ixs < (src_width - 1) && iys < (src_height - 1)) {
a = Math.max(xs - ixs, 0.0);
b = Math.max(ys - iys, 0.0);
off = (src_width*iys + ixs)|0;
p0 = src_d[off] + a * (src_d[off+1] - src_d[off]);
p1 = src_d[off+src_width] + a * (src_d[off+src_width+1] - src_d[off+src_width]);
dst_d[dptr] = p0 + b * (p1 - p0);
}
else dst_d[dptr] = fill_value;
}
}
},
// transform is 3x3 or 2x3 matrix_t only first 6 values referenced
warp_affine: function(src, dst, transform, fill_value) {
if (typeof fill_value === "undefined") { fill_value = 0; }
var src_width=src.cols, src_height=src.rows, dst_width=dst.cols, dst_height=dst.rows;
var src_d=src.data, dst_d=dst.data;
var x=0,y=0,off=0,ixs=0,iys=0,xs=0.0,ys=0.0,a=0.0,b=0.0,p0=0.0,p1=0.0;
var td=transform.data;
var m00=td[0],m01=td[1],m02=td[2],
m10=td[3],m11=td[4],m12=td[5];
for(var dptr = 0; y < dst_height; ++y) {
xs = m01 * y + m02;
ys = m11 * y + m12;
for(x = 0; x < dst_width; ++x, ++dptr, xs+=m00, ys+=m10) {
ixs = xs | 0; iys = ys | 0;
if(ixs >= 0 && iys >= 0 && ixs < (src_width - 1) && iys < (src_height - 1)) {
a = xs - ixs;
b = ys - iys;
off = src_width*iys + ixs;
p0 = src_d[off] + a * (src_d[off+1] - src_d[off]);
p1 = src_d[off+src_width] + a * (src_d[off+src_width+1] - src_d[off+src_width]);
dst_d[dptr] = p0 + b * (p1 - p0);
}
else dst_d[dptr] = fill_value;
}
}
},
// Basic RGB Skin detection filter
// from http://popscan.blogspot.fr/2012/08/skin-detection-in-digital-images.html
skindetector: function(src,dst) {
var r,g,b,j;
var i = src.width*src.height;
while(i--){
j = i*4;
r = src.data[j];
g = src.data[j+1];
b = src.data[j+2];
if((r>95)&&(g>40)&&(b>20)
&&(r>g)&&(r>b)
&&(r-Math.min(g,b)>15)
&&(Math.abs(r-g)>15)){
dst[i] = 255;
} else {
dst[i] = 0;
}
}
}
};
})();
global.imgproc = imgproc;
})(jsfeat);
/**
* @author Eugene Zatepyakin / http://inspirit.ru/
*
* This is FAST corner detector, contributed to OpenCV by the author, Edward Rosten.
*/
/*
The references are:
* Machine learning for high-speed corner detection,
E. Rosten and T. Drummond, ECCV 2006
* Faster and better: A machine learning approach to corner detection
E. Rosten, R. Porter and T. Drummond, PAMI, 2009
*/
(function(global) {
"use strict";
//
var fast_corners = (function() {
var offsets16 = new Int32Array([0, 3, 1, 3, 2, 2, 3, 1, 3, 0, 3, -1, 2, -2, 1, -3, 0, -3, -1, -3, -2, -2, -3, -1, -3, 0, -3, 1, -2, 2, -1, 3]);
var threshold_tab = new Uint8Array(512);
var pixel_off = new Int32Array(25);
var score_diff = new Int32Array(25);
// private functions
var _cmp_offsets = function(pixel, step, pattern_size) {
var k = 0;
var offsets = offsets16;
for( ; k < pattern_size; ++k ) {
pixel[k] = offsets[k<<1] + offsets[(k<<1)+1] * step;
}
for( ; k < 25; ++k ) {
pixel[k] = pixel[k - pattern_size];
}
},
_cmp_score_16 = function(src, off, pixel, d, threshold) {
var N = 25, k = 0, v = src[off];
var a0 = threshold,a=0,b0=0,b=0;
for( ; k < N; ++k ) {
d[k] = v - src[off+pixel[k]];
}
for( k = 0; k < 16; k += 2 ) {
a = Math.min(d[k+1], d[k+2]);
a = Math.min(a, d[k+3]);
if( a <= a0 ) continue;
a = Math.min(a, d[k+4]);
a = Math.min(a, d[k+5]);
a = Math.min(a, d[k+6]);
a = Math.min(a, d[k+7]);
a = Math.min(a, d[k+8]);
a0 = Math.max(a0, Math.min(a, d[k]));
a0 = Math.max(a0, Math.min(a, d[k+9]));
}
b0 = -a0;
for( k = 0; k < 16; k += 2 ) {
b = Math.max(d[k+1], d[k+2]);
b = Math.max(b, d[k+3]);
b = Math.max(b, d[k+4]);
b = Math.max(b, d[k+5]);
if( b >= b0 ) continue;
b = Math.max(b, d[k+6]);
b = Math.max(b, d[k+7]);
b = Math.max(b, d[k+8]);
b0 = Math.min(b0, Math.max(b, d[k]));
b0 = Math.min(b0, Math.max(b, d[k+9]));
}
return -b0-1;
};
var _threshold = 20;
return {
set_threshold: function(threshold) {
_threshold = Math.min(Math.max(threshold, 0), 255);
for (var i = -255; i <= 255; ++i) {
threshold_tab[(i + 255)] = (i < -_threshold ? 1 : (i > _threshold ? 2 : 0));
}
return _threshold;
},
detect: function(src, corners, border) {
if (typeof border === "undefined") { border = 3; }
var K = 8, N = 25;
var img = src.data, w = src.cols, h = src.rows;
var i=0, j=0, k=0, vt=0, x=0, m3=0;
var buf_node = jsfeat.cache.get_buffer(3 * w);
var cpbuf_node = jsfeat.cache.get_buffer(((w+1)*3)<<2);
var buf = buf_node.u8;
var cpbuf = cpbuf_node.i32;
var pixel = pixel_off;
var sd = score_diff;
var sy = Math.max(3, border);
var ey = Math.min((h-2), (h-border));
var sx = Math.max(3, border);
var ex = Math.min((w - 3), (w - border));
var _count = 0, corners_cnt = 0, pt;
var score_func = _cmp_score_16;
var thresh_tab = threshold_tab;
var threshold = _threshold;
var v=0,tab=0,d=0,ncorners=0,cornerpos=0,curr=0,ptr=0,prev=0,pprev=0;
var jp1=0,jm1=0,score=0;
_cmp_offsets(pixel, w, 16);
// local vars are faster?
var pixel0 = pixel[0];
var pixel1 = pixel[1];
var pixel2 = pixel[2];
var pixel3 = pixel[3];
var pixel4 = pixel[4];
var pixel5 = pixel[5];
var pixel6 = pixel[6];
var pixel7 = pixel[7];
var pixel8 = pixel[8];
var pixel9 = pixel[9];
var pixel10 = pixel[10];
var pixel11 = pixel[11];
var pixel12 = pixel[12];
var pixel13 = pixel[13];
var pixel14 = pixel[14];
var pixel15 = pixel[15];
for(i = 0; i < w*3; ++i) {
buf[i] = 0;
}
for(i = sy; i < ey; ++i) {
ptr = ((i * w) + sx)|0;
m3 = (i - 3)%3;
curr = (m3*w)|0;
cornerpos = (m3*(w+1))|0;
for (j = 0; j < w; ++j) buf[curr+j] = 0;
ncorners = 0;
if( i < (ey - 1) ) {
j = sx;
for( ; j < ex; ++j, ++ptr ) {
v = img[ptr];
tab = ( - v + 255 );
d = ( thresh_tab[tab+img[ptr+pixel0]] | thresh_tab[tab+img[ptr+pixel8]] );
if( d == 0 ) {
continue;
}
d &= ( thresh_tab[tab+img[ptr+pixel2]] | thresh_tab[tab+img[ptr+pixel10]] );
d &= ( thresh_tab[tab+img[ptr+pixel4]] | thresh_tab[tab+img[ptr+pixel12]] );
d &= ( thresh_tab[tab+img[ptr+pixel6]] | thresh_tab[tab+img[ptr+pixel14]] );
if( d == 0 ) {
continue;
}
d &= ( thresh_tab[tab+img[ptr+pixel1]] | thresh_tab[tab+img[ptr+pixel9]] );
d &= ( thresh_tab[tab+img[ptr+pixel3]] | thresh_tab[tab+img[ptr+pixel11]] );
d &= ( thresh_tab[tab+img[ptr+pixel5]] | thresh_tab[tab+img[ptr+pixel13]] );
d &= ( thresh_tab[tab+img[ptr+pixel7]] | thresh_tab[tab+img[ptr+pixel15]] );
if( d & 1 ) {
vt = (v - threshold);
_count = 0;
for( k = 0; k < N; ++k ) {
x = img[(ptr+pixel[k])];
if(x < vt) {
++_count;
if( _count > K ) {
++ncorners;
cpbuf[cornerpos+ncorners] = j;
buf[curr+j] = score_func(img, ptr, pixel, sd, threshold);
break;
}
}
else {
_count = 0;
}
}
}
if( d & 2 ) {
vt = (v + threshold);
_count = 0;
for( k = 0; k < N; ++k ) {
x = img[(ptr+pixel[k])];
if(x > vt) {
++_count;
if( _count > K ) {
++ncorners;
cpbuf[cornerpos+ncorners] = j;
buf[curr+j] = score_func(img, ptr, pixel, sd, threshold);
break;
}
}
else {
_count = 0;
}
}
}
}
}
cpbuf[cornerpos+w] = ncorners;
if ( i == sy ) {
continue;
}
m3 = (i - 4 + 3)%3;
prev = (m3*w)|0;
cornerpos = (m3*(w+1))|0;
m3 = (i - 5 + 3)%3;
pprev = (m3*w)|0;
ncorners = cpbuf[cornerpos+w];
for( k = 0; k < ncorners; ++k ) {
j = cpbuf[cornerpos+k];
jp1 = (j+1)|0;
jm1 = (j-1)|0;
score = buf[prev+j];
if( (score > buf[prev+jp1] && score > buf[prev+jm1] &&
score > buf[pprev+jm1] && score > buf[pprev+j] && score > buf[pprev+jp1] &&
score > buf[curr+jm1] && score > buf[curr+j] && score > buf[curr+jp1]) ) {
// save corner
pt = corners[corners_cnt];
pt.x = j, pt.y = (i-1), pt.score = score;
corners_cnt++;
}
}
} // y loop
jsfeat.cache.put_buffer(buf_node);
jsfeat.cache.put_buffer(cpbuf_node);
return corners_cnt;
}
};
})();
global.fast_corners = fast_corners;
fast_corners.set_threshold(20); // set default
})(jsfeat);
/**
* @author Eugene Zatepyakin / http://inspirit.ru/
*
* Copyright 2007 Computer Vision Lab,
* Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland.
* @author Vincent Lepetit (http://cvlab.epfl.ch/~lepetit)
*/
(function(global) {
"use strict";
//
var yape06 = (function() {
var compute_laplacian = function(src, dst, w, h, Dxx, Dyy, sx,sy, ex,ey) {
var y=0,x=0,yrow=(sy*w+sx)|0,row=yrow;
for(y = sy; y < ey; ++y, yrow+=w, row = yrow) {
for(x = sx; x < ex; ++x, ++row) {
dst[row] = -4 * src[row] + src[row+Dxx] + src[row-Dxx] + src[row+Dyy] + src[row-Dyy];
}
}
}
var hessian_min_eigen_value = function(src, off, tr, Dxx, Dyy, Dxy, Dyx) {
var Ixx = -2 * src[off] + src[off + Dxx] + src[off - Dxx];
var Iyy = -2 * src[off] + src[off + Dyy] + src[off - Dyy];
var Ixy = src[off + Dxy] + src[off - Dxy] - src[off + Dyx] - src[off - Dyx];
var sqrt_delta = ( Math.sqrt(((Ixx - Iyy) * (Ixx - Iyy) + 4 * Ixy * Ixy) ) )|0;
return Math.min(Math.abs(tr - sqrt_delta), Math.abs(-(tr + sqrt_delta)));
}
return {
laplacian_threshold: 30,
min_eigen_value_threshold: 25,
detect: function(src, points, border) {
if (typeof border === "undefined") { border = 5; }
var x=0,y=0;
var w=src.cols, h=src.rows, srd_d=src.data;
var Dxx = 5, Dyy = (5 * w)|0;
var Dxy = (3 + 3 * w)|0, Dyx = (3 - 3 * w)|0;
var lap_buf = jsfeat.cache.get_buffer((w*h)<<2);
var laplacian = lap_buf.i32;
var lv=0, row=0,rowx=0,min_eigen_value=0,pt;
var number_of_points = 0;
var lap_thresh = this.laplacian_threshold;
var eigen_thresh = this.min_eigen_value_threshold;
var sx = Math.max(5, border)|0;
var sy = Math.max(3, border)|0;
var ex = Math.min(w-5, w-border)|0;
var ey = Math.min(h-3, h-border)|0;
x = w*h;
while(--x>=0) {laplacian[x]=0;}
compute_laplacian(srd_d, laplacian, w, h, Dxx, Dyy, sx,sy, ex,ey);
row = (sy*w+sx)|0;
for(y = sy; y < ey; ++y, row += w) {
for(x = sx, rowx=row; x < ex; ++x, ++rowx) {
lv = laplacian[rowx];
if ((lv < -lap_thresh &&
lv < laplacian[rowx - 1] && lv < laplacian[rowx + 1] &&
lv < laplacian[rowx - w] && lv < laplacian[rowx + w] &&
lv < laplacian[rowx - w - 1] && lv < laplacian[rowx + w - 1] &&
lv < laplacian[rowx - w + 1] && lv < laplacian[rowx + w + 1])
||
(lv > lap_thresh &&
lv > laplacian[rowx - 1] && lv > laplacian[rowx + 1] &&
lv > laplacian[rowx - w] && lv > laplacian[rowx + w] &&
lv > laplacian[rowx - w - 1] && lv > laplacian[rowx + w - 1] &&
lv > laplacian[rowx - w + 1] && lv > laplacian[rowx + w + 1])
) {
min_eigen_value = hessian_min_eigen_value(srd_d, rowx, lv, Dxx, Dyy, Dxy, Dyx);
if (min_eigen_value > eigen_thresh) {
pt = points[number_of_points];
pt.x = x, pt.y = y, pt.score = min_eigen_value;
++number_of_points;
++x, ++rowx; // skip next pixel since this is maxima in 3x3
}
}
}
}
jsfeat.cache.put_buffer(lap_buf);
return number_of_points;
}
};
})();
global.yape06 = yape06;
})(jsfeat);
/**
* @author Eugene Zatepyakin / http://inspirit.ru/
*
* Copyright 2007 Computer Vision Lab,
* Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland.
*/
(function(global) {
"use strict";
//
var yape = (function() {
var precompute_directions = function(step, dirs, R) {
var i = 0;
var x, y;
x = R;
for(y = 0; y < x; y++, i++)
{
x = (Math.sqrt((R * R - y * y)) + 0.5)|0;
dirs[i] = (x + step * y);
}
for(x-- ; x < y && x >= 0; x--, i++)
{
y = (Math.sqrt((R * R - x * x)) + 0.5)|0;
dirs[i] = (x + step * y);
}
for( ; -x < y; x--, i++)
{
y = (Math.sqrt((R * R - x * x)) + 0.5)|0;
dirs[i] = (x + step * y);
}
for(y-- ; y >= 0; y--, i++)
{
x = (-Math.sqrt((R * R - y * y)) - 0.5)|0;
dirs[i] = (x + step * y);
}
for(; y > x; y--, i++)
{
x = (-Math.sqrt((R * R - y * y)) - 0.5)|0;
dirs[i] = (x + step * y);
}
for(x++ ; x <= 0; x++, i++)
{
y = (-Math.sqrt((R * R - x * x)) - 0.5)|0;
dirs[i] = (x + step * y);
}
for( ; x < -y; x++, i++)
{
y = (-Math.sqrt((R * R - x * x)) - 0.5)|0;
dirs[i] = (x + step * y);
}
for(y++ ; y < 0; y++, i++)
{
x = (Math.sqrt((R * R - y * y)) + 0.5)|0;
dirs[i] = (x + step * y);
}
dirs[i] = dirs[0];
dirs[i + 1] = dirs[1];
return i;
}
var third_check = function (Sb, off, step) {
var n = 0;
if(Sb[off+1] != 0) n++;
if(Sb[off-1] != 0) n++;
if(Sb[off+step] != 0) n++;
if(Sb[off+step+1] != 0) n++;
if(Sb[off+step-1] != 0) n++;
if(Sb[off-step] != 0) n++;
if(Sb[off-step+1] != 0) n++;
if(Sb[off-step-1] != 0) n++;
return n;
}
var is_local_maxima = function(p, off, v, step, neighborhood) {
var x, y;
if (v > 0) {
off -= step*neighborhood;
for (y= -neighborhood; y<=neighborhood; ++y) {
for (x= -neighborhood; x<=neighborhood; ++x) {
if (p[off+x] > v) return false;
}
off += step;
}
} else {
off -= step*neighborhood;
for (y= -neighborhood; y<=neighborhood; ++y) {
for (x= -neighborhood; x<=neighborhood; ++x) {
if (p[off+x] < v) return false;
}
off += step;
}
}
return true;
}
var perform_one_point = function(I, x, Scores, Im, Ip, dirs, opposite, dirs_nb) {
var score = 0;
var a = 0, b = (opposite - 1)|0;
var A=0, B0=0, B1=0, B2=0;
var state=0;
// WE KNOW THAT NOT(A ~ I0 & B1 ~ I0):
A = I[x+dirs[a]];
if ((A <= Ip)) {
if ((A >= Im)) { // A ~ I0
B0 = I[x+dirs[b]];
if ((B0 <= Ip)) {
if ((B0 >= Im)) { Scores[x] = 0; return; }
else {
b++; B1 = I[x+dirs[b]];
if ((B1 > Ip)) {
b++; B2 = I[x+dirs[b]];
if ((B2 > Ip)) state = 3;
else if ((B2 < Im)) state = 6;
else { Scores[x] = 0; return; } // A ~ I0, B2 ~ I0
}
else/* if ((B1 < Im))*/ {
b++; B2 = I[x+dirs[b]];
if ((B2 > Ip)) state = 7;
else if ((B2 < Im)) state = 2;
else { Scores[x] = 0; return; } // A ~ I0, B2 ~ I0
}
//else { Scores[x] = 0; return; } // A ~ I0, B1 ~ I0
}
}
else { // B0 < I0
b++; B1 = I[x+dirs[b]];
if ((B1 > Ip)) {
b++; B2 = I[x+dirs[b]];
if ((B2 > Ip)) state = 3;
else if ((B2 < Im)) state = 6;
else { Scores[x] = 0; return; } // A ~ I0, B2 ~ I0
}
else if ((B1 < Im)) {
b++; B2 = I[x+dirs[b]];
if ((B2 > Ip)) state = 7;
else if ((B2 < Im)) state = 2;
else { Scores[x] = 0; return; } // A ~ I0, B2 ~ I0
}
else { Scores[x] = 0; return; } // A ~ I0, B1 ~ I0
}
}
else { // A > I0
B0 = I[x+dirs[b]];
if ((B0 > Ip)) { Scores[x] = 0; return; }
b++; B1 = I[x+dirs[b]];
if ((B1 > Ip)) { Scores[x] = 0; return; }
b++; B2 = I[x+dirs[b]];
if ((B2 > Ip)) { Scores[x] = 0; return; }
state = 1;
}
}
else // A < I0
{
B0 = I[x+dirs[b]];
if ((B0 < Im)) { Scores[x] = 0; return; }
b++; B1 = I[x+dirs[b]];
if ((B1 < Im)) { Scores[x] = 0; return; }
b++; B2 = I[x+dirs[b]];
if ((B2 < Im)) { Scores[x] = 0; return; }
state = 0;
}
for(a = 1; a <= opposite; a++)
{
A = I[x+dirs[a]];
switch(state)
{
case 0:
if ((A > Ip)) {
B1 = B2; b++; B2 = I[x+dirs[b]];
if ((B2 < Im)) { Scores[x] = 0; return; }
{ score -= A + B1; state = 0; break; };
}
if ((A < Im)) {
if ((B1 > Ip)) { Scores[x] = 0; return; }
if ((B2 > Ip)) { Scores[x] = 0; return; }
B1 = B2; b++; B2 = I[x+dirs[b]];
if ((B2 > Ip)) { Scores[x] = 0; return; }
{ score -= A + B1; state = 8; break; };
}
// A ~ I0
if ((B1 <= Ip)) { Scores[x] = 0; return; }
if ((B2 <= Ip)) { Scores[x] = 0; return; }
B1 = B2; b++; B2 = I[x+dirs[b]];
if ((B2 > Ip)) { score -= A + B1; state = 3; break; };
if ((B2 < Im)) { score -= A + B1; state = 6; break; };
{ Scores[x] = 0; return; }
case 1:
if ((A < Im)) {
B1 = B2; b++; B2 = I[x+dirs[b]];
if ((B2 > Ip)) { Scores[x] = 0; return; }
{ score -= A + B1; state = 1; break; };
}
if ((A > Ip)) {
if ((B1 < Im)) { Scores[x] = 0; return; }
if ((B2 < Im)) { Scores[x] = 0; return; }
B1 = B2; b++; B2 = I[x+dirs[b]];
if ((B2 < Im)) { Scores[x] = 0; return; }
{ score -= A + B1; state = 9; break; };
}
// A ~ I0
if ((B1 >= Im)) { Scores[x] = 0; return; }
if ((B2 >= Im)) { Scores[x] = 0; return; }
B1 = B2; b++; B2 = I[x+dirs[b]];
if ((B2 < Im)) { score -= A + B1; state = 2; break; };
if ((B2 > Ip)) { score -= A + B1; state = 7; break; };
{ Scores[x] = 0; return; }
case 2:
if ((A > Ip)) { Scores[x] = 0; return; }
B1 = B2; b++; B2 = I[x+dirs[b]];
if ((A < Im))
{
if ((B2 > Ip)) { Scores[x] = 0; return; }
{ score -= A + B1; state = 4; break; };
}
// A ~ I0
if ((B2 > Ip)) { score -= A + B1; state = 7; break; };
if ((B2 < Im)) { score -= A + B1; state = 2; break; };
{ Scores[x] = 0; return; } // A ~ I0, B2 ~ I0
case 3:
if ((A < Im)) { Scores[x] = 0; return; }
B1 = B2; b++; B2 = I[x+dirs[b]];
if ((A > Ip)) {
if ((B2 < Im)) { Scores[x] = 0; return; }
{ score -= A + B1; state = 5; break; };
}
// A ~ I0
if ((B2 > Ip)) { score -= A + B1; state = 3; break; };
if ((B2 < Im)) { score -= A + B1; state = 6; break; };
{ Scores[x] = 0; return; }
case 4:
if ((A > Ip)) { Scores[x] = 0; return; }
if ((A < Im)) {
B1 = B2; b++; B2 = I[x+dirs[b]];
if ((B2 > Ip)) { Scores[x] = 0; return; }
{ score -= A + B1; state = 1; break; };
}
if ((B2 >= Im)) { Scores[x] = 0; return; }
B1 = B2; b++; B2 = I[x+dirs[b]];
if ((B2 < Im)) { score -= A + B1; state = 2; break; };
if ((B2 > Ip)) { score -= A + B1; state = 7; break; };
{ Scores[x] = 0; return; }
case 5:
if ((A < Im)) { Scores[x] = 0; return; }
if ((A > Ip)) {
B1 = B2; b++; B2 = I[x+dirs[b]];
if ((B2 < Im)) { Scores[x] = 0; return; }
{ score -= A + B1; state = 0; break; };
}
// A ~ I0
if ((B2 <= Ip)) { Scores[x] = 0; return; }
B1 = B2; b++; B2 = I[x+dirs[b]];
if ((B2 > Ip)) { score -= A + B1; state = 3; break; };
if ((B2 < Im)) { score -= A + B1; state = 6; break; };
{ Scores[x] = 0; return; }
case 7:
if ((A > Ip)) { Scores[x] = 0; return; }
if ((A < Im)) { Scores[x] = 0; return; }
B1 = B2; b++; B2 = I[x+dirs[b]];
// A ~ I0
if ((B2 > Ip)) { score -= A + B1; state = 3; break; };
if ((B2 < Im)) { score -= A + B1; state = 6; break; };
{ Scores[x] = 0; return; } // A ~ I0, B2 ~ I0
case 6:
if ((A > Ip)) { Scores[x] = 0; return; }
if ((A < Im)) { Scores[x] = 0; return; }
B1 = B2; b++; B2 = I[x+dirs[b]];
// A ~ I0
if ((B2 < Im)) { score -= A + B1; state = 2; break; };
if ((B2 > Ip)) { score -= A + B1; state = 7; break; };
{ Scores[x] = 0; return; } // A ~ I0, B2 ~ I0
case 8:
if ((A > Ip)) {
if ((B2 < Im)) { Scores[x] = 0; return; }
B1 = B2; b++; B2 = I[x+dirs[b]];
if ((B2 < Im)) { Scores[x] = 0; return; }
{ score -= A + B1; state = 9; break; };
}
if ((A < Im)) {
B1 = B2; b++; B2 = I[x+dirs[b]];
if ((B2 > Ip)) { Scores[x] = 0; return; }
{ score -= A + B1; state = 1; break; };
}
{ Scores[x] = 0; return; }
case 9:
if ((A < Im)) {
if ((B2 > Ip)) { Scores[x] = 0; return; }
B1 = B2; b++; B2 = I[x+dirs[b]];
if ((B2 > Ip)) { Scores[x] = 0; return; }
{ score -= A + B1; state = 8; break; };
}
if ((A > Ip)) {
B1 = B2; b++; B2 = I[x+dirs[b]];
if ((B2 < Im)) { Scores[x] = 0; return; }
{ score -= A + B1; state = 0; break; };
}
{ Scores[x] = 0; return; }
default:
//"PB default";
break;
} // switch(state)
} // for(a...)
Scores[x] = (score + dirs_nb * I[x]);
}
var lev_table_t = (function () {
function lev_table_t(w, h, r) {
this.dirs = new Int32Array(1024);
this.dirs_count = precompute_directions(w, this.dirs, r)|0;
this.scores = new Int32Array(w*h);
this.radius = r|0;
}
return lev_table_t;
})();
return {
level_tables: [],
tau: 7,
init: function(width, height, radius, pyramid_levels) {
if (typeof pyramid_levels === "undefined") { pyramid_levels = 1; }
var i;
radius = Math.min(radius, 7);
radius = Math.max(radius, 3);
for(i = 0; i < pyramid_levels; ++i) {
this.level_tables[i] = new lev_table_t(width>>i, height>>i, radius);
}
},
detect: function(src, points, border) {
if (typeof border === "undefined") { border = 4; }
var t = this.level_tables[0];
var R = t.radius|0, Rm1 = (R-1)|0;
var dirs = t.dirs;
var dirs_count = t.dirs_count|0;
var opposite = dirs_count >> 1;
var img = src.data, w=src.cols|0, h=src.rows|0,hw=w>>1;
var scores = t.scores;
var x=0,y=0,row=0,rowx=0,ip=0,im=0,abs_score=0, score=0;
var tau = this.tau|0;
var number_of_points = 0, pt;
var sx = Math.max(R+1, border)|0;
var sy = Math.max(R+1, border)|0;
var ex = Math.min(w-R-2, w-border)|0;
var ey = Math.min(h-R-2, h-border)|0;
row = (sy*w+sx)|0;
for(y = sy; y < ey; ++y, row+=w) {
for(x = sx, rowx = row; x < ex; ++x, ++rowx) {
ip = img[rowx] + tau, im = img[rowx] - tau;
if (im= 3 && is_local_maxima(scores, rowx, score, hw, R)) {
pt = points[number_of_points];
pt.x = x, pt.y = y, pt.score = abs_score;
++number_of_points;
x += Rm1, rowx += Rm1;
}
}
}
}
return number_of_points;
}
};
})();
global.yape = yape;
})(jsfeat);
/**
* @author Eugene Zatepyakin / http://inspirit.ru/
*
* Original implementation derived from OpenCV,
* @authors Ethan Rublee, Vincent Rabaud, Gary Bradski
*/
(function(global) {
"use strict";
//
var orb = (function() {
var bit_pattern_31_ = new Int32Array([
8,-3, 9,5/*mean (0), correlation (0)*/,
4,2, 7,-12/*mean (1.12461e-05), correlation (0.0437584)*/,
-11,9, -8,2/*mean (3.37382e-05), correlation (0.0617409)*/,
7,-12, 12,-13/*mean (5.62303e-05), correlation (0.0636977)*/,
2,-13, 2,12/*mean (0.000134953), correlation (0.085099)*/,
1,-7, 1,6/*mean (0.000528565), correlation (0.0857175)*/,
-2,-10, -2,-4/*mean (0.0188821), correlation (0.0985774)*/,
-13,-13, -11,-8/*mean (0.0363135), correlation (0.0899616)*/,
-13,-3, -12,-9/*mean (0.121806), correlation (0.099849)*/,
10,4, 11,9/*mean (0.122065), correlation (0.093285)*/,
-13,-8, -8,-9/*mean (0.162787), correlation (0.0942748)*/,
-11,7, -9,12/*mean (0.21561), correlation (0.0974438)*/,
7,7, 12,6/*mean (0.160583), correlation (0.130064)*/,
-4,-5, -3,0/*mean (0.228171), correlation (0.132998)*/,
-13,2, -12,-3/*mean (0.00997526), correlation (0.145926)*/,
-9,0, -7,5/*mean (0.198234), correlation (0.143636)*/,
12,-6, 12,-1/*mean (0.0676226), correlation (0.16689)*/,
-3,6, -2,12/*mean (0.166847), correlation (0.171682)*/,
-6,-13, -4,-8/*mean (0.101215), correlation (0.179716)*/,
11,-13, 12,-8/*mean (0.200641), correlation (0.192279)*/,
4,7, 5,1/*mean (0.205106), correlation (0.186848)*/,
5,-3, 10,-3/*mean (0.234908), correlation (0.192319)*/,
3,-7, 6,12/*mean (0.0709964), correlation (0.210872)*/,
-8,-7, -6,-2/*mean (0.0939834), correlation (0.212589)*/,
-2,11, -1,-10/*mean (0.127778), correlation (0.20866)*/,
-13,12, -8,10/*mean (0.14783), correlation (0.206356)*/,
-7,3, -5,-3/*mean (0.182141), correlation (0.198942)*/,
-4,2, -3,7/*mean (0.188237), correlation (0.21384)*/,
-10,-12, -6,11/*mean (0.14865), correlation (0.23571)*/,
5,-12, 6,-7/*mean (0.222312), correlation (0.23324)*/,
5,-6, 7,-1/*mean (0.229082), correlation (0.23389)*/,
1,0, 4,-5/*mean (0.241577), correlation (0.215286)*/,
9,11, 11,-13/*mean (0.00338507), correlation (0.251373)*/,
4,7, 4,12/*mean (0.131005), correlation (0.257622)*/,
2,-1, 4,4/*mean (0.152755), correlation (0.255205)*/,
-4,-12, -2,7/*mean (0.182771), correlation (0.244867)*/,
-8,-5, -7,-10/*mean (0.186898), correlation (0.23901)*/,
4,11, 9,12/*mean (0.226226), correlation (0.258255)*/,
0,-8, 1,-13/*mean (0.0897886), correlation (0.274827)*/,
-13,-2, -8,2/*mean (0.148774), correlation (0.28065)*/,
-3,-2, -2,3/*mean (0.153048), correlation (0.283063)*/,
-6,9, -4,-9/*mean (0.169523), correlation (0.278248)*/,
8,12, 10,7/*mean (0.225337), correlation (0.282851)*/,
0,9, 1,3/*mean (0.226687), correlation (0.278734)*/,
7,-5, 11,-10/*mean (0.00693882), correlation (0.305161)*/,
-13,-6, -11,0/*mean (0.0227283), correlation (0.300181)*/,
10,7, 12,1/*mean (0.125517), correlation (0.31089)*/,
-6,-3, -6,12/*mean (0.131748), correlation (0.312779)*/,
10,-9, 12,-4/*mean (0.144827), correlation (0.292797)*/,
-13,8, -8,-12/*mean (0.149202), correlation (0.308918)*/,
-13,0, -8,-4/*mean (0.160909), correlation (0.310013)*/,
3,3, 7,8/*mean (0.177755), correlation (0.309394)*/,
5,7, 10,-7/*mean (0.212337), correlation (0.310315)*/,
-1,7, 1,-12/*mean (0.214429), correlation (0.311933)*/,
3,-10, 5,6/*mean (0.235807), correlation (0.313104)*/,
2,-4, 3,-10/*mean (0.00494827), correlation (0.344948)*/,
-13,0, -13,5/*mean (0.0549145), correlation (0.344675)*/,
-13,-7, -12,12/*mean (0.103385), correlation (0.342715)*/,
-13,3, -11,8/*mean (0.134222), correlation (0.322922)*/,
-7,12, -4,7/*mean (0.153284), correlation (0.337061)*/,
6,-10, 12,8/*mean (0.154881), correlation (0.329257)*/,
-9,-1, -7,-6/*mean (0.200967), correlation (0.33312)*/,
-2,-5, 0,12/*mean (0.201518), correlation (0.340635)*/,
-12,5, -7,5/*mean (0.207805), correlation (0.335631)*/,
3,-10, 8,-13/*mean (0.224438), correlation (0.34504)*/,
-7,-7, -4,5/*mean (0.239361), correlation (0.338053)*/,
-3,-2, -1,-7/*mean (0.240744), correlation (0.344322)*/,
2,9, 5,-11/*mean (0.242949), correlation (0.34145)*/,
-11,-13, -5,-13/*mean (0.244028), correlation (0.336861)*/,
-1,6, 0,-1/*mean (0.247571), correlation (0.343684)*/,
5,-3, 5,2/*mean (0.000697256), correlation (0.357265)*/,
-4,-13, -4,12/*mean (0.00213675), correlation (0.373827)*/,
-9,-6, -9,6/*mean (0.0126856), correlation (0.373938)*/,
-12,-10, -8,-4/*mean (0.0152497), correlation (0.364237)*/,
10,2, 12,-3/*mean (0.0299933), correlation (0.345292)*/,
7,12, 12,12/*mean (0.0307242), correlation (0.366299)*/,
-7,-13, -6,5/*mean (0.0534975), correlation (0.368357)*/,
-4,9, -3,4/*mean (0.099865), correlation (0.372276)*/,
7,-1, 12,2/*mean (0.117083), correlation (0.364529)*/,
-7,6, -5,1/*mean (0.126125), correlation (0.369606)*/,
-13,11, -12,5/*mean (0.130364), correlation (0.358502)*/,
-3,7, -2,-6/*mean (0.131691), correlation (0.375531)*/,
7,-8, 12,-7/*mean (0.160166), correlation (0.379508)*/,
-13,-7, -11,-12/*mean (0.167848), correlation (0.353343)*/,
1,-3, 12,12/*mean (0.183378), correlation (0.371916)*/,
2,-6, 3,0/*mean (0.228711), correlation (0.371761)*/,
-4,3, -2,-13/*mean (0.247211), correlation (0.364063)*/,
-1,-13, 1,9/*mean (0.249325), correlation (0.378139)*/,
7,1, 8,-6/*mean (0.000652272), correlation (0.411682)*/,
1,-1, 3,12/*mean (0.00248538), correlation (0.392988)*/,
9,1, 12,6/*mean (0.0206815), correlation (0.386106)*/,
-1,-9, -1,3/*mean (0.0364485), correlation (0.410752)*/,
-13,-13, -10,5/*mean (0.0376068), correlation (0.398374)*/,
7,7, 10,12/*mean (0.0424202), correlation (0.405663)*/,
12,-5, 12,9/*mean (0.0942645), correlation (0.410422)*/,
6,3, 7,11/*mean (0.1074), correlation (0.413224)*/,
5,-13, 6,10/*mean (0.109256), correlation (0.408646)*/,
2,-12, 2,3/*mean (0.131691), correlation (0.416076)*/,
3,8, 4,-6/*mean (0.165081), correlation (0.417569)*/,
2,6, 12,-13/*mean (0.171874), correlation (0.408471)*/,
9,-12, 10,3/*mean (0.175146), correlation (0.41296)*/,
-8,4, -7,9/*mean (0.183682), correlation (0.402956)*/,
-11,12, -4,-6/*mean (0.184672), correlation (0.416125)*/,
1,12, 2,-8/*mean (0.191487), correlation (0.386696)*/,
6,-9, 7,-4/*mean (0.192668), correlation (0.394771)*/,
2,3, 3,-2/*mean (0.200157), correlation (0.408303)*/,
6,3, 11,0/*mean (0.204588), correlation (0.411762)*/,
3,-3, 8,-8/*mean (0.205904), correlation (0.416294)*/,
7,8, 9,3/*mean (0.213237), correlation (0.409306)*/,
-11,-5, -6,-4/*mean (0.243444), correlation (0.395069)*/,
-10,11, -5,10/*mean (0.247672), correlation (0.413392)*/,
-5,-8, -3,12/*mean (0.24774), correlation (0.411416)*/,
-10,5, -9,0/*mean (0.00213675), correlation (0.454003)*/,
8,-1, 12,-6/*mean (0.0293635), correlation (0.455368)*/,
4,-6, 6,-11/*mean (0.0404971), correlation (0.457393)*/,
-10,12, -8,7/*mean (0.0481107), correlation (0.448364)*/,
4,-2, 6,7/*mean (0.050641), correlation (0.455019)*/,
-2,0, -2,12/*mean (0.0525978), correlation (0.44338)*/,
-5,-8, -5,2/*mean (0.0629667), correlation (0.457096)*/,
7,-6, 10,12/*mean (0.0653846), correlation (0.445623)*/,
-9,-13, -8,-8/*mean (0.0858749), correlation (0.449789)*/,
-5,-13, -5,-2/*mean (0.122402), correlation (0.450201)*/,
8,-8, 9,-13/*mean (0.125416), correlation (0.453224)*/,
-9,-11, -9,0/*mean (0.130128), correlation (0.458724)*/,
1,-8, 1,-2/*mean (0.132467), correlation (0.440133)*/,
7,-4, 9,1/*mean (0.132692), correlation (0.454)*/,
-2,1, -1,-4/*mean (0.135695), correlation (0.455739)*/,
11,-6, 12,-11/*mean (0.142904), correlation (0.446114)*/,
-12,-9, -6,4/*mean (0.146165), correlation (0.451473)*/,
3,7, 7,12/*mean (0.147627), correlation (0.456643)*/,
5,5, 10,8/*mean (0.152901), correlation (0.455036)*/,
0,-4, 2,8/*mean (0.167083), correlation (0.459315)*/,
-9,12, -5,-13/*mean (0.173234), correlation (0.454706)*/,
0,7, 2,12/*mean (0.18312), correlation (0.433855)*/,
-1,2, 1,7/*mean (0.185504), correlation (0.443838)*/,
5,11, 7,-9/*mean (0.185706), correlation (0.451123)*/,
3,5, 6,-8/*mean (0.188968), correlation (0.455808)*/,
-13,-4, -8,9/*mean (0.191667), correlation (0.459128)*/,
-5,9, -3,-3/*mean (0.193196), correlation (0.458364)*/,
-4,-7, -3,-12/*mean (0.196536), correlation (0.455782)*/,
6,5, 8,0/*mean (0.1972), correlation (0.450481)*/,
-7,6, -6,12/*mean (0.199438), correlation (0.458156)*/,
-13,6, -5,-2/*mean (0.211224), correlation (0.449548)*/,
1,-10, 3,10/*mean (0.211718), correlation (0.440606)*/,
4,1, 8,-4/*mean (0.213034), correlation (0.443177)*/,
-2,-2, 2,-13/*mean (0.234334), correlation (0.455304)*/,
2,-12, 12,12/*mean (0.235684), correlation (0.443436)*/,
-2,-13, 0,-6/*mean (0.237674), correlation (0.452525)*/,
4,1, 9,3/*mean (0.23962), correlation (0.444824)*/,
-6,-10, -3,-5/*mean (0.248459), correlation (0.439621)*/,
-3,-13, -1,1/*mean (0.249505), correlation (0.456666)*/,
7,5, 12,-11/*mean (0.00119208), correlation (0.495466)*/,
4,-2, 5,-7/*mean (0.00372245), correlation (0.484214)*/,
-13,9, -9,-5/*mean (0.00741116), correlation (0.499854)*/,
7,1, 8,6/*mean (0.0208952), correlation (0.499773)*/,
7,-8, 7,6/*mean (0.0220085), correlation (0.501609)*/,
-7,-4, -7,1/*mean (0.0233806), correlation (0.496568)*/,
-8,11, -7,-8/*mean (0.0236505), correlation (0.489719)*/,
-13,6, -12,-8/*mean (0.0268781), correlation (0.503487)*/,
2,4, 3,9/*mean (0.0323324), correlation (0.501938)*/,
10,-5, 12,3/*mean (0.0399235), correlation (0.494029)*/,
-6,-5, -6,7/*mean (0.0420153), correlation (0.486579)*/,
8,-3, 9,-8/*mean (0.0548021), correlation (0.484237)*/,
2,-12, 2,8/*mean (0.0616622), correlation (0.496642)*/,
-11,-2, -10,3/*mean (0.0627755), correlation (0.498563)*/,
-12,-13, -7,-9/*mean (0.0829622), correlation (0.495491)*/,
-11,0, -10,-5/*mean (0.0843342), correlation (0.487146)*/,
5,-3, 11,8/*mean (0.0929937), correlation (0.502315)*/,
-2,-13, -1,12/*mean (0.113327), correlation (0.48941)*/,
-1,-8, 0,9/*mean (0.132119), correlation (0.467268)*/,
-13,-11, -12,-5/*mean (0.136269), correlation (0.498771)*/,
-10,-2, -10,11/*mean (0.142173), correlation (0.498714)*/,
-3,9, -2,-13/*mean (0.144141), correlation (0.491973)*/,
2,-3, 3,2/*mean (0.14892), correlation (0.500782)*/,
-9,-13, -4,0/*mean (0.150371), correlation (0.498211)*/,
-4,6, -3,-10/*mean (0.152159), correlation (0.495547)*/,
-4,12, -2,-7/*mean (0.156152), correlation (0.496925)*/,
-6,-11, -4,9/*mean (0.15749), correlation (0.499222)*/,
6,-3, 6,11/*mean (0.159211), correlation (0.503821)*/,
-13,11, -5,5/*mean (0.162427), correlation (0.501907)*/,
11,11, 12,6/*mean (0.16652), correlation (0.497632)*/,
7,-5, 12,-2/*mean (0.169141), correlation (0.484474)*/,
-1,12, 0,7/*mean (0.169456), correlation (0.495339)*/,
-4,-8, -3,-2/*mean (0.171457), correlation (0.487251)*/,
-7,1, -6,7/*mean (0.175), correlation (0.500024)*/,
-13,-12, -8,-13/*mean (0.175866), correlation (0.497523)*/,
-7,-2, -6,-8/*mean (0.178273), correlation (0.501854)*/,
-8,5, -6,-9/*mean (0.181107), correlation (0.494888)*/,
-5,-1, -4,5/*mean (0.190227), correlation (0.482557)*/,
-13,7, -8,10/*mean (0.196739), correlation (0.496503)*/,
1,5, 5,-13/*mean (0.19973), correlation (0.499759)*/,
1,0, 10,-13/*mean (0.204465), correlation (0.49873)*/,
9,12, 10,-1/*mean (0.209334), correlation (0.49063)*/,
5,-8, 10,-9/*mean (0.211134), correlation (0.503011)*/,
-1,11, 1,-13/*mean (0.212), correlation (0.499414)*/,
-9,-3, -6,2/*mean (0.212168), correlation (0.480739)*/,
-1,-10, 1,12/*mean (0.212731), correlation (0.502523)*/,
-13,1, -8,-10/*mean (0.21327), correlation (0.489786)*/,
8,-11, 10,-6/*mean (0.214159), correlation (0.488246)*/,
2,-13, 3,-6/*mean (0.216993), correlation (0.50287)*/,
7,-13, 12,-9/*mean (0.223639), correlation (0.470502)*/,
-10,-10, -5,-7/*mean (0.224089), correlation (0.500852)*/,
-10,-8, -8,-13/*mean (0.228666), correlation (0.502629)*/,
4,-6, 8,5/*mean (0.22906), correlation (0.498305)*/,
3,12, 8,-13/*mean (0.233378), correlation (0.503825)*/,
-4,2, -3,-3/*mean (0.234323), correlation (0.476692)*/,
5,-13, 10,-12/*mean (0.236392), correlation (0.475462)*/,
4,-13, 5,-1/*mean (0.236842), correlation (0.504132)*/,
-9,9, -4,3/*mean (0.236977), correlation (0.497739)*/,
0,3, 3,-9/*mean (0.24314), correlation (0.499398)*/,
-12,1, -6,1/*mean (0.243297), correlation (0.489447)*/,
3,2, 4,-8/*mean (0.00155196), correlation (0.553496)*/,
-10,-10, -10,9/*mean (0.00239541), correlation (0.54297)*/,
8,-13, 12,12/*mean (0.0034413), correlation (0.544361)*/,
-8,-12, -6,-5/*mean (0.003565), correlation (0.551225)*/,
2,2, 3,7/*mean (0.00835583), correlation (0.55285)*/,
10,6, 11,-8/*mean (0.00885065), correlation (0.540913)*/,
6,8, 8,-12/*mean (0.0101552), correlation (0.551085)*/,
-7,10, -6,5/*mean (0.0102227), correlation (0.533635)*/,
-3,-9, -3,9/*mean (0.0110211), correlation (0.543121)*/,
-1,-13, -1,5/*mean (0.0113473), correlation (0.550173)*/,
-3,-7, -3,4/*mean (0.0140913), correlation (0.554774)*/,
-8,-2, -8,3/*mean (0.017049), correlation (0.55461)*/,
4,2, 12,12/*mean (0.01778), correlation (0.546921)*/,
2,-5, 3,11/*mean (0.0224022), correlation (0.549667)*/,
6,-9, 11,-13/*mean (0.029161), correlation (0.546295)*/,
3,-1, 7,12/*mean (0.0303081), correlation (0.548599)*/,
11,-1, 12,4/*mean (0.0355151), correlation (0.523943)*/,
-3,0, -3,6/*mean (0.0417904), correlation (0.543395)*/,
4,-11, 4,12/*mean (0.0487292), correlation (0.542818)*/,
2,-4, 2,1/*mean (0.0575124), correlation (0.554888)*/,
-10,-6, -8,1/*mean (0.0594242), correlation (0.544026)*/,
-13,7, -11,1/*mean (0.0597391), correlation (0.550524)*/,
-13,12, -11,-13/*mean (0.0608974), correlation (0.55383)*/,
6,0, 11,-13/*mean (0.065126), correlation (0.552006)*/,
0,-1, 1,4/*mean (0.074224), correlation (0.546372)*/,
-13,3, -9,-2/*mean (0.0808592), correlation (0.554875)*/,
-9,8, -6,-3/*mean (0.0883378), correlation (0.551178)*/,
-13,-6, -8,-2/*mean (0.0901035), correlation (0.548446)*/,
5,-9, 8,10/*mean (0.0949843), correlation (0.554694)*/,
2,7, 3,-9/*mean (0.0994152), correlation (0.550979)*/,
-1,-6, -1,-1/*mean (0.10045), correlation (0.552714)*/,
9,5, 11,-2/*mean (0.100686), correlation (0.552594)*/,
11,-3, 12,-8/*mean (0.101091), correlation (0.532394)*/,
3,0, 3,5/*mean (0.101147), correlation (0.525576)*/,
-1,4, 0,10/*mean (0.105263), correlation (0.531498)*/,
3,-6, 4,5/*mean (0.110785), correlation (0.540491)*/,
-13,0, -10,5/*mean (0.112798), correlation (0.536582)*/,
5,8, 12,11/*mean (0.114181), correlation (0.555793)*/,
8,9, 9,-6/*mean (0.117431), correlation (0.553763)*/,
7,-4, 8,-12/*mean (0.118522), correlation (0.553452)*/,
-10,4, -10,9/*mean (0.12094), correlation (0.554785)*/,
7,3, 12,4/*mean (0.122582), correlation (0.555825)*/,
9,-7, 10,-2/*mean (0.124978), correlation (0.549846)*/,
7,0, 12,-2/*mean (0.127002), correlation (0.537452)*/,
-1,-6, 0,-11/*mean (0.127148), correlation (0.547401)*/
]);
var H = new jsfeat.matrix_t(3, 3, jsfeat.F32_t|jsfeat.C1_t);
var patch_img = new jsfeat.matrix_t(32, 32, jsfeat.U8_t|jsfeat.C1_t);
var rectify_patch = function(src, dst, angle, px, py, psize) {
var cosine = Math.cos(angle);
var sine = Math.sin(angle);
H.data[0] = cosine, H.data[1] = -sine, H.data[2] = (-cosine + sine ) * psize*0.5 + px,
H.data[3] = sine, H.data[4] = cosine, H.data[5] = (-sine - cosine) * psize*0.5 + py;
jsfeat.imgproc.warp_affine(src, dst, H, 128);
}
return {
describe: function(src, corners, count, descriptors) {
var DESCR_SIZE = 32; // bytes;
var i=0,b=0,px=0.0,py=0.0,angle=0.0;
var t0=0, t1=0, val=0;
var img = src.data, w = src.cols, h = src.rows;
var patch_d = patch_img.data;
var patch_off = 16*32 + 16; // center of patch
var patt=0;
if(!(descriptors.type&jsfeat.U8_t)) {
// relocate to U8 type
descriptors.type = jsfeat.U8_t;
descriptors.cols = DESCR_SIZE;
descriptors.rows = count;
descriptors.channel = 1;
descriptors.allocate();
} else {
descriptors.resize(DESCR_SIZE, count, 1);
}
var descr_d = descriptors.data;
var descr_off = 0;
for(i = 0; i < count; ++i) {
px = corners[i].x;
py = corners[i].y;
angle = corners[i].angle;
rectify_patch(src, patch_img, angle, px, py, 32);
// describe the patch
patt = 0;
for (b = 0; b < DESCR_SIZE; ++b) {
t0 = patch_d[patch_off + bit_pattern_31_[patt+1] * 32 + bit_pattern_31_[patt]]; patt += 2
t1 = patch_d[patch_off + bit_pattern_31_[patt+1] * 32 + bit_pattern_31_[patt]]; patt += 2
val = (t0 < t1)|0;
t0 = patch_d[patch_off + bit_pattern_31_[patt+1] * 32 + bit_pattern_31_[patt]]; patt += 2
t1 = patch_d[patch_off + bit_pattern_31_[patt+1] * 32 + bit_pattern_31_[patt]]; patt += 2
val |= (t0 < t1) << 1;
t0 = patch_d[patch_off + bit_pattern_31_[patt+1] * 32 + bit_pattern_31_[patt]]; patt += 2
t1 = patch_d[patch_off + bit_pattern_31_[patt+1] * 32 + bit_pattern_31_[patt]]; patt += 2
val |= (t0 < t1) << 2;
t0 = patch_d[patch_off + bit_pattern_31_[patt+1] * 32 + bit_pattern_31_[patt]]; patt += 2
t1 = patch_d[patch_off + bit_pattern_31_[patt+1] * 32 + bit_pattern_31_[patt]]; patt += 2
val |= (t0 < t1) << 3;
t0 = patch_d[patch_off + bit_pattern_31_[patt+1] * 32 + bit_pattern_31_[patt]]; patt += 2
t1 = patch_d[patch_off + bit_pattern_31_[patt+1] * 32 + bit_pattern_31_[patt]]; patt += 2
val |= (t0 < t1) << 4;
t0 = patch_d[patch_off + bit_pattern_31_[patt+1] * 32 + bit_pattern_31_[patt]]; patt += 2
t1 = patch_d[patch_off + bit_pattern_31_[patt+1] * 32 + bit_pattern_31_[patt]]; patt += 2
val |= (t0 < t1) << 5;
t0 = patch_d[patch_off + bit_pattern_31_[patt+1] * 32 + bit_pattern_31_[patt]]; patt += 2
t1 = patch_d[patch_off + bit_pattern_31_[patt+1] * 32 + bit_pattern_31_[patt]]; patt += 2
val |= (t0 < t1) << 6;
t0 = patch_d[patch_off + bit_pattern_31_[patt+1] * 32 + bit_pattern_31_[patt]]; patt += 2
t1 = patch_d[patch_off + bit_pattern_31_[patt+1] * 32 + bit_pattern_31_[patt]]; patt += 2
val |= (t0 < t1) << 7;
descr_d[descr_off+b] = val;
}
descr_off += DESCR_SIZE;
}
}
};
})();
global.orb = orb;
})(jsfeat);
/**
* @author Eugene Zatepyakin / http://inspirit.ru/
*
* this code is a rewrite from OpenCV's Lucas-Kanade optical flow implementation
*/
(function(global) {
"use strict";
//
var optical_flow_lk = (function() {
// short link to shar deriv
var scharr_deriv = jsfeat.imgproc.scharr_derivatives;
return {
track: function(prev_pyr, curr_pyr, prev_xy, curr_xy, count, win_size, max_iter, status, eps, min_eigen_threshold) {
if (typeof max_iter === "undefined") { max_iter = 30; }
if (typeof status === "undefined") { status = new Uint8Array(count); }
if (typeof eps === "undefined") { eps = 0.01; }
if (typeof min_eigen_threshold === "undefined") { min_eigen_threshold = 0.0001; }
var half_win = (win_size-1)*0.5;
var win_area = (win_size*win_size)|0;
var win_area2 = win_area << 1;
var prev_imgs = prev_pyr.data, next_imgs = curr_pyr.data;
var img_prev=prev_imgs[0].data,img_next=next_imgs[0].data;
var w0 = prev_imgs[0].cols, h0 = prev_imgs[0].rows,lw=0,lh=0;
var iwin_node = jsfeat.cache.get_buffer(win_area<<2);
var deriv_iwin_node = jsfeat.cache.get_buffer(win_area2<<2);
var deriv_lev_node = jsfeat.cache.get_buffer((h0*(w0<<1))<<2);
var deriv_m = new jsfeat.matrix_t(w0, h0, jsfeat.S32C2_t, deriv_lev_node.data);
var iwin_buf = iwin_node.i32;
var deriv_iwin = deriv_iwin_node.i32;
var deriv_lev = deriv_lev_node.i32;
var dstep=0,src=0,dsrc=0,iptr=0,diptr=0,jptr=0;
var lev_sc=0.0,prev_x=0.0,prev_y=0.0,next_x=0.0,next_y=0.0;
var prev_delta_x=0.0,prev_delta_y=0.0,delta_x=0.0,delta_y=0.0;
var iprev_x=0,iprev_y=0,inext_x=0,inext_y=0;
var i=0,j=0,x=0,y=0,level=0,ptid=0,iter=0;
var brd_tl=0,brd_r=0,brd_b=0;
var a=0.0,b=0.0,b1=0.0,b2=0.0;
// fixed point math
var W_BITS14 = 14;
var W_BITS4 = 14;
var W_BITS1m5 = W_BITS4 - 5;
var W_BITS1m51 = (1 << ((W_BITS1m5) - 1));
var W_BITS14_ = (1 << W_BITS14);
var W_BITS41 = (1 << ((W_BITS4) - 1));
var FLT_SCALE = 1.0/(1 << 20);
var iw00=0,iw01=0,iw10=0,iw11=0,ival=0,ixval=0,iyval=0;
var A11=0.0,A12=0.0,A22=0.0,D=0.0,min_eig=0.0;
var FLT_EPSILON = 0.00000011920929;
eps *= eps;
// reset status
for(; i < count; ++i) {
status[i] = 1;
}
var max_level = (prev_pyr.levels - 1)|0;
level = max_level;
for(; level >= 0; --level) {
lev_sc = (1.0/(1 << level));
lw = w0 >> level;
lh = h0 >> level;
dstep = lw << 1;
img_prev = prev_imgs[level].data;
img_next = next_imgs[level].data;
brd_r = (lw - win_size)|0;
brd_b = (lh - win_size)|0;
// calculate level derivatives
scharr_deriv(prev_imgs[level], deriv_m);
// iterate through points
for(ptid = 0; ptid < count; ++ptid) {
i = ptid << 1;
j = i + 1;
prev_x = prev_xy[i]*lev_sc;
prev_y = prev_xy[j]*lev_sc;
if( level == max_level ) {
next_x = prev_x;
next_y = prev_y;
} else {
next_x = curr_xy[i]*2.0;
next_y = curr_xy[j]*2.0;
}
curr_xy[i] = next_x;
curr_xy[j] = next_y;
prev_x -= half_win;
prev_y -= half_win;
iprev_x = prev_x|0;
iprev_y = prev_y|0;
// border check
x = (iprev_x <= brd_tl)|(iprev_x >= brd_r)|(iprev_y <= brd_tl)|(iprev_y >= brd_b);
if( x != 0 ) {
if( level == 0 ) {
status[ptid] = 0;
}
continue;
}
a = prev_x - iprev_x;
b = prev_y - iprev_y;
iw00 = (((1.0 - a)*(1.0 - b)*W_BITS14_) + 0.5)|0;
iw01 = ((a*(1.0 - b)*W_BITS14_) + 0.5)|0;
iw10 = (((1.0 - a)*b*W_BITS14_) + 0.5)|0;
iw11 = (W_BITS14_ - iw00 - iw01 - iw10);
A11 = 0.0, A12 = 0.0, A22 = 0.0;
// extract the patch from the first image, compute covariation matrix of derivatives
for( y = 0; y < win_size; ++y ) {
src = ( (y + iprev_y)*lw + iprev_x )|0;
dsrc = src << 1;
iptr = (y*win_size)|0;
diptr = iptr << 1;
for(x = 0 ; x < win_size; ++x, ++src, ++iptr, dsrc += 2) {
ival = ( (img_prev[src])*iw00 + (img_prev[src+1])*iw01 +
(img_prev[src+lw])*iw10 + (img_prev[src+lw+1])*iw11 );
ival = (((ival) + W_BITS1m51) >> (W_BITS1m5));
ixval = ( deriv_lev[dsrc]*iw00 + deriv_lev[dsrc+2]*iw01 +
deriv_lev[dsrc+dstep]*iw10 + deriv_lev[dsrc+dstep+2]*iw11 );
ixval = (((ixval) + W_BITS41) >> (W_BITS4));
iyval = ( deriv_lev[dsrc+1]*iw00 + deriv_lev[dsrc+3]*iw01 + deriv_lev[dsrc+dstep+1]*iw10 +
deriv_lev[dsrc+dstep+3]*iw11 );
iyval = (((iyval) + W_BITS41) >> (W_BITS4));
iwin_buf[iptr] = ival;
deriv_iwin[diptr++] = ixval;
deriv_iwin[diptr++] = iyval;
A11 += ixval*ixval;
A12 += ixval*iyval;
A22 += iyval*iyval;
}
}
A11 *= FLT_SCALE; A12 *= FLT_SCALE; A22 *= FLT_SCALE;
D = A11*A22 - A12*A12;
min_eig = (A22 + A11 - Math.sqrt((A11-A22)*(A11-A22) + 4.0*A12*A12)) / win_area2;
if( min_eig < min_eigen_threshold || D < FLT_EPSILON )
{
if( level == 0 ) {
status[ptid] = 0;
}
continue;
}
D = 1.0/D;
next_x -= half_win;
next_y -= half_win;
prev_delta_x = 0.0;
prev_delta_y = 0.0;
for( iter = 0; iter < max_iter; ++iter ) {
inext_x = next_x|0;
inext_y = next_y|0;
x = (inext_x <= brd_tl)|(inext_x >= brd_r)|(inext_y <= brd_tl)|(inext_y >= brd_b);
if( x != 0 ) {
if( level == 0 ) {
status[ptid] = 0;
}
break;
}
a = next_x - inext_x;
b = next_y - inext_y;
iw00 = (((1.0 - a)*(1.0 - b)*W_BITS14_) + 0.5)|0;
iw01 = ((a*(1.0 - b)*W_BITS14_) + 0.5)|0;
iw10 = (((1.0 - a)*b*W_BITS14_) + 0.5)|0;
iw11 = (W_BITS14_ - iw00 - iw01 - iw10);
b1 = 0.0, b2 = 0.0;
for( y = 0; y < win_size; ++y ) {
jptr = ( (y + inext_y)*lw + inext_x )|0;
iptr = (y*win_size)|0;
diptr = iptr << 1;
for( x = 0 ; x < win_size; ++x, ++jptr, ++iptr ) {
ival = ( (img_next[jptr])*iw00 + (img_next[jptr+1])*iw01 +
(img_next[jptr+lw])*iw10 + (img_next[jptr+lw+1])*iw11 );
ival = (((ival) + W_BITS1m51) >> (W_BITS1m5));
ival = (ival - iwin_buf[iptr]);
b1 += ival * deriv_iwin[diptr++];
b2 += ival * deriv_iwin[diptr++];
}
}
b1 *= FLT_SCALE;
b2 *= FLT_SCALE;
delta_x = ((A12*b2 - A22*b1) * D);
delta_y = ((A12*b1 - A11*b2) * D);
next_x += delta_x;
next_y += delta_y;
curr_xy[i] = next_x + half_win;
curr_xy[j] = next_y + half_win;
if( delta_x*delta_x + delta_y*delta_y <= eps ) {
break;
}
if( iter > 0 && Math.abs(delta_x + prev_delta_x) < 0.01 &&
Math.abs(delta_y + prev_delta_y) < 0.01 ) {
curr_xy[i] -= delta_x*0.5;
curr_xy[j] -= delta_y*0.5;
break;
}
prev_delta_x = delta_x;
prev_delta_y = delta_y;
}
} // points loop
} // levels loop
jsfeat.cache.put_buffer(iwin_node);
jsfeat.cache.put_buffer(deriv_iwin_node);
jsfeat.cache.put_buffer(deriv_lev_node);
}
};
})();
global.optical_flow_lk = optical_flow_lk;
})(jsfeat);
/**
* @author Eugene Zatepyakin / http://inspirit.ru/
*
* this code is a rewrite from https://github.com/mtschirs/js-objectdetect implementation
* @author Martin Tschirsich / http://www.tu-darmstadt.de/~m_t
*/
(function(global) {
"use strict";
//
var haar = (function() {
var _group_func = function(r1, r2) {
var distance = (r1.width * 0.25 + 0.5)|0;
return r2.x <= r1.x + distance &&
r2.x >= r1.x - distance &&
r2.y <= r1.y + distance &&
r2.y >= r1.y - distance &&
r2.width <= (r1.width * 1.5 + 0.5)|0 &&
(r2.width * 1.5 + 0.5)|0 >= r1.width;
}
return {
edges_density: 0.07,
detect_single_scale: function(int_sum, int_sqsum, int_tilted, int_canny_sum, width, height, scale, classifier) {
var win_w = (classifier.size[0] * scale)|0,
win_h = (classifier.size[1] * scale)|0,
step_x = (0.5 * scale + 1.5)|0,
step_y = step_x;
var i,j,k,x,y,ex=(width-win_w)|0,ey=(height-win_h)|0;
var w1=(width+1)|0,edge_dens,mean,variance,std;
var inv_area = 1.0 / (win_w * win_h);
var stages,stage,trees,tree,sn,tn,fn,found=true,stage_thresh,stage_sum,tree_sum,feature,features;
var fi_a,fi_b,fi_c,fi_d,fw,fh;
var ii_a=0,ii_b=win_w,ii_c=win_h*w1,ii_d=ii_c+win_w;
var edges_thresh = ((win_w*win_h) * 0xff * this.edges_density)|0;
// if too much gradient we also can skip
//var edges_thresh_high = ((win_w*win_h) * 0xff * 0.3)|0;
var rects = [];
for(y = 0; y < ey; y += step_y) {
ii_a = y * w1;
for(x = 0; x < ex; x += step_x, ii_a += step_x) {
mean = int_sum[ii_a]
- int_sum[ii_a+ii_b]
- int_sum[ii_a+ii_c]
+ int_sum[ii_a+ii_d];
// canny prune
if(int_canny_sum) {
edge_dens = (int_canny_sum[ii_a]
- int_canny_sum[ii_a+ii_b]
- int_canny_sum[ii_a+ii_c]
+ int_canny_sum[ii_a+ii_d]);
if(edge_dens < edges_thresh || mean < 20) {
x += step_x, ii_a += step_x;
continue;
}
}
mean *= inv_area;
variance = (int_sqsum[ii_a]
- int_sqsum[ii_a+ii_b]
- int_sqsum[ii_a+ii_c]
+ int_sqsum[ii_a+ii_d]) * inv_area - mean * mean;
std = variance > 0. ? Math.sqrt(variance) : 1;
stages = classifier.complexClassifiers;
sn = stages.length;
found = true;
for(i = 0; i < sn; ++i) {
stage = stages[i];
stage_thresh = stage.threshold;
trees = stage.simpleClassifiers;
tn = trees.length;
stage_sum = 0;
for(j = 0; j < tn; ++j) {
tree = trees[j];
tree_sum = 0;
features = tree.features;
fn = features.length;
if(tree.tilted === 1) {
for(k=0; k < fn; ++k) {
feature = features[k];
fi_a = ~~(x + feature[0] * scale) + ~~(y + feature[1] * scale) * w1;
fw = ~~(feature[2] * scale);
fh = ~~(feature[3] * scale);
fi_b = fw * w1;
fi_c = fh * w1;
tree_sum += (int_tilted[fi_a]
- int_tilted[fi_a + fw + fi_b]
- int_tilted[fi_a - fh + fi_c]
+ int_tilted[fi_a + fw - fh + fi_b + fi_c]) * feature[4];
}
} else {
for(k=0; k < fn; ++k) {
feature = features[k];
fi_a = ~~(x + feature[0] * scale) + ~~(y + feature[1] * scale) * w1;
fw = ~~(feature[2] * scale);
fh = ~~(feature[3] * scale);
fi_c = fh * w1;
tree_sum += (int_sum[fi_a]
- int_sum[fi_a+fw]
- int_sum[fi_a+fi_c]
+ int_sum[fi_a+fi_c+fw]) * feature[4];
}
}
stage_sum += (tree_sum * inv_area < tree.threshold * std) ? tree.left_val : tree.right_val;
}
if (stage_sum < stage_thresh) {
found = false;
break;
}
}
if(found) {
rects.push({"x" : x,
"y" : y,
"width" : win_w,
"height" : win_h,
"neighbor" : 1,
"confidence" : stage_sum});
x += step_x, ii_a += step_x;
}
}
}
return rects;
},
detect_multi_scale: function(int_sum, int_sqsum, int_tilted, int_canny_sum, width, height, classifier, scale_factor, scale_min) {
if (typeof scale_factor === "undefined") { scale_factor = 1.2; }
if (typeof scale_min === "undefined") { scale_min = 1.0; }
var win_w = classifier.size[0];
var win_h = classifier.size[1];
var rects = [];
while (scale_min * win_w < width && scale_min * win_h < height) {
rects = rects.concat(this.detect_single_scale(int_sum, int_sqsum, int_tilted, int_canny_sum, width, height, scale_min, classifier));
scale_min *= scale_factor;
}
return rects;
},
// OpenCV method to group detected rectangles
group_rectangles: function(rects, min_neighbors) {
if (typeof min_neighbors === "undefined") { min_neighbors = 1; }
var i, j, n = rects.length;
var node = [];
for (i = 0; i < n; ++i) {
node[i] = {"parent" : -1,
"element" : rects[i],
"rank" : 0};
}
for (i = 0; i < n; ++i) {
if (!node[i].element)
continue;
var root = i;
while (node[root].parent != -1)
root = node[root].parent;
for (j = 0; j < n; ++j) {
if( i != j && node[j].element && _group_func(node[i].element, node[j].element)) {
var root2 = j;
while (node[root2].parent != -1)
root2 = node[root2].parent;
if(root2 != root) {
if(node[root].rank > node[root2].rank)
node[root2].parent = root;
else {
node[root].parent = root2;
if (node[root].rank == node[root2].rank)
node[root2].rank++;
root = root2;
}
/* compress path from node2 to the root: */
var temp, node2 = j;
while (node[node2].parent != -1) {
temp = node2;
node2 = node[node2].parent;
node[temp].parent = root;
}
/* compress path from node to the root: */
node2 = i;
while (node[node2].parent != -1) {
temp = node2;
node2 = node[node2].parent;
node[temp].parent = root;
}
}
}
}
}
var idx_seq = [];
var class_idx = 0;
for(i = 0; i < n; i++) {
j = -1;
var node1 = i;
if(node[node1].element) {
while (node[node1].parent != -1)
node1 = node[node1].parent;
if(node[node1].rank >= 0)
node[node1].rank = ~class_idx++;
j = ~node[node1].rank;
}
idx_seq[i] = j;
}
var comps = [];
for (i = 0; i < class_idx+1; ++i) {
comps[i] = {"neighbors" : 0,
"x" : 0,
"y" : 0,
"width" : 0,
"height" : 0,
"confidence" : 0};
}
// count number of neighbors
for(i = 0; i < n; ++i) {
var r1 = rects[i];
var idx = idx_seq[i];
if (comps[idx].neighbors == 0)
comps[idx].confidence = r1.confidence;
++comps[idx].neighbors;
comps[idx].x += r1.x;
comps[idx].y += r1.y;
comps[idx].width += r1.width;
comps[idx].height += r1.height;
comps[idx].confidence = Math.max(comps[idx].confidence, r1.confidence);
}
var seq2 = [];
// calculate average bounding box
for(i = 0; i < class_idx; ++i) {
n = comps[i].neighbors;
if (n >= min_neighbors)
seq2.push({"x" : (comps[i].x * 2 + n) / (2 * n),
"y" : (comps[i].y * 2 + n) / (2 * n),
"width" : (comps[i].width * 2 + n) / (2 * n),
"height" : (comps[i].height * 2 + n) / (2 * n),
"neighbors" : comps[i].neighbors,
"confidence" : comps[i].confidence});
}
var result_seq = [];
n = seq2.length;
// filter out small face rectangles inside large face rectangles
for(i = 0; i < n; ++i) {
var r1 = seq2[i];
var flag = true;
for(j = 0; j < n; ++j) {
var r2 = seq2[j];
var distance = (r2.width * 0.25 + 0.5)|0;
if(i != j &&
r1.x >= r2.x - distance &&
r1.y >= r2.y - distance &&
r1.x + r1.width <= r2.x + r2.width + distance &&
r1.y + r1.height <= r2.y + r2.height + distance &&
(r2.neighbors > Math.max(3, r1.neighbors) || r1.neighbors < 3)) {
flag = false;
break;
}
}
if(flag)
result_seq.push(r1);
}
return result_seq;
}
};
})();
global.haar = haar;
})(jsfeat);
/**
* BBF: Brightness Binary Feature
*
* @author Eugene Zatepyakin / http://inspirit.ru/
*
* this code is a rewrite from https://github.com/liuliu/ccv implementation
* @author Liu Liu / http://liuliu.me/
*
* The original paper refers to: YEF∗ Real-Time Object Detection, Yotam Abramson and Bruno Steux
*/
(function(global) {
"use strict";
//
var bbf = (function() {
var _group_func = function(r1, r2) {
var distance = (r1.width * 0.25 + 0.5)|0;
return r2.x <= r1.x + distance &&
r2.x >= r1.x - distance &&
r2.y <= r1.y + distance &&
r2.y >= r1.y - distance &&
r2.width <= (r1.width * 1.5 + 0.5)|0 &&
(r2.width * 1.5 + 0.5)|0 >= r1.width;
}
var img_pyr = new jsfeat.pyramid_t(1);
return {
interval: 4,
scale: 1.1486,
next: 5,
scale_to: 1,
// make features local copy
// to avoid array allocation with each scale
// this is strange but array works faster than Int32 version???
prepare_cascade: function(cascade) {
var sn = cascade.stage_classifier.length;
for (var j = 0; j < sn; j++) {
var orig_feature = cascade.stage_classifier[j].feature;
var f_cnt = cascade.stage_classifier[j].count;
var feature = cascade.stage_classifier[j]._feature = new Array(f_cnt);
for (var k = 0; k < f_cnt; k++) {
feature[k] = {"size" : orig_feature[k].size,
"px" : new Array(orig_feature[k].size),
"pz" : new Array(orig_feature[k].size),
"nx" : new Array(orig_feature[k].size),
"nz" : new Array(orig_feature[k].size)};
}
}
},
build_pyramid: function(src, min_width, min_height, interval) {
if (typeof interval === "undefined") { interval = 4; }
var sw=src.cols,sh=src.rows;
var i=0,nw=0,nh=0;
var new_pyr=false;
var src0=src,src1=src;
var data_type = jsfeat.U8_t | jsfeat.C1_t;
this.interval = interval;
this.scale = Math.pow(2, 1 / (this.interval + 1));
this.next = (this.interval + 1)|0;
this.scale_to = (Math.log(Math.min(sw / min_width, sh / min_height)) / Math.log(this.scale))|0;
var pyr_l = ((this.scale_to + this.next * 2) * 4) | 0;
if(img_pyr.levels != pyr_l) {
img_pyr.levels = pyr_l;
img_pyr.data = new Array(pyr_l);
new_pyr = true;
img_pyr.data[0] = src; // first is src
}
for (i = 1; i <= this.interval; ++i) {
nw = (sw / Math.pow(this.scale, i))|0;
nh = (sh / Math.pow(this.scale, i))|0;
src0 = img_pyr.data[i<<2];
if(new_pyr || nw != src0.cols || nh != src0.rows) {
img_pyr.data[i<<2] = new jsfeat.matrix_t(nw, nh, data_type);
src0 = img_pyr.data[i<<2];
}
jsfeat.imgproc.resample(src, src0, nw, nh);
}
for (i = this.next; i < this.scale_to + this.next * 2; ++i) {
src1 = img_pyr.data[(i << 2) - (this.next << 2)];
src0 = img_pyr.data[i<<2];
nw = src1.cols >> 1;
nh = src1.rows >> 1;
if(new_pyr || nw != src0.cols || nh != src0.rows) {
img_pyr.data[i<<2] = new jsfeat.matrix_t(nw, nh, data_type);
src0 = img_pyr.data[i<<2];
}
jsfeat.imgproc.pyrdown(src1, src0);
}
for (i = this.next * 2; i < this.scale_to + this.next * 2; ++i) {
src1 = img_pyr.data[(i << 2) - (this.next << 2)];
nw = src1.cols >> 1;
nh = src1.rows >> 1;
src0 = img_pyr.data[(i<<2)+1];
if(new_pyr || nw != src0.cols || nh != src0.rows) {
img_pyr.data[(i<<2)+1] = new jsfeat.matrix_t(nw, nh, data_type);
src0 = img_pyr.data[(i<<2)+1];
}
jsfeat.imgproc.pyrdown(src1, src0, 1, 0);
//
src0 = img_pyr.data[(i<<2)+2];
if(new_pyr || nw != src0.cols || nh != src0.rows) {
img_pyr.data[(i<<2)+2] = new jsfeat.matrix_t(nw, nh, data_type);
src0 = img_pyr.data[(i<<2)+2];
}
jsfeat.imgproc.pyrdown(src1, src0, 0, 1);
//
src0 = img_pyr.data[(i<<2)+3];
if(new_pyr || nw != src0.cols || nh != src0.rows) {
img_pyr.data[(i<<2)+3] = new jsfeat.matrix_t(nw, nh, data_type);
src0 = img_pyr.data[(i<<2)+3];
}
jsfeat.imgproc.pyrdown(src1, src0, 1, 1);
}
return img_pyr;
},
detect: function(pyramid, cascade) {
var interval = this.interval;
var scale = this.scale;
var next = this.next;
var scale_upto = this.scale_to;
var i=0,j=0,k=0,n=0,x=0,y=0,q=0,sn=0,f_cnt=0,q_cnt=0,p=0,pmin=0,nmax=0,f=0,i4=0,qw=0,qh=0;
var sum=0.0, alpha, feature, orig_feature, feature_k, feature_o, flag = true, shortcut=true;
var scale_x = 1.0, scale_y = 1.0;
var dx = [0, 1, 0, 1];
var dy = [0, 0, 1, 1];
var seq = [];
var pyr=pyramid.data, bpp = 1, bpp2 = 2, bpp4 = 4;
var u8 = [], u8o = [0,0,0];
var step = [0,0,0];
var paddings = [0,0,0];
for (i = 0; i < scale_upto; i++) {
i4 = (i<<2);
qw = pyr[i4 + (next << 3)].cols - (cascade.width >> 2);
qh = pyr[i4 + (next << 3)].rows - (cascade.height >> 2);
step[0] = pyr[i4].cols * bpp;
step[1] = pyr[i4 + (next << 2)].cols * bpp;
step[2] = pyr[i4 + (next << 3)].cols * bpp;
paddings[0] = (pyr[i4].cols * bpp4) - (qw * bpp4);
paddings[1] = (pyr[i4 + (next << 2)].cols * bpp2) - (qw * bpp2);
paddings[2] = (pyr[i4 + (next << 3)].cols * bpp) - (qw * bpp);
sn = cascade.stage_classifier.length;
for (j = 0; j < sn; j++) {
orig_feature = cascade.stage_classifier[j].feature;
feature = cascade.stage_classifier[j]._feature;
f_cnt = cascade.stage_classifier[j].count;
for (k = 0; k < f_cnt; k++) {
feature_k = feature[k];
feature_o = orig_feature[k];
q_cnt = feature_o.size|0;
for (q = 0; q < q_cnt; q++) {
feature_k.px[q] = (feature_o.px[q] * bpp) + feature_o.py[q] * step[feature_o.pz[q]];
feature_k.pz[q] = feature_o.pz[q];
feature_k.nx[q] = (feature_o.nx[q] * bpp) + feature_o.ny[q] * step[feature_o.nz[q]];
feature_k.nz[q] = feature_o.nz[q];
}
}
}
u8[0] = pyr[i4].data; u8[1] = pyr[i4 + (next<<2)].data;
for (q = 0; q < 4; q++) {
u8[2] = pyr[i4 + (next<<3) + q].data;
u8o[0] = (dx[q]*bpp2) + dy[q] * (pyr[i4].cols*bpp2);
u8o[1] = (dx[q]*bpp) + dy[q] * (pyr[i4 + (next<<2)].cols*bpp);
u8o[2] = 0;
for (y = 0; y < qh; y++) {
for (x = 0; x < qw; x++) {
sum = 0;
flag = true;
sn = cascade.stage_classifier.length;
for (j = 0; j < sn; j++) {
sum = 0;
alpha = cascade.stage_classifier[j].alpha;
feature = cascade.stage_classifier[j]._feature;
f_cnt = cascade.stage_classifier[j].count;
for (k = 0; k < f_cnt; k++) {
feature_k = feature[k];
pmin = u8[feature_k.pz[0]][u8o[feature_k.pz[0]] + feature_k.px[0]];
nmax = u8[feature_k.nz[0]][u8o[feature_k.nz[0]] + feature_k.nx[0]];
if (pmin <= nmax) {
sum += alpha[k << 1];
} else {
shortcut = true;
q_cnt = feature_k.size;
for (f = 1; f < q_cnt; f++) {
if (feature_k.pz[f] >= 0) {
p = u8[feature_k.pz[f]][u8o[feature_k.pz[f]] + feature_k.px[f]];
if (p < pmin) {
if (p <= nmax) {
shortcut = false;
break;
}
pmin = p;
}
}
if (feature_k.nz[f] >= 0) {
n = u8[feature_k.nz[f]][u8o[feature_k.nz[f]] + feature_k.nx[f]];
if (n > nmax) {
if (pmin <= n) {
shortcut = false;
break;
}
nmax = n;
}
}
}
sum += (shortcut) ? alpha[(k << 1) + 1] : alpha[k << 1];
}
}
if (sum < cascade.stage_classifier[j].threshold) {
flag = false;
break;
}
}
if (flag) {
seq.push({"x" : (x * 4 + dx[q] * 2) * scale_x,
"y" : (y * 4 + dy[q] * 2) * scale_y,
"width" : cascade.width * scale_x,
"height" : cascade.height * scale_y,
"neighbor" : 1,
"confidence" : sum});
++x;
u8o[0] += bpp4;
u8o[1] += bpp2;
u8o[2] += bpp;
}
u8o[0] += bpp4;
u8o[1] += bpp2;
u8o[2] += bpp;
}
u8o[0] += paddings[0];
u8o[1] += paddings[1];
u8o[2] += paddings[2];
}
}
scale_x *= scale;
scale_y *= scale;
}
return seq;
},
// OpenCV method to group detected rectangles
group_rectangles: function(rects, min_neighbors) {
if (typeof min_neighbors === "undefined") { min_neighbors = 1; }
var i, j, n = rects.length;
var node = [];
for (i = 0; i < n; ++i) {
node[i] = {"parent" : -1,
"element" : rects[i],
"rank" : 0};
}
for (i = 0; i < n; ++i) {
if (!node[i].element)
continue;
var root = i;
while (node[root].parent != -1)
root = node[root].parent;
for (j = 0; j < n; ++j) {
if( i != j && node[j].element && _group_func(node[i].element, node[j].element)) {
var root2 = j;
while (node[root2].parent != -1)
root2 = node[root2].parent;
if(root2 != root) {
if(node[root].rank > node[root2].rank)
node[root2].parent = root;
else {
node[root].parent = root2;
if (node[root].rank == node[root2].rank)
node[root2].rank++;
root = root2;
}
/* compress path from node2 to the root: */
var temp, node2 = j;
while (node[node2].parent != -1) {
temp = node2;
node2 = node[node2].parent;
node[temp].parent = root;
}
/* compress path from node to the root: */
node2 = i;
while (node[node2].parent != -1) {
temp = node2;
node2 = node[node2].parent;
node[temp].parent = root;
}
}
}
}
}
var idx_seq = [];
var class_idx = 0;
for(i = 0; i < n; i++) {
j = -1;
var node1 = i;
if(node[node1].element) {
while (node[node1].parent != -1)
node1 = node[node1].parent;
if(node[node1].rank >= 0)
node[node1].rank = ~class_idx++;
j = ~node[node1].rank;
}
idx_seq[i] = j;
}
var comps = [];
for (i = 0; i < class_idx+1; ++i) {
comps[i] = {"neighbors" : 0,
"x" : 0,
"y" : 0,
"width" : 0,
"height" : 0,
"confidence" : 0};
}
// count number of neighbors
for(i = 0; i < n; ++i) {
var r1 = rects[i];
var idx = idx_seq[i];
if (comps[idx].neighbors == 0)
comps[idx].confidence = r1.confidence;
++comps[idx].neighbors;
comps[idx].x += r1.x;
comps[idx].y += r1.y;
comps[idx].width += r1.width;
comps[idx].height += r1.height;
comps[idx].confidence = Math.max(comps[idx].confidence, r1.confidence);
}
var seq2 = [];
// calculate average bounding box
for(i = 0; i < class_idx; ++i) {
n = comps[i].neighbors;
if (n >= min_neighbors)
seq2.push({"x" : (comps[i].x * 2 + n) / (2 * n),
"y" : (comps[i].y * 2 + n) / (2 * n),
"width" : (comps[i].width * 2 + n) / (2 * n),
"height" : (comps[i].height * 2 + n) / (2 * n),
"neighbors" : comps[i].neighbors,
"confidence" : comps[i].confidence});
}
var result_seq = [];
n = seq2.length;
// filter out small face rectangles inside large face rectangles
for(i = 0; i < n; ++i) {
var r1 = seq2[i];
var flag = true;
for(j = 0; j < n; ++j) {
var r2 = seq2[j];
var distance = (r2.width * 0.25 + 0.5)|0;
if(i != j &&
r1.x >= r2.x - distance &&
r1.y >= r2.y - distance &&
r1.x + r1.width <= r2.x + r2.width + distance &&
r1.y + r1.height <= r2.y + r2.height + distance &&
(r2.neighbors > Math.max(3, r1.neighbors) || r1.neighbors < 3)) {
flag = false;
break;
}
}
if(flag)
result_seq.push(r1);
}
return result_seq;
}
};
})();
global.bbf = bbf;
})(jsfeat);
/**
* @author Eugene Zatepyakin / http://inspirit.ru/
*/
(function(lib) {
"use strict";
if (typeof module === "undefined" || typeof module.exports === "undefined") {
// in a browser, define its namespaces in global
window.jsfeat = lib;
} else {
// in commonjs, or when AMD wrapping has been applied, define its namespaces as exports
module.exports = lib;
}
})(jsfeat);
};
BundleModuleCode['plugins/image/wavelet']=function (module,exports,global,process){
/**
* Created by Favre Cyril on 01.04.17.
http://bigwww.epfl.ch/demo/ip/algorithms/Wavelet.js
http://bigwww.epfl.ch/demo/ip/demos/wavelets/index.js
Uses ImageAccess for image class (input ...):
https://github.com/Biomedical-Imaging-Group/image-access
The following image(Access) object methods must be implemented:
createEmpty
getSubImage
putSubImage
getRow
putRow
getColumn
putColumn
getPixel
putPixel
getMinimum
getMaximum
getInterpolatedPixel
*/
(function(window) {
"use strict";
var _Wavelet = {};
_Wavelet.convolve = function convolve(input, wx, wy) {
var m = input.width;
var out = ImageAccess.createEmpty( m, m );
for (var j = 0; j < m; j++) {
var x = input.getRow( j );
var y = _Wavelet.convolver( x, wx );
out.putRow( j, y );
}
for (var i = 0; i < m; i++) {
x = out.getColumn( i );
y = _Wavelet.convolver( x, wy );
out.putColumn( i, y );
}
return out;
};
_Wavelet.convolver = function(u, mask) {
var m = u.length;
var n = mask.length;
var h = Math.floor(n / 2);
var nh = n - h;
var v = [];
for (var k = 0; k < m; k++) {
v[k] = 0;
for(var j = -h; j <= h; j++){
var km = k - j;
while (km >= m) {
km = -km + 2 * (n - 1);
}
while(km < 0) {
km = -km;
while (km >= m) {
km = -km + 2 * (n - 1);
}
}
v[k] += u[km] * mask[j + h];
}
}
return v;
};
_Wavelet.getScalingFunction = function(order) {
if ( order === 0 ) {
return [1];
}
else if ( order === 1 ) {
var m = Math.sqrt( 2 );
return [1 / m, 1 / m, 0];
}
else {
var t = Math.sqrt( 3 );
var n = 4 * Math.sqrt( 2 );
return [(1 - t) / n, (3 - t) / n, (3 + t) / n, (1 + t) / n, 0];
}
};
_Wavelet.getWaveletFunction = function(order) {
if ( order === 0 ) {
return [1];
}
else if ( order === 1 ) {
var m = Math.sqrt( 2 );
return [-1 / m, 1 / m, 0];
}
else {
var t = Math.sqrt( 3 );
var n = 4 * Math.sqrt( 2 );
return [(-1 - t) / n, (3 + t) / n, (t - 3) / n, (1 - t) / n, 0];
}
};
_Wavelet.reflect = function(arr) {
var n = arr.length;
var out = [];
for (var i = 0; i < n; i++)
out[i] = arr[n - 1 - i];
return out;
};
_Wavelet.analyze = function(image, n, order) {
var nx = image.width;
var ny = image.height;
var output = image.clone();
for (var i = 0; i < n; i++) {
var sub = output.getSubImage( 0, 0, nx, ny );
sub = _Wavelet.analyze1( sub, order );
output.putSubImage( 0, 0, sub );
nx = nx / 2;
ny = ny / 2;
}
return output;
};
_Wavelet.analyze1 = function(input, order) {
var m = input.width;
var s = _Wavelet.getScalingFunction( order );
var w = _Wavelet.getWaveletFunction( order );
var merge = ImageAccess.createEmpty( m, m );
merge.putSubImage( 0, 0, _Wavelet.downSample( _Wavelet.convolve( input, s, s ) ) );
merge.putSubImage( m / 2, 0, _Wavelet.downSample( _Wavelet.convolve( input, w, s ) ) );
merge.putSubImage( 0, m / 2, _Wavelet.downSample( _Wavelet.convolve( input, s, w ) ) );
merge.putSubImage( m / 2, m / 2, _Wavelet.downSample( _Wavelet.convolve( input, w, w ) ) );
return merge;
};
_Wavelet.synthesize = function(image, n, order) {
var div = Math.pow( 2, n - 1 );
var nx = image.width / div;
var ny = image.height / div;
var output = image.clone();
for (var i = 0; i < n; i++) {
var sub = output.getSubImage( 0, 0, nx, ny );
sub = _Wavelet.synthesize1( sub, order );
output.putSubImage( 0, 0, sub );
nx = nx * 2;
ny = ny * 2;
}
return output;
};
_Wavelet.synthesize1 = function(coef, order) {
var m = coef.width;
var s = _Wavelet.reflect( _Wavelet.getScalingFunction( order ) );
var w = _Wavelet.reflect( _Wavelet.getWaveletFunction( order ) );
var LL = coef.getSubImage( 0, 0, m / 2, m / 2 );
var HL = coef.getSubImage( m / 2, 0, m / 2, m / 2 );
var LH = coef.getSubImage( 0, m / 2, m / 2, m / 2 );
var HH = coef.getSubImage( m / 2, m / 2, m / 2, m / 2 );
LL = _Wavelet.convolve( _Wavelet.upSample( LL ), s, s );
HL = _Wavelet.convolve( _Wavelet.upSample( HL ), w, s );
LH = _Wavelet.convolve( _Wavelet.upSample( LH ), s, w );
HH = _Wavelet.convolve( _Wavelet.upSample( HH ), w, w );
LL.add( LH );
LL.add( HL );
LL.add( HH );
return LL;
};
_Wavelet.downSample = function(input) {
var m = Math.floor(input.width / 2);
var out = new ImageAccess( m, m );
for (var k = 0; k < m; k++)
for (var l = 0; l < m; l++)
out.putPixel( k, l, input.getPixel( 2 * k, 2 * l ) );
return out;
};
_Wavelet.upSample = function(input) {
var m = input.width;
var out = ImageAccess.createEmpty( m * 2, m * 2 );
for (var k = 0; k < m; k++)
for (var l = 0; l < m; l++)
out.putPixel( 2 * k, 2 * l, input.getPixel( k, l ) );
return out;
};
_Wavelet.keepLowpass = function(input, n) {
var nx = input.width;
var ny = input.height;
var p = Math.pow(2, n);
var out = ImageAccess.createEmpty( nx, ny );
var sub = input.getSubImage( 0, 0, nx / p, ny / p );
out.putSubImage( 0, 0, sub );
return out;
};
_Wavelet.doSoftThreshold = function(input, threshold) {
var nx = input.width;
var ny = input.height;
var output = ImageAccess.createEmpty( nx, ny );
for (var x = 0; x < nx; x++)
for (var y = 0; y < ny; y++) {
var pixel = input.getPixel( x, y );
if ( pixel < -threshold ) {
pixel = pixel + threshold;
}
else if ( pixel > threshold ) {
pixel = pixel - threshold;
}
else {
pixel = 0.0;
}
output.putPixel( x, y, pixel );
}
return output;
};
_Wavelet.denoiseAuto = function(input) {
var coef = _Wavelet.analyze( input, 3, 2 );
var nx = input.width;
var ny = input.height;
var sub = coef.getSubImage( nx / 2, ny / 2, nx / 2, ny / 2 );
var threshold = _Wavelet.stdDev( sub );
return _Wavelet.synthesize( _Wavelet.doSoftThreshold( coef, threshold ), 3, 2 );
};
_Wavelet.stdDev = function(image) {
var mean = image.getMean();
var stdDev = 0.0;
for (var i = 0; i < image.width; i++)
for (var j = 0; j < image.height; j++) {
var v = image.getPixel( i, j );
stdDev += (v - mean) * (v - mean);
}
return Math.sqrt( stdDev / (image.width * image.height) );
};
_Wavelet.splines = {};
_Wavelet.splines.analyze = function(input, n, order) {
var nx = input.width;
var ny = input.height;
for (var i = 0; i < n; i++) {
var sub = input.getSubImage(0, 0, nx, ny);
sub = _Wavelet.splines.analysis1(sub, order);
input.putSubImage(0, 0, sub);
nx = nx / 2;
ny = ny / 2;
}
return input;
};
_Wavelet.splines.analysis1 = function(input, order) {
var nx = input.width;
var ny = input.height;
var u = [];
var v = [];
var filters = _Wavelet.splines.getSplineFilter(order);
for (var y = 0; y < ny; y++) {
u = input.getRow(y);
v = _Wavelet.splines.splitMirror(u, filters.h, filters.g);
input.putRow(y, v);
}
for (var x = 0; x < nx; x++) {
u = input.getColumn(x);
v = _Wavelet.splines.splitMirror(u, filters.h, filters.g);
input.putColumn(x, v);
}
return input;
};
_Wavelet.splines.synthesis = function(input, scales, order) {
var div = Math.floor( Math.pow(2, scales - 1) );
var nx = Math.max(1, input.width / div);
var ny = Math.max(1, input.height / div);
var out = input.clone();
for ( var i=0; i= n)
j1 = period - j1; // Symmetrize
}
j2 = j + k;
if (j2 >= n) { // Mirror conditions
while (j2 >= n)
j2 -= period; // Periodize
if (j2 < 0)
j2 = -j2; // Symmetrize
}
pix += h[k] * (vin[j1] + vin[j2]);
}
vout[i] = pix;
j = j + 1;
pix = vin[j] * g[0]; // High pass part
for (k = 1; k < ng; k++) {
j1 = j - k;
if (j1 < 0) { // Mirror conditions
while (j1 < 0)
j1 += period; // Periodize
if (j1 >= n)
j1 = period - j1; // Symmetrize
}
j2 = j + k;
if (j2 >= n) { // Mirror conditions
while (j2 >= n)
j2 -= period; // Periodize
if (j2 < 0)
j2 = -j2; // Symmetrize
}
pix += g[k] * (vin[j1] + vin[j2]);
}
vout[i + n2] = pix;
}
return vout;
};
_Wavelet.splines.mergeMirror = function(vin, h, g) {
var n = vin.length;
var n2 = Math.floor(n / 2);
var nh = h.length;
var ng = g.length;
var vout = [];
var pix1, pix2;
var j, k, kk, i1, i2;
var k01 = Math.floor(nh / 2) * 2 - 1;
var k02 = Math.floor(ng / 2) * 2 - 1;
var period = 2 * n2 - 1; // period for mirror boundary conditions
for (var i = 0; i < n2; i++) {
j = 2 * i;
pix1 = h[0] * vin[i];
for (k = 2; k < nh; k += 2) {
i1 = i - (k / 2);
if (i1 < 0) {
i1 = (-i1) % period;
if (i1 >= n2)
i1 = period - i1;
}
i2 = i + (k / 2);
if (i2 > n2 - 1) {
i2 = i2 % period;
if (i2 >= n2)
i2 = period - i2;
}
pix1 = pix1 + h[k] * (vin[i1] + vin[i2]);
}
pix2 = 0.;
for (k = -k02; k < ng; k += 2) {
kk = Math.abs(k);
i1 = i + (k - 1) / 2;
if (i1 < 0) {
i1 = (-i1 - 1) % period;
if (i1 >= n2)
i1 = period - 1 - i1;
}
if (i1 >= n2) {
i1 = i1 % period;
if (i1 >= n2)
i1 = period - 1 - i1;
}
pix2 = pix2 + g[kk] * vin[i1 + n2];
}
vout[j] = (pix1 + pix2);
j = j + 1;
pix1 = 0.;
for (k = -k01; k < nh; k += 2) {
kk = Math.abs(k);
i1 = i + (k + 1) / 2;
if (i1 < 0) {
i1 = (-i1) % period;
if (i1 >= n2)
i1 = period - i1;
}
if (i1 >= n2) {
i1 = (i1) % period;
if (i1 >= n2)
i1 = period - i1;
}
pix1 = pix1 + h[kk] * vin[i1];
}
pix2 = g[0] * vin[i + n2];
for (k = 2; k < ng; k += 2) {
i1 = i - (k / 2);
if (i1 < 0) {
i1 = (-i1 - 1) % period;
if (i1 >= n2)
i1 = period - 1 - i1;
}
i2 = i + (k / 2);
if (i2 > n2 - 1) {
i2 = i2 % period;
if (i2 >= n2)
i2 = period - 1 - i2;
}
pix2 = pix2 + g[k] * (vin[i1 + n2] + vin[i2 + n2]);
}
vout[j] = (pix1 + pix2);
}
return vout;
};
_Wavelet.splines.getSplineFilter = function(order) {
var h = [], g = [];
switch (order) {
case 1:
h = [
0.81764640621546, 0.39729708810751, -0.06910098743038, -0.05194534825542, 0.01697104840045, 0.00999059568192, -0.00388326235731, -0.00220195129177, 0.00092337104427, 0.00051163604209, -0.00022429633694, -0.00012268632858,
0.00005535633860, 0.00003001119291, -0.00001381880394, -0.00000744435611, 0.00000347980027, 0.00000186561005, -0.00000088225856, -0.00000047122304, 0.00000022491351, 0.00000011976480, -0.00000005759525, -0.00000003059265,
0.00000001480431, 0.00000000784714, -0.00000000381742, -0.00000000201987, 0.00000000098705, 0.00000000052147, -0.00000000025582, -0.00000000013497, 0.00000000006644, 0.00000000003501, -0.00000000001729, -0.00000000000910,
0.00000000000451, 0.00000000000237, -0.00000000000118, -0.00000000000062, 0.00000000000031, 0.00000000000016, -0.00000000000008, -0.00000000000004, 0.00000000000002, 0.00000000000001, 0
];
break;
case 3:
h = [
0.76613005375980, 0.43392263358931, -0.05020172467149, -0.11003701838811, 0.03208089747022, 0.04206835144072, -0.01717631549201, -0.01798232098097, 0.00868529481309, 0.00820147720600, -0.00435383945777, -0.00388242526560,
0.00218671237015, 0.00188213352389, -0.00110373982039, -0.00092719873146, 0.00055993664336, 0.00046211522752, -0.00028538371867, -0.00023234729403, 0.00014604186978, 0.00011762760216, -0.00007499842461, -0.00005987934057,
0.00003863216129, 0.00003062054907, -0.00001995254847, -0.00001571784835, 0.00001032898225, 0.00000809408097, -0.00000535805976 - 0.00000417964096, 0.00000278450629, 0.00000216346143, -0.00000144942177, -0.00000112219704,
0.00000075557065, 0.00000058316635, -0.00000039439119, -0.00000030355006, 0.00000020610937, 0.00000015823692, -0.00000010783016, -0.00000008259641, 0.00000005646954, 0.00000004316539, -0.00000002959949, -0.00000002258313,
0.00000001552811, 0.00000001182675, -0.00000000815248, -0.00000000619931, 0.00000000428324, 0.00000000325227, -0.00000000225188, -0.00000000170752, 0.00000000118465, 0.00000000089713, -0.00000000062357, -0.00000000047167,
0.00000000032841, 0.00000000024814, -0.00000000017305, -0.00000000013062, 0.00000000009123, 0.00000000006879, -0.00000000004811, -0.00000000003625, 0.00000000002539, 0.00000000001911, -0.00000000001340, -0.00000000001008,
0.00000000000708, 0.00000000000532, -0.00000000000374, -0.00000000000281, 0.00000000000198, 0.00000000000148, -0.00000000000104, -0.00000000000078, 0.00000000000055, 0.00000000000041, -0.00000000000029, -0.00000000000022,
0.00000000000015, 0.00000000000012, -0.00000000000008 - 0.00000000000006, 0.00000000000004, 0.00000000000003, -0.00000000000002, -0.00000000000002, 0.00000000000001, 0.00000000000001, -0.00000000000001, -0.00000000000000,
0
];
break;
case 5:
h = [
0.74729, 0.4425, -0.037023, -0.12928, 0.029477, 0.061317, -0.021008, -0.032523, 0.014011, 0.01821, -0.0090501, -0.010563, 0.0057688, 0.0062796, -0.0036605, -0.0037995, 0.0023214, 0.0023288, -0.0014738, -0.0014414, 0.00093747,
0.00089889, -0.00059753, -0.00056398, 0.00038165, 0.00035559, -0.00024423, -0.00022512, 0.00015658, 0.00014301, -0.00010055, -9.1113e-05, 6.4669e-05, 5.8198e-05, -4.1649e-05, -3.7256e-05, 2.729e-05, 2.458e-05, -2.2593e-05,
-3.5791e-05, -1.7098e-05, -2.9619e-06, 0
];
break;
}
if ( order > 0 ) {
g[0] = h[0];
for (var k = 1; k < h.length; k++) {
if ( k % 2 == 0 )
g[k] = h[k];
else
g[k] = -h[k];
}
}
else {
g[0] = -h[0];
}
return {h: h, g: g};
};
// Export the object
window.Wavelet = _Wavelet;
}( typeof module == 'object' && module.exports? module.exports:window ));
};
BundleModuleCode['plugins/image/adathres']=function (module,exports,global,process){
/*
Adaptive threshold filtering of images (binarization)
https://github.com/FujiHaruka/node-adaptive-threshold
*/
// https://github.com/scijs/zeros/blob/master/zeros.js
function dtypeToType(dtype) {
switch(dtype) {
case 'uint8':
return Uint8Array;
case 'uint16':
return Uint16Array;
case 'uint32':
return Uint32Array;
case 'int8':
return Int8Array;
case 'int16':
return Int16Array;
case 'int32':
return Int32Array;
case 'float':
case 'float32':
return Float32Array;
case 'double':
case 'float64':
return Float64Array;
case 'uint8_clamped':
return Uint8ClampedArray;
case 'generic':
case 'buffer':
case 'data':
case 'dataview':
return ArrayBuffer;
case 'array':
return Array;
}
}
function ndarray(data,shape) {
if (shape.length==2) {
var w = shape[0],
h = shape[1]
return {
data:data,
shape:shape,
get : function (x,y) {
return data[(y*w)+x]
},
set : function (x,y,v) {
data[(y*w)+x]=v
}
}
}
if (shape.length==3) {
var w = shape[0],
h = shape[1],
d = shape[2]
return {
data:data,
shape:shape,
get : function (x,y,z) {
return data[((y*w)+x)*d+z]
},
set : function (x,y,z,v) {
data[((y*w)+x)*d+z]=v
}
}
}
}
function zeros(shape, dtype) {
dtype = dtype || 'float64';
var sz = 1;
for(var i=0; i= mWidth) {
mX = mWidth - 1
} else if (y - midSize < 0) {
mY = 0
} else if (y - midSize > mHeight) {
mY = mHeight - 1
}
let mean = meanMatrix.get(mX, mY)
let threshold = mean - compensation
if (pixel < threshold) {
res.set(x, y, invert?0:255)
} else {
res.set(x, y, invert?255:0)
}
}
}
return {
width:width,
height:height,
depth:1,
data:res.data
}
}
module.exports = adaptiveThreshold
};
BundleModuleCode['plugins/image/clahe']=function (module,exports,global,process){
/*
https://stackoverflow.com/questions/38346702/how-to-implement-contrast-limited-adaptive-histogram-equalization-using-clahe-in
https://jsfiddle.net/Subhasish2015/abwLtneb/1/
var iml = document.getElementById('imageLoader');
iml.addEventListener('change', handleImage, false);
var cnv = document.getElementById('imageCanvas');
var ctx = cnv.getContext('2d');
var cnvori = document.getElementById('imageOriginalCanvas')
var ctxori = cnvori.getContext('2d');
*/
// typeof options = {odepth,invert,scale,clipLimit,tileSize}
function clahe(img,options) {
var imgData = img.data,
depth = img.depth,
h = img.height,
w = img.width,
pixelLength = h * w,
odepth = (options && options.odepth) || depth,
invert = (options && options.invert) || false,
scale = (options && options.scale) || 1,
dstData = new Uint8Array(pixelLength*odepth);
var min = 255,
max = 0;
var intens = new Uint8Array(pixelLength);
if (/int16/.test(imgData.constructor.name)) scale=256;
if (/int32/.test(imgData.constructor.name)) scale=256*256*256;
var levels = [];
var j = 0;
switch (depth) {
case 1:
for (var i = 0; i < imgData.length; i++) {
intens[i] = imgData[i]/scale;
}
break;
case 3:
for (var i = 0; i < imgData.length; i += 3) {
intens[j] = (imgData[i] + imgData[i + 1] + imgData[i + 2]) / 3 / scale;
j++;
}
break;
case 4:
for (var i = 0; i < imgData.length; i += 4) {
intens[j] = (imgData[i] + imgData[i + 1] + imgData[i + 2]) / 3 / scale;
j++;
}
break;
}
var tilesize = options.tileSize?[options.tileSize,options.tileSize]: [32, 32];
var clipLimit = options.clipLimit || 0.1;
// number of bins
var num_bins = 256;
// number of tiles in x and y direction
var xtiles = Math.ceil(w / tilesize[0]);
var ytiles = Math.ceil(h / tilesize[1]);
var cdfs = new Array(ytiles);
for (var i = 0; i < ytiles; i++)
cdfs[i] = new Array(xtiles);
var inv_tile_size = [1.0 / tilesize[0], 1.0 / tilesize[1]];
var cdf = [];
// create histograms
for (var i = 0; i < ytiles; i++) {
var y0 = i * tilesize[1];
var y1 = y0 + tilesize[1];
for (var j = 0; j < xtiles; j++) {
var x0 = j * tilesize[0];
var x1 = x0 + tilesize[0];
var hist = histogram(intens, x0, y0, x1, y1, num_bins, h, w);
cdfs[i][j] = buildcdf(hist, num_bins, tilesize[0] * tilesize[1], clipLimit);
}
}
var finalArray = new Uint8Array(imgData.length);
var p = 0;
for (var y = 0, idx = 0; y < h; ++y) {
for (var x = 0; x < w; ++x, idx += 4) {
// intensity of current pixel
var I = Math.floor(intens[y * w + x]);
var tx = x * inv_tile_size[0] - 0.5;
var ty = y * inv_tile_size[1] - 0.5;
var xl = Math.max(Math.floor(tx), 0);
var xr = Math.min(xl + 1, xtiles - 1);
var yt = Math.max(Math.floor(ty), 0);
var yd = Math.min(yt + 1, ytiles - 1);
var fx = tx - xl;
var fy = ty - yt;
var cdf11 = (cdfs[yt][xl][I]) * 255;
var cdf12 = (cdfs[yd][xl][I]) * 255;
var cdf21 = (cdfs[yt][xr][I]) * 255;
var cdf22 = (cdfs[yd][xr][I]) * 255;
var Iout = (1 - fx) * (1 - fy) * cdf11 +
(1 - fx) * fy * cdf12 +
fx * (1 - fy) * cdf21 +
fx * fy * cdf22;
finalArray[p] = Iout;
p++;
}
}
switch (odepth) {
case 1:
for (var index = 0; index < pixelLength; index++) {
var result = finalArray[index];
dstData[index] = invert?255-result:result;
}
break;
case 3:
for (var index = 0, indexToFill = 3; index < pixelLength; index++, indexToFill = indexToFill + 3) {
var result = finalArray[index];
dstData[indexToFill - 3] =
dstData[indexToFill - 2] =
dstData[indexToFill - 1] = invert?255-result:result;
}
break;
case 4:
for (var index = 0, indexToFill = 3; index < pixelLength; index++, indexToFill = indexToFill + 4) {
var result = finalArray[index];
dstData[indexToFill - 3] = // 0
dstData[indexToFill - 2] =
dstData[indexToFill - 1] = invert?255 - result:result;
dstData[indexToFill] = 255; // 255 - result
}
break;
}
return {
width:w,
height:h,
depth:odepth,
data:dstData
}
}
var getInputArray = function(mArray, x, y, hDiff, vDiff, rows, columns) {
var inputArray = [];
var k = 0;
for (var i = x - vDiff; i <= x + vDiff; i++) {
for (var j = y - hDiff; j <= y + hDiff; j++) {
if (i >= 0 && j >= 0 && i < rows && j < columns) {
inputArray[k] = mArray[i][j];
} else {
inputArray[k] = 0;
}
k++;
}
}
var finalResult = getHEArray(inputArray, x, y, mArray);
return finalResult;
}
// build cdf from given pdf
function buildcdf(hist, num_bins, num_pixels, clipLimit) {
var excess = 0;
for (var i = 0; i < num_bins; ++i) {
hist[i] = hist[i] / num_pixels;
if (hist[i] > clipLimit) {
excess = excess + hist[i] - clipLimit;
hist[i] = clipLimit;
}
}
var addExcess = excess / num_bins;
var cumuhist = [];
cumuhist[0] = hist[0] + addExcess;
for (var i = 1; i < num_bins; ++i)
cumuhist[i] = cumuhist[i - 1] + hist[i] + addExcess;
return cumuhist;
}
function histogram(intens, x1, y1, x2, y2, num_bins, h, w) {
var hist = [];
for (var i = 0; i < num_bins; ++i)
hist[i] = 0;
for (var y = y1; y < y2; ++y) {
for (var x = x1; x < x2; ++x) {
var idx;
if (x >= w && y < h) {
idx = (y * w + (w - 1));
} else if (y >= h && x < w) {
idx = ((h - 1) * w + x);
} else if (y >= h && x >= w) {
idx = (h * w) - 1;
} else {
idx = (y * w + x);
}
var val = Math.floor(intens[idx]);
hist[val]++;
}
}
return hist;
}
module.exports = clahe
};
BundleModuleCode['plugins/image/otsu']=function (module,exports,global,process){
const histo = (data, bins) =>
data.reduce((arr, e) => {
arr[bins.indexOf(e)] += 1;
return arr;
}, [...Array(bins.length)].fill(0));
const width = (hist, s, e) => {
let v = 0;
for (let i = s; i < e; i += 1) {
v += hist[i];
}
return v;
};
const bins = data => Array.from(new Set(data)).sort((e0, e1) => e0 - e1);
const weight = (hist, s, e, total) => {
let v = 0;
for (let i = s; i < e; i += 1) {
v += hist[i];
}
return v / total;
};
const mean = (hist, bins, s, e, width) => {
let v = 0;
for (let i = s; i < e; i += 1) {
v += hist[i] * bins[i];
}
return v * width;
};
const variance = (hist, bins, s, e, mean, width) => {
let v = 0;
for (let i = s; i < e; i += 1) {
const d = bins[i] - mean;
v += d * d * hist[i];
}
return v * width;
};
const cross = (wb, vb, wf, vf) => wb * vb + wf * vf;
function otsu(data) {
const b = bins(data);
const h = histo(data, b);
const { length: total } = data;
const vars = [...Array(b.length)].map((_, i) => {
const s0 = 0;
const e0 = i;
const s1 = i;
const e1 = h.length;
const w0 = 1 / width(h, s0, e0);
const w1 = 1 / width(h, s1, e1);
const wb = weight(h, s0, e0, total);
const vb = variance(h, b, s0, e0, mean(h, b, s0, e0, w0), w0);
const wf = weight(h, s1, e1, total);
const vf = variance(h, b, s1, e1, mean(h, b, s1, e1, w1), w1);
const x = cross(wb, vb, wf, vf);
return !isNaN(x) ? x : Number.POSITIVE_INFINITY;
});
return b[vars.indexOf(Math.min(...vars))];
};
module.exports = otsu
};
BundleModuleCode['plugins/image/triangle']=function (module,exports,global,process){
// Triangular threshold computation (from ImageJ)
function triangularThresholdSplit(hist) {
var histogram = hist.slice();
// Zack, G. W., Rogers, W. E. and Latt, S. A., 1977,
// Automatic Measurement of Sister Chromatid Exchange Frequency,
// Journal of Histochemistry and Cytochemistry 25 (7), pp. 741-753
//
// modified from Johannes Schindelin plugin
//
// find min and max
var min = 0, max = 0, min2 = 0;
var dmax = 0;
for (var i = 0; i < histogram.length; i++) {
if (histogram[i] > 0) {
min = i;
break;
}
}
if (min > 0)
min--; // line to the (p==0) point, not to histogram[min]
// The Triangle algorithm cannot tell whether the data is skewed to one
// side
// or another. This causes a problem as there are 2 possible thresholds
// between the max and the 2 extremes of the histogram. Here I propose
// to
// find out to which side of the max point the data is furthest, and use
// that as the other extreme.
for (var i = histogram.length - 1; i > 0; i--) {
if (histogram[i] > 0) {
min2 = i;
break;
}
}
// line to the (p==0) point, not to histogram[min]
if (min2 < histogram.length - 1)
min2++;
for (var i = 0; i < histogram.length; i++) {
if (histogram[i] > dmax) {
max = i;
dmax = histogram[i];
}
}
// find which is the furthest side
// IJ.log(""+min+" "+max+" "+min2);
var inverted = false;
if ((max - min) < (min2 - max)) {
// reverse the histogram
// IJ.log("Reversing histogram.");
inverted = true;
var left = 0; // index of leftmost element
var right = histogram.length - 1; // index of rightmost element
while (left < right) {
// exchange the left and right elements
var temp = histogram[left];
histogram[left] = histogram[right];
histogram[right] = temp;
// move the bounds toward the center
left++;
right--;
}
min = histogram.length - 1 - min2;
max = histogram.length - 1 - max;
}
if (min == max) {
// IJ.log("Triangle: min == max.");
return min;
}
// describe line by nx * x + ny * y - d = 0
var nx, ny, d;
// nx is just the max frequency as the other point has freq=0
// lowest value bmin = (p=0)% in the image
nx = histogram[max]; // -min; // histogram[min];
ny = min - max;
d = Math.sqrt(nx * nx + ny * ny);
nx /= d;
ny /= d;
d = nx * min + ny * histogram[min];
// find split point
var split = min;
var splitDistance = 0;
for (var i = min + 1; i <= max; i++) {
var newDistance = nx * i + ny * histogram[i] - d;
if (newDistance > splitDistance) {
split = i;
splitDistance = newDistance;
}
}
split--;
if (inverted) {
// The histogram might be used for something else, so let's reverse
// it
// back
var left = 0;
var right = histogram.length - 1;
while (left < right) {
var temp = histogram[left];
histogram[left] = histogram[right];
histogram[right] = temp;
left++;
right--;
}
return (histogram.length - 1 - split);
}
return split;
}
module.exports = function triangle(data,bins,range) {
bins=bins||256
range=range||256
var dh = range/bins
var hist = Array(bins).fill(0)
for(var i=0;i maxi )
maxi = input.getPixel(x+i, y+j);
}
out.putPixel(x, y, maxi);
}
return out;
};
ImageProcessing.min = function( input ) {
var out = new ImageAccess(input.width, input.height);
for(var x = 0; x < input.width; x++)
for(var y = 0; y < input.height; y++) {
var mini = Number.MAX_VALUE;
for (var i = -1; i<=1; i++)
for (var j = -1; j<=1; j++) {
if ( input.getPixel( x+i, y+j ) < mini )
mini = input.getPixel(x+i, y+j);
}
out.putPixel(x, y, mini);
}
return out;
};
ImageProcessing.snr = function( input1, input2 ) {
var tmp1 = 0.0;
var tmp2 = 0.0;
for(var i = 0; i < input1.length; i++) {
tmp1 += input2[i];
tmp2 += Math.abs( input1[i] - input2[i] );
}
return tmp1 / tmp2;
};
ImageProcessing.subtract = function( input1, input2 ) {
var out = new ImageAccess(input1.width, input1.height);
for(var x = 0; x < input1.width; x++)
for(var y = 0; y < input1.height; y++) {
out.putPixel(x, y, input1.getPixel(x, y) - input2.getPixel(x, y));
}
return out;
};
ImageProcessing.open = function( input ) {
return ImageProcessing.max(ImageProcessing.min(input));
};
ImageProcessing.close = function( input ) {
return ImageProcessing.min(ImageProcessing.max(input));
};
ImageProcessing.tophatBright = function( input ) {
return ImageProcessing.subtract(input, ImageProcessing.open(input));
};
ImageProcessing.tophatDark = function( input ) {
return ImageProcessing.subtract(ImageProcessing.close(input), input);
};
ImageProcessing.gradientMorpho = function( input ) {
return ImageProcessing.subtract(ImageProcessing.max(input), ImageProcessing.min(input));
};
/**
*
* @param {number[]} u
* @param {number[]} ker
* @return {number[]} v
*/
var correlate3 = function(u, ker) {
var n = u.length;
var v = [];
v[0] = ker[0] * u[1] + ker[1] * u[0] + ker[2] * u[1];
for (var k = 1; k < n - 1; k++) {
v[k] = ker[0] * u[k - 1] + ker[1] * u[k] + ker[2] * u[k + 1];
}
v[n - 1] = ker[0] * u[n - 2] + ker[1] * u[n - 1] + ker[2] * u[n - 2];
return v;
};
/**
* @param {ImageAccess} input
* @return {ImageAccess[]} gradient
*/
ImageProcessing.gradient3 = function(input) {
var nx = input.width;
var ny = input.height;
var gradient = [];
gradient[0] = ImageAccess.createEmpty( nx, ny ); // to store the magnitude
var gradient2 = ImageProcessing.gradient2( input );
gradient[1] = gradient2[0];
gradient[2] = gradient2[1];
var vx, vy, g;
for (var x = 0; x < nx; x++) {
for (var y = 0; y < ny; y++) {
vx = gradient[1].getPixel( x, y );
vy = gradient[2].getPixel( x, y );
g = Math.sqrt( vx * vx + vy * vy );
// TODO : division by zero
gradient[0].putPixel( x, y, g );
gradient[1].putPixel( x, y, vx / g || 0 );
gradient[2].putPixel( x, y, vy / g || 0 );
}
}
return gradient;
};
/**
* @param {ImageAccess} input
* @return {ImageAccess[]} gradient
*/
ImageProcessing.gradient2 = function(input) {
var nx = input.width;
var ny = input.height;
var kernel1 = [-1 / 2, 0, 1 / 2];
var kernel0 = [1 / 6, 4 / 6, 1 / 6];
var ru, rv, cu, cv;
var gx = ImageAccess.createEmpty( nx, ny );
var gy = ImageAccess.createEmpty( nx, ny );
for (var y = 0; y < ny; y++) {
ru = input.getRow( y );
rv = correlate3( ru, kernel1 );
gx.putRow( y, rv );
}
for (var x = 0; x < nx; x++) {
cu = gx.getColumn( x );
cv = correlate3( cu, kernel0 );
gx.putColumn( x, cv );
}
for (y = 0; y < ny; y++) {
ru = input.getRow( y );
rv = correlate3( ru, kernel0 );
gy.putRow( y, rv );
}
for (x = 0; x < nx; x++) {
cu = gy.getColumn( x );
cv = correlate3( cu, kernel1 );
gy.putColumn( x, cv );
}
return [gx, gy];
};
/**
*
* @param {ImageAccess[]} input
* @return {ImageAccess} out
*/
ImageProcessing.applyNonMaximumSuppression = function(input) {
var nx = input[0].width;
var ny = input[0].height;
var out = new ImageAccess( nx, ny );
var g1, g2, g, dx, dy;
for (var y = 0; y < ny; y++) {
for (var x = 0; x < nx; x++) {
g = input[0].getPixel( x, y );
if ( g !== 0 ) {
dx = input[1].getPixel( x, y );
dy = input[2].getPixel( x, y );
g1 = input[0].getInterpolatedPixel( x - dx, y - dy );
if ( g >= g1 ) {
g2 = input[0].getInterpolatedPixel( x + dx, y + dy );
if ( g >= g2 ) {
out.putPixel( x, y, g );
}
}
}
}
}
return out;
};
/**
*
* @param {ImageAccess} input
* @return {ImageAccess[]}
*/
ImageProcessing.hessian = function(input) {
var nx = input.width;
var ny = input.height;
var kernel0 = [1.0 / 6.0, 4.0 / 6.0, 1.0 / 6.0];
var kernel1 = [-1.0 / 2.0, 0.0, 1.0 / 2.0];
var kernel2 = [1.0, -2.0, 1.0];
var ru,
rxx,
rxy,
ryy,
cu,
cout0,
cout1,
cout2;
// Second Derivative in X axis
var hxx = ImageAccess.createEmpty( nx, ny );
var hyy = ImageAccess.createEmpty( nx, ny );
var hxy = ImageAccess.createEmpty( nx, ny );
for (var x = 0; x < nx; x++) {
cu = input.getColumn( x );
cout0 = correlate3( cu, kernel0 );
hxx.putColumn( x, cout0 );
cout2 = correlate3( cu, kernel2 );
hyy.putColumn( x, cout2 );
cout1 = correlate3( cu, kernel1 );
hxy.putColumn( x, cout1 );
}
for (var y = 0; y < ny; y++) {
ru = hxx.getRow( y );
rxx = correlate3( ru, kernel2 );
hxx.putRow( y, rxx );
ru = hyy.getRow( y );
ryy = correlate3( ru, kernel0 );
hyy.putRow( y, ryy );
ru = hxy.getRow( y );
rxy = correlate3( ru, kernel1 );
hxy.putRow( y, rxy );
}
var hessian = [];
hessian[0] = new ImageAccess( nx, ny ); // to store the merit
hessian[1] = new ImageAccess( nx, ny ); // to store the orientation (x)
hessian[2] = new ImageAccess( nx, ny ); // to store the orientation (y)
var delta, cxx, cyy, cxy;
for (y = 0; y < ny; y++)
for (x = 0; x < nx; x++) {
cxx = hxx.getPixel( x, y );
cyy = hyy.getPixel( x, y );
cxy = hxy.getPixel( x, y );
delta = (cxx - cyy) * (cxx - cyy) + 4 * cxy * cxy;
if ( delta >= 0 ) {
delta = Math.sqrt( delta );
var lMin = (cxx + cyy - delta) * 0.5;
var lMax = (cxx + cyy + delta) * 0.5;
var m = Math.sqrt( Math.abs( lMin ) * Math.abs( lMin - lMax ) );
hessian[0].putPixel( x, y, m );
var dx = hxy.getPixel( x, y ) / m;
var dy = (lMin - hxx.getPixel( x, y )) / m;
var norm = Math.sqrt( dx * dx + dy * dy );
if ( norm < 0.00001 )
norm = 0.00001;
hessian[1].putPixel( x, y, dx / norm );
hessian[2].putPixel( x, y, dy / norm );
}
}
return hessian;
};
/******************************************************************************************************************/
//***************
//*************** Detector Tools
//***************
/******************************************************************************************************************/
var tolerance = 1e-6;
/**
* Convolution with a Finite Impulse Response (FIR) filter.
*
* Note: Only with the periodic boundary conditions.
*
* @param {number[]} signal 1D input signal, 1D output signal at the end (in-place)
* @param {number[]} kernel kernel of the filter
* @param {number} origin origin
*
* @return {Float32Array} output
*/
ImageProcessing.convolveFIR = function(signal, kernel, origin) {
var l = signal.length;
assert( l > 1, "convolveFIR: input signal too short" );
var output = new Float32Array( l );
var indexQ = kernel.length - 1;
var indexP = 0;
var n2 = 2 * (l - 1);
var m = 1 + origin - kernel.length;
m -= (m < 0) ? (n2 * ((m + 1 - n2) / n2)) : (n2 * (m / n2));
var i, j, sum, k, n, kp, km;
for (i = 0; i < l; i++) {
j = -kernel.length;
k = m;
indexQ = kernel.length - 1;
sum = 0;
while (j < 0) {
indexP = k;
kp = ((k - l) < j) ? (j) : (k - l);
if ( kp < 0 ) {
for (n = kp; n < 0; n++) {
sum += signal[indexP] * kernel[indexQ];
indexQ--;
indexP++;
}
k -= kp;
j -= kp;
}
indexP = n2 - k;
km = ((k - n2) < j) ? (j) : (k - n2);
if ( km < 0 ) {
for (n = km; n < 0; n++) {
sum += signal[indexP] * kernel[indexQ];
indexQ--;
indexP--;
}
j -= km;
}
k = 0;
}
if ( ++m == n2 ) {
m = 0;
}
output[i] = sum;
}
return output;
};
/**
*
* @param {number[]} c
* @param {number} z
* @return {number}
*/
function getInitialAntiCausalCoefficientMirror(c, z) {
return ((z * c[c.length - 2] + c[c.length - 1]) * z / (z * z - 1.0));
}
/**
*
* @param {number[]} c
* @param {number} z
* @return {number}
*/
function getInitialCausalCoefficientMirror(c, z) {
var z1 = z;
var zn = Math.pow( z, c.length - 1 );
var sum = c[0] + zn * c[c.length - 1];
var horizon = c.length;
if ( 0.0 < tolerance ) {
horizon = 2 + ~~(Math.log( tolerance ) / Math.log( Math.abs( z ) ));
horizon = (horizon < c.length) ? (horizon) : (c.length);
}
zn = zn * zn;
for (var n = 1, cond = horizon - 1; n < cond; n++) {
zn = zn / z;
sum = sum + (z1 + zn) * c[n];
z1 = z1 * z;
}
return (sum / (1.0 - Math.pow( z, 2 * c.length - 2 )));
}
var STRONG = 250;
var WEAK = 170;
var CANDIDATE = 128;
var BACKGROUND = 0;
var FOREGROUND = 255;
/**
* Applies a hysteresis threshold to an image.
*
* The method call a recursive method trackEdge to track
* the contour according the thresholds.
* @param {ImageAccess} input
* @param {number} thresholdLow
* @param {number} thresholdHigh
* @return {ImageAccess} output image
*/
ImageProcessing.doHysteresisThreshold = function(input, thresholdLow, thresholdHigh) {
var max = input.getMaximum();
var tl = thresholdLow / 100 * max;
var th = thresholdHigh / 100 * max;
var nx = input.width;
var ny = input.height;
var out = ImageAccess.createEmpty( nx, ny );
var value, x, y, col;
for (x = 0; x < nx; x++) {
col = input.getColumn( x ); //optimisation
for (y = 0; y < ny; y++) {
if ( col[y] > th ) {
col[y] = STRONG;
} else if ( col[y] > tl ) {
col[y] = CANDIDATE;
} else {
col[y] = BACKGROUND;
}
}
out.putColumn( x, col );
}
var neigh;
for (x = 1; x < nx - 1; x++) {
col = out.getColumn( x ); //optimisation
for (y = 1; y < ny - 1; y++) {
value = col[y];
if ( value == STRONG ) {
neigh = out.getNeighborhood( x, y, 3, 3 );
if ( neigh[2][2] == CANDIDATE )
trackEdge( out, x + 1, y + 1 );
if ( neigh[2][1] == CANDIDATE )
trackEdge( out, x + 1, y );
if ( neigh[2][0] == CANDIDATE )
trackEdge( out, x + 1, y - 1 );
if ( neigh[1][2] == CANDIDATE )
trackEdge( out, x, y + 1 );
if ( neigh[1][0] == CANDIDATE )
trackEdge( out, x, y - 1 );
if ( neigh[0][2] == CANDIDATE )
trackEdge( out, x - 1, y + 1 );
if ( neigh[0][1] == CANDIDATE )
trackEdge( out, x - 1, y );
if ( neigh[0][0] == CANDIDATE )
trackEdge( out, x - 1, y - 1 );
}
}
}
for (x = 0; x < nx; x++) {
col = out.getColumn( x );
for (y = 0; y < ny; y++) {
if ( col[y] >= WEAK )
col[y] = FOREGROUND;
else
col[y] = BACKGROUND;
}
out.putColumn( x, col );
}
return out;
};
/**
* Tracks the edges in an image.
*
* The edges are marked directly in the image.
*
* @param {ImageAccess} image input image
* @param {number} x starting point to track
* @param {number} y starting point to track
*/
function trackEdge(image, x, y) {
var nx = image.width;
var ny = image.height;
if ( x < 0 || y < 0 || x > nx - 1 || y > ny - 1 )
return;
if ( image.getPixel( x, y ) != CANDIDATE )
return;
image.putPixel( x, y, WEAK );
var neigh = image.getNeighborhood( x, y, 3, 3 );
if ( neigh[2][2] == CANDIDATE )
trackEdge( image, x + 1, y + 1 );
if ( neigh[2][1] == CANDIDATE )
trackEdge( image, x + 1, y );
if ( neigh[2][0] == CANDIDATE )
trackEdge( image, x + 1, y - 1 );
if ( neigh[1][2] == CANDIDATE )
trackEdge( image, x, y + 1 );
if ( neigh[1][0] == CANDIDATE )
trackEdge( image, x, y - 1 );
if ( neigh[0][2] == CANDIDATE )
trackEdge( image, x - 1, y + 1 );
if ( neigh[0][1] == CANDIDATE )
trackEdge( image, x - 1, y );
if ( neigh[0][0] == CANDIDATE )
trackEdge( image, x - 1, y - 1 );
}
/**
* Implements a gaussian smooth filter with a parameter sigma.
* Uses a IIR filter.
*
* Mirror border conditions are applied.
*
* N iterations of the symmetrical exponential filter (N=3)
*
*
* N sqrt(N^2 + 2*N*sigma^2)
* alpha = 1 + ------- - ------------------------
* sigma^2 sigma^2
*
* @param {ImageAccess} input an ImageAccess object
* @param {number} sigma a value of the sigma of the gaussian
* @return {ImageAccess} the smoothed version of the input image
*/
ImageProcessing.smoothGaussian = function(input, sigma) {
assert( sigma >= 0, "smoothGaussian : wrong parameter" );
if(sigma == 0)
return input.clone();
var nx = input.width;
var ny = input.height;
var out = new ImageAccess( nx, ny );
var N = 3;
var s2 = sigma * sigma;
var a = 1.0 + (N / s2) - (Math.sqrt( N * N + 2.0 * N * s2 ) / s2);
var poles = [a, a, a];
var row;
for (var y = 0; y < ny; y++) {
row = input.getRow( y );
row = convolveIIR( row, poles );
out.putRow( y, row );
}
var col;
for (var x = 0; x < nx; x++) {
col = out.getColumn( x );
col = convolveIIR( col, poles );
out.putColumn( x, col );
}
return out;
};
/**
* Convolve with with a Infinite Impluse Response filter (IIR)
*
* @param {number[]} signal 1D input signal, 1D output signal at the end (in-place)
* @param {number[]} poles 1D array containing the poles of the filter
*/
function convolveIIR(signal, poles) {
var lambda = 1;
for (var k = 0, pl = poles.length; k < pl; k++) {
lambda = lambda * (1 - poles[k]) * (1 - 1 / poles[k]);
}
for (var n = 0, sl = signal.length; n < sl; n++) {
signal[n] = signal[n] * lambda;
}
for (k = 0; k < pl; k++) {
signal[0] = getInitialCausalCoefficientMirror( signal, poles[k] );
for (n = 1; n < sl; n++) {
signal[n] = signal[n] + poles[k] * signal[n - 1];
}
signal[signal.length - 1] = getInitialAntiCausalCoefficientMirror( signal, poles[k] );
for (n = signal.length - 2; 0 <= n; n--) {
signal[n] = poles[k] * (signal[n + 1] - signal[n]);
}
}
return signal;
}
// Export the variable tp global context
window.ImageProcessing = ImageProcessing;
window.ImageAccess = ImageAccess;
})( typeof module == 'object' && module.exports? module.exports:window );
};
BundleModuleCode['plugins/image/warp']=function (module,exports,global,process){
/*
Multi-point grid image warping (distortion or correction)
https://github.com/cxcxcxcx/imgwarp-js
TODO: Remove canvas logic, replace with generic matrix logic
*/
var ImgWarper = {};
// Deformation
ImgWarper.Warper = function(img, optGridSize, optAlpha, canvas) {
this.alpha = optAlpha || 1;
this.gridSize = optGridSize || 20;
var source = img;
this.width = source.width;
this.height = source.height;
this.imgData = source.data;
this.depth = source.depth||1;
this.canvas = canvas;
// this.imgTargetData = source.data.slice();
if (this.canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
canvas.width = source.width;
canvas.height = source.height;
this.ctx.setTransform(1, 0, 0, 1, 0, 0);
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.putImageData(imgData, 0, 0);
console.log('drawn');
}
this.bilinearInterpolation =
new ImgWarper.BilinearInterpolation(this.width, this.height, this.depth);
this.grid = [];
for (var i = 0; i < this.width ; i += this.gridSize) {
for (var j = 0; j < this.height ; j += this.gridSize) {
a = new ImgWarper.Point(i,j);
b = new ImgWarper.Point(i + this.gridSize, j);
c = new ImgWarper.Point(i + this.gridSize, j + this.gridSize);
d = new ImgWarper.Point(i, j + this.gridSize);
this.grid.push([a, b, c, d]);
}
}
this.points = {
fromPoints : [],
toPoints : []
}
}
ImgWarper.Warper.prototype.addPoint = function(fromX, fromY, toX, toY) {
var p1 = new ImgWarper.Point(fromX, fromY),
p2 = new ImgWarper.Point(toX, toY);
this.points.fromPoints.push(p1)
this.points.toPoints.push(p2)
}
ImgWarper.Warper.prototype.warp = function(fromPoints, toPoints) {
if (!fromPoints) fromPoints = this.points.fromPoints
if (!toPoints) toPoints = this.points.toPoints
// console.log('warp,',fromPoints, toPoints,this.alpha)
var t0 = (new Date()).getTime();
var deformation =
new ImgWarper.AffineDeformation(toPoints, fromPoints, this.alpha);
var transformedGrid = [];
for (var i = 0; i < this.grid.length; ++i) {
transformedGrid[i] = [
deformation.pointMover(this.grid[i][0]),
deformation.pointMover(this.grid[i][1]),
deformation.pointMover(this.grid[i][2]),
deformation.pointMover(this.grid[i][3])];
}
var t1 = (new Date()).getTime();
this.warptime=t1-t0
var newImg = this.bilinearInterpolation.generate(this.imgData, this.grid, transformedGrid);
if (this.canvas) {
this.ctx.setTransform(1, 0, 0, 1, 0, 0);
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.putImageData(newImg, 0, 0);
this.drawGrid(fromPoints, toPoints);
}
return {
width : this.width,
height : this.height,
depth : this.depth,
data : newImg
}
}
ImgWarper.Warper.prototype.drawGrid = function(fromPoints, toPoints) {
if (!this.canvas) return;
// Forward warping.
var deformation =
new ImgWarper.AffineDeformation(fromPoints, toPoints, this.alpha);
var context = this.canvas.getContext("2d");
for (var i = 0; i < this.grid.length; ++i) {
context.beginPath();
var point = deformation.pointMover(this.grid[i][0]);
context.moveTo(point.x, point.y);
for (var j = 1; j < 4; ++j) {
point = deformation.pointMover(this.grid[i][j]);
context.lineTo(point.x, point.y);
}
context.strokeStyle = 'rgba(170, 170, 170, 0.5)';
context.stroke();
}
}
ImgWarper.AffineDeformation = function(fromPoints, toPoints, alpha) {
this.w = null;
this.pRelative = null;
this.qRelative = null;
this.A = null;
if (fromPoints.length != toPoints.length) {
throw Error('Points are not of same length.');
}
this.n = fromPoints.length;
this.fromPoints = fromPoints;
this.toPoints = toPoints;
this.alpha = alpha;
};
ImgWarper.AffineDeformation.prototype.pointMover = function (point){
if (null == this.pRelative || this.pRelative.length < this.n) {
this.pRelative = new Array(this.n);
}
if (null == this.qRelative || this.qRelative.length < this.n) {
this.qRelative = new Array(this.n);
}
if (null == this.w || this.w.length < this.n) {
this.w = new Array(this.n);
}
if (null == this.A || this.A.length < this.n) {
this.A = new Array(this.n);
}
for (var i = 0; i < this.n; ++i) {
var t = this.fromPoints[i].subtract(point);
this.w[i] = Math.pow(t.x * t.x + t.y * t.y, -this.alpha);
}
var pAverage = ImgWarper.Point.weightedAverage(this.fromPoints, this.w);
var qAverage = ImgWarper.Point.weightedAverage(this.toPoints, this.w);
for (var i = 0; i < this.n; ++i) {
this.pRelative[i] = this.fromPoints[i].subtract(pAverage);
this.qRelative[i] = this.toPoints[i].subtract(qAverage);
}
var B = new ImgWarper.Matrix22(0, 0, 0, 0);
for (var i = 0; i < this.n; ++i) {
B.addM(this.pRelative[i].wXtX(this.w[i]));
}
B = B.inverse();
for (var j = 0; j < this.n; ++j) {
this.A[j] = point.subtract(pAverage).multiply(B)
.dotP(this.pRelative[j]) * this.w[j];
}
var r = qAverage; //r is an point
for (var j = 0; j < this.n; ++j) {
r = r.add(this.qRelative[j].multiply_d(this.A[j]));
}
if (isNaN(r.x) || isNaN(r.y)) { r.x=point.x;r.y=point.y }
// console.log(point,r)
return r;
};
// Interpolation
ImgWarper.BilinearInterpolation = function(width, height, depth){
this.width = width;
this.height = height;
this.depth = depth;
if (this.canvas) {
this.ctx = this.canvas.getContext("2d");
this.imgTargetData = this.ctx.createImageData(this.width, this.height);
}
};
ImgWarper.BilinearInterpolation.prototype.generate = function(source, fromGrid, toGrid) {
// console.log(fromGrid, toGrid)
this.imgData = source;
this.imgTargetData = new source.constructor(source.length);
for (var i = 0; i < toGrid.length; ++i) {
this.fill(toGrid[i], fromGrid[i]);
}
return this.imgTargetData;
};
ImgWarper.BilinearInterpolation.prototype.fill = function(sourcePoints, fillingPoints) {
var i, j;
var srcX, srcY;
var x0 = fillingPoints[0].x;
var x1 = fillingPoints[2].x;
var y0 = fillingPoints[0].y;
var y1 = fillingPoints[2].y;
x0 = Math.max(x0, 0);
y0 = Math.max(y0, 0);
x1 = Math.min(x1, this.width - 1);
y1 = Math.min(y1, this.height - 1);
// console.log(sourcePoints, fillingPoints)
var xl, xr, topX, topY, bottomX, bottomY;
var yl, yr, rgb, index;
for (i = x0; i <= x1; ++i) {
xl = (i - x0) / (x1 - x0);
xr = 1 - xl;
topX = xr * sourcePoints[0].x + xl * sourcePoints[1].x;
topY = xr * sourcePoints[0].y + xl * sourcePoints[1].y;
bottomX = xr * sourcePoints[3].x + xl * sourcePoints[2].x;
bottomY = xr * sourcePoints[3].y + xl * sourcePoints[2].y;
for (j = y0; j <= y1; ++j) {
yl = (j - y0) / (y1 - y0);
yr = 1 - yl;
srcX = topX * yr + bottomX * yl;
srcY = topY * yr + bottomY * yl;
index = ((j * this.width) + i) * this.depth;
if (srcX < 0 || srcX > this.width - 1 ||
srcY < 0 || srcY > this.height - 1) {
switch (this.depth) {
case 1:
this.imgTargetData[index] = 255;
break;
case 3:
this.imgTargetData[index] = 255;
this.imgTargetData[index + 1] = 255;
this.imgTargetData[index + 2] = 255;
break;
case 4:
this.imgTargetData[index] = 255;
this.imgTargetData[index + 1] = 255;
this.imgTargetData[index + 2] = 255;
this.imgTargetData[index + 3] = 255;
break;
}
continue;
}
var srcX1 = Math.floor(srcX);
var srcY1 = Math.floor(srcY);
var base = ((srcY1 * this.width) + srcX1) * this.depth;
//rgb = this.nnquery(srcX, srcY);
switch (this.depth) {
case 1:
this.imgTargetData[index] = this.imgData[base];
break;
case 3:
this.imgTargetData[index] = this.imgData[base];
this.imgTargetData[index + 1] = this.imgData[base + 1];
this.imgTargetData[index + 2] = this.imgData[base + 2];
break;
case 4:
this.imgTargetData[index] = this.imgData[base];
this.imgTargetData[index + 1] = this.imgData[base + 1];
this.imgTargetData[index + 2] = this.imgData[base + 2];
this.imgTargetData[index + 3] = this.imgData[base + 3];
break;
}
}
}
};
ImgWarper.BilinearInterpolation.prototype.nnquery = function(x, y) {
var x1 = Math.floor(x);
var y1 = Math.floor(y);
var base = ((y1 * this.width) + x1) * this.depth;
switch (this.depth) {
case 1:
return [
this.imgData[base]];
case 3:
return [
this.imgData[base],
this.imgData[base + 1],
this.imgData[base + 2]];
case 4:
return [
this.imgData[base],
this.imgData[base + 1],
this.imgData[base + 2],
this.imgData[base + 3]];
}
};
ImgWarper.BilinearInterpolation.prototype.query = function(x, y) {
var x1,x2,y1,y2,t11,t12,t21,t22,t;
x1 = Math.floor(x); x2 = Math.ceil(x);
y1 = Math.floor(y); y2 = Math.ceil(y);
var base11 = ((y1 * this.width) + x1) * this.depth;
var base12 = ((y2 * this.width) + x1) * this.depth;
var base21 = ((y1 * this.width) + x2) * this.depth;
var base22 = ((y2 * this.width) + x2) * this.depth;
switch (this.depth) {
case 1:
// 1 channel: GRAY
var c = 9;
t11 = this.imgData[base11];
t12 = this.imgData[base12];
t21 = this.imgData[base21];
t22 = this.imgData[base22];
t = (t11 * (x2 - x) * (y2 - y) +
t21 * (x - x1) * (y2 - y) +
t12 * (x2 - x) * (y - y1) +
t22 * (x - x1) * (y - y1)) / ((x2 - x1) * (y2 - y1));
c = parseInt(t);
break;
case 3:
// 3 channels: RGB
var c = [0, 0, 0]; // get new RGB
for (var i = 0; i < 3; ++i) {
t11 = this.imgData[base11 + i];
t12 = this.imgData[base12 + i];
t21 = this.imgData[base21 + i];
t22 = this.imgData[base22 + i];
t = (t11 * (x2 - x) * (y2 - y) +
t21 * (x - x1) * (y2 - y) +
t12 * (x2 - x) * (y - y1) +
t22 * (x - x1) * (y - y1)) / ((x2 - x1) * (y2 - y1));
c[i] = parseInt(t);
}
break;
case 4:
// 4 channels: RGBA
var c = [0, 0, 0, 0]; // get new RGB
for (var i = 0; i < 4; ++i) {
t11 = this.imgData[base11 + i];
t12 = this.imgData[base12 + i];
t21 = this.imgData[base21 + i];
t22 = this.imgData[base22 + i];
t = (t11 * (x2 - x) * (y2 - y) +
t21 * (x - x1) * (y2 - y) +
t12 * (x2 - x) * (y - y1) +
t22 * (x - x1) * (y - y1)) / ((x2 - x1) * (y2 - y1));
c[i] = parseInt(t);
}
break;
}
return c;
};
// Matrix
ImgWarper.Matrix22 = function(N11, N12, N21, N22) {
this.M11 = N11;
this.M12 = N12;
this.M21 = N21;
this.M22 = N22;
};
ImgWarper.Matrix22.prototype.adjugate = function () {
return new ImgWarper.Matrix22(
this.M22, -this.M12,
-this.M21, this.M11);
};
ImgWarper.Matrix22.prototype.determinant = function () {
return this.M11 * this.M22 - this.M12 * this.M21;
};
ImgWarper.Matrix22.prototype.multiply = function (m) {
this.M11 *= m;
this.M12 *= m;
this.M21 *= m;
this.M22 *= m;
return this;
};
ImgWarper.Matrix22.prototype.addM = function(o) {
this.M11 += o.M11;
this.M12 += o.M12;
this.M21 += o.M21;
this.M22 += o.M22;
};
ImgWarper.Matrix22.prototype.inverse = function () {
return this.adjugate().multiply(1.0 / this.determinant());
};
// Point
ImgWarper.Point = function (x, y) {
this.x = x;
this.y = y;
};
ImgWarper.Point.prototype.add = function (o) {
return new ImgWarper.Point(this.x + o.x, this.y + o.y);
};
ImgWarper.Point.prototype.subtract = function (o) {
return new ImgWarper.Point(this.x - o.x, this.y - o.y);
};
// w * [x; y] * [x, y]
ImgWarper.Point.prototype.wXtX = function (w) {
return (new ImgWarper.Matrix22(
this.x * this.x * w, this.x * this.y * w,
this.y * this.x * w, this.y * this.y * w
));
};
// Dot product
ImgWarper.Point.prototype.dotP = function (o) {
return this.x * o.x + this.y * o.y;
};
ImgWarper.Point.prototype.multiply = function (o) {
return new ImgWarper.Point(
this.x * o.M11 + this.y * o.M21, this.x * o.M12 + this.y * o.M22);
};
ImgWarper.Point.prototype.multiply_d = function (o) {
return new ImgWarper.Point(this.x * o, this.y * o);
};
ImgWarper.Point.weightedAverage = function (p, w) {
var i;
var sx = 0,
sy = 0,
sw = 0;
for (i = 0; i < p.length; i++) {
sx += p[i].x * w[i];
sy += p[i].y * w[i];
sw += w[i];
}
return new ImgWarper.Point(sx / sw, sy / sw);
};
ImgWarper.Point.prototype.InfintyNormDistanceTo = function (o) {
return Math.max(Math.abs(this.x - o.x), Math.abs(this.y - o.y));
}
module.exports = ImgWarper
};
BundleModuleCode['plugins/image/smartcrop']=function (module,exports,global,process){
/**
* smartcrop.js
* A javascript library implementing content aware image cropping
*
!!! Needs canvas logic (for image resampling) !!!
Smartcrop.js implements an algorithm to find good crops for images.
It can be used in the browser, in node or via a CLI.
smartcrop.crop(image, { width: 100, height: 100 }).then(function(result) {
console.log(result);
});
// you pass in an image as well as the width & height of the crop you
// want to optimize.
// smartcrop will output you its best guess for a crop
// you can now use this data to crop the image.
{topCrop: {x: 300, y: 200, height: 200, width: 200}}
* Copyright (C) 2018 Jonas Wagner
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
if (0) (function() {
'use strict';
var smartcrop = {};
// Promise implementation to use
function NoPromises() {
throw new Error('No native promises and smartcrop.Promise not set.');
}
function ImageFromData(imagedata) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = imagedata.width;
canvas.height = imagedata.height;
ctx.putImageData(imagedata, 0, 0);
var image = new Image();
image.src = canvas.toDataURL();
return image;
}
smartcrop.Promise = typeof Promise !== 'undefined' ? Promise : NoPromises;
smartcrop.DEFAULTS = {
width: 0,
height: 0,
aspect: 0,
cropWidth: 0,
cropHeight: 0,
detailWeight: 0.2,
depth:4,
skinColor: [0.78, 0.57, 0.44],
skinBias: 0.01,
skinBrightnessMin: 0.2,
skinBrightnessMax: 1.0,
skinThreshold: 0.8,
skinWeight: 1.8,
saturationBrightnessMin: 0.05,
saturationBrightnessMax: 0.9,
saturationThreshold: 0.4,
saturationBias: 0.2,
saturationWeight: 0.1,
// Step * minscale rounded down to the next power of two should be good
scoreDownSample: 8,
step: 8,
scaleStep: 0.1,
minScale: 1.0,
maxScale: 1.0,
edgeRadius: 0.4,
edgeWeight: -20.0,
outsideImportance: -0.5,
boostWeight: 100.0,
ruleOfThirds: true,
prescale: true,
imageOperations: null,
canvasFactory: defaultCanvasFactory,
// Factory: defaultFactories,
debug: false
};
// typeOf @inputImage = Image | {width,height,depth,data}
smartcrop.crop = function(inputImage, options_, callback) {
var options = extend({}, smartcrop.DEFAULTS, options_);
if (options.aspect) {
options.width = options.aspect;
options.height = 1;
}
if (options.imageOperations === null) {
options.imageOperations = canvasImageOperations(options.canvasFactory);
}
var iop = options.imageOperations;
var scale = 1;
var prescale = 1;
if (!(inputImage instanceof Image)) {
var image = inputImage,
w = image.width,
h = image.height,
d = image.depth || (image.data.length/(w*h)),
s = w*h,
src = image.data
var imgdata = new ImageData(w,h),
data = imgdata.data
options.depth=4
switch (d) {
case 1:
for(var i=0;i min
// don't set minscale smaller than 1/scale
// -> don't pick crops that need upscaling
options.minScale = min(
options.maxScale,
max(1 / scale, options.minScale)
);
// prescale if possible
if (options.prescale !== false) {
prescale = min(max(256 / image.width, 256 / image.height), 1);
if (prescale < 1) {
image = iop.resample(
image,
image.width * prescale,
image.height * prescale
);
options.cropWidth = ~~(options.cropWidth * prescale);
options.cropHeight = ~~(options.cropHeight * prescale);
if (options.boost) {
options.boost = options.boost.map(function(boost) {
return {
x: ~~(boost.x * prescale),
y: ~~(boost.y * prescale),
width: ~~(boost.width * prescale),
height: ~~(boost.height * prescale),
weight: boost.weight
};
});
}
} else {
prescale = 1;
}
}
}
return image;
})
.then(function(image) {
return iop.getData(image).then(function(data) {
var result = analyse(options, data);
var crops = result.crops || [result.topCrop];
for (var i = 0, iLen = crops.length; i < iLen; i++) {
var crop = crops[i];
crop.x = ~~(crop.x / prescale);
crop.y = ~~(crop.y / prescale);
crop.width = ~~(crop.width / prescale);
crop.height = ~~(crop.height / prescale);
}
result.image=inputImage
if (callback) callback(result);
return result;
});
});
};
// Check if all the dependencies are there
// todo:
smartcrop.isAvailable = function(options) {
if (!smartcrop.Promise) return false;
var canvasFactory = options ? options.canvasFactory : defaultCanvasFactory;
if (canvasFactory === defaultCanvasFactory) {
var c = document.createElement('canvas');
if (!c.getContext('2d')) {
return false;
}
}
return true;
};
function edgeDetect(i, o) {
var id = i.data;
var od = o.data;
var w = i.width;
var h = i.height;
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
var p = (y * w + x) * 4;
var lightness;
if (x === 0 || x >= w - 1 || y === 0 || y >= h - 1) {
lightness = 0; // sample(id, p);
} else {
lightness =
sample(id, p) * 4 -
sample(id, p - w * 4) -
sample(id, p - 4) -
sample(id, p + 4) -
sample(id, p + w * 4);
}
od[p + 1] = Math.abs(lightness);
}
}
}
function skinDetect(options, i, o) {
var id = i.data;
var od = o.data;
var w = i.width;
var h = i.height;
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
var p = (y * w + x) * 4;
var lightness = cie(id[p], id[p + 1], id[p + 2]) / 255;
var skin = skinColor(options, id[p], id[p + 1], id[p + 2]);
var isSkinColor = skin > options.skinThreshold;
var isSkinBrightness =
lightness >= options.skinBrightnessMin &&
lightness <= options.skinBrightnessMax;
if (isSkinColor && isSkinBrightness) {
od[p] =
(skin - options.skinThreshold) *
(255 / (1 - options.skinThreshold));
} else {
od[p] = 0;
}
}
}
}
function saturationDetect(options, i, o) {
var id = i.data;
var od = o.data;
var w = i.width;
var h = i.height;
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
var p = (y * w + x) * 4;
var lightness = cie(id[p], id[p + 1], id[p + 2]) / 255;
var sat = saturation(id[p], id[p + 1], id[p + 2]);
var acceptableSaturation = sat > options.saturationThreshold;
var acceptableLightness =
lightness >= options.saturationBrightnessMin &&
lightness <= options.saturationBrightnessMax;
if (acceptableLightness && acceptableSaturation) {
od[p + 2] =
(sat - options.saturationThreshold) *
(255 / (1 - options.saturationThreshold));
} else {
od[p + 2] = 0;
}
}
}
}
function applyBoosts(options, output) {
if (!options.boost) return;
var od = output.data;
for (var i = 0; i < output.width; i += 4) {
od[i + 3] = 0;
}
for (i = 0; i < options.boost.length; i++) {
applyBoost(options.boost[i], options, output);
}
}
function applyBoost(boost, options, output) {
var od = output.data;
var w = output.width;
var x0 = ~~boost.x;
var x1 = ~~(boost.x + boost.width);
var y0 = ~~boost.y;
var y1 = ~~(boost.y + boost.height);
var weight = boost.weight * 255;
for (var y = y0; y < y1; y++) {
for (var x = x0; x < x1; x++) {
var i = (y * w + x) * 4;
od[i + 3] += weight;
}
}
}
function generateCrops(options, width, height) {
var results = [];
var minDimension = min(width, height);
var cropWidth = options.cropWidth || minDimension;
var cropHeight = options.cropHeight || minDimension;
console.log(width,height,cropWidth,cropHeight)
for (
var scale = options.maxScale;
scale >= options.minScale;
scale -= options.scaleStep
) {
for (var y = 0; y + cropHeight * scale <= height; y += options.step) {
for (var x = 0; x + cropWidth * scale <= width; x += options.step) {
results.push({
x: x,
y: y,
width: cropWidth * scale,
height: cropHeight * scale
});
}
}
}
return results;
}
function score(options, output, crop) {
var result = {
detail: 0,
saturation: 0,
skin: 0,
boost: 0,
total: 0
};
var od = output.data;
var downSample = options.scoreDownSample;
var invDownSample = 1 / downSample;
var outputHeightDownSample = output.height * downSample;
var outputWidthDownSample = output.width * downSample;
var outputWidth = output.width;
for (var y = 0; y < outputHeightDownSample; y += downSample) {
for (var x = 0; x < outputWidthDownSample; x += downSample) {
var p =
(~~(y * invDownSample) * outputWidth + ~~(x * invDownSample)) * 4;
var i = importance(options, crop, x, y);
var detail = od[p + 1] / 255;
result.skin += (od[p] / 255) * (detail + options.skinBias) * i;
result.detail += detail * i;
result.saturation +=
(od[p + 2] / 255) * (detail + options.saturationBias) * i;
result.boost += (od[p + 3] / 255) * i;
}
}
result.total =
(result.detail * options.detailWeight +
result.skin * options.skinWeight +
result.saturation * options.saturationWeight +
result.boost * options.boostWeight) /
(crop.width * crop.height);
return result;
}
function importance(options, crop, x, y) {
if (
crop.x > x ||
x >= crop.x + crop.width ||
crop.y > y ||
y >= crop.y + crop.height
) {
return options.outsideImportance;
}
x = (x - crop.x) / crop.width;
y = (y - crop.y) / crop.height;
var px = abs(0.5 - x) * 2;
var py = abs(0.5 - y) * 2;
// Distance from edge
var dx = Math.max(px - 1.0 + options.edgeRadius, 0);
var dy = Math.max(py - 1.0 + options.edgeRadius, 0);
var d = (dx * dx + dy * dy) * options.edgeWeight;
var s = 1.41 - sqrt(px * px + py * py);
if (options.ruleOfThirds) {
s += Math.max(0, s + d + 0.5) * 1.2 * (thirds(px) + thirds(py));
}
return s + d;
}
smartcrop.importance = importance;
function skinColor(options, r, g, b) {
var mag = sqrt(r * r + g * g + b * b);
var rd = r / mag - options.skinColor[0];
var gd = g / mag - options.skinColor[1];
var bd = b / mag - options.skinColor[2];
var d = sqrt(rd * rd + gd * gd + bd * bd);
return 1 - d;
}
function analyse(options, input) {
var result = {};
var output = new ImgData(input.width, input.height);
edgeDetect(input, output);
skinDetect(options, input, output);
saturationDetect(options, input, output);
applyBoosts(options, output);
var scoreOutput = downSample(output, options.scoreDownSample);
var topScore = -Infinity;
var topCrop = null;
var crops = generateCrops(options, input.width, input.height);
for (var i = 0, iLen = crops.length; i < iLen; i++) {
var crop = crops[i];
crop.score = score(options, scoreOutput, crop);
if (crop.score.total > topScore) {
topCrop = crop;
topScore = crop.score.total;
}
}
result.topCrop = topCrop;
result.crops = crops
result.output = output
result.scoreOutput = scoreOutput
console.log(result)
if (options.debug && topCrop) {
result.crops = crops;
result.debugOutput = output;
result.debugOptions = options;
// Create a copy which will not be adjusted by the post scaling of smartcrop.crop
result.debugTopCrop = extend({}, result.topCrop);
}
return result;
}
function ImgData(width, height, data) {
this.width = width;
this.height = height;
if (data) {
this.data = new Uint8ClampedArray(data);
} else {
this.data = new Uint8ClampedArray(width * height * 4);
}
}
smartcrop.ImgData = ImgData;
function downSample(input, factor) {
var idata = input.data;
var iwidth = input.width;
var width = Math.floor(input.width / factor);
var height = Math.floor(input.height / factor);
var output = new ImgData(width, height);
var data = output.data;
var ifactor2 = 1 / (factor * factor);
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var i = (y * width + x) * 4;
var r = 0;
var g = 0;
var b = 0;
var a = 0;
var mr = 0;
var mg = 0;
for (var v = 0; v < factor; v++) {
for (var u = 0; u < factor; u++) {
var j = ((y * factor + v) * iwidth + (x * factor + u)) * 4;
r += idata[j];
g += idata[j + 1];
b += idata[j + 2];
a += idata[j + 3];
mr = Math.max(mr, idata[j]);
mg = Math.max(mg, idata[j + 1]);
// unused
// mb = Math.max(mb, idata[j + 2]);
}
}
// this is some funky magic to preserve detail a bit more for
// skin (r) and detail (g). Saturation (b) does not get this boost.
data[i] = r * ifactor2 * 0.5 + mr * 0.5;
data[i + 1] = g * ifactor2 * 0.7 + mg * 0.3;
data[i + 2] = b * ifactor2;
data[i + 3] = a * ifactor2;
}
}
return output;
}
smartcrop._downSample = downSample;
function defaultCanvasFactory(w, h) {
var c = document.createElement('canvas');
c.width = w;
c.height = h;
return c;
}
function canvasImageOperations(canvasFactory) {
return {
// Takes imageInput as argument
// returns an object which has at least
// {width: n, height: n}
open: function(image) {
// Work around images scaled in css by drawing them onto a canvas
var w = image.naturalWidth || image.width;
var h = image.naturalHeight || image.height;
var c = canvasFactory(w, h);
var ctx = c.getContext('2d');
if (
image.naturalWidth &&
(image.naturalWidth != image.width ||
image.naturalHeight != image.height)
) {
c.width = image.naturalWidth;
c.height = image.naturalHeight;
} else {
c.width = image.width;
c.height = image.height;
}
ctx.drawImage(image, 0, 0);
return smartcrop.Promise.resolve(c);
},
// Takes an image (as returned by open), and changes it's size by resampling
resample: function(image, width, height) {
return Promise.resolve(image).then(function(image) {
var c = canvasFactory(~~width, ~~height);
var ctx = c.getContext('2d');
ctx.drawImage(
image,
0,
0,
image.width,
image.height,
0,
0,
c.width,
c.height
);
return smartcrop.Promise.resolve(c);
});
},
getData: function(image) {
return Promise.resolve(image).then(function(c) {
var ctx = c.getContext('2d');
var id = ctx.getImageData(0, 0, c.width, c.height);
return new ImgData(c.width, c.height, id.data);
});
}
};
}
smartcrop._canvasImageOperations = canvasImageOperations;
// Aliases and helpers
var min = Math.min;
var max = Math.max;
var abs = Math.abs;
var sqrt = Math.sqrt;
function extend(o) {
for (var i = 1, iLen = arguments.length; i < iLen; i++) {
var arg = arguments[i];
if (arg) {
for (var name in arg) {
o[name] = arg[name];
}
}
}
return o;
}
// Gets value in the range of [0, 1] where 0 is the center of the pictures
// returns weight of rule of thirds [0, 1]
function thirds(x) {
x = (((x - 1 / 3 + 1.0) % 2.0) * 0.5 - 0.5) * 16;
return Math.max(1.0 - x * x, 0.0);
}
function cie(r, g, b) {
return 0.5126 * b + 0.7152 * g + 0.0722 * r;
}
function sample(id, p) {
return cie(id[p], id[p + 1], id[p + 2]);
}
function saturation(r, g, b) {
var maximum = max(r / 255, g / 255, b / 255);
var minimum = min(r / 255, g / 255, b / 255);
if (maximum === minimum) {
return 0;
}
var l = (maximum + minimum) / 2;
var d = maximum - minimum;
return l > 0.5 ? d / (2 - maximum - minimum) : d / (maximum + minimum);
}
// Amd
if (typeof define !== 'undefined' && define.amd)
define(function() {
return smartcrop;
});
// Common js
if (typeof exports !== 'undefined') exports.smartcrop = smartcrop;
else if (typeof navigator !== 'undefined')
// Browser
window.SmartCrop = window.smartcrop = smartcrop;
// Nodejs
if (typeof module !== 'undefined') {
module.exports = smartcrop;
}
})();
var Hull = Require('plugins/math/hull.js')
function autocrop(image,options) {
var t0=Date.now()
var _image = image
options=options||{}
options.background = ~~options.background
options.foreground = ~~options.foreground
options.threshold = ~~options.threshold
options.t1 = ~~options.t1
options.t2 = ~~options.t2
options.blur = ~~options.blur
options.scale = ~~options.scale
options.maxPoints = options.maxPoints || 1000
options.padding = options.padding || 0
if (options.fast===undefined) options.fast=true
function ImgData(width, height, data, constructor) {
constructor=constructor||Uint8ClampedArray
this.width = width;
this.height = height;
this.depth = 1;
if (data) {
this.data = new constructor(data);
} else {
this.data = new constructor(width * height);
}
}
// Code.print(image.data.constructor.name)
if (options.color) {
} else if (options.blur || options.background || options.foreground ||image.depth!=1 ||
/16|32|64/.test(image.data.construtor.name)) {
if (image.depth==1 && !/16|32|64/.test(image.data.constructor.name))
image=new ImgData(image.width,image.height,image.data);
else {
var w=image.width,
h=image.height,
d=image.depth,
scales=[1,256,256*256,1],
s=options.scale||scales[["8","16","32","64"].indexOf(image.data.constructor.name.replace(/[a-zA-Z]/g,''))]||1
image=new ImgData(image.width,image.height);
console.log('autotcrop, scaling image',w,h,d,s)
switch (d){
case 1: for(var i=0;i<(w*h);i++) image.data[i]=_image.data[i]/s; break;
case 3: for(var i=0;i<(w*h);i++) image.data[i]=(_image.data[i*3]+_image.data[i*3+2]+_image.data[i*3+2])/(3*s); break;
case 4: for(var i=0;i<(w*h);i++) image.data[i]=(_image.data[i*4]+_image.data[i*4+2]+_image.data[i*4+2])/(3*s); break;
}
}
}
function makeGaussKernel(sigma){
const GAUSSKERN = 6.0;
var dim = parseInt(Math.max(3.0, GAUSSKERN * sigma));
var sqrtSigmaPi2 = Math.sqrt(Math.PI*2.0)*sigma;
var s2 = 2.0 * sigma * sigma;
var sum = 0.0;
var kernel = new Float32Array(dim - !(dim & 1)); // Make it odd number
const half = parseInt(kernel.length / 2);
for (var j = 0, i = -half; j < kernel.length; i++, j++)
{
kernel[j] = Math.exp(-(i*i)/(s2)) / sqrtSigmaPi2;
sum += kernel[j];
}
// Normalize the gaussian kernel to prevent image darkening/brightening
for (var i = 0; i < dim; i++) {
kernel[i] /= sum;
}
return kernel;
}
function blur(i) {
var sigma = options.blur
// https://fiveko.com/gaussian-filter-in-pure-javascript/
var id = i.data;
var w = i.width;
var h = i.height;
var kernel = makeGaussKernel(sigma);
var mk = Math.floor(kernel.length / 2);
var kl = kernel.length
var buff = new Uint8Array(w*h);
// First step process columns
for (var j = 0, hw = 0; j < h; j++, hw += w)
{
for (var i = 0; i < w; i++)
{
var sum = 0;
for (var k = 0; k < kl; k++)
{
var col = i + (k - mk);
col = (col < 0) ? 0 : ((col >= w) ? w - 1 : col);
sum += id[hw + col]*kernel[k];
}
buff[hw + i] = sum;
}
}
// Second step process rows
for (var j = 0, offset = 0; j < h; j++, offset += w)
{
for (var i = 0; i < w; i++)
{
var sum = 0;
for (k = 0; k < kl; k++)
{
var row = j + (k - mk);
row = (row < 0) ? 0 : ((row >= h) ? h - 1 : row);
sum += buff[(row*w + i)]*kernel[k];
}
var off = j*w + i;
id[off] = sum
}
}
}
var L = 255, H = 0, X1=image.width-1,Y1=image.height-1,X2=0,Y2=0
function edgeDetect(i, o) {
var id = i.data;
var od = o.data;
var w = i.width;
var h = i.height;
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
var p = y * w + x;
var lightness;
if (x === 0 || x >= w - 1 || y === 0 || y >= h - 1) {
lightness = 0; // sample(id, p);
} else {
lightness =
id[p] * 4 -
id[p - w] -
id[ p - 1] -
id[ p + 1] -
id[ p + w];
}
lightness=Math.abs(lightness);
od[p] = lightness
L=Math.min(L,lightness); H=Math.max(H,lightness)
}
}
}
function threshold(o) {
var od = o.data;
var w = o.width;
var h = o.height;
if (options.threshold > 0) {
var t = options.threshold
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
var p = y * w + x;
if (od[p]>t) {
od[p]=255;
X1=Math.min(X1,x)
X2=Math.max(X2,x)
Y1=Math.min(Y1,y)
Y2=Math.max(Y2,y)
}
else od[p]=0;
}
}
} else {
var t = options.threshold
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
var p = y * w + x;
if (od[p]=options.t1 && od[p]<=options.t2) {
od[p]=255;
X1=Math.min(X1,x)
X2=Math.max(X2,x)
Y1=Math.min(Y1,y)
Y2=Math.max(Y2,y)
}
else od[p]=0;
}
}
}
function threshold0(o) {
var od = o.data;
var w = o.width;
var h = o.height;
if (options.background>0) {
var t = options.background
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
var p = y * w + x;
if (od[p]<=t) od[p]=0;
}
}
} else {
t = Math.abs(options.background)
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
var p = y * w + x;
if (od[p]>=t) od[p]=0;
}
}
}
}
function threshold1(o) {
var od = o.data;
var w = o.width;
var h = o.height;
if (options.foreground>0) {
var t = options.foreground
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
var p = y * w + x;
if (od[p]>=t) od[p]=255;
else od[p]=0;
}
}
} else {
var t = Math.abs(options.foreground)
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
var p = y * w + x;
if (od[p]<=t) od[p]=255;
else od[p]=0;
}
}
}
}
function com(o) {
var od = o.data;
var w = o.width;
var h = o.height;
var xc = 0,yc=0,nc=0
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
var p = y * w + x;
if (od[p]) {xc+=x;yc+=y;nc++}
}
}
return [(xc/nc)|0,(yc/nc)|0,nc]
}
function bbox(pts) {
var x1,y1,x2,y2
x1=x2= pts[0][0]
y1=y2= pts[0][1]
for(var i=1;ioptions.maxPoints||pc[2]==0) return pc[2];
var pts = []
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
var p = y * w + x;
if (od[p]) {pts.push([x,y])}
}
}
return bbox(Hull(pts))
}
function count (x1,y1,x2,y2) {
var n=0
for (var y = y1; y <= y2; y++) {
for (var x = x1; x <= x2; x++) {
var p = y * w + x;
if (od[p]) n++;
}
}
return n
}
if (options.background) threshold0(image);
if (options.foreground) threshold1(image);
if (options.blur) blur(image);
var output = new ImgData(image.width,image.height)
edgeDetect(image, output)
if (options.threshold) threshold(output)
else if (options.t1 || options.t2) threshold12(output)
else {
options.threshold=1;
threshold(output)
}
var pc=com(output),
cc=options.fast?{
x:X1,
y:Y1,
w:(X2-X1+1),
h:(Y2-Y1+1)
}:fitHull(output,pc)
if (cc.w<0 || cc.h<0) cc=0;
if (cc && options.padding) {
if (typeof options.padding == 'number') {
cc.x-=options.padding;
cc.y-=options.padding;
cc.w+=(options.padding*2);
cc.h+=(options.padding*2);
} else {
// [t,r,b,l]
cc.x-=options.padding[3];
cc.y-=options.padding[0];
cc.w+=(options.padding[3]+options.padding[1]);
cc.h+=(options.padding[0]+options.padding[2]);
}
}
var result = {
xc : pc[0],
yc : pc[1],
nc : pc[2],
crop : cc,
time : Date.now()-t0,
input : image,
output : output,
cropped : 0
}
if (typeof cc == 'object') {
result.cropped={
width : cc.w,
height : cc.h,
depth : _image.depth,
format : _image.format,
data : new _image.data.constructor(cc.w*cc.h*_image.depth)
}
var id=_image.data,
od=result.cropped.data,
d=_image.depth,
iw=_image.width,
ih=_image.height,
ow=cc.w,
oh=cc.h
for(var y=cc.y;y<(cc.y+cc.h);y++) {
for(var x=cc.x;x<(cc.x+cc.w);x++) {
var ip = ((y*iw)+x)*d,
op = (((y-cc.y)*ow)+(x-cc.x))*d
for(var i=0;i= 2 && (_cross(lower[lower.length - 2], lower[lower.length - 1], pointset[l]) <= 0)) {
lower.pop();
}
lower.push(pointset[l]);
}
lower.pop();
return lower;
}
function _lowerTangent(pointset) {
const reversed = pointset.reverse(),
upper = [];
for (let u = 0; u < reversed.length; u++) {
while (upper.length >= 2 && (_cross(upper[upper.length - 2], upper[upper.length - 1], reversed[u]) <= 0)) {
upper.pop();
}
upper.push(reversed[u]);
}
upper.pop();
return upper;
}
// pointset has to be sorted by X
function convex(pointset) {
const upper = _upperTangent(pointset),
lower = _lowerTangent(pointset);
const convex = lower.concat(upper);
convex.push(pointset[0]);
return convex;
}
module.exports = convex;
},{}],2:[function(require,module,exports){
module.exports = {
toXy: function(pointset, format) {
if (format === undefined) {
return pointset.slice();
}
return pointset.map(function(pt) {
/*jslint evil: true */
const _getXY = new Function('pt', 'return [pt' + format[0] + ',' + 'pt' + format[1] + '];');
return _getXY(pt);
});
},
fromXy: function(pointset, format) {
if (format === undefined) {
return pointset.slice();
}
return pointset.map(function(pt) {
/*jslint evil: true */
const _getObj = new Function('pt', 'const o = {}; o' + format[0] + '= pt[0]; o' + format[1] + '= pt[1]; return o;');
return _getObj(pt);
});
}
}
},{}],3:[function(require,module,exports){
function Grid(points, cellSize) {
this._cells = [];
this._cellSize = cellSize;
this._reverseCellSize = 1 / cellSize;
for (let i = 0; i < points.length; i++) {
const point = points[i];
const x = this.coordToCellNum(point[0]);
const y = this.coordToCellNum(point[1]);
if (!this._cells[x]) {
const array = [];
array[y] = [point];
this._cells[x] = array;
} else if (!this._cells[x][y]) {
this._cells[x][y] = [point];
} else {
this._cells[x][y].push(point);
}
}
}
Grid.prototype = {
cellPoints: function(x, y) { // (Number, Number) -> Array
return (this._cells[x] !== undefined && this._cells[x][y] !== undefined) ? this._cells[x][y] : [];
},
rangePoints: function(bbox) { // (Array) -> Array
const tlCellX = this.coordToCellNum(bbox[0]);
const tlCellY = this.coordToCellNum(bbox[1]);
const brCellX = this.coordToCellNum(bbox[2]);
const brCellY = this.coordToCellNum(bbox[3]);
const points = [];
for (let x = tlCellX; x <= brCellX; x++) {
for (let y = tlCellY; y <= brCellY; y++) {
Array.prototype.push.apply(points, this.cellPoints(x, y));
}
}
return points;
},
removePoint: function(point) { // (Array) -> Array
const cellX = this.coordToCellNum(point[0]);
const cellY = this.coordToCellNum(point[1]);
const cell = this._cells[cellX][cellY];
let pointIdxInCell;
for (let i = 0; i < cell.length; i++) {
if (cell[i][0] === point[0] && cell[i][1] === point[1]) {
pointIdxInCell = i;
break;
}
}
cell.splice(pointIdxInCell, 1);
return cell;
},
trunc: Math.trunc || function(val) { // (number) -> number
return val - val % 1;
},
coordToCellNum: function(x) { // (number) -> number
return this.trunc(x * this._reverseCellSize);
},
extendBbox: function(bbox, scaleFactor) { // (Array, Number) -> Array
return [
bbox[0] - (scaleFactor * this._cellSize),
bbox[1] - (scaleFactor * this._cellSize),
bbox[2] + (scaleFactor * this._cellSize),
bbox[3] + (scaleFactor * this._cellSize)
];
}
};
function grid(points, cellSize) {
return new Grid(points, cellSize);
}
module.exports = grid;
},{}],4:[function(require,module,exports){
/*
(c) 2014-2019, Andrii Heonia
Hull.js, a JavaScript library for concave hull generation by set of points.
https://github.com/AndriiHeonia/hull
*/
'use strict';
const intersect = require('./intersect.js');
const grid = require('./grid.js');
const formatUtil = require('./format.js');
const convexHull = require('./convex.js');
function _filterDuplicates(pointset) {
const unique = [pointset[0]];
let lastPoint = pointset[0];
for (let i = 1; i < pointset.length; i++) {
const currentPoint = pointset[i];
if (lastPoint[0] !== currentPoint[0] || lastPoint[1] !== currentPoint[1]) {
unique.push(currentPoint);
}
lastPoint = currentPoint;
}
return unique;
}
function _sortByX(pointset) {
return pointset.sort(function(a, b) {
return (a[0] - b[0]) || (a[1] - b[1]);
});
}
function _sqLength(a, b) {
return Math.pow(b[0] - a[0], 2) + Math.pow(b[1] - a[1], 2);
}
function _cos(o, a, b) {
const aShifted = [a[0] - o[0], a[1] - o[1]],
bShifted = [b[0] - o[0], b[1] - o[1]],
sqALen = _sqLength(o, a),
sqBLen = _sqLength(o, b),
dot = aShifted[0] * bShifted[0] + aShifted[1] * bShifted[1];
return dot / Math.sqrt(sqALen * sqBLen);
}
function _intersect(segment, pointset) {
for (let i = 0; i < pointset.length - 1; i++) {
const seg = [pointset[i], pointset[i + 1]];
if (segment[0][0] === seg[0][0] && segment[0][1] === seg[0][1] ||
segment[0][0] === seg[1][0] && segment[0][1] === seg[1][1]) {
continue;
}
if (intersect(segment, seg)) {
return true;
}
}
return false;
}
function _occupiedArea(pointset) {
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (let i = pointset.length - 1; i >= 0; i--) {
if (pointset[i][0] < minX) {
minX = pointset[i][0];
}
if (pointset[i][1] < minY) {
minY = pointset[i][1];
}
if (pointset[i][0] > maxX) {
maxX = pointset[i][0];
}
if (pointset[i][1] > maxY) {
maxY = pointset[i][1];
}
}
return [
maxX - minX, // width
maxY - minY // height
];
}
function _bBoxAround(edge) {
return [
Math.min(edge[0][0], edge[1][0]), // left
Math.min(edge[0][1], edge[1][1]), // top
Math.max(edge[0][0], edge[1][0]), // right
Math.max(edge[0][1], edge[1][1]) // bottom
];
}
function _midPoint(edge, innerPoints, convex) {
let point = null,
angle1Cos = MAX_CONCAVE_ANGLE_COS,
angle2Cos = MAX_CONCAVE_ANGLE_COS,
a1Cos, a2Cos;
for (let i = 0; i < innerPoints.length; i++) {
a1Cos = _cos(edge[0], edge[1], innerPoints[i]);
a2Cos = _cos(edge[1], edge[0], innerPoints[i]);
if (a1Cos > angle1Cos && a2Cos > angle2Cos &&
!_intersect([edge[0], innerPoints[i]], convex) &&
!_intersect([edge[1], innerPoints[i]], convex)) {
angle1Cos = a1Cos;
angle2Cos = a2Cos;
point = innerPoints[i];
}
}
return point;
}
function _concave(convex, maxSqEdgeLen, maxSearchArea, grid, edgeSkipList) {
let midPointInserted = false;
for (let i = 0; i < convex.length - 1; i++) {
const edge = [convex[i], convex[i + 1]];
// generate a key in the format X0,Y0,X1,Y1
const keyInSkipList = edge[0][0] + ',' + edge[0][1] + ',' + edge[1][0] + ',' + edge[1][1];
if (_sqLength(edge[0], edge[1]) < maxSqEdgeLen ||
edgeSkipList.has(keyInSkipList)) { continue; }
let scaleFactor = 0;
let bBoxAround = _bBoxAround(edge);
let bBoxWidth;
let bBoxHeight;
let midPoint;
do {
bBoxAround = grid.extendBbox(bBoxAround, scaleFactor);
bBoxWidth = bBoxAround[2] - bBoxAround[0];
bBoxHeight = bBoxAround[3] - bBoxAround[1];
midPoint = _midPoint(edge, grid.rangePoints(bBoxAround), convex);
scaleFactor++;
} while (midPoint === null && (maxSearchArea[0] > bBoxWidth || maxSearchArea[1] > bBoxHeight));
if (bBoxWidth >= maxSearchArea[0] && bBoxHeight >= maxSearchArea[1]) {
edgeSkipList.add(keyInSkipList);
}
if (midPoint !== null) {
convex.splice(i + 1, 0, midPoint);
grid.removePoint(midPoint);
midPointInserted = true;
}
}
if (midPointInserted) {
return _concave(convex, maxSqEdgeLen, maxSearchArea, grid, edgeSkipList);
}
return convex;
}
function hull(pointset, concavity, format) {
let maxEdgeLen = concavity || 20;
const points = _filterDuplicates(_sortByX(formatUtil.toXy(pointset, format)));
if (points.length < 4) {
return points.concat([points[0]]);
}
const occupiedArea = _occupiedArea(points);
const maxSearchArea = [
occupiedArea[0] * MAX_SEARCH_BBOX_SIZE_PERCENT,
occupiedArea[1] * MAX_SEARCH_BBOX_SIZE_PERCENT
];
const convex = convexHull(points);
const innerPoints = points.filter(function(pt) {
return convex.indexOf(pt) < 0;
});
const cellSize = Math.ceil(1 / (points.length / (occupiedArea[0] * occupiedArea[1])));
const concave = _concave(
convex, Math.pow(maxEdgeLen, 2),
maxSearchArea, grid(innerPoints, cellSize), new Set());
if (format) {
return formatUtil.fromXy(concave, format);
} else {
return concave;
}
}
const MAX_CONCAVE_ANGLE_COS = Math.cos(90 / (180 / Math.PI)); // angle = 90 deg
const MAX_SEARCH_BBOX_SIZE_PERCENT = 0.6;
module.exports = hull;
},{"./convex.js":1,"./format.js":2,"./grid.js":3,"./intersect.js":5}],5:[function(require,module,exports){
function ccw(x1, y1, x2, y2, x3, y3) {
const cw = ((y3 - y1) * (x2 - x1)) - ((y2 - y1) * (x3 - x1));
return cw > 0 ? true : cw < 0 ? false : true; // colinear
}
function intersect(seg1, seg2) {
const x1 = seg1[0][0], y1 = seg1[0][1],
x2 = seg1[1][0], y2 = seg1[1][1],
x3 = seg2[0][0], y3 = seg2[0][1],
x4 = seg2[1][0], y4 = seg2[1][1];
return ccw(x1, y1, x3, y3, x4, y4) !== ccw(x2, y2, x3, y3, x4, y4) && ccw(x1, y1, x2, y2, x3, y3) !== ccw(x1, y1, x2, y2, x4, y4);
}
module.exports = intersect;
},{}]},{},[4])(4)
});
};
Base64=Require('os/base64');
//Buffer=Require('os/buffer').Buffer;
window.IMAGE=IMAGE = Require('plugins/image/image.utils.js');
}; IMAGE$Init()
if (typeof module == 'object') module.exports = {IMAGE$Init:IMAGE$Init}
Draws = {}
Draw = {
arrow : function (from,to,headlen) {
from={x:from.x,y:from.y}; to={x:to.x,y:to.y};
var angle = Math.atan2(to.y - from.y, to.x - from.x);
headlen = headlen || 15; // arrow head size
// calculate the points.
var points = [
{
x: to.x - headlen * Math.cos(angle - Math.PI / 8),
y: to.y - headlen * Math.sin(angle - Math.PI / 8)
},
{
x: to.x, // start point
y: to.y
},
{
x: to.x - headlen * Math.cos(angle + Math.PI / 8),
y: to.y - headlen * Math.sin(angle + Math.PI / 8)
},
];
return points;
},
drawIndex : 0,
drawQueue : [],
callback : function (id,ev,node,label) {
console.log('Draw.callback',id,ev,node);
var drawing = Draws[id],svg;
if (!drawing) return;
if (drawing.options.callback) drawing.options.callback(ev,label,node);
},
// Create overlay snippet text+pic canvase
create : function picCreate(options,text) {
var i = Draw.drawIndex++,
id = 'draw'+i,
pic;
if (!options) options={};
options.width=options.width||800;
options.height=options.height||500;
options.fontSize=options.fontSize||Draw.defaults.fontSize;
options.label=options.label||id;
options.overlay=options.overlay||false;
// Construct cell DOM tree
var cell = $('', {
id: 'draw-cell'+i,
tabindex : "2",
style: (options.center?'margin:auto;':''),
class: 'cell code_cell unrendered unselected',
});
$(cell).click(function () {
$(cell).removeClass('unselected');
if (Common.snippetSelect) {
$(Common.snippetSelect).removeClass('selected')
$(Common.snippetSelect).addClass('unselected')
}
Common.snippetSelect=cell;
$(cell).addClass('selected');
});
var header = $('', {
id: 'draw-header'+i,
tabindex : "2",
style:"margin-left:12ex;",
class: 'snippet-label',
}).appendTo(cell);
$(''+options.label+'').appendTo(header);
$('')
.appendTo(header);
if (options.sketchpad)
$('')
.appendTo(header);
var input = $('', {
id: 'draw-input'+i,
class: 'input',
}).appendTo(cell);
var input_prompt = $('', {
id: 'draw-input_prompt'+i,
class: 'prompt input_prompt button',
title: 'double click to switch rendering',
}).appendTo(input);
if (!options.sketchpad) $(input_prompt).dblclick(function () {
Common.run(id);
})
var inner_cell = $('', {
id: 'draw-inner_cell'+i,
class: 'inner_cell',
}).appendTo(input);
var ctb_hideshow = $('', {
id: 'draw-ctb_hideshow'+i,
class: 'ctb_hideshow',
}).appendTo(inner_cell);
var input_area = $('', {
id: 'draw-input_area'+i,
class: 'input_area',
}).appendTo(inner_cell);
if (options.sketchpad) {
var sketch_area = $('', {
id: 'draw-sketchpad'+i,
style: 'width:'+options.width+'px; height:'+options.height+'px; left:0px; border:1px solid;',
}).appendTo(input_area);
var rendered_html = $('', {
id: 'draw-rendered_html'+i,
tabindex : "-1",
class: 'ext_cell_render rendered_html',
}).appendTo(inner_cell);
sketch_area.Scribble();
Draws[id]=sketch_area;
Draws[id].options=options;
sketch_area.flipped=false;
sketch_area.getValue = function () {
if (!sketch_area.flipped) {
var svg = sketch_area.Scribble('toText', 'svg');
return svg;
} else return sketch_area.svg;
}
sketch_area.run = function () {
if (!sketch_area.flipped) {
var svg = sketch_area.Scribble('toText', 'svg');
input_area.hide();
rendered_html.show();
rendered_html.empty();
rendered_html.html(svg);
// console.log(svg);
sketch_area.flipped=1;
sketch_area.svg=svg;
} else {
input_area.show();
rendered_html.hide();
sketch_area.flipped=0;
}
}
$(input_prompt).dblclick(function () {
sketch_area.run();
})
if (text) {
sketch_area.Scribble('fromText',text);
}
if (Common.snippetSelect) {
var index;
$(cell).insertAfter(Common.snippetSelect);
Common.snippets.forEach(function (entry,i) { if (entry.cell===Common.snippetSelect) index=i });
Common.snippets=Common.snippets.slice(0,index+1)
.concat({draw:sketch_area,id:id,i:i,cell:cell,options:options})
.concat(Common.snippets.slice(index+1));
} else {
$('#content').append(cell);
Common.snippets.push({draw:sketch_area,id:id,i:i,cell:cell,options:options});
}
setTimeout(function() {
if (options.run) {
sketch_area.run();
}
},1);
} else {
var textarea = $('', {
id: 'draw-text'+i,
class: '',
}).appendTo(input_area);
var rendered_html = $('', {
id: 'draw-rendered_html'+i,
tabindex : "-1",
class: 'ext_cell_render rendered_html',
}).appendTo(inner_cell);
var editor=CodeMirror.fromTextArea(textarea[0], {
lineWrapping : true,
lineNumbers : true,
mode : 'markdown',
index : id,
extraKeys: {
"Ctrl-Enter": function(instance) {
Common.run(id);
},
},
panel:'',
});
Editors[id]=editor;
editor.options={};
editor.options.collapsed=false;
editor.compiled=false;
editor.rendered_html=rendered_html;
editor.run=function () {
// console.log('run',editor);
if (options.overlay) {
if (options.overlay==true || options.overlay==2) options.overlay=1;
else if (options.overlay==1) options.overlay=2;
if (options.overlay==1) {
$(input_area).show();
$(rendered_html).hide();
refresh();
editor.compiled=false;
} else {
$(input_area).hide();
$(rendered_html).show();
}
}
if (!editor.compiled) {
var text = editor.getValue().toString();
var shapes = Draw.parser(text);
rendered_html.empty();
// $(input_area).hide();
shapes.forEach(function (shape) {
Draw.draw(id,shape);
});
if (options.overlay) editor.compiled=true;
}
}
if (text) editor.setValue(text);
function refresh() {
// hitting hard!
// force recalculation of line wrapping (avoid line breaking glitches)
editor.setOption('lineWrapping',false);
editor.setOption('lineWrapping',true);
editor.refresh();
}
setTimeout(function() {
editor.refresh();
if (options.run) {
editor.run();
}
},1);
if (Common.snippetSelect) {
var index;
$(cell).insertAfter(Common.snippetSelect);
Common.snippets.forEach(function (entry,i) { if (entry.cell===Common.snippetSelect) index=i });
Common.snippets=Common.snippets.slice(0,index+1)
.concat({draw:editor,id:id,i:i,cell:cell,options:options})
.concat(Common.snippets.slice(index+1));
} else {
$('#content').append(cell);
Common.snippets.push({draw:editor,id:id,i:i,cell:cell,options:options});
}
Draws[id]=editor;
editor.options=options;
editor.options.collapsed=false;
editor.index=i;
}
},
// Create HTML from pic; return canvas cell
compile : function (pic,options) {
options=options||{}
var i = Draw.drawIndex++,
id = 'draw'+i;
var cell = options.svg?{}:$('', {
id:id,
style:(options.center?'margin:auto;':''),
});
Draws[id]={
options:options,
rendered_html:cell
}
var shapes = Draw.parser(pic,options);
// $(input_area).hide();
shapes.forEach(function (shape) {
if (options.svg) Draw.svg(id,shape);
else Draw.draw(id,shape);
});
if (options.svg) cell=Draws[id].svg.head+
Draws[id].svg.body.join('')+
Draws[id].svg.tail;
if (!options.callback) delete Draws[id];
return cell;
},
defaults : {
linewidth : 1,
fontSize : 18,
},
destructor : function (id) {
delete Draws[id];
},
// draw a shape
draw : function (id,shape) { try {
var ctx,drawing = typeof id == 'object'?id:Draws[id];
if (!drawing) return Code.error('draw: unknown drawing '+id);
var cell = drawing.rendered_html;
console.log(shape);
switch (shape.shape) {
case 'Canvas':
var c = document.createElement('canvas'),
t = c.getContext('2d'), w = shape.width*shape.scale, h = shape.height*shape.scale;
c.width = c.style.width = w;
c.height = c.style.height = h;
if (!drawing.options.noborder && shape.border!=0)
c.style['border']=(shape.border?shape.border:1)+'px solid #888';
$(c).appendTo(cell);
drawing.canvas=c;
drawing.context=t;
break;
case 'Circle':
if (!drawing.context) return;
ctx=drawing.context;
ctx.beginPath();
ctx.lineWidth = (shape.strokeWidth||1)*shape.scale;
ctx.strokeStyle = shape.stroke||"black";
ctx.arc(shape.center.x*shape.scale, shape.center.y*shape.scale,
shape.radius*shape.scale, 0, 2 * Math.PI);
if (shape.fill!='transparent') {
ctx.fillStyle=shape.fill;
ctx.fillArc(shape.center.x*shape.scale, shape.center.y*shape.scale,
shape.radius*shape.scale, 0, 2 * Math.PI);
}
ctx.stroke();
if (shape.text) Draw.draw(id,Object.assign(shape.text,{shape:'Text',scale:shape.scale}));
break;
case 'Ellipse':
if (!drawing.context) return;
ctx=drawing.context;
ctx.beginPath();
ctx.lineWidth = (shape.strokeWidth||1)*shape.scale;
ctx.strokeStyle = shape.stroke||"black";
ctx.ellipse(shape.center.x*shape.scale, shape.center.y*shape.scale,
shape.rx*shape.scale, shape.ry*shape.scale, 0, 0, 2 * Math.PI);
if (shape.fill!='transparent') {
ctx.fillStyle=shape.fill;
ctx.fillEllipse(shape.center.x*shape.scale, shape.center.y*shape.scale,
shape.rx*shape.scale, shape.ry*shape.scale, 0, 0, 2 * Math.PI);
}
ctx.stroke();
if (shape.text) Draw.draw(id,Object.assign(shape.text,{shape:'Text',scale:shape.scale}));
break;
case 'Image':
if (!drawing.context) return;
ctx=drawing.context;
ctx.beginPath();
ctx.lineWidth = (shape.strokeWidth||1)*shape.scale;
ctx.strokeStyle = shape.stroke||"black";
ctx.rect(shape.left*shape.scale, shape.top*shape.scale,
shape.width*shape.scale, shape.height*shape.scale);
if (shape.fill!='transparent') {
ctx.fillStyle=shape.fill;
ctx.fillRect(shape.left*shape.scale, shape.top*shape.scale,
shape.width*shape.scale, shape.height*shape.scale);
}
ctx.stroke();
if (shape.img) {
var img = shape.img;
ctx.drawImage(img,0,0,img.width,img.height,
shape.left*shape.scale,shape.top*shape.scale,
shape.width*shape.scale, shape.height*shape.scale);
} else {
var img = new Image;
img.onload = function(){
ctx.drawImage(img,0,0,img.width,img.height,
shape.left*shape.scale,shape.top*shape.scale,
shape.width*shape.scale, shape.height*shape.scale);
};
if (shape.text) img.src = shape.text.text;
}
break;
case 'Line':
if (!drawing.context) return;
ctx=drawing.context;
ctx.beginPath();
ctx.lineWidth = (shape.strokeWidth||1)*shape.scale;
ctx.strokeStyle = shape.stroke||"black";
ctx.moveTo(shape.from.x*shape.scale,shape.from.y*shape.scale);
ctx.lineTo(shape.to.x*shape.scale,shape.to.y*shape.scale);
if (shape.arrow) {
if (/->/.test(shape.arrow)) {
var points = Draw.arrow(shape.from,shape.to,shape.size||shape.arrowsize);
points.forEach(function (p,index) {
if (index==0) ctx.moveTo(p.x*shape.scale,p.y*shape.scale);
else ctx.lineTo(p.x*shape.scale,p.y*shape.scale);
});
}
if (/<-/.test(shape.arrow)) {
var points = Draw.arrow(shape.to,shape.from,shape.size||shape.arrowsize);
points.forEach(function (p,index) {
if (index==0) ctx.moveTo(p.x*shape.scale,p.y*shape.scale);
else ctx.lineTo(p.x*shape.scale,p.y*shape.scale);
});
}
}
ctx.stroke();
if (shape.text) Draw.draw(id,Object.assign(shape.text,{shape:'Text',scale:shape.scale}));
break;
case 'Rect':
if (!drawing.context) return;
ctx=drawing.context;
ctx.beginPath();
ctx.lineWidth = (shape.strokeWidth||1)*shape.scale;
ctx.strokeStyle = shape.stroke||"black";
ctx.rect(shape.left*shape.scale, shape.top*shape.scale,
shape.width*shape.scale, shape.height*shape.scale);
if (shape.fill!='transparent') {
ctx.fillStyle=shape.fill;
ctx.fillRect(shape.left*shape.scale, shape.top*shape.scale,
shape.width*shape.scale, shape.height*shape.scale);
}
ctx.stroke();
if (shape.text) Draw.draw(id,Object.assign(shape.text,{shape:'Text',scale:shape.scale}));
break;
case 'Text':
if (!drawing.context) return;
var lines = shape.text.split('\n');
ctx=drawing.context;
ctx.fillStyle="black";
ctx.font = (shape.fontSize*shape.scale)+'px '+shape.fontFamily;
ctx.textAlign = shape.textAlign;
ctx.textBaseline = 'middle';
if (lines.length==1) {
var text = lines[0].replace(/->/g,'→');
ctx.fillText(text, shape.left*shape.scale, shape.top*shape.scale);
} else {
var lineHeight = (shape.lineHeight?shape.lineHeight:1.1)*shape.fontSize*shape.scale;
// Assuming centered text
var x = shape.left*shape.scale,
y = shape.top*shape.scale-Math.floor(lines.length/2)*lineHeight;
if ((lines.length%2)==0) y += (lineHeight/2);
for(var i=0;i/g,'→');
ctx.fillText(text,x,y);
y += lineHeight;
}
}
break;
}
} catch (e) { Code.error('Draw.draw failed ('+shape.shape+'): '+e) }
},
// Create HTML from pic; return canvas cell
drawShapes : function (shapes,options) {
options=options||{}
if (options.scale) shapes.forEach(function (s) { s.scale=options.scale });
var i = Draw.drawIndex++,
id = 'draw'+i;
var cell = options.svg?{}:$('', {
id:id,
style:(options.center?'margin:auto;':''),
});
Draws[id]={
options:options,
rendered_html:cell
}
// First shape MUST be a canvas shape!
shapes.forEach(function (shape) {
shape.scale=options.scale||1;
if (options.svg) Draw.svg(id,shape);
else Draw.draw(id,shape);
});
if (options.svg) cell=Draws[id].svg.head+
Draws[id].svg.body.join('')+
Draws[id].svg.tail;
if (!options.callback) delete Draws[id];
return cell;
},
editor : function (options) {
},
// autolayout of shape graph { nodes:shape [], links:shape [] }
graphLayout : async function (graph,options,callback) {
var shapes = [],
nodes = graph.nodes,
links = graph.links,
scale = 1,
_graph;
if (graph.options) options=graph.options;
if (options.scale) scale=options.scale;
if (typeof $klay != 'object') throw "Draw.graph: needs klay.js";
var _graph = {
"id": "root",
"properties": {
"direction": options.direction||"RIGHT",
"spacing": options.spacing||20,
},
"children": [],
//{"id": "n1", "width": 40, "height": 40}
"edges": []
// {"id": "e1", "source": "n1", "target": "n2"}]
};
var _ports=[],ports=[];
for(var i in nodes) {
var _node = {
id : nodes[i].id||nodes[i].label,
width : nodes[i].width,
height : nodes[i].height,
}
// console.log(nodes[i]);
// Important: Ports id format: NodeId.PortId !!!
if (nodes[i].ports && nodes[i].ports.length) {
_node.ports=nodes[i].ports;
if (_node.ports[0].portSide) {
_node.properties={portConstraints:"FIXED_SIDE"};
_graph.properties={portConstraints:"FIXED_SIDE"};
for(var k in _node.ports) _node.ports[k].properties={portSide:_node.ports[k].portSide};
}
ports=ports.concat(nodes[i].ports);
_ports=_ports.concat(nodes[i].ports.map(function (p,i) {
return p.id || (_node.id+'.'+i)
}))
}
_graph.children.push(_node)
}
for(var i in links) {
var _edge = {
id : links[i].id!=undefined?links[i].id:'e'+i,
source : links[i].from,
target : links[i].to
}
if (_edge.source==undefined) throw ('Data.graphLayout: Link '+_edge.id+' has no source (target '+_edge.target+')')
if (_edge.target==undefined) throw ('Data.graphLayout: Link '+_edge.id+' has no target (source '+_edge.source+')')
if (_ports.indexOf(_edge.source)!=-1) {
_edge.sourcePort = _edge.source;
_edge.source = _edge.source.replace(/\.[^$]+$/,'');
}
if (_ports.indexOf(_edge.target)!=-1) {
_edge.targetPort = _edge.target;
_edge.target = _edge.target.replace(/\.[^$]+$/,'');
}
_graph.edges.push(_edge)
}
var promise = new Promise(function (resolve,reject) {
$klay.layout({
graph: _graph,
options: { },
success: resolve,
error: resolve
})
});
function process(layout) {
if (layout.stacktrace) {
throw (layout.text+(layout.value?': '+layout.value.id:''));
}
var bbox = { x1:-1,y1:-1,x2:0,y2:0 },
canvas = { shape:'Canvas', width:0, height:0 };
shapes.push(canvas)
function expbb(bbox,p) {
bbox.x1=Math.min(bbox.x1,p.x);
bbox.y1=Math.min(bbox.y1,p.y);
bbox.x2=Math.max(bbox.x2,p.x);
bbox.y2=Math.max(bbox.y2,p.y);
}
for (var i in nodes) {
function drawShape(shape,auto) {
switch (shape.shape.toLowerCase()) {
case 'circ':
shape.shape='Circ';
var width = shape.radius||shape.width,
height = shape.radius || shape.height,
left = auto.x,
top = auto.y;
shape.center = {x:left+Math.floor(width/2),y:top+Math.floor(height/2)}
if (bbox.x1==-1) { bbox.x1=left; bbox.y1=top}
else { bbox.x1=Math.min(bbox.x1,left);bbox.y1=Math.min(bbox.y1,top)}
bbox.x2=Math.max(left+shape.width,bbox.x2);
bbox.y2=Math.max(top+shape.height,bbox.y2);
if (width==height && ! shape.radius) shape.radius = width/2;
else if (width!=height) { shape.shape='Ellipse'; shape.rx=width; shape.ry=height }
shapes.push(shape);
break;
case 'rect':
shape.shape='Rect';
shape.left = auto.x;
shape.top = auto.y;
if (bbox.x1==-1) { bbox.x1=shape.left; bbox.y1=shape.top}
else { bbox.x1=Math.min(bbox.x1,shape.left);bbox.y1=Math.min(bbox.y1,shape.top)}
bbox.x2=Math.max(shape.left+shape.width,bbox.x2);
bbox.y2=Math.max(shape.top+shape.height,bbox.y2);
shapes.push(shape);
break;
}
if (shape.label||shape.text) shapes.push({
shape : 'Text',
text : (shape.text && shape.text.text)||shape.label,
left : shape.left+Math.floor((shape.width||shape.radius||shape.rx)/2),
top : shape.top+Math.floor((shape.height||shape.radius||shape.ry)/2),
textAlign : 'center',
fontSize : (shape.text && shape.text.size) || shape.fontSize || options.fontSize || 14,
stroke : shape.text && (shape.text.color || shape.text.stroke || shape.text.fill),
});
if (!shape.label) shape.label=shape.id;
delete shape.text;
if (shape.ports) {
for(var i in shape.ports) {
auto.ports[i].x+=auto.x;
auto.ports[i].y+=auto.y;
drawShape(shape.ports[i],auto.ports[i])
}
}
}
var shape = nodes[i],
auto = layout.children[i];
drawShape(shape,auto);
}
for (var i in links) {
var shape=links[i],
auto = _graph.edges[i];
shapes.push({
shape :'Line',
arrow : !auto.bendPoints?shape.arrow:undefined,
arrowsize: shape.arrowsize||options.arrowsize,
strokeWidth:shape.thickness,
stroke:shape.stroke,
from : auto.sourcePoint,
to : auto.bendPoints?auto.bendPoints[0]:auto.targetPoint
})
expbb(bbox,auto.sourcePoint);
expbb(bbox,auto.targetPoint);
if (auto.bendPoints) {
for(var k in auto.bendPoints) expbb(bbox,auto.bendPoints[k]);
for(var k=0;k=]+|"(?:\\"|[^"])+"/g).filter(function (token) { return token });
// console.log(tokens)
function unit (str) {
if (!isNaN(Number(str))) return Number(str);
else return str;
}
function isNumber(str) {
return !isNaN(Number(str))
}
if (shape.label) Labels[shape.label]=shape;
tokens.forEach(function (token,index) {
var lookahead=tokens[index+1],x,y;
if (state.skip) return state.skip--;
function pop() {
state.skip++;
lookahead=tokens[index+state.skip+1];
return tokens[index+state.skip];;
}
if (token[0]=='"') { shape.text=(shape.text||[]); return shape.text.push(unwrap('"',token,'"'))};
if (lookahead=='=') {
pop();
if (!options[token]) defaultStyles[token]=unit(pop());
return;
}
switch (token) {
case 'canvas': shape.shape = 'Canvas'; break;
case 'box': shape.shape = 'Rect'; break;
case 'circle': shape.shape = 'Circle'; break;
case 'ellipse': shape.shape = 'Circle'; break;
case 'line': shape.shape = 'Line'; break;
case 'arrow': shape.shape = 'Line'; break;
case 'image': shape.shape = 'Image'; break;
case 'text': shape.shape = 'Text'; break;
case 'clear': shape.control = 'clear'; break;
case 'wid':
case 'width': shape.width=unit(pop()); break;
case 'ht':
case 'height': shape.height=unit(pop(token)); break;
case 'rad':
case 'radius': shape.radius=unit(pop(token)); break;
case 'th':
case 'thickness': shape.thickness=unit(pop(token)); break;
case 'sz':
case 'size' : shape.size=unit(pop(token)); break;
case 'arrowsz': shape.arrowsize=unit(pop(token)); break;
case 'color': shape.stroke=unit(pop(token)); break;
case '<->' :
case '->' :
case '<-' :
shape.arrow=token;
shape.arrowsize=defaultStyles.arrowsize;
break;
case 'at':
x=pop();
if (lookahead && isNumber(lookahead)) {
y=pop()
shape.center={x:unit(x),y:unit(y)};
}
break;
case 'from':
x=pop();
if (!isNumber(x)) {
shape.from=x;
} else if (lookahead && isNumber(lookahead)) {
y=pop()
shape.from={x:unit(x),y:unit(y)};
}
break;
case 'to':
x=pop();
if (!isNumber(x)) {
shape.to=x;
} else if (lookahead && isNumber(lookahead)) {
y=pop()
shape.to={x:unit(x),y:unit(y)};
}
break;
case 'fill':
if (lookahead && isNumber(lookahead)) {
var d = pop();
if (lookahead && isNumber(lookahead)) {
d = d+'.'+pop();
}
shape.fill=unit(d);
if (keywords.indexOf(lookahead)==-1)
shape.fillColor=pop();
} else if (!lookahead || keywords.indexOf(lookahead)!=-1) {
shape.fill=defaultStyles.fill;
}
break;
}
});
if (defaultStyles.scale) shape.scale=Number(defaultStyles.scale);
if (defaultStyles.border!=undefined) shape.border=Number(defaultStyles.border);
// console.log(shape)
if (shape.center || shape.from || shape.to) {
switch (shape.shape) {
case 'Circle':
if (!shape.radius) {
shape.width=shape.width||defaultStyles.circlerad*2;
shape.height=shape.height||defaultStyles.circlerad*2;
if (shape.width==shape.height) shape.radius=shape.width/2;
else {
// Ellipse class
shape.rx=shape.width/2;
shape.ry=shape.height/2;
shape.shape='Ellipse';
}
} else {
shape.width=shape.width||shape.radius*2;
shape.height=shape.height||shape.radius*2;
}
shape.left=shape.center.x-Math.floor(shape.width/2);
shape.top=shape.center.y-Math.floor(shape.height/2);
break;
case 'Line':
shape.points=[
{x:Number(shape.from.x),y:Number(shape.from.y)},
{x:Number(shape.to.x),y:Number(shape.to.y)}
];
break;
case 'Rect':
case 'Image':
shape.width=shape.width||defaultStyles.boxwid;
shape.height=shape.height||defaultStyles.boxht;
shape.left=shape.center.x-Math.floor(shape.width/2);
shape.top=shape.center.y-Math.floor(shape.height/2);
break;
case 'Text':
if (!shape.fontSize) shape.fontSize = defaultStyles.fontsz;
if (!shape.fontFamily) shape.fontFamily = defaultStyles.font;
if (!shape.lineHeight) shape.lineHeight = defaultStyles.textlineht;
if (!shape.width) {
shape.width=100; // TODO
}
if (!shape.height) {
shape.height = shape.fontSize;
}
shape.left=shape.center.x; // !!centered text
shape.top=shape.center.y;
delete shape.center;
var lines = shape.text.length;
shape.textAlign = 'center';
shape.text=shape.text.join('\n');
break;
}
}
if (shape.thickness) {
shape.strokeWidth=shape.thickness;
delete shape.thickness;
} else shape.strokeWidth=defaultStyles.thickness;
if (shape.fill == undefined) {
switch (shape.shape) {
case 'Circle':
case 'Ellipse':
case 'Rect':
shape.fill='transparent';
break;
}
} else {
var color = shape.fillColor || defaultStyles.fillColor;
shape.fill='rgba('+Color(color).values.rgb.concat([shape.fill]).join(',')+')';
}
if (shape.text && shape.shape!='Text') {
var text = shape.text.join('\n');
shape.text = {
text : text,
fontSize : shape.fontSize || defaultStyles.fontsz,
fontFamily : shape.fontFamily || defaultStyles.font,
lineHeight : defaultStyles.textlineht,
}
// default: center / middle position TODO
shape.text.left = shape.left+shape.width/2;
var lines = text.split('\n').length;
shape.text.top = shape.top+shape.height/2;
shape.text.textAlign = 'center';
shape.text.width=(shape.width||(shape.radius*2));
}
return shape;
});
function pointOn(shape,side) {
switch (side) {
case 'W':
if (shape.center && shape.width) return {x:shape.center.x-shape.width/2,
y:shape.center.y}
case 'E':
if (shape.center && shape.width) return {x:shape.center.x+shape.width/2,
y:shape.center.y}
case 'N':
if (shape.center && shape.height) return {x:shape.center.x,
y:shape.center.y-shape.height/2}
case 'S':
if (shape.center && shape.height) return {x:shape.center.x,
y:shape.center.y+shape.height/2}
case 'NW':
if (shape.shape=='Rect' && shape.center && shape.width)
return {x:shape.center.x-shape.width/2,
y:shape.center.y-shape.height/2}
if ((shape.shape=='Circle'||shape.shape=='Ellipse') && shape.center && shape.width)
return {x:shape.center.x-shape.width/3,
y:shape.center.y-shape.height/3}
case 'NE':
if (shape.shape=='Rect' && shape.center && shape.width)
return {x:shape.center.x+shape.width/2,
y:shape.center.y-shape.height/2}
if ((shape.shape=='Circle'||shape.shape=='Ellipse') && shape.center && shape.width)
return {x:shape.center.x+shape.width/3,
y:shape.center.y-shape.height/3}
case 'SW':
if (shape.shape=='Rect' && shape.center && shape.width)
return {x:shape.center.x-shape.width/2,
y:shape.center.y+shape.height/2}
if ((shape.shape=='Circle'||shape.shape=='Ellipse') && shape.center && shape.width)
return {x:shape.center.x-shape.width/3,
y:shape.center.y+shape.height/3}
case 'SE':
if (shape.shape=='Rect' && shape.center && shape.width)
return {x:shape.center.x+shape.width/2,
y:shape.center.y+shape.height/2}
if ((shape.shape=='Circle'||shape.shape=='Ellipse') && shape.center && shape.width)
return {x:shape.center.x+shape.width/3,
y:shape.center.y+shape.height/3}
}
}
// Resolution of node label references
shapes.forEach(function (shape) {
switch (shape.shape) {
case 'Line':
// resolve shape positions
if (typeof shape.from == 'string') {
// NODE.SIDE?
var parts = shape.from.split('.');
if (parts[1] && Labels[parts[0]]) {
shape.from=pointOn(Labels[parts[0]],parts[1]);
}
}
if (typeof shape.to == 'string') {
// NODE.SIDE?
var parts = shape.to.split('.');
if (parts[1] && Labels[parts[0]]) {
shape.to=pointOn(Labels[parts[0]],parts[1]);
}
}
break;
}
});
return shapes;
} catch (e) { Code.error('Draw.parser failed: '+e) }
},
// SVG: draw a shape
svg : function (id,shape) { try {
var drawing = typeof id == 'object'?id:Draws[id],svg,
options = drawing && drawing.options;
if (!drawing) return Code.error('Draw.svg: unknown drawing '+id);
// console.log(shape);
switch (shape.shape) {
case 'Canvas':
var style={
"max-width":"unset !important",
"max-height":"unset !important",
},w = (shape.width+5)*shape.scale, h = (shape.height+5)*shape.scale;
if (!drawing.options.noborder && shape.border!=0)
style['border']=(shape.border?shape.border:1)+'px solid #888';
var vb = [(shape.left||0)*shape.scale,(shape.top||0)*shape.scale,w,h];
drawing.svg = {
head: '',
body: [],
}
break;
case 'Circle':
if (!drawing.svg) return;
var lineWidth = (shape.strokeWidth||1)*shape.scale,
strokeStyle = shape.stroke||"black",
style={
"stroke-width":lineWidth,
stroke:strokeStyle,
}
style.fill=shape.fill;
svg = '';
drawing.svg.body.push(svg);
if (shape.text) Draw.svg(id,Object.assign(shape.text,{shape:'Text',scale:shape.scale}));
break;
case 'Ellipse':
if (!drawing.svg) return;
var lineWidth = (shape.strokeWidth||1)*shape.scale,
strokeStyle = shape.stroke||"black",
style={
"stroke-width":lineWidth,
stroke:strokeStyle,
}
style.fill=shape.fill;
svg = '';
drawing.svg.body.push(svg);
if (shape.text) Draw.svg(id,Object.assign(shape.text,{shape:'Text',scale:shape.scale}));
break;
case 'Image':
if (!drawing.svg) return;
var lineWidth = (shape.strokeWidth||1)*shape.scale,
strokeStyle = shape.stroke||"black",
style={
"stroke-width":lineWidth,
stroke:strokeStyle,
}
style.fill=shape.fill;
svg = '';
drawing.svg.body.push(svg);
svg='';
drawing.svg.body.push(svg);
break;
case 'Line':
if (!drawing.svg) return;
var lineWidth = (shape.strokeWidth||1)*shape.scale,
strokeStyle = shape.stroke||"black",
style={
"stroke-width":lineWidth,
stroke:strokeStyle,
}
var points=[
[shape.from.x*shape.scale,shape.from.y*shape.scale],
[shape.to.x*shape.scale,shape.to.y*shape.scale]
]
svg='';
if (shape.arrow) {
if (/->/.test(shape.arrow)) {
var points = Draw.arrow(shape.from,shape.to,shape.size||shape.arrowsize);
svg=svg+'';
}
if (/<-/.test(shape.arrow)) {
var points = Draw.arrow(shape.to,shape.from,shape.size||shape.arrowsize);
svg=svg+'';
}
}
drawing.svg.body.push(svg);
if (shape.text) Draw.svg(id,Object.assign(shape.text,{shape:'Text',scale:shape.scale}));
break;
case 'Rect':
if (!drawing.svg) return;
var lineWidth = (shape.strokeWidth||1)*shape.scale,
strokeStyle = shape.stroke||"black",
style={
"stroke-width":lineWidth,
stroke:strokeStyle,
}
style.fill=shape.fill;
svg = '';
drawing.svg.body.push(svg);
if (shape.text) Draw.svg(id,Object.assign(shape.text,{shape:'Text',scale:shape.scale}));
break;
case 'Text':
if (!drawing.svg) return;
var lines = shape.text.split('\n');
var fillStyle = shape.stroke||shape.fill||"black",
anchor=shape.textAlign=='center'?"middle":"start",
baseline="central",
baseline2="middle",
style={
fill:fillStyle,
"font-size":(shape.fontSize*shape.scale)+'px',
"font-family":shape.fontFamily,
}
if (lines.length==1) {
var text = lines[0].replace(/->/g,'→');
svg=''+text+'';
} else {
var lineHeight = (shape.lineHeight?shape.lineHeight:1.1)*shape.fontSize*shape.scale;
// Assuming centered text
var x = shape.left*shape.scale,
y = shape.top*shape.scale-Math.floor(lines.length/2)*lineHeight;
if ((lines.length%2)==0) y += (lineHeight/2);
svg='';
for(var i=0;i/g,'→');
svg+=''+text+'';
y += lineHeight;
}
}
drawing.svg.body.push(svg);
break;
}
} catch (e) { console.log(e), Code.error('Draw.svg failed ('+shape.shape+'): '+e) }
},
fromJSON : function (json) {
},
toJSON : function (pic) {
},
toCSS : function (styles) {
var str='';
for(var p in styles) str+=(p+':'+styles[p]+';');
return str
},
update : function (id,options) {
var draw = Draws[id];
if (!draw) return;
var index = draw.index;
if (options.width != draw.options.width ||
options.height != draw.options.height ||
options.fontSize != draw.options.fontSize ||
options.overlay != draw.options.overlay) {
if (draw.pic && (options.width != draw.options.width ||
options.height != draw.options.height ||
options.overlay != draw.options.overlay )) {
}
if (draw.options.sketchpad && (options.width != draw.options.width ||
options.height != draw.options.height ||
options.overlay != draw.options.overlay )) {
var svg = draw.getValue().
replace(/