All files / src/lib/barcodePicker barcodePicker.ts

99.68% Statements 312/313
98.91% Branches 181/183
100% Functions 57/57
99.67% Lines 301/302

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 133715x 15x   15x   15x   15x 15x   15x     15x 15x 15x   15x 15x 15x 15x 15x                   15x                                                                     30x                                                 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x                                     61x 61x 61x   61x 61x       61x   61x   61x 61x 61x   61x 61x 61x   61x                               61x 8x   53x 53x     61x                                                                                                                                                                                                 15x   67x 134x 134x 134x 134x 134x 134x 134x 67x 67x 67x 134x 134x 134x 134x 134x 134x 67x 134x 67x 134x                                               67x 67x 67x     67x   67x   67x 67x 3x   64x 7x             64x 1x             63x 2x               61x                                     61x           61x 61x 61x   61x     61x   3x         61x 14x 14x       47x                               93x 48x 48x 48x 48x 45x   48x 48x                 15x 1x   1x           15x 6x                             69x 60x   60x 51x     60x 16x     60x                         15x 15x   15x 11x     28x 4x     15x           15x 15x                                               15x 11x 3x 3x   4x 4x     8x     7x                                               15x 4x 2x   2x     3x           15x 5x                     15x 3x   3x           15x 16x                         15x 5x   5x             15x 5x                     15x 65x   65x             15x 5x                     15x 65x   65x           15x 3x                     15x 2x           2x           15x 3x                     15x 2x   2x           15x 3x                     15x 2x   2x           15x 3x                     15x 2x   2x                             15x 4x   2x                       15x 4x   2x           15x 2x                                                                                                                                                                                                                     168x 86x 6x 1x   5x     80x 4x   76x       86x                   15x 5x   5x                 15x 8x   8x                         15x 1x                           15x 4x   4x                           15x 2x   2x                                           15x 8x 8x 4x     6x                 15x 7x                         15x 3x 2x           1x   1x                               15x 65x 2x   65x   65x           15x 69x                     15x 1x   1x                           15x 2x   2x                       15x 2x   2x     15x 1x 1x     29x 29x   29x   29x   26x 26x   28x     23x 23x 22x   23x 22x       26x       12774x 6388x 12750x       15x 6x 4x 2x   2x   4x 7x 2x   3x     2x       15x 37x       37x       36x 7x   29x     37x 35x 6x             35x       31x   31x 29x     4x       4x 4x         15x 6373x 39x     6334x               6333x   6333x     1x   2x     1x 1x   2x 2x     15x 10x 10x   15x                                                                                                                                                                                        
import { EventEmitter, ListenerFn } from "eventemitter3";
import { Howl, Howler } from "howler/dist/howler.core.min.js";
 
import { beepSound } from "../assets/base64assets";
 
import { userLicenseKey } from "../../index";
import { BrowserCompatibility } from "../browserCompatibility";
import { BrowserHelper } from "../browserHelper";
import { Camera } from "../camera";
import { CameraSettings } from "../cameraSettings";
import { CustomError } from "../customError";
import { ImageSettings } from "../imageSettings";
import { Parser } from "../parser";
import { Scanner } from "../scanner";
import { ScanResult } from "../scanResult";
import { ScanSettings } from "../scanSettings";
import { SearchArea } from "../searchArea";
import { SingleImageModePlatformSettings, SingleImageModeSettings } from "../singleImageModeSettings";
import { UnsupportedBrowserError } from "../unsupportedBrowserError";
import { CameraManager } from "./cameraManager";
import { DummyCameraManager } from "./dummyCameraManager";
import { GUI } from "./gui";
 
/**
 * @hidden
 */
type EventName = "ready" | "submitFrame" | "processFrame" | "scan" | "scanError";
 
/**
 * @hidden
 */
class BarcodePickerEventEmitter extends EventEmitter<EventName> {}
 
/**
 * A barcode picker element used to get and show camera input and perform scanning operations.
 *
 * The barcode picker will automatically fit and scale inside the given *originElement*.
 *
 * Each barcode picker internally contains a [[Scanner]] object with its own WebWorker thread running a
 * separate copy of the external Scandit Engine library. To optimize loading times and performance it's
 * recommended to reuse the same picker and to already create the picker in advance (hidden) and just
 * display it when needed whenever possible.
 *
 * As the loading of the external Scandit Engine library can take some time, the picker always starts inactive
 * (but showing GUI and video) and then activates, if not paused, as soon as the library is ready to scan.
 * The [[on]] method targeting the [[ready]] event can be used to set up a listener function to be called when the
 * library is loaded. The picker will be ready to start scanning when the library is fully loaded.
 *
 * By default the external Scandit Engine library is preloaded in order to reduce the initialization time as much as
 * possible.
 *
 * The picker can also operate in Single Image Mode: letting the user click/tap to take a single image to be scanned
 * via the camera (mobile) or a file select dialog (desktop). This is provided automatically as fallback by
 * default when the OS/browser only supports part of the needed features and cannot provide direct access to the camera
 * for video streaming and continuous scanning, or can also be forced on/off. This behaviour can be set up on creation
 * via the *singleImageModeSettings* option. Note that in this mode some of the functions provided by the picker will
 * have no effect.
 *
 * By default an alert is shown if an internal error during scanning is encountered which prevents the scanning
 * procedure from continuing when running on a local IP address. As this uses the built-in [[scanError]] event
 * functionality, if unwanted it can be disabled by calling [[removeAllListeners]] on the BarcodePicker
 * instance (right after creation).
 *
 * In accordance with our license terms, the Scandit logo displayed in the bottom right corner of the barcode picker
 * must be displayed and cannot be hidden by any method. Workarounds are not allowed.
 */
export class BarcodePicker {
  private readonly cameraManager: CameraManager;
  private readonly gui: GUI;
  private readonly eventEmitter: BarcodePickerEventEmitter;
  private readonly scanner: Scanner;
  private readonly beepSound: Howl;
  private readonly vibrateFunction?: (pattern: number | number[]) => boolean;
  private readonly scannerReadyEventListener: () => void;
 
  private playSoundOnScan: boolean;
  private vibrateOnScan: boolean;
  private scanningPaused: boolean;
  private fatalError: Error;
  private latestVideoTimeProcessed: number;
  private destroyed: boolean;
  private isReadyToWork: boolean;
  private cameraAccess: boolean;
  private targetScanningFPS: number;
  private averageProcessingTime: number;
  private externalImageData: Uint8Array;
  private internalImageData?: Uint8Array;
 
