@ericblade/quagga2 1.10.1 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/DEPENDENCIES.md +286 -0
  2. package/HALFSAMPLE_PERFORMANCE_ANALYSIS.md +178 -0
  3. package/README.md +119 -10
  4. package/dist/quagga.js +11087 -10681
  5. package/dist/quagga.min.js +4 -3
  6. package/docs/_config.yml +3 -0
  7. package/docs/assets/bb-binary.png +0 -0
  8. package/docs/assets/bb-rotated.png +0 -0
  9. package/docs/assets/binary.png +0 -0
  10. package/docs/assets/component-labeling-line.png +0 -0
  11. package/docs/assets/component-labeling-text.png +0 -0
  12. package/docs/assets/component-labeling.png +0 -0
  13. package/docs/assets/connected-patch-labels.png +0 -0
  14. package/docs/assets/mobile-detected.png +0 -0
  15. package/docs/assets/mobile-located.png +0 -0
  16. package/docs/assets/patches_found.png +0 -0
  17. package/docs/assets/quaggaJS-code128.png +0 -0
  18. package/docs/assets/remaining-patch-labels.png +0 -0
  19. package/docs/assets/skeleton.png +0 -0
  20. package/docs/assets/teaser.png +0 -0
  21. package/docs/contributing.md +102 -0
  22. package/docs/explanation/algorithm-overview.md +69 -0
  23. package/docs/explanation/architecture.md +117 -0
  24. package/docs/explanation/how-barcode-localization-works.md +197 -0
  25. package/docs/explanation/index.md +80 -0
  26. package/docs/explanation/input-streams.md +270 -0
  27. package/docs/getting-started.md +213 -0
  28. package/docs/how-to-guides/configure-readers.md +79 -0
  29. package/docs/how-to-guides/external-readers.md +234 -0
  30. package/docs/how-to-guides/handle-difficult-barcodes.md +127 -0
  31. package/docs/how-to-guides/index.md +77 -0
  32. package/docs/how-to-guides/optimize-performance.md +114 -0
  33. package/docs/how-to-guides/tips-and-tricks.md +115 -0
  34. package/docs/how-to-guides/use-debug-flags.md +776 -0
  35. package/docs/how-to-guides/working-with-coordinates.md +254 -0
  36. package/docs/index.md +118 -0
  37. package/docs/reference/api.md +716 -0
  38. package/docs/reference/browser-support.md +109 -0
  39. package/docs/reference/camera-access.md +376 -0
  40. package/docs/reference/configuration.md +1008 -0
  41. package/docs/reference/dependencies.md +295 -0
  42. package/docs/reference/index.md +74 -0
  43. package/docs/reference/readers.md +261 -0
  44. package/docs/tutorials/first-scan.md +141 -0
  45. package/docs/tutorials/index.md +77 -0
  46. package/docs/tutorials/node-usage.md +182 -0
  47. package/docs/tutorials/react-integration.md +176 -0
  48. package/docs/tutorials/static-image.md +130 -0
  49. package/lib/quagga.js +3140 -2757
  50. package/package.json +22 -18
  51. package/type-definitions/quagga.d.ts +111 -9
