1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
// Copyright 2016 Drew Short <drew@sothr.com>.
//
// Licensed under the MIT license<LICENSE-MIT or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed except according to those terms.

// Enable nightly features for extra testing behind the bench feature
#![cfg_attr(feature = "bench", feature(test))]

extern crate image;
extern crate libc;
extern crate rustc_serialize;
#[cfg(feature = "bench")]
extern crate test;

use std::ffi::CStr;
use std::path::Path;

use cache::Cache;

pub mod cache;
pub mod hash;

#[repr(C)]
pub struct PIHash<'a> {
    cache: Option<Cache<'a>>,
}

impl<'a> PIHash<'a> {
    /**
     * Create a new pihash library, and initialize a cache of a path is passed.
     * If none is passed then no cache is initialized or used with the library
     */
    pub fn new(cache_path: Option<&'a str>) -> PIHash<'a> {
        match cache_path {
            Some(path) => {
                let cache = Cache {
                    cache_dir: path,
                    use_cache: true,
                };
                match cache.init() {
                    Ok(_) => PIHash { cache: Some(cache) },
                    Err(e) => {
                        println!("Error creating library with cache: {}", e);
                        PIHash { cache: None }
                    }
                }
            }
            None => PIHash { cache: None },
        }
    }

    pub fn get_perceptual_hash(
        &self,
        path: &Path,
        precision: &hash::Precision,
        hash_type: &hash::HashType,
    ) -> u64 {
        hash::get_perceptual_hash(&path, &precision, &hash_type, &self.cache)
    }

    pub fn get_phashes(&self, path: &'a Path) -> hash::PerceptualHashes {
        hash::get_perceptual_hashes(&path, &hash::Precision::Medium, &self.cache)
    }

    pub fn get_ahash(&self, path: &Path) -> u64 {
        hash::get_perceptual_hash(
            &path,
            &hash::Precision::Medium,
            &hash::HashType::AHash,
            &self.cache,
        )
    }

    pub fn get_dhash(&self, path: &Path) -> u64 {
        hash::get_perceptual_hash(
            &path,
            &hash::Precision::Medium,
            &hash::HashType::DHash,
            &self.cache,
        )
    }

    pub fn get_phash(&self, path: &Path) -> u64 {
        hash::get_perceptual_hash(
            &path,
            &hash::Precision::Medium,
            &hash::HashType::PHash,
            &self.cache,
        )
    }
}

/**
 * Get the Hamming Distance between two hashes.
 * Represents the absolute difference between two numbers.
 */
pub fn get_hamming_distance(hash1: u64, hash2: u64) -> u64 {
    hash::calculate_hamming_distance(hash1, hash2)
}

// External proxies for the get_*hash methods //

#[no_mangle]
pub extern "C" fn ext_init(cache_path_char: *const libc::c_char) -> *const libc::c_void {
    unsafe {
        let path_cstr = CStr::from_ptr(cache_path_char);
        let path_str = match path_cstr.to_str() {
            Ok(path) => Some(path),
            Err(_) => None,
        };
        // println!("Created new lib, with cache at {}", path_str.unwrap());
        let lib = Box::new(PIHash::new(path_str));
        let ptr = Box::into_raw(lib) as *mut libc::c_void;
        ptr
    }
}

#[no_mangle]
pub extern "C" fn ext_free(raw_lib: *const libc::c_void) {
    unsafe {
        drop(Box::from_raw(raw_lib as *mut PIHash));
    }
}

#[no_mangle]
pub extern "C" fn ext_get_ahash(lib: &PIHash, path_char: *const libc::c_char) -> libc::uint64_t {
    unsafe {
        let path_str = CStr::from_ptr(path_char);
        let image_path = match path_str.to_str() {
            Ok(result) => result,
            Err(e) => {
                println!(
                    "Error: {}. Unable to parse '{}'",
                    e,
                    to_hex_string(path_str.to_bytes())
                );
                panic!("Unable to parse path")
            }
        };
        let path = Path::new(&image_path);
        lib.get_ahash(path)
    }
}

#[no_mangle]
pub extern "C" fn ext_get_dhash(lib: &PIHash, path_char: *const libc::c_char) -> libc::uint64_t {
    unsafe {
        let path_str = CStr::from_ptr(path_char);
        let image_path = match path_str.to_str() {
            Ok(result) => result,
            Err(e) => {
                println!(
                    "Error: {}. Unable to parse '{}'",
                    e,
                    to_hex_string(path_str.to_bytes())
                );
                panic!("Unable to parse path")
            }
        };
        let path = Path::new(&image_path);
        lib.get_dhash(path)
    }
}

#[no_mangle]
pub extern "C" fn ext_get_phash(lib: &PIHash, path_char: *const libc::c_char) -> libc::uint64_t {
    unsafe {
        let path_str = CStr::from_ptr(path_char);
        let image_path = match path_str.to_str() {
            Ok(result) => result,
            Err(e) => {
                println!(
                    "Error: {}. Unable to parse '{}'",
                    e,
                    to_hex_string(path_str.to_bytes())
                );
                panic!("Unable to parse path")
            }
        };
        let path = Path::new(&image_path);
        lib.get_phash(path)
    }
}

#[repr(C)]
pub struct PIHashes {
    ahash: libc::uint64_t,
    dhash: libc::uint64_t,
    phash: libc::uint64_t,
}

#[no_mangle]
pub extern "C" fn ext_get_phashes(lib: &PIHash, path_char: *const libc::c_char) -> *mut PIHashes {
    unsafe {
        let path_str = CStr::from_ptr(path_char);
        let image_path = match path_str.to_str() {
            Ok(result) => result,
            Err(e) => {
                println!(
                    "Error: {}. Unable to parse '{}'",
                    e,
                    to_hex_string(path_str.to_bytes())
                );
                panic!("Unable to parse path")
            }
        };
        let path = Path::new(&image_path);
        let phashes = lib.get_phashes(path);
        Box::into_raw(Box::new(PIHashes {
            ahash: phashes.ahash,
            dhash: phashes.dhash,
            phash: phashes.phash,
        }))
    }
}

#[no_mangle]
pub extern "C" fn ext_free_phashes(raw_phashes: *const libc::c_void) {
    unsafe {
        drop(Box::from_raw(raw_phashes as *mut PIHashes));
    }
}

fn to_hex_string(bytes: &[u8]) -> String {
    println!("length: {}", bytes.len());
    let mut strs: Vec<String> = Vec::new();
    for byte in bytes {
        // println!("{:02x}", byte);
        strs.push(format!("{:02x}", byte));
    }
    strs.join("\\x")
}

// Module for the tests
//
#[cfg(test)]
mod tests {
    use std::fs;
    use std::path::Path;

    use cache;
    use hash;

    #[cfg(feature = "bench")]
    use super::test::Bencher;
    use super::PIHash;

    #[test]
    fn test_can_get_test_images() {
        let paths = fs::read_dir(&Path::new("./test_images")).unwrap();
        let mut num_paths = 0;
        for path in paths {
            let orig_path = path.unwrap().path();
            let ext = Path::new(&orig_path).extension();
            match ext {
                Some(_) => {
                    if ext.unwrap() == "jpg" {
                        num_paths += 1;
                        println!("Is a image {}: {:?}", num_paths, orig_path);
                    }
                }
                _ => {
                    println!("Not an image: {:?}", orig_path);
                    continue;
                }
            }
            // println!("Name: {}", path.unwrap().path().display())
        }
        // Currently 12 images in the test images directory
        assert_eq!(num_paths, 12);
    }

    /**
     * Updated test function. Assumes 3 images to a set and no hamming distances.
     * We don't need to confirm that the hamming distance calculation works in these tests.
     */
    fn test_imageset_hash(
        hash_type: hash::HashType,
        hash_precision: hash::Precision,
        max_hamming_distance: u64,
        image_paths: [&Path; 3],
        image_hashes: [u64; 3],
        lib: &PIHash,
    ) {
        let mut hashes: [u64; 3] = [0; 3];
        for index in 0..image_paths.len() {
            let image_path = image_paths[index];
            let calculated_hash = lib.get_perceptual_hash(&image_path, &hash_precision, &hash_type);
            println!(
                "[{}] Image hashes for [{}] expected: [{}] actual: [{}]",
                hash_type,
                image_path.to_str().unwrap(),
                image_hashes[index],
                calculated_hash
            );
            assert_eq!(calculated_hash, image_hashes[index]);
            hashes[index] = calculated_hash;
        }

        for index in 0..hashes.len() {
            for index2 in 0..hashes.len() {
                if index == index2 {
                    continue;
                } else {
                    let distance = hash::calculate_hamming_distance(hashes[index], hashes[index2]);
                    println!("Hashes [{}] and [{}] have a hamming distance of [{}] of a max allowed distance of [{}]",
                             hashes[index],
                             hashes[index2],
                             distance,
                             max_hamming_distance);
                    assert!(distance <= max_hamming_distance);
                }
            }
        }
    }

    #[test]
    fn test_confirm_ahash_results() {
        // Prep_library
        let lib = PIHash::new(Some(cache::DEFAULT_CACHE_DIR));

        // Sample_01 tests
        let sample_01_images: [&Path; 3] = [
            &Path::new("./test_images/sample_01_large.jpg"),
            &Path::new("./test_images/sample_01_medium.jpg"),
            &Path::new("./test_images/sample_01_small.jpg"),
        ];
        let sample_01_hashes: [u64; 3] = [857051991849750, 857051991849750, 857051991849750];
        test_imageset_hash(
            hash::HashType::AHash,
            hash::Precision::Medium,
            1u64,
            sample_01_images,
            sample_01_hashes,
            &lib,
        );

        // Sample_02 tests
        let sample_02_images: [&Path; 3] = [
            &Path::new("./test_images/sample_02_large.jpg"),
            &Path::new("./test_images/sample_02_medium.jpg"),
            &Path::new("./test_images/sample_02_small.jpg"),
        ];
        let sample_02_hashes: [u64; 3] = [
            18446744073441116160,
            18446744073441116160,
            18446744073441116160,
        ];
        test_imageset_hash(
            hash::HashType::AHash,
            hash::Precision::Medium,
            3u64,
            sample_02_images,
            sample_02_hashes,
            &lib,
        );

        // Sample_03 tests
        let sample_03_images: [&Path; 3] = [
            &Path::new("./test_images/sample_03_large.jpg"),
            &Path::new("./test_images/sample_03_medium.jpg"),
            &Path::new("./test_images/sample_03_small.jpg"),
        ];
        let sample_03_hashes: [u64; 3] =
            [135670932300497406, 135670932300497406, 135670932300497406];
        test_imageset_hash(
            hash::HashType::AHash,
            hash::Precision::Medium,
            1u64,
            sample_03_images,
            sample_03_hashes,
            &lib,
        );

        // Sample_04 tests
        let sample_04_images: [&Path; 3] = [
            &Path::new("./test_images/sample_04_large.jpg"),
            &Path::new("./test_images/sample_04_medium.jpg"),
            &Path::new("./test_images/sample_04_small.jpg"),
        ];
        let sample_04_hashes: [u64; 3] = [
            18446460933225054208,
            18446460933225054208,
            18446460933225054208,
        ];
        test_imageset_hash(
            hash::HashType::AHash,
            hash::Precision::Medium,
            0u64,
            sample_04_images,
            sample_04_hashes,
            &lib,
        );

        // Clean_Cache
        // super::teardown();
    }

    #[test]
    fn test_confirm_dhash_results() {
        // Prep_library
        let lib = PIHash::new(Some(cache::DEFAULT_CACHE_DIR));

        // Sample_01 tests
        let sample_01_images: [&Path; 3] = [
            &Path::new("./test_images/sample_01_large.jpg"),
            &Path::new("./test_images/sample_01_medium.jpg"),
            &Path::new("./test_images/sample_01_small.jpg"),
        ];
        let sample_01_hashes: [u64; 3] = [
            3404580580803739582,
            3404580580803739582,
            3404580580803739582,
        ];
        test_imageset_hash(
            hash::HashType::DHash,
            hash::Precision::Medium,
            0u64,
            sample_01_images,
            sample_01_hashes,
            &lib,
        );

        // Sample_02 tests
        let sample_02_images: [&Path; 3] = [
            &Path::new("./test_images/sample_02_large.jpg"),
            &Path::new("./test_images/sample_02_medium.jpg"),
            &Path::new("./test_images/sample_02_small.jpg"),
        ];
        let sample_02_hashes: [u64; 3] = [
            14726771606135242753,
            14726771606135242753,
            14726771606135242753,
        ];
        test_imageset_hash(
            hash::HashType::DHash,
            hash::Precision::Medium,
            0u64,
            sample_02_images,
            sample_02_hashes,
            &lib,
        );

        // Sample_03 tests
        let sample_03_images: [&Path; 3] = [
            &Path::new("./test_images/sample_03_large.jpg"),
            &Path::new("./test_images/sample_03_medium.jpg"),
            &Path::new("./test_images/sample_03_small.jpg"),
        ];
        let sample_03_hashes: [u64; 3] =
            [144115181601817086, 144115181601817086, 144115181601817086];
        test_imageset_hash(
            hash::HashType::DHash,
            hash::Precision::Medium,
            0u64,
            sample_03_images,
            sample_03_hashes,
            &lib,
        );

        // Sample_04 tests
        let sample_04_images: [&Path; 3] = [
            &Path::new("./test_images/sample_04_large.jpg"),
            &Path::new("./test_images/sample_04_medium.jpg"),
            &Path::new("./test_images/sample_04_small.jpg"),
        ];
        let sample_04_hashes: [u64; 3] = [
            18374262188442386433,
            18374262188442386433,
            18374262188442386433,
        ];
        test_imageset_hash(
            hash::HashType::DHash,
            hash::Precision::Medium,
            1u64,
            sample_04_images,
            sample_04_hashes,
            &lib,
        );

        // Clean_Cache
        // super::teardown();
    }

    #[test]
    fn test_confirm_phash_results() {
        // Prep_library
        let lib = PIHash::new(Some(cache::DEFAULT_CACHE_DIR));

        // Sample_01 tests
        let sample_01_images: [&Path; 3] = [
            &Path::new("./test_images/sample_01_large.jpg"),
            &Path::new("./test_images/sample_01_medium.jpg"),
            &Path::new("./test_images/sample_01_small.jpg"),
        ];
        let sample_01_hashes: [u64; 3] = [72357778504597504, 72357778504597504, 72357778504597504];
        test_imageset_hash(
            hash::HashType::PHash,
            hash::Precision::Medium,
            1u64,
            sample_01_images,
            sample_01_hashes,
            &lib,
        );

        // Sample_02 tests
        let sample_02_images: [&Path; 3] = [
            &Path::new("./test_images/sample_02_large.jpg"),
            &Path::new("./test_images/sample_02_medium.jpg"),
            &Path::new("./test_images/sample_02_small.jpg"),
        ];
        let sample_02_hashes: [u64; 3] = [
            5332332327550844928,
            5332332327550844928,
            5332332327550844928,
        ];
        test_imageset_hash(
            hash::HashType::PHash,
            hash::Precision::Medium,
            1u64,
            sample_02_images,
            sample_02_hashes,
            &lib,
        );

        // Sample_03 tests
        let sample_03_images: [&Path; 3] = [
            &Path::new("./test_images/sample_03_large.jpg"),
            &Path::new("./test_images/sample_03_medium.jpg"),
            &Path::new("./test_images/sample_03_small.jpg"),
        ];
        let sample_03_hashes: [u64; 3] = [
            6917529027641081856,
            6917529027641081856,
            6917529027641081856,
        ];
        test_imageset_hash(
            hash::HashType::PHash,
            hash::Precision::Medium,
            0u64,
            sample_03_images,
            sample_03_hashes,
            &lib,
        );

        // Sample_04 tests
        let sample_04_images: [&Path; 3] = [
            &Path::new("./test_images/sample_04_large.jpg"),
            &Path::new("./test_images/sample_04_medium.jpg"),
            &Path::new("./test_images/sample_04_small.jpg"),
        ];
        let sample_04_hashes: [u64; 3] = [
            10997931646002397184,
            10997931646002397184,
            10997931646002397184,
        ];
        test_imageset_hash(
            hash::HashType::PHash,
            hash::Precision::Medium,
            3u64,
            sample_04_images,
            sample_04_hashes,
            &lib,
        );

        // Clean_Cache
        // super::teardown();
    }

    #[cfg(feature = "bench")]
    #[bench]
    fn bench_with_cache(bench: &mut Bencher) -> () {
        // Prep_library
        let lib = PIHash::new(Some(cache::DEFAULT_CACHE_DIR));

        // Setup the caches to make sure we're good to properly bench
        // All phashes so that the matricies are pulled from cache as well
        lib.get_perceptual_hash(
            &Path::new("./test_images/sample_01_large.jpg"),
            &hash::Precision::Medium,
            &hash::HashType::PHash,
        );

        bench.iter(|| {
            // Sample_01 Bench
            lib.get_perceptual_hash(
                &Path::new("./test_images/sample_01_large.jpg"),
                &hash::Precision::Medium,
                &hash::HashType::PHash,
            );
        })
    }

    #[cfg(feature = "bench")]
    #[bench]
    fn bench_without_cache(bench: &mut Bencher) -> () {
        // Prep_library
        let lib = PIHash::new(None);

        bench.iter(|| {
            // Sample_01 Bench
            lib.get_perceptual_hash(
                &Path::new("./test_images/sample_01_large.jpg"),
                &hash::Precision::Medium,
                &hash::HashType::PHash,
            );
        })
    }
}