  private constructor(
    originElement: HTMLElement,
    {
      visible,
      singleImageModeEnabled,
      singleImageModeSettings,
      playSoundOnScan,
      vibrateOnScan,
      scanningPaused,
      guiStyle,
      videoFit,
      laserArea,
      viewfinderArea,
      scanner,
      scanSettings,
      cameraType,
      targetScanningFPS,
      hideLogo,
    }: {
      visible: boolean;
      singleImageModeEnabled: boolean;
      singleImageModeSettings: SingleImageModePlatformSettings;
      playSoundOnScan: boolean;
      vibrateOnScan: boolean;
      scanningPaused: boolean;
      guiStyle: BarcodePicker.GuiStyle;
      videoFit: BarcodePicker.ObjectFit;
      laserArea?: SearchArea;
      viewfinderArea?: SearchArea;
      scanner?: Scanner;
      scanSettings: ScanSettings;
      cameraType: Camera.Type;
      targetScanningFPS: number;
      hideLogo: boolean;
    }
  ) {
    this.isReadyToWork = false;
    this.destroyed = false;
    this.scanningPaused = scanningPaused;
 
    Howler.autoSuspend = false;
    this.beepSound = new Howl({
      src: beepSound,
    });
 
    this.vibrateFunction = navigator.vibrate ?? navigator.webkitVibrate ?? navigator.mozVibrate ?? navigator.msVibrate;
 
    this.eventEmitter = new EventEmitter();
 
    this.setPlaySoundOnScanEnabled(playSoundOnScan);
    this.setVibrateOnScanEnabled(vibrateOnScan);
    this.setTargetScanningFPS(targetScanningFPS);
 
    this.scanner = scanner?.applyScanSettings(scanSettings) ?? new Scanner({ scanSettings });
    this.scannerReadyEventListener = this.handleScannerReady.bind(this);
    this.scanner.on("ready", this.scannerReadyEventListener);
 
    this.gui = new GUI({
      scanner: this.scanner,
      originElement,
      singleImageModeEnabled,
      singleImageModeSettings,
      scanningPaused,
      visible,
      guiStyle,
      videoFit,
      hideLogo,
      cameraType,
      laserArea,
      viewfinderArea,
      cameraUploadCallback: this.processVideoFrame.bind(this, true),
    });
 
    if (singleImageModeEnabled) {
      this.cameraManager = new DummyCameraManager(this.triggerFatalError.bind(this), this.gui);
    } else {
      this.cameraManager = new CameraManager(this.triggerFatalError.bind(this), this.gui);
      this.scheduleVideoProcessing();
    }
 
    this.gui.setCameraManager(this.cameraManager);
  }
 
