Commit 5f69dffb authored by 耿迪迪's avatar 耿迪迪

视频监控漏提 gengdidi

parent f9f0b73d
This diff is collapsed.
/**
* Created by wangweijie5 on 2016/12/16.
*/
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var __instance = function () {
var instance = void 0;
return function (newInstance) {
if (newInstance) instance = newInstance;
return instance;
};
}();
var AudioRenderer = function () {
function AudioRenderer() {
_classCallCheck(this, AudioRenderer);
if (__instance()) return __instance();
// 确保只有单例
if (AudioRenderer.unique !== undefined) {
return AudioRenderer.unique;
}
AudioRenderer.unique = this;
this.oAudioContext = null;
this.currentVolume = 0.8; // 初始音量
this.bSetVolume = false;
this.gainNode = null;
this.iWndNum = -1; // 窗口号
this.mVolumes = new Map(); // 用于存储所有音量
// Init AudioContext
var AudioContext = window.AudioContext || window.webkitAudioContext;
this.oAudioContext = new AudioContext();
this.writeString = function (view, offset, string) {
for (var i = 0; i < string.length; i++) {
view.setUint8(offset + i, string.charCodeAt(i));
}
};
this.setBufferToDataview = function (output, offset, input) {
for (var i = 0; i < input.length; i++, offset++) {
output.setUint8(offset, input[i]);
}
};
__instance(this);
}
/**
* @synopsis 音频播放
*
* @param dataBuf [IN] 音频缓存
* @param dataLen [IN] 缓存长度
* @param audioInfo [IN] 音频参数
*
* @returns 状态码
*/
_createClass(AudioRenderer, [{
key: 'Play',
value: function Play(dataBuf, dataLen, audioInfo) {
var bufferData = new ArrayBuffer(44 + dataLen);
var viewTalk = new DataView(bufferData);
var sampleRates = audioInfo.samplesPerSec;
var channels = audioInfo.channels;
var bitsPerSample = audioInfo.bitsPerSample;
//console.log("audiorender sampleRates"+sampleRates+"channels:"+channels+"bitsPerSample:"+bitsPerSample);
/* RIFF identifier */
this.writeString(viewTalk, 0, 'RIFF');
/* file length */
viewTalk.setUint32(4, 32 + dataLen * 2, true);
/* RIFF type */
this.writeString(viewTalk, 8, 'WAVE');
/* format chunk identifier */
this.writeString(viewTalk, 12, 'fmt ');
/* format chunk length */
viewTalk.setUint32(16, 16, true);
/* sample format (raw) */
viewTalk.setUint16(20, 1, true);
/* channel count */
viewTalk.setUint16(22, channels, true);
/* sample rate */
viewTalk.setUint32(24, sampleRates, true);
/* byte rate (sample rate * block align) */
viewTalk.setUint32(28, sampleRates * 2, true);
/* block align (channel count * bytes per sample)/8 */
viewTalk.setUint16(32, channels * bitsPerSample / 8, true);
/* bits per sample */
viewTalk.setUint16(34, bitsPerSample, true);
/* data chunk identifier */
this.writeString(viewTalk, 36, 'data');
/* data chunk length */
viewTalk.setUint32(40, dataLen, true);
this.setBufferToDataview(viewTalk, 44, dataBuf);
var self = this;
this.oAudioContext.decodeAudioData(viewTalk.buffer, function (buffer) {
var bufferSource = self.oAudioContext.createBufferSource();
if (bufferSource == null) {
return -1;
}
bufferSource.buffer = buffer;
bufferSource.start(0);
if (self.gainNode == null || self.bSetVolume) {
self.gainNode = self.oAudioContext.createGain();
// self.gainNode.gain.value = self.currentVolume;
// // self.currentVolume = self.gainNode.gain.value;
// self.gainNode.connect(self.oAudioContext.destination);
self.bSetVolume = false;
}
self.gainNode.gain.value = self.currentVolume;
// self.currentVolume = self.gainNode.gain.value;
self.gainNode.connect(self.oAudioContext.destination);
bufferSource.connect(self.gainNode);
}, function (e) {
console.log("decode error");
return -1;
});
return 0;
}
/**
* @synopsis 停止播放
*
* @returns 返回音量
*/
}, {
key: 'Stop',
value: function Stop() {
if (this.gainNode != null) {
this.gainNode.disconnect();
this.gainNode = null;
}
// this.oAudioContext.close();
// AudioRenderer.unique = undefined;
// __instance() = null;
return true;
}
/**
* @synopsis 设置音量
*
* @param iVolume [IN] 音量
*
* @returns 状态码
*/
}, {
key: 'SetVolume',
value: function SetVolume(iVolume) {
this.bSetVolume = true;
this.currentVolume = iVolume;
// 储存当前窗口设置音量值
this.mVolumes.set(this.iWndNum, iVolume);
return true;
}
/**
* @synopsis 设置窗口号
*
* @param iWndNum [IN] 窗口号
*
* @returns 状态码
*/
}, {
key: 'SetWndNum',
value: function SetWndNum(iWndNum) {
this.iWndNum = iWndNum;
// 获取当前窗口设置音量值
var iVolume = this.mVolumes.get(iWndNum);
if (iVolume == undefined) {
iVolume = 0.8; // 默认音量
}
this.currentVolume = iVolume;
return true;
}
/**
* @synopsis 获取音量
*
* @returns 返回音量
*/
}, {
key: 'GetVolume',
value: function GetVolume() {
// 获取当前窗口设置音量值
var iVolume = this.mVolumes.get(this.iWndNum);
if (iVolume == undefined) {
iVolume = 0.8; // 默认音量
}
return iVolume;
}
}]);
return AudioRenderer;
}();
//# sourceMappingURL=AudioRenderer.js.map
\ No newline at end of file
This diff is collapsed.
"use strict";var vertexYUVShader=["#version 300 es","layout(location = 0) in vec4 vertexPos;","layout(location = 1) in vec2 texturePos;","out vec2 textureCoord;","void main()","{","gl_Position = vertexPos;","textureCoord = texturePos;","}"].join("\n");var fragmentYUVShader=["#version 300 es","precision highp float;","in vec2 textureCoord;","out vec4 fragColor;","uniform sampler2D ySampler;","uniform sampler2D uSampler;","uniform sampler2D vSampler;","const mat4 YUV2RGB = mat4","(","1.1643828125, 0, 1.59602734375, -.87078515625,","1.1643828125, -.39176171875, -.81296875, .52959375,","1.1643828125, 2.017234375, 0, -1.081390625,","0, 0, 0, 1",");","void main(void) {","float y = texture(ySampler, textureCoord).r;","float u = texture(uSampler, textureCoord).r;","float v = texture(vSampler, textureCoord).r;","fragColor = vec4(y, u, v, 1) * YUV2RGB;","}"].join("\n");var vertexLineShader=["#version 300 es","layout(location = 0) in vec4 vertexPosLine;","void main()","{","gl_Position = vertexPosLine;","}"].join("\n");var fragmentLineShader=["#version 300 es","precision highp float;","uniform mediump float fRcom;","uniform mediump float fGcom;","uniform mediump float fBcom;","out vec4 fragColor;","void main()","{","fragColor = vec4(fRcom,fGcom,fBcom,1.0);","}"].join("\n");(function(e,r){e.SuperRender2=r()})(this,function(){function e(e){this.canvasElement=document.getElementById(e);this.initContextGL();if(this.contextGL){this.YUVProgram=this.initProgram(vertexYUVShader,fragmentYUVShader);this.LineProgram=this.initProgram(vertexLineShader,fragmentLineShader);this.initBuffers();this.initTextures()}}e.prototype.initContextGL=function(){var e=this.canvasElement;var r=null;try{r=e.getContext("webgl2")}catch(e){r=null}if(!r||typeof r.getParameter!=="function"){r=null}this.contextGL=r;console.log("WebGL2.0")};e.prototype.initProgram=function(e,r){var t=this.contextGL;var a=t.createShader(t.VERTEX_SHADER);t.shaderSource(a,e);t.compileShader(a);if(!t.getShaderParameter(a,t.COMPILE_STATUS)){console.log("Vertex shader failed to compile: "+t.getShaderInfoLog(a))}var i=t.createShader(t.FRAGMENT_SHADER);t.shaderSource(i,r);t.compileShader(i);if(!t.getShaderParameter(i,t.COMPILE_STATUS)){console.log("Fragment shader failed to compile: "+t.getShaderInfoLog(i))}var o=t.createProgram();t.attachShader(o,a);t.attachShader(o,i);t.linkProgram(o);if(!t.getProgramParameter(o,t.LINK_STATUS)){console.log("Program failed to compile: "+t.getProgramInfoLog(o))}t.deleteShader(a);t.deleteShader(i);return o};e.prototype.initBuffers=function(){var e=this.contextGL;var r=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,r);e.bufferData(e.ARRAY_BUFFER,new Float32Array([1,1,-1,1,1,-1,-1,-1]),e.STATIC_DRAW);e.bindBuffer(e.ARRAY_BUFFER,null);var t=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,t);e.bufferData(e.ARRAY_BUFFER,new Float32Array([1,0,0,0,1,1,0,1]),e.DYNAMIC_DRAW);e.bindBuffer(e.ARRAY_BUFFER,null);var a=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,a);e.bufferData(e.ARRAY_BUFFER,16,e.DYNAMIC_DRAW);e.bindBuffer(e.ARRAY_BUFFER,null);this.vertexPosBuffer=r;this.texturePosBuffer=t;this.vertexLineBuffer=a};e.prototype.initTextures=function(){var e=this.contextGL;var r=this.YUVProgram;e.useProgram(r);var t=this.initTexture();var a=e.getUniformLocation(r,"ySampler");e.uniform1i(a,0);this.yTextureRef=t;var i=this.initTexture();var o=e.getUniformLocation(r,"uSampler");e.uniform1i(o,1);this.uTextureRef=i;var n=this.initTexture();var f=e.getUniformLocation(r,"vSampler");e.uniform1i(f,2);this.vTextureRef=n;e.useProgram(null)};e.prototype.initTexture=function(){var e=this.contextGL;var r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r);e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR);e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR);e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE);e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE);e.bindTexture(e.TEXTURE_2D,null);return r};e.prototype.SR_DisplayFrameData=function(e,r,t){if(e<=0||r<=0){return}var a=this.contextGL;if(null==t){a.clearColor(0,0,0,0);a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT);return}var i=this.canvasElement;this.nWindowWidth=i.width;this.nWindowHeight=i.height;var o=this.nWindowWidth;var n=this.nWindowHeight;a.clearColor(.8,.8,1,1);a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT);a.viewport(0,0,o,n);this.updateFrameData(e,r,t);var f=this.YUVProgram;a.useProgram(f);var u=this.vertexPosBuffer;a.bindBuffer(a.ARRAY_BUFFER,u);var s=a.getAttribLocation(f,"vertexPos");a.enableVertexAttribArray(s);a.vertexAttribPointer(s,2,a.FLOAT,false,0,0);a.bindBuffer(a.ARRAY_BUFFER,null);var v=this.texturePosBuffer;a.bindBuffer(a.ARRAY_BUFFER,v);var l=a.getAttribLocation(f,"texturePos");a.enableVertexAttribArray(l);a.vertexAttribPointer(l,2,a.FLOAT,false,0,0);a.bindBuffer(a.ARRAY_BUFFER,null);a.drawArrays(a.TRIANGLE_STRIP,0,4);a.disableVertexAttribArray(s);a.disableVertexAttribArray(l);a.useProgram(null)};e.prototype.updateFrameData=function(e,r,t){var a=this.contextGL;var i=this.yTextureRef;var o=this.uTextureRef;var n=this.vTextureRef;var f=t;var u=e*r;var s=f.subarray(0,u);a.activeTexture(a.TEXTURE0);a.bindTexture(a.TEXTURE_2D,i);a.texImage2D(a.TEXTURE_2D,0,a.LUMINANCE,e,r,0,a.LUMINANCE,a.UNSIGNED_BYTE,s);var v=e/2*r/2;var l=f.subarray(u,u+v);a.activeTexture(a.TEXTURE1);a.bindTexture(a.TEXTURE_2D,o);a.texImage2D(a.TEXTURE_2D,0,a.LUMINANCE,e/2,r/2,0,a.LUMINANCE,a.UNSIGNED_BYTE,l);var R=v;var m=f.subarray(u+v,u+v+R);a.activeTexture(a.TEXTURE2);a.bindTexture(a.TEXTURE_2D,n);a.texImage2D(a.TEXTURE_2D,0,a.LUMINANCE,e/2,r/2,0,a.LUMINANCE,a.UNSIGNED_BYTE,m)};e.prototype.SR_DrawLine=function(e,r,t,a){var i=this.contextGL;var o=this.nWindowWidth;var n=this.nWindowHeight;var f=this.LineProgram;i.useProgram(f);var u=i.getUniformLocation(f,"fRcom");i.uniform1f(u,t.fR);var s=i.getUniformLocation(f,"fGcom");i.uniform1f(s,t.fG);var v=i.getUniformLocation(f,"fBcom");i.uniform1f(v,t.fB);var l=e.fX/o*2-1;var R=-(e.fY/n)*2+1;var m=r.fX/o*2-1;var h=-(r.fY/n)*2+1;var E=this.vertexLineBuffer;i.bindBuffer(i.ARRAY_BUFFER,E);i.bufferSubData(i.ARRAY_BUFFER,0,new Float32Array([l,R,m,h]));var T=i.getAttribLocation(f,"vertexPosLine");i.enableVertexAttribArray(T);i.vertexAttribPointer(T,2,i.FLOAT,false,0,0);i.bindBuffer(i.ARRAY_BUFFER,null);i.drawArrays(i.LINES,0,2);i.disableVertexAttribArray(T);i.useProgram(null)};e.prototype.SR_SetDisplayRect=function(e){var r=this.contextGL;var t=this.nWindowWidth;var a=this.nWindowHeight;var i=null;if(e&&t>0&&a>0){var o=e.left/t;var n=e.top/a;var f=e.right/t;var u=e.bottom/a;i=new Float32Array([f,n,o,n,f,u,o,u])}else{i=new Float32Array([1,0,0,0,1,1,0,1])}var s=this.texturePosBuffer;r.bindBuffer(r.ARRAY_BUFFER,s);r.bufferSubData(r.ARRAY_BUFFER,0,i);r.bindBuffer(r.ARRAY_BUFFER,null)};e.prototype.SR_Destroy=function(){var e=this.contextGL;var r=this.YUVProgram;e.deleteProgram(r);var t=this.LineProgram;e.deleteProgram(t);var a=this.vertexPosBuffer;var i=this.texturePosBuffer;var o=this.vertexLineBuffer;e.deleteBuffer(a);e.deleteBuffer(i);e.deleteBuffer(o);var n=this.yTextureRef;var f=this.uTextureRef;var u=this.vTextureRef;e.deleteTexture(n);e.deleteTexture(f);e.deleteTexture(u)};return e});
\ No newline at end of file
This diff is collapsed.
/**
* @license
* Copyright 2015 The Emscripten Authors
* SPDX-License-Identifier: MIT
*/
// Pthread Web Worker startup routine:
// This is the entry point file that is loaded first by each Web Worker
// that executes pthreads on the Emscripten application.
// Thread-local:
var initializedJS = false; // Guard variable for one-time init of the JS state (currently only embind types registration)
var Module = {};
function assert(condition, text) {
if (!condition) abort('Assertion failed: ' + text);
}
function threadPrintErr() {
var text = Array.prototype.slice.call(arguments).join(' ');
console.error(text);
}
function threadAlert() {
var text = Array.prototype.slice.call(arguments).join(' ');
postMessage({cmd: 'alert', text: text, threadId: Module['_pthread_self']()});
}
// We don't need out() for now, but may need to add it if we want to use it
// here. Or, if this code all moves into the main JS, that problem will go
// away. (For now, adding it here increases code size for no benefit.)
var out = function() {
throw 'out() is not defined in worker.js.';
}
var err = threadPrintErr;
this.alert = threadAlert;
Module['instantiateWasm'] = function(info, receiveInstance) {
// Instantiate from the module posted from the main thread.
// We can just use sync instantiation in the worker.
var instance = new WebAssembly.Instance(Module['wasmModule'], info);
// 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, we can remove this if/else.
receiveInstance(instance);
// We don't need the module anymore; new threads will be spawned from the main thread.
Module['wasmModule'] = null;
return instance.exports;
};
function moduleLoaded() {
}
this.onmessage = function(e) {
try {
if (e.data.cmd === 'load') { // Preload command that is called once per worker to parse and load the Emscripten code.
// Module and memory were sent from main thread
Module['wasmModule'] = e.data.wasmModule;
Module['wasmMemory'] = e.data.wasmMemory;
Module['buffer'] = Module['wasmMemory'].buffer;
Module['ENVIRONMENT_IS_PTHREAD'] = true;
if (typeof e.data.urlOrBlob === 'string') {
importScripts(e.data.urlOrBlob);
} else {
var objectUrl = URL.createObjectURL(e.data.urlOrBlob);
importScripts(objectUrl);
URL.revokeObjectURL(objectUrl);
}
JSPlayerModule(Module).then(function (instance) {
Module = instance;
moduleLoaded();
});
} else if (e.data.cmd === 'objectTransfer') {
Module['PThread'].receiveObjectTransfer(e.data);
} else if (e.data.cmd === 'run') {
// This worker was idle, and now should start executing its pthread entry
// point.
// performance.now() is specced to return a wallclock time in msecs since
// that Web Worker/main thread launched. However for pthreads this can
// cause subtle problems in emscripten_get_now() as this essentially
// would measure time from pthread_create(), meaning that the clocks
// between each threads would be wildly out of sync. Therefore sync all
// pthreads to the clock on the main browser thread, so that different
// threads see a somewhat coherent clock across each of them
// (+/- 0.1msecs in testing).
Module['__performance_now_clock_drift'] = performance.now() - e.data.time;
// Pass the thread address inside the asm.js scope to store it for fast access that avoids the need for a FFI out.
Module['__emscripten_thread_init'](e.data.threadInfoStruct, /*isMainBrowserThread=*/0, /*isMainRuntimeThread=*/0);
// Establish the stack frame for this thread in global scope
// The stack grows downwards
var max = e.data.stackBase;
var top = e.data.stackBase + e.data.stackSize;
assert(e.data.threadInfoStruct);
assert(top != 0);
assert(max != 0);
assert(top > max);
// Also call inside JS module to set up the stack frame for this pthread in JS module scope
Module['establishStackSpace'](top, max);
Module['PThread'].receiveObjectTransfer(e.data);
Module['PThread'].threadInit();
// Embind must initialize itself on all threads, as it generates support JS.
// We only do this once per worker since they get reused
if (!initializedJS) {
Module['___embind_register_native_and_builtin_types']();
initializedJS = true;
}
try {
// pthread entry points are always of signature 'void *ThreadMain(void *arg)'
// Native codebases sometimes spawn threads with other thread entry point signatures,
// such as void ThreadMain(void *arg), void *ThreadMain(), or void ThreadMain().
// That is not acceptable per C/C++ specification, but x86 compiler ABI extensions
// enable that to work. If you find the following line to crash, either change the signature
// to "proper" void *ThreadMain(void *arg) form, or try linking with the Emscripten linker
// flag -s EMULATE_FUNCTION_POINTER_CASTS=1 to add in emulation for this x86 ABI extension.
var result = Module['invokeEntryPoint'](e.data.start_routine, e.data.arg);
Module['checkStackCookie']();
if (Module['keepRuntimeAlive']()) {
Module['PThread'].setExitStatus(result);
} else {
Module['PThread'].threadExit(result);
}
} catch(ex) {
if (ex === 'Canceled!') {
Module['PThread'].threadCancel();
} else if (ex != 'unwind') {
// FIXME(sbc): Figure out if this is still needed or useful. Its not
// clear to me how this check could ever fail. In order to get into
// this try/catch block at all we have already called bunch of
// functions on `Module`.. why is this one special?
if (typeof(Module['_emscripten_futex_wake']) !== "function") {
err("Thread Initialisation failed.");
throw ex;
}
// ExitStatus not present in MINIMAL_RUNTIME
if (ex instanceof Module['ExitStatus']) {
if (Module['keepRuntimeAlive']()) {
err('Pthread 0x' + Module['_pthread_self']().toString(16) + ' called exit(), staying alive due to noExitRuntime.');
} else {
err('Pthread 0x' + Module['_pthread_self']().toString(16) + ' called exit(), calling threadExit.');
Module['PThread'].threadExit(ex.status);
}
}
else
{
Module['PThread'].threadExit(-2);
throw ex;
}
} else {
// else e == 'unwind', and we should fall through here and keep the pthread alive for asynchronous events.
err('Pthread 0x' + Module['_pthread_self']().toString(16) + ' completed its pthread main entry point with an unwind, keeping the pthread worker alive for asynchronous operation.');
}
}
} else if (e.data.cmd === 'cancel') { // Main thread is asking for a pthread_cancel() on this thread.
if (Module['_pthread_self']()) {
Module['PThread'].threadCancel();
}
} else if (e.data.target === 'setimmediate') {
// no-op
} else if (e.data.cmd === 'processThreadQueue') {
if (Module['_pthread_self']()) { // If this thread is actually running?
Module['_emscripten_current_thread_process_queued_calls']();
}
} else {
err('worker.js received unknown command ' + e.data.cmd);
err(e.data);
}
} catch(ex) {
err('worker.js onmessage() captured an uncaught exception: ' + ex);
if (ex && ex.stack) err(ex.stack);
throw ex;
}
};
This diff is collapsed.
This diff is collapsed.
/**
* @license
* Copyright 2015 The Emscripten Authors
* SPDX-License-Identifier: MIT
*/
// Pthread Web Worker startup routine:
// This is the entry point file that is loaded first by each Web Worker
// that executes pthreads on the Emscripten application.
// Thread-local:
var initializedJS = false; // Guard variable for one-time init of the JS state (currently only embind types registration)
var Module = {};
function assert(condition, text) {
if (!condition) abort('Assertion failed: ' + text);
}
function threadPrintErr() {
var text = Array.prototype.slice.call(arguments).join(' ');
console.error(text);
}
function threadAlert() {
var text = Array.prototype.slice.call(arguments).join(' ');
postMessage({cmd: 'alert', text: text, threadId: Module['_pthread_self']()});
}
// We don't need out() for now, but may need to add it if we want to use it
// here. Or, if this code all moves into the main JS, that problem will go
// away. (For now, adding it here increases code size for no benefit.)
var out = function() {
throw 'out() is not defined in worker.js.';
}
var err = threadPrintErr;
this.alert = threadAlert;
Module['instantiateWasm'] = function(info, receiveInstance) {
// Instantiate from the module posted from the main thread.
// We can just use sync instantiation in the worker.
var instance = new WebAssembly.Instance(Module['wasmModule'], info);
// 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, we can remove this if/else.
receiveInstance(instance);
// We don't need the module anymore; new threads will be spawned from the main thread.
Module['wasmModule'] = null;
return instance.exports;
};
function moduleLoaded() {
}
this.onmessage = function(e) {
try {
if (e.data.cmd === 'load') { // Preload command that is called once per worker to parse and load the Emscripten code.
// Module and memory were sent from main thread
Module['wasmModule'] = e.data.wasmModule;
Module['wasmMemory'] = e.data.wasmMemory;
Module['buffer'] = Module['wasmMemory'].buffer;
Module['ENVIRONMENT_IS_PTHREAD'] = true;
if (typeof e.data.urlOrBlob === 'string') {
importScripts(e.data.urlOrBlob);
} else {
var objectUrl = URL.createObjectURL(e.data.urlOrBlob);
importScripts(objectUrl);
URL.revokeObjectURL(objectUrl);
}
JSAudioInterComModule(Module).then(function (instance) {
Module = instance;
moduleLoaded();
});
} else if (e.data.cmd === 'objectTransfer') {
Module['PThread'].receiveObjectTransfer(e.data);
} else if (e.data.cmd === 'run') {
// This worker was idle, and now should start executing its pthread entry
// point.
// performance.now() is specced to return a wallclock time in msecs since
// that Web Worker/main thread launched. However for pthreads this can
// cause subtle problems in emscripten_get_now() as this essentially
// would measure time from pthread_create(), meaning that the clocks
// between each threads would be wildly out of sync. Therefore sync all
// pthreads to the clock on the main browser thread, so that different
// threads see a somewhat coherent clock across each of them
// (+/- 0.1msecs in testing).
Module['__performance_now_clock_drift'] = performance.now() - e.data.time;
// Pass the thread address inside the asm.js scope to store it for fast access that avoids the need for a FFI out.
Module['__emscripten_thread_init'](e.data.threadInfoStruct, /*isMainBrowserThread=*/0, /*isMainRuntimeThread=*/0);
// Establish the stack frame for this thread in global scope
// The stack grows downwards
var max = e.data.stackBase;
var top = e.data.stackBase + e.data.stackSize;
assert(e.data.threadInfoStruct);
assert(top != 0);
assert(max != 0);
assert(top > max);
// Also call inside JS module to set up the stack frame for this pthread in JS module scope
Module['establishStackSpace'](top, max);
Module['PThread'].receiveObjectTransfer(e.data);
Module['PThread'].threadInit();
// Embind must initialize itself on all threads, as it generates support JS.
// We only do this once per worker since they get reused
if (!initializedJS) {
Module['___embind_register_native_and_builtin_types']();
initializedJS = true;
}
try {
// pthread entry points are always of signature 'void *ThreadMain(void *arg)'
// Native codebases sometimes spawn threads with other thread entry point signatures,
// such as void ThreadMain(void *arg), void *ThreadMain(), or void ThreadMain().
// That is not acceptable per C/C++ specification, but x86 compiler ABI extensions
// enable that to work. If you find the following line to crash, either change the signature
// to "proper" void *ThreadMain(void *arg) form, or try linking with the Emscripten linker
// flag -s EMULATE_FUNCTION_POINTER_CASTS=1 to add in emulation for this x86 ABI extension.
var result = Module['invokeEntryPoint'](e.data.start_routine, e.data.arg);
Module['checkStackCookie']();
if (Module['keepRuntimeAlive']()) {
Module['PThread'].setExitStatus(result);
} else {
Module['PThread'].threadExit(result);
}
} catch(ex) {
if (ex === 'Canceled!') {
Module['PThread'].threadCancel();
} else if (ex != 'unwind') {
// FIXME(sbc): Figure out if this is still needed or useful. Its not
// clear to me how this check could ever fail. In order to get into
// this try/catch block at all we have already called bunch of
// functions on `Module`.. why is this one special?
if (typeof(Module['_emscripten_futex_wake']) !== "function") {
err("Thread Initialisation failed.");
throw ex;
}
// ExitStatus not present in MINIMAL_RUNTIME
if (ex instanceof Module['ExitStatus']) {
if (Module['keepRuntimeAlive']()) {
err('Pthread 0x' + Module['_pthread_self']().toString(16) + ' called exit(), staying alive due to noExitRuntime.');
} else {
err('Pthread 0x' + Module['_pthread_self']().toString(16) + ' called exit(), calling threadExit.');
Module['PThread'].threadExit(ex.status);
}
}
else
{
Module['PThread'].threadExit(-2);
throw ex;
}
} else {
// else e == 'unwind', and we should fall through here and keep the pthread alive for asynchronous events.
err('Pthread 0x' + Module['_pthread_self']().toString(16) + ' completed its pthread main entry point with an unwind, keeping the pthread worker alive for asynchronous operation.');
}
}
} else if (e.data.cmd === 'cancel') { // Main thread is asking for a pthread_cancel() on this thread.
if (Module['_pthread_self']()) {
Module['PThread'].threadCancel();
}
} else if (e.data.target === 'setimmediate') {
// no-op
} else if (e.data.cmd === 'processThreadQueue') {
if (Module['_pthread_self']()) { // If this thread is actually running?
Module['_emscripten_current_thread_process_queued_calls']();
}
} else {
err('worker.js received unknown command ' + e.data.cmd);
err(e.data);
}
} catch(ex) {
err('worker.js onmessage() captured an uncaught exception: ' + ex);
if (ex && ex.stack) err(ex.stack);
throw ex;
}
};
// Node.js support
if (typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node === 'string') {
// Create as web-worker-like an environment as we can.
self = {
location: {
href: __filename
}
};
var onmessage = this.onmessage;
var nodeWorkerThreads = require('worker_threads');
global.Worker = nodeWorkerThreads.Worker;
var parentPort = nodeWorkerThreads.parentPort;
parentPort.on('message', function(data) {
onmessage({ data: data });
});
var nodeFS = require('fs');
var nodeRead = function(filename) {
return nodeFS.readFileSync(filename, 'utf8');
};
function globalEval(x) {
global.require = require;
global.Module = Module;
eval.call(null, x);
}
importScripts = function(f) {
globalEval(nodeRead(f));
};
postMessage = function(msg) {
parentPort.postMessage(msg);
};
if (typeof performance === 'undefined') {
performance = {
now: function() {
return Date.now();
}
};
}
}
importScripts('libSystemTransform.js');
const RECORDRTP = 0; //录制一份未经过转封装的码流原始数据,用于定位问题
let dataType = 1;
// 转封装库回调函数
self.STCallBack = function (fileIndex,indexLen, data, dataLen)
{
//stFrameInfo的类型见DETAIL_FRAME_INFO
let stFrameInfo = Module._GetDetialFrameInfo();
let nIsMp4Index = stFrameInfo.nIsMp4Index;
//console.log("FrameType is " , stFrameInfo);
//console.log("nIsMp4Index is " + nIsMp4Index);
//debugger
var pData = null;
pData = new Uint8Array(dataLen);
pData.set(Module.HEAPU8.subarray(data, data + dataLen));
if (dataType === 1) {
if (pData[0] == 0x49 && pData[1] == 0x4d && pData[2] == 0x4b && pData[3] == 0x48) {//码流头丢掉
return;
}
postMessage({type: "outputData", buf: pData, dType: 1});
dataType = 2;
} else {
if (nIsMp4Index) {
postMessage({type: "outputData", buf: pData, dType: 6}); //6:索引类型
} else {
postMessage({type: "outputData", buf: pData, dType: 2}); //2:码流
}
}
//stFrameInfo的类型见DETAIL_FRAME_INFO
//let stFrameInfo = Module._GetDetialFrameInfo();
//let stFrameType = stFrameInfo.nFrameType;
//let nFrameNum = stFrameInfo.nFrameNum;
//let nTimeStamp = stFrameInfo.nTimeStamp;
//let nIsMp4Index = stFrameInfo.nIsMp4Index;
//console.log("FrameType is " + stFrameType);
//console.log("nIsMp4Index is " + nIsMp4Index);
}
// self.Module = { memoryInitializerRequest: loadMemInitFile(), TOTAL_MEMORY: 128*1024*1024 };
// importScripts('SystemTransform.js');
self.Module['onRuntimeInitialized'] = function (){
postMessage({type: "loaded"});
}
onmessage = function (e) {
var data = e.data;
if ("create" === data.type) {
if (RECORDRTP) {
postMessage({type: "created"});
postMessage({type: "outputData", buf: data.buf, dType: 1});
} else {
var iHeadLen = data.len;
var pHead = Module._malloc(iHeadLen);
self.writeArrayToMemory(new Uint8Array(data.buf), pHead);
var iTransType = data.packType;//目标格式
var iRet = Module._CreatHandle(pHead, iTransType, 4096);
if (iRet != 0) {
console.log("_CreatHandle failed!" + iRet);
} else {
iRet = Module._SysTransRegisterDataCallBack();
if(iRet != 0)
{
console.log("_SysTransRegisterDataCallBack Failed:" + iRet);
}
iRet = Module._SysTransStart(null, null);
if(iRet != 0)
{
console.log("_SysTransStart Failed:" + iRet);
}
postMessage({type: "created"});
}
}
} else if ("inputData" === data.type) {
if (RECORDRTP) {
var aFileData = new Uint8Array(data.buf); // 拷贝一份
var iBufferLen = aFileData.length;
var szBufferLen = iBufferLen.toString(16);
if (szBufferLen.length === 1) {
szBufferLen = "000" + szBufferLen;
} else if (szBufferLen.length === 2) {
szBufferLen = "00" + szBufferLen;
} else if (szBufferLen.length === 3) {
szBufferLen = "0" + szBufferLen;
}
var aData = [0, 0, parseInt(szBufferLen.substring(0, 2), 16), parseInt(szBufferLen.substring(2, 4), 16)];
for(var iIndex = 0, iDataLength = aFileData.length; iIndex < iDataLength; iIndex++) {
aData[iIndex + 4] = aFileData[iIndex]
}
var dataUint8 = new Uint8Array(aData);
postMessage({type: "outputData", buf: dataUint8.buffer, dType: 2});
} else {
let pInputDataBuf = Module._malloc(data.len);
var idataLen = data.len;
self.writeArrayToMemory(new Uint8Array(data.buf), pInputDataBuf);
// 输入数据,每次最多2m
let pp = Module._SysTransInputData(0, pInputDataBuf, idataLen);
if(pp != 0) {
//console.log("InputData Failed:" + pp);
}
Module._free(pInputDataBuf);
}
} else if ("release" === data.type) {
var iRet = Module._SysTransStop();
if (iRet != 0) {
console.log("_SysTransStop Failed:", iRet);
}
Module._SysTransRelease();
if (iRet != 0) {
console.log("_SysTransRelease Failed:", iRet);
}
close();
}
};
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment