1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
/*!
High-level and low-level ZBar binding for the Rust language.

## Compilation

To compile this crate, you need to compile the ZBar library first. You can install ZBar in your operating system, or in somewhere in your file system. As for the latter, you need to set the following environment variables to link the ZBar library:

* `ZBAR_LIB_DIRS`: The directories of library files, like `-L`. Use `:` to separate.
* `ZBAR_LIBS`: The library names that you want to link, like `-l`. Use `:` to separate. Typically, it is **iconv:zbar**.
* `ZBAR_INCLUDE_DIRS`: The directories of header files, like `-i`. Use `:` to separate.

## Examples

```rust,ignore
extern crate zbar_rust;
extern crate image;

use zbar_rust::ZBarImageScanner;

use image::GenericImageView;

let img = image::open(INPUT_IMAGE_PATH).unwrap();

let (width, height) = img.dimensions();

let luma_img = img.to_luma();

let luma_img_data: Vec<u8> = luma_img.to_vec();

let mut scanner = ZBarImageScanner::new();

let results = scanner.scan_y800(&luma_img_data, width, height).unwrap();

for result in results {
    println!("{}", String::from_utf8(result.data).unwrap())
}
```

More examples are in the `examples` folder.
*/

#![allow(clippy::enum_clike_unportable_variant)]

#[macro_use]
extern crate enum_ordinalize;

extern crate libc;

use std::ptr;

use libc::{c_char, c_int, c_uint, c_ulong, c_void};

#[derive(Debug, Copy, Clone, Eq, PartialEq, Ordinalize)]
#[repr(isize)]
pub enum ZBarColor {
    ZBarSpace = 0,
    ZBarBar   = 1,
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Ordinalize)]
#[repr(isize)]
pub enum ZBarSymbolType {
    ZBarNone       = 0,
    ZBarPartial    = 1,
    ZBarEAN2       = 2,
    ZBarEAN5       = 5,
    ZBarEAN8       = 8,
    ZBarUPCE       = 9,
    ZBarISBN10     = 10,
    ZBarUPCA       = 12,
    ZBarEAN13      = 13,
    ZBarISBN13     = 14,
    ZBarComposite  = 15,
    ZBarI25        = 25,
    ZBarDataBar    = 34,
    ZBarDataBarExp = 35,
    ZBarCodeBar    = 38,
    ZBarCode39     = 39,
    ZBarPDF417     = 57,
    ZBarQRCode     = 64,
    ZBarCode93     = 93,
    ZBarCode128    = 128,
    ZBarSymbol     = 0x00ff,
    ZBarAddOn2     = 0x0200,
    ZBarAddOn5     = 0x0500,
    ZBarAddOn      = 0x0700,
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Ordinalize)]
#[repr(isize)]
pub enum ZBarOrientation {
    ZBarOrientUnknown = -1,
    ZBarOrientUp      = 0,
    ZBarOrientRight   = 1,
    ZBarOrientDown    = 2,
    ZBarOrientLeft    = 3,
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Ordinalize)]
#[repr(isize)]
pub enum ZBarError {
    ZBarOK,
    ZBarErrNoMem,
    ZBarErrInternal,
    ZBarErrUnsupported,
    ZBarErrInvalid,
    ZBarErrSystem,
    ZBarErrLocking,
    ZBarErrBudy,
    ZBarErrXDisplay,
    ZBarErrXProto,
    ZBarErrClosed,
    ZBarErrWinAPI,
    ZBarErrNum,
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Ordinalize)]
#[repr(isize)]
pub enum ZBarConfig {
    ZBarCfgEnable    = 0,
    ZBarCfgAddCheck  = 1,
    ZBarCfgEmitCheck = 2,
    ZBarCfgASCII     = 3,
    ZBarCfgNum       = 4,
    ZBarCfgMinLen    = 0x20,
    ZBarCfgMaxLen    = 0x21,
    ZBarCfgPosition  = 0x80,
    ZBarCfgXDensity  = 0x100,
    ZBarCfgYDensity  = 0x101,
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Ordinalize)]
#[repr(isize)]
pub enum ZBarModifier {
    ZBarModGS1,
    ZBarModAIM,
    ZBarModNum,
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Ordinalize)]
#[repr(isize)]
pub enum VideoControlType {
    VideoCntlInteger   = 1,
    VideoCntlMenu      = 2,
    VideoCntlButton    = 3,
    VideoCntlInteger64 = 4,
    VideoCntlString    = 5,
    VideoCntlBoolean   = 6,
}

// TODO: ----- General Interface START-----

#[link(name = "zbar")]
extern {
    pub fn zbar_version(major: *mut c_uint, minor: *mut c_uint) -> c_int;
    pub fn zbar_set_verbosity(verbosity: c_int);
}

// TODO: ----- General Interface END-----

// TODO: ----- Image Interface START-----