  /**
   * Create a [[BarcodePicker]] instance, creating the needed HTML in the given origin element.
   * If the *accessCamera* option is enabled (active by default) and the picker is not in Single Image Mode,
   * the available cameras are accessed and camera access permission is requested to the user if needed.
   * This object expects that at least a camera is available. The active camera is accessed and kept active during the
   * lifetime of the picker (also when hidden or scanning is paused), and is only released when [[destroy]] is called.
   *
   * It is required to having configured the library via [[configure]] before this object can be created.
   *
   * Depending on parameters, device features and user permissions for camera access, any of the following errors
   * could be the rejected result of the returned promise:
   * - `AbortError`
   * - `LibraryNotConfiguredError`
   * - `NoCameraAvailableError`
   * - `NoOriginElementError`
   * - `NotAllowedError`
   * - `NotFoundError`
   * - `NotReadableError`
   * - `SecurityError`
   * - `UnsupportedBrowserError`
   *
   * @param originElement The HTMLElement inside which all the necessary elements for the picker will be added.
   * @param visible <div class="tsd-signature-symbol">Default =&nbsp;true</div>
   * Whether the picker starts in a visible state.
   * @param singleImageModeSettings <div class="tsd-signature-symbol">Default =&nbsp;</div>
   * <pre><code>{
   *   desktop: {
   *     usageStrategy: SingleImageModeSettings.UsageStrategy.FALLBACK,
   *     informationElement: &lt;HTMLElement&gt;,
   *     buttonElement: &lt;SVGElement&gt;,
   *     containerStyle: { backgroundColor: "#333333" },
   *     informationStyle: { color: "#FFFFFF" },
   *     buttonStyle: { borderColor: "#FFFFFF", color: "#FFFFFF", fill: "#FFFFFF" }
   *   },
   *   mobile: {
   *     usageStrategy: SingleImageModeSettings.UsageStrategy.FALLBACK,
   *     informationElement: &lt;HTMLElement&gt;,
   *     buttonElement: &lt;SVGElement&gt;,
   *     containerStyle: { backgroundColor: "#333333" },
   *     informationStyle: { color: "#FFFFFF" },
   *     buttonStyle: { borderColor: "#FFFFFF", color: "#FFFFFF", fill: "#FFFFFF" }
   *   }
   * }</code></pre>
   * Settings for Single Image Mode: an alternative/fallback mode for a barcode picker to provide single camera
   * pictures to be scanned instead of continuous camera video stream access. In Single Image Mode users click/tap to
   * directly take a picture with the camera (mobile) or upload a file (desktop). Its usage depends on the given
   * settings and the camera video stream features provided by the OS/browser.
   * @param playSoundOnScan <div class="tsd-signature-symbol">Default =&nbsp;false</div>
   * Whether a sound is played on barcode recognition (iOS requires user input).
   * @param vibrateOnScan <div class="tsd-signature-symbol">Default =&nbsp;false</div>
   * Whether the device vibrates on barcode recognition (only Chrome & Firefox, requires user input).
   * @param scanningPaused <div class="tsd-signature-symbol">Default =&nbsp;false</div>
   * Whether the picker starts in a paused scanning state.
   * @param guiStyle <div class="tsd-signature-symbol">Default =&nbsp;GuiStyle.LASER</div>
   * The GUI style for the picker.
   * @param videoFit <div class="tsd-signature-symbol">Default =&nbsp;ObjectFit.CONTAIN</div>
   * The fit type for the video element of the picker.
   * @param laserArea <div class="tsd-signature-symbol">Default =&nbsp;undefined</div>
   * The area of the laser displayed when the GUI style is set to *laser* (the laser will match the width and be
   * vertically centered), by default the area will match the current [[ScanSettings]]'s *searchArea* option.
   * @param viewfinderArea <div class="tsd-signature-symbol">Default =&nbsp;undefined</div>
   * The area of the viewfinder displayed when the GUI style is set to *viewfinder*, by default the area will match
   * the current [[ScanSettings]]'s *searchArea* option.
   * @param enableCameraSwitcher <div class="tsd-signature-symbol">Default =&nbsp;true</div>
   * Whether to show a GUI button to switch between different cameras (when available).
   * @param enableTorchToggle <div class="tsd-signature-symbol">Default =&nbsp;true</div>
   * Whether to show a GUI button to toggle device torch on/off (when available, only Chrome).
   * @param enableTapToFocus <div class="tsd-signature-symbol">Default =&nbsp;true</div>
   * Whether to trigger a manual focus of the camera when clicking/tapping on the video (when available, only Chrome).
   * @param enablePinchToZoom <div class="tsd-signature-symbol">Default =&nbsp;true</div>
   * Whether to control the zoom of the camera when doing a pinching gesture on the video (when available, only Chrome).
   * @param accessCamera <div class="tsd-signature-symbol">Default =&nbsp;true</div>
   * Whether to immediately access the camera (and requesting user permissions if needed) on picker creation.
   * @param camera <div class="tsd-signature-symbol">Default =&nbsp;undefined</div>
   * The initial camera to be used for video input, if not specified the camera automatically selected depending on
   * the *cameraType* option will be used.
   * @param cameraType <div class="tsd-signature-symbol">Default =&nbsp;Camera.Type.BACK</div>
   * The preferred initial camera type (facing mode/direction) to be used for video input and Single Image Mode
   * (when available), by default the back or only camera will be used. If the *camera* option is provided then
   * *cameraType* is ignored.
   * @param cameraSettings <div class="tsd-signature-symbol">Default =&nbsp;undefined</div>
   * The camera options used when accessing the camera, by default HD resolution is used.
   * @param scanner <div class="tsd-signature-symbol">Default =&nbsp;undefined</div>
   * The scanner object responsible for scanning via the external Scandit Engine library
   * (a new scanner will be created and initialized if not provided).
   * @param scanSettings <div class="tsd-signature-symbol">Default =&nbsp;new ScanSettings()</div>
   * The configuration object for scanning options to be applied to the scanner (all symbologies disabled by default).
   * @param targetScanningFPS <div class="tsd-signature-symbol">Default =&nbsp;30</div>
   * The target frames per second to be processed, the final speed is limited by the camera framerate (usually 30 FPS)
   * and the frame processing time of the device. By setting this to lower numbers devices can save power by performing
   * less work during scanning operations, depending on device speed (faster devices can "sleep" for longer periods).
   * Must be a number bigger than 0.
   * @returns A promise resolving to the created ready [[BarcodePicker]] object.
   */
  public static create(
    originElement: HTMLElement,
    {
      visible = true,
      singleImageModeSettings = {},
      playSoundOnScan = false,
      vibrateOnScan = false,
      scanningPaused = false,
      guiStyle = BarcodePicker.GuiStyle.LASER,
      videoFit = BarcodePicker.ObjectFit.CONTAIN,
      laserArea,
      viewfinderArea,
      scanner,
      scanSettings = new ScanSettings(),
      enableCameraSwitcher = true,
      enableTorchToggle = true,
      enableTapToFocus = true,
      enablePinchToZoom = true,
      accessCamera = true,
      camera,
      cameraType = Camera.Type.BACK,
      cameraSettings,
      targetScanningFPS = 30,
    }: {
      visible?: boolean;
      singleImageModeSettings?: SingleImageModeSettings;
      playSoundOnScan?: boolean;
      vibrateOnScan?: boolean;
      scanningPaused?: boolean;
      guiStyle?: BarcodePicker.GuiStyle;
      videoFit?: BarcodePicker.ObjectFit;
      laserArea?: SearchArea;
      viewfinderArea?: SearchArea;
      scanner?: Scanner;
      scanSettings?: ScanSettings;
      enableCameraSwitcher?: boolean;
      enableTorchToggle?: boolean;
      enableTapToFocus?: boolean;
      enablePinchToZoom?: boolean;
      accessCamera?: boolean;
      camera?: Camera;
      cameraType?: Camera.Type;
      cameraSettings?: CameraSettings;
      targetScanningFPS?: number;
    } = {}
  ): Promise<BarcodePicker> {
    const deviceType: string | undefined = BrowserHelper.userAgentInfo.getDevice().type;
    const isMobileDevice: boolean = deviceType === "mobile" || deviceType === "tablet";
    const singleImageModePlatformSettings: SingleImageModePlatformSettings =
      (isMobileDevice ? singleImageModeSettings.mobile : singleImageModeSettings.desktop) ?? {};
    const singleImageModeDisallowed: boolean =
      singleImageModePlatformSettings.usageStrategy === SingleImageModeSettings.UsageStrategy.NEVER;
    const singleImageModeForced: boolean =
      singleImageModePlatformSettings.usageStrategy === SingleImageModeSettings.UsageStrategy.ALWAYS;
 
    const browserCompatibility: BrowserCompatibility = BrowserHelper.checkBrowserCompatibility();
    if (!browserCompatibility.scannerSupport || (singleImageModeDisallowed && !browserCompatibility.fullSupport)) {
      return Promise.reject(new UnsupportedBrowserError(browserCompatibility));
    }
    if (!browserCompatibility.fullSupport && !singleImageModeForced) {
      console.log(
        "NOTE: BarcodePicker's Single Image Mode is being used as fallback as the OS/browser combination doesn't " +
          "support camera video stream scanning (https://caniuse.com/#feat=stream). " +
          'You can configure this behaviour via the "singleImageModeSettings" option.'
      );
    }
 
    if (userLicenseKey == null) {
      return Promise.reject(
        new CustomError({
          name: "LibraryNotConfiguredError",
          message: "The library has not correctly been configured yet, please call 'configure' with valid parameters",
        })
      );
    }
    if (!BrowserHelper.isValidHTMLElement(originElement)) {
      return Promise.reject(
        new CustomError({
          name: "NoOriginElementError",
          message: "A valid origin HTML element must be given",
        })
      );
    }
 
    const barcodePicker: BarcodePicker = new BarcodePicker(originElement, {
      visible,
      singleImageModeEnabled: browserCompatibility.fullSupport ? singleImageModeForced : true,
      singleImageModeSettings: singleImageModePlatformSettings,
      playSoundOnScan,
      vibrateOnScan,
      scanningPaused,
      guiStyle,
      videoFit,
      laserArea,
      viewfinderArea,
      scanner,
      scanSettings,
      cameraType,
      targetScanningFPS,
      // tslint:disable-next-line:use-named-parameter
      hideLogo: arguments[1]?.hideLogo === true, // Hidden parameter
    });
 
    barcodePicker.cameraManager.setInteractionOptions(
      enableCameraSwitcher,
      enableTorchToggle,
      enableTapToFocus,
      enablePinchToZoom
    );
    barcodePicker.cameraManager.setInitialCameraType(cameraType);
    barcodePicker.cameraManager.setSelectedCamera(camera);
    barcodePicker.cameraManager.setSelectedCameraSettings(cameraSettings);
 
    barcodePicker.cameraAccess = accessCamera;
 
    // Show error in alert on ScanError by default when running on local IP address for easier customer debugging
    barcodePicker.on("scanError", (error) => {
      // istanbul ignore if
      if (["localhost", "127.0.0.1", ""].includes(window.location.hostname)) {
        alert(error);
      }
    });
 
    if (accessCamera) {
      return barcodePicker.cameraManager.setupCameras().then(() => {
        return barcodePicker;
      });
    }
 
    return Promise.resolve(barcodePicker);
  }
 
