UNPKG

dynamsoft-capture-vision-router

Version:

The Dynamsoft Capture Vision Router module is the cornerstone of the Dynamsoft Capture Vision architecture.

12 lines (11 loc) 37.2 kB
/*! * Dynamsoft JavaScript Library * @product Dynamsoft Capture Vision Router JS Edition * @website http://www.dynamsoft.com * @copyright Copyright 2024, Dynamsoft Corporation * @author Dynamsoft * @version "2.4.33" * @fileoverview Dynamsoft JavaScript Library for Capture Vision * More info on cvr JS: https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/capture-vision-router-module.html */ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("dynamsoft-core")):"function"==typeof define&&define.amd?define(["exports","dynamsoft-core"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).Dynamsoft=e.Dynamsoft||{},e.Dynamsoft.CVR={}),e.Dynamsoft.Core)}(this,(function(e,t){"use strict";function s(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)}function i(e,t,s,i,a){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!a)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!a:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?a.call(e,s):a?a.value=s:t.set(e,s),s}"function"==typeof SuppressedError&&SuppressedError;const a=e=>e&&"object"==typeof e&&"function"==typeof e.then,r=(async()=>{})().constructor;class n extends r{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,a(e)?t=e:"function"==typeof e&&(t=new r(e)),t&&(async()=>{try{const s=await t;e===this._task&&this.resolve(s)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}constructor(e){let t,s;super(((e,i)=>{t=e,s=i})),this._s="pending",this.resolve=e=>{this.isPending&&(a(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",s(e))},this.task=e}}class o{constructor(e){this._cvr=e}async getMaxBufferedItems(){return await new Promise(((e,s)=>{let i=t.getNextTaskID();t.mapTaskCallBack[i]=async t=>{if(t.success)return e(t.count);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,s(e)}},t.worker.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})}))}async setMaxBufferedItems(e){return await new Promise(((s,i)=>{let a=t.getNextTaskID();t.mapTaskCallBack[a]=async e=>{if(e.success)return s();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}},t.worker.postMessage({type:"cvr_setMaxBufferedItems",id:a,instanceID:this._cvr._instanceID,body:{count:e}})}))}async getBufferedCharacterItemSet(){return await new Promise(((e,s)=>{let i=t.getNextTaskID();t.mapTaskCallBack[i]=async t=>{if(t.success)return e(t.itemSet);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,s(e)}},t.worker.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})}))}}var c={onTaskResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onColourImageUnitReceived:!1,onScaledDownColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledUpBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1,onLogicLinesReceived:!1};const l=e=>{for(let t in e._irrRegistryState)e._irrRegistryState[t]=!1;for(let t of e._intermediateResultReceiverSet)if(t.isDce||t.isFilter)e._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let s in t)e._irrRegistryState[s]||(e._irrRegistryState[s]=!!t[s])};class d{constructor(e){this._irrRegistryState=c,this._intermediateResultReceiverSet=new Set,this._cvr=e}async addResultReceiver(e){if("object"!=typeof e)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(e),l(this);let s=-1,i={};if(!e.isDce&&!e.isFilter){if(!e._observedResultUnitTypes||!e._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");s=e._observedResultUnitTypes,e._observedTaskMap.forEach(((e,t)=>{i[t]=e})),e._observedTaskMap.clear()}return await new Promise(((e,a)=>{let r=t.getNextTaskID();t.mapTaskCallBack[r]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,a(e)}},t.worker.postMessage({type:"cvr_setIrrRegistry",id:r,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:s.toString(),observedTaskMap:i}})}))}async removeResultReceiver(e){return this._intermediateResultReceiverSet.delete(e),l(this),await new Promise(((e,s)=>{let i=t.getNextTaskID();t.mapTaskCallBack[i]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,s(e)}},t.worker.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})}))}getOriginalImage(){return this._cvr._dsImage}}const u="undefined"==typeof self,m="function"==typeof importScripts,h=(()=>{if(!m){if(!u&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"}})(),g=e=>{if(null==e&&(e="./"),u||m);else{let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e};var p;t.CoreModule.engineResourcePaths.cvr={version:"2.4.33",path:h,isInternal:!0},t.workerAutoResources.cvr={js:!0,wasm:!0,deps:["license","dip"]},t.mapPackageRegister.cvr={};const f="1.4.21";"string"!=typeof t.CoreModule.engineResourcePaths.std&&t.compareVersion(t.CoreModule.engineResourcePaths.std.version,f)<0&&(t.CoreModule.engineResourcePaths.std={version:f,path:g(h+`../../dynamsoft-capture-vision-std@${f}/dist/`),isInternal:!0});const R="2.4.31";(!t.CoreModule.engineResourcePaths.dip||"string"!=typeof t.CoreModule.engineResourcePaths.dip&&t.compareVersion(t.CoreModule.engineResourcePaths.dip.version,R)<0)&&(t.CoreModule.engineResourcePaths.dip={version:R,path:g(h+`../../dynamsoft-image-processing@${R}/dist/`),isInternal:!0});class _{static getVersion(){return this._version}}_._version=`2.4.33(Worker: ${null===(p=t.innerVersions.cvr)||void 0===p?void 0:p.worker}, Wasm: loading...`;const I={barcodeResultItems:{type:t.EnumCapturedResultItemType.CRIT_BARCODE,reveiver:"onDecodedBarcodesReceived",isNeedFilter:!0},textLineResultItems:{type:t.EnumCapturedResultItemType.CRIT_TEXT_LINE,reveiver:"onRecognizedTextLinesReceived",isNeedFilter:!0},detectedQuadResultItems:{type:t.EnumCapturedResultItemType.CRIT_DETECTED_QUAD,reveiver:"onDetectedQuadsReceived",isNeedFilter:!1},normalizedImageResultItems:{type:t.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE,reveiver:"onNormalizedImagesReceived",isNeedFilter:!1},parsedResultItems:{type:t.EnumCapturedResultItemType.CRIT_PARSED_RESULT,reveiver:"onParsedResultsReceived",isNeedFilter:!1}};var v,T,y,C,w,k,E,D,S,b,O,N,M;function L(e,t){if(e&&e.location){const s=e.location.points;for(let e of s)e.x=e.x/t,e.y=e.y/t;L(e.referencedItem,t)}}function U(e){if(e.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}e.EnumImageSourceState=void 0,(v=e.EnumImageSourceState||(e.EnumImageSourceState={}))[v.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",v[v.ISS_EXHAUSTED=1]="ISS_EXHAUSTED";const P={onTaskResultsReceived:()=>{},isFilter:!0};class B{constructor(){this.maxImageSideLength=["iPhone","Android","HarmonyOS"].includes(t.CoreModule.browserInfo.OS)?2048:4096,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,T.set(this,null),y.set(this,null),C.set(this,null),w.set(this,null),k.set(this,null),E.set(this,new Set),D.set(this,new Set),S.set(this,new Set),b.set(this,0),O.set(this,!1),N.set(this,!1),M.set(this,!1),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return s(this,M,"f")}static async createInstance(){if(!t.mapPackageRegister.license)throw Error("Module `license` is not existed.");await t.mapPackageRegister.license.dynamsoft(),await t.loadWasm(["cvr"]);const e=new B,s=new n;let a=t.getNextTaskID();return t.mapTaskCallBack[a]=async a=>{var r;if(a.success)e._instanceID=a.instanceID,e._currentSettings=JSON.parse(JSON.parse(a.outputSettings).data),_._version=`2.4.33(Worker: ${null===(r=t.innerVersions.cvr)||void 0===r?void 0:r.worker}, Wasm: ${a.version})`,i(e,N,!0,"f"),i(e,w,e.getIntermediateResultManager(),"f"),i(e,N,!1,"f"),s.resolve(e);else{const e=Error(a.message);a.stack&&(e.stack=a.stack),s.reject(e)}},t.worker.postMessage({type:"cvr_createInstance",id:a}),s}async _singleFrameModeCallback(e){for(let t of s(this,E,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:e});const t={bytes:new Uint8Array(e.bytes),width:e.width,height:e.height,stride:e.stride,format:e.format,tag:e.tag};this._templateName||(this._templateName=this._currentSettings.CaptureVisionTemplates[0].Name);const i=await this.capture(t,this._templateName);i.originalImageTag=e.tag;const a={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let e of s(this,E,"f"))if(e.isDce)e.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1});else{for(let t in I){const s=t,r=I[s];e[r.reveiver]&&i[s]&&e[r.reveiver](Object.assign(Object.assign({},a),{[s]:i[s]}))}e.onCapturedResultReceived&&e.onCapturedResultReceived(i)}}setInput(e){if(U(this),e){if(i(this,T,e,"f"),e.isCameraEnhancer){s(this,w,"f")&&(s(this,T,"f")._intermediateResultReceiver.isDce=!0,s(this,w,"f").addResultReceiver(s(this,T,"f")._intermediateResultReceiver));const e=s(this,T,"f").getCameraView();if(e){const t=e._capturedResultReceiver;t.isDce=!0,s(this,E,"f").add(t)}}}else i(this,T,null,"f")}getInput(){return s(this,T,"f")}addImageSourceStateListener(e){if(U(this),"object"!=typeof e)return console.warn("Invalid ISA state listener.");e&&Object.keys(e)&&s(this,D,"f").add(e)}removeImageSourceStateListener(e){return U(this),s(this,D,"f").delete(e)}addResultReceiver(e){if(U(this),"object"!=typeof e)throw new Error("Invalid receiver.");e&&Object.keys(e).length&&(s(this,E,"f").add(e),this._setCrrRegistry())}removeResultReceiver(e){U(this),s(this,E,"f").delete(e),this._setCrrRegistry()}async _setCrrRegistry(){const e={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onParsedResultsReceived:!1};for(let t of s(this,E,"f"))t.isDce||(e.onCapturedResultReceived=!!t.onCapturedResultReceived,e.onDecodedBarcodesReceived=!!t.onDecodedBarcodesReceived,e.onRecognizedTextLinesReceived=!!t.onRecognizedTextLinesReceived,e.onDetectedQuadsReceived=!!t.onDetectedQuadsReceived,e.onNormalizedImagesReceived=!!t.onNormalizedImagesReceived,e.onParsedResultsReceived=!!t.onParsedResultsReceived);const i=new n;let a=t.getNextTaskID();return t.mapTaskCallBack[a]=async e=>{if(e.success)i.resolve();else{let t=new Error(e.message);t.stack=e.stack+"\n"+t.stack,i.reject()}},t.worker.postMessage({type:"cvr_setCrrRegistry",id:a,instanceID:this._instanceID,body:{receiver:JSON.stringify(e)}}),i}async addResultFilter(e){if(U(this),!e||"object"!=typeof e||!Object.keys(e).length)return console.warn("Invalid filter.");s(this,S,"f").add(e),e._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(e){U(this),s(this,S,"f").delete(e),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(s(this,w,"f").removeResultReceiver(P),0===s(this,S,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const e={[t.EnumCapturedResultItemType.CRIT_BARCODE]:!1,[t.EnumCapturedResultItemType.CRIT_TEXT_LINE]:!1,[t.EnumCapturedResultItemType.CRIT_DETECTED_QUAD]:!1,[t.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE]:!1},s={[t.EnumCapturedResultItemType.CRIT_BARCODE]:!1,[t.EnumCapturedResultItemType.CRIT_TEXT_LINE]:!1,[t.EnumCapturedResultItemType.CRIT_DETECTED_QUAD]:!1,[t.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE]:!1};return await A(this,e),void await F(this,s)}for(let e of s(this,S,"f")){if(this._isOpenBarcodeVerify=e.isResultCrossVerificationEnabled(t.EnumCapturedResultItemType.CRIT_BARCODE),this._isOpenLabelVerify=e.isResultCrossVerificationEnabled(t.EnumCapturedResultItemType.CRIT_TEXT_LINE),this._isOpenDetectVerify=e.isResultCrossVerificationEnabled(t.EnumCapturedResultItemType.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=e.isResultCrossVerificationEnabled(t.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE),e.isLatestOverlappingEnabled(t.EnumCapturedResultItemType.CRIT_BARCODE)){[...s(this,w,"f")._intermediateResultReceiverSet.values()].find((e=>e.isFilter))||s(this,w,"f").addResultReceiver(P)}await A(this,e.verificationEnabled),await F(this,e.duplicateFilterEnabled),await x(this,e.duplicateForgetTime)}}async startCapturing(e){var a,r;if(U(this),!this._isPauseScan)return;if(!s(this,T,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");e||(e=B._defaultTemplate);const o=await this.containsTask(e);await t.loadWasm(o);for(let e of s(this,S,"f"))await this.addResultFilter(e);if(o.includes("dlr")&&!(null===(a=t.mapPackageRegister.dlr)||void 0===a?void 0:a.bLoadConfusableCharsData)){const e=t.handleEngineResourcePaths(t.CoreModule.engineResourcePaths);await(null===(r=t.mapPackageRegister.dlr)||void 0===r?void 0:r.loadRecognitionData("ConfusableChars",e.dlr))}if(s(this,T,"f").isCameraEnhancer&&(o.includes("ddn")?s(this,T,"f").setPixelFormat(t.EnumImagePixelFormat.IPF_ABGR_8888):s(this,T,"f").setPixelFormat(t.EnumImagePixelFormat.IPF_GRAYSCALED)),void 0!==s(this,T,"f").singleFrameMode&&"disabled"!==s(this,T,"f").singleFrameMode)return this._templateName=e,void s(this,T,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind);return s(this,T,"f").getColourChannelUsageType()===t.EnumColourChannelUsageType.CCUT_AUTO&&s(this,T,"f").setColourChannelUsageType(o.includes("ddn")?t.EnumColourChannelUsageType.CCUT_FULL_CHANNEL:t.EnumColourChannelUsageType.CCUT_Y_CHANNEL_ONLY),s(this,C,"f")&&s(this,C,"f").isPending?s(this,C,"f"):(i(this,C,new n(((i,a)=>{if(this.disposed)return;let r=t.getNextTaskID();t.mapTaskCallBack[r]=async t=>{if(s(this,C,"f")&&!s(this,C,"f").isFulfilled){if(!t.success){let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,a(e)}this._isPauseScan=!1,this._isOutputOriginalImage=t.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((async()=>{-1!==this._minImageCaptureInterval&&s(this,T,"f").startFetching(),this._loopReadVideo(e),i()}),0)}},t.worker.postMessage({type:"cvr_startCapturing",id:r,instanceID:this._instanceID,body:{templateName:e}})})),"f"),await s(this,C,"f"))}stopCapturing(){U(this),s(this,T,"f")&&(s(this,T,"f").isCameraEnhancer&&void 0!==s(this,T,"f").singleFrameMode&&"disabled"!==s(this,T,"f").singleFrameMode?s(this,T,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(!async function(e){let s=t.getNextTaskID();const i=new n;t.mapTaskCallBack[s]=async e=>{if(e.success)return i.resolve();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i.reject(t)}},t.worker.postMessage({type:"cvr_clearVerifyList",id:s,instanceID:e._instanceID})}(this),s(this,T,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,i(this,C,null,"f"),s(this,T,"f").setColourChannelUsageType(t.EnumColourChannelUsageType.CCUT_AUTO)))}async containsTask(e){return U(this),await new Promise(((s,i)=>{let a=t.getNextTaskID();t.mapTaskCallBack[a]=async e=>{if(e.success)return s(JSON.parse(e.tasks));{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}},t.worker.postMessage({type:"cvr_containsTask",id:a,instanceID:this._instanceID,body:{templateName:e}})}))}async _loopReadVideo(a){if(this.disposed||this._isPauseScan)return;if(i(this,O,!0,"f"),s(this,T,"f").isBufferEmpty())if(s(this,T,"f").hasNextImageToFetch())for(let t of s(this,D,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(e.EnumImageSourceState.ISS_BUFFER_EMPTY);else if(!s(this,T,"f").hasNextImageToFetch())for(let t of s(this,D,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(e.EnumImageSourceState.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||s(this,T,"f").isBufferEmpty())try{s(this,T,"f").isBufferEmpty()&&B._onLog&&B._onLog("buffer is empty so fetch image"),B._onLog&&B._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=s(this,T,"f").fetchImage(),B._onLog&&B._onLog(`DCE: finish fetching a frame: ${Date.now()}`),s(this,T,"f").setImageFetchInterval(this._averageTime)}catch(e){return void this._reRunCurrnetFunc(a)}else if(s(this,T,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=s(this,T,"f").getImage(),this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(a);if(!this._dsImage)return void this._reRunCurrnetFunc(a);for(let e of s(this,E,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:this._dsImage});const r=Date.now();this._captureDsimage(this._dsImage,a).then((async e=>{if(B._onLog&&B._onLog("no js handle time: "+(Date.now()-r)),this._isPauseScan)return void this._reRunCurrnetFunc(a);e.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;const i={originalImageHashId:e.originalImageHashId,originalImageTag:e.originalImageTag,errorCode:e.errorCode,errorString:e.errorString};for(let a of s(this,E,"f"))if(a.isDce){const t=Date.now();if(a.onCapturedResultReceived(e,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify}),B._onLog){const e=Date.now()-t;e>10&&B._onLog(`draw result time: ${e}`)}}else{for(let t in I){const s=t,r=I[s];a[r.reveiver],a[r.reveiver]&&e[s]&&a[r.reveiver](Object.assign(Object.assign({},i),{[s]:e[s].filter((e=>!r.isNeedFilter||!e.isFilter))})),e[s]&&(e[s]=e[s].filter((e=>!r.isNeedFilter||!e.isFilter)))}a.onCapturedResultReceived&&(e.items=e.items.filter((e=>[t.EnumCapturedResultItemType.CRIT_DETECTED_QUAD,t.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE].includes(e.type)||!e.isFilter)),a.onCapturedResultReceived(e))}const n=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-r),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,B._onLog&&(B._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),B._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),B._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),B._onLog(`averageTime: ${this._averageTime}`))),B._onLog){const e=Date.now()-n;e>10&&B._onLog(`fetch image calculate time: ${e}`)}B._onLog&&B._onLog(`time finish decode: ${Date.now()}`),B._onLog&&B._onLog("main time: "+(Date.now()-r)),B._onLog&&B._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(a)}),this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(a)}),Math.max(this._minImageCaptureInterval,0))})).catch((e=>{s(this,T,"f").stopFetching(),e.errorCode&&0===e.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{s(this,T,"f").startFetching(),this._loopReadVideo(a)}),Math.max(this._minImageCaptureInterval,1e3))),"platform error"!==e.message&&setTimeout((()=>{throw e}),0)}))}_reRunCurrnetFunc(e){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(e)}),0)}async capture(e,s){var a,r;U(this),s||(s=B._defaultTemplate);const n=await this.containsTask(s);if(await t.loadWasm(n),n.includes("dlr")&&!(null===(a=t.mapPackageRegister.dlr)||void 0===a?void 0:a.bLoadConfusableCharsData)){const e=t.handleEngineResourcePaths(t.CoreModule.engineResourcePaths);await(null===(r=t.mapPackageRegister.dlr)||void 0===r?void 0:r.loadRecognitionData("ConfusableChars",e.dlr))}let o;if(i(this,O,!1,"f"),t.isDSImageData(e))o=await this._captureDsimage(e,s);else if("string"==typeof e)o="data:image/"==e.substring(0,11)?await this._captureBase64(e,s):await this._captureUrl(e,s);else if(e instanceof Blob)o=await this._captureBlob(e,s);else if(e instanceof HTMLImageElement)o=await this._captureImage(e,s);else if(e instanceof HTMLCanvasElement)o=await this._captureCanvas(e,s);else{if(!(e instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");o=await this._captureVideo(e,s)}return o}async _captureDsimage(e,t){return await this._captureInWorker(e,t)}async _captureUrl(e,s){let i=await t.requestResource(e,"blob");return await this._captureBlob(i,s)}async _captureBase64(e,t){e=e.substring(e.indexOf(",")+1);let s=atob(e),i=s.length,a=new Uint8Array(i);for(;i--;)a[i]=s.charCodeAt(i);return await this._captureBlob(new Blob([a]),t)}async _captureBlob(e,t){let s=null,i=null;if("undefined"!=typeof createImageBitmap)try{s=await createImageBitmap(e)}catch(e){}s||(i=await async function(e){return await new Promise(((t,s)=>{let i=URL.createObjectURL(e),a=new Image;a.src=i,a.onload=()=>{URL.revokeObjectURL(a.dbrObjUrl),t(a)},a.onerror=e=>{s(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let a=await this._captureImage(s||i,t);return s&&s.close(),a}async _captureImage(e,t){let a,r,n=e instanceof HTMLImageElement?e.naturalWidth:e.width,o=e instanceof HTMLImageElement?e.naturalHeight:e.height,c=Math.max(n,o);c>this.maxImageSideLength?(i(this,b,this.maxImageSideLength/c,"f"),a=Math.round(n*s(this,b,"f")),r=Math.round(o*s(this,b,"f"))):(a=n,r=o),s(this,y,"f")||i(this,y,document.createElement("canvas"),"f");const l=s(this,y,"f");l.width===a&&l.height===r||(l.width=a,l.height=r),l.ctx2d||(l.ctx2d=l.getContext("2d",{willReadFrequently:!0}));return l.ctx2d.drawImage(e,0,0,n,o,0,0,a,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl),await this._captureCanvas(l,t)}async _captureCanvas(e,t){if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";if([e.width,e.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const s=e.ctx2d||e.getContext("2d",{willReadFrequently:!0}),i={bytes:Uint8Array.from(s.getImageData(0,0,e.width,e.height).data),width:e.width,height:e.height,stride:4*e.width,format:10};return await this._captureInWorker(i,t)}async _captureVideo(e,t){if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";let a,r,n=e.videoWidth,o=e.videoHeight,c=Math.max(n,o);c>this.maxImageSideLength?(i(this,b,this.maxImageSideLength/c,"f"),a=Math.round(n*s(this,b,"f")),r=Math.round(o*s(this,b,"f"))):(a=n,r=o),s(this,y,"f")||i(this,y,document.createElement("canvas"),"f");const l=s(this,y,"f");l.width===a&&l.height===r||(l.width=a,l.height=r),l.ctx2d||(l.ctx2d=l.getContext("2d",{willReadFrequently:!0}));return l.ctx2d.drawImage(e,0,0,n,o,0,0,a,r),await this._captureCanvas(l,t)}async _captureInWorker(e,a){const{bytes:r,width:o,height:c,stride:l,format:d}=e;let u=t.getNextTaskID();const m=new n;return t.mapTaskCallBack[u]=async a=>{var r,n;if(!a.success){let e=new Error(a.message);return e.stack=a.stack+"\n"+e.stack,m.reject(e)}{const o=Date.now();B._onLog&&(B._onLog(`get result time from worker: ${o}`),B._onLog("worker to main time consume: "+(o-a.workerReturnMsgTime)));try{const o=a.captureResult;if(0!==o.errorCode){let e=new Error(o.errorString);return e.errorCode=o.errorCode,m.reject(e)}e.bytes=a.bytes;for(let i of o.items)0!==s(this,b,"f")&&L(i,s(this,b,"f")),i.type===t.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE?i.imageData=e:i.type===t.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE?null===(r=t.mapPackageRegister.ddn)||void 0===r||r.handleNormalizedImageResultItem(i):i.type===t.EnumCapturedResultItemType.CRIT_PARSED_RESULT&&(null===(n=t.mapPackageRegister.dcp)||void 0===n||n.handleParsedResultItem(i));if(s(this,O,"f"))for(let e of s(this,S,"f"))e.onDecodedBarcodesReceived(o),e.onRecognizedTextLinesReceived(o),e.onDetectedQuadsReceived(o),e.onNormalizedImagesReceived(o);for(let e in I){const t=e,s=o.items.filter((e=>e.type===I[t].type));s.length&&(o[e]=s)}if(!this._isPauseScan||!s(this,O,"f")){const t=o.intermediateResult;if(t){let i=0;for(let a of s(this,w,"f")._intermediateResultReceiverSet){i++;for(let r of t){if("onTaskResultsReceived"===r.info.callbackName){for(let t of r.intermediateResultUnits)t.originalImageTag=e.tag?e.tag:null;a[r.info.callbackName]&&a[r.info.callbackName]({intermediateResultUnits:r.intermediateResultUnits},r.info)}else a[r.info.callbackName]&&a[r.info.callbackName](r.result,r.info);i===s(this,w,"f")._intermediateResultReceiverSet.size&&delete r.info.callbackName}}}}return o&&o.hasOwnProperty("intermediateResult")&&delete o.intermediateResult,i(this,b,0,"f"),m.resolve(o)}catch(e){return m.reject(e)}}},B._onLog&&B._onLog(`send buffer to worker: ${Date.now()}`),t.worker.postMessage({type:"cvr_capture",id:u,instanceID:this._instanceID,body:{bytes:r,width:o,height:c,stride:l,format:d,templateName:a||"",isScanner:s(this,O,"f")}},[r.buffer]),m}async initSettings(e){return U(this),e&&["string","object"].includes(typeof e)?("string"==typeof e?e.trimStart().startsWith("{")||(e=await t.requestResource(e,"text")):"object"==typeof e&&(e=JSON.stringify(e)),await new Promise(((s,i)=>{let a=t.getNextTaskID();t.mapTaskCallBack[a]=async a=>{if(a.success){const r=JSON.parse(a.response);if(0!==r.errorCode){let e=new Error(r.errorString?r.errorString:"Init Settings Failed.");return e.errorCode=r.errorCode,i(e)}const n=JSON.parse(e);this._currentSettings=n;let o=[],c=n.CaptureVisionTemplates;for(let e=0;e<c.length;e++){let t=await this.containsTask(c[e].Name);o=o.concat(t)}return await t.loadWasm([...new Set(o)]),this._isOutputOriginalImage=1===this._currentSettings.CaptureVisionTemplates[0].OutputOriginalImage,B._defaultTemplate=this._currentSettings.CaptureVisionTemplates[0].Name,s(r)}{let e=new Error(a.message);return e.stack=a.stack+"\n"+e.stack,i(e)}},t.worker.postMessage({type:"cvr_initSettings",id:a,instanceID:this._instanceID,body:{settings:e}})}))):console.error("Invalid template.")}async outputSettings(e){return U(this),await new Promise(((s,i)=>{let a=t.getNextTaskID();t.mapTaskCallBack[a]=async e=>{if(e.success){const t=JSON.parse(e.response);if(0!==t.errorCode){let e=new Error(t.errorString);return e.errorCode=t.errorCode,i(e)}return s(JSON.parse(t.data))}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}},t.worker.postMessage({type:"cvr_outputSettings",id:a,instanceID:this._instanceID,body:{templateName:e||"*"}})}))}async outputSettingsToFile(e,t,s){const i=await this.outputSettings(e),a=new Blob([JSON.stringify(i,null,2,(function(e,t){return t instanceof Array?JSON.stringify(t):t}),2)],{type:"application/json"});if(s){const e=document.createElement("a");e.href=URL.createObjectURL(a),t.endsWith(".json")&&(t=t.replace(".json","")),e.download=`${t}.json`,e.onclick=()=>{setTimeout((()=>{URL.revokeObjectURL(e.href)}),500)},e.click()}return a}async getTemplateNames(){return U(this),await new Promise(((e,s)=>{let i=t.getNextTaskID();t.mapTaskCallBack[i]=async t=>{if(t.success){const i=JSON.parse(t.response);if(0!==i.errorCode){let e=new Error(i.errorString);return e.errorCode=i.errorCode,s(e)}return e(JSON.parse(i.data))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,s(e)}},t.worker.postMessage({type:"cvr_getTemplateNames",id:i,instanceID:this._instanceID})}))}async getSimplifiedSettings(e){U(this),e||(e=this._currentSettings.CaptureVisionTemplates[0].Name);const s=await this.containsTask(e);return await t.loadWasm(s),await new Promise(((s,i)=>{let a=t.getNextTaskID();t.mapTaskCallBack[a]=async e=>{if(e.success){const t=JSON.parse(e.response);if(0!==t.errorCode){let e=new Error(t.errorString);return e.errorCode=t.errorCode,i(e)}const a=JSON.parse(t.data,((e,t)=>"barcodeFormatIds"===e?BigInt(t):t));return a.minImageCaptureInterval=this._minImageCaptureInterval,s(a)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}},t.worker.postMessage({type:"cvr_getSimplifiedSettings",id:a,instanceID:this._instanceID,body:{templateName:e}})}))}async updateSettings(e,s){U(this);const i=await this.containsTask(e);return await t.loadWasm(i),await new Promise(((i,a)=>{let r=t.getNextTaskID();t.mapTaskCallBack[r]=async e=>{if(e.success){const t=JSON.parse(e.response);if(s.minImageCaptureInterval&&s.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=s.minImageCaptureInterval),this._isOutputOriginalImage=e.isOutputOriginalImage,0!==t.errorCode){let e=new Error(t.errorString?t.errorString:"Update Settings Failed.");return e.errorCode=t.errorCode,a(e)}return this._currentSettings=await this.outputSettings("*"),i(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},t.worker.postMessage({type:"cvr_updateSettings",id:r,instanceID:this._instanceID,body:{settings:s,templateName:e}})}))}async resetSettings(){return U(this),await new Promise(((e,s)=>{let i=t.getNextTaskID();t.mapTaskCallBack[i]=async t=>{if(t.success){const i=JSON.parse(t.response);if(0!==i.errorCode){let e=new Error(i.errorString?i.errorString:"Reset Settings Failed.");return e.errorCode=i.errorCode,s(e)}return this._currentSettings=await this.outputSettings("*"),e(i)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,s(e)}},t.worker.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})}))}getBufferedItemsManager(){return s(this,k,"f")||i(this,k,new o(this),"f"),s(this,k,"f")}getIntermediateResultManager(){if(U(this),!s(this,N,"f")&&0!==t.CoreModule.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return s(this,w,"f")||i(this,w,new d(this),"f"),s(this,w,"f")}async parseRequiredResources(e){return U(this),await new Promise(((s,i)=>{let a=t.getNextTaskID();t.mapTaskCallBack[a]=async e=>{if(e.success)return s(JSON.parse(e.resources));{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}},t.worker.postMessage({type:"cvr_parseRequiredResources",id:a,instanceID:this._instanceID,body:{templateName:e}})}))}async dispose(){U(this),s(this,C,"f")&&this.stopCapturing(),i(this,T,null,"f"),s(this,E,"f").clear(),s(this,D,"f").clear(),s(this,S,"f").clear(),s(this,w,"f")._intermediateResultReceiverSet.clear(),i(this,M,!0,"f");let e=t.getNextTaskID();t.mapTaskCallBack[e]=e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}},t.worker.postMessage({type:"cvr_dispose",id:e,instanceID:this._instanceID})}_getInternalData(){return{isa:s(this,T,"f"),promiseStartScan:s(this,C,"f"),intermediateResultManager:s(this,w,"f"),bufferdItemsManager:s(this,k,"f"),resultReceiverSet:s(this,E,"f"),isaStateListenerSet:s(this,D,"f"),resultFilterSet:s(this,S,"f"),compressRate:s(this,b,"f"),canvas:s(this,y,"f"),isScanner:s(this,O,"f"),innerUseTag:s(this,N,"f"),isDestroyed:s(this,M,"f")}}async _getWasmFilterState(){return await new Promise(((e,s)=>{let i=t.getNextTaskID();t.mapTaskCallBack[i]=async t=>{if(t.success){const s=JSON.parse(t.response);return e(s)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,s(e)}},t.worker.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})}))}}async function A(e,s){return U(e),await new Promise(((i,a)=>{let r=t.getNextTaskID();t.mapTaskCallBack[r]=async e=>{if(e.success)return i(e.result);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},t.worker.postMessage({type:"cvr_enableResultCrossVerification",id:r,instanceID:e._instanceID,body:{verificationEnabled:s}})}))}async function F(e,s){return U(e),await new Promise(((i,a)=>{let r=t.getNextTaskID();t.mapTaskCallBack[r]=async e=>{if(e.success)return i(e.result);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},t.worker.postMessage({type:"cvr_enableResultDeduplication",id:r,instanceID:e._instanceID,body:{duplicateFilterEnabled:s}})}))}async function x(e,s){return U(e),await new Promise(((i,a)=>{let r=t.getNextTaskID();t.mapTaskCallBack[r]=async e=>{if(e.success)return i(e.result);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},t.worker.postMessage({type:"cvr_setDuplicateForgetTime",id:r,instanceID:e._instanceID,body:{duplicateForgetTime:s}})}))}T=new WeakMap,y=new WeakMap,C=new WeakMap,w=new WeakMap,k=new WeakMap,E=new WeakMap,D=new WeakMap,S=new WeakMap,b=new WeakMap,O=new WeakMap,N=new WeakMap,M=new WeakMap,B._defaultTemplate="Default";var V;e.EnumPresetTemplate=void 0,(V=e.EnumPresetTemplate||(e.EnumPresetTemplate={})).PT_DEFAULT="Default",V.PT_READ_BARCODES="ReadBarcodes_Default",V.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",V.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",V.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",V.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",V.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",V.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",V.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",V.PT_READ_SINGLE_BARCODE="ReadBarcodes_Balanced",V.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",V.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",V.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",V.PT_RECOGNIZE_LETTERS="RecognizeLetters",V.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",V.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",V.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters",e.CaptureVisionRouter=B,e.CaptureVisionRouterModule=_,e.CapturedResultReceiver=class{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}},e.IntermediateResultReceiver=class{constructor(){this._observedResultUnitTypes=t.EnumIntermediateResultUnitType.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:e=>{this._observedResultUnitTypes=e},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:e=>!!(e&this._observedResultUnitTypes),addObservedTask:e=>{this._observedTaskMap.set(e,!0)},removeObservedTask:e=>{this._observedTaskMap.set(e,!1)},isTaskObserved:e=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(e)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledDownColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}}}));