├── example ├── assets │ └── .gitkeep ├── favicon.ico ├── typings.d.ts ├── app │ ├── app.component.html │ ├── app.module.ts │ ├── app.component.scss │ └── app.component.ts ├── tsconfig.app.json ├── index.html ├── main.ts ├── tsconfig.spec.json ├── test.ts └── polyfills.ts ├── config ├── environment.prod.ts └── environment.ts ├── src ├── index.ts ├── qr-scanner.module.ts ├── lib │ └── qr-decoder │ │ ├── errorlevel.ts │ │ ├── bitmat.ts │ │ ├── decoder.ts │ │ ├── datablock.ts │ │ ├── datamask.ts │ │ ├── perpesctivetransform.ts │ │ ├── grid.ts │ │ ├── formatinf.ts │ │ ├── rsdecoder.ts │ │ ├── bmparser.ts │ │ ├── qrcode.ts │ │ ├── alignpat.ts │ │ ├── gf256.ts │ │ ├── databr.ts │ │ ├── detector.ts │ │ ├── version.ts │ │ └── findpat.ts └── qr-scanner.component.ts ├── ng-package.json ├── tsconfig.json ├── .gitignore ├── .npmignore ├── package.json ├── README.md ├── tslint.json ├── angular.json └── LICENSE /example/assets/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /config/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './qr-scanner.module'; 2 | export * from './qr-scanner.component'; -------------------------------------------------------------------------------- /example/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/goergch/angular2-qrscanner/HEAD/example/favicon.ico -------------------------------------------------------------------------------- /example/typings.d.ts: -------------------------------------------------------------------------------- 1 | /* SystemJS module definition */ 2 | declare var module: NodeModule; 3 | interface NodeModule { 4 | id: string; 5 | } 6 | -------------------------------------------------------------------------------- /ng-package.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/ng-packagr/ng-package.schema.json", 3 | "lib": { 4 | "entryFile": "src/index.ts" 5 | } 6 | } -------------------------------------------------------------------------------- /example/app/app.component.html: -------------------------------------------------------------------------------- 1 | 7 | -------------------------------------------------------------------------------- /example/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "baseUrl": "./", 6 | "module": "es2015", 7 | "types": [] 8 | }, 9 | "exclude": [ 10 | "test.ts", 11 | "**/*.spec.ts" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /example/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Angular Library Starter Kit 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /config/environment.ts: -------------------------------------------------------------------------------- 1 | // The file contents for the current environment will overwrite these during build. 2 | // The build system defaults to the dev environment which uses `environment.ts`, but if you do 3 | // `ng build --env=prod` then `environment.prod.ts` will be used instead. 4 | // The list of which env maps to which file can be found in `.angular-cli.json`. 5 | 6 | export const environment = { 7 | production: false 8 | }; 9 | -------------------------------------------------------------------------------- /example/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from '../config/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule) 12 | .catch(err => console.log(err)); 13 | -------------------------------------------------------------------------------- /example/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "baseUrl": "./", 6 | "module": "commonjs", 7 | "target": "es5", 8 | "types": [ 9 | "jasmine", 10 | "node" 11 | ] 12 | }, 13 | "files": [ 14 | "test.ts", 15 | "polyfills.ts" 16 | ], 17 | "include": [ 18 | "**/*.spec.ts", 19 | "**/*.d.ts", 20 | "../src/*.spec.ts" 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /example/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | 4 | import { NgQrScannerModule } from '../../src'; 5 | 6 | import { AppComponent } from './app.component'; 7 | 8 | @NgModule({ 9 | imports: [ 10 | BrowserModule, 11 | NgQrScannerModule, 12 | ], 13 | declarations: [ 14 | AppComponent, 15 | ], 16 | providers: [], 17 | bootstrap: [AppComponent] 18 | }) 19 | export class AppModule { } 20 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "outDir": "./dist/out-tsc", 5 | "sourceMap": true, 6 | "declaration": false, 7 | "moduleResolution": "node", 8 | "emitDecoratorMetadata": true, 9 | "experimentalDecorators": true, 10 | "target": "es5", 11 | "typeRoots": [ 12 | "node_modules/@types" 13 | ], 14 | "lib": [ 15 | "es2017", 16 | "dom" 17 | ], 18 | "module": "es2015", 19 | "baseUrl": "./" 20 | } 21 | } -------------------------------------------------------------------------------- /src/qr-scanner.module.ts: -------------------------------------------------------------------------------- 1 | import {ModuleWithProviders, NgModule} from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { QrScannerComponent } from './qr-scanner.component'; 4 | 5 | @NgModule({ 6 | imports: [ 7 | CommonModule 8 | ], 9 | declarations: [QrScannerComponent], 10 | exports: [QrScannerComponent] 11 | }) 12 | export class NgQrScannerModule { 13 | static forRoot(): ModuleWithProviders { 14 | return { 15 | ngModule: NgQrScannerModule 16 | }; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /dist-ghpages 6 | /tmp 7 | /out-tsc 8 | 9 | # dependencies 10 | /node_modules 11 | 12 | # IDEs and editors 13 | /.idea 14 | .project 15 | .classpath 16 | .c9/ 17 | *.launch 18 | .settings/ 19 | *.sublime-workspace 20 | 21 | # IDE - VSCode 22 | .vscode/* 23 | !.vscode/settings.json 24 | !.vscode/tasks.json 25 | !.vscode/launch.json 26 | !.vscode/extensions.json 27 | 28 | # misc 29 | /.sass-cache 30 | /connect.lock 31 | /coverage 32 | /libpeerconnection.log 33 | npm-debug.log 34 | testem.log 35 | /typings 36 | 37 | # e2e 38 | /e2e/*.js 39 | /e2e/*.map 40 | 41 | # System Files 42 | .DS_Store 43 | Thumbs.db 44 | -------------------------------------------------------------------------------- /example/app/app.component.scss: -------------------------------------------------------------------------------- 1 | @import url('https://fonts.googleapis.com/css?family=Montserrat|Open+Sans'); 2 | 3 | html, body { 4 | color: #444; 5 | font-family: 'Open Sans', sans-serif; 6 | background: #4aabc9; 7 | background: linear-gradient(135deg, #4aabc9 0%,#7db9e8 100%); 8 | margin: 0; 9 | padding: 0; 10 | width: 100%; 11 | height: 100%; 12 | } 13 | 14 | h1 { 15 | font-family: 'Montserrat'; 16 | font-weight: 200; 17 | padding: 30px; 18 | margin: 0; 19 | } 20 | 21 | a.neat { 22 | color: inherit; 23 | text-decoration: none; 24 | } 25 | 26 | a.shadowy { 27 | padding: .5rem 1rem; 28 | transition: .2s all ease-in; 29 | 30 | &:hover { 31 | color: #4aabc9; 32 | background-color: #fff; 33 | } 34 | } 35 | 36 | .greetings { 37 | color: #fff; 38 | } 39 | 40 | .center { 41 | height: 100%; 42 | display: flex; 43 | align-items: center; 44 | justify-content: center; 45 | text-align: center; 46 | } 47 | -------------------------------------------------------------------------------- /example/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/dist/long-stack-trace-zone'; 4 | import 'zone.js/dist/proxy.js'; 5 | import 'zone.js/dist/sync-test'; 6 | import 'zone.js/dist/jasmine-patch'; 7 | import 'zone.js/dist/async-test'; 8 | import 'zone.js/dist/fake-async-test'; 9 | import { getTestBed } from '@angular/core/testing'; 10 | import { 11 | BrowserDynamicTestingModule, 12 | platformBrowserDynamicTesting 13 | } from '@angular/platform-browser-dynamic/testing'; 14 | 15 | // Unfortunately there's no typing for the `__karma__` variable. Just declare it as any. 16 | declare const __karma__: any; 17 | declare const require: any; 18 | 19 | // Prevent Karma from running prematurely. 20 | __karma__.loaded = function () {}; 21 | 22 | // First, initialize the Angular testing environment. 23 | getTestBed().initTestEnvironment( 24 | BrowserDynamicTestingModule, 25 | platformBrowserDynamicTesting() 26 | ); 27 | // Then we find all the tests. 28 | const contextExample = require.context('./', true, /\.spec\.ts$/); 29 | const contextSrc = require.context('../src/', true, /\.spec\.ts$/); 30 | // And load the modules. 31 | contextExample.keys().map(contextExample); 32 | contextSrc.keys().map(contextSrc); 33 | // Finally, start Karma to run the tests. 34 | __karma__.start(); 35 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | *.ts 3 | !*.d.ts 4 | src/ 5 | 6 | # Created by https://www.gitignore.io/api/webstorm 7 | 8 | ### WebStorm ### 9 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 10 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 11 | 12 | # User-specific stuff: 13 | .idea/**/workspace.xml 14 | .idea/**/tasks.xml 15 | .idea/dictionaries 16 | 17 | # Sensitive or high-churn files: 18 | .idea/**/dataSources/ 19 | .idea/**/dataSources.ids 20 | .idea/**/dataSources.xml 21 | .idea/**/dataSources.local.xml 22 | .idea/**/sqlDataSources.xml 23 | .idea/**/dynamic.xml 24 | .idea/**/uiDesigner.xml 25 | 26 | # Gradle: 27 | .idea/**/gradle.xml 28 | .idea/**/libraries 29 | 30 | # CMake 31 | cmake-build-debug/ 32 | 33 | # Mongo Explorer plugin: 34 | .idea/**/mongoSettings.xml 35 | 36 | ## File-based project format: 37 | *.iws 38 | 39 | ## Plugin-specific files: 40 | 41 | # IntelliJ 42 | /out/ 43 | 44 | # mpeltonen/sbt-idea plugin 45 | .idea_modules/ 46 | 47 | # JIRA plugin 48 | atlassian-ide-plugin.xml 49 | 50 | # Cursive Clojure plugin 51 | .idea/replstate.xml 52 | 53 | # Ruby plugin and RubyMine 54 | /.rakeTasks 55 | 56 | # Crashlytics plugin (for Android Studio and IntelliJ) 57 | com_crashlytics_export_strings.xml 58 | crashlytics.properties 59 | crashlytics-build.properties 60 | fabric.properties 61 | 62 | ### WebStorm Patch ### 63 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 64 | 65 | # *.iml 66 | # modules.xml 67 | # .idea/misc.xml 68 | # *.ipr 69 | 70 | # Sonarlint plugin 71 | .idea/sonarlint 72 | 73 | # End of https://www.gitignore.io/api/webstorm -------------------------------------------------------------------------------- /src/lib/qr-decoder/errorlevel.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Ported to JavaScript by Lazar Laszlo 2011 3 | 4 | lazarsoft@gmail.com, www.lazarsoft.info 5 | 6 | */ 7 | 8 | /* 9 | * 10 | * Copyright 2007 ZXing authors 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | 25 | export class ErrorCorrectionLevel{ 26 | 27 | static forBits( bits:any) 28 | { 29 | if (bits < 0 || bits >= this.FOR_BITS.length) 30 | { 31 | throw "ArgumentException"; 32 | } 33 | return this.FOR_BITS[bits]; 34 | } 35 | 36 | static L = new ErrorCorrectionLevel(0, 0x01, "L"); 37 | static M = new ErrorCorrectionLevel(1, 0x00, "M"); 38 | static Q = new ErrorCorrectionLevel(2, 0x03, "Q"); 39 | static H = new ErrorCorrectionLevel(3, 0x02, "H"); 40 | static FOR_BITS = new Array( ErrorCorrectionLevel.M, ErrorCorrectionLevel.L, ErrorCorrectionLevel.H, ErrorCorrectionLevel.Q); 41 | 42 | 43 | ordinal_Renamed_Field:any; 44 | bits:any; 45 | name:any; 46 | constructor(ordinal:any , bits:any, name:any){ 47 | 48 | this.ordinal_Renamed_Field = ordinal; 49 | this.bits = bits; 50 | this.name = name; 51 | } 52 | 53 | get Bits() 54 | { 55 | return this.bits; 56 | }; 57 | get Name() 58 | { 59 | return this.name; 60 | }; 61 | ordinal() 62 | { 63 | return this.ordinal_Renamed_Field; 64 | } 65 | 66 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular2-qrscanner", 3 | "version": "1.0.7", 4 | "scripts": { 5 | "start": "ng serve --aot --host 0.0.0.0", 6 | "build": "ng-packagr -p ng-package.json", 7 | "test": "npm run lint && ng test --watch false", 8 | "test-watch": "ng test", 9 | "e2e": "ng e2e", 10 | "e2e-watch": "watch \"ng e2e -s false\" src e2e --wait=1", 11 | "lint": "ng lint" 12 | }, 13 | "main": "./src/index.ts", 14 | "repository": { 15 | "type": "git", 16 | "url": "cd dishttps://github.com/goergch/angular2-qrscanner" 17 | }, 18 | "author": { 19 | "name": "Christian Görg", 20 | "email": "goergc@gmx.de" 21 | }, 22 | "contributors": [ 23 | "Mosh Mage (http://moshmage.gitlab.io)", 24 | "Christian Görg (http://github.com/goergch)" 25 | ], 26 | "keywords": [ 27 | "angular", 28 | "angular2", 29 | "QRCode", 30 | "Scanner" 31 | ], 32 | "license": "GPL-3.0-or-later", 33 | "bugs": { 34 | "url": "https://github.com/goergch/angular2-qrscanner/issues" 35 | }, 36 | "dependencies": {}, 37 | "devDependencies": { 38 | "@angular-devkit/build-angular": "~0.8.0", 39 | "@angular/cli": "^6.2.3", 40 | "@angular/common": "6.1.7", 41 | "@angular/compiler": "6.1.7", 42 | "@angular/compiler-cli": "6.1.7", 43 | "@angular/core": "6.1.7", 44 | "@angular/platform-browser": "6.1.7", 45 | "@angular/platform-browser-dynamic": "6.1.7", 46 | "@angular/platform-server": "6.1.7", 47 | "@types/es6-shim": "^0.31.37", 48 | "@types/jasmine": "^2.8.8", 49 | "@types/jasminewd2": "~2.0.3", 50 | "@types/node": "^9.6.31", 51 | "@types/selenium-webdriver": "^3.0.10", 52 | "codelyzer": "^4.4.4", 53 | "core-js": "^2.5.7", 54 | "moment": "~>2.19.3", 55 | "ng-packagr": "^2.4.5", 56 | "rxjs": "^6.3.2", 57 | "ssri": "~>5.2.2", 58 | "ts-node": "~4.1.0", 59 | "tsickle": "^0.26.0", 60 | "tslint": "^5.11.0", 61 | "typescript": "2.9.2", 62 | "zone.js": "^0.8.26" 63 | }, 64 | "publishConfig": { 65 | "registry": "https://registry.npmjs.org/" 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /example/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import {Component, ViewChild, ViewEncapsulation, OnInit, AfterViewInit} from '@angular/core'; 2 | import {QrScannerComponent} from '../../src'; 3 | 4 | @Component({ 5 | selector: 'app-root', 6 | templateUrl: './app.component.html', 7 | styleUrls: ['./app.component.scss'], 8 | encapsulation: ViewEncapsulation.None, 9 | }) 10 | export class AppComponent implements OnInit, AfterViewInit { 11 | 12 | 13 | decodedOutput(text: string) { 14 | console.log(text); 15 | } 16 | 17 | @ViewChild(QrScannerComponent) qrScannerComponent: QrScannerComponent ; 18 | 19 | 20 | 21 | ngOnInit() { 22 | 23 | // *** Use this code, if you want to define the used device *** 24 | // this.qrScannerComponent.getMediaDevices().then(devices => { 25 | // console.log(devices); 26 | // const videoDevices: MediaDeviceInfo[] = []; 27 | // for (const device of devices) { 28 | // if (device.kind.toString() === 'videoinput') { 29 | // videoDevices.push(device); 30 | // } 31 | // } 32 | // if (videoDevices.length > 0){ 33 | // let choosenDev; 34 | // for (const dev of videoDevices){ 35 | // if (dev.label.includes('front')){ 36 | // choosenDev = dev; 37 | // break; 38 | // } 39 | // } 40 | // if (choosenDev) { 41 | // this.qrScannerComponent.chooseCamera.next(choosenDev); 42 | // } else { 43 | // this.qrScannerComponent.chooseCamera.next(videoDevices[0]); 44 | // } 45 | // } 46 | // }); 47 | 48 | this.qrScannerComponent.capturedQr.subscribe(result => { 49 | console.log(result); 50 | // this.qrScannerComponent.stopScanning(); 51 | }); 52 | 53 | 54 | 55 | } 56 | 57 | ngAfterViewInit() { 58 | // *** Use this code, if you want the user to decide, which camera to use 59 | this.qrScannerComponent.startScanning(null); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # angular2-qrscanner 2 | QrScanner will scan for a QRCode from your Web-cam and return its 3 | string representation by drawing the captured image onto a 2D Canvas 4 | and use [@LazarSoft/jsqrcode](https://github.com/LazarSoft/jsqrcode) to check for a valid QRCode every *Xms* 5 | 6 | ### usage 7 | ```bash 8 | $ npm install --save angular2-qrscanner 9 | ``` 10 | 11 | ```typescript 12 | // app.module.ts 13 | import { NgQrScannerModule } from 'angular2-qrscanner'; 14 | @NgModule({ 15 | declarations: [ 16 | // ... 17 | ], 18 | imports: [ 19 | // ... 20 | NgQrScannerModule, 21 | ], 22 | providers: [], 23 | bootstrap: [ 24 | 25 | ] 26 | }) 27 | export class AppModule { } 28 | ``` 29 | 30 | ```html 31 | 32 | 35 | [canvasHeight]="720" 36 | [stopAfterScan]="true" 37 | [updateTime]="500"> 38 | 39 | 40 | ``` 41 | 42 | ```typescript 43 | // app.component.ts 44 | 45 | import {Component, ViewChild, ViewEncapsulation, OnInit} from '@angular/core'; 46 | import {QrScannerComponent} from 'angular2-qrscanner'; 47 | 48 | @Component({ 49 | selector: 'app-root', 50 | templateUrl: './app.component.html', 51 | styleUrls: ['./app.component.scss'], 52 | encapsulation: ViewEncapsulation.None, 53 | }) 54 | export class AppComponent implements OnInit { 55 | 56 | 57 | @ViewChild(QrScannerComponent) qrScannerComponent: QrScannerComponent ; 58 | 59 | ngOnInit() { 60 | this.qrScannerComponent.getMediaDevices().then(devices => { 61 | console.log(devices); 62 | const videoDevices: MediaDeviceInfo[] = []; 63 | for (const device of devices) { 64 | if (device.kind.toString() === 'videoinput') { 65 | videoDevices.push(device); 66 | } 67 | } 68 | if (videoDevices.length > 0){ 69 | let choosenDev; 70 | for (const dev of videoDevices){ 71 | if (dev.label.includes('front')){ 72 | choosenDev = dev; 73 | break; 74 | } 75 | } 76 | if (choosenDev) { 77 | this.qrScannerComponent.chooseCamera.next(choosenDev); 78 | } else { 79 | this.qrScannerComponent.chooseCamera.next(videoDevices[0]); 80 | } 81 | } 82 | }); 83 | 84 | this.qrScannerComponent.capturedQr.subscribe(result => { 85 | console.log(result); 86 | }); 87 | } 88 | } 89 | 90 | 91 | ``` 92 | -------------------------------------------------------------------------------- /example/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE9, IE10 and IE11 requires all of the following polyfills. **/ 22 | // import 'core-js/es6/symbol'; 23 | // import 'core-js/es6/object'; 24 | // import 'core-js/es6/function'; 25 | // import 'core-js/es6/parse-int'; 26 | // import 'core-js/es6/parse-float'; 27 | // import 'core-js/es6/number'; 28 | // import 'core-js/es6/math'; 29 | // import 'core-js/es6/string'; 30 | // import 'core-js/es6/date'; 31 | // import 'core-js/es6/array'; 32 | // import 'core-js/es6/regexp'; 33 | // import 'core-js/es6/map'; 34 | // import 'core-js/es6/weak-map'; 35 | // import 'core-js/es6/set'; 36 | 37 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 38 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 39 | 40 | /** IE10 and IE11 requires the following for the Reflect API. */ 41 | // import 'core-js/es6/reflect'; 42 | 43 | 44 | /** Evergreen browsers require these. **/ 45 | // Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove. 46 | import 'core-js/es7/reflect'; 47 | 48 | 49 | /** 50 | * Required to support Web Animations `@angular/platform-browser/animations`. 51 | * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation 52 | **/ 53 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 54 | 55 | 56 | 57 | /*************************************************************************************************** 58 | * Zone JS is required by Angular itself. 59 | */ 60 | import 'zone.js/dist/zone'; // Included with Angular CLI. 61 | 62 | 63 | 64 | /*************************************************************************************************** 65 | * APPLICATION IMPORTS 66 | */ 67 | 68 | /** 69 | * Date, currency, decimal and percent pipes. 70 | * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 71 | */ 72 | // import 'intl'; // Run `npm install --save intl`. 73 | /** 74 | * Need to import at least one locale-data with intl. 75 | */ 76 | // import 'intl/locale-data/jsonp/en'; 77 | -------------------------------------------------------------------------------- /src/lib/qr-decoder/bitmat.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Ported to JavaScript by Lazar Laszlo 2011 3 | 4 | lazarsoft@gmail.com, www.lazarsoft.info 5 | 6 | */ 7 | 8 | /* 9 | * 10 | * Copyright 2007 ZXing authors 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | 25 | 26 | export class BitMatrix{ 27 | width:number; 28 | height: number; 29 | rowSize: number; 30 | bits: any; 31 | constructor(width: number, height?: number){ 32 | if(!height) 33 | height=width; 34 | if (width < 1 || height < 1) 35 | { 36 | throw "Both dimensions must be greater than 0"; 37 | } 38 | this.width = width; 39 | this.height = height; 40 | this.rowSize = width >> 5; 41 | if ((width & 0x1f) != 0) 42 | { 43 | this.rowSize++; 44 | } 45 | this.bits = new Array(this.rowSize * height); 46 | for(var i=0;i= 0) 70 | return number >> bits; 71 | else 72 | return (number >> bits) + (2 << ~bits); 73 | } 74 | 75 | 76 | get_Renamed( x: any, y: any): any 77 | { 78 | var offset = y * this.rowSize + (x >> 5); 79 | return ((this.URShift(this.bits[offset], (x & 0x1f))) & 1) != 0; 80 | } 81 | set_Renamed( x: any, y: any): any 82 | { 83 | var offset = y * this.rowSize + (x >> 5); 84 | this.bits[offset] |= 1 << (x & 0x1f); 85 | } 86 | flip( x: any, y: any): void 87 | { 88 | var offset = y * this.rowSize + (x >> 5); 89 | this.bits[offset] ^= 1 << (x & 0x1f); 90 | } 91 | clear(): void 92 | { 93 | var max = this.bits.length; 94 | for (var i = 0; i < max; i++) 95 | { 96 | this.bits[i] = 0; 97 | } 98 | } 99 | setRegion( left: any, top: any, width: any, height: any): void 100 | { 101 | if (top < 0 || left < 0) 102 | { 103 | throw "Left and top must be nonnegative"; 104 | } 105 | if (height < 1 || width < 1) 106 | { 107 | throw "Height and width must be at least 1"; 108 | } 109 | var right = left + width; 110 | var bottom = top + height; 111 | if (bottom > this.height || right > this.width) 112 | { 113 | throw "The region must fit inside the matrix"; 114 | } 115 | for (var y = top; y < bottom; y++) 116 | { 117 | var offset = y * this.rowSize; 118 | for (var x = left; x < right; x++) 119 | { 120 | this.bits[offset + (x >> 5)] |= 1 << (x & 0x1f); 121 | } 122 | } 123 | } 124 | 125 | } 126 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rulesDirectory": [ 3 | "node_modules/codelyzer" 4 | ], 5 | "rules": { 6 | "arrow-return-shorthand": true, 7 | "callable-types": true, 8 | "class-name": true, 9 | "comment-format": [ 10 | true, 11 | "check-space" 12 | ], 13 | "curly": true, 14 | "eofline": true, 15 | "forin": true, 16 | "import-blacklist": [ 17 | true, 18 | "rxjs/Rx" 19 | ], 20 | "import-spacing": true, 21 | "indent": [ 22 | true, 23 | "spaces" 24 | ], 25 | "interface-over-type-literal": true, 26 | "label-position": true, 27 | "max-line-length": [ 28 | true, 29 | 140 30 | ], 31 | "member-access": false, 32 | "member-ordering": [ 33 | true, 34 | { 35 | "order": [ 36 | "static-field", 37 | "instance-field", 38 | "static-method", 39 | "instance-method" 40 | ] 41 | } 42 | ], 43 | "no-arg": true, 44 | "no-bitwise": true, 45 | "no-console": [ 46 | true, 47 | "debug", 48 | "info", 49 | "time", 50 | "timeEnd", 51 | "trace" 52 | ], 53 | "no-construct": true, 54 | "no-debugger": true, 55 | "no-duplicate-super": true, 56 | "no-empty": false, 57 | "no-empty-interface": true, 58 | "no-eval": true, 59 | "no-inferrable-types": [ 60 | true, 61 | "ignore-params" 62 | ], 63 | "no-misused-new": true, 64 | "no-non-null-assertion": true, 65 | "no-shadowed-variable": true, 66 | "no-string-literal": false, 67 | "no-string-throw": true, 68 | "no-switch-case-fall-through": true, 69 | "no-trailing-whitespace": true, 70 | "no-unnecessary-initializer": true, 71 | "no-unused-expression": true, 72 | "no-use-before-declare": true, 73 | "no-var-keyword": true, 74 | "object-literal-sort-keys": false, 75 | "one-line": [ 76 | true, 77 | "check-open-brace", 78 | "check-catch", 79 | "check-else", 80 | "check-whitespace" 81 | ], 82 | "prefer-const": true, 83 | "quotemark": [ 84 | true, 85 | "single" 86 | ], 87 | "radix": true, 88 | "semicolon": [ 89 | true, 90 | "always" 91 | ], 92 | "triple-equals": [ 93 | true, 94 | "allow-null-check" 95 | ], 96 | "typedef-whitespace": [ 97 | true, 98 | { 99 | "call-signature": "nospace", 100 | "index-signature": "nospace", 101 | "parameter": "nospace", 102 | "property-declaration": "nospace", 103 | "variable-declaration": "nospace" 104 | } 105 | ], 106 | "typeof-compare": true, 107 | "unified-signatures": true, 108 | "variable-name": false, 109 | "whitespace": [ 110 | true, 111 | "check-branch", 112 | "check-decl", 113 | "check-operator", 114 | "check-separator", 115 | "check-type" 116 | ], 117 | "angular-whitespace": [true, "check-interpolation"], 118 | "no-output-on-prefix": true, 119 | "use-input-property-decorator": true, 120 | "use-output-property-decorator": true, 121 | "use-host-property-decorator": true, 122 | "no-input-rename": true, 123 | "no-output-rename": true, 124 | "use-life-cycle-interface": true, 125 | "use-pipe-transform-interface": true, 126 | "component-class-suffix": true, 127 | "directive-class-suffix": true 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/lib/qr-decoder/decoder.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Ported to JavaScript by Lazar Laszlo 2011 3 | 4 | lazarsoft@gmail.com, www.lazarsoft.info 5 | 6 | */ 7 | 8 | /* 9 | * 10 | * Copyright 2007 ZXing authors 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | import {ReedSolomonDecoder} from "./rsdecoder" 25 | import {GF256} from "./gf256" 26 | import {BitMatrixParser} from "./bmparser" 27 | import {DataBlock} from "./datablock" 28 | import {QRCodeDataBlockReader} from "./databr" 29 | 30 | export class Decoder{ 31 | rsDecoder = new ReedSolomonDecoder(GF256.QR_CODE_FIELD); 32 | 33 | 34 | correctErrors( codewordBytes:any, numDataCodewords:any): void 35 | { 36 | var numCodewords = codewordBytes.length; 37 | // First read into an array of ints 38 | var codewordsInts = new Array(numCodewords); 39 | for (var i = 0; i < numCodewords; i++) 40 | { 41 | codewordsInts[i] = codewordBytes[i] & 0xFF; 42 | } 43 | var numECCodewords = codewordBytes.length - numDataCodewords; 44 | try 45 | { 46 | this.rsDecoder.decode(codewordsInts, numECCodewords); 47 | //var corrector = new ReedSolomon(codewordsInts, numECCodewords); 48 | //corrector.correct(); 49 | } 50 | catch ( rse) 51 | { 52 | throw rse; 53 | } 54 | // Copy back into array of bytes -- only need to worry about the bytes that were data 55 | // We don't care about errors in the error-correction codewords 56 | for (var i = 0; i < numDataCodewords; i++) 57 | { 58 | codewordBytes[i] = codewordsInts[i]; 59 | } 60 | } 61 | 62 | decode=function(bits: any) 63 | { 64 | var parser: BitMatrixParser = new BitMatrixParser(bits); 65 | var version = parser.readVersion(); 66 | var ecLevel = parser.readFormatInformation().ErrorCorrectionLevel; 67 | 68 | // Read codewords 69 | var codewords = parser.readCodewords(); 70 | 71 | // Separate into data blocks 72 | var dataBlocks = DataBlock.getDataBlocks(codewords, version, ecLevel); 73 | 74 | // Count total number of data bytes 75 | var totalBytes = 0; 76 | for (var i = 0; i < dataBlocks.length; i++) 77 | { 78 | totalBytes += dataBlocks[i].NumDataCodewords; 79 | } 80 | var resultBytes = new Array(totalBytes); 81 | var resultOffset = 0; 82 | 83 | // Error-correct and copy data blocks together into a stream of bytes 84 | for (var j = 0; j < dataBlocks.length; j++) 85 | { 86 | var dataBlock = dataBlocks[j]; 87 | var codewordBytes = dataBlock.Codewords; 88 | var numDataCodewords = dataBlock.NumDataCodewords; 89 | this.correctErrors(codewordBytes, numDataCodewords); 90 | for (var i = 0; i < numDataCodewords; i++) 91 | { 92 | resultBytes[resultOffset++] = codewordBytes[i]; 93 | } 94 | } 95 | 96 | // Decode the contents of that stream of bytes 97 | var reader = new QRCodeDataBlockReader(resultBytes, version.VersionNumber, ecLevel.Bits); 98 | return reader; 99 | //return DecodedBitStreamParser.decode(resultBytes, version, ecLevel); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/lib/qr-decoder/datablock.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Ported to JavaScript by Lazar Laszlo 2011 3 | 4 | lazarsoft@gmail.com, www.lazarsoft.info 5 | 6 | */ 7 | 8 | /* 9 | * 10 | * Copyright 2007 ZXing authors 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | 25 | export class DataBlock{ 26 | numDataCodewords:any; 27 | codewords: any; 28 | 29 | constructor(numDataCodewords:any, codewords:any){ 30 | this.numDataCodewords = numDataCodewords; 31 | this.codewords = codewords; 32 | } 33 | 34 | get NumDataCodewords(): any{ 35 | return this.numDataCodewords; 36 | } 37 | 38 | get Codewords(): any{ 39 | return this.codewords; 40 | } 41 | 42 | static getDataBlocks(rawCodewords: any, version: any, ecLevel: any) 43 | { 44 | 45 | if (rawCodewords.length != version.TotalCodewords) 46 | { 47 | throw "ArgumentException"; 48 | } 49 | 50 | // Figure out the number and size of data blocks used by this version and 51 | // error correction level 52 | var ecBlocks = version.getECBlocksForLevel(ecLevel); 53 | 54 | // First count the total number of data blocks 55 | var totalBlocks = 0; 56 | var ecBlockArray = ecBlocks.getECBlocks(); 57 | for (var i = 0; i < ecBlockArray.length; i++) 58 | { 59 | totalBlocks += ecBlockArray[i].Count; 60 | } 61 | 62 | // Now establish DataBlocks of the appropriate size and number of data codewords 63 | var result = new Array(totalBlocks); 64 | var numResultBlocks = 0; 65 | for (var j = 0; j < ecBlockArray.length; j++) 66 | { 67 | var ecBlock = ecBlockArray[j]; 68 | for (var i = 0; i < ecBlock.Count; i++) 69 | { 70 | var numDataCodewords = ecBlock.DataCodewords; 71 | var numBlockCodewords = ecBlocks.ECCodewordsPerBlock + numDataCodewords; 72 | result[numResultBlocks++] = new DataBlock(numDataCodewords, new Array(numBlockCodewords)); 73 | } 74 | } 75 | 76 | // All blocks have the same amount of data, except that the last n 77 | // (where n may be 0) have 1 more byte. Figure out where these start. 78 | var shorterBlocksTotalCodewords = result[0].codewords.length; 79 | var longerBlocksStartAt = result.length - 1; 80 | while (longerBlocksStartAt >= 0) 81 | { 82 | var numCodewords = result[longerBlocksStartAt].codewords.length; 83 | if (numCodewords == shorterBlocksTotalCodewords) 84 | { 85 | break; 86 | } 87 | longerBlocksStartAt--; 88 | } 89 | longerBlocksStartAt++; 90 | 91 | var shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.ECCodewordsPerBlock; 92 | // The last elements of result may be 1 element longer; 93 | // first fill out as many elements as all of them have 94 | var rawCodewordsOffset = 0; 95 | for (var i = 0; i < shorterBlocksNumDataCodewords; i++) 96 | { 97 | for (var j = 0; j < numResultBlocks; j++) 98 | { 99 | result[j].codewords[i] = rawCodewords[rawCodewordsOffset++]; 100 | } 101 | } 102 | // Fill out the last data block in the longer ones 103 | for (var j = longerBlocksStartAt; j < numResultBlocks; j++) 104 | { 105 | result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset++]; 106 | } 107 | // Now add in error correction blocks 108 | var max = result[0].codewords.length; 109 | for (var i = shorterBlocksNumDataCodewords; i < max; i++) 110 | { 111 | for (var j = 0; j < numResultBlocks; j++) 112 | { 113 | var iOffset = j < longerBlocksStartAt?i:i + 1; 114 | result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++]; 115 | } 116 | } 117 | return result; 118 | } 119 | } 120 | 121 | -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "angular2-qr-scanner-example": { 7 | "root": "", 8 | "sourceRoot": "example", 9 | "projectType": "application", 10 | "architect": { 11 | "build": { 12 | "builder": "@angular-devkit/build-angular:browser", 13 | "options": { 14 | "outputPath": "dist", 15 | "index": "example/index.html", 16 | "main": "example/main.ts", 17 | "tsConfig": "example/tsconfig.app.json", 18 | "polyfills": "example/polyfills.ts", 19 | "assets": [ 20 | "example/assets", 21 | "example/favicon.ico" 22 | ], 23 | "styles": [], 24 | "scripts": [] 25 | }, 26 | "configurations": { 27 | "prod": { 28 | "fileReplacements": [ 29 | { 30 | "replace": "example/config/environment.ts", 31 | "with": "example/config/environment.prod.ts" 32 | } 33 | ] 34 | }, 35 | "production": { 36 | "optimization": true, 37 | "outputHashing": "all", 38 | "sourceMap": false, 39 | "extractCss": true, 40 | "namedChunks": false, 41 | "aot": true, 42 | "extractLicenses": true, 43 | "vendorChunk": false, 44 | "buildOptimizer": true 45 | } 46 | } 47 | }, 48 | "serve": { 49 | "builder": "@angular-devkit/build-angular:dev-server", 50 | "options": { 51 | "browserTarget": "angular2-qr-scanner-example:build" 52 | }, 53 | "configurations": { 54 | "prod": { 55 | "browserTarget": "angular2-qr-scanner-example:build:prod" 56 | }, 57 | "production": { 58 | "browserTarget": "angular2-qr-scanner-example:build:production" 59 | } 60 | } 61 | }, 62 | "extract-i18n": { 63 | "builder": "@angular-devkit/build-angular:extract-i18n", 64 | "options": { 65 | "browserTarget": "angular2-qr-scanner-example:build" 66 | } 67 | }, 68 | "test": { 69 | "builder": "@angular-devkit/build-angular:karma", 70 | "options": { 71 | "main": "example/test.ts", 72 | "karmaConfig": "./karma.conf.js", 73 | "polyfills": "example/polyfills.ts", 74 | "tsConfig": "example/tsconfig.spec.json", 75 | "scripts": [], 76 | "styles": [], 77 | "assets": [ 78 | "example/assets", 79 | "example/favicon.ico" 80 | ] 81 | } 82 | }, 83 | "lint": { 84 | "builder": "@angular-devkit/build-angular:tslint", 85 | "options": { 86 | "tsConfig": [ 87 | "example/tsconfig.app.json", 88 | "example/tsconfig.spec.json" 89 | ], 90 | "exclude": [ 91 | "**/node_modules/**" 92 | ] 93 | } 94 | } 95 | } 96 | }, 97 | "angular2-qr-scanner-example-e2e": { 98 | "root": "e2e", 99 | "sourceRoot": "e2e", 100 | "projectType": "application", 101 | "architect": { 102 | "e2e": { 103 | "builder": "@angular-devkit/build-angular:protractor", 104 | "options": { 105 | "protractorConfig": "./protractor.conf.js", 106 | "devServerTarget": "angular2-qr-scanner-example:serve" 107 | } 108 | }, 109 | "lint": { 110 | "builder": "@angular-devkit/build-angular:tslint", 111 | "options": { 112 | "tsConfig": [], 113 | "exclude": [ 114 | "**/node_modules/**" 115 | ] 116 | } 117 | } 118 | } 119 | } 120 | }, 121 | "defaultProject": "angular2-qr-scanner-example", 122 | "schematics": { 123 | "@schematics/angular:class": { 124 | "spec": false 125 | }, 126 | "@schematics/angular:component": { 127 | "prefix": "app", 128 | "styleext": "scss" 129 | }, 130 | "@schematics/angular:directive": { 131 | "prefix": "app" 132 | } 133 | } 134 | } -------------------------------------------------------------------------------- /src/lib/qr-decoder/datamask.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Ported to JavaScript by Lazar Laszlo 2011 3 | 4 | lazarsoft@gmail.com, www.lazarsoft.info 5 | 6 | */ 7 | 8 | /* 9 | * 10 | * Copyright 2007 ZXing authors 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | 25 | export class DataMask000{ 26 | unmaskBitMatrix(bits:any, dimension:any):any 27 | { 28 | for (var i = 0; i < dimension; i++) 29 | { 30 | for (var j = 0; j < dimension; j++) 31 | { 32 | if (this.isMasked(i, j)) 33 | { 34 | bits.flip(j, i); 35 | } 36 | } 37 | } 38 | } 39 | isMasked=function( i:any, j:any) 40 | { 41 | return ((i + j) & 0x01) == 0; 42 | } 43 | } 44 | 45 | export class DataMask001{ 46 | unmaskBitMatrix(bits:any, dimension:any):any 47 | { 48 | for (var i = 0; i < dimension; i++) 49 | { 50 | for (var j = 0; j < dimension; j++) 51 | { 52 | if (this.isMasked(i, j)) 53 | { 54 | bits.flip(j, i); 55 | } 56 | } 57 | } 58 | } 59 | isMasked=function( i:any, j:any) 60 | { 61 | return (i & 0x01) == 0; 62 | } 63 | } 64 | 65 | 66 | export class DataMask010{ 67 | unmaskBitMatrix(bits:any, dimension:any):any 68 | { 69 | for (var i = 0; i < dimension; i++) 70 | { 71 | for (var j = 0; j < dimension; j++) 72 | { 73 | if (this.isMasked(i, j)) 74 | { 75 | bits.flip(j, i); 76 | } 77 | } 78 | } 79 | } 80 | isMasked=function( i:any, j:any) 81 | { 82 | return j % 3 == 0; 83 | } 84 | } 85 | export class DataMask011{ 86 | unmaskBitMatrix(bits:any, dimension:any):any 87 | { 88 | for (var i = 0; i < dimension; i++) 89 | { 90 | for (var j = 0; j < dimension; j++) 91 | { 92 | if (this.isMasked(i, j)) 93 | { 94 | bits.flip(j, i); 95 | } 96 | } 97 | } 98 | } 99 | isMasked=function( i:any, j:any) 100 | { 101 | return (i + j) % 3 == 0; 102 | } 103 | } 104 | 105 | export class DataMask100{ 106 | unmaskBitMatrix(bits:any, dimension:any):any 107 | { 108 | for (var i = 0; i < dimension; i++) 109 | { 110 | for (var j = 0; j < dimension; j++) 111 | { 112 | if (this.isMasked(i, j)) 113 | { 114 | bits.flip(j, i); 115 | } 116 | } 117 | } 118 | } 119 | 120 | URShift( number:any, bits:any):any 121 | { 122 | if (number >= 0) 123 | return number >> bits; 124 | else 125 | return (number >> bits) + (2 << ~bits); 126 | } 127 | 128 | isMasked=function( i:any, j:any) 129 | { 130 | return (((this.URShift(i, 1)) + (j / 3)) & 0x01) == 0; 131 | } 132 | } 133 | export class DataMask101{ 134 | unmaskBitMatrix(bits:any, dimension:any):any 135 | { 136 | for (var i = 0; i < dimension; i++) 137 | { 138 | for (var j = 0; j < dimension; j++) 139 | { 140 | if (this.isMasked(i, j)) 141 | { 142 | bits.flip(j, i); 143 | } 144 | } 145 | } 146 | } 147 | isMasked=function( i:any, j:any) 148 | { 149 | var temp = i * j; 150 | return (temp & 0x01) + (temp % 3) == 0; 151 | } 152 | } 153 | 154 | export class DataMask110{ 155 | unmaskBitMatrix(bits:any, dimension:any):any 156 | { 157 | for (var i = 0; i < dimension; i++) 158 | { 159 | for (var j = 0; j < dimension; j++) 160 | { 161 | if (this.isMasked(i, j)) 162 | { 163 | bits.flip(j, i); 164 | } 165 | } 166 | } 167 | } 168 | isMasked=function( i:any, j:any) 169 | { 170 | var temp = i * j; 171 | return (((temp & 0x01) + (temp % 3)) & 0x01) == 0; 172 | } 173 | } 174 | 175 | export class DataMask111{ 176 | unmaskBitMatrix(bits:any, dimension:any):any 177 | { 178 | for (var i = 0; i < dimension; i++) 179 | { 180 | for (var j = 0; j < dimension; j++) 181 | { 182 | if (this.isMasked(i, j)) 183 | { 184 | bits.flip(j, i); 185 | } 186 | } 187 | } 188 | } 189 | isMasked=function( i:any, j:any) 190 | { 191 | return ((((i + j) & 0x01) + ((i * j) % 3)) & 0x01) == 0; 192 | } 193 | } 194 | 195 | export class DataMask{ 196 | static DATA_MASKS = new Array(new DataMask000(), new DataMask001(), new DataMask010(), new DataMask011(), new DataMask100(), new DataMask101(), new DataMask110(), new DataMask111()); 197 | static forReference(reference:any):any 198 | { 199 | if (reference < 0 || reference > 7) 200 | { 201 | throw "System.ArgumentException"; 202 | } 203 | return DataMask.DATA_MASKS[reference]; 204 | } 205 | } 206 | 207 | 208 | -------------------------------------------------------------------------------- /src/lib/qr-decoder/perpesctivetransform.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Ported to JavaScript by Lazar Laszlo 2011 3 | 4 | lazarsoft@gmail.com, www.lazarsoft.info 5 | 6 | */ 7 | 8 | /* 9 | * 10 | * Copyright 2007 ZXing authors 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | export class PerspectiveTransform{ 25 | a11:number; 26 | a12:number; 27 | a13:number; 28 | a21:number; 29 | a22:number; 30 | a23:number; 31 | a31:number; 32 | a32:number; 33 | a33:number; 34 | 35 | constructor( a11:number, a21:number, a31:number, a12:number, a22:number, a32:number, a13:number, a23:number, a33:number) { 36 | this.a11 = a11; 37 | this.a12 = a12; 38 | this.a13 = a13; 39 | this.a21 = a21; 40 | this.a22 = a22; 41 | this.a23 = a23; 42 | this.a31 = a31; 43 | this.a32 = a32; 44 | this.a33 = a33; 45 | } 46 | transformPoints1=function( points:any) 47 | { 48 | var max = points.length; 49 | var a11 = this.a11; 50 | var a12 = this.a12; 51 | var a13 = this.a13; 52 | var a21 = this.a21; 53 | var a22 = this.a22; 54 | var a23 = this.a23; 55 | var a31 = this.a31; 56 | var a32 = this.a32; 57 | var a33 = this.a33; 58 | for (var i = 0; i < max; i += 2) 59 | { 60 | var x = points[i]; 61 | var y = points[i + 1]; 62 | var denominator = a13 * x + a23 * y + a33; 63 | points[i] = (a11 * x + a21 * y + a31) / denominator; 64 | points[i + 1] = (a12 * x + a22 * y + a32) / denominator; 65 | } 66 | } 67 | transformPoints2=function(xValues:any, yValues:any) 68 | { 69 | var n = xValues.length; 70 | for (var i = 0; i < n; i++) 71 | { 72 | var x = xValues[i]; 73 | var y = yValues[i]; 74 | var denominator = this.a13 * x + this.a23 * y + this.a33; 75 | xValues[i] = (this.a11 * x + this.a21 * y + this.a31) / denominator; 76 | yValues[i] = (this.a12 * x + this.a22 * y + this.a32) / denominator; 77 | } 78 | } 79 | buildAdjoint=function() 80 | { 81 | // Adjoint is the transpose of the cofactor matrix: 82 | return new PerspectiveTransform(this.a22 * this.a33 - this.a23 * this.a32, this.a23 * this.a31 - this.a21 * this.a33, this.a21 * this.a32 - this.a22 * this.a31, this.a13 * this.a32 - this.a12 * this.a33, this.a11 * this.a33 - this.a13 * this.a31, this.a12 * this.a31 - this.a11 * this.a32, this.a12 * this.a23 - this.a13 * this.a22, this.a13 * this.a21 - this.a11 * this.a23, this.a11 * this.a22 - this.a12 * this.a21); 83 | } 84 | times=function( other:any) 85 | { 86 | return new PerspectiveTransform(this.a11 * other.a11 + this.a21 * other.a12 + this.a31 * other.a13, this.a11 * other.a21 + this.a21 * other.a22 + this.a31 * other.a23, this.a11 * other.a31 + this.a21 * other.a32 + this.a31 * other.a33, this.a12 * other.a11 + this.a22 * other.a12 + this.a32 * other.a13, this.a12 * other.a21 + this.a22 * other.a22 + this.a32 * other.a23, this.a12 * other.a31 + this.a22 * other.a32 + this.a32 * other.a33, this.a13 * other.a11 + this.a23 * other.a12 +this.a33 * other.a13, this.a13 * other.a21 + this.a23 * other.a22 + this.a33 * other.a23, this.a13 * other.a31 + this.a23 * other.a32 + this.a33 * other.a33); 87 | } 88 | 89 | static quadrilateralToQuadrilateral( x0: any, y0: any, x1: any, y1: any, x2: any, y2: any, x3: any, y3: any 90 | , x0p: any, y0p: any, x1p: any, y1p: any, x2p: any, y2p: any, x3p: any, y3p: any) 91 | { 92 | 93 | var qToS = this.quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3); 94 | var sToQ = this.squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p); 95 | return sToQ.times(qToS); 96 | } 97 | 98 | static squareToQuadrilateral( x0:any, y0:any, x1:any, y1:any, x2:any, y2:any, x3:any, y3:any) 99 | { 100 | var dy2 = y3 - y2; 101 | var dy3 = y0 - y1 + y2 - y3; 102 | if (dy2 == 0.0 && dy3 == 0.0) 103 | { 104 | return new PerspectiveTransform(x1 - x0, x2 - x1, x0, y1 - y0, y2 - y1, y0, 0.0, 0.0, 1.0); 105 | } 106 | else 107 | { 108 | var dx1 = x1 - x2; 109 | var dx2 = x3 - x2; 110 | var dx3 = x0 - x1 + x2 - x3; 111 | var dy1 = y1 - y2; 112 | var denominator = dx1 * dy2 - dx2 * dy1; 113 | var a13 = (dx3 * dy2 - dx2 * dy3) / denominator; 114 | var a23 = (dx1 * dy3 - dx3 * dy1) / denominator; 115 | return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, a13, a23, 1.0); 116 | } 117 | } 118 | static quadrilateralToSquare( x0:any, y0:any, x1:any, y1:any, x2:any, y2:any, x3:any, y3:any) 119 | { 120 | // Here, the adjoint serves as the inverse: 121 | const t = this.squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3); 122 | return t.buildAdjoint(); 123 | } 124 | } -------------------------------------------------------------------------------- /src/lib/qr-decoder/grid.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Ported to JavaScript by Lazar Laszlo 2011 3 | 4 | lazarsoft@gmail.com, www.lazarsoft.info 5 | 6 | */ 7 | 8 | /* 9 | * 10 | * Copyright 2007 ZXing authors 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | 25 | 26 | import {PerspectiveTransform} from "./perpesctivetransform"; 27 | 28 | import {BitMatrix} from "./bitmat" 29 | 30 | 31 | export class GridSampler{ 32 | 33 | width: number; 34 | height: number; 35 | 36 | constructor(width:any, height:any){ 37 | this.width = width; 38 | this.height = height; 39 | } 40 | 41 | checkAndNudgePoints( image:any, points:any): void 42 | { 43 | var width = this.width; 44 | var height = this.height; 45 | // Check and nudge points from start until we see some that are OK: 46 | var nudged = true; 47 | for (var offset = 0; offset < points.length && nudged; offset += 2) 48 | { 49 | var x = Math.floor (points[offset]); 50 | var y = Math.floor( points[offset + 1]); 51 | if (x < - 1 || x > width || y < - 1 || y > height) 52 | { 53 | throw "Error.checkAndNudgePoints "; 54 | } 55 | nudged = false; 56 | if (x == - 1) 57 | { 58 | points[offset] = 0.0; 59 | nudged = true; 60 | } 61 | else if (x == width) 62 | { 63 | points[offset] = width - 1; 64 | nudged = true; 65 | } 66 | if (y == - 1) 67 | { 68 | points[offset + 1] = 0.0; 69 | nudged = true; 70 | } 71 | else if (y == height) 72 | { 73 | points[offset + 1] = height - 1; 74 | nudged = true; 75 | } 76 | } 77 | // Check and nudge points from end: 78 | nudged = true; 79 | for (var offset = points.length - 2; offset >= 0 && nudged; offset -= 2) 80 | { 81 | var x = Math.floor( points[offset]); 82 | var y = Math.floor( points[offset + 1]); 83 | if (x < - 1 || x > width || y < - 1 || y > height) 84 | { 85 | throw "Error.checkAndNudgePoints "; 86 | } 87 | nudged = false; 88 | if (x == - 1) 89 | { 90 | points[offset] = 0.0; 91 | nudged = true; 92 | } 93 | else if (x == width) 94 | { 95 | points[offset] = width - 1; 96 | nudged = true; 97 | } 98 | if (y == - 1) 99 | { 100 | points[offset + 1] = 0.0; 101 | nudged = true; 102 | } 103 | else if (y == height) 104 | { 105 | points[offset + 1] = height - 1; 106 | nudged = true; 107 | } 108 | } 109 | } 110 | 111 | 112 | 113 | sampleGrid3( image:any,rawImage: any, dimension:any, transform:any): any 114 | { 115 | var bits = new BitMatrix(dimension, dimension); 116 | var points = new Array(dimension << 1); 117 | for (var y = 0; y < dimension; y++) 118 | { 119 | var max = points.length; 120 | var iValue = y + 0.5; 121 | for (var x = 0; x < max; x += 2) 122 | { 123 | points[x] = (x >> 1) + 0.5; 124 | points[x + 1] = iValue; 125 | } 126 | transform.transformPoints1(points); 127 | // Quick check to see if points transformed to something inside the image; 128 | // sufficient to check the endpoints 129 | this.checkAndNudgePoints(image, points); 130 | try 131 | { 132 | for (var x = 0; x < max; x += 2) 133 | { 134 | var xpoint = (Math.floor( points[x]) * 4) + (Math.floor( points[x + 1]) * this.width * 4); 135 | var bit = image[Math.floor( points[x])+ this.width* Math.floor( points[x + 1])]; 136 | rawImage.data[xpoint] = bit?255:0; 137 | rawImage.data[xpoint+1] = bit?255:0; 138 | rawImage.data[xpoint+2] = 0; 139 | rawImage.data[xpoint+3] = 255; 140 | //bits[x >> 1][ y]=bit; 141 | if(bit) 142 | bits.set_Renamed(x >> 1, y); 143 | } 144 | } 145 | catch ( aioobe) 146 | { 147 | // This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting 148 | // transform gets "twisted" such that it maps a straight line of points to a set of points 149 | // whose endpoints are in bounds, but others are not. There is probably some mathematical 150 | // way to detect this about the transformation that I don't know yet. 151 | // This results in an ugly runtime exception despite our clever checks above -- can't have 152 | // that. We could check each point's coordinates but that feels duplicative. We settle for 153 | // catching and wrapping ArrayIndexOutOfBoundsException. 154 | throw "Error.checkAndNudgePoints"; 155 | } 156 | } 157 | return bits; 158 | } 159 | 160 | sampleGridx( image:any, dimension:any, p1ToX:any, p1ToY:any, p2ToX:any, p2ToY:any, p3ToX:any, p3ToY:any, p4ToX:any, p4ToY:any, p1FromX:any, p1FromY:any, p2FromX:any, p2FromY:any, p3FromX:any, p3FromY:any, p4FromX:any, p4FromY:any): any 161 | { 162 | 163 | 164 | var transform = PerspectiveTransform.quadrilateralToQuadrilateral(p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY); 165 | 166 | return this.sampleGrid3(image, {}, dimension, transform); 167 | } 168 | 169 | } 170 | 171 | 172 | 173 | 174 | 175 | -------------------------------------------------------------------------------- /src/lib/qr-decoder/formatinf.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Ported to JavaScript by Lazar Laszlo 2011 3 | 4 | lazarsoft@gmail.com, www.lazarsoft.info 5 | 6 | */ 7 | 8 | /* 9 | * 10 | * Copyright 2007 ZXing authors 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | import {ErrorCorrectionLevel} from "./errorlevel" 25 | 26 | 27 | export class FormatInformation { 28 | static FORMAT_INFO_MASK_QR = 0x5412; 29 | static FORMAT_INFO_DECODE_LOOKUP = new Array(new Array(0x5412, 0x00), new Array(0x5125, 0x01), new Array(0x5E7C, 0x02), new Array(0x5B4B, 0x03), new Array(0x45F9, 0x04), new Array(0x40CE, 0x05), new Array(0x4F97, 0x06), new Array(0x4AA0, 0x07), new Array(0x77C4, 0x08), new Array(0x72F3, 0x09), new Array(0x7DAA, 0x0A), new Array(0x789D, 0x0B), new Array(0x662F, 0x0C), new Array(0x6318, 0x0D), new Array(0x6C41, 0x0E), new Array(0x6976, 0x0F), new Array(0x1689, 0x10), new Array(0x13BE, 0x11), new Array(0x1CE7, 0x12), new Array(0x19D0, 0x13), new Array(0x0762, 0x14), new Array(0x0255, 0x15), new Array(0x0D0C, 0x16), new Array(0x083B, 0x17), new Array(0x355F, 0x18), new Array(0x3068, 0x19), new Array(0x3F31, 0x1A), new Array(0x3A06, 0x1B), new Array(0x24B4, 0x1C), new Array(0x2183, 0x1D), new Array(0x2EDA, 0x1E), new Array(0x2BED, 0x1F)); 30 | static BITS_SET_IN_HALF_BYTE = new Array(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4); 31 | static L = new ErrorCorrectionLevel(0, 0x01, "L"); 32 | static M = new ErrorCorrectionLevel(1, 0x00, "M"); 33 | static Q = new ErrorCorrectionLevel(2, 0x03, "Q"); 34 | static H = new ErrorCorrectionLevel(3, 0x02, "H"); 35 | static FOR_BITS = new Array(FormatInformation.M, FormatInformation.L, FormatInformation.H, FormatInformation.Q); 36 | errorCorrectionLevel: any; 37 | dataMask: any; 38 | 39 | constructor(formatInfo: any) { 40 | this.errorCorrectionLevel = ErrorCorrectionLevel.forBits((formatInfo >> 3) & 0x03); 41 | this.dataMask = (formatInfo & 0x07); 42 | } 43 | 44 | get ErrorCorrectionLevel() { 45 | return this.errorCorrectionLevel; 46 | }; 47 | 48 | get DataMask() { 49 | return this.dataMask; 50 | }; 51 | 52 | GetHashCode () { 53 | return (this.errorCorrectionLevel.ordinal() << 3) | this.dataMask; 54 | } 55 | 56 | Equals = function (o: any) { 57 | var other = o; 58 | return this.errorCorrectionLevel == other.errorCorrectionLevel && this.dataMask == other.dataMask; 59 | } 60 | 61 | static URShift(number: any, bits: any): any { 62 | if (number >= 0) 63 | return number >> bits; 64 | else 65 | return (number >> bits) + (2 << ~bits); 66 | } 67 | 68 | static numBitsDiffering (a: any, b: any) { 69 | a ^= b; // a now has a 1 bit exactly where its bit differs with b's 70 | // Count bits set quickly with a series of lookups: 71 | return FormatInformation.BITS_SET_IN_HALF_BYTE[a & 0x0F] 72 | + FormatInformation.BITS_SET_IN_HALF_BYTE[(this.URShift(a, 4) & 0x0F)] 73 | + FormatInformation.BITS_SET_IN_HALF_BYTE[(this.URShift(a, 8) & 0x0F)] 74 | + FormatInformation.BITS_SET_IN_HALF_BYTE[(this.URShift(a, 12) & 0x0F)] 75 | + FormatInformation.BITS_SET_IN_HALF_BYTE[(this.URShift(a, 16) & 0x0F)] 76 | + FormatInformation.BITS_SET_IN_HALF_BYTE[(this.URShift(a, 20) & 0x0F)] 77 | + FormatInformation.BITS_SET_IN_HALF_BYTE[(this.URShift(a, 24) & 0x0F)] 78 | + FormatInformation.BITS_SET_IN_HALF_BYTE[(this.URShift(a, 28) & 0x0F)]; 79 | } 80 | 81 | static decodeFormatInformation (maskedFormatInfo: any) { 82 | var formatInfo = this.doDecodeFormatInformation(maskedFormatInfo); 83 | if (formatInfo != null) { 84 | return formatInfo; 85 | } 86 | // Should return null, but, some QR codes apparently 87 | // do not mask this info. Try again by actually masking the pattern 88 | // first 89 | return this.doDecodeFormatInformation(maskedFormatInfo ^ FormatInformation.FORMAT_INFO_MASK_QR); 90 | } 91 | 92 | static doDecodeFormatInformation (maskedFormatInfo: any) { 93 | // Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing 94 | var bestDifference = 0xffffffff; 95 | var bestFormatInfo = 0; 96 | for (var i = 0; i < FormatInformation.FORMAT_INFO_DECODE_LOOKUP.length; i++) { 97 | var decodeInfo = FormatInformation.FORMAT_INFO_DECODE_LOOKUP[i]; 98 | var targetInfo = decodeInfo[0]; 99 | if (targetInfo == maskedFormatInfo) { 100 | // Found an exact match 101 | return new FormatInformation(decodeInfo[1]); 102 | } 103 | var bitsDifference = FormatInformation.numBitsDiffering(maskedFormatInfo, targetInfo); 104 | if (bitsDifference < bestDifference) { 105 | bestFormatInfo = decodeInfo[1]; 106 | bestDifference = bitsDifference; 107 | } 108 | } 109 | // Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits 110 | // differing means we found a match 111 | if (bestDifference <= 3) { 112 | return new FormatInformation(bestFormatInfo); 113 | } 114 | return null; 115 | } 116 | 117 | static forBits (bits: any) { 118 | { 119 | if (bits < 0 || bits >= FormatInformation.FOR_BITS.length) { 120 | throw "ArgumentException"; 121 | } 122 | return FormatInformation.FOR_BITS[bits]; 123 | } 124 | } 125 | } 126 | 127 | -------------------------------------------------------------------------------- /src/lib/qr-decoder/rsdecoder.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Ported to JavaScript by Lazar Laszlo 2011 3 | 4 | lazarsoft@gmail.com, www.lazarsoft.info 5 | 6 | */ 7 | 8 | /* 9 | * 10 | * Copyright 2007 ZXing authors 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | 25 | import {GF256Poly, GF256} from "./gf256" 26 | 27 | 28 | export class ReedSolomonDecoder{ 29 | field: any; 30 | 31 | constructor(field: any){ 32 | this.field = field; 33 | } 34 | 35 | 36 | decode(received: any, twoS: any): void 37 | { 38 | var poly = new GF256Poly(this.field, received); 39 | var syndromeCoefficients = new Array(twoS); 40 | for(var i=0;i= b's 77 | if (a.Degree < b.Degree) 78 | { 79 | var temp = a; 80 | a = b; 81 | b = temp; 82 | } 83 | 84 | var rLast = a; 85 | var r = b; 86 | var sLast = this.field.One; 87 | var s = this.field.Zero; 88 | var tLast = this.field.Zero; 89 | var t = this.field.One; 90 | 91 | // Run Euclidean algorithm until r's degree is less than R/2 92 | while (r.Degree >= Math.floor(R / 2)) 93 | { 94 | var rLastLast = rLast; 95 | var sLastLast = sLast; 96 | var tLastLast = tLast; 97 | rLast = r; 98 | sLast = s; 99 | tLast = t; 100 | 101 | // Divide rLastLast by rLast, with quotient in q and remainder in r 102 | if (rLast.Zero) 103 | { 104 | // Oops, Euclidean algorithm already terminated? 105 | throw "r_{i-1} was zero"; 106 | } 107 | r = rLastLast; 108 | var q = this.field.Zero; 109 | var denominatorLeadingTerm = rLast.getCoefficient(rLast.Degree); 110 | var dltInverse = this.field.inverse(denominatorLeadingTerm); 111 | while (r.Degree >= rLast.Degree && !r.Zero) 112 | { 113 | var degreeDiff = r.Degree - rLast.Degree; 114 | var scale = this.field.multiply(r.getCoefficient(r.Degree), dltInverse); 115 | q = q.addOrSubtract(this.field.buildMonomial(degreeDiff, scale)); 116 | r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale)); 117 | //r.EXE(); 118 | } 119 | 120 | s = q.multiply1(sLast).addOrSubtract(sLastLast); 121 | t = q.multiply1(tLast).addOrSubtract(tLastLast); 122 | } 123 | 124 | var sigmaTildeAtZero = t.getCoefficient(0); 125 | if (sigmaTildeAtZero == 0) 126 | { 127 | throw "ReedSolomonException sigmaTilde(0) was zero"; 128 | } 129 | 130 | var inverse = this.field.inverse(sigmaTildeAtZero); 131 | var sigma = t.multiply2(inverse); 132 | var omega = r.multiply2(inverse); 133 | return new Array(sigma, omega); 134 | } 135 | findErrorLocations( errorLocator:any ): any 136 | { 137 | // This is a direct application of Chien's search 138 | var numErrors = errorLocator.Degree; 139 | if (numErrors == 1) 140 | { 141 | // shortcut 142 | return new Array(errorLocator.getCoefficient(1)); 143 | } 144 | var result = new Array(numErrors); 145 | var e = 0; 146 | for (var i = 1; i < 256 && e < numErrors; i++) 147 | { 148 | if (errorLocator.evaluateAt(i) == 0) 149 | { 150 | result[e] = this.field.inverse(i); 151 | e++; 152 | } 153 | } 154 | if (e != numErrors) 155 | { 156 | throw "Error locator degree does not match number of roots"; 157 | } 158 | return result; 159 | } 160 | findErrorMagnitudes( errorEvaluator:any, errorLocations:any, dataMatrix:any): any 161 | { 162 | // This is directly applying Forney's Formula 163 | var s = errorLocations.length; 164 | var result = new Array(s); 165 | for (var i = 0; i < s; i++) 166 | { 167 | var xiInverse = this.field.inverse(errorLocations[i]); 168 | var denominator = 1; 169 | for (var j = 0; j < s; j++) 170 | { 171 | if (i != j) 172 | { 173 | denominator = this.field.multiply(denominator, GF256.addOrSubtract(1, this.field.multiply(errorLocations[j], xiInverse))); 174 | } 175 | } 176 | result[i] = this.field.multiply(errorEvaluator.evaluateAt(xiInverse), this.field.inverse(denominator)); 177 | // Thanks to sanfordsquires for this fix: 178 | if (dataMatrix) 179 | { 180 | result[i] = this.field.multiply(result[i], xiInverse); 181 | } 182 | } 183 | return result; 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /src/lib/qr-decoder/bmparser.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Ported to JavaScript by Lazar Laszlo 2011 3 | 4 | lazarsoft@gmail.com, www.lazarsoft.info 5 | 6 | */ 7 | 8 | /* 9 | * 10 | * Copyright 2007 ZXing authors 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | 25 | import {BitMatrix} from "./bitmat"; 26 | import {DataMask} from "./datamask" 27 | import {FormatInformation} from "./formatinf"; 28 | import {Version} from "./version" 29 | 30 | 31 | export class BitMatrixParser{ 32 | bitMatrix: BitMatrix; 33 | parsedVersion: any; 34 | parsedFormatInfo: any; 35 | 36 | constructor(bitmatrix: BitMatrix){ 37 | var dimension = bitmatrix.Dimension; 38 | if (dimension < 21 || (dimension & 0x03) != 1) 39 | { 40 | throw "Error BitMatrixParser"; 41 | } 42 | this.bitMatrix = bitmatrix; 43 | } 44 | 45 | copyBit( i:any, j:any, versionBits:any):any 46 | { 47 | return this.bitMatrix.get_Renamed(i, j)?(versionBits << 1) | 0x1:versionBits << 1; 48 | } 49 | 50 | readFormatInformation():any 51 | { 52 | if (this.parsedFormatInfo != null) 53 | { 54 | return this.parsedFormatInfo; 55 | } 56 | 57 | // Read top-left format info bits 58 | var formatInfoBits = 0; 59 | for (var i = 0; i < 6; i++) 60 | { 61 | formatInfoBits = this.copyBit(i, 8, formatInfoBits); 62 | } 63 | // .. and skip a bit in the timing pattern ... 64 | formatInfoBits = this.copyBit(7, 8, formatInfoBits); 65 | formatInfoBits = this.copyBit(8, 8, formatInfoBits); 66 | formatInfoBits = this.copyBit(8, 7, formatInfoBits); 67 | // .. and skip a bit in the timing pattern ... 68 | for (var j = 5; j >= 0; j--) 69 | { 70 | formatInfoBits = this.copyBit(8, j, formatInfoBits); 71 | } 72 | 73 | this.parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits); 74 | if (this.parsedFormatInfo != null) 75 | { 76 | return this.parsedFormatInfo; 77 | } 78 | 79 | // Hmm, failed. Try the top-right/bottom-left pattern 80 | var dimension = this.bitMatrix.Dimension; 81 | formatInfoBits = 0; 82 | var iMin = dimension - 8; 83 | for (var i = dimension - 1; i >= iMin; i--) 84 | { 85 | formatInfoBits = this.copyBit(i, 8, formatInfoBits); 86 | } 87 | for (var j = dimension - 7; j < dimension; j++) 88 | { 89 | formatInfoBits = this.copyBit(8, j, formatInfoBits); 90 | } 91 | 92 | this.parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits); 93 | if (this.parsedFormatInfo != null) 94 | { 95 | return this.parsedFormatInfo; 96 | } 97 | throw "Error readFormatInformation"; 98 | } 99 | readVersion():any 100 | { 101 | 102 | if (this.parsedVersion != null) 103 | { 104 | return this.parsedVersion; 105 | } 106 | 107 | var dimension = this.bitMatrix.Dimension; 108 | 109 | var provisionalVersion = (dimension - 17) >> 2; 110 | if (provisionalVersion <= 6) 111 | { 112 | return Version.getVersionForNumber(provisionalVersion); 113 | } 114 | 115 | // Read top-right version info: 3 wide by 6 tall 116 | var versionBits = 0; 117 | var ijMin = dimension - 11; 118 | for (var j = 5; j >= 0; j--) 119 | { 120 | for (var i = dimension - 9; i >= ijMin; i--) 121 | { 122 | versionBits = this.copyBit(i, j, versionBits); 123 | } 124 | } 125 | 126 | this.parsedVersion = Version.decodeVersionInformation(versionBits); 127 | if (this.parsedVersion != null && this.parsedVersion.DimensionForVersion == dimension) 128 | { 129 | return this.parsedVersion; 130 | } 131 | 132 | // Hmm, failed. Try bottom left: 6 wide by 3 tall 133 | versionBits = 0; 134 | for (var i = 5; i >= 0; i--) 135 | { 136 | for (var j = dimension - 9; j >= ijMin; j--) 137 | { 138 | versionBits = this.copyBit(i, j, versionBits); 139 | } 140 | } 141 | 142 | this.parsedVersion = Version.decodeVersionInformation(versionBits); 143 | if (this.parsedVersion != null && this.parsedVersion.DimensionForVersion == dimension) 144 | { 145 | return this.parsedVersion; 146 | } 147 | throw "Error readVersion"; 148 | } 149 | readCodewords():any 150 | { 151 | 152 | var formatInfo = this.readFormatInformation(); 153 | var version = this.readVersion(); 154 | 155 | // Get the data mask for the format used in this QR Code. This will exclude 156 | // some bits from reading as we wind through the bit matrix. 157 | var dataMask = DataMask.forReference( formatInfo.DataMask); 158 | var dimension = this.bitMatrix.Dimension; 159 | dataMask.unmaskBitMatrix(this.bitMatrix, dimension); 160 | 161 | var functionPattern = version.buildFunctionPattern(); 162 | 163 | var readingUp = true; 164 | var result = new Array(version.TotalCodewords); 165 | var resultOffset = 0; 166 | var currentByte = 0; 167 | var bitsRead = 0; 168 | // Read columns in pairs, from right to left 169 | for (var j = dimension - 1; j > 0; j -= 2) 170 | { 171 | if (j == 6) 172 | { 173 | // Skip whole column with vertical alignment pattern; 174 | // saves time and makes the other code proceed more cleanly 175 | j--; 176 | } 177 | // Read alternatingly from bottom to top then top to bottom 178 | for (var count = 0; count < dimension; count++) 179 | { 180 | var i = readingUp?dimension - 1 - count:count; 181 | for (var col = 0; col < 2; col++) 182 | { 183 | // Ignore bits covered by the function pattern 184 | if (!functionPattern.get_Renamed(j - col, i)) 185 | { 186 | // Read a bit 187 | bitsRead++; 188 | currentByte <<= 1; 189 | if (this.bitMatrix.get_Renamed(j - col, i)) 190 | { 191 | currentByte |= 1; 192 | } 193 | // If we've made a whole byte, save it off 194 | if (bitsRead == 8) 195 | { 196 | result[resultOffset++] = currentByte; 197 | bitsRead = 0; 198 | currentByte = 0; 199 | } 200 | } 201 | } 202 | } 203 | readingUp = !readingUp; // readingUp = !readingUp; // switch directions 204 | } 205 | if (resultOffset != version.TotalCodewords) 206 | { 207 | throw "Error readCodewords"; 208 | } 209 | return result; 210 | } 211 | } 212 | -------------------------------------------------------------------------------- /src/qr-scanner.component.ts: -------------------------------------------------------------------------------- 1 | import { 2 | AfterViewInit, 3 | Component, ElementRef, EventEmitter, Input, OnDestroy, OnInit, Output, 4 | ViewChild, Renderer2 5 | } from '@angular/core'; 6 | import {Subject, Subscription} from 'rxjs'; 7 | import {QRCode} from './lib/qr-decoder/qrcode'; 8 | 9 | @Component({ 10 | selector: 'qr-scanner', 11 | styles: [ 12 | ':host video {height: auto; width: 100%;}', 13 | ':host .mirrored { transform: rotateY(180deg); -webkit-transform:rotateY(180deg); -moz-transform:rotateY(180deg); }', 14 | ':host {}' 15 | ], 16 | template: ` 17 | 18 | 19 | 20 |
21 |
22 | 23 |

