-
-
Notifications
You must be signed in to change notification settings - Fork 224
/
browser-code-reader.ts
324 lines (259 loc) · 9.68 KB
/
browser-code-reader.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import {
Reader,
BinaryBitmap,
HybridBinarizer,
Result,
Exception,
HTMLCanvasElementLuminanceSource,
} from '@zxing/library';
/**
* Based on zxing-typescript BrowserCodeReader
*/
export class BrowserCodeReader {
/**
* The HTML video element, used to display the camera stream.
*/
private videoElement: HTMLVideoElement;
/**
* Should contain the actual registered listener for video play-ended,
* used to unregister that listener when needed.
*/
private videoPlayEndedEventListener: EventListener;
/**
* Should contain the actual registered listener for video playing,
* used to unregister that listener when needed.
*/
private videoPlayingEventListener: EventListener;
/**
* Should contain the actual registered listener for video loaded-metadata,
* used to unregister that listener when needed.
*/
private videoLoadedMetadataEventListener: EventListener;
/**
* The HTML image element, used as a fallback for the video element when decoding.
*/
private imageElement: HTMLImageElement;
/**
* Should contain the actual registered listener for image loading,
* used to unregister that listener when needed.
*/
private imageLoadedEventListener: EventListener;
/**
* The HTML canvas element, used to draw the video or image's frame for decoding.
*/
private canvasElement: HTMLCanvasElement;
/**
* The HTML canvas element context.
*/
private canvasElementContext: CanvasRenderingContext2D;
/**
* The continuous scan timeout Id.
*/
private timeoutHandler: number;
/**
* The stream output from camera.
*/
private stream: MediaStream;
/**
* Constructor for dependency injection.
*
* @param reader The barcode reader to be used to decode the stream.
* @param timeBetweenScans The scan throttling in milliseconds.
*/
public constructor(private reader: Reader, private timeBetweenScans: number = 500) { }
/**
* Starts the decoding from the actual or a new video element.
*
* @param callbackFn The callback to be executed after every scan attempt
* @param deviceId The device's to be used Id
* @param videoElement A new video element
*/
public decodeFromInputVideoDevice(callbackFn: (result: Result) => any, deviceId?: string, videoElement?: HTMLVideoElement): void {
this.reset();
this.prepareVideoElement(videoElement);
const video = deviceId === undefined
? { facingMode: { exact: 'environment' } }
: { deviceId: { exact: deviceId } };
const constraints: MediaStreamConstraints = {
audio: false,
video
};
if (navigator) {
navigator
.mediaDevices
.getUserMedia(constraints)
.then((stream: MediaStream) => this.startDecodeFromStream(stream, callbackFn))
.catch((err: any) => {
/* handle the error, or not */
console.error(err);
});
}
}
/**
* Sets the new stream and request a new decoding-with-delay.
*
* @param stream The stream to be shown in the video element.
* @param callbackFn A callback for the decode method.
*/
private startDecodeFromStream(stream: MediaStream, callbackFn: (result: Result) => any): void {
this.stream = stream;
// Older browsers may not have srcObject
if ('srcObject' in this.videoElement) {
// @NOTE Throws Exception if interrupted by a new loaded request
this.videoElement.srcObject = stream;
} else {
// @NOTE Avoid using this in new browsers, as it is going away.
(<HTMLVideoElement>this.videoElement).src = window.URL.createObjectURL(stream);
}
this.videoPlayingEventListener = () => {
this.decodeWithDelay(callbackFn);
};
this.videoElement.addEventListener('playing', this.videoPlayingEventListener);
this.videoLoadedMetadataEventListener = () => {
this.videoElement.play();
};
this.videoElement.addEventListener('loadedmetadata', this.videoLoadedMetadataEventListener);
}
/**
* Sets a HTMLVideoElement for scanning or creates a new one.
*
* @param videoElement The HTMLVideoElement to be set.
*/
private prepareVideoElement(videoElement?: HTMLVideoElement) {
if (!videoElement) {
this.videoElement = document.createElement('video');
this.videoElement.width = 200;
this.videoElement.height = 200;
} else {
this.videoElement = videoElement;
}
}
/**
*
* @param callbackFn
*/
private decodeWithDelay(callbackFn: (result: Result) => any): void {
this.timeoutHandler = window.setTimeout(this.decode.bind(this, callbackFn), this.timeBetweenScans);
}
/**
* Does the real image decoding job.
*
* @param callbackFn
* @param retryIfNotFound
* @param retryIfChecksumOrFormatError
* @param once
*/
private decode(
callbackFn: (result: Result) => any,
retryIfNotFound: boolean = true,
retryIfChecksumOrFormatError: boolean = true,
once = false
): void {
if (undefined === this.canvasElementContext) {
this.prepareCaptureCanvas();
}
this.canvasElementContext.drawImage(this.videoElement || this.imageElement, 0, 0);
const luminanceSource = new HTMLCanvasElementLuminanceSource(this.canvasElement);
const binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));
try {
const result = this.readerDecode(binaryBitmap);
callbackFn(result);
if (!once && !!this.stream) {
setTimeout(() => this.decodeWithDelay(callbackFn), this.timeBetweenScans);
}
} catch (re) {
console.debug(retryIfChecksumOrFormatError, re);
if (retryIfNotFound && Exception.isOfType(re, Exception.NotFoundException)) {
console.debug('zxing-scanner', 'QR-code not-found, trying again...');
this.decodeWithDelay(callbackFn);
} else if (
retryIfChecksumOrFormatError &&
(
Exception.isOfType(re, Exception.ChecksumException) ||
Exception.isOfType(re, Exception.FormatException)
)
) {
console.warn('zxing-scanner', 'Checksum or format error, trying again...', re);
this.decodeWithDelay(callbackFn);
}
}
}
/**
* Alias for this.reader.decode
*
* @param binaryBitmap
*/
protected readerDecode(binaryBitmap: BinaryBitmap): Result {
return this.reader.decode(binaryBitmap);
}
/**
* 🖌 Prepares the canvas for capture and scan frames.
*/
private prepareCaptureCanvas() {
const canvasElement = document.createElement('canvas');
let width: number;
let height: number;
if (undefined !== this.videoElement) {
width = this.videoElement.videoWidth;
height = this.videoElement.videoHeight;
} else {
width = this.imageElement.naturalWidth || this.imageElement.width;
height = this.imageElement.naturalHeight || this.imageElement.height;
}
canvasElement.style.width = width + 'px';
canvasElement.style.height = height + 'px';
canvasElement.width = width;
canvasElement.height = height;
this.canvasElement = canvasElement;
this.canvasElementContext = canvasElement.getContext('2d');
}
/**
* Stops the continuous scan and cleans the stream.
*/
private stop(): void {
if (this.timeoutHandler) {
window.clearTimeout(this.timeoutHandler);
this.timeoutHandler = null;
}
if (this.stream) {
this.stream.getTracks()[0].stop();
this.stream = null;
}
}
/**
* Resets the scanner and it's configurations.
*/
public reset(): void {
// stops the camera, preview and scan 🔴
this.stop();
if (this.videoElement) {
// first gives freedon to the element 🕊
if (undefined !== this.videoPlayEndedEventListener) {
this.videoElement.removeEventListener('ended', this.videoPlayEndedEventListener);
}
if (undefined !== this.videoPlayingEventListener) {
this.videoElement.removeEventListener('playing', this.videoPlayingEventListener);
}
if (undefined !== this.videoLoadedMetadataEventListener) {
this.videoElement.removeEventListener('loadedmetadata', this.videoLoadedMetadataEventListener);
}
// then forgets about that element 😢
this.videoElement.srcObject = undefined;
this.videoElement.removeAttribute('src');
this.videoElement = undefined;
}
if (this.imageElement) {
// first gives freedon to the element 🕊
if (undefined !== this.videoPlayEndedEventListener) {
this.imageElement.removeEventListener('load', this.imageLoadedEventListener);
}
// then forgets about that element 😢
this.imageElement.src = undefined;
this.imageElement.removeAttribute('src');
this.imageElement = undefined;
}
// cleans canvas references 🖌
this.canvasElementContext = undefined;
this.canvasElement = undefined;
}
}