#[link(name = "zbar")]
extern {
    pub fn zbar_image_create() -> *mut c_void;
    pub fn zbar_image_destroy(image: *mut c_void);
    pub fn zbar_image_ref(image: *mut c_void, refs: c_int);
    pub fn zbar_image_convert(image: *const c_void, format: c_ulong) -> *mut c_void;
    pub fn zbar_image_convert_resize(
        image: *const c_void,
        format: c_ulong,
        width: c_uint,
        height: c_int,
    ) -> *mut c_void;
    pub fn zbar_image_get_format(image: *const c_void) -> c_ulong;
    pub fn zbar_image_get_sequence(image: *const c_void) -> c_uint;
    pub fn zbar_image_get_width(image: *const c_void) -> c_uint;
    pub fn zbar_image_get_height(image: *const c_void) -> c_uint;
    pub fn zbar_image_get_size(image: *const c_void, width: *mut c_uint, height: *mut c_uint);
    pub fn zbar_image_get_crop(
        image: *const c_void,
        x: *mut c_uint,
        y: *mut c_uint,
        width: *mut c_uint,
        height: *mut c_uint,
    );
    pub fn zbar_image_get_data(image: *const c_void) -> *const c_void;
    pub fn zbar_image_get_data_length(image: *const c_void) -> c_ulong;
    pub fn zbar_image_get_symbols(image: *const c_void) -> *const c_void;
    pub fn zbar_image_set_symbols(image: *mut c_void, symbols: *const c_void);
    pub fn zbar_image_first_symbol(image: *const c_void) -> *const c_void;
    pub fn zbar_image_set_format(image: *mut c_void, format: c_ulong);
    pub fn zbar_image_set_sequence(image: *mut c_void, sequence_num: c_ulong);
    pub fn zbar_image_set_size(image: *mut c_void, width: c_ulong, height: c_ulong);
    pub fn zbar_image_set_crop(
        image: *mut c_void,
        x: c_ulong,
        y: c_ulong,
        width: c_ulong,
        height: c_ulong,
    );
    pub fn zbar_image_set_data(
        image: *mut c_void,
        data: *const c_void,
        data_byte_length: c_ulong,
        handler: *mut c_void,
    );
    pub fn zbar_image_free_data(image: *mut c_void);
    pub fn zbar_image_set_userdata(image: *mut c_void, userdata: *const c_void);
    pub fn zbar_image_get_userdata(image: *const c_void) -> *const c_void;
    pub fn zbar_image_write(image: *const c_void, filebase: *const c_char) -> c_uint;
    pub fn zbar_image_read(filename: *mut c_char) -> *const c_void;
}

pub struct ZBarImage {
    image: *mut c_void,
}

impl ZBarImage {
    pub fn new() -> ZBarImage {
        let image = unsafe { zbar_image_create() };

        ZBarImage {
            image,
        }
    }

    pub fn set_format(&mut self, format: u32) {
        unsafe {
            zbar_image_set_format(self.image, c_ulong::from(format));
        }
    }

    pub fn set_size(&mut self, width: u32, height: u32) {
        unsafe {
            zbar_image_set_size(self.image, c_ulong::from(width), c_ulong::from(height));
        }
    }

    pub fn set_ref(&mut self, r: isize) {
        unsafe {
            zbar_image_ref(self.image, r as c_int);
        }
    }

    pub fn destroy(mut self) {
        unsafe {
            zbar_image_destroy(self.image);
            self.image = ptr::null_mut();
        }
    }
}

impl Default for ZBarImage {
    #[inline]
    fn default() -> Self {
        ZBarImage::new()
    }
}

// TODO: ----- Image Interface END-----

// TODO: ----- Symbol Interface START-----

#[link(name = "zbar")]
extern {
    pub fn zbar_symbol_ref(symbol: *const c_void, refs: c_int);
    pub fn zbar_symbol_get_type(symbol: *const c_void) -> c_int;
    pub fn zbar_symbol_get_configs(symbol: *const c_void) -> c_uint;
    pub fn zbar_symbol_get_modifiers(symbol: *const c_void) -> c_uint;
    pub fn zbar_symbol_get_data(symbol: *const c_void) -> *mut c_char;
    pub fn zbar_symbol_get_data_length(symbol: *const c_void) -> c_uint;
    pub fn zbar_symbol_get_quality(symbol: *const c_void) -> c_int;
    pub fn zbar_symbol_get_count(symbol: *const c_void) -> c_int;
    pub fn zbar_symbol_get_loc_size(symbol: *const c_void) -> c_uint;
    pub fn zbar_symbol_get_loc_x(symbol: *const c_void, index: c_uint) -> c_int;
    pub fn zbar_symbol_get_loc_y(symbol: *const c_void, index: c_uint) -> c_int;
    pub fn zbar_symbol_get_orientation(symbol: *const c_void) -> c_int;
    pub fn zbar_symbol_next(symbol: *const c_void) -> *const c_void;
    pub fn zbar_symbol_get_components(symbol: *const c_void) -> *const c_void;
    pub fn zbar_symbol_first_component(symbol: *const c_void) -> *const c_void;
    pub fn zbar_symbol_xml(
        symbol: *const c_void,
        buffer: *mut *mut c_char,
        buflen: *mut c_uint,
    ) -> *mut c_char;
}