  /**
   * Stop scanning and displaying video output, remove HTML elements added to the page,
   * destroy the internal [[Scanner]] (by default) and destroy the barcode picker itself; ensuring complete cleanup.
   *
   * This method should be called after you don't plan to use the picker anymore,
   * before the object is automatically cleaned up by JavaScript.
   * The barcode picker must not be used in any way after this call.
   *
   * If the [[Scanner]] is or will be in use for other purposes, the relative option can be passed to prevent
   * its destruction.
   *
   * @param destroyScanner Whether to destroy the internally used [[Scanner]] or not.
   */
  public destroy(destroyScanner: boolean = true): void {
    this.pauseScanning(true);
    this.scanner.removeListener("ready", this.scannerReadyEventListener);
    this.destroyed = true;
    if (destroyScanner) {
      this.scanner.destroy();
    }
    this.gui.destroy();
    this.eventEmitter.removeAllListeners();
  }
 
  /**
   * Apply a new set of scan settings to the internal scanner (replacing old settings).
   *
   * @param scanSettings The scan configuration object to be applied to the scanner.
   * @returns The updated [[BarcodePicker]] object.
   */
  public applyScanSettings(scanSettings: ScanSettings): BarcodePicker {
    this.scanner.applyScanSettings(scanSettings);
 
    return this;
  }
 
  /**
   * @returns Whether the scanning is currently paused.
   */
  public isScanningPaused(): boolean {
    return this.scanningPaused;
  }
 
  /**
   * Pause the recognition of codes in the input image.
   *
   * By default video from the camera is still shown, if the *pauseCamera* option is enabled the camera stream
   * is paused (camera access is fully interrupted) and will be resumed when calling [[resumeScanning]] or
   * [[accessCamera]], possibly requesting user permissions if needed.
   *
   * In Single Image Mode the input for submitting a picture is disabled.
   *
   * @param pauseCamera Whether to also pause the camera stream.
   * @returns The updated [[BarcodePicker]] object.
   */
  public pauseScanning(pauseCamera: boolean = false): BarcodePicker {
    this.scanningPaused = true;
 
    if (pauseCamera) {
      this.cameraManager.stopStream();
    }
 
    if (this.scanner.isReady()) {
      this.gui.pauseScanning();
    }
 
    return this;
  }
 
  /**
   * Resume the recognition of codes in the input image.
   *
   * If the camera stream was stopped when calling [[pauseScanning]], the camera stream is also resumed and
   * user permissions are requested if needed to resume video input.
   *
   * In Single Image Mode the input for submitting a picture is enabled.
   *
   * @returns The updated [[BarcodePicker]] object.
   */
  public async resumeScanning(): Promise<BarcodePicker> {
    this.scanningPaused = false;
 
    if (this.scanner.isReady()) {
      this.gui.resumeScanning();
    }
 
    if (this.cameraManager.activeCamera == null && this.cameraAccess) {
      await this.cameraManager.setupCameras();
    }
 
    return this;
  }
 
  /**
   * @returns The currently active camera.
   */
  public getActiveCamera(): Camera | undefined {
    return this.cameraManager.activeCamera;
  }
 
  /**
   * Select a camera to be used for video input, if no camera is passed, the default one is selected.
   *
   * If camera access is enabled, the camera is enabled and accessed.
   *
   * Depending on device features and user permissions for camera access, any of the following errors
   * could be the rejected result of the returned promise:
   * - `AbortError`
   * - `NoCameraAvailableError`
   * - `NotAllowedError`
   * - `NotFoundError`
   * - `NotReadableError`
   * - `SecurityError`
   *
   * In Single Image Mode this method has no effect.
   *
   * @param camera The new camera to be used, by default the automatically detected back camera is used.
   * @param cameraSettings The camera options used when accessing the camera, by default HD resolution is used.
   * @returns A promise resolving to the updated [[BarcodePicker]] object when the camera is set
   * (and accessed, if camera access is currently enabled).
   */
  public async setActiveCamera(camera?: Camera, cameraSettings?: CameraSettings): Promise<BarcodePicker> {
    if (camera == null || !this.cameraAccess) {
      this.cameraManager.setSelectedCamera(camera);
      this.cameraManager.setSelectedCameraSettings(cameraSettings);
 
      if (this.cameraAccess) {
        await this.cameraManager.setupCameras();
      }
    } else {
      await this.cameraManager.initializeCameraWithSettings(camera, cameraSettings);
    }
 
    return this;
  }
 
  /**
   * Try to apply new settings to the currently used camera for video input,
   * if no settings are passed the default ones are set.
   *
   * If camera access is enabled, the camera is updated and accessed with the new settings.
   *
   * Depending on device features and user permissions for camera access, any of the following errors
   * could be the rejected result of the returned promise:
   * - `AbortError`
   * - `NoCameraAvailableError`
   * - `NotAllowedError`
   * - `NotFoundError`
   * - `NotReadableError`
   * - `SecurityError`
   *
   * In Single Image Mode this method has no effect.
   *
   * @param cameraSettings The new camera options used when accessing the camera, by default HD resolution is used.
   * @returns A promise resolving to the updated [[BarcodePicker]] object when the camera is updated
   * (and accessed, if camera access is currently enabled).
   */
  public async applyCameraSettings(cameraSettings?: CameraSettings): Promise<BarcodePicker> {
    if (!this.cameraAccess) {
      this.cameraManager.setSelectedCameraSettings(cameraSettings);
    } else {
      await this.cameraManager.applyCameraSettings(cameraSettings);
    }
 
    return this;
  }
 
  /**
   * @returns Whether the picker is in a visible state or not.
   */
  public isVisible(): boolean {
    return this.gui.isVisible();
  }
 
  /**
   * Enable or disable picker visibility.
   *
   * Note that this does not affect camera access, frame processing or any other picker logic.
   *
   * @param visible Whether the picker is in a visible state or not.
   * @returns The updated [[BarcodePicker]] object.
   */
  public setVisible(visible: boolean): BarcodePicker {
    this.gui.setVisible(visible);
 
    return this;
  }
 
