Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/wechat mini program #70

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,20 @@
"@types/emscripten": "^1.39.6",
"@types/jest": "^27.0.3",
"@types/offscreencanvas": "^2019.6.4",
"@types/wechat-miniprogram": "^3.4.0",
"@typescript-eslint/eslint-plugin": "^5.9.1",
"@typescript-eslint/parser": "^5.9.1",
"esbuild": "^0.13.14",
"eslint": "^7.31.0",
"eslint-config-alloy": "^4.4.0",
"jest": "^26.6.3",
"jest-canvas-mock": "^2.3.1",
"magic-string": "^0.25.7",
"rimraf": "^3.0.2",
"rollup": "^2.38.5",
"rollup-plugin-esbuild": "^4.7.1",
"rollup-plugin-terser": "^7.0.2",
"rollup-plugin-jscc": "^2.0.0",
"ts-jest": "^26.5.0",
"tslib": "^2.1.0",
"typedoc": "^0.22.10",
Expand Down
255 changes: 255 additions & 0 deletions web/script/plugin/replace-config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,255 @@
/* eslint-disable */
export const replaceFunctionConfig = [
{
name: 'replace __emval_get_method_caller',
start: 'function __emval_get_method_caller(argCount, argTypes)',
end: 'function __emval_get_module_property(name)',
type: 'function',
replaceStr: (function __emval_get_method_caller(argCount, argTypes) {
var types = __emval_lookupTypes(argCount, argTypes);
var retType = types[0];
var signatureName = retType.name + "_$" + types.slice(1).map(function(t) {
return t.name;
}).join("_") + "$";
var returnId = emval_registeredMethods[signatureName];
if (returnId !== void 0) {
return returnId;
}
var params = ["retType"];
var args = [retType];
var argsList = "";
for (var i2 = 0; i2 < argCount - 1; ++i2) {
argsList += (i2 !== 0 ? ", " : "") + "arg" + i2;
params.push("argType" + i2);
args.push(types[1 + i2]);
}
var functionName = makeLegalFunctionName("methodCaller_" + signatureName);
var functionBody = "return function " + functionName + "(handle, name, destructors, args) {\n";
var offset = 0;
for (var i2 = 0; i2 < argCount - 1; ++i2) {
functionBody += " var arg" + i2 + " = argType" + i2 + ".readValueFromPointer(args" + (offset ? "+" + offset : "") + ");\n";
offset += types[i2 + 1]["argPackAdvance"];
}
functionBody += " var rv = handle[name](" + argsList + ");\n";
for (var i2 = 0; i2 < argCount - 1; ++i2) {
if (types[i2 + 1]["deleteObject"]) {
functionBody += " argType" + i2 + ".deleteObject(arg" + i2 + ");\n";
}
}
if (!retType.isVoid) {
functionBody += " return retType.toWireType(destructors, rv);\n";
}
functionBody += "};\n";
params.push(functionBody);
var anonymous = function (retType) {
var parentargs = Array.from(arguments);
parentargs.shift();
return this[makeLegalFunctionName("methodCaller_" + signatureName)] = function (handle, name, destructors, args) {
var paramList = [];
var offset = 0;
for (var i =0; i < parentargs.length; i ++){
paramList.push(parentargs[i].readValueFromPointer(args + offset));
offset += types[i + 1]["argPackAdvance"]
}
var rv = handle[name](...paramList);
if (!retType.isVoid) {
return retType.toWireType(destructors, rv);
}
}
}
var invokerFunction = anonymous.apply({}, args);
returnId = __emval_addMethodCaller(invokerFunction);
emval_registeredMethods[signatureName] = returnId;
return returnId;
}).toString()
},
{
name: 'replace craftEmvalAllocator',
start: 'function craftEmvalAllocator(argCount)',
end: 'var emval_newers = {};',
type: 'function',
replaceStr: (function craftEmvalAllocator(argCount) {
var argsList = "";
for (var i2 = 0; i2 < argCount; ++i2) {
argsList += (i2 !== 0 ? ", " : "") + "arg" + i2;
}
var functionBody = "return function emval_allocator_" + argCount + "(constructor, argTypes, args) {\n";
for (var i2 = 0; i2 < argCount; ++i2) {
functionBody += "var argType" + i2 + " = requireRegisteredType(Module['HEAP32'][(argTypes >>> 2) + " + i2 + '], "parameter ' + i2 + '");\nvar arg' + i2 + " = argType" + i2 + ".readValueFromPointer(args);\nargs += argType" + i2 + "['argPackAdvance'];\n";
}
functionBody += "var obj = new constructor(" + argsList + ");\nreturn valueToHandle(obj);\n}\n";
function anonymous(requireRegisteredType, Module, valueToHandle) {
return function(constructor, argTypes, args) {
var resultList = [];
for (var i2 = 0; i2 < argCount; ++i2) {
var currentArg = requireRegisteredType(Module['HEAP32'][(argTypes >>> 2) + i2], `parameter ${i2}`);
var res = currentArg.readValueFromPointer(args);
resultList.push(res);
args += currentArg['argPackAdvance']
}
var obj = new constructor(...resultList);
return valueToHandle(obj)
}
}
var invokerFunction = anonymous.apply({}, [requireRegisteredType, Module, Emval.toHandle]);
return invokerFunction
}).toString()
},
{
name: 'replace craftInvokerFunction',
start: 'function craftInvokerFunction(humanName, argTypes, classType, cppInvokerFunc, cppTargetFunc)',
end: 'function heap32VectorToArray(count, firstElement)',
type: 'funtcion',
replaceStr: (function craftInvokerFunction(humanName, argTypes, classType, cppInvokerFunc, cppTargetFunc) {
var createOption = {};
createOption.argCount = argTypes.length;
var argCount = argTypes.length;
if (argCount < 2) {
throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!");
}
createOption.isClassMethodFunc = argTypes[1] !== null && classType !== null;
var isClassMethodFunc = argTypes[1] !== null && classType !== null;
var needsDestructorStack = false;
for (var i2 = 1; i2 < argTypes.length; ++i2) {
if (argTypes[i2] !== null && argTypes[i2].destructorFunction === void 0) {
needsDestructorStack = true;
break;
}
}
createOption.needsDestructorStack = needsDestructorStack;
var returns = argTypes[0].name !== "void";
createOption.returns = argTypes[0].name !== "void";
createOption.childArgs = [];
createOption.childDtorFunc = [];
for (var i2 = 0; i2 < argCount - 2; ++i2) {
createOption.childArgs.push(i2);
}
var args1 = ["throwBindingError", "invoker", "fn", "runDestructors", "retType", "classParam"];
var args2 = [throwBindingError, cppInvokerFunc, cppTargetFunc, runDestructors, argTypes[0], argTypes[1]];
for (var i2 = 0; i2 < argCount - 2; ++i2) {
args1.push("argType" + i2);
args2.push(argTypes[i2 + 2]);
}
args2.push(Asyncify);
if (!needsDestructorStack) {
for (var i2 = isClassMethodFunc ? 1 : 2; i2 < argTypes.length; ++i2) {
var paramName = i2 === 1 ? "thisWired" : "arg" + (i2 - 2) + "Wired";
if (argTypes[i2].destructorFunction !== null) {
createOption.childDtorFunc.push({
paramName,
func: argTypes[i2].destructorFunction,
index: i2
});
}
}
}
function anonymous(throwBindingError, invoker, fn, runDestructors, retType, classParam) {
const anonymousArg = Array.from(arguments);

return this[makeLegalFunctionName(humanName)] = function () {
var parentargs = Array.from(arguments);
var argumentLen = createOption.childArgs.length;
if (parentargs.length !== argCount - 2) {
throwBindingError('function _PAGPlayer._getComposition called with ' + parentargs.length + ' arguments, expected 0 args!');
}
const argArr = anonymousArg.slice(6, 6 + argumentLen);
var destructors = [];
var dtorStack = needsDestructorStack ? destructors : null;
var thisWired;
var argWiredList = [];
var rv;
if (isClassMethodFunc) {
thisWired = classParam.toWireType(dtorStack, this)
}
for (var i = 0; i < createOption.childArgs.length; i ++) {
argWiredList.push(argArr[i].toWireType(dtorStack, parentargs[i]));
}
if(isClassMethodFunc) {
rv = invoker(fn, thisWired, ...argWiredList);
} else {
rv = invoker(fn, ...argWiredList);
}
function onDone(crv) {
if (needsDestructorStack) {
runDestructors(destructors)
} else {
const funcOption = createOption.childDtorFunc;
for (var i = 0; i < funcOption.length; i ++) {
const currentOption = funcOption[i];
if (currentOption.index === 1) {
currentOption.func(thisWired);
} else {
const ci = createOption.childArgs.indexOf(currentOption.index);
if (ci >= 0) {
currentOption.func(argWiredList[ci]);
}
}
}
}
if (returns) {
var ret = retType.fromWireType(crv);
return ret;
}
}
return Asyncify.currData ? Asyncify.whenDone().then(onDone) : onDone(rv);
}
}
var invokerFunction = anonymous.apply({}, args2);
return invokerFunction;
}).toString()
},
{
name: 'replace createNamedFunction',
start: 'function createNamedFunction(name, body)',
end: 'function extendError(baseErrorType, errorName)',
replaceStr: (function createNamedFunction(name, body) {
name = makeLegalFunctionName(name);
return function() {
return body.apply(this, arguments);
}
}).toString()
},
{
name: 'replace getBinaryPromise',
start: 'function getBinaryPromise()',
end: 'function createWasm()',
replaceStr: (function getBinaryPromise() {
return new Promise((resolve, reject) => {
if (globalThis.isWxWebAssembly) {
resolve(wasmBinaryFile)
} else {
const fs = wx.getFileSystemManager()
fs.readFile({
filePath: wasmBinaryFile,
position: 0,
success(res) {
resolve(res.data);
},
fail(res) {
reject(res);
}
});
}
});
}).toString()
},
{
name: 'replace WebAssembly Runtime error',
type: 'string',
start: 'var e = new WebAssembly.RuntimeError(what);',
replaceStr: 'var e = "run time error";'
},
{
name: 'replace performance',
type: 'string',
start: 'performance.now();',
replaceStr: 'wx.getPerformance().now();'
},
{
name: 'replace libpag.wasm name',
type: 'string',
start: 'libpag.wasm',
replaceStr: 'libpag.wasm.br'
},
];