24 | You are using an outdated browser. 25 | Please upgrade your browser to improve your experience. 26 |

27 |
28 |
` 29 | }) 30 | export class QrScannerComponent implements OnInit, OnDestroy, AfterViewInit { 31 | 32 | @Input() canvasWidth = 640; 33 | @Input() canvasHeight = 480; 34 | @Input() debug = false; 35 | @Input() stopAfterScan = true; 36 | @Input() updateTime = 500; 37 | 38 | @Output() capturedQr: EventEmitter = new EventEmitter(); 39 | @Output() foundCameras: EventEmitter = new EventEmitter(); 40 | 41 | @ViewChild('videoWrapper') videoWrapper: ElementRef; 42 | @ViewChild('qrCanvas') qrCanvas: ElementRef; 43 | 44 | @Input() chooseCamera: Subject = new Subject(); 45 | 46 | private chooseCamera$: Subscription; 47 | 48 | public gCtx: CanvasRenderingContext2D; 49 | public videoElement: HTMLVideoElement; 50 | public qrCode: QRCode; 51 | public stream: MediaStream; 52 | public captureTimeout: any; 53 | private canvasHidden = true; 54 | get isCanvasSupported(): boolean { 55 | const canvas = this.renderer.createElement('canvas'); 56 | return !!(canvas.getContext && canvas.getContext('2d')); 57 | } 58 | 59 | constructor(private renderer: Renderer2) { 60 | } 61 | 62 | ngOnInit() { 63 | } 64 | 65 | ngOnDestroy() { 66 | this.chooseCamera$.unsubscribe(); 67 | this.stopScanning(); 68 | } 69 | 70 | ngAfterViewInit() { 71 | if (this.debug) console.log('[QrScanner] ViewInit, isSupported: ', this.isCanvasSupported); 72 | if (this.isCanvasSupported) { 73 | this.gCtx = this.qrCanvas.nativeElement.getContext('2d'); 74 | this.gCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight); 75 | this.qrCode = new QRCode(); 76 | if (this.debug) this.qrCode.debug = true; 77 | this.qrCode.myCallback = (decoded: string) => this.QrDecodeCallback(decoded); 78 | } 79 | this.chooseCamera$ = this.chooseCamera.subscribe((camera: MediaDeviceInfo) => this.useDevice(camera)); 80 | this.getMediaDevices().then(devices => this.foundCameras.next(devices)); 81 | } 82 | 83 | startScanning(device: MediaDeviceInfo) { 84 | this.useDevice(device); 85 | } 86 | 87 | stopScanning() { 88 | 89 | if (this.captureTimeout) { 90 | clearTimeout(this.captureTimeout); 91 | this.captureTimeout = 0; 92 | } 93 | this.canvasHidden = false; 94 | 95 | const stream = this.stream && this.stream.getTracks().length && this.stream; 96 | if (stream) { 97 | stream.getTracks().forEach(track => track.enabled && track.stop()) 98 | this.stream = null; 99 | } 100 | } 101 | 102 | getMediaDevices(): Promise { 103 | if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) return Promise.resolve([]); 104 | return navigator.mediaDevices.enumerateDevices() 105 | .then((devices: MediaDeviceInfo[]) => devices) 106 | .catch((error: any): any[] => { 107 | if (this.debug) console.warn('Error', error); 108 | return []; 109 | }); 110 | } 111 | 112 | public QrDecodeCallback(decoded: string) { 113 | if (this.stopAfterScan) { 114 | this.stopScanning(); 115 | this.capturedQr.next(decoded); 116 | } else { 117 | this.capturedQr.next(decoded); 118 | this.captureTimeout = setTimeout(() => this.captureToCanvas(), this.updateTime); 119 | } 120 | 121 | 122 | } 123 | 124 | private captureToCanvas() { 125 | try { 126 | this.gCtx.drawImage(this.videoElement, 0, 0, this.canvasWidth, this.canvasHeight); 127 | this.qrCode.decode(this.qrCanvas.nativeElement); 128 | } catch (e) { 129 | if (this.debug) console.log('[QrScanner] Thrown', e); 130 | if (!this.stream) return; 131 | this.captureTimeout = setTimeout(() => this.captureToCanvas(), this.updateTime); 132 | } 133 | } 134 | 135 | private setStream(stream: any) { 136 | this.canvasHidden = true; 137 | this.gCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight); 138 | this.stream = stream; 139 | this.videoElement.srcObject = stream; 140 | this.captureTimeout = setTimeout(() => this.captureToCanvas(), this.updateTime); 141 | } 142 | 143 | private useDevice(_device: MediaDeviceInfo) { 144 | const _navigator: any = navigator; 145 | 146 | if (this.captureTimeout) { 147 | this.stopScanning(); 148 | } 149 | 150 | if (!this.videoElement) { 151 | this.videoElement = this.renderer.createElement('video'); 152 | this.videoElement.setAttribute('autoplay', 'true'); 153 | this.videoElement.setAttribute('muted', 'true'); 154 | this.renderer.appendChild(this.videoWrapper.nativeElement, this.videoElement); 155 | } 156 | const self = this; 157 | 158 | let constraints: MediaStreamConstraints; 159 | if (_device) { 160 | constraints = {audio: false, video: {deviceId: _device.deviceId}}; 161 | } else { 162 | 163 | constraints = {audio: false, video: true}; 164 | } 165 | _navigator.mediaDevices.getUserMedia(constraints).then(function (stream) { 166 | self.setStream(stream); 167 | }).catch(function (err) { 168 | return self.debug && console.warn('Error', err); 169 | }); 170 | } 171 | 172 | } 173 | -------------------------------------------------------------------------------- /src/lib/qr-decoder/qrcode.ts: -------------------------------------------------------------------------------- 1 | import {Detector} from "./detector" 2 | import {Decoder} from "./decoder" 3 | /* 4 | Copyright 2011 Lazar Laszlo (lazarsoft@gmail.com, www.lazarsoft.info) 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); 7 | you may not use this file except in compliance with the License. 8 | You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software 13 | distributed under the License is distributed on an "AS IS" BASIS, 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | See the License for the specific language governing permissions and 16 | limitations under the License. 17 | */ 18 | 19 | export class QRCode { 20 | imagedata: ImageData; 21 | width: number; 22 | height: number; 23 | debug: boolean = false; 24 | maxImgSize: number = 1024*1024; 25 | sizeOfDataLengthInfo = [ [ 10, 9, 8, 8 ], [ 12, 11, 16, 10 ], [ 14, 13, 16, 12 ] ]; 26 | result: string; 27 | 28 | public myCallback: (qrText: string) => void; 29 | 30 | public decode(canvas: HTMLCanvasElement): string { 31 | 32 | let context = canvas.getContext('2d'); 33 | this.width = canvas.width; 34 | this.height = canvas.height; 35 | this.imagedata = context.getImageData(0, 0, this.width, this.height); 36 | this.result = this.process(context); 37 | if(this.myCallback!=null) 38 | this.myCallback(this.result); 39 | return this.result; 40 | } 41 | 42 | process(context: CanvasRenderingContext2D): string { 43 | var start = new Date().getTime(); 44 | var image = this.grayScaleToBitmap(this.grayscale()); 45 | 46 | if(this.debug) 47 | { 48 | for (var y = 0; y < this.height; y++) 49 | { 50 | for (var x = 0; x < this.width; x++) 51 | { 52 | var point = (x * 4) + (y * this.width * 4); 53 | this.imagedata.data[point] = image[x+y*this.width]?0:0; 54 | this.imagedata.data[point+1] = image[x+y*this.width]?0:0; 55 | this.imagedata.data[point+2] = image[x+y*this.width]?255:0; 56 | } 57 | } 58 | context.putImageData(this.imagedata, 0, 0); 59 | } 60 | 61 | var detector = new Detector(image,this.imagedata, this.width, this.height); 62 | 63 | var qRCodeMatrix = detector.detect(); 64 | if(this.debug) 65 | context.putImageData(this.imagedata, 0, 0); 66 | var decoder = new Decoder(); 67 | var reader = decoder.decode(qRCodeMatrix.bits); 68 | var data = reader.DataByte; 69 | var str=""; 70 | for(var i=0;i): Array 84 | { 85 | var middle = this.getMiddleBrightnessPerArea(grayScale); 86 | var sqrtNumArea = middle.length; 87 | var areaWidth = Math.floor(this.width / sqrtNumArea); 88 | var areaHeight = Math.floor(this.height / sqrtNumArea); 89 | var bitmap = new Array(this.height*this.width); 90 | 91 | for (var ay = 0; ay < sqrtNumArea; ay++) 92 | { 93 | for (var ax = 0; ax < sqrtNumArea; ax++) 94 | { 95 | for (var dy = 0; dy < areaHeight; dy++) 96 | { 97 | for (var dx = 0; dx < areaWidth; dx++) 98 | { 99 | bitmap[areaWidth * ax + dx+ (areaHeight * ay + dy)*this.width] = (grayScale[areaWidth * ax + dx+ (areaHeight * ay + dy)*this.width] < middle[ax][ay])?true:false; 100 | } 101 | } 102 | } 103 | } 104 | return bitmap; 105 | } 106 | 107 | grayscale(): Array{ 108 | var ret = new Array(this.width*this.height); 109 | for (var y = 0; y < this.height; y++) 110 | { 111 | for (var x = 0; x < this.width; x++) 112 | { 113 | var gray = this.getPixel(x, y); 114 | 115 | ret[x+y*this.width] = gray; 116 | } 117 | } 118 | return ret; 119 | } 120 | 121 | getPixel(x:number,y:number): number{ 122 | if (this.width < x) { 123 | throw "point error"; 124 | } 125 | if (this.height < y) { 126 | throw "point error"; 127 | } 128 | let point = (x * 4) + (y * this.width * 4); 129 | let p = (this.imagedata.data[point]*33 + this.imagedata.data[point + 1]*34 + this.imagedata.data[point + 2]*33)/100; 130 | return p; 131 | } 132 | 133 | getMiddleBrightnessPerArea(image: Array): Array> 134 | { 135 | var numSqrtArea = 4; 136 | //obtain middle brightness((min + max) / 2) per area 137 | var areaWidth = Math.floor(this.width / numSqrtArea); 138 | var areaHeight = Math.floor(this.height / numSqrtArea); 139 | var minmax = new Array(numSqrtArea); 140 | for (var i = 0; i < numSqrtArea; i++) 141 | { 142 | minmax[i] = new Array(numSqrtArea); 143 | for (var i2 = 0; i2 < numSqrtArea; i2++) 144 | { 145 | minmax[i][i2] = new Array(0,0); 146 | } 147 | } 148 | for (var ay = 0; ay < numSqrtArea; ay++) 149 | { 150 | for (var ax = 0; ax < numSqrtArea; ax++) 151 | { 152 | minmax[ax][ay][0] = 0xFF; 153 | for (var dy = 0; dy < areaHeight; dy++) 154 | { 155 | for (var dx = 0; dx < areaWidth; dx++) 156 | { 157 | var target = image[areaWidth * ax + dx+(areaHeight * ay + dy)*this.width]; 158 | if (target < minmax[ax][ay][0]) 159 | minmax[ax][ay][0] = target; 160 | if (target > minmax[ax][ay][1]) 161 | minmax[ax][ay][1] = target; 162 | } 163 | } 164 | //minmax[ax][ay][0] = (minmax[ax][ay][0] + minmax[ax][ay][1]) / 2; 165 | } 166 | } 167 | var middle = new Array(numSqrtArea); 168 | for (var i3 = 0; i3 < numSqrtArea; i3++) 169 | { 170 | middle[i3] = new Array(numSqrtArea); 171 | } 172 | for (var ay = 0; ay < numSqrtArea; ay++) 173 | { 174 | for (var ax = 0; ax < numSqrtArea; ax++) 175 | { 176 | middle[ax][ay] = Math.floor((minmax[ax][ay][0] + minmax[ax][ay][1]) / 2); 177 | //Console.out.print(middle[ax][ay] + ","); 178 | } 179 | //Console.out.println(""); 180 | } 181 | //Console.out.println(""); 182 | 183 | return middle; 184 | } 185 | } 186 | 187 | 188 | 189 | 190 | 191 | 192 | // 193 | // 194 | // Array.prototype.remove = function(from, to) { 195 | // var rest = this.slice((to || from) + 1 || this.length); 196 | // this.length = from < 0 ? this.length + from : from; 197 | // return this.push.apply(this, rest); 198 | // }; 199 | -------------------------------------------------------------------------------- /src/lib/qr-decoder/alignpat.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Ported to JavaScript by Lazar Laszlo 2011 3 | 4 | lazarsoft@gmail.com, www.lazarsoft.info 5 | 6 | */ 7 | 8 | /* 9 | * 10 | * Copyright 2007 ZXing authors 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | 25 | export class AlignmentPattern{ 26 | x:any; 27 | y: any; 28 | count = 1; 29 | estimatedModuleSize: any 30 | constructor(posX: any, posY: any, estimatedModuleSize: any){ 31 | this.x=posX; 32 | this.y=posY; 33 | this.estimatedModuleSize = estimatedModuleSize; 34 | } 35 | 36 | get EstimatedModuleSize() 37 | { 38 | return this.estimatedModuleSize; 39 | }; 40 | 41 | get Count() 42 | { 43 | return this.count; 44 | }; 45 | get X() 46 | { 47 | return Math.floor(this.x); 48 | }; 49 | get Y() 50 | { 51 | return Math.floor(this.y); 52 | }; 53 | 54 | 55 | incrementCount = function() 56 | { 57 | this.count++; 58 | } 59 | aboutEquals=function( moduleSize: any, i: any, j: any) 60 | { 61 | if (Math.abs(i - this.y) <= moduleSize && Math.abs(j - this.x) <= moduleSize) 62 | { 63 | var moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize); 64 | return moduleSizeDiff <= 1.0 || moduleSizeDiff / this.estimatedModuleSize <= 1.0; 65 | } 66 | return false; 67 | } 68 | 69 | } 70 | 71 | 72 | export class AlignmentPatternFinder{ 73 | image:any; 74 | possibleCenters = new Array(); 75 | startX:any; 76 | startY:any; 77 | width:any; 78 | height:any; 79 | moduleSize:any; 80 | crossCheckStateCount = new Array(0,0,0); 81 | resultPointCallback:any; 82 | imageWidth:number; 83 | imageHeight: number; 84 | 85 | constructor( image: any, startX: any, startY: any, width: any, height: any, moduleSize: any, imageWidth:number, imageHeight: number, resultPointCallback: any){ 86 | this.image = image; 87 | 88 | this.startX = startX; 89 | this.startY = startY; 90 | this.width = width; 91 | this.height = height; 92 | this.moduleSize = moduleSize; 93 | this.resultPointCallback = resultPointCallback; 94 | this.imageWidth = imageWidth; 95 | this.imageHeight = imageHeight; 96 | 97 | } 98 | 99 | centerFromEnd=function(stateCount:any, end:any) 100 | { 101 | return (end - stateCount[2]) - stateCount[1] / 2.0; 102 | } 103 | foundPatternCross = function(stateCount:any) 104 | { 105 | var moduleSize = this.moduleSize; 106 | var maxVariance = moduleSize / 2.0; 107 | for (var i = 0; i < 3; i++) 108 | { 109 | if (Math.abs(moduleSize - stateCount[i]) >= maxVariance) 110 | { 111 | return false; 112 | } 113 | } 114 | return true; 115 | } 116 | 117 | crossCheckVertical=function( startI:any, centerJ:any, maxCount:any, originalStateCountTotal:any) 118 | { 119 | var image = this.image; 120 | 121 | var maxI = this.imageHeight; 122 | var stateCount = this.crossCheckStateCount; 123 | stateCount[0] = 0; 124 | stateCount[1] = 0; 125 | stateCount[2] = 0; 126 | 127 | // Start counting up from center 128 | var i = startI; 129 | while (i >= 0 && image[centerJ + i*this.imageWidth] && stateCount[1] <= maxCount) 130 | { 131 | stateCount[1]++; 132 | i--; 133 | } 134 | // If already too many modules in this state or ran off the edge: 135 | if (i < 0 || stateCount[1] > maxCount) 136 | { 137 | return NaN; 138 | } 139 | while (i >= 0 && !image[centerJ + i*this.imageWidth] && stateCount[0] <= maxCount) 140 | { 141 | stateCount[0]++; 142 | i--; 143 | } 144 | if (stateCount[0] > maxCount) 145 | { 146 | return NaN; 147 | } 148 | 149 | // Now also count down from center 150 | i = startI + 1; 151 | while (i < maxI && image[centerJ + i*this.imageWidth] && stateCount[1] <= maxCount) 152 | { 153 | stateCount[1]++; 154 | i++; 155 | } 156 | if (i == maxI || stateCount[1] > maxCount) 157 | { 158 | return NaN; 159 | } 160 | while (i < maxI && !image[centerJ + i*this.imageWidth] && stateCount[2] <= maxCount) 161 | { 162 | stateCount[2]++; 163 | i++; 164 | } 165 | if (stateCount[2] > maxCount) 166 | { 167 | return NaN; 168 | } 169 | 170 | var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; 171 | if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) 172 | { 173 | return NaN; 174 | } 175 | 176 | return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, i):NaN; 177 | } 178 | 179 | handlePossibleCenter=function( stateCount:any, i:any, j:any) 180 | { 181 | var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; 182 | var centerJ = this.centerFromEnd(stateCount, j); 183 | var centerI = this.crossCheckVertical(i, Math.floor (centerJ), 2 * stateCount[1], stateCountTotal); 184 | if (!isNaN(centerI)) 185 | { 186 | var estimatedModuleSize = (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0; 187 | var max = this.possibleCenters.length; 188 | for (var index = 0; index < max; index++) 189 | { 190 | var center = this.possibleCenters[index]; 191 | // Look for about the same center and module size: 192 | if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) 193 | { 194 | return new AlignmentPattern(centerJ, centerI, estimatedModuleSize); 195 | } 196 | } 197 | // Hadn't found this before; save it 198 | var point = new AlignmentPattern(centerJ, centerI, estimatedModuleSize); 199 | this.possibleCenters.push(point); 200 | if (this.resultPointCallback != null) 201 | { 202 | this.resultPointCallback.foundPossibleResultPoint(point); 203 | } 204 | } 205 | return null; 206 | } 207 | 208 | find = function() 209 | { 210 | var startX = this.startX; 211 | var height = this.height; 212 | var maxJ = startX + this.width; 213 | var middleI = this.startY + (height >> 1); 214 | // We are looking for black/white/black modules in 1:1:1 ratio; 215 | // this tracks the number of black/white/black modules seen so far 216 | var stateCount = new Array(0,0,0); 217 | for (var iGen = 0; iGen < height; iGen++) 218 | { 219 | // Search from middle outwards 220 | var i = middleI + ((iGen & 0x01) == 0?((iGen + 1) >> 1):- ((iGen + 1) >> 1)); 221 | stateCount[0] = 0; 222 | stateCount[1] = 0; 223 | stateCount[2] = 0; 224 | var j = startX; 225 | // Burn off leading white pixels before anything else; if we start in the middle of 226 | // a white run, it doesn't make sense to count its length, since we don't know if the 227 | // white run continued to the left of the start point 228 | while (j < maxJ && !this.image[j + this.imageWidth* i]) 229 | { 230 | j++; 231 | } 232 | var currentState = 0; 233 | while (j < maxJ) 234 | { 235 | if (this.image[j + i*this.imageWidth]) 236 | { 237 | // Black pixel 238 | if (currentState == 1) 239 | { 240 | // Counting black pixels 241 | stateCount[currentState]++; 242 | } 243 | else 244 | { 245 | // Counting white pixels 246 | if (currentState == 2) 247 | { 248 | // A winner? 249 | if (this.foundPatternCross(stateCount)) 250 | { 251 | // Yes 252 | var confirmed = this.handlePossibleCenter(stateCount, i, j); 253 | if (confirmed != null) 254 | { 255 | return confirmed; 256 | } 257 | } 258 | stateCount[0] = stateCount[2]; 259 | stateCount[1] = 1; 260 | stateCount[2] = 0; 261 | currentState = 1; 262 | } 263 | else 264 | { 265 | stateCount[++currentState]++; 266 | } 267 | } 268 | } 269 | else 270 | { 271 | // White pixel 272 | if (currentState == 1) 273 | { 274 | // Counting black pixels 275 | currentState++; 276 | } 277 | stateCount[currentState]++; 278 | } 279 | j++; 280 | } 281 | if (this.foundPatternCross(stateCount)) 282 | { 283 | var confirmed = this.handlePossibleCenter(stateCount, i, maxJ); 284 | if (confirmed != null) 285 | { 286 | return confirmed; 287 | } 288 | } 289 | } 290 | 291 | // Hmm, nothing we saw was observed and confirmed twice. If we had 292 | // any guess at all, return it. 293 | if (!(this.possibleCenters.length == 0)) 294 | { 295 | return this.possibleCenters[0]; 296 | } 297 | 298 | throw `Couldn't find enough alignment patterns`; 299 | } 300 | } 301 | -------------------------------------------------------------------------------- /src/lib/qr-decoder/gf256.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Ported to JavaScript by Lazar Laszlo 2011 3 | 4 | lazarsoft@gmail.com, www.lazarsoft.info 5 | 6 | */ 7 | 8 | /* 9 | * 10 | * Copyright 2007 ZXing authors 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | 25 | export class GF256Poly{ 26 | 27 | field: any; 28 | coefficients: any; 29 | constructor(field: any, coefficients: any){ 30 | if (coefficients == null || coefficients.length == 0) 31 | { 32 | throw "System.ArgumentException"; 33 | } 34 | this.field = field; 35 | var coefficientsLength = coefficients.length; 36 | if (coefficientsLength > 1 && coefficients[0] == 0) 37 | { 38 | // Leading term must be non-zero for anything except the constant polynomial "0" 39 | var firstNonZero = 1; 40 | while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0) 41 | { 42 | firstNonZero++; 43 | } 44 | if (firstNonZero == coefficientsLength) 45 | { 46 | this.coefficients = field.Zero.coefficients; 47 | } 48 | else 49 | { 50 | this.coefficients = new Array(coefficientsLength - firstNonZero); 51 | for(var i=0;i largerCoefficients.length) 125 | { 126 | var temp = smallerCoefficients; 127 | smallerCoefficients = largerCoefficients; 128 | largerCoefficients = temp; 129 | } 130 | var sumDiff = new Array(largerCoefficients.length); 131 | var lengthDiff = largerCoefficients.length - smallerCoefficients.length; 132 | // Copy high-order terms only found in higher-degree polynomial's coefficients 133 | //Array.Copy(largerCoefficients, 0, sumDiff, 0, lengthDiff); 134 | for(var ci=0;ci= other.Degree && !remainder.Zero) 223 | { 224 | var degreeDifference = remainder.Degree - other.Degree; 225 | var scale = this.field.multiply(remainder.getCoefficient(remainder.Degree), inverseDenominatorLeadingTerm); 226 | var term = other.multiplyByMonomial(degreeDifference, scale); 227 | var iterationQuotient = this.field.buildMonomial(degreeDifference, scale); 228 | quotient = quotient.addOrSubtract(iterationQuotient); 229 | remainder = remainder.addOrSubtract(term); 230 | } 231 | 232 | return new Array(quotient, remainder); 233 | } 234 | 235 | 236 | } 237 | 238 | 239 | 240 | export class GF256{ 241 | 242 | expTable = new Array(256); 243 | logTable = new Array(256); 244 | zero : any; 245 | one: any 246 | constructor(primitive: any){ 247 | var x = 1; 248 | for (var i = 0; i < 256; i++) 249 | { 250 | this.expTable[i] = x; 251 | x <<= 1; // x = x * 2; we're assuming the generator alpha is 2 252 | if (x >= 0x100) 253 | { 254 | x ^= primitive; 255 | } 256 | } 257 | for (var i = 0; i < 255; i++) 258 | { 259 | this.logTable[this.expTable[i]] = i; 260 | } 261 | // logTable[0] == 0 but this should never be used 262 | var at0=new Array(1);at0[0]=0; 263 | this.zero = new GF256Poly(this, new Array(at0)); 264 | var at1=new Array(1);at1[0]=1; 265 | this.one = new GF256Poly(this, new Array(at1)); 266 | } 267 | 268 | 269 | 270 | get Zero(): any 271 | { 272 | return this.zero; 273 | }; 274 | get One(): any 275 | { 276 | return this.one; 277 | }; 278 | buildMonomial( degree: any, coefficient: any): any 279 | { 280 | if (degree < 0) 281 | { 282 | throw "System.ArgumentException"; 283 | } 284 | if (coefficient == 0) 285 | { 286 | return this.zero; 287 | } 288 | var coefficients = new Array(degree + 1); 289 | for(var i=0;i= 10 && version <= 26) 38 | this.dataLengthMode = 1; 39 | else if (version >= 27 && version <= 40) 40 | this.dataLengthMode = 2; 41 | } 42 | 43 | getNextBits( numBits: any): any 44 | { 45 | var bits = 0; 46 | if (numBits < this.bitPointer + 1) 47 | { 48 | // next word fits into current data block 49 | var mask = 0; 50 | for (var i = 0; i < numBits; i++) 51 | { 52 | mask += (1 << i); 53 | } 54 | mask <<= (this.bitPointer - numBits + 1); 55 | 56 | bits = (this.blocks[this.blockPointer] & mask) >> (this.bitPointer - numBits + 1); 57 | this.bitPointer -= numBits; 58 | return bits; 59 | } 60 | else if (numBits < this.bitPointer + 1 + 8) 61 | { 62 | // next word crosses 2 data blocks 63 | var mask1 = 0; 64 | for (var i = 0; i < this.bitPointer + 1; i++) 65 | { 66 | mask1 += (1 << i); 67 | } 68 | bits = (this.blocks[this.blockPointer] & mask1) << (numBits - (this.bitPointer + 1)); 69 | this.blockPointer++; 70 | bits += ((this.blocks[this.blockPointer]) >> (8 - (numBits - (this.bitPointer + 1)))); 71 | 72 | this.bitPointer = this.bitPointer - numBits % 8; 73 | if (this.bitPointer < 0) 74 | { 75 | this.bitPointer = 8 + this.bitPointer; 76 | } 77 | return bits; 78 | } 79 | else if (numBits < this.bitPointer + 1 + 16) 80 | { 81 | // next word crosses 3 data blocks 82 | var mask1 = 0; // mask of first block 83 | var mask3 = 0; // mask of 3rd block 84 | //bitPointer + 1 : number of bits of the 1st block 85 | //8 : number of the 2nd block (note that use already 8bits because next word uses 3 data blocks) 86 | //numBits - (bitPointer + 1 + 8) : number of bits of the 3rd block 87 | for (var i = 0; i < this.bitPointer + 1; i++) 88 | { 89 | mask1 += (1 << i); 90 | } 91 | var bitsFirstBlock = (this.blocks[this.blockPointer] & mask1) << (numBits - (this.bitPointer + 1)); 92 | this.blockPointer++; 93 | 94 | var bitsSecondBlock = this.blocks[this.blockPointer] << (numBits - (this.bitPointer + 1 + 8)); 95 | this.blockPointer++; 96 | 97 | for (var i = 0; i < numBits - (this.bitPointer + 1 + 8); i++) 98 | { 99 | mask3 += (1 << i); 100 | } 101 | mask3 <<= 8 - (numBits - (this.bitPointer + 1 + 8)); 102 | var bitsThirdBlock = (this.blocks[this.blockPointer] & mask3) >> (8 - (numBits - (this.bitPointer + 1 + 8))); 103 | 104 | bits = bitsFirstBlock + bitsSecondBlock + bitsThirdBlock; 105 | this.bitPointer = this.bitPointer - (numBits - 8) % 8; 106 | if (this.bitPointer < 0) 107 | { 108 | this.bitPointer = 8 + this.bitPointer; 109 | } 110 | return bits; 111 | } 112 | else 113 | { 114 | return 0; 115 | } 116 | } 117 | NextMode():any 118 | { 119 | if ((this.blockPointer > this.blocks.length - this.numErrorCorrectionCode - 2)) 120 | return 0; 121 | else 122 | return this.getNextBits(4); 123 | } 124 | getDataLength( modeIndicator: any):any 125 | { 126 | var index = 0; 127 | while (true) 128 | { 129 | if ((modeIndicator >> index) == 1) 130 | break; 131 | index++; 132 | } 133 | 134 | return this.getNextBits(QRCodeDataBlockReader.sizeOfDataLengthInfo[this.dataLengthMode][index]); 135 | } 136 | getRomanAndFigureString( dataLength:any ):any 137 | { 138 | var length = dataLength; 139 | var intData = 0; 140 | var strData = ""; 141 | var tableRomanAndFigure = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':'); 142 | do 143 | { 144 | if (length > 1) 145 | { 146 | intData = this.getNextBits(11); 147 | var firstLetter = Math.floor(intData / 45); 148 | var secondLetter = intData % 45; 149 | strData += tableRomanAndFigure[firstLetter]; 150 | strData += tableRomanAndFigure[secondLetter]; 151 | length -= 2; 152 | } 153 | else if (length == 1) 154 | { 155 | intData = this.getNextBits(6); 156 | strData += tableRomanAndFigure[intData]; 157 | length -= 1; 158 | } 159 | } 160 | while (length > 0); 161 | 162 | return strData; 163 | } 164 | getFigureString( dataLength:any):any 165 | { 166 | var length = dataLength; 167 | var intData = 0; 168 | var strData = ""; 169 | do 170 | { 171 | if (length >= 3) 172 | { 173 | intData = this.getNextBits(10); 174 | if (intData < 100) 175 | strData += "0"; 176 | if (intData < 10) 177 | strData += "0"; 178 | length -= 3; 179 | } 180 | else if (length == 2) 181 | { 182 | intData = this.getNextBits(7); 183 | if (intData < 10) 184 | strData += "0"; 185 | length -= 2; 186 | } 187 | else if (length == 1) 188 | { 189 | intData = this.getNextBits(4); 190 | length -= 1; 191 | } 192 | strData += intData; 193 | } 194 | while (length > 0); 195 | 196 | return strData; 197 | } 198 | get8bitByteArray( dataLength:any):any 199 | { 200 | var length = dataLength; 201 | var intData = 0; 202 | var output = new Array(); 203 | 204 | do 205 | { 206 | intData = this.getNextBits(8); 207 | output.push( intData); 208 | length--; 209 | } 210 | while (length > 0); 211 | return output; 212 | } 213 | getKanjiString( dataLength:any):any 214 | { 215 | var length = dataLength; 216 | var intData = 0; 217 | var unicodeString = ""; 218 | do 219 | { 220 | intData = this.getNextBits(13); 221 | var lowerByte = intData % 0xC0; 222 | var higherByte = intData / 0xC0; 223 | 224 | var tempWord = (higherByte << 8) + lowerByte; 225 | var shiftjisWord = 0; 226 | if (tempWord + 0x8140 <= 0x9FFC) 227 | { 228 | // between 8140 - 9FFC on Shift_JIS character set 229 | shiftjisWord = tempWord + 0x8140; 230 | } 231 | else 232 | { 233 | // between E040 - EBBF on Shift_JIS character set 234 | shiftjisWord = tempWord + 0xC140; 235 | } 236 | 237 | //var tempByte = new Array(0,0); 238 | //tempByte[0] = (sbyte) (shiftjisWord >> 8); 239 | //tempByte[1] = (sbyte) (shiftjisWord & 0xFF); 240 | //unicodeString += new String(SystemUtils.ToCharArray(SystemUtils.ToByteArray(tempByte))); 241 | unicodeString += String.fromCharCode(shiftjisWord); 242 | length--; 243 | } 244 | while (length > 0); 245 | 246 | 247 | return unicodeString; 248 | } 249 | 250 | 251 | get DataByte(): any 252 | { 253 | var output = new Array(); 254 | var MODE_NUMBER = 1; 255 | var MODE_ROMAN_AND_NUMBER = 2; 256 | var MODE_8BIT_BYTE = 4; 257 | var MODE_KANJI = 8; 258 | do 259 | { 260 | var mode = this.NextMode(); 261 | //canvas.println("mode: " + mode); 262 | if (mode == 0) 263 | { 264 | if (output.length > 0) 265 | break; 266 | else 267 | throw "Empty data block"; 268 | } 269 | //if (mode != 1 && mode != 2 && mode != 4 && mode != 8) 270 | // break; 271 | //} 272 | if (mode != MODE_NUMBER && mode != MODE_ROMAN_AND_NUMBER && mode != MODE_8BIT_BYTE && mode != MODE_KANJI) 273 | { 274 | /* canvas.println("Invalid mode: " + mode); 275 | mode = guessMode(mode); 276 | canvas.println("Guessed mode: " + mode); */ 277 | throw "Invalid mode: " + mode + " in (block:" + this.blockPointer + " bit:" + this.bitPointer + ")"; 278 | } 279 | let dataLength = this.getDataLength(mode); 280 | if (dataLength < 1) 281 | throw "Invalid data length: " + dataLength; 282 | //canvas.println("length: " + dataLength); 283 | switch (mode) 284 | { 285 | 286 | case MODE_NUMBER: 287 | //canvas.println("Mode: Figure"); 288 | var temp_str = this.getFigureString(dataLength); 289 | var ta = new Array(temp_str.length); 290 | for(var j=0;j Math.abs(toX - fromX); 61 | if (steep) 62 | { 63 | var temp = fromX; 64 | fromX = fromY; 65 | fromY = temp; 66 | temp = toX; 67 | toX = toY; 68 | toY = temp; 69 | } 70 | 71 | var dx = Math.abs(toX - fromX); 72 | var dy = Math.abs(toY - fromY); 73 | var error = - dx >> 1; 74 | var ystep = fromY < toY?1:- 1; 75 | var xstep = fromX < toX?1:- 1; 76 | var state = 0; // In black pixels, looking for white, first or second time 77 | for (var x = fromX, y = fromY; x != toX; x += xstep) 78 | { 79 | 80 | var realX = steep?y:x; 81 | var realY = steep?x:y; 82 | if (state == 1) 83 | { 84 | // In white pixels, looking for black 85 | if (this.image[realX + realY*this.width]) 86 | { 87 | state++; 88 | } 89 | } 90 | else 91 | { 92 | if (!this.image[realX + realY*this.width]) 93 | { 94 | state++; 95 | } 96 | } 97 | 98 | if (state == 3) 99 | { 100 | // Found black, white, black, and stumbled back onto white; done 101 | var diffX = x - fromX; 102 | var diffY = y - fromY; 103 | return Math.sqrt( (diffX * diffX + diffY * diffY)); 104 | } 105 | error += dy; 106 | if (error > 0) 107 | { 108 | if (y == toY) 109 | { 110 | break; 111 | } 112 | y += ystep; 113 | error -= dx; 114 | } 115 | } 116 | var diffX2 = toX - fromX; 117 | var diffY2 = toY - fromY; 118 | return Math.sqrt( (diffX2 * diffX2 + diffY2 * diffY2)); 119 | } 120 | 121 | sizeOfBlackWhiteBlackRunBothWays( fromX:any, fromY:any, toX:any, toY:any): number 122 | { 123 | 124 | var result = this.sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY); 125 | 126 | // Now count other way -- don't run off image though of course 127 | var scale = 1.0; 128 | var otherToX = fromX - (toX - fromX); 129 | if (otherToX < 0) 130 | { 131 | scale = fromX / (fromX - otherToX); 132 | otherToX = 0; 133 | } 134 | else if (otherToX >= this.width) 135 | { 136 | scale = (this.width - 1 - fromX) / (otherToX - fromX); 137 | otherToX = this.width - 1; 138 | } 139 | var otherToY = Math.floor (fromY - (toY - fromY) * scale); 140 | 141 | scale = 1.0; 142 | if (otherToY < 0) 143 | { 144 | scale = fromY / (fromY - otherToY); 145 | otherToY = 0; 146 | } 147 | else if (otherToY >= this.height) 148 | { 149 | scale = (this.height - 1 - fromY) / (otherToY - fromY); 150 | otherToY = this.height - 1; 151 | } 152 | otherToX = Math.floor (fromX + (otherToX - fromX) * scale); 153 | 154 | result += this.sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY); 155 | return result - 1.0; // -1 because we counted the middle pixel twice 156 | } 157 | calculateModuleSizeOneWay=function( pattern:any, otherPattern:any) 158 | { 159 | var moduleSizeEst1 = this.sizeOfBlackWhiteBlackRunBothWays(Math.floor( pattern.X), Math.floor( pattern.Y), Math.floor( otherPattern.X), Math.floor(otherPattern.Y)); 160 | var moduleSizeEst2 = this.sizeOfBlackWhiteBlackRunBothWays(Math.floor(otherPattern.X), Math.floor(otherPattern.Y), Math.floor( pattern.X), Math.floor(pattern.Y)); 161 | if (isNaN(moduleSizeEst1)) 162 | { 163 | return moduleSizeEst2 / 7.0; 164 | } 165 | if (isNaN(moduleSizeEst2)) 166 | { 167 | return moduleSizeEst1 / 7.0; 168 | } 169 | // Average them, and divide by 7 since we've counted the width of 3 black modules, 170 | // and 1 white and 1 black module on either side. Ergo, divide sum by 14. 171 | return (moduleSizeEst1 + moduleSizeEst2) / 14.0; 172 | } 173 | calculateModuleSize=function( topLeft:any, topRight:any, bottomLeft:any) 174 | { 175 | // Take the average 176 | return (this.calculateModuleSizeOneWay(topLeft, topRight) + this.calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0; 177 | } 178 | distance=function( pattern1:any, pattern2:any) 179 | { 180 | let xDiff = pattern1.X - pattern2.X; 181 | let yDiff = pattern1.Y - pattern2.Y; 182 | return Math.sqrt( (xDiff * xDiff + yDiff * yDiff)); 183 | } 184 | computeDimension=function( topLeft:any, topRight:any, bottomLeft:any, moduleSize:any) 185 | { 186 | 187 | var tltrCentersDimension = Math.round(this.distance(topLeft, topRight) / moduleSize); 188 | var tlblCentersDimension = Math.round(this.distance(topLeft, bottomLeft) / moduleSize); 189 | var dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7; 190 | switch (dimension & 0x03) 191 | { 192 | 193 | // mod 4 194 | case 0: 195 | dimension++; 196 | break; 197 | // 1? do nothing 198 | 199 | case 2: 200 | dimension--; 201 | break; 202 | 203 | case 3: 204 | throw "Error"; 205 | } 206 | return dimension; 207 | } 208 | findAlignmentInRegion=function( overallEstModuleSize:any, estAlignmentX:any, estAlignmentY:any, allowanceFactor:any) 209 | { 210 | // Look for an alignment pattern (3 modules in size) around where it 211 | // should be 212 | var allowance = Math.floor (allowanceFactor * overallEstModuleSize); 213 | var alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance); 214 | var alignmentAreaRightX = Math.min(this.width - 1, estAlignmentX + allowance); 215 | if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) 216 | { 217 | throw "Error"; 218 | } 219 | 220 | var alignmentAreaTopY = Math.max(0, estAlignmentY - allowance); 221 | var alignmentAreaBottomY = Math.min(this.height - 1, estAlignmentY + allowance); 222 | 223 | var alignmentFinder = new AlignmentPatternFinder(this.image, alignmentAreaLeftX, alignmentAreaTopY, alignmentAreaRightX - alignmentAreaLeftX, alignmentAreaBottomY - alignmentAreaTopY, overallEstModuleSize, this.width,this.height, this.resultPointCallback); 224 | return alignmentFinder.find(); 225 | } 226 | 227 | createTransform=function( topLeft:any, topRight:any, bottomLeft:any, alignmentPattern:any, dimension:any) 228 | { 229 | var dimMinusThree = dimension - 3.5; 230 | var bottomRightX:any; 231 | var bottomRightY:any; 232 | var sourceBottomRightX:any; 233 | var sourceBottomRightY:any; 234 | if (alignmentPattern != null) 235 | { 236 | bottomRightX = alignmentPattern.X; 237 | bottomRightY = alignmentPattern.Y; 238 | sourceBottomRightX = sourceBottomRightY = dimMinusThree - 3.0; 239 | } 240 | else 241 | { 242 | // Don't have an alignment pattern, just make up the bottom-right point 243 | bottomRightX = (topRight.X - topLeft.X) + bottomLeft.X; 244 | bottomRightY = (topRight.Y - topLeft.Y) + bottomLeft.Y; 245 | sourceBottomRightX = sourceBottomRightY = dimMinusThree; 246 | } 247 | 248 | var transform = PerspectiveTransform.quadrilateralToQuadrilateral(3.5, 3.5, dimMinusThree, 3.5, sourceBottomRightX, sourceBottomRightY, 3.5, dimMinusThree, topLeft.X, topLeft.Y, topRight.X, topRight.Y, bottomRightX, bottomRightY, bottomLeft.X, bottomLeft.Y); 249 | 250 | return transform; 251 | } 252 | sampleGrid=function( image:any, transform:any, dimension:any) 253 | { 254 | 255 | var sampler = new GridSampler(this.width,this.height); 256 | return sampler.sampleGrid3(image,this.rawImage, dimension, transform); 257 | } 258 | processFinderPatternInfo( info:any):any 259 | { 260 | 261 | var topLeft = info.TopLeft; 262 | var topRight = info.TopRight; 263 | var bottomLeft = info.BottomLeft; 264 | 265 | var moduleSize = this.calculateModuleSize(topLeft, topRight, bottomLeft); 266 | if (moduleSize < 1.0) 267 | { 268 | throw "Error"; 269 | } 270 | var dimension = this.computeDimension(topLeft, topRight, bottomLeft, moduleSize); 271 | var provisionalVersion = Version.getProvisionalVersionForDimension(dimension); 272 | var modulesBetweenFPCenters = provisionalVersion.DimensionForVersion - 7; 273 | 274 | var alignmentPattern: any = null; 275 | // Anything above version 1 has an alignment pattern 276 | if (provisionalVersion.AlignmentPatternCenters.length > 0) 277 | { 278 | 279 | // Guess where a "bottom right" finder pattern would have been 280 | var bottomRightX = topRight.X - topLeft.X + bottomLeft.X; 281 | var bottomRightY = topRight.Y - topLeft.Y + bottomLeft.Y; 282 | 283 | // Estimate that alignment pattern is closer by 3 modules 284 | // from "bottom right" to known top left location 285 | var correctionToTopLeft = 1.0 - 3.0 / modulesBetweenFPCenters; 286 | var estAlignmentX = Math.floor (topLeft.X + correctionToTopLeft * (bottomRightX - topLeft.X)); 287 | var estAlignmentY = Math.floor (topLeft.Y + correctionToTopLeft * (bottomRightY - topLeft.Y)); 288 | 289 | // Kind of arbitrary -- expand search radius before giving up 290 | for (var i = 4; i <= 16; i <<= 1) 291 | { 292 | //try 293 | //{ 294 | alignmentPattern = this.findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY, i); 295 | break; 296 | //} 297 | //catch (re) 298 | //{ 299 | // try next round 300 | //} 301 | } 302 | // If we didn't find alignment pattern... well try anyway without it 303 | } 304 | 305 | var transform = this.createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension); 306 | 307 | var bits = this.sampleGrid(this.image, transform, dimension); 308 | 309 | var points: any; 310 | if (alignmentPattern == null) 311 | { 312 | points = new Array(bottomLeft, topLeft, topRight); 313 | } 314 | else 315 | { 316 | points = new Array(bottomLeft, topLeft, topRight, alignmentPattern); 317 | } 318 | return new DetectorResult(bits, points); 319 | } 320 | detect=function() 321 | { 322 | var info = new FinderPatternFinder(this.width, this.height).findFinderPattern(this.image); 323 | 324 | return this.processFinderPatternInfo(info); 325 | } 326 | } -------------------------------------------------------------------------------- /src/lib/qr-decoder/version.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Ported to JavaScript by Lazar Laszlo 2011 3 | 4 | lazarsoft@gmail.com, www.lazarsoft.info 5 | 6 | */ 7 | 8 | /* 9 | * 10 | * Copyright 2007 ZXing authors 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | 25 | import {BitMatrix} from "./bitmat" 26 | import {FormatInformation} from "./formatinf" 27 | 28 | export class ECB{ 29 | count: any; 30 | dataCodewords: any; 31 | constructor(count: any, dataCodewords: any){ 32 | this.count = count; 33 | this.dataCodewords = dataCodewords; 34 | } 35 | get Count() 36 | { 37 | return this.count; 38 | }; 39 | 40 | get DataCodewords() 41 | { 42 | return this.dataCodewords; 43 | }; 44 | 45 | } 46 | 47 | export class ECBlocks{ 48 | 49 | ecCodewordsPerBlock: any; 50 | ecBlocks: any; 51 | constructor( ecCodewordsPerBlock:any, ecBlocks1:any, ecBlocks2?:any){ 52 | this.ecCodewordsPerBlock = ecCodewordsPerBlock; 53 | if(ecBlocks2) 54 | this.ecBlocks = new Array(ecBlocks1, ecBlocks2); 55 | else 56 | this.ecBlocks = new Array(ecBlocks1); 57 | } 58 | get ECCodewordsPerBlock() 59 | { 60 | return this.ecCodewordsPerBlock; 61 | }; 62 | get TotalECCodewords() 63 | { 64 | return this.ecCodewordsPerBlock * this.NumBlocks; 65 | }; 66 | get NumBlocks() 67 | { 68 | var total = 0; 69 | for (var i = 0; i < this.ecBlocks.length; i++) 70 | { 71 | total += this.ecBlocks[i].length; 72 | } 73 | return total; 74 | }; 75 | 76 | getECBlocks=function() 77 | { 78 | return this.ecBlocks; 79 | } 80 | } 81 | 82 | 83 | export class Version{ 84 | 85 | versionNumber:any; 86 | alignmentPatternCenters:any; 87 | ecBlocks:any; 88 | totalCodewords: any; 89 | 90 | constructor( versionNumber: any, alignmentPatternCenters: any, ecBlocks1: any, ecBlocks2: any, ecBlocks3: any, ecBlocks4: any){ 91 | this.versionNumber = versionNumber; 92 | this.alignmentPatternCenters = alignmentPatternCenters; 93 | this.ecBlocks = new Array(ecBlocks1, ecBlocks2, ecBlocks3, ecBlocks4); 94 | 95 | var total = 0; 96 | var ecCodewords = ecBlocks1.ECCodewordsPerBlock; 97 | var ecbArray = ecBlocks1.getECBlocks(); 98 | for (var i = 0; i < ecbArray.length; i++) 99 | { 100 | var ecBlock = ecbArray[i]; 101 | total += ecBlock.Count * (ecBlock.DataCodewords + ecCodewords); 102 | } 103 | this.totalCodewords = total; 104 | } 105 | get VersionNumber() 106 | { 107 | return this.versionNumber; 108 | }; 109 | 110 | get AlignmentPatternCenters() 111 | { 112 | return this.alignmentPatternCenters; 113 | }; 114 | get TotalCodewords() 115 | { 116 | return this.totalCodewords; 117 | }; 118 | get DimensionForVersion() 119 | { 120 | return 17 + 4 * this.versionNumber; 121 | }; 122 | 123 | buildFunctionPattern=function() 124 | { 125 | var dimension = this.DimensionForVersion; 126 | var bitMatrix = new BitMatrix(dimension); 127 | 128 | // Top left finder pattern + separator + format 129 | bitMatrix.setRegion(0, 0, 9, 9); 130 | // Top right finder pattern + separator + format 131 | bitMatrix.setRegion(dimension - 8, 0, 8, 9); 132 | // Bottom left finder pattern + separator + format 133 | bitMatrix.setRegion(0, dimension - 8, 9, 8); 134 | 135 | // Alignment patterns 136 | var max = this.alignmentPatternCenters.length; 137 | for (var x = 0; x < max; x++) 138 | { 139 | var i = this.alignmentPatternCenters[x] - 2; 140 | for (var y = 0; y < max; y++) 141 | { 142 | if ((x == 0 && (y == 0 || y == max - 1)) || (x == max - 1 && y == 0)) 143 | { 144 | // No alignment patterns near the three finder paterns 145 | continue; 146 | } 147 | bitMatrix.setRegion(this.alignmentPatternCenters[y] - 2, i, 5, 5); 148 | } 149 | } 150 | 151 | // Vertical timing pattern 152 | bitMatrix.setRegion(6, 9, 1, dimension - 17); 153 | // Horizontal timing pattern 154 | bitMatrix.setRegion(9, 6, dimension - 17, 1); 155 | 156 | if (this.versionNumber > 6) 157 | { 158 | // Version info, top right 159 | bitMatrix.setRegion(dimension - 11, 0, 3, 6); 160 | // Version info, bottom left 161 | bitMatrix.setRegion(0, dimension - 11, 6, 3); 162 | } 163 | 164 | return bitMatrix; 165 | } 166 | getECBlocksForLevel=function( ecLevel: any) 167 | { 168 | return this.ecBlocks[ecLevel.ordinal()]; 169 | } 170 | 171 | static VERSION_DECODE_INFO = new Array(0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6, 0x0C762, 0x0D847, 0x0E60D, 0x0F928, 0x10B78, 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683, 0x168C9, 0x177EC, 0x18EC4, 0x191E1, 0x1AFAB, 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, 0x1F250, 0x209D5, 0x216F0, 0x228BA, 0x2379F, 0x24B0B, 0x2542E, 0x26A64, 0x27541, 0x28C69); 172 | 173 | static VERSIONS = Version.buildVersions(); 174 | 175 | static getVersionForNumber( versionNumber: any) 176 | { 177 | if (versionNumber < 1 || versionNumber > 40) 178 | { 179 | throw "ArgumentException"; 180 | } 181 | return Version.VERSIONS[versionNumber - 1]; 182 | } 183 | 184 | static getProvisionalVersionForDimension(dimension: any) 185 | { 186 | if (dimension % 4 != 1) 187 | { 188 | throw "Error getProvisionalVersionForDimension"; 189 | } 190 | try 191 | { 192 | return Version.getVersionForNumber((dimension - 17) >> 2); 193 | } 194 | catch ( iae) 195 | { 196 | throw "Error getVersionForNumber"; 197 | } 198 | } 199 | 200 | static decodeVersionInformation( versionBits: any) 201 | { 202 | var bestDifference = 0xffffffff; 203 | var bestVersion = 0; 204 | for (var i = 0; i < Version.VERSION_DECODE_INFO.length; i++) 205 | { 206 | var targetVersion = Version.VERSION_DECODE_INFO[i]; 207 | // Do the version info bits match exactly? done. 208 | if (targetVersion == versionBits) 209 | { 210 | return this.getVersionForNumber(i + 7); 211 | } 212 | // Otherwise see if this is the closest to a real version info bit string 213 | // we have seen so far 214 | var bitsDifference = FormatInformation.numBitsDiffering(versionBits, targetVersion); 215 | if (bitsDifference < bestDifference) 216 | { 217 | bestVersion = i + 7; 218 | bestDifference = bitsDifference; 219 | } 220 | } 221 | // We can tolerate up to 3 bits of error since no two version info codewords will 222 | // differ in less than 4 bits. 223 | if (bestDifference <= 3) 224 | { 225 | return this.getVersionForNumber(bestVersion); 226 | } 227 | // If we didn't find a close enough match, fail 228 | return null; 229 | } 230 | 231 | static buildVersions() 232 | { 233 | return new Array(new Version(1, new Array(), new ECBlocks(7, new ECB(1, 19)), new ECBlocks(10, new ECB(1, 16)), new ECBlocks(13, new ECB(1, 13)), new ECBlocks(17, new ECB(1, 9))), 234 | new Version(2, new Array(6, 18), new ECBlocks(10, new ECB(1, 34)), new ECBlocks(16, new ECB(1, 28)), new ECBlocks(22, new ECB(1, 22)), new ECBlocks(28, new ECB(1, 16))), 235 | new Version(3, new Array(6, 22), new ECBlocks(15, new ECB(1, 55)), new ECBlocks(26, new ECB(1, 44)), new ECBlocks(18, new ECB(2, 17)), new ECBlocks(22, new ECB(2, 13))), 236 | new Version(4, new Array(6, 26), new ECBlocks(20, new ECB(1, 80)), new ECBlocks(18, new ECB(2, 32)), new ECBlocks(26, new ECB(2, 24)), new ECBlocks(16, new ECB(4, 9))), 237 | new Version(5, new Array(6, 30), new ECBlocks(26, new ECB(1, 108)), new ECBlocks(24, new ECB(2, 43)), new ECBlocks(18, new ECB(2, 15), new ECB(2, 16)), new ECBlocks(22, new ECB(2, 11), new ECB(2, 12))), 238 | new Version(6, new Array(6, 34), new ECBlocks(18, new ECB(2, 68)), new ECBlocks(16, new ECB(4, 27)), new ECBlocks(24, new ECB(4, 19)), new ECBlocks(28, new ECB(4, 15))), 239 | new Version(7, new Array(6, 22, 38), new ECBlocks(20, new ECB(2, 78)), new ECBlocks(18, new ECB(4, 31)), new ECBlocks(18, new ECB(2, 14), new ECB(4, 15)), new ECBlocks(26, new ECB(4, 13), new ECB(1, 14))), 240 | new Version(8, new Array(6, 24, 42), new ECBlocks(24, new ECB(2, 97)), new ECBlocks(22, new ECB(2, 38), new ECB(2, 39)), new ECBlocks(22, new ECB(4, 18), new ECB(2, 19)), new ECBlocks(26, new ECB(4, 14), new ECB(2, 15))), 241 | new Version(9, new Array(6, 26, 46), new ECBlocks(30, new ECB(2, 116)), new ECBlocks(22, new ECB(3, 36), new ECB(2, 37)), new ECBlocks(20, new ECB(4, 16), new ECB(4, 17)), new ECBlocks(24, new ECB(4, 12), new ECB(4, 13))), 242 | new Version(10, new Array(6, 28, 50), new ECBlocks(18, new ECB(2, 68), new ECB(2, 69)), new ECBlocks(26, new ECB(4, 43), new ECB(1, 44)), new ECBlocks(24, new ECB(6, 19), new ECB(2, 20)), new ECBlocks(28, new ECB(6, 15), new ECB(2, 16))), 243 | new Version(11, new Array(6, 30, 54), new ECBlocks(20, new ECB(4, 81)), new ECBlocks(30, new ECB(1, 50), new ECB(4, 51)), new ECBlocks(28, new ECB(4, 22), new ECB(4, 23)), new ECBlocks(24, new ECB(3, 12), new ECB(8, 13))), 244 | new Version(12, new Array(6, 32, 58), new ECBlocks(24, new ECB(2, 92), new ECB(2, 93)), new ECBlocks(22, new ECB(6, 36), new ECB(2, 37)), new ECBlocks(26, new ECB(4, 20), new ECB(6, 21)), new ECBlocks(28, new ECB(7, 14), new ECB(4, 15))), 245 | new Version(13, new Array(6, 34, 62), new ECBlocks(26, new ECB(4, 107)), new ECBlocks(22, new ECB(8, 37), new ECB(1, 38)), new ECBlocks(24, new ECB(8, 20), new ECB(4, 21)), new ECBlocks(22, new ECB(12, 11), new ECB(4, 12))), 246 | new Version(14, new Array(6, 26, 46, 66), new ECBlocks(30, new ECB(3, 115), new ECB(1, 116)), new ECBlocks(24, new ECB(4, 40), new ECB(5, 41)), new ECBlocks(20, new ECB(11, 16), new ECB(5, 17)), new ECBlocks(24, new ECB(11, 12), new ECB(5, 13))), 247 | new Version(15, new Array(6, 26, 48, 70), new ECBlocks(22, new ECB(5, 87), new ECB(1, 88)), new ECBlocks(24, new ECB(5, 41), new ECB(5, 42)), new ECBlocks(30, new ECB(5, 24), new ECB(7, 25)), new ECBlocks(24, new ECB(11, 12), new ECB(7, 13))), 248 | new Version(16, new Array(6, 26, 50, 74), new ECBlocks(24, new ECB(5, 98), new ECB(1, 99)), new ECBlocks(28, new ECB(7, 45), new ECB(3, 46)), new ECBlocks(24, new ECB(15, 19), new ECB(2, 20)), new ECBlocks(30, new ECB(3, 15), new ECB(13, 16))), 249 | new Version(17, new Array(6, 30, 54, 78), new ECBlocks(28, new ECB(1, 107), new ECB(5, 108)), new ECBlocks(28, new ECB(10, 46), new ECB(1, 47)), new ECBlocks(28, new ECB(1, 22), new ECB(15, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(17, 15))), 250 | new Version(18, new Array(6, 30, 56, 82), new ECBlocks(30, new ECB(5, 120), new ECB(1, 121)), new ECBlocks(26, new ECB(9, 43), new ECB(4, 44)), new ECBlocks(28, new ECB(17, 22), new ECB(1, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(19, 15))), 251 | new Version(19, new Array(6, 30, 58, 86), new ECBlocks(28, new ECB(3, 113), new ECB(4, 114)), new ECBlocks(26, new ECB(3, 44), new ECB(11, 45)), new ECBlocks(26, new ECB(17, 21), new ECB(4, 22)), new ECBlocks(26, new ECB(9, 13), new ECB(16, 14))), 252 | new Version(20, new Array(6, 34, 62, 90), new ECBlocks(28, new ECB(3, 107), new ECB(5, 108)), new ECBlocks(26, new ECB(3, 41), new ECB(13, 42)), new ECBlocks(30, new ECB(15, 24), new ECB(5, 25)), new ECBlocks(28, new ECB(15, 15), new ECB(10, 16))), 253 | new Version(21, new Array(6, 28, 50, 72, 94), new ECBlocks(28, new ECB(4, 116), new ECB(4, 117)), new ECBlocks(26, new ECB(17, 42)), new ECBlocks(28, new ECB(17, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(19, 16), new ECB(6, 17))), 254 | new Version(22, new Array(6, 26, 50, 74, 98), new ECBlocks(28, new ECB(2, 111), new ECB(7, 112)), new ECBlocks(28, new ECB(17, 46)), new ECBlocks(30, new ECB(7, 24), new ECB(16, 25)), new ECBlocks(24, new ECB(34, 13))), 255 | new Version(23, new Array(6, 30, 54, 74, 102), new ECBlocks(30, new ECB(4, 121), new ECB(5, 122)), new ECBlocks(28, new ECB(4, 47), new ECB(14, 48)), new ECBlocks(30, new ECB(11, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(16, 15), new ECB(14, 16))), 256 | new Version(24, new Array(6, 28, 54, 80, 106), new ECBlocks(30, new ECB(6, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(6, 45), new ECB(14, 46)), new ECBlocks(30, new ECB(11, 24), new ECB(16, 25)), new ECBlocks(30, new ECB(30, 16), new ECB(2, 17))), 257 | new Version(25, new Array(6, 32, 58, 84, 110), new ECBlocks(26, new ECB(8, 106), new ECB(4, 107)), new ECBlocks(28, new ECB(8, 47), new ECB(13, 48)), new ECBlocks(30, new ECB(7, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(22, 15), new ECB(13, 16))), 258 | new Version(26, new Array(6, 30, 58, 86, 114), new ECBlocks(28, new ECB(10, 114), new ECB(2, 115)), new ECBlocks(28, new ECB(19, 46), new ECB(4, 47)), new ECBlocks(28, new ECB(28, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(33, 16), new ECB(4, 17))), 259 | new Version(27, new Array(6, 34, 62, 90, 118), new ECBlocks(30, new ECB(8, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(22, 45), new ECB(3, 46)), new ECBlocks(30, new ECB(8, 23), new ECB(26, 24)), new ECBlocks(30, new ECB(12, 15), new ECB(28, 16))), 260 | new Version(28, new Array(6, 26, 50, 74, 98, 122), new ECBlocks(30, new ECB(3, 117), new ECB(10, 118)), new ECBlocks(28, new ECB(3, 45), new ECB(23, 46)), new ECBlocks(30, new ECB(4, 24), new ECB(31, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(31, 16))), 261 | new Version(29, new Array(6, 30, 54, 78, 102, 126), new ECBlocks(30, new ECB(7, 116), new ECB(7, 117)), new ECBlocks(28, new ECB(21, 45), new ECB(7, 46)), new ECBlocks(30, new ECB(1, 23), new ECB(37, 24)), new ECBlocks(30, new ECB(19, 15), new ECB(26, 16))), 262 | new Version(30, new Array(6, 26, 52, 78, 104, 130), new ECBlocks(30, new ECB(5, 115), new ECB(10, 116)), new ECBlocks(28, new ECB(19, 47), new ECB(10, 48)), new ECBlocks(30, new ECB(15, 24), new ECB(25, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(25, 16))), 263 | new Version(31, new Array(6, 30, 56, 82, 108, 134), new ECBlocks(30, new ECB(13, 115), new ECB(3, 116)), new ECBlocks(28, new ECB(2, 46), new ECB(29, 47)), new ECBlocks(30, new ECB(42, 24), new ECB(1, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(28, 16))), 264 | new Version(32, new Array(6, 34, 60, 86, 112, 138), new ECBlocks(30, new ECB(17, 115)), new ECBlocks(28, new ECB(10, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(10, 24), new ECB(35, 25)), new ECBlocks(30, new ECB(19, 15), new ECB(35, 16))), 265 | new Version(33, new Array(6, 30, 58, 86, 114, 142), new ECBlocks(30, new ECB(17, 115), new ECB(1, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(21, 47)), new ECBlocks(30, new ECB(29, 24), new ECB(19, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(46, 16))), 266 | new Version(34, new Array(6, 34, 62, 90, 118, 146), new ECBlocks(30, new ECB(13, 115), new ECB(6, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(44, 24), new ECB(7, 25)), new ECBlocks(30, new ECB(59, 16), new ECB(1, 17))), 267 | new Version(35, new Array(6, 30, 54, 78, 102, 126, 150), new ECBlocks(30, new ECB(12, 121), new ECB(7, 122)), new ECBlocks(28, new ECB(12, 47), new ECB(26, 48)), new ECBlocks(30, new ECB(39, 24), new ECB(14, 25)),new ECBlocks(30, new ECB(22, 15), new ECB(41, 16))), 268 | new Version(36, new Array(6, 24, 50, 76, 102, 128, 154), new ECBlocks(30, new ECB(6, 121), new ECB(14, 122)), new ECBlocks(28, new ECB(6, 47), new ECB(34, 48)), new ECBlocks(30, new ECB(46, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(2, 15), new ECB(64, 16))), 269 | new Version(37, new Array(6, 28, 54, 80, 106, 132, 158), new ECBlocks(30, new ECB(17, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(29, 46), new ECB(14, 47)), new ECBlocks(30, new ECB(49, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(24, 15), new ECB(46, 16))), 270 | new Version(38, new Array(6, 32, 58, 84, 110, 136, 162), new ECBlocks(30, new ECB(4, 122), new ECB(18, 123)), new ECBlocks(28, new ECB(13, 46), new ECB(32, 47)), new ECBlocks(30, new ECB(48, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(42, 15), new ECB(32, 16))), 271 | new Version(39, new Array(6, 26, 54, 82, 110, 138, 166), new ECBlocks(30, new ECB(20, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(40, 47), new ECB(7, 48)), new ECBlocks(30, new ECB(43, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(10, 15), new ECB(67, 16))), 272 | new Version(40, new Array(6, 30, 58, 86, 114, 142, 170), new ECBlocks(30, new ECB(19, 118), new ECB(6, 119)), new ECBlocks(28, new ECB(18, 47), new ECB(31, 48)), new ECBlocks(30, new ECB(34, 24), new ECB(34, 25)), new ECBlocks(30, new ECB(20, 15), new ECB(61, 16)))); 273 | } 274 | } 275 | 276 | -------------------------------------------------------------------------------- /src/lib/qr-decoder/findpat.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Ported to JavaScript by Lazar Laszlo 2011 3 | 4 | lazarsoft@gmail.com, www.lazarsoft.info 5 | 6 | */ 7 | 8 | /* 9 | * 10 | * Copyright 2007 ZXing authors 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | declare global{ 25 | interface Array{ 26 | remove(from:T):T[]; 27 | } 28 | } 29 | 30 | if(!Array.prototype.remove){ 31 | Array.prototype.remove = function (from:any ) 32 | { 33 | var rest = this.slice((from) + 1 || this.length); 34 | this.length = from < 0 ? this.length + from : from; 35 | return this.push.apply(this, rest); 36 | } 37 | } 38 | 39 | 40 | 41 | 42 | export class FinderPattern{ 43 | static MIN_SKIP = 3; 44 | static MAX_MODULES = 57; 45 | static INTEGER_MATH_SHIFT = 8; 46 | static CENTER_QUORUM = 2; 47 | 48 | x: any; 49 | y: any; 50 | count: any; 51 | estimatedModuleSize: any; 52 | 53 | 54 | constructor(posX: any, posY: any, estimatedModuleSize: any){ 55 | this.x=posX; 56 | this.y=posY; 57 | this.count = 1; 58 | this.estimatedModuleSize = estimatedModuleSize; 59 | } 60 | 61 | get EstimatedModuleSize() 62 | { 63 | return this.estimatedModuleSize; 64 | }; 65 | get Count() 66 | { 67 | return this.count; 68 | }; 69 | get X() 70 | { 71 | return this.x; 72 | }; 73 | get Y() 74 | { 75 | return this.y; 76 | }; 77 | incrementCount = function() 78 | { 79 | this.count++; 80 | } 81 | aboutEquals=function( moduleSize: any, i:any , j:any) 82 | { 83 | if (Math.abs(i - this.y) <= moduleSize && Math.abs(j - this.x) <= moduleSize) 84 | { 85 | var moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize); 86 | return moduleSizeDiff <= 1.0 || moduleSizeDiff / this.estimatedModuleSize <= 1.0; 87 | } 88 | return false; 89 | } 90 | 91 | } 92 | 93 | export class FinderPatternInfo{ 94 | bottomLeft: any; 95 | topLeft: any; 96 | topRight: any; 97 | constructor(patternCenters: any){ 98 | this.bottomLeft = patternCenters[0]; 99 | this.topLeft = patternCenters[1]; 100 | this.topRight = patternCenters[2]; 101 | } 102 | get BottomLeft() 103 | { 104 | return this.bottomLeft; 105 | }; 106 | get TopLeft() 107 | { 108 | return this.topLeft; 109 | }; 110 | get TopRight() 111 | { 112 | return this.topRight; 113 | }; 114 | } 115 | 116 | export class FinderPatternFinder{ 117 | 118 | width:any; 119 | height:any; 120 | image:any; 121 | possibleCenters: any[] = new Array(); 122 | hasSkipped = false; 123 | crossCheckStateCount = new Array(0,0,0,0,0); 124 | resultPointCallback:any; 125 | 126 | constructor(width: any, height: any){ 127 | this.width = width; 128 | this.height = height; 129 | } 130 | 131 | get CrossCheckStateCount() 132 | { 133 | this.crossCheckStateCount[0] = 0; 134 | this.crossCheckStateCount[1] = 0; 135 | this.crossCheckStateCount[2] = 0; 136 | this.crossCheckStateCount[3] = 0; 137 | this.crossCheckStateCount[4] = 0; 138 | return this.crossCheckStateCount; 139 | }; 140 | 141 | orderBestPatterns=function(patterns:any ) 142 | { 143 | 144 | function distance( pattern1: any, pattern2: any) 145 | { 146 | let xDiff = pattern1.X - pattern2.X; 147 | let yDiff = pattern1.Y - pattern2.Y; 148 | return Math.sqrt( (xDiff * xDiff + yDiff * yDiff)); 149 | } 150 | 151 | /// Returns the z component of the cross product between vectors BC and BA. 152 | function crossProductZ( pointA: any, pointB: any, pointC: any) 153 | { 154 | var bX = pointB.x; 155 | var bY = pointB.y; 156 | return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX)); 157 | } 158 | 159 | 160 | // Find distances between pattern centers 161 | var zeroOneDistance = distance(patterns[0], patterns[1]); 162 | var oneTwoDistance = distance(patterns[1], patterns[2]); 163 | var zeroTwoDistance = distance(patterns[0], patterns[2]); 164 | 165 | var pointA: any, pointB: any, pointC: any; 166 | // Assume one closest to other two is B; A and C will just be guesses at first 167 | if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance) 168 | { 169 | pointB = patterns[0]; 170 | pointA = patterns[1]; 171 | pointC = patterns[2]; 172 | } 173 | else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance) 174 | { 175 | pointB = patterns[1]; 176 | pointA = patterns[0]; 177 | pointC = patterns[2]; 178 | } 179 | else 180 | { 181 | pointB = patterns[2]; 182 | pointA = patterns[0]; 183 | pointC = patterns[1]; 184 | } 185 | 186 | // Use cross product to figure out whether A and C are correct or flipped. 187 | // This asks whether BC x BA has a positive z component, which is the arrangement 188 | // we want for A, B, C. If it's negative, then we've got it flipped around and 189 | // should swap A and C. 190 | if (crossProductZ(pointA, pointB, pointC) < 0.0) 191 | { 192 | var temp = pointA; 193 | pointA = pointC; 194 | pointC = temp; 195 | } 196 | 197 | patterns[0] = pointA; 198 | patterns[1] = pointB; 199 | patterns[2] = pointC; 200 | } 201 | 202 | foundPatternCross=function( stateCount: any) 203 | { 204 | var totalModuleSize = 0; 205 | for (var i = 0; i < 5; i++) 206 | { 207 | var count = stateCount[i]; 208 | if (count == 0) 209 | { 210 | return false; 211 | } 212 | totalModuleSize += count; 213 | } 214 | if (totalModuleSize < 7) 215 | { 216 | return false; 217 | } 218 | var moduleSize = Math.floor((totalModuleSize << FinderPattern.INTEGER_MATH_SHIFT) / 7); 219 | var maxVariance = Math.floor(moduleSize / 2); 220 | // Allow less than 50% variance from 1-1-3-1-1 proportions 221 | return Math.abs(moduleSize - (stateCount[0] 222 | << FinderPattern.INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(moduleSize - (stateCount[1] 223 | << FinderPattern.INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(3 * moduleSize - (stateCount[2] 224 | << FinderPattern.INTEGER_MATH_SHIFT)) < 3 * maxVariance && Math.abs(moduleSize - (stateCount[3] 225 | << FinderPattern.INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(moduleSize - (stateCount[4] 226 | << FinderPattern.INTEGER_MATH_SHIFT)) < maxVariance; 227 | } 228 | 229 | centerFromEnd=function( stateCount: any, end: any) 230 | { 231 | return (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0; 232 | } 233 | 234 | crossCheckVertical=function( startI: any, centerJ: any, maxCount: any, originalStateCountTotal: any) 235 | { 236 | var image = this.image; 237 | 238 | var maxI = this.height; 239 | var stateCount = this.CrossCheckStateCount; 240 | 241 | // Start counting up from center 242 | var i = startI; 243 | while (i >= 0 && image[centerJ + i*this.width]) 244 | { 245 | stateCount[2]++; 246 | i--; 247 | } 248 | if (i < 0) 249 | { 250 | return NaN; 251 | } 252 | while (i >= 0 && !image[centerJ +i*this.width] && stateCount[1] <= maxCount) 253 | { 254 | stateCount[1]++; 255 | i--; 256 | } 257 | // If already too many modules in this state or ran off the edge: 258 | if (i < 0 || stateCount[1] > maxCount) 259 | { 260 | return NaN; 261 | } 262 | while (i >= 0 && image[centerJ + i*this.width] && stateCount[0] <= maxCount) 263 | { 264 | stateCount[0]++; 265 | i--; 266 | } 267 | if (stateCount[0] > maxCount) 268 | { 269 | return NaN; 270 | } 271 | 272 | // Now also count down from center 273 | i = startI + 1; 274 | while (i < maxI && image[centerJ +i*this.width]) 275 | { 276 | stateCount[2]++; 277 | i++; 278 | } 279 | if (i == maxI) 280 | { 281 | return NaN; 282 | } 283 | while (i < maxI && !image[centerJ + i*this.width] && stateCount[3] < maxCount) 284 | { 285 | stateCount[3]++; 286 | i++; 287 | } 288 | if (i == maxI || stateCount[3] >= maxCount) 289 | { 290 | return NaN; 291 | } 292 | while (i < maxI && image[centerJ + i*this.width] && stateCount[4] < maxCount) 293 | { 294 | stateCount[4]++; 295 | i++; 296 | } 297 | if (stateCount[4] >= maxCount) 298 | { 299 | return NaN; 300 | } 301 | 302 | // If we found a finder-pattern-like section, but its size is more than 40% different than 303 | // the original, assume it's a false positive 304 | var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; 305 | if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) 306 | { 307 | return NaN; 308 | } 309 | 310 | return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, i):NaN; 311 | } 312 | 313 | crossCheckHorizontal=function( startJ: any, centerI: any, maxCount: any, originalStateCountTotal: any) 314 | { 315 | var image = this.image; 316 | 317 | var maxJ = this.width; 318 | var stateCount = this.CrossCheckStateCount; 319 | 320 | var j = startJ; 321 | while (j >= 0 && image[j+ centerI*this.width]) 322 | { 323 | stateCount[2]++; 324 | j--; 325 | } 326 | if (j < 0) 327 | { 328 | return NaN; 329 | } 330 | while (j >= 0 && !image[j+ centerI*this.width] && stateCount[1] <= maxCount) 331 | { 332 | stateCount[1]++; 333 | j--; 334 | } 335 | if (j < 0 || stateCount[1] > maxCount) 336 | { 337 | return NaN; 338 | } 339 | while (j >= 0 && image[j+ centerI*this.width] && stateCount[0] <= maxCount) 340 | { 341 | stateCount[0]++; 342 | j--; 343 | } 344 | if (stateCount[0] > maxCount) 345 | { 346 | return NaN; 347 | } 348 | 349 | j = startJ + 1; 350 | while (j < maxJ && image[j+ centerI*this.width]) 351 | { 352 | stateCount[2]++; 353 | j++; 354 | } 355 | if (j == maxJ) 356 | { 357 | return NaN; 358 | } 359 | while (j < maxJ && !image[j+ centerI*this.width] && stateCount[3] < maxCount) 360 | { 361 | stateCount[3]++; 362 | j++; 363 | } 364 | if (j == maxJ || stateCount[3] >= maxCount) 365 | { 366 | return NaN; 367 | } 368 | while (j < maxJ && image[j+ centerI*this.width] && stateCount[4] < maxCount) 369 | { 370 | stateCount[4]++; 371 | j++; 372 | } 373 | if (stateCount[4] >= maxCount) 374 | { 375 | return NaN; 376 | } 377 | 378 | // If we found a finder-pattern-like section, but its size is significantly different than 379 | // the original, assume it's a false positive 380 | var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; 381 | if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) 382 | { 383 | return NaN; 384 | } 385 | 386 | return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, j):NaN; 387 | } 388 | handlePossibleCenter=function( stateCount: any, i: any, j: any) 389 | { 390 | var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; 391 | var centerJ = this.centerFromEnd(stateCount, j); //float 392 | var centerI = this.crossCheckVertical(i, Math.floor( centerJ), stateCount[2], stateCountTotal); //float 393 | if (!isNaN(centerI)) 394 | { 395 | // Re-cross check 396 | centerJ = this.crossCheckHorizontal(Math.floor( centerJ), Math.floor( centerI), stateCount[2], stateCountTotal); 397 | if (!isNaN(centerJ)) 398 | { 399 | var estimatedModuleSize = stateCountTotal / 7.0; 400 | var found = false; 401 | var max = this.possibleCenters.length; 402 | for (var index = 0; index < max; index++) 403 | { 404 | var center = this.possibleCenters[index]; 405 | // Look for about the same center and module size: 406 | if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) 407 | { 408 | center.incrementCount(); 409 | found = true; 410 | break; 411 | } 412 | } 413 | if (!found) 414 | { 415 | var point = new FinderPattern(centerJ, centerI, estimatedModuleSize); 416 | this.possibleCenters.push(point); 417 | if (this.resultPointCallback != null) 418 | { 419 | this.resultPointCallback.foundPossibleResultPoint(point); 420 | } 421 | } 422 | return true; 423 | } 424 | } 425 | return false; 426 | } 427 | 428 | selectBestPatterns=function() 429 | { 430 | 431 | var startSize = this.possibleCenters.length; 432 | if (startSize < 3) 433 | { 434 | // Couldn't find enough finder patterns 435 | throw `Couldn't find enough finder patterns (found: ${startSize})`; 436 | } 437 | 438 | // Filter outlier possibilities whose module size is too different 439 | if (startSize > 3) 440 | { 441 | // But we can only afford to do so if we have at least 4 possibilities to choose from 442 | var totalModuleSize = 0.0; 443 | var square = 0.0; 444 | for (var i = 0; i < startSize; i++) 445 | { 446 | //totalModuleSize += this.possibleCenters[i].EstimatedModuleSize; 447 | var centerValue=this.possibleCenters[i].EstimatedModuleSize; 448 | totalModuleSize += centerValue; 449 | square += (centerValue * centerValue); 450 | } 451 | var average = totalModuleSize / startSize; 452 | this.possibleCenters.sort(function(center1: any,center2: any) { 453 | var dA=Math.abs(center2.EstimatedModuleSize - average); 454 | var dB=Math.abs(center1.EstimatedModuleSize - average); 455 | if (dA < dB) { 456 | return (-1); 457 | } else if (dA == dB) { 458 | return 0; 459 | } else { 460 | return 1; 461 | } 462 | }); 463 | 464 | var stdDev = Math.sqrt(square / startSize - average * average); 465 | var limit = Math.max(0.2 * average, stdDev); 466 | for (var i = this.possibleCenters.length - 1; i >= 0 ; i--) 467 | { 468 | var pattern = this.possibleCenters[i]; 469 | //if (Math.abs(pattern.EstimatedModuleSize - average) > 0.2 * average) 470 | if (Math.abs(pattern.EstimatedModuleSize - average) > limit) 471 | { 472 | this.possibleCenters.remove(i); 473 | } 474 | } 475 | } 476 | 477 | if (this.possibleCenters.length > 3) 478 | { 479 | // Throw away all but those first size candidate points we found. 480 | this.possibleCenters.sort(function(a: any, b: any){ 481 | if (a.count > b.count){return -1;} 482 | if (a.count < b.count){return 1;} 483 | return 0; 484 | }); 485 | } 486 | 487 | return new Array( this.possibleCenters[0], this.possibleCenters[1], this.possibleCenters[2]); 488 | } 489 | 490 | findRowSkip=function() 491 | { 492 | var max = this.possibleCenters.length; 493 | if (max <= 1) 494 | { 495 | return 0; 496 | } 497 | var firstConfirmedCenter: any = null; 498 | for (var i = 0; i < max; i++) 499 | { 500 | var center = this.possibleCenters[i]; 501 | if (center.Count >= FinderPattern.CENTER_QUORUM) 502 | { 503 | if (firstConfirmedCenter == null) 504 | { 505 | firstConfirmedCenter = center; 506 | } 507 | else 508 | { 509 | // We have two confirmed centers 510 | // How far down can we skip before resuming looking for the next 511 | // pattern? In the worst case, only the difference between the 512 | // difference in the x / y coordinates of the two centers. 513 | // This is the case where you find top left last. 514 | this.hasSkipped = true; 515 | return Math.floor ((Math.abs(firstConfirmedCenter.X - center.X) - Math.abs(firstConfirmedCenter.Y - center.Y)) / 2); 516 | } 517 | } 518 | } 519 | return 0; 520 | } 521 | 522 | haveMultiplyConfirmedCenters=function() 523 | { 524 | var confirmedCount = 0; 525 | var totalModuleSize = 0.0; 526 | var max = this.possibleCenters.length; 527 | for (var i = 0; i < max; i++) 528 | { 529 | var pattern = this.possibleCenters[i]; 530 | if (pattern.Count >= FinderPattern.CENTER_QUORUM) 531 | { 532 | confirmedCount++; 533 | totalModuleSize += pattern.EstimatedModuleSize; 534 | } 535 | } 536 | if (confirmedCount < 3) 537 | { 538 | return false; 539 | } 540 | // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive" 541 | // and that we need to keep looking. We detect this by asking if the estimated module sizes 542 | // vary too much. We arbitrarily say that when the total deviation from average exceeds 543 | // 5% of the total module size estimates, it's too much. 544 | var average = totalModuleSize / max; 545 | var totalDeviation = 0.0; 546 | for (var i = 0; i < max; i++) 547 | { 548 | pattern = this.possibleCenters[i]; 549 | totalDeviation += Math.abs(pattern.EstimatedModuleSize - average); 550 | } 551 | return totalDeviation <= 0.05 * totalModuleSize; 552 | } 553 | 554 | findFinderPattern = function(image: any) 555 | { 556 | var tryHarder = false; 557 | this.image=image; 558 | var maxI = this.height; 559 | var maxJ = this.width; 560 | var iSkip = Math.floor((3 * maxI) / (4 * FinderPattern.MAX_MODULES)); 561 | if (iSkip < FinderPattern.MIN_SKIP || tryHarder) 562 | { 563 | iSkip = FinderPattern.MIN_SKIP; 564 | } 565 | 566 | var done = false; 567 | var stateCount = new Array(5); 568 | for (var i = iSkip - 1; i < maxI && !done; i += iSkip) 569 | { 570 | // Get a row of black/white values 571 | stateCount[0] = 0; 572 | stateCount[1] = 0; 573 | stateCount[2] = 0; 574 | stateCount[3] = 0; 575 | stateCount[4] = 0; 576 | var currentState = 0; 577 | for (var j = 0; j < maxJ; j++) 578 | { 579 | if (image[j+i*this.width] ) 580 | { 581 | // Black pixel 582 | if ((currentState & 1) == 1) 583 | { 584 | // Counting white pixels 585 | currentState++; 586 | } 587 | stateCount[currentState]++; 588 | } 589 | else 590 | { 591 | // White pixel 592 | if ((currentState & 1) == 0) 593 | { 594 | // Counting black pixels 595 | if (currentState == 4) 596 | { 597 | // A winner? 598 | if (this.foundPatternCross(stateCount)) 599 | { 600 | // Yes 601 | var confirmed = this.handlePossibleCenter(stateCount, i, j); 602 | if (confirmed) 603 | { 604 | // Start examining every other line. Checking each line turned out to be too 605 | // expensive and didn't improve performance. 606 | iSkip = 2; 607 | if (this.hasSkipped) 608 | { 609 | done = this.haveMultiplyConfirmedCenters(); 610 | } 611 | else 612 | { 613 | var rowSkip = this.findRowSkip(); 614 | if (rowSkip > stateCount[2]) 615 | { 616 | // Skip rows between row of lower confirmed center 617 | // and top of presumed third confirmed center 618 | // but back up a bit to get a full chance of detecting 619 | // it, entire width of center of finder pattern 620 | 621 | // Skip by rowSkip, but back off by stateCount[2] (size of last center 622 | // of pattern we saw) to be conservative, and also back off by iSkip which 623 | // is about to be re-added 624 | i += rowSkip - stateCount[2] - iSkip; 625 | j = maxJ - 1; 626 | } 627 | } 628 | } 629 | else 630 | { 631 | // Advance to next black pixel 632 | do 633 | { 634 | j++; 635 | } 636 | while (j < maxJ && !image[j + i*this.width]); 637 | j--; // back up to that last white pixel 638 | } 639 | // Clear state to start looking again 640 | currentState = 0; 641 | stateCount[0] = 0; 642 | stateCount[1] = 0; 643 | stateCount[2] = 0; 644 | stateCount[3] = 0; 645 | stateCount[4] = 0; 646 | } 647 | else 648 | { 649 | // No, shift counts back by two 650 | stateCount[0] = stateCount[2]; 651 | stateCount[1] = stateCount[3]; 652 | stateCount[2] = stateCount[4]; 653 | stateCount[3] = 1; 654 | stateCount[4] = 0; 655 | currentState = 3; 656 | } 657 | } 658 | else 659 | { 660 | stateCount[++currentState]++; 661 | } 662 | } 663 | else 664 | { 665 | // Counting white pixels 666 | stateCount[currentState]++; 667 | } 668 | } 669 | } 670 | if (this.foundPatternCross(stateCount)) 671 | { 672 | var confirmed = this.handlePossibleCenter(stateCount, i, maxJ); 673 | if (confirmed) 674 | { 675 | iSkip = stateCount[0]; 676 | if (this.hasSkipped) 677 | { 678 | // Found a third one 679 | done = this.haveMultiplyConfirmedCenters(); 680 | } 681 | } 682 | } 683 | } 684 | 685 | var patternInfo = this.selectBestPatterns(); 686 | this.orderBestPatterns(patternInfo); 687 | 688 | return new FinderPatternInfo(patternInfo); 689 | }; 690 | } 691 | 692 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------