  /**
   * @returns Whether the currently selected camera's video is mirrored along the vertical axis.
   */
  public isMirrorImageEnabled(): boolean {
    return this.gui.isMirrorImageEnabled();
  }
 
  /**
   * Enable or disable camera video mirroring along the vertical axis.
   * By default front cameras are automatically mirrored.
   * This setting is applied per camera and the method has no effect if no camera is currently selected.
   *
   * In Single Image Mode this method has no effect.
   *
   * @param enabled Whether the camera video is mirrored along the vertical axis.
   * @returns The updated [[BarcodePicker]] object.
   */
  public setMirrorImageEnabled(enabled: boolean): BarcodePicker {
    this.gui.setMirrorImageEnabled(enabled, true);
 
    return this;
  }
 
  /**
   * @returns Whether a sound should be played on barcode recognition (iOS requires user input).
   * Note that the sound is played if there's at least a barcode not rejected via [[ScanResult.rejectCode]].
   */
  public isPlaySoundOnScanEnabled(): boolean {
    return this.playSoundOnScan;
  }
 
  /**
   * Enable or disable playing a sound on barcode recognition (iOS requires user input).
   *
   * The sound is played if there's at least a barcode not rejected via [[ScanResult.rejectCode]].
   *
   * @param enabled Whether a sound should be played on barcode recognition.
   * @returns The updated [[BarcodePicker]] object.
   */
  public setPlaySoundOnScanEnabled(enabled: boolean): BarcodePicker {
    this.playSoundOnScan = enabled;
 
    return this;
  }
 
  /**
   * @returns Whether the device should vibrate on barcode recognition (only Chrome & Firefox, requires user input).
   * Note that the vibration is triggered if there's at least a barcode not rejected via [[ScanResult.rejectCode]].
   */
  public isVibrateOnScanEnabled(): boolean {
    return this.vibrateOnScan;
  }
 
  /**
   * Enable or disable vibrating the device on barcode recognition (only Chrome & Firefox, requires user input).
   *
   * The vibration is triggered if there's at least a barcode not rejected via [[ScanResult.rejectCode]].
   *
   * @param enabled Whether the device should vibrate on barcode recognition.
   * @returns The updated [[BarcodePicker]] object.
   */
  public setVibrateOnScanEnabled(enabled: boolean): BarcodePicker {
    this.vibrateOnScan = enabled;
 
    return this;
  }
 
  /**
   * @returns Whether a GUI button to switch between different cameras is shown (when available).
   */
  public isCameraSwitcherEnabled(): boolean {
    return this.cameraManager.isCameraSwitcherEnabled();
  }
 
  /**
   * Show or hide a GUI button to switch between different cameras (when available).
   *
   * In Single Image Mode this method has no effect.
   *
   * @param enabled Whether to show a GUI button to switch between different cameras.
   * @returns The updated [[BarcodePicker]] object.
   */
  public setCameraSwitcherEnabled(enabled: boolean): BarcodePicker {
    this.cameraManager.setCameraSwitcherEnabled(enabled).catch(
      /* istanbul ignore next */ () => {
        // Ignored
      }
    );
 
    return this;
  }
 
  /**
   * @returns Whether a GUI button to toggle device torch on/off is shown (when available, only Chrome).
   */
  public isTorchToggleEnabled(): boolean {
    return this.cameraManager.isTorchToggleEnabled();
  }
 
  /**
   * Show or hide a GUI button to toggle device torch on/off (when available, only Chrome).
   *
   * In Single Image Mode this method has no effect.
   *
   * @param enabled Whether to show a GUI button to toggle device torch on/off.
   * @returns The updated [[BarcodePicker]] object.
   */
  public setTorchToggleEnabled(enabled: boolean): BarcodePicker {
    this.cameraManager.setTorchToggleEnabled(enabled);
 
    return this;
  }
 
  /**
   * @returns Whether manual camera focus when clicking/tapping on the video is enabled (when available, only Chrome).
   */
  public isTapToFocusEnabled(): boolean {
    return this.cameraManager.isTapToFocusEnabled();
  }
 
  /**
   * Enable or disable manual camera focus when clicking/tapping on the video (when available, only Chrome).
   *
   * In Single Image Mode this method has no effect.
   *
   * @param enabled Whether to enable manual camera focus when clicking/tapping on the video.
   * @returns The updated [[BarcodePicker]] object.
   */
  public setTapToFocusEnabled(enabled: boolean): BarcodePicker {
    this.cameraManager.setTapToFocusEnabled(enabled);
 
    return this;
  }
 
  /**
   * @returns Whether camera zoom control via pinching gesture on the video is enabled (when available, only Chrome).
   */
  public isPinchToZoomEnabled(): boolean {
    return this.cameraManager.isPinchToZoomEnabled();
  }
 
  /**
   * Enable or disable camera zoom control via pinching gesture on the video (when available, only Chrome).
   *
   * In Single Image Mode this method has no effect.
   *
   * @param enabled Whether to enable camera zoom control via pinching gesture on the video.
   * @returns The updated [[BarcodePicker]] object.
   */
  public setPinchToZoomEnabled(enabled: boolean): BarcodePicker {
    this.cameraManager.setPinchToZoomEnabled(enabled);
 
    return this;
  }
 
  /**
   * Enable or disable the torch/flashlight of the device (when available, only Chrome).
   * Changing active camera or camera settings will cause the torch to become disabled.
   *
   * A button on the [[BarcodePicker]] GUI to let the user toggle this functionality can also be set
   * on creation via the *enableTorchToggle* option (enabled by default, when available).
   *
   * In Single Image Mode this method has no effect.
   *
   * @param enabled Whether the torch should be enabled or disabled.
   * @returns A promise resolving to the updated [[BarcodePicker]] object when the torch is enabled/disabled.
   */
  public async setTorchEnabled(enabled: boolean): Promise<BarcodePicker> {
    await this.cameraManager.setTorchEnabled(enabled);
 
    return this;
  }
 
  /**
   * Set the zoom level of the device (when available, only Chrome).
   * Changing active camera or camera settings will cause the zoom to be reset.
   *
   * In Single Image Mode this method has no effect.
   *
   * @param zoomPercentage The percentage of the max zoom (between 0 and 1).
   * @returns The updated [[BarcodePicker]] object.
   */
  public async setZoom(zoomPercentage: number): Promise<BarcodePicker> {
    await this.cameraManager.setZoom(zoomPercentage);
 
    return this;
  }
 
