2747 lines
82 KiB
JavaScript
2747 lines
82 KiB
JavaScript
// The Module object: Our interface to the outside world. We import
|
|
// and export values on it. There are various ways Module can be used:
|
|
// 1. Not defined. We create it here
|
|
// 2. A function parameter, function(Module) { ..generated code.. }
|
|
// 3. pre-run appended it, var Module = {}; ..generated code..
|
|
// 4. External script tag defines var Module.
|
|
// We need to check if Module already exists (e.g. case 3 above).
|
|
// Substitution will be replaced with actual code on later stage of the build,
|
|
// this way Closure Compiler will not mangle it (e.g. case 4. above).
|
|
// Note that if you want to run closure, and also to use Module
|
|
// after the generated code, you will need to define var Module = {};
|
|
// before the code. Then that object will be used in the code, and you
|
|
|
|
|
|
// can continue to use Module afterwards as well.
|
|
var Module = typeof Module !== 'undefined' ? Module : {};
|
|
|
|
|
|
|
|
// --pre-jses are emitted after the Module integration code, so that they can
|
|
// refer to Module (if they choose; they can also define Module)
|
|
// {{PRE_JSES}}
|
|
|
|
// Sometimes an existing Module object exists with properties
|
|
// meant to overwrite the default module functionality. Here
|
|
// we collect those properties and reapply _after_ we configure
|
|
// the current environment's defaults to avoid having to be so
|
|
// defensive during initialization.
|
|
var moduleOverrides = {};
|
|
var key;
|
|
for (key in Module) {
|
|
if (Module.hasOwnProperty(key)) {
|
|
moduleOverrides[key] = Module[key];
|
|
}
|
|
}
|
|
|
|
var arguments_ = [];
|
|
var thisProgram = './this.program';
|
|
var quit_ = function(status, toThrow) {
|
|
throw toThrow;
|
|
};
|
|
|
|
// Determine the runtime environment we are in. You can customize this by
|
|
// setting the ENVIRONMENT setting at compile time (see settings.js).
|
|
|
|
var ENVIRONMENT_IS_WEB = false;
|
|
var ENVIRONMENT_IS_WORKER = false;
|
|
var ENVIRONMENT_IS_NODE = false;
|
|
var ENVIRONMENT_IS_SHELL = false;
|
|
ENVIRONMENT_IS_WEB = typeof window === 'object';
|
|
ENVIRONMENT_IS_WORKER = typeof importScripts === 'function';
|
|
// N.b. Electron.js environment is simultaneously a NODE-environment, but
|
|
// also a web environment.
|
|
ENVIRONMENT_IS_NODE = typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node === 'string';
|
|
ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
|
|
|
|
|
|
|
|
|
|
// `/` should be present at the end if `scriptDirectory` is not empty
|
|
var scriptDirectory = '';
|
|
function locateFile(path) {
|
|
if (Module['locateFile']) {
|
|
return Module['locateFile'](path, scriptDirectory);
|
|
}
|
|
return scriptDirectory + path;
|
|
}
|
|
|
|
// Hooks that are implemented differently in different runtime environments.
|
|
var read_,
|
|
readAsync,
|
|
readBinary,
|
|
setWindowTitle;
|
|
|
|
var nodeFS;
|
|
var nodePath;
|
|
|
|
if (ENVIRONMENT_IS_NODE) {
|
|
if (ENVIRONMENT_IS_WORKER) {
|
|
scriptDirectory = require('path').dirname(scriptDirectory) + '/';
|
|
} else {
|
|
scriptDirectory = __dirname + '/';
|
|
}
|
|
|
|
|
|
|
|
|
|
read_ = function shell_read(filename, binary) {
|
|
if (!nodeFS) nodeFS = require('fs');
|
|
if (!nodePath) nodePath = require('path');
|
|
filename = nodePath['normalize'](filename);
|
|
return nodeFS['readFileSync'](filename, binary ? null : 'utf8');
|
|
};
|
|
|
|
readBinary = function readBinary(filename) {
|
|
var ret = read_(filename, true);
|
|
if (!ret.buffer) {
|
|
ret = new Uint8Array(ret);
|
|
}
|
|
assert(ret.buffer);
|
|
return ret;
|
|
};
|
|
|
|
|
|
|
|
|
|
if (process['argv'].length > 1) {
|
|
thisProgram = process['argv'][1].replace(/\\/g, '/');
|
|
}
|
|
|
|
arguments_ = process['argv'].slice(2);
|
|
|
|
if (typeof module !== 'undefined') {
|
|
module['exports'] = Module;
|
|
}
|
|
|
|
process['on']('uncaughtException', function(ex) {
|
|
// suppress ExitStatus exceptions from showing an error
|
|
if (!(ex instanceof ExitStatus)) {
|
|
throw ex;
|
|
}
|
|
});
|
|
|
|
process['on']('unhandledRejection', abort);
|
|
|
|
quit_ = function(status) {
|
|
process['exit'](status);
|
|
};
|
|
|
|
Module['inspect'] = function () { return '[Emscripten Module object]'; };
|
|
|
|
|
|
|
|
} else
|
|
if (ENVIRONMENT_IS_SHELL) {
|
|
|
|
|
|
if (typeof read != 'undefined') {
|
|
read_ = function shell_read(f) {
|
|
return read(f);
|
|
};
|
|
}
|
|
|
|
readBinary = function readBinary(f) {
|
|
var data;
|
|
if (typeof readbuffer === 'function') {
|
|
return new Uint8Array(readbuffer(f));
|
|
}
|
|
data = read(f, 'binary');
|
|
assert(typeof data === 'object');
|
|
return data;
|
|
};
|
|
|
|
if (typeof scriptArgs != 'undefined') {
|
|
arguments_ = scriptArgs;
|
|
} else if (typeof arguments != 'undefined') {
|
|
arguments_ = arguments;
|
|
}
|
|
|
|
if (typeof quit === 'function') {
|
|
quit_ = function(status) {
|
|
quit(status);
|
|
};
|
|
}
|
|
|
|
if (typeof print !== 'undefined') {
|
|
// Prefer to use print/printErr where they exist, as they usually work better.
|
|
if (typeof console === 'undefined') console = /** @type{!Console} */({});
|
|
console.log = /** @type{!function(this:Console, ...*): undefined} */ (print);
|
|
console.warn = console.error = /** @type{!function(this:Console, ...*): undefined} */ (typeof printErr !== 'undefined' ? printErr : print);
|
|
}
|
|
|
|
|
|
} else
|
|
|
|
// Note that this includes Node.js workers when relevant (pthreads is enabled).
|
|
// Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and
|
|
// ENVIRONMENT_IS_NODE.
|
|
if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
|
|
if (ENVIRONMENT_IS_WORKER) { // Check worker, not web, since window could be polyfilled
|
|
scriptDirectory = self.location.href;
|
|
} else if (document.currentScript) { // web
|
|
scriptDirectory = document.currentScript.src;
|
|
}
|
|
// blob urls look like blob:http://site.com/etc/etc and we cannot infer anything from them.
|
|
// otherwise, slice off the final part of the url to find the script directory.
|
|
// if scriptDirectory does not contain a slash, lastIndexOf will return -1,
|
|
// and scriptDirectory will correctly be replaced with an empty string.
|
|
if (scriptDirectory.indexOf('blob:') !== 0) {
|
|
scriptDirectory = scriptDirectory.substr(0, scriptDirectory.lastIndexOf('/')+1);
|
|
} else {
|
|
scriptDirectory = '';
|
|
}
|
|
|
|
|
|
// Differentiate the Web Worker from the Node Worker case, as reading must
|
|
// be done differently.
|
|
{
|
|
|
|
|
|
|
|
|
|
read_ = function shell_read(url) {
|
|
var xhr = new XMLHttpRequest();
|
|
xhr.open('GET', url, false);
|
|
xhr.send(null);
|
|
return xhr.responseText;
|
|
};
|
|
|
|
if (ENVIRONMENT_IS_WORKER) {
|
|
readBinary = function readBinary(url) {
|
|
var xhr = new XMLHttpRequest();
|
|
xhr.open('GET', url, false);
|
|
xhr.responseType = 'arraybuffer';
|
|
xhr.send(null);
|
|
return new Uint8Array(/** @type{!ArrayBuffer} */(xhr.response));
|
|
};
|
|
}
|
|
|
|
readAsync = function readAsync(url, onload, onerror) {
|
|
var xhr = new XMLHttpRequest();
|
|
xhr.open('GET', url, true);
|
|
xhr.responseType = 'arraybuffer';
|
|
xhr.onload = function xhr_onload() {
|
|
if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0
|
|
onload(xhr.response);
|
|
return;
|
|
}
|
|
onerror();
|
|
};
|
|
xhr.onerror = onerror;
|
|
xhr.send(null);
|
|
};
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
//setWindowTitle = function(title) { document.title = title };
|
|
} else
|
|
{
|
|
}
|
|
|
|
|
|
// Set up the out() and err() hooks, which are how we can print to stdout or
|
|
// stderr, respectively.
|
|
var out = Module['print'] || console.log.bind(console);
|
|
var err = Module['printErr'] || console.warn.bind(console);
|
|
|
|
// Merge back in the overrides
|
|
for (key in moduleOverrides) {
|
|
if (moduleOverrides.hasOwnProperty(key)) {
|
|
Module[key] = moduleOverrides[key];
|
|
}
|
|
}
|
|
// Free the object hierarchy contained in the overrides, this lets the GC
|
|
// reclaim data used e.g. in memoryInitializerRequest, which is a large typed array.
|
|
moduleOverrides = null;
|
|
|
|
// Emit code to handle expected values on the Module object. This applies Module.x
|
|
// to the proper local x. This has two benefits: first, we only emit it if it is
|
|
// expected to arrive, and second, by using a local everywhere else that can be
|
|
// minified.
|
|
if (Module['arguments']) arguments_ = Module['arguments'];
|
|
if (Module['thisProgram']) thisProgram = Module['thisProgram'];
|
|
if (Module['quit']) quit_ = Module['quit'];
|
|
|
|
// perform assertions in shell.js after we set up out() and err(), as otherwise if an assertion fails it cannot print the message
|
|
|
|
|
|
|
|
|
|
|
|
// {{PREAMBLE_ADDITIONS}}
|
|
|
|
var STACK_ALIGN = 16;
|
|
|
|
function dynamicAlloc(size) {
|
|
var ret = HEAP32[DYNAMICTOP_PTR>>2];
|
|
var end = (ret + size + 15) & -16;
|
|
HEAP32[DYNAMICTOP_PTR>>2] = end;
|
|
return ret;
|
|
}
|
|
|
|
function alignMemory(size, factor) {
|
|
if (!factor) factor = STACK_ALIGN; // stack alignment (16-byte) by default
|
|
return Math.ceil(size / factor) * factor;
|
|
}
|
|
|
|
function getNativeTypeSize(type) {
|
|
switch (type) {
|
|
case 'i1': case 'i8': return 1;
|
|
case 'i16': return 2;
|
|
case 'i32': return 4;
|
|
case 'i64': return 8;
|
|
case 'float': return 4;
|
|
case 'double': return 8;
|
|
default: {
|
|
if (type[type.length-1] === '*') {
|
|
return 4; // A pointer
|
|
} else if (type[0] === 'i') {
|
|
var bits = Number(type.substr(1));
|
|
assert(bits % 8 === 0, 'getNativeTypeSize invalid bits ' + bits + ', type ' + type);
|
|
return bits / 8;
|
|
} else {
|
|
return 0;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
function warnOnce(text) {
|
|
if (!warnOnce.shown) warnOnce.shown = {};
|
|
if (!warnOnce.shown[text]) {
|
|
warnOnce.shown[text] = 1;
|
|
err(text);
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// Wraps a JS function as a wasm function with a given signature.
|
|
function convertJsFunctionToWasm(func, sig) {
|
|
|
|
// If the type reflection proposal is available, use the new
|
|
// "WebAssembly.Function" constructor.
|
|
// Otherwise, construct a minimal wasm module importing the JS function and
|
|
// re-exporting it.
|
|
if (typeof WebAssembly.Function === "function") {
|
|
var typeNames = {
|
|
'i': 'i32',
|
|
'j': 'i64',
|
|
'f': 'f32',
|
|
'd': 'f64'
|
|
};
|
|
var type = {
|
|
parameters: [],
|
|
results: sig[0] == 'v' ? [] : [typeNames[sig[0]]]
|
|
};
|
|
for (var i = 1; i < sig.length; ++i) {
|
|
type.parameters.push(typeNames[sig[i]]);
|
|
}
|
|
return new WebAssembly.Function(type, func);
|
|
}
|
|
|
|
// The module is static, with the exception of the type section, which is
|
|
// generated based on the signature passed in.
|
|
var typeSection = [
|
|
0x01, // id: section,
|
|
0x00, // length: 0 (placeholder)
|
|
0x01, // count: 1
|
|
0x60, // form: func
|
|
];
|
|
var sigRet = sig.slice(0, 1);
|
|
var sigParam = sig.slice(1);
|
|
var typeCodes = {
|
|
'i': 0x7f, // i32
|
|
'j': 0x7e, // i64
|
|
'f': 0x7d, // f32
|
|
'd': 0x7c, // f64
|
|
};
|
|
|
|
// Parameters, length + signatures
|
|
typeSection.push(sigParam.length);
|
|
for (var i = 0; i < sigParam.length; ++i) {
|
|
typeSection.push(typeCodes[sigParam[i]]);
|
|
}
|
|
|
|
// Return values, length + signatures
|
|
// With no multi-return in MVP, either 0 (void) or 1 (anything else)
|
|
if (sigRet == 'v') {
|
|
typeSection.push(0x00);
|
|
} else {
|
|
typeSection = typeSection.concat([0x01, typeCodes[sigRet]]);
|
|
}
|
|
|
|
// Write the overall length of the type section back into the section header
|
|
// (excepting the 2 bytes for the section id and length)
|
|
typeSection[1] = typeSection.length - 2;
|
|
|
|
// Rest of the module is static
|
|
var bytes = new Uint8Array([
|
|
0x00, 0x61, 0x73, 0x6d, // magic ("\0asm")
|
|
0x01, 0x00, 0x00, 0x00, // version: 1
|
|
].concat(typeSection, [
|
|
0x02, 0x07, // import section
|
|
// (import "e" "f" (func 0 (type 0)))
|
|
0x01, 0x01, 0x65, 0x01, 0x66, 0x00, 0x00,
|
|
0x07, 0x05, // export section
|
|
// (export "f" (func 0 (type 0)))
|
|
0x01, 0x01, 0x66, 0x00, 0x00,
|
|
]));
|
|
|
|
// We can compile this wasm module synchronously because it is very small.
|
|
// This accepts an import (at "e.f"), that it reroutes to an export (at "f")
|
|
var module = new WebAssembly.Module(bytes);
|
|
var instance = new WebAssembly.Instance(module, {
|
|
'e': {
|
|
'f': func
|
|
}
|
|
});
|
|
var wrappedFunc = instance.exports['f'];
|
|
return wrappedFunc;
|
|
}
|
|
|
|
var freeTableIndexes = [];
|
|
|
|
// Weak map of functions in the table to their indexes, created on first use.
|
|
var functionsInTableMap;
|
|
|
|
// Add a wasm function to the table.
|
|
function addFunctionWasm(func, sig) {
|
|
var table = wasmTable;
|
|
|
|
// Check if the function is already in the table, to ensure each function
|
|
// gets a unique index. First, create the map if this is the first use.
|
|
if (!functionsInTableMap) {
|
|
functionsInTableMap = new WeakMap();
|
|
for (var i = 0; i < table.length; i++) {
|
|
var item = table.get(i);
|
|
// Ignore null values.
|
|
if (item) {
|
|
functionsInTableMap.set(item, i);
|
|
}
|
|
}
|
|
}
|
|
if (functionsInTableMap.has(func)) {
|
|
return functionsInTableMap.get(func);
|
|
}
|
|
|
|
// It's not in the table, add it now.
|
|
|
|
|
|
var ret;
|
|
// Reuse a free index if there is one, otherwise grow.
|
|
if (freeTableIndexes.length) {
|
|
ret = freeTableIndexes.pop();
|
|
} else {
|
|
ret = table.length;
|
|
// Grow the table
|
|
try {
|
|
table.grow(1);
|
|
} catch (err) {
|
|
if (!(err instanceof RangeError)) {
|
|
throw err;
|
|
}
|
|
throw 'Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.';
|
|
}
|
|
}
|
|
|
|
// Set the new value.
|
|
try {
|
|
// Attempting to call this with JS function will cause of table.set() to fail
|
|
table.set(ret, func);
|
|
} catch (err) {
|
|
if (!(err instanceof TypeError)) {
|
|
throw err;
|
|
}
|
|
var wrapped = convertJsFunctionToWasm(func, sig);
|
|
table.set(ret, wrapped);
|
|
}
|
|
|
|
functionsInTableMap.set(func, ret);
|
|
|
|
return ret;
|
|
}
|
|
|
|
function removeFunctionWasm(index) {
|
|
functionsInTableMap.delete(wasmTable.get(index));
|
|
freeTableIndexes.push(index);
|
|
}
|
|
|
|
// 'sig' parameter is required for the llvm backend but only when func is not
|
|
// already a WebAssembly function.
|
|
function addFunction(func, sig) {
|
|
|
|
return addFunctionWasm(func, sig);
|
|
}
|
|
|
|
function removeFunction(index) {
|
|
removeFunctionWasm(index);
|
|
}
|
|
|
|
|
|
|
|
var funcWrappers = {};
|
|
|
|
function getFuncWrapper(func, sig) {
|
|
if (!func) return; // on null pointer, return undefined
|
|
assert(sig);
|
|
if (!funcWrappers[sig]) {
|
|
funcWrappers[sig] = {};
|
|
}
|
|
var sigCache = funcWrappers[sig];
|
|
if (!sigCache[func]) {
|
|
// optimize away arguments usage in common cases
|
|
if (sig.length === 1) {
|
|
sigCache[func] = function dynCall_wrapper() {
|
|
return dynCall(sig, func);
|
|
};
|
|
} else if (sig.length === 2) {
|
|
sigCache[func] = function dynCall_wrapper(arg) {
|
|
return dynCall(sig, func, [arg]);
|
|
};
|
|
} else {
|
|
// general case
|
|
sigCache[func] = function dynCall_wrapper() {
|
|
return dynCall(sig, func, Array.prototype.slice.call(arguments));
|
|
};
|
|
}
|
|
}
|
|
return sigCache[func];
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function makeBigInt(low, high, unsigned) {
|
|
return unsigned ? ((+((low>>>0)))+((+((high>>>0)))*4294967296.0)) : ((+((low>>>0)))+((+((high|0)))*4294967296.0));
|
|
}
|
|
|
|
/** @param {Array=} args */
|
|
function dynCall(sig, ptr, args) {
|
|
if (args && args.length) {
|
|
return Module['dynCall_' + sig].apply(null, [ptr].concat(args));
|
|
} else {
|
|
return Module['dynCall_' + sig].call(null, ptr);
|
|
}
|
|
}
|
|
|
|
var tempRet0 = 0;
|
|
|
|
var setTempRet0 = function(value) {
|
|
tempRet0 = value;
|
|
};
|
|
|
|
var getTempRet0 = function() {
|
|
return tempRet0;
|
|
};
|
|
|
|
|
|
// The address globals begin at. Very low in memory, for code size and optimization opportunities.
|
|
// Above 0 is static memory, starting with globals.
|
|
// Then the stack.
|
|
// Then 'dynamic' memory for sbrk.
|
|
var GLOBAL_BASE = 1024;
|
|
|
|
|
|
|
|
|
|
|
|
// === Preamble library stuff ===
|
|
|
|
// Documentation for the public APIs defined in this file must be updated in:
|
|
// site/source/docs/api_reference/preamble.js.rst
|
|
// A prebuilt local version of the documentation is available at:
|
|
// site/build/text/docs/api_reference/preamble.js.txt
|
|
// You can also build docs locally as HTML or other formats in site/
|
|
// An online HTML version (which may be of a different version of Emscripten)
|
|
// is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html
|
|
|
|
|
|
var wasmBinary;if (Module['wasmBinary']) wasmBinary = Module['wasmBinary'];
|
|
var noExitRuntime;if (Module['noExitRuntime']) noExitRuntime = Module['noExitRuntime'];
|
|
|
|
|
|
if (typeof WebAssembly !== 'object') {
|
|
err('no native wasm support detected');
|
|
}
|
|
|
|
|
|
|
|
|
|
// In MINIMAL_RUNTIME, setValue() and getValue() are only available when building with safe heap enabled, for heap safety checking.
|
|
// In traditional runtime, setValue() and getValue() are always available (although their use is highly discouraged due to perf penalties)
|
|
|
|
/** @param {number} ptr
|
|
@param {number} value
|
|
@param {string} type
|
|
@param {number|boolean=} noSafe */
|
|
function setValue(ptr, value, type, noSafe) {
|
|
type = type || 'i8';
|
|
if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
|
|
switch(type) {
|
|
case 'i1': HEAP8[((ptr)>>0)]=value; break;
|
|
case 'i8': HEAP8[((ptr)>>0)]=value; break;
|
|
case 'i16': HEAP16[((ptr)>>1)]=value; break;
|
|
case 'i32': HEAP32[((ptr)>>2)]=value; break;
|
|
case 'i64': (tempI64 = [value>>>0,(tempDouble=value,(+(Math_abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math_min((+(Math_floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math_ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[((ptr)>>2)]=tempI64[0],HEAP32[(((ptr)+(4))>>2)]=tempI64[1]); break;
|
|
case 'float': HEAPF32[((ptr)>>2)]=value; break;
|
|
case 'double': HEAPF64[((ptr)>>3)]=value; break;
|
|
default: abort('invalid type for setValue: ' + type);
|
|
}
|
|
}
|
|
|
|
/** @param {number} ptr
|
|
@param {string} type
|
|
@param {number|boolean=} noSafe */
|
|
function getValue(ptr, type, noSafe) {
|
|
type = type || 'i8';
|
|
if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
|
|
switch(type) {
|
|
case 'i1': return HEAP8[((ptr)>>0)];
|
|
case 'i8': return HEAP8[((ptr)>>0)];
|
|
case 'i16': return HEAP16[((ptr)>>1)];
|
|
case 'i32': return HEAP32[((ptr)>>2)];
|
|
case 'i64': return HEAP32[((ptr)>>2)];
|
|
case 'float': return HEAPF32[((ptr)>>2)];
|
|
case 'double': return HEAPF64[((ptr)>>3)];
|
|
default: abort('invalid type for getValue: ' + type);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// Wasm globals
|
|
|
|
var wasmMemory;
|
|
|
|
// In fastcomp asm.js, we don't need a wasm Table at all.
|
|
// In the wasm backend, we polyfill the WebAssembly object,
|
|
// so this creates a (non-native-wasm) table for us.
|
|
var wasmTable = new WebAssembly.Table({
|
|
'initial': 4,
|
|
'maximum': 4 + 0,
|
|
'element': 'anyfunc'
|
|
});
|
|
|
|
|
|
//========================================
|
|
// Runtime essentials
|
|
//========================================
|
|
|
|
// whether we are quitting the application. no code should run after this.
|
|
// set in exit() and abort()
|
|
var ABORT = false;
|
|
|
|
// set by exit() and abort(). Passed to 'onExit' handler.
|
|
// NOTE: This is also used as the process return code code in shell environments
|
|
// but only when noExitRuntime is false.
|
|
var EXITSTATUS = 0;
|
|
|
|
/** @type {function(*, string=)} */
|
|
function assert(condition, text) {
|
|
if (!condition) {
|
|
abort('Assertion failed: ' + text);
|
|
}
|
|
}
|
|
|
|
// Returns the C function with a specified identifier (for C++, you need to do manual name mangling)
|
|
function getCFunc(ident) {
|
|
var func = Module['_' + ident]; // closure exported function
|
|
assert(func, 'Cannot call unknown function ' + ident + ', make sure it is exported');
|
|
return func;
|
|
}
|
|
|
|
// C calling interface.
|
|
/** @param {string|null=} returnType
|
|
@param {Array=} argTypes
|
|
@param {Arguments|Array=} args
|
|
@param {Object=} opts */
|
|
function ccall(ident, returnType, argTypes, args, opts) {
|
|
// For fast lookup of conversion functions
|
|
var toC = {
|
|
'string': function(str) {
|
|
var ret = 0;
|
|
if (str !== null && str !== undefined && str !== 0) { // null string
|
|
// at most 4 bytes per UTF-8 code point, +1 for the trailing '\0'
|
|
var len = (str.length << 2) + 1;
|
|
ret = stackAlloc(len);
|
|
stringToUTF8(str, ret, len);
|
|
}
|
|
return ret;
|
|
},
|
|
'array': function(arr) {
|
|
var ret = stackAlloc(arr.length);
|
|
writeArrayToMemory(arr, ret);
|
|
return ret;
|
|
}
|
|
};
|
|
|
|
function convertReturnValue(ret) {
|
|
if (returnType === 'string') return UTF8ToString(ret);
|
|
if (returnType === 'boolean') return Boolean(ret);
|
|
return ret;
|
|
}
|
|
|
|
var func = getCFunc(ident);
|
|
var cArgs = [];
|
|
var stack = 0;
|
|
if (args) {
|
|
for (var i = 0; i < args.length; i++) {
|
|
var converter = toC[argTypes[i]];
|
|
if (converter) {
|
|
if (stack === 0) stack = stackSave();
|
|
cArgs[i] = converter(args[i]);
|
|
} else {
|
|
cArgs[i] = args[i];
|
|
}
|
|
}
|
|
}
|
|
var ret = func.apply(null, cArgs);
|
|
|
|
ret = convertReturnValue(ret);
|
|
if (stack !== 0) stackRestore(stack);
|
|
return ret;
|
|
}
|
|
|
|
/** @param {string=} returnType
|
|
@param {Array=} argTypes
|
|
@param {Object=} opts */
|
|
function cwrap(ident, returnType, argTypes, opts) {
|
|
argTypes = argTypes || [];
|
|
// When the function takes numbers and returns a number, we can just return
|
|
// the original function
|
|
var numericArgs = argTypes.every(function(type){ return type === 'number'});
|
|
var numericRet = returnType !== 'string';
|
|
if (numericRet && numericArgs && !opts) {
|
|
return getCFunc(ident);
|
|
}
|
|
return function() {
|
|
return ccall(ident, returnType, argTypes, arguments, opts);
|
|
}
|
|
}
|
|
|
|
var ALLOC_NORMAL = 0; // Tries to use _malloc()
|
|
var ALLOC_STACK = 1; // Lives for the duration of the current function call
|
|
var ALLOC_DYNAMIC = 2; // Cannot be freed except through sbrk
|
|
var ALLOC_NONE = 3; // Do not allocate
|
|
|
|
// allocate(): This is for internal use. You can use it yourself as well, but the interface
|
|
// is a little tricky (see docs right below). The reason is that it is optimized
|
|
// for multiple syntaxes to save space in generated code. So you should
|
|
// normally not use allocate(), and instead allocate memory using _malloc(),
|
|
// initialize it with setValue(), and so forth.
|
|
// @slab: An array of data, or a number. If a number, then the size of the block to allocate,
|
|
// in *bytes* (note that this is sometimes confusing: the next parameter does not
|
|
// affect this!)
|
|
// @types: Either an array of types, one for each byte (or 0 if no type at that position),
|
|
// or a single type which is used for the entire block. This only matters if there
|
|
// is initial data - if @slab is a number, then this does not matter at all and is
|
|
// ignored.
|
|
// @allocator: How to allocate memory, see ALLOC_*
|
|
/** @type {function((TypedArray|Array<number>|number), string, number, number=)} */
|
|
function allocate(slab, types, allocator, ptr) {
|
|
var zeroinit, size;
|
|
if (typeof slab === 'number') {
|
|
zeroinit = true;
|
|
size = slab;
|
|
} else {
|
|
zeroinit = false;
|
|
size = slab.length;
|
|
}
|
|
|
|
var singleType = typeof types === 'string' ? types : null;
|
|
|
|
var ret;
|
|
if (allocator == ALLOC_NONE) {
|
|
ret = ptr;
|
|
} else {
|
|
ret = [_malloc,
|
|
stackAlloc,
|
|
dynamicAlloc][allocator](Math.max(size, singleType ? 1 : types.length));
|
|
}
|
|
|
|
if (zeroinit) {
|
|
var stop;
|
|
ptr = ret;
|
|
assert((ret & 3) == 0);
|
|
stop = ret + (size & ~3);
|
|
for (; ptr < stop; ptr += 4) {
|
|
HEAP32[((ptr)>>2)]=0;
|
|
}
|
|
stop = ret + size;
|
|
while (ptr < stop) {
|
|
HEAP8[((ptr++)>>0)]=0;
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
if (singleType === 'i8') {
|
|
if (slab.subarray || slab.slice) {
|
|
HEAPU8.set(/** @type {!Uint8Array} */ (slab), ret);
|
|
} else {
|
|
HEAPU8.set(new Uint8Array(slab), ret);
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
var i = 0, type, typeSize, previousType;
|
|
while (i < size) {
|
|
var curr = slab[i];
|
|
|
|
type = singleType || types[i];
|
|
if (type === 0) {
|
|
i++;
|
|
continue;
|
|
}
|
|
|
|
if (type == 'i64') type = 'i32'; // special case: we have one i32 here, and one i32 later
|
|
|
|
setValue(ret+i, curr, type);
|
|
|
|
// no need to look up size unless type changes, so cache it
|
|
if (previousType !== type) {
|
|
typeSize = getNativeTypeSize(type);
|
|
previousType = type;
|
|
}
|
|
i += typeSize;
|
|
}
|
|
|
|
return ret;
|
|
}
|
|
|
|
// Allocate memory during any stage of startup - static memory early on, dynamic memory later, malloc when ready
|
|
function getMemory(size) {
|
|
if (!runtimeInitialized) return dynamicAlloc(size);
|
|
return _malloc(size);
|
|
}
|
|
|
|
|
|
|
|
|
|
// runtime_strings.js: Strings related runtime functions that are part of both MINIMAL_RUNTIME and regular runtime.
|
|
|
|
// Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the given array that contains uint8 values, returns
|
|
// a copy of that string as a Javascript String object.
|
|
|
|
var UTF8Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf8') : undefined;
|
|
|
|
/**
|
|
* @param {number} idx
|
|
* @param {number=} maxBytesToRead
|
|
* @return {string}
|
|
*/
|
|
function UTF8ArrayToString(heap, idx, maxBytesToRead) {
|
|
var endIdx = idx + maxBytesToRead;
|
|
var endPtr = idx;
|
|
// TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself.
|
|
// Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage.
|
|
// (As a tiny code save trick, compare endPtr against endIdx using a negation, so that undefined means Infinity)
|
|
while (heap[endPtr] && !(endPtr >= endIdx)) ++endPtr;
|
|
|
|
if (endPtr - idx > 16 && heap.subarray && UTF8Decoder) {
|
|
return UTF8Decoder.decode(heap.subarray(idx, endPtr));
|
|
} else {
|
|
var str = '';
|
|
// If building with TextDecoder, we have already computed the string length above, so test loop end condition against that
|
|
while (idx < endPtr) {
|
|
// For UTF8 byte structure, see:
|
|
// http://en.wikipedia.org/wiki/UTF-8#Description
|
|
// https://www.ietf.org/rfc/rfc2279.txt
|
|
// https://tools.ietf.org/html/rfc3629
|
|
var u0 = heap[idx++];
|
|
if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; }
|
|
var u1 = heap[idx++] & 63;
|
|
if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; }
|
|
var u2 = heap[idx++] & 63;
|
|
if ((u0 & 0xF0) == 0xE0) {
|
|
u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;
|
|
} else {
|
|
u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heap[idx++] & 63);
|
|
}
|
|
|
|
if (u0 < 0x10000) {
|
|
str += String.fromCharCode(u0);
|
|
} else {
|
|
var ch = u0 - 0x10000;
|
|
str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
|
|
}
|
|
}
|
|
}
|
|
return str;
|
|
}
|
|
|
|
// Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the emscripten HEAP, returns a
|
|
// copy of that string as a Javascript String object.
|
|
// maxBytesToRead: an optional length that specifies the maximum number of bytes to read. You can omit
|
|
// this parameter to scan the string until the first \0 byte. If maxBytesToRead is
|
|
// passed, and the string at [ptr, ptr+maxBytesToReadr[ contains a null byte in the
|
|
// middle, then the string will cut short at that byte index (i.e. maxBytesToRead will
|
|
// not produce a string of exact length [ptr, ptr+maxBytesToRead[)
|
|
// N.B. mixing frequent uses of UTF8ToString() with and without maxBytesToRead may
|
|
// throw JS JIT optimizations off, so it is worth to consider consistently using one
|
|
// style or the other.
|
|
/**
|
|
* @param {number} ptr
|
|
* @param {number=} maxBytesToRead
|
|
* @return {string}
|
|
*/
|
|
function UTF8ToString(ptr, maxBytesToRead) {
|
|
return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : '';
|
|
}
|
|
|
|
// Copies the given Javascript String object 'str' to the given byte array at address 'outIdx',
|
|
// encoded in UTF8 form and null-terminated. The copy will require at most str.length*4+1 bytes of space in the HEAP.
|
|
// Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write.
|
|
// Parameters:
|
|
// str: the Javascript string to copy.
|
|
// heap: the array to copy to. Each index in this array is assumed to be one 8-byte element.
|
|
// outIdx: The starting offset in the array to begin the copying.
|
|
// maxBytesToWrite: The maximum number of bytes this function can write to the array.
|
|
// This count should include the null terminator,
|
|
// i.e. if maxBytesToWrite=1, only the null terminator will be written and nothing else.
|
|
// maxBytesToWrite=0 does not write any bytes to the output, not even the null terminator.
|
|
// Returns the number of bytes written, EXCLUDING the null terminator.
|
|
|
|
function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) {
|
|
if (!(maxBytesToWrite > 0)) // Parameter maxBytesToWrite is not optional. Negative values, 0, null, undefined and false each don't write out any bytes.
|
|
return 0;
|
|
|
|
var startIdx = outIdx;
|
|
var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator.
|
|
for (var i = 0; i < str.length; ++i) {
|
|
// Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! So decode UTF16->UTF32->UTF8.
|
|
// See http://unicode.org/faq/utf_bom.html#utf16-3
|
|
// For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description and https://www.ietf.org/rfc/rfc2279.txt and https://tools.ietf.org/html/rfc3629
|
|
var u = str.charCodeAt(i); // possibly a lead surrogate
|
|
if (u >= 0xD800 && u <= 0xDFFF) {
|
|
var u1 = str.charCodeAt(++i);
|
|
u = 0x10000 + ((u & 0x3FF) << 10) | (u1 & 0x3FF);
|
|
}
|
|
if (u <= 0x7F) {
|
|
if (outIdx >= endIdx) break;
|
|
heap[outIdx++] = u;
|
|
} else if (u <= 0x7FF) {
|
|
if (outIdx + 1 >= endIdx) break;
|
|
heap[outIdx++] = 0xC0 | (u >> 6);
|
|
heap[outIdx++] = 0x80 | (u & 63);
|
|
} else if (u <= 0xFFFF) {
|
|
if (outIdx + 2 >= endIdx) break;
|
|
heap[outIdx++] = 0xE0 | (u >> 12);
|
|
heap[outIdx++] = 0x80 | ((u >> 6) & 63);
|
|
heap[outIdx++] = 0x80 | (u & 63);
|
|
} else {
|
|
if (outIdx + 3 >= endIdx) break;
|
|
heap[outIdx++] = 0xF0 | (u >> 18);
|
|
heap[outIdx++] = 0x80 | ((u >> 12) & 63);
|
|
heap[outIdx++] = 0x80 | ((u >> 6) & 63);
|
|
heap[outIdx++] = 0x80 | (u & 63);
|
|
}
|
|
}
|
|
// Null-terminate the pointer to the buffer.
|
|
heap[outIdx] = 0;
|
|
return outIdx - startIdx;
|
|
}
|
|
|
|
// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
|
|
// null-terminated and encoded in UTF8 form. The copy will require at most str.length*4+1 bytes of space in the HEAP.
|
|
// Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write.
|
|
// Returns the number of bytes written, EXCLUDING the null terminator.
|
|
|
|
function stringToUTF8(str, outPtr, maxBytesToWrite) {
|
|
return stringToUTF8Array(str, HEAPU8,outPtr, maxBytesToWrite);
|
|
}
|
|
|
|
// Returns the number of bytes the given Javascript string takes if encoded as a UTF8 byte array, EXCLUDING the null terminator byte.
|
|
function lengthBytesUTF8(str) {
|
|
var len = 0;
|
|
for (var i = 0; i < str.length; ++i) {
|
|
// Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! So decode UTF16->UTF32->UTF8.
|
|
// See http://unicode.org/faq/utf_bom.html#utf16-3
|
|
var u = str.charCodeAt(i); // possibly a lead surrogate
|
|
if (u >= 0xD800 && u <= 0xDFFF) u = 0x10000 + ((u & 0x3FF) << 10) | (str.charCodeAt(++i) & 0x3FF);
|
|
if (u <= 0x7F) ++len;
|
|
else if (u <= 0x7FF) len += 2;
|
|
else if (u <= 0xFFFF) len += 3;
|
|
else len += 4;
|
|
}
|
|
return len;
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// runtime_strings_extra.js: Strings related runtime functions that are available only in regular runtime.
|
|
|
|
// Given a pointer 'ptr' to a null-terminated ASCII-encoded string in the emscripten HEAP, returns
|
|
// a copy of that string as a Javascript String object.
|
|
|
|
function AsciiToString(ptr) {
|
|
var str = '';
|
|
while (1) {
|
|
var ch = HEAPU8[((ptr++)>>0)];
|
|
if (!ch) return str;
|
|
str += String.fromCharCode(ch);
|
|
}
|
|
}
|
|
|
|
// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
|
|
// null-terminated and encoded in ASCII form. The copy will require at most str.length+1 bytes of space in the HEAP.
|
|
|
|
function stringToAscii(str, outPtr) {
|
|
return writeAsciiToMemory(str, outPtr, false);
|
|
}
|
|
|
|
// Given a pointer 'ptr' to a null-terminated UTF16LE-encoded string in the emscripten HEAP, returns
|
|
// a copy of that string as a Javascript String object.
|
|
|
|
var UTF16Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-16le') : undefined;
|
|
|
|
function UTF16ToString(ptr, maxBytesToRead) {
|
|
var endPtr = ptr;
|
|
// TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself.
|
|
// Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage.
|
|
var idx = endPtr >> 1;
|
|
var maxIdx = idx + maxBytesToRead / 2;
|
|
// If maxBytesToRead is not passed explicitly, it will be undefined, and this
|
|
// will always evaluate to true. This saves on code size.
|
|
while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx;
|
|
endPtr = idx << 1;
|
|
|
|
if (endPtr - ptr > 32 && UTF16Decoder) {
|
|
return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr));
|
|
} else {
|
|
var i = 0;
|
|
|
|
var str = '';
|
|
while (1) {
|
|
var codeUnit = HEAP16[(((ptr)+(i*2))>>1)];
|
|
if (codeUnit == 0 || i == maxBytesToRead / 2) return str;
|
|
++i;
|
|
// fromCharCode constructs a character from a UTF-16 code unit, so we can pass the UTF16 string right through.
|
|
str += String.fromCharCode(codeUnit);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
|
|
// null-terminated and encoded in UTF16 form. The copy will require at most str.length*4+2 bytes of space in the HEAP.
|
|
// Use the function lengthBytesUTF16() to compute the exact number of bytes (excluding null terminator) that this function will write.
|
|
// Parameters:
|
|
// str: the Javascript string to copy.
|
|
// outPtr: Byte address in Emscripten HEAP where to write the string to.
|
|
// maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null
|
|
// terminator, i.e. if maxBytesToWrite=2, only the null terminator will be written and nothing else.
|
|
// maxBytesToWrite<2 does not write any bytes to the output, not even the null terminator.
|
|
// Returns the number of bytes written, EXCLUDING the null terminator.
|
|
|
|
function stringToUTF16(str, outPtr, maxBytesToWrite) {
|
|
// Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.
|
|
if (maxBytesToWrite === undefined) {
|
|
maxBytesToWrite = 0x7FFFFFFF;
|
|
}
|
|
if (maxBytesToWrite < 2) return 0;
|
|
maxBytesToWrite -= 2; // Null terminator.
|
|
var startPtr = outPtr;
|
|
var numCharsToWrite = (maxBytesToWrite < str.length*2) ? (maxBytesToWrite / 2) : str.length;
|
|
for (var i = 0; i < numCharsToWrite; ++i) {
|
|
// charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP.
|
|
var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
|
|
HEAP16[((outPtr)>>1)]=codeUnit;
|
|
outPtr += 2;
|
|
}
|
|
// Null-terminate the pointer to the HEAP.
|
|
HEAP16[((outPtr)>>1)]=0;
|
|
return outPtr - startPtr;
|
|
}
|
|
|
|
// Returns the number of bytes the given Javascript string takes if encoded as a UTF16 byte array, EXCLUDING the null terminator byte.
|
|
|
|
function lengthBytesUTF16(str) {
|
|
return str.length*2;
|
|
}
|
|
|
|
function UTF32ToString(ptr, maxBytesToRead) {
|
|
var i = 0;
|
|
|
|
var str = '';
|
|
// If maxBytesToRead is not passed explicitly, it will be undefined, and this
|
|
// will always evaluate to true. This saves on code size.
|
|
while (!(i >= maxBytesToRead / 4)) {
|
|
var utf32 = HEAP32[(((ptr)+(i*4))>>2)];
|
|
if (utf32 == 0) break;
|
|
++i;
|
|
// Gotcha: fromCharCode constructs a character from a UTF-16 encoded code (pair), not from a Unicode code point! So encode the code point to UTF-16 for constructing.
|
|
// See http://unicode.org/faq/utf_bom.html#utf16-3
|
|
if (utf32 >= 0x10000) {
|
|
var ch = utf32 - 0x10000;
|
|
str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
|
|
} else {
|
|
str += String.fromCharCode(utf32);
|
|
}
|
|
}
|
|
return str;
|
|
}
|
|
|
|
// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
|
|
// null-terminated and encoded in UTF32 form. The copy will require at most str.length*4+4 bytes of space in the HEAP.
|
|
// Use the function lengthBytesUTF32() to compute the exact number of bytes (excluding null terminator) that this function will write.
|
|
// Parameters:
|
|
// str: the Javascript string to copy.
|
|
// outPtr: Byte address in Emscripten HEAP where to write the string to.
|
|
// maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null
|
|
// terminator, i.e. if maxBytesToWrite=4, only the null terminator will be written and nothing else.
|
|
// maxBytesToWrite<4 does not write any bytes to the output, not even the null terminator.
|
|
// Returns the number of bytes written, EXCLUDING the null terminator.
|
|
|
|
function stringToUTF32(str, outPtr, maxBytesToWrite) {
|
|
// Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.
|
|
if (maxBytesToWrite === undefined) {
|
|
maxBytesToWrite = 0x7FFFFFFF;
|
|
}
|
|
if (maxBytesToWrite < 4) return 0;
|
|
var startPtr = outPtr;
|
|
var endPtr = startPtr + maxBytesToWrite - 4;
|
|
for (var i = 0; i < str.length; ++i) {
|
|
// Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! We must decode the string to UTF-32 to the heap.
|
|
// See http://unicode.org/faq/utf_bom.html#utf16-3
|
|
var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
|
|
if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) {
|
|
var trailSurrogate = str.charCodeAt(++i);
|
|
codeUnit = 0x10000 + ((codeUnit & 0x3FF) << 10) | (trailSurrogate & 0x3FF);
|
|
}
|
|
HEAP32[((outPtr)>>2)]=codeUnit;
|
|
outPtr += 4;
|
|
if (outPtr + 4 > endPtr) break;
|
|
}
|
|
// Null-terminate the pointer to the HEAP.
|
|
HEAP32[((outPtr)>>2)]=0;
|
|
return outPtr - startPtr;
|
|
}
|
|
|
|
// Returns the number of bytes the given Javascript string takes if encoded as a UTF16 byte array, EXCLUDING the null terminator byte.
|
|
|
|
function lengthBytesUTF32(str) {
|
|
var len = 0;
|
|
for (var i = 0; i < str.length; ++i) {
|
|
// Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! We must decode the string to UTF-32 to the heap.
|
|
// See http://unicode.org/faq/utf_bom.html#utf16-3
|
|
var codeUnit = str.charCodeAt(i);
|
|
if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) ++i; // possibly a lead surrogate, so skip over the tail surrogate.
|
|
len += 4;
|
|
}
|
|
|
|
return len;
|
|
}
|
|
|
|
// Allocate heap space for a JS string, and write it there.
|
|
// It is the responsibility of the caller to free() that memory.
|
|
function allocateUTF8(str) {
|
|
var size = lengthBytesUTF8(str) + 1;
|
|
var ret = _malloc(size);
|
|
if (ret) stringToUTF8Array(str, HEAP8, ret, size);
|
|
return ret;
|
|
}
|
|
|
|
// Allocate stack space for a JS string, and write it there.
|
|
function allocateUTF8OnStack(str) {
|
|
var size = lengthBytesUTF8(str) + 1;
|
|
var ret = stackAlloc(size);
|
|
stringToUTF8Array(str, HEAP8, ret, size);
|
|
return ret;
|
|
}
|
|
|
|
// Deprecated: This function should not be called because it is unsafe and does not provide
|
|
// a maximum length limit of how many bytes it is allowed to write. Prefer calling the
|
|
// function stringToUTF8Array() instead, which takes in a maximum length that can be used
|
|
// to be secure from out of bounds writes.
|
|
/** @deprecated
|
|
@param {boolean=} dontAddNull */
|
|
function writeStringToMemory(string, buffer, dontAddNull) {
|
|
warnOnce('writeStringToMemory is deprecated and should not be called! Use stringToUTF8() instead!');
|
|
|
|
var /** @type {number} */ lastChar, /** @type {number} */ end;
|
|
if (dontAddNull) {
|
|
// stringToUTF8Array always appends null. If we don't want to do that, remember the
|
|
// character that existed at the location where the null will be placed, and restore
|
|
// that after the write (below).
|
|
end = buffer + lengthBytesUTF8(string);
|
|
lastChar = HEAP8[end];
|
|
}
|
|
stringToUTF8(string, buffer, Infinity);
|
|
if (dontAddNull) HEAP8[end] = lastChar; // Restore the value under the null character.
|
|
}
|
|
|
|
function writeArrayToMemory(array, buffer) {
|
|
HEAP8.set(array, buffer);
|
|
}
|
|
|
|
/** @param {boolean=} dontAddNull */
|
|
function writeAsciiToMemory(str, buffer, dontAddNull) {
|
|
for (var i = 0; i < str.length; ++i) {
|
|
HEAP8[((buffer++)>>0)]=str.charCodeAt(i);
|
|
}
|
|
// Null-terminate the pointer to the HEAP.
|
|
if (!dontAddNull) HEAP8[((buffer)>>0)]=0;
|
|
}
|
|
|
|
|
|
|
|
// Memory management
|
|
|
|
var PAGE_SIZE = 16384;
|
|
var WASM_PAGE_SIZE = 65536;
|
|
var ASMJS_PAGE_SIZE = 16777216;
|
|
|
|
function alignUp(x, multiple) {
|
|
if (x % multiple > 0) {
|
|
x += multiple - (x % multiple);
|
|
}
|
|
return x;
|
|
}
|
|
|
|
var HEAP,
|
|
/** @type {ArrayBuffer} */
|
|
buffer,
|
|
/** @type {Int8Array} */
|
|
HEAP8,
|
|
/** @type {Uint8Array} */
|
|
HEAPU8,
|
|
/** @type {Int16Array} */
|
|
HEAP16,
|
|
/** @type {Uint16Array} */
|
|
HEAPU16,
|
|
/** @type {Int32Array} */
|
|
HEAP32,
|
|
/** @type {Uint32Array} */
|
|
HEAPU32,
|
|
/** @type {Float32Array} */
|
|
HEAPF32,
|
|
/** @type {Float64Array} */
|
|
HEAPF64;
|
|
|
|
function updateGlobalBufferAndViews(buf) {
|
|
buffer = buf;
|
|
Module['HEAP8'] = HEAP8 = new Int8Array(buf);
|
|
Module['HEAP16'] = HEAP16 = new Int16Array(buf);
|
|
Module['HEAP32'] = HEAP32 = new Int32Array(buf);
|
|
Module['HEAPU8'] = HEAPU8 = new Uint8Array(buf);
|
|
Module['HEAPU16'] = HEAPU16 = new Uint16Array(buf);
|
|
Module['HEAPU32'] = HEAPU32 = new Uint32Array(buf);
|
|
Module['HEAPF32'] = HEAPF32 = new Float32Array(buf);
|
|
Module['HEAPF64'] = HEAPF64 = new Float64Array(buf);
|
|
}
|
|
|
|
var STATIC_BASE = 1024,
|
|
STACK_BASE = 5340160,
|
|
STACKTOP = STACK_BASE,
|
|
STACK_MAX = 97280,
|
|
DYNAMIC_BASE = 5340160,
|
|
DYNAMICTOP_PTR = 97120;
|
|
|
|
|
|
|
|
var TOTAL_STACK = 5242880;
|
|
|
|
var INITIAL_INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// In non-standalone/normal mode, we create the memory here.
|
|
|
|
|
|
|
|
// Create the main memory. (Note: this isn't used in STANDALONE_WASM mode since the wasm
|
|
// memory is created in the wasm, not in JS.)
|
|
|
|
if (Module['wasmMemory']) {
|
|
wasmMemory = Module['wasmMemory'];
|
|
} else
|
|
{
|
|
wasmMemory = new WebAssembly.Memory({
|
|
'initial': INITIAL_INITIAL_MEMORY / WASM_PAGE_SIZE
|
|
,
|
|
'maximum': 2147483648 / WASM_PAGE_SIZE
|
|
});
|
|
}
|
|
|
|
|
|
if (wasmMemory) {
|
|
buffer = wasmMemory.buffer;
|
|
}
|
|
|
|
// If the user provides an incorrect length, just use that length instead rather than providing the user to
|
|
// specifically provide the memory length with Module['INITIAL_MEMORY'].
|
|
INITIAL_INITIAL_MEMORY = buffer.byteLength;
|
|
updateGlobalBufferAndViews(buffer);
|
|
|
|
HEAP32[DYNAMICTOP_PTR>>2] = DYNAMIC_BASE;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function callRuntimeCallbacks(callbacks) {
|
|
while(callbacks.length > 0) {
|
|
var callback = callbacks.shift();
|
|
if (typeof callback == 'function') {
|
|
callback(Module); // Pass the module as the first argument.
|
|
continue;
|
|
}
|
|
var func = callback.func;
|
|
if (typeof func === 'number') {
|
|
if (callback.arg === undefined) {
|
|
Module['dynCall_v'](func);
|
|
} else {
|
|
Module['dynCall_vi'](func, callback.arg);
|
|
}
|
|
} else {
|
|
func(callback.arg === undefined ? null : callback.arg);
|
|
}
|
|
}
|
|
}
|
|
|
|
var __ATPRERUN__ = []; // functions called before the runtime is initialized
|
|
var __ATINIT__ = []; // functions called during startup
|
|
var __ATMAIN__ = []; // functions called when main() is to be run
|
|
var __ATEXIT__ = []; // functions called during shutdown
|
|
var __ATPOSTRUN__ = []; // functions called after the main() is called
|
|
|
|
var runtimeInitialized = false;
|
|
var runtimeExited = false;
|
|
|
|
|
|
function preRun() {
|
|
|
|
if (Module['preRun']) {
|
|
if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']];
|
|
while (Module['preRun'].length) {
|
|
addOnPreRun(Module['preRun'].shift());
|
|
}
|
|
}
|
|
|
|
callRuntimeCallbacks(__ATPRERUN__);
|
|
}
|
|
|
|
function initRuntime() {
|
|
runtimeInitialized = true;
|
|
|
|
callRuntimeCallbacks(__ATINIT__);
|
|
}
|
|
|
|
function preMain() {
|
|
|
|
callRuntimeCallbacks(__ATMAIN__);
|
|
}
|
|
|
|
function exitRuntime() {
|
|
runtimeExited = true;
|
|
}
|
|
|
|
function postRun() {
|
|
|
|
if (Module['postRun']) {
|
|
if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']];
|
|
while (Module['postRun'].length) {
|
|
addOnPostRun(Module['postRun'].shift());
|
|
}
|
|
}
|
|
|
|
callRuntimeCallbacks(__ATPOSTRUN__);
|
|
}
|
|
|
|
function addOnPreRun(cb) {
|
|
__ATPRERUN__.unshift(cb);
|
|
}
|
|
|
|
function addOnInit(cb) {
|
|
__ATINIT__.unshift(cb);
|
|
}
|
|
|
|
function addOnPreMain(cb) {
|
|
__ATMAIN__.unshift(cb);
|
|
}
|
|
|
|
function addOnExit(cb) {
|
|
}
|
|
|
|
function addOnPostRun(cb) {
|
|
__ATPOSTRUN__.unshift(cb);
|
|
}
|
|
|
|
/** @param {number|boolean=} ignore */
|
|
function unSign(value, bits, ignore) {
|
|
if (value >= 0) {
|
|
return value;
|
|
}
|
|
return bits <= 32 ? 2*Math.abs(1 << (bits-1)) + value // Need some trickery, since if bits == 32, we are right at the limit of the bits JS uses in bitshifts
|
|
: Math.pow(2, bits) + value;
|
|
}
|
|
/** @param {number|boolean=} ignore */
|
|
function reSign(value, bits, ignore) {
|
|
if (value <= 0) {
|
|
return value;
|
|
}
|
|
var half = bits <= 32 ? Math.abs(1 << (bits-1)) // abs is needed if bits == 32
|
|
: Math.pow(2, bits-1);
|
|
if (value >= half && (bits <= 32 || value > half)) { // for huge values, we can hit the precision limit and always get true here. so don't do that
|
|
// but, in general there is no perfect solution here. With 64-bit ints, we get rounding and errors
|
|
// TODO: In i64 mode 1, resign the two parts separately and safely
|
|
value = -2*half + value; // Cannot bitshift half, as it may be at the limit of the bits JS uses in bitshifts
|
|
}
|
|
return value;
|
|
}
|
|
|
|
|
|
|
|
|
|
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul
|
|
|
|
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/fround
|
|
|
|
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32
|
|
|
|
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
|
|
|
|
|
|
var Math_abs = Math.abs;
|
|
var Math_cos = Math.cos;
|
|
var Math_sin = Math.sin;
|
|
var Math_tan = Math.tan;
|
|
var Math_acos = Math.acos;
|
|
var Math_asin = Math.asin;
|
|
var Math_atan = Math.atan;
|
|
var Math_atan2 = Math.atan2;
|
|
var Math_exp = Math.exp;
|
|
var Math_log = Math.log;
|
|
var Math_sqrt = Math.sqrt;
|
|
var Math_ceil = Math.ceil;
|
|
var Math_floor = Math.floor;
|
|
var Math_pow = Math.pow;
|
|
var Math_imul = Math.imul;
|
|
var Math_fround = Math.fround;
|
|
var Math_round = Math.round;
|
|
var Math_min = Math.min;
|
|
var Math_max = Math.max;
|
|
var Math_clz32 = Math.clz32;
|
|
var Math_trunc = Math.trunc;
|
|
|
|
|
|
|
|
// A counter of dependencies for calling run(). If we need to
|
|
// do asynchronous work before running, increment this and
|
|
// decrement it. Incrementing must happen in a place like
|
|
// Module.preRun (used by emcc to add file preloading).
|
|
// Note that you can add dependencies in preRun, even though
|
|
// it happens right before run - run will be postponed until
|
|
// the dependencies are met.
|
|
var runDependencies = 0;
|
|
var runDependencyWatcher = null;
|
|
var dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled
|
|
|
|
function getUniqueRunDependency(id) {
|
|
return id;
|
|
}
|
|
|
|
function addRunDependency(id) {
|
|
runDependencies++;
|
|
|
|
if (Module['monitorRunDependencies']) {
|
|
Module['monitorRunDependencies'](runDependencies);
|
|
}
|
|
|
|
}
|
|
|
|
function removeRunDependency(id) {
|
|
runDependencies--;
|
|
|
|
if (Module['monitorRunDependencies']) {
|
|
Module['monitorRunDependencies'](runDependencies);
|
|
}
|
|
|
|
if (runDependencies == 0) {
|
|
if (runDependencyWatcher !== null) {
|
|
clearInterval(runDependencyWatcher);
|
|
runDependencyWatcher = null;
|
|
}
|
|
if (dependenciesFulfilled) {
|
|
var callback = dependenciesFulfilled;
|
|
dependenciesFulfilled = null;
|
|
callback(); // can add another dependenciesFulfilled
|
|
}
|
|
}
|
|
}
|
|
|
|
Module["preloadedImages"] = {}; // maps url to image data
|
|
Module["preloadedAudios"] = {}; // maps url to audio data
|
|
|
|
/** @param {string|number=} what */
|
|
function abort(what) {
|
|
if (Module['onAbort']) {
|
|
Module['onAbort'](what);
|
|
}
|
|
|
|
what += '';
|
|
out(what);
|
|
err(what);
|
|
|
|
ABORT = true;
|
|
EXITSTATUS = 1;
|
|
|
|
what = 'abort(' + what + '). Build with -s ASSERTIONS=1 for more info.';
|
|
|
|
// Throw a wasm runtime error, because a JS error might be seen as a foreign
|
|
// exception, which means we'd run destructors on it. We need the error to
|
|
// simply make the program stop.
|
|
throw new WebAssembly.RuntimeError(what);
|
|
}
|
|
|
|
|
|
var memoryInitializer = null;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function hasPrefix(str, prefix) {
|
|
return String.prototype.startsWith ?
|
|
str.startsWith(prefix) :
|
|
str.indexOf(prefix) === 0;
|
|
}
|
|
|
|
// Prefix of data URIs emitted by SINGLE_FILE and related options.
|
|
var dataURIPrefix = 'data:application/octet-stream;base64,';
|
|
|
|
// Indicates whether filename is a base64 data URI.
|
|
function isDataURI(filename) {
|
|
return hasPrefix(filename, dataURIPrefix);
|
|
}
|
|
|
|
var fileURIPrefix = "file://";
|
|
|
|
// Indicates whether filename is delivered via file protocol (as opposed to http/https)
|
|
function isFileURI(filename) {
|
|
return hasPrefix(filename, fileURIPrefix);
|
|
}
|
|
|
|
|
|
|
|
|
|
var wasmBinaryFile = 'rnn_denoise.wasm';
|
|
if (!isDataURI(wasmBinaryFile)) {
|
|
wasmBinaryFile = locateFile(wasmBinaryFile);
|
|
}
|
|
|
|
function getBinary() {
|
|
try {
|
|
if (wasmBinary) {
|
|
return new Uint8Array(wasmBinary);
|
|
}
|
|
|
|
if (readBinary) {
|
|
return readBinary(wasmBinaryFile);
|
|
} else {
|
|
throw "both async and sync fetching of the wasm failed";
|
|
}
|
|
}
|
|
catch (err) {
|
|
abort(err);
|
|
}
|
|
}
|
|
|
|
function getBinaryPromise() {
|
|
// If we don't have the binary yet, and have the Fetch api, use that;
|
|
// in some environments, like Electron's render process, Fetch api may be present, but have a different context than expected, let's only use it on the Web
|
|
if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) && typeof fetch === 'function'
|
|
// Let's not use fetch to get objects over file:// as it's most likely Cordova which doesn't support fetch for file://
|
|
&& !isFileURI(wasmBinaryFile)
|
|
) {
|
|
return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function(response) {
|
|
if (!response['ok']) {
|
|
throw "failed to load wasm binary file at '" + wasmBinaryFile + "'";
|
|
}
|
|
return response['arrayBuffer']();
|
|
}).catch(function () {
|
|
return getBinary();
|
|
});
|
|
}
|
|
// Otherwise, getBinary should be able to get it synchronously
|
|
return new Promise(function(resolve, reject) {
|
|
resolve(getBinary());
|
|
});
|
|
}
|
|
|
|
|
|
|
|
// Create the wasm instance.
|
|
// Receives the wasm imports, returns the exports.
|
|
function createWasm() {
|
|
// prepare imports
|
|
var info = {
|
|
'env': asmLibraryArg,
|
|
'wasi_snapshot_preview1': asmLibraryArg
|
|
};
|
|
// Load the wasm module and create an instance of using native support in the JS engine.
|
|
// handle a generated wasm instance, receiving its exports and
|
|
// performing other necessary setup
|
|
/** @param {WebAssembly.Module=} module*/
|
|
function receiveInstance(instance, module) {
|
|
var exports = instance.exports;
|
|
Module['asm'] = exports;
|
|
removeRunDependency('wasm-instantiate');
|
|
}
|
|
// we can't run yet (except in a pthread, where we have a custom sync instantiator)
|
|
addRunDependency('wasm-instantiate');
|
|
|
|
|
|
function receiveInstantiatedSource(output) {
|
|
// 'output' is a WebAssemblyInstantiatedSource object which has both the module and instance.
|
|
// receiveInstance() will swap in the exports (to Module.asm) so they can be called
|
|
// TODO: Due to Closure regression https://github.com/google/closure-compiler/issues/3193, the above line no longer optimizes out down to the following line.
|
|
// When the regression is fixed, can restore the above USE_PTHREADS-enabled path.
|
|
receiveInstance(output['instance']);
|
|
}
|
|
|
|
|
|
function instantiateArrayBuffer(receiver) {
|
|
return getBinaryPromise().then(function(binary) {
|
|
return WebAssembly.instantiate(binary, info);
|
|
}).then(receiver, function(reason) {
|
|
err('failed to asynchronously prepare wasm: ' + reason);
|
|
abort(reason);
|
|
});
|
|
}
|
|
|
|
// Prefer streaming instantiation if available.
|
|
function instantiateAsync() {
|
|
if (!wasmBinary &&
|
|
typeof WebAssembly.instantiateStreaming === 'function' &&
|
|
!isDataURI(wasmBinaryFile) &&
|
|
// Don't use streaming for file:// delivered objects in a webview, fetch them synchronously.
|
|
!isFileURI(wasmBinaryFile) &&
|
|
typeof fetch === 'function') {
|
|
fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function (response) {
|
|
var result = WebAssembly.instantiateStreaming(response, info);
|
|
return result.then(receiveInstantiatedSource, function(reason) {
|
|
// We expect the most common failure cause to be a bad MIME type for the binary,
|
|
// in which case falling back to ArrayBuffer instantiation should work.
|
|
err('wasm streaming compile failed: ' + reason);
|
|
err('falling back to ArrayBuffer instantiation');
|
|
return instantiateArrayBuffer(receiveInstantiatedSource);
|
|
});
|
|
});
|
|
} else {
|
|
return instantiateArrayBuffer(receiveInstantiatedSource);
|
|
}
|
|
}
|
|
// User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback
|
|
// to manually instantiate the Wasm module themselves. This allows pages to run the instantiation parallel
|
|
// to any other async startup actions they are performing.
|
|
if (Module['instantiateWasm']) {
|
|
try {
|
|
var exports = Module['instantiateWasm'](info, receiveInstance);
|
|
return exports;
|
|
} catch(e) {
|
|
err('Module.instantiateWasm callback failed with error: ' + e);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
instantiateAsync();
|
|
return {}; // no exports yet; we'll fill them in later
|
|
}
|
|
|
|
|
|
// Globals used by JS i64 conversions
|
|
var tempDouble;
|
|
var tempI64;
|
|
|
|
// === Body ===
|
|
|
|
var ASM_CONSTS = {
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// STATICTOP = STATIC_BASE + 96256;
|
|
/* global initializers */ __ATINIT__.push({ func: function() { ___wasm_call_ctors() } });
|
|
|
|
|
|
|
|
|
|
/* no memory initializer */
|
|
// {{PRE_LIBRARY}}
|
|
|
|
|
|
function demangle(func) {
|
|
return func;
|
|
}
|
|
|
|
function demangleAll(text) {
|
|
var regex =
|
|
/\b_Z[\w\d_]+/g;
|
|
return text.replace(regex,
|
|
function(x) {
|
|
var y = demangle(x);
|
|
return x === y ? x : (y + ' [' + x + ']');
|
|
});
|
|
}
|
|
|
|
function jsStackTrace() {
|
|
var err = new Error();
|
|
if (!err.stack) {
|
|
// IE10+ special cases: It does have callstack info, but it is only populated if an Error object is thrown,
|
|
// so try that as a special-case.
|
|
try {
|
|
throw new Error();
|
|
} catch(e) {
|
|
err = e;
|
|
}
|
|
if (!err.stack) {
|
|
return '(no stack trace available)';
|
|
}
|
|
}
|
|
return err.stack.toString();
|
|
}
|
|
|
|
function stackTrace() {
|
|
var js = jsStackTrace();
|
|
if (Module['extraStackTrace']) js += '\n' + Module['extraStackTrace']();
|
|
return demangleAll(js);
|
|
}
|
|
|
|
|
|
var _emscripten_get_now;if (ENVIRONMENT_IS_NODE) {
|
|
_emscripten_get_now = function() {
|
|
var t = process['hrtime']();
|
|
return t[0] * 1e3 + t[1] / 1e6;
|
|
};
|
|
} else if (typeof dateNow !== 'undefined') {
|
|
_emscripten_get_now = dateNow;
|
|
} else _emscripten_get_now = function() { return performance.now(); }
|
|
;
|
|
|
|
var _emscripten_get_now_is_monotonic=true;;
|
|
|
|
function setErrNo(value) {
|
|
HEAP32[((___errno_location())>>2)]=value;
|
|
return value;
|
|
}function _clock_gettime(clk_id, tp) {
|
|
// int clock_gettime(clockid_t clk_id, struct timespec *tp);
|
|
var now;
|
|
if (clk_id === 0) {
|
|
now = Date.now();
|
|
} else if ((clk_id === 1 || clk_id === 4) && _emscripten_get_now_is_monotonic) {
|
|
now = _emscripten_get_now();
|
|
} else {
|
|
setErrNo(28);
|
|
return -1;
|
|
}
|
|
HEAP32[((tp)>>2)]=(now/1000)|0; // seconds
|
|
HEAP32[(((tp)+(4))>>2)]=((now % 1000)*1000*1000)|0; // nanoseconds
|
|
return 0;
|
|
}
|
|
|
|
function _emscripten_get_sbrk_ptr() {
|
|
return 97120;
|
|
}
|
|
|
|
function _emscripten_memcpy_big(dest, src, num) {
|
|
HEAPU8.copyWithin(dest, src, src + num);
|
|
}
|
|
|
|
|
|
function _emscripten_get_heap_size() {
|
|
return HEAPU8.length;
|
|
}
|
|
|
|
function emscripten_realloc_buffer(size) {
|
|
try {
|
|
// round size grow request up to wasm page size (fixed 64KB per spec)
|
|
wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16); // .grow() takes a delta compared to the previous size
|
|
updateGlobalBufferAndViews(wasmMemory.buffer);
|
|
return 1 /*success*/;
|
|
} catch(e) {
|
|
}
|
|
}function _emscripten_resize_heap(requestedSize) {
|
|
requestedSize = requestedSize >>> 0;
|
|
var oldSize = _emscripten_get_heap_size();
|
|
// With pthreads, races can happen (another thread might increase the size in between), so return a failure, and let the caller retry.
|
|
|
|
|
|
var PAGE_MULTIPLE = 65536;
|
|
|
|
// Memory resize rules:
|
|
// 1. When resizing, always produce a resized heap that is at least 16MB (to avoid tiny heap sizes receiving lots of repeated resizes at startup)
|
|
// 2. Always increase heap size to at least the requested size, rounded up to next page multiple.
|
|
// 3a. If MEMORY_GROWTH_LINEAR_STEP == -1, excessively resize the heap geometrically: increase the heap size according to
|
|
// MEMORY_GROWTH_GEOMETRIC_STEP factor (default +20%),
|
|
// At most overreserve by MEMORY_GROWTH_GEOMETRIC_CAP bytes (default 96MB).
|
|
// 3b. If MEMORY_GROWTH_LINEAR_STEP != -1, excessively resize the heap linearly: increase the heap size by at least MEMORY_GROWTH_LINEAR_STEP bytes.
|
|
// 4. Max size for the heap is capped at 2048MB-PAGE_MULTIPLE, or by MAXIMUM_MEMORY, or by ASAN limit, depending on which is smallest
|
|
// 5. If we were unable to allocate as much memory, it may be due to over-eager decision to excessively reserve due to (3) above.
|
|
// Hence if an allocation fails, cut down on the amount of excess growth, in an attempt to succeed to perform a smaller allocation.
|
|
|
|
// A limit was set for how much we can grow. We should not exceed that
|
|
// (the wasm binary specifies it, so if we tried, we'd fail anyhow).
|
|
var maxHeapSize = 2147483648;
|
|
if (requestedSize > maxHeapSize) {
|
|
return false;
|
|
}
|
|
|
|
var minHeapSize = 16777216;
|
|
|
|
// Loop through potential heap size increases. If we attempt a too eager reservation that fails, cut down on the
|
|
// attempted size and reserve a smaller bump instead. (max 3 times, chosen somewhat arbitrarily)
|
|
for(var cutDown = 1; cutDown <= 4; cutDown *= 2) {
|
|
var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown); // ensure geometric growth
|
|
// but limit overreserving (default to capping at +96MB overgrowth at most)
|
|
overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296 );
|
|
|
|
|
|
var newSize = Math.min(maxHeapSize, alignUp(Math.max(minHeapSize, requestedSize, overGrownHeapSize), PAGE_MULTIPLE));
|
|
|
|
var replacement = emscripten_realloc_buffer(newSize);
|
|
if (replacement) {
|
|
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
|
|
|
|
var PATH={splitPath:function(filename) {
|
|
var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
|
|
return splitPathRe.exec(filename).slice(1);
|
|
},normalizeArray:function(parts, allowAboveRoot) {
|
|
// if the path tries to go above the root, `up` ends up > 0
|
|
var up = 0;
|
|
for (var i = parts.length - 1; i >= 0; i--) {
|
|
var last = parts[i];
|
|
if (last === '.') {
|
|
parts.splice(i, 1);
|
|
} else if (last === '..') {
|
|
parts.splice(i, 1);
|
|
up++;
|
|
} else if (up) {
|
|
parts.splice(i, 1);
|
|
up--;
|
|
}
|
|
}
|
|
// if the path is allowed to go above the root, restore leading ..s
|
|
if (allowAboveRoot) {
|
|
for (; up; up--) {
|
|
parts.unshift('..');
|
|
}
|
|
}
|
|
return parts;
|
|
},normalize:function(path) {
|
|
var isAbsolute = path.charAt(0) === '/',
|
|
trailingSlash = path.substr(-1) === '/';
|
|
// Normalize the path
|
|
path = PATH.normalizeArray(path.split('/').filter(function(p) {
|
|
return !!p;
|
|
}), !isAbsolute).join('/');
|
|
if (!path && !isAbsolute) {
|
|
path = '.';
|
|
}
|
|
if (path && trailingSlash) {
|
|
path += '/';
|
|
}
|
|
return (isAbsolute ? '/' : '') + path;
|
|
},dirname:function(path) {
|
|
var result = PATH.splitPath(path),
|
|
root = result[0],
|
|
dir = result[1];
|
|
if (!root && !dir) {
|
|
// No dirname whatsoever
|
|
return '.';
|
|
}
|
|
if (dir) {
|
|
// It has a dirname, strip trailing slash
|
|
dir = dir.substr(0, dir.length - 1);
|
|
}
|
|
return root + dir;
|
|
},basename:function(path) {
|
|
// EMSCRIPTEN return '/'' for '/', not an empty string
|
|
if (path === '/') return '/';
|
|
var lastSlash = path.lastIndexOf('/');
|
|
if (lastSlash === -1) return path;
|
|
return path.substr(lastSlash+1);
|
|
},extname:function(path) {
|
|
return PATH.splitPath(path)[3];
|
|
},join:function() {
|
|
var paths = Array.prototype.slice.call(arguments, 0);
|
|
return PATH.normalize(paths.join('/'));
|
|
},join2:function(l, r) {
|
|
return PATH.normalize(l + '/' + r);
|
|
}};var SYSCALLS={mappings:{},buffers:[null,[],[]],printChar:function(stream, curr) {
|
|
var buffer = SYSCALLS.buffers[stream];
|
|
if (curr === 0 || curr === 10) {
|
|
(stream === 1 ? out : err)(UTF8ArrayToString(buffer, 0));
|
|
buffer.length = 0;
|
|
} else {
|
|
buffer.push(curr);
|
|
}
|
|
},varargs:undefined,get:function() {
|
|
SYSCALLS.varargs += 4;
|
|
var ret = HEAP32[(((SYSCALLS.varargs)-(4))>>2)];
|
|
return ret;
|
|
},getStr:function(ptr) {
|
|
var ret = UTF8ToString(ptr);
|
|
return ret;
|
|
},get64:function(low, high) {
|
|
return low;
|
|
}};function _fd_close(fd) {
|
|
return 0;
|
|
}
|
|
|
|
function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {
|
|
}
|
|
|
|
|
|
function flush_NO_FILESYSTEM() {
|
|
// flush anything remaining in the buffers during shutdown
|
|
if (typeof _fflush !== 'undefined') _fflush(0);
|
|
var buffers = SYSCALLS.buffers;
|
|
if (buffers[1].length) SYSCALLS.printChar(1, 10);
|
|
if (buffers[2].length) SYSCALLS.printChar(2, 10);
|
|
}function _fd_write(fd, iov, iovcnt, pnum) {
|
|
// hack to support printf in SYSCALLS_REQUIRE_FILESYSTEM=0
|
|
var num = 0;
|
|
for (var i = 0; i < iovcnt; i++) {
|
|
var ptr = HEAP32[(((iov)+(i*8))>>2)];
|
|
var len = HEAP32[(((iov)+(i*8 + 4))>>2)];
|
|
for (var j = 0; j < len; j++) {
|
|
SYSCALLS.printChar(fd, HEAPU8[ptr+j]);
|
|
}
|
|
num += len;
|
|
}
|
|
HEAP32[((pnum)>>2)]=num
|
|
return 0;
|
|
}
|
|
|
|
function _setTempRet0($i) {
|
|
setTempRet0(($i) | 0);
|
|
}
|
|
var ASSERTIONS = false;
|
|
|
|
|
|
|
|
/** @type {function(string, boolean=, number=)} */
|
|
function intArrayFromString(stringy, dontAddNull, length) {
|
|
var len = length > 0 ? length : lengthBytesUTF8(stringy)+1;
|
|
var u8array = new Array(len);
|
|
var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);
|
|
if (dontAddNull) u8array.length = numBytesWritten;
|
|
return u8array;
|
|
}
|
|
|
|
function intArrayToString(array) {
|
|
var ret = [];
|
|
for (var i = 0; i < array.length; i++) {
|
|
var chr = array[i];
|
|
if (chr > 0xFF) {
|
|
if (ASSERTIONS) {
|
|
assert(false, 'Character code ' + chr + ' (' + String.fromCharCode(chr) + ') at offset ' + i + ' not in 0x00-0xFF.');
|
|
}
|
|
chr &= 0xFF;
|
|
}
|
|
ret.push(String.fromCharCode(chr));
|
|
}
|
|
return ret.join('');
|
|
}
|
|
|
|
|
|
var asmGlobalArg = {};
|
|
var asmLibraryArg = { "clock_gettime": _clock_gettime, "emscripten_get_sbrk_ptr": _emscripten_get_sbrk_ptr, "emscripten_memcpy_big": _emscripten_memcpy_big, "emscripten_resize_heap": _emscripten_resize_heap, "fd_close": _fd_close, "fd_seek": _fd_seek, "fd_write": _fd_write, "memory": wasmMemory, "setTempRet0": _setTempRet0, "table": wasmTable };
|
|
var asm = createWasm();
|
|
/** @type {function(...*):?} */
|
|
var ___wasm_call_ctors = Module["___wasm_call_ctors"] = function() {
|
|
return (___wasm_call_ctors = Module["___wasm_call_ctors"] = Module["asm"]["__wasm_call_ctors"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var _rnnoise_get_size = Module["_rnnoise_get_size"] = function() {
|
|
return (_rnnoise_get_size = Module["_rnnoise_get_size"] = Module["asm"]["rnnoise_get_size"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var _rnnoise_init = Module["_rnnoise_init"] = function() {
|
|
return (_rnnoise_init = Module["_rnnoise_init"] = Module["asm"]["rnnoise_init"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var _rnnoise_create = Module["_rnnoise_create"] = function() {
|
|
return (_rnnoise_create = Module["_rnnoise_create"] = Module["asm"]["rnnoise_create"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var _malloc = Module["_malloc"] = function() {
|
|
return (_malloc = Module["_malloc"] = Module["asm"]["malloc"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var _rnnoise_destroy = Module["_rnnoise_destroy"] = function() {
|
|
return (_rnnoise_destroy = Module["_rnnoise_destroy"] = Module["asm"]["rnnoise_destroy"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var _free = Module["_free"] = function() {
|
|
return (_free = Module["_free"] = Module["asm"]["free"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var _rnnoise_process_frame = Module["_rnnoise_process_frame"] = function() {
|
|
return (_rnnoise_process_frame = Module["_rnnoise_process_frame"] = Module["asm"]["rnnoise_process_frame"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var _denoise_proc = Module["_denoise_proc"] = function() {
|
|
return (_denoise_proc = Module["_denoise_proc"] = Module["asm"]["denoise_proc"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var _rnnDenoise_rawmem = Module["_rnnDenoise_rawmem"] = function() {
|
|
return (_rnnDenoise_rawmem = Module["_rnnDenoise_rawmem"] = Module["asm"]["rnnDenoise_rawmem"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var _rnnDenoise_rawmem_perf = Module["_rnnDenoise_rawmem_perf"] = function() {
|
|
return (_rnnDenoise_rawmem_perf = Module["_rnnDenoise_rawmem_perf"] = Module["asm"]["rnnDenoise_rawmem_perf"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var _get_rnnDenoise_rawmem_time = Module["_get_rnnDenoise_rawmem_time"] = function() {
|
|
return (_get_rnnDenoise_rawmem_time = Module["_get_rnnDenoise_rawmem_time"] = Module["asm"]["get_rnnDenoise_rawmem_time"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var _getResultPointer = Module["_getResultPointer"] = function() {
|
|
return (_getResultPointer = Module["_getResultPointer"] = Module["asm"]["getResultPointer"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var _getResultSize = Module["_getResultSize"] = function() {
|
|
return (_getResultSize = Module["_getResultSize"] = Module["asm"]["getResultSize"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var _getsampleRate = Module["_getsampleRate"] = function() {
|
|
return (_getsampleRate = Module["_getsampleRate"] = Module["asm"]["getsampleRate"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var _getchannels = Module["_getchannels"] = function() {
|
|
return (_getchannels = Module["_getchannels"] = Module["asm"]["getchannels"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var _getsampleCount = Module["_getsampleCount"] = function() {
|
|
return (_getsampleCount = Module["_getsampleCount"] = Module["asm"]["getsampleCount"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var _freeBuffer = Module["_freeBuffer"] = function() {
|
|
return (_freeBuffer = Module["_freeBuffer"] = Module["asm"]["freeBuffer"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var _main = Module["_main"] = function() {
|
|
return (_main = Module["_main"] = Module["asm"]["main"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var ___errno_location = Module["___errno_location"] = function() {
|
|
return (___errno_location = Module["___errno_location"] = Module["asm"]["__errno_location"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var stackSave = Module["stackSave"] = function() {
|
|
return (stackSave = Module["stackSave"] = Module["asm"]["stackSave"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var stackRestore = Module["stackRestore"] = function() {
|
|
return (stackRestore = Module["stackRestore"] = Module["asm"]["stackRestore"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var stackAlloc = Module["stackAlloc"] = function() {
|
|
return (stackAlloc = Module["stackAlloc"] = Module["asm"]["stackAlloc"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var __growWasmMemory = Module["__growWasmMemory"] = function() {
|
|
return (__growWasmMemory = Module["__growWasmMemory"] = Module["asm"]["__growWasmMemory"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var dynCall_ii = Module["dynCall_ii"] = function() {
|
|
return (dynCall_ii = Module["dynCall_ii"] = Module["asm"]["dynCall_ii"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var dynCall_iiii = Module["dynCall_iiii"] = function() {
|
|
return (dynCall_iiii = Module["dynCall_iiii"] = Module["asm"]["dynCall_iiii"]).apply(null, arguments);
|
|
};
|
|
|
|
/** @type {function(...*):?} */
|
|
var dynCall_jiji = Module["dynCall_jiji"] = function() {
|
|
return (dynCall_jiji = Module["dynCall_jiji"] = Module["asm"]["dynCall_jiji"]).apply(null, arguments);
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
// === Auto-generated postamble setup entry stuff ===
|
|
|
|
|
|
|
|
|
|
|
|
Module["cwrap"] = cwrap;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
var calledRun;
|
|
|
|
/**
|
|
* @constructor
|
|
* @this {ExitStatus}
|
|
*/
|
|
function ExitStatus(status) {
|
|
this.name = "ExitStatus";
|
|
this.message = "Program terminated with exit(" + status + ")";
|
|
this.status = status;
|
|
}
|
|
|
|
var calledMain = false;
|
|
|
|
|
|
dependenciesFulfilled = function runCaller() {
|
|
// If run has never been called, and we should call run (INVOKE_RUN is true, and Module.noInitialRun is not false)
|
|
if (!calledRun) run();
|
|
if (!calledRun) dependenciesFulfilled = runCaller; // try this again later, after new deps are fulfilled
|
|
};
|
|
|
|
function callMain(args) {
|
|
|
|
var entryFunction = Module['_main'];
|
|
|
|
|
|
args = args || [];
|
|
|
|
var argc = args.length+1;
|
|
var argv = stackAlloc((argc + 1) * 4);
|
|
HEAP32[argv >> 2] = allocateUTF8OnStack(thisProgram);
|
|
for (var i = 1; i < argc; i++) {
|
|
HEAP32[(argv >> 2) + i] = allocateUTF8OnStack(args[i - 1]);
|
|
}
|
|
HEAP32[(argv >> 2) + argc] = 0;
|
|
|
|
try {
|
|
|
|
|
|
var ret = entryFunction(argc, argv);
|
|
|
|
|
|
// In PROXY_TO_PTHREAD builds, we should never exit the runtime below, as execution is asynchronously handed
|
|
// off to a pthread.
|
|
// if we're not running an evented main loop, it's time to exit
|
|
exit(ret, /* implicit = */ true);
|
|
}
|
|
catch(e) {
|
|
if (e instanceof ExitStatus) {
|
|
// exit() throws this once it's done to make sure execution
|
|
// has been stopped completely
|
|
return;
|
|
} else if (e == 'unwind') {
|
|
// running an evented main loop, don't immediately exit
|
|
noExitRuntime = true;
|
|
return;
|
|
} else {
|
|
var toLog = e;
|
|
if (e && typeof e === 'object' && e.stack) {
|
|
toLog = [e, e.stack];
|
|
}
|
|
err('exception thrown: ' + toLog);
|
|
quit_(1, e);
|
|
}
|
|
} finally {
|
|
calledMain = true;
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
/** @type {function(Array=)} */
|
|
function run(args) {
|
|
args = args || arguments_;
|
|
|
|
if (runDependencies > 0) {
|
|
return;
|
|
}
|
|
|
|
|
|
preRun();
|
|
|
|
if (runDependencies > 0) return; // a preRun added a dependency, run will be called later
|
|
|
|
function doRun() {
|
|
// run may have just been called through dependencies being fulfilled just in this very frame,
|
|
// or while the async setStatus time below was happening
|
|
if (calledRun) return;
|
|
calledRun = true;
|
|
Module['calledRun'] = true;
|
|
|
|
if (ABORT) return;
|
|
|
|
initRuntime();
|
|
|
|
preMain();
|
|
|
|
if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']();
|
|
|
|
if (shouldRunNow) callMain(args);
|
|
|
|
postRun();
|
|
}
|
|
|
|
if (Module['setStatus']) {
|
|
Module['setStatus']('Running...');
|
|
setTimeout(function() {
|
|
setTimeout(function() {
|
|
Module['setStatus']('');
|
|
}, 1);
|
|
doRun();
|
|
}, 1);
|
|
} else
|
|
{
|
|
doRun();
|
|
}
|
|
}
|
|
Module['run'] = run;
|
|
|
|
|
|
/** @param {boolean|number=} implicit */
|
|
function exit(status, implicit) {
|
|
|
|
// if this is just main exit-ing implicitly, and the status is 0, then we
|
|
// don't need to do anything here and can just leave. if the status is
|
|
// non-zero, though, then we need to report it.
|
|
// (we may have warned about this earlier, if a situation justifies doing so)
|
|
if (implicit && noExitRuntime && status === 0) {
|
|
return;
|
|
}
|
|
|
|
if (noExitRuntime) {
|
|
} else {
|
|
|
|
ABORT = true;
|
|
EXITSTATUS = status;
|
|
|
|
exitRuntime();
|
|
|
|
if (Module['onExit']) Module['onExit'](status);
|
|
}
|
|
|
|
quit_(status, new ExitStatus(status));
|
|
}
|
|
|
|
if (Module['preInit']) {
|
|
if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']];
|
|
while (Module['preInit'].length > 0) {
|
|
Module['preInit'].pop()();
|
|
}
|
|
}
|
|
|
|
// shouldRunNow refers to calling main(), not run().
|
|
var shouldRunNow = true;
|
|
|
|
if (Module['noInitialRun']) shouldRunNow = false;
|
|
|
|
|
|
noExitRuntime = true;
|
|
|
|
run();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// {{MODULE_ADDITIONS}}
|
|
|
|
|
|
var BUFF_SIZE = 16384;
|
|
//var startRecordingButton = document.getElementById("startRecordingButton");
|
|
//var stopRecordingButton = document.getElementById("stopRecordingButton");
|
|
//var playButtonR = document.getElementById("playButtonR");
|
|
//var playButtonD = document.getElementById("playButtonD");
|
|
//var fileElem = document.getElementById('file-input');
|
|
//var lRecordingMsg = document.getElementById('RecordingMessage');
|
|
//var lProcessingMode = document.getElementById('ProcessingMode');
|
|
//var lSampleRate = document.getElementById('SampleRate');
|
|
//var lDataSize = document.getElementById('DataSize');
|
|
//var lTimeIntervel = document.getElementById('TimeIntervel');
|
|
//var lKbps = document.getElementById('Kbps');
|
|
//var myBr = document.createElement('br');
|
|
|
|
|
|
var fileContents = null;
|
|
var leftchannel = [];
|
|
var rightchannel = [];
|
|
var denoisedchannel = [];
|
|
|
|
var recorder = null;
|
|
var recordingLength = 0;
|
|
var volume = null;
|
|
var mediaStream = null;
|
|
var sampleRate = 44100;
|
|
var sampleSize = 0;
|
|
var context = null;
|
|
|
|
var blobIn = null;
|
|
var blobOut = null;
|
|
var wasm_processing_time = 0;
|
|
var total_wasm_processing_time = 0;
|
|
|
|
function reset() {
|
|
fileContents = null;
|
|
leftchannel = [];
|
|
rightchannel = [];
|
|
denoisedchannel = [];
|
|
|
|
recorder = null;
|
|
recordingLength = 0;
|
|
volume = null;
|
|
mediaStream = null;
|
|
sampleRate = 44100;
|
|
context = null;
|
|
|
|
blobIn = null;
|
|
blobOut = null;
|
|
}
|
|
|
|
|
|
/*
|
|
fileElem.addEventListener('change', readSingleFile, false);
|
|
function readSingleFile(e) {
|
|
const file = e.target.files[0];
|
|
|
|
if (!file) {
|
|
return;
|
|
}
|
|
reset();
|
|
|
|
var reader = new FileReader();
|
|
reader.onload = function(e) {
|
|
contents = e.target.result;
|
|
fileContents = contents;
|
|
|
|
// Use WebAudio
|
|
var ac = new (AudioContext || webkitAudioContext)();
|
|
ac.decodeAudioData(contents).then(function(buffer) {
|
|
audioBufferFromFile = buffer;
|
|
sampleRate = buffer.sampleRate;
|
|
recordingLength = buffer.length;
|
|
|
|
leftchannel.push(audioBufferFromFile.getChannelData(0));
|
|
sampleSize = audioBufferFromFile.getChannelData(0).length;
|
|
|
|
//Input files are used for perf assessment.
|
|
denoisedchannel.push(wasm_denoise_stream_perf(audioBufferFromFile.getChannelData(0)));
|
|
// playF32Audio(buffer.getChannelData(0), 503784, 48000);
|
|
|
|
|
|
// console.log("Wasm Performance:");
|
|
// console.log();
|
|
// console.log("Processing Audio File: " + file.name);
|
|
// console.log("SampleRate: " + sampleRate);
|
|
// console.log("DataSize (bytes): " + sampleSize);
|
|
// console.log();
|
|
// console.log("Time Intervel (ms): " + wasm_processing_time);
|
|
// console.log("Kbps: " + sampleSize / wasm_processing_time );
|
|
|
|
lProcessingMode.innerHTML = 'Processed Audio File: '+file.name+'<br>';
|
|
lSampleRate.innerHTML = 'Sample Rate: '+sampleRate+'<br>';
|
|
lDataSize.innerHTML = 'Data Size (bytes): '+sampleSize+'<br>';
|
|
lTimeIntervel.innerHTML = 'Wasm Time Elapsed (ms): '+wasm_processing_time+'<br>';
|
|
lKbps.innerHTML = 'Kbps: '+sampleSize/wasm_processing_time+'<br>';
|
|
})
|
|
};
|
|
// reader.readAsBinaryString(file);
|
|
reader.readAsArrayBuffer(file);
|
|
|
|
}
|
|
|
|
|
|
startRecordingButton.addEventListener("click", function () {
|
|
|
|
reset();
|
|
lRecordingMsg.innerHTML='Recording in progress..';
|
|
|
|
// Initialize recorder
|
|
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
|
|
navigator.getUserMedia(
|
|
{
|
|
audio: true
|
|
},
|
|
function (e) {
|
|
console.log("user consent");
|
|
|
|
// creates the audio context
|
|
window.AudioContext = window.AudioContext || window.webkitAudioContext;
|
|
// context = new AudioContext({sampleRate: 48000});
|
|
context = new AudioContext();
|
|
|
|
// creates an audio node from the microphone incoming stream
|
|
mediaStream = context.createMediaStreamSource(e);
|
|
|
|
// onaudioprocess is triggered when bufferSize is full. Acceps power of two upto 16384.
|
|
var bufferSize = BUFF_SIZE;
|
|
|
|
//currently limited to single channel audio. Sterio is doable fairly easily.
|
|
var numberOfInputChannels = 1;
|
|
var numberOfOutputChannels = 1;
|
|
|
|
if (context.createScriptProcessor) {
|
|
recorder = context.createScriptProcessor(bufferSize, numberOfInputChannels, numberOfOutputChannels);
|
|
} else {
|
|
recorder = context.createJavaScriptNode(bufferSize, numberOfInputChannels, numberOfOutputChannels);
|
|
}
|
|
|
|
recorder.onaudioprocess = function (e) {
|
|
leftchannel.push(new Float32Array(e.inputBuffer.getChannelData(0)));
|
|
|
|
var outbuffer = wasm_denoise_stream_perf(e.inputBuffer.getChannelData(0));
|
|
|
|
denoisedchannel.push(outbuffer);
|
|
recordingLength += bufferSize;
|
|
}
|
|
|
|
// Recorder. Needs user permission.
|
|
mediaStream.connect(recorder);
|
|
recorder.connect(context.destination);
|
|
},
|
|
function (e) {
|
|
console.error(e);
|
|
});
|
|
});
|
|
|
|
stopRecordingButton.addEventListener("click", function () {
|
|
recorder.disconnect(context.destination);
|
|
mediaStream.disconnect(recorder);
|
|
lRecordingMsg.innerHTML='';
|
|
|
|
|
|
lProcessingMode.innerHTML = '<b>Processed microphone stream:</b>'+'<br>';
|
|
lSampleRate.innerHTML = '<b>Sample Rate:</b> '+sampleRate+'<br>';
|
|
lDataSize.innerHTML = '<b>Data Size (bytes):</b> '+recordingLength+'<br>';
|
|
lTimeIntervel.innerHTML = '<b>Wasm Time Elapsed (ms):</b> '+total_wasm_processing_time+'<br>';
|
|
lKbps.innerHTML = '<b>Kbps:</b> '+recordingLength/total_wasm_processing_time+'<br>';
|
|
|
|
});
|
|
|
|
playButtonR.addEventListener("click", function () {
|
|
if (leftchannel == null) {
|
|
return;
|
|
}
|
|
|
|
var inAudioF32 = flattenArray(leftchannel, recordingLength);
|
|
playF32Audio(inAudioF32, recordingLength, sampleRate);
|
|
});
|
|
|
|
playButtonD.addEventListener("click", function () {
|
|
if (denoisedchannel == null) {
|
|
return;
|
|
}
|
|
|
|
var outAudioF32 = flattenArray(denoisedchannel, recordingLength);
|
|
playF32Audio(outAudioF32, recordingLength, sampleRate);
|
|
});
|
|
|
|
*/
|
|
|
|
function flattenArray(channelBuffer, recordingLength) {
|
|
var result = new Float32Array(recordingLength);
|
|
var offset = 0;
|
|
for (var i = 0; i < channelBuffer.length; i++) {
|
|
var buffer = channelBuffer[i];
|
|
result.set(buffer, offset);
|
|
offset += buffer.length;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
//Play raw f32Array audio using WebAudio
|
|
function playF32Audio(f32buffer, inSize, inSampleRate) {
|
|
|
|
var audioCtx = new (window.AudioContext || window.webkitAudioContext)({sampleRate: inSampleRate});
|
|
var myArrayBuffer = audioCtx.createBuffer(1, inSize, inSampleRate);
|
|
|
|
myArrayBuffer.copyToChannel(f32buffer, 0,0);
|
|
|
|
var source = audioCtx.createBufferSource();
|
|
source.buffer = myArrayBuffer;
|
|
|
|
source.connect(audioCtx.destination);
|
|
source.start();
|
|
}
|
|
|
|
//cwrap wasm api's for ease of use
|
|
// let wasm_rnnDenoiseMem = Module.cwrap('rnnDenoiseMem', 'number', ['number', 'number']);
|
|
let wasm_getsampleCount = Module.cwrap('getsampleCount', 'number');
|
|
let wasm_getsampleRate = Module.cwrap('getsampleRate', 'number');
|
|
let wasm_getResultSize = Module.cwrap('getResultSize', 'number', []);
|
|
let wasm_getResultPointer = Module.cwrap('getResultPointer', 'number', []);
|
|
let wasm_rnnDenoise_rawmem = Module.cwrap('rnnDenoise_rawmem', 'number', ['number', 'number', 'number', 'number']);
|
|
let wasm_rnnDenoise_rawmem_perf = Module.cwrap('rnnDenoise_rawmem_perf', 'number', ['number', 'number', 'number', 'number']);
|
|
let wasm_get_rnnDenoise_rawmem_time = Module.cwrap('get_rnnDenoise_rawmem_time', 'number', ['']);
|
|
let wasm_freeBuffer = Module.cwrap('freeBuffer', '', []);
|
|
|
|
|
|
////
|
|
// WASM denoise wav files. will use wav library to decode.
|
|
// To enable define USE_WAV_MP3_LIBRARIES in rnnoise demo source and rebuild wasm modules
|
|
////
|
|
|
|
// function wasm_denoise_Arr(audioArrayBuffer)
|
|
// {
|
|
// var u8audiobuffer = new Uint8Array(audioArrayBuffer);
|
|
// let wasm_memp_in = Module._malloc(u8audiobuffer.length);
|
|
// let wasm_mem = new Uint8Array(wasmMemory.buffer, wasm_memp_in, u8audiobuffer.length);
|
|
// wasm_mem.set(u8audiobuffer);
|
|
|
|
// //wasm call
|
|
// let x= wasm_rnnDenoiseMem(wasm_memp_in, u8audiobuffer.length);
|
|
|
|
// recordingLength = getResultSize();
|
|
// sampleRate = getsampleRate();
|
|
|
|
// let bProcessedArr = new Uint8Array(wasmMemory.buffer, x, u8audiobuffer.length);
|
|
|
|
// var fProcessedArr = new Float32Array(getResultSize());
|
|
// fProcessedArr = new Float32Array(wasmMemory.buffer, x, getsampleCount());
|
|
|
|
// //Test
|
|
// // playF32Audio(fProcessedArr, getResultSize(), getsampleRate());
|
|
|
|
// return fProcessedArr;
|
|
// }
|
|
|
|
//WASM Denoise raw audio in f32array
|
|
function wasm_denoise_stream(f32buffer) {
|
|
|
|
let wasm_memp_in = Module._malloc(f32buffer.length * 4 );
|
|
let wasm_mem = new Float32Array(wasmMemory.buffer, wasm_memp_in, f32buffer.length);
|
|
wasm_mem.set(f32buffer);
|
|
|
|
//wasm call
|
|
let x= wasm_rnnDenoise_rawmem(wasm_memp_in, sampleRate, 1, f32buffer.length);
|
|
|
|
let fProcessedArr = new Float32Array(wasmMemory.buffer, x, f32buffer.length);
|
|
|
|
//Test
|
|
// playF32Audio(f32buffer, fProcessedArr.length, sampleRate);
|
|
// playF32Audio(fProcessedArr, fProcessedArr.length, sampleRate);
|
|
|
|
return fProcessedArr;
|
|
}
|
|
|
|
//WASM Denoise raw audio in f32array
|
|
function wasm_denoise_stream_perf(f32buffer) {
|
|
|
|
let wasm_memp_in = Module._malloc(f32buffer.length * 4);
|
|
let wasm_mem = new Float32Array(wasmMemory.buffer, wasm_memp_in, f32buffer.length);
|
|
wasm_mem.set(f32buffer);
|
|
|
|
//wasm call
|
|
let t0 = performance.now();
|
|
let x= wasm_rnnDenoise_rawmem(wasm_memp_in, sampleRate, 1, f32buffer.length);
|
|
let t1 = performance.now();
|
|
wasm_processing_time = t1 - t0;
|
|
//lTimeIntervel.innerHTML='Buffer Processing Time: '+wasm_processing_time;
|
|
total_wasm_processing_time = total_wasm_processing_time + wasm_processing_time;
|
|
|
|
// console.log( 'Buffer Processing Time: ' + wasm_processing_time );
|
|
|
|
|
|
let fProcessedArr = new Float32Array(wasmMemory.buffer, x, f32buffer.length);
|
|
|
|
return fProcessedArr;
|
|
} |