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 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
|
#!/usr/bin/perl -w
# $Id: findimagedupes,v 2.0 2006/09/20 12:45:30 jhnc Exp jhnc $
#
# findimagedupes - Finds visually similar or duplicate images
#
# Copyright 2006 by Jonathan H N Chin <code@jhnc.org>.
#
# This program is free software; you may redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
use strict;
require 5.6.1;
use Cwd qw(realpath);
use DB_File;
use Digest::MD5 qw(md5_hex);
use Getopt::Long;
use File::MimeInfo::Magic;
use File::Temp qw(tempdir tempfile);
use Image::Magick;
use MIME::Base64;
use Pod::Usage;
use Inline
C => 'DATA',
NAME => 'findimagedupes',
DIRECTORY => '/usr/local/lib/findimagedupes';
# ----------------------------------------------------------------------
#
# option parsing
#
use vars qw(
$null
$add
$collection
@debug %debug
@fpdb
$merge
$nocompare
$program
$quiet
$rescan
$script
$threshold
@verbosity
$prune
);
$add = 0;
$quiet = 0;
$threshold = 90;
my %opt;
GetOptions(
'0|null' => \$null,
'a|add' => \$add,
'c|collection=s' => \$collection,
'd|debug=s@' => \@debug,
'f|fingerprints|fp|db=s' => \@fpdb,
'h|?|help' => sub { pod2usage(-verbose => 1) },
'm|merge=s' => \$merge,
'n|no-compare' => \$nocompare,
'p|program=s' => \$program,
'q|quiet' => sub { $quiet++ },
'r|rescan' => \$rescan,
's|script=s' => \$script,
't|threshold=i' => \$threshold,
'v|verbosity=s' => \@verbosity,
'man' => sub { pod2usage(-verbose => 2) },
'prune' => \$prune,
) or pod2usage(-verbose => 0);
# ----------------------------------------------------------------------
my @errors = ();
my @warnings = ();
sub exitvalue {
return(2) if @errors;
return(1) if @warnings;
return(0);
}
sub mkerr { push @errors, join("", @_); }
sub mkwarn { push @warnings, join("", @_); }
sub nqprint { print(@_) unless $quiet; }
sub nqwarn { warn("Warning: ", @_) unless $quiet; }
sub nqdie { nqwarn(@_); die; }
sub nqdie2 { warn("Error: ", @_) if $quiet<2; die; }
sub nqexit { warn("Error: ", @_) if $quiet<2; exit(3); }
my $inFP = 0;
$SIG{SEGV} = sub { die $inFP ? "caught segfault" : ()};
# ----------------------------------------------------------------------
#
# setup
#
my ($verb_fp, $verb_md5);
my $read_input = grep(/^-$/, @ARGV);
# XXX: can we tie these to save memory without breaking hv_iterinit() ?
my (%fpcache, %filelist);
my $image = Image::Magick->new;
for (@debug) { $debug{$_} = 1 }
# ----------------------------------------------------------------------
#
# sanity checks
#
# +----------+
# | warnings |
# +----------+
if ($read_input>1) {
mkwarn("extra occurrences of \"-\" will be ignored");
}
if ($null and !grep(/^-$/, @ARGV)) {
mkwarn("--null has no effect in this context");
}
if ($prune and !@fpdb) {
mkwarn("--prune has no effect in this context");
}
if ($nocompare) {
mkwarn("--program ignored because --no-compare given") if $program;
mkwarn("--script ignored because --no-compare given") if $script;
}
if (@warnings and !$quiet) {
warn( join("\n", map {"Warning: $_"} @warnings), "\n" );
}
# +--------+
# | errors |
# +--------+
if ($collection and -e($collection)) {
mkerr("Output file for --collection exists: $collection");
}
for (@fpdb) {
mkerr("File for --fingerprints does not exist: $_")
unless (-f($_) or (@fpdb==1 and !$merge));
}
if (@fpdb>1 and !$merge) {
mkerr("Require --merge if using multiple fingerprint databases");
}
# XXX: not sure this is true any more
#if (@fpdb<1 and $merge) {
# mkerr("Cannot use --merge unless --fingerprints also specified");
#}
if ($merge and -e($merge)) {
mkerr("Output file for --merge exists: $merge");
}
if ($program) {
if (! -e($program)) {
mkerr("File for --program does not exist: $program");
}
elsif (! -x($program)) {
mkerr("File for --program not executable: $program");
}
}
if ($script and -e($script)) {
mkerr("Output file for --script exists: $script");
}
if ($threshold>100 or $threshold<0) {
mkerr("--threshold takes values between 0 and 100");
}
for (split(",", join(",", @verbosity))) {
/^(fingerprint|fp)$/ && do { $verb_fp = 1; next; };
/^md5$/ && do { $verb_md5 = 1; next; };
mkerr("unknown option to --verbosity: $_");
}
if (@errors) {
exit(exitvalue()) unless $quiet<2;
pod2usage(
-verbose => 0,
-exitval => exitvalue(),
-msg => join("\n", map {"Error: $_"} @errors),
);
}
# +-------------------------------------------------+
# | last chance to abort without altering any files |
# +-------------------------------------------------+
unless (@ARGV>0 or @fpdb or $merge) {
exit(exitvalue()) unless $quiet<2;
warn("Nothing to do!\n") unless @warnings or $quiet;
pod2usage(
-verbose => 0,
-exitval => exitvalue(),
);
}
# ----------------------------------------------------------------------
#
# load fingerprint cache
#
for my $db (@fpdb) {
my %data;
tie(%data, 'DB_File', $db) or nqexit("tie($db): $!\n");
while (my ($file, $fp) = each %data) {
next if ($prune && !-f($file));
if (exists $fpcache{$file}) {
# duplicate fingerprint, force regeneration
delete $fpcache{$file};
}
else {
$fpcache{$file} = $fp;
}
}
untie(%data);
}
# ----------------------------------------------------------------------
#
# build file list
#
my %mergelist;
my $rw = 0;
if ($merge) {
tie(%mergelist, 'DB_File', $merge) or nqexit("tie($merge): $!\n");
%mergelist = %fpcache;
$rw = 1;
}
elsif (@fpdb==1) {
tie(%mergelist, 'DB_File', $fpdb[0]) or nqexit("tie($fpdb[0]): $!\n");
%mergelist = %fpcache if $prune;
$rw = 1;
}
$| = 1;
$/ = "\0" if $null;
for (@ARGV) {
classify($_);
}
untie(%mergelist);
finddupes() unless $nocompare;
exit 0;
# ----------------------------------------------------------------------
sub process_file {
my ($path) = @_;
my $file = realpath($path); # normalize to absolute canonical path
if (!$file) {
nqwarn("skipping bogus file: $path\n");
}
else {
if (!$rescan and $fpcache{$file}) {
$filelist{$file} = $fpcache{$file};
delete $fpcache{$file};
# mergelist has already been set from fpcache
}
else {
my $fp = fingerprint($file);
if ($fp) {
$filelist{$file} = $fp;
$mergelist{$file} = $filelist{$file} if $rw;
}
}
if ($verb_fp) {
if ($filelist{$file}) {
print(encode_base64($filelist{$file}, ""), " $file\n");
}
else {
nqwarn("can't get fingerprint: $file\n");
}
}
if ($verb_md5) {
open(FILE, $file) or nqdie2("open($file): $!\n");
binmode(FILE);
my $digest = Digest::MD5->new->addfile(*FILE)->hexdigest;
if ($digest) {
print("$digest $file\n");
}
else {
nqwarn("can't get md5sum: $file\n");
}
close(FILE);
}
}
}
sub classify {
my ($file) = @_;
if ($file eq "-") {
if ($read_input) {
$read_input = 0;
while (<>) {
chomp;
classify($_);
}
}
else {
# silently ignore any extra occurrences of "-"
# (we already reported them at startup)
}
}
elsif (-d($file) and !-l($file)) {
# don't follow directory symlinks, to prevent looping
while (glob("$file/*")) {
chomp;
process_file($_) if (-f($_)); # no recursing
}
}
elsif (-f($file)) {
# symlinks are okay for normal files
process_file($file);
}
else {
# skip anything else (devices, etc)
nqwarn("skipping file: $file\n");
}
}
# ----------------------------------------------------------------------
sub try {
my ($err) = @_;
if ($err and $err !~ /Warning (315|330):/) {
die("imagemagick problem: $err\n");
}
}
sub fingerprint {
my ($file) = @_;
my $blob;
# imagemagick doesn't always catch output from the programs
# it spawns, so we have to clean up for it...
open(SAVED_OUT, ">&", \*STDOUT) or nqdie2("open(/dev/null): $!");
open(SAVED_ERR, ">&", \*STDERR) or nqdie2("open(/dev/null): $!");
open(STDOUT, ">/dev/null");
open(STDERR, ">/dev/null");
$inFP = 1;
my $result = eval {
if ((mimetype($file)||'') =~ /^(audio|video)/) {
die("not fingerprinting A/V file: $file\n");
}
if (!$image->Ping($file)) {
die("not fingerprinting unknown-type file: $file\n");
}
try $image->Read($file);
if ($#$image<0) {
die("fingerprint: not enough image data for $file");
}
else {
$#$image = 0;
}
try $image->Sample("160x160!");
try $image->Modulate(saturation=>-100);
try $image->Blur(radius=>3,sigma=>99);
try $image->Normalize();
try $image->Equalize();
try $image->Sample("16x16");
try $image->Threshold();
try $image->Set(magick=>'mono');
($blob) = $image->ImageToBlob();
if (!defined($blob)) {
die("This can't happen! undefined blob for: $file\n");
}
};
$inFP = 0;
@$image = ();
open(STDOUT, ">&", \*SAVED_OUT) or nqdie2("open(/dev/null): $!");
open(STDERR, ">&", \*SAVED_ERR) or nqdie2("open(/dev/null): $!");
close(SAVED_OUT);
close(SAVED_ERR);
if (defined $result) {
return $blob;
}
else {
nqwarn($@);
return undef;
}
}
sub finddupes {
my @matches = diffbits(\%fpcache, \%filelist, $threshold, $add);
my (%set, %ptr, %val);
while (@matches) {
my $a = shift(@matches);
my $b = shift(@matches);
my $c = shift(@matches);
$set{$a} = 1;
$set{$b} = 1;
# cf. debian bug #87013
if (!defined($ptr{$a}) and !defined($ptr{$b})) {
$ptr{$a} = $a;
push @{$val{$a}}, $a, $b;
$ptr{$b} = $a;
$#{$val{$b}} = 0;
}
elsif (defined($ptr{$a}) and !defined($ptr{$b})) {
push @{$val{$ptr{$a}}}, $b;
$ptr{$b} = $ptr{$a};
$#{$val{$b}} = 0;
}
elsif (!defined($ptr{$a}) and defined($ptr{$b})) {
push @{$val{$ptr{$b}}}, $a;
$ptr{$a} = $ptr{$b};
$#{$val{$a}} = 0;
}
elsif ($ptr{$a} ne $ptr{$b}) {
my $valptrb = $val{$ptr{$b}};
push @{$val{$ptr{$a}}}, @{$valptrb};
for my $bkey (@{$valptrb}) {
$ptr{$bkey} = $ptr{$a};
}
$#$valptrb = 0;
# else $val{$a} is $val{$b} already
}
}
my $cnt = 0;
for my $k (keys %filelist, keys %fpcache) {
$set{$cnt} = $k if defined $set{$cnt};
$cnt++;
}
if ($script) {
open(COMMANDS, "> $script") or nqdie2("open(> $script): $!\n");
}
else {
open(COMMANDS, "| /bin/sh") or nqdie2("open(| /bin/sh): $!\n");
}
select(COMMANDS);
unless ($program) {
$program = 'VIEW';
print <<'EOD';
#!/bin/sh
VIEW(){
echo "$@"
}
EOD
}
for my $k (keys %ptr) {
next unless $ptr{$k} eq $k;
print join(" \\\n\t",
$program,
( map { quotemeta $set{$_} } @{$val{$ptr{$k}}} ),
";\n"
);
}
close(COMMANDS);
}
# ======================================================================
__DATA__
=head1 NAME
findimagedupes - Finds visually similar or duplicate images
=head1 SYNOPSIS
findimagedupes [option ...] [--] [ - | [file ...] ]
Options:
-f, --fingerprints=FILE -c, --collection=FILE
--merge=FILE -p, --program=PROGRAM
--prune -s, --script=FILE
-a, --add
-r, --rescan -q, --quiet
-n, --no-compare -v, --verbosity=LIST
-d, --debug=OPTS
-t, --threshold=NUM
-h, --help
-0, --null --man
With no options, compares the specified files and does not use
nor update any fingerprint database.
Directories of images may be specified instead of individual files;
Sub-directories are NOT searched recursively.
=head1 OPTIONS
=over 8
=item B<-0>, B<--null>
If a file C<-> is given, a list of files is read from stdin.
Without B<-0>, the list is specified one file per line, such as
produced by find(1) with its C<-print> option.
With B<-0>, the list is expected to be null-delimited, such as
produced by find(1) with its C<-print0> option.
=item B<-a>, B<--add>
Only look for duplicates of files specified on the commandline.
Matches are also sought in any fingerprint databases specified.
=item B<-c>, B<--collection>=I<FILE>
B<NOT IMPLEMENTED> (does anyone use this option?)
Create GQView collection I<FILE>.gqv of duplicates.
=item B<-d>, B<--debug>=I<OPTS>
Enable debugging output. Options I<OPTS> are subject to change.
See the program source for details.
=item B<-f>, B<--fingerprints>=I<FILE>
Use I<FILE> as fingerprint database.
May be abbreviated as B<--fp> or B<--db>.
This option may be given multiple times when B<--merge> is used.
(Note: I<FILE> could contain commas, so multiple databases may
not be specified as a single comma-delimited list.)
=item B<-h>, B<--help>
Print usage and option sections of this manual.
=item B<--man>
Display the full documentation, using default pager.
=item B<--merge>=I<FILE>
Takes any databases specified with B<--fingerprints>
and merges them into a new database called I<FILE>.
Conflicting fingerprints for an image will cause one of two actions to occur:
=over 4
=item 1.
If the image does not exist, then the entry is elided.
=item 2.
If the image does exist, then the old information is ignored
and a new fingerprint is generated from scratch.
=back
By default, image existence is not checked unless there is a conflict.
To force removal of defunct data, use B<--prune> as well.
A list of image files is not required if this option is used.
However, if a list is provided, fingerprint data for the files
will be copied or (re)generated as appropriate.
When B<--merge> is used, the original fingerprint databases are not modified,
even if B<--prune> is used.
See also: B<--rescan>
=item B<-n>, B<--no-compare>
Don't look for duplicates.
=item B<-p>, B<--program>=I<PROGRAM>
Launch I<PROGRAM> (in foreground) to view each set of dupes.
See also: B<--script>.
=item B<--prune>
Remove fingerprint data for images that do not exist any more.
Has no effect unless B<--fingerprints> or B<--merge> is also used.
Databases specified by B<--fingerprints> are only modified if
B<--merge> is not used.
=item B<-q>, B<--quiet>
This option may be given multiple times.
Usually, progress, warning and error messages are printed on stderr.
If this option is given, warnings are not displayed.
If it is given twice or more, errors are not displayed either.
Information requested with B<--verbosity> is still displayed.
=item B<-r>, B<--rescan>
(Re)generate all fingerprints, not just any that are unknown.
If used with B<--add>, only the fingerprints of files specified
on the commandline are (re)generated.
Implies B<--prune>.
=item B<-s>, B<--script>=I<FILE>
When used with B<--program>, I<PROGRAM> is not launched immediately.
Instead sh(1)-style commands are saved to I<FILE>.
This script may be edited (if desired) and then executed manually.
When used without B<--program>, a skeletal shell function C<VIEW>
is generated, which simply echo(1)s its arguments.
To display to terminal (or feed into a pipe), use C<-> as I<FILE>.
=item B<-t>, B<--threshold>=I<NUM>
Use I<NUM> as threshold% of similarity.
Default is 90 if not specified.
=item B<-v>, B<--verbosity>=I<LIST>
Enable display of informational messages to stdout,
where I<LIST> is a comma-delimited list of:
=over 8
=item B<md5>
Display the checksum for each file, as per md5sum(1).
=item B<fingerprint>,B<fp>
Display the base64-encoded fingerprint of each file.
=back
Alternatively, B<--verbosity> may be given multiple times, and accumulates.
Note that this may not be sensible. For example, to be useful,
B<md5> output probably should not be merged with B<fingerprint> data.
=back
=head1 DESCRIPTION
B<findimagedupes> compares a list of files for visual similarity.
=over 1
=item To calculate an image fingerprint:
1) Read image.
2) Resample to 160x160 to standardize size.
3) Grayscale by reducing saturation.
4) Blur a lot to get rid of noise.
5) Normalize to spread out intensity as much as possible.
6) Equalize to make image as contrasty as possible.
7) Resample again down to 16x16.
8) Reduce to 1bpp.
9) The fingerprint is this raw image data.
=item To compare two images for similarity:
1) Take fingerprint pairs and xor them.
2) Compute the percentage of 1 bits in the result.
3) If percentage exceeds threshold, declare files to be similar.
=back
=head1 RETURN VALUE
=over 4
=item 0
Success.
=item 1
Usage information was requested (B<--help> or B<--man>), or there
were warnings.
=item 2
Invalid options or arguments were provided.
=item 3
Runtime error.
=back
Any other return values indicate an internal error of some sort.
=head1 DIAGNOSTICS
To be written.
=head1 EXAMPLES
To be written.
=head1 FILES
To be written.
=head1 BUGS
There is a memory leak somewhere.
Killing the programme may corrupt the fingerprint database(s).
=head1 NOTES
Directory recursion is deliberately not implemented:
Composing a file-list and using it with C<-> is a more flexible approach.
Repetitions are culled before comparisons take place, so a commandline
like C<findimagedupes a.jpg a.jpg> will not produce a match.
The program needs a lot of memory. Probably not an issue, unless your
machine has less than 128MB of free RAM and you try to compare more than
a hundred-thousand files at once (and the program will run quite slowly
with that many files anyway---about eight hours initially to generate
fingerprints and another ten minutes to do the actual comparing).
=head1 SEE ALSO
find(1), md5sum(1)
B<gqview> - A simple image viewer using GTK+
=head1 AUTHOR
Jonathan H N Chin <code@jhnc.org>
=head1 COPYRIGHT AND LICENSE
Copyright 2006 by Jonathan H N Chin <code@jhnc.org>.
This program is free software; you may redistribute it and/or modify it
under the same terms as Perl itself.
=head1 HISTORY
This code has been written from scratch. However it owes its existence
to B<findimagedupes> by Rob Kudla and uses the same duplicate-detection
algorithm.
=cut
__C__
/* efficient bit-comparison */
#include <stdint.h>
#include <string.h>
#define LOOKUP_SIZE 65536
#define FP_CHUNKS 16
typedef uint16_t FP[FP_CHUNKS];
unsigned int simplecountbits (unsigned int i) {
unsigned int val = i, res = 0;
while (val) {
res += (val&1);
val >>= 1;
}
return(res);
}
void diffbits (SV* oldfiles, SV* newfiles, unsigned int percent, unsigned limit) {
FP *the_data, *a, *b;
unsigned int lookup[LOOKUP_SIZE];
unsigned int i, j, k, m, bits, threshold, old, new;
HV *oldhash;
HE *oldhash_entry;
HV *newhash;
HE *newhash_entry;
unsigned int numkeys = 0;
SV *sv_val;
Inline_Stack_Vars;
if ((percent<1) || (percent>99)) {
croak("ridiculous percentage specified");
}
threshold = floor(2.56*(100-percent));
/* pack fingerprints into C array */
/* partly lifted from Inline::C-Cookbook */
if (! SvROK(newfiles)) {
croak("newfiles is not a reference");
}
newhash = (HV *)SvRV(newfiles);
new = hv_iterinit(newhash);
if (! SvROK(oldfiles)) {
croak("oldfiles is not a reference");
}
oldhash = (HV *)SvRV(oldfiles);
old = hv_iterinit(oldhash);
numkeys = new+old;
if (numkeys<2) {
/* minor optimization: return without doing anything */
/* malloc(0) could be bad... */
Inline_Stack_Void;
}
the_data = (FP *)malloc(numkeys*sizeof(FP));
if (!the_data) {
croak("malloc failed");
}
for (i = 0; i<new; i++) {
newhash_entry = hv_iternext(newhash);
sv_val = hv_iterval(newhash, newhash_entry);
memcpy(the_data+i, SvPV(sv_val, PL_na), sizeof(FP));
}
for (i = new; i<numkeys; i++) {
oldhash_entry = hv_iternext(oldhash);
sv_val = hv_iterval(oldhash, oldhash_entry);
memcpy(the_data+i, SvPV(sv_val, PL_na), sizeof(FP));
}
/* initialise lookup table */
/* XXX: fast enough? could optimise more or compile-in a static table */
for (i=0; i<LOOKUP_SIZE; i++) {
lookup[i] = simplecountbits(i);
}
/* look for matches */
Inline_Stack_Reset;
for (a=the_data, i=0, m=(limit>0 ? new-1 : numkeys-1); i<m; a++, i++) {
for (b=a+1, j=i+1; j<numkeys; b++, j++) {
for (bits=0, k=0; k<FP_CHUNKS; k++) {
bits += lookup[(*a)[k]^(*b)[k]];
if (bits > threshold) goto abortmatch;
}
/* if (bits <= threshold) */ {
Inline_Stack_Push(sv_2mortal(newSViv(i)));
Inline_Stack_Push(sv_2mortal(newSViv(j)));
Inline_Stack_Push(sv_2mortal(newSViv(bits)));
}
abortmatch:;
}
}
Inline_Stack_Done;
/* clean up */
free(the_data);
}
|