  /**
   * @returns Whether the barcode picker has loaded the external Scandit Engine library and is ready to scan.
   */
  public isReady(): boolean {
    return this.isReadyToWork;
  }
 
  /**
   * Add the listener function to the listeners array for an event.
   *
   * No checks are made to see if the listener has already been added.
   * Multiple calls passing the same listener will result in the listener being added, and called, multiple times.
   *
   * @param eventName The name of the event to listen to.
   * @param listener The listener function.
   * @param once <div class="tsd-signature-symbol">Default =&nbsp;false</div>
   * Whether the listener should just be triggered only once and then discarded.
   * @returns The updated [[BarcodePicker]] object.
   */
  // tslint:disable-next-line:bool-param-default
  public on(eventName: EventName, listener: ListenerFn, once?: boolean): BarcodePicker;
  /**
   * Add the listener function to the listeners array for the [[ready]] event, fired when the external
   * Scandit Engine library has been loaded and the barcode picker can thus start to scan barcodes.
   * If the library has already been loaded the listener is called immediately.
   *
   * No checks are made to see if the listener has already been added.
   * Multiple calls passing the same listener will result in the listener being added, and called, multiple times.
   *
   * @param eventName The name of the event to listen to.
   * @param listener The listener function.
   * @returns The updated [[BarcodePicker]] object.
   */
  public on(eventName: "ready", listener: () => void): BarcodePicker;
  /**
   * Add the listener function to the listeners array for the [[submitFrame]] event, fired when a new frame is submitted
   * to the engine to be processed. As the frame is not processed yet, the [[ScanResult.barcodes]] property will
   * always be empty (no results yet).
   *
   * No checks are made to see if the listener has already been added.
   * Multiple calls passing the same listener will result in the listener being added, and called, multiple times.
   *
   * @param eventName The name of the event to listen to.
   * @param listener The listener function, which will be invoked with a [[ScanResult]] object.
   * @param once <div class="tsd-signature-symbol">Default =&nbsp;false</div>
   * Whether the listener should just be triggered only once and then discarded.
   * @returns The updated [[BarcodePicker]] object.
   */
  public on(
    eventName: "submitFrame",
    listener: (scanResult: ScanResult) => void,
    // tslint:disable-next-line:bool-param-default
    once?: boolean
  ): BarcodePicker;
  /**
   * Add the listener function to the listeners array for the [[processFrame]] event, fired when a new frame is
   * processed. This event is fired on every frame, independently from the number of recognized barcodes (can be none).
   * The returned barcodes are affected by [[ScanSettings]]'s *codeDuplicateFilter* option.
   *
   * No checks are made to see if the listener has already been added.
   * Multiple calls passing the same listener will result in the listener being added, and called, multiple times.
   *
   * @param eventName The name of the event to listen to.
   * @param listener The listener function, which will be invoked with a [[ScanResult]] object.
   * @param once <div class="tsd-signature-symbol">Default =&nbsp;false</div>
   * Whether the listener should just be triggered only once and then discarded.
   * @returns The updated [[BarcodePicker]] object.
   */
  public on(
    // tslint:disable-next-line:unified-signatures
    eventName: "processFrame",
    listener: (scanResult: ScanResult) => void,
    // tslint:disable-next-line:bool-param-default
    once?: boolean
  ): BarcodePicker;
  /**
   * Add the listener function to the listeners array for the [[scan]] event, fired when new barcodes
   * are recognized in the image frame. The returned barcodes are affected by [[ScanSettings]]'s *codeDuplicateFilter*
   * option.
   *
   * No checks are made to see if the listener has already been added.
   * Multiple calls passing the same listener will result in the listener being added, and called, multiple times.
   *
   * @param eventName The name of the event to listen to.
   * @param listener The listener function, which will be invoked with a [[ScanResult]] object.
   * @param once <div class="tsd-signature-symbol">Default =&nbsp;false</div>
   * Whether the listener should just be triggered only once and then discarded.
   * @returns The updated [[BarcodePicker]] object.
   */
  public on(
    // tslint:disable-next-line:unified-signatures
    eventName: "scan",
    listener: (scanResult: ScanResult) => void,
    // tslint:disable-next-line:bool-param-default
    once?: boolean
  ): BarcodePicker;
  /**
   * Add the listener function to the listeners array for the [[scanError]] event, fired when an error occurs
   * during scanning initialization and execution. The barcode picker will be automatically paused when this happens.
   *
   * No checks are made to see if the listener has already been added.
   * Multiple calls passing the same listener will result in the listener being added, and called, multiple times.
   *
   * @param eventName The name of the event to listen to.
   * @param listener The listener function, which will be invoked with an `ScanditEngineError` object.
   * @param once <div class="tsd-signature-symbol">Default =&nbsp;false</div>
   * Whether the listener should just be triggered only once and then discarded.
   * @returns The updated [[BarcodePicker]] object.
   */
  // tslint:disable-next-line:bool-param-default
  public on(eventName: "scanError", listener: (error: Error) => void, once?: boolean): BarcodePicker;
  public on(eventName: EventName, listener: ListenerFn, once: boolean = false): BarcodePicker {
    if (eventName === "ready") {
      if (this.isReadyToWork) {
        listener();
      } else {
        this.eventEmitter.once(eventName, listener, this);
      }
    } else {
      if (once === true) {
        this.eventEmitter.once(eventName, listener, this);
      } else {
        this.eventEmitter.on(eventName, listener, this);
      }
    }
 
    return this;
  }
 
  /**
   * Remove the specified listener from the given event's listener array.
   *
   * @param eventName The name of the event from which to remove the listener.
   * @param listener The listener function to be removed.
   * @returns The updated [[BarcodePicker]] object.
   */
  public removeListener(eventName: EventName, listener: ListenerFn): BarcodePicker {
    this.eventEmitter.removeListener(eventName, listener);
 
    return this;
  }
 
  /**
   * Remove all listeners from the given event's listener array.
   *
   * @param eventName The name of the event from which to remove all listeners.
   * @returns The updated [[BarcodePicker]] object.
   */
  public removeAllListeners(eventName: EventName): BarcodePicker {
    this.eventEmitter.removeAllListeners(eventName);
 
    return this;
  }
 
  /**
   * *See the [[on]] method.*
   *
   * @param eventName The name of the event to listen to.
   * @param listener The listener function.
   * @param once <div class="tsd-signature-symbol">Default =&nbsp;false</div>
   * Whether the listener should just be triggered only once and then discarded.
   * @returns The updated [[BarcodePicker]] object.
   */
  // tslint:disable-next-line:bool-param-default
  public addListener(eventName: EventName, listener: ListenerFn, once?: boolean): BarcodePicker {
    return this.on(eventName, listener, once);
  }
 