30 changes: 30 additions & 0 deletions web/script/plugin/rollup-plugin-replace.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import MagicString from 'magic-string';
import { replaceFunctionConfig } from './replace-config';

export default function replaceFunc() {
return {
name: 'replaceFunc',
transform (code, id) {
let codeStr = `${code}`;
const magic = new MagicString(codeStr);
replaceFunctionConfig.forEach(item => {
if (item.type === 'string') {
const startOffset = codeStr.indexOf(item.start);
if (startOffset > -1) {
magic.overwrite(startOffset, startOffset + item.start.length, item.replaceStr)
}
} else {
const startOffset = codeStr.indexOf(item.start);
const endOffset = codeStr.indexOf(item.end);
if (startOffset > -1 && endOffset > startOffset && item.replaceStr) {
magic.overwrite(startOffset, endOffset, item.replaceStr)
}
}
})
return {
code: magic.toString(),
map: magic.generateMap({ hires: true })
}
}
}
}
12 changes: 11 additions & 1 deletion web/script/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import commonJs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import { terser } from 'rollup-plugin-terser';
import esbuild from 'rollup-plugin-esbuild';
import jscc from 'rollup-plugin-jscc';
import replaceFunc from './plugin/rollup-plugin-replace';

import pkg from '../package.json';

Expand Down Expand Up @@ -55,6 +57,7 @@ const umdMinConfig = {
plugins: [esbuild({ tsconfig: 'tsconfig.json', minify: false }), json(), resolve(), commonJs(), terser()],
};