@@ -0,0 +1,270 @@
1
+ # How Input Streams Work {#how-input-streams-work}
2
+
3
+ This article explains the technical details of how Quagga2's input stream system works. Understanding this is helpful for troubleshooting initialization issues and understanding async behavior.
4
+
5
+ ## Overview {#overview}
6
+
7
+ Quagga2 supports three types of input streams for reading barcode data:
8
+
9
+ | Type | Use Case | Input Source |
10
+ |------|----------|--------------|
11
+ | **LiveStream** | Real-time camera scanning | Device camera via getUserMedia |
12
+ | **VideoStream** | Pre-recorded video files | Video file via `<video>` element |
13
+ | **ImageStream** | Static images or image sequences | Image file(s) via URL |
14
+
15
+ All three stream types share the same interface (`InputStream`) and follow a common initialization pattern, but differ in how they acquire media.
16
+
17
+ ## The InputStream Interface {#inputstream-interface}
18
+
19
+ Every input stream implements these core methods:
20
+
21
+ ```typescript
22
+ interface InputStream {
23
+ // Dimensions
24
+ getWidth(): number;
25
+ getHeight(): number;
26
+ getRealWidth(): number;
27
+ getRealHeight(): number;
28
+ setWidth(width: number): void;
29
+ setHeight(height: number): void;
30
+
31
+ // Frame access
32
+ getFrame(): HTMLVideoElement | HTMLImageElement | null;
33
+
34
+ // Event handling
35
+ addEventListener(event: string, handler: Function): void;
36
+ clearEventHandlers(): void;
37
+ trigger(eventName: string, args?: any): void;
38
+
39
+ // Playback control
40
+ play(): void;
41
+ pause(): void;
42
+ ended(): boolean;
43
+
44
+ // Configuration
45
+ setInputStream(config: any): void;
46
+ getConfig(): any;
47
+ }
48
+ ```
49
+
50
+ ## Initialization Flow {#initialization-flow}
51
+
52
+ All stream types follow the same initialization sequence:
53
+
54
+ ```
55
+ init() → initInputStream() → [async media access] → 'canrecord' event → canRecord() → framegrabber created
56
+ ```
57
+
58
+ Here's what happens at each step:
59
+
60
+ ### 1. `init()` is called {#step-1-init}
61
+
62
+ The static `Quagga.init(config, callback)` function starts the process:
63
+
64
+ ```javascript
65
+ Quagga.init({
66
+ inputStream: {
67
+ type: 'LiveStream', // or 'VideoStream' or 'ImageStream'
68
+ target: document.querySelector('#scanner'),
69
+ // ... other options
70
+ },
71
+ // ... decoder config
72
+ }, (err) => {
73
+ if (err) {
74
+ console.error('Init failed:', err);
75
+ return;
76
+ }
77
+ Quagga.start();
78
+ });
79
+ ```
80
+
81
+ ### 2. `initInputStream()` creates the stream {#step-2-initinputstream}
82
+
83
+ Based on the `type` configuration, the appropriate stream factory is called:
84
+
85
+ - `LiveStream` → `createLiveStream(video)`
86
+ - `VideoStream` → `createVideoStream(video)`
87
+ - `ImageStream` → `createImageStream()`
88
+
89
+ ### 3. Async media access begins {#step-3-async-media}
90
+
91
+ This is where the streams diverge:
92
+
93
+ **LiveStream**: Calls `CameraAccess.request()` which uses `navigator.mediaDevices.getUserMedia()`. This is async because:
94
+ - Browser shows a permission prompt
95
+ - Camera hardware needs to spin up
96
+ - Video dimensions aren't known until stream starts
97
+
98
+ **VideoStream**: Creates a `<video>` element and waits for the video to load metadata. Async because the video file must be fetched.
99
+
100
+ **ImageStream**: Uses `ImageLoader` to fetch and decode image(s). Async because images must be downloaded.
101
+
102
+ ### 4. `canrecord` event fires {#step-4-canrecord}
103
+
104
+ When the media is ready, the stream triggers the `canrecord` event. This is the signal that:
105
+ - Media dimensions are now available
106
+ - Frames can be grabbed
107
+ - Processing can begin
108
+
109
+ ### 5. `canRecord()` completes initialization {#step-5-canrecord-callback}
110
+
111
+ The `canRecord()` callback:
112
+ 1. Validates the input stream is properly initialized
113
+ 2. Calls `checkImageConstraints()` to validate/adjust dimensions
114
+ 3. Creates the canvas for drawing frames
115
+ 4. Creates the **framegrabber** (the component that extracts frames)
116
+ 5. Sets up worker threads (if configured)
117
+ 6. Calls the user's callback to signal init is complete
118
+
119
+ ### 6. Framegrabber indicates completion {#step-6-framegrabber}
120
+
121
+ The `framegrabber` being non-null is the reliable indicator that initialization completed successfully. This is why:
122
+
123
+ - The static `start()` function checks `if (!_context.framegrabber)` before proceeding
124
+ - The `stop()` function uses `!framegrabber` to detect if init was still in progress
125
+
126
+ ## Stream Type Details {#stream-type-details}
127
+
128
+ ### LiveStream {#livestream}
129
+
130
+ **Purpose**: Real-time barcode scanning using the device camera.
131
+
132
+ **How it works**:
133
+ 1. Creates or finds a `<video>` element in the target container
134
+ 2. Requests camera access via `getUserMedia()`
135
+ 3. Attaches the camera stream to the video element
136
+ 4. Sets `autoplay="true"` so the video starts immediately
137
+ 5. Triggers `canrecord` when camera is ready
138
+
139
+ **Key characteristics**:
140
+ - `ended()` always returns `false` (camera never "ends")
141
+ - Requires HTTPS in production (browser security requirement)
142
+ - Can specify camera constraints (facing mode, resolution)
143
+
144
+ **Configuration example**:
145
+ ```javascript
146
+ inputStream: {
147
+ type: 'LiveStream',
148
+ target: document.querySelector('#camera'),
149
+ constraints: {
150
+ facingMode: 'environment', // Back camera
151
+ width: { min: 640 },
152
+ height: { min: 480 }
153
+ }
154
+ }
155
+ ```
156
+
157
+ ### VideoStream {#videostream}
158
+
159
+ **Purpose**: Scanning barcodes from pre-recorded video files.
160
+
161
+ **How it works**:
162
+ 1. Creates a new `<video>` element
163
+ 2. Sets the `src` attribute to the video URL
164
+ 3. Waits for video metadata to load
165
+ 4. Triggers `canrecord` when dimensions are known
166
+
167
+ **Key characteristics**:
168
+ - `ended()` returns the video element's ended state
169
+ - Supports seeking via `setCurrentTime()`
170
+ - Video plays frame-by-frame during scanning
171
+
172
+ **Configuration example**:
173
+ ```javascript
174
+ inputStream: {
175
+ type: 'VideoStream',
176
+ src: '/path/to/video.mp4'
177
+ }
178
+ ```
179
+
180
+ ### ImageStream {#imagestream}
181
+
182
+ **Purpose**: Scanning barcodes from static images or image sequences.
183
+
184
+ **How it works**:
185
+ 1. Parses the image URL configuration
186
+ 2. Uses `ImageLoader` to fetch the image(s)
187
+ 3. Reads EXIF data to handle image orientation
188
+ 4. Calculates dimensions based on size config
189
+ 5. Triggers `canrecord` when image(s) are loaded
190
+
191
+ **Key characteristics**:
192
+ - Can process a single image or a sequence
193
+ - Handles EXIF orientation automatically
194
+ - `ended()` returns true after all images are processed
195
+ - Used internally by `decodeSingle()`
196
+
197
+ **Configuration example (single image)**:
198
+ ```javascript
199
+ inputStream: {
200
+ type: 'ImageStream',
201
+ src: '/path/to/barcode.jpg',
202
+ sequence: false
203
+ }
204
+ ```
205
+
206
+ **Configuration example (image sequence)**:
207
+ ```javascript
208
+ inputStream: {
209
+ type: 'ImageStream',
210
+ src: '/path/to/images/img_%d.jpg', // %d is replaced with frame number
211
+ sequence: true,
212
+ length: 10 // Number of images
213
+ }
214
+ ```
215
+
216
+ ## Race Conditions and Async Behavior {#race-conditions}
217
+
218
+ Because initialization involves async operations (camera access, file loading), race conditions can occur if:
219
+
220
+ 1. **`stop()` is called during `init()`**: The `canrecord` event may fire after `stop()` has begun cleanup. Quagga2 handles this with an `initAborted` flag.
221
+
222
+ 2. **React StrictMode double-invocation**: StrictMode mounts, unmounts, and remounts components, causing rapid `init() → stop() → init()` sequences.
223
+
224
+ 3. **Component unmounting before camera ready**: User navigates away before `getUserMedia()` resolves.
225
+
226
+ **Best practices to avoid issues**:
227
+
228
+ ```javascript
229
+ useLayoutEffect(() => {
230
+ let cancelled = false;
231
+
232
+ Quagga.init(config, (err) => {
233
+ if (cancelled) return; // Ignore if unmounted
234
+ if (err) {
235
+ console.error(err);
236
+ return;
237
+ }
238
+ Quagga.start();
239
+ });
240
+
241
+ return () => {
242
+ cancelled = true;
243
+ Quagga.stop();
244
+ };
245
+ }, []);
246
+ ```
247
+
248
+ ## Source Code {#source-code}
249
+
250
+ The input stream system is implemented in:
251
+
252
+ - `src/input/input_stream/input_stream_browser.ts` - Browser stream implementations
253
+ - `src/input/input_stream/input_stream.ts` - Node.js stream implementation
254
+ - `src/input/input_stream/input_stream.d.ts` - TypeScript interface
255
+ - `src/quagga/setupInputStream.ts` - Stream factory selection
256
+ - `src/input/camera_access.ts` - Camera permission handling
257
+ - `src/input/frame_grabber.js` - Frame extraction for Node.js (uses ndarray)
258
+ - `src/input/frame_grabber_browser.js` - Frame extraction for browsers (uses canvas)
259
+
260
+ > **Note**: Webpack replaces `frame_grabber.js` with `frame_grabber_browser.js` when building the browser bundle. The Node.js version uses `ndarray` for image manipulation, while the browser version uses the Canvas API.
261
+
262
+ ## Related Reading {#related-reading}
263
+
264
+ - [How Barcode Localization Works](how-barcode-localization-works.md) - What happens after frames are grabbed
265
+ - [Camera Access Reference](../reference/camera-access.md) - Camera configuration options
266
+ - [Configuration Reference](../reference/configuration.md) - Full config documentation
267
+
268
+ ---
269
+
270
+ [← Back to Explanation Index](index.md)
@@ -0,0 +1,213 @@
1
+ # Getting Started with Quagga2 {#getting-started}
2
+
3
+ This guide will help you install Quagga2 and get your first barcode scanner running quickly.
4
+
5
+ ## What is Quagga2? {#what-is-quagga2}
6
+
7
+ Quagga2 is a JavaScript barcode scanner library that works in both browsers and Node.js. It can:
8
+
9
+ - **Scan barcodes in real-time** using your device's camera
10
+ - **Decode barcodes from images** (photos, screenshots, etc.)
11
+ - **Support multiple formats**: EAN, CODE 128, CODE 39, EAN 8, UPC-A, UPC-C, I2of5, 2of5, CODE 93, CODE 32, and CODABAR
12
+ - **Work offline** - all processing happens in the browser/Node.js, no server required
13
+
14
+ Unlike some libraries, Quagga2 includes a barcode **locator** that can find and decode barcodes regardless of their rotation or scale in the image.
15
+
16
+ ## Installation {#installation}
17
+
18
+ ### Using NPM (Recommended) {#using-npm}
19
+
20
+ ```bash
21
+ npm install --save @ericblade/quagga2
22
+ ```
23
+
24
+ Then import it in your project:
25
+
26
+ ```javascript
27
+ // ES6 modules
28
+ import Quagga from '@ericblade/quagga2';
29
+
30
+ // CommonJS (important: note the .default)
31
+ const Quagga = require('@ericblade/quagga2').default;
32
+ ```
33
+
34
+ ### Using CDN (Script Tag) {#using-cdn}
35
+
36
+ Add one of these script tags to your HTML:
37
+
38
+ **Unminified version** (useful for development):
39
+
40
+ ```html
41
+ <script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2/dist/quagga.js"></script>
42
+ ```
43
+
44
+ **Minified version** (recommended for production):
45
+
46
+ ```html
47
+ <script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2/dist/quagga.min.js"></script>
48
+ ```
49
+
50
+ **Specific version** (recommended to avoid breaking changes):
51
+
52
+ ```html
53
+ <script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2@1.8.4/dist/quagga.min.js"></script>
54
+ ```
55
+
56
+ The script tag exposes the library globally as `Quagga`.
57
+
58
+ ## Basic Usage - Live Camera Scanning {#live-camera-scanning}
59
+
60
+ Here's a minimal example to scan barcodes using your device's camera:
61
+
62
+ ### HTML {#html-example}
63
+
64
+ ```html
65
+ <!DOCTYPE html>
66
+ <html>
67
+ <head>
68
+ <meta charset="utf-8">
69
+ <title>Quagga2 Barcode Scanner</title>
70
+ </head>
71
+ <body>
72
+ <div id="scanner-container"></div>
73
+ <script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2/dist/quagga.min.js"></script>
74
+ <script src="app.js"></script>
75
+ </body>
76
+ </html>
77
+ ```
78
+
79
+ ### JavaScript (app.js) {#javascript-example}
80
+
81
+ ```javascript
82
+ Quagga.init({
83
+ inputStream: {
84
+ type: "LiveStream",
85
+ target: document.querySelector('#scanner-container')
86
+ },
87
+ decoder: {
88
+ readers: ["code_128_reader"]
89
+ }
90
+ }, function(err) {
91
+ if (err) {
92
+ console.error(err);
93
+ return;
94
+ }
95
+ console.log("Initialization finished. Ready to start");
96
+ Quagga.start();
97
+ });
98
+
99
+ Quagga.onDetected(function(result) {
100
+ const code = result.codeResult.code;
101
+ console.log("Barcode detected:", code);
102
+ alert("Found barcode: " + code);
103
+ });
104
+ ```
105
+
106
+ That's it! This will:
107
+
108
+ 1. Request camera access
109
+ 2. Display the camera feed in `#scanner-container`
110
+ 3. Continuously scan for CODE 128 barcodes
111
+ 4. Alert you when a barcode is detected
112
+
113
+ ## Basic Usage - Static Image Scanning {#static-image-scanning}
114
+
115
+ To decode a barcode from an existing image:
116
+
117
+ ```javascript
118
+ Quagga.decodeSingle({
119
+ src: "path/to/your/image.jpg",
120
+ decoder: {
121
+ readers: ["code_128_reader"]
122
+ }
123
+ // Note: Images are scaled to 800px (longest side) by default.
124
+ // See inputStream.size in the Configuration Reference for details.
125
+ }, function(result) {
126
+ if (result && result.codeResult) {
127
+ console.log("Barcode found:", result.codeResult.code);
128
+ } else {
129
+ console.log("No barcode found");
130
+ }
131
+ });
132
+ ```
133
+
134
+ ## Important Notes {#important-notes}
135
+
136
+ ### HTTPS Required {#https-required}
137
+
138
+ For security reasons, browsers require **HTTPS** to access the camera, except on `localhost`. If you host your app on a domain, you must use `https://`.
139
+
140
+ ### Browser Compatibility {#browser-compatibility}
141
+
142
+ Quagga2 works in modern browsers that support:
143
+
144
+ - Canvas API
145
+ - Typed Arrays
146
+ - MediaDevices API (for camera access)
147
+
148
+ See the [Browser Support](reference/browser-support.md) page for detailed compatibility information.
149
+
150
+ ### Polyfill Recommendation {#polyfill-recommendation}
151
+
152
+ Different browsers implement camera APIs differently. We recommend including [webrtc-adapter](https://github.com/webrtc/adapter) for better compatibility:
153
+
154
+ ```html
155
+ <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
156
+ ```
157
+
158
+ ## Next Steps {#next-steps}
159
+
160
+ Now that you have the basics working:
161
+
162
+ - **[Try a complete tutorial](tutorials/first-scan.md)** - Build a working barcode scanner step-by-step
163
+ - **[Learn about configuration options](reference/configuration.md)** - Customize behavior
164
+ - **[Explore supported barcode types](reference/readers.md)** - Enable different formats
165
+ - **[Check out live examples](https://serratus.github.io/quaggaJS/examples)** - See Quagga2 in action
166
+
167
+ ## Common Issues {#common-issues}
168
+
169
+ ### Camera Permission Denied {#camera-permission-denied}
170
+
171
+ If the user denies camera access, the `init` callback will receive an error. Always handle this gracefully:
172
+
173
+ ```javascript
174
+ Quagga.init(config, function(err) {
175
+ if (err) {
176
+ if (err.name === 'NotAllowedError') {
177
+ alert('Please allow camera access to scan barcodes');
178
+ }
179
+ console.error(err);
180
+ return;
181
+ }
182
+ Quagga.start();
183
+ });
184
+ ```
185
+
186
+ ### Camera Not Found {#camera-not-found}
187
+
188
+ Some devices don't have a camera (desktops, VMs). Check for camera availability:
189
+
190
+ ```javascript
191
+ if (navigator.mediaDevices && typeof navigator.mediaDevices.getUserMedia === 'function') {
192
+ // Camera API available
193
+ Quagga.init(config, callback);
194
+ } else {
195
+ // Fallback to file upload
196
+ alert('Camera not available, please upload an image');
197
+ }
198
+ ```
199
+
200
+ ### No Barcode Detected {#no-barcode-detected}
201
+
202
+ If Quagga2 isn't detecting your barcode:
203
+
204
+ - Make sure you've enabled the correct reader (e.g., `ean_reader` for EAN-13)
205
+ - Ensure good lighting
206
+ - Try holding the barcode steady and filling most of the camera view
207
+ - See [How to Handle Difficult Barcodes](how-to-guides/handle-difficult-barcodes.md)
208
+
209
+ ## Getting Help {#getting-help}
210
+
211
+ - **[GitHub Issues](https://github.com/ericblade/quagga2/issues)** - Report bugs or request features
212
+ - **[Gitter Chat](https://gitter.im/quaggaJS/Lobby)** - Ask questions and get help from the community
213
+ - **[API Documentation](reference/api.md)** - Complete API reference
@@ -0,0 +1,79 @@
1
+ # Configure Barcode Readers {#configure-readers}
2
+
3
+ This guide explains how to configure which barcode formats Quagga2 will detect.
4
+
5
+ ## Basic Configuration {#basic-configuration}
6
+
7
+ Specify readers in the `decoder.readers` array:
8
+
9
+ ```javascript
10
+ Quagga.init({
11
+ decoder: {
12
+ readers: ["code_128_reader", "ean_reader"]
13
+ }
14
+ });
15
+ ```
16
+
17
+ ## Available Readers {#available-readers}
18
+
19
+ | Reader | Format | Common Uses |
20
+ |--------|--------|-------------|
21
+ | `code_128_reader` | Code 128 | Shipping, packaging |
22
+ | `ean_reader` | EAN-13 | Retail products |
23
+ | `ean_8_reader` | EAN-8 | Small products |
24
+ | `upc_reader` | UPC-A | North American retail |
25
+ | `upc_e_reader` | UPC-E | Small products |
26
+ | `code_39_reader` | Code 39 | Industrial |
27
+ | `code_39_vin_reader` | Code 39 VIN | Vehicle identification |
28
+ | `codabar_reader` | Codabar | Libraries, blood banks |
29
+ | `i2of5_reader` | Interleaved 2 of 5 | Warehouse |
30
+ | `2of5_reader` | Standard 2 of 5 | Industrial |
31
+ | `code_93_reader` | Code 93 | Logistics |
32
+ | `code_32_reader` | Code 32 | Italian pharmaceuticals |
33
+
34
+ ## Reader Priority {#reader-priority}
35
+
36
+ Readers are processed in order. Put most likely formats first:
37
+
38
+ ```javascript
39
+ decoder: {
40
+ readers: [
41
+ "ean_reader", // Most common - checked first
42
+ "upc_reader", // Second most common
43
+ "code_128_reader" // Fallback
44
+ ]
45
+ }
46
+ ```
47
+
48
+ ## EAN Supplements {#ean-supplements}
49
+
50
+ To read EAN-2 or EAN-5 extension supplements:
51
+
52
+ ```javascript
53
+ decoder: {
54
+ readers: [
55
+ "ean_reader", // Regular EAN without supplements
56
+ {
57
+ format: "ean_reader",
58
+ config: {
59
+ supplements: ["ean_5_reader", "ean_2_reader"]
60
+ }
61
+ }
62
+ ]
63
+ }
64
+ ```
65
+
66
+ ## Best Practices {#best-practices}
67
+
68
+ 1. **Only enable needed readers** - More readers = slower performance
69
+ 2. **Order by frequency** - Put most common formats first
70
+ 3. **Test thoroughly** - Some formats can conflict
71
+
72
+ ## Related {#related}
73
+
74
+ - [Supported Barcode Types](../reference/readers.md) - Complete reader documentation
75
+ - [Configuration Reference](../reference/configuration.md) - All configuration options
76
+
77
+ ---
78
+
79
+ [← Back to How-To Guides](index.md)