// TODO: ----- Symbol Interface END-----

// TODO: ----- Image Scanner Interface START-----

#[link(name = "zbar")]
extern {
    pub fn zbar_image_scanner_create() -> *mut c_void;
    pub fn zbar_image_scanner_destroy(scanner: *mut c_void);
    pub fn zbar_image_scanner_set_data_handler(
        scanner: *mut c_void,
        handler: *const c_void,
        userdata: *const c_void,
    );
    pub fn zbar_image_scanner_set_config(
        scanner: *mut c_void,
        symbology: c_int,
        config: c_int,
        value: c_int,
    ) -> c_int;
    pub fn zbar_image_scanner_parse_config(
        scanner: *mut c_void,
        config_string: *const c_char,
    ) -> c_int;
    pub fn zbar_image_scanner_enable_cache(scanner: *mut c_void, enable: c_int);
    pub fn zbar_image_scanner_recycle_image(scanner: *mut c_void, image: *mut c_void);
    pub fn zbar_image_scanner_get_results(scanner: *const c_void) -> *const c_void;
    pub fn zbar_scan_image(scanner: *mut c_void, image: *mut c_void) -> c_int;
}

#[derive(Debug)]
pub struct ZBarImageScanResult {
    pub symbol_type: ZBarSymbolType,
    pub data: Vec<u8>,
}

pub struct ZBarImageScanner {
    scanner: *mut c_void,
}

impl ZBarImageScanner {
    pub fn new() -> ZBarImageScanner {
        let scanner = unsafe { zbar_image_scanner_create() };

        ZBarImageScanner {
            scanner,
        }
    }

    pub fn set_config(
        &mut self,
        symbology: ZBarSymbolType,
        config: ZBarConfig,
        value: isize,
    ) -> Result<(), &'static str> {
        let result = unsafe {
            zbar_image_scanner_set_config(
                self.scanner,
                symbology.ordinal() as c_int,
                config.ordinal() as c_int,
                value as c_int,
            )
        };
        if result == 0 {
            Ok(())
        } else {
            Err("unsuccessfully")
        }
    }

    pub fn destroy(mut self) {
        unsafe {
            zbar_image_scanner_destroy(self.scanner);
            self.scanner = ptr::null_mut();
        }
    }

    pub fn scan_y800<D: AsRef<[u8]>>(
        &mut self,
        data: D,
        width: u32,
        height: u32,
    ) -> Result<Vec<ZBarImageScanResult>, &'static str> {
        //        let format: u32 = unsafe { transmute([b'Y', b'8', b'0', b'0']) };
        self.scan(data, width, height, 808_466_521)
    }

    pub fn scan_gray<D: AsRef<[u8]>>(
        &mut self,
        data: D,
        width: u32,
        height: u32,
    ) -> Result<Vec<ZBarImageScanResult>, &'static str> {
        //        let format: u32 = unsafe { transmute([b'G', b'R', b'A', b'Y']) };
        self.scan(data, width, height, 1_497_453_127)
    }

    pub fn scan<D: AsRef<[u8]>>(
        &mut self,
        data: D,
        width: u32,
        height: u32,
        format: u32,
    ) -> Result<Vec<ZBarImageScanResult>, &'static str> {
        let data = data.as_ref();

        let mut image = ZBarImage::new();

        image.set_size(width, height);
        image.set_format(format);

        unsafe {
            zbar_image_set_data(
                image.image,
                data.as_ptr() as *const c_void,
                data.len() as c_ulong,
                zbar_image_free_data as *mut c_void,
            );
        }

        let n = unsafe { zbar_scan_image(self.scanner, image.image) };

        if n < 0 {
            return Err("incorrect image");
        }

        let mut result_array = Vec::with_capacity(n as usize);

        let mut symbol = unsafe { zbar_image_first_symbol(image.image) };

        while !symbol.is_null() {
            let symbol_type = unsafe { zbar_symbol_get_type(symbol) };
            let symbol_type = unsafe { ZBarSymbolType::from_ordinal_unsafe(symbol_type as isize) };
            let data = unsafe {
                let data = zbar_symbol_get_data(symbol);
                let data_length = zbar_symbol_get_data_length(symbol) as usize;
                Vec::from_raw_parts(data as *mut u8, data_length, data_length)
            };

            let result = ZBarImageScanResult {
                symbol_type,
                data,
            };

            result_array.push(result);

            symbol = unsafe { zbar_symbol_next(symbol) };
        }

        Ok(result_array)
    }
}

impl Default for ZBarImageScanner {
    #[inline]
    fn default() -> Self {
        ZBarImageScanner::new()
    }
}

impl Drop for ZBarImageScanner {
    fn drop(&mut self) {
        if !self.scanner.is_null() {
            unsafe {
                zbar_image_scanner_destroy(self.scanner);
            }
        }
    }
}
// TODO: ----- Image Scanner Interface END-----