  /**
   * Set the GUI style for the picker.
   *
   * In Single Image Mode this method has no effect.
   *
   * When the GUI style is set to *laser* or *viewfinder*, the GUI will flash on barcode recognition.
   * Note that the GUI will flash if there's at least a barcode not rejected via [[ScanResult.rejectCode]].
   *
   * @param guiStyle The new GUI style to be applied.
   * @returns The updated [[BarcodePicker]] object.
   */
  public setGuiStyle(guiStyle: BarcodePicker.GuiStyle): BarcodePicker {
    this.gui.setGuiStyle(guiStyle);
 
    return this;
  }
 
  /**
   * Set the fit type for the video element of the picker.
   *
   * If the "cover" type is selected the maximum available search area for barcode detection is (continuously) adjusted
   * automatically according to the visible area of the picker.
   *
   * In Single Image Mode this method has no effect.
   *
   * @param objectFit The new fit type to be applied.
   * @returns The updated [[BarcodePicker]] object.
   */
  public setVideoFit(objectFit: BarcodePicker.ObjectFit): BarcodePicker {
    this.gui.setVideoFit(objectFit);
 
    return this;
  }
 
  /**
   * Access the currently set or default camera, requesting user permissions if needed.
   * This method is meant to be used after the picker has been initialized with disabled camera access
   * (*accessCamera*=false) or after [[pauseScanning]] has been called with the pause camera stream option.
   * Calling this doesn't do anything if the camera is already being accessed.
   *
   * Depending on device features and user permissions for camera access, any of the following errors
   * could be the rejected result of the returned promise:
   * - `AbortError`
   * - `NoCameraAvailableError`
   * - `NotAllowedError`
   * - `NotFoundError`
   * - `NotReadableError`
   * - `SecurityError`
   *
   * In Single Image Mode this method has no effect.
   *
   * @returns A promise resolving to the updated [[BarcodePicker]] object when the camera is accessed.
   */
  public async accessCamera(): Promise<BarcodePicker> {
    if (!this.cameraAccess || this.cameraManager.activeCamera == null) {
      await this.cameraManager.setupCameras();
      this.cameraAccess = true;
    }
 
    return this;
  }
 
  /**
   * Create a new parser object.
   *
   * @param dataFormat The format of the input data for the parser.
   * @returns The newly created parser.
   */
  public createParserForFormat(dataFormat: Parser.DataFormat): Parser {
    return this.scanner.createParserForFormat(dataFormat);
  }
 
  /**
   * Reassign the barcode picker to a different HTML element.
   *
   * All the barcode picker elements inside the current origin element will be moved to the new given one.
   *
   * If an invalid element is given, a `NoOriginElementError` error is thrown.
   *
   * @param originElement The HTMLElement into which all the necessary elements for the picker will be moved.
   * @returns The updated [[BarcodePicker]] object.
   */
  public reassignOriginElement(originElement: HTMLElement): BarcodePicker {
    if (!BrowserHelper.isValidHTMLElement(originElement)) {
      throw new CustomError({
        name: "NoOriginElementError",
        message: "A valid origin HTML element must be given",
      });
    }
 
    this.gui.reassignOriginElement(originElement);
 
    return this;
  }
 
  /**
   * Set the target frames per second to be processed by the scanning engine.
   *
   * The final speed is limited by the camera framerate (usually 30 FPS) and the frame processing time of the device.
   * By setting this to lower numbers devices can save power by performing less work during scanning operations,
   * depending on device speed (faster devices can "sleep" for longer periods).
   *
   * In Single Image Mode this method has no effect.
   *
   * @param targetScanningFPS The target frames per second to be processed.
   * Must be a number bigger than 0, by default set to 30.
   * @returns The updated [[BarcodePicker]] object.
   */
  public setTargetScanningFPS(targetScanningFPS: number): BarcodePicker {
    if (targetScanningFPS <= 0) {
      targetScanningFPS = 30;
    }
    this.targetScanningFPS = targetScanningFPS;
 
    return this;
  }
 
  /**
   * @returns The internally used initialized (and possibly configured) [[Scanner]] object instance.
   */
  public getScanner(): Scanner {
    return this.scanner;
  }
 
  /**
   * Clear the internal scanner session.
   *
   * This removes all recognized barcodes from the scanner session and allows them to be scanned again in case a custom
   * *codeDuplicateFilter* option was set in the [[ScanSettings]].
   *
   * @returns The updated [[BarcodePicker]] object.
   */
  public clearSession(): BarcodePicker {
    this.scanner.clearSession();
 
    return this;
  }
 
  /**
   * Set the area of the laser displayed when the GUI style is set to *laser* (the laser will match the width and be
   * vertically centered).
   * Note that this functionality affects UI only and doesn't change the actual *searchArea* option set via
   * [[ScanSettings]]. If no area is passed, the default automatic size behaviour is set, where the laser will match
   * the current area of the image in which barcodes are searched, controlled via the *searchArea* option in
   * [[ScanSettings]].
   *
   * @param area The new search area, by default the area will match [[ScanSettings]]'s *searchArea* option.
   * @returns The updated [[BarcodePicker]] object.
   */
  public setLaserArea(area?: SearchArea): BarcodePicker {
    this.gui.setLaserArea(area);
 
    return this;
  }
 
  /**
   * Set the area of the viewfinder displayed when the GUI style is set to *viewfinder*.
   * Note that this functionality affects UI only and doesn't change the actual search area set via [[ScanSettings]].
   * If no area is passed, the default automatic size behaviour is set, where the viewfinder will match the current area
   * of the image in which barcodes are searched, controlled via the *searchArea* option in [[ScanSettings]].
   *
   * @param area The new search area, by default the area will match the [[ScanSettings]]'s *searchArea*.
   * @returns The updated [[BarcodePicker]] object.
   */
  public setViewfinderArea(area?: SearchArea): BarcodePicker {
    this.gui.setViewfinderArea(area);
 
    return this;
  }
 
  private triggerFatalError(error: Error): void {
    this.fatalError = error;
    console.error(error);
  }
 
  private handleScanResult(scanResult: ScanResult): void {
    scanResult = new ScanResult(scanResult.barcodes, this.externalImageData, scanResult.imageSettings);
 
    this.eventEmitter.emit("processFrame", scanResult);
 
    if (scanResult.barcodes.length !== 0) {
      // This will get executed only after the other existing listeners for "processFrame" and "scan" are executed
      this.eventEmitter.once("scan", () => {
        if (
          scanResult.barcodes.some((barcode) => {
            return !scanResult.rejectedCodes.has(barcode);
          })
        ) {
          this.gui.flashGUI();
          if (this.playSoundOnScan) {
            this.beepSound.play();
          }
          if (this.vibrateOnScan) {
            this.vibrateFunction?.call(navigator, 300);
          }
        }
      });
      this.eventEmitter.emit("scan", scanResult);
    }
  }
 
