@scandit/web-datacapture-core 7.6.1 → 7.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/electron/common.cjs +1 -1
- package/build/electron/constants.cjs +1 -1
- package/build/electron/main.cjs +1 -1
- package/build/electron/preload.cjs +1 -1
- package/build/js/{Camera-C_4xOv5n.d.ts → Camera-C1Hz9V3G.d.ts} +4 -1
- package/build/js/Camera.d.ts +1 -1
- package/build/js/Camera.js +1 -1
- package/build/js/CameraAccess.d.ts +1 -1
- package/build/js/CameraRelated.d.ts +1 -1
- package/build/js/DataCaptureContext.d.ts +1 -1
- package/build/js/DataCaptureContext.js +1 -1
- package/build/js/DataCaptureContextRelated.d.ts +1 -1
- package/build/js/DataCaptureVersion.js +1 -1
- package/build/js/DataCaptureView.d.ts +1 -1
- package/build/js/DataCaptureView.js +1 -1
- package/build/js/Defaults.d.ts +1 -1
- package/build/js/FrameData.d.ts +1 -1
- package/build/js/ImageFrameSource.d.ts +1 -1
- package/build/js/NotificationPresenter/index.d.ts +1 -1
- package/build/js/NotificationPresenter/private/ConcreteNotificationPresenter.d.ts +1 -1
- package/build/js/NotificationPresenter/private/presets.d.ts +1 -1
- package/build/js/ScanditIconBuilder.js +1 -1
- package/build/js/SingleImageUploader.d.ts +1 -1
- package/build/js/chunks/{chunk-L3BBOGIY.js → chunk-D767RWTQ.js} +1 -1
- package/build/js/chunks/chunk-DMHDEPDF.js +1 -0
- package/build/js/chunks/{chunk-Q5DQ3FTE.js → chunk-GK6JPJTE.js} +1 -1
- package/build/js/chunks/{chunk-4XTOUXDD.js → chunk-GPR2J64V.js} +1 -1
- package/build/js/chunks/chunk-L7LE453T.js +35 -0
- package/build/js/chunks/{chunk-GYQMVT7L.js → chunk-MGKDPTWE.js} +1 -1
- package/build/js/chunks/chunk-NQF3GUK2.js +1 -0
- package/build/js/chunks/{chunk-BPNTTDTU.js → chunk-OMJQ7GOF.js} +1 -1
- package/build/js/chunks/{chunk-ULRY4SXF.js → chunk-PAPLDTB7.js} +1 -1
- package/build/js/chunks/{chunk-M6SPJT67.js → chunk-RT3XSTKA.js} +1 -1
- package/build/js/chunks/chunk-SENWWWXU.js +1 -0
- package/build/js/chunks/{chunk-KK47T3R2.js → chunk-ZZEQCILC.js} +1 -1
- package/build/js/index.d.ts +2 -2
- package/build/js/index.js +1 -1
- package/build/js/private/CameraAccess.d.ts +1 -1
- package/build/js/private/CameraManager.d.ts +1 -1
- package/build/js/private/CameraManager.js +1 -1
- package/build/js/private/CanvasDrawerWithMetrics.d.ts +1 -1
- package/build/js/private/CoreModuleLicenseTextProvider.d.ts +1 -1
- package/build/js/private/DataCaptureContextRelated.d.ts +1 -1
- package/build/js/private/FrameReaders/FrameReader.d.ts +1 -1
- package/build/js/private/FrameReaders/FrameReader.js +1 -1
- package/build/js/private/FrameReaders/FrameReaderAbstract.d.ts +1 -1
- package/build/js/private/FrameReaders/FrameReaderAbstract.js +1 -1
- package/build/js/private/FrameReaders/GrayScaleFrameReader.d.ts +3 -2
- package/build/js/private/FrameReaders/GrayScaleFrameReader.js +1 -1
- package/build/js/private/FrameReaders/index.d.ts +1 -1
- package/build/js/private/FrameReaders/index.js +1 -1
- package/build/js/private/NormalizedConfigureOptions.d.ts +1 -1
- package/build/js/private/ViewControls+related.js +1 -1
- package/build/js/private/ViewControls_related.d.ts +1 -1
- package/build/js/private/ViewsRegistry.d.ts +1 -1
- package/build/js/private/ui/atoms/Toast.d.ts +1 -1
- package/build/js/private/ui/molecules/HintPresenter.d.ts +1 -1
- package/build/js/private/utils/replaceImagesInViewUtils.d.ts +1 -1
- package/build/js/sdk.d.ts +1 -1
- package/build/js/worker/WorkerMain.d.ts +1 -1
- package/build/js/worker/WorkerMain.js +1 -1
- package/build/js/worker/coreCapture.inlineWorker.d.ts +1 -1
- package/build/js/worker/coreCapture.inlineWorker.js +1 -1
- package/build/js/worker/dataCaptureEngine.d.ts +1 -1
- package/build/js/worker/dataCaptureEngine.js +1 -1
- package/build/js/worker/dataCaptureLoader.d.ts +1 -1
- package/build/js/worker/dataCaptureWorkerRelated.d.ts +1 -1
- package/build/js/worker/index.d.ts +1 -1
- package/build/js/worker/index.js +1 -1
- package/package.json +1 -1
- package/build/js/chunks/chunk-7B2VPGLP.js +0 -35
- package/build/js/chunks/chunk-ECRBANIT.js +0 -1
- package/build/js/chunks/chunk-MW5PTAU7.js +0 -1
- package/build/js/chunks/chunk-VBNI76IP.js +0 -1
- /package/build/js/chunks/{chunk-6TG3MN7M.js → chunk-W2FVIH2I.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
var e,t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,p=Object.prototype.hasOwnProperty;module.exports=(e={},((e,n,
|
|
1
|
+
"use strict";var e,t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,p=Object.prototype.hasOwnProperty;module.exports=(e={},((e,c,n,l)=>{if(c&&"object"==typeof c||"function"==typeof c)for(let u of o(c))p.call(e,u)||u===n||t(e,u,{get:()=>c[u],enumerable:!(l=r(c,u))||l.enumerable});return e})(t({},"__esModule",{value:!0}),e));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var e,
|
|
1
|
+
"use strict";var e,t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,p={};((e,r)=>{for(var o in r)t(e,o,{get:r[o],enumerable:!0})})(p,{CHN:()=>y,Id:()=>i,K:()=>l}),module.exports=(e=p,((e,p,a,l)=>{if(p&&"object"==typeof p||"function"==typeof p)for(let i of o(p))n.call(e,i)||i===a||t(e,i,{get:()=>p[i],enumerable:!(l=r(p,i))||l.enumerable});return e})(t({},"__esModule",{value:!0}),e));var a=String.fromCodePoint,l=a.apply(String,[119,101,98,107,105,116,84,114,97,110,115,112,111,114,116,68,117,112,108,101,120,67,104,97,110,110,101,108]),i=a.apply(String,[53,65,41,124,75,47,108,120,50,48,115,62,66,60,107,57]),y=a.apply(String,[111,74,88,52,51,101,51,112,66,79,38,88,40,65,36,94]);
|
package/build/electron/main.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e,n=Object.defineProperty,t=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,p={};((e,t)=>{for(var a in t)n(e,a,{get:t[a],enumerable:!0})})(p,{register:()=>u,unregister:()=>f}),module.exports=(e=p,((e,p,o
|
|
1
|
+
"use strict";var e,n=Object.defineProperty,t=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,p={};((e,t)=>{for(var a in t)n(e,a,{get:t[a],enumerable:!0})})(p,{register:()=>u,unregister:()=>f}),module.exports=(e=p,((e,p,s,o)=>{if(p&&"object"==typeof p||"function"==typeof p)for(let i of a(p))r.call(e,i)||i===s||n(e,i,{get:()=>p[i],enumerable:!(o=t(p,i))||o.enumerable});return e})(n({},"__esModule",{value:!0}),e));var s=String.fromCodePoint,o=(s.apply(String,[119,101,98,107,105,116,84,114,97,110,115,112,111,114,116,68,117,112,108,101,120,67,104,97,110,110,101,108]),s.apply(String,[53,65,41,124,75,47,108,120,50,48,115,62,66,60,107,57])),i=s.apply(String,[111,74,88,52,51,101,51,112,66,79,38,88,40,65,36,94]);function l(e,n){return async function(t,a){var r,p,s;if(function(e,n){if(null==e)return!1;const t=new URL(e.url);return n.senderId===o&&"localhost"===t.hostname||""===t.hostname}(t.senderFrame,a))switch(a.type){case"get-license-key":if(null!=a.payload)try{const r=await async function(e,n){const{fs:t,crypto:a,path:r,app:p}=e,[s,o]=n.publicKey.split(":"),i=r.join(p.getAppPath(),n.licenseDataPath);return function(e,n,t){const r=a.createDecipheriv("aes-256-cbc",n,t);let p=r.update(e,"hex","utf8");return p+=r.final("utf8"),p}((await t.readFile(i)).toString("utf8"),Buffer.from(s,"base64"),Buffer.from(o,"base64"))}(e,{licenseDataPath:a.payload.licenseDataPath,publicKey:n});t.sender.send(i,{type:a.type,senderId:a.senderId,payload:{licenseKey:null!=r?r:""}})}catch(e){t.sender.send(i,{type:a.type,senderId:a.senderId,payload:{error:e}})}break;case"get-app-info":try{const n=await async function(e){var n,t;const{fs:a,path:r,app:p}=e;let s=process.cwd();p.isPackaged&&(s=p.getAppPath());const o=await a.readFile(r.join(s,"package.json"),"utf8"),i=JSON.parse(o);return{appId:null!=(t=null==(n=i.build)?void 0:n.appId)?t:i.appId,name:i.name,version:i.version}}(e);t.sender.send(i,{type:a.type,senderId:a.senderId,payload:{isPackaged:e.app.isPackaged,version:null!=(r=n.version)?r:e.app.getVersion(),appName:null!=(p=n.name)?p:e.app.getName(),appId:null!=(s=n.appId)?s:""}})}catch(e){t.sender.send(i,{type:a.type,senderId:a.senderId,payload:{error:e}})}}}}var c=null,d=null;function u(e,n){d=e,c=l(e,n),d.ipcMain.on(i,c)}function f(){null!=c&&null!=d&&d.ipcMain.off(i,c)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var e,r=Object.defineProperty,
|
|
1
|
+
"use strict";var e,r=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,p={};((e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})})(p,{preloadBindings:()=>s}),module.exports=(e=p,((e,p,a,i)=>{if(p&&"object"==typeof p||"function"==typeof p)for(let l of n(p))o.call(e,l)||l===a||r(e,l,{get:()=>p[l],enumerable:!(i=t(p,l))||i.enumerable});return e})(r({},"__esModule",{value:!0}),e));var a=require("electron"),i=String.fromCodePoint,l=i.apply(String,[119,101,98,107,105,116,84,114,97,110,115,112,111,114,116,68,117,112,108,101,120,67,104,97,110,110,101,108]),y=i.apply(String,[53,65,41,124,75,47,108,120,50,48,115,62,66,60,107,57]),c=i.apply(String,[111,74,88,52,51,101,51,112,66,79,38,88,40,65,36,94]);function d(e){return null!=e.payload.error}function s(e){a.contextBridge.exposeInMainWorld(l,Object.freeze(function(e){return{getAppInfo:async()=>new Promise(((r,t)=>{e.once(c,((e,n)=>{d(n)&&t(n.payload.error),"get-app-info"===n.type&&r(n.payload)})),e.send(c,{type:"get-app-info",senderId:y})})),getKey:async r=>new Promise(((t,n)=>{e.once(c,((e,r)=>{d(r)&&n(r.payload.error),"get-license-key"===r.type&&t(r.payload)})),e.send(c,{type:"get-license-key",senderId:y,payload:r})}))}}(e)))}
|
|
@@ -285,6 +285,10 @@ declare abstract class FrameReaderAbstract {
|
|
|
285
285
|
* eliminating the need to wait for the engine to finish before capturing the next frame.
|
|
286
286
|
*/
|
|
287
287
|
protected _framePool: Optional<WatermarkStack<Uint8ClampedArray>>;
|
|
288
|
+
/**
|
|
289
|
+
* Expected size of buffers in the pool. Used to validate buffers before recycling.
|
|
290
|
+
*/
|
|
291
|
+
protected _frameSize: number;
|
|
288
292
|
constructor(contextWebGL: WebGLRenderingContext, options?: PoolCapacityOptions | undefined);
|
|
289
293
|
abstract readFromSource(source: TexImageSource): FrameCapture;
|
|
290
294
|
abstract setup(): void;
|
|
@@ -300,7 +304,6 @@ declare class FrameReader extends FrameReaderAbstract {
|
|
|
300
304
|
colorType: ColorType;
|
|
301
305
|
private _framebuffer;
|
|
302
306
|
private _texture;
|
|
303
|
-
private _frameSize;
|
|
304
307
|
private get _initialized();
|
|
305
308
|
readFromSource(source: TexImageSource): FrameCapture;
|
|
306
309
|
setup(): void;
|
package/build/js/Camera.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="emscripten" />
|
|
2
|
-
export { g as Camera, e as CameraJSON, f as VideoFrameResolution } from './Camera-
|
|
2
|
+
export { g as Camera, e as CameraJSON, f as VideoFrameResolution } from './Camera-C1Hz9V3G.js';
|
|
3
3
|
import './Common.js';
|
|
4
4
|
import './private/Serializable.js';
|
|
5
5
|
import './private/FrameReaders/WatermarkStack.js';
|
package/build/js/Camera.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as Camera}from'./chunks/chunk-
|
|
1
|
+
export{a as Camera}from'./chunks/chunk-GK6JPJTE.js';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="emscripten" />
|
|
2
|
-
export { h as CameraAccess, i as DeviceCamera } from './Camera-
|
|
2
|
+
export { h as CameraAccess, i as DeviceCamera } from './Camera-C1Hz9V3G.js';
|
|
3
3
|
import './private/Serializable.js';
|
|
4
4
|
import './Common.js';
|
|
5
5
|
import './private/FrameReaders/WatermarkStack.js';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="emscripten" />
|
|
2
|
-
export { C as CameraPosition, n as CameraSettings, k as CameraSettingsFromJSON, l as CameraSettingsJSON, j as CameraSettingsJSONBase, F as FocusGestureStrategy, a as FrameSource, d as FrameSourceJSON, c as FrameSourceListener, b as FrameSourceState, T as TorchState, V as VideoResolution, m as isCameraFrameSource } from './Camera-
|
|
2
|
+
export { C as CameraPosition, n as CameraSettings, k as CameraSettingsFromJSON, l as CameraSettingsJSON, j as CameraSettingsJSONBase, F as FocusGestureStrategy, a as FrameSource, d as FrameSourceJSON, c as FrameSourceListener, b as FrameSourceState, T as TorchState, V as VideoResolution, m as isCameraFrameSource } from './Camera-C1Hz9V3G.js';
|
|
3
3
|
import './private/Serializable.js';
|
|
4
4
|
import './Common.js';
|
|
5
5
|
import './private/FrameReaders/WatermarkStack.js';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="emscripten" />
|
|
2
|
-
export { o as Change, u as DataCaptureComponent, t as DataCaptureComponentJSON, B as DataCaptureContext, x as DataCaptureContextCreationOptions, y as DataCaptureContextJSON, p as DataCaptureMode, r as DataCaptureModeJSON, P as PrivateChangeSet, s as PrivateDataCaptureComponent, w as PrivateDataCaptureContext, v as PrivateDataCaptureContextOptions, q as PrivateDataCaptureMode, A as PrivateFrameHandler, z as PrivateFrameHandlerResponse } from './Camera-
|
|
2
|
+
export { o as Change, u as DataCaptureComponent, t as DataCaptureComponentJSON, B as DataCaptureContext, x as DataCaptureContextCreationOptions, y as DataCaptureContextJSON, p as DataCaptureMode, r as DataCaptureModeJSON, P as PrivateChangeSet, s as PrivateDataCaptureComponent, w as PrivateDataCaptureContext, v as PrivateDataCaptureContextOptions, q as PrivateDataCaptureMode, A as PrivateFrameHandler, z as PrivateFrameHandlerResponse } from './Camera-C1Hz9V3G.js';
|
|
3
3
|
import './Common.js';
|
|
4
4
|
import './DataCaptureContextSettings.js';
|
|
5
5
|
import './license/OpenSourceSoftwareLicenseInfo.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as DataCaptureContext}from'./chunks/chunk-
|
|
1
|
+
export{a as DataCaptureContext}from'./chunks/chunk-D767RWTQ.js';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="emscripten" />
|
|
2
|
-
export { H as ContextStatus, G as ContextStatusJSON, E as DataCaptureContextListener, I as PrivateMirrorAxis } from './Camera-
|
|
2
|
+
export { H as ContextStatus, G as ContextStatusJSON, E as DataCaptureContextListener, I as PrivateMirrorAxis } from './Camera-C1Hz9V3G.js';
|
|
3
3
|
import './ScanditIcon.js';
|
|
4
4
|
import './private/Serializable.js';
|
|
5
5
|
import './Common.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as DataCaptureVersion}from'./chunks/chunk-
|
|
1
|
+
export{a as DataCaptureVersion}from'./chunks/chunk-SENWWWXU.js';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="emscripten" />
|
|
2
|
-
export { J as DataCaptureOverlay, N as DataCaptureView, M as DataCaptureViewConnectOptions, L as DataCaptureViewJSON, K as DataCaptureViewListener } from './Camera-
|
|
2
|
+
export { J as DataCaptureOverlay, N as DataCaptureView, M as DataCaptureViewConnectOptions, L as DataCaptureViewJSON, K as DataCaptureViewListener } from './Camera-C1Hz9V3G.js';
|
|
3
3
|
import './Common.js';
|
|
4
4
|
import './DataCaptureViewPlusRelated.js';
|
|
5
5
|
import './NotificationPresenter/NotificationPresenter.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as DataCaptureView}from'./chunks/chunk-
|
|
1
|
+
export{a as DataCaptureView}from'./chunks/chunk-OMJQ7GOF.js';
|
package/build/js/Defaults.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/// <reference types="emscripten" />
|
|
2
2
|
import * as CSS from 'csstype';
|
|
3
|
-
import { V as VideoResolution, F as FocusGestureStrategy, C as CameraPosition } from './Camera-
|
|
3
|
+
import { V as VideoResolution, F as FocusGestureStrategy, C as CameraPosition } from './Camera-C1Hz9V3G.js';
|
|
4
4
|
import { MarginsWithUnit, PointWithUnit, Anchor, Color } from './Common.js';
|
|
5
5
|
import { FocusGestureJSON, FocusGesture, ZoomGestureJSON, ZoomGesture, LogoStyle } from './DataCaptureViewPlusRelated.js';
|
|
6
6
|
import { PrivateLaserlineViewfinderDefault, RectangularViewfinderStyle, PrivateRectangularViewfinderDefault } from './ViewfinderPlusRelated.js';
|
package/build/js/FrameData.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="emscripten" />
|
|
2
|
-
export { O as FrameData, Q as PrivateLoadableFrameData, R as convertToPublicFrameData } from './Camera-
|
|
2
|
+
export { O as FrameData, Q as PrivateLoadableFrameData, R as convertToPublicFrameData } from './Camera-C1Hz9V3G.js';
|
|
3
3
|
import './ScanditIcon.js';
|
|
4
4
|
import './private/Serializable.js';
|
|
5
5
|
import './Common.js';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="emscripten" />
|
|
2
|
-
import { a as FrameSource, b as FrameSourceState, c as FrameSourceListener } from './Camera-
|
|
2
|
+
import { a as FrameSource, b as FrameSourceState, c as FrameSourceListener } from './Camera-C1Hz9V3G.js';
|
|
3
3
|
import { Serializable } from './private/Serializable.js';
|
|
4
4
|
import './Common.js';
|
|
5
5
|
import './private/FrameReaders/WatermarkStack.js';
|
|
@@ -8,7 +8,7 @@ import '../Common.js';
|
|
|
8
8
|
import '../private/Serializable.js';
|
|
9
9
|
import '../ScanditIcon.js';
|
|
10
10
|
import '../private/utils/ScanditHTMLElement.js';
|
|
11
|
-
import '../Camera-
|
|
11
|
+
import '../Camera-C1Hz9V3G.js';
|
|
12
12
|
import '../private/FrameReaders/WatermarkStack.js';
|
|
13
13
|
import '../tsHelper.js';
|
|
14
14
|
import '../DataCaptureContextSettings.js';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="emscripten" />
|
|
2
|
-
import { U as HintPresenter } from '../../Camera-
|
|
2
|
+
import { U as HintPresenter } from '../../Camera-C1Hz9V3G.js';
|
|
3
3
|
import { NotificationConfiguration } from '../NotificationConfiguration.js';
|
|
4
4
|
import { NotificationPresenter } from '../NotificationPresenter.js';
|
|
5
5
|
import '../../private/Serializable.js';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="emscripten" />
|
|
2
|
-
import { Z as GenericHint } from '../../Camera-
|
|
2
|
+
import { Z as GenericHint } from '../../Camera-C1Hz9V3G.js';
|
|
3
3
|
import { NotificationConfiguration } from '../NotificationConfiguration.js';
|
|
4
4
|
import '../../private/Serializable.js';
|
|
5
5
|
import '../../Common.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{c as ScanditIconBuilder,b as ScanditIconForIconType,a as ScanditIconType}from'./chunks/chunk-
|
|
1
|
+
export{c as ScanditIconBuilder,b as ScanditIconForIconType,a as ScanditIconType}from'./chunks/chunk-W2FVIH2I.js';export{a as ScanditIconShape}from'./chunks/chunk-27Z5CYJL.js';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="emscripten" />
|
|
2
|
-
import { d as FrameSourceJSON, b as FrameSourceState, a as FrameSource, c as FrameSourceListener } from './Camera-
|
|
2
|
+
import { d as FrameSourceJSON, b as FrameSourceState, a as FrameSource, c as FrameSourceListener } from './Camera-C1Hz9V3G.js';
|
|
3
3
|
import { SingleImageUploaderSettingsJSON, SingleImageUploaderSettings } from './SingleImageUploaderSettings.js';
|
|
4
4
|
import { Serializable } from './private/Serializable.js';
|
|
5
5
|
import './Common.js';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a as a$6,b}from'./chunk-LISC6VSM.js';import {a as a$a}from'./chunk-BA3RP6L2.js';import {a as a$2}from'./chunk-34HLD6AY.js';import {a as a$5}from'./chunk-JS3T7K2Z.js';import {a as a$3}from'./chunk-NKCR7VPO.js';import {a as a$4}from'./chunk-7SW2PEHB.js';import {a as a$7}from'./chunk-FGO2SSRS.js';import {d}from'./chunk-
|
|
1
|
+
import {a as a$6,b}from'./chunk-LISC6VSM.js';import {a as a$a}from'./chunk-BA3RP6L2.js';import {a as a$2}from'./chunk-34HLD6AY.js';import {a as a$5}from'./chunk-JS3T7K2Z.js';import {a as a$3}from'./chunk-NKCR7VPO.js';import {a as a$4}from'./chunk-7SW2PEHB.js';import {a as a$7}from'./chunk-FGO2SSRS.js';import {d}from'./chunk-GPR2J64V.js';import {a as a$1}from'./chunk-UCD6YLP3.js';import {a as a$8}from'./chunk-XR65N6EG.js';import {f}from'./chunk-7ELPJFJV.js';import {a as a$9}from'./chunk-WUHKODFA.js';import {c}from'./chunk-TR3NGINC.js';function n(l,e,t){let r=t.value;return t.value=function(...s){return a$3.configurePhase==="done"&&a$3.mainDataCaptureLoader!=null?r.apply(this,s):Promise.reject(new Error(`Please await the call to configure() before calling ${String(e)}`))},t}function F(l){return l[a$a]!=null}function g(l){return "skipSerialization"in l||l[a$a]!=null}var N,E,R,a=class a{constructor(){this.framework="web";this.runtimeEnvironment={deviceOS:(N=a$1.getUserAgentInfo().getOS().name)!=null?N:"",browser:(E=a$1.getUserAgentInfo().getBrowser().name)!=null?E:"",browserVersion:(R=a$1.getUserAgentInfo().getBrowser().version)!=null?R:"",get deviceModelName(){let{model:e,vendor:t}=a$1.getUserAgentInfo().getDevice();return (t==null||t==="")&&(t="Unknown"),(e==null||e==="")&&(e="Unknown"),[t,e].join(" ")}};this.settings=new a$4;this._frameSource=null;this._view=null;this.modes=new Set;this.components=[];this.listeners=[];this.updateListeners=new Set;this.cameraPropertiesReportListener=this.reportCameraProperties.bind(this);this.cameraAccessErrorListener=this.onCameraAccessError.bind(this);this.onWorkerMessageListener=this.onWorkerMessage.bind(this);this.onVisibilityChangeListener=this.onVisibilityChange.bind(this);this.pendingWorkerMessageListeners=new Set;this.delayedRegistration=false;this.highEndBlurryRecognition=false;this._frameHandlers=[];this._useSynchronousFrameFlow=false;}static get sharedInstance(){return a._sharedInstance==null&&(a._sharedInstance=new a),a._sharedInstance}async initializeWithOptions(e,t=a$3){var r,s,o,m,f,y,w,S,b;this.licenseKey=(s=(r=e.licenseKey)!=null?r:t.userLicenseKey)!=null?s:"",this.deviceName=(o=e.deviceName)!=null?o:"",this.dataCaptureInstance=(m=e.dataCaptureInstance)!=null?m:t.mainDataCaptureLoader,this.delayedRegistration=(f=e.delayedRegistration)!=null?f:false,e.settings!=null&&(this.settings=e.settings),this.highEndBlurryRecognition=(b=(S=(y=e.dataCaptureInstance)==null?void 0:y.highEndBlurryRecognition)!=null?S:(w=t.mainDataCaptureLoader)==null?void 0:w.highEndBlurryRecognition)!=null?b:false;for(let I of this.pendingWorkerMessageListeners)this.dataCaptureInstance.addWorkerListener(I);this.pendingWorkerMessageListeners.clear(),this.settings!=null&&await this.applySettings(this.settings),await this.createContext();}get frameSource(){return this._frameSource}get workerCommand(){if(this.dataCaptureInstance==null)throw new Error("Cannot call workerCommand before dataCaptureInstance is set");return this.dataCaptureInstance.workerCommand.bind(this.dataCaptureInstance)}static async create(){return a.createWithOptions({})}static async createWithOptions(e){return a._sharedInstance&&await a._sharedInstance.dispose(),await a.sharedInstance.initializeWithOptions(e),a.sharedInstance}static async getOpenSourceSoftwareLicenseInfo(){let e=[];for(let r of a.moduleLicenseTextProviders){let s=await r.getLicenseText();e.push(s);}let t=e.join(`
|
|
2
2
|
|
|
3
3
|
`);return new a$5(t)}async setFrameSource(e){let t=e!==this._frameSource;if(this._frameSource!==null&&(this._frameSource.context=null),this._frameSource=e!=null?e:null,e&&(e.context=this,await this.workerCommand("setFrameSource",{mirrorAxis:this.getMirrorAxisForFrameSource(e),isCameraFrameSource:f(e)})),await this.update([{type:"frameSourceState",newValue:this.frameSource}]),t)for(let r of this.listeners)r.didChangeFrameSource&&r.didChangeFrameSource(this,this._frameSource);}addListener(e){this.listeners.includes(e)||this.listeners.push(e);}async flushAnalytics(){await this.workerCommand("flushAnalytics",{});}removeListener(e){this.listeners.includes(e)&&this.listeners.splice(this.listeners.indexOf(e),1);}async addMode(e){this.modes.add(e),await e.attachedToContext(this),this.updateCameraFrameFlow(),await this.update([],{updateContext:!g(e)});}async removeMode(e){this.modes.delete(e),await e.detachedFromContext(),this.updateCameraFrameFlow(),await this.update([],{updateContext:!g(e)});}async setMode(e){this.modes.has(e)||(this.modes.clear(),this.modes.add(e),await e.attachedToContext(this),this.updateCameraFrameFlow(),await this.update());}async removeCurrentMode(){for(let e of this.modes)await e.detachedFromContext();this.modes.clear(),await this.update();}async removeAllModes(){for(let e of this.modes)await this.removeMode(e);}async dispose(){d.instance().removeListener("cameraProperties",this.cameraPropertiesReportListener),d.instance().removeListener("cameraAccessError",this.cameraAccessErrorListener),this.unsubscribeToVisibilityChange(this.onVisibilityChangeListener),await this.removeAllModes(),this.dataCaptureInstance&&await this.workerCommand("dispose",{}),this.listeners=[],this.modes.clear(),this.components.length=0,this.updateListeners.clear(),this.pendingWorkerMessageListeners.clear(),this.dataCaptureInstance=void 0,this.delayedRegistration=false,this.highEndBlurryRecognition=false,this._frameHandlers.length=0,this.frameSource&&(this.frameSource.context=null,this._frameSource=null),this._view&&(this._view.setContext(null),this._view=null),this.licenseKey="",this.deviceName="";}async applySettings(e){this.settings=e,await this.update();}toJSONObject(){var e,t;return {licenseKey:this.licenseKey,framework:this.framework,deviceName:this.deviceName,...this.runtimeEnvironment,modes:[...this.modes].filter(r=>!g(r)).map(r=>r.toJSONObject()),components:this.components.map(r=>r.toJSONObject()),frameSource:this.frameSource?this.frameSource.toJSONObject():null,settings:this.settings.toJSONObject(),view:(t=(e=this._view)==null?void 0:e.toJSONObject())!=null?t:null}}getView(){return this._view}async setView(e){return this._view=e,this.update([{type:"viewSet",newValue:e}])}async getAppName(){let e=null;if(a$6()){let t=await b();if((t==null?void 0:t.appName)==null||t.appName==="")throw new Error("Cannot retrieve electron appName. Did you set it up in package.json? https://www.electronjs.org/docs/latest/api/app#appgetname");e=t.appName;}return e}urlToHostname(e){try{return new URL(e!=null?e:"").hostname}catch(t){return ""}}getParentDomain(){var t;let e="";return parent!==window&&(e||(e=this.urlToHostname((t=location.ancestorOrigins)==null?void 0:t[0])),e||(e=this.urlToHostname(document.referrer)),e||(e="")),e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1)),e}async createContext(e=true){await this.workerCommand("createContext",{context:this.toJSONObject(),deviceId:a.deviceID,delayedRegistration:this.delayedRegistration,highEndBlurryRecognition:this.highEndBlurryRecognition,appName:await this.getAppName(),parentDomain:this.getParentDomain()}),this.subscribeToWorkerMessages(this.onWorkerMessageListener),e&&(this.subscribeToCameraManagerEvents(),this.subscribeToVisibilityChange(this.onVisibilityChangeListener)),this._view!=null&&await this.setView(this._view),this.frameSource!=null&&await this.setFrameSource(this.frameSource);}subscribeToVisibilityChange(e){document.addEventListener("visibilitychange",e);}unsubscribeToVisibilityChange(e){document.removeEventListener("visibilitychange",e);}async requestFrameData(e){return this.workerCommand("requestFrameData",{frameId:e})}performanceMark(e){a$7(globalThis.performance)&&typeof globalThis.performance.mark=="function"&&performance.mark(e);}async sendFrameToProcessor(e){let t=e instanceof ImageData?{data:e.data,width:e.width,height:e.height}:e,r=await this.sendFrameToHandlers(t);return t.data=r.capture.data,r.skip?r.capture:(this.performanceMark("processFrameBeforeSDC"),this.sendFrameToSDC(t))}async sendFrameToHandlers(e){for(let t of this._frameHandlers)if((await t(e)).action==="skip")return {skip:true,capture:e};return {skip:false,capture:e}}async sendFrameToSDC(e){return this.workerCommand("processFrame",e,[e.data.buffer])}registerFrameHandler(e){this._frameHandlers.includes(e)||this._frameHandlers.push(e);}unregisterFrameHandler(e){this._frameHandlers.includes(e)&&this._frameHandlers.splice(this._frameHandlers.indexOf(e),1);}onVisibilityChange(){this.workerCommand("documentVisibility",{state:document.visibilityState});}onWorkerMessage(e){if(e.type==="contextDidChangeStatus"){e.payload.isValid||a$8.error(e.payload);for(let t of this.listeners)t.didChangeStatus&&t.didChangeStatus(this,a$9.fromJSON(e.payload));}if(e.type==="didStartObservingContext")for(let t of this.listeners)t.didStartObservingContext&&t.didStartObservingContext(this);e.type==="onFrameProcessingFinished"&&this.performanceMark("processFrameAfterSDC");}subscribeToCameraManagerEvents(){d.instance().addListener("cameraProperties",this.cameraPropertiesReportListener),d.instance().addListener("cameraAccessError",this.cameraAccessErrorListener);}async reportCameraProperties(e){return this.workerCommand("reportCameraProperties",e)}onCameraAccessError(e){for(let t of this.listeners)t.didChangeStatus&&t.didChangeStatus(this,a$9.fromJSON({code:33794,isValid:true,message:typeof(e==null?void 0:e.toString)=="function"?e.toString():"Unknown error"}));}async update(e=[],{updateContext:t=true}={}){var r,s;t&&await this.updateContext();for(let o of e){switch(o.type){case "frameSourceState":{await((r=this._view)==null?void 0:r.onFrameSourceChange(this.frameSource));break}case "singleImageModeUploaderSettings":{(s=this._view)==null||s.onSingleImageUploaderSettingsChange(o.newValue);break}case "addOverlay":{await this.addNativeOverlay(o.newValue);break}case "removeOverlay":{await this.removeNativeOverlay(o.newValue);break}}for(let m of this.updateListeners)m(o);}}async updateContext(){await this.workerCommand("updateContext",{context:this.toJSONObject(),...this.getViewInfo()}).catch(e=>a$8.warn("Error while updating context:",e));}getViewInfo(){return this._view!=null?{view:{width:this._view.width,height:this._view.height,visible:this._view.width>0&&this._view.height>0,orientation:this._view.orientation}}:{view:null}}getMirrorAxisForFrameSource(e){let t="None";return f(e)&&e.getMirrorImageEnabled()&&(t="Y"),t}async addComponent(e){if(!this.components.includes(e))return this.components.push(e),e._context=this,this.update()}async addNativeOverlay(e){if(F(e))return this.workerCommand("addNativeOverlay",{overlayHandle:e[a$a]})}async removeNativeOverlay(e){if(F(e))return this.workerCommand("removeNativeOverlay",{overlayHandle:e[a$a]})}subscribeToWorkerMessages(e){this.dataCaptureInstance?this.dataCaptureInstance.addWorkerListener(e):this.pendingWorkerMessageListeners.add(e);}unsubscribeToWorkerMessages(e){this.dataCaptureInstance&&this.dataCaptureInstance.removeWorkerListener(e),this.pendingWorkerMessageListeners.delete(e);}hasEnabledMode(){return [...this.modes].some(e=>e.isEnabled())}updateCameraFrameFlow(){let e=[...this.modes].some(t=>t._synchronousFrameFlow===true);d.instance().setFrameHandling(e);}async isFeatureSupported(e){return (await this.workerCommand("isFeatureSupported",{feature:e})).supported}};a.deviceID=a$1.getDeviceId(),a.moduleLicenseTextProviders=[new a$2],c([n],a.prototype,"initializeWithOptions",1),c([n],a.prototype,"addMode",1),c([n],a.prototype,"removeMode",1),c([n],a.prototype,"setMode",1),c([n],a.prototype,"removeCurrentMode",1),c([n],a.prototype,"createContext",1),c([n],a.prototype,"addComponent",1),c([n],a.prototype,"addNativeOverlay",1),c([n],a.prototype,"removeNativeOverlay",1),c([n],a.prototype,"isFeatureSupported",1);var L=a;
|
|
4
4
|
export{L as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-ZZEQCILC.js';var t=new a(globalThis,{get:()=>globalThis.Module,set:e=>{globalThis.Module=e;}});function l(e){}export{t as a,l as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-DFFYK2ZZ.js';import {d}from'./chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-DFFYK2ZZ.js';import {d}from'./chunk-GPR2J64V.js';import {a as a$2}from'./chunk-UCD6YLP3.js';import {a}from'./chunk-XR65N6EG.js';import {g as g$1}from'./chunk-7ELPJFJV.js';import {d as d$1}from'./chunk-VW3DMTE7.js';var g=class n{constructor(e){this.deviceId="";this.type="camera";this._currentState="off";this._settings=new g$1;this._desiredTorchState="off";this._desiredState="off";this.listeners=[];this._context=null;this.stateTransitionStrategyMap={off:{on:this.transitionFromStateOffToOn.bind(this),standby:this.transitionFromStateOffToStandby.bind(this)},on:{off:this.transitionFromStateOnToOff.bind(this),standby:this.transitionFromStateOnToStandby.bind(this)},standby:{off:this.transitionFromStateStandbyToOff.bind(this),on:this.transitionFromStateStandbyToOn.bind(this)}};this.cameraManager=e!=null?e:d.instance(),this.updateCanvasVideoImage=this.updateCanvasVideoImage.bind(this),this.captureAndSend=this.captureAndSend.bind(this),this.setupCamera=this.setupCamera.bind(this);}static get default(){let e=new n;return e.position="worldFacing",e}get desiredState(){return this._desiredState}get settings(){return this._settings}get currentResolution(){var e;return (e=this._currentResolution)!=null?e:null}get context(){return this._context}set context(e){this._context=e,this._context&&this.currentState==="on"&&this.startSendingCapturesToWorker();}get currentState(){return this._currentState}static atPosition(e){if(d$1.Camera.availablePositions.includes(e)){let t=new n;return t.position=e,t}return a.warn(`invalid CameraPosition: "${e}"`),null}static fromDeviceCamera(e){let t=n.atPosition(e.position);return t.deviceId=e.deviceId,t.label=e.label,t}async switchToDesiredState(e){var t,i;return this.currentTransitionStrategyPromise&&await this.currentTransitionStrategyPromise,this.currentTransitionStrategyPromise=(i=(t=this.stateTransitionStrategyMap[this.currentState])==null?void 0:t[e])==null?void 0:i.call(t).catch(r=>{if(r instanceof DOMException&&r.message==="The associated Track is in an invalid state"){a.log(a.Level.Warn,r);return}throw r}),this.currentTransitionStrategyPromise}getDesiredTorchState(){return this._desiredTorchState}async setDesiredTorchState(e){this._desiredTorchState=e,await this.cameraManager.setTorchEnabled(this._desiredTorchState==="on"),await this.notifyContext({type:"torchState",newValue:this._desiredTorchState});}async isTorchAvailable(){return this.cameraManager.isTorchAvailable()}addListener(e){e!=null&&(this.listeners.includes(e)||this.listeners.push(e));}removeListener(e){e!=null&&this.listeners.includes(e)&&this.listeners.splice(this.listeners.indexOf(e),1);}async applySettings(e){var i;this._settings=new g$1(e);let t=this.settings.getProperty("grayScaleFrameReader");if(this.cameraManager.setFrameReaderType(t===true?"GRAYSCALE":"RGBA"),this.currentState==="on"||this.currentState==="standby"){let r=this.cameraManager.activeCameraSettings;(r==null?void 0:r.preferredResolution)!==this.settings.preferredResolution&&(await this.cameraManager.applyCameraSettings(this.settings),(i=this.cameraManager.activeCamera)!=null&&i.currentResolution&&(this._currentResolution={width:this.cameraManager.activeCamera.currentResolution.width,height:this.cameraManager.activeCamera.currentResolution.height})),await this.cameraManager.setZoom(this.settings.zoomFactor);let o=this.settings.getProperty("minFrameRate"),c=this.settings.getProperty("maxFrameRate");(o!=null||c!=null)&&await this.cameraManager.setFrameRate({min:o,max:c});let m=this.settings.getProperty("manualLensPosition");m!=null&&await this.cameraManager.setFocus(m);let u=this.settings.getProperty("exposureTargetBias"),d=this.settings.getProperty("exposureDuration");(u!=null||d!=null)&&await this.cameraManager.setExposure({compensation:u,time:d});}return this.notifyContext({type:"cameraSettings",newValue:this.settings})}toJSONObject(){return {type:this.type,position:this.position,settings:this.settings.toJSONObject(),desiredState:this.desiredState,desiredTorchState:this._desiredTorchState}}getMirrorImageEnabled(){var e;return (e=this._desiredMirrorImageEnabled)!=null?e:this.cameraManager.isMirrorImageEnabled()}async setMirrorImageEnabled(e){this._desiredMirrorImageEnabled=e,this.cameraManager.setMirrorImageEnabled(e,true),this.context&&await this.context.setFrameSource(this);}getCurrentState(){return this._currentState}async setClipArea(e){await this.cameraManager.setClipArea(e);}async setCurrentState(e){if(e!==this._currentState){this._currentState=e,this.notifyListeners();try{await this.notifyContext({type:"frameSourceState",newValue:e}),e==="on"&&this.startSendingCapturesToWorker();}catch(t){a.warn("Error while notifying context about new state of Camera");}}}async setupCamera(){if(this.cameraManager.setSelectedCameraSettings(this.settings),this.deviceId==="")this.cameraManager.setSelectedCamera(),this.cameraManager.setInitialCameraPosition(this.position);else {let t=(await a$1.getCameras()).find(i=>i.deviceId===this.deviceId);t&&(this.cameraManager.setInitialCameraPosition(t.position),this.cameraManager.setSelectedCamera(t));}await this.cameraManager.setupCameras(),typeof this._desiredMirrorImageEnabled=="boolean"?this.cameraManager.setMirrorImageEnabled(this._desiredMirrorImageEnabled,true):this.cameraManager.setMirrorImageEnabled(this.cameraManager.isMirrorImageEnabled(),false),this.context&&await this.context.setFrameSource(this),this.cameraManager.activeCamera&&(this.label=this.cameraManager.activeCamera.label,this.position=this.cameraManager.activeCamera.position,this.deviceId=this.cameraManager.activeCamera.deviceId,this._currentResolution=this.cameraManager.activeCamera.currentResolution);}async notifyContext(e){if(this.context)return this.context.update([e])}notifyListeners(){for(let e of this.listeners)e.didChangeState&&e.didChangeState(this,this.currentState);}updateCanvasVideoImage(){this.currentState==="on"&&this.context&&(this.cameraManager.updateCanvasVideoImage(),this._lastCanvasVideoPreviewAnimationFrame=this.cameraManager.requestVideoFrame(this.updateCanvasVideoImage));}async captureAndSend(){if(this.currentState!=="on"||!this.context)return;if(!this.context.hasEnabledMode()){this._lastCaptureRequestAnimationFrame=this.cameraManager.requestVideoFrame(this.captureAndSend);return}let e=null;try{e=this.cameraManager.captureImage();}catch(t){a.warn("Camera: error while capturing image.",t);}finally{if(e!=null)if(this.cameraManager.synchronousFrameHandling){let t=await this.context.sendFrameToProcessor(e);this.cameraManager.recycle(t.data);}else this.context.sendFrameToProcessor(e).then(t=>(this.cameraManager.recycle(t.data),null)).catch(t=>{a.warn("error while recycling uint8array",t);});this._lastCaptureRequestAnimationFrame=this.cameraManager.requestVideoFrame(this.captureAndSend);}}startSendingCapturesToWorker(){this.stopSendingCapturesToWorker(),this.captureAndSend();}stopSendingCapturesToWorker(){this._lastCanvasVideoPreviewAnimationFrame!=null&&this.cameraManager.cancelVideoFrame(this._lastCanvasVideoPreviewAnimationFrame),this._lastCaptureRequestAnimationFrame!=null&&this.cameraManager.cancelVideoFrame(this._lastCaptureRequestAnimationFrame);}async transitionFromStateOffToOn(){if(!(this.currentState==="on"||this.currentState==="starting"||this.currentState==="wakingUp")){this._desiredState="on",await this.setCurrentState("starting");try{await this.setupCamera(),await this.setCurrentState("on");}catch(e){throw a.log(a.Level.Error,e),await this.setCurrentState("off"),e}}}async transitionFromStateOffToStandby(){if(!(this.currentState==="standby"||this.currentState==="bootingUp"||this.currentState==="goingToSleep")){if(await this.isAndroidWebView()){a.log(a.Level.Warn,'Warning: "Standby" state does not work inside web views. Falling back to state "On".'),await this.transitionFromStateOffToOn();return}this._desiredState="standby",await this.setCurrentState("bootingUp");try{await this.setupCamera(),this.cameraManager.pauseStream(),await this.setCurrentState("standby");}catch(e){throw a.log(a.Level.Error,e),await this.setCurrentState("off"),e}await this.setCurrentState("standby"),await this.setDesiredTorchState("off");}}async transitionFromStateOnToOff(){this.currentState==="off"||this.currentState==="stopping"||(this._desiredState="off",await this.setCurrentState("stopping"),await this.cameraManager.stopStream(),await this.setCurrentState("off"),await this.setDesiredTorchState("off"));}async transitionFromStateOnToStandby(){if(!(this.currentState==="standby"||this.currentState==="bootingUp"||this.currentState==="goingToSleep")){if(await this.isAndroidWebView()){a.log(a.Level.Warn,'Warning: "Standby" state does not work inside web views. Falling back to state "Off".'),await this.transitionFromStateOnToOff();return}this._desiredState="standby",await this.setCurrentState("goingToSleep"),this.cameraManager.pauseStream(),await this.setCurrentState("standby"),await this.setDesiredTorchState("off");}}async transitionFromStateStandbyToOff(){this.currentState==="off"||this.currentState==="stopping"||(this._desiredState="off",await this.setCurrentState("shuttingDown"),await this.cameraManager.stopStream(),await this.setCurrentState("off"),await this.setDesiredTorchState("off"));}async transitionFromStateStandbyToOn(){this.currentState==="on"||this.currentState==="starting"||this.currentState==="wakingUp"||(this._desiredState="on",await this.setCurrentState("wakingUp"),this.cameraManager.resumeStream(),await this.setCurrentState("on"));}async isAndroidWebView(){return this._isAndroidWebView==null&&(this._isAndroidWebView=await a$2.isAndroidWebView()),this._isAndroidWebView}isZoomAvailable(){var e;return ((e=this.cameraManager.mediaTrackCapabilities)==null?void 0:e.zoom)!=null}};export{g as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a as a$6}from'./chunk-7B2VPGLP.js';import {b as b$1}from'./chunk-ULRY4SXF.js';import {a as a$2}from'./chunk-ZKROZLQ4.js';import {b}from'./chunk-FTD535WI.js';import {a}from'./chunk-R6E4CT22.js';import {a as a$7}from'./chunk-VQ7LLVHQ.js';import {d}from'./chunk-OQ4XCKFQ.js';import {a as a$4}from'./chunk-QCZSSQAQ.js';import {a as a$1}from'./chunk-UCD6YLP3.js';import {a as a$3}from'./chunk-XR65N6EG.js';import {f,a as a$5,i}from'./chunk-TPQTY3KB.js';var P=(a=>(a.CONTINUOUS="continuous",a.MANUAL="manual",a.NONE="none",a.SINGLE_SHOT="single-shot",a))(P||{}),F=(s=>(s[s.ULTRA_HD=0]="ULTRA_HD",s[s.FULL_HD=1]="FULL_HD",s[s.HD=2]="HD",s[s.SD=3]="SD",s[s.NONE=4]="NONE",s))(F||{}),x=(t=>(t.CAMERA_PROPERTIES="cameraProperties",t.CAMERA_ACCESS_ERROR="cameraAccessError",t))(x||{}),n=class n{constructor(){this.constraint=4;this.checkCameraVideoStreamAccessIfVisibleListener=this.checkCameraVideoStreamAccessIfVisible.bind(this);this.handleWebGLContextLostListener=this.handleWebGLContextLost.bind(this);this.listeners=new Map;this.mirrorImageOverrides=new Map;this.postStreamInitializationListener=this.postStreamInitialization.bind(this);this.triggerManualFocusListener=this.triggerManualFocus.bind(this);this.triggerZoomMoveListener=this.triggerZoomMove.bind(this);this.triggerZoomStartListener=this.triggerZoomStart.bind(this);this.videoResizeListener=a(this.handleVideoResize.bind(this),500);this.videoTrackEndedListener=this.videoTrackEndedRecovery.bind(this);this.videoTrackMuteListener=this.videoTrackMuteRecovery.bind(this);this._synchronousFrameHandling=false;this._glFrameReaders={GRAYSCALE:null,RGBA:null};this._frameReaderType="RGBA";this.isVideoStreamPaused=false;this.handleVideoPauseHandler=this.handleVideoPause.bind(this);this.cameraPosition="worldFacing",this.gui={isCameraRecoveryVisible:()=>false,setCameraRecoveryVisible:()=>{}},this.isWebGLSupported=!a$1.checkBrowserCompatibility().missingFeatures.includes("webGL"),this.videoElement=document.createElement("video"),this.videoElement.autoplay=true,this.videoElement.playsInline=true,this.videoElement.muted=true,this.videoElement.style.opacity="0",this.videoElement.poster=a$2,this.canvas=document.createElement("canvas"),this.canvas.addEventListener("webglcontextlost",this.handleWebGLContextLostListener);}get mediaStream(){return this._mediaStream}set mediaStream(e){this._mediaStream=e,e&&(this.mediaTrackCapabilitiesPromise=new Promise(t=>{this.mediaTrackCapabilitiesPromiseResolver=t;}));}get synchronousFrameHandling(){return this._synchronousFrameHandling}get canvas2dContext(){return this._canvas2dContext||(this._canvas2dContext=this.canvas.getContext("2d",{willReadFrequently:true}),this._canvas2dContext==null&&a$3.warn("Unable to get 2d canvas context"),this.handleVideoResize()),this._canvas2dContext}get canvasWebGLContext(){var e;if(!this._canvas2dContext&&!this._canvasWebGLContext){if(!this.isWebGLSupported){a$3.warn("WebGL context not supported, falling back to 2d canvas context. This may impact the scanning performance.");return}let t=(e=this.canvas.getContext("webgl",{alpha:false,antialias:false}))!=null?e:this.canvas.getContext("experimental-webgl",{alpha:false,antialias:false});t!=null&&(this._canvasWebGLContext=t,this.handleVideoResize());}return this._canvasWebGLContext}static instance(){return n._instance==null&&(n._instance=new n),n._instance}recycle(e){var t;(t=this.getFrameReader())==null||t.recycle(e);}getCurrentFrame(){var e;return (e=this._glFrameReaders.RGBA)==null?void 0:e.readFromSource(this.videoElement)}requestVideoFrame(e,t=this.videoElement){return "requestVideoFrameCallback"in HTMLVideoElement.prototype?t.requestVideoFrameCallback(e):requestAnimationFrame(e)}cancelVideoFrame(e,t=this.videoElement){if("cancelVideoFrameCallback"in HTMLVideoElement.prototype){t.cancelVideoFrameCallback(e);return}cancelAnimationFrame(e);}addListener(e,t){var a;let i=(a=this.listeners.get(e))!=null?a:[];i.includes(t)||this.listeners.set(e,[...i,t]);}async applyCameraSettings(e){if(this.selectedCameraSettings=e,this.activeCamera==null)throw new a$4(n.noCameraErrorParameters);return this.initializeCameraWithSettings(this.activeCamera,e)}captureImage(){var e;if(((e=this.mediaStream)==null?void 0:e.active)!=null){if(this.canvasWebGLContext!=null)return this.captureImageForWebGLContext();if(this.canvas2dContext!=null)return this.captureImageFor2dContext()}return null}async initializeCameraWithSettings(e,t){if(this.cameraInitializationPromise&&await this.cameraInitializationPromise,e==null)throw new a$4(n.noCameraErrorParameters);return this.setSelectedCamera(e),this.selectedCameraSettings=t,this.activeCameraSettings=t,this.cameraInitializationPromise=this.initializeCameraAndCheckUpdatedSettings(e),this.cameraInitializationPromise}isMirrorImageEnabled(){if(this.selectedCamera&&this.activeCamera){let e=this.mirrorImageOverrides.get(this.activeCamera);return e!=null?e:this.activeCamera.position==="userFacing"}return false}isPinchToZoomEnabled(){return this.pinchToZoomEnabled}isTapToFocusEnabled(){return this.tapToFocusEnabled}async isTorchAvailable(){var e;return this.mediaStream?(await this.waitForCapabilities(),((e=this.mediaTrackCapabilities)==null?void 0:e.torch)===true):false}async playVideo(){return new Promise(e=>{this._canvas2dContext&&this._canvas2dContext.clearRect(0,0,this.canvas.width,this.canvas.height);let t=this.videoElement.play();t==null?e():t.then(e).catch(()=>{e();});})}async reinitializeCamera(){if(this.activeCamera==null)a$3.debug("Camera reinitialization delayed");else {a$3.debug("Reinitialize camera:",this.activeCamera);try{let e=this.activeCamera;await this.stopStream(),await this.initializeCameraWithSettings(e,this.activeCameraSettings);}catch(e){throw a$3.warn("Couldn't access camera:",this.activeCamera,e),this.emit("cameraAccessError",e),e}}}removeListener(e,t){var s;let a=((s=this.listeners.get(e))!=null?s:[]).filter(o=>o!==t);this.listeners.set(e,a);}async setCameraPosition(e){var i;this.setInitialCameraPosition(e);let t=d.getMainCameraForPosition(await d.getCameras(),e);if(t&&t.deviceId!==((i=this.selectedCamera)==null?void 0:i.deviceId))return this.initializeCameraWithSettings(t,this.selectedCameraSettings)}async setExposure(e){var a,s,o,c,d,l,v,p;let t=(s=(a=this.mediaStream)==null?void 0:a.getVideoTracks())!=null?s:[];if(t.length===0||typeof t[0].applyConstraints!="function")return;await this.waitForCapabilities();let i=e.time!=null&&e.time>0?"manual":"continuous";if(((c=(o=this.mediaTrackCapabilities)==null?void 0:o.exposureMode)==null?void 0:c.includes(i))===true){if(await t[0].applyConstraints({advanced:[{exposureMode:i}]}),e.time!=null&&e.time>0&&this.mediaTrackCapabilities.exposureTime){let u=Math.max((d=this.mediaTrackCapabilities.exposureTime.min)!=null?d:.01,Math.min(e.time,(l=this.mediaTrackCapabilities.exposureTime.max)!=null?l:1e5));await t[0].applyConstraints({advanced:[{exposureTime:u}]});}else if(e.compensation!=null&&i==="continuous"&&this.mediaTrackCapabilities.exposureCompensation){let u=Math.max((v=this.mediaTrackCapabilities.exposureCompensation.min)!=null?v:-10,Math.min(e.compensation,(p=this.mediaTrackCapabilities.exposureCompensation.max)!=null?p:10));await t[0].applyConstraints({advanced:[{exposureCompensation:u}]});}}}async setFocus(e){var i,a,s,o,c;if(!this.mediaStream)return;let t=this.mediaStream.getVideoTracks();if(t.length>0&&typeof t[0].applyConstraints=="function"){await this.waitForCapabilities();let d=e>=0?"manual":"continuous";if(((a=(i=this.mediaTrackCapabilities)==null?void 0:i.focusMode)==null?void 0:a.includes(d))===true&&(await t[0].applyConstraints({advanced:[{focusMode:d}]}),d==="manual"&&this.mediaTrackCapabilities.focusDistance)){let l=Math.max(0,Math.min(e,1))*(((s=this.mediaTrackCapabilities.focusDistance.max)!=null?s:1e3)-((o=this.mediaTrackCapabilities.focusDistance.min)!=null?o:.01))+((c=this.mediaTrackCapabilities.focusDistance.min)!=null?c:.01);await t[0].applyConstraints({advanced:[{focusDistance:l}]});}}}async setFrameRate(e){var t,i,a;if(this.mediaStream&&(await this.waitForCapabilities(),(t=this.mediaTrackCapabilities)!=null&&t.frameRate)){let s=this.mediaStream.getVideoTracks();if(s.length>0&&typeof s[0].applyConstraints=="function"){let o=Math.min((i=this.mediaTrackCapabilities.frameRate.max)!=null?i:240,(a=e.max)!=null?a:240);await s[0].applyConstraints({advanced:[{frameRate:o}]});}}}setInitialCameraPosition(e){this.cameraPosition=e;}setInteractionOptions(e,t,i){this.torchToggleEnabled=e,this.tapToFocusEnabled=t,this.pinchToZoomEnabled=i;}setMirrorImageEnabled(e,t){this.selectedCamera&&(e?(this.videoElement.classList.add(n.MIRRORED_CLASS_NAME),this.canvas.classList.add(n.MIRRORED_CLASS_NAME)):(this.videoElement.classList.remove(n.MIRRORED_CLASS_NAME),this.canvas.classList.remove(n.MIRRORED_CLASS_NAME)),t&&this.mirrorImageOverrides.set(this.selectedCamera,e));}setPinchToZoomEnabled(e){this.pinchToZoomEnabled=e,this.mediaStream&&(this.pinchToZoomEnabled?this.enablePinchToZoomListeners():this.disablePinchToZoomListeners());}setSelectedCamera(e){this.selectedCamera=e;}setSelectedCameraSettings(e){this.selectedCameraSettings=e;}setTapToFocusEnabled(e){this.tapToFocusEnabled=e,this.mediaStream&&(this.tapToFocusEnabled?this.enableTapToFocusListeners():this.disableTapToFocusListeners());}async setTorchEnabled(e){var t;if(this.mediaStream&&((t=this.mediaTrackCapabilities)==null?void 0:t.torch)===true){this.torchEnabled=e;let i=this.mediaStream.getVideoTracks();i.length>0&&typeof i[0].applyConstraints=="function"&&await i[0].applyConstraints({advanced:[{torch:e}]});}}async setZoom(e){var t,i,a;if(this.mediaStream&&(await this.waitForCapabilities(),(t=this.mediaTrackCapabilities)!=null&&t.zoom)){let s=this.mediaStream.getVideoTracks();if(s.length>0&&typeof s[0].applyConstraints=="function"){let o=Math.max((i=this.mediaTrackCapabilities.zoom.min)!=null?i:1,Math.min(e,(a=this.mediaTrackCapabilities.zoom.max)!=null?a:16));await s[0].applyConstraints({advanced:[{zoom:o}]});}}}async setupCameras(){if(this.cameraSetupPromise)return this.cameraSetupPromise;let e=this.isVideoStreamPaused;return this.cameraSetupPromise=this.setupCamerasAndStream(),this.cameraSetupPromise.then(()=>{e||(this.isVideoStreamPaused=false);})}pauseStream(){if(this.mediaStream){for(let e of this.mediaStream.getVideoTracks())e.enabled=false;this.isVideoStreamPaused=true,a$3.debug("Paused camera video stream",this.mediaStream);}}resumeStream(){if(this.mediaStream){for(let e of this.mediaStream.getVideoTracks())e.enabled=true;this.isVideoStreamPaused=false,a$3.debug("Resumed camera video stream",this.mediaStream);}}async stopStream(e=false){this.activeCamera&&(this.activeCamera.currentResolution=void 0),this.activeCamera=void 0,this.torchEnabled=false,this.isVideoStreamPaused=false,this.mediaStream&&(a$3.debug(`Stop camera video stream access${e?" (abort access detection)":""}:`,this.mediaStream),a$3.debug("Stopping camera video stream access",this.mediaStream),document.removeEventListener("visibilitychange",this.checkCameraVideoStreamAccessIfVisibleListener),window.clearTimeout(this.cameraAccessTimeout),window.clearInterval(this.videoMetadataCheckInterval),window.clearTimeout(this.getCapabilitiesTimeout),window.clearTimeout(this.manualFocusWaitTimeout),window.clearTimeout(this.manualToAutofocusResumeTimeout),window.clearInterval(this.autofocusInterval),this.videoElement.pause(),await new Promise(t=>{setTimeout(()=>{var i,a,s;for(let o of (a=(i=this.mediaStream)==null?void 0:i.getVideoTracks())!=null?a:[])o.removeEventListener("ended",this.videoTrackEndedListener),o.stop();this.videoElement.srcObject=null,this._canvas2dContext&&this._canvas2dContext.clearRect(0,0,this.canvas.width,this.canvas.height),this.mediaStream=void 0,this.mediaTrackCapabilities=void 0,this.mediaTrackCapabilitiesPromise=void 0,this.mediaTrackCapabilitiesPromiseResolver=void 0,e||(s=this.abortedCameraInitializationResolveCallback)==null||s.call(this),t();},0);}));}stopVideoTracks(){if(this.mediaStream!=null)for(let e of this.mediaStream.getVideoTracks())e.stop();}async toggleTorch(){this.torchEnabled=!this.torchEnabled,await this.setTorchEnabled(this.torchEnabled);}updateCanvasVideoImage(){this.canvas2dContext.drawImage(this.videoElement,0,0);}async waitForCapabilities(){var e;return (e=this.mediaTrackCapabilitiesPromise)!=null?e:Promise.resolve()}setFrameReaderType(e){e!==this._frameReaderType&&(this._frameReaderType=e,a$3.log(a$3.Level.Debug,`Change frame reader type to ${this._frameReaderType} mode`));}async allowPictureInPicture(e){e?(this.videoElement.disablePictureInPicture=false,this.videoElement.removeAttribute("controlslist"),this.videoElement.removeAttribute("disablepictureinpicture")):(this.videoElement.disablePictureInPicture=true,this.videoElement.setAttribute("controlslist","nodownload"),this.videoElement.setAttribute("disablepictureinpicture","true")),await this.reinitializeCamera();}setFrameHandling(e){var t;this._synchronousFrameHandling=e,this._frameReaderOptions=this.getFrameReaderOptions(e),(t=this._glFrameReaders[this._frameReaderType])==null||t.dispose(),delete this._glFrameReaders[this._frameReaderType];}async setClipArea(e){if(this.activeCamera&&this.isVideoAndContextStateValid()){this.clipArea=e?this.frameRectFromViewRect(e):void 0,await this.initializeStreamForResolution(this.activeCamera,this.constraint,this.isVideoStreamPaused);return}this.clipArea=e;}frameRectFromViewRect(e){let t=this.videoElement.videoWidth/this.videoElement.clientWidth||1,i$1=this.videoElement.videoHeight/this.videoElement.clientHeight||1;return new f(new a$5(e.origin.x*t,e.origin.y*i$1),new i(e.size.width*t,e.size.height*i$1))}async accessAutoselectedCamera(e){let t=d.sortCamerasForCameraPosition(e,this.cameraPosition),i=t.shift();for(;i;)try{await this.initializeCameraWithSettings(i,this.selectedCameraSettings);return}catch(a){if(this.setSelectedCamera(),t.length>0){a$3.log(a$3.Level.Warn,"Couldn't access camera:",i,a),i=t.shift();continue}throw a}throw new a$4(n.noCameraErrorParameters)}getFrameReaderOptions(e){return e?{minPoolCapacity:0,maxPoolCapacity:1}:a$1.isDesktopDevice()?{maxPoolCapacity:2,minPoolCapacity:1}:{maxPoolCapacity:10,minPoolCapacity:3}}getFrameReader(){var t;if(this._glFrameReaders[this._frameReaderType])return this._glFrameReaders[this._frameReaderType];if(!this._canvasWebGLContext)return null;let e=(t=this._frameReaderOptions)!=null?t:this.getFrameReaderOptions(this._synchronousFrameHandling);switch(this._frameReaderType){case "GRAYSCALE":{this._glFrameReaders.GRAYSCALE=new a$6(this._canvasWebGLContext,e),this._glFrameReaders.RGBA=new b$1(this._canvasWebGLContext,{minPoolCapacity:1,maxPoolCapacity:2});break}case "RGBA":{this._glFrameReaders.RGBA=new b$1(this._canvasWebGLContext,e);break}default:b(this._frameReaderType);}return a$3.debug(`Created frame reader ${this._frameReaderType}`,e),this._glFrameReaders[this._frameReaderType]}async accessInitialCamera(){let e={position:this.cameraPosition,deviceId:"",label:""};try{await this.initializeCameraWithSettings(e,this.selectedCameraSettings);}catch(t){}finally{this.setSelectedCamera();}return e}recreateCanvas(){this.canvas.removeEventListener("webglcontextlost",this.handleWebGLContextLostListener),this._canvasWebGLContext=void 0,this._canvas2dContext=void 0;for(let t of Object.values(this._glFrameReaders))t==null||t.dispose();let e=document.createElement("canvas");e.addEventListener("webglcontextlost",this.handleWebGLContextLostListener),e.width=this.canvas.width,e.height=this.canvas.height,e.className=this.canvas.className,this.canvas=e;}captureImageFor2dContext(){if(!this.isVideoAndContextStateValid())return null;let{width:e,height:t}=this.canvas;return {colorType:"RGBA",data:this.canvas2dContext.getImageData(0,0,e,t).data,width:e,height:t}}areVideoAndWebGLSizeMismatching(){return this.canvasWebGLContext?this.canvasWebGLContext.drawingBufferWidth!==this.videoElement.videoWidth||this.canvasWebGLContext.drawingBufferHeight!==this.videoElement.videoHeight:true}captureImageForWebGLContext(){if(!this.isVideoAndContextStateValid()||!this.canvasWebGLContext||this.canvasWebGLContext.drawingBufferWidth<=2||this.canvasWebGLContext.drawingBufferHeight<=2||this.areVideoAndWebGLSizeMismatching()||this.getFrameReader()==null)return null;let e=this.getFrameReader().readFromSource(this.videoElement);if(e.data[3]!==255&&e.colorType==="RGBA"){if(a$3.log(a$3.Level.Warn,"Detected incorrect GPU accelerated WebGL image processing, switching to canvas mode"),this.recreateCanvas(),this.canvas2dContext==null)throw new Error("Unable to get 2d canvas context");return this.captureImage()}return e}async checkCameraAccess(e){return new Promise((t,i)=>{this.cameraAccessRejectCallback=a=>{a$3.log(a$3.Level.Debug,"Camera video stream access failure (video data load timeout):",e),this.gui.setCameraRecoveryVisible(true),i(a);},this.setCameraAccessTimeout();})}checkCameraVideoStreamAccessIfVisible(){document.visibilityState==="visible"&&(a$3.debug("Page is visible again, waiting for camera video stream start..."),document.removeEventListener("visibilitychange",this.checkCameraVideoStreamAccessIfVisibleListener),this.setCameraAccessTimeout());}async checkVideoMetadata(e){return new Promise((t,i)=>{this.videoElement.onloadeddata=()=>{if(this.videoElement.onloadeddata=null,window.clearTimeout(this.cameraAccessTimeout),this.videoElement.videoWidth>2&&this.videoElement.videoHeight>2&&this.videoElement.currentTime>0){this.updateActiveCameraCurrentResolution(e),a$3.log(a$3.Level.Debug,"Camera video stream access success:",e),t();return}let a=performance.now();window.clearInterval(this.videoMetadataCheckInterval),this.videoMetadataCheckInterval=window.setInterval(async()=>{if(this.videoElement.videoWidth<=2||this.videoElement.videoHeight<=2||this.videoElement.currentTime===0){if(performance.now()-a>n.videoMetadataCheckTimeoutMs){a$3.log(a$3.Level.Warn,"Camera video stream access failure (valid video metadata timeout):",e),window.clearInterval(this.videoMetadataCheckInterval),await this.stopStream(true),i(new a$4(n.notReadableErrorParameters));return}return}window.clearInterval(this.videoMetadataCheckInterval),this.updateActiveCameraCurrentResolution(e),a$3.log(a$3.Level.Debug,"Camera video stream access success:",e),t();},n.videoMetadataCheckIntervalMs);};})}disablePinchToZoomListeners(){this.videoElement.removeEventListener("touchstart",this.triggerZoomStartListener),this.videoElement.removeEventListener("touchmove",this.triggerZoomMoveListener);}disableTapToFocusListeners(){for(let e of ["touchend","mousedown"])this.videoElement.removeEventListener(e,this.triggerManualFocusListener);}emit(e,t){var a;let i=(a=this.listeners.get(e))!=null?a:[];for(let s of i)s(t);}enablePinchToZoomListeners(){this.videoElement.addEventListener("touchstart",this.triggerZoomStartListener),this.videoElement.addEventListener("touchmove",this.triggerZoomMoveListener);}enableTapToFocusListeners(){for(let e of ["touchend","mousedown"])this.videoElement.addEventListener(e,this.triggerManualFocusListener);}getActiveCamera(e,t,i){return e.length===1?e[0]:e.find(a=>a.deviceId===i||a.label!==""&&a.label===t)}getInitialCameraResolutionConstraint(e){var i;let t;switch((i=this.activeCameraSettings)==null?void 0:i.preferredResolution){case "uhd4k":{t=0;break}case "fullHd":{t=1;break}default:{t=2;break}}return t}async handleCameraInitializationError(e,t,i){if(!["OverconstrainedError","NotReadableError"].includes(i.name)||i.name==="NotReadableError"&&t===4)throw a$3.log(a$3.Level.Debug,"Camera video stream access failure (unrecoverable error)",e,i),i.name!=="NotAllowedError"&&d.markCameraAsInaccessible(e),i;if(i.name==="OverconstrainedError"&&t===4){if(e.deviceId==="")throw a$3.log(a$3.Level.Warn,"Camera video stream access failure (no camera with such type error)",e,i),i;a$3.log(a$3.Level.Warn,"Detected non-existent deviceId error, attempt to find and reaccess updated camera",e,i);let a=e.deviceId;if(await d.getCameras(true),a===e.deviceId)throw a$3.log(a$3.Level.Warn,"Camera video stream access failure (updated camera not found after non-existent deviceId error)",e,i),d.markCameraAsInaccessible(e),i;return a$3.log(a$3.Level.Warn,"Updated camera found (recovered from non-existent deviceId error), attempt to access it",e),this.initializeCameraForResolution(e)}return this.initializeCameraForResolution(e,t+1)}handleVideoResize(){if(!(this.videoElement.videoWidth<=2||this.videoElement.videoHeight<=2)){if(this.activeCamera&&this.updateActiveCameraCurrentResolution(this.activeCamera),this.canvasWebGLContext!=null){if(this.canvas.width===this.videoElement.videoWidth&&this.canvas.height===this.videoElement.videoHeight)return;this.canvas.width=this.videoElement.videoWidth,this.canvas.height=this.videoElement.videoHeight,this.canvasWebGLContext.viewport(0,0,this.canvasWebGLContext.drawingBufferWidth,this.canvasWebGLContext.drawingBufferHeight);}else if(this.canvas2dContext!=null){if(this.canvas.width===this.videoElement.videoWidth&&this.canvas.height===this.videoElement.videoHeight)return;this.canvas.width=this.videoElement.videoWidth,this.canvas.height=this.videoElement.videoHeight;}}}handleWebGLContextLost(){a$3.log(a$3.Level.Warn,"WebGL context has been lost, restoring..."),this._canvasWebGLContext=void 0,this.canvasWebGLContext?(this.handleVideoResize(),a$3.log(a$3.Level.Warn,"WebGL context restored")):a$3.log(a$3.Level.Error,"WebGL context restore failed");}async initializeCameraAndCheckUpdatedSettings(e){var t,i,a,s,o;try{if(await this.initializeCameraForResolution(e),this.selectedCameraSettings!==this.activeCameraSettings&&(this.selectedCameraSettings==null||this.activeCameraSettings==null||Object.keys(this.selectedCameraSettings).some(u=>{var b,f;return ((b=this.selectedCameraSettings)==null?void 0:b[u])!==((f=this.activeCameraSettings)==null?void 0:f[u])}))){this.activeCameraSettings=this.selectedCameraSettings,await this.initializeCameraAndCheckUpdatedSettings(e);return}this.activeCameraSettings&&this.activeCameraSettings.zoomFactor>1&&await this.setZoom(this.activeCameraSettings.zoomFactor);let c=(t=this.activeCameraSettings)==null?void 0:t.getProperty("minFrameRate"),d=(i=this.activeCameraSettings)==null?void 0:i.getProperty("maxFrameRate");(c!=null||d!=null)&&await this.setFrameRate({min:c,max:d});let l=(a=this.activeCameraSettings)==null?void 0:a.getProperty("manualLensPosition");l!=null&&await this.setFocus(l);let v=(s=this.activeCameraSettings)==null?void 0:s.getProperty("exposureTargetBias"),p=(o=this.activeCameraSettings)==null?void 0:o.getProperty("exposureDuration");(v!=null||p!=null)&&await this.setExposure({compensation:v,time:p});}finally{this.cameraInitializationPromise=void 0;}}async initializeCameraForResolution(e,t){var i;this.gui.setCameraRecoveryVisible(false),this.constraint=t!=null?t:this.getInitialCameraResolutionConstraint(e),this.mediaStream!=null&&e.deviceId!==""&&((i=this.activeCamera)==null?void 0:i.deviceId)===e.deviceId?await(a$1.isIPhone()?this.initializeStreamForResolution(e,this.constraint):this.updateStreamForResolution(e,this.constraint)):await this.initializeStreamForResolution(e,this.constraint);}async initializeStreamForResolution(e,t,i=false){var a;await this.stopStream();try{let s=(a=this.activeCameraSettings)==null?void 0:a.getProperty("preferredAspectRatio"),o=await d.accessCameraStream(e,t,s),c=await this.clipMediaStreamIfNeeded(o);if(a$3.log(a$3.Level.Debug,"Camera accessed, waiting for camera video stream start..."),typeof c.getVideoTracks()[0].getSettings=="function"){let d=c.getVideoTracks()[0].getSettings();if(d.width!=null&&d.height!=null&&(d.width===2||d.height===2)){if(a$3.log(a$3.Level.Debug,"Camera video stream access failure (invalid video metadata):",e),t===4)throw new a$4(n.notReadableErrorParameters);return await this.stopStream(),this.initializeStreamForResolution(e,t+1)}}this.mediaStream=c,i&&this.pauseStream();for(let d of this.mediaStream.getVideoTracks())d.addEventListener("ended",this.videoTrackEndedListener),d.addEventListener("mute",this.videoTrackMuteListener),d.addEventListener("unmute",this.videoTrackMuteListener);try{await this.setupCameraStreamVideo(e,c);}catch(d){if(t===4)throw d;return this.initializeStreamForResolution(e,t+1)}}catch(s){return this.handleCameraInitializationError(e,t,s)}}isVideoAndContextStateValid(){return this.videoElement.readyState===4&&this.videoElement.videoWidth>2&&this.videoElement.videoHeight>2&&this.canvas.width>2&&this.canvas.height>2}postStreamInitialization(){window.clearTimeout(this.getCapabilitiesTimeout),this.getCapabilitiesTimeout=window.setTimeout(()=>{this.storeStreamCapabilities(),this.setupAutofocus();},n.getCapabilitiesTimeoutMs);}async recoverStreamIfNeeded(){var t,i;let e=(t=this.mediaStream)==null?void 0:t.getVideoTracks();((i=e==null?void 0:e[0])==null?void 0:i.readyState)==="ended"&&await this.reinitializeCamera();}reportCameraProperties(e,t,i=true){this.emit("cameraProperties",{deviceId:e,isFrontFacing:t==="userFacing",hasAutofocus:i});}setCameraAccessTimeout(){window.clearTimeout(this.cameraAccessTimeout),this.cameraAccessTimeout=window.setTimeout(async()=>{var e;document.visibilityState==="visible"?(await this.stopStream(true),(e=this.cameraAccessRejectCallback)==null||e.call(this,new a$4(n.notReadableErrorParameters))):(a$3.debug("Page is currently not visible, delay camera video stream access detection"),document.addEventListener("visibilitychange",this.checkCameraVideoStreamAccessIfVisibleListener));},n.cameraAccessTimeoutMs);}setupAutofocus(){if(window.clearTimeout(this.manualFocusWaitTimeout),window.clearTimeout(this.manualToAutofocusResumeTimeout),this.mediaStream&&this.mediaTrackCapabilities){let e=this.mediaTrackCapabilities.focusMode;Array.isArray(e)&&!e.includes("continuous")&&e.includes("single-shot")&&(window.clearInterval(this.autofocusInterval),this.autofocusInterval=window.setInterval(this.triggerAutoFocus.bind(this),n.autofocusIntervalMs));}}async setupCameraStreamVideo(e,t){this.videoElement.addEventListener("loadedmetadata",this.postStreamInitializationListener),this.videoElement.addEventListener("resize",this.videoResizeListener),this.tapToFocusEnabled&&this.enableTapToFocusListeners(),this.pinchToZoomEnabled&&this.enablePinchToZoomListeners();let i=Promise.race([this.checkCameraAccess(e),this.checkVideoMetadata(e),new Promise(a=>{this.abortedCameraInitializationResolveCallback=a;})]);return this.videoElement.srcObject=t,this.videoElement.load(),await this.playVideo(),this.handleVideoResize(),this.reportCameraProperties(e.deviceId,e.position),i}async setupCamerasAndStream(){var e,t;try{let i;this.selectedCamera==null&&(i=await this.accessInitialCamera());let a=await d.getCameras(false,true),s=(t=(e=this.mediaStream)==null?void 0:e.getVideoTracks()[0])==null?void 0:t.getSettings().deviceId;if(this.mediaStream&&i){let o=this.getActiveCamera(a,i.label,s);if(o){if(d.adjustCameraFromMediaStream(this.mediaStream,o),a$1.isDesktopDevice()&&(d.setMainCameraForPositionOverridesOnDesktop(this.cameraPosition,o),d.setMainCameraForPositionOverridesOnDesktop(o.position,o)),a.length===1||d.getMainCameraForPosition(a,this.cameraPosition)===o){a$3.debug("Initial camera access was correct (main camera), keep camera:",o),this.setSelectedCamera(o),this.updateActiveCameraCurrentResolution(o),await this.recoverStreamIfNeeded();return}a$3.debug("Initial camera access was incorrect (not main camera), change camera",{...i,deviceId:s});}else a$3.debug("Initial camera access was incorrect (unknown camera), change camera",{...i,deviceId:s});}if(this.selectedCamera==null){await this.accessAutoselectedCamera(a);return}await this.initializeCameraWithSettings(this.selectedCamera,this.selectedCameraSettings);}finally{this.cameraSetupPromise=void 0;}}storeStreamCapabilities(){var e;if(this.mediaStream){let t=this.mediaStream.getVideoTracks();t.length>0&&typeof t[0].getCapabilities=="function"&&(this.mediaTrackCapabilities=t[0].getCapabilities()),this.mediaTrackCapabilitiesPromiseResolver&&this.mediaTrackCapabilitiesPromiseResolver();}this.activeCamera&&this.reportCameraProperties(this.activeCamera.deviceId,this.activeCamera.position,((e=this.mediaTrackCapabilities)==null?void 0:e.focusMode)==null||this.mediaTrackCapabilities.focusMode.includes("continuous"));}async triggerAutoFocus(){await this.triggerFocusMode("single-shot");}async triggerFocusMode(e){if(this.mediaStream){let t=this.mediaStream.getVideoTracks();if(t.length>0&&typeof t[0].applyConstraints=="function")try{await t[0].applyConstraints({advanced:[{focusMode:e}]});}catch(i){}}}async triggerManualFocus(e){if(e){if(e.preventDefault(),e.type==="touchend"&&e.touches.length>0)return;if(this.pinchToZoomDistance!=null){this.pinchToZoomDistance=void 0;return}}if(window.clearTimeout(this.manualFocusWaitTimeout),window.clearTimeout(this.manualToAutofocusResumeTimeout),!this.mediaStream||!this.mediaTrackCapabilities)return;let t=this.mediaTrackCapabilities.focusMode;Array.isArray(t)&&t.includes("single-shot")&&(t.includes("continuous")&&t.includes("manual")?await this.triggerManualFocusForContinuous():t.includes("continuous")||await this.triggerManualFocusForSingleShot());}async triggerManualFocusForContinuous(){var i;if(!this.mediaStream)return;this.manualToAutofocusResumeTimeout=window.setTimeout(async()=>{await this.triggerFocusMode("continuous");},n.manualToAutofocusResumeTimeoutMs);let e=true,t=this.mediaStream.getVideoTracks();t.length>0&&typeof t[0].getConstraints=="function"&&(e=((i=t[0].getConstraints().advanced)==null?void 0:i.some(a=>a.focusMode==="manual"))===true),e?(await this.triggerFocusMode("continuous"),this.manualFocusWaitTimeout=window.setTimeout(async()=>{await this.triggerFocusMode("manual");},n.manualFocusWaitTimeoutMs)):await this.triggerFocusMode("manual");}async triggerManualFocusForSingleShot(){window.clearInterval(this.autofocusInterval),this.manualToAutofocusResumeTimeout=window.setTimeout(()=>{this.autofocusInterval=window.setInterval(this.triggerAutoFocus.bind(this),n.autofocusIntervalMs);},n.manualToAutofocusResumeTimeoutMs);try{await this.triggerFocusMode("single-shot");}catch(e){}}async triggerZoomMove(e){this.pinchToZoomDistance==null||(e==null?void 0:e.touches.length)!==2||e.preventDefault();}triggerZoomStart(e){var a,s,o,c;if((e==null?void 0:e.touches.length)!==2||(e.preventDefault(),this.pinchToZoomDistance=Math.hypot((e.touches[1].screenX-e.touches[0].screenX)/screen.width,(e.touches[1].screenY-e.touches[0].screenY)/screen.height),!this.mediaStream||!((a=this.mediaTrackCapabilities)!=null&&a.zoom)))return;let t=this.mediaStream.getVideoTracks();if(t.length===0||typeof t[0].getConstraints!="function")return;this.pinchToZoomInitialZoom=(s=this.mediaTrackCapabilities.zoom.min)!=null?s:1;let i=t[0].getConstraints();if(i.advanced){let d=(o=i.advanced.find(l=>"zoom"in l))==null?void 0:o.zoom;d!=null&&(this.pinchToZoomInitialZoom=typeof d=="number"?d:(c=d.ideal)!=null?c:1);}}updateActiveCameraCurrentResolution(e){this.videoElement.videoWidth>2&&this.videoElement.videoHeight>2&&(e.currentResolution={width:this.videoElement.videoWidth,height:this.videoElement.videoHeight}),e.deviceId!==""&&(this.activeCamera=e,this.setMirrorImageEnabled(this.isMirrorImageEnabled(),false));}async updateStreamForResolution(e,t){var i;if(this.mediaStream==null)await this.initializeCameraForResolution(e,t);else try{let a=(i=this.activeCameraSettings)==null?void 0:i.getProperty("preferredAspectRatio");a$3.debug("Setting new resolution for active camera video stream..."),await this.mediaStream.getVideoTracks()[0].applyConstraints(d.getUserMediaVideoParameters(t,a)),await new Promise(o=>{this.videoElement.addEventListener("timeupdate",()=>{o();},{once:true});});let s=this.mediaStream.getVideoTracks()[0].getSettings();a$3.debug("New active camera video stream resolution set",{width:s.width,height:s.height});}catch(a){if(t===4)throw a;await this.updateStreamForResolution(e,t+1);}}async videoTrackEndedRecovery(){if(document.visibilityState==="visible")try{a$3.debug('Detected video track "ended" event, try to reinitialize camera'),await this.reinitializeCamera();}catch(e){}else a$3.debug("Page is currently not visible, delay camera reinitialization until visible"),document.addEventListener("visibilitychange",this.checkCameraVideoStreamAccessIfVisibleListener);}videoTrackMuteRecovery(e){if(this.videoElement.onloadeddata!=null){a$3.debug(`Detected video track "${e.type}" event, delay camera video stream access detection`),this.setCameraAccessTimeout();return}let t=e.type==="mute";t!==this.gui.isCameraRecoveryVisible()&&(a$3.debug(`Detected video track "${e.type}" event, ${t?"enable":"disable"} camera recovery`),this.gui.setCameraRecoveryVisible(t));}async clipMediaStreamIfNeeded(e){if(!this.clipArea)return e;let t=this.videoElement.cloneNode();t.srcObject=e,t.load();let i=document.createElement("canvas");i.width=this.clipArea.size.width,i.height=this.clipArea.size.height;let a=i.getContext("2d",{alpha:false,willReadFrequently:false});return a?(t.addEventListener("play",this.drawClippedFrame.bind(this,this.clipArea,t,a),{once:true}),t.addEventListener("pause",this.cleanupClippedStream.bind(this,t),{once:true}),await t.play(),i.captureStream()):e}drawClippedFrame(e,t,i){i.drawImage(t,e.origin.x,e.origin.y,e.size.width,e.size.height,0,0,e.size.width,e.size.height),this.clippedFrameRequestID=this.requestVideoFrame(this.drawClippedFrame.bind(this,e,t,i),t);}cleanupClippedStream(e){this.clippedFrameRequestID&&(this.cancelVideoFrame(this.clippedFrameRequestID,e),this.clippedFrameRequestID=void 0);}connectedCallback(e){e.replaceWith(this.videoElement),this.canvas.addEventListener("webglcontextlost",this.handleWebGLContextLostListener),this.videoElement.addEventListener("pause",this.handleVideoPauseHandler),this.playVideo();}disconnectedCallback(){this.canvas.removeEventListener("webglcontextlost",this.handleWebGLContextLostListener),this.videoElement.removeEventListener("pause",this.handleVideoPauseHandler),this.videoElement.remove();}getVideoElement(){return this.videoElement}handleVideoPause(){this.playVideo();}};n.autofocusIntervalMs=1500,n.cameraAccessTimeoutMs=4e3,n.getCapabilitiesTimeoutMs=500,n.manualFocusWaitTimeoutMs=400,n.manualToAutofocusResumeTimeoutMs=5e3,n.noCameraErrorParameters={name:"NoCameraAvailableError",message:"No camera available"},n.notReadableErrorParameters={name:"NotReadableError",message:"Could not initialize camera correctly"},n.videoMetadataCheckIntervalMs=50,n.videoMetadataCheckTimeoutMs=4e3,n.MIRRORED_CLASS_NAME=a$7.MIRRORED_CLASS_NAME,n._instance=null;var k=n;export{P as a,F as b,x as c,k as d};
|
|
1
|
+
import {a as a$6}from'./chunk-L7LE453T.js';import {b as b$1}from'./chunk-PAPLDTB7.js';import {a as a$2}from'./chunk-ZKROZLQ4.js';import {b}from'./chunk-FTD535WI.js';import {a}from'./chunk-R6E4CT22.js';import {a as a$7}from'./chunk-VQ7LLVHQ.js';import {d}from'./chunk-OQ4XCKFQ.js';import {a as a$4}from'./chunk-QCZSSQAQ.js';import {a as a$1}from'./chunk-UCD6YLP3.js';import {a as a$3}from'./chunk-XR65N6EG.js';import {f,a as a$5,i}from'./chunk-TPQTY3KB.js';var P=(a=>(a.CONTINUOUS="continuous",a.MANUAL="manual",a.NONE="none",a.SINGLE_SHOT="single-shot",a))(P||{}),F=(s=>(s[s.ULTRA_HD=0]="ULTRA_HD",s[s.FULL_HD=1]="FULL_HD",s[s.HD=2]="HD",s[s.SD=3]="SD",s[s.NONE=4]="NONE",s))(F||{}),x=(t=>(t.CAMERA_PROPERTIES="cameraProperties",t.CAMERA_ACCESS_ERROR="cameraAccessError",t))(x||{}),n=class n{constructor(){this.constraint=4;this.checkCameraVideoStreamAccessIfVisibleListener=this.checkCameraVideoStreamAccessIfVisible.bind(this);this.handleWebGLContextLostListener=this.handleWebGLContextLost.bind(this);this.listeners=new Map;this.mirrorImageOverrides=new Map;this.postStreamInitializationListener=this.postStreamInitialization.bind(this);this.triggerManualFocusListener=this.triggerManualFocus.bind(this);this.triggerZoomMoveListener=this.triggerZoomMove.bind(this);this.triggerZoomStartListener=this.triggerZoomStart.bind(this);this.videoResizeListener=a(this.handleVideoResize.bind(this),500);this.videoTrackEndedListener=this.videoTrackEndedRecovery.bind(this);this.videoTrackMuteListener=this.videoTrackMuteRecovery.bind(this);this._synchronousFrameHandling=false;this._glFrameReaders={GRAYSCALE:null,RGBA:null};this._frameReaderType="RGBA";this.isVideoStreamPaused=false;this.handleVideoPauseHandler=this.handleVideoPause.bind(this);this.cameraPosition="worldFacing",this.gui={isCameraRecoveryVisible:()=>false,setCameraRecoveryVisible:()=>{}},this.isWebGLSupported=!a$1.checkBrowserCompatibility().missingFeatures.includes("webGL"),this.videoElement=document.createElement("video"),this.videoElement.autoplay=true,this.videoElement.playsInline=true,this.videoElement.muted=true,this.videoElement.style.opacity="0",this.videoElement.poster=a$2,this.canvas=document.createElement("canvas"),this.canvas.addEventListener("webglcontextlost",this.handleWebGLContextLostListener);}get mediaStream(){return this._mediaStream}set mediaStream(e){this._mediaStream=e,e&&(this.mediaTrackCapabilitiesPromise=new Promise(t=>{this.mediaTrackCapabilitiesPromiseResolver=t;}));}get synchronousFrameHandling(){return this._synchronousFrameHandling}get canvas2dContext(){return this._canvas2dContext||(this._canvas2dContext=this.canvas.getContext("2d",{willReadFrequently:true}),this._canvas2dContext==null&&a$3.warn("Unable to get 2d canvas context"),this.handleVideoResize()),this._canvas2dContext}get canvasWebGLContext(){var e;if(!this._canvas2dContext&&!this._canvasWebGLContext){if(!this.isWebGLSupported){a$3.warn("WebGL context not supported, falling back to 2d canvas context. This may impact the scanning performance.");return}let t=(e=this.canvas.getContext("webgl",{alpha:false,antialias:false}))!=null?e:this.canvas.getContext("experimental-webgl",{alpha:false,antialias:false});t!=null&&(this._canvasWebGLContext=t,this.handleVideoResize());}return this._canvasWebGLContext}static instance(){return n._instance==null&&(n._instance=new n),n._instance}recycle(e){var t;(t=this.getFrameReader())==null||t.recycle(e);}getCurrentFrame(){var e;return (e=this._glFrameReaders.RGBA)==null?void 0:e.readFromSource(this.videoElement)}requestVideoFrame(e,t=this.videoElement){return "requestVideoFrameCallback"in HTMLVideoElement.prototype?t.requestVideoFrameCallback(e):requestAnimationFrame(e)}cancelVideoFrame(e,t=this.videoElement){if("cancelVideoFrameCallback"in HTMLVideoElement.prototype){t.cancelVideoFrameCallback(e);return}cancelAnimationFrame(e);}addListener(e,t){var a;let i=(a=this.listeners.get(e))!=null?a:[];i.includes(t)||this.listeners.set(e,[...i,t]);}async applyCameraSettings(e){if(this.selectedCameraSettings=e,this.activeCamera==null)throw new a$4(n.noCameraErrorParameters);return this.initializeCameraWithSettings(this.activeCamera,e)}captureImage(){var e;if(((e=this.mediaStream)==null?void 0:e.active)!=null){if(this.canvasWebGLContext!=null)return this.captureImageForWebGLContext();if(this.canvas2dContext!=null)return this.captureImageFor2dContext()}return null}async initializeCameraWithSettings(e,t){if(this.cameraInitializationPromise&&await this.cameraInitializationPromise,e==null)throw new a$4(n.noCameraErrorParameters);return this.setSelectedCamera(e),this.selectedCameraSettings=t,this.activeCameraSettings=t,this.cameraInitializationPromise=this.initializeCameraAndCheckUpdatedSettings(e),this.cameraInitializationPromise}isMirrorImageEnabled(){if(this.selectedCamera&&this.activeCamera){let e=this.mirrorImageOverrides.get(this.activeCamera);return e!=null?e:this.activeCamera.position==="userFacing"}return false}isPinchToZoomEnabled(){return this.pinchToZoomEnabled}isTapToFocusEnabled(){return this.tapToFocusEnabled}async isTorchAvailable(){var e;return this.mediaStream?(await this.waitForCapabilities(),((e=this.mediaTrackCapabilities)==null?void 0:e.torch)===true):false}async playVideo(){return new Promise(e=>{this._canvas2dContext&&this._canvas2dContext.clearRect(0,0,this.canvas.width,this.canvas.height);let t=this.videoElement.play();t==null?e():t.then(e).catch(()=>{e();});})}async reinitializeCamera(){if(this.activeCamera==null)a$3.debug("Camera reinitialization delayed");else {a$3.debug("Reinitialize camera:",this.activeCamera);try{let e=this.activeCamera;await this.stopStream(),await this.initializeCameraWithSettings(e,this.activeCameraSettings);}catch(e){throw a$3.warn("Couldn't access camera:",this.activeCamera,e),this.emit("cameraAccessError",e),e}}}removeListener(e,t){var s;let a=((s=this.listeners.get(e))!=null?s:[]).filter(o=>o!==t);this.listeners.set(e,a);}async setCameraPosition(e){var i;this.setInitialCameraPosition(e);let t=d.getMainCameraForPosition(await d.getCameras(),e);if(t&&t.deviceId!==((i=this.selectedCamera)==null?void 0:i.deviceId))return this.initializeCameraWithSettings(t,this.selectedCameraSettings)}async setExposure(e){var a,s,o,c,d,l,v,p;let t=(s=(a=this.mediaStream)==null?void 0:a.getVideoTracks())!=null?s:[];if(t.length===0||typeof t[0].applyConstraints!="function")return;await this.waitForCapabilities();let i=e.time!=null&&e.time>0?"manual":"continuous";if(((c=(o=this.mediaTrackCapabilities)==null?void 0:o.exposureMode)==null?void 0:c.includes(i))===true){if(await t[0].applyConstraints({advanced:[{exposureMode:i}]}),e.time!=null&&e.time>0&&this.mediaTrackCapabilities.exposureTime){let u=Math.max((d=this.mediaTrackCapabilities.exposureTime.min)!=null?d:.01,Math.min(e.time,(l=this.mediaTrackCapabilities.exposureTime.max)!=null?l:1e5));await t[0].applyConstraints({advanced:[{exposureTime:u}]});}else if(e.compensation!=null&&i==="continuous"&&this.mediaTrackCapabilities.exposureCompensation){let u=Math.max((v=this.mediaTrackCapabilities.exposureCompensation.min)!=null?v:-10,Math.min(e.compensation,(p=this.mediaTrackCapabilities.exposureCompensation.max)!=null?p:10));await t[0].applyConstraints({advanced:[{exposureCompensation:u}]});}}}async setFocus(e){var i,a,s,o,c;if(!this.mediaStream)return;let t=this.mediaStream.getVideoTracks();if(t.length>0&&typeof t[0].applyConstraints=="function"){await this.waitForCapabilities();let d=e>=0?"manual":"continuous";if(((a=(i=this.mediaTrackCapabilities)==null?void 0:i.focusMode)==null?void 0:a.includes(d))===true&&(await t[0].applyConstraints({advanced:[{focusMode:d}]}),d==="manual"&&this.mediaTrackCapabilities.focusDistance)){let l=Math.max(0,Math.min(e,1))*(((s=this.mediaTrackCapabilities.focusDistance.max)!=null?s:1e3)-((o=this.mediaTrackCapabilities.focusDistance.min)!=null?o:.01))+((c=this.mediaTrackCapabilities.focusDistance.min)!=null?c:.01);await t[0].applyConstraints({advanced:[{focusDistance:l}]});}}}async setFrameRate(e){var t,i,a;if(this.mediaStream&&(await this.waitForCapabilities(),(t=this.mediaTrackCapabilities)!=null&&t.frameRate)){let s=this.mediaStream.getVideoTracks();if(s.length>0&&typeof s[0].applyConstraints=="function"){let o=Math.min((i=this.mediaTrackCapabilities.frameRate.max)!=null?i:240,(a=e.max)!=null?a:240);await s[0].applyConstraints({advanced:[{frameRate:o}]});}}}setInitialCameraPosition(e){this.cameraPosition=e;}setInteractionOptions(e,t,i){this.torchToggleEnabled=e,this.tapToFocusEnabled=t,this.pinchToZoomEnabled=i;}setMirrorImageEnabled(e,t){this.selectedCamera&&(e?(this.videoElement.classList.add(n.MIRRORED_CLASS_NAME),this.canvas.classList.add(n.MIRRORED_CLASS_NAME)):(this.videoElement.classList.remove(n.MIRRORED_CLASS_NAME),this.canvas.classList.remove(n.MIRRORED_CLASS_NAME)),t&&this.mirrorImageOverrides.set(this.selectedCamera,e));}setPinchToZoomEnabled(e){this.pinchToZoomEnabled=e,this.mediaStream&&(this.pinchToZoomEnabled?this.enablePinchToZoomListeners():this.disablePinchToZoomListeners());}setSelectedCamera(e){this.selectedCamera=e;}setSelectedCameraSettings(e){this.selectedCameraSettings=e;}setTapToFocusEnabled(e){this.tapToFocusEnabled=e,this.mediaStream&&(this.tapToFocusEnabled?this.enableTapToFocusListeners():this.disableTapToFocusListeners());}async setTorchEnabled(e){var t;if(this.mediaStream&&((t=this.mediaTrackCapabilities)==null?void 0:t.torch)===true){this.torchEnabled=e;let i=this.mediaStream.getVideoTracks();i.length>0&&typeof i[0].applyConstraints=="function"&&await i[0].applyConstraints({advanced:[{torch:e}]});}}async setZoom(e){var t,i,a;if(this.mediaStream&&(await this.waitForCapabilities(),(t=this.mediaTrackCapabilities)!=null&&t.zoom)){let s=this.mediaStream.getVideoTracks();if(s.length>0&&typeof s[0].applyConstraints=="function"){let o=Math.max((i=this.mediaTrackCapabilities.zoom.min)!=null?i:1,Math.min(e,(a=this.mediaTrackCapabilities.zoom.max)!=null?a:16));await s[0].applyConstraints({advanced:[{zoom:o}]});}}}async setupCameras(){if(this.cameraSetupPromise)return this.cameraSetupPromise;let e=this.isVideoStreamPaused;return this.cameraSetupPromise=this.setupCamerasAndStream(),this.cameraSetupPromise.then(()=>{e||(this.isVideoStreamPaused=false);})}pauseStream(){if(this.mediaStream){for(let e of this.mediaStream.getVideoTracks())e.enabled=false;this.isVideoStreamPaused=true,a$3.debug("Paused camera video stream",this.mediaStream);}}resumeStream(){if(this.mediaStream){for(let e of this.mediaStream.getVideoTracks())e.enabled=true;this.isVideoStreamPaused=false,a$3.debug("Resumed camera video stream",this.mediaStream);}}async stopStream(e=false){this.activeCamera&&(this.activeCamera.currentResolution=void 0),this.activeCamera=void 0,this.torchEnabled=false,this.isVideoStreamPaused=false,this.mediaStream&&(a$3.debug(`Stop camera video stream access${e?" (abort access detection)":""}:`,this.mediaStream),a$3.debug("Stopping camera video stream access",this.mediaStream),document.removeEventListener("visibilitychange",this.checkCameraVideoStreamAccessIfVisibleListener),window.clearTimeout(this.cameraAccessTimeout),window.clearInterval(this.videoMetadataCheckInterval),window.clearTimeout(this.getCapabilitiesTimeout),window.clearTimeout(this.manualFocusWaitTimeout),window.clearTimeout(this.manualToAutofocusResumeTimeout),window.clearInterval(this.autofocusInterval),this.videoElement.pause(),await new Promise(t=>{setTimeout(()=>{var i,a,s;for(let o of (a=(i=this.mediaStream)==null?void 0:i.getVideoTracks())!=null?a:[])o.removeEventListener("ended",this.videoTrackEndedListener),o.stop();this.videoElement.srcObject=null,this._canvas2dContext&&this._canvas2dContext.clearRect(0,0,this.canvas.width,this.canvas.height),this.mediaStream=void 0,this.mediaTrackCapabilities=void 0,this.mediaTrackCapabilitiesPromise=void 0,this.mediaTrackCapabilitiesPromiseResolver=void 0,e||(s=this.abortedCameraInitializationResolveCallback)==null||s.call(this),t();},0);}));}stopVideoTracks(){if(this.mediaStream!=null)for(let e of this.mediaStream.getVideoTracks())e.stop();}async toggleTorch(){this.torchEnabled=!this.torchEnabled,await this.setTorchEnabled(this.torchEnabled);}updateCanvasVideoImage(){this.canvas2dContext.drawImage(this.videoElement,0,0);}async waitForCapabilities(){var e;return (e=this.mediaTrackCapabilitiesPromise)!=null?e:Promise.resolve()}setFrameReaderType(e){e!==this._frameReaderType&&(this._frameReaderType=e,a$3.log(a$3.Level.Debug,`Change frame reader type to ${this._frameReaderType} mode`));}async allowPictureInPicture(e){e?(this.videoElement.disablePictureInPicture=false,this.videoElement.removeAttribute("controlslist"),this.videoElement.removeAttribute("disablepictureinpicture")):(this.videoElement.disablePictureInPicture=true,this.videoElement.setAttribute("controlslist","nodownload"),this.videoElement.setAttribute("disablepictureinpicture","true")),await this.reinitializeCamera();}setFrameHandling(e){var t;this._synchronousFrameHandling=e,this._frameReaderOptions=this.getFrameReaderOptions(e),(t=this._glFrameReaders[this._frameReaderType])==null||t.dispose(),delete this._glFrameReaders[this._frameReaderType];}async setClipArea(e){if(this.activeCamera&&this.isVideoAndContextStateValid()){this.clipArea=e?this.frameRectFromViewRect(e):void 0,await this.initializeStreamForResolution(this.activeCamera,this.constraint,this.isVideoStreamPaused);return}this.clipArea=e;}frameRectFromViewRect(e){let t=this.videoElement.videoWidth/this.videoElement.clientWidth||1,i$1=this.videoElement.videoHeight/this.videoElement.clientHeight||1;return new f(new a$5(e.origin.x*t,e.origin.y*i$1),new i(e.size.width*t,e.size.height*i$1))}async accessAutoselectedCamera(e){let t=d.sortCamerasForCameraPosition(e,this.cameraPosition),i=t.shift();for(;i;)try{await this.initializeCameraWithSettings(i,this.selectedCameraSettings);return}catch(a){if(this.setSelectedCamera(),t.length>0){a$3.log(a$3.Level.Warn,"Couldn't access camera:",i,a),i=t.shift();continue}throw a}throw new a$4(n.noCameraErrorParameters)}getFrameReaderOptions(e){return e?{minPoolCapacity:0,maxPoolCapacity:1}:a$1.isDesktopDevice()?{maxPoolCapacity:2,minPoolCapacity:1}:{maxPoolCapacity:10,minPoolCapacity:3}}getFrameReader(){var t;if(this._glFrameReaders[this._frameReaderType])return this._glFrameReaders[this._frameReaderType];if(!this._canvasWebGLContext)return null;let e=(t=this._frameReaderOptions)!=null?t:this.getFrameReaderOptions(this._synchronousFrameHandling);switch(this._frameReaderType){case "GRAYSCALE":{this._glFrameReaders.GRAYSCALE=new a$6(this._canvasWebGLContext,e),this._glFrameReaders.RGBA=new b$1(this._canvasWebGLContext,{minPoolCapacity:1,maxPoolCapacity:2});break}case "RGBA":{this._glFrameReaders.RGBA=new b$1(this._canvasWebGLContext,e);break}default:b(this._frameReaderType);}return a$3.debug(`Created frame reader ${this._frameReaderType}`,e),this._glFrameReaders[this._frameReaderType]}async accessInitialCamera(){let e={position:this.cameraPosition,deviceId:"",label:""};try{await this.initializeCameraWithSettings(e,this.selectedCameraSettings);}catch(t){}finally{this.setSelectedCamera();}return e}recreateCanvas(){this.canvas.removeEventListener("webglcontextlost",this.handleWebGLContextLostListener),this._canvasWebGLContext=void 0,this._canvas2dContext=void 0;for(let t of Object.values(this._glFrameReaders))t==null||t.dispose();let e=document.createElement("canvas");e.addEventListener("webglcontextlost",this.handleWebGLContextLostListener),e.width=this.canvas.width,e.height=this.canvas.height,e.className=this.canvas.className,this.canvas=e;}captureImageFor2dContext(){if(!this.isVideoAndContextStateValid())return null;let{width:e,height:t}=this.canvas;return {colorType:"RGBA",data:this.canvas2dContext.getImageData(0,0,e,t).data,width:e,height:t}}areVideoAndWebGLSizeMismatching(){return this.canvasWebGLContext?this.canvasWebGLContext.drawingBufferWidth!==this.videoElement.videoWidth||this.canvasWebGLContext.drawingBufferHeight!==this.videoElement.videoHeight:true}captureImageForWebGLContext(){if(!this.isVideoAndContextStateValid()||!this.canvasWebGLContext||this.canvasWebGLContext.drawingBufferWidth<=2||this.canvasWebGLContext.drawingBufferHeight<=2||this.areVideoAndWebGLSizeMismatching()||this.getFrameReader()==null)return null;let e=this.getFrameReader().readFromSource(this.videoElement);if(e.data[3]!==255&&e.colorType==="RGBA"){if(a$3.log(a$3.Level.Warn,"Detected incorrect GPU accelerated WebGL image processing, switching to canvas mode"),this.recreateCanvas(),this.canvas2dContext==null)throw new Error("Unable to get 2d canvas context");return this.captureImage()}return e}async checkCameraAccess(e){return new Promise((t,i)=>{this.cameraAccessRejectCallback=a=>{a$3.log(a$3.Level.Debug,"Camera video stream access failure (video data load timeout):",e),this.gui.setCameraRecoveryVisible(true),i(a);},this.setCameraAccessTimeout();})}checkCameraVideoStreamAccessIfVisible(){document.visibilityState==="visible"&&(a$3.debug("Page is visible again, waiting for camera video stream start..."),document.removeEventListener("visibilitychange",this.checkCameraVideoStreamAccessIfVisibleListener),this.setCameraAccessTimeout());}async checkVideoMetadata(e){return new Promise((t,i)=>{this.videoElement.onloadeddata=()=>{if(this.videoElement.onloadeddata=null,window.clearTimeout(this.cameraAccessTimeout),this.videoElement.videoWidth>2&&this.videoElement.videoHeight>2&&this.videoElement.currentTime>0){this.updateActiveCameraCurrentResolution(e),a$3.log(a$3.Level.Debug,"Camera video stream access success:",e),t();return}let a=performance.now();window.clearInterval(this.videoMetadataCheckInterval),this.videoMetadataCheckInterval=window.setInterval(async()=>{if(this.videoElement.videoWidth<=2||this.videoElement.videoHeight<=2||this.videoElement.currentTime===0){if(performance.now()-a>n.videoMetadataCheckTimeoutMs){a$3.log(a$3.Level.Warn,"Camera video stream access failure (valid video metadata timeout):",e),window.clearInterval(this.videoMetadataCheckInterval),await this.stopStream(true),i(new a$4(n.notReadableErrorParameters));return}return}window.clearInterval(this.videoMetadataCheckInterval),this.updateActiveCameraCurrentResolution(e),a$3.log(a$3.Level.Debug,"Camera video stream access success:",e),t();},n.videoMetadataCheckIntervalMs);};})}disablePinchToZoomListeners(){this.videoElement.removeEventListener("touchstart",this.triggerZoomStartListener),this.videoElement.removeEventListener("touchmove",this.triggerZoomMoveListener);}disableTapToFocusListeners(){for(let e of ["touchend","mousedown"])this.videoElement.removeEventListener(e,this.triggerManualFocusListener);}emit(e,t){var a;let i=(a=this.listeners.get(e))!=null?a:[];for(let s of i)s(t);}enablePinchToZoomListeners(){this.videoElement.addEventListener("touchstart",this.triggerZoomStartListener),this.videoElement.addEventListener("touchmove",this.triggerZoomMoveListener);}enableTapToFocusListeners(){for(let e of ["touchend","mousedown"])this.videoElement.addEventListener(e,this.triggerManualFocusListener);}getActiveCamera(e,t,i){return e.length===1?e[0]:e.find(a=>a.deviceId===i||a.label!==""&&a.label===t)}getInitialCameraResolutionConstraint(e){var i;let t;switch((i=this.activeCameraSettings)==null?void 0:i.preferredResolution){case "uhd4k":{t=0;break}case "fullHd":{t=1;break}default:{t=2;break}}return t}async handleCameraInitializationError(e,t,i){if(!["OverconstrainedError","NotReadableError"].includes(i.name)||i.name==="NotReadableError"&&t===4)throw a$3.log(a$3.Level.Debug,"Camera video stream access failure (unrecoverable error)",e,i),i.name!=="NotAllowedError"&&d.markCameraAsInaccessible(e),i;if(i.name==="OverconstrainedError"&&t===4){if(e.deviceId==="")throw a$3.log(a$3.Level.Warn,"Camera video stream access failure (no camera with such type error)",e,i),i;a$3.log(a$3.Level.Warn,"Detected non-existent deviceId error, attempt to find and reaccess updated camera",e,i);let a=e.deviceId;if(await d.getCameras(true),a===e.deviceId)throw a$3.log(a$3.Level.Warn,"Camera video stream access failure (updated camera not found after non-existent deviceId error)",e,i),d.markCameraAsInaccessible(e),i;return a$3.log(a$3.Level.Warn,"Updated camera found (recovered from non-existent deviceId error), attempt to access it",e),this.initializeCameraForResolution(e)}return this.initializeCameraForResolution(e,t+1)}handleVideoResize(){if(!(this.videoElement.videoWidth<=2||this.videoElement.videoHeight<=2)){if(this.activeCamera&&this.updateActiveCameraCurrentResolution(this.activeCamera),this.canvasWebGLContext!=null){if(this.canvas.width===this.videoElement.videoWidth&&this.canvas.height===this.videoElement.videoHeight)return;this.canvas.width=this.videoElement.videoWidth,this.canvas.height=this.videoElement.videoHeight,this.canvasWebGLContext.viewport(0,0,this.canvasWebGLContext.drawingBufferWidth,this.canvasWebGLContext.drawingBufferHeight);}else if(this.canvas2dContext!=null){if(this.canvas.width===this.videoElement.videoWidth&&this.canvas.height===this.videoElement.videoHeight)return;this.canvas.width=this.videoElement.videoWidth,this.canvas.height=this.videoElement.videoHeight;}}}handleWebGLContextLost(){a$3.log(a$3.Level.Warn,"WebGL context has been lost, restoring..."),this._canvasWebGLContext=void 0,this.canvasWebGLContext?(this.handleVideoResize(),a$3.log(a$3.Level.Warn,"WebGL context restored")):a$3.log(a$3.Level.Error,"WebGL context restore failed");}async initializeCameraAndCheckUpdatedSettings(e){var t,i,a,s,o;try{if(await this.initializeCameraForResolution(e),this.selectedCameraSettings!==this.activeCameraSettings&&(this.selectedCameraSettings==null||this.activeCameraSettings==null||Object.keys(this.selectedCameraSettings).some(u=>{var b,f;return ((b=this.selectedCameraSettings)==null?void 0:b[u])!==((f=this.activeCameraSettings)==null?void 0:f[u])}))){this.activeCameraSettings=this.selectedCameraSettings,await this.initializeCameraAndCheckUpdatedSettings(e);return}this.activeCameraSettings&&this.activeCameraSettings.zoomFactor>1&&await this.setZoom(this.activeCameraSettings.zoomFactor);let c=(t=this.activeCameraSettings)==null?void 0:t.getProperty("minFrameRate"),d=(i=this.activeCameraSettings)==null?void 0:i.getProperty("maxFrameRate");(c!=null||d!=null)&&await this.setFrameRate({min:c,max:d});let l=(a=this.activeCameraSettings)==null?void 0:a.getProperty("manualLensPosition");l!=null&&await this.setFocus(l);let v=(s=this.activeCameraSettings)==null?void 0:s.getProperty("exposureTargetBias"),p=(o=this.activeCameraSettings)==null?void 0:o.getProperty("exposureDuration");(v!=null||p!=null)&&await this.setExposure({compensation:v,time:p});}finally{this.cameraInitializationPromise=void 0;}}async initializeCameraForResolution(e,t){var i;this.gui.setCameraRecoveryVisible(false),this.constraint=t!=null?t:this.getInitialCameraResolutionConstraint(e),this.mediaStream!=null&&e.deviceId!==""&&((i=this.activeCamera)==null?void 0:i.deviceId)===e.deviceId?await(a$1.isIPhone()?this.initializeStreamForResolution(e,this.constraint):this.updateStreamForResolution(e,this.constraint)):await this.initializeStreamForResolution(e,this.constraint);}async initializeStreamForResolution(e,t,i=false){var a;await this.stopStream();try{let s=(a=this.activeCameraSettings)==null?void 0:a.getProperty("preferredAspectRatio"),o=await d.accessCameraStream(e,t,s),c=await this.clipMediaStreamIfNeeded(o);if(a$3.log(a$3.Level.Debug,"Camera accessed, waiting for camera video stream start..."),typeof c.getVideoTracks()[0].getSettings=="function"){let d=c.getVideoTracks()[0].getSettings();if(d.width!=null&&d.height!=null&&(d.width===2||d.height===2)){if(a$3.log(a$3.Level.Debug,"Camera video stream access failure (invalid video metadata):",e),t===4)throw new a$4(n.notReadableErrorParameters);return await this.stopStream(),this.initializeStreamForResolution(e,t+1)}}this.mediaStream=c,i&&this.pauseStream();for(let d of this.mediaStream.getVideoTracks())d.addEventListener("ended",this.videoTrackEndedListener),d.addEventListener("mute",this.videoTrackMuteListener),d.addEventListener("unmute",this.videoTrackMuteListener);try{await this.setupCameraStreamVideo(e,c);}catch(d){if(t===4)throw d;return this.initializeStreamForResolution(e,t+1)}}catch(s){return this.handleCameraInitializationError(e,t,s)}}isVideoAndContextStateValid(){return this.videoElement.readyState===4&&this.videoElement.videoWidth>2&&this.videoElement.videoHeight>2&&this.canvas.width>2&&this.canvas.height>2}postStreamInitialization(){window.clearTimeout(this.getCapabilitiesTimeout),this.getCapabilitiesTimeout=window.setTimeout(()=>{this.storeStreamCapabilities(),this.setupAutofocus();},n.getCapabilitiesTimeoutMs);}async recoverStreamIfNeeded(){var t,i;let e=(t=this.mediaStream)==null?void 0:t.getVideoTracks();((i=e==null?void 0:e[0])==null?void 0:i.readyState)==="ended"&&await this.reinitializeCamera();}reportCameraProperties(e,t,i=true){this.emit("cameraProperties",{deviceId:e,isFrontFacing:t==="userFacing",hasAutofocus:i});}setCameraAccessTimeout(){window.clearTimeout(this.cameraAccessTimeout),this.cameraAccessTimeout=window.setTimeout(async()=>{var e;document.visibilityState==="visible"?(await this.stopStream(true),(e=this.cameraAccessRejectCallback)==null||e.call(this,new a$4(n.notReadableErrorParameters))):(a$3.debug("Page is currently not visible, delay camera video stream access detection"),document.addEventListener("visibilitychange",this.checkCameraVideoStreamAccessIfVisibleListener));},n.cameraAccessTimeoutMs);}setupAutofocus(){if(window.clearTimeout(this.manualFocusWaitTimeout),window.clearTimeout(this.manualToAutofocusResumeTimeout),this.mediaStream&&this.mediaTrackCapabilities){let e=this.mediaTrackCapabilities.focusMode;Array.isArray(e)&&!e.includes("continuous")&&e.includes("single-shot")&&(window.clearInterval(this.autofocusInterval),this.autofocusInterval=window.setInterval(this.triggerAutoFocus.bind(this),n.autofocusIntervalMs));}}async setupCameraStreamVideo(e,t){this.videoElement.addEventListener("loadedmetadata",this.postStreamInitializationListener),this.videoElement.addEventListener("resize",this.videoResizeListener),this.tapToFocusEnabled&&this.enableTapToFocusListeners(),this.pinchToZoomEnabled&&this.enablePinchToZoomListeners();let i=Promise.race([this.checkCameraAccess(e),this.checkVideoMetadata(e),new Promise(a=>{this.abortedCameraInitializationResolveCallback=a;})]);return this.videoElement.srcObject=t,this.videoElement.load(),await this.playVideo(),this.handleVideoResize(),this.reportCameraProperties(e.deviceId,e.position),i}async setupCamerasAndStream(){var e,t;try{let i;this.selectedCamera==null&&(i=await this.accessInitialCamera());let a=await d.getCameras(false,true),s=(t=(e=this.mediaStream)==null?void 0:e.getVideoTracks()[0])==null?void 0:t.getSettings().deviceId;if(this.mediaStream&&i){let o=this.getActiveCamera(a,i.label,s);if(o){if(d.adjustCameraFromMediaStream(this.mediaStream,o),a$1.isDesktopDevice()&&(d.setMainCameraForPositionOverridesOnDesktop(this.cameraPosition,o),d.setMainCameraForPositionOverridesOnDesktop(o.position,o)),a.length===1||d.getMainCameraForPosition(a,this.cameraPosition)===o){a$3.debug("Initial camera access was correct (main camera), keep camera:",o),this.setSelectedCamera(o),this.updateActiveCameraCurrentResolution(o),await this.recoverStreamIfNeeded();return}a$3.debug("Initial camera access was incorrect (not main camera), change camera",{...i,deviceId:s});}else a$3.debug("Initial camera access was incorrect (unknown camera), change camera",{...i,deviceId:s});}if(this.selectedCamera==null){await this.accessAutoselectedCamera(a);return}await this.initializeCameraWithSettings(this.selectedCamera,this.selectedCameraSettings);}finally{this.cameraSetupPromise=void 0;}}storeStreamCapabilities(){var e;if(this.mediaStream){let t=this.mediaStream.getVideoTracks();t.length>0&&typeof t[0].getCapabilities=="function"&&(this.mediaTrackCapabilities=t[0].getCapabilities()),this.mediaTrackCapabilitiesPromiseResolver&&this.mediaTrackCapabilitiesPromiseResolver();}this.activeCamera&&this.reportCameraProperties(this.activeCamera.deviceId,this.activeCamera.position,((e=this.mediaTrackCapabilities)==null?void 0:e.focusMode)==null||this.mediaTrackCapabilities.focusMode.includes("continuous"));}async triggerAutoFocus(){await this.triggerFocusMode("single-shot");}async triggerFocusMode(e){if(this.mediaStream){let t=this.mediaStream.getVideoTracks();if(t.length>0&&typeof t[0].applyConstraints=="function")try{await t[0].applyConstraints({advanced:[{focusMode:e}]});}catch(i){}}}async triggerManualFocus(e){if(e){if(e.preventDefault(),e.type==="touchend"&&e.touches.length>0)return;if(this.pinchToZoomDistance!=null){this.pinchToZoomDistance=void 0;return}}if(window.clearTimeout(this.manualFocusWaitTimeout),window.clearTimeout(this.manualToAutofocusResumeTimeout),!this.mediaStream||!this.mediaTrackCapabilities)return;let t=this.mediaTrackCapabilities.focusMode;Array.isArray(t)&&t.includes("single-shot")&&(t.includes("continuous")&&t.includes("manual")?await this.triggerManualFocusForContinuous():t.includes("continuous")||await this.triggerManualFocusForSingleShot());}async triggerManualFocusForContinuous(){var i;if(!this.mediaStream)return;this.manualToAutofocusResumeTimeout=window.setTimeout(async()=>{await this.triggerFocusMode("continuous");},n.manualToAutofocusResumeTimeoutMs);let e=true,t=this.mediaStream.getVideoTracks();t.length>0&&typeof t[0].getConstraints=="function"&&(e=((i=t[0].getConstraints().advanced)==null?void 0:i.some(a=>a.focusMode==="manual"))===true),e?(await this.triggerFocusMode("continuous"),this.manualFocusWaitTimeout=window.setTimeout(async()=>{await this.triggerFocusMode("manual");},n.manualFocusWaitTimeoutMs)):await this.triggerFocusMode("manual");}async triggerManualFocusForSingleShot(){window.clearInterval(this.autofocusInterval),this.manualToAutofocusResumeTimeout=window.setTimeout(()=>{this.autofocusInterval=window.setInterval(this.triggerAutoFocus.bind(this),n.autofocusIntervalMs);},n.manualToAutofocusResumeTimeoutMs);try{await this.triggerFocusMode("single-shot");}catch(e){}}async triggerZoomMove(e){this.pinchToZoomDistance==null||(e==null?void 0:e.touches.length)!==2||e.preventDefault();}triggerZoomStart(e){var a,s,o,c;if((e==null?void 0:e.touches.length)!==2||(e.preventDefault(),this.pinchToZoomDistance=Math.hypot((e.touches[1].screenX-e.touches[0].screenX)/screen.width,(e.touches[1].screenY-e.touches[0].screenY)/screen.height),!this.mediaStream||!((a=this.mediaTrackCapabilities)!=null&&a.zoom)))return;let t=this.mediaStream.getVideoTracks();if(t.length===0||typeof t[0].getConstraints!="function")return;this.pinchToZoomInitialZoom=(s=this.mediaTrackCapabilities.zoom.min)!=null?s:1;let i=t[0].getConstraints();if(i.advanced){let d=(o=i.advanced.find(l=>"zoom"in l))==null?void 0:o.zoom;d!=null&&(this.pinchToZoomInitialZoom=typeof d=="number"?d:(c=d.ideal)!=null?c:1);}}updateActiveCameraCurrentResolution(e){this.videoElement.videoWidth>2&&this.videoElement.videoHeight>2&&(e.currentResolution={width:this.videoElement.videoWidth,height:this.videoElement.videoHeight}),e.deviceId!==""&&(this.activeCamera=e,this.setMirrorImageEnabled(this.isMirrorImageEnabled(),false));}async updateStreamForResolution(e,t){var i;if(this.mediaStream==null)await this.initializeCameraForResolution(e,t);else try{let a=(i=this.activeCameraSettings)==null?void 0:i.getProperty("preferredAspectRatio");a$3.debug("Setting new resolution for active camera video stream..."),await this.mediaStream.getVideoTracks()[0].applyConstraints(d.getUserMediaVideoParameters(t,a)),await new Promise(o=>{this.videoElement.addEventListener("timeupdate",()=>{o();},{once:true});});let s=this.mediaStream.getVideoTracks()[0].getSettings();a$3.debug("New active camera video stream resolution set",{width:s.width,height:s.height});}catch(a){if(t===4)throw a;await this.updateStreamForResolution(e,t+1);}}async videoTrackEndedRecovery(){if(document.visibilityState==="visible")try{a$3.debug('Detected video track "ended" event, try to reinitialize camera'),await this.reinitializeCamera();}catch(e){}else a$3.debug("Page is currently not visible, delay camera reinitialization until visible"),document.addEventListener("visibilitychange",this.checkCameraVideoStreamAccessIfVisibleListener);}videoTrackMuteRecovery(e){if(this.videoElement.onloadeddata!=null){a$3.debug(`Detected video track "${e.type}" event, delay camera video stream access detection`),this.setCameraAccessTimeout();return}let t=e.type==="mute";t!==this.gui.isCameraRecoveryVisible()&&(a$3.debug(`Detected video track "${e.type}" event, ${t?"enable":"disable"} camera recovery`),this.gui.setCameraRecoveryVisible(t));}async clipMediaStreamIfNeeded(e){if(!this.clipArea)return e;let t=this.videoElement.cloneNode();t.srcObject=e,t.load();let i=document.createElement("canvas");i.width=this.clipArea.size.width,i.height=this.clipArea.size.height;let a=i.getContext("2d",{alpha:false,willReadFrequently:false});return a?(t.addEventListener("play",this.drawClippedFrame.bind(this,this.clipArea,t,a),{once:true}),t.addEventListener("pause",this.cleanupClippedStream.bind(this,t),{once:true}),await t.play(),i.captureStream()):e}drawClippedFrame(e,t,i){i.drawImage(t,e.origin.x,e.origin.y,e.size.width,e.size.height,0,0,e.size.width,e.size.height),this.clippedFrameRequestID=this.requestVideoFrame(this.drawClippedFrame.bind(this,e,t,i),t);}cleanupClippedStream(e){this.clippedFrameRequestID&&(this.cancelVideoFrame(this.clippedFrameRequestID,e),this.clippedFrameRequestID=void 0);}connectedCallback(e){e.replaceWith(this.videoElement),this.canvas.addEventListener("webglcontextlost",this.handleWebGLContextLostListener),this.videoElement.addEventListener("pause",this.handleVideoPauseHandler),this.playVideo();}disconnectedCallback(){this.canvas.removeEventListener("webglcontextlost",this.handleWebGLContextLostListener),this.videoElement.removeEventListener("pause",this.handleVideoPauseHandler),this.videoElement.remove();}getVideoElement(){return this.videoElement}handleVideoPause(){this.playVideo();}};n.autofocusIntervalMs=1500,n.cameraAccessTimeoutMs=4e3,n.getCapabilitiesTimeoutMs=500,n.manualFocusWaitTimeoutMs=400,n.manualToAutofocusResumeTimeoutMs=5e3,n.noCameraErrorParameters={name:"NoCameraAvailableError",message:"No camera available"},n.notReadableErrorParameters={name:"NotReadableError",message:"Could not initialize camera correctly"},n.videoMetadataCheckIntervalMs=50,n.videoMetadataCheckTimeoutMs=4e3,n.MIRRORED_CLASS_NAME=a$7.MIRRORED_CLASS_NAME,n._instance=null;var k=n;export{P as a,F as b,x as c,k as d};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import {b}from'./chunk-PAPLDTB7.js';import {a}from'./chunk-NQF3GUK2.js';import {a as a$2}from'./chunk-QHBIT2WY.js';import {b as b$1,a as a$3}from'./chunk-SK6L34IF.js';import {a as a$1}from'./chunk-XR65N6EG.js';var v=`
|
|
2
|
+
attribute vec2 a_position;
|
|
3
|
+
varying vec2 v_texcoord;
|
|
4
|
+
|
|
5
|
+
void main() {
|
|
6
|
+
gl_Position = vec4(a_position, 0, 1);
|
|
7
|
+
v_texcoord = a_position * 0.5 + 0.5;
|
|
8
|
+
}
|
|
9
|
+
`,R=`
|
|
10
|
+
precision mediump float;
|
|
11
|
+
varying vec2 v_texcoord;
|
|
12
|
+
uniform sampler2D u_texture;
|
|
13
|
+
uniform float x_spacing; // Uniform for x-spacing between pixels
|
|
14
|
+
|
|
15
|
+
// Function to calculate grayscale
|
|
16
|
+
float toGray(vec4 color) {
|
|
17
|
+
return dot(color.rgb, vec3(0.299, 0.587, 0.114));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
void main() {
|
|
21
|
+
// Sample adjacent pixels with spacing of 1/width
|
|
22
|
+
vec4 a = texture2D(u_texture, v_texcoord + vec2(0.0 * x_spacing, 0.0));
|
|
23
|
+
vec4 b = texture2D(u_texture, v_texcoord + vec2(1.0 * x_spacing, 0.0));
|
|
24
|
+
vec4 c = texture2D(u_texture, v_texcoord + vec2(2.0 * x_spacing, 0.0));
|
|
25
|
+
vec4 d = texture2D(u_texture, v_texcoord + vec2(3.0 * x_spacing, 0.0));
|
|
26
|
+
|
|
27
|
+
// Calculate grayscale values
|
|
28
|
+
float grayscaleA = toGray(a);
|
|
29
|
+
float grayscaleB = toGray(b);
|
|
30
|
+
float grayscaleC = toGray(c);
|
|
31
|
+
float grayscaleD = toGray(d);
|
|
32
|
+
|
|
33
|
+
// Set the final color with grayscale values
|
|
34
|
+
gl_FragColor = vec4(grayscaleA, grayscaleB, grayscaleC, grayscaleD);
|
|
35
|
+
}`,p=class extends a{constructor(e,t){super(e,t);this.colorType="GRAYSCALE";this._useRgbaFallback=false;this._positions=new Float32Array([-1,-1,-1,1,1,-1,1,-1,-1,1,1,1]);this._canvas=document.createElement("canvas");}get _webglContext(){var e;if(!this._ctx){if(this._ctx=(e=this._canvas)==null?void 0:e.getContext("webgl",{antialias:false}),!this._ctx)throw new Error("Cannot get WebGL context");this.setup();}return this._ctx}readFromSource(e){var c,g;let t=(c=e==null?void 0:e.videoWidth)!=null?c:this._contextWebGL.drawingBufferWidth,i=t%4!==0;if(i!==this._useRgbaFallback&&(i?(a$1.debug("[GrayScaleFrameReader] Video width not divisible by 4, falling back to RGBA reader for better performance",{width:t}),this._rgbaFallbackReader||(this._rgbaFallbackReader=new b(this._contextWebGL,{minPoolCapacity:this._minPoolCapacity,maxPoolCapacity:this._maxPoolCapacity}),this._rgbaFallbackReader.setup())):a$1.log(a$1.Level.Info,"[GrayScaleFrameReader] Video width now divisible by 4, using optimized grayscale reader",{width:t}),this._useRgbaFallback=i),this._useRgbaFallback&&this._rgbaFallbackReader)return this._rgbaFallbackReader.readFromSource(e);this.updateCanvasSizeIfNeeded(),this.updateFrameSizeIfNeeded();let{drawingBufferWidth:n,drawingBufferHeight:r,TEXTURE_2D:u,RGBA:s,UNSIGNED_BYTE:h,TRIANGLES:m}=this._webglContext;this._webglContext.viewport(0,0,n,r);let w=this._webglContext.getUniformLocation(this._shaderProgram,"x_spacing"),C=1/t;this._webglContext.uniform1f(w,C),this._webglContext.texImage2D(u,0,s,s,h,e),this._webglContext.drawArrays(m,0,6);let a=(g=this._framePool)==null?void 0:g.pop();if(!a)throw new Error("Frame pool found empty!");let l=n*r*4;return a.length!==l&&(a$1.warn("[GrayScaleFrameReader] Buffer from pool has wrong size, allocating new one",{bufferLength:a.length,requiredSize:l}),a=new Uint8ClampedArray(l)),this._webglContext.readPixels(0,0,n,r,s,h,a),{width:t,height:r,data:new Uint8ClampedArray(a.buffer,0,t*r),colorType:"GRAYSCALE"}}setup(){this.initShaderProgram(),this.initBuffers(),this.initTexture();}dispose(){var e;this._ctx&&(this._shaderProgram&&(this._ctx.deleteProgram(this._shaderProgram),this._shaderProgram=null),this._positionBuffer&&(this._ctx.deleteBuffer(this._positionBuffer),this._positionBuffer=null),this._texture&&(this._ctx.deleteTexture(this._texture),this._texture=null),this._ctx=null),this._rgbaFallbackReader&&(this._rgbaFallbackReader.dispose(),this._rgbaFallbackReader=null),(e=this._framePool)==null||e.empty(),this._canvas=void 0;}updateCanvasSizeIfNeeded(){if(!this._canvas)return;let e=Math.ceil(this._contextWebGL.drawingBufferWidth/4);(this._canvas.width!==e||this._canvas.height!==this._contextWebGL.drawingBufferHeight)&&(this._canvas.width=e,this._canvas.height=this._contextWebGL.drawingBufferHeight);}updateFrameSizeIfNeeded(){let{drawingBufferWidth:e,drawingBufferHeight:t}=this._webglContext,i=e*t*4;this._frameSize!==i&&(this._frameSize=i,this._framePool&&this._framePool.empty(),this._framePool=new a$2({capacity:this._maxPoolCapacity,lowWaterMark:this._minPoolCapacity,createItem:()=>new Uint8ClampedArray(this._frameSize)}));}initShaderProgram(){let e=b$1(this._webglContext,this._webglContext.VERTEX_SHADER,v),t=b$1(this._webglContext,this._webglContext.FRAGMENT_SHADER,R);if(!e||!t)throw new Error("Shaders cannot be created");this._shaderProgram=a$3(this._webglContext,e,t),this._webglContext.useProgram(this._shaderProgram);}initBuffers(){this._positionBuffer=this._webglContext.createBuffer(),this._webglContext.bindBuffer(this._webglContext.ARRAY_BUFFER,this._positionBuffer),this._webglContext.bufferData(this._webglContext.ARRAY_BUFFER,this._positions,this._webglContext.STATIC_DRAW);let e=this._webglContext.getAttribLocation(this._shaderProgram,"a_position");this._webglContext.enableVertexAttribArray(e),this._webglContext.bindBuffer(this._webglContext.ARRAY_BUFFER,this._positionBuffer),this._webglContext.vertexAttribPointer(e,2,this._webglContext.FLOAT,false,0,0);}initTexture(){this._texture=this._webglContext.createTexture(),this._webglContext.bindTexture(this._webglContext.TEXTURE_2D,this._texture),this._webglContext.texParameteri(this._webglContext.TEXTURE_2D,this._webglContext.TEXTURE_WRAP_S,this._webglContext.CLAMP_TO_EDGE),this._webglContext.texParameteri(this._webglContext.TEXTURE_2D,this._webglContext.TEXTURE_WRAP_T,this._webglContext.CLAMP_TO_EDGE),this._webglContext.texParameteri(this._webglContext.TEXTURE_2D,this._webglContext.TEXTURE_MIN_FILTER,this._webglContext.LINEAR),this._webglContext.texParameteri(this._webglContext.TEXTURE_2D,this._webglContext.TEXTURE_MAG_FILTER,this._webglContext.LINEAR);let e=this._webglContext.getUniformLocation(this._shaderProgram,"u_texture");this._webglContext.uniform1i(e,0);}};export{p as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-GK6JPJTE.js';import {d as d$1}from'./chunk-OQ4XCKFQ.js';import {a as a$2}from'./chunk-UCD6YLP3.js';import {a}from'./chunk-XR65N6EG.js';import {f as f$1,g as g$1}from'./chunk-7ELPJFJV.js';var S=(t=>(t.Idle="idle",t.Pressed="pressed",t))(S||{}),d=class{constructor(e,t){this.state="idle";this.isHover=false;this.controlTypeToAriaLabelMap={"camera-fov":"Switch camera field of view",camera:"Switch camera",torch:"Toggle torch"};this.control=e,this.domHost=t,this.onTouchStartListener=this.onTouchStart.bind(this),this.onMouseEnterListener=this.onMouseEnter.bind(this),this.onMouseLeaveListener=this.onMouseLeave.bind(this),this.onClickListener=this.onClick.bind(this),this.setup();}get frameSource(){var e,t;return (t=(e=this.control.view)==null?void 0:e.getContext())==null?void 0:t.frameSource}get context(){var e;return (e=this.control.view)==null?void 0:e.getContext()}async install(){this.button||this.setup();let e=await this.canShow();return e?(this.updateButtonBackground(this.button,this.getImageFromState()),this.show()):this.hide(),e}remove(e=false){e&&this.button?(this.button.removeEventListener("mouseenter",this.onMouseEnterListener),this.button.removeEventListener("mouseleave",this.onMouseLeaveListener),this.button.removeEventListener("touchstart",this.onTouchStartListener),this.button.removeEventListener("click",this.onClickListener),this.button.remove(),this.isHover=false,this.button=void 0):this.hide();}hide(){this.button&&(this.button.style.display="none");}show(){this.button&&(this.button.style.display="block");}setupButton(){let e=document.createElement("button");e.type="button",e.style.display="none",e.className=`scandit-control-widget scandit-control-widget-${this.control.type}`,this.updateButtonBackground(e,this.getImageFromState()),this.domHost.append(e),e.addEventListener("mouseenter",this.onMouseEnterListener),e.addEventListener("mouseleave",this.onMouseLeaveListener),a$2.isDesktopDevice()||e.addEventListener("touchstart",this.onTouchStartListener),e.addEventListener("click",this.onClickListener),e.setAttribute("aria-pressed",String(this.state==="pressed"));let t=this.control.type,a=this.controlTypeToAriaLabelMap[t];return e.setAttribute("aria-label",a),this.button=e,this.button}setup(){this.setupButton();}onTouchStart(){var e,t;(e=this.button)==null||e.removeEventListener("mouseenter",this.onMouseEnterListener),(t=this.button)==null||t.removeEventListener("mouseleave",this.onMouseLeaveListener);}onMouseEnter(){this.isHover=true,this.updateButtonBackground(this.button,this.getImageFromState());}onMouseLeave(){this.isHover=false,this.updateButtonBackground(this.button,this.getImageFromState());}onClick(){var e;this.state=this.state==="pressed"?"idle":"pressed",this.buttonClicked(),this.updateButtonBackground(this.button,this.getImageFromState()),(e=this.button)==null||e.setAttribute("aria-pressed",String(this.state==="pressed"));}updateButtonBackground(e,t){t!=null&&e!=null&&(e.style.backgroundImage=`url(${JSON.stringify(t)})`);}},C=class extends d{constructor(e,t){super(e,t);}async buttonClicked(){await this.frameSource.setDesiredTorchState(this.retrieveTorchState()==="on"?"off":"on");}async canShow(){return this.isTorchAvailable()}getImageFromState(){return this.retrieveTorchState()==="on"?this.isHover?this.control.torchOnPressedImage:this.control.torchOnImage:this.isHover?this.control.torchOffPressedImage:this.control.torchOffImage}setup(){if(this.control.torchOffImage==null||this.control.torchOnImage==null){a.log(a.Level.Warn,"TorchSwitchControl icon is not set or is empty, the control will not be rendered.");return}super.setup();}async isTorchAvailable(){return f$1(this.frameSource)?this.frameSource.isTorchAvailable():false}retrieveTorchState(){return f$1(this.frameSource)?this.frameSource.getDesiredTorchState():"off"}},f=class s extends d{constructor(e,t){super(e,t);}static get CameraAccess(){return d$1}static get Camera(){return a$1}async canShow(){return (await s.CameraAccess.getCameras()).length>1}getImageFromState(){return this.isHover?this.control.pressedImage:this.control.idleImage}async buttonClicked(){if(this.isTransitioning)return;let e=await this.getNextDeviceCamera();e&&await this.switchCameras(e);}setup(){if(this.control.idleImage==null){a.log(a.Level.Warn,"CameraSwitchControl idle icon is not set or is empty, the control will not be rendered.");return}super.setup();}async getNextDeviceCamera(){var o,n;let e=await s.CameraAccess.getCameras(),t=this.frameSource?this.frameSource:null,a=(o=t==null?void 0:t.cameraManager.activeCamera)==null?void 0:o.deviceId,r=e.findIndex(c=>c.deviceId===a);return r>-1?(n=e[r+1])!=null?n:e[0]:e.length>0?e[0]:null}async switchCameras(e){var n,c,u;this.isTransitioning=true;let t=(n=this.context)==null?void 0:n.frameSource,a,r;t!=null&&(a=new g$1(t.settings),r=t.desiredState),await(t==null?void 0:t.switchToDesiredState("off"));let o=s.Camera.fromDeviceCamera(e);a!=null&&await o.applySettings(a),await((c=this.context)==null?void 0:c.setFrameSource(o)),await((u=this.context)==null?void 0:u.frameSource).switchToDesiredState(r!=null?r:"on"),this.isTransitioning=false;}},g=class s extends d{constructor(e,t){super(e,t);}static get Camera(){return a$1}static get CameraAccess(){return d$1}async install(){let e=await super.install();return e&&await this.setInitialCamera(),e}async canShow(){return !a$2.isIOSDeviceWithExtendedCameraAccess()||!f$1(this.frameSource)?false:d$1.isIOSBackDualWideCameraLabel(this.frameSource.label)||d$1.isIOSBackCameraLabel(this.frameSource.label)||d$1.isIOSUltraWideBackCameraLabel(this.frameSource.label)}getImageFromState(){return this.isUltraWideBackCamera()?this.isHover?this.control.cameraFOVUltraWidePressedImage:this.control.cameraFOVUltraWideImage:this.isHover?this.control.cameraFOVWidePressedImage:this.control.cameraFOVWideImage}async buttonClicked(){if(this.isTransitioning)return;let e=await this.getAlternativeDeviceCamera();e&&await this.switchCameras(e);}setup(){if(this.control.cameraFOVUltraWideImage==null||this.control.cameraFOVWideImage==null){a.log(a.Level.Warn,"CameraFOVSwitchControl icon is not set or is empty, the control will not be rendered.");return}super.setup();}async setInitialCamera(){var e,t;if(!this.isTransitioning&&!d$1.isIOSBackCameraLabel((t=(e=this.frameSource)==null?void 0:e.label)!=null?t:"")){let r=(await s.CameraAccess.getCameras()).find(o=>d$1.isIOSBackCameraLabel(o.label));r&&await this.switchCameras(r);}}isUltraWideBackCamera(){return f$1(this.frameSource)?d$1.isIOSUltraWideBackCameraLabel(this.frameSource.label):false}async getAlternativeDeviceCamera(){return (await s.CameraAccess.getCameras()).find(t=>this.isUltraWideBackCamera()?d$1.isIOSBackCameraLabel(t.label):d$1.isIOSUltraWideBackCameraLabel(t.label))}async switchCameras(e){var n,c,u;this.isTransitioning=true;let t=(n=this.context)==null?void 0:n.frameSource,a,r;t!=null&&(a=new g$1(t.settings),r=t.desiredState),await(t==null?void 0:t.switchToDesiredState("off"));let o=s.Camera.fromDeviceCamera(e);a!=null&&await o.applySettings(a),await((c=this.context)==null?void 0:c.setFrameSource(o)),await((u=this.context)==null?void 0:u.frameSource).switchToDesiredState(r!=null?r:"on"),this.isTransitioning=false;}};export{S as a,C as b,f as c,g as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var o=class{constructor(r,e){var a,t;this._contextWebGL=r,this._maxPoolCapacity=(a=e==null?void 0:e.maxPoolCapacity)!=null?a:2,this._minPoolCapacity=(t=e==null?void 0:e.minPoolCapacity)!=null?t:1;}recycle(r){var e;r.length===this._frameSize&&((e=this._framePool)==null||e.push(r));}};export{o as a};
|