export default [
umdConfig,
umdMinConfig,
Expand All @@ -64,6 +67,13 @@ export default [
{ banner, file: pkg.module, format: 'esm', sourcemap: true },
{ banner, file: pkg.main, format: 'cjs', exports: 'auto', sourcemap: true },
],
plugins: [esbuild({ tsconfig: 'tsconfig.json', minify: false }), resolve(), commonJs()],
plugins: [esbuild({ tsconfig: 'tsconfig.json', minify: false }), resolve(), commonJs() ],
},
{
input: 'src/pag.ts',
output: [
{ banner, file: 'lib/libpag.wx.js', format: 'cjs', exports: 'auto', sourcemap: true },
],
plugins: [jscc({ values: { _WECHAT: 1 } }), esbuild({ tsconfig: 'tsconfig.json', minify: false }), resolve(), commonJs(), replaceFunc()],
},
];
15 changes: 6 additions & 9 deletions web/src/binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,14 @@ import { PAGView } from './pag-view';
import { PAGFont } from './pag-font';
import { PAGLayer } from './pag-layer';
import { PAGComposition } from './pag-composition';
import { VideoReader } from './core/video-reader';
import { ScalerContext } from './core/scaler-context';
import { WebMask } from './core/web-mask';
import { NativeImage } from './core/native-image';
/* #if _WECHAT
import { VideoReader } from './core/wechat-video-reader';
//#else */
import { VideoReader } from './core/video-reader';
// #endif

/**
* Binding pag js module on pag webassembly module.
Expand Down Expand Up @@ -54,14 +58,7 @@ export const binding = (module: PAG) => {
return new PAGSurface(module, pagSurfaceWasm);
};
module._PAGSurface.FromFrameBuffer = async function (frameBufferID, width, height, flipY): Promise<PAGSurface> {
const pagSurfaceWasm = await module.webAssemblyQueue.exec(
this._FromFrameBuffer,
this,
frameBufferID,
width,
height,
flipY,
);
const pagSurfaceWasm = await module.webAssemblyQueue.exec(this._FromFrameBuffer, this, frameBufferID, width, height, flipY);
return new PAGSurface(module, pagSurfaceWasm);
};
module._PAGImage.FromBytes = async function (bytes, length): Promise<PAGImage> {
Expand Down
Loading