  private scheduleVideoProcessing(timeout: number = 0): void {
    window.setTimeout(async () => {
      await this.videoProcessing();
    }, timeout); // Leave some breathing room for other operations
  }
 
  private async scheduleNextVideoProcessing(processingStartTime: number): Promise<void> {
    if (this.targetScanningFPS < 60) {
      if (this.averageProcessingTime == null) {
        this.averageProcessingTime = performance.now() - processingStartTime;
      } else {
        this.averageProcessingTime = this.averageProcessingTime * 0.9 + (performance.now() - processingStartTime) * 0.1;
      }
      const nextProcessingCallDelay: number = Math.max(0, 1000 / this.targetScanningFPS - this.averageProcessingTime);
      if (Math.round(nextProcessingCallDelay) <= 16) {
        await this.videoProcessing();
      } else {
        this.scheduleVideoProcessing(nextProcessingCallDelay);
      }
    } else {
      await this.videoProcessing();
    }
  }
 
  private async processVideoFrame(highQualitySingleFrameMode: boolean): Promise<void> {
    this.internalImageData = this.gui.getImageData(this.internalImageData);
 
    // This could happen in unexpected situations and should be temporary
    // istanbul ignore if
    if (this.internalImageData == null) {
      return;
    }
 
    if (this.externalImageData == null || this.externalImageData.length !== this.internalImageData.length) {
      this.externalImageData = new Uint8Array(this.internalImageData);
    } else {
      this.externalImageData.set(this.internalImageData);
    }
 
    if (!this.scanningPaused) {
      if (this.eventEmitter.listenerCount("submitFrame") > 0) {
        this.eventEmitter.emit(
          "submitFrame",
          new ScanResult([], this.externalImageData, <ImageSettings>this.scanner.getImageSettings())
        );
      }
 
      try {
        const scanResult: ScanResult = await this.scanner.processImage(
          this.internalImageData,
          highQualitySingleFrameMode
        );
        this.internalImageData = scanResult.imageData;
        // Paused status could have changed in the meantime
        if (!this.scanningPaused) {
          this.handleScanResult(scanResult);
        }
      } catch (error) {
        Iif (error.name === "ImageSettingsDataMismatch") {
          // This could happen in unexpected situations and should be temporary
          return;
        }
        this.pauseScanning();
        this.eventEmitter.emit("scanError", error);
      }
    }
  }
 
  private async videoProcessing(): Promise<void> {
    if (this.destroyed) {
      return;
    }
 
    if (
      this.cameraManager.activeCamera?.currentResolution == null ||
      this.fatalError != null ||
      this.scanningPaused ||
      !this.scanner.isReady() ||
      this.scanner.isBusyProcessing() ||
      this.latestVideoTimeProcessed === this.gui.getVideoCurrentTime()
    ) {
      this.scheduleVideoProcessing();
 
      return;
    }
 
    if (Ithis.latestVideoTimeProcessed == null) {
      // Show active GUI if needed, as now it's the moment the scanner is ready and used for the first time
      await this.resumeScanning();
    }
 
    const processingStartTime: number = performance.now();
    this.latestVideoTimeProcessed = this.gui.getVideoCurrentTime();
 
    await this.processVideoFrame(false);
    await this.scheduleNextVideoProcessing(processingStartTime);
  }
 
  private handleScannerReady(): void {
    this.isReadyToWork = true;
    this.eventEmitter.emit("ready");
  }
}
 
// istanbul ignore next
export namespace BarcodePicker {
  /**
   * Fired when the external Scandit Engine library has been loaded and the barcode picker can thus start to scan
   * barcodes.
   *
   * @asMemberOf BarcodePicker
   * @event
   */
  // @ts-ignore
  declare function ready(): void;
  /**
   * Fired when a new frame is submitted to the engine to be processed. As the frame is not processed yet, the
   * [[ScanResult.barcodes]] property will always be empty (no results yet).
   *
   * @asMemberOf BarcodePicker
   * @event
   * @param scanResult The result of the scanning operation on the image.
   */
  // @ts-ignore
  declare function submitFrame(scanResult: ScanResult): void;
  /**
   * Fired when a new frame is processed by the engine. This event is fired on every frame, independently from the
   * number of recognized barcodes (can be none). The returned barcodes are affected by [[ScanSettings]]'s
   * *codeDuplicateFilter* option.
   *
   * @asMemberOf BarcodePicker
   * @event
   * @param scanResult The result of the scanning operation on the image.
   */
  // @ts-ignore
  declare function processFrame(scanResult: ScanResult): void;
  /**
   * Fired when new barcodes are recognized in the image frame. The returned barcodes are affected by [[ScanSettings]]'s
   * *codeDuplicateFilter* option.
   *
   * @asMemberOf BarcodePicker
   * @event
   * @param scanResult The result of the scanning operation on the image.
   */
  // @ts-ignore
  declare function scan(scanResult: ScanResult): void;
  /**
   * Fired when an error occurs during scanning initialization and execution. The barcode picker will be automatically
   * paused when this happens.
   *
   * @asMemberOf BarcodePicker
   * @event
   * @param error The ScanditEngineError that was triggered.
   */
  // @ts-ignore
  declare function scanError(error: Error): void;
 
  /**
   * GUI style to be used by a barcode picker, used to hint barcode placement in the frame.
   */
  export enum GuiStyle {
    /**
     * No GUI is shown to indicate where the barcode should be placed.
     * Be aware that the Scandit logo continues to be displayed as showing it is part of the license agreement.
     */
    NONE = "none",
    /**
     * A laser line is shown.
     */
    LASER = "laser",
    /**
     * A rectangular viewfinder with rounded corners is shown.
     */
    VIEWFINDER = "viewfinder",
  }
 
  /**
   * Fit type used to control the resizing (scale) of the barcode picker to fit in its container *originElement*.
   */
  export enum ObjectFit {
    /**
     * Scale to maintain aspect ratio while fitting within the *originElement*'s content box.
     * Aspect ratio is preserved, so the barcode picker will be "letterboxed" if its aspect ratio
     * does not match the aspect ratio of the box.
     */
    CONTAIN = "contain",
    /**
     * Scale to maintain aspect ratio while filling the *originElement*'s entire content box.
     * Aspect ratio is preserved, so the barcode picker will be clipped to fit if its aspect ratio
     * does not match the aspect ratio of the box.
     */
    COVER = "cover",
  }
}