From 7d3612d9f6ebc5ecbdc400acbb97333c7bb402c9 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sun, 7 Oct 2007 23:20:12 +0100 Subject: [PATCH 001/184] Create repo structure --- .gitignore | 22 ++ AUTHORS | 1 + COPYING | 504 ++++++++++++++++++++++++++++++++++++++++++ ChangeLog | 1 + INSTALL | 234 ++++++++++++++++++++ Makefile.am | 2 + NEWS | 0 README | 0 THANKS | 4 + autogen.sh | 7 + configure.ac | 31 +++ libfprint/Makefile.am | 9 + libfprint/core.c | 25 +++ 13 files changed, 840 insertions(+) create mode 100644 .gitignore create mode 100644 AUTHORS create mode 100644 COPYING create mode 100644 ChangeLog create mode 100644 INSTALL create mode 100644 Makefile.am create mode 100644 NEWS create mode 100644 README create mode 100644 THANKS create mode 100755 autogen.sh create mode 100644 configure.ac create mode 100644 libfprint/Makefile.am create mode 100644 libfprint/core.c diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..a026bd33 --- /dev/null +++ b/.gitignore @@ -0,0 +1,22 @@ +ltmain.sh +missing +stamp-h1 +libtool +*.la +*.lo +*.o +*.swp +Makefile +Makefile.in +config.h* +aclocal.m4 +autom4te.cache +config.guess +config.log +config.status +config.sub +configure +depcomp +install-sh +.deps +.libs diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 00000000..e119bbd8 --- /dev/null +++ b/AUTHORS @@ -0,0 +1 @@ +Daniel Drake diff --git a/COPYING b/COPYING new file mode 100644 index 00000000..5ab7695a --- /dev/null +++ b/COPYING @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/ChangeLog b/ChangeLog new file mode 100644 index 00000000..941b3ac2 --- /dev/null +++ b/ChangeLog @@ -0,0 +1 @@ +The ChangeLog is maintained in the git source control system. diff --git a/INSTALL b/INSTALL new file mode 100644 index 00000000..5458714e --- /dev/null +++ b/INSTALL @@ -0,0 +1,234 @@ +Installation Instructions +************************* + +Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002, 2004, 2005, +2006 Free Software Foundation, Inc. + +This file is free documentation; the Free Software Foundation gives +unlimited permission to copy, distribute and modify it. + +Basic Installation +================== + +Briefly, the shell commands `./configure; make; make install' should +configure, build, and install this package. The following +more-detailed instructions are generic; see the `README' file for +instructions specific to this package. + + The `configure' shell script attempts to guess correct values for +various system-dependent variables used during compilation. It uses +those values to create a `Makefile' in each directory of the package. +It may also create one or more `.h' files containing system-dependent +definitions. Finally, it creates a shell script `config.status' that +you can run in the future to recreate the current configuration, and a +file `config.log' containing compiler output (useful mainly for +debugging `configure'). + + It can also use an optional file (typically called `config.cache' +and enabled with `--cache-file=config.cache' or simply `-C') that saves +the results of its tests to speed up reconfiguring. Caching is +disabled by default to prevent problems with accidental use of stale +cache files. + + If you need to do unusual things to compile the package, please try +to figure out how `configure' could check whether to do them, and mail +diffs or instructions to the address given in the `README' so they can +be considered for the next release. If you are using the cache, and at +some point `config.cache' contains results you don't want to keep, you +may remove or edit it. + + The file `configure.ac' (or `configure.in') is used to create +`configure' by a program called `autoconf'. You need `configure.ac' if +you want to change it or regenerate `configure' using a newer version +of `autoconf'. + +The simplest way to compile this package is: + + 1. `cd' to the directory containing the package's source code and type + `./configure' to configure the package for your system. + + Running `configure' might take a while. While running, it prints + some messages telling which features it is checking for. + + 2. Type `make' to compile the package. + + 3. Optionally, type `make check' to run any self-tests that come with + the package. + + 4. Type `make install' to install the programs and any data files and + documentation. + + 5. You can remove the program binaries and object files from the + source code directory by typing `make clean'. To also remove the + files that `configure' created (so you can compile the package for + a different kind of computer), type `make distclean'. There is + also a `make maintainer-clean' target, but that is intended mainly + for the package's developers. If you use it, you may have to get + all sorts of other programs in order to regenerate files that came + with the distribution. + +Compilers and Options +===================== + +Some systems require unusual options for compilation or linking that the +`configure' script does not know about. Run `./configure --help' for +details on some of the pertinent environment variables. + + You can give `configure' initial values for configuration parameters +by setting variables in the command line or in the environment. Here +is an example: + + ./configure CC=c99 CFLAGS=-g LIBS=-lposix + + *Note Defining Variables::, for more details. + +Compiling For Multiple Architectures +==================================== + +You can compile the package for more than one kind of computer at the +same time, by placing the object files for each architecture in their +own directory. To do this, you can use GNU `make'. `cd' to the +directory where you want the object files and executables to go and run +the `configure' script. `configure' automatically checks for the +source code in the directory that `configure' is in and in `..'. + + With a non-GNU `make', it is safer to compile the package for one +architecture at a time in the source code directory. After you have +installed the package for one architecture, use `make distclean' before +reconfiguring for another architecture. + +Installation Names +================== + +By default, `make install' installs the package's commands under +`/usr/local/bin', include files under `/usr/local/include', etc. You +can specify an installation prefix other than `/usr/local' by giving +`configure' the option `--prefix=PREFIX'. + + You can specify separate installation prefixes for +architecture-specific files and architecture-independent files. If you +pass the option `--exec-prefix=PREFIX' to `configure', the package uses +PREFIX as the prefix for installing programs and libraries. +Documentation and other data files still use the regular prefix. + + In addition, if you use an unusual directory layout you can give +options like `--bindir=DIR' to specify different values for particular +kinds of files. Run `configure --help' for a list of the directories +you can set and what kinds of files go in them. + + If the package supports it, you can cause programs to be installed +with an extra prefix or suffix on their names by giving `configure' the +option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'. + +Optional Features +================= + +Some packages pay attention to `--enable-FEATURE' options to +`configure', where FEATURE indicates an optional part of the package. +They may also pay attention to `--with-PACKAGE' options, where PACKAGE +is something like `gnu-as' or `x' (for the X Window System). The +`README' should mention any `--enable-' and `--with-' options that the +package recognizes. + + For packages that use the X Window System, `configure' can usually +find the X include and library files automatically, but if it doesn't, +you can use the `configure' options `--x-includes=DIR' and +`--x-libraries=DIR' to specify their locations. + +Specifying the System Type +========================== + +There may be some features `configure' cannot figure out automatically, +but needs to determine by the type of machine the package will run on. +Usually, assuming the package is built to be run on the _same_ +architectures, `configure' can figure that out, but if it prints a +message saying it cannot guess the machine type, give it the +`--build=TYPE' option. TYPE can either be a short name for the system +type, such as `sun4', or a canonical name which has the form: + + CPU-COMPANY-SYSTEM + +where SYSTEM can have one of these forms: + + OS KERNEL-OS + + See the file `config.sub' for the possible values of each field. If +`config.sub' isn't included in this package, then this package doesn't +need to know the machine type. + + If you are _building_ compiler tools for cross-compiling, you should +use the option `--target=TYPE' to select the type of system they will +produce code for. + + If you want to _use_ a cross compiler, that generates code for a +platform different from the build platform, you should specify the +"host" platform (i.e., that on which the generated programs will +eventually be run) with `--host=TYPE'. + +Sharing Defaults +================ + +If you want to set default values for `configure' scripts to share, you +can create a site shell script called `config.site' that gives default +values for variables like `CC', `cache_file', and `prefix'. +`configure' looks for `PREFIX/share/config.site' if it exists, then +`PREFIX/etc/config.site' if it exists. Or, you can set the +`CONFIG_SITE' environment variable to the location of the site script. +A warning: not all `configure' scripts look for a site script. + +Defining Variables +================== + +Variables not defined in a site shell script can be set in the +environment passed to `configure'. However, some packages may run +configure again during the build, and the customized values of these +variables may be lost. In order to avoid this problem, you should set +them in the `configure' command line, using `VAR=value'. For example: + + ./configure CC=/usr/local2/bin/gcc + +causes the specified `gcc' to be used as the C compiler (unless it is +overridden in the site shell script). + +Unfortunately, this technique does not work for `CONFIG_SHELL' due to +an Autoconf bug. Until the bug is fixed you can use this workaround: + + CONFIG_SHELL=/bin/bash /bin/bash ./configure CONFIG_SHELL=/bin/bash + +`configure' Invocation +====================== + +`configure' recognizes the following options to control how it operates. + +`--help' +`-h' + Print a summary of the options to `configure', and exit. + +`--version' +`-V' + Print the version of Autoconf used to generate the `configure' + script, and exit. + +`--cache-file=FILE' + Enable the cache: use and save the results of the tests in FILE, + traditionally `config.cache'. FILE defaults to `/dev/null' to + disable caching. + +`--config-cache' +`-C' + Alias for `--cache-file=config.cache'. + +`--quiet' +`--silent' +`-q' + Do not print messages saying which checks are being made. To + suppress all normal output, redirect it to `/dev/null' (any error + messages will still be shown). + +`--srcdir=DIR' + Look for the package's source code in directory DIR. Usually + `configure' can determine that directory automatically. + +`configure' also accepts some other, not widely useful, options. Run +`configure --help' for more details. + diff --git a/Makefile.am b/Makefile.am new file mode 100644 index 00000000..df6f390a --- /dev/null +++ b/Makefile.am @@ -0,0 +1,2 @@ +SUBDIRS = libfprint +EXTRA_DIST = THANKS diff --git a/NEWS b/NEWS new file mode 100644 index 00000000..e69de29b diff --git a/README b/README new file mode 100644 index 00000000..e69de29b diff --git a/THANKS b/THANKS new file mode 100644 index 00000000..7df327c4 --- /dev/null +++ b/THANKS @@ -0,0 +1,4 @@ +Tony Vroon - hardware donations +Gerrie Mansur from Security Database BV (http://www.securitydatabase.net/) - hardware donations +Joaquin Custodio - hardware donations +TimeTrex (http://www.timetrex.com/) - hardware donations diff --git a/autogen.sh b/autogen.sh new file mode 100755 index 00000000..90932ea8 --- /dev/null +++ b/autogen.sh @@ -0,0 +1,7 @@ +#!/bin/sh +libtoolize --copy --force || exit 1 +aclocal || exit 1 +autoheader || exit 1 +autoconf || exit 1 +automake -a -c || exit 1 +./configure --enable-maintainer-mode $* diff --git a/configure.ac b/configure.ac new file mode 100644 index 00000000..ca9f19b8 --- /dev/null +++ b/configure.ac @@ -0,0 +1,31 @@ +AC_INIT([libfprint], [0.0]) +AM_INIT_AUTOMAKE +AC_CONFIG_SRCDIR([libfprint/core.c]) +AM_CONFIG_HEADER([config.h]) + +AC_PREREQ([2.61]) +AC_PROG_CC +AC_PROG_LIBTOOL +AC_C_INLINE + +# Library versioning +lt_major="0" +lt_revision="0" +lt_age="0" +AC_SUBST(lt_major) +AC_SUBST(lt_revision) +AC_SUBST(lt_age) + +PKG_CHECK_MODULES(LIBUSB, "libusb") +AC_SUBST(LIBUSB_CFLAGS) +AC_SUBST(LIBUSB_LIBS) + +PKG_CHECK_MODULES(GLIB, "glib-2.0") +AC_SUBST(GLIB_CFLAGS) +AC_SUBST(GLIB_LIBS) + +AC_DEFINE([API_EXPORTED], [__attribute__((visibility("default")))], [Default visibility]) + +AC_CONFIG_FILES([Makefile] [libfprint/Makefile]) +AC_OUTPUT + diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am new file mode 100644 index 00000000..ddfa3276 --- /dev/null +++ b/libfprint/Makefile.am @@ -0,0 +1,9 @@ +lib_LTLIBRARIES = libfprint.la + +libfprint_la_CFLAGS = -fvisibility=hidden $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) +libfprint_la_LDFLAGS = -version-info @lt_major@:@lt_revision@:@lt_age@ +libfprint_la_LIBADD = $(LIBUSB_LIBS) $(GLIB_LIBS) + +libfprint_la_SOURCES = \ + core.c + diff --git a/libfprint/core.c b/libfprint/core.c new file mode 100644 index 00000000..d96a78d1 --- /dev/null +++ b/libfprint/core.c @@ -0,0 +1,25 @@ +/* + * Core functions for libfprint + * Copyright (C) 2007 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include + +API_EXPORTED int fp_init(void) +{ + return 0; +} From 046bdc0bdab54d1890c5a5445b6ca711e4a13f19 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 8 Oct 2007 16:46:42 +0100 Subject: [PATCH 002/184] Initial driver registration mechanism Also added the basis of the upekts driver, which is the first I'll implement. --- libfprint/Makefile.am | 9 ++++++-- libfprint/core.c | 24 ++++++++++++++++++++++ libfprint/drivers/upekts.c | 32 +++++++++++++++++++++++++++++ libfprint/fp_internal.h | 42 ++++++++++++++++++++++++++++++++++++++ libfprint/fprint.h | 26 +++++++++++++++++++++++ 5 files changed, 131 insertions(+), 2 deletions(-) create mode 100644 libfprint/drivers/upekts.c create mode 100644 libfprint/fp_internal.h create mode 100644 libfprint/fprint.h diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index ddfa3276..7f798280 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -1,9 +1,14 @@ lib_LTLIBRARIES = libfprint.la +UPEKTS_SRC = drivers/upekts.c + +DRIVER_SRC = $(UPEKTS_SRC) + libfprint_la_CFLAGS = -fvisibility=hidden $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) libfprint_la_LDFLAGS = -version-info @lt_major@:@lt_revision@:@lt_age@ libfprint_la_LIBADD = $(LIBUSB_LIBS) $(GLIB_LIBS) -libfprint_la_SOURCES = \ - core.c +libfprint_la_SOURCES = \ + core.c \ + $(DRIVER_SRC) diff --git a/libfprint/core.c b/libfprint/core.c index d96a78d1..e7ee538f 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -19,7 +19,31 @@ #include +#include + +#include "fp_internal.h" + +static GList *registered_drivers = NULL; + +static void register_driver(const struct fp_driver *drv) +{ + registered_drivers = g_list_prepend(registered_drivers, (gpointer) drv); +} + +static const struct fp_driver * const drivers[] = { + &upekts_driver, +}; + +static void register_drivers(void) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(drivers); i++) + register_driver(drivers[i]); +} + API_EXPORTED int fp_init(void) { + register_drivers(); return 0; } diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c new file mode 100644 index 00000000..fdf97a38 --- /dev/null +++ b/libfprint/drivers/upekts.c @@ -0,0 +1,32 @@ +/* + * UPEK TouchStrip driver for libfprint + * Copyright (C) 2007 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include + +static const struct usb_id id_table[] = { + { .vendor = 0x0483, .product = 0x2016 }, + { 0 }, /* terminating entry */ +}; + +const struct fp_driver upekts_driver = { + .name = "upekts", + .full_name = "UPEK TouchStrip", + .id_table = id_table, +}; + diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h new file mode 100644 index 00000000..19f5ee5e --- /dev/null +++ b/libfprint/fp_internal.h @@ -0,0 +1,42 @@ +/* + * Internal/private definitions for libfprint + * Copyright (C) 2007 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef __FPRINT_INTERNAL_H__ +#define __FPRINT_INTERNAL_H__ + +#include + +#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*a)) + +struct usb_id { + uint16_t vendor; + uint16_t product; + unsigned long driver_data; +}; + +struct fp_driver { + const char *name; + const char *full_name; + const struct usb_id * const id_table; +}; + +extern const struct fp_driver upekts_driver; + +#endif + diff --git a/libfprint/fprint.h b/libfprint/fprint.h new file mode 100644 index 00000000..889dda74 --- /dev/null +++ b/libfprint/fprint.h @@ -0,0 +1,26 @@ +/* + * Main definitions for libfprint + * Copyright (C) 2007 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef __FPRINT_H__ +#define __FPRINT_H__ + +int fp_init(void); + +#endif + From 7d31cb4d456185a951fc98276b1244039317a0a2 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 8 Oct 2007 16:55:50 +0100 Subject: [PATCH 003/184] Basic device discovery infrastructure --- libfprint/core.c | 78 +++++++++++++++++++++++++++++++++++++++++ libfprint/fp_internal.h | 9 +++++ libfprint/fprint.h | 7 ++++ 3 files changed, 94 insertions(+) diff --git a/libfprint/core.c b/libfprint/core.c index e7ee538f..744424f3 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -20,6 +20,7 @@ #include #include +#include #include "fp_internal.h" @@ -42,8 +43,85 @@ static void register_drivers(void) register_driver(drivers[i]); } +static const struct fp_driver *find_supporting_driver(struct usb_device *udev) +{ + GList *elem = registered_drivers; + + do { + const struct fp_driver *drv = elem->data; + const struct usb_id *id; + + for (id = drv->id_table; id->vendor; id++) + if (udev->descriptor.idVendor == id->vendor && + udev->descriptor.idProduct == id->product) + return drv; + } while (elem = g_list_next(elem)); + return NULL; +} + +API_EXPORTED struct fp_dscv_dev **fp_discover_devs(void) +{ + GList *tmplist = NULL; + struct fp_dscv_dev **list; + struct usb_device *udev; + struct usb_bus *bus; + int dscv_count = 0; + + if (registered_drivers == NULL) + return NULL; + + usb_find_busses(); + usb_find_devices(); + + /* Check each device against each driver, temporarily storing successfully + * discovered devices in a GList. + * + * Quite inefficient but excusable as we'll only be dealing with small + * sets of drivers against small sets of USB devices */ + for (bus = usb_get_busses(); bus; bus = bus->next) + for (udev = bus->devices; udev; udev = udev->next) { + const struct fp_driver *drv = find_supporting_driver(udev); + struct fp_dscv_dev *ddev; + if (!drv) + continue; + ddev = g_malloc0(sizeof(*ddev)); + ddev->drv = drv; + ddev->udev = udev; + tmplist = g_list_prepend(tmplist, (gpointer) ddev); + dscv_count++; + } + + /* Convert our temporary GList into a standard NULL-terminated pointer + * array. */ + list = g_malloc(sizeof(*list) * (dscv_count + 1)); + if (dscv_count > 0) { + GList *elem = tmplist; + int i = 0; + do { + list[i++] = elem->data; + } while (elem = g_list_next(elem)); + } + list[dscv_count] = NULL; /* NULL-terminate */ + + g_list_free(tmplist); + return list; +} + +API_EXPORTED void fp_dscv_devs_free(struct fp_dscv_dev **devs) +{ + int i; + if (!devs) + return; + + for (i = 0; devs[i]; i++) + g_free(devs[i]); + g_free(devs); +} + API_EXPORTED int fp_init(void) { + usb_init(); register_drivers(); return 0; } + diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 19f5ee5e..3b6ab058 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -22,6 +22,10 @@ #include +#include + +#include + #define ARRAY_SIZE(a) (sizeof(a) / sizeof(*a)) struct usb_id { @@ -38,5 +42,10 @@ struct fp_driver { extern const struct fp_driver upekts_driver; +struct fp_dscv_dev { + struct usb_device *udev; + const struct fp_driver *drv; +}; + #endif diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 889dda74..5be53119 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -20,6 +20,13 @@ #ifndef __FPRINT_H__ #define __FPRINT_H__ +/* structs that applications are not allowed to peek into */ +struct fp_dscv_dev; + +/* Device discovery */ +struct fp_dscv_dev **fp_discover_devs(void); +void fp_dscv_devs_free(struct fp_dscv_dev **devs); + int fp_init(void); #endif From 711bb1151b161f3696d97b78de975221ccee82cd Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 8 Oct 2007 17:01:08 +0100 Subject: [PATCH 004/184] open/close device functions --- libfprint/core.c | 34 ++++++++++++++++++++++++++++++++++ libfprint/fp_internal.h | 10 ++++++++++ libfprint/fprint.h | 5 +++++ 3 files changed, 49 insertions(+) diff --git a/libfprint/core.c b/libfprint/core.c index 744424f3..a8922c55 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -118,6 +118,40 @@ API_EXPORTED void fp_dscv_devs_free(struct fp_dscv_dev **devs) g_free(devs); } +API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) +{ + struct fp_dev *dev; + const struct fp_driver *drv = ddev->drv; + int r; + + usb_dev_handle *udevh = usb_open(ddev->udev); + if (!udevh) + return NULL; + + dev = g_malloc0(sizeof(*dev)); + dev->drv = drv; + dev->udev = udevh; + + if (drv->init) { + r = drv->init(dev); + if (r) { + usb_close(udevh); + g_free(dev); + return NULL; + } + } + + return dev; +} + +API_EXPORTED void fp_dev_close(struct fp_dev *dev) +{ + if (dev->drv->exit) + dev->drv->exit(dev); + usb_close(dev->udev); + g_free(dev); +} + API_EXPORTED int fp_init(void) { usb_init(); diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 3b6ab058..c4629dec 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -28,6 +28,12 @@ #define ARRAY_SIZE(a) (sizeof(a) / sizeof(*a)) +struct fp_dev { + const struct fp_driver *drv; + usb_dev_handle *udev; + void *priv; +}; + struct usb_id { uint16_t vendor; uint16_t product; @@ -38,6 +44,10 @@ struct fp_driver { const char *name; const char *full_name; const struct usb_id * const id_table; + + /* Device operations */ + int (*init)(struct fp_dev *dev); + void (*exit)(struct fp_dev *dev); }; extern const struct fp_driver upekts_driver; diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 5be53119..07d35d37 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -22,11 +22,16 @@ /* structs that applications are not allowed to peek into */ struct fp_dscv_dev; +struct fp_dev; /* Device discovery */ struct fp_dscv_dev **fp_discover_devs(void); void fp_dscv_devs_free(struct fp_dscv_dev **devs); +/* Device handling */ +struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev); +void fp_dev_close(struct fp_dev *dev); + int fp_init(void); #endif From 2c06a4ebfaed93505bb7daa7d9a49bb394bdbfb4 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 8 Oct 2007 17:05:58 +0100 Subject: [PATCH 005/184] Expose driver info to library users --- libfprint/core.c | 20 ++++++++++++++++++++ libfprint/fprint.h | 7 +++++++ 2 files changed, 27 insertions(+) diff --git a/libfprint/core.c b/libfprint/core.c index a8922c55..2fbaa48d 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -118,6 +118,11 @@ API_EXPORTED void fp_dscv_devs_free(struct fp_dscv_dev **devs) g_free(devs); } +API_EXPORTED const struct fp_driver *fp_dscv_dev_get_driver(struct fp_dscv_dev *dev) +{ + return dev->drv; +} + API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) { struct fp_dev *dev; @@ -152,6 +157,21 @@ API_EXPORTED void fp_dev_close(struct fp_dev *dev) g_free(dev); } +API_EXPORTED const struct fp_driver *fp_dev_get_driver(struct fp_dev *dev) +{ + return dev->drv; +} + +API_EXPORTED const char *fp_driver_get_name(const struct fp_driver *drv) +{ + return drv->name; +} + +API_EXPORTED const char *fp_driver_get_full_name(const struct fp_driver *drv) +{ + return drv->full_name; +} + API_EXPORTED int fp_init(void) { usb_init(); diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 07d35d37..3a3f34e0 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -23,14 +23,21 @@ /* structs that applications are not allowed to peek into */ struct fp_dscv_dev; struct fp_dev; +struct fp_driver; /* Device discovery */ struct fp_dscv_dev **fp_discover_devs(void); void fp_dscv_devs_free(struct fp_dscv_dev **devs); +const struct fp_driver *fp_dscv_dev_get_driver(struct fp_dscv_dev *dev); /* Device handling */ struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev); void fp_dev_close(struct fp_dev *dev); +const struct fp_driver *fp_dev_get_driver(struct fp_dev *dev); + +/* Drivers */ +const char *fp_driver_get_name(const struct fp_driver *drv); +const char *fp_driver_get_full_name(const struct fp_driver *drv); int fp_init(void); From f81aa47a19a8ab7c1e53d9b483ead064fdd85884 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 8 Oct 2007 17:15:21 +0100 Subject: [PATCH 006/184] Add 'verify' example skeleton This will become an example program to enroll a fingerprint and then verify a finger against it. --- Makefile.am | 8 +++++- autogen.sh | 2 +- configure.ac | 9 +++++- examples/Makefile.am | 6 ++++ examples/verify.c | 67 ++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 89 insertions(+), 3 deletions(-) create mode 100644 examples/Makefile.am create mode 100644 examples/verify.c diff --git a/Makefile.am b/Makefile.am index df6f390a..57f8dfe1 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1,2 +1,8 @@ -SUBDIRS = libfprint EXTRA_DIST = THANKS + +SUBDIRS = libfprint + +if BUILD_EXAMPLES +SUBDIRS += examples +endif + diff --git a/autogen.sh b/autogen.sh index 90932ea8..fe264051 100755 --- a/autogen.sh +++ b/autogen.sh @@ -4,4 +4,4 @@ aclocal || exit 1 autoheader || exit 1 autoconf || exit 1 automake -a -c || exit 1 -./configure --enable-maintainer-mode $* +./configure --enable-maintainer-mode --enable-examples-build $* diff --git a/configure.ac b/configure.ac index ca9f19b8..9e76bd84 100644 --- a/configure.ac +++ b/configure.ac @@ -24,8 +24,15 @@ PKG_CHECK_MODULES(GLIB, "glib-2.0") AC_SUBST(GLIB_CFLAGS) AC_SUBST(GLIB_LIBS) +# Examples build +AC_ARG_ENABLE([examples-build], [AS_HELP_STRING([--enable-examples-build], + [build example applications (default n)])], + [build_examples=$enableval], + [build_examples='no']) +AM_CONDITIONAL([BUILD_EXAMPLES], [test "x$build_examples" != "xno"]) + AC_DEFINE([API_EXPORTED], [__attribute__((visibility("default")))], [Default visibility]) -AC_CONFIG_FILES([Makefile] [libfprint/Makefile]) +AC_CONFIG_FILES([Makefile] [libfprint/Makefile] [examples/Makefile]) AC_OUTPUT diff --git a/examples/Makefile.am b/examples/Makefile.am new file mode 100644 index 00000000..5b676c62 --- /dev/null +++ b/examples/Makefile.am @@ -0,0 +1,6 @@ +INCLUDES = -I$(top_srcdir) +noinst_PROGRAMS = verify + +verify_SOURCES = verify.c +verify_LDADD = ../libfprint/libfprint.la -lfprint + diff --git a/examples/verify.c b/examples/verify.c new file mode 100644 index 00000000..7ada2c61 --- /dev/null +++ b/examples/verify.c @@ -0,0 +1,67 @@ +/* + * Example fingerprint verification program + * Copyright (C) 2007 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include + +#include + +struct fp_dscv_dev *discover_device(struct fp_dscv_dev **discovered_devs) +{ + struct fp_dscv_dev *ddev = NULL; + struct fp_dscv_dev *tmpdev; + int i; + + for (i = 0; tmpdev = discovered_devs[i]; i++) { + const struct fp_driver *drv = fp_dscv_dev_get_driver(tmpdev); + printf("Found device claimed by %s driver\n", + fp_driver_get_full_name(drv)); + return ddev; + } + + return ddev; +} + +int main(void) +{ + int r; + struct fp_dscv_dev *ddev; + struct fp_dscv_dev **discovered_devs; + + r = fp_init(); + if (r < 0) { + fprintf(stderr, "Failed to initialize libfprint\n"); + exit(1); + } + + discovered_devs = fp_discover_devs(); + if (!discovered_devs) { + fprintf(stderr, "Could not discover devices\n"); + exit(1); + } + + ddev = discover_device(discovered_devs); + if (!ddev) { + fprintf(stderr, "No devices detected.\n"); + exit(1); + } + + fp_dscv_devs_free(discovered_devs); +} + From 59b73af909162c5fa7d57d3c14f66508a7589873 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 8 Oct 2007 17:37:58 +0100 Subject: [PATCH 007/184] Documentation update --- HACKING | 34 ++++++++++++++++++++++++++++++++++ Makefile.am | 2 +- TODO | 29 +++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 HACKING create mode 100644 TODO diff --git a/HACKING b/HACKING new file mode 100644 index 00000000..43027e4b --- /dev/null +++ b/HACKING @@ -0,0 +1,34 @@ +USB +=== + +At the time of development, there are no known consumer fingerprint readers +which do not operate over the USB bus. Therefore the library is designed around +the fact that each driver drivers USB devices, and each device is a USB device. +If we were to ever support a non-USB device, some rearchitecting would be +needed, but this would not be a substantial task. + + +GLib +==== + +Although the library uses GLib internally, libfprint is designed to provide +a completely neutral interface to it's application users. So, the public +APIs should never return GLib data types or anything like that. + + +Two-faced-ness +============== + +Like any decent library, this one is designed to provide a stable and +documented API to it's users: applications. Clear distinction is made between +data available internally in the library, and data/functions available to +the applications. + +This library is confused a little by the fact that there is another 'interface' +at hand: the internal interface provided to drivers. So, we effectively end +up with 2 APIs: + + 1. The external-facing API for applications + 2. The internal API for fingerprint drivers + + diff --git a/Makefile.am b/Makefile.am index 57f8dfe1..9d5938a0 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1,4 +1,4 @@ -EXTRA_DIST = THANKS +EXTRA_DIST = THANKS TODO HACKING SUBDIRS = libfprint diff --git a/TODO b/TODO new file mode 100644 index 00000000..472960b5 --- /dev/null +++ b/TODO @@ -0,0 +1,29 @@ +LIBRARY +======= +fingerprint data representation +storage mechanism +enrollment +verification +imaging support +external imaging APIs +identification +external API documentation +test suite against NISTIR + +DRIVERS +======= +UPEK TouchStrip driver +Sunplus 895 driver +AES3501 driver +AES4000 driver +ID Mouse driver +DigitalPersona U.are.U 4000/4000B driver +Support for 2nd generation MS devices +Support for 2nd generation UPEK devices + +MISC +==== +upekts/thinkfinger relicensing (GPL --> LGPL) +make library optionally asynchronous and maybe thread-safe +pkg-config file + From b071f3cdb928117401d173aa5ea0bb9555295618 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 8 Oct 2007 18:24:29 +0100 Subject: [PATCH 008/184] Initial fingerprint data representation ideas --- libfprint/Makefile.am | 1 + libfprint/data.c | 47 +++++++++++++++++++++++++++++++++++++++++ libfprint/fp_internal.h | 10 +++++++++ libfprint/fprint.h | 5 +++++ 4 files changed, 63 insertions(+) create mode 100644 libfprint/data.c diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 7f798280..1d3fa913 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -10,5 +10,6 @@ libfprint_la_LIBADD = $(LIBUSB_LIBS) $(GLIB_LIBS) libfprint_la_SOURCES = \ core.c \ + data.c \ $(DRIVER_SRC) diff --git a/libfprint/data.c b/libfprint/data.c new file mode 100644 index 00000000..b9222376 --- /dev/null +++ b/libfprint/data.c @@ -0,0 +1,47 @@ +/* + * Fingerprint data handling and storage + * Copyright (C) 2007 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include + +#include + +#include "fp_internal.h" + +struct fp_print_data *fpi_print_data_new(struct fp_driver *drv, size_t length) +{ + struct fp_print_data *data = g_malloc(sizeof(*data) + length); + data->driver_name = drv->name; + data->length = length; +} + +unsigned char *fpi_print_data_get_buffer(struct fp_print_data *data) +{ + return data->buffer; +} + +API_EXPORTED void fp_print_data_free(struct fp_print_data *data) +{ + g_free(data); +} + +int fpi_print_data_compatible(struct fp_dev *dev, struct fp_print_data *data) +{ + return strcmp(dev->drv->name, data->driver_name) == 0; +} diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index c4629dec..34d1231e 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -57,5 +57,15 @@ struct fp_dscv_dev { const struct fp_driver *drv; }; +struct fp_print_data { + const char *driver_name; + size_t length; + unsigned char buffer[0]; +}; + +struct fp_print_data *fpi_print_data_new(struct fp_driver *drv, size_t length); +unsigned char *fpi_print_data_get_buffer(struct fp_print_data *data); +int fpi_print_data_compatible(struct fp_dev *dev, struct fp_print_data *data); + #endif diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 3a3f34e0..14a5f381 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -24,6 +24,7 @@ struct fp_dscv_dev; struct fp_dev; struct fp_driver; +struct fp_print_data; /* Device discovery */ struct fp_dscv_dev **fp_discover_devs(void); @@ -39,6 +40,10 @@ const struct fp_driver *fp_dev_get_driver(struct fp_dev *dev); const char *fp_driver_get_name(const struct fp_driver *drv); const char *fp_driver_get_full_name(const struct fp_driver *drv); +/* Data handling */ +void fp_print_data_free(struct fp_print_data *data); + +/* Library */ int fp_init(void); #endif From 016ff33533bf4930e05ed5c818b83a5610e6b219 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 8 Oct 2007 19:53:50 +0100 Subject: [PATCH 009/184] Enrolment infrastructure --- TODO | 6 ++--- examples/verify.c | 58 ++++++++++++++++++++++++++++++++++++++--- libfprint/core.c | 16 ++++++++++++ libfprint/fp_internal.h | 4 +++ libfprint/fprint.h | 12 +++++++++ 5 files changed, 90 insertions(+), 6 deletions(-) diff --git a/TODO b/TODO index 472960b5..730ad015 100644 --- a/TODO +++ b/TODO @@ -1,14 +1,14 @@ LIBRARY ======= -fingerprint data representation +debugging messages +fingerprint data classifcation by device or device type storage mechanism -enrollment verification imaging support external imaging APIs identification external API documentation -test suite against NISTIR +test suite against NFIQ compliance set DRIVERS ======= diff --git a/examples/verify.c b/examples/verify.c index 7ada2c61..1a424fdf 100644 --- a/examples/verify.c +++ b/examples/verify.c @@ -25,11 +25,10 @@ struct fp_dscv_dev *discover_device(struct fp_dscv_dev **discovered_devs) { struct fp_dscv_dev *ddev = NULL; - struct fp_dscv_dev *tmpdev; int i; - for (i = 0; tmpdev = discovered_devs[i]; i++) { - const struct fp_driver *drv = fp_dscv_dev_get_driver(tmpdev); + for (i = 0; ddev = discovered_devs[i]; i++) { + const struct fp_driver *drv = fp_dscv_dev_get_driver(ddev); printf("Found device claimed by %s driver\n", fp_driver_get_full_name(drv)); return ddev; @@ -38,11 +37,49 @@ struct fp_dscv_dev *discover_device(struct fp_dscv_dev **discovered_devs) return ddev; } +struct fp_print_data *enroll(struct fp_dev *dev) { + struct fp_print_data *enrolled_print = NULL; + enum fp_enroll_status status; + + printf("You will need to successfully scan your finger %d times to " + "complete the process.\n", fp_dev_get_nr_enroll_stages(dev)); + + do { + printf("Scan your finger now.\n"); + status = fp_enroll_finger(dev, &enrolled_print); + switch (status) { + case FP_ENROLL_COMPLETE: + printf("Enroll complete!\n"); + break; + case FP_ENROLL_FAIL: + printf("Enroll failed, something wen't wrong :(\n"); + return NULL; + case FP_ENROLL_PASS: + printf("Enroll stage passed. Yay!\n"); + break; + case FP_ENROLL_RETRY: + printf("Didn't quite catch that. Please try again.\n"); + break; + } + } while (status != FP_ENROLL_COMPLETE); + + if (!enrolled_print) { + fprintf(stderr, "Enroll complete but no print?\n"); + return NULL; + } + + printf("got a print!\n"); + return enrolled_print; +} + int main(void) { int r; + int ret = 1; struct fp_dscv_dev *ddev; struct fp_dscv_dev **discovered_devs; + struct fp_dev *dev; + struct fp_print_data *data; r = fp_init(); if (r < 0) { @@ -62,6 +99,21 @@ int main(void) exit(1); } + dev = fp_dev_open(ddev); fp_dscv_devs_free(discovered_devs); + if (!dev) { + fprintf(stderr, "Could not open device.\n"); + } + + printf("Opened device. It's now time to enroll your finger.\n\n"); + data = enroll(dev); + if (!data) + goto out_close; + + ret = 0; +out_close: + fp_dev_close(dev); + return ret; } + diff --git a/libfprint/core.c b/libfprint/core.c index 2fbaa48d..d2fe52f4 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -162,6 +162,11 @@ API_EXPORTED const struct fp_driver *fp_dev_get_driver(struct fp_dev *dev) return dev->drv; } +API_EXPORTED int fp_dev_get_nr_enroll_stages(struct fp_dev *dev) +{ + return dev->nr_enroll_stages; +} + API_EXPORTED const char *fp_driver_get_name(const struct fp_driver *drv) { return drv->name; @@ -172,6 +177,16 @@ API_EXPORTED const char *fp_driver_get_full_name(const struct fp_driver *drv) return drv->full_name; } +API_EXPORTED enum fp_enroll_status fp_enroll_finger(struct fp_dev *dev, + struct fp_print_data **print_data) +{ + const struct fp_driver *drv = dev->drv; + if (!dev->nr_enroll_stages || !drv->enroll) + return FP_ENROLL_FAIL; + + return drv->enroll(dev, print_data); +} + API_EXPORTED int fp_init(void) { usb_init(); @@ -179,3 +194,4 @@ API_EXPORTED int fp_init(void) return 0; } + diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 34d1231e..0d380c4a 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -32,6 +32,8 @@ struct fp_dev { const struct fp_driver *drv; usb_dev_handle *udev; void *priv; + + int nr_enroll_stages; }; struct usb_id { @@ -48,6 +50,8 @@ struct fp_driver { /* Device operations */ int (*init)(struct fp_dev *dev); void (*exit)(struct fp_dev *dev); + enum fp_enroll_status (*enroll)(struct fp_dev *dev, + struct fp_print_data **print_data); }; extern const struct fp_driver upekts_driver; diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 14a5f381..6a2ac9ab 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -35,11 +35,23 @@ const struct fp_driver *fp_dscv_dev_get_driver(struct fp_dscv_dev *dev); struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev); void fp_dev_close(struct fp_dev *dev); const struct fp_driver *fp_dev_get_driver(struct fp_dev *dev); +int fp_dev_get_nr_enroll_stages(struct fp_dev *dev); /* Drivers */ const char *fp_driver_get_name(const struct fp_driver *drv); const char *fp_driver_get_full_name(const struct fp_driver *drv); +/* Enrolment */ +enum fp_enroll_status { + FP_ENROLL_COMPLETE, + FP_ENROLL_FAIL, + FP_ENROLL_PASS, + FP_ENROLL_RETRY, +}; + +enum fp_enroll_status fp_enroll_finger(struct fp_dev *dev, + struct fp_print_data **print_data); + /* Data handling */ void fp_print_data_free(struct fp_print_data *data); From ec91736ac4fb77e5d852959820d0070d1b4fc56f Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Wed, 10 Oct 2007 15:51:50 +0100 Subject: [PATCH 010/184] Add logging infrastructure Also added some debug/error messages to existing code. For now debugging is always on, this will be made optional later. --- libfprint/core.c | 55 ++++++++++++++++++++++++++++++++++++++--- libfprint/data.c | 1 + libfprint/fp_internal.h | 21 ++++++++++++++++ 3 files changed, 74 insertions(+), 3 deletions(-) diff --git a/libfprint/core.c b/libfprint/core.c index d2fe52f4..19a78b8b 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -21,14 +21,51 @@ #include #include +#include #include "fp_internal.h" static GList *registered_drivers = NULL; +void fpi_log(enum fpi_log_level level, const char *component, + const char *function, const char *format, ...) +{ + va_list args; + FILE *stream = stdout; + const char *prefix; + + switch (level) { + case LOG_LEVEL_INFO: + prefix = "info"; + break; + case LOG_LEVEL_WARNING: + stream = stderr; + prefix = "warning"; + break; + case LOG_LEVEL_ERROR: + stream = stderr; + prefix = "error"; + break; + case LOG_LEVEL_DEBUG: + stream = stderr; + prefix = "debug"; + break; + } + + fprintf(stream, "%s:%s [%s] ", component ? component : "fp", prefix, + function); + + va_start (args, format); + vfprintf(stream, format, args); + va_end (args); + + fprintf(stream, "\n"); +} + static void register_driver(const struct fp_driver *drv) { registered_drivers = g_list_prepend(registered_drivers, (gpointer) drv); + fp_dbg("registered driver %s", drv->name); } static const struct fp_driver * const drivers[] = { @@ -53,8 +90,11 @@ static const struct fp_driver *find_supporting_driver(struct usb_device *udev) for (id = drv->id_table; id->vendor; id++) if (udev->descriptor.idVendor == id->vendor && - udev->descriptor.idProduct == id->product) + udev->descriptor.idProduct == id->product) { + fp_dbg("driver %s supports USB device %04x:%04x", + drv->name, id->vendor, id->product); return drv; + } } while (elem = g_list_next(elem)); return NULL; } @@ -130,8 +170,10 @@ API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) int r; usb_dev_handle *udevh = usb_open(ddev->udev); - if (!udevh) + if (!udevh) { + fp_err("usb_open failed"); return NULL; + } dev = g_malloc0(sizeof(*dev)); dev->drv = drv; @@ -140,17 +182,20 @@ API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) if (drv->init) { r = drv->init(dev); if (r) { + fp_err("device initialisation failed, driver=%s", drv->name); usb_close(udevh); g_free(dev); return NULL; } } + fp_dbg(""); return dev; } API_EXPORTED void fp_dev_close(struct fp_dev *dev) { + fp_dbg(""); if (dev->drv->exit) dev->drv->exit(dev); usb_close(dev->udev); @@ -181,14 +226,18 @@ API_EXPORTED enum fp_enroll_status fp_enroll_finger(struct fp_dev *dev, struct fp_print_data **print_data) { const struct fp_driver *drv = dev->drv; - if (!dev->nr_enroll_stages || !drv->enroll) + if (!dev->nr_enroll_stages || !drv->enroll) { + fp_err("driver %s has 0 enroll stages or no enroll func", + dev->drv->name); return FP_ENROLL_FAIL; + } return drv->enroll(dev, print_data); } API_EXPORTED int fp_init(void) { + fp_dbg(""); usb_init(); register_drivers(); return 0; diff --git a/libfprint/data.c b/libfprint/data.c index b9222376..d3b416cb 100644 --- a/libfprint/data.c +++ b/libfprint/data.c @@ -27,6 +27,7 @@ struct fp_print_data *fpi_print_data_new(struct fp_driver *drv, size_t length) { struct fp_print_data *data = g_malloc(sizeof(*data) + length); + fp_dbg("length=%z", length); data->driver_name = drv->name; data->length = length; } diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 0d380c4a..69af87d0 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -28,6 +28,27 @@ #define ARRAY_SIZE(a) (sizeof(a) / sizeof(*a)) +enum fpi_log_level { + LOG_LEVEL_DEBUG, + LOG_LEVEL_INFO, + LOG_LEVEL_WARNING, + LOG_LEVEL_ERROR, +}; + +void fpi_log(enum fpi_log_level, const char *component, const char *function, + const char *format, ...); + +#ifndef FP_COMPONENT +#define FP_COMPONENT NULL +#endif + +#define _fpi_log(level, fmt...) fpi_log(level, FP_COMPONENT, __FUNCTION__, fmt) + +#define fp_dbg(fmt...) _fpi_log(LOG_LEVEL_DEBUG, fmt) +#define fp_info(fmt...) _fpi_log(LOG_LEVEL_INFO, fmt) +#define fp_warn(fmt...) _fpi_log(LOG_LEVEL_WARNING, fmt) +#define fp_err(fmt...) _fpi_log(LOG_LEVEL_ERROR, fmt) + struct fp_dev { const struct fp_driver *drv; usb_dev_handle *udev; From e6624fe5086dc3d86a3947e396ab7c52c0cdddb8 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Fri, 12 Oct 2007 15:16:51 +0100 Subject: [PATCH 011/184] Add 16 bit endianness functions --- libfprint/fp_internal.h | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 69af87d0..23213b61 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -24,6 +24,16 @@ #include +#ifdef __DARWIN_NULL +/* Darwin does endianness slightly differently */ +#include +#define __BYTE_ORDER BYTE_ORDER +#define __LITTLE_ENDIAN LITTLE_ENDIAN +#define __BIG_ENDIAN BIG_ENDIAN +#else /* Linux */ +#include +#endif + #include #define ARRAY_SIZE(a) (sizeof(a) / sizeof(*a)) @@ -92,5 +102,20 @@ struct fp_print_data *fpi_print_data_new(struct fp_driver *drv, size_t length); unsigned char *fpi_print_data_get_buffer(struct fp_print_data *data); int fpi_print_data_compatible(struct fp_dev *dev, struct fp_print_data *data); +#define bswap16(x) (((x & 0xff) << 8) | (x >> 8)) +#if __BYTE_ORDER == __LITTLE_ENDIAN +#define cpu_to_le16(x) (x) +#define le16_to_cpu(x) (x) +#define cpu_to_be16(x) bswap16(x) +#define be16_to_cpu(x) bswap16(x) +#elif __BYTE_ORDER == __BIG_ENDIAN +#define cpu_to_le16(x) bswap16(x) +#define le16_to_cpu(x) bswap16(x) +#define cpu_to_be16(x) (x) +#define be16_to_cpu(x) (x) +#else +#error "Unrecognized endianness" +#endif + #endif From 50e2de0730c5d93dd1ad5f0f07e010ee1d92ad01 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Fri, 12 Oct 2007 15:27:23 +0100 Subject: [PATCH 012/184] Enrollment tweaks upekts will need to know when the first enrollment stage is attempted for the first time, so add an __enroll_stage counter which actually indicates the next stage to enroll. -1 is a special value and it means 0 is next *and* it is the initial attemt. Added more debug output to the enroll handler. Added new fp_enroll_status codes for too short or uncentered scans. Changed the print_data allocator to consider the device rather than the driver, this feels more natural. Added missing return value. Make fp_enroll_status codes start at 1. 0 can now be used as a special/temporary value by the drivers. Also check that we aren't exceeding the number of enroll stages. Also add a missing exit() call to the verify example and update for the above. --- examples/verify.c | 8 +++++++ libfprint/core.c | 48 ++++++++++++++++++++++++++++++++++++++++- libfprint/data.c | 7 +++--- libfprint/fp_internal.h | 10 ++++++--- libfprint/fprint.h | 4 +++- 5 files changed, 69 insertions(+), 8 deletions(-) diff --git a/examples/verify.c b/examples/verify.c index 1a424fdf..5f668606 100644 --- a/examples/verify.c +++ b/examples/verify.c @@ -60,6 +60,13 @@ struct fp_print_data *enroll(struct fp_dev *dev) { case FP_ENROLL_RETRY: printf("Didn't quite catch that. Please try again.\n"); break; + case FP_ENROLL_RETRY_TOO_SHORT: + printf("Your swipe was too short, please try again.\n"); + break; + case FP_ENROLL_RETRY_CENTER_FINGER: + printf("Didn't catch that, please center your finger on the " + "sensor and try again.\n"); + break; } } while (status != FP_ENROLL_COMPLETE); @@ -103,6 +110,7 @@ int main(void) fp_dscv_devs_free(discovered_devs); if (!dev) { fprintf(stderr, "Could not open device.\n"); + exit(1); } printf("Opened device. It's now time to enroll your finger.\n\n"); diff --git a/libfprint/core.c b/libfprint/core.c index 19a78b8b..b6d90f02 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -178,6 +178,7 @@ API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) dev = g_malloc0(sizeof(*dev)); dev->drv = drv; dev->udev = udevh; + dev->__enroll_stage = -1; if (drv->init) { r = drv->init(dev); @@ -226,13 +227,58 @@ API_EXPORTED enum fp_enroll_status fp_enroll_finger(struct fp_dev *dev, struct fp_print_data **print_data) { const struct fp_driver *drv = dev->drv; + enum fp_enroll_status ret; + int stage = dev->__enroll_stage; + gboolean initial = FALSE; + if (!dev->nr_enroll_stages || !drv->enroll) { fp_err("driver %s has 0 enroll stages or no enroll func", dev->drv->name); return FP_ENROLL_FAIL; } - return drv->enroll(dev, print_data); + if (stage == -1) { + initial = TRUE; + dev->__enroll_stage = ++stage; + } + + if (stage >= dev->nr_enroll_stages) { + fp_err("exceeding number of enroll stages for device claimed by " + "driver %s (%d stages)", dev->drv->name, dev->nr_enroll_stages); + return FP_ENROLL_FAIL; + } + fp_dbg("%s will handle enroll stage %d/%d%s", drv->name, stage, + dev->nr_enroll_stages - 1, initial ? " (initial)" : ""); + + ret = drv->enroll(dev, initial, stage, print_data); + switch (ret) { + case FP_ENROLL_PASS: + fp_dbg("enroll stage passed"); + dev->__enroll_stage = stage + 1; + break; + case FP_ENROLL_COMPLETE: + fp_dbg("enroll complete"); + dev->__enroll_stage = -1; + break; + case FP_ENROLL_RETRY: + fp_dbg("enroll should retry"); + break; + case FP_ENROLL_RETRY_TOO_SHORT: + fp_dbg("swipe was too short, enroll should retry"); + break; + case FP_ENROLL_RETRY_CENTER_FINGER: + fp_dbg("finger was not centered, enroll should retry"); + break; + case FP_ENROLL_FAIL: + fp_err("enroll failed"); + dev->__enroll_stage = -1; + break; + default: + fp_err("unrecognised return code %d", ret); + dev->__enroll_stage = -1; + return FP_ENROLL_FAIL; + } + return ret; } API_EXPORTED int fp_init(void) diff --git a/libfprint/data.c b/libfprint/data.c index d3b416cb..9f940b83 100644 --- a/libfprint/data.c +++ b/libfprint/data.c @@ -24,12 +24,13 @@ #include "fp_internal.h" -struct fp_print_data *fpi_print_data_new(struct fp_driver *drv, size_t length) +struct fp_print_data *fpi_print_data_new(struct fp_dev *dev, size_t length) { struct fp_print_data *data = g_malloc(sizeof(*data) + length); - fp_dbg("length=%z", length); - data->driver_name = drv->name; + fp_dbg("length=%zd", length); + data->driver_name = dev->drv->name; data->length = length; + return data; } unsigned char *fpi_print_data_get_buffer(struct fp_print_data *data) diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 23213b61..5073866c 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -22,6 +22,7 @@ #include +#include #include #ifdef __DARWIN_NULL @@ -65,6 +66,9 @@ struct fp_dev { void *priv; int nr_enroll_stages; + + /* drivers should not mess with these */ + int __enroll_stage; }; struct usb_id { @@ -81,8 +85,8 @@ struct fp_driver { /* Device operations */ int (*init)(struct fp_dev *dev); void (*exit)(struct fp_dev *dev); - enum fp_enroll_status (*enroll)(struct fp_dev *dev, - struct fp_print_data **print_data); + enum fp_enroll_status (*enroll)(struct fp_dev *dev, gboolean initial, + int stage, struct fp_print_data **print_data); }; extern const struct fp_driver upekts_driver; @@ -98,7 +102,7 @@ struct fp_print_data { unsigned char buffer[0]; }; -struct fp_print_data *fpi_print_data_new(struct fp_driver *drv, size_t length); +struct fp_print_data *fpi_print_data_new(struct fp_dev *dev, size_t length); unsigned char *fpi_print_data_get_buffer(struct fp_print_data *data); int fpi_print_data_compatible(struct fp_dev *dev, struct fp_print_data *data); diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 6a2ac9ab..721cf02b 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -43,10 +43,12 @@ const char *fp_driver_get_full_name(const struct fp_driver *drv); /* Enrolment */ enum fp_enroll_status { - FP_ENROLL_COMPLETE, + FP_ENROLL_COMPLETE = 1, FP_ENROLL_FAIL, FP_ENROLL_PASS, FP_ENROLL_RETRY, + FP_ENROLL_RETRY_TOO_SHORT, + FP_ENROLL_RETRY_CENTER_FINGER, }; enum fp_enroll_status fp_enroll_finger(struct fp_dev *dev, From 299514431073828585c10b27af34a43936014703 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 13 Oct 2007 15:52:50 +0100 Subject: [PATCH 013/184] Build system tweaks Add configure-time controls for logging Set some default compile-time warnings --- autogen.sh | 3 ++- configure.ac | 19 +++++++++++++++++++ libfprint/Makefile.am | 2 +- libfprint/core.c | 6 +++++- libfprint/fp_internal.h | 11 +++++++++++ 5 files changed, 38 insertions(+), 3 deletions(-) diff --git a/autogen.sh b/autogen.sh index fe264051..7d368f84 100755 --- a/autogen.sh +++ b/autogen.sh @@ -4,4 +4,5 @@ aclocal || exit 1 autoheader || exit 1 autoconf || exit 1 automake -a -c || exit 1 -./configure --enable-maintainer-mode --enable-examples-build $* +./configure --enable-maintainer-mode --enable-examples-build \ + --enable-debug-log $* diff --git a/configure.ac b/configure.ac index 9e76bd84..45b95653 100644 --- a/configure.ac +++ b/configure.ac @@ -31,7 +31,26 @@ AC_ARG_ENABLE([examples-build], [AS_HELP_STRING([--enable-examples-build], [build_examples='no']) AM_CONDITIONAL([BUILD_EXAMPLES], [test "x$build_examples" != "xno"]) +# Message logging +AC_ARG_ENABLE([log], [AS_HELP_STRING([--disable-log], [disable all logging])], + [log_enabled=$enableval], + [log_enabled='yes']) +if test "x$log_enabled" != "xno"; then + AC_DEFINE([ENABLE_LOGGING], 1, [Message logging]) +fi + +AC_ARG_ENABLE([debug-log], [AS_HELP_STRING([--enable-debug-log], + [enable debug logging (default n)])], + [debug_log_enabled=$enableval], + [debug_log_enabled='no']) +if test "x$debug_log_enabled" != "xno"; then + AC_DEFINE([ENABLE_DEBUG_LOGGING], 1, [Debug message logging]) +fi + + AC_DEFINE([API_EXPORTED], [__attribute__((visibility("default")))], [Default visibility]) +AM_CFLAGS="-Werror-implicit-function-declaration -Wimplicit-int -Wunreachable-code -Wunused-function -Wunused-label -Wunused-value -Wunused-variable -Wnonnull -Wreturn-type -Wextra -Wshadow" +AC_SUBST(AM_CFLAGS) AC_CONFIG_FILES([Makefile] [libfprint/Makefile] [examples/Makefile]) AC_OUTPUT diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 1d3fa913..9790fbe8 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -4,7 +4,7 @@ UPEKTS_SRC = drivers/upekts.c DRIVER_SRC = $(UPEKTS_SRC) -libfprint_la_CFLAGS = -fvisibility=hidden $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) +libfprint_la_CFLAGS = -fvisibility=hidden $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) $(AM_CFLAGS) libfprint_la_LDFLAGS = -version-info @lt_major@:@lt_revision@:@lt_age@ libfprint_la_LIBADD = $(LIBUSB_LIBS) $(GLIB_LIBS) diff --git a/libfprint/core.c b/libfprint/core.c index b6d90f02..02c0e864 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -50,6 +50,10 @@ void fpi_log(enum fpi_log_level level, const char *component, stream = stderr; prefix = "debug"; break; + default: + stream = stderr; + prefix = "unknown"; + break; } fprintf(stream, "%s:%s [%s] ", component ? component : "fp", prefix, @@ -74,7 +78,7 @@ static const struct fp_driver * const drivers[] = { static void register_drivers(void) { - int i; + unsigned int i; for (i = 0; i < ARRAY_SIZE(drivers); i++) register_driver(drivers[i]); diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 5073866c..39ba08ae 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -20,6 +20,8 @@ #ifndef __FPRINT_INTERNAL_H__ #define __FPRINT_INTERNAL_H__ +#include + #include #include @@ -53,9 +55,18 @@ void fpi_log(enum fpi_log_level, const char *component, const char *function, #define FP_COMPONENT NULL #endif +#ifdef ENABLE_LOGGING #define _fpi_log(level, fmt...) fpi_log(level, FP_COMPONENT, __FUNCTION__, fmt) +#else +#define _fpi_log(level, fmt...) +#endif +#ifdef ENABLE_DEBUG_LOGGING #define fp_dbg(fmt...) _fpi_log(LOG_LEVEL_DEBUG, fmt) +#else +#define fp_dbg(fmt...) +#endif + #define fp_info(fmt...) _fpi_log(LOG_LEVEL_INFO, fmt) #define fp_warn(fmt...) _fpi_log(LOG_LEVEL_WARNING, fmt) #define fp_err(fmt...) _fpi_log(LOG_LEVEL_ERROR, fmt) From ab5b1ca8e9815599a5e5034736db7bcabebc9101 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 13 Oct 2007 16:24:20 +0100 Subject: [PATCH 014/184] upekts: communication handling and enrollment implementation This completes an enrollment implementation for the upekts driver. It's based on code from libthinkfinger, but as there seemed to be many unknown details there, I spent some time analysing the bus messages in more detail and have effectively rewritten almost all of the borrowed code. Note that libthinkfinger is GPL licensed, so that reflects on this code too. At release time I will ask them if they are OK for me to relicense it. --- COPYING | 10 + COPYING.GPL | 340 +++++++++++++++++++ README | 11 + libfprint/drivers/upekts.c | 647 ++++++++++++++++++++++++++++++++++++- 4 files changed, 996 insertions(+), 12 deletions(-) create mode 100644 COPYING.GPL diff --git a/COPYING b/COPYING index 5ab7695a..3a0a5754 100644 --- a/COPYING +++ b/COPYING @@ -1,3 +1,13 @@ +NOTE: This prerelease version of libfprint is mostly LGPL-licensed (as in the +text below) but also includes code from libthinkfinger which is licensed under +the GPL. +This libfprint release is therefore licensed under the LGPL *and* the GPL. +The GPL terms can be found in the COPYING.GPL file. + +At release time, I will contact libthinkfinger authors and see if they will +be happy to relicense. I expect they will. + + GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 diff --git a/COPYING.GPL b/COPYING.GPL new file mode 100644 index 00000000..3912109b --- /dev/null +++ b/COPYING.GPL @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/README b/README index e69de29b..65620a32 100644 --- a/README +++ b/README @@ -0,0 +1,11 @@ +libfprint +http://www.reactivated.net/fprint + +libfprint is primarily licensed under the GNU LGPL. HOWEVER, THIS PRERELEASE +VERSION INCLUDES GPL CODE FROM LIBTHINKFINGER, therefore distribution is +subject to both the terms of the LGPL (see COPYING) *and* the GPL +(see COPYING.GPL). + +At release time, I will contact libthinkfinger authors and see if they will +be happy to relicense. I expect they will. + diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index fdf97a38..c83e200e 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -2,31 +2,654 @@ * UPEK TouchStrip driver for libfprint * Copyright (C) 2007 Daniel Drake * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. + * Based in part on libthinkfinger: + * Copyright (C) 2006-2007 Timo Hoenig + * Copyright (C) 2006 Pavel Machek * - * This library is distributed in the hope that it will be useful, + * LGPL CRC code copied from GStreamer-0.10.10: + * Copyright (C) <1999> Erik Walthinsen + * Copyright (C) 2004,2006 Thomas Vander Stichele + * + * This program is free software; you can 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 - * Lesser General Public License for more details. + * 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 Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * 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. */ +#define FP_COMPONENT "upekts" + +#include +#include + +#include + #include +#define EP_IN (1 | USB_ENDPOINT_IN) +#define EP_OUT (2 | USB_ENDPOINT_OUT) +#define TIMEOUT 5000 + +struct upekts_dev { + uint8_t seq; +}; + +static const uint16_t crc_table[256] = { + 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, + 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, + 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, + 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, + 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, + 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, + 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, + 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, + 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, + 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, + 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, + 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, + 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, + 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, + 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, + 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, + 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, + 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, + 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, + 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, + 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, + 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, + 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, + 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, + 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, + 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, + 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, + 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, + 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, + 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, + 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, + 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 +}; + +static uint16_t udf_crc(unsigned char *buffer, size_t size) +{ + uint16_t crc = 0; + while (size--) + crc = (uint16_t) ((crc << 8) ^ + crc_table[((crc >> 8) & 0x00ff) ^ *buffer++]); + return crc; +} + +/* + * MESSAGE FORMAT + * + * Messages to and from the device have the same format. + * + * Byte-wise: + * 'C' 'i' 'a' 'o' A B L C1 C2 + * + * Ciao prefixes all messages. L is the length of the data, is L bytes + * long. C1 and C2 are the UDF-CRC16 for the whole message minus the Ciao + * prefix. + * + * When the device wants to command the driver to do something, it sends + * a message where B=0 and A!=0. The A value indicates the type of command. + * If the system is expected to respond to the command, it sends a message back + * with B=0 and A incremented. + * + * When the driver sends a command to the device, A=0 and B is used as a + * sequence counter. It starts at 0, increments by 0x10 on each command, and + * wraps around. + * After each command is sent, the device responds with another message + * indicating completion of the command including any data that was requested. + * This message has the same A and B values. + * + * When the driver is sending commands as above, and when the device is + * responding, the seems to follow this structure: + * + * 28 L 0 0 0 S + * + * Where the length of is L-3, and S is some kind of subcommand + * code. In the device's response to a command, the subcommand code will be + * unchanged. + * + * After deducing and documenting the above, I found a few places where the + * above doesn't hold true. Those are marked with FIXME's below. + */ + +#define CMD_SEQ_INCREMENT 0x10 + +static int send_cmd(struct fp_dev *dev, unsigned char seq_a, + unsigned char seq_b, unsigned char *data, uint8_t len) +{ + int r; + uint16_t crc; + + /* 9 bytes extra for: 4 byte 'Ciao', 1 byte A, 1 byte B, 1 byte length, + * 2 byte CRC */ + size_t urblen = len + 9; + unsigned char *buf; + + if (!data && len > 0) { + fp_err("len>0 but no data?"); + return -EINVAL; + } + + buf = g_malloc(urblen); + + /* Write header */ + strncpy(buf, "Ciao", 4); + buf[4] = seq_a; + buf[5] = seq_b; + buf[6] = len; + + /* Copy data */ + if (data) + memcpy(buf + 7, data, len); + + /* Append CRC */ + crc = cpu_to_be16(udf_crc(buf + 4, urblen - 6)); + buf[urblen - 2] = crc >> 8; + buf[urblen - 1] = crc & 0xff; + + r = usb_bulk_write(dev->udev, EP_OUT, buf, urblen, TIMEOUT); + g_free(buf); + if (r < 0) { + fp_err("cmd write failed, code %d", r); + return r; + } else if ((unsigned int) r < urblen) { + fp_err("cmd write too short (%d/%d)", r, urblen); + return -EIO; + } + + return 0; +} + +static int send_cmd28(struct fp_dev *dev, unsigned char subcmd, + unsigned char *data, uint8_t innerlen) +{ + size_t len = innerlen + 6; + unsigned char *buf = g_malloc0(len); + struct upekts_dev *upekdev = dev->priv; + uint8_t seq = upekdev->seq + CMD_SEQ_INCREMENT; + int r; + + fp_dbg("seq=%02x subcmd=%02x with %d bytes of data", seq, subcmd, innerlen); + + buf[0] = 0x28; + buf[1] = innerlen + 3; + buf[5] = subcmd; + memcpy(buf + 6, data, innerlen); + + r = send_cmd(dev, 0, seq, buf, len); + if (r == 0) + upekdev->seq = seq; + + g_free(buf); + return r; +} + +static int send_cmdresponse(struct fp_dev *dev, unsigned char seq, + unsigned char *data, uint8_t len) +{ + fp_dbg("seq=%02x len=%d", seq, len); + return send_cmd(dev, seq, 0, data, len); +} + +static unsigned char *__read_msg(struct fp_dev *dev, size_t *data_len) +{ +#define MSG_READ_BUF_SIZE 0x40 +#define MAX_DATA_IN_READ_BUF (MSG_READ_BUF_SIZE - 9) + unsigned char *buf = g_malloc(MSG_READ_BUF_SIZE); + size_t buf_size = MSG_READ_BUF_SIZE; + uint16_t computed_crc, msg_crc; + uint8_t len; + int r; + + r = usb_bulk_read(dev->udev, EP_IN, buf, buf_size, TIMEOUT); + if (r < 0) { + fp_err("msg read failed, code %d", r); + goto err; + } else if (r < 9) { + fp_err("msg read too short (%d/%d)", r, buf_size); + goto err; + } + + if (strncmp(buf, "Ciao", 4) != 0) { + fp_err("no Ciao for you!!"); + goto err; + } + + len = buf[6]; + + if (r != MSG_READ_BUF_SIZE && (len + 9) < r) { + /* Check that the length claimed inside the message is in line with + * the amount of data that was transferred over USB. */ + fp_err("msg didn't include enough data, expected=%d recv=%d", + len + 9, r); + goto err; + } + + /* We use a 64 byte buffer for reading messages. However, sometimes + * messages are longer, in which case we have to do another USB bulk read + * to read the remainder. This is handled below. */ + if (len > MAX_DATA_IN_READ_BUF) { + int needed = len - MAX_DATA_IN_READ_BUF; + fp_dbg("didn't fit in buffer, need to extend by %d bytes", needed); + buf = g_realloc((gpointer) buf, MSG_READ_BUF_SIZE + needed); + r = usb_bulk_read(dev->udev, EP_IN, buf + MSG_READ_BUF_SIZE, needed, + TIMEOUT); + if (r < 0) { + fp_err("extended msg read failed, code %d", r); + goto err; + } else if (r < needed) { + fp_err("extended msg short read (%d/%d)", r, needed); + goto err; + } + buf_size += needed; + } + + computed_crc = udf_crc(buf + 4, len + 3); + msg_crc = le16_to_cpu((buf[len + 8] << 8) | buf[len + 7]); + if (computed_crc != msg_crc) { + fp_err("CRC failed, got %04x expected %04x", msg_crc, computed_crc); + goto err; + } + + *data_len = buf_size; + return buf; +err: + g_free(buf); + return NULL; +} + +enum read_msg_status { + READ_MSG_ERROR = -1, + READ_MSG_CMD = 1, + READ_MSG_RESPONSE = 2, +}; + +static enum read_msg_status read_msg(struct fp_dev *dev, uint8_t *seq, + unsigned char *subcmd, unsigned char **data, size_t *data_len) +{ +#define MSG_READ_BUF_SIZE 0x40 +#define MAX_DATA_IN_READ_BUF (MSG_READ_BUF_SIZE - 9) + unsigned char *buf; + size_t buf_size; + unsigned char code_a; + unsigned char code_b; + uint8_t len; + enum read_msg_status ret = READ_MSG_ERROR; + +retry: + buf = __read_msg(dev, &buf_size); + if (!buf) + return READ_MSG_ERROR; + + code_a = buf[4]; + code_b = buf[5]; + len = buf[6]; + fp_dbg("A=%02x B=%02x len=%d", code_a, code_b, len); + + if (code_a && !code_b) { + /* device sends command to driver */ + fp_dbg("cmd %x from device to driver", code_a); + + if (code_a == 0x08) { + fp_dbg("device busy, send busy-ack"); + send_cmdresponse(dev, 0x09, NULL, 0); + g_free(buf); + goto retry; + } + + if (seq) + *seq = code_a; + if (data) { + if (len > 0) { + unsigned char *tmp = g_malloc(len); + memcpy(tmp, buf + 7, len); + *data = tmp; + } + *data_len = len; + } + ret = READ_MSG_CMD; + } else if (!code_a) { + /* device sends response to a previously executed command */ + unsigned char *innerbuf = buf + 7; + unsigned char _subcmd; + uint8_t innerlen; + + if (len < 6) { + fp_err("cmd response too short (%d)", len); + goto out; + } + if (innerbuf[0] != 0x28) { + fp_err("cmd response without 28 byte?"); + goto out; + } + if (innerbuf[2] || innerbuf[3] || innerbuf[4]) { + fp_err("non-zero bytes in cmd response"); + goto out; + } + + innerlen = innerbuf[1] - 3; + _subcmd = innerbuf[5]; + fp_dbg("device responds to subcmd %x with %d bytes", _subcmd, innerlen); + if (seq) + *seq = code_b; + if (subcmd) + *subcmd = _subcmd; + if (data) { + if (innerlen > 0) { + unsigned char *tmp = g_malloc(innerlen); + memcpy(tmp, innerbuf + 6, innerlen); + *data = tmp; + } + *data_len = innerlen; + } + ret = READ_MSG_RESPONSE; + } else { + fp_err("don't know how to handle this message"); + } + +out: + g_free(buf); + return ret; +} + +static int read_msg28(struct fp_dev *dev, unsigned char subcmd, + unsigned char **data, size_t *data_len) +{ + struct upekts_dev *upekdev = dev->priv; + uint8_t _seq; + unsigned char _subcmd; + enum read_msg_status msgstat; + + msgstat = read_msg(dev, &_seq, &_subcmd, data, data_len); + if (msgstat != READ_MSG_RESPONSE) { + fp_err("expected response, got %d seq=%x", msgstat, _seq); + return -EPROTO; + } + if (_subcmd != subcmd) { + fp_warn("expected response to subcmd %02x, got response to %02x", + subcmd, _subcmd); + return -EPROTO; + } + if (_seq != upekdev->seq) { + fp_err("expected response to cmd seq=%02x, got response to %02x", + upekdev->seq, _seq); + return -EPROTO; + } + + return 0; +} + +static const unsigned char init_resp03[] = { + 0x01, 0x00, 0xe8, 0x03, 0x00, 0x00, 0xff, 0x07 +}; +static const unsigned char init28_08[] = { + 0x04, 0x83, 0x00, 0x2c, 0x22, 0x23, 0x97, 0xc9, 0xa7, 0x15, 0xa0, 0x8a, + 0xab, 0x3c, 0xd0, 0xbf, 0xdb, 0xf3, 0x92, 0x6f, 0xae, 0x3b, 0x1e, 0x44, + 0xc4 +}; +static const unsigned char init28_0c[] = { + 0x04, 0x03, 0x00, 0x00, 0x00 +}; +static const unsigned char init28_0b[] = { + 0x04, 0x03, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0xf4, 0x01, 0x00, 0x00, 0x64, 0x01, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x0a, + 0x00, 0x64, 0x00, 0xf4, 0x01, 0x32, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00 +}; + +static int dev_init(struct fp_dev *dev) +{ + struct upekts_dev *upekdev; + unsigned char dummy = 0x10; + enum read_msg_status msgstat; + uint8_t seq; + int r; + + r = usb_claim_interface(dev->udev, 0); + if (r < 0) + return r; + + r = usb_control_msg(dev->udev, USB_TYPE_VENDOR | USB_RECIP_DEVICE, + 0x0c, 0x100, 0x400, &dummy, sizeof(dummy), TIMEOUT); + if (r < 0) + return r; + + upekdev = g_malloc(sizeof(*upekdev)); + upekdev->seq = 0xf0; /* incremented to 0x00 before first cmd */ + dev->priv = upekdev; + dev->nr_enroll_stages = 3; + + msgstat = read_msg(dev, &seq, NULL, NULL, NULL); + if (msgstat != READ_MSG_CMD) { + fp_err("expected command, got %d seq=%x", msgstat, seq); + goto err; + } + if (seq != 3) { + fp_err("expected seq=3, got %x", seq); + goto err; + } + + r = send_cmdresponse(dev, ++seq, (unsigned char *) init_resp03, + sizeof(init_resp03)); + if (r < 0) + goto err; + + msgstat = read_msg(dev, &seq, NULL, NULL, NULL); + if (msgstat != READ_MSG_CMD) { + fp_err("expected command, got %d seq=%x", msgstat, seq); + goto err; + } + if (seq != 5) { + fp_err("expected seq=5, got %x", seq); + goto err; + } + + seq = 0; + dummy = 0x04; + r = send_cmd28(dev, 0x06, &dummy, 1); + if (r < 0) + goto err; + if (read_msg28(dev, 0x06, NULL, NULL) < 0) + goto err; + + dummy = 0x04; + r = send_cmd28(dev, 0x07, &dummy, 1); + if (r < 0) + goto err; + if (read_msg28(dev, 0x07, NULL, NULL) < 0) + goto err; + + r = send_cmd28(dev, 0x08, (unsigned char *) init28_08, + sizeof(init28_08)); + if (r < 0) + goto err; + if (read_msg28(dev, 0x08, NULL, NULL) < 0) + goto err; + + r = send_cmd28(dev, 0x0c, (unsigned char *) init28_0c, + sizeof(init28_0c)); + if (r < 0) + goto err; + if (read_msg28(dev, 0x0c, NULL, NULL) < 0) + goto err; + + r = send_cmd28(dev, 0x0b, (unsigned char *) init28_0b, + sizeof(init28_0b)); + if (r < 0) + goto err; + if (read_msg28(dev, 0x0b, NULL, NULL) < 0) + goto err; + + return 0; +err: + g_free(upekdev); + return -EPROTO; +} + +static void dev_exit(struct fp_dev *dev) +{ + unsigned char dummy = 0; + + /* FIXME: either i've misunderstood the message system or this is illegal + * here, since we arent responding to anything. */ + send_cmdresponse(dev, 0x07, &dummy, 1); + + // FIXME should read msg A=01 + + g_free(dev->priv); +} + +static const unsigned char enroll_init[] = { + 0x02, 0xc0, 0xd4, 0x01, 0x00, 0x04, 0x00, 0x08 +}; +static const unsigned char scan_comp[] = { + 0x12, 0xff, 0xff, 0xff, 0xff /* scan completion, prefixes print data */ +}; + +static enum fp_enroll_status enroll(struct fp_dev *dev, gboolean initial, + int stage, struct fp_print_data **_data) +{ + unsigned char poll_data[] = { 0x30, 0x01 }; + unsigned char *data; + size_t data_len; + int r; + int result = 0; + int passed = 0; + + if (initial) { + r = send_cmd28(dev, 0x02, (unsigned char *) enroll_init, + sizeof(enroll_init)); + if (r < 0) + return FP_ENROLL_FAIL; + /* FIXME: protocol misunderstanding here. device receives response + * to subcmd 0 after submitting subcmd 2? */ + if (read_msg28(dev, 0x00, NULL, NULL) < 0) + return FP_ENROLL_FAIL; + } + + while (!result) { + unsigned char status; + + r = send_cmd28(dev, 0x00, poll_data, sizeof(poll_data)); + if (r < 0) + return r; + if (read_msg28(dev, 0x00, &data, &data_len) < 0) + return FP_ENROLL_FAIL; + + if (data_len != 14) { + fp_err("received 3001 poll response of %d bytes?", data_len); + g_free(data); + return FP_ENROLL_FAIL; + } + + status = data[5]; + fp_dbg("poll result = %02x", status); + + /* These codes indicate that we're waiting for a finger scan, so poll + * again */ + switch (status) { + case 0x0c: + case 0x0d: + case 0x0e: + /* no news, poll again */ + if (passed) + result = FP_ENROLL_PASS; + break; + case 0x1c: /* FIXME what does this one mean? */ + case 0x0f: /* scan taking too long, remove finger and try again */ + result = FP_ENROLL_RETRY; + break; + case 0x1e: /* swipe too short */ + result = FP_ENROLL_RETRY_TOO_SHORT; + break; + case 0x24: /* finger not centered */ + result = FP_ENROLL_RETRY_CENTER_FINGER; + break; + case 0x20: + passed = 1; + break; + case 0x00: + if (passed) + result = FP_ENROLL_COMPLETE; + break; + default: + fp_err("unrecognised scan status code %02x", status); + result = FP_ENROLL_FAIL; + break; + } + + if (result != FP_ENROLL_COMPLETE) + g_free(data); + } + + /* FIXME: need to extend protocol research to handle the case when + * enrolment fails, e.g. you scan a different finger on each stage */ + + if (result == FP_ENROLL_COMPLETE) { + struct fp_print_data *fdata; + unsigned char *buf; + + r = send_cmd28(dev, 0x00, poll_data, sizeof(poll_data)); + if (r < 0) + return r; + /* FIXME: protocol misunderstanding here. device receives response + * to subcmd 0 after submitting subcmd 2? */ + if (read_msg28(dev, 0x02, &data, &data_len) < 0) + return FP_ENROLL_FAIL; + + if (data_len < sizeof(scan_comp)) { + fp_err("fingerprint data too short (%d bytes)", data_len); + return FP_ENROLL_FAIL; + } + if (memcmp(data, scan_comp, sizeof(scan_comp)) != 0) { + fp_err("unrecognised data prefix %x %x %x %x %x", + data[0], data[1], data[2], data[3], data[4]); + return FP_ENROLL_FAIL; + } + if (!_data) { + fp_err("complete but no data storage!"); + return FP_ENROLL_COMPLETE; + } + + fdata = fpi_print_data_new(dev, data_len - sizeof(scan_comp)); + buf = fpi_print_data_get_buffer(fdata); + memcpy(buf, data + sizeof(scan_comp), data_len - sizeof(scan_comp)); + *_data = fdata; + g_free(data); + } + + return result; +} + + static const struct usb_id id_table[] = { { .vendor = 0x0483, .product = 0x2016 }, - { 0 }, /* terminating entry */ + { 0, 0, 0, }, /* terminating entry */ }; const struct fp_driver upekts_driver = { - .name = "upekts", + .name = FP_COMPONENT, .full_name = "UPEK TouchStrip", .id_table = id_table, + .init = dev_init, + .exit = dev_exit, + .enroll = enroll, }; From 39271b4fe50b5f3ceb880e47c951f906b9bc8ff2 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sun, 14 Oct 2007 00:45:49 +0100 Subject: [PATCH 015/184] Enrollment: improved error reporting Convert enrollment function to return a signed integer, which is negative on error or corresponds into fp_enroll_result otherwise. Now we can treat a 'FAIL' condition differently from an actual error: fail means that enrollment didn't complete because the data was nonsense or whatever (e.g. scanned a different finger for each stage?). Updated upekts accordingly. --- examples/verify.c | 22 ++++++++++++++++------ libfprint/core.c | 26 ++++++++++++++++++-------- libfprint/drivers/upekts.c | 36 +++++++++++++++++++++--------------- libfprint/fp_internal.h | 4 ++-- libfprint/fprint.h | 10 +++++----- 5 files changed, 62 insertions(+), 36 deletions(-) diff --git a/examples/verify.c b/examples/verify.c index 5f668606..07c0c2ce 100644 --- a/examples/verify.c +++ b/examples/verify.c @@ -19,6 +19,7 @@ #include #include +#include #include @@ -39,15 +40,20 @@ struct fp_dscv_dev *discover_device(struct fp_dscv_dev **discovered_devs) struct fp_print_data *enroll(struct fp_dev *dev) { struct fp_print_data *enrolled_print = NULL; - enum fp_enroll_status status; + int r; printf("You will need to successfully scan your finger %d times to " "complete the process.\n", fp_dev_get_nr_enroll_stages(dev)); do { - printf("Scan your finger now.\n"); - status = fp_enroll_finger(dev, &enrolled_print); - switch (status) { + sleep(1); + printf("\nScan your finger now.\n"); + r = fp_enroll_finger(dev, &enrolled_print); + if (r < 0) { + printf("Enroll failed with error %d\n", r); + return NULL; + } + switch (r) { case FP_ENROLL_COMPLETE: printf("Enroll complete!\n"); break; @@ -67,15 +73,19 @@ struct fp_print_data *enroll(struct fp_dev *dev) { printf("Didn't catch that, please center your finger on the " "sensor and try again.\n"); break; + case FP_ENROLL_RETRY_REMOVE_FINGER: + printf("Scan failed, please remove your finger and then try " + "again.\n"); + break; } - } while (status != FP_ENROLL_COMPLETE); + } while (r != FP_ENROLL_COMPLETE); if (!enrolled_print) { fprintf(stderr, "Enroll complete but no print?\n"); return NULL; } - printf("got a print!\n"); + printf("Enrollment completed!\n"); return enrolled_print; } diff --git a/libfprint/core.c b/libfprint/core.c index 02c0e864..2e4697d8 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -18,10 +18,11 @@ */ #include +#include +#include #include #include -#include #include "fp_internal.h" @@ -227,18 +228,18 @@ API_EXPORTED const char *fp_driver_get_full_name(const struct fp_driver *drv) return drv->full_name; } -API_EXPORTED enum fp_enroll_status fp_enroll_finger(struct fp_dev *dev, +API_EXPORTED int fp_enroll_finger(struct fp_dev *dev, struct fp_print_data **print_data) { const struct fp_driver *drv = dev->drv; - enum fp_enroll_status ret; + int ret; int stage = dev->__enroll_stage; gboolean initial = FALSE; if (!dev->nr_enroll_stages || !drv->enroll) { fp_err("driver %s has 0 enroll stages or no enroll func", - dev->drv->name); - return FP_ENROLL_FAIL; + drv->name); + return -ENOTSUP; } if (stage == -1) { @@ -248,13 +249,19 @@ API_EXPORTED enum fp_enroll_status fp_enroll_finger(struct fp_dev *dev, if (stage >= dev->nr_enroll_stages) { fp_err("exceeding number of enroll stages for device claimed by " - "driver %s (%d stages)", dev->drv->name, dev->nr_enroll_stages); - return FP_ENROLL_FAIL; + "driver %s (%d stages)", drv->name, dev->nr_enroll_stages); + dev->__enroll_stage = -1; + return -EINVAL; } fp_dbg("%s will handle enroll stage %d/%d%s", drv->name, stage, dev->nr_enroll_stages - 1, initial ? " (initial)" : ""); ret = drv->enroll(dev, initial, stage, print_data); + if (ret < 0) { + fp_err("enroll failed with code %d", ret); + dev->__enroll_stage = -1; + return ret; + } switch (ret) { case FP_ENROLL_PASS: fp_dbg("enroll stage passed"); @@ -273,6 +280,9 @@ API_EXPORTED enum fp_enroll_status fp_enroll_finger(struct fp_dev *dev, case FP_ENROLL_RETRY_CENTER_FINGER: fp_dbg("finger was not centered, enroll should retry"); break; + case FP_ENROLL_RETRY_REMOVE_FINGER: + fp_dbg("scan failed, remove finger and retry"); + break; case FP_ENROLL_FAIL: fp_err("enroll failed"); dev->__enroll_stage = -1; @@ -280,7 +290,7 @@ API_EXPORTED enum fp_enroll_status fp_enroll_finger(struct fp_dev *dev, default: fp_err("unrecognised return code %d", ret); dev->__enroll_stage = -1; - return FP_ENROLL_FAIL; + return -EINVAL; } return ret; } diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index c83e200e..c05807b3 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -461,7 +461,6 @@ static int dev_init(struct fp_dev *dev) goto err; } - seq = 0; dummy = 0x04; r = send_cmd28(dev, 0x06, &dummy, 1); if (r < 0) @@ -523,7 +522,7 @@ static const unsigned char scan_comp[] = { 0x12, 0xff, 0xff, 0xff, 0xff /* scan completion, prefixes print data */ }; -static enum fp_enroll_status enroll(struct fp_dev *dev, gboolean initial, +static int enroll(struct fp_dev *dev, gboolean initial, int stage, struct fp_print_data **_data) { unsigned char poll_data[] = { 0x30, 0x01 }; @@ -537,11 +536,11 @@ static enum fp_enroll_status enroll(struct fp_dev *dev, gboolean initial, r = send_cmd28(dev, 0x02, (unsigned char *) enroll_init, sizeof(enroll_init)); if (r < 0) - return FP_ENROLL_FAIL; + return r; /* FIXME: protocol misunderstanding here. device receives response * to subcmd 0 after submitting subcmd 2? */ if (read_msg28(dev, 0x00, NULL, NULL) < 0) - return FP_ENROLL_FAIL; + return -EPROTO; } while (!result) { @@ -551,12 +550,12 @@ static enum fp_enroll_status enroll(struct fp_dev *dev, gboolean initial, if (r < 0) return r; if (read_msg28(dev, 0x00, &data, &data_len) < 0) - return FP_ENROLL_FAIL; + return -EPROTO; if (data_len != 14) { fp_err("received 3001 poll response of %d bytes?", data_len); g_free(data); - return FP_ENROLL_FAIL; + return -EPROTO; } status = data[5]; @@ -573,9 +572,11 @@ static enum fp_enroll_status enroll(struct fp_dev *dev, gboolean initial, result = FP_ENROLL_PASS; break; case 0x1c: /* FIXME what does this one mean? */ - case 0x0f: /* scan taking too long, remove finger and try again */ result = FP_ENROLL_RETRY; break; + case 0x0f: /* scan taking too long, remove finger and try again */ + result = FP_ENROLL_RETRY_REMOVE_FINGER; + break; case 0x1e: /* swipe too short */ result = FP_ENROLL_RETRY_TOO_SHORT; break; @@ -583,6 +584,9 @@ static enum fp_enroll_status enroll(struct fp_dev *dev, gboolean initial, result = FP_ENROLL_RETRY_CENTER_FINGER; break; case 0x20: + /* finger scanned successfully */ + /* don't break out immediately, need to look at the next + * value to determine if enrollment is complete or not */ passed = 1; break; case 0x00: @@ -591,12 +595,10 @@ static enum fp_enroll_status enroll(struct fp_dev *dev, gboolean initial, break; default: fp_err("unrecognised scan status code %02x", status); - result = FP_ENROLL_FAIL; + result = -EPROTO; break; } - - if (result != FP_ENROLL_COMPLETE) - g_free(data); + g_free(data); } /* FIXME: need to extend protocol research to handle the case when @@ -612,26 +614,30 @@ static enum fp_enroll_status enroll(struct fp_dev *dev, gboolean initial, /* FIXME: protocol misunderstanding here. device receives response * to subcmd 0 after submitting subcmd 2? */ if (read_msg28(dev, 0x02, &data, &data_len) < 0) - return FP_ENROLL_FAIL; + return -EPROTO; if (data_len < sizeof(scan_comp)) { fp_err("fingerprint data too short (%d bytes)", data_len); - return FP_ENROLL_FAIL; + result = -EPROTO; + goto comp_out; } if (memcmp(data, scan_comp, sizeof(scan_comp)) != 0) { fp_err("unrecognised data prefix %x %x %x %x %x", data[0], data[1], data[2], data[3], data[4]); - return FP_ENROLL_FAIL; + result = -EPROTO; + goto comp_out; } if (!_data) { fp_err("complete but no data storage!"); - return FP_ENROLL_COMPLETE; + result = FP_ENROLL_COMPLETE; + goto comp_out; } fdata = fpi_print_data_new(dev, data_len - sizeof(scan_comp)); buf = fpi_print_data_get_buffer(fdata); memcpy(buf, data + sizeof(scan_comp), data_len - sizeof(scan_comp)); *_data = fdata; +comp_out: g_free(data); } diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 39ba08ae..35a26d72 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -96,8 +96,8 @@ struct fp_driver { /* Device operations */ int (*init)(struct fp_dev *dev); void (*exit)(struct fp_dev *dev); - enum fp_enroll_status (*enroll)(struct fp_dev *dev, gboolean initial, - int stage, struct fp_print_data **print_data); + int (*enroll)(struct fp_dev *dev, gboolean initial, int stage, + struct fp_print_data **print_data); }; extern const struct fp_driver upekts_driver; diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 721cf02b..7c6473d2 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -41,18 +41,18 @@ int fp_dev_get_nr_enroll_stages(struct fp_dev *dev); const char *fp_driver_get_name(const struct fp_driver *drv); const char *fp_driver_get_full_name(const struct fp_driver *drv); -/* Enrolment */ -enum fp_enroll_status { +/* Enrollment */ +enum fp_enroll_result { FP_ENROLL_COMPLETE = 1, FP_ENROLL_FAIL, FP_ENROLL_PASS, - FP_ENROLL_RETRY, + FP_ENROLL_RETRY = 100, FP_ENROLL_RETRY_TOO_SHORT, FP_ENROLL_RETRY_CENTER_FINGER, + FP_ENROLL_RETRY_REMOVE_FINGER, }; -enum fp_enroll_status fp_enroll_finger(struct fp_dev *dev, - struct fp_print_data **print_data); +int fp_enroll_finger(struct fp_dev *dev, struct fp_print_data **print_data); /* Data handling */ void fp_print_data_free(struct fp_print_data *data); From 68bdfc7868f8a0467da58cba4796a44569f806b9 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sun, 14 Oct 2007 00:58:45 +0100 Subject: [PATCH 016/184] Verification infrastructure Similar model to enrollment. --- examples/verify.c | 56 +++++++++++++++++++++++++++++++++++++++-- libfprint/core.c | 33 ++++++++++++++++++++++++ libfprint/fp_internal.h | 1 + libfprint/fprint.h | 12 +++++++++ 4 files changed, 100 insertions(+), 2 deletions(-) diff --git a/examples/verify.c b/examples/verify.c index 07c0c2ce..825b6090 100644 --- a/examples/verify.c +++ b/examples/verify.c @@ -85,10 +85,45 @@ struct fp_print_data *enroll(struct fp_dev *dev) { return NULL; } - printf("Enrollment completed!\n"); + printf("Enrollment completed!\n\n"); return enrolled_print; } +int verify(struct fp_dev *dev, struct fp_print_data *data) +{ + int r; + + do { + sleep(1); + printf("\nScan your finger now.\n"); + r = fp_verify_finger(dev, data); + if (r < 0) { + printf("verification failed with error %d :(\n", r); + return r; + } + switch (r) { + case FP_VERIFY_NO_MATCH: + printf("NO MATCH!\n"); + return 0; + case FP_VERIFY_MATCH: + printf("MATCH!\n"); + return 0; + case FP_VERIFY_RETRY: + printf("Scan didn't quite work. Please try again.\n"); + break; + case FP_VERIFY_RETRY_TOO_SHORT: + printf("Swipe was too short, please try again.\n"); + break; + case FP_VERIFY_RETRY_CENTER_FINGER: + printf("Please center your finger on the sensor and try again.\n"); + break; + case FP_VERIFY_RETRY_REMOVE_FINGER: + printf("Please remove finger from the sensor and try again.\n"); + break; + } + } while (1); +} + int main(void) { int r; @@ -128,7 +163,24 @@ int main(void) if (!data) goto out_close; - ret = 0; + + printf("Normally we'd save that print to disk, and recall it at some " + "point later when we want to authenticate the user who just " + "enrolled. In the interests of demonstration, we'll authenticate " + "that user immediately.\n"); + + do { + char buffer[20]; + + verify(dev, data); + printf("Verify again? [Y/n]? "); + fgets(buffer, sizeof(buffer), stdin); + buffer[sizeof(buffer) - 1] = 0; /* null-terminate */ + if (buffer[0] != '\n' && buffer[0] != 'y' && buffer[0] != 'Y') + break; + } while (1); + + fp_print_data_free(data); out_close: fp_dev_close(dev); return ret; diff --git a/libfprint/core.c b/libfprint/core.c index 2e4697d8..b10ceb67 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -295,6 +295,39 @@ API_EXPORTED int fp_enroll_finger(struct fp_dev *dev, return ret; } +API_EXPORTED int fp_verify_finger(struct fp_dev *dev, + struct fp_print_data *enrolled_print) +{ + const struct fp_driver *drv = dev->drv; + int r; + + if (!enrolled_print) { + fp_err("no print given"); + return -EINVAL; + } + + if (!drv->verify) { + fp_err("driver %s has no verify func", drv->name); + return -EINVAL; + } + + if (!fpi_print_data_compatible(dev, enrolled_print)) { + fp_err("print is not compatible with device"); + return -EINVAL; + } + + fp_dbg("to be handled by %s", drv->name); + r = drv->verify(dev, enrolled_print); + if (r < 0) + fp_dbg("verify error %d", r); + else if (r == 0) + fp_dbg("result: no match"); + else + fp_dbg("result: match"); + + return r; +} + API_EXPORTED int fp_init(void) { fp_dbg(""); diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 35a26d72..45b2cc86 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -98,6 +98,7 @@ struct fp_driver { void (*exit)(struct fp_dev *dev); int (*enroll)(struct fp_dev *dev, gboolean initial, int stage, struct fp_print_data **print_data); + int (*verify)(struct fp_dev *dev, struct fp_print_data *data); }; extern const struct fp_driver upekts_driver; diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 7c6473d2..fce42838 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -54,6 +54,18 @@ enum fp_enroll_result { int fp_enroll_finger(struct fp_dev *dev, struct fp_print_data **print_data); +/* Verification */ +enum fp_verify_result { + FP_VERIFY_NO_MATCH = 0, + FP_VERIFY_MATCH = 1, + FP_VERIFY_RETRY = FP_ENROLL_RETRY, + FP_VERIFY_RETRY_TOO_SHORT = FP_ENROLL_RETRY_TOO_SHORT, + FP_VERIFY_RETRY_CENTER_FINGER = FP_ENROLL_RETRY_CENTER_FINGER, + FP_VERIFY_RETRY_REMOVE_FINGER = FP_ENROLL_RETRY_REMOVE_FINGER, +}; + +int fp_verify_finger(struct fp_dev *dev, struct fp_print_data *enrolled_print); + /* Data handling */ void fp_print_data_free(struct fp_print_data *data); From f59112d57cf008969d074ff4ffa5f31c5d29a099 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 15 Oct 2007 22:07:22 +0100 Subject: [PATCH 017/184] Unhide fprint_data buffer from drivers May as well keep things out in the open. --- libfprint/data.c | 5 ----- libfprint/drivers/upekts.c | 4 +--- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/libfprint/data.c b/libfprint/data.c index 9f940b83..4201665c 100644 --- a/libfprint/data.c +++ b/libfprint/data.c @@ -33,11 +33,6 @@ struct fp_print_data *fpi_print_data_new(struct fp_dev *dev, size_t length) return data; } -unsigned char *fpi_print_data_get_buffer(struct fp_print_data *data) -{ - return data->buffer; -} - API_EXPORTED void fp_print_data_free(struct fp_print_data *data) { g_free(data); diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index c05807b3..a2d32800 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -606,7 +606,6 @@ static int enroll(struct fp_dev *dev, gboolean initial, if (result == FP_ENROLL_COMPLETE) { struct fp_print_data *fdata; - unsigned char *buf; r = send_cmd28(dev, 0x00, poll_data, sizeof(poll_data)); if (r < 0) @@ -634,8 +633,7 @@ static int enroll(struct fp_dev *dev, gboolean initial, } fdata = fpi_print_data_new(dev, data_len - sizeof(scan_comp)); - buf = fpi_print_data_get_buffer(fdata); - memcpy(buf, data + sizeof(scan_comp), data_len - sizeof(scan_comp)); + memcpy(fdata->buffer, data + sizeof(scan_comp), data_len - sizeof(scan_comp)); *_data = fdata; comp_out: g_free(data); From bf9ce44f43c013a3822fe63a5214faf946a2ce8b Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 15 Oct 2007 22:09:46 +0100 Subject: [PATCH 018/184] upekts: verify implementation We can now verify live fingerprints using the verify example. Error handling during verification needs to be improved. --- libfprint/drivers/upekts.c | 128 ++++++++++++++++++++++++++++++++++++- 1 file changed, 125 insertions(+), 3 deletions(-) diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index a2d32800..305001ad 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -522,10 +522,12 @@ static const unsigned char scan_comp[] = { 0x12, 0xff, 0xff, 0xff, 0xff /* scan completion, prefixes print data */ }; +/* used for enrollment and verification */ +static const unsigned char poll_data[] = { 0x30, 0x01 }; + static int enroll(struct fp_dev *dev, gboolean initial, int stage, struct fp_print_data **_data) { - unsigned char poll_data[] = { 0x30, 0x01 }; unsigned char *data; size_t data_len; int r; @@ -539,6 +541,8 @@ static int enroll(struct fp_dev *dev, gboolean initial, return r; /* FIXME: protocol misunderstanding here. device receives response * to subcmd 0 after submitting subcmd 2? */ + /* actually this is probably a poll response? does the above cmd + * include a 30 01 poll somewhere? */ if (read_msg28(dev, 0x00, NULL, NULL) < 0) return -EPROTO; } @@ -546,7 +550,8 @@ static int enroll(struct fp_dev *dev, gboolean initial, while (!result) { unsigned char status; - r = send_cmd28(dev, 0x00, poll_data, sizeof(poll_data)); + r = send_cmd28(dev, 0x00, (unsigned char *) poll_data, + sizeof(poll_data)); if (r < 0) return r; if (read_msg28(dev, 0x00, &data, &data_len) < 0) @@ -607,7 +612,8 @@ static int enroll(struct fp_dev *dev, gboolean initial, if (result == FP_ENROLL_COMPLETE) { struct fp_print_data *fdata; - r = send_cmd28(dev, 0x00, poll_data, sizeof(poll_data)); + r = send_cmd28(dev, 0x00, (unsigned char *) poll_data, + sizeof(poll_data)); if (r < 0) return r; /* FIXME: protocol misunderstanding here. device receives response @@ -642,6 +648,121 @@ comp_out: return result; } +static const unsigned char verify_hdr[] = { + 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0xc0, 0xd4, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, + 0x00 +}; + +static int verify(struct fp_dev *dev, struct fp_print_data *print) +{ + size_t data_len = sizeof(verify_hdr) + print->length; + unsigned char *data; + int r; + unsigned char status; + gboolean need_poll = FALSE; + gboolean done = FALSE; + + if (data_len > 255) { + fp_err("file too long!\n"); + return -EINVAL; + } + + data = g_malloc(data_len); + memcpy(data, verify_hdr, sizeof(verify_hdr)); + memcpy(data + sizeof(verify_hdr), print->buffer, print->length); + + r = send_cmd28(dev, 0x03, data, data_len); + if (r < 0) + return r; + g_free(data); + + while (!done) { + if (need_poll) { + r = send_cmd28(dev, 0x00, (unsigned char *) poll_data, + sizeof(poll_data)); + if (r < 0) + return r; + } else { + need_poll = TRUE; + } + if (read_msg28(dev, 0x00, &data, &data_len) < 0) + return -EPROTO; + + if (data_len != 14) { + fp_err("received 3001 poll response of %d bytes?", data_len); + r = -EPROTO; + goto out; + } + + status = data[5]; + fp_dbg("poll result = %02x", status); + + /* These codes indicate that we're waiting for a finger scan, so poll + * again */ + switch (status) { + case 0x0c: /* no news, poll again */ + break; + case 0x20: + fp_dbg("processing scan for verification"); + break; + case 0x00: + fp_dbg("good image"); + done = TRUE; + break; + case 0x1c: /* FIXME what does this one mean? */ + r = FP_VERIFY_RETRY; + goto out; + case 0x0f: /* scan taking too long, remove finger and try again */ + r = FP_VERIFY_RETRY_REMOVE_FINGER; + goto out; + case 0x1e: /* swipe too short */ + r = FP_VERIFY_RETRY_TOO_SHORT; + goto out; + case 0x24: /* finger not centered */ + r = FP_VERIFY_RETRY_CENTER_FINGER; + goto out; + default: + fp_err("unrecognised verify status code %02x", status); + r = -EPROTO; + goto out; + } + g_free(data); + } + + if (status == 0x00) { + /* poll again for verify result */ + r = send_cmd28(dev, 0x00, (unsigned char *) poll_data, + sizeof(poll_data)); + if (r < 0) + return r; + if (read_msg28(dev, 0x03, &data, &data_len) < 0) + return -EPROTO; + if (data_len < 2) { + fp_err("verify result abnormally short!"); + r = -EPROTO; + goto out; + } + if (data[0] != 0x12) { + fp_err("unexpected verify header byte %02x", data[0]); + r = -EPROTO; + goto out; + } + if (data[1] == 0x00) { + r = FP_VERIFY_NO_MATCH; + } else if (data[1] == 0x01) { + r = FP_VERIFY_MATCH; + } else { + fp_err("unrecognised verify result %02x", data[1]); + r = -EPROTO; + goto out; + } + } + +out: + g_free(data); + return r; +} static const struct usb_id id_table[] = { { .vendor = 0x0483, .product = 0x2016 }, @@ -655,5 +776,6 @@ const struct fp_driver upekts_driver = { .init = dev_init, .exit = dev_exit, .enroll = enroll, + .verify = verify, }; From 10bb96a0dfd9dfb50e870499661f2adf8050f11f Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 15 Oct 2007 22:16:22 +0100 Subject: [PATCH 019/184] Rename verify to verify_live ...to make way for an enroll example which stores on disk, and a verify example that loads from disk. --- TODO | 3 --- examples/Makefile.am | 6 +++--- examples/{verify.c => verify_live.c} | 0 3 files changed, 3 insertions(+), 6 deletions(-) rename examples/{verify.c => verify_live.c} (100%) diff --git a/TODO b/TODO index 730ad015..4ddda910 100644 --- a/TODO +++ b/TODO @@ -1,9 +1,7 @@ LIBRARY ======= -debugging messages fingerprint data classifcation by device or device type storage mechanism -verification imaging support external imaging APIs identification @@ -12,7 +10,6 @@ test suite against NFIQ compliance set DRIVERS ======= -UPEK TouchStrip driver Sunplus 895 driver AES3501 driver AES4000 driver diff --git a/examples/Makefile.am b/examples/Makefile.am index 5b676c62..fa58c783 100644 --- a/examples/Makefile.am +++ b/examples/Makefile.am @@ -1,6 +1,6 @@ INCLUDES = -I$(top_srcdir) -noinst_PROGRAMS = verify +noinst_PROGRAMS = verify_live -verify_SOURCES = verify.c -verify_LDADD = ../libfprint/libfprint.la -lfprint +verify_live_SOURCES = verify_live.c +verify_live_LDADD = ../libfprint/libfprint.la -lfprint diff --git a/examples/verify.c b/examples/verify_live.c similarity index 100% rename from examples/verify.c rename to examples/verify_live.c From 3b8f8c195cc49532669cce859be7969ff5813611 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Tue, 16 Oct 2007 13:41:23 +0100 Subject: [PATCH 020/184] upekts: support large messages Add support for messages with a length greater than 255. Also picked out a few more retry codes. --- libfprint/drivers/upekts.c | 56 ++++++++++++++++++++------------------ 1 file changed, 30 insertions(+), 26 deletions(-) diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index 305001ad..f1ddad46 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -95,9 +95,10 @@ static uint16_t udf_crc(unsigned char *buffer, size_t size) * Byte-wise: * 'C' 'i' 'a' 'o' A B L C1 C2 * - * Ciao prefixes all messages. L is the length of the data, is L bytes - * long. C1 and C2 are the UDF-CRC16 for the whole message minus the Ciao - * prefix. + * Ciao prefixes all messages. The rightmost 4 bits of B become the uppermost + * 4 bits of L, and when combined with the lower 8 bits listed as 'L', L is + * the length of the data, is L bytes long. C1 and C2 are the + * UDF-CRC16 for the whole message minus the Ciao prefix. * * When the device wants to command the driver to do something, it sends * a message where B=0 and A!=0. The A value indicates the type of command. @@ -114,11 +115,11 @@ static uint16_t udf_crc(unsigned char *buffer, size_t size) * When the driver is sending commands as above, and when the device is * responding, the seems to follow this structure: * - * 28 L 0 0 0 S + * 28 L1 L2 0 0 S * * Where the length of is L-3, and S is some kind of subcommand - * code. In the device's response to a command, the subcommand code will be - * unchanged. + * code. L1 is the least significant bits of L, L2 is the most significant. In + * the device's response to a command, the subcommand code will be unchanged. * * After deducing and documenting the above, I found a few places where the * above doesn't hold true. Those are marked with FIXME's below. @@ -127,13 +128,13 @@ static uint16_t udf_crc(unsigned char *buffer, size_t size) #define CMD_SEQ_INCREMENT 0x10 static int send_cmd(struct fp_dev *dev, unsigned char seq_a, - unsigned char seq_b, unsigned char *data, uint8_t len) + unsigned char seq_b, unsigned char *data, uint16_t len) { int r; uint16_t crc; - /* 9 bytes extra for: 4 byte 'Ciao', 1 byte A, 1 byte B, 1 byte length, - * 2 byte CRC */ + /* 9 bytes extra for: 4 byte 'Ciao', 1 byte A, 1 byte B | lenHI, + * 1 byte lenLO, 2 byte CRC */ size_t urblen = len + 9; unsigned char *buf; @@ -146,9 +147,10 @@ static int send_cmd(struct fp_dev *dev, unsigned char seq_a, /* Write header */ strncpy(buf, "Ciao", 4); + len = cpu_to_le16(len); buf[4] = seq_a; - buf[5] = seq_b; - buf[6] = len; + buf[5] = seq_b | ((len & 0xf00) >> 8); + buf[6] = len & 0x00ff; /* Copy data */ if (data) @@ -173,7 +175,7 @@ static int send_cmd(struct fp_dev *dev, unsigned char seq_a, } static int send_cmd28(struct fp_dev *dev, unsigned char subcmd, - unsigned char *data, uint8_t innerlen) + unsigned char *data, uint16_t innerlen) { size_t len = innerlen + 6; unsigned char *buf = g_malloc0(len); @@ -183,8 +185,10 @@ static int send_cmd28(struct fp_dev *dev, unsigned char subcmd, fp_dbg("seq=%02x subcmd=%02x with %d bytes of data", seq, subcmd, innerlen); + innerlen = cpu_to_le16(innerlen + 3); buf[0] = 0x28; - buf[1] = innerlen + 3; + buf[1] = innerlen & 0x00ff; + buf[2] = (innerlen & 0xff00) >> 8; buf[5] = subcmd; memcpy(buf + 6, data, innerlen); @@ -210,7 +214,7 @@ static unsigned char *__read_msg(struct fp_dev *dev, size_t *data_len) unsigned char *buf = g_malloc(MSG_READ_BUF_SIZE); size_t buf_size = MSG_READ_BUF_SIZE; uint16_t computed_crc, msg_crc; - uint8_t len; + uint16_t len; int r; r = usb_bulk_read(dev->udev, EP_IN, buf, buf_size, TIMEOUT); @@ -227,7 +231,7 @@ static unsigned char *__read_msg(struct fp_dev *dev, size_t *data_len) goto err; } - len = buf[6]; + len = le16_to_cpu(((buf[5] & 0xf) << 8) | buf[6]); if (r != MSG_READ_BUF_SIZE && (len + 9) < r) { /* Check that the length claimed inside the message is in line with @@ -285,7 +289,7 @@ static enum read_msg_status read_msg(struct fp_dev *dev, uint8_t *seq, size_t buf_size; unsigned char code_a; unsigned char code_b; - uint8_t len; + uint16_t len; enum read_msg_status ret = READ_MSG_ERROR; retry: @@ -294,8 +298,8 @@ retry: return READ_MSG_ERROR; code_a = buf[4]; - code_b = buf[5]; - len = buf[6]; + code_b = buf[5] & 0xf0; + len = le16_to_cpu(((buf[5] & 0xf) << 8) | buf[6]); fp_dbg("A=%02x B=%02x len=%d", code_a, code_b, len); if (code_a && !code_b) { @@ -324,7 +328,7 @@ retry: /* device sends response to a previously executed command */ unsigned char *innerbuf = buf + 7; unsigned char _subcmd; - uint8_t innerlen; + uint16_t innerlen; if (len < 6) { fp_err("cmd response too short (%d)", len); @@ -334,12 +338,13 @@ retry: fp_err("cmd response without 28 byte?"); goto out; } - if (innerbuf[2] || innerbuf[3] || innerbuf[4]) { + if (innerbuf[3] || innerbuf[4]) { fp_err("non-zero bytes in cmd response"); goto out; } - innerlen = innerbuf[1] - 3; + innerlen = innerbuf[1] | (innerbuf[2] << 8); + innerlen = le16_to_cpu(innerlen) - 3; _subcmd = innerbuf[5]; fp_dbg("device responds to subcmd %x with %d bytes", _subcmd, innerlen); if (seq) @@ -577,6 +582,8 @@ static int enroll(struct fp_dev *dev, gboolean initial, result = FP_ENROLL_PASS; break; case 0x1c: /* FIXME what does this one mean? */ + case 0x0b: /* FIXME what does this one mean? */ + case 0x23: /* FIXME what does this one mean? */ result = FP_ENROLL_RETRY; break; case 0x0f: /* scan taking too long, remove finger and try again */ @@ -663,11 +670,6 @@ static int verify(struct fp_dev *dev, struct fp_print_data *print) gboolean need_poll = FALSE; gboolean done = FALSE; - if (data_len > 255) { - fp_err("file too long!\n"); - return -EINVAL; - } - data = g_malloc(data_len); memcpy(data, verify_hdr, sizeof(verify_hdr)); memcpy(data + sizeof(verify_hdr), print->buffer, print->length); @@ -711,6 +713,8 @@ static int verify(struct fp_dev *dev, struct fp_print_data *print) done = TRUE; break; case 0x1c: /* FIXME what does this one mean? */ + case 0x0b: /* FIXME what does this one mean? */ + case 0x23: /* FIXME what does this one mean? */ r = FP_VERIFY_RETRY; goto out; case 0x0f: /* scan taking too long, remove finger and try again */ From 680142f268ad8bdfd0cbcbd6654f2e0dc2d20187 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Tue, 16 Oct 2007 14:23:30 +0100 Subject: [PATCH 021/184] storage: add save/load functionality Prints can now be saved to disk (but you currently must classify which finger they are) and you can load them later. Added 2 simple example programs to demonstrate this. --- examples/Makefile.am | 8 ++- examples/enroll.c | 147 +++++++++++++++++++++++++++++++++++++++++ examples/verify.c | 138 ++++++++++++++++++++++++++++++++++++++ examples/verify_live.c | 4 +- libfprint/data.c | 119 +++++++++++++++++++++++++++++++++ libfprint/fprint.h | 17 +++++ 6 files changed, 429 insertions(+), 4 deletions(-) create mode 100644 examples/enroll.c create mode 100644 examples/verify.c diff --git a/examples/Makefile.am b/examples/Makefile.am index fa58c783..708a378d 100644 --- a/examples/Makefile.am +++ b/examples/Makefile.am @@ -1,6 +1,12 @@ INCLUDES = -I$(top_srcdir) -noinst_PROGRAMS = verify_live +noinst_PROGRAMS = verify_live enroll verify verify_live_SOURCES = verify_live.c verify_live_LDADD = ../libfprint/libfprint.la -lfprint +enroll_SOURCES = enroll.c +enroll_LDADD = ../libfprint/libfprint.la -lfprint + +verify_SOURCES = verify.c +verify_LDADD = ../libfprint/libfprint.la -lfprint + diff --git a/examples/enroll.c b/examples/enroll.c new file mode 100644 index 00000000..3ed5c8a0 --- /dev/null +++ b/examples/enroll.c @@ -0,0 +1,147 @@ +/* + * Example fingerprint enrollment program + * Enrolls your right index finger and saves the print to disk + * Copyright (C) 2007 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include +#include + +#include + +struct fp_dscv_dev *discover_device(struct fp_dscv_dev **discovered_devs) +{ + struct fp_dscv_dev *ddev = NULL; + int i; + + for (i = 0; ddev = discovered_devs[i]; i++) { + const struct fp_driver *drv = fp_dscv_dev_get_driver(ddev); + printf("Found device claimed by %s driver\n", + fp_driver_get_full_name(drv)); + return ddev; + } + + return ddev; +} + +struct fp_print_data *enroll(struct fp_dev *dev) { + struct fp_print_data *enrolled_print = NULL; + int r; + + printf("You will need to successfully scan your finger %d times to " + "complete the process.\n", fp_dev_get_nr_enroll_stages(dev)); + + do { + sleep(1); + printf("\nScan your finger now.\n"); + r = fp_enroll_finger(dev, &enrolled_print); + if (r < 0) { + printf("Enroll failed with error %d\n", r); + return NULL; + } + switch (r) { + case FP_ENROLL_COMPLETE: + printf("Enroll complete!\n"); + break; + case FP_ENROLL_FAIL: + printf("Enroll failed, something wen't wrong :(\n"); + return NULL; + case FP_ENROLL_PASS: + printf("Enroll stage passed. Yay!\n"); + break; + case FP_ENROLL_RETRY: + printf("Didn't quite catch that. Please try again.\n"); + break; + case FP_ENROLL_RETRY_TOO_SHORT: + printf("Your swipe was too short, please try again.\n"); + break; + case FP_ENROLL_RETRY_CENTER_FINGER: + printf("Didn't catch that, please center your finger on the " + "sensor and try again.\n"); + break; + case FP_ENROLL_RETRY_REMOVE_FINGER: + printf("Scan failed, please remove your finger and then try " + "again.\n"); + break; + } + } while (r != FP_ENROLL_COMPLETE); + + if (!enrolled_print) { + fprintf(stderr, "Enroll complete but no print?\n"); + return NULL; + } + + printf("Enrollment completed!\n\n"); + return enrolled_print; +} + +int main(void) +{ + int r; + struct fp_dscv_dev *ddev; + struct fp_dscv_dev **discovered_devs; + struct fp_dev *dev; + struct fp_print_data *data; + + printf("This program will enroll your right index finger, " + "unconditionally overwriting any right-index print that was enrolled " + "previously. If you want to continue, press enter, otherwise hit " + "Ctrl+C\n"); + getchar(); + + r = fp_init(); + if (r < 0) { + fprintf(stderr, "Failed to initialize libfprint\n"); + exit(1); + } + + discovered_devs = fp_discover_devs(); + if (!discovered_devs) { + fprintf(stderr, "Could not discover devices\n"); + exit(1); + } + + ddev = discover_device(discovered_devs); + if (!ddev) { + fprintf(stderr, "No devices detected.\n"); + exit(1); + } + + dev = fp_dev_open(ddev); + fp_dscv_devs_free(discovered_devs); + if (!dev) { + fprintf(stderr, "Could not open device.\n"); + exit(1); + } + + printf("Opened device. It's now time to enroll your finger.\n\n"); + data = enroll(dev); + if (!data) + goto out_close; + + r = fp_print_data_save(data, RIGHT_INDEX); + if (r < 0) + fprintf(stderr, "Data save failed, code %d\n", r); + + fp_print_data_free(data); +out_close: + fp_dev_close(dev); + return r; +} + + diff --git a/examples/verify.c b/examples/verify.c new file mode 100644 index 00000000..3837c6a5 --- /dev/null +++ b/examples/verify.c @@ -0,0 +1,138 @@ +/* + * Example fingerprint verification program, which verifies the right index + * finger which has been previously enrolled to disk. + * Copyright (C) 2007 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include +#include + +#include + +struct fp_dscv_dev *discover_device(struct fp_dscv_dev **discovered_devs) +{ + struct fp_dscv_dev *ddev = NULL; + int i; + + for (i = 0; ddev = discovered_devs[i]; i++) { + const struct fp_driver *drv = fp_dscv_dev_get_driver(ddev); + printf("Found device claimed by %s driver\n", + fp_driver_get_full_name(drv)); + return ddev; + } + + return ddev; +} + +int verify(struct fp_dev *dev, struct fp_print_data *data) +{ + int r; + + do { + sleep(1); + printf("\nScan your finger now.\n"); + r = fp_verify_finger(dev, data); + if (r < 0) { + printf("verification failed with error %d :(\n", r); + return r; + } + switch (r) { + case FP_VERIFY_NO_MATCH: + printf("NO MATCH!\n"); + return 0; + case FP_VERIFY_MATCH: + printf("MATCH!\n"); + return 0; + case FP_VERIFY_RETRY: + printf("Scan didn't quite work. Please try again.\n"); + break; + case FP_VERIFY_RETRY_TOO_SHORT: + printf("Swipe was too short, please try again.\n"); + break; + case FP_VERIFY_RETRY_CENTER_FINGER: + printf("Please center your finger on the sensor and try again.\n"); + break; + case FP_VERIFY_RETRY_REMOVE_FINGER: + printf("Please remove finger from the sensor and try again.\n"); + break; + } + } while (1); +} + +int main(void) +{ + int r; + struct fp_dscv_dev *ddev; + struct fp_dscv_dev **discovered_devs; + struct fp_dev *dev; + struct fp_print_data *data; + + r = fp_init(); + if (r < 0) { + fprintf(stderr, "Failed to initialize libfprint\n"); + exit(1); + } + + discovered_devs = fp_discover_devs(); + if (!discovered_devs) { + fprintf(stderr, "Could not discover devices\n"); + exit(1); + } + + ddev = discover_device(discovered_devs); + if (!ddev) { + fprintf(stderr, "No devices detected.\n"); + exit(1); + } + + dev = fp_dev_open(ddev); + fp_dscv_devs_free(discovered_devs); + if (!dev) { + fprintf(stderr, "Could not open device.\n"); + exit(1); + } + + printf("Opened device. Loading previously enrolled right index finger " + "data...\n"); + + r = fp_print_data_load(dev, RIGHT_INDEX, &data); + if (r != 0) { + fprintf(stderr, "Failed to load fingerprint, error %d\n", r); + fprintf(stderr, "Did you remember to enroll your right index finger " + "first?\n"); + goto out_close; + } + + printf("Print loaded. Time to verify!\n"); + do { + char buffer[20]; + + verify(dev, data); + printf("Verify again? [Y/n]? "); + fgets(buffer, sizeof(buffer), stdin); + if (buffer[0] != '\n' && buffer[0] != 'y' && buffer[0] != 'Y') + break; + } while (1); + + fp_print_data_free(data); +out_close: + fp_dev_close(dev); + return r; +} + + diff --git a/examples/verify_live.c b/examples/verify_live.c index 825b6090..50dbe962 100644 --- a/examples/verify_live.c +++ b/examples/verify_live.c @@ -127,7 +127,6 @@ int verify(struct fp_dev *dev, struct fp_print_data *data) int main(void) { int r; - int ret = 1; struct fp_dscv_dev *ddev; struct fp_dscv_dev **discovered_devs; struct fp_dev *dev; @@ -175,7 +174,6 @@ int main(void) verify(dev, data); printf("Verify again? [Y/n]? "); fgets(buffer, sizeof(buffer), stdin); - buffer[sizeof(buffer) - 1] = 0; /* null-terminate */ if (buffer[0] != '\n' && buffer[0] != 'y' && buffer[0] != 'Y') break; } while (1); @@ -183,7 +181,7 @@ int main(void) fp_print_data_free(data); out_close: fp_dev_close(dev); - return ret; + return r; } diff --git a/libfprint/data.c b/libfprint/data.c index 4201665c..ebfde409 100644 --- a/libfprint/data.c +++ b/libfprint/data.c @@ -18,12 +18,55 @@ */ #include +#include #include +#include +#include +#include #include #include "fp_internal.h" +#define DIR_PERMS 0700 + +/* FIXME: should free this during library shutdown */ +static char *base_store = NULL; + +static void storage_setup(void) +{ + const char *homedir; + + homedir = g_getenv("HOME"); + if (!homedir) + homedir = g_get_home_dir(); + if (!homedir) + return; + + base_store = g_build_filename(homedir, ".fprint/prints", NULL); + g_mkdir_with_parents(base_store, DIR_PERMS); + /* FIXME handle failure */ +} + +static const char *finger_code_to_str(enum fp_finger finger) +{ + const char *names[] = { + [LEFT_THUMB] = "lthu", + [LEFT_INDEX] = "lind", + [LEFT_MIDDLE] = "lmid", + [LEFT_RING] = "lrin", + [LEFT_LITTLE] = "llit", + [RIGHT_THUMB] = "rthu", + [RIGHT_INDEX] = "rind", + [RIGHT_MIDDLE] = "rmid", + [RIGHT_RING] = "rrin", + [RIGHT_LITTLE] = "rlit", + }; + if (finger < LEFT_THUMB || finger > RIGHT_LITTLE) + return NULL; + return names[finger]; +} + struct fp_print_data *fpi_print_data_new(struct fp_dev *dev, size_t length) { struct fp_print_data *data = g_malloc(sizeof(*data) + length); @@ -33,6 +76,82 @@ struct fp_print_data *fpi_print_data_new(struct fp_dev *dev, size_t length) return data; } +API_EXPORTED int fp_print_data_save(struct fp_print_data *data, + enum fp_finger finger) +{ + GError *err = NULL; + char *path; + char *dirpath; + const char *fingerstr = finger_code_to_str(finger); + int r; + + if (!fingerstr) + return -EINVAL; + + if (!base_store) + storage_setup(); + + fp_dbg("save %s print from %s", fingerstr, data->driver_name); + dirpath = g_build_filename(base_store, data->driver_name, NULL); + r = g_mkdir_with_parents(dirpath, DIR_PERMS); + if (r < 0) { + fp_err("couldn't create storage directory"); + g_free(dirpath); + return r; + } + + path = g_build_filename(dirpath, fingerstr, NULL); + fp_dbg("saving to %s", path); + g_file_set_contents(path, data->buffer, data->length, &err); + g_free(dirpath); + g_free(path); + if (err) { + r = err->code; + fp_err("%s save failed: %s", fingerstr, err->message); + g_error_free(err); + return r; + } + + return 0; +} + +API_EXPORTED int fp_print_data_load(struct fp_dev *dev, + enum fp_finger finger, struct fp_print_data **data) +{ + const char *fingerstr = finger_code_to_str(finger); + gchar *path; + gsize length; + gchar *contents; + GError *err = NULL; + struct fp_print_data *fdata; + + if (!fingerstr) + return -EINVAL; + + if (!base_store) + storage_setup(); + + path = g_build_filename(base_store, dev->drv->name, fingerstr, NULL); + fp_dbg("from %s", path); + g_file_get_contents(path, &contents, &length, &err); + g_free(path); + if (err) { + int r = err->code; + fp_err("%s load failed: %s", fingerstr, err->message); + g_error_free(err); + if (r == G_FILE_ERROR_NOENT) + return -ENOENT; + else + return r; + } + + fdata = fpi_print_data_new(dev, length); + memcpy(fdata->buffer, contents, length); + g_free(contents); + *data = fdata; + return 0; +} + API_EXPORTED void fp_print_data_free(struct fp_print_data *data) { g_free(data); diff --git a/libfprint/fprint.h b/libfprint/fprint.h index fce42838..8f7984fd 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -26,6 +26,20 @@ struct fp_dev; struct fp_driver; struct fp_print_data; +/* misc/general stuff */ +enum fp_finger { + LEFT_THUMB = 1, + LEFT_INDEX, + LEFT_MIDDLE, + LEFT_RING, + LEFT_LITTLE, + RIGHT_THUMB, + RIGHT_INDEX, + RIGHT_MIDDLE, + RIGHT_RING, + RIGHT_LITTLE, +}; + /* Device discovery */ struct fp_dscv_dev **fp_discover_devs(void); void fp_dscv_devs_free(struct fp_dscv_dev **devs); @@ -67,6 +81,9 @@ enum fp_verify_result { int fp_verify_finger(struct fp_dev *dev, struct fp_print_data *enrolled_print); /* Data handling */ +int fp_print_data_load(struct fp_dev *dev, enum fp_finger finger, + struct fp_print_data **data); +int fp_print_data_save(struct fp_print_data *data, enum fp_finger finger); void fp_print_data_free(struct fp_print_data *data); /* Library */ From 801fcfc07ce3cee36ce8c16e8e4fa26d22ae8db3 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Tue, 16 Oct 2007 14:34:47 +0100 Subject: [PATCH 022/184] upekts: fix memory corruption Found by valgrind --- libfprint/drivers/upekts.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index f1ddad46..2724a17f 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -177,6 +177,7 @@ static int send_cmd(struct fp_dev *dev, unsigned char seq_a, static int send_cmd28(struct fp_dev *dev, unsigned char subcmd, unsigned char *data, uint16_t innerlen) { + uint16_t _innerlen = innerlen; size_t len = innerlen + 6; unsigned char *buf = g_malloc0(len); struct upekts_dev *upekdev = dev->priv; @@ -185,10 +186,10 @@ static int send_cmd28(struct fp_dev *dev, unsigned char subcmd, fp_dbg("seq=%02x subcmd=%02x with %d bytes of data", seq, subcmd, innerlen); - innerlen = cpu_to_le16(innerlen + 3); + _innerlen = cpu_to_le16(innerlen + 3); buf[0] = 0x28; - buf[1] = innerlen & 0x00ff; - buf[2] = (innerlen & 0xff00) >> 8; + buf[1] = _innerlen & 0x00ff; + buf[2] = (_innerlen & 0xff00) >> 8; buf[5] = subcmd; memcpy(buf + 6, data, innerlen); From c97f4bb1a721c7cee3acd8dec081a3f0fb86a5bb Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Tue, 16 Oct 2007 14:35:33 +0100 Subject: [PATCH 023/184] Fix verify debug messages Teach it about the various error conditions. --- libfprint/core.c | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/libfprint/core.c b/libfprint/core.c index b10ceb67..e1315c8a 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -318,12 +318,34 @@ API_EXPORTED int fp_verify_finger(struct fp_dev *dev, fp_dbg("to be handled by %s", drv->name); r = drv->verify(dev, enrolled_print); - if (r < 0) + if (r < 0) { fp_dbg("verify error %d", r); - else if (r == 0) + return r; + } + + switch (r) { + case FP_VERIFY_NO_MATCH: fp_dbg("result: no match"); - else + break; + case FP_VERIFY_MATCH: fp_dbg("result: match"); + break; + case FP_VERIFY_RETRY: + fp_dbg("verify should retry"); + break; + case FP_VERIFY_RETRY_TOO_SHORT: + fp_dbg("swipe was too short, verify should retry"); + break; + case FP_VERIFY_RETRY_CENTER_FINGER: + fp_dbg("finger was not centered, verify should retry"); + break; + case FP_VERIFY_RETRY_REMOVE_FINGER: + fp_dbg("scan failed, remove finger and retry"); + break; + default: + fp_err("unrecognised return code %d", r); + return -EINVAL; + } return r; } From 2709c6dc8c2429c3202b88b709593376d69392e5 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Tue, 23 Oct 2007 23:24:21 +0100 Subject: [PATCH 024/184] Basic image driver foundations The basic model is that image drivers declare a fp_img_driver structure rather than a fp_driver struct. fp_img_driver will contain primitive imaging operations such as 'scan finger and return image'. The imgdev layer will generically implement the primitive fp_driver operations, and the imgdev layer will fix up the enroll/verify/etc pointers at driver registration time. Removed const from all fp_driver declarations, as these are now modified dynamically in the case of imaging drivers. --- examples/enroll.c | 2 +- examples/verify.c | 2 +- examples/verify_live.c | 2 +- libfprint/Makefile.am | 1 + libfprint/core.c | 38 ++++++++++++++++++++++++-------------- libfprint/drivers/upekts.c | 2 +- libfprint/fp_internal.h | 23 ++++++++++++++++++++--- libfprint/fprint.h | 8 ++++---- libfprint/imgdev.c | 29 +++++++++++++++++++++++++++++ 9 files changed, 82 insertions(+), 25 deletions(-) create mode 100644 libfprint/imgdev.c diff --git a/examples/enroll.c b/examples/enroll.c index 3ed5c8a0..a1062f82 100644 --- a/examples/enroll.c +++ b/examples/enroll.c @@ -30,7 +30,7 @@ struct fp_dscv_dev *discover_device(struct fp_dscv_dev **discovered_devs) int i; for (i = 0; ddev = discovered_devs[i]; i++) { - const struct fp_driver *drv = fp_dscv_dev_get_driver(ddev); + struct fp_driver *drv = fp_dscv_dev_get_driver(ddev); printf("Found device claimed by %s driver\n", fp_driver_get_full_name(drv)); return ddev; diff --git a/examples/verify.c b/examples/verify.c index 3837c6a5..42b07bbf 100644 --- a/examples/verify.c +++ b/examples/verify.c @@ -30,7 +30,7 @@ struct fp_dscv_dev *discover_device(struct fp_dscv_dev **discovered_devs) int i; for (i = 0; ddev = discovered_devs[i]; i++) { - const struct fp_driver *drv = fp_dscv_dev_get_driver(ddev); + struct fp_driver *drv = fp_dscv_dev_get_driver(ddev); printf("Found device claimed by %s driver\n", fp_driver_get_full_name(drv)); return ddev; diff --git a/examples/verify_live.c b/examples/verify_live.c index 50dbe962..5f3932b7 100644 --- a/examples/verify_live.c +++ b/examples/verify_live.c @@ -29,7 +29,7 @@ struct fp_dscv_dev *discover_device(struct fp_dscv_dev **discovered_devs) int i; for (i = 0; ddev = discovered_devs[i]; i++) { - const struct fp_driver *drv = fp_dscv_dev_get_driver(ddev); + struct fp_driver *drv = fp_dscv_dev_get_driver(ddev); printf("Found device claimed by %s driver\n", fp_driver_get_full_name(drv)); return ddev; diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 9790fbe8..3d84d105 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -11,5 +11,6 @@ libfprint_la_LIBADD = $(LIBUSB_LIBS) $(GLIB_LIBS) libfprint_la_SOURCES = \ core.c \ data.c \ + imgdev.c \ $(DRIVER_SRC) diff --git a/libfprint/core.c b/libfprint/core.c index e1315c8a..24a9adc5 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -67,30 +67,40 @@ void fpi_log(enum fpi_log_level level, const char *component, fprintf(stream, "\n"); } -static void register_driver(const struct fp_driver *drv) +static void register_driver(struct fp_driver *drv) { registered_drivers = g_list_prepend(registered_drivers, (gpointer) drv); fp_dbg("registered driver %s", drv->name); } -static const struct fp_driver * const drivers[] = { +static struct fp_driver * const primitive_drivers[] = { &upekts_driver, }; +static struct fp_img_driver * const img_drivers[] = { + &uru4000_driver, +}; + static void register_drivers(void) { unsigned int i; - for (i = 0; i < ARRAY_SIZE(drivers); i++) - register_driver(drivers[i]); + for (i = 0; i < ARRAY_SIZE(primitive_drivers); i++) + register_driver(primitive_drivers[i]); + + for (i = 0; i < ARRAY_SIZE(img_drivers); i++) { + struct fp_img_driver *imgdriver = img_drivers[i]; + fpi_img_driver_setup(imgdriver); + register_driver(&imgdriver->driver); + } } -static const struct fp_driver *find_supporting_driver(struct usb_device *udev) +static struct fp_driver *find_supporting_driver(struct usb_device *udev) { GList *elem = registered_drivers; do { - const struct fp_driver *drv = elem->data; + struct fp_driver *drv = elem->data; const struct usb_id *id; for (id = drv->id_table; id->vendor; id++) @@ -125,7 +135,7 @@ API_EXPORTED struct fp_dscv_dev **fp_discover_devs(void) * sets of drivers against small sets of USB devices */ for (bus = usb_get_busses(); bus; bus = bus->next) for (udev = bus->devices; udev; udev = udev->next) { - const struct fp_driver *drv = find_supporting_driver(udev); + struct fp_driver *drv = find_supporting_driver(udev); struct fp_dscv_dev *ddev; if (!drv) continue; @@ -163,7 +173,7 @@ API_EXPORTED void fp_dscv_devs_free(struct fp_dscv_dev **devs) g_free(devs); } -API_EXPORTED const struct fp_driver *fp_dscv_dev_get_driver(struct fp_dscv_dev *dev) +API_EXPORTED struct fp_driver *fp_dscv_dev_get_driver(struct fp_dscv_dev *dev) { return dev->drv; } @@ -171,7 +181,7 @@ API_EXPORTED const struct fp_driver *fp_dscv_dev_get_driver(struct fp_dscv_dev * API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) { struct fp_dev *dev; - const struct fp_driver *drv = ddev->drv; + struct fp_driver *drv = ddev->drv; int r; usb_dev_handle *udevh = usb_open(ddev->udev); @@ -208,7 +218,7 @@ API_EXPORTED void fp_dev_close(struct fp_dev *dev) g_free(dev); } -API_EXPORTED const struct fp_driver *fp_dev_get_driver(struct fp_dev *dev) +API_EXPORTED struct fp_driver *fp_dev_get_driver(struct fp_dev *dev) { return dev->drv; } @@ -218,12 +228,12 @@ API_EXPORTED int fp_dev_get_nr_enroll_stages(struct fp_dev *dev) return dev->nr_enroll_stages; } -API_EXPORTED const char *fp_driver_get_name(const struct fp_driver *drv) +API_EXPORTED const char *fp_driver_get_name(struct fp_driver *drv) { return drv->name; } -API_EXPORTED const char *fp_driver_get_full_name(const struct fp_driver *drv) +API_EXPORTED const char *fp_driver_get_full_name(struct fp_driver *drv) { return drv->full_name; } @@ -231,7 +241,7 @@ API_EXPORTED const char *fp_driver_get_full_name(const struct fp_driver *drv) API_EXPORTED int fp_enroll_finger(struct fp_dev *dev, struct fp_print_data **print_data) { - const struct fp_driver *drv = dev->drv; + struct fp_driver *drv = dev->drv; int ret; int stage = dev->__enroll_stage; gboolean initial = FALSE; @@ -298,7 +308,7 @@ API_EXPORTED int fp_enroll_finger(struct fp_dev *dev, API_EXPORTED int fp_verify_finger(struct fp_dev *dev, struct fp_print_data *enrolled_print) { - const struct fp_driver *drv = dev->drv; + struct fp_driver *drv = dev->drv; int r; if (!enrolled_print) { diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index 2724a17f..fe9042ce 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -774,7 +774,7 @@ static const struct usb_id id_table[] = { { 0, 0, 0, }, /* terminating entry */ }; -const struct fp_driver upekts_driver = { +struct fp_driver upekts_driver = { .name = FP_COMPONENT, .full_name = "UPEK TouchStrip", .id_table = id_table, diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 45b2cc86..686d707c 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -72,7 +72,7 @@ void fpi_log(enum fpi_log_level, const char *component, const char *function, #define fp_err(fmt...) _fpi_log(LOG_LEVEL_ERROR, fmt) struct fp_dev { - const struct fp_driver *drv; + struct fp_driver *drv; usb_dev_handle *udev; void *priv; @@ -88,10 +88,18 @@ struct usb_id { unsigned long driver_data; }; +enum fp_driver_type { + DRIVER_PRIMITIVE = 0, + DRIVER_IMAGING = 1, +}; + struct fp_driver { const char *name; const char *full_name; const struct usb_id * const id_table; + enum fp_driver_type type; + + void *priv; /* Device operations */ int (*init)(struct fp_dev *dev); @@ -101,11 +109,20 @@ struct fp_driver { int (*verify)(struct fp_dev *dev, struct fp_print_data *data); }; -extern const struct fp_driver upekts_driver; +struct fp_img_driver { + struct fp_driver driver; + + /* Device operations */ +}; + +extern struct fp_driver upekts_driver; +extern struct fp_img_driver uru4000_driver; + +void fpi_img_driver_setup(struct fp_img_driver *idriver); struct fp_dscv_dev { struct usb_device *udev; - const struct fp_driver *drv; + struct fp_driver *drv; }; struct fp_print_data { diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 8f7984fd..bcc9845d 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -43,17 +43,17 @@ enum fp_finger { /* Device discovery */ struct fp_dscv_dev **fp_discover_devs(void); void fp_dscv_devs_free(struct fp_dscv_dev **devs); -const struct fp_driver *fp_dscv_dev_get_driver(struct fp_dscv_dev *dev); +struct fp_driver *fp_dscv_dev_get_driver(struct fp_dscv_dev *dev); /* Device handling */ struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev); void fp_dev_close(struct fp_dev *dev); -const struct fp_driver *fp_dev_get_driver(struct fp_dev *dev); +struct fp_driver *fp_dev_get_driver(struct fp_dev *dev); int fp_dev_get_nr_enroll_stages(struct fp_dev *dev); /* Drivers */ -const char *fp_driver_get_name(const struct fp_driver *drv); -const char *fp_driver_get_full_name(const struct fp_driver *drv); +const char *fp_driver_get_name(struct fp_driver *drv); +const char *fp_driver_get_full_name(struct fp_driver *drv); /* Enrollment */ enum fp_enroll_result { diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c new file mode 100644 index 00000000..7071f11b --- /dev/null +++ b/libfprint/imgdev.c @@ -0,0 +1,29 @@ +/* + * Core imaging functions for libfprint + * Copyright (C) 2007 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include + +#include "fp_internal.h" + +void fpi_img_driver_setup(struct fp_img_driver *idriver) +{ + idriver->driver.type = DRIVER_IMAGING; + /* FIXME fill in primitive operations */ +} + From 0ac74ef649802000da82bb1bddf8c1637c515de6 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Thu, 25 Oct 2007 15:00:30 +0100 Subject: [PATCH 025/184] Pass driver_data from ID table to driver init function --- libfprint/core.c | 10 +++++++--- libfprint/drivers/upekts.c | 2 +- libfprint/fp_internal.h | 3 ++- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/libfprint/core.c b/libfprint/core.c index 24a9adc5..5b2a3c78 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -95,7 +95,8 @@ static void register_drivers(void) } } -static struct fp_driver *find_supporting_driver(struct usb_device *udev) +static struct fp_driver *find_supporting_driver(struct usb_device *udev, + unsigned long *driver_data) { GList *elem = registered_drivers; @@ -108,6 +109,7 @@ static struct fp_driver *find_supporting_driver(struct usb_device *udev) udev->descriptor.idProduct == id->product) { fp_dbg("driver %s supports USB device %04x:%04x", drv->name, id->vendor, id->product); + *driver_data = id->driver_data; return drv; } } while (elem = g_list_next(elem)); @@ -135,13 +137,15 @@ API_EXPORTED struct fp_dscv_dev **fp_discover_devs(void) * sets of drivers against small sets of USB devices */ for (bus = usb_get_busses(); bus; bus = bus->next) for (udev = bus->devices; udev; udev = udev->next) { - struct fp_driver *drv = find_supporting_driver(udev); + unsigned long driver_data; + struct fp_driver *drv = find_supporting_driver(udev, &driver_data); struct fp_dscv_dev *ddev; if (!drv) continue; ddev = g_malloc0(sizeof(*ddev)); ddev->drv = drv; ddev->udev = udev; + ddev->driver_data = driver_data; tmplist = g_list_prepend(tmplist, (gpointer) ddev); dscv_count++; } @@ -196,7 +200,7 @@ API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) dev->__enroll_stage = -1; if (drv->init) { - r = drv->init(dev); + r = drv->init(dev, ddev->driver_data); if (r) { fp_err("device initialisation failed, driver=%s", drv->name); usb_close(udevh); diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index fe9042ce..b0bb09d8 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -420,7 +420,7 @@ static const unsigned char init28_0b[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00 }; -static int dev_init(struct fp_dev *dev) +static int dev_init(struct fp_dev *dev, unsigned long driver_data) { struct upekts_dev *upekdev; unsigned char dummy = 0x10; diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 686d707c..c017f137 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -102,7 +102,7 @@ struct fp_driver { void *priv; /* Device operations */ - int (*init)(struct fp_dev *dev); + int (*init)(struct fp_dev *dev, unsigned long driver_data); void (*exit)(struct fp_dev *dev); int (*enroll)(struct fp_dev *dev, gboolean initial, int stage, struct fp_print_data **print_data); @@ -123,6 +123,7 @@ void fpi_img_driver_setup(struct fp_img_driver *idriver); struct fp_dscv_dev { struct usb_device *udev; struct fp_driver *drv; + unsigned long driver_data; }; struct fp_print_data { From 0aac3706d707b26f478656282d2d7dce47e3adbf Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Thu, 25 Oct 2007 15:35:10 +0100 Subject: [PATCH 026/184] upekts: release interface on error condition and normal exit --- libfprint/drivers/upekts.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index b0bb09d8..be958e34 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -32,6 +32,7 @@ #include #include +#include #include @@ -422,7 +423,7 @@ static const unsigned char init28_0b[] = { static int dev_init(struct fp_dev *dev, unsigned long driver_data) { - struct upekts_dev *upekdev; + struct upekts_dev *upekdev = NULL; unsigned char dummy = 0x10; enum read_msg_status msgstat; uint8_t seq; @@ -434,8 +435,10 @@ static int dev_init(struct fp_dev *dev, unsigned long driver_data) r = usb_control_msg(dev->udev, USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0x0c, 0x100, 0x400, &dummy, sizeof(dummy), TIMEOUT); - if (r < 0) - return r; + if (r < 0) { + fp_dbg("control write failed\n"); + goto err; + } upekdev = g_malloc(sizeof(*upekdev)); upekdev->seq = 0xf0; /* incremented to 0x00 before first cmd */ @@ -504,7 +507,9 @@ static int dev_init(struct fp_dev *dev, unsigned long driver_data) return 0; err: + usb_release_interface(dev->udev, 0); g_free(upekdev); + return -EPROTO; } @@ -518,6 +523,7 @@ static void dev_exit(struct fp_dev *dev) // FIXME should read msg A=01 + usb_release_interface(dev->udev, 0); g_free(dev->priv); } From f3a838e856423af802de1d777a19163843cdf635 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 27 Oct 2007 00:06:53 +0100 Subject: [PATCH 027/184] Initial implementation for image device access and capture Also added new example: img_capture --- TODO | 3 -- examples/Makefile.am | 5 +- examples/img_capture.c | 100 +++++++++++++++++++++++++++++++++++++ libfprint/Makefile.am | 1 + libfprint/core.c | 9 +++- libfprint/fp_internal.h | 33 +++++++++++- libfprint/fprint.h | 12 +++++ libfprint/img.c | 106 +++++++++++++++++++++++++++++++++++++++ libfprint/imgdev.c | 108 +++++++++++++++++++++++++++++++++++++++- 9 files changed, 369 insertions(+), 8 deletions(-) create mode 100644 examples/img_capture.c create mode 100644 libfprint/img.c diff --git a/TODO b/TODO index 4ddda910..d33bc883 100644 --- a/TODO +++ b/TODO @@ -1,9 +1,6 @@ LIBRARY ======= fingerprint data classifcation by device or device type -storage mechanism -imaging support -external imaging APIs identification external API documentation test suite against NFIQ compliance set diff --git a/examples/Makefile.am b/examples/Makefile.am index 708a378d..d7d47063 100644 --- a/examples/Makefile.am +++ b/examples/Makefile.am @@ -1,5 +1,5 @@ INCLUDES = -I$(top_srcdir) -noinst_PROGRAMS = verify_live enroll verify +noinst_PROGRAMS = verify_live enroll verify img_capture verify_live_SOURCES = verify_live.c verify_live_LDADD = ../libfprint/libfprint.la -lfprint @@ -10,3 +10,6 @@ enroll_LDADD = ../libfprint/libfprint.la -lfprint verify_SOURCES = verify.c verify_LDADD = ../libfprint/libfprint.la -lfprint +img_capture_SOURCES = img_capture.c +img_capture_LDADD = ../libfprint/libfprint.la -lfprint + diff --git a/examples/img_capture.c b/examples/img_capture.c new file mode 100644 index 00000000..6edc191b --- /dev/null +++ b/examples/img_capture.c @@ -0,0 +1,100 @@ +/* + * Example libfprint image capture program + * Copyright (C) 2007 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include + +#include + +struct fp_dscv_dev *discover_device(struct fp_dscv_dev **discovered_devs) +{ + struct fp_dscv_dev *ddev = NULL; + int i; + + for (i = 0; ddev = discovered_devs[i]; i++) { + struct fp_driver *drv = fp_dscv_dev_get_driver(ddev); + printf("Found device claimed by %s driver\n", + fp_driver_get_full_name(drv)); + return ddev; + } + + return ddev; +} + +int main(void) +{ + int r = 1; + struct fp_dscv_dev *ddev; + struct fp_dscv_dev **discovered_devs; + struct fp_dev *dev; + struct fp_img_dev *imgdev; + struct fp_img *img = NULL; + + r = fp_init(); + if (r < 0) { + fprintf(stderr, "Failed to initialize libfprint\n"); + exit(1); + } + + discovered_devs = fp_discover_devs(); + if (!discovered_devs) { + fprintf(stderr, "Could not discover devices\n"); + exit(1); + } + + ddev = discover_device(discovered_devs); + if (!ddev) { + fprintf(stderr, "No devices detected.\n"); + exit(1); + } + + dev = fp_dev_open(ddev); + fp_dscv_devs_free(discovered_devs); + if (!dev) { + fprintf(stderr, "Could not open device.\n"); + exit(1); + } + + imgdev = fp_dev_to_img_dev(dev); + if (!imgdev) { + fprintf(stderr, "could not get image dev, is this an imaging " + "device?\n"); + goto out_close; + } + + printf("Opened device. It's now time to scan your finger.\n\n"); + + r = fp_imgdev_capture(imgdev, 0, &img); + if (r) { + fprintf(stderr, "image capture failed, code %d\n", r); + goto out_close; + } + + r = fp_img_save_to_file(img, "finger.pgm"); + if (r) { + fprintf(stderr, "img save failed, code %d\n", r); + goto out_close; + } + + r = 0; +out_close: + fp_dev_close(dev); + return r; +} + diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 3d84d105..5ffb8d63 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -11,6 +11,7 @@ libfprint_la_LIBADD = $(LIBUSB_LIBS) $(GLIB_LIBS) libfprint_la_SOURCES = \ core.c \ data.c \ + img.c \ imgdev.c \ $(DRIVER_SRC) diff --git a/libfprint/core.c b/libfprint/core.c index 5b2a3c78..ff8850ab 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -193,7 +193,7 @@ API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) fp_err("usb_open failed"); return NULL; } - + dev = g_malloc0(sizeof(*dev)); dev->drv = drv; dev->udev = udevh; @@ -242,6 +242,13 @@ API_EXPORTED const char *fp_driver_get_full_name(struct fp_driver *drv) return drv->full_name; } +API_EXPORTED struct fp_img_dev *fp_dev_to_img_dev(struct fp_dev *dev) +{ + if (dev->drv->type != DRIVER_IMAGING) + return NULL; + return dev->priv; +} + API_EXPORTED int fp_enroll_finger(struct fp_dev *dev, struct fp_print_data **print_data) { diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index c017f137..e8aeb2e4 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -41,6 +41,10 @@ #define ARRAY_SIZE(a) (sizeof(a) / sizeof(*a)) +#define container_of(ptr, type, member) ({ \ + const typeof( ((type *)0)->member ) *__mptr = (ptr); \ + (type *)( (char *)__mptr - offsetof(type,member) );}) + enum fpi_log_level { LOG_LEVEL_DEBUG, LOG_LEVEL_INFO, @@ -82,6 +86,12 @@ struct fp_dev { int __enroll_stage; }; +struct fp_img_dev { + struct fp_dev *dev; + usb_dev_handle *udev; + void *priv; +}; + struct usb_id { uint16_t vendor; uint16_t product; @@ -109,10 +119,20 @@ struct fp_driver { int (*verify)(struct fp_dev *dev, struct fp_print_data *data); }; +/* flags for fp_img_driver.flags */ +#define FP_IMGDRV_SUPPORTS_UNCONDITIONAL_CAPTURE (1 << 0) + struct fp_img_driver { struct fp_driver driver; + uint16_t flags; /* Device operations */ + int (*init)(struct fp_img_dev *dev, unsigned long driver_data); + void (*exit)(struct fp_img_dev *dev); + int (*await_finger_on)(struct fp_img_dev *dev); + int (*await_finger_off)(struct fp_img_dev *dev); + int (*capture)(struct fp_img_dev *dev, gboolean unconditional, + struct fp_img **image); }; extern struct fp_driver upekts_driver; @@ -133,9 +153,20 @@ struct fp_print_data { }; struct fp_print_data *fpi_print_data_new(struct fp_dev *dev, size_t length); -unsigned char *fpi_print_data_get_buffer(struct fp_print_data *data); int fpi_print_data_compatible(struct fp_dev *dev, struct fp_print_data *data); +struct fp_img { + int width; + int height; + size_t length; + unsigned char data[0]; +}; + +struct fp_img *fpi_img_new(size_t length); +struct fp_img *fpi_img_new_dims(int width, int height); +struct fp_img *fpi_img_resize(struct fp_img *img, size_t newsize); +gboolean fpi_img_is_sane(struct fp_img *img); + #define bswap16(x) (((x & 0xff) << 8) | (x >> 8)) #if __BYTE_ORDER == __LITTLE_ENDIAN #define cpu_to_le16(x) (x) diff --git a/libfprint/fprint.h b/libfprint/fprint.h index bcc9845d..128c0119 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -25,6 +25,7 @@ struct fp_dscv_dev; struct fp_dev; struct fp_driver; struct fp_print_data; +struct fp_img; /* misc/general stuff */ enum fp_finger { @@ -50,6 +51,7 @@ struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev); void fp_dev_close(struct fp_dev *dev); struct fp_driver *fp_dev_get_driver(struct fp_dev *dev); int fp_dev_get_nr_enroll_stages(struct fp_dev *dev); +struct fp_img_dev *fp_dev_to_img_dev(struct fp_dev *dev); /* Drivers */ const char *fp_driver_get_name(struct fp_driver *drv); @@ -86,6 +88,16 @@ int fp_print_data_load(struct fp_dev *dev, enum fp_finger finger, int fp_print_data_save(struct fp_print_data *data, enum fp_finger finger); void fp_print_data_free(struct fp_print_data *data); +/* Imaging devices */ +int fp_imgdev_capture(struct fp_img_dev *imgdev, int unconditional, + struct fp_img **image); + +/* Image handling */ +int fp_img_get_height(struct fp_img *img); +int fp_img_get_width(struct fp_img *img); +unsigned char *fp_img_get_data(struct fp_img *img); +int fp_img_save_to_file(struct fp_img *img, char *path); + /* Library */ int fp_init(void); diff --git a/libfprint/img.c b/libfprint/img.c new file mode 100644 index 00000000..664bbeae --- /dev/null +++ b/libfprint/img.c @@ -0,0 +1,106 @@ +/* + * Image management functions for libfprint + * Copyright (C) 2007 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include +#include +#include + +#include + +#include "fp_internal.h" + +struct fp_img *fpi_img_new(size_t length) +{ + struct fp_img *img = g_malloc(sizeof(*img) + length); + memset(img, 0, sizeof(*img)); + fp_dbg("length=%zd", length); + img->length = length; + return img; +} + +struct fp_img *fpi_img_new_dims(int width, int height) +{ + struct fp_img *img = fpi_img_new(width * height); + img->width = width; + img->height = height; + return img; +} + +gboolean fpi_img_is_sane(struct fp_img *img) +{ + /* basic checks */ + if (!img->length || !img->width || !img->height) + return FALSE; + + /* buffer is big enough? */ + if ((img->length * img->height) < img->length) + return FALSE; + + return TRUE; +} + +struct fp_img *fpi_img_resize(struct fp_img *img, size_t newsize) +{ + return g_realloc(img, sizeof(*img) + newsize); +} + +API_EXPORTED int fp_img_get_height(struct fp_img *img) +{ + return img->height; +} + +API_EXPORTED int fp_img_get_width(struct fp_img *img) +{ + return img->width; +} + +API_EXPORTED unsigned char *fp_img_get_data(struct fp_img *img) +{ + return img->data; +} + +API_EXPORTED int fp_img_save_to_file(struct fp_img *img, char *path) +{ + FILE *fd = fopen(path, "w"); + size_t write_size = img->width * img->height; + int r; + + if (!fd) { + fp_dbg("could not open '%s' for writing: %d", path, errno); + return -errno; + } + + r = fprintf(fd, "P5 %d %d 255\n", img->width, img->height); + if (r < 0) { + fp_err("pgm header write failed, error %d", r); + return r; + } + + r = fwrite(img->data, 1, write_size, fd); + if (r < write_size) { + fp_err("short write (%d)", r); + return -EIO; + } + + fclose(fd); + fp_dbg("written to '%s'", path); + return 0; +} + diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index 7071f11b..be48b860 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -1,5 +1,5 @@ /* - * Core imaging functions for libfprint + * Core imaging device functions for libfprint * Copyright (C) 2007 Daniel Drake * * This library is free software; you can redistribute it and/or @@ -17,13 +17,117 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ +#include #include #include "fp_internal.h" +#define driver_to_img_driver(drv) \ + container_of((drv), struct fp_img_driver, driver) + +static int img_dev_init(struct fp_dev *dev, unsigned long driver_data) +{ + struct fp_img_dev *imgdev = g_malloc0(sizeof(*imgdev)); + struct fp_img_driver *imgdrv = driver_to_img_driver(dev->drv); + int r = 0; + + imgdev->dev = dev; + dev->priv = imgdev; + dev->nr_enroll_stages = 1; + + /* for consistency in driver code, allow udev access through imgdev */ + imgdev->udev = dev->udev; + + if (imgdrv->init) { + r = imgdrv->init(imgdev, driver_data); + if (r) + goto err; + } + + return 0; +err: + g_free(imgdev); + return r; +} + +static void img_dev_exit(struct fp_dev *dev) +{ + struct fp_img_dev *imgdev = dev->priv; + struct fp_img_driver *imgdrv = driver_to_img_driver(dev->drv); + + if (imgdrv->exit) + imgdrv->exit(imgdev); + + g_free(imgdev); +} + +API_EXPORTED int fp_imgdev_capture(struct fp_img_dev *imgdev, + int unconditional, struct fp_img **image) +{ + struct fp_driver *drv = imgdev->dev->drv; + struct fp_img_driver *imgdrv = driver_to_img_driver(drv); + int r; + + if (!image) { + fp_err("no image pointer given"); + return -EINVAL; + } + + if (!imgdrv->capture) { + fp_err("img driver %s has no capture func", drv->name); + return -ENOTSUP; + } + + if (unconditional) { + if (!(imgdrv->flags & FP_IMGDRV_SUPPORTS_UNCONDITIONAL_CAPTURE)) { + fp_dbg("requested unconditional capture, but driver %s does not " + "support it", drv->name); + return -ENOTSUP; + } + } + + fp_dbg("%s will handle capture request", drv->name); + + if (!unconditional && imgdrv->await_finger_on) { + r = imgdrv->await_finger_on(imgdev); + if (r) { + fp_err("await_finger_on failed with error %d", r); + return r; + } + } + + r = imgdrv->capture(imgdev, unconditional, image); + if (r) { + fp_err("capture failed with error %d", r); + return r; + } + + if (!unconditional && imgdrv->await_finger_off) { + r = imgdrv->await_finger_off(imgdev); + if (r) { + fp_err("await_finger_off failed with error %d", r); + return r; + } + } + + if (r == 0) { + if (*image == NULL) { + fp_err("capture succeeded but no image returned?"); + return -ENODATA; + } + if (!fpi_img_is_sane(*image)) { + fp_err("image is not sane!"); + return -EIO; + } + } + + return r; +} + void fpi_img_driver_setup(struct fp_img_driver *idriver) { idriver->driver.type = DRIVER_IMAGING; - /* FIXME fill in primitive operations */ + idriver->driver.init = img_dev_init; + idriver->driver.exit = img_dev_exit; } From f367ae8f4be9dc504d5526d4e74fab497f9f1f59 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 27 Oct 2007 00:09:46 +0100 Subject: [PATCH 028/184] Zero out fprint_data fields on allocation --- libfprint/data.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libfprint/data.c b/libfprint/data.c index ebfde409..6eba48ce 100644 --- a/libfprint/data.c +++ b/libfprint/data.c @@ -70,6 +70,7 @@ static const char *finger_code_to_str(enum fp_finger finger) struct fp_print_data *fpi_print_data_new(struct fp_dev *dev, size_t length) { struct fp_print_data *data = g_malloc(sizeof(*data) + length); + memset(data, 0, sizeof(*data)); fp_dbg("length=%zd", length); data->driver_name = dev->drv->name; data->length = length; @@ -139,6 +140,7 @@ API_EXPORTED int fp_print_data_load(struct fp_dev *dev, int r = err->code; fp_err("%s load failed: %s", fingerstr, err->message); g_error_free(err); + /* FIXME interpret more error codes */ if (r == G_FILE_ERROR_NOENT) return -ENOENT; else From 0ddfef6c21e9944e1ed34e4cbb895e105b82359d Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 27 Oct 2007 00:10:32 +0100 Subject: [PATCH 029/184] Add uru4000 driver --- TODO | 1 - libfprint/Makefile.am | 3 +- libfprint/drivers/uru4000.c | 506 ++++++++++++++++++++++++++++++++++++ 3 files changed, 508 insertions(+), 2 deletions(-) create mode 100644 libfprint/drivers/uru4000.c diff --git a/TODO b/TODO index d33bc883..586e45ac 100644 --- a/TODO +++ b/TODO @@ -11,7 +11,6 @@ Sunplus 895 driver AES3501 driver AES4000 driver ID Mouse driver -DigitalPersona U.are.U 4000/4000B driver Support for 2nd generation MS devices Support for 2nd generation UPEK devices diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 5ffb8d63..bdec4718 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -1,8 +1,9 @@ lib_LTLIBRARIES = libfprint.la UPEKTS_SRC = drivers/upekts.c +URU4000_SRC = drivers/uru4000.c -DRIVER_SRC = $(UPEKTS_SRC) +DRIVER_SRC = $(UPEKTS_SRC) $(URU4000_SRC) libfprint_la_CFLAGS = -fvisibility=hidden $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) $(AM_CFLAGS) libfprint_la_LDFLAGS = -version-info @lt_major@:@lt_revision@:@lt_age@ diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c new file mode 100644 index 00000000..8a324971 --- /dev/null +++ b/libfprint/drivers/uru4000.c @@ -0,0 +1,506 @@ +/* + * Digital Persona U.are.U 4000/4000B driver for libfprint + * Copyright (C) 2007 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#define FP_COMPONENT "uru4000" + +#include +#include +#include + +#include + +#include + +#define EP_INTR (1 | USB_ENDPOINT_IN) +#define EP_DATA (2 | USB_ENDPOINT_IN) +#define USB_RQ 0x04 +#define CTRL_IN (USB_TYPE_VENDOR | USB_ENDPOINT_IN) +#define CTRL_OUT (USB_TYPE_VENDOR | USB_ENDPOINT_OUT) +#define CTRL_TIMEOUT 5000 +#define BULK_TIMEOUT 5000 +#define DATABLK1_RQLEN 0x10000 +#define DATABLK2_RQLEN 0xb340 +#define DATABLK2_EXPECT 0xb1c0 +#define CAPTURE_HDRLEN 64 +#define IRQ_LENGTH 64 +#define IMG_WIDTH 384 +#define IMG_HEIGHT 289 + +enum { + IRQDATA_SCANPWR_ON = 0x56aa, + IRQDATA_FINGER_ON = 0x0101, + IRQDATA_FINGER_OFF = 0x0200, +}; + +enum { + REG_HWSTAT = 0x07, + REG_MODE = 0x4e, +}; + +enum { + MODE_INIT = 0x00, + MODE_AWAIT_FINGER_ON = 0x10, + MODE_AWAIT_FINGER_OFF = 0x12, + MODE_CAPTURE = 0x20, + MODE_SHUT_UP = 0x30, + MODE_READY = 0x80, +}; + +enum { + MS_KBD, + MS_INTELLIMOUSE, + MS_STANDALONE, + MS_STANDALONE_V2, + DP_URU4000, + DP_URU4000B, +}; + +static const struct uru4k_dev_profile { + const char *name; + uint16_t firmware_start; + uint16_t fw_enc_offset; +} uru4k_dev_info[] = { + [MS_KBD] = { + .name = "Microsoft Keyboard with Fingerprint Reader", + .firmware_start = 0x100, + .fw_enc_offset = 0x42b, + }, + [MS_INTELLIMOUSE] = { + .name = "Microsoft Wireless IntelliMouse with Fingerprint Reader", + .firmware_start = 0x100, + .fw_enc_offset = 0x42b, + }, + [MS_STANDALONE] = { + .name = "Microsoft Fingerprint Reader", + .firmware_start = 0x100, + .fw_enc_offset = 0x42b, + }, + [DP_URU4000B] = { + .name = "Digital Persona U.are.U 4000B", + .firmware_start = 0x100, + .fw_enc_offset = 0x42b, + }, +}; + +struct uru4k_dev { + uint8_t interface; +}; + +static int get_hwstat(struct fp_img_dev *dev, unsigned char *data) +{ + int r; + + /* The windows driver uses a request of 0x0c here. We use 0x04 to be + * consistent with every other command we know about. */ + r = usb_control_msg(dev->udev, CTRL_IN, USB_RQ, REG_HWSTAT, 0, + data, 1, CTRL_TIMEOUT); + if (r < 0) { + fp_err("error %d", r); + return r; + } else if (r < 1) { + fp_err("read too short (%d)", r); + return -EIO; + } + + fp_dbg("val=%02x", *data); + return 0; +} + +static int set_hwstat(struct fp_img_dev *dev, unsigned char data) +{ + int r; + fp_dbg("val=%02x", data); + + r = usb_control_msg(dev->udev, CTRL_OUT, USB_RQ, REG_HWSTAT, 0, + &data, 1, CTRL_TIMEOUT); + if (r < 0) { + fp_err("error %d", r); + return r; + } else if (r < 1) { + fp_err("read too short (%d)", r); + return -EIO; + } + + return 0; +} + +static int set_mode(struct fp_img_dev *dev, unsigned char mode) +{ + int r; + + fp_dbg("%02x", mode); + r = usb_control_msg(dev->udev, CTRL_OUT, USB_RQ, REG_MODE, 0, &mode, 1, + CTRL_TIMEOUT); + if (r < 0) { + fp_err("error %d", r); + return r; + } else if (r < 1) { + fp_err("write too short (%d)", r); + return -EIO; + } + + return 0; +} + +static int get_irq(struct fp_img_dev *dev, unsigned char *buf, int timeout) +{ + uint16_t type; + int r; + int infinite_timeout = 0; + + if (timeout == 0) + infinite_timeout = 1; + + /* Darwin and Linux behave inconsistently with regard to infinite timeouts. + * Linux accepts a timeout value of 0 as infinite timeout, whereas darwin + * returns -ETIMEDOUT immediately when a 0 timeout is used. We use a + * looping hack until libusb is fixed. + * See http://thread.gmane.org/gmane.comp.lib.libusb.devel.general/1315 */ + +retry: + r = usb_interrupt_read(dev->udev, EP_INTR, buf, IRQ_LENGTH, 1000); + if (r == -ETIMEDOUT && + ((!infinite_timeout && timeout > 0) || infinite_timeout)) { + fp_dbg("timeout, retry"); + timeout--; + goto retry; + } + + if (r < 0) { + fp_err("interrupt read failed, error %d", r); + return r; + } else if (r < IRQ_LENGTH) { + fp_err("received %d byte IRQ!?", r); + return -EIO; + } + + type = be16_to_cpu(*((uint16_t *) buf)); + fp_dbg("irq type %04x", type); + + return 0; +} + +static int get_irq_with_type(struct fp_img_dev *dev, uint16_t irqtype, + int timeout) +{ + uint16_t hdr; + int discarded = -1; + unsigned char irqbuf[IRQ_LENGTH]; + + fp_dbg("type=%04x", irqtype); + + /* Sometimes we get an interrupt from a previous 'session' indicating + * finger-on-sensor, we ignore this and wait for the real interrupt */ + do { + int r; + discarded++; + + r = get_irq(dev, irqbuf, timeout); + if (r < 0) + return r; + hdr = be16_to_cpu(*((uint16_t *) irqbuf)); + } while (hdr != irqtype); + + if (discarded > 0) + fp_dbg("discarded %d interrupts", discarded); + + return 0; +} + +static int await_finger_on(struct fp_img_dev *dev) +{ + int r; + + r = set_mode(dev, MODE_AWAIT_FINGER_ON); + if (r < 0) + return r; + + return get_irq_with_type(dev, IRQDATA_FINGER_ON, 0); +} + +static int await_finger_off(struct fp_img_dev *dev) +{ + int r; + + r = set_mode(dev, MODE_AWAIT_FINGER_OFF); + if (r < 0) + return r; + + return get_irq_with_type(dev, IRQDATA_FINGER_OFF, 0); +} + +static int capture(struct fp_img_dev *dev, gboolean unconditional, + struct fp_img **ret) +{ + int r; + struct fp_img *img; + size_t image_size = DATABLK1_RQLEN + DATABLK2_EXPECT - CAPTURE_HDRLEN; + + r = set_mode(dev, MODE_CAPTURE); + if (r < 0) + return r; + + /* The image is split up into 2 blocks over 2 USB transactions, which are + * joined contiguously. The image is prepended by a 64 byte header which + * we completely ignore. + * + * We mimic the windows driver behaviour by requesting 0xb340 bytes in the + * 2nd request, but we only expect 0xb1c0 in response. However, our buffers + * must be set up on the offchance that we receive as much data as we + * asked for. */ + + img = fpi_img_new(DATABLK1_RQLEN + DATABLK2_RQLEN); + + r = usb_bulk_read(dev->udev, EP_DATA, img->data, DATABLK1_RQLEN, + BULK_TIMEOUT); + if (r < 0) { + fp_err("part 1 capture failed, error %d", r); + goto err; + } else if (r < DATABLK1_RQLEN) { + fp_err("part 1 capture too short (%d)", r); + r = -EIO; + goto err; + } + + r = usb_bulk_read(dev->udev, EP_DATA, img->data + DATABLK1_RQLEN, + DATABLK2_RQLEN, BULK_TIMEOUT); + if (r < 0) { + fp_err("part 2 capture failed, error %d", r); + goto err; + } else if (r != DATABLK2_EXPECT) { + fp_err("unexpected part 2 capture size (%d)", r); + r = -EIO; + goto err; + } + + /* remove header and shrink allocation */ + g_memmove(img->data, img->data + CAPTURE_HDRLEN, image_size); + img = fpi_img_resize(img, image_size); + img->width = IMG_WIDTH; + img->height = IMG_HEIGHT; + + *ret = img; + return 0; +err: + g_free(img); + return r; +} + +static int do_init(struct fp_img_dev *dev) +{ + unsigned char status; + unsigned char tmp; + int i; + int r; + + r = get_hwstat(dev, &status); + if (r < 0) + return r; + + /* After closing an app and setting hwstat to 0x80, my ms keyboard + * gets in a confused state and returns hwstat 0x85. On next app run, + * we don't get the 56aa interrupt. This is the best way I've found to + * fix it: mess around with hwstat until it starts returning more + * recognisable values. This doesn't happen on my other devices: + * uru4000, uru4000b, ms fp rdr v2 + * The windows driver copes with this OK, but then again it uploads + * firmware right after reading the 0x85 hwstat, allowing some time + * to pass before it attempts to tweak hwstat again... */ + if ((status & 0x84) == 0x84) { + fp_dbg("rebooting device power"); + r = set_hwstat(dev, status & 0xf); + if (r < 0) + return r; + + for (i = 0; i < 100; i++) { + r = get_hwstat(dev, &status); + if (r < 0) + return r; + if (status & 0x1) + break; + usleep(10000); + } + if ((status & 0x1) == 0) { + fp_err("could not reboot device power"); + return -EIO; + } + } + + if ((status & 0x80) == 0) { + status |= 0x80; + r = set_hwstat(dev, status); + if (r < 0) + return r; + } + + /* FIXME fix firmware (disable encryption) */ + + /* Power up device and wait for interrupt notification */ + /* The combination of both modifying firmware *and* doing C-R auth on + * my ms fp v2 device causes us not to get to get the 56aa interrupt and + * for the hwstat write not to take effect. We loop a few times, + * authenticating each time, until the device wakes up. */ + for (i = 0; i < 100; i++) { /* max 1 sec */ + r = set_hwstat(dev, status & 0xf); + if (r < 0) + return r; + + r = get_hwstat(dev, &tmp); + if (r < 0) + return r; + + if ((tmp & 0x80) == 0) + break; + + usleep(10000); + + /* FIXME do C-R auth for v2 devices */ + } + + if (tmp & 0x80) { + fp_err("could not power up device"); + return -EIO; + } + + r = get_irq_with_type(dev, IRQDATA_SCANPWR_ON, 5); + if (r < 0) + return r; + + return 0; +} + +static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) +{ + struct usb_config_descriptor *config; + struct usb_interface *iface = NULL; + struct usb_interface_descriptor *iface_desc; + struct usb_endpoint_descriptor *ep; + struct uru4k_dev *urudev; + int i; + int r; + + /* Find fingerprint interface */ + config = usb_device(dev->udev)->config; + for (i = 0; i < config->bNumInterfaces; i++) { + struct usb_interface *cur_iface = &config->interface[i]; + + if (cur_iface->num_altsetting < 1) + continue; + + iface_desc = &cur_iface->altsetting[0]; + if (iface_desc->bInterfaceClass == 255 + && iface_desc->bInterfaceSubClass == 255 + && iface_desc->bInterfaceProtocol == 255) { + iface = cur_iface; + break; + } + } + + if (iface == NULL) { + fp_err("could not find interface"); + return -ENODEV; + } + + /* Find/check endpoints */ + + if (iface_desc->bNumEndpoints != 2) { + fp_err("found %d endpoints!?", iface_desc->bNumEndpoints); + return -ENODEV; + } + + ep = &iface_desc->endpoint[0]; + if (ep->bEndpointAddress != EP_INTR + || (ep->bmAttributes & USB_ENDPOINT_TYPE_MASK) != + USB_ENDPOINT_TYPE_INTERRUPT) { + fp_err("unrecognised interrupt endpoint"); + return -ENODEV; + } + + ep = &iface_desc->endpoint[1]; + if (ep->bEndpointAddress != EP_DATA + || (ep->bmAttributes & USB_ENDPOINT_TYPE_MASK) != + USB_ENDPOINT_TYPE_BULK) { + fp_err("unrecognised bulk endpoint"); + return -ENODEV; + } + + /* Device looks like a supported reader */ + + r = usb_claim_interface(dev->udev, iface_desc->bInterfaceNumber); + if (r < 0) { + fp_err("interface claim failed"); + return r; + } + + urudev = g_malloc0(sizeof(*urudev)); + urudev->interface = iface_desc->bInterfaceNumber; + dev->priv = urudev; + + r = do_init(dev); + if (r < 0) + goto err; + + return 0; +err: + usb_release_interface(dev->udev, iface_desc->bInterfaceNumber); + g_free(urudev); + return r; +} + +static void dev_exit(struct fp_img_dev *dev) +{ + struct uru4k_dev *urudev = dev->priv; + + set_mode(dev, MODE_INIT); + set_hwstat(dev, 0x80); + usb_release_interface(dev->udev, urudev->interface); + g_free(urudev); +} + +static const struct usb_id id_table[] = { + /* ms kbd with fp rdr */ + { .vendor = 0x045e, .product = 0x00bb, .driver_data = MS_KBD }, + + /* ms intellimouse with fp rdr */ + { .vendor = 0x045e, .product = 0x00bc, .driver_data = MS_INTELLIMOUSE }, + + /* ms fp rdr (standalone) */ + { .vendor = 0x045e, .product = 0x00bd, .driver_data = MS_STANDALONE }, + + /* dp uru4000b (standalone) */ + { .vendor = 0x05ba, .product = 0x000a, .driver_data = DP_URU4000B }, + + /* terminating entry */ + { 0, 0, 0, }, +}; + +struct fp_img_driver uru4000_driver = { + .driver = { + .name = FP_COMPONENT, + .full_name = "Digital Persona U.are.U 4000/4000B", + .id_table = id_table, + }, + .flags = FP_IMGDRV_SUPPORTS_UNCONDITIONAL_CAPTURE, + .init = dev_init, + .exit = dev_exit, + .await_finger_on = await_finger_on, + .await_finger_off = await_finger_off, + .capture = capture, +}; + From 9960a7ff3450fe6df892f794904c8fa2ac398115 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 27 Oct 2007 12:07:11 +0100 Subject: [PATCH 030/184] Image standardization Initially supports flipping and colour inversion --- examples/img_capture.c | 7 +++++ libfprint/drivers/uru4000.c | 1 + libfprint/fp_internal.h | 6 ++++ libfprint/fprint.h | 1 + libfprint/img.c | 60 +++++++++++++++++++++++++++++++++++++ 5 files changed, 75 insertions(+) diff --git a/examples/img_capture.c b/examples/img_capture.c index 6edc191b..1d88fdf4 100644 --- a/examples/img_capture.c +++ b/examples/img_capture.c @@ -92,6 +92,13 @@ int main(void) goto out_close; } + fp_img_standardize(img); + r = fp_img_save_to_file(img, "finger_standardized.pgm"); + if (r) { + fprintf(stderr, "standardized img save failed, code %d\n", r); + goto out_close; + } + r = 0; out_close: fp_dev_close(dev); diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index 8a324971..56e5027a 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -294,6 +294,7 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, img = fpi_img_resize(img, image_size); img->width = IMG_WIDTH; img->height = IMG_HEIGHT; + img->flags = FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED | FP_IMG_COLORS_INVERTED; *ret = img; return 0; diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index e8aeb2e4..537b0d91 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -155,10 +155,16 @@ struct fp_print_data { struct fp_print_data *fpi_print_data_new(struct fp_dev *dev, size_t length); int fpi_print_data_compatible(struct fp_dev *dev, struct fp_print_data *data); +/* bit values for fp_img.flags */ +#define FP_IMG_V_FLIPPED (1<<0) +#define FP_IMG_H_FLIPPED (1<<1) +#define FP_IMG_COLORS_INVERTED (1<<2) + struct fp_img { int width; int height; size_t length; + uint16_t flags; unsigned char data[0]; }; diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 128c0119..541e9762 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -97,6 +97,7 @@ int fp_img_get_height(struct fp_img *img); int fp_img_get_width(struct fp_img *img); unsigned char *fp_img_get_data(struct fp_img *img); int fp_img_save_to_file(struct fp_img *img, char *path); +void fp_img_standardize(struct fp_img *img); /* Library */ int fp_init(void); diff --git a/libfprint/img.c b/libfprint/img.c index 664bbeae..38c492f3 100644 --- a/libfprint/img.c +++ b/libfprint/img.c @@ -104,3 +104,63 @@ API_EXPORTED int fp_img_save_to_file(struct fp_img *img, char *path) return 0; } +static void vflip(struct fp_img *img) +{ + int width = img->width; + int data_len = img->width * img->height; + unsigned char rowbuf[width]; + int i; + + for (i = 0; i < img->height / 2; i++) { + int offset = i * width; + int swap_offset = data_len - (width * (i + 1)); + + /* copy top row into buffer */ + memcpy(rowbuf, img->data + offset, width); + + /* copy lower row over upper row */ + memcpy(img->data + offset, img->data + swap_offset, width); + + /* copy buffer over lower row */ + memcpy(img->data + swap_offset, rowbuf, width); + } +} + +static void hflip(struct fp_img *img) +{ + int width = img->width; + unsigned char rowbuf[width]; + int i, j; + + for (i = 0; i < img->height; i++) { + int offset = i * width; + + memcpy(rowbuf, img->data + offset, width); + for (j = 0; j < width; j++) + img->data[offset + j] = rowbuf[width - j - 1]; + } +} + +static void invert_colors(struct fp_img *img) +{ + int data_len = img->width * img->height; + int i; + for (i = 0; i < data_len; i++) + img->data[i] = 0xff - img->data[i]; +} + +API_EXPORTED void fp_img_standardize(struct fp_img *img) +{ + if (img->flags & FP_IMG_V_FLIPPED) { + vflip(img); + img->flags &= ~FP_IMG_V_FLIPPED; + } + if (img->flags & FP_IMG_H_FLIPPED) { + hflip(img); + img->flags &= ~FP_IMG_H_FLIPPED; + } + if (img->flags & FP_IMG_COLORS_INVERTED) { + invert_colors(img); + img->flags &= ~FP_IMG_COLORS_INVERTED; + } +} From c2a83ec948ffb5604e30cb9cba4f6b71b5ad2b43 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 27 Oct 2007 14:45:14 +0100 Subject: [PATCH 031/184] Improved image dimension handling Drivers now specify the size of the image they provide, and theres an API so that you can get the size of an image before you capture it. --- libfprint/drivers/uru4000.c | 7 +++---- libfprint/fp_internal.h | 2 ++ libfprint/fprint.h | 2 ++ libfprint/imgdev.c | 21 +++++++++++++++++++-- 4 files changed, 26 insertions(+), 6 deletions(-) diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index 56e5027a..f11aa89a 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -39,8 +39,6 @@ #define DATABLK2_EXPECT 0xb1c0 #define CAPTURE_HDRLEN 64 #define IRQ_LENGTH 64 -#define IMG_WIDTH 384 -#define IMG_HEIGHT 289 enum { IRQDATA_SCANPWR_ON = 0x56aa, @@ -292,8 +290,6 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, /* remove header and shrink allocation */ g_memmove(img->data, img->data + CAPTURE_HDRLEN, image_size); img = fpi_img_resize(img, image_size); - img->width = IMG_WIDTH; - img->height = IMG_HEIGHT; img->flags = FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED | FP_IMG_COLORS_INVERTED; *ret = img; @@ -498,6 +494,9 @@ struct fp_img_driver uru4000_driver = { .id_table = id_table, }, .flags = FP_IMGDRV_SUPPORTS_UNCONDITIONAL_CAPTURE, + .img_height = 289, + .img_width = 384, + .init = dev_init, .exit = dev_exit, .await_finger_on = await_finger_on, diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 537b0d91..47eea27d 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -125,6 +125,8 @@ struct fp_driver { struct fp_img_driver { struct fp_driver driver; uint16_t flags; + int img_width; + int img_height; /* Device operations */ int (*init)(struct fp_img_dev *dev, unsigned long driver_data); diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 541e9762..8a10a90e 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -91,6 +91,8 @@ void fp_print_data_free(struct fp_print_data *data); /* Imaging devices */ int fp_imgdev_capture(struct fp_img_dev *imgdev, int unconditional, struct fp_img **image); +int fp_imgdev_get_img_width(struct fp_img_dev *imgdev); +int fp_imgdev_get_img_height(struct fp_img_dev *imgdev); /* Image handling */ int fp_img_get_height(struct fp_img *img); diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index be48b860..e1f4c3ac 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -61,6 +61,20 @@ static void img_dev_exit(struct fp_dev *dev) g_free(imgdev); } +API_EXPORTED int fp_imgdev_get_img_width(struct fp_img_dev *imgdev) +{ + struct fp_driver *drv = imgdev->dev->drv; + struct fp_img_driver *imgdrv = driver_to_img_driver(drv); + return imgdrv->img_width; +} + +API_EXPORTED int fp_imgdev_get_img_height(struct fp_img_dev *imgdev) +{ + struct fp_driver *drv = imgdev->dev->drv; + struct fp_img_driver *imgdrv = driver_to_img_driver(drv); + return imgdrv->img_height; +} + API_EXPORTED int fp_imgdev_capture(struct fp_img_dev *imgdev, int unconditional, struct fp_img **image) { @@ -111,11 +125,14 @@ API_EXPORTED int fp_imgdev_capture(struct fp_img_dev *imgdev, } if (r == 0) { - if (*image == NULL) { + struct fp_img *img = *image; + if (img == NULL) { fp_err("capture succeeded but no image returned?"); return -ENODATA; } - if (!fpi_img_is_sane(*image)) { + img->width = imgdrv->img_width; + img->height = imgdrv->img_height; + if (!fpi_img_is_sane(img)) { fp_err("image is not sane!"); return -EIO; } From da071ff8a2a20984b5f3ea5c355c8a7063f51860 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 27 Oct 2007 15:16:54 +0100 Subject: [PATCH 032/184] Add API for freeing images --- examples/img_capture.c | 1 + libfprint/fprint.h | 1 + libfprint/img.c | 5 +++++ 3 files changed, 7 insertions(+) diff --git a/examples/img_capture.c b/examples/img_capture.c index 1d88fdf4..977113d9 100644 --- a/examples/img_capture.c +++ b/examples/img_capture.c @@ -94,6 +94,7 @@ int main(void) fp_img_standardize(img); r = fp_img_save_to_file(img, "finger_standardized.pgm"); + fp_img_free(img); if (r) { fprintf(stderr, "standardized img save failed, code %d\n", r); goto out_close; diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 8a10a90e..89d05c78 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -100,6 +100,7 @@ int fp_img_get_width(struct fp_img *img); unsigned char *fp_img_get_data(struct fp_img *img); int fp_img_save_to_file(struct fp_img *img, char *path); void fp_img_standardize(struct fp_img *img); +void fp_img_free(struct fp_img *img); /* Library */ int fp_init(void); diff --git a/libfprint/img.c b/libfprint/img.c index 38c492f3..55e11907 100644 --- a/libfprint/img.c +++ b/libfprint/img.c @@ -61,6 +61,11 @@ struct fp_img *fpi_img_resize(struct fp_img *img, size_t newsize) return g_realloc(img, sizeof(*img) + newsize); } +API_EXPORTED void fp_img_free(struct fp_img *img) +{ + g_free(img); +} + API_EXPORTED int fp_img_get_height(struct fp_img *img) { return img->height; From 351ccb4ab7f60ce2225f10bab13fd0862c1d17de Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 27 Oct 2007 15:17:19 +0100 Subject: [PATCH 033/184] Add XV-based img_capture_continuous example --- configure.ac | 33 ++++ examples/Makefile.am | 8 + examples/img_capture_continuous.c | 257 ++++++++++++++++++++++++++++++ 3 files changed, 298 insertions(+) create mode 100644 examples/img_capture_continuous.c diff --git a/configure.ac b/configure.ac index 45b95653..6c372a30 100644 --- a/configure.ac +++ b/configure.ac @@ -7,6 +7,7 @@ AC_PREREQ([2.61]) AC_PROG_CC AC_PROG_LIBTOOL AC_C_INLINE +AM_PROG_CC_C_O # Library versioning lt_major="0" @@ -31,6 +32,38 @@ AC_ARG_ENABLE([examples-build], [AS_HELP_STRING([--enable-examples-build], [build_examples='no']) AM_CONDITIONAL([BUILD_EXAMPLES], [test "x$build_examples" != "xno"]) +# Examples build +AC_ARG_ENABLE([x11-examples-build], [AS_HELP_STRING([--enable-x11-examples-build], + [build X11 example applications (default n)])], + [build_x11_examples=$enableval], + [build_x11_examples='no']) +AM_CONDITIONAL([BUILD_X11_EXAMPLES], [test "x$build_x11_examples" != "xno"]) + + +if test "x$build_x11_examples" != "xno"; then + # check for Xv extensions + # imported from Coriander + AC_DEFUN([AC_CHECK_XV],[ + AC_SUBST(XV_CFLAGS) + AC_SUBST(XV_LIBS) + AC_MSG_CHECKING(for Xv extensions) + AC_TRY_COMPILE([ + #include + #include ],[ + int main(void) { (void) XvGetPortAttribute(0, 0, 0, 0); return 0; } + ],xv=yes,xv=no); + AC_MSG_RESULT($xv) + if test x$xv = xyes; then + XV_LIBS="-lXv -lXext" + XV_CFLAGS="" + AC_DEFINE(HAVE_XV,1,[defined if XV video overlay is available]) + else + AC_MSG_ERROR([XV is required for X11 examples]) + fi + ]) + AC_CHECK_XV +fi + # Message logging AC_ARG_ENABLE([log], [AS_HELP_STRING([--disable-log], [disable all logging])], [log_enabled=$enableval], diff --git a/examples/Makefile.am b/examples/Makefile.am index d7d47063..eb6dedbc 100644 --- a/examples/Makefile.am +++ b/examples/Makefile.am @@ -13,3 +13,11 @@ verify_LDADD = ../libfprint/libfprint.la -lfprint img_capture_SOURCES = img_capture.c img_capture_LDADD = ../libfprint/libfprint.la -lfprint +if BUILD_X11_EXAMPLES +noinst_PROGRAMS += img_capture_continuous + +img_capture_continuous_CFLAGS = $(X_CFLAGS) $(XV_CFLAGS) +img_capture_continuous_SOURCES = img_capture_continuous.c +img_capture_continuous_LDADD = ../libfprint/libfprint.la -lfprint $(X_LIBS) $(X_PRE_LIBS) $(XV_LIBS) -lX11 $(X_EXTRA_LIBS); +endif + diff --git a/examples/img_capture_continuous.c b/examples/img_capture_continuous.c new file mode 100644 index 00000000..ca67b33d --- /dev/null +++ b/examples/img_capture_continuous.c @@ -0,0 +1,257 @@ +/* + * Example libfprint continuous image capture program + * Copyright (C) 2007 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include +#include + +#include +#include +#include +#include + +#define FORMAT 0x32595559 + +static int adaptor = -1; +static unsigned char *framebuffer = NULL; + +static Display *display = NULL; +static Window window=(Window)NULL; +static XvImage *xv_image = NULL; +static XvAdaptorInfo *info; +static GC gc; +static int connection = -1; + +/* based on macro by Bart Nabbe */ +#define GREY2YUV(grey, y, u, v)\ + y = (9798*grey + 19235*grey + 3736*grey) / 32768;\ + u = (-4784*grey - 9437*grey + 14221*grey) / 32768 + 128;\ + v = (20218*grey - 16941*grey - 3277*grey) / 32768 + 128;\ + y = y < 0 ? 0 : y;\ + u = u < 0 ? 0 : u;\ + v = v < 0 ? 0 : v;\ + y = y > 255 ? 255 : y;\ + u = u > 255 ? 255 : u;\ + v = v > 255 ? 255 : v + +static void grey2yuy2 (unsigned char *grey, unsigned char *YUV, int num) { + int i, j; + int y0, y1, u0, u1, v0, v1; + int gval; + + for (i = 0, j = 0; i < num; i += 2, j += 4) + { + gval = grey[i]; + GREY2YUV (gval, y0, u0 , v0); + gval = grey[i + 1]; + GREY2YUV (gval, y1, u1 , v1); + YUV[j + 0] = y0; + YUV[j + 1] = (u0+u1)/2; + YUV[j + 2] = y1; + YUV[j + 3] = (v0+v1)/2; + } +} + +static void display_frame(struct fp_img *img) +{ + int width = fp_img_get_width(img); + int height = fp_img_get_height(img); + unsigned char *data = fp_img_get_data(img); + + if (adaptor < 0) + return; + + grey2yuy2(data, framebuffer, width * height); + xv_image = XvCreateImage(display, info[adaptor].base_id, FORMAT, + framebuffer, width, height); + XvPutImage(display, info[adaptor].base_id, window, gc, xv_image, + 0, 0, width, height, 0, 0, width, height); +} + +static void QueryXv() +{ + int num_adaptors; + int num_formats; + XvImageFormatValues *formats = NULL; + int i,j; + char xv_name[5]; + + XvQueryAdaptors(display, DefaultRootWindow(display), &num_adaptors, + &info); + + for(i = 0; i < num_adaptors; i++) { + formats = XvListImageFormats(display, info[i].base_id, + &num_formats); + for(j = 0; j < num_formats; j++) { + xv_name[4] = 0; + memcpy(xv_name, &formats[j].id, 4); + if(formats[j].id == FORMAT) { + printf("using Xv format 0x%x %s %s\n", + formats[j].id, xv_name, + (formats[j].format==XvPacked) + ? "packed" : "planar"); + if (adaptor < 0) + adaptor = i; + } + } + } + XFree(formats); + if (adaptor < 0) + printf("No suitable Xv adaptor found\n"); +} + +static struct fp_dscv_dev *discover_device(struct fp_dscv_dev **discovered_devs) +{ + struct fp_dscv_dev *ddev = NULL; + int i; + + for (i = 0; ddev = discovered_devs[i]; i++) { + struct fp_driver *drv = fp_dscv_dev_get_driver(ddev); + printf("Found device claimed by %s driver\n", + fp_driver_get_full_name(drv)); + return ddev; + } + + return ddev; +} + +int main(void) +{ + int r = 1; + XEvent xev; + XGCValues xgcv; + long background=0x010203; + struct fp_dscv_dev *ddev; + struct fp_dscv_dev **discovered_devs; + struct fp_dev *dev; + struct fp_img_dev *imgdev; + int img_width; + int img_height; + int standardize = 0; + + r = fp_init(); + if (r < 0) { + fprintf(stderr, "Failed to initialize libfprint\n"); + exit(1); + } + + discovered_devs = fp_discover_devs(); + if (!discovered_devs) { + fprintf(stderr, "Could not discover devices\n"); + exit(1); + } + + ddev = discover_device(discovered_devs); + if (!ddev) { + fprintf(stderr, "No devices detected.\n"); + exit(1); + } + + dev = fp_dev_open(ddev); + fp_dscv_devs_free(discovered_devs); + if (!dev) { + fprintf(stderr, "Could not open device.\n"); + exit(1); + } + + imgdev = fp_dev_to_img_dev(dev); + if (!imgdev) { + fprintf(stderr, "could not get image dev, is this an imaging " + "device?\n"); + goto out; + } + + img_width = fp_imgdev_get_img_width(imgdev); + img_height = fp_imgdev_get_img_height(imgdev); + framebuffer = malloc(img_width * img_height * 2); + if (!framebuffer) + goto out; + + /* make the window */ + display = XOpenDisplay(getenv("DISPLAY")); + if(display == NULL) { + fprintf(stderr,"Could not open display \"%s\"\n", + getenv("DISPLAY")); + goto out; + } + + QueryXv(); + + if (adaptor < 0) + goto out; + + window = XCreateSimpleWindow(display, DefaultRootWindow(display), 0, 0, + img_width, img_height, 0, + WhitePixel(display, DefaultScreen(display)), background); + + XSelectInput(display, window, StructureNotifyMask | KeyPressMask); + XMapWindow(display, window); + connection = ConnectionNumber(display); + + gc = XCreateGC(display, window, 0, &xgcv); + + printf("Press S to toggle standardized mode, Q to quit\n"); + + while (1) { /* event loop */ + struct fp_img *img; + + r = fp_imgdev_capture(imgdev, 1, &img); + if (r) { + fprintf(stderr, "image capture failed, code %d\n", r); + goto out; + } + if (standardize) + fp_img_standardize(img); + + display_frame(img); + fp_img_free(img); + XFlush(display); + + while (XPending(display) > 0) { + XNextEvent(display, &xev); + if (xev.type != KeyPress) + continue; + + switch (XKeycodeToKeysym(display, xev.xkey.keycode, 0)) { + case XK_q: + case XK_Q: + r = 0; + goto out; + break; + case XK_s: + case XK_S: + standardize = !standardize; + break; + } + } /* XPending */ + } + + r = 0; +out: + if (framebuffer) + free(framebuffer); + fp_dev_close(dev); + if ((void *) window != NULL) + XUnmapWindow(display, window); + if (display != NULL) + XFlush(display); + return r; +} + + From 3bbb7b8b51829acd5b8efaf54d60338aec0c4717 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 27 Oct 2007 18:10:06 +0100 Subject: [PATCH 034/184] Internal image allocation API changes Creating by dimensions is likely not useful now that we can infer image size from a device in question. --- libfprint/fp_internal.h | 5 ++++- libfprint/img.c | 5 ++++- libfprint/imgdev.c | 13 +++++-------- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 47eea27d..7a2b58af 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -142,6 +142,9 @@ extern struct fp_img_driver uru4000_driver; void fpi_img_driver_setup(struct fp_img_driver *idriver); +#define fpi_driver_to_img_driver(drv) \ + container_of((drv), struct fp_img_driver, driver) + struct fp_dscv_dev { struct usb_device *udev; struct fp_driver *drv; @@ -171,7 +174,7 @@ struct fp_img { }; struct fp_img *fpi_img_new(size_t length); -struct fp_img *fpi_img_new_dims(int width, int height); +struct fp_img *fpi_img_new_for_imgdev(struct fp_img_dev *dev); struct fp_img *fpi_img_resize(struct fp_img *img, size_t newsize); gboolean fpi_img_is_sane(struct fp_img *img); diff --git a/libfprint/img.c b/libfprint/img.c index 55e11907..f2bfe9c1 100644 --- a/libfprint/img.c +++ b/libfprint/img.c @@ -35,8 +35,11 @@ struct fp_img *fpi_img_new(size_t length) return img; } -struct fp_img *fpi_img_new_dims(int width, int height) +struct fp_img *fpi_img_new_for_imgdev(struct fp_img_dev *imgdev) { + struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(imgdev->dev->drv); + int width = imgdrv->img_width; + int height = imgdrv->img_height; struct fp_img *img = fpi_img_new(width * height); img->width = width; img->height = height; diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index e1f4c3ac..cb6f86ee 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -22,13 +22,10 @@ #include "fp_internal.h" -#define driver_to_img_driver(drv) \ - container_of((drv), struct fp_img_driver, driver) - static int img_dev_init(struct fp_dev *dev, unsigned long driver_data) { struct fp_img_dev *imgdev = g_malloc0(sizeof(*imgdev)); - struct fp_img_driver *imgdrv = driver_to_img_driver(dev->drv); + struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(dev->drv); int r = 0; imgdev->dev = dev; @@ -53,7 +50,7 @@ err: static void img_dev_exit(struct fp_dev *dev) { struct fp_img_dev *imgdev = dev->priv; - struct fp_img_driver *imgdrv = driver_to_img_driver(dev->drv); + struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(dev->drv); if (imgdrv->exit) imgdrv->exit(imgdev); @@ -64,14 +61,14 @@ static void img_dev_exit(struct fp_dev *dev) API_EXPORTED int fp_imgdev_get_img_width(struct fp_img_dev *imgdev) { struct fp_driver *drv = imgdev->dev->drv; - struct fp_img_driver *imgdrv = driver_to_img_driver(drv); + struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); return imgdrv->img_width; } API_EXPORTED int fp_imgdev_get_img_height(struct fp_img_dev *imgdev) { struct fp_driver *drv = imgdev->dev->drv; - struct fp_img_driver *imgdrv = driver_to_img_driver(drv); + struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); return imgdrv->img_height; } @@ -79,7 +76,7 @@ API_EXPORTED int fp_imgdev_capture(struct fp_img_dev *imgdev, int unconditional, struct fp_img **image) { struct fp_driver *drv = imgdev->dev->drv; - struct fp_img_driver *imgdrv = driver_to_img_driver(drv); + struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); int r; if (!image) { From be67f85caa1c65c4c55d4e969d757e7f2790bd7e Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 27 Oct 2007 18:12:16 +0100 Subject: [PATCH 035/184] Add Authentec AES4000 driver --- TODO | 1 - libfprint/Makefile.am | 3 +- libfprint/core.c | 1 + libfprint/drivers/aes4000.c | 225 ++++++++++++++++++++++++++++++++++++ libfprint/fp_internal.h | 1 + 5 files changed, 229 insertions(+), 2 deletions(-) create mode 100644 libfprint/drivers/aes4000.c diff --git a/TODO b/TODO index 586e45ac..f92bfcde 100644 --- a/TODO +++ b/TODO @@ -9,7 +9,6 @@ DRIVERS ======= Sunplus 895 driver AES3501 driver -AES4000 driver ID Mouse driver Support for 2nd generation MS devices Support for 2nd generation UPEK devices diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index bdec4718..a6857747 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -2,8 +2,9 @@ lib_LTLIBRARIES = libfprint.la UPEKTS_SRC = drivers/upekts.c URU4000_SRC = drivers/uru4000.c +AES4000_SRC = drivers/aes4000.c -DRIVER_SRC = $(UPEKTS_SRC) $(URU4000_SRC) +DRIVER_SRC = $(UPEKTS_SRC) $(URU4000_SRC) $(AES4000_SRC) libfprint_la_CFLAGS = -fvisibility=hidden $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) $(AM_CFLAGS) libfprint_la_LDFLAGS = -version-info @lt_major@:@lt_revision@:@lt_age@ diff --git a/libfprint/core.c b/libfprint/core.c index ff8850ab..d6c36328 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -79,6 +79,7 @@ static struct fp_driver * const primitive_drivers[] = { static struct fp_img_driver * const img_drivers[] = { &uru4000_driver, + &aes4000_driver, }; static void register_drivers(void) diff --git a/libfprint/drivers/aes4000.c b/libfprint/drivers/aes4000.c new file mode 100644 index 00000000..cbbcfbf0 --- /dev/null +++ b/libfprint/drivers/aes4000.c @@ -0,0 +1,225 @@ +/* + * AuthenTec AES4000 driver for libfprint + * Copyright (C) 2007 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#define FP_COMPONENT "aes4000" + +#include + +#include +#include + +#include + +#define CTRL_TIMEOUT 1000 +#define EP_IN (1 | USB_ENDPOINT_IN) +#define EP_OUT (2 | USB_ENDPOINT_OUT) +#define DATA_BUFLEN 0x1259 +#define NR_SUBARRAYS 6 +#define SUBARRAY_LEN 768 + +static int write_reg(struct fp_img_dev *dev, unsigned char reg, + unsigned char value) +{ + unsigned char data[] = { reg, value }; + int r; + + fp_dbg("%02x=%02x", reg, value); + r = usb_bulk_write(dev->udev, EP_OUT, data, sizeof(data), CTRL_TIMEOUT); + if (r < 0) { + fp_err("bulk write error %d", r); + return r; + } else if (r < sizeof(data)) { + fp_err("unexpected short write %d/%d", r, sizeof(data)); + return -EIO; + } + + return 0; +} + +static void process_subarray(unsigned char *src, unsigned char *dst) +{ + int col, row; + int offset = -1; + + for (col = 95; col >= 0; col--) { + for (row = 15; row >= 0; row -= 2) { + unsigned char val = src[++offset]; + dst[(row * 96) + col] = (val & 0x7) * 36; + dst[((row - 1) * 96) + col] = ((val & 0x70) >> 4) * 36; + } + } +} + +static const struct aes4000_regwrite { + unsigned char reg; + unsigned char value; +} init_reqs[] = { + /* master reset */ + { 0x80, 0x01 }, + { 0x80, 0x00 }, + + { 0x81, 0x00 }, + { 0x80, 0x00 }, + + /* scan reset */ + { 0x80, 0x02 }, + { 0x80, 0x00 }, + + /* disable register buffering */ + { 0x80, 0x04 }, + { 0x80, 0x00 }, + + { 0x81, 0x00 }, + /* windows driver reads registers now (81 02) */ + { 0x80, 0x00 }, + { 0x81, 0x00 }, + + /* set excitation bias current: 2mhz drive ring frequency, + * 4V drive ring voltage, 16.5mA excitation bias */ + { 0x82, 0x04 }, + + /* continuously sample drive ring for finger detection, + * 62.50ms debounce delay */ + { 0x83, 0x13 }, + + { 0x84, 0x07 }, /* set calibration resistance to 12 kiloohms */ + { 0x85, 0x3d }, /* set calibration capacitance */ + { 0x86, 0x03 }, /* detect drive voltage */ + { 0x87, 0x01 }, /* set detection frequency to 125khz */ + { 0x88, 0x03 }, /* set column scan period */ + { 0x89, 0x03 }, /* set measure drive */ + { 0x8a, 0x32 }, /* set measure frequency and sense amplifier bias */ + { 0x8b, 0x33 }, /* set matrix pattern */ + { 0x8c, 0x0b }, /* set demodulation phase 1 */ + { 0x8d, 0x04 }, /* set demodulation phase 2 */ + { 0x8e, 0x33 }, /* set sensor gain */ + { 0x8f, 0x03 }, /* set image parameters */ + { 0x90, 0x0f }, /* carrier offset null */ + { 0x91, 0x03 }, /* set A/D reference high */ + { 0x92, 0x03 }, /* set A/D reference low */ + { 0x93, 0x00 }, /* set start row to 0 */ + { 0x94, 0x05 }, /* set end row to 5 */ + { 0x95, 0x00 }, /* set start column to 0 */ + { 0x96, 0x18 }, /* set end column to 24*4=96 */ + { 0x97, 0x04 }, /* data format and thresholds */ + { 0x98, 0x28 }, /* image data control */ + { 0x99, 0x00 }, /* disable general purpose outputs */ + { 0x9a, 0x0b }, /* set initial scan state */ + { 0x9b, 0x00 }, /* clear challenge word bits */ + { 0x9c, 0x00 }, /* clear challenge word bits */ + { 0x9d, 0x09 }, /* set some challenge word bits */ + { 0x9e, 0x53 }, /* clear challenge word bits */ + { 0x9f, 0x6b }, /* set some challenge word bits */ + + { 0x80, 0x00 }, + { 0x81, 0x00 }, + { 0x81, 0x04 }, + { 0x81, 0x00 }, +}; + +static int capture(struct fp_img_dev *dev, gboolean unconditional, + struct fp_img **ret) +{ + int i; + int r; + struct fp_img *img; + unsigned char *data; + unsigned char *ptr; + + for (i = 0; i < ARRAY_SIZE(init_reqs); i++) { + r = write_reg(dev, init_reqs[i].reg, init_reqs[i].value); + if (r < 0) + return r; + } + + img = fpi_img_new_for_imgdev(dev); + data = g_malloc(DATA_BUFLEN); + ptr = data; + + /* See the timeout explanation in the uru4000 driver for the reasoning + * behind this silly loop. */ +retry: + r = usb_bulk_read(dev->udev, EP_IN, data, DATA_BUFLEN, 1000); + if (r == -ETIMEDOUT) + goto retry; + + if (r < 0) { + fp_err("data read failed, error %d", r); + goto err; + } else if (r < DATA_BUFLEN) { + fp_err("short data read (%d)", r); + r = -EIO; + goto err; + } + + for (i = NR_SUBARRAYS - 1; i >= 0; i--) { + fp_dbg("subarray header byte %02x", *ptr); + ptr++; + process_subarray(ptr, img->data + (i * 96 * 16)); + ptr += SUBARRAY_LEN; + } + + img->flags = FP_IMG_COLORS_INVERTED; + *ret = img; + g_free(data); + return 0; +err: + g_free(data); + g_free(img); + return r; +} + +static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) +{ + int r; + + r = usb_claim_interface(dev->udev, 0); + if (r < 0) { + fp_err("could not claim interface 0"); + return r; + } + + return 0; +} + +static void dev_exit(struct fp_img_dev *dev) +{ + usb_release_interface(dev->udev, 0); +} + +static const struct usb_id id_table[] = { + { .vendor = 0x08ff, .product = 0x5501 }, + { 0, 0, 0, }, +}; + +struct fp_img_driver aes4000_driver = { + .driver = { + .name = FP_COMPONENT, + .full_name = "AuthenTec AES4000", + .id_table = id_table, + }, + .flags = 0, + .img_height = 96, + .img_width = 96, + + .init = dev_init, + .exit = dev_exit, + .capture = capture, +}; + diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 7a2b58af..32ae1c5c 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -139,6 +139,7 @@ struct fp_img_driver { extern struct fp_driver upekts_driver; extern struct fp_img_driver uru4000_driver; +extern struct fp_img_driver aes4000_driver; void fpi_img_driver_setup(struct fp_img_driver *idriver); From 41b25f28a4dd980b88fef2e9ff9f243390793639 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 27 Oct 2007 22:48:09 +0100 Subject: [PATCH 036/184] Add mindtct from NBIS; implement enroll for image devices mindtct is mostly as-is for now, with just a couple of bits ripped out. --- libfprint/Makefile.am | 38 +- libfprint/fp_internal.h | 2 + libfprint/img.c | 105 + libfprint/imgdev.c | 33 + libfprint/nbis/include/bozorth.h | 263 +++ libfprint/nbis/include/bz_array.h | 121 + libfprint/nbis/include/defs.h | 63 + libfprint/nbis/include/lfs.h | 1208 ++++++++++ libfprint/nbis/include/log.h | 48 + libfprint/nbis/include/morph.h | 39 + libfprint/nbis/include/mytime.h | 80 + libfprint/nbis/include/sunrast.h | 76 + libfprint/nbis/mindtct/binar.c | 455 ++++ libfprint/nbis/mindtct/block.c | 377 +++ libfprint/nbis/mindtct/chaincod.c | 191 ++ libfprint/nbis/mindtct/contour.c | 1274 +++++++++++ libfprint/nbis/mindtct/detect.c | 709 ++++++ libfprint/nbis/mindtct/dft.c | 358 +++ libfprint/nbis/mindtct/free.c | 116 + libfprint/nbis/mindtct/getmin.c | 155 ++ libfprint/nbis/mindtct/globals.c | 293 +++ libfprint/nbis/mindtct/imgutil.c | 469 ++++ libfprint/nbis/mindtct/init.c | 768 +++++++ libfprint/nbis/mindtct/isempty.c | 94 + libfprint/nbis/mindtct/line.c | 203 ++ libfprint/nbis/mindtct/link.c | 1238 ++++++++++ libfprint/nbis/mindtct/log.c | 90 + libfprint/nbis/mindtct/loop.c | 1228 ++++++++++ libfprint/nbis/mindtct/maps.c | 2552 +++++++++++++++++++++ libfprint/nbis/mindtct/matchpat.c | 271 +++ libfprint/nbis/mindtct/minutia.c | 3557 +++++++++++++++++++++++++++++ libfprint/nbis/mindtct/morph.c | 226 ++ libfprint/nbis/mindtct/mytime.c | 60 + libfprint/nbis/mindtct/quality.c | 467 ++++ libfprint/nbis/mindtct/remove.c | 3404 +++++++++++++++++++++++++++ libfprint/nbis/mindtct/results.c | 682 ++++++ libfprint/nbis/mindtct/ridges.c | 831 +++++++ libfprint/nbis/mindtct/shape.c | 304 +++ libfprint/nbis/mindtct/sort.c | 320 +++ libfprint/nbis/mindtct/util.c | 605 +++++ libfprint/nbis/mindtct/xytreps.c | 133 ++ 41 files changed, 23503 insertions(+), 3 deletions(-) create mode 100644 libfprint/nbis/include/bozorth.h create mode 100644 libfprint/nbis/include/bz_array.h create mode 100644 libfprint/nbis/include/defs.h create mode 100644 libfprint/nbis/include/lfs.h create mode 100644 libfprint/nbis/include/log.h create mode 100644 libfprint/nbis/include/morph.h create mode 100644 libfprint/nbis/include/mytime.h create mode 100644 libfprint/nbis/include/sunrast.h create mode 100644 libfprint/nbis/mindtct/binar.c create mode 100644 libfprint/nbis/mindtct/block.c create mode 100644 libfprint/nbis/mindtct/chaincod.c create mode 100644 libfprint/nbis/mindtct/contour.c create mode 100644 libfprint/nbis/mindtct/detect.c create mode 100644 libfprint/nbis/mindtct/dft.c create mode 100644 libfprint/nbis/mindtct/free.c create mode 100644 libfprint/nbis/mindtct/getmin.c create mode 100644 libfprint/nbis/mindtct/globals.c create mode 100644 libfprint/nbis/mindtct/imgutil.c create mode 100644 libfprint/nbis/mindtct/init.c create mode 100644 libfprint/nbis/mindtct/isempty.c create mode 100644 libfprint/nbis/mindtct/line.c create mode 100644 libfprint/nbis/mindtct/link.c create mode 100644 libfprint/nbis/mindtct/log.c create mode 100644 libfprint/nbis/mindtct/loop.c create mode 100644 libfprint/nbis/mindtct/maps.c create mode 100644 libfprint/nbis/mindtct/matchpat.c create mode 100644 libfprint/nbis/mindtct/minutia.c create mode 100644 libfprint/nbis/mindtct/morph.c create mode 100644 libfprint/nbis/mindtct/mytime.c create mode 100644 libfprint/nbis/mindtct/quality.c create mode 100644 libfprint/nbis/mindtct/remove.c create mode 100644 libfprint/nbis/mindtct/results.c create mode 100644 libfprint/nbis/mindtct/ridges.c create mode 100644 libfprint/nbis/mindtct/shape.c create mode 100644 libfprint/nbis/mindtct/sort.c create mode 100644 libfprint/nbis/mindtct/util.c create mode 100644 libfprint/nbis/mindtct/xytreps.c diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index a6857747..f857e6b0 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -6,14 +6,46 @@ AES4000_SRC = drivers/aes4000.c DRIVER_SRC = $(UPEKTS_SRC) $(URU4000_SRC) $(AES4000_SRC) -libfprint_la_CFLAGS = -fvisibility=hidden $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) $(AM_CFLAGS) +NBIS_SRC = \ + nbis/mindtct/binar.c \ + nbis/mindtct/block.c \ + nbis/mindtct/chaincod.c \ + nbis/mindtct/contour.c \ + nbis/mindtct/detect.c \ + nbis/mindtct/dft.c \ + nbis/mindtct/free.c \ + nbis/mindtct/getmin.c \ + nbis/mindtct/globals.c \ + nbis/mindtct/imgutil.c \ + nbis/mindtct/init.c \ + nbis/mindtct/isempty.c \ + nbis/mindtct/line.c \ + nbis/mindtct/link.c \ + nbis/mindtct/log.c \ + nbis/mindtct/loop.c \ + nbis/mindtct/maps.c \ + nbis/mindtct/matchpat.c \ + nbis/mindtct/minutia.c \ + nbis/mindtct/morph.c \ + nbis/mindtct/mytime.c \ + nbis/mindtct/quality.c \ + nbis/mindtct/remove.c \ + nbis/mindtct/results.c \ + nbis/mindtct/ridges.c \ + nbis/mindtct/shape.c \ + nbis/mindtct/sort.c \ + nbis/mindtct/util.c \ + nbis/mindtct/xytreps.c + +libfprint_la_CFLAGS = -fvisibility=hidden -Inbis/include $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) $(AM_CFLAGS) libfprint_la_LDFLAGS = -version-info @lt_major@:@lt_revision@:@lt_age@ -libfprint_la_LIBADD = $(LIBUSB_LIBS) $(GLIB_LIBS) +libfprint_la_LIBADD = -lm $(LIBUSB_LIBS) $(GLIB_LIBS) libfprint_la_SOURCES = \ core.c \ data.c \ img.c \ imgdev.c \ - $(DRIVER_SRC) + $(DRIVER_SRC) \ + $(NBIS_SRC) diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 32ae1c5c..f998dc5d 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -178,6 +178,8 @@ struct fp_img *fpi_img_new(size_t length); struct fp_img *fpi_img_new_for_imgdev(struct fp_img_dev *dev); struct fp_img *fpi_img_resize(struct fp_img *img, size_t newsize); gboolean fpi_img_is_sane(struct fp_img *img); +int fpi_img_detect_minutiae(struct fp_img_dev *imgdev, struct fp_img *img, + struct fp_print_data **ret); #define bswap16(x) (((x & 0xff) << 8) | (x >> 8)) #if __BYTE_ORDER == __LITTLE_ENDIAN diff --git a/libfprint/img.c b/libfprint/img.c index f2bfe9c1..2418ffdb 100644 --- a/libfprint/img.c +++ b/libfprint/img.c @@ -25,6 +25,8 @@ #include #include "fp_internal.h" +#include "nbis/include/bozorth.h" +#include "nbis/include/lfs.h" struct fp_img *fpi_img_new(size_t length) { @@ -172,3 +174,106 @@ API_EXPORTED void fp_img_standardize(struct fp_img *img) img->flags &= ~FP_IMG_COLORS_INVERTED; } } + +static int sort_x_y(const void *a, const void *b) +{ + struct minutiae_struct *af = (struct minutiae_struct *) a; + struct minutiae_struct *bf = (struct minutiae_struct *) b; + + if (af->col[0] < bf->col[0]) + return -1; + if (af->col[0] > bf->col[0]) + return 1; + + if (af->col[1] < bf->col[1]) + return -1; + if (af->col[1] > bf->col[1]) + return 1; + + return 0; +} + +/* Based on write_minutiae_XYTQ and bz_load */ +static void minutiae_to_xyt(MINUTIAE *minutiae, int bwidth, + int bheight, unsigned char *buf) +{ + int i; + MINUTIA *minutia; + struct minutiae_struct c[MAX_FILE_MINUTIAE]; + struct xyt_struct *xyt = (struct xyt_struct *) buf; + + /* FIXME: only considers first 150 minutiae (MAX_FILE_MINUTIAE) */ + /* nist does weird stuff with 150 vs 1000 limits */ + int nmin = min(minutiae->num, MAX_FILE_MINUTIAE); + + for (i = 0; i < nmin; i++){ + minutia = minutiae->list[i]; + + lfs2nist_minutia_XYT(&c[i].col[0], &c[i].col[1], &c[i].col[2], + minutia, bwidth, bheight); + c[i].col[3] = sround(minutia->reliability * 100.0); + + if (c[i].col[2] > 180) + c[i].col[2] -= 360; + } + + qsort((void *) &c, (size_t) nmin, sizeof(struct minutiae_struct), + sort_x_y); + + for (i = 0; i < nmin; i++) { + xyt->xcol[i] = c[i].col[0]; + xyt->ycol[i] = c[i].col[1]; + xyt->thetacol[i] = c[i].col[2]; + } + xyt->nrows = nmin; +} + +int fpi_img_detect_minutiae(struct fp_img_dev *imgdev, struct fp_img *img, + struct fp_print_data **ret) +{ + MINUTIAE *minutiae; + int r; + int *direction_map, *low_contrast_map, *low_flow_map; + int *high_curve_map, *quality_map; + int map_w, map_h; + unsigned char *bdata; + int bw, bh, bd; + struct fp_print_data *print; + GTimer *timer; + + /* 25.4 mm per inch */ + timer = g_timer_new(); + r = get_minutiae(&minutiae, &quality_map, &direction_map, + &low_contrast_map, &low_flow_map, &high_curve_map, + &map_w, &map_h, &bdata, &bw, &bh, &bd, + img->data, img->width, img->height, 8, + DEFAULT_PPI / (double)25.4, &lfsparms_V2); + g_timer_stop(timer); + fp_dbg("minutiae scan completed in %f secs", g_timer_elapsed(timer, NULL)); + g_timer_destroy(timer); + if (r) { + fp_err("get minutiae failed, code %d", r); + return r; + } + fp_dbg("detected %d minutiae", minutiae->num); + r = minutiae->num; + + /* FIXME: space is wasted if we dont hit the max minutiae count. would + * be good to make this dynamic. */ + print = fpi_print_data_new(imgdev->dev, sizeof(struct xyt_struct)); + minutiae_to_xyt(minutiae, bw, bh, print->buffer); + /* FIXME: the print buffer at this point is endian-specific, and will + * only work when loaded onto machines with identical endianness. not good! + * data format should be platform-independant. */ + *ret = print; + + free_minutiae(minutiae); + free(quality_map); + free(direction_map); + free(low_contrast_map); + free(low_flow_map); + free(high_curve_map); + free(bdata); + + return r; +} diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index cb6f86ee..1ff9bc63 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -138,10 +138,43 @@ API_EXPORTED int fp_imgdev_capture(struct fp_img_dev *imgdev, return r; } +#define MIN_ACCEPTABLE_MINUTIAE 5 + +int img_dev_enroll(struct fp_dev *dev, gboolean initial, int stage, + struct fp_print_data **ret) +{ + struct fp_img *img; + struct fp_img_dev *imgdev = dev->priv; + struct fp_print_data *print; + int r; + + /* FIXME: convert to 3-stage enroll mechanism, where we scan 3 prints, + * use NFIQ to pick the best one, and discard the others */ + + r = fp_imgdev_capture(imgdev, 0, &img); + if (r) + return r; + + fp_img_standardize(img); + r = fpi_img_detect_minutiae(imgdev, img, &print); + fp_img_free(img); + if (r < 0) + return r; + if (r < MIN_ACCEPTABLE_MINUTIAE) { + fp_dbg("not enough minutiae, %d/%d", r, MIN_ACCEPTABLE_MINUTIAE); + fp_print_data_free(print); + return FP_ENROLL_RETRY; + } + + *ret = print; + return FP_ENROLL_COMPLETE; +} + void fpi_img_driver_setup(struct fp_img_driver *idriver) { idriver->driver.type = DRIVER_IMAGING; idriver->driver.init = img_dev_init; idriver->driver.exit = img_dev_exit; + idriver->driver.enroll = img_dev_enroll; } diff --git a/libfprint/nbis/include/bozorth.h b/libfprint/nbis/include/bozorth.h new file mode 100644 index 00000000..7d37b37e --- /dev/null +++ b/libfprint/nbis/include/bozorth.h @@ -0,0 +1,263 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +#ifndef _BOZORTH_H +#define _BOZORTH_H + +/* The max number of points in any Probe or Gallery XYT is set to 200; */ +/* a pointwise comparison table therefore has a maximum number of: */ +/* (200^2)/2 = 20000 comparisons. */ + + +#include +#include +#include +#include /* Needed for type pid_t */ +#include + +/* If not defined in sys/param.h */ +#ifndef MAX +#define MAX(a,b) (((a)>(b))?(a):(b)) +#endif + +/**************************************************************************/ +/* Math-Related Macros, Definitions & Prototypes */ +/**************************************************************************/ +#include + /* This macro adjusts angles to the range (-180,180] */ +#define IANGLE180(deg) ( ( (deg) > 180 ) ? ( (deg) - 360 ) : ( (deg) <= -180 ? ( (deg) + 360 ) : (deg) ) ) + +#define SENSE(a,b) ( (a) < (b) ? (-1) : ( ( (a) == (b) ) ? 0 : 1 ) ) +#define SENSE_NEG_POS(a,b) ( (a) < (b) ? (-1) : 1 ) + +#define SQUARED(n) ( (n) * (n) ) + +#ifdef ROUND_USING_LIBRARY +/* These functions should be declared in math.h: + extern float roundf( float ); + extern double round( double ); +*/ +#define ROUND(f) (roundf(f)) +#else +#define ROUND(f) ( ( (f) < 0.0F ) ? ( (int) ( (f) - 0.5F ) ) : ( (int) ( (f) + 0.5F ) ) ) +#endif + +/* PI is used in: bozorth3.c, comp.c */ +#ifdef M_PI +#define PI M_PI +#define PI_SINGLE ( (float) PI ) +#else +#define PI 3.14159 +#define PI_SINGLE 3.14159F +#endif + +/* Provide prototype for atanf() */ +extern float atanf( float ); + +/**************************************************************************/ +/* Array Length Definitions */ +/**************************************************************************/ +#include + + +/**************************************************************************/ +/**************************************************************************/ + /* GENERAL DEFINITIONS */ +/**************************************************************************/ + +#define FPNULL ((FILE *) NULL) +#define CNULL ((char *) NULL) + +#define PROGRAM "bozorth3" + +#define MAX_LINE_LENGTH 1024 + +#define SCOREFILE_EXTENSION ".scr" + +#define MAX_FILELIST_LENGTH 10000 + +#define DEFAULT_BOZORTH_MINUTIAE 150 +#define MAX_BOZORTH_MINUTIAE 200 +#define MIN_BOZORTH_MINUTIAE 0 +#define MIN_COMPUTABLE_BOZORTH_MINUTIAE 10 + +#define DEFAULT_MAX_MATCH_SCORE 400 +#define ZERO_MATCH_SCORE 0 + +#define DEFAULT_SCORE_LINE_FORMAT "s" + +#define DM 125 +#define FD 5625 +#define FDD 500 +#define TK 0.05F +#define TXS 121 +#define CTXS 121801 +#define MSTR 3 +#define MMSTR 8 +#define WWIM 10 + +#define QQ_SIZE 4000 + +#define QQ_OVERFLOW_SCORE QQ_SIZE + +/**************************************************************************/ +/**************************************************************************/ + /* MACROS DEFINITIONS */ +/**************************************************************************/ +#define INT_SET(dst,count,value) { \ + int * int_set_dst = (dst); \ + int int_set_count = (count); \ + int int_set_value = (value); \ + while ( int_set_count-- > 0 ) \ + *int_set_dst++ = int_set_value; \ + } + +/* The code that calls it assumed dst gets bumped, so don't assign to a local variable */ +#define INT_COPY(dst,src,count) { \ + int * int_copy_src = (src); \ + int int_copy_count = (count); \ + while ( int_copy_count-- > 0 ) \ + *dst++ = *int_copy_src++; \ + } + + +/**************************************************************************/ +/**************************************************************************/ + /* STRUCTURES & TYPEDEFS */ +/**************************************************************************/ + +/**************************************************************************/ +/* In BZ_SORT.C - supports stdlib qsort() and customized quicksort */ +/**************************************************************************/ + +/* Used by call to stdlib qsort() */ +struct minutiae_struct { + int col[4]; +}; + +/* Used by custom quicksort */ +#define BZ_STACKSIZE 1000 +struct cell { + int index; /* pointer to an array of pointers to index arrays */ + int item; /* pointer to an item array */ +}; + +/**************************************************************************/ +/* In BZ_IO : Supports the loading and manipulation of XYT data */ +/**************************************************************************/ +#define MAX_FILE_MINUTIAE 1000 /* bz_load() */ + +struct xyt_struct { + int nrows; + int xcol[ MAX_BOZORTH_MINUTIAE ]; + int ycol[ MAX_BOZORTH_MINUTIAE ]; + int thetacol[ MAX_BOZORTH_MINUTIAE ]; +}; + +#define XYT_NULL ( (struct xyt_struct *) NULL ) /* bz_load() */ + + +/**************************************************************************/ +/**************************************************************************/ + /* GLOBAL VARIABLES */ +/**************************************************************************/ + +/**************************************************************************/ +/* In: SRC/BIN/BOZORTH3/BOZORTH3.C */ +/**************************************************************************/ +/* Globals supporting command line options */ +extern int m1_xyt; +extern int max_minutiae; +extern int min_computable_minutiae; +extern int verbose_main; +extern int verbose_load; +extern int verbose_bozorth; +extern int verbose_threshold; +/* Global supporting error reporting */ +extern FILE *errorfp; + +/**************************************************************************/ +/* In: BZ_GBLS.C */ +/**************************************************************************/ +/* Global arrays supporting "core" bozorth algorithm */ +extern int colp[ COLP_SIZE_1 ][ COLP_SIZE_2 ]; +extern int scols[ SCOLS_SIZE_1 ][ COLS_SIZE_2 ]; +extern int fcols[ FCOLS_SIZE_1 ][ COLS_SIZE_2 ]; +extern int * scolpt[ SCOLPT_SIZE ]; +extern int * fcolpt[ FCOLPT_SIZE ]; +extern int sc[ SC_SIZE ]; +extern int yl[ YL_SIZE_1 ][ YL_SIZE_2 ]; +/* Global arrays supporting "core" bozorth algorithm continued: */ +/* Globals used significantly by sift() */ +extern int rq[ RQ_SIZE ]; +extern int tq[ TQ_SIZE ]; +extern int zz[ ZZ_SIZE ]; +extern int rx[ RX_SIZE ]; +extern int mm[ MM_SIZE ]; +extern int nn[ NN_SIZE ]; +extern int qq[ QQ_SIZE ]; +extern int rk[ RK_SIZE ]; +extern int cp[ CP_SIZE ]; +extern int rp[ RP_SIZE ]; +extern int rf[RF_SIZE_1][RF_SIZE_2]; +extern int cf[CF_SIZE_1][CF_SIZE_2]; +extern int y[20000]; + +/**************************************************************************/ +/**************************************************************************/ +/* ROUTINE PROTOTYPES */ +/**************************************************************************/ +/* In: BZ_DRVRS.C */ +extern int bozorth_probe_init( struct xyt_struct *); +extern int bozorth_gallery_init( struct xyt_struct *); +extern int bozorth_to_gallery(int, struct xyt_struct *, struct xyt_struct *); +extern int bozorth_main(struct xyt_struct *, struct xyt_struct *); +/* In: BOZORTH3.C */ +extern void bz_comp(int, int [], int [], int [], int *, int [][COLS_SIZE_2], + int *[]); +extern void bz_find(int *, int *[]); +extern int bz_match(int, int); +extern int bz_match_score(int, struct xyt_struct *, struct xyt_struct *); +extern void bz_sift(int *, int, int *, int, int, int, int *, int *); +/* In: BZ_ALLOC.C */ +extern char *malloc_or_exit(int, const char *); +extern char *malloc_or_return_error(int, const char *); +/* In: BZ_IO.C */ +extern int parse_line_range(const char *, int *, int *); +extern void set_progname(int, char *, pid_t); +extern void set_probe_filename(char *); +extern void set_gallery_filename(char *); +extern char *get_progname(void); +extern char *get_probe_filename(void); +extern char *get_gallery_filename(void); +extern char *get_next_file(char *, FILE *, FILE *, int *, int *, char *, + int, char **, int *, int *, int, int); +extern char *get_score_filename(const char *, const char *); +extern char *get_score_line(const char *, const char *, int, int, const char *); +extern struct xyt_struct *bz_load(const char *); +extern int fd_readable(int); +/* In: BZ_SORT.C */ +extern int sort_quality_decreasing(const void *, const void *); +extern int sort_order_decreasing(int [], int, int []); + +#endif /* !_BOZORTH_H */ diff --git a/libfprint/nbis/include/bz_array.h b/libfprint/nbis/include/bz_array.h new file mode 100644 index 00000000..19b7da09 --- /dev/null +++ b/libfprint/nbis/include/bz_array.h @@ -0,0 +1,121 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +#ifndef _BZ_ARRAY_H +#define _BZ_ARRAY_H + +#define STATIC static +/* #define BAD_BOUNDS 1 */ + +#define COLP_SIZE_1 20000 +#define COLP_SIZE_2 5 + +#define COLS_SIZE_2 6 +#define SCOLS_SIZE_1 20000 +#define FCOLS_SIZE_1 20000 + +#define SCOLPT_SIZE 20000 +#define FCOLPT_SIZE 20000 + +#define SC_SIZE 20000 + + +#define RQ_SIZE 20000 +#define TQ_SIZE 20000 +#define ZZ_SIZE 20000 + + + +#define RX_SIZE 100 +#define MM_SIZE 100 +#define NN_SIZE 20 + + + +#define RK_SIZE 20000 + + + +#define RR_SIZE 100 +#define AVN_SIZE 5 +#define AVV_SIZE_1 2000 +#define AVV_SIZE_2 5 +#define CT_SIZE 2000 +#define GCT_SIZE 2000 +#define CTT_SIZE 2000 + + +#ifdef BAD_BOUNDS +#define CTP_SIZE_1 2000 +#define CTP_SIZE_2 1000 +#else +#define CTP_SIZE_1 2000 +#define CTP_SIZE_2 2500 +#endif + + + +/* +rp[x] == ctp[][x] :: sct[x][] +*/ + + + + +#define RF_SIZE_1 100 +#define RF_SIZE_2 10 + +#define CF_SIZE_1 100 +#define CF_SIZE_2 10 + +#define Y_SIZE 20000 + + + + + + +#define YL_SIZE_1 2 +#define YL_SIZE_2 2000 + + + + +#define YY_SIZE_1 1000 +#define YY_SIZE_2 2 +#define YY_SIZE_3 2000 + + + +#ifdef BAD_BOUNDS +#define SCT_SIZE_1 1000 +#define SCT_SIZE_2 1000 +#else +#define SCT_SIZE_1 2500 +#define SCT_SIZE_2 1000 +#endif + +#define CP_SIZE 20000 +#define RP_SIZE 20000 + +#endif /* !_BZ_ARRAY_H */ diff --git a/libfprint/nbis/include/defs.h b/libfprint/nbis/include/defs.h new file mode 100644 index 00000000..1e982d04 --- /dev/null +++ b/libfprint/nbis/include/defs.h @@ -0,0 +1,63 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +#ifndef _DEFS_H +#define _DEFS_H + +/*********************************************************************/ +/* General Purpose Defines */ +/*********************************************************************/ +#ifndef True +#define True 1 +#define False 0 +#endif +#ifndef TRUE +#define TRUE True +#define FALSE False +#endif +#define Yes True +#define No False +#define Empty NULL +#ifndef None +#define None -1 +#endif +#ifndef FOUND +#define FOUND 1 +#endif +#define NOT_FOUND_NEG -1 +#define EOL EOF +#ifndef DEG2RAD +#define DEG2RAD (double)(57.29578) +#endif +#define max(a, b) ((a) > (b) ? (a) : (b)) +#define min(a, b) ((a) < (b) ? (a) : (b)) +#define sround(x) ((int) (((x)<0) ? (x)-0.5 : (x)+0.5)) +#define sround_uint(x) ((unsigned int) (((x)<0) ? (x)-0.5 : (x)+0.5)) +#define xor(a, b) (!(a && b) && (a || b)) +#define align_to_16(_v_) ((((_v_)+15)>>4)<<4) +#define align_to_32(_v_) ((((_v_)+31)>>5)<<5) +#ifndef CHUNKS +#define CHUNKS 100 +#endif + +#endif /* !_DEFS_H */ diff --git a/libfprint/nbis/include/lfs.h b/libfprint/nbis/include/lfs.h new file mode 100644 index 00000000..b37147e1 --- /dev/null +++ b/libfprint/nbis/include/lfs.h @@ -0,0 +1,1208 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +#ifndef _LFS_H +#define _LFS_H + +/*********************************************************************** + PACKAGE: NIST Latent Fingerprint System + AUTHOR: Michael D. Garris + DATE: 03/16/1999 + UPDATED: 10/04/1999 Version 2 by MDG + UPDATED: 10/26/1999 by MDG + Comments added to guide changes to blocksize + or number of detected directions. + UPDATED: 03/11/2005 by MDG + + FILE: LFS.H + + Contains all custom structure definitions, constant definitions, + external function definitions, and external global variable + definitions required by the NIST Latent Fingerprint System (LFS). +***********************************************************************/ + +#include +#include + +/*************************************************************************/ +/* OUTPUT FILE EXTENSIONS */ +/*************************************************************************/ +#define MIN_TXT_EXT "min" +#define LOW_CONTRAST_MAP_EXT "lcm" +#define HIGH_CURVE_MAP_EXT "hcm" +#define DIRECTION_MAP_EXT "dm" +#define LOW_FLOW_MAP_EXT "lfm" +#define QUALITY_MAP_EXT "qm" +#define AN2K_OUT_EXT "mdt" +#define BINARY_IMG_EXT "brw" +#define XYT_EXT "xyt" + +/*************************************************************************/ +/* MINUTIAE XYT REPRESENTATION SCHEMES */ +/*************************************************************************/ +#define NIST_INTERNAL_XYT_REP 0 +#define M1_XYT_REP 1 + +/*************************************************************************/ +/* MACRO DEFINITIONS */ +/*************************************************************************/ + +#define max(a, b) ((a) > (b) ? (a) : (b)) +#define min(a, b) ((a) < (b) ? (a) : (b)) +#define sround(x) ((int) (((x)<0) ? (x)-0.5 : (x)+0.5)) +#define trunc_dbl_precision(x, scale) ((double) (((x)<0.0) \ + ? ((int)(((x)*(scale))-0.5))/(scale) \ + : ((int)(((x)*(scale))+0.5))/(scale))) + +#ifndef M_PI +#define M_PI 3.14159265358979323846 /* pi */ +#endif + +/*************************************************************************/ +/* STRUCTURE DEFINITIONS */ +/*************************************************************************/ + +/* Lookup tables for converting from integer directions */ +/* to angles in radians. */ +typedef struct dir2rad{ + int ndirs; + double *cos; + double *sin; +} DIR2RAD; + +/* DFT wave form structure containing both cosine and */ +/* sine components for a specific frequency. */ +typedef struct dftwave{ + double *cos; + double *sin; +} DFTWAVE; + +/* DFT wave forms structure containing all wave forms */ +/* to be used in DFT analysis. */ +typedef struct dftwaves{ + int nwaves; + int wavelen; + DFTWAVE **waves; +}DFTWAVES; + +/* Rotated pixel offsets for a grid of specified dimensions */ +/* rotated at a specified number of different orientations */ +/* (directions). This structure used by the DFT analysis */ +/* when generating a Direction Map and also for conducting */ +/* isotropic binarization. */ +typedef struct rotgrids{ + int pad; + int relative2; + double start_angle; + int ngrids; + int grid_w; + int grid_h; + int **grids; +} ROTGRIDS; + +/*************************************************************************/ +/* 10, 2X3 pixel pair feature patterns used to define ridge endings */ +/* and bifurcations. */ +/* 2nd pixel pair is permitted to repeat multiple times in match. */ +#define NFEATURES 10 +#define BIFURCATION 0 +#define RIDGE_ENDING 1 +#define DISAPPEARING 0 +#define APPEARING 1 + +typedef struct minutia{ + int x; + int y; + int ex; + int ey; + int direction; + double reliability; + int type; + int appearing; + int feature_id; + int *nbrs; + int *ridge_counts; + int num_nbrs; +} MINUTIA; + +typedef struct minutiae{ + int alloc; + int num; + MINUTIA **list; +} MINUTIAE; + +typedef struct feature_pattern{ + int type; + int appearing; + int first[2]; + int second[2]; + int third[2]; +} FEATURE_PATTERN; + +/* SHAPE structure definitions. */ +typedef struct rows{ + int y; /* Y-coord of current row in shape. */ + int *xs; /* X-coords for shape contour points on current row. */ + int alloc; /* Number of points allocate for x-coords on row. */ + int npts; /* Number of points assigned for x-coords on row. */ +} ROW; + +typedef struct shape{ + int ymin; /* Y-coord of top-most scanline in shape. */ + int ymax; /* Y-coord of bottom-most scanline in shape. */ + ROW **rows; /* List of row pointers comprising the shape. */ + int alloc; /* Number of rows allocated for shape. */ + int nrows; /* Number of rows assigned to shape. */ +} SHAPE; + +/* Parameters used by LFS for setting thresholds and */ +/* defining testing criterion. */ +typedef struct lfsparms{ + /* Image Controls */ + int pad_value; + int join_line_radius; + + /* Map Controls */ + int blocksize; /* Pixel dimension image block. */ + int windowsize; /* Pixel dimension window surrounding block. */ + int windowoffset; /* Offset in X & Y from block to window origin. */ + int num_directions; + double start_dir_angle; + int rmv_valid_nbr_min; + double dir_strength_min; + int dir_distance_max; + int smth_valid_nbr_min; + int vort_valid_nbr_min; + int highcurv_vorticity_min; + int highcurv_curvature_min; + int min_interpolate_nbrs; + int percentile_min_max; + int min_contrast_delta; + + /* DFT Controls */ + int num_dft_waves; + double powmax_min; + double pownorm_min; + double powmax_max; + int fork_interval; + double fork_pct_powmax; + double fork_pct_pownorm; + + /* Binarization Controls */ + int dirbin_grid_w; + int dirbin_grid_h; + int isobin_grid_dim; + int num_fill_holes; + + /* Minutiae Detection Controls */ + int max_minutia_delta; + double max_high_curve_theta; + int high_curve_half_contour; + int min_loop_len; + double min_loop_aspect_dist; + double min_loop_aspect_ratio; + + /* Minutiae Link Controls */ + int link_table_dim; + int max_link_dist; + int min_theta_dist; + int maxtrans; + double score_theta_norm; + double score_dist_norm; + double score_dist_weight; + double score_numerator; + + /* False Minutiae Removal Controls */ + int max_rmtest_dist; + int max_hook_len; + int max_half_loop; + int trans_dir_pix; + int small_loop_len; + int side_half_contour; + int inv_block_margin; + int rm_valid_nbr_min; + int max_overlap_dist; + int max_overlap_join_dist; + int malformation_steps_1; + int malformation_steps_2; + double min_malformation_ratio; + int max_malformation_dist; + int pores_trans_r; + int pores_perp_steps; + int pores_steps_fwd; + int pores_steps_bwd; + double pores_min_dist2; + double pores_max_ratio; + + /* Ridge Counting Controls */ + int max_nbrs; + int max_ridge_steps; +} LFSPARMS; + +/*************************************************************************/ +/* LFS CONSTANT DEFINITIONS */ +/*************************************************************************/ + +/***** IMAGE CONSTANTS *****/ + +#ifndef DEFAULT_PPI +#define DEFAULT_PPI 500 +#endif + +/* Intensity used to fill padded image area */ +#define PAD_VALUE 128 /* medium gray @ 8 bits */ + +/* Intensity used to draw on grayscale images */ +#define DRAW_PIXEL 255 /* white in 8 bits */ + +/* Definitions for 8-bit binary pixel intensities. */ +#define WHITE_PIXEL 255 +#define BLACK_PIXEL 0 + +/* Definitions for controlling join_miutia(). */ +/* Draw without opposite perimeter pixels. */ +#define NO_BOUNDARY 0 + +/* Draw with opposite perimeter pixels. */ +#define WITH_BOUNDARY 1 + +/* Radial width added to join line (not including the boundary pixels). */ +#define JOIN_LINE_RADIUS 1 + + +/***** MAP CONSTANTS *****/ + +/* Map value for not well-defined directions */ +#define INVALID_DIR -1 + +/* Map value assigned when the current block has no neighbors */ +/* with valid direction. */ +#define NO_VALID_NBRS -3 + +/* Map value designating a block is near a high-curvature */ +/* area such as a core or delta. */ +#define HIGH_CURVATURE -2 + +/* This specifies the pixel dimensions of each block in the IMAP */ +#define IMAP_BLOCKSIZE 24 + +/* Pixel dimension of image blocks. The following three constants work */ +/* together to define a system of 8X8 adjacent and non-overlapping */ +/* blocks that are assigned results from analyzing a larger 24X24 */ +/* window centered about each of the 8X8 blocks. */ +/* CAUTION: If MAP_BLOCKSIZE_V2 is changed, then the following will */ +/* likely need to be changed: MAP_WINDOWOFFSET_V2, */ +/* TRANS_DIR_PIX_V2, */ +/* INV_BLOCK_MARGIN_V2 */ +#define MAP_BLOCKSIZE_V2 8 + +/* Pixel dimension of window that surrounds the block. The result from */ +/* analyzing the content of the window is stored in the interior block. */ +#define MAP_WINDOWSIZE_V2 24 + +/* Pixel offset in X & Y from the origin of the block to the origin of */ +/* the surrounding window. */ +#define MAP_WINDOWOFFSET_V2 8 + +/* This is the number of integer directions to be used in semicircle. */ +/* CAUTION: If NUM_DIRECTIONS is changed, then the following will */ +/* likely need to be changed: HIGHCURV_VORTICITY_MIN, */ +/* HIGHCURV_CURVATURE_MIN, */ +/* FORK_INTERVAL */ +#define NUM_DIRECTIONS 16 + +/* This is the theta from which integer directions */ +/* are to begin. */ +#define START_DIR_ANGLE (double)(M_PI/2.0) /* 90 degrees */ + +/* Minimum number of valid neighbors required for a */ +/* valid block value to keep from being removed. */ +#define RMV_VALID_NBR_MIN 3 + +/* Minimum strength for a direction to be considered significant. */ +#define DIR_STRENGTH_MIN 0.2 + +/* Maximum distance allowable between valid block direction */ +/* and the average direction of its neighbors before the */ +/* direction is removed. */ +#define DIR_DISTANCE_MAX 3 + +/* Minimum number of valid neighbors required for an */ +/* INVALID block direction to receive its direction from */ +/* the average of its neighbors. */ +#define SMTH_VALID_NBR_MIN 7 + +/* Minimum number of valid neighbors required for a block */ +/* with an INVALID block direction to be measured for */ +/* vorticity. */ +#define VORT_VALID_NBR_MIN 7 + +/* The minimum vorticity value whereby an INVALID block */ +/* is determined to be high-curvature based on the directions */ +/* of it neighbors. */ +#define HIGHCURV_VORTICITY_MIN 5 + +/* The minimum curvature value whereby a VALID direction block is */ +/* determined to be high-curvature based on it value compared with */ +/* its neighbors' directions. */ +#define HIGHCURV_CURVATURE_MIN 5 + +/* Minimum number of neighbors with VALID direction for an INVALID */ +/* directon block to have its direction interpolated from those neighbors. */ +#define MIN_INTERPOLATE_NBRS 2 + +/* Definitions for creating a low contrast map. */ +/* Percentile cut off for choosing min and max pixel intensities */ +/* in a block. */ +#define PERCENTILE_MIN_MAX 10 + +/* The minimum delta between min and max percentile pixel intensities */ +/* in block for block NOT to be considered low contrast. (Note that */ +/* this value is in terms of 6-bit pixels.) */ +#define MIN_CONTRAST_DELTA 5 + + +/***** DFT CONSTANTS *****/ + +/* This specifies the number of DFT wave forms to be applied */ +#define NUM_DFT_WAVES 4 + +/* Minimum total DFT power for any given block */ +/* which is used to compute an average power. */ +/* By setting a non-zero minimum total,possible */ +/* division by zero is avoided. This value was */ +/* taken from HO39. */ +#define MIN_POWER_SUM 10.0 + +/* Thresholds and factors used by HO39. Renamed */ +/* here to give more meaning. */ + /* HO39 Name=Value */ +/* Minimum DFT power allowable in any one direction. */ +#define POWMAX_MIN 100000.0 /* thrhf=1e5f */ + +/* Minimum normalized power allowable in any one */ +/* direction. */ +#define POWNORM_MIN 3.8 /* disc=3.8f */ + +/* Maximum power allowable at the lowest frequency */ +/* DFT wave. */ +#define POWMAX_MAX 50000000.0 /* thrlf=5e7f */ + +/* Check for a fork at +- this number of units from */ +/* current integer direction. For example, */ +/* 2 dir ==> 11.25 X 2 degrees. */ +#define FORK_INTERVAL 2 + +/* Minimum DFT power allowable at fork angles is */ +/* FORK_PCT_POWMAX X block's max directional power. */ +#define FORK_PCT_POWMAX 0.7 + +/* Minimum normalized power allowable at fork angles */ +/* is FORK_PCT_POWNORM X POWNORM_MIN */ +#define FORK_PCT_POWNORM 0.75 + + +/***** BINRAIZATION CONSTANTS *****/ + +/* Directional binarization grid dimensions. */ +#define DIRBIN_GRID_W 7 +#define DIRBIN_GRID_H 9 + +/* The pixel dimension (square) of the grid used in isotropic */ +/* binarization. */ +#define ISOBIN_GRID_DIM 11 + +/* Number of passes through the resulting binary image where holes */ +/* of pixel length 1 in horizontal and vertical runs are filled. */ +#define NUM_FILL_HOLES 3 + + +/***** MINUTIAE DETECTION CONSTANTS *****/ + +/* The maximum pixel translation distance in X or Y within which */ +/* two potential minutia points are to be considered similar. */ +#define MAX_MINUTIA_DELTA 10 + +/* If the angle of a contour exceeds this angle, then it is NOT */ +/* to be considered to contain minutiae. */ +#define MAX_HIGH_CURVE_THETA (double)(M_PI/3.0) + +/* Half the length in pixels to be extracted for a high-curvature contour. */ +#define HIGH_CURVE_HALF_CONTOUR 14 + +/* Loop must be larger than this threshold (in pixels) to be considered */ +/* to contain minutiae. */ +#define MIN_LOOP_LEN 20 + +/* If loop's minimum distance half way across its contour is less than */ +/* this threshold, then loop is tested for minutiae. */ +#define MIN_LOOP_ASPECT_DIST 1.0 + +/* If ratio of loop's maximum/minimum distances half way across its */ +/* contour is >= to this threshold, then loop is tested for minutiae. */ +#define MIN_LOOP_ASPECT_RATIO 2.25 + +/* There are 10 unique feature patterns with ID = [0..9] , */ +/* so set LOOP ID to 10 (one more than max pattern ID). */ +#define LOOP_ID 10 + +/* Definitions for controlling the scanning of minutiae. */ +#define SCAN_HORIZONTAL 0 +#define SCAN_VERTICAL 1 +#define SCAN_CLOCKWISE 0 +#define SCAN_COUNTER_CLOCKWISE 1 + +/* The dimension of the chaincode loopkup matrix. */ +#define NBR8_DIM 3 + +/* Default minutiae reliability. */ +#define DEFAULT_RELIABILITY 0.99 + +/* Medium minutia reliability. */ +#define MEDIUM_RELIABILITY 0.50 + +/* High minutia reliability. */ +#define HIGH_RELIABILITY 0.99 + + +/***** MINUTIAE LINKING CONSTANTS *****/ + +/* Definitions for controlling the linking of minutiae. */ +/* Square dimensions of 2D table of potentially linked minutiae. */ +#define LINK_TABLE_DIM 20 + +/* Distance (in pixels) used to determine if the orthogonal distance */ +/* between the coordinates of 2 minutia points are sufficiently close */ +/* to be considered for linking. */ +#define MAX_LINK_DIST 20 + +/* Minimum distance (in pixels) between 2 minutia points that an angle */ +/* computed between the points may be considered reliable. */ +#define MIN_THETA_DIST 5 + +/* Maximum number of transitions along a contiguous pixel trajectory */ +/* between 2 minutia points for that trajectory to be considered "free" */ +/* of obstacles. */ +#define MAXTRANS 2 + +/* Parameters used to compute a link score between 2 minutiae. */ +#define SCORE_THETA_NORM 15.0 +#define SCORE_DIST_NORM 10.0 +#define SCORE_DIST_WEIGHT 4.0 +#define SCORE_NUMERATOR 32000.0 + + +/***** FALSE MINUTIAE REMOVAL CONSTANTS *****/ + +/* Definitions for removing hooks, islands, lakes, and overlaps. */ +/* Distance (in pixels) used to determine if the orthogonal distance */ +/* between the coordinates of 2 minutia points are sufficiently close */ +/* to be considered for removal. */ +#define MAX_RMTEST_DIST 8 + +#define MAX_RMTEST_DIST_V2 16 + +/* Length of pixel contours to be traced and analyzed for possible hooks. */ +#define MAX_HOOK_LEN 15 + +#define MAX_HOOK_LEN_V2 30 + +/* Half the maximum length of pixel contours to be traced and analyzed */ +/* for possible loops (islands/lakes). */ +#define MAX_HALF_LOOP 15 + +#define MAX_HALF_LOOP_V2 30 + +/* Definitions for removing minutiae that are sufficiently close and */ +/* point to a block with invalid ridge flow. */ +/* Distance (in pixels) in direction opposite the minutia to be */ +/* considered sufficiently close to an invalid block. */ +#define TRANS_DIR_PIX 6 + +#define TRANS_DIR_PIX_V2 4 + +/* Definitions for removing small holes (islands/lakes). */ +/* Maximum circumference (in pixels) of qualifying loops. */ +#define SMALL_LOOP_LEN 15 + +/* Definitions for removing or adusting side minutiae. */ +/* Half the number of pixels to be traced to form a complete contour. */ +#define SIDE_HALF_CONTOUR 7 + +/* Definitions for removing minutiae near invalid blocks. */ +/* Maximum orthogonal distance a minutia can be neighboring a block with */ +/* invalid ridge flow in order to be removed. */ +#define INV_BLOCK_MARGIN 6 + +#define INV_BLOCK_MARGIN_V2 4 + +/* Given a sufficiently close, neighboring invalid block, if that invalid */ +/* block has a total number of neighboring blocks with valid ridge flow */ +/* less than this threshold, then the minutia point is removed. */ +#define RM_VALID_NBR_MIN 7 + +/* Definitions for removing overlaps. */ +/* Maximum pixel distance between 2 points to be tested for overlapping */ +/* conditions. */ +#define MAX_OVERLAP_DIST 8 + +/* Maximum pixel distance between 2 points on opposite sides of an overlap */ +/* will be joined. */ +#define MAX_OVERLAP_JOIN_DIST 6 + +/* Definitions for removing "irregularly-shaped" minutiae. */ +/* Contour steps to be traced to 1st measuring point. */ +#define MALFORMATION_STEPS_1 10 +/* Contour steps to be traced to 2nd measuring point. */ +#define MALFORMATION_STEPS_2 20 +/* Minimum ratio of distances across feature at the two point to be */ +/* considered normal. */ +#define MIN_MALFORMATION_RATIO 2.0 +/* Maximum distance permitted across feature to be considered normal. */ +#define MAX_MALFORMATION_DIST 20 + +/* Definitions for removing minutiae on pores. */ +/* Translation distance (in pixels) from minutia point in opposite direction */ +/* in order to get off a valley edge and into the neighboring ridge. */ +#define PORES_TRANS_R 3 + +/* Number of steps (in pixels) to search for edge of current ridge. */ +#define PORES_PERP_STEPS 12 + +/* Number of pixels to be traced to find forward contour points. */ +#define PORES_STEPS_FWD 10 + +/* Number of pixels to be traced to find backward contour points. */ +#define PORES_STEPS_BWD 8 + +/* Minimum squared distance between points before being considered zero. */ +#define PORES_MIN_DIST2 0.5 + +/* Max ratio of computed distances between pairs of forward and backward */ +/* contour points to be considered a pore. */ +#define PORES_MAX_RATIO 2.25 + + +/***** RIDGE COUNTING CONSTANTS *****/ + +/* Definitions for detecting nearest neighbors and counting ridges. */ +/* Maximum number of nearest neighbors per minutia. */ +#define MAX_NBRS 5 + +/* Maximum number of contour steps taken to validate a ridge crossing. */ +#define MAX_RIDGE_STEPS 10 + +/*************************************************************************/ +/* QUALITY/RELIABILITY DEFINITIONS */ +/*************************************************************************/ +/* Quality map levels */ +#define QMAP_LEVELS 5 + +/* Neighborhood radius in millimeters computed from 11 pixles */ +/* scanned at 19.69 pixels/mm. */ +#define RADIUS_MM ((double)(11.0 / 19.69)) + +/* Ideal Standard Deviation of pixel values in a neighborhood. */ +#define IDEALSTDEV 64 +/* Ideal Mean of pixel values in a neighborhood. */ +#define IDEALMEAN 127 + +/* Look for neighbors this many blocks away. */ +#define NEIGHBOR_DELTA 2 + +/*************************************************************************/ +/* GENERAL DEFINITIONS */ +/*************************************************************************/ +#define LFS_VERSION_STR "NIST_LFS_VER2" + +/* This factor converts degrees to radians. */ +#ifndef DEG2RAD +#define DEG2RAD (double)(M_PI/180.0) +#endif + +#define NORTH 0 +#define SOUTH 4 +#define EAST 2 +#define WEST 6 + +#ifndef TRUE +#define TRUE 1 +#endif +#ifndef FALSE +#define FALSE 0 +#endif + +#ifndef FOUND +#define FOUND TRUE +#endif +#ifndef NOT_FOUND +#define NOT_FOUND FALSE +#endif + +#define HOOK_FOUND 1 +#define LOOP_FOUND 1 +#define IGNORE 2 +#define LIST_FULL 3 +#define INCOMPLETE 3 + +/* Pixel value limit in 6-bit image. */ +#define IMG_6BIT_PIX_LIMIT 64 + +/* Maximum number (or reallocated chunks) of minutia to be detected */ +/* in an image. */ +#define MAX_MINUTIAE 1000 + +/* If both deltas in X and Y for a line of specified slope is less than */ +/* this threshold, then the angle for the line is set to 0 radians. */ +#define MIN_SLOPE_DELTA 0.5 + +/* Designates that rotated grid offsets should be relative */ +/* to the grid's center. */ +#define RELATIVE2CENTER 0 + +/* Designates that rotated grid offsets should be relative */ +/* to the grid's origin. */ +#define RELATIVE2ORIGIN 1 + +/* Truncate floating point precision by multiply, rounding, and then */ +/* dividing by this value. This enables consistant results across */ +/* different computer architectures. */ +#define TRUNC_SCALE 16384.0 + +/* Designates passed argument as undefined. */ +#define UNDEFINED -1 + +/* Dummy values for unused LFS control parameters. */ +#define UNUSED_INT 0 +#define UNUSED_DBL 0.0 + +/*************************************************************************/ +/* EXTERNAL FUNCTION DEFINITIONS */ +/*************************************************************************/ + +/* binar.c */ +extern int binarize(unsigned char **, int *, int *, + unsigned char *, const int, const int, + int *, const int, const int, + const ROTGRIDS *, const LFSPARMS *); +extern int binarize_V2(unsigned char **, int *, int *, + unsigned char *, const int, const int, + int *, const int, const int, + const ROTGRIDS *, const LFSPARMS *); +extern int binarize_image(unsigned char **, int *, int *, + unsigned char *, const int, const int, + const int *, const int, const int, const int, + const ROTGRIDS *, const int); +extern int binarize_image_V2(unsigned char **, int *, int *, + unsigned char *, const int, const int, + const int *, const int, const int, + const int, const ROTGRIDS *); +extern int dirbinarize(const unsigned char *, const int, const ROTGRIDS *); +extern int isobinarize(unsigned char *, const int, const int, const int); + +/* block.c */ +extern int block_offsets(int **, int *, int *, const int, const int, + const int, const int); +extern int low_contrast_block(const int, const int, + unsigned char *, const int, const int, const LFSPARMS *); +extern int find_valid_block(int *, int *, int *, int *, int *, + const int, const int, const int, const int, + const int, const int); +extern void set_margin_blocks(int *, const int, const int, const int); + +/* chaincod.c */ +extern int chain_code_loop(int **, int *, const int *, const int *, const int); +extern int is_chain_clockwise(const int *, const int, const int); + +/* contour.c */ +extern int allocate_contour(int **, int **, int **, int **, const int); +extern void free_contour(int *, int *, int *, int *); +extern int get_high_curvature_contour(int **, int **, int **, int **, int *, + const int, const int, const int, const int, const int, + unsigned char *, const int, const int); +extern int get_centered_contour(int **, int **, int **, int **, int *, + const int, const int, const int, const int, const int, + unsigned char *, const int, const int); +extern int trace_contour(int **, int **, int **, int **, int *, + const int, const int, const int, const int, const int, + const int, const int, const int, + unsigned char *, const int, const int); +extern int search_contour(const int, const int, const int, + const int, const int, const int, const int, const int, + unsigned char *, const int, const int); +extern int next_contour_pixel(int *, int *, int *, int *, + const int, const int, const int, const int, const int, + unsigned char *, const int, const int); +extern int start_scan_nbr(const int, const int, const int, const int); +extern int next_scan_nbr(const int, const int); +extern int min_contour_theta(int *, double *, const int, const int *, + const int *, const int); +extern void contour_limits(int *, int *, int *, int *, const int *, + const int *, const int); +extern void fix_edge_pixel_pair(int *, int *, int *, int *, + unsigned char *, const int, const int); + +/* detect.c */ +extern int lfs_detect_minutiae( MINUTIAE **, + int **, int **, int *, int *, + unsigned char **, int *, int *, + unsigned char *, const int, const int, + const LFSPARMS *); + +extern int lfs_detect_minutiae_V2(MINUTIAE **, + int **, int **, int **, int **, int *, int *, + unsigned char **, int *, int *, + unsigned char *, const int, const int, + const LFSPARMS *); + +/* dft.c */ +extern int dft_dir_powers(double **, unsigned char *, const int, + const int, const int, const DFTWAVES *, + const ROTGRIDS *); +extern void sum_rot_block_rows(int *, const unsigned char *, const int *, + const int); +extern void dft_power(double *, const int *, const DFTWAVE *, const int); +extern int dft_power_stats(int *, double *, int *, double *, double **, + const int, const int, const int); +extern void get_max_norm(double *, int *, double *, const double *, const int); +extern int sort_dft_waves(int *, const double *, const double *, const int); + +/* free.c */ +extern void free_dir2rad(DIR2RAD *); +extern void free_dftwaves(DFTWAVES *); +extern void free_rotgrids(ROTGRIDS *); +extern void free_dir_powers(double **, const int); + +/* getmin.c */ +extern int get_minutiae(MINUTIAE **, int **, int **, int **, + int **, int **, int *, int *, + unsigned char **, int *, int *, int *, + unsigned char *, const int, const int, + const int, const double, const LFSPARMS *); + +/* imgutil.c */ +extern void bits_6to8(unsigned char *, const int, const int); +extern void bits_8to6(unsigned char *, const int, const int); +extern void gray2bin(const int, const int, const int, + unsigned char *, const int, const int); +extern int pad_uchar_image(unsigned char **, int *, int *, + unsigned char *, const int, const int, const int, + const int); +extern void fill_holes(unsigned char *, const int, const int); +extern int free_path(const int, const int, const int, const int, + unsigned char *, const int, const int, const LFSPARMS *); +extern int search_in_direction(int *, int *, int *, int *, const int, + const int, const int, const double, const double, + const int, unsigned char *, const int, const int); + +/* init.c */ +extern int init_dir2rad(DIR2RAD **, const int); +extern int init_dftwaves(DFTWAVES **, const double *, const int, const int); +extern int get_max_padding(const int, const int, const int, const int); +extern int get_max_padding_V2(const int, const int, const int, const int); +extern int init_rotgrids(ROTGRIDS **, const int, const int, const int, + const double, const int, const int, const int, const int); +extern int alloc_dir_powers(double ***, const int, const int); +extern int alloc_power_stats(int **, double **, int **, double **, const int); + +/* isempty.c */ +extern int is_image_empty(int *, const int, const int); +extern int is_qmap_empty(int *, const int, const int); + + +/* line.c */ +extern int line_points(int **, int **, int *, + const int, const int, const int, const int); +extern int bresenham_line_points(int **, int **, int *, + const int, const int, const int, const int); + +/* link.c */ +extern int link_minutiae(MINUTIAE *, unsigned char *, const int, const int, + int *, const int, const int, const LFSPARMS *); +extern int create_link_table(int **, int **, int **, int *, int *, int *, + const int, const int, const MINUTIAE *, const int *, + int *, const int, const int, unsigned char *, + const int, const int, const LFSPARMS *); +extern int update_link_table(int *, int *, int *, int *, int *, int *, + const int, int *, int *, int *, int *, + const int, const int, const int); +extern int order_link_table(int *, int *, int *, const int, const int, + const int, const int, const MINUTIAE *, const int); +extern int process_link_table(const int *, const int *, const int *, + const int, const int, const int, const int, MINUTIAE *, + int *, unsigned char *, const int, const int, + const LFSPARMS *); +extern double link_score(const double, const double, const LFSPARMS *); + +/* loop.c */ +extern int get_loop_list(int **, MINUTIAE *, const int, unsigned char *, + const int, const int); +extern int on_loop(const MINUTIA *, const int, unsigned char *, const int, + const int); +extern int on_island_lake(int **, int **, int **, int **, int *, + const MINUTIA *, const MINUTIA *, const int, + unsigned char *, const int, const int); +extern int on_hook(const MINUTIA *, const MINUTIA *, const int, + unsigned char *, const int, const int); +extern int is_loop_clockwise(const int *, const int *, const int, const int); +extern int process_loop(MINUTIAE *, const int *, const int *, + const int *, const int *, const int, + unsigned char *, const int, const int, const LFSPARMS *); +extern int process_loop_V2(MINUTIAE *, const int *, const int *, + const int *, const int *, const int, + unsigned char *, const int, const int, + int *, const LFSPARMS *); +extern void get_loop_aspect(int *, int *, double *, int *, int *, double *, + const int *, const int *, const int); +extern int fill_loop(const int *, const int *, const int, + unsigned char *, const int, const int); +extern void fill_partial_row(const int, const int, const int, const int, + unsigned char *, const int, const int); +extern void flood_loop(const int *, const int *, const int, + unsigned char *, const int, const int); +extern void flood_fill4(const int, const int, const int, + unsigned char *, const int, const int); + +/* maps.c */ +extern int gen_image_maps(int **, int **, int **, int **, int *, int *, + unsigned char *, const int, const int, + const DIR2RAD *, const DFTWAVES *, + const ROTGRIDS *, const LFSPARMS *); +extern int gen_initial_maps(int **, int **, int **, + int *, const int, const int, + unsigned char *, const int, const int, + const DFTWAVES *, const ROTGRIDS *, const LFSPARMS *); +extern int interpolate_direction_map(int *, int *, const int, const int, + const LFSPARMS *); +extern int morph_TF_map(int *, const int, const int, const LFSPARMS *); +extern int pixelize_map(int **, const int, const int, + int *, const int, const int, const int); +extern void smooth_direction_map(int *, int *, const int, const int, + const DIR2RAD *, const LFSPARMS *); +extern int gen_high_curve_map(int **, int *, const int, const int, + const LFSPARMS *); +extern int gen_imap(int **, int *, int *, + unsigned char *, const int, const int, + const DIR2RAD *, const DFTWAVES *, const ROTGRIDS *, + const LFSPARMS *); +extern int gen_initial_imap(int **, int *, const int, const int, + unsigned char *, const int, const int, + const DFTWAVES *, const ROTGRIDS *, const LFSPARMS *); +extern int primary_dir_test(double **, const int *, const double *, + const int *, const double *, const int, + const LFSPARMS *); +extern int secondary_fork_test(double **, const int *, const double *, + const int *, const double *, const int, + const LFSPARMS *); +extern void remove_incon_dirs(int *, const int, const int, + const DIR2RAD *, const LFSPARMS *); +extern int test_top_edge(const int, const int, const int, const int, + int *, const int, const int, const DIR2RAD *, + const LFSPARMS *); +extern int test_right_edge(const int, const int, const int, const int, + int *, const int, const int, const DIR2RAD *, + const LFSPARMS *); +extern int test_bottom_edge(const int, const int, const int, const int, + int *, const int, const int, const DIR2RAD *, + const LFSPARMS *); +extern int test_left_edge(const int, const int, const int, const int, + int *, const int, const int, const DIR2RAD *, + const LFSPARMS *); +extern int remove_dir(int *, const int, const int, const int, const int, + const DIR2RAD *, const LFSPARMS *); +extern void average_8nbr_dir(int *, double *, int *, int *, const int, + const int, const int, const int, const DIR2RAD *); +extern int num_valid_8nbrs(int *, const int, const int, const int, const int); +extern void smooth_imap(int *, const int, const int, const DIR2RAD *, + const LFSPARMS *); +extern int gen_nmap(int **, int *, const int, const int, const LFSPARMS *); +extern int vorticity(int *, const int, const int, const int, const int, + const int); +extern void accum_nbr_vorticity(int *, const int, const int, const int); +extern int curvature(int *, const int, const int, const int, const int, + const int); + +/* matchpat.c */ +extern int match_1st_pair(unsigned char, unsigned char, int *, int *); +extern int match_2nd_pair(unsigned char, unsigned char, int *, int *); +extern int match_3rd_pair(unsigned char, unsigned char, int *, int *); +extern void skip_repeated_horizontal_pair(int *, const int, + unsigned char **, unsigned char **, const int, const int); +extern void skip_repeated_vertical_pair(int *, const int, + unsigned char **, unsigned char **, const int, const int); + +/* minutia.c */ +extern int alloc_minutiae(MINUTIAE **, const int); +extern int realloc_minutiae(MINUTIAE *, const int); +extern int detect_minutiae(MINUTIAE *, unsigned char *, const int, const int, + const int *, const int *, const int, const int, + const LFSPARMS *); +extern int detect_minutiae_V2(MINUTIAE *, + unsigned char *, const int, const int, + int *, int *, int *, const int, const int, + const LFSPARMS *); +extern int update_minutiae(MINUTIAE *, MINUTIA *, unsigned char *, + const int, const int, const LFSPARMS *); +extern int update_minutiae_V2(MINUTIAE *, MINUTIA *, const int, const int, + unsigned char *, const int, const int, + const LFSPARMS *); +extern int sort_minutiae(MINUTIAE *, const int, const int); +extern int sort_minutiae_y_x(MINUTIAE *, const int, const int); +extern int sort_minutiae_x_y(MINUTIAE *, const int, const int); +extern int rm_dup_minutiae(MINUTIAE *); +extern void dump_minutiae(FILE *, const MINUTIAE *); +extern void dump_minutiae_pts(FILE *, const MINUTIAE *); +extern void dump_reliable_minutiae_pts(FILE *, const MINUTIAE *, const double); +extern int create_minutia(MINUTIA **, const int, const int, + const int, const int, const int, const double, + const int, const int, const int); +extern void free_minutiae(MINUTIAE *); +extern void free_minutia(MINUTIA *); +extern int remove_minutia(const int, MINUTIAE *); +extern int join_minutia(const MINUTIA *, const MINUTIA *, unsigned char *, + const int, const int, const int, const int); +extern int minutia_type(const int); +extern int is_minutia_appearing(const int, const int, const int, const int); +extern int choose_scan_direction(const int, const int); +int scan4minutiae(MINUTIAE *, unsigned char *, const int, const int, + const int *, const int *, const int, const int, + const int, const int, const int, const int, + const int, const int, const int, const LFSPARMS *); +extern int scan4minutiae_horizontally(MINUTIAE *, unsigned char *, + const int, const int, const int, const int, + const int, const int, const int, const int, + const LFSPARMS *); +extern int scan4minutiae_horizontally_V2(MINUTIAE *, + unsigned char *, const int, const int, + int *, int *, int *, + const LFSPARMS *); +extern int scan4minutiae_vertically(MINUTIAE *, unsigned char *, + const int, const int, const int, const int, + const int, const int, const int, const int, + const LFSPARMS *); +extern int rescan4minutiae_horizontally(MINUTIAE *, unsigned char *bdata, + const int, const int, const int *, const int *, + const int, const int, const int, const int, + const int, const int, const int, const int, + const LFSPARMS *); +extern int scan4minutiae_vertically_V2(MINUTIAE *, + unsigned char *, const int, const int, + int *, int *, int *, const LFSPARMS *); +extern int rescan4minutiae_vertically(MINUTIAE *, unsigned char *, + const int, const int, const int *, const int *, + const int, const int, const int, const int, + const int, const int, const int, const int, + const LFSPARMS *); +extern int rescan_partial_horizontally(const int, MINUTIAE *, + unsigned char *, const int, const int, + const int *, const int *, + const int, const int, const int, const int, + const int, const int, const int, const int, + const LFSPARMS *); +extern int rescan_partial_vertically(const int, MINUTIAE *, + unsigned char *, const int, const int, + const int *, const int *, + const int, const int, const int, const int, + const int, const int, const int, const int, + const LFSPARMS *); +extern int get_nbr_block_index(int *, const int, const int, const int, + const int, const int); +extern int adjust_horizontal_rescan(const int, int *, int *, int *, int *, + const int, const int, const int, const int, const int); +extern int adjust_vertical_rescan(const int, int *, int *, int *, int *, + const int, const int, const int, const int, const int); +extern int process_horizontal_scan_minutia(MINUTIAE *, const int, const int, + const int, const int, + unsigned char *, const int, const int, + const int, const int, const LFSPARMS *); +extern int process_horizontal_scan_minutia_V2(MINUTIAE *, + const int, const int, const int, const int, + unsigned char *, const int, const int, + int *, int *, int *, const LFSPARMS *); +extern int process_vertical_scan_minutia(MINUTIAE *, const int, const int, + const int, const int, + unsigned char *, const int, const int, + const int, const int, const LFSPARMS *); +extern int process_vertical_scan_minutia_V2(MINUTIAE *, const int, const int, + const int, const int, + unsigned char *, const int, const int, + int *, int *, int *, const LFSPARMS *); +extern int update_minutiae_V2(MINUTIAE *, MINUTIA *, const int, const int, + unsigned char *, const int, const int, + const LFSPARMS *); +extern int adjust_high_curvature_minutia(int *, int *, int *, int *, int *, + const int, const int, const int, const int, + unsigned char *, const int, const int, + MINUTIAE *, const LFSPARMS *); +extern int adjust_high_curvature_minutia_V2(int *, int *, int *, + int *, int *, const int, const int, + const int, const int, + unsigned char *, const int, const int, + int *, MINUTIAE *, const LFSPARMS *); +extern int get_low_curvature_direction(const int, const int, const int, + const int); + +/* quality.c */ +extern int gen_quality_map(int **, int *, int *, int *, int *, + const int, const int); +extern int combined_minutia_quality(MINUTIAE *, int *, const int, const int, + const int, unsigned char *, const int, const int, + const int, const double); +double grayscale_reliability(MINUTIA *, unsigned char *, + const int, const int, const int); +extern void get_neighborhood_stats(double *, double *, MINUTIA *, + unsigned char *, const int, const int, const int); +extern int reliability_fr_quality_map(MINUTIAE *, int *, const int, + const int, const int, const int, const int); + +/* remove.c */ +extern int remove_false_minutia(MINUTIAE *, + unsigned char *, const int, const int, + int *, const int, const int, const LFSPARMS *); +extern int remove_false_minutia_V2(MINUTIAE *, + unsigned char *, const int, const int, + int *, int *, int *, const int, const int, + const LFSPARMS *); +extern int remove_holes(MINUTIAE *, unsigned char *, const int, const int, + const LFSPARMS *); +extern int remove_hooks(MINUTIAE *, + unsigned char *, const int, const int, const LFSPARMS *); +extern int remove_hooks_islands_lakes_overlaps(MINUTIAE *, unsigned char *, + const int, const int, const LFSPARMS *); +extern int remove_islands_and_lakes(MINUTIAE *, + unsigned char *, const int, const int, const LFSPARMS *); +extern int remove_malformations(MINUTIAE *, + unsigned char *, const int, const int, + int *, const int, const int, const LFSPARMS *); +extern int remove_near_invblock(MINUTIAE *, int *, const int, const int, + const LFSPARMS *); +extern int remove_near_invblock_V2(MINUTIAE *, int *, + const int, const int, const LFSPARMS *); +extern int remove_pointing_invblock(MINUTIAE *, int *, const int, const int, + const LFSPARMS *); +extern int remove_pointing_invblock_V2(MINUTIAE *, + int *, const int, const int, const LFSPARMS *); +extern int remove_overlaps(MINUTIAE *, + unsigned char *, const int, const int, const LFSPARMS *); +extern int remove_pores(MINUTIAE *, + unsigned char *, const int, const int, + int *, const int, const int, const LFSPARMS *); +extern int remove_pores_V2(MINUTIAE *, + unsigned char *, const int, const int, + int *, int *, int *, const int, const int, + const LFSPARMS *); +extern int remove_or_adjust_side_minutiae(MINUTIAE *, unsigned char *, + const int, const int, const LFSPARMS *); +extern int remove_or_adjust_side_minutiae_V2(MINUTIAE *, + unsigned char *, const int, const int, + int *, const int, const int, const LFSPARMS *); + +/* results.c */ +extern int write_text_results(char *, const int, const int, const int, + const MINUTIAE *, int *, int *, int *, int *, int *, + const int, const int); +extern int write_minutiae_XYTQ(char *ofile, const int, + const MINUTIAE *, const int, const int); +extern void dump_map(FILE *, int *, const int, const int); +extern int drawimap(int *, const int, const int, unsigned char *, + const int, const int, const ROTGRIDS *, const int); +extern void drawimap2(int *, const int *, const int, const int, + unsigned char *, const int, const int, + const double, const int, const int); +extern void drawblocks(const int *, const int, const int, + unsigned char *, const int, const int, const int ); +extern int drawrotgrid(const ROTGRIDS *, const int, unsigned char *, + const int, const int, const int, const int); +extern void dump_link_table(FILE *, const int *, const int *, const int *, + const int, const int, const int, const MINUTIAE *); + +/* ridges.c */ +extern int count_minutiae_ridges(MINUTIAE *, + unsigned char *, const int, const int, + const LFSPARMS *); +extern int count_minutia_ridges(const int, MINUTIAE *, + unsigned char *, const int, const int, + const LFSPARMS *); +extern int find_neighbors(int **, int *, const int, const int, MINUTIAE *); +extern int update_nbr_dists(int *, double *, int *, const int, + const int, const int, MINUTIAE *); +extern int insert_neighbor(const int, const int, const double, + int *, double *, int *, const int); +extern int sort_neighbors(int *, const int, const int, MINUTIAE *); +extern int ridge_count(const int, const int, MINUTIAE *, + unsigned char *, const int, const int, const LFSPARMS *); +extern int find_transition(int *, const int, const int, + const int *, const int *, const int, + unsigned char *, const int, const int); +extern int validate_ridge_crossing(const int, const int, + const int *, const int *, const int, + unsigned char *, const int, const int, const int); + +/* shape.c */ +extern int alloc_shape(SHAPE **, const int, const int, const int, const int); +extern void free_shape(SHAPE *); +extern void dump_shape(FILE *, const SHAPE *); +extern int shape_from_contour(SHAPE **, const int *, const int *, const int); +extern void sort_row_on_x(ROW *); + +/* sort.c */ +extern int sort_indices_int_inc(int **, int *, const int); +extern int sort_indices_double_inc(int **, double *, const int); +extern void bubble_sort_int_inc_2(int *, int *, const int); +extern void bubble_sort_double_inc_2(double *, int *, const int); +extern void bubble_sort_double_dec_2(double *, int *, const int); +extern void bubble_sort_int_inc(int *, const int); + +/* util.c */ +extern int maxv(const int *, const int); +extern int minv(const int *, const int); +extern int minmaxs(int **, int **, int **, int *, int *, + const int *, const int); +extern double distance(const int, const int, const int, const int); +extern double squared_distance(const int, const int, const int, const int); +extern int in_int_list(const int, const int *, const int); +extern int remove_from_int_list(const int, int *, const int); +extern int find_incr_position_dbl(const double, double *, const int); +extern double angle2line(const int, const int, const int, const int); +extern int line2direction(const int, const int, const int, const int, + const int); +extern int closest_dir_dist(const int, const int, const int); + +/* xytreps.c */ +extern void lfs2nist_minutia_XYT(int *, int *, int *, + const MINUTIA *, const int, const int); +extern void lfs2m1_minutia_XYT(int *, int *, int *, const MINUTIA *); + + +/*************************************************************************/ +/* EXTERNAL GLOBAL VARIABLE DEFINITIONS */ +/*************************************************************************/ +extern double dft_coefs[]; +extern LFSPARMS lfsparms; +extern LFSPARMS lfsparms_V2; +extern int nbr8_dx[]; +extern int nbr8_dy[]; +extern int chaincodes_nbr8[]; +extern FEATURE_PATTERN feature_patterns[]; + +#endif diff --git a/libfprint/nbis/include/log.h b/libfprint/nbis/include/log.h new file mode 100644 index 00000000..36967f19 --- /dev/null +++ b/libfprint/nbis/include/log.h @@ -0,0 +1,48 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +#ifndef _LOG_H +#define _LOG_H + +/* Definitions and references to support log report files. */ +/* UPDATED: 03/16/2005 by MDG */ + +#include +#include +#include + +#ifdef LOG_REPORT +/* Uncomment the following line to enable logging. */ +#define LOG_FILE "log.txt" +#endif + +extern FILE *logfp; +extern int avrdir; +extern float dir_strength; +extern int nvalid; + +extern int open_logfile(void); +extern int close_logfile(void); +extern void print2log(char *, ...); + +#endif diff --git a/libfprint/nbis/include/morph.h b/libfprint/nbis/include/morph.h new file mode 100644 index 00000000..782d331b --- /dev/null +++ b/libfprint/nbis/include/morph.h @@ -0,0 +1,39 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +#ifndef __MORPH_H__ +#define __MORPH_H__ + +/* Modified 10/26/1999 by MDG to avoid indisciminate erosion of pixels */ +/* along the edge of the binary image. */ + +extern void erode_charimage_2(unsigned char *, unsigned char *, + const int, const int); +extern void dilate_charimage_2(unsigned char *, unsigned char *, + const int, const int); +extern char get_south8_2(char *, const int, const int, const int, const int); +extern char get_north8_2(char *, const int, const int, const int); +extern char get_east8_2(char *, const int, const int, const int); +extern char get_west8_2(char *, const int, const int); + +#endif /* !__MORPH_H__ */ diff --git a/libfprint/nbis/include/mytime.h b/libfprint/nbis/include/mytime.h new file mode 100644 index 00000000..4abb1ac4 --- /dev/null +++ b/libfprint/nbis/include/mytime.h @@ -0,0 +1,80 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +#ifndef _MYTIME_H +#define _MYTIME_H + +/* this file needed to support timer and ticks */ +/* UPDATED: 03/16/2005 by MDG */ + +#ifdef TIMER +#include +#include +#endif + +#ifdef TIMER +#define set_timer(_timer_); \ + { \ + _timer_ = (unsigned long)ticks(); +#else +#define set_timer(_timer_); +#endif + +#ifdef TIMER +#define time_accum(_timer_, _var_); \ + _var_ += ((unsigned long)ticks() - _timer_)/(float)ticksPerSec(); \ + } +#else +#define time_accum(_timer_, _var_); +#endif + +#ifdef TIMER +#define print_time(_fp_, _fmt_, _var_); \ + fprintf(_fp_, _fmt_, _var_); +#else +#define print_time(_fp_, _fmt_, _var_); +#endif + +extern unsigned long ticks(void); +extern int ticksPerSec(void); + +extern unsigned long total_timer; +extern float total_time; + +extern unsigned long imap_timer; +extern float imap_time; + +extern unsigned long bin_timer; +extern float bin_time; + +extern unsigned long minutia_timer; +extern float minutia_time; + +extern unsigned long rm_minutia_timer; +extern float rm_minutia_time; + +extern unsigned long ridge_count_timer; +extern float ridge_count_time; + +#endif + diff --git a/libfprint/nbis/include/sunrast.h b/libfprint/nbis/include/sunrast.h new file mode 100644 index 00000000..3d7deeaa --- /dev/null +++ b/libfprint/nbis/include/sunrast.h @@ -0,0 +1,76 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +#ifndef _SUNRAST_H +#define _SUNRAST_H + +/************************************************************/ +/* File Name: Sunrast.h */ +/* Package: Sun Rasterfile I/O */ +/* Author: Michael D. Garris */ +/* Date: 8/19/99 */ +/* Updated: 03/16/2005 by MDG */ +/* */ +/************************************************************/ + +/* Contains header information related to Sun Rasterfile images. */ + +typedef struct sunrasterhdr { + int magic; /* magic number */ + int width; /* width (in pixels) of image */ + int height; /* height (in pixels) of image */ + int depth; /* depth (1, 8, or 24 bits) of pixel */ + int raslength; /* length (in bytes) of image */ + int rastype; /* type of file; see SUN_* below */ + int maptype; /* type of colormap; see MAP_* below */ + int maplength; /* length (bytes) of following map */ + /* color map follows for maplength bytes, followed by image */ +} SUNHEAD; + +#define SUN_MAGIC 0x59a66a95 + + /* Sun supported ras_type's */ +#define SUN_STANDARD 1 /* Raw pixrect image in 68000 byte order */ +#define SUN_RUN_LENGTH 2 /* Run-length compression of bytes */ +#define SUN_FORMAT_RGB 3 /* XRGB or RGB instead of XBGR or BGR */ +#define SUN_FORMAT_TIFF 4 /* tiff <-> standard rasterfile */ +#define SUN_FORMAT_IFF 5 /* iff (TAAC format) <-> standard rasterfile */ + + /* Sun supported maptype's */ +#define MAP_RAW 2 +#define MAP_NONE 0 /* maplength is expected to be 0 */ +#define MAP_EQUAL_RGB 1 /* red[maplength/3],green[],blue[] */ + +/* + * NOTES: + * Each line of a bitmap image should be rounded out to a multiple + * of 16 bits. + */ + +/* sunrast.c */ +extern int ReadSunRaster(const char *, SUNHEAD **, unsigned char **, int *, + unsigned char **, int *, int *, int *, int *); +extern int WriteSunRaster(char *, unsigned char *, const int, const int, + const int); + +#endif diff --git a/libfprint/nbis/mindtct/binar.c b/libfprint/nbis/mindtct/binar.c new file mode 100644 index 00000000..2c4355cc --- /dev/null +++ b/libfprint/nbis/mindtct/binar.c @@ -0,0 +1,455 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: BINAR.C + AUTHOR: Michael D. Garris + DATE: 03/16/1999 + UPDATED: 10/04/1999 Version 2 by MDG + UPDATED: 03/16/2005 by MDG + + Contains routines responsible for binarizing a grayscale image based + on an arbitrarily-sized image and its precomputed direcitonal ridge + flow (IMAP) as part of the NIST Latent Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + binarize() + binarize_V2() + binarize_image() + binarize_image_V2() + dirbinarize() + isobinarize() + +***********************************************************************/ + +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: binarize - Takes a padded grayscale input image and its associated ridge +#cat: direction flow NMAP and produces a binarized version of the +#cat: image. It then fills horizontal and vertical "holes" in the +#cat: binary image results. + + Input: + pdata - padded input grayscale image + pw - padded width (in pixels) of input image + ph - padded height (in pixels) of input image + nmap - 2-D vector of IMAP directions and other codes + mw - width (in blocks) of the NMAP + mh - height (in blocks) of the NMAP + dirbingrids - set of rotated grid offsets used for directional + binarization + lfsparms - parameters and thresholds for controlling LFS + Output: + optr - points to created (unpadded) binary image + ow - width of binary image + oh - height of binary image + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int binarize(unsigned char **optr, int *ow, int *oh, + unsigned char *pdata, const int pw, const int ph, + int *nmap, const int mw, const int mh, + const ROTGRIDS *dirbingrids, const LFSPARMS *lfsparms) +{ + unsigned char *bdata; + int i, bw, bh, ret; /* return code */ + + /* 1. Binarize the padded input image using NMAP information. */ + if((ret = binarize_image(&bdata, &bw, &bh, pdata, pw, ph, + nmap, mw, mh, lfsparms->blocksize, + dirbingrids, lfsparms->isobin_grid_dim))){ + return(ret); + } + + /* 2. Fill black and white holes in binary image. */ + /* LFS scans the binary image, filling holes, 3 times. */ + for(i = 0; i < lfsparms->num_fill_holes; i++) + fill_holes(bdata, bw, bh); + + /* Return binarized input image. */ + *optr = bdata; + *ow = bw; + *oh = bh; + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: binarize_V2 - Takes a padded grayscale input image and its associated +#cat: Direction Map and produces a binarized version of the +#cat: image. It then fills horizontal and vertical "holes" in +#cat: the binary image results. Note that the input image must +#cat: be padded sufficiently to contain in memory rotated +#cat: directional binarization grids applied to pixels along the +#cat: perimeter of the input image. + + Input: + pdata - padded input grayscale image + pw - padded width (in pixels) of input image + ph - padded height (in pixels) of input image + direction_map - 2-D vector of discrete ridge flow directions + mw - width (in blocks) of the map + mh - height (in blocks) of the map + dirbingrids - set of rotated grid offsets used for directional + binarization + lfsparms - parameters and thresholds for controlling LFS + Output: + odata - points to created (unpadded) binary image + ow - width of binary image + oh - height of binary image + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int binarize_V2(unsigned char **odata, int *ow, int *oh, + unsigned char *pdata, const int pw, const int ph, + int *direction_map, const int mw, const int mh, + const ROTGRIDS *dirbingrids, const LFSPARMS *lfsparms) +{ + unsigned char *bdata; + int i, bw, bh, ret; /* return code */ + + /* 1. Binarize the padded input image using directional block info. */ + if((ret = binarize_image_V2(&bdata, &bw, &bh, pdata, pw, ph, + direction_map, mw, mh, + lfsparms->blocksize, dirbingrids))){ + return(ret); + } + + /* 2. Fill black and white holes in binary image. */ + /* LFS scans the binary image, filling holes, 3 times. */ + for(i = 0; i < lfsparms->num_fill_holes; i++) + fill_holes(bdata, bw, bh); + + /* Return binarized input image. */ + *odata = bdata; + *ow = bw; + *oh = bh; + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: binarize_image - Takes a grayscale input image and its associated +#cat: NMAP and generates a binarized version of the image. + + Input: + pdata - padded input grayscale image + pw - padded width (in pixels) of input image + ph - padded height (in pixels) of input image + nmap - 2-D vector of IMAP directions and other codes + mw - width (in blocks) of the NMAP + mh - height (in blocks) of the NMAP + imap_blocksize - dimension (in pixels) of each NMAP block + dirbingrids - set of rotated grid offsets used for directional + binarization + isobin_grid_dim - dimension (in pixels) of grid used for isotropic + binarization + Output: + optr - points to binary image results + ow - points to binary image width + oh - points to binary image height + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int binarize_image(unsigned char **optr, int *ow, int *oh, + unsigned char *pdata, const int pw, const int ph, + const int *nmap, const int mw, const int mh, + const int imap_blocksize, const ROTGRIDS *dirbingrids, + const int isobin_grid_dim) +{ + int ix, iy, bw, bh, bx, by, nmapval; + unsigned char *bdata, *bptr; + unsigned char *pptr, *spptr; + + /* Compute dimensions of "unpadded" binary image results. */ + bw = pw - (dirbingrids->pad<<1); + bh = ph - (dirbingrids->pad<<1); + + bdata = (unsigned char *)malloc(bw*bh*sizeof(unsigned char)); + if(bdata == (unsigned char *)NULL){ + fprintf(stderr, "ERROR : binarize_image : malloc : bdata\n"); + return(-110); + } + + bptr = bdata; + spptr = pdata + (dirbingrids->pad * pw) + dirbingrids->pad; + for(iy = 0; iy < bh; iy++){ + /* Set pixel pointer to start of next row in grid. */ + pptr = spptr; + for(ix = 0; ix < bw; ix++){ + /* Compute which block the current pixel is in. */ + bx = (int)(ix/imap_blocksize); + by = (int)(iy/imap_blocksize); + /* Get corresponding value in NMAP */ + nmapval = *(nmap + (by*mw) + bx); + /* If current block has no neighboring blocks with */ + /* VALID directions ... */ + if(nmapval == NO_VALID_NBRS) + /* Set binary pixel to white (255). */ + *bptr = WHITE_PIXEL; + /* Otherwise, if block's NMAP has a valid direction ... */ + else if(nmapval >= 0) + /* Use directional binarization based on NMAP direction. */ + *bptr = dirbinarize(pptr, nmapval, dirbingrids); + else + /* Otherwise, the block's NMAP is either INVALID or */ + /* HIGH-CURVATURE, so use isotropic binarization. */ + *bptr = isobinarize(pptr, pw, ph, isobin_grid_dim); + /* Bump input and output pixel pointers. */ + pptr++; + bptr++; + } + /* Bump pointer to the next row in padded input image. */ + spptr += pw; + } + + *optr = bdata; + *ow = bw; + *oh = bh; + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: binarize_image_V2 - Takes a grayscale input image and its associated +#cat: Direction Map and generates a binarized version of the +#cat: image. Note that there is no "Isotropic" binarization +#cat: used in this version. + + Input: + pdata - padded input grayscale image + pw - padded width (in pixels) of input image + ph - padded height (in pixels) of input image + direction_map - 2-D vector of discrete ridge flow directions + mw - width (in blocks) of the map + mh - height (in blocks) of the map + blocksize - dimension (in pixels) of each NMAP block + dirbingrids - set of rotated grid offsets used for directional + binarization + Output: + odata - points to binary image results + ow - points to binary image width + oh - points to binary image height + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int binarize_image_V2(unsigned char **odata, int *ow, int *oh, + unsigned char *pdata, const int pw, const int ph, + const int *direction_map, const int mw, const int mh, + const int blocksize, const ROTGRIDS *dirbingrids) +{ + int ix, iy, bw, bh, bx, by, mapval; + unsigned char *bdata, *bptr; + unsigned char *pptr, *spptr; + + /* Compute dimensions of "unpadded" binary image results. */ + bw = pw - (dirbingrids->pad<<1); + bh = ph - (dirbingrids->pad<<1); + + bdata = (unsigned char *)malloc(bw*bh*sizeof(unsigned char)); + if(bdata == (unsigned char *)NULL){ + fprintf(stderr, "ERROR : binarize_image_V2 : malloc : bdata\n"); + return(-600); + } + + bptr = bdata; + spptr = pdata + (dirbingrids->pad * pw) + dirbingrids->pad; + for(iy = 0; iy < bh; iy++){ + /* Set pixel pointer to start of next row in grid. */ + pptr = spptr; + for(ix = 0; ix < bw; ix++){ + + /* Compute which block the current pixel is in. */ + bx = (int)(ix/blocksize); + by = (int)(iy/blocksize); + /* Get corresponding value in Direction Map. */ + mapval = *(direction_map + (by*mw) + bx); + /* If current block has has INVALID direction ... */ + if(mapval == INVALID_DIR) + /* Set binary pixel to white (255). */ + *bptr = WHITE_PIXEL; + /* Otherwise, if block has a valid direction ... */ + else /*if(mapval >= 0)*/ + /* Use directional binarization based on block's direction. */ + *bptr = dirbinarize(pptr, mapval, dirbingrids); + + /* Bump input and output pixel pointers. */ + pptr++; + bptr++; + } + /* Bump pointer to the next row in padded input image. */ + spptr += pw; + } + + *odata = bdata; + *ow = bw; + *oh = bh; + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: dirbinarize - Determines the binary value of a grayscale pixel based +#cat: on a VALID IMAP ridge flow direction. + + CAUTION: The image to which the input pixel points must be appropriately + padded to account for the radius of the rotated grid. Otherwise, + this routine may access "unkown" memory. + + Input: + pptr - pointer to current grayscale pixel + idir - IMAP integer direction associated with the block the + current is in + dirbingrids - set of precomputed rotated grid offsets + Return Code: + BLACK_PIXEL - pixel intensity for BLACK + WHITE_PIXEL - pixel intensity of WHITE +**************************************************************************/ +int dirbinarize(const unsigned char *pptr, const int idir, + const ROTGRIDS *dirbingrids) +{ + int gx, gy, gi, cy; + int rsum, gsum, csum = 0; + int *grid; + double dcy; + + /* Assign nickname pointer. */ + grid = dirbingrids->grids[idir]; + /* Calculate center (0-oriented) row in grid. */ + dcy = (dirbingrids->grid_h-1)/(double)2.0; + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + dcy = trunc_dbl_precision(dcy, TRUNC_SCALE); + cy = sround(dcy); + /* Initialize grid's pixel offset index to zero. */ + gi = 0; + /* Initialize grid's pixel accumulator to zero */ + gsum = 0; + + /* Foreach row in grid ... */ + for(gy = 0; gy < dirbingrids->grid_h; gy++){ + /* Initialize row pixel sum to zero. */ + rsum = 0; + /* Foreach column in grid ... */ + for(gx = 0; gx < dirbingrids->grid_w; gx++){ + /* Accumulate next pixel along rotated row in grid. */ + rsum += *(pptr+grid[gi]); + /* Bump grid's pixel offset index. */ + gi++; + } + /* Accumulate row sum into grid pixel sum. */ + gsum += rsum; + /* If current row is center row, then save row sum separately. */ + if(gy == cy) + csum = rsum; + } + + /* If the center row sum treated as an average is less than the */ + /* total pixel sum in the rotated grid ... */ + if((csum * dirbingrids->grid_h) < gsum) + /* Set the binary pixel to BLACK. */ + return(BLACK_PIXEL); + else + /* Otherwise set the binary pixel to WHITE. */ + return(WHITE_PIXEL); +} + +/************************************************************************* +************************************************************************** +#cat: isobinarize - Determines the binary value of a grayscale pixel based +#cat: on comparing the grayscale value with a surrounding +#cat: neighborhood grid of pixels. If the current pixel (treated +#cat: as an average) is less than the sum of the pixels in +#cat: the neighborhood, then the binary value is set to BLACK, +#cat: otherwise it is set to WHITE. This binarization technique +#cat: is used when there is no VALID IMAP direction for the +#cat: block in which the current pixel resides. + + CAUTION: The image to which the input pixel points must be appropriately + padded to account for the radius of the neighborhood. Otherwise, + this routine may access "unkown" memory. + + Input: + pptr - pointer to curent grayscale pixel + pw - padded width (in pixels) of the grayscale image + ph - padded height (in pixels) of the grayscale image + isobin_grid_dim - dimension (in pixels) of the neighborhood + Return Code: + BLACK_PIXEL - pixel intensity for BLACK + WHITE_PIXEL - pixel intensity of WHITE +**************************************************************************/ +int isobinarize(unsigned char *pptr, const int pw, const int ph, + const int isobin_grid_dim) +{ + unsigned char *sptr, *cptr; + int px, py; + int radius; + int bsum; + double drad; + + /* Initialize grid pixel sum to zero. */ + bsum = 0; + /* Compute radius from current pixel based on isobin_grid_dim. */ + drad = (isobin_grid_dim - 1)/(double)2.0; + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + drad = trunc_dbl_precision(drad, TRUNC_SCALE); + radius = sround(drad); + /* Set pointer to origin of grid centered on the current pixel. */ + sptr = pptr - (radius*pw) - radius; + + /* For each row in the grid ... */ + for(py = 0; py < isobin_grid_dim; py++){ + /* Set pixel pointer to start of next row in grid. */ + cptr = sptr; + /* For each column in the grid ... */ + for(px = 0; px < isobin_grid_dim; px++){ + /* Accumulate next pixel in the grid. */ + bsum += *cptr; + /* Bump pixel pointer. */ + cptr++; + } + /* Bump to the start of the next row in the grid. */ + sptr += pw; + } + + /* If current (center) pixel when treated as an average for the */ + /* entire grid is less than the total pixel sum of the grid ... */ + if((*pptr * isobin_grid_dim * isobin_grid_dim) < bsum) + /* Set the binary pixel to BLACK. */ + return(BLACK_PIXEL); + else + /* Otherwise, set the binary pixel to WHITE. */ + return(WHITE_PIXEL); +} diff --git a/libfprint/nbis/mindtct/block.c b/libfprint/nbis/mindtct/block.c new file mode 100644 index 00000000..7c7a6565 --- /dev/null +++ b/libfprint/nbis/mindtct/block.c @@ -0,0 +1,377 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: BLOCK.C + AUTHOR: Michael D. Garris + DATE: 03/16/1999 + UPDATED: 10/04/1999 Version 2 by MDG + UPDATED: 03/16/2005 by MDG + + Contains routines responsible for partitioning arbitrarily- + sized images into equally-sized blocks as part of the NIST + Latent Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + block_offsets() + low_contrast_block() + find_valid_block() + set_margin_blocks() + +***********************************************************************/ + +#include +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: block_offsets - Divides an image into mw X mh equally sized blocks, +#cat: returning a list of offsets to the top left corner of each block. +#cat: For images that are even multiples of BLOCKSIZE, blocks do not +#cat: not overlap and are immediately adjacent to each other. For image +#cat: that are NOT even multiples of BLOCKSIZE, blocks continue to be +#cat: non-overlapping up to the last column and/or last row of blocks. +#cat: In these cases the blocks are adjacent to the edge of the image and +#cat: extend inwards BLOCKSIZE units, overlapping the neighboring column +#cat: or row of blocks. This routine also accounts for image padding +#cat: which makes things a little more "messy". This routine is primarily +#cat: responsible providing the ability to processs arbitrarily-sized +#cat: images. The strategy used here is simple, but others are possible. + + Input: + iw - width (in pixels) of the orginal input image + ih - height (in pixels) of the orginal input image + pad - the padding (in pixels) required to support the desired + range of block orientations for DFT analysis. This padding + is required along the entire perimeter of the input image. + For certain applications, the pad may be zero. + blocksize - the width and height (in pixels) of each image block + Output: + optr - points to the list of pixel offsets to the origin of + each block in the "padded" input image + ow - the number of horizontal blocks in the input image + oh - the number of vertical blocks in the input image + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int block_offsets(int **optr, int *ow, int *oh, + const int iw, const int ih, const int pad, const int blocksize) +{ + int *blkoffs, bx, by, bw, bh, bi, bsize; + int blkrow_start, blkrow_size, offset; + int lastbw, lastbh; + int pad2, pw, ph; + + /* Test if unpadded image is smaller than a single block */ + if((iw < blocksize) || (ih < blocksize)){ + fprintf(stderr, + "ERROR : block_offsets : image must be at least %d by %d in size\n", + blocksize, blocksize); + return(-80); + } + + /* Compute padded width and height of image */ + pad2 = pad<<1; + pw = iw + pad2; + ph = ih + pad2; + + /* Compute the number of columns and rows of blocks in the image. */ + /* Take the ceiling to account for "leftovers" at the right and */ + /* bottom of the unpadded image */ + bw = (int)ceil(iw / (double)blocksize); + bh = (int)ceil(ih / (double)blocksize); + + /* Total number of blocks in the image */ + bsize = bw*bh; + + /* The index of the last column */ + lastbw = bw - 1; + /* The index of the last row */ + lastbh = bh - 1; + + /* Allocate list of block offsets */ + blkoffs = (int *)malloc(bsize * sizeof(int)); + if(blkoffs == (int *)NULL){ + fprintf(stderr, "ERROR : block_offsets : malloc : blkoffs\n"); + return(-81); + } + + /* Current block index */ + bi = 0; + + /* Current offset from top of padded image to start of new row of */ + /* unpadded image blocks. It is initialize to account for the */ + /* padding and will always be indented the size of the padding */ + /* from the left edge of the padded image. */ + blkrow_start = (pad * pw) + pad; + + /* Number of pixels in a row of blocks in the padded image */ + blkrow_size = pw * blocksize; /* row width X block height */ + + /* Foreach non-overlapping row of blocks in the image */ + for(by = 0; by < lastbh; by++){ + /* Current offset from top of padded image to beginning of */ + /* the next block */ + offset = blkrow_start; + /* Foreach non-overlapping column of blocks in the image */ + for(bx = 0; bx < lastbw; bx++){ + /* Store current block offset */ + blkoffs[bi++] = offset; + /* Bump to the beginning of the next block */ + offset += blocksize; + } + + /* Compute and store "left-over" block in row. */ + /* This is the block in the last column of row. */ + /* Start at far right edge of unpadded image data */ + /* and come in BLOCKSIZE pixels. */ + blkoffs[bi++] = blkrow_start + iw - blocksize; + /* Bump to beginning of next row of blocks */ + blkrow_start += blkrow_size; + } + + /* Compute and store "left-over" row of blocks at bottom of image */ + /* Start at bottom edge of unpadded image data and come up */ + /* BLOCKSIZE pixels. This too must account for padding. */ + blkrow_start = ((pad + ih - blocksize) * pw) + pad; + /* Start the block offset for the last row at this point */ + offset = blkrow_start; + /* Foreach non-overlapping column of blocks in last row of the image */ + for(bx = 0; bx < lastbw; bx++){ + /* Store current block offset */ + blkoffs[bi++] = offset; + /* Bump to the beginning of the next block */ + offset += blocksize; + } + + /* Compute and store last "left-over" block in last row. */ + /* Start at right edge of unpadded image data and come in */ + /* BLOCKSIZE pixels. */ + blkoffs[bi++] = blkrow_start + iw - blocksize; + + *optr = blkoffs; + *ow = bw; + *oh = bh; + return(0); +} + +/************************************************************************* +#cat: low_contrast_block - Takes the offset to an image block of specified +#cat: dimension, and analyzes the pixel intensities in the block +#cat: to determine if there is sufficient contrast for further +#cat: processing. + + Input: + blkoffset - byte offset into the padded input image to the origin of + the block to be analyzed + blocksize - dimension (in pixels) of the width and height of the block + (passing separate blocksize from LFSPARMS on purpose) + pdata - padded input image data (8 bits [0..256) grayscale) + pw - width (in pixels) of the padded input image + ph - height (in pixels) of the padded input image + lfsparms - parameters and thresholds for controlling LFS + Return Code: + TRUE - block has sufficiently low contrast + FALSE - block has sufficiently hight contrast + Negative - system error +************************************************************************** +**************************************************************************/ +int low_contrast_block(const int blkoffset, const int blocksize, + unsigned char *pdata, const int pw, const int ph, + const LFSPARMS *lfsparms) +{ + int pixtable[IMG_6BIT_PIX_LIMIT], numpix; + int px, py, pi; + unsigned char *sptr, *pptr; + int delta; + double tdbl; + int prctmin = 0, prctmax = 0, prctthresh; + int pixsum, found; + + numpix = blocksize*blocksize; + memset(pixtable, 0, IMG_6BIT_PIX_LIMIT*sizeof(int)); + + tdbl = (lfsparms->percentile_min_max/100.0) * (double)(numpix-1); + tdbl = trunc_dbl_precision(tdbl, TRUNC_SCALE); + prctthresh = sround(tdbl); + + sptr = pdata+blkoffset; + for(py = 0; py < blocksize; py++){ + pptr = sptr; + for(px = 0; px < blocksize; px++){ + pixtable[*pptr]++; + pptr++; + } + sptr += pw; + } + + pi = 0; + pixsum = 0; + found = FALSE; + while(pi < IMG_6BIT_PIX_LIMIT){ + pixsum += pixtable[pi]; + if(pixsum >= prctthresh){ + prctmin = pi; + found = TRUE; + break; + } + pi++; + } + if(!found){ + fprintf(stderr, + "ERROR : low_contrast_block : min percentile pixel not found\n"); + return(-510); + } + + pi = IMG_6BIT_PIX_LIMIT-1; + pixsum = 0; + found = FALSE; + while(pi >= 0){ + pixsum += pixtable[pi]; + if(pixsum >= prctthresh){ + prctmax = pi; + found = TRUE; + break; + } + pi--; + } + if(!found){ + fprintf(stderr, + "ERROR : low_contrast_block : max percentile pixel not found\n"); + return(-511); + } + + delta = prctmax - prctmin; + + if(delta < lfsparms->min_contrast_delta) + return(TRUE); + else + return(FALSE); +} + +/************************************************************************* +************************************************************************** +#cat: find_valid_block - Take a Direction Map, Low Contrast Map, +#cat: Starting block address, a direction and searches the +#cat: maps in the specified direction until either a block valid +#cat: direction is encountered or a block flagged as LOW CONTRAST +#cat: is encountered. If a valid direction is located, it and the +#cat: address of the corresponding block are returned with a +#cat: code of FOUND. Otherwise, a code of NOT_FOUND is returned. + + Input: + direction_map - map of blocks containing directional ridge flows + low_contrast_map - map of blocks flagged as LOW CONTRAST + sx - X-block coord where search starts in maps + sy - Y-block coord where search starts in maps + mw - number of blocks horizontally in the maps + mh - number of blocks vertically in the maps + x_incr - X-block increment to direct search + y_incr - Y-block increment to direct search + Output: + nbr_dir - valid direction found + nbr_x - X-block coord where valid direction found + nbr_y - Y-block coord where valid direction found + Return Code: + FOUND - neighboring block with valid direction found + NOT_FOUND - neighboring block with valid direction NOT found +**************************************************************************/ +int find_valid_block(int *nbr_dir, int *nbr_x, int *nbr_y, + int *direction_map, int *low_contrast_map, + const int sx, const int sy, + const int mw, const int mh, + const int x_incr, const int y_incr) +{ + int x, y, dir; + + /* Initialize starting block coords. */ + x = sx + x_incr; + y = sy + y_incr; + + /* While we are not outside the boundaries of the map ... */ + while((x >= 0) && (x < mw) && (y >= 0) && (y < mh)){ + /* Stop unsuccessfully if we encounter a LOW CONTRAST block. */ + if(*(low_contrast_map+(y*mw)+x)) + return(NOT_FOUND); + + /* Stop successfully if we encounter a block with valid direction. */ + if((dir = *(direction_map+(y*mw)+x)) >= 0){ + *nbr_dir = dir; + *nbr_x = x; + *nbr_y = y; + return(FOUND); + } + + /* Otherwise, advance to the next block in the map. */ + x += x_incr; + y += y_incr; + } + + /* If we get here, then we did not find a valid block in the given */ + /* direction in the map. */ + return(NOT_FOUND); +} + +/************************************************************************* +************************************************************************** +#cat: set_margin_blocks - Take an image map and sets its perimeter values to +#cat: the specified value. + + Input: + map - map of blocks to be modified + mw - number of blocks horizontally in the map + mh - number of blocks vertically in the map + margin_value - value to be assigned to the perimeter blocks + Output: + map - resulting map +**************************************************************************/ +void set_margin_blocks(int *map, const int mw, const int mh, + const int margin_value) +{ + int x, y; + int *ptr1, *ptr2; + + ptr1 = map; + ptr2 = map+((mh-1)*mw); + for(x = 0; x < mw; x++){ + *ptr1++ = margin_value; + *ptr2++ = margin_value; + } + + ptr1 = map + mw; + ptr2 = map + mw + mw - 1; + for(y = 1; y < mh-1; y++){ + *ptr1 = margin_value; + *ptr2 = margin_value; + ptr1 += mw; + ptr2 += mw; + } + +} + diff --git a/libfprint/nbis/mindtct/chaincod.c b/libfprint/nbis/mindtct/chaincod.c new file mode 100644 index 00000000..006c996d --- /dev/null +++ b/libfprint/nbis/mindtct/chaincod.c @@ -0,0 +1,191 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: CHAINCODE.C + AUTHOR: Michael D. Garris + DATE: 05/11/1999 + + Contains routines responsible for generating and manipulating + chain codes as part of the NIST Latent Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + chain_code_loop() + is_chain_clockwise() +***********************************************************************/ + +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: chain_code_loop - Converts a feature's contour points into an +#cat: 8-connected chain code vector. This encoding represents +#cat: the direction taken between each adjacent point in the +#cat: contour. Chain codes may be used for many purposes, such +#cat: as computing the perimeter or area of an object, and they +#cat: may be used in object detection and recognition. + + Input: + contour_x - x-coord list for feature's contour points + contour_y - y-coord list for feature's contour points + ncontour - number of points in contour + Output: + ochain - resulting vector of chain codes + onchain - number of codes in chain + (same as number of points in contour) + Return Code: + Zero - chain code successful derived + Negative - system error +**************************************************************************/ +int chain_code_loop(int **ochain, int *onchain, + const int *contour_x, const int *contour_y, const int ncontour) +{ + int *chain; + int i, j, dx, dy; + + /* If we don't have at least 3 points in the contour ... */ + if(ncontour <= 3){ + /* Then we don't have a loop, so set chain length to 0 */ + /* and return without any allocations. */ + *onchain = 0; + return(0); + } + + /* Allocate chain code vector. It will be the same length as the */ + /* number of points in the contour. There will be one chain code */ + /* between each point on the contour including a code between the */ + /* last to the first point on the contour (completing the loop). */ + chain = (int *)malloc(ncontour * sizeof(int)); + /* If the allocation fails ... */ + if(chain == (int *)NULL){ + fprintf(stderr, "ERROR : chain_code_loop : malloc : chain\n"); + return(-170); + } + + /* For each neighboring point in the list (with "i" pointing to the */ + /* previous neighbor and "j" pointing to the next neighbor... */ + for(i = 0, j=1; i < ncontour-1; i++, j++){ + /* Compute delta in X between neighbors. */ + dx = contour_x[j] - contour_x[i]; + /* Compute delta in Y between neighbors. */ + dy = contour_y[j] - contour_y[i]; + /* Derive chain code index from neighbor deltas. */ + /* The deltas are on the range [-1..1], so to use them as indices */ + /* into the code list, they must first be incremented by one. */ + chain[i] = *(chaincodes_nbr8+((dy+1)*NBR8_DIM)+dx+1); + } + + /* Now derive chain code between last and first points in the */ + /* contour list. */ + dx = contour_x[0] - contour_x[i]; + dy = contour_y[0] - contour_y[i]; + chain[i] = *(chaincodes_nbr8+((dy+1)*NBR8_DIM)+dx+1); + + /* Store results to the output pointers. */ + *ochain = chain; + *onchain = ncontour; + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: is_chain_clockwise - Takes an 8-connected chain code vector and +#cat: determines if the codes are ordered clockwise or +#cat: counter-clockwise. +#cat: The routine also requires a default return value be +#cat: specified in the case the the routine is not able to +#cat: definitively determine the chains direction. This allows +#cat: the default response to be application-specific. + + Input: + chain - chain code vector + nchain - number of codes in chain + default_ret - default return code (used when we can't tell the order) + Return Code: + TRUE - chain determined to be ordered clockwise + FALSE - chain determined to be ordered counter-clockwise + Default - could not determine the order of the chain +**************************************************************************/ +int is_chain_clockwise(const int *chain, const int nchain, + const int default_ret) +{ + int i, j, d, sum; + + /* Initialize turn-accumulator to 0. */ + sum = 0; + + /* Foreach neighboring code in chain, compute the difference in */ + /* direction and accumulate. Left-hand turns increment, whereas */ + /* right-hand decrement. */ + for(i = 0, j =1; i < nchain-1; i++, j++){ + /* Compute delta in neighbor direction. */ + d = chain[j] - chain[i]; + /* Make the delta the "inner" distance. */ + /* If delta >= 4, for example if chain_i==2 and chain_j==7 (which */ + /* means the contour went from a step up to step down-to-the-right) */ + /* then 5=(7-2) which is >=4, so -3=(5-8) which means that the */ + /* change in direction is a righ-hand turn of 3 units). */ + if(d >= 4) + d -= 8; + /* If delta <= -4, for example if chain_i==7 and chain_j==2 (which */ + /* means the contour went from a step down-to-the-right to step up) */ + /* then -5=(2-7) which is <=-4, so 3=(-5+8) which means that the */ + /* change in direction is a left-hand turn of 3 units). */ + else if (d <= -4) + d += 8; + + /* The delta direction is then accumulated. */ + sum += d; + } + + /* Now we need to add in the final delta direction between the last */ + /* and first codes in the chain. */ + d = chain[0] - chain[i]; + if(d >= 4) + d -= 8; + else if (d <= -4) + d += 8; + sum += d; + + /* If the final turn_accumulator == 0, then we CAN'T TELL the */ + /* direction of the chain code, so return the default return value. */ + if(sum == 0) + return(default_ret); + /* Otherwise, if the final turn-accumulator is positive ... */ + else if(sum > 0) + /* Then we had a greater amount of left-hand turns than right-hand */ + /* turns, so the chain is in COUNTER-CLOCKWISE order, so return FALSE. */ + return(FALSE); + /* Otherwise, the final turn-accumulator is negative ... */ + else + /* So we had a greater amount of right-hand turns than left-hand */ + /* turns, so the chain is in CLOCKWISE order, so return TRUE. */ + return(TRUE); +} diff --git a/libfprint/nbis/mindtct/contour.c b/libfprint/nbis/mindtct/contour.c new file mode 100644 index 00000000..ae434711 --- /dev/null +++ b/libfprint/nbis/mindtct/contour.c @@ -0,0 +1,1274 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: CONTOUR.C + AUTHOR: Michael D. Garris + DATE: 05/11/1999 + UPDATED: 10/04/1999 Version 2 by MDG + UPDATED: 03/16/2005 by MDG + + Contains routines responsible for extracting and analyzing + minutia feature contour lists as part of the NIST Latent + Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + allocate_contour() + free_contour() + get_high_curvature_contour() + get_centered_contour() + trace_contour() + search_contour() + next_contour_pixel() + start_scan_nbr() + next_scan_nbr() + min_contour_theta() + contour_limits() +***********************************************************************/ + +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: allocate_contour - Allocates the lists needed to represent the +#cat: contour of a minutia feature (a ridge or valley-ending). +#cat: This includes two lists of coordinate pairs. The first is +#cat: the 8-connected chain of points interior to the feature +#cat: and are called the feature's "contour points". +#cat: The second is a list or corresponding points each +#cat: adjacent to its respective feature contour point in the first +#cat: list and on the exterior of the feature. These second points +#cat: are called the feature's "edge points". Don't be confused, +#cat: both lists of points are on the "edge". The first set is +#cat: guaranteed 8-connected and the color of the feature. The +#cat: second set is NOT guaranteed to be 8-connected and its points +#cat: are opposite the color of the feature. Remeber that "feature" +#cat: means either ridge-ending (black pixels) or valley-ending +#cat: (white pixels). + + Input: + ncontour - number of items in each coordinate list to be allocated + Output: + ocontour_x - allocated x-coord list for feature's contour points + ocontour_y - allocated y-coord list for feature's contour points + ocontour_ex - allocated x-coord list for feature's edge points + ocontour_ey - allocated y-coord list for feature's edge points + Return Code: + Zero - lists were successfully allocated + Negative - system (allocation) error +**************************************************************************/ +int allocate_contour(int **ocontour_x, int **ocontour_y, + int **ocontour_ex, int **ocontour_ey, const int ncontour) +{ + int *contour_x, *contour_y, *contour_ex, *contour_ey; + + /* Allocate contour's x-coord list. */ + contour_x = (int *)malloc(ncontour*sizeof(int)); + /* If allocation error... */ + if(contour_x == (int *)NULL){ + fprintf(stderr, "ERROR : allocate_contour : malloc : contour_x\n"); + return(-180); + } + + /* Allocate contour's y-coord list. */ + contour_y = (int *)malloc(ncontour*sizeof(int)); + /* If allocation error... */ + if(contour_y == (int *)NULL){ + /* Deallocate memory allocated to this point in this routine. */ + free(contour_x); + fprintf(stderr, "ERROR : allocate_contour : malloc : contour_y\n"); + return(-181); + } + + /* Allocate contour's edge x-coord list. */ + contour_ex = (int *)malloc(ncontour*sizeof(int)); + /* If allocation error... */ + if(contour_ex == (int *)NULL){ + /* Deallocate memory allocated to this point in this routine. */ + free(contour_x); + free(contour_y); + fprintf(stderr, "ERROR : allocate_contour : malloc : contour_ex\n"); + return(-182); + } + + /* Allocate contour's edge y-coord list. */ + contour_ey = (int *)malloc(ncontour*sizeof(int)); + /* If allocation error... */ + if(contour_ey == (int *)NULL){ + /* Deallocate memory allocated to this point in this routine. */ + free(contour_x); + free(contour_y); + free(contour_ex); + fprintf(stderr, "ERROR : allocate_contour : malloc : contour_ey\n"); + return(-183); + } + + /* Otherwise, allocations successful, so assign output pointers. */ + *ocontour_x = contour_x; + *ocontour_y = contour_y; + *ocontour_ex = contour_ex; + *ocontour_ey = contour_ey; + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: free_contour - Deallocates the lists used to represent the +#cat: contour of a minutia feature (a ridge or valley-ending). +#cat: This includes two lists of coordinate pairs. The first is +#cat: the 8-connected chain of points interior to the feature +#cat: and are called the feature's "contour points". +#cat: The second is a list or corresponding points each +#cat: adjacent to its respective feature contour point in the first +#cat: list and on the exterior of the feature. These second points +#cat: are called the feature's "edge points". + + Input: + contour_x - x-coord list for feature's contour points + contour_y - y-coord list for feature's contour points + contour_ex - x-coord list for feature's edge points + contour_ey - y-coord list for feature's edge points +**************************************************************************/ +void free_contour(int *contour_x, int *contour_y, + int *contour_ex, int *contour_ey) +{ + free(contour_x); + free(contour_y); + free(contour_ex); + free(contour_ey); +} + +/************************************************************************* +************************************************************************** +#cat: get_high_curvature_contour - Takes the pixel coordinate of a detected +#cat: minutia feature point and its corresponding/adjacent edge +#cat: pixel and attempts to extract a contour of specified length +#cat: of the feature's edge. The contour is extracted by walking +#cat: the feature's edge a specified number of steps clockwise and +#cat: then counter-clockwise. If a loop is detected while +#cat: extracting the contour, the contour of the loop is returned +#cat: with a return code of (LOOP_FOUND). If the process fails +#cat: to extract a contour of total specified length, then +#cat: the returned contour length is set to Zero, NO allocated +#cat: memory is returned in this case, and the return code is set +#cat: to Zero. An alternative implementation would be to return +#cat: the incomplete contour with a return code of (INCOMPLETE). +#cat: For now, NO allocated contour is returned in this case. + + Input: + half_contour - half the length of the extracted contour + (full-length non-loop contour = (half_contourX2)+1) + x_loc - starting x-pixel coord of feature (interior to feature) + y_loc - starting y-pixel coord of feature (interior to feature) + x_edge - x-pixel coord of corresponding edge pixel + (exterior to feature) + y_edge - y-pixel coord of corresponding edge pixel + (exterior to feature) + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + ocontour_x - x-pixel coords of contour (interior to feature) + ocontour_y - y-pixel coords of contour (interior to feature) + ocontour_ex - x-pixel coords of corresponding edge (exterior to feature) + ocontour_ey - y-pixel coords of corresponding edge (exterior to feature) + oncontour - number of contour points returned + Return Code: + Zero - resulting contour was successfully extracted or is empty + LOOP_FOUND - resulting contour forms a complete loop + Negative - system error +**************************************************************************/ +int get_high_curvature_contour(int **ocontour_x, int **ocontour_y, + int **ocontour_ex, int **ocontour_ey, int *oncontour, + const int half_contour, + const int x_loc, const int y_loc, + const int x_edge, const int y_edge, + unsigned char *bdata, const int iw, const int ih) +{ + int max_contour; + int *half1_x, *half1_y, *half1_ex, *half1_ey, nhalf1; + int *half2_x, *half2_y, *half2_ex, *half2_ey, nhalf2; + int *contour_x, *contour_y, *contour_ex, *contour_ey, ncontour; + int i, j, ret; + + /* Compute maximum length of complete contour */ + /* (2 half contours + feature point). */ + max_contour = (half_contour<<1) + 1; + + /* Initialize output contour length to 0. */ + *oncontour = 0; + + /* Get 1st half contour with clockwise neighbor trace. */ + if((ret = trace_contour(&half1_x, &half1_y, &half1_ex, &half1_ey, &nhalf1, + half_contour, x_loc, y_loc, x_loc, y_loc, x_edge, y_edge, + SCAN_CLOCKWISE, bdata, iw, ih))){ + + /* If trace was not possible ... */ + if(ret == IGNORE) + /* Return, with nothing allocated and contour length equal to 0. */ + return(0); + + /* If 1st half contour forms a loop ... */ + if(ret == LOOP_FOUND){ + /* Need to reverse the 1st half contour so that the points are */ + /* in consistent order. */ + /* We need to add the original feature point to the list, so */ + /* set new contour length to one plus length of 1st half contour. */ + ncontour = nhalf1+1; + /* Allocate new contour list. */ + if((ret = allocate_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, ncontour))){ + /* If allcation error, then deallocate memory allocated to */ + /* this point in this routine. */ + free_contour(half1_x, half1_y, half1_ex, half1_ey); + /* Return error code. */ + return(ret); + } + + /* Otherwise, we have the new contour allocated, so store the */ + /* original feature point. */ + contour_x[0] = x_loc; + contour_y[0] = y_loc; + contour_ex[0] = x_edge; + contour_ey[0] = y_edge; + + /* Now store the first half contour in reverse order. */ + for(i = 1, j = nhalf1-1; i < ncontour; i++, j--){ + contour_x[i] = half1_x[j]; + contour_y[i] = half1_y[j]; + contour_ex[i] = half1_ex[j]; + contour_ey[i] = half1_ey[j]; + } + + /* Deallocate the first half contour. */ + free_contour(half1_x, half1_y, half1_ex, half1_ey); + + /* Assign the output pointers. */ + *ocontour_x = contour_x; + *ocontour_y = contour_y; + *ocontour_ex = contour_ex; + *ocontour_ey = contour_ey; + *oncontour = ncontour; + + /* Return LOOP_FOUND for further processing. */ + return(LOOP_FOUND); + } + + /* Otherwise, return the system error code from the first */ + /* call to trace_contour. */ + return(ret); + } + + /* If 1st half contour not complete ... */ + if(nhalf1 < half_contour){ + /* Deallocate the partial contour. */ + free_contour(half1_x, half1_y, half1_ex, half1_ey); + /* Return, with nothing allocated and contour length equal to 0. */ + return(0); + } + + /* Otherwise, we have a complete 1st half contour... */ + /* Get 2nd half contour with counter-clockwise neighbor trace. */ + /* Use the last point from the first contour trace as the */ + /* point to test for a loop when tracing the second contour. */ + if((ret = trace_contour(&half2_x, &half2_y, &half2_ex, &half2_ey, &nhalf2, + half_contour, half1_x[nhalf1-1], half1_y[nhalf1-1], + x_loc, y_loc, x_edge, y_edge, + SCAN_COUNTER_CLOCKWISE, bdata, iw, ih))){ + + /* If 2nd trace was not possible ... */ + if(ret == IGNORE){ + /* Deallocate the 1st half contour. */ + free_contour(half1_x, half1_y, half1_ex, half1_ey); + /* Return, with nothing allocated and contour length equal to 0. */ + return(0); + } + + /* If non-zero return code is NOT LOOP_FOUND, then system error ... */ + if(ret != LOOP_FOUND){ + /* Deallocate the 1st half contour. */ + free_contour(half1_x, half1_y, half1_ex, half1_ey); + /* Return system error. */ + return(ret); + } + } + + /* If 2nd half NOT a loop AND not complete ... */ + if((ret != LOOP_FOUND) && (nhalf2 < half_contour)){ + /* Deallocate both half contours. */ + free_contour(half1_x, half1_y, half1_ex, half1_ey); + free_contour(half2_x, half2_y, half2_ex, half2_ey); + /* Return, with nothing allocated and contour length equal to 0. */ + return(0); + } + + /* Otherwise we have a full 1st half contour and a 2nd half contour */ + /* that is either a loop or complete. In either case we need to */ + /* concatenate the two half contours into one longer contour. */ + + /* Allocate output contour list. Go ahead and allocate the */ + /* "max_contour" amount even though the resulting contour will */ + /* likely be shorter if it forms a loop. */ + if((ret = allocate_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, max_contour))){ + /* If allcation error, then deallocate memory allocated to */ + /* this point in this routine. */ + free_contour(half1_x, half1_y, half1_ex, half1_ey); + free_contour(half2_x, half2_y, half2_ex, half2_ey); + /* Return error code. */ + return(ret); + } + + /* Set the current contour point counter to 0 */ + ncontour = 0; + + /* Copy 1st half contour into output contour buffers. */ + /* This contour was collected clockwise, so it's points */ + /* are entered in reverse order of the trace. The result */ + /* is the first point in the output contour if farthest */ + /* from the starting feature point. */ + for(i = 0, j = nhalf1-1; i < nhalf1; i++, j--){ + contour_x[i] = half1_x[j]; + contour_y[i] = half1_y[j]; + contour_ex[i] = half1_ex[j]; + contour_ey[i] = half1_ey[j]; + ncontour++; + } + + /* Deallocate 1st half contour. */ + free_contour(half1_x, half1_y, half1_ex, half1_ey); + + /* Next, store starting feature point into output contour buffers. */ + contour_x[nhalf1] = x_loc; + contour_y[nhalf1] = y_loc; + contour_ex[nhalf1] = x_edge; + contour_ey[nhalf1] = y_edge; + ncontour++; + + /* Now, append 2nd half contour to permanent contour buffers. */ + for(i = 0, j = nhalf1+1; i < nhalf2; i++, j++){ + contour_x[j] = half2_x[i]; + contour_y[j] = half2_y[i]; + contour_ex[j] = half2_ex[i]; + contour_ey[j] = half2_ey[i]; + ncontour++; + } + + /* Deallocate 2nd half contour. */ + free_contour(half2_x, half2_y, half2_ex, half2_ey); + + /* Assign outputs contour to output ponters. */ + *ocontour_x = contour_x; + *ocontour_y = contour_y; + *ocontour_ex = contour_ex; + *ocontour_ey = contour_ey; + *oncontour = ncontour; + + /* Return the resulting return code form the 2nd call to trace_contour */ + /* (the value will either be 0 or LOOP_FOUND). */ + return(ret); +} + +/************************************************************************* +************************************************************************** +#cat: get_centered_contour - Takes the pixel coordinate of a detected +#cat: minutia feature point and its corresponding/adjacent edge +#cat: pixel and attempts to extract a contour of specified length +#cat: of the feature's edge. The contour is extracted by walking +#cat: the feature's edge a specified number of steps clockwise and +#cat: then counter-clockwise. If a loop is detected while +#cat: extracting the contour, no contour is returned with a return +#cat: code of (LOOP_FOUND). If the process fails to extract a +#cat: a complete contour, a code of INCOMPLETE is returned. + + Input: + half_contour - half the length of the extracted contour + (full-length non-loop contour = (half_contourX2)+1) + x_loc - starting x-pixel coord of feature (interior to feature) + y_loc - starting y-pixel coord of feature (interior to feature) + x_edge - x-pixel coord of corresponding edge pixel + (exterior to feature) + y_edge - y-pixel coord of corresponding edge pixel + (exterior to feature) + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + ocontour_x - x-pixel coords of contour (interior to feature) + ocontour_y - y-pixel coords of contour (interior to feature) + ocontour_ex - x-pixel coords of corresponding edge (exterior to feature) + ocontour_ey - y-pixel coords of corresponding edge (exterior to feature) + oncontour - number of contour points returned + Return Code: + Zero - resulting contour was successfully extracted or is empty + LOOP_FOUND - resulting contour forms a complete loop + IGNORE - contour could not be traced due to problem starting + conditions + INCOMPLETE - resulting contour was not long enough + Negative - system error +**************************************************************************/ +int get_centered_contour(int **ocontour_x, int **ocontour_y, + int **ocontour_ex, int **ocontour_ey, int *oncontour, + const int half_contour, + const int x_loc, const int y_loc, + const int x_edge, const int y_edge, + unsigned char *bdata, const int iw, const int ih) +{ + int max_contour; + int *half1_x, *half1_y, *half1_ex, *half1_ey, nhalf1; + int *half2_x, *half2_y, *half2_ex, *half2_ey, nhalf2; + int *contour_x, *contour_y, *contour_ex, *contour_ey, ncontour; + int i, j, ret; + + /* Compute maximum length of complete contour */ + /* (2 half contours + feature point). */ + max_contour = (half_contour<<1) + 1; + + /* Initialize output contour length to 0. */ + *oncontour = 0; + + /* Get 1st half contour with clockwise neighbor trace. */ + ret = trace_contour(&half1_x, &half1_y, &half1_ex, &half1_ey, &nhalf1, + half_contour, x_loc, y_loc, x_loc, y_loc, x_edge, y_edge, + SCAN_CLOCKWISE, bdata, iw, ih); + + /* If system error occurred ... */ + if(ret < 0){ + /* Return error code. */ + return(ret); + } + + /* If trace was not possible ... */ + if(ret == IGNORE) + /* Return IGNORE, with nothing allocated. */ + return(IGNORE); + + /* If 1st half contour forms a loop ... */ + if(ret == LOOP_FOUND){ + /* Deallocate loop's contour. */ + free_contour(half1_x, half1_y, half1_ex, half1_ey); + /* Return LOOP_FOUND, with nothing allocated. */ + return(LOOP_FOUND); + } + + /* If 1st half contour not complete ... */ + if(nhalf1 < half_contour){ + /* Deallocate the partial contour. */ + free_contour(half1_x, half1_y, half1_ex, half1_ey); + /* Return, with nothing allocated and contour length equal to 0. */ + return(INCOMPLETE); + } + + /* Otherwise, we have a complete 1st half contour... */ + /* Get 2nd half contour with counter-clockwise neighbor trace. */ + /* Use the last point from the first contour trace as the */ + /* point to test for a loop when tracing the second contour. */ + ret = trace_contour(&half2_x, &half2_y, &half2_ex, &half2_ey, &nhalf2, + half_contour, half1_x[nhalf1-1], half1_y[nhalf1-1], + x_loc, y_loc, x_edge, y_edge, + SCAN_COUNTER_CLOCKWISE, bdata, iw, ih); + + /* If system error occurred on 2nd trace ... */ + if(ret < 0){ + /* Return error code. */ + return(ret); + } + + /* If 2nd trace was not possible ... */ + if(ret == IGNORE){ + /* Deallocate the 1st half contour. */ + free_contour(half1_x, half1_y, half1_ex, half1_ey); + /* Return, with nothing allocated and contour length equal to 0. */ + return(IGNORE); + } + + /* If 2nd trace forms a loop ... */ + if(ret == LOOP_FOUND){ + /* Deallocate 1st and 2nd half contours. */ + free_contour(half1_x, half1_y, half1_ex, half1_ey); + free_contour(half2_x, half2_y, half2_ex, half2_ey); + /* Return LOOP_FOUND, with nothing allocated. */ + return(LOOP_FOUND); + } + + /* If 2nd half contour not complete ... */ + if(nhalf2 < half_contour){ + /* Deallocate 1st and 2nd half contours. */ + free_contour(half1_x, half1_y, half1_ex, half1_ey); + free_contour(half2_x, half2_y, half2_ex, half2_ey); + /* Return, with nothing allocated and contour length equal to 0. */ + return(INCOMPLETE); + } + + /* Otherwise we have a full 1st half contour and a 2nd half contour */ + /* that do not form a loop and are complete. We now need to */ + /* concatenate the two half contours into one longer contour. */ + + /* Allocate output contour list. */ + if((ret = allocate_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, max_contour))){ + /* If allcation error, then deallocate memory allocated to */ + /* this point in this routine. */ + free_contour(half1_x, half1_y, half1_ex, half1_ey); + free_contour(half2_x, half2_y, half2_ex, half2_ey); + /* Return error code. */ + return(ret); + } + + /* Set the current contour point counter to 0 */ + ncontour = 0; + + /* Copy 1st half contour into output contour buffers. */ + /* This contour was collected clockwise, so it's points */ + /* are entered in reverse order of the trace. The result */ + /* is the first point in the output contour if farthest */ + /* from the starting feature point. */ + for(i = 0, j = nhalf1-1; i < nhalf1; i++, j--){ + contour_x[i] = half1_x[j]; + contour_y[i] = half1_y[j]; + contour_ex[i] = half1_ex[j]; + contour_ey[i] = half1_ey[j]; + ncontour++; + } + + /* Deallocate 1st half contour. */ + free_contour(half1_x, half1_y, half1_ex, half1_ey); + + /* Next, store starting feature point into output contour buffers. */ + contour_x[nhalf1] = x_loc; + contour_y[nhalf1] = y_loc; + contour_ex[nhalf1] = x_edge; + contour_ey[nhalf1] = y_edge; + ncontour++; + + /* Now, append 2nd half contour to permanent contour buffers. */ + for(i = 0, j = nhalf1+1; i < nhalf2; i++, j++){ + contour_x[j] = half2_x[i]; + contour_y[j] = half2_y[i]; + contour_ex[j] = half2_ex[i]; + contour_ey[j] = half2_ey[i]; + ncontour++; + } + + /* Deallocate 2nd half contour. */ + free_contour(half2_x, half2_y, half2_ex, half2_ey); + + /* Assign outputs contour to output ponters. */ + *ocontour_x = contour_x; + *ocontour_y = contour_y; + *ocontour_ex = contour_ex; + *ocontour_ey = contour_ey; + *oncontour = ncontour; + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: trace_contour - Takes the pixel coordinate of a detected minutia +#cat: feature point and its corresponding/adjacent edge pixel +#cat: and extracts a contour (up to a specified maximum length) +#cat: of the feature's edge in either a clockwise or counter- +#cat: clockwise direction. A second point is specified, such that +#cat: if this point is encounted while extracting the contour, +#cat: it is to be assumed that a loop has been found and a code +#cat: of (LOOP_FOUND) is returned with the contour. By independently +#cat: specifying this point, successive calls can be made to +#cat: this routine from the same starting point, and loops across +#cat: successive calls can be detected. + + Input: + max_len - maximum length of contour to be extracted + x_loop - x-pixel coord of point, if encountered, triggers LOOP_FOUND + y_loop - y-pixel coord of point, if encountered, triggers LOOP_FOUND + x_loc - starting x-pixel coord of feature (interior to feature) + y_loc - starting y-pixel coord of feature (interior to feature) + x_edge - x-pixel coord of corresponding edge pixel (exterior to feature) + y_edge - y-pixel coord of corresponding edge pixel (exterior to feature) + scan_clock - direction in which neighboring pixels are to be scanned + for the next contour pixel + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + ocontour_x - x-pixel coords of contour (interior to feature) + ocontour_y - y-pixel coords of contour (interior to feature) + ocontour_ex - x-pixel coords of corresponding edge (exterior to feature) + ocontour_ey - y-pixel coords of corresponding edge (exterior to feature) + oncontour - number of contour points returned + Return Code: + Zero - resulting contour was successfully allocated and extracted + LOOP_FOUND - resulting contour forms a complete loop + IGNORE - trace is not possible due to state of inputs + Negative - system error +**************************************************************************/ +int trace_contour(int **ocontour_x, int **ocontour_y, + int **ocontour_ex, int **ocontour_ey, int *oncontour, + const int max_len, const int x_loop, const int y_loop, + const int x_loc, const int y_loc, + const int x_edge, const int y_edge, + const int scan_clock, + unsigned char *bdata, const int iw, const int ih) +{ + int *contour_x, *contour_y, *contour_ex, *contour_ey, ncontour; + int cur_x_loc, cur_y_loc; + int cur_x_edge, cur_y_edge; + int next_x_loc, next_y_loc; + int next_x_edge, next_y_edge; + int i, ret; + + /* Check to make sure that the feature and edge values are opposite. */ + if(*(bdata+(y_loc*iw)+x_loc) == + *(bdata+(y_edge*iw)+x_edge)) + /* If not opposite, then the trace will not work, so return IGNORE. */ + return(IGNORE); + + /* Allocate contour buffers. */ + if((ret = allocate_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, max_len))){ + /* If allocation error, return code. */ + return(ret); + } + + /* Set pixel counter to 0. */ + ncontour = 0; + + /* Set up for finding first contour pixel. */ + cur_x_loc = x_loc; + cur_y_loc = y_loc; + cur_x_edge = x_edge; + cur_y_edge = y_edge; + + /* Foreach pixel to be collected on the feature's contour... */ + for(i = 0; i < max_len; i++){ + /* Find the next contour pixel. */ + if(next_contour_pixel(&next_x_loc, &next_y_loc, + &next_x_edge, &next_y_edge, + cur_x_loc, cur_y_loc, + cur_x_edge, cur_y_edge, + scan_clock, bdata, iw, ih)){ + + /* If we trace back around to the specified starting */ + /* feature location... */ + if((next_x_loc == x_loop) && (next_y_loc == y_loop)){ + /* Then we have found a loop, so return what we */ + /* have traced to this point. */ + *ocontour_x = contour_x; + *ocontour_y = contour_y; + *ocontour_ex = contour_ex; + *ocontour_ey = contour_ey; + *oncontour = ncontour; + return(LOOP_FOUND); + } + + /* Otherwise, we found another point on our feature's contour, */ + /* so store the new contour point. */ + contour_x[i] = next_x_loc; + contour_y[i] = next_y_loc; + contour_ex[i] = next_x_edge; + contour_ey[i] = next_y_edge; + /* Bump the number of points stored. */ + ncontour++; + + /* Set up for finding next contour pixel. */ + cur_x_loc = next_x_loc; + cur_y_loc = next_y_loc; + cur_x_edge = next_x_edge; + cur_y_edge = next_y_edge; + } + /* Otherwise, no new contour point found ... */ + else{ + /* So, stop short and return the number of pixels found */ + /* on the contour to this point. */ + *ocontour_x = contour_x; + *ocontour_y = contour_y; + *ocontour_ex = contour_ex; + *ocontour_ey = contour_ey; + *oncontour = ncontour; + + /* Return normally. */ + return(0); + } + } + + /* If we get here, we successfully found the maximum points we */ + /* were looking for on the feature contour, so assign the contour */ + /* buffers to the output pointers and return. */ + *ocontour_x = contour_x; + *ocontour_y = contour_y; + *ocontour_ex = contour_ex; + *ocontour_ey = contour_ey; + *oncontour = ncontour; + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: search_contour - Walk the contour of a minutia feature starting at a +#cat: specified point on the feature and walking N steps in the +#cat: specified direction (clockwise or counter-clockwise), looking +#cat: for a second specified point. In this code, "feature" is +#cat: consistently referring to either the black interior edge of +#cat: a ridge-ending or the white interior edge of a valley-ending +#cat: (bifurcation). The term "edge of the feature" refers to +#cat: neighboring pixels on the "exterior" edge of the feature. +#cat: So "edge" pixels are opposite in color from the interior +#cat: feature pixels. + + Input: + x_search - x-pixel coord of point being searched for + y_search - y-pixel coord of point being searched for + search_len - number of step to walk contour in search + x_loc - starting x-pixel coord of feature (interior to feature) + y_loc - starting y-pixel coord of feature (interior to feature) + x_edge - x-pixel coord of corresponding edge pixel + (exterior to feature) + y_edge - y-pixel coord of corresponding edge pixel + (exterior to feature) + scan_clock - direction in which neighbor pixels are to be scanned + (clockwise or counter-clockwise) + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + Return Code: + NOT_FOUND - desired pixel not found along N steps of feature's contour + FOUND - desired pixel WAS found along N steps of feature's contour +**************************************************************************/ +int search_contour(const int x_search, const int y_search, + const int search_len, + const int x_loc, const int y_loc, + const int x_edge, const int y_edge, + const int scan_clock, + unsigned char *bdata, const int iw, const int ih) +{ + int cur_x_loc, cur_y_loc; + int cur_x_edge, cur_y_edge; + int next_x_loc, next_y_loc; + int next_x_edge, next_y_edge; + int i; + + /* Set up for finding first contour pixel. */ + cur_x_loc = x_loc; + cur_y_loc = y_loc; + cur_x_edge = x_edge; + cur_y_edge = y_edge; + + /* Foreach point to be collected on the feature's contour... */ + for(i = 0; i < search_len; i++){ + /* Find the next contour pixel. */ + if(next_contour_pixel(&next_x_loc, &next_y_loc, + &next_x_edge, &next_y_edge, + cur_x_loc, cur_y_loc, + cur_x_edge, cur_y_edge, + scan_clock, bdata, iw, ih)){ + + /* If we find the point we are looking for on the contour... */ + if((next_x_loc == x_search) && (next_y_loc == y_search)){ + /* Then return FOUND. */ + return(FOUND); + } + + /* Otherwise, set up for finding next contour pixel. */ + cur_x_loc = next_x_loc; + cur_y_loc = next_y_loc; + cur_x_edge = next_x_edge; + cur_y_edge = next_y_edge; + } + /* Otherwise, no new contour point found ... */ + else{ + /* So, stop searching, and return NOT_FOUND. */ + return(NOT_FOUND); + } + } + + /* If we get here, we successfully searched the maximum points */ + /* without finding our desired point, so return NOT_FOUND. */ + return(NOT_FOUND); +} + +/************************************************************************* +************************************************************************** +#cat: next_contour_pixel - Takes a pixel coordinate of a point determined +#cat: to be on the interior edge of a feature (ridge or valley- +#cat: ending), and attempts to locate a neighboring pixel on the +#cat: feature's contour. Neighbors of the current feature pixel +#cat: are searched in a specified direction (clockwise or counter- +#cat: clockwise) and the first pair of adjacent/neigboring pixels +#cat: found with the first pixel having the color of the feature +#cat: and the second the opposite color are returned as the next +#cat: point on the contour. One exception happens when the new +#cat: point is on an "exposed" corner. + + Input: + cur_x_loc - x-pixel coord of current point on feature's + interior contour + cur_y_loc - y-pixel coord of current point on feature's + interior contour + cur_x_edge - x-pixel coord of corresponding edge pixel + (exterior to feature) + cur_y_edge - y-pixel coord of corresponding edge pixel + (exterior to feature) + scan_clock - direction in which neighboring pixels are to be scanned + for the next contour pixel + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + next_x_loc - x-pixel coord of next point on feature's interior contour + next_y_loc - y-pixel coord of next point on feature's interior contour + next_x_edge - x-pixel coord of corresponding edge (exterior to feature) + next_y_edge - y-pixel coord of corresponding edge (exterior to feature) + Return Code: + TRUE - next contour point found and returned + FALSE - next contour point NOT found +**************************************************************************/ +/*************************************************************************/ +int next_contour_pixel(int *next_x_loc, int *next_y_loc, + int *next_x_edge, int *next_y_edge, + const int cur_x_loc, const int cur_y_loc, + const int cur_x_edge, const int cur_y_edge, + const int scan_clock, + unsigned char *bdata, const int iw, const int ih) +{ + int feature_pix, edge_pix; + int prev_nbr_pix, prev_nbr_x, prev_nbr_y; + int cur_nbr_pix, cur_nbr_x, cur_nbr_y; + int ni, nx, ny, npix; + int nbr_i, i; + + /* Get the feature's pixel value. */ + feature_pix = *(bdata + (cur_y_loc * iw) + cur_x_loc); + /* Get the feature's edge pixel value. */ + edge_pix = *(bdata + (cur_y_edge * iw) + cur_x_edge); + + /* Get the nieghbor position of the feature's edge pixel in relationship */ + /* to the feature's actual position. */ + /* REMEBER: The feature's position is always interior and on a ridge */ + /* ending (black pixel) or (for bifurcations) on a valley ending (white */ + /* pixel). The feature's edge pixel is an adjacent pixel to the feature */ + /* pixel that is exterior to the ridge or valley ending and opposite in */ + /* pixel value. */ + nbr_i = start_scan_nbr(cur_x_loc, cur_y_loc, cur_x_edge, cur_y_edge); + + /* Set current neighbor scan pixel to the feature's edge pixel. */ + cur_nbr_x = cur_x_edge; + cur_nbr_y = cur_y_edge; + cur_nbr_pix = edge_pix; + + /* Foreach pixel neighboring the feature pixel ... */ + for(i = 0; i < 8; i++){ + + /* Set current neighbor scan pixel to previous scan pixel. */ + prev_nbr_x = cur_nbr_x; + prev_nbr_y = cur_nbr_y; + prev_nbr_pix = cur_nbr_pix; + + /* Bump pixel neighbor index clockwise or counter-clockwise. */ + nbr_i = next_scan_nbr(nbr_i, scan_clock); + + /* Set current scan pixel to the new neighbor. */ + /* REMEMBER: the neighbors are being scanned around the original */ + /* feature point. */ + cur_nbr_x = cur_x_loc + nbr8_dx[nbr_i]; + cur_nbr_y = cur_y_loc + nbr8_dy[nbr_i]; + + /* If new neighbor is not within image boundaries... */ + if((cur_nbr_x < 0) || (cur_nbr_x >= iw) || + (cur_nbr_y < 0) || (cur_nbr_y >= ih)) + /* Return (FALSE==>Failure) if neighbor out of bounds. */ + return(FALSE); + + /* Get the new neighbor's pixel value. */ + cur_nbr_pix = *(bdata + (cur_nbr_y * iw) + cur_nbr_x); + + /* If the new neighbor's pixel value is the same as the feature's */ + /* pixel value AND the previous neighbor's pixel value is the same */ + /* as the features's edge, then we have "likely" found our next */ + /* contour pixel. */ + if((cur_nbr_pix == feature_pix) && (prev_nbr_pix == edge_pix)){ + + /* Check to see if current neighbor is on the corner of the */ + /* neighborhood, and if so, test to see if it is "exposed". */ + /* The neighborhood corners have odd neighbor indicies. */ + if(nbr_i % 2){ + /* To do this, look ahead one more neighbor pixel. */ + ni = next_scan_nbr(nbr_i, scan_clock); + nx = cur_x_loc + nbr8_dx[ni]; + ny = cur_y_loc + nbr8_dy[ni]; + /* If new neighbor is not within image boundaries... */ + if((nx < 0) || (nx >= iw) || + (ny < 0) || (ny >= ih)) + /* Return (FALSE==>Failure) if neighbor out of bounds. */ + return(FALSE); + npix = *(bdata + (ny * iw) + nx); + + /* If the next neighbor's value is also the same as the */ + /* feature's pixel, then corner is NOT exposed... */ + if(npix == feature_pix){ + /* Assign the current neighbor pair to the output pointers. */ + *next_x_loc = cur_nbr_x; + *next_y_loc = cur_nbr_y; + *next_x_edge = prev_nbr_x; + *next_y_edge = prev_nbr_y; + /* Return TRUE==>Success. */ + return(TRUE); + } + /* Otherwise, corner pixel is "exposed" so skip it. */ + else{ + /* Skip current corner neighbor by resetting it to the */ + /* next neighbor, which upon the iteration will immediately */ + /* become the previous neighbor. */ + cur_nbr_x = nx; + cur_nbr_y = ny; + cur_nbr_pix = npix; + /* Advance neighbor index. */ + nbr_i = ni; + /* Advance neighbor count. */ + i++; + } + } + /* Otherwise, current neighbor is not a corner ... */ + else{ + /* Assign the current neighbor pair to the output pointers. */ + *next_x_loc = cur_nbr_x; + *next_y_loc = cur_nbr_y; + *next_x_edge = prev_nbr_x; + *next_y_edge = prev_nbr_y; + /* Return TRUE==>Success. */ + return(TRUE); + } + } + } + + /* If we get here, then we did not find the next contour pixel */ + /* within the 8 neighbors of the current feature pixel so */ + /* return (FALSE==>Failure). */ + /* NOTE: This must mean we found a single isolated pixel. */ + /* Perhaps this should be filled? */ + return(FALSE); +} + +/************************************************************************* +************************************************************************** +#cat: start_scan_nbr - Takes a two pixel coordinates that are either +#cat: aligned north-to-south or east-to-west, and returns the +#cat: position the second pixel is in realtionship to the first. +#cat: The positions returned are based on 8-connectedness. +#cat: NOTE, this routine does NOT account for diagonal positions. + + Input: + x_prev - x-coord of first point + y_prev - y-coord of first point + x_next - x-coord of second point + y_next - y-coord of second point + Return Code: + NORTH - second pixel above first + SOUTH - second pixel below first + EAST - second pixel right of first + WEST - second pixel left of first +**************************************************************************/ +int start_scan_nbr(const int x_prev, const int y_prev, + const int x_next, const int y_next) +{ + if((x_prev==x_next) && (y_next > y_prev)) + return(SOUTH); + else if ((x_prev==x_next) && (y_next < y_prev)) + return(NORTH); + else if ((x_next > x_prev) && (y_prev==y_next)) + return(EAST); + else if ((x_next < x_prev) && (y_prev==y_next)) + return(WEST); + + /* Added by MDG on 03-16-05 */ + /* Should never reach here. Added to remove compiler warning. */ + return(INVALID_DIR); /* -1 */ +} + +/************************************************************************* +************************************************************************** +#cat: next_scan_nbr - Advances the given 8-connected neighbor index +#cat: on location in the specifiec direction (clockwise or +#cat: counter-clockwise). + + Input: + nbr_i - current 8-connected neighbor index + scan_clock - direction in which the neighbor index is to be advanced + Return Code: + Next neighbor - 8-connected index of next neighbor +**************************************************************************/ +int next_scan_nbr(const int nbr_i, const int scan_clock) +{ + int new_i; + + /* If scanning neighbors clockwise ... */ + if(scan_clock == SCAN_CLOCKWISE) + /* Advance one neighbor clockwise. */ + new_i = (nbr_i+1)%8; + /* Otherwise, scanning neighbors counter-clockwise ... */ + else + /* Advance one neighbor counter-clockwise. */ + /* There are 8 pixels in the neighborhood, so to */ + /* decrement with wrapping from 0 around to 7, add */ + /* the nieghbor index by 7 and mod with 8. */ + new_i = (nbr_i+7)%8; + + /* Return the new neighbor index. */ + return(new_i); +} + +/************************************************************************* +************************************************************************** +#cat: min_contour_theta - Takes a contour list and analyzes it locating the +#cat: point at which the contour has highest curvature +#cat: (or minimum interior angle). The angle of curvature is +#cat: computed by searching a majority of points on the contour. +#cat: At each of these points, a left and right segment (or edge) +#cat: are extended out N number of pixels from the center point +#cat: on the contour. The angle is formed between the straight line +#cat: connecting the center point to the end point on the left edge +#cat: and the line connecting the center point to the end of the +#cat: right edge. The point of highest curvature is determined +#cat: by locating the where the minimum of these angles occurs. + + Input: + angle_edge - length of the left and right edges extending from a + common/centered pixel on the contour + contour_x - x-coord list for contour points + contour_y - y-coord list for contour points + ncontour - number of points in contour + Output: + omin_i - index of contour point where minimum occurred + omin_theta - minimum angle found along the contour + Return Code: + Zero - minimum angle successfully located + IGNORE - ignore the contour + Negative - system error +**************************************************************************/ +int min_contour_theta(int *omin_i, double *omin_theta, + const int angle_edge, const int *contour_x, + const int *contour_y, const int ncontour) +{ + int pleft, pcenter, pright; + double theta1, theta2, dtheta; + int min_i; + double min_theta; + + /* If the contour length is too short for processing... */ + if(ncontour < (angle_edge<<1)+1) + /* Return IGNORE. */ + return(IGNORE); + + /* Intialize running minimum values. */ + min_theta = M_PI; + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when comparing doubles. */ + min_theta = trunc_dbl_precision(min_theta, TRUNC_SCALE); + min_i = -1; + + /* Set left angle point to first contour point. */ + pleft = 0; + /* Set center angle point to "angle_edge" points into contour. */ + pcenter = angle_edge; + /* Set right angle point to "angle_edge" points from pcenter. */ + pright = pcenter + angle_edge; + + /* Loop until the right angle point exceeds the contour list. */ + while(pright < ncontour){ + /* Compute angle to first edge line (connecting pcenter to pleft). */ + theta1 = angle2line(contour_x[pcenter],contour_y[pcenter], + contour_x[pleft],contour_y[pleft]); + /* Compute angle to second edge line (connecting pcenter to pright). */ + theta2 = angle2line(contour_x[pcenter],contour_y[pcenter], + contour_x[pright],contour_y[pright]); + + /* Compute delta between angles accounting for an inner */ + /* and outer distance between the angles. */ + dtheta = fabs(theta2 - theta1); + dtheta = min(dtheta, (M_PI*2.0)-dtheta); + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when comparing doubles. */ + dtheta = trunc_dbl_precision(dtheta, TRUNC_SCALE); + + /* Keep track of running minimum theta. */ + if(dtheta < min_theta){ + min_i = pcenter; + min_theta = dtheta; + } + + /* Bump to next points on contour. */ + pleft++; + pcenter++; + pright++; + } + + /* If no minimum found (then contour is perfectly flat) so minimum */ + /* to center point on contour. */ + if(min_i == -1){ + *omin_i = ncontour>>1; + *omin_theta = min_theta; + } + else{ + /* Assign minimum theta information to output pointers. */ + *omin_i = min_i; + *omin_theta = min_theta; + } + + /* Return successfully. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: contour_limits - Determines the X and Y coordinate limits of the +#cat: given contour list. + + Input: + contour_x - x-coord list for contour points + contour_y - y-coord list for contour points + ncontour - number of points in contour + Output: + xmin - left-most x-coord in contour + ymin - top-most y-coord in contour + xmax - right-most x-coord in contour + ymax - bottom-most y-coord in contour +**************************************************************************/ +void contour_limits(int *xmin, int *ymin, int *xmax, int *ymax, + const int *contour_x, const int *contour_y, const int ncontour) +{ + /* Find the minimum x-coord from the list of contour points. */ + *xmin = minv(contour_x, ncontour); + /* Find the minimum y-coord from the list of contour points. */ + *ymin = minv(contour_y, ncontour); + /* Find the maximum x-coord from the list of contour points. */ + *xmax = maxv(contour_x, ncontour); + /* Find the maximum y-coord from the list of contour points. */ + *ymax = maxv(contour_y, ncontour); +} + +/************************************************************************* +************************************************************************** +#cat: fix_edge_pixel_pair - Takes a pair of pixel points with the first +#cat: pixel on a feature and the second adjacent and off the feature, +#cat: determines if the pair neighbor diagonally. If they do, their +#cat: locations are adjusted so that the resulting pair retains the +#cat: same pixel values, but are neighboring either to the N,S,E or W. +#cat: This routine is needed in order to prepare the pixel pair for +#cat: contour tracing. + + Input: + feat_x - pointer to x-pixel coord on feature + feat_y - pointer to y-pixel coord on feature + edge_x - pointer to x-pixel coord on edge of feature + edge_y - pointer to y-pixel coord on edge of feature + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + feat_x - pointer to resulting x-pixel coord on feature + feat_y - pointer to resulting y-pixel coord on feature + edge_x - pointer to resulting x-pixel coord on edge of feature + edge_y - pointer to resulting y-pixel coord on edge of feature +**************************************************************************/ +void fix_edge_pixel_pair(int *feat_x, int *feat_y, int *edge_x, int *edge_y, + unsigned char *bdata, const int iw, const int ih) +{ + int dx, dy; + int px, py, cx, cy; + int feature_pix; + + /* Get the pixel value of the feature. */ + feature_pix = *(bdata + ((*feat_y) * iw) + (*feat_x)); + + /* Store the input points to current and previous points. */ + cx = *feat_x; + cy = *feat_y; + px = *edge_x; + py = *edge_y; + + /* Compute detlas between current and previous point. */ + dx = px - cx; + dy = py - cy; + + /* If previous point (P) is diagonal neighbor of */ + /* current point (C)... This is a problem because */ + /* the contour tracing routine requires that the */ + /* "edge" pixel be north, south, east, or west of */ + /* of the feature point. If the previous pixel is */ + /* diagonal neighbor, then we need to adjust either */ + /* the positon of te previous or current pixel. */ + if((abs(dx)==1) && (abs(dy)==1)){ + /* Then we have one of the 4 following conditions: */ + /* */ + /* *C C* */ + /* 1. P* 2. P* 3. *P 4. *P */ + /* *C C* */ + /* */ + /* dx = -1 -1 1 1 */ + /* dy = 1 -1 -1 1 */ + /* */ + /* Want to test values in positions of '*': */ + /* Let point P == (px, py) */ + /* p1 == '*' positon where x changes */ + /* p2 == '*' positon where y changes */ + /* */ + /* p1 = px+1,py px+1,py px-1,py px-1,py */ + /* p2 = px,py-1 px,py+1 px,py+1 px,py-1 */ + /* */ + /* These can all be rewritten: */ + /* p1 = px-dx,py */ + /* p2 = px,py-dy */ + + /* Check if 'p1' is NOT the value we are searching for... */ + if(*(bdata+(py*iw)+(px-dx)) != feature_pix) + /* Then set x-coord of edge pixel to p1. */ + px -= dx; + /* Check if 'p2' is NOT the value we are searching for... */ + else if(*(bdata+((py-dy)*iw)+px) != feature_pix) + /* Then set y-coord of edge pixel to p2. */ + py -= dy; + /* Otherwise, the current pixel 'C' is exposed on a corner ... */ + else{ + /* Set pixel 'C' to 'p1', which also has the pixel */ + /* value we are searching for. */ + cy += dy; + } + + /* Set the pointers to the resulting values. */ + *feat_x = cx; + *feat_y = cy; + *edge_x = px; + *edge_y = py; + } + + /* Otherwise, nothing has changed. */ +} diff --git a/libfprint/nbis/mindtct/detect.c b/libfprint/nbis/mindtct/detect.c new file mode 100644 index 00000000..3f567384 --- /dev/null +++ b/libfprint/nbis/mindtct/detect.c @@ -0,0 +1,709 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: DETECT.C + AUTHOR: Michael D. Garris + DATE: 08/16/1999 + UPDATED: 10/04/1999 Version 2 by MDG + UPDATED: 03/16/2005 by MDG + + Takes an 8-bit grayscale fingerpinrt image and detects minutiae + as part of the NIST Latent Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + lfs_detect_minutiae() + lfs_detect_minutiae_V2() + +***********************************************************************/ + +#include +#include +#include +#include +#include + +/************************************************************************* +#cat: lfs_detect_minutiae - Takes a grayscale fingerprint image (of arbitrary +#cat: size), and returns a map of directional ridge flow in the image +#cat: (2 versions), a binarized image designating ridges from valleys, +#cat: and a list of minutiae (including position, type, direction, +#cat: neighbors, and ridge counts to neighbors). + + Input: + idata - input 8-bit grayscale fingerprint image data + iw - width (in pixels) of the image + ih - height (in pixels) of the image + lfsparms - parameters and thresholds for controlling LFS + Output: + ominutiae - resulting list of minutiae + oimap - resulting IMAP + {invalid (-1) or valid ridge directions} + onmap - resulting NMAP + {invalid (-1), high-curvature (-2), blanked blocks {-3} or + valid ridge directions} + omw - width (in blocks) of image maps + omh - height (in blocks) of image maps + obdata - resulting binarized image + {0 = black pixel (ridge) and 255 = white pixel (valley)} + obw - width (in pixels) of the binary image + obh - height (in pixels) of the binary image + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int lfs_detect_minutiae(MINUTIAE **ominutiae, + int **oimap, int **onmap, int *omw, int *omh, + unsigned char **obdata, int *obw, int *obh, + unsigned char *idata, const int iw, const int ih, + const LFSPARMS *lfsparms) +{ + unsigned char *pdata, *bdata; + int pw, ph, bw, bh; + DIR2RAD *dir2rad; + DFTWAVES *dftwaves; + ROTGRIDS *dftgrids; + ROTGRIDS *dirbingrids; + int *imap, *nmap, mw, mh; + int ret, maxpad; + MINUTIAE *minutiae; + + set_timer(total_timer); + + /******************/ + /* INITIALIZATION */ + /******************/ + + /* If LOG_REPORT defined, open log report file. */ + if((ret = open_logfile())) + /* If system error, exit with error code. */ + return(ret); + + /* Determine the maximum amount of image padding required to support */ + /* LFS processes. */ + maxpad = get_max_padding(lfsparms->blocksize, + lfsparms->dirbin_grid_w, lfsparms->dirbin_grid_h, + lfsparms->isobin_grid_dim); + + /* Initialize lookup table for converting integer IMAP directions */ + /* to angles in radians. */ + if((ret = init_dir2rad(&dir2rad, lfsparms->num_directions))){ + /* Free memory allocated to this point. */ + return(ret); + } + + /* Initialize wave form lookup tables for DFT analyses. */ + /* used for direction binarization. */ + if((ret = init_dftwaves(&dftwaves, dft_coefs, lfsparms->num_dft_waves, + lfsparms->blocksize))){ + /* Free memory allocated to this point. */ + free_dir2rad(dir2rad); + return(ret); + } + + /* Initialize lookup table for pixel offsets to rotated grids */ + /* used for DFT analyses. */ + if((ret = init_rotgrids(&dftgrids, iw, ih, maxpad, + lfsparms->start_dir_angle, lfsparms->num_directions, + lfsparms->blocksize, lfsparms->blocksize, + RELATIVE2ORIGIN))){ + /* Free memory allocated to this point. */ + free_dir2rad(dir2rad); + free_dftwaves(dftwaves); + return(ret); + } + + /* Pad input image based on max padding. */ + if(maxpad > 0){ /* May not need to pad at all */ + if((ret = pad_uchar_image(&pdata, &pw, &ph, idata, iw, ih, + maxpad, lfsparms->pad_value))){ + /* Free memory allocated to this point. */ + free_dir2rad(dir2rad); + free_dftwaves(dftwaves); + free_rotgrids(dftgrids); + return(ret); + } + } + else{ + /* If padding is unnecessary, then copy the input image. */ + pdata = (unsigned char *)malloc(iw*ih); + if(pdata == (unsigned char *)NULL){ + /* Free memory allocated to this point. */ + free_dir2rad(dir2rad); + free_dftwaves(dftwaves); + free_rotgrids(dftgrids); + fprintf(stderr, "ERROR : lfs_detect_minutiae : malloc : pdata\n"); + return(-430); + } + memcpy(pdata, idata, iw*ih); + pw = iw; + ph = ih; + } + + /* Scale input image to 6 bits [0..63] */ + /* !!! Would like to remove this dependency eventualy !!! */ + /* But, the DFT computations will need to be changed, and */ + /* could not get this work upon first attempt. */ + bits_8to6(pdata, pw, ph); + + print2log("\nINITIALIZATION AND PADDING DONE\n"); + + /******************/ + /* IMAP */ + /******************/ + set_timer(imap_timer); + + /* Generate IMAP for the input image. */ + if((ret = gen_imap(&imap, &mw, &mh, pdata, pw, ph, dir2rad, + dftwaves, dftgrids, lfsparms))){ + /* Free memory allocated to this point. */ + free_dir2rad(dir2rad); + free_dftwaves(dftwaves); + free_rotgrids(dftgrids); + free(pdata); + return(ret); + } + + free_dir2rad(dir2rad); + free_dftwaves(dftwaves); + free_rotgrids(dftgrids); + + print2log("\nIMAP DONE\n"); + + /* Generate NMAP from the IMAP of the input image. */ + if((ret = gen_nmap(&nmap, imap, mw, mh, lfsparms))){ + /* Free memory allocated to this point. */ + free(pdata); + free(imap); + return(ret); + } + + print2log("\nNMAP DONE\n"); + + time_accum(imap_timer, imap_time); + + /******************/ + /* BINARIZARION */ + /******************/ + set_timer(bin_timer); + + /* Initialize lookup table for pixel offsets to rotated grids */ + /* used for directional binarization. */ + if((ret = init_rotgrids(&dirbingrids, iw, ih, maxpad, + lfsparms->start_dir_angle, lfsparms->num_directions, + lfsparms->dirbin_grid_w, lfsparms->dirbin_grid_h, + RELATIVE2CENTER))){ + /* Free memory allocated to this point. */ + free(pdata); + free(imap); + free(nmap); + return(ret); + } + + /* Binarize input image based on NMAP information. */ + if((ret = binarize(&bdata, &bw, &bh, pdata, pw, ph, nmap, mw, mh, + dirbingrids, lfsparms))){ + /* Free memory allocated to this point. */ + free(pdata); + free(imap); + free(nmap); + free_rotgrids(dirbingrids); + return(ret); + } + free_rotgrids(dirbingrids); + + /* Check dimension of binary image. If they are different from */ + /* the input image, then ERROR. */ + if((iw != bw) || (ih != bh)){ + /* Free memory allocated to this point. */ + free(pdata); + free(imap); + free(nmap); + free(bdata); + fprintf(stderr, + "ERROR : lfs_detect_minutiae : binary image has bad dimensions : %d, %d\n", + bw, bh); + return(-431); + } + + print2log("\nBINARIZATION DONE\n"); + + time_accum(bin_timer, bin_time); + + /******************/ + /* DETECTION */ + /******************/ + set_timer(minutia_timer); + + /* Convert 8-bit grayscale binary image [0,255] to */ + /* 8-bit binary image [0,1]. */ + gray2bin(1, 1, 0, bdata, iw, ih); + + /* Allocate list of maximum number of minutia pointers. */ + if((ret = alloc_minutiae(&minutiae, MAX_MINUTIAE))){ + return(ret); + } + + /* Detect the minutiae in the binarized image. */ + if((ret = detect_minutiae(minutiae, bdata, iw, ih, imap, nmap, mw, mh, + lfsparms))){ + /* Free memory allocated to this point. */ + free(pdata); + free(imap); + free(nmap); + free(bdata); + return(ret); + } + + time_accum(minutia_timer, minutia_time); + + set_timer(rm_minutia_timer); + + if((ret = remove_false_minutia(minutiae, bdata, iw, ih, nmap, mw, mh, + lfsparms))){ + /* Free memory allocated to this point. */ + free(pdata); + free(imap); + free(nmap); + free(bdata); + free_minutiae(minutiae); + return(ret); + } + + print2log("\nMINUTIA DETECTION DONE\n"); + + time_accum(rm_minutia_timer, rm_minutia_time); + + /******************/ + /* RIDGE COUNTS */ + /******************/ + set_timer(ridge_count_timer); + + if((ret = count_minutiae_ridges(minutiae, bdata, iw, ih, lfsparms))){ + /* Free memory allocated to this point. */ + free(pdata); + free(imap); + free(nmap); + free(bdata); + free_minutiae(minutiae); + return(ret); + } + + + print2log("\nNEIGHBOR RIDGE COUNT DONE\n"); + + time_accum(ridge_count_timer, ridge_count_time); + + /******************/ + /* WRAP-UP */ + /******************/ + + /* Convert 8-bit binary image [0,1] to 8-bit */ + /* grayscale binary image [0,255]. */ + gray2bin(1, 255, 0, bdata, iw, ih); + + /* Deallocate working memory. */ + free(pdata); + + /* Assign results to output pointers. */ + *oimap = imap; + *onmap = nmap; + *omw = mw; + *omh = mh; + *obdata = bdata; + *obw = bw; + *obh = bh; + *ominutiae = minutiae; + + time_accum(total_timer, total_time); + + /******************/ + /* PRINT TIMINGS */ + /******************/ + /* These Timings will print when TIMER is defined. */ + /* print IMAP generation timing statistics */ + print_time(stderr, "TIMER: IMAP time = %f (secs)\n", imap_time); + /* print binarization timing statistics */ + print_time(stderr, "TIMER: Binarization time = %f (secs)\n", bin_time); + /* print minutia detection timing statistics */ + print_time(stderr, "TIMER: Minutia Detection time = %f (secs)\n", + minutia_time); + /* print minutia removal timing statistics */ + print_time(stderr, "TIMER: Minutia Removal time = %f (secs)\n", + rm_minutia_time); + /* print neighbor ridge count timing statistics */ + print_time(stderr, "TIMER: Neighbor Ridge Counting time = %f (secs)\n", + ridge_count_time); + /* print total timing statistics */ + print_time(stderr, "TIMER: Total time = %f (secs)\n", total_time); + + /* If LOG_REPORT defined, close log report file. */ + if((ret = close_logfile())) + return(ret); + + return(0); +} + +/************************************************************************* +#cat: lfs_detect_minutiae_V2 - Takes a grayscale fingerprint image (of +#cat: arbitrary size), and returns a set of image block maps, +#cat: a binarized image designating ridges from valleys, +#cat: and a list of minutiae (including position, reliability, +#cat: type, direction, neighbors, and ridge counts to neighbors). +#cat: The image maps include a ridge flow directional map, +#cat: a map of low contrast blocks, a map of low ridge flow blocks. +#cat: and a map of high-curvature blocks. + + Input: + idata - input 8-bit grayscale fingerprint image data + iw - width (in pixels) of the image + ih - height (in pixels) of the image + lfsparms - parameters and thresholds for controlling LFS + + Output: + ominutiae - resulting list of minutiae + odmap - resulting Direction Map + {invalid (-1) or valid ridge directions} + olcmap - resulting Low Contrast Map + {low contrast (TRUE), high contrast (FALSE)} + olfmap - resulting Low Ridge Flow Map + {low ridge flow (TRUE), high ridge flow (FALSE)} + ohcmap - resulting High Curvature Map + {high curvature (TRUE), low curvature (FALSE)} + omw - width (in blocks) of image maps + omh - height (in blocks) of image maps + obdata - resulting binarized image + {0 = black pixel (ridge) and 255 = white pixel (valley)} + obw - width (in pixels) of the binary image + obh - height (in pixels) of the binary image + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int lfs_detect_minutiae_V2(MINUTIAE **ominutiae, + int **odmap, int **olcmap, int **olfmap, int **ohcmap, + int *omw, int *omh, + unsigned char **obdata, int *obw, int *obh, + unsigned char *idata, const int iw, const int ih, + const LFSPARMS *lfsparms) +{ + unsigned char *pdata, *bdata; + int pw, ph, bw, bh; + DIR2RAD *dir2rad; + DFTWAVES *dftwaves; + ROTGRIDS *dftgrids; + ROTGRIDS *dirbingrids; + int *direction_map, *low_contrast_map, *low_flow_map, *high_curve_map; + int mw, mh; + int ret, maxpad; + MINUTIAE *minutiae; + + set_timer(total_timer); + + /******************/ + /* INITIALIZATION */ + /******************/ + + /* If LOG_REPORT defined, open log report file. */ + if((ret = open_logfile())) + /* If system error, exit with error code. */ + return(ret); + + /* Determine the maximum amount of image padding required to support */ + /* LFS processes. */ + maxpad = get_max_padding_V2(lfsparms->windowsize, lfsparms->windowoffset, + lfsparms->dirbin_grid_w, lfsparms->dirbin_grid_h); + + /* Initialize lookup table for converting integer directions */ + /* to angles in radians. */ + if((ret = init_dir2rad(&dir2rad, lfsparms->num_directions))){ + /* Free memory allocated to this point. */ + return(ret); + } + + /* Initialize wave form lookup tables for DFT analyses. */ + /* used for direction binarization. */ + if((ret = init_dftwaves(&dftwaves, dft_coefs, lfsparms->num_dft_waves, + lfsparms->windowsize))){ + /* Free memory allocated to this point. */ + free_dir2rad(dir2rad); + return(ret); + } + + /* Initialize lookup table for pixel offsets to rotated grids */ + /* used for DFT analyses. */ + if((ret = init_rotgrids(&dftgrids, iw, ih, maxpad, + lfsparms->start_dir_angle, lfsparms->num_directions, + lfsparms->windowsize, lfsparms->windowsize, + RELATIVE2ORIGIN))){ + /* Free memory allocated to this point. */ + free_dir2rad(dir2rad); + free_dftwaves(dftwaves); + return(ret); + } + + /* Pad input image based on max padding. */ + if(maxpad > 0){ /* May not need to pad at all */ + if((ret = pad_uchar_image(&pdata, &pw, &ph, idata, iw, ih, + maxpad, lfsparms->pad_value))){ + /* Free memory allocated to this point. */ + free_dir2rad(dir2rad); + free_dftwaves(dftwaves); + free_rotgrids(dftgrids); + return(ret); + } + } + else{ + /* If padding is unnecessary, then copy the input image. */ + pdata = (unsigned char *)malloc(iw*ih); + if(pdata == (unsigned char *)NULL){ + /* Free memory allocated to this point. */ + free_dir2rad(dir2rad); + free_dftwaves(dftwaves); + free_rotgrids(dftgrids); + fprintf(stderr, "ERROR : lfs_detect_minutiae_V2 : malloc : pdata\n"); + return(-580); + } + memcpy(pdata, idata, iw*ih); + pw = iw; + ph = ih; + } + + /* Scale input image to 6 bits [0..63] */ + /* !!! Would like to remove this dependency eventualy !!! */ + /* But, the DFT computations will need to be changed, and */ + /* could not get this work upon first attempt. Also, if not */ + /* careful, I think accumulated power magnitudes may overflow */ + /* doubles. */ + bits_8to6(pdata, pw, ph); + + print2log("\nINITIALIZATION AND PADDING DONE\n"); + + /******************/ + /* MAPS */ + /******************/ + set_timer(imap_timer); + + /* Generate block maps from the input image. */ + if((ret = gen_image_maps(&direction_map, &low_contrast_map, + &low_flow_map, &high_curve_map, &mw, &mh, + pdata, pw, ph, dir2rad, dftwaves, dftgrids, lfsparms))){ + /* Free memory allocated to this point. */ + free_dir2rad(dir2rad); + free_dftwaves(dftwaves); + free_rotgrids(dftgrids); + free(pdata); + return(ret); + } + /* Deallocate working memories. */ + free_dir2rad(dir2rad); + free_dftwaves(dftwaves); + free_rotgrids(dftgrids); + + print2log("\nMAPS DONE\n"); + + time_accum(imap_timer, imap_time); + + /******************/ + /* BINARIZARION */ + /******************/ + set_timer(bin_timer); + + /* Initialize lookup table for pixel offsets to rotated grids */ + /* used for directional binarization. */ + if((ret = init_rotgrids(&dirbingrids, iw, ih, maxpad, + lfsparms->start_dir_angle, lfsparms->num_directions, + lfsparms->dirbin_grid_w, lfsparms->dirbin_grid_h, + RELATIVE2CENTER))){ + /* Free memory allocated to this point. */ + free(pdata); + free(direction_map); + free(low_contrast_map); + free(low_flow_map); + free(high_curve_map); + return(ret); + } + + /* Binarize input image based on NMAP information. */ + if((ret = binarize_V2(&bdata, &bw, &bh, + pdata, pw, ph, direction_map, mw, mh, + dirbingrids, lfsparms))){ + /* Free memory allocated to this point. */ + free(pdata); + free(direction_map); + free(low_contrast_map); + free(low_flow_map); + free(high_curve_map); + free_rotgrids(dirbingrids); + return(ret); + } + + /* Deallocate working memory. */ + free_rotgrids(dirbingrids); + + /* Check dimension of binary image. If they are different from */ + /* the input image, then ERROR. */ + if((iw != bw) || (ih != bh)){ + /* Free memory allocated to this point. */ + free(pdata); + free(direction_map); + free(low_contrast_map); + free(low_flow_map); + free(high_curve_map); + free(bdata); + fprintf(stderr, "ERROR : lfs_detect_minutiae_V2 :"); + fprintf(stderr,"binary image has bad dimensions : %d, %d\n", + bw, bh); + return(-581); + } + + print2log("\nBINARIZATION DONE\n"); + + time_accum(bin_timer, bin_time); + + /******************/ + /* DETECTION */ + /******************/ + set_timer(minutia_timer); + + /* Convert 8-bit grayscale binary image [0,255] to */ + /* 8-bit binary image [0,1]. */ + gray2bin(1, 1, 0, bdata, iw, ih); + + /* Allocate initial list of minutia pointers. */ + if((ret = alloc_minutiae(&minutiae, MAX_MINUTIAE))){ + return(ret); + } + + /* Detect the minutiae in the binarized image. */ + if((ret = detect_minutiae_V2(minutiae, bdata, iw, ih, + direction_map, low_flow_map, high_curve_map, + mw, mh, lfsparms))){ + /* Free memory allocated to this point. */ + free(pdata); + free(direction_map); + free(low_contrast_map); + free(low_flow_map); + free(high_curve_map); + free(bdata); + return(ret); + } + + time_accum(minutia_timer, minutia_time); + + set_timer(rm_minutia_timer); + + if((ret = remove_false_minutia_V2(minutiae, bdata, iw, ih, + direction_map, low_flow_map, high_curve_map, mw, mh, + lfsparms))){ + /* Free memory allocated to this point. */ + free(pdata); + free(direction_map); + free(low_contrast_map); + free(low_flow_map); + free(high_curve_map); + free(bdata); + free_minutiae(minutiae); + return(ret); + } + + print2log("\nMINUTIA DETECTION DONE\n"); + + time_accum(rm_minutia_timer, rm_minutia_time); + + /******************/ + /* RIDGE COUNTS */ + /******************/ + set_timer(ridge_count_timer); + + if((ret = count_minutiae_ridges(minutiae, bdata, iw, ih, lfsparms))){ + /* Free memory allocated to this point. */ + free(pdata); + free(direction_map); + free(low_contrast_map); + free(low_flow_map); + free(high_curve_map); + free_minutiae(minutiae); + return(ret); + } + + + print2log("\nNEIGHBOR RIDGE COUNT DONE\n"); + + time_accum(ridge_count_timer, ridge_count_time); + + /******************/ + /* WRAP-UP */ + /******************/ + + /* Convert 8-bit binary image [0,1] to 8-bit */ + /* grayscale binary image [0,255]. */ + gray2bin(1, 255, 0, bdata, iw, ih); + + /* Deallocate working memory. */ + free(pdata); + + /* Assign results to output pointers. */ + *odmap = direction_map; + *olcmap = low_contrast_map; + *olfmap = low_flow_map; + *ohcmap = high_curve_map; + *omw = mw; + *omh = mh; + *obdata = bdata; + *obw = bw; + *obh = bh; + *ominutiae = minutiae; + + time_accum(total_timer, total_time); + + /******************/ + /* PRINT TIMINGS */ + /******************/ + /* These Timings will print when TIMER is defined. */ + /* print MAP generation timing statistics */ + print_time(stderr, "TIMER: MAPS time = %f (secs)\n", imap_time); + /* print binarization timing statistics */ + print_time(stderr, "TIMER: Binarization time = %f (secs)\n", bin_time); + /* print minutia detection timing statistics */ + print_time(stderr, "TIMER: Minutia Detection time = %f (secs)\n", + minutia_time); + /* print minutia removal timing statistics */ + print_time(stderr, "TIMER: Minutia Removal time = %f (secs)\n", + rm_minutia_time); + /* print neighbor ridge count timing statistics */ + print_time(stderr, "TIMER: Neighbor Ridge Counting time = %f (secs)\n", + ridge_count_time); + /* print total timing statistics */ + print_time(stderr, "TIMER: Total time = %f (secs)\n", total_time); + + /* If LOG_REPORT defined, close log report file. */ + if((ret = close_logfile())) + return(ret); + + return(0); +} + diff --git a/libfprint/nbis/mindtct/dft.c b/libfprint/nbis/mindtct/dft.c new file mode 100644 index 00000000..1159fa16 --- /dev/null +++ b/libfprint/nbis/mindtct/dft.c @@ -0,0 +1,358 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: DFT.C + AUTHOR: Michael D. Garris + DATE: 03/16/1999 + UPDATED: 03/16/2005 by MDG + + Contains routines responsible for conducting Discrete Fourier + Transforms (DFT) analysis on a block of image data as part of + the NIST Latent Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + dft_dir_powers() + sum_rot_block_rows() + dft_power() + dft_power_stats() + get_max_norm() + sort_dft_waves() +***********************************************************************/ + +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: dft_dir_powers - Conducts the DFT analysis on a block of image data. +#cat: The image block is sampled across a range of orientations +#cat: (directions) and multiple wave forms of varying frequency are +#cat: applied at each orientation. At each orentation, pixels are +#cat: accumulated along each rotated pixel row, creating a vector +#cat: of pixel row sums. Each DFT wave form is then applied +#cat: individually to this vector of pixel row sums. A DFT power +#cat: value is computed for each wave form (frequency0 at each +#cat: orientaion within the image block. Therefore, the resulting DFT +#cat: power vectors are of dimension (N Waves X M Directions). +#cat: The power signatures derived form this process are used to +#cat: determine dominant direction flow within the image block. + + Input: + pdata - the padded input image. It is important that the image + be properly padded, or else the sampling at various block + orientations may result in accessing unkown memory. + blkoffset - the pixel offset form the origin of the padded image to + the origin of the current block in the image + pw - the width (in pixels) of the padded input image + ph - the height (in pixels) of the padded input image + dftwaves - structure containing the DFT wave forms + dftgrids - structure containing the rotated pixel grid offsets + Output: + powers - DFT power computed from each wave form frequencies at each + orientation (direction) in the current image block + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int dft_dir_powers(double **powers, unsigned char *pdata, + const int blkoffset, const int pw, const int ph, + const DFTWAVES *dftwaves, const ROTGRIDS *dftgrids) +{ + int w, dir; + int *rowsums; + unsigned char *blkptr; + + /* Allocate line sum vector, and initialize to zeros */ + /* This routine requires square block (grid), so ERROR otherwise. */ + if(dftgrids->grid_w != dftgrids->grid_h){ + fprintf(stderr, "ERROR : dft_dir_powers : DFT grids must be square\n"); + return(-90); + } + rowsums = (int *)malloc(dftgrids->grid_w * sizeof(int)); + if(rowsums == (int *)NULL){ + fprintf(stderr, "ERROR : dft_dir_powers : malloc : rowsums\n"); + return(-91); + } + + /* Foreach direction ... */ + for(dir = 0; dir < dftgrids->ngrids; dir++){ + /* Compute vector of line sums from rotated grid */ + blkptr = pdata + blkoffset; + sum_rot_block_rows(rowsums, blkptr, + dftgrids->grids[dir], dftgrids->grid_w); + + /* Foreach DFT wave ... */ + for(w = 0; w < dftwaves->nwaves; w++){ + dft_power(&(powers[w][dir]), rowsums, + dftwaves->waves[w], dftwaves->wavelen); + } + } + + /* Deallocate working memory. */ + free(rowsums); + + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: sum_rot_block_rows - Computes a vector or pixel row sums by sampling +#cat: the current image block at a given orientation. The +#cat: sampling is conducted using a precomputed set of rotated +#cat: pixel offsets (called a grid) relative to the orgin of +#cat: the image block. + + Input: + blkptr - the pixel address of the origin of the current image block + grid_offsets - the rotated pixel offsets for a block-sized grid + rotated according to a specific orientation + blocksize - the width and height of the image block and thus the size + of the rotated grid + Output: + rowsums - the resulting vector of pixel row sums +**************************************************************************/ +void sum_rot_block_rows(int *rowsums, const unsigned char *blkptr, + const int *grid_offsets, const int blocksize) +{ + int ix, iy, gi; + + /* Initialize rotation offset index. */ + gi = 0; + + /* For each row in block ... */ + for(iy = 0; iy < blocksize; iy++){ + /* The sums are accumlated along the rotated rows of the grid, */ + /* so initialize row sum to 0. */ + rowsums[iy] = 0; + /* Foreach column in block ... */ + for(ix = 0; ix < blocksize; ix++){ + /* Accumulate pixel value at rotated grid position in image */ + rowsums[iy] += *(blkptr + grid_offsets[gi]); + gi++; + } + } +} + +/************************************************************************* +************************************************************************** +#cat: dft_power - Computes the DFT power by applying a specific wave form +#cat: frequency to a vector of pixel row sums computed from a +#cat: specific orientation of the block image + + Input: + rowsums - accumulated rows of pixels from within a rotated grid + overlaying an input image block + wave - the wave form (cosine and sine components) at a specific + frequency + wavelen - the length of the wave form (must match the height of the + image block which is the length of the rowsum vector) + Output: + power - the computed DFT power for the given wave form at the + given orientation within the image block +**************************************************************************/ +void dft_power(double *power, const int *rowsums, + const DFTWAVE *wave, const int wavelen) +{ + int i; + double cospart, sinpart; + + /* Initialize accumulators */ + cospart = 0.0; + sinpart = 0.0; + + /* Accumulate cos and sin components of DFT. */ + for(i = 0; i < wavelen; i++){ + /* Multiply each rotated row sum by its */ + /* corresponding cos or sin point in DFT wave. */ + cospart += (rowsums[i] * wave->cos[i]); + sinpart += (rowsums[i] * wave->sin[i]); + } + + /* Power is the sum of the squared cos and sin components */ + *power = (cospart * cospart) + (sinpart * sinpart); +} + +/************************************************************************* +************************************************************************** +#cat: dft_power_stats - Derives statistics from a set of DFT power vectors. +#cat: Statistics are computed for all but the lowest frequency +#cat: wave form, including the Maximum power for each wave form, +#cat: the direction at which the maximum power occured, and a +#cat: normalized value for the maximum power. In addition, the +#cat: statistics are ranked in descending order based on normalized +#cat: squared maximum power. These statistics are fundamental +#cat: to selecting a dominant direction flow for the current +#cat: input image block. + + Input: + powers - DFT power vectors (N Waves X M Directions) computed for + the current image block from which the values in the + statistics arrays are derived + fw - the beginning of the range of wave form indices from which + the statistcs are to derived + tw - the ending of the range of wave form indices from which + the statistcs are to derived (last index is tw-1) + ndirs - number of orientations (directions) at which the DFT + analysis was conducted + Output: + wis - list of ranked wave form indicies of the corresponding + statistics based on normalized squared maximum power. These + indices will be used as indirect addresses when processing + the power statistics in descending order of "dominance" + powmaxs - array holding the maximum DFT power for each wave form + (other than the lowest frequecy) + powmax_dirs - array to holding the direction corresponding to + each maximum power value in powmaxs + pownorms - array to holding the normalized maximum powers corresponding + to each value in powmaxs + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int dft_power_stats(int *wis, double *powmaxs, int *powmax_dirs, + double *pownorms, double **powers, + const int fw, const int tw, const int ndirs) +{ + int w, i; + int ret; /* return code */ + + for(w = fw, i = 0; w < tw; w++, i++){ + get_max_norm(&(powmaxs[i]), &(powmax_dirs[i]), + &(pownorms[i]), powers[w], ndirs); + } + + /* Get sorted order of applied DFT waves based on normalized power */ + if((ret = sort_dft_waves(wis, powmaxs, pownorms, tw-fw))) + return(ret); + + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: get_max_norm - Analyses a DFT power vector for a specific wave form +#cat: applied at different orientations (directions) to the +#cat: current image block. The routine retuns the maximum +#cat: power value in the vector, the direction at which the +#cat: maximum occurs, and a normalized power value. The +#cat: normalized power is computed as the maximum power divided +#cat: by the average power across all the directions. These +#cat: simple statistics are fundamental to the selection of +#cat: a dominant direction flow for the image block. + + Input: + power_vector - the DFT power values derived form a specific wave form + applied at different directions + ndirs - the number of directions to which the wave form was applied + Output: + powmax - the maximum power value in the DFT power vector + powmax_dir - the direciton at which the maximum power value occured + pownorm - the normalized power corresponding to the maximum power +**************************************************************************/ +void get_max_norm(double *powmax, int *powmax_dir, + double *pownorm, const double *power_vector, const int ndirs) +{ + int dir; + double max_v, powsum; + int max_i; + double powmean; + + /* Find max power value and store corresponding direction */ + max_v = power_vector[0]; + max_i = 0; + + /* Sum the total power in a block at a given direction */ + powsum = power_vector[0]; + + /* For each direction ... */ + for(dir = 1; dir < ndirs; dir++){ + powsum += power_vector[dir]; + if(power_vector[dir] > max_v){ + max_v = power_vector[dir]; + max_i = dir; + } + } + + *powmax = max_v; + *powmax_dir = max_i; + + /* Powmean is used as denominator for pownorm, so setting */ + /* a non-zero minimum avoids possible division by zero. */ + powmean = max(powsum, MIN_POWER_SUM)/(double)ndirs; + + *pownorm = *powmax / powmean; +} + +/************************************************************************* +************************************************************************** +#cat: sort_dft_waves - Creates a ranked list of DFT wave form statistics +#cat: by sorting on the normalized squared maximum power. + + Input: + powmaxs - maximum DFT power for each wave form used to derive + statistics + pownorms - normalized maximum power corresponding to values in powmaxs + nstats - number of wave forms used to derive statistics (N Wave - 1) + Output: + wis - sorted list of indices corresponding to the ranked set of + wave form statistics. These indices will be used as + indirect addresses when processing the power statistics + in descending order of "dominance" + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int sort_dft_waves(int *wis, const double *powmaxs, const double *pownorms, + const int nstats) +{ + int i; + double *pownorms2; + + /* Allocate normalized power^2 array */ + pownorms2 = (double *)malloc(nstats * sizeof(double)); + if(pownorms2 == (double *)NULL){ + fprintf(stderr, "ERROR : sort_dft_waves : malloc : pownorms2\n"); + return(-100); + } + + for(i = 0; i < nstats; i++){ + /* Wis will hold the sorted statistic indices when all is done. */ + wis[i] = i; + /* This is normalized squared max power. */ + pownorms2[i] = powmaxs[i] * pownorms[i]; + } + + /* Sort the statistic indices on the normalized squared power. */ + bubble_sort_double_dec_2(pownorms2, wis, nstats); + + /* Deallocate the working memory. */ + free(pownorms2); + + return(0); +} + diff --git a/libfprint/nbis/mindtct/free.c b/libfprint/nbis/mindtct/free.c new file mode 100644 index 00000000..fd7612e4 --- /dev/null +++ b/libfprint/nbis/mindtct/free.c @@ -0,0 +1,116 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: FREE.C + AUTHOR: Michael D. Garris + DATE: 03/16/1999 + + Contains routines responsible for deallocating + memories required by the NIST Latent Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + free_dir2rad() + free_dftwaves() + free_rotgrids() + free_dir_powers() +***********************************************************************/ + +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: free_dir2rad - Deallocates memory associated with a DIR2RAD structure + + Input: + dir2rad - pointer to memory to be freed +*************************************************************************/ +void free_dir2rad(DIR2RAD *dir2rad) +{ + free(dir2rad->cos); + free(dir2rad->sin); + free(dir2rad); +} + +/************************************************************************* +************************************************************************** +#cat: free_dftwaves - Deallocates the memory associated with a DFTWAVES +#cat: structure + + Input: + dftwaves - pointer to memory to be freed +**************************************************************************/ +void free_dftwaves(DFTWAVES *dftwaves) +{ + int i; + + for(i = 0; i < dftwaves->nwaves; i++){ + free(dftwaves->waves[i]->cos); + free(dftwaves->waves[i]->sin); + free(dftwaves->waves[i]); + } + free(dftwaves->waves); + free(dftwaves); +} + +/************************************************************************* +************************************************************************** +#cat: free_rotgrids - Deallocates the memory associated with a ROTGRIDS +#cat: structure + + Input: + rotgrids - pointer to memory to be freed +**************************************************************************/ +void free_rotgrids(ROTGRIDS *rotgrids) +{ + int i; + + for(i = 0; i < rotgrids->ngrids; i++) + free(rotgrids->grids[i]); + free(rotgrids->grids); + free(rotgrids); +} + +/************************************************************************* +************************************************************************** +#cat: free_dir_powers - Deallocate memory associated with DFT power vectors + + Input: + powers - vectors of DFT power values (N Waves X M Directions) + nwaves - number of DFT wave forms used +**************************************************************************/ +void free_dir_powers(double **powers, const int nwaves) +{ + int w; + + for(w = 0; w < nwaves; w++) + free(powers[w]); + + free(powers); +} + diff --git a/libfprint/nbis/mindtct/getmin.c b/libfprint/nbis/mindtct/getmin.c new file mode 100644 index 00000000..22404f14 --- /dev/null +++ b/libfprint/nbis/mindtct/getmin.c @@ -0,0 +1,155 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: GETMIN.C + AUTHOR: Michael D. Garris + DATE: 09/10/2004 + UPDATED: 03/16/2005 by MDG + + Takes an 8-bit grayscale fingerpinrt image and detects minutiae + as part of the NIST Latent Fingerprint System (LFS), returning + minutiae with final reliabilities and maps including a merged + quality map. + +*********************************************************************** + ROUTINES: + get_minutiae() + +***********************************************************************/ + +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: get_minutiae - Takes a grayscale fingerprint image, binarizes the input +#cat: image, and detects minutiae points using LFS Version 2. +#cat: The routine passes back the detected minutiae, the +#cat: binarized image, and a set of image quality maps. + + Input: + idata - grayscale fingerprint image data + iw - width (in pixels) of the grayscale image + ih - height (in pixels) of the grayscale image + id - pixel depth (in bits) of the grayscale image + ppmm - the scan resolution (in pixels/mm) of the grayscale image + lfsparms - parameters and thresholds for controlling LFS + Output: + ominutiae - points to a structure containing the + detected minutiae + oquality_map - resulting integrated image quality map + odirection_map - resulting direction map + olow_contrast_map - resulting low contrast map + olow_flow_map - resulting low ridge flow map + ohigh_curve_map - resulting high curvature map + omap_w - width (in blocks) of image maps + omap_h - height (in blocks) of image maps + obdata - points to binarized image data + obw - width (in pixels) of binarized image + obh - height (in pixels) of binarized image + obd - pixel depth (in bits) of binarized image + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int get_minutiae(MINUTIAE **ominutiae, int **oquality_map, + int **odirection_map, int **olow_contrast_map, + int **olow_flow_map, int **ohigh_curve_map, + int *omap_w, int *omap_h, + unsigned char **obdata, int *obw, int *obh, int *obd, + unsigned char *idata, const int iw, const int ih, + const int id, const double ppmm, const LFSPARMS *lfsparms) +{ + int ret; + MINUTIAE *minutiae; + int *direction_map, *low_contrast_map, *low_flow_map; + int *high_curve_map, *quality_map; + int map_w, map_h; + unsigned char *bdata; + int bw, bh; + + /* If input image is not 8-bit grayscale ... */ + if(id != 8){ + fprintf(stderr, "ERROR : get_minutiae : input image pixel "); + fprintf(stderr, "depth = %d != 8.\n", id); + return(-2); + } + + /* Detect minutiae in grayscale fingerpeint image. */ + if((ret = lfs_detect_minutiae_V2(&minutiae, + &direction_map, &low_contrast_map, + &low_flow_map, &high_curve_map, + &map_w, &map_h, + &bdata, &bw, &bh, + idata, iw, ih, lfsparms))){ + return(ret); + } + + /* Build integrated quality map. */ + if((ret = gen_quality_map(&quality_map, + direction_map, low_contrast_map, + low_flow_map, high_curve_map, map_w, map_h))){ + free_minutiae(minutiae); + free(direction_map); + free(low_contrast_map); + free(low_flow_map); + free(high_curve_map); + free(bdata); + return(ret); + } + + /* Assign reliability from quality map. */ + if((ret = combined_minutia_quality(minutiae, quality_map, map_w, map_h, + lfsparms->blocksize, + idata, iw, ih, id, ppmm))){ + free_minutiae(minutiae); + free(direction_map); + free(low_contrast_map); + free(low_flow_map); + free(high_curve_map); + free(quality_map); + free(bdata); + return(ret); + } + + /* Set output pointers. */ + *ominutiae = minutiae; + *oquality_map = quality_map; + *odirection_map = direction_map; + *olow_contrast_map = low_contrast_map; + *olow_flow_map = low_flow_map; + *ohigh_curve_map = high_curve_map; + *omap_w = map_w; + *omap_h = map_h; + *obdata = bdata; + *obw = bw; + *obh = bh; + *obd = id; + + /* Return normally. */ + return(0); +} diff --git a/libfprint/nbis/mindtct/globals.c b/libfprint/nbis/mindtct/globals.c new file mode 100644 index 00000000..01454dba --- /dev/null +++ b/libfprint/nbis/mindtct/globals.c @@ -0,0 +1,293 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: GLOBALS.C + AUTHOR: Michael D. Garris + DATE: 03/16/1999 + UPDATED: 10/04/1999 Version 2 by MDG + + Contains general global variable definitions required by the + NIST Latent Fingerprint System (LFS). +***********************************************************************/ + +#include + +/*************************************************************************/ +/* GOBAL DECLARATIONS */ +/*************************************************************************/ + +#ifdef LOG_REPORT +FILE *logfp; +#endif + +/* Constants (C) for defining 4 DFT frequencies, where */ +/* frequency is defined as C*(PI_FACTOR). PI_FACTOR */ +/* regulates the period of the function in x, so: */ +/* 1 = one period in range X. */ +/* 2 = twice the frequency in range X. */ +/* 3 = three times the frequency in reange X. */ +/* 4 = four times the frequency in ranage X. */ +double dft_coefs[NUM_DFT_WAVES] = { 1,2,3,4 }; + +/* Allocate and initialize a global LFS parameters structure. */ +LFSPARMS lfsparms = { + /* Image Controls */ + PAD_VALUE, + JOIN_LINE_RADIUS, + + /* Map Controls */ + IMAP_BLOCKSIZE, + UNUSED_INT, /* windowsize */ + UNUSED_INT, /* windowoffset */ + NUM_DIRECTIONS, + START_DIR_ANGLE, + RMV_VALID_NBR_MIN, + DIR_STRENGTH_MIN, + DIR_DISTANCE_MAX, + SMTH_VALID_NBR_MIN, + VORT_VALID_NBR_MIN, + HIGHCURV_VORTICITY_MIN, + HIGHCURV_CURVATURE_MIN, + UNUSED_INT, /* min_interpolate_nbrs */ + UNUSED_INT, /* percentile_min_max */ + UNUSED_INT, /* min_contrast_delta */ + + /* DFT Controls */ + NUM_DFT_WAVES, + POWMAX_MIN, + POWNORM_MIN, + POWMAX_MAX, + FORK_INTERVAL, + FORK_PCT_POWMAX, + FORK_PCT_POWNORM, + + /* Binarization Controls */ + DIRBIN_GRID_W, + DIRBIN_GRID_H, + ISOBIN_GRID_DIM, + NUM_FILL_HOLES, + + /* Minutiae Detection Controls */ + MAX_MINUTIA_DELTA, + MAX_HIGH_CURVE_THETA, + HIGH_CURVE_HALF_CONTOUR, + MIN_LOOP_LEN, + MIN_LOOP_ASPECT_DIST, + MIN_LOOP_ASPECT_RATIO, + + /* Minutiae Link Controls */ + LINK_TABLE_DIM, + MAX_LINK_DIST, + MIN_THETA_DIST, + MAXTRANS, + SCORE_THETA_NORM, + SCORE_DIST_NORM, + SCORE_DIST_WEIGHT, + SCORE_NUMERATOR, + + /* False Minutiae Removal Controls */ + MAX_RMTEST_DIST, + MAX_HOOK_LEN, + MAX_HALF_LOOP, + TRANS_DIR_PIX, + SMALL_LOOP_LEN, + SIDE_HALF_CONTOUR, + INV_BLOCK_MARGIN, + RM_VALID_NBR_MIN, + UNUSED_INT, /* max_overlap_dist */ + UNUSED_INT, /* max_overlap_join_dist */ + UNUSED_INT, /* malformation_steps_1 */ + UNUSED_INT, /* malformation_steps_2 */ + UNUSED_DBL, /* min_malformation_ratio */ + UNUSED_INT, /* max_malformation_dist */ + PORES_TRANS_R, + PORES_PERP_STEPS, + PORES_STEPS_FWD, + PORES_STEPS_BWD, + PORES_MIN_DIST2, + PORES_MAX_RATIO, + + /* Ridge Counting Controls */ + MAX_NBRS, + MAX_RIDGE_STEPS +}; + + +/* Allocate and initialize VERSION 2 global LFS parameters structure. */ +LFSPARMS lfsparms_V2 = { + /* Image Controls */ + PAD_VALUE, + JOIN_LINE_RADIUS, + + /* Map Controls */ + MAP_BLOCKSIZE_V2, + MAP_WINDOWSIZE_V2, + MAP_WINDOWOFFSET_V2, + NUM_DIRECTIONS, + START_DIR_ANGLE, + RMV_VALID_NBR_MIN, + DIR_STRENGTH_MIN, + DIR_DISTANCE_MAX, + SMTH_VALID_NBR_MIN, + VORT_VALID_NBR_MIN, + HIGHCURV_VORTICITY_MIN, + HIGHCURV_CURVATURE_MIN, + MIN_INTERPOLATE_NBRS, + PERCENTILE_MIN_MAX, + MIN_CONTRAST_DELTA, + + /* DFT Controls */ + NUM_DFT_WAVES, + POWMAX_MIN, + POWNORM_MIN, + POWMAX_MAX, + FORK_INTERVAL, + FORK_PCT_POWMAX, + FORK_PCT_POWNORM, + + /* Binarization Controls */ + DIRBIN_GRID_W, + DIRBIN_GRID_H, + UNUSED_INT, /* isobin_grid_dim */ + NUM_FILL_HOLES, + + /* Minutiae Detection Controls */ + MAX_MINUTIA_DELTA, + MAX_HIGH_CURVE_THETA, + HIGH_CURVE_HALF_CONTOUR, + MIN_LOOP_LEN, + MIN_LOOP_ASPECT_DIST, + MIN_LOOP_ASPECT_RATIO, + + /* Minutiae Link Controls */ + UNUSED_INT, /* link_table_dim */ + UNUSED_INT, /* max_link_dist */ + UNUSED_INT, /* min_theta_dist */ + MAXTRANS, /* used for removing overlaps as well */ + UNUSED_DBL, /* score_theta_norm */ + UNUSED_DBL, /* score_dist_norm */ + UNUSED_DBL, /* score_dist_weight */ + UNUSED_DBL, /* score_numerator */ + + /* False Minutiae Removal Controls */ + MAX_RMTEST_DIST_V2, + MAX_HOOK_LEN_V2, + MAX_HALF_LOOP_V2, + TRANS_DIR_PIX_V2, + SMALL_LOOP_LEN, + SIDE_HALF_CONTOUR, + INV_BLOCK_MARGIN_V2, + RM_VALID_NBR_MIN, + MAX_OVERLAP_DIST, + MAX_OVERLAP_JOIN_DIST, + MALFORMATION_STEPS_1, + MALFORMATION_STEPS_2, + MIN_MALFORMATION_RATIO, + MAX_MALFORMATION_DIST, + PORES_TRANS_R, + PORES_PERP_STEPS, + PORES_STEPS_FWD, + PORES_STEPS_BWD, + PORES_MIN_DIST2, + PORES_MAX_RATIO, + + /* Ridge Counting Controls */ + MAX_NBRS, + MAX_RIDGE_STEPS +}; + +/* Variables for conducting 8-connected neighbor analyses. */ +/* Pixel neighbor offsets: 0 1 2 3 4 5 6 7 */ /* 7 0 1 */ +int nbr8_dx[] = { 0, 1, 1, 1, 0,-1,-1,-1 }; /* 6 C 2 */ +int nbr8_dy[] = { -1,-1, 0, 1, 1, 1, 0,-1 }; /* 5 4 3 */ + +/* The chain code lookup matrix for 8-connected neighbors. */ +/* Should put this in globals. */ +int chaincodes_nbr8[]={ 3, 2, 1, + 4,-1, 0, + 5, 6, 7}; + +/* Global array of feature pixel pairs. */ +FEATURE_PATTERN feature_patterns[]= + {{RIDGE_ENDING, /* a. Ridge Ending (appearing) */ + APPEARING, + {0,0}, + {0,1}, + {0,0}}, + + {RIDGE_ENDING, /* b. Ridge Ending (disappearing) */ + DISAPPEARING, + {0,0}, + {1,0}, + {0,0}}, + + {BIFURCATION, /* c. Bifurcation (disappearing) */ + DISAPPEARING, + {1,1}, + {0,1}, + {1,1}}, + + {BIFURCATION, /* d. Bifurcation (appearing) */ + APPEARING, + {1,1}, + {1,0}, + {1,1}}, + + {BIFURCATION, /* e. Bifurcation (disappearing) */ + DISAPPEARING, + {1,0}, + {0,1}, + {1,1}}, + + {BIFURCATION, /* f. Bifurcation (disappearing) */ + DISAPPEARING, + {1,1}, + {0,1}, + {1,0}}, + + {BIFURCATION, /* g. Bifurcation (appearing) */ + APPEARING, + {1,1}, + {1,0}, + {0,1}}, + + {BIFURCATION, /* h. Bifurcation (appearing) */ + APPEARING, + {0,1}, + {1,0}, + {1,1}}, + + {BIFURCATION, /* i. Bifurcation (disappearing) */ + DISAPPEARING, + {1,0}, + {0,1}, + {1,0}}, + + {BIFURCATION, /* j. Bifurcation (appearing) */ + APPEARING, + {0,1}, + {1,0}, + {0,1}}}; diff --git a/libfprint/nbis/mindtct/imgutil.c b/libfprint/nbis/mindtct/imgutil.c new file mode 100644 index 00000000..c4fa8689 --- /dev/null +++ b/libfprint/nbis/mindtct/imgutil.c @@ -0,0 +1,469 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: IMGUTIL.C + AUTHOR: Michael D. Garris + DATE: 03/16/1999 + UPDATED: 03/16/2005 by MDG + + Contains general support image routines required by the NIST + Latent Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + bits_6to8() + bits_8to6() + gray2bin() + pad_uchar_image() + fill_holes() + free_path() + search_in_direction() + +***********************************************************************/ + +#include +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: bits_6to8 - Takes an array of unsigned characters and bitwise shifts +#cat: each value 2 postitions to the left. This is equivalent +#cat: to multiplying each value by 4. This puts original values +#cat: on the range [0..64) now on the range [0..256). Another +#cat: way to say this, is the original 6-bit values now fit in +#cat: 8 bits. This is to be used to undo the effects of bits_8to6. + + Input: + idata - input array of unsigned characters + iw - width (in characters) of the input array + ih - height (in characters) of the input array + Output: + idata - contains the bit-shifted results +**************************************************************************/ +void bits_6to8(unsigned char *idata, const int iw, const int ih) +{ + int i, isize; + unsigned char *iptr; + + isize = iw * ih; + iptr = idata; + for(i = 0; i < isize; i++){ + /* Multiply every pixel value by 4 so that [0..64) -> [0..255) */ + *iptr++ <<= 2; + } +} + +/************************************************************************* +************************************************************************** +#cat: bits_8to6 - Takes an array of unsigned characters and bitwise shifts +#cat: each value 2 postitions to the right. This is equivalent +#cat: to dividing each value by 4. This puts original values +#cat: on the range [0..256) now on the range [0..64). Another +#cat: way to say this, is the original 8-bit values now fit in +#cat: 6 bits. I would really like to make this dependency +#cat: go away. + + Input: + idata - input array of unsigned characters + iw - width (in characters) of the input array + ih - height (in characters) of the input array + Output: + idata - contains the bit-shifted results +**************************************************************************/ +void bits_8to6(unsigned char *idata, const int iw, const int ih) +{ + int i, isize; + unsigned char *iptr; + + isize = iw * ih; + iptr = idata; + for(i = 0; i < isize; i++){ + /* Divide every pixel value by 4 so that [0..256) -> [0..64) */ + *iptr++ >>= 2; + } +} + +/************************************************************************* +************************************************************************** +#cat: gray2bin - Takes an 8-bit threshold value and two 8-bit pixel values. +#cat: Those pixels in the image less than the threhsold are set +#cat: to the first specified pixel value, whereas those pixels +#cat: greater than or equal to the threshold are set to the second +#cat: specified pixel value. On application for this routine is +#cat: to convert binary images from 8-bit pixels valued {0,255} to +#cat: {1,0} and vice versa. + + Input: + thresh - 8-bit pixel threshold + less_pix - pixel value used when image pixel is < threshold + greater_pix - pixel value used when image pixel is >= threshold + bdata - 8-bit image data + iw - width (in pixels) of the image + ih - height (in pixels) of the image + Output: + bdata - altered 8-bit image data +**************************************************************************/ +void gray2bin(const int thresh, const int less_pix, const int greater_pix, + unsigned char *bdata, const int iw, const int ih) +{ + int i; + + for(i = 0; i < iw*ih; i++){ + if(bdata[i] >= thresh) + bdata[i] = (unsigned char)greater_pix; + else + bdata[i] = (unsigned char)less_pix; + } +} + +/************************************************************************* +************************************************************************** +#cat: pad_uchar_image - Copies an 8-bit grayscale images into a larger +#cat: output image centering the input image so as to +#cat: add a specified amount of pixel padding along the +#cat: entire perimeter of the input image. The amount of +#cat: pixel padding and the intensity of the pixel padding +#cat: are specified. An alternative to padding with a +#cat: constant intensity would be to copy the edge pixels +#cat: of the centered image into the adjacent pad area. + + Input: + idata - input 8-bit grayscale image + iw - width (in pixels) of the input image + ih - height (in pixels) of the input image + pad - size of padding (in pixels) to be added + pad_value - intensity of the padded area + Output: + optr - points to the newly padded image + ow - width (in pixels) of the padded image + oh - height (in pixels) of the padded image + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int pad_uchar_image(unsigned char **optr, int *ow, int *oh, + unsigned char *idata, const int iw, const int ih, + const int pad, const int pad_value) +{ + unsigned char *pdata, *pptr, *iptr; + int i, pw, ph; + int pad2, psize; + + /* Account for pad on both sides of image */ + pad2 = pad<<1; + + /* Compute new pad sizes */ + pw = iw + pad2; + ph = ih + pad2; + psize = pw * ph; + + /* Allocate padded image */ + pdata = (unsigned char *)malloc(psize * sizeof(unsigned char)); + if(pdata == (unsigned char *)NULL){ + fprintf(stderr, "ERROR : pad_uchar_image : malloc : pdata\n"); + return(-160); + } + + /* Initialize values to a constant PAD value */ + memset(pdata, pad_value, psize); + + /* Copy input image into padded image one scanline at a time */ + iptr = idata; + pptr = pdata + (pad * pw) + pad; + for(i = 0; i < ih; i++){ + memcpy(pptr, iptr, iw); + iptr += iw; + pptr += pw; + } + + *optr = pdata; + *ow = pw; + *oh = ph; + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: fill_holes - Takes an input image and analyzes triplets of horizontal +#cat: pixels first and then triplets of vertical pixels, filling +#cat: in holes of width 1. A hole is defined as the case where +#cat: the neighboring 2 pixels are equal, AND the center pixel +#cat: is different. Each hole is filled with the value of its +#cat: immediate neighbors. This routine modifies the input image. + + Input: + bdata - binary image data to be processed + iw - width (in pixels) of the binary input image + ih - height (in pixels) of the binary input image + Output: + bdata - points to the results +**************************************************************************/ +void fill_holes(unsigned char *bdata, const int iw, const int ih) +{ + int ix, iy, iw2; + unsigned char *lptr, *mptr, *rptr, *tptr, *bptr, *sptr; + + /* 1. Fill 1-pixel wide holes in horizontal runs first ... */ + sptr = bdata + 1; + /* Foreach row in image ... */ + for(iy = 0; iy < ih; iy++){ + /* Initialize pointers to start of next line ... */ + lptr = sptr-1; /* Left pixel */ + mptr = sptr; /* Middle pixel */ + rptr = sptr+1; /* Right pixel */ + /* Foreach column in image (less far left and right pixels) ... */ + for(ix = 1; ix < iw-1; ix++){ + /* Do we have a horizontal hole of length 1? */ + if((*lptr != *mptr) && (*lptr == *rptr)){ + /* If so, then fill it. */ + *mptr = *lptr; + /* Bump passed right pixel because we know it will not */ + /* be a hole. */ + lptr+=2; + mptr+=2; + rptr+=2; + /* We bump ix once here and then the FOR bumps it again. */ + ix++; + } + else{ + /* Otherwise, bump to the next pixel to the right. */ + lptr++; + mptr++; + rptr++; + } + } + /* Bump to start of next row. */ + sptr += iw; + } + + /* 2. Now, fill 1-pixel wide holes in vertical runs ... */ + iw2 = iw<<1; + /* Start processing column one row down from the top of the image. */ + sptr = bdata + iw; + /* Foreach column in image ... */ + for(ix = 0; ix < iw; ix++){ + /* Initialize pointers to start of next column ... */ + tptr = sptr-iw; /* Top pixel */ + mptr = sptr; /* Middle pixel */ + bptr = sptr+iw; /* Bottom pixel */ + /* Foreach row in image (less top and bottom row) ... */ + for(iy = 1; iy < ih-1; iy++){ + /* Do we have a vertical hole of length 1? */ + if((*tptr != *mptr) && (*tptr == *bptr)){ + /* If so, then fill it. */ + *mptr = *tptr; + /* Bump passed bottom pixel because we know it will not */ + /* be a hole. */ + tptr+=iw2; + mptr+=iw2; + bptr+=iw2; + /* We bump iy once here and then the FOR bumps it again. */ + iy++; + } + else{ + /* Otherwise, bump to the next pixel below. */ + tptr+=iw; + mptr+=iw; + bptr+=iw; + } + } + /* Bump to start of next column. */ + sptr++; + } +} + +/************************************************************************* +************************************************************************** +#cat: free_path - Traverses a straight line between 2 pixel points in an +#cat: image and determines if a "free path" exists between the +#cat: 2 points by counting the number of pixel value transitions +#cat: between adjacent pixels along the trajectory. + + Input: + x1 - x-pixel coord of first point + y1 - y-pixel coord of first point + x2 - x-pixel coord of second point + y2 - y-pixel coord of second point + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + lfsparms - parameters and threshold for controlling LFS + Return Code: + TRUE - free path determined to exist + FALSE - free path determined not to exist + Negative - system error +**************************************************************************/ +int free_path(const int x1, const int y1, const int x2, const int y2, + unsigned char *bdata, const int iw, const int ih, + const LFSPARMS *lfsparms) +{ + int *x_list, *y_list, num; + int ret; + int i, trans, preval, nextval; + + /* Compute points along line segment between the two points. */ + if((ret = line_points(&x_list, &y_list, &num, x1, y1, x2, y2))) + return(ret); + + /* Intialize the number of transitions to 0. */ + trans = 0; + /* Get the pixel value of first point along line segment. */ + preval = *(bdata+(y1*iw)+x1); + + /* Foreach remaining point along line segment ... */ + for(i = 1; i < num; i++){ + /* Get pixel value of next point along line segment. */ + nextval = *(bdata+(y_list[i]*iw)+x_list[i]); + + /* If next pixel value different from previous pixel value ... */ + if(nextval != preval){ + /* Then we have detected a transition, so bump counter. */ + trans++; + /* If number of transitions seen > than threshold (ex. 2) ... */ + if(trans > lfsparms->maxtrans){ + /* Deallocate the line segment's coordinate lists. */ + free(x_list); + free(y_list); + /* Return free path to be FALSE. */ + return(FALSE); + } + /* Otherwise, maximum number of transitions not yet exceeded. */ + /* Assign the next pixel value to the previous pixel value. */ + preval = nextval; + } + /* Otherwise, no transition detected this interation. */ + + } + + /* If we get here we did not exceed the maximum allowable number */ + /* of transitions. So, deallocate the line segment's coordinate lists. */ + free(x_list); + free(y_list); + + /* Return free path to be TRUE. */ + return(TRUE); +} + +/************************************************************************* +************************************************************************** +#cat: search_in_direction - Takes a specified maximum number of steps in a +#cat: specified direction looking for the first occurence of +#cat: a pixel with specified value. (Once found, adjustments +#cat: are potentially made to make sure the resulting pixel +#cat: and its associated edge pixel are 4-connected.) + + Input: + pix - value of pixel to be searched for + strt_x - x-pixel coord to start search + strt_y - y-pixel coord to start search + delta_x - increment in x for each step + delta_y - increment in y for each step + maxsteps - maximum number of steps to conduct search + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + ox - x coord of located pixel + oy - y coord of located pixel + oex - x coord of associated edge pixel + oey - y coord of associated edge pixel + Return Code: + TRUE - pixel of specified value found + FALSE - pixel of specified value NOT found +**************************************************************************/ +int search_in_direction(int *ox, int *oy, int *oex, int *oey, const int pix, + const int strt_x, const int strt_y, + const double delta_x, const double delta_y, const int maxsteps, + unsigned char *bdata, const int iw, const int ih) +{ + + int i, x, y, px, py; + double fx, fy; + + /* Set previous point to starting point. */ + px = strt_x; + py = strt_y; + /* Set floating point accumulators to starting point. */ + fx = (double)strt_x; + fy = (double)strt_y; + + /* Foreach step up to the specified maximum ... */ + for(i = 0; i < maxsteps; i++){ + + /* Increment accumulators. */ + fx += delta_x; + fy += delta_y; + /* Round to get next step. */ + x = sround(fx); + y = sround(fy); + + /* If we stepped outside the image boundaries ... */ + if((x < 0) || (x >= iw) || + (y < 0) || (y >= ih)){ + /* Return FALSE (we did not find what we were looking for). */ + *ox = -1; + *oy = -1; + *oex = -1; + *oey = -1; + return(FALSE); + } + + /* Otherwise, test to see if we found our pixel with value 'pix'. */ + if(*(bdata+(y*iw)+x) == pix){ + /* The previous and current pixels form a feature, edge pixel */ + /* pair, which we would like to use for edge following. The */ + /* previous pixel may be a diagonal neighbor however to the */ + /* current pixel, in which case the pair could not be used by */ + /* the contour tracing (which requires the edge pixel in the */ + /* pair neighbor to the N,S,E or W. */ + /* This routine adjusts the pair so that the results may be */ + /* used by the contour tracing. */ + fix_edge_pixel_pair(&x, &y, &px, &py, bdata, iw, ih); + + /* Return TRUE (we found what we were looking for). */ + *ox = x; + *oy = y; + *oex = px; + *oey = py; + return(TRUE); + } + + /* Otherwise, still haven't found pixel with desired value, */ + /* so set current point to previous and take another step. */ + px = x; + py = y; + } + + /* Return FALSE (we did not find what we were looking for). */ + *ox = -1; + *oy = -1; + *oex = -1; + *oey = -1; + return(FALSE); +} + diff --git a/libfprint/nbis/mindtct/init.c b/libfprint/nbis/mindtct/init.c new file mode 100644 index 00000000..44141652 --- /dev/null +++ b/libfprint/nbis/mindtct/init.c @@ -0,0 +1,768 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: INIT.C + AUTHOR: Michael D. Garris + DATE: 03/16/1999 + UPDATED: 10/04/1999 Version 2 by MDG + UPDATED: 03/16/2005 by MDG + + Contains routines responsible for allocation and/or initialization + of memories required by the NIST Latent Fingerprint System. + +*********************************************************************** + ROUTINES: + init_dir2rad() + init_dftwaves() + get_max_padding() + get_max_padding_V2() + init_rotgrids() + alloc_dir_powers() + alloc_power_stats() +***********************************************************************/ + +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: init_dir2rad - Allocates and initializes a lookup table containing +#cat: cosine and sine values needed to convert integer IMAP +#cat: directions to angles in radians. + + Input: + ndirs - the number of integer directions to be defined in a + semicircle + Output: + optr - points to the allocated/initialized DIR2RAD structure + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int init_dir2rad(DIR2RAD **optr, const int ndirs) +{ + DIR2RAD *dir2rad; + int i; + double theta, pi_factor; + double cs, sn; + + /* Allocate structure */ + dir2rad = (DIR2RAD *)malloc(sizeof(DIR2RAD)); + if(dir2rad == (DIR2RAD *)NULL){ + fprintf(stderr, "ERROR : init_dir2rad : malloc : dir2rad\n"); + return(-10); + } + + /* Assign number of directions */ + dir2rad->ndirs = ndirs; + + /* Allocate cosine vector */ + dir2rad->cos = (double *)malloc(ndirs * sizeof(double)); + if(dir2rad->cos == (double *)NULL){ + /* Free memory allocated to this point. */ + free(dir2rad); + fprintf(stderr, "ERROR : init_dir2rad : malloc : dir2rad->cos\n"); + return(-11); + } + + /* Allocate sine vector */ + dir2rad->sin = (double *)malloc(ndirs * sizeof(double)); + if(dir2rad->sin == (double *)NULL){ + /* Free memory allocated to this point. */ + free(dir2rad->cos); + free(dir2rad); + fprintf(stderr, "ERROR : init_dir2rad : malloc : dir2rad->sin\n"); + return(-12); + } + + /* Pi_factor sets the period of the trig functions to NDIRS units in x. */ + /* For example, if NDIRS==16, then pi_factor = 2(PI/16) = .3926... */ + pi_factor = 2.0*M_PI/(double)ndirs; + + /* Now compute cos and sin values for each direction. */ + for (i = 0; i < ndirs; ++i) { + theta = (double)(i * pi_factor); + cs = cos(theta); + sn = sin(theta); + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures. */ + cs = trunc_dbl_precision(cs, TRUNC_SCALE); + sn = trunc_dbl_precision(sn, TRUNC_SCALE); + dir2rad->cos[i] = cs; + dir2rad->sin[i] = sn; + } + + *optr = dir2rad; + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: init_dftwaves - Allocates and initializes a set of wave forms needed +#cat: to conduct DFT analysis on blocks of the input image + + Input: + dft_coefs - array of multipliers used to define the frequency for + each wave form to be computed + nwaves - number of wave forms to be computed + blocksize - the width and height of each block of image data to + be DFT analyzed + Output: + optr - points to the allocated/initialized DFTWAVES structure + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int init_dftwaves(DFTWAVES **optr, const double *dft_coefs, + const int nwaves, const int blocksize) +{ + DFTWAVES *dftwaves; + int i, j; + double pi_factor, freq, x; + double *cptr, *sptr; + + /* Allocate structure */ + dftwaves = (DFTWAVES *)malloc(sizeof(DFTWAVES)); + if(dftwaves == (DFTWAVES *)NULL){ + fprintf(stderr, "ERROR : init_dftwaves : malloc : dftwaves\n"); + return(-20); + } + + /* Set number of DFT waves */ + dftwaves->nwaves = nwaves; + /* Set wave length of the DFT waves (they all must be the same length) */ + dftwaves->wavelen = blocksize; + + /* Allocate list of wave pointers */ + dftwaves->waves = (DFTWAVE **)malloc(nwaves * sizeof(DFTWAVE *)); + if(dftwaves == (DFTWAVES *)NULL){ + /* Free memory allocated to this point. */ + free(dftwaves); + fprintf(stderr, "ERROR : init_dftwaves : malloc : dftwaves->waves\n"); + return(-21); + } + + /* Pi_factor sets the period of the trig functions to BLOCKSIZE units */ + /* in x. For example, if BLOCKSIZE==24, then */ + /* pi_factor = 2(PI/24) = .26179... */ + pi_factor = 2.0*M_PI/(double)blocksize; + + /* Foreach of 4 DFT frequency coef ... */ + for (i = 0; i < nwaves; ++i) { + /* Allocate wave structure */ + dftwaves->waves[i] = (DFTWAVE *)malloc(sizeof(DFTWAVE)); + if(dftwaves->waves[i] == (DFTWAVE *)NULL){ + /* Free memory allocated to this point. */ + { int _j; for(_j = 0; _j < i; _j++){ + free(dftwaves->waves[_j]->cos); + free(dftwaves->waves[_j]->sin); + free(dftwaves->waves[_j]); + }} + free(dftwaves->waves); + free(dftwaves); + fprintf(stderr, + "ERROR : init_dftwaves : malloc : dftwaves->waves[i]\n"); + return(-22); + } + /* Allocate cosine vector */ + dftwaves->waves[i]->cos = (double *)malloc(blocksize * sizeof(double)); + if(dftwaves->waves[i]->cos == (double *)NULL){ + /* Free memory allocated to this point. */ + { int _j; for(_j = 0; _j < i; _j++){ + free(dftwaves->waves[_j]->cos); + free(dftwaves->waves[_j]->sin); + free(dftwaves->waves[_j]); + }} + free(dftwaves->waves[i]); + free(dftwaves->waves); + free(dftwaves); + fprintf(stderr, + "ERROR : init_dftwaves : malloc : dftwaves->waves[i]->cos\n"); + return(-23); + } + /* Allocate sine vector */ + dftwaves->waves[i]->sin = (double *)malloc(blocksize * sizeof(double)); + if(dftwaves->waves[i]->sin == (double *)NULL){ + /* Free memory allocated to this point. */ + { int _j; for(_j = 0; _j < i; _j++){ + free(dftwaves->waves[_j]->cos); + free(dftwaves->waves[_j]->sin); + free(dftwaves->waves[_j]); + }} + free(dftwaves->waves[i]->cos); + free(dftwaves->waves[i]); + free(dftwaves->waves); + free(dftwaves); + fprintf(stderr, + "ERROR : init_dftwaves : malloc : dftwaves->waves[i]->sin\n"); + return(-24); + } + + /* Assign pointer nicknames */ + cptr = dftwaves->waves[i]->cos; + sptr = dftwaves->waves[i]->sin; + + /* Compute actual frequency */ + freq = pi_factor * dft_coefs[i]; + + /* Used as a 1D DFT on a 24 long vector of pixel sums */ + for (j = 0; j < blocksize; ++j) { + /* Compute sample points from frequency */ + x = freq * (double)j; + /* Store cos and sin components of sample point */ + *cptr++ = cos(x); + *sptr++ = sin(x); + } + } + + *optr = dftwaves; + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: get_max_padding - Deterines the maximum amount of image pixel padding +#cat: required by all LFS processes. Padding is currently +#cat: required by the rotated grids used in DFT analyses, +#cat: rotated grids used in directional binarization, +#cat: and in the grid used for isotropic binarization. +#cat: The NIST generalized code enables the parameters +#cat: governing these processes to be redefined, so a check +#cat: at runtime is required to determine which process +#cat: requires the most padding. By using the maximum as +#cat: the padding factor, all processes will run safely +#cat: with a single padding of the input image avoiding the +#cat: need to repad for further processes. + + Input: + imap_blocksize - the size (in pixels) of each IMAP block in the image + dirbin_grid_w - the width (in pixels) of the rotated grids used in + directional binarization + dirbin_grid_h - the height (in pixels) of the rotated grids used in + directional binarization + isobin_grid_dim - the dimension (in pixels) of the square grid used in + isotropic binarization + Return Code: + Non-negative - the maximum padding required for all processes +**************************************************************************/ +int get_max_padding(const int imap_blocksize, + const int dirbin_grid_w, const int dirbin_grid_h, + const int isobin_grid_dim) +{ + int dft_pad, dirbin_pad, isobin_pad, max_pad; + double diag; + double pad; + + /* Compute pad required for rotated blocks used in DFT analyses. */ + diag = sqrt((double)(2.0 * imap_blocksize * imap_blocksize)); + /* Compute pad as difference between the IMAP blocksize */ + /* and the diagonal distance of the block. */ + /* Assumption: all block origins reside in valid/allocated memory. */ + /* DFT grids are computed with pixel offsets RELATIVE2ORIGIN. */ + pad = (diag-imap_blocksize)/(double)2.0; + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + pad = trunc_dbl_precision(pad, TRUNC_SCALE); + dft_pad = sround(pad); + + /* Compute pad required for rotated blocks used in directional */ + /* binarization. */ + diag = sqrt((double)((dirbin_grid_w*dirbin_grid_w)+ + (dirbin_grid_h*dirbin_grid_h))); + /* Assumption: all grid centers reside in valid/allocated memory. */ + /* dirbin grids are computed with pixel offsets RELATIVE2CENTER. */ + pad = (diag-1)/(double)2.0; + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + pad = trunc_dbl_precision(pad, TRUNC_SCALE); + dirbin_pad = sround(pad); + + /* Compute pad required for grids used in isotropic binarization. */ + pad = (isobin_grid_dim - 1)/(double)2.0; + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + pad = trunc_dbl_precision(pad, TRUNC_SCALE); + isobin_pad = sround((isobin_grid_dim - 1)/(double)2.0); + + max_pad = max(dft_pad, dirbin_pad); + max_pad = max(max_pad, isobin_pad); + + /* Return the maximum of the three required paddings. This padding will */ + /* be sufficiently large for all three purposes, so that padding of the */ + /* input image will only be required once. */ + return(max_pad); +} + +/************************************************************************* +************************************************************************** +#cat: get_max_padding_V2 - Deterines the maximum amount of image pixel padding +#cat: required by all LFS (Version 2) processes. Padding is currently +#cat: required by the rotated grids used in DFT analyses and in +#cat: directional binarization. The NIST generalized code enables +#cat: the parameters governing these processes to be redefined, so a +#cat: check at runtime is required to determine which process +#cat: requires the most padding. By using the maximum as the padding +#cat: factor, all processes will run safely with a single padding of +#cat: the input image avoiding the need to repad for further processes. + + Input: + map_windowsize - the size (in pixels) of each window centered about + each block in the image used in DFT analyses + map_windowoffset - the offset (in pixels) from the orgin of the + surrounding window to the origin of the block + dirbin_grid_w - the width (in pixels) of the rotated grids used in + directional binarization + dirbin_grid_h - the height (in pixels) of the rotated grids used in + directional binarization + Return Code: + Non-negative - the maximum padding required for all processes +**************************************************************************/ +int get_max_padding_V2(const int map_windowsize, const int map_windowoffset, + const int dirbin_grid_w, const int dirbin_grid_h) +{ + int dft_pad, dirbin_pad, max_pad; + double diag; + double pad; + + + /* 1. Compute pad required for rotated windows used in DFT analyses. */ + + /* Explanation of DFT padding: + + B--------------------- + | window | + | | + | | + | A.......______|__________ + | : : | + |<-C-->: block: | + <--|--D-->: : | image + | ........ | + | | | + | | | + | | | + ---------------------- + | + | + | + + Pixel A = Origin of entire fingerprint image + = Also origin of first block in image. Each pixel in + this block gets the same DFT results computed from + the surrounding window. Note that in general + blocks are adjacent and non-overlapping. + + Pixel B = Origin of surrounding window in which DFT + analysis is conducted. Note that this window is not + completely contained in the image but extends to the + top and to the right. + + Distance C = Number of pixels in which the window extends + beyond the image (map_windowoffset). + + Distance D = Amount of padding required to hold the entire + rotated window in memory. + + */ + + /* Compute pad as difference between the MAP windowsize */ + /* and the diagonal distance of the window. */ + /* (DFT grids are computed with pixel offsets RELATIVE2ORIGIN.) */ + diag = sqrt((double)(2.0 * map_windowsize * map_windowsize)); + pad = (diag-map_windowsize)/(double)2.0; + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + pad = trunc_dbl_precision(pad, TRUNC_SCALE); + /* Must add the window offset to the rotational padding. */ + dft_pad = sround(pad) + map_windowoffset; + + /* 2. Compute pad required for rotated blocks used in directional */ + /* binarization. Binarization blocks are applied to each pixel */ + /* in the input image. */ + diag = sqrt((double)((dirbin_grid_w*dirbin_grid_w)+ + (dirbin_grid_h*dirbin_grid_h))); + /* Assumption: all grid centers reside in valid/allocated memory. */ + /* (Dirbin grids are computed with pixel offsets RELATIVE2CENTER.) */ + pad = (diag-1)/(double)2.0; + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + pad = trunc_dbl_precision(pad, TRUNC_SCALE); + dirbin_pad = sround(pad); + + max_pad = max(dft_pad, dirbin_pad); + + /* Return the maximum of the two required paddings. This padding will */ + /* be sufficiently large for all purposes, so that padding of the */ + /* input image will only be required once. */ + return(max_pad); +} + +/************************************************************************* +************************************************************************** +#cat: init_rotgrids - Allocates and initializes a set of offsets that address +#cat: individual rotated pixels within a grid. +#cat: These rotated grids are used to conduct DFT analyses +#cat: on blocks of input image data, and they are used +#cat: in isotropic binarization. + + Input: + iw - width (in pixels) of the input image + ih - height (in pixels) of the input image + pad - designates the number of pixels to be padded to the perimeter + of the input image. May be passed as UNDEFINED, in which + case the specific padding required by the rotated grids + will be computed and returned in ROTGRIDS. + start_dir_angle - angle from which rotations are to start + ndirs - number of rotations to compute (within a semicircle) + grid_w - width of the grid in pixels to be rotated + grid_h - height of the grid in pixels to be rotated + relative2 - designates whether pixel offsets whould be computed + relative to the ORIGIN or the CENTER of the grid + Output: + optr - points to the allcated/initialized ROTGRIDS structure + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int init_rotgrids(ROTGRIDS **optr, const int iw, const int ih, const int ipad, + const double start_dir_angle, const int ndirs, + const int grid_w, const int grid_h, const int relative2) +{ + ROTGRIDS *rotgrids; + double pi_offset, pi_incr; + int dir, ix, iy, grid_size, pw, grid_pad, min_dim; + int *grid; + double diag, theta, cs, sn, cx, cy; + double fxm, fym, fx, fy; + int ixt, iyt; + double pad; + + /* Allocate structure */ + rotgrids = (ROTGRIDS *)malloc(sizeof(ROTGRIDS)); + if(rotgrids == (ROTGRIDS *)NULL){ + fprintf(stderr, "ERROR : init_rotgrids : malloc : rotgrids\n"); + return(-30); + } + + /* Set rotgrid attributes */ + rotgrids->ngrids = ndirs; + rotgrids->grid_w = grid_w; + rotgrids->grid_h = grid_h; + rotgrids->start_angle = start_dir_angle; + rotgrids->relative2 = relative2; + + /* Compute pad based on diagonal of the grid */ + diag = sqrt((double)((grid_w*grid_w)+(grid_h*grid_h))); + switch(relative2){ + case RELATIVE2CENTER: + /* Assumption: all grid centers reside in valid/allocated memory. */ + pad = (diag-1)/(double)2.0; + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + pad = trunc_dbl_precision(pad, TRUNC_SCALE); + grid_pad = sround(pad); + break; + case RELATIVE2ORIGIN: + /* Assumption: all grid origins reside in valid/allocated memory. */ + min_dim = min(grid_w, grid_h); + /* Compute pad as difference between the smallest grid dimension */ + /* and the diagonal distance of the grid. */ + pad = (diag-min_dim)/(double)2.0; + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + pad = trunc_dbl_precision(pad, TRUNC_SCALE); + grid_pad = sround(pad); + break; + default: + fprintf(stderr, + "ERROR : init_rotgrids : Illegal relative flag : %d\n", + relative2); + free(rotgrids); + return(-31); + } + + /* If input padding is UNDEFINED ... */ + if(ipad == UNDEFINED) + /* Use the padding specifically required by the rotated grids herein. */ + rotgrids->pad = grid_pad; + else{ + /* Otherwise, input pad was specified, so check to make sure it is */ + /* sufficiently large to handle the rotated grids herein. */ + if(ipad < grid_pad){ + /* If input pad is NOT large enough, then ERROR. */ + fprintf(stderr, "ERROR : init_rotgrids : Pad passed is too small\n"); + free(rotgrids); + return(-32); + } + /* Otherwise, use the specified input pad in computing grid offsets. */ + rotgrids->pad = ipad; + } + + /* Total number of points in grid */ + grid_size = grid_w * grid_h; + + /* Compute width of "padded" image */ + pw = iw + (rotgrids->pad<<1); + + /* Center coord of grid (0-oriented). */ + cx = (grid_w-1)/(double)2.0; + cy = (grid_h-1)/(double)2.0; + + /* Allocate list of rotgrid pointers */ + rotgrids->grids = (int **)malloc(ndirs * sizeof(int *)); + if(rotgrids->grids == (int **)NULL){ + /* Free memory allocated to this point. */ + free(rotgrids); + fprintf(stderr, "ERROR : init_rotgrids : malloc : rotgrids->grids\n"); + return(-33); + } + + /* Pi_offset is the offset in radians from which angles are to begin. */ + pi_offset = start_dir_angle; + pi_incr = M_PI/(double)ndirs; /* if ndirs == 16, incr = 11.25 degrees */ + + /* For each direction to rotate a grid ... */ + for (dir = 0, theta = pi_offset; + dir < ndirs; dir++, theta += pi_incr) { + + /* Allocate a rotgrid */ + rotgrids->grids[dir] = (int *)malloc(grid_size * sizeof(int)); + if(rotgrids->grids[dir] == (int *)NULL){ + /* Free memory allocated to this point. */ + { int _j; for(_j = 0; _j < dir; _j++){ + free(rotgrids->grids[_j]); + }} + free(rotgrids); + fprintf(stderr, + "ERROR : init_rotgrids : malloc : rotgrids->grids[dir]\n"); + return(-34); + } + + /* Set pointer to current grid */ + grid = rotgrids->grids[dir]; + + /* Compute cos and sin of current angle */ + cs = cos(theta); + sn = sin(theta); + + /* This next section of nested FOR loops precomputes a */ + /* rotated grid. The rotation is set up to rotate a GRID_W X */ + /* GRID_H grid on its center point at C=(Cx,Cy). The current */ + /* pixel being rotated is P=(Ix,Iy). Therefore, we have a */ + /* rotation transformation of point P about pivot point C. */ + /* The rotation transformation about a pivot point in matrix */ + /* form is: */ + /* + +- -+ + | cos(T) sin(T) 0 | + [Ix Iy 1] | -sin(T) cos(T) 0 | + | (1-cos(T))*Cx + Cy*sin(T) (1-cos(T))*Cy - Cx*sin(T) 1 | + +- -+ + */ + /* Multiplying the 2 matrices and combining terms yeilds the */ + /* equations for rotated coordinates (Rx, Ry): */ + /* Rx = Cx + (Ix - Cx)*cos(T) - (Iy - Cy)*sin(T) */ + /* Ry = Cy + (Ix - Cx)*sin(T) + (Iy - Cy)*cos(T) */ + /* */ + /* Care has been taken to ensure that (for example) when */ + /* BLOCKSIZE==24 the rotated indices stay within a centered */ + /* 34X34 area. */ + /* This is important for computing an accurate padding of */ + /* the input image. The rotation occurs "in-place" so that */ + /* outer pixels in the grid are mapped at times from */ + /* adjoining blocks. As a result, to keep from accessing */ + /* "unknown" memory or pixels wrapped from the other side of */ + /* the image, the input image should first be padded by */ + /* PAD=round((DIAG - BLOCKSIZE)/2.0) where DIAG is the */ + /* diagonal distance of the grid. */ + /* For example, when BLOCKSIZE==24, Dx=34, so PAD=5. */ + + /* Foreach each y coord in block ... */ + for (iy = 0; iy < grid_h; ++iy) { + /* Compute rotation factors dependent on Iy (include constant) */ + fxm = -1.0 * ((iy - cy) * sn); + fym = ((iy - cy) * cs); + + /* If offsets are to be relative to the grids origin, then */ + /* we need to subtract CX and CY. */ + if(relative2 == RELATIVE2ORIGIN){ + fxm += cx; + fym += cy; + } + + /* foreach each x coord in block ... */ + for (ix = 0; ix < grid_w; ++ix) { + + /* Now combine factors dependent on Iy with those of Ix */ + fx = fxm + ((ix - cx) * cs); + fy = fym + ((ix - cx) * sn); + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + fx = trunc_dbl_precision(fx, TRUNC_SCALE); + fy = trunc_dbl_precision(fy, TRUNC_SCALE); + ixt = sround(fx); + iyt = sround(fy); + + /* Store the current pixels relative */ + /* rotated offset. Make sure to */ + /* multiply the y-component of the */ + /* offset by the "padded" image width! */ + *grid++ = ixt + (iyt * pw); + }/* ix */ + }/* iy */ + }/* dir */ + + *optr = rotgrids; + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: alloc_dir_powers - Allocates the memory associated with DFT power +#cat: vectors. The DFT analysis is conducted block by block in the +#cat: input image, and within each block, N wave forms are applied +#cat: at M different directions. + + Input: + nwaves - number of DFT wave forms + ndirs - number of orientations (directions) used in DFT analysis + Output: + opowers - pointer to the allcated power vectors + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int alloc_dir_powers(double ***opowers, const int nwaves, const int ndirs) +{ + int w; + double **powers; + + /* Allocate list of double pointers to hold power vectors */ + powers = (double **)malloc(nwaves * sizeof(double*)); + if(powers == (double **)NULL){ + fprintf(stderr, "ERROR : alloc_dir_powers : malloc : powers\n"); + return(-40); + } + /* Foreach DFT wave ... */ + for(w = 0; w < nwaves; w++){ + /* Allocate power vector for all directions */ + powers[w] = (double *)malloc(ndirs * sizeof(double)); + if(powers[w] == (double *)NULL){ + /* Free memory allocated to this point. */ + { int _j; for(_j = 0; _j < w; _j++){ + free(powers[_j]); + }} + free(powers); + fprintf(stderr, "ERROR : alloc_dir_powers : malloc : powers[w]\n"); + return(-41); + } + } + + *opowers = powers; + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: alloc_power_stats - Allocates memory associated with set of statistics +#cat: derived from DFT power vectors computed in a block of the +#cat: input image. Statistics are not computed for the lowest DFT +#cat: wave form, so the length of the statistics arrays is 1 less +#cat: than the number of DFT wave forms used. The staistics +#cat: include the Maximum power for each wave form, the direction +#cat: at which the maximum power occured, and a normalized value +#cat: for the maximum power. In addition, the statistics are +#cat: ranked in descending order based on normalized squared +#cat: maximum power. + + Input: + nstats - the number of waves forms from which statistics are to be + derived (N Waves - 1) + Output: + owis - points to an array to hold the ranked wave form indicies + of the corresponding statistics + opowmaxs - points to an array to hold the maximum DFT power for each + wave form + opowmax_dirs - points to an array to hold the direction corresponding to + each maximum power value + opownorms - points to an array to hold the normalized maximum power + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int alloc_power_stats(int **owis, double **opowmaxs, int **opowmax_dirs, + double **opownorms, const int nstats) +{ + int *wis, *powmax_dirs; + double *powmaxs, *pownorms; + + /* Allocate DFT wave index vector */ + wis = (int *)malloc(nstats * sizeof(int)); + if(wis == (int *)NULL){ + fprintf(stderr, "ERROR : alloc_power_stats : malloc : wis\n"); + return(-50); + } + + /* Allocate max power vector */ + powmaxs = (double *)malloc(nstats * sizeof(double)); + if(powmaxs == (double *)NULL){ + /* Free memory allocated to this point. */ + free(wis); + fprintf(stderr, "ERROR : alloc_power_stats : malloc : powmaxs\n"); + return(-51); + } + + /* Allocate max power direction vector */ + powmax_dirs = (int *)malloc(nstats * sizeof(int)); + if(powmax_dirs == (int *)NULL){ + /* Free memory allocated to this point. */ + free(wis); + free(powmaxs); + fprintf(stderr, "ERROR : alloc_power_stats : malloc : powmax_dirs\n"); + return(-52); + } + + /* Allocate normalized power vector */ + pownorms = (double *)malloc(nstats * sizeof(double)); + if(pownorms == (double *)NULL){ + /* Free memory allocated to this point. */ + free(wis); + free(powmaxs); + free(pownorms); + fprintf(stderr, "ERROR : alloc_power_stats : malloc : pownorms\n"); + return(-53); + } + + *owis = wis; + *opowmaxs = powmaxs; + *opowmax_dirs = powmax_dirs; + *opownorms = pownorms; + return(0); +} + + + diff --git a/libfprint/nbis/mindtct/isempty.c b/libfprint/nbis/mindtct/isempty.c new file mode 100644 index 00000000..da42cc35 --- /dev/null +++ b/libfprint/nbis/mindtct/isempty.c @@ -0,0 +1,94 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/************************************************************************/ +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: ISEMPTY.C + AUTHOR: Michael D. Garris + DATE: 09/13/2004 + + Contains routines responsible for determining if a fingerprint + image is empty. + +*********************************************************************** + ROUTINES: + is_image_empty() + is_qmap_empty() + +***********************************************************************/ + +#include + +/*********************************************************************** +************************************************************************ +#cat: is_image_empty - Routine determines if statistics passed indicate +#cat: an empty image. + + Input: + quality_map - quality map computed by NIST's Mindtct + map_w - width of map + map_h - height of map + Return Code: + True - image determined empty + False - image determined NOT empty +************************************************************************/ +int is_image_empty(int *quality_map, const int map_w, const int map_h) +{ + /* This routine is designed to be expanded as more statistical */ + /* tests are developed. */ + + if(is_qmap_empty(quality_map, map_w, map_h)) + return(TRUE); + else + return(FALSE); +} + +/*********************************************************************** +************************************************************************ +#cat: is_qmap_empty - Routine determines if quality map is all set to zero + + Input: + quality_map - quality map computed by NIST's Mindtct + map_w - width of map + map_h - height of map + Return Code: + True - quality map is empty + False - quality map is NOT empty +************************************************************************/ +int is_qmap_empty(int *quality_map, const int map_w, const int map_h) +{ + int i, maplen; + int *qptr; + + qptr = quality_map; + maplen = map_w * map_h; + for(i = 0; i < maplen; i++){ + if(*qptr++ != 0){ + return(FALSE); + } + } + return(TRUE); +} + diff --git a/libfprint/nbis/mindtct/line.c b/libfprint/nbis/mindtct/line.c new file mode 100644 index 00000000..5d9a8ed5 --- /dev/null +++ b/libfprint/nbis/mindtct/line.c @@ -0,0 +1,203 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: LINE.C + AUTHOR: Michael D. Garris + DATE: 03/16/1999 + + Contains routines that compute contiguous linear trajectories + between two coordinate points required by the NIST Latent + Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + line_points() +***********************************************************************/ + +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: line_points - Returns the contiguous coordinates of a line connecting +#cat: 2 specified points. + + Input: + x1 - x-coord of first point + y1 - y-coord of first point + x2 - x-coord of second point + y2 - y-coord of second point + Output: + ox_list - x-coords along line trajectory + oy_list - y-coords along line trajectory + onum - number of points along line trajectory + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int line_points(int **ox_list, int **oy_list, int *onum, + const int x1, const int y1, const int x2, const int y2) +{ + int asize; + int dx, dy, adx, ady; + int x_incr, y_incr; + int i, inx, iny, intx, inty; + double x_factor, y_factor; + double rx, ry; + int ix, iy; + int *x_list, *y_list; + + /* Compute maximum number of points needed to hold line segment. */ + asize = max(abs(x2-x1)+2, abs(y2-y1)+2); + + /* Allocate x and y-pixel coordinate lists to length 'asize'. */ + x_list = (int *)malloc(asize*sizeof(int)); + if(x_list == (int *)NULL){ + fprintf(stderr, "ERROR : line_points : malloc : x_list\n"); + return(-410); + } + y_list = (int *)malloc(asize*sizeof(int)); + if(y_list == (int *)NULL){ + free(x_list); + fprintf(stderr, "ERROR : line_points : malloc : y_list\n"); + return(-411); + } + + /* Compute delta x and y. */ + dx = x2 - x1; + dy = y2 - y1; + + /* Set x and y increments. */ + if(dx >= 0) + x_incr = 1; + else + x_incr = -1; + + if(dy >= 0) + y_incr = 1; + else + y_incr = -1; + + /* Compute |DX| and |DY|. */ + adx = abs(dx); + ady = abs(dy); + + /* Set x-orientation. */ + if(adx > ady) + inx = 1; + else + inx = 0; + + /* Set y-orientation. */ + if(ady > adx) + iny = 1; + else + iny = 0; + + /* CASE 1: |DX| > |DY| */ + /* Increment in X by +-1 */ + /* in Y by +-|DY|/|DX| */ + /* inx = 1 */ + /* iny = 0 */ + /* intx = 1 (inx) */ + /* inty = 0 (iny) */ + /* CASE 2: |DX| < |DY| */ + /* Increment in Y by +-1 */ + /* in X by +-|DX|/|DY| */ + /* inx = 0 */ + /* iny = 1 */ + /* intx = 0 (inx) */ + /* inty = 1 (iny) */ + /* CASE 3: |DX| == |DY| */ + /* inx = 0 */ + /* iny = 0 */ + /* intx = 1 */ + /* inty = 1 */ + intx = 1 - iny; + inty = 1 - inx; + + /* DX */ + /* x_factor = (inx * +-1) + ( iny * ------------ ) */ + /* max(1, |DY|) */ + /* */ + x_factor = (inx * x_incr) + (iny * ((double)dx/max(1, ady))); + + /* DY */ + /* y_factor = (iny * +-1) + ( inx * ------------ ) */ + /* max(1, |DX|) */ + /* */ + y_factor = (iny * y_incr) + (inx * ((double)dy/max(1, adx))); + + /* Initialize integer coordinates. */ + ix = x1; + iy = y1; + /* Set floating point coordinates. */ + rx = (double)x1; + ry = (double)y1; + + /* Initialize to first point in line segment. */ + i = 0; + + /* Assign first point into coordinate list. */ + x_list[i] = x1; + y_list[i++] = y1; + + while((ix != x2) || (iy != y2)){ + + if(i >= asize){ + fprintf(stderr, "ERROR : line_points : coord list overflow\n"); + free(x_list); + free(y_list); + return(-412); + } + + rx += x_factor; + ry += y_factor; + + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when truncating doubles. */ + rx = trunc_dbl_precision(rx, TRUNC_SCALE); + ry = trunc_dbl_precision(ry, TRUNC_SCALE); + + /* Compute new x and y-pixel coords in floating point and */ + /* then round to the nearest integer. */ + ix = (intx * (ix + x_incr)) + (iny * (int)(rx + 0.5)); + iy = (inty * (iy + y_incr)) + (inx * (int)(ry + 0.5)); + + /* Assign first point into coordinate list. */ + x_list[i] = ix; + y_list[i++] = iy; + } + + /* Set output pointers. */ + *ox_list = x_list; + *oy_list = y_list; + *onum = i; + + /* Return normally. */ + return(0); +} diff --git a/libfprint/nbis/mindtct/link.c b/libfprint/nbis/mindtct/link.c new file mode 100644 index 00000000..2a864528 --- /dev/null +++ b/libfprint/nbis/mindtct/link.c @@ -0,0 +1,1238 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: LINK.C + AUTHOR: Michael D. Garris + DATE: 08/02/1999 + UPDATED: 10/04/1999 Version 2 by MDG + UPDATED: 03/16/2005 by MDG + + Contains routines responsible for linking compatible minutiae + together as part of the NIST Latent Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + link_minutiae() + create_link_table() + update_link_table() + order_link_table() + process_link_table() + link_score() +***********************************************************************/ + +#include +#include +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: link_minutiae - Clusters minutiae that are sufficiently close to each +#cat: other and have compatible directions to be considered part +#cat: of the same ridge or valley and then links them together. +#cat: In linking two minutia, the respective minutia features +#cat: in the image are joined by drawing pixels and the points +#cat: are removed from the list. + + Input: + minutiae - list of true and false minutiae + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + nmap - IMAP ridge flow matrix with invalid, high-curvature, + and no-valid-neighbor regions identified + mw - width in blocks of the NMAP + mh - height in blocks of the NMAP + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of pruned minutiae + bdata - edited binary image with breaks in ridges and valleys filled + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int link_minutiae(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + int *nmap, const int mw, const int mh, + const LFSPARMS *lfsparms) +{ + int i, ret, *onloop; + MINUTIA *main_min; /* Renamed by MDG on 03-16-05 */ + int main_x, main_y; + int *link_table, *x_axis, *y_axis, nx_axis, ny_axis, n_entries; + + print2log("\nLINKING MINUTIA:\n"); + + /* Go through the list of minutiae and detect any small loops (ex. */ + /* < 15 pixels in circumference), and remove any minutiae */ + /* (bifurcations) with bad contours. */ + if((ret = get_loop_list(&onloop, minutiae, lfsparms->small_loop_len, + bdata, iw, ih))) + return(ret); + + i = 0; + /* Foreach minutia treated as a "main" minutia */ + /* (except for the very last one) ... */ + while(i < minutiae->num-1){ + + /* Set current minutia to "main" minutia. */ + main_min = minutiae->list[i]; + main_x = main_min->x; + main_y = main_min->y; + + /* If the main minutia is NOT on a small loop ... */ + if(!onloop[i]){ + + /* Then minutia is a ridge-ending OR a bifurcation */ + /* which is NOT to be skipped ... */ + + /* We now want to build a connected graph (link table) of */ + /* all those minutiae sufficiently close and complementing */ + /* each other that they potentially could be merged (linked) */ + /* together. (Ex. table has max dimensions of 20). */ + if((ret = create_link_table(&link_table, &x_axis, &y_axis, + &nx_axis, &ny_axis, &n_entries, + lfsparms->link_table_dim, + i, minutiae, onloop, nmap, mw, mh, + bdata, iw, ih, lfsparms))){ + /* Deallocate working memory. */ + free(onloop); + /* Return error code. */ + return(ret); + } + + /* Put the link table in sorted order based on x and then y-axis */ + /* entries. These minutia are sorted based on their point of */ + /* perpendicular intersection with a line running from the origin */ + /* at an angle equal to the average direction of all entries in */ + /* the link table. */ + if((ret = order_link_table(link_table, x_axis, y_axis, + nx_axis, ny_axis, n_entries, + lfsparms->link_table_dim, minutiae, + lfsparms->num_directions))){ + /* Deallocate working memories. */ + free(link_table); + free(x_axis); + free(y_axis); + free(onloop); + /* Return error code. */ + return(ret); + } + + /* Process the link table deciding which minutia pairs in */ + /* the table should be linked (ie. joined in the image and */ + /* removed from the minutiae list (and from onloop). */ + if((ret = process_link_table(link_table, x_axis, y_axis, + nx_axis, ny_axis, n_entries, + lfsparms->link_table_dim, + minutiae, onloop, bdata, iw, ih, lfsparms))){ + /* Deallocate working memories. */ + free(link_table); + free(x_axis); + free(y_axis); + free(onloop); + /* Return error code. */ + return(ret); + } + + /* Deallocate link table buffers. */ + free(link_table); + free(x_axis); + free(y_axis); + } + /* Otherwise, skip minutia on a small loop. */ + + /* Check to see if the current "main" minutia has been removed */ + /* from the minutiae list. If it has not, then we need to */ + /* advance to the next minutia in the list. If it has been */ + /* removed, then we are pointing to the next minutia already. */ + if((minutiae->list[i]->x == main_x) && + (minutiae->list[i]->y == main_y)) + /* Advance to the next main feature in the list. */ + i++; + + /* At this point 'i' is pointing to the next main minutia to be */ + /* processed, so continue. */ + } + + free(onloop); + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: create_link_table - Builds a 2D minutia link table where each cell in the +#cat: table represents a potential linking of 2 different +#cat: minutia points. Minutia IDs are stored on each axes +#cat: and scores representing the degree of compatibility +#cat: between 2 minutia are stored in each cell. Note that +#cat: the table is sparsely filled with scores. + + Input: + tbldim - dimension of each axes of the link table + start - index position of starting minutia point in input list + minutiae - list of minutia + onloop - list of loop flags (on flag for each minutia point in list) + nmap - IMAP ridge flow matrix with invalid, high-curvature, + and no-valid-neighbor regions identified + mw - width in blocks of the NMAP + mh - height in blocks of the NMAP + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + lfsparms - parameters and thresholds for controlling LFS + Output: + olink_table - sparse 2D table containing scores of potentially + linked minutia pairs + ox_axis - minutia IDs registered along x-axis + oy_axis - minutia IDs registered along y-axis + onx_axis - number of minutia registered along x-axis + ony_axis - number of minutia registered along y-axis + on_entries - number of scores currently entered in the table + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int create_link_table(int **olink_table, int **ox_axis, int **oy_axis, + int *onx_axis, int *ony_axis, int *on_entries, const int tbldim, + const int start, const MINUTIAE *minutiae, const int *onloop, + int *nmap, const int mw, const int mh, + unsigned char *bdata, const int iw, const int ih, + const LFSPARMS *lfsparms) +{ + int ret, first, second; + int full_ndirs, qtr_ndirs, half_ndirs, low_curve_min_deltadir, deltadir; + int *link_table, *x_axis, *y_axis, nx_axis, ny_axis, n_entries, tblalloc; + int *queue, *inqueue, head, tail; + MINUTIA *minutia1, *minutia2; + int xblk, yblk; + int nmapval, opp1dir, joindir, iscore; + double jointheta, joindist, dscore; + + /* Compute number of directions on full circle. */ + full_ndirs = lfsparms->num_directions<<1; + /* Compute number of directions in 45=(180/4) degrees. */ + qtr_ndirs = lfsparms->num_directions>>2; + /* Compute number of directions in 90=(180/2) degrees. */ + half_ndirs = lfsparms->num_directions>>1; + + /* Minimum allowable deltadir to link minutia in low-curvature region. */ + /* (The closer the deltadir is to 180 degrees, the more likely the link. */ + /* When ndirs==16, then this value is 11=(3*4)-1 == 123.75 degrees. */ + /* I chose to parameterize this threshold based on a fixed fraction of */ + /* 'ndirs' rather than on passing in a parameter in degrees and doing */ + /* the conversion. I doubt the difference matters. */ + low_curve_min_deltadir = (3 * qtr_ndirs) - 1; + + /* Allocate and initialize link table buffers. */ + /* Note: The use of "calloc" initializes all table values to 0. */ + tblalloc = tbldim * tbldim; + link_table = (int *)calloc(tblalloc, sizeof(int)); + if(link_table == (int *)NULL){ + fprintf(stderr, "ERROR : create_link_table : calloc : link_table\n"); + return(-330); + } + /* Allocate horizontal axis entries in table. */ + x_axis = (int *)malloc(tbldim * sizeof(int)); + if(x_axis == (int *)NULL){ + free(link_table); + fprintf(stderr, "ERROR : create_link_table : malloc : x_axis\n"); + return(-331); + } + /* Allocate vertical axis entries in table. */ + y_axis = (int *)malloc(tbldim * sizeof(int)); + if(y_axis == (int *)NULL){ + free(link_table); + free(x_axis); + fprintf(stderr, "ERROR : create_link_table : malloc : y_axis\n"); + return(-332); + } + nx_axis = 0; + ny_axis = 0; + n_entries = 0; + + /* Allocate and initalize queue buffers. As minutia are entered into */ + /* the link table they are placed in the queue for subsequent matching. */ + queue = (int *)malloc(minutiae->num * sizeof(int)); + if(queue == (int *)NULL){ + free(link_table); + free(x_axis); + free(y_axis); + fprintf(stderr, "ERROR : create_link_table : malloc : queue\n"); + return(-333); + } + /* List of flags to indicate if a manutia has been entered in the queue. */ + /* Once a minutia "in queue" status is set to TRUE it will not be reset. */ + /* This way a minutia will only ever be processed as a primary minutia */ + /* once when builing the link table. Note that the calloc() initializes */ + /* the flags to FALSE (as the queue is initially empty). */ + inqueue = (int *)calloc(minutiae->num, sizeof(int)); + if(inqueue == (int *)NULL){ + free(link_table); + free(x_axis); + free(y_axis); + free(queue); + fprintf(stderr, "ERROR : create_link_table : calloc : inqueue\n"); + return(-334); + } + /* Initialize head and tail to start of queue. */ + head = 0; + tail = 0; + + /* Push the index of the "main" manutia point onto the queue. */ + queue[tail++] = start; + /* Set "main" minutia inqueue flag to TRUE. */ + inqueue[start] = TRUE; + + print2log("BUILD TABLE:\n"); + + /* While the queue is NOT empty ... */ + while(head != tail){ + /* Pop the next manutia point from the queue and refer to it as */ + /* the primary (first) minutia. */ + first = queue[head++]; + minutia1 = minutiae->list[first]; + + /* Look for those minutia points that potentially match the */ + /* "first" minutia and add them to the link table. These */ + /* potentially matching minutia are secondary and refered to */ + /* as the "second" minutia. Always restart the search at the */ + /* original "main" manutia. */ + second = start+1; + + /* While secondary manutae remain to be matched to the current */ + /* first minutia... */ + while(second < minutiae->num){ + /* Assign second minutia to temporary pointer. */ + minutia2 = minutiae->list[second]; + + print2log("1:%d(%d,%d)%d 2:%d(%d,%d)%d ", + first, minutia1->x, minutia1->y, minutia1->type, + second, minutia2->x, minutia2->y, minutia2->type); + + /* 1. If y-delta from second to first minutia is small (ex. */ + /* <= 20 pixels) ... */ + if((minutia2->y - minutia1->y) <= lfsparms->max_link_dist){ + + print2log("1DY "); + + + /* 2. If first and second minutia are not the same point ... */ + /* (Remeber that the search for matching seconds starts */ + /* all the way back to the starting "main" minutia.) */ + if(first != second){ + + print2log("2NE "); + + /* 3. If first and second minutia are the same type ... */ + if(minutia1->type == minutia2->type){ + + print2log("3TP "); + + /* 4. If |x-delta| between minutiae is small (ex. <= */ + /* 20 pixels) ... */ + if(abs(minutia1->x - minutia2->x) <= + lfsparms->max_link_dist){ + + print2log("4DX "); + + /* 5. If second minutia is NOT on a small loop ... */ + if(!onloop[second]){ + + print2log("5NL "); + + /* The second minutia is ridge-ending OR a */ + /* bifurcation NOT to be skipped ... */ + + /* Compute the "inner" distance between the */ + /* first and second minutia's directions. */ + deltadir = closest_dir_dist(minutia1->direction, + minutia2->direction, full_ndirs); + /* If the resulting direction is INVALID */ + /* (this should never happen, but just in case)... */ + if(deltadir == INVALID_DIR){ + free(link_table); + free(x_axis); + free(y_axis); + free(queue); + free(inqueue); + /* Then there is a problem. */ + fprintf(stderr, + "ERROR : create_link_table : INVALID direction\n"); + return(-335); + } + + /* Compute first minutia's block coords from */ + /* its pixel coords. */ + xblk = minutia1->x/lfsparms->blocksize; + yblk = minutia1->y/lfsparms->blocksize; + /* Get corresponding block's NMAP value. */ + /* -3 == NO_VALID_NBRS */ + /* -2 == HIGH_CURVATURE */ + /* -1 == INVALID_DIR */ + /* 0 <= VALID_DIR */ + nmapval = *(nmap+(yblk*mw)+xblk); + /* 6. CASE I: If block has VALID_DIR and deltadir */ + /* relatively close to 180 degrees (at */ + /* least 123.75 deg when ndirs==16)... */ + /* OR */ + /* CASE II: If block is HIGH_CURVATURE and */ + /* deltadir is at least 45 degrees... */ + if(((nmapval >= 0) && + (deltadir >= low_curve_min_deltadir)) || + ((nmapval == HIGH_CURVATURE) && + (deltadir >= qtr_ndirs))){ + + print2log("6DA "); + + /* Then compute direction of "joining" vector. */ + /* First, compute direction of line from first */ + /* to second minutia points. */ + joindir = line2direction(minutia1->x, minutia1->y, + minutia2->x, minutia2->y, + lfsparms->num_directions); + + /* Comptue opposite direction of first minutia. */ + opp1dir = (minutia1->direction+ + lfsparms->num_directions)%full_ndirs; + /* Take "inner" distance on full circle between */ + /* the first minutia's opposite direction and */ + /* the joining direction. */ + joindir = abs(opp1dir - joindir); + joindir = min(joindir, full_ndirs - joindir); + /* 7. If join angle is <= 90 deg... */ + if(joindir <= half_ndirs){ + + print2log("7JA "); + + /* Convert integer join direction to angle */ + /* in radians on full circle. Multiply */ + /* direction by (2PI)/32==PI/16 radians per */ + /* unit direction and you get radians. */ + jointheta = joindir * + (M_PI/(double)lfsparms->num_directions); + /* Compute squared distance between frist */ + /* and second minutia points. */ + joindist = distance(minutia1->x, minutia1->y, + minutia2->x, minutia2->y); + /* 8. If the 2 minutia points are close enough */ + /* (ex. thresh == 20 pixels)... */ + if(joindist <= lfsparms->max_link_dist){ + + print2log("8JD "); + + /* 9. Does a "free path" exist between the */ + /* 2 minutia points? */ + if(free_path(minutia1->x, minutia1->y, + minutia2->x, minutia2->y, + bdata, iw, ih, lfsparms)){ + + print2log("9FP "); + + /* If the join distance is very small, */ + /* join theta will be unreliable, so set */ + /* join theta to zero. */ + /* (ex. thresh == 5 pixels)... */ + if(joindist < lfsparms->min_theta_dist) + /* Set the join theta to zero. */ + jointheta = 0.0; + /* Combine the join theta and distance */ + /* to compute a link score. */ + dscore = link_score(jointheta, joindist, + lfsparms); + /* Round off the floating point score. */ + /* Need to truncate so answers are same */ + /* on different computers. */ + dscore = trunc_dbl_precision(dscore, + TRUNC_SCALE); + iscore = sround(dscore); + /* Add minutia pair and their link score */ + /* to the Link Table. */ + + if(iscore > 0){ + print2log("UPDATE"); + + if((ret = update_link_table(link_table, + x_axis, y_axis, &nx_axis, &ny_axis, + &n_entries, tbldim, + queue, &head, &tail, inqueue, + first, second, iscore))){ + /* If update ERROR, deallocate */ + /* working memories. */ + free(link_table); + free(x_axis); + free(y_axis); + free(queue); + free(inqueue); + return(ret); + } + } /* Else score is <= 0, so skip second. */ + } /* 9. Else no free path, so skip second. */ + } /* 8. Else joindist too big, so skip second. */ + } /* 7. Else joindir is too big, so skip second. */ + } /* 6. Else INVALID DIR or deltadir too small, */ + /* so skip second. */ + } /* 5. Else second minutia on small loop, so skip it. */ + } /* 4. Else X distance too big, so skip second. */ + } /* 3. Else first and second NOT same type, so skip second. */ + } /* 2. Else first and second ARE same point, so skip second. */ + + /* If we get here, we want to advance to the next secondary. */ + second++; + + print2log("\n"); + + + } + /* 1. Otherwise, Y distnace too big, so we are done searching for */ + /* secondary matches to the current frist minutia. It is time */ + /* to take the next minutia in the queue and begin matching */ + /* secondaries to it. */ + else{ + + print2log("\n"); + + /* So, break out of the secondary minutiae while loop. */ + break; + } + } + /* Done matching current first minutia to secondaries. */ + } + /* Get here when queue is empty, and we have our complete link table. */ + + /* Deallocate working memories. */ + free(queue); + free(inqueue); + + /* Assign link table buffers and attributes to output pointers. */ + *olink_table = link_table; + *ox_axis = x_axis; + *oy_axis = y_axis; + *onx_axis = nx_axis; + *ony_axis = ny_axis; + *on_entries = n_entries; + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: update_link_table - Takes the indices of 2 minutia and their link +#cat: compatibility score and updates the 2D link table. +#cat: The input minutia are registered to positions along +#cat: different axes, if they are not already in the table, +#cat: and a queue is maintained so that a cluster of +#cat: potentially linked points may be gathered. + + Input: + link_table - sparse 2D table containing scores of potentially linked + minutia pairs + x_axis - minutia IDs registered along x-axis + y_axis - minutia IDs registered along y-axis + nx_axis - number of minutia registered along x-axis + ny_axis - number of minutia registered along y-axis + n_entries - number of scores currently entered in the table + tbldim - dimension of each axes of the link table + queue - list of clustered minutiae yet to be used to locate + other compatible minutiae + head - head of the queue + tail - tail of the queue + inqueue - flag for each minutia point in minutiae list to signify if + it has been clustered with the points in this current link + table + first - index position of first minutia of current link pair + second - index position of second minutia of current link pair + score - degree of link compatibility of current link pair + Output: + link_table - updated sparse 2D table containing scores of potentially + linked minutia pairs + x_axis - updated minutia IDs registered along x-axis + y_axis - updated minutia IDs registered along y-axis + nx_axis - updated number of minutia registered along x-axis + ny_axis - updated number of minutia registered along y-axis + n_entries - updated number of scores currently entered in the table + queue - updated list of clustered minutiae yet to be used to locate + other compatible minutiae + tail - updated tail of the queue + inqueue - updated list of flags, one for each minutia point in + minutiae list to signify if it has been clustered with + the points in this current link table + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int update_link_table(int *link_table, int *x_axis, int *y_axis, + int *nx_axis, int *ny_axis, int *n_entries, const int tbldim, + int *queue, int *head, int *tail, int *inqueue, + const int first, const int second, const int score) +{ + int x, y, *tptr; + + /* If the link table is empty. */ + if(*n_entries == 0){ + /* Add first and second minutia to the table. */ + + /* If horizontal axis of table is full ... */ + if(*nx_axis >= tbldim) + /* Then ignore the minutia pair and return normally. */ + return(0); + /* Add first minutia to horizontal axis. */ + x_axis[*nx_axis] = first; + + /* If vertical axis of table is full ... */ + if(*ny_axis >= tbldim) + /* Then ignore the minutia pair and return normally. */ + return(0); + /* Add second minutia to vertical axis. */ + y_axis[*ny_axis] = second; + + /* Enter minutia pair score to the link table. */ + tptr = link_table + ((*ny_axis)*tbldim) + (*nx_axis); + *tptr = score; + (*n_entries)++; + + /* Bump number of entries in each axis. */ + (*nx_axis)++; + (*ny_axis)++; + + /* Add second minutia to queue (if not already in queue), so it */ + /* can be processed to see who might link to it. */ + if(!inqueue[second]){ + queue[*tail] = second; + (*tail)++; + inqueue[second] = TRUE; + } + + /* Done, so return normally. */ + return(0); + } + + /* We are filling in the table with a "faimily" or "cluster" of */ + /* potentially inter-linked points. Once the first entry is */ + /* made in the table, all subsequent updates will be based on */ + /* at least the first minutia already being in the table. */ + + /* If first minutia already stored in horizontal axis */ + /* of the link table. */ + if((x = in_int_list(first, x_axis, *nx_axis)) >= 0){ + /* If second minutia already stored in vertical axis */ + /* of the link table. */ + if((y = in_int_list(second, y_axis, *ny_axis)) >= 0){ + /* Entry may not be set or the new score may be larger. */ + tptr = link_table + (y*tbldim) + x; + if(*tptr == 0) + /* Assign the minutia pair score to the table. */ + *tptr = score; + + } + /* Otherwise, second minutia not in vertical axis of link table. */ + else{ + /* Add the second minutia to the vertical axis and */ + /* the minutia pair's score to the link table. */ + + /* If vertical axis of table is full ... */ + if(*ny_axis >= tbldim) + /* Then ignore the minutia pair and return normally. */ + return(0); + /* Add second minutia to vertical axis. */ + y_axis[*ny_axis] = second; + + /* Enter minutia pair score to the link table. */ + tptr = link_table + ((*ny_axis)*tbldim) + x; + *tptr = score; + (*n_entries)++; + + /* Bump number of entries in vertical axis. */ + (*ny_axis)++; + + /* Add second minutia to queue (if not already in queue), so it */ + /* can be processed to see who might link to it. */ + if(!inqueue[second]){ + queue[*tail] = second; + (*tail)++; + inqueue[second] = TRUE; + } + } + } + /* Otherwise, first minutia not in horizontal axis of link table. */ + else{ + /* If first minutia already stored in vertical axis */ + /* of the link table. */ + if((y = in_int_list(first, y_axis, *ny_axis)) >= 0){ + /* If second minutia already stored in horizontal axis */ + /* of the link table. */ + if((x = in_int_list(second, x_axis, *nx_axis)) >= 0){ + /* Entry may not be set or the new score may be larger. */ + tptr = link_table + (y*tbldim) + x; + if(*tptr == 0) + /* Assign the minutia pair score to the table. */ + *tptr = score; + } + /* Otherwise, second minutia not in horizontal axis of link table. */ + else{ + /* Add the second minutia to the horizontal axis and */ + /* the minutia pair's score to the link table. */ + + /* If horizontal axis of table is full ... */ + if(*nx_axis >= tbldim) + /* Then ignore the minutia pair and return normally. */ + return(0); + /* Add second minutia to vertical axis. */ + x_axis[*nx_axis] = second; + + /* Enter minutia pair score to the link table. */ + tptr = link_table + (y*tbldim) + (*nx_axis); + *tptr = score; + (*n_entries)++; + + /* Bump number of entries in horizontal axis. */ + (*nx_axis)++; + + /* Add second minutia to queue (if not already in queue), so it */ + /* can be processed to see who might link to it. */ + if(!inqueue[second]){ + queue[*tail] = second; + (*tail)++; + inqueue[second] = TRUE; + } + } + } + /* Otherwise, first minutia not in vertical or horizontal axis of */ + /* link table. This is an error, as this should only happen upon */ + /* the first point being entered, which is already handled above. */ + else{ + fprintf(stderr, + "ERROR : update_link_table : first minutia not found in table\n"); + return(-340); + } + } + + /* Done, so return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: order_link_table - Puts the link table in sorted order based on x and +#cat: then y-axis entries. These minutia are sorted based +#cat: on their point of perpendicular intersection with a +#cat: line running from the origin at an angle equal to the +#cat: average direction of all entries in the link table. + + Input: + link_table - sparse 2D table containing scores of potentially linked + minutia pairs + x_axis - minutia IDs registered along x-axis + y_axis - minutia IDs registered along y-axis + nx_axis - number of minutia registered along x-axis + ny_axis - number of minutia registered along y-axis + n_entries - number of scores currently entered in the table + tbldim - dimension of each axes of the link table + minutiae - list of minutia + ndirs - number of IMAP directions (in semicircle) + Output: + link_table - sorted sparse 2D table containing scores of potentially + linked minutia pairs + x_axis - sorted minutia IDs registered along x-axis + y_axis - sorted minutia IDs registered along y-axis + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int order_link_table(int *link_table, int *x_axis, int *y_axis, + const int nx_axis, const int ny_axis, const int n_entries, + const int tbldim, const MINUTIAE *minutiae, + const int ndirs) +{ + int i, j, ret, sumdir, avrdir, *order; + double davrdir, avrtheta, pi_factor, cs, sn; + double *dlist; + MINUTIA *minutia; + int *tlink_table, *tx_axis, *ty_axis, tblalloc; + int *toptr, *frptr; + + /* If the table is empty or if there is only one horizontal or */ + /* vertical entry in the table ... */ + if((nx_axis <= 1) || (ny_axis <= 1)) + /* Then don't reorder the table, just return normally. */ + return(0); + + /* Compute average direction (on semi-circle) of all minutia entered */ + /* in the link table. This gives an average ridge-flow direction */ + /* among all the potentially linked minutiae in the table. */ + + /* Initialize direction accumulator to 0. */ + sumdir = 0; + + /* Accumulate directions (on semi-circle) of minutia entered in the */ + /* horizontal axis of the link table. */ + for(i = 0; i < nx_axis; i++) + sumdir += (minutiae->list[x_axis[i]]->direction % ndirs); + + /* Accumulate directions of minutia entered in the vertical axis */ + /* of the link table. */ + for(i = 0; i < ny_axis; i++) + sumdir += (minutiae->list[y_axis[i]]->direction % ndirs); + + /* Compute the average direction and round off to integer. */ + davrdir = (sumdir / (double)(nx_axis + ny_axis)); + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + davrdir = trunc_dbl_precision(davrdir, TRUNC_SCALE); + avrdir = sround(davrdir); + + /* Conversion factor from integer directions to radians. */ + pi_factor = M_PI / (double)ndirs; + + /* Compute sine and cosine of average direction in radians. */ + avrtheta = avrdir*pi_factor; + sn = sin(avrtheta); + cs = cos(avrtheta); + + /* Allocate list to hold distances to be sorted on. */ + dlist = (double *)malloc(tbldim * sizeof(double)); + if(dlist == (double *)NULL){ + fprintf(stderr, "ERROR : order_link_table : malloc : dlist\n"); + return(-350); + } + + /* Allocate and initialize temporary link table buffers. */ + tblalloc = tbldim * tbldim; + tlink_table = (int *)calloc(tblalloc, sizeof(int)); + if(tlink_table == (int *)NULL){ + free(dlist); + fprintf(stderr, "ERROR : order_link_table : calloc : tlink_table\n"); + return(-351); + } + tx_axis = (int *)malloc(tbldim * sizeof(int)); + if(tx_axis == (int *)NULL){ + free(dlist); + free(tlink_table); + fprintf(stderr, "ERROR : order_link_table : malloc : tx_axis\n"); + return(-352); + } + ty_axis = (int *)malloc(tbldim * sizeof(int)); + if(ty_axis == (int *)NULL){ + free(dlist); + free(tlink_table); + free(tx_axis); + fprintf(stderr, "ERROR : order_link_table : malloc : ty_axis\n"); + return(-353); + } + + /* Compute distance measures for each minutia entered in the */ + /* horizontal axis of the link table. */ + /* The measure is: dist = X*cos(avrtheta) + Y*sin(avrtheta) */ + /* which measures the distance from the origin along the line */ + /* at angle "avrtheta" to the point of perpendicular inter- */ + /* section from the point (X,Y). */ + + /* Foreach minutia in horizontal axis of the link table ... */ + for(i = 0; i < nx_axis; i++){ + minutia = minutiae->list[x_axis[i]]; + dlist[i] = (minutia->x * cs) + (minutia->y * sn); + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + dlist[i] = trunc_dbl_precision(dlist[i], TRUNC_SCALE); + } + + /* Get sorted order of distance for minutiae in horizontal axis. */ + if((ret = sort_indices_double_inc(&order, dlist, nx_axis))){ + free(dlist); + return(ret); + } + + /* Store entries on y_axis into temporary list. */ + memcpy(ty_axis, y_axis, ny_axis * sizeof(int)); + + /* For each horizontal entry in link table ... */ + for(i = 0; i < nx_axis; i++){ + /* Store next minutia in sorted order to temporary x_axis. */ + tx_axis[i] = x_axis[order[i]]; + /* Store corresponding column of scores into temporary table. */ + frptr = link_table + order[i]; + toptr = tlink_table + i; + for(j = 0; j < ny_axis; j++){ + *toptr = *frptr; + toptr += tbldim; + frptr += tbldim; + } + } + + /* Deallocate sorted order of distance measures. */ + free(order); + + /* Compute distance measures for each minutia entered in the */ + /* vertical axis of the temporary link table (already sorted */ + /* based on its horizontal axis entries. */ + + /* Foreach minutia in vertical axis of the link table ... */ + for(i = 0; i < ny_axis; i++){ + minutia = minutiae->list[y_axis[i]]; + dlist[i] = (minutia->x * cs) + (minutia->y * sn); + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + dlist[i] = trunc_dbl_precision(dlist[i], TRUNC_SCALE); + } + + /* Get sorted order of distance for minutiae in vertical axis. */ + if((ret = sort_indices_double_inc(&order, dlist, ny_axis))){ + free(dlist); + return(ret); + } + + /* Store entries in temporary x_axis. */ + memcpy(x_axis, tx_axis, nx_axis * sizeof(int)); + + /* For each vertical entry in the temporary link table ... */ + for(i = 0; i < ny_axis; i++){ + /* Store next minutia in sorted order to y_axis. */ + y_axis[i] = ty_axis[order[i]]; + /* Store corresponding row of scores into link table. */ + frptr = tlink_table + (order[i] * tbldim); + toptr = link_table + (i * tbldim); + for(j = 0; j < nx_axis; j++){ + *toptr++ = *frptr++; + } + } + + /* Deallocate sorted order of distance measures. */ + free(order); + + /* Link table is now sorted on x and y axes. */ + /* Deallocate the working memories. */ + free(dlist); + free(tlink_table); + free(tx_axis); + free(ty_axis); + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: process_link_table - Processes the link table deciding which minutia +#cat: pairs in the table should be linked (ie. joined in +#cat: the image and removed from the minutiae list (and +#cat: from onloop). + + Input: + link_table - sparse 2D table containing scores of potentially linked + minutia pairs + x_axis - minutia IDs registered along x-axis + y_axis - minutia IDs registered along y-axis + nx_axis - number of minutia registered along x-axis + ny_axis - number of minutia registered along y-axis + n_entries - number of scores currently entered in the table + tbldim - dimension of each axes of the link table + minutiae - list of minutia + onloop - list of flags signifying which minutia lie on small lakes + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of pruned minutiae + onloop - updated loop flags + bdata - edited image with minutia features joined + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int process_link_table(const int *link_table, + const int *x_axis, const int *y_axis, + const int nx_axis, const int ny_axis, const int n_entries, + const int tbldim, MINUTIAE *minutiae, int *onloop, + unsigned char *bdata, const int iw, const int ih, + const LFSPARMS *lfsparms) +{ + int i, j, ret, first, second; + MINUTIA *minutia1, *minutia2; + int rm1, rm2; + int *to_remove; + int n_lines, line_len, entry_incr, line_incr; + int line_i, entry_i; + int start, end; + int max_v, max_tbl_i, max_line_i, max_x, max_y; + + + print2log("LINKING FROM TABLE:\n"); + + /* If link table is empty, just return normally. */ + if(n_entries == 0) + return(0); + + /* If there is only 1 entry in the table, then join the minutia pair. */ + if(n_entries == 1){ + /* Join the minutia pair in the image. */ + first = x_axis[0]; + second = y_axis[0]; + minutia1 = minutiae->list[first]; + minutia2 = minutiae->list[second]; + + /* Connect the points with a line with specified radius (ex. 1 pixel). */ + if((ret = join_minutia(minutia1, minutia2, bdata, iw, ih, + WITH_BOUNDARY, lfsparms->join_line_radius))) + return(ret); + + /* Need to remove minutiae from onloop first, as onloop is dependent */ + /* on the length of the minutiae list. We also need to remove the */ + /* highest index from the lists first or the indices will be off. */ + if(first > second){ + rm1 = first; + rm2 = second; + } + else{ + rm1 = second; + rm2 = first; + } + if((ret = remove_from_int_list(rm1, onloop, minutiae->num))) + return(ret); + if((ret = remove_from_int_list(rm2, onloop, minutiae->num-1))) + return(ret); + + /* Now, remove the minutia from the minutiae list. */ + if((ret = remove_minutia(rm1, minutiae))) + return(ret); + if((ret = remove_minutia(rm2, minutiae))) + return(ret); + + /* Return normally. */ + return(0); + } + + /* Otherwise, we need to make decisions as to who links to who. */ + + /* Allocate list of minutia indices that upon completion of linking */ + /* should be removed from the onloop and minutiae lists. Note: That */ + /* using "calloc" initializes the list to FALSE. */ + to_remove = (int *)calloc(minutiae->num, sizeof(int)); + if(to_remove == (int *)NULL){ + fprintf(stderr, "process_link_table : calloc : to_remove\n"); + return(-360); + } + + /* If the number of horizontal entries is <= vertical entries ... */ + if(nx_axis <= ny_axis){ + /* Process columns in table as lines. */ + n_lines = nx_axis; + /* Set length of each line to number of vertical entries. */ + line_len = ny_axis; + /* Increment down column to next entry in line. */ + entry_incr = tbldim; + /* Increment across row to next line. */ + line_incr = 1; + } + /* Otherwise, the number of vertical entreis < horizontal entries ... */ + else{ + /* Process rows in table as lines. */ + n_lines = ny_axis; + /* Set length of each line to number of horizontal entries. */ + line_len = nx_axis; + /* Increment across row to next entry in line. */ + entry_incr = 1; + /* Increment down column to next line. */ + line_incr = tbldim; + } + + /* Set start of next line index to origin of link table. */ + line_i = 0; + + /* Initialize the search limits for the line ... */ + start = 0; + end = line_len - n_lines + 1; + + /* Foreach line in table ... */ + for(i = 0; i < n_lines; i++){ + + /* Find max score in the line given current search limits. */ + + /* Set table entry index to start of next line. */ + entry_i = line_i; + + /* Initialize running maximum with score in current line */ + /* at offset 'start'. */ + entry_i += (start*entry_incr); + + /* Set running maximum score. */ + max_v = link_table[entry_i]; + /* Set table index of maximum score. */ + max_tbl_i = entry_i; + /* Set line index of maximum score. */ + max_line_i = start; + + /* Advance table entry index along line. */ + entry_i += entry_incr; + /* Foreach successive entry in line up to line index 'end' ... */ + + for(j = start+1; j < end; j++){ + /* If current entry > maximum score seen so far ... */ + if(link_table[entry_i] >= max_v){ + /* Store current entry as new maximum. */ + max_v = link_table[entry_i]; + max_tbl_i = entry_i; + max_line_i = j; + } + /* Advance table entry index along line. */ + entry_i += entry_incr; + } + + /* Convert entry index at maximum to table row and column indices. */ + max_x = max_tbl_i % tbldim; + max_y = max_tbl_i / tbldim; + + /* Set indices and pointers corresponding to minutia pair */ + /* with maximum score this pass. */ + first = x_axis[max_x]; + second = y_axis[max_y]; + minutia1 = minutiae->list[first]; + minutia2 = minutiae->list[second]; + + /* Check to make sure the the maximum score found in the current */ + /* line is > 0 (just to be safe) AND */ + /* If a "free path" exists between minutia pair ... */ + if( /* (max_v >0) && */ + free_path(minutia1->x, minutia1->y, minutia2->x, minutia2->y, + bdata, iw, ih, lfsparms)){ + + print2log("%d,%d to %d,%d LINK\n", + minutia1->x, minutia1->y, minutia2->x, minutia2->y); + + /* Join the minutia pair in the image. */ + if((ret = join_minutia(minutia1, minutia2, bdata, iw, ih, + WITH_BOUNDARY, lfsparms->join_line_radius))){ + free(to_remove); + return(ret); + } + + /* Set remove flags for minutia pair. A minutia point may */ + /* be linked to more than one other minutia in this process */ + /* so, just flag them to be removed for now and actually */ + /* conduct the removal after all linking is complete. */ + to_remove[first] = TRUE; + to_remove[second] = TRUE; + + } + /* Set starting line index to one passed maximum found this pass. */ + start = max_line_i + 1; + /* Bump ending line index. */ + end++; + + /* Advance start of line index to next line. */ + line_i += line_incr; + + } /* End for lines */ + + /* Now that all linking from the current table is complete, */ + /* remove any linked minutia from the onloop and minutiae lists. */ + /* NOTE: Need to remove the minutia from their lists in reverse */ + /* order, otherwise, indices will be off. */ + for(i = minutiae->num-1; i >= 0; i--){ + /* If the current minutia index is flagged for removal ... */ + if(to_remove[i]){ + /* Remove the minutia from the onloop list before removing */ + /* from minutiae list as the length of onloop depends on the */ + /* length of the minutiae list. */ + if((ret = remove_from_int_list(i, onloop, minutiae->num))){ + free(to_remove); + return(ret); + } + /* Now, remove the minutia from the minutiae list. */ + if((ret = remove_minutia(i, minutiae))){ + free(to_remove); + return(ret); + } + } + } + + /* Deallocate remove list. */ + free(to_remove); + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: link_score - Takes 2 parameters, a 'join angle' and a 'join distance' +#cat: computed between 2 minutia and combines these to compute +#cat: a score representing the degree of link compatibility +#cat: between the 2 minutiae. + + Input: + jointheta - angle measured between 2 minutiae + joindist - distance between 2 minutiae + lfsparms - parameters and thresholds for controlling LFS + Return Code: + Score - degree of link compatibility +**************************************************************************/ +double link_score(const double jointheta, const double joindist, + const LFSPARMS *lfsparms) +{ + double score, theta_factor, dist_factor; + + /* Calculates a weighted score between the distance between the 1st & */ + /* 2nd features and the delta angle between the reflected 1st feature */ + /* and the "joining" vector to the 2nd feature. */ + /* */ + /* SCORE_NUMERATOR */ + /* SCORE = ------------------------------------------ */ + /* THETA_FACTOR * DIST_FACTOR */ + /* */ + /* THETA_FACTOR = exp((jointheta/SCORE_THETA_NORM)^2) */ + /* DIST_FACTOR = (1+exp(((joindist/SCORE_DIST_NORM)-1) */ + /* *SCORE_DIST_WEIGHT)) */ + /* */ + /* For example: */ + /* SCORE_NUMERATOR = 32000.0 */ + /* SCORE_THETA_NORM = 15.0*(PI/180) */ + /* SCORE_DIST_NORM = 10.0 */ + /* SCORE_DIST_WEIGHT = 4.0 */ + /* */ + /* 3200.0 */ + /* SCORE = ----------------------------------------------------------- */ + /* exp((jointheta/15.0)^2) * (1+exp(((joindist/10.0)-1.0)*4.0))*/ + /* */ + /* In this case, increases in distance drops off faster than */ + /* in theta. */ + + /* Compute the THETA_FACTOR. */ + theta_factor = jointheta / (lfsparms->score_theta_norm * DEG2RAD); + theta_factor = exp(theta_factor * theta_factor); + /* Compute the DIST_FACTOR. */ + dist_factor = 1.0+exp(((joindist/lfsparms->score_dist_norm)-1.0) * + lfsparms->score_dist_weight); + + /* Compute the floating point score. */ + score = lfsparms->score_numerator / (theta_factor * dist_factor); + + /* Return the floating point score. */ + return(score); +} + diff --git a/libfprint/nbis/mindtct/log.c b/libfprint/nbis/mindtct/log.c new file mode 100644 index 00000000..d3aafbf9 --- /dev/null +++ b/libfprint/nbis/mindtct/log.c @@ -0,0 +1,90 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: LOG.C + AUTHOR: Michael D. Garris + DATE: 08/02/1999 + + Contains routines responsible for dynamically updating a log file + during the execution of the NIST Latent Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + open_logfile() + print2log() + close_logfile() +***********************************************************************/ + +#include + +/* If logging is on, declare global file pointer and supporting */ +/* global variable for logging intermediate results. */ +FILE *logfp; +int avrdir; +float dir_strength; +int nvalid; + +/***************************************************************************/ +/***************************************************************************/ +int open_logfile() +{ +#ifdef LOG_REPORT + if((logfp = fopen(LOG_FILE, "wb")) == NULL){ + fprintf(stderr, "ERROR : open_logfile : fopen : %s\n", LOG_FILE); + return(-1); + } +#endif + + return(0); +} + +/***************************************************************************/ +/***************************************************************************/ +void print2log(char *fmt, ...) +{ +#ifdef LOG_REPORT + va_list ap; + + va_start(ap, fmt); + vfprintf(logfp, fmt, ap); + va_end(ap); +#endif +} + +/***************************************************************************/ +/***************************************************************************/ +int close_logfile() +{ +#ifdef LOG_REPORT + if(fclose(logfp)){ + fprintf(stderr, "ERROR : close_logfile : fclose : %s\n", LOG_FILE); + return(-1); + } +#endif + + return(0); +} + diff --git a/libfprint/nbis/mindtct/loop.c b/libfprint/nbis/mindtct/loop.c new file mode 100644 index 00000000..1e84c461 --- /dev/null +++ b/libfprint/nbis/mindtct/loop.c @@ -0,0 +1,1228 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: LOOP.C + AUTHOR: Michael D. Garris + DATE: 05/11/1999 + UPDATED: 10/04/1999 Version 2 by MDG + UPDATED: 03/16/2005 by MDG + + Contains routines responsible for analyzing and filling + lakes and islands within a binary image as part of the + NIST Latent Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + get_loop_list() + on_loop() + on_island_lake() + on_hook() + is_loop_clockwise() + process_loop() + process_loop_V2() + get_loop_aspect() + fill_loop() + fill_partial_row() + flood_loop() + flood_fill4() +***********************************************************************/ + +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: get_loop_list - Takes a list of minutia points and determines which +#cat: ones lie on loops around valleys (lakes) of a specified +#cat: maximum circumference. The routine returns a list of +#cat: flags, one for each minutia in the input list, and if +#cat: the minutia is on a qualifying loop, the corresponding +#cat: flag is set to TRUE, otherwise it is set to FALSE. +#cat: If for some reason it was not possible to trace the +#cat: minutia's contour, then it is removed from the list. +#cat: This can occur due to edits dynamically taking place +#cat: in the image by other routines. + + Input: + minutiae - list of true and false minutiae + loop_len - maximum size of loop searched for + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + oonloop - loop flags: TRUE == loop, FALSE == no loop + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int get_loop_list(int **oonloop, MINUTIAE *minutiae, const int loop_len, + unsigned char *bdata, const int iw, const int ih) +{ + int i, ret; + int *onloop; + MINUTIA *minutia; + + /* Allocate a list of onloop flags (one for each minutia in list). */ + onloop = (int *)malloc(minutiae->num * sizeof(int)); + if(onloop == (int *)NULL){ + fprintf(stderr, "ERROR : get_loop_list : malloc : onloop\n"); + return(-320); + } + + i = 0; + /* Foreach minutia remaining in list ... */ + while(i < minutiae->num){ + /* Assign a temporary pointer. */ + minutia = minutiae->list[i]; + /* If current minutia is a bifurcation ... */ + if(minutia->type == BIFURCATION){ + /* Check to see if it is on a loop of specified length. */ + ret = on_loop(minutia, loop_len, bdata, iw, ih); + /* If minutia is on a loop... */ + if(ret == LOOP_FOUND){ + /* Then set the onloop flag to TRUE. */ + onloop[i] = TRUE; + /* Advance to next minutia in the list. */ + i++; + } + /* If on loop test IGNORED ... */ + else if (ret == IGNORE){ + /* Remove the current minutia from the list. */ + if((ret = remove_minutia(i, minutiae))){ + /* Deallocate working memory. */ + free(onloop); + /* Return error code. */ + return(ret); + } + /* No need to advance because next minutia has "slid" */ + /* into position pointed to by 'i'. */ + } + /* If the minutia is NOT on a loop... */ + else if (ret == FALSE){ + /* Then set the onloop flag to FALSE. */ + onloop[i] = FALSE; + /* Advance to next minutia in the list. */ + i++; + } + /* Otherwise, an ERROR occurred while looking for loop. */ + else{ + /* Deallocate working memory. */ + free(onloop); + /* Return error code. */ + return(ret); + } + } + /* Otherwise, the current minutia is a ridge-ending... */ + else{ + /* Ridge-endings will never be on a loop, so set flag to FALSE. */ + onloop[i] = FALSE; + /* Advance to next minutia in the list. */ + i++; + } + } + + /* Store flag list to output pointer. */ + *oonloop = onloop; + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: on_loop - Determines if a minutia point lies on a loop (island or lake) +#cat: of specified maximum circumference. + + Input: + minutiae - list of true and false minutiae + max_loop_len - maximum size of loop searched for + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + Return Code: + IGNORE - minutia contour could not be traced + LOOP_FOUND - minutia determined to lie on qualifying loop + FALSE - minutia determined not to lie on qualifying loop + Negative - system error +**************************************************************************/ +int on_loop(const MINUTIA *minutia, const int max_loop_len, + unsigned char *bdata, const int iw, const int ih) +{ + int ret; + int *contour_x, *contour_y, *contour_ex, *contour_ey, ncontour; + + /* Trace the contour of the feature starting at the minutia point */ + /* and stepping along up to the specified maximum number of steps. */ + ret = trace_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, max_loop_len, + minutia->x, minutia->y, minutia->x, minutia->y, + minutia->ex, minutia->ey, + SCAN_CLOCKWISE, bdata, iw, ih); + + /* If trace was not possible ... */ + if(ret == IGNORE) + return(ret); + + /* If the trace completed a loop ... */ + if(ret == LOOP_FOUND){ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + return(LOOP_FOUND); + } + + /* If the trace successfully followed the minutia's contour, but did */ + /* not complete a loop within the specified number of steps ... */ + if(ret == 0){ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + return(FALSE); + } + + /* Otherwise, the trace had an error in following the contour ... */ + return(ret); +} + +/************************************************************************* +************************************************************************** +#cat: on_island_lake - Determines if two minutia points lie on the same loop +#cat: (island or lake). If a loop is detected, the contour +#cat: points of the loop are returned. + + Input: + minutia1 - first minutia point + minutia2 - second minutia point + max_half_loop - maximum size of half the loop circumference searched for + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + ocontour_x - x-pixel coords of loop contour + ocontour_y - y-pixel coords of loop contour + ocontour_x - x coord of each contour point's edge pixel + ocontour_y - y coord of each contour point's edge pixel + oncontour - number of points in the contour. + Return Code: + IGNORE - contour could not be traced + LOOP_FOUND - minutiae determined to lie on same qualifying loop + FALSE - minutiae determined not to lie on same qualifying loop + Negative - system error +**************************************************************************/ +int on_island_lake(int **ocontour_x, int **ocontour_y, + int **ocontour_ex, int **ocontour_ey, int *oncontour, + const MINUTIA *minutia1, const MINUTIA *minutia2, + const int max_half_loop, + unsigned char *bdata, const int iw, const int ih) +{ + int i, l, ret; + int *contour1_x, *contour1_y, *contour1_ex, *contour1_ey, ncontour1; + int *contour2_x, *contour2_y, *contour2_ex, *contour2_ey, ncontour2; + int *loop_x, *loop_y, *loop_ex, *loop_ey, nloop; + + /* Trace the contour of the feature starting at the 1st minutia point */ + /* and stepping along up to the specified maximum number of steps or */ + /* until 2nd mintuia point is encountered. */ + ret = trace_contour(&contour1_x, &contour1_y, + &contour1_ex, &contour1_ey, &ncontour1, max_half_loop, + minutia2->x, minutia2->y, minutia1->x, minutia1->y, + minutia1->ex, minutia1->ey, + SCAN_CLOCKWISE, bdata, iw, ih); + + /* If trace was not possible, return IGNORE. */ + if(ret == IGNORE) + return(ret); + + /* If the trace encounters 2nd minutia point ... */ + if(ret == LOOP_FOUND){ + + /* Now, trace the contour of the feature starting at the 2nd minutia, */ + /* continuing to search for edge neighbors clockwise, and stepping */ + /* along up to the specified maximum number of steps or until 1st */ + /* mintuia point is encountered. */ + ret = trace_contour(&contour2_x, &contour2_y, + &contour2_ex, &contour2_ey, &ncontour2, max_half_loop, + minutia1->x, minutia1->y, minutia2->x, minutia2->y, + minutia2->ex, minutia2->ey, + SCAN_CLOCKWISE, bdata, iw, ih); + + /* If trace was not possible, return IGNORE. */ + if(ret == IGNORE){ + free_contour(contour1_x, contour1_y, contour1_ex, contour1_ey); + return(ret); + } + + /* If the 2nd trace encounters 1st minutia point ... */ + if(ret == LOOP_FOUND){ + /* Combine the 2 half loop contours into one full loop. */ + + /* Compute loop length (including the minutia pair). */ + nloop = ncontour1 + ncontour2 + 2; + + /* Allocate loop contour. */ + if((ret = allocate_contour(&loop_x, &loop_y, &loop_ex, &loop_ey, + nloop))){ + free_contour(contour1_x, contour1_y, contour1_ex, contour1_ey); + free_contour(contour2_x, contour2_y, contour2_ex, contour2_ey); + return(ret); + } + + /* Store 1st minutia. */ + l = 0; + loop_x[l] = minutia1->x; + loop_y[l] = minutia1->y; + loop_ex[l] = minutia1->ex; + loop_ey[l++] = minutia1->ey; + /* Store first contour. */ + for(i = 0; i < ncontour1; i++){ + loop_x[l] = contour1_x[i]; + loop_y[l] = contour1_y[i]; + loop_ex[l] = contour1_ex[i]; + loop_ey[l++] = contour1_ey[i]; + } + /* Store 2nd minutia. */ + loop_x[l] = minutia2->x; + loop_y[l] = minutia2->y; + loop_ex[l] = minutia2->ex; + loop_ey[l++] = minutia2->ey; + /* Store 2nd contour. */ + for(i = 0; i < ncontour2; i++){ + loop_x[l] = contour2_x[i]; + loop_y[l] = contour2_y[i]; + loop_ex[l] = contour2_ex[i]; + loop_ey[l++] = contour2_ey[i]; + } + + /* Deallocate the half loop contours. */ + free_contour(contour1_x, contour1_y, contour1_ex, contour1_ey); + free_contour(contour2_x, contour2_y, contour2_ex, contour2_ey); + + /* Assign loop contour to return pointers. */ + *ocontour_x = loop_x; + *ocontour_y = loop_y; + *ocontour_ex = loop_ex; + *ocontour_ey = loop_ey; + *oncontour = nloop; + + /* Then return that an island/lake WAS found (LOOP_FOUND). */ + return(LOOP_FOUND); + } + + /* If the trace successfully followed 2nd minutia's contour, but */ + /* did not encounter 1st minutia point within the specified number */ + /* of steps ... */ + if(ret == 0){ + /* Deallocate the two contours. */ + free_contour(contour1_x, contour1_y, contour1_ex, contour1_ey); + free_contour(contour2_x, contour2_y, contour2_ex, contour2_ey); + /* Then return that an island/lake was NOT found (FALSE). */ + return(FALSE); + } + + /* Otherwise, the 2nd trace had an error in following the contour ... */ + free_contour(contour1_x, contour1_y, contour1_ex, contour1_ey); + return(ret); + } + + /* If the 1st trace successfully followed 1st minutia's contour, but */ + /* did not encounter the 2nd minutia point within the specified number */ + /* of steps ... */ + if(ret == 0){ + free_contour(contour1_x, contour1_y, contour1_ex, contour1_ey); + /* Then return that an island/lake was NOT found (FALSE). */ + return(FALSE); + } + + /* Otherwise, the 1st trace had an error in following the contour ... */ + return(ret); +} + +/************************************************************************* +************************************************************************** +#cat: on_hook - Determines if two minutia points lie on a hook on the side +#cat: of a ridge or valley. + + Input: + minutia1 - first minutia point + minutia2 - second minutia point + max_hook_len - maximum length of contour searched along for a hook + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + Return Code: + IGNORE - contour could not be traced + HOOK_FOUND - minutiae determined to lie on same qualifying hook + FALSE - minutiae determined not to lie on same qualifying hook + Negative - system error +**************************************************************************/ +int on_hook(const MINUTIA *minutia1, const MINUTIA *minutia2, + const int max_hook_len, + unsigned char *bdata, const int iw, const int ih) +{ + int ret; + int *contour_x, *contour_y, *contour_ex, *contour_ey, ncontour; + + /* NOTE: This routine should only be called when the 2 minutia points */ + /* are of "opposite" type. */ + + /* Trace the contour of the feature starting at the 1st minutia's */ + /* "edge" point and stepping along up to the specified maximum number */ + /* of steps or until the 2nd minutia point is encountered. */ + /* First search for edge neighbors clockwise. */ + + ret = trace_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, max_hook_len, + minutia2->x, minutia2->y, minutia1->ex, minutia1->ey, + minutia1->x, minutia1->y, + SCAN_CLOCKWISE, bdata, iw, ih); + + /* If trace was not possible, return IGNORE. */ + if(ret == IGNORE) + return(ret); + + /* If the trace encountered the second minutia point ... */ + if(ret == LOOP_FOUND){ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + return(HOOK_FOUND); + } + + /* If trace had an error in following the contour ... */ + if(ret != 0) + return(ret); + + + /* Otherwise, the trace successfully followed the contour, but did */ + /* not encounter the 2nd minutia point within the specified number */ + /* of steps. */ + + /* Deallocate previously extracted contour. */ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + + /* Try searching contour from 1st minutia "edge" searching for */ + /* edge neighbors counter-clockwise. */ + ret = trace_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, max_hook_len, + minutia2->x, minutia2->y, minutia1->ex, minutia1->ey, + minutia1->x, minutia1->y, + SCAN_COUNTER_CLOCKWISE, bdata, iw, ih); + + /* If trace was not possible, return IGNORE. */ + if(ret == IGNORE) + return(ret); + + /* If the trace encountered the second minutia point ... */ + if(ret == LOOP_FOUND){ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + return(HOOK_FOUND); + } + + /* If the trace successfully followed the 1st minutia's contour, but */ + /* did not encounter the 2nd minutia point within the specified number */ + /* of steps ... */ + if(ret == 0){ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + /* Then return hook NOT found (FALSE). */ + return(FALSE); + } + + /* Otherwise, the 2nd trace had an error in following the contour ... */ + return(ret); +} + +/************************************************************************* +************************************************************************** +#cat: is_loop_clockwise - Takes a feature's contour points and determines if +#cat: the points are ordered clockwise or counter-clockwise about +#cat: the feature. The routine also requires a default return +#cat: value be specified in the case the the routine is not able +#cat: to definitively determine the contour's order. This allows +#cat: the default response to be application-specific. + + Input: + contour_x - x-coord list for feature's contour points + contour_y - y-coord list for feature's contour points + ncontour - number of points in contour + default_ret - default return code (used when we can't tell the order) + Return Code: + TRUE - contour determined to be ordered clockwise + FALSE - contour determined to be ordered counter-clockwise + Default - could not determine the order of the contour + Negative - system error +**************************************************************************/ +int is_loop_clockwise(const int *contour_x, const int *contour_y, + const int ncontour, const int default_ret) +{ + int ret; + int *chain, nchain; + + /* Derive chain code from contour points. */ + if((ret = chain_code_loop(&chain, &nchain, + contour_x, contour_y, ncontour))) + /* If there is a system error, return the error code. */ + return(ret); + + /* If chain is empty... */ + if(nchain == 0){ + /* There wasn't enough contour points to tell, so return the */ + /* the default return value. No chain needs to be deallocated */ + /* in this case. */ + return(default_ret); + } + + /* If the chain code for contour is clockwise ... pass default return */ + /* value on to this routine to correctly handle the case where we can't */ + /* tell the direction of the chain code. */ + ret = is_chain_clockwise(chain, nchain, default_ret); + + /* Free the chain code and return result. */ + free(chain); + return(ret); +} + +/************************************************************************* +************************************************************************** +#cat: process_loop - Takes a contour list that has been determined to form +#cat: a complete loop, and processes it. If the loop is sufficiently +#cat: large and elongated, then two minutia points are calculated +#cat: along the loop's longest aspect axis. If it is determined +#cat: that the loop does not contain minutiae, it is filled in the +#cat: binary image. + + Input: + contour_x - x-coord list for loop's contour points + contour_y - y-coord list for loop's contour points + contour_ex - x-coord list for loop's edge points + contour_ey - y-coord list for loop's edge points + ncontour - number of points in contour + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - points to a list of detected minutia structures + OR + bdata - binary image data with loop filled + Return Code: + Zero - loop processed successfully + Negative - system error +**************************************************************************/ +int process_loop(MINUTIAE *minutiae, + const int *contour_x, const int *contour_y, + const int *contour_ex, const int *contour_ey, const int ncontour, + unsigned char *bdata, const int iw, const int ih, + const LFSPARMS *lfsparms) +{ + int halfway; + int idir, type, appearing; + double min_dist, max_dist; + int min_fr, max_fr, min_to, max_to; + int mid_x, mid_y, mid_pix; + int feature_pix; + int ret; + MINUTIA *minutia; + + /* If contour is empty, then just return. */ + if(ncontour <= 0) + return(0); + + /* If loop is large enough ... */ + if(ncontour > lfsparms->min_loop_len){ + /* Get pixel value of feature's interior. */ + feature_pix = *(bdata + (contour_y[0] * iw) + contour_x[0]); + + /* Compute half the perimeter of the loop. */ + halfway = ncontour>>1; + + /* Get the aspect dimensions of the loop in units of */ + /* squared distance. */ + get_loop_aspect(&min_fr, &min_to, &min_dist, + &max_fr, &max_to, &max_dist, + contour_x, contour_y, ncontour); + + /* If loop passes aspect ratio tests ... loop is sufficiently */ + /* narrow or elongated ... */ + if((min_dist < lfsparms->min_loop_aspect_dist) || + ((max_dist/min_dist) >= lfsparms->min_loop_aspect_ratio)){ + + /* Update minutiae list with opposite points of max distance */ + /* on the loop. */ + + /* First, check if interior point has proper pixel value. */ + mid_x = (contour_x[max_fr]+contour_x[max_to])>>1; + mid_y = (contour_y[max_fr]+contour_y[max_to])>>1; + mid_pix = *(bdata + (mid_y * iw) + mid_x); + /* If interior point is the same as the feature... */ + if(mid_pix == feature_pix){ + + /* 1. Treat maximum distance point as a potential minutia. */ + + /* Compute direction from maximum loop point to its */ + /* opposite point. */ + idir = line2direction(contour_x[max_fr], contour_y[max_fr], + contour_x[max_to], contour_y[max_to], + lfsparms->num_directions); + /* Get type of minutia: BIFURCATION or RIDGE_ENDING. */ + type = minutia_type(feature_pix); + /* Determine if minutia is appearing or disappearing. */ + if((appearing = is_minutia_appearing( + contour_x[max_fr], contour_y[max_fr], + contour_ex[max_fr], contour_ey[max_fr])) < 0){ + /* Return system error code. */ + return(appearing); + } + /* Create new minutia object. */ + if((ret = create_minutia(&minutia, + contour_x[max_fr], contour_y[max_fr], + contour_ex[max_fr], contour_ey[max_fr], + idir, DEFAULT_RELIABILITY, + type, appearing, LOOP_ID))){ + /* Return system error code. */ + return(ret); + } + /* Update the minutiae list with potential new minutia. */ + ret = update_minutiae(minutiae, minutia, bdata, iw, ih, lfsparms); + + /* If minuitia IGNORED and not added to the minutia list ... */ + if(ret == IGNORE) + /* Deallocate the minutia. */ + free_minutia(minutia); + + /* 2. Treat point opposite of maximum distance point as */ + /* a potential minutia. */ + + /* Flip the direction 180 degrees. Make sure new direction */ + /* is on the range [0..(ndirsX2)]. */ + idir += lfsparms->num_directions; + idir %= (lfsparms->num_directions<<1); + + /* The type of minutia will stay the same. */ + + /* Determine if minutia is appearing or disappearing. */ + if((appearing = is_minutia_appearing( + contour_x[max_to], contour_y[max_to], + contour_ex[max_to], contour_ey[max_to])) < 0){ + /* Return system error code. */ + return(appearing); + } + /* Create new minutia object. */ + if((ret = create_minutia(&minutia, + contour_x[max_to], contour_y[max_to], + contour_ex[max_to], contour_ey[max_to], + idir, DEFAULT_RELIABILITY, + type, appearing, LOOP_ID))){ + /* Return system error code. */ + return(ret); + } + /* Update the minutiae list with potential new minutia. */ + ret = update_minutiae(minutiae, minutia, bdata, iw, ih, lfsparms); + + /* If minuitia IGNORED and not added to the minutia list ... */ + if(ret == IGNORE) + /* Deallocate the minutia. */ + free_minutia(minutia); + + /* Done successfully processing this loop, so return normally. */ + return(0); + + } /* Otherwise, loop interior has problems. */ + } /* Otherwise, loop is not the right shape for minutiae. */ + } /* Otherwise, loop's perimeter is too small for minutiae. */ + + /* If we get here, we have a loop that is assumed to not contain */ + /* minutiae, so remove the loop from the image. */ + ret = fill_loop(contour_x, contour_y, ncontour, bdata, iw, ih); + + /* Return either an error code from fill_loop or return normally. */ + return(ret); +} + +/************************************************************************* +************************************************************************** +#cat: process_loop_V2 - Takes a contour list that has been determined to form +#cat: a complete loop, and processes it. If the loop is sufficiently +#cat: large and elongated, then two minutia points are calculated +#cat: along the loop's longest aspect axis. If it is determined +#cat: that the loop does not contain minutiae, it is filled in the +#cat: binary image. + + Input: + contour_x - x-coord list for loop's contour points + contour_y - y-coord list for loop's contour points + contour_ex - x-coord list for loop's edge points + contour_ey - y-coord list for loop's edge points + ncontour - number of points in contour + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + plow_flow_map - pixelized Low Ridge Flow Map + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - points to a list of detected minutia structures + OR + bdata - binary image data with loop filled + Return Code: + Zero - loop processed successfully + Negative - system error +**************************************************************************/ +int process_loop_V2(MINUTIAE *minutiae, + const int *contour_x, const int *contour_y, + const int *contour_ex, const int *contour_ey, const int ncontour, + unsigned char *bdata, const int iw, const int ih, + int *plow_flow_map, const LFSPARMS *lfsparms) +{ + int halfway; + int idir, type, appearing; + double min_dist, max_dist; + int min_fr, max_fr, min_to, max_to; + int mid_x, mid_y, mid_pix; + int feature_pix; + int ret; + MINUTIA *minutia; + int fmapval; + double reliability; + + /* If contour is empty, then just return. */ + if(ncontour <= 0) + return(0); + + /* If loop is large enough ... */ + if(ncontour > lfsparms->min_loop_len){ + /* Get pixel value of feature's interior. */ + feature_pix = *(bdata + (contour_y[0] * iw) + contour_x[0]); + + /* Compute half the perimeter of the loop. */ + halfway = ncontour>>1; + + /* Get the aspect dimensions of the loop in units of */ + /* squared distance. */ + get_loop_aspect(&min_fr, &min_to, &min_dist, + &max_fr, &max_to, &max_dist, + contour_x, contour_y, ncontour); + + /* If loop passes aspect ratio tests ... loop is sufficiently */ + /* narrow or elongated ... */ + if((min_dist < lfsparms->min_loop_aspect_dist) || + ((max_dist/min_dist) >= lfsparms->min_loop_aspect_ratio)){ + + /* Update minutiae list with opposite points of max distance */ + /* on the loop. */ + + /* First, check if interior point has proper pixel value. */ + mid_x = (contour_x[max_fr]+contour_x[max_to])>>1; + mid_y = (contour_y[max_fr]+contour_y[max_to])>>1; + mid_pix = *(bdata + (mid_y * iw) + mid_x); + /* If interior point is the same as the feature... */ + if(mid_pix == feature_pix){ + + /* 1. Treat maximum distance point as a potential minutia. */ + + /* Compute direction from maximum loop point to its */ + /* opposite point. */ + idir = line2direction(contour_x[max_fr], contour_y[max_fr], + contour_x[max_to], contour_y[max_to], + lfsparms->num_directions); + /* Get type of minutia: BIFURCATION or RIDGE_ENDING. */ + type = minutia_type(feature_pix); + /* Determine if minutia is appearing or disappearing. */ + if((appearing = is_minutia_appearing( + contour_x[max_fr], contour_y[max_fr], + contour_ex[max_fr], contour_ey[max_fr])) < 0){ + /* Return system error code. */ + return(appearing); + } + + /* Is the new point in a LOW RIDGE FLOW block? */ + fmapval = *(plow_flow_map+(contour_y[max_fr]*iw)+ + contour_x[max_fr]); + + /* If current minutia is in a LOW RIDGE FLOW block ... */ + if(fmapval) + reliability = MEDIUM_RELIABILITY; + else + /* Otherwise, minutia is in a reliable block. */ + reliability = HIGH_RELIABILITY; + + /* Create new minutia object. */ + if((ret = create_minutia(&minutia, + contour_x[max_fr], contour_y[max_fr], + contour_ex[max_fr], contour_ey[max_fr], + idir, reliability, + type, appearing, LOOP_ID))){ + /* Return system error code. */ + return(ret); + } + /* Update the minutiae list with potential new minutia. */ + /* NOTE: Deliberately using version one of this routine. */ + ret = update_minutiae(minutiae, minutia, bdata, iw, ih, lfsparms); + + /* If minuitia IGNORED and not added to the minutia list ... */ + if(ret == IGNORE) + /* Deallocate the minutia. */ + free_minutia(minutia); + + /* 2. Treat point opposite of maximum distance point as */ + /* a potential minutia. */ + + /* Flip the direction 180 degrees. Make sure new direction */ + /* is on the range [0..(ndirsX2)]. */ + idir += lfsparms->num_directions; + idir %= (lfsparms->num_directions<<1); + + /* The type of minutia will stay the same. */ + + /* Determine if minutia is appearing or disappearing. */ + if((appearing = is_minutia_appearing( + contour_x[max_to], contour_y[max_to], + contour_ex[max_to], contour_ey[max_to])) < 0){ + /* Return system error code. */ + return(appearing); + } + + /* Is the new point in a LOW RIDGE FLOW block? */ + fmapval = *(plow_flow_map+(contour_y[max_to]*iw)+ + contour_x[max_to]); + + /* If current minutia is in a LOW RIDGE FLOW block ... */ + if(fmapval) + reliability = MEDIUM_RELIABILITY; + else + /* Otherwise, minutia is in a reliable block. */ + reliability = HIGH_RELIABILITY; + + /* Create new minutia object. */ + if((ret = create_minutia(&minutia, + contour_x[max_to], contour_y[max_to], + contour_ex[max_to], contour_ey[max_to], + idir, reliability, + type, appearing, LOOP_ID))){ + /* Return system error code. */ + return(ret); + } + + /* Update the minutiae list with potential new minutia. */ + /* NOTE: Deliberately using version one of this routine. */ + ret = update_minutiae(minutiae, minutia, bdata, iw, ih, lfsparms); + + /* If minuitia IGNORED and not added to the minutia list ... */ + if(ret == IGNORE) + /* Deallocate the minutia. */ + free_minutia(minutia); + + /* Done successfully processing this loop, so return normally. */ + return(0); + + } /* Otherwise, loop interior has problems. */ + } /* Otherwise, loop is not the right shape for minutiae. */ + } /* Otherwise, loop's perimeter is too small for minutiae. */ + + /* If we get here, we have a loop that is assumed to not contain */ + /* minutiae, so remove the loop from the image. */ + ret = fill_loop(contour_x, contour_y, ncontour, bdata, iw, ih); + + /* Return either an error code from fill_loop or return normally. */ + return(ret); +} + +/************************************************************************* +************************************************************************** +#cat: get_loop_aspect - Takes a contour list (determined to form a complete +#cat: loop) and measures the loop's aspect (the largest and smallest +#cat: distances across the loop) and returns the points on the +#cat: loop where these distances occur. + + Input: + contour_x - x-coord list for loop's contour points + contour_y - y-coord list for loop's contour points + ncontour - number of points in contour + Output: + omin_fr - contour point index where minimum aspect occurs + omin_to - opposite contour point index where minimum aspect occurs + omin_dist - the minimum distance across the loop + omax_fr - contour point index where maximum aspect occurs + omax_to - contour point index where maximum aspect occurs + omax_dist - the maximum distance across the loop +**************************************************************************/ +void get_loop_aspect(int *omin_fr, int *omin_to, double *omin_dist, + int *omax_fr, int *omax_to, double *omax_dist, + const int *contour_x, const int *contour_y, const int ncontour) +{ + int halfway, limit; + int i, j; + double dist; + double min_dist, max_dist; + int min_i, max_i, min_j, max_j; + + /* Compute half the perimeter of the loop. */ + halfway = ncontour>>1; + + /* Take opposite points on the contour and walk half way */ + /* around the loop. */ + i = 0; + j = halfway; + /* Compute squared distance between opposite points on loop. */ + dist = squared_distance(contour_x[i], contour_y[i], + contour_x[j], contour_y[j]); + + /* Initialize running minimum and maximum distances along loop. */ + min_dist = dist; + min_i = i; + min_j = j; + max_dist = dist; + max_i = i; + max_j = j; + /* Bump to next pair of opposite points. */ + i++; + /* Make sure j wraps around end of list. */ + j++; + j %= ncontour; + + /* If the loop is of even length, then we only need to walk half */ + /* way around as the other half will be exactly redundant. If */ + /* the loop is of odd length, then the second half will not be */ + /* be exactly redundant and the difference "may" be meaningful. */ + /* If execution speed is an issue, then probably get away with */ + /* walking only the fist half of the loop under ALL conditions. */ + + /* If loop has odd length ... */ + if(ncontour % 2) + /* Walk the loop's entire perimeter. */ + limit = ncontour; + /* Otherwise the loop has even length ... */ + else + /* Only walk half the perimeter. */ + limit = halfway; + + /* While we have not reached our perimeter limit ... */ + while(i < limit){ + /* Compute squared distance between opposite points on loop. */ + dist = squared_distance(contour_x[i], contour_y[i], + contour_x[j], contour_y[j]); + /* Check the running minimum and maximum distances. */ + if(dist < min_dist){ + min_dist = dist; + min_i = i; + min_j = j; + } + if(dist > max_dist){ + max_dist = dist; + max_i = i; + max_j = j; + } + /* Bump to next pair of opposite points. */ + i++; + /* Make sure j wraps around end of list. */ + j++; + j %= ncontour; + } + + /* Assign minimum and maximum distances to output pointers. */ + *omin_fr = min_i; + *omin_to = min_j; + *omin_dist = min_dist; + *omax_fr = max_i; + *omax_to = max_j; + *omax_dist = max_dist; +} + +/************************************************************************* +************************************************************************** +#cat: fill_loop - Takes a contour list that has been determined to form +#cat: a complete loop, and fills the loop accounting for +#cat: complex/concaved shapes. +#cat: NOTE, I tried using a flood-fill in place of this routine, +#cat: but the contour (although 8-connected) is NOT guaranteed to +#cat: be "complete" surrounded (in an 8-connected sense) by pixels +#cat: of opposite color. Therefore, the flood would occasionally +#cat: escape the loop and corrupt the binary image! + + Input: + contour_x - x-coord list for loop's contour points + contour_y - y-coord list for loop's contour points + ncontour - number of points in contour + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + bdata - binary image data with loop filled + Return Code: + Zero - loop filled successfully + Negative - system error +**************************************************************************/ +int fill_loop(const int *contour_x, const int *contour_y, + const int ncontour, unsigned char *bdata, + const int iw, const int ih) +{ + SHAPE *shape; + int ret, i, j, x, nx, y; + int lastj; + int next_pix, feature_pix, edge_pix; + + /* Create a shape structure from loop's contour. */ + if((ret = shape_from_contour(&shape, contour_x, contour_y, ncontour))) + /* If system error, then return error code. */ + return(ret); + + /* Get feature pixel value (the value on the interior of the loop */ + /* to be filled). */ + feature_pix = *(bdata+(contour_y[0]*iw)+contour_x[0]); + /* Now get edge pixel value (the value on the exterior of the loop */ + /* to be used to filled the loop). We can get this value by flipping */ + /* the feature pixel value. */ + if(feature_pix) + edge_pix = 0; + else + edge_pix = 1; + + /* Foreach row in shape... */ + for(i = 0; i < shape->nrows; i++){ + /* Get y-coord of current row in shape. */ + y = shape->rows[i]->y; + + /* There should always be at least 1 contour points in the row. */ + /* If there isn't, then something is wrong, so post a warning and */ + /* just return. This is mostly for debug purposes. */ + if(shape->rows[i]->npts < 1){ + /* Deallocate the shape. */ + free_shape(shape); + fprintf(stderr, + "WARNING : fill_loop : unexpected shape, preempting loop fill\n"); + /* This is unexpected, but not fatal, so return normally. */ + return(0); + } + + /* Reset x index on row to the left-most contour point in the row. */ + j = 0; + /* Get first x-coord corresponding to the first contour point on row. */ + x = shape->rows[i]->xs[j]; + /* Fill the first contour point on the row. */ + *(bdata+(y*iw)+x) = edge_pix; + /* Set the index of last contour point on row. */ + lastj = shape->rows[i]->npts - 1; + /* While last contour point on row has not been processed... */ + while(j < lastj){ + + /* On each interation, we have filled up to the current */ + /* contour point on the row pointed to by "j", and now we */ + /* need to determine if we need to skip some edge pixels */ + /* caused by a concavity in the shape or not. */ + + /* Get the next pixel value on the row just right of the */ + /* last contour point filled. We know there are more points */ + /* on the row because we haven't processed the last contour */ + /* point on the row yet. */ + x++; + next_pix = *(bdata+(y*iw)+x); + + /* If the next pixel is the same value as loop's edge pixels ... */ + if(next_pix == edge_pix){ + /* Then assume we have found a concavity and skip to next */ + /* contour point on row. */ + j++; + /* Fill the new contour point because we know it is on the */ + /* feature's contour. */ + x = shape->rows[i]->xs[j]; + *(bdata+(y*iw)+x) = edge_pix; + + /* Now we are ready to loop again. */ + } + + /* Otherwise, fill from current pixel up through the next contour */ + /* point to the right on the row. */ + else{ + /* Bump to the next contour point to the right on row. */ + j++; + /* Set the destination x-coord to the next contour point */ + /* to the right on row. Realize that this could be the */ + /* same pixel as the current x-coord if contour points are */ + /* adjacent. */ + nx = shape->rows[i]->xs[j]; + + /* Fill between current x-coord and next contour point to the */ + /* right on the row (including the new contour point).*/ + fill_partial_row(edge_pix, x, nx, y, bdata, iw, ih); + } + + /* Once we are here we have filled the row up to (and including) */ + /* the contour point currently pointed to by "j". */ + /* We are now ready to loop again. */ + + } /* End WHILE */ + } /* End FOR */ + + free_shape(shape); + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: fill_partial_row - Fills a specified range of contiguous pixels on +#cat: a specified row of an 8-bit pixel image with a specified +#cat: pixel value. NOTE, the pixel coordinates are assumed to +#cat: be within the image boundaries. + + Input: + fill_pix - pixel value to fill with (should be on range [0..255] + frx - x-pixel coord where fill should begin + tox - x-pixel coord where fill should end (inclusive) + y - y-pixel coord of current row being filled + bdata - 8-bit image data + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + bdata - 8-bit image data with partial row filled. +**************************************************************************/ +void fill_partial_row(const int fill_pix, const int frx, const int tox, + const int y, unsigned char *bdata, const int iw, const int ih) +{ + int x; + unsigned char *bptr; + + /* Set pixel pointer to starting x-coord on current row. */ + bptr = bdata+(y*iw)+frx; + + /* Foreach pixel between starting and ending x-coord on row */ + /* (including the end points) ... */ + for(x = frx; x <= tox; x++){ + /* Set current pixel with fill pixel value. */ + *bptr = fill_pix; + /* Bump to next pixel in the row. */ + bptr++; + } +} + +/************************************************************************* +************************************************************************** +#cat: flood_loop - Fills a given contour (determined to form a complete loop) +#cat: with a specified pixel value using a recursive flood-fill +#cat: technique. +#cat: NOTE, this fill approach will NOT always work with the +#cat: contours generated in this application because they +#cat: are NOT guaranteed to be ENTIRELY surrounded by 8-connected +#cat: pixels not equal to the fill pixel value. This is unfortunate +#cat: because the flood-fill is a simple algorithm that will handle +#cat: complex/concaved shapes. + + Input: + contour_x - x-coord list for loop's contour points + contour_y - y-coord list for loop's contour points + ncontour - number of points in contour + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + bdata - binary image data with loop filled +**************************************************************************/ +void flood_loop(const int *contour_x, const int *contour_y, + const int ncontour, unsigned char *bdata, + const int iw, const int ih) +{ + int feature_pix, fill_pix; + int i; + + /* Get the pixel value of the minutia feauture. This is */ + /* the pixel value we wish to replace with the flood. */ + feature_pix = *(bdata + (contour_y[0] * iw) + contour_x[0]); + + /* Flip the feature pixel value to the value we want to */ + /* fill with and send this value to the flood routine. */ + fill_pix = !feature_pix; + + /* Flood-fill interior of contour using a 4-neighbor fill. */ + /* We are using a 4-neighbor fill because the contour was */ + /* collected using 8-neighbors, and the 4-neighbor fill */ + /* will NOT escape the 8-neighbor based contour. */ + /* The contour passed must be guarenteed to be complete for */ + /* the flood-fill to work properly. */ + /* We are initiating a flood-fill from each point on the */ + /* contour to make sure complex patterns get filled in. */ + /* The complex patterns we are concerned about are those */ + /* that "pinch" the interior of the feature off due to */ + /* skipping "exposed" corners along the contour. */ + /* Simple shapes will fill upon invoking the first contour */ + /* pixel, and the subsequent calls will immediately return */ + /* as their seed pixel will have already been flipped. */ + for(i = 0; i < ncontour; i++){ + /* Start the recursive flooding. */ + flood_fill4(fill_pix, contour_x[i], contour_y[i], + bdata, iw, ih); + } +} + +/************************************************************************* +************************************************************************** +#cat: flood_fill4 - Recursively floods a region of an 8-bit pixel image with a +#cat: specified pixel value given a starting (seed) point. The +#cat: recursion is based neighbors being 4-connected. + + Input: + fill_pix - 8-bit pixel value to be filled with (on range [0..255] + x - starting x-pixel coord + y - starting y-pixel coord + bdata - 8-bit pixel image data + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + bdata - 8-bit pixel image data with region filled +**************************************************************************/ +void flood_fill4(const int fill_pix, const int x, const int y, + unsigned char *bdata, const int iw, const int ih) +{ + unsigned char *pptr; + int y_north, y_south, x_east, x_west; + + /* Get address of current pixel. */ + pptr = bdata + (y*iw) + x; + /* If pixel needs to be filled ... */ + if(*pptr != fill_pix){ + /* Fill the current pixel. */ + *pptr = fill_pix; + + /* Recursively invoke flood on the pixel's 4 neighbors. */ + /* Test to make sure neighbors are within image boudaries */ + /* before invoking each flood. */ + y_north = y-1; + y_south = y+1; + x_west = x-1; + x_east = x+1; + + /* Invoke North */ + if(y_north >= 0) + flood_fill4(fill_pix, x, y_north, bdata, iw, ih); + + /* Invoke East */ + if(x_east < iw) + flood_fill4(fill_pix, x_east, y, bdata, iw, ih); + + /* Invoke South */ + if(y_south < ih) + flood_fill4(fill_pix, x, y_south, bdata, iw, ih); + + /* Invoke West */ + if(x_west >= 0) + flood_fill4(fill_pix, x_west, y, bdata, iw, ih); + } + + /* Otherwise, there is nothing to be done. */ +} diff --git a/libfprint/nbis/mindtct/maps.c b/libfprint/nbis/mindtct/maps.c new file mode 100644 index 00000000..3050c5cc --- /dev/null +++ b/libfprint/nbis/mindtct/maps.c @@ -0,0 +1,2552 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: MAPS.C + AUTHOR: Michael D. Garris + DATE: 03/16/1999 + UPDATED: 10/04/1999 Version 2 by MDG + UPDATED: 10/26/1999 by MDG + To permit margin blocks to be flagged in + low contrast and low flow maps. + UPDATED: 03/16/2005 by MDG + + Contains routines responsible for computing various block-based + maps (including directional ridge flow maps) from an arbitrarily- + sized image as part of the NIST Latent Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + gen_image_maps() + gen_initial_maps() + interpolate_direction_map() + morph_TF_map() + pixelize_map() + smooth_direction_map() + gen_high_curve_map() + gen_imap() + gen_initial_imap() + primary_dir_test() + secondary_fork_test() + remove_incon_dirs() + test_top_edge() + test_right_edge() + test_bottom_edge() + test_left_edge() + remove_dir() + average_8nbr_dir() + num_valid_8nbrs() + smooth_imap() + gen_nmap() + vorticity() + accum_nbr_vorticity() + curvature() + +***********************************************************************/ + +#include +#include +#include +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: gen_image_maps - Computes a set of image maps based on Version 2 +#cat: of the NIST LFS System. The first map is a Direction Map +#cat: which is a 2D vector of integer directions, where each +#cat: direction represents the dominant ridge flow in a block of +#cat: the input grayscale image. The Low Contrast Map flags +#cat: blocks with insufficient contrast. The Low Flow Map flags +#cat: blocks with insufficient ridge flow. The High Curve Map +#cat: flags blocks containing high curvature. This routine will +#cat: generate maps for an arbitrarily sized, non-square, image. + + Input: + pdata - padded input image data (8 bits [0..256) grayscale) + pw - padded width (in pixels) of the input image + ph - padded height (in pixels) of the input image + dir2rad - lookup table for converting integer directions + dftwaves - structure containing the DFT wave forms + dftgrids - structure containing the rotated pixel grid offsets + lfsparms - parameters and thresholds for controlling LFS + Output: + odmap - points to the created Direction Map + olcmap - points to the created Low Contrast Map + olfmap - points to the Low Ridge Flow Map + ohcmap - points to the High Curvature Map + omw - width (in blocks) of the maps + omh - height (in blocks) of the maps + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int gen_image_maps(int **odmap, int **olcmap, int **olfmap, int **ohcmap, + int *omw, int *omh, + unsigned char *pdata, const int pw, const int ph, + const DIR2RAD *dir2rad, const DFTWAVES *dftwaves, + const ROTGRIDS *dftgrids, const LFSPARMS *lfsparms) +{ + int *direction_map, *low_contrast_map, *low_flow_map, *high_curve_map; + int mw, mh, iw, ih; + int *blkoffs; + int ret; /* return code */ + + /* 1. Compute block offsets for the entire image, accounting for pad */ + /* Block_offsets() assumes square block (grid), so ERROR otherwise. */ + if(dftgrids->grid_w != dftgrids->grid_h){ + fprintf(stderr, + "ERROR : gen_image_maps : DFT grids must be square\n"); + return(-540); + } + /* Compute unpadded image dimensions. */ + iw = pw - (dftgrids->pad<<1); + ih = ph - (dftgrids->pad<<1); + if((ret = block_offsets(&blkoffs, &mw, &mh, iw, ih, + dftgrids->pad, lfsparms->blocksize))){ + return(ret); + } + + /* 2. Generate initial Direction Map and Low Contrast Map*/ + if((ret = gen_initial_maps(&direction_map, &low_contrast_map, + &low_flow_map, blkoffs, mw, mh, + pdata, pw, ph, dftwaves, dftgrids, lfsparms))){ + /* Free memory allocated to this point. */ + free(blkoffs); + return(ret); + } + + if((ret = morph_TF_map(low_flow_map, mw, mh, lfsparms))){ + return(ret); + } + + /* 3. Remove directions that are inconsistent with neighbors */ + remove_incon_dirs(direction_map, mw, mh, dir2rad, lfsparms); + + + /* 4. Smooth Direction Map values with their neighbors */ + smooth_direction_map(direction_map, low_contrast_map, mw, mh, + dir2rad, lfsparms); + + /* 5. Interpolate INVALID direction blocks with their valid neighbors. */ + if((ret = interpolate_direction_map(direction_map, low_contrast_map, + mw, mh, lfsparms))){ + return(ret); + } + + /* May be able to skip steps 6 and/or 7 if computation time */ + /* is a critical factor. */ + + /* 6. Remove directions that are inconsistent with neighbors */ + remove_incon_dirs(direction_map, mw, mh, dir2rad, lfsparms); + + /* 7. Smooth Direction Map values with their neighbors. */ + smooth_direction_map(direction_map, low_contrast_map, mw, mh, + dir2rad, lfsparms); + + /* 8. Set the Direction Map values in the image margin to INVALID. */ + set_margin_blocks(direction_map, mw, mh, INVALID_DIR); + + /* 9. Generate High Curvature Map from interpolated Direction Map. */ + if((ret = gen_high_curve_map(&high_curve_map, direction_map, mw, mh, + lfsparms))){ + return(ret); + } + + /* Deallocate working memory. */ + free(blkoffs); + + *odmap = direction_map; + *olcmap = low_contrast_map; + *olfmap = low_flow_map; + *ohcmap = high_curve_map; + *omw = mw; + *omh = mh; + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: gen_initial_maps - Creates an initial Direction Map from the given +#cat: input image. It very important that the image be properly +#cat: padded so that rotated grids along the boundary of the image +#cat: do not access unkown memory. The rotated grids are used by a +#cat: DFT-based analysis to determine the integer directions +#cat: in the map. Typically this initial vector of directions will +#cat: subsequently have weak or inconsistent directions removed +#cat: followed by a smoothing process. The resulting Direction +#cat: Map contains valid directions >= 0 and INVALID values = -1. +#cat: This routine also computes and returns 2 other image maps. +#cat: The Low Contrast Map flags blocks in the image with +#cat: insufficient contrast. Blocks with low contrast have a +#cat: corresponding direction of INVALID in the Direction Map. +#cat: The Low Flow Map flags blocks in which the DFT analyses +#cat: could not determine a significant ridge flow. Blocks with +#cat: low ridge flow also have a corresponding direction of +#cat: INVALID in the Direction Map. + + Input: + blkoffs - offsets to the pixel origin of each block in the padded image + mw - number of blocks horizontally in the padded input image + mh - number of blocks vertically in the padded input image + pdata - padded input image data (8 bits [0..256) grayscale) + pw - width (in pixels) of the padded input image + ph - height (in pixels) of the padded input image + dftwaves - structure containing the DFT wave forms + dftgrids - structure containing the rotated pixel grid offsets + lfsparms - parameters and thresholds for controlling LFS + Output: + odmap - points to the newly created Direction Map + olcmap - points to the newly created Low Contrast Map + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int gen_initial_maps(int **odmap, int **olcmap, int **olfmap, + int *blkoffs, const int mw, const int mh, + unsigned char *pdata, const int pw, const int ph, + const DFTWAVES *dftwaves, const ROTGRIDS *dftgrids, + const LFSPARMS *lfsparms) +{ + int *direction_map, *low_contrast_map, *low_flow_map; + int bi, bsize, blkdir; + int *wis, *powmax_dirs; + double **powers, *powmaxs, *pownorms; + int nstats; + int ret; /* return code */ + int dft_offset; + int xminlimit, xmaxlimit, yminlimit, ymaxlimit; + int win_x, win_y, low_contrast_offset; + + print2log("INITIAL MAP\n"); + + /* Compute total number of blocks in map */ + bsize = mw * mh; + + /* Allocate Direction Map memory */ + direction_map = (int *)malloc(bsize * sizeof(int)); + if(direction_map == (int *)NULL){ + fprintf(stderr, + "ERROR : gen_initial_maps : malloc : direction_map\n"); + return(-550); + } + /* Initialize the Direction Map to INVALID (-1). */ + memset(direction_map, INVALID_DIR, bsize * sizeof(int)); + + /* Allocate Low Contrast Map memory */ + low_contrast_map = (int *)malloc(bsize * sizeof(int)); + if(low_contrast_map == (int *)NULL){ + free(direction_map); + fprintf(stderr, + "ERROR : gen_initial_maps : malloc : low_contrast_map\n"); + return(-551); + } + /* Initialize the Low Contrast Map to FALSE (0). */ + memset(low_contrast_map, 0, bsize * sizeof(int)); + + /* Allocate Low Ridge Flow Map memory */ + low_flow_map = (int *)malloc(bsize * sizeof(int)); + if(low_flow_map == (int *)NULL){ + free(direction_map); + free(low_contrast_map); + fprintf(stderr, + "ERROR : gen_initial_maps : malloc : low_flow_map\n"); + return(-552); + } + /* Initialize the Low Flow Map to FALSE (0). */ + memset(low_flow_map, 0, bsize * sizeof(int)); + + /* Allocate DFT directional power vectors */ + if((ret = alloc_dir_powers(&powers, dftwaves->nwaves, dftgrids->ngrids))){ + /* Free memory allocated to this point. */ + free(direction_map); + free(low_contrast_map); + free(low_flow_map); + return(ret); + } + + /* Allocate DFT power statistic arrays */ + /* Compute length of statistics arrays. Statistics not needed */ + /* for the first DFT wave, so the length is number of waves - 1. */ + nstats = dftwaves->nwaves - 1; + if((ret = alloc_power_stats(&wis, &powmaxs, &powmax_dirs, + &pownorms, nstats))){ + /* Free memory allocated to this point. */ + free(direction_map); + free(low_contrast_map); + free(low_flow_map); + free_dir_powers(powers, dftwaves->nwaves); + return(ret); + } + + /* Compute special window origin limits for determining low contrast. */ + /* These pixel limits avoid analyzing the padded borders of the image. */ + xminlimit = dftgrids->pad; + yminlimit = dftgrids->pad; + xmaxlimit = pw - dftgrids->pad - lfsparms->windowsize - 1; + ymaxlimit = ph - dftgrids->pad - lfsparms->windowsize - 1; + + /* Foreach block in image ... */ + for(bi = 0; bi < bsize; bi++){ + /* Adjust block offset from pointing to block origin to pointing */ + /* to surrounding window origin. */ + dft_offset = blkoffs[bi] - (lfsparms->windowoffset * pw) - + lfsparms->windowoffset; + + /* Compute pixel coords of window origin. */ + win_x = dft_offset % pw; + win_y = (int)(dft_offset / pw); + + /* Make sure the current window does not access padded image pixels */ + /* for analyzing low contrast. */ + win_x = max(xminlimit, win_x); + win_x = min(xmaxlimit, win_x); + win_y = max(yminlimit, win_y); + win_y = min(ymaxlimit, win_y); + low_contrast_offset = (win_y * pw) + win_x; + + print2log(" BLOCK %2d (%2d, %2d) ", bi, bi%mw, bi/mw); + + /* If block is low contrast ... */ + if((ret = low_contrast_block(low_contrast_offset, lfsparms->windowsize, + pdata, pw, ph, lfsparms))){ + /* If system error ... */ + if(ret < 0){ + free(direction_map); + free(low_contrast_map); + free(low_flow_map); + free_dir_powers(powers, dftwaves->nwaves); + free(wis); + free(powmaxs); + free(powmax_dirs); + free(pownorms); + return(ret); + } + + /* Otherwise, block is low contrast ... */ + print2log("LOW CONTRAST\n"); + low_contrast_map[bi] = TRUE; + /* Direction Map's block is already set to INVALID. */ + } + /* Otherwise, sufficient contrast for DFT processing ... */ + else { + print2log("\n"); + + /* Compute DFT powers */ + if((ret = dft_dir_powers(powers, pdata, low_contrast_offset, pw, ph, + dftwaves, dftgrids))){ + /* Free memory allocated to this point. */ + free(direction_map); + free(low_contrast_map); + free(low_flow_map); + free_dir_powers(powers, dftwaves->nwaves); + free(wis); + free(powmaxs); + free(powmax_dirs); + free(pownorms); + return(ret); + } + + /* Compute DFT power statistics, skipping first applied DFT */ + /* wave. This is dependent on how the primary and secondary */ + /* direction tests work below. */ + if((ret = dft_power_stats(wis, powmaxs, powmax_dirs, pownorms, powers, + 1, dftwaves->nwaves, dftgrids->ngrids))){ + /* Free memory allocated to this point. */ + free(direction_map); + free(low_contrast_map); + free(low_flow_map); + free_dir_powers(powers, dftwaves->nwaves); + free(wis); + free(powmaxs); + free(powmax_dirs); + free(pownorms); + return(ret); + } + +#ifdef LOG_REPORT /*vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv*/ + { int _w; + fprintf(logfp, " Power\n"); + for(_w = 0; _w < nstats; _w++){ + /* Add 1 to wis[w] to create index to original dft_coefs[] */ + fprintf(logfp, " wis[%d] %d %12.3f %2d %9.3f %12.3f\n", + _w, wis[_w]+1, + powmaxs[wis[_w]], powmax_dirs[wis[_w]], pownorms[wis[_w]], + powers[0][powmax_dirs[wis[_w]]]); + } + } +#endif /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/ + + /* Conduct primary direction test */ + blkdir = primary_dir_test(powers, wis, powmaxs, powmax_dirs, + pownorms, nstats, lfsparms); + + if(blkdir != INVALID_DIR) + direction_map[bi] = blkdir; + else{ + /* Conduct secondary (fork) direction test */ + blkdir = secondary_fork_test(powers, wis, powmaxs, powmax_dirs, + pownorms, nstats, lfsparms); + if(blkdir != INVALID_DIR) + direction_map[bi] = blkdir; + /* Otherwise current direction in Direction Map remains INVALID */ + else + /* Flag the block as having LOW RIDGE FLOW. */ + low_flow_map[bi] = TRUE; + } + + } /* End DFT */ + } /* bi */ + + /* Deallocate working memory */ + free_dir_powers(powers, dftwaves->nwaves); + free(wis); + free(powmaxs); + free(powmax_dirs); + free(pownorms); + + *odmap = direction_map; + *olcmap = low_contrast_map; + *olfmap = low_flow_map; + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: interpolate_direction_map - Take a Direction Map and Low Contrast +#cat: Map and attempts to fill in INVALID directions in the +#cat: Direction Map based on a blocks valid neighbors. The +#cat: valid neighboring directions are combined in a weighted +#cat: average inversely proportional to their distance from +#cat: the block being interpolated. Low Contrast blocks are +#cat: used to prempt the search for a valid neighbor in a +#cat: specific direction, which keeps the process from +#cat: interpolating directions for blocks in the background and +#cat: and perimeter of the fingerprint in the image. + + Input: + direction_map - map of blocks containing directional ridge flow + low_contrast_map - map of blocks flagged as LOW CONTRAST + mw - number of blocks horizontally in the maps + mh - number of blocks vertically in the maps + lfsparms - parameters and thresholds for controlling LFS + Output: + direction_map - contains the newly interpolated results + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int interpolate_direction_map(int *direction_map, int *low_contrast_map, + const int mw, const int mh, const LFSPARMS *lfsparms) +{ + int x, y, new_dir; + int n_dir, e_dir, s_dir, w_dir; + int n_dist = 0, e_dist = 0, s_dist = 0, w_dist = 0, total_dist; + int n_found, e_found, s_found, w_found, total_found; + int n_delta = 0, e_delta = 0, s_delta = 0, w_delta = 0, total_delta; + int nbr_x, nbr_y; + int *omap, *dptr, *cptr, *optr; + double avr_dir; + + print2log("INTERPOLATE DIRECTION MAP\n"); + + /* Allocate output (interpolated) Direction Map. */ + omap = (int *)malloc(mw*mh*sizeof(int)); + if(omap == (int *)NULL){ + fprintf(stderr, + "ERROR : interpolate_direction_map : malloc : omap\n"); + return(-520); + } + + /* Set pointers to the first block in the maps. */ + dptr = direction_map; + cptr = low_contrast_map; + optr = omap; + + /* Foreach block in the maps ... */ + for(y = 0; y < mh; y++){ + for(x = 0; x < mw; x++){ + + /* If image block is NOT LOW CONTRAST and has INVALID direction ... */ + if((!*cptr) && (*dptr == INVALID_DIR)){ + + /* Set neighbor accumulators to 0. */ + total_found = 0; + total_dist = 0; + + /* Find north neighbor. */ + if((n_found = find_valid_block(&n_dir, &nbr_x, &nbr_y, + direction_map, low_contrast_map, + x, y, mw, mh, 0, -1)) == FOUND){ + /* Compute north distance. */ + n_dist = y - nbr_y; + /* Accumulate neighbor distance. */ + total_dist += n_dist; + /* Bump number of neighbors found. */ + total_found++; + } + + /* Find east neighbor. */ + if((e_found = find_valid_block(&e_dir, &nbr_x, &nbr_y, + direction_map, low_contrast_map, + x, y, mw, mh, 1, 0)) == FOUND){ + /* Compute east distance. */ + e_dist = nbr_x - x; + /* Accumulate neighbor distance. */ + total_dist += e_dist; + /* Bump number of neighbors found. */ + total_found++; + } + + /* Find south neighbor. */ + if((s_found = find_valid_block(&s_dir, &nbr_x, &nbr_y, + direction_map, low_contrast_map, + x, y, mw, mh, 0, 1)) == FOUND){ + /* Compute south distance. */ + s_dist = nbr_y - y; + /* Accumulate neighbor distance. */ + total_dist += s_dist; + /* Bump number of neighbors found. */ + total_found++; + } + + /* Find west neighbor. */ + if((w_found = find_valid_block(&w_dir, &nbr_x, &nbr_y, + direction_map, low_contrast_map, + x, y, mw, mh, -1, 0)) == FOUND){ + /* Compute west distance. */ + w_dist = x - nbr_x; + /* Accumulate neighbor distance. */ + total_dist += w_dist; + /* Bump number of neighbors found. */ + total_found++; + } + + /* If a sufficient number of neighbors found (Ex. 2) ... */ + if(total_found >= lfsparms->min_interpolate_nbrs){ + + /* Accumulate weighted sum of neighboring directions */ + /* inversely related to the distance from current block. */ + total_delta = 0.0; + /* If neighbor found to the north ... */ + if(n_found){ + n_delta = total_dist - n_dist; + total_delta += n_delta; + } + /* If neighbor found to the east ... */ + if(e_found){ + e_delta = total_dist - e_dist; + total_delta += e_delta; + } + /* If neighbor found to the south ... */ + if(s_found){ + s_delta = total_dist - s_dist; + total_delta += s_delta; + } + /* If neighbor found to the west ... */ + if(w_found){ + w_delta = total_dist - w_dist; + total_delta += w_delta; + } + + avr_dir = 0.0; + + if(n_found){ + avr_dir += (n_dir*(n_delta/(double)total_delta)); + } + if(e_found){ + avr_dir += (e_dir*(e_delta/(double)total_delta)); + } + if(s_found){ + avr_dir += (s_dir*(s_delta/(double)total_delta)); + } + if(w_found){ + avr_dir += (w_dir*(w_delta/(double)total_delta)); + } + + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + avr_dir = trunc_dbl_precision(avr_dir, TRUNC_SCALE); + + /* Assign interpolated direction to output Direction Map. */ + new_dir = sround(avr_dir); + + print2log(" Block %d,%d INTERP numnbs=%d newdir=%d\n", + x, y, total_found, new_dir); + + *optr = new_dir; + } + else{ + /* Otherwise, the direction remains INVALID. */ + *optr = *dptr; + } + } + else{ + /* Otherwise, assign the current direction to the output block. */ + *optr = *dptr; + } + + /* Bump to the next block in the maps ... */ + dptr++; + cptr++; + optr++; + } + } + + /* Copy the interpolated directions into the input map. */ + memcpy(direction_map, omap, mw*mh*sizeof(int)); + /* Deallocate the working memory. */ + free(omap); + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: morph_tf_map - Takes a 2D vector of TRUE and FALSE values integers +#cat: and dialates and erodes the map in an attempt to fill +#cat: in voids in the map. + + Input: + tfmap - vector of integer block values + mw - width (in blocks) of the map + mh - height (in blocks) of the map + lfsparms - parameters and thresholds for controlling LFS + Output: + tfmap - resulting morphed map +**************************************************************************/ +int morph_TF_map(int *tfmap, const int mw, const int mh, + const LFSPARMS *lfsparms) +{ + unsigned char *cimage, *mimage, *cptr; + int *mptr; + int i; + + + /* Convert TRUE/FALSE map into a binary byte image. */ + cimage = (unsigned char *)malloc(mw*mh); + if(cimage == (unsigned char *)NULL){ + fprintf(stderr, "ERROR : morph_TF_map : malloc : cimage\n"); + return(-660); + } + + mimage = (unsigned char *)malloc(mw*mh); + if(mimage == (unsigned char *)NULL){ + fprintf(stderr, "ERROR : morph_TF_map : malloc : mimage\n"); + return(-661); + } + + cptr = cimage; + mptr = tfmap; + for(i = 0; i < mw*mh; i++){ + *cptr++ = *mptr++; + } + + dilate_charimage_2(cimage, mimage, mw, mh); + dilate_charimage_2(mimage, cimage, mw, mh); + erode_charimage_2(cimage, mimage, mw, mh); + erode_charimage_2(mimage, cimage, mw, mh); + + cptr = cimage; + mptr = tfmap; + for(i = 0; i < mw*mh; i++){ + *mptr++ = *cptr++; + } + + free(cimage); + free(mimage); + + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: pixelize_map - Takes a block image map and assigns each pixel in the +#cat: image its corresponding block value. This allows block +#cat: values in maps to be directly accessed via pixel addresses. + + Input: + iw - the width (in pixels) of the corresponding image + ih - the height (in pixels) of the corresponding image + imap - input block image map + mw - the width (in blocks) of the map + mh - the height (in blocks) of the map + blocksize - the dimension (in pixels) of each block + Output: + omap - points to the resulting pixelized map + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int pixelize_map(int **omap, const int iw, const int ih, + int *imap, const int mw, const int mh, const int blocksize) +{ + int *pmap; + int ret, x, y; + int *blkoffs, bw, bh, bi; + int *spptr, *pptr; + + pmap = (int *)malloc(iw*ih*sizeof(int)); + if(pmap == (int *)NULL){ + fprintf(stderr, "ERROR : pixelize_map : malloc : pmap\n"); + return(-590); + } + + if((ret = block_offsets(&blkoffs, &bw, &bh, iw, ih, 0, blocksize))){ + return(ret); + } + + if((bw != mw) || (bh != mh)){ + free(blkoffs); + fprintf(stderr, + "ERROR : pixelize_map : block dimensions do not match\n"); + return(-591); + } + + for(bi = 0; bi < mw*mh; bi++){ + spptr = pmap + blkoffs[bi]; + for(y = 0; y < blocksize; y++){ + pptr = spptr; + for(x = 0; x < blocksize; x++){ + *pptr++ = imap[bi]; + } + spptr += iw; + } + } + + /* Deallocate working memory. */ + free(blkoffs); + /* Assign pixelized map to output pointer. */ + *omap = pmap; + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: smooth_direction_map - Takes a vector of integer directions and smooths +#cat: them by analyzing the direction of adjacent neighbors. + + Input: + direction_map - vector of integer block values + mw - width (in blocks) of the map + mh - height (in blocks) of the map + dir2rad - lookup table for converting integer directions + lfsparms - parameters and thresholds for controlling LFS + Output: + imap - vector of smoothed input values +**************************************************************************/ +void smooth_direction_map(int *direction_map, int *low_contrast_map, + const int mw, const int mh, + const DIR2RAD *dir2rad, const LFSPARMS *lfsparms) +{ + int mx, my; + int *dptr, *cptr; + int avrdir, nvalid; + double dir_strength; + + print2log("SMOOTH DIRECTION MAP\n"); + + /* Assign pointers to beginning of both maps. */ + dptr = direction_map; + cptr = low_contrast_map; + + /* Foreach block in maps ... */ + for(my = 0; my < mh; my++){ + for(mx = 0; mx < mw; mx++){ + /* If the current block does NOT have LOW CONTRAST ... */ + if(!*cptr){ + + /* Compute average direction from neighbors, returning the */ + /* number of valid neighbors used in the computation, and */ + /* the "strength" of the average direction. */ + average_8nbr_dir(&avrdir, &dir_strength, &nvalid, + direction_map, mx, my, mw, mh, dir2rad); + + /* If average direction strength is strong enough */ + /* (Ex. thresh==0.2)... */ + if(dir_strength >= lfsparms->dir_strength_min){ + /* If Direction Map direction is valid ... */ + if(*dptr != INVALID_DIR){ + /* Conduct valid neighbor test (Ex. thresh==3)... */ + if(nvalid >= lfsparms->rmv_valid_nbr_min){ + +#ifdef LOG_REPORT /*vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv*/ + fprintf(logfp, " BLOCK %2d (%2d, %2d)\n", + mx+(my*mw), mx, my); + fprintf(logfp, " Average NBR : %2d %6.3f %d\n", + avrdir, dir_strength, nvalid); + fprintf(logfp, " 1. Valid NBR (%d >= %d)\n", + nvalid, lfsparms->rmv_valid_nbr_min); + fprintf(logfp, " Valid Direction = %d\n", *dptr); + fprintf(logfp, " Smoothed Direction = %d\n", avrdir); +#endif /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/ + + /* Reassign valid direction with average direction. */ + *dptr = avrdir; + } + } + /* Otherwise direction is invalid ... */ + else{ + /* Even if DIRECTION_MAP value is invalid, if number of */ + /* valid neighbors is big enough (Ex. thresh==7)... */ + if(nvalid >= lfsparms->smth_valid_nbr_min){ + +#ifdef LOG_REPORT /*vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv*/ + fprintf(logfp, " BLOCK %2d (%2d, %2d)\n", + mx+(my*mw), mx, my); + fprintf(logfp, " Average NBR : %2d %6.3f %d\n", + avrdir, dir_strength, nvalid); + fprintf(logfp, " 2. Invalid NBR (%d >= %d)\n", + nvalid, lfsparms->smth_valid_nbr_min); + fprintf(logfp, " Invalid Direction = %d\n", *dptr); + fprintf(logfp, " Smoothed Direction = %d\n", avrdir); +#endif /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/ + + /* Assign invalid direction with average direction. */ + *dptr = avrdir; + } + } + } + } + /* Otherwise, block has LOW CONTRAST, so keep INVALID direction. */ + + /* Bump to next block in maps. */ + dptr++; + cptr++; + } + } +} + +/************************************************************************* +************************************************************************** +#cat: gen_high_curve_map - Takes a Direction Map and generates a new map +#cat: that flags blocks with HIGH CURVATURE. + + Input: + direction_map - map of blocks containing directional ridge flow + mw - the width (in blocks) of the map + mh - the height (in blocks) of the map + lfsparms - parameters and thresholds for controlling LFS + Output: + ohcmap - points to the created High Curvature Map + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int gen_high_curve_map(int **ohcmap, int *direction_map, + const int mw, const int mh, const LFSPARMS *lfsparms) +{ + int *high_curve_map, mapsize; + int *hptr, *dptr; + int bx, by; + int nvalid, cmeasure, vmeasure; + + mapsize = mw*mh; + + /* Allocate High Curvature Map. */ + high_curve_map = (int *)malloc(mapsize * sizeof(int)); + if(high_curve_map == (int *)NULL){ + fprintf(stderr, + "ERROR: gen_high_curve_map : malloc : high_curve_map\n"); + return(-530); + } + /* Initialize High Curvature Map to FALSE (0). */ + memset(high_curve_map, 0, mapsize*sizeof(int)); + + hptr = high_curve_map; + dptr = direction_map; + + /* Foreach row in maps ... */ + for(by = 0; by < mh; by++){ + /* Foreach column in maps ... */ + for(bx = 0; bx < mw; bx++){ + + /* Count number of valid neighbors around current block ... */ + nvalid = num_valid_8nbrs(direction_map, bx, by, mw, mh); + + /* If valid neighbors exist ... */ + if(nvalid > 0){ + /* If current block's direction is INVALID ... */ + if(*dptr == INVALID_DIR){ + /* If a sufficient number of VALID neighbors exists ... */ + if(nvalid >= lfsparms->vort_valid_nbr_min){ + /* Measure vorticity of neighbors. */ + vmeasure = vorticity(direction_map, bx, by, mw, mh, + lfsparms->num_directions); + /* If vorticity is sufficiently high ... */ + if(vmeasure >= lfsparms->highcurv_vorticity_min) + /* Flag block as HIGH CURVATURE. */ + *hptr = TRUE; + } + } + /* Otherwise block has valid direction ... */ + else{ + /* Measure curvature around the valid block. */ + cmeasure = curvature(direction_map, bx, by, mw, mh, + lfsparms->num_directions); + /* If curvature is sufficiently high ... */ + if(cmeasure >= lfsparms->highcurv_curvature_min) + *hptr = TRUE; + } + } /* Else (nvalid <= 0) */ + + /* Bump pointers to next block in maps. */ + dptr++; + hptr++; + + } /* bx */ + } /* by */ + + /* Assign High Curvature Map to output pointer. */ + *ohcmap = high_curve_map; + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: gen_imap - Computes an IMAP, which is a 2D vector of integer directions, +#cat: where each direction represents the dominant ridge flow in +#cat: a block of the input grayscale image. This routine will +#cat: generate an IMAP for arbitrarily sized, non-square, images. + + Input: + pdata - padded input image data (8 bits [0..256) grayscale) + pw - padded width (in pixels) of the input image + ph - padded height (in pixels) of the input image + dir2rad - lookup table for converting integer directions + dftwaves - structure containing the DFT wave forms + dftgrids - structure containing the rotated pixel grid offsets + lfsparms - parameters and thresholds for controlling LFS + Output: + optr - points to the created IMAP + ow - width (in blocks) of the IMAP + oh - height (in blocks) of the IMAP + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int gen_imap(int **optr, int *ow, int *oh, + unsigned char *pdata, const int pw, const int ph, + const DIR2RAD *dir2rad, const DFTWAVES *dftwaves, + const ROTGRIDS *dftgrids, const LFSPARMS *lfsparms) +{ + int *imap, mw, mh, iw, ih; + int *blkoffs; + int ret; /* return code */ + + /* 1. Compute block offsets for the entire image, accounting for pad */ + /* Block_offsets() assumes square block (grid), so ERROR otherwise. */ + if(dftgrids->grid_w != dftgrids->grid_h){ + fprintf(stderr, "ERROR : gen_imap : DFT grids must be square\n"); + return(-60); + } + /* Compute unpadded image dimensions. */ + iw = pw - (dftgrids->pad<<1); + ih = ph - (dftgrids->pad<<1); + if((ret = block_offsets(&blkoffs, &mw, &mh, iw, ih, + dftgrids->pad, dftgrids->grid_w))){ + return(ret); + } + + /* 2. Generate initial imap */ + if((ret = gen_initial_imap(&imap, blkoffs, mw, mh, pdata, pw, ph, + dftwaves, dftgrids, lfsparms))){ + /* Free memory allocated to this point. */ + free(blkoffs); + return(ret); + } + + /* 3. Remove IMAP directions that are inconsistent with neighbors */ + remove_incon_dirs(imap, mw, mh, dir2rad, lfsparms); + + /* 4. Smooth imap values with their neighbors */ + smooth_imap(imap, mw, mh, dir2rad, lfsparms); + + /* Deallocate working memory. */ + free(blkoffs); + + *optr = imap; + *ow = mw; + *oh = mh; + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: gen_initial_imap - Creates an initial IMAP from the given input image. +#cat: It very important that the image be properly padded so +#cat: that rotated grids along the boudary of the image do not +#cat: access unkown memory. The rotated grids are used by a +#cat: DFT-based analysis to determine the integer directions +#cat: in the IMAP. Typically this initial vector of directions will +#cat: subsequently have weak or inconsistent directions removed +#cat: followed by a smoothing process. + + Input: + blkoffs - offsets to the pixel origin of each block in the padded image + mw - number of blocks horizontally in the padded input image + mh - number of blocks vertically in the padded input image + pdata - padded input image data (8 bits [0..256) grayscale) + pw - width (in pixels) of the padded input image + ph - height (in pixels) of the padded input image + dftwaves - structure containing the DFT wave forms + dftgrids - structure containing the rotated pixel grid offsets + lfsparms - parameters and thresholds for controlling LFS + Output: + optr - points to the newly created IMAP + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int gen_initial_imap(int **optr, int *blkoffs, const int mw, const int mh, + unsigned char *pdata, const int pw, const int ph, + const DFTWAVES *dftwaves, const ROTGRIDS *dftgrids, + const LFSPARMS *lfsparms) +{ + int *imap; + int bi, bsize, blkdir; + int *wis, *powmax_dirs; + double **powers, *powmaxs, *pownorms; + int nstats; + int ret; /* return code */ + + print2log("INITIAL MAP\n"); + + /* Compute total number of blocks in IMAP */ + bsize = mw * mh; + + /* Allocate IMAP memory */ + imap = (int *)malloc(bsize * sizeof(int)); + if(imap == (int *)NULL){ + fprintf(stderr, "ERROR : gen_initial_imap : malloc : imap\n"); + return(-70); + } + + /* Allocate DFT directional power vectors */ + if((ret = alloc_dir_powers(&powers, dftwaves->nwaves, dftgrids->ngrids))){ + /* Free memory allocated to this point. */ + free(imap); + return(ret); + } + + /* Allocate DFT power statistic arrays */ + /* Compute length of statistics arrays. Statistics not needed */ + /* for the first DFT wave, so the length is number of waves - 1. */ + nstats = dftwaves->nwaves - 1; + if((ret = alloc_power_stats(&wis, &powmaxs, &powmax_dirs, + &pownorms, nstats))){ + /* Free memory allocated to this point. */ + free(imap); + free_dir_powers(powers, dftwaves->nwaves); + return(ret); + } + + /* Initialize the imap to -1 */ + memset(imap, INVALID_DIR, bsize * sizeof(int)); + + /* Foreach block in imap ... */ + for(bi = 0; bi < bsize; bi++){ + + print2log(" BLOCK %2d (%2d, %2d)\n", bi, bi%mw, bi/mw); + + /* Compute DFT powers */ + if((ret = dft_dir_powers(powers, pdata, blkoffs[bi], pw, ph, + dftwaves, dftgrids))){ + /* Free memory allocated to this point. */ + free(imap); + free_dir_powers(powers, dftwaves->nwaves); + free(wis); + free(powmaxs); + free(powmax_dirs); + free(pownorms); + return(ret); + } + + /* Compute DFT power statistics, skipping first applied DFT */ + /* wave. This is dependent on how the primary and secondary */ + /* direction tests work below. */ + if((ret = dft_power_stats(wis, powmaxs, powmax_dirs, pownorms, powers, + 1, dftwaves->nwaves, dftgrids->ngrids))){ + /* Free memory allocated to this point. */ + free(imap); + free_dir_powers(powers, dftwaves->nwaves); + free(wis); + free(powmaxs); + free(powmax_dirs); + free(pownorms); + return(ret); + } + +#ifdef LOG_REPORT /*vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv*/ + { int _w; + fprintf(logfp, " Power\n"); + for(_w = 0; _w < nstats; _w++){ + /* Add 1 to wis[w] to create index to original dft_coefs[] */ + fprintf(logfp, " wis[%d] %d %12.3f %2d %9.3f %12.3f\n", + _w, wis[_w]+1, + powmaxs[wis[_w]], powmax_dirs[wis[_w]], pownorms[wis[_w]], + powers[0][powmax_dirs[wis[_w]]]); + } + } +#endif /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/ + + /* Conduct primary direction test */ + blkdir = primary_dir_test(powers, wis, powmaxs, powmax_dirs, + pownorms, nstats, lfsparms); + + if(blkdir != INVALID_DIR) + imap[bi] = blkdir; + else{ + /* Conduct secondary (fork) direction test */ + blkdir = secondary_fork_test(powers, wis, powmaxs, powmax_dirs, + pownorms, nstats, lfsparms); + if(blkdir != INVALID_DIR) + imap[bi] = blkdir; + } + + /* Otherwise current block direction in IMAP remains INVALID */ + + } /* bi */ + + /* Deallocate working memory */ + free_dir_powers(powers, dftwaves->nwaves); + free(wis); + free(powmaxs); + free(powmax_dirs); + free(pownorms); + + *optr = imap; + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: primary_dir_test - Applies the primary set of criteria for selecting +#cat: an IMAP integer direction from a set of DFT results +#cat: computed from a block of image data + + Input: + powers - DFT power computed from each (N) wave frequencies at each + rotation direction in the current image block + wis - sorted order of the highest N-1 frequency power statistics + powmaxs - maximum power for each of the highest N-1 frequencies + powmax_dirs - directions associated with each of the N-1 maximum powers + pownorms - normalized power for each of the highest N-1 frequencies + nstats - N-1 wave frequencies (where N is the length of dft_coefs) + lfsparms - parameters and thresholds for controlling LFS + Return Code: + Zero or Positive - The selected IMAP integer direction + INVALID_DIR - IMAP Integer direction could not be determined +**************************************************************************/ +int primary_dir_test(double **powers, const int *wis, + const double *powmaxs, const int *powmax_dirs, + const double *pownorms, const int nstats, + const LFSPARMS *lfsparms) +{ + int w; + + print2log(" Primary\n"); + + /* Look at max power statistics in decreasing order ... */ + for(w = 0; w < nstats; w++){ + /* 1. Test magnitude of current max power (Ex. Thresh==100000) */ + if((powmaxs[wis[w]] > lfsparms->powmax_min) && + /* 2. Test magnitude of normalized max power (Ex. Thresh==3.8) */ + (pownorms[wis[w]] > lfsparms->pownorm_min) && + /* 3. Test magnitude of power of lowest DFT frequency at current */ + /* max power direction and make sure it is not too big. */ + /* (Ex. Thresh==50000000) */ + (powers[0][powmax_dirs[wis[w]]] <= lfsparms->powmax_max)){ + +#ifdef LOG_REPORT /*vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv*/ + /* Add 1 to wis[w] to create index to original dft_coefs[] */ + fprintf(logfp, + " Selected Wave = %d\n", wis[w]+1); + fprintf(logfp, + " 1. Power Magnitude (%12.3f > %12.3f)\n", + powmaxs[wis[w]], lfsparms->powmax_min); + fprintf(logfp, + " 2. Norm Power Magnitude (%9.3f > %9.3f)\n", + pownorms[wis[w]], lfsparms->pownorm_min); + fprintf(logfp, + " 3. Low Freq Wave Magnitude (%12.3f <= %12.3f)\n", + powers[0][powmax_dirs[wis[w]]], lfsparms->powmax_max); + fprintf(logfp, + " PASSED\n"); + fprintf(logfp, + " Selected Direction = %d\n", + powmax_dirs[wis[w]]); +#endif /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/ + + /* If ALL 3 criteria met, return current max power direction. */ + return(powmax_dirs[wis[w]]); + + } + } + + /* Otherwise test failed. */ + +#ifdef LOG_REPORT /*vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv*/ + fprintf(logfp, " 1. Power Magnitude ( > %12.3f)\n", + lfsparms->powmax_min); + fprintf(logfp, " 2. Norm Power Magnitude ( > %9.3f)\n", + lfsparms->pownorm_min); + fprintf(logfp, " 3. Low Freq Wave Magnitude ( <= %12.3f)\n", + lfsparms->powmax_max); + fprintf(logfp, " FAILED\n"); +#endif /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/ + + return(INVALID_DIR); +} + +/************************************************************************* +************************************************************************** +#cat: secondary_fork_test - Applies a secondary set of criteria for selecting +#cat: an IMAP integer direction from a set of DFT results +#cat: computed from a block of image data. This test +#cat: analyzes the strongest power statistics associated +#cat: with a given frequency and direction and analyses +#cat: small changes in direction to the left and right to +#cat: determine if the block contains a "fork". + + Input: + powers - DFT power computed from each (N) wave frequencies at each + rotation direction in the current image block + wis - sorted order of the highest N-1 frequency power statistics + powmaxs - maximum power for each of the highest N-1 frequencies + powmax_dirs - directions associated with each of the N-1 maximum powers + pownorms - normalized power for each of the highest N-1 frequencies + nstats - N-1 wave frequencies (where N is the length of dft_coefs) + lfsparms - parameters and thresholds for controlling LFS + Return Code: + Zero or Positive - The selected IMAP integer direction + INVALID_DIR - IMAP Integer direction could not be determined +**************************************************************************/ +int secondary_fork_test(double **powers, const int *wis, + const double *powmaxs, const int *powmax_dirs, + const double *pownorms, const int nstats, + const LFSPARMS *lfsparms) +{ + int ldir, rdir; + double fork_pownorm_min, fork_pow_thresh; + +#ifdef LOG_REPORT +{ int firstpart = 0; /* Flag to determine if passed 1st part ... */ + fprintf(logfp, " Secondary\n"); +#endif + + /* Relax the normalized power threshold under fork conditions. */ + fork_pownorm_min = lfsparms->fork_pct_pownorm * lfsparms->pownorm_min; + + /* 1. Test magnitude of largest max power (Ex. Thresh==100000) */ + if((powmaxs[wis[0]] > lfsparms->powmax_min) && + /* 2. Test magnitude of corresponding normalized power */ + /* (Ex. Thresh==2.85) */ + (pownorms[wis[0]] >= fork_pownorm_min) && + /* 3. Test magnitude of power of lowest DFT frequency at largest */ + /* max power direction and make sure it is not too big. */ + /* (Ex. Thresh==50000000) */ + (powers[0][powmax_dirs[wis[0]]] <= lfsparms->powmax_max)){ + +#ifdef LOG_REPORT /*vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv*/ + /* First part passed ... */ + firstpart = 1; + fprintf(logfp, + " Selected Wave = %d\n", wis[0]+1); + fprintf(logfp, + " 1. Power Magnitude (%12.3f > %12.3f)\n", + powmaxs[wis[0]], lfsparms->powmax_min); + fprintf(logfp, + " 2. Norm Power Magnitude (%9.3f >= %9.3f)\n", + pownorms[wis[0]], fork_pownorm_min); + fprintf(logfp, + " 3. Low Freq Wave Magnitude (%12.3f <= %12.3f)\n", + powers[0][powmax_dirs[wis[0]]], lfsparms->powmax_max); +#endif /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/ + + /* Add FORK_INTERVALs to current direction modulo NDIRS */ + rdir = (powmax_dirs[wis[0]] + lfsparms->fork_interval) % + lfsparms->num_directions; + + /* Subtract FORK_INTERVALs from direction modulo NDIRS */ + /* For example, FORK_INTERVAL==2 & NDIRS==16, then */ + /* ldir = (dir - (16-2)) % 16 */ + /* which keeps result in proper modulo range. */ + ldir = (powmax_dirs[wis[0]] + lfsparms->num_directions - + lfsparms->fork_interval) % lfsparms->num_directions; + + print2log(" Left = %d, Current = %d, Right = %d\n", + ldir, powmax_dirs[wis[0]], rdir); + + /* Set forked angle threshold to be a % of the max directional */ + /* power. (Ex. thresh==0.7*powmax) */ + fork_pow_thresh = powmaxs[wis[0]] * lfsparms->fork_pct_powmax; + + /* Look up and test the computed power for the left and right */ + /* fork directions.s */ + /* The power stats (and thus wis) are on the range [0..nwaves-1) */ + /* as the statistics for the first DFT wave are not included. */ + /* The original power vectors exist for ALL DFT waves, therefore */ + /* wis indices must be added by 1 before addressing the original */ + /* powers vector. */ + /* LFS permits one and only one of the fork angles to exceed */ + /* the relative power threshold. */ + if(((powers[wis[0]+1][ldir] <= fork_pow_thresh) || + (powers[wis[0]+1][rdir] <= fork_pow_thresh)) && + ((powers[wis[0]+1][ldir] > fork_pow_thresh) || + (powers[wis[0]+1][rdir] > fork_pow_thresh))){ + +#ifdef LOG_REPORT /*vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv*/ + fprintf(logfp, + " 4. Left Power Magnitude (%12.3f > %12.3f)\n", + powers[wis[0]+1][ldir], fork_pow_thresh); + fprintf(logfp, + " 5. Right Power Magnitude (%12.3f > %12.3f)\n", + powers[wis[0]+1][rdir], fork_pow_thresh); + fprintf(logfp, " PASSED\n"); + fprintf(logfp, + " Selected Direction = %d\n", powmax_dirs[wis[0]]); +#endif /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/ + + /* If ALL the above criteria hold, then return the direction */ + /* of the largest max power. */ + return(powmax_dirs[wis[0]]); + } + } + + /* Otherwise test failed. */ + +#ifdef LOG_REPORT /*vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv*/ + if(!firstpart){ + fprintf(logfp, + " 1. Power Magnitude ( > %12.3f)\n", + lfsparms->powmax_min); + fprintf(logfp, + " 2. Norm Power Magnitude ( > %9.3f)\n", + fork_pownorm_min); + fprintf(logfp, + " 3. Low Freq Wave Magnitude ( <= %12.3f)\n", + lfsparms->powmax_max); + } + else{ + fprintf(logfp, " 4. Left Power Magnitude (%12.3f > %12.3f)\n", + powers[wis[0]+1][ldir], fork_pow_thresh); + fprintf(logfp, " 5. Right Power Magnitude (%12.3f > %12.3f)\n", + powers[wis[0]+1][rdir], fork_pow_thresh); + } + fprintf(logfp, " FAILED\n"); +} /* Close scope of firstpart */ +#endif /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/ + + return(INVALID_DIR); +} + +/************************************************************************* +************************************************************************** +#cat: remove_incon_dirs - Takes a vector of integer directions and removes +#cat: individual directions that are too weak or inconsistent. +#cat: Directions are tested from the center of the IMAP working +#cat: outward in concentric squares, and the process resets to +#cat: the center and continues until no changes take place during +#cat: a complete pass. + + Input: + imap - vector of IMAP integer directions + mw - width (in blocks) of the IMAP + mh - height (in blocks) of the IMAP + dir2rad - lookup table for converting integer directions + lfsparms - parameters and thresholds for controlling LFS + Output: + imap - vector of pruned input values +**************************************************************************/ +void remove_incon_dirs(int *imap, const int mw, const int mh, + const DIR2RAD *dir2rad, const LFSPARMS *lfsparms) +{ + int cx, cy; + int *iptr; + int nremoved; + int lbox, rbox, tbox, bbox; + +#ifdef LOG_REPORT +{ int numpass = 0; + fprintf(logfp, "REMOVE MAP\n"); +#endif + + /* Compute center coords of IMAP */ + cx = mw>>1; + cy = mh>>1; + + /* Do pass, while directions have been removed in a pass ... */ + do{ + +#ifdef LOG_REPORT + /* Count number of complete passes through IMAP */ + ++numpass; + fprintf(logfp, " PASS = %d\n", numpass); +#endif + + /* Reinitialize number of removed directions to 0 */ + nremoved = 0; + + /* Start at center */ + iptr = imap + (cy * mw) + cx; + /* If valid IMAP direction and test for removal is true ... */ + if((*iptr != INVALID_DIR)&& + (remove_dir(imap, cx, cy, mw, mh, dir2rad, lfsparms))){ + + /* Set to INVALID */ + *iptr = INVALID_DIR; + /* Bump number of removed IMAP directions */ + nremoved++; + } + + /* Initialize side indices of concentric boxes */ + lbox = cx-1; + tbox = cy-1; + rbox = cx+1; + bbox = cy+1; + + /* Grow concentric boxes, until ALL edges of imap are exceeded */ + while((lbox >= 0) || (rbox < mw) || (tbox >= 0) || (bbox < mh)){ + + /* test top edge of box */ + if(tbox >= 0) + nremoved += test_top_edge(lbox, tbox, rbox, bbox, imap, mw, mh, + dir2rad, lfsparms); + + /* test right edge of box */ + if(rbox < mw) + nremoved += test_right_edge(lbox, tbox, rbox, bbox, imap, mw, mh, + dir2rad, lfsparms); + + /* test bottom edge of box */ + if(bbox < mh) + nremoved += test_bottom_edge(lbox, tbox, rbox, bbox, imap, mw, mh, + dir2rad, lfsparms); + + /* test left edge of box */ + if(lbox >=0) + nremoved += test_left_edge(lbox, tbox, rbox, bbox, imap, mw, mh, + dir2rad, lfsparms); + + /* Resize current box */ + lbox--; + tbox--; + rbox++; + bbox++; + } + }while(nremoved); + +#ifdef LOG_REPORT +} /* Close scope of numpass */ +#endif + +} + +/************************************************************************* +************************************************************************** +#cat: test_top_edge - Walks the top edge of a concentric square in the IMAP, +#cat: testing directions along the way to see if they should +#cat: be removed due to being too weak or inconsistent with +#cat: respect to their adjacent neighbors. + + Input: + lbox - left edge of current concentric square + tbox - top edge of current concentric square + rbox - right edge of current concentric square + bbox - bottom edge of current concentric square + imap - vector of IMAP integer directions + mw - width (in blocks) of the IMAP + mh - height (in blocks) of the IMAP + dir2rad - lookup table for converting integer directions + lfsparms - parameters and thresholds for controlling LFS + Return Code: + Positive - direction should be removed from IMAP + Zero - direction should NOT be remove from IMAP +**************************************************************************/ +int test_top_edge(const int lbox, const int tbox, const int rbox, + const int bbox, int *imap, const int mw, const int mh, + const DIR2RAD *dir2rad, const LFSPARMS *lfsparms) +{ + int bx, by, sx, ex; + int *iptr, *sptr, *eptr; + int nremoved; + + /* Initialize number of directions removed on edge to 0 */ + nremoved = 0; + + /* Set start pointer to top-leftmost point of box, or set it to */ + /* the leftmost point in the IMAP row (0), whichever is larger. */ + sx = max(lbox, 0); + sptr = imap + (tbox*mw) + sx; + + /* Set end pointer to either 1 point short of the top-rightmost */ + /* point of box, or set it to the rightmost point in the IMAP */ + /* row (lastx=mw-1), whichever is smaller. */ + ex = min(rbox-1, mw-1); + eptr = imap + (tbox*mw) + ex; + + /* For each point on box's edge ... */ + for(iptr = sptr, bx = sx, by = tbox; + iptr <= eptr; + iptr++, bx++){ + /* If valid IMAP direction and test for removal is true ... */ + if((*iptr != INVALID_DIR)&& + (remove_dir(imap, bx, by, mw, mh, dir2rad, lfsparms))){ + /* Set to INVALID */ + *iptr = INVALID_DIR; + /* Bump number of removed IMAP directions */ + nremoved++; + } + } + + /* Return the number of directions removed on edge */ + return(nremoved); +} + +/************************************************************************* +************************************************************************** +#cat: test_right_edge - Walks the right edge of a concentric square in the +#cat: IMAP, testing directions along the way to see if they +#cat: should be removed due to being too weak or inconsistent +#cat: with respect to their adjacent neighbors. + + Input: + lbox - left edge of current concentric square + tbox - top edge of current concentric square + rbox - right edge of current concentric square + bbox - bottom edge of current concentric square + imap - vector of IMAP integer directions + mw - width (in blocks) of the IMAP + mh - height (in blocks) of the IMAP + dir2rad - lookup table for converting integer directions + lfsparms - parameters and thresholds for controlling LFS + Return Code: + Positive - direction should be removed from IMAP + Zero - direction should NOT be remove from IMAP +**************************************************************************/ +int test_right_edge(const int lbox, const int tbox, const int rbox, + const int bbox, int *imap, const int mw, const int mh, + const DIR2RAD *dir2rad, const LFSPARMS *lfsparms) +{ + int bx, by, sy, ey; + int *iptr, *sptr, *eptr; + int nremoved; + + /* Initialize number of directions removed on edge to 0 */ + nremoved = 0; + + /* Set start pointer to top-rightmost point of box, or set it to */ + /* the topmost point in IMAP column (0), whichever is larger. */ + sy = max(tbox, 0); + sptr = imap + (sy*mw) + rbox; + + /* Set end pointer to either 1 point short of the bottom- */ + /* rightmost point of box, or set it to the bottommost point */ + /* in the IMAP column (lasty=mh-1), whichever is smaller. */ + ey = min(bbox-1,mh-1); + eptr = imap + (ey*mw) + rbox; + + /* For each point on box's edge ... */ + for(iptr = sptr, bx = rbox, by = sy; + iptr <= eptr; + iptr+=mw, by++){ + /* If valid IMAP direction and test for removal is true ... */ + if((*iptr != INVALID_DIR)&& + (remove_dir(imap, bx, by, mw, mh, dir2rad, lfsparms))){ + /* Set to INVALID */ + *iptr = INVALID_DIR; + /* Bump number of removed IMAP directions */ + nremoved++; + } + } + + /* Return the number of directions removed on edge */ + return(nremoved); +} + +/************************************************************************* +************************************************************************** +#cat: test_bottom_edge - Walks the bottom edge of a concentric square in the +#cat: IMAP, testing directions along the way to see if they +#cat: should be removed due to being too weak or inconsistent +#cat: with respect to their adjacent neighbors. + Input: + lbox - left edge of current concentric square + tbox - top edge of current concentric square + rbox - right edge of current concentric square + bbox - bottom edge of current concentric square + imap - vector of IMAP integer directions + mw - width (in blocks) of the IMAP + mh - height (in blocks) of the IMAP + dir2rad - lookup table for converting integer directions + lfsparms - parameters and thresholds for controlling LFS + Return Code: + Positive - direction should be removed from IMAP + Zero - direction should NOT be remove from IMAP +**************************************************************************/ +int test_bottom_edge(const int lbox, const int tbox, const int rbox, + const int bbox, int *imap, const int mw, const int mh, + const DIR2RAD *dir2rad, const LFSPARMS *lfsparms) +{ + int bx, by, sx, ex; + int *iptr, *sptr, *eptr; + int nremoved; + + /* Initialize number of directions removed on edge to 0 */ + nremoved = 0; + + /* Set start pointer to bottom-rightmost point of box, or set it to the */ + /* rightmost point in the IMAP ROW (lastx=mw-1), whichever is smaller. */ + sx = min(rbox, mw-1); + sptr = imap + (bbox*mw) + sx; + + /* Set end pointer to either 1 point short of the bottom- */ + /* lefttmost point of box, or set it to the leftmost point */ + /* in the IMAP row (x=0), whichever is larger. */ + ex = max(lbox-1, 0); + eptr = imap + (bbox*mw) + ex; + + /* For each point on box's edge ... */ + for(iptr = sptr, bx = sx, by = bbox; + iptr >= eptr; + iptr--, bx--){ + /* If valid IMAP direction and test for removal is true ... */ + if((*iptr != INVALID_DIR)&& + (remove_dir(imap, bx, by, mw, mh, dir2rad, lfsparms))){ + /* Set to INVALID */ + *iptr = INVALID_DIR; + /* Bump number of removed IMAP directions */ + nremoved++; + } + } + + /* Return the number of directions removed on edge */ + return(nremoved); +} + +/************************************************************************* +************************************************************************** +#cat: test_left_edge - Walks the left edge of a concentric square in the IMAP, +#cat: testing directions along the way to see if they should +#cat: be removed due to being too weak or inconsistent with +#cat: respect to their adjacent neighbors. + + Input: + lbox - left edge of current concentric square + tbox - top edge of current concentric square + rbox - right edge of current concentric square + bbox - bottom edge of current concentric square + imap - vector of IMAP integer directions + mw - width (in blocks) of the IMAP + mh - height (in blocks) of the IMAP + dir2rad - lookup table for converting integer directions + lfsparms - parameters and thresholds for controlling LFS + Return Code: + Positive - direction should be removed from IMAP + Zero - direction should NOT be remove from IMAP +**************************************************************************/ +int test_left_edge(const int lbox, const int tbox, const int rbox, + const int bbox, int *imap, const int mw, const int mh, + const DIR2RAD *dir2rad, const LFSPARMS *lfsparms) +{ + int bx, by, sy, ey; + int *iptr, *sptr, *eptr; + int nremoved; + + /* Initialize number of directions removed on edge to 0 */ + nremoved = 0; + + /* Set start pointer to bottom-leftmost point of box, or set it to */ + /* the bottommost point in IMAP column (lasty=mh-1), whichever */ + /* is smaller. */ + sy = min(bbox, mh-1); + sptr = imap + (sy*mw) + lbox; + + /* Set end pointer to either 1 point short of the top-leftmost */ + /* point of box, or set it to the topmost point in the IMAP */ + /* column (y=0), whichever is larger. */ + ey = max(tbox-1, 0); + eptr = imap + (ey*mw) + lbox; + + /* For each point on box's edge ... */ + for(iptr = sptr, bx = lbox, by = sy; + iptr >= eptr; + iptr-=mw, by--){ + /* If valid IMAP direction and test for removal is true ... */ + if((*iptr != INVALID_DIR)&& + (remove_dir(imap, bx, by, mw, mh, dir2rad, lfsparms))){ + /* Set to INVALID */ + *iptr = INVALID_DIR; + /* Bump number of removed IMAP directions */ + nremoved++; + } + } + + /* Return the number of directions removed on edge */ + return(nremoved); +} + +/************************************************************************* +************************************************************************** +#cat: remove_dir - Determines if an IMAP direction should be removed based +#cat: on analyzing its adjacent neighbors + + Input: + imap - vector of IMAP integer directions + mx - IMAP X-coord of the current direction being tested + my - IMPA Y-coord of the current direction being tested + mw - width (in blocks) of the IMAP + mh - height (in blocks) of the IMAP + dir2rad - lookup table for converting integer directions + lfsparms - parameters and thresholds for controlling LFS + Return Code: + Positive - direction should be removed from IMAP + Zero - direction should NOT be remove from IMAP +**************************************************************************/ +int remove_dir(int *imap, const int mx, const int my, + const int mw, const int mh, const DIR2RAD *dir2rad, + const LFSPARMS *lfsparms) +{ + int avrdir, nvalid, dist; + double dir_strength; + + /* Compute average direction from neighbors, returning the */ + /* number of valid neighbors used in the computation, and */ + /* the "strength" of the average direction. */ + average_8nbr_dir(&avrdir, &dir_strength, &nvalid, imap, mx, my, mw, mh, + dir2rad); + + /* Conduct valid neighbor test (Ex. thresh==3) */ + if(nvalid < lfsparms->rmv_valid_nbr_min){ + +#ifdef LOG_REPORT /*vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv*/ + fprintf(logfp, " BLOCK %2d (%2d, %2d)\n", + mx+(my*mw), mx, my); + fprintf(logfp, " Average NBR : %2d %6.3f %d\n", + avrdir, dir_strength, nvalid); + fprintf(logfp, " 1. Valid NBR (%d < %d)\n", + nvalid, lfsparms->rmv_valid_nbr_min); +#endif /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/ + + return(1); + } + + /* If stregnth of average neighbor direction is large enough to */ + /* put credence in ... (Ex. thresh==0.2) */ + if(dir_strength >= lfsparms->dir_strength_min){ + + /* Conduct direction distance test (Ex. thresh==3) */ + /* Compute minimum absolute distance between current and */ + /* average directions accounting for wrapping from 0 to NDIRS. */ + dist = abs(avrdir - *(imap+(my*mw)+mx)); + dist = min(dist, dir2rad->ndirs-dist); + if(dist > lfsparms->dir_distance_max){ + +#ifdef LOG_REPORT /*vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv*/ + fprintf(logfp, " BLOCK %2d (%2d, %2d)\n", + mx+(my*mw), mx, my); + fprintf(logfp, " Average NBR : %2d %6.3f %d\n", + avrdir, dir_strength, nvalid); + fprintf(logfp, " 1. Valid NBR (%d < %d)\n", + nvalid, lfsparms->rmv_valid_nbr_min); + fprintf(logfp, " 2. Direction Strength (%6.3f >= %6.3f)\n", + dir_strength, lfsparms->dir_strength_min); + fprintf(logfp, " Current Dir = %d, Average Dir = %d\n", + *(imap+(my*mw)+mx), avrdir); + fprintf(logfp, " 3. Direction Distance (%d > %d)\n", + dist, lfsparms->dir_distance_max); +#endif /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/ + + return(2); + } + } + + /* Otherwise, the strength of the average direciton is not strong enough */ + /* to put credence in, so leave the current block's directon alone. */ + + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: average_8nbr_dir - Given an IMAP direction, computes an average +#cat: direction from its adjacent 8 neighbors returning +#cat: the average direction, its strength, and the +#cat: number of valid direction in the neighborhood. + + Input: + imap - vector of IMAP integer directions + mx - IMAP X-coord of the current direction + my - IMPA Y-coord of the current direction + mw - width (in blocks) of the IMAP + mh - height (in blocks) of the IMAP + dir2rad - lookup table for converting integer directions + Output: + avrdir - the average direction computed from neighbors + dir_strenght - the strength of the average direction + nvalid - the number of valid directions used to compute the + average +**************************************************************************/ +void average_8nbr_dir(int *avrdir, double *dir_strength, int *nvalid, + int *imap, const int mx, const int my, + const int mw, const int mh, + const DIR2RAD *dir2rad) +{ + int *iptr; + int e,w,n,s; + double cospart, sinpart; + double pi2, pi_factor, theta; + double avr; + + /* Compute neighbor coordinates to current IMAP direction */ + e = mx+1; /* East */ + w = mx-1; /* West */ + n = my-1; /* North */ + s = my+1; /* South */ + + /* Intialize accumulators */ + *nvalid = 0; + cospart = 0.0; + sinpart = 0.0; + + /* 1. Test NW */ + /* If NW point within IMAP boudaries ... */ + if((w >= 0) && (n >= 0)){ + iptr = imap + (n*mw) + w; + /* If valid direction ... */ + if(*iptr != INVALID_DIR){ + /* Accumulate cosine and sine components of the direction */ + cospart += dir2rad->cos[*iptr]; + sinpart += dir2rad->sin[*iptr]; + /* Bump number of accumulated directions */ + (*nvalid)++; + } + } + + /* 2. Test N */ + /* If N point within IMAP boudaries ... */ + if(n >= 0){ + iptr = imap + (n*mw) + mx; + /* If valid direction ... */ + if(*iptr != INVALID_DIR){ + /* Accumulate cosine and sine components of the direction */ + cospart += dir2rad->cos[*iptr]; + sinpart += dir2rad->sin[*iptr]; + /* Bump number of accumulated directions */ + (*nvalid)++; + } + } + + /* 3. Test NE */ + /* If NE point within IMAP boudaries ... */ + if((e < mw) && (n >= 0)){ + iptr = imap + (n*mw) + e; + /* If valid direction ... */ + if(*iptr != INVALID_DIR){ + /* Accumulate cosine and sine components of the direction */ + cospart += dir2rad->cos[*iptr]; + sinpart += dir2rad->sin[*iptr]; + /* Bump number of accumulated directions */ + (*nvalid)++; + } + } + + /* 4. Test E */ + /* If E point within IMAP boudaries ... */ + if(e < mw){ + iptr = imap + (my*mw) + e; + /* If valid direction ... */ + if(*iptr != INVALID_DIR){ + /* Accumulate cosine and sine components of the direction */ + cospart += dir2rad->cos[*iptr]; + sinpart += dir2rad->sin[*iptr]; + /* Bump number of accumulated directions */ + (*nvalid)++; + } + } + + /* 5. Test SE */ + /* If SE point within IMAP boudaries ... */ + if((e < mw) && (s < mh)){ + iptr = imap + (s*mw) + e; + /* If valid direction ... */ + if(*iptr != INVALID_DIR){ + /* Accumulate cosine and sine components of the direction */ + cospart += dir2rad->cos[*iptr]; + sinpart += dir2rad->sin[*iptr]; + /* Bump number of accumulated directions */ + (*nvalid)++; + } + } + + /* 6. Test S */ + /* If S point within IMAP boudaries ... */ + if(s < mh){ + iptr = imap + (s*mw) + mx; + /* If valid direction ... */ + if(*iptr != INVALID_DIR){ + /* Accumulate cosine and sine components of the direction */ + cospart += dir2rad->cos[*iptr]; + sinpart += dir2rad->sin[*iptr]; + /* Bump number of accumulated directions */ + (*nvalid)++; + } + } + + /* 7. Test SW */ + /* If SW point within IMAP boudaries ... */ + if((w >= 0) && (s < mh)){ + iptr = imap + (s*mw) + w; + /* If valid direction ... */ + if(*iptr != INVALID_DIR){ + /* Accumulate cosine and sine components of the direction */ + cospart += dir2rad->cos[*iptr]; + sinpart += dir2rad->sin[*iptr]; + /* Bump number of accumulated directions */ + (*nvalid)++; + } + } + + /* 8. Test W */ + /* If W point within IMAP boudaries ... */ + if(w >= 0){ + iptr = imap + (my*mw) + w; + /* If valid direction ... */ + if(*iptr != INVALID_DIR){ + /* Accumulate cosine and sine components of the direction */ + cospart += dir2rad->cos[*iptr]; + sinpart += dir2rad->sin[*iptr]; + /* Bump number of accumulated directions */ + (*nvalid)++; + } + } + + /* If there were no neighbors found with valid direction ... */ + if(*nvalid == 0){ + /* Return INVALID direction. */ + *dir_strength = 0; + *avrdir = INVALID_DIR; + return; + } + + /* Compute averages of accumulated cosine and sine direction components */ + cospart /= (double)(*nvalid); + sinpart /= (double)(*nvalid); + + /* Compute directional strength as hypotenuse (without sqrt) of average */ + /* cosine and sine direction components. Believe this value will be on */ + /* the range of [0 .. 1]. */ + *dir_strength = (cospart * cospart) + (sinpart * sinpart); + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when comparing doubles. */ + *dir_strength = trunc_dbl_precision(*dir_strength, TRUNC_SCALE); + + /* If the direction strength is not sufficiently high ... */ + if(*dir_strength < DIR_STRENGTH_MIN){ + /* Return INVALID direction. */ + *dir_strength = 0; + *avrdir = INVALID_DIR; + return; + } + + /* Compute angle (in radians) from Arctan of avarage */ + /* cosine and sine direction components. I think this order */ + /* is necessary because 0 direction is vertical and positive */ + /* direction is clockwise. */ + theta = atan2(sinpart, cospart); + + /* Atan2 returns theta on range [-PI..PI]. Adjust theta so that */ + /* it is on the range [0..2PI]. */ + pi2 = 2*M_PI; + theta += pi2; + theta = fmod(theta, pi2); + + /* Pi_factor sets the period of the trig functions to NDIRS units in x. */ + /* For example, if NDIRS==16, then pi_factor = 2(PI/16) = .3926... */ + /* Dividing theta (in radians) by this factor ((1/pi_factor)==2.546...) */ + /* will produce directions on the range [0..NDIRS]. */ + pi_factor = pi2/(double)dir2rad->ndirs; /* 2(M_PI/ndirs) */ + + /* Round off the direction and return it as an average direction */ + /* for the neighborhood. */ + avr = theta / pi_factor; + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + avr = trunc_dbl_precision(avr, TRUNC_SCALE); + *avrdir = sround(avr); + + /* Really do need to map values > NDIRS back onto [0..NDIRS) range. */ + *avrdir %= dir2rad->ndirs; +} + +/************************************************************************* +************************************************************************** +#cat: num_valid_8nbrs - Given a block in an IMAP, counts the number of +#cat: immediate neighbors that have a valid IMAP direction. + + Input: + imap - 2-D vector of directional ridge flows + mx - horizontal coord of current block in IMAP + my - vertical coord of current block in IMAP + mw - width (in blocks) of the IMAP + mh - height (in blocks) of the IMAP + Return Code: + Non-negative - the number of valid IMAP neighbors +**************************************************************************/ +int num_valid_8nbrs(int *imap, const int mx, const int my, + const int mw, const int mh) +{ + int e_ind, w_ind, n_ind, s_ind; + int nvalid; + + /* Initialize VALID IMAP counter to zero. */ + nvalid = 0; + + /* Compute neighbor coordinates to current IMAP direction */ + e_ind = mx+1; /* East index */ + w_ind = mx-1; /* West index */ + n_ind = my-1; /* North index */ + s_ind = my+1; /* South index */ + + /* 1. Test NW IMAP value. */ + /* If neighbor indices are within IMAP boundaries and it is VALID ... */ + if((w_ind >= 0) && (n_ind >= 0) && (*(imap + (n_ind*mw) + w_ind) >= 0)) + /* Bump VALID counter. */ + nvalid++; + + /* 2. Test N IMAP value. */ + if((n_ind >= 0) && (*(imap + (n_ind*mw) + mx) >= 0)) + nvalid++; + + /* 3. Test NE IMAP value. */ + if((n_ind >= 0) && (e_ind < mw) && (*(imap + (n_ind*mw) + e_ind) >= 0)) + nvalid++; + + /* 4. Test E IMAP value. */ + if((e_ind < mw) && (*(imap + (my*mw) + e_ind) >= 0)) + nvalid++; + + /* 5. Test SE IMAP value. */ + if((e_ind < mw) && (s_ind < mh) && (*(imap + (s_ind*mw) + e_ind) >= 0)) + nvalid++; + + /* 6. Test S IMAP value. */ + if((s_ind < mh) && (*(imap + (s_ind*mw) + mx) >= 0)) + nvalid++; + + /* 7. Test SW IMAP value. */ + if((w_ind >= 0) && (s_ind < mh) && (*(imap + (s_ind*mw) + w_ind) >= 0)) + nvalid++; + + /* 8. Test W IMAP value. */ + if((w_ind >= 0) && (*(imap + (my*mw) + w_ind) >= 0)) + nvalid++; + + /* Return number of neighbors with VALID IMAP values. */ + return(nvalid); +} + +/************************************************************************* +************************************************************************** +#cat: smooth_imap - Takes a vector of integer directions and smooths them +#cat: by analyzing the direction of adjacent neighbors. + + Input: + imap - vector of IMAP integer directions + mw - width (in blocks) of the IMAP + mh - height (in blocks) of the IMAP + dir2rad - lookup table for converting integer directions + lfsparms - parameters and thresholds for controlling LFS + Output: + imap - vector of smoothed input values +**************************************************************************/ +void smooth_imap(int *imap, const int mw, const int mh, + const DIR2RAD *dir2rad, const LFSPARMS *lfsparms) +{ + int mx, my; + int *iptr; + int avrdir, nvalid; + double dir_strength; + + print2log("SMOOTH MAP\n"); + + iptr = imap; + for(my = 0; my < mh; my++){ + for(mx = 0; mx < mw; mx++){ + /* Compute average direction from neighbors, returning the */ + /* number of valid neighbors used in the computation, and */ + /* the "strength" of the average direction. */ + average_8nbr_dir(&avrdir, &dir_strength, &nvalid, + imap, mx, my, mw, mh, dir2rad); + + /* If average direction strength is strong enough */ + /* (Ex. thresh==0.2)... */ + if(dir_strength >= lfsparms->dir_strength_min){ + /* If IMAP direction is valid ... */ + if(*iptr != INVALID_DIR){ + /* Conduct valid neighbor test (Ex. thresh==3)... */ + if(nvalid >= lfsparms->rmv_valid_nbr_min){ + +#ifdef LOG_REPORT /*vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv*/ + fprintf(logfp, " BLOCK %2d (%2d, %2d)\n", + mx+(my*mw), mx, my); + fprintf(logfp, " Average NBR : %2d %6.3f %d\n", + avrdir, dir_strength, nvalid); + fprintf(logfp, " 1. Valid NBR (%d >= %d)\n", + nvalid, lfsparms->rmv_valid_nbr_min); + fprintf(logfp, " Valid Direction = %d\n", *iptr); + fprintf(logfp, " Smoothed Direction = %d\n", avrdir); +#endif /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/ + + /* Reassign valid IMAP direction with average direction. */ + *iptr = avrdir; + } + } + /* Otherwise IMAP direction is invalid ... */ + else{ + /* Even if IMAP value is invalid, if number of valid */ + /* neighbors is big enough (Ex. thresh==7)... */ + if(nvalid >= lfsparms->smth_valid_nbr_min){ + +#ifdef LOG_REPORT /*vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv*/ + fprintf(logfp, " BLOCK %2d (%2d, %2d)\n", + mx+(my*mw), mx, my); + fprintf(logfp, " Average NBR : %2d %6.3f %d\n", + avrdir, dir_strength, nvalid); + fprintf(logfp, " 2. Invalid NBR (%d >= %d)\n", + nvalid, lfsparms->smth_valid_nbr_min); + fprintf(logfp, " Invalid Direction = %d\n", *iptr); + fprintf(logfp, " Smoothed Direction = %d\n", avrdir); +#endif /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/ + + /* Assign invalid IMAP direction with average direction. */ + *iptr = avrdir; + } + } + } + + /* Bump to next IMAP direction. */ + iptr++; + } + } +} + +/************************************************************************* +************************************************************************** +#cat: gen_nmap - Computes an NMAP from its associated 2D vector of integer +#cat: directions (IMAP). Each value in the NMAP either represents +#cat: a direction of dominant ridge flow in a block of the input +#cat: grayscale image, or it contains a codes describing why such +#cat: a direction was not procuded. +#cat: For example, blocks near areas of high-curvature (such as +#cat: with cores and deltas) will not produce reliable IMAP +#cat: directions. + + Input: + imap - associated input vector of IMAP directions + mw - the width (in blocks) of the IMAP + mh - the height (in blocks) of the IMAP + lfsparms - parameters and thresholds for controlling LFS + Output: + optr - points to the created NMAP + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int gen_nmap(int **optr, int *imap, const int mw, const int mh, + const LFSPARMS *lfsparms) +{ + int *nmap, mapsize; + int *nptr, *iptr; + int bx, by; + int nvalid, cmeasure, vmeasure; + + mapsize = mw*mh; + nmap = (int *)malloc(mapsize * sizeof(int)); + if(nmap == (int *)NULL){ + fprintf(stderr, "ERROR: gen_nmap : malloc : nmap\n"); + return(-120); + } + + nptr = nmap; + iptr = imap; + /* Foreach row in IMAP ... */ + for(by = 0; by < mh; by++){ + /* Foreach column in IMAP ... */ + for(bx = 0; bx < mw; bx++){ + /* Count number of valid neighbors around current block ... */ + nvalid = num_valid_8nbrs(imap, bx, by, mw, mh); + /* If block has no valid neighbors ... */ + if(nvalid == 0) + /* Set NMAP value to NO VALID NEIGHBORS */ + *nptr = NO_VALID_NBRS; + else{ + /* If current IMAP value is INVALID ... */ + if(*iptr == INVALID_DIR){ + /* If not enough VALID neighbors ... */ + if(nvalid < lfsparms->vort_valid_nbr_min){ + /* Set NMAP value to INVALID */ + *nptr = INVALID_DIR; + } + else{ + /* Otherwise measure vorticity of neighbors. */ + vmeasure = vorticity(imap, bx, by, mw, mh, + lfsparms->num_directions); + /* If vorticity too low ... */ + if(vmeasure < lfsparms->highcurv_vorticity_min) + *nptr = INVALID_DIR; + else + /* Otherwise high-curvature area (Ex. core or delta). */ + *nptr = HIGH_CURVATURE; + } + } + /* Otherwise VALID IMAP value ... */ + else{ + /* Measure curvature around the VALID IMAP block. */ + cmeasure = curvature(imap, bx, by, mw, mh, + lfsparms->num_directions); + /* If curvature is too high ... */ + if(cmeasure >= lfsparms->highcurv_curvature_min) + *nptr = HIGH_CURVATURE; + else + /* Otherwise acceptable amount of curature, so assign */ + /* VALID IMAP value to NMAP. */ + *nptr = *iptr; + } + } /* end else (nvalid > 0) */ + /* BUMP IMAP and NMAP pointers. */ + iptr++; + nptr++; + + } /* bx */ + } /* by */ + + *optr = nmap; + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: vorticity - Measures the amount of cummulative curvature incurred +#cat: among the IMAP neighbors of the given block. + + Input: + imap - 2D vector of ridge flow directions + mx - horizontal coord of current IMAP block + my - vertical coord of current IMAP block + mw - width (in blocks) of the IMAP + mh - height (in blocks) of the IMAP + ndirs - number of possible directions in the IMAP + Return Code: + Non-negative - the measured vorticity among the neighbors +**************************************************************************/ +int vorticity(int *imap, const int mx, const int my, + const int mw, const int mh, const int ndirs) +{ + int e_ind, w_ind, n_ind, s_ind; + int nw_val, n_val, ne_val, e_val, se_val, s_val, sw_val, w_val; + int vmeasure; + + /* Compute neighbor coordinates to current IMAP direction */ + e_ind = mx+1; /* East index */ + w_ind = mx-1; /* West index */ + n_ind = my-1; /* North index */ + s_ind = my+1; /* South index */ + + /* 1. Get NW IMAP value. */ + /* If neighbor indices are within IMAP boundaries ... */ + if((w_ind >= 0) && (n_ind >= 0)) + /* Set neighbor value to IMAP value. */ + nw_val = *(imap + (n_ind*mw) + w_ind); + else + /* Otherwise, set the neighbor value to INVALID. */ + nw_val = INVALID_DIR; + + /* 2. Get N IMAP value. */ + if(n_ind >= 0) + n_val = *(imap + (n_ind*mw) + mx); + else + n_val = INVALID_DIR; + + /* 3. Get NE IMAP value. */ + if((n_ind >= 0) && (e_ind < mw)) + ne_val = *(imap + (n_ind*mw) + e_ind); + else + ne_val = INVALID_DIR; + + /* 4. Get E IMAP value. */ + if(e_ind < mw) + e_val = *(imap + (my*mw) + e_ind); + else + e_val = INVALID_DIR; + + /* 5. Get SE IMAP value. */ + if((e_ind < mw) && (s_ind < mh)) + se_val = *(imap + (s_ind*mw) + e_ind); + else + se_val = INVALID_DIR; + + /* 6. Get S IMAP value. */ + if(s_ind < mh) + s_val = *(imap + (s_ind*mw) + mx); + else + s_val = INVALID_DIR; + + /* 7. Get SW IMAP value. */ + if((w_ind >= 0) && (s_ind < mh)) + sw_val = *(imap + (s_ind*mw) + w_ind); + else + sw_val = INVALID_DIR; + + /* 8. Get W IMAP value. */ + if(w_ind >= 0) + w_val = *(imap + (my*mw) + w_ind); + else + w_val = INVALID_DIR; + + /* Now that we have all IMAP neighbors, accumulate vorticity between */ + /* the neighboring directions. */ + + /* Initialize vorticity accumulator to zero. */ + vmeasure = 0; + + /* 1. NW & N */ + accum_nbr_vorticity(&vmeasure, nw_val, n_val, ndirs); + + /* 2. N & NE */ + accum_nbr_vorticity(&vmeasure, n_val, ne_val, ndirs); + + /* 3. NE & E */ + accum_nbr_vorticity(&vmeasure, ne_val, e_val, ndirs); + + /* 4. E & SE */ + accum_nbr_vorticity(&vmeasure, e_val, se_val, ndirs); + + /* 5. SE & S */ + accum_nbr_vorticity(&vmeasure, se_val, s_val, ndirs); + + /* 6. S & SW */ + accum_nbr_vorticity(&vmeasure, s_val, sw_val, ndirs); + + /* 7. SW & W */ + accum_nbr_vorticity(&vmeasure, sw_val, w_val, ndirs); + + /* 8. W & NW */ + accum_nbr_vorticity(&vmeasure, w_val, nw_val, ndirs); + + /* Return the accumulated vorticity measure. */ + return(vmeasure); +} + +/************************************************************************* +************************************************************************** +#cat: accum_nbor_vorticity - Accumlates the amount of curvature measures +#cat: between neighboring IMAP blocks. + + Input: + dir1 - first neighbor's integer IMAP direction + dir2 - second neighbor's integer IMAP direction + ndirs - number of possible IMAP directions + Output: + vmeasure - accumulated vorticity among neighbors measured so far +**************************************************************************/ +void accum_nbr_vorticity(int *vmeasure, const int dir1, const int dir2, + const int ndirs) +{ + int dist; + + /* Measure difference in direction between a pair of neighboring */ + /* directions. */ + /* If both neighbors are not equal and both are VALID ... */ + if((dir1 != dir2) && (dir1 >= 0)&&(dir2 >= 0)){ + /* Measure the clockwise distance from the first to the second */ + /* directions. */ + dist = dir2 - dir1; + /* If dist is negative, then clockwise distance must wrap around */ + /* the high end of the direction range. For example: */ + /* dir1 = 8 */ + /* dir2 = 3 */ + /* and ndirs = 16 */ + /* 3 - 8 = -5 */ + /* so 16 - 5 = 11 (the clockwise distance from 8 to 3) */ + if(dist < 0) + dist += ndirs; + /* If the change in clockwise direction is larger than 90 degrees as */ + /* in total the total number of directions covers 180 degrees. */ + if(dist > (ndirs>>1)) + /* Decrement the vorticity measure. */ + (*vmeasure)--; + else + /* Otherwise, bump the vorticity measure. */ + (*vmeasure)++; + } + /* Otherwise both directions are either equal or */ + /* one or both directions are INVALID, so ignore. */ +} + +/************************************************************************* +************************************************************************** +#cat: curvature - Measures the largest change in direction between the +#cat: current IMAP direction and its immediate neighbors. + + Input: + imap - 2D vector of ridge flow directions + mx - horizontal coord of current IMAP block + my - vertical coord of current IMAP block + mw - width (in blocks) of the IMAP + mh - height (in blocks) of the IMAP + ndirs - number of possible directions in the IMAP + Return Code: + Non-negative - maximum change in direction found (curvature) + Negative - No valid neighbor found to measure change in direction +**************************************************************************/ +int curvature(int *imap, const int mx, const int my, + const int mw, const int mh, const int ndirs) +{ + int *iptr; + int e_ind, w_ind, n_ind, s_ind; + int nw_val, n_val, ne_val, e_val, se_val, s_val, sw_val, w_val; + int cmeasure, dist; + + /* Compute neighbor coordinates to current IMAP direction */ + e_ind = mx+1; /* East index */ + w_ind = mx-1; /* West index */ + n_ind = my-1; /* North index */ + s_ind = my+1; /* South index */ + + /* 1. Get NW IMAP value. */ + /* If neighbor indices are within IMAP boundaries ... */ + if((w_ind >= 0) && (n_ind >= 0)) + /* Set neighbor value to IMAP value. */ + nw_val = *(imap + (n_ind*mw) + w_ind); + else + /* Otherwise, set the neighbor value to INVALID. */ + nw_val = INVALID_DIR; + + /* 2. Get N IMAP value. */ + if(n_ind >= 0) + n_val = *(imap + (n_ind*mw) + mx); + else + n_val = INVALID_DIR; + + /* 3. Get NE IMAP value. */ + if((n_ind >= 0) && (e_ind < mw)) + ne_val = *(imap + (n_ind*mw) + e_ind); + else + ne_val = INVALID_DIR; + + /* 4. Get E IMAP value. */ + if(e_ind < mw) + e_val = *(imap + (my*mw) + e_ind); + else + e_val = INVALID_DIR; + + /* 5. Get SE IMAP value. */ + if((e_ind < mw) && (s_ind < mh)) + se_val = *(imap + (s_ind*mw) + e_ind); + else + se_val = INVALID_DIR; + + /* 6. Get S IMAP value. */ + if(s_ind < mh) + s_val = *(imap + (s_ind*mw) + mx); + else + s_val = INVALID_DIR; + + /* 7. Get SW IMAP value. */ + if((w_ind >= 0) && (s_ind < mh)) + sw_val = *(imap + (s_ind*mw) + w_ind); + else + sw_val = INVALID_DIR; + + /* 8. Get W IMAP value. */ + if(w_ind >= 0) + w_val = *(imap + (my*mw) + w_ind); + else + w_val = INVALID_DIR; + + /* Now that we have all IMAP neighbors, determine largest change in */ + /* direction from current block to each of its 8 VALID neighbors. */ + + /* Initialize pointer to current IMAP value. */ + iptr = imap + (my*mw) + mx; + + /* Initialize curvature measure to negative as closest_dir_dist() */ + /* always returns -1=INVALID or a positive value. */ + cmeasure = -1; + + /* 1. With NW */ + /* Compute closest distance between neighboring directions. */ + dist = closest_dir_dist(*iptr, nw_val, ndirs); + /* Keep track of maximum. */ + if(dist > cmeasure) + cmeasure = dist; + + /* 2. With N */ + dist = closest_dir_dist(*iptr, n_val, ndirs); + if(dist > cmeasure) + cmeasure = dist; + + /* 3. With NE */ + dist = closest_dir_dist(*iptr, ne_val, ndirs); + if(dist > cmeasure) + cmeasure = dist; + + /* 4. With E */ + dist = closest_dir_dist(*iptr, e_val, ndirs); + if(dist > cmeasure) + cmeasure = dist; + + /* 5. With SE */ + dist = closest_dir_dist(*iptr, se_val, ndirs); + if(dist > cmeasure) + cmeasure = dist; + + /* 6. With S */ + dist = closest_dir_dist(*iptr, s_val, ndirs); + if(dist > cmeasure) + cmeasure = dist; + + /* 7. With SW */ + dist = closest_dir_dist(*iptr, sw_val, ndirs); + if(dist > cmeasure) + cmeasure = dist; + + /* 8. With W */ + dist = closest_dir_dist(*iptr, w_val, ndirs); + if(dist > cmeasure) + cmeasure = dist; + + /* Return maximum difference between current block's IMAP direction */ + /* and the rest of its VALID neighbors. */ + return(cmeasure); +} diff --git a/libfprint/nbis/mindtct/matchpat.c b/libfprint/nbis/mindtct/matchpat.c new file mode 100644 index 00000000..ed4fc7c4 --- /dev/null +++ b/libfprint/nbis/mindtct/matchpat.c @@ -0,0 +1,271 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: MATCHPAT.C + AUTHOR: Michael D. Garris + DATE: 05/11/1999 + UPDATED: 03/16/2005 by MDG + + Contains routines responsible for matching minutia feature + patterns as part of the NIST Latent Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + match_1st_pair() + match_2nd_pair() + match_3rd_pair() + skip_repeated_horizontal_pair() + skip_repeated_vertical_pair() +***********************************************************************/ + +#include +#include + +/************************************************************************* +************************************************************************** +#cat: match_1st_pair - Determines which of the feature_patterns[] have their +#cat: first pixel pair match the specified pixel pair. + + Input: + p1 - first pixel value of pair + p2 - second pixel value of pair + Output: + possible - list of matching feature_patterns[] indices + nposs - number of matches + Return Code: + nposs - number of matches +*************************************************************************/ +int match_1st_pair(unsigned char p1, unsigned char p2, + int *possible, int *nposs) +{ + int i; + + /* Set possibilities to 0 */ + *nposs = 0; + + /* Foreach set of feature pairs ... */ + for(i = 0; i < NFEATURES; i++){ + /* If current scan pair matches first pair for feature ... */ + if((p1==feature_patterns[i].first[0]) && + (p2==feature_patterns[i].first[1])){ + /* Store feature as a possible match. */ + possible[*nposs] = i; + /* Bump number of stored possibilities. */ + (*nposs)++; + } + } + + /* Return number of stored possibilities. */ + return(*nposs); +} + +/************************************************************************* +************************************************************************** +#cat: match_2nd_pair - Determines which of the passed feature_patterns[] have +#cat: their second pixel pair match the specified pixel pair. + + Input: + p1 - first pixel value of pair + p2 - second pixel value of pair + possible - list of potentially-matching feature_patterns[] indices + nposs - number of potential matches + Output: + possible - list of matching feature_patterns[] indices + nposs - number of matches + Return Code: + nposs - number of matches +*************************************************************************/ +int match_2nd_pair(unsigned char p1, unsigned char p2, + int *possible, int *nposs) +{ + int i; + int tnposs; + + /* Store input possibilities. */ + tnposs = *nposs; + /* Reset output possibilities to 0. */ + *nposs = 0; + + /* If current scan pair values are the same ... */ + if(p1 == p2) + /* Simply return because pair can't be a second feature pair. */ + return(*nposs); + + /* Foreach possible match based on first pair ... */ + for(i = 0; i < tnposs; i++){ + /* If current scan pair matches second pair for feature ... */ + if((p1==feature_patterns[possible[i]].second[0]) && + (p2==feature_patterns[possible[i]].second[1])){ + /* Store feature as a possible match. */ + possible[*nposs] = possible[i]; + /* Bump number of stored possibilities. */ + (*nposs)++; + } + } + + /* Return number of stored possibilities. */ + return(*nposs); +} + +/************************************************************************* +************************************************************************** +#cat: match_3rd_pair - Determines which of the passed feature_patterns[] have +#cat: their third pixel pair match the specified pixel pair. + + Input: + p1 - first pixel value of pair + p2 - second pixel value of pair + possible - list of potentially-matching feature_patterns[] indices + nposs - number of potential matches + Output: + possible - list of matching feature_patterns[] indices + nposs - number of matches + Return Code: + nposs - number of matches +*************************************************************************/ +int match_3rd_pair(unsigned char p1, unsigned char p2, + int *possible, int *nposs) +{ + int i; + int tnposs; + + /* Store input possibilities. */ + tnposs = *nposs; + /* Reset output possibilities to 0. */ + *nposs = 0; + + /* Foreach possible match based on first and second pairs ... */ + for(i = 0; i < tnposs; i++){ + /* If current scan pair matches third pair for feature ... */ + if((p1==feature_patterns[possible[i]].third[0]) && + (p2==feature_patterns[possible[i]].third[1])){ + /* Store feature as a possible match. */ + possible[*nposs] = possible[i]; + /* Bump number of stored possibilities. */ + (*nposs)++; + } + } + + /* Return number of stored possibilities. */ + return(*nposs); +} + +/************************************************************************* +************************************************************************** +#cat: skip_repeated_horizontal_pair - Takes the location of two pixel in +#cat: adjacent pixel rows within an image region and skips +#cat: rightward until the either the pixel pair no longer repeats +#cat: itself or the image region is exhausted. + + Input: + cx - current x-coord of starting pixel pair + ex - right edge of the image region + p1ptr - pointer to current top pixel in pair + p2ptr - pointer to current bottom pixel in pair + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + cx - x-coord of where rightward skip terminated + p1ptr - points to top pixel where rightward skip terminated + p2ptr - points to bottom pixel where rightward skip terminated +*************************************************************************/ +void skip_repeated_horizontal_pair(int *cx, const int ex, + unsigned char **p1ptr, unsigned char **p2ptr, + const int iw, const int ih) +{ + int old1, old2; + + /* Store starting pixel pair. */ + old1 = **p1ptr; + old2 = **p2ptr; + + /* Bump horizontally to next pixel pair. */ + (*cx)++; + (*p1ptr)++; + (*p2ptr)++; + + /* While not at right of scan region... */ + while(*cx < ex){ + /* If one or the other pixels in the new pair are different */ + /* from the starting pixel pair... */ + if((**p1ptr != old1) || (**p2ptr != old2)) + /* Done skipping repreated pixel pairs. */ + return; + /* Otherwise, bump horizontally to next pixel pair. */ + (*cx)++; + (*p1ptr)++; + (*p2ptr)++; + } +} + +/************************************************************************* +************************************************************************** +#cat: skip_repeated_vertical_pair - Takes the location of two pixel in +#cat: adjacent pixel columns within an image region and skips +#cat: downward until the either the pixel pair no longer repeats +#cat: itself or the image region is exhausted. + + Input: + cy - current y-coord of starting pixel pair + ey - bottom of the image region + p1ptr - pointer to current left pixel in pair + p2ptr - pointer to current right pixel in pair + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + cy - y-coord of where downward skip terminated + p1ptr - points to left pixel where downward skip terminated + p2ptr - points to right pixel where donward skip terminated +*************************************************************************/ +void skip_repeated_vertical_pair(int *cy, const int ey, + unsigned char **p1ptr, unsigned char **p2ptr, + const int iw, const int ih) +{ + int old1, old2; + + /* Store starting pixel pair. */ + old1 = **p1ptr; + old2 = **p2ptr; + + /* Bump vertically to next pixel pair. */ + (*cy)++; + (*p1ptr)+=iw; + (*p2ptr)+=iw; + + /* While not at bottom of scan region... */ + while(*cy < ey){ + /* If one or the other pixels in the new pair are different */ + /* from the starting pixel pair... */ + if((**p1ptr != old1) || (**p2ptr != old2)) + /* Done skipping repreated pixel pairs. */ + return; + /* Otherwise, bump vertically to next pixel pair. */ + (*cy)++; + (*p1ptr)+=iw; + (*p2ptr)+=iw; + } +} + diff --git a/libfprint/nbis/mindtct/minutia.c b/libfprint/nbis/mindtct/minutia.c new file mode 100644 index 00000000..29f505c7 --- /dev/null +++ b/libfprint/nbis/mindtct/minutia.c @@ -0,0 +1,3557 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: MINUTIA.C + AUTHOR: Michael D. Garris + DATE: 05/11/1999 + UPDATED: 10/04/1999 Version 2 by MDG + UPDATED: 09/13/2004 + + Contains routines responsible for detecting initial minutia + points as part of the NIST Latent Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + alloc_minutiae() + realloc_minutiae() + detect_minutiae() + detect_minutiae_V2() + update_minutiae() + update_minutiae_V2() + sort_minutiae_y_x() + sort_minutiae_x_y() + rm_dup_minutiae() + dump_minutiae() + dump_minutiae_pts() + dump_reliable_minutiae_pts() + create_minutia() + free_minutiae() + free_minutia() + remove_minutia() + join_minutia() + minutia_type() + is_minutia_appearing() + choose_scan_direction() + scan4minutiae() + scan4minutiae_horizontally() + scan4minutiae_horizontally_V2() + scan4minutiae_vertically() + scan4minutiae_vertically_V2() + rescan4minutiae_horizontally() + rescan4minutiae_vertically() + rescan_partial_horizontally() + rescan_partial_vertically() + get_nbr_block_index() + adjust_horizontal_rescan() + adjust_vertical_rescan() + process_horizontal_scan_minutia() + process_horizontal_scan_minutia_V2() + process_vertical_scan_minutia() + process_vertical_scan_minutia_V2() + adjust_high_curvature_minutia() + adjust_high_curvature_minutia_V2() + get_low_curvature_direction() + +***********************************************************************/ + +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: alloc_minutiae - Allocates and initializes a minutia list based on the +#cat: specified maximum number of minutiae to be detected. + + Input: + max_minutiae - number of minutia to be allocated in list + Output: + ominutiae - points to the allocated minutiae list + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int alloc_minutiae(MINUTIAE **ominutiae, const int max_minutiae) +{ + MINUTIAE *minutiae; + + minutiae = (MINUTIAE *)malloc(sizeof(MINUTIAE)); + if(minutiae == (MINUTIAE *)NULL){ + fprintf(stderr, "ERROR : alloc_minutiae : malloc : minutiae\n"); + exit(-430); + } + minutiae->list = (MINUTIA **)malloc(max_minutiae * sizeof(MINUTIA *)); + if(minutiae->list == (MINUTIA **)NULL){ + fprintf(stderr, "ERROR : alloc_minutiae : malloc : minutiae->list\n"); + exit(-431); + } + + minutiae->alloc = max_minutiae; + minutiae->num = 0; + + *ominutiae = minutiae; + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: realloc_minutiae - Reallocates a previously allocated minutia list +#cat: extending its allocated length based on the specified +#cat: increment. + + Input: + minutiae - previously allocated list of minutiae points + max_minutiae - number of minutia to be allocated in list + Output: + minutiae - extended list of minutiae points + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int realloc_minutiae(MINUTIAE *minutiae, const int incr_minutiae) +{ + minutiae->alloc += incr_minutiae; + minutiae->list = (MINUTIA **)realloc(minutiae->list, + minutiae->alloc * sizeof(MINUTIA *)); + if(minutiae->list == (MINUTIA **)NULL){ + fprintf(stderr, "ERROR : realloc_minutiae : realloc : minutiae->list\n"); + exit(-432); + } + + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: detect_minutiae - Takes a binary image and its associated IMAP and +#cat: NMAP matrices and scans each image block for potential +#cat: minutia points. + + Input: + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + imap - matrix of ridge flow directions + nmap - IMAP augmented with blocks of HIGH-CURVATURE and + blocks which have no neighboring valid directions. + mw - width (in blocks) of IMAP and NMAP matrices. + mh - height (in blocks) of IMAP and NMAP matrices. + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - points to a list of detected minutia structures + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int detect_minutiae(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + const int *imap, const int *nmap, const int mw, const int mh, + const LFSPARMS *lfsparms) +{ + int blk_i, blk_x, blk_y; + int scan_x, scan_y, scan_w, scan_h; + int scan_dir; + int ret; + + /* Start with first block in IMAP. */ + blk_i = 0; + + /* Start with first scan line in image. */ + scan_y = 0; + + /* Foreach row of blocks in IMAP... */ + for(blk_y = 0; blk_y < mh; blk_y++){ + /* Reset to beginning of new block row. */ + scan_x = 0; + /* Foreach block in current IMAP row... */ + for(blk_x = 0; blk_x < mw; blk_x++){ + + /* If IMAP is VALID ... */ + if(imap[blk_i] != INVALID_DIR){ + /* Choose the feature scan direction based on the block's */ + /* VALID IMAP direction. The scan direction will either */ + /* be HORIZONTAL or VERTICAL. */ + scan_dir = choose_scan_direction(imap[blk_i], + lfsparms->num_directions); + /* Set width of scan region. The image may not be an even */ + /* multiple of "blocksize" in width and height, so we must */ + /* account for this. */ + /* Bump right by "blocksize" pixels, but not beyond the */ + /* image boundary. */ + scan_w = min(scan_x+lfsparms->blocksize, iw); + /* Make the resulting width relative to the region's starting */ + /* x-pixel column. */ + scan_w -= scan_x; + /* Bump down by "blocksize" pixels, but not beyond the */ + /* image boundary. */ + scan_h = min(scan_y+lfsparms->blocksize, ih); + /* Make the resulting height relative to the region's starting */ + /* y-pixel row. */ + scan_h -= scan_y; + /* Scan the defined region for minutia features. */ + if((ret = scan4minutiae(minutiae, bdata, iw, ih, + imap, nmap, blk_x, blk_y, mw, mh, + scan_x, scan_y, scan_w, scan_h, scan_dir, + lfsparms))){ + /* Return code may be: */ + /* 1. ret<0 (implying system error) */ + return(ret); + } + + } /* Otherwise, IMAP is INVALID, so ignore the block. This seems */ + /* quite drastic! */ + + /* Advance to the next IMAP block in the row in the image. */ + scan_x += lfsparms->blocksize; + /* Advance to the next IMAP block in the row. */ + blk_i++; + } /* End foreach blk_x */ + /* Advance to the next IMAP row in the image. */ + scan_y += lfsparms->blocksize; + } /* End foreach blk_y */ + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: detect_minutiae_V2 - Takes a binary image and its associated +#cat: Direction and Low Flow Maps and scans each image block +#cat: with valid direction for minutia points. Minutia points +#cat: detected in LOW FLOW blocks are set with lower reliability. + + Input: + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + direction_map - map of image blocks containing directional ridge flow + low_flow_map - map of image blocks flagged as LOW RIDGE FLOW + high_curve_map - map of image blocks flagged as HIGH CURVATURE + mw - width (in blocks) of the maps + mh - height (in blocks) of the maps + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - points to a list of detected minutia structures + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int detect_minutiae_V2(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + int *direction_map, int *low_flow_map, int *high_curve_map, + const int mw, const int mh, + const LFSPARMS *lfsparms) +{ + int ret; + int *pdirection_map, *plow_flow_map, *phigh_curve_map; + + /* Pixelize the maps by assigning block values to individual pixels. */ + if((ret = pixelize_map(&pdirection_map, iw, ih, direction_map, mw, mh, + lfsparms->blocksize))){ + return(ret); + } + + if((ret = pixelize_map(&plow_flow_map, iw, ih, low_flow_map, mw, mh, + lfsparms->blocksize))){ + free(pdirection_map); + return(ret); + } + + if((ret = pixelize_map(&phigh_curve_map, iw, ih, high_curve_map, mw, mh, + lfsparms->blocksize))){ + free(pdirection_map); + free(plow_flow_map); + return(ret); + } + + if((ret = scan4minutiae_horizontally_V2(minutiae, bdata, iw, ih, + pdirection_map, plow_flow_map, phigh_curve_map, lfsparms))){ + free(pdirection_map); + free(plow_flow_map); + free(phigh_curve_map); + return(ret); + } + + if((ret = scan4minutiae_vertically_V2(minutiae, bdata, iw, ih, + pdirection_map, plow_flow_map, phigh_curve_map, lfsparms))){ + free(pdirection_map); + free(plow_flow_map); + free(phigh_curve_map); + return(ret); + } + + /* Deallocate working memories. */ + free(pdirection_map); + free(plow_flow_map); + free(phigh_curve_map); + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: update_minutiae - Takes a detected minutia point and (if it is not +#cat: determined to already be in the minutiae list) adds it to +#cat: the list. + + Input: + minutia - minutia structure for detected point + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - points to a list of detected minutia structures + Return Code: + Zero - minutia added to successfully added to minutiae list + IGNORE - minutia is to be ignored (already in the minutiae list) + Negative - system error +**************************************************************************/ +int update_minutiae(MINUTIAE *minutiae, MINUTIA *minutia, + unsigned char *bdata, const int iw, const int ih, + const LFSPARMS *lfsparms) +{ + int i, ret, dy, dx, delta_dir; + int qtr_ndirs, full_ndirs; + + /* Check to see if minutiae list is full ... if so, then extend */ + /* the length of the allocated list of minutia points. */ + if(minutiae->num >= minutiae->alloc){ + if((ret = realloc_minutiae(minutiae, MAX_MINUTIAE))) + return(ret); + } + + /* Otherwise, there is still room for more minutia. */ + + /* Compute quarter of possible directions in a semi-circle */ + /* (ie. 45 degrees). */ + qtr_ndirs = lfsparms->num_directions>>2; + + /* Compute number of directions in full circle. */ + full_ndirs = lfsparms->num_directions<<1; + + /* Is the minutiae list empty? */ + if(minutiae->num > 0){ + /* Foreach minutia stored in the list... */ + for(i = 0; i < minutiae->num; i++){ + /* If x distance between new minutia and current list minutia */ + /* are sufficiently close... */ + dx = abs(minutiae->list[i]->x - minutia->x); + if(dx < lfsparms->max_minutia_delta){ + /* If y distance between new minutia and current list minutia */ + /* are sufficiently close... */ + dy = abs(minutiae->list[i]->y - minutia->y); + if(dy < lfsparms->max_minutia_delta){ + /* If new minutia and current list minutia are same type... */ + if(minutiae->list[i]->type == minutia->type){ + /* Test to see if minutiae have similar directions. */ + /* Take minimum of computed inner and outer */ + /* direction differences. */ + delta_dir = abs(minutiae->list[i]->direction - + minutia->direction); + delta_dir = min(delta_dir, full_ndirs-delta_dir); + /* If directional difference is <= 45 degrees... */ + if(delta_dir <= qtr_ndirs){ + /* If new minutia and current list minutia share */ + /* the same point... */ + if((dx==0) && (dy==0)){ + /* Then the minutiae match, so don't add the new one */ + /* to the list. */ + return(IGNORE); + } + /* Othewise, check if they share the same contour. */ + /* Start by searching "max_minutia_delta" steps */ + /* clockwise. */ + /* If new minutia point found on contour... */ + if(search_contour(minutia->x, minutia->y, + lfsparms->max_minutia_delta, + minutiae->list[i]->x, minutiae->list[i]->y, + minutiae->list[i]->ex, minutiae->list[i]->ey, + SCAN_CLOCKWISE, bdata, iw, ih)){ + /* Consider the new minutia to be the same as the */ + /* current list minutia, so don't add the new one */ + /* to the list. */ + return(IGNORE); + } + /* Now search "max_minutia_delta" steps counter- */ + /* clockwise along contour. */ + /* If new minutia point found on contour... */ + if(search_contour(minutia->x, minutia->y, + lfsparms->max_minutia_delta, + minutiae->list[i]->x, minutiae->list[i]->y, + minutiae->list[i]->ex, minutiae->list[i]->ey, + SCAN_COUNTER_CLOCKWISE, bdata, iw, ih)){ + /* Consider the new minutia to be the same as the */ + /* current list minutia, so don't add the new one */ + /* to the list. */ + return(IGNORE); + } + + /* Otherwise, new minutia and current list minutia do */ + /* not share the same contour, so although they are */ + /* similar in type and location, treat them as 2 */ + /* different minutia. */ + + } /* Otherwise, directions are too different. */ + } /* Otherwise, minutiae are different type. */ + } /* Otherwise, minutiae too far apart in Y. */ + } /* Otherwise, minutiae too far apart in X. */ + } /* End FOR minutia in list. */ + } /* Otherwise, minutiae list is empty. */ + + /* Otherwise, assume new minutia is not in the list, so add it. */ + minutiae->list[minutiae->num] = minutia; + (minutiae->num)++; + + /* New minutia was successfully added to the list. */ + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: update_minutiae_V2 - Takes a detected minutia point and (if it is not +#cat: determined to already be in the minutiae list or the +#cat: new point is determined to be "more compatible") adds +#cat: it to the list. + + Input: + minutia - minutia structure for detected point + scan_dir - orientation of scan when minutia was detected + dmapval - directional ridge flow of block minutia is in + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - points to a list of detected minutia structures + Return Code: + Zero - minutia added to successfully added to minutiae list + IGNORE - minutia is to be ignored (already in the minutiae list) + Negative - system error +**************************************************************************/ +int update_minutiae_V2(MINUTIAE *minutiae, MINUTIA *minutia, + const int scan_dir, const int dmapval, + unsigned char *bdata, const int iw, const int ih, + const LFSPARMS *lfsparms) +{ + int i, ret, dy, dx, delta_dir; + int qtr_ndirs, full_ndirs; + int map_scan_dir; + + /* Check to see if minutiae list is full ... if so, then extend */ + /* the length of the allocated list of minutia points. */ + if(minutiae->num >= minutiae->alloc){ + if((ret = realloc_minutiae(minutiae, MAX_MINUTIAE))) + return(ret); + } + + /* Otherwise, there is still room for more minutia. */ + + /* Compute quarter of possible directions in a semi-circle */ + /* (ie. 45 degrees). */ + qtr_ndirs = lfsparms->num_directions>>2; + + /* Compute number of directions in full circle. */ + full_ndirs = lfsparms->num_directions<<1; + + /* Is the minutiae list empty? */ + if(minutiae->num > 0){ + /* Foreach minutia stored in the list (in reverse order) ... */ + for(i = minutiae->num-1; i >= 0; i--){ + /* If x distance between new minutia and current list minutia */ + /* are sufficiently close... */ + dx = abs(minutiae->list[i]->x - minutia->x); + if(dx < lfsparms->max_minutia_delta){ + /* If y distance between new minutia and current list minutia */ + /* are sufficiently close... */ + dy = abs(minutiae->list[i]->y - minutia->y); + if(dy < lfsparms->max_minutia_delta){ + /* If new minutia and current list minutia are same type... */ + if(minutiae->list[i]->type == minutia->type){ + /* Test to see if minutiae have similar directions. */ + /* Take minimum of computed inner and outer */ + /* direction differences. */ + delta_dir = abs(minutiae->list[i]->direction - + minutia->direction); + delta_dir = min(delta_dir, full_ndirs-delta_dir); + /* If directional difference is <= 45 degrees... */ + if(delta_dir <= qtr_ndirs){ + /* If new minutia and current list minutia share */ + /* the same point... */ + if((dx==0) && (dy==0)){ + /* Then the minutiae match, so don't add the new one */ + /* to the list. */ + return(IGNORE); + } + /* Othewise, check if they share the same contour. */ + /* Start by searching "max_minutia_delta" steps */ + /* clockwise. */ + /* If new minutia point found on contour... */ + if(search_contour(minutia->x, minutia->y, + lfsparms->max_minutia_delta, + minutiae->list[i]->x, minutiae->list[i]->y, + minutiae->list[i]->ex, minutiae->list[i]->ey, + SCAN_CLOCKWISE, bdata, iw, ih) || + search_contour(minutia->x, minutia->y, + lfsparms->max_minutia_delta, + minutiae->list[i]->x, minutiae->list[i]->y, + minutiae->list[i]->ex, minutiae->list[i]->ey, + SCAN_COUNTER_CLOCKWISE, bdata, iw, ih)){ + /* If new minutia has VALID block direction ... */ + if(dmapval >= 0){ + /* Derive feature scan direction compatible */ + /* with VALID direction. */ + map_scan_dir = choose_scan_direction(dmapval, + lfsparms->num_directions); + /* If map scan direction compatible with scan */ + /* direction in which new minutia was found ... */ + if(map_scan_dir == scan_dir){ + /* Then choose the new minutia over the one */ + /* currently in the list. */ + if((ret = remove_minutia(i, minutiae))){ + return(ret); + } + /* Continue on ... */ + } + else + /* Othersize, scan directions not compatible...*/ + /* so choose to keep the current minutia in */ + /* the list and ignore the new one. */ + return(IGNORE); + } + else{ + /* Otherwise, no reason to believe new minutia */ + /* is any better than the current one in the list,*/ + /* so consider the new minutia to be the same as */ + /* the current list minutia, and don't add the new*/ + /* one to the list. */ + return(IGNORE); + } + } + + /* Otherwise, new minutia and current list minutia do */ + /* not share the same contour, so although they are */ + /* similar in type and location, treat them as 2 */ + /* different minutia. */ + + } /* Otherwise, directions are too different. */ + } /* Otherwise, minutiae are different type. */ + } /* Otherwise, minutiae too far apart in Y. */ + } /* Otherwise, minutiae too far apart in X. */ + } /* End FOR minutia in list. */ + } /* Otherwise, minutiae list is empty. */ + + /* Otherwise, assume new minutia is not in the list, or those that */ + /* were close neighbors were selectively removed, so add it. */ + minutiae->list[minutiae->num] = minutia; + (minutiae->num)++; + + /* New minutia was successfully added to the list. */ + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: sort_minutiae_y_x - Takes a list of minutia points and sorts them +#cat: top-to-bottom and then left-to-right. + + Input: + minutiae - list of minutiae + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + minutiae - list of sorted minutiae + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int sort_minutiae_y_x(MINUTIAE *minutiae, const int iw, const int ih) +{ + int *ranks, *order; + int i, ret; + MINUTIA **newlist; + + /* Allocate a list of integers to hold 1-D image pixel offsets */ + /* for each of the 2-D minutia coordinate points. */ + ranks = (int *)malloc(minutiae->num * sizeof(int)); + if(ranks == (int *)NULL){ + fprintf(stderr, "ERROR : sort_minutiae_y_x : malloc : ranks\n"); + return(-310); + } + + /* Compute 1-D image pixel offsets form 2-D minutia coordinate points. */ + for(i = 0; i < minutiae->num; i++) + ranks[i] = (minutiae->list[i]->y * iw) + minutiae->list[i]->x; + + /* Get sorted order of minutiae. */ + if((ret = sort_indices_int_inc(&order, ranks, minutiae->num))){ + free(ranks); + return(ret); + } + + /* Allocate new MINUTIA list to hold sorted minutiae. */ + newlist = (MINUTIA **)malloc(minutiae->num * sizeof(MINUTIA *)); + if(newlist == (MINUTIA **)NULL){ + free(ranks); + free(order); + fprintf(stderr, "ERROR : sort_minutiae_y_x : malloc : newlist\n"); + return(-311); + } + + /* Put minutia into sorted order in new list. */ + for(i = 0; i < minutiae->num; i++) + newlist[i] = minutiae->list[order[i]]; + + /* Deallocate non-sorted list of minutia pointers. */ + free(minutiae->list); + /* Assign new sorted list of minutia to minutiae list. */ + minutiae->list = newlist; + + /* Free the working memories supporting the sort. */ + free(order); + free(ranks); + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: sort_minutiae_x_y - Takes a list of minutia points and sorts them +#cat: left-to-right and then top-to-bottom. + + Input: + minutiae - list of minutiae + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + minutiae - list of sorted minutiae + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int sort_minutiae_x_y(MINUTIAE *minutiae, const int iw, const int ih) +{ + int *ranks, *order; + int i, ret; + MINUTIA **newlist; + + /* Allocate a list of integers to hold 1-D image pixel offsets */ + /* for each of the 2-D minutia coordinate points. */ + ranks = (int *)malloc(minutiae->num * sizeof(int)); + if(ranks == (int *)NULL){ + fprintf(stderr, "ERROR : sort_minutiae_x_y : malloc : ranks\n"); + return(-440); + } + + /* Compute 1-D image pixel offsets form 2-D minutia coordinate points. */ + for(i = 0; i < minutiae->num; i++) + ranks[i] = (minutiae->list[i]->x * iw) + minutiae->list[i]->y; + + /* Get sorted order of minutiae. */ + if((ret = sort_indices_int_inc(&order, ranks, minutiae->num))){ + free(ranks); + return(ret); + } + + /* Allocate new MINUTIA list to hold sorted minutiae. */ + newlist = (MINUTIA **)malloc(minutiae->num * sizeof(MINUTIA *)); + if(newlist == (MINUTIA **)NULL){ + free(ranks); + free(order); + fprintf(stderr, "ERROR : sort_minutiae_x_y : malloc : newlist\n"); + return(-441); + } + + /* Put minutia into sorted order in new list. */ + for(i = 0; i < minutiae->num; i++) + newlist[i] = minutiae->list[order[i]]; + + /* Deallocate non-sorted list of minutia pointers. */ + free(minutiae->list); + /* Assign new sorted list of minutia to minutiae list. */ + minutiae->list = newlist; + + /* Free the working memories supporting the sort. */ + free(order); + free(ranks); + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: rm_dup_minutiae - Takes a list of minutiae sorted in some adjacent order +#cat: and detects and removes redundant minutia that have the +#cat: same exact pixel coordinate locations (even if other +#cat: attributes may differ). + + Input: + mintuiae - list of sorted minutiae + Output: + mintuiae - list of sorted minutiae with duplicates removed + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int rm_dup_minutiae(MINUTIAE *minutiae) +{ + int i, ret; + MINUTIA *minutia1, *minutia2; + + /* Work backward from the end of the list of minutiae. This way */ + /* we can selectively remove minutia from the list and not cause */ + /* problems with keeping track of current indices. */ + for(i = minutiae->num-1; i > 0; i--){ + minutia1 = minutiae->list[i]; + minutia2 = minutiae->list[i-1]; + /* If minutia pair has identical coordinates ... */ + if((minutia1->x == minutia2->x) && + (minutia1->y == minutia2->y)){ + /* Remove the 2nd minutia from the minutiae list. */ + if((ret = remove_minutia(i-1, minutiae))) + return(ret); + /* The first minutia slides into the position of the 2nd. */ + } + } + + /* Return successfully. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: dump_minutiae - Given a minutiae list, writes a formatted text report of +#cat: the list's contents to the specified open file pointer. + + Input: + minutiae - list of minutia structures + Output: + fpout - open file pointer +**************************************************************************/ +void dump_minutiae(FILE *fpout, const MINUTIAE *minutiae) +{ + int i, j; + + fprintf(fpout, "\n%d Minutiae Detected\n\n", minutiae->num); + + for(i = 0; i < minutiae->num; i++){ + /* Precision of reliablity added one decimal position */ + /* on 09-13-04 */ + fprintf(fpout, "%4d : %4d, %4d : %2d : %6.3f :", i, + minutiae->list[i]->x, minutiae->list[i]->y, + minutiae->list[i]->direction, minutiae->list[i]->reliability); + if(minutiae->list[i]->type == RIDGE_ENDING) + fprintf(fpout, "RIG : "); + else + fprintf(fpout, "BIF : "); + + if(minutiae->list[i]->appearing) + fprintf(fpout, "APP : "); + else + fprintf(fpout, "DIS : "); + + fprintf(fpout, "%2d ", minutiae->list[i]->feature_id); + + for(j = 0; j < minutiae->list[i]->num_nbrs; j++){ + fprintf(fpout, ": %4d,%4d; %2d ", + minutiae->list[minutiae->list[i]->nbrs[j]]->x, + minutiae->list[minutiae->list[i]->nbrs[j]]->y, + minutiae->list[i]->ridge_counts[j]); + } + + fprintf(fpout, "\n"); + } +} + +/************************************************************************* +************************************************************************** +#cat: dump_minutiae_pts - Given a minutiae list, writes the coordinate point +#cat: for each minutia in the list to the specified open +#cat: file pointer. + + Input: + minutiae - list of minutia structures + Output: + fpout - open file pointer +**************************************************************************/ +void dump_minutiae_pts(FILE *fpout, const MINUTIAE *minutiae) +{ + int i; + + /* First line in the output file contians the number of minutia */ + /* points to be written to the file. */ + fprintf(fpout, "%d\n", minutiae->num); + + /* Foreach minutia in list... */ + for(i = 0; i < minutiae->num; i++){ + /* Write the minutia's coordinate point to the file pointer. */ + fprintf(fpout, "%4d %4d\n", minutiae->list[i]->x, minutiae->list[i]->y); + } +} + + +/************************************************************************* +************************************************************************** +#cat: dump_reliable_minutiae_pts - Given a minutiae list, writes the +#cat: coordinate point for each minutia in the list that has +#cat: the specified reliability to the specified open +#cat: file pointer. + + Input: + minutiae - list of minutia structures + reliability - desired reliability level for minutiae to be reported + Output: + fpout - open file pointer +**************************************************************************/ +void dump_reliable_minutiae_pts(FILE *fpout, const MINUTIAE *minutiae, + const double reliability) +{ + int i, count; + + /* First count the number of qualifying minutiae so that the */ + /* MFS header may be written. */ + count = 0; + /* Foreach minutia in list... */ + for(i = 0; i < minutiae->num; i++){ + if(minutiae->list[i]->reliability == reliability) + count++; + } + + /* First line in the output file contians the number of minutia */ + /* points to be written to the file. */ + fprintf(fpout, "%d\n", count); + + /* Foreach minutia in list... */ + for(i = 0; i < minutiae->num; i++){ + if(minutiae->list[i]->reliability == reliability) + /* Write the minutia's coordinate point to the file pointer. */ + fprintf(fpout, "%4d %4d\n", + minutiae->list[i]->x, minutiae->list[i]->y); + } +} + +/************************************************************************* +************************************************************************** +#cat: create_minutia - Takes attributes associated with a detected minutia +#cat: point and allocates and initializes a minutia structure. + + Input: + x_loc - x-pixel coord of minutia (interior to feature) + y_loc - y-pixel coord of minutia (interior to feature) + x_edge - x-pixel coord of corresponding edge pixel (exterior to feature) + y_edge - y-pixel coord of corresponding edge pixel (exterior to feature) + idir - integer direction of the minutia + reliability - floating point measure of minutia's reliability + type - type of the minutia (ridge-ending or bifurcation) + appearing - designates the minutia as appearing or disappearing + feature_id - index of minutia's matching feature_patterns[] + Output: + ominutia - ponter to an allocated and initialized minutia structure + Return Code: + Zero - minutia structure successfully allocated and initialized + Negative - system error +*************************************************************************/ +int create_minutia(MINUTIA **ominutia, const int x_loc, const int y_loc, + const int x_edge, const int y_edge, const int idir, + const double reliability, + const int type, const int appearing, const int feature_id) +{ + MINUTIA *minutia; + + /* Allocate a minutia structure. */ + minutia = (MINUTIA *)malloc(sizeof(MINUTIA)); + /* If allocation error... */ + if(minutia == (MINUTIA *)NULL){ + fprintf(stderr, "ERROR : create_minutia : malloc : minutia\n"); + return(-230); + } + + /* Assign minutia structure attributes. */ + minutia->x = x_loc; + minutia->y = y_loc; + minutia->ex = x_edge; + minutia->ey = y_edge; + minutia->direction = idir; + minutia->reliability = reliability; + minutia->type = type; + minutia->appearing = appearing; + minutia->feature_id = feature_id; + minutia->nbrs = (int *)NULL; + minutia->ridge_counts = (int *)NULL; + minutia->num_nbrs = 0; + + /* Set minutia object to output pointer. */ + *ominutia = minutia; + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: free_minutiae - Takes a minutiae list and deallocates all memory +#cat: associated with it. + + Input: + minutiae - pointer to allocated list of minutia structures +*************************************************************************/ +void free_minutiae(MINUTIAE *minutiae) +{ + int i; + + /* Deallocate minutia structures in the list. */ + for(i = 0; i < minutiae->num; i++) + free_minutia(minutiae->list[i]); + /* Deallocate list of minutia pointers. */ + free(minutiae->list); + + /* Deallocate the list structure. */ + free(minutiae); +} + +/************************************************************************* +************************************************************************** +#cat: free_minutia - Takes a minutia pointer and deallocates all memory +#cat: associated with it. + + Input: + minutia - pointer to allocated minutia structure +*************************************************************************/ +void free_minutia(MINUTIA *minutia) +{ + /* Deallocate sublists. */ + if(minutia->nbrs != (int *)NULL) + free(minutia->nbrs); + if(minutia->ridge_counts != (int *)NULL) + free(minutia->ridge_counts); + + /* Deallocate the minutia structure. */ + free(minutia); +} + +/************************************************************************* +************************************************************************** +#cat: remove_minutia - Removes the specified minutia point from the input +#cat: list of minutiae. + + Input: + index - position of minutia to be removed from list + minutiae - input list of minutiae + Output: + minutiae - list with minutia removed + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int remove_minutia(const int index, MINUTIAE *minutiae) +{ + int fr, to; + + /* Make sure the requested index is within range. */ + if((index < 0) && (index >= minutiae->num)){ + fprintf(stderr, "ERROR : remove_minutia : index out of range\n"); + return(-380); + } + + /* Deallocate the minutia structure to be removed. */ + free_minutia(minutiae->list[index]); + + /* Slide the remaining list of minutiae up over top of the */ + /* position of the minutia being removed. */ + for(to = index, fr = index+1; fr < minutiae->num; to++, fr++) + minutiae->list[to] = minutiae->list[fr]; + + /* Decrement the number of minutiae remaining in the list. */ + minutiae->num--; + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: join_minutia - Takes 2 minutia points and connectes their features in +#cat: the input binary image. A line is drawn in the image +#cat: between the 2 minutia with a specified line-width radius +#cat: and a conditional border of pixels opposite in color +#cat: from the interior line. + + Input: + minutia1 - first minutia point to be joined + minutia2 - second minutia point to be joined + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + with_boundary - signifies the inclusion of border pixels + line_radius - line-width radius of join line + Output: + bdata - edited image with minutia features joined + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int join_minutia(const MINUTIA *minutia1, const MINUTIA *minutia2, + unsigned char *bdata, const int iw, const int ih, + const int with_boundary, const int line_radius) +{ + int dx_gte_dy, delta_x, delta_y; + int *x_list, *y_list, num; + int minutia_pix, boundary_pix; + int i, j, ret; + int x1, y1, x2, y2; + + /* Compute X and Y deltas between minutia points. */ + delta_x = abs(minutia1->x - minutia2->x); + delta_y = abs(minutia1->y - minutia2->y); + + /* Set flag based on |DX| >= |DY|. */ + /* If flag is true then add additional pixel width to the join line */ + /* by adding pixels neighboring top and bottom. */ + /* If flag is false then add additional pixel width to the join line */ + /* by adding pixels neighboring left and right. */ + if(delta_x >= delta_y) + dx_gte_dy = 1; + else + dx_gte_dy = 0; + + /* Compute points along line segment between the two minutia points. */ + if((ret = line_points(&x_list, &y_list, &num, + minutia1->x, minutia1->y, minutia2->x, minutia2->y))) + /* If error with line routine, return error code. */ + return(ret); + + /* Determine pixel color of minutia and boundary. */ + if(minutia1->type == RIDGE_ENDING){ + /* To connect 2 ridge-endings, draw black. */ + minutia_pix = 1; + boundary_pix = 0; + } + else{ + /* To connect 2 bifurcations, draw white. */ + minutia_pix = 0; + boundary_pix = 1; + } + + /* Foreach point on line connecting the minutiae points ... */ + for(i = 1; i < num-1; i++){ + /* Draw minutia pixel at current point on line. */ + *(bdata+(y_list[i]*iw)+x_list[i]) = minutia_pix; + + /* Initialize starting corrdinates for adding width to the */ + /* join line to the current point on the line. */ + x1 = x_list[i]; + y1 = y_list[i]; + x2 = x1; + y2 = y1; + /* Foreach pixel of added radial width ... */ + for(j = 0; j < line_radius; j++){ + + /* If |DX|>=|DY|, we want to add width to line by writing */ + /* to pixels neighboring above and below. */ + /* x1 -= (0=(1-1)); y1 -= 1 ==> ABOVE */ + /* x2 += (0=(1-1)); y2 += 1 ==> BELOW */ + /* If |DX|<|DY|, we want to add width to line by writing */ + /* to pixels neighboring left and right. */ + /* x1 -= (1=(1-0)); y1 -= 0 ==> LEFT */ + /* x2 += (1=(1-0)); y2 += 0 ==> RIGHT */ + + /* Advance 1st point along width dimension. */ + x1 -= (1 - dx_gte_dy); + y1 -= dx_gte_dy; + /* If pixel 1st point is within image boundaries ... */ + if((x1 >= 0) && (x1 < iw) && + (y1 >= 0) && (y1 < ih)) + /* Write the pixel ABOVE or LEFT. */ + *(bdata+(y1*iw)+x1) = minutia_pix; + + /* Advance 2nd point along width dimension. */ + x2 += (1 - dx_gte_dy); + y2 += dx_gte_dy; + /* If pixel 2nd point is within image boundaries ... */ + if((x2 >= 0) && (x2 < iw) && + /* Write the pixel BELOW or RIGHT. */ + (y2 >= 0) && (y2 < ih)) + *(bdata+(y2*iw)+x2) = minutia_pix; + } + + /* If boundary flag is set ... draw the boundary pixels.*/ + if(with_boundary){ + /* Advance 1st point along width dimension. */ + x1 -= (1 - dx_gte_dy); + y1 -= dx_gte_dy; + /* If pixel 1st point is within image boundaries ... */ + if((x1 >= 0) && (x1 < iw) && + (y1 >= 0) && (y1 < ih)) + /* Write the pixel ABOVE or LEFT of opposite color. */ + *(bdata+(y1*iw)+x1) = boundary_pix; + + /* Advance 2nd point along width dimension. */ + x2 += (1 - dx_gte_dy); + y2 += dx_gte_dy; + /* If pixel 2nd point is within image boundaries ... */ + if((x2 >= 0) && (x2 < iw) && + (y2 >= 0) && (y2 < ih)) + /* Write the pixel BELOW or RIGHT of opposite color. */ + *(bdata+(y2*iw)+x2) = boundary_pix; + } + } + + /* Deallocate points along connecting line. */ + free(x_list); + free(y_list); + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: minutia_type - Given the pixel color of the detected feature, returns +#cat: whether the minutia is a ridge-ending (black pixel) or +#cat: bifurcation (white pixel). + + Input: + feature_pix - pixel color of the feature's interior + Return Code: + RIDGE_ENDING - minutia is a ridge-ending + BIFURCATION - minutia is a bifurcation (valley-ending) +**************************************************************************/ +int minutia_type(const int feature_pix) +{ + int type; + + /* If feature pixel is white ... */ + if(feature_pix == 0) + /* Then the feature is a valley-ending, so BIFURCATION. */ + type = BIFURCATION; + /* Otherwise, the feature pixel is black ... */ + else + /* So the feature is a RIDGE-ENDING. */ + type = RIDGE_ENDING; + + /* Return the type. */ + return(type); +} + +/************************************************************************* +************************************************************************** +#cat: is_minutia_appearing - Given the pixel location of a minutia feature +#cat: and its corresponding adjacent edge pixel, returns whether +#cat: the minutia is appearing or disappearing. Remeber, that +#cat: "feature" refers to either a ridge or valley-ending. + + Input: + x_loc - x-pixel coord of feature (interior to feature) + y_loc - y-pixel coord of feature (interior to feature) + x_edge - x-pixel coord of corresponding edge pixel + (exterior to feature) + y_edge - y-pixel coord of corresponding edge pixel + (exterior to feature) + Return Code: + APPEARING - minutia is appearing (TRUE==1) + DISAPPEARING - minutia is disappearing (FALSE==0) + Negative - system error +**************************************************************************/ +int is_minutia_appearing(const int x_loc, const int y_loc, + const int x_edge, const int y_edge) +{ + /* Edge pixels will always be N,S,E,W of feature pixel. */ + + /* 1. When scanning for feature's HORIZONTALLY... */ + /* If the edge is above the feature, then appearing. */ + if(x_edge < x_loc) + return(APPEARING); + /* If the edge is below the feature, then disappearing. */ + if(x_edge > x_loc) + return(DISAPPEARING); + + /* 1. When scanning for feature's VERTICALLY... */ + /* If the edge is left of feature, then appearing. */ + if(y_edge < y_loc) + return(APPEARING); + /* If the edge is right of feature, then disappearing. */ + if(y_edge > y_loc) + return(DISAPPEARING); + + /* Should never get here, but just in case. */ + fprintf(stderr, + "ERROR : is_minutia_appearing : bad configuration of pixels\n"); + return(-240); +} + +/************************************************************************* +************************************************************************** +#cat: choose_scan_direction - Determines the orientation (horizontal or +#cat: vertical) in which a block is to be scanned for minutiae. +#cat: The orientation is based on the blocks corresponding IMAP +#cat: direction. + + Input: + imapval - Block's IMAP direction + ndirs - number of possible IMAP directions (within semicircle) + Return Code: + SCAN_HORIZONTAL - horizontal orientation + SCAN_VERTICAL - vertical orientation +**************************************************************************/ +int choose_scan_direction(const int imapval, const int ndirs) +{ + int qtr_ndirs; + + /* Compute quarter of directions in semi-circle. */ + qtr_ndirs = ndirs>>2; + + /* If ridge flow in block is relatively vertical, then we want */ + /* to scan for minutia features in the opposite direction */ + /* (ie. HORIZONTALLY). */ + if((imapval <= qtr_ndirs) || (imapval > (qtr_ndirs*3))) + return(SCAN_HORIZONTAL); + /* Otherwise, ridge flow is realtively horizontal, and we want */ + /* to scan for minutia features in the opposite direction */ + /* (ie. VERTICALLY). */ + else + return(SCAN_VERTICAL); + +} + +/************************************************************************* +************************************************************************** +#cat: scan4minutiae - Scans a block of binary image data detecting potential +#cat: minutiae points. + + Input: + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + imap - matrix of ridge flow directions + nmap - IMAP augmented with blocks of HIGH-CURVATURE and + blocks which have no neighboring valid directions. + blk_x - x-block coord to be scanned + blk_y - y-block coord to be scanned + mw - width (in blocks) of IMAP and NMAP matrices. + mh - height (in blocks) of IMAP and NMAP matrices. + scan_x - x-pixel coord of origin of region to be scanned + scan_y - y-pixel coord of origin of region to be scanned + scan_w - width (in pixels) of region to be scanned + scan_h - height (in pixels) of region to be scanned + scan_dir - the scan orientation (horizontal or vertical) + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - points to a list of detected minutia structures + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int scan4minutiae(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + const int *imap, const int *nmap, + const int blk_x, const int blk_y, const int mw, const int mh, + const int scan_x, const int scan_y, + const int scan_w, const int scan_h, const int scan_dir, + const LFSPARMS *lfsparms) +{ + int blk_i, ret; + + /* Compute block index from block coordinates. */ + blk_i = (blk_y*mw) + blk_x; + + /* Conduct primary scan for minutiae horizontally. */ + if(scan_dir == SCAN_HORIZONTAL){ + + if((ret = scan4minutiae_horizontally(minutiae, bdata, iw, ih, + imap[blk_i], nmap[blk_i], + scan_x, scan_y, scan_w, scan_h, lfsparms))){ + /* Return code may be: */ + /* 1. ret<0 (implying system error) */ + return(ret); + } + + /* Rescan block vertically. */ + if((ret = rescan4minutiae_vertically(minutiae, bdata, iw, ih, + imap, nmap, blk_x, blk_y, mw, mh, + scan_x, scan_y, scan_w, scan_h, lfsparms))){ + /* Return code may be: */ + /* 1. ret<0 (implying system error) */ + return(ret); + } + } + + /* Otherwise, conduct primary scan for minutiae vertically. */ + else{ + if((ret = scan4minutiae_vertically(minutiae, bdata, iw, ih, + imap[blk_i], nmap[blk_i], + scan_x, scan_y, scan_w, scan_h, lfsparms))){ + /* Return resulting code. */ + return(ret); + } + + /* Rescan block horizontally. */ + if((ret = rescan4minutiae_horizontally(minutiae, bdata, iw, ih, + imap, nmap, blk_x, blk_y, mw, mh, + scan_x, scan_y, scan_w, scan_h, lfsparms))){ + /* Return resulting code. */ + return(ret); + } + } + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: scan4minutiae_horizontally - Scans a specified region of binary image +#cat: data horizontally, detecting potential minutiae points. +#cat: Minutia detected via the horizontal scan process are +#cat: by nature vertically oriented (orthogonal to the scan). +#cat: The region actually scanned is slightly larger than that +#cat: specified. This overlap attempts to minimize the number +#cat: of minutiae missed at the region boundaries. +#cat: HOWEVER, some minutiae will still be missed! + + Input: + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + imapval - IMAP value associated with this image region + nmapval - NMAP value associated with this image region + scan_x - x-pixel coord of origin of region to be scanned + scan_y - y-pixel coord of origin of region to be scanned + scan_w - width (in pixels) of region to be scanned + scan_h - height (in pixels) of region to be scanned + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - points to a list of detected minutia structures + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int scan4minutiae_horizontally(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + const int imapval, const int nmapval, + const int scan_x, const int scan_y, + const int scan_w, const int scan_h, + const LFSPARMS *lfsparms) +{ + int sx, sy, ex, ey, cx, cy, x2; + unsigned char *p1ptr, *p2ptr; + int possible[NFEATURES], nposs; + int ret; + + /* NOTE!!! Minutia that "straddle" region boundaries may be missed! */ + + /* If possible, overlap left and right of current scan region */ + /* by 2 pixel columns to help catch some minutia that straddle the */ + /* the scan region boundaries. */ + sx = max(0, scan_x-2); + ex = min(iw, scan_x+scan_w+2); + + /* If possible, overlap the scan region below by 1 pixel row. */ + sy = scan_y; + ey = min(ih, scan_y+scan_h+1); + + /* For now, we will not adjust for IMAP edge, as the binary image */ + /* was properly padded at its edges so as not to cause anomallies. */ + + /* Start at first row in region. */ + cy = sy; + /* While second scan row not outside the bottom of the scan region... */ + while(cy+1 < ey){ + /* Start at beginning of new scan row in region. */ + cx = sx; + /* While not at end of region's current scan row. */ + while(cx < ex){ + /* Get pixel pair from current x position in current and next */ + /* scan rows. */ + p1ptr = bdata+(cy*iw)+cx; + p2ptr = bdata+((cy+1)*iw)+cx; + /* If scan pixel pair matches first pixel pair of */ + /* 1 or more features... */ + if(match_1st_pair(*p1ptr, *p2ptr, possible, &nposs)){ + /* Bump forward to next scan pixel pair. */ + cx++; + p1ptr++; + p2ptr++; + /* If not at end of region's current scan row... */ + if(cx < ex){ + /* If scan pixel pair matches second pixel pair of */ + /* 1 or more features... */ + if(match_2nd_pair(*p1ptr, *p2ptr, possible, &nposs)){ + /* Store current x location. */ + x2 = cx; + /* Skip repeated pixel pairs. */ + skip_repeated_horizontal_pair(&cx, ex, &p1ptr, &p2ptr, + iw, ih); + /* If not at end of region's current scan row... */ + if(cx < ex){ + /* If scan pixel pair matches third pixel pair of */ + /* a single feature... */ + if(match_3rd_pair(*p1ptr, *p2ptr, possible, &nposs)){ + /* Process detected minutia point. */ + if((ret = process_horizontal_scan_minutia(minutiae, + cx, cy, x2, possible[0], + bdata, iw, ih, + imapval, nmapval, lfsparms))){ + /* Return code may be: */ + /* 1. ret< 0 (implying system error) */ + /* 2. ret==IGNORE (ignore current feature) */ + if(ret < 0) + return(ret); + /* Otherwise, IGNORE and continue. */ + } + } + + /* Set up to resume scan. */ + /* Test to see if 3rd pair can slide into 2nd pair. */ + /* The values of the 2nd pair MUST be different. */ + /* If 3rd pair values are different ... */ + if(*p1ptr != *p2ptr){ + /* Set next first pair to last of repeated */ + /* 2nd pairs, ie. back up one pair. */ + cx--; + } + + /* Otherwise, 3rd pair can't be a 2nd pair, so */ + /* keep pointing to 3rd pair so that it is used */ + /* in the next first pair test. */ + + } /* Else, at end of current scan row. */ + } + + /* Otherwise, 2nd pair failed, so keep pointing to it */ + /* so that it is used in the next first pair test. */ + + } /* Else, at end of current scan row. */ + } + /* Otherwise, 1st pair failed... */ + else{ + /* Bump forward to next pixel pair. */ + cx++; + } + } /* While not at end of current scan row. */ + /* Bump forward to next scan row. */ + cy++; + } /* While not out of scan rows. */ + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: scan4minutiae_horizontally_V2 - Scans an entire binary image +#cat: horizontally, detecting potential minutiae points. +#cat: Minutia detected via the horizontal scan process are +#cat: by nature vertically oriented (orthogonal to the scan). + + Input: + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + pdirection_map - pixelized Direction Map + plow_flow_map - pixelized Low Ridge Flow Map + phigh_curve_map - pixelized High Curvature Map + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - points to a list of detected minutia structures + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int scan4minutiae_horizontally_V2(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + int *pdirection_map, int *plow_flow_map, int *phigh_curve_map, + const LFSPARMS *lfsparms) +{ + int sx, sy, ex, ey, cx, cy, x2; + unsigned char *p1ptr, *p2ptr; + int possible[NFEATURES], nposs; + int ret; + + /* Set scan region to entire image. */ + sx = 0; + ex = iw; + sy = 0; + ey = ih; + + /* Start at first row in region. */ + cy = sy; + /* While second scan row not outside the bottom of the scan region... */ + while(cy+1 < ey){ + /* Start at beginning of new scan row in region. */ + cx = sx; + /* While not at end of region's current scan row. */ + while(cx < ex){ + /* Get pixel pair from current x position in current and next */ + /* scan rows. */ + p1ptr = bdata+(cy*iw)+cx; + p2ptr = bdata+((cy+1)*iw)+cx; + /* If scan pixel pair matches first pixel pair of */ + /* 1 or more features... */ + if(match_1st_pair(*p1ptr, *p2ptr, possible, &nposs)){ + /* Bump forward to next scan pixel pair. */ + cx++; + p1ptr++; + p2ptr++; + /* If not at end of region's current scan row... */ + if(cx < ex){ + /* If scan pixel pair matches second pixel pair of */ + /* 1 or more features... */ + if(match_2nd_pair(*p1ptr, *p2ptr, possible, &nposs)){ + /* Store current x location. */ + x2 = cx; + /* Skip repeated pixel pairs. */ + skip_repeated_horizontal_pair(&cx, ex, &p1ptr, &p2ptr, + iw, ih); + /* If not at end of region's current scan row... */ + if(cx < ex){ + /* If scan pixel pair matches third pixel pair of */ + /* a single feature... */ + if(match_3rd_pair(*p1ptr, *p2ptr, possible, &nposs)){ + /* Process detected minutia point. */ + if((ret = process_horizontal_scan_minutia_V2(minutiae, + cx, cy, x2, possible[0], + bdata, iw, ih, pdirection_map, + plow_flow_map, phigh_curve_map, + lfsparms))){ + /* Return code may be: */ + /* 1. ret< 0 (implying system error) */ + /* 2. ret==IGNORE (ignore current feature) */ + if(ret < 0) + return(ret); + /* Otherwise, IGNORE and continue. */ + } + } + + /* Set up to resume scan. */ + /* Test to see if 3rd pair can slide into 2nd pair. */ + /* The values of the 2nd pair MUST be different. */ + /* If 3rd pair values are different ... */ + if(*p1ptr != *p2ptr){ + /* Set next first pair to last of repeated */ + /* 2nd pairs, ie. back up one pair. */ + cx--; + } + + /* Otherwise, 3rd pair can't be a 2nd pair, so */ + /* keep pointing to 3rd pair so that it is used */ + /* in the next first pair test. */ + + } /* Else, at end of current scan row. */ + } + + /* Otherwise, 2nd pair failed, so keep pointing to it */ + /* so that it is used in the next first pair test. */ + + } /* Else, at end of current scan row. */ + } + /* Otherwise, 1st pair failed... */ + else{ + /* Bump forward to next pixel pair. */ + cx++; + } + } /* While not at end of current scan row. */ + /* Bump forward to next scan row. */ + cy++; + } /* While not out of scan rows. */ + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: scan4minutiae_vertically - Scans a specified region of binary image data +#cat: vertically, detecting potential minutiae points. +#cat: Minutia detected via the vetical scan process are +#cat: by nature horizontally oriented (orthogonal to the scan). +#cat: The region actually scanned is slightly larger than that +#cat: specified. This overlap attempts to minimize the number +#cat: of minutiae missed at the region boundaries. +#cat: HOWEVER, some minutiae will still be missed! + + Input: + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + imapval - IMAP value associated with this image region + nmapval - NMAP value associated with this image region + scan_x - x-pixel coord of origin of region to be scanned + scan_y - y-pixel coord of origin of region to be scanned + scan_w - width (in pixels) of region to be scanned + scan_h - height (in pixels) of region to be scanned + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - points to a list of detected minutia structures + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int scan4minutiae_vertically(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + const int imapval, const int nmapval, + const int scan_x, const int scan_y, + const int scan_w, const int scan_h, + const LFSPARMS *lfsparms) +{ + int sx, sy, ex, ey, cx, cy, y2; + unsigned char *p1ptr, *p2ptr; + int possible[NFEATURES], nposs; + int ret; + + /* NOTE!!! Minutia that "straddle" region boundaries may be missed! */ + + /* If possible, overlap scan region to the right by 1 pixel column. */ + sx = scan_x; + ex = min(iw, scan_x+scan_w+1); + + /* If possible, overlap top and bottom of current scan region */ + /* by 2 pixel rows to help catch some minutia that straddle the */ + /* the scan region boundaries. */ + sy = max(0, scan_y-2); + ey = min(ih, scan_y+scan_h+2); + + /* For now, we will not adjust for IMAP edge, as the binary image */ + /* was properly padded at its edges so as not to cause anomalies. */ + + /* Start at first column in region. */ + cx = sx; + /* While second scan column not outside the right of the region ... */ + while(cx+1 < ex){ + /* Start at beginning of new scan column in region. */ + cy = sy; + /* While not at end of region's current scan column. */ + while(cy < ey){ + /* Get pixel pair from current y position in current and next */ + /* scan columns. */ + p1ptr = bdata+(cy*iw)+cx; + p2ptr = p1ptr+1; + /* If scan pixel pair matches first pixel pair of */ + /* 1 or more features... */ + if(match_1st_pair(*p1ptr, *p2ptr, possible, &nposs)){ + /* Bump forward to next scan pixel pair. */ + cy++; + p1ptr+=iw; + p2ptr+=iw; + /* If not at end of region's current scan column... */ + if(cy < ey){ + /* If scan pixel pair matches second pixel pair of */ + /* 1 or more features... */ + if(match_2nd_pair(*p1ptr, *p2ptr, possible, &nposs)){ + /* Store current y location. */ + y2 = cy; + /* Skip repeated pixel pairs. */ + skip_repeated_vertical_pair(&cy, ey, &p1ptr, &p2ptr, + iw, ih); + /* If not at end of region's current scan column... */ + if(cy < ey){ + /* If scan pixel pair matches third pixel pair of */ + /* a single feature... */ + if(match_3rd_pair(*p1ptr, *p2ptr, possible, &nposs)){ + /* Process detected minutia point. */ + if((ret = process_vertical_scan_minutia(minutiae, + cx, cy, y2, possible[0], + bdata, iw, ih, + imapval, nmapval, lfsparms))){ + /* Return code may be: */ + /* 1. ret< 0 (implying system error) */ + /* 2. ret==IGNORE (ignore current feature) */ + if(ret < 0) + return(ret); + /* Otherwise, IGNORE and continue. */ + } + } + + /* Set up to resume scan. */ + /* Test to see if 3rd pair can slide into 2nd pair. */ + /* The values of the 2nd pair MUST be different. */ + /* If 3rd pair values are different ... */ + if(*p1ptr != *p2ptr){ + /* Set next first pair to last of repeated */ + /* 2nd pairs, ie. back up one pair. */ + cy--; + } + + /* Otherwise, 3rd pair can't be a 2nd pair, so */ + /* keep pointing to 3rd pair so that it is used */ + /* in the next first pair test. */ + + } /* Else, at end of current scan row. */ + } + + /* Otherwise, 2nd pair failed, so keep pointing to it */ + /* so that it is used in the next first pair test. */ + + } /* Else, at end of current scan column. */ + } + /* Otherwise, 1st pair failed... */ + else{ + /* Bump forward to next pixel pair. */ + cy++; + } + } /* While not at end of current scan column. */ + /* Bump forward to next scan column. */ + cx++; + } /* While not out of scan columns. */ + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: scan4minutiae_vertically_V2 - Scans an entire binary image +#cat: vertically, detecting potential minutiae points. +#cat: Minutia detected via the vetical scan process are +#cat: by nature horizontally oriented (orthogonal to the scan). + + Input: + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + pdirection_map - pixelized Direction Map + plow_flow_map - pixelized Low Ridge Flow Map + phigh_curve_map - pixelized High Curvature Map + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - points to a list of detected minutia structures + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int scan4minutiae_vertically_V2(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + int *pdirection_map, int *plow_flow_map, int *phigh_curve_map, + const LFSPARMS *lfsparms) +{ + int sx, sy, ex, ey, cx, cy, y2; + unsigned char *p1ptr, *p2ptr; + int possible[NFEATURES], nposs; + int ret; + + /* Set scan region to entire image. */ + sx = 0; + ex = iw; + sy = 0; + ey = ih; + + /* Start at first column in region. */ + cx = sx; + /* While second scan column not outside the right of the region ... */ + while(cx+1 < ex){ + /* Start at beginning of new scan column in region. */ + cy = sy; + /* While not at end of region's current scan column. */ + while(cy < ey){ + /* Get pixel pair from current y position in current and next */ + /* scan columns. */ + p1ptr = bdata+(cy*iw)+cx; + p2ptr = p1ptr+1; + /* If scan pixel pair matches first pixel pair of */ + /* 1 or more features... */ + if(match_1st_pair(*p1ptr, *p2ptr, possible, &nposs)){ + /* Bump forward to next scan pixel pair. */ + cy++; + p1ptr+=iw; + p2ptr+=iw; + /* If not at end of region's current scan column... */ + if(cy < ey){ + /* If scan pixel pair matches second pixel pair of */ + /* 1 or more features... */ + if(match_2nd_pair(*p1ptr, *p2ptr, possible, &nposs)){ + /* Store current y location. */ + y2 = cy; + /* Skip repeated pixel pairs. */ + skip_repeated_vertical_pair(&cy, ey, &p1ptr, &p2ptr, + iw, ih); + /* If not at end of region's current scan column... */ + if(cy < ey){ + /* If scan pixel pair matches third pixel pair of */ + /* a single feature... */ + if(match_3rd_pair(*p1ptr, *p2ptr, possible, &nposs)){ + /* Process detected minutia point. */ + if((ret = process_vertical_scan_minutia_V2(minutiae, + cx, cy, y2, possible[0], + bdata, iw, ih, pdirection_map, + plow_flow_map, phigh_curve_map, + lfsparms))){ + /* Return code may be: */ + /* 1. ret< 0 (implying system error) */ + /* 2. ret==IGNORE (ignore current feature) */ + if(ret < 0) + return(ret); + /* Otherwise, IGNORE and continue. */ + } + } + + /* Set up to resume scan. */ + /* Test to see if 3rd pair can slide into 2nd pair. */ + /* The values of the 2nd pair MUST be different. */ + /* If 3rd pair values are different ... */ + if(*p1ptr != *p2ptr){ + /* Set next first pair to last of repeated */ + /* 2nd pairs, ie. back up one pair. */ + cy--; + } + + /* Otherwise, 3rd pair can't be a 2nd pair, so */ + /* keep pointing to 3rd pair so that it is used */ + /* in the next first pair test. */ + + } /* Else, at end of current scan row. */ + } + + /* Otherwise, 2nd pair failed, so keep pointing to it */ + /* so that it is used in the next first pair test. */ + + } /* Else, at end of current scan column. */ + } + /* Otherwise, 1st pair failed... */ + else{ + /* Bump forward to next pixel pair. */ + cy++; + } + } /* While not at end of current scan column. */ + /* Bump forward to next scan column. */ + cx++; + } /* While not out of scan columns. */ + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: rescan4minutiae_horizontally - Rescans portions of a block of binary +#cat: image data horizontally for potential minutiae. The areas +#cat: rescanned within the block are based on the current +#cat: block's neighboring blocks' IMAP and NMAP values. + + Input: + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + imap - matrix of ridge flow directions + nmap - IMAP augmented with blocks of HIGH-CURVATURE and + blocks which have no neighboring valid directions. + blk_x - x-block coord to be rescanned + blk_y - y-block coord to be rescanned + mw - width (in blocks) of IMAP and NMAP matrices. + mh - height (in blocks) of IMAP and NMAP matrices. + scan_x - x-pixel coord of origin of region to be rescanned + scan_y - y-pixel coord of origin of region to be rescanned + scan_w - width (in pixels) of region to be rescanned + scan_h - height (in pixels) of region to be rescanned + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - points to a list of detected minutia structures + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int rescan4minutiae_horizontally(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + const int *imap, const int *nmap, + const int blk_x, const int blk_y, + const int mw, const int mh, + const int scan_x, const int scan_y, + const int scan_w, const int scan_h, + const LFSPARMS *lfsparms) +{ + int blk_i, ret; + + /* Compute block index from block coordinates. */ + blk_i = (blk_y*mw)+blk_x; + + /* If high-curve block... */ + if(nmap[blk_i] == HIGH_CURVATURE){ + /* Rescan entire block in orthogonal direction. */ + if((ret = scan4minutiae_horizontally(minutiae, bdata, iw, ih, + imap[blk_i], nmap[blk_i], + scan_x, scan_y, scan_w, scan_h, lfsparms))) + /* Return code may be: */ + /* 1. ret<0 (implying system error) */ + return(ret); + } + /* Otherwise, block is low-curvature. */ + else{ + /* 1. Rescan horizontally to the North. */ + if((ret = rescan_partial_horizontally(NORTH, minutiae, bdata, iw, ih, + imap, nmap, blk_x, blk_y, mw, mh, + scan_x, scan_y, scan_w, scan_h, lfsparms))) + /* Return code may be: */ + /* 1. ret<0 (implying system error) */ + return(ret); + + /* 2. Rescan horizontally to the East. */ + if((ret = rescan_partial_horizontally(EAST, minutiae, bdata, iw, ih, + imap, nmap, blk_x, blk_y, mw, mh, + scan_x, scan_y, scan_w, scan_h, lfsparms))) + return(ret); + + /* 3. Rescan horizontally to the South. */ + if((ret = rescan_partial_horizontally(SOUTH, minutiae, bdata, iw, ih, + imap, nmap, blk_x, blk_y, mw, mh, + scan_x, scan_y, scan_w, scan_h, lfsparms))) + return(ret); + + /* 4. Rescan horizontally to the West. */ + if((ret = rescan_partial_horizontally(WEST, minutiae, bdata, iw, ih, + imap, nmap, blk_x, blk_y, mw, mh, + scan_x, scan_y, scan_w, scan_h, lfsparms))) + return(ret); + } /* End low-curvature rescan. */ + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: rescan4minutiae_vertically - Rescans portions of a block of binary +#cat: image data vertically for potential minutiae. The areas +#cat: rescanned within the block are based on the current +#cat: block's neighboring blocks' IMAP and NMAP values. + + Input: + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + imap - matrix of ridge flow directions + nmap - IMAP augmented with blocks of HIGH-CURVATURE and + blocks which have no neighboring valid directions. + blk_x - x-block coord to be rescanned + blk_y - y-block coord to be rescanned + mw - width (in blocks) of IMAP and NMAP matrices. + mh - height (in blocks) of IMAP and NMAP matrices. + scan_x - x-pixel coord of origin of region to be rescanned + scan_y - y-pixel coord of origin of region to be rescanned + scan_w - width (in pixels) of region to be rescanned + scan_h - height (in pixels) of region to be rescanned + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - points to a list of detected minutia structures + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int rescan4minutiae_vertically(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + const int *imap, const int *nmap, + const int blk_x, const int blk_y, + const int mw, const int mh, + const int scan_x, const int scan_y, + const int scan_w, const int scan_h, + const LFSPARMS *lfsparms) +{ + int blk_i, ret; + + /* Compute block index from block coordinates. */ + blk_i = (blk_y*mw)+blk_x; + + /* If high-curve block... */ + if(nmap[blk_i] == HIGH_CURVATURE){ + /* Rescan entire block in orthogonal direction. */ + if((ret = scan4minutiae_vertically(minutiae, bdata, iw, ih, + imap[blk_i], nmap[blk_i], + scan_x, scan_y, scan_w, scan_h, lfsparms))) + /* Return code may be: */ + /* 1. ret<0 (implying system error) */ + return(ret); + } + /* Otherwise, block is low-curvature. */ + else{ + /* 1. Rescan vertically to the North. */ + if((ret = rescan_partial_vertically(NORTH, minutiae, bdata, iw, ih, + imap, nmap, blk_x, blk_y, mw, mh, + scan_x, scan_y, scan_w, scan_h, lfsparms))) + /* Return code may be: */ + /* 1. ret<0 (implying system error) */ + return(ret); + + /* 2. Rescan vertically to the East. */ + if((ret = rescan_partial_vertically(EAST, minutiae, bdata, iw, ih, + imap, nmap, blk_x, blk_y, mw, mh, + scan_x, scan_y, scan_w, scan_h, lfsparms))) + return(ret); + + /* 3. Rescan vertically to the South. */ + if((ret = rescan_partial_vertically(SOUTH, minutiae, bdata, iw, ih, + imap, nmap, blk_x, blk_y, mw, mh, + scan_x, scan_y, scan_w, scan_h, lfsparms))) + return(ret); + + /* 4. Rescan vertically to the West. */ + if((ret = rescan_partial_vertically(WEST, minutiae, bdata, iw, ih, + imap, nmap, blk_x, blk_y, mw, mh, + scan_x, scan_y, scan_w, scan_h, lfsparms))) + return(ret); + } /* End low-curvature rescan. */ + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: rescan_partial_horizontally - Rescans a portion of a block of binary +#cat: image data horizontally based on the IMAP and NMAP values +#cat: of a specified neighboring block. + + Input: + nbr_dir - specifies which block neighbor {NORTH, SOUTH, EAST, WEST} + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + imap - matrix of ridge flow directions + nmap - IMAP augmented with blocks of HIGH-CURVATURE and + blocks which have no neighboring valid directions. + blk_x - x-block coord to be rescanned + blk_y - y-block coord to be rescanned + mw - width (in blocks) of IMAP and NMAP matrices. + mh - height (in blocks) of IMAP and NMAP matrices. + scan_x - x-pixel coord of origin of image region + scan_y - y-pixel coord of origin of image region + scan_w - width (in pixels) of image region + scan_h - height (in pixels) of image region + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - points to a list of detected minutia structures + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int rescan_partial_horizontally(const int nbr_dir, MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + const int *imap, const int *nmap, + const int blk_x, const int blk_y, + const int mw, const int mh, + const int scan_x, const int scan_y, + const int scan_w, const int scan_h, + const LFSPARMS *lfsparms) +{ + int nblk_i, blk_i; + int rescan_dir; + int rescan_x, rescan_y, rescan_w, rescan_h; + int ret; + + /* Neighbor will either be NORTH, SOUTH, EAST, OR WEST. */ + ret = get_nbr_block_index(&nblk_i, nbr_dir, blk_x, blk_y, mw, mh); + /* Will return: */ + /* 1. Neighbor index found == FOUND */ + /* 2. Neighbor not found == NOT_FOUND */ + /* 3. System error < 0 */ + + /* If system error ... */ + if(ret < 0) + /* Return the error code. */ + return(ret); + + /* If neighbor not found ... */ + if(ret == NOT_FOUND) + /* Nothing to do, so return normally. */ + return(0); + + /* Otherwise, neighboring block found ... */ + + /* If neighbor block is VALID... */ + if(imap[nblk_i] != INVALID_DIR){ + + /* Compute block index from current (not neighbor) block coordinates. */ + blk_i = (blk_y*mw)+blk_x; + + /* Select feature scan direction based on neighbor IMAP. */ + rescan_dir = choose_scan_direction(imap[nblk_i], + lfsparms->num_directions); + /* If new scan direction is HORIZONTAL... */ + if(rescan_dir == SCAN_HORIZONTAL){ + /* Adjust scan_x, scan_y, scan_w, scan_h for rescan. */ + if((ret = adjust_horizontal_rescan(nbr_dir, &rescan_x, &rescan_y, + &rescan_w, &rescan_h, + scan_x, scan_y, scan_w, scan_h, lfsparms->blocksize))) + /* Return system error code. */ + return(ret); + /* Rescan specified region in block vertically. */ + /* Pass IMAP direction for the block, NOT its neighbor. */ + if((ret = scan4minutiae_horizontally(minutiae, bdata, iw, ih, + imap[blk_i], nmap[blk_i], + rescan_x, rescan_y, rescan_w, rescan_h, lfsparms))) + /* Return code may be: */ + /* 1. ret<0 (implying system error) */ + return(ret); + } /* Otherwise, block has already been scanned vertically. */ + } /* Otherwise, neighbor has INVALID IMAP, so ignore rescan. */ + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: rescan_partial_vertically - Rescans a portion of a block of binary +#cat: image data vertically based on the IMAP and NMAP values +#cat: of a specified neighboring block. + + Input: + nbr_dir - specifies which block neighbor {NORTH, SOUTH, EAST, WEST} + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + imap - matrix of ridge flow directions + nmap - IMAP augmented with blocks of HIGH-CURVATURE and + blocks which have no neighboring valid directions. + blk_x - x-block coord to be rescanned + blk_y - y-block coord to be rescanned + mw - width (in blocks) of IMAP and NMAP matrices. + mh - height (in blocks) of IMAP and NMAP matrices. + scan_x - x-pixel coord of origin of image region + scan_y - y-pixel coord of origin of image region + scan_w - width (in pixels) of image region + scan_h - height (in pixels) of image region + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - points to a list of detected minutia structures + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int rescan_partial_vertically(const int nbr_dir, MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + const int *imap, const int *nmap, + const int blk_x, const int blk_y, + const int mw, const int mh, + const int scan_x, const int scan_y, + const int scan_w, const int scan_h, + const LFSPARMS *lfsparms) +{ + int nblk_i, blk_i; + int rescan_dir; + int rescan_x, rescan_y, rescan_w, rescan_h; + int ret; + + /* Neighbor will either be NORTH, SOUTH, EAST, OR WEST. */ + ret = get_nbr_block_index(&nblk_i, nbr_dir, blk_x, blk_y, mw, mh); + /* Will return: */ + /* 1. Neighbor index found == FOUND */ + /* 2. Neighbor not found == NOT_FOUND */ + /* 3. System error < 0 */ + + /* If system error ... */ + if(ret < 0) + /* Return the error code. */ + return(ret); + + /* If neighbor not found ... */ + if(ret == NOT_FOUND) + /* Nothing to do, so return normally. */ + return(0); + + /* Otherwise, neighboring block found ... */ + + /* If neighbor block is VALID... */ + if(imap[nblk_i] != INVALID_DIR){ + + /* Compute block index from current (not neighbor) block coordinates. */ + blk_i = (blk_y*mw)+blk_x; + + /* Select feature scan direction based on neighbor IMAP. */ + rescan_dir = choose_scan_direction(imap[nblk_i], + lfsparms->num_directions); + /* If new scan direction is VERTICAL... */ + if(rescan_dir == SCAN_VERTICAL){ + /* Adjust scan_x, scan_y, scan_w, scan_h for rescan. */ + if((ret = adjust_vertical_rescan(nbr_dir, &rescan_x, &rescan_y, + &rescan_w, &rescan_h, + scan_x, scan_y, scan_w, scan_h, lfsparms->blocksize))) + /* Return system error code. */ + return(ret); + /* Rescan specified region in block vertically. */ + /* Pass IMAP direction for the block, NOT its neighbor. */ + if((ret = scan4minutiae_vertically(minutiae, bdata, iw, ih, + imap[blk_i], nmap[blk_i], + rescan_x, rescan_y, rescan_w, rescan_h, lfsparms))) + /* Return code may be: */ + /* 1. ret<0 (implying system error) */ + return(ret); + } /* Otherwise, block has already been scanned horizontally. */ + } /* Otherwise, neighbor has INVALID IMAP, so ignore rescan. */ + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: get_nbr_block_index - Determines the block index (if one exists) +#cat: for a specified neighbor of a block in the image. + + Input: + nbr_dir - specifies which block neighbor {NORTH, SOUTH, EAST, WEST} + blk_x - x-block coord to find neighbor of + blk_y - y-block coord to find neighbor of + mw - width (in blocks) of IMAP and NMAP matrices. + mh - height (in blocks) of IMAP and NMAP matrices. + Output: + oblk_i - points to neighbor's block index + Return Code: + NOT_FOUND - neighbor index does not exist + FOUND - neighbor index exists and returned + Negative - system error +**************************************************************************/ +int get_nbr_block_index(int *oblk_i, const int nbr_dir, + const int blk_x, const int blk_y, const int mw, const int mh) +{ + int nx, ny, ni; + + switch(nbr_dir){ + case NORTH: + /* If neighbor doesn't exist above... */ + if((ny = blk_y-1) < 0) + /* Done, so return normally. */ + return(NOT_FOUND); + /* Get neighbor's block index. */ + ni = (ny*mw)+blk_x; + break; + case EAST: + /* If neighbor doesn't exist to the right... */ + if((nx = blk_x+1) >= mw) + /* Done, so return normally. */ + return(NOT_FOUND); + /* Get neighbor's block index. */ + ni = (blk_y*mw)+nx; + break; + case SOUTH: + /* If neighbor doesn't exist below... */ + if((ny = blk_y+1) >= mh) + /* Return normally. */ + return(NOT_FOUND); + /* Get neighbor's block index. */ + ni = (ny*mw)+blk_x; + break; + case WEST: + /* If neighbor doesn't exist to the left... */ + if((nx = blk_x-1) < 0) + /* Return normally. */ + return(NOT_FOUND); + /* Get neighbor's block index. */ + ni = (blk_y*mw)+nx; + break; + default: + fprintf(stderr, + "ERROR : get_nbr_block_index : illegal neighbor direction\n"); + return(-200); + } + + /* Assign output pointer. */ + *oblk_i = ni; + + /* Return neighbor FOUND. */ + return(FOUND); +} + +/************************************************************************* +************************************************************************** +#cat: adjust_horizontal_rescan - Determines the portion of an image block to +#cat: be rescanned horizontally based on a specified neighbor. + + Input: + nbr_dir - specifies which block neighbor {NORTH, SOUTH, EAST, WEST} + scan_x - x-pixel coord of origin of image region + scan_y - y-pixel coord of origin of image region + scan_w - width (in pixels) of image region + scan_h - height (in pixels) of image region + blocksize - dimension of image blocks (in pixels) + Output: + rescan_x - x-pixel coord of origin of region to be rescanned + rescan_y - y-pixel coord of origin of region to be rescanned + rescan_w - width (in pixels) of region to be rescanned + rescan_h - height (in pixels) of region to be rescanned + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int adjust_horizontal_rescan(const int nbr_dir, int *rescan_x, int *rescan_y, + int *rescan_w, int *rescan_h, const int scan_x, const int scan_y, + const int scan_w, const int scan_h, const int blocksize) +{ + int half_blocksize, qtr_blocksize; + + /* Compute half of blocksize. */ + half_blocksize = blocksize>>1; + /* Compute quarter of blocksize. */ + qtr_blocksize = blocksize>>2; + + /* Neighbor will either be NORTH, SOUTH, EAST, OR WEST. */ + switch(nbr_dir){ + case NORTH: + /* + ************************* + * RESCAN NORTH * + * AREA * + ************************* + | | + | | + | | + | | + | | + | | + ------------------------- + */ + /* Rescan origin stays the same. */ + *rescan_x = scan_x; + *rescan_y = scan_y; + /* Rescan width stays the same. */ + *rescan_w = scan_w; + /* Rescan height is reduced to "qtr_blocksize" */ + /* if scan_h is larger. */ + *rescan_h = min(qtr_blocksize, scan_h); + break; + case EAST: + /* + ------------************* + | * * + | * * + | * E R * + | * A E * + | * S S * + | * T C * + | * A * + | * N * + | * * + | * * + ------------************* + */ + /* Rescan x-orign is set to half_blocksize from right edge of */ + /* block if scan width is larger. */ + *rescan_x = max(scan_x+scan_w-half_blocksize, scan_x); + /* Rescan y-origin stays the same. */ + *rescan_y = scan_y; + /* Rescan width is reduced to "half_blocksize" */ + /* if scan width is larger. */ + *rescan_w = min(half_blocksize, scan_w); + /* Rescan height stays the same. */ + *rescan_h = scan_h; + break; + case SOUTH: + /* + ------------------------- + | | + | | + | | + | | + | | + | | + ************************* + * RESCAN SOUTH * + * AREA * + ************************* + */ + /* Rescan x-origin stays the same. */ + *rescan_x = scan_x; + /* Rescan y-orign is set to qtr_blocksize from bottom edge of */ + /* block if scan height is larger. */ + *rescan_y = max(scan_y+scan_h-qtr_blocksize, scan_y); + /* Rescan width stays the same. */ + *rescan_w = scan_w; + /* Rescan height is reduced to "qtr_blocksize" */ + /* if scan height is larger. */ + *rescan_h = min(qtr_blocksize, scan_h); + break; + case WEST: + /* + *************------------ + * * | + * * | + * W R * | + * E E * | + * S S * | + * T C * | + * A * | + * N * | + * * | + * * | + *************------------ + */ + /* Rescan origin stays the same. */ + *rescan_x = scan_x; + *rescan_y = scan_y; + /* Rescan width is reduced to "half_blocksize" */ + /* if scan width is larger. */ + *rescan_w = min(half_blocksize, scan_w); + /* Rescan height stays the same. */ + *rescan_h = scan_h; + break; + default: + fprintf(stderr, + "ERROR : adjust_horizontal_rescan : illegal neighbor direction\n"); + return(-210); + } + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: adjust_vertical_rescan - Determines the portion of an image block to +#cat: be rescanned vertically based on a specified neighbor. + + Input: + nbr_dir - specifies which block neighbor {NORTH, SOUTH, EAST, WEST} + scan_x - x-pixel coord of origin of image region + scan_y - y-pixel coord of origin of image region + scan_w - width (in pixels) of image region + scan_h - height (in pixels) of image region + blocksize - dimension of image blocks (in pixels) + Output: + rescan_x - x-pixel coord of origin of region to be rescanned + rescan_y - y-pixel coord of origin of region to be rescanned + rescan_w - width (in pixels) of region to be rescanned + rescan_h - height (in pixels) of region to be rescanned + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int adjust_vertical_rescan(const int nbr_dir, int *rescan_x, int *rescan_y, + int *rescan_w, int *rescan_h, const int scan_x, const int scan_y, + const int scan_w, const int scan_h, const int blocksize) +{ + int half_blocksize, qtr_blocksize; + + /* Compute half of blocksize. */ + half_blocksize = blocksize>>1; + /* Compute quarter of blocksize. */ + qtr_blocksize = blocksize>>2; + + /* Neighbor will either be NORTH, SOUTH, EAST, OR WEST. */ + switch(nbr_dir){ + case NORTH: + /* + ************************* + * * + * RESCAN NORTH * + * AREA * + * * + ************************* + | | + | | + | | + | | + | | + ------------------------- + */ + /* Rescan origin stays the same. */ + *rescan_x = scan_x; + *rescan_y = scan_y; + /* Rescan width stays the same. */ + *rescan_w = scan_w; + /* Rescan height is reduced to "half_blocksize" */ + /* if scan_h is larger. */ + *rescan_h = min(half_blocksize, scan_h); + break; + case EAST: + /* + ------------------******* + | * * + | * * + | * E R * + | * A E * + | * S S * + | * T C * + | * A * + | * N * + | * * + | * * + ------------------******* + */ + /* Rescan x-orign is set to qtr_blocksize from right edge of */ + /* block if scan width is larger. */ + *rescan_x = max(scan_x+scan_w-qtr_blocksize, scan_x); + /* Rescan y-origin stays the same. */ + *rescan_y = scan_y; + /* Rescan width is reduced to "qtr_blocksize" */ + /* if scan width is larger. */ + *rescan_w = min(qtr_blocksize, scan_w); + /* Rescan height stays the same. */ + *rescan_h = scan_h; + break; + case SOUTH: + /* + ------------------------- + | | + | | + | | + | | + | | + ************************* + * * + * RESCAN SOUTH * + * AREA * + * * + ************************* + */ + /* Rescan x-origin stays the same. */ + *rescan_x = scan_x; + /* Rescan y-orign is set to half_blocksize from bottom edge of */ + /* block if scan height is larger. */ + *rescan_y = max(scan_y+scan_h-half_blocksize, scan_y); + /* Rescan width stays the same. */ + *rescan_w = scan_w; + /* Rescan height is reduced to "half_blocksize" */ + /* if scan height is larger. */ + *rescan_h = min(half_blocksize, scan_h); + break; + case WEST: + /* + *******------------------ + * * | + * * | + * W R * | + * E E * | + * S S * | + * T C * | + * A * | + * N * | + * * | + * * | + *******------------------ + */ + /* Rescan origin stays the same. */ + *rescan_x = scan_x; + *rescan_y = scan_y; + /* Rescan width is reduced to "qtr_blocksize" */ + /* if scan width is larger. */ + *rescan_w = min(qtr_blocksize, scan_w); + /* Rescan height stays the same. */ + *rescan_h = scan_h; + break; + default: + fprintf(stderr, + "ERROR : adjust_vertical_rescan : illegal neighbor direction\n"); + return(-220); + } + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: process_horizontal_scan_minutia - Takes a minutia point that was +#cat: detected via the horizontal scan process and +#cat: adjusts its location (if necessary), determines its +#cat: direction, and (if it is not already in the minutiae +#cat: list) adds it to the list. These minutia are by nature +#cat: vertical in orientation (orthogonal to the scan). + + Input: + cx - x-pixel coord where 3rd pattern pair of mintuia was detected + cy - y-pixel coord where 3rd pattern pair of mintuia was detected + y2 - y-pixel coord where 2nd pattern pair of mintuia was detected + feature_id - type of minutia (ex. index into feature_patterns[] list) + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + imapval - IMAP value associated with this image region + nmapval - NMAP value associated with this image region + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - points to a list of detected minutia structures + Return Code: + Zero - successful completion + IGNORE - minutia is to be ignored + Negative - system error +**************************************************************************/ +int process_horizontal_scan_minutia(MINUTIAE *minutiae, + const int cx, const int cy, + const int x2, const int feature_id, + unsigned char *bdata, const int iw, const int ih, + const int imapval, const int nmapval, + const LFSPARMS *lfsparms) +{ + MINUTIA *minutia; + int x_loc, y_loc; + int x_edge, y_edge; + int idir, ret; + + /* Set x location of minutia point to be half way between */ + /* first position of second feature pair and position of */ + /* third feature pair. */ + x_loc = (cx + x2)>>1; + + /* Set same x location to neighboring edge pixel. */ + x_edge = x_loc; + + /* Feature location should always point to either ending */ + /* of ridge or (for bifurcations) ending of valley. */ + /* So, if detected feature is APPEARING... */ + if(feature_patterns[feature_id].appearing){ + /* Set y location to second scan row. */ + y_loc = cy+1; + /* Set y location of neighboring edge pixel to the first scan row. */ + y_edge = cy; + } + /* Otherwise, feature is DISAPPEARING... */ + else{ + /* Set y location to first scan row. */ + y_loc = cy; + /* Set y location of neighboring edge pixel to the second scan row. */ + y_edge = cy+1; + } + + /* If current minutia is in a high-curvature block... */ + if(nmapval == HIGH_CURVATURE){ + /* Adjust location and direction locally. */ + if((ret = adjust_high_curvature_minutia(&idir, &x_loc, &y_loc, + &x_edge, &y_edge, x_loc, y_loc, x_edge, y_edge, + bdata, iw, ih, minutiae, lfsparms))){ + /* Could be a system error or IGNORE minutia. */ + return(ret); + } + /* Otherwise, we have our high-curvature minutia attributes. */ + } + /* Otherwise, minutia is in fairly low-curvature block... */ + else{ + /* Get minutia direction based on current IMAP value. */ + idir = get_low_curvature_direction(SCAN_HORIZONTAL, + feature_patterns[feature_id].appearing, + imapval, lfsparms->num_directions); + } + + /* Create a minutia object based on derived attributes. */ + if((ret = create_minutia(&minutia, x_loc, y_loc, x_edge, y_edge, idir, + DEFAULT_RELIABILITY, + feature_patterns[feature_id].type, + feature_patterns[feature_id].appearing, feature_id))) + /* Return system error. */ + return(ret); + + /* Update the minutiae list with potential new minutia. */ + ret = update_minutiae(minutiae, minutia, bdata, iw, ih, lfsparms); + + /* If minuitia IGNORED and not added to the minutia list ... */ + if(ret == IGNORE) + /* Deallocate the minutia. */ + free_minutia(minutia); + + /* Otherwise, return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: process_horizontal_scan_minutia_V2 - Takes a minutia point that was +#cat: detected via the horizontal scan process and +#cat: adjusts its location (if necessary), determines its +#cat: direction, and (if it is not already in the minutiae +#cat: list) adds it to the list. These minutia are by nature +#cat: vertical in orientation (orthogonal to the scan). + + Input: + cx - x-pixel coord where 3rd pattern pair of mintuia was detected + cy - y-pixel coord where 3rd pattern pair of mintuia was detected + y2 - y-pixel coord where 2nd pattern pair of mintuia was detected + feature_id - type of minutia (ex. index into feature_patterns[] list) + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + pdirection_map - pixelized Direction Map + plow_flow_map - pixelized Low Ridge Flow Map + phigh_curve_map - pixelized High Curvature Map + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - points to a list of detected minutia structures + Return Code: + Zero - successful completion + IGNORE - minutia is to be ignored + Negative - system error +**************************************************************************/ +int process_horizontal_scan_minutia_V2(MINUTIAE *minutiae, + const int cx, const int cy, + const int x2, const int feature_id, + unsigned char *bdata, const int iw, const int ih, + int *pdirection_map, int *plow_flow_map, int *phigh_curve_map, + const LFSPARMS *lfsparms) +{ + MINUTIA *minutia; + int x_loc, y_loc; + int x_edge, y_edge; + int idir, ret; + int dmapval, fmapval, cmapval; + double reliability; + + /* Set x location of minutia point to be half way between */ + /* first position of second feature pair and position of */ + /* third feature pair. */ + x_loc = (cx + x2)>>1; + + /* Set same x location to neighboring edge pixel. */ + x_edge = x_loc; + + /* Feature location should always point to either ending */ + /* of ridge or (for bifurcations) ending of valley. */ + /* So, if detected feature is APPEARING... */ + if(feature_patterns[feature_id].appearing){ + /* Set y location to second scan row. */ + y_loc = cy+1; + /* Set y location of neighboring edge pixel to the first scan row. */ + y_edge = cy; + } + /* Otherwise, feature is DISAPPEARING... */ + else{ + /* Set y location to first scan row. */ + y_loc = cy; + /* Set y location of neighboring edge pixel to the second scan row. */ + y_edge = cy+1; + } + + dmapval = *(pdirection_map+(y_loc*iw)+x_loc); + fmapval = *(plow_flow_map+(y_loc*iw)+x_loc); + cmapval = *(phigh_curve_map+(y_loc*iw)+x_loc); + + /* If the minutia point is in a block with INVALID direction ... */ + if(dmapval == INVALID_DIR) + /* Then, IGNORE the point. */ + return(IGNORE); + + /* If current minutia is in a HIGH CURVATURE block ... */ + if(cmapval){ + /* Adjust location and direction locally. */ + if((ret = adjust_high_curvature_minutia_V2(&idir, &x_loc, &y_loc, + &x_edge, &y_edge, x_loc, y_loc, x_edge, y_edge, + bdata, iw, ih, plow_flow_map, minutiae, lfsparms))){ + /* Could be a system error or IGNORE minutia. */ + return(ret); + } + /* Otherwise, we have our high-curvature minutia attributes. */ + } + /* Otherwise, minutia is in fairly low-curvature block... */ + else{ + /* Get minutia direction based on current block's direction. */ + idir = get_low_curvature_direction(SCAN_HORIZONTAL, + feature_patterns[feature_id].appearing, dmapval, + lfsparms->num_directions); + } + + /* If current minutia is in a LOW RIDGE FLOW block ... */ + if(fmapval) + reliability = MEDIUM_RELIABILITY; + else + /* Otherwise, minutia is in a block with reliable direction and */ + /* binarization. */ + reliability = HIGH_RELIABILITY; + + /* Create a minutia object based on derived attributes. */ + if((ret = create_minutia(&minutia, x_loc, y_loc, x_edge, y_edge, idir, + reliability, + feature_patterns[feature_id].type, + feature_patterns[feature_id].appearing, feature_id))) + /* Return system error. */ + return(ret); + + /* Update the minutiae list with potential new minutia. */ + ret = update_minutiae_V2(minutiae, minutia, SCAN_HORIZONTAL, + dmapval, bdata, iw, ih, lfsparms); + + /* If minuitia IGNORED and not added to the minutia list ... */ + if(ret == IGNORE) + /* Deallocate the minutia. */ + free_minutia(minutia); + + /* Otherwise, return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: process_vertical_scan_minutia - Takes a minutia point that was +#cat: detected in via the vertical scan process and +#cat: adjusts its location (if necessary), determines its +#cat: direction, and (if it is not already in the minutiae +#cat: list) adds it to the list. These minutia are by nature +#cat: horizontal in orientation (orthogonal to the scan). + + Input: + cx - x-pixel coord where 3rd pattern pair of mintuia was detected + cy - y-pixel coord where 3rd pattern pair of mintuia was detected + x2 - x-pixel coord where 2nd pattern pair of mintuia was detected + feature_id - type of minutia (ex. index into feature_patterns[] list) + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + imapval - IMAP value associated with this image region + nmapval - NMAP value associated with this image region + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - points to a list of detected minutia structures + Return Code: + Zero - successful completion + IGNORE - minutia is to be ignored + Negative - system error +**************************************************************************/ +int process_vertical_scan_minutia(MINUTIAE *minutiae, + const int cx, const int cy, + const int y2, const int feature_id, + unsigned char *bdata, const int iw, const int ih, + const int imapval, const int nmapval, + const LFSPARMS *lfsparms) +{ + MINUTIA *minutia; + int x_loc, y_loc; + int x_edge, y_edge; + int idir, ret; + + /* Feature location should always point to either ending */ + /* of ridge or (for bifurcations) ending of valley. */ + /* So, if detected feature is APPEARING... */ + if(feature_patterns[feature_id].appearing){ + /* Set x location to second scan column. */ + x_loc = cx+1; + /* Set x location of neighboring edge pixel to the first scan column. */ + x_edge = cx; + } + /* Otherwise, feature is DISAPPEARING... */ + else{ + /* Set x location to first scan column. */ + x_loc = cx; + /* Set x location of neighboring edge pixel to the second scan column. */ + x_edge = cx+1; + } + + /* Set y location of minutia point to be half way between */ + /* first position of second feature pair and position of */ + /* third feature pair. */ + y_loc = (cy + y2)>>1; + /* Set same y location to neighboring edge pixel. */ + y_edge = y_loc; + + /* If current minutia is in a high-curvature block... */ + if(nmapval == HIGH_CURVATURE){ + /* Adjust location and direction locally. */ + if((ret = adjust_high_curvature_minutia(&idir, &x_loc, &y_loc, + &x_edge, &y_edge, x_loc, y_loc, x_edge, y_edge, + bdata, iw, ih, minutiae, lfsparms))){ + /* Could be a system error or IGNORE minutia. */ + return(ret); + } + /* Otherwise, we have our high-curvature minutia attributes. */ + } + /* Otherwise, minutia is in fairly low-curvature block... */ + else{ + /* Get minutia direction based on current IMAP value. */ + idir = get_low_curvature_direction(SCAN_VERTICAL, + feature_patterns[feature_id].appearing, + imapval, lfsparms->num_directions); + } + + /* Create a minutia object based on derived attributes. */ + if((ret = create_minutia(&minutia, x_loc, y_loc, x_edge, y_edge, idir, + DEFAULT_RELIABILITY, + feature_patterns[feature_id].type, + feature_patterns[feature_id].appearing, feature_id))) + /* Return system error. */ + return(ret); + + /* Update the minutiae list with potential new minutia. */ + ret = update_minutiae(minutiae, minutia, bdata, iw, ih, lfsparms); + + /* If minuitia IGNORED and not added to the minutia list ... */ + if(ret == IGNORE) + /* Deallocate the minutia. */ + free_minutia(minutia); + + /* Otherwise, return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: process_vertical_scan_minutia_V2 - Takes a minutia point that was +#cat: detected in via the vertical scan process and +#cat: adjusts its location (if necessary), determines its +#cat: direction, and (if it is not already in the minutiae +#cat: list) adds it to the list. These minutia are by nature +#cat: horizontal in orientation (orthogonal to the scan). + + Input: + cx - x-pixel coord where 3rd pattern pair of mintuia was detected + cy - y-pixel coord where 3rd pattern pair of mintuia was detected + x2 - x-pixel coord where 2nd pattern pair of mintuia was detected + feature_id - type of minutia (ex. index into feature_patterns[] list) + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + pdirection_map - pixelized Direction Map + plow_flow_map - pixelized Low Ridge Flow Map + phigh_curve_map - pixelized High Curvature Map + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - points to a list of detected minutia structures + Return Code: + Zero - successful completion + IGNORE - minutia is to be ignored + Negative - system error +**************************************************************************/ +int process_vertical_scan_minutia_V2(MINUTIAE *minutiae, + const int cx, const int cy, + const int y2, const int feature_id, + unsigned char *bdata, const int iw, const int ih, + int *pdirection_map, int *plow_flow_map, int *phigh_curve_map, + const LFSPARMS *lfsparms) +{ + MINUTIA *minutia; + int x_loc, y_loc; + int x_edge, y_edge; + int idir, ret; + int dmapval, fmapval, cmapval; + double reliability; + + /* Feature location should always point to either ending */ + /* of ridge or (for bifurcations) ending of valley. */ + /* So, if detected feature is APPEARING... */ + if(feature_patterns[feature_id].appearing){ + /* Set x location to second scan column. */ + x_loc = cx+1; + /* Set x location of neighboring edge pixel to the first scan column. */ + x_edge = cx; + } + /* Otherwise, feature is DISAPPEARING... */ + else{ + /* Set x location to first scan column. */ + x_loc = cx; + /* Set x location of neighboring edge pixel to the second scan column. */ + x_edge = cx+1; + } + + /* Set y location of minutia point to be half way between */ + /* first position of second feature pair and position of */ + /* third feature pair. */ + y_loc = (cy + y2)>>1; + /* Set same y location to neighboring edge pixel. */ + y_edge = y_loc; + + dmapval = *(pdirection_map+(y_loc*iw)+x_loc); + fmapval = *(plow_flow_map+(y_loc*iw)+x_loc); + cmapval = *(phigh_curve_map+(y_loc*iw)+x_loc); + + /* If the minutia point is in a block with INVALID direction ... */ + if(dmapval == INVALID_DIR) + /* Then, IGNORE the point. */ + return(IGNORE); + + /* If current minutia is in a HIGH CURVATURE block... */ + if(cmapval){ + /* Adjust location and direction locally. */ + if((ret = adjust_high_curvature_minutia_V2(&idir, &x_loc, &y_loc, + &x_edge, &y_edge, x_loc, y_loc, x_edge, y_edge, + bdata, iw, ih, plow_flow_map, minutiae, lfsparms))){ + /* Could be a system error or IGNORE minutia. */ + return(ret); + } + /* Otherwise, we have our high-curvature minutia attributes. */ + } + /* Otherwise, minutia is in fairly low-curvature block... */ + else{ + /* Get minutia direction based on current block's direction. */ + idir = get_low_curvature_direction(SCAN_VERTICAL, + feature_patterns[feature_id].appearing, dmapval, + lfsparms->num_directions); + } + + /* If current minutia is in a LOW RIDGE FLOW block ... */ + if(fmapval) + reliability = MEDIUM_RELIABILITY; + else + /* Otherwise, minutia is in a block with reliable direction and */ + /* binarization. */ + reliability = HIGH_RELIABILITY; + + /* Create a minutia object based on derived attributes. */ + if((ret = create_minutia(&minutia, x_loc, y_loc, x_edge, y_edge, idir, + reliability, + feature_patterns[feature_id].type, + feature_patterns[feature_id].appearing, feature_id))) + /* Return system error. */ + return(ret); + + /* Update the minutiae list with potential new minutia. */ + ret = update_minutiae_V2(minutiae, minutia, SCAN_VERTICAL, + dmapval, bdata, iw, ih, lfsparms); + + /* If minuitia IGNORED and not added to the minutia list ... */ + if(ret == IGNORE) + /* Deallocate the minutia. */ + free_minutia(minutia); + + /* Otherwise, return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: adjust_high_curvature_minutia - Takes an initial minutia point detected +#cat: in a high-curvature area and adjusts its location and +#cat: direction. First, it walks and extracts the contour +#cat: of the detected feature looking for and processing any loop +#cat: discovered along the way. Once the contour is extracted, +#cat: the point of highest-curvature is determined and used to +#cat: adjust the location of the minutia point. The angle of +#cat: the line perpendicular to the tangent on the high-curvature +#cat: contour at the minutia point is used as the mintutia's +#cat: direction. + + Input: + x_loc - starting x-pixel coord of feature (interior to feature) + y_loc - starting y-pixel coord of feature (interior to feature) + x_edge - x-pixel coord of corresponding edge pixel + (exterior to feature) + y_edge - y-pixel coord of corresponding edge pixel + (exterior to feature) + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + lfsparms - parameters and thresholds for controlling LFS + Output: + oidir - direction of adjusted minutia point + ox_loc - adjusted x-pixel coord of feature + oy_loc - adjusted y-pixel coord of feature + ox_edge - adjusted x-pixel coord of corresponding edge pixel + oy_edge - adjusted y-pixel coord of corresponding edge pixel + minutiae - points to a list of detected minutia structures + Return Code: + Zero - minutia point processed successfully + IGNORE - minutia point is to be ignored + Negative - system error +**************************************************************************/ +int adjust_high_curvature_minutia(int *oidir, int *ox_loc, int *oy_loc, + int *ox_edge, int *oy_edge, + const int x_loc, const int y_loc, + const int x_edge, const int y_edge, + unsigned char *bdata, const int iw, const int ih, + MINUTIAE *minutiae, const LFSPARMS *lfsparms) +{ + int ret; + int *contour_x, *contour_y, *contour_ex, *contour_ey, ncontour; + int min_i; + double min_theta; + int feature_pix; + int mid_x, mid_y, mid_pix; + int idir; + int half_contour, angle_edge; + + /* Set variable from parameter structure. */ + half_contour = lfsparms->high_curve_half_contour; + + /* Set edge length for computing contour's angle of curvature */ + /* to one quarter of desired pixel length of entire contour. */ + /* Ex. If half_contour==14, then contour length==29=(2X14)+1 */ + /* and angle_edge==7=(14/2). */ + angle_edge = half_contour>>1; + + /* Get the pixel value of current feature. */ + feature_pix = *(bdata + (y_loc * iw) + x_loc); + + /* Extract feature's contour. */ + if((ret = get_high_curvature_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, half_contour, + x_loc, y_loc, x_edge, y_edge, bdata, iw, ih))){ + /* Returns with: */ + /* 1. Successful or empty contour == 0 */ + /* If contour is empty, then contour lists are not allocated. */ + /* 2. Contour forms loop == LOOP_FOUND */ + /* 3. Sysetm error < 0 */ + + /* If the contour forms a loop... */ + if(ret == LOOP_FOUND){ + + /* If the order of the contour is clockwise, then the loops's */ + /* contour pixels are outside the corresponding edge pixels. We */ + /* definitely do NOT want to fill based on the feature pixel in */ + /* this case, because it is OUTSIDE the loop. For now we will */ + /* ignore the loop and the minutia that triggered its tracing. */ + /* It is likely that other minutia on the loop will be */ + /* detected that create a contour on the "inside" of the loop. */ + /* There is another issue here that could be addressed ... */ + /* It seems that many/multiple minutia are often detected within */ + /* the same loop, which currently requires retracing the loop, */ + /* locating minutia on opposite ends of the major axis of the */ + /* loop, and then determining that the minutia have already been */ + /* entered into the minutiae list upon processing the very first */ + /* minutia detected in the loop. There is a lot of redundant */ + /* work being done here! */ + /* Is_loop_clockwise takes a default value to be returned if the */ + /* routine is unable to determine the direction of the contour. */ + /* In this case, we want to IGNORE the loop if we can't tell its */ + /* direction so that we do not inappropriately fill the loop, so */ + /* we are passing the default value TRUE. */ + if((ret = is_loop_clockwise(contour_x, contour_y, ncontour, TRUE))){ + /* Deallocate contour lists. */ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + /* If we had a system error... */ + if(ret < 0) + /* Return the error code. */ + return(ret); + /* Otherwise, loop is clockwise, so return IGNORE. */ + return(IGNORE); + } + + /* Otherwise, process the clockwise-ordered contour of the loop */ + /* as it may contain minutia. If no minutia found, then it is */ + /* filled in. */ + ret = process_loop(minutiae, contour_x, contour_y, + contour_ex, contour_ey, ncontour, + bdata, iw, ih, lfsparms); + /* Returns with: */ + /* 1. Successful processing of loop == 0 */ + /* 2. System error < 0 */ + + /* Deallocate contour lists. */ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + + /* If loop processed successfully ... */ + if(ret == 0) + /* Then either a minutia pair was extracted or the loop was */ + /* filled. Either way we want to IGNORE the minutia that */ + /* started the whole loop processing in the beginning. */ + return(IGNORE); + + /* Otherwise, there was a system error. */ + /* Return the resulting code. */ + return(ret); + } + + /* Otherwise not a loop, so get_high_curvature_contour incurred */ + /* a system error. Return the error code. */ + return(ret); + } + + /* If contour is empty ... then contour lists were not allocated, so */ + /* simply return IGNORE. The contour comes back empty when there */ + /* were not a sufficient number of points found on the contour. */ + if(ncontour == 0) + return(IGNORE); + + /* Otherwise, there are contour points to process. */ + + /* Given the contour, determine the point of highest curvature */ + /* (ie. forming the minimum angle between contour walls). */ + if((ret = min_contour_theta(&min_i, &min_theta, angle_edge, + contour_x, contour_y, ncontour))){ + /* Deallocate contour lists. */ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + /* Returns IGNORE or system error. Either way */ + /* free the contour and return the code. */ + return(ret); + } + + /* If the minimum theta found along the contour is too large... */ + if(min_theta >= lfsparms->max_high_curve_theta){ + /* Deallocate contour lists. */ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + /* Reject the high-curvature minutia, and return IGNORE. */ + return(IGNORE); + } + + /* Test to see if interior of curvature is OK. Compute midpoint */ + /* between left and right points symmetrically distant (angle_edge */ + /* pixels) from the contour's point of minimum theta. */ + mid_x = (contour_x[min_i-angle_edge] + contour_x[min_i+angle_edge])>>1; + mid_y = (contour_y[min_i-angle_edge] + contour_y[min_i+angle_edge])>>1; + mid_pix = *(bdata + (mid_y * iw) + mid_x); + /* If the interior pixel value is not the same as the feature's... */ + if(mid_pix != feature_pix){ + /* Deallocate contour lists. */ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + /* Reject the high-curvature minutia and return IGNORE. */ + return(IGNORE); + } + + /* Compute new direction based on line connecting adjusted feature */ + /* location and the midpoint in the feature's interior. */ + idir = line2direction(contour_x[min_i], contour_y[min_i], + mid_x, mid_y, lfsparms->num_directions); + + /* Set minutia location to minimum theta position on the contour. */ + *oidir = idir; + *ox_loc = contour_x[min_i]; + *oy_loc = contour_y[min_i]; + *ox_edge = contour_ex[min_i]; + *oy_edge = contour_ey[min_i]; + + /* Deallocate contour buffers. */ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + + /*Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: adjust_high_curvature_minutia_V2 - Takes an initial minutia point +#cat: in a high-curvature area and adjusts its location and +#cat: direction. First, it walks and extracts the contour +#cat: of the detected feature looking for and processing any loop +#cat: discovered along the way. Once the contour is extracted, +#cat: the point of highest-curvature is determined and used to +#cat: adjust the location of the minutia point. The angle of +#cat: the line perpendicular to the tangent on the high-curvature +#cat: contour at the minutia point is used as the mintutia's +#cat: direction. + + Input: + x_loc - starting x-pixel coord of feature (interior to feature) + y_loc - starting y-pixel coord of feature (interior to feature) + x_edge - x-pixel coord of corresponding edge pixel + (exterior to feature) + y_edge - y-pixel coord of corresponding edge pixel + (exterior to feature) + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + plow_flow_map - pixelized Low Ridge Flow Map + lfsparms - parameters and thresholds for controlling LFS + Output: + oidir - direction of adjusted minutia point + ox_loc - adjusted x-pixel coord of feature + oy_loc - adjusted y-pixel coord of feature + ox_edge - adjusted x-pixel coord of corresponding edge pixel + oy_edge - adjusted y-pixel coord of corresponding edge pixel + minutiae - points to a list of detected minutia structures + Return Code: + Zero - minutia point processed successfully + IGNORE - minutia point is to be ignored + Negative - system error +**************************************************************************/ +int adjust_high_curvature_minutia_V2(int *oidir, int *ox_loc, int *oy_loc, + int *ox_edge, int *oy_edge, + const int x_loc, const int y_loc, + const int x_edge, const int y_edge, + unsigned char *bdata, const int iw, const int ih, + int *plow_flow_map, MINUTIAE *minutiae, const LFSPARMS *lfsparms) +{ + int ret; + int *contour_x, *contour_y, *contour_ex, *contour_ey, ncontour; + int min_i; + double min_theta; + int feature_pix; + int mid_x, mid_y, mid_pix; + int idir; + int half_contour, angle_edge; + + /* Set variable from parameter structure. */ + half_contour = lfsparms->high_curve_half_contour; + + /* Set edge length for computing contour's angle of curvature */ + /* to one quarter of desired pixel length of entire contour. */ + /* Ex. If half_contour==14, then contour length==29=(2X14)+1 */ + /* and angle_edge==7=(14/2). */ + angle_edge = half_contour>>1; + + /* Get the pixel value of current feature. */ + feature_pix = *(bdata + (y_loc * iw) + x_loc); + + /* Extract feature's contour. */ + if((ret = get_high_curvature_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, half_contour, + x_loc, y_loc, x_edge, y_edge, bdata, iw, ih))){ + /* Returns with: */ + /* 1. Successful or empty contour == 0 */ + /* If contour is empty, then contour lists are not allocated. */ + /* 2. Contour forms loop == LOOP_FOUND */ + /* 3. Sysetm error < 0 */ + + /* If the contour forms a loop... */ + if(ret == LOOP_FOUND){ + + /* If the order of the contour is clockwise, then the loops's */ + /* contour pixels are outside the corresponding edge pixels. We */ + /* definitely do NOT want to fill based on the feature pixel in */ + /* this case, because it is OUTSIDE the loop. For now we will */ + /* ignore the loop and the minutia that triggered its tracing. */ + /* It is likely that other minutia on the loop will be */ + /* detected that create a contour on the "inside" of the loop. */ + /* There is another issue here that could be addressed ... */ + /* It seems that many/multiple minutia are often detected within */ + /* the same loop, which currently requires retracing the loop, */ + /* locating minutia on opposite ends of the major axis of the */ + /* loop, and then determining that the minutia have already been */ + /* entered into the minutiae list upon processing the very first */ + /* minutia detected in the loop. There is a lot of redundant */ + /* work being done here! */ + /* Is_loop_clockwise takes a default value to be returned if the */ + /* routine is unable to determine the direction of the contour. */ + /* In this case, we want to IGNORE the loop if we can't tell its */ + /* direction so that we do not inappropriately fill the loop, so */ + /* we are passing the default value TRUE. */ + if((ret = is_loop_clockwise(contour_x, contour_y, ncontour, TRUE))){ + /* Deallocate contour lists. */ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + /* If we had a system error... */ + if(ret < 0) + /* Return the error code. */ + return(ret); + /* Otherwise, loop is clockwise, so return IGNORE. */ + return(IGNORE); + } + + /* Otherwise, process the clockwise-ordered contour of the loop */ + /* as it may contain minutia. If no minutia found, then it is */ + /* filled in. */ + ret = process_loop_V2(minutiae, contour_x, contour_y, + contour_ex, contour_ey, ncontour, + bdata, iw, ih, plow_flow_map, lfsparms); + /* Returns with: */ + /* 1. Successful processing of loop == 0 */ + /* 2. System error < 0 */ + + /* Deallocate contour lists. */ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + + /* If loop processed successfully ... */ + if(ret == 0) + /* Then either a minutia pair was extracted or the loop was */ + /* filled. Either way we want to IGNORE the minutia that */ + /* started the whole loop processing in the beginning. */ + return(IGNORE); + + /* Otherwise, there was a system error. */ + /* Return the resulting code. */ + return(ret); + } + + /* Otherwise not a loop, so get_high_curvature_contour incurred */ + /* a system error. Return the error code. */ + return(ret); + } + + /* If contour is empty ... then contour lists were not allocated, so */ + /* simply return IGNORE. The contour comes back empty when there */ + /* were not a sufficient number of points found on the contour. */ + if(ncontour == 0) + return(IGNORE); + + /* Otherwise, there are contour points to process. */ + + /* Given the contour, determine the point of highest curvature */ + /* (ie. forming the minimum angle between contour walls). */ + if((ret = min_contour_theta(&min_i, &min_theta, angle_edge, + contour_x, contour_y, ncontour))){ + /* Deallocate contour lists. */ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + /* Returns IGNORE or system error. Either way */ + /* free the contour and return the code. */ + return(ret); + } + + /* If the minimum theta found along the contour is too large... */ + if(min_theta >= lfsparms->max_high_curve_theta){ + /* Deallocate contour lists. */ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + /* Reject the high-curvature minutia, and return IGNORE. */ + return(IGNORE); + } + + /* Test to see if interior of curvature is OK. Compute midpoint */ + /* between left and right points symmetrically distant (angle_edge */ + /* pixels) from the contour's point of minimum theta. */ + mid_x = (contour_x[min_i-angle_edge] + contour_x[min_i+angle_edge])>>1; + mid_y = (contour_y[min_i-angle_edge] + contour_y[min_i+angle_edge])>>1; + mid_pix = *(bdata + (mid_y * iw) + mid_x); + /* If the interior pixel value is not the same as the feature's... */ + if(mid_pix != feature_pix){ + /* Deallocate contour lists. */ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + /* Reject the high-curvature minutia and return IGNORE. */ + return(IGNORE); + } + + /* Compute new direction based on line connecting adjusted feature */ + /* location and the midpoint in the feature's interior. */ + idir = line2direction(contour_x[min_i], contour_y[min_i], + mid_x, mid_y, lfsparms->num_directions); + + /* Set minutia location to minimum theta position on the contour. */ + *oidir = idir; + *ox_loc = contour_x[min_i]; + *oy_loc = contour_y[min_i]; + *ox_edge = contour_ex[min_i]; + *oy_edge = contour_ey[min_i]; + + /* Deallocate contour buffers. */ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + + /*Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: get_low_curvature_direction - Converts a bi-direcitonal IMAP direction +#cat: (based on a semi-circle) to a uni-directional value covering +#cat: a full circle based on the scan orientation used to detect +#cat: a minutia feature (horizontal or vertical) and whether the +#cat: detected minutia is appearing or disappearing. + + Input: + scan_dir - designates the feature scan orientation + appearing - designates the minutia as appearing or disappearing + imapval - IMAP block direction + ndirs - number of IMAP directions (in semicircle) + Return Code: + New direction - bi-directonal integer direction on full circle +*************************************************************************/ +int get_low_curvature_direction(const int scan_dir, const int appearing, + const int imapval, const int ndirs) +{ + int idir; + + /* Start direction out with IMAP value. */ + idir = imapval; + + /* NOTE! */ + /* The logic in this routine should hold whether for ridge endings */ + /* or for bifurcations. The examples in the comments show ridge */ + /* ending conditions only. */ + + /* CASE I : Ridge flow in Quadrant I; directions [0..8] */ + if(imapval <= (ndirs>>1)){ + /* I.A: HORIZONTAL scan */ + if(scan_dir == SCAN_HORIZONTAL){ + /* I.A.1: Appearing Minutia */ + if(appearing){ + /* Ex. 0 0 0 */ + /* 0 1 0 */ + /* ? ? */ + /* Ridge flow is up and to the right, whereas */ + /* actual ridge is running down and to the */ + /* left. */ + /* Thus: HORIZONTAL : appearing : should be */ + /* OPPOSITE the ridge flow direction. */ + idir += ndirs; + } + /* Otherwise: */ + /* I.A.2: Disappearing Minutia */ + /* Ex. ? ? */ + /* 0 1 0 */ + /* 0 0 0 */ + /* Ridge flow is up and to the right, which */ + /* should be SAME direction from which ridge */ + /* is projecting. */ + /* Thus: HORIZONTAL : disappearing : should */ + /* be the same as ridge flow direction. */ + } /* End if HORIZONTAL scan */ + /* Otherwise: */ + /* I.B: VERTICAL scan */ + else{ + /* I.B.1: Disappearing Minutia */ + if(!appearing){ + /* Ex. 0 0 */ + /* ? 1 0 */ + /* ? 0 0 */ + /* Ridge flow is up and to the right, whereas */ + /* actual ridge is projecting down and to the */ + /* left. */ + /* Thus: VERTICAL : disappearing : should be */ + /* OPPOSITE the ridge flow direction. */ + idir += ndirs; + } + /* Otherwise: */ + /* I.B.2: Appearing Minutia */ + /* Ex. 0 0 ? */ + /* 0 1 ? */ + /* 0 0 */ + /* Ridge flow is up and to the right, which */ + /* should be SAME direction the ridge is */ + /* running. */ + /* Thus: VERTICAL : appearing : should be */ + /* be the same as ridge flow direction. */ + } /* End else VERTICAL scan */ + } /* End if Quadrant I */ + + /* Otherwise: */ + /* CASE II : Ridge flow in Quadrant II; directions [9..15] */ + else{ + /* II.A: HORIZONTAL scan */ + if(scan_dir == SCAN_HORIZONTAL){ + /* II.A.1: Disappearing Minutia */ + if(!appearing){ + /* Ex. ? ? */ + /* 0 1 0 */ + /* 0 0 0 */ + /* Ridge flow is down and to the right, */ + /* whereas actual ridge is running up and to */ + /* the left. */ + /* Thus: HORIZONTAL : disappearing : should */ + /* be OPPOSITE the ridge flow direction.*/ + idir += ndirs; + } + /* Otherwise: */ + /* II.A.2: Appearing Minutia */ + /* Ex. 0 0 0 */ + /* 0 1 0 */ + /* ? ? */ + /* Ridge flow is down and to the right, which */ + /* should be same direction from which ridge */ + /* is projecting. */ + /* Thus: HORIZONTAL : appearing : should be */ + /* the SAME as ridge flow direction. */ + } /* End if HORIZONTAL scan */ + /* Otherwise: */ + /* II.B: VERTICAL scan */ + else{ + /* II.B.1: Disappearing Minutia */ + if(!appearing){ + /* Ex. ? 0 0 */ + /* ? 1 0 */ + /* 0 0 */ + /* Ridge flow is down and to the right, */ + /* whereas actual ridge is running up and to */ + /* the left. */ + /* Thus: VERTICAL : disappearing : should be */ + /* OPPOSITE the ridge flow direction. */ + idir += ndirs; + } + /* Otherwise: */ + /* II.B.2: Appearing Minutia */ + /* Ex. 0 0 */ + /* 0 1 ? */ + /* 0 0 ? */ + /* Ridge flow is down and to the right, which */ + /* should be same direction the ridge is */ + /* projecting. */ + /* Thus: VERTICAL : appearing : should be */ + /* be the SAME as ridge flow direction. */ + } /* End else VERTICAL scan */ + } /* End else Quadrant II */ + + /* Return resulting direction on range [0..31]. */ + return(idir); +} + diff --git a/libfprint/nbis/mindtct/morph.c b/libfprint/nbis/mindtct/morph.c new file mode 100644 index 00000000..b6be74f3 --- /dev/null +++ b/libfprint/nbis/mindtct/morph.c @@ -0,0 +1,226 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: MORPH.C + AUTHOR: Michael D. Garris + DATE: 10/04/1999 + UPDATED: 10/26/1999 by MDG + To avoid indisciminate erosion of pixels along + the edge of the binary image. + UPDATED: 03/16/2005 by MDG + + Contains general support image morphology routines required by + the NIST Latent Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + erode_charimage_2() + dilate_charimage_2() + get_south8_2() + get_north8_2() + get_east8_2() + get_west8_2() + +***********************************************************************/ + +#include +#include + +/************************************************************************* +************************************************************************** +#cat: erode_charimage_2 - Erodes an 8-bit image by setting true pixels to zero +#cat: if any of their 4 neighbors is zero. Allocation of the +#cat: output image is the responsibility of the caller. The +#cat: input image remains unchanged. This routine will NOT +#cat: erode pixels indiscriminately along the image border. + + Input: + inp - input 8-bit image to be eroded + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + out - contains to the resulting eroded image +**************************************************************************/ +void erode_charimage_2(unsigned char *inp, unsigned char *out, + const int iw, const int ih) +{ + int row, col; + unsigned char *itr = inp, *otr = out; + + memcpy(out, inp, iw*ih); + + /* for true pixels. kill pixel if there is at least one false neighbor */ + for ( row = 0 ; row < ih ; row++ ) + for ( col = 0 ; col < iw ; col++ ) + { + if (*itr) /* erode only operates on true pixels */ + { + /* more efficient with C's left to right evaluation of */ + /* conjuctions. E N S functions not executed if W is false */ + if (!(get_west8_2 ((char *)itr, col , 1 ) && + get_east8_2 ((char *)itr, col, iw , 1 ) && + get_north8_2((char *)itr, row, iw , 1 ) && + get_south8_2((char *)itr, row, iw, ih, 1))) + *otr = 0; + } + itr++ ; otr++; + } +} + +/************************************************************************* +************************************************************************** +#cat: dilate_charimage_2 - Dilates an 8-bit image by setting false pixels to +#cat: one if any of their 4 neighbors is non-zero. Allocation +#cat: of the output image is the responsibility of the caller. +#cat: The input image remains unchanged. + + Input: + inp - input 8-bit image to be dilated + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + out - contains to the resulting dilated image +**************************************************************************/ +void dilate_charimage_2(unsigned char *inp, unsigned char *out, + const int iw, const int ih) +{ + int row, col; + unsigned char *itr = inp, *otr = out; + + memcpy(out, inp, iw*ih); + + /* for all pixels. set pixel if there is at least one true neighbor */ + for ( row = 0 ; row < ih ; row++ ) + for ( col = 0 ; col < iw ; col++ ) + { + if (!*itr) /* pixel is already true, neighbors irrelevant */ + { + /* more efficient with C's left to right evaluation of */ + /* conjuctions. E N S functions not executed if W is false */ + if (get_west8_2 ((char *)itr, col , 0) || + get_east8_2 ((char *)itr, col, iw , 0) || + get_north8_2((char *)itr, row, iw , 0) || + get_south8_2((char *)itr, row, iw, ih, 0)) + *otr = 1; + } + itr++ ; otr++; + } +} + +/************************************************************************* +************************************************************************** +#cat: get_south8_2 - Returns the value of the 8-bit image pixel 1 below the +#cat: current pixel if defined else it returns (char)0. + + Input: + ptr - points to current pixel in image + row - y-coord of current pixel + iw - width (in pixels) of image + ih - height (in pixels) of image + failcode - return value if desired pixel does not exist + Return Code: + Zero - if neighboring pixel is undefined + (outside of image boundaries) + Pixel - otherwise, value of neighboring pixel +**************************************************************************/ +char get_south8_2(char *ptr, const int row, const int iw, const int ih, + const int failcode) +{ + if (row >= ih-1) /* catch case where image is undefined southwards */ + return failcode; /* use plane geometry and return code. */ + + return *(ptr+iw); +} + +/************************************************************************* +************************************************************************** +#cat: get_north8_2 - Returns the value of the 8-bit image pixel 1 above the +#cat: current pixel if defined else it returns (char)0. + + Input: + ptr - points to current pixel in image + row - y-coord of current pixel + iw - width (in pixels) of image + failcode - return value if desired pixel does not exist + Return Code: + Zero - if neighboring pixel is undefined + (outside of image boundaries) + Pixel - otherwise, value of neighboring pixel +**************************************************************************/ +char get_north8_2(char *ptr, const int row, const int iw, + const int failcode) +{ + if (row < 1) /* catch case where image is undefined northwards */ + return failcode; /* use plane geometry and return code. */ + + return *(ptr-iw); +} + +/************************************************************************* +************************************************************************** +#cat: get_east8_2 - Returns the value of the 8-bit image pixel 1 right of the +#cat: current pixel if defined else it returns (char)0. + + Input: + ptr - points to current pixel in image + col - x-coord of current pixel + iw - width (in pixels) of image + failcode - return value if desired pixel does not exist + Return Code: + Zero - if neighboring pixel is undefined + (outside of image boundaries) + Pixel - otherwise, value of neighboring pixel +**************************************************************************/ +char get_east8_2(char *ptr, const int col, const int iw, + const int failcode) +{ + if (col >= iw-1) /* catch case where image is undefined eastwards */ + return failcode; /* use plane geometry and return code. */ + + return *(ptr+ 1); +} + +/************************************************************************* +************************************************************************** +#cat: get_west8_2 - Returns the value of the 8-bit image pixel 1 left of the +#cat: current pixel if defined else it returns (char)0. + + Input: + ptr - points to current pixel in image + col - x-coord of current pixel + failcode - return value if desired pixel does not exist + Return Code: + Zero - if neighboring pixel is undefined + (outside of image boundaries) + Pixel - otherwise, value of neighboring pixel +**************************************************************************/ +char get_west8_2(char *ptr, const int col, const int failcode) +{ + if (col < 1) /* catch case where image is undefined westwards */ + return failcode; /* use plane geometry and return code. */ + + return *(ptr- 1); +} diff --git a/libfprint/nbis/mindtct/mytime.c b/libfprint/nbis/mindtct/mytime.c new file mode 100644 index 00000000..296503ae --- /dev/null +++ b/libfprint/nbis/mindtct/mytime.c @@ -0,0 +1,60 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: MYTIME.C + AUTHOR: Michael D. Garris + DATE: 03/16/1999 + + Contains global variable definitions used to record timings by + the NIST Latent Fingerprint System (LFS). +***********************************************************************/ + +/* Total time: including all initializations */ +/* : excluding all I/O except for required HO39 input image */ +/* (This is done to contrast the fact that the NIST GENHO39 */ +/* eliminates the need for this extra read.) */ +unsigned long total_timer; +float total_time = 0.0; /* time accumulator */ + +/* IMAP generation time: excluding initialization */ +unsigned long imap_timer; +float imap_time = 0.0; /* time accumulator */ + +/* Binarization time: excluding initialization */ +unsigned long bin_timer; +float bin_time = 0.0; /* time accumulator */ + +/* Minutia Detection time */ +unsigned long minutia_timer; +float minutia_time = 0.0; /* time accumulator */ + +/* Minutia Removal time */ +unsigned long rm_minutia_timer; +float rm_minutia_time = 0.0; /* time accumulator */ + +/* Neighbor Ridge Counting time */ +unsigned long ridge_count_timer; +float ridge_count_time = 0.0; /* time accumulator */ diff --git a/libfprint/nbis/mindtct/quality.c b/libfprint/nbis/mindtct/quality.c new file mode 100644 index 00000000..834767f4 --- /dev/null +++ b/libfprint/nbis/mindtct/quality.c @@ -0,0 +1,467 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: QUALITY.C + AUTHOR: Michael D. Garris + DATE: 09/25/2000 + UPDATED: 03/16/2005 by MDG + + Contains routines responsible for assessing minutia quality + and assigning different reliability measures. These routines + are primarily to support the rejection of bad minutiae. + +*********************************************************************** + ROUTINES: + gen_quality_map() + combined_minutia_quality() + grayscale_reliability() + get_neighborhood_stats() + reliability_fr_quality_map() + +***********************************************************************/ + +#include +#include +#include +#include +#include + +/*********************************************************************** +************************************************************************ +#cat: gen_quality_map - Takes a direction map, low contrast map, low ridge +#cat: flow map, and high curvature map, and combines them +#cat: into a single map containing 5 levels of decreasing +#cat: quality. This is done through a set of heuristics. + + Code originally written by Austin Hicklin for FBI ATU + Modified by Michael D. Garris (NIST) Sept. 1, 2000 + + Set quality of 0(unusable)..4(good) (I call these grades A..F) + 0/F: low contrast OR no direction + 1/D: low flow OR high curve + (with low contrast OR no direction neighbor) + (or within NEIGHBOR_DELTA of edge) + 2/C: low flow OR high curve + (or good quality with low contrast/no direction neighbor) + 3/B: good quality with low flow / high curve neighbor + 4/A: good quality (none of the above) + + Generally, the features in A/B quality are useful, the C/D quality + ones are not. + + Input: + direction_map - map with blocks assigned dominant ridge flow direction + low_contrast_map - map with blocks flagged as low contrast + low_flow_map - map with blocks flagged as low ridge flow + high_curve_map - map with blocks flagged as high curvature + map_w - width (in blocks) of the maps + map_h - height (in blocks) of the maps + Output: + oqmap - points to new quality map + Return Code: + Zero - successful completion + Negative - system error +************************************************************************/ +int gen_quality_map(int **oqmap, int *direction_map, int *low_contrast_map, + int *low_flow_map, int *high_curve_map, + const int map_w, const int map_h) +{ + + int *QualMap; + int thisX, thisY; + int compX, compY; + int arrayPos, arrayPos2; + int QualOffset; + + QualMap = (int *)malloc(map_w * map_h * sizeof(int)); + if(QualMap == (int *)NULL){ + fprintf(stderr, "ERROR : gen_quality_map : malloc : QualMap\n"); + return(-2); + } + + /* Foreach row of blocks in maps ... */ + for(thisY=0; thisY map_h - 1 - NEIGHBOR_DELTA || + thisX < NEIGHBOR_DELTA || thisX > map_w - 1 - NEIGHBOR_DELTA) + /* Set block's quality to 1/E. */ + QualMap[arrayPos]=1; + /* Otherwise, test neighboring blocks ... */ + else{ + /* Initialize quality adjustment to 0. */ + QualOffset=0; + /* Foreach row in neighborhood ... */ + for(compY=thisY-NEIGHBOR_DELTA; + compY<=thisY+NEIGHBOR_DELTA;compY++){ + /* Foreach block in neighborhood */ + /* (including current block)... */ + for(compX=thisX-NEIGHBOR_DELTA; + compX<=thisX+NEIGHBOR_DELTA;compX++) { + /* Compute neighboring block's index. */ + arrayPos2 = (compY*map_w)+compX; + /* If neighbor block (which might be itself) has */ + /* low contrast or INVALID direction .. */ + if(low_contrast_map[arrayPos2] || + direction_map[arrayPos2]<0) { + /* Set quality adjustment to -2. */ + QualOffset=-2; + /* Done with neighborhood row. */ + break; + } + /* Otherwise, if neighbor block (which might be */ + /* itself) has low flow or high curvature ... */ + else if(low_flow_map[arrayPos2] || + high_curve_map[arrayPos2]) { + /* Set quality to -1 if not already -2. */ + QualOffset=min(QualOffset,-1); + } + } + } + /* Decrement minutia quality by neighborhood adjustment. */ + QualMap[arrayPos]+=QualOffset; + } + } + } + } + + /* Set output pointer. */ + *oqmap = QualMap; + /* Return normally. */ + return(0); +} + +/*********************************************************************** +************************************************************************ +#cat: combined_minutia_quality - Combines quality measures derived from +#cat: the quality map and neighboring pixel statistics to +#cat: infer a reliability measure on the scale [0...1]. + + Input: + minutiae - structure contining the detected minutia + quality_map - map with blocks assigned 1 of 5 quality levels + map_w - width (in blocks) of the map + map_h - height (in blocks) of the map + blocksize - size (in pixels) of each block in the map + idata - 8-bit grayscale fingerprint image + iw - width (in pixels) of the image + ih - height (in pixels) of the image + id - depth (in pixels) of the image + ppmm - scan resolution of the image in pixels/mm + Output: + minutiae - updated reliability members + Return Code: + Zero - successful completion + Negative - system error +************************************************************************/ +int combined_minutia_quality(MINUTIAE *minutiae, + int *quality_map, const int mw, const int mh, const int blocksize, + unsigned char *idata, const int iw, const int ih, const int id, + const double ppmm) +{ + int ret, i, index, radius_pix; + int *pquality_map, qmap_value; + MINUTIA *minutia; + double gs_reliability, reliability; + + /* If image is not 8-bit grayscale ... */ + if(id != 8){ + fprintf(stderr, "ERROR : combined_miutia_quality : "); + fprintf(stderr, "image must pixel depth = %d must be 8 ", id); + fprintf(stderr, "to compute reliability\n"); + return(-2); + } + + /* Compute pixel radius of neighborhood based on image's scan resolution. */ + radius_pix = sround(RADIUS_MM * ppmm); + + /* Expand block map values to pixel map. */ + if((ret = pixelize_map(&pquality_map, iw, ih, + quality_map, mw, mh, blocksize))){ + return(ret); + } + + /* Foreach minutiae detected ... */ + for(i = 0; i < minutiae->num; i++){ + /* Assign minutia pointer. */ + minutia = minutiae->list[i]; + + /* Compute reliability from stdev and mean of pixel neighborhood. */ + gs_reliability = grayscale_reliability(minutia, + idata, iw, ih, radius_pix); + + /* Lookup quality map value. */ + /* Compute minutia pixel index. */ + index = (minutia->y * iw) + minutia->x; + /* Switch on pixel's quality value ... */ + qmap_value = pquality_map[index]; + + /* Combine grayscale reliability and quality map value. */ + switch(qmap_value){ + /* Quality A : [50..99]% */ + case 4 : + reliability = 0.50 + (0.49 * gs_reliability); + break; + /* Quality B : [25..49]% */ + case 3 : + reliability = 0.25 + (0.24 * gs_reliability); + break; + /* Quality C : [10..24]% */ + case 2 : + reliability = 0.10 + (0.14 * gs_reliability); + break; + /* Quality D : [5..9]% */ + case 1 : + reliability = 0.05 + (0.04 * gs_reliability); + break; + /* Quality E : 1% */ + case 0 : + reliability = 0.01; + break; + /* Error if quality value not in range [0..4]. */ + default: + fprintf(stderr, "ERROR : combined_miutia_quality : "); + fprintf(stderr, "unexpected quality map value %d ", qmap_value); + fprintf(stderr, "not in range [0..4]\n"); + free(pquality_map); + return(-3); + } + minutia->reliability = reliability; + } + + /* NEW 05-08-2002 */ + free(pquality_map); + + /* Return normally. */ + return(0); +} + + +/*********************************************************************** +************************************************************************ +#cat: grayscale_reliability - Given a minutia point, computes a reliability +#cat: measure from the stdev and mean of its pixel neighborhood. + + Code originally written by Austin Hicklin for FBI ATU + Modified by Michael D. Garris (NIST) Sept. 25, 2000 + + GrayScaleReliability - reasonable reliability heuristic, returns + 0.0 .. 1.0 based on stdev and Mean of a localized histogram where + "ideal" stdev is >=64; "ideal" Mean is 127. In a 1 ridge radius + (11 pixels), if the bytevalue (shade of gray) in the image has a + stdev of >= 64 & a mean of 127, returns 1.0 (well defined + light & dark areas in equal proportions). + + Input: + minutia - structure containing detected minutia + idata - 8-bit grayscale fingerprint image + iw - width (in pixels) of the image + ih - height (in pixels) of the image + radius_pix - pixel radius of surrounding neighborhood + Return Value: + reliability - computed reliability measure +************************************************************************/ +double grayscale_reliability(MINUTIA *minutia, unsigned char *idata, + const int iw, const int ih, const int radius_pix) +{ + double mean, stdev; + double reliability; + + get_neighborhood_stats(&mean, &stdev, minutia, idata, iw, ih, radius_pix); + + reliability = min((stdev>IDEALSTDEV ? 1.0 : stdev/(double)IDEALSTDEV), + (1.0-(fabs(mean-IDEALMEAN)/(double)IDEALMEAN))); + + return(reliability); +} + + +/*********************************************************************** +************************************************************************ +#cat: get_neighborhood_stats - Given a minutia point, computes the mean +#cat: and stdev of the 8-bit grayscale pixels values in a +#cat: surrounding neighborhood with specified radius. + + Code originally written by Austin Hicklin for FBI ATU + Modified by Michael D. Garris (NIST) Sept. 25, 2000 + + Input: + minutia - structure containing detected minutia + idata - 8-bit grayscale fingerprint image + iw - width (in pixels) of the image + ih - height (in pixels) of the image + radius_pix - pixel radius of surrounding neighborhood + Output: + mean - mean of neighboring pixels + stdev - standard deviation of neighboring pixels +************************************************************************/ +void get_neighborhood_stats(double *mean, double *stdev, MINUTIA *minutia, + unsigned char *idata, const int iw, const int ih, + const int radius_pix) +{ + int i, x, y, rows, cols; + int n = 0, sumX = 0, sumXX = 0; + int histogram[256]; + + /* Zero out histogram. */ + memset(histogram, 0, 256 * sizeof(int)); + + /* Set minutia's coordinate variables. */ + x = minutia->x; + y = minutia->y; + + + /* If minutiae point is within sampleboxsize distance of image border, */ + /* a value of 0 reliability is returned. */ + if ((x < radius_pix) || (x > iw-radius_pix-1) || + (y < radius_pix) || (y > ih-radius_pix-1)) { + *mean = 0.0; + *stdev = 0.0; + return; + + } + + /* Foreach row in neighborhood ... */ + for(rows = y - radius_pix; + rows <= y + radius_pix; + rows++){ + /* Foreach column in neighborhood ... */ + for(cols = x - radius_pix; + cols <= x + radius_pix; + cols++){ + /* Bump neighbor's pixel value bin in histogram. */ + histogram[*(idata+(rows * iw)+cols)]++; + } + } + + /* Foreach grayscale pixel bin ... */ + for(i = 0; i < 256; i++){ + if(histogram[i]){ + /* Accumulate Sum(X[i]) */ + sumX += (i * histogram[i]); + /* Accumulate Sum(X[i]^2) */ + sumXX += (i * i * histogram[i]); + /* Accumulate N samples */ + n += histogram[i]; + } + } + + /* Mean = Sum(X[i])/N */ + *mean = sumX/(double)n; + /* Stdev = sqrt((Sum(X[i]^2)/N) - Mean^2) */ + *stdev = sqrt((sumXX/(double)n) - ((*mean)*(*mean))); +} + +/*********************************************************************** +************************************************************************ +#cat: reliability_fr_quality_map - Takes a set of minutiae and assigns +#cat: each one a reliability measure based on 1 of 5 possible +#cat: quality levels from its location in a quality map. + + Input: + minutiae - structure contining the detected minutia + quality_map - map with blocks assigned 1 of 5 quality levels + map_w - width (in blocks) of the map + map_h - height (in blocks) of the map + blocksize - size (in pixels) of each block in the map + Output: + minutiae - updated reliability members + Return Code: + Zero - successful completion + Negative - system error +************************************************************************/ +int reliability_fr_quality_map(MINUTIAE *minutiae, + int *quality_map, const int mw, const int mh, + const int iw, const int ih, const int blocksize) +{ + int ret, i, index; + int *pquality_map; + MINUTIA *minutia; + + /* Expand block map values to pixel map. */ + if((ret = pixelize_map(&pquality_map, iw, ih, + quality_map, mw, mh, blocksize))){ + return(ret); + } + + /* Foreach minutiae detected ... */ + for(i = 0; i < minutiae->num; i++){ + /* Assign minutia pointer. */ + minutia = minutiae->list[i]; + /* Compute minutia pixel index. */ + index = (minutia->y * iw) + minutia->x; + /* Switch on pixel's quality value ... */ + switch(pquality_map[index]){ + case 0: + minutia->reliability = 0.0; + break; + case 1: + minutia->reliability = 0.25; + break; + case 2: + minutia->reliability = 0.50; + break; + case 3: + minutia->reliability = 0.75; + break; + case 4: + minutia->reliability = 0.99; + break; + /* Error if quality value not in range [0..4]. */ + default: + fprintf(stderr, "ERROR : reliability_fr_quality_map :"); + fprintf(stderr, "unexpected quality value %d ", + pquality_map[index]); + fprintf(stderr, "not in range [0..4]\n"); + return(-2); + } + } + + /* Deallocate pixelized quality map. */ + free(pquality_map); + + /* Return normally. */ + return(0); +} diff --git a/libfprint/nbis/mindtct/remove.c b/libfprint/nbis/mindtct/remove.c new file mode 100644 index 00000000..e3ddbefc --- /dev/null +++ b/libfprint/nbis/mindtct/remove.c @@ -0,0 +1,3404 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: REMOVE.C + AUTHOR: Michael D. Garris + DATE: 08/02/1999 + UPDATED: 10/04/1999 Version 2 by MDG + UPDATED: 03/16/2005 by MDG + + Contains routines responsible for detecting and removing false + minutiae as part of the NIST Latent Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + remove_false_minutia() + remove_false_minutia_V2() + remove_holes() + remove_hooks() + remove_hooks_islands_overlaps() + remove_islands_and_lakes() + remove_malformations() + remove_near_invblocks() + remove_near_invblocks_V2() + remove_pointing_invblock() + remove_pointing_invblock_V2() + remove_overlaps() + remove_pores() + remove_pores_V2() + remove_or_adjust_side_minutiae() + remove_or_adjust_side_minutiae_V2() + +***********************************************************************/ + +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: remove_false_minutia - Takes a list of true and false minutiae and +#cat: attempts to detect and remove the false minutiae based +#cat: on a series of tests. + + Input: + minutiae - list of true and false minutiae + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + nmap - IMAP ridge flow matrix with invalid, high-curvature, + and no-valid-neighbor regions identified + mw - width in blocks of the NMAP + mh - height in blocks of the NMAP + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of pruned minutiae + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int remove_false_minutia(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + int *nmap, const int mw, const int mh, + const LFSPARMS *lfsparms) +{ + int ret; + + /* Sort minutiae points top-to-bottom and left-to-right. */ + if((ret = sort_minutiae_y_x(minutiae, iw, ih))){ + return(ret); + } + + if((ret = link_minutiae(minutiae, bdata, iw, ih, nmap, mw, mh, lfsparms))){ + return(ret); + } + + if((ret = remove_hooks_islands_lakes_overlaps(minutiae, bdata, iw, ih, + lfsparms))){ + return(ret); + } + + if((ret = remove_pointing_invblock(minutiae, nmap, mw, mh, lfsparms))){ + return(ret); + } + + if((ret = remove_holes(minutiae, bdata, iw, ih, lfsparms))){ + return(ret); + } + + if((ret = remove_or_adjust_side_minutiae(minutiae, + bdata, iw, ih, lfsparms))){ + return(ret); + } + + if((ret = remove_near_invblock(minutiae, nmap, mw, mh, lfsparms))){ + return(ret); + } + + if((ret = remove_pores(minutiae, bdata, iw, ih, nmap, mw, mh, lfsparms))){ + return(ret); + } + + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: remove_false_minutia_V2 - Takes a list of true and false minutiae and +#cat: attempts to detect and remove the false minutiae based +#cat: on a series of tests. + + Input: + minutiae - list of true and false minutiae + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + direction_map - map of image blocks containing directional ridge flow + low_flow_map - map of image blocks flagged as LOW RIDGE FLOW + high_curve_map - map of image blocks flagged as HIGH CURVATURE + mw - width in blocks of the maps + mh - height in blocks of the maps + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of pruned minutiae + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int remove_false_minutia_V2(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + int *direction_map, int *low_flow_map, int *high_curve_map, + const int mw, const int mh, const LFSPARMS *lfsparms) +{ + int ret; + + /* 1. Sort minutiae points top-to-bottom and left-to-right. */ + if((ret = sort_minutiae_y_x(minutiae, iw, ih))){ + return(ret); + } + + /* 2. Remove minutiae on lakes (filled with white pixels) and */ + /* islands (filled with black pixels), both defined by a pair of */ + /* minutia points. */ + if((ret = remove_islands_and_lakes(minutiae, bdata, iw, ih, lfsparms))){ + return(ret); + } + + /* 3. Remove minutiae on holes in the binary image defined by a */ + /* single point. */ + if((ret = remove_holes(minutiae, bdata, iw, ih, lfsparms))){ + return(ret); + } + + /* 4. Remove minutiae that point sufficiently close to a block with */ + /* INVALID direction. */ + if((ret = remove_pointing_invblock_V2(minutiae, direction_map, mw, mh, + lfsparms))){ + return(ret); + } + + /* 5. Remove minutiae that are sufficiently close to a block with */ + /* INVALID direction. */ + if((ret = remove_near_invblock_V2(minutiae, direction_map, mw, mh, + lfsparms))){ + return(ret); + } + + /* 6. Remove or adjust minutiae that reside on the side of a ridge */ + /* or valley. */ + if((ret = remove_or_adjust_side_minutiae_V2(minutiae, bdata, iw, ih, + direction_map, mw, mh, lfsparms))){ + return(ret); + } + + /* 7. Remove minutiae that form a hook on the side of a ridge or valley. */ + if((ret = remove_hooks(minutiae, bdata, iw, ih, lfsparms))){ + return(ret); + } + + /* 8. Remove minutiae that are on opposite sides of an overlap. */ + if((ret = remove_overlaps(minutiae, bdata, iw, ih, lfsparms))){ + return(ret); + } + + /* 9. Remove minutiae that are "irregularly" shaped. */ + if((ret = remove_malformations(minutiae, bdata, iw, ih, + low_flow_map, mw, mh, lfsparms))){ + return(ret); + } + + /* 10. Remove minutiae that form long, narrow, loops in the */ + /* "unreliable" regions in the binary image. */ + if((ret = remove_pores_V2(minutiae, bdata, iw, ih, + direction_map, low_flow_map, high_curve_map, + mw, mh, lfsparms))){ + return(ret); + } + + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: remove_holes - Removes minutia points on small loops around valleys. + + Input: + minutiae - list of true and false minutiae + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of pruned minutiae + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int remove_holes(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + const LFSPARMS *lfsparms) +{ + int i, ret; + MINUTIA *minutia; + + print2log("\nREMOVING HOLES:\n"); + + i = 0; + /* Foreach minutia remaining in list ... */ + while(i < minutiae->num){ + /* Assign a temporary pointer. */ + minutia = minutiae->list[i]; + /* If current minutia is a bifurcation ... */ + if(minutia->type == BIFURCATION){ + /* Check to see if it is on a loop of specified length (ex. 15). */ + ret = on_loop(minutia, lfsparms->small_loop_len, bdata, iw, ih); + /* If minutia is on a loop ... or loop test IGNORED */ + if((ret == LOOP_FOUND) || (ret == IGNORE)){ + + print2log("%d,%d RM\n", minutia->x, minutia->y); + + /* Then remove the minutia from list. */ + if((ret = remove_minutia(i, minutiae))){ + /* Return error code. */ + return(ret); + } + /* No need to advance because next minutia has "slid" */ + /* into position pointed to by 'i'. */ + } + /* If the minutia is NOT on a loop... */ + else if (ret == FALSE){ + /* Simply advance to next minutia in the list. */ + i++; + } + /* Otherwise, an ERROR occurred while looking for loop. */ + else{ + /* Return error code. */ + return(ret); + } + } + /* Otherwise, the current minutia is a ridge-ending... */ + else{ + /* Advance to next minutia in the list. */ + i++; + } + } + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: remove_hooks - Takes a list of true and false minutiae and +#cat: attempts to detect and remove those false minutiae that +#cat: are on a hook (white or black). + + Input: + minutiae - list of true and false minutiae + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of pruned minutiae + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int remove_hooks(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + const LFSPARMS *lfsparms) +{ + int *to_remove; + int i, f, s, ret; + int delta_y, full_ndirs, qtr_ndirs, deltadir, min_deltadir; + MINUTIA *minutia1, *minutia2; + double dist; + + print2log("\nREMOVING HOOKS:\n"); + + /* Allocate list of minutia indices that upon completion of testing */ + /* should be removed from the minutiae lists. Note: That using */ + /* "calloc" initializes the list to FALSE. */ + to_remove = (int *)calloc(minutiae->num, sizeof(int)); + if(to_remove == (int *)NULL){ + fprintf(stderr, "ERROR : remove_hooks : calloc : to_remove\n"); + return(-640); + } + + /* Compute number directions in full circle. */ + full_ndirs = lfsparms->num_directions<<1; + /* Compute number of directions in 45=(180/4) degrees. */ + qtr_ndirs = lfsparms->num_directions>>2; + + /* Minimum allowable deltadir to consider joining minutia. */ + /* (The closer the deltadir is to 180 degrees, the more likely the join. */ + /* When ndirs==16, then this value is 11=(3*4)-1 == 123.75 degrees. */ + /* I chose to parameterize this threshold based on a fixed fraction of */ + /* 'ndirs' rather than on passing in a parameter in degrees and doing */ + /* the conversion. I doubt the difference matters. */ + min_deltadir = (3 * qtr_ndirs) - 1; + + f = 0; + /* Foreach primary (first) minutia (except for last one in list) ... */ + while(f < minutiae->num-1){ + + /* If current first minutia not previously set to be removed. */ + if(!to_remove[f]){ + + print2log("\n"); + + /* Set first minutia to temporary pointer. */ + minutia1 = minutiae->list[f]; + /* Foreach secondary (second) minutia to right of first minutia ... */ + s = f+1; + while(s < minutiae->num){ + /* Set second minutia to temporary pointer. */ + minutia2 = minutiae->list[s]; + + print2log("1:%d(%d,%d)%d 2:%d(%d,%d)%d ", + f, minutia1->x, minutia1->y, minutia1->type, + s, minutia2->x, minutia2->y, minutia2->type); + + /* The binary image is potentially being edited during each */ + /* iteration of the secondary minutia loop, therefore */ + /* minutia pixel values may be changed. We need to catch */ + /* these events by using the next 2 tests. */ + + /* If the first minutia's pixel has been previously changed... */ + if(*(bdata+(minutia1->y*iw)+minutia1->x) != minutia1->type){ + print2log("\n"); + /* Then break out of secondary loop and skip to next first. */ + break; + } + + /* If the second minutia's pixel has been previously changed... */ + if(*(bdata+(minutia2->y*iw)+minutia2->x) != minutia2->type) + /* Set to remove second minutia. */ + to_remove[s] = TRUE; + + /* If the second minutia not previously set to be removed. */ + if(!to_remove[s]){ + + /* Compute delta y between 1st & 2nd minutiae and test. */ + delta_y = minutia2->y - minutia1->y; + /* If delta y small enough (ex. < 8 pixels) ... */ + if(delta_y <= lfsparms->max_rmtest_dist){ + + print2log("1DY "); + + /* Compute Euclidean distance between 1st & 2nd mintuae. */ + dist = distance(minutia1->x, minutia1->y, + minutia2->x, minutia2->y); + /* If distance is NOT too large (ex. < 8 pixels) ... */ + if(dist <= lfsparms->max_rmtest_dist){ + + print2log("2DS "); + + /* Compute "inner" difference between directions on */ + /* a full circle and test. */ + if((deltadir = closest_dir_dist(minutia1->direction, + minutia2->direction, full_ndirs)) == + INVALID_DIR){ + free(to_remove); + fprintf(stderr, + "ERROR : remove_hooks : INVALID direction\n"); + return(-641); + } + /* If the difference between dirs is large enough ... */ + /* (the more 1st & 2nd point away from each other the */ + /* more likely they should be joined) */ + if(deltadir > min_deltadir){ + + print2log("3DD "); + + /* If 1st & 2nd minutiae are NOT same type ... */ + if(minutia1->type != minutia2->type){ + /* Check to see if pair on a hook with contour */ + /* of specified length (ex. 15 pixels) ... */ + + ret = on_hook(minutia1, minutia2, + lfsparms->max_hook_len, + bdata, iw, ih); + + /* If hook detected between pair ... */ + if(ret == HOOK_FOUND){ + + print2log("4HK RM\n"); + + /* Set to remove first minutia. */ + to_remove[f] = TRUE; + /* Set to remove second minutia. */ + to_remove[s] = TRUE; + } + /* If hook test IGNORED ... */ + else if (ret == IGNORE){ + + print2log("RM\n"); + + /* Set to remove first minutia. */ + to_remove[f] = TRUE; + /* Skip to next 1st minutia by breaking out of */ + /* inner secondary loop. */ + break; + } + /* If system error occurred during hook test ... */ + else if (ret < 0){ + free(to_remove); + return(ret); + } + /* Otherwise, no hook found, so skip to next */ + /* second minutia. */ + else + print2log("\n"); + } + else + print2log("\n"); + /* End different type test. */ + }/* End deltadir test. */ + else + print2log("\n"); + }/* End distance test. */ + else + print2log("\n"); + } + /* Otherwise, current 2nd too far below 1st, so skip to next */ + /* 1st minutia. */ + else{ + + print2log("\n"); + + /* Break out of inner secondary loop. */ + break; + }/* End delta-y test. */ + + }/* End if !to_remove[s] */ + else + print2log("\n"); + + /* Bump to next second minutia in minutiae list. */ + s++; + }/* End secondary minutiae loop. */ + + }/* Otherwise, first minutia already flagged to be removed. */ + + /* Bump to next first minutia in minutiae list. */ + f++; + }/* End primary minutiae loop. */ + + /* Now remove all minutiae in list that have been flagged for removal. */ + /* NOTE: Need to remove the minutia from their lists in reverse */ + /* order, otherwise, indices will be off. */ + for(i = minutiae->num-1; i >= 0; i--){ + /* If the current minutia index is flagged for removal ... */ + if(to_remove[i]){ + /* Remove the minutia from the minutiae list. */ + if((ret = remove_minutia(i, minutiae))){ + free(to_remove); + return(ret); + } + } + } + + /* Deallocate flag list. */ + free(to_remove); + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: remove_hooks_islands_lakes_overlaps - Removes minutia points on hooks, +#cat: islands, lakes, and overlaps and fills in small small +#cat: loops in the binary image and joins minutia features in +#cat: the image on opposite sides of an overlap. So, this +#cat: routine not only prunes minutia points but it edits the +#cat: binary input image as well. + + Input: + minutiae - list of true and false minutiae + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of pruned minutiae + bdata - edited binary image with loops filled and overlaps removed + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int remove_hooks_islands_lakes_overlaps(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + const LFSPARMS *lfsparms) +{ + int *to_remove; + int i, f, s, ret; + int delta_y, full_ndirs, qtr_ndirs, deltadir, min_deltadir; + int *loop_x, *loop_y, *loop_ex, *loop_ey, nloop; + MINUTIA *minutia1, *minutia2; + double dist; + + print2log("\nREMOVING HOOKS, ISLANDS, LAKES, AND OVERLAPS:\n"); + + /* Allocate list of minutia indices that upon completion of testing */ + /* should be removed from the minutiae lists. Note: That using */ + /* "calloc" initializes the list to FALSE. */ + to_remove = (int *)calloc(minutiae->num, sizeof(int)); + if(to_remove == (int *)NULL){ + fprintf(stderr, + "ERROR : remove_hooks_islands_lakes_overlaps : calloc : to_remove\n"); + return(-300); + } + + /* Compute number directions in full circle. */ + full_ndirs = lfsparms->num_directions<<1; + /* Compute number of directions in 45=(180/4) degrees. */ + qtr_ndirs = lfsparms->num_directions>>2; + + /* Minimum allowable deltadir to consider joining minutia. */ + /* (The closer the deltadir is to 180 degrees, the more likely the join. */ + /* When ndirs==16, then this value is 11=(3*4)-1 == 123.75 degrees. */ + /* I chose to parameterize this threshold based on a fixed fraction of */ + /* 'ndirs' rather than on passing in a parameter in degrees and doing */ + /* the conversion. I doubt the difference matters. */ + min_deltadir = (3 * qtr_ndirs) - 1; + + f = 0; + /* Foreach primary (first) minutia (except for last one in list) ... */ + while(f < minutiae->num-1){ + + /* If current first minutia not previously set to be removed. */ + if(!to_remove[f]){ + + print2log("\n"); + + /* Set first minutia to temporary pointer. */ + minutia1 = minutiae->list[f]; + /* Foreach secondary (second) minutia to right of first minutia ... */ + s = f+1; + while(s < minutiae->num){ + /* Set second minutia to temporary pointer. */ + minutia2 = minutiae->list[s]; + + print2log("1:%d(%d,%d)%d 2:%d(%d,%d)%d ", + f, minutia1->x, minutia1->y, minutia1->type, + s, minutia2->x, minutia2->y, minutia2->type); + + /* The binary image is potentially being edited during each */ + /* iteration of the secondary minutia loop, therefore */ + /* minutia pixel values may be changed. We need to catch */ + /* these events by using the next 2 tests. */ + + /* If the first minutia's pixel has been previously changed... */ + if(*(bdata+(minutia1->y*iw)+minutia1->x) != minutia1->type){ + print2log("\n"); + /* Then break out of secondary loop and skip to next first. */ + break; + } + + /* If the second minutia's pixel has been previously changed... */ + if(*(bdata+(minutia2->y*iw)+minutia2->x) != minutia2->type) + /* Set to remove second minutia. */ + to_remove[s] = TRUE; + + /* If the second minutia not previously set to be removed. */ + if(!to_remove[s]){ + + /* Compute delta y between 1st & 2nd minutiae and test. */ + delta_y = minutia2->y - minutia1->y; + /* If delta y small enough (ex. < 8 pixels) ... */ + if(delta_y <= lfsparms->max_rmtest_dist){ + + print2log("1DY "); + + /* Compute Euclidean distance between 1st & 2nd mintuae. */ + dist = distance(minutia1->x, minutia1->y, + minutia2->x, minutia2->y); + /* If distance is NOT too large (ex. < 8 pixels) ... */ + if(dist <= lfsparms->max_rmtest_dist){ + + print2log("2DS "); + + /* Compute "inner" difference between directions on */ + /* a full circle and test. */ + if((deltadir = closest_dir_dist(minutia1->direction, + minutia2->direction, full_ndirs)) == + INVALID_DIR){ + free(to_remove); + fprintf(stderr, + "ERROR : remove_hooks_islands_lakes_overlaps : INVALID direction\n"); + return(-301); + } + /* If the difference between dirs is large enough ... */ + /* (the more 1st & 2nd point away from each other the */ + /* more likely they should be joined) */ + if(deltadir > min_deltadir){ + + print2log("3DD "); + + /* If 1st & 2nd minutiae are NOT same type ... */ + if(minutia1->type != minutia2->type){ + /* Check to see if pair on a hook with contour */ + /* of specified length (ex. 15 pixels) ... */ + ret = on_hook(minutia1, minutia2, + lfsparms->max_hook_len, + bdata, iw, ih); + /* If hook detected between pair ... */ + if(ret == HOOK_FOUND){ + + print2log("4HK RM\n"); + + /* Set to remove first minutia. */ + to_remove[f] = TRUE; + /* Set to remove second minutia. */ + to_remove[s] = TRUE; + } + /* If hook test IGNORED ... */ + else if (ret == IGNORE){ + + print2log("RM\n"); + + /* Set to remove first minutia. */ + to_remove[f] = TRUE; + /* Skip to next 1st minutia by breaking out of */ + /* inner secondary loop. */ + break; + } + /* If system error occurred during hook test ... */ + else if (ret < 0){ + free(to_remove); + return(ret); + } + /* Otherwise, no hook found, so skip to next */ + /* second minutia. */ + else + print2log("\n"); + } + /* Otherwise, pair is the same type, so test to see */ + /* if both are on an island or lake. */ + else{ + /* Check to see if pair on a loop of specified */ + /* half length (ex. 15 pixels) ... */ + ret = on_island_lake(&loop_x, &loop_y, + &loop_ex, &loop_ey, &nloop, + minutia1, minutia2, + lfsparms->max_half_loop, + bdata, iw, ih); + /* If pair is on island/lake ... */ + if(ret == LOOP_FOUND){ + + print2log("4IL RM\n"); + + /* Fill the loop. */ + if((ret = fill_loop(loop_x, loop_y, nloop, + bdata, iw, ih))){ + free_contour(loop_x, loop_y, + loop_ex, loop_ey); + free(to_remove); + return(ret); + } + /* Set to remove first minutia. */ + to_remove[f] = TRUE; + /* Set to remove second minutia. */ + to_remove[s] = TRUE; + /* Deallocate loop contour. */ + free_contour(loop_x, loop_y, loop_ex, loop_ey); + } + /* If island/lake test IGNORED ... */ + else if (ret == IGNORE){ + + print2log("RM\n"); + + /* Set to remove first minutia. */ + to_remove[f] = TRUE; + /* Skip to next 1st minutia by breaking out of */ + /* inner secondary loop. */ + break; + } + /* If ERROR while looking for island/lake ... */ + else if (ret < 0){ + free(to_remove); + return(ret); + } + /* Otherwise, minutia pair not on island/lake, */ + /* but might be on an overlap. */ + else { + /* If free path exists between pair ... */ + if(free_path(minutia1->x, minutia1->y, + minutia2->x, minutia2->y, + bdata, iw, ih, lfsparms)){ + + print2log("4OV RM\n"); + + /* Then assume overlap, so ... */ + /* Join first and second minutiae in image. */ + if((ret = join_minutia(minutia1, minutia2, + bdata, iw, ih, NO_BOUNDARY, + JOIN_LINE_RADIUS))){ + free(to_remove); + return(ret); + } + /* Set to remove first minutia. */ + to_remove[f] = TRUE; + /* Set to remove second minutia. */ + to_remove[s] = TRUE; + } + /* Otherwise, pair not on an overlap, so skip */ + /* to next second minutia. */ + else + print2log("\n"); + }/* End overlap test. */ + }/* End same type tests (island/lake & overlap). */ + }/* End deltadir test. */ + else + print2log("\n"); + }/* End distance test. */ + else + print2log("\n"); + } + /* Otherwise, current 2nd too far below 1st, so skip to next */ + /* 1st minutia. */ + else{ + + print2log("\n"); + + /* Break out of inner secondary loop. */ + break; + }/* End delta-y test. */ + + }/* End if !to_remove[s] */ + else + print2log("\n"); + + /* Bump to next second minutia in minutiae list. */ + s++; + }/* End secondary minutiae loop. */ + + }/* Otherwise, first minutia already flagged to be removed. */ + + /* Bump to next first minutia in minutiae list. */ + f++; + }/* End primary minutiae loop. */ + + /* Now remove all minutiae in list that have been flagged for removal. */ + /* NOTE: Need to remove the minutia from their lists in reverse */ + /* order, otherwise, indices will be off. */ + for(i = minutiae->num-1; i >= 0; i--){ + /* If the current minutia index is flagged for removal ... */ + if(to_remove[i]){ + /* Remove the minutia from the minutiae list. */ + if((ret = remove_minutia(i, minutiae))){ + free(to_remove); + return(ret); + } + } + } + + /* Deallocate flag list. */ + free(to_remove); + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: remove_islands_and_lakes - Takes a list of true and false minutiae and +#cat: attempts to detect and remove those false minutiae that +#cat: are either on a common island (filled with black pixels) +#cat: or a lake (filled with white pixels). +#cat: Note that this routine edits the binary image by filling +#cat: detected lakes or islands. + + Input: + minutiae - list of true and false minutiae + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of pruned minutiae + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int remove_islands_and_lakes(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + const LFSPARMS *lfsparms) +{ + int *to_remove; + int i, f, s, ret; + int delta_y, full_ndirs, qtr_ndirs, deltadir, min_deltadir; + int *loop_x, *loop_y, *loop_ex, *loop_ey, nloop; + MINUTIA *minutia1, *minutia2; + double dist; + int dist_thresh, half_loop; + + print2log("\nREMOVING ISLANDS AND LAKES:\n"); + + dist_thresh = lfsparms->max_rmtest_dist; + half_loop = lfsparms->max_half_loop; + + /* Allocate list of minutia indices that upon completion of testing */ + /* should be removed from the minutiae lists. Note: That using */ + /* "calloc" initializes the list to FALSE. */ + to_remove = (int *)calloc(minutiae->num, sizeof(int)); + if(to_remove == (int *)NULL){ + fprintf(stderr, + "ERROR : remove_islands_and_lakes : calloc : to_remove\n"); + return(-610); + } + + /* Compute number directions in full circle. */ + full_ndirs = lfsparms->num_directions<<1; + /* Compute number of directions in 45=(180/4) degrees. */ + qtr_ndirs = lfsparms->num_directions>>2; + + /* Minimum allowable deltadir to consider joining minutia. */ + /* (The closer the deltadir is to 180 degrees, the more likely the join. */ + /* When ndirs==16, then this value is 11=(3*4)-1 == 123.75 degrees. */ + /* I chose to parameterize this threshold based on a fixed fraction of */ + /* 'ndirs' rather than on passing in a parameter in degrees and doing */ + /* the conversion. I doubt the difference matters. */ + min_deltadir = (3 * qtr_ndirs) - 1; + + /* Foreach primary (first) minutia (except for last one in list) ... */ + f = 0; + while(f < minutiae->num-1){ + + /* If current first minutia not previously set to be removed. */ + if(!to_remove[f]){ + + print2log("\n"); + + /* Set first minutia to temporary pointer. */ + minutia1 = minutiae->list[f]; + + /* Foreach secondary minutia to right of first minutia ... */ + s = f+1; + while(s < minutiae->num){ + /* Set second minutia to temporary pointer. */ + minutia2 = minutiae->list[s]; + + /* If the secondary minutia is desired type ... */ + if(minutia2->type == minutia1->type){ + + print2log("1:%d(%d,%d)%d 2:%d(%d,%d)%d ", + f, minutia1->x, minutia1->y, minutia1->type, + s, minutia2->x, minutia2->y, minutia2->type); + + /* The binary image is potentially being edited during */ + /* each iteration of the secondary minutia loop, */ + /* therefore minutia pixel values may be changed. We */ + /* need to catch these events by using the next 2 tests. */ + + /* If the first minutia's pixel has been previously */ + /* changed... */ + if(*(bdata+(minutia1->y*iw)+minutia1->x) != minutia1->type){ + print2log("\n"); + /* Then break out of secondary loop and skip to next */ + /* first. */ + break; + } + + /* If the second minutia's pixel has been previously */ + /* changed... */ + if(*(bdata+(minutia2->y*iw)+minutia2->x) != minutia2->type) + /* Set to remove second minutia. */ + to_remove[s] = TRUE; + + /* If the second minutia not previously set to be removed. */ + if(!to_remove[s]){ + + /* Compute delta y between 1st & 2nd minutiae and test. */ + delta_y = minutia2->y - minutia1->y; + /* If delta y small enough (ex. <16 pixels)... */ + if(delta_y <= dist_thresh){ + + print2log("1DY "); + + /* Compute Euclidean distance between 1st & 2nd */ + /* mintuae. */ + dist = distance(minutia1->x, minutia1->y, + minutia2->x, minutia2->y); + + /* If distance is NOT too large (ex. <16 pixels)... */ + if(dist <= dist_thresh){ + + print2log("2DS "); + + /* Compute "inner" difference between directions */ + /* on a full circle and test. */ + if((deltadir = closest_dir_dist(minutia1->direction, + minutia2->direction, full_ndirs)) == + INVALID_DIR){ + free(to_remove); + fprintf(stderr, + "ERROR : remove_islands_and_lakes : INVALID direction\n"); + return(-611); + } + /* If the difference between dirs is large */ + /* enough ... */ + /* (the more 1st & 2nd point away from each */ + /* other the more likely they should be joined) */ + if(deltadir > min_deltadir){ + + print2log("3DD "); + + /* Pair is the same type, so test to see */ + /* if both are on an island or lake. */ + + /* Check to see if pair on a loop of specified */ + /* half length (ex. 30 pixels) ... */ + ret = on_island_lake(&loop_x, &loop_y, + &loop_ex, &loop_ey, &nloop, + minutia1, minutia2, + half_loop, bdata, iw, ih); + /* If pair is on island/lake ... */ + if(ret == LOOP_FOUND){ + + print2log("4IL RM\n"); + + /* Fill the loop. */ + if((ret = fill_loop(loop_x, loop_y, nloop, + bdata, iw, ih))){ + free_contour(loop_x, loop_y, + loop_ex, loop_ey); + free(to_remove); + return(ret); + } + /* Set to remove first minutia. */ + to_remove[f] = TRUE; + /* Set to remove second minutia. */ + to_remove[s] = TRUE; + /* Deallocate loop contour. */ + free_contour(loop_x,loop_y,loop_ex,loop_ey); + } + /* If island/lake test IGNORED ... */ + else if (ret == IGNORE){ + + print2log("RM\n"); + + /* Set to remove first minutia. */ + to_remove[f] = TRUE; + /* Skip to next 1st minutia by breaking out */ + /* of inner secondary loop. */ + break; + } + /* If ERROR while looking for island/lake ... */ + else if (ret < 0){ + free(to_remove); + return(ret); + } + else + print2log("\n"); + }/* End deltadir test. */ + else + print2log("\n"); + }/* End distance test. */ + else + print2log("\n"); + } + /* Otherwise, current 2nd too far below 1st, so skip to */ + /* next 1st minutia. */ + else{ + + print2log("\n"); + + /* Break out of inner secondary loop. */ + break; + }/* End delta-y test. */ + }/* End if !to_remove[s] */ + else + print2log("\n"); + + }/* End if 2nd not desired type */ + + /* Bump to next second minutia in minutiae list. */ + s++; + }/* End secondary minutiae loop. */ + + }/* Otherwise, first minutia already flagged to be removed. */ + + /* Bump to next first minutia in minutiae list. */ + f++; + }/* End primary minutiae loop. */ + + /* Now remove all minutiae in list that have been flagged for removal. */ + /* NOTE: Need to remove the minutia from their lists in reverse */ + /* order, otherwise, indices will be off. */ + for(i = minutiae->num-1; i >= 0; i--){ + /* If the current minutia index is flagged for removal ... */ + if(to_remove[i]){ + /* Remove the minutia from the minutiae list. */ + if((ret = remove_minutia(i, minutiae))){ + free(to_remove); + return(ret); + } + } + } + + /* Deallocate flag list. */ + free(to_remove); + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: remove_malformations - Attempts to detect and remove minutia points +#cat: that are "irregularly" shaped. Irregularity is measured +#cat: by measuring across the interior of the feature at +#cat: two progressive points down the feature's contour. The +#cat: test is triggered if a pixel of opposite color from the +#cat: feture's type is found. The ratio of the distances across +#cat: the feature at the two points is computed and if the ratio +#cat: is too large then the minutia is determined to be malformed. +#cat: A cursory test is conducted prior to the general tests in +#cat: the event that the minutia lies in a block with LOW RIDGE +#cat: FLOW. In this case, the distance across the feature at +#cat: the second progressive contour point is measured and if +#cat: too large, the point is determined to be malformed. + + Input: + minutiae - list of true and false minutiae + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + low_flow_map - map of image blocks flagged as LOW RIDGE FLOW + mw - width in blocks of the map + mh - height in blocks of the map + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of pruned minutiae + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int remove_malformations(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + int *low_flow_map, const int mw, const int mh, + const LFSPARMS *lfsparms) +{ + int i, j, ret; + MINUTIA *minutia; + int *contour_x, *contour_y, *contour_ex, *contour_ey, ncontour; + int ax1, ay1, bx1, by1; + int ax2, ay2, bx2, by2; + int *x_list, *y_list, num; + double a_dist, b_dist, ratio; + int fmapval, removed; + int blk_x, blk_y; + + print2log("\nREMOVING MALFORMATIONS:\n"); + + for(i = minutiae->num-1; i >= 0; i--){ + minutia = minutiae->list[i]; + ret = trace_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, + lfsparms->malformation_steps_2, + minutia->x, minutia->y, + minutia->x, minutia->y, minutia->ex, minutia->ey, + SCAN_COUNTER_CLOCKWISE, bdata, iw, ih); + + /* If system error occurred during trace ... */ + if(ret < 0){ + /* Return error code. */ + return(ret); + } + + /* If trace was not possible OR loop found OR */ + /* contour is incomplete ... */ + if((ret == IGNORE) || + (ret == LOOP_FOUND) || + (ncontour < lfsparms->malformation_steps_2)){ + /* If contour allocated and returned ... */ + if((ret == LOOP_FOUND) || + (ncontour < lfsparms->malformation_steps_2)) + /* Deallocate the contour. */ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + + print2log("%d,%d RMA\n", minutia->x, minutia->y); + + /* Then remove the minutia. */ + if((ret = remove_minutia(i, minutiae))) + /* If system error, return error code. */ + return(ret); + } + /* Otherwise, traced contour is complete. */ + else{ + /* Store 'A1' contour point. */ + ax1 = contour_x[lfsparms->malformation_steps_1-1]; + ay1 = contour_y[lfsparms->malformation_steps_1-1]; + + /* Store 'B1' contour point. */ + bx1 = contour_x[lfsparms->malformation_steps_2-1]; + by1 = contour_y[lfsparms->malformation_steps_2-1]; + + /* Deallocate the contours. */ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + + ret = trace_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, + lfsparms->malformation_steps_2, + minutia->x, minutia->y, + minutia->x, minutia->y, minutia->ex, minutia->ey, + SCAN_CLOCKWISE, bdata, iw, ih); + + /* If system error occurred during trace ... */ + if(ret < 0){ + /* Return error code. */ + return(ret); + } + + /* If trace was not possible OR loop found OR */ + /* contour is incomplete ... */ + if((ret == IGNORE) || + (ret == LOOP_FOUND) || + (ncontour < lfsparms->malformation_steps_2)){ + /* If contour allocated and returned ... */ + if((ret == LOOP_FOUND) || + (ncontour < lfsparms->malformation_steps_2)) + /* Deallocate the contour. */ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + + print2log("%d,%d RMB\n", minutia->x, minutia->y); + + /* Then remove the minutia. */ + if((ret = remove_minutia(i, minutiae))) + /* If system error, return error code. */ + return(ret); + } + /* Otherwise, traced contour is complete. */ + else{ + /* Store 'A2' contour point. */ + ax2 = contour_x[lfsparms->malformation_steps_1-1]; + ay2 = contour_y[lfsparms->malformation_steps_1-1]; + + /* Store 'B2' contour point. */ + bx2 = contour_x[lfsparms->malformation_steps_2-1]; + by2 = contour_y[lfsparms->malformation_steps_2-1]; + + /* Deallocate the contour. */ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + + /* Compute distances along A & B paths. */ + a_dist = distance(ax1, ay1, ax2, ay2); + b_dist = distance(bx1, by1, bx2, by2); + + /* Compute block coords from minutia's pixel location. */ + blk_x = minutia->x/lfsparms->blocksize; + blk_y = minutia->y/lfsparms->blocksize; + + removed = FALSE; + + /* Check to see if distances are not zero. */ + if((a_dist == 0.0) || (b_dist == 0.0)){ + /* Remove the malformation minutia. */ + print2log("%d,%d RMMAL1\n", minutia->x, minutia->y); + if((ret = remove_minutia(i, minutiae))) + /* If system error, return error code. */ + return(ret); + removed = TRUE; + } + + if(!removed){ + /* Determine if minutia is in LOW RIDGE FLOW block. */ + fmapval = *(low_flow_map+(blk_y*mw)+blk_x); + if(fmapval){ + /* If in LOW RIDGE LFOW, conduct a cursory distance test. */ + /* Need to test this out! */ + if(b_dist > lfsparms->max_malformation_dist){ + /* Remove the malformation minutia. */ + print2log("%d,%d RMMAL2\n", minutia->x, minutia->y); + if((ret = remove_minutia(i, minutiae))) + /* If system error, return error code. */ + return(ret); + removed = TRUE; + } + } + } + + if(!removed){ + /* Compute points on line between the points A & B. */ + if((ret = line_points(&x_list, &y_list, &num, + bx1, by1, bx2, by2))) + return(ret); + /* Foreach remaining point along line segment ... */ + for(j = 0; j < num; j++){ + /* If B path contains pixel opposite minutia type ... */ + if(*(bdata+(y_list[j]*iw)+x_list[j]) != minutia->type){ + /* Compute ratio of A & B path lengths. */ + ratio = b_dist / a_dist; + /* Need to truncate precision so that answers are */ + /* consistent on different computer architectures. */ + ratio = trunc_dbl_precision(ratio, TRUNC_SCALE); + /* If the B path is sufficiently longer than A path ... */ + if(ratio > lfsparms->min_malformation_ratio){ + /* Remove the malformation minutia. */ + /* Then remove the minutia. */ + print2log("%d,%d RMMAL3 (%f)\n", + minutia->x, minutia->y, ratio); + if((ret = remove_minutia(i, minutiae))){ + free(x_list); + free(y_list); + /* If system error, return error code. */ + return(ret); + } + /* Break out of FOR loop. */ + break; + } + } + } + + free(x_list); + free(y_list); + + } + } + } + } + + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: remove_near_invblocks - Removes minutia points from the given list +#cat: that are sufficiently close to a block with invalid +#cat: ridge flow or to the edge of the image. + + Input: + minutiae - list of true and false minutiae + nmap - IMAP ridge flow matrix with invalid, high-curvature, + and no-valid-neighbor regions identified + mw - width in blocks of the NMAP + mh - height in blocks of the NMAP + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of pruned minutiae + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int remove_near_invblock(MINUTIAE *minutiae, int *nmap, + const int mw, const int mh, const LFSPARMS *lfsparms) +{ + int i, ret; + int ni, nbx, nby, nvalid; + int ix, iy, sbi, ebi; + int bx, by, px, py; + int removed; + MINUTIA *minutia; + int lo_margin, hi_margin; + + /* MDG: The next 2 lookup tables are indexed by 'ix' and 'iy'. */ + /* When a feature pixel lies within a 6-pixel margin of a */ + /* block, this routine examines neighboring blocks to */ + /* determine appropriate actions. */ + /* 'ix' may take on values: */ + /* 0 == x-pixel coord in leftmost margin */ + /* 1 == x-pixel coord in middle of block */ + /* 2 == x-pixel coord in rightmost margin */ + /* 'iy' may take on values: */ + /* 0 == y-pixel coord in topmost margin */ + /* 1 == y-pixel coord in middle of block */ + /* 2 == y-pixel coord in bottommost margin */ + /* Given (ix, iy): */ + /* 'startblk[ix][iy]' == starting neighbor index (sbi) */ + /* 'endblk[ix][iy]' == ending neighbor index (ebi) */ + /* so that neighbors begin to be analized from index */ + /* 'sbi' to 'ebi'. */ + /* Ex. (ix, iy) = (2, 0) */ + /* ix==2 ==> x-pixel coord in rightmost margin */ + /* iy==0 ==> y-pixel coord in topmost margin */ + /* X - marks the region in the current block */ + /* corresponding to (ix=2, iy=0). */ + /* sbi = 0 = startblk[2][0] */ + /* ebi = 2 = endblk[2][0] */ + /* so neighbors are analized on index range [0..2] */ + /* | */ + /* nbr block 0 | nbr block 1 */ + /* --------------------------+------------ */ + /* top margin | X | */ + /* _._._._._._._._._._._._._.| */ + /* | | */ + /* current block .r m| nbr block 2 */ + /* |i a| */ + /* .g g| */ + /* |h i| */ + /* .t n| */ + /* | | */ + + /* MDG: LUT for starting neighbor index given (ix, iy). */ + static int startblk[9] = { 6, 0, 0, + 6,-1, 2, + 4, 4, 2 }; + /* MDG: LUT for ending neighbor index given (ix, iy). */ + static int endblk[9] = { 8, 0, 2, + 6,-1, 2, + 6, 4, 4 }; + + /* MDG: Pixel coord offsets specifying the order in which neighboring */ + /* blocks are searched. The current block is in the middle of */ + /* 8 surrounding neighbors. The following illustrates the order */ + /* of neighbor indices. (Note that 9 overlaps 1.) */ + /* 8 */ + /* 7 0 1 */ + /* 6 C 2 */ + /* 5 4 3 */ + /* */ + /* 0 1 2 3 4 5 6 7 8 */ + static int blkdx[9] = { 0, 1, 1, 1, 0,-1,-1,-1, 0 }; /* Delta-X */ + static int blkdy[9] = { -1,-1, 0, 1, 1, 1, 0,-1,-1 }; /* Delta-Y */ + + print2log("\nREMOVING MINUTIA NEAR INVALID BLOCKS:\n"); + + /* If the margin covers more than the entire block ... */ + if(lfsparms->inv_block_margin > (lfsparms->blocksize>>1)){ + /* Then treat this as an error. */ + fprintf(stderr, + "ERROR : remove_near_invblock : margin too large for blocksize\n"); + return(-270); + } + + /* Compute the low and high pixel margin boundaries (ex. 6 pixels wide) */ + /* in the block. */ + lo_margin = lfsparms->inv_block_margin; + hi_margin = lfsparms->blocksize - lfsparms->inv_block_margin - 1; + + i = 0; + /* Foreach minutia remaining in the list ... */ + while(i < minutiae->num){ + /* Assign temporary minutia pointer. */ + minutia = minutiae->list[i]; + + /* Compute NMAP block coords from minutia's pixel location. */ + bx = minutia->x/lfsparms->blocksize; + by = minutia->y/lfsparms->blocksize; + + /* Compute pixel offset into the NMAP block corresponding to the */ + /* minutia's pixel location. */ + /* NOTE: The margins used here will necessarily correspond to the */ + /* actual block, boundaries used to compute the NMAP values. */ + /* This will be true when the image width and/or height is not an */ + /* even multiple of 'blocksize' and we are processing minutia */ + /* located in the right-most column (or bottom-most row) of */ + /* blocks. I don't think this will pose a problem in practice. */ + px = minutia->x % lfsparms->blocksize; + py = minutia->y % lfsparms->blocksize; + + /* Determine if x pixel offset into the block is in the margins. */ + /* If x pixel offset is in left margin ... */ + if(px < lo_margin) + ix = 0; + /* If x pixel offset is in right margin ... */ + else if(px > hi_margin) + ix = 2; + /* Otherwise, x pixel offset is in middle of block. */ + else + ix = 1; + + /* Determine if y pixel offset into the block is in the margins. */ + /* If y pixel offset is in top margin ... */ + if(py < lo_margin) + iy = 0; + /* If y pixel offset is in bottom margin ... */ + else if(py > hi_margin) + iy = 2; + /* Otherwise, y pixel offset is in middle of block. */ + else + iy = 1; + + /* Set remove flag to FALSE. */ + removed = FALSE; + + /* If one of the minutia's pixel offsets is in a margin ... */ + if((ix != 1) || (iy != 1)){ + + /* Compute the starting neighbor block index for processing. */ + sbi = *(startblk+(iy*3)+ix); + /* Compute the ending neighbor block index for processing. */ + ebi = *(endblk+(iy*3)+ix); + + /* Foreach neighbor in the range to be processed ... */ + for(ni = sbi; ni <= ebi; ni++){ + /* Compute the neighbor's NMAP block coords relative to */ + /* the block the current minutia is in. */ + nbx = bx + blkdx[ni]; + nby = by + blkdy[ni]; + + /* If neighbor's block coords are outside of NMAP boundaries... */ + if((nbx < 0) || (nbx >= mw) || + (nby < 0) || (nby >= mh)){ + + print2log("%d,%d RM1\n", minutia->x, minutia->y); + + /* Then the minutia is in a margin adjacent to the edge of */ + /* the image. */ + /* NOTE: This is true when the image width and/or height */ + /* is an even multiple of blocksize. When the image is not*/ + /* an even multiple, then some minutia may not be detected */ + /* as being in the margin of "the image" (not the block). */ + /* In practice, I don't think this will impact performance.*/ + if((ret = remove_minutia(i, minutiae))) + /* If system error occurred while removing minutia, */ + /* then return error code. */ + return(ret); + /* Set remove flag to TURE. */ + removed = TRUE; + /* Break out of neighboring block loop. */ + break; + } + /* If the neighboring NMAP block is INVALID ... */ + else if (*(nmap+(nby*mw)+nbx) == INVALID_DIR){ + /* Count the number of valid blocks neighboring */ + /* the current neighbor. */ + nvalid = num_valid_8nbrs(nmap, nbx, nby, mw, mh); + /* If the number of valid neighbors is < threshold */ + /* (ex. 7)... */ + if(nvalid < lfsparms->rm_valid_nbr_min){ + + print2log("%d,%d RM2\n", minutia->x, minutia->y); + + /* Then remove the current minutia from the list. */ + if((ret = remove_minutia(i, minutiae))) + /* If system error occurred while removing minutia, */ + /* then return error code. */ + return(ret); + /* Set remove flag to TURE. */ + removed = TRUE; + /* Break out of neighboring block loop. */ + break; + } + /* Otherwise enough valid neighbors, so don't remove minutia */ + /* based on this neighboring block. */ + } + /* Otherwise neighboring block is VALID, HIGH_CURVATURE, or */ + /* NO_VALID_NBRS, so don't remove minutia based on this */ + /* neighboring block. */ + } + + } /* Otherwise not in margin, so skip to next minutia in list. */ + + /* If current minutia not removed ... */ + if(!removed) + /* Advance to the next minutia in the list. */ + i++; + /* Otherwise the next minutia has slid into the spot where current */ + /* minutia was removed, so don't bump minutia index. */ + } /* End minutia loop */ + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: remove_near_invblocks_V2 - Removes minutia points from the given list +#cat: that are sufficiently close to a block with invalid +#cat: ridge flow or to the edge of the image. + + Input: + minutiae - list of true and false minutiae + direction_map - map of image blocks containing direction ridge flow + mw - width in blocks of the map + mh - height in blocks of the map + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of pruned minutiae + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int remove_near_invblock_V2(MINUTIAE *minutiae, int *direction_map, + const int mw, const int mh, const LFSPARMS *lfsparms) +{ + int i, ret; + int ni, nbx, nby, nvalid; + int ix, iy, sbi, ebi; + int bx, by, px, py; + int removed; + MINUTIA *minutia; + int lo_margin, hi_margin; + + /* The next 2 lookup tables are indexed by 'ix' and 'iy'. */ + /* When a feature pixel lies within a 6-pixel margin of a */ + /* block, this routine examines neighboring blocks to */ + /* determine appropriate actions. */ + /* 'ix' may take on values: */ + /* 0 == x-pixel coord in leftmost margin */ + /* 1 == x-pixel coord in middle of block */ + /* 2 == x-pixel coord in rightmost margin */ + /* 'iy' may take on values: */ + /* 0 == y-pixel coord in topmost margin */ + /* 1 == y-pixel coord in middle of block */ + /* 2 == y-pixel coord in bottommost margin */ + /* Given (ix, iy): */ + /* 'startblk[ix][iy]' == starting neighbor index (sbi) */ + /* 'endblk[ix][iy]' == ending neighbor index (ebi) */ + /* so that neighbors begin to be analized from index */ + /* 'sbi' to 'ebi'. */ + /* Ex. (ix, iy) = (2, 0) */ + /* ix==2 ==> x-pixel coord in rightmost margin */ + /* iy==0 ==> y-pixel coord in topmost margin */ + /* X - marks the region in the current block */ + /* corresponding to (ix=2, iy=0). */ + /* sbi = 0 = startblk[2][0] */ + /* ebi = 2 = endblk[2][0] */ + /* so neighbors are analized on index range [0..2] */ + /* | */ + /* nbr block 0 | nbr block 1 */ + /* --------------------------+------------ */ + /* top margin | X | */ + /* _._._._._._._._._._._._._.| */ + /* | | */ + /* current block .r m| nbr block 2 */ + /* |i a| */ + /* .g g| */ + /* |h i| */ + /* .t n| */ + /* | | */ + + /* LUT for starting neighbor index given (ix, iy). */ + static int startblk[9] = { 6, 0, 0, + 6,-1, 2, + 4, 4, 2 }; + /* LUT for ending neighbor index given (ix, iy). */ + static int endblk[9] = { 8, 0, 2, + 6,-1, 2, + 6, 4, 4 }; + + /* Pixel coord offsets specifying the order in which neighboring */ + /* blocks are searched. The current block is in the middle of */ + /* 8 surrounding neighbors. The following illustrates the order */ + /* of neighbor indices. (Note that 9 overlaps 1.) */ + /* 8 */ + /* 7 0 1 */ + /* 6 C 2 */ + /* 5 4 3 */ + /* */ + /* 0 1 2 3 4 5 6 7 8 */ + static int blkdx[9] = { 0, 1, 1, 1, 0,-1,-1,-1, 0 }; /* Delta-X */ + static int blkdy[9] = { -1,-1, 0, 1, 1, 1, 0,-1,-1 }; /* Delta-Y */ + + print2log("\nREMOVING MINUTIA NEAR INVALID BLOCKS:\n"); + + /* If the margin covers more than the entire block ... */ + if(lfsparms->inv_block_margin > (lfsparms->blocksize>>1)){ + /* Then treat this as an error. */ + fprintf(stderr, + "ERROR : remove_near_invblock_V2 : margin too large for blocksize\n"); + return(-620); + } + + /* Compute the low and high pixel margin boundaries (ex. 6 pixels wide) */ + /* in the block. */ + lo_margin = lfsparms->inv_block_margin; + hi_margin = lfsparms->blocksize - lfsparms->inv_block_margin - 1; + + i = 0; + /* Foreach minutia remaining in the list ... */ + while(i < minutiae->num){ + /* Assign temporary minutia pointer. */ + minutia = minutiae->list[i]; + + /* Compute block coords from minutia's pixel location. */ + bx = minutia->x/lfsparms->blocksize; + by = minutia->y/lfsparms->blocksize; + + /* Compute pixel offset into the image block corresponding to the */ + /* minutia's pixel location. */ + /* NOTE: The margins used here will not necessarily correspond to */ + /* the actual block boundaries used to compute the map values. */ + /* This will be true when the image width and/or height is not an */ + /* even multiple of 'blocksize' and we are processing minutia */ + /* located in the right-most column (or bottom-most row) of */ + /* blocks. I don't think this will pose a problem in practice. */ + px = minutia->x % lfsparms->blocksize; + py = minutia->y % lfsparms->blocksize; + + /* Determine if x pixel offset into the block is in the margins. */ + /* If x pixel offset is in left margin ... */ + if(px < lo_margin) + ix = 0; + /* If x pixel offset is in right margin ... */ + else if(px > hi_margin) + ix = 2; + /* Otherwise, x pixel offset is in middle of block. */ + else + ix = 1; + + /* Determine if y pixel offset into the block is in the margins. */ + /* If y pixel offset is in top margin ... */ + if(py < lo_margin) + iy = 0; + /* If y pixel offset is in bottom margin ... */ + else if(py > hi_margin) + iy = 2; + /* Otherwise, y pixel offset is in middle of block. */ + else + iy = 1; + + /* Set remove flag to FALSE. */ + removed = FALSE; + + /* If one of the minutia's pixel offsets is in a margin ... */ + if((ix != 1) || (iy != 1)){ + + /* Compute the starting neighbor block index for processing. */ + sbi = *(startblk+(iy*3)+ix); + /* Compute the ending neighbor block index for processing. */ + ebi = *(endblk+(iy*3)+ix); + + /* Foreach neighbor in the range to be processed ... */ + for(ni = sbi; ni <= ebi; ni++){ + /* Compute the neighbor's block coords relative to */ + /* the block the current minutia is in. */ + nbx = bx + blkdx[ni]; + nby = by + blkdy[ni]; + + /* If neighbor's block coords are outside of map boundaries... */ + if((nbx < 0) || (nbx >= mw) || + (nby < 0) || (nby >= mh)){ + + print2log("%d,%d RM1\n", minutia->x, minutia->y); + + /* Then the minutia is in a margin adjacent to the edge of */ + /* the image. */ + /* NOTE: This is true when the image width and/or height */ + /* is an even multiple of blocksize. When the image is not*/ + /* an even multiple, then some minutia may not be detected */ + /* as being in the margin of "the image" (not the block). */ + /* In practice, I don't think this will impact performance.*/ + if((ret = remove_minutia(i, minutiae))) + /* If system error occurred while removing minutia, */ + /* then return error code. */ + return(ret); + /* Set remove flag to TURE. */ + removed = TRUE; + /* Break out of neighboring block loop. */ + break; + } + /* If the neighboring block has INVALID direction ... */ + else if (*(direction_map+(nby*mw)+nbx) == INVALID_DIR){ + /* Count the number of valid blocks neighboring */ + /* the current neighbor. */ + nvalid = num_valid_8nbrs(direction_map, nbx, nby, mw, mh); + /* If the number of valid neighbors is < threshold */ + /* (ex. 7)... */ + if(nvalid < lfsparms->rm_valid_nbr_min){ + + print2log("%d,%d RM2\n", minutia->x, minutia->y); + + /* Then remove the current minutia from the list. */ + if((ret = remove_minutia(i, minutiae))) + /* If system error occurred while removing minutia, */ + /* then return error code. */ + return(ret); + /* Set remove flag to TURE. */ + removed = TRUE; + /* Break out of neighboring block loop. */ + break; + } + /* Otherwise enough valid neighbors, so don't remove minutia */ + /* based on this neighboring block. */ + } + /* Otherwise neighboring block has valid direction, */ + /* so don't remove minutia based on this neighboring block. */ + } + + } /* Otherwise not in margin, so skip to next minutia in list. */ + + /* If current minutia not removed ... */ + if(!removed) + /* Advance to the next minutia in the list. */ + i++; + /* Otherwise the next minutia has slid into the spot where current */ + /* minutia was removed, so don't bump minutia index. */ + } /* End minutia loop */ + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: remove_pointing_invblock - Removes minutia points that are relatively +#cat: close in the direction opposite the minutia to an NMAP +#cat: block with invalid ridge flow. + + Input: + minutiae - list of true and false minutiae + nmap - IMAP ridge flow matrix with invalid, high-curvature, + and no-valid-neighbor regions identified + mw - width in blocks of the NMAP + mh - height in blocks of the NMAP + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of pruned minutiae + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int remove_pointing_invblock(MINUTIAE *minutiae, + int *nmap, const int mw, const int mh, + const LFSPARMS *lfsparms) +{ + int i, ret; + int delta_x, delta_y, nmapval; + int nx, ny, bx, by; + MINUTIA *minutia; + double pi_factor, theta; + double dx, dy; + + print2log("\nREMOVING MINUTIA POINTING TO INVALID BLOCKS:\n"); + + /* Compute factor for converting integer directions to radians. */ + pi_factor = M_PI / (double)lfsparms->num_directions; + + i = 0; + /* Foreach minutia remaining in list ... */ + while(i < minutiae->num){ + /* Set temporary minutia pointer. */ + minutia = minutiae->list[i]; + /* Convert minutia's direction to radians. */ + theta = minutia->direction * pi_factor; + /* Compute translation offsets (ex. 6 pixels). */ + dx = sin(theta) * (double)lfsparms->trans_dir_pix; + dy = cos(theta) * (double)lfsparms->trans_dir_pix; + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + dx = trunc_dbl_precision(dx, TRUNC_SCALE); + dy = trunc_dbl_precision(dy, TRUNC_SCALE); + delta_x = sround(dx); + delta_y = sround(dy); + /* Translate the minutia's coords. */ + nx = minutia->x - delta_x; + ny = minutia->y + delta_y; + /* Convert pixel coords to NMAP block coords. */ + bx = (int)(nx / lfsparms->blocksize); + by = (int)(ny / lfsparms->blocksize); + /* The translation could move the point out of image boundaries, */ + /* and therefore the corresponding block coords can be out of */ + /* IMAP boundaries, so limit the block coords to within boundaries. */ + bx = max(0, bx); + bx = min(mw-1, bx); + by = max(0, by); + by = min(mh-1, by); + + /* Get corresponding block's NMAP value. */ + /* -3 == NO_VALID_NBRS */ + /* -2 == HIGH_CURVATURE */ + /* -1 == INVALID_DIR */ + /* 0 <= VALID_DIR */ + nmapval = *(nmap+(by*mw)+bx); + + /* If the NMAP value of translated minutia point is INVALID ... */ + if(nmapval == INVALID_DIR){ + + print2log("%d,%d RM\n", minutia->x, minutia->y); + + /* Remove the minutia from the minutiae list. */ + if((ret = remove_minutia(i, minutiae))){ + return(ret); + } + /* No need to advance because next minutia has slid into slot. */ + } + else{ + /* Advance to next minutia in list. */ + i++; + } + } + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: remove_pointing_invblock_V2 - Removes minutia points that are relatively +#cat: close in the direction opposite the minutia to a +#cat: block with INVALID ridge flow. + + Input: + minutiae - list of true and false minutiae + direction_map - map of image blocks containing directional ridge flow + mw - width in blocks of the map + mh - height in blocks of the map + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of pruned minutiae + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int remove_pointing_invblock_V2(MINUTIAE *minutiae, + int *direction_map, const int mw, const int mh, + const LFSPARMS *lfsparms) +{ + int i, ret; + int delta_x, delta_y, dmapval; + int nx, ny, bx, by; + MINUTIA *minutia; + double pi_factor, theta; + double dx, dy; + + print2log("\nREMOVING MINUTIA POINTING TO INVALID BLOCKS:\n"); + + /* Compute factor for converting integer directions to radians. */ + pi_factor = M_PI / (double)lfsparms->num_directions; + + i = 0; + /* Foreach minutia remaining in list ... */ + while(i < minutiae->num){ + /* Set temporary minutia pointer. */ + minutia = minutiae->list[i]; + /* Convert minutia's direction to radians. */ + theta = minutia->direction * pi_factor; + /* Compute translation offsets (ex. 6 pixels). */ + dx = sin(theta) * (double)(lfsparms->trans_dir_pix); + dy = cos(theta) * (double)(lfsparms->trans_dir_pix); + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + dx = trunc_dbl_precision(dx, TRUNC_SCALE); + dy = trunc_dbl_precision(dy, TRUNC_SCALE); + delta_x = sround(dx); + delta_y = sround(dy); + /* Translate the minutia's coords. */ + nx = minutia->x - delta_x; + ny = minutia->y + delta_y; + /* Convert pixel coords to block coords. */ + bx = (int)(nx / lfsparms->blocksize); + by = (int)(ny / lfsparms->blocksize); + /* The translation could move the point out of image boundaries, */ + /* and therefore the corresponding block coords can be out of */ + /* map boundaries, so limit the block coords to within boundaries. */ + bx = max(0, bx); + bx = min(mw-1, bx); + by = max(0, by); + by = min(mh-1, by); + + /* Get corresponding block's ridge flow direction. */ + dmapval = *(direction_map+(by*mw)+bx); + + /* If the block's direction is INVALID ... */ + if(dmapval == INVALID_DIR){ + + print2log("%d,%d RM\n", minutia->x, minutia->y); + + /* Remove the minutia from the minutiae list. */ + if((ret = remove_minutia(i, minutiae))){ + return(ret); + } + /* No need to advance because next minutia has slid into slot. */ + } + else{ + /* Advance to next minutia in list. */ + i++; + } + } + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: remove_overlaps - Takes a list of true and false minutiae and +#cat: attempts to detect and remove those false minutiae that +#cat: are on opposite sides of an overlap. Note that this +#cat: routine does NOT edit the binary image when overlaps +#cat: are removed. + + Input: + minutiae - list of true and false minutiae + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of pruned minutiae + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int remove_overlaps(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + const LFSPARMS *lfsparms) +{ + int *to_remove; + int i, f, s, ret; + int delta_y, full_ndirs, qtr_ndirs, deltadir, min_deltadir; + MINUTIA *minutia1, *minutia2; + double dist; + int joindir, opp1dir, half_ndirs; + + print2log("\nREMOVING OVERLAPS:\n"); + + /* Allocate list of minutia indices that upon completion of testing */ + /* should be removed from the minutiae lists. Note: That using */ + /* "calloc" initializes the list to FALSE. */ + to_remove = (int *)calloc(minutiae->num, sizeof(int)); + if(to_remove == (int *)NULL){ + fprintf(stderr, "ERROR : remove_overlaps : calloc : to_remove\n"); + return(-650); + } + + /* Compute number directions in full circle. */ + full_ndirs = lfsparms->num_directions<<1; + /* Compute number of directions in 45=(180/4) degrees. */ + qtr_ndirs = lfsparms->num_directions>>2; + /* Compute number of directions in 90=(180/2) degrees. */ + half_ndirs = lfsparms->num_directions>>1; + + /* Minimum allowable deltadir to consider joining minutia. */ + /* (The closer the deltadir is to 180 degrees, the more likely the join. */ + /* When ndirs==16, then this value is 11=(3*4)-1 == 123.75 degrees. */ + /* I chose to parameterize this threshold based on a fixed fraction of */ + /* 'ndirs' rather than on passing in a parameter in degrees and doing */ + /* the conversion. I doubt the difference matters. */ + min_deltadir = (3 * qtr_ndirs) - 1; + + f = 0; + /* Foreach primary (first) minutia (except for last one in list) ... */ + while(f < minutiae->num-1){ + + /* If current first minutia not previously set to be removed. */ + if(!to_remove[f]){ + + print2log("\n"); + + /* Set first minutia to temporary pointer. */ + minutia1 = minutiae->list[f]; + /* Foreach secondary (second) minutia to right of first minutia ... */ + s = f+1; + while(s < minutiae->num){ + /* Set second minutia to temporary pointer. */ + minutia2 = minutiae->list[s]; + + print2log("1:%d(%d,%d)%d 2:%d(%d,%d)%d ", + f, minutia1->x, minutia1->y, minutia1->type, + s, minutia2->x, minutia2->y, minutia2->type); + + /* The binary image is potentially being edited during each */ + /* iteration of the secondary minutia loop, therefore */ + /* minutia pixel values may be changed. We need to catch */ + /* these events by using the next 2 tests. */ + + /* If the first minutia's pixel has been previously changed... */ + if(*(bdata+(minutia1->y*iw)+minutia1->x) != minutia1->type){ + print2log("\n"); + /* Then break out of secondary loop and skip to next first. */ + break; + } + + /* If the second minutia's pixel has been previously changed... */ + if(*(bdata+(minutia2->y*iw)+minutia2->x) != minutia2->type) + /* Set to remove second minutia. */ + to_remove[s] = TRUE; + + /* If the second minutia not previously set to be removed. */ + if(!to_remove[s]){ + + /* Compute delta y between 1st & 2nd minutiae and test. */ + delta_y = minutia2->y - minutia1->y; + /* If delta y small enough (ex. < 8 pixels) ... */ + if(delta_y <= lfsparms->max_overlap_dist){ + + print2log("1DY "); + + /* Compute Euclidean distance between 1st & 2nd mintuae. */ + dist = distance(minutia1->x, minutia1->y, + minutia2->x, minutia2->y); + /* If distance is NOT too large (ex. < 8 pixels) ... */ + if(dist <= lfsparms->max_overlap_dist){ + + print2log("2DS "); + + /* Compute "inner" difference between directions on */ + /* a full circle and test. */ + if((deltadir = closest_dir_dist(minutia1->direction, + minutia2->direction, full_ndirs)) == + INVALID_DIR){ + free(to_remove); + fprintf(stderr, + "ERROR : remove_overlaps : INVALID direction\n"); + return(-651); + } + /* If the difference between dirs is large enough ... */ + /* (the more 1st & 2nd point away from each other the */ + /* more likely they should be joined) */ + if(deltadir > min_deltadir){ + + print2log("3DD "); + + /* If 1st & 2nd minutiae are same type ... */ + if(minutia1->type == minutia2->type){ + /* Test to see if both are on opposite sides */ + /* of an overlap. */ + + /* Compute direction of "joining" vector. */ + /* First, compute direction of line from first */ + /* to second minutia points. */ + joindir = line2direction(minutia1->x, minutia1->y, + minutia2->x, minutia2->y, + lfsparms->num_directions); + + /* Comptue opposite direction of first minutia. */ + opp1dir = (minutia1->direction+ + lfsparms->num_directions)%full_ndirs; + /* Take "inner" distance on full circle between */ + /* the first minutia's opposite direction and */ + /* the joining direction. */ + joindir = abs(opp1dir - joindir); + joindir = min(joindir, full_ndirs - joindir); + + print2log("joindir=%d dist=%f ", joindir,dist); + + /* If the joining angle is <= 90 degrees OR */ + /* the 2 points are sufficiently close AND */ + /* a free path exists between pair ... */ + if(((joindir <= half_ndirs) || + (dist <= lfsparms->max_overlap_join_dist)) && + free_path(minutia1->x, minutia1->y, + minutia2->x, minutia2->y, + bdata, iw, ih, lfsparms)){ + + print2log("4OV RM\n"); + + /* Then assume overlap, so ... */ + /* Set to remove first minutia. */ + to_remove[f] = TRUE; + /* Set to remove second minutia. */ + to_remove[s] = TRUE; + } + /* Otherwise, pair not on an overlap, so skip */ + /* to next second minutia. */ + else + print2log("\n"); + } + else + print2log("\n"); + /* End same type test. */ + }/* End deltadir test. */ + else + print2log("\n"); + }/* End distance test. */ + else + print2log("\n"); + } + /* Otherwise, current 2nd too far below 1st, so skip to next */ + /* 1st minutia. */ + else{ + + print2log("\n"); + + /* Break out of inner secondary loop. */ + break; + }/* End delta-y test. */ + + }/* End if !to_remove[s] */ + else + print2log("\n"); + + /* Bump to next second minutia in minutiae list. */ + s++; + }/* End secondary minutiae loop. */ + + }/* Otherwise, first minutia already flagged to be removed. */ + + /* Bump to next first minutia in minutiae list. */ + f++; + }/* End primary minutiae loop. */ + + /* Now remove all minutiae in list that have been flagged for removal. */ + /* NOTE: Need to remove the minutia from their lists in reverse */ + /* order, otherwise, indices will be off. */ + for(i = minutiae->num-1; i >= 0; i--){ + /* If the current minutia index is flagged for removal ... */ + if(to_remove[i]){ + /* Remove the minutia from the minutiae list. */ + if((ret = remove_minutia(i, minutiae))){ + free(to_remove); + return(ret); + } + } + } + + /* Deallocate flag list. */ + free(to_remove); + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: remove_pores - Attempts to detect and remove minutia points located on +#cat: pore-shaped valleys. + + Input: + minutiae - list of true and false minutiae + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + nmap - IMAP ridge flow matrix with invalid, high-curvature, + and no-valid-neighbor regions identified + mw - width in blocks of the NMAP + mh - height in blocks of the NMAP + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of pruned minutiae + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int remove_pores(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + int *nmap, const int mw, const int mh, + const LFSPARMS *lfsparms) +{ + int i, ret; + int removed, blk_x, blk_y; + int rx, ry; + int px, py, pex, pey, bx, by, dx, dy; + int qx, qy, qex, qey, ax, ay, cx, cy; + MINUTIA *minutia; + double pi_factor, theta, sin_theta, cos_theta; + double ab2, cd2, ratio; + int *contour_x, *contour_y, *contour_ex, *contour_ey, ncontour; + double drx, dry; + + /* MDG: This routine attempts to locate the following points on all */ + /* bifurcations within the feature list. */ + /* 1. Compute R 3 pixels opposite the feature direction from */ + /* feature point F. */ + /* 2. Find white pixel transitions P & Q within 12 steps from */ + /* from R perpendicular to the feature's direction. */ + /* 3. Find points B & D by walking white edge from P. */ + /* 4. Find points A & C by walking white edge from Q. */ + /* 5. Measure squared distances between A-B and C-D. */ + /* 6. Compute ratio of squared distances and compare against */ + /* threshold (2.25). If A-B sufficiently larger than C-D, */ + /* then assume NOT pore, otherwise flag the feature point F.*/ + /* If along the way, finding any of these points fails, then */ + /* assume the feature is a pore and flag it. */ + /* */ + /* A */ + /* _____._ */ + /* ----___ Q C */ + /* ------____ ---_.________.___ */ + /* ---_ */ + /* (valley) F.\ .R (ridge) */ + /* ____/ */ + /* ______---- ___-.--------.--- */ + /* ____--- P D */ + /* -----.- */ + /* B */ + /* */ + /* AB^2/CD^2 <= 2.25 then flag feature */ + /* */ + + + print2log("\nREMOVING PORES:\n"); + + /* Factor for converting integer directions into radians. */ + pi_factor = M_PI/(double)lfsparms->num_directions; + + /* Initialize to the beginning of the minutia list. */ + i = 0; + /* Foreach minutia remaining in the list ... */ + while(i < minutiae->num){ + /* Set temporary minutia pointer. */ + minutia = minutiae->list[i]; + + /* Initialize remove flag to FALSE. */ + removed = FALSE; + + /* If minutia is a bifurcation ... */ + if(minutia->type == BIFURCATION){ + /* Compute NMAP block coords from minutia point. */ + blk_x = minutia->x / lfsparms->blocksize; + blk_y = minutia->y / lfsparms->blocksize; + /* If NMAP block has a VALID direction... */ + if(*(nmap+(blk_y*mw)+blk_x) >= 0){ + /* Compute radian angle from minutia direction. */ + theta = (double)minutia->direction * pi_factor; + /* Compute sine and cosine factors of this angle. */ + sin_theta = sin(theta); + cos_theta = cos(theta); + /* Translate the minutia point (ex. 3 pixels) in opposite */ + /* direction minutia is pointing. Call this point 'R'. */ + drx = (double)minutia->x - + (sin_theta * (double)lfsparms->pores_trans_r); + dry = (double)minutia->y + + (cos_theta * (double)lfsparms->pores_trans_r); + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + drx = trunc_dbl_precision(drx, TRUNC_SCALE); + dry = trunc_dbl_precision(dry, TRUNC_SCALE); + rx = sround(drx); + ry = sround(dry); + + /* If 'R' is on a black pixel ... */ + if(*(bdata+(ry*iw)+rx) == 1){ + + /* Search a specified number of steps (ex. 12) from 'R' in a */ + /* perpendicular direction from the minutia direction until */ + /* the first white pixel is found. If a white pixel is */ + /* found within the specified number of steps, then call */ + /* this point 'P' (storing the point's edge pixel as well). */ + if(search_in_direction(&px, &py, &pex, &pey, + 0, rx, ry, -cos_theta, -sin_theta, + lfsparms->pores_perp_steps, + bdata, iw, ih)){ + /* Trace contour from P's edge pixel in counter-clockwise */ + /* scan and step along specified number of steps (ex. 10). */ + ret = trace_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, + lfsparms->pores_steps_fwd, + px, py, px, py, pex, pey, + SCAN_COUNTER_CLOCKWISE, bdata, iw, ih); + + /* If system error occurred during trace ... */ + if(ret < 0){ + /* Return error code. */ + return(ret); + } + + /* If trace was not possible OR loop found OR */ + /* contour is incomplete ... */ + if((ret == IGNORE) || + (ret == LOOP_FOUND) || + (ncontour < lfsparms->pores_steps_fwd)){ + /* If contour allocated and returned ... */ + if((ret == LOOP_FOUND) || + (ncontour < lfsparms->pores_steps_fwd)) + /* Deallocate the contour. */ + free_contour(contour_x, contour_y, + contour_ex, contour_ey); + + + print2log("%d,%d RMB\n", minutia->x, minutia->y); + + /* Then remove the minutia. */ + if((ret = remove_minutia(i, minutiae))) + /* If system error, return error code. */ + return(ret); + /* Set remove flag to TRUE. */ + removed = TRUE; + } + /* Otherwise, traced contour is complete. */ + else{ + /* Store last point in contour as point 'B'. */ + bx = contour_x[ncontour-1]; + by = contour_y[ncontour-1]; + /* Deallocate the contour. */ + free_contour(contour_x, contour_y, + contour_ex, contour_ey); + + /* Trace contour from P's edge pixel in clockwise scan */ + /* and step along specified number of steps (ex. 8). */ + ret = trace_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, + lfsparms->pores_steps_bwd, + px, py, px, py, pex, pey, + SCAN_CLOCKWISE, bdata, iw, ih); + + /* If system error occurred during trace ... */ + if(ret < 0){ + /* Return error code. */ + return(ret); + } + + /* If trace was not possible OR loop found OR */ + /* contour is incomplete ... */ + if((ret == IGNORE) || + (ret == LOOP_FOUND) || + (ncontour < lfsparms->pores_steps_bwd)){ + /* If contour allocated and returned ... */ + if((ret == LOOP_FOUND) || + (ncontour < lfsparms->pores_steps_bwd)) + /* Deallocate the contour. */ + free_contour(contour_x, contour_y, + contour_ex, contour_ey); + + print2log("%d,%d RMD\n", minutia->x, minutia->y); + + /* Then remove the minutia. */ + if((ret = remove_minutia(i, minutiae))) + /* If system error, return error code. */ + return(ret); + /* Set remove flag to TRUE. */ + removed = TRUE; + } + /* Otherwise, traced contour is complete. */ + else{ + /* Store last point in contour as point 'D'. */ + dx = contour_x[ncontour-1]; + dy = contour_y[ncontour-1]; + /* Deallocate the contour. */ + free_contour(contour_x, contour_y, + contour_ex, contour_ey); + /* Search a specified number of steps (ex. 12) from */ + /* 'R' in opposite direction of that used to find */ + /* 'P' until the first white pixel is found. If a */ + /* white pixel is found within the specified number */ + /* of steps, then call this point 'Q' (storing the */ + /* point's edge pixel as well). */ + if(search_in_direction(&qx, &qy, &qex, &qey, + 0, rx, ry, cos_theta, sin_theta, + lfsparms->pores_perp_steps, + bdata, iw, ih)){ + /* Trace contour from Q's edge pixel in clockwise */ + /* scan and step along specified number of steps */ + /* (ex. 10). */ + ret = trace_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, + lfsparms->pores_steps_fwd, + qx, qy, qx, qy, qex, qey, + SCAN_CLOCKWISE, bdata, iw, ih); + + /* If system error occurred during trace ... */ + if(ret < 0){ + /* Return error code. */ + return(ret); + } + + /* If trace was not possible OR loop found OR */ + /* contour is incomplete ... */ + if((ret == IGNORE) || + (ret == LOOP_FOUND) || + (ncontour < lfsparms->pores_steps_fwd)){ + /* If contour allocated and returned ... */ + if((ret == LOOP_FOUND) || + (ncontour < lfsparms->pores_steps_fwd)) + /* Deallocate the contour. */ + free_contour(contour_x, contour_y, + contour_ex, contour_ey); + + print2log("%d,%d RMA\n", minutia->x, minutia->y); + + /* Then remove the minutia. */ + if((ret = remove_minutia(i, minutiae))) + /* If system error, return error code. */ + return(ret); + /* Set remove flag to TRUE. */ + removed = TRUE; + } + /* Otherwise, traced contour is complete. */ + else{ + /* Store last point in contour as point 'A'. */ + ax = contour_x[ncontour-1]; + ay = contour_y[ncontour-1]; + /* Deallocate the contour. */ + free_contour(contour_x, contour_y, + contour_ex, contour_ey); + + /* Trace contour from Q's edge pixel in */ + /* counter-clockwise scan and step along a */ + /* specified number of steps (ex. 8). */ + ret = trace_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, + lfsparms->pores_steps_bwd, + qx, qy, qx, qy, qex, qey, + SCAN_COUNTER_CLOCKWISE, bdata, iw, ih); + + /* If system error occurred during scan ... */ + if(ret < 0){ + /* Return error code. */ + return(ret); + } + + /* If trace was not possible OR loop found OR */ + /* contour is incomplete ... */ + if((ret == IGNORE) || + (ret == LOOP_FOUND) || + (ncontour < lfsparms->pores_steps_bwd)){ + /* If contour allocated and returned ... */ + if((ret == LOOP_FOUND) || + (ncontour < lfsparms->pores_steps_bwd)) + /* Deallocate the contour. */ + free_contour(contour_x, contour_y, + contour_ex, contour_ey); + + print2log("%d,%d RMC\n", + minutia->x, minutia->y); + + /* Then remove the minutia. */ + if((ret = remove_minutia(i, minutiae))) + /* If system error, return error code. */ + return(ret); + /* Set remove flag to TRUE. */ + removed = TRUE; + } + /* Otherwise, traced contour is complete. */ + else{ + /* Store last point in contour as 'C'. */ + cx = contour_x[ncontour-1]; + cy = contour_y[ncontour-1]; + /* Deallocate the contour. */ + free_contour(contour_x, contour_y, + contour_ex, contour_ey); + + /* Compute squared distance between points */ + /* 'A' and 'B'. */ + ab2 = squared_distance(ax, ay, bx, by); + /* Compute squared distance between points */ + /* 'C' and 'D'. */ + cd2 = squared_distance(cx, cy, dx, dy); + /* If CD distance is not near zero */ + /* (ex. 0,5) ... */ + if(cd2 > lfsparms->pores_min_dist2){ + /* Compute ratio of squared distances. */ + ratio = ab2 / cd2; + /* If ratio is small enough (ex. 2.25)...*/ + if(ratio <= lfsparms->pores_max_ratio){ + + print2log("%d,%d ", + minutia->x, minutia->y); + print2log("R=%d,%d P=%d,%d B=%d,%d D=%d,%d Q=%d,%d A=%d,%d C=%d,%d ", + rx, ry, px, py, bx, by, dx, dy, qx, qy, ax, ay, cx, cy); + print2log("RMRATIO\n"); + + /* Then assume pore & remove minutia. */ + if((ret = remove_minutia(i, minutiae))) + /* If system error, return code. */ + return(ret); + /* Set remove flag to TRUE. */ + removed = TRUE; + } + /* Otherwise, ratio to big, so assume */ + /* legitimate bifurcation. */ + } /* Else, cd2 too small. */ + } /* Done with C. */ + } /* Done with A. */ + } + /* Otherwise, Q not found ... */ + else{ + + print2log("%d,%d RMQ\n", minutia->x, minutia->y); + + /* Then remove the minutia. */ + if((ret = remove_minutia(i, minutiae))) + /* If system error, return error code. */ + return(ret); + /* Set remove flag to TRUE. */ + removed = TRUE; + } /* Done with Q. */ + } /* Done with D. */ + } /* Done with B. */ + } + /* Otherwise, P not found ... */ + else{ + + print2log("%d,%d RMP\n", minutia->x, minutia->y); + + /* Then remove the minutia. */ + if((ret = remove_minutia(i, minutiae))) + /* If system error, return error code. */ + return(ret); + /* Set remove flag to TRUE. */ + removed = TRUE; + } + } /* Else, R is on white pixel. */ + } /* Else NMAP is INVALID, HIGH_CURVATURE, or NO_VALID_NBRS. */ + } /* Else, Ridge Ending. */ + + /* If current minutia not removed ... */ + if(!removed) + /* Bump to next minutia in list. */ + i++; + /* Otherwise, next minutia has slid into slot of current removed one. */ + + } /* End While minutia remaining in list. */ + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: remove_pores_V2 - Attempts to detect and remove minutia points located on +#cat: pore-shaped valleys and/or ridges. Detection for +#cat: these features are only performed in blocks with +#cat: LOW RIDGE FLOW or HIGH CURVATURE. + + Input: + minutiae - list of true and false minutiae + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + direction_map - map of image blocks containing directional ridge flow + low_flow_map - map of image blocks flagged as LOW RIDGE FLOW + high_curve_map - map of image blocks flagged as HIGH CURVATURE + mw - width in blocks of the maps + mh - height in blocks of the maps + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of pruned minutiae + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int remove_pores_V2(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + int *direction_map, int *low_flow_map, + int *high_curve_map, const int mw, const int mh, + const LFSPARMS *lfsparms) +{ + int i, ret; + int removed, blk_x, blk_y; + int rx, ry; + int px, py, pex, pey, bx, by, dx, dy; + int qx, qy, qex, qey, ax, ay, cx, cy; + MINUTIA *minutia; + double pi_factor, theta, sin_theta, cos_theta; + double ab2, cd2, ratio; + int *contour_x, *contour_y, *contour_ex, *contour_ey, ncontour; + double drx, dry; + + /* This routine attempts to locate the following points on all */ + /* minutia within the feature list. */ + /* 1. Compute R 3 pixels opposite the feature direction from */ + /* feature point F. */ + /* 2. Find white pixel transitions P & Q within 12 steps from */ + /* from R perpendicular to the feature's direction. */ + /* 3. Find points B & D by walking white edge from P. */ + /* 4. Find points A & C by walking white edge from Q. */ + /* 5. Measure squared distances between A-B and C-D. */ + /* 6. Compute ratio of squared distances and compare against */ + /* threshold (2.25). If A-B sufficiently larger than C-D, */ + /* then assume NOT pore, otherwise flag the feature point F.*/ + /* If along the way, finding any of these points fails, then */ + /* assume the feature is a pore and flag it. */ + /* */ + /* A */ + /* _____._ */ + /* ----___ Q C */ + /* ------____ ---_.________.___ */ + /* ---_ */ + /* (valley) F.\ .R (ridge) */ + /* ____/ */ + /* ______---- ___-.--------.--- */ + /* ____--- P D */ + /* -----.- */ + /* B */ + /* */ + /* AB^2/CD^2 <= 2.25 then flag feature */ + /* */ + + + print2log("\nREMOVING PORES:\n"); + + /* Factor for converting integer directions into radians. */ + pi_factor = M_PI/(double)lfsparms->num_directions; + + /* Initialize to the beginning of the minutia list. */ + i = 0; + /* Foreach minutia remaining in the list ... */ + while(i < minutiae->num){ + /* Set temporary minutia pointer. */ + minutia = minutiae->list[i]; + + /* Initialize remove flag to FALSE. */ + removed = FALSE; + + /* Compute block coords from minutia point. */ + blk_x = minutia->x / lfsparms->blocksize; + blk_y = minutia->y / lfsparms->blocksize; + + /* If minutia in LOW RIDGE FLOW or HIGH CURVATURE block */ + /* with a valid direction ... */ + if((*(low_flow_map+(blk_y*mw)+blk_x) || + *(high_curve_map+(blk_y*mw)+blk_x)) && + (*(direction_map+(blk_y*mw)+blk_x) >= 0)){ + /* Compute radian angle from minutia direction. */ + theta = (double)minutia->direction * pi_factor; + /* Compute sine and cosine factors of this angle. */ + sin_theta = sin(theta); + cos_theta = cos(theta); + /* Translate the minutia point (ex. 3 pixels) in opposite */ + /* direction minutia is pointing. Call this point 'R'. */ + drx = (double)minutia->x - + (sin_theta * (double)lfsparms->pores_trans_r); + dry = (double)minutia->y + + (cos_theta * (double)lfsparms->pores_trans_r); + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + drx = trunc_dbl_precision(drx, TRUNC_SCALE); + dry = trunc_dbl_precision(dry, TRUNC_SCALE); + rx = sround(drx); + ry = sround(dry); + + /* If 'R' is opposite color from minutia type ... */ + if(*(bdata+(ry*iw)+rx) != minutia->type){ + + /* Search a specified number of steps (ex. 12) from 'R' in a */ + /* perpendicular direction from the minutia direction until */ + /* the first white pixel is found. If a white pixel is */ + /* found within the specified number of steps, then call */ + /* this point 'P' (storing the point's edge pixel as well). */ + if(search_in_direction(&px, &py, &pex, &pey, + minutia->type, + rx, ry, -cos_theta, -sin_theta, + lfsparms->pores_perp_steps, + bdata, iw, ih)){ + /* Trace contour from P's edge pixel in counter-clockwise */ + /* scan and step along specified number of steps (ex. 10). */ + ret = trace_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, + lfsparms->pores_steps_fwd, + px, py, px, py, pex, pey, + SCAN_COUNTER_CLOCKWISE, bdata, iw, ih); + + /* If system error occurred during trace ... */ + if(ret < 0){ + /* Return error code. */ + return(ret); + } + + /* If trace was not possible OR loop found OR */ + /* contour is incomplete ... */ + if((ret == IGNORE) || + (ret == LOOP_FOUND) || + (ncontour < lfsparms->pores_steps_fwd)){ + /* If contour allocated and returned ... */ + if((ret == LOOP_FOUND) || + (ncontour < lfsparms->pores_steps_fwd)) + /* Deallocate the contour. */ + free_contour(contour_x, contour_y, + contour_ex, contour_ey); + + print2log("%d,%d RMB\n", minutia->x, minutia->y); + + /* Then remove the minutia. */ + if((ret = remove_minutia(i, minutiae))) + /* If system error, return error code. */ + return(ret); + /* Set remove flag to TRUE. */ + removed = TRUE; + } + /* Otherwise, traced contour is complete. */ + else{ + /* Store last point in contour as point 'B'. */ + bx = contour_x[ncontour-1]; + by = contour_y[ncontour-1]; + /* Deallocate the contour. */ + free_contour(contour_x, contour_y, + contour_ex, contour_ey); + + /* Trace contour from P's edge pixel in clockwise scan */ + /* and step along specified number of steps (ex. 8). */ + ret = trace_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, + lfsparms->pores_steps_bwd, + px, py, px, py, pex, pey, + SCAN_CLOCKWISE, bdata, iw, ih); + + /* If system error occurred during trace ... */ + if(ret < 0){ + /* Return error code. */ + return(ret); + } + + /* If trace was not possible OR loop found OR */ + /* contour is incomplete ... */ + if((ret == IGNORE) || + (ret == LOOP_FOUND) || + (ncontour < lfsparms->pores_steps_bwd)){ + /* If contour allocated and returned ... */ + if((ret == LOOP_FOUND) || + (ncontour < lfsparms->pores_steps_bwd)) + /* Deallocate the contour. */ + free_contour(contour_x, contour_y, + contour_ex, contour_ey); + + print2log("%d,%d RMD\n", minutia->x, minutia->y); + + /* Then remove the minutia. */ + if((ret = remove_minutia(i, minutiae))) + /* If system error, return error code. */ + return(ret); + /* Set remove flag to TRUE. */ + removed = TRUE; + } + /* Otherwise, traced contour is complete. */ + else{ + /* Store last point in contour as point 'D'. */ + dx = contour_x[ncontour-1]; + dy = contour_y[ncontour-1]; + /* Deallocate the contour. */ + free_contour(contour_x, contour_y, + contour_ex, contour_ey); + /* Search a specified number of steps (ex. 12) from */ + /* 'R' in opposite direction of that used to find */ + /* 'P' until the first white pixel is found. If a */ + /* white pixel is found within the specified number */ + /* of steps, then call this point 'Q' (storing the */ + /* point's edge pixel as well). */ + if(search_in_direction(&qx, &qy, &qex, &qey, + minutia->type, + rx, ry, cos_theta, sin_theta, + lfsparms->pores_perp_steps, + bdata, iw, ih)){ + /* Trace contour from Q's edge pixel in clockwise */ + /* scan and step along specified number of steps */ + /* (ex. 10). */ + ret = trace_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, + lfsparms->pores_steps_fwd, + qx, qy, qx, qy, qex, qey, + SCAN_CLOCKWISE, bdata, iw, ih); + + /* If system error occurred during trace ... */ + if(ret < 0){ + /* Return error code. */ + return(ret); + } + + /* If trace was not possible OR loop found OR */ + /* contour is incomplete ... */ + if((ret == IGNORE) || + (ret == LOOP_FOUND) || + (ncontour < lfsparms->pores_steps_fwd)){ + /* If contour allocated and returned ... */ + if((ret == LOOP_FOUND) || + (ncontour < lfsparms->pores_steps_fwd)) + /* Deallocate the contour. */ + free_contour(contour_x, contour_y, + contour_ex, contour_ey); + + print2log("%d,%d RMA\n", minutia->x, minutia->y); + + /* Then remove the minutia. */ + if((ret = remove_minutia(i, minutiae))) + /* If system error, return error code. */ + return(ret); + /* Set remove flag to TRUE. */ + removed = TRUE; + } + /* Otherwise, traced contour is complete. */ + else{ + /* Store last point in contour as point 'A'. */ + ax = contour_x[ncontour-1]; + ay = contour_y[ncontour-1]; + /* Deallocate the contour. */ + free_contour(contour_x, contour_y, + contour_ex, contour_ey); + + /* Trace contour from Q's edge pixel in */ + /* counter-clockwise scan and step along a */ + /* specified number of steps (ex. 8). */ + ret = trace_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, + lfsparms->pores_steps_bwd, + qx, qy, qx, qy, qex, qey, + SCAN_COUNTER_CLOCKWISE, bdata, iw, ih); + + /* If system error occurred during scan ... */ + if(ret < 0){ + /* Return error code. */ + return(ret); + } + + /* If trace was not possible OR loop found OR */ + /* contour is incomplete ... */ + if((ret == IGNORE) || + (ret == LOOP_FOUND) || + (ncontour < lfsparms->pores_steps_bwd)){ + /* If contour allocated and returned ... */ + if((ret == LOOP_FOUND) || + (ncontour < lfsparms->pores_steps_bwd)) + /* Deallocate the contour. */ + free_contour(contour_x, contour_y, + contour_ex, contour_ey); + + print2log("%d,%d RMC\n", + minutia->x, minutia->y); + + /* Then remove the minutia. */ + if((ret = remove_minutia(i, minutiae))) + /* If system error, return error code. */ + return(ret); + /* Set remove flag to TRUE. */ + removed = TRUE; + } + /* Otherwise, traced contour is complete. */ + else{ + /* Store last point in contour as 'C'. */ + cx = contour_x[ncontour-1]; + cy = contour_y[ncontour-1]; + /* Deallocate the contour. */ + free_contour(contour_x, contour_y, + contour_ex, contour_ey); + + /* Compute squared distance between points */ + /* 'A' and 'B'. */ + ab2 = squared_distance(ax, ay, bx, by); + /* Compute squared distance between points */ + /* 'C' and 'D'. */ + cd2 = squared_distance(cx, cy, dx, dy); + /* If CD distance is not near zero */ + /* (ex. 0.5) ... */ + if(cd2 > lfsparms->pores_min_dist2){ + /* Compute ratio of squared distances. */ + ratio = ab2 / cd2; + + /* If ratio is small enough (ex. 2.25)...*/ + if(ratio <= lfsparms->pores_max_ratio){ + + print2log("%d,%d ", + minutia->x, minutia->y); + print2log("R=%d,%d P=%d,%d B=%d,%d D=%d,%d Q=%d,%d A=%d,%d C=%d,%d ", + rx, ry, px, py, bx, by, dx, dy, qx, qy, ax, ay, cx, cy); + print2log("RMRATIO %f\n", ratio); + + /* Then assume pore & remove minutia. */ + if((ret = remove_minutia(i, minutiae))) + /* If system error, return code. */ + return(ret); + /* Set remove flag to TRUE. */ + removed = TRUE; + } + /* Otherwise, ratio to big, so assume */ + /* legitimate minutia. */ + } /* Else, cd2 too small. */ + } /* Done with C. */ + } /* Done with A. */ + } + /* Otherwise, Q not found ... */ + else{ + + print2log("%d,%d RMQ\n", minutia->x, minutia->y); + + /* Then remove the minutia. */ + if((ret = remove_minutia(i, minutiae))) + /* If system error, return error code. */ + return(ret); + /* Set remove flag to TRUE. */ + removed = TRUE; + } /* Done with Q. */ + } /* Done with D. */ + } /* Done with B. */ + } + /* Otherwise, P not found ... */ + else{ + + print2log("%d,%d RMP\n", minutia->x, minutia->y); + + /* Then remove the minutia. */ + if((ret = remove_minutia(i, minutiae))) + /* If system error, return error code. */ + return(ret); + /* Set remove flag to TRUE. */ + removed = TRUE; + } + } /* Else, R is on pixel the same color as type, so do not */ + /* remove minutia point and skip to next one. */ + } /* Else block is unreliable or has INVALID direction. */ + + /* If current minutia not removed ... */ + if(!removed) + /* Bump to next minutia in list. */ + i++; + /* Otherwise, next minutia has slid into slot of current removed one. */ + + } /* End While minutia remaining in list. */ + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: remove_or_adjust_side_minutiae - Removes loops or minutia points that +#cat: are not on complete contours of specified length. If the +#cat: contour is complete, then the minutia is adjusted based +#cat: on a minmax analysis of the rotated y-coords of the contour. + + Input: + minutiae - list of true and false minutiae + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of pruned minutiae + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int remove_or_adjust_side_minutiae(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + const LFSPARMS *lfsparms) +{ + int i, j, ret; + MINUTIA *minutia; + double pi_factor, theta, sin_theta, cos_theta; + int *contour_x, *contour_y, *contour_ex, *contour_ey, ncontour; + int *rot_y, minloc; + int *minmax_val, *minmax_i, *minmax_type, minmax_alloc, minmax_num; + double drot_y; + + print2log("\nADJUSTING SIDE MINUTIA:\n"); + + /* Allocate working memory for holding rotated y-coord of a */ + /* minutia's contour. */ + rot_y = (int *)malloc(((lfsparms->side_half_contour<<1)+1) * sizeof(int)); + if(rot_y == (int *)NULL){ + fprintf(stderr, + "ERROR : remove_or_adjust_side_minutiae : malloc : rot_y\n"); + return(-280); + } + + /* Compute factor for converting integer directions to radians. */ + pi_factor = M_PI / (double)lfsparms->num_directions; + + i = 0; + /* Foreach minutia remaining in list ... */ + while(i < minutiae->num){ + /* Assign a temporary pointer. */ + minutia = minutiae->list[i]; + + /* Extract a contour centered on the minutia point (ex. 7 pixels */ + /* in both directions). */ + ret = get_centered_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, + lfsparms->side_half_contour, + minutia->x, minutia->y, minutia->ex, minutia->ey, + bdata, iw, ih); + + /* If system error occurred ... */ + if(ret < 0){ + /* Deallocate working memory. */ + free(rot_y); + /* Return error code. */ + return(ret); + } + + /* If we didn't succeed in extracting a complete contour for any */ + /* other reason ... */ + if((ret == LOOP_FOUND) || + (ret == IGNORE) || + (ret == INCOMPLETE)){ + + print2log("%d,%d RM1\n", minutia->x, minutia->y); + + /* Remove minutia from list. */ + if((ret = remove_minutia(i, minutiae))){ + /* Deallocate working memory. */ + free(rot_y); + /* Return error code. */ + return(ret); + } + /* No need to advance because next minutia has "slid" */ + /* into position pointed to by 'i'. */ + } + /* Otherwise, a complete contour was found and extracted ... */ + else{ + /* Rotate contour points by negative angle of feature's direction. */ + /* The contour of a well-formed minutia point will form a bowl */ + /* shape concaved in the direction of the minutia. By rotating */ + /* the contour points by the negative angle of feature's direction */ + /* the bowl will be transformed to be concaved upwards and minima */ + /* and maxima of the transformed y-coords can be analyzed to */ + /* determine if the minutia is "well-formed" or not. If well- */ + /* formed then the position of the minutia point is adjusted. If */ + /* not well-formed, then the minutia point is removed altogether. */ + + /* Normal rotation of T degrees around the origin of */ + /* the point (x,y): */ + /* rx = x*cos(T) - y*sin(T) */ + /* ry = x*cos(T) + y*sin(T) */ + /* The rotation here is for -T degrees: */ + /* rx = x*cos(-T) - y*sin(-T) */ + /* ry = x*cos(-T) + y*sin(-T) */ + /* which can be written: */ + /* rx = x*cos(T) + y*sin(T) */ + /* ry = x*sin(T) - y*cos(T) */ + + /* Convert minutia's direction to radians. */ + theta = (double)minutia->direction * pi_factor; + /* Compute sine and cosine values at theta for rotation. */ + sin_theta = sin(theta); + cos_theta = cos(theta); + + for(j = 0; j < ncontour; j++){ + /* We only need to rotate the y-coord (don't worry */ + /* about rotating the x-coord or contour edge pixels). */ + drot_y = ((double)contour_x[j] * sin_theta) - + ((double)contour_y[j] * cos_theta); + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + drot_y = trunc_dbl_precision(drot_y, TRUNC_SCALE); + rot_y[j] = sround(drot_y); + } + + /* Locate relative minima and maxima in vector of rotated */ + /* y-coords of current minutia's contour. */ + if((ret = minmaxs(&minmax_val, &minmax_type, &minmax_i, + &minmax_alloc, &minmax_num, + rot_y, ncontour))){ + /* If system error, then deallocate working memories. */ + free(rot_y); + free_contour(contour_x, contour_y, contour_ex, contour_ey); + /* Return error code. */ + return(ret); + } + + /* If one and only one minima was found in rotated y-coord */ + /* of contour ... */ + if((minmax_num == 1) && + (minmax_type[0] == -1)){ + + print2log("%d,%d AD1 ", minutia->x, minutia->y); + + /* Reset loation of minutia point to contour point at minima. */ + minutia->x = contour_x[minmax_i[0]]; + minutia->y = contour_y[minmax_i[0]]; + minutia->ex = contour_ex[minmax_i[0]]; + minutia->ey = contour_ey[minmax_i[0]]; + /* Advance to the next minutia in the list. */ + i++; + + print2log("%d,%d\n", minutia->x, minutia->y); + + } + /* If exactly 3 min/max found and they are min-max-min ... */ + else if((minmax_num == 3) && + (minmax_type[0] == -1)){ + /* Choose minima location with smallest rotated y-coord. */ + if(minmax_val[0] < minmax_val[2]) + minloc = minmax_i[0]; + else + minloc = minmax_i[2]; + + print2log("%d,%d AD2 ", minutia->x, minutia->y); + + /* Reset loation of minutia point to contour point at minima. */ + minutia->x = contour_x[minloc]; + minutia->y = contour_y[minloc]; + minutia->ex = contour_ex[minloc]; + minutia->ey = contour_ey[minloc]; + /* Advance to the next minutia in the list. */ + i++; + + print2log("%d,%d\n", minutia->x, minutia->y); + + } + /* Otherwise, ... */ + else{ + + print2log("%d,%d RM2\n", minutia->x, minutia->y); + + /* Remove minutia from list. */ + if((ret = remove_minutia(i, minutiae))){ + /* If system error, then deallocate working memories. */ + free(rot_y); + free_contour(contour_x, contour_y, contour_ex, contour_ey); + if(minmax_alloc > 0){ + free(minmax_val); + free(minmax_type); + free(minmax_i); + } + /* Return error code. */ + return(ret); + } + /* No need to advance because next minutia has "slid" */ + /* into position pointed to by 'i'. */ + + } + + /* Deallocate contour and min/max buffers. */ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + if(minmax_alloc > 0){ + free(minmax_val); + free(minmax_type); + free(minmax_i); + } + } /* End else contour extracted. */ + } /* End while not end of minutiae list. */ + + /* Deallocate working memory. */ + free(rot_y); + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: remove_or_adjust_side_minutiae_V2 - Removes loops or minutia points that +#cat: are not on complete contours of specified length. If the +#cat: contour is complete, then the minutia is adjusted based +#cat: on a minmax analysis of the rotated y-coords of the contour. + + Input: + minutiae - list of true and false minutiae + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + direction_map - map of image blocks containing directional ridge flow + mw - width (in blocks) of the map + mh - height (in blocks) of the map + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of pruned minutiae + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int remove_or_adjust_side_minutiae_V2(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + int *direction_map, const int mw, const int mh, + const LFSPARMS *lfsparms) +{ + int i, j, ret; + MINUTIA *minutia; + double pi_factor, theta, sin_theta, cos_theta; + int *contour_x, *contour_y, *contour_ex, *contour_ey, ncontour; + int *rot_y, minloc; + int *minmax_val, *minmax_i, *minmax_type, minmax_alloc, minmax_num; + double drot_y; + int bx, by; + + print2log("\nADJUSTING SIDE MINUTIA:\n"); + + /* Allocate working memory for holding rotated y-coord of a */ + /* minutia's contour. */ + rot_y = (int *)malloc(((lfsparms->side_half_contour<<1)+1) * sizeof(int)); + if(rot_y == (int *)NULL){ + fprintf(stderr, + "ERROR : remove_or_adjust_side_minutiae_V2 : malloc : rot_y\n"); + return(-630); + } + + /* Compute factor for converting integer directions to radians. */ + pi_factor = M_PI / (double)lfsparms->num_directions; + + i = 0; + /* Foreach minutia remaining in list ... */ + while(i < minutiae->num){ + /* Assign a temporary pointer. */ + minutia = minutiae->list[i]; + + /* Extract a contour centered on the minutia point (ex. 7 pixels */ + /* in both directions). */ + ret = get_centered_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, + lfsparms->side_half_contour, + minutia->x, minutia->y, minutia->ex, minutia->ey, + bdata, iw, ih); + + /* If system error occurred ... */ + if(ret < 0){ + /* Deallocate working memory. */ + free(rot_y); + /* Return error code. */ + return(ret); + } + + /* If we didn't succeed in extracting a complete contour for any */ + /* other reason ... */ + if((ret == LOOP_FOUND) || + (ret == IGNORE) || + (ret == INCOMPLETE)){ + + print2log("%d,%d RM1\n", minutia->x, minutia->y); + + /* Remove minutia from list. */ + if((ret = remove_minutia(i, minutiae))){ + /* Deallocate working memory. */ + free(rot_y); + /* Return error code. */ + return(ret); + } + /* No need to advance because next minutia has "slid" */ + /* into position pointed to by 'i'. */ + } + /* Otherwise, a complete contour was found and extracted ... */ + else{ + /* Rotate contour points by negative angle of feature's direction. */ + /* The contour of a well-formed minutia point will form a bowl */ + /* shape concaved in the direction of the minutia. By rotating */ + /* the contour points by the negative angle of feature's direction */ + /* the bowl will be transformed to be concaved upwards and minima */ + /* and maxima of the transformed y-coords can be analyzed to */ + /* determine if the minutia is "well-formed" or not. If well- */ + /* formed then the position of the minutia point is adjusted. If */ + /* not well-formed, then the minutia point is removed altogether. */ + + /* Normal rotation of T degrees around the origin of */ + /* the point (x,y): */ + /* rx = x*cos(T) - y*sin(T) */ + /* ry = x*cos(T) + y*sin(T) */ + /* The rotation here is for -T degrees: */ + /* rx = x*cos(-T) - y*sin(-T) */ + /* ry = x*cos(-T) + y*sin(-T) */ + /* which can be written: */ + /* rx = x*cos(T) + y*sin(T) */ + /* ry = x*sin(T) - y*cos(T) */ + + /* Convert minutia's direction to radians. */ + theta = (double)minutia->direction * pi_factor; + /* Compute sine and cosine values at theta for rotation. */ + sin_theta = sin(theta); + cos_theta = cos(theta); + + for(j = 0; j < ncontour; j++){ + /* We only need to rotate the y-coord (don't worry */ + /* about rotating the x-coord or contour edge pixels). */ + drot_y = ((double)contour_x[j] * sin_theta) - + ((double)contour_y[j] * cos_theta); + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + drot_y = trunc_dbl_precision(drot_y, TRUNC_SCALE); + rot_y[j] = sround(drot_y); + } + + /* Locate relative minima and maxima in vector of rotated */ + /* y-coords of current minutia's contour. */ + if((ret = minmaxs(&minmax_val, &minmax_type, &minmax_i, + &minmax_alloc, &minmax_num, + rot_y, ncontour))){ + /* If system error, then deallocate working memories. */ + free(rot_y); + free_contour(contour_x, contour_y, contour_ex, contour_ey); + /* Return error code. */ + return(ret); + } + + /* If one and only one minima was found in rotated y-coord */ + /* of contour ... */ + if((minmax_num == 1) && + (minmax_type[0] == -1)){ + + print2log("%d,%d ", minutia->x, minutia->y); + + /* Reset loation of minutia point to contour point at minima. */ + minutia->x = contour_x[minmax_i[0]]; + minutia->y = contour_y[minmax_i[0]]; + minutia->ex = contour_ex[minmax_i[0]]; + minutia->ey = contour_ey[minmax_i[0]]; + + /* Must check if adjusted minutia is now in INVALID block ... */ + bx = minutia->x/lfsparms->blocksize; + by = minutia->y/lfsparms->blocksize; + if(*(direction_map+(by*mw)+bx) == INVALID_DIR){ + /* Remove minutia from list. */ + if((ret = remove_minutia(i, minutiae))){ + /* Deallocate working memory. */ + free(rot_y); + free_contour(contour_x, contour_y, contour_ex, contour_ey); + if(minmax_alloc > 0){ + free(minmax_val); + free(minmax_type); + free(minmax_i); + } + /* Return error code. */ + return(ret); + } + /* No need to advance because next minutia has "slid" */ + /* into position pointed to by 'i'. */ + + print2log("RM2\n"); + } + else{ + /* Advance to the next minutia in the list. */ + i++; + print2log("AD1 %d,%d\n", minutia->x, minutia->y); + } + + } + /* If exactly 3 min/max found and they are min-max-min ... */ + else if((minmax_num == 3) && + (minmax_type[0] == -1)){ + /* Choose minima location with smallest rotated y-coord. */ + if(minmax_val[0] < minmax_val[2]) + minloc = minmax_i[0]; + else + minloc = minmax_i[2]; + + print2log("%d,%d ", minutia->x, minutia->y); + + /* Reset loation of minutia point to contour point at minima. */ + minutia->x = contour_x[minloc]; + minutia->y = contour_y[minloc]; + minutia->ex = contour_ex[minloc]; + minutia->ey = contour_ey[minloc]; + + /* Must check if adjusted minutia is now in INVALID block ... */ + bx = minutia->x/lfsparms->blocksize; + by = minutia->y/lfsparms->blocksize; + if(*(direction_map+(by*mw)+bx) == INVALID_DIR){ + /* Remove minutia from list. */ + if((ret = remove_minutia(i, minutiae))){ + /* Deallocate working memory. */ + free(rot_y); + free_contour(contour_x, contour_y, contour_ex, contour_ey); + if(minmax_alloc > 0){ + free(minmax_val); + free(minmax_type); + free(minmax_i); + } + /* Return error code. */ + return(ret); + } + /* No need to advance because next minutia has "slid" */ + /* into position pointed to by 'i'. */ + + print2log("RM3\n"); + } + else{ + /* Advance to the next minutia in the list. */ + i++; + print2log("AD2 %d,%d\n", minutia->x, minutia->y); + } + } + /* Otherwise, ... */ + else{ + + print2log("%d,%d RM4\n", minutia->x, minutia->y); + + /* Remove minutia from list. */ + if((ret = remove_minutia(i, minutiae))){ + /* If system error, then deallocate working memories. */ + free(rot_y); + free_contour(contour_x, contour_y, contour_ex, contour_ey); + if(minmax_alloc > 0){ + free(minmax_val); + free(minmax_type); + free(minmax_i); + } + /* Return error code. */ + return(ret); + } + /* No need to advance because next minutia has "slid" */ + /* into position pointed to by 'i'. */ + } + + /* Deallocate contour and min/max buffers. */ + free_contour(contour_x, contour_y, contour_ex, contour_ey); + if(minmax_alloc > 0){ + free(minmax_val); + free(minmax_type); + free(minmax_i); + } + } /* End else contour extracted. */ + } /* End while not end of minutiae list. */ + + /* Deallocate working memory. */ + free(rot_y); + + /* Return normally. */ + return(0); +} + diff --git a/libfprint/nbis/mindtct/results.c b/libfprint/nbis/mindtct/results.c new file mode 100644 index 00000000..1f8f1dbc --- /dev/null +++ b/libfprint/nbis/mindtct/results.c @@ -0,0 +1,682 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: RESULTS.C + AUTHOR: Michael D. Garris + DATE: 03/16/1999 + UPDATED: 10/04/1999 Version 2 by MDG + 09/14/2004 + UPDATED: 03/16/2005 by MDG + + Contains routines useful in visualizing intermediate and final + results when exercising the NIST Latent Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + write_text_results() + write_minutiae_XYTQ() + dump_map() + drawmap() + drawmap2() + drawblocks() + drawrotgrid() + dump_link_table() + +***********************************************************************/ + +#include +#include +#include +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: write_text_results - Takes LFS results including minutiae and image +#cat: maps and writes them to separate formatted text files. + + Input: + oroot - root pathname for output files + m1flag - if flag set, write (X,Y,T)'s out to "*.xyt" file according + to M1 (ANSI INCITS 378-2004) minutiae representation + + M1 Rep: + 1. pixel origin top left + 2. direction pointing up the ridge ending or + bifurcaiton valley + NIST Internal Rep: + 1. pixel origin bottom left + 2. direction pointing out and away from the + ridge ending or bifurcation valley + + iw - image pixel width + ih - image pixel height + minutiae - structure containing the detected minutiae + quality_map - integrated image quality map + direction_map - direction map + low_contrast_map - low contrast map + low_flow_map - low ridge flow map + high_curve_map - high curvature map + map_w - width (in blocks) of image maps + map_h - height (in blocks) of image maps + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int write_text_results(char *oroot, const int m1flag, + const int iw, const int ih, + const MINUTIAE *minutiae, int *quality_map, + int *direction_map, int *low_contrast_map, + int *low_flow_map, int *high_curve_map, + const int map_w, const int map_h) +{ + FILE *fp; + int ret; + char ofile[MAXPATHLEN]; + + /* 1. Write Minutiae results to text file ".min". */ + /* XYT's written in LFS native representation: */ + /* 1. pixel coordinates with origin top-left */ + /* 2. 11.25 degrees quantized integer orientation */ + /* on range [0..31] */ + /* 3. minutiae reliability on range [0.0 .. 1.0] */ + /* with 0.0 lowest and 1.0 highest reliability */ + sprintf(ofile, "%s.%s", oroot, MIN_TXT_EXT); + if((fp = fopen(ofile, "wb")) == (FILE *)NULL){ + fprintf(stderr, "ERROR : write_text_results : fopen : %s\n", ofile); + return(-2); + } + /* Print out Image Dimensions Header */ + /* !!!! Image dimension header added 09-13-04 !!!! */ + fprintf(fp, "Image (w,h) %d %d\n", iw, ih); + /* Print text report from the structure containing detected minutiae. */ + dump_minutiae(fp, minutiae); + if(fclose(fp)){ + fprintf(stderr, "ERROR : write_text_results : fclose : %s\n", ofile); + return(-3); + } + + /* 2. Write just minutiae XYT's & Qualities to text */ + /* file ".xyt". */ + /* */ + /* A. If M1 flag set: */ + /* XYTQ's written according to M1 (ANSI INCITS */ + /* 378-2004) representation: */ + /* 1. pixel coordinates with origin top-left */ + /* 2. orientation in degrees on range [0..360] */ + /* with 0 pointing east and increasing counter */ + /* clockwise */ + /* 3. direction pointing up the ridge ending or */ + /* bifurcaiton valley */ + /* 4. minutiae qualities on integer range [0..100] */ + /* (non-standard) */ + /* */ + /* B. If M1 flag NOT set: */ + /* XYTQ's written according to NIST internal rep. */ + /* 1. pixel coordinates with origin bottom-left */ + /* 2. orientation in degrees on range [0..360] */ + /* with 0 pointing east and increasing counter */ + /* clockwise (same as M1) */ + /* 3. direction pointing out and away from the */ + /* ridge ending or bifurcation valley */ + /* (opposite direction from M1) */ + /* 4. minutiae qualities on integer range [0..100] */ + /* (non-standard) */ + sprintf(ofile, "%s.%s", oroot, XYT_EXT); + if(m1flag){ + if((ret = write_minutiae_XYTQ(ofile, M1_XYT_REP, minutiae, iw, ih))){ + return(ret); + } + } + else{ + if((ret = write_minutiae_XYTQ(ofile, NIST_INTERNAL_XYT_REP, + minutiae, iw, ih))){ + return(ret); + } + } + + /* 3. Write Integrated Quality Map results to text file. */ + sprintf(ofile, "%s.%s", oroot, QUALITY_MAP_EXT); + if((fp = fopen(ofile, "wb")) == (FILE *)NULL){ + fprintf(stderr, "ERROR : write_text_results : fopen : %s\n", ofile); + return(-4); + } + /* Print a text report from the map. */ + dump_map(fp, quality_map, map_w, map_h); + if(fclose(fp)){ + fprintf(stderr, "ERROR : write_text_results : fclose : %s\n", ofile); + return(-5); + } + + /* 4. Write Direction Map results to text file. */ + sprintf(ofile, "%s.%s", oroot, DIRECTION_MAP_EXT); + if((fp = fopen(ofile, "wb")) == (FILE *)NULL){ + fprintf(stderr, "ERROR : write_text_results : fopen : %s\n", ofile); + return(-6); + } + /* Print a text report from the map. */ + dump_map(fp, direction_map, map_w, map_h); + if(fclose(fp)){ + fprintf(stderr, "ERROR : write_text_results : fclose : %s\n", ofile); + return(-7); + } + + /* 5. Write Low Contrast Map results to text file. */ + sprintf(ofile, "%s.%s", oroot, LOW_CONTRAST_MAP_EXT); + if((fp = fopen(ofile, "wb")) == (FILE *)NULL){ + fprintf(stderr, "ERROR : write_text_results : fopen : %s\n", ofile); + return(-8); + } + /* Print a text report from the map. */ + dump_map(fp, low_contrast_map, map_w, map_h); + if(fclose(fp)){ + fprintf(stderr, "ERROR : write_text_results : fclose : %s\n", ofile); + return(-9); + } + + /* 6. Write Low Flow Map results to text file. */ + sprintf(ofile, "%s.%s", oroot, LOW_FLOW_MAP_EXT); + if((fp = fopen(ofile, "wb")) == (FILE *)NULL){ + fprintf(stderr, "ERROR : write_text_results : fopen : %s\n", ofile); + return(-10); + } + /* Print a text report from the map. */ + dump_map(fp, low_flow_map, map_w, map_h); + if(fclose(fp)){ + fprintf(stderr, "ERROR : write_text_results : fclose : %s\n", ofile); + return(-11); + } + + /* 7. Write High Curvature Map results to text file. */ + sprintf(ofile, "%s.%s", oroot, HIGH_CURVE_MAP_EXT); + if((fp = fopen(ofile, "wb")) == (FILE *)NULL){ + fprintf(stderr, "ERROR : write_text_results : fopen : %s\n", ofile); + return(-12); + } + /* Print a text report from the map. */ + dump_map(fp, high_curve_map, map_w, map_h); + if(fclose(fp)){ + fprintf(stderr, "ERROR : write_text_results : fclose : %s\n", ofile); + return(-13); + } + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: write_minutiae_XYTQ - Write just minutiae XYT's & Qualities to text +#cat: file according to the specified mintuiae represenation + + Input: + ofile - output file name + reptype - specifies XYT output representation + minutiae - structure containing a list of LFS detected minutiae + iw - width (in pixels) of the input image + ih - height (in pixels) of the input image + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int write_minutiae_XYTQ(char *ofile, const int reptype, + const MINUTIAE *minutiae, const int iw, const int ih) +{ + FILE *fp; + int i, ox, oy, ot, oq; + MINUTIA *minutia; + + /* A. If M1 flag set: */ + /* XYTQ's written according to M1 (ANSI INCITS */ + /* 378-2004) representation: */ + /* 1. pixel coordinates with origin top-left */ + /* 2. orientation in degrees on range [0..360] */ + /* with 0 pointing east and increasing counter */ + /* clockwise */ + /* 3. direction pointing up the ridge ending or */ + /* bifurcaiton valley */ + /* 4. minutiae qualities on integer range [0..100] */ + /* (non-standard) */ + /* */ + /* B. If M1 flag NOT set: */ + /* XYTQ's written according to NIST internal rep. */ + /* 1. pixel coordinates with origin bottom-left */ + /* 2. orientation in degrees on range [0..360] */ + /* with 0 pointing east and increasing counter */ + /* clockwise (same as M1) */ + /* 3. direction pointing out and away from the */ + /* ridge ending or bifurcation valley */ + /* (opposite direction from M1) */ + /* 4. minutiae qualities on integer range [0..100] */ + /* (non-standard) */ + + if((fp = fopen(ofile, "wb")) == (FILE *)NULL){ + fprintf(stderr, "ERROR : write_minutiae_XYTQ : fopen : %s\n", ofile); + return(-2); + } + + for(i = 0; i < minutiae->num; i++){ + minutia = minutiae->list[i]; + + switch(reptype){ + case M1_XYT_REP: + lfs2m1_minutia_XYT(&ox, &oy, &ot, minutia); + break; + case NIST_INTERNAL_XYT_REP: + lfs2nist_minutia_XYT(&ox, &oy, &ot, minutia, iw, ih); + break; + default: + fprintf(stderr, "ERROR : write_minutiae_XYTQ : "); + fprintf(stderr, "Invalid XYT representation type = %d\n", reptype); + fclose(fp); + return(-4); + } + + oq = sround(minutia->reliability * 100.0); + + fprintf(fp, "%d %d %d %d\n", ox, oy, ot, oq); + } + + + if(fclose(fp)){ + fprintf(stderr, "ERROR : write_minutiae_XYTQ : fopen : %s\n", ofile); + return(-5); + } + + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: dump_map - Prints a text report to the specified open file pointer +#cat: of the integer values in a 2D integer vector. + + Input: + fpout - open file pointer + map - vector of integer directions (-1 ==> invalid direction) + mw - width (number of blocks) of map vector + mh - height (number of blocks) of map vector +**************************************************************************/ +void dump_map(FILE *fpout, int *map, const int mw, const int mh) +{ + int mx, my; + int *iptr; + + /* Simply print the map matrix out to the specified file pointer. */ + iptr = map; + for(my = 0; my < mh; my++){ + for(mx = 0; mx < mw; mx++){ + fprintf(fpout, "%2d ", *iptr++); + } + fprintf(fpout, "\n"); + } +} + +/************************************************************************* +************************************************************************** +#cat: drawmap - Draws integer direction vectors over their respective blocks +#cat: of an input image. Note that the input image is modified +#cat: upon return form this routine. + + Input: + imap - computed vector of integer directions. (-1 ==> invalid) + mw - width (in blocks) of the map + mh - height (in blocks) of the map + idata - input image data to be annotated + iw - width (in pixels) of the input image + ih - height (in pixels) of the input image + rotgrids - structure containing the rotated pixel grid offsets + draw_pixel - pixel intensity to be used when drawing on the image + Output: + idata - input image contains the results of the annoatation + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int drawmap(int *imap, const int mw, const int mh, + unsigned char *idata, const int iw, const int ih, + const ROTGRIDS *dftgrids, const int draw_pixel) +{ + int bi, *iptr; + double dy, dx, xincr, yincr; + int cbxy; + int i, xyoffset; + unsigned char *cptr, *lptr, *rptr, *eptr; + double theta, pi_incr; + int *blkoffs, bw, bh; + int ret; /* return code */ + + /* Compute block offsets into the input image. */ + /* Block_offsets() assumes square block (grid), so ERROR otherwise. */ + if(dftgrids->grid_w != dftgrids->grid_h){ + fprintf(stderr, "ERROR : drawmap : DFT grids must be square\n"); + return(-130); + } + if((ret = block_offsets(&blkoffs, &bw, &bh, iw, ih, + dftgrids->pad, dftgrids->grid_w))){ + return(ret); + } + + if((bw != mw) || (bh != mh)){ + /* Free memory allocated to this point. */ + free(blkoffs); + fprintf(stderr, + "ERROR : drawmap : block dimensions between map and image do not match\n"); + return(-131); + } + + cbxy = dftgrids->grid_w>>1; + pi_incr = M_PI/(double)dftgrids->ngrids; + + eptr = idata + (ih*iw); + iptr = imap; + /* Foreach block in image ... */ + for(bi = 0; bi < mw*mh; bi++){ + + /* If valid direction for block ... */ + if(*iptr != INVALID_DIR){ + + /* Get slope components of direction angle */ + theta = dftgrids->start_angle + (*iptr * pi_incr); + dx = cos(theta); + dy = sin(theta); + + /* Draw line rotated by the direction angle and centered */ + /* on the block. */ + /* Check if line is perfectly vertical ... */ + if(dx == 0){ + /* Draw vertical line starting at top of block shifted */ + /* over to horizontal center of the block. */ + lptr = idata + blkoffs[bi] + cbxy; + for(i = 0; i < dftgrids->grid_w; i++){ + if((lptr > idata) && (lptr < eptr)){ + *lptr = draw_pixel; + } + lptr += iw; + } + } + else{ + cptr = idata + blkoffs[bi] + (cbxy*iw) + cbxy; + + /* Draw center pixel */ + *cptr = draw_pixel; + + /* Draw left and right half of line */ + xincr = dx; + yincr = dy; + for(i = 0; i < cbxy; i++){ + xyoffset = (sround(yincr)*iw) + sround(xincr); + rptr = cptr + xyoffset; + if((rptr > idata) && (rptr < eptr)){ + *rptr = draw_pixel; + } + lptr = cptr - xyoffset; + if((lptr > idata) && (lptr < eptr)){ + *lptr = draw_pixel; + } + xincr += dx; + yincr += dy; + } + } + } + iptr++; + } + + /* Deallocate working memory */ + free(blkoffs); + + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: drawmap2 - Draws integer direction vectors over their respective blocks +#cat: of an input image. Note that the input image is modified +#cat: upon return form this routine. In this version of the +#cat: routine, offsets to the origin of each block in the image +#cat: must be precomputed and passed in. + + Input: + imap - computed vector of integer directions. (-1 ==> invalid) + blkoffs - list of pixel offsets to the origin of each block in the + image from which the map was computed + mw - width (in blocks) of the map + mh - height (in blocks) of the map + pdata - input image data to be annotated + pw - width (in pixels) of the input image + ph - height (in pixels) of the input image + start_angle - the angle (in radians) that the direction 0 points in + ndirs - number of directions within a half circle + blocksize - the dimensions (in pixels) of each block + Output: + pdata - input image contains the results of the annoatation +**************************************************************************/ +void drawmap2(int *imap, const int *blkoffs, const int mw, const int mh, + unsigned char *pdata, const int pw, const int ph, + const double start_angle, const int ndirs, const int blocksize) +{ + int bi, *iptr; + double dy, dx, xincr, yincr; + int cbxy; + int i, xyoffset; + unsigned char *cptr, *lptr, *rptr, *eptr; + double theta, pi_incr; + + cbxy = blocksize>>1; + pi_incr = M_PI/(double)ndirs; + + eptr = pdata + (pw*ph); + iptr = imap; + /* Foreach block in image ... */ + for(bi = 0; bi < mw*mh; bi++){ + + /* If valid direction for block ... */ + if(*iptr != INVALID_DIR){ + + /* Get slope components of direction angle */ + theta = start_angle + (*iptr * pi_incr); + dx = cos((double)theta); + dy = sin((double)theta); + + /* Draw line rotated by the direction angle and centered */ + /* on the block. */ + /* Check if line is perfectly vertical ... */ + if(dx == 0){ + /* Draw vertical line starting at top of block shifted */ + /* over to horizontal center of the block. */ + lptr = pdata + blkoffs[bi] + cbxy; + for(i = 0; i < blocksize; i++){ + if((lptr > pdata) && (lptr < eptr)) + *lptr = 255; + lptr += pw; + } + } + else{ + cptr = pdata + blkoffs[bi] + (cbxy*pw) + cbxy; + + /* Draw center pixel */ + *cptr = 255; + + /* Draw left and right half of line */ + xincr = dx; + yincr = dy; + for(i = 0; i < cbxy; i++){ + xyoffset = (sround(yincr)*pw) + sround(xincr); + rptr = cptr + xyoffset; + if((rptr > pdata) && (rptr < eptr)) + *rptr = 255; + lptr = cptr - xyoffset; + if((lptr > pdata) && (lptr < eptr)) + *lptr = 255; + xincr += dx; + yincr += dy; + } + } + } + iptr++; + } +} + +/************************************************************************* +************************************************************************** +#cat: drawblocks - Annotates an input image with the location of each block's +#cat: origin. This routine is useful to see how blocks are +#cat: assigned to arbitrarily-sized images that are not an even +#cat: width or height of the block size. In these cases the last +#cat: column pair and row pair of blocks overlap each other. +#cat: Note that the input image is modified upon return form +#cat: this routine. + + Input: + blkoffs - offsets to the pixel origin of each block in the image + mw - number of blocks horizontally in the input image + mh - number of blocks vertically in the input image + pdata - input image data to be annotated that has pixel dimensions + compatible with the offsets in blkoffs + pw - width (in pixels) of the input image + ph - height (in pixels) of the input image + draw_pixel - pixel intensity to be used when drawing on the image + Output: + pdata - input image contains the results of the annoatation +**************************************************************************/ +void drawblocks(const int *blkoffs, const int mw, const int mh, + unsigned char *pdata, const int pw, const int ph, + const int draw_pixel) +{ + int bi; + unsigned char *bptr; + + for(bi = 0; bi < mw*mh; bi++){ + bptr = pdata + blkoffs[bi]; + *bptr = draw_pixel; + } +} + + +/************************************************************************* +************************************************************************** +#cat: drawrotgrid - Annotates an input image with a specified rotated grid. +#cat: This routine is useful to see the location and orientation +#cat: of a specific rotated grid within a specific block in the +#cat: image. Note that the input image is modified upon return +#cat: form this routine. + + Input: + rotgrids - structure containing the rotated pixel grid offsets + dir - integer direction of the rotated grid to be annontated + idata - input image data to be annotated. + blkoffset - the pixel offset from the origin of the input image to + the origin of the specific block to be annoted + iw - width (in pixels) of the input image + ih - height (in pixels) of the input image + draw_pixel - pixel intensity to be used when drawing on the image + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int drawrotgrid(const ROTGRIDS *rotgrids, const int dir, + unsigned char *idata, const int blkoffset, + const int iw, const int ih, const int draw_pixel) +{ + int i, j, gi; + + /* Check if specified rotation direction is within range of */ + /* rotated grids. */ + if(dir >= rotgrids->ngrids){ + fprintf(stderr, + "ERROR : drawrotgrid : input direction exceeds range of rotated grids\n"); + return(-140); + } + + /* Intialize grid offset index */ + gi = 0; + /* Foreach row in rotated grid ... */ + for(i = 0; i < rotgrids->grid_h; i++){ + /* Foreach column in rotated grid ... */ + for(j = 0; j < rotgrids->grid_w; j++){ + /* Draw pixels from every other rotated row to represent direction */ + /* of line sums used in DFT processing. */ + if(i%2) + *(idata+blkoffset+rotgrids->grids[dir][gi]) = draw_pixel; + /* Bump grid offset index */ + gi++; + } + } + + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: dump_link_table - takes a link table and vectors of minutia IDs +#cat: assigned to its axes and prints the table's contents out +#cat: as formatted text to the specified open file pointer. + + Input: + fpout - open file pointer + link_table - sparse 2D table containing scores of potentially linked + minutia pairs + x_axis - minutia IDs registered along x-axis + y_axis - minutia IDs registered along y-axis + nx_axis - number of minutia registered along x-axis + ny_axis - number of minutia registered along y-axis + tbldim - dimension of each axes of the link table + minutiae - list of minutia points +**************************************************************************/ +void dump_link_table(FILE *fpout, const int *link_table, + const int *x_axis, const int *y_axis, + const int nx_axis, const int ny_axis, const int tbldim, + const MINUTIAE *minutiae) +{ + int i, tx, ty, sentry, entry; + + fprintf(fpout, "DUMP LINK TABLE:\n"); + + fprintf(fpout, "X-AXIS:\n"); + for(i = 0; i < nx_axis; i++){ + fprintf(fpout, "%d: %d,%d\n", i, minutiae->list[x_axis[i]]->x, + minutiae->list[x_axis[i]]->y); + } + + fprintf(fpout, "Y-AXIS:\n"); + for(i = 0; i < ny_axis; i++){ + fprintf(fpout, "%d: %d,%d\n", i, minutiae->list[y_axis[i]]->x, + minutiae->list[y_axis[i]]->y); + } + + fprintf(fpout, "TABLE:\n"); + sentry = 0; + for(ty = 0; ty < ny_axis; ty++){ + entry = sentry; + for(tx = 0; tx < nx_axis; tx++){ + fprintf(fpout, "%7d ", link_table[entry++]); + } + fprintf(fpout, "\n"); + sentry += tbldim; + } +} + diff --git a/libfprint/nbis/mindtct/ridges.c b/libfprint/nbis/mindtct/ridges.c new file mode 100644 index 00000000..8cbfbe7c --- /dev/null +++ b/libfprint/nbis/mindtct/ridges.c @@ -0,0 +1,831 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: RIDGES.C + AUTHOR: Michael D. Garris + DATE: 08/09/1999 + UPDATED: 03/16/2005 by MDG + + Contains routines responsible for locating nearest minutia + neighbors and counting intervening ridges as part of the + NIST Latent Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + count_minutiae_ridges() + count_minutia_ridges() + find_neighbors() + update_nbr_dists() + insert_neighbor() + sort_neighbors() + ridge_count() + find_transition() + validate_ridge_crossing() +***********************************************************************/ + +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: count_minutiae_ridges - Takes a list of minutiae, and for each one, +#cat: determines its closest neighbors and counts the number +#cat: of interveining ridges between the minutia point and +#cat: each of its neighbors. + + Input: + minutiae - list of minutiae + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of minutiae augmented with neighbors and ridge counts + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int count_minutiae_ridges(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + const LFSPARMS *lfsparms) +{ + int ret; + int i; + + print2log("\nFINDING NBRS AND COUNTING RIDGES:\n"); + + /* Sort minutia points on x then y (column-oriented). */ + if((ret = sort_minutiae_x_y(minutiae, iw, ih))){ + return(ret); + } + + /* Remove any duplicate minutia points from the list. */ + if((ret = rm_dup_minutiae(minutiae))){ + return(ret); + } + + /* Foreach remaining sorted minutia in list ... */ + for(i = 0; i < minutiae->num-1; i++){ + /* Located neighbors and count number of ridges in between. */ + /* NOTE: neighbor and ridge count results are stored in */ + /* minutiae->list[i]. */ + if((ret = count_minutia_ridges(i, minutiae, bdata, iw, ih, lfsparms))){ + return(ret); + } + } + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: count_minutia_ridges - Takes a minutia, and determines its closest +#cat: neighbors and counts the number of interveining ridges +#cat: between the minutia point and each of its neighbors. + + Input: + minutia - input minutia + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - minutia augmented with neighbors and ridge counts + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int count_minutia_ridges(const int first, MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + const LFSPARMS *lfsparms) +{ + int i, ret, *nbr_list, *nbr_nridges, nnbrs; + + /* Find up to the maximum number of qualifying neighbors. */ + if((ret = find_neighbors(&nbr_list, &nnbrs, lfsparms->max_nbrs, + first, minutiae))){ + free(nbr_list); + return(ret); + } + + print2log("NBRS FOUND: %d,%d = %d\n", minutiae->list[first]->x, + minutiae->list[first]->y, nnbrs); + + /* If no neighors found ... */ + if(nnbrs == 0){ + /* Then no list returned and no ridges to count. */ + return(0); + } + + /* Sort neighbors on delta dirs. */ + if((ret = sort_neighbors(nbr_list, nnbrs, first, minutiae))){ + free(nbr_list); + return(ret); + } + + /* Count ridges between first and neighbors. */ + /* List of ridge counts, one for each neighbor stored. */ + nbr_nridges = (int *)malloc(nnbrs * sizeof(int)); + if(nbr_nridges == (int *)NULL){ + free(nbr_list); + fprintf(stderr, "ERROR : count_minutia_ridges : malloc : nbr_nridges\n"); + return(-450); + } + + /* Foreach neighbor found and sorted in list ... */ + for(i = 0; i < nnbrs; i++){ + /* Count the ridges between the primary minutia and the neighbor. */ + ret = ridge_count(first, nbr_list[i], minutiae, bdata, iw, ih, lfsparms); + /* If system error ... */ + if(ret < 0){ + /* Deallocate working memories. */ + free(nbr_list); + free(nbr_nridges); + /* Return error code. */ + return(ret); + } + + /* Otherwise, ridge count successful, so store ridge count to list. */ + nbr_nridges[i] = ret; + } + + /* Assign neighbor indices and ridge counts to primary minutia. */ + minutiae->list[first]->nbrs = nbr_list; + minutiae->list[first]->ridge_counts = nbr_nridges; + minutiae->list[first]->num_nbrs = nnbrs; + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: find_neighbors - Takes a primary minutia and a list of all minutiae +#cat: and locates a specified maximum number of closest neighbors +#cat: to the primary point. Neighbors are searched, starting +#cat: in the same pixel column, below, the primary point and then +#cat: along consecutive and complete pixel columns in the image +#cat: to the right of the primary point. + + Input: + max_nbrs - maximum number of closest neighbors to be returned + first - index of the primary minutia point + minutiae - list of minutiae + Output: + onbr_list - points to list of detected closest neighbors + onnbrs - points to number of neighbors returned + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int find_neighbors(int **onbr_list, int *onnbrs, const int max_nbrs, + const int first, MINUTIAE *minutiae) +{ + int ret, second, last_nbr; + MINUTIA *minutia1, *minutia2; + int *nbr_list, nnbrs; + double *nbr_sqr_dists, xdist, xdist2; + + /* Allocate list of neighbor minutiae indices. */ + nbr_list = (int *)malloc(max_nbrs * sizeof(int)); + if(nbr_list == (int *)NULL){ + fprintf(stderr, "ERROR : find_neighbors : malloc : nbr_list\n"); + return(-460); + } + + /* Allocate list of squared euclidean distances between neighbors */ + /* and current primary minutia point. */ + nbr_sqr_dists = (double *)malloc(max_nbrs * sizeof(double)); + if(nbr_sqr_dists == (double *)NULL){ + free(nbr_list); + fprintf(stderr, + "ERROR : find_neighbors : malloc : nbr_sqr_dists\n"); + return(-461); + } + + /* Initialize number of stored neighbors to 0. */ + nnbrs = 0; + /* Assign secondary to one passed current primary minutia. */ + second = first + 1; + /* Compute location of maximum last stored neighbor. */ + last_nbr = max_nbrs - 1; + + /* While minutia (in sorted order) still remian for processing ... */ + /* NOTE: The minutia in the input list have been sorted on X and */ + /* then on Y. So, the neighbors are selected according to those */ + /* that lie below the primary minutia in the same pixel column and */ + /* then subsequently those that lie in complete pixel columns to */ + /* the right of the primary minutia. */ + while(second < minutiae->num){ + /* Assign temporary minutia pointers. */ + minutia1 = minutiae->list[first]; + minutia2 = minutiae->list[second]; + + /* Compute squared distance between minutiae along x-axis. */ + xdist = minutia2->x - minutia1->x; + xdist2 = xdist * xdist; + + /* If the neighbor lists are not full OR the x-distance to current */ + /* secondary is smaller than maximum neighbor distance stored ... */ + if((nnbrs < max_nbrs) || + (xdist2 < nbr_sqr_dists[last_nbr])){ + /* Append or insert the new neighbor into the neighbor lists. */ + if((ret = update_nbr_dists(nbr_list, nbr_sqr_dists, &nnbrs, max_nbrs, + first, second, minutiae))){ + free(nbr_sqr_dists); + return(ret); + } + } + /* Otherwise, if the neighbor lists is full AND the x-distance */ + /* to current secondary is larger than maximum neighbor distance */ + /* stored ... */ + else + /* So, stop searching for more neighbors. */ + break; + + /* Bump to next secondary minutia. */ + second++; + } + + /* Deallocate working memory. */ + free(nbr_sqr_dists); + + /* If no neighbors found ... */ + if(nnbrs == 0){ + /* Deallocate the neighbor list. */ + free(nbr_list); + *onnbrs = 0; + } + /* Otherwise, assign neighbors to output pointer. */ + else{ + *onbr_list = nbr_list; + *onnbrs = nnbrs; + } + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: update_nbr_dists - Takes the current list of neighbors along with a +#cat: primary minutia and a potential new neighbor, and +#cat: determines if the new neighbor is sufficiently close +#cat: to be added to the list of nearest neighbors. If added, +#cat: it is placed in the list in its proper order based on +#cat: squared distance to the primary point. + + Input: + nbr_list - current list of nearest neighbor minutia indices + nbr_sqr_dists - corresponding squared euclidean distance of each + neighbor to the primary minutia point + nnbrs - number of neighbors currently in the list + max_nbrs - maximum number of closest neighbors to be returned + first - index of the primary minutia point + second - index of the secondary (new neighbor) point + minutiae - list of minutiae + Output: + nbr_list - updated list of nearest neighbor indices + nbr_sqr_dists - updated list of nearest neighbor distances + nnbrs - number of neighbors in the update lists + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int update_nbr_dists(int *nbr_list, double *nbr_sqr_dists, + int *nnbrs, const int max_nbrs, + const int first, const int second, MINUTIAE *minutiae) +{ + double dist2; + MINUTIA *minutia1, *minutia2; + int pos, last_nbr; + + /* Compute position of maximum last neighbor stored. */ + last_nbr = max_nbrs - 1; + + /* Assigne temporary minutia pointers. */ + minutia1 = minutiae->list[first]; + minutia2 = minutiae->list[second]; + + /* Compute squared euclidean distance between minutia pair. */ + dist2 = squared_distance(minutia1->x, minutia1->y, + minutia2->x, minutia2->y); + + /* If maximum number of neighbors not yet stored in lists OR */ + /* if the squared distance to current secondary is less */ + /* than the largest stored neighbor distance ... */ + if((*nnbrs < max_nbrs) || + (dist2 < nbr_sqr_dists[last_nbr])){ + + /* Find insertion point in neighbor lists. */ + pos = find_incr_position_dbl(dist2, nbr_sqr_dists, *nnbrs); + /* If the position returned is >= maximum list length (this should */ + /* never happen, but just in case) ... */ + if(pos >= max_nbrs){ + fprintf(stderr, + "ERROR : update_nbr_dists : illegal position for new neighbor\n"); + return(-470); + } + /* Insert the new neighbor into the neighbor lists at the */ + /* specified location. */ + if(insert_neighbor(pos, second, dist2, + nbr_list, nbr_sqr_dists, nnbrs, max_nbrs)) + return(-471); + + /* Otherwise, neighbor inserted successfully, so return normally. */ + return(0); + } + /* Otherwise, the new neighbor is not sufficiently close to be */ + /* added or inserted into the neighbor lists, so ignore the neighbor */ + /* and return normally. */ + else + return(0); + +} + +/************************************************************************* +************************************************************************** +#cat: insert_neighbor - Takes a minutia index and its squared distance to a +#cat: primary minutia point, and inserts them in the specified +#cat: position of their respective lists, shifting previously +#cat: stored values down and off the lists as necessary. + + Input: + pos - postions where values are to be inserted in lists + nbr_index - index of minutia being inserted + nbr_dist2 - squared distance of minutia to its primary point + nbr_list - current list of nearest neighbor minutia indices + nbr_sqr_dists - corresponding squared euclidean distance of each + neighbor to the primary minutia point + nnbrs - number of neighbors currently in the list + max_nbrs - maximum number of closest neighbors to be returned + Output: + nbr_list - updated list of nearest neighbor indices + nbr_sqr_dists - updated list of nearest neighbor distances + nnbrs - number of neighbors in the update lists + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int insert_neighbor(const int pos, const int nbr_index, const double nbr_dist2, + int *nbr_list, double *nbr_sqr_dists, + int *nnbrs, const int max_nbrs) +{ + int i; + + /* If the desired insertion position is beyond one passed the last */ + /* neighbor in the lists OR greater than equal to the maximum ... */ + /* NOTE: pos is zero-oriented while nnbrs and max_nbrs are 1-oriented. */ + if((pos > *nnbrs) || + (pos >= max_nbrs)){ + fprintf(stderr, + "ERROR : insert_neighbor : insertion point exceeds lists\n"); + return(-480); + } + + /* If the neighbor lists are NOT full ... */ + if(*nnbrs < max_nbrs){ + /* Then we have room to shift everything down to make room for new */ + /* neighbor and increase the number of neighbors stored by 1. */ + i = *nnbrs-1; + (*nnbrs)++; + } + /* Otherwise, the neighbors lists are full ... */ + else if(*nnbrs == max_nbrs) + /* So, we must bump the last neighbor in the lists off to make */ + /* room for the new neighbor (ignore last neighbor in lists). */ + i = *nnbrs-2; + /* Otherwise, there is a list overflow error condition */ + /* (shouldn't ever happen, but just in case) ... */ + else{ + fprintf(stderr, + "ERROR : insert_neighbor : overflow in neighbor lists\n"); + return(-481); + } + + /* While we havn't reached the desired insertion point ... */ + while(i >= pos){ + /* Shift the current neighbor down the list 1 positon. */ + nbr_list[i+1] = nbr_list[i]; + nbr_sqr_dists[i+1] = nbr_sqr_dists[i]; + i--; + } + + /* We are now ready to put our new neighbor in the position where */ + /* we shifted everything down from to make room. */ + nbr_list[pos] = nbr_index; + nbr_sqr_dists[pos] = nbr_dist2; + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: sort_neighbors - Takes a list of primary minutia and its neighboring +#cat: minutia indices and sorts the neighbors based on their +#cat: position relative to the primary minutia point. Neighbors +#cat: are sorted starting vertical to the primary point and +#cat: proceeding clockwise. + + Input: + nbr_list - list of neighboring minutia indices + nnbrs - number of neighbors in the list + first - the index of the primary minutia point + minutiae - list of minutiae + Output: + nbr_list - neighboring minutia indices in sorted order + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int sort_neighbors(int *nbr_list, const int nnbrs, const int first, + MINUTIAE *minutiae) +{ + double *join_thetas, theta; + int i; + static double pi2 = M_PI*2.0; + + /* List of angles of lines joining the current primary to each */ + /* of the secondary neighbors. */ + join_thetas = (double *)malloc(nnbrs * sizeof(double)); + if(join_thetas == (double *)NULL){ + fprintf(stderr, "ERROR : sort_neighbors : malloc : join_thetas\n"); + return(-490); + } + + for(i = 0; i < nnbrs; i++){ + /* Compute angle to line connecting the 2 points. */ + /* Coordinates are swapped and order of points reversed to */ + /* account for 0 direction is vertical and positive direction */ + /* is clockwise. */ + theta = angle2line(minutiae->list[nbr_list[i]]->y, + minutiae->list[nbr_list[i]]->x, + minutiae->list[first]->y, + minutiae->list[first]->x); + + /* Make sure the angle is positive. */ + theta += pi2; + theta = fmod(theta, pi2); + join_thetas[i] = theta; + } + + /* Sort the neighbor indicies into rank order. */ + bubble_sort_double_inc_2(join_thetas, nbr_list, nnbrs); + + /* Deallocate the list of angles. */ + free(join_thetas); + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: ridge_count - Takes a pair of minutiae, and counts the number of +#cat: ridges crossed along the linear trajectory connecting +#cat: the 2 points in the image. + + Input: + first - index of primary minutia + second - index of secondary (neighbor) minutia + minutiae - list of minutiae + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + lfsparms - parameters and thresholds for controlling LFS + Return Code: + Zero or Positive - number of ridges counted + Negative - system error +**************************************************************************/ +int ridge_count(const int first, const int second, MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + const LFSPARMS *lfsparms) +{ + MINUTIA *minutia1, *minutia2; + int i, ret, found; + int *xlist, *ylist, num; + int ridge_count, ridge_start, ridge_end; + int prevpix, curpix; + + minutia1 = minutiae->list[first]; + minutia2 = minutiae->list[second]; + + /* If the 2 mintuia have identical pixel coords ... */ + if((minutia1->x == minutia2->x) && + (minutia1->y == minutia2->y)) + /* Then zero ridges between points. */ + return(0); + + /* Compute linear trajectory of contiguous pixels between first */ + /* and second minutia points. */ + if((ret = line_points(&xlist, &ylist, &num, + minutia1->x, minutia1->y, minutia2->x, minutia2->y))){ + return(ret); + } + + /* It there are no points on the line trajectory, then no ridges */ + /* to count (this should not happen, but just in case) ... */ + if(num == 0){ + free(xlist); + free(ylist); + return(0); + } + + /* Find first pixel opposite type along linear trajectory from */ + /* first minutia. */ + prevpix = *(bdata+(ylist[0]*iw)+xlist[0]); + i = 1; + found = FALSE; + while(i < num){ + curpix = *(bdata+(ylist[i]*iw)+xlist[i]); + if(curpix != prevpix){ + found = TRUE; + break; + } + i++; + } + + /* If opposite pixel not found ... then no ridges to count */ + if(!found){ + free(xlist); + free(ylist); + return(0); + } + + /* Ready to count ridges, so initialize counter to 0. */ + ridge_count = 0; + + print2log("RIDGE COUNT: %d,%d to %d,%d ", minutia1->x, minutia1->y, + minutia2->x, minutia2->y); + + /* While not at the end of the trajectory ... */ + while(i < num){ + /* If 0-to-1 transition not found ... */ + if(!find_transition(&i, 0, 1, xlist, ylist, num, bdata, iw, ih)){ + /* Then we are done looking for ridges. */ + free(xlist); + free(ylist); + + print2log("\n"); + + /* Return number of ridges counted to this point. */ + return(ridge_count); + } + /* Otherwise, we found a new ridge start transition, so store */ + /* its location (the location of the 1 in 0-to-1 transition). */ + ridge_start = i; + + print2log(": RS %d,%d ", xlist[i], ylist[i]); + + /* If 1-to-0 transition not found ... */ + if(!find_transition(&i, 1, 0, xlist, ylist, num, bdata, iw, ih)){ + /* Then we are done looking for ridges. */ + free(xlist); + free(ylist); + + print2log("\n"); + + /* Return number of ridges counted to this point. */ + return(ridge_count); + } + /* Otherwise, we found a new ridge end transition, so store */ + /* its location (the location of the 0 in 1-to-0 transition). */ + ridge_end = i; + + print2log("; RE %d,%d ", xlist[i], ylist[i]); + + /* Conduct the validation, tracing the contour of the ridge */ + /* from the ridge ending point a specified number of steps */ + /* scanning for neighbors clockwise and counter-clockwise. */ + /* If the ridge starting point is encounted during the trace */ + /* then we can assume we do not have a valid ridge crossing */ + /* and instead we are walking on and off the edge of the */ + /* side of a ridge. */ + ret = validate_ridge_crossing(ridge_start, ridge_end, + xlist, ylist, num, bdata, iw, ih, + lfsparms->max_ridge_steps); + + /* If system error ... */ + if(ret < 0){ + free(xlist); + free(ylist); + /* Return the error code. */ + return(ret); + } + + print2log("; V%d ", ret); + + /* If validation result is TRUE ... */ + if(ret){ + /* Then assume we have found a valid ridge crossing and bump */ + /* the ridge counter. */ + ridge_count++; + } + + /* Otherwise, ignore the current ridge start and end transitions */ + /* and go back and search for new ridge start. */ + } + + /* Deallocate working memories. */ + free(xlist); + free(ylist); + + print2log("\n"); + + /* Return the number of ridges counted. */ + return(ridge_count); +} + +/************************************************************************* +************************************************************************** +#cat: find_transition - Takes a pixel trajectory and a starting index, and +#cat: searches forward along the trajectory until the specified +#cat: adjacent pixel pair is found, returning the index where +#cat: the pair was found (the index of the second pixel). + + Input: + iptr - pointer to starting pixel index into trajectory + pix1 - first pixel value in transition pair + pix2 - second pixel value in transition pair + xlist - x-pixel coords of line trajectory + ylist - y-pixel coords of line trajectory + num - number of coords in line trajectory + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + iptr - points to location where 2nd pixel in pair is found + Return Code: + TRUE - pixel pair transition found + FALSE - pixel pair transition not found +**************************************************************************/ +int find_transition(int *iptr, const int pix1, const int pix2, + const int *xlist, const int *ylist, const int num, + unsigned char *bdata, const int iw, const int ih) +{ + int i, j; + + /* Set previous index to starting position. */ + i = *iptr; + /* Bump previous index by 1 to get next index. */ + j = i+1; + + /* While not one point from the end of the trajectory .. */ + while(i < num-1){ + /* If we have found the desired transition ... */ + if((*(bdata+(ylist[i]*iw)+xlist[i]) == pix1) && + (*(bdata+(ylist[j]*iw)+xlist[j]) == pix2)){ + /* Adjust the position pointer to the location of the */ + /* second pixel in the transition. */ + *iptr = j; + + /* Return TRUE. */ + return(TRUE); + } + /* Otherwise, the desired transition was not found in current */ + /* pixel pair, so bump to the next pair along the trajector. */ + i++; + j++; + } + + /* If we get here, then we exhausted the trajector without finding */ + /* the desired transition, so set the position pointer to the end */ + /* of the trajector, and return FALSE. */ + *iptr = num; + return(FALSE); +} + +/************************************************************************* +************************************************************************** +#cat: validate_ridge_crossing - Takes a pair of points, a ridge start +#cat: transition and a ridge end transition, and walks the +#cat: ridge contour from thre ridge end points a specified +#cat: number of steps, looking for the ridge start point. +#cat: If found, then transitions determined not to be a valid +#cat: ridge crossing. + + Input: + ridge_start - index into line trajectory of ridge start transition + ridge_end - index into line trajectory of ridge end transition + xlist - x-pixel coords of line trajectory + ylist - y-pixel coords of line trajectory + num - number of coords in line trajectory + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + max_ridge_steps - number of steps taken in search in both + scan directions + Return Code: + TRUE - ridge crossing VALID + FALSE - ridge corssing INVALID + Negative - system error +**************************************************************************/ +int validate_ridge_crossing(const int ridge_start, const int ridge_end, + const int *xlist, const int *ylist, const int num, + unsigned char *bdata, const int iw, const int ih, + const int max_ridge_steps) +{ + int ret; + int feat_x, feat_y, edge_x, edge_y; + int *contour_x, *contour_y, *contour_ex, *contour_ey, ncontour; + + /* Assign edge pixel pair for contour trace. */ + feat_x = xlist[ridge_end]; + feat_y = ylist[ridge_end]; + edge_x = xlist[ridge_end-1]; + edge_y = ylist[ridge_end-1]; + + /* Adjust pixel pair if they neighbor each other diagonally. */ + fix_edge_pixel_pair(&feat_x, &feat_y, &edge_x, &edge_y, + bdata, iw, ih); + + /* Trace ridge contour, starting at the ridge end transition, and */ + /* taking a specified number of step scanning for edge neighbors */ + /* clockwise. As we trace the ridge, we want to detect if we */ + /* encounter the ridge start transition. NOTE: The ridge end */ + /* position is on the white (of a black to white transition) and */ + /* the ridge start is on the black (of a black to white trans), */ + /* so the edge trace needs to look for the what pixel (not the */ + /* black one) of the ridge start transition. */ + ret = trace_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, + max_ridge_steps, + xlist[ridge_start-1], ylist[ridge_start-1], + feat_x, feat_y, edge_x, edge_y, + SCAN_CLOCKWISE, bdata, iw, ih); + /* If a system error occurred ... */ + if(ret < 0) + /* Return error code. */ + return(ret); + + /* Otherwise, if the trace was not IGNORED, then a contour was */ + /* was generated and returned. We aren't interested in the */ + /* actual contour, so deallocate it. */ + if(ret != IGNORE) + free_contour(contour_x, contour_y, contour_ex, contour_ey); + + /* If the trace was IGNORED, then we had some sort of initialization */ + /* problem, so treat this the same as if was actually located the */ + /* ridge start point (in which case LOOP_FOUND is returned). */ + /* So, If not IGNORED and ridge start not encounted in trace ... */ + if((ret != IGNORE) && + (ret != LOOP_FOUND)){ + + /* Now conduct contour trace scanning for edge neighbors counter- */ + /* clockwise. */ + ret = trace_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, + max_ridge_steps, + xlist[ridge_start-1], ylist[ridge_start-1], + feat_x, feat_y, edge_x, edge_y, + SCAN_COUNTER_CLOCKWISE, bdata, iw, ih); + /* If a system error occurred ... */ + if(ret < 0) + /* Return error code. */ + return(ret); + + /* Otherwise, if the trace was not IGNORED, then a contour was */ + /* was generated and returned. We aren't interested in the */ + /* actual contour, so deallocate it. */ + if(ret != IGNORE) + free_contour(contour_x, contour_y, contour_ex, contour_ey); + + /* If trace not IGNORED and ridge start not encounted in 2nd trace ... */ + if((ret != IGNORE) && + (ret != LOOP_FOUND)){ + /* If we get here, assume we have a ridge crossing. */ + return(TRUE); + } + /* Otherwise, second trace returned IGNORE or ridge start found. */ + } + /* Otherwise, first trace returned IGNORE or ridge start found. */ + + /* If we get here, then we failed to validate a ridge crossing. */ + return(FALSE); +} diff --git a/libfprint/nbis/mindtct/shape.c b/libfprint/nbis/mindtct/shape.c new file mode 100644 index 00000000..23ba16ca --- /dev/null +++ b/libfprint/nbis/mindtct/shape.c @@ -0,0 +1,304 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: SHAPE.C + AUTHOR: Michael D. Garris + DATE: 05/11/1999 + UPDATED: 03/16/2005 by MDG + + Contains routines responsible for creating and manipulating + shape stuctures as part of the NIST Latent Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + alloc_shape() + free_shape() + dump_shape() + shape_from_contour() + sort_row_on_x() +***********************************************************************/ + +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: alloc_shape - Allocates and initializes a shape structure given the +#cat: the X and Y limits of the shape. + + Input: + xmin - left-most x-coord in shape + ymin - top-most y-coord in shape + xmax - right-most x-coord in shape + ymax - bottom-most y-coord in shape + Output: + oshape - pointer to the allocated & initialized shape structure + Return Code: + Zero - Shape successfully allocated and initialized + Negative - System error +**************************************************************************/ +int alloc_shape(SHAPE **oshape, const int xmin, const int ymin, + const int xmax, const int ymax) +{ + SHAPE *shape; + int alloc_rows, alloc_pts; + int i, j, y; + + /* Compute allocation parameters. */ + /* First, compute the number of scanlines spanned by the shape. */ + alloc_rows = ymax - ymin + 1; + /* Second, compute the "maximum" number of contour points possible */ + /* on a row. Here we are allocating the maximum number of contiguous */ + /* pixels on each row which will be sufficiently larger than the */ + /* number of actual contour points. */ + alloc_pts = xmax - xmin + 1; + + /* Allocate the shape structure. */ + shape = (SHAPE *)malloc(sizeof(SHAPE)); + /* If there is an allocation error... */ + if(shape == (SHAPE *)NULL){ + fprintf(stderr, "ERROR : alloc_shape : malloc : shape\n"); + return(-250); + } + + /* Allocate the list of row pointers. We now this number will fit */ + /* the shape exactly. */ + shape->rows = (ROW **)malloc(alloc_rows * sizeof(ROW *)); + /* If there is an allocation error... */ + if(shape->rows == (ROW **)NULL){ + /* Deallocate memory alloated by this routine to this point. */ + free(shape); + fprintf(stderr, "ERROR : alloc_shape : malloc : shape->rows\n"); + return(-251); + } + + /* Initialize the shape structure's attributes. */ + shape->ymin = ymin; + shape->ymax = ymax; + /* The number of allocated rows will be exactly the number of */ + /* assigned rows for the shape. */ + shape->alloc = alloc_rows; + shape->nrows = alloc_rows; + + /* Foreach row in the shape... */ + for(i = 0, y = ymin; i < alloc_rows; i++, y++){ + /* Allocate a row structure and store it in its respective position */ + /* in the shape structure's list of row pointers. */ + shape->rows[i] = (ROW *)malloc(sizeof(ROW)); + /* If there is an allocation error... */ + if(shape->rows[i] == (ROW *)NULL){ + /* Deallocate memory alloated by this routine to this point. */ + for(j = 0; j < i; j++){ + free(shape->rows[j]->xs); + free(shape->rows[j]); + } + free(shape->rows); + free(shape); + fprintf(stderr, "ERROR : alloc_shape : malloc : shape->rows[i]\n"); + return(-252); + } + + /* Allocate the current rows list of x-coords. */ + shape->rows[i]->xs = (int *)malloc(alloc_pts * sizeof(int)); + /* If there is an allocation error... */ + if(shape->rows[i]->xs == (int *)NULL){ + /* Deallocate memory alloated by this routine to this point. */ + for(j = 0; j < i; j++){ + free(shape->rows[j]->xs); + free(shape->rows[j]); + } + free(shape->rows[i]); + free(shape->rows); + free(shape); + fprintf(stderr, + "ERROR : alloc_shape : malloc : shape->rows[i]->xs\n"); + return(-253); + } + + /* Initialize the current row structure's attributes. */ + shape->rows[i]->y = y; + shape->rows[i]->alloc = alloc_pts; + /* There are initially ZERO points assigned to the row. */ + shape->rows[i]->npts = 0; + } + + /* Assign structure to output pointer. */ + *oshape = shape; + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: free_shape - Deallocates a shape structure and all its allocated +#cat: attributes. + + Input: + shape - pointer to the shape structure to be deallocated +**************************************************************************/ +void free_shape(SHAPE *shape) +{ + int i; + + /* Foreach allocated row in the shape ... */ + for(i = 0; i < shape->alloc; i++){ + /* Deallocate the current row's list of x-coords. */ + free(shape->rows[i]->xs); + /* Deallocate the current row structure. */ + free(shape->rows[i]); + } + + /* Deallocate the list of row pointers. */ + free(shape->rows); + /* Deallocate the shape structure. */ + free(shape); +} + +/************************************************************************* +************************************************************************** +#cat: dump_shape - Takes an initialized shape structure and dumps its contents +#cat: as formatted text to the specified open file pointer. + + Input: + shape - shape structure to be dumped + Output: + fpout - open file pointer to be written to +**************************************************************************/ +void dump_shape(FILE *fpout, const SHAPE *shape) +{ + int i, j; + + /* Print the shape's y-limits and number of scanlines. */ + fprintf(fpout, "shape: ymin=%d, ymax=%d, nrows=%d\n", + shape->ymin, shape->ymax, shape->nrows); + + /* Foreach row in the shape... */ + for(i = 0; i < shape->nrows; i++){ + /* Print the current row's y-coord and number of points on the row. */ + fprintf(fpout, "row %d : y=%d, npts=%d\n", i, shape->rows[i]->y, + shape->rows[i]->npts); + /* Print each successive point on the current row. */ + for(j = 0; j < shape->rows[i]->npts; j++){ + fprintf(fpout, "pt %d : %d %d\n", j, shape->rows[i]->xs[j], + shape->rows[i]->y); + } + } +} + +/************************************************************************* +************************************************************************** +#cat: shape_from_contour - Converts a contour list that has been determined +#cat: to form a complete loop into a shape representation where +#cat: the contour points on each contiguous scanline of the shape +#cat: are stored in left-to-right order. + + Input: + contour_x - x-coord list for loop's contour points + contour_y - y-coord list for loop's contour points + ncontour - number of points in contour + Output: + oshape - points to the resulting shape structure + Return Code: + Zero - shape successfully derived + Negative - system error +**************************************************************************/ +int shape_from_contour(SHAPE **oshape, const int *contour_x, + const int *contour_y, const int ncontour) +{ + SHAPE *shape; + ROW *row; + int ret, i, xmin, ymin, xmax, ymax; + + /* Find xmin, ymin, xmax, ymax on contour. */ + contour_limits(&xmin, &ymin, &xmax, &ymax, + contour_x, contour_y, ncontour); + + /* Allocate and initialize a shape structure. */ + if((ret = alloc_shape(&shape, xmin, ymin, xmax, ymax))) + /* If system error, then return error code. */ + return(ret); + + /* Foreach point on contour ... */ + for(i = 0; i < ncontour; i++){ + /* Add point to corresponding row. */ + /* First set a pointer to the current row. We need to subtract */ + /* ymin because the rows are indexed relative to the top-most */ + /* scanline in the shape. */ + row = shape->rows[contour_y[i]-ymin]; + + /* It is possible with complex shapes to reencounter points */ + /* already visited on a contour, especially at "pinching" points */ + /* along the contour. So we need to test to see if a point has */ + /* already been stored in the row. If not in row list already ... */ + if(in_int_list(contour_x[i], row->xs, row->npts) < 0){ + /* If row is full ... */ + if(row->npts >= row->alloc){ + /* This should never happen becuase we have allocated */ + /* based on shape bounding limits. */ + fprintf(stderr, + "ERROR : shape_from_contour : row overflow\n"); + return(-260); + } + /* Assign the x-coord of the current contour point to the row */ + /* and bump the row's point counter. All the contour points */ + /* on the same row share the same y-coord. */ + row->xs[row->npts++] = contour_x[i]; + } + /* Otherwise, point is already stored in row, so ignore. */ + } + + /* Foreach row in the shape. */ + for(i = 0; i < shape->nrows; i++) + /* Sort row points increasing on their x-coord. */ + sort_row_on_x(shape->rows[i]); + + /* Assign shape structure to output pointer. */ + *oshape = shape; + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: sort_row_on_x - Takes a row structure and sorts its points left-to- +#cat: right on X. + + Input: + row - row structure to be sorted + Output: + row - row structure with points in sorted order +**************************************************************************/ +void sort_row_on_x(ROW *row) +{ + /* Conduct a simple increasing bubble sort on the x-coords */ + /* in the given row. A bubble sort is satisfactory as the */ + /* number of points will be relatively small. */ + bubble_sort_int_inc(row->xs, row->npts); +} + diff --git a/libfprint/nbis/mindtct/sort.c b/libfprint/nbis/mindtct/sort.c new file mode 100644 index 00000000..3a0f47c9 --- /dev/null +++ b/libfprint/nbis/mindtct/sort.c @@ -0,0 +1,320 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: SORT.C + AUTHOR: Michael D. Garris + DATE: 03/16/1999 + UPDATED: 03/16/2005 by MDG + + Contains sorting routines required by the NIST Latent Fingerprint + System (LFS). + +*********************************************************************** + ROUTINES: + sort_indices_int_inc() + sort_indices_double_inc() + bubble_sort_int_inc_2() + bubble_sort_double_inc_2() + bubble_sort_double_dec_2() + bubble_sort_int_inc() +***********************************************************************/ + +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: sort_indices_int_inc - Takes a list of integers and returns a list of +#cat: indices referencing the integer list in increasing order. +#cat: The original list of integers is also returned in sorted +#cat: order. + + Input: + ranks - list of integers to be sorted + num - number of integers in the list + Output: + optr - list of indices referencing the integer list in sorted order + ranks - list of integers in increasing order + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int sort_indices_int_inc(int **optr, int *ranks, const int num) +{ + int *order; + int i; + + /* Allocate list of sequential indices. */ + order = (int *)malloc(num * sizeof(int)); + if(order == (int *)NULL){ + fprintf(stderr, "ERROR : sort_indices_int_inc : malloc : order\n"); + return(-390); + } + /* Initialize list of sequential indices. */ + for(i = 0; i < num; i++) + order[i] = i; + + /* Sort the indecies into rank order. */ + bubble_sort_int_inc_2(ranks, order, num); + + /* Set output pointer to the resulting order of sorted indices. */ + *optr = order; + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: sort_indices_double_inc - Takes a list of doubles and returns a list of +#cat: indices referencing the double list in increasing order. +#cat: The original list of doubles is also returned in sorted +#cat: order. + + Input: + ranks - list of doubles to be sorted + num - number of doubles in the list + Output: + optr - list of indices referencing the double list in sorted order + ranks - list of doubles in increasing order + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int sort_indices_double_inc(int **optr, double *ranks, const int num) +{ + int *order; + int i; + + /* Allocate list of sequential indices. */ + order = (int *)malloc(num * sizeof(int)); + if(order == (int *)NULL){ + fprintf(stderr, "ERROR : sort_indices_double_inc : malloc : order\n"); + return(-400); + } + /* Initialize list of sequential indices. */ + for(i = 0; i < num; i++) + order[i] = i; + + /* Sort the indicies into rank order. */ + bubble_sort_double_inc_2(ranks, order, num); + + /* Set output pointer to the resulting order of sorted indices. */ + *optr = order; + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: bubble_sort_int_inc_2 - Takes a list of integer ranks and a corresponding +#cat: list of integer attributes, and sorts the ranks +#cat: into increasing order moving the attributes +#cat: correspondingly. + + Input: + ranks - list of integers to be sort on + items - list of corresponding integer attributes + len - number of items in list + Output: + ranks - list of integers sorted in increasing order + items - list of attributes in corresponding sorted order +**************************************************************************/ +void bubble_sort_int_inc_2(int *ranks, int *items, const int len) +{ + int done = 0; + int i, p, n, trank, titem; + + /* Set counter to the length of the list being sorted. */ + n = len; + + /* While swaps in order continue to occur from the */ + /* previous iteration... */ + while(!done){ + /* Reset the done flag to TRUE. */ + done = TRUE; + /* Foreach rank in list up to current end index... */ + /* ("p" points to current rank and "i" points to the next rank.) */ + for (i=1, p = 0; i ranks[i]){ + /* Swap ranks. */ + trank = ranks[i]; + ranks[i] = ranks[p]; + ranks[p] = trank; + /* Swap items. */ + titem = items[i]; + items[i] = items[p]; + items[p] = titem; + /* Changes were made, so set done flag to FALSE. */ + done = FALSE; + } + /* Otherwise, rank pair is in order, so continue. */ + } + /* Decrement the ending index. */ + n--; + } +} + +/************************************************************************* +************************************************************************** +#cat: bubble_sort_double_inc_2 - Takes a list of double ranks and a +#cat: corresponding list of integer attributes, and sorts the +#cat: ranks into increasing order moving the attributes +#cat: correspondingly. + + Input: + ranks - list of double to be sort on + items - list of corresponding integer attributes + len - number of items in list + Output: + ranks - list of doubles sorted in increasing order + items - list of attributes in corresponding sorted order +**************************************************************************/ +void bubble_sort_double_inc_2(double *ranks, int *items, const int len) +{ + int done = 0; + int i, p, n, titem; + double trank; + + /* Set counter to the length of the list being sorted. */ + n = len; + + /* While swaps in order continue to occur from the */ + /* previous iteration... */ + while(!done){ + /* Reset the done flag to TRUE. */ + done = TRUE; + /* Foreach rank in list up to current end index... */ + /* ("p" points to current rank and "i" points to the next rank.) */ + for (i=1, p = 0; i ranks[i]){ + /* Swap ranks. */ + trank = ranks[i]; + ranks[i] = ranks[p]; + ranks[p] = trank; + /* Swap items. */ + titem = items[i]; + items[i] = items[p]; + items[p] = titem; + /* Changes were made, so set done flag to FALSE. */ + done = FALSE; + } + /* Otherwise, rank pair is in order, so continue. */ + } + /* Decrement the ending index. */ + n--; + } +} + +/*************************************************************************** +************************************************************************** +#cat: bubble_sort_double_dec_2 - Conducts a simple bubble sort returning a list +#cat: of ranks in decreasing order and their associated items in sorted +#cat: order as well. + + Input: + ranks - list of values to be sorted + items - list of items, each corresponding to a particular rank value + len - length of the lists to be sorted + Output: + ranks - list of values sorted in descending order + items - list of items in the corresponding sorted order of the ranks. + If these items are indices, upon return, they may be used as + indirect addresses reflecting the sorted order of the ranks. +****************************************************************************/ +void bubble_sort_double_dec_2(double *ranks, int *items, const int len) +{ + int done = 0; + int i, p, n, titem; + double trank; + + n = len; + while(!done){ + done = 1; + for (i=1, p = 0;i ranks[i]){ + /* Swap ranks. */ + trank = ranks[i]; + ranks[i] = ranks[p]; + ranks[p] = trank; + /* Changes were made, so set done flag to FALSE. */ + done = FALSE; + } + /* Otherwise, rank pair is in order, so continue. */ + } + /* Decrement the ending index. */ + n--; + } +} + diff --git a/libfprint/nbis/mindtct/util.c b/libfprint/nbis/mindtct/util.c new file mode 100644 index 00000000..a4e98da9 --- /dev/null +++ b/libfprint/nbis/mindtct/util.c @@ -0,0 +1,605 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: UTIL.C + AUTHOR: Michael D. Garris + DATE: 03/16/1999 + + Contains general support routines required by the NIST + Latent Fingerprint System (LFS). + +*********************************************************************** + ROUTINES: + maxv() + minv() + minmaxs() + distance() + squared_distance() + in_int_list() + remove_from_int_list() + find_incr_position_dbl() + angle2line() + line2direction() + closest_dir_dist() +***********************************************************************/ + +#include +#include +#include + +/************************************************************************* +************************************************************************** +#cat: maxv - Determines the maximum value in the given list of integers. +#cat: NOTE, the list is assumed to be NOT empty! + + Input: + list - non-empty list of integers to be searched + num - number of integers in the list + Return Code: + Maximum - maximum value in the list +**************************************************************************/ +int maxv(const int *list, const int num) +{ + int i; + int maxval; + + /* NOTE: The list is assumed to be NOT empty. */ + /* Initialize running maximum to first item in list. */ + maxval = list[0]; + + /* Foreach subsequent item in the list... */ + for(i = 1; i < num; i++){ + /* If current item is larger than running maximum... */ + if(list[i] > maxval) + /* Set running maximum to the larger item. */ + maxval = list[i]; + /* Otherwise, skip to next item. */ + } + + /* Return the resulting maximum. */ + return(maxval); +} + +/************************************************************************* +************************************************************************** +#cat: minv - Determines the minimum value in the given list of integers. +#cat: NOTE, the list is assumed to be NOT empty! + + Input: + list - non-empty list of integers to be searched + num - number of integers in the list + Return Code: + Minimum - minimum value in the list +**************************************************************************/ +int minv(const int *list, const int num) +{ + int i; + int minval; + + /* NOTE: The list is assumed to be NOT empty. */ + /* Initialize running minimum to first item in list. */ + minval = list[0]; + + /* Foreach subsequent item in the list... */ + for(i = 1; i < num; i++){ + /* If current item is smaller than running minimum... */ + if(list[i] < minval) + /* Set running minimum to the smaller item. */ + minval = list[i]; + /* Otherwise, skip to next item. */ + } + + /* Return the resulting minimum. */ + return(minval); +} + +/************************************************************************* +************************************************************************** +#cat: minmaxs - Takes a list of integers and identifies points of relative +#cat: minima and maxima. The midpoint of flat plateaus and valleys +#cat: are selected when they are detected. + + Input: + items - list of integers to be analyzed + num - number of items in the list + Output: + ominmax_val - value of the item at each minima or maxima + ominmax_type - identifies a minima as '-1' and maxima as '1' + ominmax_i - index of item's position in list + ominmax_alloc - number of allocated minima and/or maxima + ominmax_num - number of detected minima and/or maxima + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int minmaxs(int **ominmax_val, int **ominmax_type, int **ominmax_i, + int *ominmax_alloc, int *ominmax_num, + const int *items, const int num) +{ + int i, diff, state, start, loc; + int *minmax_val, *minmax_type, *minmax_i, minmax_alloc, minmax_num; + + + /* Determine maximum length for allocation of buffers. */ + /* If there are fewer than 3 items ... */ + if(num < 3){ + /* Then no min/max is possible, so set allocated length */ + /* to 0 and return. */ + *ominmax_alloc = 0; + *ominmax_num = 0; + return(0); + } + /* Otherwise, set allocation length to number of items - 2 */ + /* (one for the first item in the list, and on for the last). */ + /* Every other intermediate point can potentially represent a */ + /* min or max. */ + minmax_alloc = num - 2; + /* Allocate the buffers. */ + minmax_val = (int *)malloc(minmax_alloc * sizeof(int)); + if(minmax_val == (int *)NULL){ + fprintf(stderr, "ERROR : minmaxs : malloc : minmax_val\n"); + return(-290); + } + minmax_type = (int *)malloc(minmax_alloc * sizeof(int)); + if(minmax_type == (int *)NULL){ + free(minmax_val); + fprintf(stderr, "ERROR : minmaxs : malloc : minmax_type\n"); + return(-291); + } + minmax_i = (int *)malloc(minmax_alloc * sizeof(int)); + if(minmax_i == (int *)NULL){ + free(minmax_val); + free(minmax_type); + fprintf(stderr, "ERROR : minmaxs : malloc : minmax_i\n"); + return(-292); + } + + /* Initialize number of min/max to 0. */ + minmax_num = 0; + + /* Start witht the first item in the list. */ + i = 0; + + /* Get starting state between first pair of items. */ + diff = items[1] - items[0]; + if(diff > 0) + state = 1; + else if (diff < 0) + state = -1; + else + state = 0; + + /* Set start location to first item in list. */ + start = 0; + + /* Bump to next item in list. */ + i++; + + /* While not at the last item in list. */ + while(i < num-1){ + + /* Compute difference between next pair of items. */ + diff = items[i+1] - items[i]; + /* If items are increasing ... */ + if(diff > 0){ + /* If previously increasing ... */ + if(state == 1){ + /* Reset start to current location. */ + start = i; + } + /* If previously decreasing ... */ + else if (state == -1){ + /* Then we have incurred a minima ... */ + /* Compute midpoint of minima. */ + loc = (start + i)/2; + /* Store value at minima midpoint. */ + minmax_val[minmax_num] = items[loc]; + /* Store type code for minima. */ + minmax_type[minmax_num] = -1; + /* Store location of minima midpoint. */ + minmax_i[minmax_num++] = loc; + /* Change state to increasing. */ + state = 1; + /* Reset start location. */ + start = i; + } + /* If previously level (this state only can occur at the */ + /* beginning of the list of items) ... */ + else { + /* If more than one level state in a row ... */ + if(i-start > 1){ + /* Then consider a minima ... */ + /* Compute midpoint of minima. */ + loc = (start + i)/2; + /* Store value at minima midpoint. */ + minmax_val[minmax_num] = items[loc]; + /* Store type code for minima. */ + minmax_type[minmax_num] = -1; + /* Store location of minima midpoint. */ + minmax_i[minmax_num++] = loc; + /* Change state to increasing. */ + state = 1; + /* Reset start location. */ + start = i; + } + /* Otherwise, ignore single level state. */ + else{ + /* Change state to increasing. */ + state = 1; + /* Reset start location. */ + start = i; + } + } + } + /* If items are decreasing ... */ + else if(diff < 0){ + /* If previously decreasing ... */ + if(state == -1){ + /* Reset start to current location. */ + start = i; + } + /* If previously increasing ... */ + else if (state == 1){ + /* Then we have incurred a maxima ... */ + /* Compute midpoint of maxima. */ + loc = (start + i)/2; + /* Store value at maxima midpoint. */ + minmax_val[minmax_num] = items[loc]; + /* Store type code for maxima. */ + minmax_type[minmax_num] = 1; + /* Store location of maxima midpoint. */ + minmax_i[minmax_num++] = loc; + /* Change state to decreasing. */ + state = -1; + /* Reset start location. */ + start = i; + } + /* If previously level (this state only can occur at the */ + /* beginning of the list of items) ... */ + else { + /* If more than one level state in a row ... */ + if(i-start > 1){ + /* Then consider a maxima ... */ + /* Compute midpoint of maxima. */ + loc = (start + i)/2; + /* Store value at maxima midpoint. */ + minmax_val[minmax_num] = items[loc]; + /* Store type code for maxima. */ + minmax_type[minmax_num] = 1; + /* Store location of maxima midpoint. */ + minmax_i[minmax_num++] = loc; + /* Change state to decreasing. */ + state = -1; + /* Reset start location. */ + start = i; + } + /* Otherwise, ignore single level state. */ + else{ + /* Change state to decreasing. */ + state = -1; + /* Reset start location. */ + start = i; + } + } + } + /* Otherwise, items are level, so continue to next item pair. */ + + /* Advance to next item pair in list. */ + i++; + } + + /* Set results to output pointers. */ + *ominmax_val = minmax_val; + *ominmax_type = minmax_type; + *ominmax_i = minmax_i; + *ominmax_alloc = minmax_alloc; + *ominmax_num = minmax_num; + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: distance - Takes two coordinate points and computes the +#cat: Euclidean distance between the two points. + + Input: + x1 - x-coord of first point + y1 - y-coord of first point + x2 - x-coord of second point + y2 - y-coord of second point + Return Code: + Distance - computed Euclidean distance +**************************************************************************/ +double distance(const int x1, const int y1, const int x2, const int y2) +{ + double dx, dy, dist; + + /* Compute delta x between points. */ + dx = (double)(x1 - x2); + /* Compute delta y between points. */ + dy = (double)(y1 - y2); + /* Compute the squared distance between points. */ + dist = (dx*dx) + (dy*dy); + /* Take square root of squared distance. */ + dist = sqrt(dist); + + /* Return the squared distance. */ + return(dist); +} + +/************************************************************************* +************************************************************************** +#cat: squared_distance - Takes two coordinate points and computes the +#cat: squared distance between the two points. + + Input: + x1 - x-coord of first point + y1 - y-coord of first point + x2 - x-coord of second point + y2 - y-coord of second point + Return Code: + Distance - computed squared distance +**************************************************************************/ +double squared_distance(const int x1, const int y1, const int x2, const int y2) +{ + double dx, dy, dist; + + /* Compute delta x between points. */ + dx = (double)(x1 - x2); + /* Compute delta y between points. */ + dy = (double)(y1 - y2); + /* Compute the squared distance between points. */ + dist = (dx*dx) + (dy*dy); + + /* Return the squared distance. */ + return(dist); +} + +/************************************************************************* +************************************************************************** +#cat: in_int_list - Determines if a specified value is store in a list of +#cat: integers and returns its location if found. + + Input: + item - value to search for in list + list - list of integers to be searched + len - number of integers in search list + Return Code: + Zero or greater - first location found equal to search value + Negative - search value not found in the list of integers +**************************************************************************/ +int in_int_list(const int item, const int *list, const int len) +{ + int i; + + /* Foreach item in list ... */ + for(i = 0; i < len; i++){ + /* If search item found in list ... */ + if(list[i] == item) + /* Return the location in list where found. */ + return(i); + } + + /* If we get here, then search item not found in list, */ + /* so return -1 ==> NOT FOUND. */ + return(-1); +} + +/************************************************************************* +************************************************************************** +#cat: remove_from_int_list - Takes a position index into an integer list and +#cat: removes the value from the list, collapsing the resulting +#cat: list. + + Input: + index - position of value to be removed from list + list - input list of integers + num - number of integers in the list + Output: + list - list with specified integer removed + num - decremented number of integers in list + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int remove_from_int_list(const int index, int *list, const int num) +{ + int fr, to; + + /* Make sure the requested index is within range. */ + if((index < 0) && (index >= num)){ + fprintf(stderr, "ERROR : remove_from_int_list : index out of range\n"); + return(-370); + } + + /* Slide the remaining list of integers up over top of the */ + /* position of the integer being removed. */ + for(to = index, fr = index+1; fr < num; to++, fr++) + list[to] = list[fr]; + + /* NOTE: Decrementing the number of integers remaining in the list is */ + /* the responsibility of the caller! */ + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: ind_incr_position_dbl - Takes a double value and a list of doubles and +#cat: determines where in the list the double may be inserted, +#cat: preserving the increasing sorted order of the list. + + Input: + val - value to be inserted into the list + list - list of double in increasing sorted order + num - number of values in the list + Return Code: + Zero or Positive - insertion position in the list +**************************************************************************/ +int find_incr_position_dbl(const double val, double *list, const int num) +{ + int i; + + /* Foreach item in double list ... */ + for(i = 0; i < num; i++){ + /* If the value is smaller than the current item in list ... */ + if(val < list[i]) + /* Then we found were to insert the value in the list maintaining */ + /* an increasing sorted order. */ + return(i); + + /* Otherwise, the value is still larger than current item, so */ + /* continue to next item in the list. */ + } + + /* Otherwise, we never found a slot within the list to insert the */ + /* the value, so place at the end of the sorted list. */ + return(i); +} + +/************************************************************************* +************************************************************************** +#cat: angle2line - Takes two coordinate points and computes the angle +#cat: to the line formed by the two points. + + Input: + fx - x-coord of first point + fy - y-coord of first point + tx - x-coord of second point + ty - y-coord of second point + Return Code: + Angle - angle to the specified line +**************************************************************************/ +double angle2line(const int fx, const int fy, const int tx, const int ty) +{ + double dx, dy, theta; + + /* Compute slope of line connecting the 2 specified points. */ + dy = (double)(fy - ty); + dx = (double)(tx - fx); + /* If delta's are sufficiently small ... */ + if((fabs(dx) < MIN_SLOPE_DELTA) && (fabs(dy) < MIN_SLOPE_DELTA)) + theta = 0.0; + /* Otherwise, compute angle to the line. */ + else + theta = atan2(dy, dx); + + /* Return the compute angle in radians. */ + return(theta); +} + +/************************************************************************* +************************************************************************** +#cat: line2direction - Takes two coordinate points and computes the +#cat: directon (on a full circle) in which the first points +#cat: to the second. + + Input: + fx - x-coord of first point (pointing from) + fy - y-coord of first point (pointing from) + tx - x-coord of second point (pointing to) + ty - y-coord of second point (pointing to) + ndirs - number of IMAP directions (in semicircle) + Return Code: + Direction - determined direction on a "full" circle +**************************************************************************/ +int line2direction(const int fx, const int fy, + const int tx, const int ty, const int ndirs) +{ + double theta, pi_factor; + int idir, full_ndirs; + static double pi2 = M_PI*2.0; + + /* Compute angle to line connecting the 2 points. */ + /* Coordinates are swapped and order of points reversed to */ + /* account for 0 direction is vertical and positive direction */ + /* is clockwise. */ + theta = angle2line(ty, tx, fy, fx); + + /* Make sure the angle is positive. */ + theta += pi2; + theta = fmod(theta, pi2); + /* Convert from radians to integer direction on range [0..(ndirsX2)]. */ + /* Multiply radians by units/radian ((ndirsX2)/(2PI)), and you get */ + /* angle in integer units. */ + /* Compute number of directions on full circle. */ + full_ndirs = ndirs<<1; + /* Compute the radians to integer direction conversion factor. */ + pi_factor = (double)full_ndirs/pi2; + /* Convert radian angle to integer direction on full circle. */ + theta *= pi_factor; + /* Need to truncate precision so that answers are consistent */ + /* on different computer architectures when rounding doubles. */ + theta = trunc_dbl_precision(theta, TRUNC_SCALE); + idir = sround(theta); + /* Make sure on range [0..(ndirsX2)]. */ + idir %= full_ndirs; + + /* Return the integer direction. */ + return(idir); +} + +/************************************************************************* +************************************************************************** +#cat: closest_dir_dist - Takes to integer IMAP directions and determines the +#cat: closest distance between them accounting for +#cat: wrap-around either at the beginning or ending of +#cat: the range of directions. + + Input: + dir1 - integer value of the first direction + dir2 - integer value of the second direction + ndirs - the number of possible directions + Return Code: + Non-negative - distance between the 2 directions +**************************************************************************/ +int closest_dir_dist(const int dir1, const int dir2, const int ndirs) +{ + int d1, d2, dist; + + /* Initialize distance to -1 = INVALID. */ + dist = INVALID_DIR; + + /* Measure shortest distance between to directions. */ + /* If both neighbors are VALID ... */ + if((dir1 >= 0)&&(dir2 >= 0)){ + /* Compute inner and outer distances to account for distances */ + /* that wrap around the end of the range of directions, which */ + /* may in fact be closer. */ + d1 = abs(dir2 - dir1); + d2 = ndirs - d1; + dist = min(d1, d2); + } + /* Otherwise one or both directions are INVALID, so ignore */ + /* and return INVALID. */ + + /* Return determined closest distance. */ + return(dist); +} + diff --git a/libfprint/nbis/mindtct/xytreps.c b/libfprint/nbis/mindtct/xytreps.c new file mode 100644 index 00000000..65621ea9 --- /dev/null +++ b/libfprint/nbis/mindtct/xytreps.c @@ -0,0 +1,133 @@ +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: LFS - NIST Latent Fingerprint System + + FILE: XYTREPS.C + AUTHOR: Michael D. Garris + DATE: 09/16/2004 + + Contains routines useful in converting minutiae in LFS "native" + representation into other representations, such as + M1 (ANSI INCITS 378-2004) & NIST internal representations. + +*********************************************************************** + ROUTINES: + lfs2nist_minutia_XTY() + lfs2m1_minutia_XTY() + +***********************************************************************/ + +#include +#include + +/************************************************************************* +************************************************************************** +#cat: lfs2nist_minutia_XYT - Converts XYT minutiae attributes in LFS native +#cat: representation to NIST internal representation + + Input: + minutia - LFS minutia structure containing attributes to be converted + Output: + ox - NIST internal based x-pixel coordinate + oy - NIST internal based y-pixel coordinate + ot - NIST internal based minutia direction/orientation + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +void lfs2nist_minutia_XYT(int *ox, int *oy, int *ot, + const MINUTIA *minutia, const int iw, const int ih) +{ + int x, y, t; + float degrees_per_unit; + + /* XYT's according to NIST internal rep: */ + /* 1. pixel coordinates with origin bottom-left */ + /* 2. orientation in degrees on range [0..360] */ + /* with 0 pointing east and increasing counter */ + /* clockwise (same as M1) */ + /* 3. direction pointing out and away from the */ + /* ridge ending or bifurcation valley */ + /* (opposite direction from M1) */ + + x = minutia->x; + y = ih - minutia->y; + + degrees_per_unit = 180 / (float)NUM_DIRECTIONS; + + t = (270 - sround(minutia->direction * degrees_per_unit)) % 360; + if(t < 0){ + t += 360; + } + + *ox = x; + *oy = y; + *ot = t; +} + +/************************************************************************* +************************************************************************** +#cat: lfs2m1_minutia_XYT - Converts XYT minutiae attributes in LFS native +#cat: representation to M1 (ANSI INCITS 378-2004) representation + + Input: + minutia - LFS minutia structure containing attributes to be converted + Output: + ox - M1 based x-pixel coordinate + oy - M1 based y-pixel coordinate + ot - M1 based minutia direction/orientation + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +void lfs2m1_minutia_XYT(int *ox, int *oy, int *ot, const MINUTIA *minutia) +{ + int x, y, t; + float degrees_per_unit; + + /* XYT's according to M1 (ANSI INCITS 378-2004): */ + /* 1. pixel coordinates with origin top-left */ + /* 2. orientation in degrees on range [0..179] */ + /* with 0 pointing east and increasing counter */ + /* clockwise */ + /* 3. direction pointing up the ridge ending or */ + /* bifurcaiton valley */ + + x = minutia->x; + y = minutia->y; + + degrees_per_unit = 180 / (float)NUM_DIRECTIONS; + t = (90 - sround(minutia->direction * degrees_per_unit)) % 360; + if(t < 0){ + t += 360; + } + + /* range of theta is 0..179 because angles are in units of 2 degress */ + t = t / 2; + + *ox = x; + *oy = y; + *ot = t; +} From 6b8d17ef2654ad7f42fa9941074d132fb4d6e324 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sun, 28 Oct 2007 00:21:49 +0100 Subject: [PATCH 037/184] Add bozorth3 from NBIS; implement verify for image devices uru4000 works splendiferously (YAY!) aes4000 is going to need some work though :( --- README | 6 + THANKS | 2 + TODO | 5 + libfprint/Makefile.am | 6 + libfprint/fp_internal.h | 2 + libfprint/img.c | 36 +- libfprint/imgdev.c | 34 +- libfprint/nbis/bozorth3/bozorth3.c | 1785 ++++++++++++++++++++++++++++ libfprint/nbis/bozorth3/bz_alloc.c | 119 ++ libfprint/nbis/bozorth3/bz_drvrs.c | 223 ++++ libfprint/nbis/bozorth3/bz_gbls.c | 113 ++ libfprint/nbis/bozorth3/bz_io.c | 632 ++++++++++ libfprint/nbis/bozorth3/bz_sort.c | 315 +++++ libfprint/nbis/include/bozorth.h | 9 +- 14 files changed, 3260 insertions(+), 27 deletions(-) create mode 100644 libfprint/nbis/bozorth3/bozorth3.c create mode 100644 libfprint/nbis/bozorth3/bz_alloc.c create mode 100644 libfprint/nbis/bozorth3/bz_drvrs.c create mode 100644 libfprint/nbis/bozorth3/bz_gbls.c create mode 100644 libfprint/nbis/bozorth3/bz_io.c create mode 100644 libfprint/nbis/bozorth3/bz_sort.c diff --git a/README b/README index 65620a32..c9ba9d59 100644 --- a/README +++ b/README @@ -6,6 +6,12 @@ VERSION INCLUDES GPL CODE FROM LIBTHINKFINGER, therefore distribution is subject to both the terms of the LGPL (see COPYING) *and* the GPL (see COPYING.GPL). +libfprint includes code from NIST's NBIS software distribution: +http://fingerprint.nist.gov/NBIS/index.html +We include bozorth3 from the US export controlled distribution. We have +determined that it is fine to ship bozorth3 in an open source project, +see http://reactivated.net/fprint/US_export_control + At release time, I will contact libthinkfinger authors and see if they will be happy to relicense. I expect they will. diff --git a/THANKS b/THANKS index 7df327c4..6db35741 100644 --- a/THANKS +++ b/THANKS @@ -2,3 +2,5 @@ Tony Vroon - hardware donations Gerrie Mansur from Security Database BV (http://www.securitydatabase.net/) - hardware donations Joaquin Custodio - hardware donations TimeTrex (http://www.timetrex.com/) - hardware donations +Craig Watson (NIST) +James Vasile (SFLC) diff --git a/TODO b/TODO index f92bfcde..f4356063 100644 --- a/TODO +++ b/TODO @@ -13,6 +13,11 @@ ID Mouse driver Support for 2nd generation MS devices Support for 2nd generation UPEK devices +IMAGING +======= +aes4000 doesn't work very well, maybe due to small minutia count? +PPMM parameter to get_minutiae seems to have no effect + MISC ==== upekts/thinkfinger relicensing (GPL --> LGPL) diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index f857e6b0..800125ff 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -7,6 +7,12 @@ AES4000_SRC = drivers/aes4000.c DRIVER_SRC = $(UPEKTS_SRC) $(URU4000_SRC) $(AES4000_SRC) NBIS_SRC = \ + nbis/bozorth3/bozorth3.c \ + nbis/bozorth3/bz_alloc.c \ + nbis/bozorth3/bz_drvrs.c \ + nbis/bozorth3/bz_gbls.c \ + nbis/bozorth3/bz_io.c \ + nbis/bozorth3/bz_sort.c \ nbis/mindtct/binar.c \ nbis/mindtct/block.c \ nbis/mindtct/chaincod.c \ diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index f998dc5d..12ec764d 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -180,6 +180,8 @@ struct fp_img *fpi_img_resize(struct fp_img *img, size_t newsize); gboolean fpi_img_is_sane(struct fp_img *img); int fpi_img_detect_minutiae(struct fp_img_dev *imgdev, struct fp_img *img, struct fp_print_data **ret); +int fpi_img_compare_print_data(struct fp_print_data *enrolled_print, + struct fp_print_data *new_print); #define bswap16(x) (((x & 0xff) << 8) | (x >> 8)) #if __BYTE_ORDER == __LITTLE_ENDIAN diff --git a/libfprint/img.c b/libfprint/img.c index 2418ffdb..b2db8b8f 100644 --- a/libfprint/img.c +++ b/libfprint/img.c @@ -175,24 +175,6 @@ API_EXPORTED void fp_img_standardize(struct fp_img *img) } } -static int sort_x_y(const void *a, const void *b) -{ - struct minutiae_struct *af = (struct minutiae_struct *) a; - struct minutiae_struct *bf = (struct minutiae_struct *) b; - - if (af->col[0] < bf->col[0]) - return -1; - if (af->col[0] > bf->col[0]) - return 1; - - if (af->col[1] < bf->col[1]) - return -1; - if (af->col[1] > bf->col[1]) - return 1; - - return 0; -} - /* Based on write_minutiae_XYTQ and bz_load */ static void minutiae_to_xyt(MINUTIAE *minutiae, int bwidth, int bheight, unsigned char *buf) @@ -277,3 +259,21 @@ int fpi_img_detect_minutiae(struct fp_img_dev *imgdev, struct fp_img *img, return r; } + +int fpi_img_compare_print_data(struct fp_print_data *enrolled_print, + struct fp_print_data *new_print) +{ + struct xyt_struct *gstruct = (struct xyt_struct *) enrolled_print->buffer; + struct xyt_struct *pstruct = (struct xyt_struct *) new_print->buffer; + GTimer *timer; + int r; + + timer = g_timer_new(); + r = bozorth_main(pstruct, gstruct); + g_timer_stop(timer); + fp_dbg("bozorth processing took %f seconds, score=%d", + g_timer_elapsed(timer, NULL), r); + g_timer_destroy(timer); + + return r; +} diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index 1ff9bc63..9355bb4e 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -138,7 +138,7 @@ API_EXPORTED int fp_imgdev_capture(struct fp_img_dev *imgdev, return r; } -#define MIN_ACCEPTABLE_MINUTIAE 5 +#define MIN_ACCEPTABLE_MINUTIAE 10 int img_dev_enroll(struct fp_dev *dev, gboolean initial, int stage, struct fp_print_data **ret) @@ -170,11 +170,43 @@ int img_dev_enroll(struct fp_dev *dev, gboolean initial, int stage, return FP_ENROLL_COMPLETE; } +static int img_dev_verify(struct fp_dev *dev, + struct fp_print_data *enrolled_print) +{ + struct fp_img_dev *imgdev = dev->priv; + struct fp_img *img; + struct fp_print_data *print; + int r; + + r = fp_imgdev_capture(imgdev, 0, &img); + if (r) + return r; + + fp_img_standardize(img); + r = fpi_img_detect_minutiae(imgdev, img, &print); + fp_img_free(img); + if (r < 0) + return r; + if (r < MIN_ACCEPTABLE_MINUTIAE) { + fp_dbg("not enough minutiae, %d/%d", r, MIN_ACCEPTABLE_MINUTIAE); + fp_print_data_free(print); + return FP_VERIFY_RETRY; + } + + r = fpi_img_compare_print_data(enrolled_print, print); + fp_print_data_free(print); + if (r >= 40) + return FP_VERIFY_MATCH; + else + return FP_VERIFY_NO_MATCH; +} + void fpi_img_driver_setup(struct fp_img_driver *idriver) { idriver->driver.type = DRIVER_IMAGING; idriver->driver.init = img_dev_init; idriver->driver.exit = img_dev_exit; idriver->driver.enroll = img_dev_enroll; + idriver->driver.verify = img_dev_verify; } diff --git a/libfprint/nbis/bozorth3/bozorth3.c b/libfprint/nbis/bozorth3/bozorth3.c new file mode 100644 index 00000000..12bb0095 --- /dev/null +++ b/libfprint/nbis/bozorth3/bozorth3.c @@ -0,0 +1,1785 @@ +/****************************************************************************** + +This file is part of the Export Control subset of the United States NIST +Biometric Image Software (NBIS) distribution: + http://fingerprint.nist.gov/NBIS/index.html + +It is our understanding that this falls within ECCN 3D980, which covers +software associated with the development, production or use of certain +equipment controlled in accordance with U.S. concerns about crime control +practices in specific countries. + +Therefore, this file should not be exported, or made available on fileservers, +except as allowed by U.S. export control laws. + +Do not remove this notice. + +******************************************************************************/ + +/* NOTE: Despite the above notice (which I have not removed), this file is + * being legally distributed within libfprint; the U.S. Export Administration + * Regulations do not place export restrictions upon distribution of + * "publicly available technology and software", as stated in EAR section + * 734.3(b)(3)(i). libfprint qualifies as publicly available technology as per + * the definition in section 734.7(a)(1). + * + * For further information, see http://reactivated.net/fprint/US_export_control + */ + +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: FING - NIST Fingerprint Systems Utilities + + FILE: BOZORTH3.C + ALGORITHM: Allan S. Bozorth (FBI) + MODIFICATIONS: Michael D. Garris (NIST) + Stan Janet (NIST) + DATE: 09/21/2004 + + Contains the "core" routines responsible for supporting the + Bozorth3 fingerprint matching algorithm. + +*********************************************************************** + + ROUTINES: +#cat: bz_comp - takes a set of minutiae (probe or gallery) and +#cat: compares/measures each minutia's {x,y,t} with every +#cat: other minutia's {x,y,t} in the set creating a table +#cat: of pairwise comparison entries +#cat: bz_find - trims sorted table of pairwise minutia comparisons to +#cat: a max distance of 75^2 +#cat: bz_match - takes the two pairwise minutia comparison tables (a probe +#cat: table and a gallery table) and compiles a list of +#cat: all relatively "compatible" entries between the two +#cat: tables generating a match table +#cat: bz_match_score - takes a match table and traverses it looking for +#cat: a sufficiently long path (or a cluster of compatible paths) +#cat: of "linked" match table entries +#cat: the accumulation of which results in a match "score" +#cat: bz_sift - main routine handling the path linking and match table +#cat: traversal +#cat: bz_final_loop - (declared static) a final postprocess after +#cat: the main match table traversal which looks to combine +#cat: clusters of compatible paths + +***********************************************************************/ + +#include +#include + +static const int verbose_bozorth = 0; +static const int m1_xyt = 0; + +/***********************************************************************/ +void bz_comp( + int npoints, /* INPUT: # of points */ + int xcol[ MAX_BOZORTH_MINUTIAE ], /* INPUT: x cordinates */ + int ycol[ MAX_BOZORTH_MINUTIAE ], /* INPUT: y cordinates */ + int thetacol[ MAX_BOZORTH_MINUTIAE ], /* INPUT: theta values */ + + int * ncomparisons, /* OUTPUT: number of pointwise comparisons */ + int cols[][ COLS_SIZE_2 ], /* OUTPUT: pointwise comparison table */ + int * colptrs[] /* INPUT and OUTPUT: sorted list of pointers to rows in cols[] */ + ) +{ +int i, j, k; + +int b; +int t; +int n; +int l; + +int table_index; + +int dx; +int dy; +int distance; + +int theta_kj; +int beta_j; +int beta_k; + +int * c; + + + +c = &cols[0][0]; + +table_index = 0; +for ( k = 0; k < npoints - 1; k++ ) { + for ( j = k + 1; j < npoints; j++ ) { + + + if ( thetacol[j] > 0 ) { + + if ( thetacol[k] == thetacol[j] - 180 ) + continue; + } else { + + if ( thetacol[k] == thetacol[j] + 180 ) + continue; + } + + + dx = xcol[j] - xcol[k]; + dy = ycol[j] - ycol[k]; + distance = SQUARED(dx) + SQUARED(dy); + if ( distance > SQUARED(DM) ) { + if ( dx > DM ) + break; + else + continue; + + } + + /* The distance is in the range [ 0, 125^2 ] */ + if ( dx == 0 ) + theta_kj = 90; + else { + double dz; + + if ( m1_xyt ) + dz = ( 180.0F / PI_SINGLE ) * atanf( (float) -dy / (float) dx ); + else + dz = ( 180.0F / PI_SINGLE ) * atanf( (float) dy / (float) dx ); + if ( dz < 0.0F ) + dz -= 0.5F; + else + dz += 0.5F; + theta_kj = (int) dz; + } + + + beta_k = theta_kj - thetacol[k]; + beta_k = IANGLE180(beta_k); + + beta_j = theta_kj - thetacol[j] + 180; + beta_j = IANGLE180(beta_j); + + + if ( beta_k < beta_j ) { + *c++ = distance; + *c++ = beta_k; + *c++ = beta_j; + *c++ = k+1; + *c++ = j+1; + *c++ = theta_kj; + } else { + *c++ = distance; + *c++ = beta_j; + *c++ = beta_k; + *c++ = k+1; + *c++ = j+1; + *c++ = theta_kj + 400; + + } + + + + + + + b = 0; + t = table_index + 1; + l = 1; + n = -1; /* Init binary search state ... */ + + + + + while ( t - b > 1 ) { + int * midpoint; + + l = ( b + t ) / 2; + midpoint = colptrs[l-1]; + + + + + for ( i=0; i < 3; i++ ) { + int dd, ff; + + dd = cols[table_index][i]; + + ff = midpoint[i]; + + + n = SENSE(dd,ff); + + + if ( n < 0 ) { + t = l; + break; + } + if ( n > 0 ) { + b = l; + break; + } + } + + if ( n == 0 ) { + n = 1; + b = l; + } + } /* END while */ + + if ( n == 1 ) + ++l; + + + + + for ( i = table_index; i >= l; --i ) + colptrs[i] = colptrs[i-1]; + + + colptrs[l-1] = &cols[table_index][0]; + ++table_index; + + + if ( table_index == 19999 ) { +#ifndef NOVERBOSE + if ( verbose_bozorth ) + printf( "bz_comp(): breaking loop to avoid table overflow\n" ); +#endif + goto COMP_END; + } + + } /* END for j */ + +} /* END for k */ + +COMP_END: + *ncomparisons = table_index; + +} + +/***********************************************************************/ +void bz_find( + int * xlim, /* INPUT: number of pointwise comparisons in table */ + /* OUTPUT: determined insertion location (NOT ALWAYS SET) */ + int * colpt[] /* INOUT: sorted list of pointers to rows in the pointwise comparison table */ + ) +{ +int midpoint; +int top; +int bottom; +int state; +int distance; + + + +/* binary search to locate the insertion location of a predefined distance in list of sorted distances */ + + +bottom = 0; +top = *xlim + 1; +midpoint = 1; +state = -1; + +while ( top - bottom > 1 ) { + midpoint = ( bottom + top ) / 2; + distance = *colpt[ midpoint-1 ]; + state = SENSE_NEG_POS(FD,distance); + if ( state < 0 ) + top = midpoint; + else { + bottom = midpoint; + } +} + +if ( state > -1 ) + ++midpoint; + +if ( midpoint < *xlim ) + *xlim = midpoint; + + + +} + +/***********************************************************************/ +/* Make room in RTP list at insertion point by shifting contents down the + list. Then insert the address of the current ROT row into desired + location */ +/***********************************************************************/ +static + +void rtp_insert( int * rtp[], int l, int idx, int * ptr ) +{ +int shiftcount; +int ** r1; +int ** r2; + + +r1 = &rtp[idx]; +r2 = r1 - 1; + +shiftcount = ( idx - l ) + 1; +while ( shiftcount-- > 0 ) { + *r1-- = *r2--; +} +*r1 = ptr; +} + +/***********************************************************************/ +/* Builds list of compatible edge pairs between the 2 Webs. */ +/* The Edge pair DeltaThetaKJs and endpoints are sorted */ +/* first on Subject's K, */ +/* then On-File's J or K (depending), */ +/* and lastly on Subject's J point index. */ +/* Return value is the # of compatible edge pairs */ +/***********************************************************************/ +int bz_match( + int probe_ptrlist_len, /* INPUT: pruned length of Subject's pointer list */ + int gallery_ptrlist_len /* INPUT: pruned length of On-File Record's pointer list */ + ) +{ +int i; /* Temp index */ +int ii; /* Temp index */ +int edge_pair_index; /* Compatible edge pair index */ +float dz; /* Delta difference and delta angle stats */ +float fi; /* Distance limit based on factor TK */ +int * ss; /* Subject's comparison stats row */ +int * ff; /* On-File Record's comparison stats row */ +int j; /* On-File Record's row index */ +int k; /* Subject's row index */ +int st; /* Starting On-File Record's row index */ +int p1; /* Adjusted Subject's ThetaKJ, DeltaThetaKJs, K or J point index */ +int p2; /* Adjusted On-File's ThetaKJ, RTP point index */ +int n; /* ThetaKJ and binary search state variable */ +int l; /* Midpoint of binary search */ +int b; /* ThetaKJ state variable, and bottom of search range */ +int t; /* Top of search range */ + +register int * rotptr; + + +#define ROT_SIZE_1 20000 +#define ROT_SIZE_2 5 + +static int rot[ ROT_SIZE_1 ][ ROT_SIZE_2 ]; + + +static int * rtp[ ROT_SIZE_1 ]; + + + + +/* These now externally defined in bozorth.h */ +/* extern int * scolpt[ SCOLPT_SIZE ]; INPUT */ +/* extern int * fcolpt[ FCOLPT_SIZE ]; INPUT */ +/* extern int colp[ COLP_SIZE_1 ][ COLP_SIZE_2 ]; OUTPUT */ +/* extern int verbose_bozorth; */ +/* extern FILE * stderr; */ +/* extern char * get_progname( void ); */ +/* extern char * get_probe_filename( void ); */ +/* extern char * get_gallery_filename( void ); */ + + + + +st = 1; +edge_pair_index = 0; +rotptr = &rot[0][0]; + +/* Foreach sorted edge in Subject's Web ... */ + +for ( k = 1; k < probe_ptrlist_len; k++ ) { + ss = scolpt[k-1]; + + /* Foreach sorted edge in On-File Record's Web ... */ + + for ( j = st; j <= gallery_ptrlist_len; j++ ) { + ff = fcolpt[j-1]; + dz = *ff - *ss; + + fi = ( 2.0F * TK ) * ( *ff + *ss ); + + + + + + + + + if ( SQUARED(dz) > SQUARED(fi) ) { + if ( dz < 0 ) { + + st = j + 1; + + continue; + } else + break; + + + } + + + + for ( i = 1; i < 3; i++ ) { + float dz_squared; + + dz = *(ss+i) - *(ff+i); + dz_squared = SQUARED(dz); + + + + + if ( dz_squared > TXS && dz_squared < CTXS ) + break; + } + + if ( i < 3 ) + continue; + + + + + + + if ( *(ss+5) >= 220 ) { + p1 = *(ss+5) - 580; + n = 1; + } else { + p1 = *(ss+5); + n = 0; + } + + + if ( *(ff+5) >= 220 ) { + p2 = *(ff+5) - 580; + b = 1; + } else { + p2 = *(ff+5); + b = 0; + } + + p1 -= p2; + p1 = IANGLE180(p1); + + + + + + + + + + + + + + + + + + + + + + + + + if ( n != b ) { + + *rotptr++ = p1; + *rotptr++ = *(ss+3); + *rotptr++ = *(ss+4); + + *rotptr++ = *(ff+4); + *rotptr++ = *(ff+3); + } else { + *rotptr++ = p1; + *rotptr++ = *(ss+3); + *rotptr++ = *(ss+4); + + *rotptr++ = *(ff+3); + *rotptr++ = *(ff+4); + } + + + + + + + n = -1; + l = 1; + b = 0; + t = edge_pair_index + 1; + while ( t - b > 1 ) { + l = ( b + t ) / 2; + + for ( i = 0; i < 3; i++ ) { + static int ii_table[] = { 1, 3, 2 }; + + /* 1 = Subject's Kth, */ + /* 3 = On-File's Jth or Kth (depending), */ + /* 2 = Subject's Jth */ + + ii = ii_table[i]; + p1 = rot[edge_pair_index][ii]; + p2 = *( rtp[l-1] + ii ); + + n = SENSE(p1,p2); + + if ( n < 0 ) { + t = l; + break; + } + if ( n > 0 ) { + b = l; + break; + } + } + + if ( n == 0 ) { + n = 1; + b = l; + } + } /* END while() for binary search */ + + + if ( n == 1 ) + ++l; + + rtp_insert( rtp, l, edge_pair_index, &rot[edge_pair_index][0] ); + ++edge_pair_index; + + if ( edge_pair_index == 19999 ) { +#ifndef NOVERBOSE + if ( verbose_bozorth ) + fprintf( stderr, "%s: bz_match(): WARNING: list is full, breaking loop early [p=%s; g=%s]\n", + get_progname(), get_probe_filename(), get_gallery_filename() ); +#endif + goto END; /* break out if list exceeded */ + } + + } /* END FOR On-File (edge) distance */ + +} /* END FOR Subject (edge) distance */ + + + +END: +{ + int * colp_ptr = &colp[0][0]; + + for ( i = 0; i < edge_pair_index; i++ ) { + INT_COPY( colp_ptr, rtp[i], COLP_SIZE_2 ); + + + } +} + + + +return edge_pair_index; /* Return the number of compatible edge pairs stored into colp[][] */ +} + +/**************************************************************************/ +/* These global arrays are declared "static" as they are only used */ +/* between bz_match_score() & bz_final_loop() */ +/**************************************************************************/ +static int ct[ CT_SIZE ]; +static int gct[ GCT_SIZE ]; +static int ctt[ CTT_SIZE ]; +static int ctp[ CTP_SIZE_1 ][ CTP_SIZE_2 ]; +static int yy[ YY_SIZE_1 ][ YY_SIZE_2 ][ YY_SIZE_3 ]; + +static int bz_final_loop( int ); + +/**************************************************************************/ +int bz_match_score( + int np, + struct xyt_struct * pstruct, + struct xyt_struct * gstruct + ) +{ +int kx, kq; +int ftt; +int tot; +int qh; +int tp; +int ll, jj, kk, n, t, b; +int k, i, j, ii, z; +int kz, l; +int p1, p2; +int dw, ww; +int match_score; +int qq_overflow = 0; +float fi; + +/* These next 3 arrays originally declared global, but moved here */ +/* locally because they are only used herein */ +int rr[ RR_SIZE ]; +int avn[ AVN_SIZE ]; +int avv[ AVV_SIZE_1 ][ AVV_SIZE_2 ]; + +/* These now externally defined in bozorth.h */ +/* extern FILE * stderr; */ +/* extern char * get_progname( void ); */ +/* extern char * get_probe_filename( void ); */ +/* extern char * get_gallery_filename( void ); */ + + + + + + +if ( pstruct->nrows < MIN_COMPUTABLE_BOZORTH_MINUTIAE ) { +#ifndef NOVERBOSE + if ( gstruct->nrows < MIN_COMPUTABLE_BOZORTH_MINUTIAE ) { + if ( verbose_bozorth ) + fprintf( stderr, "%s: bz_match_score(): both probe and gallery file have too few minutiae (%d,%d) to compute a real Bozorth match score; min. is %d [p=%s; g=%s]\n", + get_progname(), + pstruct->nrows, gstruct->nrows, MIN_COMPUTABLE_BOZORTH_MINUTIAE, + get_probe_filename(), get_gallery_filename() ); + } else { + if ( verbose_bozorth ) + fprintf( stderr, "%s: bz_match_score(): probe file has too few minutiae (%d) to compute a real Bozorth match score; min. is %d [p=%s; g=%s]\n", + get_progname(), + pstruct->nrows, MIN_COMPUTABLE_BOZORTH_MINUTIAE, + get_probe_filename(), get_gallery_filename() ); + } +#endif + return ZERO_MATCH_SCORE; +} + + + +if ( gstruct->nrows < MIN_COMPUTABLE_BOZORTH_MINUTIAE ) { +#ifndef NOVERBOSE + if ( verbose_bozorth ) + fprintf( stderr, "%s: bz_match_score(): gallery file has too few minutiae (%d) to compute a real Bozorth match score; min. is %d [p=%s; g=%s]\n", + get_progname(), + gstruct->nrows, MIN_COMPUTABLE_BOZORTH_MINUTIAE, + get_probe_filename(), get_gallery_filename() ); +#endif + return ZERO_MATCH_SCORE; +} + + + + + + + + + + /* initialize tables to 0's */ +INT_SET( (int *) &yl, YL_SIZE_1 * YL_SIZE_2, 0 ); + + + +INT_SET( (int *) &sc, SC_SIZE, 0 ); +INT_SET( (int *) &cp, CP_SIZE, 0 ); +INT_SET( (int *) &rp, RP_SIZE, 0 ); +INT_SET( (int *) &tq, TQ_SIZE, 0 ); +INT_SET( (int *) &rq, RQ_SIZE, 0 ); +INT_SET( (int *) &zz, ZZ_SIZE, 1000 ); /* zz[] initialized to 1000's */ + +INT_SET( (int *) &avn, AVN_SIZE, 0 ); /* avn[0...4] <== 0; */ + + + + + +tp = 0; +p1 = 0; +tot = 0; +ftt = 0; +kx = 0; +match_score = 0; + +for ( k = 0; k < np - 1; k++ ) { + /* printf( "compute(): looping with k=%d\n", k ); */ + + if ( sc[k] ) /* If SC counter for current pair already incremented ... */ + continue; /* Skip to next pair */ + + + i = colp[k][1]; + t = colp[k][3]; + + + + + qq[0] = i; + rq[t-1] = i; + tq[i-1] = t; + + + ww = 0; + dw = 0; + + do { + ftt++; + tot = 0; + qh = 1; + kx = k; + + + + + do { + + + + + + + + + + kz = colp[kx][2]; + l = colp[kx][4]; + kx++; + bz_sift( &ww, kz, &qh, l, kx, ftt, &tot, &qq_overflow ); + if ( qq_overflow ) { + fprintf( stderr, "%s: WARNING: bz_match_score(): qq[] overflow from bz_sift() #1 [p=%s; g=%s]\n", + get_progname(), get_probe_filename(), get_gallery_filename() ); + return QQ_OVERFLOW_SCORE; + } + +#ifndef NOVERBOSE + if ( verbose_bozorth ) + printf( "x1 %d %d %d %d %d %d\n", kx, colp[kx][0], colp[kx][1], colp[kx][2], colp[kx][3], colp[kx][4] ); +#endif + + } while ( colp[kx][3] == colp[k][3] && colp[kx][1] == colp[k][1] ); + /* While the startpoints of lookahead edge pairs are the same as the starting points of the */ + /* current pair, set KQ to lookahead edge pair index where above bz_sift() loop left off */ + + kq = kx; + + for ( j = 1; j < qh; j++ ) { + for ( i = kq; i < np; i++ ) { + + for ( z = 1; z < 3; z++ ) { + if ( z == 1 ) { + if ( (j+1) > QQ_SIZE ) { + fprintf( stderr, "%s: WARNING: bz_match_score(): qq[] overflow #1 in bozorth3(); j-1 is %d [p=%s; g=%s]\n", + get_progname(), j-1, get_probe_filename(), get_gallery_filename() ); + return QQ_OVERFLOW_SCORE; + } + p1 = qq[j]; + } else { + p1 = tq[p1-1]; + + } + + + + + + + if ( colp[i][2*z] != p1 ) + break; + } + + + if ( z == 3 ) { + z = colp[i][1]; + l = colp[i][3]; + + + + if ( z != colp[k][1] && l != colp[k][3] ) { + kx = i + 1; + bz_sift( &ww, z, &qh, l, kx, ftt, &tot, &qq_overflow ); + if ( qq_overflow ) { + fprintf( stderr, "%s: WARNING: bz_match_score(): qq[] overflow from bz_sift() #2 [p=%s; g=%s]\n", + get_progname(), get_probe_filename(), get_gallery_filename() ); + return QQ_OVERFLOW_SCORE; + } + } + } + } /* END for i */ + + + + /* Done looking ahead for current j */ + + + + + + l = 1; + t = np + 1; + b = kq; + + while ( t - b > 1 ) { + l = ( b + t ) / 2; + + for ( i = 1; i < 3; i++ ) { + + if ( i == 1 ) { + if ( (j+1) > QQ_SIZE ) { + fprintf( stderr, "%s: WARNING: bz_match_score(): qq[] overflow #2 in bozorth3(); j-1 is %d [p=%s; g=%s]\n", + get_progname(), j-1, get_probe_filename(), get_gallery_filename() ); + return QQ_OVERFLOW_SCORE; + } + p1 = qq[j]; + } else { + p1 = tq[p1-1]; + } + + + + p2 = colp[l-1][i*2-1]; + + n = SENSE(p1,p2); + + if ( n < 0 ) { + t = l; + break; + } + if ( n > 0 ) { + b = l; + break; + } + } + + if ( n == 0 ) { + + + + + + + /* Locates the head of consecutive sequence of edge pairs all having the same starting Subject and On-File edgepoints */ + while ( colp[l-2][3] == p2 && colp[l-2][1] == colp[l-1][1] ) + l--; + + kx = l - 1; + + + do { + kz = colp[kx][2]; + l = colp[kx][4]; + kx++; + bz_sift( &ww, kz, &qh, l, kx, ftt, &tot, &qq_overflow ); + if ( qq_overflow ) { + fprintf( stderr, "%s: WARNING: bz_match_score(): qq[] overflow from bz_sift() #3 [p=%s; g=%s]\n", + get_progname(), get_probe_filename(), get_gallery_filename() ); + return QQ_OVERFLOW_SCORE; + } + } while ( colp[kx][3] == p2 && colp[kx][1] == colp[kx-1][1] ); + + break; + } /* END if ( n == 0 ) */ + + } /* END while */ + + } /* END for j */ + + + + + if ( tot >= MSTR ) { + jj = 0; + kk = 0; + n = 0; + l = 0; + + for ( i = 0; i < tot; i++ ) { + + + int colp_value = colp[ y[i]-1 ][0]; + if ( colp_value < 0 ) { + kk += colp_value; + n++; + } else { + jj += colp_value; + l++; + } + } + + + if ( n == 0 ) { + n = 1; + } else if ( l == 0 ) { + l = 1; + } + + + + fi = (float) jj / (float) l - (float) kk / (float) n; + + if ( fi > 180.0F ) { + fi = ( jj + kk + n * 360 ) / (float) tot; + if ( fi > 180.0F ) + fi -= 360.0F; + } else { + fi = ( jj + kk ) / (float) tot; + } + + jj = ROUND(fi); + if ( jj <= -180 ) + jj += 360; + + + + kk = 0; + for ( i = 0; i < tot; i++ ) { + int diff = colp[ y[i]-1 ][0] - jj; + j = SQUARED( diff ); + + + + + if ( j > TXS && j < CTXS ) + kk++; + else + y[i-kk] = y[i]; + } /* END FOR i */ + + tot -= kk; /* Adjust the total edge pairs TOT based on # of edge pairs skipped */ + + } /* END if ( tot >= MSTR ) */ + + + + + if ( tot < MSTR ) { + + + + + for ( i = tot-1 ; i >= 0; i-- ) { + int idx = y[i] - 1; + if ( rk[idx] == 0 ) { + sc[idx] = -1; + } else { + sc[idx] = rk[idx]; + } + } + ftt--; + + } else { /* tot >= MSTR */ + /* Otherwise size of TOT group (seq. of TOT indices stored in Y) is large enough to analyze */ + + int pa = 0; + int pb = 0; + int pc = 0; + int pd = 0; + + for ( i = 0; i < tot; i++ ) { + int idx = y[i] - 1; + for ( ii = 1; ii < 4; ii++ ) { + + + + + kk = ( SQUARED(ii) - ii + 2 ) / 2 - 1; + + + + + jj = colp[idx][kk]; + + switch ( ii ) { + case 1: + if ( colp[idx][0] < 0 ) { + pd += colp[idx][0]; + pb++; + } else { + pa += colp[idx][0]; + pc++; + } + break; + case 2: + avn[ii-1] += pstruct->xcol[jj-1]; + avn[ii] += pstruct->ycol[jj-1]; + break; + default: + avn[ii] += gstruct->xcol[jj-1]; + avn[ii+1] += gstruct->ycol[jj-1]; + break; + } /* switch */ + } /* END for ii = [1..3] */ + + for ( ii = 0; ii < 2; ii++ ) { + n = -1; + l = 1; + + for ( jj = 1; jj < 3; jj++ ) { + + + + + + + + + + + p1 = colp[idx][ 2 * ii + jj ]; + + + b = 0; + t = yl[ii][tp] + 1; + + while ( t - b > 1 ) { + l = ( b + t ) / 2; + p2 = yy[l-1][ii][tp]; + n = SENSE(p1,p2); + + if ( n < 0 ) { + t = l; + } else { + if ( n > 0 ) { + b = l; + } else { + break; + } + } + } /* END WHILE */ + + if ( n != 0 ) { + if ( n == 1 ) + ++l; + + for ( kk = yl[ii][tp]; kk >= l; --kk ) { + yy[kk][ii][tp] = yy[kk-1][ii][tp]; + } + + ++yl[ii][tp]; + yy[l-1][ii][tp] = p1; + + + } /* END if ( n != 0 ) */ + + /* Otherwise, edgepoint already stored in YY */ + + } /* END FOR jj in [1,2] */ + } /* END FOR ii in [0,1] */ + } /* END FOR i */ + + if ( pb == 0 ) { + pb = 1; + } else if ( pc == 0 ) { + pc = 1; + } + + + + fi = (float) pa / (float) pc - (float) pd / (float) pb; + if ( fi > 180.0F ) { + + fi = ( pa + pd + pb * 360 ) / (float) tot; + if ( fi > 180.0F ) + fi -= 360.0F; + } else { + fi = ( pa + pd ) / (float) tot; + } + + pa = ROUND(fi); + if ( pa <= -180 ) + pa += 360; + + + + avv[tp][0] = pa; + + for ( ii = 1; ii < 5; ii++ ) { + avv[tp][ii] = avn[ii] / tot; + avn[ii] = 0; + } + + ct[tp] = tot; + gct[tp] = tot; + + if ( tot > match_score ) /* If current TOT > match_score ... */ + match_score = tot; /* Keep track of max TOT in match_score */ + + ctt[tp] = 0; /* Init CTT[TP] to 0 */ + ctp[tp][0] = tp; /* Store TP into CTP */ + + for ( ii = 0; ii < tp; ii++ ) { + int found; + int diff; + + int * avv_tp_ptr = &avv[tp][0]; + int * avv_ii_ptr = &avv[ii][0]; + diff = *avv_tp_ptr++ - *avv_ii_ptr++; + j = SQUARED( diff ); + + + + + + + if ( j > TXS && j < CTXS ) + continue; + + + + + + + + + + ll = *avv_tp_ptr++ - *avv_ii_ptr++; + jj = *avv_tp_ptr++ - *avv_ii_ptr++; + kk = *avv_tp_ptr++ - *avv_ii_ptr++; + j = *avv_tp_ptr++ - *avv_ii_ptr++; + + { + float tt, ai, dz; + + tt = (float) (SQUARED(ll) + SQUARED(jj)); + ai = (float) (SQUARED(j) + SQUARED(kk)); + + fi = ( 2.0F * TK ) * ( tt + ai ); + dz = tt - ai; + + + if ( SQUARED(dz) > SQUARED(fi) ) + continue; + } + + + + if ( ll ) { + + if ( m1_xyt ) + fi = ( 180.0F / PI_SINGLE ) * atanf( (float) -jj / (float) ll ); + else + fi = ( 180.0F / PI_SINGLE ) * atanf( (float) jj / (float) ll ); + if ( fi < 0.0F ) { + if ( ll < 0 ) + fi += 180.5F; + else + fi -= 0.5F; + } else { + if ( ll < 0 ) + fi -= 180.5F; + else + fi += 0.5F; + } + jj = (int) fi; + if ( jj <= -180 ) + jj += 360; + } else { + + if ( m1_xyt ) { + if ( jj > 0 ) + jj = -90; + else + jj = 90; + } else { + if ( jj > 0 ) + jj = 90; + else + jj = -90; + } + } + + + + if ( kk ) { + + if ( m1_xyt ) + fi = ( 180.0F / PI_SINGLE ) * atanf( (float) -j / (float) kk ); + else + fi = ( 180.0F / PI_SINGLE ) * atanf( (float) j / (float) kk ); + if ( fi < 0.0F ) { + if ( kk < 0 ) + fi += 180.5F; + else + fi -= 0.5F; + } else { + if ( kk < 0 ) + fi -= 180.5F; + else + fi += 0.5F; + } + j = (int) fi; + if ( j <= -180 ) + j += 360; + } else { + + if ( m1_xyt ) { + if ( j > 0 ) + j = -90; + else + j = 90; + } else { + if ( j > 0 ) + j = 90; + else + j = -90; + } + } + + + + + + pa = 0; + pb = 0; + pc = 0; + pd = 0; + + if ( avv[tp][0] < 0 ) { + pd += avv[tp][0]; + pb++; + } else { + pa += avv[tp][0]; + pc++; + } + + if ( avv[ii][0] < 0 ) { + pd += avv[ii][0]; + pb++; + } else { + pa += avv[ii][0]; + pc++; + } + + if ( pb == 0 ) { + pb = 1; + } else if ( pc == 0 ) { + pc = 1; + } + + + + fi = (float) pa / (float) pc - (float) pd / (float) pb; + + if ( fi > 180.0F ) { + fi = ( pa + pd + pb * 360 ) / 2.0F; + if ( fi > 180.0F ) + fi -= 360.0F; + } else { + fi = ( pa + pd ) / 2.0F; + } + + pb = ROUND(fi); + if ( pb <= -180 ) + pb += 360; + + + + + + pa = jj - j; + pa = IANGLE180(pa); + kk = SQUARED(pb-pa); + + + + + /* Was: if ( SQUARED(kk) > TXS && kk < CTXS ) : assume typo */ + if ( kk > TXS && kk < CTXS ) + continue; + + + found = 0; + for ( kk = 0; kk < 2; kk++ ) { + jj = 0; + ll = 0; + + do { + while ( yy[jj][kk][ii] < yy[ll][kk][tp] && jj < yl[kk][ii] ) { + + jj++; + } + + + + + while ( yy[jj][kk][ii] > yy[ll][kk][tp] && ll < yl[kk][tp] ) { + + ll++; + } + + + + + if ( yy[jj][kk][ii] == yy[ll][kk][tp] && jj < yl[kk][ii] && ll < yl[kk][tp] ) { + found = 1; + break; + } + + + } while ( jj < yl[kk][ii] && ll < yl[kk][tp] ); + if ( found ) + break; + } /* END for kk */ + + if ( ! found ) { /* If we didn't find what we were searching for ... */ + gct[ii] += ct[tp]; + if ( gct[ii] > match_score ) + match_score = gct[ii]; + ++ctt[ii]; + ctp[ii][ctt[ii]] = tp; + } + + } /* END for ii in [0,TP-1] prior TP group */ + + tp++; /* Bump TP counter */ + + + } /* END ELSE if ( tot == MSTR ) */ + + + + if ( qh > QQ_SIZE ) { + fprintf( stderr, "%s: WARNING: bz_match_score(): qq[] overflow #3 in bozorth3(); qh-1 is %d [p=%s; g=%s]\n", + get_progname(), qh-1, get_probe_filename(), get_gallery_filename() ); + return QQ_OVERFLOW_SCORE; + } + for ( i = qh - 1; i > 0; i-- ) { + n = qq[i] - 1; + if ( ( tq[n] - 1 ) >= 0 ) { + rq[tq[n]-1] = 0; + tq[n] = 0; + zz[n] = 1000; + } + } + + for ( i = dw - 1; i >= 0; i-- ) { + n = rr[i] - 1; + if ( tq[n] ) { + rq[tq[n]-1] = 0; + tq[n] = 0; + } + } + + i = 0; + j = ww - 1; + while ( i >= 0 && j >= 0 ) { + if ( nn[j] < mm[j] ) { + ++nn[j]; + + for ( i = ww - 1; i >= 0; i-- ) { + int rt = rx[i]; + if ( rt < 0 ) { + rt = - rt; + rt--; + z = rf[i][nn[i]-1]-1; + + + + if (( tq[z] != (rt+1) && tq[z] ) || ( rq[rt] != (z+1) && rq[rt] )) + break; + + + tq[z] = rt+1; + rq[rt] = z+1; + rr[i] = z+1; + } else { + rt--; + z = cf[i][nn[i]-1]-1; + + + if (( tq[rt] != (z+1) && tq[rt] ) || ( rq[z] != (rt+1) && rq[z] )) + break; + + + tq[rt] = z+1; + rq[z] = rt+1; + rr[i] = rt+1; + } + } /* END for i */ + + if ( i >= 0 ) { + for ( z = i + 1; z < ww; z++) { + n = rr[z] - 1; + if ( tq[n] - 1 >= 0 ) { + rq[tq[n]-1] = 0; + tq[n] = 0; + } + } + j = ww - 1; + } + + } else { + nn[j] = 1; + j--; + } + + } + + if ( tp > 1999 ) + break; + + dw = ww; + + + } while ( j >= 0 ); /* END while endpoint group remain ... */ + + + if ( tp > 1999 ) + break; + + + + + n = qq[0] - 1; + if ( tq[n] - 1 >= 0 ) { + rq[tq[n]-1] = 0; + tq[n] = 0; + } + + for ( i = ww-1; i >= 0; i-- ) { + n = rx[i]; + if ( n < 0 ) { + n = - n; + rp[n-1] = 0; + } else { + cp[n-1] = 0; + } + + } + +} /* END FOR each edge pair */ + + + +if ( match_score < MMSTR ) { + return match_score; +} + +match_score = bz_final_loop( tp ); +return match_score; +} + + +/***********************************************************************/ +/* These globals signficantly used by bz_sift () */ +/* Now externally defined in bozorth.h */ +/* extern int sc[ SC_SIZE ]; */ +/* extern int rq[ RQ_SIZE ]; */ +/* extern int tq[ TQ_SIZE ]; */ +/* extern int rf[ RF_SIZE_1 ][ RF_SIZE_2 ]; */ +/* extern int cf[ CF_SIZE_1 ][ CF_SIZE_2 ]; */ +/* extern int zz[ ZZ_SIZE ]; */ +/* extern int rx[ RX_SIZE ]; */ +/* extern int mm[ MM_SIZE ]; */ +/* extern int nn[ NN_SIZE ]; */ +/* extern int qq[ QQ_SIZE ]; */ +/* extern int rk[ RK_SIZE ]; */ +/* extern int cp[ CP_SIZE ]; */ +/* extern int rp[ RP_SIZE ]; */ +/* extern int y[ Y_SIZE ]; */ + +void bz_sift( + int * ww, /* INPUT and OUTPUT; endpoint groups index; *ww may be bumped by one or by two */ + int kz, /* INPUT only; endpoint of lookahead Subject edge */ + int * qh, /* INPUT and OUTPUT; the value is an index into qq[] and is stored in zz[]; *qh may be bumped by one */ + int l, /* INPUT only; endpoint of lookahead On-File edge */ + int kx, /* INPUT only -- index */ + int ftt, /* INPUT only */ + int * tot, /* OUTPUT -- counter is incremented by one, sometimes */ + int * qq_overflow /* OUTPUT -- flag is set only if qq[] overflows */ + ) +{ +int n; +int t; + +/* These now externally defined in bozorth.h */ +/* extern FILE * stderr; */ +/* extern char * get_progname( void ); */ +/* extern char * get_probe_filename( void ); */ +/* extern char * get_gallery_filename( void ); */ + + + +n = tq[ kz - 1]; /* Lookup On-File edgepoint stored in TQ at index of endpoint of lookahead Subject edge */ +t = rq[ l - 1]; /* Lookup Subject edgepoint stored in RQ at index of endpoint of lookahead On-File edge */ + +if ( n == 0 && t == 0 ) { + + + if ( sc[kx-1] != ftt ) { + y[ (*tot)++ ] = kx; + rk[kx-1] = sc[kx-1]; + sc[kx-1] = ftt; + } + + if ( *qh >= QQ_SIZE ) { + fprintf( stderr, "%s: ERROR: bz_sift(): qq[] overflow #1; the index [*qh] is %d [p=%s; g=%s]\n", + get_progname(), + *qh, get_probe_filename(), get_gallery_filename() ); + *qq_overflow = 1; + return; + } + qq[ *qh ] = kz; + zz[ kz-1 ] = (*qh)++; + + + /* The TQ and RQ locations are set, so set them ... */ + tq[ kz-1 ] = l; + rq[ l-1 ] = kz; + + return; +} /* END if ( n == 0 && t == 0 ) */ + + + + + + + + + +if ( n == l ) { + + if ( sc[kx-1] != ftt ) { + if ( zz[kx-1] == 1000 ) { + if ( *qh >= QQ_SIZE ) { + fprintf( stderr, "%s: ERROR: bz_sift(): qq[] overflow #2; the index [*qh] is %d [p=%s; g=%s]\n", + get_progname(), + *qh, + get_probe_filename(), get_gallery_filename() ); + *qq_overflow = 1; + return; + } + qq[*qh] = kz; + zz[kz-1] = (*qh)++; + } + y[(*tot)++] = kx; + rk[kx-1] = sc[kx-1]; + sc[kx-1] = ftt; + } + + return; +} /* END if ( n == l ) */ + + + + + +if ( *ww >= WWIM ) /* This limits the number of endpoint groups that can be constructed */ + return; + + +{ +int b; +int b_index; +register int i; +int notfound; +int lim; +register int * lptr; + +/* If lookahead Subject endpoint previously assigned to TQ but not paired with lookahead On-File endpoint ... */ + +if ( n ) { + b = cp[ kz - 1 ]; + if ( b == 0 ) { + b = ++*ww; + b_index = b - 1; + cp[kz-1] = b; + cf[b_index][0] = n; + mm[b_index] = 1; + nn[b_index] = 1; + rx[b_index] = kz; + + } else { + b_index = b - 1; + } + + lim = mm[b_index]; + lptr = &cf[b_index][0]; + notfound = 1; + +#ifndef NOVERBOSE + if ( verbose_bozorth ) { + int * llptr = lptr; + printf( "bz_sift(): n: looking for l=%d in [", l ); + for ( i = 0; i < lim; i++ ) { + printf( " %d", *llptr++ ); + } + printf( " ]\n" ); + } +#endif + + for ( i = 0; i < lim; i++ ) { + if ( *lptr++ == l ) { + notfound = 0; + break; + } + } + if ( notfound ) { /* If lookahead On-File endpoint not in list ... */ + cf[b_index][i] = l; + ++mm[b_index]; + } +} /* END if ( n ) */ + + +/* If lookahead On-File endpoint previously assigned to RQ but not paired with lookahead Subject endpoint... */ + +if ( t ) { + b = rp[ l - 1 ]; + if ( b == 0 ) { + b = ++*ww; + b_index = b - 1; + rp[l-1] = b; + rf[b_index][0] = t; + mm[b_index] = 1; + nn[b_index] = 1; + rx[b_index] = -l; + + + } else { + b_index = b - 1; + } + + lim = mm[b_index]; + lptr = &rf[b_index][0]; + notfound = 1; + +#ifndef NOVERBOSE + if ( verbose_bozorth ) { + int * llptr = lptr; + printf( "bz_sift(): t: looking for kz=%d in [", kz ); + for ( i = 0; i < lim; i++ ) { + printf( " %d", *llptr++ ); + } + printf( " ]\n" ); + } +#endif + + for ( i = 0; i < lim; i++ ) { + if ( *lptr++ == kz ) { + notfound = 0; + break; + } + } + if ( notfound ) { /* If lookahead Subject endpoint not in list ... */ + rf[b_index][i] = kz; + ++mm[b_index]; + } +} /* END if ( t ) */ + +} + +} + +/**************************************************************************/ + +static int bz_final_loop( int tp ) +{ +int ii, i, t, b, n, k, j, kk, jj; +int lim; +int match_score; + +/* This array originally declared global, but moved here */ +/* locally because it is only used herein. The use of */ +/* "static" is required as the array will exceed the */ +/* stack allocation on our local systems otherwise. */ +static int sct[ SCT_SIZE_1 ][ SCT_SIZE_2 ]; + +match_score = 0; +for ( ii = 0; ii < tp; ii++ ) { /* For each index up to the current value of TP ... */ + + if ( match_score >= gct[ii] ) /* if next group total not bigger than current match_score.. */ + continue; /* skip to next TP index */ + + lim = ctt[ii] + 1; + for ( i = 0; i < lim; i++ ) { + sct[i][0] = ctp[ii][i]; + } + + t = 0; + y[0] = lim; + cp[0] = 1; + b = 0; + n = 1; + do { /* looping until T < 0 ... */ + if ( y[t] - cp[t] > 1 ) { + k = sct[cp[t]][t]; + j = ctt[k] + 1; + for ( i = 0; i < j; i++ ) { + rp[i] = ctp[k][i]; + } + k = 0; + kk = cp[t]; + jj = 0; + + do { + while ( rp[jj] < sct[kk][t] && jj < j ) + jj++; + while ( rp[jj] > sct[kk][t] && kk < y[t] ) + kk++; + while ( rp[jj] == sct[kk][t] && kk < y[t] && jj < j ) { + sct[k][t+1] = sct[kk][t]; + k++; + kk++; + jj++; + } + } while ( kk < y[t] && jj < j ); + + t++; + cp[t] = 1; + y[t] = k; + b = t; + n = 1; + } else { + int tot = 0; + + lim = y[t]; + for ( i = n-1; i < lim; i++ ) { + tot += ct[ sct[i][t] ]; + } + + for ( i = 0; i < b; i++ ) { + tot += ct[ sct[0][i] ]; + } + + if ( tot > match_score ) { /* If the current total is larger than the running total ... */ + match_score = tot; /* then set match_score to the new total */ + for ( i = 0; i < b; i++ ) { + rk[i] = sct[0][i]; + } + + { + int rk_index = b; + lim = y[t]; + for ( i = n-1; i < lim; ) { + rk[ rk_index++ ] = sct[ i++ ][ t ]; + } + } + } + b = t; + t--; + if ( t >= 0 ) { + ++cp[t]; + n = y[t]; + } + } /* END IF */ + + } while ( t >= 0 ); + +} /* END FOR ii */ + +return match_score; + +} /* END bz_final_loop() */ diff --git a/libfprint/nbis/bozorth3/bz_alloc.c b/libfprint/nbis/bozorth3/bz_alloc.c new file mode 100644 index 00000000..275a1429 --- /dev/null +++ b/libfprint/nbis/bozorth3/bz_alloc.c @@ -0,0 +1,119 @@ +/****************************************************************************** + +This file is part of the Export Control subset of the United States NIST +Biometric Image Software (NBIS) distribution: + http://fingerprint.nist.gov/NBIS/index.html + +It is our understanding that this falls within ECCN 3D980, which covers +software associated with the development, production or use of certain +equipment controlled in accordance with U.S. concerns about crime control +practices in specific countries. + +Therefore, this file should not be exported, or made available on fileservers, +except as allowed by U.S. export control laws. + +Do not remove this notice. + +******************************************************************************/ + +/* NOTE: Despite the above notice (which I have not removed), this file is + * being legally distributed within libfprint; the U.S. Export Administration + * Regulations do not place export restrictions upon distribution of + * "publicly available technology and software", as stated in EAR section + * 734.3(b)(3)(i). libfprint qualifies as publicly available technology as per + * the definition in section 734.7(a)(1). + * + * For further information, see http://reactivated.net/fprint/US_export_control + */ + +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: FING - NIST Fingerprint Systems Utilities + + FILE: BZ_ALLOC.C + ALGORITHM: Allan S. Bozorth (FBI) + MODIFICATIONS: Michael D. Garris (NIST) + Stan Janet (NIST) + DATE: 09/21/2004 + + Contains routines responsible for supporting the + Bozorth3 fingerprint matching algorithm. + +*********************************************************************** + + ROUTINES: +#cat: malloc_or_exit - allocates a buffer of bytes from the heap of +#cat: specified length exiting directly upon system error +#cat: malloc_or_return_error - allocates a buffer of bytes from the heap +#cat: of specified length returning an error code upon system error + +***********************************************************************/ + +#include +#include +#include + + +/***********************************************************************/ +char * malloc_or_exit( int nbytes, const char * what ) +{ +char * p; + +/* These are now externally defined in bozorth.h */ +/* extern FILE * stderr; */ +/* extern char * get_progname( void ); */ + + +p = malloc( (size_t) nbytes ); +if ( p == CNULL ) { + fprintf( stderr, "%s: ERROR: malloc() of %d bytes for %s failed: %s\n", + get_progname(), + nbytes, + what, + strerror( errno ) + ); + exit(1); +} +return p; +} + +/***********************************************************************/ +/* returns CNULL on error */ +char * malloc_or_return_error( int nbytes, const char * what ) +{ +char * p; + +p = malloc( (size_t) nbytes ); +if ( p == CNULL ) { + fprintf( stderr, "%s: ERROR: malloc() of %d bytes for %s failed: %s\n", + get_progname(), + nbytes, + what, + strerror( errno ) + ); + return(CNULL); +} +return p; +} diff --git a/libfprint/nbis/bozorth3/bz_drvrs.c b/libfprint/nbis/bozorth3/bz_drvrs.c new file mode 100644 index 00000000..4ff47570 --- /dev/null +++ b/libfprint/nbis/bozorth3/bz_drvrs.c @@ -0,0 +1,223 @@ +/****************************************************************************** + +This file is part of the Export Control subset of the United States NIST +Biometric Image Software (NBIS) distribution: + http://fingerprint.nist.gov/NBIS/index.html + +It is our understanding that this falls within ECCN 3D980, which covers +software associated with the development, production or use of certain +equipment controlled in accordance with U.S. concerns about crime control +practices in specific countries. + +Therefore, this file should not be exported, or made available on fileservers, +except as allowed by U.S. export control laws. + +Do not remove this notice. + +******************************************************************************/ + +/* NOTE: Despite the above notice (which I have not removed), this file is + * being legally distributed within libfprint; the U.S. Export Administration + * Regulations do not place export restrictions upon distribution of + * "publicly available technology and software", as stated in EAR section + * 734.3(b)(3)(i). libfprint qualifies as publicly available technology as per + * the definition in section 734.7(a)(1). + * + * For further information, see http://reactivated.net/fprint/US_export_control + */ + +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: FING - NIST Fingerprint Systems Utilities + + FILE: BZ_DRVRS.C + ALGORITHM: Allan S. Bozorth (FBI) + MODIFICATIONS: Michael D. Garris (NIST) + Stan Janet (NIST) + DATE: 09/21/2004 + + Contains driver routines responsible for kicking off matches + using the Bozorth3 fingerprint matching algorithm. + +*********************************************************************** + + ROUTINES: +#cat: bozorth_probe_init - creates the pairwise minutia comparison +#cat: table for the probe fingerprint +#cat: bozorth_gallery_init - creates the pairwise minutia comparison +#cat: table for the gallery fingerprint +#cat: bozorth_to_gallery - supports the matching scenario where the +#cat: same probe fingerprint is matches repeatedly +#cat: to multiple gallery fingerprints as in +#cat: identification mode +#cat: bozorth_main - supports the matching scenario where a +#cat: single probe fingerprint is to be matched +#cat: to a single gallery fingerprint as in +#cat: verificaiton mode + +***********************************************************************/ + +#include +#include +#include +#include + +/**************************************************************************/ + +int bozorth_probe_init( struct xyt_struct * pstruct ) +{ +int sim; /* number of pointwise comparisons for Subject's record*/ +int msim; /* Pruned length of Subject's comparison pointer list */ + + + +/* Take Subject's points and compute pointwise comparison statistics table and sorted row-pointer list. */ +/* This builds a "Web" of relative edge statistics between points. */ +bz_comp( + pstruct->nrows, + pstruct->xcol, + pstruct->ycol, + pstruct->thetacol, + &sim, + scols, + scolpt ); + +msim = sim; /* Init search to end of Subject's pointwise comparison table (last edge in Web) */ + + + +bz_find( &msim, scolpt ); + + + +if ( msim < FDD ) /* Makes sure there are a reasonable number of edges (at least 500, if possible) to analyze in the Web */ + msim = ( sim > FDD ) ? FDD : sim; + + + + + +return msim; +} + +/**************************************************************************/ + +int bozorth_gallery_init( struct xyt_struct * gstruct ) +{ +int fim; /* number of pointwise comparisons for On-File record*/ +int mfim; /* Pruned length of On-File Record's pointer list */ + + +/* Take On-File Record's points and compute pointwise comparison statistics table and sorted row-pointer list. */ +/* This builds a "Web" of relative edge statistics between points. */ +bz_comp( + gstruct->nrows, + gstruct->xcol, + gstruct->ycol, + gstruct->thetacol, + &fim, + fcols, + fcolpt ); + +mfim = fim; /* Init search to end of On-File Record's pointwise comparison table (last edge in Web) */ + + + +bz_find( &mfim, fcolpt ); + + + +if ( mfim < FDD ) /* Makes sure there are a reasonable number of edges (at least 500, if possible) to analyze in the Web */ + mfim = ( fim > FDD ) ? FDD : fim; + + + + + +return mfim; +} + +/**************************************************************************/ + +int bozorth_to_gallery( + int probe_len, + struct xyt_struct * pstruct, + struct xyt_struct * gstruct + ) +{ +int np; +int gallery_len; + +gallery_len = bozorth_gallery_init( gstruct ); +np = bz_match( probe_len, gallery_len ); +return bz_match_score( np, pstruct, gstruct ); +} + +/**************************************************************************/ + +int bozorth_main( + struct xyt_struct * pstruct, + struct xyt_struct * gstruct + ) +{ +int ms; +int np; +int probe_len; +int gallery_len; + + + +#ifdef DEBUG + printf( "PROBE_INIT() called\n" ); +#endif +probe_len = bozorth_probe_init( pstruct ); + + +#ifdef DEBUG + printf( "GALLERY_INIT() called\n" ); +#endif +gallery_len = bozorth_gallery_init( gstruct ); + + +#ifdef DEBUG + printf( "BZ_MATCH() called\n" ); +#endif +np = bz_match( probe_len, gallery_len ); + + +#ifdef DEBUG + printf( "BZ_MATCH() returned %d edge pairs\n", np ); + printf( "COMPUTE() called\n" ); +#endif +ms = bz_match_score( np, pstruct, gstruct ); + + +#ifdef DEBUG + printf( "COMPUTE() returned %d\n", ms ); +#endif + + +return ms; +} diff --git a/libfprint/nbis/bozorth3/bz_gbls.c b/libfprint/nbis/bozorth3/bz_gbls.c new file mode 100644 index 00000000..958c9ee3 --- /dev/null +++ b/libfprint/nbis/bozorth3/bz_gbls.c @@ -0,0 +1,113 @@ +/****************************************************************************** + +This file is part of the Export Control subset of the United States NIST +Biometric Image Software (NBIS) distribution: + http://fingerprint.nist.gov/NBIS/index.html + +It is our understanding that this falls within ECCN 3D980, which covers +software associated with the development, production or use of certain +equipment controlled in accordance with U.S. concerns about crime control +practices in specific countries. + +Therefore, this file should not be exported, or made available on fileservers, +except as allowed by U.S. export control laws. + +Do not remove this notice. + +******************************************************************************/ + +/* NOTE: Despite the above notice (which I have not removed), this file is + * being legally distributed within libfprint; the U.S. Export Administration + * Regulations do not place export restrictions upon distribution of + * "publicly available technology and software", as stated in EAR section + * 734.3(b)(3)(i). libfprint qualifies as publicly available technology as per + * the definition in section 734.7(a)(1). + * + * For further information, see http://reactivated.net/fprint/US_export_control + */ + +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: FING - NIST Fingerprint Systems Utilities + + FILE: BZ_GBLS.C + ALGORITHM: Allan S. Bozorth (FBI) + MODIFICATIONS: Michael D. Garris (NIST) + Stan Janet (NIST) + DATE: 09/21/2004 + + Contains global variables responsible for supporting the + Bozorth3 fingerprint matching "core" algorithm. + +*********************************************************************** +***********************************************************************/ + +#include + +/**************************************************************************/ +/* General supporting global variables */ +/**************************************************************************/ + +int colp[ COLP_SIZE_1 ][ COLP_SIZE_2 ]; /* Output from match(), this is a sorted table of compatible edge pairs containing: */ + /* DeltaThetaKJs, Subject's K, J, then On-File's {K,J} or {J,K} depending */ + /* Sorted first on Subject's point index K, */ + /* then On-File's K or J point index (depending), */ + /* lastly on Subject's J point index */ +int scols[ SCOLS_SIZE_1 ][ COLS_SIZE_2 ]; /* Subject's pointwise comparison table containing: */ + /* Distance,min(BetaK,BetaJ),max(BetaK,BbetaJ), K,J,ThetaKJ */ +int fcols[ FCOLS_SIZE_1 ][ COLS_SIZE_2 ]; /* On-File Record's pointwise comparison table with: */ + /* Distance,min(BetaK,BetaJ),max(BetaK,BbetaJ),K,J, ThetaKJ */ +int * scolpt[ SCOLPT_SIZE ]; /* Subject's list of pointers to pointwise comparison rows, sorted on: */ + /* Distance, min(BetaK,BetaJ), then max(BetaK,BetaJ) */ +int * fcolpt[ FCOLPT_SIZE ]; /* On-File Record's list of pointers to pointwise comparison rows sorted on: */ + /* Distance, min(BetaK,BetaJ), then max(BetaK,BetaJ) */ +int sc[ SC_SIZE ]; /* Flags all compatible edges in the Subject's Web */ + +int yl[ YL_SIZE_1 ][ YL_SIZE_2 ]; + + +/**************************************************************************/ +/* Globals used significantly by sift() */ +/**************************************************************************/ +int rq[ RQ_SIZE ] = {}; +int tq[ TQ_SIZE ] = {}; +int zz[ ZZ_SIZE ] = {}; + +int rx[ RX_SIZE ] = {}; +int mm[ MM_SIZE ] = {}; +int nn[ NN_SIZE ] = {}; + +int qq[ QQ_SIZE ] = {}; + +int rk[ RK_SIZE ] = {}; + +int cp[ CP_SIZE ] = {}; +int rp[ RP_SIZE ] = {}; + +int rf[RF_SIZE_1][RF_SIZE_2] = {}; +int cf[CF_SIZE_1][CF_SIZE_2] = {}; + +int y[20000] = {}; + diff --git a/libfprint/nbis/bozorth3/bz_io.c b/libfprint/nbis/bozorth3/bz_io.c new file mode 100644 index 00000000..8bb166f2 --- /dev/null +++ b/libfprint/nbis/bozorth3/bz_io.c @@ -0,0 +1,632 @@ +/****************************************************************************** + +This file is part of the Export Control subset of the United States NIST +Biometric Image Software (NBIS) distribution: + http://fingerprint.nist.gov/NBIS/index.html + +It is our understanding that this falls within ECCN 3D980, which covers +software associated with the development, production or use of certain +equipment controlled in accordance with U.S. concerns about crime control +practices in specific countries. + +Therefore, this file should not be exported, or made available on fileservers, +except as allowed by U.S. export control laws. + +Do not remove this notice. + +******************************************************************************/ + +/* NOTE: Despite the above notice (which I have not removed), this file is + * being legally distributed within libfprint; the U.S. Export Administration + * Regulations do not place export restrictions upon distribution of + * "publicly available technology and software", as stated in EAR section + * 734.3(b)(3)(i). libfprint qualifies as publicly available technology as per + * the definition in section 734.7(a)(1). + * + * For further information, see http://reactivated.net/fprint/US_export_control + */ + +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: FING - NIST Fingerprint Systems Utilities + + FILE: BZ_IO.C + ALGORITHM: Allan S. Bozorth (FBI) + MODIFICATIONS: Michael D. Garris (NIST) + Stan Janet (NIST) + DATE: 09/21/2004 + + Contains routines responsible for supporting command line + processing, file and data input to, and output from the + Bozorth3 fingerprint matching algorithm. + +*********************************************************************** + + ROUTINES: +#cat: parse_line_range - parses strings of the form #-# into the upper +#cat: and lower bounds of a range corresponding to lines in +#cat: an input file list +#cat: set_progname - stores the program name for the current invocation +#cat: set_probe_filename - stores the name of the current probe file +#cat: being processed +#cat: set_gallery_filename - stores the name of the current gallery file +#cat: being processed +#cat: get_progname - retrieves the program name for the current invocation +#cat: get_probe_filename - retrieves the name of the current probe file +#cat: being processed +#cat: get_gallery_filename - retrieves the name of the current gallery +#cat: file being processed +#cat: get_next_file - gets the next probe (or gallery) filename to be +#cat: processed, either from the command line or from a +#cat: file list +#cat: get_score_filename - returns the filename to which the output line +#cat: should be written +#cat: get_score_line - formats output lines based on command line options +#cat: specified +#cat: bz_load - loads the contents of the specified XYT file into +#cat: structured memory +#cat: fd_readable - when multiple bozorth processes are being run +#cat: concurrently and one of the processes determines a +#cat: has been found, the other processes poll a file +#cat: descriptor using this function to see if they +#cat: should exit as well + +***********************************************************************/ + +#include +#include +#include +#include + +static const int verbose_load = 0; +static const int verbose_main = 0; + +/***********************************************************************/ +int parse_line_range( const char * sb, int * begin, int * end ) +{ +int ib, ie; +char * se; + + +if ( ! isdigit(*sb) ) + return -1; +ib = atoi( sb ); + +se = strchr( sb, '-' ); +if ( se != (char *) NULL ) { + se++; + if ( ! isdigit(*se) ) + return -2; + ie = atoi( se ); +} else { + ie = ib; +} + +if ( ib <= 0 ) { + if ( ie <= 0 ) { + return -3; + } else { + return -4; + } +} + +if ( ie <= 0 ) { + return -5; +} + +if ( ib > ie ) + return -6; + +*begin = ib; +*end = ie; + +return 0; +} + +/***********************************************************************/ + +/* Used by the following set* and get* routines */ +static char program_buffer[ 1024 ]; +static char * pfile; +static char * gfile; + +/***********************************************************************/ +void set_progname( int use_pid, char * basename, pid_t pid ) +{ +if ( use_pid ) + sprintf( program_buffer, "%s pid %ld", basename, (long) pid ); +else + sprintf( program_buffer, "%s", basename ); +} + +/***********************************************************************/ +void set_probe_filename( char * filename ) +{ +pfile = filename; +} + +/***********************************************************************/ +void set_gallery_filename( char * filename ) +{ +gfile = filename; +} + +/***********************************************************************/ +char * get_progname( void ) +{ +return program_buffer; +} + +/***********************************************************************/ +char * get_probe_filename( void ) +{ +return pfile; +} + +/***********************************************************************/ +char * get_gallery_filename( void ) +{ +return gfile; +} + +/***********************************************************************/ +char * get_next_file( + char * fixed_file, + FILE * list_fp, + FILE * mates_fp, + int * done_now, + int * done_afterwards, + char * line, + int argc, + char ** argv, + int * optind, + + int * lineno, + int begin, + int end + ) +{ +char * p; +FILE * fp; + + + +if ( fixed_file != (char *) NULL ) { + if ( verbose_main ) + fprintf( stderr, "returning fixed filename: %s\n", fixed_file ); + return fixed_file; +} + + +fp = list_fp; +if ( fp == (FILE *) NULL ) + fp = mates_fp; +if ( fp != (FILE *) NULL ) { + while (1) { + if ( fgets( line, MAX_LINE_LENGTH, fp ) == (char *) NULL ) { + *done_now = 1; + if ( verbose_main ) + fprintf( stderr, "returning NULL -- reached EOF\n" ); + return (char *) NULL; + } + ++*lineno; + + if ( begin <= 0 ) /* no line number range was specified */ + break; + if ( *lineno > end ) { + *done_now = 1; + if ( verbose_main ) + fprintf( stderr, "returning NULL -- current line (%d) > end line (%d)\n", + *lineno, end ); + return (char *) NULL; + } + if ( *lineno >= begin ) { + break; + } + /* Otherwise ( *lineno < begin ) so read another line */ + } + + p = strchr( line, '\n' ); + if ( p == (char *) NULL ) { + *done_now = 1; + if ( verbose_main ) + fprintf( stderr, "returning NULL -- missing newline character\n" ); + return (char *) NULL; + } + *p = '\0'; + + p = line; + if ( verbose_main ) + fprintf( stderr, "returning filename from next line: %s\n", p ); + return p; +} + + +p = argv[*optind]; +++*optind; +if ( *optind >= argc ) + *done_afterwards = 1; +if ( verbose_main ) + fprintf( stderr, "returning next argv: %s [done_afterwards=%d]\n", p, *done_afterwards ); +return p; +} + +/***********************************************************************/ +/* returns CNULL on error */ +char * get_score_filename( const char * outdir, const char * listfile ) +{ +const char * basename; +int baselen; +int dirlen; +int extlen; +char * outfile; + +/* These are now exteranlly defined in bozorth.h */ +/* extern FILE * stderr; */ +/* extern char * get_progname( void ); */ + + + +basename = strrchr( listfile, '/' ); +if ( basename == CNULL ) { + basename = listfile; +} else { + ++basename; +} +baselen = strlen( basename ); +if ( baselen == 0 ) { + fprintf( stderr, "%s: ERROR: couldn't find basename of %s\n", get_progname(), listfile ); + return(CNULL); +} +dirlen = strlen( outdir ); +if ( dirlen == 0 ) { + fprintf( stderr, "%s: ERROR: illegal output directory %s\n", get_progname(), outdir ); + return(CNULL); +} + +extlen = strlen( SCOREFILE_EXTENSION ); +outfile = malloc_or_return_error( dirlen + baselen + extlen + 2, "output filename" ); +if ( outfile == CNULL) + return(CNULL); + +sprintf( outfile, "%s/%s%s", outdir, basename, SCOREFILE_EXTENSION ); + +return outfile; +} + +/***********************************************************************/ +char * get_score_line( + const char * probe_file, + const char * gallery_file, + int n, + int static_flag, + const char * fmt + ) +{ +int nchars; +char * bufptr; +static char linebuf[1024]; + +nchars = 0; +bufptr = &linebuf[0]; +while ( *fmt ) { + if ( nchars++ > 0 ) + *bufptr++ = ' '; + switch ( *fmt++ ) { + case 's': + sprintf( bufptr, "%d", n ); + break; + case 'p': + sprintf( bufptr, "%s", probe_file ); + break; + case 'g': + sprintf( bufptr, "%s", gallery_file ); + break; + default: + return (char *) NULL; + } + bufptr = strchr( bufptr, '\0' ); +} +*bufptr++ = '\n'; +*bufptr = '\0'; + +return static_flag ? &linebuf[0] : strdup( linebuf ); +} + +/************************************************************************ +Load a 3-4 column (X,Y,T[,Q]) set of minutiae from the specified file. +Row 3's value is an angle which is normalized to the interval (-180,180]. +A maximum of MAX_BOZORTH_MINUTIAE minutiae can be returned -- fewer if +"DEFAULT_BOZORTH_MINUTIAE" is smaller. If the file contains more minutiae than are +to be returned, the highest-quality minutiae are returned. +*************************************************************************/ + +/***********************************************************************/ +struct xyt_struct * bz_load( const char * xyt_file ) +{ +int nminutiae; +int j; +int m; +int nargs_expected; +FILE * fp; +struct xyt_struct * s; +int * xptr; +int * yptr; +int * tptr; +int * qptr; +struct minutiae_struct c[MAX_FILE_MINUTIAE]; +int xvals_lng[MAX_FILE_MINUTIAE], /* Temporary lists to store all the minutaie from a file */ + yvals_lng[MAX_FILE_MINUTIAE], + tvals_lng[MAX_FILE_MINUTIAE], + qvals_lng[MAX_FILE_MINUTIAE]; +int order[MAX_FILE_MINUTIAE]; /* The ranked order, after sort, for each index */ +int xvals[MAX_BOZORTH_MINUTIAE], /* Temporary lists to hold input coordinates */ + yvals[MAX_BOZORTH_MINUTIAE], + tvals[MAX_BOZORTH_MINUTIAE], + qvals[MAX_BOZORTH_MINUTIAE]; +char xyt_line[ MAX_LINE_LENGTH ]; + +/* This is now externally defined in bozorth.h */ +/* extern FILE * stderr; */ + + + +#define C1 0 +#define C2 1 + + + +fp = fopen( xyt_file, "r" ); +if ( fp == (FILE *) NULL ) { + fprintf( stderr, "%s: ERROR: fopen() of minutiae file \"%s\" failed: %s\n", + get_progname(), xyt_file, strerror(errno) ); + return XYT_NULL; +} + +nminutiae = 0; +nargs_expected = 0; +while ( fgets( xyt_line, sizeof xyt_line, fp ) != CNULL ) { + + m = sscanf( xyt_line, "%d %d %d %d", + &xvals_lng[nminutiae], + &yvals_lng[nminutiae], + &tvals_lng[nminutiae], + &qvals_lng[nminutiae] ); + if ( nminutiae == 0 ) { + if ( m != 3 && m != 4 ) { + fprintf( stderr, "%s: ERROR: sscanf() failed on line %u in minutiae file \"%s\"\n", + get_progname(), nminutiae+1, xyt_file ); + return XYT_NULL; + } + nargs_expected = m; + } else { + if ( m != nargs_expected ) { + fprintf( stderr, "%s: ERROR: inconsistent argument count on line %u of minutiae file \"%s\"\n", + get_progname(), nminutiae+1, xyt_file ); + return XYT_NULL; + } + } + if ( m == 3 ) + qvals_lng[nminutiae] = 1; + + + + if ( tvals_lng[nminutiae] > 180 ) + tvals_lng[nminutiae] -= 360; + + /* + if ( C1 ) { + c[nminutiae].col[0] = xvals_lng[nminutiae]; + c[nminutiae].col[1] = yvals_lng[nminutiae]; + c[nminutiae].col[2] = tvals_lng[nminutiae]; + c[nminutiae].col[3] = qvals_lng[nminutiae]; + } + */ + + ++nminutiae; + if ( nminutiae == MAX_FILE_MINUTIAE ) + break; +} + +if ( fclose(fp) != 0 ) { + fprintf( stderr, "%s: ERROR: fclose() of minutiae file \"%s\" failed: %s\n", + get_progname(), xyt_file, strerror(errno) ); + return XYT_NULL; +} + + + + +if ( nminutiae > DEFAULT_BOZORTH_MINUTIAE ) { + if ( verbose_load ) + fprintf( stderr, "%s: WARNING: bz_load(): trimming minutiae to the %d of highest quality\n", + get_progname(), DEFAULT_BOZORTH_MINUTIAE ); + + if ( verbose_load ) + fprintf( stderr, "Before quality sort:\n" ); + if ( sort_order_decreasing( qvals_lng, nminutiae, order )) { + fprintf( stderr, "%s: ERROR: sort failed and returned on error\n", get_progname()); + return XYT_NULL; + } + + for ( j = 0; j < nminutiae; j++ ) { + + if ( verbose_load ) + fprintf( stderr, " %3d: %3d %3d %3d ---> order = %3d\n", + j, xvals_lng[j], yvals_lng[j], qvals_lng[j], order[j] ); + + if ( j == 0 ) + continue; + if ( qvals_lng[order[j]] > qvals_lng[order[j-1]] ) { + fprintf( stderr, "%s: ERROR: sort failed: j=%d; qvals_lng[%d] > qvals_lng[%d]\n", + get_progname(), j, order[j], order[j-1] ); + return XYT_NULL; + } + } + + + if ( verbose_load ) + fprintf( stderr, "\nAfter quality sort:\n" ); + for ( j = 0; j < DEFAULT_BOZORTH_MINUTIAE; j++ ) { + xvals[j] = xvals_lng[order[j]]; + yvals[j] = yvals_lng[order[j]]; + tvals[j] = tvals_lng[order[j]]; + qvals[j] = qvals_lng[order[j]]; + if ( verbose_load ) + fprintf( stderr, " %3d: %3d %3d %3d\n", j, xvals[j], yvals[j], qvals[j] ); + } + + + if ( C1 ) { + if ( verbose_load ) + fprintf( stderr, "\nAfter qsort():\n" ); + qsort( (void *) &c, (size_t) nminutiae, sizeof(struct minutiae_struct), sort_quality_decreasing ); + for ( j = 0; j < nminutiae; j++ ) { + + if ( verbose_load ) + fprintf( stderr, "Q %3d: %3d %3d %3d\n", + j, c[j].col[0], c[j].col[1], c[j].col[3] ); + + if ( j > 0 && c[j].col[3] > c[j-1].col[3] ) { + fprintf( stderr, "%s: ERROR: sort failed: c[%d].col[3] > c[%d].col[3]\n", + get_progname(), j, j-1 ); + return XYT_NULL; + } + } + } + + if ( verbose_load ) + fprintf( stderr, "\n" ); + + xptr = xvals; + yptr = yvals; + tptr = tvals; + qptr = qvals; + + nminutiae = DEFAULT_BOZORTH_MINUTIAE; +} else{ + xptr = xvals_lng; + yptr = yvals_lng; + tptr = tvals_lng; + qptr = qvals_lng; +} + + + +for ( j=0; j < nminutiae; j++ ) { + c[j].col[0] = xptr[j]; + c[j].col[1] = yptr[j]; + c[j].col[2] = tptr[j]; + c[j].col[3] = qptr[j]; +} +qsort( (void *) &c, (size_t) nminutiae, sizeof(struct minutiae_struct), sort_x_y ); + + + + +if ( verbose_load ) { + fprintf( stderr, "\nSorted on increasing x, then increasing y\n" ); + for ( j = 0; j < nminutiae; j++ ) { + fprintf( stderr, "%d : %3d, %3d, %3d, %3d\n", j, c[j].col[0], c[j].col[1], c[j].col[2], c[j].col[3] ); + if ( j > 0 ) { + if ( c[j].col[0] < c[j-1].col[0] ) { + fprintf( stderr, "%s: ERROR: sort failed: c[%d].col[0]=%d > c[%d].col[0]=%d\n", + get_progname(), + j, c[j].col[0], j-1, c[j-1].col[0] + ); + return XYT_NULL; + } + if ( c[j].col[0] == c[j-1].col[0] && c[j].col[1] < c[j-1].col[1] ) { + fprintf( stderr, "%s: ERROR: sort failed: c[%d].col[0]=%d == c[%d].col[0]=%d; c[%d].col[0]=%d == c[%d].col[0]=%d\n", + get_progname(), + j, c[j].col[0], j-1, c[j-1].col[0], + j, c[j].col[1], j-1, c[j-1].col[1] + ); + return XYT_NULL; + } + } + } +} + + + +s = (struct xyt_struct *) malloc( sizeof( struct xyt_struct ) ); +if ( s == XYT_NULL ) { + fprintf( stderr, "%s: ERROR: malloc() failure while loading minutiae file \"%s\" failed: %s\n", + get_progname(), + xyt_file, + strerror(errno) + ); + return XYT_NULL; +} + + + +for ( j = 0; j < nminutiae; j++ ) { + s->xcol[j] = c[j].col[0]; + s->ycol[j] = c[j].col[1]; + s->thetacol[j] = c[j].col[2]; +} +s->nrows = nminutiae; + + + + +if ( verbose_load ) + fprintf( stderr, "Loaded %s\n", xyt_file ); + +return s; +} + +/***********************************************************************/ +#ifdef PARALLEL_SEARCH +int fd_readable( int fd ) +{ +int retval; +fd_set rfds; +struct timeval tv; + + +FD_ZERO( &rfds ); +FD_SET( fd, &rfds ); +tv.tv_sec = 0; +tv.tv_usec = 0; + +retval = select( fd+1, &rfds, NULL, NULL, &tv ); + +if ( retval < 0 ) { + perror( "select() failed" ); + return 0; +} + +if ( FD_ISSET( fd, &rfds ) ) { + /*fprintf( stderr, "data is available now.\n" );*/ + return 1; +} + +/* fprintf( stderr, "no data is available\n" ); */ +return 0; +} +#endif diff --git a/libfprint/nbis/bozorth3/bz_sort.c b/libfprint/nbis/bozorth3/bz_sort.c new file mode 100644 index 00000000..c7bced36 --- /dev/null +++ b/libfprint/nbis/bozorth3/bz_sort.c @@ -0,0 +1,315 @@ +/****************************************************************************** + +This file is part of the Export Control subset of the United States NIST +Biometric Image Software (NBIS) distribution: + http://fingerprint.nist.gov/NBIS/index.html + +It is our understanding that this falls within ECCN 3D980, which covers +software associated with the development, production or use of certain +equipment controlled in accordance with U.S. concerns about crime control +practices in specific countries. + +Therefore, this file should not be exported, or made available on fileservers, +except as allowed by U.S. export control laws. + +Do not remove this notice. + +******************************************************************************/ + +/* NOTE: Despite the above notice (which I have not removed), this file is + * being legally distributed within libfprint; the U.S. Export Administration + * Regulations do not place export restrictions upon distribution of + * "publicly available technology and software", as stated in EAR section + * 734.3(b)(3)(i). libfprint qualifies as publicly available technology as per + * the definition in section 734.7(a)(1). + * + * For further information, see http://reactivated.net/fprint/US_export_control + */ + +/******************************************************************************* + +License: +This software was developed at the National Institute of Standards and +Technology (NIST) by employees of the Federal Government in the course +of their official duties. Pursuant to title 17 Section 105 of the +United States Code, this software is not subject to copyright protection +and is in the public domain. NIST assumes no responsibility whatsoever for +its use by other parties, and makes no guarantees, expressed or implied, +about its quality, reliability, or any other characteristic. + +Disclaimer: +This software was developed to promote biometric standards and biometric +technology testing for the Federal Government in accordance with the USA +PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. +Specific hardware and software products identified in this software were used +in order to perform the software development. In no case does such +identification imply recommendation or endorsement by the National Institute +of Standards and Technology, nor does it imply that the products and equipment +identified are necessarily the best available for the purpose. + +*******************************************************************************/ + +/*********************************************************************** + LIBRARY: FING - NIST Fingerprint Systems Utilities + + FILE: BZ_SORT.C + ALGORITHM: Allan S. Bozorth (FBI) + MODIFICATIONS: Michael D. Garris (NIST) + Stan Janet (NIST) + DATE: 09/21/2004 + + Contains sorting routines responsible for supporting the + Bozorth3 fingerprint matching algorithm. + +*********************************************************************** + + ROUTINES: +#cat: sort_quality_decreasing - comparison function passed to stdlib +#cat: qsort() used to sort minutia qualities +#cat: sort_x_y - comparison function passed to stdlib qsort() used +#cat: to sort minutia coordinates increasing first on x +#cat: then on y +#cat: sort_order_decreasing - calls a custom quicksort that sorts +#cat: a list of integers in decreasing order + +***********************************************************************/ + +#include +#include + +/* These are now externally defined in bozorth.h */ +/* extern char * get_progname( void ); */ + +/***********************************************************************/ +int sort_quality_decreasing( const void * a, const void * b ) +{ +struct minutiae_struct * af; +struct minutiae_struct * bf; + +af = (struct minutiae_struct *) a; +bf = (struct minutiae_struct *) b; + +if ( af->col[3] > bf->col[3] ) + return -1; +if ( af->col[3] < bf->col[3] ) + return 1; +return 0; +} + +/***********************************************************************/ +int sort_x_y( const void * a, const void * b ) +{ +struct minutiae_struct * af; +struct minutiae_struct * bf; + +af = (struct minutiae_struct *) a; +bf = (struct minutiae_struct *) b; + +if ( af->col[0] < bf->col[0] ) + return -1; +if ( af->col[0] > bf->col[0] ) + return 1; + +if ( af->col[1] < bf->col[1] ) + return -1; +if ( af->col[1] > bf->col[1] ) + return 1; + +return 0; +} + +/******************************************************** +qsort_decreasing() - quicksort an array of integers in decreasing + order [based on multisort.c, by Michael Garris + and Ted Zwiesler, 1986] +********************************************************/ +/* Used by custom quicksort code below */ +static int stack[BZ_STACKSIZE]; +static int * stack_pointer = stack; + +/***********************************************************************/ +/* return values: 0 == successful, 1 == error */ +static int popstack( int *popval ) +{ +if ( --stack_pointer < stack ) { + fprintf( stderr, "%s: ERROR: popstack(): stack underflow\n", get_progname() ); + return 1; +} + +*popval = *stack_pointer; +return 0; +} + +/***********************************************************************/ +/* return values: 0 == successful, 1 == error */ +static int pushstack( int position ) +{ +*stack_pointer++ = position; +if ( stack_pointer > ( stack + BZ_STACKSIZE ) ) { + fprintf( stderr, "%s: ERROR: pushstack(): stack overflow\n", get_progname() ); + return 1; +} +return 0; +} + +/***********************************************************************/ +/******************************************************************* +select_pivot() +selects a pivot from a list being sorted using the Singleton Method. +*******************************************************************/ +static int select_pivot( struct cell v[], int left, int right ) +{ +int midpoint; + + +midpoint = ( left + right ) / 2; +if ( v[left].index <= v[midpoint].index ) { + if ( v[midpoint].index <= v[right].index ) { + return midpoint; + } else { + if ( v[right].index > v[left].index ) { + return right; + } else { + return left; + } + } +} else { + if ( v[left].index < v[right].index ) { + return left; + } else { + if ( v[right].index < v[midpoint].index ) { + return midpoint; + } else { + return right; + } + } +} +} + +/***********************************************************************/ +/******************************************************** +partition_dec() +Inputs a pivot element making comparisons and swaps with other elements in a list, +until pivot resides at its correct position in the list. +********************************************************/ +static void partition_dec( struct cell v[], int *llen, int *rlen, int *ll, int *lr, int *rl, int *rr, int p, int l, int r ) +{ +#define iswap(a,b) { int itmp = (a); a = (b); b = itmp; } + +*ll = l; +*rr = r; +while ( 1 ) { + if ( l < p ) { + if ( v[l].index < v[p].index ) { + iswap( v[l].index, v[p].index ) + iswap( v[l].item, v[p].item ) + p = l; + } else { + l++; + } + } else { + if ( r > p ) { + if ( v[r].index > v[p].index ) { + iswap( v[r].index, v[p].index ) + iswap( v[r].item, v[p].item ) + p = r; + l++; + } else { + r--; + } + } else { + *lr = p - 1; + *rl = p + 1; + *llen = *lr - *ll + 1; + *rlen = *rr - *rl + 1; + break; + } + } +} +} + +/***********************************************************************/ +/******************************************************** +qsort_decreasing() +This procedure inputs a pointer to an index_struct, the subscript of an index array to be +sorted, a left subscript pointing to where the sort is to begin in the index array, and a right +subscript where to end. This module invokes a decreasing quick-sort sorting the index array from l to r. +********************************************************/ +/* return values: 0 == successful, 1 == error */ +static int qsort_decreasing( struct cell v[], int left, int right ) +{ +int pivot; +int llen, rlen; +int lleft, lright, rleft, rright; + + +if ( pushstack( left )) + return 1; +if ( pushstack( right )) + return 2; +while ( stack_pointer != stack ) { + if (popstack(&right)) + return 3; + if (popstack(&left )) + return 4; + if ( right - left > 0 ) { + pivot = select_pivot( v, left, right ); + partition_dec( v, &llen, &rlen, &lleft, &lright, &rleft, &rright, pivot, left, right ); + if ( llen > rlen ) { + if ( pushstack( lleft )) + return 5; + if ( pushstack( lright )) + return 6; + if ( pushstack( rleft )) + return 7; + if ( pushstack( rright )) + return 8; + } else{ + if ( pushstack( rleft )) + return 9; + if ( pushstack( rright )) + return 10; + if ( pushstack( lleft )) + return 11; + if ( pushstack( lright )) + return 12; + } + } +} +return 0; +} + +/***********************************************************************/ +/* return values: 0 == successful, 1 == error */ +int sort_order_decreasing( + int values[], /* INPUT: the unsorted values themselves */ + int num, /* INPUT: the number of values */ + int order[] /* OUTPUT: the order for each of the values if sorted */ + ) +{ +int i; +struct cell * cells; + + +cells = (struct cell *) malloc( num * sizeof(struct cell) ); +if ( cells == (struct cell *) NULL ){ + fprintf( stderr, "%s: ERROR: malloc(): struct cell\n", get_progname() ); + return 1; +} + +for( i = 0; i < num; i++ ) { + cells[i].index = values[i]; + cells[i].item = i; +} + +if ( qsort_decreasing( cells, 0, num-1 ) < 0) + return 2; + +for( i = 0; i < num; i++ ) { + order[i] = cells[i].item; +} + +free( (void *) cells ); + +return 0; +} diff --git a/libfprint/nbis/include/bozorth.h b/libfprint/nbis/include/bozorth.h index 7d37b37e..dbac4094 100644 --- a/libfprint/nbis/include/bozorth.h +++ b/libfprint/nbis/include/bozorth.h @@ -186,15 +186,7 @@ struct xyt_struct { /* In: SRC/BIN/BOZORTH3/BOZORTH3.C */ /**************************************************************************/ /* Globals supporting command line options */ -extern int m1_xyt; -extern int max_minutiae; -extern int min_computable_minutiae; -extern int verbose_main; -extern int verbose_load; -extern int verbose_bozorth; extern int verbose_threshold; -/* Global supporting error reporting */ -extern FILE *errorfp; /**************************************************************************/ /* In: BZ_GBLS.C */ @@ -258,6 +250,7 @@ extern struct xyt_struct *bz_load(const char *); extern int fd_readable(int); /* In: BZ_SORT.C */ extern int sort_quality_decreasing(const void *, const void *); +extern int sort_x_y(const void *, const void *); extern int sort_order_decreasing(int [], int, int []); #endif /* !_BOZORTH_H */ From 4e5cfdf92aa305a5d8ed58fb650ccdad028742ac Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sun, 28 Oct 2007 15:45:28 +0000 Subject: [PATCH 038/184] NBIS cleanup Part 1 of many. Remove some unused/pointless code, and made some code static. --- .gitignore | 1 + libfprint/Makefile.am | 2 - libfprint/nbis/include/lfs.h | 94 ----- libfprint/nbis/include/mytime.h | 80 ---- libfprint/nbis/mindtct/binar.c | 206 ---------- libfprint/nbis/mindtct/detect.c | 364 ----------------- libfprint/nbis/mindtct/dft.c | 310 +++++++------- libfprint/nbis/mindtct/init.c | 75 ---- libfprint/nbis/mindtct/loop.c | 368 ++++++----------- libfprint/nbis/mindtct/maps.c | 165 -------- libfprint/nbis/mindtct/minutia.c | 94 ----- libfprint/nbis/mindtct/mytime.c | 60 --- libfprint/nbis/mindtct/remove.c | 294 +++++-------- libfprint/nbis/mindtct/results.c | 682 ------------------------------- libfprint/nbis/mindtct/shape.c | 52 +-- 15 files changed, 405 insertions(+), 2442 deletions(-) delete mode 100644 libfprint/nbis/include/mytime.h delete mode 100644 libfprint/nbis/mindtct/mytime.c delete mode 100644 libfprint/nbis/mindtct/results.c diff --git a/.gitignore b/.gitignore index a026bd33..8a4f1197 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,4 @@ depcomp install-sh .deps .libs +compile diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 800125ff..c537b764 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -33,10 +33,8 @@ NBIS_SRC = \ nbis/mindtct/matchpat.c \ nbis/mindtct/minutia.c \ nbis/mindtct/morph.c \ - nbis/mindtct/mytime.c \ nbis/mindtct/quality.c \ nbis/mindtct/remove.c \ - nbis/mindtct/results.c \ nbis/mindtct/ridges.c \ nbis/mindtct/shape.c \ nbis/mindtct/sort.c \ diff --git a/libfprint/nbis/include/lfs.h b/libfprint/nbis/include/lfs.h index b37147e1..f260c488 100644 --- a/libfprint/nbis/include/lfs.h +++ b/libfprint/nbis/include/lfs.h @@ -701,24 +701,15 @@ typedef struct lfsparms{ /*************************************************************************/ /* binar.c */ -extern int binarize(unsigned char **, int *, int *, - unsigned char *, const int, const int, - int *, const int, const int, - const ROTGRIDS *, const LFSPARMS *); extern int binarize_V2(unsigned char **, int *, int *, unsigned char *, const int, const int, int *, const int, const int, const ROTGRIDS *, const LFSPARMS *); -extern int binarize_image(unsigned char **, int *, int *, - unsigned char *, const int, const int, - const int *, const int, const int, const int, - const ROTGRIDS *, const int); extern int binarize_image_V2(unsigned char **, int *, int *, unsigned char *, const int, const int, const int *, const int, const int, const int, const ROTGRIDS *); extern int dirbinarize(const unsigned char *, const int, const ROTGRIDS *); -extern int isobinarize(unsigned char *, const int, const int, const int); /* block.c */ extern int block_offsets(int **, int *, int *, const int, const int, @@ -763,12 +754,6 @@ extern void fix_edge_pixel_pair(int *, int *, int *, int *, unsigned char *, const int, const int); /* detect.c */ -extern int lfs_detect_minutiae( MINUTIAE **, - int **, int **, int *, int *, - unsigned char **, int *, int *, - unsigned char *, const int, const int, - const LFSPARMS *); - extern int lfs_detect_minutiae_V2(MINUTIAE **, int **, int **, int **, int **, int *, int *, unsigned char **, int *, int *, @@ -779,13 +764,8 @@ extern int lfs_detect_minutiae_V2(MINUTIAE **, extern int dft_dir_powers(double **, unsigned char *, const int, const int, const int, const DFTWAVES *, const ROTGRIDS *); -extern void sum_rot_block_rows(int *, const unsigned char *, const int *, - const int); -extern void dft_power(double *, const int *, const DFTWAVE *, const int); extern int dft_power_stats(int *, double *, int *, double *, double **, const int, const int, const int); -extern void get_max_norm(double *, int *, double *, const double *, const int); -extern int sort_dft_waves(int *, const double *, const double *, const int); /* free.c */ extern void free_dir2rad(DIR2RAD *); @@ -818,7 +798,6 @@ extern int search_in_direction(int *, int *, int *, int *, const int, /* init.c */ extern int init_dir2rad(DIR2RAD **, const int); extern int init_dftwaves(DFTWAVES **, const double *, const int, const int); -extern int get_max_padding(const int, const int, const int, const int); extern int get_max_padding_V2(const int, const int, const int, const int); extern int init_rotgrids(ROTGRIDS **, const int, const int, const int, const double, const int, const int, const int, const int); @@ -833,8 +812,6 @@ extern int is_qmap_empty(int *, const int, const int); /* line.c */ extern int line_points(int **, int **, int *, const int, const int, const int, const int); -extern int bresenham_line_points(int **, int **, int *, - const int, const int, const int, const int); /* link.c */ extern int link_minutiae(MINUTIAE *, unsigned char *, const int, const int, @@ -872,16 +849,8 @@ extern int process_loop_V2(MINUTIAE *, const int *, const int *, const int *, const int *, const int, unsigned char *, const int, const int, int *, const LFSPARMS *); -extern void get_loop_aspect(int *, int *, double *, int *, int *, double *, - const int *, const int *, const int); extern int fill_loop(const int *, const int *, const int, unsigned char *, const int, const int); -extern void fill_partial_row(const int, const int, const int, const int, - unsigned char *, const int, const int); -extern void flood_loop(const int *, const int *, const int, - unsigned char *, const int, const int); -extern void flood_fill4(const int, const int, const int, - unsigned char *, const int, const int); /* maps.c */ extern int gen_image_maps(int **, int **, int **, int **, int *, int *, @@ -901,10 +870,6 @@ extern void smooth_direction_map(int *, int *, const int, const int, const DIR2RAD *, const LFSPARMS *); extern int gen_high_curve_map(int **, int *, const int, const int, const LFSPARMS *); -extern int gen_imap(int **, int *, int *, - unsigned char *, const int, const int, - const DIR2RAD *, const DFTWAVES *, const ROTGRIDS *, - const LFSPARMS *); extern int gen_initial_imap(int **, int *, const int, const int, unsigned char *, const int, const int, const DFTWAVES *, const ROTGRIDS *, const LFSPARMS *); @@ -935,7 +900,6 @@ extern void average_8nbr_dir(int *, double *, int *, int *, const int, extern int num_valid_8nbrs(int *, const int, const int, const int, const int); extern void smooth_imap(int *, const int, const int, const DIR2RAD *, const LFSPARMS *); -extern int gen_nmap(int **, int *, const int, const int, const LFSPARMS *); extern int vorticity(int *, const int, const int, const int, const int, const int); extern void accum_nbr_vorticity(int *, const int, const int, const int); @@ -954,9 +918,6 @@ extern void skip_repeated_vertical_pair(int *, const int, /* minutia.c */ extern int alloc_minutiae(MINUTIAE **, const int); extern int realloc_minutiae(MINUTIAE *, const int); -extern int detect_minutiae(MINUTIAE *, unsigned char *, const int, const int, - const int *, const int *, const int, const int, - const LFSPARMS *); extern int detect_minutiae_V2(MINUTIAE *, unsigned char *, const int, const int, int *, int *, int *, const int, const int, @@ -1083,58 +1044,6 @@ extern int remove_false_minutia_V2(MINUTIAE *, unsigned char *, const int, const int, int *, int *, int *, const int, const int, const LFSPARMS *); -extern int remove_holes(MINUTIAE *, unsigned char *, const int, const int, - const LFSPARMS *); -extern int remove_hooks(MINUTIAE *, - unsigned char *, const int, const int, const LFSPARMS *); -extern int remove_hooks_islands_lakes_overlaps(MINUTIAE *, unsigned char *, - const int, const int, const LFSPARMS *); -extern int remove_islands_and_lakes(MINUTIAE *, - unsigned char *, const int, const int, const LFSPARMS *); -extern int remove_malformations(MINUTIAE *, - unsigned char *, const int, const int, - int *, const int, const int, const LFSPARMS *); -extern int remove_near_invblock(MINUTIAE *, int *, const int, const int, - const LFSPARMS *); -extern int remove_near_invblock_V2(MINUTIAE *, int *, - const int, const int, const LFSPARMS *); -extern int remove_pointing_invblock(MINUTIAE *, int *, const int, const int, - const LFSPARMS *); -extern int remove_pointing_invblock_V2(MINUTIAE *, - int *, const int, const int, const LFSPARMS *); -extern int remove_overlaps(MINUTIAE *, - unsigned char *, const int, const int, const LFSPARMS *); -extern int remove_pores(MINUTIAE *, - unsigned char *, const int, const int, - int *, const int, const int, const LFSPARMS *); -extern int remove_pores_V2(MINUTIAE *, - unsigned char *, const int, const int, - int *, int *, int *, const int, const int, - const LFSPARMS *); -extern int remove_or_adjust_side_minutiae(MINUTIAE *, unsigned char *, - const int, const int, const LFSPARMS *); -extern int remove_or_adjust_side_minutiae_V2(MINUTIAE *, - unsigned char *, const int, const int, - int *, const int, const int, const LFSPARMS *); - -/* results.c */ -extern int write_text_results(char *, const int, const int, const int, - const MINUTIAE *, int *, int *, int *, int *, int *, - const int, const int); -extern int write_minutiae_XYTQ(char *ofile, const int, - const MINUTIAE *, const int, const int); -extern void dump_map(FILE *, int *, const int, const int); -extern int drawimap(int *, const int, const int, unsigned char *, - const int, const int, const ROTGRIDS *, const int); -extern void drawimap2(int *, const int *, const int, const int, - unsigned char *, const int, const int, - const double, const int, const int); -extern void drawblocks(const int *, const int, const int, - unsigned char *, const int, const int, const int ); -extern int drawrotgrid(const ROTGRIDS *, const int, unsigned char *, - const int, const int, const int, const int); -extern void dump_link_table(FILE *, const int *, const int *, const int *, - const int, const int, const int, const MINUTIAE *); /* ridges.c */ extern int count_minutiae_ridges(MINUTIAE *, @@ -1159,11 +1068,8 @@ extern int validate_ridge_crossing(const int, const int, unsigned char *, const int, const int, const int); /* shape.c */ -extern int alloc_shape(SHAPE **, const int, const int, const int, const int); extern void free_shape(SHAPE *); -extern void dump_shape(FILE *, const SHAPE *); extern int shape_from_contour(SHAPE **, const int *, const int *, const int); -extern void sort_row_on_x(ROW *); /* sort.c */ extern int sort_indices_int_inc(int **, int *, const int); diff --git a/libfprint/nbis/include/mytime.h b/libfprint/nbis/include/mytime.h deleted file mode 100644 index 4abb1ac4..00000000 --- a/libfprint/nbis/include/mytime.h +++ /dev/null @@ -1,80 +0,0 @@ -/******************************************************************************* - -License: -This software was developed at the National Institute of Standards and -Technology (NIST) by employees of the Federal Government in the course -of their official duties. Pursuant to title 17 Section 105 of the -United States Code, this software is not subject to copyright protection -and is in the public domain. NIST assumes no responsibility whatsoever for -its use by other parties, and makes no guarantees, expressed or implied, -about its quality, reliability, or any other characteristic. - -Disclaimer: -This software was developed to promote biometric standards and biometric -technology testing for the Federal Government in accordance with the USA -PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. -Specific hardware and software products identified in this software were used -in order to perform the software development. In no case does such -identification imply recommendation or endorsement by the National Institute -of Standards and Technology, nor does it imply that the products and equipment -identified are necessarily the best available for the purpose. - -*******************************************************************************/ - -#ifndef _MYTIME_H -#define _MYTIME_H - -/* this file needed to support timer and ticks */ -/* UPDATED: 03/16/2005 by MDG */ - -#ifdef TIMER -#include -#include -#endif - -#ifdef TIMER -#define set_timer(_timer_); \ - { \ - _timer_ = (unsigned long)ticks(); -#else -#define set_timer(_timer_); -#endif - -#ifdef TIMER -#define time_accum(_timer_, _var_); \ - _var_ += ((unsigned long)ticks() - _timer_)/(float)ticksPerSec(); \ - } -#else -#define time_accum(_timer_, _var_); -#endif - -#ifdef TIMER -#define print_time(_fp_, _fmt_, _var_); \ - fprintf(_fp_, _fmt_, _var_); -#else -#define print_time(_fp_, _fmt_, _var_); -#endif - -extern unsigned long ticks(void); -extern int ticksPerSec(void); - -extern unsigned long total_timer; -extern float total_time; - -extern unsigned long imap_timer; -extern float imap_time; - -extern unsigned long bin_timer; -extern float bin_time; - -extern unsigned long minutia_timer; -extern float minutia_time; - -extern unsigned long rm_minutia_timer; -extern float rm_minutia_time; - -extern unsigned long ridge_count_timer; -extern float ridge_count_time; - -#endif - diff --git a/libfprint/nbis/mindtct/binar.c b/libfprint/nbis/mindtct/binar.c index 2c4355cc..916d56e2 100644 --- a/libfprint/nbis/mindtct/binar.c +++ b/libfprint/nbis/mindtct/binar.c @@ -36,12 +36,9 @@ identified are necessarily the best available for the purpose. *********************************************************************** ROUTINES: - binarize() binarize_V2() - binarize_image() binarize_image_V2() dirbinarize() - isobinarize() ***********************************************************************/ @@ -49,58 +46,6 @@ identified are necessarily the best available for the purpose. #include #include -/************************************************************************* -************************************************************************** -#cat: binarize - Takes a padded grayscale input image and its associated ridge -#cat: direction flow NMAP and produces a binarized version of the -#cat: image. It then fills horizontal and vertical "holes" in the -#cat: binary image results. - - Input: - pdata - padded input grayscale image - pw - padded width (in pixels) of input image - ph - padded height (in pixels) of input image - nmap - 2-D vector of IMAP directions and other codes - mw - width (in blocks) of the NMAP - mh - height (in blocks) of the NMAP - dirbingrids - set of rotated grid offsets used for directional - binarization - lfsparms - parameters and thresholds for controlling LFS - Output: - optr - points to created (unpadded) binary image - ow - width of binary image - oh - height of binary image - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int binarize(unsigned char **optr, int *ow, int *oh, - unsigned char *pdata, const int pw, const int ph, - int *nmap, const int mw, const int mh, - const ROTGRIDS *dirbingrids, const LFSPARMS *lfsparms) -{ - unsigned char *bdata; - int i, bw, bh, ret; /* return code */ - - /* 1. Binarize the padded input image using NMAP information. */ - if((ret = binarize_image(&bdata, &bw, &bh, pdata, pw, ph, - nmap, mw, mh, lfsparms->blocksize, - dirbingrids, lfsparms->isobin_grid_dim))){ - return(ret); - } - - /* 2. Fill black and white holes in binary image. */ - /* LFS scans the binary image, filling holes, 3 times. */ - for(i = 0; i < lfsparms->num_fill_holes; i++) - fill_holes(bdata, bw, bh); - - /* Return binarized input image. */ - *optr = bdata; - *ow = bw; - *oh = bh; - return(0); -} - /************************************************************************* ************************************************************************** #cat: binarize_V2 - Takes a padded grayscale input image and its associated @@ -156,89 +101,6 @@ int binarize_V2(unsigned char **odata, int *ow, int *oh, return(0); } -/************************************************************************* -************************************************************************** -#cat: binarize_image - Takes a grayscale input image and its associated -#cat: NMAP and generates a binarized version of the image. - - Input: - pdata - padded input grayscale image - pw - padded width (in pixels) of input image - ph - padded height (in pixels) of input image - nmap - 2-D vector of IMAP directions and other codes - mw - width (in blocks) of the NMAP - mh - height (in blocks) of the NMAP - imap_blocksize - dimension (in pixels) of each NMAP block - dirbingrids - set of rotated grid offsets used for directional - binarization - isobin_grid_dim - dimension (in pixels) of grid used for isotropic - binarization - Output: - optr - points to binary image results - ow - points to binary image width - oh - points to binary image height - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int binarize_image(unsigned char **optr, int *ow, int *oh, - unsigned char *pdata, const int pw, const int ph, - const int *nmap, const int mw, const int mh, - const int imap_blocksize, const ROTGRIDS *dirbingrids, - const int isobin_grid_dim) -{ - int ix, iy, bw, bh, bx, by, nmapval; - unsigned char *bdata, *bptr; - unsigned char *pptr, *spptr; - - /* Compute dimensions of "unpadded" binary image results. */ - bw = pw - (dirbingrids->pad<<1); - bh = ph - (dirbingrids->pad<<1); - - bdata = (unsigned char *)malloc(bw*bh*sizeof(unsigned char)); - if(bdata == (unsigned char *)NULL){ - fprintf(stderr, "ERROR : binarize_image : malloc : bdata\n"); - return(-110); - } - - bptr = bdata; - spptr = pdata + (dirbingrids->pad * pw) + dirbingrids->pad; - for(iy = 0; iy < bh; iy++){ - /* Set pixel pointer to start of next row in grid. */ - pptr = spptr; - for(ix = 0; ix < bw; ix++){ - /* Compute which block the current pixel is in. */ - bx = (int)(ix/imap_blocksize); - by = (int)(iy/imap_blocksize); - /* Get corresponding value in NMAP */ - nmapval = *(nmap + (by*mw) + bx); - /* If current block has no neighboring blocks with */ - /* VALID directions ... */ - if(nmapval == NO_VALID_NBRS) - /* Set binary pixel to white (255). */ - *bptr = WHITE_PIXEL; - /* Otherwise, if block's NMAP has a valid direction ... */ - else if(nmapval >= 0) - /* Use directional binarization based on NMAP direction. */ - *bptr = dirbinarize(pptr, nmapval, dirbingrids); - else - /* Otherwise, the block's NMAP is either INVALID or */ - /* HIGH-CURVATURE, so use isotropic binarization. */ - *bptr = isobinarize(pptr, pw, ph, isobin_grid_dim); - /* Bump input and output pixel pointers. */ - pptr++; - bptr++; - } - /* Bump pointer to the next row in padded input image. */ - spptr += pw; - } - - *optr = bdata; - *ow = bw; - *oh = bh; - return(0); -} - /************************************************************************* ************************************************************************** #cat: binarize_image_V2 - Takes a grayscale input image and its associated @@ -385,71 +247,3 @@ int dirbinarize(const unsigned char *pptr, const int idir, return(WHITE_PIXEL); } -/************************************************************************* -************************************************************************** -#cat: isobinarize - Determines the binary value of a grayscale pixel based -#cat: on comparing the grayscale value with a surrounding -#cat: neighborhood grid of pixels. If the current pixel (treated -#cat: as an average) is less than the sum of the pixels in -#cat: the neighborhood, then the binary value is set to BLACK, -#cat: otherwise it is set to WHITE. This binarization technique -#cat: is used when there is no VALID IMAP direction for the -#cat: block in which the current pixel resides. - - CAUTION: The image to which the input pixel points must be appropriately - padded to account for the radius of the neighborhood. Otherwise, - this routine may access "unkown" memory. - - Input: - pptr - pointer to curent grayscale pixel - pw - padded width (in pixels) of the grayscale image - ph - padded height (in pixels) of the grayscale image - isobin_grid_dim - dimension (in pixels) of the neighborhood - Return Code: - BLACK_PIXEL - pixel intensity for BLACK - WHITE_PIXEL - pixel intensity of WHITE -**************************************************************************/ -int isobinarize(unsigned char *pptr, const int pw, const int ph, - const int isobin_grid_dim) -{ - unsigned char *sptr, *cptr; - int px, py; - int radius; - int bsum; - double drad; - - /* Initialize grid pixel sum to zero. */ - bsum = 0; - /* Compute radius from current pixel based on isobin_grid_dim. */ - drad = (isobin_grid_dim - 1)/(double)2.0; - /* Need to truncate precision so that answers are consistent */ - /* on different computer architectures when rounding doubles. */ - drad = trunc_dbl_precision(drad, TRUNC_SCALE); - radius = sround(drad); - /* Set pointer to origin of grid centered on the current pixel. */ - sptr = pptr - (radius*pw) - radius; - - /* For each row in the grid ... */ - for(py = 0; py < isobin_grid_dim; py++){ - /* Set pixel pointer to start of next row in grid. */ - cptr = sptr; - /* For each column in the grid ... */ - for(px = 0; px < isobin_grid_dim; px++){ - /* Accumulate next pixel in the grid. */ - bsum += *cptr; - /* Bump pixel pointer. */ - cptr++; - } - /* Bump to the start of the next row in the grid. */ - sptr += pw; - } - - /* If current (center) pixel when treated as an average for the */ - /* entire grid is less than the total pixel sum of the grid ... */ - if((*pptr * isobin_grid_dim * isobin_grid_dim) < bsum) - /* Set the binary pixel to BLACK. */ - return(BLACK_PIXEL); - else - /* Otherwise, set the binary pixel to WHITE. */ - return(WHITE_PIXEL); -} diff --git a/libfprint/nbis/mindtct/detect.c b/libfprint/nbis/mindtct/detect.c index 3f567384..3b05d21c 100644 --- a/libfprint/nbis/mindtct/detect.c +++ b/libfprint/nbis/mindtct/detect.c @@ -35,7 +35,6 @@ identified are necessarily the best available for the purpose. *********************************************************************** ROUTINES: - lfs_detect_minutiae() lfs_detect_minutiae_V2() ***********************************************************************/ @@ -43,330 +42,8 @@ identified are necessarily the best available for the purpose. #include #include #include -#include #include -/************************************************************************* -#cat: lfs_detect_minutiae - Takes a grayscale fingerprint image (of arbitrary -#cat: size), and returns a map of directional ridge flow in the image -#cat: (2 versions), a binarized image designating ridges from valleys, -#cat: and a list of minutiae (including position, type, direction, -#cat: neighbors, and ridge counts to neighbors). - - Input: - idata - input 8-bit grayscale fingerprint image data - iw - width (in pixels) of the image - ih - height (in pixels) of the image - lfsparms - parameters and thresholds for controlling LFS - Output: - ominutiae - resulting list of minutiae - oimap - resulting IMAP - {invalid (-1) or valid ridge directions} - onmap - resulting NMAP - {invalid (-1), high-curvature (-2), blanked blocks {-3} or - valid ridge directions} - omw - width (in blocks) of image maps - omh - height (in blocks) of image maps - obdata - resulting binarized image - {0 = black pixel (ridge) and 255 = white pixel (valley)} - obw - width (in pixels) of the binary image - obh - height (in pixels) of the binary image - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int lfs_detect_minutiae(MINUTIAE **ominutiae, - int **oimap, int **onmap, int *omw, int *omh, - unsigned char **obdata, int *obw, int *obh, - unsigned char *idata, const int iw, const int ih, - const LFSPARMS *lfsparms) -{ - unsigned char *pdata, *bdata; - int pw, ph, bw, bh; - DIR2RAD *dir2rad; - DFTWAVES *dftwaves; - ROTGRIDS *dftgrids; - ROTGRIDS *dirbingrids; - int *imap, *nmap, mw, mh; - int ret, maxpad; - MINUTIAE *minutiae; - - set_timer(total_timer); - - /******************/ - /* INITIALIZATION */ - /******************/ - - /* If LOG_REPORT defined, open log report file. */ - if((ret = open_logfile())) - /* If system error, exit with error code. */ - return(ret); - - /* Determine the maximum amount of image padding required to support */ - /* LFS processes. */ - maxpad = get_max_padding(lfsparms->blocksize, - lfsparms->dirbin_grid_w, lfsparms->dirbin_grid_h, - lfsparms->isobin_grid_dim); - - /* Initialize lookup table for converting integer IMAP directions */ - /* to angles in radians. */ - if((ret = init_dir2rad(&dir2rad, lfsparms->num_directions))){ - /* Free memory allocated to this point. */ - return(ret); - } - - /* Initialize wave form lookup tables for DFT analyses. */ - /* used for direction binarization. */ - if((ret = init_dftwaves(&dftwaves, dft_coefs, lfsparms->num_dft_waves, - lfsparms->blocksize))){ - /* Free memory allocated to this point. */ - free_dir2rad(dir2rad); - return(ret); - } - - /* Initialize lookup table for pixel offsets to rotated grids */ - /* used for DFT analyses. */ - if((ret = init_rotgrids(&dftgrids, iw, ih, maxpad, - lfsparms->start_dir_angle, lfsparms->num_directions, - lfsparms->blocksize, lfsparms->blocksize, - RELATIVE2ORIGIN))){ - /* Free memory allocated to this point. */ - free_dir2rad(dir2rad); - free_dftwaves(dftwaves); - return(ret); - } - - /* Pad input image based on max padding. */ - if(maxpad > 0){ /* May not need to pad at all */ - if((ret = pad_uchar_image(&pdata, &pw, &ph, idata, iw, ih, - maxpad, lfsparms->pad_value))){ - /* Free memory allocated to this point. */ - free_dir2rad(dir2rad); - free_dftwaves(dftwaves); - free_rotgrids(dftgrids); - return(ret); - } - } - else{ - /* If padding is unnecessary, then copy the input image. */ - pdata = (unsigned char *)malloc(iw*ih); - if(pdata == (unsigned char *)NULL){ - /* Free memory allocated to this point. */ - free_dir2rad(dir2rad); - free_dftwaves(dftwaves); - free_rotgrids(dftgrids); - fprintf(stderr, "ERROR : lfs_detect_minutiae : malloc : pdata\n"); - return(-430); - } - memcpy(pdata, idata, iw*ih); - pw = iw; - ph = ih; - } - - /* Scale input image to 6 bits [0..63] */ - /* !!! Would like to remove this dependency eventualy !!! */ - /* But, the DFT computations will need to be changed, and */ - /* could not get this work upon first attempt. */ - bits_8to6(pdata, pw, ph); - - print2log("\nINITIALIZATION AND PADDING DONE\n"); - - /******************/ - /* IMAP */ - /******************/ - set_timer(imap_timer); - - /* Generate IMAP for the input image. */ - if((ret = gen_imap(&imap, &mw, &mh, pdata, pw, ph, dir2rad, - dftwaves, dftgrids, lfsparms))){ - /* Free memory allocated to this point. */ - free_dir2rad(dir2rad); - free_dftwaves(dftwaves); - free_rotgrids(dftgrids); - free(pdata); - return(ret); - } - - free_dir2rad(dir2rad); - free_dftwaves(dftwaves); - free_rotgrids(dftgrids); - - print2log("\nIMAP DONE\n"); - - /* Generate NMAP from the IMAP of the input image. */ - if((ret = gen_nmap(&nmap, imap, mw, mh, lfsparms))){ - /* Free memory allocated to this point. */ - free(pdata); - free(imap); - return(ret); - } - - print2log("\nNMAP DONE\n"); - - time_accum(imap_timer, imap_time); - - /******************/ - /* BINARIZARION */ - /******************/ - set_timer(bin_timer); - - /* Initialize lookup table for pixel offsets to rotated grids */ - /* used for directional binarization. */ - if((ret = init_rotgrids(&dirbingrids, iw, ih, maxpad, - lfsparms->start_dir_angle, lfsparms->num_directions, - lfsparms->dirbin_grid_w, lfsparms->dirbin_grid_h, - RELATIVE2CENTER))){ - /* Free memory allocated to this point. */ - free(pdata); - free(imap); - free(nmap); - return(ret); - } - - /* Binarize input image based on NMAP information. */ - if((ret = binarize(&bdata, &bw, &bh, pdata, pw, ph, nmap, mw, mh, - dirbingrids, lfsparms))){ - /* Free memory allocated to this point. */ - free(pdata); - free(imap); - free(nmap); - free_rotgrids(dirbingrids); - return(ret); - } - free_rotgrids(dirbingrids); - - /* Check dimension of binary image. If they are different from */ - /* the input image, then ERROR. */ - if((iw != bw) || (ih != bh)){ - /* Free memory allocated to this point. */ - free(pdata); - free(imap); - free(nmap); - free(bdata); - fprintf(stderr, - "ERROR : lfs_detect_minutiae : binary image has bad dimensions : %d, %d\n", - bw, bh); - return(-431); - } - - print2log("\nBINARIZATION DONE\n"); - - time_accum(bin_timer, bin_time); - - /******************/ - /* DETECTION */ - /******************/ - set_timer(minutia_timer); - - /* Convert 8-bit grayscale binary image [0,255] to */ - /* 8-bit binary image [0,1]. */ - gray2bin(1, 1, 0, bdata, iw, ih); - - /* Allocate list of maximum number of minutia pointers. */ - if((ret = alloc_minutiae(&minutiae, MAX_MINUTIAE))){ - return(ret); - } - - /* Detect the minutiae in the binarized image. */ - if((ret = detect_minutiae(minutiae, bdata, iw, ih, imap, nmap, mw, mh, - lfsparms))){ - /* Free memory allocated to this point. */ - free(pdata); - free(imap); - free(nmap); - free(bdata); - return(ret); - } - - time_accum(minutia_timer, minutia_time); - - set_timer(rm_minutia_timer); - - if((ret = remove_false_minutia(minutiae, bdata, iw, ih, nmap, mw, mh, - lfsparms))){ - /* Free memory allocated to this point. */ - free(pdata); - free(imap); - free(nmap); - free(bdata); - free_minutiae(minutiae); - return(ret); - } - - print2log("\nMINUTIA DETECTION DONE\n"); - - time_accum(rm_minutia_timer, rm_minutia_time); - - /******************/ - /* RIDGE COUNTS */ - /******************/ - set_timer(ridge_count_timer); - - if((ret = count_minutiae_ridges(minutiae, bdata, iw, ih, lfsparms))){ - /* Free memory allocated to this point. */ - free(pdata); - free(imap); - free(nmap); - free(bdata); - free_minutiae(minutiae); - return(ret); - } - - - print2log("\nNEIGHBOR RIDGE COUNT DONE\n"); - - time_accum(ridge_count_timer, ridge_count_time); - - /******************/ - /* WRAP-UP */ - /******************/ - - /* Convert 8-bit binary image [0,1] to 8-bit */ - /* grayscale binary image [0,255]. */ - gray2bin(1, 255, 0, bdata, iw, ih); - - /* Deallocate working memory. */ - free(pdata); - - /* Assign results to output pointers. */ - *oimap = imap; - *onmap = nmap; - *omw = mw; - *omh = mh; - *obdata = bdata; - *obw = bw; - *obh = bh; - *ominutiae = minutiae; - - time_accum(total_timer, total_time); - - /******************/ - /* PRINT TIMINGS */ - /******************/ - /* These Timings will print when TIMER is defined. */ - /* print IMAP generation timing statistics */ - print_time(stderr, "TIMER: IMAP time = %f (secs)\n", imap_time); - /* print binarization timing statistics */ - print_time(stderr, "TIMER: Binarization time = %f (secs)\n", bin_time); - /* print minutia detection timing statistics */ - print_time(stderr, "TIMER: Minutia Detection time = %f (secs)\n", - minutia_time); - /* print minutia removal timing statistics */ - print_time(stderr, "TIMER: Minutia Removal time = %f (secs)\n", - rm_minutia_time); - /* print neighbor ridge count timing statistics */ - print_time(stderr, "TIMER: Neighbor Ridge Counting time = %f (secs)\n", - ridge_count_time); - /* print total timing statistics */ - print_time(stderr, "TIMER: Total time = %f (secs)\n", total_time); - - /* If LOG_REPORT defined, close log report file. */ - if((ret = close_logfile())) - return(ret); - - return(0); -} - /************************************************************************* #cat: lfs_detect_minutiae_V2 - Takes a grayscale fingerprint image (of #cat: arbitrary size), and returns a set of image block maps, @@ -421,8 +98,6 @@ int lfs_detect_minutiae_V2(MINUTIAE **ominutiae, int ret, maxpad; MINUTIAE *minutiae; - set_timer(total_timer); - /******************/ /* INITIALIZATION */ /******************/ @@ -505,7 +180,6 @@ int lfs_detect_minutiae_V2(MINUTIAE **ominutiae, /******************/ /* MAPS */ /******************/ - set_timer(imap_timer); /* Generate block maps from the input image. */ if((ret = gen_image_maps(&direction_map, &low_contrast_map, @@ -525,12 +199,9 @@ int lfs_detect_minutiae_V2(MINUTIAE **ominutiae, print2log("\nMAPS DONE\n"); - time_accum(imap_timer, imap_time); - /******************/ /* BINARIZARION */ /******************/ - set_timer(bin_timer); /* Initialize lookup table for pixel offsets to rotated grids */ /* used for directional binarization. */ @@ -582,12 +253,9 @@ int lfs_detect_minutiae_V2(MINUTIAE **ominutiae, print2log("\nBINARIZATION DONE\n"); - time_accum(bin_timer, bin_time); - /******************/ /* DETECTION */ /******************/ - set_timer(minutia_timer); /* Convert 8-bit grayscale binary image [0,255] to */ /* 8-bit binary image [0,1]. */ @@ -612,10 +280,6 @@ int lfs_detect_minutiae_V2(MINUTIAE **ominutiae, return(ret); } - time_accum(minutia_timer, minutia_time); - - set_timer(rm_minutia_timer); - if((ret = remove_false_minutia_V2(minutiae, bdata, iw, ih, direction_map, low_flow_map, high_curve_map, mw, mh, lfsparms))){ @@ -632,13 +296,9 @@ int lfs_detect_minutiae_V2(MINUTIAE **ominutiae, print2log("\nMINUTIA DETECTION DONE\n"); - time_accum(rm_minutia_timer, rm_minutia_time); - /******************/ /* RIDGE COUNTS */ /******************/ - set_timer(ridge_count_timer); - if((ret = count_minutiae_ridges(minutiae, bdata, iw, ih, lfsparms))){ /* Free memory allocated to this point. */ free(pdata); @@ -653,8 +313,6 @@ int lfs_detect_minutiae_V2(MINUTIAE **ominutiae, print2log("\nNEIGHBOR RIDGE COUNT DONE\n"); - time_accum(ridge_count_timer, ridge_count_time); - /******************/ /* WRAP-UP */ /******************/ @@ -678,28 +336,6 @@ int lfs_detect_minutiae_V2(MINUTIAE **ominutiae, *obh = bh; *ominutiae = minutiae; - time_accum(total_timer, total_time); - - /******************/ - /* PRINT TIMINGS */ - /******************/ - /* These Timings will print when TIMER is defined. */ - /* print MAP generation timing statistics */ - print_time(stderr, "TIMER: MAPS time = %f (secs)\n", imap_time); - /* print binarization timing statistics */ - print_time(stderr, "TIMER: Binarization time = %f (secs)\n", bin_time); - /* print minutia detection timing statistics */ - print_time(stderr, "TIMER: Minutia Detection time = %f (secs)\n", - minutia_time); - /* print minutia removal timing statistics */ - print_time(stderr, "TIMER: Minutia Removal time = %f (secs)\n", - rm_minutia_time); - /* print neighbor ridge count timing statistics */ - print_time(stderr, "TIMER: Neighbor Ridge Counting time = %f (secs)\n", - ridge_count_time); - /* print total timing statistics */ - print_time(stderr, "TIMER: Total time = %f (secs)\n", total_time); - /* If LOG_REPORT defined, close log report file. */ if((ret = close_logfile())) return(ret); diff --git a/libfprint/nbis/mindtct/dft.c b/libfprint/nbis/mindtct/dft.c index 1159fa16..af136536 100644 --- a/libfprint/nbis/mindtct/dft.c +++ b/libfprint/nbis/mindtct/dft.c @@ -47,6 +47,84 @@ identified are necessarily the best available for the purpose. #include #include +/************************************************************************* +************************************************************************** +#cat: sum_rot_block_rows - Computes a vector or pixel row sums by sampling +#cat: the current image block at a given orientation. The +#cat: sampling is conducted using a precomputed set of rotated +#cat: pixel offsets (called a grid) relative to the orgin of +#cat: the image block. + + Input: + blkptr - the pixel address of the origin of the current image block + grid_offsets - the rotated pixel offsets for a block-sized grid + rotated according to a specific orientation + blocksize - the width and height of the image block and thus the size + of the rotated grid + Output: + rowsums - the resulting vector of pixel row sums +**************************************************************************/ +static void sum_rot_block_rows(int *rowsums, const unsigned char *blkptr, + const int *grid_offsets, const int blocksize) +{ + int ix, iy, gi; + + /* Initialize rotation offset index. */ + gi = 0; + + /* For each row in block ... */ + for(iy = 0; iy < blocksize; iy++){ + /* The sums are accumlated along the rotated rows of the grid, */ + /* so initialize row sum to 0. */ + rowsums[iy] = 0; + /* Foreach column in block ... */ + for(ix = 0; ix < blocksize; ix++){ + /* Accumulate pixel value at rotated grid position in image */ + rowsums[iy] += *(blkptr + grid_offsets[gi]); + gi++; + } + } +} + +/************************************************************************* +************************************************************************** +#cat: dft_power - Computes the DFT power by applying a specific wave form +#cat: frequency to a vector of pixel row sums computed from a +#cat: specific orientation of the block image + + Input: + rowsums - accumulated rows of pixels from within a rotated grid + overlaying an input image block + wave - the wave form (cosine and sine components) at a specific + frequency + wavelen - the length of the wave form (must match the height of the + image block which is the length of the rowsum vector) + Output: + power - the computed DFT power for the given wave form at the + given orientation within the image block +**************************************************************************/ +static void dft_power(double *power, const int *rowsums, + const DFTWAVE *wave, const int wavelen) +{ + int i; + double cospart, sinpart; + + /* Initialize accumulators */ + cospart = 0.0; + sinpart = 0.0; + + /* Accumulate cos and sin components of DFT. */ + for(i = 0; i < wavelen; i++){ + /* Multiply each rotated row sum by its */ + /* corresponding cos or sin point in DFT wave. */ + cospart += (rowsums[i] * wave->cos[i]); + sinpart += (rowsums[i] * wave->sin[i]); + } + + /* Power is the sum of the squared cos and sin components */ + *power = (cospart * cospart) + (sinpart * sinpart); +} + /************************************************************************* ************************************************************************** #cat: dft_dir_powers - Conducts the DFT analysis on a block of image data. @@ -121,80 +199,105 @@ int dft_dir_powers(double **powers, unsigned char *pdata, /************************************************************************* ************************************************************************** -#cat: sum_rot_block_rows - Computes a vector or pixel row sums by sampling -#cat: the current image block at a given orientation. The -#cat: sampling is conducted using a precomputed set of rotated -#cat: pixel offsets (called a grid) relative to the orgin of -#cat: the image block. +#cat: get_max_norm - Analyses a DFT power vector for a specific wave form +#cat: applied at different orientations (directions) to the +#cat: current image block. The routine retuns the maximum +#cat: power value in the vector, the direction at which the +#cat: maximum occurs, and a normalized power value. The +#cat: normalized power is computed as the maximum power divided +#cat: by the average power across all the directions. These +#cat: simple statistics are fundamental to the selection of +#cat: a dominant direction flow for the image block. Input: - blkptr - the pixel address of the origin of the current image block - grid_offsets - the rotated pixel offsets for a block-sized grid - rotated according to a specific orientation - blocksize - the width and height of the image block and thus the size - of the rotated grid + power_vector - the DFT power values derived form a specific wave form + applied at different directions + ndirs - the number of directions to which the wave form was applied Output: - rowsums - the resulting vector of pixel row sums + powmax - the maximum power value in the DFT power vector + powmax_dir - the direciton at which the maximum power value occured + pownorm - the normalized power corresponding to the maximum power **************************************************************************/ -void sum_rot_block_rows(int *rowsums, const unsigned char *blkptr, - const int *grid_offsets, const int blocksize) +static void get_max_norm(double *powmax, int *powmax_dir, + double *pownorm, const double *power_vector, const int ndirs) { - int ix, iy, gi; + int dir; + double max_v, powsum; + int max_i; + double powmean; - /* Initialize rotation offset index. */ - gi = 0; + /* Find max power value and store corresponding direction */ + max_v = power_vector[0]; + max_i = 0; - /* For each row in block ... */ - for(iy = 0; iy < blocksize; iy++){ - /* The sums are accumlated along the rotated rows of the grid, */ - /* so initialize row sum to 0. */ - rowsums[iy] = 0; - /* Foreach column in block ... */ - for(ix = 0; ix < blocksize; ix++){ - /* Accumulate pixel value at rotated grid position in image */ - rowsums[iy] += *(blkptr + grid_offsets[gi]); - gi++; + /* Sum the total power in a block at a given direction */ + powsum = power_vector[0]; + + /* For each direction ... */ + for(dir = 1; dir < ndirs; dir++){ + powsum += power_vector[dir]; + if(power_vector[dir] > max_v){ + max_v = power_vector[dir]; + max_i = dir; } } + + *powmax = max_v; + *powmax_dir = max_i; + + /* Powmean is used as denominator for pownorm, so setting */ + /* a non-zero minimum avoids possible division by zero. */ + powmean = max(powsum, MIN_POWER_SUM)/(double)ndirs; + + *pownorm = *powmax / powmean; } /************************************************************************* ************************************************************************** -#cat: dft_power - Computes the DFT power by applying a specific wave form -#cat: frequency to a vector of pixel row sums computed from a -#cat: specific orientation of the block image +#cat: sort_dft_waves - Creates a ranked list of DFT wave form statistics +#cat: by sorting on the normalized squared maximum power. Input: - rowsums - accumulated rows of pixels from within a rotated grid - overlaying an input image block - wave - the wave form (cosine and sine components) at a specific - frequency - wavelen - the length of the wave form (must match the height of the - image block which is the length of the rowsum vector) + powmaxs - maximum DFT power for each wave form used to derive + statistics + pownorms - normalized maximum power corresponding to values in powmaxs + nstats - number of wave forms used to derive statistics (N Wave - 1) Output: - power - the computed DFT power for the given wave form at the - given orientation within the image block + wis - sorted list of indices corresponding to the ranked set of + wave form statistics. These indices will be used as + indirect addresses when processing the power statistics + in descending order of "dominance" + Return Code: + Zero - successful completion + Negative - system error **************************************************************************/ -void dft_power(double *power, const int *rowsums, - const DFTWAVE *wave, const int wavelen) +static int sort_dft_waves(int *wis, const double *powmaxs, const double *pownorms, + const int nstats) { int i; - double cospart, sinpart; + double *pownorms2; - /* Initialize accumulators */ - cospart = 0.0; - sinpart = 0.0; - - /* Accumulate cos and sin components of DFT. */ - for(i = 0; i < wavelen; i++){ - /* Multiply each rotated row sum by its */ - /* corresponding cos or sin point in DFT wave. */ - cospart += (rowsums[i] * wave->cos[i]); - sinpart += (rowsums[i] * wave->sin[i]); + /* Allocate normalized power^2 array */ + pownorms2 = (double *)malloc(nstats * sizeof(double)); + if(pownorms2 == (double *)NULL){ + fprintf(stderr, "ERROR : sort_dft_waves : malloc : pownorms2\n"); + return(-100); } - /* Power is the sum of the squared cos and sin components */ - *power = (cospart * cospart) + (sinpart * sinpart); + for(i = 0; i < nstats; i++){ + /* Wis will hold the sorted statistic indices when all is done. */ + wis[i] = i; + /* This is normalized squared max power. */ + pownorms2[i] = powmaxs[i] * pownorms[i]; + } + + /* Sort the statistic indices on the normalized squared power. */ + bubble_sort_double_dec_2(pownorms2, wis, nstats); + + /* Deallocate the working memory. */ + free(pownorms2); + + return(0); } /************************************************************************* @@ -253,106 +356,3 @@ int dft_power_stats(int *wis, double *powmaxs, int *powmax_dirs, return(0); } -/************************************************************************* -************************************************************************** -#cat: get_max_norm - Analyses a DFT power vector for a specific wave form -#cat: applied at different orientations (directions) to the -#cat: current image block. The routine retuns the maximum -#cat: power value in the vector, the direction at which the -#cat: maximum occurs, and a normalized power value. The -#cat: normalized power is computed as the maximum power divided -#cat: by the average power across all the directions. These -#cat: simple statistics are fundamental to the selection of -#cat: a dominant direction flow for the image block. - - Input: - power_vector - the DFT power values derived form a specific wave form - applied at different directions - ndirs - the number of directions to which the wave form was applied - Output: - powmax - the maximum power value in the DFT power vector - powmax_dir - the direciton at which the maximum power value occured - pownorm - the normalized power corresponding to the maximum power -**************************************************************************/ -void get_max_norm(double *powmax, int *powmax_dir, - double *pownorm, const double *power_vector, const int ndirs) -{ - int dir; - double max_v, powsum; - int max_i; - double powmean; - - /* Find max power value and store corresponding direction */ - max_v = power_vector[0]; - max_i = 0; - - /* Sum the total power in a block at a given direction */ - powsum = power_vector[0]; - - /* For each direction ... */ - for(dir = 1; dir < ndirs; dir++){ - powsum += power_vector[dir]; - if(power_vector[dir] > max_v){ - max_v = power_vector[dir]; - max_i = dir; - } - } - - *powmax = max_v; - *powmax_dir = max_i; - - /* Powmean is used as denominator for pownorm, so setting */ - /* a non-zero minimum avoids possible division by zero. */ - powmean = max(powsum, MIN_POWER_SUM)/(double)ndirs; - - *pownorm = *powmax / powmean; -} - -/************************************************************************* -************************************************************************** -#cat: sort_dft_waves - Creates a ranked list of DFT wave form statistics -#cat: by sorting on the normalized squared maximum power. - - Input: - powmaxs - maximum DFT power for each wave form used to derive - statistics - pownorms - normalized maximum power corresponding to values in powmaxs - nstats - number of wave forms used to derive statistics (N Wave - 1) - Output: - wis - sorted list of indices corresponding to the ranked set of - wave form statistics. These indices will be used as - indirect addresses when processing the power statistics - in descending order of "dominance" - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int sort_dft_waves(int *wis, const double *powmaxs, const double *pownorms, - const int nstats) -{ - int i; - double *pownorms2; - - /* Allocate normalized power^2 array */ - pownorms2 = (double *)malloc(nstats * sizeof(double)); - if(pownorms2 == (double *)NULL){ - fprintf(stderr, "ERROR : sort_dft_waves : malloc : pownorms2\n"); - return(-100); - } - - for(i = 0; i < nstats; i++){ - /* Wis will hold the sorted statistic indices when all is done. */ - wis[i] = i; - /* This is normalized squared max power. */ - pownorms2[i] = powmaxs[i] * pownorms[i]; - } - - /* Sort the statistic indices on the normalized squared power. */ - bubble_sort_double_dec_2(pownorms2, wis, nstats); - - /* Deallocate the working memory. */ - free(pownorms2); - - return(0); -} - diff --git a/libfprint/nbis/mindtct/init.c b/libfprint/nbis/mindtct/init.c index 44141652..50dc0d7e 100644 --- a/libfprint/nbis/mindtct/init.c +++ b/libfprint/nbis/mindtct/init.c @@ -37,7 +37,6 @@ identified are necessarily the best available for the purpose. ROUTINES: init_dir2rad() init_dftwaves() - get_max_padding() get_max_padding_V2() init_rotgrids() alloc_dir_powers() @@ -243,80 +242,6 @@ int init_dftwaves(DFTWAVES **optr, const double *dft_coefs, return(0); } -/************************************************************************* -************************************************************************** -#cat: get_max_padding - Deterines the maximum amount of image pixel padding -#cat: required by all LFS processes. Padding is currently -#cat: required by the rotated grids used in DFT analyses, -#cat: rotated grids used in directional binarization, -#cat: and in the grid used for isotropic binarization. -#cat: The NIST generalized code enables the parameters -#cat: governing these processes to be redefined, so a check -#cat: at runtime is required to determine which process -#cat: requires the most padding. By using the maximum as -#cat: the padding factor, all processes will run safely -#cat: with a single padding of the input image avoiding the -#cat: need to repad for further processes. - - Input: - imap_blocksize - the size (in pixels) of each IMAP block in the image - dirbin_grid_w - the width (in pixels) of the rotated grids used in - directional binarization - dirbin_grid_h - the height (in pixels) of the rotated grids used in - directional binarization - isobin_grid_dim - the dimension (in pixels) of the square grid used in - isotropic binarization - Return Code: - Non-negative - the maximum padding required for all processes -**************************************************************************/ -int get_max_padding(const int imap_blocksize, - const int dirbin_grid_w, const int dirbin_grid_h, - const int isobin_grid_dim) -{ - int dft_pad, dirbin_pad, isobin_pad, max_pad; - double diag; - double pad; - - /* Compute pad required for rotated blocks used in DFT analyses. */ - diag = sqrt((double)(2.0 * imap_blocksize * imap_blocksize)); - /* Compute pad as difference between the IMAP blocksize */ - /* and the diagonal distance of the block. */ - /* Assumption: all block origins reside in valid/allocated memory. */ - /* DFT grids are computed with pixel offsets RELATIVE2ORIGIN. */ - pad = (diag-imap_blocksize)/(double)2.0; - /* Need to truncate precision so that answers are consistent */ - /* on different computer architectures when rounding doubles. */ - pad = trunc_dbl_precision(pad, TRUNC_SCALE); - dft_pad = sround(pad); - - /* Compute pad required for rotated blocks used in directional */ - /* binarization. */ - diag = sqrt((double)((dirbin_grid_w*dirbin_grid_w)+ - (dirbin_grid_h*dirbin_grid_h))); - /* Assumption: all grid centers reside in valid/allocated memory. */ - /* dirbin grids are computed with pixel offsets RELATIVE2CENTER. */ - pad = (diag-1)/(double)2.0; - /* Need to truncate precision so that answers are consistent */ - /* on different computer architectures when rounding doubles. */ - pad = trunc_dbl_precision(pad, TRUNC_SCALE); - dirbin_pad = sround(pad); - - /* Compute pad required for grids used in isotropic binarization. */ - pad = (isobin_grid_dim - 1)/(double)2.0; - /* Need to truncate precision so that answers are consistent */ - /* on different computer architectures when rounding doubles. */ - pad = trunc_dbl_precision(pad, TRUNC_SCALE); - isobin_pad = sround((isobin_grid_dim - 1)/(double)2.0); - - max_pad = max(dft_pad, dirbin_pad); - max_pad = max(max_pad, isobin_pad); - - /* Return the maximum of the three required paddings. This padding will */ - /* be sufficiently large for all three purposes, so that padding of the */ - /* input image will only be required once. */ - return(max_pad); -} - /************************************************************************* ************************************************************************** #cat: get_max_padding_V2 - Deterines the maximum amount of image pixel padding diff --git a/libfprint/nbis/mindtct/loop.c b/libfprint/nbis/mindtct/loop.c index 1e84c461..9e15e95b 100644 --- a/libfprint/nbis/mindtct/loop.c +++ b/libfprint/nbis/mindtct/loop.c @@ -46,8 +46,6 @@ identified are necessarily the best available for the purpose. get_loop_aspect() fill_loop() fill_partial_row() - flood_loop() - flood_fill4() ***********************************************************************/ #include @@ -499,6 +497,107 @@ int is_loop_clockwise(const int *contour_x, const int *contour_y, return(ret); } +/************************************************************************* +************************************************************************** +#cat: get_loop_aspect - Takes a contour list (determined to form a complete +#cat: loop) and measures the loop's aspect (the largest and smallest +#cat: distances across the loop) and returns the points on the +#cat: loop where these distances occur. + + Input: + contour_x - x-coord list for loop's contour points + contour_y - y-coord list for loop's contour points + ncontour - number of points in contour + Output: + omin_fr - contour point index where minimum aspect occurs + omin_to - opposite contour point index where minimum aspect occurs + omin_dist - the minimum distance across the loop + omax_fr - contour point index where maximum aspect occurs + omax_to - contour point index where maximum aspect occurs + omax_dist - the maximum distance across the loop +**************************************************************************/ +static void get_loop_aspect(int *omin_fr, int *omin_to, double *omin_dist, + int *omax_fr, int *omax_to, double *omax_dist, + const int *contour_x, const int *contour_y, const int ncontour) +{ + int halfway, limit; + int i, j; + double dist; + double min_dist, max_dist; + int min_i, max_i, min_j, max_j; + + /* Compute half the perimeter of the loop. */ + halfway = ncontour>>1; + + /* Take opposite points on the contour and walk half way */ + /* around the loop. */ + i = 0; + j = halfway; + /* Compute squared distance between opposite points on loop. */ + dist = squared_distance(contour_x[i], contour_y[i], + contour_x[j], contour_y[j]); + + /* Initialize running minimum and maximum distances along loop. */ + min_dist = dist; + min_i = i; + min_j = j; + max_dist = dist; + max_i = i; + max_j = j; + /* Bump to next pair of opposite points. */ + i++; + /* Make sure j wraps around end of list. */ + j++; + j %= ncontour; + + /* If the loop is of even length, then we only need to walk half */ + /* way around as the other half will be exactly redundant. If */ + /* the loop is of odd length, then the second half will not be */ + /* be exactly redundant and the difference "may" be meaningful. */ + /* If execution speed is an issue, then probably get away with */ + /* walking only the fist half of the loop under ALL conditions. */ + + /* If loop has odd length ... */ + if(ncontour % 2) + /* Walk the loop's entire perimeter. */ + limit = ncontour; + /* Otherwise the loop has even length ... */ + else + /* Only walk half the perimeter. */ + limit = halfway; + + /* While we have not reached our perimeter limit ... */ + while(i < limit){ + /* Compute squared distance between opposite points on loop. */ + dist = squared_distance(contour_x[i], contour_y[i], + contour_x[j], contour_y[j]); + /* Check the running minimum and maximum distances. */ + if(dist < min_dist){ + min_dist = dist; + min_i = i; + min_j = j; + } + if(dist > max_dist){ + max_dist = dist; + max_i = i; + max_j = j; + } + /* Bump to next pair of opposite points. */ + i++; + /* Make sure j wraps around end of list. */ + j++; + j %= ncontour; + } + + /* Assign minimum and maximum distances to output pointers. */ + *omin_fr = min_i; + *omin_to = min_j; + *omin_dist = min_dist; + *omax_fr = max_i; + *omax_to = max_j; + *omax_dist = max_dist; +} + /************************************************************************* ************************************************************************** #cat: process_loop - Takes a contour list that has been determined to form @@ -845,103 +944,39 @@ int process_loop_V2(MINUTIAE *minutiae, /************************************************************************* ************************************************************************** -#cat: get_loop_aspect - Takes a contour list (determined to form a complete -#cat: loop) and measures the loop's aspect (the largest and smallest -#cat: distances across the loop) and returns the points on the -#cat: loop where these distances occur. +#cat: fill_partial_row - Fills a specified range of contiguous pixels on +#cat: a specified row of an 8-bit pixel image with a specified +#cat: pixel value. NOTE, the pixel coordinates are assumed to +#cat: be within the image boundaries. Input: - contour_x - x-coord list for loop's contour points - contour_y - y-coord list for loop's contour points - ncontour - number of points in contour + fill_pix - pixel value to fill with (should be on range [0..255] + frx - x-pixel coord where fill should begin + tox - x-pixel coord where fill should end (inclusive) + y - y-pixel coord of current row being filled + bdata - 8-bit image data + iw - width (in pixels) of image + ih - height (in pixels) of image Output: - omin_fr - contour point index where minimum aspect occurs - omin_to - opposite contour point index where minimum aspect occurs - omin_dist - the minimum distance across the loop - omax_fr - contour point index where maximum aspect occurs - omax_to - contour point index where maximum aspect occurs - omax_dist - the maximum distance across the loop + bdata - 8-bit image data with partial row filled. **************************************************************************/ -void get_loop_aspect(int *omin_fr, int *omin_to, double *omin_dist, - int *omax_fr, int *omax_to, double *omax_dist, - const int *contour_x, const int *contour_y, const int ncontour) +static void fill_partial_row(const int fill_pix, const int frx, const int tox, + const int y, unsigned char *bdata, const int iw, const int ih) { - int halfway, limit; - int i, j; - double dist; - double min_dist, max_dist; - int min_i, max_i, min_j, max_j; + int x; + unsigned char *bptr; - /* Compute half the perimeter of the loop. */ - halfway = ncontour>>1; + /* Set pixel pointer to starting x-coord on current row. */ + bptr = bdata+(y*iw)+frx; - /* Take opposite points on the contour and walk half way */ - /* around the loop. */ - i = 0; - j = halfway; - /* Compute squared distance between opposite points on loop. */ - dist = squared_distance(contour_x[i], contour_y[i], - contour_x[j], contour_y[j]); - - /* Initialize running minimum and maximum distances along loop. */ - min_dist = dist; - min_i = i; - min_j = j; - max_dist = dist; - max_i = i; - max_j = j; - /* Bump to next pair of opposite points. */ - i++; - /* Make sure j wraps around end of list. */ - j++; - j %= ncontour; - - /* If the loop is of even length, then we only need to walk half */ - /* way around as the other half will be exactly redundant. If */ - /* the loop is of odd length, then the second half will not be */ - /* be exactly redundant and the difference "may" be meaningful. */ - /* If execution speed is an issue, then probably get away with */ - /* walking only the fist half of the loop under ALL conditions. */ - - /* If loop has odd length ... */ - if(ncontour % 2) - /* Walk the loop's entire perimeter. */ - limit = ncontour; - /* Otherwise the loop has even length ... */ - else - /* Only walk half the perimeter. */ - limit = halfway; - - /* While we have not reached our perimeter limit ... */ - while(i < limit){ - /* Compute squared distance between opposite points on loop. */ - dist = squared_distance(contour_x[i], contour_y[i], - contour_x[j], contour_y[j]); - /* Check the running minimum and maximum distances. */ - if(dist < min_dist){ - min_dist = dist; - min_i = i; - min_j = j; - } - if(dist > max_dist){ - max_dist = dist; - max_i = i; - max_j = j; - } - /* Bump to next pair of opposite points. */ - i++; - /* Make sure j wraps around end of list. */ - j++; - j %= ncontour; + /* Foreach pixel between starting and ending x-coord on row */ + /* (including the end points) ... */ + for(x = frx; x <= tox; x++){ + /* Set current pixel with fill pixel value. */ + *bptr = fill_pix; + /* Bump to next pixel in the row. */ + bptr++; } - - /* Assign minimum and maximum distances to output pointers. */ - *omin_fr = min_i; - *omin_to = min_j; - *omin_dist = min_dist; - *omax_fr = max_i; - *omax_to = max_j; - *omax_dist = max_dist; } /************************************************************************* @@ -1075,154 +1110,3 @@ int fill_loop(const int *contour_x, const int *contour_y, return(0); } -/************************************************************************* -************************************************************************** -#cat: fill_partial_row - Fills a specified range of contiguous pixels on -#cat: a specified row of an 8-bit pixel image with a specified -#cat: pixel value. NOTE, the pixel coordinates are assumed to -#cat: be within the image boundaries. - - Input: - fill_pix - pixel value to fill with (should be on range [0..255] - frx - x-pixel coord where fill should begin - tox - x-pixel coord where fill should end (inclusive) - y - y-pixel coord of current row being filled - bdata - 8-bit image data - iw - width (in pixels) of image - ih - height (in pixels) of image - Output: - bdata - 8-bit image data with partial row filled. -**************************************************************************/ -void fill_partial_row(const int fill_pix, const int frx, const int tox, - const int y, unsigned char *bdata, const int iw, const int ih) -{ - int x; - unsigned char *bptr; - - /* Set pixel pointer to starting x-coord on current row. */ - bptr = bdata+(y*iw)+frx; - - /* Foreach pixel between starting and ending x-coord on row */ - /* (including the end points) ... */ - for(x = frx; x <= tox; x++){ - /* Set current pixel with fill pixel value. */ - *bptr = fill_pix; - /* Bump to next pixel in the row. */ - bptr++; - } -} - -/************************************************************************* -************************************************************************** -#cat: flood_loop - Fills a given contour (determined to form a complete loop) -#cat: with a specified pixel value using a recursive flood-fill -#cat: technique. -#cat: NOTE, this fill approach will NOT always work with the -#cat: contours generated in this application because they -#cat: are NOT guaranteed to be ENTIRELY surrounded by 8-connected -#cat: pixels not equal to the fill pixel value. This is unfortunate -#cat: because the flood-fill is a simple algorithm that will handle -#cat: complex/concaved shapes. - - Input: - contour_x - x-coord list for loop's contour points - contour_y - y-coord list for loop's contour points - ncontour - number of points in contour - bdata - binary image data (0==while & 1==black) - iw - width (in pixels) of image - ih - height (in pixels) of image - Output: - bdata - binary image data with loop filled -**************************************************************************/ -void flood_loop(const int *contour_x, const int *contour_y, - const int ncontour, unsigned char *bdata, - const int iw, const int ih) -{ - int feature_pix, fill_pix; - int i; - - /* Get the pixel value of the minutia feauture. This is */ - /* the pixel value we wish to replace with the flood. */ - feature_pix = *(bdata + (contour_y[0] * iw) + contour_x[0]); - - /* Flip the feature pixel value to the value we want to */ - /* fill with and send this value to the flood routine. */ - fill_pix = !feature_pix; - - /* Flood-fill interior of contour using a 4-neighbor fill. */ - /* We are using a 4-neighbor fill because the contour was */ - /* collected using 8-neighbors, and the 4-neighbor fill */ - /* will NOT escape the 8-neighbor based contour. */ - /* The contour passed must be guarenteed to be complete for */ - /* the flood-fill to work properly. */ - /* We are initiating a flood-fill from each point on the */ - /* contour to make sure complex patterns get filled in. */ - /* The complex patterns we are concerned about are those */ - /* that "pinch" the interior of the feature off due to */ - /* skipping "exposed" corners along the contour. */ - /* Simple shapes will fill upon invoking the first contour */ - /* pixel, and the subsequent calls will immediately return */ - /* as their seed pixel will have already been flipped. */ - for(i = 0; i < ncontour; i++){ - /* Start the recursive flooding. */ - flood_fill4(fill_pix, contour_x[i], contour_y[i], - bdata, iw, ih); - } -} - -/************************************************************************* -************************************************************************** -#cat: flood_fill4 - Recursively floods a region of an 8-bit pixel image with a -#cat: specified pixel value given a starting (seed) point. The -#cat: recursion is based neighbors being 4-connected. - - Input: - fill_pix - 8-bit pixel value to be filled with (on range [0..255] - x - starting x-pixel coord - y - starting y-pixel coord - bdata - 8-bit pixel image data - iw - width (in pixels) of image - ih - height (in pixels) of image - Output: - bdata - 8-bit pixel image data with region filled -**************************************************************************/ -void flood_fill4(const int fill_pix, const int x, const int y, - unsigned char *bdata, const int iw, const int ih) -{ - unsigned char *pptr; - int y_north, y_south, x_east, x_west; - - /* Get address of current pixel. */ - pptr = bdata + (y*iw) + x; - /* If pixel needs to be filled ... */ - if(*pptr != fill_pix){ - /* Fill the current pixel. */ - *pptr = fill_pix; - - /* Recursively invoke flood on the pixel's 4 neighbors. */ - /* Test to make sure neighbors are within image boudaries */ - /* before invoking each flood. */ - y_north = y-1; - y_south = y+1; - x_west = x-1; - x_east = x+1; - - /* Invoke North */ - if(y_north >= 0) - flood_fill4(fill_pix, x, y_north, bdata, iw, ih); - - /* Invoke East */ - if(x_east < iw) - flood_fill4(fill_pix, x_east, y, bdata, iw, ih); - - /* Invoke South */ - if(y_south < ih) - flood_fill4(fill_pix, x, y_south, bdata, iw, ih); - - /* Invoke West */ - if(x_west >= 0) - flood_fill4(fill_pix, x_west, y, bdata, iw, ih); - } - - /* Otherwise, there is nothing to be done. */ -} diff --git a/libfprint/nbis/mindtct/maps.c b/libfprint/nbis/mindtct/maps.c index 3050c5cc..6f49e3c6 100644 --- a/libfprint/nbis/mindtct/maps.c +++ b/libfprint/nbis/mindtct/maps.c @@ -46,7 +46,6 @@ identified are necessarily the best available for the purpose. pixelize_map() smooth_direction_map() gen_high_curve_map() - gen_imap() gen_initial_imap() primary_dir_test() secondary_fork_test() @@ -59,7 +58,6 @@ identified are necessarily the best available for the purpose. average_8nbr_dir() num_valid_8nbrs() smooth_imap() - gen_nmap() vorticity() accum_nbr_vorticity() curvature() @@ -930,75 +928,6 @@ int gen_high_curve_map(int **ohcmap, int *direction_map, return(0); } -/************************************************************************* -************************************************************************** -#cat: gen_imap - Computes an IMAP, which is a 2D vector of integer directions, -#cat: where each direction represents the dominant ridge flow in -#cat: a block of the input grayscale image. This routine will -#cat: generate an IMAP for arbitrarily sized, non-square, images. - - Input: - pdata - padded input image data (8 bits [0..256) grayscale) - pw - padded width (in pixels) of the input image - ph - padded height (in pixels) of the input image - dir2rad - lookup table for converting integer directions - dftwaves - structure containing the DFT wave forms - dftgrids - structure containing the rotated pixel grid offsets - lfsparms - parameters and thresholds for controlling LFS - Output: - optr - points to the created IMAP - ow - width (in blocks) of the IMAP - oh - height (in blocks) of the IMAP - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int gen_imap(int **optr, int *ow, int *oh, - unsigned char *pdata, const int pw, const int ph, - const DIR2RAD *dir2rad, const DFTWAVES *dftwaves, - const ROTGRIDS *dftgrids, const LFSPARMS *lfsparms) -{ - int *imap, mw, mh, iw, ih; - int *blkoffs; - int ret; /* return code */ - - /* 1. Compute block offsets for the entire image, accounting for pad */ - /* Block_offsets() assumes square block (grid), so ERROR otherwise. */ - if(dftgrids->grid_w != dftgrids->grid_h){ - fprintf(stderr, "ERROR : gen_imap : DFT grids must be square\n"); - return(-60); - } - /* Compute unpadded image dimensions. */ - iw = pw - (dftgrids->pad<<1); - ih = ph - (dftgrids->pad<<1); - if((ret = block_offsets(&blkoffs, &mw, &mh, iw, ih, - dftgrids->pad, dftgrids->grid_w))){ - return(ret); - } - - /* 2. Generate initial imap */ - if((ret = gen_initial_imap(&imap, blkoffs, mw, mh, pdata, pw, ph, - dftwaves, dftgrids, lfsparms))){ - /* Free memory allocated to this point. */ - free(blkoffs); - return(ret); - } - - /* 3. Remove IMAP directions that are inconsistent with neighbors */ - remove_incon_dirs(imap, mw, mh, dir2rad, lfsparms); - - /* 4. Smooth imap values with their neighbors */ - smooth_imap(imap, mw, mh, dir2rad, lfsparms); - - /* Deallocate working memory. */ - free(blkoffs); - - *optr = imap; - *ow = mw; - *oh = mh; - return(0); -} - /************************************************************************* ************************************************************************** #cat: gen_initial_imap - Creates an initial IMAP from the given input image. @@ -2160,100 +2089,6 @@ void smooth_imap(int *imap, const int mw, const int mh, } } -/************************************************************************* -************************************************************************** -#cat: gen_nmap - Computes an NMAP from its associated 2D vector of integer -#cat: directions (IMAP). Each value in the NMAP either represents -#cat: a direction of dominant ridge flow in a block of the input -#cat: grayscale image, or it contains a codes describing why such -#cat: a direction was not procuded. -#cat: For example, blocks near areas of high-curvature (such as -#cat: with cores and deltas) will not produce reliable IMAP -#cat: directions. - - Input: - imap - associated input vector of IMAP directions - mw - the width (in blocks) of the IMAP - mh - the height (in blocks) of the IMAP - lfsparms - parameters and thresholds for controlling LFS - Output: - optr - points to the created NMAP - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int gen_nmap(int **optr, int *imap, const int mw, const int mh, - const LFSPARMS *lfsparms) -{ - int *nmap, mapsize; - int *nptr, *iptr; - int bx, by; - int nvalid, cmeasure, vmeasure; - - mapsize = mw*mh; - nmap = (int *)malloc(mapsize * sizeof(int)); - if(nmap == (int *)NULL){ - fprintf(stderr, "ERROR: gen_nmap : malloc : nmap\n"); - return(-120); - } - - nptr = nmap; - iptr = imap; - /* Foreach row in IMAP ... */ - for(by = 0; by < mh; by++){ - /* Foreach column in IMAP ... */ - for(bx = 0; bx < mw; bx++){ - /* Count number of valid neighbors around current block ... */ - nvalid = num_valid_8nbrs(imap, bx, by, mw, mh); - /* If block has no valid neighbors ... */ - if(nvalid == 0) - /* Set NMAP value to NO VALID NEIGHBORS */ - *nptr = NO_VALID_NBRS; - else{ - /* If current IMAP value is INVALID ... */ - if(*iptr == INVALID_DIR){ - /* If not enough VALID neighbors ... */ - if(nvalid < lfsparms->vort_valid_nbr_min){ - /* Set NMAP value to INVALID */ - *nptr = INVALID_DIR; - } - else{ - /* Otherwise measure vorticity of neighbors. */ - vmeasure = vorticity(imap, bx, by, mw, mh, - lfsparms->num_directions); - /* If vorticity too low ... */ - if(vmeasure < lfsparms->highcurv_vorticity_min) - *nptr = INVALID_DIR; - else - /* Otherwise high-curvature area (Ex. core or delta). */ - *nptr = HIGH_CURVATURE; - } - } - /* Otherwise VALID IMAP value ... */ - else{ - /* Measure curvature around the VALID IMAP block. */ - cmeasure = curvature(imap, bx, by, mw, mh, - lfsparms->num_directions); - /* If curvature is too high ... */ - if(cmeasure >= lfsparms->highcurv_curvature_min) - *nptr = HIGH_CURVATURE; - else - /* Otherwise acceptable amount of curature, so assign */ - /* VALID IMAP value to NMAP. */ - *nptr = *iptr; - } - } /* end else (nvalid > 0) */ - /* BUMP IMAP and NMAP pointers. */ - iptr++; - nptr++; - - } /* bx */ - } /* by */ - - *optr = nmap; - return(0); -} - /************************************************************************* ************************************************************************** #cat: vorticity - Measures the amount of cummulative curvature incurred diff --git a/libfprint/nbis/mindtct/minutia.c b/libfprint/nbis/mindtct/minutia.c index 29f505c7..5193fc8a 100644 --- a/libfprint/nbis/mindtct/minutia.c +++ b/libfprint/nbis/mindtct/minutia.c @@ -37,7 +37,6 @@ identified are necessarily the best available for the purpose. ROUTINES: alloc_minutiae() realloc_minutiae() - detect_minutiae() detect_minutiae_V2() update_minutiae() update_minutiae_V2() @@ -144,99 +143,6 @@ int realloc_minutiae(MINUTIAE *minutiae, const int incr_minutiae) return(0); } -/************************************************************************* -************************************************************************** -#cat: detect_minutiae - Takes a binary image and its associated IMAP and -#cat: NMAP matrices and scans each image block for potential -#cat: minutia points. - - Input: - bdata - binary image data (0==while & 1==black) - iw - width (in pixels) of image - ih - height (in pixels) of image - imap - matrix of ridge flow directions - nmap - IMAP augmented with blocks of HIGH-CURVATURE and - blocks which have no neighboring valid directions. - mw - width (in blocks) of IMAP and NMAP matrices. - mh - height (in blocks) of IMAP and NMAP matrices. - lfsparms - parameters and thresholds for controlling LFS - Output: - minutiae - points to a list of detected minutia structures - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int detect_minutiae(MINUTIAE *minutiae, - unsigned char *bdata, const int iw, const int ih, - const int *imap, const int *nmap, const int mw, const int mh, - const LFSPARMS *lfsparms) -{ - int blk_i, blk_x, blk_y; - int scan_x, scan_y, scan_w, scan_h; - int scan_dir; - int ret; - - /* Start with first block in IMAP. */ - blk_i = 0; - - /* Start with first scan line in image. */ - scan_y = 0; - - /* Foreach row of blocks in IMAP... */ - for(blk_y = 0; blk_y < mh; blk_y++){ - /* Reset to beginning of new block row. */ - scan_x = 0; - /* Foreach block in current IMAP row... */ - for(blk_x = 0; blk_x < mw; blk_x++){ - - /* If IMAP is VALID ... */ - if(imap[blk_i] != INVALID_DIR){ - /* Choose the feature scan direction based on the block's */ - /* VALID IMAP direction. The scan direction will either */ - /* be HORIZONTAL or VERTICAL. */ - scan_dir = choose_scan_direction(imap[blk_i], - lfsparms->num_directions); - /* Set width of scan region. The image may not be an even */ - /* multiple of "blocksize" in width and height, so we must */ - /* account for this. */ - /* Bump right by "blocksize" pixels, but not beyond the */ - /* image boundary. */ - scan_w = min(scan_x+lfsparms->blocksize, iw); - /* Make the resulting width relative to the region's starting */ - /* x-pixel column. */ - scan_w -= scan_x; - /* Bump down by "blocksize" pixels, but not beyond the */ - /* image boundary. */ - scan_h = min(scan_y+lfsparms->blocksize, ih); - /* Make the resulting height relative to the region's starting */ - /* y-pixel row. */ - scan_h -= scan_y; - /* Scan the defined region for minutia features. */ - if((ret = scan4minutiae(minutiae, bdata, iw, ih, - imap, nmap, blk_x, blk_y, mw, mh, - scan_x, scan_y, scan_w, scan_h, scan_dir, - lfsparms))){ - /* Return code may be: */ - /* 1. ret<0 (implying system error) */ - return(ret); - } - - } /* Otherwise, IMAP is INVALID, so ignore the block. This seems */ - /* quite drastic! */ - - /* Advance to the next IMAP block in the row in the image. */ - scan_x += lfsparms->blocksize; - /* Advance to the next IMAP block in the row. */ - blk_i++; - } /* End foreach blk_x */ - /* Advance to the next IMAP row in the image. */ - scan_y += lfsparms->blocksize; - } /* End foreach blk_y */ - - /* Return normally. */ - return(0); -} - /************************************************************************* ************************************************************************** #cat: detect_minutiae_V2 - Takes a binary image and its associated diff --git a/libfprint/nbis/mindtct/mytime.c b/libfprint/nbis/mindtct/mytime.c deleted file mode 100644 index 296503ae..00000000 --- a/libfprint/nbis/mindtct/mytime.c +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - -License: -This software was developed at the National Institute of Standards and -Technology (NIST) by employees of the Federal Government in the course -of their official duties. Pursuant to title 17 Section 105 of the -United States Code, this software is not subject to copyright protection -and is in the public domain. NIST assumes no responsibility whatsoever for -its use by other parties, and makes no guarantees, expressed or implied, -about its quality, reliability, or any other characteristic. - -Disclaimer: -This software was developed to promote biometric standards and biometric -technology testing for the Federal Government in accordance with the USA -PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. -Specific hardware and software products identified in this software were used -in order to perform the software development. In no case does such -identification imply recommendation or endorsement by the National Institute -of Standards and Technology, nor does it imply that the products and equipment -identified are necessarily the best available for the purpose. - -*******************************************************************************/ - -/*********************************************************************** - LIBRARY: LFS - NIST Latent Fingerprint System - - FILE: MYTIME.C - AUTHOR: Michael D. Garris - DATE: 03/16/1999 - - Contains global variable definitions used to record timings by - the NIST Latent Fingerprint System (LFS). -***********************************************************************/ - -/* Total time: including all initializations */ -/* : excluding all I/O except for required HO39 input image */ -/* (This is done to contrast the fact that the NIST GENHO39 */ -/* eliminates the need for this extra read.) */ -unsigned long total_timer; -float total_time = 0.0; /* time accumulator */ - -/* IMAP generation time: excluding initialization */ -unsigned long imap_timer; -float imap_time = 0.0; /* time accumulator */ - -/* Binarization time: excluding initialization */ -unsigned long bin_timer; -float bin_time = 0.0; /* time accumulator */ - -/* Minutia Detection time */ -unsigned long minutia_timer; -float minutia_time = 0.0; /* time accumulator */ - -/* Minutia Removal time */ -unsigned long rm_minutia_timer; -float rm_minutia_time = 0.0; /* time accumulator */ - -/* Neighbor Ridge Counting time */ -unsigned long ridge_count_timer; -float ridge_count_time = 0.0; /* time accumulator */ diff --git a/libfprint/nbis/mindtct/remove.c b/libfprint/nbis/mindtct/remove.c index e3ddbefc..592cb721 100644 --- a/libfprint/nbis/mindtct/remove.c +++ b/libfprint/nbis/mindtct/remove.c @@ -35,15 +35,14 @@ identified are necessarily the best available for the purpose. *********************************************************************** ROUTINES: - remove_false_minutia() remove_false_minutia_V2() remove_holes() remove_hooks() - remove_hooks_islands_overlaps() + remove_hooks_islands_lakes_overlaps() remove_islands_and_lakes() remove_malformations() - remove_near_invblocks() - remove_near_invblocks_V2() + remove_near_invblock() + remove_near_invblock_V2() remove_pointing_invblock() remove_pointing_invblock_V2() remove_overlaps() @@ -58,169 +57,6 @@ identified are necessarily the best available for the purpose. #include #include -/************************************************************************* -************************************************************************** -#cat: remove_false_minutia - Takes a list of true and false minutiae and -#cat: attempts to detect and remove the false minutiae based -#cat: on a series of tests. - - Input: - minutiae - list of true and false minutiae - bdata - binary image data (0==while & 1==black) - iw - width (in pixels) of image - ih - height (in pixels) of image - nmap - IMAP ridge flow matrix with invalid, high-curvature, - and no-valid-neighbor regions identified - mw - width in blocks of the NMAP - mh - height in blocks of the NMAP - lfsparms - parameters and thresholds for controlling LFS - Output: - minutiae - list of pruned minutiae - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int remove_false_minutia(MINUTIAE *minutiae, - unsigned char *bdata, const int iw, const int ih, - int *nmap, const int mw, const int mh, - const LFSPARMS *lfsparms) -{ - int ret; - - /* Sort minutiae points top-to-bottom and left-to-right. */ - if((ret = sort_minutiae_y_x(minutiae, iw, ih))){ - return(ret); - } - - if((ret = link_minutiae(minutiae, bdata, iw, ih, nmap, mw, mh, lfsparms))){ - return(ret); - } - - if((ret = remove_hooks_islands_lakes_overlaps(minutiae, bdata, iw, ih, - lfsparms))){ - return(ret); - } - - if((ret = remove_pointing_invblock(minutiae, nmap, mw, mh, lfsparms))){ - return(ret); - } - - if((ret = remove_holes(minutiae, bdata, iw, ih, lfsparms))){ - return(ret); - } - - if((ret = remove_or_adjust_side_minutiae(minutiae, - bdata, iw, ih, lfsparms))){ - return(ret); - } - - if((ret = remove_near_invblock(minutiae, nmap, mw, mh, lfsparms))){ - return(ret); - } - - if((ret = remove_pores(minutiae, bdata, iw, ih, nmap, mw, mh, lfsparms))){ - return(ret); - } - - return(0); -} - -/************************************************************************* -************************************************************************** -#cat: remove_false_minutia_V2 - Takes a list of true and false minutiae and -#cat: attempts to detect and remove the false minutiae based -#cat: on a series of tests. - - Input: - minutiae - list of true and false minutiae - bdata - binary image data (0==while & 1==black) - iw - width (in pixels) of image - ih - height (in pixels) of image - direction_map - map of image blocks containing directional ridge flow - low_flow_map - map of image blocks flagged as LOW RIDGE FLOW - high_curve_map - map of image blocks flagged as HIGH CURVATURE - mw - width in blocks of the maps - mh - height in blocks of the maps - lfsparms - parameters and thresholds for controlling LFS - Output: - minutiae - list of pruned minutiae - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int remove_false_minutia_V2(MINUTIAE *minutiae, - unsigned char *bdata, const int iw, const int ih, - int *direction_map, int *low_flow_map, int *high_curve_map, - const int mw, const int mh, const LFSPARMS *lfsparms) -{ - int ret; - - /* 1. Sort minutiae points top-to-bottom and left-to-right. */ - if((ret = sort_minutiae_y_x(minutiae, iw, ih))){ - return(ret); - } - - /* 2. Remove minutiae on lakes (filled with white pixels) and */ - /* islands (filled with black pixels), both defined by a pair of */ - /* minutia points. */ - if((ret = remove_islands_and_lakes(minutiae, bdata, iw, ih, lfsparms))){ - return(ret); - } - - /* 3. Remove minutiae on holes in the binary image defined by a */ - /* single point. */ - if((ret = remove_holes(minutiae, bdata, iw, ih, lfsparms))){ - return(ret); - } - - /* 4. Remove minutiae that point sufficiently close to a block with */ - /* INVALID direction. */ - if((ret = remove_pointing_invblock_V2(minutiae, direction_map, mw, mh, - lfsparms))){ - return(ret); - } - - /* 5. Remove minutiae that are sufficiently close to a block with */ - /* INVALID direction. */ - if((ret = remove_near_invblock_V2(minutiae, direction_map, mw, mh, - lfsparms))){ - return(ret); - } - - /* 6. Remove or adjust minutiae that reside on the side of a ridge */ - /* or valley. */ - if((ret = remove_or_adjust_side_minutiae_V2(minutiae, bdata, iw, ih, - direction_map, mw, mh, lfsparms))){ - return(ret); - } - - /* 7. Remove minutiae that form a hook on the side of a ridge or valley. */ - if((ret = remove_hooks(minutiae, bdata, iw, ih, lfsparms))){ - return(ret); - } - - /* 8. Remove minutiae that are on opposite sides of an overlap. */ - if((ret = remove_overlaps(minutiae, bdata, iw, ih, lfsparms))){ - return(ret); - } - - /* 9. Remove minutiae that are "irregularly" shaped. */ - if((ret = remove_malformations(minutiae, bdata, iw, ih, - low_flow_map, mw, mh, lfsparms))){ - return(ret); - } - - /* 10. Remove minutiae that form long, narrow, loops in the */ - /* "unreliable" regions in the binary image. */ - if((ret = remove_pores_V2(minutiae, bdata, iw, ih, - direction_map, low_flow_map, high_curve_map, - mw, mh, lfsparms))){ - return(ret); - } - - return(0); -} - /************************************************************************* ************************************************************************** #cat: remove_holes - Removes minutia points on small loops around valleys. @@ -237,7 +73,7 @@ int remove_false_minutia_V2(MINUTIAE *minutiae, Zero - successful completion Negative - system error **************************************************************************/ -int remove_holes(MINUTIAE *minutiae, +static int remove_holes(MINUTIAE *minutiae, unsigned char *bdata, const int iw, const int ih, const LFSPARMS *lfsparms) { @@ -308,7 +144,7 @@ int remove_holes(MINUTIAE *minutiae, Zero - successful completion Negative - system error **************************************************************************/ -int remove_hooks(MINUTIAE *minutiae, +static int remove_hooks(MINUTIAE *minutiae, unsigned char *bdata, const int iw, const int ih, const LFSPARMS *lfsparms) { @@ -532,7 +368,7 @@ int remove_hooks(MINUTIAE *minutiae, Zero - successful completion Negative - system error **************************************************************************/ -int remove_hooks_islands_lakes_overlaps(MINUTIAE *minutiae, +static int remove_hooks_islands_lakes_overlaps(MINUTIAE *minutiae, unsigned char *bdata, const int iw, const int ih, const LFSPARMS *lfsparms) { @@ -827,7 +663,7 @@ int remove_hooks_islands_lakes_overlaps(MINUTIAE *minutiae, Zero - successful completion Negative - system error **************************************************************************/ -int remove_islands_and_lakes(MINUTIAE *minutiae, +static int remove_islands_and_lakes(MINUTIAE *minutiae, unsigned char *bdata, const int iw, const int ih, const LFSPARMS *lfsparms) { @@ -1081,7 +917,7 @@ int remove_islands_and_lakes(MINUTIAE *minutiae, Zero - successful completion Negative - system error **************************************************************************/ -int remove_malformations(MINUTIAE *minutiae, +static int remove_malformations(MINUTIAE *minutiae, unsigned char *bdata, const int iw, const int ih, int *low_flow_map, const int mw, const int mh, const LFSPARMS *lfsparms) @@ -1287,7 +1123,7 @@ int remove_malformations(MINUTIAE *minutiae, Zero - successful completion Negative - system error **************************************************************************/ -int remove_near_invblock(MINUTIAE *minutiae, int *nmap, +static int remove_near_invblock(MINUTIAE *minutiae, int *nmap, const int mw, const int mh, const LFSPARMS *lfsparms) { int i, ret; @@ -1517,7 +1353,7 @@ int remove_near_invblock(MINUTIAE *minutiae, int *nmap, Zero - successful completion Negative - system error **************************************************************************/ -int remove_near_invblock_V2(MINUTIAE *minutiae, int *direction_map, +static int remove_near_invblock_V2(MINUTIAE *minutiae, int *direction_map, const int mw, const int mh, const LFSPARMS *lfsparms) { int i, ret; @@ -1747,7 +1583,7 @@ int remove_near_invblock_V2(MINUTIAE *minutiae, int *direction_map, Zero - successful completion Negative - system error **************************************************************************/ -int remove_pointing_invblock(MINUTIAE *minutiae, +static int remove_pointing_invblock(MINUTIAE *minutiae, int *nmap, const int mw, const int mh, const LFSPARMS *lfsparms) { @@ -1839,7 +1675,7 @@ int remove_pointing_invblock(MINUTIAE *minutiae, Zero - successful completion Negative - system error **************************************************************************/ -int remove_pointing_invblock_V2(MINUTIAE *minutiae, +static int remove_pointing_invblock_V2(MINUTIAE *minutiae, int *direction_map, const int mw, const int mh, const LFSPARMS *lfsparms) { @@ -1929,7 +1765,7 @@ int remove_pointing_invblock_V2(MINUTIAE *minutiae, Zero - successful completion Negative - system error **************************************************************************/ -int remove_overlaps(MINUTIAE *minutiae, +static int remove_overlaps(MINUTIAE *minutiae, unsigned char *bdata, const int iw, const int ih, const LFSPARMS *lfsparms) { @@ -2160,7 +1996,7 @@ int remove_overlaps(MINUTIAE *minutiae, Zero - successful completion Negative - system error **************************************************************************/ -int remove_pores(MINUTIAE *minutiae, +static int remove_pores(MINUTIAE *minutiae, unsigned char *bdata, const int iw, const int ih, int *nmap, const int mw, const int mh, const LFSPARMS *lfsparms) @@ -2548,7 +2384,7 @@ int remove_pores(MINUTIAE *minutiae, Zero - successful completion Negative - system error **************************************************************************/ -int remove_pores_V2(MINUTIAE *minutiae, +static int remove_pores_V2(MINUTIAE *minutiae, unsigned char *bdata, const int iw, const int ih, int *direction_map, int *low_flow_map, int *high_curve_map, const int mw, const int mh, @@ -2936,7 +2772,7 @@ int remove_pores_V2(MINUTIAE *minutiae, Zero - successful completion Negative - system error **************************************************************************/ -int remove_or_adjust_side_minutiae(MINUTIAE *minutiae, +static int remove_or_adjust_side_minutiae(MINUTIAE *minutiae, unsigned char *bdata, const int iw, const int ih, const LFSPARMS *lfsparms) { @@ -3156,7 +2992,7 @@ int remove_or_adjust_side_minutiae(MINUTIAE *minutiae, Zero - successful completion Negative - system error **************************************************************************/ -int remove_or_adjust_side_minutiae_V2(MINUTIAE *minutiae, +static int remove_or_adjust_side_minutiae_V2(MINUTIAE *minutiae, unsigned char *bdata, const int iw, const int ih, int *direction_map, const int mw, const int mh, const LFSPARMS *lfsparms) @@ -3402,3 +3238,99 @@ int remove_or_adjust_side_minutiae_V2(MINUTIAE *minutiae, return(0); } +/************************************************************************* +************************************************************************** +#cat: remove_false_minutia_V2 - Takes a list of true and false minutiae and +#cat: attempts to detect and remove the false minutiae based +#cat: on a series of tests. + + Input: + minutiae - list of true and false minutiae + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + direction_map - map of image blocks containing directional ridge flow + low_flow_map - map of image blocks flagged as LOW RIDGE FLOW + high_curve_map - map of image blocks flagged as HIGH CURVATURE + mw - width in blocks of the maps + mh - height in blocks of the maps + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of pruned minutiae + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int remove_false_minutia_V2(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + int *direction_map, int *low_flow_map, int *high_curve_map, + const int mw, const int mh, const LFSPARMS *lfsparms) +{ + int ret; + + /* 1. Sort minutiae points top-to-bottom and left-to-right. */ + if((ret = sort_minutiae_y_x(minutiae, iw, ih))){ + return(ret); + } + + /* 2. Remove minutiae on lakes (filled with white pixels) and */ + /* islands (filled with black pixels), both defined by a pair of */ + /* minutia points. */ + if((ret = remove_islands_and_lakes(minutiae, bdata, iw, ih, lfsparms))){ + return(ret); + } + + /* 3. Remove minutiae on holes in the binary image defined by a */ + /* single point. */ + if((ret = remove_holes(minutiae, bdata, iw, ih, lfsparms))){ + return(ret); + } + + /* 4. Remove minutiae that point sufficiently close to a block with */ + /* INVALID direction. */ + if((ret = remove_pointing_invblock_V2(minutiae, direction_map, mw, mh, + lfsparms))){ + return(ret); + } + + /* 5. Remove minutiae that are sufficiently close to a block with */ + /* INVALID direction. */ + if((ret = remove_near_invblock_V2(minutiae, direction_map, mw, mh, + lfsparms))){ + return(ret); + } + + /* 6. Remove or adjust minutiae that reside on the side of a ridge */ + /* or valley. */ + if((ret = remove_or_adjust_side_minutiae_V2(minutiae, bdata, iw, ih, + direction_map, mw, mh, lfsparms))){ + return(ret); + } + + /* 7. Remove minutiae that form a hook on the side of a ridge or valley. */ + if((ret = remove_hooks(minutiae, bdata, iw, ih, lfsparms))){ + return(ret); + } + + /* 8. Remove minutiae that are on opposite sides of an overlap. */ + if((ret = remove_overlaps(minutiae, bdata, iw, ih, lfsparms))){ + return(ret); + } + + /* 9. Remove minutiae that are "irregularly" shaped. */ + if((ret = remove_malformations(minutiae, bdata, iw, ih, + low_flow_map, mw, mh, lfsparms))){ + return(ret); + } + + /* 10. Remove minutiae that form long, narrow, loops in the */ + /* "unreliable" regions in the binary image. */ + if((ret = remove_pores_V2(minutiae, bdata, iw, ih, + direction_map, low_flow_map, high_curve_map, + mw, mh, lfsparms))){ + return(ret); + } + + return(0); +} + diff --git a/libfprint/nbis/mindtct/results.c b/libfprint/nbis/mindtct/results.c deleted file mode 100644 index 1f8f1dbc..00000000 --- a/libfprint/nbis/mindtct/results.c +++ /dev/null @@ -1,682 +0,0 @@ -/******************************************************************************* - -License: -This software was developed at the National Institute of Standards and -Technology (NIST) by employees of the Federal Government in the course -of their official duties. Pursuant to title 17 Section 105 of the -United States Code, this software is not subject to copyright protection -and is in the public domain. NIST assumes no responsibility whatsoever for -its use by other parties, and makes no guarantees, expressed or implied, -about its quality, reliability, or any other characteristic. - -Disclaimer: -This software was developed to promote biometric standards and biometric -technology testing for the Federal Government in accordance with the USA -PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. -Specific hardware and software products identified in this software were used -in order to perform the software development. In no case does such -identification imply recommendation or endorsement by the National Institute -of Standards and Technology, nor does it imply that the products and equipment -identified are necessarily the best available for the purpose. - -*******************************************************************************/ - -/*********************************************************************** - LIBRARY: LFS - NIST Latent Fingerprint System - - FILE: RESULTS.C - AUTHOR: Michael D. Garris - DATE: 03/16/1999 - UPDATED: 10/04/1999 Version 2 by MDG - 09/14/2004 - UPDATED: 03/16/2005 by MDG - - Contains routines useful in visualizing intermediate and final - results when exercising the NIST Latent Fingerprint System (LFS). - -*********************************************************************** - ROUTINES: - write_text_results() - write_minutiae_XYTQ() - dump_map() - drawmap() - drawmap2() - drawblocks() - drawrotgrid() - dump_link_table() - -***********************************************************************/ - -#include -#include -#include -#include -#include -#include - -/************************************************************************* -************************************************************************** -#cat: write_text_results - Takes LFS results including minutiae and image -#cat: maps and writes them to separate formatted text files. - - Input: - oroot - root pathname for output files - m1flag - if flag set, write (X,Y,T)'s out to "*.xyt" file according - to M1 (ANSI INCITS 378-2004) minutiae representation - - M1 Rep: - 1. pixel origin top left - 2. direction pointing up the ridge ending or - bifurcaiton valley - NIST Internal Rep: - 1. pixel origin bottom left - 2. direction pointing out and away from the - ridge ending or bifurcation valley - - iw - image pixel width - ih - image pixel height - minutiae - structure containing the detected minutiae - quality_map - integrated image quality map - direction_map - direction map - low_contrast_map - low contrast map - low_flow_map - low ridge flow map - high_curve_map - high curvature map - map_w - width (in blocks) of image maps - map_h - height (in blocks) of image maps - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int write_text_results(char *oroot, const int m1flag, - const int iw, const int ih, - const MINUTIAE *minutiae, int *quality_map, - int *direction_map, int *low_contrast_map, - int *low_flow_map, int *high_curve_map, - const int map_w, const int map_h) -{ - FILE *fp; - int ret; - char ofile[MAXPATHLEN]; - - /* 1. Write Minutiae results to text file ".min". */ - /* XYT's written in LFS native representation: */ - /* 1. pixel coordinates with origin top-left */ - /* 2. 11.25 degrees quantized integer orientation */ - /* on range [0..31] */ - /* 3. minutiae reliability on range [0.0 .. 1.0] */ - /* with 0.0 lowest and 1.0 highest reliability */ - sprintf(ofile, "%s.%s", oroot, MIN_TXT_EXT); - if((fp = fopen(ofile, "wb")) == (FILE *)NULL){ - fprintf(stderr, "ERROR : write_text_results : fopen : %s\n", ofile); - return(-2); - } - /* Print out Image Dimensions Header */ - /* !!!! Image dimension header added 09-13-04 !!!! */ - fprintf(fp, "Image (w,h) %d %d\n", iw, ih); - /* Print text report from the structure containing detected minutiae. */ - dump_minutiae(fp, minutiae); - if(fclose(fp)){ - fprintf(stderr, "ERROR : write_text_results : fclose : %s\n", ofile); - return(-3); - } - - /* 2. Write just minutiae XYT's & Qualities to text */ - /* file ".xyt". */ - /* */ - /* A. If M1 flag set: */ - /* XYTQ's written according to M1 (ANSI INCITS */ - /* 378-2004) representation: */ - /* 1. pixel coordinates with origin top-left */ - /* 2. orientation in degrees on range [0..360] */ - /* with 0 pointing east and increasing counter */ - /* clockwise */ - /* 3. direction pointing up the ridge ending or */ - /* bifurcaiton valley */ - /* 4. minutiae qualities on integer range [0..100] */ - /* (non-standard) */ - /* */ - /* B. If M1 flag NOT set: */ - /* XYTQ's written according to NIST internal rep. */ - /* 1. pixel coordinates with origin bottom-left */ - /* 2. orientation in degrees on range [0..360] */ - /* with 0 pointing east and increasing counter */ - /* clockwise (same as M1) */ - /* 3. direction pointing out and away from the */ - /* ridge ending or bifurcation valley */ - /* (opposite direction from M1) */ - /* 4. minutiae qualities on integer range [0..100] */ - /* (non-standard) */ - sprintf(ofile, "%s.%s", oroot, XYT_EXT); - if(m1flag){ - if((ret = write_minutiae_XYTQ(ofile, M1_XYT_REP, minutiae, iw, ih))){ - return(ret); - } - } - else{ - if((ret = write_minutiae_XYTQ(ofile, NIST_INTERNAL_XYT_REP, - minutiae, iw, ih))){ - return(ret); - } - } - - /* 3. Write Integrated Quality Map results to text file. */ - sprintf(ofile, "%s.%s", oroot, QUALITY_MAP_EXT); - if((fp = fopen(ofile, "wb")) == (FILE *)NULL){ - fprintf(stderr, "ERROR : write_text_results : fopen : %s\n", ofile); - return(-4); - } - /* Print a text report from the map. */ - dump_map(fp, quality_map, map_w, map_h); - if(fclose(fp)){ - fprintf(stderr, "ERROR : write_text_results : fclose : %s\n", ofile); - return(-5); - } - - /* 4. Write Direction Map results to text file. */ - sprintf(ofile, "%s.%s", oroot, DIRECTION_MAP_EXT); - if((fp = fopen(ofile, "wb")) == (FILE *)NULL){ - fprintf(stderr, "ERROR : write_text_results : fopen : %s\n", ofile); - return(-6); - } - /* Print a text report from the map. */ - dump_map(fp, direction_map, map_w, map_h); - if(fclose(fp)){ - fprintf(stderr, "ERROR : write_text_results : fclose : %s\n", ofile); - return(-7); - } - - /* 5. Write Low Contrast Map results to text file. */ - sprintf(ofile, "%s.%s", oroot, LOW_CONTRAST_MAP_EXT); - if((fp = fopen(ofile, "wb")) == (FILE *)NULL){ - fprintf(stderr, "ERROR : write_text_results : fopen : %s\n", ofile); - return(-8); - } - /* Print a text report from the map. */ - dump_map(fp, low_contrast_map, map_w, map_h); - if(fclose(fp)){ - fprintf(stderr, "ERROR : write_text_results : fclose : %s\n", ofile); - return(-9); - } - - /* 6. Write Low Flow Map results to text file. */ - sprintf(ofile, "%s.%s", oroot, LOW_FLOW_MAP_EXT); - if((fp = fopen(ofile, "wb")) == (FILE *)NULL){ - fprintf(stderr, "ERROR : write_text_results : fopen : %s\n", ofile); - return(-10); - } - /* Print a text report from the map. */ - dump_map(fp, low_flow_map, map_w, map_h); - if(fclose(fp)){ - fprintf(stderr, "ERROR : write_text_results : fclose : %s\n", ofile); - return(-11); - } - - /* 7. Write High Curvature Map results to text file. */ - sprintf(ofile, "%s.%s", oroot, HIGH_CURVE_MAP_EXT); - if((fp = fopen(ofile, "wb")) == (FILE *)NULL){ - fprintf(stderr, "ERROR : write_text_results : fopen : %s\n", ofile); - return(-12); - } - /* Print a text report from the map. */ - dump_map(fp, high_curve_map, map_w, map_h); - if(fclose(fp)){ - fprintf(stderr, "ERROR : write_text_results : fclose : %s\n", ofile); - return(-13); - } - - /* Return normally. */ - return(0); -} - -/************************************************************************* -************************************************************************** -#cat: write_minutiae_XYTQ - Write just minutiae XYT's & Qualities to text -#cat: file according to the specified mintuiae represenation - - Input: - ofile - output file name - reptype - specifies XYT output representation - minutiae - structure containing a list of LFS detected minutiae - iw - width (in pixels) of the input image - ih - height (in pixels) of the input image - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int write_minutiae_XYTQ(char *ofile, const int reptype, - const MINUTIAE *minutiae, const int iw, const int ih) -{ - FILE *fp; - int i, ox, oy, ot, oq; - MINUTIA *minutia; - - /* A. If M1 flag set: */ - /* XYTQ's written according to M1 (ANSI INCITS */ - /* 378-2004) representation: */ - /* 1. pixel coordinates with origin top-left */ - /* 2. orientation in degrees on range [0..360] */ - /* with 0 pointing east and increasing counter */ - /* clockwise */ - /* 3. direction pointing up the ridge ending or */ - /* bifurcaiton valley */ - /* 4. minutiae qualities on integer range [0..100] */ - /* (non-standard) */ - /* */ - /* B. If M1 flag NOT set: */ - /* XYTQ's written according to NIST internal rep. */ - /* 1. pixel coordinates with origin bottom-left */ - /* 2. orientation in degrees on range [0..360] */ - /* with 0 pointing east and increasing counter */ - /* clockwise (same as M1) */ - /* 3. direction pointing out and away from the */ - /* ridge ending or bifurcation valley */ - /* (opposite direction from M1) */ - /* 4. minutiae qualities on integer range [0..100] */ - /* (non-standard) */ - - if((fp = fopen(ofile, "wb")) == (FILE *)NULL){ - fprintf(stderr, "ERROR : write_minutiae_XYTQ : fopen : %s\n", ofile); - return(-2); - } - - for(i = 0; i < minutiae->num; i++){ - minutia = minutiae->list[i]; - - switch(reptype){ - case M1_XYT_REP: - lfs2m1_minutia_XYT(&ox, &oy, &ot, minutia); - break; - case NIST_INTERNAL_XYT_REP: - lfs2nist_minutia_XYT(&ox, &oy, &ot, minutia, iw, ih); - break; - default: - fprintf(stderr, "ERROR : write_minutiae_XYTQ : "); - fprintf(stderr, "Invalid XYT representation type = %d\n", reptype); - fclose(fp); - return(-4); - } - - oq = sround(minutia->reliability * 100.0); - - fprintf(fp, "%d %d %d %d\n", ox, oy, ot, oq); - } - - - if(fclose(fp)){ - fprintf(stderr, "ERROR : write_minutiae_XYTQ : fopen : %s\n", ofile); - return(-5); - } - - return(0); -} - -/************************************************************************* -************************************************************************** -#cat: dump_map - Prints a text report to the specified open file pointer -#cat: of the integer values in a 2D integer vector. - - Input: - fpout - open file pointer - map - vector of integer directions (-1 ==> invalid direction) - mw - width (number of blocks) of map vector - mh - height (number of blocks) of map vector -**************************************************************************/ -void dump_map(FILE *fpout, int *map, const int mw, const int mh) -{ - int mx, my; - int *iptr; - - /* Simply print the map matrix out to the specified file pointer. */ - iptr = map; - for(my = 0; my < mh; my++){ - for(mx = 0; mx < mw; mx++){ - fprintf(fpout, "%2d ", *iptr++); - } - fprintf(fpout, "\n"); - } -} - -/************************************************************************* -************************************************************************** -#cat: drawmap - Draws integer direction vectors over their respective blocks -#cat: of an input image. Note that the input image is modified -#cat: upon return form this routine. - - Input: - imap - computed vector of integer directions. (-1 ==> invalid) - mw - width (in blocks) of the map - mh - height (in blocks) of the map - idata - input image data to be annotated - iw - width (in pixels) of the input image - ih - height (in pixels) of the input image - rotgrids - structure containing the rotated pixel grid offsets - draw_pixel - pixel intensity to be used when drawing on the image - Output: - idata - input image contains the results of the annoatation - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int drawmap(int *imap, const int mw, const int mh, - unsigned char *idata, const int iw, const int ih, - const ROTGRIDS *dftgrids, const int draw_pixel) -{ - int bi, *iptr; - double dy, dx, xincr, yincr; - int cbxy; - int i, xyoffset; - unsigned char *cptr, *lptr, *rptr, *eptr; - double theta, pi_incr; - int *blkoffs, bw, bh; - int ret; /* return code */ - - /* Compute block offsets into the input image. */ - /* Block_offsets() assumes square block (grid), so ERROR otherwise. */ - if(dftgrids->grid_w != dftgrids->grid_h){ - fprintf(stderr, "ERROR : drawmap : DFT grids must be square\n"); - return(-130); - } - if((ret = block_offsets(&blkoffs, &bw, &bh, iw, ih, - dftgrids->pad, dftgrids->grid_w))){ - return(ret); - } - - if((bw != mw) || (bh != mh)){ - /* Free memory allocated to this point. */ - free(blkoffs); - fprintf(stderr, - "ERROR : drawmap : block dimensions between map and image do not match\n"); - return(-131); - } - - cbxy = dftgrids->grid_w>>1; - pi_incr = M_PI/(double)dftgrids->ngrids; - - eptr = idata + (ih*iw); - iptr = imap; - /* Foreach block in image ... */ - for(bi = 0; bi < mw*mh; bi++){ - - /* If valid direction for block ... */ - if(*iptr != INVALID_DIR){ - - /* Get slope components of direction angle */ - theta = dftgrids->start_angle + (*iptr * pi_incr); - dx = cos(theta); - dy = sin(theta); - - /* Draw line rotated by the direction angle and centered */ - /* on the block. */ - /* Check if line is perfectly vertical ... */ - if(dx == 0){ - /* Draw vertical line starting at top of block shifted */ - /* over to horizontal center of the block. */ - lptr = idata + blkoffs[bi] + cbxy; - for(i = 0; i < dftgrids->grid_w; i++){ - if((lptr > idata) && (lptr < eptr)){ - *lptr = draw_pixel; - } - lptr += iw; - } - } - else{ - cptr = idata + blkoffs[bi] + (cbxy*iw) + cbxy; - - /* Draw center pixel */ - *cptr = draw_pixel; - - /* Draw left and right half of line */ - xincr = dx; - yincr = dy; - for(i = 0; i < cbxy; i++){ - xyoffset = (sround(yincr)*iw) + sround(xincr); - rptr = cptr + xyoffset; - if((rptr > idata) && (rptr < eptr)){ - *rptr = draw_pixel; - } - lptr = cptr - xyoffset; - if((lptr > idata) && (lptr < eptr)){ - *lptr = draw_pixel; - } - xincr += dx; - yincr += dy; - } - } - } - iptr++; - } - - /* Deallocate working memory */ - free(blkoffs); - - return(0); -} - -/************************************************************************* -************************************************************************** -#cat: drawmap2 - Draws integer direction vectors over their respective blocks -#cat: of an input image. Note that the input image is modified -#cat: upon return form this routine. In this version of the -#cat: routine, offsets to the origin of each block in the image -#cat: must be precomputed and passed in. - - Input: - imap - computed vector of integer directions. (-1 ==> invalid) - blkoffs - list of pixel offsets to the origin of each block in the - image from which the map was computed - mw - width (in blocks) of the map - mh - height (in blocks) of the map - pdata - input image data to be annotated - pw - width (in pixels) of the input image - ph - height (in pixels) of the input image - start_angle - the angle (in radians) that the direction 0 points in - ndirs - number of directions within a half circle - blocksize - the dimensions (in pixels) of each block - Output: - pdata - input image contains the results of the annoatation -**************************************************************************/ -void drawmap2(int *imap, const int *blkoffs, const int mw, const int mh, - unsigned char *pdata, const int pw, const int ph, - const double start_angle, const int ndirs, const int blocksize) -{ - int bi, *iptr; - double dy, dx, xincr, yincr; - int cbxy; - int i, xyoffset; - unsigned char *cptr, *lptr, *rptr, *eptr; - double theta, pi_incr; - - cbxy = blocksize>>1; - pi_incr = M_PI/(double)ndirs; - - eptr = pdata + (pw*ph); - iptr = imap; - /* Foreach block in image ... */ - for(bi = 0; bi < mw*mh; bi++){ - - /* If valid direction for block ... */ - if(*iptr != INVALID_DIR){ - - /* Get slope components of direction angle */ - theta = start_angle + (*iptr * pi_incr); - dx = cos((double)theta); - dy = sin((double)theta); - - /* Draw line rotated by the direction angle and centered */ - /* on the block. */ - /* Check if line is perfectly vertical ... */ - if(dx == 0){ - /* Draw vertical line starting at top of block shifted */ - /* over to horizontal center of the block. */ - lptr = pdata + blkoffs[bi] + cbxy; - for(i = 0; i < blocksize; i++){ - if((lptr > pdata) && (lptr < eptr)) - *lptr = 255; - lptr += pw; - } - } - else{ - cptr = pdata + blkoffs[bi] + (cbxy*pw) + cbxy; - - /* Draw center pixel */ - *cptr = 255; - - /* Draw left and right half of line */ - xincr = dx; - yincr = dy; - for(i = 0; i < cbxy; i++){ - xyoffset = (sround(yincr)*pw) + sround(xincr); - rptr = cptr + xyoffset; - if((rptr > pdata) && (rptr < eptr)) - *rptr = 255; - lptr = cptr - xyoffset; - if((lptr > pdata) && (lptr < eptr)) - *lptr = 255; - xincr += dx; - yincr += dy; - } - } - } - iptr++; - } -} - -/************************************************************************* -************************************************************************** -#cat: drawblocks - Annotates an input image with the location of each block's -#cat: origin. This routine is useful to see how blocks are -#cat: assigned to arbitrarily-sized images that are not an even -#cat: width or height of the block size. In these cases the last -#cat: column pair and row pair of blocks overlap each other. -#cat: Note that the input image is modified upon return form -#cat: this routine. - - Input: - blkoffs - offsets to the pixel origin of each block in the image - mw - number of blocks horizontally in the input image - mh - number of blocks vertically in the input image - pdata - input image data to be annotated that has pixel dimensions - compatible with the offsets in blkoffs - pw - width (in pixels) of the input image - ph - height (in pixels) of the input image - draw_pixel - pixel intensity to be used when drawing on the image - Output: - pdata - input image contains the results of the annoatation -**************************************************************************/ -void drawblocks(const int *blkoffs, const int mw, const int mh, - unsigned char *pdata, const int pw, const int ph, - const int draw_pixel) -{ - int bi; - unsigned char *bptr; - - for(bi = 0; bi < mw*mh; bi++){ - bptr = pdata + blkoffs[bi]; - *bptr = draw_pixel; - } -} - - -/************************************************************************* -************************************************************************** -#cat: drawrotgrid - Annotates an input image with a specified rotated grid. -#cat: This routine is useful to see the location and orientation -#cat: of a specific rotated grid within a specific block in the -#cat: image. Note that the input image is modified upon return -#cat: form this routine. - - Input: - rotgrids - structure containing the rotated pixel grid offsets - dir - integer direction of the rotated grid to be annontated - idata - input image data to be annotated. - blkoffset - the pixel offset from the origin of the input image to - the origin of the specific block to be annoted - iw - width (in pixels) of the input image - ih - height (in pixels) of the input image - draw_pixel - pixel intensity to be used when drawing on the image - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int drawrotgrid(const ROTGRIDS *rotgrids, const int dir, - unsigned char *idata, const int blkoffset, - const int iw, const int ih, const int draw_pixel) -{ - int i, j, gi; - - /* Check if specified rotation direction is within range of */ - /* rotated grids. */ - if(dir >= rotgrids->ngrids){ - fprintf(stderr, - "ERROR : drawrotgrid : input direction exceeds range of rotated grids\n"); - return(-140); - } - - /* Intialize grid offset index */ - gi = 0; - /* Foreach row in rotated grid ... */ - for(i = 0; i < rotgrids->grid_h; i++){ - /* Foreach column in rotated grid ... */ - for(j = 0; j < rotgrids->grid_w; j++){ - /* Draw pixels from every other rotated row to represent direction */ - /* of line sums used in DFT processing. */ - if(i%2) - *(idata+blkoffset+rotgrids->grids[dir][gi]) = draw_pixel; - /* Bump grid offset index */ - gi++; - } - } - - return(0); -} - -/************************************************************************* -************************************************************************** -#cat: dump_link_table - takes a link table and vectors of minutia IDs -#cat: assigned to its axes and prints the table's contents out -#cat: as formatted text to the specified open file pointer. - - Input: - fpout - open file pointer - link_table - sparse 2D table containing scores of potentially linked - minutia pairs - x_axis - minutia IDs registered along x-axis - y_axis - minutia IDs registered along y-axis - nx_axis - number of minutia registered along x-axis - ny_axis - number of minutia registered along y-axis - tbldim - dimension of each axes of the link table - minutiae - list of minutia points -**************************************************************************/ -void dump_link_table(FILE *fpout, const int *link_table, - const int *x_axis, const int *y_axis, - const int nx_axis, const int ny_axis, const int tbldim, - const MINUTIAE *minutiae) -{ - int i, tx, ty, sentry, entry; - - fprintf(fpout, "DUMP LINK TABLE:\n"); - - fprintf(fpout, "X-AXIS:\n"); - for(i = 0; i < nx_axis; i++){ - fprintf(fpout, "%d: %d,%d\n", i, minutiae->list[x_axis[i]]->x, - minutiae->list[x_axis[i]]->y); - } - - fprintf(fpout, "Y-AXIS:\n"); - for(i = 0; i < ny_axis; i++){ - fprintf(fpout, "%d: %d,%d\n", i, minutiae->list[y_axis[i]]->x, - minutiae->list[y_axis[i]]->y); - } - - fprintf(fpout, "TABLE:\n"); - sentry = 0; - for(ty = 0; ty < ny_axis; ty++){ - entry = sentry; - for(tx = 0; tx < nx_axis; tx++){ - fprintf(fpout, "%7d ", link_table[entry++]); - } - fprintf(fpout, "\n"); - sentry += tbldim; - } -} - diff --git a/libfprint/nbis/mindtct/shape.c b/libfprint/nbis/mindtct/shape.c index 23ba16ca..4e8ea8fd 100644 --- a/libfprint/nbis/mindtct/shape.c +++ b/libfprint/nbis/mindtct/shape.c @@ -36,7 +36,6 @@ identified are necessarily the best available for the purpose. ROUTINES: alloc_shape() free_shape() - dump_shape() shape_from_contour() sort_row_on_x() ***********************************************************************/ @@ -61,7 +60,7 @@ identified are necessarily the best available for the purpose. Zero - Shape successfully allocated and initialized Negative - System error **************************************************************************/ -int alloc_shape(SHAPE **oshape, const int xmin, const int ymin, +static int alloc_shape(SHAPE **oshape, const int xmin, const int ymin, const int xmax, const int ymax) { SHAPE *shape; @@ -181,33 +180,20 @@ void free_shape(SHAPE *shape) /************************************************************************* ************************************************************************** -#cat: dump_shape - Takes an initialized shape structure and dumps its contents -#cat: as formatted text to the specified open file pointer. +#cat: sort_row_on_x - Takes a row structure and sorts its points left-to- +#cat: right on X. Input: - shape - shape structure to be dumped + row - row structure to be sorted Output: - fpout - open file pointer to be written to + row - row structure with points in sorted order **************************************************************************/ -void dump_shape(FILE *fpout, const SHAPE *shape) +static void sort_row_on_x(ROW *row) { - int i, j; - - /* Print the shape's y-limits and number of scanlines. */ - fprintf(fpout, "shape: ymin=%d, ymax=%d, nrows=%d\n", - shape->ymin, shape->ymax, shape->nrows); - - /* Foreach row in the shape... */ - for(i = 0; i < shape->nrows; i++){ - /* Print the current row's y-coord and number of points on the row. */ - fprintf(fpout, "row %d : y=%d, npts=%d\n", i, shape->rows[i]->y, - shape->rows[i]->npts); - /* Print each successive point on the current row. */ - for(j = 0; j < shape->rows[i]->npts; j++){ - fprintf(fpout, "pt %d : %d %d\n", j, shape->rows[i]->xs[j], - shape->rows[i]->y); - } - } + /* Conduct a simple increasing bubble sort on the x-coords */ + /* in the given row. A bubble sort is satisfactory as the */ + /* number of points will be relatively small. */ + bubble_sort_int_inc(row->xs, row->npts); } /************************************************************************* @@ -284,21 +270,3 @@ int shape_from_contour(SHAPE **oshape, const int *contour_x, return(0); } -/************************************************************************* -************************************************************************** -#cat: sort_row_on_x - Takes a row structure and sorts its points left-to- -#cat: right on X. - - Input: - row - row structure to be sorted - Output: - row - row structure with points in sorted order -**************************************************************************/ -void sort_row_on_x(ROW *row) -{ - /* Conduct a simple increasing bubble sort on the x-coords */ - /* in the given row. A bubble sort is satisfactory as the */ - /* number of points will be relatively small. */ - bubble_sort_int_inc(row->xs, row->npts); -} - From 294f9ad44730400800f9de0cd213a7050f6ef2a5 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sun, 28 Oct 2007 22:02:04 +0000 Subject: [PATCH 039/184] Improve print_data structure and on-disk format Drivers now have an ID number. These will be assigned by me and documented on the wiki. 0 cannot be used. Drivers now define a devtype for each device they initialise. This is to cope with the situation where a driver can support varying devices where their print data is incompatible (i.e. image scaling is totally changed). This doesn't apply to any existing supported devices. Print data no longer includes driver name, and includes driver ID instead. Paths to saved print data now include driver ID and devtype, and no longer include driver name. APIs exposed for converting a print_data into a blob which can then be loaded back again later. Useful for systems who don't want to use my simple storage system (which is only aimed at a single user). File format is now defined and will be documented on the wiki. The header is larger as we can no longer rely on directory paths in all scenarios. Print data compat check now checks devtype and driver ID. --- TODO | 9 +- libfprint/core.c | 6 +- libfprint/data.c | 169 +++++++++++++++++++++++++++++++++--- libfprint/drivers/aes4000.c | 1 + libfprint/drivers/upekts.c | 5 +- libfprint/drivers/uru4000.c | 1 + libfprint/fp_internal.h | 28 ++++-- libfprint/fprint.h | 3 + libfprint/img.c | 13 ++- libfprint/imgdev.c | 2 + 10 files changed, 210 insertions(+), 27 deletions(-) diff --git a/TODO b/TODO index f4356063..519ee0e6 100644 --- a/TODO +++ b/TODO @@ -1,6 +1,5 @@ LIBRARY ======= -fingerprint data classifcation by device or device type identification external API documentation test suite against NFIQ compliance set @@ -8,7 +7,9 @@ test suite against NFIQ compliance set DRIVERS ======= Sunplus 895 driver -AES3501 driver +AES1610 driver +AES2501 driver +AES3400/3500 driver ID Mouse driver Support for 2nd generation MS devices Support for 2nd generation UPEK devices @@ -17,10 +18,12 @@ IMAGING ======= aes4000 doesn't work very well, maybe due to small minutia count? PPMM parameter to get_minutiae seems to have no effect +nbis minutiae should be stored in endian-independent format +return images with standard enroll/verify calls MISC ==== upekts/thinkfinger relicensing (GPL --> LGPL) make library optionally asynchronous and maybe thread-safe pkg-config file - +nbis cleanups diff --git a/libfprint/core.c b/libfprint/core.c index d6c36328..40d956fd 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -69,6 +69,10 @@ void fpi_log(enum fpi_log_level level, const char *component, static void register_driver(struct fp_driver *drv) { + if (drv->id == 0) { + fp_err("not registering driver %s: driver ID is 0"); + return; + } registered_drivers = g_list_prepend(registered_drivers, (gpointer) drv); fp_dbg("registered driver %s", drv->name); } @@ -333,7 +337,7 @@ API_EXPORTED int fp_verify_finger(struct fp_dev *dev, return -EINVAL; } - if (!fpi_print_data_compatible(dev, enrolled_print)) { + if (!fpi_print_data_compatible(enrolled_print, dev)) { fp_err("print is not compatible with device"); return -EINVAL; } diff --git a/libfprint/data.c b/libfprint/data.c index 6eba48ce..4bd6e91b 100644 --- a/libfprint/data.c +++ b/libfprint/data.c @@ -67,16 +67,114 @@ static const char *finger_code_to_str(enum fp_finger finger) return names[finger]; } +static enum fp_print_data_type get_data_type_for_dev(struct fp_dev *dev) +{ + switch (dev->drv->type) { + case DRIVER_PRIMITIVE: + return PRINT_DATA_RAW; + case DRIVER_IMAGING: + return PRINT_DATA_NBIS_MINUTIAE; + default: + fp_err("unrecognised drv type %d", dev->drv->type); + return PRINT_DATA_RAW; + } +} + +static struct fp_print_data *print_data_new(uint16_t driver_id, + uint32_t devtype, enum fp_print_data_type type, size_t length) +{ + struct fp_print_data *data = g_malloc(sizeof(*data) + length); + fp_dbg("length=%zd driver=%02x devtype=%04x", length, driver_id, devtype); + memset(data, 0, sizeof(*data)); + data->driver_id = driver_id; + data->devtype = devtype; + data->type = type; + data->length = length; + return data; +} + struct fp_print_data *fpi_print_data_new(struct fp_dev *dev, size_t length) { struct fp_print_data *data = g_malloc(sizeof(*data) + length); memset(data, 0, sizeof(*data)); - fp_dbg("length=%zd", length); - data->driver_name = dev->drv->name; - data->length = length; + return print_data_new(dev->drv->id, dev->devtype, + get_data_type_for_dev(dev), length); +} + +API_EXPORTED size_t fp_print_data_get_data(struct fp_print_data *data, + unsigned char **ret) +{ + struct fpi_print_data_fp1 *buf; + size_t buflen; + + fp_dbg(""); + + buflen = sizeof(*buf) + data->length; + buf = malloc(buflen); + if (!buf) + return 0; + + *ret = (unsigned char *) buf; + buf->prefix[0] = 'F'; + buf->prefix[1] = 'P'; + buf->prefix[2] = '1'; + buf->driver_id = GUINT16_TO_LE(data->driver_id); + buf->devtype = GUINT32_TO_LE(data->devtype); + buf->data_type = data->type; + memcpy(buf->data, data->data, data->length); + return buflen; +} + +API_EXPORTED struct fp_print_data *fp_print_data_from_data(unsigned char *buf, + size_t buflen) +{ + struct fpi_print_data_fp1 *raw = (struct fpi_print_data_fp1 *) buf; + size_t print_data_len; + struct fp_print_data *data; + + fp_dbg("buffer size %zd", buflen); + if (buflen < sizeof(*raw)) + return NULL; + + if (strncmp(raw->prefix, "FP1", 3) != 0) { + fp_dbg("bad header prefix"); + return NULL; + } + + print_data_len = buflen - sizeof(*raw); + data = print_data_new(GUINT16_FROM_LE(raw->driver_id), + GUINT32_FROM_LE(raw->devtype), raw->data_type, print_data_len); + memcpy(data->data, raw->data, print_data_len); return data; } +static char *__get_path_to_storedir(uint16_t driver_id, uint32_t devtype) +{ + char idstr[5]; + char devtypestr[9]; + + g_snprintf(idstr, sizeof(idstr), "%04x", driver_id); + g_snprintf(devtypestr, sizeof(devtypestr), "%08x", devtype); + + return g_build_filename(base_store, idstr, devtypestr, NULL); +} + +static char *get_path_to_storedir(struct fp_dev *dev) +{ + return __get_path_to_storedir(dev->drv->id, dev->devtype); +} + +static char *get_path_to_print(struct fp_dev *dev, const char *fingerstr) +{ + char *dirpath; + char *path; + + dirpath = get_path_to_storedir(dev); + path = g_build_filename(dirpath, fingerstr, NULL); + g_free(dirpath); + return path; +} + API_EXPORTED int fp_print_data_save(struct fp_print_data *data, enum fp_finger finger) { @@ -84,6 +182,8 @@ API_EXPORTED int fp_print_data_save(struct fp_print_data *data, char *path; char *dirpath; const char *fingerstr = finger_code_to_str(finger); + unsigned char *buf; + size_t len; int r; if (!fingerstr) @@ -92,8 +192,12 @@ API_EXPORTED int fp_print_data_save(struct fp_print_data *data, if (!base_store) storage_setup(); - fp_dbg("save %s print from %s", fingerstr, data->driver_name); - dirpath = g_build_filename(base_store, data->driver_name, NULL); + fp_dbg("save %s print from driver %04x", fingerstr, data->driver_id); + len = fp_print_data_get_data(data, &buf); + if (!len) + return -ENOMEM; + + dirpath = __get_path_to_storedir(data->driver_id, data->devtype); r = g_mkdir_with_parents(dirpath, DIR_PERMS); if (r < 0) { fp_err("couldn't create storage directory"); @@ -103,19 +207,57 @@ API_EXPORTED int fp_print_data_save(struct fp_print_data *data, path = g_build_filename(dirpath, fingerstr, NULL); fp_dbg("saving to %s", path); - g_file_set_contents(path, data->buffer, data->length, &err); + g_file_set_contents(path, buf, len, &err); + free(buf); g_free(dirpath); g_free(path); if (err) { r = err->code; fp_err("%s save failed: %s", fingerstr, err->message); g_error_free(err); + /* FIXME interpret error codes */ return r; } return 0; } +gboolean fpi_print_data_compatible(struct fp_print_data *data, + struct fp_dev *dev) +{ + struct fp_driver *drv = dev->drv; + + if (drv->id != data->driver_id) { + fp_dbg("driver name mismatch: %02x vs %02x", drv->id, data->driver_id); + return FALSE; + } + + if (dev->devtype != data->devtype) { + fp_dbg("devtype mismatch: %04x vs %04x", dev->devtype, data->devtype); + return FALSE; + } + + switch (data->type) { + case PRINT_DATA_RAW: + if (drv->type != DRIVER_PRIMITIVE) { + fp_dbg("raw data vs primitive driver mismatch"); + return FALSE; + } + break; + case PRINT_DATA_NBIS_MINUTIAE: + if (drv->type != DRIVER_IMAGING) { + fp_dbg("minutiae data vs imaging driver mismatch"); + return FALSE; + } + break; + default: + fp_err("unrecognised data type %d", data->type); + return FALSE; + } + + return TRUE; +} + API_EXPORTED int fp_print_data_load(struct fp_dev *dev, enum fp_finger finger, struct fp_print_data **data) { @@ -132,7 +274,7 @@ API_EXPORTED int fp_print_data_load(struct fp_dev *dev, if (!base_store) storage_setup(); - path = g_build_filename(base_store, dev->drv->name, fingerstr, NULL); + path = get_path_to_print(dev, fingerstr); fp_dbg("from %s", path); g_file_get_contents(path, &contents, &length, &err); g_free(path); @@ -147,9 +289,14 @@ API_EXPORTED int fp_print_data_load(struct fp_dev *dev, return r; } - fdata = fpi_print_data_new(dev, length); - memcpy(fdata->buffer, contents, length); + fdata = fp_print_data_from_data(contents, length); g_free(contents); + + if (!fpi_print_data_compatible(fdata, dev)) { + fp_err("print data is not compatible!"); + return -EINVAL; + } + *data = fdata; return 0; } @@ -159,7 +306,3 @@ API_EXPORTED void fp_print_data_free(struct fp_print_data *data) g_free(data); } -int fpi_print_data_compatible(struct fp_dev *dev, struct fp_print_data *data) -{ - return strcmp(dev->drv->name, data->driver_name) == 0; -} diff --git a/libfprint/drivers/aes4000.c b/libfprint/drivers/aes4000.c index cbbcfbf0..5ad08d2a 100644 --- a/libfprint/drivers/aes4000.c +++ b/libfprint/drivers/aes4000.c @@ -210,6 +210,7 @@ static const struct usb_id id_table[] = { struct fp_img_driver aes4000_driver = { .driver = { + .id = 3, .name = FP_COMPONENT, .full_name = "AuthenTec AES4000", .id_table = id_table, diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index be958e34..8287d5c8 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -653,7 +653,7 @@ static int enroll(struct fp_dev *dev, gboolean initial, } fdata = fpi_print_data_new(dev, data_len - sizeof(scan_comp)); - memcpy(fdata->buffer, data + sizeof(scan_comp), data_len - sizeof(scan_comp)); + memcpy(fdata->data, data + sizeof(scan_comp), data_len - sizeof(scan_comp)); *_data = fdata; comp_out: g_free(data); @@ -679,7 +679,7 @@ static int verify(struct fp_dev *dev, struct fp_print_data *print) data = g_malloc(data_len); memcpy(data, verify_hdr, sizeof(verify_hdr)); - memcpy(data + sizeof(verify_hdr), print->buffer, print->length); + memcpy(data + sizeof(verify_hdr), print->data, print->length); r = send_cmd28(dev, 0x03, data, data_len); if (r < 0) @@ -781,6 +781,7 @@ static const struct usb_id id_table[] = { }; struct fp_driver upekts_driver = { + .id = 1, .name = FP_COMPONENT, .full_name = "UPEK TouchStrip", .id_table = id_table, diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index f11aa89a..b81da652 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -489,6 +489,7 @@ static const struct usb_id id_table[] = { struct fp_img_driver uru4000_driver = { .driver = { + .id = 2, .name = FP_COMPONENT, .full_name = "Digital Persona U.are.U 4000/4000B", .id_table = id_table, diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 12ec764d..cba79acc 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -78,6 +78,7 @@ void fpi_log(enum fpi_log_level, const char *component, const char *function, struct fp_dev { struct fp_driver *drv; usb_dev_handle *udev; + uint32_t devtype; void *priv; int nr_enroll_stages; @@ -104,6 +105,7 @@ enum fp_driver_type { }; struct fp_driver { + const uint16_t id; const char *name; const char *full_name; const struct usb_id * const id_table; @@ -152,14 +154,30 @@ struct fp_dscv_dev { unsigned long driver_data; }; -struct fp_print_data { - const char *driver_name; - size_t length; - unsigned char buffer[0]; +enum fp_print_data_type { + PRINT_DATA_RAW = 0, /* memset-imposed default */ + PRINT_DATA_NBIS_MINUTIAE, }; +struct fp_print_data { + uint16_t driver_id; + uint32_t devtype; + enum fp_print_data_type type; + size_t length; + unsigned char data[0]; +}; + +struct fpi_print_data_fp1 { + char prefix[3]; + uint16_t driver_id; + uint32_t devtype; + unsigned char data_type; + unsigned char data[0]; +} __attribute__((__packed__)); + struct fp_print_data *fpi_print_data_new(struct fp_dev *dev, size_t length); -int fpi_print_data_compatible(struct fp_dev *dev, struct fp_print_data *data); +gboolean fpi_print_data_compatible(struct fp_print_data *data, + struct fp_dev *dev); /* bit values for fp_img.flags */ #define FP_IMG_V_FLIPPED (1<<0) diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 89d05c78..15ea3654 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -87,6 +87,9 @@ int fp_print_data_load(struct fp_dev *dev, enum fp_finger finger, struct fp_print_data **data); int fp_print_data_save(struct fp_print_data *data, enum fp_finger finger); void fp_print_data_free(struct fp_print_data *data); +size_t fp_print_data_get_data(struct fp_print_data *data, unsigned char **ret); +struct fp_print_data *fp_print_data_from_data(unsigned char *buf, + size_t buflen); /* Imaging devices */ int fp_imgdev_capture(struct fp_img_dev *imgdev, int unconditional, diff --git a/libfprint/img.c b/libfprint/img.c index b2db8b8f..f421c36d 100644 --- a/libfprint/img.c +++ b/libfprint/img.c @@ -243,7 +243,8 @@ int fpi_img_detect_minutiae(struct fp_img_dev *imgdev, struct fp_img *img, /* FIXME: space is wasted if we dont hit the max minutiae count. would * be good to make this dynamic. */ print = fpi_print_data_new(imgdev->dev, sizeof(struct xyt_struct)); - minutiae_to_xyt(minutiae, bw, bh, print->buffer); + print->type = PRINT_DATA_NBIS_MINUTIAE; + minutiae_to_xyt(minutiae, bw, bh, print->data); /* FIXME: the print buffer at this point is endian-specific, and will * only work when loaded onto machines with identical endianness. not good! * data format should be platform-independant. */ @@ -263,11 +264,17 @@ int fpi_img_detect_minutiae(struct fp_img_dev *imgdev, struct fp_img *img, int fpi_img_compare_print_data(struct fp_print_data *enrolled_print, struct fp_print_data *new_print) { - struct xyt_struct *gstruct = (struct xyt_struct *) enrolled_print->buffer; - struct xyt_struct *pstruct = (struct xyt_struct *) new_print->buffer; + struct xyt_struct *gstruct = (struct xyt_struct *) enrolled_print->data; + struct xyt_struct *pstruct = (struct xyt_struct *) new_print->data; GTimer *timer; int r; + if (enrolled_print->type != PRINT_DATA_NBIS_MINUTIAE || + new_print->type != PRINT_DATA_NBIS_MINUTIAE) { + fp_err("invalid print format"); + return -EINVAL; + } + timer = g_timer_new(); r = bozorth_main(pstruct, gstruct); g_timer_stop(timer); diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index 9355bb4e..b5431dda 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -195,6 +195,8 @@ static int img_dev_verify(struct fp_dev *dev, r = fpi_img_compare_print_data(enrolled_print, print); fp_print_data_free(print); + if (r < 0) + return r; if (r >= 40) return FP_VERIFY_MATCH; else From 6f633cc771c5290593880c79304234eafb5e8e83 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 29 Oct 2007 23:06:06 +0000 Subject: [PATCH 040/184] Use glib's byte order functions --- libfprint/drivers/upekts.c | 14 +++++++------- libfprint/drivers/uru4000.c | 4 ++-- libfprint/fp_internal.h | 26 -------------------------- 3 files changed, 9 insertions(+), 35 deletions(-) diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index 8287d5c8..2571a829 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -148,7 +148,7 @@ static int send_cmd(struct fp_dev *dev, unsigned char seq_a, /* Write header */ strncpy(buf, "Ciao", 4); - len = cpu_to_le16(len); + len = GUINT16_TO_LE(len); buf[4] = seq_a; buf[5] = seq_b | ((len & 0xf00) >> 8); buf[6] = len & 0x00ff; @@ -158,7 +158,7 @@ static int send_cmd(struct fp_dev *dev, unsigned char seq_a, memcpy(buf + 7, data, len); /* Append CRC */ - crc = cpu_to_be16(udf_crc(buf + 4, urblen - 6)); + crc = GUINT16_TO_BE(udf_crc(buf + 4, urblen - 6)); buf[urblen - 2] = crc >> 8; buf[urblen - 1] = crc & 0xff; @@ -187,7 +187,7 @@ static int send_cmd28(struct fp_dev *dev, unsigned char subcmd, fp_dbg("seq=%02x subcmd=%02x with %d bytes of data", seq, subcmd, innerlen); - _innerlen = cpu_to_le16(innerlen + 3); + _innerlen = GUINT16_TO_LE(innerlen + 3); buf[0] = 0x28; buf[1] = _innerlen & 0x00ff; buf[2] = (_innerlen & 0xff00) >> 8; @@ -233,7 +233,7 @@ static unsigned char *__read_msg(struct fp_dev *dev, size_t *data_len) goto err; } - len = le16_to_cpu(((buf[5] & 0xf) << 8) | buf[6]); + len = GUINT16_FROM_LE(((buf[5] & 0xf) << 8) | buf[6]); if (r != MSG_READ_BUF_SIZE && (len + 9) < r) { /* Check that the length claimed inside the message is in line with @@ -263,7 +263,7 @@ static unsigned char *__read_msg(struct fp_dev *dev, size_t *data_len) } computed_crc = udf_crc(buf + 4, len + 3); - msg_crc = le16_to_cpu((buf[len + 8] << 8) | buf[len + 7]); + msg_crc = GUINT16_FROM_LE((buf[len + 8] << 8) | buf[len + 7]); if (computed_crc != msg_crc) { fp_err("CRC failed, got %04x expected %04x", msg_crc, computed_crc); goto err; @@ -301,7 +301,7 @@ retry: code_a = buf[4]; code_b = buf[5] & 0xf0; - len = le16_to_cpu(((buf[5] & 0xf) << 8) | buf[6]); + len = GUINT16_FROM_LE(((buf[5] & 0xf) << 8) | buf[6]); fp_dbg("A=%02x B=%02x len=%d", code_a, code_b, len); if (code_a && !code_b) { @@ -346,7 +346,7 @@ retry: } innerlen = innerbuf[1] | (innerbuf[2] << 8); - innerlen = le16_to_cpu(innerlen) - 3; + innerlen = GUINT16_FROM_LE(innerlen) - 3; _subcmd = innerbuf[5]; fp_dbg("device responds to subcmd %x with %d bytes", _subcmd, innerlen); if (seq) diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index b81da652..04c76e37 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -188,7 +188,7 @@ retry: return -EIO; } - type = be16_to_cpu(*((uint16_t *) buf)); + type = GUINT16_FROM_BE(*((uint16_t *) buf)); fp_dbg("irq type %04x", type); return 0; @@ -212,7 +212,7 @@ static int get_irq_with_type(struct fp_img_dev *dev, uint16_t irqtype, r = get_irq(dev, irqbuf, timeout); if (r < 0) return r; - hdr = be16_to_cpu(*((uint16_t *) irqbuf)); + hdr = GUINT16_FROM_BE(*((uint16_t *) irqbuf)); } while (hdr != irqtype); if (discarded > 0) diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index cba79acc..f6e7d304 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -21,22 +21,11 @@ #define __FPRINT_INTERNAL_H__ #include - #include #include #include -#ifdef __DARWIN_NULL -/* Darwin does endianness slightly differently */ -#include -#define __BYTE_ORDER BYTE_ORDER -#define __LITTLE_ENDIAN LITTLE_ENDIAN -#define __BIG_ENDIAN BIG_ENDIAN -#else /* Linux */ -#include -#endif - #include #define ARRAY_SIZE(a) (sizeof(a) / sizeof(*a)) @@ -201,20 +190,5 @@ int fpi_img_detect_minutiae(struct fp_img_dev *imgdev, struct fp_img *img, int fpi_img_compare_print_data(struct fp_print_data *enrolled_print, struct fp_print_data *new_print); -#define bswap16(x) (((x & 0xff) << 8) | (x >> 8)) -#if __BYTE_ORDER == __LITTLE_ENDIAN -#define cpu_to_le16(x) (x) -#define le16_to_cpu(x) (x) -#define cpu_to_be16(x) bswap16(x) -#define be16_to_cpu(x) bswap16(x) -#elif __BYTE_ORDER == __BIG_ENDIAN -#define cpu_to_le16(x) bswap16(x) -#define le16_to_cpu(x) bswap16(x) -#define cpu_to_be16(x) (x) -#define be16_to_cpu(x) (x) -#else -#error "Unrecognized endianness" -#endif - #endif From f0ef386f43d944430654f3ef486464db5717b4c9 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 29 Oct 2007 23:37:28 +0000 Subject: [PATCH 041/184] More NBIS cleanups --- TODO | 2 + configure.ac | 2 +- libfprint/Makefile.am | 7 +- libfprint/nbis/include/lfs.h | 83 +- libfprint/nbis/mindtct/chaincod.c | 191 ----- libfprint/nbis/mindtct/contour.c | 460 +++++------ libfprint/nbis/mindtct/detect.c | 112 ++- libfprint/nbis/mindtct/getmin.c | 155 ---- libfprint/nbis/mindtct/isempty.c | 94 --- libfprint/nbis/mindtct/link.c | 1238 ----------------------------- libfprint/nbis/mindtct/loop.c | 151 ++++ libfprint/nbis/mindtct/minutia.c | 48 ++ libfprint/nbis/mindtct/quality.c | 302 +++---- libfprint/nbis/mindtct/remove.c | 1227 ---------------------------- libfprint/nbis/mindtct/ridges.c | 791 +++++++++--------- libfprint/nbis/mindtct/xytreps.c | 133 ---- 16 files changed, 1063 insertions(+), 3933 deletions(-) delete mode 100644 libfprint/nbis/mindtct/chaincod.c delete mode 100644 libfprint/nbis/mindtct/getmin.c delete mode 100644 libfprint/nbis/mindtct/isempty.c delete mode 100644 libfprint/nbis/mindtct/link.c delete mode 100644 libfprint/nbis/mindtct/xytreps.c diff --git a/TODO b/TODO index 519ee0e6..d417f759 100644 --- a/TODO +++ b/TODO @@ -27,3 +27,5 @@ upekts/thinkfinger relicensing (GPL --> LGPL) make library optionally asynchronous and maybe thread-safe pkg-config file nbis cleanups +track open devices, so we can close them during libfprint close +free memory during libfprint close diff --git a/configure.ac b/configure.ac index 6c372a30..d6a0c4a8 100644 --- a/configure.ac +++ b/configure.ac @@ -3,7 +3,7 @@ AM_INIT_AUTOMAKE AC_CONFIG_SRCDIR([libfprint/core.c]) AM_CONFIG_HEADER([config.h]) -AC_PREREQ([2.61]) +AC_PREREQ([2.50]) AC_PROG_CC AC_PROG_LIBTOOL AC_C_INLINE diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index c537b764..f6e7e07f 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -15,18 +15,14 @@ NBIS_SRC = \ nbis/bozorth3/bz_sort.c \ nbis/mindtct/binar.c \ nbis/mindtct/block.c \ - nbis/mindtct/chaincod.c \ nbis/mindtct/contour.c \ nbis/mindtct/detect.c \ nbis/mindtct/dft.c \ nbis/mindtct/free.c \ - nbis/mindtct/getmin.c \ nbis/mindtct/globals.c \ nbis/mindtct/imgutil.c \ nbis/mindtct/init.c \ - nbis/mindtct/isempty.c \ nbis/mindtct/line.c \ - nbis/mindtct/link.c \ nbis/mindtct/log.c \ nbis/mindtct/loop.c \ nbis/mindtct/maps.c \ @@ -38,8 +34,7 @@ NBIS_SRC = \ nbis/mindtct/ridges.c \ nbis/mindtct/shape.c \ nbis/mindtct/sort.c \ - nbis/mindtct/util.c \ - nbis/mindtct/xytreps.c + nbis/mindtct/util.c libfprint_la_CFLAGS = -fvisibility=hidden -Inbis/include $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) $(AM_CFLAGS) libfprint_la_LDFLAGS = -version-info @lt_major@:@lt_revision@:@lt_age@ diff --git a/libfprint/nbis/include/lfs.h b/libfprint/nbis/include/lfs.h index f260c488..c184425b 100644 --- a/libfprint/nbis/include/lfs.h +++ b/libfprint/nbis/include/lfs.h @@ -721,12 +721,9 @@ extern int find_valid_block(int *, int *, int *, int *, int *, const int, const int); extern void set_margin_blocks(int *, const int, const int, const int); -/* chaincod.c */ -extern int chain_code_loop(int **, int *, const int *, const int *, const int); -extern int is_chain_clockwise(const int *, const int, const int); - /* contour.c */ -extern int allocate_contour(int **, int **, int **, int **, const int); +int allocate_contour(int **ocontour_x, int **ocontour_y, + int **ocontour_ex, int **ocontour_ey, const int ncontour); extern void free_contour(int *, int *, int *, int *); extern int get_high_curvature_contour(int **, int **, int **, int **, int *, const int, const int, const int, const int, const int, @@ -741,11 +738,6 @@ extern int trace_contour(int **, int **, int **, int **, int *, extern int search_contour(const int, const int, const int, const int, const int, const int, const int, const int, unsigned char *, const int, const int); -extern int next_contour_pixel(int *, int *, int *, int *, - const int, const int, const int, const int, const int, - unsigned char *, const int, const int); -extern int start_scan_nbr(const int, const int, const int, const int); -extern int next_scan_nbr(const int, const int); extern int min_contour_theta(int *, double *, const int, const int *, const int *, const int); extern void contour_limits(int *, int *, int *, int *, const int *, @@ -754,11 +746,11 @@ extern void fix_edge_pixel_pair(int *, int *, int *, int *, unsigned char *, const int, const int); /* detect.c */ -extern int lfs_detect_minutiae_V2(MINUTIAE **, - int **, int **, int **, int **, int *, int *, - unsigned char **, int *, int *, - unsigned char *, const int, const int, - const LFSPARMS *); +extern int get_minutiae(MINUTIAE **, int **, int **, int **, + int **, int **, int *, int *, + unsigned char **, int *, int *, int *, + unsigned char *, const int, const int, + const int, const double, const LFSPARMS *); /* dft.c */ extern int dft_dir_powers(double **, unsigned char *, const int, @@ -773,13 +765,6 @@ extern void free_dftwaves(DFTWAVES *); extern void free_rotgrids(ROTGRIDS *); extern void free_dir_powers(double **, const int); -/* getmin.c */ -extern int get_minutiae(MINUTIAE **, int **, int **, int **, - int **, int **, int *, int *, - unsigned char **, int *, int *, int *, - unsigned char *, const int, const int, - const int, const double, const LFSPARMS *); - /* imgutil.c */ extern void bits_6to8(unsigned char *, const int, const int); extern void bits_8to6(unsigned char *, const int, const int); @@ -804,33 +789,10 @@ extern int init_rotgrids(ROTGRIDS **, const int, const int, const int, extern int alloc_dir_powers(double ***, const int, const int); extern int alloc_power_stats(int **, double **, int **, double **, const int); -/* isempty.c */ -extern int is_image_empty(int *, const int, const int); -extern int is_qmap_empty(int *, const int, const int); - - /* line.c */ extern int line_points(int **, int **, int *, const int, const int, const int, const int); -/* link.c */ -extern int link_minutiae(MINUTIAE *, unsigned char *, const int, const int, - int *, const int, const int, const LFSPARMS *); -extern int create_link_table(int **, int **, int **, int *, int *, int *, - const int, const int, const MINUTIAE *, const int *, - int *, const int, const int, unsigned char *, - const int, const int, const LFSPARMS *); -extern int update_link_table(int *, int *, int *, int *, int *, int *, - const int, int *, int *, int *, int *, - const int, const int, const int); -extern int order_link_table(int *, int *, int *, const int, const int, - const int, const int, const MINUTIAE *, const int); -extern int process_link_table(const int *, const int *, const int *, - const int, const int, const int, const int, MINUTIAE *, - int *, unsigned char *, const int, const int, - const LFSPARMS *); -extern double link_score(const double, const double, const LFSPARMS *); - /* loop.c */ extern int get_loop_list(int **, MINUTIAE *, const int, unsigned char *, const int, const int); @@ -1022,6 +984,8 @@ extern int adjust_high_curvature_minutia_V2(int *, int *, int *, int *, MINUTIAE *, const LFSPARMS *); extern int get_low_curvature_direction(const int, const int, const int, const int); +void lfs2nist_minutia_XYT(int *ox, int *oy, int *ot, + const MINUTIA *minutia, const int iw, const int ih); /* quality.c */ extern int gen_quality_map(int **, int *, int *, int *, int *, @@ -1029,12 +993,6 @@ extern int gen_quality_map(int **, int *, int *, int *, int *, extern int combined_minutia_quality(MINUTIAE *, int *, const int, const int, const int, unsigned char *, const int, const int, const int, const double); -double grayscale_reliability(MINUTIA *, unsigned char *, - const int, const int, const int); -extern void get_neighborhood_stats(double *, double *, MINUTIA *, - unsigned char *, const int, const int, const int); -extern int reliability_fr_quality_map(MINUTIAE *, int *, const int, - const int, const int, const int, const int); /* remove.c */ extern int remove_false_minutia(MINUTIAE *, @@ -1049,23 +1007,6 @@ extern int remove_false_minutia_V2(MINUTIAE *, extern int count_minutiae_ridges(MINUTIAE *, unsigned char *, const int, const int, const LFSPARMS *); -extern int count_minutia_ridges(const int, MINUTIAE *, - unsigned char *, const int, const int, - const LFSPARMS *); -extern int find_neighbors(int **, int *, const int, const int, MINUTIAE *); -extern int update_nbr_dists(int *, double *, int *, const int, - const int, const int, MINUTIAE *); -extern int insert_neighbor(const int, const int, const double, - int *, double *, int *, const int); -extern int sort_neighbors(int *, const int, const int, MINUTIAE *); -extern int ridge_count(const int, const int, MINUTIAE *, - unsigned char *, const int, const int, const LFSPARMS *); -extern int find_transition(int *, const int, const int, - const int *, const int *, const int, - unsigned char *, const int, const int); -extern int validate_ridge_crossing(const int, const int, - const int *, const int *, const int, - unsigned char *, const int, const int, const int); /* shape.c */ extern void free_shape(SHAPE *); @@ -1094,12 +1035,6 @@ extern int line2direction(const int, const int, const int, const int, const int); extern int closest_dir_dist(const int, const int, const int); -/* xytreps.c */ -extern void lfs2nist_minutia_XYT(int *, int *, int *, - const MINUTIA *, const int, const int); -extern void lfs2m1_minutia_XYT(int *, int *, int *, const MINUTIA *); - - /*************************************************************************/ /* EXTERNAL GLOBAL VARIABLE DEFINITIONS */ /*************************************************************************/ diff --git a/libfprint/nbis/mindtct/chaincod.c b/libfprint/nbis/mindtct/chaincod.c deleted file mode 100644 index 006c996d..00000000 --- a/libfprint/nbis/mindtct/chaincod.c +++ /dev/null @@ -1,191 +0,0 @@ -/******************************************************************************* - -License: -This software was developed at the National Institute of Standards and -Technology (NIST) by employees of the Federal Government in the course -of their official duties. Pursuant to title 17 Section 105 of the -United States Code, this software is not subject to copyright protection -and is in the public domain. NIST assumes no responsibility whatsoever for -its use by other parties, and makes no guarantees, expressed or implied, -about its quality, reliability, or any other characteristic. - -Disclaimer: -This software was developed to promote biometric standards and biometric -technology testing for the Federal Government in accordance with the USA -PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. -Specific hardware and software products identified in this software were used -in order to perform the software development. In no case does such -identification imply recommendation or endorsement by the National Institute -of Standards and Technology, nor does it imply that the products and equipment -identified are necessarily the best available for the purpose. - -*******************************************************************************/ - -/*********************************************************************** - LIBRARY: LFS - NIST Latent Fingerprint System - - FILE: CHAINCODE.C - AUTHOR: Michael D. Garris - DATE: 05/11/1999 - - Contains routines responsible for generating and manipulating - chain codes as part of the NIST Latent Fingerprint System (LFS). - -*********************************************************************** - ROUTINES: - chain_code_loop() - is_chain_clockwise() -***********************************************************************/ - -#include -#include -#include - -/************************************************************************* -************************************************************************** -#cat: chain_code_loop - Converts a feature's contour points into an -#cat: 8-connected chain code vector. This encoding represents -#cat: the direction taken between each adjacent point in the -#cat: contour. Chain codes may be used for many purposes, such -#cat: as computing the perimeter or area of an object, and they -#cat: may be used in object detection and recognition. - - Input: - contour_x - x-coord list for feature's contour points - contour_y - y-coord list for feature's contour points - ncontour - number of points in contour - Output: - ochain - resulting vector of chain codes - onchain - number of codes in chain - (same as number of points in contour) - Return Code: - Zero - chain code successful derived - Negative - system error -**************************************************************************/ -int chain_code_loop(int **ochain, int *onchain, - const int *contour_x, const int *contour_y, const int ncontour) -{ - int *chain; - int i, j, dx, dy; - - /* If we don't have at least 3 points in the contour ... */ - if(ncontour <= 3){ - /* Then we don't have a loop, so set chain length to 0 */ - /* and return without any allocations. */ - *onchain = 0; - return(0); - } - - /* Allocate chain code vector. It will be the same length as the */ - /* number of points in the contour. There will be one chain code */ - /* between each point on the contour including a code between the */ - /* last to the first point on the contour (completing the loop). */ - chain = (int *)malloc(ncontour * sizeof(int)); - /* If the allocation fails ... */ - if(chain == (int *)NULL){ - fprintf(stderr, "ERROR : chain_code_loop : malloc : chain\n"); - return(-170); - } - - /* For each neighboring point in the list (with "i" pointing to the */ - /* previous neighbor and "j" pointing to the next neighbor... */ - for(i = 0, j=1; i < ncontour-1; i++, j++){ - /* Compute delta in X between neighbors. */ - dx = contour_x[j] - contour_x[i]; - /* Compute delta in Y between neighbors. */ - dy = contour_y[j] - contour_y[i]; - /* Derive chain code index from neighbor deltas. */ - /* The deltas are on the range [-1..1], so to use them as indices */ - /* into the code list, they must first be incremented by one. */ - chain[i] = *(chaincodes_nbr8+((dy+1)*NBR8_DIM)+dx+1); - } - - /* Now derive chain code between last and first points in the */ - /* contour list. */ - dx = contour_x[0] - contour_x[i]; - dy = contour_y[0] - contour_y[i]; - chain[i] = *(chaincodes_nbr8+((dy+1)*NBR8_DIM)+dx+1); - - /* Store results to the output pointers. */ - *ochain = chain; - *onchain = ncontour; - - /* Return normally. */ - return(0); -} - -/************************************************************************* -************************************************************************** -#cat: is_chain_clockwise - Takes an 8-connected chain code vector and -#cat: determines if the codes are ordered clockwise or -#cat: counter-clockwise. -#cat: The routine also requires a default return value be -#cat: specified in the case the the routine is not able to -#cat: definitively determine the chains direction. This allows -#cat: the default response to be application-specific. - - Input: - chain - chain code vector - nchain - number of codes in chain - default_ret - default return code (used when we can't tell the order) - Return Code: - TRUE - chain determined to be ordered clockwise - FALSE - chain determined to be ordered counter-clockwise - Default - could not determine the order of the chain -**************************************************************************/ -int is_chain_clockwise(const int *chain, const int nchain, - const int default_ret) -{ - int i, j, d, sum; - - /* Initialize turn-accumulator to 0. */ - sum = 0; - - /* Foreach neighboring code in chain, compute the difference in */ - /* direction and accumulate. Left-hand turns increment, whereas */ - /* right-hand decrement. */ - for(i = 0, j =1; i < nchain-1; i++, j++){ - /* Compute delta in neighbor direction. */ - d = chain[j] - chain[i]; - /* Make the delta the "inner" distance. */ - /* If delta >= 4, for example if chain_i==2 and chain_j==7 (which */ - /* means the contour went from a step up to step down-to-the-right) */ - /* then 5=(7-2) which is >=4, so -3=(5-8) which means that the */ - /* change in direction is a righ-hand turn of 3 units). */ - if(d >= 4) - d -= 8; - /* If delta <= -4, for example if chain_i==7 and chain_j==2 (which */ - /* means the contour went from a step down-to-the-right to step up) */ - /* then -5=(2-7) which is <=-4, so 3=(-5+8) which means that the */ - /* change in direction is a left-hand turn of 3 units). */ - else if (d <= -4) - d += 8; - - /* The delta direction is then accumulated. */ - sum += d; - } - - /* Now we need to add in the final delta direction between the last */ - /* and first codes in the chain. */ - d = chain[0] - chain[i]; - if(d >= 4) - d -= 8; - else if (d <= -4) - d += 8; - sum += d; - - /* If the final turn_accumulator == 0, then we CAN'T TELL the */ - /* direction of the chain code, so return the default return value. */ - if(sum == 0) - return(default_ret); - /* Otherwise, if the final turn-accumulator is positive ... */ - else if(sum > 0) - /* Then we had a greater amount of left-hand turns than right-hand */ - /* turns, so the chain is in COUNTER-CLOCKWISE order, so return FALSE. */ - return(FALSE); - /* Otherwise, the final turn-accumulator is negative ... */ - else - /* So we had a greater amount of right-hand turns than left-hand */ - /* turns, so the chain is in CLOCKWISE order, so return TRUE. */ - return(TRUE); -} diff --git a/libfprint/nbis/mindtct/contour.c b/libfprint/nbis/mindtct/contour.c index ae434711..24d15c4a 100644 --- a/libfprint/nbis/mindtct/contour.c +++ b/libfprint/nbis/mindtct/contour.c @@ -591,6 +591,236 @@ int get_centered_contour(int **ocontour_x, int **ocontour_y, return(0); } +/************************************************************************* +************************************************************************** +#cat: start_scan_nbr - Takes a two pixel coordinates that are either +#cat: aligned north-to-south or east-to-west, and returns the +#cat: position the second pixel is in realtionship to the first. +#cat: The positions returned are based on 8-connectedness. +#cat: NOTE, this routine does NOT account for diagonal positions. + + Input: + x_prev - x-coord of first point + y_prev - y-coord of first point + x_next - x-coord of second point + y_next - y-coord of second point + Return Code: + NORTH - second pixel above first + SOUTH - second pixel below first + EAST - second pixel right of first + WEST - second pixel left of first +**************************************************************************/ +static int start_scan_nbr(const int x_prev, const int y_prev, + const int x_next, const int y_next) +{ + if((x_prev==x_next) && (y_next > y_prev)) + return(SOUTH); + else if ((x_prev==x_next) && (y_next < y_prev)) + return(NORTH); + else if ((x_next > x_prev) && (y_prev==y_next)) + return(EAST); + else if ((x_next < x_prev) && (y_prev==y_next)) + return(WEST); + + /* Added by MDG on 03-16-05 */ + /* Should never reach here. Added to remove compiler warning. */ + return(INVALID_DIR); /* -1 */ +} + +/************************************************************************* +************************************************************************** +#cat: next_scan_nbr - Advances the given 8-connected neighbor index +#cat: on location in the specifiec direction (clockwise or +#cat: counter-clockwise). + + Input: + nbr_i - current 8-connected neighbor index + scan_clock - direction in which the neighbor index is to be advanced + Return Code: + Next neighbor - 8-connected index of next neighbor +**************************************************************************/ +static int next_scan_nbr(const int nbr_i, const int scan_clock) +{ + int new_i; + + /* If scanning neighbors clockwise ... */ + if(scan_clock == SCAN_CLOCKWISE) + /* Advance one neighbor clockwise. */ + new_i = (nbr_i+1)%8; + /* Otherwise, scanning neighbors counter-clockwise ... */ + else + /* Advance one neighbor counter-clockwise. */ + /* There are 8 pixels in the neighborhood, so to */ + /* decrement with wrapping from 0 around to 7, add */ + /* the nieghbor index by 7 and mod with 8. */ + new_i = (nbr_i+7)%8; + + /* Return the new neighbor index. */ + return(new_i); +} + +/************************************************************************* +************************************************************************** +#cat: next_contour_pixel - Takes a pixel coordinate of a point determined +#cat: to be on the interior edge of a feature (ridge or valley- +#cat: ending), and attempts to locate a neighboring pixel on the +#cat: feature's contour. Neighbors of the current feature pixel +#cat: are searched in a specified direction (clockwise or counter- +#cat: clockwise) and the first pair of adjacent/neigboring pixels +#cat: found with the first pixel having the color of the feature +#cat: and the second the opposite color are returned as the next +#cat: point on the contour. One exception happens when the new +#cat: point is on an "exposed" corner. + + Input: + cur_x_loc - x-pixel coord of current point on feature's + interior contour + cur_y_loc - y-pixel coord of current point on feature's + interior contour + cur_x_edge - x-pixel coord of corresponding edge pixel + (exterior to feature) + cur_y_edge - y-pixel coord of corresponding edge pixel + (exterior to feature) + scan_clock - direction in which neighboring pixels are to be scanned + for the next contour pixel + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + next_x_loc - x-pixel coord of next point on feature's interior contour + next_y_loc - y-pixel coord of next point on feature's interior contour + next_x_edge - x-pixel coord of corresponding edge (exterior to feature) + next_y_edge - y-pixel coord of corresponding edge (exterior to feature) + Return Code: + TRUE - next contour point found and returned + FALSE - next contour point NOT found +**************************************************************************/ +/*************************************************************************/ +static int next_contour_pixel(int *next_x_loc, int *next_y_loc, + int *next_x_edge, int *next_y_edge, + const int cur_x_loc, const int cur_y_loc, + const int cur_x_edge, const int cur_y_edge, + const int scan_clock, + unsigned char *bdata, const int iw, const int ih) +{ + int feature_pix, edge_pix; + int prev_nbr_pix, prev_nbr_x, prev_nbr_y; + int cur_nbr_pix, cur_nbr_x, cur_nbr_y; + int ni, nx, ny, npix; + int nbr_i, i; + + /* Get the feature's pixel value. */ + feature_pix = *(bdata + (cur_y_loc * iw) + cur_x_loc); + /* Get the feature's edge pixel value. */ + edge_pix = *(bdata + (cur_y_edge * iw) + cur_x_edge); + + /* Get the nieghbor position of the feature's edge pixel in relationship */ + /* to the feature's actual position. */ + /* REMEBER: The feature's position is always interior and on a ridge */ + /* ending (black pixel) or (for bifurcations) on a valley ending (white */ + /* pixel). The feature's edge pixel is an adjacent pixel to the feature */ + /* pixel that is exterior to the ridge or valley ending and opposite in */ + /* pixel value. */ + nbr_i = start_scan_nbr(cur_x_loc, cur_y_loc, cur_x_edge, cur_y_edge); + + /* Set current neighbor scan pixel to the feature's edge pixel. */ + cur_nbr_x = cur_x_edge; + cur_nbr_y = cur_y_edge; + cur_nbr_pix = edge_pix; + + /* Foreach pixel neighboring the feature pixel ... */ + for(i = 0; i < 8; i++){ + + /* Set current neighbor scan pixel to previous scan pixel. */ + prev_nbr_x = cur_nbr_x; + prev_nbr_y = cur_nbr_y; + prev_nbr_pix = cur_nbr_pix; + + /* Bump pixel neighbor index clockwise or counter-clockwise. */ + nbr_i = next_scan_nbr(nbr_i, scan_clock); + + /* Set current scan pixel to the new neighbor. */ + /* REMEMBER: the neighbors are being scanned around the original */ + /* feature point. */ + cur_nbr_x = cur_x_loc + nbr8_dx[nbr_i]; + cur_nbr_y = cur_y_loc + nbr8_dy[nbr_i]; + + /* If new neighbor is not within image boundaries... */ + if((cur_nbr_x < 0) || (cur_nbr_x >= iw) || + (cur_nbr_y < 0) || (cur_nbr_y >= ih)) + /* Return (FALSE==>Failure) if neighbor out of bounds. */ + return(FALSE); + + /* Get the new neighbor's pixel value. */ + cur_nbr_pix = *(bdata + (cur_nbr_y * iw) + cur_nbr_x); + + /* If the new neighbor's pixel value is the same as the feature's */ + /* pixel value AND the previous neighbor's pixel value is the same */ + /* as the features's edge, then we have "likely" found our next */ + /* contour pixel. */ + if((cur_nbr_pix == feature_pix) && (prev_nbr_pix == edge_pix)){ + + /* Check to see if current neighbor is on the corner of the */ + /* neighborhood, and if so, test to see if it is "exposed". */ + /* The neighborhood corners have odd neighbor indicies. */ + if(nbr_i % 2){ + /* To do this, look ahead one more neighbor pixel. */ + ni = next_scan_nbr(nbr_i, scan_clock); + nx = cur_x_loc + nbr8_dx[ni]; + ny = cur_y_loc + nbr8_dy[ni]; + /* If new neighbor is not within image boundaries... */ + if((nx < 0) || (nx >= iw) || + (ny < 0) || (ny >= ih)) + /* Return (FALSE==>Failure) if neighbor out of bounds. */ + return(FALSE); + npix = *(bdata + (ny * iw) + nx); + + /* If the next neighbor's value is also the same as the */ + /* feature's pixel, then corner is NOT exposed... */ + if(npix == feature_pix){ + /* Assign the current neighbor pair to the output pointers. */ + *next_x_loc = cur_nbr_x; + *next_y_loc = cur_nbr_y; + *next_x_edge = prev_nbr_x; + *next_y_edge = prev_nbr_y; + /* Return TRUE==>Success. */ + return(TRUE); + } + /* Otherwise, corner pixel is "exposed" so skip it. */ + else{ + /* Skip current corner neighbor by resetting it to the */ + /* next neighbor, which upon the iteration will immediately */ + /* become the previous neighbor. */ + cur_nbr_x = nx; + cur_nbr_y = ny; + cur_nbr_pix = npix; + /* Advance neighbor index. */ + nbr_i = ni; + /* Advance neighbor count. */ + i++; + } + } + /* Otherwise, current neighbor is not a corner ... */ + else{ + /* Assign the current neighbor pair to the output pointers. */ + *next_x_loc = cur_nbr_x; + *next_y_loc = cur_nbr_y; + *next_x_edge = prev_nbr_x; + *next_y_edge = prev_nbr_y; + /* Return TRUE==>Success. */ + return(TRUE); + } + } + } + + /* If we get here, then we did not find the next contour pixel */ + /* within the 8 neighbors of the current feature pixel so */ + /* return (FALSE==>Failure). */ + /* NOTE: This must mean we found a single isolated pixel. */ + /* Perhaps this should be filled? */ + return(FALSE); +} + /************************************************************************* ************************************************************************** #cat: trace_contour - Takes the pixel coordinate of a detected minutia @@ -816,236 +1046,6 @@ int search_contour(const int x_search, const int y_search, return(NOT_FOUND); } -/************************************************************************* -************************************************************************** -#cat: next_contour_pixel - Takes a pixel coordinate of a point determined -#cat: to be on the interior edge of a feature (ridge or valley- -#cat: ending), and attempts to locate a neighboring pixel on the -#cat: feature's contour. Neighbors of the current feature pixel -#cat: are searched in a specified direction (clockwise or counter- -#cat: clockwise) and the first pair of adjacent/neigboring pixels -#cat: found with the first pixel having the color of the feature -#cat: and the second the opposite color are returned as the next -#cat: point on the contour. One exception happens when the new -#cat: point is on an "exposed" corner. - - Input: - cur_x_loc - x-pixel coord of current point on feature's - interior contour - cur_y_loc - y-pixel coord of current point on feature's - interior contour - cur_x_edge - x-pixel coord of corresponding edge pixel - (exterior to feature) - cur_y_edge - y-pixel coord of corresponding edge pixel - (exterior to feature) - scan_clock - direction in which neighboring pixels are to be scanned - for the next contour pixel - bdata - binary image data (0==while & 1==black) - iw - width (in pixels) of image - ih - height (in pixels) of image - Output: - next_x_loc - x-pixel coord of next point on feature's interior contour - next_y_loc - y-pixel coord of next point on feature's interior contour - next_x_edge - x-pixel coord of corresponding edge (exterior to feature) - next_y_edge - y-pixel coord of corresponding edge (exterior to feature) - Return Code: - TRUE - next contour point found and returned - FALSE - next contour point NOT found -**************************************************************************/ -/*************************************************************************/ -int next_contour_pixel(int *next_x_loc, int *next_y_loc, - int *next_x_edge, int *next_y_edge, - const int cur_x_loc, const int cur_y_loc, - const int cur_x_edge, const int cur_y_edge, - const int scan_clock, - unsigned char *bdata, const int iw, const int ih) -{ - int feature_pix, edge_pix; - int prev_nbr_pix, prev_nbr_x, prev_nbr_y; - int cur_nbr_pix, cur_nbr_x, cur_nbr_y; - int ni, nx, ny, npix; - int nbr_i, i; - - /* Get the feature's pixel value. */ - feature_pix = *(bdata + (cur_y_loc * iw) + cur_x_loc); - /* Get the feature's edge pixel value. */ - edge_pix = *(bdata + (cur_y_edge * iw) + cur_x_edge); - - /* Get the nieghbor position of the feature's edge pixel in relationship */ - /* to the feature's actual position. */ - /* REMEBER: The feature's position is always interior and on a ridge */ - /* ending (black pixel) or (for bifurcations) on a valley ending (white */ - /* pixel). The feature's edge pixel is an adjacent pixel to the feature */ - /* pixel that is exterior to the ridge or valley ending and opposite in */ - /* pixel value. */ - nbr_i = start_scan_nbr(cur_x_loc, cur_y_loc, cur_x_edge, cur_y_edge); - - /* Set current neighbor scan pixel to the feature's edge pixel. */ - cur_nbr_x = cur_x_edge; - cur_nbr_y = cur_y_edge; - cur_nbr_pix = edge_pix; - - /* Foreach pixel neighboring the feature pixel ... */ - for(i = 0; i < 8; i++){ - - /* Set current neighbor scan pixel to previous scan pixel. */ - prev_nbr_x = cur_nbr_x; - prev_nbr_y = cur_nbr_y; - prev_nbr_pix = cur_nbr_pix; - - /* Bump pixel neighbor index clockwise or counter-clockwise. */ - nbr_i = next_scan_nbr(nbr_i, scan_clock); - - /* Set current scan pixel to the new neighbor. */ - /* REMEMBER: the neighbors are being scanned around the original */ - /* feature point. */ - cur_nbr_x = cur_x_loc + nbr8_dx[nbr_i]; - cur_nbr_y = cur_y_loc + nbr8_dy[nbr_i]; - - /* If new neighbor is not within image boundaries... */ - if((cur_nbr_x < 0) || (cur_nbr_x >= iw) || - (cur_nbr_y < 0) || (cur_nbr_y >= ih)) - /* Return (FALSE==>Failure) if neighbor out of bounds. */ - return(FALSE); - - /* Get the new neighbor's pixel value. */ - cur_nbr_pix = *(bdata + (cur_nbr_y * iw) + cur_nbr_x); - - /* If the new neighbor's pixel value is the same as the feature's */ - /* pixel value AND the previous neighbor's pixel value is the same */ - /* as the features's edge, then we have "likely" found our next */ - /* contour pixel. */ - if((cur_nbr_pix == feature_pix) && (prev_nbr_pix == edge_pix)){ - - /* Check to see if current neighbor is on the corner of the */ - /* neighborhood, and if so, test to see if it is "exposed". */ - /* The neighborhood corners have odd neighbor indicies. */ - if(nbr_i % 2){ - /* To do this, look ahead one more neighbor pixel. */ - ni = next_scan_nbr(nbr_i, scan_clock); - nx = cur_x_loc + nbr8_dx[ni]; - ny = cur_y_loc + nbr8_dy[ni]; - /* If new neighbor is not within image boundaries... */ - if((nx < 0) || (nx >= iw) || - (ny < 0) || (ny >= ih)) - /* Return (FALSE==>Failure) if neighbor out of bounds. */ - return(FALSE); - npix = *(bdata + (ny * iw) + nx); - - /* If the next neighbor's value is also the same as the */ - /* feature's pixel, then corner is NOT exposed... */ - if(npix == feature_pix){ - /* Assign the current neighbor pair to the output pointers. */ - *next_x_loc = cur_nbr_x; - *next_y_loc = cur_nbr_y; - *next_x_edge = prev_nbr_x; - *next_y_edge = prev_nbr_y; - /* Return TRUE==>Success. */ - return(TRUE); - } - /* Otherwise, corner pixel is "exposed" so skip it. */ - else{ - /* Skip current corner neighbor by resetting it to the */ - /* next neighbor, which upon the iteration will immediately */ - /* become the previous neighbor. */ - cur_nbr_x = nx; - cur_nbr_y = ny; - cur_nbr_pix = npix; - /* Advance neighbor index. */ - nbr_i = ni; - /* Advance neighbor count. */ - i++; - } - } - /* Otherwise, current neighbor is not a corner ... */ - else{ - /* Assign the current neighbor pair to the output pointers. */ - *next_x_loc = cur_nbr_x; - *next_y_loc = cur_nbr_y; - *next_x_edge = prev_nbr_x; - *next_y_edge = prev_nbr_y; - /* Return TRUE==>Success. */ - return(TRUE); - } - } - } - - /* If we get here, then we did not find the next contour pixel */ - /* within the 8 neighbors of the current feature pixel so */ - /* return (FALSE==>Failure). */ - /* NOTE: This must mean we found a single isolated pixel. */ - /* Perhaps this should be filled? */ - return(FALSE); -} - -/************************************************************************* -************************************************************************** -#cat: start_scan_nbr - Takes a two pixel coordinates that are either -#cat: aligned north-to-south or east-to-west, and returns the -#cat: position the second pixel is in realtionship to the first. -#cat: The positions returned are based on 8-connectedness. -#cat: NOTE, this routine does NOT account for diagonal positions. - - Input: - x_prev - x-coord of first point - y_prev - y-coord of first point - x_next - x-coord of second point - y_next - y-coord of second point - Return Code: - NORTH - second pixel above first - SOUTH - second pixel below first - EAST - second pixel right of first - WEST - second pixel left of first -**************************************************************************/ -int start_scan_nbr(const int x_prev, const int y_prev, - const int x_next, const int y_next) -{ - if((x_prev==x_next) && (y_next > y_prev)) - return(SOUTH); - else if ((x_prev==x_next) && (y_next < y_prev)) - return(NORTH); - else if ((x_next > x_prev) && (y_prev==y_next)) - return(EAST); - else if ((x_next < x_prev) && (y_prev==y_next)) - return(WEST); - - /* Added by MDG on 03-16-05 */ - /* Should never reach here. Added to remove compiler warning. */ - return(INVALID_DIR); /* -1 */ -} - -/************************************************************************* -************************************************************************** -#cat: next_scan_nbr - Advances the given 8-connected neighbor index -#cat: on location in the specifiec direction (clockwise or -#cat: counter-clockwise). - - Input: - nbr_i - current 8-connected neighbor index - scan_clock - direction in which the neighbor index is to be advanced - Return Code: - Next neighbor - 8-connected index of next neighbor -**************************************************************************/ -int next_scan_nbr(const int nbr_i, const int scan_clock) -{ - int new_i; - - /* If scanning neighbors clockwise ... */ - if(scan_clock == SCAN_CLOCKWISE) - /* Advance one neighbor clockwise. */ - new_i = (nbr_i+1)%8; - /* Otherwise, scanning neighbors counter-clockwise ... */ - else - /* Advance one neighbor counter-clockwise. */ - /* There are 8 pixels in the neighborhood, so to */ - /* decrement with wrapping from 0 around to 7, add */ - /* the nieghbor index by 7 and mod with 8. */ - new_i = (nbr_i+7)%8; - - /* Return the new neighbor index. */ - return(new_i); -} - /************************************************************************* ************************************************************************** #cat: min_contour_theta - Takes a contour list and analyzes it locating the diff --git a/libfprint/nbis/mindtct/detect.c b/libfprint/nbis/mindtct/detect.c index 3b05d21c..214459b8 100644 --- a/libfprint/nbis/mindtct/detect.c +++ b/libfprint/nbis/mindtct/detect.c @@ -36,6 +36,7 @@ identified are necessarily the best available for the purpose. *********************************************************************** ROUTINES: lfs_detect_minutiae_V2() + get_minutiae() ***********************************************************************/ @@ -80,7 +81,7 @@ identified are necessarily the best available for the purpose. Zero - successful completion Negative - system error **************************************************************************/ -int lfs_detect_minutiae_V2(MINUTIAE **ominutiae, +static int lfs_detect_minutiae_V2(MINUTIAE **ominutiae, int **odmap, int **olcmap, int **olfmap, int **ohcmap, int *omw, int *omh, unsigned char **obdata, int *obw, int *obh, @@ -343,3 +344,112 @@ int lfs_detect_minutiae_V2(MINUTIAE **ominutiae, return(0); } +/************************************************************************* +************************************************************************** +#cat: get_minutiae - Takes a grayscale fingerprint image, binarizes the input +#cat: image, and detects minutiae points using LFS Version 2. +#cat: The routine passes back the detected minutiae, the +#cat: binarized image, and a set of image quality maps. + + Input: + idata - grayscale fingerprint image data + iw - width (in pixels) of the grayscale image + ih - height (in pixels) of the grayscale image + id - pixel depth (in bits) of the grayscale image + ppmm - the scan resolution (in pixels/mm) of the grayscale image + lfsparms - parameters and thresholds for controlling LFS + Output: + ominutiae - points to a structure containing the + detected minutiae + oquality_map - resulting integrated image quality map + odirection_map - resulting direction map + olow_contrast_map - resulting low contrast map + olow_flow_map - resulting low ridge flow map + ohigh_curve_map - resulting high curvature map + omap_w - width (in blocks) of image maps + omap_h - height (in blocks) of image maps + obdata - points to binarized image data + obw - width (in pixels) of binarized image + obh - height (in pixels) of binarized image + obd - pixel depth (in bits) of binarized image + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +int get_minutiae(MINUTIAE **ominutiae, int **oquality_map, + int **odirection_map, int **olow_contrast_map, + int **olow_flow_map, int **ohigh_curve_map, + int *omap_w, int *omap_h, + unsigned char **obdata, int *obw, int *obh, int *obd, + unsigned char *idata, const int iw, const int ih, + const int id, const double ppmm, const LFSPARMS *lfsparms) +{ + int ret; + MINUTIAE *minutiae; + int *direction_map, *low_contrast_map, *low_flow_map; + int *high_curve_map, *quality_map; + int map_w, map_h; + unsigned char *bdata; + int bw, bh; + + /* If input image is not 8-bit grayscale ... */ + if(id != 8){ + fprintf(stderr, "ERROR : get_minutiae : input image pixel "); + fprintf(stderr, "depth = %d != 8.\n", id); + return(-2); + } + + /* Detect minutiae in grayscale fingerpeint image. */ + if((ret = lfs_detect_minutiae_V2(&minutiae, + &direction_map, &low_contrast_map, + &low_flow_map, &high_curve_map, + &map_w, &map_h, + &bdata, &bw, &bh, + idata, iw, ih, lfsparms))){ + return(ret); + } + + /* Build integrated quality map. */ + if((ret = gen_quality_map(&quality_map, + direction_map, low_contrast_map, + low_flow_map, high_curve_map, map_w, map_h))){ + free_minutiae(minutiae); + free(direction_map); + free(low_contrast_map); + free(low_flow_map); + free(high_curve_map); + free(bdata); + return(ret); + } + + /* Assign reliability from quality map. */ + if((ret = combined_minutia_quality(minutiae, quality_map, map_w, map_h, + lfsparms->blocksize, + idata, iw, ih, id, ppmm))){ + free_minutiae(minutiae); + free(direction_map); + free(low_contrast_map); + free(low_flow_map); + free(high_curve_map); + free(quality_map); + free(bdata); + return(ret); + } + + /* Set output pointers. */ + *ominutiae = minutiae; + *oquality_map = quality_map; + *odirection_map = direction_map; + *olow_contrast_map = low_contrast_map; + *olow_flow_map = low_flow_map; + *ohigh_curve_map = high_curve_map; + *omap_w = map_w; + *omap_h = map_h; + *obdata = bdata; + *obw = bw; + *obh = bh; + *obd = id; + + /* Return normally. */ + return(0); +} diff --git a/libfprint/nbis/mindtct/getmin.c b/libfprint/nbis/mindtct/getmin.c deleted file mode 100644 index 22404f14..00000000 --- a/libfprint/nbis/mindtct/getmin.c +++ /dev/null @@ -1,155 +0,0 @@ -/******************************************************************************* - -License: -This software was developed at the National Institute of Standards and -Technology (NIST) by employees of the Federal Government in the course -of their official duties. Pursuant to title 17 Section 105 of the -United States Code, this software is not subject to copyright protection -and is in the public domain. NIST assumes no responsibility whatsoever for -its use by other parties, and makes no guarantees, expressed or implied, -about its quality, reliability, or any other characteristic. - -Disclaimer: -This software was developed to promote biometric standards and biometric -technology testing for the Federal Government in accordance with the USA -PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. -Specific hardware and software products identified in this software were used -in order to perform the software development. In no case does such -identification imply recommendation or endorsement by the National Institute -of Standards and Technology, nor does it imply that the products and equipment -identified are necessarily the best available for the purpose. - -*******************************************************************************/ - -/*********************************************************************** - LIBRARY: LFS - NIST Latent Fingerprint System - - FILE: GETMIN.C - AUTHOR: Michael D. Garris - DATE: 09/10/2004 - UPDATED: 03/16/2005 by MDG - - Takes an 8-bit grayscale fingerpinrt image and detects minutiae - as part of the NIST Latent Fingerprint System (LFS), returning - minutiae with final reliabilities and maps including a merged - quality map. - -*********************************************************************** - ROUTINES: - get_minutiae() - -***********************************************************************/ - -#include -#include -#include - -/************************************************************************* -************************************************************************** -#cat: get_minutiae - Takes a grayscale fingerprint image, binarizes the input -#cat: image, and detects minutiae points using LFS Version 2. -#cat: The routine passes back the detected minutiae, the -#cat: binarized image, and a set of image quality maps. - - Input: - idata - grayscale fingerprint image data - iw - width (in pixels) of the grayscale image - ih - height (in pixels) of the grayscale image - id - pixel depth (in bits) of the grayscale image - ppmm - the scan resolution (in pixels/mm) of the grayscale image - lfsparms - parameters and thresholds for controlling LFS - Output: - ominutiae - points to a structure containing the - detected minutiae - oquality_map - resulting integrated image quality map - odirection_map - resulting direction map - olow_contrast_map - resulting low contrast map - olow_flow_map - resulting low ridge flow map - ohigh_curve_map - resulting high curvature map - omap_w - width (in blocks) of image maps - omap_h - height (in blocks) of image maps - obdata - points to binarized image data - obw - width (in pixels) of binarized image - obh - height (in pixels) of binarized image - obd - pixel depth (in bits) of binarized image - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int get_minutiae(MINUTIAE **ominutiae, int **oquality_map, - int **odirection_map, int **olow_contrast_map, - int **olow_flow_map, int **ohigh_curve_map, - int *omap_w, int *omap_h, - unsigned char **obdata, int *obw, int *obh, int *obd, - unsigned char *idata, const int iw, const int ih, - const int id, const double ppmm, const LFSPARMS *lfsparms) -{ - int ret; - MINUTIAE *minutiae; - int *direction_map, *low_contrast_map, *low_flow_map; - int *high_curve_map, *quality_map; - int map_w, map_h; - unsigned char *bdata; - int bw, bh; - - /* If input image is not 8-bit grayscale ... */ - if(id != 8){ - fprintf(stderr, "ERROR : get_minutiae : input image pixel "); - fprintf(stderr, "depth = %d != 8.\n", id); - return(-2); - } - - /* Detect minutiae in grayscale fingerpeint image. */ - if((ret = lfs_detect_minutiae_V2(&minutiae, - &direction_map, &low_contrast_map, - &low_flow_map, &high_curve_map, - &map_w, &map_h, - &bdata, &bw, &bh, - idata, iw, ih, lfsparms))){ - return(ret); - } - - /* Build integrated quality map. */ - if((ret = gen_quality_map(&quality_map, - direction_map, low_contrast_map, - low_flow_map, high_curve_map, map_w, map_h))){ - free_minutiae(minutiae); - free(direction_map); - free(low_contrast_map); - free(low_flow_map); - free(high_curve_map); - free(bdata); - return(ret); - } - - /* Assign reliability from quality map. */ - if((ret = combined_minutia_quality(minutiae, quality_map, map_w, map_h, - lfsparms->blocksize, - idata, iw, ih, id, ppmm))){ - free_minutiae(minutiae); - free(direction_map); - free(low_contrast_map); - free(low_flow_map); - free(high_curve_map); - free(quality_map); - free(bdata); - return(ret); - } - - /* Set output pointers. */ - *ominutiae = minutiae; - *oquality_map = quality_map; - *odirection_map = direction_map; - *olow_contrast_map = low_contrast_map; - *olow_flow_map = low_flow_map; - *ohigh_curve_map = high_curve_map; - *omap_w = map_w; - *omap_h = map_h; - *obdata = bdata; - *obw = bw; - *obh = bh; - *obd = id; - - /* Return normally. */ - return(0); -} diff --git a/libfprint/nbis/mindtct/isempty.c b/libfprint/nbis/mindtct/isempty.c deleted file mode 100644 index da42cc35..00000000 --- a/libfprint/nbis/mindtct/isempty.c +++ /dev/null @@ -1,94 +0,0 @@ -/******************************************************************************* - -License: -This software was developed at the National Institute of Standards and -Technology (NIST) by employees of the Federal Government in the course -of their official duties. Pursuant to title 17 Section 105 of the -United States Code, this software is not subject to copyright protection -and is in the public domain. NIST assumes no responsibility whatsoever for -its use by other parties, and makes no guarantees, expressed or implied, -about its quality, reliability, or any other characteristic. - -Disclaimer: -This software was developed to promote biometric standards and biometric -technology testing for the Federal Government in accordance with the USA -PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. -Specific hardware and software products identified in this software were used -in order to perform the software development. In no case does such -identification imply recommendation or endorsement by the National Institute -of Standards and Technology, nor does it imply that the products and equipment -identified are necessarily the best available for the purpose. - -*******************************************************************************/ - -/************************************************************************/ -/*********************************************************************** - LIBRARY: LFS - NIST Latent Fingerprint System - - FILE: ISEMPTY.C - AUTHOR: Michael D. Garris - DATE: 09/13/2004 - - Contains routines responsible for determining if a fingerprint - image is empty. - -*********************************************************************** - ROUTINES: - is_image_empty() - is_qmap_empty() - -***********************************************************************/ - -#include - -/*********************************************************************** -************************************************************************ -#cat: is_image_empty - Routine determines if statistics passed indicate -#cat: an empty image. - - Input: - quality_map - quality map computed by NIST's Mindtct - map_w - width of map - map_h - height of map - Return Code: - True - image determined empty - False - image determined NOT empty -************************************************************************/ -int is_image_empty(int *quality_map, const int map_w, const int map_h) -{ - /* This routine is designed to be expanded as more statistical */ - /* tests are developed. */ - - if(is_qmap_empty(quality_map, map_w, map_h)) - return(TRUE); - else - return(FALSE); -} - -/*********************************************************************** -************************************************************************ -#cat: is_qmap_empty - Routine determines if quality map is all set to zero - - Input: - quality_map - quality map computed by NIST's Mindtct - map_w - width of map - map_h - height of map - Return Code: - True - quality map is empty - False - quality map is NOT empty -************************************************************************/ -int is_qmap_empty(int *quality_map, const int map_w, const int map_h) -{ - int i, maplen; - int *qptr; - - qptr = quality_map; - maplen = map_w * map_h; - for(i = 0; i < maplen; i++){ - if(*qptr++ != 0){ - return(FALSE); - } - } - return(TRUE); -} - diff --git a/libfprint/nbis/mindtct/link.c b/libfprint/nbis/mindtct/link.c deleted file mode 100644 index 2a864528..00000000 --- a/libfprint/nbis/mindtct/link.c +++ /dev/null @@ -1,1238 +0,0 @@ -/******************************************************************************* - -License: -This software was developed at the National Institute of Standards and -Technology (NIST) by employees of the Federal Government in the course -of their official duties. Pursuant to title 17 Section 105 of the -United States Code, this software is not subject to copyright protection -and is in the public domain. NIST assumes no responsibility whatsoever for -its use by other parties, and makes no guarantees, expressed or implied, -about its quality, reliability, or any other characteristic. - -Disclaimer: -This software was developed to promote biometric standards and biometric -technology testing for the Federal Government in accordance with the USA -PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. -Specific hardware and software products identified in this software were used -in order to perform the software development. In no case does such -identification imply recommendation or endorsement by the National Institute -of Standards and Technology, nor does it imply that the products and equipment -identified are necessarily the best available for the purpose. - -*******************************************************************************/ - -/*********************************************************************** - LIBRARY: LFS - NIST Latent Fingerprint System - - FILE: LINK.C - AUTHOR: Michael D. Garris - DATE: 08/02/1999 - UPDATED: 10/04/1999 Version 2 by MDG - UPDATED: 03/16/2005 by MDG - - Contains routines responsible for linking compatible minutiae - together as part of the NIST Latent Fingerprint System (LFS). - -*********************************************************************** - ROUTINES: - link_minutiae() - create_link_table() - update_link_table() - order_link_table() - process_link_table() - link_score() -***********************************************************************/ - -#include -#include -#include -#include -#include - -/************************************************************************* -************************************************************************** -#cat: link_minutiae - Clusters minutiae that are sufficiently close to each -#cat: other and have compatible directions to be considered part -#cat: of the same ridge or valley and then links them together. -#cat: In linking two minutia, the respective minutia features -#cat: in the image are joined by drawing pixels and the points -#cat: are removed from the list. - - Input: - minutiae - list of true and false minutiae - bdata - binary image data (0==while & 1==black) - iw - width (in pixels) of image - ih - height (in pixels) of image - nmap - IMAP ridge flow matrix with invalid, high-curvature, - and no-valid-neighbor regions identified - mw - width in blocks of the NMAP - mh - height in blocks of the NMAP - lfsparms - parameters and thresholds for controlling LFS - Output: - minutiae - list of pruned minutiae - bdata - edited binary image with breaks in ridges and valleys filled - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int link_minutiae(MINUTIAE *minutiae, - unsigned char *bdata, const int iw, const int ih, - int *nmap, const int mw, const int mh, - const LFSPARMS *lfsparms) -{ - int i, ret, *onloop; - MINUTIA *main_min; /* Renamed by MDG on 03-16-05 */ - int main_x, main_y; - int *link_table, *x_axis, *y_axis, nx_axis, ny_axis, n_entries; - - print2log("\nLINKING MINUTIA:\n"); - - /* Go through the list of minutiae and detect any small loops (ex. */ - /* < 15 pixels in circumference), and remove any minutiae */ - /* (bifurcations) with bad contours. */ - if((ret = get_loop_list(&onloop, minutiae, lfsparms->small_loop_len, - bdata, iw, ih))) - return(ret); - - i = 0; - /* Foreach minutia treated as a "main" minutia */ - /* (except for the very last one) ... */ - while(i < minutiae->num-1){ - - /* Set current minutia to "main" minutia. */ - main_min = minutiae->list[i]; - main_x = main_min->x; - main_y = main_min->y; - - /* If the main minutia is NOT on a small loop ... */ - if(!onloop[i]){ - - /* Then minutia is a ridge-ending OR a bifurcation */ - /* which is NOT to be skipped ... */ - - /* We now want to build a connected graph (link table) of */ - /* all those minutiae sufficiently close and complementing */ - /* each other that they potentially could be merged (linked) */ - /* together. (Ex. table has max dimensions of 20). */ - if((ret = create_link_table(&link_table, &x_axis, &y_axis, - &nx_axis, &ny_axis, &n_entries, - lfsparms->link_table_dim, - i, minutiae, onloop, nmap, mw, mh, - bdata, iw, ih, lfsparms))){ - /* Deallocate working memory. */ - free(onloop); - /* Return error code. */ - return(ret); - } - - /* Put the link table in sorted order based on x and then y-axis */ - /* entries. These minutia are sorted based on their point of */ - /* perpendicular intersection with a line running from the origin */ - /* at an angle equal to the average direction of all entries in */ - /* the link table. */ - if((ret = order_link_table(link_table, x_axis, y_axis, - nx_axis, ny_axis, n_entries, - lfsparms->link_table_dim, minutiae, - lfsparms->num_directions))){ - /* Deallocate working memories. */ - free(link_table); - free(x_axis); - free(y_axis); - free(onloop); - /* Return error code. */ - return(ret); - } - - /* Process the link table deciding which minutia pairs in */ - /* the table should be linked (ie. joined in the image and */ - /* removed from the minutiae list (and from onloop). */ - if((ret = process_link_table(link_table, x_axis, y_axis, - nx_axis, ny_axis, n_entries, - lfsparms->link_table_dim, - minutiae, onloop, bdata, iw, ih, lfsparms))){ - /* Deallocate working memories. */ - free(link_table); - free(x_axis); - free(y_axis); - free(onloop); - /* Return error code. */ - return(ret); - } - - /* Deallocate link table buffers. */ - free(link_table); - free(x_axis); - free(y_axis); - } - /* Otherwise, skip minutia on a small loop. */ - - /* Check to see if the current "main" minutia has been removed */ - /* from the minutiae list. If it has not, then we need to */ - /* advance to the next minutia in the list. If it has been */ - /* removed, then we are pointing to the next minutia already. */ - if((minutiae->list[i]->x == main_x) && - (minutiae->list[i]->y == main_y)) - /* Advance to the next main feature in the list. */ - i++; - - /* At this point 'i' is pointing to the next main minutia to be */ - /* processed, so continue. */ - } - - free(onloop); - return(0); -} - -/************************************************************************* -************************************************************************** -#cat: create_link_table - Builds a 2D minutia link table where each cell in the -#cat: table represents a potential linking of 2 different -#cat: minutia points. Minutia IDs are stored on each axes -#cat: and scores representing the degree of compatibility -#cat: between 2 minutia are stored in each cell. Note that -#cat: the table is sparsely filled with scores. - - Input: - tbldim - dimension of each axes of the link table - start - index position of starting minutia point in input list - minutiae - list of minutia - onloop - list of loop flags (on flag for each minutia point in list) - nmap - IMAP ridge flow matrix with invalid, high-curvature, - and no-valid-neighbor regions identified - mw - width in blocks of the NMAP - mh - height in blocks of the NMAP - bdata - binary image data (0==while & 1==black) - iw - width (in pixels) of image - ih - height (in pixels) of image - lfsparms - parameters and thresholds for controlling LFS - Output: - olink_table - sparse 2D table containing scores of potentially - linked minutia pairs - ox_axis - minutia IDs registered along x-axis - oy_axis - minutia IDs registered along y-axis - onx_axis - number of minutia registered along x-axis - ony_axis - number of minutia registered along y-axis - on_entries - number of scores currently entered in the table - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int create_link_table(int **olink_table, int **ox_axis, int **oy_axis, - int *onx_axis, int *ony_axis, int *on_entries, const int tbldim, - const int start, const MINUTIAE *minutiae, const int *onloop, - int *nmap, const int mw, const int mh, - unsigned char *bdata, const int iw, const int ih, - const LFSPARMS *lfsparms) -{ - int ret, first, second; - int full_ndirs, qtr_ndirs, half_ndirs, low_curve_min_deltadir, deltadir; - int *link_table, *x_axis, *y_axis, nx_axis, ny_axis, n_entries, tblalloc; - int *queue, *inqueue, head, tail; - MINUTIA *minutia1, *minutia2; - int xblk, yblk; - int nmapval, opp1dir, joindir, iscore; - double jointheta, joindist, dscore; - - /* Compute number of directions on full circle. */ - full_ndirs = lfsparms->num_directions<<1; - /* Compute number of directions in 45=(180/4) degrees. */ - qtr_ndirs = lfsparms->num_directions>>2; - /* Compute number of directions in 90=(180/2) degrees. */ - half_ndirs = lfsparms->num_directions>>1; - - /* Minimum allowable deltadir to link minutia in low-curvature region. */ - /* (The closer the deltadir is to 180 degrees, the more likely the link. */ - /* When ndirs==16, then this value is 11=(3*4)-1 == 123.75 degrees. */ - /* I chose to parameterize this threshold based on a fixed fraction of */ - /* 'ndirs' rather than on passing in a parameter in degrees and doing */ - /* the conversion. I doubt the difference matters. */ - low_curve_min_deltadir = (3 * qtr_ndirs) - 1; - - /* Allocate and initialize link table buffers. */ - /* Note: The use of "calloc" initializes all table values to 0. */ - tblalloc = tbldim * tbldim; - link_table = (int *)calloc(tblalloc, sizeof(int)); - if(link_table == (int *)NULL){ - fprintf(stderr, "ERROR : create_link_table : calloc : link_table\n"); - return(-330); - } - /* Allocate horizontal axis entries in table. */ - x_axis = (int *)malloc(tbldim * sizeof(int)); - if(x_axis == (int *)NULL){ - free(link_table); - fprintf(stderr, "ERROR : create_link_table : malloc : x_axis\n"); - return(-331); - } - /* Allocate vertical axis entries in table. */ - y_axis = (int *)malloc(tbldim * sizeof(int)); - if(y_axis == (int *)NULL){ - free(link_table); - free(x_axis); - fprintf(stderr, "ERROR : create_link_table : malloc : y_axis\n"); - return(-332); - } - nx_axis = 0; - ny_axis = 0; - n_entries = 0; - - /* Allocate and initalize queue buffers. As minutia are entered into */ - /* the link table they are placed in the queue for subsequent matching. */ - queue = (int *)malloc(minutiae->num * sizeof(int)); - if(queue == (int *)NULL){ - free(link_table); - free(x_axis); - free(y_axis); - fprintf(stderr, "ERROR : create_link_table : malloc : queue\n"); - return(-333); - } - /* List of flags to indicate if a manutia has been entered in the queue. */ - /* Once a minutia "in queue" status is set to TRUE it will not be reset. */ - /* This way a minutia will only ever be processed as a primary minutia */ - /* once when builing the link table. Note that the calloc() initializes */ - /* the flags to FALSE (as the queue is initially empty). */ - inqueue = (int *)calloc(minutiae->num, sizeof(int)); - if(inqueue == (int *)NULL){ - free(link_table); - free(x_axis); - free(y_axis); - free(queue); - fprintf(stderr, "ERROR : create_link_table : calloc : inqueue\n"); - return(-334); - } - /* Initialize head and tail to start of queue. */ - head = 0; - tail = 0; - - /* Push the index of the "main" manutia point onto the queue. */ - queue[tail++] = start; - /* Set "main" minutia inqueue flag to TRUE. */ - inqueue[start] = TRUE; - - print2log("BUILD TABLE:\n"); - - /* While the queue is NOT empty ... */ - while(head != tail){ - /* Pop the next manutia point from the queue and refer to it as */ - /* the primary (first) minutia. */ - first = queue[head++]; - minutia1 = minutiae->list[first]; - - /* Look for those minutia points that potentially match the */ - /* "first" minutia and add them to the link table. These */ - /* potentially matching minutia are secondary and refered to */ - /* as the "second" minutia. Always restart the search at the */ - /* original "main" manutia. */ - second = start+1; - - /* While secondary manutae remain to be matched to the current */ - /* first minutia... */ - while(second < minutiae->num){ - /* Assign second minutia to temporary pointer. */ - minutia2 = minutiae->list[second]; - - print2log("1:%d(%d,%d)%d 2:%d(%d,%d)%d ", - first, minutia1->x, minutia1->y, minutia1->type, - second, minutia2->x, minutia2->y, minutia2->type); - - /* 1. If y-delta from second to first minutia is small (ex. */ - /* <= 20 pixels) ... */ - if((minutia2->y - minutia1->y) <= lfsparms->max_link_dist){ - - print2log("1DY "); - - - /* 2. If first and second minutia are not the same point ... */ - /* (Remeber that the search for matching seconds starts */ - /* all the way back to the starting "main" minutia.) */ - if(first != second){ - - print2log("2NE "); - - /* 3. If first and second minutia are the same type ... */ - if(minutia1->type == minutia2->type){ - - print2log("3TP "); - - /* 4. If |x-delta| between minutiae is small (ex. <= */ - /* 20 pixels) ... */ - if(abs(minutia1->x - minutia2->x) <= - lfsparms->max_link_dist){ - - print2log("4DX "); - - /* 5. If second minutia is NOT on a small loop ... */ - if(!onloop[second]){ - - print2log("5NL "); - - /* The second minutia is ridge-ending OR a */ - /* bifurcation NOT to be skipped ... */ - - /* Compute the "inner" distance between the */ - /* first and second minutia's directions. */ - deltadir = closest_dir_dist(minutia1->direction, - minutia2->direction, full_ndirs); - /* If the resulting direction is INVALID */ - /* (this should never happen, but just in case)... */ - if(deltadir == INVALID_DIR){ - free(link_table); - free(x_axis); - free(y_axis); - free(queue); - free(inqueue); - /* Then there is a problem. */ - fprintf(stderr, - "ERROR : create_link_table : INVALID direction\n"); - return(-335); - } - - /* Compute first minutia's block coords from */ - /* its pixel coords. */ - xblk = minutia1->x/lfsparms->blocksize; - yblk = minutia1->y/lfsparms->blocksize; - /* Get corresponding block's NMAP value. */ - /* -3 == NO_VALID_NBRS */ - /* -2 == HIGH_CURVATURE */ - /* -1 == INVALID_DIR */ - /* 0 <= VALID_DIR */ - nmapval = *(nmap+(yblk*mw)+xblk); - /* 6. CASE I: If block has VALID_DIR and deltadir */ - /* relatively close to 180 degrees (at */ - /* least 123.75 deg when ndirs==16)... */ - /* OR */ - /* CASE II: If block is HIGH_CURVATURE and */ - /* deltadir is at least 45 degrees... */ - if(((nmapval >= 0) && - (deltadir >= low_curve_min_deltadir)) || - ((nmapval == HIGH_CURVATURE) && - (deltadir >= qtr_ndirs))){ - - print2log("6DA "); - - /* Then compute direction of "joining" vector. */ - /* First, compute direction of line from first */ - /* to second minutia points. */ - joindir = line2direction(minutia1->x, minutia1->y, - minutia2->x, minutia2->y, - lfsparms->num_directions); - - /* Comptue opposite direction of first minutia. */ - opp1dir = (minutia1->direction+ - lfsparms->num_directions)%full_ndirs; - /* Take "inner" distance on full circle between */ - /* the first minutia's opposite direction and */ - /* the joining direction. */ - joindir = abs(opp1dir - joindir); - joindir = min(joindir, full_ndirs - joindir); - /* 7. If join angle is <= 90 deg... */ - if(joindir <= half_ndirs){ - - print2log("7JA "); - - /* Convert integer join direction to angle */ - /* in radians on full circle. Multiply */ - /* direction by (2PI)/32==PI/16 radians per */ - /* unit direction and you get radians. */ - jointheta = joindir * - (M_PI/(double)lfsparms->num_directions); - /* Compute squared distance between frist */ - /* and second minutia points. */ - joindist = distance(minutia1->x, minutia1->y, - minutia2->x, minutia2->y); - /* 8. If the 2 minutia points are close enough */ - /* (ex. thresh == 20 pixels)... */ - if(joindist <= lfsparms->max_link_dist){ - - print2log("8JD "); - - /* 9. Does a "free path" exist between the */ - /* 2 minutia points? */ - if(free_path(minutia1->x, minutia1->y, - minutia2->x, minutia2->y, - bdata, iw, ih, lfsparms)){ - - print2log("9FP "); - - /* If the join distance is very small, */ - /* join theta will be unreliable, so set */ - /* join theta to zero. */ - /* (ex. thresh == 5 pixels)... */ - if(joindist < lfsparms->min_theta_dist) - /* Set the join theta to zero. */ - jointheta = 0.0; - /* Combine the join theta and distance */ - /* to compute a link score. */ - dscore = link_score(jointheta, joindist, - lfsparms); - /* Round off the floating point score. */ - /* Need to truncate so answers are same */ - /* on different computers. */ - dscore = trunc_dbl_precision(dscore, - TRUNC_SCALE); - iscore = sround(dscore); - /* Add minutia pair and their link score */ - /* to the Link Table. */ - - if(iscore > 0){ - print2log("UPDATE"); - - if((ret = update_link_table(link_table, - x_axis, y_axis, &nx_axis, &ny_axis, - &n_entries, tbldim, - queue, &head, &tail, inqueue, - first, second, iscore))){ - /* If update ERROR, deallocate */ - /* working memories. */ - free(link_table); - free(x_axis); - free(y_axis); - free(queue); - free(inqueue); - return(ret); - } - } /* Else score is <= 0, so skip second. */ - } /* 9. Else no free path, so skip second. */ - } /* 8. Else joindist too big, so skip second. */ - } /* 7. Else joindir is too big, so skip second. */ - } /* 6. Else INVALID DIR or deltadir too small, */ - /* so skip second. */ - } /* 5. Else second minutia on small loop, so skip it. */ - } /* 4. Else X distance too big, so skip second. */ - } /* 3. Else first and second NOT same type, so skip second. */ - } /* 2. Else first and second ARE same point, so skip second. */ - - /* If we get here, we want to advance to the next secondary. */ - second++; - - print2log("\n"); - - - } - /* 1. Otherwise, Y distnace too big, so we are done searching for */ - /* secondary matches to the current frist minutia. It is time */ - /* to take the next minutia in the queue and begin matching */ - /* secondaries to it. */ - else{ - - print2log("\n"); - - /* So, break out of the secondary minutiae while loop. */ - break; - } - } - /* Done matching current first minutia to secondaries. */ - } - /* Get here when queue is empty, and we have our complete link table. */ - - /* Deallocate working memories. */ - free(queue); - free(inqueue); - - /* Assign link table buffers and attributes to output pointers. */ - *olink_table = link_table; - *ox_axis = x_axis; - *oy_axis = y_axis; - *onx_axis = nx_axis; - *ony_axis = ny_axis; - *on_entries = n_entries; - - /* Return normally. */ - return(0); -} - -/************************************************************************* -************************************************************************** -#cat: update_link_table - Takes the indices of 2 minutia and their link -#cat: compatibility score and updates the 2D link table. -#cat: The input minutia are registered to positions along -#cat: different axes, if they are not already in the table, -#cat: and a queue is maintained so that a cluster of -#cat: potentially linked points may be gathered. - - Input: - link_table - sparse 2D table containing scores of potentially linked - minutia pairs - x_axis - minutia IDs registered along x-axis - y_axis - minutia IDs registered along y-axis - nx_axis - number of minutia registered along x-axis - ny_axis - number of minutia registered along y-axis - n_entries - number of scores currently entered in the table - tbldim - dimension of each axes of the link table - queue - list of clustered minutiae yet to be used to locate - other compatible minutiae - head - head of the queue - tail - tail of the queue - inqueue - flag for each minutia point in minutiae list to signify if - it has been clustered with the points in this current link - table - first - index position of first minutia of current link pair - second - index position of second minutia of current link pair - score - degree of link compatibility of current link pair - Output: - link_table - updated sparse 2D table containing scores of potentially - linked minutia pairs - x_axis - updated minutia IDs registered along x-axis - y_axis - updated minutia IDs registered along y-axis - nx_axis - updated number of minutia registered along x-axis - ny_axis - updated number of minutia registered along y-axis - n_entries - updated number of scores currently entered in the table - queue - updated list of clustered minutiae yet to be used to locate - other compatible minutiae - tail - updated tail of the queue - inqueue - updated list of flags, one for each minutia point in - minutiae list to signify if it has been clustered with - the points in this current link table - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int update_link_table(int *link_table, int *x_axis, int *y_axis, - int *nx_axis, int *ny_axis, int *n_entries, const int tbldim, - int *queue, int *head, int *tail, int *inqueue, - const int first, const int second, const int score) -{ - int x, y, *tptr; - - /* If the link table is empty. */ - if(*n_entries == 0){ - /* Add first and second minutia to the table. */ - - /* If horizontal axis of table is full ... */ - if(*nx_axis >= tbldim) - /* Then ignore the minutia pair and return normally. */ - return(0); - /* Add first minutia to horizontal axis. */ - x_axis[*nx_axis] = first; - - /* If vertical axis of table is full ... */ - if(*ny_axis >= tbldim) - /* Then ignore the minutia pair and return normally. */ - return(0); - /* Add second minutia to vertical axis. */ - y_axis[*ny_axis] = second; - - /* Enter minutia pair score to the link table. */ - tptr = link_table + ((*ny_axis)*tbldim) + (*nx_axis); - *tptr = score; - (*n_entries)++; - - /* Bump number of entries in each axis. */ - (*nx_axis)++; - (*ny_axis)++; - - /* Add second minutia to queue (if not already in queue), so it */ - /* can be processed to see who might link to it. */ - if(!inqueue[second]){ - queue[*tail] = second; - (*tail)++; - inqueue[second] = TRUE; - } - - /* Done, so return normally. */ - return(0); - } - - /* We are filling in the table with a "faimily" or "cluster" of */ - /* potentially inter-linked points. Once the first entry is */ - /* made in the table, all subsequent updates will be based on */ - /* at least the first minutia already being in the table. */ - - /* If first minutia already stored in horizontal axis */ - /* of the link table. */ - if((x = in_int_list(first, x_axis, *nx_axis)) >= 0){ - /* If second minutia already stored in vertical axis */ - /* of the link table. */ - if((y = in_int_list(second, y_axis, *ny_axis)) >= 0){ - /* Entry may not be set or the new score may be larger. */ - tptr = link_table + (y*tbldim) + x; - if(*tptr == 0) - /* Assign the minutia pair score to the table. */ - *tptr = score; - - } - /* Otherwise, second minutia not in vertical axis of link table. */ - else{ - /* Add the second minutia to the vertical axis and */ - /* the minutia pair's score to the link table. */ - - /* If vertical axis of table is full ... */ - if(*ny_axis >= tbldim) - /* Then ignore the minutia pair and return normally. */ - return(0); - /* Add second minutia to vertical axis. */ - y_axis[*ny_axis] = second; - - /* Enter minutia pair score to the link table. */ - tptr = link_table + ((*ny_axis)*tbldim) + x; - *tptr = score; - (*n_entries)++; - - /* Bump number of entries in vertical axis. */ - (*ny_axis)++; - - /* Add second minutia to queue (if not already in queue), so it */ - /* can be processed to see who might link to it. */ - if(!inqueue[second]){ - queue[*tail] = second; - (*tail)++; - inqueue[second] = TRUE; - } - } - } - /* Otherwise, first minutia not in horizontal axis of link table. */ - else{ - /* If first minutia already stored in vertical axis */ - /* of the link table. */ - if((y = in_int_list(first, y_axis, *ny_axis)) >= 0){ - /* If second minutia already stored in horizontal axis */ - /* of the link table. */ - if((x = in_int_list(second, x_axis, *nx_axis)) >= 0){ - /* Entry may not be set or the new score may be larger. */ - tptr = link_table + (y*tbldim) + x; - if(*tptr == 0) - /* Assign the minutia pair score to the table. */ - *tptr = score; - } - /* Otherwise, second minutia not in horizontal axis of link table. */ - else{ - /* Add the second minutia to the horizontal axis and */ - /* the minutia pair's score to the link table. */ - - /* If horizontal axis of table is full ... */ - if(*nx_axis >= tbldim) - /* Then ignore the minutia pair and return normally. */ - return(0); - /* Add second minutia to vertical axis. */ - x_axis[*nx_axis] = second; - - /* Enter minutia pair score to the link table. */ - tptr = link_table + (y*tbldim) + (*nx_axis); - *tptr = score; - (*n_entries)++; - - /* Bump number of entries in horizontal axis. */ - (*nx_axis)++; - - /* Add second minutia to queue (if not already in queue), so it */ - /* can be processed to see who might link to it. */ - if(!inqueue[second]){ - queue[*tail] = second; - (*tail)++; - inqueue[second] = TRUE; - } - } - } - /* Otherwise, first minutia not in vertical or horizontal axis of */ - /* link table. This is an error, as this should only happen upon */ - /* the first point being entered, which is already handled above. */ - else{ - fprintf(stderr, - "ERROR : update_link_table : first minutia not found in table\n"); - return(-340); - } - } - - /* Done, so return normally. */ - return(0); -} - -/************************************************************************* -************************************************************************** -#cat: order_link_table - Puts the link table in sorted order based on x and -#cat: then y-axis entries. These minutia are sorted based -#cat: on their point of perpendicular intersection with a -#cat: line running from the origin at an angle equal to the -#cat: average direction of all entries in the link table. - - Input: - link_table - sparse 2D table containing scores of potentially linked - minutia pairs - x_axis - minutia IDs registered along x-axis - y_axis - minutia IDs registered along y-axis - nx_axis - number of minutia registered along x-axis - ny_axis - number of minutia registered along y-axis - n_entries - number of scores currently entered in the table - tbldim - dimension of each axes of the link table - minutiae - list of minutia - ndirs - number of IMAP directions (in semicircle) - Output: - link_table - sorted sparse 2D table containing scores of potentially - linked minutia pairs - x_axis - sorted minutia IDs registered along x-axis - y_axis - sorted minutia IDs registered along y-axis - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int order_link_table(int *link_table, int *x_axis, int *y_axis, - const int nx_axis, const int ny_axis, const int n_entries, - const int tbldim, const MINUTIAE *minutiae, - const int ndirs) -{ - int i, j, ret, sumdir, avrdir, *order; - double davrdir, avrtheta, pi_factor, cs, sn; - double *dlist; - MINUTIA *minutia; - int *tlink_table, *tx_axis, *ty_axis, tblalloc; - int *toptr, *frptr; - - /* If the table is empty or if there is only one horizontal or */ - /* vertical entry in the table ... */ - if((nx_axis <= 1) || (ny_axis <= 1)) - /* Then don't reorder the table, just return normally. */ - return(0); - - /* Compute average direction (on semi-circle) of all minutia entered */ - /* in the link table. This gives an average ridge-flow direction */ - /* among all the potentially linked minutiae in the table. */ - - /* Initialize direction accumulator to 0. */ - sumdir = 0; - - /* Accumulate directions (on semi-circle) of minutia entered in the */ - /* horizontal axis of the link table. */ - for(i = 0; i < nx_axis; i++) - sumdir += (minutiae->list[x_axis[i]]->direction % ndirs); - - /* Accumulate directions of minutia entered in the vertical axis */ - /* of the link table. */ - for(i = 0; i < ny_axis; i++) - sumdir += (minutiae->list[y_axis[i]]->direction % ndirs); - - /* Compute the average direction and round off to integer. */ - davrdir = (sumdir / (double)(nx_axis + ny_axis)); - /* Need to truncate precision so that answers are consistent */ - /* on different computer architectures when rounding doubles. */ - davrdir = trunc_dbl_precision(davrdir, TRUNC_SCALE); - avrdir = sround(davrdir); - - /* Conversion factor from integer directions to radians. */ - pi_factor = M_PI / (double)ndirs; - - /* Compute sine and cosine of average direction in radians. */ - avrtheta = avrdir*pi_factor; - sn = sin(avrtheta); - cs = cos(avrtheta); - - /* Allocate list to hold distances to be sorted on. */ - dlist = (double *)malloc(tbldim * sizeof(double)); - if(dlist == (double *)NULL){ - fprintf(stderr, "ERROR : order_link_table : malloc : dlist\n"); - return(-350); - } - - /* Allocate and initialize temporary link table buffers. */ - tblalloc = tbldim * tbldim; - tlink_table = (int *)calloc(tblalloc, sizeof(int)); - if(tlink_table == (int *)NULL){ - free(dlist); - fprintf(stderr, "ERROR : order_link_table : calloc : tlink_table\n"); - return(-351); - } - tx_axis = (int *)malloc(tbldim * sizeof(int)); - if(tx_axis == (int *)NULL){ - free(dlist); - free(tlink_table); - fprintf(stderr, "ERROR : order_link_table : malloc : tx_axis\n"); - return(-352); - } - ty_axis = (int *)malloc(tbldim * sizeof(int)); - if(ty_axis == (int *)NULL){ - free(dlist); - free(tlink_table); - free(tx_axis); - fprintf(stderr, "ERROR : order_link_table : malloc : ty_axis\n"); - return(-353); - } - - /* Compute distance measures for each minutia entered in the */ - /* horizontal axis of the link table. */ - /* The measure is: dist = X*cos(avrtheta) + Y*sin(avrtheta) */ - /* which measures the distance from the origin along the line */ - /* at angle "avrtheta" to the point of perpendicular inter- */ - /* section from the point (X,Y). */ - - /* Foreach minutia in horizontal axis of the link table ... */ - for(i = 0; i < nx_axis; i++){ - minutia = minutiae->list[x_axis[i]]; - dlist[i] = (minutia->x * cs) + (minutia->y * sn); - /* Need to truncate precision so that answers are consistent */ - /* on different computer architectures when rounding doubles. */ - dlist[i] = trunc_dbl_precision(dlist[i], TRUNC_SCALE); - } - - /* Get sorted order of distance for minutiae in horizontal axis. */ - if((ret = sort_indices_double_inc(&order, dlist, nx_axis))){ - free(dlist); - return(ret); - } - - /* Store entries on y_axis into temporary list. */ - memcpy(ty_axis, y_axis, ny_axis * sizeof(int)); - - /* For each horizontal entry in link table ... */ - for(i = 0; i < nx_axis; i++){ - /* Store next minutia in sorted order to temporary x_axis. */ - tx_axis[i] = x_axis[order[i]]; - /* Store corresponding column of scores into temporary table. */ - frptr = link_table + order[i]; - toptr = tlink_table + i; - for(j = 0; j < ny_axis; j++){ - *toptr = *frptr; - toptr += tbldim; - frptr += tbldim; - } - } - - /* Deallocate sorted order of distance measures. */ - free(order); - - /* Compute distance measures for each minutia entered in the */ - /* vertical axis of the temporary link table (already sorted */ - /* based on its horizontal axis entries. */ - - /* Foreach minutia in vertical axis of the link table ... */ - for(i = 0; i < ny_axis; i++){ - minutia = minutiae->list[y_axis[i]]; - dlist[i] = (minutia->x * cs) + (minutia->y * sn); - /* Need to truncate precision so that answers are consistent */ - /* on different computer architectures when rounding doubles. */ - dlist[i] = trunc_dbl_precision(dlist[i], TRUNC_SCALE); - } - - /* Get sorted order of distance for minutiae in vertical axis. */ - if((ret = sort_indices_double_inc(&order, dlist, ny_axis))){ - free(dlist); - return(ret); - } - - /* Store entries in temporary x_axis. */ - memcpy(x_axis, tx_axis, nx_axis * sizeof(int)); - - /* For each vertical entry in the temporary link table ... */ - for(i = 0; i < ny_axis; i++){ - /* Store next minutia in sorted order to y_axis. */ - y_axis[i] = ty_axis[order[i]]; - /* Store corresponding row of scores into link table. */ - frptr = tlink_table + (order[i] * tbldim); - toptr = link_table + (i * tbldim); - for(j = 0; j < nx_axis; j++){ - *toptr++ = *frptr++; - } - } - - /* Deallocate sorted order of distance measures. */ - free(order); - - /* Link table is now sorted on x and y axes. */ - /* Deallocate the working memories. */ - free(dlist); - free(tlink_table); - free(tx_axis); - free(ty_axis); - - /* Return normally. */ - return(0); -} - -/************************************************************************* -************************************************************************** -#cat: process_link_table - Processes the link table deciding which minutia -#cat: pairs in the table should be linked (ie. joined in -#cat: the image and removed from the minutiae list (and -#cat: from onloop). - - Input: - link_table - sparse 2D table containing scores of potentially linked - minutia pairs - x_axis - minutia IDs registered along x-axis - y_axis - minutia IDs registered along y-axis - nx_axis - number of minutia registered along x-axis - ny_axis - number of minutia registered along y-axis - n_entries - number of scores currently entered in the table - tbldim - dimension of each axes of the link table - minutiae - list of minutia - onloop - list of flags signifying which minutia lie on small lakes - bdata - binary image data (0==while & 1==black) - iw - width (in pixels) of image - ih - height (in pixels) of image - lfsparms - parameters and thresholds for controlling LFS - Output: - minutiae - list of pruned minutiae - onloop - updated loop flags - bdata - edited image with minutia features joined - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int process_link_table(const int *link_table, - const int *x_axis, const int *y_axis, - const int nx_axis, const int ny_axis, const int n_entries, - const int tbldim, MINUTIAE *minutiae, int *onloop, - unsigned char *bdata, const int iw, const int ih, - const LFSPARMS *lfsparms) -{ - int i, j, ret, first, second; - MINUTIA *minutia1, *minutia2; - int rm1, rm2; - int *to_remove; - int n_lines, line_len, entry_incr, line_incr; - int line_i, entry_i; - int start, end; - int max_v, max_tbl_i, max_line_i, max_x, max_y; - - - print2log("LINKING FROM TABLE:\n"); - - /* If link table is empty, just return normally. */ - if(n_entries == 0) - return(0); - - /* If there is only 1 entry in the table, then join the minutia pair. */ - if(n_entries == 1){ - /* Join the minutia pair in the image. */ - first = x_axis[0]; - second = y_axis[0]; - minutia1 = minutiae->list[first]; - minutia2 = minutiae->list[second]; - - /* Connect the points with a line with specified radius (ex. 1 pixel). */ - if((ret = join_minutia(minutia1, minutia2, bdata, iw, ih, - WITH_BOUNDARY, lfsparms->join_line_radius))) - return(ret); - - /* Need to remove minutiae from onloop first, as onloop is dependent */ - /* on the length of the minutiae list. We also need to remove the */ - /* highest index from the lists first or the indices will be off. */ - if(first > second){ - rm1 = first; - rm2 = second; - } - else{ - rm1 = second; - rm2 = first; - } - if((ret = remove_from_int_list(rm1, onloop, minutiae->num))) - return(ret); - if((ret = remove_from_int_list(rm2, onloop, minutiae->num-1))) - return(ret); - - /* Now, remove the minutia from the minutiae list. */ - if((ret = remove_minutia(rm1, minutiae))) - return(ret); - if((ret = remove_minutia(rm2, minutiae))) - return(ret); - - /* Return normally. */ - return(0); - } - - /* Otherwise, we need to make decisions as to who links to who. */ - - /* Allocate list of minutia indices that upon completion of linking */ - /* should be removed from the onloop and minutiae lists. Note: That */ - /* using "calloc" initializes the list to FALSE. */ - to_remove = (int *)calloc(minutiae->num, sizeof(int)); - if(to_remove == (int *)NULL){ - fprintf(stderr, "process_link_table : calloc : to_remove\n"); - return(-360); - } - - /* If the number of horizontal entries is <= vertical entries ... */ - if(nx_axis <= ny_axis){ - /* Process columns in table as lines. */ - n_lines = nx_axis; - /* Set length of each line to number of vertical entries. */ - line_len = ny_axis; - /* Increment down column to next entry in line. */ - entry_incr = tbldim; - /* Increment across row to next line. */ - line_incr = 1; - } - /* Otherwise, the number of vertical entreis < horizontal entries ... */ - else{ - /* Process rows in table as lines. */ - n_lines = ny_axis; - /* Set length of each line to number of horizontal entries. */ - line_len = nx_axis; - /* Increment across row to next entry in line. */ - entry_incr = 1; - /* Increment down column to next line. */ - line_incr = tbldim; - } - - /* Set start of next line index to origin of link table. */ - line_i = 0; - - /* Initialize the search limits for the line ... */ - start = 0; - end = line_len - n_lines + 1; - - /* Foreach line in table ... */ - for(i = 0; i < n_lines; i++){ - - /* Find max score in the line given current search limits. */ - - /* Set table entry index to start of next line. */ - entry_i = line_i; - - /* Initialize running maximum with score in current line */ - /* at offset 'start'. */ - entry_i += (start*entry_incr); - - /* Set running maximum score. */ - max_v = link_table[entry_i]; - /* Set table index of maximum score. */ - max_tbl_i = entry_i; - /* Set line index of maximum score. */ - max_line_i = start; - - /* Advance table entry index along line. */ - entry_i += entry_incr; - /* Foreach successive entry in line up to line index 'end' ... */ - - for(j = start+1; j < end; j++){ - /* If current entry > maximum score seen so far ... */ - if(link_table[entry_i] >= max_v){ - /* Store current entry as new maximum. */ - max_v = link_table[entry_i]; - max_tbl_i = entry_i; - max_line_i = j; - } - /* Advance table entry index along line. */ - entry_i += entry_incr; - } - - /* Convert entry index at maximum to table row and column indices. */ - max_x = max_tbl_i % tbldim; - max_y = max_tbl_i / tbldim; - - /* Set indices and pointers corresponding to minutia pair */ - /* with maximum score this pass. */ - first = x_axis[max_x]; - second = y_axis[max_y]; - minutia1 = minutiae->list[first]; - minutia2 = minutiae->list[second]; - - /* Check to make sure the the maximum score found in the current */ - /* line is > 0 (just to be safe) AND */ - /* If a "free path" exists between minutia pair ... */ - if( /* (max_v >0) && */ - free_path(minutia1->x, minutia1->y, minutia2->x, minutia2->y, - bdata, iw, ih, lfsparms)){ - - print2log("%d,%d to %d,%d LINK\n", - minutia1->x, minutia1->y, minutia2->x, minutia2->y); - - /* Join the minutia pair in the image. */ - if((ret = join_minutia(minutia1, minutia2, bdata, iw, ih, - WITH_BOUNDARY, lfsparms->join_line_radius))){ - free(to_remove); - return(ret); - } - - /* Set remove flags for minutia pair. A minutia point may */ - /* be linked to more than one other minutia in this process */ - /* so, just flag them to be removed for now and actually */ - /* conduct the removal after all linking is complete. */ - to_remove[first] = TRUE; - to_remove[second] = TRUE; - - } - /* Set starting line index to one passed maximum found this pass. */ - start = max_line_i + 1; - /* Bump ending line index. */ - end++; - - /* Advance start of line index to next line. */ - line_i += line_incr; - - } /* End for lines */ - - /* Now that all linking from the current table is complete, */ - /* remove any linked minutia from the onloop and minutiae lists. */ - /* NOTE: Need to remove the minutia from their lists in reverse */ - /* order, otherwise, indices will be off. */ - for(i = minutiae->num-1; i >= 0; i--){ - /* If the current minutia index is flagged for removal ... */ - if(to_remove[i]){ - /* Remove the minutia from the onloop list before removing */ - /* from minutiae list as the length of onloop depends on the */ - /* length of the minutiae list. */ - if((ret = remove_from_int_list(i, onloop, minutiae->num))){ - free(to_remove); - return(ret); - } - /* Now, remove the minutia from the minutiae list. */ - if((ret = remove_minutia(i, minutiae))){ - free(to_remove); - return(ret); - } - } - } - - /* Deallocate remove list. */ - free(to_remove); - - /* Return normally. */ - return(0); -} - -/************************************************************************* -************************************************************************** -#cat: link_score - Takes 2 parameters, a 'join angle' and a 'join distance' -#cat: computed between 2 minutia and combines these to compute -#cat: a score representing the degree of link compatibility -#cat: between the 2 minutiae. - - Input: - jointheta - angle measured between 2 minutiae - joindist - distance between 2 minutiae - lfsparms - parameters and thresholds for controlling LFS - Return Code: - Score - degree of link compatibility -**************************************************************************/ -double link_score(const double jointheta, const double joindist, - const LFSPARMS *lfsparms) -{ - double score, theta_factor, dist_factor; - - /* Calculates a weighted score between the distance between the 1st & */ - /* 2nd features and the delta angle between the reflected 1st feature */ - /* and the "joining" vector to the 2nd feature. */ - /* */ - /* SCORE_NUMERATOR */ - /* SCORE = ------------------------------------------ */ - /* THETA_FACTOR * DIST_FACTOR */ - /* */ - /* THETA_FACTOR = exp((jointheta/SCORE_THETA_NORM)^2) */ - /* DIST_FACTOR = (1+exp(((joindist/SCORE_DIST_NORM)-1) */ - /* *SCORE_DIST_WEIGHT)) */ - /* */ - /* For example: */ - /* SCORE_NUMERATOR = 32000.0 */ - /* SCORE_THETA_NORM = 15.0*(PI/180) */ - /* SCORE_DIST_NORM = 10.0 */ - /* SCORE_DIST_WEIGHT = 4.0 */ - /* */ - /* 3200.0 */ - /* SCORE = ----------------------------------------------------------- */ - /* exp((jointheta/15.0)^2) * (1+exp(((joindist/10.0)-1.0)*4.0))*/ - /* */ - /* In this case, increases in distance drops off faster than */ - /* in theta. */ - - /* Compute the THETA_FACTOR. */ - theta_factor = jointheta / (lfsparms->score_theta_norm * DEG2RAD); - theta_factor = exp(theta_factor * theta_factor); - /* Compute the DIST_FACTOR. */ - dist_factor = 1.0+exp(((joindist/lfsparms->score_dist_norm)-1.0) * - lfsparms->score_dist_weight); - - /* Compute the floating point score. */ - score = lfsparms->score_numerator / (theta_factor * dist_factor); - - /* Return the floating point score. */ - return(score); -} - diff --git a/libfprint/nbis/mindtct/loop.c b/libfprint/nbis/mindtct/loop.c index 9e15e95b..da5de0e5 100644 --- a/libfprint/nbis/mindtct/loop.c +++ b/libfprint/nbis/mindtct/loop.c @@ -36,6 +36,8 @@ identified are necessarily the best available for the purpose. *********************************************************************** ROUTINES: + chain_code_loop() + is_chain_clockwise() get_loop_list() on_loop() on_island_lake() @@ -52,6 +54,155 @@ identified are necessarily the best available for the purpose. #include #include +/************************************************************************* +************************************************************************** +#cat: chain_code_loop - Converts a feature's contour points into an +#cat: 8-connected chain code vector. This encoding represents +#cat: the direction taken between each adjacent point in the +#cat: contour. Chain codes may be used for many purposes, such +#cat: as computing the perimeter or area of an object, and they +#cat: may be used in object detection and recognition. + + Input: + contour_x - x-coord list for feature's contour points + contour_y - y-coord list for feature's contour points + ncontour - number of points in contour + Output: + ochain - resulting vector of chain codes + onchain - number of codes in chain + (same as number of points in contour) + Return Code: + Zero - chain code successful derived + Negative - system error +**************************************************************************/ +static int chain_code_loop(int **ochain, int *onchain, + const int *contour_x, const int *contour_y, const int ncontour) +{ + int *chain; + int i, j, dx, dy; + + /* If we don't have at least 3 points in the contour ... */ + if(ncontour <= 3){ + /* Then we don't have a loop, so set chain length to 0 */ + /* and return without any allocations. */ + *onchain = 0; + return(0); + } + + /* Allocate chain code vector. It will be the same length as the */ + /* number of points in the contour. There will be one chain code */ + /* between each point on the contour including a code between the */ + /* last to the first point on the contour (completing the loop). */ + chain = (int *)malloc(ncontour * sizeof(int)); + /* If the allocation fails ... */ + if(chain == (int *)NULL){ + fprintf(stderr, "ERROR : chain_code_loop : malloc : chain\n"); + return(-170); + } + + /* For each neighboring point in the list (with "i" pointing to the */ + /* previous neighbor and "j" pointing to the next neighbor... */ + for(i = 0, j=1; i < ncontour-1; i++, j++){ + /* Compute delta in X between neighbors. */ + dx = contour_x[j] - contour_x[i]; + /* Compute delta in Y between neighbors. */ + dy = contour_y[j] - contour_y[i]; + /* Derive chain code index from neighbor deltas. */ + /* The deltas are on the range [-1..1], so to use them as indices */ + /* into the code list, they must first be incremented by one. */ + chain[i] = *(chaincodes_nbr8+((dy+1)*NBR8_DIM)+dx+1); + } + + /* Now derive chain code between last and first points in the */ + /* contour list. */ + dx = contour_x[0] - contour_x[i]; + dy = contour_y[0] - contour_y[i]; + chain[i] = *(chaincodes_nbr8+((dy+1)*NBR8_DIM)+dx+1); + + /* Store results to the output pointers. */ + *ochain = chain; + *onchain = ncontour; + + /* Return normally. */ + return(0); +} + +/************************************************************************* +************************************************************************** +#cat: is_chain_clockwise - Takes an 8-connected chain code vector and +#cat: determines if the codes are ordered clockwise or +#cat: counter-clockwise. +#cat: The routine also requires a default return value be +#cat: specified in the case the the routine is not able to +#cat: definitively determine the chains direction. This allows +#cat: the default response to be application-specific. + + Input: + chain - chain code vector + nchain - number of codes in chain + default_ret - default return code (used when we can't tell the order) + Return Code: + TRUE - chain determined to be ordered clockwise + FALSE - chain determined to be ordered counter-clockwise + Default - could not determine the order of the chain +**************************************************************************/ +static int is_chain_clockwise(const int *chain, const int nchain, + const int default_ret) +{ + int i, j, d, sum; + + /* Initialize turn-accumulator to 0. */ + sum = 0; + + /* Foreach neighboring code in chain, compute the difference in */ + /* direction and accumulate. Left-hand turns increment, whereas */ + /* right-hand decrement. */ + for(i = 0, j =1; i < nchain-1; i++, j++){ + /* Compute delta in neighbor direction. */ + d = chain[j] - chain[i]; + /* Make the delta the "inner" distance. */ + /* If delta >= 4, for example if chain_i==2 and chain_j==7 (which */ + /* means the contour went from a step up to step down-to-the-right) */ + /* then 5=(7-2) which is >=4, so -3=(5-8) which means that the */ + /* change in direction is a righ-hand turn of 3 units). */ + if(d >= 4) + d -= 8; + /* If delta <= -4, for example if chain_i==7 and chain_j==2 (which */ + /* means the contour went from a step down-to-the-right to step up) */ + /* then -5=(2-7) which is <=-4, so 3=(-5+8) which means that the */ + /* change in direction is a left-hand turn of 3 units). */ + else if (d <= -4) + d += 8; + + /* The delta direction is then accumulated. */ + sum += d; + } + + /* Now we need to add in the final delta direction between the last */ + /* and first codes in the chain. */ + d = chain[0] - chain[i]; + if(d >= 4) + d -= 8; + else if (d <= -4) + d += 8; + sum += d; + + /* If the final turn_accumulator == 0, then we CAN'T TELL the */ + /* direction of the chain code, so return the default return value. */ + if(sum == 0) + return(default_ret); + /* Otherwise, if the final turn-accumulator is positive ... */ + else if(sum > 0) + /* Then we had a greater amount of left-hand turns than right-hand */ + /* turns, so the chain is in COUNTER-CLOCKWISE order, so return FALSE. */ + return(FALSE); + /* Otherwise, the final turn-accumulator is negative ... */ + else + /* So we had a greater amount of right-hand turns than left-hand */ + /* turns, so the chain is in CLOCKWISE order, so return TRUE. */ + return(TRUE); +} + /************************************************************************* ************************************************************************** #cat: get_loop_list - Takes a list of minutia points and determines which diff --git a/libfprint/nbis/mindtct/minutia.c b/libfprint/nbis/mindtct/minutia.c index 5193fc8a..6bcfaab7 100644 --- a/libfprint/nbis/mindtct/minutia.c +++ b/libfprint/nbis/mindtct/minutia.c @@ -73,6 +73,7 @@ identified are necessarily the best available for the purpose. adjust_high_curvature_minutia() adjust_high_curvature_minutia_V2() get_low_curvature_direction() + lfs2nist_minutia_XYT() ***********************************************************************/ @@ -80,6 +81,8 @@ identified are necessarily the best available for the purpose. #include #include + + /************************************************************************* ************************************************************************** #cat: alloc_minutiae - Allocates and initializes a minutia list based on the @@ -3461,3 +3464,48 @@ int get_low_curvature_direction(const int scan_dir, const int appearing, return(idir); } +/************************************************************************* +************************************************************************** +#cat: lfs2nist_minutia_XYT - Converts XYT minutiae attributes in LFS native +#cat: representation to NIST internal representation + + Input: + minutia - LFS minutia structure containing attributes to be converted + Output: + ox - NIST internal based x-pixel coordinate + oy - NIST internal based y-pixel coordinate + ot - NIST internal based minutia direction/orientation + Return Code: + Zero - successful completion + Negative - system error +**************************************************************************/ +void lfs2nist_minutia_XYT(int *ox, int *oy, int *ot, + const MINUTIA *minutia, const int iw, const int ih) +{ + int x, y, t; + float degrees_per_unit; + + /* XYT's according to NIST internal rep: */ + /* 1. pixel coordinates with origin bottom-left */ + /* 2. orientation in degrees on range [0..360] */ + /* with 0 pointing east and increasing counter */ + /* clockwise (same as M1) */ + /* 3. direction pointing out and away from the */ + /* ridge ending or bifurcation valley */ + /* (opposite direction from M1) */ + + x = minutia->x; + y = ih - minutia->y; + + degrees_per_unit = 180 / (float)NUM_DIRECTIONS; + + t = (270 - sround(minutia->direction * degrees_per_unit)) % 360; + if(t < 0){ + t += 360; + } + + *ox = x; + *oy = y; + *ot = t; +} + diff --git a/libfprint/nbis/mindtct/quality.c b/libfprint/nbis/mindtct/quality.c index 834767f4..5dcabc2a 100644 --- a/libfprint/nbis/mindtct/quality.c +++ b/libfprint/nbis/mindtct/quality.c @@ -39,7 +39,6 @@ identified are necessarily the best available for the purpose. combined_minutia_quality() grayscale_reliability() get_neighborhood_stats() - reliability_fr_quality_map() ***********************************************************************/ @@ -173,6 +172,120 @@ int gen_quality_map(int **oqmap, int *direction_map, int *low_contrast_map, return(0); } +/*********************************************************************** +************************************************************************ +#cat: get_neighborhood_stats - Given a minutia point, computes the mean +#cat: and stdev of the 8-bit grayscale pixels values in a +#cat: surrounding neighborhood with specified radius. + + Code originally written by Austin Hicklin for FBI ATU + Modified by Michael D. Garris (NIST) Sept. 25, 2000 + + Input: + minutia - structure containing detected minutia + idata - 8-bit grayscale fingerprint image + iw - width (in pixels) of the image + ih - height (in pixels) of the image + radius_pix - pixel radius of surrounding neighborhood + Output: + mean - mean of neighboring pixels + stdev - standard deviation of neighboring pixels +************************************************************************/ +static void get_neighborhood_stats(double *mean, double *stdev, MINUTIA *minutia, + unsigned char *idata, const int iw, const int ih, + const int radius_pix) +{ + int i, x, y, rows, cols; + int n = 0, sumX = 0, sumXX = 0; + int histogram[256]; + + /* Zero out histogram. */ + memset(histogram, 0, 256 * sizeof(int)); + + /* Set minutia's coordinate variables. */ + x = minutia->x; + y = minutia->y; + + + /* If minutiae point is within sampleboxsize distance of image border, */ + /* a value of 0 reliability is returned. */ + if ((x < radius_pix) || (x > iw-radius_pix-1) || + (y < radius_pix) || (y > ih-radius_pix-1)) { + *mean = 0.0; + *stdev = 0.0; + return; + + } + + /* Foreach row in neighborhood ... */ + for(rows = y - radius_pix; + rows <= y + radius_pix; + rows++){ + /* Foreach column in neighborhood ... */ + for(cols = x - radius_pix; + cols <= x + radius_pix; + cols++){ + /* Bump neighbor's pixel value bin in histogram. */ + histogram[*(idata+(rows * iw)+cols)]++; + } + } + + /* Foreach grayscale pixel bin ... */ + for(i = 0; i < 256; i++){ + if(histogram[i]){ + /* Accumulate Sum(X[i]) */ + sumX += (i * histogram[i]); + /* Accumulate Sum(X[i]^2) */ + sumXX += (i * i * histogram[i]); + /* Accumulate N samples */ + n += histogram[i]; + } + } + + /* Mean = Sum(X[i])/N */ + *mean = sumX/(double)n; + /* Stdev = sqrt((Sum(X[i]^2)/N) - Mean^2) */ + *stdev = sqrt((sumXX/(double)n) - ((*mean)*(*mean))); +} + +/*********************************************************************** +************************************************************************ +#cat: grayscale_reliability - Given a minutia point, computes a reliability +#cat: measure from the stdev and mean of its pixel neighborhood. + + Code originally written by Austin Hicklin for FBI ATU + Modified by Michael D. Garris (NIST) Sept. 25, 2000 + + GrayScaleReliability - reasonable reliability heuristic, returns + 0.0 .. 1.0 based on stdev and Mean of a localized histogram where + "ideal" stdev is >=64; "ideal" Mean is 127. In a 1 ridge radius + (11 pixels), if the bytevalue (shade of gray) in the image has a + stdev of >= 64 & a mean of 127, returns 1.0 (well defined + light & dark areas in equal proportions). + + Input: + minutia - structure containing detected minutia + idata - 8-bit grayscale fingerprint image + iw - width (in pixels) of the image + ih - height (in pixels) of the image + radius_pix - pixel radius of surrounding neighborhood + Return Value: + reliability - computed reliability measure +************************************************************************/ +static double grayscale_reliability(MINUTIA *minutia, unsigned char *idata, + const int iw, const int ih, const int radius_pix) +{ + double mean, stdev; + double reliability; + + get_neighborhood_stats(&mean, &stdev, minutia, idata, iw, ih, radius_pix); + + reliability = min((stdev>IDEALSTDEV ? 1.0 : stdev/(double)IDEALSTDEV), + (1.0-(fabs(mean-IDEALMEAN)/(double)IDEALMEAN))); + + return(reliability); +} + /*********************************************************************** ************************************************************************ #cat: combined_minutia_quality - Combines quality measures derived from @@ -277,191 +390,4 @@ int combined_minutia_quality(MINUTIAE *minutiae, /* Return normally. */ return(0); } - -/*********************************************************************** -************************************************************************ -#cat: grayscale_reliability - Given a minutia point, computes a reliability -#cat: measure from the stdev and mean of its pixel neighborhood. - - Code originally written by Austin Hicklin for FBI ATU - Modified by Michael D. Garris (NIST) Sept. 25, 2000 - - GrayScaleReliability - reasonable reliability heuristic, returns - 0.0 .. 1.0 based on stdev and Mean of a localized histogram where - "ideal" stdev is >=64; "ideal" Mean is 127. In a 1 ridge radius - (11 pixels), if the bytevalue (shade of gray) in the image has a - stdev of >= 64 & a mean of 127, returns 1.0 (well defined - light & dark areas in equal proportions). - - Input: - minutia - structure containing detected minutia - idata - 8-bit grayscale fingerprint image - iw - width (in pixels) of the image - ih - height (in pixels) of the image - radius_pix - pixel radius of surrounding neighborhood - Return Value: - reliability - computed reliability measure -************************************************************************/ -double grayscale_reliability(MINUTIA *minutia, unsigned char *idata, - const int iw, const int ih, const int radius_pix) -{ - double mean, stdev; - double reliability; - - get_neighborhood_stats(&mean, &stdev, minutia, idata, iw, ih, radius_pix); - - reliability = min((stdev>IDEALSTDEV ? 1.0 : stdev/(double)IDEALSTDEV), - (1.0-(fabs(mean-IDEALMEAN)/(double)IDEALMEAN))); - - return(reliability); -} - - -/*********************************************************************** -************************************************************************ -#cat: get_neighborhood_stats - Given a minutia point, computes the mean -#cat: and stdev of the 8-bit grayscale pixels values in a -#cat: surrounding neighborhood with specified radius. - - Code originally written by Austin Hicklin for FBI ATU - Modified by Michael D. Garris (NIST) Sept. 25, 2000 - - Input: - minutia - structure containing detected minutia - idata - 8-bit grayscale fingerprint image - iw - width (in pixels) of the image - ih - height (in pixels) of the image - radius_pix - pixel radius of surrounding neighborhood - Output: - mean - mean of neighboring pixels - stdev - standard deviation of neighboring pixels -************************************************************************/ -void get_neighborhood_stats(double *mean, double *stdev, MINUTIA *minutia, - unsigned char *idata, const int iw, const int ih, - const int radius_pix) -{ - int i, x, y, rows, cols; - int n = 0, sumX = 0, sumXX = 0; - int histogram[256]; - - /* Zero out histogram. */ - memset(histogram, 0, 256 * sizeof(int)); - - /* Set minutia's coordinate variables. */ - x = minutia->x; - y = minutia->y; - - - /* If minutiae point is within sampleboxsize distance of image border, */ - /* a value of 0 reliability is returned. */ - if ((x < radius_pix) || (x > iw-radius_pix-1) || - (y < radius_pix) || (y > ih-radius_pix-1)) { - *mean = 0.0; - *stdev = 0.0; - return; - - } - - /* Foreach row in neighborhood ... */ - for(rows = y - radius_pix; - rows <= y + radius_pix; - rows++){ - /* Foreach column in neighborhood ... */ - for(cols = x - radius_pix; - cols <= x + radius_pix; - cols++){ - /* Bump neighbor's pixel value bin in histogram. */ - histogram[*(idata+(rows * iw)+cols)]++; - } - } - - /* Foreach grayscale pixel bin ... */ - for(i = 0; i < 256; i++){ - if(histogram[i]){ - /* Accumulate Sum(X[i]) */ - sumX += (i * histogram[i]); - /* Accumulate Sum(X[i]^2) */ - sumXX += (i * i * histogram[i]); - /* Accumulate N samples */ - n += histogram[i]; - } - } - - /* Mean = Sum(X[i])/N */ - *mean = sumX/(double)n; - /* Stdev = sqrt((Sum(X[i]^2)/N) - Mean^2) */ - *stdev = sqrt((sumXX/(double)n) - ((*mean)*(*mean))); -} - -/*********************************************************************** -************************************************************************ -#cat: reliability_fr_quality_map - Takes a set of minutiae and assigns -#cat: each one a reliability measure based on 1 of 5 possible -#cat: quality levels from its location in a quality map. - - Input: - minutiae - structure contining the detected minutia - quality_map - map with blocks assigned 1 of 5 quality levels - map_w - width (in blocks) of the map - map_h - height (in blocks) of the map - blocksize - size (in pixels) of each block in the map - Output: - minutiae - updated reliability members - Return Code: - Zero - successful completion - Negative - system error -************************************************************************/ -int reliability_fr_quality_map(MINUTIAE *minutiae, - int *quality_map, const int mw, const int mh, - const int iw, const int ih, const int blocksize) -{ - int ret, i, index; - int *pquality_map; - MINUTIA *minutia; - - /* Expand block map values to pixel map. */ - if((ret = pixelize_map(&pquality_map, iw, ih, - quality_map, mw, mh, blocksize))){ - return(ret); - } - - /* Foreach minutiae detected ... */ - for(i = 0; i < minutiae->num; i++){ - /* Assign minutia pointer. */ - minutia = minutiae->list[i]; - /* Compute minutia pixel index. */ - index = (minutia->y * iw) + minutia->x; - /* Switch on pixel's quality value ... */ - switch(pquality_map[index]){ - case 0: - minutia->reliability = 0.0; - break; - case 1: - minutia->reliability = 0.25; - break; - case 2: - minutia->reliability = 0.50; - break; - case 3: - minutia->reliability = 0.75; - break; - case 4: - minutia->reliability = 0.99; - break; - /* Error if quality value not in range [0..4]. */ - default: - fprintf(stderr, "ERROR : reliability_fr_quality_map :"); - fprintf(stderr, "unexpected quality value %d ", - pquality_map[index]); - fprintf(stderr, "not in range [0..4]\n"); - return(-2); - } - } - - /* Deallocate pixelized quality map. */ - free(pquality_map); - - /* Return normally. */ - return(0); -} diff --git a/libfprint/nbis/mindtct/remove.c b/libfprint/nbis/mindtct/remove.c index 592cb721..029a0bca 100644 --- a/libfprint/nbis/mindtct/remove.c +++ b/libfprint/nbis/mindtct/remove.c @@ -38,17 +38,12 @@ identified are necessarily the best available for the purpose. remove_false_minutia_V2() remove_holes() remove_hooks() - remove_hooks_islands_lakes_overlaps() remove_islands_and_lakes() remove_malformations() - remove_near_invblock() remove_near_invblock_V2() - remove_pointing_invblock() remove_pointing_invblock_V2() remove_overlaps() - remove_pores() remove_pores_V2() - remove_or_adjust_side_minutiae() remove_or_adjust_side_minutiae_V2() ***********************************************************************/ @@ -346,302 +341,6 @@ static int remove_hooks(MINUTIAE *minutiae, return(0); } -/************************************************************************* -************************************************************************** -#cat: remove_hooks_islands_lakes_overlaps - Removes minutia points on hooks, -#cat: islands, lakes, and overlaps and fills in small small -#cat: loops in the binary image and joins minutia features in -#cat: the image on opposite sides of an overlap. So, this -#cat: routine not only prunes minutia points but it edits the -#cat: binary input image as well. - - Input: - minutiae - list of true and false minutiae - bdata - binary image data (0==while & 1==black) - iw - width (in pixels) of image - ih - height (in pixels) of image - lfsparms - parameters and thresholds for controlling LFS - Output: - minutiae - list of pruned minutiae - bdata - edited binary image with loops filled and overlaps removed - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -static int remove_hooks_islands_lakes_overlaps(MINUTIAE *minutiae, - unsigned char *bdata, const int iw, const int ih, - const LFSPARMS *lfsparms) -{ - int *to_remove; - int i, f, s, ret; - int delta_y, full_ndirs, qtr_ndirs, deltadir, min_deltadir; - int *loop_x, *loop_y, *loop_ex, *loop_ey, nloop; - MINUTIA *minutia1, *minutia2; - double dist; - - print2log("\nREMOVING HOOKS, ISLANDS, LAKES, AND OVERLAPS:\n"); - - /* Allocate list of minutia indices that upon completion of testing */ - /* should be removed from the minutiae lists. Note: That using */ - /* "calloc" initializes the list to FALSE. */ - to_remove = (int *)calloc(minutiae->num, sizeof(int)); - if(to_remove == (int *)NULL){ - fprintf(stderr, - "ERROR : remove_hooks_islands_lakes_overlaps : calloc : to_remove\n"); - return(-300); - } - - /* Compute number directions in full circle. */ - full_ndirs = lfsparms->num_directions<<1; - /* Compute number of directions in 45=(180/4) degrees. */ - qtr_ndirs = lfsparms->num_directions>>2; - - /* Minimum allowable deltadir to consider joining minutia. */ - /* (The closer the deltadir is to 180 degrees, the more likely the join. */ - /* When ndirs==16, then this value is 11=(3*4)-1 == 123.75 degrees. */ - /* I chose to parameterize this threshold based on a fixed fraction of */ - /* 'ndirs' rather than on passing in a parameter in degrees and doing */ - /* the conversion. I doubt the difference matters. */ - min_deltadir = (3 * qtr_ndirs) - 1; - - f = 0; - /* Foreach primary (first) minutia (except for last one in list) ... */ - while(f < minutiae->num-1){ - - /* If current first minutia not previously set to be removed. */ - if(!to_remove[f]){ - - print2log("\n"); - - /* Set first minutia to temporary pointer. */ - minutia1 = minutiae->list[f]; - /* Foreach secondary (second) minutia to right of first minutia ... */ - s = f+1; - while(s < minutiae->num){ - /* Set second minutia to temporary pointer. */ - minutia2 = minutiae->list[s]; - - print2log("1:%d(%d,%d)%d 2:%d(%d,%d)%d ", - f, minutia1->x, minutia1->y, minutia1->type, - s, minutia2->x, minutia2->y, minutia2->type); - - /* The binary image is potentially being edited during each */ - /* iteration of the secondary minutia loop, therefore */ - /* minutia pixel values may be changed. We need to catch */ - /* these events by using the next 2 tests. */ - - /* If the first minutia's pixel has been previously changed... */ - if(*(bdata+(minutia1->y*iw)+minutia1->x) != minutia1->type){ - print2log("\n"); - /* Then break out of secondary loop and skip to next first. */ - break; - } - - /* If the second minutia's pixel has been previously changed... */ - if(*(bdata+(minutia2->y*iw)+minutia2->x) != minutia2->type) - /* Set to remove second minutia. */ - to_remove[s] = TRUE; - - /* If the second minutia not previously set to be removed. */ - if(!to_remove[s]){ - - /* Compute delta y between 1st & 2nd minutiae and test. */ - delta_y = minutia2->y - minutia1->y; - /* If delta y small enough (ex. < 8 pixels) ... */ - if(delta_y <= lfsparms->max_rmtest_dist){ - - print2log("1DY "); - - /* Compute Euclidean distance between 1st & 2nd mintuae. */ - dist = distance(minutia1->x, minutia1->y, - minutia2->x, minutia2->y); - /* If distance is NOT too large (ex. < 8 pixels) ... */ - if(dist <= lfsparms->max_rmtest_dist){ - - print2log("2DS "); - - /* Compute "inner" difference between directions on */ - /* a full circle and test. */ - if((deltadir = closest_dir_dist(minutia1->direction, - minutia2->direction, full_ndirs)) == - INVALID_DIR){ - free(to_remove); - fprintf(stderr, - "ERROR : remove_hooks_islands_lakes_overlaps : INVALID direction\n"); - return(-301); - } - /* If the difference between dirs is large enough ... */ - /* (the more 1st & 2nd point away from each other the */ - /* more likely they should be joined) */ - if(deltadir > min_deltadir){ - - print2log("3DD "); - - /* If 1st & 2nd minutiae are NOT same type ... */ - if(minutia1->type != minutia2->type){ - /* Check to see if pair on a hook with contour */ - /* of specified length (ex. 15 pixels) ... */ - ret = on_hook(minutia1, minutia2, - lfsparms->max_hook_len, - bdata, iw, ih); - /* If hook detected between pair ... */ - if(ret == HOOK_FOUND){ - - print2log("4HK RM\n"); - - /* Set to remove first minutia. */ - to_remove[f] = TRUE; - /* Set to remove second minutia. */ - to_remove[s] = TRUE; - } - /* If hook test IGNORED ... */ - else if (ret == IGNORE){ - - print2log("RM\n"); - - /* Set to remove first minutia. */ - to_remove[f] = TRUE; - /* Skip to next 1st minutia by breaking out of */ - /* inner secondary loop. */ - break; - } - /* If system error occurred during hook test ... */ - else if (ret < 0){ - free(to_remove); - return(ret); - } - /* Otherwise, no hook found, so skip to next */ - /* second minutia. */ - else - print2log("\n"); - } - /* Otherwise, pair is the same type, so test to see */ - /* if both are on an island or lake. */ - else{ - /* Check to see if pair on a loop of specified */ - /* half length (ex. 15 pixels) ... */ - ret = on_island_lake(&loop_x, &loop_y, - &loop_ex, &loop_ey, &nloop, - minutia1, minutia2, - lfsparms->max_half_loop, - bdata, iw, ih); - /* If pair is on island/lake ... */ - if(ret == LOOP_FOUND){ - - print2log("4IL RM\n"); - - /* Fill the loop. */ - if((ret = fill_loop(loop_x, loop_y, nloop, - bdata, iw, ih))){ - free_contour(loop_x, loop_y, - loop_ex, loop_ey); - free(to_remove); - return(ret); - } - /* Set to remove first minutia. */ - to_remove[f] = TRUE; - /* Set to remove second minutia. */ - to_remove[s] = TRUE; - /* Deallocate loop contour. */ - free_contour(loop_x, loop_y, loop_ex, loop_ey); - } - /* If island/lake test IGNORED ... */ - else if (ret == IGNORE){ - - print2log("RM\n"); - - /* Set to remove first minutia. */ - to_remove[f] = TRUE; - /* Skip to next 1st minutia by breaking out of */ - /* inner secondary loop. */ - break; - } - /* If ERROR while looking for island/lake ... */ - else if (ret < 0){ - free(to_remove); - return(ret); - } - /* Otherwise, minutia pair not on island/lake, */ - /* but might be on an overlap. */ - else { - /* If free path exists between pair ... */ - if(free_path(minutia1->x, minutia1->y, - minutia2->x, minutia2->y, - bdata, iw, ih, lfsparms)){ - - print2log("4OV RM\n"); - - /* Then assume overlap, so ... */ - /* Join first and second minutiae in image. */ - if((ret = join_minutia(minutia1, minutia2, - bdata, iw, ih, NO_BOUNDARY, - JOIN_LINE_RADIUS))){ - free(to_remove); - return(ret); - } - /* Set to remove first minutia. */ - to_remove[f] = TRUE; - /* Set to remove second minutia. */ - to_remove[s] = TRUE; - } - /* Otherwise, pair not on an overlap, so skip */ - /* to next second minutia. */ - else - print2log("\n"); - }/* End overlap test. */ - }/* End same type tests (island/lake & overlap). */ - }/* End deltadir test. */ - else - print2log("\n"); - }/* End distance test. */ - else - print2log("\n"); - } - /* Otherwise, current 2nd too far below 1st, so skip to next */ - /* 1st minutia. */ - else{ - - print2log("\n"); - - /* Break out of inner secondary loop. */ - break; - }/* End delta-y test. */ - - }/* End if !to_remove[s] */ - else - print2log("\n"); - - /* Bump to next second minutia in minutiae list. */ - s++; - }/* End secondary minutiae loop. */ - - }/* Otherwise, first minutia already flagged to be removed. */ - - /* Bump to next first minutia in minutiae list. */ - f++; - }/* End primary minutiae loop. */ - - /* Now remove all minutiae in list that have been flagged for removal. */ - /* NOTE: Need to remove the minutia from their lists in reverse */ - /* order, otherwise, indices will be off. */ - for(i = minutiae->num-1; i >= 0; i--){ - /* If the current minutia index is flagged for removal ... */ - if(to_remove[i]){ - /* Remove the minutia from the minutiae list. */ - if((ret = remove_minutia(i, minutiae))){ - free(to_remove); - return(ret); - } - } - } - - /* Deallocate flag list. */ - free(to_remove); - - /* Return normally. */ - return(0); -} - /************************************************************************* ************************************************************************** #cat: remove_islands_and_lakes - Takes a list of true and false minutiae and @@ -1104,237 +803,6 @@ static int remove_malformations(MINUTIAE *minutiae, return(0); } -/************************************************************************* -************************************************************************** -#cat: remove_near_invblocks - Removes minutia points from the given list -#cat: that are sufficiently close to a block with invalid -#cat: ridge flow or to the edge of the image. - - Input: - minutiae - list of true and false minutiae - nmap - IMAP ridge flow matrix with invalid, high-curvature, - and no-valid-neighbor regions identified - mw - width in blocks of the NMAP - mh - height in blocks of the NMAP - lfsparms - parameters and thresholds for controlling LFS - Output: - minutiae - list of pruned minutiae - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -static int remove_near_invblock(MINUTIAE *minutiae, int *nmap, - const int mw, const int mh, const LFSPARMS *lfsparms) -{ - int i, ret; - int ni, nbx, nby, nvalid; - int ix, iy, sbi, ebi; - int bx, by, px, py; - int removed; - MINUTIA *minutia; - int lo_margin, hi_margin; - - /* MDG: The next 2 lookup tables are indexed by 'ix' and 'iy'. */ - /* When a feature pixel lies within a 6-pixel margin of a */ - /* block, this routine examines neighboring blocks to */ - /* determine appropriate actions. */ - /* 'ix' may take on values: */ - /* 0 == x-pixel coord in leftmost margin */ - /* 1 == x-pixel coord in middle of block */ - /* 2 == x-pixel coord in rightmost margin */ - /* 'iy' may take on values: */ - /* 0 == y-pixel coord in topmost margin */ - /* 1 == y-pixel coord in middle of block */ - /* 2 == y-pixel coord in bottommost margin */ - /* Given (ix, iy): */ - /* 'startblk[ix][iy]' == starting neighbor index (sbi) */ - /* 'endblk[ix][iy]' == ending neighbor index (ebi) */ - /* so that neighbors begin to be analized from index */ - /* 'sbi' to 'ebi'. */ - /* Ex. (ix, iy) = (2, 0) */ - /* ix==2 ==> x-pixel coord in rightmost margin */ - /* iy==0 ==> y-pixel coord in topmost margin */ - /* X - marks the region in the current block */ - /* corresponding to (ix=2, iy=0). */ - /* sbi = 0 = startblk[2][0] */ - /* ebi = 2 = endblk[2][0] */ - /* so neighbors are analized on index range [0..2] */ - /* | */ - /* nbr block 0 | nbr block 1 */ - /* --------------------------+------------ */ - /* top margin | X | */ - /* _._._._._._._._._._._._._.| */ - /* | | */ - /* current block .r m| nbr block 2 */ - /* |i a| */ - /* .g g| */ - /* |h i| */ - /* .t n| */ - /* | | */ - - /* MDG: LUT for starting neighbor index given (ix, iy). */ - static int startblk[9] = { 6, 0, 0, - 6,-1, 2, - 4, 4, 2 }; - /* MDG: LUT for ending neighbor index given (ix, iy). */ - static int endblk[9] = { 8, 0, 2, - 6,-1, 2, - 6, 4, 4 }; - - /* MDG: Pixel coord offsets specifying the order in which neighboring */ - /* blocks are searched. The current block is in the middle of */ - /* 8 surrounding neighbors. The following illustrates the order */ - /* of neighbor indices. (Note that 9 overlaps 1.) */ - /* 8 */ - /* 7 0 1 */ - /* 6 C 2 */ - /* 5 4 3 */ - /* */ - /* 0 1 2 3 4 5 6 7 8 */ - static int blkdx[9] = { 0, 1, 1, 1, 0,-1,-1,-1, 0 }; /* Delta-X */ - static int blkdy[9] = { -1,-1, 0, 1, 1, 1, 0,-1,-1 }; /* Delta-Y */ - - print2log("\nREMOVING MINUTIA NEAR INVALID BLOCKS:\n"); - - /* If the margin covers more than the entire block ... */ - if(lfsparms->inv_block_margin > (lfsparms->blocksize>>1)){ - /* Then treat this as an error. */ - fprintf(stderr, - "ERROR : remove_near_invblock : margin too large for blocksize\n"); - return(-270); - } - - /* Compute the low and high pixel margin boundaries (ex. 6 pixels wide) */ - /* in the block. */ - lo_margin = lfsparms->inv_block_margin; - hi_margin = lfsparms->blocksize - lfsparms->inv_block_margin - 1; - - i = 0; - /* Foreach minutia remaining in the list ... */ - while(i < minutiae->num){ - /* Assign temporary minutia pointer. */ - minutia = minutiae->list[i]; - - /* Compute NMAP block coords from minutia's pixel location. */ - bx = minutia->x/lfsparms->blocksize; - by = minutia->y/lfsparms->blocksize; - - /* Compute pixel offset into the NMAP block corresponding to the */ - /* minutia's pixel location. */ - /* NOTE: The margins used here will necessarily correspond to the */ - /* actual block, boundaries used to compute the NMAP values. */ - /* This will be true when the image width and/or height is not an */ - /* even multiple of 'blocksize' and we are processing minutia */ - /* located in the right-most column (or bottom-most row) of */ - /* blocks. I don't think this will pose a problem in practice. */ - px = minutia->x % lfsparms->blocksize; - py = minutia->y % lfsparms->blocksize; - - /* Determine if x pixel offset into the block is in the margins. */ - /* If x pixel offset is in left margin ... */ - if(px < lo_margin) - ix = 0; - /* If x pixel offset is in right margin ... */ - else if(px > hi_margin) - ix = 2; - /* Otherwise, x pixel offset is in middle of block. */ - else - ix = 1; - - /* Determine if y pixel offset into the block is in the margins. */ - /* If y pixel offset is in top margin ... */ - if(py < lo_margin) - iy = 0; - /* If y pixel offset is in bottom margin ... */ - else if(py > hi_margin) - iy = 2; - /* Otherwise, y pixel offset is in middle of block. */ - else - iy = 1; - - /* Set remove flag to FALSE. */ - removed = FALSE; - - /* If one of the minutia's pixel offsets is in a margin ... */ - if((ix != 1) || (iy != 1)){ - - /* Compute the starting neighbor block index for processing. */ - sbi = *(startblk+(iy*3)+ix); - /* Compute the ending neighbor block index for processing. */ - ebi = *(endblk+(iy*3)+ix); - - /* Foreach neighbor in the range to be processed ... */ - for(ni = sbi; ni <= ebi; ni++){ - /* Compute the neighbor's NMAP block coords relative to */ - /* the block the current minutia is in. */ - nbx = bx + blkdx[ni]; - nby = by + blkdy[ni]; - - /* If neighbor's block coords are outside of NMAP boundaries... */ - if((nbx < 0) || (nbx >= mw) || - (nby < 0) || (nby >= mh)){ - - print2log("%d,%d RM1\n", minutia->x, minutia->y); - - /* Then the minutia is in a margin adjacent to the edge of */ - /* the image. */ - /* NOTE: This is true when the image width and/or height */ - /* is an even multiple of blocksize. When the image is not*/ - /* an even multiple, then some minutia may not be detected */ - /* as being in the margin of "the image" (not the block). */ - /* In practice, I don't think this will impact performance.*/ - if((ret = remove_minutia(i, minutiae))) - /* If system error occurred while removing minutia, */ - /* then return error code. */ - return(ret); - /* Set remove flag to TURE. */ - removed = TRUE; - /* Break out of neighboring block loop. */ - break; - } - /* If the neighboring NMAP block is INVALID ... */ - else if (*(nmap+(nby*mw)+nbx) == INVALID_DIR){ - /* Count the number of valid blocks neighboring */ - /* the current neighbor. */ - nvalid = num_valid_8nbrs(nmap, nbx, nby, mw, mh); - /* If the number of valid neighbors is < threshold */ - /* (ex. 7)... */ - if(nvalid < lfsparms->rm_valid_nbr_min){ - - print2log("%d,%d RM2\n", minutia->x, minutia->y); - - /* Then remove the current minutia from the list. */ - if((ret = remove_minutia(i, minutiae))) - /* If system error occurred while removing minutia, */ - /* then return error code. */ - return(ret); - /* Set remove flag to TURE. */ - removed = TRUE; - /* Break out of neighboring block loop. */ - break; - } - /* Otherwise enough valid neighbors, so don't remove minutia */ - /* based on this neighboring block. */ - } - /* Otherwise neighboring block is VALID, HIGH_CURVATURE, or */ - /* NO_VALID_NBRS, so don't remove minutia based on this */ - /* neighboring block. */ - } - - } /* Otherwise not in margin, so skip to next minutia in list. */ - - /* If current minutia not removed ... */ - if(!removed) - /* Advance to the next minutia in the list. */ - i++; - /* Otherwise the next minutia has slid into the spot where current */ - /* minutia was removed, so don't bump minutia index. */ - } /* End minutia loop */ - - /* Return normally. */ - return(0); -} - /************************************************************************* ************************************************************************** #cat: remove_near_invblocks_V2 - Removes minutia points from the given list @@ -1564,99 +1032,6 @@ static int remove_near_invblock_V2(MINUTIAE *minutiae, int *direction_map, return(0); } -/************************************************************************* -************************************************************************** -#cat: remove_pointing_invblock - Removes minutia points that are relatively -#cat: close in the direction opposite the minutia to an NMAP -#cat: block with invalid ridge flow. - - Input: - minutiae - list of true and false minutiae - nmap - IMAP ridge flow matrix with invalid, high-curvature, - and no-valid-neighbor regions identified - mw - width in blocks of the NMAP - mh - height in blocks of the NMAP - lfsparms - parameters and thresholds for controlling LFS - Output: - minutiae - list of pruned minutiae - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -static int remove_pointing_invblock(MINUTIAE *minutiae, - int *nmap, const int mw, const int mh, - const LFSPARMS *lfsparms) -{ - int i, ret; - int delta_x, delta_y, nmapval; - int nx, ny, bx, by; - MINUTIA *minutia; - double pi_factor, theta; - double dx, dy; - - print2log("\nREMOVING MINUTIA POINTING TO INVALID BLOCKS:\n"); - - /* Compute factor for converting integer directions to radians. */ - pi_factor = M_PI / (double)lfsparms->num_directions; - - i = 0; - /* Foreach minutia remaining in list ... */ - while(i < minutiae->num){ - /* Set temporary minutia pointer. */ - minutia = minutiae->list[i]; - /* Convert minutia's direction to radians. */ - theta = minutia->direction * pi_factor; - /* Compute translation offsets (ex. 6 pixels). */ - dx = sin(theta) * (double)lfsparms->trans_dir_pix; - dy = cos(theta) * (double)lfsparms->trans_dir_pix; - /* Need to truncate precision so that answers are consistent */ - /* on different computer architectures when rounding doubles. */ - dx = trunc_dbl_precision(dx, TRUNC_SCALE); - dy = trunc_dbl_precision(dy, TRUNC_SCALE); - delta_x = sround(dx); - delta_y = sround(dy); - /* Translate the minutia's coords. */ - nx = minutia->x - delta_x; - ny = minutia->y + delta_y; - /* Convert pixel coords to NMAP block coords. */ - bx = (int)(nx / lfsparms->blocksize); - by = (int)(ny / lfsparms->blocksize); - /* The translation could move the point out of image boundaries, */ - /* and therefore the corresponding block coords can be out of */ - /* IMAP boundaries, so limit the block coords to within boundaries. */ - bx = max(0, bx); - bx = min(mw-1, bx); - by = max(0, by); - by = min(mh-1, by); - - /* Get corresponding block's NMAP value. */ - /* -3 == NO_VALID_NBRS */ - /* -2 == HIGH_CURVATURE */ - /* -1 == INVALID_DIR */ - /* 0 <= VALID_DIR */ - nmapval = *(nmap+(by*mw)+bx); - - /* If the NMAP value of translated minutia point is INVALID ... */ - if(nmapval == INVALID_DIR){ - - print2log("%d,%d RM\n", minutia->x, minutia->y); - - /* Remove the minutia from the minutiae list. */ - if((ret = remove_minutia(i, minutiae))){ - return(ret); - } - /* No need to advance because next minutia has slid into slot. */ - } - else{ - /* Advance to next minutia in list. */ - i++; - } - } - - /* Return normally. */ - return(0); -} - /************************************************************************* ************************************************************************** #cat: remove_pointing_invblock_V2 - Removes minutia points that are relatively @@ -1975,391 +1350,6 @@ static int remove_overlaps(MINUTIAE *minutiae, return(0); } -/************************************************************************* -************************************************************************** -#cat: remove_pores - Attempts to detect and remove minutia points located on -#cat: pore-shaped valleys. - - Input: - minutiae - list of true and false minutiae - bdata - binary image data (0==while & 1==black) - iw - width (in pixels) of image - ih - height (in pixels) of image - nmap - IMAP ridge flow matrix with invalid, high-curvature, - and no-valid-neighbor regions identified - mw - width in blocks of the NMAP - mh - height in blocks of the NMAP - lfsparms - parameters and thresholds for controlling LFS - Output: - minutiae - list of pruned minutiae - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -static int remove_pores(MINUTIAE *minutiae, - unsigned char *bdata, const int iw, const int ih, - int *nmap, const int mw, const int mh, - const LFSPARMS *lfsparms) -{ - int i, ret; - int removed, blk_x, blk_y; - int rx, ry; - int px, py, pex, pey, bx, by, dx, dy; - int qx, qy, qex, qey, ax, ay, cx, cy; - MINUTIA *minutia; - double pi_factor, theta, sin_theta, cos_theta; - double ab2, cd2, ratio; - int *contour_x, *contour_y, *contour_ex, *contour_ey, ncontour; - double drx, dry; - - /* MDG: This routine attempts to locate the following points on all */ - /* bifurcations within the feature list. */ - /* 1. Compute R 3 pixels opposite the feature direction from */ - /* feature point F. */ - /* 2. Find white pixel transitions P & Q within 12 steps from */ - /* from R perpendicular to the feature's direction. */ - /* 3. Find points B & D by walking white edge from P. */ - /* 4. Find points A & C by walking white edge from Q. */ - /* 5. Measure squared distances between A-B and C-D. */ - /* 6. Compute ratio of squared distances and compare against */ - /* threshold (2.25). If A-B sufficiently larger than C-D, */ - /* then assume NOT pore, otherwise flag the feature point F.*/ - /* If along the way, finding any of these points fails, then */ - /* assume the feature is a pore and flag it. */ - /* */ - /* A */ - /* _____._ */ - /* ----___ Q C */ - /* ------____ ---_.________.___ */ - /* ---_ */ - /* (valley) F.\ .R (ridge) */ - /* ____/ */ - /* ______---- ___-.--------.--- */ - /* ____--- P D */ - /* -----.- */ - /* B */ - /* */ - /* AB^2/CD^2 <= 2.25 then flag feature */ - /* */ - - - print2log("\nREMOVING PORES:\n"); - - /* Factor for converting integer directions into radians. */ - pi_factor = M_PI/(double)lfsparms->num_directions; - - /* Initialize to the beginning of the minutia list. */ - i = 0; - /* Foreach minutia remaining in the list ... */ - while(i < minutiae->num){ - /* Set temporary minutia pointer. */ - minutia = minutiae->list[i]; - - /* Initialize remove flag to FALSE. */ - removed = FALSE; - - /* If minutia is a bifurcation ... */ - if(minutia->type == BIFURCATION){ - /* Compute NMAP block coords from minutia point. */ - blk_x = minutia->x / lfsparms->blocksize; - blk_y = minutia->y / lfsparms->blocksize; - /* If NMAP block has a VALID direction... */ - if(*(nmap+(blk_y*mw)+blk_x) >= 0){ - /* Compute radian angle from minutia direction. */ - theta = (double)minutia->direction * pi_factor; - /* Compute sine and cosine factors of this angle. */ - sin_theta = sin(theta); - cos_theta = cos(theta); - /* Translate the minutia point (ex. 3 pixels) in opposite */ - /* direction minutia is pointing. Call this point 'R'. */ - drx = (double)minutia->x - - (sin_theta * (double)lfsparms->pores_trans_r); - dry = (double)minutia->y + - (cos_theta * (double)lfsparms->pores_trans_r); - /* Need to truncate precision so that answers are consistent */ - /* on different computer architectures when rounding doubles. */ - drx = trunc_dbl_precision(drx, TRUNC_SCALE); - dry = trunc_dbl_precision(dry, TRUNC_SCALE); - rx = sround(drx); - ry = sround(dry); - - /* If 'R' is on a black pixel ... */ - if(*(bdata+(ry*iw)+rx) == 1){ - - /* Search a specified number of steps (ex. 12) from 'R' in a */ - /* perpendicular direction from the minutia direction until */ - /* the first white pixel is found. If a white pixel is */ - /* found within the specified number of steps, then call */ - /* this point 'P' (storing the point's edge pixel as well). */ - if(search_in_direction(&px, &py, &pex, &pey, - 0, rx, ry, -cos_theta, -sin_theta, - lfsparms->pores_perp_steps, - bdata, iw, ih)){ - /* Trace contour from P's edge pixel in counter-clockwise */ - /* scan and step along specified number of steps (ex. 10). */ - ret = trace_contour(&contour_x, &contour_y, - &contour_ex, &contour_ey, &ncontour, - lfsparms->pores_steps_fwd, - px, py, px, py, pex, pey, - SCAN_COUNTER_CLOCKWISE, bdata, iw, ih); - - /* If system error occurred during trace ... */ - if(ret < 0){ - /* Return error code. */ - return(ret); - } - - /* If trace was not possible OR loop found OR */ - /* contour is incomplete ... */ - if((ret == IGNORE) || - (ret == LOOP_FOUND) || - (ncontour < lfsparms->pores_steps_fwd)){ - /* If contour allocated and returned ... */ - if((ret == LOOP_FOUND) || - (ncontour < lfsparms->pores_steps_fwd)) - /* Deallocate the contour. */ - free_contour(contour_x, contour_y, - contour_ex, contour_ey); - - - print2log("%d,%d RMB\n", minutia->x, minutia->y); - - /* Then remove the minutia. */ - if((ret = remove_minutia(i, minutiae))) - /* If system error, return error code. */ - return(ret); - /* Set remove flag to TRUE. */ - removed = TRUE; - } - /* Otherwise, traced contour is complete. */ - else{ - /* Store last point in contour as point 'B'. */ - bx = contour_x[ncontour-1]; - by = contour_y[ncontour-1]; - /* Deallocate the contour. */ - free_contour(contour_x, contour_y, - contour_ex, contour_ey); - - /* Trace contour from P's edge pixel in clockwise scan */ - /* and step along specified number of steps (ex. 8). */ - ret = trace_contour(&contour_x, &contour_y, - &contour_ex, &contour_ey, &ncontour, - lfsparms->pores_steps_bwd, - px, py, px, py, pex, pey, - SCAN_CLOCKWISE, bdata, iw, ih); - - /* If system error occurred during trace ... */ - if(ret < 0){ - /* Return error code. */ - return(ret); - } - - /* If trace was not possible OR loop found OR */ - /* contour is incomplete ... */ - if((ret == IGNORE) || - (ret == LOOP_FOUND) || - (ncontour < lfsparms->pores_steps_bwd)){ - /* If contour allocated and returned ... */ - if((ret == LOOP_FOUND) || - (ncontour < lfsparms->pores_steps_bwd)) - /* Deallocate the contour. */ - free_contour(contour_x, contour_y, - contour_ex, contour_ey); - - print2log("%d,%d RMD\n", minutia->x, minutia->y); - - /* Then remove the minutia. */ - if((ret = remove_minutia(i, minutiae))) - /* If system error, return error code. */ - return(ret); - /* Set remove flag to TRUE. */ - removed = TRUE; - } - /* Otherwise, traced contour is complete. */ - else{ - /* Store last point in contour as point 'D'. */ - dx = contour_x[ncontour-1]; - dy = contour_y[ncontour-1]; - /* Deallocate the contour. */ - free_contour(contour_x, contour_y, - contour_ex, contour_ey); - /* Search a specified number of steps (ex. 12) from */ - /* 'R' in opposite direction of that used to find */ - /* 'P' until the first white pixel is found. If a */ - /* white pixel is found within the specified number */ - /* of steps, then call this point 'Q' (storing the */ - /* point's edge pixel as well). */ - if(search_in_direction(&qx, &qy, &qex, &qey, - 0, rx, ry, cos_theta, sin_theta, - lfsparms->pores_perp_steps, - bdata, iw, ih)){ - /* Trace contour from Q's edge pixel in clockwise */ - /* scan and step along specified number of steps */ - /* (ex. 10). */ - ret = trace_contour(&contour_x, &contour_y, - &contour_ex, &contour_ey, &ncontour, - lfsparms->pores_steps_fwd, - qx, qy, qx, qy, qex, qey, - SCAN_CLOCKWISE, bdata, iw, ih); - - /* If system error occurred during trace ... */ - if(ret < 0){ - /* Return error code. */ - return(ret); - } - - /* If trace was not possible OR loop found OR */ - /* contour is incomplete ... */ - if((ret == IGNORE) || - (ret == LOOP_FOUND) || - (ncontour < lfsparms->pores_steps_fwd)){ - /* If contour allocated and returned ... */ - if((ret == LOOP_FOUND) || - (ncontour < lfsparms->pores_steps_fwd)) - /* Deallocate the contour. */ - free_contour(contour_x, contour_y, - contour_ex, contour_ey); - - print2log("%d,%d RMA\n", minutia->x, minutia->y); - - /* Then remove the minutia. */ - if((ret = remove_minutia(i, minutiae))) - /* If system error, return error code. */ - return(ret); - /* Set remove flag to TRUE. */ - removed = TRUE; - } - /* Otherwise, traced contour is complete. */ - else{ - /* Store last point in contour as point 'A'. */ - ax = contour_x[ncontour-1]; - ay = contour_y[ncontour-1]; - /* Deallocate the contour. */ - free_contour(contour_x, contour_y, - contour_ex, contour_ey); - - /* Trace contour from Q's edge pixel in */ - /* counter-clockwise scan and step along a */ - /* specified number of steps (ex. 8). */ - ret = trace_contour(&contour_x, &contour_y, - &contour_ex, &contour_ey, &ncontour, - lfsparms->pores_steps_bwd, - qx, qy, qx, qy, qex, qey, - SCAN_COUNTER_CLOCKWISE, bdata, iw, ih); - - /* If system error occurred during scan ... */ - if(ret < 0){ - /* Return error code. */ - return(ret); - } - - /* If trace was not possible OR loop found OR */ - /* contour is incomplete ... */ - if((ret == IGNORE) || - (ret == LOOP_FOUND) || - (ncontour < lfsparms->pores_steps_bwd)){ - /* If contour allocated and returned ... */ - if((ret == LOOP_FOUND) || - (ncontour < lfsparms->pores_steps_bwd)) - /* Deallocate the contour. */ - free_contour(contour_x, contour_y, - contour_ex, contour_ey); - - print2log("%d,%d RMC\n", - minutia->x, minutia->y); - - /* Then remove the minutia. */ - if((ret = remove_minutia(i, minutiae))) - /* If system error, return error code. */ - return(ret); - /* Set remove flag to TRUE. */ - removed = TRUE; - } - /* Otherwise, traced contour is complete. */ - else{ - /* Store last point in contour as 'C'. */ - cx = contour_x[ncontour-1]; - cy = contour_y[ncontour-1]; - /* Deallocate the contour. */ - free_contour(contour_x, contour_y, - contour_ex, contour_ey); - - /* Compute squared distance between points */ - /* 'A' and 'B'. */ - ab2 = squared_distance(ax, ay, bx, by); - /* Compute squared distance between points */ - /* 'C' and 'D'. */ - cd2 = squared_distance(cx, cy, dx, dy); - /* If CD distance is not near zero */ - /* (ex. 0,5) ... */ - if(cd2 > lfsparms->pores_min_dist2){ - /* Compute ratio of squared distances. */ - ratio = ab2 / cd2; - /* If ratio is small enough (ex. 2.25)...*/ - if(ratio <= lfsparms->pores_max_ratio){ - - print2log("%d,%d ", - minutia->x, minutia->y); - print2log("R=%d,%d P=%d,%d B=%d,%d D=%d,%d Q=%d,%d A=%d,%d C=%d,%d ", - rx, ry, px, py, bx, by, dx, dy, qx, qy, ax, ay, cx, cy); - print2log("RMRATIO\n"); - - /* Then assume pore & remove minutia. */ - if((ret = remove_minutia(i, minutiae))) - /* If system error, return code. */ - return(ret); - /* Set remove flag to TRUE. */ - removed = TRUE; - } - /* Otherwise, ratio to big, so assume */ - /* legitimate bifurcation. */ - } /* Else, cd2 too small. */ - } /* Done with C. */ - } /* Done with A. */ - } - /* Otherwise, Q not found ... */ - else{ - - print2log("%d,%d RMQ\n", minutia->x, minutia->y); - - /* Then remove the minutia. */ - if((ret = remove_minutia(i, minutiae))) - /* If system error, return error code. */ - return(ret); - /* Set remove flag to TRUE. */ - removed = TRUE; - } /* Done with Q. */ - } /* Done with D. */ - } /* Done with B. */ - } - /* Otherwise, P not found ... */ - else{ - - print2log("%d,%d RMP\n", minutia->x, minutia->y); - - /* Then remove the minutia. */ - if((ret = remove_minutia(i, minutiae))) - /* If system error, return error code. */ - return(ret); - /* Set remove flag to TRUE. */ - removed = TRUE; - } - } /* Else, R is on white pixel. */ - } /* Else NMAP is INVALID, HIGH_CURVATURE, or NO_VALID_NBRS. */ - } /* Else, Ridge Ending. */ - - /* If current minutia not removed ... */ - if(!removed) - /* Bump to next minutia in list. */ - i++; - /* Otherwise, next minutia has slid into slot of current removed one. */ - - } /* End While minutia remaining in list. */ - - /* Return normally. */ - return(0); -} - /************************************************************************* ************************************************************************** #cat: remove_pores_V2 - Attempts to detect and remove minutia points located on @@ -2753,223 +1743,6 @@ static int remove_pores_V2(MINUTIAE *minutiae, return(0); } -/************************************************************************* -************************************************************************** -#cat: remove_or_adjust_side_minutiae - Removes loops or minutia points that -#cat: are not on complete contours of specified length. If the -#cat: contour is complete, then the minutia is adjusted based -#cat: on a minmax analysis of the rotated y-coords of the contour. - - Input: - minutiae - list of true and false minutiae - bdata - binary image data (0==while & 1==black) - iw - width (in pixels) of image - ih - height (in pixels) of image - lfsparms - parameters and thresholds for controlling LFS - Output: - minutiae - list of pruned minutiae - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -static int remove_or_adjust_side_minutiae(MINUTIAE *minutiae, - unsigned char *bdata, const int iw, const int ih, - const LFSPARMS *lfsparms) -{ - int i, j, ret; - MINUTIA *minutia; - double pi_factor, theta, sin_theta, cos_theta; - int *contour_x, *contour_y, *contour_ex, *contour_ey, ncontour; - int *rot_y, minloc; - int *minmax_val, *minmax_i, *minmax_type, minmax_alloc, minmax_num; - double drot_y; - - print2log("\nADJUSTING SIDE MINUTIA:\n"); - - /* Allocate working memory for holding rotated y-coord of a */ - /* minutia's contour. */ - rot_y = (int *)malloc(((lfsparms->side_half_contour<<1)+1) * sizeof(int)); - if(rot_y == (int *)NULL){ - fprintf(stderr, - "ERROR : remove_or_adjust_side_minutiae : malloc : rot_y\n"); - return(-280); - } - - /* Compute factor for converting integer directions to radians. */ - pi_factor = M_PI / (double)lfsparms->num_directions; - - i = 0; - /* Foreach minutia remaining in list ... */ - while(i < minutiae->num){ - /* Assign a temporary pointer. */ - minutia = minutiae->list[i]; - - /* Extract a contour centered on the minutia point (ex. 7 pixels */ - /* in both directions). */ - ret = get_centered_contour(&contour_x, &contour_y, - &contour_ex, &contour_ey, &ncontour, - lfsparms->side_half_contour, - minutia->x, minutia->y, minutia->ex, minutia->ey, - bdata, iw, ih); - - /* If system error occurred ... */ - if(ret < 0){ - /* Deallocate working memory. */ - free(rot_y); - /* Return error code. */ - return(ret); - } - - /* If we didn't succeed in extracting a complete contour for any */ - /* other reason ... */ - if((ret == LOOP_FOUND) || - (ret == IGNORE) || - (ret == INCOMPLETE)){ - - print2log("%d,%d RM1\n", minutia->x, minutia->y); - - /* Remove minutia from list. */ - if((ret = remove_minutia(i, minutiae))){ - /* Deallocate working memory. */ - free(rot_y); - /* Return error code. */ - return(ret); - } - /* No need to advance because next minutia has "slid" */ - /* into position pointed to by 'i'. */ - } - /* Otherwise, a complete contour was found and extracted ... */ - else{ - /* Rotate contour points by negative angle of feature's direction. */ - /* The contour of a well-formed minutia point will form a bowl */ - /* shape concaved in the direction of the minutia. By rotating */ - /* the contour points by the negative angle of feature's direction */ - /* the bowl will be transformed to be concaved upwards and minima */ - /* and maxima of the transformed y-coords can be analyzed to */ - /* determine if the minutia is "well-formed" or not. If well- */ - /* formed then the position of the minutia point is adjusted. If */ - /* not well-formed, then the minutia point is removed altogether. */ - - /* Normal rotation of T degrees around the origin of */ - /* the point (x,y): */ - /* rx = x*cos(T) - y*sin(T) */ - /* ry = x*cos(T) + y*sin(T) */ - /* The rotation here is for -T degrees: */ - /* rx = x*cos(-T) - y*sin(-T) */ - /* ry = x*cos(-T) + y*sin(-T) */ - /* which can be written: */ - /* rx = x*cos(T) + y*sin(T) */ - /* ry = x*sin(T) - y*cos(T) */ - - /* Convert minutia's direction to radians. */ - theta = (double)minutia->direction * pi_factor; - /* Compute sine and cosine values at theta for rotation. */ - sin_theta = sin(theta); - cos_theta = cos(theta); - - for(j = 0; j < ncontour; j++){ - /* We only need to rotate the y-coord (don't worry */ - /* about rotating the x-coord or contour edge pixels). */ - drot_y = ((double)contour_x[j] * sin_theta) - - ((double)contour_y[j] * cos_theta); - /* Need to truncate precision so that answers are consistent */ - /* on different computer architectures when rounding doubles. */ - drot_y = trunc_dbl_precision(drot_y, TRUNC_SCALE); - rot_y[j] = sround(drot_y); - } - - /* Locate relative minima and maxima in vector of rotated */ - /* y-coords of current minutia's contour. */ - if((ret = minmaxs(&minmax_val, &minmax_type, &minmax_i, - &minmax_alloc, &minmax_num, - rot_y, ncontour))){ - /* If system error, then deallocate working memories. */ - free(rot_y); - free_contour(contour_x, contour_y, contour_ex, contour_ey); - /* Return error code. */ - return(ret); - } - - /* If one and only one minima was found in rotated y-coord */ - /* of contour ... */ - if((minmax_num == 1) && - (minmax_type[0] == -1)){ - - print2log("%d,%d AD1 ", minutia->x, minutia->y); - - /* Reset loation of minutia point to contour point at minima. */ - minutia->x = contour_x[minmax_i[0]]; - minutia->y = contour_y[minmax_i[0]]; - minutia->ex = contour_ex[minmax_i[0]]; - minutia->ey = contour_ey[minmax_i[0]]; - /* Advance to the next minutia in the list. */ - i++; - - print2log("%d,%d\n", minutia->x, minutia->y); - - } - /* If exactly 3 min/max found and they are min-max-min ... */ - else if((minmax_num == 3) && - (minmax_type[0] == -1)){ - /* Choose minima location with smallest rotated y-coord. */ - if(minmax_val[0] < minmax_val[2]) - minloc = minmax_i[0]; - else - minloc = minmax_i[2]; - - print2log("%d,%d AD2 ", minutia->x, minutia->y); - - /* Reset loation of minutia point to contour point at minima. */ - minutia->x = contour_x[minloc]; - minutia->y = contour_y[minloc]; - minutia->ex = contour_ex[minloc]; - minutia->ey = contour_ey[minloc]; - /* Advance to the next minutia in the list. */ - i++; - - print2log("%d,%d\n", minutia->x, minutia->y); - - } - /* Otherwise, ... */ - else{ - - print2log("%d,%d RM2\n", minutia->x, minutia->y); - - /* Remove minutia from list. */ - if((ret = remove_minutia(i, minutiae))){ - /* If system error, then deallocate working memories. */ - free(rot_y); - free_contour(contour_x, contour_y, contour_ex, contour_ey); - if(minmax_alloc > 0){ - free(minmax_val); - free(minmax_type); - free(minmax_i); - } - /* Return error code. */ - return(ret); - } - /* No need to advance because next minutia has "slid" */ - /* into position pointed to by 'i'. */ - - } - - /* Deallocate contour and min/max buffers. */ - free_contour(contour_x, contour_y, contour_ex, contour_ey); - if(minmax_alloc > 0){ - free(minmax_val); - free(minmax_type); - free(minmax_i); - } - } /* End else contour extracted. */ - } /* End while not end of minutiae list. */ - - /* Deallocate working memory. */ - free(rot_y); - - /* Return normally. */ - return(0); -} - /************************************************************************* ************************************************************************** #cat: remove_or_adjust_side_minutiae_V2 - Removes loops or minutia points that diff --git a/libfprint/nbis/mindtct/ridges.c b/libfprint/nbis/mindtct/ridges.c index 8cbfbe7c..0fb26863 100644 --- a/libfprint/nbis/mindtct/ridges.c +++ b/libfprint/nbis/mindtct/ridges.c @@ -52,135 +52,156 @@ identified are necessarily the best available for the purpose. /************************************************************************* ************************************************************************** -#cat: count_minutiae_ridges - Takes a list of minutiae, and for each one, -#cat: determines its closest neighbors and counts the number -#cat: of interveining ridges between the minutia point and -#cat: each of its neighbors. +#cat: insert_neighbor - Takes a minutia index and its squared distance to a +#cat: primary minutia point, and inserts them in the specified +#cat: position of their respective lists, shifting previously +#cat: stored values down and off the lists as necessary. Input: - minutiae - list of minutiae - bdata - binary image data (0==while & 1==black) - iw - width (in pixels) of image - ih - height (in pixels) of image - lfsparms - parameters and thresholds for controlling LFS + pos - postions where values are to be inserted in lists + nbr_index - index of minutia being inserted + nbr_dist2 - squared distance of minutia to its primary point + nbr_list - current list of nearest neighbor minutia indices + nbr_sqr_dists - corresponding squared euclidean distance of each + neighbor to the primary minutia point + nnbrs - number of neighbors currently in the list + max_nbrs - maximum number of closest neighbors to be returned Output: - minutiae - list of minutiae augmented with neighbors and ridge counts + nbr_list - updated list of nearest neighbor indices + nbr_sqr_dists - updated list of nearest neighbor distances + nnbrs - number of neighbors in the update lists Return Code: - Zero - successful completion - Negative - system error + Zero - successful completion + Negative - system error **************************************************************************/ -int count_minutiae_ridges(MINUTIAE *minutiae, - unsigned char *bdata, const int iw, const int ih, - const LFSPARMS *lfsparms) +static int insert_neighbor(const int pos, const int nbr_index, const double nbr_dist2, + int *nbr_list, double *nbr_sqr_dists, + int *nnbrs, const int max_nbrs) { - int ret; int i; - print2log("\nFINDING NBRS AND COUNTING RIDGES:\n"); - - /* Sort minutia points on x then y (column-oriented). */ - if((ret = sort_minutiae_x_y(minutiae, iw, ih))){ - return(ret); + /* If the desired insertion position is beyond one passed the last */ + /* neighbor in the lists OR greater than equal to the maximum ... */ + /* NOTE: pos is zero-oriented while nnbrs and max_nbrs are 1-oriented. */ + if((pos > *nnbrs) || + (pos >= max_nbrs)){ + fprintf(stderr, + "ERROR : insert_neighbor : insertion point exceeds lists\n"); + return(-480); } - /* Remove any duplicate minutia points from the list. */ - if((ret = rm_dup_minutiae(minutiae))){ - return(ret); + /* If the neighbor lists are NOT full ... */ + if(*nnbrs < max_nbrs){ + /* Then we have room to shift everything down to make room for new */ + /* neighbor and increase the number of neighbors stored by 1. */ + i = *nnbrs-1; + (*nnbrs)++; + } + /* Otherwise, the neighbors lists are full ... */ + else if(*nnbrs == max_nbrs) + /* So, we must bump the last neighbor in the lists off to make */ + /* room for the new neighbor (ignore last neighbor in lists). */ + i = *nnbrs-2; + /* Otherwise, there is a list overflow error condition */ + /* (shouldn't ever happen, but just in case) ... */ + else{ + fprintf(stderr, + "ERROR : insert_neighbor : overflow in neighbor lists\n"); + return(-481); } - /* Foreach remaining sorted minutia in list ... */ - for(i = 0; i < minutiae->num-1; i++){ - /* Located neighbors and count number of ridges in between. */ - /* NOTE: neighbor and ridge count results are stored in */ - /* minutiae->list[i]. */ - if((ret = count_minutia_ridges(i, minutiae, bdata, iw, ih, lfsparms))){ - return(ret); - } + /* While we havn't reached the desired insertion point ... */ + while(i >= pos){ + /* Shift the current neighbor down the list 1 positon. */ + nbr_list[i+1] = nbr_list[i]; + nbr_sqr_dists[i+1] = nbr_sqr_dists[i]; + i--; } + /* We are now ready to put our new neighbor in the position where */ + /* we shifted everything down from to make room. */ + nbr_list[pos] = nbr_index; + nbr_sqr_dists[pos] = nbr_dist2; + /* Return normally. */ return(0); } /************************************************************************* ************************************************************************** -#cat: count_minutia_ridges - Takes a minutia, and determines its closest -#cat: neighbors and counts the number of interveining ridges -#cat: between the minutia point and each of its neighbors. +#cat: update_nbr_dists - Takes the current list of neighbors along with a +#cat: primary minutia and a potential new neighbor, and +#cat: determines if the new neighbor is sufficiently close +#cat: to be added to the list of nearest neighbors. If added, +#cat: it is placed in the list in its proper order based on +#cat: squared distance to the primary point. Input: - minutia - input minutia - bdata - binary image data (0==while & 1==black) - iw - width (in pixels) of image - ih - height (in pixels) of image - lfsparms - parameters and thresholds for controlling LFS + nbr_list - current list of nearest neighbor minutia indices + nbr_sqr_dists - corresponding squared euclidean distance of each + neighbor to the primary minutia point + nnbrs - number of neighbors currently in the list + max_nbrs - maximum number of closest neighbors to be returned + first - index of the primary minutia point + second - index of the secondary (new neighbor) point + minutiae - list of minutiae Output: - minutiae - minutia augmented with neighbors and ridge counts + nbr_list - updated list of nearest neighbor indices + nbr_sqr_dists - updated list of nearest neighbor distances + nnbrs - number of neighbors in the update lists Return Code: - Zero - successful completion - Negative - system error + Zero - successful completion + Negative - system error **************************************************************************/ -int count_minutia_ridges(const int first, MINUTIAE *minutiae, - unsigned char *bdata, const int iw, const int ih, - const LFSPARMS *lfsparms) +static int update_nbr_dists(int *nbr_list, double *nbr_sqr_dists, + int *nnbrs, const int max_nbrs, + const int first, const int second, MINUTIAE *minutiae) { - int i, ret, *nbr_list, *nbr_nridges, nnbrs; + double dist2; + MINUTIA *minutia1, *minutia2; + int pos, last_nbr; - /* Find up to the maximum number of qualifying neighbors. */ - if((ret = find_neighbors(&nbr_list, &nnbrs, lfsparms->max_nbrs, - first, minutiae))){ - free(nbr_list); - return(ret); - } + /* Compute position of maximum last neighbor stored. */ + last_nbr = max_nbrs - 1; - print2log("NBRS FOUND: %d,%d = %d\n", minutiae->list[first]->x, - minutiae->list[first]->y, nnbrs); + /* Assigne temporary minutia pointers. */ + minutia1 = minutiae->list[first]; + minutia2 = minutiae->list[second]; - /* If no neighors found ... */ - if(nnbrs == 0){ - /* Then no list returned and no ridges to count. */ + /* Compute squared euclidean distance between minutia pair. */ + dist2 = squared_distance(minutia1->x, minutia1->y, + minutia2->x, minutia2->y); + + /* If maximum number of neighbors not yet stored in lists OR */ + /* if the squared distance to current secondary is less */ + /* than the largest stored neighbor distance ... */ + if((*nnbrs < max_nbrs) || + (dist2 < nbr_sqr_dists[last_nbr])){ + + /* Find insertion point in neighbor lists. */ + pos = find_incr_position_dbl(dist2, nbr_sqr_dists, *nnbrs); + /* If the position returned is >= maximum list length (this should */ + /* never happen, but just in case) ... */ + if(pos >= max_nbrs){ + fprintf(stderr, + "ERROR : update_nbr_dists : illegal position for new neighbor\n"); + return(-470); + } + /* Insert the new neighbor into the neighbor lists at the */ + /* specified location. */ + if(insert_neighbor(pos, second, dist2, + nbr_list, nbr_sqr_dists, nnbrs, max_nbrs)) + return(-471); + + /* Otherwise, neighbor inserted successfully, so return normally. */ return(0); } + /* Otherwise, the new neighbor is not sufficiently close to be */ + /* added or inserted into the neighbor lists, so ignore the neighbor */ + /* and return normally. */ + else + return(0); - /* Sort neighbors on delta dirs. */ - if((ret = sort_neighbors(nbr_list, nnbrs, first, minutiae))){ - free(nbr_list); - return(ret); - } - - /* Count ridges between first and neighbors. */ - /* List of ridge counts, one for each neighbor stored. */ - nbr_nridges = (int *)malloc(nnbrs * sizeof(int)); - if(nbr_nridges == (int *)NULL){ - free(nbr_list); - fprintf(stderr, "ERROR : count_minutia_ridges : malloc : nbr_nridges\n"); - return(-450); - } - - /* Foreach neighbor found and sorted in list ... */ - for(i = 0; i < nnbrs; i++){ - /* Count the ridges between the primary minutia and the neighbor. */ - ret = ridge_count(first, nbr_list[i], minutiae, bdata, iw, ih, lfsparms); - /* If system error ... */ - if(ret < 0){ - /* Deallocate working memories. */ - free(nbr_list); - free(nbr_nridges); - /* Return error code. */ - return(ret); - } - - /* Otherwise, ridge count successful, so store ridge count to list. */ - nbr_nridges[i] = ret; - } - - /* Assign neighbor indices and ridge counts to primary minutia. */ - minutiae->list[first]->nbrs = nbr_list; - minutiae->list[first]->ridge_counts = nbr_nridges; - minutiae->list[first]->num_nbrs = nnbrs; - - /* Return normally. */ - return(0); } /************************************************************************* @@ -203,7 +224,7 @@ int count_minutia_ridges(const int first, MINUTIAE *minutiae, Zero - successful completion Negative - system error **************************************************************************/ -int find_neighbors(int **onbr_list, int *onnbrs, const int max_nbrs, +static int find_neighbors(int **onbr_list, int *onnbrs, const int max_nbrs, const int first, MINUTIAE *minutiae) { int ret, second, last_nbr; @@ -291,160 +312,6 @@ int find_neighbors(int **onbr_list, int *onnbrs, const int max_nbrs, return(0); } -/************************************************************************* -************************************************************************** -#cat: update_nbr_dists - Takes the current list of neighbors along with a -#cat: primary minutia and a potential new neighbor, and -#cat: determines if the new neighbor is sufficiently close -#cat: to be added to the list of nearest neighbors. If added, -#cat: it is placed in the list in its proper order based on -#cat: squared distance to the primary point. - - Input: - nbr_list - current list of nearest neighbor minutia indices - nbr_sqr_dists - corresponding squared euclidean distance of each - neighbor to the primary minutia point - nnbrs - number of neighbors currently in the list - max_nbrs - maximum number of closest neighbors to be returned - first - index of the primary minutia point - second - index of the secondary (new neighbor) point - minutiae - list of minutiae - Output: - nbr_list - updated list of nearest neighbor indices - nbr_sqr_dists - updated list of nearest neighbor distances - nnbrs - number of neighbors in the update lists - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int update_nbr_dists(int *nbr_list, double *nbr_sqr_dists, - int *nnbrs, const int max_nbrs, - const int first, const int second, MINUTIAE *minutiae) -{ - double dist2; - MINUTIA *minutia1, *minutia2; - int pos, last_nbr; - - /* Compute position of maximum last neighbor stored. */ - last_nbr = max_nbrs - 1; - - /* Assigne temporary minutia pointers. */ - minutia1 = minutiae->list[first]; - minutia2 = minutiae->list[second]; - - /* Compute squared euclidean distance between minutia pair. */ - dist2 = squared_distance(minutia1->x, minutia1->y, - minutia2->x, minutia2->y); - - /* If maximum number of neighbors not yet stored in lists OR */ - /* if the squared distance to current secondary is less */ - /* than the largest stored neighbor distance ... */ - if((*nnbrs < max_nbrs) || - (dist2 < nbr_sqr_dists[last_nbr])){ - - /* Find insertion point in neighbor lists. */ - pos = find_incr_position_dbl(dist2, nbr_sqr_dists, *nnbrs); - /* If the position returned is >= maximum list length (this should */ - /* never happen, but just in case) ... */ - if(pos >= max_nbrs){ - fprintf(stderr, - "ERROR : update_nbr_dists : illegal position for new neighbor\n"); - return(-470); - } - /* Insert the new neighbor into the neighbor lists at the */ - /* specified location. */ - if(insert_neighbor(pos, second, dist2, - nbr_list, nbr_sqr_dists, nnbrs, max_nbrs)) - return(-471); - - /* Otherwise, neighbor inserted successfully, so return normally. */ - return(0); - } - /* Otherwise, the new neighbor is not sufficiently close to be */ - /* added or inserted into the neighbor lists, so ignore the neighbor */ - /* and return normally. */ - else - return(0); - -} - -/************************************************************************* -************************************************************************** -#cat: insert_neighbor - Takes a minutia index and its squared distance to a -#cat: primary minutia point, and inserts them in the specified -#cat: position of their respective lists, shifting previously -#cat: stored values down and off the lists as necessary. - - Input: - pos - postions where values are to be inserted in lists - nbr_index - index of minutia being inserted - nbr_dist2 - squared distance of minutia to its primary point - nbr_list - current list of nearest neighbor minutia indices - nbr_sqr_dists - corresponding squared euclidean distance of each - neighbor to the primary minutia point - nnbrs - number of neighbors currently in the list - max_nbrs - maximum number of closest neighbors to be returned - Output: - nbr_list - updated list of nearest neighbor indices - nbr_sqr_dists - updated list of nearest neighbor distances - nnbrs - number of neighbors in the update lists - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -int insert_neighbor(const int pos, const int nbr_index, const double nbr_dist2, - int *nbr_list, double *nbr_sqr_dists, - int *nnbrs, const int max_nbrs) -{ - int i; - - /* If the desired insertion position is beyond one passed the last */ - /* neighbor in the lists OR greater than equal to the maximum ... */ - /* NOTE: pos is zero-oriented while nnbrs and max_nbrs are 1-oriented. */ - if((pos > *nnbrs) || - (pos >= max_nbrs)){ - fprintf(stderr, - "ERROR : insert_neighbor : insertion point exceeds lists\n"); - return(-480); - } - - /* If the neighbor lists are NOT full ... */ - if(*nnbrs < max_nbrs){ - /* Then we have room to shift everything down to make room for new */ - /* neighbor and increase the number of neighbors stored by 1. */ - i = *nnbrs-1; - (*nnbrs)++; - } - /* Otherwise, the neighbors lists are full ... */ - else if(*nnbrs == max_nbrs) - /* So, we must bump the last neighbor in the lists off to make */ - /* room for the new neighbor (ignore last neighbor in lists). */ - i = *nnbrs-2; - /* Otherwise, there is a list overflow error condition */ - /* (shouldn't ever happen, but just in case) ... */ - else{ - fprintf(stderr, - "ERROR : insert_neighbor : overflow in neighbor lists\n"); - return(-481); - } - - /* While we havn't reached the desired insertion point ... */ - while(i >= pos){ - /* Shift the current neighbor down the list 1 positon. */ - nbr_list[i+1] = nbr_list[i]; - nbr_sqr_dists[i+1] = nbr_sqr_dists[i]; - i--; - } - - /* We are now ready to put our new neighbor in the position where */ - /* we shifted everything down from to make room. */ - nbr_list[pos] = nbr_index; - nbr_sqr_dists[pos] = nbr_dist2; - - /* Return normally. */ - return(0); -} - /************************************************************************* ************************************************************************** #cat: sort_neighbors - Takes a list of primary minutia and its neighboring @@ -464,7 +331,7 @@ int insert_neighbor(const int pos, const int nbr_index, const double nbr_dist2, Zero - successful completion Negative - system error **************************************************************************/ -int sort_neighbors(int *nbr_list, const int nnbrs, const int first, +static int sort_neighbors(int *nbr_list, const int nnbrs, const int first, MINUTIAE *minutiae) { double *join_thetas, theta; @@ -505,6 +372,174 @@ int sort_neighbors(int *nbr_list, const int nnbrs, const int first, return(0); } +/************************************************************************* +************************************************************************** +#cat: find_transition - Takes a pixel trajectory and a starting index, and +#cat: searches forward along the trajectory until the specified +#cat: adjacent pixel pair is found, returning the index where +#cat: the pair was found (the index of the second pixel). + + Input: + iptr - pointer to starting pixel index into trajectory + pix1 - first pixel value in transition pair + pix2 - second pixel value in transition pair + xlist - x-pixel coords of line trajectory + ylist - y-pixel coords of line trajectory + num - number of coords in line trajectory + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + Output: + iptr - points to location where 2nd pixel in pair is found + Return Code: + TRUE - pixel pair transition found + FALSE - pixel pair transition not found +**************************************************************************/ +static int find_transition(int *iptr, const int pix1, const int pix2, + const int *xlist, const int *ylist, const int num, + unsigned char *bdata, const int iw, const int ih) +{ + int i, j; + + /* Set previous index to starting position. */ + i = *iptr; + /* Bump previous index by 1 to get next index. */ + j = i+1; + + /* While not one point from the end of the trajectory .. */ + while(i < num-1){ + /* If we have found the desired transition ... */ + if((*(bdata+(ylist[i]*iw)+xlist[i]) == pix1) && + (*(bdata+(ylist[j]*iw)+xlist[j]) == pix2)){ + /* Adjust the position pointer to the location of the */ + /* second pixel in the transition. */ + *iptr = j; + + /* Return TRUE. */ + return(TRUE); + } + /* Otherwise, the desired transition was not found in current */ + /* pixel pair, so bump to the next pair along the trajector. */ + i++; + j++; + } + + /* If we get here, then we exhausted the trajector without finding */ + /* the desired transition, so set the position pointer to the end */ + /* of the trajector, and return FALSE. */ + *iptr = num; + return(FALSE); +} + +/************************************************************************* +************************************************************************** +#cat: validate_ridge_crossing - Takes a pair of points, a ridge start +#cat: transition and a ridge end transition, and walks the +#cat: ridge contour from thre ridge end points a specified +#cat: number of steps, looking for the ridge start point. +#cat: If found, then transitions determined not to be a valid +#cat: ridge crossing. + + Input: + ridge_start - index into line trajectory of ridge start transition + ridge_end - index into line trajectory of ridge end transition + xlist - x-pixel coords of line trajectory + ylist - y-pixel coords of line trajectory + num - number of coords in line trajectory + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + max_ridge_steps - number of steps taken in search in both + scan directions + Return Code: + TRUE - ridge crossing VALID + FALSE - ridge corssing INVALID + Negative - system error +**************************************************************************/ +static int validate_ridge_crossing(const int ridge_start, const int ridge_end, + const int *xlist, const int *ylist, const int num, + unsigned char *bdata, const int iw, const int ih, + const int max_ridge_steps) +{ + int ret; + int feat_x, feat_y, edge_x, edge_y; + int *contour_x, *contour_y, *contour_ex, *contour_ey, ncontour; + + /* Assign edge pixel pair for contour trace. */ + feat_x = xlist[ridge_end]; + feat_y = ylist[ridge_end]; + edge_x = xlist[ridge_end-1]; + edge_y = ylist[ridge_end-1]; + + /* Adjust pixel pair if they neighbor each other diagonally. */ + fix_edge_pixel_pair(&feat_x, &feat_y, &edge_x, &edge_y, + bdata, iw, ih); + + /* Trace ridge contour, starting at the ridge end transition, and */ + /* taking a specified number of step scanning for edge neighbors */ + /* clockwise. As we trace the ridge, we want to detect if we */ + /* encounter the ridge start transition. NOTE: The ridge end */ + /* position is on the white (of a black to white transition) and */ + /* the ridge start is on the black (of a black to white trans), */ + /* so the edge trace needs to look for the what pixel (not the */ + /* black one) of the ridge start transition. */ + ret = trace_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, + max_ridge_steps, + xlist[ridge_start-1], ylist[ridge_start-1], + feat_x, feat_y, edge_x, edge_y, + SCAN_CLOCKWISE, bdata, iw, ih); + /* If a system error occurred ... */ + if(ret < 0) + /* Return error code. */ + return(ret); + + /* Otherwise, if the trace was not IGNORED, then a contour was */ + /* was generated and returned. We aren't interested in the */ + /* actual contour, so deallocate it. */ + if(ret != IGNORE) + free_contour(contour_x, contour_y, contour_ex, contour_ey); + + /* If the trace was IGNORED, then we had some sort of initialization */ + /* problem, so treat this the same as if was actually located the */ + /* ridge start point (in which case LOOP_FOUND is returned). */ + /* So, If not IGNORED and ridge start not encounted in trace ... */ + if((ret != IGNORE) && + (ret != LOOP_FOUND)){ + + /* Now conduct contour trace scanning for edge neighbors counter- */ + /* clockwise. */ + ret = trace_contour(&contour_x, &contour_y, + &contour_ex, &contour_ey, &ncontour, + max_ridge_steps, + xlist[ridge_start-1], ylist[ridge_start-1], + feat_x, feat_y, edge_x, edge_y, + SCAN_COUNTER_CLOCKWISE, bdata, iw, ih); + /* If a system error occurred ... */ + if(ret < 0) + /* Return error code. */ + return(ret); + + /* Otherwise, if the trace was not IGNORED, then a contour was */ + /* was generated and returned. We aren't interested in the */ + /* actual contour, so deallocate it. */ + if(ret != IGNORE) + free_contour(contour_x, contour_y, contour_ex, contour_ey); + + /* If trace not IGNORED and ridge start not encounted in 2nd trace ... */ + if((ret != IGNORE) && + (ret != LOOP_FOUND)){ + /* If we get here, assume we have a ridge crossing. */ + return(TRUE); + } + /* Otherwise, second trace returned IGNORE or ridge start found. */ + } + /* Otherwise, first trace returned IGNORE or ridge start found. */ + + /* If we get here, then we failed to validate a ridge crossing. */ + return(FALSE); +} + /************************************************************************* ************************************************************************** #cat: ridge_count - Takes a pair of minutiae, and counts the number of @@ -523,7 +558,7 @@ int sort_neighbors(int *nbr_list, const int nnbrs, const int first, Zero or Positive - number of ridges counted Negative - system error **************************************************************************/ -int ridge_count(const int first, const int second, MINUTIAE *minutiae, +static int ridge_count(const int first, const int second, MINUTIAE *minutiae, unsigned char *bdata, const int iw, const int ih, const LFSPARMS *lfsparms) { @@ -664,168 +699,134 @@ int ridge_count(const int first, const int second, MINUTIAE *minutiae, /************************************************************************* ************************************************************************** -#cat: find_transition - Takes a pixel trajectory and a starting index, and -#cat: searches forward along the trajectory until the specified -#cat: adjacent pixel pair is found, returning the index where -#cat: the pair was found (the index of the second pixel). +#cat: count_minutia_ridges - Takes a minutia, and determines its closest +#cat: neighbors and counts the number of interveining ridges +#cat: between the minutia point and each of its neighbors. Input: - iptr - pointer to starting pixel index into trajectory - pix1 - first pixel value in transition pair - pix2 - second pixel value in transition pair - xlist - x-pixel coords of line trajectory - ylist - y-pixel coords of line trajectory - num - number of coords in line trajectory - bdata - binary image data (0==while & 1==black) - iw - width (in pixels) of image - ih - height (in pixels) of image + minutia - input minutia + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + lfsparms - parameters and thresholds for controlling LFS Output: - iptr - points to location where 2nd pixel in pair is found + minutiae - minutia augmented with neighbors and ridge counts Return Code: - TRUE - pixel pair transition found - FALSE - pixel pair transition not found + Zero - successful completion + Negative - system error **************************************************************************/ -int find_transition(int *iptr, const int pix1, const int pix2, - const int *xlist, const int *ylist, const int num, - unsigned char *bdata, const int iw, const int ih) +static int count_minutia_ridges(const int first, MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + const LFSPARMS *lfsparms) { - int i, j; + int i, ret, *nbr_list, *nbr_nridges, nnbrs; - /* Set previous index to starting position. */ - i = *iptr; - /* Bump previous index by 1 to get next index. */ - j = i+1; - - /* While not one point from the end of the trajectory .. */ - while(i < num-1){ - /* If we have found the desired transition ... */ - if((*(bdata+(ylist[i]*iw)+xlist[i]) == pix1) && - (*(bdata+(ylist[j]*iw)+xlist[j]) == pix2)){ - /* Adjust the position pointer to the location of the */ - /* second pixel in the transition. */ - *iptr = j; - - /* Return TRUE. */ - return(TRUE); - } - /* Otherwise, the desired transition was not found in current */ - /* pixel pair, so bump to the next pair along the trajector. */ - i++; - j++; + /* Find up to the maximum number of qualifying neighbors. */ + if((ret = find_neighbors(&nbr_list, &nnbrs, lfsparms->max_nbrs, + first, minutiae))){ + free(nbr_list); + return(ret); } - /* If we get here, then we exhausted the trajector without finding */ - /* the desired transition, so set the position pointer to the end */ - /* of the trajector, and return FALSE. */ - *iptr = num; - return(FALSE); + print2log("NBRS FOUND: %d,%d = %d\n", minutiae->list[first]->x, + minutiae->list[first]->y, nnbrs); + + /* If no neighors found ... */ + if(nnbrs == 0){ + /* Then no list returned and no ridges to count. */ + return(0); + } + + /* Sort neighbors on delta dirs. */ + if((ret = sort_neighbors(nbr_list, nnbrs, first, minutiae))){ + free(nbr_list); + return(ret); + } + + /* Count ridges between first and neighbors. */ + /* List of ridge counts, one for each neighbor stored. */ + nbr_nridges = (int *)malloc(nnbrs * sizeof(int)); + if(nbr_nridges == (int *)NULL){ + free(nbr_list); + fprintf(stderr, "ERROR : count_minutia_ridges : malloc : nbr_nridges\n"); + return(-450); + } + + /* Foreach neighbor found and sorted in list ... */ + for(i = 0; i < nnbrs; i++){ + /* Count the ridges between the primary minutia and the neighbor. */ + ret = ridge_count(first, nbr_list[i], minutiae, bdata, iw, ih, lfsparms); + /* If system error ... */ + if(ret < 0){ + /* Deallocate working memories. */ + free(nbr_list); + free(nbr_nridges); + /* Return error code. */ + return(ret); + } + + /* Otherwise, ridge count successful, so store ridge count to list. */ + nbr_nridges[i] = ret; + } + + /* Assign neighbor indices and ridge counts to primary minutia. */ + minutiae->list[first]->nbrs = nbr_list; + minutiae->list[first]->ridge_counts = nbr_nridges; + minutiae->list[first]->num_nbrs = nnbrs; + + /* Return normally. */ + return(0); } /************************************************************************* ************************************************************************** -#cat: validate_ridge_crossing - Takes a pair of points, a ridge start -#cat: transition and a ridge end transition, and walks the -#cat: ridge contour from thre ridge end points a specified -#cat: number of steps, looking for the ridge start point. -#cat: If found, then transitions determined not to be a valid -#cat: ridge crossing. +#cat: count_minutiae_ridges - Takes a list of minutiae, and for each one, +#cat: determines its closest neighbors and counts the number +#cat: of interveining ridges between the minutia point and +#cat: each of its neighbors. Input: - ridge_start - index into line trajectory of ridge start transition - ridge_end - index into line trajectory of ridge end transition - xlist - x-pixel coords of line trajectory - ylist - y-pixel coords of line trajectory - num - number of coords in line trajectory - bdata - binary image data (0==while & 1==black) - iw - width (in pixels) of image - ih - height (in pixels) of image - max_ridge_steps - number of steps taken in search in both - scan directions + minutiae - list of minutiae + bdata - binary image data (0==while & 1==black) + iw - width (in pixels) of image + ih - height (in pixels) of image + lfsparms - parameters and thresholds for controlling LFS + Output: + minutiae - list of minutiae augmented with neighbors and ridge counts Return Code: - TRUE - ridge crossing VALID - FALSE - ridge corssing INVALID - Negative - system error + Zero - successful completion + Negative - system error **************************************************************************/ -int validate_ridge_crossing(const int ridge_start, const int ridge_end, - const int *xlist, const int *ylist, const int num, - unsigned char *bdata, const int iw, const int ih, - const int max_ridge_steps) +int count_minutiae_ridges(MINUTIAE *minutiae, + unsigned char *bdata, const int iw, const int ih, + const LFSPARMS *lfsparms) { int ret; - int feat_x, feat_y, edge_x, edge_y; - int *contour_x, *contour_y, *contour_ex, *contour_ey, ncontour; + int i; - /* Assign edge pixel pair for contour trace. */ - feat_x = xlist[ridge_end]; - feat_y = ylist[ridge_end]; - edge_x = xlist[ridge_end-1]; - edge_y = ylist[ridge_end-1]; + print2log("\nFINDING NBRS AND COUNTING RIDGES:\n"); - /* Adjust pixel pair if they neighbor each other diagonally. */ - fix_edge_pixel_pair(&feat_x, &feat_y, &edge_x, &edge_y, - bdata, iw, ih); - - /* Trace ridge contour, starting at the ridge end transition, and */ - /* taking a specified number of step scanning for edge neighbors */ - /* clockwise. As we trace the ridge, we want to detect if we */ - /* encounter the ridge start transition. NOTE: The ridge end */ - /* position is on the white (of a black to white transition) and */ - /* the ridge start is on the black (of a black to white trans), */ - /* so the edge trace needs to look for the what pixel (not the */ - /* black one) of the ridge start transition. */ - ret = trace_contour(&contour_x, &contour_y, - &contour_ex, &contour_ey, &ncontour, - max_ridge_steps, - xlist[ridge_start-1], ylist[ridge_start-1], - feat_x, feat_y, edge_x, edge_y, - SCAN_CLOCKWISE, bdata, iw, ih); - /* If a system error occurred ... */ - if(ret < 0) - /* Return error code. */ + /* Sort minutia points on x then y (column-oriented). */ + if((ret = sort_minutiae_x_y(minutiae, iw, ih))){ return(ret); - - /* Otherwise, if the trace was not IGNORED, then a contour was */ - /* was generated and returned. We aren't interested in the */ - /* actual contour, so deallocate it. */ - if(ret != IGNORE) - free_contour(contour_x, contour_y, contour_ex, contour_ey); - - /* If the trace was IGNORED, then we had some sort of initialization */ - /* problem, so treat this the same as if was actually located the */ - /* ridge start point (in which case LOOP_FOUND is returned). */ - /* So, If not IGNORED and ridge start not encounted in trace ... */ - if((ret != IGNORE) && - (ret != LOOP_FOUND)){ - - /* Now conduct contour trace scanning for edge neighbors counter- */ - /* clockwise. */ - ret = trace_contour(&contour_x, &contour_y, - &contour_ex, &contour_ey, &ncontour, - max_ridge_steps, - xlist[ridge_start-1], ylist[ridge_start-1], - feat_x, feat_y, edge_x, edge_y, - SCAN_COUNTER_CLOCKWISE, bdata, iw, ih); - /* If a system error occurred ... */ - if(ret < 0) - /* Return error code. */ - return(ret); - - /* Otherwise, if the trace was not IGNORED, then a contour was */ - /* was generated and returned. We aren't interested in the */ - /* actual contour, so deallocate it. */ - if(ret != IGNORE) - free_contour(contour_x, contour_y, contour_ex, contour_ey); - - /* If trace not IGNORED and ridge start not encounted in 2nd trace ... */ - if((ret != IGNORE) && - (ret != LOOP_FOUND)){ - /* If we get here, assume we have a ridge crossing. */ - return(TRUE); - } - /* Otherwise, second trace returned IGNORE or ridge start found. */ } - /* Otherwise, first trace returned IGNORE or ridge start found. */ - - /* If we get here, then we failed to validate a ridge crossing. */ - return(FALSE); + + /* Remove any duplicate minutia points from the list. */ + if((ret = rm_dup_minutiae(minutiae))){ + return(ret); + } + + /* Foreach remaining sorted minutia in list ... */ + for(i = 0; i < minutiae->num-1; i++){ + /* Located neighbors and count number of ridges in between. */ + /* NOTE: neighbor and ridge count results are stored in */ + /* minutiae->list[i]. */ + if((ret = count_minutia_ridges(i, minutiae, bdata, iw, ih, lfsparms))){ + return(ret); + } + } + + /* Return normally. */ + return(0); } + diff --git a/libfprint/nbis/mindtct/xytreps.c b/libfprint/nbis/mindtct/xytreps.c deleted file mode 100644 index 65621ea9..00000000 --- a/libfprint/nbis/mindtct/xytreps.c +++ /dev/null @@ -1,133 +0,0 @@ -/******************************************************************************* - -License: -This software was developed at the National Institute of Standards and -Technology (NIST) by employees of the Federal Government in the course -of their official duties. Pursuant to title 17 Section 105 of the -United States Code, this software is not subject to copyright protection -and is in the public domain. NIST assumes no responsibility whatsoever for -its use by other parties, and makes no guarantees, expressed or implied, -about its quality, reliability, or any other characteristic. - -Disclaimer: -This software was developed to promote biometric standards and biometric -technology testing for the Federal Government in accordance with the USA -PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. -Specific hardware and software products identified in this software were used -in order to perform the software development. In no case does such -identification imply recommendation or endorsement by the National Institute -of Standards and Technology, nor does it imply that the products and equipment -identified are necessarily the best available for the purpose. - -*******************************************************************************/ - -/*********************************************************************** - LIBRARY: LFS - NIST Latent Fingerprint System - - FILE: XYTREPS.C - AUTHOR: Michael D. Garris - DATE: 09/16/2004 - - Contains routines useful in converting minutiae in LFS "native" - representation into other representations, such as - M1 (ANSI INCITS 378-2004) & NIST internal representations. - -*********************************************************************** - ROUTINES: - lfs2nist_minutia_XTY() - lfs2m1_minutia_XTY() - -***********************************************************************/ - -#include -#include - -/************************************************************************* -************************************************************************** -#cat: lfs2nist_minutia_XYT - Converts XYT minutiae attributes in LFS native -#cat: representation to NIST internal representation - - Input: - minutia - LFS minutia structure containing attributes to be converted - Output: - ox - NIST internal based x-pixel coordinate - oy - NIST internal based y-pixel coordinate - ot - NIST internal based minutia direction/orientation - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -void lfs2nist_minutia_XYT(int *ox, int *oy, int *ot, - const MINUTIA *minutia, const int iw, const int ih) -{ - int x, y, t; - float degrees_per_unit; - - /* XYT's according to NIST internal rep: */ - /* 1. pixel coordinates with origin bottom-left */ - /* 2. orientation in degrees on range [0..360] */ - /* with 0 pointing east and increasing counter */ - /* clockwise (same as M1) */ - /* 3. direction pointing out and away from the */ - /* ridge ending or bifurcation valley */ - /* (opposite direction from M1) */ - - x = minutia->x; - y = ih - minutia->y; - - degrees_per_unit = 180 / (float)NUM_DIRECTIONS; - - t = (270 - sround(minutia->direction * degrees_per_unit)) % 360; - if(t < 0){ - t += 360; - } - - *ox = x; - *oy = y; - *ot = t; -} - -/************************************************************************* -************************************************************************** -#cat: lfs2m1_minutia_XYT - Converts XYT minutiae attributes in LFS native -#cat: representation to M1 (ANSI INCITS 378-2004) representation - - Input: - minutia - LFS minutia structure containing attributes to be converted - Output: - ox - M1 based x-pixel coordinate - oy - M1 based y-pixel coordinate - ot - M1 based minutia direction/orientation - Return Code: - Zero - successful completion - Negative - system error -**************************************************************************/ -void lfs2m1_minutia_XYT(int *ox, int *oy, int *ot, const MINUTIA *minutia) -{ - int x, y, t; - float degrees_per_unit; - - /* XYT's according to M1 (ANSI INCITS 378-2004): */ - /* 1. pixel coordinates with origin top-left */ - /* 2. orientation in degrees on range [0..179] */ - /* with 0 pointing east and increasing counter */ - /* clockwise */ - /* 3. direction pointing up the ridge ending or */ - /* bifurcaiton valley */ - - x = minutia->x; - y = minutia->y; - - degrees_per_unit = 180 / (float)NUM_DIRECTIONS; - t = (90 - sround(minutia->direction * degrees_per_unit)) % 360; - if(t < 0){ - t += 360; - } - - /* range of theta is 0..179 because angles are in units of 2 degress */ - t = t / 2; - - *ox = x; - *oy = y; - *ot = t; -} From cc3e976042e49587ecca87a7fdb3d6dbdcf76d0e Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Tue, 30 Oct 2007 22:15:45 +0000 Subject: [PATCH 042/184] Add 'discover' hook for drivers Drivers can now offer a discover function, and are expected to offer the device devtype during discovery, without accessing the USB device. Hmm. Maybe we'll have to change that later... --- libfprint/core.c | 36 ++++++++++++++++++++++++++++-------- libfprint/fp_internal.h | 2 ++ 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/libfprint/core.c b/libfprint/core.c index 40d956fd..c8548945 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -121,6 +121,32 @@ static struct fp_driver *find_supporting_driver(struct usb_device *udev, return NULL; } +static struct fp_dscv_dev *discover_dev(struct usb_device *udev) +{ + struct usb_id *usb_id; + struct fp_driver *drv = find_supporting_driver(udev, &usb_id); + struct fp_dscv_dev *ddev; + uint32_t devtype = 0; + + if (!drv) + return NULL; + + if (drv->discover) { + int r = drv->discover(usb_id, &devtype); + if (r < 0) + fp_err("%s discover failed, code %d", drv->name, r); + if (r <= 0) + return NULL; + } + + ddev = g_malloc0(sizeof(*ddev)); + ddev->drv = drv; + ddev->udev = udev; + ddev->driver_data = usb_id->driver_data; + ddev->devtype = devtype; + return ddev; +} + API_EXPORTED struct fp_dscv_dev **fp_discover_devs(void) { GList *tmplist = NULL; @@ -142,15 +168,9 @@ API_EXPORTED struct fp_dscv_dev **fp_discover_devs(void) * sets of drivers against small sets of USB devices */ for (bus = usb_get_busses(); bus; bus = bus->next) for (udev = bus->devices; udev; udev = udev->next) { - unsigned long driver_data; - struct fp_driver *drv = find_supporting_driver(udev, &driver_data); - struct fp_dscv_dev *ddev; - if (!drv) + struct fp_dscv_dev *ddev = discover_dev(udev); + if (!ddev) continue; - ddev = g_malloc0(sizeof(*ddev)); - ddev->drv = drv; - ddev->udev = udev; - ddev->driver_data = driver_data; tmplist = g_list_prepend(tmplist, (gpointer) ddev); dscv_count++; } diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index f6e7d304..b41841bd 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -103,6 +103,7 @@ struct fp_driver { void *priv; /* Device operations */ + int (*discover)(struct usb_id *usb_id, uint32_t *devtype); int (*init)(struct fp_dev *dev, unsigned long driver_data); void (*exit)(struct fp_dev *dev); int (*enroll)(struct fp_dev *dev, gboolean initial, int stage, @@ -141,6 +142,7 @@ struct fp_dscv_dev { struct usb_device *udev; struct fp_driver *drv; unsigned long driver_data; + uint32_t devtype; }; enum fp_print_data_type { From b96aade69ca93c28ed20bdac8be432d4feb0f9fd Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Tue, 30 Oct 2007 22:24:31 +0000 Subject: [PATCH 043/184] Flesh out driver_id/devtype API Add accessor functions to the various structures --- libfprint/core.c | 15 +++++++++++++++ libfprint/data.c | 9 +++++++++ libfprint/fprint.h | 10 ++++++++++ 3 files changed, 34 insertions(+) diff --git a/libfprint/core.c b/libfprint/core.c index c8548945..ce64aaa0 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -207,6 +207,11 @@ API_EXPORTED struct fp_driver *fp_dscv_dev_get_driver(struct fp_dscv_dev *dev) return dev->drv; } +API_EXPORTED uint32_t fp_dscv_dev_get_devtype(struct fp_dscv_dev *dev) +{ + return dev->devtype; +} + API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) { struct fp_dev *dev; @@ -257,6 +262,11 @@ API_EXPORTED int fp_dev_get_nr_enroll_stages(struct fp_dev *dev) return dev->nr_enroll_stages; } +API_EXPORTED uint32_t fp_dev_get_devtype(struct fp_dev *dev) +{ + return dev->devtype; +} + API_EXPORTED const char *fp_driver_get_name(struct fp_driver *drv) { return drv->name; @@ -267,6 +277,11 @@ API_EXPORTED const char *fp_driver_get_full_name(struct fp_driver *drv) return drv->full_name; } +API_EXPORTED uint16_t fp_driver_get_driver_id(struct fp_driver *drv) +{ + return drv->id; +} + API_EXPORTED struct fp_img_dev *fp_dev_to_img_dev(struct fp_dev *dev) { if (dev->drv->type != DRIVER_IMAGING) diff --git a/libfprint/data.c b/libfprint/data.c index 4bd6e91b..f958b5a8 100644 --- a/libfprint/data.c +++ b/libfprint/data.c @@ -306,3 +306,12 @@ API_EXPORTED void fp_print_data_free(struct fp_print_data *data) g_free(data); } +API_EXPORTED uint16_t fp_print_data_get_driver_id(struct fp_print_data *data) +{ + return data->driver_id; +} + +API_EXPORTED uint32_t fp_print_data_get_devtype(struct fp_print_data *data) +{ + return data->devtype; +} diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 15ea3654..778b9802 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -45,6 +45,12 @@ enum fp_finger { struct fp_dscv_dev **fp_discover_devs(void); void fp_dscv_devs_free(struct fp_dscv_dev **devs); struct fp_driver *fp_dscv_dev_get_driver(struct fp_dscv_dev *dev); +uint32_t fp_dscv_dev_get_devtype(struct fp_dscv_dev *dev); + +static inline uint16_t fp_dscv_dev_get_driver_id(struct fp_dscv_dev *dev) +{ + return fp_driver_get_driver_id(fp_dscv_dev_get_driver(dev)); +} /* Device handling */ struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev); @@ -52,10 +58,12 @@ void fp_dev_close(struct fp_dev *dev); struct fp_driver *fp_dev_get_driver(struct fp_dev *dev); int fp_dev_get_nr_enroll_stages(struct fp_dev *dev); struct fp_img_dev *fp_dev_to_img_dev(struct fp_dev *dev); +uint32_t fp_dev_get_devtype(struct fp_dev *dev); /* Drivers */ const char *fp_driver_get_name(struct fp_driver *drv); const char *fp_driver_get_full_name(struct fp_driver *drv); +uint16_t fp_driver_get_driver_id(struct fp_driver *drv); /* Enrollment */ enum fp_enroll_result { @@ -90,6 +98,8 @@ void fp_print_data_free(struct fp_print_data *data); size_t fp_print_data_get_data(struct fp_print_data *data, unsigned char **ret); struct fp_print_data *fp_print_data_from_data(unsigned char *buf, size_t buflen); +uint16_t fp_print_data_get_driver_id(struct fp_print_data *data); +uint32_t fp_print_data_get_devtype(struct fp_print_data *data); /* Imaging devices */ int fp_imgdev_capture(struct fp_img_dev *imgdev, int unconditional, From 447b1f01b3163bebf640f2f44d09a7fbf0c4e79c Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Wed, 31 Oct 2007 13:12:04 +0000 Subject: [PATCH 044/184] Print discovery Add concept of "discovered prints" and flesh out the API. A discovered print was found based on file name but has not been checked for file integrity, and of course there is no guarantee that it is usable when you try to use it later (might have been deleted, etc). The .fprint directory structure was changed - instead of using mnemonics like "rind" we use their numeric value in the fp_finger enum as the filename. --- libfprint/core.c | 75 +++++++++- libfprint/data.c | 325 ++++++++++++++++++++++++++++++---------- libfprint/fp_internal.h | 16 +- libfprint/fprint.h | 32 +++- 4 files changed, 353 insertions(+), 95 deletions(-) diff --git a/libfprint/core.c b/libfprint/core.c index ce64aaa0..7bc13f87 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -101,7 +101,7 @@ static void register_drivers(void) } static struct fp_driver *find_supporting_driver(struct usb_device *udev, - unsigned long *driver_data) + const struct usb_id **usb_id) { GList *elem = registered_drivers; @@ -114,7 +114,7 @@ static struct fp_driver *find_supporting_driver(struct usb_device *udev, udev->descriptor.idProduct == id->product) { fp_dbg("driver %s supports USB device %04x:%04x", drv->name, id->vendor, id->product); - *driver_data = id->driver_data; + *usb_id = id; return drv; } } while (elem = g_list_next(elem)); @@ -123,7 +123,7 @@ static struct fp_driver *find_supporting_driver(struct usb_device *udev, static struct fp_dscv_dev *discover_dev(struct usb_device *udev) { - struct usb_id *usb_id; + const struct usb_id *usb_id; struct fp_driver *drv = find_supporting_driver(udev, &usb_id); struct fp_dscv_dev *ddev; uint32_t devtype = 0; @@ -212,6 +212,58 @@ API_EXPORTED uint32_t fp_dscv_dev_get_devtype(struct fp_dscv_dev *dev) return dev->devtype; } +enum fp_print_data_type fpi_driver_get_data_type(struct fp_driver *drv) +{ + switch (drv->type) { + case DRIVER_PRIMITIVE: + return PRINT_DATA_RAW; + case DRIVER_IMAGING: + return PRINT_DATA_NBIS_MINUTIAE; + default: + fp_err("unrecognised drv type %d", drv->type); + return PRINT_DATA_RAW; + } +} + +API_EXPORTED int fp_dscv_dev_supports_print_data(struct fp_dscv_dev *dev, + struct fp_print_data *data) +{ + return fpi_print_data_compatible(dev->drv->id, dev->devtype, + fpi_driver_get_data_type(dev->drv), data->driver_id, data->devtype, + data->type); +} + +API_EXPORTED int fp_dscv_dev_supports_dscv_print(struct fp_dscv_dev *dev, + struct fp_dscv_print *data) +{ + return fpi_print_data_compatible(dev->drv->id, dev->devtype, 0, + data->driver_id, data->devtype, 0); +} + +API_EXPORTED struct fp_dscv_dev *fp_dscv_dev_for_print_data(struct fp_dscv_dev **devs, + struct fp_print_data *data) +{ + struct fp_dscv_dev *ddev; + int i; + + for (i = 0; ddev = devs[i]; i++) + if (fp_dscv_dev_supports_print_data(ddev, data)) + return ddev; + return NULL; +} + +API_EXPORTED struct fp_dscv_dev *fp_dscv_dev_for_dscv_print(struct fp_dscv_dev **devs, + struct fp_dscv_print *print) +{ + struct fp_dscv_dev *ddev; + int i; + + for (i = 0; ddev = devs[i]; i++) + if (fp_dscv_dev_supports_dscv_print(ddev, print)) + return ddev; + return NULL; +} + API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) { struct fp_dev *dev; @@ -267,6 +319,21 @@ API_EXPORTED uint32_t fp_dev_get_devtype(struct fp_dev *dev) return dev->devtype; } +API_EXPORTED int fp_dev_supports_print_data(struct fp_dev *dev, + struct fp_print_data *data) +{ + return fpi_print_data_compatible(dev->drv->id, dev->devtype, + fpi_driver_get_data_type(dev->drv), data->driver_id, data->devtype, + data->type); +} + +API_EXPORTED int fp_dev_supports_dscv_print(struct fp_dev *dev, + struct fp_dscv_print *data) +{ + return fpi_print_data_compatible(dev->drv->id, dev->devtype, + 0, data->driver_id, data->devtype, 0); +} + API_EXPORTED const char *fp_driver_get_name(struct fp_driver *drv) { return drv->name; @@ -372,7 +439,7 @@ API_EXPORTED int fp_verify_finger(struct fp_dev *dev, return -EINVAL; } - if (!fpi_print_data_compatible(enrolled_print, dev)) { + if (!fp_dev_supports_print_data(dev, enrolled_print)) { fp_err("print is not compatible with device"); return -EINVAL; } diff --git a/libfprint/data.c b/libfprint/data.c index f958b5a8..fb380fcc 100644 --- a/libfprint/data.c +++ b/libfprint/data.c @@ -48,38 +48,29 @@ static void storage_setup(void) /* FIXME handle failure */ } -static const char *finger_code_to_str(enum fp_finger finger) +#define FP_FINGER_IS_VALID(finger) \ + ((finger) >= LEFT_THUMB && (finger) <= RIGHT_LITTLE) + +/* for debug messages only */ +static const char *finger_num_to_str(enum fp_finger finger) { const char *names[] = { - [LEFT_THUMB] = "lthu", - [LEFT_INDEX] = "lind", - [LEFT_MIDDLE] = "lmid", - [LEFT_RING] = "lrin", - [LEFT_LITTLE] = "llit", - [RIGHT_THUMB] = "rthu", - [RIGHT_INDEX] = "rind", - [RIGHT_MIDDLE] = "rmid", - [RIGHT_RING] = "rrin", - [RIGHT_LITTLE] = "rlit", + [LEFT_THUMB] = "left thumb", + [LEFT_INDEX] = "left index", + [LEFT_MIDDLE] = "left middle", + [LEFT_RING] = "left ring", + [LEFT_LITTLE] = "left little", + [RIGHT_THUMB] = "right thumb", + [RIGHT_INDEX] = "right index", + [RIGHT_MIDDLE] = "right middle", + [RIGHT_RING] = "right ring", + [RIGHT_LITTLE] = "right little", }; - if (finger < LEFT_THUMB || finger > RIGHT_LITTLE) - return NULL; + if (!FP_FINGER_IS_VALID(finger)) + return "UNKNOWN"; return names[finger]; } -static enum fp_print_data_type get_data_type_for_dev(struct fp_dev *dev) -{ - switch (dev->drv->type) { - case DRIVER_PRIMITIVE: - return PRINT_DATA_RAW; - case DRIVER_IMAGING: - return PRINT_DATA_NBIS_MINUTIAE; - default: - fp_err("unrecognised drv type %d", dev->drv->type); - return PRINT_DATA_RAW; - } -} - static struct fp_print_data *print_data_new(uint16_t driver_id, uint32_t devtype, enum fp_print_data_type type, size_t length) { @@ -98,7 +89,7 @@ struct fp_print_data *fpi_print_data_new(struct fp_dev *dev, size_t length) struct fp_print_data *data = g_malloc(sizeof(*data) + length); memset(data, 0, sizeof(*data)); return print_data_new(dev->drv->id, dev->devtype, - get_data_type_for_dev(dev), length); + fpi_driver_get_data_type(dev->drv), length); } API_EXPORTED size_t fp_print_data_get_data(struct fp_print_data *data, @@ -148,7 +139,7 @@ API_EXPORTED struct fp_print_data *fp_print_data_from_data(unsigned char *buf, return data; } -static char *__get_path_to_storedir(uint16_t driver_id, uint32_t devtype) +static char *get_path_to_storedir(uint16_t driver_id, uint32_t devtype) { char idstr[5]; char devtypestr[9]; @@ -159,53 +150,55 @@ static char *__get_path_to_storedir(uint16_t driver_id, uint32_t devtype) return g_build_filename(base_store, idstr, devtypestr, NULL); } -static char *get_path_to_storedir(struct fp_dev *dev) -{ - return __get_path_to_storedir(dev->drv->id, dev->devtype); -} - -static char *get_path_to_print(struct fp_dev *dev, const char *fingerstr) +static char *__get_path_to_print(uint16_t driver_id, uint32_t devtype, + enum fp_finger finger) { char *dirpath; char *path; + char fingername[2]; - dirpath = get_path_to_storedir(dev); - path = g_build_filename(dirpath, fingerstr, NULL); + g_snprintf(fingername, 2, "%x", finger); + + dirpath = get_path_to_storedir(driver_id, devtype); + path = g_build_filename(dirpath, fingername, NULL); g_free(dirpath); return path; } +static char *get_path_to_print(struct fp_dev *dev, enum fp_finger finger) +{ + return __get_path_to_print(dev->drv->id, dev->devtype, finger); +} + API_EXPORTED int fp_print_data_save(struct fp_print_data *data, enum fp_finger finger) { GError *err = NULL; char *path; char *dirpath; - const char *fingerstr = finger_code_to_str(finger); unsigned char *buf; size_t len; int r; - if (!fingerstr) - return -EINVAL; - if (!base_store) storage_setup(); - fp_dbg("save %s print from driver %04x", fingerstr, data->driver_id); + fp_dbg("save %s print from driver %04x", finger_num_to_str(finger), + data->driver_id); len = fp_print_data_get_data(data, &buf); if (!len) return -ENOMEM; - dirpath = __get_path_to_storedir(data->driver_id, data->devtype); + path = __get_path_to_print(data->driver_id, data->devtype, finger); + dirpath = g_path_get_dirname(path); r = g_mkdir_with_parents(dirpath, DIR_PERMS); if (r < 0) { fp_err("couldn't create storage directory"); + g_free(path); g_free(dirpath); return r; } - path = g_build_filename(dirpath, fingerstr, NULL); fp_dbg("saving to %s", path); g_file_set_contents(path, buf, len, &err); free(buf); @@ -213,7 +206,7 @@ API_EXPORTED int fp_print_data_save(struct fp_print_data *data, g_free(path); if (err) { r = err->code; - fp_err("%s save failed: %s", fingerstr, err->message); + fp_err("save failed: %s", err->message); g_error_free(err); /* FIXME interpret error codes */ return r; @@ -222,65 +215,39 @@ API_EXPORTED int fp_print_data_save(struct fp_print_data *data, return 0; } -gboolean fpi_print_data_compatible(struct fp_print_data *data, - struct fp_dev *dev) +gboolean fpi_print_data_compatible(uint16_t driver_id1, uint32_t devtype1, + enum fp_print_data_type type1, uint16_t driver_id2, uint32_t devtype2, + enum fp_print_data_type type2) { - struct fp_driver *drv = dev->drv; - - if (drv->id != data->driver_id) { - fp_dbg("driver name mismatch: %02x vs %02x", drv->id, data->driver_id); + if (driver_id1 != driver_id2) { + fp_dbg("driver ID mismatch: %02x vs %02x", driver_id1, driver_id2); return FALSE; } - if (dev->devtype != data->devtype) { - fp_dbg("devtype mismatch: %04x vs %04x", dev->devtype, data->devtype); + if (devtype1 != devtype2) { + fp_dbg("devtype mismatch: %04x vs %04x", devtype1, devtype2); return FALSE; } - switch (data->type) { - case PRINT_DATA_RAW: - if (drv->type != DRIVER_PRIMITIVE) { - fp_dbg("raw data vs primitive driver mismatch"); - return FALSE; - } - break; - case PRINT_DATA_NBIS_MINUTIAE: - if (drv->type != DRIVER_IMAGING) { - fp_dbg("minutiae data vs imaging driver mismatch"); - return FALSE; - } - break; - default: - fp_err("unrecognised data type %d", data->type); + if (type1 != type2) { + fp_dbg("type mismatch: %d vs %d", type1, type2); return FALSE; } return TRUE; } -API_EXPORTED int fp_print_data_load(struct fp_dev *dev, - enum fp_finger finger, struct fp_print_data **data) +static int load_from_file(char *path, struct fp_print_data **data) { - const char *fingerstr = finger_code_to_str(finger); - gchar *path; gsize length; gchar *contents; GError *err = NULL; - struct fp_print_data *fdata; - if (!fingerstr) - return -EINVAL; - - if (!base_store) - storage_setup(); - - path = get_path_to_print(dev, fingerstr); fp_dbg("from %s", path); g_file_get_contents(path, &contents, &length, &err); - g_free(path); if (err) { int r = err->code; - fp_err("%s load failed: %s", fingerstr, err->message); + fp_err("%s load failed: %s", path, err->message); g_error_free(err); /* FIXME interpret more error codes */ if (r == G_FILE_ERROR_NOENT) @@ -289,11 +256,30 @@ API_EXPORTED int fp_print_data_load(struct fp_dev *dev, return r; } - fdata = fp_print_data_from_data(contents, length); + *data = fp_print_data_from_data(contents, length); g_free(contents); + return 0; +} - if (!fpi_print_data_compatible(fdata, dev)) { +API_EXPORTED int fp_print_data_load(struct fp_dev *dev, + enum fp_finger finger, struct fp_print_data **data) +{ + gchar *path; + struct fp_print_data *fdata; + int r; + + if (!base_store) + storage_setup(); + + path = get_path_to_print(dev, finger); + r = load_from_file(path, &fdata); + g_free(path); + if (r) + return r; + + if (!fp_dev_supports_print_data(dev, fdata)) { fp_err("print data is not compatible!"); + fp_print_data_free(fdata); return -EINVAL; } @@ -301,6 +287,12 @@ API_EXPORTED int fp_print_data_load(struct fp_dev *dev, return 0; } +API_EXPORTED int fp_print_data_from_dscv_print(struct fp_dscv_print *print, + struct fp_print_data **data) +{ + return load_from_file(print->path, data); +} + API_EXPORTED void fp_print_data_free(struct fp_print_data *data) { g_free(data); @@ -315,3 +307,170 @@ API_EXPORTED uint32_t fp_print_data_get_devtype(struct fp_print_data *data) { return data->devtype; } + +static GSList *scan_dev_store_dir(char *devpath, uint16_t driver_id, + uint32_t devtype, GSList *list) +{ + GError *err = NULL; + const gchar *ent; + struct fp_dscv_print *print; + + GDir *dir = g_dir_open(devpath, 0, &err); + if (!dir) { + fp_err("opendir %s failed: %s", devpath, err->message); + g_error_free(err); + return list; + } + + while (ent = g_dir_read_name(dir)) { + /* ent is an 1 hex character fp_finger code */ + guint64 val; + enum fp_finger finger; + gchar *endptr; + + if (*ent == 0 || strlen(ent) != 1) + continue; + + val = g_ascii_strtoull(ent, &endptr, 16); + if (endptr == ent || !FP_FINGER_IS_VALID(val)) { + fp_dbg("skipping print file %s", ent); + continue; + } + + finger = (enum fp_finger) val; + print = g_malloc(sizeof(*print)); + print->driver_id = driver_id; + print->devtype = devtype; + print->path = g_build_filename(devpath, ent, NULL); + print->finger = finger; + list = g_slist_prepend(list, print); + } + + g_dir_close(dir); + return list; +} + +static GSList *scan_driver_store_dir(char *drvpath, uint16_t driver_id, + GSList *list) +{ + GError *err = NULL; + const gchar *ent; + + GDir *dir = g_dir_open(drvpath, 0, &err); + if (!dir) { + fp_err("opendir %s failed: %s", drvpath, err->message); + g_error_free(err); + return list; + } + + while (ent = g_dir_read_name(dir)) { + /* ent is an 8 hex character devtype */ + guint64 val; + uint32_t devtype; + gchar *endptr; + gchar *path; + + if (*ent == 0 || strlen(ent) != 8) + continue; + + val = g_ascii_strtoull(ent, &endptr, 16); + if (endptr == ent) { + fp_dbg("skipping devtype %s", ent); + continue; + } + + devtype = (uint32_t) val; + path = g_build_filename(drvpath, ent, NULL); + list = scan_dev_store_dir(path, driver_id, devtype, list); + g_free(path); + } + + g_dir_close(dir); + return list; +} + +API_EXPORTED struct fp_dscv_print **fp_discover_prints(void) +{ + GDir *dir; + const gchar *ent; + GError *err = NULL; + GSList *tmplist = NULL; + GSList *elem; + unsigned int tmplist_len; + struct fp_dscv_print **list; + unsigned int i; + + if (!base_store) + storage_setup(); + + dir = g_dir_open(base_store, 0, &err); + if (!dir) { + fp_err("opendir %s failed: %s", base_store, err->message); + g_error_free(err); + return NULL; + } + + while (ent = g_dir_read_name(dir)) { + /* ent is a 4 hex digit driver_id */ + gchar *endptr; + gchar *path; + guint64 val; + uint16_t driver_id; + + if (*ent == 0 || strlen(ent) != 4) + continue; + + val = g_ascii_strtoull(ent, &endptr, 16); + if (endptr == ent) { + fp_dbg("skipping drv id %s", ent); + continue; + } + + driver_id = (uint16_t) val; + path = g_build_filename(base_store, ent, NULL); + tmplist = scan_driver_store_dir(path, driver_id, tmplist); + g_free(path); + } + + g_dir_close(dir); + tmplist_len = g_slist_length(tmplist); + list = g_malloc(sizeof(*list) * (tmplist_len + 1)); + elem = tmplist; + for (i = 0; i < tmplist_len; i++, elem = g_slist_next(elem)) + list[i] = elem->data; + list[tmplist_len] = NULL; /* NULL-terminate */ + + g_slist_free(tmplist); + return list; +} + +API_EXPORTED void fp_dscv_prints_free(struct fp_dscv_print **prints) +{ + int i; + struct fp_dscv_print *print; + + if (!prints) + return; + + for (i = 0; print = prints[i]; i++) { + if (print) + g_free(print->path); + g_free(print); + } + g_free(prints); +} + +API_EXPORTED uint16_t fp_dscv_print_get_driver_id(struct fp_dscv_print *print) +{ + return print->driver_id; +} + +API_EXPORTED uint32_t fp_dscv_print_get_devtype(struct fp_dscv_print *print) +{ + return print->devtype; +} + +API_EXPORTED enum fp_finger fp_dscv_print_get_finger(struct fp_dscv_print *print) +{ + return print->finger; +} diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index b41841bd..39b3204c 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -103,7 +103,7 @@ struct fp_driver { void *priv; /* Device operations */ - int (*discover)(struct usb_id *usb_id, uint32_t *devtype); + int (*discover)(const struct usb_id *usb_id, uint32_t *devtype); int (*init)(struct fp_dev *dev, unsigned long driver_data); void (*exit)(struct fp_dev *dev); int (*enroll)(struct fp_dev *dev, gboolean initial, int stage, @@ -111,6 +111,8 @@ struct fp_driver { int (*verify)(struct fp_dev *dev, struct fp_print_data *data); }; +enum fp_print_data_type fpi_driver_get_data_type(struct fp_driver *drv); + /* flags for fp_img_driver.flags */ #define FP_IMGDRV_SUPPORTS_UNCONDITIONAL_CAPTURE (1 << 0) @@ -145,6 +147,13 @@ struct fp_dscv_dev { uint32_t devtype; }; +struct fp_dscv_print { + uint16_t driver_id; + uint32_t devtype; + enum fp_finger finger; + char *path; +}; + enum fp_print_data_type { PRINT_DATA_RAW = 0, /* memset-imposed default */ PRINT_DATA_NBIS_MINUTIAE, @@ -167,8 +176,9 @@ struct fpi_print_data_fp1 { } __attribute__((__packed__)); struct fp_print_data *fpi_print_data_new(struct fp_dev *dev, size_t length); -gboolean fpi_print_data_compatible(struct fp_print_data *data, - struct fp_dev *dev); +gboolean fpi_print_data_compatible(uint16_t driver_id1, uint32_t devtype1, + enum fp_print_data_type type1, uint16_t driver_id2, uint32_t devtype2, + enum fp_print_data_type type2); /* bit values for fp_img.flags */ #define FP_IMG_V_FLIPPED (1<<0) diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 778b9802..1f2e2e80 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -20,8 +20,11 @@ #ifndef __FPRINT_H__ #define __FPRINT_H__ +#include + /* structs that applications are not allowed to peek into */ struct fp_dscv_dev; +struct fp_dscv_print; struct fp_dev; struct fp_driver; struct fp_print_data; @@ -41,17 +44,37 @@ enum fp_finger { RIGHT_LITTLE, }; +/* Drivers */ +const char *fp_driver_get_name(struct fp_driver *drv); +const char *fp_driver_get_full_name(struct fp_driver *drv); +uint16_t fp_driver_get_driver_id(struct fp_driver *drv); + /* Device discovery */ struct fp_dscv_dev **fp_discover_devs(void); void fp_dscv_devs_free(struct fp_dscv_dev **devs); struct fp_driver *fp_dscv_dev_get_driver(struct fp_dscv_dev *dev); uint32_t fp_dscv_dev_get_devtype(struct fp_dscv_dev *dev); +int fp_dscv_dev_supports_print_data(struct fp_dscv_dev *dev, + struct fp_print_data *print); +int fp_dscv_dev_supports_dscv_print(struct fp_dscv_dev *dev, + struct fp_dscv_print *print); +struct fp_dscv_dev *fp_dscv_dev_for_print_data(struct fp_dscv_dev **devs, + struct fp_print_data *print); +struct fp_dscv_dev *fp_dscv_dev_for_dscv_print(struct fp_dscv_dev **devs, + struct fp_dscv_print *print); static inline uint16_t fp_dscv_dev_get_driver_id(struct fp_dscv_dev *dev) { return fp_driver_get_driver_id(fp_dscv_dev_get_driver(dev)); } +/* Print discovery */ +struct fp_dscv_print **fp_discover_prints(void); +void fp_dscv_prints_free(struct fp_dscv_print **prints); +uint16_t fp_dscv_print_get_driver_id(struct fp_dscv_print *print); +uint32_t fp_dscv_print_get_devtype(struct fp_dscv_print *print); +enum fp_finger fp_dscv_print_get_finger(struct fp_dscv_print *print); + /* Device handling */ struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev); void fp_dev_close(struct fp_dev *dev); @@ -59,11 +82,8 @@ struct fp_driver *fp_dev_get_driver(struct fp_dev *dev); int fp_dev_get_nr_enroll_stages(struct fp_dev *dev); struct fp_img_dev *fp_dev_to_img_dev(struct fp_dev *dev); uint32_t fp_dev_get_devtype(struct fp_dev *dev); - -/* Drivers */ -const char *fp_driver_get_name(struct fp_driver *drv); -const char *fp_driver_get_full_name(struct fp_driver *drv); -uint16_t fp_driver_get_driver_id(struct fp_driver *drv); +int fp_dev_supports_print_data(struct fp_dev *dev, struct fp_print_data *data); +int fp_dev_supports_dscv_print(struct fp_dev *dev, struct fp_dscv_print *print); /* Enrollment */ enum fp_enroll_result { @@ -93,6 +113,8 @@ int fp_verify_finger(struct fp_dev *dev, struct fp_print_data *enrolled_print); /* Data handling */ int fp_print_data_load(struct fp_dev *dev, enum fp_finger finger, struct fp_print_data **data); +int fp_print_data_from_dscv_print(struct fp_dscv_print *print, + struct fp_print_data **data); int fp_print_data_save(struct fp_print_data *data, enum fp_finger finger); void fp_print_data_free(struct fp_print_data *data); size_t fp_print_data_get_data(struct fp_print_data *data, unsigned char **ret); From fc0a97a801377fb5d9666d81a18b2c93c4c37f61 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Wed, 31 Oct 2007 13:18:30 +0000 Subject: [PATCH 045/184] Build system tweaks Install fprint.h header Include headers in distribution distcheck fixes Include and install pkgconfig file --- Makefile.am | 6 +++++- TODO | 15 ++++++++------- configure.ac | 2 +- libfprint.pc.in | 11 +++++++++++ libfprint/Makefile.am | 11 ++++++++++- 5 files changed, 35 insertions(+), 10 deletions(-) create mode 100644 libfprint.pc.in diff --git a/Makefile.am b/Makefile.am index 9d5938a0..3a0c7458 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1,4 +1,4 @@ -EXTRA_DIST = THANKS TODO HACKING +EXTRA_DIST = THANKS TODO HACKING libfprint.pc.in SUBDIRS = libfprint @@ -6,3 +6,7 @@ if BUILD_EXAMPLES SUBDIRS += examples endif +pkgconfigdir=$(libdir)/pkgconfig +pkgconfig_DATA=libfprint.pc +DISTCLEANFILES=libfprint.pc + diff --git a/TODO b/TODO index d417f759..338ad915 100644 --- a/TODO +++ b/TODO @@ -3,9 +3,13 @@ LIBRARY identification external API documentation test suite against NFIQ compliance set +make library optionally asynchronous and maybe thread-safe +nbis cleanups +track open devices, so we can close them during libfprint close +free memory during libfprint close -DRIVERS -======= +NEW DRIVERS +=========== Sunplus 895 driver AES1610 driver AES2501 driver @@ -20,12 +24,9 @@ aes4000 doesn't work very well, maybe due to small minutia count? PPMM parameter to get_minutiae seems to have no effect nbis minutiae should be stored in endian-independent format return images with standard enroll/verify calls +upekts reverify problems MISC ==== upekts/thinkfinger relicensing (GPL --> LGPL) -make library optionally asynchronous and maybe thread-safe -pkg-config file -nbis cleanups -track open devices, so we can close them during libfprint close -free memory during libfprint close + diff --git a/configure.ac b/configure.ac index d6a0c4a8..84344392 100644 --- a/configure.ac +++ b/configure.ac @@ -85,6 +85,6 @@ AC_DEFINE([API_EXPORTED], [__attribute__((visibility("default")))], [Default vis AM_CFLAGS="-Werror-implicit-function-declaration -Wimplicit-int -Wunreachable-code -Wunused-function -Wunused-label -Wunused-value -Wunused-variable -Wnonnull -Wreturn-type -Wextra -Wshadow" AC_SUBST(AM_CFLAGS) -AC_CONFIG_FILES([Makefile] [libfprint/Makefile] [examples/Makefile]) +AC_CONFIG_FILES([libfprint.pc] [Makefile] [libfprint/Makefile] [examples/Makefile]) AC_OUTPUT diff --git a/libfprint.pc.in b/libfprint.pc.in new file mode 100644 index 00000000..30687d13 --- /dev/null +++ b/libfprint.pc.in @@ -0,0 +1,11 @@ +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ + +Name: libfprint +Description: Generic C API for fingerprint reader access +Version: @VERSION@ +Libs: -L${libdir} -lfprint +Cflags: -I${includedir}/libfprint + diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index f6e7e07f..ea07a414 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -7,6 +7,13 @@ AES4000_SRC = drivers/aes4000.c DRIVER_SRC = $(UPEKTS_SRC) $(URU4000_SRC) $(AES4000_SRC) NBIS_SRC = \ + nbis/include/bozorth.h \ + nbis/include/bz_array.h \ + nbis/include/defs.h \ + nbis/include/lfs.h \ + nbis/include/log.h \ + nbis/include/morph.h \ + nbis/include/sunrast.h \ nbis/bozorth3/bozorth3.c \ nbis/bozorth3/bz_alloc.c \ nbis/bozorth3/bz_drvrs.c \ @@ -36,11 +43,12 @@ NBIS_SRC = \ nbis/mindtct/sort.c \ nbis/mindtct/util.c -libfprint_la_CFLAGS = -fvisibility=hidden -Inbis/include $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) $(AM_CFLAGS) +libfprint_la_CFLAGS = -fvisibility=hidden -I$(srcdir)/nbis/include $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) $(AM_CFLAGS) libfprint_la_LDFLAGS = -version-info @lt_major@:@lt_revision@:@lt_age@ libfprint_la_LIBADD = -lm $(LIBUSB_LIBS) $(GLIB_LIBS) libfprint_la_SOURCES = \ + fp_internal.h \ core.c \ data.c \ img.c \ @@ -48,3 +56,4 @@ libfprint_la_SOURCES = \ $(DRIVER_SRC) \ $(NBIS_SRC) +pkginclude_HEADERS = fprint.h From 07a81b07becb597d919c706e9894c31b2e95432f Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Wed, 31 Oct 2007 21:51:37 +0000 Subject: [PATCH 046/184] upekts: initialise and deinitialise device during verify/capture Otherwise it heats up, and verify retries fail because we didn't end the session. --- TODO | 1 - libfprint/drivers/upekts.c | 196 +++++++++++++++++++++---------------- 2 files changed, 113 insertions(+), 84 deletions(-) diff --git a/TODO b/TODO index 338ad915..e7dda736 100644 --- a/TODO +++ b/TODO @@ -24,7 +24,6 @@ aes4000 doesn't work very well, maybe due to small minutia count? PPMM parameter to get_minutiae seems to have no effect nbis minutiae should be stored in endian-independent format return images with standard enroll/verify calls -upekts reverify problems MISC ==== diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index 2571a829..5f0842c7 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -421,108 +421,128 @@ static const unsigned char init28_0b[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00 }; +static int do_init(struct fp_dev *dev) +{ + enum read_msg_status msgstat; + unsigned char dummy = 0x10; + uint8_t seq; + int r; + + r = usb_control_msg(dev->udev, USB_TYPE_VENDOR | USB_RECIP_DEVICE, + 0x0c, 0x100, 0x400, &dummy, sizeof(dummy), TIMEOUT); + if (r < 0) { + fp_dbg("control write failed\n"); + return r; + } + + msgstat = read_msg(dev, &seq, NULL, NULL, NULL); + if (msgstat != READ_MSG_CMD) { + fp_err("expected command, got %d seq=%x", msgstat, seq); + return -EPROTO; + } + if (seq != 3) { + fp_err("expected seq=3, got %x", seq); + return -EPROTO; + } + + r = send_cmdresponse(dev, ++seq, (unsigned char *) init_resp03, + sizeof(init_resp03)); + if (r < 0) + return r; + + msgstat = read_msg(dev, &seq, NULL, NULL, NULL); + if (msgstat != READ_MSG_CMD) { + fp_err("expected command, got %d seq=%x", msgstat, seq); + return -EPROTO; + } + if (seq != 5) { + fp_err("expected seq=5, got %x", seq); + return -EPROTO; + } + + dummy = 0x04; + r = send_cmd28(dev, 0x06, &dummy, 1); + if (r < 0) + return r; + if (read_msg28(dev, 0x06, NULL, NULL) < 0) + return r; + + dummy = 0x04; + r = send_cmd28(dev, 0x07, &dummy, 1); + if (r < 0) + return r; + if (read_msg28(dev, 0x07, NULL, NULL) < 0) + return r; + + r = send_cmd28(dev, 0x08, (unsigned char *) init28_08, + sizeof(init28_08)); + if (r < 0) + return r; + if (read_msg28(dev, 0x08, NULL, NULL) < 0) + return r; + + r = send_cmd28(dev, 0x0c, (unsigned char *) init28_0c, + sizeof(init28_0c)); + if (r < 0) + return r; + if (read_msg28(dev, 0x0c, NULL, NULL) < 0) + return r; + + r = send_cmd28(dev, 0x0b, (unsigned char *) init28_0b, + sizeof(init28_0b)); + if (r < 0) + return r; + if (read_msg28(dev, 0x0b, NULL, NULL) < 0) + return r; + + return 0; +} + +static int do_deinit(struct fp_dev *dev) +{ + unsigned char dummy = 0; + enum read_msg_status msgstat; + uint8_t seq; + int r; + + /* FIXME: either i've misunderstood the message system or this is illegal + * here, since we arent responding to anything. */ + r = send_cmdresponse(dev, 0x07, &dummy, 1); + if (r < 0) + return r; + + msgstat = read_msg(dev, &seq, NULL, NULL, NULL); + if (msgstat != READ_MSG_CMD) { + fp_err("expected command, got %d seq=%x", msgstat, seq); + return -EPROTO; + } + if (seq != 1) { + fp_err("expected seq=1, got %x", seq); + return -EPROTO; + } + + return 0; +} + static int dev_init(struct fp_dev *dev, unsigned long driver_data) { struct upekts_dev *upekdev = NULL; - unsigned char dummy = 0x10; - enum read_msg_status msgstat; - uint8_t seq; int r; r = usb_claim_interface(dev->udev, 0); if (r < 0) return r; - r = usb_control_msg(dev->udev, USB_TYPE_VENDOR | USB_RECIP_DEVICE, - 0x0c, 0x100, 0x400, &dummy, sizeof(dummy), TIMEOUT); - if (r < 0) { - fp_dbg("control write failed\n"); - goto err; - } - upekdev = g_malloc(sizeof(*upekdev)); upekdev->seq = 0xf0; /* incremented to 0x00 before first cmd */ dev->priv = upekdev; dev->nr_enroll_stages = 3; - msgstat = read_msg(dev, &seq, NULL, NULL, NULL); - if (msgstat != READ_MSG_CMD) { - fp_err("expected command, got %d seq=%x", msgstat, seq); - goto err; - } - if (seq != 3) { - fp_err("expected seq=3, got %x", seq); - goto err; - } - - r = send_cmdresponse(dev, ++seq, (unsigned char *) init_resp03, - sizeof(init_resp03)); - if (r < 0) - goto err; - - msgstat = read_msg(dev, &seq, NULL, NULL, NULL); - if (msgstat != READ_MSG_CMD) { - fp_err("expected command, got %d seq=%x", msgstat, seq); - goto err; - } - if (seq != 5) { - fp_err("expected seq=5, got %x", seq); - goto err; - } - - dummy = 0x04; - r = send_cmd28(dev, 0x06, &dummy, 1); - if (r < 0) - goto err; - if (read_msg28(dev, 0x06, NULL, NULL) < 0) - goto err; - - dummy = 0x04; - r = send_cmd28(dev, 0x07, &dummy, 1); - if (r < 0) - goto err; - if (read_msg28(dev, 0x07, NULL, NULL) < 0) - goto err; - - r = send_cmd28(dev, 0x08, (unsigned char *) init28_08, - sizeof(init28_08)); - if (r < 0) - goto err; - if (read_msg28(dev, 0x08, NULL, NULL) < 0) - goto err; - - r = send_cmd28(dev, 0x0c, (unsigned char *) init28_0c, - sizeof(init28_0c)); - if (r < 0) - goto err; - if (read_msg28(dev, 0x0c, NULL, NULL) < 0) - goto err; - - r = send_cmd28(dev, 0x0b, (unsigned char *) init28_0b, - sizeof(init28_0b)); - if (r < 0) - goto err; - if (read_msg28(dev, 0x0b, NULL, NULL) < 0) - goto err; - return 0; -err: - usb_release_interface(dev->udev, 0); - g_free(upekdev); - - return -EPROTO; } static void dev_exit(struct fp_dev *dev) { - unsigned char dummy = 0; - - /* FIXME: either i've misunderstood the message system or this is illegal - * here, since we arent responding to anything. */ - send_cmdresponse(dev, 0x07, &dummy, 1); - - // FIXME should read msg A=01 - usb_release_interface(dev->udev, 0); g_free(dev->priv); } @@ -547,6 +567,10 @@ static int enroll(struct fp_dev *dev, gboolean initial, int passed = 0; if (initial) { + r = do_init(dev); + if (r < 0) + return r; + r = send_cmd28(dev, 0x02, (unsigned char *) enroll_init, sizeof(enroll_init)); if (r < 0) @@ -656,6 +680,7 @@ static int enroll(struct fp_dev *dev, gboolean initial, memcpy(fdata->data, data + sizeof(scan_comp), data_len - sizeof(scan_comp)); *_data = fdata; comp_out: + do_deinit(dev); g_free(data); } @@ -677,6 +702,10 @@ static int verify(struct fp_dev *dev, struct fp_print_data *print) gboolean need_poll = FALSE; gboolean done = FALSE; + r = do_init(dev); + if (r < 0) + return r; + data = g_malloc(data_len); memcpy(data, verify_hdr, sizeof(verify_hdr)); memcpy(data + sizeof(verify_hdr), print->data, print->length); @@ -771,6 +800,7 @@ static int verify(struct fp_dev *dev, struct fp_print_data *print) } out: + do_deinit(dev); g_free(data); return r; } From fc77786e46f8e7e8912426e13e858eb041b8ecc2 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Wed, 31 Oct 2007 22:42:09 +0000 Subject: [PATCH 047/184] uru4000: interrupt handling fixes This should improve driver stability somewhat. Powerup problems seem to happen when we receive 3 unrelated interrupts while waiting for the power-on interrupt, so let's assume that the device can only buffer 3 interrupts, and when the buffer is full, it discards new ones. When we detect a possible buffer overflow, ask the caller to retry the operation. Also, saw the interrupt of death a few times, so add in a warning when this happens. Haven't seen it since handling interrupt overflows though. --- libfprint/drivers/uru4000.c | 89 ++++++++++++++++++++++++++++++------- 1 file changed, 73 insertions(+), 16 deletions(-) diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index 04c76e37..ef9746e0 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -44,6 +44,7 @@ enum { IRQDATA_SCANPWR_ON = 0x56aa, IRQDATA_FINGER_ON = 0x0101, IRQDATA_FINGER_OFF = 0x0200, + IRQDATA_DEATH = 0x0800, }; enum { @@ -100,6 +101,31 @@ struct uru4k_dev { uint8_t interface; }; +/* + * HWSTAT + * + * This register has caused me a lot of headaches. It pretty much defines + * code flow, and if you don't get it right, the pretty lights don't come on. + * I think the situation is somewhat complicated by the fact that writing it + * doesn't affect the read results in the way you'd expect -- but then again + * it does have some obvious effects. Here's what we know + * + * BIT 7: LOW POWER MODE + * When this bit is set, the device is partially turned off or something. Some + * things, like firmware upload, need to be done in this state. But generally + * we want to clear this bit during late initialization, which can sometimes + * be tricky. + * + * BIT 2: SOMETHING WENT WRONG + * Not sure about this, but see the init function, as when we detect it, + * we reboot the device. Well, we mess with hwstat until this evil bit gets + * cleared. + * + * BIT 1: IRQ PENDING + * Just had a brainwave. This bit is set when the device is trying to deliver + * and interrupt to the host. Maybe? + */ + static int get_hwstat(struct fp_img_dev *dev, unsigned char *data) { int r; @@ -191,56 +217,86 @@ retry: type = GUINT16_FROM_BE(*((uint16_t *) buf)); fp_dbg("irq type %04x", type); + /* The 0800 interrupt seems to indicate imminent failure (0 bytes transfer) + * of the next scan. I think I've stopped it from coming up, not sure + * though! */ + if (type == IRQDATA_DEATH) + fp_warn("oh no! got the interrupt OF DEATH! expect things to go bad"); + return 0; } -static int get_irq_with_type(struct fp_img_dev *dev, uint16_t irqtype, - int timeout) +enum get_irq_status { + GET_IRQ_SUCCESS = 0, + GET_IRQ_OVERFLOW = 1, +}; + +static int get_irq_with_type(struct fp_img_dev *dev, + uint16_t irqtype, int timeout) { uint16_t hdr; - int discarded = -1; + int discarded = 0; unsigned char irqbuf[IRQ_LENGTH]; fp_dbg("type=%04x", irqtype); - /* Sometimes we get an interrupt from a previous 'session' indicating - * finger-on-sensor, we ignore this and wait for the real interrupt */ do { - int r; - discarded++; - - r = get_irq(dev, irqbuf, timeout); + int r = get_irq(dev, irqbuf, timeout); if (r < 0) return r; + hdr = GUINT16_FROM_BE(*((uint16_t *) irqbuf)); - } while (hdr != irqtype); + if (hdr == irqtype) + break; + discarded++; + } while (discarded < 3); if (discarded > 0) fp_dbg("discarded %d interrupts", discarded); - return 0; + if (hdr == irqtype) { + return GET_IRQ_SUCCESS; + } else { + /* I've seen several cases where we're waiting for the 56aa powerup + * interrupt, but instead we just get three 0200 interrupts and then + * nothing. My theory is that the device can only queue 3 interrupts, + * or something. So, if we discard 3, ask the caller to retry whatever + * it was doing. */ + fp_dbg("possible IRQ overflow detected!"); + return GET_IRQ_OVERFLOW; + } } static int await_finger_on(struct fp_img_dev *dev) { int r; +retry: r = set_mode(dev, MODE_AWAIT_FINGER_ON); if (r < 0) return r; - return get_irq_with_type(dev, IRQDATA_FINGER_ON, 0); + r = get_irq_with_type(dev, IRQDATA_FINGER_ON, 0); + if (r == GET_IRQ_OVERFLOW) + goto retry; + else + return r; } static int await_finger_off(struct fp_img_dev *dev) { int r; +retry: r = set_mode(dev, MODE_AWAIT_FINGER_OFF); if (r < 0) return r; - return get_irq_with_type(dev, IRQDATA_FINGER_OFF, 0); + r = get_irq_with_type(dev, IRQDATA_FINGER_OFF, 0); + if (r == GET_IRQ_OVERFLOW) + goto retry; + else + return r; } static int capture(struct fp_img_dev *dev, gboolean unconditional, @@ -306,6 +362,7 @@ static int do_init(struct fp_img_dev *dev) int i; int r; +retry: r = get_hwstat(dev, &status); if (r < 0) return r; @@ -376,10 +433,10 @@ static int do_init(struct fp_img_dev *dev) } r = get_irq_with_type(dev, IRQDATA_SCANPWR_ON, 5); - if (r < 0) + if (r == GET_IRQ_OVERFLOW) + goto retry; + else return r; - - return 0; } static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) From 7e6f25908bbd160f7f2a44618f29bbaded748bf9 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Fri, 2 Nov 2007 17:04:19 +0000 Subject: [PATCH 048/184] remove imgdev abstraction from public API Make it easier for application developers, don't have to care about this level of abstraction which we're intending to make superfluous to them. --- TODO | 2 +- examples/img_capture.c | 9 +++------ libfprint/core.c | 41 ++++++++++++++++++++++++++++++++++++++++- libfprint/fp_internal.h | 5 +++++ libfprint/fprint.h | 13 ++++++------- libfprint/imgdev.c | 12 ++++++------ 6 files changed, 61 insertions(+), 21 deletions(-) diff --git a/TODO b/TODO index e7dda736..9430dad0 100644 --- a/TODO +++ b/TODO @@ -23,7 +23,7 @@ IMAGING aes4000 doesn't work very well, maybe due to small minutia count? PPMM parameter to get_minutiae seems to have no effect nbis minutiae should be stored in endian-independent format -return images with standard enroll/verify calls +return images with standard enroll/verify call variants MISC ==== diff --git a/examples/img_capture.c b/examples/img_capture.c index 977113d9..794f1d1e 100644 --- a/examples/img_capture.c +++ b/examples/img_capture.c @@ -43,7 +43,6 @@ int main(void) struct fp_dscv_dev *ddev; struct fp_dscv_dev **discovered_devs; struct fp_dev *dev; - struct fp_img_dev *imgdev; struct fp_img *img = NULL; r = fp_init(); @@ -71,16 +70,14 @@ int main(void) exit(1); } - imgdev = fp_dev_to_img_dev(dev); - if (!imgdev) { - fprintf(stderr, "could not get image dev, is this an imaging " - "device?\n"); + if (!fp_dev_supports_imaging(dev)) { + fprintf(stderr, "this device does not have imaging capabilities.\n"); goto out_close; } printf("Opened device. It's now time to scan your finger.\n\n"); - r = fp_imgdev_capture(imgdev, 0, &img); + r = fp_dev_img_capture(dev, 0, &img); if (r) { fprintf(stderr, "image capture failed, code %d\n", r); goto out_close; diff --git a/libfprint/core.c b/libfprint/core.c index 7bc13f87..7467e325 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -349,13 +349,52 @@ API_EXPORTED uint16_t fp_driver_get_driver_id(struct fp_driver *drv) return drv->id; } -API_EXPORTED struct fp_img_dev *fp_dev_to_img_dev(struct fp_dev *dev) +static struct fp_img_dev *dev_to_img_dev(struct fp_dev *dev) { if (dev->drv->type != DRIVER_IMAGING) return NULL; return dev->priv; } +API_EXPORTED int fp_dev_supports_imaging(struct fp_dev *dev) +{ + return dev->drv->type == DRIVER_IMAGING; +} + +API_EXPORTED int fp_dev_img_capture(struct fp_dev *dev, int unconditional, + struct fp_img **image) +{ + struct fp_img_dev *imgdev = dev_to_img_dev(dev); + if (!imgdev) { + fp_dbg("image capture on non-imaging device"); + return -ENOTSUP; + } + + return fpi_imgdev_capture(imgdev, unconditional, image); +} + +API_EXPORTED int fp_dev_get_img_width(struct fp_dev *dev) +{ + struct fp_img_dev *imgdev = dev_to_img_dev(dev); + if (!imgdev) { + fp_dbg("get image width for non-imaging device"); + return -1; + } + + return fpi_imgdev_get_img_width(imgdev); +} + +API_EXPORTED int fp_dev_get_img_height(struct fp_dev *dev) +{ + struct fp_img_dev *imgdev = dev_to_img_dev(dev); + if (!imgdev) { + fp_dbg("get image height for non-imaging device"); + return -1; + } + + return fpi_imgdev_get_img_height(imgdev); +} + API_EXPORTED int fp_enroll_finger(struct fp_dev *dev, struct fp_print_data **print_data) { diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 39b3204c..361969d5 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -82,6 +82,11 @@ struct fp_img_dev { void *priv; }; +int fpi_imgdev_capture(struct fp_img_dev *imgdev, int unconditional, + struct fp_img **image); +int fpi_imgdev_get_img_width(struct fp_img_dev *imgdev); +int fpi_imgdev_get_img_height(struct fp_img_dev *imgdev); + struct usb_id { uint16_t vendor; uint16_t product; diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 1f2e2e80..3164b9c4 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -80,11 +80,16 @@ struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev); void fp_dev_close(struct fp_dev *dev); struct fp_driver *fp_dev_get_driver(struct fp_dev *dev); int fp_dev_get_nr_enroll_stages(struct fp_dev *dev); -struct fp_img_dev *fp_dev_to_img_dev(struct fp_dev *dev); uint32_t fp_dev_get_devtype(struct fp_dev *dev); int fp_dev_supports_print_data(struct fp_dev *dev, struct fp_print_data *data); int fp_dev_supports_dscv_print(struct fp_dev *dev, struct fp_dscv_print *print); +int fp_dev_supports_imaging(struct fp_dev *dev); +int fp_dev_img_capture(struct fp_dev *dev, int unconditional, + struct fp_img **image); +int fp_dev_get_img_width(struct fp_dev *dev); +int fp_dev_get_img_height(struct fp_dev *dev); + /* Enrollment */ enum fp_enroll_result { FP_ENROLL_COMPLETE = 1, @@ -123,12 +128,6 @@ struct fp_print_data *fp_print_data_from_data(unsigned char *buf, uint16_t fp_print_data_get_driver_id(struct fp_print_data *data); uint32_t fp_print_data_get_devtype(struct fp_print_data *data); -/* Imaging devices */ -int fp_imgdev_capture(struct fp_img_dev *imgdev, int unconditional, - struct fp_img **image); -int fp_imgdev_get_img_width(struct fp_img_dev *imgdev); -int fp_imgdev_get_img_height(struct fp_img_dev *imgdev); - /* Image handling */ int fp_img_get_height(struct fp_img *img); int fp_img_get_width(struct fp_img *img); diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index b5431dda..18ba789d 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -58,22 +58,22 @@ static void img_dev_exit(struct fp_dev *dev) g_free(imgdev); } -API_EXPORTED int fp_imgdev_get_img_width(struct fp_img_dev *imgdev) +int fpi_imgdev_get_img_width(struct fp_img_dev *imgdev) { struct fp_driver *drv = imgdev->dev->drv; struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); return imgdrv->img_width; } -API_EXPORTED int fp_imgdev_get_img_height(struct fp_img_dev *imgdev) +int fpi_imgdev_get_img_height(struct fp_img_dev *imgdev) { struct fp_driver *drv = imgdev->dev->drv; struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); return imgdrv->img_height; } -API_EXPORTED int fp_imgdev_capture(struct fp_img_dev *imgdev, - int unconditional, struct fp_img **image) +int fpi_imgdev_capture(struct fp_img_dev *imgdev, int unconditional, + struct fp_img **image) { struct fp_driver *drv = imgdev->dev->drv; struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); @@ -151,7 +151,7 @@ int img_dev_enroll(struct fp_dev *dev, gboolean initial, int stage, /* FIXME: convert to 3-stage enroll mechanism, where we scan 3 prints, * use NFIQ to pick the best one, and discard the others */ - r = fp_imgdev_capture(imgdev, 0, &img); + r = fpi_imgdev_capture(imgdev, 0, &img); if (r) return r; @@ -178,7 +178,7 @@ static int img_dev_verify(struct fp_dev *dev, struct fp_print_data *print; int r; - r = fp_imgdev_capture(imgdev, 0, &img); + r = fpi_imgdev_capture(imgdev, 0, &img); if (r) return r; From 2e6c3b940cf30705e7a2aa4bbb5c1c191fa94fdc Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Thu, 1 Nov 2007 23:11:29 +0000 Subject: [PATCH 049/184] API documentation --- Makefile.am | 2 +- TODO | 2 + configure.ac | 2 +- doc/Makefile.am | 10 + doc/doxygen.cfg | 1294 ++++++++++++++++++++++++++++++++++++++++++++ libfprint/core.c | 462 +++++++++++++++- libfprint/data.c | 162 +++++- libfprint/fprint.h | 69 ++- libfprint/img.c | 51 ++ 9 files changed, 2038 insertions(+), 16 deletions(-) create mode 100644 doc/Makefile.am create mode 100644 doc/doxygen.cfg diff --git a/Makefile.am b/Makefile.am index 3a0c7458..1921cdc0 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1,6 +1,6 @@ EXTRA_DIST = THANKS TODO HACKING libfprint.pc.in -SUBDIRS = libfprint +SUBDIRS = libfprint doc if BUILD_EXAMPLES SUBDIRS += examples diff --git a/TODO b/TODO index 9430dad0..9b70a181 100644 --- a/TODO +++ b/TODO @@ -7,6 +7,8 @@ make library optionally asynchronous and maybe thread-safe nbis cleanups track open devices, so we can close them during libfprint close free memory during libfprint close +API function to determine if img device supports uncond. capture +race-free way of saying "save this print but don't overwrite" NEW DRIVERS =========== diff --git a/configure.ac b/configure.ac index 84344392..e6b501a7 100644 --- a/configure.ac +++ b/configure.ac @@ -85,6 +85,6 @@ AC_DEFINE([API_EXPORTED], [__attribute__((visibility("default")))], [Default vis AM_CFLAGS="-Werror-implicit-function-declaration -Wimplicit-int -Wunreachable-code -Wunused-function -Wunused-label -Wunused-value -Wunused-variable -Wnonnull -Wreturn-type -Wextra -Wshadow" AC_SUBST(AM_CFLAGS) -AC_CONFIG_FILES([libfprint.pc] [Makefile] [libfprint/Makefile] [examples/Makefile]) +AC_CONFIG_FILES([libfprint.pc] [Makefile] [libfprint/Makefile] [examples/Makefile] [doc/Makefile]) AC_OUTPUT diff --git a/doc/Makefile.am b/doc/Makefile.am new file mode 100644 index 00000000..3367df38 --- /dev/null +++ b/doc/Makefile.am @@ -0,0 +1,10 @@ +EXTRA_DIST = doxygen.cfg + +docs: doxygen.cfg + doxygen $^ + +docs-upload: docs + ln -s html fprint-api + ncftpput -f ~/.ncftp/reactivated -m -R httpdocs fprint-api/ + rm -f fprint-api + diff --git a/doc/doxygen.cfg b/doc/doxygen.cfg new file mode 100644 index 00000000..41b1a071 --- /dev/null +++ b/doc/doxygen.cfg @@ -0,0 +1,1294 @@ +# Doxyfile 1.5.3 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project +# +# All text after a hash (#) is considered a comment and will be ignored +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" ") + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the config file that +# follow. The default is UTF-8 which is also the encoding used for all text before +# the first occurrence of this tag. Doxygen uses libiconv (or the iconv built into +# libc) for the transcoding. See http://www.gnu.org/software/libiconv for the list of +# possible encodings. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded +# by quotes) that should identify the project. + +PROJECT_NAME = libfprint + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, +# Croatian, Czech, Danish, Dutch, Finnish, French, German, Greek, Hungarian, +# Italian, Japanese, Japanese-en (Japanese with English messages), Korean, +# Korean-en, Lithuanian, Norwegian, Polish, Portuguese, Romanian, Russian, +# Serbian, Slovak, Slovene, Spanish, Swedish, and Ukrainian. + +OUTPUT_LANGUAGE = English + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = NO + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful is your file systems +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like regular Qt-style comments +# (thus requiring an explicit @brief command for a brief description.) + +JAVADOC_AUTOBRIEF = YES + +# If the QT_AUTOBRIEF tag is set to YES then Doxygen will +# interpret the first line (until the first dot) of a Qt-style +# comment as the brief description. If set to NO, the comments +# will behave just like regular Qt-style comments (thus requiring +# an explicit \brief command for a brief description.) + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the DETAILS_AT_TOP tag is set to YES then Doxygen +# will output the detailed description near the top, like JavaDoc. +# If set to NO, the detailed description appears after the member +# documentation. + +DETAILS_AT_TOP = NO + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 4 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = YES + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java +# sources only. Doxygen will then generate output that is more tailored for Java. +# For instance, namespaces will be presented as packages, qualified scopes +# will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want to +# include (a tag file for) the STL sources as input, then you should +# set this tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. +# func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. + +BUILTIN_STL_SUPPORT = NO + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. + +CPP_CLI_SUPPORT = NO + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = NO + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = NO + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be extracted +# and appear in the documentation as a namespace called 'anonymous_namespace{file}', +# where file will be replaced with the base name of the file that contains the anonymous +# namespace. By default anonymous namespace are hidden. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = YES + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = NO + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = YES + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = NO + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if sectionname ... \endif. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or define consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and defines in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = YES + +# If the sources in your project are distributed over multiple directories +# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy +# in the documentation. The default is NO. + +SHOW_DIRECTORIES = NO + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from the +# version control system). Doxygen will invoke the program by executing (via +# popen()) the command , where is the value of +# the FILE_VERSION_FILTER tag, and is the name of an input file +# provided by doxygen. Whatever the program writes to standard output +# is used as the file version. See the manual for examples. + +FILE_VERSION_FILTER = + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = YES + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = YES + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be abled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = ../libfprint + +# This tag can be used to specify the character encoding of the source files that +# doxygen parses. Internally doxygen uses the UTF-8 encoding, which is also the default +# input encoding. Doxygen uses libiconv (or the iconv built into libc) for the transcoding. +# See http://www.gnu.org/software/libiconv for the list of possible encodings. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx +# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py + +FILE_PATTERNS = + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. + +EXCLUDE = ../libfprint/fp_internal.h + +# The EXCLUDE_SYMLINKS tag can be used select whether or not files or +# directories that are symbolic links (a Unix filesystem feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. Note that the wildcards are matched +# against the file with absolute path, so to exclude all test directories +# for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the output. +# The symbol name can be a fully qualified name, a word, or if the wildcard * is used, +# a substring. Examples: ANamespace, AClass, AClass::ANamespace, ANamespace::*Test + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command , where +# is the value of the INPUT_FILTER tag, and is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. If FILTER_PATTERNS is specified, this tag will be +# ignored. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER +# is applied to all files. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. If you have enabled CALL_GRAPH or CALLER_GRAPH +# then you must also enable this option. If you don't then doxygen will produce +# a warning and turn it on anyway + +SOURCE_BROWSER = NO + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C and C++ comments will always remain visible. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES (the default) +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = YES + +# If the REFERENCES_RELATION tag is set to YES (the default) +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = YES + +# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) +# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from +# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will +# link to the source code. Otherwise they will link to the documentstion. + +REFERENCES_LINK_SOURCE = YES + +# If the USE_HTAGS tag is set to YES then the references to source code +# will point to the HTML generated by the htags(1) tool instead of doxygen +# built-in source browser. The htags tool is part of GNU's global source +# tagging system (see http://www.gnu.org/software/global/global.html). You +# will need version 4.8.6 or higher. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = YES + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If the tag is left blank doxygen +# will generate a default style sheet. Note that doxygen will try to copy +# the style sheet file to the HTML output directory, so don't put your own +# stylesheet in the HTML output directory as well, or it will be erased! + +HTML_STYLESHEET = + +# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, +# files or namespaces will be aligned in HTML using tables. If set to +# NO a bullet list will be used. + +HTML_ALIGN_MEMBERS = YES + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compressed HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. For this to work a browser that supports +# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox +# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). + +HTML_DYNAMIC_SECTIONS = YES + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index at +# top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. + +DISABLE_INDEX = NO + +# This tag can be used to set the number of enum values (range [1..20]) +# that doxygen will group on one line in the generated HTML documentation. + +ENUM_VALUES_PER_LINE = 4 + +# If the GENERATE_TREEVIEW tag is set to YES, a side panel will be +# generated containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (for instance Mozilla 1.0+, +# Netscape 6.0+, Internet explorer 5.0+, or Konqueror). Windows users are +# probably better off using the HTML help feature. + +GENERATE_TREEVIEW = NO + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 250 + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = NO + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, a4wide, letter, legal and +# executive. If left blank a4wide will be used. + +PAPER_TYPE = a4wide + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = NO + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = NO + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = NO + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = .3 + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. This is useful +# if you want to understand what is going on. On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = YES + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_DEFINED tags. + +EXPAND_ONLY_PREDEF = YES + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# in the INCLUDE_PATH (see below) will be search if a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = API_EXPORTED= + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all function-like macros that are alone +# on a line, have an all uppercase name, and do not end with a semicolon. Such +# function macros are typically used for boiler-plate code, and will confuse +# the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. +# Optionally an initial location of the external documentation +# can be added for each tagfile. The format of a tag file without +# this location is as follows: +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths or +# URLs. If a location is present for each tag, the installdox tool +# does not have to be run to correct the links. +# Note that each tag file must have a unique name +# (where the name does NOT include the path) +# If a tag file is not located in the directory in which doxygen +# is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option is superseded by the HAVE_DOT option below. This is only a +# fallback. It is recommended to install and use dot, since it yields more +# powerful graphs. + +CLASS_DIAGRAMS = YES + +# You can define message sequence charts within doxygen comments using the \msc +# command. Doxygen will then run the mscgen tool (see http://www.mcternan.me.uk/mscgen/) to +# produce the chart and insert it in the documentation. The MSCGEN_PATH tag allows you to +# specify the directory where the mscgen tool resides. If left empty the tool is assumed to +# be found in the default search path. + +MSCGEN_PATH = + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = NO + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# the CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +GROUP_GRAPHS = YES + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH, SOURCE_BROWSER and HAVE_DOT tags are set to YES then doxygen will +# generate a call dependency graph for every global function or class method. +# Note that enabling this option will significantly increase the time of a run. +# So in most cases it will be better to enable call graphs for selected +# functions only using the \callgraph command. + +CALL_GRAPH = NO + +# If the CALLER_GRAPH, SOURCE_BROWSER and HAVE_DOT tags are set to YES then doxygen will +# generate a caller dependency graph for every global function or class method. +# Note that enabling this option will significantly increase the time of a run. +# So in most cases it will be better to enable caller graphs for selected +# functions only using the \callergraph command. + +CALLER_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are png, jpg, or gif +# If left blank png will be used. + +DOT_IMAGE_FORMAT = png + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The MAX_DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of +# nodes that will be shown in the graph. If the number of nodes in a graph +# becomes larger than this value, doxygen will truncate the graph, which is +# visualized by representing a node as a red box. Note that doxygen if the number +# of direct children of the root node in a graph is already larger than +# MAX_DOT_GRAPH_NOTES then the graph will not be shown at all. Also note +# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. + +DOT_GRAPH_MAX_NODES = 50 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that the size of a graph can be further restricted by +# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, which results in a white background. +# Warning: Depending on the platform used, enabling this option may lead to +# badly anti-aliased labels on the edges of a graph (i.e. they become hard to +# read). + +DOT_TRANSPARENT = NO + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to the search engine +#--------------------------------------------------------------------------- + +# The SEARCHENGINE tag specifies whether or not a search engine should be +# used. If set to NO the values of all tags below this one will be ignored. + +SEARCHENGINE = NO diff --git a/libfprint/core.c b/libfprint/core.c index 7467e325..1685b4b9 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -26,6 +26,256 @@ #include "fp_internal.h" +/** + * \mainpage libfprint API Reference + * libfprint is an open source library to provide access to fingerprint + * scanning devices. For more info, see the + * libfprint project + * homepage. + * + * This documentation is aimed at application developers who wish to integrate + * fingerprint-related functionality into their software. libfprint has been + * designed so that you only have to do this once - by integrating your + * software with libfprint, you'll be supporting all the fingerprint readers + * that we have got our hands on. As such, the API is rather general (and + * therefore hopefully easy to comprehend!), and does it's best to hide the + * technical details that required to operate the hardware. + * + * This documentation is not aimed at developers wishing to develop and + * contribute fingerprint device drivers to libfprint. + * + * Feedback on this API and it's associated documentation is appreciated. Was + * anything unclear? Does anything seem unreasonably complicated? Is anything + * missing? Let us know on the + * mailing list. + * + * \section enrollment Enrollment + * + * Before you dive into the API, it's worth introducing a couple of concepts. + * + * The process of enrolling a finger is where you effectively scan your + * finger for the purposes of teaching the system what your finger looks like. + * This means that you scan your fingerprint, then the system processes it and + * stores some data about your fingerprint to refer to later. + * + * \section verification Verification + * + * Verification is what most people think of when they think about fingerprint + * scanning. The process of verification is effectively performing a fresh + * fingerprint scan, and then comparing that scan to a finger that was + * previously enrolled. + * + * As an example scenario, verification can be used to implement what people + * would picture as fingerprint login (i.e. fingerprint replaces password). + * For example: + * - I enroll my fingerprint through some software that trusts I am who I say + * I am. This is a prerequisite before I can perform fingerprint-based + * login for my account. + * - Some time later, I want to login to my computer. I enter my username, + * but instead of prompting me for a password, it asks me to scan my finger. + * I scan my finger. + * - The system compares the finger I just scanned to the one that was + * enrolled earlier. If the system decides that the fingerprints match, + * I am successfully logged in. Otherwise, the system informs me that I am + * not authorised to login as that user. + * + * \section identification Identification + * + * libfprint supports enrollment and verification as described above. Although + * libfprint does not yet support identification (it is planned), it is worth + * introducing the concept to give you a complete picture. + * + * Identification is the process of comparing a freshly scanned fingerprint + * to a collection of previously enrolled fingerprints. For example, + * imagine there are 100 people in an organisation, and they all have enrolled + * their fingerprints. One user walks up to a fingerprint scanner and scans + * their finger. With no other knowledge of who that user might be, + * the system examines their fingerprint, looks in the database, and determines + * that the user is user number #61. + * + * In other words, verification might be seen as a one-to-one fingerprint + * comparison where you know the identity of the user that you wish to + * authenticate, whereas identification is a one-to-many comparison where you + * do not know the identity of the user that you wish to authenticate. + * + * \section compat_general Device and print compatibility + * Moving off generic conceptual ideas and onto libfprint-specific + * implementation details, here are some introductory notes regarding how + * libfprint copes with compatibility of fingerprints. + * + * libfprint deals with a whole variety of different fingerprint readers and + * the design includes considerations of compatibility and interoperability + * between multiple devices. Your application should also be prepared to + * work with more than one type of fingerprint reader and should consider that + * enrolled fingerprint X may not be compatible with the device the user has + * plugged in today. + * + * libfprint implements the principle that fingerprints from different devices + * are not necessarily compatible. For example, different devices may see + * significantly different areas of fingerprint surface, and comparing images + * between the devices would be unreliable. Also, devices can stretch and + * distort images in different ways. + * + * libfprint also implements the principle that in some cases, fingerprints + * are compatible between different devices. If you go and buy two + * identical fingerprint readers, it seems logical that you should be able + * to enroll on one and verify on another without problems. + * + * libfprint takes a fairly simplistic approach to these issues. Internally, + * fingerprint hardware is driven by individual drivers. libfprint enforces + * that a fingerprint that came from a device backed by driver X is never + * compared to a fingerprint that came from a device backed by driver Y. + * + * Additionally, libfprint is designed for the situation where a single driver + * may support a range of devices which differ in imaging or scanning + * properties. For example, a driver may support two ranges of devices which + * even though are programmed over the same interface, one device sees + * substantially less of the finger flesh, therefore images from the two + * device types should be incompatible despite being from the same driver. To + * implement this, each driver assigns a device type to each device + * that it detects based on its imaging characteristics. libfprint ensures that + * two prints being compared have the same device type. + * + * In summary, libfprint represents fingerprints in several internal structures + * and each representation will offer you a way of determining the + * \ref driver_id "driver ID" and \ref devtype "devtype" of the print in + * question. Prints are only compatible if the driver ID and devtypes + * match. libfprint does offer you some "is this print compatible?" helper + * functions, so you don't have to worry about these details too much. + * + * \section Synchronity/asynchronity + * + * Currently, all data acquisition operations are synchronous and can + * potentially block for extended periods of time. For example, the enroll + * function will block for an unpredictable amount of time until the user + * scans their finger. + * + * Alternative asynchronous/non-blocking functionality will be offered in + * future but has not been implemented yet. + * + * \section getting_started Getting started + * + * libfprint includes several simple functional examples under the examples/ + * directory in the libfprint source distribution. Those are good starting + * points. + * + * Usually the first thing you want to do is determine which fingerprint + * devices are present. This is done through \ref dscv_dev "device discovery". + * + * Once you have found a device you would like to operate, you should open it. + * Refer to \ref dev "device operations". This section also details enrollment, + * image capture, and verification. + * + * + * That should be enough to get you started, but do remember there are + * documentation pages on other aspects of libfprint's API (see the modules + * page). + */ + +/** @defgroup core Core library operations */ + +/** + * @defgroup dev Device operations + * In order to interact with fingerprint scanners, your software will + * interface primarily with libfprint's representation of devices, detailed + * on this page. + * + * \section enrolling Enrolling + * Enrolling is represented within libfprint as a multi-stage process. This + * slightly complicates things for application developers, but is required + * for a smooth process. + * + * Some devices require the user to scan their finger multiple times in + * order to complete the enrollment process. libfprint must return control + * to your application inbetween each scan in order for your application to + * instruct the user to swipe their finger again. Each scan is referred to + * as a stage, so a device that requires 3 scans for enrollment corresponds + * to you running 3 enrollment stages using libfprint. + * + * The fp_dev_get_nr_enroll_stages() function can be used to find out how + * many enroll stages are needed. + * + * In order to complete an enroll stage, you call an enroll function such + * as fp_enroll_finger(). The return of this function does not necessarily + * indicate that a stage has completed though, as the user may not have + * produced a good enough scan. Each stage may have to be retried several + * times. + * + * The exact semantics of the enroll functions are described in the + * fp_enroll_finger() documentation. You should pay careful attention to the + * details. + * + * \section imaging Imaging + * libfprint provides you with some ways to retrieve images of scanned + * fingers, such as the fp_dev_img_capture() function, or some enroll/verify + * function variants which provide images. You may wish to do something with + * such images in your application. + * + * However, you must be aware that not all hardware supported by libfprint + * operates like this. Most hardware does operate simply by sending + * fingerprint images to the host computer for further processing, but some + * devices do all fingerprint processing in hardware and do not present images + * to the host computer. + * + * You can use fp_dev_supports_imaging() to see if image capture is possible + * on a particular device. Your application must be able to cope with the + * fact that libfprint does support regular operations (e.g. enrolling and + * verification) on some devices which do not provide images. + * + * \section devtype Devtypes + * Internally, the \ref drv "driver" behind a device assigns a 32-bit + * devtype identifier to the device. This cannot be used as a unique + * ID for a specific device as many devices under the same range may share + * the same devtype. The devtype may even be 0 in all cases. + * + * The only reason you may be interested in retrieving the devtype for a + * device is for the purpose of checking if some print data is compatible + * with a device. libfprint uses the devtype as one way of checking that the + * print you are verifying is compatible with the device in question - the + * devtypes must be equal. This effectively allows drivers to support more + * than one type of device where the data from each one is not compatible with + * the other. Note that libfprint does provide you with helper functions to + * determine whether a print is compatible with a device, so under most + * circumstances, you don't have to worry about devtypes at all. + */ + +/** @defgroup dscv_dev Device discovery + * These functions allow you to scan the system for supported fingerprint + * scanning hardware. This is your starting point when integrating libfprint + * into your software. + * + * When you've identified a discovered device that you would like to control, + * you can open it with fp_dev_open(). Note that discovered devices may no + * longer be available at the time when you want to open them, for example + * the user may have unplugged the device. + */ + +/** @defgroup drv Driver operations + * Internally, libfprint is abstracted into various drivers to communicate + * with the different types of supported fingerprint readers. libfprint works + * hard so that you don't have to care about these internal abstractions, + * however there are some situations where you may be interested in a little + * behind-the-scenes driver info. + * + * You can obtain the driver for a device using fp_dev_get_driver(), which + * you can pass to the functions documented on this page. + * + * \section driver_id Driver IDs + * Each driver is assigned a unique ID by the project maintainer. These + * assignments are + * + * documented on the wiki and will never change. + * + * The only reason you may be interested in retrieving the driver ID for a + * driver is for the purpose of checking if some print data is compatible + * with a device. libfprint uses the driver ID as one way of checking that + * the print you are trying to verify is compatible with the device in + * question - it ensures that enrollment data from one driver is never fed to + * another. Note that libfprint does provide you with helper functions to + * determine whether a print is compatible with a device, so under most + * circumstances, you don't have to worry about driver IDs at all. + */ + static GList *registered_drivers = NULL; void fpi_log(enum fpi_log_level level, const char *component, @@ -147,6 +397,12 @@ static struct fp_dscv_dev *discover_dev(struct usb_device *udev) return ddev; } +/** \ingroup dscv_dev + * Scans the system and returns a list of discovered devices. This is your + * entry point into finding a fingerprint reader to operate. + * \returns a NULL-terminated list of discovered devices. Must be freed with + * fp_dscv_devs_free() after use. + */ API_EXPORTED struct fp_dscv_dev **fp_discover_devs(void) { GList *tmplist = NULL; @@ -191,6 +447,12 @@ API_EXPORTED struct fp_dscv_dev **fp_discover_devs(void) return list; } +/** \ingroup dscv_dev + * Free a list of discovered devices. This function destroys the list and all + * discovered devices that it included, so make sure you have opened your + * discovered device before freeing the list. + * \param devs the list of discovered devices + */ API_EXPORTED void fp_dscv_devs_free(struct fp_dscv_dev **devs) { int i; @@ -202,11 +464,21 @@ API_EXPORTED void fp_dscv_devs_free(struct fp_dscv_dev **devs) g_free(devs); } +/** \ingroup dscv_dev + * Gets the \ref drv "driver" for a discovered device. + * \param dev the discovered device + * \returns the driver backing the device + */ API_EXPORTED struct fp_driver *fp_dscv_dev_get_driver(struct fp_dscv_dev *dev) { return dev->drv; } +/** \ingroup dscv_dev + * Gets the \ref devtype "devtype" for a discovered device. + * \param dev the discovered device + * \returns the devtype of the device + */ API_EXPORTED uint32_t fp_dscv_dev_get_devtype(struct fp_dscv_dev *dev) { return dev->devtype; @@ -225,6 +497,13 @@ enum fp_print_data_type fpi_driver_get_data_type(struct fp_driver *drv) } } +/** \ingroup dscv_dev + * Determines if a specific \ref print_data "stored print" appears to be + * compatible with a discovered device. + * \param dev the discovered device + * \param data the print for compatibility checking + * \returns 1 if the print is compatible with the device, 0 otherwise + */ API_EXPORTED int fp_dscv_dev_supports_print_data(struct fp_dscv_dev *dev, struct fp_print_data *data) { @@ -233,6 +512,13 @@ API_EXPORTED int fp_dscv_dev_supports_print_data(struct fp_dscv_dev *dev, data->type); } +/** \ingroup dscv_dev + * Determines if a specific \ref dscv_print "discovered print" appears to be + * compatible with a discovered device. + * \param dev the discovered device + * \param data the discovered print for compatibility checking + * \returns 1 if the print is compatible with the device, 0 otherwise + */ API_EXPORTED int fp_dscv_dev_supports_dscv_print(struct fp_dscv_dev *dev, struct fp_dscv_print *data) { @@ -240,6 +526,14 @@ API_EXPORTED int fp_dscv_dev_supports_dscv_print(struct fp_dscv_dev *dev, data->driver_id, data->devtype, 0); } +/** \ingroup dscv_dev + * Searches a list of discovered devices for a device that appears to be + * compatible with a \ref print_data "stored print". + * \param devs a list of discovered devices + * \param data the print under inspection + * \returns the first discovered device that appears to support the print, or + * NULL if no apparently compatible devices could be found + */ API_EXPORTED struct fp_dscv_dev *fp_dscv_dev_for_print_data(struct fp_dscv_dev **devs, struct fp_print_data *data) { @@ -252,6 +546,14 @@ API_EXPORTED struct fp_dscv_dev *fp_dscv_dev_for_print_data(struct fp_dscv_dev * return NULL; } +/** \ingroup dscv_dev + * Searches a list of discovered devices for a device that appears to be + * compatible with a \ref dscv_print "discovered print". + * \param devs a list of discovered devices + * \param print the print under inspection + * \returns the first discovered device that appears to support the print, or + * NULL if no apparently compatible devices could be found + */ API_EXPORTED struct fp_dscv_dev *fp_dscv_dev_for_dscv_print(struct fp_dscv_dev **devs, struct fp_dscv_print *print) { @@ -264,6 +566,13 @@ API_EXPORTED struct fp_dscv_dev *fp_dscv_dev_for_dscv_print(struct fp_dscv_dev * return NULL; } +/** \ingroup dev + * Opens and initialises a device. This is the function you call in order + * to convert a \ref dscv_dev "discovered device" into an actual device handle + * that you can perform operations with. + * \param ddev the discovered device to open + * \returns the opened device handle, or NULL on error + */ API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) { struct fp_dev *dev; @@ -295,6 +604,11 @@ API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) return dev; } +/** \ingroup dev + * Close a device. You must call this function when you are finished using + * a fingerprint device. + * \param dev the device to close + */ API_EXPORTED void fp_dev_close(struct fp_dev *dev) { fp_dbg(""); @@ -304,21 +618,43 @@ API_EXPORTED void fp_dev_close(struct fp_dev *dev) g_free(dev); } +/** \ingroup dev + * Get the \ref drv "driver" for a fingerprint device. + * \param dev the device + * \returns the driver controlling the device + */ API_EXPORTED struct fp_driver *fp_dev_get_driver(struct fp_dev *dev) { return dev->drv; } +/** \ingroup dev + * Gets the number of \ref enrolling "enroll stages" required to enroll a + * fingerprint with the device. + * \param dev the device + * \returns the number of enroll stages + */ API_EXPORTED int fp_dev_get_nr_enroll_stages(struct fp_dev *dev) { return dev->nr_enroll_stages; } +/** \ingroup dev + * Gets the \ref devtype "devtype" for a device. + * \param dev the device + * \returns the devtype + */ API_EXPORTED uint32_t fp_dev_get_devtype(struct fp_dev *dev) { return dev->devtype; } +/** \ingroup dev + * Determines if a stored print is compatible with a certain device. + * \param dev the device + * \param data the stored print + * \returns 1 if the print is compatible with the device, 0 if not + */ API_EXPORTED int fp_dev_supports_print_data(struct fp_dev *dev, struct fp_print_data *data) { @@ -327,6 +663,13 @@ API_EXPORTED int fp_dev_supports_print_data(struct fp_dev *dev, data->type); } +/** \ingroup dev + * Determines if a \ref dscv_print "discovered print" appears to be compatible + * with a certain device. + * \param dev the device + * \param data the discovered print + * \returns 1 if the print is compatible with the device, 0 if not + */ API_EXPORTED int fp_dev_supports_dscv_print(struct fp_dev *dev, struct fp_dscv_print *data) { @@ -334,16 +677,31 @@ API_EXPORTED int fp_dev_supports_dscv_print(struct fp_dev *dev, 0, data->driver_id, data->devtype, 0); } +/** \ingroup drv + * Retrieves the name of the driver. For example: "upekts" + * \param drv the driver + * \returns the driver name. Must not be modified or freed. + */ API_EXPORTED const char *fp_driver_get_name(struct fp_driver *drv) { return drv->name; } +/** \ingroup drv + * Retrieves a descriptive name of the driver. For example: "UPEK TouchStrip" + * \param drv the driver + * \returns the descriptive name. Must not be modified or freed. + */ API_EXPORTED const char *fp_driver_get_full_name(struct fp_driver *drv) { return drv->full_name; } +/** \ingroup drv + * Retrieves the driver ID code for a driver. + * \param drv the driver + * \returns the driver ID + */ API_EXPORTED uint16_t fp_driver_get_driver_id(struct fp_driver *drv) { return drv->id; @@ -356,11 +714,39 @@ static struct fp_img_dev *dev_to_img_dev(struct fp_dev *dev) return dev->priv; } +/** \ingroup dev + * Determines if a device has imaging capabilities. If a device has imaging + * capabilities you are able to perform imaging operations such as retrieving + * scan images using fp_dev_img_capture(). However, not all devices are + * imaging devices - some do all processing in hardware. This function will + * indicate which class a device in question falls into. + * \param dev the fingerprint device + * \returns 1 if the device is an imaging device, 0 if the device does not + * provide images to the host computer + */ API_EXPORTED int fp_dev_supports_imaging(struct fp_dev *dev) { return dev->drv->type == DRIVER_IMAGING; } +/** \ingroup dev + * Captures an \ref img "image" from a device. The returned image is the raw + * image provided by the device, you may wish to \ref img_std "standardize" it. + * + * If set, the unconditional flag indicates that the device should + * capture an image unconditionally, regardless of whether a finger is there + * or not. If unset, this function will block until a finger is detected on + * the sensor. + * + * \param dev the device + * \param unconditional whether to unconditionally capture an image, or to only capture when a finger is detected + * \param image a location to return the captured image. Must be freed with + * fp_img_free() after use. + * \return 0 on success, non-zero on error. -ENOTSUP indicates that either the + * unconditional flag was set but the device does not support this, or that the + * device does not support imaging. + * \sa fp_dev_supports_imaging() + */ API_EXPORTED int fp_dev_img_capture(struct fp_dev *dev, int unconditional, struct fp_img **image) { @@ -373,6 +759,15 @@ API_EXPORTED int fp_dev_img_capture(struct fp_dev *dev, int unconditional, return fpi_imgdev_capture(imgdev, unconditional, image); } +/** \ingroup dev + * Gets the expected width of images that will be captured from the device. + * This function will return -1 for devices that are not + * \ref imaging "imaging devices". If the width of images from this device + * can vary, 0 will be returned. + * \param dev the device + * \returns the expected image width, or 0 for variable, or -1 for non-imaging + * devices. + */ API_EXPORTED int fp_dev_get_img_width(struct fp_dev *dev) { struct fp_img_dev *imgdev = dev_to_img_dev(dev); @@ -384,6 +779,15 @@ API_EXPORTED int fp_dev_get_img_width(struct fp_dev *dev) return fpi_imgdev_get_img_width(imgdev); } +/** \ingroup dev + * Gets the expected height of images that will be captured from the device. + * This function will return -1 for devices that are not + * \ref imaging "imaging devices". If the height of images from this device + * can vary, 0 will be returned. + * \param dev the device + * \returns the expected image height, or 0 for variable, or -1 for non-imaging + * devices. + */ API_EXPORTED int fp_dev_get_img_height(struct fp_dev *dev) { struct fp_img_dev *imgdev = dev_to_img_dev(dev); @@ -395,6 +799,51 @@ API_EXPORTED int fp_dev_get_img_height(struct fp_dev *dev) return fpi_imgdev_get_img_height(imgdev); } +/** \ingroup dev + * Performs an enroll stage. See \ref enrolling for an explanation of enroll + * stages. + * + * If no enrollment is in process, this kicks of the process and runs the + * first stage. If an enrollment is already in progress, calling this + * function runs the next stage, which may well be the last. + * + * A negative error code may be returned from any stage. When this occurs, + * further calls to the enroll function will start a new enrollment process, + * i.e. a negative error code indicates that the enrollment process has been + * aborted. These error codes only ever indicate unexpected internal errors + * or I/O problems. + * + * The RETRY codes from #fp_enroll_result may be returned from any enroll + * stage. These codes indicate that the scan was not succesful in that the + * user did not position their finger correctly or similar. When a RETRY code + * is returned, the enrollment stage is not advanced, so the next call + * into this function will retry the current stage again. The current stage may + * need to be retried several times. + * + * The fp_enroll_result#FP_ENROLL_FAIL code may be returned from any enroll + * stage. This code indicates that even though the scans themselves have been + * acceptable, data processing applied to these scans produces incomprehensible + * results. In other words, the user may have been scanning a different finger + * for each stage or something like that. Like negative error codes, this + * return code indicates that the enrollment process has been aborted. + * + * The fp_enroll_result#FP_ENROLL_PASS code will only ever be returned for + * non-final stages. This return code indicates that the scan was acceptable + * and the next call into this function will advance onto the next enroll + * stage. + * + * The fp_enroll_result#FP_ENROLL_COMPLETE code will only ever be returned + * from the final enroll stage. It indicates that enrollment completed + * successfully, and that print_data has been assigned to point to the + * resultant enrollment data. The print_data parameter will not be modified + * during any other enrollment stages, hence it is actually legal to pass NULL + * as this argument for all but the final stage. + * + * \param dev the device + * \param print_data a location to return the resultant enrollment data from + * the final stage. Must be freed with fp_print_data_free() after use. + * \return negative code on error, otherwise a code from #fp_verify_result + */ API_EXPORTED int fp_enroll_finger(struct fp_dev *dev, struct fp_print_data **print_data) { @@ -462,6 +911,13 @@ API_EXPORTED int fp_enroll_finger(struct fp_dev *dev, return ret; } +/** \ingroup dev + * Performs a new scan and verify it against a previously enrolled print. + * \param dev the device to perform the scan. + * \param enrolled_print the print to verify against. Must have been previously + * enrolled with a device compatible to the device selected to perform the scan. + * \return negative code on error, otherwise a code from #fp_verify_result + */ API_EXPORTED int fp_verify_finger(struct fp_dev *dev, struct fp_print_data *enrolled_print) { @@ -517,6 +973,11 @@ API_EXPORTED int fp_verify_finger(struct fp_dev *dev, return r; } +/** \ingroup core + * Initialise libfprint. This function must be called before you attempt to + * use the library in any way. + * \return 0 on success, non-zero on error. + */ API_EXPORTED int fp_init(void) { fp_dbg(""); @@ -525,4 +986,3 @@ API_EXPORTED int fp_init(void) return 0; } - diff --git a/libfprint/data.c b/libfprint/data.c index fb380fcc..564a70df 100644 --- a/libfprint/data.c +++ b/libfprint/data.c @@ -30,6 +30,21 @@ #define DIR_PERMS 0700 +/** @defgroup print_data Stored prints + * Stored prints are represented by a structure named fp_print_data. + * Stored prints are originally obtained from an enrollment function such as + * fp_enroll_finger(). + * + * This page documents the various operations you can do with a stored print. + * Note that by default, "stored prints" are not actually stored anywhere + * except in RAM. For the simple scenarios, libfprint provides a simple API + * for you to save and load the stored prints referring to a single user in + * their home directory. For more advanced users, libfprint provides APIs for + * you to convert print data to a byte string, and to reconstruct stored prints + * from such data at a later point. You are welcome to store these byte strings + * in any fashion that suits you. + */ + /* FIXME: should free this during library shutdown */ static char *base_store = NULL; @@ -92,6 +107,15 @@ struct fp_print_data *fpi_print_data_new(struct fp_dev *dev, size_t length) fpi_driver_get_data_type(dev->drv), length); } +/** \ingroup print_data + * Convert a stored print into a unified representation inside a data buffer. + * You can then store this data buffer in any way that suits you, and load + * it back at some later time using fp_print_data_from_data(). + * \param data the stored print + * \param ret output location for the data buffer. Must be freed with free() + * after use. + * \returns the size of the freshly allocated buffer, or 0 on error. + */ API_EXPORTED size_t fp_print_data_get_data(struct fp_print_data *data, unsigned char **ret) { @@ -116,6 +140,15 @@ API_EXPORTED size_t fp_print_data_get_data(struct fp_print_data *data, return buflen; } +/** \ingroup print_data + * Load a stored print from a data buffer. The contents of said buffer must + * be the untouched contents of a buffer previously supplied to you by the + * fp_print_data_get_data() function. + * \param buf the data buffer + * \param buflen the length of the buffer + * \returns the stored print represented by the data, or NULL on error. Must + * be freed with fp_print_data_free() after use. + */ API_EXPORTED struct fp_print_data *fp_print_data_from_data(unsigned char *buf, size_t buflen) { @@ -170,6 +203,21 @@ static char *get_path_to_print(struct fp_dev *dev, enum fp_finger finger) return __get_path_to_print(dev->drv->id, dev->devtype, finger); } +/** \ingroup print_data + * Saves a stored print to disk, assigned to a specific finger. Even though + * you are limited to storing only the 10 human fingers, this is a + * per-device-type limit. For example, you can store the users right index + * finger from a DigitalPersona scanner, and you can also save the right index + * finger from a UPEK scanner. When you later come to load the print, the right + * one will be automatically selected. + * + * This function will unconditionally overwrite a fingerprint previously + * saved for the same finger and device type. The print is saved in a hidden + * directory beneath the current user's home directory. + * \param data the stored print to save to disk + * \param finger the finger that this print corresponds to + * \returns 0 on success, non-zero on error. + */ API_EXPORTED int fp_print_data_save(struct fp_print_data *data, enum fp_finger finger) { @@ -242,6 +290,7 @@ static int load_from_file(char *path, struct fp_print_data **data) gsize length; gchar *contents; GError *err = NULL; + struct fp_print_data *fdata; fp_dbg("from %s", path); g_file_get_contents(path, &contents, &length, &err); @@ -256,11 +305,28 @@ static int load_from_file(char *path, struct fp_print_data **data) return r; } - *data = fp_print_data_from_data(contents, length); + fdata = fp_print_data_from_data(contents, length); g_free(contents); + if (!fdata) + return -EIO; + *data = fdata; return 0; } +/** \ingroup print_data + * Loads a previously stored print from disk. The print must have been saved + * earlier using the fp_print_data_save() function. + * + * A return code of -ENOENT indicates that the fingerprint requested could not + * be found. Other error codes (both positive and negative) are possible for + * obscure error conditions (e.g. corruption). + * + * \param dev the device you are loading the print for + * \param finger the finger of the file you are loading + * \param data output location to put the corresponding stored print. Must be + * freed with fp_print_data_free() after use. + * \returns 0 on success, non-zero on error + */ API_EXPORTED int fp_print_data_load(struct fp_dev *dev, enum fp_finger finger, struct fp_print_data **data) { @@ -287,27 +353,89 @@ API_EXPORTED int fp_print_data_load(struct fp_dev *dev, return 0; } +/** \ingroup print_data + * Attempts to load a stored print based on a \ref dscv_print + * "discovered print" record. + * + * A return code of -ENOENT indicates that the file referred to by the + * discovered print could not be found. Other error codes (both positive and + * negative) are possible for obscure error conditions (e.g. corruption). + * + * \param print the discovered print + * \param data output location to point to the corresponding stored print. Must + * be freed with fp_print_data_free() after use. + * \returns 0 on success, non-zero on error. + */ API_EXPORTED int fp_print_data_from_dscv_print(struct fp_dscv_print *print, struct fp_print_data **data) { return load_from_file(print->path, data); } +/** \ingroup print_data + * Frees a stored print. Must be called when you are finished using the print. + * \param data the stored print to destroy + */ API_EXPORTED void fp_print_data_free(struct fp_print_data *data) { g_free(data); } +/** \ingroup print_data + * Gets the \ref driver_id "driver ID" for a stored print. The driver ID + * indicates which driver the print originally came from. The print is + * only usable with a device controlled by that driver. + * \param data the stored print + * \returns the driver ID of the driver compatible with the print + */ API_EXPORTED uint16_t fp_print_data_get_driver_id(struct fp_print_data *data) { return data->driver_id; } +/** \ingroup print_data + * Gets the \ref devtype "devtype" for a stored print. The devtype represents + * which type of device under the parent driver is compatible with the print. + * \param data the stored print + * \returns the devtype of the device range compatible with the print + */ API_EXPORTED uint32_t fp_print_data_get_devtype(struct fp_print_data *data) { return data->devtype; } +/** @defgroup dscv_print Print discovery + * The \ref print_data "stored print" documentation detailed a simple API + * for storing per-device prints for a single user, namely + * fp_print_data_save(). It also detailed a load function, + * fp_print_data_load(), but usage of this function is limited to scenarios + * where you know which device you would like to use, and you know which + * finger you are looking to verify. + * + * In other cases, it would be more useful to be able to enumerate all + * previously saved prints, potentially even before device discovery. These + * functions are designed to offer this functionality to you. + * + * Discovered prints are stored in a dscv_print structure, and you + * can use functions documented below to access some information about these + * prints. You can determine if a discovered print appears to be compatible + * with a device using functions such as fp_dscv_dev_supports_dscv_print() and + * fp_dev_supports_dscv_print(). + * + * When you are ready to use the print, you can load it into memory in the form + * of a stored print by using the fp_print_data_from_dscv_print() function. + * + * You may have noticed the use of the word "appears" in the above paragraphs. + * libfprint performs print discovery simply by examining the file and + * directory structure of libfprint's private data store. It does not examine + * the actual prints themselves. Just because a print has been discovered + * and appears to be compatible with a certain device does not necessarily mean + * that it is usable; when you come to load or use it, under unusual + * circumstances it may turn out that the print is corrupt or not for the + * device that it appeared to be. Also, it is possible that the print may have + * been deleted by the time you come to load it. + */ + static GSList *scan_dev_store_dir(char *devpath, uint16_t driver_id, uint32_t devtype, GSList *list) { @@ -389,6 +517,12 @@ static GSList *scan_driver_store_dir(char *drvpath, uint16_t driver_id, return list; } +/** \ingroup dscv_print + * Scans the users home directory and returns a list of prints that were + * previously saved using fp_print_data_save(). + * \returns a NULL-terminated list of discovered prints, must be freed with + * fp_dscv_prints_free() after use. + */ API_EXPORTED struct fp_dscv_print **fp_discover_prints(void) { GDir *dir; @@ -444,6 +578,12 @@ API_EXPORTED struct fp_dscv_print **fp_discover_prints(void) return list; } +/** \ingroup dscv_print + * Frees a list of discovered prints. This function also frees the discovered + * prints themselves, so make sure you do not use any discovered prints + * after calling this function. + * \param prints the list of discovered prints + */ API_EXPORTED void fp_dscv_prints_free(struct fp_dscv_print **prints) { int i; @@ -460,17 +600,37 @@ API_EXPORTED void fp_dscv_prints_free(struct fp_dscv_print **prints) g_free(prints); } +/** \ingroup dscv_print + * Gets the \ref driver_id "driver ID" for a discovered print. The driver ID + * indicates which driver the print originally came from. The print is only + * usable with a device controlled by that driver. + * \param print the discovered print + * \returns the driver ID of the driver compatible with the print + */ API_EXPORTED uint16_t fp_dscv_print_get_driver_id(struct fp_dscv_print *print) { return print->driver_id; } +/** \ingroup dscv_print + * Gets the \ref devtype "devtype" for a discovered print. The devtype + * represents which type of device under the parent driver is compatible + * with the print. + * \param print the discovered print + * \returns the devtype of the device range compatible with the print + */ API_EXPORTED uint32_t fp_dscv_print_get_devtype(struct fp_dscv_print *print) { return print->devtype; } +/** \ingroup dscv_print + * Gets the finger code for a discovered print. + * \param print discovered print + * \returns a finger code from #fp_finger + */ API_EXPORTED enum fp_finger fp_dscv_print_get_finger(struct fp_dscv_print *print) { return print->finger; } + diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 3164b9c4..6e881da3 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -31,17 +31,23 @@ struct fp_print_data; struct fp_img; /* misc/general stuff */ + +/** \ingroup print_data + * Numeric codes used to refer to fingers (and thumbs) of a human. These are + * purposely not available as strings, to avoid getting the library tangled up + * in localization efforts. + */ enum fp_finger { - LEFT_THUMB = 1, - LEFT_INDEX, - LEFT_MIDDLE, - LEFT_RING, - LEFT_LITTLE, - RIGHT_THUMB, - RIGHT_INDEX, - RIGHT_MIDDLE, - RIGHT_RING, - RIGHT_LITTLE, + LEFT_THUMB = 1, /** thumb (left hand) */ + LEFT_INDEX, /** index finger (left hand) */ + LEFT_MIDDLE, /** middle finger (left hand) */ + LEFT_RING, /** ring finger (left hand) */ + LEFT_LITTLE, /** little finger (left hand) */ + RIGHT_THUMB, /** thumb (right hand) */ + RIGHT_INDEX, /** index finger (right hand) */ + RIGHT_MIDDLE, /** middle finger (right hand) */ + RIGHT_RING, /** ring finger (right hand) */ + RIGHT_LITTLE, /** little finger (right hand) */ }; /* Drivers */ @@ -90,26 +96,65 @@ int fp_dev_img_capture(struct fp_dev *dev, int unconditional, int fp_dev_get_img_width(struct fp_dev *dev); int fp_dev_get_img_height(struct fp_dev *dev); -/* Enrollment */ +/** \ingroup dev + * Enrollment result codes returned from fp_enroll_finger(). + * Result codes with RETRY in the name suggest that the scan failed due to + * user error. Applications will generally want to inform the user of the + * problem and then retry the enrollment stage. For more info on the semantics + * of interpreting these result codes and tracking enrollment process, see + * \ref enrolling. + */ enum fp_enroll_result { + /** Enrollment completed successfully, the enrollment data has been + * returned to the caller. */ FP_ENROLL_COMPLETE = 1, + /** Enrollment failed due to incomprehensible data; this may occur when + * the user scans a different finger on each enroll stage. */ FP_ENROLL_FAIL, + /** Enroll stage passed; more stages are need to complete the process. */ FP_ENROLL_PASS, + /** The enrollment scan did not succeed due to poor scan quality or + * other general user scanning problem. */ FP_ENROLL_RETRY = 100, + /** The enrollment scan did not succeed because the finger swipe was + * too short. */ FP_ENROLL_RETRY_TOO_SHORT, + /** The enrollment scan did not succeed because the finger was not + * centered on the scanner. */ FP_ENROLL_RETRY_CENTER_FINGER, + /** The verification scan did not succeed due to quality or pressure + * problems; the user should remove their finger from the scanner before + * retrying. */ FP_ENROLL_RETRY_REMOVE_FINGER, }; int fp_enroll_finger(struct fp_dev *dev, struct fp_print_data **print_data); -/* Verification */ +/** \ingroup dev + * Verification result codes returned from fp_verify_finger(). + * Result codes with RETRY in the name suggest that the scan failed due to + * user error. Applications will generally want to inform the user of the + * problem and then retry the verify operation. + */ enum fp_verify_result { + /** The verification scan completed successfully, but the newly scanned + * fingerprint does not match the fingerprint being verified against. */ FP_VERIFY_NO_MATCH = 0, + /** The verification scan completed successfully and the newly scanned + * fingerprint does match the fingerprint being verified. */ FP_VERIFY_MATCH = 1, + /** The verification scan did not succeed due to poor scan quality or + * other general user scanning problem. */ FP_VERIFY_RETRY = FP_ENROLL_RETRY, + /** The verification scan did not succeed because the finger swipe was + * too short. */ FP_VERIFY_RETRY_TOO_SHORT = FP_ENROLL_RETRY_TOO_SHORT, + /** The verification scan did not succeed because the finger was not + * centered on the scanner. */ FP_VERIFY_RETRY_CENTER_FINGER = FP_ENROLL_RETRY_CENTER_FINGER, + /** The verification scan did not succeed due to quality or pressure + * problems; the user should remove their finger from the scanner before + * retrying. */ FP_VERIFY_RETRY_REMOVE_FINGER = FP_ENROLL_RETRY_REMOVE_FINGER, }; diff --git a/libfprint/img.c b/libfprint/img.c index f421c36d..4e376d25 100644 --- a/libfprint/img.c +++ b/libfprint/img.c @@ -28,6 +28,23 @@ #include "nbis/include/bozorth.h" #include "nbis/include/lfs.h" +/** @defgroup img Image operations + * libfprint offers several ways of retrieving images from imaging devices, + * one example being the fp_dev_img_capture() function. The functions + * documented below allow you to work with such images. + * + * \section img_fmt Image format + * All images are represented as 8-bit greyscale data. + * + * \section img_std Image standardization + * In some contexts, images you are provided through libfprint are raw images + * from the hardware. The orientation of these varies from device-to-device, + * as does the color scheme (black-on-white or white-on-black?). libfprint + * provides the fp_img_standardize function to convert images into standard + * form, which is defined to be: finger flesh as black on white surroundings, + * natural upright orientation. + */ + struct fp_img *fpi_img_new(size_t length) { struct fp_img *img = g_malloc(sizeof(*img) + length); @@ -66,26 +83,53 @@ struct fp_img *fpi_img_resize(struct fp_img *img, size_t newsize) return g_realloc(img, sizeof(*img) + newsize); } +/** \ingroup img + * Frees an image. Must be called when you are finished working with an image. + * \param img the image to destroy + */ API_EXPORTED void fp_img_free(struct fp_img *img) { g_free(img); } +/** \ingroup img + * Gets the pixel height of an image. + * \param img an image + * \returns the height of the image + */ API_EXPORTED int fp_img_get_height(struct fp_img *img) { return img->height; } +/** \ingroup img + * Gets the pixel width of an image. + * \param img an image + * \returns the width of the image + */ API_EXPORTED int fp_img_get_width(struct fp_img *img) { return img->width; } +/** \ingroup img + * Gets the greyscale data for an image. This data must not be modified or + * freed, and must not be used after fp_img_free() has been called. + * \param img an image + * \returns a pointer to libfprint's internal data for the image + */ API_EXPORTED unsigned char *fp_img_get_data(struct fp_img *img) { return img->data; } +/** \ingroup img + * A quick convenience function to save an image to a file in + * PGM format. + * \param img the image to save + * \param path the path to save the image. Existing files will be overwritten. + * \returns 0 on success, non-zero on error. + */ API_EXPORTED int fp_img_save_to_file(struct fp_img *img, char *path) { FILE *fd = fopen(path, "w"); @@ -159,6 +203,13 @@ static void invert_colors(struct fp_img *img) img->data[i] = 0xff - img->data[i]; } +/** \ingroup img + * \ref img_std "Standardizes" an image by normalizing its orientation, colors, + * etc. It is safe to call this multiple times on an image, libfprint keeps + * track of the work it needs to do to make an image standard and will not + * perform these operations more than once for a given image. + * \param img the image to standardize + */ API_EXPORTED void fp_img_standardize(struct fp_img *img) { if (img->flags & FP_IMG_V_FLIPPED) { From cbe1111e4e68702ac3d1b23c4a65b81052f0656c Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sun, 4 Nov 2007 18:57:44 +0000 Subject: [PATCH 050/184] uru4000: handle images without headers While testing the new code on my MS keyboard, I found some strange conditions where occasionally, the device will stop providing images headers until it is replugged. Detect and work around this when it happens. --- libfprint/drivers/uru4000.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index ef9746e0..0fecfc9d 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -305,6 +305,7 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, int r; struct fp_img *img; size_t image_size = DATABLK1_RQLEN + DATABLK2_EXPECT - CAPTURE_HDRLEN; + int hdr_skip = CAPTURE_HDRLEN; r = set_mode(dev, MODE_CAPTURE); if (r < 0) @@ -338,13 +339,20 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, fp_err("part 2 capture failed, error %d", r); goto err; } else if (r != DATABLK2_EXPECT) { - fp_err("unexpected part 2 capture size (%d)", r); - r = -EIO; - goto err; + if (r == DATABLK2_EXPECT - CAPTURE_HDRLEN) { + /* this is rather odd, but it happens sometimes with my MS + * keyboard */ + fp_dbg("got image with no header!"); + hdr_skip = 0; + } else { + fp_err("unexpected part 2 capture size (%d)", r); + r = -EIO; + goto err; + } } /* remove header and shrink allocation */ - g_memmove(img->data, img->data + CAPTURE_HDRLEN, image_size); + g_memmove(img->data, img->data + hdr_skip, image_size); img = fpi_img_resize(img, image_size); img->flags = FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED | FP_IMG_COLORS_INVERTED; From f733ddcc3b3748a73a3c63865be681af4fc5ed12 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sun, 4 Nov 2007 19:01:15 +0000 Subject: [PATCH 051/184] uru4000: retry scanner powerup 3 times When we include the await_finger_off procedure (i.e. set mode 12), the current power-up code is unreliable - no 56aa interrupt arrives sometimes. Comparing the F0 data and hwstat at this point between a working and a non-working run yields no differences. Work around this issue by retrying power-on 3 times. --- libfprint/drivers/uru4000.c | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index 0fecfc9d..8bdb27c4 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -188,8 +188,10 @@ static int get_irq(struct fp_img_dev *dev, unsigned char *buf, int timeout) int r; int infinite_timeout = 0; - if (timeout == 0) + if (timeout == 0) { infinite_timeout = 1; + timeout = 1000; + } /* Darwin and Linux behave inconsistently with regard to infinite timeouts. * Linux accepts a timeout value of 0 as infinite timeout, whereas darwin @@ -198,16 +200,13 @@ static int get_irq(struct fp_img_dev *dev, unsigned char *buf, int timeout) * See http://thread.gmane.org/gmane.comp.lib.libusb.devel.general/1315 */ retry: - r = usb_interrupt_read(dev->udev, EP_INTR, buf, IRQ_LENGTH, 1000); - if (r == -ETIMEDOUT && - ((!infinite_timeout && timeout > 0) || infinite_timeout)) { - fp_dbg("timeout, retry"); - timeout--; + r = usb_interrupt_read(dev->udev, EP_INTR, buf, IRQ_LENGTH, timeout); + if (r == -ETIMEDOUT && infinite_timeout) goto retry; - } if (r < 0) { - fp_err("interrupt read failed, error %d", r); + if (r != -ETIMEDOUT) + fp_err("interrupt read failed, error %d", r); return r; } else if (r < IRQ_LENGTH) { fp_err("received %d byte IRQ!?", r); @@ -367,6 +366,7 @@ static int do_init(struct fp_img_dev *dev) { unsigned char status; unsigned char tmp; + int timeouts = 0; int i; int r; @@ -440,11 +440,19 @@ retry: return -EIO; } - r = get_irq_with_type(dev, IRQDATA_SCANPWR_ON, 5); - if (r == GET_IRQ_OVERFLOW) + r = get_irq_with_type(dev, IRQDATA_SCANPWR_ON, 400); + if (r == GET_IRQ_OVERFLOW) { goto retry; - else - return r; + } else if (r == -ETIMEDOUT) { + timeouts++; + if (timeouts <= 3) { + fp_dbg("scan power up timeout, retrying..."); + goto retry; + } else { + fp_err("could not power up scanner after 3 attempts"); + } + } + return r; } static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) From f498fcd1eac49b2d5cee6285d6e16e0cd1498f7c Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sun, 4 Nov 2007 19:10:23 +0000 Subject: [PATCH 052/184] Fix img_capture_continuous build Also enable it in the default development build --- autogen.sh | 2 +- examples/img_capture_continuous.c | 13 +++++-------- libfprint/drivers/uru4000.c | 2 +- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/autogen.sh b/autogen.sh index 7d368f84..5499285b 100755 --- a/autogen.sh +++ b/autogen.sh @@ -5,4 +5,4 @@ autoheader || exit 1 autoconf || exit 1 automake -a -c || exit 1 ./configure --enable-maintainer-mode --enable-examples-build \ - --enable-debug-log $* + --enable-x11-examples-build --enable-debug-log $* diff --git a/examples/img_capture_continuous.c b/examples/img_capture_continuous.c index ca67b33d..b00bb14f 100644 --- a/examples/img_capture_continuous.c +++ b/examples/img_capture_continuous.c @@ -140,7 +140,6 @@ int main(void) struct fp_dscv_dev *ddev; struct fp_dscv_dev **discovered_devs; struct fp_dev *dev; - struct fp_img_dev *imgdev; int img_width; int img_height; int standardize = 0; @@ -170,15 +169,13 @@ int main(void) exit(1); } - imgdev = fp_dev_to_img_dev(dev); - if (!imgdev) { - fprintf(stderr, "could not get image dev, is this an imaging " - "device?\n"); + if (!fp_dev_supports_imaging(dev)) { + fprintf(stderr, "this device does not have imaging capabilities.\n"); goto out; } - img_width = fp_imgdev_get_img_width(imgdev); - img_height = fp_imgdev_get_img_height(imgdev); + img_width = fp_dev_get_img_width(dev); + img_height = fp_dev_get_img_height(dev); framebuffer = malloc(img_width * img_height * 2); if (!framebuffer) goto out; @@ -211,7 +208,7 @@ int main(void) while (1) { /* event loop */ struct fp_img *img; - r = fp_imgdev_capture(imgdev, 1, &img); + r = fp_dev_img_capture(dev, 1, &img); if (r) { fprintf(stderr, "image capture failed, code %d\n", r); goto out; diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index 8bdb27c4..e91e16b2 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -440,7 +440,7 @@ retry: return -EIO; } - r = get_irq_with_type(dev, IRQDATA_SCANPWR_ON, 400); + r = get_irq_with_type(dev, IRQDATA_SCANPWR_ON, 300); if (r == GET_IRQ_OVERFLOW) { goto retry; } else if (r == -ETIMEDOUT) { From 8e7afef736711d81a4f33b17800b8e132ac251d7 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sun, 4 Nov 2007 21:12:48 +0000 Subject: [PATCH 053/184] uru4000: add Digital Persona U.are.U 4000 support My UareU4000 device isn't working properly -- only seeing an all-white image and no finger-on detection, however I think this code should work for working devices. --- libfprint/drivers/uru4000.c | 57 +++++++++++++++++++++++++++++++------ 1 file changed, 48 insertions(+), 9 deletions(-) diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index e91e16b2..56ac3981 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -50,6 +50,7 @@ enum { enum { REG_HWSTAT = 0x07, REG_MODE = 0x4e, + FIRMWARE_START = 0x100, }; enum { @@ -77,27 +78,28 @@ static const struct uru4k_dev_profile { } uru4k_dev_info[] = { [MS_KBD] = { .name = "Microsoft Keyboard with Fingerprint Reader", - .firmware_start = 0x100, - .fw_enc_offset = 0x42b, + .fw_enc_offset = 0x411, }, [MS_INTELLIMOUSE] = { .name = "Microsoft Wireless IntelliMouse with Fingerprint Reader", - .firmware_start = 0x100, - .fw_enc_offset = 0x42b, + .fw_enc_offset = 0x411, }, [MS_STANDALONE] = { .name = "Microsoft Fingerprint Reader", - .firmware_start = 0x100, - .fw_enc_offset = 0x42b, + .fw_enc_offset = 0x411, + }, + [DP_URU4000] = { + .name = "Digital Persona U.are.U 4000", + .fw_enc_offset = 0x693, }, [DP_URU4000B] = { .name = "Digital Persona U.are.U 4000B", - .firmware_start = 0x100, - .fw_enc_offset = 0x42b, + .fw_enc_offset = 0x411, }, }; struct uru4k_dev { + const struct uru4k_dev_profile *profile; uint8_t interface; }; @@ -362,6 +364,36 @@ err: return r; } +static int fix_firmware(struct fp_img_dev *dev) +{ + struct uru4k_dev *urudev = dev->priv; + uint32_t enc_addr = FIRMWARE_START + urudev->profile->fw_enc_offset; + unsigned char val, new; + int r; + + r = usb_control_msg(dev->udev, 0xc0, 0x0c, enc_addr, 0, &val, 1, + CTRL_TIMEOUT); + if (r < 0) + return r; + + fp_dbg("encryption byte at %x reads %02x", enc_addr, val); + if (val != 0x07 && val != 0x17) + fp_dbg("strange encryption byte value, please report this"); + + new = val & 0xef; + //new = 0x17; + if (new == val) + return 0; + + r = usb_control_msg(dev->udev, 0x40, 0x04, enc_addr, 0, &new, 1, + CTRL_TIMEOUT); + if (r < 0) + return r; + + fp_dbg("fixed encryption byte to %02x", new); + return 1; +} + static int do_init(struct fp_img_dev *dev) { unsigned char status; @@ -411,7 +443,10 @@ retry: return r; } - /* FIXME fix firmware (disable encryption) */ + + r = fix_firmware(dev); + if (r < 0) + return r; /* Power up device and wait for interrupt notification */ /* The combination of both modifying firmware *and* doing C-R auth on @@ -519,6 +554,7 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) } urudev = g_malloc0(sizeof(*urudev)); + urudev->profile = &uru4k_dev_info[driver_data]; urudev->interface = iface_desc->bInterfaceNumber; dev->priv = urudev; @@ -553,6 +589,9 @@ static const struct usb_id id_table[] = { /* ms fp rdr (standalone) */ { .vendor = 0x045e, .product = 0x00bd, .driver_data = MS_STANDALONE }, + /* dp uru4000 (standalone) */ + { .vendor = 0x05ba, .product = 0x0007, .driver_data = DP_URU4000 }, + /* dp uru4000b (standalone) */ { .vendor = 0x05ba, .product = 0x000a, .driver_data = DP_URU4000B }, From e1a25eeb672fdc0de2f1bb019b234587138b37f1 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Thu, 8 Nov 2007 13:41:52 +0000 Subject: [PATCH 054/184] Doc update --- HACKING | 51 +++++++++++++++++++++++++++++++++++++++++++++++++ README | 19 +++++++++++++++--- THANKS | 2 ++ TODO | 1 - doc/Makefile.am | 6 +++--- 5 files changed, 72 insertions(+), 7 deletions(-) diff --git a/HACKING b/HACKING index 43027e4b..fcd3e19d 100644 --- a/HACKING +++ b/HACKING @@ -31,4 +31,55 @@ up with 2 APIs: 1. The external-facing API for applications 2. The internal API for fingerprint drivers +Non-static functions which are intended for internal use only are prepended +with the "fpi_" prefix. + + +API stability +============= + +No API stability has been promised to anyone: go wild, there's no issue with +breaking APIs at this point in time. + + +Portability +=========== + +libfprint is primarily written for Linux. However, I'm interested in +supporting efforts to port this to other operating systems too. + +You should ensure code is portable wherever possible. Try and use GLib rather +than OS-specific features. + +Endianness must be considered in all code. libfprint must support both big- +and little-endian systems. + + +Coding Style +============ + +This project follows Linux kernel coding style but with a tab width of 4. + + +Documentation +============= + +All additions of public API functions must be accompanied with doxygen +comments. + +All changes which potentially change the behaviour of the public API must +be reflected by updating the appropriate doxygen comments. + + +Contributing +============ + +Patches should be sent to the fprint mailing list detailed on the website. +A subscription is required. + +Information about libfprint development repositories can be found here: +http://www.reactivated.net/fprint/Libfprint_development + +If you're looking for ideas for things to work on, look at the TODO file or +grep the source code for FIXMEs. diff --git a/README b/README index c9ba9d59..2696662d 100644 --- a/README +++ b/README @@ -1,17 +1,30 @@ libfprint +========= + +libfprint is part of the fprint project: http://www.reactivated.net/fprint +libfprint was originally developed as part of an academic project at the +University of Manchester with the aim of hiding differences between different +consumer fingerprint scanners and providing a single uniform API to application +developers. The ultimate goal of the fprint project is to make fingerprint +scanners widely and easily usable under common Linux environments. + +For more information on libfprint, supported devices, API documentation, etc., +see the homepage: +http://www.reactivated.net/fprint/Libfprint + libfprint is primarily licensed under the GNU LGPL. HOWEVER, THIS PRERELEASE VERSION INCLUDES GPL CODE FROM LIBTHINKFINGER, therefore distribution is subject to both the terms of the LGPL (see COPYING) *and* the GPL (see COPYING.GPL). +At release time, I will contact libthinkfinger authors and see if they will +be happy to relicense. I expect they will. + libfprint includes code from NIST's NBIS software distribution: http://fingerprint.nist.gov/NBIS/index.html We include bozorth3 from the US export controlled distribution. We have determined that it is fine to ship bozorth3 in an open source project, see http://reactivated.net/fprint/US_export_control -At release time, I will contact libthinkfinger authors and see if they will -be happy to relicense. I expect they will. - diff --git a/THANKS b/THANKS index 6db35741..76c08171 100644 --- a/THANKS +++ b/THANKS @@ -4,3 +4,5 @@ Joaquin Custodio - hardware donations TimeTrex (http://www.timetrex.com/) - hardware donations Craig Watson (NIST) James Vasile (SFLC) +Toby Howard (University of Manchester) +Seemant Kulleen diff --git a/TODO b/TODO index 9b70a181..74a0b6ef 100644 --- a/TODO +++ b/TODO @@ -1,7 +1,6 @@ LIBRARY ======= identification -external API documentation test suite against NFIQ compliance set make library optionally asynchronous and maybe thread-safe nbis cleanups diff --git a/doc/Makefile.am b/doc/Makefile.am index 3367df38..7f200a0b 100644 --- a/doc/Makefile.am +++ b/doc/Makefile.am @@ -4,7 +4,7 @@ docs: doxygen.cfg doxygen $^ docs-upload: docs - ln -s html fprint-api - ncftpput -f ~/.ncftp/reactivated -m -R httpdocs fprint-api/ - rm -f fprint-api + ln -s html api + ncftpput -f ~/.ncftp/reactivated -m -R httpdocs/fprint api/ + rm -f api From b9238e8b8a308f15fc0cadd2217ed105aab0cdde Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Thu, 8 Nov 2007 13:56:21 +0000 Subject: [PATCH 055/184] Support images with variable dimensions For example, AES2501 returns images that vary in height. --- examples/img_capture_continuous.c | 5 ++++ libfprint/imgdev.c | 46 +++++++++++++++++++++---------- 2 files changed, 36 insertions(+), 15 deletions(-) diff --git a/examples/img_capture_continuous.c b/examples/img_capture_continuous.c index b00bb14f..5079fe70 100644 --- a/examples/img_capture_continuous.c +++ b/examples/img_capture_continuous.c @@ -176,6 +176,11 @@ int main(void) img_width = fp_dev_get_img_width(dev); img_height = fp_dev_get_img_height(dev); + if (img_width <= 0 || img_height <= 0) { + fprintf(stderr, "this device returns images with variable dimensions," + " this example does not support that.\n"); + goto out; + } framebuffer = malloc(img_width * img_height * 2); if (!framebuffer) goto out; diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index 18ba789d..6ccfd65d 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -73,13 +73,14 @@ int fpi_imgdev_get_img_height(struct fp_img_dev *imgdev) } int fpi_imgdev_capture(struct fp_img_dev *imgdev, int unconditional, - struct fp_img **image) + struct fp_img **_img) { struct fp_driver *drv = imgdev->dev->drv; struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); + struct fp_img *img; int r; - if (!image) { + if (!_img) { fp_err("no image pointer given"); return -EINVAL; } @@ -107,35 +108,50 @@ int fpi_imgdev_capture(struct fp_img_dev *imgdev, int unconditional, } } - r = imgdrv->capture(imgdev, unconditional, image); + r = imgdrv->capture(imgdev, unconditional, &img); if (r) { fp_err("capture failed with error %d", r); return r; } + if (img == NULL) { + fp_err("capture succeeded but no image returned?"); + return -ENODATA; + } + if (!unconditional && imgdrv->await_finger_off) { r = imgdrv->await_finger_off(imgdev); if (r) { fp_err("await_finger_off failed with error %d", r); + fp_img_free(img); return r; } } - if (r == 0) { - struct fp_img *img = *image; - if (img == NULL) { - fp_err("capture succeeded but no image returned?"); - return -ENODATA; - } + if (imgdrv->img_width > 0) { img->width = imgdrv->img_width; - img->height = imgdrv->img_height; - if (!fpi_img_is_sane(img)) { - fp_err("image is not sane!"); - return -EIO; - } + } else if (img->width <= 0) { + fp_err("no image width assigned"); + goto err; } - return r; + if (imgdrv->img_height > 0) { + img->height = imgdrv->img_height; + } else if (img->height <= 0) { + fp_err("no image height assigned"); + goto err; + } + + if (!fpi_img_is_sane(img)) { + fp_err("image is not sane!"); + goto err; + } + + *_img = img; + return 0; +err: + fp_img_free(img); + return -EIO; } #define MIN_ACCEPTABLE_MINUTIAE 10 From a73cbc10fb2ab3ded4551707b772a4c8b88ec8c4 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Fri, 9 Nov 2007 13:47:32 +0000 Subject: [PATCH 056/184] aes4000: image quality improvements The windows driver takes one sample at the previous register settings and then changes some registers before resamping (and getting much better images). The exact changes that it makes seem to vary, perhaps based on the histogram. Anyway, this is an approximation of the settings used for the 2nd sample which should help matching results. --- libfprint/drivers/aes4000.c | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/libfprint/drivers/aes4000.c b/libfprint/drivers/aes4000.c index 5ad08d2a..8f732b3c 100644 --- a/libfprint/drivers/aes4000.c +++ b/libfprint/drivers/aes4000.c @@ -102,17 +102,17 @@ static const struct aes4000_regwrite { { 0x85, 0x3d }, /* set calibration capacitance */ { 0x86, 0x03 }, /* detect drive voltage */ { 0x87, 0x01 }, /* set detection frequency to 125khz */ - { 0x88, 0x03 }, /* set column scan period */ - { 0x89, 0x03 }, /* set measure drive */ - { 0x8a, 0x32 }, /* set measure frequency and sense amplifier bias */ + { 0x88, 0x02 }, /* set column scan period */ + { 0x89, 0x02 }, /* set measure drive */ + { 0x8a, 0x33 }, /* set measure frequency and sense amplifier bias */ { 0x8b, 0x33 }, /* set matrix pattern */ - { 0x8c, 0x0b }, /* set demodulation phase 1 */ + { 0x8c, 0x0f }, /* set demodulation phase 1 */ { 0x8d, 0x04 }, /* set demodulation phase 2 */ - { 0x8e, 0x33 }, /* set sensor gain */ - { 0x8f, 0x03 }, /* set image parameters */ - { 0x90, 0x0f }, /* carrier offset null */ - { 0x91, 0x03 }, /* set A/D reference high */ - { 0x92, 0x03 }, /* set A/D reference low */ + { 0x8e, 0x23 }, /* set sensor gain */ + { 0x8f, 0x07 }, /* set image parameters */ + { 0x90, 0x00 }, /* carrier offset null */ + { 0x91, 0x1c }, /* set A/D reference high */ + { 0x92, 0x08 }, /* set A/D reference low */ { 0x93, 0x00 }, /* set start row to 0 */ { 0x94, 0x05 }, /* set end row to 5 */ { 0x95, 0x00 }, /* set start column to 0 */ From e3451158e9e1d0d2cb1f81197a8e392ac4294ec0 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Thu, 8 Nov 2007 17:04:45 +0000 Subject: [PATCH 057/184] Custom image resizing mindtct appears to completely ignore the pixels-per-mm input parameter (ippmm). When processing AES4000 images, the binarized image is completely mangled and a lot of ridge information is lost. Resizing the AES4000's small images results in a huge imaging performance gain. We use imagemagick for the resizing, as it's resizing code resamples the image too (smoothing it out), which further improves performance. --- configure.ac | 4 +++ libfprint/Makefile.am | 4 +-- libfprint/drivers/aes4000.c | 1 + libfprint/fp_internal.h | 1 + libfprint/img.c | 61 ++++++++++++++++++++++++++++++++++++- 5 files changed, 68 insertions(+), 3 deletions(-) diff --git a/configure.ac b/configure.ac index e6b501a7..55f342a3 100644 --- a/configure.ac +++ b/configure.ac @@ -25,6 +25,10 @@ PKG_CHECK_MODULES(GLIB, "glib-2.0") AC_SUBST(GLIB_CFLAGS) AC_SUBST(GLIB_LIBS) +PKG_CHECK_MODULES(IMAGEMAGICK, "ImageMagick") +AC_SUBST(IMAGEMAGICK_CFLAGS) +AC_SUBST(IMAGEMAGICK_LIBS) + # Examples build AC_ARG_ENABLE([examples-build], [AS_HELP_STRING([--enable-examples-build], [build example applications (default n)])], diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index ea07a414..18c0c524 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -43,9 +43,9 @@ NBIS_SRC = \ nbis/mindtct/sort.c \ nbis/mindtct/util.c -libfprint_la_CFLAGS = -fvisibility=hidden -I$(srcdir)/nbis/include $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) $(AM_CFLAGS) +libfprint_la_CFLAGS = -fvisibility=hidden -I$(srcdir)/nbis/include $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) $(IMAGEMAGICK_CFLAGS) $(AM_CFLAGS) libfprint_la_LDFLAGS = -version-info @lt_major@:@lt_revision@:@lt_age@ -libfprint_la_LIBADD = -lm $(LIBUSB_LIBS) $(GLIB_LIBS) +libfprint_la_LIBADD = -lm $(LIBUSB_LIBS) $(GLIB_LIBS) $(IMAGEMAGICK_LIBS) libfprint_la_SOURCES = \ fp_internal.h \ diff --git a/libfprint/drivers/aes4000.c b/libfprint/drivers/aes4000.c index 8f732b3c..58e1e76e 100644 --- a/libfprint/drivers/aes4000.c +++ b/libfprint/drivers/aes4000.c @@ -218,6 +218,7 @@ struct fp_img_driver aes4000_driver = { .flags = 0, .img_height = 96, .img_width = 96, + .enlarge_factor = 3, .init = dev_init, .exit = dev_exit, diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 361969d5..f32fc557 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -126,6 +126,7 @@ struct fp_img_driver { uint16_t flags; int img_width; int img_height; + unsigned int enlarge_factor; /* Device operations */ int (*init)(struct fp_img_dev *dev, unsigned long driver_data); diff --git a/libfprint/img.c b/libfprint/img.c index 4e376d25..72504ae8 100644 --- a/libfprint/img.c +++ b/libfprint/img.c @@ -23,6 +23,7 @@ #include #include +#include #include "fp_internal.h" #include "nbis/include/bozorth.h" @@ -226,6 +227,50 @@ API_EXPORTED void fp_img_standardize(struct fp_img *img) } } +static struct fp_img *im_resize(struct fp_img *img, unsigned int factor) +{ + Image *mimg; + Image *resized; + ExceptionInfo *exception; + MagickBooleanType ret; + int new_width = img->width * factor; + int new_height = img->height * factor; + struct fp_img *newimg; + + /* It is possible to implement resizing using a simple algorithm, however + * we use ImageMagick because it applies some kind of smoothing to the + * result, which improves matching performances in my experiments. */ + + if (!IsMagickInstantiated()) + MagickCoreGenesis(NULL, MagickFalse); + + exception = AcquireExceptionInfo(); + + mimg = ConstituteImage(img->width, img->height, "I", CharPixel, img->data, exception); + + ClearMagickException(exception); + resized = ResizeImage(mimg, new_width, new_height, 0, 1.0, exception); + + newimg = fpi_img_new(new_width * new_height); + newimg->width = new_width; + newimg->height = new_height; + newimg->flags = img->flags; + + ClearMagickException(exception); + ret = ExportImagePixels(resized, 0, 0, new_width, new_height, "I", + CharPixel, newimg->data, exception); + if (ret != MagickTrue) { + fp_err("export failed"); + return NULL; + } + + DestroyImage(mimg); + DestroyImage(resized); + DestroyExceptionInfo(exception); + + return newimg; +} + /* Based on write_minutiae_XYTQ and bz_load */ static void minutiae_to_xyt(MINUTIAE *minutiae, int bwidth, int bheight, unsigned char *buf) @@ -261,7 +306,7 @@ static void minutiae_to_xyt(MINUTIAE *minutiae, int bwidth, xyt->nrows = nmin; } -int fpi_img_detect_minutiae(struct fp_img_dev *imgdev, struct fp_img *img, +int fpi_img_detect_minutiae(struct fp_img_dev *imgdev, struct fp_img *_img, struct fp_print_data **ret) { MINUTIAE *minutiae; @@ -272,8 +317,20 @@ int fpi_img_detect_minutiae(struct fp_img_dev *imgdev, struct fp_img *img, unsigned char *bdata; int bw, bh, bd; struct fp_print_data *print; + struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(imgdev->dev->drv); + struct fp_img *img = _img; + int free_img = 0; GTimer *timer; + if (imgdrv->enlarge_factor) { + /* FIXME: enlarge_factor should not exist! instead, MINDTCT should + * actually look at the value of the pixels-per-mm parameter and + * figure out itself when the image needs to be treated as if it + * were bigger. */ + img = im_resize(_img, imgdrv->enlarge_factor); + free_img = 1; + } + /* 25.4 mm per inch */ timer = g_timer_new(); r = get_minutiae(&minutiae, &quality_map, &direction_map, @@ -284,6 +341,8 @@ int fpi_img_detect_minutiae(struct fp_img_dev *imgdev, struct fp_img *img, g_timer_stop(timer); fp_dbg("minutiae scan completed in %f secs", g_timer_elapsed(timer, NULL)); g_timer_destroy(timer); + if (free_img) + g_free(img); if (r) { fp_err("get minutiae failed, code %d", r); return r; From 71e4bb39ec214883bc707b5ba2b95423f1fd05b6 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Fri, 9 Nov 2007 14:57:42 +0000 Subject: [PATCH 058/184] Allow drivers to specify custom bz3 match threshold aes4000 detects fewer minutiae and hence returns lower scores. --- libfprint/drivers/aes4000.c | 3 +++ libfprint/fp_internal.h | 1 + libfprint/imgdev.c | 9 ++++++++- 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/libfprint/drivers/aes4000.c b/libfprint/drivers/aes4000.c index 58e1e76e..8198132d 100644 --- a/libfprint/drivers/aes4000.c +++ b/libfprint/drivers/aes4000.c @@ -220,6 +220,9 @@ struct fp_img_driver aes4000_driver = { .img_width = 96, .enlarge_factor = 3, + /* temporarily lowered until image quality improves */ + .bz3_threshold = 9, + .init = dev_init, .exit = dev_exit, .capture = capture, diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index f32fc557..3ed42f2c 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -127,6 +127,7 @@ struct fp_img_driver { int img_width; int img_height; unsigned int enlarge_factor; + int bz3_threshold; /* Device operations */ int (*init)(struct fp_img_dev *dev, unsigned long driver_data); diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index 6ccfd65d..d8d651a9 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -186,12 +186,16 @@ int img_dev_enroll(struct fp_dev *dev, gboolean initial, int stage, return FP_ENROLL_COMPLETE; } +#define BOZORTH3_DEFAULT_THRESHOLD 40 + static int img_dev_verify(struct fp_dev *dev, struct fp_print_data *enrolled_print) { struct fp_img_dev *imgdev = dev->priv; + struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(dev->drv); struct fp_img *img; struct fp_print_data *print; + int match_score = imgdrv->bz3_threshold; int r; r = fpi_imgdev_capture(imgdev, 0, &img); @@ -209,11 +213,14 @@ static int img_dev_verify(struct fp_dev *dev, return FP_VERIFY_RETRY; } + if (match_score == 0) + match_score = BOZORTH3_DEFAULT_THRESHOLD; + r = fpi_img_compare_print_data(enrolled_print, print); fp_print_data_free(print); if (r < 0) return r; - if (r >= 40) + if (r >= match_score) return FP_VERIFY_MATCH; else return FP_VERIFY_NO_MATCH; From a76f55db0d668278e1a8108a203e685b65400458 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 12 Nov 2007 23:32:17 +0000 Subject: [PATCH 059/184] upekts relicensing Pavel Machek and Timo Hoenig agreed to relicense their work. Thanks guys, I look forward to working together. --- COPYING | 10 -- COPYING.GPL | 340 ------------------------------------- README | 9 +- TODO | 4 - libfprint/drivers/upekts.c | 23 ++- 5 files changed, 13 insertions(+), 373 deletions(-) delete mode 100644 COPYING.GPL diff --git a/COPYING b/COPYING index 3a0a5754..5ab7695a 100644 --- a/COPYING +++ b/COPYING @@ -1,13 +1,3 @@ -NOTE: This prerelease version of libfprint is mostly LGPL-licensed (as in the -text below) but also includes code from libthinkfinger which is licensed under -the GPL. -This libfprint release is therefore licensed under the LGPL *and* the GPL. -The GPL terms can be found in the COPYING.GPL file. - -At release time, I will contact libthinkfinger authors and see if they will -be happy to relicense. I expect they will. - - GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 diff --git a/COPYING.GPL b/COPYING.GPL deleted file mode 100644 index 3912109b..00000000 --- a/COPYING.GPL +++ /dev/null @@ -1,340 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Library General -Public License instead of this License. diff --git a/README b/README index 2696662d..6e4686cc 100644 --- a/README +++ b/README @@ -14,13 +14,8 @@ For more information on libfprint, supported devices, API documentation, etc., see the homepage: http://www.reactivated.net/fprint/Libfprint -libfprint is primarily licensed under the GNU LGPL. HOWEVER, THIS PRERELEASE -VERSION INCLUDES GPL CODE FROM LIBTHINKFINGER, therefore distribution is -subject to both the terms of the LGPL (see COPYING) *and* the GPL -(see COPYING.GPL). - -At release time, I will contact libthinkfinger authors and see if they will -be happy to relicense. I expect they will. +libfprint is licensed under the GNU LGPL version 2.1. See the COPYING file +for the license text. libfprint includes code from NIST's NBIS software distribution: http://fingerprint.nist.gov/NBIS/index.html diff --git a/TODO b/TODO index 74a0b6ef..eeaea7c0 100644 --- a/TODO +++ b/TODO @@ -26,7 +26,3 @@ PPMM parameter to get_minutiae seems to have no effect nbis minutiae should be stored in endian-independent format return images with standard enroll/verify call variants -MISC -==== -upekts/thinkfinger relicensing (GPL --> LGPL) - diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index 5f0842c7..350fe488 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -9,21 +9,20 @@ * LGPL CRC code copied from GStreamer-0.10.10: * Copyright (C) <1999> Erik Walthinsen * Copyright (C) 2004,2006 Thomas Vander Stichele + + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; version + * 2.1 of the License. * - * This program is free software; you can 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, + * This library 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. + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser 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. + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define FP_COMPONENT "upekts" From a86cd51959cdb6e34ba0ddee4eed07880ac0fa2c Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Tue, 13 Nov 2007 14:32:31 +0000 Subject: [PATCH 060/184] Clean up on exit, and convert to singly-linked-lists This adds fp_exit() to the public API, intended to be called while the driving app is shutting down. --- TODO | 2 - examples/enroll.c | 10 +++-- examples/img_capture.c | 8 ++-- examples/img_capture_continuous.c | 24 +++++------ examples/verify.c | 10 +++-- examples/verify_live.c | 10 +++-- libfprint/core.c | 66 ++++++++++++++++++++++++------- libfprint/data.c | 6 ++- libfprint/fp_internal.h | 1 + libfprint/fprint.h | 1 + 10 files changed, 94 insertions(+), 44 deletions(-) diff --git a/TODO b/TODO index eeaea7c0..a137e92e 100644 --- a/TODO +++ b/TODO @@ -4,8 +4,6 @@ identification test suite against NFIQ compliance set make library optionally asynchronous and maybe thread-safe nbis cleanups -track open devices, so we can close them during libfprint close -free memory during libfprint close API function to determine if img device supports uncond. capture race-free way of saying "save this print but don't overwrite" diff --git a/examples/enroll.c b/examples/enroll.c index a1062f82..97671a60 100644 --- a/examples/enroll.c +++ b/examples/enroll.c @@ -92,7 +92,7 @@ struct fp_print_data *enroll(struct fp_dev *dev) { int main(void) { - int r; + int r = 1; struct fp_dscv_dev *ddev; struct fp_dscv_dev **discovered_devs; struct fp_dev *dev; @@ -113,20 +113,20 @@ int main(void) discovered_devs = fp_discover_devs(); if (!discovered_devs) { fprintf(stderr, "Could not discover devices\n"); - exit(1); + goto out; } ddev = discover_device(discovered_devs); if (!ddev) { fprintf(stderr, "No devices detected.\n"); - exit(1); + goto out; } dev = fp_dev_open(ddev); fp_dscv_devs_free(discovered_devs); if (!dev) { fprintf(stderr, "Could not open device.\n"); - exit(1); + goto out; } printf("Opened device. It's now time to enroll your finger.\n\n"); @@ -141,6 +141,8 @@ int main(void) fp_print_data_free(data); out_close: fp_dev_close(dev); +out: + fp_exit(); return r; } diff --git a/examples/img_capture.c b/examples/img_capture.c index 794f1d1e..ea494c89 100644 --- a/examples/img_capture.c +++ b/examples/img_capture.c @@ -54,20 +54,20 @@ int main(void) discovered_devs = fp_discover_devs(); if (!discovered_devs) { fprintf(stderr, "Could not discover devices\n"); - exit(1); + goto out; } ddev = discover_device(discovered_devs); if (!ddev) { fprintf(stderr, "No devices detected.\n"); - exit(1); + goto out; } dev = fp_dev_open(ddev); fp_dscv_devs_free(discovered_devs); if (!dev) { fprintf(stderr, "Could not open device.\n"); - exit(1); + goto out; } if (!fp_dev_supports_imaging(dev)) { @@ -100,6 +100,8 @@ int main(void) r = 0; out_close: fp_dev_close(dev); +out: + fp_exit(); return r; } diff --git a/examples/img_capture_continuous.c b/examples/img_capture_continuous.c index 5079fe70..0f1644eb 100644 --- a/examples/img_capture_continuous.c +++ b/examples/img_capture_continuous.c @@ -153,25 +153,25 @@ int main(void) discovered_devs = fp_discover_devs(); if (!discovered_devs) { fprintf(stderr, "Could not discover devices\n"); - exit(1); + goto out; } ddev = discover_device(discovered_devs); if (!ddev) { fprintf(stderr, "No devices detected.\n"); - exit(1); + goto out; } dev = fp_dev_open(ddev); fp_dscv_devs_free(discovered_devs); if (!dev) { fprintf(stderr, "Could not open device.\n"); - exit(1); + goto out; } if (!fp_dev_supports_imaging(dev)) { fprintf(stderr, "this device does not have imaging capabilities.\n"); - goto out; + goto out_close; } img_width = fp_dev_get_img_width(dev); @@ -179,24 +179,24 @@ int main(void) if (img_width <= 0 || img_height <= 0) { fprintf(stderr, "this device returns images with variable dimensions," " this example does not support that.\n"); - goto out; + goto out_close; } framebuffer = malloc(img_width * img_height * 2); if (!framebuffer) - goto out; + goto out_close; /* make the window */ display = XOpenDisplay(getenv("DISPLAY")); if(display == NULL) { fprintf(stderr,"Could not open display \"%s\"\n", getenv("DISPLAY")); - goto out; + goto out_close; } QueryXv(); if (adaptor < 0) - goto out; + goto out_close; window = XCreateSimpleWindow(display, DefaultRootWindow(display), 0, 0, img_width, img_height, 0, @@ -216,7 +216,7 @@ int main(void) r = fp_dev_img_capture(dev, 1, &img); if (r) { fprintf(stderr, "image capture failed, code %d\n", r); - goto out; + goto out_close; } if (standardize) fp_img_standardize(img); @@ -234,7 +234,7 @@ int main(void) case XK_q: case XK_Q: r = 0; - goto out; + goto out_close; break; case XK_s: case XK_S: @@ -245,7 +245,7 @@ int main(void) } r = 0; -out: +out_close: if (framebuffer) free(framebuffer); fp_dev_close(dev); @@ -253,6 +253,8 @@ out: XUnmapWindow(display, window); if (display != NULL) XFlush(display); +out: + fp_exit(); return r; } diff --git a/examples/verify.c b/examples/verify.c index 42b07bbf..ef66d5e1 100644 --- a/examples/verify.c +++ b/examples/verify.c @@ -76,7 +76,7 @@ int verify(struct fp_dev *dev, struct fp_print_data *data) int main(void) { - int r; + int r = 1; struct fp_dscv_dev *ddev; struct fp_dscv_dev **discovered_devs; struct fp_dev *dev; @@ -91,20 +91,20 @@ int main(void) discovered_devs = fp_discover_devs(); if (!discovered_devs) { fprintf(stderr, "Could not discover devices\n"); - exit(1); + goto out; } ddev = discover_device(discovered_devs); if (!ddev) { fprintf(stderr, "No devices detected.\n"); - exit(1); + goto out; } dev = fp_dev_open(ddev); fp_dscv_devs_free(discovered_devs); if (!dev) { fprintf(stderr, "Could not open device.\n"); - exit(1); + goto out; } printf("Opened device. Loading previously enrolled right index finger " @@ -132,6 +132,8 @@ int main(void) fp_print_data_free(data); out_close: fp_dev_close(dev); +out: + fp_exit(); return r; } diff --git a/examples/verify_live.c b/examples/verify_live.c index 5f3932b7..0e1db6d7 100644 --- a/examples/verify_live.c +++ b/examples/verify_live.c @@ -126,7 +126,7 @@ int verify(struct fp_dev *dev, struct fp_print_data *data) int main(void) { - int r; + int r = 1; struct fp_dscv_dev *ddev; struct fp_dscv_dev **discovered_devs; struct fp_dev *dev; @@ -141,20 +141,20 @@ int main(void) discovered_devs = fp_discover_devs(); if (!discovered_devs) { fprintf(stderr, "Could not discover devices\n"); - exit(1); + goto out; } ddev = discover_device(discovered_devs); if (!ddev) { fprintf(stderr, "No devices detected.\n"); - exit(1); + goto out; } dev = fp_dev_open(ddev); fp_dscv_devs_free(discovered_devs); if (!dev) { fprintf(stderr, "Could not open device.\n"); - exit(1); + goto out; } printf("Opened device. It's now time to enroll your finger.\n\n"); @@ -181,6 +181,8 @@ int main(void) fp_print_data_free(data); out_close: fp_dev_close(dev); +out: + fp_exit(); return r; } diff --git a/libfprint/core.c b/libfprint/core.c index 1685b4b9..effded91 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -276,7 +276,8 @@ * circumstances, you don't have to worry about driver IDs at all. */ -static GList *registered_drivers = NULL; +static GSList *registered_drivers = NULL; +static GSList *opened_devices = NULL; void fpi_log(enum fpi_log_level level, const char *component, const char *function, const char *format, ...) @@ -323,7 +324,7 @@ static void register_driver(struct fp_driver *drv) fp_err("not registering driver %s: driver ID is 0"); return; } - registered_drivers = g_list_prepend(registered_drivers, (gpointer) drv); + registered_drivers = g_slist_prepend(registered_drivers, (gpointer) drv); fp_dbg("registered driver %s", drv->name); } @@ -353,7 +354,7 @@ static void register_drivers(void) static struct fp_driver *find_supporting_driver(struct usb_device *udev, const struct usb_id **usb_id) { - GList *elem = registered_drivers; + GSList *elem = registered_drivers; do { struct fp_driver *drv = elem->data; @@ -367,7 +368,7 @@ static struct fp_driver *find_supporting_driver(struct usb_device *udev, *usb_id = id; return drv; } - } while (elem = g_list_next(elem)); + } while (elem = g_slist_next(elem)); return NULL; } @@ -405,7 +406,7 @@ static struct fp_dscv_dev *discover_dev(struct usb_device *udev) */ API_EXPORTED struct fp_dscv_dev **fp_discover_devs(void) { - GList *tmplist = NULL; + GSList *tmplist = NULL; struct fp_dscv_dev **list; struct usb_device *udev; struct usb_bus *bus; @@ -418,7 +419,7 @@ API_EXPORTED struct fp_dscv_dev **fp_discover_devs(void) usb_find_devices(); /* Check each device against each driver, temporarily storing successfully - * discovered devices in a GList. + * discovered devices in a GSList. * * Quite inefficient but excusable as we'll only be dealing with small * sets of drivers against small sets of USB devices */ @@ -427,23 +428,23 @@ API_EXPORTED struct fp_dscv_dev **fp_discover_devs(void) struct fp_dscv_dev *ddev = discover_dev(udev); if (!ddev) continue; - tmplist = g_list_prepend(tmplist, (gpointer) ddev); + tmplist = g_slist_prepend(tmplist, (gpointer) ddev); dscv_count++; } - /* Convert our temporary GList into a standard NULL-terminated pointer + /* Convert our temporary GSList into a standard NULL-terminated pointer * array. */ list = g_malloc(sizeof(*list) * (dscv_count + 1)); if (dscv_count > 0) { - GList *elem = tmplist; + GSList *elem = tmplist; int i = 0; do { list[i++] = elem->data; - } while (elem = g_list_next(elem)); + } while (elem = g_slist_next(elem)); } list[dscv_count] = NULL; /* NULL-terminate */ - g_list_free(tmplist); + g_slist_free(tmplist); return list; } @@ -601,9 +602,19 @@ API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) } fp_dbg(""); + opened_devices = g_slist_prepend(opened_devices, (gpointer) dev); return dev; } +/* performs close operation without modifying opened_devices list */ +static void do_close(struct fp_dev *dev) +{ + if (dev->drv->exit) + dev->drv->exit(dev); + usb_close(dev->udev); + g_free(dev); +} + /** \ingroup dev * Close a device. You must call this function when you are finished using * a fingerprint device. @@ -612,10 +623,11 @@ API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) API_EXPORTED void fp_dev_close(struct fp_dev *dev) { fp_dbg(""); - if (dev->drv->exit) - dev->drv->exit(dev); - usb_close(dev->udev); - g_free(dev); + + if (g_slist_index(opened_devices, (gconstpointer) dev) == -1) + fp_err("device %p not in opened list!", dev); + opened_devices = g_slist_remove(opened_devices, (gconstpointer) dev); + do_close(dev); } /** \ingroup dev @@ -986,3 +998,27 @@ API_EXPORTED int fp_init(void) return 0; } +/** \ingroup core + * Deinitialise libfprint. This function should be called during your program + * exit sequence. You must not use any libfprint functions after calling this + * function, unless you call fp_init() again. + */ +API_EXPORTED void fp_exit(void) +{ + GSList *elem = opened_devices; + fp_dbg(""); + + if (elem != NULL) { + do { + fp_dbg("naughty app left a device open on exit!"); + do_close((struct fp_dev *) elem->data); + } while (elem = g_slist_next(elem)); + g_slist_free(opened_devices); + opened_devices = NULL; + } + + fpi_data_exit(); + g_slist_free(registered_drivers); + registered_drivers = NULL; +} + diff --git a/libfprint/data.c b/libfprint/data.c index 564a70df..97ed5d0a 100644 --- a/libfprint/data.c +++ b/libfprint/data.c @@ -45,7 +45,6 @@ * in any fashion that suits you. */ -/* FIXME: should free this during library shutdown */ static char *base_store = NULL; static void storage_setup(void) @@ -63,6 +62,11 @@ static void storage_setup(void) /* FIXME handle failure */ } +void fpi_data_exit(void) +{ + g_free(base_store); +} + #define FP_FINGER_IS_VALID(finger) \ ((finger) >= LEFT_THUMB && (finger) <= RIGHT_LITTLE) diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 3ed42f2c..435ec46e 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -182,6 +182,7 @@ struct fpi_print_data_fp1 { unsigned char data[0]; } __attribute__((__packed__)); +void fpi_data_exit(void); struct fp_print_data *fpi_print_data_new(struct fp_dev *dev, size_t length); gboolean fpi_print_data_compatible(uint16_t driver_id1, uint32_t devtype1, enum fp_print_data_type type1, uint16_t driver_id2, uint32_t devtype2, diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 6e881da3..399b5e13 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -183,6 +183,7 @@ void fp_img_free(struct fp_img *img); /* Library */ int fp_init(void); +void fp_exit(void); #endif From 5485f8031d97f26a88ae51e83872c6c79edafc3e Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Tue, 13 Nov 2007 20:46:15 +0000 Subject: [PATCH 061/184] Return images through enroll/verify path Added new API functions to obtain images, even when scans are bad, perhaps a useful way to show the user just how good/bad the scan actually was. Drivers and examples updated accordingly. --- TODO | 1 - doc/doxygen.cfg | 2 +- examples/enroll.c | 11 +++++++++- examples/verify.c | 9 +++++++- libfprint/core.c | 45 +++++++++++++++++++++++++++++++------- libfprint/drivers/upekts.c | 5 +++-- libfprint/fp_internal.h | 5 +++-- libfprint/fprint.h | 37 +++++++++++++++++++++++++++++-- libfprint/img.c | 2 +- libfprint/imgdev.c | 24 ++++++++++++++------ 10 files changed, 115 insertions(+), 26 deletions(-) diff --git a/TODO b/TODO index a137e92e..62d210b1 100644 --- a/TODO +++ b/TODO @@ -22,5 +22,4 @@ IMAGING aes4000 doesn't work very well, maybe due to small minutia count? PPMM parameter to get_minutiae seems to have no effect nbis minutiae should be stored in endian-independent format -return images with standard enroll/verify call variants diff --git a/doc/doxygen.cfg b/doc/doxygen.cfg index 41b1a071..3548e662 100644 --- a/doc/doxygen.cfg +++ b/doc/doxygen.cfg @@ -249,7 +249,7 @@ EXTRACT_PRIVATE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. -EXTRACT_STATIC = NO +EXTRACT_STATIC = YES # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. diff --git a/examples/enroll.c b/examples/enroll.c index 97671a60..2031938c 100644 --- a/examples/enroll.c +++ b/examples/enroll.c @@ -47,13 +47,22 @@ struct fp_print_data *enroll(struct fp_dev *dev) { "complete the process.\n", fp_dev_get_nr_enroll_stages(dev)); do { + struct fp_img *img = NULL; + sleep(1); printf("\nScan your finger now.\n"); - r = fp_enroll_finger(dev, &enrolled_print); + + r = fp_enroll_finger_img(dev, &enrolled_print, &img); + if (img) { + fp_img_save_to_file(img, "enrolled.pgm"); + printf("Wrote scanned image to enrolled.pgm\n"); + fp_img_free(img); + } if (r < 0) { printf("Enroll failed with error %d\n", r); return NULL; } + switch (r) { case FP_ENROLL_COMPLETE: printf("Enroll complete!\n"); diff --git a/examples/verify.c b/examples/verify.c index ef66d5e1..af4327f1 100644 --- a/examples/verify.c +++ b/examples/verify.c @@ -44,9 +44,16 @@ int verify(struct fp_dev *dev, struct fp_print_data *data) int r; do { + struct fp_img *img = NULL; + sleep(1); printf("\nScan your finger now.\n"); - r = fp_verify_finger(dev, data); + r = fp_verify_finger_img(dev, data, &img); + if (img) { + fp_img_save_to_file(img, "verify.pgm"); + printf("Wrote scanned image to verify.pgm\n"); + fp_img_free(img); + } if (r < 0) { printf("verification failed with error %d :(\n", r); return r; diff --git a/libfprint/core.c b/libfprint/core.c index effded91..0aa6dd1f 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -143,7 +143,7 @@ * match. libfprint does offer you some "is this print compatible?" helper * functions, so you don't have to worry about these details too much. * - * \section Synchronity/asynchronity + * \section sync Synchronity/asynchronity * * Currently, all data acquisition operations are synchronous and can * potentially block for extended periods of time. For example, the enroll @@ -850,16 +850,25 @@ API_EXPORTED int fp_dev_get_img_height(struct fp_dev *dev) * resultant enrollment data. The print_data parameter will not be modified * during any other enrollment stages, hence it is actually legal to pass NULL * as this argument for all but the final stage. + * + * If the device is an imaging device, it can also return the image from + * the scan, even when the enroll fails with a RETRY or FAIL code. It is legal + * to call this function even on non-imaging devices, just don't expect them to + * provide images. * * \param dev the device * \param print_data a location to return the resultant enrollment data from * the final stage. Must be freed with fp_print_data_free() after use. - * \return negative code on error, otherwise a code from #fp_verify_result + * \param img location to store the scan image. accepts NULL for no image + * storage. If an image is returned, it must be freed with fp_img_free() after + * use. + * \return negative code on error, otherwise a code from #fp_enroll_result */ -API_EXPORTED int fp_enroll_finger(struct fp_dev *dev, - struct fp_print_data **print_data) +API_EXPORTED int fp_enroll_finger_img(struct fp_dev *dev, + struct fp_print_data **print_data, struct fp_img **img) { struct fp_driver *drv = dev->drv; + struct fp_img *_img = NULL; int ret; int stage = dev->__enroll_stage; gboolean initial = FALSE; @@ -884,12 +893,18 @@ API_EXPORTED int fp_enroll_finger(struct fp_dev *dev, fp_dbg("%s will handle enroll stage %d/%d%s", drv->name, stage, dev->nr_enroll_stages - 1, initial ? " (initial)" : ""); - ret = drv->enroll(dev, initial, stage, print_data); + ret = drv->enroll(dev, initial, stage, print_data, &_img); if (ret < 0) { fp_err("enroll failed with code %d", ret); dev->__enroll_stage = -1; return ret; } + + if (img) + *img = _img; + else + fp_img_free(_img); + switch (ret) { case FP_ENROLL_PASS: fp_dbg("enroll stage passed"); @@ -925,15 +940,24 @@ API_EXPORTED int fp_enroll_finger(struct fp_dev *dev, /** \ingroup dev * Performs a new scan and verify it against a previously enrolled print. + * If the device is an imaging device, it can also return the image from + * the scan, even when the verify fails with a RETRY code. It is legal to + * call this function even on non-imaging devices, just don't expect them to + * provide images. + * * \param dev the device to perform the scan. * \param enrolled_print the print to verify against. Must have been previously * enrolled with a device compatible to the device selected to perform the scan. + * \param img location to store the scan image. accepts NULL for no image + * storage. If an image is returned, it must be freed with fp_img_free() after + * use. * \return negative code on error, otherwise a code from #fp_verify_result */ -API_EXPORTED int fp_verify_finger(struct fp_dev *dev, - struct fp_print_data *enrolled_print) +API_EXPORTED int fp_verify_finger_img(struct fp_dev *dev, + struct fp_print_data *enrolled_print, struct fp_img **img) { struct fp_driver *drv = dev->drv; + struct fp_img *_img = NULL; int r; if (!enrolled_print) { @@ -952,12 +976,17 @@ API_EXPORTED int fp_verify_finger(struct fp_dev *dev, } fp_dbg("to be handled by %s", drv->name); - r = drv->verify(dev, enrolled_print); + r = drv->verify(dev, enrolled_print, &_img); if (r < 0) { fp_dbg("verify error %d", r); return r; } + if (img) + *img = _img; + else + fp_img_free(_img); + switch (r) { case FP_VERIFY_NO_MATCH: fp_dbg("result: no match"); diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index 350fe488..8b8ce08f 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -557,7 +557,7 @@ static const unsigned char scan_comp[] = { static const unsigned char poll_data[] = { 0x30, 0x01 }; static int enroll(struct fp_dev *dev, gboolean initial, - int stage, struct fp_print_data **_data) + int stage, struct fp_print_data **_data, struct fp_img **img) { unsigned char *data; size_t data_len; @@ -692,7 +692,8 @@ static const unsigned char verify_hdr[] = { 0x00 }; -static int verify(struct fp_dev *dev, struct fp_print_data *print) +static int verify(struct fp_dev *dev, struct fp_print_data *print, + struct fp_img **img) { size_t data_len = sizeof(verify_hdr) + print->length; unsigned char *data; diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 435ec46e..00add029 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -112,8 +112,9 @@ struct fp_driver { int (*init)(struct fp_dev *dev, unsigned long driver_data); void (*exit)(struct fp_dev *dev); int (*enroll)(struct fp_dev *dev, gboolean initial, int stage, - struct fp_print_data **print_data); - int (*verify)(struct fp_dev *dev, struct fp_print_data *data); + struct fp_print_data **print_data, struct fp_img **img); + int (*verify)(struct fp_dev *dev, struct fp_print_data *data, + struct fp_img **img); }; enum fp_print_data_type fpi_driver_get_data_type(struct fp_driver *drv); diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 399b5e13..334fe999 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -128,7 +128,25 @@ enum fp_enroll_result { FP_ENROLL_RETRY_REMOVE_FINGER, }; -int fp_enroll_finger(struct fp_dev *dev, struct fp_print_data **print_data); +int fp_enroll_finger_img(struct fp_dev *dev, struct fp_print_data **print_data, + struct fp_img **img); + +/** \ingroup dev + * Performs an enroll stage. See \ref enrolling for an explanation of enroll + * stages. This function is just a shortcut to calling fp_enroll_finger_img() + * with a NULL image parameter. Be sure to read the description of + * fp_enroll_finger_img() in order to understand its behaviour. + * + * \param dev the device + * \param print_data a location to return the resultant enrollment data from + * the final stage. Must be freed with fp_print_data_free() after use. + * \return negative code on error, otherwise a code from #fp_enroll_result + */ +static inline int fp_enroll_finger(struct fp_dev *dev, + struct fp_print_data **print_data) +{ + return fp_enroll_finger_img(dev, print_data, NULL); +} /** \ingroup dev * Verification result codes returned from fp_verify_finger(). @@ -158,7 +176,22 @@ enum fp_verify_result { FP_VERIFY_RETRY_REMOVE_FINGER = FP_ENROLL_RETRY_REMOVE_FINGER, }; -int fp_verify_finger(struct fp_dev *dev, struct fp_print_data *enrolled_print); +int fp_verify_finger_img(struct fp_dev *dev, + struct fp_print_data *enrolled_print, struct fp_img **img); + +/** \ingroup dev + * Performs a new scan and verify it against a previously enrolled print. + * \param dev the device to perform the scan. + * \param enrolled_print the print to verify against. Must have been previously + * enrolled with a device compatible to the device selected to perform the scan. + * \return negative code on error, otherwise a code from #fp_verify_result + * \sa fp_verify_finger_img() + */ +static inline int fp_verify_finger(struct fp_dev *dev, + struct fp_print_data *enrolled_print) +{ + return fp_verify_finger_img(dev, enrolled_print, NULL); +} /* Data handling */ int fp_print_data_load(struct fp_dev *dev, enum fp_finger finger, diff --git a/libfprint/img.c b/libfprint/img.c index 72504ae8..9bc9a512 100644 --- a/libfprint/img.c +++ b/libfprint/img.c @@ -86,7 +86,7 @@ struct fp_img *fpi_img_resize(struct fp_img *img, size_t newsize) /** \ingroup img * Frees an image. Must be called when you are finished working with an image. - * \param img the image to destroy + * \param img the image to destroy. If NULL, function simply returns. */ API_EXPORTED void fp_img_free(struct fp_img *img) { diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index d8d651a9..b9da4b5a 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -157,7 +157,7 @@ err: #define MIN_ACCEPTABLE_MINUTIAE 10 int img_dev_enroll(struct fp_dev *dev, gboolean initial, int stage, - struct fp_print_data **ret) + struct fp_print_data **ret, struct fp_img **_img) { struct fp_img *img; struct fp_img_dev *imgdev = dev->priv; @@ -168,12 +168,17 @@ int img_dev_enroll(struct fp_dev *dev, gboolean initial, int stage, * use NFIQ to pick the best one, and discard the others */ r = fpi_imgdev_capture(imgdev, 0, &img); + + /* If we got an image, standardize it and return it even if the scan + * quality was too low for processing. */ + if (img) + fp_img_standardize(img); + if (_img) + *_img = img; if (r) return r; - fp_img_standardize(img); r = fpi_img_detect_minutiae(imgdev, img, &print); - fp_img_free(img); if (r < 0) return r; if (r < MIN_ACCEPTABLE_MINUTIAE) { @@ -189,22 +194,27 @@ int img_dev_enroll(struct fp_dev *dev, gboolean initial, int stage, #define BOZORTH3_DEFAULT_THRESHOLD 40 static int img_dev_verify(struct fp_dev *dev, - struct fp_print_data *enrolled_print) + struct fp_print_data *enrolled_print, struct fp_img **_img) { struct fp_img_dev *imgdev = dev->priv; struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(dev->drv); - struct fp_img *img; + struct fp_img *img = NULL; struct fp_print_data *print; int match_score = imgdrv->bz3_threshold; int r; r = fpi_imgdev_capture(imgdev, 0, &img); + + /* If we got an image, standardize it and return it even if the scan + * quality was too low for processing. */ + if (img) + fp_img_standardize(img); + if (_img) + *_img = img; if (r) return r; - fp_img_standardize(img); r = fpi_img_detect_minutiae(imgdev, img, &print); - fp_img_free(img); if (r < 0) return r; if (r < MIN_ACCEPTABLE_MINUTIAE) { From 2ad14c021299fd362072a1fc36e634fc491df255 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Wed, 7 Nov 2007 17:49:10 +0000 Subject: [PATCH 062/184] Add AES2501 driver This driver works quite nicely. Seems a little too sensitive though (too much black in the standardized image, not enough ridge gap definition). Processing results are quite good, but you need a good enrollment image (i.e. long!). It's best to get such images by pressing harder than you might think necessary and swiping slowly. --- TODO | 7 +- libfprint/Makefile.am | 3 +- libfprint/core.c | 1 + libfprint/drivers/aes2501.c | 614 ++++++++++++++++++++++++++++++++++++ libfprint/drivers/aes2501.h | 170 ++++++++++ libfprint/fp_internal.h | 1 + 6 files changed, 793 insertions(+), 3 deletions(-) create mode 100644 libfprint/drivers/aes2501.c create mode 100644 libfprint/drivers/aes2501.h diff --git a/TODO b/TODO index 62d210b1..bbb4cf6f 100644 --- a/TODO +++ b/TODO @@ -11,7 +11,6 @@ NEW DRIVERS =========== Sunplus 895 driver AES1610 driver -AES2501 driver AES3400/3500 driver ID Mouse driver Support for 2nd generation MS devices @@ -19,7 +18,11 @@ Support for 2nd generation UPEK devices IMAGING ======= -aes4000 doesn't work very well, maybe due to small minutia count? +ignore first frame or two with aes2501 +aes2501: increase threshold "sum" for end-of-image detection +aes2501 gain calibration +aes4000 gain calibration +aes4000 resampling PPMM parameter to get_minutiae seems to have no effect nbis minutiae should be stored in endian-independent format diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 18c0c524..c5ff97bb 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -2,9 +2,10 @@ lib_LTLIBRARIES = libfprint.la UPEKTS_SRC = drivers/upekts.c URU4000_SRC = drivers/uru4000.c +AES2501_SRC = drivers/aes2501.c drivers/aes2501.h AES4000_SRC = drivers/aes4000.c -DRIVER_SRC = $(UPEKTS_SRC) $(URU4000_SRC) $(AES4000_SRC) +DRIVER_SRC = $(UPEKTS_SRC) $(URU4000_SRC) $(AES2501_SRC) $(AES4000_SRC) NBIS_SRC = \ nbis/include/bozorth.h \ diff --git a/libfprint/core.c b/libfprint/core.c index 0aa6dd1f..928b2851 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -334,6 +334,7 @@ static struct fp_driver * const primitive_drivers[] = { static struct fp_img_driver * const img_drivers[] = { &uru4000_driver, + &aes2501_driver, &aes4000_driver, }; diff --git a/libfprint/drivers/aes2501.c b/libfprint/drivers/aes2501.c new file mode 100644 index 00000000..3334df7e --- /dev/null +++ b/libfprint/drivers/aes2501.c @@ -0,0 +1,614 @@ +/* + * AuthenTec AES2501 driver for libfprint + * Copyright (C) 2007 Daniel Drake + * Copyright (C) 2007 Cyrille Bagard + * Copyright (C) 2007 Vasily Khoruzhick + * + * Based on code from http://home.gna.org/aes2501, relicensed with permission + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#define FP_COMPONENT "aes2501" + +#include +#include + +#include + +#include +#include "aes2501.h" + +/* FIXME these need checking */ +#define EP_IN (1 | USB_ENDPOINT_IN) +#define EP_OUT (2 | USB_ENDPOINT_OUT) + +#define BULK_TIMEOUT 4000 + +/* + * The AES2501 is an imaging device using a swipe-type sensor. It samples + * the finger at preprogrammed intervals, sending a 192x16 frame to the + * computer. + * Unless the user is scanning their finger unreasonably fast, the frames + * *will* overlap. The implementation below detects this overlap and produces + * a contiguous image as the end result. + * The fact that the user determines the length of the swipe (and hence the + * number of useful frames) and also the fact that overlap varies means that + * images returned from this driver vary in height. + */ + +#define FRAME_WIDTH 192 +#define FRAME_HEIGHT 16 +#define FRAME_SIZE (FRAME_WIDTH * FRAME_HEIGHT) +/* maximum number of frames to read during a scan */ +/* FIXME reduce substantially */ +#define MAX_FRAMES 150 + +struct aes2501_regwrite { + unsigned char reg; + unsigned char value; +}; + +static int write_reg(struct fp_img_dev *dev, unsigned char reg, + unsigned char value) +{ + unsigned char data[] = { reg, value }; + int r; + + fp_dbg("%02x=%02x", reg, value); + r = usb_bulk_write(dev->udev, EP_OUT, data, sizeof(data), BULK_TIMEOUT); + if (r < 0) { + fp_err("bulk write error %d", r); + return r; + } else if (r < sizeof(data)) { + fp_err("unexpected short write %d/%d", r, sizeof(data)); + return -EIO; + } + + return 0; +} + +static int write_regv(struct fp_img_dev *dev, struct aes2501_regwrite *regs, + unsigned int num) +{ + unsigned int i; + int r; + + /* FIXME: could combine multiple writes into a single transaction */ + + for (i = 0; i < num; i++) { + r = write_reg(dev, regs[i].reg, regs[i].value); + if (r < 0) + return r; + } + return 0; +} + +static int read_data(struct fp_img_dev *dev, unsigned char *data, size_t len) +{ + int r; + fp_dbg("len=%zd", len); + + r = usb_bulk_read(dev->udev, EP_IN, data, len, BULK_TIMEOUT); + if (r < 0) { + fp_err("bulk read error %d", r); + return r; + } else if (r < len) { + fp_err("unexpected short read %d/%zd", r, len); + return -EIO; + } + return 0; +} + +static int read_regs(struct fp_img_dev *dev, unsigned char *data) +{ + int r; + fp_dbg(""); + + r = write_reg(dev, AES2501_REG_CTRL2, AES2501_CTRL2_READ_REGS); + if (r < 0) + return r; + + return read_data(dev, data, 126); +} + +static const struct aes2501_regwrite init_1[] = { + { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, + { 0xb0, 0x27 }, /* Reserved? */ + { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, + { AES2501_REG_EXCITCTRL, 0x40 }, + { 0xff, 0x00 }, /* Reserved? */ + { 0xff, 0x00 }, /* Reserved? */ + { 0xff, 0x00 }, /* Reserved? */ + { 0xff, 0x00 }, /* Reserved? */ + { 0xff, 0x00 }, /* Reserved? */ + { 0xff, 0x00 }, /* Reserved? */ + { 0xff, 0x00 }, /* Reserved? */ + { 0xff, 0x00 }, /* Reserved? */ + { 0xff, 0x00 }, /* Reserved? */ + { 0xff, 0x00 }, /* Reserved? */ + { 0xff, 0x00 }, /* Reserved? */ + { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, + { AES2501_REG_EXCITCTRL, 0x40 }, + { AES2501_REG_DETCTRL, + AES2501_DETCTRL_DRATE_CONTINUOUS | AES2501_DETCTRL_SDELAY_31_MS }, + { AES2501_REG_COLSCAN, AES2501_COLSCAN_SRATE_128_US }, + { AES2501_REG_MEASDRV, + AES2501_MEASDRV_MDRIVE_0_325 | AES2501_MEASDRV_MEASURE_SQUARE }, + { AES2501_REG_MEASFREQ, AES2501_MEASFREQ_2M }, + { AES2501_REG_DEMODPHASE1, DEMODPHASE_NONE }, + { AES2501_REG_DEMODPHASE2, DEMODPHASE_NONE }, + { AES2501_REG_CHANGAIN, + AES2501_CHANGAIN_STAGE2_4X | AES2501_CHANGAIN_STAGE1_16X }, + { AES2501_REG_ADREFHI, 0x44 }, + { AES2501_REG_ADREFLO, 0x34 }, + { AES2501_REG_STRTCOL, 0x16 }, + { AES2501_REG_ENDCOL, 0x16 }, + { AES2501_REG_DATFMT, AES2501_DATFMT_BIN_IMG | 0x08 }, + { AES2501_REG_TREG1, 0x70 }, + { 0xa2, 0x02 }, + { 0xa7, 0x00 }, + { AES2501_REG_TREGC, AES2501_TREGC_ENABLE }, + { AES2501_REG_TREGD, 0x1a }, + { AES2501_REG_CTRL1, AES2501_CTRL1_REG_UPDATE }, + { AES2501_REG_CTRL2, AES2501_CTRL2_SET_ONE_SHOT }, + { AES2501_REG_LPONT, AES2501_LPONT_MIN_VALUE }, +}; + +static const struct aes2501_regwrite init_2[] = { + { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, + { AES2501_REG_EXCITCTRL, 0x40 }, + { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, + { AES2501_REG_AUTOCALOFFSET, 0x41 }, + { AES2501_REG_EXCITCTRL, 0x42 }, + { AES2501_REG_DETCTRL, 0x53 }, + { AES2501_REG_CTRL1, AES2501_CTRL1_REG_UPDATE }, +}; + +static const struct aes2501_regwrite init_3[] = { + { 0xff, 0x00 }, + { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, + { AES2501_REG_AUTOCALOFFSET, 0x41 }, + { AES2501_REG_EXCITCTRL, 0x42 }, + { AES2501_REG_DETCTRL, 0x53 }, + { AES2501_REG_CTRL1, AES2501_CTRL1_REG_UPDATE }, +}; + +static const struct aes2501_regwrite init_4[] = { + { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, + { AES2501_REG_EXCITCTRL, 0x40 }, + { 0xb0, 0x27 }, + { AES2501_REG_ENDROW, 0x0a }, + { AES2501_REG_CTRL1, AES2501_CTRL1_REG_UPDATE }, + { AES2501_REG_DETCTRL, 0x45 }, + { AES2501_REG_AUTOCALOFFSET, 0x41 }, +}; + +static const struct aes2501_regwrite init_5[] = { + { 0xb0, 0x27 }, + { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, + { AES2501_REG_EXCITCTRL, 0x40 }, + { 0xff, 0x00 }, + { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, + { AES2501_REG_EXCITCTRL, 0x40 }, + { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, + { AES2501_REG_EXCITCTRL, 0x40 }, + { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, + { AES2501_REG_EXCITCTRL, 0x40 }, + { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, + { AES2501_REG_EXCITCTRL, 0x40 }, + { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, + { AES2501_REG_EXCITCTRL, 0x40 }, + { AES2501_REG_CTRL1, AES2501_CTRL1_SCAN_RESET }, + { AES2501_REG_CTRL1, AES2501_CTRL1_SCAN_RESET }, +}; + +static int do_init(struct fp_img_dev *dev) +{ + unsigned char buffer[128]; + int r; + int i; + + /* part 1, probably not needed */ + r = write_regv(dev, init_1, ARRAY_SIZE(init_1)); + if (r < 0) + return r; + + r = read_data(dev, buffer, 20); + if (r < 0) + return r; + + /* part 2 */ + r = write_regv(dev, init_2, ARRAY_SIZE(init_2)); + if (r < 0) + return r; + + r = read_regs(dev, buffer); + if (r < 0) + return r; + + /* part 3 */ + fp_dbg("reg 0xaf = %x", buffer[0x5f]); + i = 0; + while (buffer[0x5f] == 0x6b) { + r = write_regv(dev, init_3, ARRAY_SIZE(init_3)); + if (r < 0) + return r; + r = read_regs(dev, buffer); + if (r < 0) + return r; + if (++i == 13) + break; + } + + /* part 4 */ + r = write_regv(dev, init_4, ARRAY_SIZE(init_4)); + if (r < 0) + return r; + + /* part 5 */ + return write_regv(dev, init_5, ARRAY_SIZE(init_5)); +} + +static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) +{ + int r; + + r = usb_claim_interface(dev->udev, 0); + if (r < 0) { + fp_err("could not claim interface 0"); + return r; + } + + /* FIXME check endpoints */ + + return do_init(dev); +} + +static void dev_exit(struct fp_img_dev *dev) +{ + usb_release_interface(dev->udev, 0); +} + +static const struct aes2501_regwrite finger_det_reqs[] = { + { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, + { AES2501_REG_EXCITCTRL, 0x40 }, + { AES2501_REG_DETCTRL, + AES2501_DETCTRL_DRATE_CONTINUOUS | AES2501_DETCTRL_SDELAY_31_MS }, + { AES2501_REG_COLSCAN, AES2501_COLSCAN_SRATE_128_US }, + { AES2501_REG_MEASDRV, AES2501_MEASDRV_MDRIVE_0_325 | AES2501_MEASDRV_MEASURE_SQUARE }, + { AES2501_REG_MEASFREQ, AES2501_MEASFREQ_2M }, + { AES2501_REG_DEMODPHASE1, DEMODPHASE_NONE }, + { AES2501_REG_DEMODPHASE2, DEMODPHASE_NONE }, + { AES2501_REG_CHANGAIN, + AES2501_CHANGAIN_STAGE2_4X | AES2501_CHANGAIN_STAGE1_16X }, + { AES2501_REG_ADREFHI, 0x44 }, + { AES2501_REG_ADREFLO, 0x34 }, + { AES2501_REG_STRTCOL, 0x16 }, + { AES2501_REG_ENDCOL, 0x16 }, + { AES2501_REG_DATFMT, AES2501_DATFMT_BIN_IMG | 0x08 }, + { AES2501_REG_TREG1, 0x70 }, + { 0xa2, 0x02 }, + { 0xa7, 0x00 }, + { AES2501_REG_TREGC, AES2501_TREGC_ENABLE }, + { AES2501_REG_TREGD, 0x1a }, + { AES2501_REG_CTRL1, AES2501_CTRL1_REG_UPDATE }, + { AES2501_REG_CTRL2, AES2501_CTRL2_SET_ONE_SHOT }, + { AES2501_REG_LPONT, AES2501_LPONT_MIN_VALUE }, +}; + +static int detect_finger(struct fp_img_dev *dev) +{ + unsigned char buffer[22]; + int r; + int i; + int sum = 0; + + r = write_regv(dev, finger_det_reqs, ARRAY_SIZE(finger_det_reqs)); + if (r < 0) + return r; + + r = read_data(dev, buffer, 20); + if (r < 0) + return r; + + for (i = 1; i < 9; i++) + sum += (buffer[i] & 0xf) + (buffer[i] >> 4); + + return sum > 20; +} + +static int await_finger_on(struct fp_img_dev *dev) +{ + int r; + do { + r = detect_finger(dev); + } while (r == 0); + return (r < 0) ? r : 0; +} + +/* Read the value of a specific register from a register dump */ +static int regval_from_dump(unsigned char *data, uint8_t target) +{ + if (*data != FIRST_AES2501_REG) { + fp_err("not a register dump"); + return -EILSEQ; + } + + if (!(FIRST_AES2501_REG <= target && target <= LAST_AES2501_REG)) { + fp_err("out of range"); + return -EINVAL; + } + + target -= FIRST_AES2501_REG; + target *= 2; + return data[target + 1]; +} + +static int sum_histogram_values(unsigned char *data, uint8_t threshold) +{ + int r = 0; + int i; + uint16_t *histogram = (uint16_t *)(data + 1); + + if (*data != 0xde) + return -EILSEQ; + + if (threshold > 0x0f) + return -EINVAL; + + /* FIXME endianness */ + for (i = threshold; i < 16; i++) + r += histogram[i]; + + return r; +} + +/* find overlapping parts of frames */ +static unsigned int find_overlap(unsigned char *first_frame, + unsigned char *second_frame) +{ + unsigned int dy; + unsigned int min_error = 255 * FRAME_SIZE; + unsigned int not_overlapped_height = 0; + for (dy = 0; dy < FRAME_HEIGHT; dy++) { + /* Calculating difference (error) between parts of frames */ + unsigned int i; + unsigned int error = 0; + for (i = 0; i < FRAME_WIDTH * (FRAME_HEIGHT - dy); i++) { + /* Using ? operator to avoid abs function */ + error += first_frame[i] > second_frame[i] ? + (first_frame[i] - second_frame[i]) : + (second_frame[i] - first_frame[i]); + } + + /* Normalize error */ + error *= 15; + error /= i; + if (error < min_error) { + min_error = error; + not_overlapped_height = dy; + } + first_frame += FRAME_WIDTH; + } + + return not_overlapped_height; +} + +/* assemble a series of frames into a single image */ +static unsigned int assemble(unsigned char *input, unsigned char *output, + int num_strips) +{ + uint8_t *assembled = output; + int frame; + uint32_t image_height = FRAME_HEIGHT; + + if (num_strips < 1) + return 0; + + /* Rotating given data by 90 degrees + * Taken from document describing aes2501 image format + * TODO: move reversing detection here */ + + for (frame = 0; frame < num_strips; frame++) { + int column; + for (column = 0; column < FRAME_WIDTH; column++) { + int row; + for (row = 0; row < (FRAME_HEIGHT / 2); row++) { + output[FRAME_WIDTH * ( 2 * row) + column] = *input & 0x0F; + output[FRAME_WIDTH * ( 2 * row + 1) + column] = *input >> 4; + input++; + } + } + + output += FRAME_SIZE; + } + + /* Detecting where frames overlaped */ + output = assembled; + for (frame = 1; frame < num_strips; frame++) { + int not_overlapped; + + output += FRAME_SIZE; + not_overlapped = find_overlap(assembled, output); + image_height += not_overlapped; + assembled += FRAME_WIDTH * not_overlapped; + memcpy(assembled, output, FRAME_SIZE); + } + return image_height; +} + +static const struct aes2501_regwrite capture_reqs_1[] = { + { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, + { AES2501_REG_EXCITCTRL, 0x40 }, + { AES2501_REG_DETCTRL, + AES2501_DETCTRL_SDELAY_31_MS | AES2501_DETCTRL_DRATE_CONTINUOUS }, + { AES2501_REG_COLSCAN, AES2501_COLSCAN_SRATE_128_US }, + { AES2501_REG_DEMODPHASE2, 0x7c }, + { AES2501_REG_MEASDRV, + AES2501_MEASDRV_MEASURE_SQUARE | AES2501_MEASDRV_MDRIVE_0_325 }, + { AES2501_REG_DEMODPHASE1, 0x24 }, + { AES2501_REG_CHWORD1, 0x00 }, + { AES2501_REG_CHWORD2, 0x6c }, + { AES2501_REG_CHWORD3, 0x09 }, + { AES2501_REG_CHWORD4, 0x54 }, + { AES2501_REG_CHWORD5, 0x78 }, + { 0xa2, 0x02 }, + { 0xa7, 0x00 }, + { 0xb6, 0x26 }, + { 0xb7, 0x1a }, + { AES2501_REG_CTRL1, AES2501_CTRL1_REG_UPDATE }, + { AES2501_REG_IMAGCTRL, + AES2501_IMAGCTRL_TST_REG_ENABLE | AES2501_IMAGCTRL_HISTO_DATA_ENABLE | + AES2501_IMAGCTRL_IMG_DATA_DISABLE }, + { AES2501_REG_STRTCOL, 0x10 }, + { AES2501_REG_ENDCOL, 0x1f }, + { AES2501_REG_CHANGAIN, + AES2501_CHANGAIN_STAGE1_2X | AES2501_CHANGAIN_STAGE2_2X }, + { AES2501_REG_ADREFHI, 0x70 }, + { AES2501_REG_ADREFLO, 0x20 }, + { AES2501_REG_CTRL2, AES2501_CTRL2_SET_ONE_SHOT }, + { AES2501_REG_LPONT, AES2501_LPONT_MIN_VALUE }, +}; + +static const struct aes2501_regwrite capture_reqs_2[] = { + { AES2501_REG_IMAGCTRL, + AES2501_IMAGCTRL_TST_REG_ENABLE | AES2501_IMAGCTRL_HISTO_DATA_ENABLE | + AES2501_IMAGCTRL_IMG_DATA_DISABLE }, + { AES2501_REG_STRTCOL, 0x10 }, + { AES2501_REG_ENDCOL, 0x1f }, + { AES2501_REG_CHANGAIN, AES2501_CHANGAIN_STAGE1_16X }, + { AES2501_REG_ADREFHI, 0x70 }, + { AES2501_REG_ADREFLO, 0x20 }, + { AES2501_REG_CTRL2, AES2501_CTRL2_SET_ONE_SHOT }, +}; + +static const struct aes2501_regwrite strip_scan_reqs[] = { + { AES2501_REG_IMAGCTRL, + AES2501_IMAGCTRL_TST_REG_ENABLE | AES2501_IMAGCTRL_HISTO_DATA_ENABLE }, + { AES2501_REG_STRTCOL, 0x00 }, + { AES2501_REG_ENDCOL, 0x2f }, + { AES2501_REG_CHANGAIN, AES2501_CHANGAIN_STAGE1_16X }, + { AES2501_REG_ADREFHI, 0x5b }, + { AES2501_REG_ADREFLO, 0x20 }, + { AES2501_REG_CTRL2, AES2501_CTRL2_SET_ONE_SHOT }, +}; + +static int capture(struct fp_img_dev *dev, gboolean unconditional, + struct fp_img **ret) +{ + int r; + struct fp_img *img; + unsigned int nstrips; + unsigned char *cooked; + unsigned char *imgptr; + unsigned char buf[1705]; + int sum; + int i; + + /* FIXME can do better here in terms of buffer management? */ + fp_dbg(""); + + r = write_regv(dev, capture_reqs_1, ARRAY_SIZE(capture_reqs_1)); + if (r < 0) + return r; + + r = read_data(dev, buf, 159); + if (r < 0) + return r; + + r = write_regv(dev, capture_reqs_2, ARRAY_SIZE(capture_reqs_2)); + if (r < 0) + return r; + + r = read_data(dev, buf, 159); + if (r < 0) + return r; + + /* FIXME: use histogram data above for gain calibration (0x8e xx) */ + + img = fpi_img_new((3 * MAX_FRAMES * FRAME_SIZE) / 2); + imgptr = img->data; + cooked = imgptr + (MAX_FRAMES * FRAME_SIZE) / 2; + + for (nstrips = 0; nstrips < MAX_FRAMES; nstrips++) { + int threshold; + + r = write_regv(dev, strip_scan_reqs, ARRAY_SIZE(strip_scan_reqs)); + if (r < 0) + goto err; + r = read_data(dev, buf, 1705); + if (r < 0) + goto err; + memcpy(imgptr, buf + 1, 192*8); + imgptr += 192*8; + + threshold = regval_from_dump((buf + 1 + 192*8 + 1 + 16*2 + 1 + 8), + AES2501_REG_DATFMT); + if (threshold < 0) { + r = threshold; + goto err; + } + + sum = sum_histogram_values((buf + 1 + 192*8), threshold & 0x0f); + if (sum < 0) { + r = sum; + goto err; + } + fp_dbg("sum=%d", sum); + if (sum == 0) + break; + } + if (nstrips == MAX_FRAMES) + fp_warn("swiping finger too slow?"); + + img->height = assemble(img->data, cooked, nstrips); + for (i = 0; i < img->height * FRAME_WIDTH; i++) + img->data[i] = (cooked[i] << 4) | 0xf; + + img = fpi_img_resize(img, img->height * FRAME_WIDTH); + img->flags = FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED | FP_IMG_COLORS_INVERTED; + *ret = img; + return 0; +err: + g_free(img); + return r; +} + +static const struct usb_id id_table[] = { + { .vendor = 0x08ff, .product = 0x2580 }, + { 0, 0, 0, }, +}; + +struct fp_img_driver aes2501_driver = { + .driver = { + .id = 4, + .name = FP_COMPONENT, + .full_name = "AuthenTec AES2501", + .id_table = id_table, + }, + .flags = 0, + .img_height = -1, + .img_width = 192, + + /* temporarily lowered until image quality improves */ + .bz3_threshold = 20, + + .init = dev_init, + .exit = dev_exit, + .await_finger_on = await_finger_on, + .capture = capture, +}; + diff --git a/libfprint/drivers/aes2501.h b/libfprint/drivers/aes2501.h new file mode 100644 index 00000000..a15699f9 --- /dev/null +++ b/libfprint/drivers/aes2501.h @@ -0,0 +1,170 @@ +/* + * AuthenTec AES2501 driver for libfprint + * Copyright (C) 2007 Cyrille Bagard + * + * Based on code from http://home.gna.org/aes2501, relicensed with permission + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef __AES2501_H +#define __AES2501_H + +enum aes2501_regs { + AES2501_REG_CTRL1 = 0x80, + AES2501_REG_CTRL2 = 0x81, + AES2501_REG_EXCITCTRL = 0x82, /* excitation control */ + AES2501_REG_DETCTRL = 0x83, /* detect control */ + AES2501_REG_COLSCAN = 0x88, /* column scan rate register */ + AES2501_REG_MEASDRV = 0x89, /* measure drive */ + AES2501_REG_MEASFREQ = 0x8a, /* measure frequency */ + AES2501_REG_DEMODPHASE1 = 0x8d, + AES2501_REG_DEMODPHASE2 = 0x8c, + AES2501_REG_CHANGAIN = 0x8e, /* channel gain */ + AES2501_REG_ADREFHI = 0x91, /* A/D reference high */ + AES2501_REG_ADREFLO = 0x92, /* A/D reference low */ + AES2501_REG_STRTROW = 0x93, /* start row */ + AES2501_REG_ENDROW = 0x94, /* end row */ + AES2501_REG_STRTCOL = 0x95, /* start column */ + AES2501_REG_ENDCOL = 0x96, /* end column */ + AES2501_REG_DATFMT = 0x97, /* data format */ + AES2501_REG_IMAGCTRL = 0x98, /* image data */ + AES2501_REG_STAT = 0x9a, + AES2501_REG_CHWORD1 = 0x9b, /* challenge word 1 */ + AES2501_REG_CHWORD2 = 0x9c, + AES2501_REG_CHWORD3 = 0x9d, + AES2501_REG_CHWORD4 = 0x9e, + AES2501_REG_CHWORD5 = 0x9f, + AES2501_REG_TREG1 = 0xa1, /* test register 1 */ + AES2501_REG_AUTOCALOFFSET = 0xa8, + AES2501_REG_TREGC = 0xac, + AES2501_REG_TREGD = 0xad, + AES2501_REG_LPONT = 0xb4, /* low power oscillator on time */ +}; + +#define FIRST_AES2501_REG AES2501_REG_CTRL1 +#define LAST_AES2501_REG AES2501_REG_CHWORD5 + +#define AES2501_CTRL1_MASTER_RESET (1<<0) +#define AES2501_CTRL1_SCAN_RESET (1<<1) /* stop + restart scan sequencer */ +/* 1 = continuously updated, 0 = updated prior to starting a scan */ +#define AES2501_CTRL1_REG_UPDATE (1<<2) + +/* 1 = continuous scans, 0 = single scans */ +#define AES2501_CTRL2_CONTINUOUS 0x01 +#define AES2501_CTRL2_READ_REGS 0x02 /* dump registers */ +#define AES2501_CTRL2_SET_ONE_SHOT 0x04 +#define AES2501_CTRL2_CLR_ONE_SHOT 0x08 +#define AES2501_CTRL2_READ_ID 0x10 + +enum aes2501_detection_rate { + /* rate of detection cycles: */ + AES2501_DETCTRL_DRATE_CONTINUOUS = 0x00, /* continuously */ + AES2501_DETCTRL_DRATE_16_MS = 0x01, /* every 16.62ms */ + AES2501_DETCTRL_DRATE_31_MS = 0x02, /* every 31.24ms */ + AES2501_DETCTRL_DRATE_62_MS = 0x03, /* every 62.50ms */ + AES2501_DETCTRL_DRATE_125_MS = 0x04, /* every 125.0ms */ + AES2501_DETCTRL_DRATE_250_MS = 0x05, /* every 250.0ms */ + AES2501_DETCTRL_DRATE_500_MS = 0x06, /* every 500.0ms */ + AES2501_DETCTRL_DRATE_1_S = 0x07, /* every 1s */ +}; + +enum aes2501_settling_delay { + AES2501_DETCTRL_SDELAY_31_MS = 0x00, /* 31.25ms */ + AES2501_DETCTRL_SSDELAY_62_MS = 0x10, /* 62.5ms */ + AES2501_DETCTRL_SSDELAY_125_MS = 0x20, /* 125ms */ + AES2501_DETCTRL_SSDELAY_250_MS = 0x30 /* 250ms */ +}; + +enum aes2501_col_scan_rate { + AES2501_COLSCAN_SRATE_32_US = 0x00, /* 32us */ + AES2501_COLSCAN_SRATE_64_US = 0x01, /* 64us */ + AES2501_COLSCAN_SRATE_128_US = 0x02, /* 128us */ + AES2501_COLSCAN_SRATE_256_US = 0x03, /* 256us */ + AES2501_COLSCAN_SRATE_512_US = 0x04, /* 512us */ + AES2501_COLSCAN_SRATE_1024_US = 0x05, /* 1024us */ + AES2501_COLSCAN_SRATE_2048_US = 0x06, /* 2048us */ + +}; + +enum aes2501_mesure_drive { + AES2501_MEASDRV_MDRIVE_0_325 = 0x00, /* 0.325 Vpp */ + AES2501_MEASDRV_MDRIVE_0_65 = 0x01, /* 0.65 Vpp */ + AES2501_MEASDRV_MDRIVE_1_3 = 0x02, /* 1.3 Vpp */ + AES2501_MEASDRV_MDRIVE_2_6 = 0x03 /* 2.6 Vpp */ + +}; + +/* Select (1=square | 0=sine) wave drive during measure */ +#define AES2501_MEASDRV_SQUARE 0x20 +/* 0 = use mesure drive setting, 1 = when sine wave is selected */ +#define AES2501_MEASDRV_MEASURE_SQUARE 0x10 + +enum aes2501_measure_freq { + AES2501_MEASFREQ_125K = 0x01, /* 125 kHz */ + AES2501_MEASFREQ_250K = 0x02, /* 250 kHz */ + AES2501_MEASFREQ_500K = 0x03, /* 500 kHz */ + AES2501_MEASFREQ_1M = 0x04, /* 1 MHz */ + AES2501_MEASFREQ_2M = 0x05 /* 2 MHz */ +}; + +#define DEMODPHASE_NONE 0x00 +#define DEMODPHASE_180_00 0x40 /* 180 degrees */ +#define DEMODPHASE_2_81 0x01 /* 2.8125 degrees */ + +#define AES2501_REG_DEMODPHASE1 0x8d +#define DEMODPHASE_1_40 0x40 /* 1.40625 degrees */ +#define DEMODPHASE_0_02 0x01 /* 0.02197256 degrees */ + +enum aes2501_sensor_gain1 { + AES2501_CHANGAIN_STAGE1_2X = 0x00, /* 2x */ + AES2501_CHANGAIN_STAGE1_4X = 0x01, /* 4x */ + AES2501_CHANGAIN_STAGE1_8X = 0x02, /* 8x */ + AES2501_CHANGAIN_STAGE1_16X = 0x03 /* 16x */ +}; + +enum aes2501_sensor_gain2 { + AES2501_CHANGAIN_STAGE2_2X = 0x00, /* 2x */ + AES2501_CHANGAIN_STAGE2_4X = 0x10, /* 4x */ + AES2501_CHANGAIN_STAGE2_8X = 0x20, /* 8x */ + AES2501_CHANGAIN_STAGE2_16X = 0x30 /* 16x */ +}; + +#define AES2501_DATFMT_EIGHT 0x40 /* 1 = 8-bit data, 0 = 4-bit data */ +#define AES2501_DATFMT_LOW_RES 0x20 +#define AES2501_DATFMT_BIN_IMG 0x10 + +/* don't send image or authentication messages when imaging */ +#define AES2501_IMAGCTRL_IMG_DATA_DISABLE 0x01 +/* send histogram when imaging */ +#define AES2501_IMAGCTRL_HISTO_DATA_ENABLE 0x02 +/* send histogram at end of each row rather than each scan */ +#define AES2501_IMAGCTRL_HISTO_EACH_ROW 0x04 +/* send full image array rather than 64x64 center */ +#define AES2501_IMAGCTRL_HISTO_FULL_ARRAY 0x08 +/* return registers before data (rather than after) */ +#define AES2501_IMAGCTRL_REG_FIRST 0x10 +/* return test registers with register dump */ +#define AES2501_IMAGCTRL_TST_REG_ENABLE 0x20 + +#define AES2501_CHWORD1_IS_FINGER 0x01 /* If set, finger is present */ + +/* Enable the reading of the register in TREGD */ +#define AES2501_TREGC_ENABLE 0x01 + +#define AES2501_LPONT_MIN_VALUE 0x00 /* 0 ms */ +#define AES2501_LPONT_MAX_VALUE 0x1f /* About 16 ms */ + +#endif /* __AES2501_H */ diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 00add029..969c6378 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -141,6 +141,7 @@ struct fp_img_driver { extern struct fp_driver upekts_driver; extern struct fp_img_driver uru4000_driver; +extern struct fp_img_driver aes2501_driver; extern struct fp_img_driver aes4000_driver; void fpi_img_driver_setup(struct fp_img_driver *idriver); From 6866ea626e22a861ade880c9eb1c1e2fd48e3510 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Thu, 15 Nov 2007 09:56:14 +0000 Subject: [PATCH 063/184] v0.0.1 release --- NEWS | 3 +++ configure.ac | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/NEWS b/NEWS index e69de29b..559ad663 100644 --- a/NEWS +++ b/NEWS @@ -0,0 +1,3 @@ +2007-11-15: v0.0.1 release + * Initial release + diff --git a/configure.ac b/configure.ac index 55f342a3..177c7880 100644 --- a/configure.ac +++ b/configure.ac @@ -1,4 +1,4 @@ -AC_INIT([libfprint], [0.0]) +AC_INIT([libfprint], [0.0.1]) AM_INIT_AUTOMAKE AC_CONFIG_SRCDIR([libfprint/core.c]) AM_CONFIG_HEADER([config.h]) From 06e8040956013fcba3c36d58356fb281b3888a58 Mon Sep 17 00:00:00 2001 From: Vasily Khoruzhick Date: Thu, 15 Nov 2007 16:09:38 +0000 Subject: [PATCH 064/184] aes2501: Detect reversed scans aes2501 can be mounted 180 degrees rotated (this happens on most part of laptops), so driver should detect whether sensor is 180degrees rotated and assemble frames in right order. --- THANKS | 1 + libfprint/drivers/aes2501.c | 36 ++++++++++++++++++++++++++---------- 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/THANKS b/THANKS index 76c08171..68143f9e 100644 --- a/THANKS +++ b/THANKS @@ -6,3 +6,4 @@ Craig Watson (NIST) James Vasile (SFLC) Toby Howard (University of Manchester) Seemant Kulleen +Vasily Khoruzhick diff --git a/libfprint/drivers/aes2501.c b/libfprint/drivers/aes2501.c index 3334df7e..3d95ea5c 100644 --- a/libfprint/drivers/aes2501.c +++ b/libfprint/drivers/aes2501.c @@ -378,11 +378,11 @@ static int sum_histogram_values(unsigned char *data, uint8_t threshold) /* find overlapping parts of frames */ static unsigned int find_overlap(unsigned char *first_frame, - unsigned char *second_frame) + unsigned char *second_frame, unsigned int *min_error) { unsigned int dy; - unsigned int min_error = 255 * FRAME_SIZE; unsigned int not_overlapped_height = 0; + *min_error = 255 * FRAME_SIZE; for (dy = 0; dy < FRAME_HEIGHT; dy++) { /* Calculating difference (error) between parts of frames */ unsigned int i; @@ -397,8 +397,8 @@ static unsigned int find_overlap(unsigned char *first_frame, /* Normalize error */ error *= 15; error /= i; - if (error < min_error) { - min_error = error; + if (error < *min_error) { + *min_error = error; not_overlapped_height = dy; } first_frame += FRAME_WIDTH; @@ -409,11 +409,13 @@ static unsigned int find_overlap(unsigned char *first_frame, /* assemble a series of frames into a single image */ static unsigned int assemble(unsigned char *input, unsigned char *output, - int num_strips) + int num_strips, gboolean reverse, unsigned int *errors_sum) { uint8_t *assembled = output; int frame; uint32_t image_height = FRAME_HEIGHT; + unsigned int min_error; + *errors_sum = 0; if (num_strips < 1) return 0; @@ -422,6 +424,8 @@ static unsigned int assemble(unsigned char *input, unsigned char *output, * Taken from document describing aes2501 image format * TODO: move reversing detection here */ + if (reverse) + output += (num_strips - 1) * FRAME_SIZE; for (frame = 0; frame < num_strips; frame++) { int column; for (column = 0; column < FRAME_WIDTH; column++) { @@ -433,7 +437,10 @@ static unsigned int assemble(unsigned char *input, unsigned char *output, } } - output += FRAME_SIZE; + if (reverse) + output -= FRAME_SIZE; + else + output += FRAME_SIZE; } /* Detecting where frames overlaped */ @@ -442,11 +449,12 @@ static unsigned int assemble(unsigned char *input, unsigned char *output, int not_overlapped; output += FRAME_SIZE; - not_overlapped = find_overlap(assembled, output); + not_overlapped = find_overlap(assembled, output, &min_error); + *errors_sum += min_error; image_height += not_overlapped; assembled += FRAME_WIDTH * not_overlapped; memcpy(assembled, output, FRAME_SIZE); - } + } return image_height; } @@ -512,6 +520,7 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, int r; struct fp_img *img; unsigned int nstrips; + unsigned int errors_sum, r_errors_sum; unsigned char *cooked; unsigned char *imgptr; unsigned char buf[1705]; @@ -574,12 +583,19 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, if (nstrips == MAX_FRAMES) fp_warn("swiping finger too slow?"); - img->height = assemble(img->data, cooked, nstrips); + img->flags = FP_IMG_COLORS_INVERTED; + img->height = assemble(img->data, cooked, nstrips, FALSE, &errors_sum); + img->height = assemble(img->data, cooked, nstrips, TRUE, &r_errors_sum); + + if (r_errors_sum > errors_sum) { + img->height = assemble(img->data, cooked, nstrips, FALSE, &errors_sum); + img->flags |= FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED; + } + for (i = 0; i < img->height * FRAME_WIDTH; i++) img->data[i] = (cooked[i] << 4) | 0xf; img = fpi_img_resize(img, img->height * FRAME_WIDTH); - img->flags = FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED | FP_IMG_COLORS_INVERTED; *ret = img; return 0; err: From 069b4a30ebdac8723a1f7a3e2d880924a6be9552 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Thu, 15 Nov 2007 17:23:36 +0000 Subject: [PATCH 065/184] Doc and build updates Add ChangeLog generation makefile target. Group all copyright notices in AUTHORS. Update some doxygen comments, and allow fp_dev_close(NULL) --- .gitignore | 1 + AUTHORS | 8 +++++++- ChangeLog | 1 - HACKING | 11 +++++++++++ Makefile.am | 6 ++++++ README | 8 +++++++- THANKS | 1 - libfprint/core.c | 8 ++++++-- libfprint/data.c | 5 +++-- 9 files changed, 41 insertions(+), 8 deletions(-) delete mode 100644 ChangeLog diff --git a/.gitignore b/.gitignore index 8a4f1197..20dcfdfc 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,4 @@ install-sh .deps .libs compile +ChangeLog diff --git a/AUTHORS b/AUTHORS index e119bbd8..f5885123 100644 --- a/AUTHORS +++ b/AUTHORS @@ -1 +1,7 @@ -Daniel Drake +Copyright (C) 2007 Daniel Drake +Copyright (C) 2006-2007 Timo Hoenig +Copyright (C) 2006 Pavel Machek +Copyright (C) 1999 Erik Walthinsen +Copyright (C) 2004,2006 Thomas Vander Stichele +Copyright (C) 2007 Cyrille Bagard +Copyright (C) 2007 Vasily Khoruzhick diff --git a/ChangeLog b/ChangeLog deleted file mode 100644 index 941b3ac2..00000000 --- a/ChangeLog +++ /dev/null @@ -1 +0,0 @@ -The ChangeLog is maintained in the git source control system. diff --git a/HACKING b/HACKING index fcd3e19d..00ff2062 100644 --- a/HACKING +++ b/HACKING @@ -1,3 +1,14 @@ +Copyright notices +================= + +If you make a contribution substantial enough to add or update a copyright +notice on a file, such notice must be mirrored in the AUTHORS file. This is +to make it easy for people to comply to section 6 of the LGPL, which states +that a "work that uses the Library" must include copyright notices from +this library. By providing them all in one place, hopefully we save such +users some time. + + USB === diff --git a/Makefile.am b/Makefile.am index 1921cdc0..729a285a 100644 --- a/Makefile.am +++ b/Makefile.am @@ -10,3 +10,9 @@ pkgconfigdir=$(libdir)/pkgconfig pkgconfig_DATA=libfprint.pc DISTCLEANFILES=libfprint.pc +.PHONY: ChangeLog +ChangeLog: + git --git-dir $(top_srcdir)/.git log > ChangeLog + +dist-hook: ChangeLog + diff --git a/README b/README index 6e4686cc..a9658925 100644 --- a/README +++ b/README @@ -17,9 +17,15 @@ http://www.reactivated.net/fprint/Libfprint libfprint is licensed under the GNU LGPL version 2.1. See the COPYING file for the license text. +Section 6 of the license states that for compiled works that use this +library, such works must include libfprint copyright notices alongside the +copyright notices for the other parts of the work. We have attempted to +make this process slightly easier for you by grouping these all in one place: +the AUTHORS file. + libfprint includes code from NIST's NBIS software distribution: http://fingerprint.nist.gov/NBIS/index.html We include bozorth3 from the US export controlled distribution. We have determined that it is fine to ship bozorth3 in an open source project, -see http://reactivated.net/fprint/US_export_control +see http://reactivated.net/fprint/wiki/US_export_control diff --git a/THANKS b/THANKS index 68143f9e..76c08171 100644 --- a/THANKS +++ b/THANKS @@ -6,4 +6,3 @@ Craig Watson (NIST) James Vasile (SFLC) Toby Howard (University of Manchester) Seemant Kulleen -Vasily Khoruzhick diff --git a/libfprint/core.c b/libfprint/core.c index 928b2851..6fc26169 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -453,7 +453,8 @@ API_EXPORTED struct fp_dscv_dev **fp_discover_devs(void) * Free a list of discovered devices. This function destroys the list and all * discovered devices that it included, so make sure you have opened your * discovered device before freeing the list. - * \param devs the list of discovered devices + * \param devs the list of discovered devices. If NULL, function simply + * returns. */ API_EXPORTED void fp_dscv_devs_free(struct fp_dscv_dev **devs) { @@ -619,10 +620,13 @@ static void do_close(struct fp_dev *dev) /** \ingroup dev * Close a device. You must call this function when you are finished using * a fingerprint device. - * \param dev the device to close + * \param dev the device to close. If NULL, function simply returns. */ API_EXPORTED void fp_dev_close(struct fp_dev *dev) { + if (!dev) + return; + fp_dbg(""); if (g_slist_index(opened_devices, (gconstpointer) dev) == -1) diff --git a/libfprint/data.c b/libfprint/data.c index 97ed5d0a..79d161db 100644 --- a/libfprint/data.c +++ b/libfprint/data.c @@ -378,7 +378,7 @@ API_EXPORTED int fp_print_data_from_dscv_print(struct fp_dscv_print *print, /** \ingroup print_data * Frees a stored print. Must be called when you are finished using the print. - * \param data the stored print to destroy + * \param data the stored print to destroy. If NULL, function simply returns. */ API_EXPORTED void fp_print_data_free(struct fp_print_data *data) { @@ -586,7 +586,8 @@ API_EXPORTED struct fp_dscv_print **fp_discover_prints(void) * Frees a list of discovered prints. This function also frees the discovered * prints themselves, so make sure you do not use any discovered prints * after calling this function. - * \param prints the list of discovered prints + * \param prints the list of discovered prints. If NULL, function simply + * returns. */ API_EXPORTED void fp_dscv_prints_free(struct fp_dscv_print **prints) { From 3fa3c0daf7f909187870f4f8136a9e830d18bdfb Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Fri, 16 Nov 2007 13:14:30 +0000 Subject: [PATCH 066/184] Initialize enrolled image pointer to NULL Currently this is a dangling pointer if the image capture fails, and then we try to standardize an invalid pointer --> crash --- libfprint/imgdev.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index b9da4b5a..1e99998b 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -159,7 +159,7 @@ err: int img_dev_enroll(struct fp_dev *dev, gboolean initial, int stage, struct fp_print_data **ret, struct fp_img **_img) { - struct fp_img *img; + struct fp_img *img = NULL; struct fp_img_dev *imgdev = dev->priv; struct fp_print_data *print; int r; From bfc55c4f0f4ff75b52c9d9c2d7b2fffb01c5dc8e Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Fri, 16 Nov 2007 12:49:29 +0000 Subject: [PATCH 067/184] Use older ImageMagick API Debian ship an ImageMagick that is more than 2 years old. Switch to using older APIs so that we have compatibility all-round. --- libfprint/img.c | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/libfprint/img.c b/libfprint/img.c index 9bc9a512..3db92488 100644 --- a/libfprint/img.c +++ b/libfprint/img.c @@ -231,7 +231,7 @@ static struct fp_img *im_resize(struct fp_img *img, unsigned int factor) { Image *mimg; Image *resized; - ExceptionInfo *exception; + ExceptionInfo exception; MagickBooleanType ret; int new_width = img->width * factor; int new_height = img->height * factor; @@ -242,23 +242,23 @@ static struct fp_img *im_resize(struct fp_img *img, unsigned int factor) * result, which improves matching performances in my experiments. */ if (!IsMagickInstantiated()) - MagickCoreGenesis(NULL, MagickFalse); + InitializeMagick(NULL); + + GetExceptionInfo(&exception); + mimg = ConstituteImage(img->width, img->height, "I", CharPixel, img->data, + &exception); - exception = AcquireExceptionInfo(); - - mimg = ConstituteImage(img->width, img->height, "I", CharPixel, img->data, exception); - - ClearMagickException(exception); - resized = ResizeImage(mimg, new_width, new_height, 0, 1.0, exception); + GetExceptionInfo(&exception); + resized = ResizeImage(mimg, new_width, new_height, 0, 1.0, &exception); newimg = fpi_img_new(new_width * new_height); newimg->width = new_width; newimg->height = new_height; newimg->flags = img->flags; - ClearMagickException(exception); + GetExceptionInfo(&exception); ret = ExportImagePixels(resized, 0, 0, new_width, new_height, "I", - CharPixel, newimg->data, exception); + CharPixel, newimg->data, &exception); if (ret != MagickTrue) { fp_err("export failed"); return NULL; @@ -266,7 +266,6 @@ static struct fp_img *im_resize(struct fp_img *img, unsigned int factor) DestroyImage(mimg); DestroyImage(resized); - DestroyExceptionInfo(exception); return newimg; } From be0e9debd90592525cc135a22fc92e08be4b0274 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Fri, 16 Nov 2007 15:35:48 +0000 Subject: [PATCH 068/184] aes2501: write multiple registers simultaneously Instead of writing each register in a separate USB transaction, we now write up to 16 at once. This drastically improves scan image quality due to reducing the amount of time needed per iteration of the sampling loop (sending 1 USB transaction per iteration instead of 7). --- libfprint/drivers/aes2501.c | 55 +++++++++++++++++++++++++++++-------- 1 file changed, 43 insertions(+), 12 deletions(-) diff --git a/libfprint/drivers/aes2501.c b/libfprint/drivers/aes2501.c index 3d95ea5c..b2494b29 100644 --- a/libfprint/drivers/aes2501.c +++ b/libfprint/drivers/aes2501.c @@ -36,6 +36,7 @@ #define EP_OUT (2 | USB_ENDPOINT_OUT) #define BULK_TIMEOUT 4000 +#define MAX_REGWRITES_PER_REQUEST 16 /* * The AES2501 is an imaging device using a swipe-type sensor. It samples @@ -61,19 +62,27 @@ struct aes2501_regwrite { unsigned char value; }; -static int write_reg(struct fp_img_dev *dev, unsigned char reg, - unsigned char value) +static int do_write_regv(struct fp_img_dev *dev, struct aes2501_regwrite *regs, + unsigned int num) { - unsigned char data[] = { reg, value }; + size_t alloc_size = num * 2; + unsigned char *data = g_malloc(alloc_size); + unsigned int i; + size_t offset = 0; int r; - fp_dbg("%02x=%02x", reg, value); - r = usb_bulk_write(dev->udev, EP_OUT, data, sizeof(data), BULK_TIMEOUT); + for (i = 0; i < num; i++) { + data[offset++] = regs[i].reg; + data[offset++] = regs[i].value; + } + + r = usb_bulk_write(dev->udev, EP_OUT, data, alloc_size, BULK_TIMEOUT); + g_free(data); if (r < 0) { fp_err("bulk write error %d", r); return r; - } else if (r < sizeof(data)) { - fp_err("unexpected short write %d/%d", r, sizeof(data)); + } else if (r < alloc_size) { + fp_err("unexpected short write %d/%d", r, alloc_size); return -EIO; } @@ -84,15 +93,27 @@ static int write_regv(struct fp_img_dev *dev, struct aes2501_regwrite *regs, unsigned int num) { unsigned int i; - int r; + int skip = 0; + int add_offset = 0; + fp_dbg("write %d regs", num); - /* FIXME: could combine multiple writes into a single transaction */ + for (i = 0; i < num; i += add_offset + skip) { + int r, j; + int limit = MIN(num, i + MAX_REGWRITES_PER_REQUEST); + skip = 0; - for (i = 0; i < num; i++) { - r = write_reg(dev, regs[i].reg, regs[i].value); + for (j = i; j < limit; j++) + if (!regs[j].reg) { + skip = 1; + break; + } + + add_offset = j - i; + r = do_write_regv(dev, ®s[i], add_offset); if (r < 0) return r; } + return 0; } @@ -115,9 +136,13 @@ static int read_data(struct fp_img_dev *dev, unsigned char *data, size_t len) static int read_regs(struct fp_img_dev *dev, unsigned char *data) { int r; + const struct aes2501_regwrite regwrite = { + AES2501_REG_CTRL2, AES2501_CTRL2_READ_REGS + }; + fp_dbg(""); - r = write_reg(dev, AES2501_REG_CTRL2, AES2501_CTRL2_READ_REGS); + r = write_regv(dev, ®write, 1); if (r < 0) return r; @@ -126,6 +151,7 @@ static int read_regs(struct fp_img_dev *dev, unsigned char *data) static const struct aes2501_regwrite init_1[] = { { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, + { 0, 0 }, { 0xb0, 0x27 }, /* Reserved? */ { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, { AES2501_REG_EXCITCTRL, 0x40 }, @@ -304,6 +330,7 @@ static const struct aes2501_regwrite finger_det_reqs[] = { { 0xa7, 0x00 }, { AES2501_REG_TREGC, AES2501_TREGC_ENABLE }, { AES2501_REG_TREGD, 0x1a }, + { 0, 0 }, { AES2501_REG_CTRL1, AES2501_CTRL1_REG_UPDATE }, { AES2501_REG_CTRL2, AES2501_CTRL2_SET_ONE_SHOT }, { AES2501_REG_LPONT, AES2501_LPONT_MIN_VALUE }, @@ -460,6 +487,7 @@ static unsigned int assemble(unsigned char *input, unsigned char *output, static const struct aes2501_regwrite capture_reqs_1[] = { { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, + { 0, 0 }, { AES2501_REG_EXCITCTRL, 0x40 }, { AES2501_REG_DETCTRL, AES2501_DETCTRL_SDELAY_31_MS | AES2501_DETCTRL_DRATE_CONTINUOUS }, @@ -590,6 +618,9 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, if (r_errors_sum > errors_sum) { img->height = assemble(img->data, cooked, nstrips, FALSE, &errors_sum); img->flags |= FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED; + fp_dbg("normal scan direction"); + } else { + fp_dbg("reversed scan direction"); } for (i = 0; i < img->height * FRAME_WIDTH; i++) From 791eeab85991f513d437809b83863f400105db13 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Fri, 16 Nov 2007 15:44:09 +0000 Subject: [PATCH 069/184] aes2501: restore default bozorth3 match threshold With the multiple register writing code, the image quality is much better. It's trivially easy to get a match score of 100, and 200 is possible with a little effort. Remove the lowered match threshold. --- libfprint/drivers/aes2501.c | 3 --- 1 file changed, 3 deletions(-) diff --git a/libfprint/drivers/aes2501.c b/libfprint/drivers/aes2501.c index b2494b29..1c60aca3 100644 --- a/libfprint/drivers/aes2501.c +++ b/libfprint/drivers/aes2501.c @@ -650,9 +650,6 @@ struct fp_img_driver aes2501_driver = { .img_height = -1, .img_width = 192, - /* temporarily lowered until image quality improves */ - .bz3_threshold = 20, - .init = dev_init, .exit = dev_exit, .await_finger_on = await_finger_on, From 72c304999a07af03f0bad9485ebee6f9d0fcb520 Mon Sep 17 00:00:00 2001 From: Jan-Michael Brummer Date: Fri, 16 Nov 2007 18:15:43 +0000 Subject: [PATCH 070/184] Add UPEK TouchChip driver The UPEK TouchChip is an active capacitance imaging device with a press-type sensor. It also has image storage capabilities which will hopefully be accessible through libfprint in the near future. This device can be found in the Samsung P35 laptop. --- AUTHORS | 1 + libfprint/Makefile.am | 3 +- libfprint/core.c | 1 + libfprint/drivers/upektc.c | 405 +++++++++++++++++++++++++++++++++++++ libfprint/fp_internal.h | 1 + 5 files changed, 410 insertions(+), 1 deletion(-) create mode 100644 libfprint/drivers/upektc.c diff --git a/AUTHORS b/AUTHORS index f5885123..db6fd07f 100644 --- a/AUTHORS +++ b/AUTHORS @@ -5,3 +5,4 @@ Copyright (C) 1999 Erik Walthinsen Copyright (C) 2004,2006 Thomas Vander Stichele Copyright (C) 2007 Cyrille Bagard Copyright (C) 2007 Vasily Khoruzhick +Copyright (C) 2007 Jan-Michael Brummer diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index c5ff97bb..194f423e 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -1,11 +1,12 @@ lib_LTLIBRARIES = libfprint.la UPEKTS_SRC = drivers/upekts.c +UPEKTC_SRC = drivers/upektc.c URU4000_SRC = drivers/uru4000.c AES2501_SRC = drivers/aes2501.c drivers/aes2501.h AES4000_SRC = drivers/aes4000.c -DRIVER_SRC = $(UPEKTS_SRC) $(URU4000_SRC) $(AES2501_SRC) $(AES4000_SRC) +DRIVER_SRC = $(UPEKTS_SRC) $(URU4000_SRC) $(AES2501_SRC) $(AES4000_SRC) $(UPEKTC_SRC) NBIS_SRC = \ nbis/include/bozorth.h \ diff --git a/libfprint/core.c b/libfprint/core.c index 6fc26169..639c4da7 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -336,6 +336,7 @@ static struct fp_img_driver * const img_drivers[] = { &uru4000_driver, &aes2501_driver, &aes4000_driver, + &upektc_driver, }; static void register_drivers(void) diff --git a/libfprint/drivers/upektc.c b/libfprint/drivers/upektc.c new file mode 100644 index 00000000..92aeffa8 --- /dev/null +++ b/libfprint/drivers/upektc.c @@ -0,0 +1,405 @@ +/* + * UPEK TouchChip driver for libfprint + * Copyright (C) 2007 Jan-Michael Brummer + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#define FP_COMPONENT "upektc" + +#include +#include + +#include +#include + +#include + +#define SENSOR_FULL_IMAGE 59904 +#define WAIT_COUNT 5 + +typedef char sint8; +typedef unsigned char uint8; +typedef int sint32; +typedef unsigned int uint32; + +/** scan command */ +static const sint8 anScanCommand[ 0x40 ] = { + 0x0e, 0x00, 0x03, 0xa8, 0x00, 0xb6, 0xbb, 0xbb, + 0xb8, 0xb7, 0xb8, 0xb5, 0xb8, 0xb9, 0xb8, 0xb9, + 0xbb, 0xbb, 0xbe, 0xbb, 0x4e, 0x16, 0xf4, 0x77, + 0xa8, 0x07, 0x32, 0x00, 0x6a, 0x16, 0xf4, 0x77, + 0x78, 0x24, 0x61, 0x00, 0xc8, 0x00, 0xec, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x3c, 0xf3, 0x2f, 0x01, + 0x05, 0x90, 0xf6, 0x77, 0x84, 0xf5, 0x2f, 0x01, + 0x05, 0x90, 0xf6, 0x00, 0xc8, 0x00, 0xec, 0x00 +}; + +/** init command */ +static const sint8 anInitCommand[ 0x40 ] = { + 0x03, 0x00, 0x00, 0x00, 0x02, 0xfb, 0x0f, 0x00, + 0xc4, 0xf9, 0x2f, 0x01, 0x6d, 0x4f, 0x01, 0x10, + 0x44, 0xf9, 0x2f, 0x01, 0x40, 0x00, 0x00, 0x00, + 0xe8, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +}; + +/** + * \brief Common interaktion routine for the sensor device + * \param dev fingerprint image device pointer + * \param pnRawString raw data string + * \param nLen length we want to read, if 0 do not read at all + * \param pnBuffer buffer pointer we want to store the read buffer + * \return error code + */ +static sint32 askScanner( struct fp_img_dev *dev, sint8 *pnRawString, sint32 nLen, sint8 *pnBuffer ) { + sint8 anBuf[ 65535 ]; + sint32 nRet; + + nRet = usb_bulk_write( dev -> udev, 0x00000003, pnRawString, 0x40, 1003 ); + if ( nRet != 0x40 ) { + return -1; + } + + if ( !nLen ) { + return 0; + } + + nRet = usb_bulk_read( dev -> udev, 0x00000082, anBuf, nLen, 1003 ); + if ( ( nRet == nLen ) && ( pnBuffer != NULL ) ) { + memcpy( pnBuffer, anBuf, nLen ); + return nRet; + } + + return nRet; +} + +/** + * \brief Quick test if finger is on sensor + * \param pnImage image pointer + * \return 1 on yes, 0 on no + */ +static sint32 ValidScan( sint8 *pnImage ) { + sint32 nIndex, nSum; + + nSum = 0; + + for ( nIndex = 0; nIndex < SENSOR_FULL_IMAGE; nIndex++ ) { + if ( ( uint8 ) pnImage[ nIndex ] < 160 ) { + nSum++; + } + } + + return nSum < 500 ? 0 : 1; +} + +/** + * \brief Setup Sensor device + * \param dev fingerprint image device pointer + * \return error code + */ +static sint32 SetupSensor( struct fp_img_dev *dev ) { + usb_claim_interface( dev -> udev, 0 ); + + /* setup sensor */ + if ( askScanner( dev, "\x03\x00\x00\x00\x02\xfe\x00\x01\xc0\xbd\xf0\xff\xff\xff\xff\xff\x00\xf0\xfd\x7f\x00\x60\xfd\x7f\x14\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x10\x00\x00\x00\xcc\xf8\x2f\x01\x09\x48\xe7\x77\xf0\xfa\x2f\x01\x09\x48\xe7\x77\xe0\x3a\xe6\x77", 0x00, NULL ) < 0 ) { + return -1; + } + + if ( askScanner( dev, "\x82\x00\x00\x00\x01\xf7\x00\x00\xc8\x01\x00\x00\x40\x00\x00\x00\x01\x00\x00\x00\x58\xf9\x2f\x01\xe9\x4f\x01\x10\xd8\xf8\x2f\x01\x40\x00\x00\x00\xe8\x03\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x02\xfe\x00\x01\xc0\xbd\xf0\xff\xff\xff\xff\xff\x00\xf0\xfd\x7f", 0x40, NULL ) < 0 ) { + return -2; + }; + + if ( askScanner( dev, "\x03\x00\x00\x00\x02\xf7\xcd\x00\x2c\xf9\x2f\x01\x6d\x4f\x01\x10\xac\xf8\x2f\x01\x40\x00\x00\x00\xe8\x03\x00\x00\x00\x00\x00\x00\x02\xfe\x16\x10\x03\xee\x00\x37\x01\x09\x02\x0e\x03\x18\x03\x1a\x03\x20\x10\x2f\x11\x3f\x12\x44\x01\x01\x07\x08\x0c\x00\x6c\x6c", 0x00, NULL ) < 0 ) { + return -3; + }; + if ( askScanner( dev, "\x82\x00\x00\x00\x01\xf8\x00\x00\x02\xfe\x16\x10\x03\xee\x00\x37\x01\x09\x02\x0e\x03\x18\x03\x1a\x03\x20\x10\x2f\x11\x3f\x12\x44\x01\x01\x07\x08\x0c\x00\x6c\x6c\x00\xf9\x2f\x01\x97\x40\x01\x10\x03\x00\x00\x00\x00\x00\x00\x00\xfa\x45\x03\x10\x02\x00\x00\x00", 0x40, NULL ) < 0 ) { + return -4; + }; + + if ( askScanner( dev, "\x8b\x00\x00\x00\x3a\x50\xf9\x2f\x01\x18\x00\x00\x00\xff\xff\xff\xff\x00\x00\x00\x00\x88\xf9\x2f\x01\x91\x99\x00\x10\xf8\x00\x00\x00\xbe\x99\x00\x10\xa0\xa6\x04\x10\x01\x9b\x00\x10\x18\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf8\x00\x00", 0x40, NULL ) < 0 ) { + return -5; + }; + if ( askScanner( dev, "\x82\x00\x00\x00\x3a\x00\x01\x02\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1f\x20\x21\x22\x23\x24\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3d\x3f\xff\x00", 0x40, NULL ) < 0 ) { + return -6; + }; + if ( askScanner( dev, "\x82\x00\x00\x00\x3a\x00\x01\x02\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1f\x20\x21\x22\x23\x24\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3d\x3f\xff\x00", 0x40, NULL ) < 0 ) { + return -7; + }; + + if ( askScanner( dev, "\x03\x00\x00\x00\x02\x0d\xff\x36\xdc\xf8\x2f\x01\xf1\x9d\x00\x10\xfc\xf8\x2f\x01\x9d\xf8\x2f\x01\x3a\x00\x00\x00\x00\x00\x00\x00\x02\x9e\xbf\x85\x85\x02\x05\x26\x25\x4d\x13\x10\x00\x00\x00\x6c\x00\x00\xcf\x00\x01\x00\x00\x1f\x01\x01\x09\x09\x0f\x00\x6c\x6c", 0x00, NULL ) < 0 ) { + return -8; + }; + if ( askScanner( dev, "\x03\x00\x00\x00\x0c\x37\x6a\x3d\x73\x3d\x71\x0e\x01\x0e\x81\x3d\x51\xf8\x2f\x01\x3a\x00\x00\x00\x00\x00\x00\x00\x02\x9e\xbf\x85\x85\x02\x05\x26\x25\x4d\x13\x10\x00\x00\x00\x6c\x00\x00\xcf\x00\x01\x00\x00\x1f\x01\x01\x09\x09\x0f\x00\x6c\x6c\xf0\xf8\x2f\x01", 0x00, NULL ) < 0 ) { + return -9; + }; + if ( askScanner( dev, "\x82\x00\x00\x00\x3a\x00\x01\x02\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1f\x20\x21\x22\x23\x24\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3d\x3f\xff\x00", 0x40, NULL ) < 0 ) { + return -10; + }; + + if ( askScanner( dev, "\x8b\x00\x01\x7c\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x7f\x14\xf5\x2f\x01\xa0\x20\x14\x00\x40\xf8\x2f\x01\x05\x90\xf6\x77\x04\x00\x00\x00\x08\x00\x00\x00\x50\xf8\x2f\x01\x40\x39\xf4\x77\xa8\x20\x14\x00\x1c\xf6\x2f\x01\x2c\x20\xf4\x77\x80\x4d\xfb\x77", 0x40, NULL ) < 0 ) { + return -11; + }; + if ( askScanner( dev, "\x8b\x00\x03\xc8\x3a\x01\x00\x00\x1f\x01\x01\x09\x09\x0f\x00\x6c\x6c\x6c\x6c\x40\x40\x40\x40\x40\x40\x40\x40\x40\x40\x6c\x00\x00\x00\x00\x00\x60\x62\x62\x62\x62\x62\x51\x6c\x00\x00\x00\x00\x00\x00\x40\xf9\x2f\x01\x4f\x9d\x00\x10\x3a\x00\x00\x00\x04\xf9\x01", 0x40, NULL ) < 0 ) { + return -12; + }; + if ( askScanner( dev, "\x8b\x00\x04\x02\x06\x0b\x07\x13\x0e\x55\x56\x01\x44\xf8\x2f\x01\x00\x00\x00\x00\x40\x00\x00\x00\x40\x40\x40\x40\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x40\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc8\x01\x00\x00\xc8\x01\x00\x00\x40\x00\x00\x00", 0x40, NULL ) < 0 ) { + return -13; + }; + + if ( askScanner( dev, "\x07\x00\x20\x00\x3a\x0e\x13\x07\x0f\x14\x07\x10\x15\x07\x12\x16\x07\x13\x17\x07\x14\x18\x07\x15\x18\x07\x16\x19\x07\x17\x1a\x07\x19\x1b\x07\x1a\x1c\x07\x1b\x1d\x07\x1c\x1e\x07\x1d\x1f\x07\x1e\x20\x07\x1f\x21\x07\x20\x22\x07\x21\x23\x07\x23\x23\x07\x24\x55", 0x00, NULL ) < 0 ) { + return -14; + }; + if ( askScanner( dev, "\x07\x00\x20\x3a\x26\x24\x07\x25\x25\x07\x26\x25\x07\x27\x26\x07\x28\x27\x07\x29\x27\x07\x2a\x28\x07\x2b\x29\x07\x2d\x29\x07\x2e\x2a\x07\x2f\x2b\x07\x30\x2b\x07\x31\x2c\x07\x07\x1d\x1f\x07\x1e\x20\x07\x1f\x21\x07\x20\x22\x07\x21\x23\x07\x23\x23\x07\x24\x55", 0x00, NULL ) < 0 ) { + return -15; + }; + + if ( askScanner( dev, "\x03\x00\x00\x00\x06\x0e\x81\x0e\x81\x09\x4d\x00\x07\x00\x20\x3a\x26\x24\x07\x25\x25\x07\x26\x25\x07\x27\x26\x07\x28\x27\x07\x29\x27\x07\x2a\x28\x07\x2b\x29\x07\x2d\x29\x07\x2e\x2a\x07\x2f\x2b\x07\x30\x2b\x07\x31\x2c\x07\x07\x1d\x1f\x07\x1e\x20\x07\x1f\x21", 0x00, NULL ) < 0 ) { + return -16; + }; + if ( askScanner( dev, "\x82\x00\x00\x00\x3a\x00\x01\x02\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1f\x20\x21\x22\x23\x24\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3d\x3f\xff\x00", 0x40, NULL ) < 0 ) { + return -17; + }; + + if ( askScanner( dev, "\x03\x00\x00\x00\x02\x0e\x85\x36\xd8\xf8\x2f\x01\xf1\x9d\x00\x10\xf8\xf8\x2f\x01\x99\xf8\x2f\x01\x3a\x00\x00\x00\x00\x00\x00\x00\x02\x9e\xbf\x85\x85\x02\x05\x26\x25\x4d\x10\x10\x00\xff\x81\x6c\x00\x00\xcf\x00\x01\x00\x00\x1f\x01\x01\x09\x09\x0f\x00\x6c\x6c", 0x00, NULL ) < 0 ) { + return -18; + }; + if ( askScanner( dev, "\x82\x00\x00\x00\x01\x0d\x00\x00\x02\x9e\xbf\x85\x85\x02\x05\x26\x25\x4d\x10\x10\x00\xff\x81\x6c\x00\x00\xcf\x00\x01\x00\x00\x1f\x01\x01\x09\x09\x0f\x00\x6c\x6c\xec\xf8\x2f\x01\x97\x40\x01\x10\x03\x00\x00\x00\x00\x00\x00\x00\xfa\x45\x03\x10\x02\x00\x00\x00", 0x40, NULL ) < 0 ) { + return -19; + }; + if ( askScanner( dev, "\x82\x00\x00\x00\x01\xf7\xcf\x00\x01\x00\x00\x1f\x01\x01\x09\x09\x0f\x00\x6c\x6c\x6c\x6c\x40\x40\x40\x40\x40\x40\x40\x40\x40\x40\x6c\x00\x00\x00\x00\x00\x60\x62\x62\x62\x62\x62\x51\x6c\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00", 0x40, NULL ) < 0 ) { + return -20; + }; + if ( askScanner( dev, "\x82\x00\x00\x00\x01\xf7\x00\x00\x02\xf9\xbf\x85\x85\x02\x05\x26\x25\x4d\x10\x10\x00\xff\x81\x6c\x00\x00\xcf\x00\x01\x00\x00\x1f\x01\x01\x09\x09\x0f\x00\x6c\x6c\x6c\x6c\x40\x40\x40\x40\x40\x40\x40\x40\x40\x40\x6c\x00\x00\x00\x00\x00\x60\x62\x62\x62\x62\x62", 0x40, NULL ) < 0 ) { + return -21; + }; + + if ( askScanner( dev, "\x03\x00\x00\x00\x02\xf7\xf4\x00\x14\xf9\x2f\x01\x6d\x4f\x01\x10\x94\xf8\x2f\x01\x40\x00\x00\x00\xe8\x03\x00\x00\x00\x00\x00\x00\x02\xf9\xbf\x85\x85\x02\x05\x26\x25\x4d\x10\x10\x00\xff\x81\x6c\x00\x00\xcf\x00\x01\x00\x00\x1f\x01\x01\x09\x09\x0f\x00\x6c\x6c", 0x00, NULL ) < 0 ) { + return -22; + }; + if ( askScanner( dev, "\x03\x00\x00\x00\x02\x20\x6c\x01\x6d\x4f\x01\x10\x94\xf8\x2f\x01\x40\x00\x00\x00\xe8\x03\x00\x00\x00\x00\x00\x00\x02\xf9\xbf\x85\x85\x02\x05\x26\x25\x4d\x10\x10\x00\xff\x81\x6c\x00\x00\xcf\x00\x01\x00\x00\x1f\x01\x01\x09\x09\x0f\x00\x6c\x6c\xe8\xf8\x2f\x01", 0x00, NULL ) < 0 ) { + return -23; + }; + if ( askScanner( dev, "\x82\x00\x00\x00\x01\xf9\x81\x6c\x00\x00\xcf\x00\x01\x00\x00\x1f\x01\x01\x09\x09\x0f\x00\x6c\x6c\xe8\xf8\x2f\x01\xec\xf8\x2f\x01\x97\x40\x01\x10\x03\x00\x00\x00\x00\x00\x00\x00\xfa\x45\x03\x10\x02\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00", 0x40, NULL ) < 0 ) { + return -24; + }; + + if ( askScanner( dev, "\x03\x00\x00\x00\x02\xf9\x01\x00\x1c\xf9\x2f\x01\x6d\x4f\x01\x10\x9c\xf8\x2f\x01\x40\x00\x00\x00\xe8\x03\x00\x00\x00\x00\x00\x00\x02\x6c\xbf\x85\x85\x02\x05\x26\x25\x4d\x10\x10\x00\xff\x81\x6c\x00\x00\xcf\x00\x01\x00\x00\x1f\x01\x01\x09\x09\x0f\x00\x6c\x6c", 0x00, NULL ) < 0 ) { + return -25; + }; + if ( askScanner( dev, "\x03\x00\x00\x00\x12\x1c\x0c\x1b\x08\x1a\x07\x30\x08\x09\x6d\x08\x27\x00\x9e\x00\x1e\x23\x47\x01\x40\x00\x00\x00\xe8\x03\x00\x00\x00\x00\x00\x00\x02\x6c\xbf\x85\x85\x02\x05\x26\x25\x4d\x10\x10\x00\xff\x81\x6c\x00\x00\xcf\x00\x01\x00\x00\x1f\x01\x01\x09\x09", 0x00, NULL ) < 0 ) { + return -26; + }; + if ( askScanner( dev, "\x82\x00\x00\x00\x3a\x00\x01\x02\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1f\x20\x21\x22\x23\x24\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3d\x3f\xff\x00", 0x40, NULL ) < 0 ) { + return -27; + }; + + if ( askScanner( dev, "\x03\x00\x00\x00\x02\x0d\xff\x36\xdc\xf8\x2f\x01\xf1\x9d\x00\x10\xfc\xf8\x2f\x01\x9d\xf8\x2f\x01\x3a\x00\x00\x00\x00\x00\x00\x00\x02\x1e\x3f\x05\x05\x02\x05\x26\x27\x6d\x10\x10\x00\xff\x85\x6c\x00\x00\xcf\x00\x01\x00\x00\x1f\x01\x01\x07\x08\x0c\x00\x6c\x6c", 0x00, NULL ) < 0 ) { + return -28; + }; + + if ( askScanner( dev, "\x08\x00\x00\x00\x0a\x00\x00\xcf\x00\x01\x00\x00\x1f\x01\x01\x10\xfc\xf8\x2f\x01\x9d\xf8\x2f\x01\x3a\x00\x00\x00\x00\x00\x00\x00\x02\x1e\x3f\x05\x05\x02\x05\x26\x27\x6d\x10\x10\x00\xff\x85\x6c\x00\x00\xcf\x00\x01\x00\x00\x1f\x01\x01\x07\x08\x0c\x00\x6c\x6c", 0x00, NULL ) < 0 ) { + return -29; + }; + + if ( askScanner( dev, "\x03\x00\x00\x00\x08\x0e\x85\x09\xed\x09\x6d\x09\xed\x1e\x3f\x05\x05\x02\x05\x26\x27\x6d\x10\x10\x00\xff\x85\x6c\x00\x00\xcf\x00\x01\x00\x00\x1f\x01\x01\x07\x08\x0c\x00\x6c\x6c\xf0\xf8\x2f\x01\x97\x40\x01\x10\x08\x00\x00\x00\x00\x00\x00\x00\x3e\xf9\x2f\x01", 0x00, NULL ) < 0 ) { + return -30; + }; + if ( askScanner( dev, "\x82\x00\x00\x00\x01\xf3\x6c\x6c\xf0\xf8\x2f\x01\x97\x40\x01\x10\x08\x00\x00\x00\x00\x00\x00\x00\x3e\xf9\x2f\x01\x04\xf9\x2f\x01\x97\x40\x01\x10\x03\x00\x00\x00\x00\x00\x00\x00\x00\x46\x03\x10\x08\x00\x00\x00\x08\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00", 0x40, NULL ) < 0 ) { + return -31; + }; + + if ( askScanner( dev, "\x84\x00\x00\x00\x32\x02\xa3\x04\x10\x3b\xa3\x04\x10\x1a\xa3\x04\x10\xf9\xa2\x04\x10\xd8\xa2\x00\xb9\x19\xe2\x87\xba\x56\x78\x72\x68\x9e\x7a\xf4\x65\x6d\xd9\xde\xf6\x33\xa2\x04\x10\x12\xa2\x04\x10\xf1\xa1\x04\x10\x04\x00\x00\x00\x00\x00\x00\xb4\x2d\x6c\xe9", 0x40, NULL ) < 0 ) { + return -32; + }; + + if ( askScanner( dev, "\x03\x00\x00\x00\x06\x1a\x07\x1b\x08\x1c\x0c\x77\x21\xac\xe5\x77\x00\x00\x00\x00\xaa\x4e\x01\x10\x3c\x01\x00\x00\xc4\xf8\x2f\x01\xdc\xf8\x2f\x01\x00\x00\x00\x00\x40\x00\x00\x00\xb9\x19\xe2\x87\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x40\x00\x00\x00", 0x00, NULL ) < 0 ) { + return -33; + }; + + if ( askScanner( dev, "\x08\x00\x00\x00\x0a\x00\x00\xcf\x00\x01\x00\x00\x1f\x01\x01\x00\x40\x00\x00\x00\x00\x00\x00\x00\x40\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc8\x01\x00\x00\x40\x00\x00\x00\x01\x00\x00\x00\xcc\xf8\x2f\x01\x8b\x41\x01\x10\x8c\xf8\x2f\x01\x40\x00\x00\x00", 0x00, NULL ) < 0 ) { + return -34; + }; + + if ( askScanner( dev, "\x03\x00\x00\x00\x04\x3d\x51\x0a\x00\x01\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\xfc\xf9\x2f\x01\x31\x10\x01\x10\xd0\xf9\x2f\x01\x00\x00\x00\x00\x1a\x07\x1b\x08\x1c\x0c\xc6\xf8\x66\xbc\xc4\xbe\x0b\x25\xc5\x4c\xf4\x03\x10\x2f\x11\x3f\x12\x44", 0x00, NULL ) < 0 ) { + return -35; + }; + if ( askScanner( dev, "\x82\x00\x00\x00\x3a\x00\x01\x02\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1f\x20\x21\x22\x23\x24\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3d\x3f\xff\x00", 0x40, NULL ) < 0 ) { + return -36; + }; + + if ( askScanner( dev, "\x03\x00\x00\x00\x02\x0a\x10\x36\x88\xf9\x2f\x01\xf1\x9d\x00\x10\xa8\xf9\x2f\x01\x49\xf9\x2f\x01\x3a\x00\x00\x00\x00\x00\x00\x00\x02\x1e\x3f\x05\x05\x02\x05\x26\x27\xed\x00\x10\x00\xff\x85\x6c\x00\x00\xcf\x00\x01\x00\x00\x1f\x01\x01\x07\x08\x0c\x00\x6c\x6c", 0x00, NULL ) < 0 ) { + return -37; + }; + if ( askScanner( dev, "\x8b\x00\x00\xbc\x3a\x40\xd3\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd8\xf4\x2f\x01\x80\x69\x67\xff\xff\xff\xff\xff\x00\xf0\xfd\x7f\x00\x60\xfd\x7f\x3c\x01\x00\x00\xa0\xf5\x2f\x01\x03\x01\x00\x00\x9a\x11\xf4\x77\x9f\x11\xf4\x77\x3c\x01\x00\x00\xa0\xf5\x01", 0x40, NULL ) < 0 ) { + return -38; + }; + if ( askScanner( dev, "\x8b\x00\x00\xf6\x3a\x0b\x07\xa5\x03\x2f\x63\x97\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 0x40, NULL ) < 0 ) { + return -39; + }; + if ( askScanner( dev, "\x8b\x00\x01\x30\x3a\x0b\x00\x00\x00\x00\x00\x00\x12\xcd\xa6\x3c\x36\xec\x6a\x73\x00\x64\x75\xdf\x2e\x13\xec\xca\x3c\x03\x00\x00\x06\xa5\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 0x40, NULL ) < 0 ) { + return -40; + }; + if ( askScanner( dev, "\x8b\x00\x01\x6a\x3a\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 0x40, NULL ) < 0 ) { + return -41; + }; + if ( askScanner( dev, "\x8b\x00\x01\xa4\x3a\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\xa5\x83\x1b\x8e\xac\x00\x00\x0b\xa5\x08\x08\x03\x00\x00\x01\x02\x03\x06\x00\x00\x00\x00\x00\x8d\xa5\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 0x40, NULL ) < 0 ) { + return -42; + }; + if ( askScanner( dev, "\x8b\x00\x01\xde\x3a\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 0x40, NULL ) < 0 ) { + return -43; + }; + if ( askScanner( dev, "\x8b\x00\x02\x18\x3a\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 0x40, NULL ) < 0 ) { + return -44; + }; + if ( askScanner( dev, "\x8b\x00\x02\x52\x3a\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 0x40, NULL ) < 0 ) { + return -45; + }; + if ( askScanner( dev, "\x8b\x00\x02\x8c\x3a\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 0x40, NULL ) < 0 ) { + return -46; + }; + if ( askScanner( dev, "\x8b\x00\x02\xc6\x2a\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc8\x01\x00\x00\xc8\x01\x00\x00\x40\x00\x00\x00", 0x40, NULL ) < 0 ) { + return -47; + }; + + if ( askScanner( dev, "\x82\x00\x00\x00\x01\xf1\x2f\x01\x49\xf9\x2f\x01\x3a\x00\x00\x00\x00\x00\x00\x00\x02\x1e\x3f\x05\x05\x02\x05\x26\x27\xed\x00\x10\x00\xff\x85\x6c\x00\x00\xcf\x00\x01\x00\x00\x1f\x01\x01\x07\x08\x0c\x00\x6c\x6c\x9c\xf9\x2f\x01\x97\x40\x01\x10\x03\x00\x00\x00", 0x40, NULL ) < 0 ) { + return -48; + }; + + if ( askScanner( dev, "\x03\x00\x00\x00\x02\xf1\x01\x00\xb4\xf9\x2f\x01\x6d\x4f\x01\x10\x34\xf9\x2f\x01\x40\x00\x00\x00\xe8\x03\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 0x00, NULL ) < 0 ) { + return -49; + }; + if ( askScanner( dev, "\x8b\x00\x01\x10\x3a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 0x40, NULL ) < 0 ) { + return -50; + }; + if ( askScanner( dev, "\x8b\x00\x01\x4a\x2e\x0b\x06\xa5\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc8\x01\x00\x00\xc8\x01\x00\x00\x40\x00\x00\x00", 0x40, NULL ) < 0 ) { + return -51; + }; + if ( askScanner( dev, "\x82\x00\x00\x00\x01\xfb\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x88\xf9\x2f\x01\x97\x40\x01\x10\x03\x00\x00\x00\x00\x00\x00\x00\xfa\x45\x03\x10\x02\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 0x40, NULL ) < 0 ) { + return -51; + }; + + /* enable sensor */ + if ( askScanner( dev, anInitCommand, 0x00, NULL ) < 0 ) { + return -52; + } + + return 0; +} + +static int DetectFinger( struct fp_img_dev *dev ) { + sint32 nRet = 0; + uint8 *pnData = NULL; + + pnData = g_malloc( SENSOR_FULL_IMAGE ); + + nRet = askScanner( dev, anScanCommand, SENSOR_FULL_IMAGE, pnData ); + + if ( nRet != SENSOR_FULL_IMAGE ) { + nRet = 0; + goto end; + } + + nRet = ValidScan( pnData ); + +end: + g_free( pnData ); + + return nRet; +} + +static int awaitFingerOn( struct fp_img_dev *dev ) { + int nRet = 0; + int nCount = WAIT_COUNT; + + /* wait until a finger is present */ + do { + nRet = DetectFinger( dev ); + } while ( nRet == 0 ); + + /* give user time to scan his full finger */ + while ( nCount-- ) { + nRet = DetectFinger( dev ); + } + + return nRet != 1 ? nRet : 0; +} + +static int capture( struct fp_img_dev *dev, gboolean unconditional, struct fp_img **ppsRet ) { + struct fp_img *psImg = NULL; + uint8 *pnData = NULL; + sint32 nRet = 0; + + psImg = fpi_img_new_for_imgdev( dev ); + pnData = g_malloc( SENSOR_FULL_IMAGE ); + + nRet = askScanner( dev, anScanCommand, SENSOR_FULL_IMAGE, pnData ); + if ( nRet == SENSOR_FULL_IMAGE ) { + memcpy( psImg -> data, pnData, SENSOR_FULL_IMAGE ); + *ppsRet = psImg; + nRet = 0; + } else { + nRet = -1; + } + +end: + g_free( pnData ); + + return nRet; +} + +static int dev_init( struct fp_img_dev *dev, unsigned long driver_data ) { + int nResult; + + nResult = usb_claim_interface( dev -> udev, 0 ); + if ( nResult < 0 ) { + fp_err( "could not claim interface 0" ); + return nResult; + } + + nResult = SetupSensor( dev ); + + return nResult; +} + +static void dev_exit( struct fp_img_dev *dev ) { + usb_release_interface( dev -> udev, 0 ); +} + +static const struct usb_id id_table[] = { + { .vendor = 0x0483, .product = 0x2015 }, + { 0, 0, 0, }, +}; + +struct fp_img_driver upektc_driver = { + .driver = { + .id = 5, + .name = FP_COMPONENT, + .full_name = "UPEK TouchChip", + .id_table = id_table, + }, + .flags = FP_IMGDRV_SUPPORTS_UNCONDITIONAL_CAPTURE, + .img_height = 288, + .img_width = 208, + + .bz3_threshold = 30, + .init = dev_init, + .exit = dev_exit, + .await_finger_on = awaitFingerOn, + .capture = capture, +}; diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 969c6378..1e6b6845 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -140,6 +140,7 @@ struct fp_img_driver { }; extern struct fp_driver upekts_driver; +extern struct fp_img_driver upektc_driver; extern struct fp_img_driver uru4000_driver; extern struct fp_img_driver aes2501_driver; extern struct fp_img_driver aes4000_driver; From ba24c0884a6c193854104bc234d981928ca33c32 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 17 Nov 2007 12:46:00 +0000 Subject: [PATCH 071/184] Rework some image handling; add public binarization API I want to offer the ability for an application to view a binarized version of a scanned print. This lead onto a few changes: 1. Store minutiae and binarized data inside fp_img 2. Move resize code to the capture path, it previously happened much later. 3. Add fp_img_binarize() to return a new image in binarized form. 4. Add a BINARIZED_FORM flag to prevent an image being binarized again. In future, it would be nice to be able to binarize without detecting minutiae, but this involves some work on the NBIS interaction. --- libfprint/drivers/aes2501.c | 2 +- libfprint/drivers/aes4000.c | 2 +- libfprint/drivers/uru4000.c | 2 +- libfprint/fp_internal.h | 30 ++++++- libfprint/fprint.h | 1 + libfprint/img.c | 169 +++++++++++++++++++---------------- libfprint/imgdev.c | 75 ++++++++++++++-- libfprint/nbis/include/lfs.h | 23 +---- 8 files changed, 198 insertions(+), 106 deletions(-) diff --git a/libfprint/drivers/aes2501.c b/libfprint/drivers/aes2501.c index 1c60aca3..e4757875 100644 --- a/libfprint/drivers/aes2501.c +++ b/libfprint/drivers/aes2501.c @@ -630,7 +630,7 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, *ret = img; return 0; err: - g_free(img); + fp_img_free(img); return r; } diff --git a/libfprint/drivers/aes4000.c b/libfprint/drivers/aes4000.c index 8198132d..4b433462 100644 --- a/libfprint/drivers/aes4000.c +++ b/libfprint/drivers/aes4000.c @@ -181,7 +181,7 @@ retry: return 0; err: g_free(data); - g_free(img); + fp_img_free(img); return r; } diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index 56ac3981..51b57c30 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -360,7 +360,7 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, *ret = img; return 0; err: - g_free(img); + fp_img_free(img); return r; } diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 1e6b6845..2fa7dad0 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -191,16 +191,43 @@ gboolean fpi_print_data_compatible(uint16_t driver_id1, uint32_t devtype1, enum fp_print_data_type type1, uint16_t driver_id2, uint32_t devtype2, enum fp_print_data_type type2); +struct fp_minutia { + int x; + int y; + int ex; + int ey; + int direction; + double reliability; + int type; + int appearing; + int feature_id; + int *nbrs; + int *ridge_counts; + int num_nbrs; +}; + +struct fp_minutiae { + int alloc; + int num; + struct fp_minutia **list; +}; + /* bit values for fp_img.flags */ #define FP_IMG_V_FLIPPED (1<<0) #define FP_IMG_H_FLIPPED (1<<1) #define FP_IMG_COLORS_INVERTED (1<<2) +#define FP_IMG_BINARIZED_FORM (1<<3) + +#define FP_IMG_STANDARDIZATION_FLAGS (FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED \ + | FP_IMG_COLORS_INVERTED) struct fp_img { int width; int height; size_t length; uint16_t flags; + struct fp_minutiae *minutiae; + unsigned char *binarized; unsigned char data[0]; }; @@ -208,7 +235,8 @@ struct fp_img *fpi_img_new(size_t length); struct fp_img *fpi_img_new_for_imgdev(struct fp_img_dev *dev); struct fp_img *fpi_img_resize(struct fp_img *img, size_t newsize); gboolean fpi_img_is_sane(struct fp_img *img); -int fpi_img_detect_minutiae(struct fp_img_dev *imgdev, struct fp_img *img, +int fpi_img_detect_minutiae(struct fp_img *img); +int fpi_img_to_print_data(struct fp_img_dev *imgdev, struct fp_img *img, struct fp_print_data **ret); int fpi_img_compare_print_data(struct fp_print_data *enrolled_print, struct fp_print_data *new_print); diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 334fe999..8eccd03f 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -212,6 +212,7 @@ int fp_img_get_width(struct fp_img *img); unsigned char *fp_img_get_data(struct fp_img *img); int fp_img_save_to_file(struct fp_img *img, char *path); void fp_img_standardize(struct fp_img *img); +struct fp_img *fp_img_binarize(struct fp_img *img); void fp_img_free(struct fp_img *img); /* Library */ diff --git a/libfprint/img.c b/libfprint/img.c index 3db92488..d579a63d 100644 --- a/libfprint/img.c +++ b/libfprint/img.c @@ -23,7 +23,6 @@ #include #include -#include #include "fp_internal.h" #include "nbis/include/bozorth.h" @@ -90,6 +89,13 @@ struct fp_img *fpi_img_resize(struct fp_img *img, size_t newsize) */ API_EXPORTED void fp_img_free(struct fp_img *img) { + if (!img) + return; + + if (img->minutiae) + free_minutiae(img->minutiae); + if (img->binarized) + free(img->binarized); g_free(img); } @@ -227,55 +233,12 @@ API_EXPORTED void fp_img_standardize(struct fp_img *img) } } -static struct fp_img *im_resize(struct fp_img *img, unsigned int factor) -{ - Image *mimg; - Image *resized; - ExceptionInfo exception; - MagickBooleanType ret; - int new_width = img->width * factor; - int new_height = img->height * factor; - struct fp_img *newimg; - - /* It is possible to implement resizing using a simple algorithm, however - * we use ImageMagick because it applies some kind of smoothing to the - * result, which improves matching performances in my experiments. */ - - if (!IsMagickInstantiated()) - InitializeMagick(NULL); - - GetExceptionInfo(&exception); - mimg = ConstituteImage(img->width, img->height, "I", CharPixel, img->data, - &exception); - - GetExceptionInfo(&exception); - resized = ResizeImage(mimg, new_width, new_height, 0, 1.0, &exception); - - newimg = fpi_img_new(new_width * new_height); - newimg->width = new_width; - newimg->height = new_height; - newimg->flags = img->flags; - - GetExceptionInfo(&exception); - ret = ExportImagePixels(resized, 0, 0, new_width, new_height, "I", - CharPixel, newimg->data, &exception); - if (ret != MagickTrue) { - fp_err("export failed"); - return NULL; - } - - DestroyImage(mimg); - DestroyImage(resized); - - return newimg; -} - /* Based on write_minutiae_XYTQ and bz_load */ -static void minutiae_to_xyt(MINUTIAE *minutiae, int bwidth, +static void minutiae_to_xyt(struct fp_minutiae *minutiae, int bwidth, int bheight, unsigned char *buf) { int i; - MINUTIA *minutia; + struct fp_minutia *minutia; struct minutiae_struct c[MAX_FILE_MINUTIAE]; struct xyt_struct *xyt = (struct xyt_struct *) buf; @@ -305,29 +268,20 @@ static void minutiae_to_xyt(MINUTIAE *minutiae, int bwidth, xyt->nrows = nmin; } -int fpi_img_detect_minutiae(struct fp_img_dev *imgdev, struct fp_img *_img, - struct fp_print_data **ret) +int fpi_img_detect_minutiae(struct fp_img *img) { - MINUTIAE *minutiae; + struct fp_minutiae *minutiae; int r; int *direction_map, *low_contrast_map, *low_flow_map; int *high_curve_map, *quality_map; int map_w, map_h; unsigned char *bdata; int bw, bh, bd; - struct fp_print_data *print; - struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(imgdev->dev->drv); - struct fp_img *img = _img; - int free_img = 0; GTimer *timer; - if (imgdrv->enlarge_factor) { - /* FIXME: enlarge_factor should not exist! instead, MINDTCT should - * actually look at the value of the pixels-per-mm parameter and - * figure out itself when the image needs to be treated as if it - * were bigger. */ - img = im_resize(_img, imgdrv->enlarge_factor); - free_img = 1; + if (img->flags & FP_IMG_STANDARDIZATION_FLAGS) { + fp_err("cant detect minutiae for non-standardized image"); + return -EINVAL; } /* 25.4 mm per inch */ @@ -340,34 +294,50 @@ int fpi_img_detect_minutiae(struct fp_img_dev *imgdev, struct fp_img *_img, g_timer_stop(timer); fp_dbg("minutiae scan completed in %f secs", g_timer_elapsed(timer, NULL)); g_timer_destroy(timer); - if (free_img) - g_free(img); if (r) { fp_err("get minutiae failed, code %d", r); return r; } fp_dbg("detected %d minutiae", minutiae->num); - r = minutiae->num; + img->minutiae = minutiae; + img->binarized = bdata; - /* FIXME: space is wasted if we dont hit the max minutiae count. would - * be good to make this dynamic. */ - print = fpi_print_data_new(imgdev->dev, sizeof(struct xyt_struct)); - print->type = PRINT_DATA_NBIS_MINUTIAE; - minutiae_to_xyt(minutiae, bw, bh, print->data); - /* FIXME: the print buffer at this point is endian-specific, and will - * only work when loaded onto machines with identical endianness. not good! - * data format should be platform-independant. */ - *ret = print; - - free_minutiae(minutiae); free(quality_map); free(direction_map); free(low_contrast_map); free(low_flow_map); free(high_curve_map); - free(bdata); + return minutiae->num; +} - return r; +int fpi_img_to_print_data(struct fp_img_dev *imgdev, struct fp_img *img, + struct fp_print_data **ret) +{ + struct fp_print_data *print; + int r; + + if (!img->minutiae) { + r = fpi_img_detect_minutiae(img); + if (r < 0) + return r; + if (!img->minutiae) { + fp_err("no minutiae after successful detection?"); + return -ENOENT; + } + } + + /* FIXME: space is wasted if we dont hit the max minutiae count. would + * be good to make this dynamic. */ + print = fpi_print_data_new(imgdev->dev, sizeof(struct xyt_struct)); + print->type = PRINT_DATA_NBIS_MINUTIAE; + minutiae_to_xyt(img->minutiae, img->width, img->height, print->data); + + /* FIXME: the print buffer at this point is endian-specific, and will + * only work when loaded onto machines with identical endianness. not good! + * data format should be platform-independant. */ + *ret = print; + + return 0; } int fpi_img_compare_print_data(struct fp_print_data *enrolled_print, @@ -393,3 +363,50 @@ int fpi_img_compare_print_data(struct fp_print_data *enrolled_print, return r; } + +/** \ingroup img + * Get a binarized form of a standardized scanned image. This is where the + * fingerprint image has been "enhanced" and is a set of pure black ridges + * on a pure white background. Internally, image processing happens on top + * of the binarized image. + * + * The image must have been \ref img_std "standardized" otherwise this function + * will fail. + * + * It is safe to binarize an image and free the original while continuing + * to use the binarized version. + * + * You cannot binarize an image twice. + * + * \param img a standardized image + * \returns a new image representing the binarized form of the original, or + * NULL on error. Must be freed with fp_img_free() after use. + */ +API_EXPORTED struct fp_img *fp_img_binarize(struct fp_img *img) +{ + struct fp_img *ret; + int height = img->height; + int width = img->width; + int imgsize = height * width; + + if (img->flags & FP_IMG_BINARIZED_FORM) { + fp_err("image already binarized"); + return NULL; + } + + if (!img->binarized) { + int r = fpi_img_detect_minutiae(img); + if (r < 0) + return NULL; + if (!img->binarized) + fp_err("no minutiae after successful detection?"); + } + + ret = fpi_img_new(imgsize); + ret->flags |= FP_IMG_BINARIZED_FORM; + ret->width = width; + ret->height = height; + memcpy(ret->data, img->binarized, imgsize); + return ret; +} + diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index 1e99998b..f072959c 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -18,7 +18,9 @@ */ #include + #include +#include #include "fp_internal.h" @@ -62,14 +64,65 @@ int fpi_imgdev_get_img_width(struct fp_img_dev *imgdev) { struct fp_driver *drv = imgdev->dev->drv; struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); - return imgdrv->img_width; + int width = imgdrv->img_width; + + if (width > 0 && imgdrv->enlarge_factor > 1) + width *= imgdrv->enlarge_factor; + return width; } int fpi_imgdev_get_img_height(struct fp_img_dev *imgdev) { struct fp_driver *drv = imgdev->dev->drv; struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); - return imgdrv->img_height; + int height = imgdrv->img_height; + + if (height > 0 && imgdrv->enlarge_factor > 1) + height *= imgdrv->enlarge_factor; + return height; +} + +static struct fp_img *im_resize(struct fp_img *img, unsigned int factor) +{ + Image *mimg; + Image *resized; + ExceptionInfo exception; + MagickBooleanType ret; + int new_width = img->width * factor; + int new_height = img->height * factor; + struct fp_img *newimg; + + /* It is possible to implement resizing using a simple algorithm, however + * we use ImageMagick because it applies some kind of smoothing to the + * result, which improves matching performances in my experiments. */ + + if (!IsMagickInstantiated()) + InitializeMagick(NULL); + + GetExceptionInfo(&exception); + mimg = ConstituteImage(img->width, img->height, "I", CharPixel, img->data, + &exception); + + GetExceptionInfo(&exception); + resized = ResizeImage(mimg, new_width, new_height, 0, 1.0, &exception); + + newimg = fpi_img_new(new_width * new_height); + newimg->width = new_width; + newimg->height = new_height; + newimg->flags = img->flags; + + GetExceptionInfo(&exception); + ret = ExportImagePixels(resized, 0, 0, new_width, new_height, "I", + CharPixel, newimg->data, &exception); + if (ret != MagickTrue) { + fp_err("export failed"); + return NULL; + } + + DestroyImage(mimg); + DestroyImage(resized); + + return newimg; } int fpi_imgdev_capture(struct fp_img_dev *imgdev, int unconditional, @@ -147,6 +200,16 @@ int fpi_imgdev_capture(struct fp_img_dev *imgdev, int unconditional, goto err; } + if (imgdrv->enlarge_factor > 1) { + /* FIXME: enlarge_factor should not exist! instead, MINDTCT should + * actually look at the value of the pixels-per-mm parameter and + * figure out itself when the image needs to be treated as if it + * were bigger. */ + struct fp_img *tmp = im_resize(img, imgdrv->enlarge_factor); + fp_img_free(img); + img = tmp; + } + *_img = img; return 0; err: @@ -178,10 +241,10 @@ int img_dev_enroll(struct fp_dev *dev, gboolean initial, int stage, if (r) return r; - r = fpi_img_detect_minutiae(imgdev, img, &print); + r = fpi_img_to_print_data(imgdev, img, &print); if (r < 0) return r; - if (r < MIN_ACCEPTABLE_MINUTIAE) { + if (img->minutiae->num < MIN_ACCEPTABLE_MINUTIAE) { fp_dbg("not enough minutiae, %d/%d", r, MIN_ACCEPTABLE_MINUTIAE); fp_print_data_free(print); return FP_ENROLL_RETRY; @@ -214,10 +277,10 @@ static int img_dev_verify(struct fp_dev *dev, if (r) return r; - r = fpi_img_detect_minutiae(imgdev, img, &print); + r = fpi_img_to_print_data(imgdev, img, &print); if (r < 0) return r; - if (r < MIN_ACCEPTABLE_MINUTIAE) { + if (img->minutiae->num < MIN_ACCEPTABLE_MINUTIAE) { fp_dbg("not enough minutiae, %d/%d", r, MIN_ACCEPTABLE_MINUTIAE); fp_print_data_free(print); return FP_VERIFY_RETRY; diff --git a/libfprint/nbis/include/lfs.h b/libfprint/nbis/include/lfs.h index c184425b..2da5d258 100644 --- a/libfprint/nbis/include/lfs.h +++ b/libfprint/nbis/include/lfs.h @@ -43,6 +43,7 @@ identified are necessarily the best available for the purpose. #include #include +#include /*************************************************************************/ /* OUTPUT FILE EXTENSIONS */ @@ -130,26 +131,8 @@ typedef struct rotgrids{ #define DISAPPEARING 0 #define APPEARING 1 -typedef struct minutia{ - int x; - int y; - int ex; - int ey; - int direction; - double reliability; - int type; - int appearing; - int feature_id; - int *nbrs; - int *ridge_counts; - int num_nbrs; -} MINUTIA; - -typedef struct minutiae{ - int alloc; - int num; - MINUTIA **list; -} MINUTIAE; +typedef struct fp_minutia MINUTIA; +typedef struct fp_minutiae MINUTIAE; typedef struct feature_pattern{ int type; From fa24d51304316f8d9901368164a133232834ead4 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 17 Nov 2007 13:15:25 +0000 Subject: [PATCH 072/184] Fix variable get_img_width/height return value Fix the functions to conform to the documentation: -1 means non-imaging device, 0 means variable. Internally, -1 is used to represent variable height (to be noticably different from the memset-imposed default of zero). --- libfprint/imgdev.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index f072959c..8ba6bb8e 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -68,6 +68,9 @@ int fpi_imgdev_get_img_width(struct fp_img_dev *imgdev) if (width > 0 && imgdrv->enlarge_factor > 1) width *= imgdrv->enlarge_factor; + else if (width == -1) + width = 0; + return width; } @@ -77,8 +80,11 @@ int fpi_imgdev_get_img_height(struct fp_img_dev *imgdev) struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); int height = imgdrv->img_height; - if (height > 0 && imgdrv->enlarge_factor > 1) + if (height > 0 && imgdrv->enlarge_factor > 1) height *= imgdrv->enlarge_factor; + else if (height == -1) + height = 0; + return height; } From af945b2738ee3f8a50e8aafcce91a8f1d356b512 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 17 Nov 2007 12:48:26 +0000 Subject: [PATCH 073/184] Version 0.0.2 --- Makefile.am | 9 ++++++--- NEWS | 10 ++++++++++ configure.ac | 2 +- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/Makefile.am b/Makefile.am index 729a285a..4c63a157 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1,4 +1,6 @@ +AUTOMAKE_OPTIONS = dist-bzip2 EXTRA_DIST = THANKS TODO HACKING libfprint.pc.in +DISTCLEANFILES = ChangeLog libfprint.pc SUBDIRS = libfprint doc @@ -8,11 +10,12 @@ endif pkgconfigdir=$(libdir)/pkgconfig pkgconfig_DATA=libfprint.pc -DISTCLEANFILES=libfprint.pc -.PHONY: ChangeLog +.PHONY: ChangeLog dist-up ChangeLog: - git --git-dir $(top_srcdir)/.git log > ChangeLog + git --git-dir $(top_srcdir)/.git log > ChangeLog || touch ChangeLog dist-hook: ChangeLog +dist-up: dist + ncftpput upload.sourceforge.net incoming $(distdir).tar.bz2 diff --git a/NEWS b/NEWS index 559ad663..8c28fdd2 100644 --- a/NEWS +++ b/NEWS @@ -1,3 +1,13 @@ +This file lists notable changes in each release. For the full history of all +changes, see ChangeLog. + +2007-11-17: v0.0.2 release + * Detect reversed scans on AES2501 (Vasily Khoruzhick) + * Improved AES2501 scanning + * Compatibility with older ImageMagick versions + * Add UPEK TouchChip driver (Jan-Michael Brummer) + * Add binarization API + 2007-11-15: v0.0.1 release * Initial release diff --git a/configure.ac b/configure.ac index 177c7880..6124eab6 100644 --- a/configure.ac +++ b/configure.ac @@ -1,4 +1,4 @@ -AC_INIT([libfprint], [0.0.1]) +AC_INIT([libfprint], [0.0.2]) AM_INIT_AUTOMAKE AC_CONFIG_SRCDIR([libfprint/core.c]) AM_CONFIG_HEADER([config.h]) From fa742a2142ec969e9392823d6113f046c336cfb8 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 17 Nov 2007 23:47:06 +0000 Subject: [PATCH 074/184] Use G_N_ELEMENTS macro --- libfprint/core.c | 4 ++-- libfprint/drivers/aes2501.c | 18 +++++++++--------- libfprint/drivers/aes4000.c | 2 +- libfprint/fp_internal.h | 2 -- 4 files changed, 12 insertions(+), 14 deletions(-) diff --git a/libfprint/core.c b/libfprint/core.c index 639c4da7..a018988e 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -343,10 +343,10 @@ static void register_drivers(void) { unsigned int i; - for (i = 0; i < ARRAY_SIZE(primitive_drivers); i++) + for (i = 0; i < G_N_ELEMENTS(primitive_drivers); i++) register_driver(primitive_drivers[i]); - for (i = 0; i < ARRAY_SIZE(img_drivers); i++) { + for (i = 0; i < G_N_ELEMENTS(img_drivers); i++) { struct fp_img_driver *imgdriver = img_drivers[i]; fpi_img_driver_setup(imgdriver); register_driver(&imgdriver->driver); diff --git a/libfprint/drivers/aes2501.c b/libfprint/drivers/aes2501.c index e4757875..0c8515a3 100644 --- a/libfprint/drivers/aes2501.c +++ b/libfprint/drivers/aes2501.c @@ -248,7 +248,7 @@ static int do_init(struct fp_img_dev *dev) int i; /* part 1, probably not needed */ - r = write_regv(dev, init_1, ARRAY_SIZE(init_1)); + r = write_regv(dev, init_1, G_N_ELEMENTS(init_1)); if (r < 0) return r; @@ -257,7 +257,7 @@ static int do_init(struct fp_img_dev *dev) return r; /* part 2 */ - r = write_regv(dev, init_2, ARRAY_SIZE(init_2)); + r = write_regv(dev, init_2, G_N_ELEMENTS(init_2)); if (r < 0) return r; @@ -269,7 +269,7 @@ static int do_init(struct fp_img_dev *dev) fp_dbg("reg 0xaf = %x", buffer[0x5f]); i = 0; while (buffer[0x5f] == 0x6b) { - r = write_regv(dev, init_3, ARRAY_SIZE(init_3)); + r = write_regv(dev, init_3, G_N_ELEMENTS(init_3)); if (r < 0) return r; r = read_regs(dev, buffer); @@ -280,12 +280,12 @@ static int do_init(struct fp_img_dev *dev) } /* part 4 */ - r = write_regv(dev, init_4, ARRAY_SIZE(init_4)); + r = write_regv(dev, init_4, G_N_ELEMENTS(init_4)); if (r < 0) return r; /* part 5 */ - return write_regv(dev, init_5, ARRAY_SIZE(init_5)); + return write_regv(dev, init_5, G_N_ELEMENTS(init_5)); } static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) @@ -343,7 +343,7 @@ static int detect_finger(struct fp_img_dev *dev) int i; int sum = 0; - r = write_regv(dev, finger_det_reqs, ARRAY_SIZE(finger_det_reqs)); + r = write_regv(dev, finger_det_reqs, G_N_ELEMENTS(finger_det_reqs)); if (r < 0) return r; @@ -558,7 +558,7 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, /* FIXME can do better here in terms of buffer management? */ fp_dbg(""); - r = write_regv(dev, capture_reqs_1, ARRAY_SIZE(capture_reqs_1)); + r = write_regv(dev, capture_reqs_1, G_N_ELEMENTS(capture_reqs_1)); if (r < 0) return r; @@ -566,7 +566,7 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, if (r < 0) return r; - r = write_regv(dev, capture_reqs_2, ARRAY_SIZE(capture_reqs_2)); + r = write_regv(dev, capture_reqs_2, G_N_ELEMENTS(capture_reqs_2)); if (r < 0) return r; @@ -583,7 +583,7 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, for (nstrips = 0; nstrips < MAX_FRAMES; nstrips++) { int threshold; - r = write_regv(dev, strip_scan_reqs, ARRAY_SIZE(strip_scan_reqs)); + r = write_regv(dev, strip_scan_reqs, G_N_ELEMENTS(strip_scan_reqs)); if (r < 0) goto err; r = read_data(dev, buf, 1705); diff --git a/libfprint/drivers/aes4000.c b/libfprint/drivers/aes4000.c index 4b433462..111a8248 100644 --- a/libfprint/drivers/aes4000.c +++ b/libfprint/drivers/aes4000.c @@ -142,7 +142,7 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, unsigned char *data; unsigned char *ptr; - for (i = 0; i < ARRAY_SIZE(init_reqs); i++) { + for (i = 0; i < G_N_ELEMENTS(init_reqs); i++) { r = write_reg(dev, init_reqs[i].reg, init_reqs[i].value); if (r < 0) return r; diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 2fa7dad0..52ea98dd 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -28,8 +28,6 @@ #include -#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*a)) - #define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) );}) From 887e0e6acf8767c1f3bf571fc1ef8f5223c4c33b Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 19 Nov 2007 00:27:27 +0000 Subject: [PATCH 075/184] Add API to access minutiae --- libfprint/fp_internal.h | 15 ------------- libfprint/fprint.h | 18 ++++++++++++++++ libfprint/img.c | 48 ++++++++++++++++++++++++++++++++++++++++- 3 files changed, 65 insertions(+), 16 deletions(-) diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 52ea98dd..5e6f15f2 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -189,21 +189,6 @@ gboolean fpi_print_data_compatible(uint16_t driver_id1, uint32_t devtype1, enum fp_print_data_type type1, uint16_t driver_id2, uint32_t devtype2, enum fp_print_data_type type2); -struct fp_minutia { - int x; - int y; - int ex; - int ey; - int direction; - double reliability; - int type; - int appearing; - int feature_id; - int *nbrs; - int *ridge_counts; - int num_nbrs; -}; - struct fp_minutiae { int alloc; int num; diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 8eccd03f..20f05453 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -207,12 +207,30 @@ uint16_t fp_print_data_get_driver_id(struct fp_print_data *data); uint32_t fp_print_data_get_devtype(struct fp_print_data *data); /* Image handling */ + +/** \ingroup img */ +struct fp_minutia { + int x; + int y; + int ex; + int ey; + int direction; + double reliability; + int type; + int appearing; + int feature_id; + int *nbrs; + int *ridge_counts; + int num_nbrs; +}; + int fp_img_get_height(struct fp_img *img); int fp_img_get_width(struct fp_img *img); unsigned char *fp_img_get_data(struct fp_img *img); int fp_img_save_to_file(struct fp_img *img, char *path); void fp_img_standardize(struct fp_img *img); struct fp_img *fp_img_binarize(struct fp_img *img); +struct fp_minutia **fp_img_get_minutiae(struct fp_img *img, int *nr_minutiae); void fp_img_free(struct fp_img *img); /* Library */ diff --git a/libfprint/img.c b/libfprint/img.c index d579a63d..c8df4b22 100644 --- a/libfprint/img.c +++ b/libfprint/img.c @@ -398,8 +398,10 @@ API_EXPORTED struct fp_img *fp_img_binarize(struct fp_img *img) int r = fpi_img_detect_minutiae(img); if (r < 0) return NULL; - if (!img->binarized) + if (!img->binarized) { fp_err("no minutiae after successful detection?"); + return NULL; + } } ret = fpi_img_new(imgsize); @@ -410,3 +412,47 @@ API_EXPORTED struct fp_img *fp_img_binarize(struct fp_img *img) return ret; } +/** \ingroup img + * Get a list of minutiae detected in an image. A minutia point is a feature + * detected on a fingerprint, typically where ridges end or split. + * libfprint's image processing code relies upon comparing sets of minutiae, + * so accurate placement of minutia points is critical for good imaging + * performance. + * + * The image must have been \ref img_std "standardized" otherwise this function + * will fail. + * + * You cannot pass a binarized image to this function. Instead, pass the + * original image. + * + * Returns a list of pointers to minutiae, where the list is of length + * indicated in the nr_minutiae output parameter. The returned list is only + * valid while the parent image has not been freed, and the minutiae data + * must not be modified or freed. + * + * \param img a standardized image + * \param nr_minutiae an output location to store minutiae list length + * \returns a list of minutiae points. Must not be modified or freed. + */ +API_EXPORTED struct fp_minutia **fp_img_get_minutiae(struct fp_img *img, + int *nr_minutiae) +{ + if (img->flags & FP_IMG_BINARIZED_FORM) { + fp_err("image is binarized"); + return NULL; + } + + if (!img->minutiae) { + int r = fpi_img_detect_minutiae(img); + if (r < 0) + return NULL; + if (!img->minutiae) { + fp_err("no minutiae after successful detection?"); + return NULL; + } + } + + *nr_minutiae = img->minutiae->num; + return img->minutiae->list; +} + From 6245acea848392861c2cd175d0292ef6b4f6638e Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 19 Nov 2007 18:29:26 +0000 Subject: [PATCH 076/184] Add API to delete enroll data --- libfprint/data.c | 43 +++++++++++++++++++++++++++++++++++++++++++ libfprint/fprint.h | 2 ++ 2 files changed, 45 insertions(+) diff --git a/libfprint/data.c b/libfprint/data.c index 79d161db..c36f94d2 100644 --- a/libfprint/data.c +++ b/libfprint/data.c @@ -25,6 +25,7 @@ #include #include +#include #include "fp_internal.h" @@ -357,6 +358,28 @@ API_EXPORTED int fp_print_data_load(struct fp_dev *dev, return 0; } +/** \ingroup print_data + * Removes a stored print from disk previously saved with fp_print_data_save(). + * \param dev the device that the print belongs to + * \param finger the finger of the file you are deleting + * \returns 0 on success, negative on error + */ +API_EXPORTED int fp_print_data_delete(struct fp_dev *dev, + enum fp_finger finger) +{ + int r; + gchar *path = get_path_to_print(dev, finger); + + fp_dbg("remove finger %d at %s", finger, path); + r = g_unlink(path); + g_free(path); + if (r < 0) + fp_dbg("unlink failed with error %d", r); + + /* FIXME: cleanup empty directory */ + return r; +} + /** \ingroup print_data * Attempts to load a stored print based on a \ref dscv_print * "discovered print" record. @@ -639,3 +662,23 @@ API_EXPORTED enum fp_finger fp_dscv_print_get_finger(struct fp_dscv_print *print return print->finger; } +/** \ingroup dscv_print + * Removes a discovered print from disk. After successful return of this + * function, functions such as fp_dscv_print_get_finger() will continue to + * operate as before, however calling fp_print_data_from_dscv_print() will + * fail for obvious reasons. + * \param print the discovered print to remove from disk + * \returns 0 on success, negative on error + */ +API_EXPORTED int fp_dscv_print_delete(struct fp_dscv_print *print) +{ + int r; + fp_dbg("remove at %s", print->path); + r = g_unlink(print->path); + if (r < 0) + fp_dbg("unlink failed with error %d", r); + + /* FIXME: cleanup empty directory */ + return r; +} + diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 20f05453..639c9630 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -80,6 +80,7 @@ void fp_dscv_prints_free(struct fp_dscv_print **prints); uint16_t fp_dscv_print_get_driver_id(struct fp_dscv_print *print); uint32_t fp_dscv_print_get_devtype(struct fp_dscv_print *print); enum fp_finger fp_dscv_print_get_finger(struct fp_dscv_print *print); +int fp_dscv_print_delete(struct fp_dscv_print *print); /* Device handling */ struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev); @@ -199,6 +200,7 @@ int fp_print_data_load(struct fp_dev *dev, enum fp_finger finger, int fp_print_data_from_dscv_print(struct fp_dscv_print *print, struct fp_print_data **data); int fp_print_data_save(struct fp_print_data *data, enum fp_finger finger); +int fp_print_data_delete(struct fp_dev *dev, enum fp_finger finger); void fp_print_data_free(struct fp_print_data *data); size_t fp_print_data_get_data(struct fp_print_data *data, unsigned char **ret); struct fp_print_data *fp_print_data_from_data(unsigned char *buf, From c5a550e42c716be0fe3aa61e135fd62b1e861ed7 Mon Sep 17 00:00:00 2001 From: Anthony Bretaudeau Date: Mon, 19 Nov 2007 18:39:03 +0000 Subject: [PATCH 077/184] Add Authentec AES1610 driver This is an active capacitance swipe-type device similar to but smaller than the AES2501. Image processing performance is good but matching performance is not so good. The bozorth3 matcher needs tweaking in order to better cope with small sets of minutiae. With a lowered threshold, matching performance is good enough for now. --- AUTHORS | 1 + TODO | 1 - libfprint/Makefile.am | 3 +- libfprint/drivers/aes1610.c | 626 ++++++++++++++++++++++++++++++++++++ 4 files changed, 629 insertions(+), 2 deletions(-) create mode 100644 libfprint/drivers/aes1610.c diff --git a/AUTHORS b/AUTHORS index db6fd07f..cc829548 100644 --- a/AUTHORS +++ b/AUTHORS @@ -6,3 +6,4 @@ Copyright (C) 2004,2006 Thomas Vander Stichele Copyright (C) 2007 Cyrille Bagard Copyright (C) 2007 Vasily Khoruzhick Copyright (C) 2007 Jan-Michael Brummer +Copyright (C) 2007 Anthony Bretaudeau diff --git a/TODO b/TODO index bbb4cf6f..07f00195 100644 --- a/TODO +++ b/TODO @@ -10,7 +10,6 @@ race-free way of saying "save this print but don't overwrite" NEW DRIVERS =========== Sunplus 895 driver -AES1610 driver AES3400/3500 driver ID Mouse driver Support for 2nd generation MS devices diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 194f423e..549deff7 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -3,10 +3,11 @@ lib_LTLIBRARIES = libfprint.la UPEKTS_SRC = drivers/upekts.c UPEKTC_SRC = drivers/upektc.c URU4000_SRC = drivers/uru4000.c +AES1610_SRC = drivers/aes1610.c AES2501_SRC = drivers/aes2501.c drivers/aes2501.h AES4000_SRC = drivers/aes4000.c -DRIVER_SRC = $(UPEKTS_SRC) $(URU4000_SRC) $(AES2501_SRC) $(AES4000_SRC) $(UPEKTC_SRC) +DRIVER_SRC = $(UPEKTS_SRC) $(URU4000_SRC) $(AES1610_SRC) $(AES2501_SRC) $(AES4000_SRC) $(UPEKTC_SRC) NBIS_SRC = \ nbis/include/bozorth.h \ diff --git a/libfprint/drivers/aes1610.c b/libfprint/drivers/aes1610.c new file mode 100644 index 00000000..f1b1a509 --- /dev/null +++ b/libfprint/drivers/aes1610.c @@ -0,0 +1,626 @@ +/* + * AuthenTec AES1610 driver for libfprint + * Copyright (C) 2007 Anthony Bretaudeau + * Copyright (C) 2007 Daniel Drake + * Copyright (C) 2007 Cyrille Bagard + * Copyright (C) 2007 Vasily Khoruzhick + * + * Based on code from http://home.gna.org/aes2501, relicensed with permission + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#define FP_COMPONENT "aes1610" + +#include +#include + +#include + +#include + +/* FIXME these need checking */ +#define EP_IN (1 | USB_ENDPOINT_IN) +#define EP_OUT (2 | USB_ENDPOINT_OUT) + +#define BULK_TIMEOUT 4000 +#define MAX_REGWRITES_PER_REQUEST 16 + +#define FIRST_AES1610_REG 0x1B +#define LAST_AES1610_REG 0xFF + +/* + * The AES1610 is an imaging device using a swipe-type sensor. It samples + * the finger at preprogrammed intervals, sending a 128x8 frame to the + * computer. + * Unless the user is scanning their finger unreasonably fast, the frames + * *will* overlap. The implementation below detects this overlap and produces + * a contiguous image as the end result. + * The fact that the user determines the length of the swipe (and hence the + * number of useful frames) and also the fact that overlap varies means that + * images returned from this driver vary in height. + */ + +#define FRAME_WIDTH 128 +#define FRAME_HEIGHT 8 +#define FRAME_SIZE (FRAME_WIDTH * FRAME_HEIGHT) +/* maximum number of frames to read during a scan */ +/* FIXME reduce substantially */ +#define MAX_FRAMES 150 + +struct aes1610_regwrite { + unsigned char reg; + unsigned char value; +}; + +static int do_write_regv(struct fp_img_dev *dev, const struct aes1610_regwrite *regs, + unsigned int num) +{ + size_t alloc_size = num * 2; + unsigned char *data = g_malloc(alloc_size); + unsigned int i; + size_t offset = 0; + int r; + + for (i = 0; i < num; i++) { + data[offset++] = regs[i].reg; + data[offset++] = regs[i].value; + } + + r = usb_bulk_write(dev->udev, EP_OUT, data, alloc_size, BULK_TIMEOUT); + g_free(data); + if (r < 0) { + fp_err("bulk write error %d", r); + return r; + } else if (r < (int) alloc_size) { + fp_err("unexpected short write %d/%d", r, alloc_size); + return -EIO; + } + + return 0; +} + +static int write_regv(struct fp_img_dev *dev, const struct aes1610_regwrite *regs, + unsigned int num) +{ + unsigned int i; + int skip = 0; + int add_offset = 0; + fp_dbg("write %d regs", num); + + for (i = 0; i < num; i += add_offset + skip) { + int r, j; + int limit = MIN(num, i + MAX_REGWRITES_PER_REQUEST); + skip = 0; + + for (j = i; j < limit; j++) + if (!regs[j].reg) { + skip = 1; + break; + } + + add_offset = j - i; + r = do_write_regv(dev, ®s[i], add_offset); + if (r < 0) + return r; + } + + return 0; +} + +static int read_data(struct fp_img_dev *dev, unsigned char *data, size_t len) +{ + int r; + fp_dbg("len=%zd", len); + + r = usb_bulk_read(dev->udev, EP_IN, data, len, BULK_TIMEOUT); + if (r < 0) { + fp_err("bulk read error %d", r); + return r; + } else if (r < (int) len) { + fp_err("unexpected short read %d/%zd", r, len); + return -EIO; + } + return 0; +} + +static const struct aes1610_regwrite init[] = { + { 0x82, 0x00 } +}; + +static const struct aes1610_regwrite stop_reader[] = { + { 0xFF, 0x00 } +}; + +static int do_init(struct fp_img_dev *dev) +{ + return write_regv(dev, init, G_N_ELEMENTS(init)); +} + +static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) +{ + int r; + + r = usb_claim_interface(dev->udev, 0); + if (r < 0) { + fp_err("could not claim interface 0"); + return r; + } + + /* FIXME check endpoints */ + + return do_init(dev); +} + +static int do_exit(struct fp_img_dev *dev) +{ + return write_regv(dev, stop_reader, G_N_ELEMENTS(stop_reader)); +} + +static void dev_exit(struct fp_img_dev *dev) +{ + do_exit(dev); + usb_release_interface(dev->udev, 0); +} + +static const struct aes1610_regwrite finger_det_reqs[] = { + { 0x80, 0x01 }, + { 0x80, 0x12 }, + { 0x85, 0x00 }, + { 0x8A, 0x00 }, + { 0x8B, 0x0E }, + { 0x8C, 0x90 }, + { 0x8D, 0x83 }, + { 0x8E, 0x07 }, + { 0x8F, 0x07 }, + { 0x96, 0x00 }, + { 0x97, 0x48 }, + { 0xA1, 0x00 }, + { 0xA2, 0x50 }, + { 0xA6, 0xE4 }, + { 0xAD, 0x08 }, + { 0xAE, 0x5B }, + { 0xAF, 0x54 }, + { 0xB1, 0x28 }, + { 0xB5, 0xAB }, + { 0xB6, 0x0E }, + { 0x1B, 0x2D }, + { 0x81, 0x04 } +}; + +static const struct aes1610_regwrite finger_det_none[] = { + { 0x80, 0x01 }, + { 0x82, 0x00 }, + { 0x86, 0x00 }, + { 0xB1, 0x28 }, + { 0x1D, 0x00 } +}; + +static int detect_finger(struct fp_img_dev *dev) +{ + unsigned char buffer[19]; + int r; + int i; + int sum = 0; + + r = write_regv(dev, finger_det_reqs, G_N_ELEMENTS(finger_det_reqs)); + if (r < 0) + return r; + + r = read_data(dev, buffer, 19); + if (r < 0) + return r; + + for (i = 3; i < 17; i++) + sum += (buffer[i] & 0xf) + (buffer[i] >> 4); + + /* We need to answer something if no finger has been detected */ + if (sum <= 20) { + r = write_regv(dev, finger_det_none, G_N_ELEMENTS(finger_det_none)); + if (r < 0) + return r; + } + + return sum > 20; +} + +static int await_finger_on(struct fp_img_dev *dev) +{ + int r; + do { + r = detect_finger(dev); + } while (r == 0); + return (r < 0) ? r : 0; +} + +/* Read the value of a specific register from a register dump */ +static int regval_from_dump(unsigned char *data, uint8_t target) +{ + if (*data != FIRST_AES1610_REG) { + fp_err("not a register dump"); + return -EILSEQ; + } + + if (!(FIRST_AES1610_REG <= target || target >= LAST_AES1610_REG)) { + fp_err("out of range"); + return -EINVAL; + } + + target -= FIRST_AES1610_REG; + target *= 2; + return data[target + 1]; +} + +/* find overlapping parts of frames */ +static unsigned int find_overlap(unsigned char *first_frame, + unsigned char *second_frame, unsigned int *min_error) +{ + unsigned int dy; + unsigned int not_overlapped_height = 0; + *min_error = 255 * FRAME_SIZE; + for (dy = 0; dy < FRAME_HEIGHT; dy++) { + /* Calculating difference (error) between parts of frames */ + unsigned int i; + unsigned int error = 0; + for (i = 0; i < FRAME_WIDTH * (FRAME_HEIGHT - dy); i++) { + /* Using ? operator to avoid abs function */ + error += first_frame[i] > second_frame[i] ? + (first_frame[i] - second_frame[i]) : + (second_frame[i] - first_frame[i]); + } + + /* Normalize error */ + error *= 15; + error /= i; + if (error < *min_error) { + *min_error = error; + not_overlapped_height = dy; + } + first_frame += FRAME_WIDTH; + } + + return not_overlapped_height; +} + +/* assemble a series of frames into a single image */ +static unsigned int assemble(unsigned char *input, unsigned char *output, + int num_strips, gboolean reverse, unsigned int *errors_sum) +{ + uint8_t *assembled = output; + int frame; + uint32_t image_height = FRAME_HEIGHT; + unsigned int min_error; + *errors_sum = 0; + + if (num_strips < 1) + return 0; + + /* Rotating given data by 90 degrees + * Taken from document describing aes1610 image format + * TODO: move reversing detection here */ + + if (reverse) + output += (num_strips - 1) * FRAME_SIZE; + for (frame = 0; frame < num_strips; frame++) { + int column; + for (column = 0; column < FRAME_WIDTH; column++) { + int row; + for (row = 0; row < (FRAME_HEIGHT / 2); row++) { + output[FRAME_WIDTH * ( 2 * row) + column] = *input & 0x0F; + output[FRAME_WIDTH * ( 2 * row + 1) + column] = *input >> 4; + input++; + } + } + + if (reverse) + output -= FRAME_SIZE; + else + output += FRAME_SIZE; + } + + /* Detecting where frames overlaped */ + output = assembled; + for (frame = 1; frame < num_strips; frame++) { + int not_overlapped; + + output += FRAME_SIZE; + not_overlapped = find_overlap(assembled, output, &min_error); + *errors_sum += min_error; + image_height += not_overlapped; + assembled += FRAME_WIDTH * not_overlapped; + memcpy(assembled, output, FRAME_SIZE); + } + return image_height; +} + +static const struct aes1610_regwrite capture_reqs[] = { + { 0x80, 0x01 }, + { 0x80, 0x12 }, + { 0x84, 0x01 }, + { 0x85, 0x00 }, + { 0x89, 0x64 }, + { 0x8A, 0x00 }, + { 0x8B, 0x0E }, + { 0x8C, 0x90 }, + { 0xBE, 0x23 }, + { 0x29, 0x06 }, + { 0x2A, 0x35 }, + { 0x96, 0x00 }, + { 0x98, 0x03 }, + { 0x99, 0x00 }, + { 0x9C, 0xA5 }, + { 0x9D, 0x40 }, + { 0x9E, 0xC6 }, + { 0x9F, 0x8E }, + { 0xA2, 0x50 }, + { 0xA3, 0xF0 }, + { 0xAD, 0x08 }, + { 0xBD, 0x4F }, + { 0xAF, 0x54 }, + { 0xB1, 0x08 }, + { 0xB5, 0xAB }, + { 0x1B, 0x2D }, + { 0xB6, 0x4E }, + { 0xB8, 0x70 }, + { 0x2B, 0xB3 }, + { 0x2C, 0x5D }, + { 0x2D, 0x98 }, + { 0x2E, 0xB0 }, + { 0x2F, 0x20 }, + { 0xA2, 0xD0 }, + { 0x1D, 0x21 }, + { 0x1E, 0xBE }, + { 0x1C, 0x00 }, + { 0x1D, 0x30 }, + { 0x1E, 0x29 }, + { 0x1C, 0x01 }, + { 0x1D, 0x00 }, + { 0x1E, 0x9E }, + { 0x1C, 0x02 }, + { 0x1D, 0x30 }, + { 0x1E, 0xBB }, + { 0x1C, 0x03 }, + { 0x1D, 0x00 }, + { 0x1E, 0x9D }, + { 0x1C, 0x04 }, + { 0x1D, 0x22 }, + { 0x1E, 0xFF }, + { 0x1C, 0x05 }, + { 0x1D, 0x1B }, + { 0x1E, 0x4E }, + { 0x1C, 0x06 }, + { 0x1D, 0x16 }, + { 0x1E, 0x28 }, + { 0x1C, 0x07 }, + { 0x1D, 0x22 }, + { 0x1E, 0xFF }, + { 0x1C, 0x08 }, + { 0x1D, 0x15 }, + { 0x1E, 0xF1 }, + { 0x1C, 0x09 }, + { 0x1D, 0x30 }, + { 0x1E, 0xD5 }, + { 0x1C, 0x0A }, + { 0x1D, 0x00 }, + { 0x1E, 0x9E }, + { 0x1C, 0x0B }, + { 0x1D, 0x17 }, + { 0x1E, 0x9D }, + { 0x1C, 0x0C }, + { 0x1D, 0x28 }, + { 0x1E, 0xD7 }, + { 0x1C, 0x0D }, + { 0x1D, 0x17 }, + { 0x1E, 0xD7 }, + { 0x1C, 0x0E }, + { 0x1D, 0x0A }, + { 0x1E, 0xCB }, + { 0x1C, 0x0F }, + { 0x1D, 0x24 }, + { 0x1E, 0x14 }, + { 0x1C, 0x10 }, + { 0x1D, 0x17 }, + { 0x1E, 0x85 }, + { 0x1C, 0x11 }, + { 0x1D, 0x15 }, + { 0x1E, 0x71 }, + { 0x1C, 0x12 }, + { 0x1D, 0x2B }, + { 0x1E, 0x36 }, + { 0x1C, 0x13 }, + { 0x1D, 0x12 }, + { 0x1E, 0x06 }, + { 0x1C, 0x14 }, + { 0x1D, 0x30 }, + { 0x1E, 0x97 }, + { 0x1C, 0x15 }, + { 0x1D, 0x21 }, + { 0x1E, 0x32 }, + { 0x1C, 0x16 }, + { 0x1D, 0x06 }, + { 0x1E, 0xE6 }, + { 0x1C, 0x17 }, + { 0x1D, 0x16 }, + { 0x1E, 0x06 }, + { 0x1C, 0x18 }, + { 0x1D, 0x30 }, + { 0x1E, 0x01 }, + { 0x1C, 0x19 }, + { 0x1D, 0x21 }, + { 0x1E, 0x37 }, + { 0x1C, 0x1A }, + { 0x1D, 0x00 }, + { 0x1E, 0x08 }, + { 0x1C, 0x1B }, + { 0x1D, 0x80 }, + { 0x1E, 0xD5 }, + { 0xA2, 0x50 }, + { 0xA2, 0x50 }, + { 0x81, 0x01 } +}; + +static const struct aes1610_regwrite strip_scan_reqs[] = { + { 0xBE, 0x23 }, + { 0x29, 0x06 }, + { 0x2A, 0x35 }, + { 0xBD, 0x4F }, + { 0xFF, 0x00 } +}; + +static const struct aes1610_regwrite capture_stop[] = { + { 0x81,0x00 } +}; + +static int capture(struct fp_img_dev *dev, gboolean unconditional, + struct fp_img **ret) +{ + int r; + struct fp_img *img; + unsigned int nstrips; + unsigned int errors_sum, r_errors_sum; + unsigned char *cooked; + unsigned char *imgptr; + unsigned char buf[665]; + int sum; + int i; + + /* FIXME can do better here in terms of buffer management? */ + fp_dbg(""); + + r = write_regv(dev, capture_reqs, G_N_ELEMENTS(capture_reqs)); + if (r < 0) + return r; + + /* FIXME: use histogram data above for gain calibration (0x8e xx) */ + + img = fpi_img_new((3 * MAX_FRAMES * FRAME_SIZE) / 2); + imgptr = img->data; + cooked = imgptr + (MAX_FRAMES * FRAME_SIZE) / 2; + + r = read_data(dev, buf, 665); + if (r < 0) + goto err; + memcpy(imgptr, buf + 1, 128*4); + imgptr += 128*4; + + r = read_data(dev, buf, 665); + if (r < 0) + goto err; + memcpy(imgptr, buf + 1, 128*4); + imgptr += 128*4; + + for (nstrips = 0; nstrips < MAX_FRAMES; nstrips++) { + int threshold; + + r = write_regv(dev, strip_scan_reqs, G_N_ELEMENTS(strip_scan_reqs)); + if (r < 0) + goto err; + r = read_data(dev, buf, 665); + if (r < 0) + goto err; + memcpy(imgptr, buf + 1, 128*4); + imgptr += 128*4; + + r = read_data(dev, buf, 665); + if (r < 0) + goto err; + memcpy(imgptr, buf + 1, 128*4); + imgptr += 128*4; + + sum = 0; + for (i = 515; i != 530; i++) + { + /* histogram[i] = number of pixels of value i + Only the pixel values from 10 to 15 are used to detect finger. */ + sum += buf[i]; + } + if (sum < 0) { + r = sum; + goto err; + } + fp_dbg("sum=%d", sum); + if (sum == 0) + break; + } + + r = write_regv(dev, capture_stop, G_N_ELEMENTS(capture_stop)); + if (r < 0) + goto err; + r = read_data(dev, buf, 665); + if (r < 0) + goto err; + memcpy(imgptr, buf + 1, 128*4); + imgptr += 128*4; + + r = read_data(dev, buf, 665); + if (r < 0) + goto err; + memcpy(imgptr, buf + 1, 128*4); + imgptr += 128*4; + + if (nstrips == MAX_FRAMES) + fp_warn("swiping finger too slow?"); + + img->flags = FP_IMG_COLORS_INVERTED; + img->height = assemble(img->data, cooked, nstrips, FALSE, &errors_sum); + img->height = assemble(img->data, cooked, nstrips, TRUE, &r_errors_sum); + + if (r_errors_sum > errors_sum) { + img->height = assemble(img->data, cooked, nstrips, FALSE, &errors_sum); + img->flags |= FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED; + fp_dbg("normal scan direction"); + } else { + fp_dbg("reversed scan direction"); + } + + for (i = 0; i < img->height * FRAME_WIDTH; i++) + img->data[i] = (cooked[i] << 4) | 0xf; + + img = fpi_img_resize(img, img->height * FRAME_WIDTH); + *ret = img; + return 0; +err: + fp_img_free(img); + return r; +} + +static const struct usb_id id_table[] = { + { .vendor = 0x08ff, .product = 0x1600 }, + { 0, 0, 0, }, +}; + +struct fp_img_driver aes1610_driver = { + .driver = { + .id = 6, + .name = FP_COMPONENT, + .full_name = "AuthenTec AES1610", + .id_table = id_table, + }, + .flags = 0, + .img_height = -1, + .img_width = 128, + + /* temporarily lowered until we sort out image processing code + * binarized scan quality is good, minutiae detection is accurate, + * it's just that we get fewer minutiae than other scanners (less scanning + * area) */ + .bz3_threshold = 15, + + .init = dev_init, + .exit = dev_exit, + .await_finger_on = await_finger_on, + .capture = capture, +}; + From dbcd293ab31cabd44b6c840d6701d4f79a9aeee2 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 19 Nov 2007 18:41:03 +0000 Subject: [PATCH 078/184] v0.0.3 release --- NEWS | 5 +++++ configure.ac | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/NEWS b/NEWS index 8c28fdd2..e354bee6 100644 --- a/NEWS +++ b/NEWS @@ -1,6 +1,11 @@ This file lists notable changes in each release. For the full history of all changes, see ChangeLog. +2007-11-19: v0.0.3 release + * Add API to access minutiae (Daniel Drake) + * Add API to delete enroll data (Daniel Drake) + * Add Authentec AES1610 driver (Anthony Bretaudeau) + 2007-11-17: v0.0.2 release * Detect reversed scans on AES2501 (Vasily Khoruzhick) * Improved AES2501 scanning diff --git a/configure.ac b/configure.ac index 6124eab6..db8555f4 100644 --- a/configure.ac +++ b/configure.ac @@ -1,4 +1,4 @@ -AC_INIT([libfprint], [0.0.2]) +AC_INIT([libfprint], [0.0.3]) AM_INIT_AUTOMAKE AC_CONFIG_SRCDIR([libfprint/core.c]) AM_CONFIG_HEADER([config.h]) From 3f70d6f79410f483a9b34945dfe5b1cf5bfc23f6 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Tue, 20 Nov 2007 21:52:10 +0000 Subject: [PATCH 079/184] Identification infrastructure --- libfprint/core.c | 94 +++++++++++++++++++++++++++++++++++++++++ libfprint/fp_internal.h | 2 + libfprint/fprint.h | 60 +++++++++++++++++++------- 3 files changed, 141 insertions(+), 15 deletions(-) diff --git a/libfprint/core.c b/libfprint/core.c index a018988e..7db625a0 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -747,6 +747,18 @@ API_EXPORTED int fp_dev_supports_imaging(struct fp_dev *dev) return dev->drv->type == DRIVER_IMAGING; } +/** \ingroup dev + * Determines if a device is capable of \ref identification "identification" + * through fp_identify_finger() and similar. Not all devices support this + * functionality. + * \param dev the fingerprint device + * \returns 1 if the device is capable of identification, 0 otherwise. + */ +API_EXPORTED int fp_dev_supports_identification(struct fp_dev *dev) +{ + return dev->drv->identify != NULL; +} + /** \ingroup dev * Captures an \ref img "image" from a device. The returned image is the raw * image provided by the device, you may wish to \ref img_std "standardize" it. @@ -1020,6 +1032,88 @@ API_EXPORTED int fp_verify_finger_img(struct fp_dev *dev, return r; } +/** \ingroup dev + * Performs a new scan and attempts to identify the scanned finger against + * a collection of previously enrolled fingerprints. + * If the device is an imaging device, it can also return the image from + * the scan, even when identification fails with a RETRY code. It is legal to + * call this function even on non-imaging devices, just don't expect them to + * provide images. + * + * This function returns codes from #fp_verify_result. The return code + * fp_verify_result#FP_VERIFY_MATCH indicates that the scanned fingerprint + * does appear in the print gallery, and the match_offset output parameter + * will indicate the index into the print gallery array of the matched print. + * + * This function will not necessarily examine the whole print gallery, it + * will return as soon as it finds a matching print. + * + * Not all devices support identification. -ENOTSUP will be returned when + * this is the case. + * + * \param dev the device to perform the scan. + * \param print_gallery NULL-terminated array of pointers to the prints to + * identify against. Each one must have been previously enrolled with a device + * compatible to the device selected to perform the scan. + * \param match_offset output location to store the array index of the matched + * gallery print (if any was found). Only valid if FP_VERIFY_MATCH was + * returned. + * \param img location to store the scan image. accepts NULL for no image + * storage. If an image is returned, it must be freed with fp_img_free() after + * use. + * \return negative code on error, otherwise a code from #fp_verify_result + */ +API_EXPORTED int fp_identify_finger_img(struct fp_dev *dev, + struct fp_print_data **print_gallery, size_t *match_offset, + struct fp_img **img) +{ + struct fp_driver *drv = dev->drv; + struct fp_img *_img; + int r; + + if (!drv->identify) { + fp_dbg("driver %s has no identify func", drv->name); + return -ENOTSUP; + } + fp_dbg("to be handled by %s", drv->name); + r = drv->identify(dev, print_gallery, match_offset, &_img); + if (r < 0) { + fp_dbg("identify error %d", r); + return r; + } + + if (img) + *img = _img; + else + fp_img_free(_img); + + switch (r) { + case FP_VERIFY_NO_MATCH: + fp_dbg("result: no match"); + break; + case FP_VERIFY_MATCH: + fp_dbg("result: match at offset %zd", match_offset); + break; + case FP_VERIFY_RETRY: + fp_dbg("verify should retry"); + break; + case FP_VERIFY_RETRY_TOO_SHORT: + fp_dbg("swipe was too short, verify should retry"); + break; + case FP_VERIFY_RETRY_CENTER_FINGER: + fp_dbg("finger was not centered, verify should retry"); + break; + case FP_VERIFY_RETRY_REMOVE_FINGER: + fp_dbg("scan failed, remove finger and retry"); + break; + default: + fp_err("unrecognised return code %d", r); + return -EINVAL; + } + + return r; +} + /** \ingroup core * Initialise libfprint. This function must be called before you attempt to * use the library in any way. diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 5e6f15f2..7581c38f 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -113,6 +113,8 @@ struct fp_driver { struct fp_print_data **print_data, struct fp_img **img); int (*verify)(struct fp_dev *dev, struct fp_print_data *data, struct fp_img **img); + int (*identify)(struct fp_dev *dev, struct fp_print_data **print_gallery, + size_t *match_offset, struct fp_img **img); }; enum fp_print_data_type fpi_driver_get_data_type(struct fp_driver *drv); diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 639c9630..2b855840 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -150,30 +150,32 @@ static inline int fp_enroll_finger(struct fp_dev *dev, } /** \ingroup dev - * Verification result codes returned from fp_verify_finger(). + * Verification result codes returned from fp_verify_finger(). Return codes + * are also shared with fp_identify_finger(). * Result codes with RETRY in the name suggest that the scan failed due to * user error. Applications will generally want to inform the user of the * problem and then retry the verify operation. */ enum fp_verify_result { - /** The verification scan completed successfully, but the newly scanned - * fingerprint does not match the fingerprint being verified against. */ + /** The scan completed successfully, but the newly scanned fingerprint + * does not match the fingerprint being verified against. + * In the case of identification, this return code indicates that the + * scanned finger could not be found in the print gallery. */ FP_VERIFY_NO_MATCH = 0, - /** The verification scan completed successfully and the newly scanned - * fingerprint does match the fingerprint being verified. */ + /** The scan completed successfully and the newly scanned fingerprint does + * match the fingerprint being verified, or in the case of identification, + * the scanned fingerprint was found in the print gallery. */ FP_VERIFY_MATCH = 1, - /** The verification scan did not succeed due to poor scan quality or - * other general user scanning problem. */ + /** The scan did not succeed due to poor scan quality or other general + * user scanning problem. */ FP_VERIFY_RETRY = FP_ENROLL_RETRY, - /** The verification scan did not succeed because the finger swipe was - * too short. */ + /** The scan did not succeed because the finger swipe was too short. */ FP_VERIFY_RETRY_TOO_SHORT = FP_ENROLL_RETRY_TOO_SHORT, - /** The verification scan did not succeed because the finger was not - * centered on the scanner. */ + /** The scan did not succeed because the finger was not centered on the + * scanner. */ FP_VERIFY_RETRY_CENTER_FINGER = FP_ENROLL_RETRY_CENTER_FINGER, - /** The verification scan did not succeed due to quality or pressure - * problems; the user should remove their finger from the scanner before - * retrying. */ + /** The scan did not succeed due to quality or pressure problems; the user + * should remove their finger from the scanner before retrying. */ FP_VERIFY_RETRY_REMOVE_FINGER = FP_ENROLL_RETRY_REMOVE_FINGER, }; @@ -181,7 +183,9 @@ int fp_verify_finger_img(struct fp_dev *dev, struct fp_print_data *enrolled_print, struct fp_img **img); /** \ingroup dev - * Performs a new scan and verify it against a previously enrolled print. + * Performs a new scan and verify it against a previously enrolled print. This + * function is just a shortcut to calling fp_verify_finger_img() with a NULL + * image output parameter. * \param dev the device to perform the scan. * \param enrolled_print the print to verify against. Must have been previously * enrolled with a device compatible to the device selected to perform the scan. @@ -194,6 +198,32 @@ static inline int fp_verify_finger(struct fp_dev *dev, return fp_verify_finger_img(dev, enrolled_print, NULL); } +int fp_dev_supports_identification(struct fp_dev *dev); +int fp_identify_finger_img(struct fp_dev *dev, + struct fp_print_data **print_gallery, size_t *match_offset, + struct fp_img **img); + +/** \ingroup dev + * Performs a new scan and attempts to identify the scanned finger against a + * collection of previously enrolled fingerprints. This function is just a + * shortcut to calling fp_identify_finger_img() with a NULL image output + * parameter. + * \param dev the device to perform the scan. + * \param print_gallery NULL-terminated array of pointers to the prints to + * identify against. Each one must have been previously enrolled with a device + * compatible to the device selected to perform the scan. + * \param match_offset output location to store the array index of the matched + * gallery print (if any was found). Only valid if FP_VERIFY_MATCH was + * returned. + * \return negative code on error, otherwise a code from #fp_verify_result + * \sa fp_identify_finger_img() + */ +static inline int fp_identify_finger(struct fp_dev *dev, + struct fp_print_data **print_gallery, size_t *match_offset) +{ + return fp_identify_finger_img(dev, print_gallery, match_offset, NULL); +} + /* Data handling */ int fp_print_data_load(struct fp_dev *dev, enum fp_finger finger, struct fp_print_data **data); From 69700855e27c655262de0d908a0447100238c5e4 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Tue, 20 Nov 2007 22:13:18 +0000 Subject: [PATCH 080/184] Implement identification for imaging devices --- TODO | 1 - libfprint/core.c | 4 ---- libfprint/fp_internal.h | 2 ++ libfprint/img.c | 19 +++++++++++++++++++ libfprint/imgdev.c | 41 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 62 insertions(+), 5 deletions(-) diff --git a/TODO b/TODO index 07f00195..66723a7b 100644 --- a/TODO +++ b/TODO @@ -1,6 +1,5 @@ LIBRARY ======= -identification test suite against NFIQ compliance set make library optionally asynchronous and maybe thread-safe nbis cleanups diff --git a/libfprint/core.c b/libfprint/core.c index 7db625a0..fc789229 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -81,10 +81,6 @@ * * \section identification Identification * - * libfprint supports enrollment and verification as described above. Although - * libfprint does not yet support identification (it is planned), it is worth - * introducing the concept to give you a complete picture. - * * Identification is the process of comparing a freshly scanned fingerprint * to a collection of previously enrolled fingerprints. For example, * imagine there are 100 people in an organisation, and they all have enrolled diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 7581c38f..e182a583 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -225,6 +225,8 @@ int fpi_img_to_print_data(struct fp_img_dev *imgdev, struct fp_img *img, struct fp_print_data **ret); int fpi_img_compare_print_data(struct fp_print_data *enrolled_print, struct fp_print_data *new_print); +int fpi_img_compare_print_data_to_gallery(struct fp_print_data *print, + struct fp_print_data **gallery, int match_threshold, int *match_offset); #endif diff --git a/libfprint/img.c b/libfprint/img.c index c8df4b22..80fd6e4e 100644 --- a/libfprint/img.c +++ b/libfprint/img.c @@ -364,6 +364,25 @@ int fpi_img_compare_print_data(struct fp_print_data *enrolled_print, return r; } +int fpi_img_compare_print_data_to_gallery(struct fp_print_data *print, + struct fp_print_data **gallery, int match_threshold, int *match_offset) +{ + struct xyt_struct *pstruct = (struct xyt_struct *) print->data; + struct fp_print_data *gallery_print; + int probe_len = bozorth_probe_init(pstruct); + size_t i = 0; + + while (gallery_print = gallery[i++]) { + struct xyt_struct *gstruct = (struct xyt_struct *) gallery_print->data; + int r = bozorth_to_gallery(probe_len, pstruct, gstruct); + if (r >= match_threshold) { + *match_offset = i - 1; + return FP_VERIFY_MATCH; + } + } + return FP_VERIFY_NO_MATCH; +} + /** \ingroup img * Get a binarized form of a standardized scanned image. This is where the * fingerprint image has been "enhanced" and is a set of pure black ridges diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index 8ba6bb8e..8deb23c0 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -305,6 +305,46 @@ static int img_dev_verify(struct fp_dev *dev, return FP_VERIFY_NO_MATCH; } +static int img_dev_identify(struct fp_dev *dev, + struct fp_print_data **print_gallery, size_t *match_offset, + struct fp_img **_img) +{ + struct fp_img_dev *imgdev = dev->priv; + struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(dev->drv); + struct fp_img *img = NULL; + struct fp_print_data *print; + int match_score = imgdrv->bz3_threshold; + int r; + + r = fpi_imgdev_capture(imgdev, 0, &img); + + /* If we got an image, standardize it and return it even if the scan + * quality was too low for processing. */ + if (img) + fp_img_standardize(img); + if (_img) + *_img = img; + if (r) + return r; + + r = fpi_img_to_print_data(imgdev, img, &print); + if (r < 0) + return r; + if (img->minutiae->num < MIN_ACCEPTABLE_MINUTIAE) { + fp_dbg("not enough minutiae, %d/%d", r, MIN_ACCEPTABLE_MINUTIAE); + fp_print_data_free(print); + return FP_VERIFY_RETRY; + } + + if (match_score == 0) + match_score = BOZORTH3_DEFAULT_THRESHOLD; + + r = fpi_img_compare_print_data_to_gallery(print, print_gallery, + match_score, match_offset); + fp_print_data_free(print); + return r; +} + void fpi_img_driver_setup(struct fp_img_driver *idriver) { idriver->driver.type = DRIVER_IMAGING; @@ -312,5 +352,6 @@ void fpi_img_driver_setup(struct fp_img_driver *idriver) idriver->driver.exit = img_dev_exit; idriver->driver.enroll = img_dev_enroll; idriver->driver.verify = img_dev_verify; + idriver->driver.identify = img_dev_identify; } From 1ee6210be320c471e448f7e5aa772e63b7ae85e8 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Thu, 22 Nov 2007 17:25:27 +0000 Subject: [PATCH 081/184] Hookup AES1610 driver An oversight pointed out by Michele B. --- libfprint/core.c | 1 + libfprint/fp_internal.h | 1 + 2 files changed, 2 insertions(+) diff --git a/libfprint/core.c b/libfprint/core.c index fc789229..1a5a1461 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -330,6 +330,7 @@ static struct fp_driver * const primitive_drivers[] = { static struct fp_img_driver * const img_drivers[] = { &uru4000_driver, + &aes1610_driver, &aes2501_driver, &aes4000_driver, &upektc_driver, diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index e182a583..96b82a9a 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -142,6 +142,7 @@ struct fp_img_driver { extern struct fp_driver upekts_driver; extern struct fp_img_driver upektc_driver; extern struct fp_img_driver uru4000_driver; +extern struct fp_img_driver aes1610_driver; extern struct fp_img_driver aes2501_driver; extern struct fp_img_driver aes4000_driver; From 4e2be56db7f977672fbf7a4cb5d260cbdc55a58c Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Thu, 22 Nov 2007 17:59:33 +0000 Subject: [PATCH 082/184] v0.0.4 release --- NEWS | 4 ++++ configure.ac | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/NEWS b/NEWS index e354bee6..4e24d27c 100644 --- a/NEWS +++ b/NEWS @@ -1,6 +1,10 @@ This file lists notable changes in each release. For the full history of all changes, see ChangeLog. +2007-11-22: v0.0.4 release + * Enable AES1610 driver thanks to Michele B + * Implement identification: one-to-many fingerprint matching (Daniel Drake) + 2007-11-19: v0.0.3 release * Add API to access minutiae (Daniel Drake) * Add API to delete enroll data (Daniel Drake) diff --git a/configure.ac b/configure.ac index db8555f4..db450c76 100644 --- a/configure.ac +++ b/configure.ac @@ -1,4 +1,4 @@ -AC_INIT([libfprint], [0.0.3]) +AC_INIT([libfprint], [0.0.4]) AM_INIT_AUTOMAKE AC_CONFIG_SRCDIR([libfprint/core.c]) AM_CONFIG_HEADER([config.h]) From 8e0e8e43867dbd214149edeb83ad5688b5d9e8f2 Mon Sep 17 00:00:00 2001 From: Anthony Bretaudeau Date: Mon, 26 Nov 2007 17:51:31 +0000 Subject: [PATCH 083/184] aes1610: imaging improvements bz threshold is now 10 (instead of 15). I think it is ok for the moment. If we manage to get higher image quality in the future, we'll change that. max_frame is set to 350. 150 was too low => incomplete fingerprints the driver was designed to stop the acquisition as soon as it gets a blank frame (=> incomplete fingerprints). Now it waits to have at least 50 blank frames before stopping. --- libfprint/drivers/aes1610.c | 37 ++++++++++++++----------------------- 1 file changed, 14 insertions(+), 23 deletions(-) diff --git a/libfprint/drivers/aes1610.c b/libfprint/drivers/aes1610.c index f1b1a509..bf42e983 100644 --- a/libfprint/drivers/aes1610.c +++ b/libfprint/drivers/aes1610.c @@ -58,7 +58,7 @@ #define FRAME_SIZE (FRAME_WIDTH * FRAME_HEIGHT) /* maximum number of frames to read during a scan */ /* FIXME reduce substantially */ -#define MAX_FRAMES 150 +#define MAX_FRAMES 350 struct aes1610_regwrite { unsigned char reg; @@ -245,24 +245,6 @@ static int await_finger_on(struct fp_img_dev *dev) return (r < 0) ? r : 0; } -/* Read the value of a specific register from a register dump */ -static int regval_from_dump(unsigned char *data, uint8_t target) -{ - if (*data != FIRST_AES1610_REG) { - fp_err("not a register dump"); - return -EILSEQ; - } - - if (!(FIRST_AES1610_REG <= target || target >= LAST_AES1610_REG)) { - fp_err("out of range"); - return -EINVAL; - } - - target -= FIRST_AES1610_REG; - target *= 2; - return data[target + 1]; -} - /* find overlapping parts of frames */ static unsigned int find_overlap(unsigned char *first_frame, unsigned char *second_frame, unsigned int *min_error) @@ -494,6 +476,7 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, unsigned char *imgptr; unsigned char buf[665]; int sum; + unsigned int count_blank = 0; int i; /* FIXME can do better here in terms of buffer management? */ @@ -521,9 +504,9 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, memcpy(imgptr, buf + 1, 128*4); imgptr += 128*4; - for (nstrips = 0; nstrips < MAX_FRAMES; nstrips++) { - int threshold; - + /* we start at 2 because we captured 2 frames above. the above captures + * should possibly be moved into the loop below, or discarded altogether */ + for (nstrips = 2; nstrips < MAX_FRAMES - 2; nstrips++) { r = write_regv(dev, strip_scan_reqs, G_N_ELEMENTS(strip_scan_reqs)); if (r < 0) goto err; @@ -552,6 +535,12 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, } fp_dbg("sum=%d", sum); if (sum == 0) + count_blank++; + else + count_blank = 0; + + /* if we got 50 blank frames, assume scan has ended. */ + if (count_blank >= 50) break; } @@ -563,12 +552,14 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, goto err; memcpy(imgptr, buf + 1, 128*4); imgptr += 128*4; + nstrips++; r = read_data(dev, buf, 665); if (r < 0) goto err; memcpy(imgptr, buf + 1, 128*4); imgptr += 128*4; + nstrips++; if (nstrips == MAX_FRAMES) fp_warn("swiping finger too slow?"); @@ -616,7 +607,7 @@ struct fp_img_driver aes1610_driver = { * binarized scan quality is good, minutiae detection is accurate, * it's just that we get fewer minutiae than other scanners (less scanning * area) */ - .bz3_threshold = 15, + .bz3_threshold = 10, .init = dev_init, .exit = dev_exit, From e228f2c7dab4960ed008d2170f07b6a53fa57eb3 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Tue, 20 Nov 2007 12:23:27 +0000 Subject: [PATCH 084/184] Introduce shared functions for authentec drivers Currently provides register writing functionality only, more common ground will be moved here soon. --- libfprint/Makefile.am | 2 + libfprint/aeslib.c | 95 +++++++++++++++++++++++++++++++++ libfprint/aeslib.h | 34 ++++++++++++ libfprint/drivers/aes1610.c | 95 ++++++--------------------------- libfprint/drivers/aes2501.c | 102 ++++++++---------------------------- libfprint/drivers/aes4000.c | 44 ++++++---------- 6 files changed, 183 insertions(+), 189 deletions(-) create mode 100644 libfprint/aeslib.c create mode 100644 libfprint/aeslib.h diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 549deff7..3e2702f8 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -56,6 +56,8 @@ libfprint_la_SOURCES = \ data.c \ img.c \ imgdev.c \ + aeslib.c \ + aeslib.h \ $(DRIVER_SRC) \ $(NBIS_SRC) diff --git a/libfprint/aeslib.c b/libfprint/aeslib.c new file mode 100644 index 00000000..e93e06f3 --- /dev/null +++ b/libfprint/aeslib.c @@ -0,0 +1,95 @@ +/* + * Shared functions between libfprint Authentec drivers + * Copyright (C) 2007 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#define FP_COMPONENT "aeslib" + +#include + +#include + +#include "fp_internal.h" +#include "aeslib.h" + +#define MAX_REGWRITES_PER_REQUEST 16 + +#define BULK_TIMEOUT 4000 +#define EP_IN (1 | USB_ENDPOINT_IN) +#define EP_OUT (2 | USB_ENDPOINT_OUT) + +static int do_write_regv(struct fp_img_dev *dev, struct aes_regwrite *regs, + unsigned int num) +{ + size_t alloc_size = num * 2; + unsigned char *data = g_malloc(alloc_size); + unsigned int i; + size_t offset = 0; + int r; + + for (i = 0; i < num; i++) { + data[offset++] = regs[i].reg; + data[offset++] = regs[i].value; + } + + r = usb_bulk_write(dev->udev, EP_OUT, data, alloc_size, BULK_TIMEOUT); + g_free(data); + if (r < 0) { + fp_err("bulk write error %d", r); + return r; + } else if ((unsigned int) r < alloc_size) { + fp_err("unexpected short write %d/%d", r, alloc_size); + return -EIO; + } + + return 0; +} + +int aes_write_regv(struct fp_img_dev *dev, struct aes_regwrite *regs, + unsigned int num) +{ + unsigned int i; + int skip = 0; + int add_offset = 0; + fp_dbg("write %d regs", num); + + for (i = 0; i < num; i += add_offset + skip) { + int r, j; + int limit = MIN(num, i + MAX_REGWRITES_PER_REQUEST); + skip = 0; + + if (!regs[i].reg) { + add_offset = 0; + skip = 1; + continue; + } + + for (j = i; j < limit; j++) + if (!regs[j].reg) { + skip = 1; + break; + } + + add_offset = j - i; + r = do_write_regv(dev, ®s[i], add_offset); + if (r < 0) + return r; + } + + return 0; +} + diff --git a/libfprint/aeslib.h b/libfprint/aeslib.h new file mode 100644 index 00000000..19b6cc6d --- /dev/null +++ b/libfprint/aeslib.h @@ -0,0 +1,34 @@ +/* + * Shared functions between libfprint Authentec drivers + * Copyright (C) 2007 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef __AESLIB_H__ +#define __AESLIB_H__ + +#include + +struct aes_regwrite { + unsigned char reg; + unsigned char value; +}; + +int aes_write_regv(struct fp_img_dev *dev, struct aes_regwrite *regs, + unsigned int num); + +#endif + diff --git a/libfprint/drivers/aes1610.c b/libfprint/drivers/aes1610.c index bf42e983..5bc4d80f 100644 --- a/libfprint/drivers/aes1610.c +++ b/libfprint/drivers/aes1610.c @@ -29,6 +29,7 @@ #include +#include #include /* FIXME these need checking */ @@ -36,7 +37,6 @@ #define EP_OUT (2 | USB_ENDPOINT_OUT) #define BULK_TIMEOUT 4000 -#define MAX_REGWRITES_PER_REQUEST 16 #define FIRST_AES1610_REG 0x1B #define LAST_AES1610_REG 0xFF @@ -60,66 +60,6 @@ /* FIXME reduce substantially */ #define MAX_FRAMES 350 -struct aes1610_regwrite { - unsigned char reg; - unsigned char value; -}; - -static int do_write_regv(struct fp_img_dev *dev, const struct aes1610_regwrite *regs, - unsigned int num) -{ - size_t alloc_size = num * 2; - unsigned char *data = g_malloc(alloc_size); - unsigned int i; - size_t offset = 0; - int r; - - for (i = 0; i < num; i++) { - data[offset++] = regs[i].reg; - data[offset++] = regs[i].value; - } - - r = usb_bulk_write(dev->udev, EP_OUT, data, alloc_size, BULK_TIMEOUT); - g_free(data); - if (r < 0) { - fp_err("bulk write error %d", r); - return r; - } else if (r < (int) alloc_size) { - fp_err("unexpected short write %d/%d", r, alloc_size); - return -EIO; - } - - return 0; -} - -static int write_regv(struct fp_img_dev *dev, const struct aes1610_regwrite *regs, - unsigned int num) -{ - unsigned int i; - int skip = 0; - int add_offset = 0; - fp_dbg("write %d regs", num); - - for (i = 0; i < num; i += add_offset + skip) { - int r, j; - int limit = MIN(num, i + MAX_REGWRITES_PER_REQUEST); - skip = 0; - - for (j = i; j < limit; j++) - if (!regs[j].reg) { - skip = 1; - break; - } - - add_offset = j - i; - r = do_write_regv(dev, ®s[i], add_offset); - if (r < 0) - return r; - } - - return 0; -} - static int read_data(struct fp_img_dev *dev, unsigned char *data, size_t len) { int r; @@ -136,19 +76,14 @@ static int read_data(struct fp_img_dev *dev, unsigned char *data, size_t len) return 0; } -static const struct aes1610_regwrite init[] = { +static const struct aes_regwrite init[] = { { 0x82, 0x00 } }; -static const struct aes1610_regwrite stop_reader[] = { +static const struct aes_regwrite stop_reader[] = { { 0xFF, 0x00 } }; -static int do_init(struct fp_img_dev *dev) -{ - return write_regv(dev, init, G_N_ELEMENTS(init)); -} - static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) { int r; @@ -161,12 +96,12 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) /* FIXME check endpoints */ - return do_init(dev); + return aes_write_regv(dev, init, G_N_ELEMENTS(init)); } static int do_exit(struct fp_img_dev *dev) { - return write_regv(dev, stop_reader, G_N_ELEMENTS(stop_reader)); + return aes_write_regv(dev, stop_reader, G_N_ELEMENTS(stop_reader)); } static void dev_exit(struct fp_img_dev *dev) @@ -175,7 +110,7 @@ static void dev_exit(struct fp_img_dev *dev) usb_release_interface(dev->udev, 0); } -static const struct aes1610_regwrite finger_det_reqs[] = { +static const struct aes_regwrite finger_det_reqs[] = { { 0x80, 0x01 }, { 0x80, 0x12 }, { 0x85, 0x00 }, @@ -200,7 +135,7 @@ static const struct aes1610_regwrite finger_det_reqs[] = { { 0x81, 0x04 } }; -static const struct aes1610_regwrite finger_det_none[] = { +static const struct aes_regwrite finger_det_none[] = { { 0x80, 0x01 }, { 0x82, 0x00 }, { 0x86, 0x00 }, @@ -215,7 +150,7 @@ static int detect_finger(struct fp_img_dev *dev) int i; int sum = 0; - r = write_regv(dev, finger_det_reqs, G_N_ELEMENTS(finger_det_reqs)); + r = aes_write_regv(dev, finger_det_reqs, G_N_ELEMENTS(finger_det_reqs)); if (r < 0) return r; @@ -228,7 +163,7 @@ static int detect_finger(struct fp_img_dev *dev) /* We need to answer something if no finger has been detected */ if (sum <= 20) { - r = write_regv(dev, finger_det_none, G_N_ELEMENTS(finger_det_none)); + r = aes_write_regv(dev, finger_det_none, G_N_ELEMENTS(finger_det_none)); if (r < 0) return r; } @@ -327,7 +262,7 @@ static unsigned int assemble(unsigned char *input, unsigned char *output, return image_height; } -static const struct aes1610_regwrite capture_reqs[] = { +static const struct aes_regwrite capture_reqs[] = { { 0x80, 0x01 }, { 0x80, 0x12 }, { 0x84, 0x01 }, @@ -453,7 +388,7 @@ static const struct aes1610_regwrite capture_reqs[] = { { 0x81, 0x01 } }; -static const struct aes1610_regwrite strip_scan_reqs[] = { +static const struct aes_regwrite strip_scan_reqs[] = { { 0xBE, 0x23 }, { 0x29, 0x06 }, { 0x2A, 0x35 }, @@ -461,7 +396,7 @@ static const struct aes1610_regwrite strip_scan_reqs[] = { { 0xFF, 0x00 } }; -static const struct aes1610_regwrite capture_stop[] = { +static const struct aes_regwrite capture_stop[] = { { 0x81,0x00 } }; @@ -482,7 +417,7 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, /* FIXME can do better here in terms of buffer management? */ fp_dbg(""); - r = write_regv(dev, capture_reqs, G_N_ELEMENTS(capture_reqs)); + r = aes_write_regv(dev, capture_reqs, G_N_ELEMENTS(capture_reqs)); if (r < 0) return r; @@ -507,7 +442,7 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, /* we start at 2 because we captured 2 frames above. the above captures * should possibly be moved into the loop below, or discarded altogether */ for (nstrips = 2; nstrips < MAX_FRAMES - 2; nstrips++) { - r = write_regv(dev, strip_scan_reqs, G_N_ELEMENTS(strip_scan_reqs)); + r = aes_write_regv(dev, strip_scan_reqs, G_N_ELEMENTS(strip_scan_reqs)); if (r < 0) goto err; r = read_data(dev, buf, 665); @@ -544,7 +479,7 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, break; } - r = write_regv(dev, capture_stop, G_N_ELEMENTS(capture_stop)); + r = aes_write_regv(dev, capture_stop, G_N_ELEMENTS(capture_stop)); if (r < 0) goto err; r = read_data(dev, buf, 665); diff --git a/libfprint/drivers/aes2501.c b/libfprint/drivers/aes2501.c index 0c8515a3..2abfa4ec 100644 --- a/libfprint/drivers/aes2501.c +++ b/libfprint/drivers/aes2501.c @@ -28,6 +28,7 @@ #include +#include #include #include "aes2501.h" @@ -36,7 +37,6 @@ #define EP_OUT (2 | USB_ENDPOINT_OUT) #define BULK_TIMEOUT 4000 -#define MAX_REGWRITES_PER_REQUEST 16 /* * The AES2501 is an imaging device using a swipe-type sensor. It samples @@ -57,66 +57,6 @@ /* FIXME reduce substantially */ #define MAX_FRAMES 150 -struct aes2501_regwrite { - unsigned char reg; - unsigned char value; -}; - -static int do_write_regv(struct fp_img_dev *dev, struct aes2501_regwrite *regs, - unsigned int num) -{ - size_t alloc_size = num * 2; - unsigned char *data = g_malloc(alloc_size); - unsigned int i; - size_t offset = 0; - int r; - - for (i = 0; i < num; i++) { - data[offset++] = regs[i].reg; - data[offset++] = regs[i].value; - } - - r = usb_bulk_write(dev->udev, EP_OUT, data, alloc_size, BULK_TIMEOUT); - g_free(data); - if (r < 0) { - fp_err("bulk write error %d", r); - return r; - } else if (r < alloc_size) { - fp_err("unexpected short write %d/%d", r, alloc_size); - return -EIO; - } - - return 0; -} - -static int write_regv(struct fp_img_dev *dev, struct aes2501_regwrite *regs, - unsigned int num) -{ - unsigned int i; - int skip = 0; - int add_offset = 0; - fp_dbg("write %d regs", num); - - for (i = 0; i < num; i += add_offset + skip) { - int r, j; - int limit = MIN(num, i + MAX_REGWRITES_PER_REQUEST); - skip = 0; - - for (j = i; j < limit; j++) - if (!regs[j].reg) { - skip = 1; - break; - } - - add_offset = j - i; - r = do_write_regv(dev, ®s[i], add_offset); - if (r < 0) - return r; - } - - return 0; -} - static int read_data(struct fp_img_dev *dev, unsigned char *data, size_t len) { int r; @@ -136,20 +76,20 @@ static int read_data(struct fp_img_dev *dev, unsigned char *data, size_t len) static int read_regs(struct fp_img_dev *dev, unsigned char *data) { int r; - const struct aes2501_regwrite regwrite = { + const struct aes_regwrite regwrite = { AES2501_REG_CTRL2, AES2501_CTRL2_READ_REGS }; fp_dbg(""); - r = write_regv(dev, ®write, 1); + r = aes_write_regv(dev, ®write, 1); if (r < 0) return r; return read_data(dev, data, 126); } -static const struct aes2501_regwrite init_1[] = { +static const struct aes_regwrite init_1[] = { { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, { 0, 0 }, { 0xb0, 0x27 }, /* Reserved? */ @@ -193,7 +133,7 @@ static const struct aes2501_regwrite init_1[] = { { AES2501_REG_LPONT, AES2501_LPONT_MIN_VALUE }, }; -static const struct aes2501_regwrite init_2[] = { +static const struct aes_regwrite init_2[] = { { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, { AES2501_REG_EXCITCTRL, 0x40 }, { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, @@ -203,7 +143,7 @@ static const struct aes2501_regwrite init_2[] = { { AES2501_REG_CTRL1, AES2501_CTRL1_REG_UPDATE }, }; -static const struct aes2501_regwrite init_3[] = { +static const struct aes_regwrite init_3[] = { { 0xff, 0x00 }, { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, { AES2501_REG_AUTOCALOFFSET, 0x41 }, @@ -212,7 +152,7 @@ static const struct aes2501_regwrite init_3[] = { { AES2501_REG_CTRL1, AES2501_CTRL1_REG_UPDATE }, }; -static const struct aes2501_regwrite init_4[] = { +static const struct aes_regwrite init_4[] = { { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, { AES2501_REG_EXCITCTRL, 0x40 }, { 0xb0, 0x27 }, @@ -222,7 +162,7 @@ static const struct aes2501_regwrite init_4[] = { { AES2501_REG_AUTOCALOFFSET, 0x41 }, }; -static const struct aes2501_regwrite init_5[] = { +static const struct aes_regwrite init_5[] = { { 0xb0, 0x27 }, { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, { AES2501_REG_EXCITCTRL, 0x40 }, @@ -248,7 +188,7 @@ static int do_init(struct fp_img_dev *dev) int i; /* part 1, probably not needed */ - r = write_regv(dev, init_1, G_N_ELEMENTS(init_1)); + r = aes_write_regv(dev, init_1, G_N_ELEMENTS(init_1)); if (r < 0) return r; @@ -257,7 +197,7 @@ static int do_init(struct fp_img_dev *dev) return r; /* part 2 */ - r = write_regv(dev, init_2, G_N_ELEMENTS(init_2)); + r = aes_write_regv(dev, init_2, G_N_ELEMENTS(init_2)); if (r < 0) return r; @@ -269,7 +209,7 @@ static int do_init(struct fp_img_dev *dev) fp_dbg("reg 0xaf = %x", buffer[0x5f]); i = 0; while (buffer[0x5f] == 0x6b) { - r = write_regv(dev, init_3, G_N_ELEMENTS(init_3)); + r = aes_write_regv(dev, init_3, G_N_ELEMENTS(init_3)); if (r < 0) return r; r = read_regs(dev, buffer); @@ -280,12 +220,12 @@ static int do_init(struct fp_img_dev *dev) } /* part 4 */ - r = write_regv(dev, init_4, G_N_ELEMENTS(init_4)); + r = aes_write_regv(dev, init_4, G_N_ELEMENTS(init_4)); if (r < 0) return r; /* part 5 */ - return write_regv(dev, init_5, G_N_ELEMENTS(init_5)); + return aes_write_regv(dev, init_5, G_N_ELEMENTS(init_5)); } static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) @@ -308,7 +248,7 @@ static void dev_exit(struct fp_img_dev *dev) usb_release_interface(dev->udev, 0); } -static const struct aes2501_regwrite finger_det_reqs[] = { +static const struct aes_regwrite finger_det_reqs[] = { { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, { AES2501_REG_EXCITCTRL, 0x40 }, { AES2501_REG_DETCTRL, @@ -343,7 +283,7 @@ static int detect_finger(struct fp_img_dev *dev) int i; int sum = 0; - r = write_regv(dev, finger_det_reqs, G_N_ELEMENTS(finger_det_reqs)); + r = aes_write_regv(dev, finger_det_reqs, G_N_ELEMENTS(finger_det_reqs)); if (r < 0) return r; @@ -485,7 +425,7 @@ static unsigned int assemble(unsigned char *input, unsigned char *output, return image_height; } -static const struct aes2501_regwrite capture_reqs_1[] = { +static const struct aes_regwrite capture_reqs_1[] = { { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, { 0, 0 }, { AES2501_REG_EXCITCTRL, 0x40 }, @@ -519,7 +459,7 @@ static const struct aes2501_regwrite capture_reqs_1[] = { { AES2501_REG_LPONT, AES2501_LPONT_MIN_VALUE }, }; -static const struct aes2501_regwrite capture_reqs_2[] = { +static const struct aes_regwrite capture_reqs_2[] = { { AES2501_REG_IMAGCTRL, AES2501_IMAGCTRL_TST_REG_ENABLE | AES2501_IMAGCTRL_HISTO_DATA_ENABLE | AES2501_IMAGCTRL_IMG_DATA_DISABLE }, @@ -531,7 +471,7 @@ static const struct aes2501_regwrite capture_reqs_2[] = { { AES2501_REG_CTRL2, AES2501_CTRL2_SET_ONE_SHOT }, }; -static const struct aes2501_regwrite strip_scan_reqs[] = { +static const struct aes_regwrite strip_scan_reqs[] = { { AES2501_REG_IMAGCTRL, AES2501_IMAGCTRL_TST_REG_ENABLE | AES2501_IMAGCTRL_HISTO_DATA_ENABLE }, { AES2501_REG_STRTCOL, 0x00 }, @@ -558,7 +498,7 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, /* FIXME can do better here in terms of buffer management? */ fp_dbg(""); - r = write_regv(dev, capture_reqs_1, G_N_ELEMENTS(capture_reqs_1)); + r = aes_write_regv(dev, capture_reqs_1, G_N_ELEMENTS(capture_reqs_1)); if (r < 0) return r; @@ -566,7 +506,7 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, if (r < 0) return r; - r = write_regv(dev, capture_reqs_2, G_N_ELEMENTS(capture_reqs_2)); + r = aes_write_regv(dev, capture_reqs_2, G_N_ELEMENTS(capture_reqs_2)); if (r < 0) return r; @@ -583,7 +523,7 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, for (nstrips = 0; nstrips < MAX_FRAMES; nstrips++) { int threshold; - r = write_regv(dev, strip_scan_reqs, G_N_ELEMENTS(strip_scan_reqs)); + r = aes_write_regv(dev, strip_scan_reqs, G_N_ELEMENTS(strip_scan_reqs)); if (r < 0) goto err; r = read_data(dev, buf, 1705); diff --git a/libfprint/drivers/aes4000.c b/libfprint/drivers/aes4000.c index 111a8248..f3004772 100644 --- a/libfprint/drivers/aes4000.c +++ b/libfprint/drivers/aes4000.c @@ -24,6 +24,7 @@ #include #include +#include #include #define CTRL_TIMEOUT 1000 @@ -33,25 +34,6 @@ #define NR_SUBARRAYS 6 #define SUBARRAY_LEN 768 -static int write_reg(struct fp_img_dev *dev, unsigned char reg, - unsigned char value) -{ - unsigned char data[] = { reg, value }; - int r; - - fp_dbg("%02x=%02x", reg, value); - r = usb_bulk_write(dev->udev, EP_OUT, data, sizeof(data), CTRL_TIMEOUT); - if (r < 0) { - fp_err("bulk write error %d", r); - return r; - } else if (r < sizeof(data)) { - fp_err("unexpected short write %d/%d", r, sizeof(data)); - return -EIO; - } - - return 0; -} - static void process_subarray(unsigned char *src, unsigned char *dst) { int col, row; @@ -66,26 +48,31 @@ static void process_subarray(unsigned char *src, unsigned char *dst) } } -static const struct aes4000_regwrite { - unsigned char reg; - unsigned char value; -} init_reqs[] = { +static const struct aes_regwrite init_reqs[] = { /* master reset */ { 0x80, 0x01 }, + { 0, 0 }, { 0x80, 0x00 }, + { 0, 0 }, { 0x81, 0x00 }, { 0x80, 0x00 }, + { 0, 0 }, /* scan reset */ { 0x80, 0x02 }, + { 0, 0 }, { 0x80, 0x00 }, + { 0, 0 }, /* disable register buffering */ { 0x80, 0x04 }, + { 0, 0 }, { 0x80, 0x00 }, + { 0, 0 }, { 0x81, 0x00 }, + { 0, 0 }, /* windows driver reads registers now (81 02) */ { 0x80, 0x00 }, { 0x81, 0x00 }, @@ -126,10 +113,13 @@ static const struct aes4000_regwrite { { 0x9d, 0x09 }, /* set some challenge word bits */ { 0x9e, 0x53 }, /* clear challenge word bits */ { 0x9f, 0x6b }, /* set some challenge word bits */ + { 0, 0 }, { 0x80, 0x00 }, { 0x81, 0x00 }, + { 0, 0 }, { 0x81, 0x04 }, + { 0, 0 }, { 0x81, 0x00 }, }; @@ -142,11 +132,9 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, unsigned char *data; unsigned char *ptr; - for (i = 0; i < G_N_ELEMENTS(init_reqs); i++) { - r = write_reg(dev, init_reqs[i].reg, init_reqs[i].value); - if (r < 0) - return r; - } + r = aes_write_regv(dev, init_reqs, G_N_ELEMENTS(init_reqs)); + if (r < 0) + return r; img = fpi_img_new_for_imgdev(dev); data = g_malloc(DATA_BUFLEN); From 3479dee0e4f6e0a2e779289378cb90c7a7710f88 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 26 Nov 2007 23:28:14 +0000 Subject: [PATCH 085/184] aeslib: image assembly All 3 authentec drivers now use a shared image assembly function. --- libfprint/aeslib.c | 15 +++++++++++++++ libfprint/aeslib.h | 3 +++ libfprint/drivers/aes1610.c | 19 ++++++------------- libfprint/drivers/aes2501.c | 20 ++++++-------------- libfprint/drivers/aes4000.c | 20 +++----------------- 5 files changed, 33 insertions(+), 44 deletions(-) diff --git a/libfprint/aeslib.c b/libfprint/aeslib.c index e93e06f3..aa8571e9 100644 --- a/libfprint/aeslib.c +++ b/libfprint/aeslib.c @@ -93,3 +93,18 @@ int aes_write_regv(struct fp_img_dev *dev, struct aes_regwrite *regs, return 0; } +int aes_assemble_image(unsigned char *input, size_t width, size_t height, + unsigned char *output) +{ + size_t frame_size = width * height; + size_t row, column; + + for (column = 0; column < width; column++) { + for (row = 0; row < height; row += 2) { + output[width * row + column] = (*input & 0x07) * 36; + output[width * (row + 1) + column] = ((*input & 0x70) >> 4) * 36; + input++; + } + } +} + diff --git a/libfprint/aeslib.h b/libfprint/aeslib.h index 19b6cc6d..c02f5074 100644 --- a/libfprint/aeslib.h +++ b/libfprint/aeslib.h @@ -30,5 +30,8 @@ struct aes_regwrite { int aes_write_regv(struct fp_img_dev *dev, struct aes_regwrite *regs, unsigned int num); +int aes_assemble_image(unsigned char *input, size_t width, size_t height, + unsigned char *output); + #endif diff --git a/libfprint/drivers/aes1610.c b/libfprint/drivers/aes1610.c index 5bc4d80f..eb71a4b9 100644 --- a/libfprint/drivers/aes1610.c +++ b/libfprint/drivers/aes1610.c @@ -231,15 +231,8 @@ static unsigned int assemble(unsigned char *input, unsigned char *output, if (reverse) output += (num_strips - 1) * FRAME_SIZE; for (frame = 0; frame < num_strips; frame++) { - int column; - for (column = 0; column < FRAME_WIDTH; column++) { - int row; - for (row = 0; row < (FRAME_HEIGHT / 2); row++) { - output[FRAME_WIDTH * ( 2 * row) + column] = *input & 0x0F; - output[FRAME_WIDTH * ( 2 * row + 1) + column] = *input >> 4; - input++; - } - } + aes_assemble_image(input, FRAME_WIDTH, FRAME_HEIGHT, output); + input += FRAME_WIDTH * (FRAME_HEIGHT / 2); if (reverse) output -= FRAME_SIZE; @@ -410,6 +403,7 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, unsigned char *cooked; unsigned char *imgptr; unsigned char buf[665]; + int final_size; int sum; unsigned int count_blank = 0; int i; @@ -511,10 +505,9 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, fp_dbg("reversed scan direction"); } - for (i = 0; i < img->height * FRAME_WIDTH; i++) - img->data[i] = (cooked[i] << 4) | 0xf; - - img = fpi_img_resize(img, img->height * FRAME_WIDTH); + final_size = img->height * FRAME_WIDTH; + memcpy(img->data, cooked, final_size); + img = fpi_img_resize(img, final_size); *ret = img; return 0; err: diff --git a/libfprint/drivers/aes2501.c b/libfprint/drivers/aes2501.c index 2abfa4ec..ff7cd107 100644 --- a/libfprint/drivers/aes2501.c +++ b/libfprint/drivers/aes2501.c @@ -394,15 +394,8 @@ static unsigned int assemble(unsigned char *input, unsigned char *output, if (reverse) output += (num_strips - 1) * FRAME_SIZE; for (frame = 0; frame < num_strips; frame++) { - int column; - for (column = 0; column < FRAME_WIDTH; column++) { - int row; - for (row = 0; row < (FRAME_HEIGHT / 2); row++) { - output[FRAME_WIDTH * ( 2 * row) + column] = *input & 0x0F; - output[FRAME_WIDTH * ( 2 * row + 1) + column] = *input >> 4; - input++; - } - } + aes_assemble_image(input, FRAME_WIDTH, FRAME_HEIGHT, output); + input += FRAME_WIDTH * (FRAME_HEIGHT / 2); if (reverse) output -= FRAME_SIZE; @@ -492,8 +485,8 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, unsigned char *cooked; unsigned char *imgptr; unsigned char buf[1705]; + int final_size; int sum; - int i; /* FIXME can do better here in terms of buffer management? */ fp_dbg(""); @@ -563,10 +556,9 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, fp_dbg("reversed scan direction"); } - for (i = 0; i < img->height * FRAME_WIDTH; i++) - img->data[i] = (cooked[i] << 4) | 0xf; - - img = fpi_img_resize(img, img->height * FRAME_WIDTH); + final_size = img->height * FRAME_WIDTH; + memcpy(img->data, cooked, final_size); + img = fpi_img_resize(img, final_size); *ret = img; return 0; err: diff --git a/libfprint/drivers/aes4000.c b/libfprint/drivers/aes4000.c index f3004772..f2c737f9 100644 --- a/libfprint/drivers/aes4000.c +++ b/libfprint/drivers/aes4000.c @@ -34,20 +34,6 @@ #define NR_SUBARRAYS 6 #define SUBARRAY_LEN 768 -static void process_subarray(unsigned char *src, unsigned char *dst) -{ - int col, row; - int offset = -1; - - for (col = 95; col >= 0; col--) { - for (row = 15; row >= 0; row -= 2) { - unsigned char val = src[++offset]; - dst[(row * 96) + col] = (val & 0x7) * 36; - dst[((row - 1) * 96) + col] = ((val & 0x70) >> 4) * 36; - } - } -} - static const struct aes_regwrite init_reqs[] = { /* master reset */ { 0x80, 0x01 }, @@ -156,14 +142,14 @@ retry: goto err; } - for (i = NR_SUBARRAYS - 1; i >= 0; i--) { + for (i = 0; i < NR_SUBARRAYS; i++) { fp_dbg("subarray header byte %02x", *ptr); ptr++; - process_subarray(ptr, img->data + (i * 96 * 16)); + aes_assemble_image(ptr, 96, 16, img->data + (i * 96 * 16)); ptr += SUBARRAY_LEN; } - img->flags = FP_IMG_COLORS_INVERTED; + img->flags = FP_IMG_COLORS_INVERTED | FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED; *ret = img; g_free(data); return 0; From c1f8581ec93d4e7d32f3880524cb1d775020d5b9 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 1 Dec 2007 13:00:33 +0000 Subject: [PATCH 086/184] Cleanup discover_device in examples Andrei Tchijov pointed out that the discover_device() function is written in a strange way. --- examples/enroll.c | 17 +++++++---------- examples/img_capture.c | 17 +++++++---------- examples/img_capture_continuous.c | 19 ++++++++----------- examples/verify.c | 17 +++++++---------- examples/verify_live.c | 17 +++++++---------- 5 files changed, 36 insertions(+), 51 deletions(-) diff --git a/examples/enroll.c b/examples/enroll.c index 2031938c..7d077881 100644 --- a/examples/enroll.c +++ b/examples/enroll.c @@ -26,16 +26,13 @@ struct fp_dscv_dev *discover_device(struct fp_dscv_dev **discovered_devs) { - struct fp_dscv_dev *ddev = NULL; - int i; - - for (i = 0; ddev = discovered_devs[i]; i++) { - struct fp_driver *drv = fp_dscv_dev_get_driver(ddev); - printf("Found device claimed by %s driver\n", - fp_driver_get_full_name(drv)); - return ddev; - } - + struct fp_dscv_dev *ddev = discovered_devs[0]; + struct fp_driver *drv; + if (!ddev) + return NULL; + + drv = fp_dscv_dev_get_driver(ddev); + printf("Found device claimed by %s driver\n", fp_driver_get_full_name(drv)); return ddev; } diff --git a/examples/img_capture.c b/examples/img_capture.c index ea494c89..d45b8b85 100644 --- a/examples/img_capture.c +++ b/examples/img_capture.c @@ -24,16 +24,13 @@ struct fp_dscv_dev *discover_device(struct fp_dscv_dev **discovered_devs) { - struct fp_dscv_dev *ddev = NULL; - int i; - - for (i = 0; ddev = discovered_devs[i]; i++) { - struct fp_driver *drv = fp_dscv_dev_get_driver(ddev); - printf("Found device claimed by %s driver\n", - fp_driver_get_full_name(drv)); - return ddev; - } - + struct fp_dscv_dev *ddev = discovered_devs[0]; + struct fp_driver *drv; + if (!ddev) + return NULL; + + drv = fp_dscv_dev_get_driver(ddev); + printf("Found device claimed by %s driver\n", fp_driver_get_full_name(drv)); return ddev; } diff --git a/examples/img_capture_continuous.c b/examples/img_capture_continuous.c index 0f1644eb..752f7101 100644 --- a/examples/img_capture_continuous.c +++ b/examples/img_capture_continuous.c @@ -116,18 +116,15 @@ static void QueryXv() printf("No suitable Xv adaptor found\n"); } -static struct fp_dscv_dev *discover_device(struct fp_dscv_dev **discovered_devs) +struct fp_dscv_dev *discover_device(struct fp_dscv_dev **discovered_devs) { - struct fp_dscv_dev *ddev = NULL; - int i; - - for (i = 0; ddev = discovered_devs[i]; i++) { - struct fp_driver *drv = fp_dscv_dev_get_driver(ddev); - printf("Found device claimed by %s driver\n", - fp_driver_get_full_name(drv)); - return ddev; - } - + struct fp_dscv_dev *ddev = discovered_devs[0]; + struct fp_driver *drv; + if (!ddev) + return NULL; + + drv = fp_dscv_dev_get_driver(ddev); + printf("Found device claimed by %s driver\n", fp_driver_get_full_name(drv)); return ddev; } diff --git a/examples/verify.c b/examples/verify.c index af4327f1..1e1dd4fb 100644 --- a/examples/verify.c +++ b/examples/verify.c @@ -26,16 +26,13 @@ struct fp_dscv_dev *discover_device(struct fp_dscv_dev **discovered_devs) { - struct fp_dscv_dev *ddev = NULL; - int i; - - for (i = 0; ddev = discovered_devs[i]; i++) { - struct fp_driver *drv = fp_dscv_dev_get_driver(ddev); - printf("Found device claimed by %s driver\n", - fp_driver_get_full_name(drv)); - return ddev; - } - + struct fp_dscv_dev *ddev = discovered_devs[0]; + struct fp_driver *drv; + if (!ddev) + return NULL; + + drv = fp_dscv_dev_get_driver(ddev); + printf("Found device claimed by %s driver\n", fp_driver_get_full_name(drv)); return ddev; } diff --git a/examples/verify_live.c b/examples/verify_live.c index 0e1db6d7..9a7b6a98 100644 --- a/examples/verify_live.c +++ b/examples/verify_live.c @@ -25,16 +25,13 @@ struct fp_dscv_dev *discover_device(struct fp_dscv_dev **discovered_devs) { - struct fp_dscv_dev *ddev = NULL; - int i; - - for (i = 0; ddev = discovered_devs[i]; i++) { - struct fp_driver *drv = fp_dscv_dev_get_driver(ddev); - printf("Found device claimed by %s driver\n", - fp_driver_get_full_name(drv)); - return ddev; - } - + struct fp_dscv_dev *ddev = discovered_devs[0]; + struct fp_driver *drv; + if (!ddev) + return NULL; + + drv = fp_dscv_dev_get_driver(ddev); + printf("Found device claimed by %s driver\n", fp_driver_get_full_name(drv)); return ddev; } From 474da5f2c779a1c4a1309fd9f05972372ced7568 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Fri, 7 Dec 2007 14:59:38 +0000 Subject: [PATCH 087/184] Add a disclaimer for the university --- README | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/README b/README index a9658925..79a1ac9e 100644 --- a/README +++ b/README @@ -10,6 +10,16 @@ consumer fingerprint scanners and providing a single uniform API to application developers. The ultimate goal of the fprint project is to make fingerprint scanners widely and easily usable under common Linux environments. +The academic university project runs off a codebase maintained separately +from this one, although I try to keep them as similar as possible (I'm not +hiding anything in the academic branch, it's just the open source release +contains some commits excluded from the academic project). + +THE UNIVERSITY OF MANCHESTER DOES NOT ENDORSE THIS THIS SOFTWARE RELEASE AND +IS IN NO WAY RESPONSIBLE FOR THE CODE CONTAINED WITHIN, OR ANY DAMAGES CAUSED +BY USING OR DISTRIBUTING THE SOFTWARE. Development does not happen on +university computers and the project is not hosted at the university either. + For more information on libfprint, supported devices, API documentation, etc., see the homepage: http://www.reactivated.net/fprint/Libfprint From 642010643d04a5e43eac6fcb3d41b18003cde132 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Fri, 16 Nov 2007 17:25:41 +0000 Subject: [PATCH 088/184] uru4000: Add support for Microsoft Fingerprint Reader v2 After lot 713, Microsoft fingerprint readers changed. The new version comes with a new USB product ID and a challenge-response authentication scheme where the device challenges the authenticity of the driver. An independent third party produced documentation on the computations needed to convert a challenge into the correct response, and I then used this documentation to produce a clean-room reimplementation of the authentication scheme. --- configure.ac | 5 ++ libfprint/Makefile.am | 4 +- libfprint/drivers/uru4000.c | 99 ++++++++++++++++++++++++++++++++++++- 3 files changed, 105 insertions(+), 3 deletions(-) diff --git a/configure.ac b/configure.ac index db450c76..ef48425c 100644 --- a/configure.ac +++ b/configure.ac @@ -21,6 +21,11 @@ PKG_CHECK_MODULES(LIBUSB, "libusb") AC_SUBST(LIBUSB_CFLAGS) AC_SUBST(LIBUSB_LIBS) +# check for OpenSSL's libcrypto +PKG_CHECK_MODULES(CRYPTO, "libcrypto") +AC_SUBST(CRYPTO_CFLAGS) +AC_SUBST(CRYPTO_LIBS) + PKG_CHECK_MODULES(GLIB, "glib-2.0") AC_SUBST(GLIB_CFLAGS) AC_SUBST(GLIB_LIBS) diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 3e2702f8..933ec690 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -46,9 +46,9 @@ NBIS_SRC = \ nbis/mindtct/sort.c \ nbis/mindtct/util.c -libfprint_la_CFLAGS = -fvisibility=hidden -I$(srcdir)/nbis/include $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) $(IMAGEMAGICK_CFLAGS) $(AM_CFLAGS) +libfprint_la_CFLAGS = -fvisibility=hidden -I$(srcdir)/nbis/include $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) $(IMAGEMAGICK_CFLAGS) $(CRYPTO_CFLAGS) $(AM_CFLAGS) libfprint_la_LDFLAGS = -version-info @lt_major@:@lt_revision@:@lt_age@ -libfprint_la_LIBADD = -lm $(LIBUSB_LIBS) $(GLIB_LIBS) $(IMAGEMAGICK_LIBS) +libfprint_la_LIBADD = -lm $(LIBUSB_LIBS) $(GLIB_LIBS) $(IMAGEMAGICK_LIBS) $(CRYPTO_LIBS) libfprint_la_SOURCES = \ fp_internal.h \ diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index 51b57c30..24698679 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -23,6 +23,7 @@ #include #include +#include #include #include @@ -39,6 +40,7 @@ #define DATABLK2_EXPECT 0xb1c0 #define CAPTURE_HDRLEN 64 #define IRQ_LENGTH 64 +#define CR_LENGTH 16 enum { IRQDATA_SCANPWR_ON = 0x56aa, @@ -51,6 +53,8 @@ enum { REG_HWSTAT = 0x07, REG_MODE = 0x4e, FIRMWARE_START = 0x100, + REG_RESPONSE = 0x2000, + REG_CHALLENGE = 0x2010, }; enum { @@ -75,32 +79,50 @@ static const struct uru4k_dev_profile { const char *name; uint16_t firmware_start; uint16_t fw_enc_offset; + gboolean auth_cr; } uru4k_dev_info[] = { [MS_KBD] = { .name = "Microsoft Keyboard with Fingerprint Reader", .fw_enc_offset = 0x411, + .auth_cr = FALSE, }, [MS_INTELLIMOUSE] = { .name = "Microsoft Wireless IntelliMouse with Fingerprint Reader", .fw_enc_offset = 0x411, + .auth_cr = FALSE, }, [MS_STANDALONE] = { .name = "Microsoft Fingerprint Reader", .fw_enc_offset = 0x411, + .auth_cr = FALSE, + }, + [MS_STANDALONE_V2] = { + .name = "Microsoft Fingerprint Reader v2", + .fw_enc_offset = 0x52e, + .auth_cr = TRUE, }, [DP_URU4000] = { .name = "Digital Persona U.are.U 4000", .fw_enc_offset = 0x693, + .auth_cr = FALSE, }, [DP_URU4000B] = { .name = "Digital Persona U.are.U 4000B", .fw_enc_offset = 0x411, + .auth_cr = FALSE, }, }; struct uru4k_dev { const struct uru4k_dev_profile *profile; uint8_t interface; + AES_KEY aeskey; +}; + +/* For 2nd generation MS devices */ +static const unsigned char crkey[] = { + 0x79, 0xac, 0x91, 0x79, 0x5c, 0xa1, 0x47, 0x8e, + 0x98, 0xe0, 0x0f, 0x3c, 0x59, 0x8f, 0x5f, 0x4b, }; /* @@ -184,6 +206,71 @@ static int set_mode(struct fp_img_dev *dev, unsigned char mode) return 0; } +static int read_challenge(struct fp_img_dev *dev, unsigned char *data) +{ + int r; + + /* The windows driver uses a request of 0x0c here. We use 0x04 to be + * consistent with every other command we know about. */ + r = usb_control_msg(dev->udev, CTRL_IN, USB_RQ, REG_CHALLENGE, 0, + data, CR_LENGTH, CTRL_TIMEOUT); + if (r < 0) { + fp_err("error %d", r); + return r; + } else if (r < CR_LENGTH) { + fp_err("read too short (%d)", r); + return -EIO; + } + + return 0; +} + +static int write_response(struct fp_img_dev *dev, unsigned char *data) +{ + int r; + + r = usb_control_msg(dev->udev, CTRL_OUT, USB_RQ, REG_RESPONSE, 0, data, + CR_LENGTH, CTRL_TIMEOUT); + if (r < 0) { + fp_err("error %d", r); + return r; + } else if (r < 1) { + fp_err("write too short (%d)", r); + return -EIO; + } + + return 0; +} + +/* + * 2nd generation MS devices added an AES-based challenge/response + * authentication scheme, where the device challenges the authenticity of the + * driver. + */ +static int auth_cr(struct fp_img_dev *dev) +{ + struct uru4k_dev *urudev = dev->priv; + unsigned char challenge[CR_LENGTH]; + unsigned char response[CR_LENGTH]; + int r; + + fp_dbg(""); + + r = read_challenge(dev, challenge); + if (r < 0) { + fp_err("error %d reading challenge", r); + return r; + } + + AES_encrypt(challenge, response, &urudev->aeskey); + + r = write_response(dev, response); + if (r < 0) + fp_err("error %d writing response", r); + + return r; +} + static int get_irq(struct fp_img_dev *dev, unsigned char *buf, int timeout) { uint16_t type; @@ -398,6 +485,8 @@ static int do_init(struct fp_img_dev *dev) { unsigned char status; unsigned char tmp; + struct uru4k_dev *urudev = dev->priv; + gboolean need_auth_cr = urudev->profile->auth_cr; int timeouts = 0; int i; int r; @@ -467,7 +556,11 @@ retry: usleep(10000); - /* FIXME do C-R auth for v2 devices */ + if (need_auth_cr) { + r = auth_cr(dev); + if (r < 0) + return r; + } } if (tmp & 0x80) { @@ -556,6 +649,7 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) urudev = g_malloc0(sizeof(*urudev)); urudev->profile = &uru4k_dev_info[driver_data]; urudev->interface = iface_desc->bInterfaceNumber; + AES_set_encrypt_key(crkey, 128, &urudev->aeskey); dev->priv = urudev; r = do_init(dev); @@ -589,6 +683,9 @@ static const struct usb_id id_table[] = { /* ms fp rdr (standalone) */ { .vendor = 0x045e, .product = 0x00bd, .driver_data = MS_STANDALONE }, + /* ms fp rdr (standalone) v2 */ + { .vendor = 0x045e, .product = 0x00ca, .driver_data = MS_STANDALONE_V2 }, + /* dp uru4000 (standalone) */ { .vendor = 0x05ba, .product = 0x0007, .driver_data = DP_URU4000 }, From c8aa33da0bd2467594a92eeda641fe7749b9f33d Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Fri, 7 Dec 2007 15:03:27 +0000 Subject: [PATCH 089/184] v0.0.5 release --- NEWS | 5 +++++ configure.ac | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/NEWS b/NEWS index 4e24d27c..c0947c37 100644 --- a/NEWS +++ b/NEWS @@ -1,6 +1,11 @@ This file lists notable changes in each release. For the full history of all changes, see ChangeLog. +2007-12-07: v0.0.5 release + * AES1610 imaging improvements + * Internal cleanups for Authentec drivers + * Add support for latest Microsoft Fingerprint Scanner hardware revision + 2007-11-22: v0.0.4 release * Enable AES1610 driver thanks to Michele B * Implement identification: one-to-many fingerprint matching (Daniel Drake) diff --git a/configure.ac b/configure.ac index ef48425c..72618eee 100644 --- a/configure.ac +++ b/configure.ac @@ -1,4 +1,4 @@ -AC_INIT([libfprint], [0.0.4]) +AC_INIT([libfprint], [0.0.5]) AM_INIT_AUTOMAKE AC_CONFIG_SRCDIR([libfprint/core.c]) AM_CONFIG_HEADER([config.h]) From 659d8346beb4a0506d5c2f20c918a57804b4f591 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Thu, 27 Dec 2007 00:46:11 +0000 Subject: [PATCH 090/184] Compiler flags update Dropped -Wextra as it is not that useful. Set compiler flags to be more like the kernel's. Set std=gnu99 Fixed some warnings. --- TODO | 4 ++++ configure.ac | 2 +- libfprint/aeslib.c | 9 ++++----- libfprint/aeslib.h | 4 ++-- libfprint/core.c | 10 +++++----- libfprint/data.c | 8 ++++---- libfprint/drivers/upektc.c | 7 +++---- libfprint/img.c | 2 +- 8 files changed, 24 insertions(+), 22 deletions(-) diff --git a/TODO b/TODO index 66723a7b..5d1034d2 100644 --- a/TODO +++ b/TODO @@ -24,3 +24,7 @@ aes4000 resampling PPMM parameter to get_minutiae seems to have no effect nbis minutiae should be stored in endian-independent format +PORTABILITY +=========== +OpenBSD can't do -Wshadow or visibility +OpenBSD: add compat codes for ENOTSUP ENODATA and EPROTO diff --git a/configure.ac b/configure.ac index 72618eee..fb128cdf 100644 --- a/configure.ac +++ b/configure.ac @@ -91,7 +91,7 @@ fi AC_DEFINE([API_EXPORTED], [__attribute__((visibility("default")))], [Default visibility]) -AM_CFLAGS="-Werror-implicit-function-declaration -Wimplicit-int -Wunreachable-code -Wunused-function -Wunused-label -Wunused-value -Wunused-variable -Wnonnull -Wreturn-type -Wextra -Wshadow" +AM_CFLAGS="-std=gnu99 -fgnu89-inline -Wall -Wundef -Wunused -Wstrict-prototypes -Werror-implicit-function-declaration -Wno-pointer-sign -Wshadow" AC_SUBST(AM_CFLAGS) AC_CONFIG_FILES([libfprint.pc] [Makefile] [libfprint/Makefile] [examples/Makefile] [doc/Makefile]) diff --git a/libfprint/aeslib.c b/libfprint/aeslib.c index aa8571e9..f6d8dfb4 100644 --- a/libfprint/aeslib.c +++ b/libfprint/aeslib.c @@ -32,8 +32,8 @@ #define EP_IN (1 | USB_ENDPOINT_IN) #define EP_OUT (2 | USB_ENDPOINT_OUT) -static int do_write_regv(struct fp_img_dev *dev, struct aes_regwrite *regs, - unsigned int num) +static int do_write_regv(struct fp_img_dev *dev, + const struct aes_regwrite *regs, unsigned int num) { size_t alloc_size = num * 2; unsigned char *data = g_malloc(alloc_size); @@ -59,7 +59,7 @@ static int do_write_regv(struct fp_img_dev *dev, struct aes_regwrite *regs, return 0; } -int aes_write_regv(struct fp_img_dev *dev, struct aes_regwrite *regs, +int aes_write_regv(struct fp_img_dev *dev, const struct aes_regwrite *regs, unsigned int num) { unsigned int i; @@ -93,10 +93,9 @@ int aes_write_regv(struct fp_img_dev *dev, struct aes_regwrite *regs, return 0; } -int aes_assemble_image(unsigned char *input, size_t width, size_t height, +void aes_assemble_image(unsigned char *input, size_t width, size_t height, unsigned char *output) { - size_t frame_size = width * height; size_t row, column; for (column = 0; column < width; column++) { diff --git a/libfprint/aeslib.h b/libfprint/aeslib.h index c02f5074..792c6d43 100644 --- a/libfprint/aeslib.h +++ b/libfprint/aeslib.h @@ -27,10 +27,10 @@ struct aes_regwrite { unsigned char value; }; -int aes_write_regv(struct fp_img_dev *dev, struct aes_regwrite *regs, +int aes_write_regv(struct fp_img_dev *dev, const struct aes_regwrite *regs, unsigned int num); -int aes_assemble_image(unsigned char *input, size_t width, size_t height, +void aes_assemble_image(unsigned char *input, size_t width, size_t height, unsigned char *output); #endif diff --git a/libfprint/core.c b/libfprint/core.c index 1a5a1461..47a4e2d3 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -367,7 +367,7 @@ static struct fp_driver *find_supporting_driver(struct usb_device *udev, *usb_id = id; return drv; } - } while (elem = g_slist_next(elem)); + } while ((elem = g_slist_next(elem))); return NULL; } @@ -439,7 +439,7 @@ API_EXPORTED struct fp_dscv_dev **fp_discover_devs(void) int i = 0; do { list[i++] = elem->data; - } while (elem = g_slist_next(elem)); + } while ((elem = g_slist_next(elem))); } list[dscv_count] = NULL; /* NULL-terminate */ @@ -541,7 +541,7 @@ API_EXPORTED struct fp_dscv_dev *fp_dscv_dev_for_print_data(struct fp_dscv_dev * struct fp_dscv_dev *ddev; int i; - for (i = 0; ddev = devs[i]; i++) + for (i = 0; (ddev = devs[i]); i++) if (fp_dscv_dev_supports_print_data(ddev, data)) return ddev; return NULL; @@ -561,7 +561,7 @@ API_EXPORTED struct fp_dscv_dev *fp_dscv_dev_for_dscv_print(struct fp_dscv_dev * struct fp_dscv_dev *ddev; int i; - for (i = 0; ddev = devs[i]; i++) + for (i = 0; (ddev = devs[i]); i++) if (fp_dscv_dev_supports_dscv_print(ddev, print)) return ddev; return NULL; @@ -1138,7 +1138,7 @@ API_EXPORTED void fp_exit(void) do { fp_dbg("naughty app left a device open on exit!"); do_close((struct fp_dev *) elem->data); - } while (elem = g_slist_next(elem)); + } while ((elem = g_slist_next(elem))); g_slist_free(opened_devices); opened_devices = NULL; } diff --git a/libfprint/data.c b/libfprint/data.c index c36f94d2..2027e9c4 100644 --- a/libfprint/data.c +++ b/libfprint/data.c @@ -477,7 +477,7 @@ static GSList *scan_dev_store_dir(char *devpath, uint16_t driver_id, return list; } - while (ent = g_dir_read_name(dir)) { + while ((ent = g_dir_read_name(dir))) { /* ent is an 1 hex character fp_finger code */ guint64 val; enum fp_finger finger; @@ -518,7 +518,7 @@ static GSList *scan_driver_store_dir(char *drvpath, uint16_t driver_id, return list; } - while (ent = g_dir_read_name(dir)) { + while ((ent = g_dir_read_name(dir))) { /* ent is an 8 hex character devtype */ guint64 val; uint32_t devtype; @@ -571,7 +571,7 @@ API_EXPORTED struct fp_dscv_print **fp_discover_prints(void) return NULL; } - while (ent = g_dir_read_name(dir)) { + while ((ent = g_dir_read_name(dir))) { /* ent is a 4 hex digit driver_id */ gchar *endptr; gchar *path; @@ -620,7 +620,7 @@ API_EXPORTED void fp_dscv_prints_free(struct fp_dscv_print **prints) if (!prints) return; - for (i = 0; print = prints[i]; i++) { + for (i = 0; (print = prints[i]); i++) { if (print) g_free(print->path); g_free(print); diff --git a/libfprint/drivers/upektc.c b/libfprint/drivers/upektc.c index 92aeffa8..16df00ad 100644 --- a/libfprint/drivers/upektc.c +++ b/libfprint/drivers/upektc.c @@ -36,7 +36,7 @@ typedef int sint32; typedef unsigned int uint32; /** scan command */ -static const sint8 anScanCommand[ 0x40 ] = { +static const unsigned char anScanCommand[ 0x40 ] = { 0x0e, 0x00, 0x03, 0xa8, 0x00, 0xb6, 0xbb, 0xbb, 0xb8, 0xb7, 0xb8, 0xb5, 0xb8, 0xb9, 0xb8, 0xb9, 0xbb, 0xbb, 0xbe, 0xbb, 0x4e, 0x16, 0xf4, 0x77, @@ -48,7 +48,7 @@ static const sint8 anScanCommand[ 0x40 ] = { }; /** init command */ -static const sint8 anInitCommand[ 0x40 ] = { +static const unsigned char anInitCommand[ 0x40 ] = { 0x03, 0x00, 0x00, 0x00, 0x02, 0xfb, 0x0f, 0x00, 0xc4, 0xf9, 0x2f, 0x01, 0x6d, 0x4f, 0x01, 0x10, 0x44, 0xf9, 0x2f, 0x01, 0x40, 0x00, 0x00, 0x00, @@ -67,7 +67,7 @@ static const sint8 anInitCommand[ 0x40 ] = { * \param pnBuffer buffer pointer we want to store the read buffer * \return error code */ -static sint32 askScanner( struct fp_img_dev *dev, sint8 *pnRawString, sint32 nLen, sint8 *pnBuffer ) { +static sint32 askScanner( struct fp_img_dev *dev, const unsigned char *pnRawString, sint32 nLen, sint8 *pnBuffer ) { sint8 anBuf[ 65535 ]; sint32 nRet; @@ -357,7 +357,6 @@ static int capture( struct fp_img_dev *dev, gboolean unconditional, struct fp_im nRet = -1; } -end: g_free( pnData ); return nRet; diff --git a/libfprint/img.c b/libfprint/img.c index 80fd6e4e..da831d5b 100644 --- a/libfprint/img.c +++ b/libfprint/img.c @@ -372,7 +372,7 @@ int fpi_img_compare_print_data_to_gallery(struct fp_print_data *print, int probe_len = bozorth_probe_init(pstruct); size_t i = 0; - while (gallery_print = gallery[i++]) { + while ((gallery_print = gallery[i++])) { struct xyt_struct *gstruct = (struct xyt_struct *) gallery_print->data; int r = bozorth_to_gallery(probe_len, pstruct, gstruct); if (r >= match_threshold) { From 6f456f399d99c49c48d28441d471a55c1d94081a Mon Sep 17 00:00:00 2001 From: Gustavo Chain Date: Thu, 27 Dec 2007 01:09:32 +0000 Subject: [PATCH 091/184] Add Secugen FDU2000 driver [dsd@gentoo.org: some trivial changes: fixed some warnings fixed fp_img memory leak on error renamed endpoint constants (calling a bulk endpoint 'ctrl' is confusing, as a control endpoint is something different) ] --- libfprint/Makefile.am | 3 +- libfprint/core.c | 1 + libfprint/drivers/fdu2000.c | 311 ++++++++++++++++++++++++++++++++++++ libfprint/fp_internal.h | 1 + 4 files changed, 315 insertions(+), 1 deletion(-) create mode 100644 libfprint/drivers/fdu2000.c diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 933ec690..fe6db4aa 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -6,8 +6,9 @@ URU4000_SRC = drivers/uru4000.c AES1610_SRC = drivers/aes1610.c AES2501_SRC = drivers/aes2501.c drivers/aes2501.h AES4000_SRC = drivers/aes4000.c +FDU2000_SRC = drivers/fdu2000.c -DRIVER_SRC = $(UPEKTS_SRC) $(URU4000_SRC) $(AES1610_SRC) $(AES2501_SRC) $(AES4000_SRC) $(UPEKTC_SRC) +DRIVER_SRC = $(UPEKTS_SRC) $(URU4000_SRC) $(AES1610_SRC) $(AES2501_SRC) $(AES4000_SRC) $(UPEKTC_SRC) $(FDU2000_SRC) NBIS_SRC = \ nbis/include/bozorth.h \ diff --git a/libfprint/core.c b/libfprint/core.c index 47a4e2d3..490bdc41 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -334,6 +334,7 @@ static struct fp_img_driver * const img_drivers[] = { &aes2501_driver, &aes4000_driver, &upektc_driver, + &fdu2000_driver, }; static void register_drivers(void) diff --git a/libfprint/drivers/fdu2000.c b/libfprint/drivers/fdu2000.c new file mode 100644 index 00000000..f9ef85b6 --- /dev/null +++ b/libfprint/drivers/fdu2000.c @@ -0,0 +1,311 @@ +/* + * Secugen FDU2000 driver for libfprint + * Copyright (C) 2007 Gustavo Chain + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include +#include + +#include + +#define FP_COMPONENT "fdu2000" +#include + +#ifndef HAVE_MEMMEM +gpointer +memmem(const gpointer haystack, size_t haystack_len, const gpointer needle, size_t needle_len) { + const gchar *begin; + const char *const last_possible = (const char *) haystack + haystack_len - needle_len; + + /* The first occurrence of the empty string is deemed to occur at + * the beginning of the string. */ + if (needle_len == 0) + return (void *) haystack; + + /* Sanity check, otherwise the loop might search through the whole + * memory. */ + if (haystack_len < needle_len) + return NULL; + + for (begin = (const char *) haystack; begin <= last_possible; ++begin) + if (begin[0] == ((const char *) needle)[0] && + !memcmp((const void *) &begin[1], + (const void *) ((const char *) needle + 1), + needle_len - 1)) + return (void *) begin; + + return NULL; +} +#endif /* HAVE_MEMMEM */ + +#define EP_IMAGE ( 0x02 | USB_ENDPOINT_IN ) +#define EP_REPLY ( 0x01 | USB_ENDPOINT_IN ) +#define EP_CMD ( 0x01 | USB_ENDPOINT_OUT ) +#define BULK_TIMEOUT 200 + +/* fdu_req[] index */ +typedef enum { + CAPTURE_READY, + CAPTURE_READ, + CAPTURE_END, + LED_OFF, + LED_ON +} req_index; + + +#define CMD_LEN 2 +#define ACK_LEN 8 +static const struct fdu2000_req { + const gchar cmd[CMD_LEN]; // Command to send + const gchar ack[ACK_LEN]; // Expected ACK + const guint ack_len; // ACK has variable length +} fdu_req[] = { + /* Capture */ + { + .cmd = { 0x00, 0x04 }, + .ack = { 0x00, 0x04, 0x01, 0x01 }, + .ack_len = 4 + }, + + { + .cmd = { 0x00, 0x01 }, + .ack = { 0x00, 0x01, 0x01, 0x01 }, + .ack_len = 4 + }, + + { + .cmd = { 0x00, 0x05 }, + .ack = { 0x00, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 }, + .ack_len = 8 + }, + + /* Led */ + { + .cmd = { 0x05, 0x00 }, + .ack = {}, + .ack_len = 0 + }, + + { + .cmd = { 0x05, 0x01 }, + .ack = {}, + .ack_len = 0 + } +}; + +/* + * Write a command and verify reponse + */ +static gint +bulk_write_safe(usb_dev_handle *dev, req_index rIndex) { + + gchar reponse[ACK_LEN]; + gint r; + gchar *cmd = (gchar *)fdu_req[rIndex].cmd; + gchar *ack = (gchar *)fdu_req[rIndex].ack; + gint ack_len = fdu_req[rIndex].ack_len; + + r = usb_bulk_write(dev, EP_CMD, cmd, sizeof(cmd), BULK_TIMEOUT); + if (r < 0) + return r; + + if (ack_len == 0) + return 0; + + /* Check reply from FP */ + r = usb_bulk_read (dev, EP_REPLY, + reponse, sizeof(reponse), BULK_TIMEOUT); + if (r < 0) + return r; + + if (!strncmp(ack, reponse, ack_len)) + return 0; + + fp_err("Expected different ACK from dev"); + return 1; /* Error */ +} + +static gint +capture(struct fp_img_dev *dev, gboolean unconditional, + struct fp_img **ret) +{ +#define RAW_IMAGE_WIDTH 398 +#define RAW_IMAGE_HEIGTH 301 +#define RAW_IMAGE_SIZE (RAW_IMAGE_WIDTH * RAW_IMAGE_HEIGTH) + + struct fp_img *img = NULL; + guint bytes, r; + const gchar SOF[] = { 0x0f, 0x0f, 0x0f, 0x0f, 0x00, 0x00, 0x0c, 0x07 }; // Start of frame + const gchar SOL[] = { 0x0f, 0x0f, 0x0f, 0x0f, 0x00, 0x00, 0x0b, 0x06 }; // Start of line + { L L } (L: Line num) (8 nibbles) + gchar *buffer; + gchar *image; + gchar *p; + guint offset; + + buffer = g_malloc0(RAW_IMAGE_SIZE * 6); + image = g_malloc0(RAW_IMAGE_SIZE); + + if ((r = bulk_write_safe(dev->udev, LED_ON))) { + fp_err("Command: LED_ON"); + goto out; + } + + if ((r = bulk_write_safe(dev->udev, CAPTURE_READY))) { + fp_err("Command: CAPTURE_READY"); + goto out; + } + +read: + if ((r = bulk_write_safe(dev->udev, CAPTURE_READ))) { + fp_err("Command: CAPTURE_READ"); + goto out; + } + + /* Now we are ready to read from dev */ + + bytes = usb_bulk_read(dev->udev, + EP_IMAGE, + buffer, RAW_IMAGE_SIZE * 6, + BULK_TIMEOUT * 10); + + if (bytes < 1) + goto read; + + /* + * Find SOF (start of line) + */ + p = memmem(buffer, RAW_IMAGE_SIZE * 6, + (const gpointer)SOF, sizeof SOF); + fp_dbg("Read %d byte/s from dev", bytes); + if (!p) + goto out; + + p += sizeof SOF; + + int i = 0; + bytes = 0; + while(p) { + if ( i >= RAW_IMAGE_HEIGTH ) + break; + + offset = p - buffer; + p = memmem(p, (RAW_IMAGE_SIZE * 6) - (offset), + (const gpointer)SOL, sizeof SOL); + if (p) { + p += sizeof SOL + 4; + int j; + for (j = 0; j < RAW_IMAGE_WIDTH; j++) { + /** + * Convert from 4 to 8 bits + * The SECUGEN-FDU2000 has 4 lines of data, so we need to join 2 bytes into 1 + */ + *(image + bytes + j) = *(p + (j * 2) + 0) << 4 & 0xf0; + *(image + bytes + j) |= *(p + (j * 2) + 1) & 0x0f; + } + p += RAW_IMAGE_WIDTH * 2; + bytes += RAW_IMAGE_WIDTH; + i++; + } + } + + if ((r = bulk_write_safe(dev->udev, CAPTURE_END))) { + fp_err("Command: CAPTURE_END"); + goto out; + } + + if ((r = bulk_write_safe(dev->udev, LED_OFF))) { + fp_err("Command: LED_OFF"); + goto out; + } + + img = fpi_img_new_for_imgdev(dev); + memcpy(img->data, image, RAW_IMAGE_SIZE); + img->flags = FP_IMG_COLORS_INVERTED | FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED; + *ret = img; + +out: + g_free(buffer); + g_free(image); + + return r; +} + +static +gint dev_init(struct fp_img_dev *dev, unsigned long driver_data) +{ + gint r; + if ( (r = usb_set_configuration(dev->udev, 1)) < 0 ) + goto out; + + if ( (r = usb_claim_interface(dev->udev, 0)) < 0 ) + goto out; + + if ( (r = usb_set_altinterface(dev->udev, 1)) < 0 ) + goto out; + + if ( (r = usb_clear_halt(dev->udev, EP_CMD)) < 0 ) + goto out; + + /* Make sure sensor mode is not capture_{ready|read} */ + if ((r = bulk_write_safe(dev->udev, CAPTURE_END))) { + fp_err("Command: CAPTURE_END"); + goto out; + } + + if ((r = bulk_write_safe(dev->udev, LED_OFF))) { + fp_err("Command: LED_OFF"); + goto out; + } + + return 0; + +out: + fp_err("could not init dev"); + fp_err(usb_strerror()); + return r; +} + +static +void dev_exit(struct fp_img_dev *dev) +{ + if (bulk_write_safe(dev->udev, CAPTURE_END)) + fp_err("Command: CAPTURE_END"); + + usb_release_interface(dev->udev, 0); +} + +static const struct usb_id id_table[] = { + { .vendor = 0x1162, .product = 0x0300 }, + { 0, 0, 0, }, +}; + +struct fp_img_driver fdu2000_driver = { + .driver = { + .id = 7, + .name = FP_COMPONENT, + .full_name = "Secugen FDU 2000", + .id_table = id_table, + }, + .img_height = RAW_IMAGE_HEIGTH, + .img_width = RAW_IMAGE_WIDTH, + .bz3_threshold = 23, + + .init = dev_init, + .exit = dev_exit, + .capture = capture, +}; diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 96b82a9a..da8e763a 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -145,6 +145,7 @@ extern struct fp_img_driver uru4000_driver; extern struct fp_img_driver aes1610_driver; extern struct fp_img_driver aes2501_driver; extern struct fp_img_driver aes4000_driver; +extern struct fp_img_driver fdu2000_driver; void fpi_img_driver_setup(struct fp_img_driver *idriver); From bf7093d6077131031e89e447082c4f21352aa46d Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Wed, 30 Jan 2008 14:16:35 +0000 Subject: [PATCH 092/184] Port to libusb-0.9.0 (synchronous I/O) Straightforward port to libusb-0.9.0 sync I/O functions, to give libusb-1.0 a bit of a test drive and to create a reference point for later. --- configure.ac | 2 +- libfprint/aeslib.c | 15 +++- libfprint/core.c | 33 ++++---- libfprint/data.c | 1 + libfprint/drivers/aes1610.c | 20 +++-- libfprint/drivers/aes2501.c | 20 +++-- libfprint/drivers/aes4000.c | 20 +++-- libfprint/drivers/fdu2000.c | 63 +++++++++------- libfprint/drivers/upektc.c | 29 ++++--- libfprint/drivers/upekts.c | 55 ++++++++++---- libfprint/drivers/uru4000.c | 146 +++++++++++++++++++++++++----------- libfprint/fp_internal.h | 8 +- 12 files changed, 274 insertions(+), 138 deletions(-) diff --git a/configure.ac b/configure.ac index fb128cdf..c6fa8287 100644 --- a/configure.ac +++ b/configure.ac @@ -17,7 +17,7 @@ AC_SUBST(lt_major) AC_SUBST(lt_revision) AC_SUBST(lt_age) -PKG_CHECK_MODULES(LIBUSB, "libusb") +PKG_CHECK_MODULES(LIBUSB, [libusb-1.0 = 0.9.0]) AC_SUBST(LIBUSB_CFLAGS) AC_SUBST(LIBUSB_LIBS) diff --git a/libfprint/aeslib.c b/libfprint/aeslib.c index f6d8dfb4..9b22043a 100644 --- a/libfprint/aeslib.c +++ b/libfprint/aeslib.c @@ -21,6 +21,7 @@ #include +#include #include #include "fp_internal.h" @@ -29,8 +30,8 @@ #define MAX_REGWRITES_PER_REQUEST 16 #define BULK_TIMEOUT 4000 -#define EP_IN (1 | USB_ENDPOINT_IN) -#define EP_OUT (2 | USB_ENDPOINT_OUT) +#define EP_IN (1 | LIBUSB_ENDPOINT_IN) +#define EP_OUT (2 | LIBUSB_ENDPOINT_OUT) static int do_write_regv(struct fp_img_dev *dev, const struct aes_regwrite *regs, unsigned int num) @@ -40,18 +41,24 @@ static int do_write_regv(struct fp_img_dev *dev, unsigned int i; size_t offset = 0; int r; + int transferred; + struct libusb_bulk_transfer msg = { + .endpoint = EP_OUT, + .data = data, + .length = alloc_size, + }; for (i = 0; i < num; i++) { data[offset++] = regs[i].reg; data[offset++] = regs[i].value; } - r = usb_bulk_write(dev->udev, EP_OUT, data, alloc_size, BULK_TIMEOUT); + r = libusb_bulk_transfer(dev->udev, &msg, &transferred, BULK_TIMEOUT); g_free(data); if (r < 0) { fp_err("bulk write error %d", r); return r; - } else if ((unsigned int) r < alloc_size) { + } else if ((unsigned int) transferred < alloc_size) { fp_err("unexpected short write %d/%d", r, alloc_size); return -EIO; } diff --git a/libfprint/core.c b/libfprint/core.c index 490bdc41..aeef6df1 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -22,7 +22,7 @@ #include #include -#include +#include #include "fp_internal.h" @@ -351,18 +351,18 @@ static void register_drivers(void) } } -static struct fp_driver *find_supporting_driver(struct usb_device *udev, +static struct fp_driver *find_supporting_driver(libusb_dev *udev, const struct usb_id **usb_id) { GSList *elem = registered_drivers; + struct libusb_dev_descriptor *dsc = libusb_dev_get_descriptor(udev); do { struct fp_driver *drv = elem->data; const struct usb_id *id; for (id = drv->id_table; id->vendor; id++) - if (udev->descriptor.idVendor == id->vendor && - udev->descriptor.idProduct == id->product) { + if (dsc->idVendor == id->vendor && dsc->idProduct == id->product) { fp_dbg("driver %s supports USB device %04x:%04x", drv->name, id->vendor, id->product); *usb_id = id; @@ -372,7 +372,7 @@ static struct fp_driver *find_supporting_driver(struct usb_device *udev, return NULL; } -static struct fp_dscv_dev *discover_dev(struct usb_device *udev) +static struct fp_dscv_dev *discover_dev(libusb_dev *udev) { const struct usb_id *usb_id; struct fp_driver *drv = find_supporting_driver(udev, &usb_id); @@ -408,23 +408,20 @@ API_EXPORTED struct fp_dscv_dev **fp_discover_devs(void) { GSList *tmplist = NULL; struct fp_dscv_dev **list; - struct usb_device *udev; - struct usb_bus *bus; + struct libusb_dev *udev; int dscv_count = 0; if (registered_drivers == NULL) return NULL; - usb_find_busses(); - usb_find_devices(); + libusb_find_devices(); /* Check each device against each driver, temporarily storing successfully * discovered devices in a GSList. * * Quite inefficient but excusable as we'll only be dealing with small * sets of drivers against small sets of USB devices */ - for (bus = usb_get_busses(); bus; bus = bus->next) - for (udev = bus->devices; udev; udev = udev->next) { + for (udev = libusb_get_devices(); udev; udev = libusb_dev_next(udev)) { struct fp_dscv_dev *ddev = discover_dev(udev); if (!ddev) continue; @@ -581,7 +578,7 @@ API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) struct fp_driver *drv = ddev->drv; int r; - usb_dev_handle *udevh = usb_open(ddev->udev); + libusb_dev_handle *udevh = libusb_open(ddev->udev); if (!udevh) { fp_err("usb_open failed"); return NULL; @@ -596,7 +593,7 @@ API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) r = drv->init(dev, ddev->driver_data); if (r) { fp_err("device initialisation failed, driver=%s", drv->name); - usb_close(udevh); + libusb_close(udevh); g_free(dev); return NULL; } @@ -612,7 +609,7 @@ static void do_close(struct fp_dev *dev) { if (dev->drv->exit) dev->drv->exit(dev); - usb_close(dev->udev); + libusb_close(dev->udev); g_free(dev); } @@ -1119,8 +1116,13 @@ API_EXPORTED int fp_identify_finger_img(struct fp_dev *dev, */ API_EXPORTED int fp_init(void) { + int r; fp_dbg(""); - usb_init(); + + r = libusb_init(); + if (r < 0) + return r; + register_drivers(); return 0; } @@ -1147,5 +1149,6 @@ API_EXPORTED void fp_exit(void) fpi_data_exit(); g_slist_free(registered_drivers); registered_drivers = NULL; + libusb_exit(); } diff --git a/libfprint/data.c b/libfprint/data.c index 2027e9c4..61dc8059 100644 --- a/libfprint/data.c +++ b/libfprint/data.c @@ -19,6 +19,7 @@ #include #include +#include #include #include #include diff --git a/libfprint/drivers/aes1610.c b/libfprint/drivers/aes1610.c index eb71a4b9..7ef5fe27 100644 --- a/libfprint/drivers/aes1610.c +++ b/libfprint/drivers/aes1610.c @@ -27,14 +27,14 @@ #include #include -#include +#include #include #include /* FIXME these need checking */ -#define EP_IN (1 | USB_ENDPOINT_IN) -#define EP_OUT (2 | USB_ENDPOINT_OUT) +#define EP_IN (1 | LIBUSB_ENDPOINT_IN) +#define EP_OUT (2 | LIBUSB_ENDPOINT_OUT) #define BULK_TIMEOUT 4000 @@ -63,13 +63,19 @@ static int read_data(struct fp_img_dev *dev, unsigned char *data, size_t len) { int r; + int transferred; + struct libusb_bulk_transfer msg = { + .endpoint = EP_IN, + .data = data, + .length = len, + }; fp_dbg("len=%zd", len); - r = usb_bulk_read(dev->udev, EP_IN, data, len, BULK_TIMEOUT); + r = libusb_bulk_transfer(dev->udev, &msg, &transferred, BULK_TIMEOUT); if (r < 0) { fp_err("bulk read error %d", r); return r; - } else if (r < (int) len) { + } else if (transferred < len) { fp_err("unexpected short read %d/%zd", r, len); return -EIO; } @@ -88,7 +94,7 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) { int r; - r = usb_claim_interface(dev->udev, 0); + r = libusb_claim_interface(dev->udev, 0); if (r < 0) { fp_err("could not claim interface 0"); return r; @@ -107,7 +113,7 @@ static int do_exit(struct fp_img_dev *dev) static void dev_exit(struct fp_img_dev *dev) { do_exit(dev); - usb_release_interface(dev->udev, 0); + libusb_release_interface(dev->udev, 0); } static const struct aes_regwrite finger_det_reqs[] = { diff --git a/libfprint/drivers/aes2501.c b/libfprint/drivers/aes2501.c index ff7cd107..26a6e54a 100644 --- a/libfprint/drivers/aes2501.c +++ b/libfprint/drivers/aes2501.c @@ -26,15 +26,15 @@ #include #include -#include +#include #include #include #include "aes2501.h" /* FIXME these need checking */ -#define EP_IN (1 | USB_ENDPOINT_IN) -#define EP_OUT (2 | USB_ENDPOINT_OUT) +#define EP_IN (1 | LIBUSB_ENDPOINT_IN) +#define EP_OUT (2 | LIBUSB_ENDPOINT_OUT) #define BULK_TIMEOUT 4000 @@ -60,13 +60,19 @@ static int read_data(struct fp_img_dev *dev, unsigned char *data, size_t len) { int r; + int transferred; + struct libusb_bulk_transfer msg = { + .endpoint = EP_IN, + .data = data, + .length = len, + }; fp_dbg("len=%zd", len); - r = usb_bulk_read(dev->udev, EP_IN, data, len, BULK_TIMEOUT); + r = libusb_bulk_transfer(dev->udev, &msg, &transferred, BULK_TIMEOUT); if (r < 0) { fp_err("bulk read error %d", r); return r; - } else if (r < len) { + } else if (transferred < len) { fp_err("unexpected short read %d/%zd", r, len); return -EIO; } @@ -232,7 +238,7 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) { int r; - r = usb_claim_interface(dev->udev, 0); + r = libusb_claim_interface(dev->udev, 0); if (r < 0) { fp_err("could not claim interface 0"); return r; @@ -245,7 +251,7 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) static void dev_exit(struct fp_img_dev *dev) { - usb_release_interface(dev->udev, 0); + libusb_release_interface(dev->udev, 0); } static const struct aes_regwrite finger_det_reqs[] = { diff --git a/libfprint/drivers/aes4000.c b/libfprint/drivers/aes4000.c index f2c737f9..7e1ad88a 100644 --- a/libfprint/drivers/aes4000.c +++ b/libfprint/drivers/aes4000.c @@ -22,14 +22,14 @@ #include #include -#include +#include #include #include #define CTRL_TIMEOUT 1000 -#define EP_IN (1 | USB_ENDPOINT_IN) -#define EP_OUT (2 | USB_ENDPOINT_OUT) +#define EP_IN (1 | LIBUSB_ENDPOINT_IN) +#define EP_OUT (2 | LIBUSB_ENDPOINT_OUT) #define DATA_BUFLEN 0x1259 #define NR_SUBARRAYS 6 #define SUBARRAY_LEN 768 @@ -114,9 +114,14 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, { int i; int r; + int transferred; struct fp_img *img; unsigned char *data; unsigned char *ptr; + struct libusb_bulk_transfer msg = { + .endpoint = EP_IN, + .length = DATA_BUFLEN, + }; r = aes_write_regv(dev, init_reqs, G_N_ELEMENTS(init_reqs)); if (r < 0) @@ -125,18 +130,19 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, img = fpi_img_new_for_imgdev(dev); data = g_malloc(DATA_BUFLEN); ptr = data; + msg.data = data; /* See the timeout explanation in the uru4000 driver for the reasoning * behind this silly loop. */ retry: - r = usb_bulk_read(dev->udev, EP_IN, data, DATA_BUFLEN, 1000); + r = libusb_bulk_transfer(dev->udev, &msg, &transferred, 1000); if (r == -ETIMEDOUT) goto retry; if (r < 0) { fp_err("data read failed, error %d", r); goto err; - } else if (r < DATA_BUFLEN) { + } else if (transferred < DATA_BUFLEN) { fp_err("short data read (%d)", r); r = -EIO; goto err; @@ -163,7 +169,7 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) { int r; - r = usb_claim_interface(dev->udev, 0); + r = libusb_claim_interface(dev->udev, 0); if (r < 0) { fp_err("could not claim interface 0"); return r; @@ -174,7 +180,7 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) static void dev_exit(struct fp_img_dev *dev) { - usb_release_interface(dev->udev, 0); + libusb_release_interface(dev->udev, 0); } static const struct usb_id id_table[] = { diff --git a/libfprint/drivers/fdu2000.c b/libfprint/drivers/fdu2000.c index f9ef85b6..0e6c53b1 100644 --- a/libfprint/drivers/fdu2000.c +++ b/libfprint/drivers/fdu2000.c @@ -21,7 +21,7 @@ #include #include -#include +#include #define FP_COMPONENT "fdu2000" #include @@ -53,9 +53,9 @@ memmem(const gpointer haystack, size_t haystack_len, const gpointer needle, size } #endif /* HAVE_MEMMEM */ -#define EP_IMAGE ( 0x02 | USB_ENDPOINT_IN ) -#define EP_REPLY ( 0x01 | USB_ENDPOINT_IN ) -#define EP_CMD ( 0x01 | USB_ENDPOINT_OUT ) +#define EP_IMAGE ( 0x02 | LIBUSB_ENDPOINT_IN ) +#define EP_REPLY ( 0x01 | LIBUSB_ENDPOINT_IN ) +#define EP_CMD ( 0x01 | LIBUSB_ENDPOINT_OUT ) #define BULK_TIMEOUT 200 /* fdu_req[] index */ @@ -112,15 +112,26 @@ static const struct fdu2000_req { * Write a command and verify reponse */ static gint -bulk_write_safe(usb_dev_handle *dev, req_index rIndex) { +bulk_write_safe(libusb_dev_handle *dev, req_index rIndex) { gchar reponse[ACK_LEN]; gint r; gchar *cmd = (gchar *)fdu_req[rIndex].cmd; gchar *ack = (gchar *)fdu_req[rIndex].ack; gint ack_len = fdu_req[rIndex].ack_len; + struct libusb_bulk_transfer wrmsg = { + .endpoint = EP_CMD, + .data = cmd, + .length = sizeof(cmd), + }; + struct libusb_bulk_transfer readmsg = { + .endpoint = EP_REPLY, + .data = reponse, + .length = sizeof(reponse), + }; + int trf; - r = usb_bulk_write(dev, EP_CMD, cmd, sizeof(cmd), BULK_TIMEOUT); + r = libusb_bulk_transfer(dev, &wrmsg, &trf, BULK_TIMEOUT); if (r < 0) return r; @@ -128,8 +139,7 @@ bulk_write_safe(usb_dev_handle *dev, req_index rIndex) { return 0; /* Check reply from FP */ - r = usb_bulk_read (dev, EP_REPLY, - reponse, sizeof(reponse), BULK_TIMEOUT); + r = libusb_bulk_transfer(dev, &readmsg, &trf, BULK_TIMEOUT); if (r < 0) return r; @@ -149,15 +159,19 @@ capture(struct fp_img_dev *dev, gboolean unconditional, #define RAW_IMAGE_SIZE (RAW_IMAGE_WIDTH * RAW_IMAGE_HEIGTH) struct fp_img *img = NULL; - guint bytes, r; + int bytes, r; const gchar SOF[] = { 0x0f, 0x0f, 0x0f, 0x0f, 0x00, 0x00, 0x0c, 0x07 }; // Start of frame const gchar SOL[] = { 0x0f, 0x0f, 0x0f, 0x0f, 0x00, 0x00, 0x0b, 0x06 }; // Start of line + { L L } (L: Line num) (8 nibbles) - gchar *buffer; + gchar *buffer = g_malloc0(RAW_IMAGE_SIZE * 6); gchar *image; gchar *p; guint offset; + struct libusb_bulk_transfer msg = { + .endpoint = EP_IMAGE, + .data = buffer, + .length = RAW_IMAGE_SIZE * 6, + }; - buffer = g_malloc0(RAW_IMAGE_SIZE * 6); image = g_malloc0(RAW_IMAGE_SIZE); if ((r = bulk_write_safe(dev->udev, LED_ON))) { @@ -178,12 +192,8 @@ read: /* Now we are ready to read from dev */ - bytes = usb_bulk_read(dev->udev, - EP_IMAGE, - buffer, RAW_IMAGE_SIZE * 6, - BULK_TIMEOUT * 10); - - if (bytes < 1) + r = libusb_bulk_transfer(dev->udev, &msg, &bytes, BULK_TIMEOUT * 10); + if (r < 0 || bytes < 1) goto read; /* @@ -249,17 +259,17 @@ static gint dev_init(struct fp_img_dev *dev, unsigned long driver_data) { gint r; - if ( (r = usb_set_configuration(dev->udev, 1)) < 0 ) + //if ( (r = usb_set_configuration(dev->udev, 1)) < 0 ) + // goto out; + + if ( (r = libusb_claim_interface(dev->udev, 0)) < 0 ) goto out; - if ( (r = usb_claim_interface(dev->udev, 0)) < 0 ) - goto out; + //if ( (r = usb_set_altinterface(dev->udev, 1)) < 0 ) + // goto out; - if ( (r = usb_set_altinterface(dev->udev, 1)) < 0 ) - goto out; - - if ( (r = usb_clear_halt(dev->udev, EP_CMD)) < 0 ) - goto out; + //if ( (r = usb_clear_halt(dev->udev, EP_CMD)) < 0 ) + // goto out; /* Make sure sensor mode is not capture_{ready|read} */ if ((r = bulk_write_safe(dev->udev, CAPTURE_END))) { @@ -276,7 +286,6 @@ gint dev_init(struct fp_img_dev *dev, unsigned long driver_data) out: fp_err("could not init dev"); - fp_err(usb_strerror()); return r; } @@ -286,7 +295,7 @@ void dev_exit(struct fp_img_dev *dev) if (bulk_write_safe(dev->udev, CAPTURE_END)) fp_err("Command: CAPTURE_END"); - usb_release_interface(dev->udev, 0); + libusb_release_interface(dev->udev, 0); } static const struct usb_id id_table[] = { diff --git a/libfprint/drivers/upektc.c b/libfprint/drivers/upektc.c index 16df00ad..1723287a 100644 --- a/libfprint/drivers/upektc.c +++ b/libfprint/drivers/upektc.c @@ -23,7 +23,7 @@ #include #include -#include +#include #include @@ -70,9 +70,20 @@ static const unsigned char anInitCommand[ 0x40 ] = { static sint32 askScanner( struct fp_img_dev *dev, const unsigned char *pnRawString, sint32 nLen, sint8 *pnBuffer ) { sint8 anBuf[ 65535 ]; sint32 nRet; + int transferred; + struct libusb_bulk_transfer msg1 = { + .endpoint = 3, + .data = pnRawString, + .length = 0x40, + }; + struct libusb_bulk_transfer msg2 = { + .endpoint = 0x82, + .data = anBuf, + .length = nLen, + }; - nRet = usb_bulk_write( dev -> udev, 0x00000003, pnRawString, 0x40, 1003 ); - if ( nRet != 0x40 ) { + nRet = libusb_bulk_transfer(dev->udev, &msg1, &transferred, 1003); + if (transferred != 0x40) { return -1; } @@ -80,10 +91,10 @@ static sint32 askScanner( struct fp_img_dev *dev, const unsigned char *pnRawStri return 0; } - nRet = usb_bulk_read( dev -> udev, 0x00000082, anBuf, nLen, 1003 ); - if ( ( nRet == nLen ) && ( pnBuffer != NULL ) ) { + nRet = libusb_bulk_transfer(dev->udev, &msg2, &transferred, 1003); + if ( ( transferred == nLen ) && ( pnBuffer != NULL ) ) { memcpy( pnBuffer, anBuf, nLen ); - return nRet; + return transferred; } return nRet; @@ -114,7 +125,7 @@ static sint32 ValidScan( sint8 *pnImage ) { * \return error code */ static sint32 SetupSensor( struct fp_img_dev *dev ) { - usb_claim_interface( dev -> udev, 0 ); + libusb_claim_interface(dev->udev, 0); /* setup sensor */ if ( askScanner( dev, "\x03\x00\x00\x00\x02\xfe\x00\x01\xc0\xbd\xf0\xff\xff\xff\xff\xff\x00\xf0\xfd\x7f\x00\x60\xfd\x7f\x14\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x10\x00\x00\x00\xcc\xf8\x2f\x01\x09\x48\xe7\x77\xf0\xfa\x2f\x01\x09\x48\xe7\x77\xe0\x3a\xe6\x77", 0x00, NULL ) < 0 ) { @@ -365,7 +376,7 @@ static int capture( struct fp_img_dev *dev, gboolean unconditional, struct fp_im static int dev_init( struct fp_img_dev *dev, unsigned long driver_data ) { int nResult; - nResult = usb_claim_interface( dev -> udev, 0 ); + nResult = libusb_claim_interface(dev->udev, 0); if ( nResult < 0 ) { fp_err( "could not claim interface 0" ); return nResult; @@ -377,7 +388,7 @@ static int dev_init( struct fp_img_dev *dev, unsigned long driver_data ) { } static void dev_exit( struct fp_img_dev *dev ) { - usb_release_interface( dev -> udev, 0 ); + libusb_release_interface(dev->udev, 0); } static const struct usb_id id_table[] = { diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index 8b8ce08f..caf5f6fb 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -31,12 +31,12 @@ #include #include -#include +#include #include -#define EP_IN (1 | USB_ENDPOINT_IN) -#define EP_OUT (2 | USB_ENDPOINT_OUT) +#define EP_IN (1 | LIBUSB_ENDPOINT_IN) +#define EP_OUT (2 | LIBUSB_ENDPOINT_OUT) #define TIMEOUT 5000 struct upekts_dev { @@ -131,6 +131,7 @@ static int send_cmd(struct fp_dev *dev, unsigned char seq_a, unsigned char seq_b, unsigned char *data, uint16_t len) { int r; + int transferred; uint16_t crc; /* 9 bytes extra for: 4 byte 'Ciao', 1 byte A, 1 byte B | lenHI, @@ -138,6 +139,11 @@ static int send_cmd(struct fp_dev *dev, unsigned char seq_a, size_t urblen = len + 9; unsigned char *buf; + struct libusb_bulk_transfer msg = { + .endpoint = EP_OUT, + .length = urblen, + }; + if (!data && len > 0) { fp_err("len>0 but no data?"); return -EINVAL; @@ -161,12 +167,13 @@ static int send_cmd(struct fp_dev *dev, unsigned char seq_a, buf[urblen - 2] = crc >> 8; buf[urblen - 1] = crc & 0xff; - r = usb_bulk_write(dev->udev, EP_OUT, buf, urblen, TIMEOUT); + msg.data = buf; + r = libusb_bulk_transfer(dev->udev, &msg, &transferred, TIMEOUT); g_free(buf); if (r < 0) { fp_err("cmd write failed, code %d", r); return r; - } else if ((unsigned int) r < urblen) { + } else if ((unsigned int) transferred < urblen) { fp_err("cmd write too short (%d/%d)", r, urblen); return -EIO; } @@ -217,12 +224,19 @@ static unsigned char *__read_msg(struct fp_dev *dev, size_t *data_len) uint16_t computed_crc, msg_crc; uint16_t len; int r; + int transferred; - r = usb_bulk_read(dev->udev, EP_IN, buf, buf_size, TIMEOUT); + struct libusb_bulk_transfer msg = { + .endpoint = EP_IN, + .data = buf, + .length = buf_size, + }; + + r = libusb_bulk_transfer(dev->udev, &msg, &transferred, TIMEOUT); if (r < 0) { fp_err("msg read failed, code %d", r); goto err; - } else if (r < 9) { + } else if (transferred < 9) { fp_err("msg read too short (%d/%d)", r, buf_size); goto err; } @@ -247,14 +261,19 @@ static unsigned char *__read_msg(struct fp_dev *dev, size_t *data_len) * to read the remainder. This is handled below. */ if (len > MAX_DATA_IN_READ_BUF) { int needed = len - MAX_DATA_IN_READ_BUF; + struct libusb_bulk_transfer extend_msg = { + .endpoint = EP_IN, + .length = needed, + }; + fp_dbg("didn't fit in buffer, need to extend by %d bytes", needed); buf = g_realloc((gpointer) buf, MSG_READ_BUF_SIZE + needed); - r = usb_bulk_read(dev->udev, EP_IN, buf + MSG_READ_BUF_SIZE, needed, - TIMEOUT); + extend_msg.data = buf + MSG_READ_BUF_SIZE; + r = libusb_bulk_transfer(dev->udev, &extend_msg, &transferred, TIMEOUT); if (r < 0) { fp_err("extended msg read failed, code %d", r); goto err; - } else if (r < needed) { + } else if (transferred < needed) { fp_err("extended msg short read (%d/%d)", r, needed); goto err; } @@ -427,8 +446,16 @@ static int do_init(struct fp_dev *dev) uint8_t seq; int r; - r = usb_control_msg(dev->udev, USB_TYPE_VENDOR | USB_RECIP_DEVICE, - 0x0c, 0x100, 0x400, &dummy, sizeof(dummy), TIMEOUT); + struct libusb_control_transfer msg = { + .requesttype = LIBUSB_TYPE_VENDOR | LIBUSB_RECIP_DEVICE, + .request = 0x0c, + .value = 0x0100, + .index = 0x0400, + .length = sizeof(dummy), + .data = &dummy, + }; + + r = libusb_control_transfer(dev->udev, &msg, TIMEOUT); if (r < 0) { fp_dbg("control write failed\n"); return r; @@ -528,7 +555,7 @@ static int dev_init(struct fp_dev *dev, unsigned long driver_data) struct upekts_dev *upekdev = NULL; int r; - r = usb_claim_interface(dev->udev, 0); + r = libusb_claim_interface(dev->udev, 0); if (r < 0) return r; @@ -542,7 +569,7 @@ static int dev_init(struct fp_dev *dev, unsigned long driver_data) static void dev_exit(struct fp_dev *dev) { - usb_release_interface(dev->udev, 0); + libusb_release_interface(dev->udev, 0); g_free(dev->priv); } diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index 24698679..955aca0e 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -24,15 +24,15 @@ #include #include -#include +#include #include -#define EP_INTR (1 | USB_ENDPOINT_IN) -#define EP_DATA (2 | USB_ENDPOINT_IN) +#define EP_INTR (1 | LIBUSB_ENDPOINT_IN) +#define EP_DATA (2 | LIBUSB_ENDPOINT_IN) #define USB_RQ 0x04 -#define CTRL_IN (USB_TYPE_VENDOR | USB_ENDPOINT_IN) -#define CTRL_OUT (USB_TYPE_VENDOR | USB_ENDPOINT_OUT) +#define CTRL_IN (LIBUSB_TYPE_VENDOR | LIBUSB_ENDPOINT_IN) +#define CTRL_OUT (LIBUSB_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT) #define CTRL_TIMEOUT 5000 #define BULK_TIMEOUT 5000 #define DATABLK1_RQLEN 0x10000 @@ -156,8 +156,16 @@ static int get_hwstat(struct fp_img_dev *dev, unsigned char *data) /* The windows driver uses a request of 0x0c here. We use 0x04 to be * consistent with every other command we know about. */ - r = usb_control_msg(dev->udev, CTRL_IN, USB_RQ, REG_HWSTAT, 0, - data, 1, CTRL_TIMEOUT); + struct libusb_control_transfer msg = { + .requesttype = CTRL_IN, + .request = USB_RQ, + .value = REG_HWSTAT, + .index = 0, + .length = 1, + .data = data, + }; + + r = libusb_control_transfer(dev->udev, &msg, CTRL_TIMEOUT); if (r < 0) { fp_err("error %d", r); return r; @@ -173,10 +181,17 @@ static int get_hwstat(struct fp_img_dev *dev, unsigned char *data) static int set_hwstat(struct fp_img_dev *dev, unsigned char data) { int r; - fp_dbg("val=%02x", data); + struct libusb_control_transfer msg = { + .requesttype = CTRL_OUT, + .request = USB_RQ, + .value = REG_HWSTAT, + .index = 0, + .length = 1, + .data = &data, + }; - r = usb_control_msg(dev->udev, CTRL_OUT, USB_RQ, REG_HWSTAT, 0, - &data, 1, CTRL_TIMEOUT); + fp_dbg("val=%02x", data); + r = libusb_control_transfer(dev->udev, &msg, CTRL_TIMEOUT); if (r < 0) { fp_err("error %d", r); return r; @@ -191,10 +206,17 @@ static int set_hwstat(struct fp_img_dev *dev, unsigned char data) static int set_mode(struct fp_img_dev *dev, unsigned char mode) { int r; + struct libusb_control_transfer msg = { + .requesttype = CTRL_OUT, + .request = USB_RQ, + .value = REG_MODE, + .index = 0, + .length = 1, + .data = &mode, + }; fp_dbg("%02x", mode); - r = usb_control_msg(dev->udev, CTRL_OUT, USB_RQ, REG_MODE, 0, &mode, 1, - CTRL_TIMEOUT); + r = libusb_control_transfer(dev->udev, &msg, CTRL_TIMEOUT); if (r < 0) { fp_err("error %d", r); return r; @@ -209,11 +231,16 @@ static int set_mode(struct fp_img_dev *dev, unsigned char mode) static int read_challenge(struct fp_img_dev *dev, unsigned char *data) { int r; + struct libusb_control_transfer msg = { + .requesttype = CTRL_IN, + .request = USB_RQ, + .value = REG_CHALLENGE, + .index = 0, + .length = CR_LENGTH, + .data = data, + }; - /* The windows driver uses a request of 0x0c here. We use 0x04 to be - * consistent with every other command we know about. */ - r = usb_control_msg(dev->udev, CTRL_IN, USB_RQ, REG_CHALLENGE, 0, - data, CR_LENGTH, CTRL_TIMEOUT); + r = libusb_control_transfer(dev->udev, &msg, CTRL_TIMEOUT); if (r < 0) { fp_err("error %d", r); return r; @@ -228,9 +255,16 @@ static int read_challenge(struct fp_img_dev *dev, unsigned char *data) static int write_response(struct fp_img_dev *dev, unsigned char *data) { int r; + struct libusb_control_transfer msg = { + .requesttype = CTRL_OUT, + .request = USB_RQ, + .value = REG_RESPONSE, + .index = 0, + .length = CR_LENGTH, + .data = data, + }; - r = usb_control_msg(dev->udev, CTRL_OUT, USB_RQ, REG_RESPONSE, 0, data, - CR_LENGTH, CTRL_TIMEOUT); + r = libusb_control_transfer(dev->udev, &msg, CTRL_TIMEOUT); if (r < 0) { fp_err("error %d", r); return r; @@ -276,6 +310,12 @@ static int get_irq(struct fp_img_dev *dev, unsigned char *buf, int timeout) uint16_t type; int r; int infinite_timeout = 0; + int transferred; + struct libusb_bulk_transfer msg = { + .endpoint = EP_INTR, + .data = buf, + .length = IRQ_LENGTH, + }; if (timeout == 0) { infinite_timeout = 1; @@ -289,7 +329,7 @@ static int get_irq(struct fp_img_dev *dev, unsigned char *buf, int timeout) * See http://thread.gmane.org/gmane.comp.lib.libusb.devel.general/1315 */ retry: - r = usb_interrupt_read(dev->udev, EP_INTR, buf, IRQ_LENGTH, timeout); + r = libusb_interrupt_transfer(dev->udev, &msg, &transferred, timeout); if (r == -ETIMEDOUT && infinite_timeout) goto retry; @@ -297,7 +337,7 @@ retry: if (r != -ETIMEDOUT) fp_err("interrupt read failed, error %d", r); return r; - } else if (r < IRQ_LENGTH) { + } else if (transferred < IRQ_LENGTH) { fp_err("received %d byte IRQ!?", r); return -EIO; } @@ -394,6 +434,16 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, struct fp_img *img; size_t image_size = DATABLK1_RQLEN + DATABLK2_EXPECT - CAPTURE_HDRLEN; int hdr_skip = CAPTURE_HDRLEN; + int transferred; + struct libusb_bulk_transfer msg1 = { + .endpoint = EP_DATA, + .length = DATABLK1_RQLEN, + }; + struct libusb_bulk_transfer msg2 = { + .endpoint = EP_DATA, + .length = DATABLK2_RQLEN, + }; + r = set_mode(dev, MODE_CAPTURE); if (r < 0) @@ -409,24 +459,24 @@ static int capture(struct fp_img_dev *dev, gboolean unconditional, * asked for. */ img = fpi_img_new(DATABLK1_RQLEN + DATABLK2_RQLEN); + msg1.data = img->data; + msg2.data = img->data + DATABLK1_RQLEN; - r = usb_bulk_read(dev->udev, EP_DATA, img->data, DATABLK1_RQLEN, - BULK_TIMEOUT); + r = libusb_bulk_transfer(dev->udev, &msg1, &transferred, BULK_TIMEOUT); if (r < 0) { fp_err("part 1 capture failed, error %d", r); goto err; - } else if (r < DATABLK1_RQLEN) { + } else if (transferred < DATABLK1_RQLEN) { fp_err("part 1 capture too short (%d)", r); r = -EIO; goto err; } - r = usb_bulk_read(dev->udev, EP_DATA, img->data + DATABLK1_RQLEN, - DATABLK2_RQLEN, BULK_TIMEOUT); + r = libusb_bulk_transfer(dev->udev, &msg2, &transferred, BULK_TIMEOUT); if (r < 0) { fp_err("part 2 capture failed, error %d", r); goto err; - } else if (r != DATABLK2_EXPECT) { + } else if (transferred != DATABLK2_EXPECT) { if (r == DATABLK2_EXPECT - CAPTURE_HDRLEN) { /* this is rather odd, but it happens sometimes with my MS * keyboard */ @@ -457,9 +507,16 @@ static int fix_firmware(struct fp_img_dev *dev) uint32_t enc_addr = FIRMWARE_START + urudev->profile->fw_enc_offset; unsigned char val, new; int r; + struct libusb_control_transfer msg = { + .requesttype = 0xc0, + .request = 0x0c, + .value = enc_addr, + .index = 0, + .data = &val, + .length = 1, + }; - r = usb_control_msg(dev->udev, 0xc0, 0x0c, enc_addr, 0, &val, 1, - CTRL_TIMEOUT); + r = libusb_control_transfer(dev->udev, &msg, CTRL_TIMEOUT); if (r < 0) return r; @@ -472,8 +529,11 @@ static int fix_firmware(struct fp_img_dev *dev) if (new == val) return 0; - r = usb_control_msg(dev->udev, 0x40, 0x04, enc_addr, 0, &new, 1, - CTRL_TIMEOUT); + msg.requesttype = 0x40; + msg.request = 0x04; + msg.data = &new; + + r = libusb_control_transfer(dev->udev, &msg, CTRL_TIMEOUT); if (r < 0) return r; @@ -585,18 +645,18 @@ retry: static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) { - struct usb_config_descriptor *config; - struct usb_interface *iface = NULL; - struct usb_interface_descriptor *iface_desc; - struct usb_endpoint_descriptor *ep; + struct libusb_config_descriptor *config; + struct libusb_interface *iface = NULL; + struct libusb_interface_descriptor *iface_desc; + struct libusb_endpoint_descriptor *ep; struct uru4k_dev *urudev; int i; int r; /* Find fingerprint interface */ - config = usb_device(dev->udev)->config; + config = libusb_dev_get_config(libusb_devh_get_dev(dev->udev)); for (i = 0; i < config->bNumInterfaces; i++) { - struct usb_interface *cur_iface = &config->interface[i]; + struct libusb_interface *cur_iface = &config->interface[i]; if (cur_iface->num_altsetting < 1) continue; @@ -624,23 +684,23 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) ep = &iface_desc->endpoint[0]; if (ep->bEndpointAddress != EP_INTR - || (ep->bmAttributes & USB_ENDPOINT_TYPE_MASK) != - USB_ENDPOINT_TYPE_INTERRUPT) { + || (ep->bmAttributes & LIBUSB_ENDPOINT_TYPE_MASK) != + LIBUSB_ENDPOINT_TYPE_INTERRUPT) { fp_err("unrecognised interrupt endpoint"); return -ENODEV; } ep = &iface_desc->endpoint[1]; if (ep->bEndpointAddress != EP_DATA - || (ep->bmAttributes & USB_ENDPOINT_TYPE_MASK) != - USB_ENDPOINT_TYPE_BULK) { + || (ep->bmAttributes & LIBUSB_ENDPOINT_TYPE_MASK) != + LIBUSB_ENDPOINT_TYPE_BULK) { fp_err("unrecognised bulk endpoint"); return -ENODEV; } /* Device looks like a supported reader */ - r = usb_claim_interface(dev->udev, iface_desc->bInterfaceNumber); + r = libusb_claim_interface(dev->udev, iface_desc->bInterfaceNumber); if (r < 0) { fp_err("interface claim failed"); return r; @@ -658,7 +718,7 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) return 0; err: - usb_release_interface(dev->udev, iface_desc->bInterfaceNumber); + libusb_release_interface(dev->udev, iface_desc->bInterfaceNumber); g_free(urudev); return r; } @@ -669,7 +729,7 @@ static void dev_exit(struct fp_img_dev *dev) set_mode(dev, MODE_INIT); set_hwstat(dev, 0x80); - usb_release_interface(dev->udev, urudev->interface); + libusb_release_interface(dev->udev, urudev->interface); g_free(urudev); } diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index da8e763a..b30c15bc 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -24,7 +24,7 @@ #include #include -#include +#include #include @@ -64,7 +64,7 @@ void fpi_log(enum fpi_log_level, const char *component, const char *function, struct fp_dev { struct fp_driver *drv; - usb_dev_handle *udev; + libusb_dev_handle *udev; uint32_t devtype; void *priv; @@ -76,7 +76,7 @@ struct fp_dev { struct fp_img_dev { struct fp_dev *dev; - usb_dev_handle *udev; + libusb_dev_handle *udev; void *priv; }; @@ -153,7 +153,7 @@ void fpi_img_driver_setup(struct fp_img_driver *idriver); container_of((drv), struct fp_img_driver, driver) struct fp_dscv_dev { - struct usb_device *udev; + libusb_dev *udev; struct fp_driver *drv; unsigned long driver_data; uint32_t devtype; From 69760547df424710b9c92e935aebac4107a37e2a Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Wed, 30 Jan 2008 14:17:08 +0000 Subject: [PATCH 093/184] Disable all drivers while internal API is being reworked --- libfprint/Makefile.am | 3 ++- libfprint/core.c | 6 +++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index fe6db4aa..88c3cf36 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -8,7 +8,8 @@ AES2501_SRC = drivers/aes2501.c drivers/aes2501.h AES4000_SRC = drivers/aes4000.c FDU2000_SRC = drivers/fdu2000.c -DRIVER_SRC = $(UPEKTS_SRC) $(URU4000_SRC) $(AES1610_SRC) $(AES2501_SRC) $(AES4000_SRC) $(UPEKTC_SRC) $(FDU2000_SRC) +#DRIVER_SRC = $(UPEKTS_SRC) $(URU4000_SRC) $(AES1610_SRC) $(AES2501_SRC) $(AES4000_SRC) $(UPEKTC_SRC) $(FDU2000_SRC) +DRIVER_SRC = NBIS_SRC = \ nbis/include/bozorth.h \ diff --git a/libfprint/core.c b/libfprint/core.c index aeef6df1..1ac21d5a 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -325,16 +325,16 @@ static void register_driver(struct fp_driver *drv) } static struct fp_driver * const primitive_drivers[] = { - &upekts_driver, + /* &upekts_driver, */ }; static struct fp_img_driver * const img_drivers[] = { - &uru4000_driver, + /* &uru4000_driver, &aes1610_driver, &aes2501_driver, &aes4000_driver, &upektc_driver, - &fdu2000_driver, + &fdu2000_driver, */ }; static void register_drivers(void) From 5b1f6a0df7eb7c8fa84ced7177188a5a1b845e2c Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 4 Feb 2008 10:23:11 +0000 Subject: [PATCH 094/184] Port primitive driver layer to asynchronous model --- libfprint/core.c | 275 ++++++++++++++++++++++------ libfprint/drv.c | 395 ++++++++++++++++++++++++++++++++++++++++ libfprint/fp_internal.h | 128 ++++++++++++- libfprint/imgdev.c | 8 +- 4 files changed, 742 insertions(+), 64 deletions(-) create mode 100644 libfprint/drv.c diff --git a/libfprint/core.c b/libfprint/core.c index 1ac21d5a..fdaa519a 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -1,6 +1,6 @@ /* * Core functions for libfprint - * Copyright (C) 2007 Daniel Drake + * Copyright (C) 2007-2008 Daniel Drake * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -325,7 +325,6 @@ static void register_driver(struct fp_driver *drv) } static struct fp_driver * const primitive_drivers[] = { - /* &upekts_driver, */ }; static struct fp_img_driver * const img_drivers[] = { @@ -578,6 +577,7 @@ API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) struct fp_driver *drv = ddev->drv; int r; + fp_dbg(""); libusb_dev_handle *udevh = libusb_open(ddev->udev); if (!udevh) { fp_err("usb_open failed"); @@ -588,27 +588,43 @@ API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) dev->drv = drv; dev->udev = udevh; dev->__enroll_stage = -1; + dev->state = DEV_STATE_INITIALIZING; - if (drv->init) { - r = drv->init(dev, ddev->driver_data); - if (r) { - fp_err("device initialisation failed, driver=%s", drv->name); - libusb_close(udevh); - g_free(dev); - return NULL; - } + r = fpi_drv_init(dev, ddev->driver_data); + if (r) { + fp_err("device initialisation failed, driver=%s", drv->name); + goto err; } - fp_dbg(""); + while (dev->state == DEV_STATE_INITIALIZING) + if (libusb_poll() < 0) + goto err_deinit; + if (dev->state != DEV_STATE_INITIALIZED) + goto err_deinit; + opened_devices = g_slist_prepend(opened_devices, (gpointer) dev); return dev; + +err_deinit: + fpi_drv_deinit(dev); + while (dev->state == DEV_STATE_DEINITIALIZING) { + if (libusb_poll() < 0) + break; + } +err: + libusb_close(udevh); + g_free(dev); + return NULL; } /* performs close operation without modifying opened_devices list */ static void do_close(struct fp_dev *dev) { - if (dev->drv->exit) - dev->drv->exit(dev); + fpi_drv_deinit(dev); + while (dev->state == DEV_STATE_DEINITIALIZING) + if (libusb_poll() < 0) + break; + libusb_close(dev->udev); g_free(dev); } @@ -751,7 +767,7 @@ API_EXPORTED int fp_dev_supports_imaging(struct fp_dev *dev) */ API_EXPORTED int fp_dev_supports_identification(struct fp_dev *dev) { - return dev->drv->identify != NULL; + return dev->drv->identify_start != NULL; } /** \ingroup dev @@ -824,6 +840,23 @@ API_EXPORTED int fp_dev_get_img_height(struct fp_dev *dev) return fpi_imgdev_get_img_height(imgdev); } +struct sync_enroll_data { + gboolean populated; + int result; + struct fp_print_data *data; + struct fp_img *img; +}; + +static void sync_enroll_cb(struct fp_dev *dev, int result, + struct fp_print_data *data, struct fp_img *img) +{ + struct sync_enroll_data *edata = dev->enroll_data; + edata->result = result; + edata->data = data; + edata->img = img; + edata->populated = TRUE; +} + /** \ingroup dev * Performs an enroll stage. See \ref enrolling for an explanation of enroll * stages. @@ -881,44 +914,66 @@ API_EXPORTED int fp_enroll_finger_img(struct fp_dev *dev, struct fp_print_data **print_data, struct fp_img **img) { struct fp_driver *drv = dev->drv; - struct fp_img *_img = NULL; - int ret; int stage = dev->__enroll_stage; - gboolean initial = FALSE; + gboolean final = FALSE; + struct sync_enroll_data *edata; + int r; - if (!dev->nr_enroll_stages || !drv->enroll) { + if (!dev->nr_enroll_stages || !drv->enroll_start) { fp_err("driver %s has 0 enroll stages or no enroll func", drv->name); return -ENOTSUP; } if (stage == -1) { - initial = TRUE; - dev->__enroll_stage = ++stage; - } + fp_dbg("starting enrollment"); + r = fpi_drv_enroll_start(dev, sync_enroll_cb); + if (r < 0) { + fp_err("failed to start enrollment"); + return r; + } + while (dev->state == DEV_STATE_ENROLL_STARTING) { + r = libusb_poll(); + if (r < 0) + goto err; + } - if (stage >= dev->nr_enroll_stages) { + if (dev->state != DEV_STATE_ENROLLING) { + r = -EIO; + goto err; + } + + dev->__enroll_stage = ++stage; + dev->enroll_data = g_malloc0(sizeof(struct sync_enroll_data)); + } else if (stage >= dev->nr_enroll_stages) { fp_err("exceeding number of enroll stages for device claimed by " "driver %s (%d stages)", drv->name, dev->nr_enroll_stages); dev->__enroll_stage = -1; - return -EINVAL; + r = -EINVAL; + final = TRUE; + goto out; } - fp_dbg("%s will handle enroll stage %d/%d%s", drv->name, stage, - dev->nr_enroll_stages - 1, initial ? " (initial)" : ""); + fp_dbg("%s will handle enroll stage %d/%d", drv->name, stage, + dev->nr_enroll_stages - 1); - ret = drv->enroll(dev, initial, stage, print_data, &_img); - if (ret < 0) { - fp_err("enroll failed with code %d", ret); - dev->__enroll_stage = -1; - return ret; + edata = dev->enroll_data; + while (!edata->populated) { + r = libusb_poll(); + if (r < 0) { + g_free(edata); + goto err; + } } + edata->populated = FALSE; + if (img) - *img = _img; + *img = edata->img; else - fp_img_free(_img); + fp_img_free(edata->img); - switch (ret) { + r = edata->result; + switch (r) { case FP_ENROLL_PASS: fp_dbg("enroll stage passed"); dev->__enroll_stage = stage + 1; @@ -926,6 +981,8 @@ API_EXPORTED int fp_enroll_finger_img(struct fp_dev *dev, case FP_ENROLL_COMPLETE: fp_dbg("enroll complete"); dev->__enroll_stage = -1; + *print_data = edata->data; + final = TRUE; break; case FP_ENROLL_RETRY: fp_dbg("enroll should retry"); @@ -942,13 +999,49 @@ API_EXPORTED int fp_enroll_finger_img(struct fp_dev *dev, case FP_ENROLL_FAIL: fp_err("enroll failed"); dev->__enroll_stage = -1; + final = TRUE; break; default: - fp_err("unrecognised return code %d", ret); + fp_err("unrecognised return code %d", r); dev->__enroll_stage = -1; - return -EINVAL; + r = -EINVAL; + final = TRUE; + break; } - return ret; + +out: + if (final) { + fp_dbg("ending enrollment"); + if (fpi_drv_enroll_stop(dev) == 0) + while (dev->state == DEV_STATE_ENROLL_STOPPING) { + if (libusb_poll() < 0) + break; + } + g_free(dev->enroll_data); + } + + return r; + +err: + if (fpi_drv_enroll_stop(dev) == 0) + while (dev->state == DEV_STATE_ENROLL_STOPPING) + if (libusb_poll() < 0) + break; + return r; +} + +struct sync_verify_data { + gboolean populated; + int result; + struct fp_img *img; +}; + +static void sync_verify_cb(struct fp_dev *dev, int result, struct fp_img *img) +{ + struct sync_verify_data *vdata = dev->sync_verify_data; + vdata->result = result; + vdata->img = img; + vdata->populated = TRUE; } /** \ingroup dev @@ -970,7 +1063,7 @@ API_EXPORTED int fp_verify_finger_img(struct fp_dev *dev, struct fp_print_data *enrolled_print, struct fp_img **img) { struct fp_driver *drv = dev->drv; - struct fp_img *_img = NULL; + struct sync_verify_data *vdata; int r; if (!enrolled_print) { @@ -978,9 +1071,9 @@ API_EXPORTED int fp_verify_finger_img(struct fp_dev *dev, return -EINVAL; } - if (!drv->verify) { + if (!drv->verify_start) { fp_err("driver %s has no verify func", drv->name); - return -EINVAL; + return -ENOTSUP; } if (!fp_dev_supports_print_data(dev, enrolled_print)) { @@ -989,17 +1082,39 @@ API_EXPORTED int fp_verify_finger_img(struct fp_dev *dev, } fp_dbg("to be handled by %s", drv->name); - r = drv->verify(dev, enrolled_print, &_img); + r = fpi_drv_verify_start(dev, sync_verify_cb, enrolled_print); if (r < 0) { - fp_dbg("verify error %d", r); + fp_dbg("verify_start error %d", r); return r; } + while (dev->state == DEV_STATE_VERIFY_STARTING) { + r = libusb_poll(); + if (r < 0) + goto err; + } + if (dev->state != DEV_STATE_VERIFYING) { + r = -EIO; + goto err; + } + + dev->sync_verify_data = g_malloc0(sizeof(struct sync_verify_data)); + vdata = dev->sync_verify_data; + + while (!vdata->populated) { + r = libusb_poll(); + if (r < 0) { + g_free(vdata); + goto err; + } + } if (img) - *img = _img; + *img = vdata->img; else - fp_img_free(_img); + fp_img_free(vdata->img); + r = vdata->result; + g_free(dev->sync_verify_data); switch (r) { case FP_VERIFY_NO_MATCH: fp_dbg("result: no match"); @@ -1021,12 +1136,38 @@ API_EXPORTED int fp_verify_finger_img(struct fp_dev *dev, break; default: fp_err("unrecognised return code %d", r); - return -EINVAL; + r = -EINVAL; + } + +err: + fp_dbg("ending verification"); + if (fpi_drv_verify_stop(dev) == 0) { + while (dev->state == DEV_STATE_VERIFY_STOPPING) { + if (libusb_poll() < 0) + break; + } } return r; } +struct sync_identify_data { + gboolean populated; + int result; + size_t match_offset; + struct fp_img *img; +}; + +static void sync_identify_cb(struct fp_dev *dev, int result, + size_t match_offset, struct fp_img *img) +{ + struct sync_identify_data *idata = dev->sync_identify_data; + idata->result = result; + idata->match_offset = match_offset; + idata->img = img; + idata->populated = TRUE; +} + /** \ingroup dev * Performs a new scan and attempts to identify the scanned finger against * a collection of previously enrolled fingerprints. @@ -1063,31 +1204,54 @@ API_EXPORTED int fp_identify_finger_img(struct fp_dev *dev, struct fp_img **img) { struct fp_driver *drv = dev->drv; - struct fp_img *_img; + struct sync_identify_data *idata; int r; - if (!drv->identify) { + if (!drv->identify_start) { fp_dbg("driver %s has no identify func", drv->name); return -ENOTSUP; } fp_dbg("to be handled by %s", drv->name); - r = drv->identify(dev, print_gallery, match_offset, &_img); + + r = fpi_drv_identify_start(dev, sync_identify_cb, print_gallery); if (r < 0) { - fp_dbg("identify error %d", r); + fp_err("identify_start error %d", r); return r; } + while (dev->state == DEV_STATE_IDENTIFY_STARTING) { + r = libusb_poll(); + if (r < 0) + goto err; + } + if (dev->state != DEV_STATE_IDENTIFYING) { + r = -EIO; + goto err; + } + + dev->sync_identify_data = g_malloc0(sizeof(struct sync_identify_data)); + idata = dev->sync_identify_data; + + while (!idata->populated) { + r = libusb_poll(); + if (r < 0) { + g_free(idata); + goto err; + } + } if (img) - *img = _img; + *img = idata->img; else - fp_img_free(_img); + fp_img_free(idata->img); + r = idata->result; switch (r) { case FP_VERIFY_NO_MATCH: fp_dbg("result: no match"); break; case FP_VERIFY_MATCH: fp_dbg("result: match at offset %zd", match_offset); + *match_offset = idata->match_offset; break; case FP_VERIFY_RETRY: fp_dbg("verify should retry"); @@ -1103,7 +1267,16 @@ API_EXPORTED int fp_identify_finger_img(struct fp_dev *dev, break; default: fp_err("unrecognised return code %d", r); - return -EINVAL; + r = -EINVAL; + } + g_free(dev->sync_identify_data); + +err: + if (fpi_drv_identify_stop(dev) == 0) { + while (dev->state == DEV_STATE_IDENTIFY_STOPPING) { + if (libusb_poll() < 0) + break; + } } return r; diff --git a/libfprint/drv.c b/libfprint/drv.c new file mode 100644 index 00000000..e45ce788 --- /dev/null +++ b/libfprint/drv.c @@ -0,0 +1,395 @@ +/* + * Functions to assist with asynchronous driver <---> library communications + * Copyright (C) 2007-2008 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include + +#include "fp_internal.h" + +/* Lib-driver: start device initialisation */ +int fpi_drv_init(struct fp_dev *dev, unsigned long driver_data) +{ + struct fp_driver *drv = dev->drv; + if (!drv->init) { + fpi_drvcb_init_complete(dev, 0); + return 0; + } + dev->state = DEV_STATE_INITIALIZING; + return drv->init(dev, driver_data); +} + +/* Driver-lib: device initialisation complete */ +void fpi_drvcb_init_complete(struct fp_dev *dev, int status) +{ + fp_dbg("status %d", status); + BUG_ON(dev->state != DEV_STATE_INITIALIZING); + dev->state = (status) ? DEV_STATE_ERROR : DEV_STATE_INITIALIZED; +} + +/* Lib-driver: start device deinitialisation */ +void fpi_drv_deinit(struct fp_dev *dev) +{ + struct fp_driver *drv = dev->drv; + if (!drv->deinit) { + fpi_drvcb_deinit_complete(dev); + return; + } + + dev->state = DEV_STATE_DEINITIALIZING; + drv->deinit(dev); +} + +/* Driver-lib: device deinitialisation complete */ +void fpi_drvcb_deinit_complete(struct fp_dev *dev) +{ + fp_dbg(""); + BUG_ON(dev->state != DEV_STATE_DEINITIALIZING); + dev->state = DEV_STATE_DEINITIALIZED; +} + +/* Lib-driver: start enrollment */ +int fpi_drv_enroll_start(struct fp_dev *dev, fp_enroll_stage_cb callback) +{ + struct fp_driver *drv = dev->drv; + int r; + if (!drv->enroll_start) + return -ENOTSUP; + dev->state = DEV_STATE_ENROLL_STARTING; + dev->enroll_cb = callback; + r = drv->enroll_start(dev); + if (r < 0) { + dev->enroll_cb = NULL; + dev->state = DEV_STATE_ERROR; + } + return r; +} + +/* Driver-lib: enrollment has now started, expect results soon */ +void fpi_drvcb_enroll_started(struct fp_dev *dev, int status) +{ + fp_dbg("status %d", status); + BUG_ON(dev->state != DEV_STATE_ENROLL_STARTING); + dev->state = (status) ? DEV_STATE_ERROR : DEV_STATE_ENROLLING; +} + +/* Driver-lib: an enroll stage has completed */ +void fpi_drvcb_enroll_stage_completed(struct fp_dev *dev, int result, + struct fp_print_data *data, struct fp_img *img) +{ + BUG_ON(dev->state != DEV_STATE_ENROLLING); + fp_dbg("result %d", result); + if (!dev->enroll_cb) { + fp_dbg("ignoring enroll result as no callback is subscribed"); + return; + } + if (result == FP_ENROLL_COMPLETE && !data) { + fp_err("BUG: complete but no data?"); + result = FP_ENROLL_FAIL; + } + dev->enroll_cb(dev, result, data, img); +} + +/* Lib-driver: stop enrollment */ +int fpi_drv_enroll_stop(struct fp_dev *dev) +{ + struct fp_driver *drv = dev->drv; + dev->enroll_cb = NULL; + + if (!drv->enroll_start) + return -ENOTSUP; + if (!drv->enroll_stop) { + dev->state = DEV_STATE_INITIALIZED; + return 0; + } + + dev->state = DEV_STATE_ENROLL_STOPPING; + return drv->enroll_stop(dev); +} + +/* Driver-lib: enrollment has stopped */ +void fpi_drvcb_enroll_stopped(struct fp_dev *dev) +{ + fp_dbg(""); + BUG_ON(dev->state != DEV_STATE_ENROLL_STOPPING); + dev->state = DEV_STATE_INITIALIZED; +} + +/* Lib-driver: start verification */ +int fpi_drv_verify_start(struct fp_dev *dev, fp_verify_cb callback, + struct fp_print_data *data) +{ + struct fp_driver *drv = dev->drv; + int r; + + fp_dbg(""); + if (!drv->verify_start) + return -ENOTSUP; + dev->state = DEV_STATE_VERIFY_STARTING; + dev->verify_cb = callback; + dev->verify_data = data; + r = drv->verify_start(dev); + if (r < 0) { + dev->verify_cb = NULL; + dev->state = DEV_STATE_ERROR; + } + return r; +} + +/* Driver-lib: verification has started, expect results soon */ +void fpi_drvcb_verify_started(struct fp_dev *dev, int status) +{ + fp_dbg(""); + BUG_ON(dev->state != DEV_STATE_VERIFY_STARTING); + dev->state = (status) ? DEV_STATE_ERROR : DEV_STATE_VERIFYING; +} + +/* Driver-lib: report a verify result (which might mark completion) */ +void fpi_drvcb_report_verify_result(struct fp_dev *dev, int result, + struct fp_img *img) +{ + fp_dbg("result %d", result); + BUG_ON(dev->state != DEV_STATE_VERIFYING); + if (result < 0 || result == FP_VERIFY_NO_MATCH + || result == FP_VERIFY_MATCH) { + dev->state = DEV_STATE_VERIFY_DONE; + } + + if (!dev->verify_cb) { + fp_dbg("ignoring verify result as no callback is subscribed"); + return; + } + dev->verify_cb(dev, result, img); +} + +/* Lib-driver: stop verification */ +int fpi_drv_verify_stop(struct fp_dev *dev) +{ + struct fp_driver *drv = dev->drv; + gboolean iterating = (dev->state == DEV_STATE_VERIFYING); + + fp_dbg(""); + BUG_ON(dev->state != DEV_STATE_VERIFYING + && dev->state != DEV_STATE_VERIFY_DONE); + dev->verify_cb = NULL; + + if (!drv->verify_start) + return -ENOTSUP; + if (!drv->verify_stop) { + dev->state = DEV_STATE_INITIALIZED; + return 0; + } + + dev->state = DEV_STATE_VERIFY_STOPPING; + return drv->verify_stop(dev, iterating); +} + +/* Driver-lib: verification has stopped */ +void fpi_drvcb_verify_stopped(struct fp_dev *dev) +{ + fp_dbg(""); + BUG_ON(dev->state != DEV_STATE_VERIFY_STOPPING); + dev->state = DEV_STATE_INITIALIZED; +} + + +/* Lib-driver: start identification */ +int fpi_drv_identify_start(struct fp_dev *dev, fp_identify_cb callback, + struct fp_print_data **gallery) +{ + struct fp_driver *drv = dev->drv; + int r; + + fp_dbg(""); + if (!drv->identify_start) + return -ENOTSUP; + dev->state = DEV_STATE_IDENTIFY_STARTING; + dev->identify_cb = callback; + dev->identify_data = gallery; + r = drv->identify_start(dev); + if (r < 0) { + dev->identify_cb = NULL; + dev->state = DEV_STATE_ERROR; + } + return r; +} + +/* Driver-lib: identification has started, expect results soon */ +void fpi_drvcb_identify_started(struct fp_dev *dev, int status) +{ + fp_dbg(""); + BUG_ON(dev->state != DEV_STATE_IDENTIFY_STARTING); + dev->state = (status) ? DEV_STATE_ERROR : DEV_STATE_IDENTIFYING; +} + +/* Driver-lib: report a verify result (which might mark completion) */ +void fpi_drvcb_report_identify_result(struct fp_dev *dev, int result, + size_t match_offset, struct fp_img *img) +{ + fp_dbg("result %d", result); + BUG_ON(dev->state != DEV_STATE_IDENTIFYING); + if (result < 0 || result == FP_VERIFY_NO_MATCH + || result == FP_VERIFY_MATCH) { + dev->state = DEV_STATE_IDENTIFY_DONE; + } + + if (!dev->identify_cb) { + fp_dbg("ignoring verify result as no callback is subscribed"); + return; + } + dev->identify_cb(dev, result, match_offset, img); +} + +/* Lib-driver: stop identification */ +int fpi_drv_identify_stop(struct fp_dev *dev) +{ + struct fp_driver *drv = dev->drv; + gboolean iterating = (dev->state == DEV_STATE_IDENTIFYING); + + fp_dbg(""); + BUG_ON(dev->state != DEV_STATE_IDENTIFYING + && dev->state != DEV_STATE_IDENTIFY_DONE); + dev->identify_cb = NULL; + + if (!drv->identify_start) + return -ENOTSUP; + if (!drv->identify_stop) { + dev->state = DEV_STATE_INITIALIZED; + return 0; + } + + dev->state = DEV_STATE_IDENTIFY_STOPPING; + return drv->identify_stop(dev, iterating); +} + +/* Driver-lib: identification has stopped */ +void fpi_drvcb_identify_stopped(struct fp_dev *dev) +{ + fp_dbg(""); + BUG_ON(dev->state != DEV_STATE_IDENTIFY_STOPPING); + dev->state = DEV_STATE_INITIALIZED; +} + +/* SSM: sequential state machine + * Asynchronous driver design encourages some kind of state machine behind it. + * In most cases, the state machine is entirely linear - you only go to the + * next state, you never jump or go backwards. The SSM functions help you + * implement such a machine. + * + * e.g. S1 --> S2 --> S3 --> S4 + * S1 is the start state + * There is also an implicit error state and an implicit accepting state + * (both with implicit edges from every state). + * + * To create a ssm, you pass a state handler function and the total number of + * states (4 in the above example). + * + * To start a ssm, you pass in a completion callback function which gets + * called when the ssm completes (both on error and on failure). + * + * To iterate to the next state, call fpi_ssm_next_state(). It is legal to + * attempt to iterate beyond the final state - this is equivalent to marking + * the ssm as successfully completed. + * + * To mark successful completion of a SSM, either iterate beyond the final + * state or call fpi_ssm_mark_completed() from any state. + * + * To mark failed completion of a SSM, call fpi_ssm_mark_aborted() from any + * state. You must pass a non-zero error code. + * + * Your state handling function looks at ssm->cur_state in order to determine + * the current state and hence which operations to perform (a switch statement + * is appropriate). + * Typically, the state handling function fires off an asynchronous libusb + * transfer, and the callback function iterates the machine to the next state + * upon success (or aborts the machine on transfer failure). + * + * Your completion callback should examine ssm->error in order to determine + * whether the ssm completed or failed. An error code of zero indicates + * successful completion. + */ + +/* Allocate a new ssm */ +struct fpi_ssm *fpi_ssm_new(struct fp_dev *dev, ssm_handler_fn handler, + int nr_states) +{ + struct fpi_ssm *machine; + BUG_ON(nr_states < 1) + + machine = g_malloc0(sizeof(*machine)); + machine->handler = handler; + machine->nr_states = nr_states; + machine->dev = dev; + machine->completed = TRUE; + return machine; +} + +/* Free a ssm */ +void fpi_ssm_free(struct fpi_ssm *machine) +{ + if (!machine) + return; + g_free(machine); +} + +/* Invoke the state handler */ +static void __ssm_call_handler(struct fpi_ssm *machine) +{ + machine->handler(machine); +} + +/* Start a ssm. You can also restart a completed or aborted ssm. */ +void fpi_ssm_start(struct fpi_ssm *ssm, ssm_completed_fn callback) +{ + BUG_ON(!ssm->completed); + ssm->callback = callback; + ssm->cur_state = 0; + ssm->completed = FALSE; + ssm->error = 0; + __ssm_call_handler(ssm); +} + +/* Mark a ssm as completed successfully. */ +void fpi_ssm_mark_completed(struct fpi_ssm *machine) +{ + BUG_ON(machine->completed); + machine->completed = TRUE; + if (machine->callback) + machine->callback(machine); +} + +/* Mark a ssm as aborted with error. */ +void fpi_ssm_mark_aborted(struct fpi_ssm *machine, int error) +{ + fp_dbg("error %d", error); + BUG_ON(error == 0); + machine->error = error; + fpi_ssm_mark_completed(machine); +} + +/* Iterate to next state of a ssm */ +void fpi_ssm_next_state(struct fpi_ssm *machine) +{ + BUG_ON(machine->completed); + machine->cur_state++; + if (machine->cur_state == machine->nr_states) { + fpi_ssm_mark_completed(machine); + } else { + __ssm_call_handler(machine); + } +} + diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index b30c15bc..63d39cd9 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -1,6 +1,6 @@ /* * Internal/private definitions for libfprint - * Copyright (C) 2007 Daniel Drake + * Copyright (C) 2007-2008 Daniel Drake * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -62,6 +62,42 @@ void fpi_log(enum fpi_log_level, const char *component, const char *function, #define fp_warn(fmt...) _fpi_log(LOG_LEVEL_WARNING, fmt) #define fp_err(fmt...) _fpi_log(LOG_LEVEL_ERROR, fmt) +#ifdef NDEBUG +#define BUG_ON(condition) \ + if ((condition)) fp_err("BUG at %s:%d", __FILE__, __LINE__) +#else +#define BUG_ON(condition) +#endif + +enum fp_dev_state { + DEV_STATE_INITIAL = 0, + DEV_STATE_ERROR, + DEV_STATE_INITIALIZING, + DEV_STATE_INITIALIZED, + DEV_STATE_DEINITIALIZING, + DEV_STATE_DEINITIALIZED, + DEV_STATE_ENROLL_STARTING, + DEV_STATE_ENROLLING, + DEV_STATE_ENROLL_STOPPING, + DEV_STATE_VERIFY_STARTING, + DEV_STATE_VERIFYING, + DEV_STATE_VERIFY_DONE, + DEV_STATE_VERIFY_STOPPING, + DEV_STATE_IDENTIFY_STARTING, + DEV_STATE_IDENTIFYING, + DEV_STATE_IDENTIFY_DONE, + DEV_STATE_IDENTIFY_STOPPING, +}; + +typedef void (*fp_enroll_stage_cb)(struct fp_dev *dev, int result, + struct fp_print_data *data, struct fp_img *img); + +typedef void (*fp_verify_cb)(struct fp_dev *dev, int result, + struct fp_img *img); + +typedef void (*fp_identify_cb)(struct fp_dev *dev, int result, + size_t match_offset, struct fp_img *img); + struct fp_dev { struct fp_driver *drv; libusb_dev_handle *udev; @@ -70,8 +106,21 @@ struct fp_dev { int nr_enroll_stages; - /* drivers should not mess with these */ + /* read-only to drivers */ + struct fp_print_data *verify_data; + + /* drivers should not mess with any of the below */ + enum fp_dev_state state; + + /* FIXME: convert this to generic state operational data mechanism? */ int __enroll_stage; + fp_enroll_stage_cb enroll_cb; + void *enroll_data; + void *sync_verify_data; + fp_verify_cb verify_cb; + void *identify_data; + void *sync_identify_data; + fp_identify_cb identify_cb; }; struct fp_img_dev { @@ -108,13 +157,13 @@ struct fp_driver { /* Device operations */ int (*discover)(const struct usb_id *usb_id, uint32_t *devtype); int (*init)(struct fp_dev *dev, unsigned long driver_data); - void (*exit)(struct fp_dev *dev); - int (*enroll)(struct fp_dev *dev, gboolean initial, int stage, - struct fp_print_data **print_data, struct fp_img **img); - int (*verify)(struct fp_dev *dev, struct fp_print_data *data, - struct fp_img **img); - int (*identify)(struct fp_dev *dev, struct fp_print_data **print_gallery, - size_t *match_offset, struct fp_img **img); + void (*deinit)(struct fp_dev *dev); + int (*enroll_start)(struct fp_dev *dev); + int (*enroll_stop)(struct fp_dev *dev); + int (*verify_start)(struct fp_dev *dev); + int (*verify_stop)(struct fp_dev *dev, gboolean iterating); + int (*identify_start)(struct fp_dev *dev); + int (*identify_stop)(struct fp_dev *dev, gboolean iterating); }; enum fp_print_data_type fpi_driver_get_data_type(struct fp_driver *drv); @@ -230,5 +279,66 @@ int fpi_img_compare_print_data(struct fp_print_data *enrolled_print, int fpi_img_compare_print_data_to_gallery(struct fp_print_data *print, struct fp_print_data **gallery, int match_threshold, int *match_offset); +/* async drv <--> lib comms */ + +struct fpi_ssm; +typedef void (*ssm_completed_fn)(struct fpi_ssm *ssm); +typedef void (*ssm_handler_fn)(struct fpi_ssm *ssm); + +/* sequential state machine: state machine that iterates sequentially over + * a predefined series of states. can be aborted by either completion or + * abortion error conditions. */ +struct fpi_ssm { + struct fp_dev *dev; + void *priv; + int nr_states; + int cur_state; + gboolean completed; + int error; + ssm_completed_fn callback; + ssm_handler_fn handler; +}; + + +/* for library and drivers */ +struct fpi_ssm *fpi_ssm_new(struct fp_dev *dev, ssm_handler_fn handler, + int nr_states); +void fpi_ssm_free(struct fpi_ssm *machine); +void fpi_ssm_start(struct fpi_ssm *machine, ssm_completed_fn callback); +int fpi_ssm_has_completed(struct fpi_ssm *machine); + +/* for drivers */ +void fpi_ssm_next_state(struct fpi_ssm *machine); +void fpi_ssm_mark_completed(struct fpi_ssm *machine); +void fpi_ssm_mark_aborted(struct fpi_ssm *machine, int error); + +int fpi_drv_init(struct fp_dev *dev, unsigned long driver_data); +void fpi_drvcb_init_complete(struct fp_dev *dev, int status); +void fpi_drv_deinit(struct fp_dev *dev); +void fpi_drvcb_deinit_complete(struct fp_dev *dev); + +int fpi_drv_enroll_start(struct fp_dev *dev, fp_enroll_stage_cb callback); +void fpi_drvcb_enroll_started(struct fp_dev *dev, int status); +void fpi_drvcb_enroll_stage_completed(struct fp_dev *dev, int result, + struct fp_print_data *data, struct fp_img *img); +int fpi_drv_enroll_stop(struct fp_dev *dev); +void fpi_drvcb_enroll_stopped(struct fp_dev *dev); + +int fpi_drv_verify_start(struct fp_dev *dev, fp_verify_cb callback, + struct fp_print_data *data); +void fpi_drvcb_verify_started(struct fp_dev *dev, int status); +void fpi_drvcb_report_verify_result(struct fp_dev *dev, int result, + struct fp_img *img); +int fpi_drv_verify_stop(struct fp_dev *dev); +void fpi_drvcb_verify_stopped(struct fp_dev *dev); + +int fpi_drv_identify_start(struct fp_dev *dev, fp_identify_cb callback, + struct fp_print_data **gallery); +void fpi_drvcb_identify_started(struct fp_dev *dev, int status); +void fpi_drvcb_report_identify_result(struct fp_dev *dev, int result, + size_t match_offset, struct fp_img *img); +int fpi_drv_identify_stop(struct fp_dev *dev); +void fpi_drvcb_identify_stopped(struct fp_dev *dev); + #endif diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index 8deb23c0..a511a198 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -349,9 +349,9 @@ void fpi_img_driver_setup(struct fp_img_driver *idriver) { idriver->driver.type = DRIVER_IMAGING; idriver->driver.init = img_dev_init; - idriver->driver.exit = img_dev_exit; - idriver->driver.enroll = img_dev_enroll; - idriver->driver.verify = img_dev_verify; - idriver->driver.identify = img_dev_identify; + //idriver->driver.exit = img_dev_exit; + //idriver->driver.enroll = img_dev_enroll; + //idriver->driver.verify = img_dev_verify; + //idriver->driver.identify = img_dev_identify; } From aeeec97fb2efafdc22d55e505e28c41ff9d117ed Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 4 Feb 2008 10:24:27 +0000 Subject: [PATCH 095/184] upekts: port to asynchronous model --- libfprint/Makefile.am | 5 +- libfprint/core.c | 1 + libfprint/drivers/upekts.c | 1555 ++++++++++++++++++++++++------------ 3 files changed, 1069 insertions(+), 492 deletions(-) diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 88c3cf36..2a8f08e7 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -8,8 +8,8 @@ AES2501_SRC = drivers/aes2501.c drivers/aes2501.h AES4000_SRC = drivers/aes4000.c FDU2000_SRC = drivers/fdu2000.c -#DRIVER_SRC = $(UPEKTS_SRC) $(URU4000_SRC) $(AES1610_SRC) $(AES2501_SRC) $(AES4000_SRC) $(UPEKTC_SRC) $(FDU2000_SRC) -DRIVER_SRC = +DRIVER_SRC = $(UPEKTS_SRC) +#DRIVER_SRC = $(URU4000_SRC) $(AES1610_SRC) $(AES2501_SRC) $(AES4000_SRC) $(UPEKTC_SRC) $(FDU2000_SRC) NBIS_SRC = \ nbis/include/bozorth.h \ @@ -56,6 +56,7 @@ libfprint_la_SOURCES = \ fp_internal.h \ core.c \ data.c \ + drv.c \ img.c \ imgdev.c \ aeslib.c \ diff --git a/libfprint/core.c b/libfprint/core.c index fdaa519a..a7741ad1 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -325,6 +325,7 @@ static void register_driver(struct fp_driver *drv) } static struct fp_driver * const primitive_drivers[] = { + &upekts_driver, }; static struct fp_img_driver * const img_drivers[] = { diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index caf5f6fb..c63f7796 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -1,6 +1,6 @@ /* * UPEK TouchStrip driver for libfprint - * Copyright (C) 2007 Daniel Drake + * Copyright (C) 2007-2008 Daniel Drake * * Based in part on libthinkfinger: * Copyright (C) 2006-2007 Timo Hoenig @@ -39,8 +39,14 @@ #define EP_OUT (2 | LIBUSB_ENDPOINT_OUT) #define TIMEOUT 5000 +#define MSG_READ_BUF_SIZE 0x40 +#define MAX_DATA_IN_READ_BUF (MSG_READ_BUF_SIZE - 9) + struct upekts_dev { - uint8_t seq; + gboolean enroll_passed; + gboolean first_verify_iteration; + gboolean stop_verify; + uint8_t seq; /* FIXME: improve/automate seq handling */ }; static const uint16_t crc_table[256] = { @@ -127,11 +133,10 @@ static uint16_t udf_crc(unsigned char *buffer, size_t size) #define CMD_SEQ_INCREMENT 0x10 -static int send_cmd(struct fp_dev *dev, unsigned char seq_a, - unsigned char seq_b, unsigned char *data, uint16_t len) +static void fill_send_cmd_urb(struct libusb_bulk_transfer *msg, + unsigned char seq_a, unsigned char seq_b, const unsigned char *data, + uint16_t len) { - int r; - int transferred; uint16_t crc; /* 9 bytes extra for: 4 byte 'Ciao', 1 byte A, 1 byte B | lenHI, @@ -139,17 +144,15 @@ static int send_cmd(struct fp_dev *dev, unsigned char seq_a, size_t urblen = len + 9; unsigned char *buf; - struct libusb_bulk_transfer msg = { - .endpoint = EP_OUT, - .length = urblen, - }; - if (!data && len > 0) { fp_err("len>0 but no data?"); - return -EINVAL; + return; } + msg->endpoint = EP_OUT; + msg->length = urblen; buf = g_malloc(urblen); + msg->data = buf; /* Write header */ strncpy(buf, "Ciao", 4); @@ -166,30 +169,17 @@ static int send_cmd(struct fp_dev *dev, unsigned char seq_a, crc = GUINT16_TO_BE(udf_crc(buf + 4, urblen - 6)); buf[urblen - 2] = crc >> 8; buf[urblen - 1] = crc & 0xff; - - msg.data = buf; - r = libusb_bulk_transfer(dev->udev, &msg, &transferred, TIMEOUT); - g_free(buf); - if (r < 0) { - fp_err("cmd write failed, code %d", r); - return r; - } else if ((unsigned int) transferred < urblen) { - fp_err("cmd write too short (%d/%d)", r, urblen); - return -EIO; - } - - return 0; } -static int send_cmd28(struct fp_dev *dev, unsigned char subcmd, - unsigned char *data, uint16_t innerlen) +static void fill_send_cmd28_urb(struct fp_dev *dev, + struct libusb_bulk_transfer *msg, unsigned char subcmd, + const unsigned char *data, uint16_t innerlen) { uint16_t _innerlen = innerlen; size_t len = innerlen + 6; unsigned char *buf = g_malloc0(len); struct upekts_dev *upekdev = dev->priv; uint8_t seq = upekdev->seq + CMD_SEQ_INCREMENT; - int r; fp_dbg("seq=%02x subcmd=%02x with %d bytes of data", seq, subcmd, innerlen); @@ -200,122 +190,88 @@ static int send_cmd28(struct fp_dev *dev, unsigned char subcmd, buf[5] = subcmd; memcpy(buf + 6, data, innerlen); - r = send_cmd(dev, 0, seq, buf, len); - if (r == 0) - upekdev->seq = seq; + fill_send_cmd_urb(msg, 0, seq, buf, len); + upekdev->seq = seq; g_free(buf); - return r; } -static int send_cmdresponse(struct fp_dev *dev, unsigned char seq, - unsigned char *data, uint8_t len) +static void fill_send_cmdresponse_urb(struct libusb_bulk_transfer *msg, + unsigned char seq, const unsigned char *data, uint8_t len) { fp_dbg("seq=%02x len=%d", seq, len); - return send_cmd(dev, seq, 0, data, len); -} - -static unsigned char *__read_msg(struct fp_dev *dev, size_t *data_len) -{ -#define MSG_READ_BUF_SIZE 0x40 -#define MAX_DATA_IN_READ_BUF (MSG_READ_BUF_SIZE - 9) - unsigned char *buf = g_malloc(MSG_READ_BUF_SIZE); - size_t buf_size = MSG_READ_BUF_SIZE; - uint16_t computed_crc, msg_crc; - uint16_t len; - int r; - int transferred; - - struct libusb_bulk_transfer msg = { - .endpoint = EP_IN, - .data = buf, - .length = buf_size, - }; - - r = libusb_bulk_transfer(dev->udev, &msg, &transferred, TIMEOUT); - if (r < 0) { - fp_err("msg read failed, code %d", r); - goto err; - } else if (transferred < 9) { - fp_err("msg read too short (%d/%d)", r, buf_size); - goto err; - } - - if (strncmp(buf, "Ciao", 4) != 0) { - fp_err("no Ciao for you!!"); - goto err; - } - - len = GUINT16_FROM_LE(((buf[5] & 0xf) << 8) | buf[6]); - - if (r != MSG_READ_BUF_SIZE && (len + 9) < r) { - /* Check that the length claimed inside the message is in line with - * the amount of data that was transferred over USB. */ - fp_err("msg didn't include enough data, expected=%d recv=%d", - len + 9, r); - goto err; - } - - /* We use a 64 byte buffer for reading messages. However, sometimes - * messages are longer, in which case we have to do another USB bulk read - * to read the remainder. This is handled below. */ - if (len > MAX_DATA_IN_READ_BUF) { - int needed = len - MAX_DATA_IN_READ_BUF; - struct libusb_bulk_transfer extend_msg = { - .endpoint = EP_IN, - .length = needed, - }; - - fp_dbg("didn't fit in buffer, need to extend by %d bytes", needed); - buf = g_realloc((gpointer) buf, MSG_READ_BUF_SIZE + needed); - extend_msg.data = buf + MSG_READ_BUF_SIZE; - r = libusb_bulk_transfer(dev->udev, &extend_msg, &transferred, TIMEOUT); - if (r < 0) { - fp_err("extended msg read failed, code %d", r); - goto err; - } else if (transferred < needed) { - fp_err("extended msg short read (%d/%d)", r, needed); - goto err; - } - buf_size += needed; - } - - computed_crc = udf_crc(buf + 4, len + 3); - msg_crc = GUINT16_FROM_LE((buf[len + 8] << 8) | buf[len + 7]); - if (computed_crc != msg_crc) { - fp_err("CRC failed, got %04x expected %04x", msg_crc, computed_crc); - goto err; - } - - *data_len = buf_size; - return buf; -err: - g_free(buf); - return NULL; + fill_send_cmd_urb(msg, seq, 0, data, len); } enum read_msg_status { - READ_MSG_ERROR = -1, - READ_MSG_CMD = 1, - READ_MSG_RESPONSE = 2, + READ_MSG_ERROR, + READ_MSG_CMD, + READ_MSG_RESPONSE, }; -static enum read_msg_status read_msg(struct fp_dev *dev, uint8_t *seq, - unsigned char *subcmd, unsigned char **data, size_t *data_len) -{ -#define MSG_READ_BUF_SIZE 0x40 -#define MAX_DATA_IN_READ_BUF (MSG_READ_BUF_SIZE - 9) - unsigned char *buf; - size_t buf_size; - unsigned char code_a; - unsigned char code_b; - uint16_t len; - enum read_msg_status ret = READ_MSG_ERROR; +typedef void (*read_msg_cb_fn)(struct fp_dev *dev, enum read_msg_status status, + uint8_t seq, unsigned char subcmd, unsigned char *data, size_t data_len, + void *user_data); -retry: - buf = __read_msg(dev, &buf_size); - if (!buf) - return READ_MSG_ERROR; +struct read_msg_data { + struct fp_dev *dev; + read_msg_cb_fn callback; + void *user_data; +}; + +static int __read_msg_async(struct read_msg_data *udata); + +#define READ_MSG_DATA_CB_ERR(udata) (udata)->callback((udata)->dev, \ + READ_MSG_ERROR, 0, 0, NULL, 0, (udata)->user_data) + +static void busy_ack_sent_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, + enum libusb_urb_cb_status status, unsigned char endpoint, int rqlength, + unsigned char *data, int actual_length, void *_data) +{ + struct read_msg_data *udata = (struct read_msg_data *) _data; + if (status != FP_URB_COMPLETED || rqlength != actual_length) { + READ_MSG_DATA_CB_ERR(udata); + g_free(udata); + } else { + int r = __read_msg_async(udata); + if (r < 0) { + READ_MSG_DATA_CB_ERR(udata); + g_free(udata); + } + } + libusb_urb_handle_free(urbh); +} + +static int busy_ack_retry_read(struct read_msg_data *udata) +{ + struct libusb_bulk_transfer msg; + libusb_urb_handle *urbh; + + fill_send_cmdresponse_urb(&msg, 0x09, NULL, 0); + urbh = libusb_async_bulk_transfer(udata->dev->udev, &msg, busy_ack_sent_cb, + udata, TIMEOUT); + if (!urbh) { + g_free(msg.data); + return -EIO; + } + return 0; +} + +/* Returns 0 if message was handled, 1 if it was a device-busy message, and + * negative on error. */ +static int __handle_incoming_msg(struct read_msg_data *udata, + unsigned char *buf) +{ + uint16_t len = GUINT16_FROM_LE(((buf[5] & 0xf) << 8) | buf[6]); + uint16_t computed_crc = udf_crc(buf + 4, len + 3); + uint16_t msg_crc = GUINT16_FROM_LE((buf[len + 8] << 8) | buf[len + 7]); + unsigned char *retdata = NULL; + unsigned char code_a, code_b; + + if (computed_crc != msg_crc) { + fp_err("CRC failed, got %04x expected %04x", msg_crc, computed_crc); + return -1; + } code_a = buf[4]; code_b = buf[5] & 0xf0; @@ -327,23 +283,19 @@ retry: fp_dbg("cmd %x from device to driver", code_a); if (code_a == 0x08) { + int r; fp_dbg("device busy, send busy-ack"); - send_cmdresponse(dev, 0x09, NULL, 0); - g_free(buf); - goto retry; + r = busy_ack_retry_read(udata); + return (r < 0) ? r : 1; } - if (seq) - *seq = code_a; - if (data) { - if (len > 0) { - unsigned char *tmp = g_malloc(len); - memcpy(tmp, buf + 7, len); - *data = tmp; - } - *data_len = len; + if (len > 0) { + retdata = g_malloc(len); + memcpy(retdata, buf + 7, len); } - ret = READ_MSG_CMD; + udata->callback(udata->dev, READ_MSG_CMD, code_a, 0, retdata, len, + udata->user_data); + g_free(retdata); } else if (!code_a) { /* device sends response to a previously executed command */ unsigned char *innerbuf = buf + 7; @@ -352,70 +304,167 @@ retry: if (len < 6) { fp_err("cmd response too short (%d)", len); - goto out; + return -1; } if (innerbuf[0] != 0x28) { fp_err("cmd response without 28 byte?"); - goto out; + return -1; } if (innerbuf[3] || innerbuf[4]) { fp_err("non-zero bytes in cmd response"); - goto out; + return -1; } innerlen = innerbuf[1] | (innerbuf[2] << 8); innerlen = GUINT16_FROM_LE(innerlen) - 3; _subcmd = innerbuf[5]; fp_dbg("device responds to subcmd %x with %d bytes", _subcmd, innerlen); - if (seq) - *seq = code_b; - if (subcmd) - *subcmd = _subcmd; - if (data) { - if (innerlen > 0) { - unsigned char *tmp = g_malloc(innerlen); - memcpy(tmp, innerbuf + 6, innerlen); - *data = tmp; - } - *data_len = innerlen; + if (innerlen > 0) { + retdata = g_malloc(innerlen); + memcpy(retdata, innerbuf + 6, innerlen); } - ret = READ_MSG_RESPONSE; + udata->callback(udata->dev, READ_MSG_RESPONSE, code_b, _subcmd, + retdata, innerlen, udata->user_data); + g_free(retdata); } else { fp_err("don't know how to handle this message"); + return -1; } - -out: - g_free(buf); - return ret; + return 0; } -static int read_msg28(struct fp_dev *dev, unsigned char subcmd, - unsigned char **data, size_t *data_len) +static void read_msg_extend_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, + enum libusb_urb_cb_status status, unsigned char endpoint, int rqlength, + unsigned char *data, int actual_length, void *user_data) { - struct upekts_dev *upekdev = dev->priv; - uint8_t _seq; - unsigned char _subcmd; - enum read_msg_status msgstat; + struct read_msg_data *udata = user_data; + unsigned char *buf = data - MSG_READ_BUF_SIZE; + int handle_result = 0; - msgstat = read_msg(dev, &_seq, &_subcmd, data, data_len); - if (msgstat != READ_MSG_RESPONSE) { - fp_err("expected response, got %d seq=%x", msgstat, _seq); - return -EPROTO; + if (status != FP_URB_COMPLETED) { + fp_err("extended msg read failed, code %d", status); + goto err; } - if (_subcmd != subcmd) { - fp_warn("expected response to subcmd %02x, got response to %02x", - subcmd, _subcmd); - return -EPROTO; - } - if (_seq != upekdev->seq) { - fp_err("expected response to cmd seq=%02x, got response to %02x", - upekdev->seq, _seq); - return -EPROTO; + if (actual_length < rqlength) { + fp_err("extended msg short read (%d/%d)", actual_length, rqlength); + goto err; } + handle_result = __handle_incoming_msg(udata, buf); + if (handle_result < 0) + goto err; + goto out; + +err: + READ_MSG_DATA_CB_ERR(udata); +out: + if (handle_result != 1) + g_free(udata); + g_free(buf); + libusb_urb_handle_free(urbh); +} + +static void read_msg_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, + enum libusb_urb_cb_status status, unsigned char endpoint, + int rqlength, unsigned char *data, int actual_length, void *user_data) +{ + struct read_msg_data *udata = user_data; + uint16_t len; + int handle_result = 0; + + if (status != FP_URB_COMPLETED) { + fp_err("async msg read failed, code %d", status); + goto err; + } + if (actual_length < 9) { + fp_err("async msg read too short (%d)", actual_length); + goto err; + } + + if (strncmp(data, "Ciao", 4) != 0) { + fp_err("no Ciao for you!!"); + goto err; + } + + len = GUINT16_FROM_LE(((data[5] & 0xf) << 8) | data[6]); + if (actual_length != MSG_READ_BUF_SIZE && (len + 9) > actual_length) { + /* Check that the length claimed inside the message is in line with + * the amount of data that was transferred over USB. */ + fp_err("msg didn't include enough data, expected=%d recv=%d", + len + 9, actual_length); + goto err; + } + + /* We use a 64 byte buffer for reading messages. However, sometimes + * messages are longer, in which case we have to do another USB bulk read + * to read the remainder. This is handled below. */ + if (len > MAX_DATA_IN_READ_BUF) { + int needed = len - MAX_DATA_IN_READ_BUF; + libusb_urb_handle *eurbh; + struct libusb_bulk_transfer extend_msg = { + .endpoint = EP_IN, + .length = needed, + }; + + fp_dbg("didn't fit in buffer, need to extend by %d bytes", needed); + data = g_realloc((gpointer) data, MSG_READ_BUF_SIZE + needed); + extend_msg.data = data + MSG_READ_BUF_SIZE; + eurbh = libusb_async_bulk_transfer(udata->dev->udev, &extend_msg, + read_msg_extend_cb, udata, TIMEOUT); + if (!eurbh) { + fp_err("extended read submission failed"); + goto err; + } + libusb_urb_handle_free(urbh); + return; + } + + handle_result = __handle_incoming_msg(udata, data); + if (handle_result < 0) + goto err; + goto out; + +err: + READ_MSG_DATA_CB_ERR(udata); +out: + libusb_urb_handle_free(urbh); + if (handle_result != 1) + g_free(udata); + g_free(data); +} + +static int __read_msg_async(struct read_msg_data *udata) +{ + unsigned char *buf = g_malloc(MSG_READ_BUF_SIZE); + struct libusb_bulk_transfer msg = { + .endpoint = EP_IN, + .data = buf, + .length = MSG_READ_BUF_SIZE, + }; + libusb_urb_handle *urbh = libusb_async_bulk_transfer(udata->dev->udev, &msg, + read_msg_cb, udata, TIMEOUT); + if (!urbh) { + g_free(buf); + return -EIO; + } return 0; } +static int read_msg_async(struct fp_dev *dev, read_msg_cb_fn callback, + void *user_data) +{ + struct read_msg_data *udata = g_malloc(sizeof(*udata)); + int r; + + udata->dev = dev; + udata->callback = callback; + udata->user_data = user_data; + r = __read_msg_async(udata); + if (r) + g_free(udata); + return r; +} + static const unsigned char init_resp03[] = { 0x01, 0x00, 0xe8, 0x03, 0x00, 0x00, 0xff, 0x07 }; @@ -439,115 +488,342 @@ static const unsigned char init28_0b[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00 }; -static int do_init(struct fp_dev *dev) +/* device initialisation state machine */ + +enum initsm_states { + WRITE_CTRL400 = 0, + READ_MSG03, + SEND_RESP03, + READ_MSG05, + SEND28_06, + READ28_06, + SEND28_07, + READ28_07, + SEND28_08, + READ28_08, + SEND28_0C, + READ28_0C, + SEND28_0B, + READ28_0B, + INITSM_NUM_STATES, +}; + +static void initsm_read_msg_response_cb(struct fpi_ssm *ssm, + enum read_msg_status status, uint8_t seq, + unsigned char expect_subcmd, unsigned char subcmd) { - enum read_msg_status msgstat; - unsigned char dummy = 0x10; - uint8_t seq; - int r; + struct fp_dev *dev = ssm->dev; + struct upekts_dev *upekdev = dev->priv; - struct libusb_control_transfer msg = { - .requesttype = LIBUSB_TYPE_VENDOR | LIBUSB_RECIP_DEVICE, - .request = 0x0c, - .value = 0x0100, - .index = 0x0400, - .length = sizeof(dummy), - .data = &dummy, - }; - - r = libusb_control_transfer(dev->udev, &msg, TIMEOUT); - if (r < 0) { - fp_dbg("control write failed\n"); - return r; + if (status != READ_MSG_RESPONSE) { + fp_err("expected response, got %d seq=%x in state %d", status, seq, + ssm->cur_state); + fpi_ssm_mark_aborted(ssm, -1); + } else if (subcmd != expect_subcmd) { + fp_warn("expected response to subcmd 0x%02x, got response to %02x in " + "state %d", expect_subcmd, subcmd, ssm->cur_state); + fpi_ssm_mark_aborted(ssm, -1); + } else if (seq != upekdev->seq) { + fp_err("expected response to cmd seq=%02x, got response to %02x " + "in state %d", upekdev->seq, seq, ssm->cur_state); + fpi_ssm_mark_aborted(ssm, -1); + } else { + fp_dbg("state %d completed", ssm->cur_state); + fpi_ssm_next_state(ssm); } - - msgstat = read_msg(dev, &seq, NULL, NULL, NULL); - if (msgstat != READ_MSG_CMD) { - fp_err("expected command, got %d seq=%x", msgstat, seq); - return -EPROTO; - } - if (seq != 3) { - fp_err("expected seq=3, got %x", seq); - return -EPROTO; - } - - r = send_cmdresponse(dev, ++seq, (unsigned char *) init_resp03, - sizeof(init_resp03)); - if (r < 0) - return r; - - msgstat = read_msg(dev, &seq, NULL, NULL, NULL); - if (msgstat != READ_MSG_CMD) { - fp_err("expected command, got %d seq=%x", msgstat, seq); - return -EPROTO; - } - if (seq != 5) { - fp_err("expected seq=5, got %x", seq); - return -EPROTO; - } - - dummy = 0x04; - r = send_cmd28(dev, 0x06, &dummy, 1); - if (r < 0) - return r; - if (read_msg28(dev, 0x06, NULL, NULL) < 0) - return r; - - dummy = 0x04; - r = send_cmd28(dev, 0x07, &dummy, 1); - if (r < 0) - return r; - if (read_msg28(dev, 0x07, NULL, NULL) < 0) - return r; - - r = send_cmd28(dev, 0x08, (unsigned char *) init28_08, - sizeof(init28_08)); - if (r < 0) - return r; - if (read_msg28(dev, 0x08, NULL, NULL) < 0) - return r; - - r = send_cmd28(dev, 0x0c, (unsigned char *) init28_0c, - sizeof(init28_0c)); - if (r < 0) - return r; - if (read_msg28(dev, 0x0c, NULL, NULL) < 0) - return r; - - r = send_cmd28(dev, 0x0b, (unsigned char *) init28_0b, - sizeof(init28_0b)); - if (r < 0) - return r; - if (read_msg28(dev, 0x0b, NULL, NULL) < 0) - return r; - - return 0; } -static int do_deinit(struct fp_dev *dev) +static void read28_0b_cb(struct fp_dev *dev, enum read_msg_status status, + uint8_t seq, unsigned char subcmd, unsigned char *data, size_t data_len, + void *user_data) { - unsigned char dummy = 0; - enum read_msg_status msgstat; - uint8_t seq; - int r; + initsm_read_msg_response_cb((struct fpi_ssm *) user_data, status, seq, + 0x0b, subcmd); +} - /* FIXME: either i've misunderstood the message system or this is illegal - * here, since we arent responding to anything. */ - r = send_cmdresponse(dev, 0x07, &dummy, 1); - if (r < 0) - return r; - - msgstat = read_msg(dev, &seq, NULL, NULL, NULL); - if (msgstat != READ_MSG_CMD) { - fp_err("expected command, got %d seq=%x", msgstat, seq); - return -EPROTO; +static void read28_0c_cb(struct fp_dev *dev, enum read_msg_status status, + uint8_t seq, unsigned char subcmd, unsigned char *data, size_t data_len, + void *user_data) +{ + initsm_read_msg_response_cb((struct fpi_ssm *) user_data, status, seq, + 0x0c, subcmd); +} + +static void read28_08_cb(struct fp_dev *dev, enum read_msg_status status, + uint8_t seq, unsigned char subcmd, unsigned char *data, size_t data_len, + void *user_data) +{ + initsm_read_msg_response_cb((struct fpi_ssm *) user_data, status, seq, + 0x08, subcmd); +} + +static void read28_07_cb(struct fp_dev *dev, enum read_msg_status status, + uint8_t seq, unsigned char subcmd, unsigned char *data, size_t data_len, + void *user_data) +{ + initsm_read_msg_response_cb((struct fpi_ssm *) user_data, status, seq, + 0x07, subcmd); +} + +static void read28_06_cb(struct fp_dev *dev, enum read_msg_status status, + uint8_t seq, unsigned char subcmd, unsigned char *data, size_t data_len, + void *user_data) +{ + initsm_read_msg_response_cb((struct fpi_ssm *) user_data, status, seq, + 0x06, subcmd); +} + +static void initsm_read_msg_cmd_cb(struct fpi_ssm *ssm, + enum read_msg_status status, uint8_t expect_seq, uint8_t seq) +{ + struct fp_dev *dev = ssm->dev; + struct upekts_dev *upekdev = dev->priv; + + if (status == READ_MSG_ERROR) { + fpi_ssm_mark_aborted(ssm, -1); + return; + } else if (status != READ_MSG_CMD) { + fp_err("expected command, got %d seq=%x in state %d", status, seq, + ssm->cur_state); + fpi_ssm_mark_aborted(ssm, -1); + return; } + upekdev->seq = seq; + if (seq != expect_seq) { + fp_err("expected seq=%x, got %x in state %d", expect_seq, seq, + ssm->cur_state); + fpi_ssm_mark_aborted(ssm, -1); + return; + } + + fpi_ssm_next_state(ssm); +} + +static void read_msg05_cb(struct fp_dev *dev, enum read_msg_status status, + uint8_t seq, unsigned char subcmd, unsigned char *data, size_t data_len, + void *user_data) +{ + initsm_read_msg_cmd_cb((struct fpi_ssm *) user_data, status, 5, seq); +} + +static void read_msg03_cb(struct fp_dev *dev, enum read_msg_status status, + uint8_t seq, unsigned char subcmd, unsigned char *data, size_t data_len, + void *user_data) +{ + initsm_read_msg_cmd_cb((struct fpi_ssm *) user_data, status, 3, seq); +} + +static void ctrl400_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, + enum libusb_urb_cb_status status, struct libusb_ctrl_setup *setup, + unsigned char *data, int actual_length, void *user_data) +{ + struct fpi_ssm *ssm = user_data; + if (status == FP_URB_COMPLETED) + fpi_ssm_next_state(ssm); + else + fpi_ssm_mark_aborted(ssm, -1); + libusb_urb_handle_free(urbh); +} + +static void initsm_read_msg_handler(struct fpi_ssm *ssm, + read_msg_cb_fn callback) +{ + int r = read_msg_async(ssm->dev, callback, ssm); + if (r < 0) { + fp_err("async read msg failed in state %d", ssm->cur_state); + fpi_ssm_mark_aborted(ssm, r); + } +} + +static void initsm_send_msg_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, + enum libusb_urb_cb_status status, unsigned char endpoint, + int rqlength, unsigned char *data, int actual_length, void *user_data) +{ + struct fpi_ssm *ssm = user_data; + if (status == FP_URB_COMPLETED && rqlength == actual_length) { + fp_dbg("state %d completed", ssm->cur_state); + fpi_ssm_next_state(ssm); + } else { + fp_err("failed, state=%d rqlength=%d actual_length=%d", ssm->cur_state, + rqlength, actual_length); + fpi_ssm_mark_aborted(ssm, -1); + } + libusb_urb_handle_free(urbh); +} + +static void initsm_send_msg28_handler(struct fpi_ssm *ssm, + unsigned char subcmd, const unsigned char *data, uint16_t innerlen) +{ + struct fp_dev *dev = ssm->dev; + struct libusb_urb_handle *urbh; + struct libusb_bulk_transfer trf; + + fill_send_cmd28_urb(dev, &trf, subcmd, data, innerlen); + urbh = libusb_async_bulk_transfer(dev->udev, &trf, initsm_send_msg_cb, + ssm, TIMEOUT); + if (!urbh) { + fp_err("urb submission failed in state %d", ssm->cur_state); + g_free(trf.data); + fpi_ssm_mark_aborted(ssm, -EIO); + } +} + +static void initsm_run_state(struct fpi_ssm *ssm) +{ + struct fp_dev *dev = ssm->dev; + struct upekts_dev *upekdev = dev->priv; + struct libusb_urb_handle *urbh; + + switch (ssm->cur_state) { + case WRITE_CTRL400: ; + unsigned char dummy = 0x10; + struct libusb_control_transfer ctrl400_trf = { + .requesttype = LIBUSB_TYPE_VENDOR | LIBUSB_RECIP_DEVICE, + .request = 0x0c, + .value = 0x0100, + .index = 0x0400, + .length = sizeof(dummy), + .data = &dummy, + }; + + urbh = libusb_async_control_transfer(ssm->dev->udev, &ctrl400_trf, + ctrl400_cb, ssm, TIMEOUT); + if (!urbh) + fpi_ssm_mark_aborted(ssm, -1); + break; + case READ_MSG03: + initsm_read_msg_handler(ssm, read_msg03_cb); + break; + case SEND_RESP03: ; + struct libusb_bulk_transfer resp03_trf; + + fill_send_cmdresponse_urb(&resp03_trf, ++upekdev->seq, init_resp03, + sizeof(init_resp03)); + urbh = libusb_async_bulk_transfer(dev->udev, &resp03_trf, + initsm_send_msg_cb, ssm, TIMEOUT); + if (!urbh) { + g_free(resp03_trf.data); + fpi_ssm_mark_aborted(ssm, -EIO); + } + break; + case READ_MSG05: + initsm_read_msg_handler(ssm, read_msg05_cb); + break; + case SEND28_06: ; + unsigned char dummy28_06 = 0x04; + upekdev->seq = 0xf0; + initsm_send_msg28_handler(ssm, 0x06, &dummy28_06, 1); + break; + case READ28_06: + initsm_read_msg_handler(ssm, read28_06_cb); + break; + case SEND28_07: ; + unsigned char dummy28_07 = 0x04; + initsm_send_msg28_handler(ssm, 0x07, &dummy28_07, 1); + break; + case READ28_07: + initsm_read_msg_handler(ssm, read28_07_cb); + break; + case SEND28_08: + initsm_send_msg28_handler(ssm, 0x08, init28_08, sizeof(init28_08)); + break; + case READ28_08: + initsm_read_msg_handler(ssm, read28_08_cb); + break; + case SEND28_0C: + initsm_send_msg28_handler(ssm, 0x0c, init28_0c, sizeof(init28_0c)); + break; + case READ28_0C: + initsm_read_msg_handler(ssm, read28_0c_cb); + break; + case SEND28_0B: + initsm_send_msg28_handler(ssm, 0x0b, init28_0b, sizeof(init28_0b)); + break; + case READ28_0B: + initsm_read_msg_handler(ssm, read28_0b_cb); + break; + } +} + +static struct fpi_ssm *initsm_new(struct fp_dev *dev) +{ + return fpi_ssm_new(dev, initsm_run_state, INITSM_NUM_STATES); +} + +enum deinitsm_states { + SEND_RESP07 = 0, + READ_MSG01, + DEINITSM_NUM_STATES, +}; + +static void send_resp07_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, + enum libusb_urb_cb_status status, unsigned char endpoint, + int rqlength, unsigned char *data, int actual_length, void *user_data) +{ + struct fpi_ssm *ssm = user_data; + if (status != FP_URB_COMPLETED) + fpi_ssm_mark_aborted(ssm, -EIO); + else if (rqlength != actual_length) + fpi_ssm_mark_aborted(ssm, -EPROTO); + else + fpi_ssm_next_state(ssm); + libusb_urb_handle_free(urbh); +} + +static void read_msg01_cb(struct fp_dev *dev, enum read_msg_status status, + uint8_t seq, unsigned char subcmd, unsigned char *data, size_t data_len, + void *user_data) +{ + struct fpi_ssm *ssm = user_data; + struct upekts_dev *upekdev = dev->priv; + + if (status == READ_MSG_ERROR) { + fpi_ssm_mark_aborted(ssm, -1); + return; + } else if (status != READ_MSG_CMD) { + fp_err("expected command, got %d seq=%x", status, seq); + fpi_ssm_mark_aborted(ssm, -1); + return; + } + upekdev->seq = seq; if (seq != 1) { fp_err("expected seq=1, got %x", seq); - return -EPROTO; + fpi_ssm_mark_aborted(ssm, -1); + return; } - return 0; + fpi_ssm_next_state(ssm); +} + +static void deinitsm_state_handler(struct fpi_ssm *ssm) +{ + struct fp_dev *dev = ssm->dev; + + switch (ssm->cur_state) { + case SEND_RESP07: ; + struct libusb_bulk_transfer msg; + struct libusb_urb_handle *urbh; + unsigned char dummy = 0; + + fill_send_cmdresponse_urb(&msg, 0x07, &dummy, 1); + urbh = libusb_async_bulk_transfer(dev->udev, &msg, send_resp07_cb, ssm, + TIMEOUT); + if (!urbh) { + g_free(msg.data); + fpi_ssm_mark_aborted(ssm, -EIO); + } + break; + case READ_MSG01: ; + int r = read_msg_async(dev, read_msg01_cb, ssm); + if (r < 0) + fpi_ssm_mark_aborted(ssm, r); + break; + } +} + +static struct fpi_ssm *deinitsm_new(struct fp_dev *dev) +{ + return fpi_ssm_new(dev, deinitsm_state_handler, DEINITSM_NUM_STATES); } static int dev_init(struct fp_dev *dev, unsigned long driver_data) @@ -564,6 +840,7 @@ static int dev_init(struct fp_dev *dev, unsigned long driver_data) dev->priv = upekdev; dev->nr_enroll_stages = 3; + fpi_drvcb_init_complete(dev, 0); return 0; } @@ -571,6 +848,7 @@ static void dev_exit(struct fp_dev *dev) { libusb_release_interface(dev->udev, 0); g_free(dev->priv); + fpi_drvcb_deinit_complete(dev); } static const unsigned char enroll_init[] = { @@ -583,134 +861,296 @@ static const unsigned char scan_comp[] = { /* used for enrollment and verification */ static const unsigned char poll_data[] = { 0x30, 0x01 }; -static int enroll(struct fp_dev *dev, gboolean initial, - int stage, struct fp_print_data **_data, struct fp_img **img) +enum enroll_start_sm_states { + RUN_INITSM = 0, + ENROLL_INIT, + READ_ENROLL_MSG28, + ENROLL_START_NUM_STATES, +}; + +/* Called when the device initialization state machine completes */ +static void enroll_start_sm_cb_initsm(struct fpi_ssm *initsm) { - unsigned char *data; - size_t data_len; - int r; - int result = 0; - int passed = 0; + struct fpi_ssm *enroll_start_ssm = initsm->priv; + int error = initsm->error; - if (initial) { - r = do_init(dev); - if (r < 0) - return r; + fpi_ssm_free(initsm); + if (error) + fpi_ssm_mark_aborted(enroll_start_ssm, error); + else + fpi_ssm_next_state(enroll_start_ssm); +} - r = send_cmd28(dev, 0x02, (unsigned char *) enroll_init, - sizeof(enroll_init)); - if (r < 0) - return r; +/* called when enroll init URB has completed */ +static void enroll_start_sm_cb_init(libusb_dev_handle *devh, + libusb_urb_handle *urbh, enum libusb_urb_cb_status status, + unsigned char endpoint, int rqlength, unsigned char *data, + int actual_length, void *user_data) +{ + struct fpi_ssm *ssm = user_data; + if (status != FP_URB_COMPLETED) + fpi_ssm_mark_aborted(ssm, -EIO); + else if (rqlength != actual_length) + fpi_ssm_mark_aborted(ssm, -EPROTO); + else + fpi_ssm_next_state(ssm); + libusb_urb_handle_free(urbh); +} + +static void enroll_start_sm_cb_msg28(struct fp_dev *dev, + enum read_msg_status status, uint8_t seq, unsigned char subcmd, + unsigned char *data, size_t data_len, void *user_data) +{ + struct upekts_dev *upekdev = dev->priv; + struct fpi_ssm *ssm = user_data; + + if (status != READ_MSG_RESPONSE) { + fp_err("expected response, got %d seq=%x", status, seq); + fpi_ssm_mark_aborted(ssm, -1); + } else if (subcmd != 0) { + fp_warn("expected response to subcmd 0, got response to %02x", + subcmd); + fpi_ssm_mark_aborted(ssm, -1); + } else if (seq != upekdev->seq) { + fp_err("expected response to cmd seq=%02x, got response to %02x", + upekdev->seq, seq); + fpi_ssm_mark_aborted(ssm, -1); + } else { + fpi_ssm_next_state(ssm); + } +} + +static void enroll_start_sm_run_state(struct fpi_ssm *ssm) +{ + struct fp_dev *dev = ssm->dev; + + switch (ssm->cur_state) { + case RUN_INITSM: ; + struct fpi_ssm *initsm = initsm_new(dev); + initsm->priv = ssm; + fpi_ssm_start(initsm, enroll_start_sm_cb_initsm); + break; + case ENROLL_INIT: ; + struct libusb_bulk_transfer msg; + struct libusb_urb_handle *urbh; + fill_send_cmd28_urb(dev, &msg, 0x02, enroll_init, sizeof(enroll_init)); + urbh = libusb_async_bulk_transfer(dev->udev, &msg, + enroll_start_sm_cb_init, ssm, TIMEOUT); + if (!urbh) { + g_free(msg.data); + fpi_ssm_mark_aborted(ssm, -EIO); + } + break; + case READ_ENROLL_MSG28: ; /* FIXME: protocol misunderstanding here. device receives response * to subcmd 0 after submitting subcmd 2? */ /* actually this is probably a poll response? does the above cmd * include a 30 01 poll somewhere? */ - if (read_msg28(dev, 0x00, NULL, NULL) < 0) - return -EPROTO; + int r = read_msg_async(dev, enroll_start_sm_cb_msg28, ssm); + if (r < 0) + fpi_ssm_mark_aborted(ssm, r); + break; + } +} + +static void enroll_iterate(struct fp_dev *dev); + +static void e_handle_resp00(struct fp_dev *dev, unsigned char *data, + size_t data_len) +{ + struct upekts_dev *upekdev = dev->priv; + unsigned char status; + int result = 0; + + if (data_len != 14) { + fp_err("received 3001 poll response of %d bytes?", data_len); + fpi_drvcb_enroll_stage_completed(dev, -EPROTO, NULL, NULL); + return; } - while (!result) { - unsigned char status; + status = data[5]; + fp_dbg("poll result = %02x", status); - r = send_cmd28(dev, 0x00, (unsigned char *) poll_data, - sizeof(poll_data)); - if (r < 0) - return r; - if (read_msg28(dev, 0x00, &data, &data_len) < 0) - return -EPROTO; - - if (data_len != 14) { - fp_err("received 3001 poll response of %d bytes?", data_len); - g_free(data); - return -EPROTO; + switch (status) { + case 0x0c: + case 0x0d: + case 0x0e: + /* if we previously completed a non-last enrollment stage, we'll + * get this code to indicate successful stage completion */ + if (upekdev->enroll_passed) { + result = FP_ENROLL_PASS; + upekdev->enroll_passed = FALSE; } + /* otherwise it just means "no news" so we poll again */ + break; + case 0x1c: /* FIXME what does this one mean? */ + case 0x0b: /* FIXME what does this one mean? */ + case 0x23: /* FIXME what does this one mean? */ + result = FP_ENROLL_RETRY; + break; + case 0x0f: /* scan taking too long, remove finger and try again */ + result = FP_ENROLL_RETRY_REMOVE_FINGER; + break; + case 0x1e: /* swipe too short */ + result = FP_ENROLL_RETRY_TOO_SHORT; + break; + case 0x24: /* finger not centered */ + result = FP_ENROLL_RETRY_CENTER_FINGER; + break; + case 0x20: + /* finger scanned successfully */ + /* need to look at the next poll result to determine if enrollment is + * complete or not */ + upekdev->enroll_passed = 1; + break; + case 0x00: /* enrollment complete */ + /* we can now expect the enrollment data on the next poll, so we + * have nothing to do here */ + break; + default: + fp_err("unrecognised scan status code %02x", status); + result = -EPROTO; + break; + } - status = data[5]; - fp_dbg("poll result = %02x", status); - - /* These codes indicate that we're waiting for a finger scan, so poll - * again */ - switch (status) { - case 0x0c: - case 0x0d: - case 0x0e: - /* no news, poll again */ - if (passed) - result = FP_ENROLL_PASS; - break; - case 0x1c: /* FIXME what does this one mean? */ - case 0x0b: /* FIXME what does this one mean? */ - case 0x23: /* FIXME what does this one mean? */ - result = FP_ENROLL_RETRY; - break; - case 0x0f: /* scan taking too long, remove finger and try again */ - result = FP_ENROLL_RETRY_REMOVE_FINGER; - break; - case 0x1e: /* swipe too short */ - result = FP_ENROLL_RETRY_TOO_SHORT; - break; - case 0x24: /* finger not centered */ - result = FP_ENROLL_RETRY_CENTER_FINGER; - break; - case 0x20: - /* finger scanned successfully */ - /* don't break out immediately, need to look at the next - * value to determine if enrollment is complete or not */ - passed = 1; - break; - case 0x00: - if (passed) - result = FP_ENROLL_COMPLETE; - break; - default: - fp_err("unrecognised scan status code %02x", status); - result = -EPROTO; - break; - } - g_free(data); + if (result) { + fpi_drvcb_enroll_stage_completed(dev, result, NULL, NULL); + if (result > 0) + enroll_iterate(dev); + } else { + enroll_iterate(dev); } /* FIXME: need to extend protocol research to handle the case when * enrolment fails, e.g. you scan a different finger on each stage */ + /* FIXME: should do proper tracking of when we expect cmd0 results and + * cmd2 results and enforce it */ +} - if (result == FP_ENROLL_COMPLETE) { - struct fp_print_data *fdata; - - r = send_cmd28(dev, 0x00, (unsigned char *) poll_data, - sizeof(poll_data)); - if (r < 0) - return r; - /* FIXME: protocol misunderstanding here. device receives response - * to subcmd 0 after submitting subcmd 2? */ - if (read_msg28(dev, 0x02, &data, &data_len) < 0) - return -EPROTO; - - if (data_len < sizeof(scan_comp)) { - fp_err("fingerprint data too short (%d bytes)", data_len); - result = -EPROTO; - goto comp_out; - } - if (memcmp(data, scan_comp, sizeof(scan_comp)) != 0) { - fp_err("unrecognised data prefix %x %x %x %x %x", - data[0], data[1], data[2], data[3], data[4]); - result = -EPROTO; - goto comp_out; - } - if (!_data) { - fp_err("complete but no data storage!"); - result = FP_ENROLL_COMPLETE; - goto comp_out; - } +static void e_handle_resp02(struct fp_dev *dev, unsigned char *data, + size_t data_len) +{ + struct fp_print_data *fdata = NULL; + int result = -EPROTO; + if (data_len < sizeof(scan_comp)) { + fp_err("fingerprint data too short (%d bytes)", data_len); + } else if (memcmp(data, scan_comp, sizeof(scan_comp)) != 0) { + fp_err("unrecognised data prefix %x %x %x %x %x", + data[0], data[1], data[2], data[3], data[4]); + } else { fdata = fpi_print_data_new(dev, data_len - sizeof(scan_comp)); - memcpy(fdata->data, data + sizeof(scan_comp), data_len - sizeof(scan_comp)); - *_data = fdata; -comp_out: - do_deinit(dev); - g_free(data); + memcpy(fdata->data, data + sizeof(scan_comp), + data_len - sizeof(scan_comp)); + + result = FP_ENROLL_COMPLETE; } - return result; + fpi_drvcb_enroll_stage_completed(dev, result, fdata, NULL); +} + +static void enroll_iterate_msg_cb(struct fp_dev *dev, + enum read_msg_status msgstat, uint8_t seq, unsigned char subcmd, + unsigned char *data, size_t data_len, void *user_data) +{ + if (msgstat != READ_MSG_RESPONSE) { + fp_err("expected response, got %d seq=%x", msgstat, seq); + fpi_drvcb_enroll_stage_completed(dev, -EPROTO, NULL, NULL); + return; + } + if (subcmd == 0) { + e_handle_resp00(dev, data, data_len); + } else if (subcmd == 2) { + e_handle_resp02(dev, data, data_len); + } else { + fp_err("unexpected subcmd %d", subcmd); + fpi_drvcb_enroll_stage_completed(dev, -EPROTO, NULL, NULL); + } + +} + +static void enroll_iterate_cmd_cb(libusb_dev_handle *devh, + libusb_urb_handle *urbh, enum libusb_urb_cb_status status, + unsigned char endpoint, int rqlength, unsigned char *data, + int actual_length, void *user_data) +{ + struct fp_dev *dev = user_data; + + if (status != FP_URB_COMPLETED) { + fpi_drvcb_enroll_stage_completed(dev, -EIO, NULL, NULL); + } else if (rqlength != actual_length) { + fpi_drvcb_enroll_stage_completed(dev, -EPROTO, NULL, NULL); + } else { + int r = read_msg_async(dev, enroll_iterate_msg_cb, NULL); + if (r < 0) + fpi_drvcb_enroll_stage_completed(dev, r, NULL, NULL); + } + libusb_urb_handle_free(urbh); +} + +static void enroll_iterate(struct fp_dev *dev) +{ + struct libusb_bulk_transfer msg; + struct libusb_urb_handle *urbh; + + fill_send_cmd28_urb(dev, &msg, 0x00, poll_data, sizeof(poll_data)); + urbh = libusb_async_bulk_transfer(dev->udev, &msg, enroll_iterate_cmd_cb, + dev, TIMEOUT); + if (!urbh) { + g_free(msg.data); + fpi_drvcb_enroll_stage_completed(dev, -EIO, NULL, NULL); + } +} + +static void enroll_started(struct fpi_ssm *ssm) +{ + struct fp_dev *dev = ssm->dev; + fpi_drvcb_enroll_started(dev, ssm->error); + + if (!ssm->error) + enroll_iterate(dev); + + fpi_ssm_free(ssm); +} + +static int enroll_start(struct fp_dev *dev) +{ + struct upekts_dev *upekdev = dev->priv; + + /* do_init state machine first */ + struct fpi_ssm *ssm = fpi_ssm_new(dev, enroll_start_sm_run_state, + ENROLL_START_NUM_STATES); + + upekdev->enroll_passed = FALSE; + fpi_ssm_start(ssm, enroll_started); + return 0; +} + +static void enroll_stop_deinit_cb(struct fpi_ssm *ssm) +{ + /* don't really care about errors */ + fpi_drvcb_enroll_stopped(ssm->dev); + fpi_ssm_free(ssm); +} + +static int enroll_stop(struct fp_dev *dev) +{ + struct fpi_ssm *ssm = deinitsm_new(dev); + fpi_ssm_start(ssm, enroll_stop_deinit_cb); + return 0; +} + +static void verify_stop_deinit_cb(struct fpi_ssm *ssm) +{ + /* don't really care about errors */ + fpi_drvcb_verify_stopped(ssm->dev); + fpi_ssm_free(ssm); +} + +static void do_verify_stop(struct fp_dev *dev) +{ + struct fpi_ssm *ssm = deinitsm_new(dev); + fpi_ssm_start(ssm, verify_stop_deinit_cb); } static const unsigned char verify_hdr[] = { @@ -719,117 +1159,250 @@ static const unsigned char verify_hdr[] = { 0x00 }; -static int verify(struct fp_dev *dev, struct fp_print_data *print, - struct fp_img **img) +enum { + VERIFY_RUN_INITSM = 0, + VERIFY_INIT, + VERIFY_NUM_STATES, +}; + +/* Called when the device initialization state machine completes */ +static void verify_start_sm_cb_initsm(struct fpi_ssm *initsm) { - size_t data_len = sizeof(verify_hdr) + print->length; - unsigned char *data; - int r; - unsigned char status; - gboolean need_poll = FALSE; - gboolean done = FALSE; + struct fpi_ssm *verify_start_ssm = initsm->priv; + if (initsm->error) + fpi_ssm_mark_aborted(verify_start_ssm, initsm->error); + else + fpi_ssm_next_state(verify_start_ssm); + fpi_ssm_free(initsm); +} - r = do_init(dev); - if (r < 0) - return r; +static void verify_init_2803_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, + enum libusb_urb_cb_status status, unsigned char endpoint, + int rqlength, unsigned char *data, int actual_length, void *user_data) +{ + struct fpi_ssm *ssm = user_data; + if (status != FP_URB_COMPLETED) + fpi_ssm_mark_aborted(ssm, -EIO); + else if (rqlength != actual_length) + fpi_ssm_mark_aborted(ssm, -EPROTO); + else + fpi_ssm_next_state(ssm); + libusb_urb_handle_free(urbh); +} - data = g_malloc(data_len); - memcpy(data, verify_hdr, sizeof(verify_hdr)); - memcpy(data + sizeof(verify_hdr), print->data, print->length); +static void verify_start_sm_run_state(struct fpi_ssm *ssm) +{ + struct fp_dev *dev = ssm->dev; - r = send_cmd28(dev, 0x03, data, data_len); - if (r < 0) - return r; - g_free(data); + switch (ssm->cur_state) { + case VERIFY_RUN_INITSM: ; + struct fpi_ssm *initsm = initsm_new(dev); + initsm->priv = ssm; + fpi_ssm_start(initsm, verify_start_sm_cb_initsm); + break; + case VERIFY_INIT: ; + struct fp_print_data *print = dev->verify_data; + size_t data_len = sizeof(verify_hdr) + print->length; + unsigned char *data = g_malloc(data_len); + struct libusb_bulk_transfer msg; + struct libusb_urb_handle *urbh; - while (!done) { - if (need_poll) { - r = send_cmd28(dev, 0x00, (unsigned char *) poll_data, - sizeof(poll_data)); - if (r < 0) - return r; - } else { - need_poll = TRUE; - } - if (read_msg28(dev, 0x00, &data, &data_len) < 0) - return -EPROTO; - - if (data_len != 14) { - fp_err("received 3001 poll response of %d bytes?", data_len); - r = -EPROTO; - goto out; - } - - status = data[5]; - fp_dbg("poll result = %02x", status); - - /* These codes indicate that we're waiting for a finger scan, so poll - * again */ - switch (status) { - case 0x0c: /* no news, poll again */ - break; - case 0x20: - fp_dbg("processing scan for verification"); - break; - case 0x00: - fp_dbg("good image"); - done = TRUE; - break; - case 0x1c: /* FIXME what does this one mean? */ - case 0x0b: /* FIXME what does this one mean? */ - case 0x23: /* FIXME what does this one mean? */ - r = FP_VERIFY_RETRY; - goto out; - case 0x0f: /* scan taking too long, remove finger and try again */ - r = FP_VERIFY_RETRY_REMOVE_FINGER; - goto out; - case 0x1e: /* swipe too short */ - r = FP_VERIFY_RETRY_TOO_SHORT; - goto out; - case 0x24: /* finger not centered */ - r = FP_VERIFY_RETRY_CENTER_FINGER; - goto out; - default: - fp_err("unrecognised verify status code %02x", status); - r = -EPROTO; - goto out; - } + memcpy(data, verify_hdr, sizeof(verify_hdr)); + memcpy(data + sizeof(verify_hdr), print->data, print->length); + fill_send_cmd28_urb(dev, &msg, 0x03, data, data_len); g_free(data); + + urbh = libusb_async_bulk_transfer(dev->udev, &msg, + verify_init_2803_cb, ssm, TIMEOUT); + if (!urbh) { + g_free(msg.data); + fpi_ssm_mark_aborted(ssm, -EIO); + } + break; + } +} + +static void verify_iterate(struct fp_dev *dev); + +static void v_handle_resp00(struct fp_dev *dev, unsigned char *data, + size_t data_len) +{ + unsigned char status; + int r = 0; + + if (data_len != 14) { + fp_err("received 3001 poll response of %d bytes?", data_len); + r = -EPROTO; + goto out; } - if (status == 0x00) { - /* poll again for verify result */ - r = send_cmd28(dev, 0x00, (unsigned char *) poll_data, - sizeof(poll_data)); - if (r < 0) - return r; - if (read_msg28(dev, 0x03, &data, &data_len) < 0) - return -EPROTO; - if (data_len < 2) { - fp_err("verify result abnormally short!"); - r = -EPROTO; - goto out; - } - if (data[0] != 0x12) { - fp_err("unexpected verify header byte %02x", data[0]); - r = -EPROTO; - goto out; - } - if (data[1] == 0x00) { - r = FP_VERIFY_NO_MATCH; - } else if (data[1] == 0x01) { - r = FP_VERIFY_MATCH; - } else { - fp_err("unrecognised verify result %02x", data[1]); - r = -EPROTO; - goto out; - } + status = data[5]; + fp_dbg("poll result = %02x", status); + + /* These codes indicate that we're waiting for a finger scan, so poll + * again */ + switch (status) { + case 0x0c: /* no news, poll again */ + break; + case 0x20: + fp_dbg("processing scan for verification"); + break; + case 0x00: + fp_dbg("good image"); + break; + case 0x1c: /* FIXME what does this one mean? */ + case 0x0b: /* FIXME what does this one mean? */ + case 0x23: /* FIXME what does this one mean? */ + r = FP_VERIFY_RETRY; + break; + case 0x0f: /* scan taking too long, remove finger and try again */ + r = FP_VERIFY_RETRY_REMOVE_FINGER; + break; + case 0x1e: /* swipe too short */ + r = FP_VERIFY_RETRY_TOO_SHORT; + break; + case 0x24: /* finger not centered */ + r = FP_VERIFY_RETRY_CENTER_FINGER; + break; + default: + fp_err("unrecognised verify status code %02x", status); + r = -EPROTO; } out: - do_deinit(dev); - g_free(data); - return r; + if (r) + fpi_drvcb_report_verify_result(dev, r, NULL); + if (r >= 0) + verify_iterate(dev); +} + +static void v_handle_resp03(struct fp_dev *dev, unsigned char *data, + size_t data_len) +{ + int r; + + if (data_len < 2) { + fp_err("verify result abnormally short!"); + r = -EPROTO; + } else if (data[0] != 0x12) { + fp_err("unexpected verify header byte %02x", data[0]); + r = -EPROTO; + } else if (data[1] == 0x00) { + r = FP_VERIFY_NO_MATCH; + } else if (data[1] == 0x01) { + r = FP_VERIFY_MATCH; + } else { + fp_err("unrecognised verify result %02x", data[1]); + r = -EPROTO; + } + fpi_drvcb_report_verify_result(dev, r, NULL); +} + +static void verify_rd2800_cb(struct fp_dev *dev, enum read_msg_status msgstat, + uint8_t seq, unsigned char subcmd, unsigned char *data, size_t data_len, + void *user_data) +{ + struct upekts_dev *upekdev = dev->priv; + + if (msgstat != READ_MSG_RESPONSE) { + fp_err("expected response, got %d seq=%x", msgstat, seq); + fpi_drvcb_report_verify_result(dev, -EPROTO, NULL); + return; + } else if (seq != upekdev->seq) { + fp_err("expected response to cmd seq=%02x, got response to %02x", + upekdev->seq, seq); + fpi_drvcb_report_verify_result(dev, -EPROTO, NULL); + return; + } + + if (subcmd == 0) + v_handle_resp00(dev, data, data_len); + else if (subcmd == 3) + v_handle_resp03(dev, data, data_len); + else + fpi_drvcb_report_verify_result(dev, -EPROTO, NULL); +} + +static void verify_wr2800_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, + enum libusb_urb_cb_status status, unsigned char endpoint, + int rqlength, unsigned char *data, int actual_length, void *user_data) +{ + struct fp_dev *dev = user_data; + + if (status != FP_URB_COMPLETED) { + fpi_drvcb_report_verify_result(dev, -EIO, NULL); + } else if (rqlength != actual_length) { + fpi_drvcb_report_verify_result(dev, -EIO, NULL); + } else { + int r = read_msg_async(dev, verify_rd2800_cb, NULL); + if (r < 0) + fpi_drvcb_report_verify_result(dev, r, NULL); + } + libusb_urb_handle_free(urbh); +} + +static void verify_iterate(struct fp_dev *dev) +{ + struct upekts_dev *upekdev = dev->priv; + struct libusb_bulk_transfer msg; + + if (upekdev->stop_verify) { + do_verify_stop(dev); + return; + } + + /* FIXME: this doesn't flow well, should the first cmd be moved from + * verify init to here? */ + if (upekdev->first_verify_iteration) { + int r = read_msg_async(dev, verify_rd2800_cb, NULL); + upekdev->first_verify_iteration = FALSE; + if (r < 0) + fpi_drvcb_report_verify_result(dev, r, NULL); + } else { + struct libusb_urb_handle *urbh; + fill_send_cmd28_urb(dev, &msg, 0x00, poll_data, sizeof(poll_data)); + urbh = libusb_async_bulk_transfer(dev->udev, &msg, verify_wr2800_cb, + dev, TIMEOUT); + if (!urbh) { + g_free(msg.data); + fpi_drvcb_report_verify_result(dev, -EIO, NULL); + } + } +} + +static void verify_started(struct fpi_ssm *ssm) +{ + struct fp_dev *dev = ssm->dev; + struct upekts_dev *upekdev = dev->priv; + + fpi_drvcb_verify_started(dev, ssm->error); + if (!ssm->error) { + upekdev->first_verify_iteration = TRUE; + verify_iterate(dev); + } + + fpi_ssm_free(ssm); +} + +static int verify_start(struct fp_dev *dev) +{ + struct upekts_dev *upekdev = dev->priv; + struct fpi_ssm *ssm = fpi_ssm_new(dev, verify_start_sm_run_state, + VERIFY_NUM_STATES); + upekdev->stop_verify = FALSE; + fpi_ssm_start(ssm, verify_started); + return 0; +} + +static int verify_stop(struct fp_dev *dev, gboolean iterating) +{ + struct upekts_dev *upekdev = dev->priv; + + if (!iterating) + do_verify_stop(dev); + else + upekdev->stop_verify = TRUE; + return 0; } static const struct usb_id id_table[] = { @@ -843,8 +1416,10 @@ struct fp_driver upekts_driver = { .full_name = "UPEK TouchStrip", .id_table = id_table, .init = dev_init, - .exit = dev_exit, - .enroll = enroll, - .verify = verify, + .deinit = dev_exit, + .enroll_start = enroll_start, + .enroll_stop = enroll_stop, + .verify_start = verify_start, + .verify_stop = verify_stop, }; From 3048b37176263201cde7e754abb33feff47eafd8 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sun, 10 Feb 2008 18:35:01 +0000 Subject: [PATCH 096/184] Port imaging layer to asynchronous model --- libfprint/core.c | 4 +- libfprint/drv.c | 4 +- libfprint/fp_internal.h | 64 ++++- libfprint/img.c | 4 +- libfprint/imgdev.c | 515 +++++++++++++++++++++++++--------------- 5 files changed, 393 insertions(+), 198 deletions(-) diff --git a/libfprint/core.c b/libfprint/core.c index a7741ad1..71ccaea9 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -798,7 +798,9 @@ API_EXPORTED int fp_dev_img_capture(struct fp_dev *dev, int unconditional, return -ENOTSUP; } - return fpi_imgdev_capture(imgdev, unconditional, image); + //return fpi_imgdev_capture(imgdev, unconditional, image); + /* FIXME reimplement async */ + return -ENOTSUP; } /** \ingroup dev diff --git a/libfprint/drv.c b/libfprint/drv.c index e45ce788..bb92126f 100644 --- a/libfprint/drv.c +++ b/libfprint/drv.c @@ -67,6 +67,7 @@ int fpi_drv_enroll_start(struct fp_dev *dev, fp_enroll_stage_cb callback) { struct fp_driver *drv = dev->drv; int r; + fp_dbg(""); if (!drv->enroll_start) return -ENOTSUP; dev->state = DEV_STATE_ENROLL_STARTING; @@ -108,6 +109,7 @@ void fpi_drvcb_enroll_stage_completed(struct fp_dev *dev, int result, int fpi_drv_enroll_stop(struct fp_dev *dev) { struct fp_driver *drv = dev->drv; + fp_dbg(""); dev->enroll_cb = NULL; if (!drv->enroll_start) @@ -328,7 +330,7 @@ struct fpi_ssm *fpi_ssm_new(struct fp_dev *dev, ssm_handler_fn handler, int nr_states) { struct fpi_ssm *machine; - BUG_ON(nr_states < 1) + BUG_ON(nr_states < 1); machine = g_malloc0(sizeof(*machine)); machine->handler = handler; diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 63d39cd9..6164672e 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -62,13 +62,15 @@ void fpi_log(enum fpi_log_level, const char *component, const char *function, #define fp_warn(fmt...) _fpi_log(LOG_LEVEL_WARNING, fmt) #define fp_err(fmt...) _fpi_log(LOG_LEVEL_ERROR, fmt) -#ifdef NDEBUG +#ifndef NDEBUG #define BUG_ON(condition) \ if ((condition)) fp_err("BUG at %s:%d", __FILE__, __LINE__) #else #define BUG_ON(condition) #endif +#define BUG() BUG_ON(1) + enum fp_dev_state { DEV_STATE_INITIAL = 0, DEV_STATE_ERROR, @@ -123,9 +125,48 @@ struct fp_dev { fp_identify_cb identify_cb; }; +enum fp_imgdev_state { + IMGDEV_STATE_INACTIVE, + IMGDEV_STATE_AWAIT_FINGER_ON, + IMGDEV_STATE_CAPTURE, + IMGDEV_STATE_AWAIT_FINGER_OFF, +}; + +enum fp_imgdev_action { + IMG_ACTION_NONE = 0, + IMG_ACTION_ENROLL, + IMG_ACTION_VERIFY, + IMG_ACTION_IDENTIFY, +}; + +enum fp_imgdev_enroll_state { + IMG_ACQUIRE_STATE_NONE = 0, + IMG_ACQUIRE_STATE_ACTIVATING, + IMG_ACQUIRE_STATE_AWAIT_FINGER_ON, + IMG_ACQUIRE_STATE_AWAIT_IMAGE, + IMG_ACQUIRE_STATE_AWAIT_FINGER_OFF, + IMG_ACQUIRE_STATE_DONE, + IMG_ACQUIRE_STATE_DEACTIVATING, +}; + +enum fp_imgdev_verify_state { + IMG_VERIFY_STATE_NONE = 0, + IMG_VERIFY_STATE_ACTIVATING +}; + struct fp_img_dev { struct fp_dev *dev; libusb_dev_handle *udev; + enum fp_imgdev_action action; + int action_state; + + struct fp_print_data *acquire_data; + struct fp_img *acquire_img; + int action_result; + + /* FIXME: better place to put this? */ + size_t identify_match_offset; + void *priv; }; @@ -181,11 +222,10 @@ struct fp_img_driver { /* Device operations */ int (*init)(struct fp_img_dev *dev, unsigned long driver_data); - void (*exit)(struct fp_img_dev *dev); - int (*await_finger_on)(struct fp_img_dev *dev); - int (*await_finger_off)(struct fp_img_dev *dev); - int (*capture)(struct fp_img_dev *dev, gboolean unconditional, - struct fp_img **image); + void (*deinit)(struct fp_img_dev *dev); + int (*activate)(struct fp_img_dev *dev, enum fp_imgdev_state state); + int (*change_state)(struct fp_img_dev *dev, enum fp_imgdev_state state); + void (*deactivate)(struct fp_img_dev *dev); }; extern struct fp_driver upekts_driver; @@ -277,7 +317,7 @@ int fpi_img_to_print_data(struct fp_img_dev *imgdev, struct fp_img *img, int fpi_img_compare_print_data(struct fp_print_data *enrolled_print, struct fp_print_data *new_print); int fpi_img_compare_print_data_to_gallery(struct fp_print_data *print, - struct fp_print_data **gallery, int match_threshold, int *match_offset); + struct fp_print_data **gallery, int match_threshold, size_t *match_offset); /* async drv <--> lib comms */ @@ -340,5 +380,15 @@ void fpi_drvcb_report_identify_result(struct fp_dev *dev, int result, int fpi_drv_identify_stop(struct fp_dev *dev); void fpi_drvcb_identify_stopped(struct fp_dev *dev); +/* for image drivers */ +void fpi_imgdev_init_complete(struct fp_img_dev *imgdev, int status); +void fpi_imgdev_deinit_complete(struct fp_img_dev *imgdev); +void fpi_imgdev_activate_complete(struct fp_img_dev *imgdev, int status); +void fpi_imgdev_deactivate_complete(struct fp_img_dev *imgdev); +void fpi_imgdev_report_finger_status(struct fp_img_dev *imgdev, + gboolean present); +void fpi_imgdev_image_captured(struct fp_img_dev *imgdev, struct fp_img *img); +void fpi_imgdev_session_error(struct fp_img_dev *imgdev, int error); + #endif diff --git a/libfprint/img.c b/libfprint/img.c index da831d5b..1c708582 100644 --- a/libfprint/img.c +++ b/libfprint/img.c @@ -334,7 +334,7 @@ int fpi_img_to_print_data(struct fp_img_dev *imgdev, struct fp_img *img, /* FIXME: the print buffer at this point is endian-specific, and will * only work when loaded onto machines with identical endianness. not good! - * data format should be platform-independant. */ + * data format should be platform-independent. */ *ret = print; return 0; @@ -365,7 +365,7 @@ int fpi_img_compare_print_data(struct fp_print_data *enrolled_print, } int fpi_img_compare_print_data_to_gallery(struct fp_print_data *print, - struct fp_print_data **gallery, int match_threshold, int *match_offset) + struct fp_print_data **gallery, int match_threshold, size_t *match_offset) { struct xyt_struct *pstruct = (struct xyt_struct *) print->data; struct fp_print_data *gallery_print; diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index a511a198..e3eb8c5f 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -1,6 +1,6 @@ /* * Core imaging device functions for libfprint - * Copyright (C) 2007 Daniel Drake + * Copyright (C) 2007-2008 Daniel Drake * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -24,6 +24,9 @@ #include "fp_internal.h" +#define MIN_ACCEPTABLE_MINUTIAE 10 +#define BOZORTH3_DEFAULT_THRESHOLD 40 + static int img_dev_init(struct fp_dev *dev, unsigned long driver_data) { struct fp_img_dev *imgdev = g_malloc0(sizeof(*imgdev)); @@ -41,6 +44,8 @@ static int img_dev_init(struct fp_dev *dev, unsigned long driver_data) r = imgdrv->init(imgdev, driver_data); if (r) goto err; + } else { + fpi_drvcb_init_complete(dev, 0); } return 0; @@ -49,43 +54,37 @@ err: return r; } -static void img_dev_exit(struct fp_dev *dev) +void fpi_imgdev_init_complete(struct fp_img_dev *imgdev, int status) +{ + fpi_drvcb_init_complete(imgdev->dev, status); +} + +static void img_dev_deinit(struct fp_dev *dev) { struct fp_img_dev *imgdev = dev->priv; struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(dev->drv); - if (imgdrv->exit) - imgdrv->exit(imgdev); + if (imgdrv->deinit) + imgdrv->deinit(imgdev); + else + fpi_drvcb_deinit_complete(dev); +} +void fpi_imgdev_deinit_complete(struct fp_img_dev *imgdev) +{ + fpi_drvcb_deinit_complete(imgdev->dev); g_free(imgdev); } -int fpi_imgdev_get_img_width(struct fp_img_dev *imgdev) +static int dev_change_state(struct fp_img_dev *imgdev, + enum fp_imgdev_state state) { struct fp_driver *drv = imgdev->dev->drv; struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); - int width = imgdrv->img_width; - if (width > 0 && imgdrv->enlarge_factor > 1) - width *= imgdrv->enlarge_factor; - else if (width == -1) - width = 0; - - return width; -} - -int fpi_imgdev_get_img_height(struct fp_img_dev *imgdev) -{ - struct fp_driver *drv = imgdev->dev->drv; - struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); - int height = imgdrv->img_height; - - if (height > 0 && imgdrv->enlarge_factor > 1) - height *= imgdrv->enlarge_factor; - else if (height == -1) - height = 0; - - return height; + if (!imgdrv->change_state) + return 0; + return imgdrv->change_state(imgdev, state); } static struct fp_img *im_resize(struct fp_img *img, unsigned int factor) @@ -131,79 +130,31 @@ static struct fp_img *im_resize(struct fp_img *img, unsigned int factor) return newimg; } -int fpi_imgdev_capture(struct fp_img_dev *imgdev, int unconditional, - struct fp_img **_img) +/* check image properties and resize it if necessary. potentially returns a new + * image after freeing the old one. */ +static int sanitize_image(struct fp_img_dev *imgdev, struct fp_img **_img) { struct fp_driver *drv = imgdev->dev->drv; struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); - struct fp_img *img; - int r; - - if (!_img) { - fp_err("no image pointer given"); - return -EINVAL; - } - - if (!imgdrv->capture) { - fp_err("img driver %s has no capture func", drv->name); - return -ENOTSUP; - } - - if (unconditional) { - if (!(imgdrv->flags & FP_IMGDRV_SUPPORTS_UNCONDITIONAL_CAPTURE)) { - fp_dbg("requested unconditional capture, but driver %s does not " - "support it", drv->name); - return -ENOTSUP; - } - } - - fp_dbg("%s will handle capture request", drv->name); - - if (!unconditional && imgdrv->await_finger_on) { - r = imgdrv->await_finger_on(imgdev); - if (r) { - fp_err("await_finger_on failed with error %d", r); - return r; - } - } - - r = imgdrv->capture(imgdev, unconditional, &img); - if (r) { - fp_err("capture failed with error %d", r); - return r; - } - - if (img == NULL) { - fp_err("capture succeeded but no image returned?"); - return -ENODATA; - } - - if (!unconditional && imgdrv->await_finger_off) { - r = imgdrv->await_finger_off(imgdev); - if (r) { - fp_err("await_finger_off failed with error %d", r); - fp_img_free(img); - return r; - } - } + struct fp_img *img = *_img; if (imgdrv->img_width > 0) { img->width = imgdrv->img_width; } else if (img->width <= 0) { fp_err("no image width assigned"); - goto err; + return -EINVAL; } if (imgdrv->img_height > 0) { img->height = imgdrv->img_height; } else if (img->height <= 0) { fp_err("no image height assigned"); - goto err; + return -EINVAL; } if (!fpi_img_is_sane(img)) { fp_err("image is not sane!"); - goto err; + return -EINVAL; } if (imgdrv->enlarge_factor > 1) { @@ -213,145 +164,335 @@ int fpi_imgdev_capture(struct fp_img_dev *imgdev, int unconditional, * were bigger. */ struct fp_img *tmp = im_resize(img, imgdrv->enlarge_factor); fp_img_free(img); - img = tmp; + *_img = tmp; } - - *_img = img; return 0; -err: - fp_img_free(img); - return -EIO; } -#define MIN_ACCEPTABLE_MINUTIAE 10 - -int img_dev_enroll(struct fp_dev *dev, gboolean initial, int stage, - struct fp_print_data **ret, struct fp_img **_img) +void fpi_imgdev_report_finger_status(struct fp_img_dev *imgdev, + gboolean present) { - struct fp_img *img = NULL; - struct fp_img_dev *imgdev = dev->priv; - struct fp_print_data *print; - int r; + int r = imgdev->action_result; + fp_dbg(present ? "finger on sensor" : "finger removed"); - /* FIXME: convert to 3-stage enroll mechanism, where we scan 3 prints, - * use NFIQ to pick the best one, and discard the others */ - - r = fpi_imgdev_capture(imgdev, 0, &img); - - /* If we got an image, standardize it and return it even if the scan - * quality was too low for processing. */ - if (img) - fp_img_standardize(img); - if (_img) - *_img = img; - if (r) - return r; - - r = fpi_img_to_print_data(imgdev, img, &print); - if (r < 0) - return r; - if (img->minutiae->num < MIN_ACCEPTABLE_MINUTIAE) { - fp_dbg("not enough minutiae, %d/%d", r, MIN_ACCEPTABLE_MINUTIAE); - fp_print_data_free(print); - return FP_ENROLL_RETRY; + if (present && imgdev->action_state == IMG_ACQUIRE_STATE_AWAIT_FINGER_ON) { + dev_change_state(imgdev, IMGDEV_STATE_CAPTURE); + imgdev->action_state = IMG_ACQUIRE_STATE_AWAIT_IMAGE; + return; + } else if (present + || imgdev->action_state != IMG_ACQUIRE_STATE_AWAIT_FINGER_OFF) { + fp_dbg("ignoring status report"); + return; } - *ret = print; - return FP_ENROLL_COMPLETE; + switch (imgdev->action) { + case IMG_ACTION_ENROLL: + fpi_drvcb_enroll_stage_completed(imgdev->dev, r, imgdev->acquire_data, + imgdev->acquire_img); + break; + case IMG_ACTION_VERIFY: + fpi_drvcb_report_verify_result(imgdev->dev, r, imgdev->acquire_img); + fp_print_data_free(imgdev->acquire_data); + break; + case IMG_ACTION_IDENTIFY: + fpi_drvcb_report_identify_result(imgdev->dev, r, + imgdev->identify_match_offset, imgdev->acquire_img); + fp_print_data_free(imgdev->acquire_data); + default: + fp_err("unhandled action %d", imgdev->action); + break; + } + imgdev->acquire_img = NULL; + imgdev->acquire_data = NULL; } -#define BOZORTH3_DEFAULT_THRESHOLD 40 - -static int img_dev_verify(struct fp_dev *dev, - struct fp_print_data *enrolled_print, struct fp_img **_img) +static void verify_process_img(struct fp_img_dev *imgdev) { - struct fp_img_dev *imgdev = dev->priv; - struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(dev->drv); - struct fp_img *img = NULL; - struct fp_print_data *print; + struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(imgdev->dev->drv); int match_score = imgdrv->bz3_threshold; int r; - r = fpi_imgdev_capture(imgdev, 0, &img); - - /* If we got an image, standardize it and return it even if the scan - * quality was too low for processing. */ - if (img) - fp_img_standardize(img); - if (_img) - *_img = img; - if (r) - return r; - - r = fpi_img_to_print_data(imgdev, img, &print); - if (r < 0) - return r; - if (img->minutiae->num < MIN_ACCEPTABLE_MINUTIAE) { - fp_dbg("not enough minutiae, %d/%d", r, MIN_ACCEPTABLE_MINUTIAE); - fp_print_data_free(print); - return FP_VERIFY_RETRY; - } - if (match_score == 0) match_score = BOZORTH3_DEFAULT_THRESHOLD; - r = fpi_img_compare_print_data(enrolled_print, print); - fp_print_data_free(print); - if (r < 0) - return r; + r = fpi_img_compare_print_data(imgdev->dev->verify_data, + imgdev->acquire_data); + if (r >= match_score) - return FP_VERIFY_MATCH; - else - return FP_VERIFY_NO_MATCH; + r = FP_VERIFY_MATCH; + else if (r >= 0) + r = FP_VERIFY_NO_MATCH; + + imgdev->action_result = r; } -static int img_dev_identify(struct fp_dev *dev, - struct fp_print_data **print_gallery, size_t *match_offset, - struct fp_img **_img) +static void identify_process_img(struct fp_img_dev *imgdev) { - struct fp_img_dev *imgdev = dev->priv; - struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(dev->drv); - struct fp_img *img = NULL; - struct fp_print_data *print; + struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(imgdev->dev->drv); int match_score = imgdrv->bz3_threshold; + size_t match_offset; int r; - r = fpi_imgdev_capture(imgdev, 0, &img); - - /* If we got an image, standardize it and return it even if the scan - * quality was too low for processing. */ - if (img) - fp_img_standardize(img); - if (_img) - *_img = img; - if (r) - return r; - - r = fpi_img_to_print_data(imgdev, img, &print); - if (r < 0) - return r; - if (img->minutiae->num < MIN_ACCEPTABLE_MINUTIAE) { - fp_dbg("not enough minutiae, %d/%d", r, MIN_ACCEPTABLE_MINUTIAE); - fp_print_data_free(print); - return FP_VERIFY_RETRY; - } - if (match_score == 0) match_score = BOZORTH3_DEFAULT_THRESHOLD; - r = fpi_img_compare_print_data_to_gallery(print, print_gallery, - match_score, match_offset); - fp_print_data_free(print); + r = fpi_img_compare_print_data_to_gallery(imgdev->acquire_data, + imgdev->dev->identify_data, match_score, &match_offset); + + imgdev->action_result = r; + imgdev->identify_match_offset = match_offset; +} + +void fpi_imgdev_image_captured(struct fp_img_dev *imgdev, struct fp_img *img) +{ + struct fp_print_data *print; + int r; + fp_dbg(""); + + if (imgdev->action_state != IMG_ACQUIRE_STATE_AWAIT_IMAGE) { + fp_dbg("ignoring due to current state %d", imgdev->action_state); + return; + } + + if (imgdev->action_result) { + fp_dbg("not overwriting existing action result"); + return; + } + + r = sanitize_image(imgdev, &img); + if (r < 0) { + imgdev->action_result = r; + fp_img_free(img); + goto next_state; + } + + fp_img_standardize(img); + imgdev->acquire_img = img; + fpi_img_to_print_data(imgdev, img, &print); + if (img->minutiae->num < MIN_ACCEPTABLE_MINUTIAE) { + fp_dbg("not enough minutiae, %d/%d", img->minutiae->num, + MIN_ACCEPTABLE_MINUTIAE); + fp_print_data_free(print); + /* depends on FP_ENROLL_RETRY == FP_VERIFY_RETRY */ + imgdev->action = FP_ENROLL_RETRY; + goto next_state; + } + + imgdev->acquire_data = print; + switch (imgdev->action) { + case IMG_ACTION_ENROLL: + imgdev->action_result = FP_ENROLL_COMPLETE; + break; + case IMG_ACTION_VERIFY: + verify_process_img(imgdev); + break; + case IMG_ACTION_IDENTIFY: + identify_process_img(imgdev); + break; + default: + BUG(); + break; + } + +next_state: + imgdev->action_state = IMG_ACQUIRE_STATE_AWAIT_FINGER_OFF; + dev_change_state(imgdev, IMGDEV_STATE_AWAIT_FINGER_OFF); +} + +void fpi_imgdev_session_error(struct fp_img_dev *imgdev, int error) +{ + fp_dbg("error %d", error); + BUG_ON(error == 0); + switch (imgdev->action) { + case IMG_ACTION_ENROLL: + fpi_drvcb_enroll_stage_completed(imgdev->dev, error, NULL, NULL); + break; + case IMG_ACTION_VERIFY: + fpi_drvcb_report_verify_result(imgdev->dev, error, NULL); + break; + case IMG_ACTION_IDENTIFY: + fpi_drvcb_report_identify_result(imgdev->dev, error, 0, NULL); + break; + default: + fp_err("unhandled action %d", imgdev->action); + break; + } +} + +void fpi_imgdev_activate_complete(struct fp_img_dev *imgdev, int status) +{ + fp_dbg("status %d", status); + + switch (imgdev->action) { + case IMG_ACTION_ENROLL: + fpi_drvcb_enroll_started(imgdev->dev, status); + break; + case IMG_ACTION_VERIFY: + fpi_drvcb_verify_started(imgdev->dev, status); + break; + case IMG_ACTION_IDENTIFY: + fpi_drvcb_identify_started(imgdev->dev, status); + break; + default: + fp_err("unhandled action %d", imgdev->action); + return; + } + + if (status == 0) { + imgdev->action_state = IMG_ACQUIRE_STATE_AWAIT_FINGER_ON; + dev_change_state(imgdev, IMGDEV_STATE_AWAIT_FINGER_ON); + } +} + +void fpi_imgdev_deactivate_complete(struct fp_img_dev *imgdev) +{ + fp_dbg(""); + + switch (imgdev->action) { + case IMG_ACTION_ENROLL: + fpi_drvcb_enroll_stopped(imgdev->dev); + break; + case IMG_ACTION_VERIFY: + fpi_drvcb_verify_stopped(imgdev->dev); + break; + case IMG_ACTION_IDENTIFY: + fpi_drvcb_identify_stopped(imgdev->dev); + break; + default: + fp_err("unhandled action %d", imgdev->action); + break; + } + + imgdev->action = IMG_ACTION_NONE; + imgdev->action_state = 0; +} + +int fpi_imgdev_get_img_width(struct fp_img_dev *imgdev) +{ + struct fp_driver *drv = imgdev->dev->drv; + struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); + int width = imgdrv->img_width; + + if (width > 0 && imgdrv->enlarge_factor > 1) + width *= imgdrv->enlarge_factor; + else if (width == -1) + width = 0; + + return width; +} + +int fpi_imgdev_get_img_height(struct fp_img_dev *imgdev) +{ + struct fp_driver *drv = imgdev->dev->drv; + struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); + int height = imgdrv->img_height; + + if (height > 0 && imgdrv->enlarge_factor > 1) + height *= imgdrv->enlarge_factor; + else if (height == -1) + height = 0; + + return height; +} + +static int dev_activate(struct fp_img_dev *imgdev, enum fp_imgdev_state state) +{ + struct fp_driver *drv = imgdev->dev->drv; + struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); + + if (!imgdrv->activate) + return 0; + return imgdrv->activate(imgdev, state); +} + +static void dev_deactivate(struct fp_img_dev *imgdev) +{ + struct fp_driver *drv = imgdev->dev->drv; + struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); + + if (!imgdrv->activate) + return; + return imgdrv->deactivate(imgdev); +} + +static int generic_acquire_start(struct fp_dev *dev, int action) +{ + struct fp_img_dev *imgdev = dev->priv; + int r; + fp_dbg("action %d", action); + imgdev->action = action; + imgdev->action_state = IMG_ACQUIRE_STATE_ACTIVATING; + + r = dev_activate(imgdev, IMGDEV_STATE_AWAIT_FINGER_ON); + if (r < 0) + fp_err("activation failed with error %d", r); + return r; + +} + +static void generic_acquire_stop(struct fp_img_dev *imgdev) +{ + imgdev->action_state = IMG_ACQUIRE_STATE_DEACTIVATING; + dev_deactivate(imgdev); + + fp_print_data_free(imgdev->acquire_data); + fp_img_free(imgdev->acquire_img); + imgdev->acquire_data = NULL; + imgdev->acquire_img = NULL; + imgdev->action_result = 0; +} + +static int img_dev_enroll_start(struct fp_dev *dev) +{ + return generic_acquire_start(dev, IMG_ACTION_ENROLL); +} + +static int img_dev_verify_start(struct fp_dev *dev) +{ + return generic_acquire_start(dev, IMG_ACTION_VERIFY); +} + +static int img_dev_identify_start(struct fp_dev *dev) +{ + return generic_acquire_start(dev, IMG_ACTION_IDENTIFY); +} + +static int img_dev_enroll_stop(struct fp_dev *dev) +{ + struct fp_img_dev *imgdev = dev->priv; + BUG_ON(imgdev->action != IMG_ACTION_ENROLL); + generic_acquire_stop(imgdev); + return 0; +} + +static int img_dev_verify_stop(struct fp_dev *dev, gboolean iterating) +{ + struct fp_img_dev *imgdev = dev->priv; + BUG_ON(imgdev->action != IMG_ACTION_VERIFY); + generic_acquire_stop(imgdev); + return 0; +} + +static int img_dev_identify_stop(struct fp_dev *dev, gboolean iterating) +{ + struct fp_img_dev *imgdev = dev->priv; + BUG_ON(imgdev->action != IMG_ACTION_IDENTIFY); + generic_acquire_stop(imgdev); + imgdev->identify_match_offset = 0; + return 0; } void fpi_img_driver_setup(struct fp_img_driver *idriver) { idriver->driver.type = DRIVER_IMAGING; idriver->driver.init = img_dev_init; - //idriver->driver.exit = img_dev_exit; - //idriver->driver.enroll = img_dev_enroll; - //idriver->driver.verify = img_dev_verify; - //idriver->driver.identify = img_dev_identify; + idriver->driver.deinit = img_dev_deinit; + idriver->driver.enroll_start = img_dev_enroll_start; + idriver->driver.enroll_stop = img_dev_enroll_stop; + idriver->driver.verify_start = img_dev_verify_start; + idriver->driver.verify_stop = img_dev_verify_stop; + idriver->driver.identify_start = img_dev_identify_start; + idriver->driver.identify_stop = img_dev_identify_stop; } From d731d5f3a3970aa8a8560096c137b2eda1b462e1 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sun, 10 Feb 2008 18:35:19 +0000 Subject: [PATCH 097/184] aeslib: port to asynchronous model --- libfprint/aeslib.c | 142 +++++++++++++++++++++++++++++++-------------- libfprint/aeslib.h | 6 +- 2 files changed, 103 insertions(+), 45 deletions(-) diff --git a/libfprint/aeslib.c b/libfprint/aeslib.c index 9b22043a..31d04610 100644 --- a/libfprint/aeslib.c +++ b/libfprint/aeslib.c @@ -1,6 +1,6 @@ /* * Shared functions between libfprint Authentec drivers - * Copyright (C) 2007 Daniel Drake + * Copyright (C) 2007-2008 Daniel Drake * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -33,71 +33,127 @@ #define EP_IN (1 | LIBUSB_ENDPOINT_IN) #define EP_OUT (2 | LIBUSB_ENDPOINT_OUT) -static int do_write_regv(struct fp_img_dev *dev, - const struct aes_regwrite *regs, unsigned int num) +struct write_regv_data { + struct fp_img_dev *imgdev; + unsigned int num_regs; + const struct aes_regwrite *regs; + unsigned int offset; + aes_write_regv_cb callback; +}; + +static void continue_write_regv(struct write_regv_data *wdata); + +/* libusb bulk callback for regv write completion transfer. continues the + * transaction */ +static void write_regv_trf_complete(libusb_dev_handle *devh, + libusb_urb_handle *urbh, enum libusb_urb_cb_status status, + unsigned char endpoint, int rqlength, unsigned char *data, + int actual_length, void *user_data) { + struct write_regv_data *wdata = user_data; + + g_free(data); + libusb_urb_handle_free(urbh); + + if (status != FP_URB_COMPLETED) + wdata->callback(wdata->imgdev, -EIO); + else if (rqlength != actual_length) + wdata->callback(wdata->imgdev, -EPROTO); + else + continue_write_regv(wdata); +} + +/* write from wdata->offset to upper_bound (inclusive) of wdata->regs */ +static int do_write_regv(struct write_regv_data *wdata, int upper_bound) +{ + unsigned int offset = wdata->offset; + unsigned int num = upper_bound - offset + 1; size_t alloc_size = num * 2; unsigned char *data = g_malloc(alloc_size); unsigned int i; - size_t offset = 0; - int r; - int transferred; + size_t data_offset = 0; + struct libusb_urb_handle *urbh; struct libusb_bulk_transfer msg = { .endpoint = EP_OUT, .data = data, .length = alloc_size, }; + fp_dbg("write batch of %d regs", num); - for (i = 0; i < num; i++) { - data[offset++] = regs[i].reg; - data[offset++] = regs[i].value; + for (i = offset; i < offset + num; i++) { + const struct aes_regwrite *regwrite = &wdata->regs[i]; + data[data_offset++] = regwrite->reg; + data[data_offset++] = regwrite->value; } - r = libusb_bulk_transfer(dev->udev, &msg, &transferred, BULK_TIMEOUT); - g_free(data); - if (r < 0) { - fp_err("bulk write error %d", r); - return r; - } else if ((unsigned int) transferred < alloc_size) { - fp_err("unexpected short write %d/%d", r, alloc_size); + urbh = libusb_async_bulk_transfer(wdata->imgdev->udev, &msg, + write_regv_trf_complete, wdata, BULK_TIMEOUT); + if (!urbh) { + g_free(data); return -EIO; } return 0; } -int aes_write_regv(struct fp_img_dev *dev, const struct aes_regwrite *regs, - unsigned int num) +/* write the next batch of registers to be written, or if there are no more, + * indicate completion to the caller */ +static void continue_write_regv(struct write_regv_data *wdata) { - unsigned int i; - int skip = 0; - int add_offset = 0; - fp_dbg("write %d regs", num); + unsigned int offset = wdata->offset; + unsigned int regs_remaining; + unsigned int limit; + unsigned int upper_bound; + int i; + int r; - for (i = 0; i < num; i += add_offset + skip) { - int r, j; - int limit = MIN(num, i + MAX_REGWRITES_PER_REQUEST); - skip = 0; - - if (!regs[i].reg) { - add_offset = 0; - skip = 1; - continue; + /* skip all zeros and ensure there is still work to do */ + while (TRUE) { + if (offset >= wdata->num_regs) { + fp_dbg("all registers written"); + wdata->callback(wdata->imgdev, 0); + return; } - - for (j = i; j < limit; j++) - if (!regs[j].reg) { - skip = 1; - break; - } - - add_offset = j - i; - r = do_write_regv(dev, ®s[i], add_offset); - if (r < 0) - return r; + if (wdata->regs[offset].reg) + break; + offset++; } - return 0; + regs_remaining = wdata->num_regs - offset; + limit = MIN(regs_remaining, MAX_REGWRITES_PER_REQUEST); + upper_bound = offset + limit; + + /* determine if we can write the entire of the regs at once, or if there + * is a zero dividing things up */ + for (i = offset; i < offset + limit; i++) + if (!wdata->regs[i].reg) { + upper_bound = i - 1; + break; + } + + r = do_write_regv(wdata, upper_bound); + if (r < 0) { + wdata->callback(wdata->imgdev, r); + return; + } + + wdata->offset = upper_bound + 1; +} + +/* write a load of registers to the device, combining multiple writes in a + * single URB up to a limit. insert writes to non-existent register 0 to force + * specific groups of writes to be separated by different URBs. */ +void aes_write_regv(struct fp_img_dev *dev, const struct aes_regwrite *regs, + unsigned int num_regs, aes_write_regv_cb callback) +{ + struct write_regv_data *wdata = g_malloc(sizeof(*wdata)); + fp_dbg("write %d regs", num_regs); + wdata->imgdev = dev; + wdata->num_regs = num_regs; + wdata->regs = regs; + wdata->offset = 0; + wdata->callback = callback; + continue_write_regv(wdata); } void aes_assemble_image(unsigned char *input, size_t width, size_t height, diff --git a/libfprint/aeslib.h b/libfprint/aeslib.h index 792c6d43..e42d1e8c 100644 --- a/libfprint/aeslib.h +++ b/libfprint/aeslib.h @@ -27,8 +27,10 @@ struct aes_regwrite { unsigned char value; }; -int aes_write_regv(struct fp_img_dev *dev, const struct aes_regwrite *regs, - unsigned int num); +typedef void (*aes_write_regv_cb)(struct fp_img_dev *dev, int result); + +void aes_write_regv(struct fp_img_dev *dev, const struct aes_regwrite *regs, + unsigned int num_regs, aes_write_regv_cb callback); void aes_assemble_image(unsigned char *input, size_t width, size_t height, unsigned char *output); From d914712437a63f9671233bd0a29bef6adb16402c Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sun, 10 Feb 2008 18:36:10 +0000 Subject: [PATCH 098/184] aes4000: port to asynchronous model --- libfprint/Makefile.am | 4 +- libfprint/core.c | 2 +- libfprint/drivers/aes4000.c | 135 ++++++++++++++++++++++++------------ 3 files changed, 92 insertions(+), 49 deletions(-) diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 2a8f08e7..9ade9aa0 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -8,8 +8,8 @@ AES2501_SRC = drivers/aes2501.c drivers/aes2501.h AES4000_SRC = drivers/aes4000.c FDU2000_SRC = drivers/fdu2000.c -DRIVER_SRC = $(UPEKTS_SRC) -#DRIVER_SRC = $(URU4000_SRC) $(AES1610_SRC) $(AES2501_SRC) $(AES4000_SRC) $(UPEKTC_SRC) $(FDU2000_SRC) +DRIVER_SRC = $(UPEKTS_SRC) $(AES4000_SRC) +#DRIVER_SRC = $(URU4000_SRC) $(AES1610_SRC) $(AES2501_SRC) $(UPEKTC_SRC) $(FDU2000_SRC) NBIS_SRC = \ nbis/include/bozorth.h \ diff --git a/libfprint/core.c b/libfprint/core.c index 71ccaea9..ed238c84 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -329,10 +329,10 @@ static struct fp_driver * const primitive_drivers[] = { }; static struct fp_img_driver * const img_drivers[] = { + &aes4000_driver, /* &uru4000_driver, &aes1610_driver, &aes2501_driver, - &aes4000_driver, &upektc_driver, &fdu2000_driver, */ }; diff --git a/libfprint/drivers/aes4000.c b/libfprint/drivers/aes4000.c index 7e1ad88a..3b9130e0 100644 --- a/libfprint/drivers/aes4000.c +++ b/libfprint/drivers/aes4000.c @@ -1,6 +1,6 @@ /* * AuthenTec AES4000 driver for libfprint - * Copyright (C) 2007 Daniel Drake + * Copyright (C) 2007-2008 Daniel Drake * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -34,6 +34,10 @@ #define NR_SUBARRAYS 6 #define SUBARRAY_LEN 768 +struct aes4k_dev { + libusb_urb_handle *img_trf; +}; + static const struct aes_regwrite init_reqs[] = { /* master reset */ { 0x80, 0x01 }, @@ -109,45 +113,32 @@ static const struct aes_regwrite init_reqs[] = { { 0x81, 0x00 }, }; -static int capture(struct fp_img_dev *dev, gboolean unconditional, - struct fp_img **ret) +static void do_capture(struct fp_img_dev *dev); + +static void img_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, + enum libusb_urb_cb_status status, unsigned char endpoint, + int rqlength, unsigned char *data, int actual_length, void *user_data) { - int i; - int r; - int transferred; + struct fp_img_dev *dev = user_data; + struct aes4k_dev *aesdev = dev->priv; + unsigned char *ptr = data; struct fp_img *img; - unsigned char *data; - unsigned char *ptr; - struct libusb_bulk_transfer msg = { - .endpoint = EP_IN, - .length = DATA_BUFLEN, - }; + int i; - r = aes_write_regv(dev, init_reqs, G_N_ELEMENTS(init_reqs)); - if (r < 0) - return r; - - img = fpi_img_new_for_imgdev(dev); - data = g_malloc(DATA_BUFLEN); - ptr = data; - msg.data = data; - - /* See the timeout explanation in the uru4000 driver for the reasoning - * behind this silly loop. */ -retry: - r = libusb_bulk_transfer(dev->udev, &msg, &transferred, 1000); - if (r == -ETIMEDOUT) - goto retry; - - if (r < 0) { - fp_err("data read failed, error %d", r); + if (status == FP_URB_CANCELLED) { goto err; - } else if (transferred < DATA_BUFLEN) { - fp_err("short data read (%d)", r); - r = -EIO; + } else if (status != FP_URB_COMPLETED) { + fpi_imgdev_session_error(dev, -EIO); + goto err; + } else if (rqlength != actual_length) { + fpi_imgdev_session_error(dev, -EPROTO); goto err; } + fpi_imgdev_report_finger_status(dev, TRUE); + + img = fpi_img_new_for_imgdev(dev); + img->flags = FP_IMG_COLORS_INVERTED | FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED; for (i = 0; i < NR_SUBARRAYS; i++) { fp_dbg("subarray header byte %02x", *ptr); ptr++; @@ -155,14 +146,60 @@ retry: ptr += SUBARRAY_LEN; } - img->flags = FP_IMG_COLORS_INVERTED | FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED; - *ret = img; - g_free(data); - return 0; + fpi_imgdev_image_captured(dev, img); + + /* FIXME: rather than assuming finger has gone, we should poll regs until + * it really has, then restart the capture */ + fpi_imgdev_report_finger_status(dev, FALSE); + + do_capture(dev); + err: g_free(data); - fp_img_free(img); - return r; + aesdev->img_trf = NULL; + libusb_urb_handle_free(urbh); +} + +static void do_capture(struct fp_img_dev *dev) +{ + struct aes4k_dev *aesdev = dev->priv; + struct libusb_bulk_transfer trf = { + .endpoint = EP_IN, + .length = DATA_BUFLEN, + .data = g_malloc(DATA_BUFLEN), + }; + + aesdev->img_trf = libusb_async_bulk_transfer(dev->udev, &trf, img_cb, dev, + 0); + if (!aesdev->img_trf) { + g_free(trf.data); + fpi_imgdev_session_error(dev, -EIO); + } +} + +static void init_reqs_cb(struct fp_img_dev *dev, int result) +{ + fpi_imgdev_activate_complete(dev, result); + if (result == 0) + do_capture(dev); +} + +static int dev_activate(struct fp_img_dev *dev, enum fp_imgdev_state state) +{ + aes_write_regv(dev, init_reqs, G_N_ELEMENTS(init_reqs), init_reqs_cb); + return 0; +} + +static void dev_deactivate(struct fp_img_dev *dev) +{ + struct aes4k_dev *aesdev = dev->priv; + + /* FIXME: should wait for cancellation to complete before returning + * from deactivation, otherwise app may legally exit before we've + * cleaned up */ + if (aesdev->img_trf) + libusb_urb_handle_cancel(dev->udev, aesdev->img_trf); + fpi_imgdev_deactivate_complete(dev); } static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) @@ -170,17 +207,22 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) int r; r = libusb_claim_interface(dev->udev, 0); - if (r < 0) { + if (r < 0) fp_err("could not claim interface 0"); - return r; - } - return 0; + dev->priv = g_malloc0(sizeof(struct aes4k_dev)); + + if (r == 0) + fpi_imgdev_init_complete(dev, 0); + + return r; } -static void dev_exit(struct fp_img_dev *dev) +static void dev_deinit(struct fp_img_dev *dev) { + g_free(dev->priv); libusb_release_interface(dev->udev, 0); + fpi_imgdev_deinit_complete(dev); } static const struct usb_id id_table[] = { @@ -204,7 +246,8 @@ struct fp_img_driver aes4000_driver = { .bz3_threshold = 9, .init = dev_init, - .exit = dev_exit, - .capture = capture, + .deinit = dev_deinit, + .activate = dev_activate, + .deactivate = dev_deactivate, }; From 6f08a3666d71a4992b4af037164493ad633b8b1b Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Fri, 15 Feb 2008 18:03:03 +0000 Subject: [PATCH 099/184] aeslib: fix register write boundaries --- libfprint/aeslib.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libfprint/aeslib.c b/libfprint/aeslib.c index 31d04610..bf9d0f20 100644 --- a/libfprint/aeslib.c +++ b/libfprint/aeslib.c @@ -78,7 +78,6 @@ static int do_write_regv(struct write_regv_data *wdata, int upper_bound) .data = data, .length = alloc_size, }; - fp_dbg("write batch of %d regs", num); for (i = offset; i < offset + num; i++) { const struct aes_regwrite *regwrite = &wdata->regs[i]; @@ -119,13 +118,14 @@ static void continue_write_regv(struct write_regv_data *wdata) offset++; } + wdata->offset = offset; regs_remaining = wdata->num_regs - offset; limit = MIN(regs_remaining, MAX_REGWRITES_PER_REQUEST); - upper_bound = offset + limit; + upper_bound = offset + limit - 1; /* determine if we can write the entire of the regs at once, or if there * is a zero dividing things up */ - for (i = offset; i < offset + limit; i++) + for (i = offset; i <= upper_bound; i++) if (!wdata->regs[i].reg) { upper_bound = i - 1; break; From 77b5dab04b1305ba1e65eb7459349f99f36eba73 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Fri, 15 Feb 2008 18:06:24 +0000 Subject: [PATCH 100/184] aeslib: introduce user_data for write registers callback aes2501 needs this for state tracking --- libfprint/aeslib.c | 12 +++++++----- libfprint/aeslib.h | 5 +++-- libfprint/drivers/aes4000.c | 4 ++-- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/libfprint/aeslib.c b/libfprint/aeslib.c index bf9d0f20..4c797c3c 100644 --- a/libfprint/aeslib.c +++ b/libfprint/aeslib.c @@ -39,6 +39,7 @@ struct write_regv_data { const struct aes_regwrite *regs; unsigned int offset; aes_write_regv_cb callback; + void *user_data; }; static void continue_write_regv(struct write_regv_data *wdata); @@ -56,9 +57,9 @@ static void write_regv_trf_complete(libusb_dev_handle *devh, libusb_urb_handle_free(urbh); if (status != FP_URB_COMPLETED) - wdata->callback(wdata->imgdev, -EIO); + wdata->callback(wdata->imgdev, -EIO, wdata->user_data); else if (rqlength != actual_length) - wdata->callback(wdata->imgdev, -EPROTO); + wdata->callback(wdata->imgdev, -EPROTO, wdata->user_data); else continue_write_regv(wdata); } @@ -110,7 +111,7 @@ static void continue_write_regv(struct write_regv_data *wdata) while (TRUE) { if (offset >= wdata->num_regs) { fp_dbg("all registers written"); - wdata->callback(wdata->imgdev, 0); + wdata->callback(wdata->imgdev, 0, wdata->user_data); return; } if (wdata->regs[offset].reg) @@ -133,7 +134,7 @@ static void continue_write_regv(struct write_regv_data *wdata) r = do_write_regv(wdata, upper_bound); if (r < 0) { - wdata->callback(wdata->imgdev, r); + wdata->callback(wdata->imgdev, r, wdata->user_data); return; } @@ -144,7 +145,7 @@ static void continue_write_regv(struct write_regv_data *wdata) * single URB up to a limit. insert writes to non-existent register 0 to force * specific groups of writes to be separated by different URBs. */ void aes_write_regv(struct fp_img_dev *dev, const struct aes_regwrite *regs, - unsigned int num_regs, aes_write_regv_cb callback) + unsigned int num_regs, aes_write_regv_cb callback, void *user_data) { struct write_regv_data *wdata = g_malloc(sizeof(*wdata)); fp_dbg("write %d regs", num_regs); @@ -153,6 +154,7 @@ void aes_write_regv(struct fp_img_dev *dev, const struct aes_regwrite *regs, wdata->regs = regs; wdata->offset = 0; wdata->callback = callback; + wdata->user_data = user_data; continue_write_regv(wdata); } diff --git a/libfprint/aeslib.h b/libfprint/aeslib.h index e42d1e8c..3c65dae9 100644 --- a/libfprint/aeslib.h +++ b/libfprint/aeslib.h @@ -27,10 +27,11 @@ struct aes_regwrite { unsigned char value; }; -typedef void (*aes_write_regv_cb)(struct fp_img_dev *dev, int result); +typedef void (*aes_write_regv_cb)(struct fp_img_dev *dev, int result, + void *user_data); void aes_write_regv(struct fp_img_dev *dev, const struct aes_regwrite *regs, - unsigned int num_regs, aes_write_regv_cb callback); + unsigned int num_regs, aes_write_regv_cb callback, void *user_data); void aes_assemble_image(unsigned char *input, size_t width, size_t height, unsigned char *output); diff --git a/libfprint/drivers/aes4000.c b/libfprint/drivers/aes4000.c index 3b9130e0..cc838e71 100644 --- a/libfprint/drivers/aes4000.c +++ b/libfprint/drivers/aes4000.c @@ -177,7 +177,7 @@ static void do_capture(struct fp_img_dev *dev) } } -static void init_reqs_cb(struct fp_img_dev *dev, int result) +static void init_reqs_cb(struct fp_img_dev *dev, int result, void *user_data) { fpi_imgdev_activate_complete(dev, result); if (result == 0) @@ -186,7 +186,7 @@ static void init_reqs_cb(struct fp_img_dev *dev, int result) static int dev_activate(struct fp_img_dev *dev, enum fp_imgdev_state state) { - aes_write_regv(dev, init_reqs, G_N_ELEMENTS(init_reqs), init_reqs_cb); + aes_write_regv(dev, init_reqs, G_N_ELEMENTS(init_reqs), init_reqs_cb, NULL); return 0; } From 0aaffcee33015163d79320433cfd9d9c5941143a Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Fri, 15 Feb 2008 18:09:14 +0000 Subject: [PATCH 101/184] Allow jumping to arbitrary state in a SSM This is looking less and less like a simple state machine now, but it's proving a useful model! --- libfprint/drv.c | 15 ++++++++++++++- libfprint/fp_internal.h | 1 + 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/libfprint/drv.c b/libfprint/drv.c index bb92126f..f1cc6c5a 100644 --- a/libfprint/drv.c +++ b/libfprint/drv.c @@ -297,6 +297,11 @@ void fpi_drvcb_identify_stopped(struct fp_dev *dev) * There is also an implicit error state and an implicit accepting state * (both with implicit edges from every state). * + * You can also jump to any arbitrary state (while marking completion of the + * current state) while the machine is running. In other words there are + * implicit edges linking one state to every other state. OK, we're stretching + * the "state machine" description at this point. + * * To create a ssm, you pass a state handler function and the total number of * states (4 in the above example). * @@ -377,7 +382,7 @@ void fpi_ssm_mark_completed(struct fpi_ssm *machine) /* Mark a ssm as aborted with error. */ void fpi_ssm_mark_aborted(struct fpi_ssm *machine, int error) { - fp_dbg("error %d", error); + fp_dbg("error %d from state %d", error, machine->cur_state); BUG_ON(error == 0); machine->error = error; fpi_ssm_mark_completed(machine); @@ -395,3 +400,11 @@ void fpi_ssm_next_state(struct fpi_ssm *machine) } } +void fpi_ssm_jump_to_state(struct fpi_ssm *machine, int state) +{ + BUG_ON(machine->completed); + BUG_ON(state >= machine->nr_states); + machine->cur_state = state; + __ssm_call_handler(machine); +} + diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 6164672e..dc6a5036 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -349,6 +349,7 @@ int fpi_ssm_has_completed(struct fpi_ssm *machine); /* for drivers */ void fpi_ssm_next_state(struct fpi_ssm *machine); +void fpi_ssm_jump_to_state(struct fpi_ssm *machine, int state); void fpi_ssm_mark_completed(struct fpi_ssm *machine); void fpi_ssm_mark_aborted(struct fpi_ssm *machine, int error); From eff26bf0be5c1ea22469958abcdb65ce6e9ec428 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Fri, 15 Feb 2008 18:11:01 +0000 Subject: [PATCH 102/184] aes2501: port to asynchronous model --- libfprint/Makefile.am | 4 +- libfprint/core.c | 2 +- libfprint/drivers/aes2501.c | 1138 +++++++++++++++++++++++------------ 3 files changed, 745 insertions(+), 399 deletions(-) diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 9ade9aa0..70aea683 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -8,8 +8,8 @@ AES2501_SRC = drivers/aes2501.c drivers/aes2501.h AES4000_SRC = drivers/aes4000.c FDU2000_SRC = drivers/fdu2000.c -DRIVER_SRC = $(UPEKTS_SRC) $(AES4000_SRC) -#DRIVER_SRC = $(URU4000_SRC) $(AES1610_SRC) $(AES2501_SRC) $(UPEKTC_SRC) $(FDU2000_SRC) +DRIVER_SRC = $(UPEKTS_SRC) $(AES4000_SRC) $(AES2501_SRC) +#DRIVER_SRC = $(URU4000_SRC) $(AES1610_SRC) $(UPEKTC_SRC) $(FDU2000_SRC) NBIS_SRC = \ nbis/include/bozorth.h \ diff --git a/libfprint/core.c b/libfprint/core.c index ed238c84..d6298117 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -330,9 +330,9 @@ static struct fp_driver * const primitive_drivers[] = { static struct fp_img_driver * const img_drivers[] = { &aes4000_driver, + &aes2501_driver, /* &uru4000_driver, &aes1610_driver, - &aes2501_driver, &upektc_driver, &fdu2000_driver, */ }; diff --git a/libfprint/drivers/aes2501.c b/libfprint/drivers/aes2501.c index 26a6e54a..37439b50 100644 --- a/libfprint/drivers/aes2501.c +++ b/libfprint/drivers/aes2501.c @@ -1,6 +1,6 @@ /* * AuthenTec AES2501 driver for libfprint - * Copyright (C) 2007 Daniel Drake + * Copyright (C) 2007-2008 Daniel Drake * Copyright (C) 2007 Cyrille Bagard * Copyright (C) 2007 Vasily Khoruzhick * @@ -32,6 +32,9 @@ #include #include "aes2501.h" +static void start_capture(struct fp_img_dev *dev); +static void complete_deactivation(struct fp_img_dev *dev); + /* FIXME these need checking */ #define EP_IN (1 | LIBUSB_ENDPOINT_IN) #define EP_OUT (2 | LIBUSB_ENDPOINT_OUT) @@ -57,44 +60,612 @@ /* FIXME reduce substantially */ #define MAX_FRAMES 150 -static int read_data(struct fp_img_dev *dev, unsigned char *data, size_t len) -{ - int r; - int transferred; - struct libusb_bulk_transfer msg = { - .endpoint = EP_IN, - .data = data, - .length = len, - }; - fp_dbg("len=%zd", len); +/****** GENERAL FUNCTIONS ******/ - r = libusb_bulk_transfer(dev->udev, &msg, &transferred, BULK_TIMEOUT); - if (r < 0) { - fp_err("bulk read error %d", r); - return r; - } else if (transferred < len) { - fp_err("unexpected short read %d/%zd", r, len); - return -EIO; +struct aes2501_dev { + uint8_t read_regs_retry_count; + GSList *strips; + size_t strips_len; + gboolean deactivating; +}; + +typedef void (*aes2501_read_regs_cb)(struct fp_img_dev *dev, int status, + unsigned char *regs, void *user_data); + +struct aes2501_read_regs { + struct fp_img_dev *dev; + aes2501_read_regs_cb callback; + struct aes_regwrite *regwrite; + void *user_data; +}; + +static void read_regs_data_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, + enum libusb_urb_cb_status status, unsigned char endpoint, int rqlength, + unsigned char *data, int actual_length, void *user_data) +{ + struct aes2501_read_regs *rdata = user_data; + unsigned char *retdata = NULL; + int r; + + if (status != FP_URB_COMPLETED) { + r = -EIO; + } else if (rqlength != actual_length) { + r = -EPROTO; + } else { + r = 0; + retdata = data; } - return 0; + + rdata->callback(rdata->dev, r, retdata, rdata->user_data); + libusb_urb_handle_free(urbh); + g_free(data); + g_free(rdata); } -static int read_regs(struct fp_img_dev *dev, unsigned char *data) +static void read_regs_rq_cb(struct fp_img_dev *dev, int result, void *user_data) { - int r; - const struct aes_regwrite regwrite = { - AES2501_REG_CTRL2, AES2501_CTRL2_READ_REGS + struct aes2501_read_regs *rdata = user_data; + struct libusb_urb_handle *urbh; + struct libusb_bulk_transfer trf = { + .endpoint = EP_IN, + .length = 126, }; + g_free(rdata->regwrite); + if (result != 0) + goto err; + + trf.data = g_malloc(trf.length); + urbh = libusb_async_bulk_transfer(dev->udev, &trf, read_regs_data_cb, + rdata, BULK_TIMEOUT); + if (!urbh) { + g_free(trf.data); + result = EIO; + goto err; + } + + return; +err: + rdata->callback(dev, result, NULL, rdata->user_data); + g_free(rdata); +} + +static void read_regs(struct fp_img_dev *dev, aes2501_read_regs_cb callback, + void *user_data) +{ + /* FIXME: regwrite is dynamic because of asynchronity. is this really + * required? */ + struct aes_regwrite *regwrite = g_malloc(sizeof(*regwrite)); + struct aes2501_read_regs *rdata = g_malloc(sizeof(*rdata)); + fp_dbg(""); + regwrite->reg = AES2501_REG_CTRL2; + regwrite->value = AES2501_CTRL2_READ_REGS; + rdata->dev = dev; + rdata->callback = callback; + rdata->user_data = user_data; + rdata->regwrite = regwrite; - r = aes_write_regv(dev, ®write, 1); - if (r < 0) - return r; - - return read_data(dev, data, 126); + aes_write_regv(dev, (const struct aes_regwrite *) regwrite, 1, + read_regs_rq_cb, rdata); } +/* Read the value of a specific register from a register dump */ +static int regval_from_dump(unsigned char *data, uint8_t target) +{ + if (*data != FIRST_AES2501_REG) { + fp_err("not a register dump"); + return -EILSEQ; + } + + if (!(FIRST_AES2501_REG <= target && target <= LAST_AES2501_REG)) { + fp_err("out of range"); + return -EINVAL; + } + + target -= FIRST_AES2501_REG; + target *= 2; + return data[target + 1]; +} + +static void generic_write_regv_cb(struct fp_img_dev *dev, int result, + void *user_data) +{ + struct fpi_ssm *ssm = user_data; + if (result == 0) + fpi_ssm_next_state(ssm); + else + fpi_ssm_mark_aborted(ssm, result); +} + +/* check that read succeeded but ignore all data */ +static void generic_ignore_data_cb(libusb_dev_handle *devh, + libusb_urb_handle *urbh, enum libusb_urb_cb_status status, + unsigned char endpoint, int rqlength, unsigned char *data, + int actual_length, void *user_data) +{ + struct fpi_ssm *ssm = user_data; + + libusb_urb_handle_free(urbh); + g_free(data); + + if (status != FP_URB_COMPLETED) + fpi_ssm_mark_aborted(ssm, -EIO); + else if (rqlength != actual_length) + fpi_ssm_mark_aborted(ssm, -EPROTO); + else + fpi_ssm_next_state(ssm); +} + +/* read the specified number of bytes from the IN endpoint but throw them + * away, then increment the SSM */ +static void generic_read_ignore_data(struct fpi_ssm *ssm, size_t bytes) +{ + struct libusb_urb_handle *urbh; + struct libusb_bulk_transfer trf = { + .endpoint = EP_IN, + .data = g_malloc(bytes), + .length = bytes, + }; + + urbh = libusb_async_bulk_transfer(ssm->dev->udev, &trf, + generic_ignore_data_cb, ssm, BULK_TIMEOUT); + if (!urbh) { + g_free(trf.data); + fpi_ssm_mark_aborted(ssm, -EIO); + } +} + +/****** IMAGE PROCESSING ******/ + +static int sum_histogram_values(unsigned char *data, uint8_t threshold) +{ + int r = 0; + int i; + uint16_t *histogram = (uint16_t *)(data + 1); + + if (*data != 0xde) + return -EILSEQ; + + if (threshold > 0x0f) + return -EINVAL; + + /* FIXME endianness */ + for (i = threshold; i < 16; i++) + r += histogram[i]; + + return r; +} + +/* find overlapping parts of frames */ +static unsigned int find_overlap(unsigned char *first_frame, + unsigned char *second_frame, unsigned int *min_error) +{ + unsigned int dy; + unsigned int not_overlapped_height = 0; + *min_error = 255 * FRAME_SIZE; + for (dy = 0; dy < FRAME_HEIGHT; dy++) { + /* Calculating difference (error) between parts of frames */ + unsigned int i; + unsigned int error = 0; + for (i = 0; i < FRAME_WIDTH * (FRAME_HEIGHT - dy); i++) { + /* Using ? operator to avoid abs function */ + error += first_frame[i] > second_frame[i] ? + (first_frame[i] - second_frame[i]) : + (second_frame[i] - first_frame[i]); + } + + /* Normalize error */ + error *= 15; + error /= i; + if (error < *min_error) { + *min_error = error; + not_overlapped_height = dy; + } + first_frame += FRAME_WIDTH; + } + + return not_overlapped_height; +} + +/* assemble a series of frames into a single image */ +static unsigned int assemble(struct aes2501_dev *aesdev, unsigned char *output, + gboolean reverse, unsigned int *errors_sum) +{ + uint8_t *assembled = output; + int frame; + uint32_t image_height = FRAME_HEIGHT; + unsigned int min_error; + size_t num_strips = aesdev->strips_len; + GSList *list_entry = aesdev->strips; + *errors_sum = 0; + + /* Rotating given data by 90 degrees + * Taken from document describing aes2501 image format + * TODO: move reversing detection here */ + + if (reverse) + output += (num_strips - 1) * FRAME_SIZE; + for (frame = 0; frame < num_strips; frame++) { + aes_assemble_image(list_entry->data, FRAME_WIDTH, FRAME_HEIGHT, output); + + if (reverse) + output -= FRAME_SIZE; + else + output += FRAME_SIZE; + list_entry = g_slist_next(list_entry); + } + + /* Detecting where frames overlaped */ + output = assembled; + for (frame = 1; frame < num_strips; frame++) { + int not_overlapped; + + output += FRAME_SIZE; + not_overlapped = find_overlap(assembled, output, &min_error); + *errors_sum += min_error; + image_height += not_overlapped; + assembled += FRAME_WIDTH * not_overlapped; + memcpy(assembled, output, FRAME_SIZE); + } + return image_height; +} + +static void assemble_and_submit_image(struct fp_img_dev *dev) +{ + struct aes2501_dev *aesdev = dev->priv; + size_t final_size; + struct fp_img *img; + unsigned int errors_sum, r_errors_sum; + + BUG_ON(aesdev->strips_len == 0); + + /* reverse list */ + aesdev->strips = g_slist_reverse(aesdev->strips); + + /* create buffer big enough for max image */ + img = fpi_img_new(aesdev->strips_len * FRAME_SIZE); + + img->flags = FP_IMG_COLORS_INVERTED; + img->height = assemble(aesdev, img->data, FALSE, &errors_sum); + img->height = assemble(aesdev, img->data, TRUE, &r_errors_sum); + + if (r_errors_sum > errors_sum) { + img->height = assemble(aesdev, img->data, FALSE, &errors_sum); + img->flags |= FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED; + fp_dbg("normal scan direction"); + } else { + fp_dbg("reversed scan direction"); + } + + /* now that overlap has been removed, resize output image buffer */ + final_size = img->height * FRAME_WIDTH; + img = fpi_img_resize(img, final_size); + fpi_imgdev_image_captured(dev, img); + + /* free strips and strip list */ + g_slist_foreach(aesdev->strips, (GFunc) g_free, NULL); + g_slist_free(aesdev->strips); + aesdev->strips = NULL; +} + + +/****** FINGER PRESENCE DETECTION ******/ + +static const struct aes_regwrite finger_det_reqs[] = { + { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, + { AES2501_REG_EXCITCTRL, 0x40 }, + { AES2501_REG_DETCTRL, + AES2501_DETCTRL_DRATE_CONTINUOUS | AES2501_DETCTRL_SDELAY_31_MS }, + { AES2501_REG_COLSCAN, AES2501_COLSCAN_SRATE_128_US }, + { AES2501_REG_MEASDRV, AES2501_MEASDRV_MDRIVE_0_325 | AES2501_MEASDRV_MEASURE_SQUARE }, + { AES2501_REG_MEASFREQ, AES2501_MEASFREQ_2M }, + { AES2501_REG_DEMODPHASE1, DEMODPHASE_NONE }, + { AES2501_REG_DEMODPHASE2, DEMODPHASE_NONE }, + { AES2501_REG_CHANGAIN, + AES2501_CHANGAIN_STAGE2_4X | AES2501_CHANGAIN_STAGE1_16X }, + { AES2501_REG_ADREFHI, 0x44 }, + { AES2501_REG_ADREFLO, 0x34 }, + { AES2501_REG_STRTCOL, 0x16 }, + { AES2501_REG_ENDCOL, 0x16 }, + { AES2501_REG_DATFMT, AES2501_DATFMT_BIN_IMG | 0x08 }, + { AES2501_REG_TREG1, 0x70 }, + { 0xa2, 0x02 }, + { 0xa7, 0x00 }, + { AES2501_REG_TREGC, AES2501_TREGC_ENABLE }, + { AES2501_REG_TREGD, 0x1a }, + { 0, 0 }, + { AES2501_REG_CTRL1, AES2501_CTRL1_REG_UPDATE }, + { AES2501_REG_CTRL2, AES2501_CTRL2_SET_ONE_SHOT }, + { AES2501_REG_LPONT, AES2501_LPONT_MIN_VALUE }, +}; + +static void start_finger_detection(struct fp_img_dev *dev); + +static void finger_det_data_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, + enum libusb_urb_cb_status status, unsigned char endpoint, + int rqlength, unsigned char *data, int actual_length, void *user_data) +{ + struct fp_img_dev *dev = user_data; + int i; + int sum = 0; + + libusb_urb_handle_free(urbh); + if (status != FP_URB_COMPLETED) { + fpi_imgdev_session_error(dev, -EIO); + goto out; + } else if (rqlength != actual_length) { + fpi_imgdev_session_error(dev, -EPROTO); + goto out; + } + + /* examine histogram to determine finger presence */ + for (i = 1; i < 9; i++) + sum += (data[i] & 0xf) + (data[i] >> 4); + if (sum > 20) { + /* finger present, start capturing */ + fpi_imgdev_report_finger_status(dev, TRUE); + start_capture(dev); + } else { + /* no finger, poll for a new histogram */ + start_finger_detection(dev); + } + +out: + g_free(data); +} + +static void finger_det_reqs_cb(struct fp_img_dev *dev, int result, + void *user_data) +{ + struct libusb_urb_handle *urbh; + struct libusb_bulk_transfer trf = { + .endpoint = EP_IN, + .length = 20, + }; + + if (result) { + fpi_imgdev_session_error(dev, result); + return; + } + + trf.data = g_malloc(trf.length); + urbh = libusb_async_bulk_transfer(dev->udev, &trf, finger_det_data_cb, + dev, BULK_TIMEOUT); + if (!urbh) { + g_free(trf.data); + fpi_imgdev_session_error(dev, -EIO); + } +} + +static void start_finger_detection(struct fp_img_dev *dev) +{ + struct aes2501_dev *aesdev = dev->priv; + fp_dbg(""); + + if (aesdev->deactivating) { + complete_deactivation(dev); + return; + } + + aes_write_regv(dev, finger_det_reqs, G_N_ELEMENTS(finger_det_reqs), + finger_det_reqs_cb, NULL); +} + +/****** CAPTURE ******/ + +static const struct aes_regwrite capture_reqs_1[] = { + { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, + { 0, 0 }, + { AES2501_REG_EXCITCTRL, 0x40 }, + { AES2501_REG_DETCTRL, + AES2501_DETCTRL_SDELAY_31_MS | AES2501_DETCTRL_DRATE_CONTINUOUS }, + { AES2501_REG_COLSCAN, AES2501_COLSCAN_SRATE_128_US }, + { AES2501_REG_DEMODPHASE2, 0x7c }, + { AES2501_REG_MEASDRV, + AES2501_MEASDRV_MEASURE_SQUARE | AES2501_MEASDRV_MDRIVE_0_325 }, + { AES2501_REG_DEMODPHASE1, 0x24 }, + { AES2501_REG_CHWORD1, 0x00 }, + { AES2501_REG_CHWORD2, 0x6c }, + { AES2501_REG_CHWORD3, 0x09 }, + { AES2501_REG_CHWORD4, 0x54 }, + { AES2501_REG_CHWORD5, 0x78 }, + { 0xa2, 0x02 }, + { 0xa7, 0x00 }, + { 0xb6, 0x26 }, + { 0xb7, 0x1a }, + { AES2501_REG_CTRL1, AES2501_CTRL1_REG_UPDATE }, + { AES2501_REG_IMAGCTRL, + AES2501_IMAGCTRL_TST_REG_ENABLE | AES2501_IMAGCTRL_HISTO_DATA_ENABLE | + AES2501_IMAGCTRL_IMG_DATA_DISABLE }, + { AES2501_REG_STRTCOL, 0x10 }, + { AES2501_REG_ENDCOL, 0x1f }, + { AES2501_REG_CHANGAIN, + AES2501_CHANGAIN_STAGE1_2X | AES2501_CHANGAIN_STAGE2_2X }, + { AES2501_REG_ADREFHI, 0x70 }, + { AES2501_REG_ADREFLO, 0x20 }, + { AES2501_REG_CTRL2, AES2501_CTRL2_SET_ONE_SHOT }, + { AES2501_REG_LPONT, AES2501_LPONT_MIN_VALUE }, +}; + +static const struct aes_regwrite capture_reqs_2[] = { + { AES2501_REG_IMAGCTRL, + AES2501_IMAGCTRL_TST_REG_ENABLE | AES2501_IMAGCTRL_HISTO_DATA_ENABLE | + AES2501_IMAGCTRL_IMG_DATA_DISABLE }, + { AES2501_REG_STRTCOL, 0x10 }, + { AES2501_REG_ENDCOL, 0x1f }, + { AES2501_REG_CHANGAIN, AES2501_CHANGAIN_STAGE1_16X }, + { AES2501_REG_ADREFHI, 0x70 }, + { AES2501_REG_ADREFLO, 0x20 }, + { AES2501_REG_CTRL2, AES2501_CTRL2_SET_ONE_SHOT }, +}; + +static const struct aes_regwrite strip_scan_reqs[] = { + { AES2501_REG_IMAGCTRL, + AES2501_IMAGCTRL_TST_REG_ENABLE | AES2501_IMAGCTRL_HISTO_DATA_ENABLE }, + { AES2501_REG_STRTCOL, 0x00 }, + { AES2501_REG_ENDCOL, 0x2f }, + { AES2501_REG_CHANGAIN, AES2501_CHANGAIN_STAGE1_16X }, + { AES2501_REG_ADREFHI, 0x5b }, + { AES2501_REG_ADREFLO, 0x20 }, + { AES2501_REG_CTRL2, AES2501_CTRL2_SET_ONE_SHOT }, +}; + +/* capture SM movement: + * write reqs and read data 1 + 2, + * request and read strip, + * jump back to request UNLESS theres no finger, in which case exit SM, + * report lack of finger presence, and move to finger detection */ + +enum capture_states { + CAPTURE_WRITE_REQS_1, + CAPTURE_READ_DATA_1, + CAPTURE_WRITE_REQS_2, + CAPTURE_READ_DATA_2, + CAPTURE_REQUEST_STRIP, + CAPTURE_READ_STRIP, + CAPTURE_NUM_STATES, +}; + +static void capture_read_strip_cb(libusb_dev_handle *devh, + libusb_urb_handle *urbh, enum libusb_urb_cb_status status, + unsigned char endpoint, int rqlength, unsigned char *data, + int actual_length, void *user_data) +{ + unsigned char *stripdata; + struct fpi_ssm *ssm = user_data; + struct fp_img_dev *dev = ssm->priv; + struct aes2501_dev *aesdev = dev->priv; + int sum; + int threshold; + + libusb_urb_handle_free(urbh); + if (status != FP_URB_COMPLETED) { + fpi_ssm_mark_aborted(ssm, -EIO); + goto out; + } else if (rqlength != actual_length) { + fpi_ssm_mark_aborted(ssm, -EPROTO); + goto out; + } + + /* FIXME: would preallocating strip buffers be a decent optimization? */ + stripdata = g_malloc(192 * 8); + memcpy(stripdata, data + 1, 192*8); + aesdev->strips = g_slist_prepend(aesdev->strips, stripdata); + aesdev->strips_len++; + + threshold = regval_from_dump(data + 1 + 192*8 + 1 + 16*2 + 1 + 8, + AES2501_REG_DATFMT); + if (threshold < 0) { + fpi_ssm_mark_aborted(ssm, threshold); + goto out; + } + + sum = sum_histogram_values(data + 1 + 192*8, threshold & 0x0f); + if (sum < 0) { + fpi_ssm_mark_aborted(ssm, sum); + goto out; + } + fp_dbg("sum=%d", sum); + + /* FIXME: 0 might be too low as a threshold */ + /* FIXME: sometimes we get 0 in the middle of a scan, should we wait for + * a few consecutive zeroes? */ + /* FIXME: we should have an upper limit on the number of strips */ + + /* If sum is 0, finger has been removed */ + if (sum == 0) { + /* assemble image and submit it to library */ + assemble_and_submit_image(dev); + fpi_imgdev_report_finger_status(dev, FALSE); + /* marking machine complete will re-trigger finger detection loop */ + fpi_ssm_mark_completed(ssm); + } else { + /* obtain next strip */ + fpi_ssm_jump_to_state(ssm, CAPTURE_REQUEST_STRIP); + } + +out: + g_free(data); +} + +static void capture_run_state(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct aes2501_dev *aesdev = dev->priv; + + switch (ssm->cur_state) { + case CAPTURE_WRITE_REQS_1: + aes_write_regv(dev, capture_reqs_1, G_N_ELEMENTS(capture_reqs_1), + generic_write_regv_cb, ssm); + break; + case CAPTURE_READ_DATA_1: + generic_read_ignore_data(ssm, 159); + break; + case CAPTURE_WRITE_REQS_2: + aes_write_regv(dev, capture_reqs_2, G_N_ELEMENTS(capture_reqs_2), + generic_write_regv_cb, ssm); + break; + case CAPTURE_READ_DATA_2: + generic_read_ignore_data(ssm, 159); + break; + case CAPTURE_REQUEST_STRIP: + if (aesdev->deactivating) + fpi_ssm_mark_completed(ssm); + else + aes_write_regv(dev, strip_scan_reqs, G_N_ELEMENTS(strip_scan_reqs), + generic_write_regv_cb, ssm); + break; + case CAPTURE_READ_STRIP: ; + struct libusb_urb_handle *urbh; + struct libusb_bulk_transfer trf = { + .endpoint = EP_IN, + .data = g_malloc(1705), + .length = 1705, + }; + urbh = libusb_async_bulk_transfer(dev->udev, &trf, + capture_read_strip_cb, ssm, BULK_TIMEOUT); + if (!urbh) { + g_free(trf.data); + fpi_ssm_mark_aborted(ssm, -EIO); + } + break; + }; +} + +static void capture_sm_complete(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct aes2501_dev *aesdev = dev->priv; + + fp_dbg(""); + if (aesdev->deactivating) + complete_deactivation(dev); + else if (ssm->error) + fpi_imgdev_session_error(dev, ssm->error); + else + start_finger_detection(dev); + fpi_ssm_free(ssm); +} + +static void start_capture(struct fp_img_dev *dev) +{ + struct aes2501_dev *aesdev = dev->priv; + struct fpi_ssm *ssm; + + if (aesdev->deactivating) { + complete_deactivation(dev); + return; + } + + ssm = fpi_ssm_new(dev->dev, capture_run_state, CAPTURE_NUM_STATES); + fp_dbg(""); + ssm->priv = dev; + fpi_ssm_start(ssm, capture_sm_complete); +} + +/****** INITIALIZATION/DEINITIALIZATION ******/ + static const struct aes_regwrite init_1[] = { { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, { 0, 0 }, @@ -187,55 +758,146 @@ static const struct aes_regwrite init_5[] = { { AES2501_REG_CTRL1, AES2501_CTRL1_SCAN_RESET }, }; -static int do_init(struct fp_img_dev *dev) +enum activate_states { + WRITE_INIT_1, + READ_DATA_1, + WRITE_INIT_2, + READ_REGS, + WRITE_INIT_3, + WRITE_INIT_4, + WRITE_INIT_5, + ACTIVATE_NUM_STATES, +}; + +void activate_read_regs_cb(struct fp_img_dev *dev, int status, + unsigned char *regs, void *user_data) { - unsigned char buffer[128]; - int r; - int i; + struct fpi_ssm *ssm = user_data; + struct aes2501_dev *aesdev = dev->priv; - /* part 1, probably not needed */ - r = aes_write_regv(dev, init_1, G_N_ELEMENTS(init_1)); - if (r < 0) - return r; - - r = read_data(dev, buffer, 20); - if (r < 0) - return r; - - /* part 2 */ - r = aes_write_regv(dev, init_2, G_N_ELEMENTS(init_2)); - if (r < 0) - return r; - - r = read_regs(dev, buffer); - if (r < 0) - return r; - - /* part 3 */ - fp_dbg("reg 0xaf = %x", buffer[0x5f]); - i = 0; - while (buffer[0x5f] == 0x6b) { - r = aes_write_regv(dev, init_3, G_N_ELEMENTS(init_3)); - if (r < 0) - return r; - r = read_regs(dev, buffer); - if (r < 0) - return r; - if (++i == 13) - break; + if (status != 0) { + fpi_ssm_mark_aborted(ssm, status); + } else { + fp_dbg("reg 0xaf = %x", regs[0x5f]); + if (regs[0x5f] != 0x6b || ++aesdev->read_regs_retry_count == 13) + fpi_ssm_jump_to_state(ssm, WRITE_INIT_4); + else + fpi_ssm_next_state(ssm); } +} - /* part 4 */ - r = aes_write_regv(dev, init_4, G_N_ELEMENTS(init_4)); - if (r < 0) - return r; +static void activate_init3_cb(struct fp_img_dev *dev, int result, + void *user_data) +{ + struct fpi_ssm *ssm = user_data; + if (result == 0) + fpi_ssm_jump_to_state(ssm, READ_REGS); + else + fpi_ssm_mark_aborted(ssm, result); +} - /* part 5 */ - return aes_write_regv(dev, init_5, G_N_ELEMENTS(init_5)); +static void activate_run_state(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + + /* This state machine isn't as linear as it may appear. After doing init1 + * and init2 register configuration writes, we have to poll a register + * waiting for a specific value. READ_REGS checks the register value, and + * if we're ready to move on, we jump to init4. Otherwise, we write init3 + * and then jump back to READ_REGS. In a synchronous model: + + [...] + aes_write_regv(init_2); + read_regs(into buffer); + i = 0; + while (buffer[0x5f] == 0x6b) { + aes_write_regv(init_3); + read_regs(into buffer); + if (++i == 13) + break; + } + aes_write_regv(init_4); + */ + + switch (ssm->cur_state) { + case WRITE_INIT_1: + aes_write_regv(dev, init_1, G_N_ELEMENTS(init_1), + generic_write_regv_cb, ssm); + break; + case READ_DATA_1: + fp_dbg("read data 1"); + generic_read_ignore_data(ssm, 20); + break; + case WRITE_INIT_2: + aes_write_regv(dev, init_2, G_N_ELEMENTS(init_2), + generic_write_regv_cb, ssm); + break; + case READ_REGS: + read_regs(dev, activate_read_regs_cb, ssm); + break; + case WRITE_INIT_3: + aes_write_regv(dev, init_4, G_N_ELEMENTS(init_4), + activate_init3_cb, ssm); + break; + case WRITE_INIT_4: + aes_write_regv(dev, init_4, G_N_ELEMENTS(init_4), + generic_write_regv_cb, ssm); + break; + case WRITE_INIT_5: + aes_write_regv(dev, init_5, G_N_ELEMENTS(init_5), + generic_write_regv_cb, ssm); + break; + } +} + +static void activate_sm_complete(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + fp_dbg("status %d", ssm->error); + fpi_imgdev_activate_complete(dev, ssm->error); + + if (!ssm->error) + start_finger_detection(dev); + fpi_ssm_free(ssm); +} + +static int dev_activate(struct fp_img_dev *dev, enum fp_imgdev_state state) +{ + struct aes2501_dev *aesdev = dev->priv; + struct fpi_ssm *ssm = fpi_ssm_new(dev->dev, activate_run_state, + ACTIVATE_NUM_STATES); + ssm->priv = dev; + aesdev->read_regs_retry_count = 0; + fpi_ssm_start(ssm, activate_sm_complete); + return 0; +} + +static void dev_deactivate(struct fp_img_dev *dev) +{ + struct aes2501_dev *aesdev = dev->priv; + /* FIXME: audit cancellation points, probably need more, specifically + * in error handling paths? */ + aesdev->deactivating = TRUE; +} + +static void complete_deactivation(struct fp_img_dev *dev) +{ + struct aes2501_dev *aesdev = dev->priv; + fp_dbg(""); + + /* FIXME: if we're in the middle of a scan, we should cancel the scan. + * maybe we can do this with a master reset, unconditionally? */ + + aesdev->deactivating = FALSE; + g_slist_free(aesdev->strips); + aesdev->strips = NULL; + aesdev->strips_len = 0; + fpi_imgdev_deactivate_complete(dev); } static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) { + /* FIXME check endpoints */ int r; r = libusb_claim_interface(dev->udev, 0); @@ -244,332 +906,16 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) return r; } - /* FIXME check endpoints */ - - return do_init(dev); -} - -static void dev_exit(struct fp_img_dev *dev) -{ - libusb_release_interface(dev->udev, 0); -} - -static const struct aes_regwrite finger_det_reqs[] = { - { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, - { AES2501_REG_EXCITCTRL, 0x40 }, - { AES2501_REG_DETCTRL, - AES2501_DETCTRL_DRATE_CONTINUOUS | AES2501_DETCTRL_SDELAY_31_MS }, - { AES2501_REG_COLSCAN, AES2501_COLSCAN_SRATE_128_US }, - { AES2501_REG_MEASDRV, AES2501_MEASDRV_MDRIVE_0_325 | AES2501_MEASDRV_MEASURE_SQUARE }, - { AES2501_REG_MEASFREQ, AES2501_MEASFREQ_2M }, - { AES2501_REG_DEMODPHASE1, DEMODPHASE_NONE }, - { AES2501_REG_DEMODPHASE2, DEMODPHASE_NONE }, - { AES2501_REG_CHANGAIN, - AES2501_CHANGAIN_STAGE2_4X | AES2501_CHANGAIN_STAGE1_16X }, - { AES2501_REG_ADREFHI, 0x44 }, - { AES2501_REG_ADREFLO, 0x34 }, - { AES2501_REG_STRTCOL, 0x16 }, - { AES2501_REG_ENDCOL, 0x16 }, - { AES2501_REG_DATFMT, AES2501_DATFMT_BIN_IMG | 0x08 }, - { AES2501_REG_TREG1, 0x70 }, - { 0xa2, 0x02 }, - { 0xa7, 0x00 }, - { AES2501_REG_TREGC, AES2501_TREGC_ENABLE }, - { AES2501_REG_TREGD, 0x1a }, - { 0, 0 }, - { AES2501_REG_CTRL1, AES2501_CTRL1_REG_UPDATE }, - { AES2501_REG_CTRL2, AES2501_CTRL2_SET_ONE_SHOT }, - { AES2501_REG_LPONT, AES2501_LPONT_MIN_VALUE }, -}; - -static int detect_finger(struct fp_img_dev *dev) -{ - unsigned char buffer[22]; - int r; - int i; - int sum = 0; - - r = aes_write_regv(dev, finger_det_reqs, G_N_ELEMENTS(finger_det_reqs)); - if (r < 0) - return r; - - r = read_data(dev, buffer, 20); - if (r < 0) - return r; - - for (i = 1; i < 9; i++) - sum += (buffer[i] & 0xf) + (buffer[i] >> 4); - - return sum > 20; -} - -static int await_finger_on(struct fp_img_dev *dev) -{ - int r; - do { - r = detect_finger(dev); - } while (r == 0); - return (r < 0) ? r : 0; -} - -/* Read the value of a specific register from a register dump */ -static int regval_from_dump(unsigned char *data, uint8_t target) -{ - if (*data != FIRST_AES2501_REG) { - fp_err("not a register dump"); - return -EILSEQ; - } - - if (!(FIRST_AES2501_REG <= target && target <= LAST_AES2501_REG)) { - fp_err("out of range"); - return -EINVAL; - } - - target -= FIRST_AES2501_REG; - target *= 2; - return data[target + 1]; -} - -static int sum_histogram_values(unsigned char *data, uint8_t threshold) -{ - int r = 0; - int i; - uint16_t *histogram = (uint16_t *)(data + 1); - - if (*data != 0xde) - return -EILSEQ; - - if (threshold > 0x0f) - return -EINVAL; - - /* FIXME endianness */ - for (i = threshold; i < 16; i++) - r += histogram[i]; - - return r; -} - -/* find overlapping parts of frames */ -static unsigned int find_overlap(unsigned char *first_frame, - unsigned char *second_frame, unsigned int *min_error) -{ - unsigned int dy; - unsigned int not_overlapped_height = 0; - *min_error = 255 * FRAME_SIZE; - for (dy = 0; dy < FRAME_HEIGHT; dy++) { - /* Calculating difference (error) between parts of frames */ - unsigned int i; - unsigned int error = 0; - for (i = 0; i < FRAME_WIDTH * (FRAME_HEIGHT - dy); i++) { - /* Using ? operator to avoid abs function */ - error += first_frame[i] > second_frame[i] ? - (first_frame[i] - second_frame[i]) : - (second_frame[i] - first_frame[i]); - } - - /* Normalize error */ - error *= 15; - error /= i; - if (error < *min_error) { - *min_error = error; - not_overlapped_height = dy; - } - first_frame += FRAME_WIDTH; - } - - return not_overlapped_height; -} - -/* assemble a series of frames into a single image */ -static unsigned int assemble(unsigned char *input, unsigned char *output, - int num_strips, gboolean reverse, unsigned int *errors_sum) -{ - uint8_t *assembled = output; - int frame; - uint32_t image_height = FRAME_HEIGHT; - unsigned int min_error; - *errors_sum = 0; - - if (num_strips < 1) - return 0; - - /* Rotating given data by 90 degrees - * Taken from document describing aes2501 image format - * TODO: move reversing detection here */ - - if (reverse) - output += (num_strips - 1) * FRAME_SIZE; - for (frame = 0; frame < num_strips; frame++) { - aes_assemble_image(input, FRAME_WIDTH, FRAME_HEIGHT, output); - input += FRAME_WIDTH * (FRAME_HEIGHT / 2); - - if (reverse) - output -= FRAME_SIZE; - else - output += FRAME_SIZE; - } - - /* Detecting where frames overlaped */ - output = assembled; - for (frame = 1; frame < num_strips; frame++) { - int not_overlapped; - - output += FRAME_SIZE; - not_overlapped = find_overlap(assembled, output, &min_error); - *errors_sum += min_error; - image_height += not_overlapped; - assembled += FRAME_WIDTH * not_overlapped; - memcpy(assembled, output, FRAME_SIZE); - } - return image_height; -} - -static const struct aes_regwrite capture_reqs_1[] = { - { AES2501_REG_CTRL1, AES2501_CTRL1_MASTER_RESET }, - { 0, 0 }, - { AES2501_REG_EXCITCTRL, 0x40 }, - { AES2501_REG_DETCTRL, - AES2501_DETCTRL_SDELAY_31_MS | AES2501_DETCTRL_DRATE_CONTINUOUS }, - { AES2501_REG_COLSCAN, AES2501_COLSCAN_SRATE_128_US }, - { AES2501_REG_DEMODPHASE2, 0x7c }, - { AES2501_REG_MEASDRV, - AES2501_MEASDRV_MEASURE_SQUARE | AES2501_MEASDRV_MDRIVE_0_325 }, - { AES2501_REG_DEMODPHASE1, 0x24 }, - { AES2501_REG_CHWORD1, 0x00 }, - { AES2501_REG_CHWORD2, 0x6c }, - { AES2501_REG_CHWORD3, 0x09 }, - { AES2501_REG_CHWORD4, 0x54 }, - { AES2501_REG_CHWORD5, 0x78 }, - { 0xa2, 0x02 }, - { 0xa7, 0x00 }, - { 0xb6, 0x26 }, - { 0xb7, 0x1a }, - { AES2501_REG_CTRL1, AES2501_CTRL1_REG_UPDATE }, - { AES2501_REG_IMAGCTRL, - AES2501_IMAGCTRL_TST_REG_ENABLE | AES2501_IMAGCTRL_HISTO_DATA_ENABLE | - AES2501_IMAGCTRL_IMG_DATA_DISABLE }, - { AES2501_REG_STRTCOL, 0x10 }, - { AES2501_REG_ENDCOL, 0x1f }, - { AES2501_REG_CHANGAIN, - AES2501_CHANGAIN_STAGE1_2X | AES2501_CHANGAIN_STAGE2_2X }, - { AES2501_REG_ADREFHI, 0x70 }, - { AES2501_REG_ADREFLO, 0x20 }, - { AES2501_REG_CTRL2, AES2501_CTRL2_SET_ONE_SHOT }, - { AES2501_REG_LPONT, AES2501_LPONT_MIN_VALUE }, -}; - -static const struct aes_regwrite capture_reqs_2[] = { - { AES2501_REG_IMAGCTRL, - AES2501_IMAGCTRL_TST_REG_ENABLE | AES2501_IMAGCTRL_HISTO_DATA_ENABLE | - AES2501_IMAGCTRL_IMG_DATA_DISABLE }, - { AES2501_REG_STRTCOL, 0x10 }, - { AES2501_REG_ENDCOL, 0x1f }, - { AES2501_REG_CHANGAIN, AES2501_CHANGAIN_STAGE1_16X }, - { AES2501_REG_ADREFHI, 0x70 }, - { AES2501_REG_ADREFLO, 0x20 }, - { AES2501_REG_CTRL2, AES2501_CTRL2_SET_ONE_SHOT }, -}; - -static const struct aes_regwrite strip_scan_reqs[] = { - { AES2501_REG_IMAGCTRL, - AES2501_IMAGCTRL_TST_REG_ENABLE | AES2501_IMAGCTRL_HISTO_DATA_ENABLE }, - { AES2501_REG_STRTCOL, 0x00 }, - { AES2501_REG_ENDCOL, 0x2f }, - { AES2501_REG_CHANGAIN, AES2501_CHANGAIN_STAGE1_16X }, - { AES2501_REG_ADREFHI, 0x5b }, - { AES2501_REG_ADREFLO, 0x20 }, - { AES2501_REG_CTRL2, AES2501_CTRL2_SET_ONE_SHOT }, -}; - -static int capture(struct fp_img_dev *dev, gboolean unconditional, - struct fp_img **ret) -{ - int r; - struct fp_img *img; - unsigned int nstrips; - unsigned int errors_sum, r_errors_sum; - unsigned char *cooked; - unsigned char *imgptr; - unsigned char buf[1705]; - int final_size; - int sum; - - /* FIXME can do better here in terms of buffer management? */ - fp_dbg(""); - - r = aes_write_regv(dev, capture_reqs_1, G_N_ELEMENTS(capture_reqs_1)); - if (r < 0) - return r; - - r = read_data(dev, buf, 159); - if (r < 0) - return r; - - r = aes_write_regv(dev, capture_reqs_2, G_N_ELEMENTS(capture_reqs_2)); - if (r < 0) - return r; - - r = read_data(dev, buf, 159); - if (r < 0) - return r; - - /* FIXME: use histogram data above for gain calibration (0x8e xx) */ - - img = fpi_img_new((3 * MAX_FRAMES * FRAME_SIZE) / 2); - imgptr = img->data; - cooked = imgptr + (MAX_FRAMES * FRAME_SIZE) / 2; - - for (nstrips = 0; nstrips < MAX_FRAMES; nstrips++) { - int threshold; - - r = aes_write_regv(dev, strip_scan_reqs, G_N_ELEMENTS(strip_scan_reqs)); - if (r < 0) - goto err; - r = read_data(dev, buf, 1705); - if (r < 0) - goto err; - memcpy(imgptr, buf + 1, 192*8); - imgptr += 192*8; - - threshold = regval_from_dump((buf + 1 + 192*8 + 1 + 16*2 + 1 + 8), - AES2501_REG_DATFMT); - if (threshold < 0) { - r = threshold; - goto err; - } - - sum = sum_histogram_values((buf + 1 + 192*8), threshold & 0x0f); - if (sum < 0) { - r = sum; - goto err; - } - fp_dbg("sum=%d", sum); - if (sum == 0) - break; - } - if (nstrips == MAX_FRAMES) - fp_warn("swiping finger too slow?"); - - img->flags = FP_IMG_COLORS_INVERTED; - img->height = assemble(img->data, cooked, nstrips, FALSE, &errors_sum); - img->height = assemble(img->data, cooked, nstrips, TRUE, &r_errors_sum); - - if (r_errors_sum > errors_sum) { - img->height = assemble(img->data, cooked, nstrips, FALSE, &errors_sum); - img->flags |= FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED; - fp_dbg("normal scan direction"); - } else { - fp_dbg("reversed scan direction"); - } - - final_size = img->height * FRAME_WIDTH; - memcpy(img->data, cooked, final_size); - img = fpi_img_resize(img, final_size); - *ret = img; + dev->priv = g_malloc0(sizeof(struct aes2501_dev)); + fpi_imgdev_init_complete(dev, 0); return 0; -err: - fp_img_free(img); - return r; +} + +static void dev_deinit(struct fp_img_dev *dev) +{ + g_free(dev->priv); + libusb_release_interface(dev->udev, 0); + fpi_imgdev_deinit_complete(dev); } static const struct usb_id id_table[] = { @@ -589,8 +935,8 @@ struct fp_img_driver aes2501_driver = { .img_width = 192, .init = dev_init, - .exit = dev_exit, - .await_finger_on = await_finger_on, - .capture = capture, + .deinit = dev_deinit, + .activate = dev_activate, + .deactivate = dev_deactivate, }; From 866dd941cc85b28ff5f0ec80b7f3696150efa50f Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 16 Feb 2008 12:44:50 +0000 Subject: [PATCH 103/184] Add timing and polling infrastructure Add timeout mechanism as an asynchronous equivalent of sleeping (uru4000 needs this). Start implementing polling infrastructure which also accounts for pending timeouts. We don't expose file descriptors yet, but this is a start. --- configure.ac | 1 + libfprint/Makefile.am | 1 + libfprint/core.c | 28 ++--- libfprint/fp_internal.h | 8 ++ libfprint/fprint.h | 5 + libfprint/poll.c | 247 ++++++++++++++++++++++++++++++++++++++++ 6 files changed, 277 insertions(+), 13 deletions(-) create mode 100644 libfprint/poll.c diff --git a/configure.ac b/configure.ac index c6fa8287..44dc151d 100644 --- a/configure.ac +++ b/configure.ac @@ -8,6 +8,7 @@ AC_PROG_CC AC_PROG_LIBTOOL AC_C_INLINE AM_PROG_CC_C_O +AC_DEFINE([_GNU_SOURCE], [], [Use GNU extensions]) # Library versioning lt_major="0" diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 70aea683..9b014205 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -59,6 +59,7 @@ libfprint_la_SOURCES = \ drv.c \ img.c \ imgdev.c \ + poll.c \ aeslib.c \ aeslib.h \ $(DRIVER_SRC) \ diff --git a/libfprint/core.c b/libfprint/core.c index d6298117..43d92c99 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -598,7 +598,7 @@ API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) } while (dev->state == DEV_STATE_INITIALIZING) - if (libusb_poll() < 0) + if (fp_handle_events() < 0) goto err_deinit; if (dev->state != DEV_STATE_INITIALIZED) goto err_deinit; @@ -609,7 +609,7 @@ API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) err_deinit: fpi_drv_deinit(dev); while (dev->state == DEV_STATE_DEINITIALIZING) { - if (libusb_poll() < 0) + if (fp_handle_events() < 0) break; } err: @@ -623,7 +623,7 @@ static void do_close(struct fp_dev *dev) { fpi_drv_deinit(dev); while (dev->state == DEV_STATE_DEINITIALIZING) - if (libusb_poll() < 0) + if (fp_handle_events() < 0) break; libusb_close(dev->udev); @@ -936,7 +936,7 @@ API_EXPORTED int fp_enroll_finger_img(struct fp_dev *dev, return r; } while (dev->state == DEV_STATE_ENROLL_STARTING) { - r = libusb_poll(); + r = fp_handle_events(); if (r < 0) goto err; } @@ -961,7 +961,7 @@ API_EXPORTED int fp_enroll_finger_img(struct fp_dev *dev, edata = dev->enroll_data; while (!edata->populated) { - r = libusb_poll(); + r = fp_handle_events(); if (r < 0) { g_free(edata); goto err; @@ -1017,7 +1017,7 @@ out: fp_dbg("ending enrollment"); if (fpi_drv_enroll_stop(dev) == 0) while (dev->state == DEV_STATE_ENROLL_STOPPING) { - if (libusb_poll() < 0) + if (fp_handle_events() < 0) break; } g_free(dev->enroll_data); @@ -1028,7 +1028,7 @@ out: err: if (fpi_drv_enroll_stop(dev) == 0) while (dev->state == DEV_STATE_ENROLL_STOPPING) - if (libusb_poll() < 0) + if (fp_handle_events() < 0) break; return r; } @@ -1091,7 +1091,7 @@ API_EXPORTED int fp_verify_finger_img(struct fp_dev *dev, return r; } while (dev->state == DEV_STATE_VERIFY_STARTING) { - r = libusb_poll(); + r = fp_handle_events(); if (r < 0) goto err; } @@ -1104,7 +1104,7 @@ API_EXPORTED int fp_verify_finger_img(struct fp_dev *dev, vdata = dev->sync_verify_data; while (!vdata->populated) { - r = libusb_poll(); + r = fp_handle_events(); if (r < 0) { g_free(vdata); goto err; @@ -1146,7 +1146,7 @@ err: fp_dbg("ending verification"); if (fpi_drv_verify_stop(dev) == 0) { while (dev->state == DEV_STATE_VERIFY_STOPPING) { - if (libusb_poll() < 0) + if (fp_handle_events() < 0) break; } } @@ -1222,7 +1222,7 @@ API_EXPORTED int fp_identify_finger_img(struct fp_dev *dev, return r; } while (dev->state == DEV_STATE_IDENTIFY_STARTING) { - r = libusb_poll(); + r = fp_handle_events(); if (r < 0) goto err; } @@ -1235,7 +1235,7 @@ API_EXPORTED int fp_identify_finger_img(struct fp_dev *dev, idata = dev->sync_identify_data; while (!idata->populated) { - r = libusb_poll(); + r = fp_handle_events(); if (r < 0) { g_free(idata); goto err; @@ -1277,7 +1277,7 @@ API_EXPORTED int fp_identify_finger_img(struct fp_dev *dev, err: if (fpi_drv_identify_stop(dev) == 0) { while (dev->state == DEV_STATE_IDENTIFY_STOPPING) { - if (libusb_poll() < 0) + if (fp_handle_events() < 0) break; } } @@ -1323,8 +1323,10 @@ API_EXPORTED void fp_exit(void) } fpi_data_exit(); + fpi_poll_exit(); g_slist_free(registered_drivers); registered_drivers = NULL; libusb_exit(); } + diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index dc6a5036..ee1230b9 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -319,6 +319,14 @@ int fpi_img_compare_print_data(struct fp_print_data *enrolled_print, int fpi_img_compare_print_data_to_gallery(struct fp_print_data *print, struct fp_print_data **gallery, int match_threshold, size_t *match_offset); +/* polling and timeouts */ + +void fpi_poll_exit(void); + +typedef void (*fpi_timeout_fn)(void *data); + +int fpi_timeout_add(unsigned int msec, fpi_timeout_fn callback, void *data); + /* async drv <--> lib comms */ struct fpi_ssm; diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 2b855840..f7626756 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -21,6 +21,7 @@ #define __FPRINT_H__ #include +#include /* structs that applications are not allowed to peek into */ struct fp_dscv_dev; @@ -265,6 +266,10 @@ struct fp_img *fp_img_binarize(struct fp_img *img); struct fp_minutia **fp_img_get_minutiae(struct fp_img *img, int *nr_minutiae); void fp_img_free(struct fp_img *img); +/* Polling and timing */ +int fp_handle_events_timeout(struct timeval *timeout); +int fp_handle_events(void); + /* Library */ int fp_init(void); void fp_exit(void); diff --git a/libfprint/poll.c b/libfprint/poll.c new file mode 100644 index 00000000..6355f5cf --- /dev/null +++ b/libfprint/poll.c @@ -0,0 +1,247 @@ +/* + * Polling/timing management + * Copyright (C) 2008 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#define FP_COMPONENT "poll" + +#include +#include +#include +#include + +#include +#include + +#include "fp_internal.h" + +/** + * @defgroup poll Polling and timing operations + * These functions are only applicable to users of libfprint's asynchronous + * API. + * + * libfprint does not create internal library threads and hence can only + * execute when your application is calling a libfprint function. However, + * libfprint often has work to be do, such as handling of completed USB + * transfers, and processing of timeouts required in order for the library + * to function. Therefore it is essential that your own application must + * regularly "phone into" libfprint so that libfprint can handle any pending + * events. + * + * The function you must call is fp_handle_events() or a variant of it. This + * function will handle any pending events, and it is from this context that + * all asynchronous event callbacks from the library will occur. You can view + * this function as a kind of iteration function. + * + * If there are no events pending, fp_handle_events() will block for a few + * seconds (and will handle any new events should anything occur in that time). + * If you wish to customise this timeout, you can use + * fp_handle_events_timeout() instead. If you wish to do a nonblocking + * iteration, call fp_handle_events_timeout() with a zero timeout. + * + * TODO: document how application is supposed to know when to call these + * functions. + */ + +/* this is a singly-linked list of pending timers, sorted with the timer that + * is expiring soonest at the head. */ +static GSList *active_timers = NULL; + +struct fpi_timeout { + struct timeval expiry; + fpi_timeout_fn callback; + void *data; +}; + +void fpi_poll_exit(void) +{ + g_slist_free(active_timers); + active_timers = NULL; +} + +static int timeout_sort_fn(gconstpointer _a, gconstpointer _b) +{ + struct fpi_timeout *a = (struct fpi_timeout *) _a; + struct fpi_timeout *b = (struct fpi_timeout *) _b; + struct timeval *tv_a = &a->expiry; + struct timeval *tv_b = &b->expiry; + + if (timercmp(tv_a, tv_b, <)) + return -1; + else if (timercmp(tv_a, tv_b, >)) + return 1; + else + return 0; +} + +/* A timeout is the asynchronous equivalent of sleeping. You create a timeout + * saying that you'd like to have a function invoked at a certain time in + * the future. */ +int fpi_timeout_add(unsigned int msec, fpi_timeout_fn callback, void *data) +{ + struct timespec ts; + struct timeval add_msec; + struct fpi_timeout *timeout; + int r; + + fp_dbg("in %dms", msec); + + r = clock_gettime(CLOCK_MONOTONIC, &ts); + if (r < 0) { + fp_err("failed to read monotonic clock, errno=%d", errno); + return r; + } + + timeout = g_malloc(sizeof(*timeout)); + timeout->callback = callback; + timeout->data = data; + TIMESPEC_TO_TIMEVAL(&timeout->expiry, &ts); + + /* calculate timeout expiry by adding delay to current monotonic clock */ + timerclear(&add_msec); + add_msec.tv_sec = msec / 1000; + add_msec.tv_usec = (msec % 1000) * 1000; + timeradd(&timeout->expiry, &add_msec, &timeout->expiry); + + active_timers = g_slist_insert_sorted(active_timers, timeout, + timeout_sort_fn); + + return 0; +} + +/* get the expiry time and optionally the timeout structure for the next + * timeout. returns 0 if there are no expired timers, or 1 if the + * timeval/timeout output parameters were populated. if the returned timeval + * is zero then it means the timeout has already expired and should be handled + * ASAP. */ +static int get_next_timeout_expiry(struct timeval *out, + struct fpi_timeout **out_timeout) +{ + struct timespec ts; + struct timeval tv; + struct fpi_timeout *next_timeout; + int r; + + if (active_timers == NULL) + return 0; + + r = clock_gettime(CLOCK_MONOTONIC, &ts); + if (r < 0) { + fp_err("failed to read monotonic clock, errno=%d", errno); + return r; + } + TIMESPEC_TO_TIMEVAL(&tv, &ts); + + next_timeout = active_timers->data; + if (out_timeout) + *out_timeout = next_timeout; + + if (timercmp(&tv, &next_timeout->expiry, >=)) { + fp_dbg("first timeout already expired"); + timerclear(out); + } else { + timersub(&next_timeout->expiry, &tv, out); + fp_dbg("next timeout in %d.%06ds", out->tv_sec, out->tv_usec); + } + + return 1; +} + +/* handle a timeout that has expired */ +static void handle_timeout(struct fpi_timeout *timeout) +{ + fp_dbg(""); + timeout->callback(timeout->data); + active_timers = g_slist_remove(active_timers, timeout); + g_free(timeout); +} + +static int handle_timeouts(void) +{ + struct timeval next_timeout_expiry; + struct fpi_timeout *next_timeout; + int r; + + r = get_next_timeout_expiry(&next_timeout_expiry, &next_timeout); + if (r <= 0) + return r; + + if (!timerisset(&next_timeout_expiry)) + handle_timeout(next_timeout); + + return 0; +} + +/** \ingroup poll + * Handle any pending events. If a non-zero timeout is specified, the function + * will potentially block for the specified amount of time, although it may + * return sooner if events have been handled. The function acts as non-blocking + * for a zero timeout. + * + * \param timeout Maximum timeout for this blocking function + * \returns 0 on success, non-zero on error. + */ +API_EXPORTED int fp_handle_events_timeout(struct timeval *timeout) +{ + struct timeval next_timeout_expiry; + struct timeval select_timeout; + struct fpi_timeout *next_timeout; + int r; + + r = get_next_timeout_expiry(&next_timeout_expiry, &next_timeout); + if (r < 0) + return r; + + if (r) { + /* timer already expired? */ + if (!timerisset(&next_timeout_expiry)) { + handle_timeout(next_timeout); + return 0; + } + + /* choose the smallest of next URB timeout or user specified timeout */ + if (timercmp(&next_timeout_expiry, timeout, <)) + select_timeout = next_timeout_expiry; + else + select_timeout = *timeout; + } else { + select_timeout = *timeout; + } + + r = libusb_poll_timeout(&select_timeout); + *timeout = select_timeout; + if (r < 0) + return r; + + return handle_timeouts(); +} + +/** \ingroup poll + * Convenience function for calling fp_handle_events_timeout() with a sensible + * default timeout value of two seconds (subject to change if we decide another + * value is more sensible). + * + * \returns 0 on success, non-zero on error. + */ +API_EXPORTED int fp_handle_events(void) +{ + struct timeval tv; + tv.tv_sec = 2; + tv.tv_usec = 0; + return fp_handle_events_timeout(&tv); +} + From b8dc77b56e89194a185a4d3db1e830459e551c5d Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 18 Feb 2008 17:50:48 +0000 Subject: [PATCH 104/184] Fix verify/identify error handling If verify_start failed, we need to run verify_stop. Same for identification. --- libfprint/drv.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/libfprint/drv.c b/libfprint/drv.c index f1cc6c5a..3055e99e 100644 --- a/libfprint/drv.c +++ b/libfprint/drv.c @@ -17,6 +17,8 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ +#define FP_COMPONENT "drv" + #include #include "fp_internal.h" @@ -185,7 +187,8 @@ int fpi_drv_verify_stop(struct fp_dev *dev) gboolean iterating = (dev->state == DEV_STATE_VERIFYING); fp_dbg(""); - BUG_ON(dev->state != DEV_STATE_VERIFYING + BUG_ON(dev->state != DEV_STATE_ERROR + && dev->state != DEV_STATE_VERIFYING && dev->state != DEV_STATE_VERIFY_DONE); dev->verify_cb = NULL; @@ -243,7 +246,8 @@ void fpi_drvcb_report_identify_result(struct fp_dev *dev, int result, size_t match_offset, struct fp_img *img) { fp_dbg("result %d", result); - BUG_ON(dev->state != DEV_STATE_IDENTIFYING); + BUG_ON(dev->state != DEV_STATE_IDENTIFYING + && dev->state != DEV_STATE_ERROR); if (result < 0 || result == FP_VERIFY_NO_MATCH || result == FP_VERIFY_MATCH) { dev->state = DEV_STATE_IDENTIFY_DONE; From 754e56aec1e78d02d9f984402be33df931350d1b Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 18 Feb 2008 17:54:15 +0000 Subject: [PATCH 105/184] Allow execution of sub-SSMs A subssm will be executed, and upon completion the parent state machine will either be advanced to the next state or aborted with error, depending on the outcome of the subssm. Also add some debug messages. --- libfprint/drv.c | 23 +++++++++++++++++++++++ libfprint/fp_internal.h | 2 ++ 2 files changed, 25 insertions(+) diff --git a/libfprint/drv.c b/libfprint/drv.c index 3055e99e..9ee54cfe 100644 --- a/libfprint/drv.c +++ b/libfprint/drv.c @@ -360,6 +360,7 @@ void fpi_ssm_free(struct fpi_ssm *machine) /* Invoke the state handler */ static void __ssm_call_handler(struct fpi_ssm *machine) { + fp_dbg("%p entering state %d", machine, machine->cur_state); machine->handler(machine); } @@ -374,11 +375,33 @@ void fpi_ssm_start(struct fpi_ssm *ssm, ssm_completed_fn callback) __ssm_call_handler(ssm); } +static void __subsm_complete(struct fpi_ssm *ssm) +{ + struct fpi_ssm *parent = ssm->parentsm; + BUG_ON(!parent); + if (ssm->error) + fpi_ssm_mark_aborted(parent, ssm->error); + else + fpi_ssm_next_state(parent); + fpi_ssm_free(ssm); +} + +/* start a SSM as a child of another. if the child completes successfully, the + * parent will be advanced to the next state. if the child aborts, the parent + * will be aborted with the same error code. the child will be automatically + * freed upon completion/abortion. */ +void fpi_ssm_start_subsm(struct fpi_ssm *parent, struct fpi_ssm *child) +{ + child->parentsm = parent; + fpi_ssm_start(child, __subsm_complete); +} + /* Mark a ssm as completed successfully. */ void fpi_ssm_mark_completed(struct fpi_ssm *machine) { BUG_ON(machine->completed); machine->completed = TRUE; + fp_dbg("%p completed with status %d", machine, machine->error); if (machine->callback) machine->callback(machine); } diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index ee1230b9..e9676e86 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -338,6 +338,7 @@ typedef void (*ssm_handler_fn)(struct fpi_ssm *ssm); * abortion error conditions. */ struct fpi_ssm { struct fp_dev *dev; + struct fpi_ssm *parentsm; void *priv; int nr_states; int cur_state; @@ -353,6 +354,7 @@ struct fpi_ssm *fpi_ssm_new(struct fp_dev *dev, ssm_handler_fn handler, int nr_states); void fpi_ssm_free(struct fpi_ssm *machine); void fpi_ssm_start(struct fpi_ssm *machine, ssm_completed_fn callback); +void fpi_ssm_start_subsm(struct fpi_ssm *parent, struct fpi_ssm *child); int fpi_ssm_has_completed(struct fpi_ssm *machine); /* for drivers */ From 83f9da1b874ce31ea69d21a2079b909c0f1f5343 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sun, 17 Feb 2008 00:08:56 +0000 Subject: [PATCH 106/184] uru4000: port to asynchronous model --- libfprint/Makefile.am | 4 +- libfprint/core.c | 4 +- libfprint/drivers/uru4000.c | 1267 +++++++++++++++++++++++------------ 3 files changed, 825 insertions(+), 450 deletions(-) diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 9b014205..1bef2461 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -8,8 +8,8 @@ AES2501_SRC = drivers/aes2501.c drivers/aes2501.h AES4000_SRC = drivers/aes4000.c FDU2000_SRC = drivers/fdu2000.c -DRIVER_SRC = $(UPEKTS_SRC) $(AES4000_SRC) $(AES2501_SRC) -#DRIVER_SRC = $(URU4000_SRC) $(AES1610_SRC) $(UPEKTC_SRC) $(FDU2000_SRC) +DRIVER_SRC = $(UPEKTS_SRC) $(AES4000_SRC) $(AES2501_SRC) $(URU4000_SRC) +#DRIVER_SRC = $(AES1610_SRC) $(UPEKTC_SRC) $(FDU2000_SRC) NBIS_SRC = \ nbis/include/bozorth.h \ diff --git a/libfprint/core.c b/libfprint/core.c index 43d92c99..cf467554 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -331,8 +331,8 @@ static struct fp_driver * const primitive_drivers[] = { static struct fp_img_driver * const img_drivers[] = { &aes4000_driver, &aes2501_driver, - /* &uru4000_driver, - &aes1610_driver, + &uru4000_driver, + /* &aes1610_driver, &upektc_driver, &fdu2000_driver, */ }; diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index 955aca0e..e5ed85cf 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -1,6 +1,6 @@ /* * Digital Persona U.are.U 4000/4000B driver for libfprint - * Copyright (C) 2007 Daniel Drake + * Copyright (C) 2007-2008 Daniel Drake * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -35,9 +35,8 @@ #define CTRL_OUT (LIBUSB_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT) #define CTRL_TIMEOUT 5000 #define BULK_TIMEOUT 5000 -#define DATABLK1_RQLEN 0x10000 -#define DATABLK2_RQLEN 0xb340 -#define DATABLK2_EXPECT 0xb1c0 +#define DATABLK_RQLEN 0x1b340 +#define DATABLK_EXPECT 0x1b1c0 #define CAPTURE_HDRLEN 64 #define IRQ_LENGTH 64 #define CR_LENGTH 16 @@ -113,9 +112,27 @@ static const struct uru4k_dev_profile { }, }; +typedef void (*irq_cb_fn)(struct fp_img_dev *dev, int status, uint16_t type, + void *user_data); +typedef void (*irqs_stopped_cb_fn)(struct fp_img_dev *dev); + struct uru4k_dev { const struct uru4k_dev_profile *profile; uint8_t interface; + enum fp_imgdev_state activate_state; + unsigned char last_hwstat_rd; + + libusb_urb_handle *irq_transfer; + libusb_urb_handle *img_transfer; + + irq_cb_fn irq_cb; + void *irq_cb_data; + irqs_stopped_cb_fn irqs_stopped_cb; + + int rebootpwr_ctr; + int powerup_ctr; + unsigned char powerup_hwstat; + AES_KEY aeskey; }; @@ -125,6 +142,60 @@ static const unsigned char crkey[] = { 0x98, 0xe0, 0x0f, 0x3c, 0x59, 0x8f, 0x5f, 0x4b, }; +typedef void (*set_reg_cb_fn)(struct fp_img_dev *dev, int status, + void *user_data); + +struct set_reg_data { + struct fp_img_dev *dev; + set_reg_cb_fn callback; + void *user_data; +}; + +static void set_reg_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, + enum libusb_urb_cb_status status, struct libusb_ctrl_setup *setup, + unsigned char *data, int actual_length, void *user_data) +{ + struct set_reg_data *srdata = user_data; + int r = 0; + + if (status != FP_URB_COMPLETED) + r = -EIO; + else if (setup->wLength != actual_length) + r = -EPROTO; + + libusb_urb_handle_free(urbh); + srdata->callback(srdata->dev, r, srdata->user_data); + g_free(srdata); +} + +static int set_reg(struct fp_img_dev *dev, unsigned char reg, + unsigned char value, set_reg_cb_fn callback, void *user_data) +{ + struct set_reg_data *srdata = g_malloc(sizeof(*srdata)); + struct libusb_urb_handle *urbh; + struct libusb_control_transfer trf = { + .requesttype = CTRL_OUT, + .request = USB_RQ, + .value = reg, + .index = 0, + .length = 1, + .data = &value, + }; + + srdata->dev = dev; + srdata->callback = callback; + srdata->user_data = user_data; + + trf.data[0] = value; + urbh = libusb_async_control_transfer(dev->udev, &trf, set_reg_cb, srdata, + CTRL_TIMEOUT); + if (!urbh) { + g_free(srdata); + return -EIO; + } + return 0; +} + /* * HWSTAT * @@ -150,130 +221,68 @@ static const unsigned char crkey[] = { * and interrupt to the host. Maybe? */ -static int get_hwstat(struct fp_img_dev *dev, unsigned char *data) +typedef void (*challenge_response_cb)(struct fp_img_dev *dev, int result, + void *user_data); + +struct c_r_data { + struct fp_img_dev *dev; + challenge_response_cb callback; + void *user_data; +}; + +static void response_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, + enum libusb_urb_cb_status status, struct libusb_ctrl_setup *setup, + unsigned char *data, int actual_length, void *user_data) { - int r; + struct c_r_data *crdata = user_data; + int r = 0; + + if (status == FP_URB_COMPLETED) + r = -EIO; + else if (actual_length != setup->wLength) + r = -EPROTO; - /* The windows driver uses a request of 0x0c here. We use 0x04 to be - * consistent with every other command we know about. */ - struct libusb_control_transfer msg = { - .requesttype = CTRL_IN, - .request = USB_RQ, - .value = REG_HWSTAT, - .index = 0, - .length = 1, - .data = data, - }; - - r = libusb_control_transfer(dev->udev, &msg, CTRL_TIMEOUT); - if (r < 0) { - fp_err("error %d", r); - return r; - } else if (r < 1) { - fp_err("read too short (%d)", r); - return -EIO; - } - - fp_dbg("val=%02x", *data); - return 0; + libusb_urb_handle_free(urbh); + crdata->callback(crdata->dev, r, crdata->user_data); } -static int set_hwstat(struct fp_img_dev *dev, unsigned char data) +static void challenge_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, + enum libusb_urb_cb_status status, struct libusb_ctrl_setup *setup, + unsigned char *data, int actual_length, void *user_data) { - int r; - struct libusb_control_transfer msg = { - .requesttype = CTRL_OUT, - .request = USB_RQ, - .value = REG_HWSTAT, - .index = 0, - .length = 1, - .data = &data, - }; + struct c_r_data *crdata = user_data; + struct fp_img_dev *dev = crdata->dev; + struct uru4k_dev *urudev = dev->priv; + unsigned char respdata[CR_LENGTH]; - fp_dbg("val=%02x", data); - r = libusb_control_transfer(dev->udev, &msg, CTRL_TIMEOUT); - if (r < 0) { - fp_err("error %d", r); - return r; - } else if (r < 1) { - fp_err("read too short (%d)", r); - return -EIO; - } - - return 0; -} - -static int set_mode(struct fp_img_dev *dev, unsigned char mode) -{ - int r; - struct libusb_control_transfer msg = { - .requesttype = CTRL_OUT, - .request = USB_RQ, - .value = REG_MODE, - .index = 0, - .length = 1, - .data = &mode, - }; - - fp_dbg("%02x", mode); - r = libusb_control_transfer(dev->udev, &msg, CTRL_TIMEOUT); - if (r < 0) { - fp_err("error %d", r); - return r; - } else if (r < 1) { - fp_err("write too short (%d)", r); - return -EIO; - } - - return 0; -} - -static int read_challenge(struct fp_img_dev *dev, unsigned char *data) -{ - int r; - struct libusb_control_transfer msg = { - .requesttype = CTRL_IN, - .request = USB_RQ, - .value = REG_CHALLENGE, - .index = 0, - .length = CR_LENGTH, - .data = data, - }; - - r = libusb_control_transfer(dev->udev, &msg, CTRL_TIMEOUT); - if (r < 0) { - fp_err("error %d", r); - return r; - } else if (r < CR_LENGTH) { - fp_err("read too short (%d)", r); - return -EIO; - } - - return 0; -} - -static int write_response(struct fp_img_dev *dev, unsigned char *data) -{ - int r; - struct libusb_control_transfer msg = { + struct libusb_urb_handle *resp_urbh; + struct libusb_control_transfer trf_write_response = { .requesttype = CTRL_OUT, .request = USB_RQ, .value = REG_RESPONSE, .index = 0, - .length = CR_LENGTH, - .data = data, + .data = respdata, + .length = sizeof(respdata), }; - r = libusb_control_transfer(dev->udev, &msg, CTRL_TIMEOUT); - if (r < 0) { - fp_err("error %d", r); - return r; - } else if (r < 1) { - fp_err("write too short (%d)", r); - return -EIO; + if (status != FP_URB_COMPLETED) { + crdata->callback(crdata->dev, -EIO, crdata->user_data); + goto out; + } else if (setup->wLength != actual_length) { + crdata->callback(crdata->dev, -EPROTO, crdata->user_data); + goto out; } - return 0; + /* produce response from challenge */ + AES_encrypt(data, respdata, &urudev->aeskey); + + /* submit response */ + resp_urbh = libusb_async_control_transfer(dev->udev, &trf_write_response, + response_cb, crdata, CTRL_TIMEOUT); + if (!resp_urbh) + crdata->callback(crdata->dev, -EIO, crdata->user_data); +out: + libusb_urb_handle_free(urbh); } /* @@ -281,368 +290,744 @@ static int write_response(struct fp_img_dev *dev, unsigned char *data) * authentication scheme, where the device challenges the authenticity of the * driver. */ -static int auth_cr(struct fp_img_dev *dev) +static int do_challenge_response(struct fp_img_dev *dev, + challenge_response_cb callback, void *user_data) { - struct uru4k_dev *urudev = dev->priv; - unsigned char challenge[CR_LENGTH]; - unsigned char response[CR_LENGTH]; - int r; - - fp_dbg(""); - - r = read_challenge(dev, challenge); - if (r < 0) { - fp_err("error %d reading challenge", r); - return r; - } - - AES_encrypt(challenge, response, &urudev->aeskey); - - r = write_response(dev, response); - if (r < 0) - fp_err("error %d writing response", r); - - return r; -} - -static int get_irq(struct fp_img_dev *dev, unsigned char *buf, int timeout) -{ - uint16_t type; - int r; - int infinite_timeout = 0; - int transferred; - struct libusb_bulk_transfer msg = { - .endpoint = EP_INTR, - .data = buf, - .length = IRQ_LENGTH, + struct c_r_data *crdata = g_malloc(sizeof(*crdata)); + struct libusb_urb_handle *urbh; + struct libusb_control_transfer trf_read_challenge = { + .requesttype = CTRL_IN, + .request = USB_RQ, + .value = REG_CHALLENGE, + .index = 0, + .length = CR_LENGTH, }; - if (timeout == 0) { - infinite_timeout = 1; - timeout = 1000; - } + fp_dbg(""); + crdata->dev = dev; + crdata->callback = callback; + crdata->user_data = user_data; - /* Darwin and Linux behave inconsistently with regard to infinite timeouts. - * Linux accepts a timeout value of 0 as infinite timeout, whereas darwin - * returns -ETIMEDOUT immediately when a 0 timeout is used. We use a - * looping hack until libusb is fixed. - * See http://thread.gmane.org/gmane.comp.lib.libusb.devel.general/1315 */ - -retry: - r = libusb_interrupt_transfer(dev->udev, &msg, &transferred, timeout); - if (r == -ETIMEDOUT && infinite_timeout) - goto retry; - - if (r < 0) { - if (r != -ETIMEDOUT) - fp_err("interrupt read failed, error %d", r); - return r; - } else if (transferred < IRQ_LENGTH) { - fp_err("received %d byte IRQ!?", r); + urbh = libusb_async_control_transfer(dev->udev, &trf_read_challenge, + challenge_cb, crdata, CTRL_TIMEOUT); + if (!urbh) { + g_free(crdata); return -EIO; } + return 0; +} - type = GUINT16_FROM_BE(*((uint16_t *) buf)); - fp_dbg("irq type %04x", type); +/***** INTERRUPT HANDLING *****/ + +#define IRQ_HANDLER_IS_RUNNING(urudev) ((urudev)->irq_transfer) + +static int start_irq_handler(struct fp_img_dev *dev); + +static void irq_handler(libusb_dev_handle *devh, libusb_urb_handle *urbh, + enum libusb_urb_cb_status status, unsigned char endpoint, + int rqlength, unsigned char *data, int actual_length, void *user_data) +{ + struct fp_img_dev *dev = user_data; + struct uru4k_dev *urudev = dev->priv; + uint16_t type; + int r = 0; + + libusb_urb_handle_free(urbh); + + if (status == FP_URB_CANCELLED) { + fp_dbg("cancelled"); + if (urudev->irqs_stopped_cb) + urudev->irqs_stopped_cb(dev); + urudev->irqs_stopped_cb = NULL; + goto out; + } else if (status != FP_URB_COMPLETED) { + r = -EIO; + goto err; + } else if (actual_length != rqlength) { + fp_err("short interrupt read? %d", actual_length); + r = -EPROTO; + goto err; + } + + type = GUINT16_FROM_BE(*((uint16_t *) data)); + g_free(data); + fp_dbg("recv irq type %04x", type); /* The 0800 interrupt seems to indicate imminent failure (0 bytes transfer) - * of the next scan. I think I've stopped it from coming up, not sure - * though! */ + * of the next scan. It still appears on occasion. */ if (type == IRQDATA_DEATH) fp_warn("oh no! got the interrupt OF DEATH! expect things to go bad"); - return 0; -} - -enum get_irq_status { - GET_IRQ_SUCCESS = 0, - GET_IRQ_OVERFLOW = 1, -}; - -static int get_irq_with_type(struct fp_img_dev *dev, - uint16_t irqtype, int timeout) -{ - uint16_t hdr; - int discarded = 0; - unsigned char irqbuf[IRQ_LENGTH]; - - fp_dbg("type=%04x", irqtype); - - do { - int r = get_irq(dev, irqbuf, timeout); - if (r < 0) - return r; - - hdr = GUINT16_FROM_BE(*((uint16_t *) irqbuf)); - if (hdr == irqtype) - break; - discarded++; - } while (discarded < 3); - - if (discarded > 0) - fp_dbg("discarded %d interrupts", discarded); - - if (hdr == irqtype) { - return GET_IRQ_SUCCESS; - } else { - /* I've seen several cases where we're waiting for the 56aa powerup - * interrupt, but instead we just get three 0200 interrupts and then - * nothing. My theory is that the device can only queue 3 interrupts, - * or something. So, if we discard 3, ask the caller to retry whatever - * it was doing. */ - fp_dbg("possible IRQ overflow detected!"); - return GET_IRQ_OVERFLOW; - } -} - -static int await_finger_on(struct fp_img_dev *dev) -{ - int r; - -retry: - r = set_mode(dev, MODE_AWAIT_FINGER_ON); - if (r < 0) - return r; - - r = get_irq_with_type(dev, IRQDATA_FINGER_ON, 0); - if (r == GET_IRQ_OVERFLOW) - goto retry; + if (urudev->irq_cb) + urudev->irq_cb(dev, 0, type, urudev->irq_cb_data); else - return r; -} + fp_dbg("ignoring interrupt"); -static int await_finger_off(struct fp_img_dev *dev) -{ - int r; + r = start_irq_handler(dev); + if (r == 0) + return; -retry: - r = set_mode(dev, MODE_AWAIT_FINGER_OFF); - if (r < 0) - return r; - - r = get_irq_with_type(dev, IRQDATA_FINGER_OFF, 0); - if (r == GET_IRQ_OVERFLOW) - goto retry; - else - return r; -} - -static int capture(struct fp_img_dev *dev, gboolean unconditional, - struct fp_img **ret) -{ - int r; - struct fp_img *img; - size_t image_size = DATABLK1_RQLEN + DATABLK2_EXPECT - CAPTURE_HDRLEN; - int hdr_skip = CAPTURE_HDRLEN; - int transferred; - struct libusb_bulk_transfer msg1 = { - .endpoint = EP_DATA, - .length = DATABLK1_RQLEN, - }; - struct libusb_bulk_transfer msg2 = { - .endpoint = EP_DATA, - .length = DATABLK2_RQLEN, - }; - - - r = set_mode(dev, MODE_CAPTURE); - if (r < 0) - return r; - - /* The image is split up into 2 blocks over 2 USB transactions, which are - * joined contiguously. The image is prepended by a 64 byte header which - * we completely ignore. - * - * We mimic the windows driver behaviour by requesting 0xb340 bytes in the - * 2nd request, but we only expect 0xb1c0 in response. However, our buffers - * must be set up on the offchance that we receive as much data as we - * asked for. */ - - img = fpi_img_new(DATABLK1_RQLEN + DATABLK2_RQLEN); - msg1.data = img->data; - msg2.data = img->data + DATABLK1_RQLEN; - - r = libusb_bulk_transfer(dev->udev, &msg1, &transferred, BULK_TIMEOUT); - if (r < 0) { - fp_err("part 1 capture failed, error %d", r); - goto err; - } else if (transferred < DATABLK1_RQLEN) { - fp_err("part 1 capture too short (%d)", r); - r = -EIO; - goto err; - } - - r = libusb_bulk_transfer(dev->udev, &msg2, &transferred, BULK_TIMEOUT); - if (r < 0) { - fp_err("part 2 capture failed, error %d", r); - goto err; - } else if (transferred != DATABLK2_EXPECT) { - if (r == DATABLK2_EXPECT - CAPTURE_HDRLEN) { - /* this is rather odd, but it happens sometimes with my MS - * keyboard */ - fp_dbg("got image with no header!"); - hdr_skip = 0; - } else { - fp_err("unexpected part 2 capture size (%d)", r); - r = -EIO; - goto err; - } - } - - /* remove header and shrink allocation */ - g_memmove(img->data, img->data + hdr_skip, image_size); - img = fpi_img_resize(img, image_size); - img->flags = FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED | FP_IMG_COLORS_INVERTED; - - *ret = img; - return 0; + data = NULL; err: - fp_img_free(img); - return r; + if (urudev->irq_cb) + urudev->irq_cb(dev, r, 0, urudev->irq_cb_data); +out: + g_free(data); + urudev->irq_transfer = NULL; } -static int fix_firmware(struct fp_img_dev *dev) +static int start_irq_handler(struct fp_img_dev *dev) { struct uru4k_dev *urudev = dev->priv; + struct libusb_urb_handle *urbh; + struct libusb_bulk_transfer trf = { + .endpoint = EP_INTR, + .length = IRQ_LENGTH, + .data = g_malloc(IRQ_LENGTH), + }; + + urbh = libusb_async_interrupt_transfer(dev->udev, &trf, irq_handler, dev, + 0); + urudev->irq_transfer = urbh; + if (!urbh) { + g_free(trf.data); + return -EIO; + } + return 0; +} + +static void stop_irq_handler(struct fp_img_dev *dev, irqs_stopped_cb_fn cb) +{ + struct uru4k_dev *urudev = dev->priv; + struct libusb_urb_handle *urbh = urudev->irq_transfer; + if (urbh) { + libusb_urb_handle_cancel(dev->udev, urbh); + urudev->irqs_stopped_cb = cb; + } +} + +/***** IMAGING LOOP *****/ + +static int start_imaging_loop(struct fp_img_dev *dev); + +static void image_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, + enum libusb_urb_cb_status status, unsigned char endpoint, + int rqlength, unsigned char *data, int actual_length, void *user_data) +{ + struct fp_img_dev *dev = user_data; + struct uru4k_dev *urudev = dev->priv; + int hdr_skip = CAPTURE_HDRLEN; + int image_size = DATABLK_EXPECT - CAPTURE_HDRLEN; + struct fp_img *img; + int r = 0; + + libusb_urb_handle_free(urbh); + if (status == FP_URB_CANCELLED) { + fp_dbg("cancelled"); + urudev->img_transfer = NULL; + g_free(data); + return; + } else if (status != FP_URB_COMPLETED) { + r = -EIO; + goto out; + } + + if (actual_length == image_size) { + /* no header! this is rather odd, but it happens sometimes with my MS + * keyboard */ + fp_dbg("got image with no header!"); + hdr_skip = 0; + } else if (actual_length != DATABLK_EXPECT) { + fp_err("unexpected image capture size (%d)", actual_length); + r = -EPROTO; + goto out; + } + + img = fpi_img_new(image_size); + memcpy(img->data, data + hdr_skip, image_size); + img->flags = FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED | FP_IMG_COLORS_INVERTED; + fpi_imgdev_image_captured(dev, img); + +out: + g_free(data); + if (r == 0) + r = start_imaging_loop(dev); + + if (r) + fpi_imgdev_session_error(dev, r); +} + +static int start_imaging_loop(struct fp_img_dev *dev) +{ + struct uru4k_dev *urudev = dev->priv; + struct libusb_urb_handle *urbh; + struct libusb_bulk_transfer trf = { + .endpoint = EP_DATA, + .length = DATABLK_RQLEN, + .data = g_malloc(DATABLK_RQLEN), + }; + + urbh = libusb_async_bulk_transfer(dev->udev, &trf, image_cb, dev, 0); + urudev->img_transfer = urbh; + if (!urbh) { + g_free(trf.data); + return -EIO; + } + + return 0; +} + +static void stop_imaging_loop(struct fp_img_dev *dev) +{ + struct uru4k_dev *urudev = dev->priv; + libusb_urb_handle *urbh = urudev->img_transfer; + if (urbh) + libusb_urb_handle_cancel(dev->udev, urbh); + /* FIXME: should probably wait for cancellation to complete */ +} + +/***** STATE CHANGING *****/ + +static void finger_presence_irq_cb(struct fp_img_dev *dev, int status, + uint16_t type, void *user_data) +{ + if (status) + fpi_imgdev_session_error(dev, status); + else if (type == IRQDATA_FINGER_ON) + fpi_imgdev_report_finger_status(dev, TRUE); + else if (type == IRQDATA_FINGER_OFF) + fpi_imgdev_report_finger_status(dev, FALSE); + else + fp_warn("ignoring unexpected interrupt %04x", type); +} + +static void change_state_set_reg_cb(struct fp_img_dev *dev, int status, + void *user_data) +{ + if (status) + fpi_imgdev_session_error(dev, status); +} + +static int dev_change_state(struct fp_img_dev *dev, enum fp_imgdev_state state) +{ + struct uru4k_dev *urudev = dev->priv; + + stop_imaging_loop(dev); + + switch (state) { + case IMGDEV_STATE_AWAIT_FINGER_ON: + if (!IRQ_HANDLER_IS_RUNNING(urudev)) + return -EIO; + urudev->irq_cb = finger_presence_irq_cb; + return set_reg(dev, REG_MODE, MODE_AWAIT_FINGER_ON, + change_state_set_reg_cb, NULL); + + case IMGDEV_STATE_CAPTURE: + urudev->irq_cb = NULL; + start_imaging_loop(dev); + return set_reg(dev, REG_MODE, MODE_CAPTURE, change_state_set_reg_cb, + NULL); + + case IMGDEV_STATE_AWAIT_FINGER_OFF: + if (!IRQ_HANDLER_IS_RUNNING(urudev)) + return -EIO; + urudev->irq_cb = finger_presence_irq_cb; + return set_reg(dev, REG_MODE, MODE_AWAIT_FINGER_OFF, + change_state_set_reg_cb, NULL); + + default: + fp_err("unrecognised state %d", state); + return -EINVAL; + } +} + +/***** GENERIC STATE MACHINE HELPER FUNCTIONS *****/ + +static void sm_set_reg_cb(struct fp_img_dev *dev, int result, void *user_data) +{ + struct fpi_ssm *ssm = user_data; + + if (result) + fpi_ssm_mark_aborted(ssm, result); + else + fpi_ssm_next_state(ssm); +} + +static void sm_set_reg(struct fpi_ssm *ssm, unsigned char reg, + unsigned char value) +{ + struct fp_img_dev *dev = ssm->priv; + int r = set_reg(dev, reg, value, sm_set_reg_cb, ssm); + if (r < 0) + fpi_ssm_mark_aborted(ssm, r); +} + +static void sm_set_mode(struct fpi_ssm *ssm, unsigned char mode) +{ + fp_dbg("mode %02x", mode); + sm_set_reg(ssm, REG_MODE, mode); +} + +static void sm_set_hwstat(struct fpi_ssm *ssm, unsigned char value) +{ + fp_dbg("set %02x", value); + sm_set_reg(ssm, REG_HWSTAT, value); +} + +static void sm_get_hwstat_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, + enum libusb_urb_cb_status status, struct libusb_ctrl_setup *setup, + unsigned char *data, int actual_length, void *user_data) +{ + struct fpi_ssm *ssm = user_data; + struct fp_img_dev *dev = ssm->priv; + struct uru4k_dev *urudev = dev->priv; + + if (status != FP_URB_COMPLETED) { + fpi_ssm_mark_aborted(ssm, -EIO); + } else if (setup->wLength != actual_length) { + fpi_ssm_mark_aborted(ssm, -EPROTO); + } else { + urudev->last_hwstat_rd = *data; + fp_dbg("value %02x", urudev->last_hwstat_rd); + fpi_ssm_next_state(ssm); + } + libusb_urb_handle_free(urbh); +} + +static void sm_get_hwstat(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct libusb_urb_handle *urbh; + + /* The windows driver uses a request of 0x0c here. We use 0x04 to be + * consistent with every other command we know about. */ + /* FIXME is the above comment still true? */ + struct libusb_control_transfer trf = { + .requesttype = CTRL_IN, + .request = USB_RQ, + .value = REG_HWSTAT, + .index = 0, + .length = 1, + }; + + urbh = libusb_async_control_transfer(dev->udev, &trf, sm_get_hwstat_cb, + ssm, CTRL_TIMEOUT); + if (!urbh) + fpi_ssm_mark_aborted(ssm, -EIO); +} + +static void sm_fix_fw_read_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, + enum libusb_urb_cb_status status, struct libusb_ctrl_setup *setup, + unsigned char *data, int actual_length, void *user_data) +{ + struct fpi_ssm *ssm = user_data; + struct fp_img_dev *dev = ssm->priv; + struct uru4k_dev *urudev = dev->priv; + unsigned char new; + unsigned char fwenc; uint32_t enc_addr = FIRMWARE_START + urudev->profile->fw_enc_offset; - unsigned char val, new; - int r; - struct libusb_control_transfer msg = { + + if (status != FP_URB_COMPLETED) { + fpi_ssm_mark_aborted(ssm, -EIO); + goto out; + } else if (actual_length != setup->wLength) { + fpi_ssm_mark_aborted(ssm, -EPROTO); + goto out; + } + + fwenc = data[0]; + fp_dbg("firmware encryption byte at %x reads %02x", enc_addr, fwenc); + if (fwenc != 0x07 && fwenc != 0x17) + fp_dbg("strange encryption byte value, please report this"); + + new = fwenc & 0xef; + if (new == fwenc) { + fpi_ssm_next_state(ssm); + } else { + fp_dbg("fixed encryption byte to %02x", new); + sm_set_reg(ssm, enc_addr, new); + } + +out: + libusb_urb_handle_free(urbh); +} + +static void sm_fix_firmware(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct uru4k_dev *urudev = dev->priv; + uint32_t enc_addr = FIRMWARE_START + urudev->profile->fw_enc_offset; + + struct libusb_urb_handle *urbh; + struct libusb_control_transfer trf_read_fw = { .requesttype = 0xc0, .request = 0x0c, .value = enc_addr, .index = 0, - .data = &val, .length = 1, }; - - r = libusb_control_transfer(dev->udev, &msg, CTRL_TIMEOUT); - if (r < 0) - return r; - fp_dbg("encryption byte at %x reads %02x", enc_addr, val); - if (val != 0x07 && val != 0x17) - fp_dbg("strange encryption byte value, please report this"); - - new = val & 0xef; - //new = 0x17; - if (new == val) - return 0; - - msg.requesttype = 0x40; - msg.request = 0x04; - msg.data = &new; - - r = libusb_control_transfer(dev->udev, &msg, CTRL_TIMEOUT); - if (r < 0) - return r; - - fp_dbg("fixed encryption byte to %02x", new); - return 1; + urbh = libusb_async_control_transfer(dev->udev, &trf_read_fw, + sm_fix_fw_read_cb, ssm, CTRL_TIMEOUT); + if (!urbh) + fpi_ssm_mark_aborted(ssm, -EIO); } -static int do_init(struct fp_img_dev *dev) +/***** INITIALIZATION *****/ + +/* After closing an app and setting hwstat to 0x80, my ms keyboard gets in a + * confused state and returns hwstat 0x85. On next app run, we don't get the + * 56aa interrupt. This is the best way I've found to fix it: mess around + * with hwstat until it starts returning more recognisable values. This + * doesn't happen on my other devices: uru4000, uru4000b, ms fp rdr v2 + * + * The windows driver copes with this OK, but then again it uploads firmware + * right after reading the 0x85 hwstat, allowing some time to pass before it + * attempts to tweak hwstat again... + * + * This is implemented with a reboot power state machine. the ssm runs during + * initialization if bits 2 and 7 are set in hwstat. it masks off the 4 high + * hwstat bits then checks that bit 1 is set. if not, it pauses before reading + * hwstat again. machine completes when reading hwstat shows bit 1 is set, + * and fails after 100 tries. */ + +enum rebootpwr_states { + REBOOTPWR_SET_HWSTAT = 0, + REBOOTPWR_GET_HWSTAT, + REBOOTPWR_CHECK_HWSTAT, + REBOOTPWR_PAUSE, + REBOOTPWR_NUM_STATES, +}; + +static void rebootpwr_pause_cb(void *data) { - unsigned char status; - unsigned char tmp; + struct fpi_ssm *ssm = data; + struct fp_img_dev *dev = ssm->priv; + struct uru4k_dev *urudev = dev->priv; + + if (!--urudev->rebootpwr_ctr) { + fp_err("could not reboot device power"); + fpi_ssm_mark_aborted(ssm, -EIO); + } else { + fpi_ssm_jump_to_state(ssm, REBOOTPWR_GET_HWSTAT); + } +} + +static void rebootpwr_run_state(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; struct uru4k_dev *urudev = dev->priv; - gboolean need_auth_cr = urudev->profile->auth_cr; - int timeouts = 0; - int i; int r; -retry: - r = get_hwstat(dev, &status); - if (r < 0) - return r; - - /* After closing an app and setting hwstat to 0x80, my ms keyboard - * gets in a confused state and returns hwstat 0x85. On next app run, - * we don't get the 56aa interrupt. This is the best way I've found to - * fix it: mess around with hwstat until it starts returning more - * recognisable values. This doesn't happen on my other devices: - * uru4000, uru4000b, ms fp rdr v2 - * The windows driver copes with this OK, but then again it uploads - * firmware right after reading the 0x85 hwstat, allowing some time - * to pass before it attempts to tweak hwstat again... */ - if ((status & 0x84) == 0x84) { - fp_dbg("rebooting device power"); - r = set_hwstat(dev, status & 0xf); + switch (ssm->cur_state) { + case REBOOTPWR_SET_HWSTAT: + urudev->rebootpwr_ctr = 100; + sm_set_hwstat(ssm, urudev->last_hwstat_rd & 0xf); + break; + case REBOOTPWR_GET_HWSTAT: + sm_get_hwstat(ssm); + break; + case REBOOTPWR_CHECK_HWSTAT: + if (urudev->last_hwstat_rd & 0x1) + fpi_ssm_mark_completed(ssm); + else + fpi_ssm_next_state(ssm); + break; + case REBOOTPWR_PAUSE: + r = fpi_timeout_add(10, rebootpwr_pause_cb, ssm); if (r < 0) - return r; - - for (i = 0; i < 100; i++) { - r = get_hwstat(dev, &status); - if (r < 0) - return r; - if (status & 0x1) - break; - usleep(10000); - } - if ((status & 0x1) == 0) { - fp_err("could not reboot device power"); - return -EIO; - } - } - - if ((status & 0x80) == 0) { - status |= 0x80; - r = set_hwstat(dev, status); - if (r < 0) - return r; + fpi_ssm_mark_aborted(ssm, r); + break; } +} +/* After messing with the device firmware in it's low-power state, we have to + * power it back up and wait for interrupt notification. It's not quite as easy + * as that: the combination of both modifying firmware *and* doing C-R auth on + * my ms fp v2 device causes us not to get to get the 56aa interrupt and + * for the hwstat write not to take effect. We have to loop a few times, + * authenticating each time, until the device wakes up. + * + * This is implemented as the powerup state machine below. Pseudo-code: - r = fix_firmware(dev); - if (r < 0) - return r; - - /* Power up device and wait for interrupt notification */ - /* The combination of both modifying firmware *and* doing C-R auth on - * my ms fp v2 device causes us not to get to get the 56aa interrupt and - * for the hwstat write not to take effect. We loop a few times, - * authenticating each time, until the device wakes up. */ - for (i = 0; i < 100; i++) { /* max 1 sec */ - r = set_hwstat(dev, status & 0xf); - if (r < 0) - return r; - - r = get_hwstat(dev, &tmp); - if (r < 0) - return r; - - if ((tmp & 0x80) == 0) + status = get_hwstat(); + for (i = 0; i < 100; i++) { + set_hwstat(status & 0xf); + if ((get_hwstat() & 0x80) == 0) break; usleep(10000); - - if (need_auth_cr) { - r = auth_cr(dev); - if (r < 0) - return r; - } + if (need_auth_cr) + auth_cr(); } - if (tmp & 0x80) { - fp_err("could not power up device"); - return -EIO; - } + if (tmp & 0x80) + error("could not power up device"); - r = get_irq_with_type(dev, IRQDATA_SCANPWR_ON, 300); - if (r == GET_IRQ_OVERFLOW) { - goto retry; - } else if (r == -ETIMEDOUT) { - timeouts++; - if (timeouts <= 3) { - fp_dbg("scan power up timeout, retrying..."); - goto retry; - } else { - fp_err("could not power up scanner after 3 attempts"); - } + */ + +enum powerup_states { + POWERUP_INIT = 0, + POWERUP_SET_HWSTAT, + POWERUP_GET_HWSTAT, + POWERUP_CHECK_HWSTAT, + POWERUP_PAUSE, + POWERUP_CHALLENGE_RESPONSE, + POWERUP_NUM_STATES, +}; + +static void powerup_pause_cb(void *data) +{ + struct fpi_ssm *ssm = data; + struct fp_img_dev *dev = ssm->priv; + struct uru4k_dev *urudev = dev->priv; + + if (!--urudev->powerup_ctr) { + fp_err("could not power device up"); + fpi_ssm_mark_aborted(ssm, -EIO); + } else if (!urudev->profile->auth_cr) { + fpi_ssm_jump_to_state(ssm, POWERUP_SET_HWSTAT); + } else { + fpi_ssm_next_state(ssm); } - return r; } +static void powerup_challenge_response_cb(struct fp_img_dev *dev, int result, + void *data) +{ + struct fpi_ssm *ssm = data; + if (result) + fpi_ssm_mark_aborted(ssm, result); + else + fpi_ssm_jump_to_state(ssm, POWERUP_SET_HWSTAT); +} + +static void powerup_run_state(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct uru4k_dev *urudev = dev->priv; + int r; + + switch (ssm->cur_state) { + case POWERUP_INIT: + urudev->powerup_ctr = 100; + urudev->powerup_hwstat = urudev->last_hwstat_rd & 0xf; + fpi_ssm_next_state(ssm); + break; + case POWERUP_SET_HWSTAT: + sm_set_hwstat(ssm, urudev->powerup_hwstat); + break; + case POWERUP_GET_HWSTAT: + sm_get_hwstat(ssm); + break; + case POWERUP_CHECK_HWSTAT: + if ((urudev->last_hwstat_rd & 0x80) == 0) + fpi_ssm_mark_completed(ssm); + else + fpi_ssm_next_state(ssm); + break; + case POWERUP_PAUSE: + r = fpi_timeout_add(10, powerup_pause_cb, ssm); + if (r < 0) + fpi_ssm_mark_aborted(ssm, r); + break; + case POWERUP_CHALLENGE_RESPONSE: + r = do_challenge_response(dev, powerup_challenge_response_cb, ssm); + if (r < 0) + fpi_ssm_mark_aborted(ssm, r); + break; + } +} + +/* + * This is the main initialization state machine. As pseudo-code: + + status = get_hwstat(); + + // correct device power state + if ((status & 0x84) == 0x84) + run_reboot_sm(); + + // power device down + if ((status & 0x80) == 0) + set_hwstat(status | 0x80); + + // disable encryption + fwenc = read_firmware_encryption_byte(); + new = fwenc & 0xef; + if (new != fwenc) + write_firmware_encryption_byte(new); + + // power device up + run_powerup_sm(); + await_irq(IRQDATA_SCANPWR_ON); + */ + +enum init_states { + INIT_GET_HWSTAT = 0, + INIT_CHECK_HWSTAT_REBOOT, + INIT_REBOOT_POWER, + INIT_CHECK_HWSTAT_POWERDOWN, + INIT_FIX_FIRMWARE, + INIT_POWERUP, + INIT_AWAIT_SCAN_POWER, + INIT_DONE, + INIT_NUM_STATES, +}; + +static void init_scanpwr_irq_cb(struct fp_img_dev *dev, int status, + uint16_t type, void *user_data) +{ + struct fpi_ssm *ssm = user_data; + + if (status) + fpi_ssm_mark_aborted(ssm, status); + else if (type != IRQDATA_SCANPWR_ON) + fp_dbg("ignoring interrupt"); + else if (ssm->cur_state != INIT_AWAIT_SCAN_POWER) + fp_err("ignoring scanpwr interrupt due to being in wrong state %d", + ssm->cur_state); + else + fpi_ssm_next_state(ssm); +} + +static void init_run_state(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct uru4k_dev *urudev = dev->priv; + + switch (ssm->cur_state) { + case INIT_GET_HWSTAT: + sm_get_hwstat(ssm); + break; + case INIT_CHECK_HWSTAT_REBOOT: + if ((urudev->last_hwstat_rd & 0x84) == 0x84) + fpi_ssm_next_state(ssm); + else + fpi_ssm_jump_to_state(ssm, INIT_CHECK_HWSTAT_POWERDOWN); + break; + case INIT_REBOOT_POWER: ; + struct fpi_ssm *rebootsm = fpi_ssm_new(dev->dev, rebootpwr_run_state, + REBOOTPWR_NUM_STATES); + rebootsm->priv = dev; + fpi_ssm_start_subsm(ssm, rebootsm); + break; + case INIT_CHECK_HWSTAT_POWERDOWN: + if ((urudev->last_hwstat_rd & 0x80) == 0) + sm_set_hwstat(ssm, urudev->last_hwstat_rd | 0x80); + else + fpi_ssm_next_state(ssm); + break; + case INIT_FIX_FIRMWARE: + sm_fix_firmware(ssm); + break; + case INIT_POWERUP: ; + struct fpi_ssm *powerupsm = fpi_ssm_new(dev->dev, powerup_run_state, + POWERUP_NUM_STATES); + powerupsm->priv = dev; + fpi_ssm_start_subsm(ssm, powerupsm); + break; + case INIT_AWAIT_SCAN_POWER: + /* FIXME: should timeout and maybe retry entire sm? */ + if (!IRQ_HANDLER_IS_RUNNING(urudev)) { + fpi_ssm_mark_aborted(ssm, -EIO); + } else { + urudev->irq_cb_data = ssm; + urudev->irq_cb = init_scanpwr_irq_cb; + } + break; + case INIT_DONE: + urudev->irq_cb_data = NULL; + urudev->irq_cb = NULL; + fpi_ssm_mark_completed(ssm); + break; + } +} + +static void activate_initsm_complete(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct uru4k_dev *urudev = dev->priv; + int r = ssm->error; + fpi_ssm_free(ssm); + + if (r) { + fpi_imgdev_activate_complete(dev, r); + return; + } + + r = dev_change_state(dev, urudev->activate_state); + fpi_imgdev_activate_complete(dev, r); +} + +/* FIXME: having state parameter here is kinda useless, will we ever + * see a scenario where the parameter is useful so early on in the activation + * process? asynchronity means that it'll only be used in a later function + * call. */ +static int dev_activate(struct fp_img_dev *dev, enum fp_imgdev_state state) +{ + struct uru4k_dev *urudev = dev->priv; + struct fpi_ssm *ssm; + int r; + + r = start_irq_handler(dev); + if (r < 0) + return r; + + urudev->activate_state = state; + ssm = fpi_ssm_new(dev->dev, init_run_state, INIT_NUM_STATES); + ssm->priv = dev; + fpi_ssm_start(ssm, activate_initsm_complete); + return 0; +} + +/***** DEINITIALIZATION *****/ + +enum deinit_states { + DEINIT_SET_MODE_INIT = 0, + DEINIT_POWERDOWN, + DEINIT_NUM_STATES, +}; + +static void deinit_run_state(struct fpi_ssm *ssm) +{ + switch (ssm->cur_state) { + case DEINIT_SET_MODE_INIT: + sm_set_mode(ssm, MODE_INIT); + break; + case DEINIT_POWERDOWN: + sm_set_hwstat(ssm, 0x80); + break; + } +} + +static void deactivate_irqs_stopped(struct fp_img_dev *dev) +{ + fpi_imgdev_deactivate_complete(dev); +} + +static void deactivate_deinitsm_complete(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + fpi_ssm_free(ssm); + stop_irq_handler(dev, deactivate_irqs_stopped); +} + +static void dev_deactivate(struct fp_img_dev *dev) +{ + struct uru4k_dev *urudev = dev->priv; + struct fpi_ssm *ssm = fpi_ssm_new(dev->dev, deinit_run_state, + DEINIT_NUM_STATES); + + stop_imaging_loop(dev); + urudev->irq_cb = NULL; + urudev->irq_cb_data = NULL; + ssm->priv = dev; + fpi_ssm_start(ssm, deactivate_deinitsm_complete); +} + +/***** LIBRARY STUFF *****/ + static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) { struct libusb_config_descriptor *config; @@ -711,26 +1096,16 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) urudev->interface = iface_desc->bInterfaceNumber; AES_set_encrypt_key(crkey, 128, &urudev->aeskey); dev->priv = urudev; - - r = do_init(dev); - if (r < 0) - goto err; - + fpi_imgdev_init_complete(dev, 0); return 0; -err: - libusb_release_interface(dev->udev, iface_desc->bInterfaceNumber); - g_free(urudev); - return r; } -static void dev_exit(struct fp_img_dev *dev) +static void dev_deinit(struct fp_img_dev *dev) { struct uru4k_dev *urudev = dev->priv; - - set_mode(dev, MODE_INIT); - set_hwstat(dev, 0x80); libusb_release_interface(dev->udev, urudev->interface); g_free(urudev); + fpi_imgdev_deinit_complete(dev); } static const struct usb_id id_table[] = { @@ -768,9 +1143,9 @@ struct fp_img_driver uru4000_driver = { .img_width = 384, .init = dev_init, - .exit = dev_exit, - .await_finger_on = await_finger_on, - .await_finger_off = await_finger_off, - .capture = capture, + .deinit = dev_deinit, + .activate = dev_activate, + .deactivate = dev_deactivate, + .change_state = dev_change_state, }; From 88e9f4a5f80cf78aaf448a7fd6cd60beba7abd5b Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Tue, 26 Feb 2008 18:04:54 +0000 Subject: [PATCH 107/184] Public async API implementation Involved some internal overhaul/reorganisation. Nice side effect is that the synchronous API is now expressed purely in terms of the public async API. --- libfprint/Makefile.am | 2 + libfprint/async.c | 414 +++++++++++++++++++++++++++ libfprint/core.c | 545 +----------------------------------- libfprint/drivers/aes2501.c | 8 +- libfprint/drivers/aes4000.c | 8 +- libfprint/drivers/upekts.c | 8 +- libfprint/drivers/uru4000.c | 8 +- libfprint/drv.c | 268 +----------------- libfprint/fp_internal.h | 63 ++--- libfprint/fprint.h | 37 +++ libfprint/imgdev.c | 53 ++-- libfprint/sync.c | 512 +++++++++++++++++++++++++++++++++ 12 files changed, 1054 insertions(+), 872 deletions(-) create mode 100644 libfprint/async.c create mode 100644 libfprint/sync.c diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 1bef2461..b4e022ce 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -54,12 +54,14 @@ libfprint_la_LIBADD = -lm $(LIBUSB_LIBS) $(GLIB_LIBS) $(IMAGEMAGICK_LIBS) $(CRYP libfprint_la_SOURCES = \ fp_internal.h \ + async.c \ core.c \ data.c \ drv.c \ img.c \ imgdev.c \ poll.c \ + sync.c \ aeslib.c \ aeslib.h \ $(DRIVER_SRC) \ diff --git a/libfprint/async.c b/libfprint/async.c new file mode 100644 index 00000000..00d97272 --- /dev/null +++ b/libfprint/async.c @@ -0,0 +1,414 @@ +/* + * Asynchronous I/O functionality + * Copyright (C) 2008 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#define FP_COMPONENT "async" + +#include +#include +#include + +#include "fp_internal.h" + +/* Drivers call this when device initialisation has completed */ +void fpi_drvcb_open_complete(struct fp_dev *dev, int status) +{ + fp_dbg("status %d", status); + BUG_ON(dev->state != DEV_STATE_INITIALIZING); + dev->state = (status) ? DEV_STATE_ERROR : DEV_STATE_INITIALIZED; + opened_devices = g_slist_prepend(opened_devices, dev); + if (dev->open_cb) + dev->open_cb(dev, status, dev->open_cb_data); +} + +API_EXPORTED int fp_async_dev_open(struct fp_dscv_dev *ddev, fp_dev_open_cb cb, + void *user_data) +{ + struct fp_driver *drv = ddev->drv; + struct fp_dev *dev; + libusb_dev_handle *udevh; + int r; + + fp_dbg(""); + udevh = libusb_open(ddev->udev); + if (!udevh) { + fp_err("usb_open failed"); + return -EIO; + } + + dev = g_malloc0(sizeof(*dev)); + dev->drv = drv; + dev->udev = udevh; + dev->__enroll_stage = -1; + dev->state = DEV_STATE_INITIALIZING; + dev->open_cb = cb; + dev->open_cb_data = user_data; + + if (!drv->open) { + fpi_drvcb_open_complete(dev, 0); + return 0; + } + + dev->state = DEV_STATE_INITIALIZING; + r = drv->open(dev, ddev->driver_data); + if (r) { + fp_err("device initialisation failed, driver=%s", drv->name); + libusb_close(udevh); + g_free(dev); + } + + return r; +} + +/* Drivers call this when device deinitialisation has completed */ +void fpi_drvcb_close_complete(struct fp_dev *dev) +{ + fp_dbg(""); + BUG_ON(dev->state != DEV_STATE_DEINITIALIZING); + dev->state = DEV_STATE_DEINITIALIZED; + libusb_close(dev->udev); + if (dev->close_cb) + dev->close_cb(dev, dev->close_cb_data); + g_free(dev); +} + +API_EXPORTED void fp_async_dev_close(struct fp_dev *dev, + fp_dev_close_cb callback, void *user_data) +{ + struct fp_driver *drv = dev->drv; + + if (g_slist_index(opened_devices, (gconstpointer) dev) == -1) + fp_err("device %p not in opened list!", dev); + opened_devices = g_slist_remove(opened_devices, (gconstpointer) dev); + + dev->close_cb = callback; + dev->close_cb_data = user_data; + + if (!drv->close) { + fpi_drvcb_close_complete(dev); + return; + } + + dev->state = DEV_STATE_DEINITIALIZING; + drv->close(dev); +} + +/* Drivers call this when enrollment has started */ +void fpi_drvcb_enroll_started(struct fp_dev *dev, int status) +{ + fp_dbg("status %d", status); + BUG_ON(dev->state != DEV_STATE_ENROLL_STARTING); + if (status) { + if (status > 0) { + status = -status; + fp_dbg("adjusted to %d", status); + } + dev->state = DEV_STATE_ERROR; + if (dev->enroll_stage_cb) + dev->enroll_stage_cb(dev, status, NULL, NULL, + dev->enroll_stage_cb_data); + } else { + dev->state = DEV_STATE_ENROLLING; + } +} + +API_EXPORTED int fp_async_enroll_start(struct fp_dev *dev, + fp_enroll_stage_cb callback, void *user_data) +{ + struct fp_driver *drv = dev->drv; + int r; + + if (!dev->nr_enroll_stages || !drv->enroll_start) { + fp_err("driver %s has 0 enroll stages or no enroll func", + drv->name); + return -ENOTSUP; + } + + fp_dbg("starting enrollment"); + dev->enroll_stage_cb = callback; + dev->enroll_stage_cb_data = user_data; + + dev->state = DEV_STATE_ENROLL_STARTING; + r = drv->enroll_start(dev); + if (r < 0) { + dev->enroll_stage_cb = NULL; + fp_err("failed to start enrollment"); + dev->state = DEV_STATE_ERROR; + } + + return r; +} + +/* Drivers call this when an enroll stage has completed */ +void fpi_drvcb_enroll_stage_completed(struct fp_dev *dev, int result, + struct fp_print_data *data, struct fp_img *img) +{ + BUG_ON(dev->state != DEV_STATE_ENROLLING); + fp_dbg("result %d", result); + if (!dev->enroll_stage_cb) { + fp_dbg("ignoring enroll result as no callback is subscribed"); + return; + } + if (result == FP_ENROLL_COMPLETE && !data) { + fp_err("BUG: complete but no data?"); + result = FP_ENROLL_FAIL; + } + dev->enroll_stage_cb(dev, result, data, img, dev->enroll_stage_cb_data); +} + +/* Drivers call this when enrollment has stopped */ +void fpi_drvcb_enroll_stopped(struct fp_dev *dev) +{ + fp_dbg(""); + BUG_ON(dev->state != DEV_STATE_ENROLL_STOPPING); + dev->state = DEV_STATE_INITIALIZED; + if (dev->enroll_stop_cb) + dev->enroll_stop_cb(dev, dev->enroll_stop_cb_data); +} + +API_EXPORTED int fp_async_enroll_stop(struct fp_dev *dev, + fp_enroll_stop_cb callback, void *user_data) +{ + struct fp_driver *drv = dev->drv; + int r; + + fp_dbg(""); + if (!drv->enroll_start) + return -ENOTSUP; + + dev->enroll_stage_cb = NULL; + dev->enroll_stop_cb = callback; + dev->enroll_stop_cb_data = user_data; + dev->state = DEV_STATE_ENROLL_STOPPING; + + if (!drv->enroll_stop) { + fpi_drvcb_enroll_stopped(dev); + return 0; + } + + r = drv->enroll_stop(dev); + if (r < 0) { + fp_err("failed to stop enrollment"); + dev->enroll_stop_cb = NULL; + } + + return r; +} + +API_EXPORTED int fp_async_verify_start(struct fp_dev *dev, + struct fp_print_data *data, fp_verify_cb callback, void *user_data) +{ + struct fp_driver *drv = dev->drv; + int r; + + fp_dbg(""); + if (!drv->verify_start) + return -ENOTSUP; + + dev->state = DEV_STATE_VERIFY_STARTING; + dev->verify_cb = callback; + dev->verify_cb_data = user_data; + dev->verify_data = data; + + r = drv->verify_start(dev); + if (r < 0) { + dev->verify_cb = NULL; + dev->state = DEV_STATE_ERROR; + fp_err("failed to start verification, error %d", r); + } + return r; +} + +/* Drivers call this when verification has started */ +void fpi_drvcb_verify_started(struct fp_dev *dev, int status) +{ + fp_dbg(""); + BUG_ON(dev->state != DEV_STATE_VERIFY_STARTING); + if (status) { + if (status > 0) { + status = -status; + fp_dbg("adjusted to %d", status); + } + dev->state = DEV_STATE_ERROR; + if (dev->verify_cb) + dev->verify_cb(dev, status, NULL, dev->verify_cb_data); + } else { + dev->state = DEV_STATE_VERIFYING; + } +} + +/* Drivers call this to report a verify result (which might mark completion) */ +void fpi_drvcb_report_verify_result(struct fp_dev *dev, int result, + struct fp_img *img) +{ + fp_dbg("result %d", result); + BUG_ON(dev->state != DEV_STATE_VERIFYING); + if (result < 0 || result == FP_VERIFY_NO_MATCH + || result == FP_VERIFY_MATCH) + dev->state = DEV_STATE_VERIFY_DONE; + + if (dev->verify_cb) + dev->verify_cb(dev, result, img, dev->verify_cb_data); + else + fp_dbg("ignoring verify result as no callback is subscribed"); +} + +/* Drivers call this when verification has stopped */ +void fpi_drvcb_verify_stopped(struct fp_dev *dev) +{ + fp_dbg(""); + BUG_ON(dev->state != DEV_STATE_VERIFY_STOPPING); + dev->state = DEV_STATE_INITIALIZED; + if (dev->verify_stop_cb) + dev->verify_stop_cb(dev, dev->verify_stop_cb_data); +} + +API_EXPORTED int fp_async_verify_stop(struct fp_dev *dev, + fp_verify_stop_cb callback, void *user_data) +{ + struct fp_driver *drv = dev->drv; + gboolean iterating = (dev->state == DEV_STATE_VERIFYING); + int r; + + fp_dbg(""); + BUG_ON(dev->state != DEV_STATE_ERROR + && dev->state != DEV_STATE_VERIFYING + && dev->state != DEV_STATE_VERIFY_DONE); + + dev->verify_cb = NULL; + dev->verify_stop_cb = callback; + dev->verify_stop_cb_data = user_data; + dev->state = DEV_STATE_VERIFY_STOPPING; + + if (!drv->verify_start) + return -ENOTSUP; + if (!drv->verify_stop) { + dev->state = DEV_STATE_INITIALIZED; + fpi_drvcb_verify_stopped(dev); + return 0; + } + + r = drv->verify_stop(dev, iterating); + if (r < 0) { + fp_err("failed to stop verification"); + dev->verify_stop_cb = NULL; + } + return r; +} + +API_EXPORTED int fp_async_identify_start(struct fp_dev *dev, + struct fp_print_data **gallery, fp_identify_cb callback, void *user_data) +{ + struct fp_driver *drv = dev->drv; + int r; + + fp_dbg(""); + if (!drv->identify_start) + return -ENOTSUP; + dev->state = DEV_STATE_IDENTIFY_STARTING; + dev->identify_cb = callback; + dev->identify_cb_data = user_data; + dev->identify_gallery = gallery; + + r = drv->identify_start(dev); + if (r < 0) { + fp_err("identify_start failed with error %d", r); + dev->identify_cb = NULL; + dev->state = DEV_STATE_ERROR; + } + return r; +} + +/* Driver-lib: identification has started, expect results soon */ +void fpi_drvcb_identify_started(struct fp_dev *dev, int status) +{ + fp_dbg("status %d", status); + BUG_ON(dev->state != DEV_STATE_IDENTIFY_STARTING); + if (status) { + if (status > 0) { + status = -status; + fp_dbg("adjusted to %d", status); + } + dev->state = DEV_STATE_ERROR; + if (dev->identify_cb) + dev->identify_cb(dev, status, 0, NULL, dev->identify_cb_data); + } else { + dev->state = DEV_STATE_IDENTIFYING; + } +} + +/* Drivers report an identify result (which might mark completion) */ +void fpi_drvcb_report_identify_result(struct fp_dev *dev, int result, + size_t match_offset, struct fp_img *img) +{ + fp_dbg("result %d", result); + BUG_ON(dev->state != DEV_STATE_IDENTIFYING + && dev->state != DEV_STATE_ERROR); + if (result < 0 || result == FP_VERIFY_NO_MATCH + || result == FP_VERIFY_MATCH) + dev->state = DEV_STATE_IDENTIFY_DONE; + + if (dev->identify_cb) + dev->identify_cb(dev, result, match_offset, img, dev->identify_cb_data); + else + fp_dbg("ignoring verify result as no callback is subscribed"); +} + +API_EXPORTED int fp_async_identify_stop(struct fp_dev *dev, + fp_identify_stop_cb callback, void *user_data) +{ + struct fp_driver *drv = dev->drv; + gboolean iterating = (dev->state == DEV_STATE_IDENTIFYING); + int r; + + fp_dbg(""); + BUG_ON(dev->state != DEV_STATE_IDENTIFYING + && dev->state != DEV_STATE_IDENTIFY_DONE); + + dev->state = DEV_STATE_IDENTIFY_STOPPING; + dev->identify_cb = NULL; + dev->identify_stop_cb = callback; + dev->identify_stop_cb_data = user_data; + + if (!drv->identify_start) + return -ENOTSUP; + if (!drv->identify_stop) { + dev->state = DEV_STATE_INITIALIZED; + fpi_drvcb_identify_stopped(dev); + return 0; + } + + r = drv->identify_stop(dev, iterating); + if (r < 0) { + fp_err("failed to stop identification"); + dev->identify_stop_cb = NULL; + } + + return r; +} + +/* Drivers call this when identification has stopped */ +void fpi_drvcb_identify_stopped(struct fp_dev *dev) +{ + fp_dbg(""); + BUG_ON(dev->state != DEV_STATE_IDENTIFY_STOPPING); + dev->state = DEV_STATE_INITIALIZED; + if (dev->identify_stop_cb) + dev->identify_stop_cb(dev, dev->identify_stop_cb_data); +} + diff --git a/libfprint/core.c b/libfprint/core.c index cf467554..e1382fa0 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -26,6 +26,8 @@ #include "fp_internal.h" +GSList *opened_devices = NULL; + /** * \mainpage libfprint API Reference * libfprint is an open source library to provide access to fingerprint @@ -273,7 +275,6 @@ */ static GSList *registered_drivers = NULL; -static GSList *opened_devices = NULL; void fpi_log(enum fpi_log_level level, const char *component, const char *function, const char *format, ...) @@ -565,89 +566,6 @@ API_EXPORTED struct fp_dscv_dev *fp_dscv_dev_for_dscv_print(struct fp_dscv_dev * return NULL; } -/** \ingroup dev - * Opens and initialises a device. This is the function you call in order - * to convert a \ref dscv_dev "discovered device" into an actual device handle - * that you can perform operations with. - * \param ddev the discovered device to open - * \returns the opened device handle, or NULL on error - */ -API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) -{ - struct fp_dev *dev; - struct fp_driver *drv = ddev->drv; - int r; - - fp_dbg(""); - libusb_dev_handle *udevh = libusb_open(ddev->udev); - if (!udevh) { - fp_err("usb_open failed"); - return NULL; - } - - dev = g_malloc0(sizeof(*dev)); - dev->drv = drv; - dev->udev = udevh; - dev->__enroll_stage = -1; - dev->state = DEV_STATE_INITIALIZING; - - r = fpi_drv_init(dev, ddev->driver_data); - if (r) { - fp_err("device initialisation failed, driver=%s", drv->name); - goto err; - } - - while (dev->state == DEV_STATE_INITIALIZING) - if (fp_handle_events() < 0) - goto err_deinit; - if (dev->state != DEV_STATE_INITIALIZED) - goto err_deinit; - - opened_devices = g_slist_prepend(opened_devices, (gpointer) dev); - return dev; - -err_deinit: - fpi_drv_deinit(dev); - while (dev->state == DEV_STATE_DEINITIALIZING) { - if (fp_handle_events() < 0) - break; - } -err: - libusb_close(udevh); - g_free(dev); - return NULL; -} - -/* performs close operation without modifying opened_devices list */ -static void do_close(struct fp_dev *dev) -{ - fpi_drv_deinit(dev); - while (dev->state == DEV_STATE_DEINITIALIZING) - if (fp_handle_events() < 0) - break; - - libusb_close(dev->udev); - g_free(dev); -} - -/** \ingroup dev - * Close a device. You must call this function when you are finished using - * a fingerprint device. - * \param dev the device to close. If NULL, function simply returns. - */ -API_EXPORTED void fp_dev_close(struct fp_dev *dev) -{ - if (!dev) - return; - - fp_dbg(""); - - if (g_slist_index(opened_devices, (gconstpointer) dev) == -1) - fp_err("device %p not in opened list!", dev); - opened_devices = g_slist_remove(opened_devices, (gconstpointer) dev); - do_close(dev); -} - /** \ingroup dev * Get the \ref drv "driver" for a fingerprint device. * \param dev the device @@ -843,448 +761,6 @@ API_EXPORTED int fp_dev_get_img_height(struct fp_dev *dev) return fpi_imgdev_get_img_height(imgdev); } -struct sync_enroll_data { - gboolean populated; - int result; - struct fp_print_data *data; - struct fp_img *img; -}; - -static void sync_enroll_cb(struct fp_dev *dev, int result, - struct fp_print_data *data, struct fp_img *img) -{ - struct sync_enroll_data *edata = dev->enroll_data; - edata->result = result; - edata->data = data; - edata->img = img; - edata->populated = TRUE; -} - -/** \ingroup dev - * Performs an enroll stage. See \ref enrolling for an explanation of enroll - * stages. - * - * If no enrollment is in process, this kicks of the process and runs the - * first stage. If an enrollment is already in progress, calling this - * function runs the next stage, which may well be the last. - * - * A negative error code may be returned from any stage. When this occurs, - * further calls to the enroll function will start a new enrollment process, - * i.e. a negative error code indicates that the enrollment process has been - * aborted. These error codes only ever indicate unexpected internal errors - * or I/O problems. - * - * The RETRY codes from #fp_enroll_result may be returned from any enroll - * stage. These codes indicate that the scan was not succesful in that the - * user did not position their finger correctly or similar. When a RETRY code - * is returned, the enrollment stage is not advanced, so the next call - * into this function will retry the current stage again. The current stage may - * need to be retried several times. - * - * The fp_enroll_result#FP_ENROLL_FAIL code may be returned from any enroll - * stage. This code indicates that even though the scans themselves have been - * acceptable, data processing applied to these scans produces incomprehensible - * results. In other words, the user may have been scanning a different finger - * for each stage or something like that. Like negative error codes, this - * return code indicates that the enrollment process has been aborted. - * - * The fp_enroll_result#FP_ENROLL_PASS code will only ever be returned for - * non-final stages. This return code indicates that the scan was acceptable - * and the next call into this function will advance onto the next enroll - * stage. - * - * The fp_enroll_result#FP_ENROLL_COMPLETE code will only ever be returned - * from the final enroll stage. It indicates that enrollment completed - * successfully, and that print_data has been assigned to point to the - * resultant enrollment data. The print_data parameter will not be modified - * during any other enrollment stages, hence it is actually legal to pass NULL - * as this argument for all but the final stage. - * - * If the device is an imaging device, it can also return the image from - * the scan, even when the enroll fails with a RETRY or FAIL code. It is legal - * to call this function even on non-imaging devices, just don't expect them to - * provide images. - * - * \param dev the device - * \param print_data a location to return the resultant enrollment data from - * the final stage. Must be freed with fp_print_data_free() after use. - * \param img location to store the scan image. accepts NULL for no image - * storage. If an image is returned, it must be freed with fp_img_free() after - * use. - * \return negative code on error, otherwise a code from #fp_enroll_result - */ -API_EXPORTED int fp_enroll_finger_img(struct fp_dev *dev, - struct fp_print_data **print_data, struct fp_img **img) -{ - struct fp_driver *drv = dev->drv; - int stage = dev->__enroll_stage; - gboolean final = FALSE; - struct sync_enroll_data *edata; - int r; - - if (!dev->nr_enroll_stages || !drv->enroll_start) { - fp_err("driver %s has 0 enroll stages or no enroll func", - drv->name); - return -ENOTSUP; - } - - if (stage == -1) { - fp_dbg("starting enrollment"); - r = fpi_drv_enroll_start(dev, sync_enroll_cb); - if (r < 0) { - fp_err("failed to start enrollment"); - return r; - } - while (dev->state == DEV_STATE_ENROLL_STARTING) { - r = fp_handle_events(); - if (r < 0) - goto err; - } - - if (dev->state != DEV_STATE_ENROLLING) { - r = -EIO; - goto err; - } - - dev->__enroll_stage = ++stage; - dev->enroll_data = g_malloc0(sizeof(struct sync_enroll_data)); - } else if (stage >= dev->nr_enroll_stages) { - fp_err("exceeding number of enroll stages for device claimed by " - "driver %s (%d stages)", drv->name, dev->nr_enroll_stages); - dev->__enroll_stage = -1; - r = -EINVAL; - final = TRUE; - goto out; - } - fp_dbg("%s will handle enroll stage %d/%d", drv->name, stage, - dev->nr_enroll_stages - 1); - - edata = dev->enroll_data; - while (!edata->populated) { - r = fp_handle_events(); - if (r < 0) { - g_free(edata); - goto err; - } - } - - edata->populated = FALSE; - - if (img) - *img = edata->img; - else - fp_img_free(edata->img); - - r = edata->result; - switch (r) { - case FP_ENROLL_PASS: - fp_dbg("enroll stage passed"); - dev->__enroll_stage = stage + 1; - break; - case FP_ENROLL_COMPLETE: - fp_dbg("enroll complete"); - dev->__enroll_stage = -1; - *print_data = edata->data; - final = TRUE; - break; - case FP_ENROLL_RETRY: - fp_dbg("enroll should retry"); - break; - case FP_ENROLL_RETRY_TOO_SHORT: - fp_dbg("swipe was too short, enroll should retry"); - break; - case FP_ENROLL_RETRY_CENTER_FINGER: - fp_dbg("finger was not centered, enroll should retry"); - break; - case FP_ENROLL_RETRY_REMOVE_FINGER: - fp_dbg("scan failed, remove finger and retry"); - break; - case FP_ENROLL_FAIL: - fp_err("enroll failed"); - dev->__enroll_stage = -1; - final = TRUE; - break; - default: - fp_err("unrecognised return code %d", r); - dev->__enroll_stage = -1; - r = -EINVAL; - final = TRUE; - break; - } - -out: - if (final) { - fp_dbg("ending enrollment"); - if (fpi_drv_enroll_stop(dev) == 0) - while (dev->state == DEV_STATE_ENROLL_STOPPING) { - if (fp_handle_events() < 0) - break; - } - g_free(dev->enroll_data); - } - - return r; - -err: - if (fpi_drv_enroll_stop(dev) == 0) - while (dev->state == DEV_STATE_ENROLL_STOPPING) - if (fp_handle_events() < 0) - break; - return r; -} - -struct sync_verify_data { - gboolean populated; - int result; - struct fp_img *img; -}; - -static void sync_verify_cb(struct fp_dev *dev, int result, struct fp_img *img) -{ - struct sync_verify_data *vdata = dev->sync_verify_data; - vdata->result = result; - vdata->img = img; - vdata->populated = TRUE; -} - -/** \ingroup dev - * Performs a new scan and verify it against a previously enrolled print. - * If the device is an imaging device, it can also return the image from - * the scan, even when the verify fails with a RETRY code. It is legal to - * call this function even on non-imaging devices, just don't expect them to - * provide images. - * - * \param dev the device to perform the scan. - * \param enrolled_print the print to verify against. Must have been previously - * enrolled with a device compatible to the device selected to perform the scan. - * \param img location to store the scan image. accepts NULL for no image - * storage. If an image is returned, it must be freed with fp_img_free() after - * use. - * \return negative code on error, otherwise a code from #fp_verify_result - */ -API_EXPORTED int fp_verify_finger_img(struct fp_dev *dev, - struct fp_print_data *enrolled_print, struct fp_img **img) -{ - struct fp_driver *drv = dev->drv; - struct sync_verify_data *vdata; - int r; - - if (!enrolled_print) { - fp_err("no print given"); - return -EINVAL; - } - - if (!drv->verify_start) { - fp_err("driver %s has no verify func", drv->name); - return -ENOTSUP; - } - - if (!fp_dev_supports_print_data(dev, enrolled_print)) { - fp_err("print is not compatible with device"); - return -EINVAL; - } - - fp_dbg("to be handled by %s", drv->name); - r = fpi_drv_verify_start(dev, sync_verify_cb, enrolled_print); - if (r < 0) { - fp_dbg("verify_start error %d", r); - return r; - } - while (dev->state == DEV_STATE_VERIFY_STARTING) { - r = fp_handle_events(); - if (r < 0) - goto err; - } - if (dev->state != DEV_STATE_VERIFYING) { - r = -EIO; - goto err; - } - - dev->sync_verify_data = g_malloc0(sizeof(struct sync_verify_data)); - vdata = dev->sync_verify_data; - - while (!vdata->populated) { - r = fp_handle_events(); - if (r < 0) { - g_free(vdata); - goto err; - } - } - - if (img) - *img = vdata->img; - else - fp_img_free(vdata->img); - - r = vdata->result; - g_free(dev->sync_verify_data); - switch (r) { - case FP_VERIFY_NO_MATCH: - fp_dbg("result: no match"); - break; - case FP_VERIFY_MATCH: - fp_dbg("result: match"); - break; - case FP_VERIFY_RETRY: - fp_dbg("verify should retry"); - break; - case FP_VERIFY_RETRY_TOO_SHORT: - fp_dbg("swipe was too short, verify should retry"); - break; - case FP_VERIFY_RETRY_CENTER_FINGER: - fp_dbg("finger was not centered, verify should retry"); - break; - case FP_VERIFY_RETRY_REMOVE_FINGER: - fp_dbg("scan failed, remove finger and retry"); - break; - default: - fp_err("unrecognised return code %d", r); - r = -EINVAL; - } - -err: - fp_dbg("ending verification"); - if (fpi_drv_verify_stop(dev) == 0) { - while (dev->state == DEV_STATE_VERIFY_STOPPING) { - if (fp_handle_events() < 0) - break; - } - } - - return r; -} - -struct sync_identify_data { - gboolean populated; - int result; - size_t match_offset; - struct fp_img *img; -}; - -static void sync_identify_cb(struct fp_dev *dev, int result, - size_t match_offset, struct fp_img *img) -{ - struct sync_identify_data *idata = dev->sync_identify_data; - idata->result = result; - idata->match_offset = match_offset; - idata->img = img; - idata->populated = TRUE; -} - -/** \ingroup dev - * Performs a new scan and attempts to identify the scanned finger against - * a collection of previously enrolled fingerprints. - * If the device is an imaging device, it can also return the image from - * the scan, even when identification fails with a RETRY code. It is legal to - * call this function even on non-imaging devices, just don't expect them to - * provide images. - * - * This function returns codes from #fp_verify_result. The return code - * fp_verify_result#FP_VERIFY_MATCH indicates that the scanned fingerprint - * does appear in the print gallery, and the match_offset output parameter - * will indicate the index into the print gallery array of the matched print. - * - * This function will not necessarily examine the whole print gallery, it - * will return as soon as it finds a matching print. - * - * Not all devices support identification. -ENOTSUP will be returned when - * this is the case. - * - * \param dev the device to perform the scan. - * \param print_gallery NULL-terminated array of pointers to the prints to - * identify against. Each one must have been previously enrolled with a device - * compatible to the device selected to perform the scan. - * \param match_offset output location to store the array index of the matched - * gallery print (if any was found). Only valid if FP_VERIFY_MATCH was - * returned. - * \param img location to store the scan image. accepts NULL for no image - * storage. If an image is returned, it must be freed with fp_img_free() after - * use. - * \return negative code on error, otherwise a code from #fp_verify_result - */ -API_EXPORTED int fp_identify_finger_img(struct fp_dev *dev, - struct fp_print_data **print_gallery, size_t *match_offset, - struct fp_img **img) -{ - struct fp_driver *drv = dev->drv; - struct sync_identify_data *idata; - int r; - - if (!drv->identify_start) { - fp_dbg("driver %s has no identify func", drv->name); - return -ENOTSUP; - } - fp_dbg("to be handled by %s", drv->name); - - r = fpi_drv_identify_start(dev, sync_identify_cb, print_gallery); - if (r < 0) { - fp_err("identify_start error %d", r); - return r; - } - while (dev->state == DEV_STATE_IDENTIFY_STARTING) { - r = fp_handle_events(); - if (r < 0) - goto err; - } - if (dev->state != DEV_STATE_IDENTIFYING) { - r = -EIO; - goto err; - } - - dev->sync_identify_data = g_malloc0(sizeof(struct sync_identify_data)); - idata = dev->sync_identify_data; - - while (!idata->populated) { - r = fp_handle_events(); - if (r < 0) { - g_free(idata); - goto err; - } - } - - if (img) - *img = idata->img; - else - fp_img_free(idata->img); - - r = idata->result; - switch (r) { - case FP_VERIFY_NO_MATCH: - fp_dbg("result: no match"); - break; - case FP_VERIFY_MATCH: - fp_dbg("result: match at offset %zd", match_offset); - *match_offset = idata->match_offset; - break; - case FP_VERIFY_RETRY: - fp_dbg("verify should retry"); - break; - case FP_VERIFY_RETRY_TOO_SHORT: - fp_dbg("swipe was too short, verify should retry"); - break; - case FP_VERIFY_RETRY_CENTER_FINGER: - fp_dbg("finger was not centered, verify should retry"); - break; - case FP_VERIFY_RETRY_REMOVE_FINGER: - fp_dbg("scan failed, remove finger and retry"); - break; - default: - fp_err("unrecognised return code %d", r); - r = -EINVAL; - } - g_free(dev->sync_identify_data); - -err: - if (fpi_drv_identify_stop(dev) == 0) { - while (dev->state == DEV_STATE_IDENTIFY_STOPPING) { - if (fp_handle_events() < 0) - break; - } - } - - return r; -} - /** \ingroup core * Initialise libfprint. This function must be called before you attempt to * use the library in any way. @@ -1310,14 +786,18 @@ API_EXPORTED int fp_init(void) */ API_EXPORTED void fp_exit(void) { - GSList *elem = opened_devices; fp_dbg(""); - if (elem != NULL) { - do { - fp_dbg("naughty app left a device open on exit!"); - do_close((struct fp_dev *) elem->data); - } while ((elem = g_slist_next(elem))); + if (opened_devices) { + GSList *copy = g_slist_copy(opened_devices); + GSList *elem = copy; + fp_dbg("naughty app left devices open on exit!"); + + do + fp_dev_close((struct fp_dev *) elem->data); + while ((elem = g_slist_next(elem))); + + g_slist_free(copy); g_slist_free(opened_devices); opened_devices = NULL; } @@ -1329,4 +809,3 @@ API_EXPORTED void fp_exit(void) libusb_exit(); } - diff --git a/libfprint/drivers/aes2501.c b/libfprint/drivers/aes2501.c index 37439b50..f0ea95d2 100644 --- a/libfprint/drivers/aes2501.c +++ b/libfprint/drivers/aes2501.c @@ -907,7 +907,7 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) } dev->priv = g_malloc0(sizeof(struct aes2501_dev)); - fpi_imgdev_init_complete(dev, 0); + fpi_imgdev_open_complete(dev, 0); return 0; } @@ -915,7 +915,7 @@ static void dev_deinit(struct fp_img_dev *dev) { g_free(dev->priv); libusb_release_interface(dev->udev, 0); - fpi_imgdev_deinit_complete(dev); + fpi_imgdev_close_complete(dev); } static const struct usb_id id_table[] = { @@ -934,8 +934,8 @@ struct fp_img_driver aes2501_driver = { .img_height = -1, .img_width = 192, - .init = dev_init, - .deinit = dev_deinit, + .open = dev_init, + .close = dev_deinit, .activate = dev_activate, .deactivate = dev_deactivate, }; diff --git a/libfprint/drivers/aes4000.c b/libfprint/drivers/aes4000.c index cc838e71..ff3b3c25 100644 --- a/libfprint/drivers/aes4000.c +++ b/libfprint/drivers/aes4000.c @@ -213,7 +213,7 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) dev->priv = g_malloc0(sizeof(struct aes4k_dev)); if (r == 0) - fpi_imgdev_init_complete(dev, 0); + fpi_imgdev_open_complete(dev, 0); return r; } @@ -222,7 +222,7 @@ static void dev_deinit(struct fp_img_dev *dev) { g_free(dev->priv); libusb_release_interface(dev->udev, 0); - fpi_imgdev_deinit_complete(dev); + fpi_imgdev_close_complete(dev); } static const struct usb_id id_table[] = { @@ -245,8 +245,8 @@ struct fp_img_driver aes4000_driver = { /* temporarily lowered until image quality improves */ .bz3_threshold = 9, - .init = dev_init, - .deinit = dev_deinit, + .open = dev_init, + .close = dev_deinit, .activate = dev_activate, .deactivate = dev_deactivate, }; diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index c63f7796..214d4fd7 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -840,7 +840,7 @@ static int dev_init(struct fp_dev *dev, unsigned long driver_data) dev->priv = upekdev; dev->nr_enroll_stages = 3; - fpi_drvcb_init_complete(dev, 0); + fpi_drvcb_open_complete(dev, 0); return 0; } @@ -848,7 +848,7 @@ static void dev_exit(struct fp_dev *dev) { libusb_release_interface(dev->udev, 0); g_free(dev->priv); - fpi_drvcb_deinit_complete(dev); + fpi_drvcb_close_complete(dev); } static const unsigned char enroll_init[] = { @@ -1415,8 +1415,8 @@ struct fp_driver upekts_driver = { .name = FP_COMPONENT, .full_name = "UPEK TouchStrip", .id_table = id_table, - .init = dev_init, - .deinit = dev_exit, + .open = dev_init, + .close = dev_exit, .enroll_start = enroll_start, .enroll_stop = enroll_stop, .verify_start = verify_start, diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index e5ed85cf..93b79b08 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -1096,7 +1096,7 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) urudev->interface = iface_desc->bInterfaceNumber; AES_set_encrypt_key(crkey, 128, &urudev->aeskey); dev->priv = urudev; - fpi_imgdev_init_complete(dev, 0); + fpi_imgdev_open_complete(dev, 0); return 0; } @@ -1105,7 +1105,7 @@ static void dev_deinit(struct fp_img_dev *dev) struct uru4k_dev *urudev = dev->priv; libusb_release_interface(dev->udev, urudev->interface); g_free(urudev); - fpi_imgdev_deinit_complete(dev); + fpi_imgdev_close_complete(dev); } static const struct usb_id id_table[] = { @@ -1142,8 +1142,8 @@ struct fp_img_driver uru4000_driver = { .img_height = 289, .img_width = 384, - .init = dev_init, - .deinit = dev_deinit, + .open = dev_init, + .close = dev_deinit, .activate = dev_activate, .deactivate = dev_deactivate, .change_state = dev_change_state, diff --git a/libfprint/drv.c b/libfprint/drv.c index 9ee54cfe..a7ba846c 100644 --- a/libfprint/drv.c +++ b/libfprint/drv.c @@ -19,277 +19,11 @@ #define FP_COMPONENT "drv" +#include #include #include "fp_internal.h" -/* Lib-driver: start device initialisation */ -int fpi_drv_init(struct fp_dev *dev, unsigned long driver_data) -{ - struct fp_driver *drv = dev->drv; - if (!drv->init) { - fpi_drvcb_init_complete(dev, 0); - return 0; - } - dev->state = DEV_STATE_INITIALIZING; - return drv->init(dev, driver_data); -} - -/* Driver-lib: device initialisation complete */ -void fpi_drvcb_init_complete(struct fp_dev *dev, int status) -{ - fp_dbg("status %d", status); - BUG_ON(dev->state != DEV_STATE_INITIALIZING); - dev->state = (status) ? DEV_STATE_ERROR : DEV_STATE_INITIALIZED; -} - -/* Lib-driver: start device deinitialisation */ -void fpi_drv_deinit(struct fp_dev *dev) -{ - struct fp_driver *drv = dev->drv; - if (!drv->deinit) { - fpi_drvcb_deinit_complete(dev); - return; - } - - dev->state = DEV_STATE_DEINITIALIZING; - drv->deinit(dev); -} - -/* Driver-lib: device deinitialisation complete */ -void fpi_drvcb_deinit_complete(struct fp_dev *dev) -{ - fp_dbg(""); - BUG_ON(dev->state != DEV_STATE_DEINITIALIZING); - dev->state = DEV_STATE_DEINITIALIZED; -} - -/* Lib-driver: start enrollment */ -int fpi_drv_enroll_start(struct fp_dev *dev, fp_enroll_stage_cb callback) -{ - struct fp_driver *drv = dev->drv; - int r; - fp_dbg(""); - if (!drv->enroll_start) - return -ENOTSUP; - dev->state = DEV_STATE_ENROLL_STARTING; - dev->enroll_cb = callback; - r = drv->enroll_start(dev); - if (r < 0) { - dev->enroll_cb = NULL; - dev->state = DEV_STATE_ERROR; - } - return r; -} - -/* Driver-lib: enrollment has now started, expect results soon */ -void fpi_drvcb_enroll_started(struct fp_dev *dev, int status) -{ - fp_dbg("status %d", status); - BUG_ON(dev->state != DEV_STATE_ENROLL_STARTING); - dev->state = (status) ? DEV_STATE_ERROR : DEV_STATE_ENROLLING; -} - -/* Driver-lib: an enroll stage has completed */ -void fpi_drvcb_enroll_stage_completed(struct fp_dev *dev, int result, - struct fp_print_data *data, struct fp_img *img) -{ - BUG_ON(dev->state != DEV_STATE_ENROLLING); - fp_dbg("result %d", result); - if (!dev->enroll_cb) { - fp_dbg("ignoring enroll result as no callback is subscribed"); - return; - } - if (result == FP_ENROLL_COMPLETE && !data) { - fp_err("BUG: complete but no data?"); - result = FP_ENROLL_FAIL; - } - dev->enroll_cb(dev, result, data, img); -} - -/* Lib-driver: stop enrollment */ -int fpi_drv_enroll_stop(struct fp_dev *dev) -{ - struct fp_driver *drv = dev->drv; - fp_dbg(""); - dev->enroll_cb = NULL; - - if (!drv->enroll_start) - return -ENOTSUP; - if (!drv->enroll_stop) { - dev->state = DEV_STATE_INITIALIZED; - return 0; - } - - dev->state = DEV_STATE_ENROLL_STOPPING; - return drv->enroll_stop(dev); -} - -/* Driver-lib: enrollment has stopped */ -void fpi_drvcb_enroll_stopped(struct fp_dev *dev) -{ - fp_dbg(""); - BUG_ON(dev->state != DEV_STATE_ENROLL_STOPPING); - dev->state = DEV_STATE_INITIALIZED; -} - -/* Lib-driver: start verification */ -int fpi_drv_verify_start(struct fp_dev *dev, fp_verify_cb callback, - struct fp_print_data *data) -{ - struct fp_driver *drv = dev->drv; - int r; - - fp_dbg(""); - if (!drv->verify_start) - return -ENOTSUP; - dev->state = DEV_STATE_VERIFY_STARTING; - dev->verify_cb = callback; - dev->verify_data = data; - r = drv->verify_start(dev); - if (r < 0) { - dev->verify_cb = NULL; - dev->state = DEV_STATE_ERROR; - } - return r; -} - -/* Driver-lib: verification has started, expect results soon */ -void fpi_drvcb_verify_started(struct fp_dev *dev, int status) -{ - fp_dbg(""); - BUG_ON(dev->state != DEV_STATE_VERIFY_STARTING); - dev->state = (status) ? DEV_STATE_ERROR : DEV_STATE_VERIFYING; -} - -/* Driver-lib: report a verify result (which might mark completion) */ -void fpi_drvcb_report_verify_result(struct fp_dev *dev, int result, - struct fp_img *img) -{ - fp_dbg("result %d", result); - BUG_ON(dev->state != DEV_STATE_VERIFYING); - if (result < 0 || result == FP_VERIFY_NO_MATCH - || result == FP_VERIFY_MATCH) { - dev->state = DEV_STATE_VERIFY_DONE; - } - - if (!dev->verify_cb) { - fp_dbg("ignoring verify result as no callback is subscribed"); - return; - } - dev->verify_cb(dev, result, img); -} - -/* Lib-driver: stop verification */ -int fpi_drv_verify_stop(struct fp_dev *dev) -{ - struct fp_driver *drv = dev->drv; - gboolean iterating = (dev->state == DEV_STATE_VERIFYING); - - fp_dbg(""); - BUG_ON(dev->state != DEV_STATE_ERROR - && dev->state != DEV_STATE_VERIFYING - && dev->state != DEV_STATE_VERIFY_DONE); - dev->verify_cb = NULL; - - if (!drv->verify_start) - return -ENOTSUP; - if (!drv->verify_stop) { - dev->state = DEV_STATE_INITIALIZED; - return 0; - } - - dev->state = DEV_STATE_VERIFY_STOPPING; - return drv->verify_stop(dev, iterating); -} - -/* Driver-lib: verification has stopped */ -void fpi_drvcb_verify_stopped(struct fp_dev *dev) -{ - fp_dbg(""); - BUG_ON(dev->state != DEV_STATE_VERIFY_STOPPING); - dev->state = DEV_STATE_INITIALIZED; -} - - -/* Lib-driver: start identification */ -int fpi_drv_identify_start(struct fp_dev *dev, fp_identify_cb callback, - struct fp_print_data **gallery) -{ - struct fp_driver *drv = dev->drv; - int r; - - fp_dbg(""); - if (!drv->identify_start) - return -ENOTSUP; - dev->state = DEV_STATE_IDENTIFY_STARTING; - dev->identify_cb = callback; - dev->identify_data = gallery; - r = drv->identify_start(dev); - if (r < 0) { - dev->identify_cb = NULL; - dev->state = DEV_STATE_ERROR; - } - return r; -} - -/* Driver-lib: identification has started, expect results soon */ -void fpi_drvcb_identify_started(struct fp_dev *dev, int status) -{ - fp_dbg(""); - BUG_ON(dev->state != DEV_STATE_IDENTIFY_STARTING); - dev->state = (status) ? DEV_STATE_ERROR : DEV_STATE_IDENTIFYING; -} - -/* Driver-lib: report a verify result (which might mark completion) */ -void fpi_drvcb_report_identify_result(struct fp_dev *dev, int result, - size_t match_offset, struct fp_img *img) -{ - fp_dbg("result %d", result); - BUG_ON(dev->state != DEV_STATE_IDENTIFYING - && dev->state != DEV_STATE_ERROR); - if (result < 0 || result == FP_VERIFY_NO_MATCH - || result == FP_VERIFY_MATCH) { - dev->state = DEV_STATE_IDENTIFY_DONE; - } - - if (!dev->identify_cb) { - fp_dbg("ignoring verify result as no callback is subscribed"); - return; - } - dev->identify_cb(dev, result, match_offset, img); -} - -/* Lib-driver: stop identification */ -int fpi_drv_identify_stop(struct fp_dev *dev) -{ - struct fp_driver *drv = dev->drv; - gboolean iterating = (dev->state == DEV_STATE_IDENTIFYING); - - fp_dbg(""); - BUG_ON(dev->state != DEV_STATE_IDENTIFYING - && dev->state != DEV_STATE_IDENTIFY_DONE); - dev->identify_cb = NULL; - - if (!drv->identify_start) - return -ENOTSUP; - if (!drv->identify_stop) { - dev->state = DEV_STATE_INITIALIZED; - return 0; - } - - dev->state = DEV_STATE_IDENTIFY_STOPPING; - return drv->identify_stop(dev, iterating); -} - -/* Driver-lib: identification has stopped */ -void fpi_drvcb_identify_stopped(struct fp_dev *dev) -{ - fp_dbg(""); - BUG_ON(dev->state != DEV_STATE_IDENTIFY_STOPPING); - dev->state = DEV_STATE_INITIALIZED; -} - /* SSM: sequential state machine * Asynchronous driver design encourages some kind of state machine behind it. * In most cases, the state machine is entirely linear - you only go to the diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index e9676e86..6a365c15 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -91,15 +91,6 @@ enum fp_dev_state { DEV_STATE_IDENTIFY_STOPPING, }; -typedef void (*fp_enroll_stage_cb)(struct fp_dev *dev, int result, - struct fp_print_data *data, struct fp_img *img); - -typedef void (*fp_verify_cb)(struct fp_dev *dev, int result, - struct fp_img *img); - -typedef void (*fp_identify_cb)(struct fp_dev *dev, int result, - size_t match_offset, struct fp_img *img); - struct fp_dev { struct fp_driver *drv; libusb_dev_handle *udev; @@ -114,15 +105,29 @@ struct fp_dev { /* drivers should not mess with any of the below */ enum fp_dev_state state; - /* FIXME: convert this to generic state operational data mechanism? */ int __enroll_stage; - fp_enroll_stage_cb enroll_cb; - void *enroll_data; - void *sync_verify_data; + + /* async I/O callbacks and data */ + /* FIXME: convert this to generic state operational data mechanism? */ + fp_dev_open_cb open_cb; + void *open_cb_data; + fp_dev_close_cb close_cb; + void *close_cb_data; + fp_enroll_stage_cb enroll_stage_cb; + void *enroll_stage_cb_data; + fp_enroll_stop_cb enroll_stop_cb; + void *enroll_stop_cb_data; fp_verify_cb verify_cb; - void *identify_data; - void *sync_identify_data; + void *verify_cb_data; + fp_verify_stop_cb verify_stop_cb; + void *verify_stop_cb_data; fp_identify_cb identify_cb; + void *identify_cb_data; + fp_identify_stop_cb identify_stop_cb; + void *identify_stop_cb_data; + + /* FIXME: better place to put this? */ + struct fp_print_data **identify_gallery; }; enum fp_imgdev_state { @@ -197,8 +202,8 @@ struct fp_driver { /* Device operations */ int (*discover)(const struct usb_id *usb_id, uint32_t *devtype); - int (*init)(struct fp_dev *dev, unsigned long driver_data); - void (*deinit)(struct fp_dev *dev); + int (*open)(struct fp_dev *dev, unsigned long driver_data); + void (*close)(struct fp_dev *dev); int (*enroll_start)(struct fp_dev *dev); int (*enroll_stop)(struct fp_dev *dev); int (*verify_start)(struct fp_dev *dev); @@ -221,8 +226,8 @@ struct fp_img_driver { int bz3_threshold; /* Device operations */ - int (*init)(struct fp_img_dev *dev, unsigned long driver_data); - void (*deinit)(struct fp_img_dev *dev); + int (*open)(struct fp_img_dev *dev, unsigned long driver_data); + void (*close)(struct fp_img_dev *dev); int (*activate)(struct fp_img_dev *dev, enum fp_imgdev_state state); int (*change_state)(struct fp_img_dev *dev, enum fp_imgdev_state state); void (*deactivate)(struct fp_img_dev *dev); @@ -236,6 +241,8 @@ extern struct fp_img_driver aes2501_driver; extern struct fp_img_driver aes4000_driver; extern struct fp_img_driver fdu2000_driver; +extern GSList *opened_devices; + void fpi_img_driver_setup(struct fp_img_driver *idriver); #define fpi_driver_to_img_driver(drv) \ @@ -363,37 +370,27 @@ void fpi_ssm_jump_to_state(struct fpi_ssm *machine, int state); void fpi_ssm_mark_completed(struct fpi_ssm *machine); void fpi_ssm_mark_aborted(struct fpi_ssm *machine, int error); -int fpi_drv_init(struct fp_dev *dev, unsigned long driver_data); -void fpi_drvcb_init_complete(struct fp_dev *dev, int status); -void fpi_drv_deinit(struct fp_dev *dev); -void fpi_drvcb_deinit_complete(struct fp_dev *dev); +void fpi_drvcb_open_complete(struct fp_dev *dev, int status); +void fpi_drvcb_close_complete(struct fp_dev *dev); -int fpi_drv_enroll_start(struct fp_dev *dev, fp_enroll_stage_cb callback); void fpi_drvcb_enroll_started(struct fp_dev *dev, int status); void fpi_drvcb_enroll_stage_completed(struct fp_dev *dev, int result, struct fp_print_data *data, struct fp_img *img); -int fpi_drv_enroll_stop(struct fp_dev *dev); void fpi_drvcb_enroll_stopped(struct fp_dev *dev); -int fpi_drv_verify_start(struct fp_dev *dev, fp_verify_cb callback, - struct fp_print_data *data); void fpi_drvcb_verify_started(struct fp_dev *dev, int status); void fpi_drvcb_report_verify_result(struct fp_dev *dev, int result, struct fp_img *img); -int fpi_drv_verify_stop(struct fp_dev *dev); void fpi_drvcb_verify_stopped(struct fp_dev *dev); -int fpi_drv_identify_start(struct fp_dev *dev, fp_identify_cb callback, - struct fp_print_data **gallery); void fpi_drvcb_identify_started(struct fp_dev *dev, int status); void fpi_drvcb_report_identify_result(struct fp_dev *dev, int result, size_t match_offset, struct fp_img *img); -int fpi_drv_identify_stop(struct fp_dev *dev); void fpi_drvcb_identify_stopped(struct fp_dev *dev); /* for image drivers */ -void fpi_imgdev_init_complete(struct fp_img_dev *imgdev, int status); -void fpi_imgdev_deinit_complete(struct fp_img_dev *imgdev); +void fpi_imgdev_open_complete(struct fp_img_dev *imgdev, int status); +void fpi_imgdev_close_complete(struct fp_img_dev *imgdev); void fpi_imgdev_activate_complete(struct fp_img_dev *imgdev, int status); void fpi_imgdev_deactivate_complete(struct fp_img_dev *imgdev); void fpi_imgdev_report_finger_status(struct fp_img_dev *imgdev, diff --git a/libfprint/fprint.h b/libfprint/fprint.h index f7626756..4cebba33 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -274,5 +274,42 @@ int fp_handle_events(void); int fp_init(void); void fp_exit(void); +/* Asynchronous I/O */ + +typedef void (*fp_dev_open_cb)(struct fp_dev *dev, int status, void *user_data); +int fp_async_dev_open(struct fp_dscv_dev *ddev, fp_dev_open_cb callback, + void *user_data); + +typedef void (*fp_dev_close_cb)(struct fp_dev *dev, void *user_data); +void fp_async_dev_close(struct fp_dev *dev, fp_dev_close_cb callback, + void *user_data); + +typedef void (*fp_enroll_stage_cb)(struct fp_dev *dev, int result, + struct fp_print_data *print, struct fp_img *img, void *user_data); +int fp_async_enroll_start(struct fp_dev *dev, fp_enroll_stage_cb callback, + void *user_data); + +typedef void (*fp_enroll_stop_cb)(struct fp_dev *dev, void *user_data); +int fp_async_enroll_stop(struct fp_dev *dev, fp_enroll_stop_cb callback, + void *user_data); + +typedef void (*fp_verify_cb)(struct fp_dev *dev, int result, + struct fp_img *img, void *user_data); +int fp_async_verify_start(struct fp_dev *dev, struct fp_print_data *data, + fp_verify_cb callback, void *user_data); + +typedef void (*fp_verify_stop_cb)(struct fp_dev *dev, void *user_data); +int fp_async_verify_stop(struct fp_dev *dev, fp_verify_stop_cb callback, + void *user_data); + +typedef void (*fp_identify_cb)(struct fp_dev *dev, int result, + size_t match_offset, struct fp_img *img, void *user_data); +int fp_async_identify_start(struct fp_dev *dev, struct fp_print_data **gallery, + fp_identify_cb callback, void *user_data); + +typedef void (*fp_identify_stop_cb)(struct fp_dev *dev, void *user_data); +int fp_async_identify_stop(struct fp_dev *dev, fp_identify_stop_cb callback, + void *user_data); + #endif diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index e3eb8c5f..1fd8ee15 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -27,7 +27,7 @@ #define MIN_ACCEPTABLE_MINUTIAE 10 #define BOZORTH3_DEFAULT_THRESHOLD 40 -static int img_dev_init(struct fp_dev *dev, unsigned long driver_data) +static int img_dev_open(struct fp_dev *dev, unsigned long driver_data) { struct fp_img_dev *imgdev = g_malloc0(sizeof(*imgdev)); struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(dev->drv); @@ -40,12 +40,12 @@ static int img_dev_init(struct fp_dev *dev, unsigned long driver_data) /* for consistency in driver code, allow udev access through imgdev */ imgdev->udev = dev->udev; - if (imgdrv->init) { - r = imgdrv->init(imgdev, driver_data); + if (imgdrv->open) { + r = imgdrv->open(imgdev, driver_data); if (r) goto err; } else { - fpi_drvcb_init_complete(dev, 0); + fpi_drvcb_open_complete(dev, 0); } return 0; @@ -54,25 +54,25 @@ err: return r; } -void fpi_imgdev_init_complete(struct fp_img_dev *imgdev, int status) +void fpi_imgdev_open_complete(struct fp_img_dev *imgdev, int status) { - fpi_drvcb_init_complete(imgdev->dev, status); + fpi_drvcb_open_complete(imgdev->dev, status); } -static void img_dev_deinit(struct fp_dev *dev) +static void img_dev_close(struct fp_dev *dev) { struct fp_img_dev *imgdev = dev->priv; struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(dev->drv); - if (imgdrv->deinit) - imgdrv->deinit(imgdev); + if (imgdrv->close) + imgdrv->close(imgdev); else - fpi_drvcb_deinit_complete(dev); + fpi_drvcb_close_complete(dev); } -void fpi_imgdev_deinit_complete(struct fp_img_dev *imgdev) +void fpi_imgdev_close_complete(struct fp_img_dev *imgdev) { - fpi_drvcb_deinit_complete(imgdev->dev); + fpi_drvcb_close_complete(imgdev->dev); g_free(imgdev); } @@ -173,6 +173,9 @@ void fpi_imgdev_report_finger_status(struct fp_img_dev *imgdev, gboolean present) { int r = imgdev->action_result; + struct fp_print_data *data = imgdev->acquire_data; + struct fp_img *img = imgdev->acquire_img; + fp_dbg(present ? "finger on sensor" : "finger removed"); if (present && imgdev->action_state == IMG_ACQUIRE_STATE_AWAIT_FINGER_ON) { @@ -185,25 +188,29 @@ void fpi_imgdev_report_finger_status(struct fp_img_dev *imgdev, return; } + /* clear these before reporting results to avoid complications with + * call cascading in and out of the library */ + imgdev->acquire_img = NULL; + imgdev->acquire_data = NULL; + + /* finger removed, report results */ switch (imgdev->action) { case IMG_ACTION_ENROLL: - fpi_drvcb_enroll_stage_completed(imgdev->dev, r, imgdev->acquire_data, - imgdev->acquire_img); + fp_dbg("reporting enroll result"); + fpi_drvcb_enroll_stage_completed(imgdev->dev, r, data, img); break; case IMG_ACTION_VERIFY: - fpi_drvcb_report_verify_result(imgdev->dev, r, imgdev->acquire_img); - fp_print_data_free(imgdev->acquire_data); + fpi_drvcb_report_verify_result(imgdev->dev, r, img); + fp_print_data_free(data); break; case IMG_ACTION_IDENTIFY: fpi_drvcb_report_identify_result(imgdev->dev, r, - imgdev->identify_match_offset, imgdev->acquire_img); - fp_print_data_free(imgdev->acquire_data); + imgdev->identify_match_offset, img); + fp_print_data_free(data); default: fp_err("unhandled action %d", imgdev->action); break; } - imgdev->acquire_img = NULL; - imgdev->acquire_data = NULL; } static void verify_process_img(struct fp_img_dev *imgdev) @@ -237,7 +244,7 @@ static void identify_process_img(struct fp_img_dev *imgdev) match_score = BOZORTH3_DEFAULT_THRESHOLD; r = fpi_img_compare_print_data_to_gallery(imgdev->acquire_data, - imgdev->dev->identify_data, match_score, &match_offset); + imgdev->dev->identify_gallery, match_score, &match_offset); imgdev->action_result = r; imgdev->identify_match_offset = match_offset; @@ -486,8 +493,8 @@ static int img_dev_identify_stop(struct fp_dev *dev, gboolean iterating) void fpi_img_driver_setup(struct fp_img_driver *idriver) { idriver->driver.type = DRIVER_IMAGING; - idriver->driver.init = img_dev_init; - idriver->driver.deinit = img_dev_deinit; + idriver->driver.open = img_dev_open; + idriver->driver.close = img_dev_close; idriver->driver.enroll_start = img_dev_enroll_start; idriver->driver.enroll_stop = img_dev_enroll_stop; idriver->driver.verify_start = img_dev_verify_start; diff --git a/libfprint/sync.c b/libfprint/sync.c new file mode 100644 index 00000000..87c033ad --- /dev/null +++ b/libfprint/sync.c @@ -0,0 +1,512 @@ +/* + * Synchronous I/O functionality + * Copyright (C) 2007-2008 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#define FP_COMPONENT "sync" + +#include +#include + +#include "fp_internal.h" + +struct sync_open_data { + struct fp_dev *dev; + int status; +}; + +static void sync_open_cb(struct fp_dev *dev, int status, void *user_data) +{ + struct sync_open_data *odata = user_data; + fp_dbg("status %d", status); + odata->dev = dev; + odata->status = status; +} + +/** \ingroup dev + * Opens and initialises a device. This is the function you call in order + * to convert a \ref dscv_dev "discovered device" into an actual device handle + * that you can perform operations with. + * \param ddev the discovered device to open + * \returns the opened device handle, or NULL on error + */ +API_EXPORTED struct fp_dev *fp_dev_open(struct fp_dscv_dev *ddev) +{ + struct fp_dev *dev = NULL; + struct sync_open_data *odata = g_malloc0(sizeof(*odata)); + int r; + + fp_dbg(""); + r = fp_async_dev_open(ddev, sync_open_cb, odata); + if (r) + goto out; + + while (!odata->dev) + if (fp_handle_events() < 0) + goto out; + + if (odata->status == 0) + dev = odata->dev; + else + fp_dev_close(odata->dev); + +out: + g_free(odata); + return dev; +} + +static void sync_close_cb(struct fp_dev *dev, void *user_data) +{ + fp_dbg(""); + gboolean *closed = user_data; + *closed = TRUE; +} + +/** \ingroup dev + * Close a device. You must call this function when you are finished using + * a fingerprint device. + * \param dev the device to close. If NULL, function simply returns. + */ +API_EXPORTED void fp_dev_close(struct fp_dev *dev) +{ + gboolean closed = FALSE; + + if (!dev) + return; + + fp_dbg(""); + fp_async_dev_close(dev, sync_close_cb, &closed); + while (!closed) + if (fp_handle_events() < 0) + break; +} + +struct sync_enroll_data { + gboolean populated; + int result; + struct fp_print_data *data; + struct fp_img *img; +}; + +static void sync_enroll_cb(struct fp_dev *dev, int result, + struct fp_print_data *data, struct fp_img *img, void *user_data) +{ + struct sync_enroll_data *edata = user_data; + fp_dbg("result %d", result); + edata->result = result; + edata->data = data; + edata->img = img; + edata->populated = TRUE; +} + +static void enroll_stop_cb(struct fp_dev *dev, void *user_data) +{ + gboolean *stopped = user_data; + fp_dbg(""); + *stopped = TRUE; +} + +/** \ingroup dev + * Performs an enroll stage. See \ref enrolling for an explanation of enroll + * stages. + * + * If no enrollment is in process, this kicks of the process and runs the + * first stage. If an enrollment is already in progress, calling this + * function runs the next stage, which may well be the last. + * + * A negative error code may be returned from any stage. When this occurs, + * further calls to the enroll function will start a new enrollment process, + * i.e. a negative error code indicates that the enrollment process has been + * aborted. These error codes only ever indicate unexpected internal errors + * or I/O problems. + * + * The RETRY codes from #fp_enroll_result may be returned from any enroll + * stage. These codes indicate that the scan was not succesful in that the + * user did not position their finger correctly or similar. When a RETRY code + * is returned, the enrollment stage is not advanced, so the next call + * into this function will retry the current stage again. The current stage may + * need to be retried several times. + * + * The fp_enroll_result#FP_ENROLL_FAIL code may be returned from any enroll + * stage. This code indicates that even though the scans themselves have been + * acceptable, data processing applied to these scans produces incomprehensible + * results. In other words, the user may have been scanning a different finger + * for each stage or something like that. Like negative error codes, this + * return code indicates that the enrollment process has been aborted. + * + * The fp_enroll_result#FP_ENROLL_PASS code will only ever be returned for + * non-final stages. This return code indicates that the scan was acceptable + * and the next call into this function will advance onto the next enroll + * stage. + * + * The fp_enroll_result#FP_ENROLL_COMPLETE code will only ever be returned + * from the final enroll stage. It indicates that enrollment completed + * successfully, and that print_data has been assigned to point to the + * resultant enrollment data. The print_data parameter will not be modified + * during any other enrollment stages, hence it is actually legal to pass NULL + * as this argument for all but the final stage. + * + * If the device is an imaging device, it can also return the image from + * the scan, even when the enroll fails with a RETRY or FAIL code. It is legal + * to call this function even on non-imaging devices, just don't expect them to + * provide images. + * + * \param dev the device + * \param print_data a location to return the resultant enrollment data from + * the final stage. Must be freed with fp_print_data_free() after use. + * \param img location to store the scan image. accepts NULL for no image + * storage. If an image is returned, it must be freed with fp_img_free() after + * use. + * \return negative code on error, otherwise a code from #fp_enroll_result + */ +API_EXPORTED int fp_enroll_finger_img(struct fp_dev *dev, + struct fp_print_data **print_data, struct fp_img **img) +{ + struct fp_driver *drv = dev->drv; + int stage = dev->__enroll_stage; + gboolean final = FALSE; + gboolean stopped = FALSE; + struct sync_enroll_data *edata; + int r; + fp_dbg(""); + + /* FIXME __enroll_stage is ugly, can we replace it by some function that + * says whether we're enrolling or not, and then put __enroll_stage into + * edata? */ + + if (stage == -1) { + edata = g_malloc0(sizeof(struct sync_enroll_data)); + r = fp_async_enroll_start(dev, sync_enroll_cb, edata); + if (r < 0) { + g_free(edata); + return r; + } + + dev->__enroll_stage = ++stage; + } else if (stage >= dev->nr_enroll_stages) { + fp_err("exceeding number of enroll stages for device claimed by " + "driver %s (%d stages)", drv->name, dev->nr_enroll_stages); + dev->__enroll_stage = -1; + r = -EINVAL; + final = TRUE; + goto out; + } + fp_dbg("%s will handle enroll stage %d/%d", drv->name, stage, + dev->nr_enroll_stages - 1); + + /* FIXME this isn't very clean */ + edata = dev->enroll_stage_cb_data; + + while (!edata->populated) { + r = fp_handle_events(); + if (r < 0) { + g_free(edata); + goto err; + } + } + + edata->populated = FALSE; + + if (img) + *img = edata->img; + else + fp_img_free(edata->img); + + r = edata->result; + switch (r) { + case FP_ENROLL_PASS: + fp_dbg("enroll stage passed"); + dev->__enroll_stage = stage + 1; + break; + case FP_ENROLL_COMPLETE: + fp_dbg("enroll complete"); + dev->__enroll_stage = -1; + *print_data = edata->data; + final = TRUE; + break; + case FP_ENROLL_RETRY: + fp_dbg("enroll should retry"); + break; + case FP_ENROLL_RETRY_TOO_SHORT: + fp_dbg("swipe was too short, enroll should retry"); + break; + case FP_ENROLL_RETRY_CENTER_FINGER: + fp_dbg("finger was not centered, enroll should retry"); + break; + case FP_ENROLL_RETRY_REMOVE_FINGER: + fp_dbg("scan failed, remove finger and retry"); + break; + case FP_ENROLL_FAIL: + fp_err("enroll failed"); + dev->__enroll_stage = -1; + final = TRUE; + break; + default: + fp_err("unrecognised return code %d", r); + dev->__enroll_stage = -1; + r = -EINVAL; + final = TRUE; + break; + } + +out: + if (final) { + fp_dbg("ending enrollment"); + g_free(edata); + } + +err: + if (fp_async_enroll_stop(dev, enroll_stop_cb, &stopped) == 0) + while (!stopped) + if (fp_handle_events() < 0) + break; + return r; +} + +struct sync_verify_data { + gboolean populated; + int result; + struct fp_img *img; +}; + +static void sync_verify_cb(struct fp_dev *dev, int result, struct fp_img *img, + void *user_data) +{ + struct sync_verify_data *vdata = user_data; + vdata->result = result; + vdata->img = img; + vdata->populated = TRUE; +} + +static void verify_stop_cb(struct fp_dev *dev, void *user_data) +{ + gboolean *stopped = user_data; + fp_dbg(""); + *stopped = TRUE; +} + +/** \ingroup dev + * Performs a new scan and verify it against a previously enrolled print. + * If the device is an imaging device, it can also return the image from + * the scan, even when the verify fails with a RETRY code. It is legal to + * call this function even on non-imaging devices, just don't expect them to + * provide images. + * + * \param dev the device to perform the scan. + * \param enrolled_print the print to verify against. Must have been previously + * enrolled with a device compatible to the device selected to perform the scan. + * \param img location to store the scan image. accepts NULL for no image + * storage. If an image is returned, it must be freed with fp_img_free() after + * use. + * \return negative code on error, otherwise a code from #fp_verify_result + */ +API_EXPORTED int fp_verify_finger_img(struct fp_dev *dev, + struct fp_print_data *enrolled_print, struct fp_img **img) +{ + struct fp_driver *drv = dev->drv; + struct sync_verify_data *vdata; + gboolean stopped = FALSE; + int r; + + if (!enrolled_print) { + fp_err("no print given"); + return -EINVAL; + } + + if (!fp_dev_supports_print_data(dev, enrolled_print)) { + fp_err("print is not compatible with device"); + return -EINVAL; + } + + fp_dbg("to be handled by %s", drv->name); + vdata = g_malloc0(sizeof(struct sync_verify_data)); + r = fp_async_verify_start(dev, enrolled_print, sync_verify_cb, vdata); + if (r < 0) { + fp_dbg("verify_start error %d", r); + g_free(vdata); + return r; + } + + while (!vdata->populated) { + r = fp_handle_events(); + if (r < 0) { + g_free(vdata); + goto err; + } + } + + if (img) + *img = vdata->img; + else + fp_img_free(vdata->img); + + r = vdata->result; + g_free(vdata); + switch (r) { + case FP_VERIFY_NO_MATCH: + fp_dbg("result: no match"); + break; + case FP_VERIFY_MATCH: + fp_dbg("result: match"); + break; + case FP_VERIFY_RETRY: + fp_dbg("verify should retry"); + break; + case FP_VERIFY_RETRY_TOO_SHORT: + fp_dbg("swipe was too short, verify should retry"); + break; + case FP_VERIFY_RETRY_CENTER_FINGER: + fp_dbg("finger was not centered, verify should retry"); + break; + case FP_VERIFY_RETRY_REMOVE_FINGER: + fp_dbg("scan failed, remove finger and retry"); + break; + default: + fp_err("unrecognised return code %d", r); + r = -EINVAL; + } + +err: + fp_dbg("ending verification"); + if (fp_async_verify_stop(dev, verify_stop_cb, &stopped) == 0) + while (!stopped) + if (fp_handle_events() < 0) + break; + + return r; +} + +struct sync_identify_data { + gboolean populated; + int result; + size_t match_offset; + struct fp_img *img; +}; + +static void sync_identify_cb(struct fp_dev *dev, int result, + size_t match_offset, struct fp_img *img, void *user_data) +{ + struct sync_identify_data *idata = user_data; + idata->result = result; + idata->match_offset = match_offset; + idata->img = img; + idata->populated = TRUE; +} + +static void identify_stop_cb(struct fp_dev *dev, void *user_data) +{ + gboolean *stopped = user_data; + fp_dbg(""); + *stopped = TRUE; +} + +/** \ingroup dev + * Performs a new scan and attempts to identify the scanned finger against + * a collection of previously enrolled fingerprints. + * If the device is an imaging device, it can also return the image from + * the scan, even when identification fails with a RETRY code. It is legal to + * call this function even on non-imaging devices, just don't expect them to + * provide images. + * + * This function returns codes from #fp_verify_result. The return code + * fp_verify_result#FP_VERIFY_MATCH indicates that the scanned fingerprint + * does appear in the print gallery, and the match_offset output parameter + * will indicate the index into the print gallery array of the matched print. + * + * This function will not necessarily examine the whole print gallery, it + * will return as soon as it finds a matching print. + * + * Not all devices support identification. -ENOTSUP will be returned when + * this is the case. + * + * \param dev the device to perform the scan. + * \param print_gallery NULL-terminated array of pointers to the prints to + * identify against. Each one must have been previously enrolled with a device + * compatible to the device selected to perform the scan. + * \param match_offset output location to store the array index of the matched + * gallery print (if any was found). Only valid if FP_VERIFY_MATCH was + * returned. + * \param img location to store the scan image. accepts NULL for no image + * storage. If an image is returned, it must be freed with fp_img_free() after + * use. + * \return negative code on error, otherwise a code from #fp_verify_result + */ +API_EXPORTED int fp_identify_finger_img(struct fp_dev *dev, + struct fp_print_data **print_gallery, size_t *match_offset, + struct fp_img **img) +{ + struct fp_driver *drv = dev->drv; + gboolean stopped = FALSE; + struct sync_identify_data *idata + = g_malloc0(sizeof(struct sync_identify_data)); + int r; + + fp_dbg("to be handled by %s", drv->name); + + r = fp_async_identify_start(dev, print_gallery, sync_identify_cb, idata); + if (r < 0) { + fp_err("identify_start error %d", r); + goto err; + } + + while (!idata->populated) { + r = fp_handle_events(); + if (r < 0) + goto err_stop; + } + + if (img) + *img = idata->img; + else + fp_img_free(idata->img); + + switch (idata->result) { + case FP_VERIFY_NO_MATCH: + fp_dbg("result: no match"); + break; + case FP_VERIFY_MATCH: + fp_dbg("result: match at offset %zd", idata->match_offset); + *match_offset = idata->match_offset; + break; + case FP_VERIFY_RETRY: + fp_dbg("verify should retry"); + break; + case FP_VERIFY_RETRY_TOO_SHORT: + fp_dbg("swipe was too short, verify should retry"); + break; + case FP_VERIFY_RETRY_CENTER_FINGER: + fp_dbg("finger was not centered, verify should retry"); + break; + case FP_VERIFY_RETRY_REMOVE_FINGER: + fp_dbg("scan failed, remove finger and retry"); + break; + default: + fp_err("unrecognised return code %d", r); + r = -EINVAL; + } + +err_stop: + if (fp_async_identify_stop(dev, identify_stop_cb, &stopped) == 0) + while (!stopped) + if (fp_handle_events() < 0) + break; + +err: + g_free(idata); + return r; +} + From 3ea28e334d2acfa0f988dbc155b4f9618a5b5fb2 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Tue, 26 Feb 2008 22:40:38 +0000 Subject: [PATCH 108/184] Provide access to fd set Includes notifications when the set changes. --- libfprint/core.c | 1 + libfprint/fp_internal.h | 1 + libfprint/fprint.h | 12 +++++++ libfprint/poll.c | 78 +++++++++++++++++++++++++++++++++++++---- 4 files changed, 86 insertions(+), 6 deletions(-) diff --git a/libfprint/core.c b/libfprint/core.c index e1382fa0..f16c6ca3 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -776,6 +776,7 @@ API_EXPORTED int fp_init(void) return r; register_drivers(); + fpi_poll_init(); return 0; } diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 6a365c15..26f679f5 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -328,6 +328,7 @@ int fpi_img_compare_print_data_to_gallery(struct fp_print_data *print, /* polling and timeouts */ +void fpi_poll_init(void); void fpi_poll_exit(void); typedef void (*fpi_timeout_fn)(void *data); diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 4cebba33..8ad8b2b3 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -267,8 +267,20 @@ struct fp_minutia **fp_img_get_minutiae(struct fp_img *img, int *nr_minutiae); void fp_img_free(struct fp_img *img); /* Polling and timing */ + +struct fp_pollfd { + int fd; + short events; +}; + int fp_handle_events_timeout(struct timeval *timeout); int fp_handle_events(void); +size_t fp_get_pollfds(struct fp_pollfd **pollfds); + +typedef void (*fp_pollfd_added_cb)(int fd, short events); +typedef void (*fp_pollfd_removed_cb)(int fd); +void fp_set_pollfd_notifiers(fp_pollfd_added_cb added_cb, + fp_pollfd_removed_cb removed_cb); /* Library */ int fp_init(void); diff --git a/libfprint/poll.c b/libfprint/poll.c index 6355f5cf..5e371bfc 100644 --- a/libfprint/poll.c +++ b/libfprint/poll.c @@ -61,18 +61,16 @@ * is expiring soonest at the head. */ static GSList *active_timers = NULL; +/* notifiers for added or removed poll fds */ +static fp_pollfd_added_cb fd_added_cb = NULL; +static fp_pollfd_removed_cb fd_removed_cb = NULL; + struct fpi_timeout { struct timeval expiry; fpi_timeout_fn callback; void *data; }; -void fpi_poll_exit(void) -{ - g_slist_free(active_timers); - active_timers = NULL; -} - static int timeout_sort_fn(gconstpointer _a, gconstpointer _b) { struct fpi_timeout *a = (struct fpi_timeout *) _a; @@ -245,3 +243,71 @@ API_EXPORTED int fp_handle_events(void) return fp_handle_events_timeout(&tv); } +/** \ingroup poll + * Retrieve a list of file descriptors that should be polled for events + * interesting to libfprint. This function is only for users who wish to + * combine libfprint's file descriptor set with other event sources - more + * simplistic users will be able to call fp_handle_events() or a variant + * directly. + * + * \param pollfds output location for a list of pollfds. If non-NULL, must be + * released with free() when done. + * \returns the number of pollfds in the resultant list, or negative on error. + */ +API_EXPORTED size_t fp_get_pollfds(struct fp_pollfd **pollfds) +{ + struct libusb_pollfd *usbfds; + struct fp_pollfd *ret; + size_t cnt; + size_t i; + + cnt = libusb_get_pollfds(&usbfds); + if (cnt <= 0) { + *pollfds = NULL; + return cnt; + } + + ret = g_malloc(sizeof(struct libusb_pollfd) * cnt); + for (i = 0; i < cnt; i++) { + ret[i].fd = usbfds[i].fd; + ret[i].events = usbfds[i].events; + } + + *pollfds = ret; + return cnt; +} + +/* FIXME: docs */ +API_EXPORTED void fp_set_pollfd_notifiers(fp_pollfd_added_cb added_cb, + fp_pollfd_removed_cb removed_cb) +{ + fd_added_cb = added_cb; + fd_removed_cb = removed_cb; +} + +static void add_pollfd(int fd, short events) +{ + if (fd_added_cb) + fd_added_cb(fd, events); +} + +static void remove_pollfd(int fd) +{ + if (fd_removed_cb) + fd_removed_cb(fd); +} + +void fpi_poll_init(void) +{ + libusb_set_pollfd_notifiers(add_pollfd, remove_pollfd); +} + +void fpi_poll_exit(void) +{ + g_slist_free(active_timers); + active_timers = NULL; + fd_added_cb = NULL; + fd_removed_cb = NULL; + libusb_set_pollfd_notifiers(NULL, NULL); +} + From b167dd02fc691a9760e80a5848762fd47f060843 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 1 Mar 2008 12:16:31 +0000 Subject: [PATCH 109/184] Add API to determine next timeout --- libfprint/fprint.h | 1 + libfprint/poll.c | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 8ad8b2b3..96450044 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -276,6 +276,7 @@ struct fp_pollfd { int fp_handle_events_timeout(struct timeval *timeout); int fp_handle_events(void); size_t fp_get_pollfds(struct fp_pollfd **pollfds); +int fp_get_next_timeout(struct timeval *tv); typedef void (*fp_pollfd_added_cb)(int fd, short events); typedef void (*fp_pollfd_removed_cb)(int fd); diff --git a/libfprint/poll.c b/libfprint/poll.c index 5e371bfc..9bd226d8 100644 --- a/libfprint/poll.c +++ b/libfprint/poll.c @@ -243,6 +243,33 @@ API_EXPORTED int fp_handle_events(void) return fp_handle_events_timeout(&tv); } +/* FIXME: docs + * returns 0 if no timeouts active + * returns 1 if timeout returned + * zero timeout means events are to be handled immediately */ +API_EXPORTED int fp_get_next_timeout(struct timeval *tv) +{ + struct timeval fprint_timeout; + struct timeval libusb_timeout; + int r_fprint; + int r_libusb; + + r_fprint = get_next_timeout_expiry(&fprint_timeout, NULL); + r_libusb = libusb_get_next_timeout(&libusb_timeout); + + /* if we have no pending timeouts and the same is true for libusb, + * indicate that we have no pending timouts */ + if (r_fprint == 0 && r_libusb == 0) + return 0; + + /* otherwise return the smaller of the 2 timeouts */ + else if (timercmp(&fprint_timeout, &libusb_timeout, <)) + *tv = fprint_timeout; + else + *tv = libusb_timeout; + return 1; +} + /** \ingroup poll * Retrieve a list of file descriptors that should be polled for events * interesting to libfprint. This function is only for users who wish to From c29c3fa01493bd03e218cf846adb90932f4c3c04 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 3 Mar 2008 13:47:59 +0000 Subject: [PATCH 110/184] Fix low minutiae handling Fixes a crash and adds in a missing break statement --- libfprint/imgdev.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index 1fd8ee15..494d6e22 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -207,6 +207,7 @@ void fpi_imgdev_report_finger_status(struct fp_img_dev *imgdev, fpi_drvcb_report_identify_result(imgdev->dev, r, imgdev->identify_match_offset, img); fp_print_data_free(data); + break; default: fp_err("unhandled action %d", imgdev->action); break; @@ -281,7 +282,7 @@ void fpi_imgdev_image_captured(struct fp_img_dev *imgdev, struct fp_img *img) MIN_ACCEPTABLE_MINUTIAE); fp_print_data_free(print); /* depends on FP_ENROLL_RETRY == FP_VERIFY_RETRY */ - imgdev->action = FP_ENROLL_RETRY; + imgdev->action_result = FP_ENROLL_RETRY; goto next_state; } From 2d27df0268002eb55d41fbf384d200e7b0418ad2 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 3 Mar 2008 23:23:50 +0000 Subject: [PATCH 111/184] Allow timeouts to be cancelled --- libfprint/drivers/uru4000.c | 11 ++++------- libfprint/fp_internal.h | 5 ++++- libfprint/poll.c | 14 +++++++++++--- 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index 93b79b08..ad64992a 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -717,7 +717,6 @@ static void rebootpwr_run_state(struct fpi_ssm *ssm) { struct fp_img_dev *dev = ssm->priv; struct uru4k_dev *urudev = dev->priv; - int r; switch (ssm->cur_state) { case REBOOTPWR_SET_HWSTAT: @@ -734,9 +733,8 @@ static void rebootpwr_run_state(struct fpi_ssm *ssm) fpi_ssm_next_state(ssm); break; case REBOOTPWR_PAUSE: - r = fpi_timeout_add(10, rebootpwr_pause_cb, ssm); - if (r < 0) - fpi_ssm_mark_aborted(ssm, r); + if (fpi_timeout_add(10, rebootpwr_pause_cb, ssm) == NULL) + fpi_ssm_mark_aborted(ssm, -ETIME); break; } } @@ -827,9 +825,8 @@ static void powerup_run_state(struct fpi_ssm *ssm) fpi_ssm_next_state(ssm); break; case POWERUP_PAUSE: - r = fpi_timeout_add(10, powerup_pause_cb, ssm); - if (r < 0) - fpi_ssm_mark_aborted(ssm, r); + if (fpi_timeout_add(10, powerup_pause_cb, ssm) == NULL) + fpi_ssm_mark_aborted(ssm, -ETIME); break; case POWERUP_CHALLENGE_RESPONSE: r = do_challenge_response(dev, powerup_challenge_response_cb, ssm); diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 26f679f5..c391e376 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -333,7 +333,10 @@ void fpi_poll_exit(void); typedef void (*fpi_timeout_fn)(void *data); -int fpi_timeout_add(unsigned int msec, fpi_timeout_fn callback, void *data); +struct fpi_timeout; +struct fpi_timeout *fpi_timeout_add(unsigned int msec, fpi_timeout_fn callback, + void *data); +void fpi_timeout_cancel(struct fpi_timeout *timeout); /* async drv <--> lib comms */ diff --git a/libfprint/poll.c b/libfprint/poll.c index 9bd226d8..df76233d 100644 --- a/libfprint/poll.c +++ b/libfprint/poll.c @@ -89,7 +89,8 @@ static int timeout_sort_fn(gconstpointer _a, gconstpointer _b) /* A timeout is the asynchronous equivalent of sleeping. You create a timeout * saying that you'd like to have a function invoked at a certain time in * the future. */ -int fpi_timeout_add(unsigned int msec, fpi_timeout_fn callback, void *data) +struct fpi_timeout *fpi_timeout_add(unsigned int msec, fpi_timeout_fn callback, + void *data) { struct timespec ts; struct timeval add_msec; @@ -101,7 +102,7 @@ int fpi_timeout_add(unsigned int msec, fpi_timeout_fn callback, void *data) r = clock_gettime(CLOCK_MONOTONIC, &ts); if (r < 0) { fp_err("failed to read monotonic clock, errno=%d", errno); - return r; + return NULL; } timeout = g_malloc(sizeof(*timeout)); @@ -118,7 +119,14 @@ int fpi_timeout_add(unsigned int msec, fpi_timeout_fn callback, void *data) active_timers = g_slist_insert_sorted(active_timers, timeout, timeout_sort_fn); - return 0; + return timeout; +} + +void fpi_timeout_cancel(struct fpi_timeout *timeout) +{ + fp_dbg(""); + active_timers = g_slist_remove(active_timers, timeout); + g_free(timeout); } /* get the expiry time and optionally the timeout structure for the next From 07a42d5f91c072bcb4639744c1e79d03cfd9f9dc Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 3 Mar 2008 23:24:00 +0000 Subject: [PATCH 112/184] uru4000: Retry initialization 3 times Sometimes we don't get the powerup interrupt, so retry the whole process up to 3 times if we time out waiting for the interrupt. --- libfprint/drivers/uru4000.c | 42 +++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index ad64992a..c2e5761e 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -133,6 +133,9 @@ struct uru4k_dev { int powerup_ctr; unsigned char powerup_hwstat; + int scanpwr_irq_timeouts; + struct fpi_timeout *scanpwr_irq_timeout; + AES_KEY aeskey; }; @@ -888,6 +891,24 @@ static void init_scanpwr_irq_cb(struct fp_img_dev *dev, int status, fpi_ssm_next_state(ssm); } +static void init_scanpwr_timeout(void *user_data) +{ + struct fpi_ssm *ssm = user_data; + struct fp_img_dev *dev = ssm->priv; + struct uru4k_dev *urudev = dev->priv; + + fp_warn("powerup timed out"); + urudev->irq_cb = NULL; + urudev->scanpwr_irq_timeout = NULL; + + if (++urudev->scanpwr_irq_timeouts >= 3) { + fp_err("powerup timed out 3 times, giving up"); + fpi_ssm_mark_aborted(ssm, -ETIMEDOUT); + } else { + fpi_ssm_jump_to_state(ssm, INIT_GET_HWSTAT); + } +} + static void init_run_state(struct fpi_ssm *ssm) { struct fp_img_dev *dev = ssm->priv; @@ -925,15 +946,27 @@ static void init_run_state(struct fpi_ssm *ssm) fpi_ssm_start_subsm(ssm, powerupsm); break; case INIT_AWAIT_SCAN_POWER: - /* FIXME: should timeout and maybe retry entire sm? */ if (!IRQ_HANDLER_IS_RUNNING(urudev)) { fpi_ssm_mark_aborted(ssm, -EIO); - } else { - urudev->irq_cb_data = ssm; - urudev->irq_cb = init_scanpwr_irq_cb; + break; } + + /* sometimes the 56aa interrupt that we are waiting for never arrives, + * so we include this timeout loop to retry the whole process 3 times + * if we don't get an irq any time soon. */ + urudev->scanpwr_irq_timeout = fpi_timeout_add(300, + init_scanpwr_timeout, ssm); + if (!urudev->scanpwr_irq_timeout) { + fpi_ssm_mark_aborted(ssm, -ETIME); + break; + } + + urudev->irq_cb_data = ssm; + urudev->irq_cb = init_scanpwr_irq_cb; break; case INIT_DONE: + fpi_timeout_cancel(urudev->scanpwr_irq_timeout); + urudev->scanpwr_irq_timeout = NULL; urudev->irq_cb_data = NULL; urudev->irq_cb = NULL; fpi_ssm_mark_completed(ssm); @@ -971,6 +1004,7 @@ static int dev_activate(struct fp_img_dev *dev, enum fp_imgdev_state state) if (r < 0) return r; + urudev->scanpwr_irq_timeouts = 0; urudev->activate_state = state; ssm = fpi_ssm_new(dev->dev, init_run_state, INIT_NUM_STATES); ssm->priv = dev; From 647d1408343b5a14ee70984865535aa5d02019a4 Mon Sep 17 00:00:00 2001 From: Vasily Khoruzhick Date: Wed, 5 Mar 2008 22:15:32 +0200 Subject: [PATCH 113/184] Fixed fp_identify_finger_img didn't return result of operation Signed-off-by: Vasily Khoruzhick --- libfprint/sync.c | 1 + 1 file changed, 1 insertion(+) diff --git a/libfprint/sync.c b/libfprint/sync.c index 87c033ad..61557eb8 100644 --- a/libfprint/sync.c +++ b/libfprint/sync.c @@ -474,6 +474,7 @@ API_EXPORTED int fp_identify_finger_img(struct fp_dev *dev, else fp_img_free(idata->img); + r = idata->result; switch (idata->result) { case FP_VERIFY_NO_MATCH: fp_dbg("result: no match"); From 81a5d6d9664ef9084213cb536218b31ab46d5cd9 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Fri, 7 Mar 2008 00:11:56 +0000 Subject: [PATCH 114/184] Only use -fgnu89-inline when supported This only works for GCC 4.3 and newer. GCC 4.2 and older already have the semantics introduced by using this argument. --- configure.ac | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/configure.ac b/configure.ac index 44dc151d..67322e07 100644 --- a/configure.ac +++ b/configure.ac @@ -90,9 +90,14 @@ if test "x$debug_log_enabled" != "xno"; then AC_DEFINE([ENABLE_DEBUG_LOGGING], 1, [Debug message logging]) fi +# Restore gnu89 inline semantics on gcc 4.3 and newer +saved_cflags="$CFLAGS" +CFLAGS="$CFLAGS -fgnu89-inline" +AC_COMPILE_IFELSE(AC_LANG_PROGRAM([]), inline_cflags="-fgnu89-inline", inline_cflags="") +CFLAGS="$saved_cflags" AC_DEFINE([API_EXPORTED], [__attribute__((visibility("default")))], [Default visibility]) -AM_CFLAGS="-std=gnu99 -fgnu89-inline -Wall -Wundef -Wunused -Wstrict-prototypes -Werror-implicit-function-declaration -Wno-pointer-sign -Wshadow" +AM_CFLAGS="-std=gnu99 $inline_cflags -Wall -Wundef -Wunused -Wstrict-prototypes -Werror-implicit-function-declaration -Wno-pointer-sign -Wshadow" AC_SUBST(AM_CFLAGS) AC_CONFIG_FILES([libfprint.pc] [Makefile] [libfprint/Makefile] [examples/Makefile] [doc/Makefile]) From 4e884807a793091e3410ea0ba10e3e314e21818f Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 10 Mar 2008 11:35:58 +0000 Subject: [PATCH 115/184] Update for libusb API rework --- libfprint/aeslib.c | 41 ++-- libfprint/async.c | 2 +- libfprint/core.c | 33 +-- libfprint/drivers/aes2501.c | 171 ++++++++------- libfprint/drivers/aes4000.c | 46 ++-- libfprint/drivers/upekts.c | 426 ++++++++++++++++++++---------------- libfprint/drivers/uru4000.c | 363 ++++++++++++++++-------------- libfprint/fp_internal.h | 6 +- libfprint/sync.c | 2 +- 9 files changed, 601 insertions(+), 489 deletions(-) diff --git a/libfprint/aeslib.c b/libfprint/aeslib.c index 4c797c3c..579cd127 100644 --- a/libfprint/aeslib.c +++ b/libfprint/aeslib.c @@ -46,22 +46,19 @@ static void continue_write_regv(struct write_regv_data *wdata); /* libusb bulk callback for regv write completion transfer. continues the * transaction */ -static void write_regv_trf_complete(libusb_dev_handle *devh, - libusb_urb_handle *urbh, enum libusb_urb_cb_status status, - unsigned char endpoint, int rqlength, unsigned char *data, - int actual_length, void *user_data) +static void write_regv_trf_complete(struct libusb_transfer *transfer) { - struct write_regv_data *wdata = user_data; + struct write_regv_data *wdata = transfer->user_data; - g_free(data); - libusb_urb_handle_free(urbh); - - if (status != FP_URB_COMPLETED) + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) wdata->callback(wdata->imgdev, -EIO, wdata->user_data); - else if (rqlength != actual_length) + else if (transfer->length != transfer->actual_length) wdata->callback(wdata->imgdev, -EPROTO, wdata->user_data); else continue_write_regv(wdata); + + g_free(transfer->buffer); + libusb_free_transfer(transfer); } /* write from wdata->offset to upper_bound (inclusive) of wdata->regs */ @@ -73,12 +70,13 @@ static int do_write_regv(struct write_regv_data *wdata, int upper_bound) unsigned char *data = g_malloc(alloc_size); unsigned int i; size_t data_offset = 0; - struct libusb_urb_handle *urbh; - struct libusb_bulk_transfer msg = { - .endpoint = EP_OUT, - .data = data, - .length = alloc_size, - }; + struct libusb_transfer *transfer = libusb_alloc_transfer(); + int r; + + if (!transfer) { + g_free(data); + return -ENOMEM; + } for (i = offset; i < offset + num; i++) { const struct aes_regwrite *regwrite = &wdata->regs[i]; @@ -86,14 +84,15 @@ static int do_write_regv(struct write_regv_data *wdata, int upper_bound) data[data_offset++] = regwrite->value; } - urbh = libusb_async_bulk_transfer(wdata->imgdev->udev, &msg, - write_regv_trf_complete, wdata, BULK_TIMEOUT); - if (!urbh) { + libusb_fill_bulk_transfer(transfer, wdata->imgdev->udev, EP_OUT, data, + alloc_size, write_regv_trf_complete, wdata, BULK_TIMEOUT); + r = libusb_submit_transfer(transfer); + if (r < 0) { g_free(data); - return -EIO; + libusb_free_transfer(transfer); } - return 0; + return r; } /* write the next batch of registers to be written, or if there are no more, diff --git a/libfprint/async.c b/libfprint/async.c index 00d97272..5d0bd102 100644 --- a/libfprint/async.c +++ b/libfprint/async.c @@ -41,7 +41,7 @@ API_EXPORTED int fp_async_dev_open(struct fp_dscv_dev *ddev, fp_dev_open_cb cb, { struct fp_driver *drv = ddev->drv; struct fp_dev *dev; - libusb_dev_handle *udevh; + libusb_device_handle *udevh; int r; fp_dbg(""); diff --git a/libfprint/core.c b/libfprint/core.c index f16c6ca3..0be45698 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -352,11 +352,11 @@ static void register_drivers(void) } } -static struct fp_driver *find_supporting_driver(libusb_dev *udev, +static struct fp_driver *find_supporting_driver(libusb_device *udev, const struct usb_id **usb_id) { GSList *elem = registered_drivers; - struct libusb_dev_descriptor *dsc = libusb_dev_get_descriptor(udev); + struct libusb_device_descriptor *dsc = libusb_get_device_descriptor(udev); do { struct fp_driver *drv = elem->data; @@ -373,7 +373,7 @@ static struct fp_driver *find_supporting_driver(libusb_dev *udev, return NULL; } -static struct fp_dscv_dev *discover_dev(libusb_dev *udev) +static struct fp_dscv_dev *discover_dev(libusb_device *udev) { const struct usb_id *usb_id; struct fp_driver *drv = find_supporting_driver(udev, &usb_id); @@ -409,33 +409,40 @@ API_EXPORTED struct fp_dscv_dev **fp_discover_devs(void) { GSList *tmplist = NULL; struct fp_dscv_dev **list; - struct libusb_dev *udev; + libusb_device *udev; + libusb_device **devs; int dscv_count = 0; + int r; + int i = 0; if (registered_drivers == NULL) return NULL; - libusb_find_devices(); + r = libusb_get_device_list(&devs); + if (r < 0) { + fp_err("couldn't enumerate USB devices, error %d", r); + return NULL; + } /* Check each device against each driver, temporarily storing successfully * discovered devices in a GSList. * * Quite inefficient but excusable as we'll only be dealing with small * sets of drivers against small sets of USB devices */ - for (udev = libusb_get_devices(); udev; udev = libusb_dev_next(udev)) { - struct fp_dscv_dev *ddev = discover_dev(udev); - if (!ddev) - continue; - tmplist = g_slist_prepend(tmplist, (gpointer) ddev); - dscv_count++; - } + while ((udev = devs[i++]) != NULL) { + struct fp_dscv_dev *ddev = discover_dev(udev); + if (!ddev) + continue; + tmplist = g_slist_prepend(tmplist, (gpointer) ddev); + dscv_count++; + } /* Convert our temporary GSList into a standard NULL-terminated pointer * array. */ list = g_malloc(sizeof(*list) * (dscv_count + 1)); if (dscv_count > 0) { GSList *elem = tmplist; - int i = 0; + i = 0; do { list[i++] = elem->data; } while ((elem = g_slist_next(elem))); diff --git a/libfprint/drivers/aes2501.c b/libfprint/drivers/aes2501.c index f0ea95d2..3e3bae60 100644 --- a/libfprint/drivers/aes2501.c +++ b/libfprint/drivers/aes2501.c @@ -79,48 +79,53 @@ struct aes2501_read_regs { void *user_data; }; -static void read_regs_data_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, - enum libusb_urb_cb_status status, unsigned char endpoint, int rqlength, - unsigned char *data, int actual_length, void *user_data) +static void read_regs_data_cb(struct libusb_transfer *transfer) { - struct aes2501_read_regs *rdata = user_data; + struct aes2501_read_regs *rdata = transfer->user_data; unsigned char *retdata = NULL; int r; - if (status != FP_URB_COMPLETED) { + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { r = -EIO; - } else if (rqlength != actual_length) { + } else if (transfer->length != transfer->actual_length) { r = -EPROTO; } else { r = 0; - retdata = data; + retdata = transfer->buffer; } rdata->callback(rdata->dev, r, retdata, rdata->user_data); - libusb_urb_handle_free(urbh); - g_free(data); g_free(rdata); + g_free(transfer->buffer); + libusb_free_transfer(transfer); } static void read_regs_rq_cb(struct fp_img_dev *dev, int result, void *user_data) { struct aes2501_read_regs *rdata = user_data; - struct libusb_urb_handle *urbh; - struct libusb_bulk_transfer trf = { - .endpoint = EP_IN, - .length = 126, - }; + struct libusb_transfer *transfer; + unsigned char *data; + int r; g_free(rdata->regwrite); if (result != 0) goto err; - trf.data = g_malloc(trf.length); - urbh = libusb_async_bulk_transfer(dev->udev, &trf, read_regs_data_cb, - rdata, BULK_TIMEOUT); - if (!urbh) { - g_free(trf.data); - result = EIO; + transfer = libusb_alloc_transfer(); + if (!transfer) { + result = -ENOMEM; + goto err; + } + + data = g_malloc(126); + libusb_fill_bulk_transfer(transfer, dev->udev, EP_IN, data, 126, + read_regs_data_cb, rdata, BULK_TIMEOUT); + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(data); + libusb_free_transfer(transfer); + result = -EIO; goto err; } @@ -179,40 +184,43 @@ static void generic_write_regv_cb(struct fp_img_dev *dev, int result, } /* check that read succeeded but ignore all data */ -static void generic_ignore_data_cb(libusb_dev_handle *devh, - libusb_urb_handle *urbh, enum libusb_urb_cb_status status, - unsigned char endpoint, int rqlength, unsigned char *data, - int actual_length, void *user_data) +static void generic_ignore_data_cb(struct libusb_transfer *transfer) { - struct fpi_ssm *ssm = user_data; + struct fpi_ssm *ssm = transfer->user_data; - libusb_urb_handle_free(urbh); - g_free(data); - - if (status != FP_URB_COMPLETED) + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) fpi_ssm_mark_aborted(ssm, -EIO); - else if (rqlength != actual_length) + else if (transfer->length != transfer->actual_length) fpi_ssm_mark_aborted(ssm, -EPROTO); else fpi_ssm_next_state(ssm); + + g_free(transfer->buffer); + libusb_free_transfer(transfer); } /* read the specified number of bytes from the IN endpoint but throw them * away, then increment the SSM */ static void generic_read_ignore_data(struct fpi_ssm *ssm, size_t bytes) { - struct libusb_urb_handle *urbh; - struct libusb_bulk_transfer trf = { - .endpoint = EP_IN, - .data = g_malloc(bytes), - .length = bytes, - }; + struct libusb_transfer *transfer = libusb_alloc_transfer(); + unsigned char *data; + int r; - urbh = libusb_async_bulk_transfer(ssm->dev->udev, &trf, + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + return; + } + + data = g_malloc(bytes); + libusb_fill_bulk_transfer(transfer, ssm->dev->udev, EP_IN, data, bytes, generic_ignore_data_cb, ssm, BULK_TIMEOUT); - if (!urbh) { - g_free(trf.data); - fpi_ssm_mark_aborted(ssm, -EIO); + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(data); + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, r); } } @@ -382,19 +390,17 @@ static const struct aes_regwrite finger_det_reqs[] = { static void start_finger_detection(struct fp_img_dev *dev); -static void finger_det_data_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, - enum libusb_urb_cb_status status, unsigned char endpoint, - int rqlength, unsigned char *data, int actual_length, void *user_data) +static void finger_det_data_cb(struct libusb_transfer *transfer) { - struct fp_img_dev *dev = user_data; + struct fp_img_dev *dev = transfer->user_data; + unsigned char *data = transfer->buffer; int i; int sum = 0; - libusb_urb_handle_free(urbh); - if (status != FP_URB_COMPLETED) { + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { fpi_imgdev_session_error(dev, -EIO); goto out; - } else if (rqlength != actual_length) { + } else if (transfer->length != transfer->actual_length) { fpi_imgdev_session_error(dev, -EPROTO); goto out; } @@ -413,28 +419,36 @@ static void finger_det_data_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, out: g_free(data); + libusb_free_transfer(transfer); } static void finger_det_reqs_cb(struct fp_img_dev *dev, int result, void *user_data) { - struct libusb_urb_handle *urbh; - struct libusb_bulk_transfer trf = { - .endpoint = EP_IN, - .length = 20, - }; + struct libusb_transfer *transfer; + unsigned char *data; + int r; if (result) { fpi_imgdev_session_error(dev, result); return; } - trf.data = g_malloc(trf.length); - urbh = libusb_async_bulk_transfer(dev->udev, &trf, finger_det_data_cb, - dev, BULK_TIMEOUT); - if (!urbh) { - g_free(trf.data); - fpi_imgdev_session_error(dev, -EIO); + transfer = libusb_alloc_transfer(); + if (!transfer) { + fpi_imgdev_session_error(dev, -ENOMEM); + return; + } + + data = g_malloc(20); + libusb_fill_bulk_transfer(transfer, dev->udev, EP_IN, data, 20, + finger_det_data_cb, dev, BULK_TIMEOUT); + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(data); + libusb_free_transfer(transfer); + fpi_imgdev_session_error(dev, r); } } @@ -527,23 +541,20 @@ enum capture_states { CAPTURE_NUM_STATES, }; -static void capture_read_strip_cb(libusb_dev_handle *devh, - libusb_urb_handle *urbh, enum libusb_urb_cb_status status, - unsigned char endpoint, int rqlength, unsigned char *data, - int actual_length, void *user_data) +static void capture_read_strip_cb(struct libusb_transfer *transfer) { unsigned char *stripdata; - struct fpi_ssm *ssm = user_data; + struct fpi_ssm *ssm = transfer->user_data; struct fp_img_dev *dev = ssm->priv; struct aes2501_dev *aesdev = dev->priv; + unsigned char *data = transfer->buffer; int sum; int threshold; - libusb_urb_handle_free(urbh); - if (status != FP_URB_COMPLETED) { + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { fpi_ssm_mark_aborted(ssm, -EIO); goto out; - } else if (rqlength != actual_length) { + } else if (transfer->length != transfer->actual_length) { fpi_ssm_mark_aborted(ssm, -EPROTO); goto out; } @@ -587,12 +598,14 @@ static void capture_read_strip_cb(libusb_dev_handle *devh, out: g_free(data); + libusb_free_transfer(transfer); } static void capture_run_state(struct fpi_ssm *ssm) { struct fp_img_dev *dev = ssm->priv; struct aes2501_dev *aesdev = dev->priv; + int r; switch (ssm->cur_state) { case CAPTURE_WRITE_REQS_1: @@ -617,17 +630,23 @@ static void capture_run_state(struct fpi_ssm *ssm) generic_write_regv_cb, ssm); break; case CAPTURE_READ_STRIP: ; - struct libusb_urb_handle *urbh; - struct libusb_bulk_transfer trf = { - .endpoint = EP_IN, - .data = g_malloc(1705), - .length = 1705, - }; - urbh = libusb_async_bulk_transfer(dev->udev, &trf, + struct libusb_transfer *transfer = libusb_alloc_transfer(); + unsigned char *data; + + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + break; + } + + data = g_malloc(1705); + libusb_fill_bulk_transfer(transfer, dev->udev, EP_IN, data, 1705, capture_read_strip_cb, ssm, BULK_TIMEOUT); - if (!urbh) { - g_free(trf.data); - fpi_ssm_mark_aborted(ssm, -EIO); + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(data); + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, r); } break; }; diff --git a/libfprint/drivers/aes4000.c b/libfprint/drivers/aes4000.c index ff3b3c25..8c2ec0ea 100644 --- a/libfprint/drivers/aes4000.c +++ b/libfprint/drivers/aes4000.c @@ -35,7 +35,7 @@ #define SUBARRAY_LEN 768 struct aes4k_dev { - libusb_urb_handle *img_trf; + struct libusb_transfer *img_trf; }; static const struct aes_regwrite init_reqs[] = { @@ -115,22 +115,20 @@ static const struct aes_regwrite init_reqs[] = { static void do_capture(struct fp_img_dev *dev); -static void img_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, - enum libusb_urb_cb_status status, unsigned char endpoint, - int rqlength, unsigned char *data, int actual_length, void *user_data) +static void img_cb(struct libusb_transfer *transfer) { - struct fp_img_dev *dev = user_data; + struct fp_img_dev *dev = transfer->user_data; struct aes4k_dev *aesdev = dev->priv; - unsigned char *ptr = data; + unsigned char *ptr = transfer->buffer; struct fp_img *img; int i; - if (status == FP_URB_CANCELLED) { + if (transfer->status == LIBUSB_TRANSFER_CANCELLED) { goto err; - } else if (status != FP_URB_COMPLETED) { + } else if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { fpi_imgdev_session_error(dev, -EIO); goto err; - } else if (rqlength != actual_length) { + } else if (transfer->length != transfer->actual_length) { fpi_imgdev_session_error(dev, -EPROTO); goto err; } @@ -155,25 +153,33 @@ static void img_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, do_capture(dev); err: - g_free(data); + g_free(transfer->buffer); aesdev->img_trf = NULL; - libusb_urb_handle_free(urbh); + libusb_free_transfer(transfer); } static void do_capture(struct fp_img_dev *dev) { struct aes4k_dev *aesdev = dev->priv; - struct libusb_bulk_transfer trf = { - .endpoint = EP_IN, - .length = DATA_BUFLEN, - .data = g_malloc(DATA_BUFLEN), - }; + unsigned char *data; + int r; - aesdev->img_trf = libusb_async_bulk_transfer(dev->udev, &trf, img_cb, dev, - 0); + aesdev->img_trf = libusb_alloc_transfer(); if (!aesdev->img_trf) { - g_free(trf.data); fpi_imgdev_session_error(dev, -EIO); + return; + } + + data = g_malloc(DATA_BUFLEN); + libusb_fill_bulk_transfer(aesdev->img_trf, dev->udev, EP_IN, data, + DATA_BUFLEN, img_cb, dev, 0); + + r = libusb_submit_transfer(aesdev->img_trf); + if (r < 0) { + g_free(data); + libusb_free_transfer(aesdev->img_trf); + aesdev->img_trf = NULL; + fpi_imgdev_session_error(dev, r); } } @@ -198,7 +204,7 @@ static void dev_deactivate(struct fp_img_dev *dev) * from deactivation, otherwise app may legally exit before we've * cleaned up */ if (aesdev->img_trf) - libusb_urb_handle_cancel(dev->udev, aesdev->img_trf); + libusb_cancel_transfer(aesdev->img_trf); fpi_imgdev_deactivate_complete(dev); } diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index 214d4fd7..e0e7d1a2 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -133,10 +133,11 @@ static uint16_t udf_crc(unsigned char *buffer, size_t size) #define CMD_SEQ_INCREMENT 0x10 -static void fill_send_cmd_urb(struct libusb_bulk_transfer *msg, +static struct libusb_transfer *alloc_send_cmd_transfer(struct fp_dev *dev, unsigned char seq_a, unsigned char seq_b, const unsigned char *data, - uint16_t len) + uint16_t len, libusb_transfer_cb_fn callback, void *user_data) { + struct libusb_transfer *transfer = libusb_alloc_transfer(); uint16_t crc; /* 9 bytes extra for: 4 byte 'Ciao', 1 byte A, 1 byte B | lenHI, @@ -144,15 +145,15 @@ static void fill_send_cmd_urb(struct libusb_bulk_transfer *msg, size_t urblen = len + 9; unsigned char *buf; + if (!transfer) + return NULL; + if (!data && len > 0) { fp_err("len>0 but no data?"); - return; + return NULL; } - - msg->endpoint = EP_OUT; - msg->length = urblen; + buf = g_malloc(urblen); - msg->data = buf; /* Write header */ strncpy(buf, "Ciao", 4); @@ -169,17 +170,22 @@ static void fill_send_cmd_urb(struct libusb_bulk_transfer *msg, crc = GUINT16_TO_BE(udf_crc(buf + 4, urblen - 6)); buf[urblen - 2] = crc >> 8; buf[urblen - 1] = crc & 0xff; + + libusb_fill_bulk_transfer(transfer, dev->udev, EP_OUT, buf, urblen, + callback, user_data, TIMEOUT); + return transfer; } -static void fill_send_cmd28_urb(struct fp_dev *dev, - struct libusb_bulk_transfer *msg, unsigned char subcmd, - const unsigned char *data, uint16_t innerlen) +static struct libusb_transfer *alloc_send_cmd28_transfer(struct fp_dev *dev, + unsigned char subcmd, const unsigned char *data, uint16_t innerlen, + libusb_transfer_cb_fn callback, void *user_data) { uint16_t _innerlen = innerlen; size_t len = innerlen + 6; unsigned char *buf = g_malloc0(len); struct upekts_dev *upekdev = dev->priv; uint8_t seq = upekdev->seq + CMD_SEQ_INCREMENT; + struct libusb_transfer *ret; fp_dbg("seq=%02x subcmd=%02x with %d bytes of data", seq, subcmd, innerlen); @@ -190,17 +196,19 @@ static void fill_send_cmd28_urb(struct fp_dev *dev, buf[5] = subcmd; memcpy(buf + 6, data, innerlen); - fill_send_cmd_urb(msg, 0, seq, buf, len); + ret = alloc_send_cmd_transfer(dev, 0, seq, buf, len, callback, user_data); upekdev->seq = seq; g_free(buf); + return ret; } -static void fill_send_cmdresponse_urb(struct libusb_bulk_transfer *msg, - unsigned char seq, const unsigned char *data, uint8_t len) +static struct libusb_transfer *alloc_send_cmdresponse_transfer( + struct fp_dev *dev, unsigned char seq, const unsigned char *data, + uint8_t len, libusb_transfer_cb_fn callback, void *user_data) { fp_dbg("seq=%02x len=%d", seq, len); - fill_send_cmd_urb(msg, seq, 0, data, len); + return alloc_send_cmd_transfer(dev, seq, 0, data, len, callback, user_data); } enum read_msg_status { @@ -224,12 +232,12 @@ static int __read_msg_async(struct read_msg_data *udata); #define READ_MSG_DATA_CB_ERR(udata) (udata)->callback((udata)->dev, \ READ_MSG_ERROR, 0, 0, NULL, 0, (udata)->user_data) -static void busy_ack_sent_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, - enum libusb_urb_cb_status status, unsigned char endpoint, int rqlength, - unsigned char *data, int actual_length, void *_data) +static void busy_ack_sent_cb(struct libusb_transfer *transfer) { - struct read_msg_data *udata = (struct read_msg_data *) _data; - if (status != FP_URB_COMPLETED || rqlength != actual_length) { + struct read_msg_data *udata = transfer->user_data; + + if (transfer->status != LIBUSB_TRANSFER_COMPLETED || + transfer->length != transfer->actual_length) { READ_MSG_DATA_CB_ERR(udata); g_free(udata); } else { @@ -239,22 +247,25 @@ static void busy_ack_sent_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, g_free(udata); } } - libusb_urb_handle_free(urbh); + libusb_free_transfer(transfer); } static int busy_ack_retry_read(struct read_msg_data *udata) { - struct libusb_bulk_transfer msg; - libusb_urb_handle *urbh; + struct libusb_transfer *transfer; + int r; - fill_send_cmdresponse_urb(&msg, 0x09, NULL, 0); - urbh = libusb_async_bulk_transfer(udata->dev->udev, &msg, busy_ack_sent_cb, - udata, TIMEOUT); - if (!urbh) { - g_free(msg.data); - return -EIO; + transfer = alloc_send_cmdresponse_transfer(udata->dev, 0x09, NULL, 0, + busy_ack_sent_cb, udata); + if (!transfer) + return -ENOMEM; + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(transfer->buffer); + libusb_free_transfer(transfer); } - return 0; + return r; } /* Returns 0 if message was handled, 1 if it was a device-busy message, and @@ -333,20 +344,19 @@ static int __handle_incoming_msg(struct read_msg_data *udata, return 0; } -static void read_msg_extend_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, - enum libusb_urb_cb_status status, unsigned char endpoint, int rqlength, - unsigned char *data, int actual_length, void *user_data) +static void read_msg_extend_cb(struct libusb_transfer *transfer) { - struct read_msg_data *udata = user_data; - unsigned char *buf = data - MSG_READ_BUF_SIZE; + struct read_msg_data *udata = transfer->user_data; + unsigned char *buf = transfer->buffer - MSG_READ_BUF_SIZE; int handle_result = 0; - if (status != FP_URB_COMPLETED) { - fp_err("extended msg read failed, code %d", status); + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { + fp_err("extended msg read failed, code %d", transfer->status); goto err; } - if (actual_length < rqlength) { - fp_err("extended msg short read (%d/%d)", actual_length, rqlength); + if (transfer->actual_length < transfer->length) { + fp_err("extended msg short read (%d/%d)", transfer->actual_length, + transfer->length); goto err; } @@ -361,23 +371,22 @@ out: if (handle_result != 1) g_free(udata); g_free(buf); - libusb_urb_handle_free(urbh); + libusb_free_transfer(transfer); } -static void read_msg_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, - enum libusb_urb_cb_status status, unsigned char endpoint, - int rqlength, unsigned char *data, int actual_length, void *user_data) +static void read_msg_cb(struct libusb_transfer *transfer) { - struct read_msg_data *udata = user_data; + struct read_msg_data *udata = transfer->user_data; + unsigned char *data = transfer->buffer; uint16_t len; int handle_result = 0; - if (status != FP_URB_COMPLETED) { - fp_err("async msg read failed, code %d", status); + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { + fp_err("async msg read failed, code %d", transfer->status); goto err; } - if (actual_length < 9) { - fp_err("async msg read too short (%d)", actual_length); + if (transfer->actual_length < 9) { + fp_err("async msg read too short (%d)", transfer->actual_length); goto err; } @@ -387,11 +396,12 @@ static void read_msg_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, } len = GUINT16_FROM_LE(((data[5] & 0xf) << 8) | data[6]); - if (actual_length != MSG_READ_BUF_SIZE && (len + 9) > actual_length) { + if (transfer->actual_length != MSG_READ_BUF_SIZE + && (len + 9) > transfer->actual_length) { /* Check that the length claimed inside the message is in line with * the amount of data that was transferred over USB. */ fp_err("msg didn't include enough data, expected=%d recv=%d", - len + 9, actual_length); + len + 9, transfer->actual_length); goto err; } @@ -400,22 +410,26 @@ static void read_msg_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, * to read the remainder. This is handled below. */ if (len > MAX_DATA_IN_READ_BUF) { int needed = len - MAX_DATA_IN_READ_BUF; - libusb_urb_handle *eurbh; - struct libusb_bulk_transfer extend_msg = { - .endpoint = EP_IN, - .length = needed, - }; + struct libusb_transfer *etransfer = libusb_alloc_transfer(); + int r; + + if (!transfer) + goto err; fp_dbg("didn't fit in buffer, need to extend by %d bytes", needed); data = g_realloc((gpointer) data, MSG_READ_BUF_SIZE + needed); - extend_msg.data = data + MSG_READ_BUF_SIZE; - eurbh = libusb_async_bulk_transfer(udata->dev->udev, &extend_msg, - read_msg_extend_cb, udata, TIMEOUT); - if (!eurbh) { + + libusb_fill_bulk_transfer(etransfer, udata->dev->udev, EP_IN, + data + MSG_READ_BUF_SIZE, needed, read_msg_extend_cb, udata, + TIMEOUT); + + r = libusb_submit_transfer(etransfer); + if (r < 0) { fp_err("extended read submission failed"); + /* FIXME memory leak here? */ goto err; } - libusb_urb_handle_free(urbh); + libusb_free_transfer(transfer); return; } @@ -427,7 +441,7 @@ static void read_msg_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, err: READ_MSG_DATA_CB_ERR(udata); out: - libusb_urb_handle_free(urbh); + libusb_free_transfer(transfer); if (handle_result != 1) g_free(udata); g_free(data); @@ -436,18 +450,23 @@ out: static int __read_msg_async(struct read_msg_data *udata) { unsigned char *buf = g_malloc(MSG_READ_BUF_SIZE); - struct libusb_bulk_transfer msg = { - .endpoint = EP_IN, - .data = buf, - .length = MSG_READ_BUF_SIZE, - }; - libusb_urb_handle *urbh = libusb_async_bulk_transfer(udata->dev->udev, &msg, - read_msg_cb, udata, TIMEOUT); - if (!urbh) { + struct libusb_transfer *transfer = libusb_alloc_transfer(); + int r; + + if (!transfer) { g_free(buf); - return -EIO; + return -ENOMEM; } - return 0; + + libusb_fill_bulk_transfer(transfer, udata->dev->udev, EP_IN, buf, + MSG_READ_BUF_SIZE, read_msg_cb, udata, TIMEOUT); + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(buf); + libusb_free_transfer(transfer); + } + + return r; } static int read_msg_async(struct fp_dev *dev, read_msg_cb_fn callback, @@ -613,16 +632,16 @@ static void read_msg03_cb(struct fp_dev *dev, enum read_msg_status status, initsm_read_msg_cmd_cb((struct fpi_ssm *) user_data, status, 3, seq); } -static void ctrl400_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, - enum libusb_urb_cb_status status, struct libusb_ctrl_setup *setup, - unsigned char *data, int actual_length, void *user_data) +static void ctrl400_cb(struct libusb_transfer *transfer) { - struct fpi_ssm *ssm = user_data; - if (status == FP_URB_COMPLETED) + struct fpi_ssm *ssm = transfer->user_data; + /* FIXME check length? */ + if (transfer->status == LIBUSB_TRANSFER_COMPLETED) fpi_ssm_next_state(ssm); else fpi_ssm_mark_aborted(ssm, -1); - libusb_urb_handle_free(urbh); + g_free(transfer->buffer); + libusb_free_transfer(transfer); } static void initsm_read_msg_handler(struct fpi_ssm *ssm, @@ -635,35 +654,40 @@ static void initsm_read_msg_handler(struct fpi_ssm *ssm, } } -static void initsm_send_msg_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, - enum libusb_urb_cb_status status, unsigned char endpoint, - int rqlength, unsigned char *data, int actual_length, void *user_data) +static void initsm_send_msg_cb(struct libusb_transfer *transfer) { - struct fpi_ssm *ssm = user_data; - if (status == FP_URB_COMPLETED && rqlength == actual_length) { + struct fpi_ssm *ssm = transfer->user_data; + if (transfer->status == LIBUSB_TRANSFER_COMPLETED + && transfer->length == transfer->actual_length) { fp_dbg("state %d completed", ssm->cur_state); fpi_ssm_next_state(ssm); } else { fp_err("failed, state=%d rqlength=%d actual_length=%d", ssm->cur_state, - rqlength, actual_length); + transfer->length, transfer->actual_length); fpi_ssm_mark_aborted(ssm, -1); } - libusb_urb_handle_free(urbh); + libusb_free_transfer(transfer); } static void initsm_send_msg28_handler(struct fpi_ssm *ssm, unsigned char subcmd, const unsigned char *data, uint16_t innerlen) { struct fp_dev *dev = ssm->dev; - struct libusb_urb_handle *urbh; - struct libusb_bulk_transfer trf; + struct libusb_transfer *transfer; + int r; - fill_send_cmd28_urb(dev, &trf, subcmd, data, innerlen); - urbh = libusb_async_bulk_transfer(dev->udev, &trf, initsm_send_msg_cb, - ssm, TIMEOUT); - if (!urbh) { - fp_err("urb submission failed in state %d", ssm->cur_state); - g_free(trf.data); + transfer = alloc_send_cmd28_transfer(dev, subcmd, data, innerlen, + initsm_send_msg_cb, ssm); + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + return; + } + + r = libusb_submit_transfer(transfer); + if (r < 0) { + fp_err("urb submission failed error %d in state %d", r, ssm->cur_state); + g_free(transfer->buffer); + libusb_free_transfer(transfer); fpi_ssm_mark_aborted(ssm, -EIO); } } @@ -672,38 +696,48 @@ static void initsm_run_state(struct fpi_ssm *ssm) { struct fp_dev *dev = ssm->dev; struct upekts_dev *upekdev = dev->priv; - struct libusb_urb_handle *urbh; + struct libusb_transfer *transfer; + int r; switch (ssm->cur_state) { case WRITE_CTRL400: ; - unsigned char dummy = 0x10; - struct libusb_control_transfer ctrl400_trf = { - .requesttype = LIBUSB_TYPE_VENDOR | LIBUSB_RECIP_DEVICE, - .request = 0x0c, - .value = 0x0100, - .index = 0x0400, - .length = sizeof(dummy), - .data = &dummy, - }; + unsigned char *data; - urbh = libusb_async_control_transfer(ssm->dev->udev, &ctrl400_trf, + transfer = libusb_alloc_transfer(); + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + break; + } + + data = g_malloc(LIBUSB_CONTROL_SETUP_SIZE + 1); + libusb_fill_control_setup(data, + LIBUSB_TYPE_VENDOR | LIBUSB_RECIP_DEVICE, 0x0c, 0x100, 0x0400, 1); + libusb_fill_control_transfer(transfer, ssm->dev->udev, data, ctrl400_cb, ssm, TIMEOUT); - if (!urbh) - fpi_ssm_mark_aborted(ssm, -1); + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(data); + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, r); + } break; case READ_MSG03: initsm_read_msg_handler(ssm, read_msg03_cb); break; case SEND_RESP03: ; - struct libusb_bulk_transfer resp03_trf; + transfer = alloc_send_cmdresponse_transfer(dev, ++upekdev->seq, + init_resp03, sizeof(init_resp03), initsm_send_msg_cb, ssm); + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + break; + } - fill_send_cmdresponse_urb(&resp03_trf, ++upekdev->seq, init_resp03, - sizeof(init_resp03)); - urbh = libusb_async_bulk_transfer(dev->udev, &resp03_trf, - initsm_send_msg_cb, ssm, TIMEOUT); - if (!urbh) { - g_free(resp03_trf.data); - fpi_ssm_mark_aborted(ssm, -EIO); + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(transfer->buffer); + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, r); } break; case READ_MSG05: @@ -756,18 +790,16 @@ enum deinitsm_states { DEINITSM_NUM_STATES, }; -static void send_resp07_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, - enum libusb_urb_cb_status status, unsigned char endpoint, - int rqlength, unsigned char *data, int actual_length, void *user_data) +static void send_resp07_cb(struct libusb_transfer *transfer) { - struct fpi_ssm *ssm = user_data; - if (status != FP_URB_COMPLETED) + struct fpi_ssm *ssm = transfer->user_data; + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) fpi_ssm_mark_aborted(ssm, -EIO); - else if (rqlength != actual_length) + else if (transfer->length != transfer->actual_length) fpi_ssm_mark_aborted(ssm, -EPROTO); else fpi_ssm_next_state(ssm); - libusb_urb_handle_free(urbh); + libusb_free_transfer(transfer); } static void read_msg01_cb(struct fp_dev *dev, enum read_msg_status status, @@ -798,23 +830,29 @@ static void read_msg01_cb(struct fp_dev *dev, enum read_msg_status status, static void deinitsm_state_handler(struct fpi_ssm *ssm) { struct fp_dev *dev = ssm->dev; + int r; switch (ssm->cur_state) { case SEND_RESP07: ; - struct libusb_bulk_transfer msg; - struct libusb_urb_handle *urbh; + struct libusb_transfer *transfer; unsigned char dummy = 0; - fill_send_cmdresponse_urb(&msg, 0x07, &dummy, 1); - urbh = libusb_async_bulk_transfer(dev->udev, &msg, send_resp07_cb, ssm, - TIMEOUT); - if (!urbh) { - g_free(msg.data); - fpi_ssm_mark_aborted(ssm, -EIO); + transfer = alloc_send_cmdresponse_transfer(dev, 0x07, &dummy, 1, + send_resp07_cb, ssm); + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + break; + } + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(transfer->buffer); + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, r); } break; case READ_MSG01: ; - int r = read_msg_async(dev, read_msg01_cb, ssm); + r = read_msg_async(dev, read_msg01_cb, ssm); if (r < 0) fpi_ssm_mark_aborted(ssm, r); break; @@ -882,19 +920,16 @@ static void enroll_start_sm_cb_initsm(struct fpi_ssm *initsm) } /* called when enroll init URB has completed */ -static void enroll_start_sm_cb_init(libusb_dev_handle *devh, - libusb_urb_handle *urbh, enum libusb_urb_cb_status status, - unsigned char endpoint, int rqlength, unsigned char *data, - int actual_length, void *user_data) +static void enroll_start_sm_cb_init(struct libusb_transfer *transfer) { - struct fpi_ssm *ssm = user_data; - if (status != FP_URB_COMPLETED) + struct fpi_ssm *ssm = transfer->user_data; + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) fpi_ssm_mark_aborted(ssm, -EIO); - else if (rqlength != actual_length) + else if (transfer->length != transfer->actual_length) fpi_ssm_mark_aborted(ssm, -EPROTO); else fpi_ssm_next_state(ssm); - libusb_urb_handle_free(urbh); + libusb_free_transfer(transfer); } static void enroll_start_sm_cb_msg28(struct fp_dev *dev, @@ -923,6 +958,7 @@ static void enroll_start_sm_cb_msg28(struct fp_dev *dev, static void enroll_start_sm_run_state(struct fpi_ssm *ssm) { struct fp_dev *dev = ssm->dev; + int r; switch (ssm->cur_state) { case RUN_INITSM: ; @@ -931,14 +967,19 @@ static void enroll_start_sm_run_state(struct fpi_ssm *ssm) fpi_ssm_start(initsm, enroll_start_sm_cb_initsm); break; case ENROLL_INIT: ; - struct libusb_bulk_transfer msg; - struct libusb_urb_handle *urbh; - fill_send_cmd28_urb(dev, &msg, 0x02, enroll_init, sizeof(enroll_init)); - urbh = libusb_async_bulk_transfer(dev->udev, &msg, - enroll_start_sm_cb_init, ssm, TIMEOUT); - if (!urbh) { - g_free(msg.data); - fpi_ssm_mark_aborted(ssm, -EIO); + struct libusb_transfer *transfer; + transfer = alloc_send_cmd28_transfer(dev, 0x02, enroll_init, + sizeof(enroll_init), enroll_start_sm_cb_init, ssm); + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + break; + } + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(transfer->buffer); + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, r); } break; case READ_ENROLL_MSG28: ; @@ -946,7 +987,7 @@ static void enroll_start_sm_run_state(struct fpi_ssm *ssm) * to subcmd 0 after submitting subcmd 2? */ /* actually this is probably a poll response? does the above cmd * include a 30 01 poll somewhere? */ - int r = read_msg_async(dev, enroll_start_sm_cb_msg28, ssm); + r = read_msg_async(dev, enroll_start_sm_cb_msg28, ssm); if (r < 0) fpi_ssm_mark_aborted(ssm, r); break; @@ -1069,35 +1110,37 @@ static void enroll_iterate_msg_cb(struct fp_dev *dev, } -static void enroll_iterate_cmd_cb(libusb_dev_handle *devh, - libusb_urb_handle *urbh, enum libusb_urb_cb_status status, - unsigned char endpoint, int rqlength, unsigned char *data, - int actual_length, void *user_data) +static void enroll_iterate_cmd_cb(struct libusb_transfer *transfer) { - struct fp_dev *dev = user_data; + struct fp_dev *dev = transfer->user_data; - if (status != FP_URB_COMPLETED) { + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { fpi_drvcb_enroll_stage_completed(dev, -EIO, NULL, NULL); - } else if (rqlength != actual_length) { + } else if (transfer->length != transfer->actual_length) { fpi_drvcb_enroll_stage_completed(dev, -EPROTO, NULL, NULL); } else { int r = read_msg_async(dev, enroll_iterate_msg_cb, NULL); if (r < 0) fpi_drvcb_enroll_stage_completed(dev, r, NULL, NULL); } - libusb_urb_handle_free(urbh); + libusb_free_transfer(transfer); } static void enroll_iterate(struct fp_dev *dev) { - struct libusb_bulk_transfer msg; - struct libusb_urb_handle *urbh; + int r; + struct libusb_transfer *transfer = alloc_send_cmd28_transfer(dev, 0x00, + poll_data, sizeof(poll_data), enroll_iterate_cmd_cb, dev); - fill_send_cmd28_urb(dev, &msg, 0x00, poll_data, sizeof(poll_data)); - urbh = libusb_async_bulk_transfer(dev->udev, &msg, enroll_iterate_cmd_cb, - dev, TIMEOUT); - if (!urbh) { - g_free(msg.data); + if (!transfer) { + fpi_drvcb_enroll_stage_completed(dev, -ENOMEM, NULL, NULL); + return; + } + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(transfer->buffer); + libusb_free_transfer(transfer); fpi_drvcb_enroll_stage_completed(dev, -EIO, NULL, NULL); } } @@ -1176,23 +1219,22 @@ static void verify_start_sm_cb_initsm(struct fpi_ssm *initsm) fpi_ssm_free(initsm); } -static void verify_init_2803_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, - enum libusb_urb_cb_status status, unsigned char endpoint, - int rqlength, unsigned char *data, int actual_length, void *user_data) +static void verify_init_2803_cb(struct libusb_transfer *transfer) { - struct fpi_ssm *ssm = user_data; - if (status != FP_URB_COMPLETED) + struct fpi_ssm *ssm = transfer->user_data; + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) fpi_ssm_mark_aborted(ssm, -EIO); - else if (rqlength != actual_length) + else if (transfer->length != transfer->actual_length) fpi_ssm_mark_aborted(ssm, -EPROTO); else fpi_ssm_next_state(ssm); - libusb_urb_handle_free(urbh); + libusb_free_transfer(transfer); } static void verify_start_sm_run_state(struct fpi_ssm *ssm) { struct fp_dev *dev = ssm->dev; + int r; switch (ssm->cur_state) { case VERIFY_RUN_INITSM: ; @@ -1204,18 +1246,22 @@ static void verify_start_sm_run_state(struct fpi_ssm *ssm) struct fp_print_data *print = dev->verify_data; size_t data_len = sizeof(verify_hdr) + print->length; unsigned char *data = g_malloc(data_len); - struct libusb_bulk_transfer msg; - struct libusb_urb_handle *urbh; + struct libusb_transfer *transfer; memcpy(data, verify_hdr, sizeof(verify_hdr)); memcpy(data + sizeof(verify_hdr), print->data, print->length); - fill_send_cmd28_urb(dev, &msg, 0x03, data, data_len); + transfer = alloc_send_cmd28_transfer(dev, 0x03, data, data_len, + verify_init_2803_cb, ssm); g_free(data); + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + break; + } - urbh = libusb_async_bulk_transfer(dev->udev, &msg, - verify_init_2803_cb, ssm, TIMEOUT); - if (!urbh) { - g_free(msg.data); + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(transfer->buffer); + libusb_free_transfer(transfer); fpi_ssm_mark_aborted(ssm, -EIO); } break; @@ -1323,28 +1369,25 @@ static void verify_rd2800_cb(struct fp_dev *dev, enum read_msg_status msgstat, fpi_drvcb_report_verify_result(dev, -EPROTO, NULL); } -static void verify_wr2800_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, - enum libusb_urb_cb_status status, unsigned char endpoint, - int rqlength, unsigned char *data, int actual_length, void *user_data) +static void verify_wr2800_cb(struct libusb_transfer *transfer) { - struct fp_dev *dev = user_data; + struct fp_dev *dev = transfer->user_data; - if (status != FP_URB_COMPLETED) { + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { fpi_drvcb_report_verify_result(dev, -EIO, NULL); - } else if (rqlength != actual_length) { + } else if (transfer->length != transfer->actual_length) { fpi_drvcb_report_verify_result(dev, -EIO, NULL); } else { int r = read_msg_async(dev, verify_rd2800_cb, NULL); if (r < 0) fpi_drvcb_report_verify_result(dev, r, NULL); } - libusb_urb_handle_free(urbh); + libusb_free_transfer(transfer); } static void verify_iterate(struct fp_dev *dev) { struct upekts_dev *upekdev = dev->priv; - struct libusb_bulk_transfer msg; if (upekdev->stop_verify) { do_verify_stop(dev); @@ -1359,12 +1402,19 @@ static void verify_iterate(struct fp_dev *dev) if (r < 0) fpi_drvcb_report_verify_result(dev, r, NULL); } else { - struct libusb_urb_handle *urbh; - fill_send_cmd28_urb(dev, &msg, 0x00, poll_data, sizeof(poll_data)); - urbh = libusb_async_bulk_transfer(dev->udev, &msg, verify_wr2800_cb, - dev, TIMEOUT); - if (!urbh) { - g_free(msg.data); + int r; + struct libusb_transfer *transfer = alloc_send_cmd28_transfer(dev, + 0x00, poll_data, sizeof(poll_data), verify_wr2800_cb, dev); + + if (!transfer) { + fpi_drvcb_report_verify_result(dev, -ENOMEM, NULL); + return; + } + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(transfer->buffer); + libusb_free_transfer(transfer); fpi_drvcb_report_verify_result(dev, -EIO, NULL); } } diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index c2e5761e..48e2b676 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -122,8 +122,8 @@ struct uru4k_dev { enum fp_imgdev_state activate_state; unsigned char last_hwstat_rd; - libusb_urb_handle *irq_transfer; - libusb_urb_handle *img_transfer; + struct libusb_transfer *irq_transfer; + struct libusb_transfer *img_transfer; irq_cb_fn irq_cb; void *irq_cb_data; @@ -154,19 +154,18 @@ struct set_reg_data { void *user_data; }; -static void set_reg_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, - enum libusb_urb_cb_status status, struct libusb_ctrl_setup *setup, - unsigned char *data, int actual_length, void *user_data) +static void set_reg_cb(struct libusb_transfer *transfer) { - struct set_reg_data *srdata = user_data; + struct set_reg_data *srdata = transfer->user_data; int r = 0; - if (status != FP_URB_COMPLETED) + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) r = -EIO; - else if (setup->wLength != actual_length) + else if (transfer->actual_length != 1) r = -EPROTO; - libusb_urb_handle_free(urbh); + g_free(transfer->buffer); + libusb_free_transfer(transfer); srdata->callback(srdata->dev, r, srdata->user_data); g_free(srdata); } @@ -174,29 +173,32 @@ static void set_reg_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, static int set_reg(struct fp_img_dev *dev, unsigned char reg, unsigned char value, set_reg_cb_fn callback, void *user_data) { - struct set_reg_data *srdata = g_malloc(sizeof(*srdata)); - struct libusb_urb_handle *urbh; - struct libusb_control_transfer trf = { - .requesttype = CTRL_OUT, - .request = USB_RQ, - .value = reg, - .index = 0, - .length = 1, - .data = &value, - }; + struct set_reg_data *srdata; + struct libusb_transfer *transfer = libusb_alloc_transfer(); + unsigned char *data; + int r; + if (!transfer) + return -ENOMEM; + + srdata = g_malloc(sizeof(*srdata)); srdata->dev = dev; srdata->callback = callback; srdata->user_data = user_data; - trf.data[0] = value; - urbh = libusb_async_control_transfer(dev->udev, &trf, set_reg_cb, srdata, - CTRL_TIMEOUT); - if (!urbh) { + data = g_malloc(LIBUSB_CONTROL_SETUP_SIZE + 1); + data[LIBUSB_CONTROL_SETUP_SIZE] = value; + libusb_fill_control_setup(data, CTRL_OUT, USB_RQ, reg, 0, 1); + libusb_fill_control_transfer(transfer, dev->udev, data, set_reg_cb, + srdata, CTRL_TIMEOUT); + + r = libusb_submit_transfer(transfer); + if (r < 0) { g_free(srdata); - return -EIO; + g_free(data); + libusb_free_transfer(transfer); } - return 0; + return r; } /* @@ -233,59 +235,65 @@ struct c_r_data { void *user_data; }; -static void response_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, - enum libusb_urb_cb_status status, struct libusb_ctrl_setup *setup, - unsigned char *data, int actual_length, void *user_data) +static void response_cb(struct libusb_transfer *transfer) { - struct c_r_data *crdata = user_data; + struct c_r_data *crdata = transfer->user_data; int r = 0; - if (status == FP_URB_COMPLETED) + if (transfer->status == LIBUSB_TRANSFER_COMPLETED) r = -EIO; - else if (actual_length != setup->wLength) + else if (transfer->actual_length != CR_LENGTH) r = -EPROTO; - libusb_urb_handle_free(urbh); + g_free(transfer->buffer); + libusb_free_transfer(transfer); crdata->callback(crdata->dev, r, crdata->user_data); } -static void challenge_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, - enum libusb_urb_cb_status status, struct libusb_ctrl_setup *setup, - unsigned char *data, int actual_length, void *user_data) +static void challenge_cb(struct libusb_transfer *transfer) { - struct c_r_data *crdata = user_data; + struct c_r_data *crdata = transfer->user_data; struct fp_img_dev *dev = crdata->dev; struct uru4k_dev *urudev = dev->priv; - unsigned char respdata[CR_LENGTH]; + struct libusb_transfer *resp_transfer; + unsigned char *respdata; + int r; - struct libusb_urb_handle *resp_urbh; - struct libusb_control_transfer trf_write_response = { - .requesttype = CTRL_OUT, - .request = USB_RQ, - .value = REG_RESPONSE, - .index = 0, - .data = respdata, - .length = sizeof(respdata), - }; - - if (status != FP_URB_COMPLETED) { + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { crdata->callback(crdata->dev, -EIO, crdata->user_data); goto out; - } else if (setup->wLength != actual_length) { + } else if (transfer->actual_length != CR_LENGTH) { crdata->callback(crdata->dev, -EPROTO, crdata->user_data); goto out; } - /* produce response from challenge */ - AES_encrypt(data, respdata, &urudev->aeskey); - /* submit response */ - resp_urbh = libusb_async_control_transfer(dev->udev, &trf_write_response, - response_cb, crdata, CTRL_TIMEOUT); - if (!resp_urbh) - crdata->callback(crdata->dev, -EIO, crdata->user_data); + resp_transfer = libusb_alloc_transfer(); + if (!resp_transfer) { + crdata->callback(crdata->dev, -ENOMEM, crdata->user_data); + goto out; + } + + respdata = g_malloc(LIBUSB_CONTROL_SETUP_SIZE + CR_LENGTH); + libusb_fill_control_setup(respdata, CTRL_OUT, USB_RQ, REG_RESPONSE, 0, + CR_LENGTH); + libusb_fill_control_transfer(transfer, dev->udev, respdata, response_cb, + crdata, CTRL_TIMEOUT); + + /* produce response from challenge */ + AES_encrypt(libusb_control_transfer_get_data(transfer), + respdata + LIBUSB_CONTROL_SETUP_SIZE, &urudev->aeskey); + + r = libusb_submit_transfer(resp_transfer); + if (r < 0) { + g_free(respdata); + libusb_free_transfer(resp_transfer); + crdata->callback(crdata->dev, r, crdata->user_data); + } + out: - libusb_urb_handle_free(urbh); + g_free(transfer->buffer); + libusb_free_transfer(transfer); } /* @@ -296,28 +304,33 @@ out: static int do_challenge_response(struct fp_img_dev *dev, challenge_response_cb callback, void *user_data) { - struct c_r_data *crdata = g_malloc(sizeof(*crdata)); - struct libusb_urb_handle *urbh; - struct libusb_control_transfer trf_read_challenge = { - .requesttype = CTRL_IN, - .request = USB_RQ, - .value = REG_CHALLENGE, - .index = 0, - .length = CR_LENGTH, - }; + struct libusb_transfer *transfer = libusb_alloc_transfer();; + struct c_r_data *crdata; + unsigned char *data; + int r; fp_dbg(""); + if (!transfer) + return -ENOMEM; + + crdata = g_malloc(sizeof(*crdata)); crdata->dev = dev; crdata->callback = callback; crdata->user_data = user_data; - urbh = libusb_async_control_transfer(dev->udev, &trf_read_challenge, - challenge_cb, crdata, CTRL_TIMEOUT); - if (!urbh) { + data = g_malloc(LIBUSB_CONTROL_SETUP_SIZE + CR_LENGTH); + libusb_fill_control_setup(data, CTRL_IN, USB_RQ, REG_CHALLENGE, 0, + CR_LENGTH); + libusb_fill_control_transfer(transfer, dev->udev, data, challenge_cb, + crdata, CTRL_TIMEOUT); + + r = libusb_submit_transfer(transfer); + if (r < 0) { g_free(crdata); - return -EIO; + g_free(data); + libusb_free_transfer(transfer); } - return 0; + return r; } /***** INTERRUPT HANDLING *****/ @@ -326,35 +339,33 @@ static int do_challenge_response(struct fp_img_dev *dev, static int start_irq_handler(struct fp_img_dev *dev); -static void irq_handler(libusb_dev_handle *devh, libusb_urb_handle *urbh, - enum libusb_urb_cb_status status, unsigned char endpoint, - int rqlength, unsigned char *data, int actual_length, void *user_data) +static void irq_handler(struct libusb_transfer *transfer) { - struct fp_img_dev *dev = user_data; + struct fp_img_dev *dev = transfer->user_data; struct uru4k_dev *urudev = dev->priv; + unsigned char *data = transfer->buffer; uint16_t type; int r = 0; - libusb_urb_handle_free(urbh); - - if (status == FP_URB_CANCELLED) { + if (transfer->status == LIBUSB_TRANSFER_CANCELLED) { fp_dbg("cancelled"); if (urudev->irqs_stopped_cb) urudev->irqs_stopped_cb(dev); urudev->irqs_stopped_cb = NULL; goto out; - } else if (status != FP_URB_COMPLETED) { + } else if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { r = -EIO; goto err; - } else if (actual_length != rqlength) { - fp_err("short interrupt read? %d", actual_length); + } else if (transfer->actual_length != transfer->length) { + fp_err("short interrupt read? %d", transfer->actual_length); r = -EPROTO; goto err; } type = GUINT16_FROM_BE(*((uint16_t *) data)); - g_free(data); fp_dbg("recv irq type %04x", type); + g_free(data); + libusb_free_transfer(transfer); /* The 0800 interrupt seems to indicate imminent failure (0 bytes transfer) * of the next scan. It still appears on occasion. */ @@ -370,41 +381,47 @@ static void irq_handler(libusb_dev_handle *devh, libusb_urb_handle *urbh, if (r == 0) return; + transfer = NULL; data = NULL; err: if (urudev->irq_cb) urudev->irq_cb(dev, r, 0, urudev->irq_cb_data); out: g_free(data); + libusb_free_transfer(transfer); urudev->irq_transfer = NULL; } static int start_irq_handler(struct fp_img_dev *dev) { struct uru4k_dev *urudev = dev->priv; - struct libusb_urb_handle *urbh; - struct libusb_bulk_transfer trf = { - .endpoint = EP_INTR, - .length = IRQ_LENGTH, - .data = g_malloc(IRQ_LENGTH), - }; + struct libusb_transfer *transfer = libusb_alloc_transfer(); + unsigned char *data; + int r; - urbh = libusb_async_interrupt_transfer(dev->udev, &trf, irq_handler, dev, - 0); - urudev->irq_transfer = urbh; - if (!urbh) { - g_free(trf.data); - return -EIO; + if (!transfer) + return -ENOMEM; + + data = g_malloc(IRQ_LENGTH); + libusb_fill_bulk_transfer(transfer, dev->udev, EP_INTR, data, IRQ_LENGTH, + irq_handler, dev, 0); + + urudev->irq_transfer = transfer; + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(data); + libusb_free_transfer(transfer); + urudev->irq_transfer = NULL; } - return 0; + return r; } static void stop_irq_handler(struct fp_img_dev *dev, irqs_stopped_cb_fn cb) { struct uru4k_dev *urudev = dev->priv; - struct libusb_urb_handle *urbh = urudev->irq_transfer; - if (urbh) { - libusb_urb_handle_cancel(dev->udev, urbh); + struct libusb_transfer *transfer = urudev->irq_transfer; + if (transfer) { + libusb_cancel_transfer(transfer); urudev->irqs_stopped_cb = cb; } } @@ -413,46 +430,45 @@ static void stop_irq_handler(struct fp_img_dev *dev, irqs_stopped_cb_fn cb) static int start_imaging_loop(struct fp_img_dev *dev); -static void image_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, - enum libusb_urb_cb_status status, unsigned char endpoint, - int rqlength, unsigned char *data, int actual_length, void *user_data) +static void image_cb(struct libusb_transfer *transfer) { - struct fp_img_dev *dev = user_data; + struct fp_img_dev *dev = transfer->user_data; struct uru4k_dev *urudev = dev->priv; int hdr_skip = CAPTURE_HDRLEN; int image_size = DATABLK_EXPECT - CAPTURE_HDRLEN; struct fp_img *img; int r = 0; - libusb_urb_handle_free(urbh); - if (status == FP_URB_CANCELLED) { + if (transfer->status == LIBUSB_TRANSFER_CANCELLED) { fp_dbg("cancelled"); urudev->img_transfer = NULL; - g_free(data); + g_free(transfer->buffer); + libusb_free_transfer(transfer); return; - } else if (status != FP_URB_COMPLETED) { + } else if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { r = -EIO; goto out; } - if (actual_length == image_size) { + if (transfer->actual_length == image_size) { /* no header! this is rather odd, but it happens sometimes with my MS * keyboard */ fp_dbg("got image with no header!"); hdr_skip = 0; - } else if (actual_length != DATABLK_EXPECT) { - fp_err("unexpected image capture size (%d)", actual_length); + } else if (transfer->actual_length != DATABLK_EXPECT) { + fp_err("unexpected image capture size (%d)", transfer->actual_length); r = -EPROTO; goto out; } img = fpi_img_new(image_size); - memcpy(img->data, data + hdr_skip, image_size); + memcpy(img->data, transfer->buffer + hdr_skip, image_size); img->flags = FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED | FP_IMG_COLORS_INVERTED; fpi_imgdev_image_captured(dev, img); out: - g_free(data); + g_free(transfer->buffer); + libusb_free_transfer(transfer); if (r == 0) r = start_imaging_loop(dev); @@ -463,29 +479,33 @@ out: static int start_imaging_loop(struct fp_img_dev *dev) { struct uru4k_dev *urudev = dev->priv; - struct libusb_urb_handle *urbh; - struct libusb_bulk_transfer trf = { - .endpoint = EP_DATA, - .length = DATABLK_RQLEN, - .data = g_malloc(DATABLK_RQLEN), - }; + struct libusb_transfer *transfer = libusb_alloc_transfer(); + unsigned char *data; + int r; - urbh = libusb_async_bulk_transfer(dev->udev, &trf, image_cb, dev, 0); - urudev->img_transfer = urbh; - if (!urbh) { - g_free(trf.data); - return -EIO; + if (!transfer) + return -ENOMEM; + + data = g_malloc(DATABLK_RQLEN); + libusb_fill_bulk_transfer(transfer, dev->udev, EP_DATA, data, + DATABLK_RQLEN, image_cb, dev, 0); + + urudev->img_transfer = transfer; + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(data); + libusb_free_transfer(transfer); } - return 0; + return r; } static void stop_imaging_loop(struct fp_img_dev *dev) { struct uru4k_dev *urudev = dev->priv; - libusb_urb_handle *urbh = urudev->img_transfer; - if (urbh) - libusb_urb_handle_cancel(dev->udev, urbh); + struct libusb_transfer *transfer = urudev->img_transfer; + if (transfer) + libusb_cancel_transfer(transfer); /* FIXME: should probably wait for cancellation to complete */ } @@ -577,68 +597,72 @@ static void sm_set_hwstat(struct fpi_ssm *ssm, unsigned char value) sm_set_reg(ssm, REG_HWSTAT, value); } -static void sm_get_hwstat_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, - enum libusb_urb_cb_status status, struct libusb_ctrl_setup *setup, - unsigned char *data, int actual_length, void *user_data) +static void sm_get_hwstat_cb(struct libusb_transfer *transfer) { - struct fpi_ssm *ssm = user_data; + struct fpi_ssm *ssm = transfer->user_data; struct fp_img_dev *dev = ssm->priv; struct uru4k_dev *urudev = dev->priv; - if (status != FP_URB_COMPLETED) { + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { fpi_ssm_mark_aborted(ssm, -EIO); - } else if (setup->wLength != actual_length) { + } else if (transfer->actual_length != 1) { fpi_ssm_mark_aborted(ssm, -EPROTO); } else { - urudev->last_hwstat_rd = *data; + urudev->last_hwstat_rd = libusb_control_transfer_get_data(transfer)[0]; fp_dbg("value %02x", urudev->last_hwstat_rd); fpi_ssm_next_state(ssm); } - libusb_urb_handle_free(urbh); + g_free(transfer->buffer); + libusb_free_transfer(transfer); } static void sm_get_hwstat(struct fpi_ssm *ssm) { struct fp_img_dev *dev = ssm->priv; - struct libusb_urb_handle *urbh; + struct libusb_transfer *transfer = libusb_alloc_transfer(); + unsigned char *data; + int r; + + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + return; + } + + data = g_malloc(LIBUSB_CONTROL_SETUP_SIZE + 1); /* The windows driver uses a request of 0x0c here. We use 0x04 to be * consistent with every other command we know about. */ /* FIXME is the above comment still true? */ - struct libusb_control_transfer trf = { - .requesttype = CTRL_IN, - .request = USB_RQ, - .value = REG_HWSTAT, - .index = 0, - .length = 1, - }; - - urbh = libusb_async_control_transfer(dev->udev, &trf, sm_get_hwstat_cb, + libusb_fill_control_setup(data, CTRL_IN, USB_RQ, REG_HWSTAT, 0, 1); + libusb_fill_control_transfer(transfer, dev->udev, data, sm_get_hwstat_cb, ssm, CTRL_TIMEOUT); - if (!urbh) + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(data); + libusb_free_transfer(transfer); fpi_ssm_mark_aborted(ssm, -EIO); + } } -static void sm_fix_fw_read_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, - enum libusb_urb_cb_status status, struct libusb_ctrl_setup *setup, - unsigned char *data, int actual_length, void *user_data) +static void sm_fix_fw_read_cb(struct libusb_transfer *transfer) { - struct fpi_ssm *ssm = user_data; + struct fpi_ssm *ssm = transfer->user_data; struct fp_img_dev *dev = ssm->priv; struct uru4k_dev *urudev = dev->priv; unsigned char new; unsigned char fwenc; uint32_t enc_addr = FIRMWARE_START + urudev->profile->fw_enc_offset; - if (status != FP_URB_COMPLETED) { + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { fpi_ssm_mark_aborted(ssm, -EIO); goto out; - } else if (actual_length != setup->wLength) { + } else if (transfer->actual_length != 1) { fpi_ssm_mark_aborted(ssm, -EPROTO); goto out; } - fwenc = data[0]; + fwenc = libusb_control_transfer_get_data(transfer)[0]; fp_dbg("firmware encryption byte at %x reads %02x", enc_addr, fwenc); if (fwenc != 0x07 && fwenc != 0x17) fp_dbg("strange encryption byte value, please report this"); @@ -652,7 +676,8 @@ static void sm_fix_fw_read_cb(libusb_dev_handle *devh, libusb_urb_handle *urbh, } out: - libusb_urb_handle_free(urbh); + g_free(transfer->buffer); + libusb_free_transfer(transfer); } static void sm_fix_firmware(struct fpi_ssm *ssm) @@ -660,20 +685,26 @@ static void sm_fix_firmware(struct fpi_ssm *ssm) struct fp_img_dev *dev = ssm->priv; struct uru4k_dev *urudev = dev->priv; uint32_t enc_addr = FIRMWARE_START + urudev->profile->fw_enc_offset; + struct libusb_transfer *transfer = libusb_alloc_transfer(); + unsigned char *data; + int r; - struct libusb_urb_handle *urbh; - struct libusb_control_transfer trf_read_fw = { - .requesttype = 0xc0, - .request = 0x0c, - .value = enc_addr, - .index = 0, - .length = 1, - }; + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + return; + } + + data = g_malloc(LIBUSB_CONTROL_SETUP_SIZE + 1); + libusb_fill_control_setup(data, 0xc0, 0x0c, enc_addr, 0, 1); + libusb_fill_control_transfer(transfer, dev->udev, data, sm_fix_fw_read_cb, + ssm, CTRL_TIMEOUT); - urbh = libusb_async_control_transfer(dev->udev, &trf_read_fw, - sm_fix_fw_read_cb, ssm, CTRL_TIMEOUT); - if (!urbh) - fpi_ssm_mark_aborted(ssm, -EIO); + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(data); + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, r); + } } /***** INITIALIZATION *****/ @@ -1070,7 +1101,7 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) int r; /* Find fingerprint interface */ - config = libusb_dev_get_config(libusb_devh_get_dev(dev->udev)); + config = libusb_get_config_descriptor(libusb_get_device(dev->udev)); for (i = 0; i < config->bNumInterfaces; i++) { struct libusb_interface *cur_iface = &config->interface[i]; diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index c391e376..5b1c289c 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -93,7 +93,7 @@ enum fp_dev_state { struct fp_dev { struct fp_driver *drv; - libusb_dev_handle *udev; + libusb_device_handle *udev; uint32_t devtype; void *priv; @@ -161,7 +161,7 @@ enum fp_imgdev_verify_state { struct fp_img_dev { struct fp_dev *dev; - libusb_dev_handle *udev; + libusb_device_handle *udev; enum fp_imgdev_action action; int action_state; @@ -249,7 +249,7 @@ void fpi_img_driver_setup(struct fp_img_driver *idriver); container_of((drv), struct fp_img_driver, driver) struct fp_dscv_dev { - libusb_dev *udev; + struct libusb_device *udev; struct fp_driver *drv; unsigned long driver_data; uint32_t devtype; diff --git a/libfprint/sync.c b/libfprint/sync.c index 61557eb8..d636edd8 100644 --- a/libfprint/sync.c +++ b/libfprint/sync.c @@ -180,7 +180,7 @@ API_EXPORTED int fp_enroll_finger_img(struct fp_dev *dev, int stage = dev->__enroll_stage; gboolean final = FALSE; gboolean stopped = FALSE; - struct sync_enroll_data *edata; + struct sync_enroll_data *edata = NULL; int r; fp_dbg(""); From f546fa2555ee180f4fef9a4bb2cf3a8f15edaa35 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Mon, 10 Mar 2008 13:33:32 +0000 Subject: [PATCH 116/184] Fix synchronous enrollment for multi-stage devices --- libfprint/sync.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/libfprint/sync.c b/libfprint/sync.c index d636edd8..440b725a 100644 --- a/libfprint/sync.c +++ b/libfprint/sync.c @@ -263,6 +263,9 @@ API_EXPORTED int fp_enroll_finger_img(struct fp_dev *dev, break; } + if (!final) + return r; + out: if (final) { fp_dbg("ending enrollment"); From 156e5e7d7c691c32e56eecfb0b272d3dbdf6e0fd Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Thu, 13 Mar 2008 12:54:27 +0000 Subject: [PATCH 117/184] Update for new libusb_get_pollfds API --- libfprint/poll.c | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/libfprint/poll.c b/libfprint/poll.c index df76233d..dc95c173 100644 --- a/libfprint/poll.c +++ b/libfprint/poll.c @@ -291,21 +291,26 @@ API_EXPORTED int fp_get_next_timeout(struct timeval *tv) */ API_EXPORTED size_t fp_get_pollfds(struct fp_pollfd **pollfds) { - struct libusb_pollfd *usbfds; + struct libusb_pollfd **usbfds; + struct libusb_pollfd *usbfd; struct fp_pollfd *ret; - size_t cnt; - size_t i; + size_t cnt = 0; + size_t i = 0; - cnt = libusb_get_pollfds(&usbfds); - if (cnt <= 0) { + usbfds = libusb_get_pollfds(); + if (!usbfds) { *pollfds = NULL; - return cnt; + return -EIO; } - ret = g_malloc(sizeof(struct libusb_pollfd) * cnt); - for (i = 0; i < cnt; i++) { - ret[i].fd = usbfds[i].fd; - ret[i].events = usbfds[i].events; + while ((usbfd = usbfds[i++]) != NULL) + cnt++; + + ret = g_malloc(sizeof(struct fp_pollfd) * cnt); + i = 0; + while ((usbfd = usbfds[i++]) != NULL) { + ret[i].fd = usbfd->fd; + ret[i].events = usbfd->events; } *pollfds = ret; From d3d68be49033f17c9933674d6edc52aea09d9b60 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Wed, 19 Mar 2008 16:19:07 +0000 Subject: [PATCH 118/184] uru4000: fix register widths Encryption byte address was being truncated in the sm_fix_fw_read_cb path --- libfprint/drivers/uru4000.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index 48e2b676..61b5e5a7 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -170,7 +170,7 @@ static void set_reg_cb(struct libusb_transfer *transfer) g_free(srdata); } -static int set_reg(struct fp_img_dev *dev, unsigned char reg, +static int set_reg(struct fp_img_dev *dev, uint16_t reg, unsigned char value, set_reg_cb_fn callback, void *user_data) { struct set_reg_data *srdata; @@ -576,7 +576,7 @@ static void sm_set_reg_cb(struct fp_img_dev *dev, int result, void *user_data) fpi_ssm_next_state(ssm); } -static void sm_set_reg(struct fpi_ssm *ssm, unsigned char reg, +static void sm_set_reg(struct fpi_ssm *ssm, uint16_t reg, unsigned char value) { struct fp_img_dev *dev = ssm->priv; @@ -652,7 +652,7 @@ static void sm_fix_fw_read_cb(struct libusb_transfer *transfer) struct uru4k_dev *urudev = dev->priv; unsigned char new; unsigned char fwenc; - uint32_t enc_addr = FIRMWARE_START + urudev->profile->fw_enc_offset; + uint16_t enc_addr = FIRMWARE_START + urudev->profile->fw_enc_offset; if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { fpi_ssm_mark_aborted(ssm, -EIO); @@ -684,7 +684,7 @@ static void sm_fix_firmware(struct fpi_ssm *ssm) { struct fp_img_dev *dev = ssm->priv; struct uru4k_dev *urudev = dev->priv; - uint32_t enc_addr = FIRMWARE_START + urudev->profile->fw_enc_offset; + uint16_t enc_addr = FIRMWARE_START + urudev->profile->fw_enc_offset; struct libusb_transfer *transfer = libusb_alloc_transfer(); unsigned char *data; int r; From fb49c24ae24bc296bb123f00bda1f80f50587eaf Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Wed, 19 Mar 2008 17:25:53 +0000 Subject: [PATCH 119/184] uru4000: Unify register I/O --- libfprint/drivers/uru4000.c | 409 +++++++++++++++++------------------- 1 file changed, 190 insertions(+), 219 deletions(-) diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index 61b5e5a7..d5fcab77 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -120,7 +120,8 @@ struct uru4k_dev { const struct uru4k_dev_profile *profile; uint8_t interface; enum fp_imgdev_state activate_state; - unsigned char last_hwstat_rd; + unsigned char last_reg_rd; + unsigned char last_hwstat; struct libusb_transfer *irq_transfer; struct libusb_transfer *img_transfer; @@ -145,35 +146,40 @@ static const unsigned char crkey[] = { 0x98, 0xe0, 0x0f, 0x3c, 0x59, 0x8f, 0x5f, 0x4b, }; -typedef void (*set_reg_cb_fn)(struct fp_img_dev *dev, int status, +/***** REGISTER I/O *****/ + +typedef void (*write_regs_cb_fn)(struct fp_img_dev *dev, int status, void *user_data); -struct set_reg_data { +struct write_regs_data { struct fp_img_dev *dev; - set_reg_cb_fn callback; + write_regs_cb_fn callback; void *user_data; }; -static void set_reg_cb(struct libusb_transfer *transfer) +static void write_regs_cb(struct libusb_transfer *transfer) { - struct set_reg_data *srdata = transfer->user_data; + struct write_regs_data *wrdata = transfer->user_data; + struct libusb_control_setup *setup = + libusb_control_transfer_get_setup(transfer); int r = 0; if (transfer->status != LIBUSB_TRANSFER_COMPLETED) r = -EIO; - else if (transfer->actual_length != 1) + else if (transfer->actual_length != setup->wLength) r = -EPROTO; g_free(transfer->buffer); libusb_free_transfer(transfer); - srdata->callback(srdata->dev, r, srdata->user_data); - g_free(srdata); + wrdata->callback(wrdata->dev, r, wrdata->user_data); + g_free(wrdata); } -static int set_reg(struct fp_img_dev *dev, uint16_t reg, - unsigned char value, set_reg_cb_fn callback, void *user_data) +static int write_regs(struct fp_img_dev *dev, uint16_t first_reg, + uint16_t num_regs, unsigned char *values, write_regs_cb_fn callback, + void *user_data) { - struct set_reg_data *srdata; + struct write_regs_data *wrdata; struct libusb_transfer *transfer = libusb_alloc_transfer(); unsigned char *data; int r; @@ -181,26 +187,98 @@ static int set_reg(struct fp_img_dev *dev, uint16_t reg, if (!transfer) return -ENOMEM; - srdata = g_malloc(sizeof(*srdata)); - srdata->dev = dev; - srdata->callback = callback; - srdata->user_data = user_data; + wrdata = g_malloc(sizeof(*wrdata)); + wrdata->dev = dev; + wrdata->callback = callback; + wrdata->user_data = user_data; - data = g_malloc(LIBUSB_CONTROL_SETUP_SIZE + 1); - data[LIBUSB_CONTROL_SETUP_SIZE] = value; - libusb_fill_control_setup(data, CTRL_OUT, USB_RQ, reg, 0, 1); - libusb_fill_control_transfer(transfer, dev->udev, data, set_reg_cb, - srdata, CTRL_TIMEOUT); + data = g_malloc(LIBUSB_CONTROL_SETUP_SIZE + num_regs); + memcpy(data + LIBUSB_CONTROL_SETUP_SIZE, values, num_regs); + libusb_fill_control_setup(data, CTRL_OUT, USB_RQ, first_reg, 0, num_regs); + libusb_fill_control_transfer(transfer, dev->udev, data, write_regs_cb, + wrdata, CTRL_TIMEOUT); r = libusb_submit_transfer(transfer); if (r < 0) { - g_free(srdata); + g_free(wrdata); g_free(data); libusb_free_transfer(transfer); } return r; } +static int write_reg(struct fp_img_dev *dev, uint16_t reg, + unsigned char value, write_regs_cb_fn callback, void *user_data) +{ + return write_regs(dev, reg, 1, &value, callback, user_data); +} + +typedef void (*read_regs_cb_fn)(struct fp_img_dev *dev, int status, + unsigned char *data, void *user_data); + +struct read_regs_data { + struct fp_img_dev *dev; + read_regs_cb_fn callback; + void *user_data; +}; + +static void read_regs_cb(struct libusb_transfer *transfer) +{ + struct read_regs_data *rrdata = transfer->user_data; + struct libusb_control_setup *setup = + libusb_control_transfer_get_setup(transfer); + unsigned char *data = NULL; + int r = 0; + + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) + r = -EIO; + else if (transfer->actual_length != setup->wLength) + r = -EPROTO; + else + data = libusb_control_transfer_get_data(transfer); + + rrdata->callback(rrdata->dev, r, data, rrdata->user_data); + g_free(rrdata); + g_free(transfer->buffer); + libusb_free_transfer(transfer); +} + +static int read_regs(struct fp_img_dev *dev, uint16_t first_reg, + uint16_t num_regs, read_regs_cb_fn callback, void *user_data) +{ + struct read_regs_data *rrdata; + struct libusb_transfer *transfer = libusb_alloc_transfer(); + unsigned char *data; + int r; + + if (!transfer) + return -ENOMEM; + + rrdata = g_malloc(sizeof(*rrdata)); + rrdata->dev = dev; + rrdata->callback = callback; + rrdata->user_data = user_data; + + data = g_malloc(LIBUSB_CONTROL_SETUP_SIZE + num_regs); + libusb_fill_control_setup(data, CTRL_IN, USB_RQ, first_reg, 0, num_regs); + libusb_fill_control_transfer(transfer, dev->udev, data, read_regs_cb, + rrdata, CTRL_TIMEOUT); + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(rrdata); + g_free(data); + libusb_free_transfer(transfer); + } + return r; +} + +static int read_reg(struct fp_img_dev *dev, uint16_t reg, + read_regs_cb_fn callback, void *user_data) +{ + return read_regs(dev, reg, 1, callback, user_data); +} + /* * HWSTAT * @@ -226,74 +304,38 @@ static int set_reg(struct fp_img_dev *dev, uint16_t reg, * and interrupt to the host. Maybe? */ -typedef void (*challenge_response_cb)(struct fp_img_dev *dev, int result, - void *user_data); - -struct c_r_data { - struct fp_img_dev *dev; - challenge_response_cb callback; - void *user_data; -}; - -static void response_cb(struct libusb_transfer *transfer) +static void response_cb(struct fp_img_dev *dev, int status, void *user_data) { - struct c_r_data *crdata = transfer->user_data; - int r = 0; - - if (transfer->status == LIBUSB_TRANSFER_COMPLETED) - r = -EIO; - else if (transfer->actual_length != CR_LENGTH) - r = -EPROTO; - - g_free(transfer->buffer); - libusb_free_transfer(transfer); - crdata->callback(crdata->dev, r, crdata->user_data); + struct fpi_ssm *ssm = user_data; + if (status == 0) + fpi_ssm_next_state(ssm); + else + fpi_ssm_mark_aborted(ssm, status); } -static void challenge_cb(struct libusb_transfer *transfer) +static void challenge_cb(struct fp_img_dev *dev, int status, + unsigned char *data, void *user_data) { - struct c_r_data *crdata = transfer->user_data; - struct fp_img_dev *dev = crdata->dev; + struct fpi_ssm *ssm = user_data; struct uru4k_dev *urudev = dev->priv; - struct libusb_transfer *resp_transfer; unsigned char *respdata; int r; - if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { - crdata->callback(crdata->dev, -EIO, crdata->user_data); - goto out; - } else if (transfer->actual_length != CR_LENGTH) { - crdata->callback(crdata->dev, -EPROTO, crdata->user_data); - goto out; + if (status != 0) { + fpi_ssm_mark_aborted(ssm, status); + return; } /* submit response */ - resp_transfer = libusb_alloc_transfer(); - if (!resp_transfer) { - crdata->callback(crdata->dev, -ENOMEM, crdata->user_data); - goto out; - } - - respdata = g_malloc(LIBUSB_CONTROL_SETUP_SIZE + CR_LENGTH); - libusb_fill_control_setup(respdata, CTRL_OUT, USB_RQ, REG_RESPONSE, 0, - CR_LENGTH); - libusb_fill_control_transfer(transfer, dev->udev, respdata, response_cb, - crdata, CTRL_TIMEOUT); - /* produce response from challenge */ - AES_encrypt(libusb_control_transfer_get_data(transfer), - respdata + LIBUSB_CONTROL_SETUP_SIZE, &urudev->aeskey); - - r = libusb_submit_transfer(resp_transfer); - if (r < 0) { - g_free(respdata); - libusb_free_transfer(resp_transfer); - crdata->callback(crdata->dev, r, crdata->user_data); - } - -out: - g_free(transfer->buffer); - libusb_free_transfer(transfer); + /* FIXME would this work in-place? */ + respdata = g_malloc(CR_LENGTH); + AES_encrypt(data, respdata, &urudev->aeskey); + + r = write_regs(dev, REG_RESPONSE, CR_LENGTH, respdata, response_cb, ssm); + g_free(respdata); + if (r < 0) + fpi_ssm_mark_aborted(ssm, r); } /* @@ -301,36 +343,15 @@ out: * authentication scheme, where the device challenges the authenticity of the * driver. */ -static int do_challenge_response(struct fp_img_dev *dev, - challenge_response_cb callback, void *user_data) +static void sm_do_challenge_response(struct fpi_ssm *ssm) { - struct libusb_transfer *transfer = libusb_alloc_transfer();; - struct c_r_data *crdata; - unsigned char *data; + struct fp_img_dev *dev = ssm->priv; int r; fp_dbg(""); - if (!transfer) - return -ENOMEM; - - crdata = g_malloc(sizeof(*crdata)); - crdata->dev = dev; - crdata->callback = callback; - crdata->user_data = user_data; - - data = g_malloc(LIBUSB_CONTROL_SETUP_SIZE + CR_LENGTH); - libusb_fill_control_setup(data, CTRL_IN, USB_RQ, REG_CHALLENGE, 0, - CR_LENGTH); - libusb_fill_control_transfer(transfer, dev->udev, data, challenge_cb, - crdata, CTRL_TIMEOUT); - - r = libusb_submit_transfer(transfer); - if (r < 0) { - g_free(crdata); - g_free(data); - libusb_free_transfer(transfer); - } - return r; + r = read_regs(dev, REG_CHALLENGE, CR_LENGTH, challenge_cb, ssm); + if (r < 0) + fpi_ssm_mark_aborted(ssm, r); } /***** INTERRUPT HANDLING *****/ @@ -524,7 +545,7 @@ static void finger_presence_irq_cb(struct fp_img_dev *dev, int status, fp_warn("ignoring unexpected interrupt %04x", type); } -static void change_state_set_reg_cb(struct fp_img_dev *dev, int status, +static void change_state_write_reg_cb(struct fp_img_dev *dev, int status, void *user_data) { if (status) @@ -542,21 +563,21 @@ static int dev_change_state(struct fp_img_dev *dev, enum fp_imgdev_state state) if (!IRQ_HANDLER_IS_RUNNING(urudev)) return -EIO; urudev->irq_cb = finger_presence_irq_cb; - return set_reg(dev, REG_MODE, MODE_AWAIT_FINGER_ON, - change_state_set_reg_cb, NULL); + return write_reg(dev, REG_MODE, MODE_AWAIT_FINGER_ON, + change_state_write_reg_cb, NULL); case IMGDEV_STATE_CAPTURE: urudev->irq_cb = NULL; start_imaging_loop(dev); - return set_reg(dev, REG_MODE, MODE_CAPTURE, change_state_set_reg_cb, + return write_reg(dev, REG_MODE, MODE_CAPTURE, change_state_write_reg_cb, NULL); case IMGDEV_STATE_AWAIT_FINGER_OFF: if (!IRQ_HANDLER_IS_RUNNING(urudev)) return -EIO; urudev->irq_cb = finger_presence_irq_cb; - return set_reg(dev, REG_MODE, MODE_AWAIT_FINGER_OFF, - change_state_set_reg_cb, NULL); + return write_reg(dev, REG_MODE, MODE_AWAIT_FINGER_OFF, + change_state_write_reg_cb, NULL); default: fp_err("unrecognised state %d", state); @@ -566,7 +587,7 @@ static int dev_change_state(struct fp_img_dev *dev, enum fp_imgdev_state state) /***** GENERIC STATE MACHINE HELPER FUNCTIONS *****/ -static void sm_set_reg_cb(struct fp_img_dev *dev, int result, void *user_data) +static void sm_write_reg_cb(struct fp_img_dev *dev, int result, void *user_data) { struct fpi_ssm *ssm = user_data; @@ -576,11 +597,37 @@ static void sm_set_reg_cb(struct fp_img_dev *dev, int result, void *user_data) fpi_ssm_next_state(ssm); } -static void sm_set_reg(struct fpi_ssm *ssm, uint16_t reg, +static void sm_write_reg(struct fpi_ssm *ssm, uint16_t reg, unsigned char value) { struct fp_img_dev *dev = ssm->priv; - int r = set_reg(dev, reg, value, sm_set_reg_cb, ssm); + int r = write_reg(dev, reg, value, sm_write_reg_cb, ssm); + if (r < 0) + fpi_ssm_mark_aborted(ssm, r); +} + +static void sm_read_reg_cb(struct fp_img_dev *dev, int result, + unsigned char *data, void *user_data) +{ + struct fpi_ssm *ssm = user_data; + struct uru4k_dev *urudev = dev->priv; + + if (result) { + fpi_ssm_mark_aborted(ssm, result); + } else { + urudev->last_reg_rd = *data; + fp_dbg("reg value %x", urudev->last_reg_rd); + fpi_ssm_next_state(ssm); + } +} + +static void sm_read_reg(struct fpi_ssm *ssm, uint16_t reg) +{ + struct fp_img_dev *dev = ssm->priv; + int r; + + fp_dbg("read reg %x", reg); + r = read_reg(dev, reg, sm_read_reg_cb, ssm); if (r < 0) fpi_ssm_mark_aborted(ssm, r); } @@ -588,81 +635,30 @@ static void sm_set_reg(struct fpi_ssm *ssm, uint16_t reg, static void sm_set_mode(struct fpi_ssm *ssm, unsigned char mode) { fp_dbg("mode %02x", mode); - sm_set_reg(ssm, REG_MODE, mode); + sm_write_reg(ssm, REG_MODE, mode); } static void sm_set_hwstat(struct fpi_ssm *ssm, unsigned char value) { fp_dbg("set %02x", value); - sm_set_reg(ssm, REG_HWSTAT, value); + sm_write_reg(ssm, REG_HWSTAT, value); } -static void sm_get_hwstat_cb(struct libusb_transfer *transfer) +static void sm_fix_fw_read_cb(struct fp_img_dev *dev, int status, + unsigned char *data, void *user_data) { - struct fpi_ssm *ssm = transfer->user_data; - struct fp_img_dev *dev = ssm->priv; - struct uru4k_dev *urudev = dev->priv; - - if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { - fpi_ssm_mark_aborted(ssm, -EIO); - } else if (transfer->actual_length != 1) { - fpi_ssm_mark_aborted(ssm, -EPROTO); - } else { - urudev->last_hwstat_rd = libusb_control_transfer_get_data(transfer)[0]; - fp_dbg("value %02x", urudev->last_hwstat_rd); - fpi_ssm_next_state(ssm); - } - g_free(transfer->buffer); - libusb_free_transfer(transfer); -} - -static void sm_get_hwstat(struct fpi_ssm *ssm) -{ - struct fp_img_dev *dev = ssm->priv; - struct libusb_transfer *transfer = libusb_alloc_transfer(); - unsigned char *data; - int r; - - if (!transfer) { - fpi_ssm_mark_aborted(ssm, -ENOMEM); - return; - } - - data = g_malloc(LIBUSB_CONTROL_SETUP_SIZE + 1); - - /* The windows driver uses a request of 0x0c here. We use 0x04 to be - * consistent with every other command we know about. */ - /* FIXME is the above comment still true? */ - libusb_fill_control_setup(data, CTRL_IN, USB_RQ, REG_HWSTAT, 0, 1); - libusb_fill_control_transfer(transfer, dev->udev, data, sm_get_hwstat_cb, - ssm, CTRL_TIMEOUT); - - r = libusb_submit_transfer(transfer); - if (r < 0) { - g_free(data); - libusb_free_transfer(transfer); - fpi_ssm_mark_aborted(ssm, -EIO); - } -} - -static void sm_fix_fw_read_cb(struct libusb_transfer *transfer) -{ - struct fpi_ssm *ssm = transfer->user_data; - struct fp_img_dev *dev = ssm->priv; + struct fpi_ssm *ssm = user_data; struct uru4k_dev *urudev = dev->priv; unsigned char new; unsigned char fwenc; uint16_t enc_addr = FIRMWARE_START + urudev->profile->fw_enc_offset; - if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { - fpi_ssm_mark_aborted(ssm, -EIO); - goto out; - } else if (transfer->actual_length != 1) { - fpi_ssm_mark_aborted(ssm, -EPROTO); - goto out; + if (status != 0) { + fpi_ssm_mark_aborted(ssm, status); + return; } - fwenc = libusb_control_transfer_get_data(transfer)[0]; + fwenc = data[0]; fp_dbg("firmware encryption byte at %x reads %02x", enc_addr, fwenc); if (fwenc != 0x07 && fwenc != 0x17) fp_dbg("strange encryption byte value, please report this"); @@ -672,12 +668,8 @@ static void sm_fix_fw_read_cb(struct libusb_transfer *transfer) fpi_ssm_next_state(ssm); } else { fp_dbg("fixed encryption byte to %02x", new); - sm_set_reg(ssm, enc_addr, new); + sm_write_reg(ssm, enc_addr, new); } - -out: - g_free(transfer->buffer); - libusb_free_transfer(transfer); } static void sm_fix_firmware(struct fpi_ssm *ssm) @@ -685,26 +677,11 @@ static void sm_fix_firmware(struct fpi_ssm *ssm) struct fp_img_dev *dev = ssm->priv; struct uru4k_dev *urudev = dev->priv; uint16_t enc_addr = FIRMWARE_START + urudev->profile->fw_enc_offset; - struct libusb_transfer *transfer = libusb_alloc_transfer(); - unsigned char *data; int r; - if (!transfer) { - fpi_ssm_mark_aborted(ssm, -ENOMEM); - return; - } - - data = g_malloc(LIBUSB_CONTROL_SETUP_SIZE + 1); - libusb_fill_control_setup(data, 0xc0, 0x0c, enc_addr, 0, 1); - libusb_fill_control_transfer(transfer, dev->udev, data, sm_fix_fw_read_cb, - ssm, CTRL_TIMEOUT); - - r = libusb_submit_transfer(transfer); - if (r < 0) { - g_free(data); - libusb_free_transfer(transfer); + r = read_reg(dev, enc_addr, sm_fix_fw_read_cb, ssm); + if (r < 0) fpi_ssm_mark_aborted(ssm, r); - } } /***** INITIALIZATION *****/ @@ -755,13 +732,14 @@ static void rebootpwr_run_state(struct fpi_ssm *ssm) switch (ssm->cur_state) { case REBOOTPWR_SET_HWSTAT: urudev->rebootpwr_ctr = 100; - sm_set_hwstat(ssm, urudev->last_hwstat_rd & 0xf); + sm_set_hwstat(ssm, urudev->last_hwstat & 0xf); break; case REBOOTPWR_GET_HWSTAT: - sm_get_hwstat(ssm); + sm_read_reg(ssm, REG_HWSTAT); break; case REBOOTPWR_CHECK_HWSTAT: - if (urudev->last_hwstat_rd & 0x1) + urudev->last_hwstat = urudev->last_reg_rd; + if (urudev->last_hwstat & 0x1) fpi_ssm_mark_completed(ssm); else fpi_ssm_next_state(ssm); @@ -805,6 +783,7 @@ enum powerup_states { POWERUP_CHECK_HWSTAT, POWERUP_PAUSE, POWERUP_CHALLENGE_RESPONSE, + POWERUP_CHALLENGE_RESPONSE_SUCCESS, POWERUP_NUM_STATES, }; @@ -824,36 +803,26 @@ static void powerup_pause_cb(void *data) } } -static void powerup_challenge_response_cb(struct fp_img_dev *dev, int result, - void *data) -{ - struct fpi_ssm *ssm = data; - if (result) - fpi_ssm_mark_aborted(ssm, result); - else - fpi_ssm_jump_to_state(ssm, POWERUP_SET_HWSTAT); -} - static void powerup_run_state(struct fpi_ssm *ssm) { struct fp_img_dev *dev = ssm->priv; struct uru4k_dev *urudev = dev->priv; - int r; switch (ssm->cur_state) { case POWERUP_INIT: urudev->powerup_ctr = 100; - urudev->powerup_hwstat = urudev->last_hwstat_rd & 0xf; + urudev->powerup_hwstat = urudev->last_hwstat & 0xf; fpi_ssm_next_state(ssm); break; case POWERUP_SET_HWSTAT: sm_set_hwstat(ssm, urudev->powerup_hwstat); break; case POWERUP_GET_HWSTAT: - sm_get_hwstat(ssm); + sm_read_reg(ssm, REG_HWSTAT); break; case POWERUP_CHECK_HWSTAT: - if ((urudev->last_hwstat_rd & 0x80) == 0) + urudev->last_hwstat = urudev->last_reg_rd; + if ((urudev->last_reg_rd & 0x80) == 0) fpi_ssm_mark_completed(ssm); else fpi_ssm_next_state(ssm); @@ -863,9 +832,10 @@ static void powerup_run_state(struct fpi_ssm *ssm) fpi_ssm_mark_aborted(ssm, -ETIME); break; case POWERUP_CHALLENGE_RESPONSE: - r = do_challenge_response(dev, powerup_challenge_response_cb, ssm); - if (r < 0) - fpi_ssm_mark_aborted(ssm, r); + sm_do_challenge_response(ssm); + break; + case POWERUP_CHALLENGE_RESPONSE_SUCCESS: + fpi_ssm_jump_to_state(ssm, POWERUP_SET_HWSTAT); break; } } @@ -947,10 +917,11 @@ static void init_run_state(struct fpi_ssm *ssm) switch (ssm->cur_state) { case INIT_GET_HWSTAT: - sm_get_hwstat(ssm); + sm_read_reg(ssm, REG_HWSTAT); break; case INIT_CHECK_HWSTAT_REBOOT: - if ((urudev->last_hwstat_rd & 0x84) == 0x84) + urudev->last_hwstat = urudev->last_reg_rd; + if ((urudev->last_hwstat & 0x84) == 0x84) fpi_ssm_next_state(ssm); else fpi_ssm_jump_to_state(ssm, INIT_CHECK_HWSTAT_POWERDOWN); @@ -962,8 +933,8 @@ static void init_run_state(struct fpi_ssm *ssm) fpi_ssm_start_subsm(ssm, rebootsm); break; case INIT_CHECK_HWSTAT_POWERDOWN: - if ((urudev->last_hwstat_rd & 0x80) == 0) - sm_set_hwstat(ssm, urudev->last_hwstat_rd | 0x80); + if ((urudev->last_hwstat & 0x80) == 0) + sm_set_hwstat(ssm, urudev->last_hwstat | 0x80); else fpi_ssm_next_state(ssm); break; From a11ac7d8f8e1dc1f04b4721247ef24ca4cd8f7d6 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Wed, 19 Mar 2008 17:46:59 +0000 Subject: [PATCH 120/184] uru4000: search for encryption byte New DigitalPersona devices have a new firmware. We now use a search scheme to find the encryption byte, by examining known locations in the firmware until we find something that we recognise. --- libfprint/drivers/uru4000.c | 109 ++++++++++++++++++++++++------------ 1 file changed, 74 insertions(+), 35 deletions(-) diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index d5fcab77..e4825e98 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -51,7 +51,7 @@ enum { enum { REG_HWSTAT = 0x07, REG_MODE = 0x4e, - FIRMWARE_START = 0x100, + /* firmware starts at 0x100 */ REG_RESPONSE = 0x2000, REG_CHALLENGE = 0x2010, }; @@ -76,42 +76,46 @@ enum { static const struct uru4k_dev_profile { const char *name; - uint16_t firmware_start; - uint16_t fw_enc_offset; gboolean auth_cr; } uru4k_dev_info[] = { [MS_KBD] = { .name = "Microsoft Keyboard with Fingerprint Reader", - .fw_enc_offset = 0x411, .auth_cr = FALSE, }, [MS_INTELLIMOUSE] = { .name = "Microsoft Wireless IntelliMouse with Fingerprint Reader", - .fw_enc_offset = 0x411, .auth_cr = FALSE, }, [MS_STANDALONE] = { .name = "Microsoft Fingerprint Reader", - .fw_enc_offset = 0x411, .auth_cr = FALSE, }, [MS_STANDALONE_V2] = { .name = "Microsoft Fingerprint Reader v2", - .fw_enc_offset = 0x52e, .auth_cr = TRUE, }, [DP_URU4000] = { .name = "Digital Persona U.are.U 4000", - .fw_enc_offset = 0x693, .auth_cr = FALSE, }, [DP_URU4000B] = { .name = "Digital Persona U.are.U 4000B", - .fw_enc_offset = 0x411, .auth_cr = FALSE, }, }; +/* As we don't know the encryption scheme, we have to disable encryption + * by powering the device down and modifying the firmware. The location of + * the encryption control byte changes based on device revision. + * + * We use a search approach to find it: we look at the 3 bytes of data starting + * from these addresses, looking for a pattern "ff X7 41" (where X is dontcare) + * When we find a pattern we know that the encryption byte ius the X7 byte. + */ +static const uint16_t fwenc_offsets[] = { + 0x510, 0x62d, 0x792, +}; + typedef void (*irq_cb_fn)(struct fp_img_dev *dev, int status, uint16_t type, void *user_data); typedef void (*irqs_stopped_cb_fn)(struct fp_img_dev *dev); @@ -137,6 +141,9 @@ struct uru4k_dev { int scanpwr_irq_timeouts; struct fpi_timeout *scanpwr_irq_timeout; + int fwfixer_offset; + unsigned char fwfixer_value; + AES_KEY aeskey; }; @@ -644,47 +651,76 @@ static void sm_set_hwstat(struct fpi_ssm *ssm, unsigned char value) sm_write_reg(ssm, REG_HWSTAT, value); } -static void sm_fix_fw_read_cb(struct fp_img_dev *dev, int status, +/***** INITIALIZATION *****/ + +enum fwfixer_states { + FWFIXER_INIT, + FWFIXER_READ_NEXT, + FWFIXER_WRITE, + FWFIXER_NUM_STATES, +}; + +static void fwfixer_read_cb(struct fp_img_dev *dev, int status, unsigned char *data, void *user_data) { struct fpi_ssm *ssm = user_data; struct uru4k_dev *urudev = dev->priv; - unsigned char new; - unsigned char fwenc; - uint16_t enc_addr = FIRMWARE_START + urudev->profile->fw_enc_offset; - if (status != 0) { + if (status != 0) fpi_ssm_mark_aborted(ssm, status); - return; - } - fwenc = data[0]; - fp_dbg("firmware encryption byte at %x reads %02x", enc_addr, fwenc); - if (fwenc != 0x07 && fwenc != 0x17) - fp_dbg("strange encryption byte value, please report this"); - - new = fwenc & 0xef; - if (new == fwenc) { - fpi_ssm_next_state(ssm); + fp_dbg("data: %02x %02x %02x", data[0], data[1], data[2]); + if (data[0] == 0xff && (data[1] & 0x0f) == 0x07 && data[2] == 0x41) { + fp_dbg("using offset %x", fwenc_offsets[urudev->fwfixer_offset]); + urudev->fwfixer_value = data[1]; + fpi_ssm_jump_to_state(ssm, FWFIXER_WRITE); } else { - fp_dbg("fixed encryption byte to %02x", new); - sm_write_reg(ssm, enc_addr, new); + fpi_ssm_jump_to_state(ssm, FWFIXER_READ_NEXT); } } -static void sm_fix_firmware(struct fpi_ssm *ssm) +static void fwfixer_run_state(struct fpi_ssm *ssm) { struct fp_img_dev *dev = ssm->priv; struct uru4k_dev *urudev = dev->priv; - uint16_t enc_addr = FIRMWARE_START + urudev->profile->fw_enc_offset; int r; - r = read_reg(dev, enc_addr, sm_fix_fw_read_cb, ssm); - if (r < 0) - fpi_ssm_mark_aborted(ssm, r); -} + switch (ssm->cur_state) { + case FWFIXER_INIT: + urudev->fwfixer_offset = -1; + fpi_ssm_next_state(ssm); + break; + case FWFIXER_READ_NEXT: ; + int offset = ++urudev->fwfixer_offset; + uint16_t try_addr; -/***** INITIALIZATION *****/ + if (offset == G_N_ELEMENTS(fwenc_offsets)) { + fp_err("could not find encryption byte"); + fpi_ssm_mark_aborted(ssm, -ENODEV); + return; + } + + try_addr = fwenc_offsets[offset]; + fp_dbg("looking for encryption byte at %x", try_addr); + + r = read_regs(dev, try_addr, 3, fwfixer_read_cb, ssm); + if (r < 0) + fpi_ssm_mark_aborted(ssm, r); + break; + case FWFIXER_WRITE: ; + uint16_t enc_addr = fwenc_offsets[urudev->fwfixer_offset] + 1; + unsigned char cur = urudev->fwfixer_value; + unsigned char new = cur & 0xef; + if (new == cur) { + fp_dbg("encryption is already disabled"); + fpi_ssm_next_state(ssm); + } else { + fp_dbg("fixing encryption byte at %x to %02x", enc_addr, new); + sm_write_reg(ssm, enc_addr, new); + } + break; + } +} /* After closing an app and setting hwstat to 0x80, my ms keyboard gets in a * confused state and returns hwstat 0x85. On next app run, we don't get the @@ -938,8 +974,11 @@ static void init_run_state(struct fpi_ssm *ssm) else fpi_ssm_next_state(ssm); break; - case INIT_FIX_FIRMWARE: - sm_fix_firmware(ssm); + case INIT_FIX_FIRMWARE: ; + struct fpi_ssm *fwsm = fpi_ssm_new(dev->dev, fwfixer_run_state, + FWFIXER_NUM_STATES); + fwsm->priv = dev; + fpi_ssm_start_subsm(ssm, fwsm); break; case INIT_POWERUP: ; struct fpi_ssm *powerupsm = fpi_ssm_new(dev->dev, powerup_run_state, From 617ca8cd1567091263f77fb37d422290c920c72e Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Wed, 19 Mar 2008 23:28:44 +0000 Subject: [PATCH 121/184] fix imaging action state for repeated enroll attempts Enroll attempts may retry in some situations, so we need to reset the state to accept more scans. --- libfprint/imgdev.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index 494d6e22..8bddd5ce 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -198,6 +198,11 @@ void fpi_imgdev_report_finger_status(struct fp_img_dev *imgdev, case IMG_ACTION_ENROLL: fp_dbg("reporting enroll result"); fpi_drvcb_enroll_stage_completed(imgdev->dev, r, data, img); + if (r > 0 && r != FP_ENROLL_COMPLETE && r != FP_ENROLL_FAIL) { + imgdev->action_result = 0; + imgdev->action_state = IMG_ACQUIRE_STATE_AWAIT_FINGER_ON; + dev_change_state(imgdev, IMG_ACQUIRE_STATE_AWAIT_FINGER_ON); + } break; case IMG_ACTION_VERIFY: fpi_drvcb_report_verify_result(imgdev->dev, r, img); From c9ff2c5541a522224137beb1fd4ecef453ba8955 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Wed, 19 Mar 2008 23:29:30 +0000 Subject: [PATCH 122/184] Add Veridicom 5th Sense driver Based on bus traffic analysis of the windows driver. This device is working well, but finger presence detection is not yet implemented. --- libfprint/Makefile.am | 3 +- libfprint/core.c | 1 + libfprint/drivers/vcom5s.c | 326 +++++++++++++++++++++++++++++++++++++ libfprint/fp_internal.h | 1 + 4 files changed, 330 insertions(+), 1 deletion(-) create mode 100644 libfprint/drivers/vcom5s.c diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index b4e022ce..8ed5732e 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -7,8 +7,9 @@ AES1610_SRC = drivers/aes1610.c AES2501_SRC = drivers/aes2501.c drivers/aes2501.h AES4000_SRC = drivers/aes4000.c FDU2000_SRC = drivers/fdu2000.c +VCOM5S_SRC = drivers/vcom5s.c -DRIVER_SRC = $(UPEKTS_SRC) $(AES4000_SRC) $(AES2501_SRC) $(URU4000_SRC) +DRIVER_SRC = $(UPEKTS_SRC) $(AES4000_SRC) $(AES2501_SRC) $(URU4000_SRC) $(VCOM5S_SRC) #DRIVER_SRC = $(AES1610_SRC) $(UPEKTC_SRC) $(FDU2000_SRC) NBIS_SRC = \ diff --git a/libfprint/core.c b/libfprint/core.c index 0be45698..01af59b9 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -333,6 +333,7 @@ static struct fp_img_driver * const img_drivers[] = { &aes4000_driver, &aes2501_driver, &uru4000_driver, + &vcom5s_driver, /* &aes1610_driver, &upektc_driver, &fdu2000_driver, */ diff --git a/libfprint/drivers/vcom5s.c b/libfprint/drivers/vcom5s.c new file mode 100644 index 00000000..afe2cc91 --- /dev/null +++ b/libfprint/drivers/vcom5s.c @@ -0,0 +1,326 @@ +/* + * Veridicom 5thSense driver for libfprint + * Copyright (C) 2008 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#define FP_COMPONENT "vcom5s" + +/* TODO: + * finger presence detection + * calibration? + */ + +#include +#include + +#include +#include + +#include + +#define CTRL_IN 0xc0 +#define CTRL_OUT 0x40 +#define CTRL_TIMEOUT 1000 +#define EP_IN (1 | LIBUSB_ENDPOINT_IN) + +#define IMG_WIDTH 300 +#define IMG_HEIGHT 288 +#define ROWS_PER_RQ 12 +#define NR_REQS (IMG_HEIGHT / ROWS_PER_RQ) +#define RQ_SIZE (IMG_WIDTH * ROWS_PER_RQ) +#define IMG_SIZE (IMG_WIDTH * IMG_HEIGHT) + +struct v5s_dev { + int capture_iteration; + struct fp_img *capture_img; + gboolean loop_running; + gboolean deactivating; +}; + +/***** REGISTER I/O *****/ + +static void sm_write_reg_cb(struct libusb_transfer *transfer) +{ + struct fpi_ssm *ssm = transfer->user_data; + + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) + fpi_ssm_mark_aborted(ssm, -EIO); + else + fpi_ssm_next_state(ssm); + + g_free(transfer->buffer); + libusb_free_transfer(transfer); +} + +static void sm_write_reg(struct fpi_ssm *ssm, unsigned char reg, + unsigned char value) +{ + struct fp_img_dev *dev = ssm->priv; + struct libusb_transfer *transfer = libusb_alloc_transfer(); + unsigned char *data; + int r; + + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + return; + } + + fp_dbg("set %02x=%02x", reg, value); + data = g_malloc(LIBUSB_CONTROL_SETUP_SIZE); + libusb_fill_control_setup(data, CTRL_OUT, reg, value, 0, 0); + libusb_fill_control_transfer(transfer, dev->udev, data, sm_write_reg_cb, + ssm, CTRL_TIMEOUT); + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(data); + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, r); + } +} + +static void sm_exec_cmd_cb(struct libusb_transfer *transfer) +{ + struct fpi_ssm *ssm = transfer->user_data; + + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) + fpi_ssm_mark_aborted(ssm, -EIO); + else + fpi_ssm_next_state(ssm); + + g_free(transfer->buffer); + libusb_free_transfer(transfer); +} + +static void sm_exec_cmd(struct fpi_ssm *ssm, unsigned char cmd, + unsigned char param) +{ + struct fp_img_dev *dev = ssm->priv; + struct libusb_transfer *transfer = libusb_alloc_transfer(); + unsigned char *data; + int r; + + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + return; + } + + fp_dbg("cmd %02x param %02x", cmd, param); + data = g_malloc(LIBUSB_CONTROL_SETUP_SIZE); + libusb_fill_control_setup(data, CTRL_IN, cmd, param, 0, 0); + libusb_fill_control_transfer(transfer, dev->udev, data, sm_exec_cmd_cb, + ssm, CTRL_TIMEOUT); + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(data); + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, r); + } +} + +/***** IMAGE ACQUISITION *****/ + +static void capture_iterate(struct fpi_ssm *ssm); + +static void capture_cb(struct libusb_transfer *transfer) +{ + struct fpi_ssm *ssm = transfer->user_data; + struct fp_img_dev *dev = ssm->priv; + struct v5s_dev *vdev = dev->priv; + + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { + fpi_ssm_mark_aborted(ssm, -EIO); + goto out; + } + + if (++vdev->capture_iteration == NR_REQS) { + struct fp_img *img = vdev->capture_img; + /* must clear this early, otherwise the call chain takes us into + * loopsm_complete where we would free it, when in fact we are + * supposed to be handing off this image */ + vdev->capture_img = NULL; + + fpi_imgdev_report_finger_status(dev, TRUE); + fpi_imgdev_image_captured(dev, img); + fpi_imgdev_report_finger_status(dev, FALSE); + fpi_ssm_next_state(ssm); + } else { + capture_iterate(ssm); + } + +out: + libusb_free_transfer(transfer); +} + +static void capture_iterate(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct v5s_dev *vdev = dev->priv; + int iteration = vdev->capture_iteration; + struct libusb_transfer *transfer = libusb_alloc_transfer(); + int r; + + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + return; + } + + libusb_fill_bulk_transfer(transfer, dev->udev, EP_IN, + vdev->capture_img->data + (RQ_SIZE * iteration), RQ_SIZE, + capture_cb, ssm, CTRL_TIMEOUT); + transfer->flags = LIBUSB_TRANSFER_SHORT_NOT_OK; + r = libusb_submit_transfer(transfer); + if (r < 0) { + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, r); + } +} + + +static void sm_do_capture(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct v5s_dev *vdev = dev->priv; + + fp_dbg(""); + vdev->capture_img = fpi_img_new_for_imgdev(dev); + vdev->capture_iteration = 0; + capture_iterate(ssm); +} + +/***** CAPTURE LOOP *****/ + +enum loop_states { + LOOP_WR02, + LOOP_WR03, + LOOP_CMDC1, + LOOP_CAPTURE, + LOOP_CAPTURE_DONE, + LOOP_NUM_STATES, +}; + +static void loop_run_state(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct v5s_dev *vdev = dev->priv; + + switch (ssm->cur_state) { + case LOOP_WR02: + sm_write_reg(ssm, 0x02, 0x02); + break; + case LOOP_WR03: + sm_write_reg(ssm, 0x03, 0x29); + break; + case LOOP_CMDC1: + if (vdev->deactivating) { + fp_dbg("deactivating, marking completed"); + fpi_ssm_mark_completed(ssm); + } else + sm_exec_cmd(ssm, 0xc1, 0x00); + break; + case LOOP_CAPTURE: + sm_do_capture(ssm); + break; + case LOOP_CAPTURE_DONE: + fpi_ssm_jump_to_state(ssm, LOOP_CMDC1); + break; + } +} + +static void loopsm_complete(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct v5s_dev *vdev = dev->priv; + int r = ssm->error; + + fpi_ssm_free(ssm); + fp_img_free(vdev->capture_img); + vdev->capture_img = NULL; + vdev->loop_running = FALSE; + + if (r) + fpi_imgdev_session_error(dev, r); + + if (vdev->deactivating) + fpi_imgdev_deactivate_complete(dev); +} + +static int dev_activate(struct fp_img_dev *dev, enum fp_imgdev_state state) +{ + struct v5s_dev *vdev = dev->priv; + struct fpi_ssm *ssm = fpi_ssm_new(dev->dev, loop_run_state, + LOOP_NUM_STATES); + ssm->priv = dev; + vdev->deactivating = FALSE; + fpi_ssm_start(ssm, loopsm_complete); + vdev->loop_running = TRUE; + fpi_imgdev_activate_complete(dev, 0); + return 0; +} + +static void dev_deactivate(struct fp_img_dev *dev) +{ + struct v5s_dev *vdev = dev->priv; + if (vdev->loop_running) + vdev->deactivating = TRUE; + else + fpi_imgdev_deactivate_complete(dev); +} + +static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) +{ + int r; + dev->priv = g_malloc0(sizeof(struct v5s_dev)); + + r = libusb_claim_interface(dev->udev, 0); + if (r < 0) + fp_err("could not claim interface 0"); + + if (r == 0) + fpi_imgdev_open_complete(dev, 0); + + return r; +} + +static void dev_deinit(struct fp_img_dev *dev) +{ + g_free(dev->priv); + libusb_release_interface(dev->udev, 0); + fpi_imgdev_close_complete(dev); +} + +static const struct usb_id id_table[] = { + { .vendor = 0x061a, .product = 0x0110 }, + { 0, 0, 0, }, +}; + +struct fp_img_driver vcom5s_driver = { + .driver = { + .id = 8, + .name = FP_COMPONENT, + .full_name = "Veridicom 5thSense", + .id_table = id_table, + }, + .flags = 0, + .img_height = IMG_HEIGHT, + .img_width = IMG_WIDTH, + + .open = dev_init, + .close = dev_deinit, + .activate = dev_activate, + .deactivate = dev_deactivate, +}; + diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 5b1c289c..7eb87f1e 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -240,6 +240,7 @@ extern struct fp_img_driver aes1610_driver; extern struct fp_img_driver aes2501_driver; extern struct fp_img_driver aes4000_driver; extern struct fp_img_driver fdu2000_driver; +extern struct fp_img_driver vcom5s_driver; extern GSList *opened_devices; From d12ad6dea905758c76558ee66a48bb0fd3c485f3 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Thu, 20 Mar 2008 13:19:44 +0000 Subject: [PATCH 123/184] Update version number I'm about to do another 0.0 release, so change the tag in this branch to avoid confusion --- configure.ac | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/configure.ac b/configure.ac index 67322e07..386333b0 100644 --- a/configure.ac +++ b/configure.ac @@ -1,4 +1,4 @@ -AC_INIT([libfprint], [0.0.5]) +AC_INIT([libfprint], [0.1.0-pre]) AM_INIT_AUTOMAKE AC_CONFIG_SRCDIR([libfprint/core.c]) AM_CONFIG_HEADER([config.h]) From d6d4e56ccffc8e0b704f4778058f677ad17c2439 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Thu, 20 Mar 2008 13:34:48 +0000 Subject: [PATCH 124/184] uru4000: add fwenc search location for UareU4000 ticket #14 includes a device with a different firmware, this should get it up and running. --- libfprint/drivers/uru4000.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index e4825e98..bcaa0256 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -113,7 +113,7 @@ static const struct uru4k_dev_profile { * When we find a pattern we know that the encryption byte ius the X7 byte. */ static const uint16_t fwenc_offsets[] = { - 0x510, 0x62d, 0x792, + 0x510, 0x62d, 0x792, 0x7f4, }; typedef void (*irq_cb_fn)(struct fp_img_dev *dev, int status, uint16_t type, From 981f2eb0aa133669523938ac17f095d82777fd33 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Thu, 20 Mar 2008 15:31:03 +0000 Subject: [PATCH 125/184] vcom5s: implement finger detection Uses thresholding of average pixel intensity of the center region of the image. Also document guessed meanings of magic numbers for registers. --- libfprint/drivers/vcom5s.c | 85 ++++++++++++++++++++++++++++++++------ 1 file changed, 72 insertions(+), 13 deletions(-) diff --git a/libfprint/drivers/vcom5s.c b/libfprint/drivers/vcom5s.c index afe2cc91..dc1958ad 100644 --- a/libfprint/drivers/vcom5s.c +++ b/libfprint/drivers/vcom5s.c @@ -20,8 +20,10 @@ #define FP_COMPONENT "vcom5s" /* TODO: - * finger presence detection * calibration? + * image size: windows gets 300x300 through vpas enrollment util? + * (probably just increase bulk read size?) + * powerdown? does windows do anything special on exit? */ #include @@ -51,6 +53,29 @@ struct v5s_dev { gboolean deactivating; }; +enum v5s_regs { + /* when using gain 0x29: + * a value of 0x00 produces mostly-black image + * 0x09 destroys ridges (too white) + * 0x01 or 0x02 seem good values */ + REG_CONTRAST = 0x02, + + /* when using contrast 0x01: + * a value of 0x00 will produce an all-black image. + * 0x29 produces a good contrast image: ridges quite dark, but some + * light grey noise as background + * 0x46 produces all-white image with grey ridges (not very dark) */ + REG_GAIN = 0x03, +}; + +enum v5s_cmd { + /* scan one row. has parameter, at a guess this is which row to scan? */ + CMD_SCAN_ONE_ROW = 0xc0, + + /* scan whole image */ + CMD_SCAN = 0xc1, +}; + /***** REGISTER I/O *****/ static void sm_write_reg_cb(struct libusb_transfer *transfer) @@ -131,6 +156,41 @@ static void sm_exec_cmd(struct fpi_ssm *ssm, unsigned char cmd, } } +/***** FINGER DETECTION *****/ + +/* We take 64x64 pixels at the center of the image, determine the average + * pixel intensity, and threshold it. */ +#define DETBOX_ROW_START 111 +#define DETBOX_COL_START 117 +#define DETBOX_ROWS 64 +#define DETBOX_COLS 64 +#define DETBOX_ROW_END (DETBOX_ROW_START + DETBOX_ROWS) +#define DETBOX_COL_END (DETBOX_COL_START + DETBOX_COLS) +#define FINGER_PRESENCE_THRESHOLD 100 + +static gboolean finger_is_present(unsigned char *data) +{ + int row; + uint16_t imgavg = 0; + + for (row = DETBOX_ROW_START; row < DETBOX_ROW_END; row++) { + unsigned char *rowdata = data + (row * IMG_WIDTH); + uint16_t rowavg = 0; + int col; + + for (col = DETBOX_COL_START; col < DETBOX_COL_END; col++) + rowavg += rowdata[col]; + rowavg /= DETBOX_COLS; + imgavg += rowavg; + } + imgavg /= DETBOX_ROWS; + fp_dbg("img avg %d", imgavg); + + return (imgavg <= FINGER_PRESENCE_THRESHOLD); +} + + + /***** IMAGE ACQUISITION *****/ static void capture_iterate(struct fpi_ssm *ssm); @@ -153,9 +213,8 @@ static void capture_cb(struct libusb_transfer *transfer) * supposed to be handing off this image */ vdev->capture_img = NULL; - fpi_imgdev_report_finger_status(dev, TRUE); + fpi_imgdev_report_finger_status(dev, finger_is_present(img->data)); fpi_imgdev_image_captured(dev, img); - fpi_imgdev_report_finger_status(dev, FALSE); fpi_ssm_next_state(ssm); } else { capture_iterate(ssm); @@ -204,9 +263,9 @@ static void sm_do_capture(struct fpi_ssm *ssm) /***** CAPTURE LOOP *****/ enum loop_states { - LOOP_WR02, - LOOP_WR03, - LOOP_CMDC1, + LOOP_SET_CONTRAST, + LOOP_SET_GAIN, + LOOP_CMD_SCAN, LOOP_CAPTURE, LOOP_CAPTURE_DONE, LOOP_NUM_STATES, @@ -218,24 +277,24 @@ static void loop_run_state(struct fpi_ssm *ssm) struct v5s_dev *vdev = dev->priv; switch (ssm->cur_state) { - case LOOP_WR02: - sm_write_reg(ssm, 0x02, 0x02); + case LOOP_SET_CONTRAST: + sm_write_reg(ssm, REG_CONTRAST, 0x01); break; - case LOOP_WR03: - sm_write_reg(ssm, 0x03, 0x29); + case LOOP_SET_GAIN: + sm_write_reg(ssm, REG_GAIN, 0x29); break; - case LOOP_CMDC1: + case LOOP_CMD_SCAN: if (vdev->deactivating) { fp_dbg("deactivating, marking completed"); fpi_ssm_mark_completed(ssm); } else - sm_exec_cmd(ssm, 0xc1, 0x00); + sm_exec_cmd(ssm, CMD_SCAN, 0x00); break; case LOOP_CAPTURE: sm_do_capture(ssm); break; case LOOP_CAPTURE_DONE: - fpi_ssm_jump_to_state(ssm, LOOP_CMDC1); + fpi_ssm_jump_to_state(ssm, LOOP_CMD_SCAN); break; } } From 1ab52617c7d857acb01368938b713595af078b4e Mon Sep 17 00:00:00 2001 From: Azzie Date: Sat, 29 Mar 2008 18:11:17 +0000 Subject: [PATCH 126/184] Update for latest libusb constant names --- libfprint/drivers/upekts.c | 2 +- libfprint/drivers/uru4000.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index e0e7d1a2..859469f8 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -711,7 +711,7 @@ static void initsm_run_state(struct fpi_ssm *ssm) data = g_malloc(LIBUSB_CONTROL_SETUP_SIZE + 1); libusb_fill_control_setup(data, - LIBUSB_TYPE_VENDOR | LIBUSB_RECIP_DEVICE, 0x0c, 0x100, 0x0400, 1); + LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE, 0x0c, 0x100, 0x0400, 1); libusb_fill_control_transfer(transfer, ssm->dev->udev, data, ctrl400_cb, ssm, TIMEOUT); diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index bcaa0256..c508cc63 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -31,8 +31,8 @@ #define EP_INTR (1 | LIBUSB_ENDPOINT_IN) #define EP_DATA (2 | LIBUSB_ENDPOINT_IN) #define USB_RQ 0x04 -#define CTRL_IN (LIBUSB_TYPE_VENDOR | LIBUSB_ENDPOINT_IN) -#define CTRL_OUT (LIBUSB_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT) +#define CTRL_IN (LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_IN) +#define CTRL_OUT (LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT) #define CTRL_TIMEOUT 5000 #define BULK_TIMEOUT 5000 #define DATABLK_RQLEN 0x1b340 From 40e7ac195a4be0e6951b7a8b0388bdbc88cfc8d7 Mon Sep 17 00:00:00 2001 From: Vasily Khoruzhick Date: Sun, 6 Apr 2008 21:56:33 +0300 Subject: [PATCH 127/184] Adapting to latest libusb Signed-off-by: Vasily Khoruzhick --- libfprint/aeslib.c | 2 +- libfprint/drivers/aes2501.c | 8 ++++---- libfprint/drivers/aes4000.c | 2 +- libfprint/drivers/upekts.c | 8 ++++---- libfprint/drivers/uru4000.c | 8 ++++---- libfprint/drivers/vcom5s.c | 6 +++--- libfprint/poll.c | 2 +- 7 files changed, 18 insertions(+), 18 deletions(-) diff --git a/libfprint/aeslib.c b/libfprint/aeslib.c index 579cd127..da9be012 100644 --- a/libfprint/aeslib.c +++ b/libfprint/aeslib.c @@ -70,7 +70,7 @@ static int do_write_regv(struct write_regv_data *wdata, int upper_bound) unsigned char *data = g_malloc(alloc_size); unsigned int i; size_t data_offset = 0; - struct libusb_transfer *transfer = libusb_alloc_transfer(); + struct libusb_transfer *transfer = libusb_alloc_transfer(0); int r; if (!transfer) { diff --git a/libfprint/drivers/aes2501.c b/libfprint/drivers/aes2501.c index 3e3bae60..e6f3b866 100644 --- a/libfprint/drivers/aes2501.c +++ b/libfprint/drivers/aes2501.c @@ -111,7 +111,7 @@ static void read_regs_rq_cb(struct fp_img_dev *dev, int result, void *user_data) if (result != 0) goto err; - transfer = libusb_alloc_transfer(); + transfer = libusb_alloc_transfer(0); if (!transfer) { result = -ENOMEM; goto err; @@ -203,7 +203,7 @@ static void generic_ignore_data_cb(struct libusb_transfer *transfer) * away, then increment the SSM */ static void generic_read_ignore_data(struct fpi_ssm *ssm, size_t bytes) { - struct libusb_transfer *transfer = libusb_alloc_transfer(); + struct libusb_transfer *transfer = libusb_alloc_transfer(0); unsigned char *data; int r; @@ -434,7 +434,7 @@ static void finger_det_reqs_cb(struct fp_img_dev *dev, int result, return; } - transfer = libusb_alloc_transfer(); + transfer = libusb_alloc_transfer(0); if (!transfer) { fpi_imgdev_session_error(dev, -ENOMEM); return; @@ -630,7 +630,7 @@ static void capture_run_state(struct fpi_ssm *ssm) generic_write_regv_cb, ssm); break; case CAPTURE_READ_STRIP: ; - struct libusb_transfer *transfer = libusb_alloc_transfer(); + struct libusb_transfer *transfer = libusb_alloc_transfer(0); unsigned char *data; if (!transfer) { diff --git a/libfprint/drivers/aes4000.c b/libfprint/drivers/aes4000.c index 8c2ec0ea..51613ba1 100644 --- a/libfprint/drivers/aes4000.c +++ b/libfprint/drivers/aes4000.c @@ -164,7 +164,7 @@ static void do_capture(struct fp_img_dev *dev) unsigned char *data; int r; - aesdev->img_trf = libusb_alloc_transfer(); + aesdev->img_trf = libusb_alloc_transfer(0); if (!aesdev->img_trf) { fpi_imgdev_session_error(dev, -EIO); return; diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index 859469f8..df648301 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -137,7 +137,7 @@ static struct libusb_transfer *alloc_send_cmd_transfer(struct fp_dev *dev, unsigned char seq_a, unsigned char seq_b, const unsigned char *data, uint16_t len, libusb_transfer_cb_fn callback, void *user_data) { - struct libusb_transfer *transfer = libusb_alloc_transfer(); + struct libusb_transfer *transfer = libusb_alloc_transfer(0); uint16_t crc; /* 9 bytes extra for: 4 byte 'Ciao', 1 byte A, 1 byte B | lenHI, @@ -410,7 +410,7 @@ static void read_msg_cb(struct libusb_transfer *transfer) * to read the remainder. This is handled below. */ if (len > MAX_DATA_IN_READ_BUF) { int needed = len - MAX_DATA_IN_READ_BUF; - struct libusb_transfer *etransfer = libusb_alloc_transfer(); + struct libusb_transfer *etransfer = libusb_alloc_transfer(0); int r; if (!transfer) @@ -450,7 +450,7 @@ out: static int __read_msg_async(struct read_msg_data *udata) { unsigned char *buf = g_malloc(MSG_READ_BUF_SIZE); - struct libusb_transfer *transfer = libusb_alloc_transfer(); + struct libusb_transfer *transfer = libusb_alloc_transfer(0); int r; if (!transfer) { @@ -703,7 +703,7 @@ static void initsm_run_state(struct fpi_ssm *ssm) case WRITE_CTRL400: ; unsigned char *data; - transfer = libusb_alloc_transfer(); + transfer = libusb_alloc_transfer(0); if (!transfer) { fpi_ssm_mark_aborted(ssm, -ENOMEM); break; diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index c508cc63..906b3072 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -187,7 +187,7 @@ static int write_regs(struct fp_img_dev *dev, uint16_t first_reg, void *user_data) { struct write_regs_data *wrdata; - struct libusb_transfer *transfer = libusb_alloc_transfer(); + struct libusb_transfer *transfer = libusb_alloc_transfer(0); unsigned char *data; int r; @@ -254,7 +254,7 @@ static int read_regs(struct fp_img_dev *dev, uint16_t first_reg, uint16_t num_regs, read_regs_cb_fn callback, void *user_data) { struct read_regs_data *rrdata; - struct libusb_transfer *transfer = libusb_alloc_transfer(); + struct libusb_transfer *transfer = libusb_alloc_transfer(0); unsigned char *data; int r; @@ -423,7 +423,7 @@ out: static int start_irq_handler(struct fp_img_dev *dev) { struct uru4k_dev *urudev = dev->priv; - struct libusb_transfer *transfer = libusb_alloc_transfer(); + struct libusb_transfer *transfer = libusb_alloc_transfer(0); unsigned char *data; int r; @@ -507,7 +507,7 @@ out: static int start_imaging_loop(struct fp_img_dev *dev) { struct uru4k_dev *urudev = dev->priv; - struct libusb_transfer *transfer = libusb_alloc_transfer(); + struct libusb_transfer *transfer = libusb_alloc_transfer(0); unsigned char *data; int r; diff --git a/libfprint/drivers/vcom5s.c b/libfprint/drivers/vcom5s.c index dc1958ad..c02873b6 100644 --- a/libfprint/drivers/vcom5s.c +++ b/libfprint/drivers/vcom5s.c @@ -95,7 +95,7 @@ static void sm_write_reg(struct fpi_ssm *ssm, unsigned char reg, unsigned char value) { struct fp_img_dev *dev = ssm->priv; - struct libusb_transfer *transfer = libusb_alloc_transfer(); + struct libusb_transfer *transfer = libusb_alloc_transfer(0); unsigned char *data; int r; @@ -134,7 +134,7 @@ static void sm_exec_cmd(struct fpi_ssm *ssm, unsigned char cmd, unsigned char param) { struct fp_img_dev *dev = ssm->priv; - struct libusb_transfer *transfer = libusb_alloc_transfer(); + struct libusb_transfer *transfer = libusb_alloc_transfer(0); unsigned char *data; int r; @@ -229,7 +229,7 @@ static void capture_iterate(struct fpi_ssm *ssm) struct fp_img_dev *dev = ssm->priv; struct v5s_dev *vdev = dev->priv; int iteration = vdev->capture_iteration; - struct libusb_transfer *transfer = libusb_alloc_transfer(); + struct libusb_transfer *transfer = libusb_alloc_transfer(0); int r; if (!transfer) { diff --git a/libfprint/poll.c b/libfprint/poll.c index dc95c173..9e5523e7 100644 --- a/libfprint/poll.c +++ b/libfprint/poll.c @@ -228,7 +228,7 @@ API_EXPORTED int fp_handle_events_timeout(struct timeval *timeout) select_timeout = *timeout; } - r = libusb_poll_timeout(&select_timeout); + r = libusb_handle_events_timeout(&select_timeout); *timeout = select_timeout; if (r < 0) return r; From 870ddfb9054d00341ebf87d1e39153feaa96cbc3 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sun, 6 Apr 2008 23:55:41 +0100 Subject: [PATCH 128/184] some libusb pointers are now const --- libfprint/core.c | 3 ++- libfprint/drivers/uru4000.c | 10 +++++----- libfprint/poll.c | 4 ++-- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/libfprint/core.c b/libfprint/core.c index 01af59b9..f0c26298 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -357,7 +357,8 @@ static struct fp_driver *find_supporting_driver(libusb_device *udev, const struct usb_id **usb_id) { GSList *elem = registered_drivers; - struct libusb_device_descriptor *dsc = libusb_get_device_descriptor(udev); + const struct libusb_device_descriptor *dsc = + libusb_get_device_descriptor(udev); do { struct fp_driver *drv = elem->data; diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index 906b3072..f2a0fdf3 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -1102,10 +1102,10 @@ static void dev_deactivate(struct fp_img_dev *dev) static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) { - struct libusb_config_descriptor *config; - struct libusb_interface *iface = NULL; - struct libusb_interface_descriptor *iface_desc; - struct libusb_endpoint_descriptor *ep; + const struct libusb_config_descriptor *config; + const struct libusb_interface *iface = NULL; + const struct libusb_interface_descriptor *iface_desc; + const struct libusb_endpoint_descriptor *ep; struct uru4k_dev *urudev; int i; int r; @@ -1113,7 +1113,7 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) /* Find fingerprint interface */ config = libusb_get_config_descriptor(libusb_get_device(dev->udev)); for (i = 0; i < config->bNumInterfaces; i++) { - struct libusb_interface *cur_iface = &config->interface[i]; + const struct libusb_interface *cur_iface = &config->interface[i]; if (cur_iface->num_altsetting < 1) continue; diff --git a/libfprint/poll.c b/libfprint/poll.c index 9e5523e7..1c357419 100644 --- a/libfprint/poll.c +++ b/libfprint/poll.c @@ -291,8 +291,8 @@ API_EXPORTED int fp_get_next_timeout(struct timeval *tv) */ API_EXPORTED size_t fp_get_pollfds(struct fp_pollfd **pollfds) { - struct libusb_pollfd **usbfds; - struct libusb_pollfd *usbfd; + const struct libusb_pollfd **usbfds; + const struct libusb_pollfd *usbfd; struct fp_pollfd *ret; size_t cnt = 0; size_t i = 0; From ebcabc1aded5043e0f5abf08e97ae14cc9ff0a60 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 12 Apr 2008 16:58:49 +0100 Subject: [PATCH 129/184] uru4000: avoid cancelling a completed transfer --- libfprint/drivers/uru4000.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index f2a0fdf3..77491f48 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -467,9 +467,13 @@ static void image_cb(struct libusb_transfer *transfer) struct fp_img *img; int r = 0; + /* remove the global reference early: otherwise we may report results, + * leading to immediate deactivation of driver, which will potentially + * try to cancel an already-completed transfer */ + urudev->img_transfer = NULL; + if (transfer->status == LIBUSB_TRANSFER_CANCELLED) { fp_dbg("cancelled"); - urudev->img_transfer = NULL; g_free(transfer->buffer); libusb_free_transfer(transfer); return; From f540ae5d5bc6ef6af3016759f6c9ca26056bec7c Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 19 Apr 2008 23:09:53 +0100 Subject: [PATCH 130/184] Fix memory leak in fpi_print_data_new() Pointed out by Krystian (yoB) on FS#24 --- libfprint/data.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/libfprint/data.c b/libfprint/data.c index 61dc8059..861c5f34 100644 --- a/libfprint/data.c +++ b/libfprint/data.c @@ -107,8 +107,6 @@ static struct fp_print_data *print_data_new(uint16_t driver_id, struct fp_print_data *fpi_print_data_new(struct fp_dev *dev, size_t length) { - struct fp_print_data *data = g_malloc(sizeof(*data) + length); - memset(data, 0, sizeof(*data)); return print_data_new(dev->drv->id, dev->devtype, fpi_driver_get_data_type(dev->drv), length); } From 76cbf212239e5561a11877a2a3a486844107ec2e Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Fri, 2 May 2008 11:55:50 +0100 Subject: [PATCH 131/184] uru4000: Add support for Digital Persona U.are.U Fingerprint Keyboard Reported by Tudor Panaitescu --- libfprint/drivers/uru4000.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index 77491f48..3169c924 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -1200,6 +1200,9 @@ static const struct usb_id id_table[] = { /* dp uru4000 (standalone) */ { .vendor = 0x05ba, .product = 0x0007, .driver_data = DP_URU4000 }, + /* dp uru4000 (keyboard) */ + { .vendor = 0x05ba, .product = 0x0008, .driver_data = DP_URU4000 }, + /* dp uru4000b (standalone) */ { .vendor = 0x05ba, .product = 0x000a, .driver_data = DP_URU4000B }, From 63421e3fd61d0779a5cc4c11a59ea7318cdb8f72 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Wed, 7 May 2008 23:46:06 +0100 Subject: [PATCH 132/184] uru4000: fix compile against latest libusb --- libfprint/drivers/uru4000.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index 3169c924..dc6da212 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -1145,16 +1145,16 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) ep = &iface_desc->endpoint[0]; if (ep->bEndpointAddress != EP_INTR - || (ep->bmAttributes & LIBUSB_ENDPOINT_TYPE_MASK) != - LIBUSB_ENDPOINT_TYPE_INTERRUPT) { + || (ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) != + LIBUSB_TRANSFER_TYPE_INTERRUPT) { fp_err("unrecognised interrupt endpoint"); return -ENODEV; } ep = &iface_desc->endpoint[1]; if (ep->bEndpointAddress != EP_DATA - || (ep->bmAttributes & LIBUSB_ENDPOINT_TYPE_MASK) != - LIBUSB_ENDPOINT_TYPE_BULK) { + || (ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) != + LIBUSB_TRANSFER_TYPE_BULK) { fp_err("unrecognised bulk endpoint"); return -ENODEV; } From aa7c8ae81eb3eae1afbbae982a6617db8e79e29d Mon Sep 17 00:00:00 2001 From: Vasily Khoruzhick Date: Tue, 13 May 2008 01:24:05 +0300 Subject: [PATCH 133/184] Adapting to latest libusb-1.0 changes Signed-off-by: Vasily Khoruzhick [dsd: remove config const qualifier and add freeing of config] --- libfprint/core.c | 12 +++++++++--- libfprint/drivers/uru4000.c | 27 +++++++++++++++++++-------- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/libfprint/core.c b/libfprint/core.c index f0c26298..2b57ca75 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -356,16 +356,22 @@ static void register_drivers(void) static struct fp_driver *find_supporting_driver(libusb_device *udev, const struct usb_id **usb_id) { + int ret; GSList *elem = registered_drivers; - const struct libusb_device_descriptor *dsc = - libusb_get_device_descriptor(udev); + struct libusb_device_descriptor dsc; + + ret = libusb_get_device_descriptor(udev, &dsc); + if (ret < 0) { + fp_err("Failed to get device descriptor"); + return NULL; + } do { struct fp_driver *drv = elem->data; const struct usb_id *id; for (id = drv->id_table; id->vendor; id++) - if (dsc->idVendor == id->vendor && dsc->idProduct == id->product) { + if (dsc.idVendor == id->vendor && dsc.idProduct == id->product) { fp_dbg("driver %s supports USB device %04x:%04x", drv->name, id->vendor, id->product); *usb_id = id; diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index dc6da212..e9e40f99 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -1106,7 +1106,7 @@ static void dev_deactivate(struct fp_img_dev *dev) static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) { - const struct libusb_config_descriptor *config; + struct libusb_config_descriptor *config; const struct libusb_interface *iface = NULL; const struct libusb_interface_descriptor *iface_desc; const struct libusb_endpoint_descriptor *ep; @@ -1115,7 +1115,11 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) int r; /* Find fingerprint interface */ - config = libusb_get_config_descriptor(libusb_get_device(dev->udev)); + r = libusb_get_config_descriptor(libusb_get_device(dev->udev), 0, &config); + if (r < 0) { + fp_err("Failed to get config descriptor"); + return r; + } for (i = 0; i < config->bNumInterfaces; i++) { const struct libusb_interface *cur_iface = &config->interface[i]; @@ -1133,14 +1137,16 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) if (iface == NULL) { fp_err("could not find interface"); - return -ENODEV; + r = -ENODEV; + goto out; } /* Find/check endpoints */ if (iface_desc->bNumEndpoints != 2) { fp_err("found %d endpoints!?", iface_desc->bNumEndpoints); - return -ENODEV; + r = -ENODEV; + goto out; } ep = &iface_desc->endpoint[0]; @@ -1148,7 +1154,8 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) || (ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) != LIBUSB_TRANSFER_TYPE_INTERRUPT) { fp_err("unrecognised interrupt endpoint"); - return -ENODEV; + r = -ENODEV; + goto out; } ep = &iface_desc->endpoint[1]; @@ -1156,7 +1163,8 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) || (ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) != LIBUSB_TRANSFER_TYPE_BULK) { fp_err("unrecognised bulk endpoint"); - return -ENODEV; + r = -ENODEV; + goto out; } /* Device looks like a supported reader */ @@ -1164,7 +1172,7 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) r = libusb_claim_interface(dev->udev, iface_desc->bInterfaceNumber); if (r < 0) { fp_err("interface claim failed"); - return r; + goto out; } urudev = g_malloc0(sizeof(*urudev)); @@ -1173,7 +1181,10 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) AES_set_encrypt_key(crkey, 128, &urudev->aeskey); dev->priv = urudev; fpi_imgdev_open_complete(dev, 0); - return 0; + +out: + libusb_free_config_descriptor(config); + return r; } static void dev_deinit(struct fp_img_dev *dev) From e1691a29dd21475264134c42d929d90b3d26ceca Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sun, 15 Jun 2008 10:54:07 -0500 Subject: [PATCH 134/184] update for new libusb_open API --- libfprint/async.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/libfprint/async.c b/libfprint/async.c index 5d0bd102..67e3481e 100644 --- a/libfprint/async.c +++ b/libfprint/async.c @@ -45,10 +45,10 @@ API_EXPORTED int fp_async_dev_open(struct fp_dscv_dev *ddev, fp_dev_open_cb cb, int r; fp_dbg(""); - udevh = libusb_open(ddev->udev); - if (!udevh) { - fp_err("usb_open failed"); - return -EIO; + r = libusb_open(ddev->udev, &udevh); + if (r < 0) { + fp_err("usb_open failed, error %d", r); + return r; } dev = g_malloc0(sizeof(*dev)); From 59c62c7d744a9b5e4c7355932889cd0342044e09 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Wed, 2 Jul 2008 23:27:37 -0500 Subject: [PATCH 135/184] Update for libusb-0.9.1 --- configure.ac | 2 +- libfprint/core.c | 7 ++++--- libfprint/fp_internal.h | 1 + libfprint/poll.c | 14 +++++++------- 4 files changed, 13 insertions(+), 11 deletions(-) diff --git a/configure.ac b/configure.ac index 386333b0..9f297716 100644 --- a/configure.ac +++ b/configure.ac @@ -18,7 +18,7 @@ AC_SUBST(lt_major) AC_SUBST(lt_revision) AC_SUBST(lt_age) -PKG_CHECK_MODULES(LIBUSB, [libusb-1.0 = 0.9.0]) +PKG_CHECK_MODULES(LIBUSB, [libusb-1.0 >= 0.9.1]) AC_SUBST(LIBUSB_CFLAGS) AC_SUBST(LIBUSB_LIBS) diff --git a/libfprint/core.c b/libfprint/core.c index 2b57ca75..f9456c7a 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -26,6 +26,7 @@ #include "fp_internal.h" +libusb_context *fpi_usb_ctx = NULL; GSList *opened_devices = NULL; /** @@ -426,7 +427,7 @@ API_EXPORTED struct fp_dscv_dev **fp_discover_devs(void) if (registered_drivers == NULL) return NULL; - r = libusb_get_device_list(&devs); + r = libusb_get_device_list(fpi_usb_ctx, &devs); if (r < 0) { fp_err("couldn't enumerate USB devices, error %d", r); return NULL; @@ -786,7 +787,7 @@ API_EXPORTED int fp_init(void) int r; fp_dbg(""); - r = libusb_init(); + r = libusb_init(&fpi_usb_ctx); if (r < 0) return r; @@ -822,6 +823,6 @@ API_EXPORTED void fp_exit(void) fpi_poll_exit(); g_slist_free(registered_drivers); registered_drivers = NULL; - libusb_exit(); + libusb_exit(fpi_usb_ctx); } diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 7eb87f1e..3d839bd4 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -242,6 +242,7 @@ extern struct fp_img_driver aes4000_driver; extern struct fp_img_driver fdu2000_driver; extern struct fp_img_driver vcom5s_driver; +extern libusb_context *fpi_usb_ctx; extern GSList *opened_devices; void fpi_img_driver_setup(struct fp_img_driver *idriver); diff --git a/libfprint/poll.c b/libfprint/poll.c index 1c357419..a8529058 100644 --- a/libfprint/poll.c +++ b/libfprint/poll.c @@ -228,7 +228,7 @@ API_EXPORTED int fp_handle_events_timeout(struct timeval *timeout) select_timeout = *timeout; } - r = libusb_handle_events_timeout(&select_timeout); + r = libusb_handle_events_timeout(fpi_usb_ctx, &select_timeout); *timeout = select_timeout; if (r < 0) return r; @@ -263,7 +263,7 @@ API_EXPORTED int fp_get_next_timeout(struct timeval *tv) int r_libusb; r_fprint = get_next_timeout_expiry(&fprint_timeout, NULL); - r_libusb = libusb_get_next_timeout(&libusb_timeout); + r_libusb = libusb_get_next_timeout(fpi_usb_ctx, &libusb_timeout); /* if we have no pending timeouts and the same is true for libusb, * indicate that we have no pending timouts */ @@ -297,7 +297,7 @@ API_EXPORTED size_t fp_get_pollfds(struct fp_pollfd **pollfds) size_t cnt = 0; size_t i = 0; - usbfds = libusb_get_pollfds(); + usbfds = libusb_get_pollfds(fpi_usb_ctx); if (!usbfds) { *pollfds = NULL; return -EIO; @@ -325,13 +325,13 @@ API_EXPORTED void fp_set_pollfd_notifiers(fp_pollfd_added_cb added_cb, fd_removed_cb = removed_cb; } -static void add_pollfd(int fd, short events) +static void add_pollfd(int fd, short events, void *user_data) { if (fd_added_cb) fd_added_cb(fd, events); } -static void remove_pollfd(int fd) +static void remove_pollfd(int fd, void *user_data) { if (fd_removed_cb) fd_removed_cb(fd); @@ -339,7 +339,7 @@ static void remove_pollfd(int fd) void fpi_poll_init(void) { - libusb_set_pollfd_notifiers(add_pollfd, remove_pollfd); + libusb_set_pollfd_notifiers(fpi_usb_ctx, add_pollfd, remove_pollfd, NULL); } void fpi_poll_exit(void) @@ -348,6 +348,6 @@ void fpi_poll_exit(void) active_timers = NULL; fd_added_cb = NULL; fd_removed_cb = NULL; - libusb_set_pollfd_notifiers(NULL, NULL); + libusb_set_pollfd_notifiers(fpi_usb_ctx, NULL, NULL, NULL); } From 3915cb262269a32844b3672d8bc3edc188b2f402 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Wed, 9 Jul 2008 03:23:21 +0100 Subject: [PATCH 136/184] Add upeksonly driver for UPEK TouchStrip sensor-only devices The long awaited 147e:2016 reverse engineering efforts. Image quality is OK, not brilliant - a little fuzzy, but it works quite well. --- libfprint/Makefile.am | 3 +- libfprint/core.c | 1 + libfprint/drivers/upeksonly.c | 1035 +++++++++++++++++++++++++++++++++ libfprint/fp_internal.h | 1 + 4 files changed, 1039 insertions(+), 1 deletion(-) create mode 100644 libfprint/drivers/upeksonly.c diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 8ed5732e..468e0208 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -2,6 +2,7 @@ lib_LTLIBRARIES = libfprint.la UPEKTS_SRC = drivers/upekts.c UPEKTC_SRC = drivers/upektc.c +UPEKSONLY_SRC = drivers/upeksonly.c URU4000_SRC = drivers/uru4000.c AES1610_SRC = drivers/aes1610.c AES2501_SRC = drivers/aes2501.c drivers/aes2501.h @@ -9,7 +10,7 @@ AES4000_SRC = drivers/aes4000.c FDU2000_SRC = drivers/fdu2000.c VCOM5S_SRC = drivers/vcom5s.c -DRIVER_SRC = $(UPEKTS_SRC) $(AES4000_SRC) $(AES2501_SRC) $(URU4000_SRC) $(VCOM5S_SRC) +DRIVER_SRC = $(UPEKTS_SRC) $(AES4000_SRC) $(AES2501_SRC) $(URU4000_SRC) $(VCOM5S_SRC) $(UPEKSONLY_SRC) #DRIVER_SRC = $(AES1610_SRC) $(UPEKTC_SRC) $(FDU2000_SRC) NBIS_SRC = \ diff --git a/libfprint/core.c b/libfprint/core.c index f9456c7a..1a45e1d6 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -335,6 +335,7 @@ static struct fp_img_driver * const img_drivers[] = { &aes2501_driver, &uru4000_driver, &vcom5s_driver, + &upeksonly_driver, /* &aes1610_driver, &upektc_driver, &fdu2000_driver, */ diff --git a/libfprint/drivers/upeksonly.c b/libfprint/drivers/upeksonly.c new file mode 100644 index 00000000..a8f29860 --- /dev/null +++ b/libfprint/drivers/upeksonly.c @@ -0,0 +1,1035 @@ +/* + * UPEK TouchStrip Sensor-Only driver for libfprint + * Copyright (C) 2008 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#define FP_COMPONENT "upeksonly" + +#include +#include + +#include +#include + +#include + +#define CTRL_TIMEOUT 1000 +#define IMG_WIDTH 288 +#define NUM_BULK_TRANSFERS 24 +#define MAX_ROWS 700 + +struct img_transfer_data { + int idx; + struct fp_img_dev *dev; + gboolean flying; + gboolean cancelling; +}; + +enum sonly_kill_transfers_action { + NOT_KILLING = 0, + + /* abort a SSM with an error code */ + ABORT_SSM, + + /* report an image session error */ + IMG_SESSION_ERROR, + + /* iterate a SSM to the next state */ + ITERATE_SSM, + + /* call a callback */ + EXEC_CALLBACK, +}; + +struct sonly_dev { + gboolean capturing; + gboolean deactivating; + uint8_t read_reg_result; + + struct fpi_ssm *loopsm; + struct libusb_transfer *img_transfer[NUM_BULK_TRANSFERS]; + struct img_transfer_data *img_transfer_data; + int num_flying; + + GSList *rows; + size_t num_rows; + unsigned char *rowbuf; + int rowbuf_offset; + + int wraparounds; + int num_blank; + int finger_removed; + int last_seqnum; + + enum sonly_kill_transfers_action killing_transfers; + int kill_status_code; + union { + struct fpi_ssm *kill_ssm; + void (*kill_cb)(struct fp_img_dev *dev); + }; +}; + +struct sonly_regwrite { + uint8_t reg; + uint8_t value; +}; + +/***** IMAGE PROCESSING *****/ + +static void free_img_transfers(struct sonly_dev *sdev) +{ + int i; + for (i = 0; i < NUM_BULK_TRANSFERS; i++) { + struct libusb_transfer *transfer = sdev->img_transfer[i]; + if (!transfer) + continue; + + g_free(transfer->buffer); + libusb_free_transfer(transfer); + } + g_free(sdev->img_transfer_data); +} + +static void last_transfer_killed(struct fp_img_dev *dev) +{ + struct sonly_dev *sdev = dev->priv; + switch (sdev->killing_transfers) { + case ABORT_SSM: + fp_dbg("abort ssm error %d", sdev->kill_status_code); + fpi_ssm_mark_aborted(sdev->kill_ssm, sdev->kill_status_code); + return; + case ITERATE_SSM: + fp_dbg("iterate ssm"); + fpi_ssm_next_state(sdev->kill_ssm); + return; + case IMG_SESSION_ERROR: + fp_dbg("session error %d", sdev->kill_status_code); + fpi_imgdev_session_error(dev, sdev->kill_status_code); + return; + default: + return; + } +} + +static void cancel_img_transfers(struct fp_img_dev *dev) +{ + struct sonly_dev *sdev = dev->priv; + int i; + + if (sdev->num_flying == 0) { + last_transfer_killed(dev); + return; + } + + for (i = 0; i < NUM_BULK_TRANSFERS; i++) { + struct img_transfer_data *idata = &sdev->img_transfer_data[i]; + if (!idata->flying || idata->cancelling) + continue; + fp_dbg("cancelling transfer %d", i); + int r = libusb_cancel_transfer(sdev->img_transfer[i]); + if (r < 0) + fp_dbg("cancel failed error %d", r); + idata->cancelling = TRUE; + } +} + +static gboolean is_capturing(struct sonly_dev *sdev) +{ + return sdev->num_rows < MAX_ROWS && !sdev->finger_removed; +} + +static void handoff_img(struct fp_img_dev *dev) +{ + struct sonly_dev *sdev = dev->priv; + size_t size = IMG_WIDTH * sdev->num_rows; + struct fp_img *img = fpi_img_new(size); + GSList *elem = sdev->rows; + size_t offset = 0; + + if (!elem) { + fp_err("no rows?"); + return; + } + + fp_dbg("%d rows", sdev->num_rows); + img->height = sdev->num_rows; + + do { + memcpy(img->data + offset, elem->data, IMG_WIDTH); + g_free(elem->data); + offset += IMG_WIDTH; + } while ((elem = g_slist_next(elem)) != NULL); + + g_slist_free(sdev->rows); + sdev->rows = NULL; + + fpi_imgdev_image_captured(dev, img); + fpi_imgdev_report_finger_status(dev, FALSE); + + sdev->killing_transfers = ITERATE_SSM; + sdev->kill_ssm = sdev->loopsm; + cancel_img_transfers(dev); +} + +static void compute_rows(unsigned char *a, unsigned char *b, int *diff, + int *total) +{ + int i; + int _total = 0; + int _diff = 0; + + for (i = 0; i < IMG_WIDTH; i++) { + if (a[i] > b[i]) + _diff += a[i] - b[i]; + else + _diff += b[i] - a[i]; + _total += b[i]; + } + *diff = _diff; + *total = _total; +} + +static void row_complete(struct fp_img_dev *dev) +{ + struct sonly_dev *sdev = dev->priv; + sdev->rowbuf_offset = -1; + + if (sdev->num_rows > 0) { + unsigned char *lastrow = sdev->rows->data; + int diff; + int total; + + compute_rows(lastrow, sdev->rowbuf, &diff, &total); + if (total < 52000) { + sdev->num_blank = 0; + } else { + sdev->num_blank++; + if (sdev->num_blank > 500) { + sdev->finger_removed = 1; + fp_dbg("detected finger removal"); + handoff_img(dev); + return; + } + } + if (diff < 3000) + return; + } + + sdev->rows = g_slist_prepend(sdev->rows, sdev->rowbuf); + sdev->num_rows++; + sdev->rowbuf = NULL; + + if (sdev->num_rows >= MAX_ROWS) { + fp_dbg("row limit met"); + handoff_img(dev); + } +} + +/* add data to row buffer */ +static void add_to_rowbuf(struct fp_img_dev *dev, unsigned char *data, int size) +{ + struct sonly_dev *sdev = dev->priv; + + memcpy(sdev->rowbuf + sdev->rowbuf_offset, data, size); + sdev->rowbuf_offset += size; + if (sdev->rowbuf_offset >= IMG_WIDTH) + row_complete(dev); +} + +static void start_new_row(struct sonly_dev *sdev, unsigned char *data, int size) +{ + if (!sdev->rowbuf) + sdev->rowbuf = g_malloc(IMG_WIDTH); + memcpy(sdev->rowbuf + IMG_WIDTH - 2, data, 2); + memcpy(sdev->rowbuf, data + 2, size - 2); + sdev->rowbuf_offset = size; +} + +/* returns number of bytes left to be copied into rowbuf (capped to 62) + * or -1 if we aren't capturing anything */ +static int rowbuf_remaining(struct sonly_dev *sdev) +{ + int r; + + if (sdev->rowbuf_offset == -1) + return -1; + + r = IMG_WIDTH - sdev->rowbuf_offset; + if (r > 62) + r = 62; + return r; +} + +static void handle_packet(struct fp_img_dev *dev, unsigned char *data) +{ + struct sonly_dev *sdev = dev->priv; + uint16_t seqnum = data[0] << 8 | data[1]; + int abs_base_addr; + int for_rowbuf; + int next_row_addr; + int diff; + + data += 2; /* skip sequence number */ + if (seqnum != sdev->last_seqnum + 1) { + if (seqnum != 0 && sdev->last_seqnum != 16383) + fp_warn("lost some data"); + } + if (seqnum <= sdev->last_seqnum) { + fp_dbg("detected wraparound"); + sdev->wraparounds++; + } + + sdev->last_seqnum = seqnum; + seqnum += sdev->wraparounds * 16384; + abs_base_addr = seqnum * 62; + + /* are we already capturing a row? if so append the data to the + * row buffer */ + for_rowbuf = rowbuf_remaining(sdev); + if (for_rowbuf != -1) { + add_to_rowbuf(dev, data, for_rowbuf); + /* FIXME: we drop a row here */ + return; + } + + /* does the packet START on a boundary? if so we want it in full */ + if (abs_base_addr % IMG_WIDTH == 0) { + start_new_row(sdev, data, 62); + return; + } + + /* does the data in the packet reside on a row boundary? + * if so capture it */ + next_row_addr = ((abs_base_addr / IMG_WIDTH) + 1) * IMG_WIDTH; + diff = next_row_addr - abs_base_addr; + if (diff < 62) + start_new_row(sdev, data + diff, 62 - diff); +} + +static void img_data_cb(struct libusb_transfer *transfer) +{ + struct img_transfer_data *idata = transfer->user_data; + struct fp_img_dev *dev = idata->dev; + struct sonly_dev *sdev = dev->priv; + int i; + + idata->flying = FALSE; + idata->cancelling = FALSE; + sdev->num_flying--; + + if (sdev->killing_transfers) { + if (sdev->num_flying == 0) + last_transfer_killed(dev); + + /* don't care about error or success if we're terminating */ + return; + } + + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { + fp_warn("bad status %d, terminating session", transfer->status); + sdev->killing_transfers = IMG_SESSION_ERROR; + sdev->kill_status_code = transfer->status; + cancel_img_transfers(dev); + } + + /* there are 64 packets in the transfer buffer + * each packet is 64 bytes in length + * the first 2 bytes are a sequence number + * then there are 62 bytes for image data + */ + for (i = 0; i < 4096; i += 64) { + if (!is_capturing(sdev)) + return; + handle_packet(dev, transfer->buffer + i); + } + + if (is_capturing(sdev)) { + int r = libusb_submit_transfer(transfer); + if (r < 0) { + fp_warn("failed resubmit, error %d", r); + sdev->killing_transfers = IMG_SESSION_ERROR; + sdev->kill_status_code = r; + cancel_img_transfers(dev); + return; + } + sdev->num_flying++; + idata->flying = TRUE; + } +} + +/***** STATE MACHINE HELPERS *****/ + +struct write_regs_data { + struct fpi_ssm *ssm; + struct libusb_transfer *transfer; + const struct sonly_regwrite *regs; + size_t num_regs; + size_t regs_written; +}; + +static void write_regs_finished(struct write_regs_data *wrdata, int result) +{ + g_free(wrdata->transfer->buffer); + libusb_free_transfer(wrdata->transfer); + if (result == 0) + fpi_ssm_next_state(wrdata->ssm); + else + fpi_ssm_mark_aborted(wrdata->ssm, result); + g_free(wrdata); +} + + +static void write_regs_iterate(struct write_regs_data *wrdata) +{ + struct fpi_ssm *ssm; + struct libusb_control_setup *setup; + const struct sonly_regwrite *regwrite; + int r; + + if (wrdata->regs_written >= wrdata->num_regs) { + write_regs_finished(wrdata, 0); + return; + } + + regwrite = &wrdata->regs[wrdata->regs_written]; + ssm = wrdata->ssm; + + fp_dbg("set %02x=%02x", regwrite->reg, regwrite->value); + setup = libusb_control_transfer_get_setup(wrdata->transfer); + setup->wIndex = regwrite->reg; + wrdata->transfer->buffer[LIBUSB_CONTROL_SETUP_SIZE] = regwrite->value; + + r = libusb_submit_transfer(wrdata->transfer); + if (r < 0) + write_regs_finished(wrdata, r); +} + +static void write_regs_cb(struct libusb_transfer *transfer) +{ + struct write_regs_data *wrdata = transfer->user_data; + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { + write_regs_finished(wrdata, transfer->status); + return; + } + + wrdata->regs_written++; + write_regs_iterate(wrdata); +} + +static void sm_write_regs(struct fpi_ssm *ssm, + const struct sonly_regwrite *regs, size_t num_regs) +{ + struct write_regs_data *wrdata = g_malloc(sizeof(*wrdata)); + unsigned char *data; + + wrdata->transfer = libusb_alloc_transfer(0); + if (!wrdata->transfer) { + g_free(wrdata); + fpi_ssm_mark_aborted(ssm, -ENOMEM); + return; + } + + data = g_malloc(LIBUSB_CONTROL_SETUP_SIZE + 1); + libusb_fill_control_setup(data, 0x40, 0x0c, 0, 0, 1); + libusb_fill_control_transfer(wrdata->transfer, ssm->dev->udev, data, + write_regs_cb, wrdata, CTRL_TIMEOUT); + wrdata->transfer->flags = LIBUSB_TRANSFER_SHORT_NOT_OK; + + wrdata->ssm = ssm; + wrdata->regs = regs; + wrdata->num_regs = num_regs; + wrdata->regs_written = 0; + write_regs_iterate(wrdata); +} + +static void sm_write_reg_cb(struct libusb_transfer *transfer) +{ + struct fpi_ssm *ssm = transfer->user_data; + g_free(transfer->buffer); + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) + fpi_ssm_mark_aborted(ssm, -EIO); + else + fpi_ssm_next_state(ssm); + +} + +static void sm_write_reg(struct fpi_ssm *ssm, uint8_t reg, uint8_t value) +{ + struct fp_img_dev *dev = ssm->priv; + struct libusb_transfer *transfer = libusb_alloc_transfer(0); + unsigned char *data; + int r; + + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + return; + } + + fp_dbg("set %02x=%02x", reg, value); + data = g_malloc(LIBUSB_CONTROL_SETUP_SIZE + 1); + libusb_fill_control_setup(data, 0x40, 0x0c, 0, reg, 1); + libusb_fill_control_transfer(transfer, dev->udev, data, sm_write_reg_cb, + ssm, CTRL_TIMEOUT); + + data[LIBUSB_CONTROL_SETUP_SIZE] = value; + transfer->flags = LIBUSB_TRANSFER_SHORT_NOT_OK | + LIBUSB_TRANSFER_FREE_TRANSFER; + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(data); + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, r); + } +} + +static void sm_read_reg_cb(struct libusb_transfer *transfer) +{ + struct fpi_ssm *ssm = transfer->user_data; + struct fp_img_dev *dev = ssm->priv; + struct sonly_dev *sdev = dev->priv; + + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { + fpi_ssm_mark_aborted(ssm, -EIO); + } else { + sdev->read_reg_result = libusb_control_transfer_get_data(transfer)[0]; + fp_dbg("read reg result = %02x", sdev->read_reg_result); + fpi_ssm_next_state(ssm); + } + + g_free(transfer->buffer); +} + +static void sm_read_reg(struct fpi_ssm *ssm, uint8_t reg) +{ + struct fp_img_dev *dev = ssm->priv; + struct libusb_transfer *transfer = libusb_alloc_transfer(0); + unsigned char *data; + int r; + + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + return; + } + + fp_dbg("read reg %02x", reg); + data = g_malloc(LIBUSB_CONTROL_SETUP_SIZE + 8); + libusb_fill_control_setup(data, 0xc0, 0x0c, 0, reg, 8); + libusb_fill_control_transfer(transfer, dev->udev, data, sm_read_reg_cb, + ssm, CTRL_TIMEOUT); + transfer->flags = LIBUSB_TRANSFER_SHORT_NOT_OK | + LIBUSB_TRANSFER_FREE_TRANSFER; + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(data); + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, r); + } +} + +static void sm_await_intr_cb(struct libusb_transfer *transfer) +{ + struct fpi_ssm *ssm = transfer->user_data; + struct fp_img_dev *dev = ssm->priv; + + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { + g_free(transfer->buffer); + fpi_ssm_mark_aborted(ssm, transfer->status); + return; + } + + fp_dbg("interrupt received: %02x %02x %02x %02x", + transfer->buffer[0], transfer->buffer[1], + transfer->buffer[2], transfer->buffer[3]); + g_free(transfer->buffer); + + fpi_imgdev_report_finger_status(dev, TRUE); + fpi_ssm_next_state(ssm); +} + +static void sm_await_intr(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct libusb_transfer *transfer = libusb_alloc_transfer(0); + unsigned char *data; + int r; + + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + return; + } + + fp_dbg(""); + data = g_malloc(4); + libusb_fill_interrupt_transfer(transfer, dev->udev, 0x83, data, 4, + sm_await_intr_cb, ssm, 0); + transfer->flags = LIBUSB_TRANSFER_SHORT_NOT_OK | + LIBUSB_TRANSFER_FREE_TRANSFER; + + r = libusb_submit_transfer(transfer); + if (r < 0) { + libusb_free_transfer(transfer); + g_free(data); + fpi_ssm_mark_aborted(ssm, r); + } +} + +/***** AWAIT FINGER *****/ + +static const struct sonly_regwrite awfsm_writev_1[] = { + { 0x0a, 0x00 }, { 0x0a, 0x00 }, { 0x09, 0x20 }, { 0x03, 0x3b }, + { 0x00, 0x67 }, { 0x00, 0x67 }, +}; + +static const struct sonly_regwrite awfsm_writev_2[] = { + { 0x01, 0xc6 }, { 0x0c, 0x13 }, { 0x0d, 0x0d }, { 0x0e, 0x0e }, + { 0x0f, 0x0d }, { 0x0b, 0x00 }, +}; + +static const struct sonly_regwrite awfsm_writev_3[] = { + { 0x13, 0x45 }, { 0x30, 0xe0 }, { 0x12, 0x01 }, { 0x20, 0x01 }, + { 0x09, 0x20 }, { 0x0a, 0x00 }, { 0x30, 0xe0 }, { 0x20, 0x01 }, +}; + +static const struct sonly_regwrite awfsm_writev_4[] = { + { 0x08, 0x00 }, { 0x10, 0x00 }, { 0x12, 0x01 }, { 0x11, 0xbf }, + { 0x12, 0x01 }, { 0x07, 0x10 }, { 0x07, 0x10 }, { 0x04, 0x00 },\ + { 0x05, 0x00 }, { 0x0b, 0x00 }, + + /* enter finger detection mode */ + { 0x15, 0x20 }, { 0x30, 0xe1 }, { 0x15, 0x24 }, { 0x15, 0x04 }, + { 0x15, 0x84 }, +}; + +enum awfsm_states { + AWFSM_WRITEV_1, + AWFSM_READ_01, + AWFSM_WRITE_01, + AWFSM_WRITEV_2, + AWFSM_READ_13, + AWFSM_WRITE_13, + AWFSM_WRITEV_3, + AWFSM_READ_07, + AWFSM_WRITE_07, + AWFSM_WRITEV_4, + AWFSM_NUM_STATES, +}; + +static void awfsm_run_state(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct sonly_dev *sdev = dev->priv; + + switch (ssm->cur_state) { + case AWFSM_WRITEV_1: + sm_write_regs(ssm, awfsm_writev_1, G_N_ELEMENTS(awfsm_writev_1)); + break; + case AWFSM_READ_01: + sm_read_reg(ssm, 0x01); + break; + case AWFSM_WRITE_01: + if (sdev->read_reg_result != 0xc6) + sm_write_reg(ssm, 0x01, 0x46); + else + sm_write_reg(ssm, 0x01, 0xc6); + break; + case AWFSM_WRITEV_2: + sm_write_regs(ssm, awfsm_writev_2, G_N_ELEMENTS(awfsm_writev_2)); + break; + case AWFSM_READ_13: + sm_read_reg(ssm, 0x13); + break; + case AWFSM_WRITE_13: + if (sdev->read_reg_result != 0x45) + sm_write_reg(ssm, 0x13, 0x05); + else + sm_write_reg(ssm, 0x13, 0x45); + break; + case AWFSM_WRITEV_3: + sm_write_regs(ssm, awfsm_writev_3, G_N_ELEMENTS(awfsm_writev_3)); + break; + case AWFSM_READ_07: + sm_read_reg(ssm, 0x07); + break; + case AWFSM_WRITE_07: + if (sdev->read_reg_result != 0x10 && sdev->read_reg_result != 0x90) + fp_warn("odd reg7 value %x", sdev->read_reg_result); + sm_write_reg(ssm, 0x07, sdev->read_reg_result); + break; + case AWFSM_WRITEV_4: + sm_write_regs(ssm, awfsm_writev_4, G_N_ELEMENTS(awfsm_writev_4)); + break; + } +} + +/***** CAPTURE MODE *****/ + +static const struct sonly_regwrite capsm_writev[] = { + /* enter capture mode */ + { 0x09, 0x28 }, { 0x13, 0x55 }, { 0x0b, 0x80 }, { 0x04, 0x00 }, + { 0x05, 0x00 }, +}; + +enum capsm_states { + CAPSM_INIT, + CAPSM_WRITE_15, + CAPSM_WRITE_30, + CAPSM_FIRE_BULK, + CAPSM_WRITEV, + CAPSM_NUM_STATES, +}; + +static void capsm_run_state(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct sonly_dev *sdev = dev->priv; + + switch (ssm->cur_state) { + case CAPSM_INIT: + sdev->rowbuf_offset = -1; + sdev->num_rows = 0; + sdev->wraparounds = -1; + sdev->num_blank = 0; + sdev->finger_removed = 0; + sdev->last_seqnum = 16383; + sdev->killing_transfers = 0; + fpi_ssm_next_state(ssm); + break; + case CAPSM_WRITE_15: + sm_write_reg(ssm, 0x15, 0x20); + break; + case CAPSM_WRITE_30: + sm_write_reg(ssm, 0x30, 0xe0); + break; + case CAPSM_FIRE_BULK: ; + int i; + for (i = 0; i < NUM_BULK_TRANSFERS; i++) { + int r = libusb_submit_transfer(sdev->img_transfer[i]); + if (r < 0) { + if (i == 0) { + /* first one failed: easy peasy */ + fpi_ssm_mark_aborted(ssm, r); + return; + } + + /* cancel all flying transfers, and request that the SSM + * gets aborted when the last transfer has dropped out of + * the sky */ + sdev->killing_transfers = ABORT_SSM; + sdev->kill_ssm = ssm; + sdev->kill_status_code = r; + cancel_img_transfers(dev); + return; + } + sdev->img_transfer_data[i].flying = TRUE; + sdev->num_flying++; + } + sdev->capturing = TRUE; + fpi_ssm_next_state(ssm); + break; + case CAPSM_WRITEV: + sm_write_regs(ssm, capsm_writev, G_N_ELEMENTS(capsm_writev)); + break; + } +} + +/***** DEINITIALIZATION *****/ + +static const struct sonly_regwrite deinitsm_writev[] = { + /* reset + enter low power mode */ + { 0x0b, 0x00 }, { 0x09, 0x20 }, { 0x13, 0x45 }, { 0x13, 0x45 }, +}; + +enum deinitsm_states { + DEINITSM_WRITEV, + DEINITSM_NUM_STATES, +}; + +static void deinitsm_run_state(struct fpi_ssm *ssm) +{ + switch (ssm->cur_state) { + case DEINITSM_WRITEV: + sm_write_regs(ssm, deinitsm_writev, G_N_ELEMENTS(deinitsm_writev)); + break; + } +} + +/***** INITIALIZATION *****/ + +static const struct sonly_regwrite initsm_writev_1[] = { + { 0x49, 0x00 }, + + /* BSAPI writes different values to register 0x3e each time. I initially + * thought this was some kind of clever authentication, but just blasting + * these sniffed values each time seems to work. */ + { 0x3e, 0x83 }, { 0x3e, 0x4f }, { 0x3e, 0x0f }, { 0x3e, 0xbf }, + { 0x3e, 0x45 }, { 0x3e, 0x35 }, { 0x3e, 0x1c }, { 0x3e, 0xae }, + + { 0x44, 0x01 }, { 0x43, 0x06 }, { 0x43, 0x05 }, { 0x43, 0x04 }, + { 0x44, 0x00 }, { 0x0b, 0x00 }, +}; + +enum initsm_states { + INITSM_WRITEV_1, + INITSM_READ_09, + INITSM_WRITE_09, + INITSM_READ_13, + INITSM_WRITE_13, + INITSM_WRITE_04, + INITSM_WRITE_05, + INITSM_NUM_STATES, +}; + +static void initsm_run_state(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct sonly_dev *sdev = dev->priv; + + switch (ssm->cur_state) { + case INITSM_WRITEV_1: + sm_write_regs(ssm, initsm_writev_1, G_N_ELEMENTS(initsm_writev_1)); + break; + case INITSM_READ_09: + sm_read_reg(ssm, 0x09); + break; + case INITSM_WRITE_09: + sm_write_reg(ssm, 0x09, sdev->read_reg_result & ~0x08); + break; + case INITSM_READ_13: + sm_read_reg(ssm, 0x13); + break; + case INITSM_WRITE_13: + sm_write_reg(ssm, 0x13, sdev->read_reg_result & ~0x10); + break; + case INITSM_WRITE_04: + sm_write_reg(ssm, 0x04, 0x00); + break; + case INITSM_WRITE_05: + sm_write_reg(ssm, 0x05, 0x00); + break; + } +} + +/***** CAPTURE LOOP *****/ + +enum loopsm_states { + LOOPSM_RUN_AWFSM, + LOOPSM_AWAIT_FINGER, + LOOPSM_RUN_CAPSM, + LOOPSM_CAPTURE, + LOOPSM_RUN_DEINITSM, + LOOPSM_FINAL, + LOOPSM_NUM_STATES, +}; + +static void loopsm_run_state(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct sonly_dev *sdev = dev->priv; + + switch (ssm->cur_state) { + case LOOPSM_RUN_AWFSM: ; + if (sdev->deactivating) { + fpi_ssm_mark_completed(ssm); + } else { + struct fpi_ssm *awfsm = fpi_ssm_new(dev->dev, awfsm_run_state, + AWFSM_NUM_STATES); + awfsm->priv = dev; + fpi_ssm_start_subsm(ssm, awfsm); + } + break; + case LOOPSM_AWAIT_FINGER: + sm_await_intr(ssm); + break; + case LOOPSM_RUN_CAPSM: ; + struct fpi_ssm *capsm = fpi_ssm_new(dev->dev, capsm_run_state, + CAPSM_NUM_STATES); + capsm->priv = dev; + fpi_ssm_start_subsm(ssm, capsm); + break; + case LOOPSM_CAPTURE: + /* bulk URBs already flying, so just wait for image completion + * to push us into next state */ + break; + case LOOPSM_RUN_DEINITSM: ; + struct fpi_ssm *deinitsm = fpi_ssm_new(dev->dev, deinitsm_run_state, + DEINITSM_NUM_STATES); + sdev->capturing = FALSE; + deinitsm->priv = dev; + fpi_ssm_start_subsm(ssm, deinitsm); + break; + case LOOPSM_FINAL: + fpi_ssm_jump_to_state(ssm, LOOPSM_RUN_AWFSM); + break; + } + +} + +/***** DRIVER STUFF *****/ + +static void deactivate_done(struct fp_img_dev *dev) +{ + struct sonly_dev *sdev = dev->priv; + + fp_dbg(""); + free_img_transfers(sdev); + g_free(sdev->rowbuf); + sdev->rowbuf = NULL; + + if (sdev->rows) { + g_slist_foreach(sdev->rows, (GFunc) g_free, NULL); + sdev->rows = NULL; + } + + fpi_imgdev_deactivate_complete(dev); +} + +static void dev_deactivate(struct fp_img_dev *dev) +{ + struct sonly_dev *sdev = dev->priv; + + if (!sdev->capturing) { + deactivate_done(dev); + return; + } + + sdev->deactivating = TRUE; + sdev->killing_transfers = ITERATE_SSM; + sdev->kill_ssm = sdev->loopsm; + cancel_img_transfers(dev); +} + +static void loopsm_complete(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct sonly_dev *sdev = dev->priv; + int r = ssm->error; + + fpi_ssm_free(ssm); + + if (sdev->deactivating) { + deactivate_done(dev); + return; + } + + if (r) { + fpi_imgdev_session_error(dev, r); + return; + } +} + +static void initsm_complete(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct sonly_dev *sdev = dev->priv; + int r = ssm->error; + + fpi_ssm_free(ssm); + fpi_imgdev_activate_complete(dev, r); + if (r != 0) + return; + + sdev->loopsm = fpi_ssm_new(dev->dev, loopsm_run_state, LOOPSM_NUM_STATES); + sdev->loopsm->priv = dev; + fpi_ssm_start(sdev->loopsm, loopsm_complete); +} + +static int dev_activate(struct fp_img_dev *dev, enum fp_imgdev_state state) +{ + struct sonly_dev *sdev = dev->priv; + struct fpi_ssm *ssm; + int i; + + sdev->deactivating = FALSE; + sdev->capturing = FALSE; + + memset(sdev->img_transfer, 0, + NUM_BULK_TRANSFERS * sizeof(struct libusb_transfer *)); + sdev->img_transfer_data = + g_malloc0(sizeof(struct img_transfer_data) * NUM_BULK_TRANSFERS); + sdev->num_flying = 0; + for (i = 0; i < NUM_BULK_TRANSFERS; i++) { + unsigned char *data; + sdev->img_transfer[i] = libusb_alloc_transfer(0); + if (!sdev->img_transfer[i]) { + free_img_transfers(sdev); + return -ENOMEM; + } + sdev->img_transfer_data[i].idx = i; + sdev->img_transfer_data[i].dev = dev; + data = g_malloc(4096); + libusb_fill_bulk_transfer(sdev->img_transfer[i], dev->udev, 0x81, data, + 4096, img_data_cb, &sdev->img_transfer_data[i], 0); + } + + ssm = fpi_ssm_new(dev->dev, initsm_run_state, INITSM_NUM_STATES); + ssm->priv = dev; + fpi_ssm_start(ssm, initsm_complete); + return 0; +} + +static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) +{ + int r; + + r = libusb_set_configuration(dev->udev, 1); + if (r < 0) { + fp_err("could not set configuration 1"); + return r; + } + + r = libusb_claim_interface(dev->udev, 0); + if (r < 0) { + fp_err("could not claim interface 0"); + return r; + } + + dev->priv = g_malloc0(sizeof(struct sonly_dev)); + fpi_imgdev_open_complete(dev, 0); + return 0; +} + +static void dev_deinit(struct fp_img_dev *dev) +{ + g_free(dev->priv); + libusb_release_interface(dev->udev, 0); + fpi_imgdev_close_complete(dev); +} + +static const struct usb_id id_table[] = { + { .vendor = 0x147e, .product = 0x2016 }, + { 0, 0, 0, }, +}; + +struct fp_img_driver upeksonly_driver = { + .driver = { + .id = 9, + .name = FP_COMPONENT, + .full_name = "UPEK TouchStrip Sensor-Only", + .id_table = id_table, + }, + .flags = 0, + .img_width = IMG_WIDTH, + .img_height = -1, + + .open = dev_init, + .close = dev_deinit, + .activate = dev_activate, + .deactivate = dev_deactivate, +}; + diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 3d839bd4..027ac127 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -235,6 +235,7 @@ struct fp_img_driver { extern struct fp_driver upekts_driver; extern struct fp_img_driver upektc_driver; +extern struct fp_img_driver upeksonly_driver; extern struct fp_img_driver uru4000_driver; extern struct fp_img_driver aes1610_driver; extern struct fp_img_driver aes2501_driver; From b6dabaacc8d27c7f3ea54fcce7bf0d3ccc0f97c3 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Wed, 9 Jul 2008 03:25:23 +0100 Subject: [PATCH 137/184] Enable libusb debug messages While we're a noisy library we might as well ask libusb to be as well --- libfprint/core.c | 1 + 1 file changed, 1 insertion(+) diff --git a/libfprint/core.c b/libfprint/core.c index 1a45e1d6..6cf2e385 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -792,6 +792,7 @@ API_EXPORTED int fp_init(void) if (r < 0) return r; + libusb_set_debug(fpi_usb_ctx, 3); register_drivers(); fpi_poll_init(); return 0; From bba1c1085fa678e856a3b1e482d68dcc81664d11 Mon Sep 17 00:00:00 2001 From: Pavel Herrman Date: Sun, 10 Aug 2008 14:21:58 -0500 Subject: [PATCH 138/184] Allow drivers to be included/excluded at compile time --- THANKS | 1 + configure.ac | 79 +++++++++++++++++++++++++++++++++++++++++ libfprint/Makefile.am | 56 +++++++++++++++++++++++++---- libfprint/core.c | 24 +++++++++++-- libfprint/fp_internal.h | 18 ++++++++++ libfprint/imgdev.c | 6 ++++ 6 files changed, 176 insertions(+), 8 deletions(-) diff --git a/THANKS b/THANKS index 76c08171..86812718 100644 --- a/THANKS +++ b/THANKS @@ -6,3 +6,4 @@ Craig Watson (NIST) James Vasile (SFLC) Toby Howard (University of Manchester) Seemant Kulleen +Pavel Herrman diff --git a/configure.ac b/configure.ac index 9f297716..d77340fc 100644 --- a/configure.ac +++ b/configure.ac @@ -18,6 +18,83 @@ AC_SUBST(lt_major) AC_SUBST(lt_revision) AC_SUBST(lt_age) +all_drivers="upekts upektc upeksonly vcom5s uru4000 fdu2000 aes1610 aes2501 aes4000" + +require_imagemagick='no' +require_aeslib='no' +enable_upekts='no' +enable_upektc='no' +enable_upeksonly='no' +enable_vcom5s='no' +enable_uru4000='no' +enable_fdu2000='no' +enable_aes1610='no' +enable_aes2501='no' +enable_aes4000='no' + +AC_ARG_WITH([drivers],[AS_HELP_STRING([--with-drivers], + [List of drivers to enable])], + [drivers="$withval"], + [drivers="$all_drivers"]) + +for driver in `echo ${drivers} | sed -e 's/,/ /g' -e 's/,$//g'`; do + case ${driver} in + upekts) + AC_DEFINE([ENABLE_UPEKTS], [], [Build UPEK TouchStrip driver]) + enable_upekts="yes" + ;; + upektc) + AC_DEFINE([ENABLE_UPEKTC], [], [Build UPEK TouchChip driver]) + enable_upektc="yes" + ;; + upeksonly) + AC_DEFINE([ENABLE_UPEKSONLY], [], [Build UPEK TouchStrip sensor-only driver]) + enable_upeksonly="yes" + ;; + uru4000) + AC_DEFINE([ENABLE_URU4000], [], [Build Digital Persona U.are.U 4000 driver]) + enable_uru4000="yes" + ;; + fdu2000) + AC_DEFINE([ENABLE_FDU2000], [], [Build Secugen FDU 2000 driver]) + enable_fdu2000="yes" + ;; + vcom5s) + AC_DEFINE([ENABLE_VCOM5S], [], [Build Veridicom 5thSense driver]) + enable_vcom5s="yes" + ;; + aes2501) + AC_DEFINE([ENABLE_AES2501], [], [Build AuthenTec AES2501 driver]) + require_aeslib="yes" + enable_aes2501="yes" + ;; + aes1610) + AC_DEFINE([ENABLE_AES1610], [], [Build AuthenTec AES1610 driver]) + require_aeslib="yes" + enable_aes1610="yes" + ;; + aes4000) + AC_DEFINE([ENABLE_AES4000], [], [Build AuthenTec AES4000 driver]) + require_aeslib="yes" + require_imagemagick="yes" + enable_aes4000="yes" + ;; + esac +done + +AM_CONDITIONAL([ENABLE_UPEKTS], [test "$enable_upekts" != "no"]) +#AM_CONDITIONAL([ENABLE_UPEKTC], [test "$enable_upektc" != "no"]) +AM_CONDITIONAL([ENABLE_UPEKSONLY], [test "$enable_upeksonly" != "no"]) +AM_CONDITIONAL([ENABLE_VCOM5S], [test "$enable_vcom5s" != "no"]) +AM_CONDITIONAL([ENABLE_URU4000], [test "$enable_uru4000" != "no"]) +#AM_CONDITIONAL([ENABLE_FDU2000], [test "$enable_fdu2000" != "no"]) +#AM_CONDITIONAL([ENABLE_AES1610], [test "$enable_aes1610" != "no"]) +AM_CONDITIONAL([ENABLE_AES2501], [test "$enable_aes2501" != "no"]) +AM_CONDITIONAL([ENABLE_AES4000], [test "$enable_aes4000" != "no"]) +AM_CONDITIONAL([REQUIRE_IMAGEMAGICK], [test "$require_imagemagick" != "no"]) +AM_CONDITIONAL([REQUIRE_AESLIB], [test "$require_aeslib" != "no"]) + + PKG_CHECK_MODULES(LIBUSB, [libusb-1.0 >= 0.9.1]) AC_SUBST(LIBUSB_CFLAGS) AC_SUBST(LIBUSB_LIBS) @@ -31,9 +108,11 @@ PKG_CHECK_MODULES(GLIB, "glib-2.0") AC_SUBST(GLIB_CFLAGS) AC_SUBST(GLIB_LIBS) +if test "$require_imagemagick" != "no"; then PKG_CHECK_MODULES(IMAGEMAGICK, "ImageMagick") AC_SUBST(IMAGEMAGICK_CFLAGS) AC_SUBST(IMAGEMAGICK_LIBS) +fi; # Examples build AC_ARG_ENABLE([examples-build], [AS_HELP_STRING([--enable-examples-build], diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 468e0208..9c53c891 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -10,8 +10,8 @@ AES4000_SRC = drivers/aes4000.c FDU2000_SRC = drivers/fdu2000.c VCOM5S_SRC = drivers/vcom5s.c -DRIVER_SRC = $(UPEKTS_SRC) $(AES4000_SRC) $(AES2501_SRC) $(URU4000_SRC) $(VCOM5S_SRC) $(UPEKSONLY_SRC) -#DRIVER_SRC = $(AES1610_SRC) $(UPEKTC_SRC) $(FDU2000_SRC) +DRIVER_SRC = "" +OTHER_SRC = "" NBIS_SRC = \ nbis/include/bozorth.h \ @@ -50,9 +50,54 @@ NBIS_SRC = \ nbis/mindtct/sort.c \ nbis/mindtct/util.c -libfprint_la_CFLAGS = -fvisibility=hidden -I$(srcdir)/nbis/include $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) $(IMAGEMAGICK_CFLAGS) $(CRYPTO_CFLAGS) $(AM_CFLAGS) +libfprint_la_CFLAGS = -fvisibility=hidden -I$(srcdir)/nbis/include $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) $(CRYPTO_CFLAGS) $(AM_CFLAGS) libfprint_la_LDFLAGS = -version-info @lt_major@:@lt_revision@:@lt_age@ -libfprint_la_LIBADD = -lm $(LIBUSB_LIBS) $(GLIB_LIBS) $(IMAGEMAGICK_LIBS) $(CRYPTO_LIBS) +libfprint_la_LIBADD = -lm $(LIBUSB_LIBS) $(GLIB_LIBS) $(CRYPTO_LIBS) + +if ENABLE_UPEKTS +DRIVER_SRC += $(UPEKTS_SRC) +endif + +if ENABLE_UPEKSONLY +DRIVER_SRC += $(UPEKSONLY_SRC) +endif + +#if ENABLE_UPEKTC +#DRIVER_SRC += $(UPEKTC_SRC) +#endif + +if ENABLE_URU4000 +DRIVER_SRC += $(URU4000_SRC) +endif + +if ENABLE_VCOM5S +DRIVER_SRC += $(VCOM5S_SRC) +endif + +#if ENABLE_FDU2000 +#DRIVER_SRC += $(FDU2000_SRC) +#endif + +#if ENABLE_AES1610 +#DRIVER_SRC += $(AES1610_SRC) +#endif + +if ENABLE_AES2501 +DRIVER_SRC += $(AES2501_SRC) +endif + +if ENABLE_AES4000 +DRIVER_SRC += $(AES4000_SRC) +endif + +if REQUIRE_IMAGEMAGICK +libfprint_la_CFLAGS += $(IMAGEMAGICK_CFLAGS) -DREQUIRE_IMAGEMAGICK +libfprint_la_LIBADD += $(IMAGEMAGICK_LIBS) +endif + +if REQUIRE_AESLIB +OTHER_SRC += aeslib.c aeslib.h +endif libfprint_la_SOURCES = \ fp_internal.h \ @@ -64,9 +109,8 @@ libfprint_la_SOURCES = \ imgdev.c \ poll.c \ sync.c \ - aeslib.c \ - aeslib.h \ $(DRIVER_SRC) \ + $(OTHER_SRC) \ $(NBIS_SRC) pkginclude_HEADERS = fprint.h diff --git a/libfprint/core.c b/libfprint/core.c index 6cf2e385..7cfea43b 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -327,18 +327,38 @@ static void register_driver(struct fp_driver *drv) } static struct fp_driver * const primitive_drivers[] = { +#ifdef ENABLE_UPEKTS &upekts_driver, +#endif }; static struct fp_img_driver * const img_drivers[] = { +#ifdef ENABLE_AES4000 &aes4000_driver, +#endif +#ifdef ENABLE_AES2501 &aes2501_driver, +#endif +#ifdef ENABLE_URU4000 &uru4000_driver, +#endif +#ifdef ENABLE_VCOM5S &vcom5s_driver, +#endif +#ifdef ENABLE_UPEKSONLY &upeksonly_driver, - /* &aes1610_driver, +#endif + /* +#ifdef ENABLE_AES1610 + &aes1610_driver, +#endif +#ifdef ENABLE_UPEKTC &upektc_driver, - &fdu2000_driver, */ +#endif +#ifdef ENABLE_FDU2000 + &fdu2000_driver, +#endif + */ }; static void register_drivers(void) diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 027ac127..dde69cda 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -233,15 +233,33 @@ struct fp_img_driver { void (*deactivate)(struct fp_img_dev *dev); }; +#ifdef ENABLE_UPEKTS extern struct fp_driver upekts_driver; +#endif +#ifdef ENABLE_UPEKTC extern struct fp_img_driver upektc_driver; +#endif +#ifdef ENABLE_UPEKSONLY extern struct fp_img_driver upeksonly_driver; +#endif +#ifdef ENABLE_URU4000 extern struct fp_img_driver uru4000_driver; +#endif +#ifdef ENABLE_AES1610 extern struct fp_img_driver aes1610_driver; +#endif +#ifdef ENABLE_AES2501 extern struct fp_img_driver aes2501_driver; +#endif +#ifdef ENABLE_AES4000 extern struct fp_img_driver aes4000_driver; +#endif +#ifdef ENABLE_FDU2000 extern struct fp_img_driver fdu2000_driver; +#endif +#ifdef ENABLE_VCOM5S extern struct fp_img_driver vcom5s_driver; +#endif extern libusb_context *fpi_usb_ctx; extern GSList *opened_devices; diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index 8bddd5ce..e1330580 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -20,7 +20,9 @@ #include #include +#ifdef REQUIRE_IMAGEMAGICK #include +#endif #include "fp_internal.h" @@ -87,6 +89,7 @@ static int dev_change_state(struct fp_img_dev *imgdev, return imgdrv->change_state(imgdev, state); } +#ifdef REQUIRE_IMAGEMAGICK static struct fp_img *im_resize(struct fp_img *img, unsigned int factor) { Image *mimg; @@ -129,6 +132,7 @@ static struct fp_img *im_resize(struct fp_img *img, unsigned int factor) return newimg; } +#endif /* check image properties and resize it if necessary. potentially returns a new * image after freeing the old one. */ @@ -157,6 +161,7 @@ static int sanitize_image(struct fp_img_dev *imgdev, struct fp_img **_img) return -EINVAL; } +#ifdef REQUIRE_IMAGEMAGICK if (imgdrv->enlarge_factor > 1) { /* FIXME: enlarge_factor should not exist! instead, MINDTCT should * actually look at the value of the pixels-per-mm parameter and @@ -166,6 +171,7 @@ static int sanitize_image(struct fp_img_dev *imgdev, struct fp_img **_img) fp_img_free(img); *_img = tmp; } +#endif return 0; } From 6b8b17f575f5932ebe865d1db93a2807a49b961b Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sun, 10 Aug 2008 14:34:44 -0500 Subject: [PATCH 139/184] Split imagemagick hack from main library Cleans up the conditional compilation system --- libfprint/Makefile.am | 3 +- libfprint/drivers/aes4000.c | 22 ++++++++---- libfprint/fp_internal.h | 2 +- libfprint/imagemagick.c | 67 +++++++++++++++++++++++++++++++++++++ libfprint/imgdev.c | 67 ++----------------------------------- 5 files changed, 88 insertions(+), 73 deletions(-) create mode 100644 libfprint/imagemagick.c diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 9c53c891..844b09ed 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -91,7 +91,8 @@ DRIVER_SRC += $(AES4000_SRC) endif if REQUIRE_IMAGEMAGICK -libfprint_la_CFLAGS += $(IMAGEMAGICK_CFLAGS) -DREQUIRE_IMAGEMAGICK +OTHER_SRC += imagemagick.c +libfprint_la_CFLAGS += $(IMAGEMAGICK_CFLAGS) libfprint_la_LIBADD += $(IMAGEMAGICK_LIBS) endif diff --git a/libfprint/drivers/aes4000.c b/libfprint/drivers/aes4000.c index 51613ba1..a8f71e6a 100644 --- a/libfprint/drivers/aes4000.c +++ b/libfprint/drivers/aes4000.c @@ -34,6 +34,10 @@ #define NR_SUBARRAYS 6 #define SUBARRAY_LEN 768 +#define IMG_HEIGHT 96 +#define IMG_WIDTH 96 +#define ENLARGE_FACTOR 3 + struct aes4k_dev { struct libusb_transfer *img_trf; }; @@ -120,6 +124,7 @@ static void img_cb(struct libusb_transfer *transfer) struct fp_img_dev *dev = transfer->user_data; struct aes4k_dev *aesdev = dev->priv; unsigned char *ptr = transfer->buffer; + struct fp_img *tmp; struct fp_img *img; int i; @@ -135,15 +140,21 @@ static void img_cb(struct libusb_transfer *transfer) fpi_imgdev_report_finger_status(dev, TRUE); - img = fpi_img_new_for_imgdev(dev); - img->flags = FP_IMG_COLORS_INVERTED | FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED; + tmp = fpi_img_new(IMG_WIDTH * IMG_HEIGHT); + tmp->width = IMG_WIDTH; + tmp->height = IMG_HEIGHT; + tmp->flags = FP_IMG_COLORS_INVERTED | FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED; for (i = 0; i < NR_SUBARRAYS; i++) { fp_dbg("subarray header byte %02x", *ptr); ptr++; - aes_assemble_image(ptr, 96, 16, img->data + (i * 96 * 16)); + aes_assemble_image(ptr, 96, 16, tmp->data + (i * 96 * 16)); ptr += SUBARRAY_LEN; } + /* FIXME: this is an ugly hack to make the image big enough for NBIS + * to process reliably */ + img = fpi_im_resize(tmp, ENLARGE_FACTOR); + fp_img_free(tmp); fpi_imgdev_image_captured(dev, img); /* FIXME: rather than assuming finger has gone, we should poll regs until @@ -244,9 +255,8 @@ struct fp_img_driver aes4000_driver = { .id_table = id_table, }, .flags = 0, - .img_height = 96, - .img_width = 96, - .enlarge_factor = 3, + .img_height = IMG_HEIGHT * ENLARGE_FACTOR, + .img_width = IMG_WIDTH * ENLARGE_FACTOR, /* temporarily lowered until image quality improves */ .bz3_threshold = 9, diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index dde69cda..01f55659 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -222,7 +222,6 @@ struct fp_img_driver { uint16_t flags; int img_width; int img_height; - unsigned int enlarge_factor; int bz3_threshold; /* Device operations */ @@ -346,6 +345,7 @@ int fpi_img_compare_print_data(struct fp_print_data *enrolled_print, struct fp_print_data *new_print); int fpi_img_compare_print_data_to_gallery(struct fp_print_data *print, struct fp_print_data **gallery, int match_threshold, size_t *match_offset); +struct fp_img *fpi_im_resize(struct fp_img *img, unsigned int factor); /* polling and timeouts */ diff --git a/libfprint/imagemagick.c b/libfprint/imagemagick.c new file mode 100644 index 00000000..ed6a1cad --- /dev/null +++ b/libfprint/imagemagick.c @@ -0,0 +1,67 @@ +/* + * Imaging utility functions for libfprint + * Copyright (C) 2007-2008 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include + +#include "fp_internal.h" + +struct fp_img *fpi_im_resize(struct fp_img *img, unsigned int factor) +{ + Image *mimg; + Image *resized; + ExceptionInfo exception; + MagickBooleanType ret; + int new_width = img->width * factor; + int new_height = img->height * factor; + struct fp_img *newimg; + + /* It is possible to implement resizing using a simple algorithm, however + * we use ImageMagick because it applies some kind of smoothing to the + * result, which improves matching performances in my experiments. */ + + if (!IsMagickInstantiated()) + InitializeMagick(NULL); + + GetExceptionInfo(&exception); + mimg = ConstituteImage(img->width, img->height, "I", CharPixel, img->data, + &exception); + + GetExceptionInfo(&exception); + resized = ResizeImage(mimg, new_width, new_height, 0, 1.0, &exception); + + newimg = fpi_img_new(new_width * new_height); + newimg->width = new_width; + newimg->height = new_height; + newimg->flags = img->flags; + + GetExceptionInfo(&exception); + ret = ExportImagePixels(resized, 0, 0, new_width, new_height, "I", + CharPixel, newimg->data, &exception); + if (ret != MagickTrue) { + fp_err("export failed"); + return NULL; + } + + DestroyImage(mimg); + DestroyImage(resized); + + return newimg; +} + diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index e1330580..4b49c73e 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -20,9 +20,6 @@ #include #include -#ifdef REQUIRE_IMAGEMAGICK -#include -#endif #include "fp_internal.h" @@ -89,51 +86,6 @@ static int dev_change_state(struct fp_img_dev *imgdev, return imgdrv->change_state(imgdev, state); } -#ifdef REQUIRE_IMAGEMAGICK -static struct fp_img *im_resize(struct fp_img *img, unsigned int factor) -{ - Image *mimg; - Image *resized; - ExceptionInfo exception; - MagickBooleanType ret; - int new_width = img->width * factor; - int new_height = img->height * factor; - struct fp_img *newimg; - - /* It is possible to implement resizing using a simple algorithm, however - * we use ImageMagick because it applies some kind of smoothing to the - * result, which improves matching performances in my experiments. */ - - if (!IsMagickInstantiated()) - InitializeMagick(NULL); - - GetExceptionInfo(&exception); - mimg = ConstituteImage(img->width, img->height, "I", CharPixel, img->data, - &exception); - - GetExceptionInfo(&exception); - resized = ResizeImage(mimg, new_width, new_height, 0, 1.0, &exception); - - newimg = fpi_img_new(new_width * new_height); - newimg->width = new_width; - newimg->height = new_height; - newimg->flags = img->flags; - - GetExceptionInfo(&exception); - ret = ExportImagePixels(resized, 0, 0, new_width, new_height, "I", - CharPixel, newimg->data, &exception); - if (ret != MagickTrue) { - fp_err("export failed"); - return NULL; - } - - DestroyImage(mimg); - DestroyImage(resized); - - return newimg; -} -#endif - /* check image properties and resize it if necessary. potentially returns a new * image after freeing the old one. */ static int sanitize_image(struct fp_img_dev *imgdev, struct fp_img **_img) @@ -161,17 +113,6 @@ static int sanitize_image(struct fp_img_dev *imgdev, struct fp_img **_img) return -EINVAL; } -#ifdef REQUIRE_IMAGEMAGICK - if (imgdrv->enlarge_factor > 1) { - /* FIXME: enlarge_factor should not exist! instead, MINDTCT should - * actually look at the value of the pixels-per-mm parameter and - * figure out itself when the image needs to be treated as if it - * were bigger. */ - struct fp_img *tmp = im_resize(img, imgdrv->enlarge_factor); - fp_img_free(img); - *_img = tmp; - } -#endif return 0; } @@ -392,9 +333,7 @@ int fpi_imgdev_get_img_width(struct fp_img_dev *imgdev) struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); int width = imgdrv->img_width; - if (width > 0 && imgdrv->enlarge_factor > 1) - width *= imgdrv->enlarge_factor; - else if (width == -1) + if (width == -1) width = 0; return width; @@ -406,9 +345,7 @@ int fpi_imgdev_get_img_height(struct fp_img_dev *imgdev) struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); int height = imgdrv->img_height; - if (height > 0 && imgdrv->enlarge_factor > 1) - height *= imgdrv->enlarge_factor; - else if (height == -1) + if (height == -1) height = 0; return height; From d94ffa22d5c2e05c4fe1a296720d3c01151983bf Mon Sep 17 00:00:00 2001 From: Gordon Stratton Date: Fri, 31 Oct 2008 23:36:55 +0000 Subject: [PATCH 140/184] Missing parameter in fp_err call --- libfprint/core.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libfprint/core.c b/libfprint/core.c index 7cfea43b..4bd617ce 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -319,7 +319,7 @@ void fpi_log(enum fpi_log_level level, const char *component, static void register_driver(struct fp_driver *drv) { if (drv->id == 0) { - fp_err("not registering driver %s: driver ID is 0"); + fp_err("not registering driver %s: driver ID is 0", drv->name); return; } registered_drivers = g_slist_prepend(registered_drivers, (gpointer) drv); From 7672c43cea603f55e04eceab1d85b9a850400af4 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sun, 2 Nov 2008 11:03:32 +0000 Subject: [PATCH 141/184] distcheck "" fix Pointed out by Bastien Nocera --- libfprint/Makefile.am | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 844b09ed..056eb676 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -10,8 +10,8 @@ AES4000_SRC = drivers/aes4000.c FDU2000_SRC = drivers/fdu2000.c VCOM5S_SRC = drivers/vcom5s.c -DRIVER_SRC = "" -OTHER_SRC = "" +DRIVER_SRC = +OTHER_SRC = NBIS_SRC = \ nbis/include/bozorth.h \ From 7c83b6d825f27b1afb7e61dfed7a4ead2e506699 Mon Sep 17 00:00:00 2001 From: Bastien Nocera Date: Thu, 30 Oct 2008 15:02:52 +0000 Subject: [PATCH 142/184] Tag fingerprint devices in HAL Tag all the fprint supported devices in HAL. Patch from myself and Timo Hoenig . --- libfprint/Makefile.am | 12 +++++ libfprint/core.c | 18 +++++++ libfprint/fp_internal.h | 2 + libfprint/fprint-list-hal-info.c | 84 ++++++++++++++++++++++++++++++++ 4 files changed, 116 insertions(+) create mode 100644 libfprint/fprint-list-hal-info.c diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 056eb676..026a710c 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -1,4 +1,5 @@ lib_LTLIBRARIES = libfprint.la +noinst_PROGRAMS = fprint-list-hal-info UPEKTS_SRC = drivers/upekts.c UPEKTC_SRC = drivers/upektc.c @@ -54,6 +55,17 @@ libfprint_la_CFLAGS = -fvisibility=hidden -I$(srcdir)/nbis/include $(LIBUSB_CFLA libfprint_la_LDFLAGS = -version-info @lt_major@:@lt_revision@:@lt_age@ libfprint_la_LIBADD = -lm $(LIBUSB_LIBS) $(GLIB_LIBS) $(CRYPTO_LIBS) +fprint_list_hal_info_SOURCES = fprint-list-hal-info.c +fprint_list_hal_info_CFLAGS = -fvisibility=hidden -I$(srcdir)/nbis/include $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) $(IMAGEMAGICK_CFLAGS) $(CRYPTO_CFLAGS) $(AM_CFLAGS) +fprint_list_hal_info_LDADD = $(builddir)/libfprint.la + +hal_fdi_DATA = 10-fingerprint-reader-fprint.fdi +hal_fdidir = $(datadir)/hal/fdi/information/20thirdparty/ + +$(hal_fdi_DATA): fprint-list-hal-info + $(builddir)/fprint-list-hal-info > $@ + + if ENABLE_UPEKTS DRIVER_SRC += $(UPEKTS_SRC) endif diff --git a/libfprint/core.c b/libfprint/core.c index 4bd617ce..acbe08fb 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -375,6 +375,24 @@ static void register_drivers(void) } } +API_EXPORTED struct fp_driver **fprint_get_drivers (void) +{ + GPtrArray *array; + unsigned int i; + + array = g_ptr_array_new (); + for (i = 0; i < G_N_ELEMENTS(primitive_drivers); i++) + g_ptr_array_add (array, primitive_drivers[i]); + + for (i = 0; i < G_N_ELEMENTS(img_drivers); i++) + g_ptr_array_add (array, &(img_drivers[i]->driver)); + + /* Add a null item terminating the array */ + g_ptr_array_add (array, NULL); + + return (struct fp_driver **) g_ptr_array_free (array, FALSE); +} + static struct fp_driver *find_supporting_driver(libusb_device *udev, const struct usb_id **usb_id) { diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 01f55659..5483d11f 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -91,6 +91,8 @@ enum fp_dev_state { DEV_STATE_IDENTIFY_STOPPING, }; +struct fp_driver **fprint_get_drivers (void); + struct fp_dev { struct fp_driver *drv; libusb_device_handle *udev; diff --git a/libfprint/fprint-list-hal-info.c b/libfprint/fprint-list-hal-info.c new file mode 100644 index 00000000..6182b130 --- /dev/null +++ b/libfprint/fprint-list-hal-info.c @@ -0,0 +1,84 @@ +/* + * Helper binary for creating a HAL FDI file for supported devices + * Copyright (C) 2008 Bastien Nocera + * Copyright (C) 2008 Timo Hoenig , + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include + +#include "fp_internal.h" + +/* FDI entry example: + * + * + * + * + * biometric.fingerprint_reader + * libfprint + * biometric + * biometric.fingerprint_reader + * aes2501 + * true + * + * + * + */ + +static void print_driver (struct fp_driver *driver) +{ + int i; + + for (i = 0; driver->id_table[i].vendor != 0; i++) { + printf (" \n", fp_driver_get_full_name (driver)); + printf (" \n", driver->id_table[i].vendor); + printf (" \n", driver->id_table[i].product); + printf (" biometric.fingerprint_reader\n"); + printf (" libfprint\n"); + printf (" biometric\n"); + printf (" biometric.fingerprint_reader\n"); + printf (" %s\n", driver->name); + printf (" true\n"); + printf (" \n"); + printf (" \n"); + } +} + +static void print_imaging_driver (struct fp_img_driver *driver) +{ + print_driver (&(driver->driver)); +} + +int main (int argc, char **argv) +{ + struct fp_driver **list; + guint i; + + list = fprint_get_drivers (); + + printf ("\n"); + printf ("\n", VERSION); + printf ("\n"); + + for (i = 0; list[i] != NULL; i++) { + print_driver (list[i]); + } + + printf ("\n"); + + return 0; +} From 2d30e40ed750d4ccd2a1eea6b2398bbf3275b39f Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sun, 2 Nov 2008 14:49:39 +0000 Subject: [PATCH 143/184] aes2501: Add AES2500 ID Reported to work with Motion Computing M1400 tablet by Daniel Hazelbaker and Alex Van Deusen. --- libfprint/drivers/aes2501.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libfprint/drivers/aes2501.c b/libfprint/drivers/aes2501.c index e6f3b866..d60f1f75 100644 --- a/libfprint/drivers/aes2501.c +++ b/libfprint/drivers/aes2501.c @@ -938,7 +938,8 @@ static void dev_deinit(struct fp_img_dev *dev) } static const struct usb_id id_table[] = { - { .vendor = 0x08ff, .product = 0x2580 }, + { .vendor = 0x08ff, .product = 0x2500 }, /* AES2500 */ + { .vendor = 0x08ff, .product = 0x2580 }, /* AES2501 */ { 0, 0, 0, }, }; From b93f038dbc35b8b8875a26d01811dd4e3dabeac4 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Tue, 18 Nov 2008 17:18:05 +0000 Subject: [PATCH 144/184] distcheck fix for fdi file --- libfprint/Makefile.am | 1 + 1 file changed, 1 insertion(+) diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 026a710c..0eb5ca65 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -1,5 +1,6 @@ lib_LTLIBRARIES = libfprint.la noinst_PROGRAMS = fprint-list-hal-info +MOSTLYCLEANFILES = $(hal_fdi_DATA) UPEKTS_SRC = drivers/upekts.c UPEKTC_SRC = drivers/upektc.c From 1fd247ecd7fb000260f2a457e264dcb6f1d09d98 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Tue, 18 Nov 2008 17:10:49 +0000 Subject: [PATCH 145/184] v0.1.0-pre1 release because Bastien asked nicely. No guarantees about API or stability. --- THANKS | 1 + configure.ac | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/THANKS b/THANKS index 86812718..ea754c12 100644 --- a/THANKS +++ b/THANKS @@ -7,3 +7,4 @@ James Vasile (SFLC) Toby Howard (University of Manchester) Seemant Kulleen Pavel Herrman +Bastien Nocera diff --git a/configure.ac b/configure.ac index d77340fc..778e7ad4 100644 --- a/configure.ac +++ b/configure.ac @@ -1,4 +1,4 @@ -AC_INIT([libfprint], [0.1.0-pre]) +AC_INIT([libfprint], [0.1.0-pre1]) AM_INIT_AUTOMAKE AC_CONFIG_SRCDIR([libfprint/core.c]) AM_CONFIG_HEADER([config.h]) From 29044d9ca95646596c8c817d470c01381f4b8f9f Mon Sep 17 00:00:00 2001 From: Bastien Nocera Date: Thu, 20 Nov 2008 14:40:01 +0000 Subject: [PATCH 146/184] Export scan type for each driver For each driver, export the scan type supported by the devices it handles. This allows front-ends to direct the user better. --- libfprint/core.c | 10 ++++++++++ libfprint/drivers/aes1610.c | 1 + libfprint/drivers/aes2501.c | 1 + libfprint/drivers/aes4000.c | 1 + libfprint/drivers/fdu2000.c | 1 + libfprint/drivers/upeksonly.c | 1 + libfprint/drivers/upektc.c | 1 + libfprint/drivers/upekts.c | 1 + libfprint/drivers/uru4000.c | 1 + libfprint/drivers/vcom5s.c | 1 + libfprint/fp_internal.h | 1 + libfprint/fprint.h | 11 +++++++++++ 12 files changed, 31 insertions(+) diff --git a/libfprint/core.c b/libfprint/core.c index acbe08fb..b3acea6f 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -710,6 +710,16 @@ API_EXPORTED uint16_t fp_driver_get_driver_id(struct fp_driver *drv) return drv->id; } +/** \ingroup drv + * Retrieves the scan type for the devices associated with the driver. + * \param drv the driver + * \returns the scan type + */ +API_EXPORTED enum fp_scan_type fp_driver_get_scan_type(struct fp_driver *drv) +{ + return drv->scan_type; +} + static struct fp_img_dev *dev_to_img_dev(struct fp_dev *dev) { if (dev->drv->type != DRIVER_IMAGING) diff --git a/libfprint/drivers/aes1610.c b/libfprint/drivers/aes1610.c index 7ef5fe27..318195fe 100644 --- a/libfprint/drivers/aes1610.c +++ b/libfprint/drivers/aes1610.c @@ -532,6 +532,7 @@ struct fp_img_driver aes1610_driver = { .name = FP_COMPONENT, .full_name = "AuthenTec AES1610", .id_table = id_table, + .scan_type = FP_SCAN_TYPE_SWIPE, }, .flags = 0, .img_height = -1, diff --git a/libfprint/drivers/aes2501.c b/libfprint/drivers/aes2501.c index d60f1f75..617bb64f 100644 --- a/libfprint/drivers/aes2501.c +++ b/libfprint/drivers/aes2501.c @@ -949,6 +949,7 @@ struct fp_img_driver aes2501_driver = { .name = FP_COMPONENT, .full_name = "AuthenTec AES2501", .id_table = id_table, + .scan_type = FP_SCAN_TYPE_SWIPE, }, .flags = 0, .img_height = -1, diff --git a/libfprint/drivers/aes4000.c b/libfprint/drivers/aes4000.c index a8f71e6a..02dc9e8d 100644 --- a/libfprint/drivers/aes4000.c +++ b/libfprint/drivers/aes4000.c @@ -253,6 +253,7 @@ struct fp_img_driver aes4000_driver = { .name = FP_COMPONENT, .full_name = "AuthenTec AES4000", .id_table = id_table, + .scan_type = FP_SCAN_TYPE_PRESS, }, .flags = 0, .img_height = IMG_HEIGHT * ENLARGE_FACTOR, diff --git a/libfprint/drivers/fdu2000.c b/libfprint/drivers/fdu2000.c index 0e6c53b1..c9afb0bf 100644 --- a/libfprint/drivers/fdu2000.c +++ b/libfprint/drivers/fdu2000.c @@ -309,6 +309,7 @@ struct fp_img_driver fdu2000_driver = { .name = FP_COMPONENT, .full_name = "Secugen FDU 2000", .id_table = id_table, + .scan_type = FP_SCAN_TYPE_PRESS, }, .img_height = RAW_IMAGE_HEIGTH, .img_width = RAW_IMAGE_WIDTH, diff --git a/libfprint/drivers/upeksonly.c b/libfprint/drivers/upeksonly.c index a8f29860..f41a6be8 100644 --- a/libfprint/drivers/upeksonly.c +++ b/libfprint/drivers/upeksonly.c @@ -1022,6 +1022,7 @@ struct fp_img_driver upeksonly_driver = { .name = FP_COMPONENT, .full_name = "UPEK TouchStrip Sensor-Only", .id_table = id_table, + .scan_type = FP_SCAN_TYPE_SWIPE, }, .flags = 0, .img_width = IMG_WIDTH, diff --git a/libfprint/drivers/upektc.c b/libfprint/drivers/upektc.c index 1723287a..e115537f 100644 --- a/libfprint/drivers/upektc.c +++ b/libfprint/drivers/upektc.c @@ -402,6 +402,7 @@ struct fp_img_driver upektc_driver = { .name = FP_COMPONENT, .full_name = "UPEK TouchChip", .id_table = id_table, + .scan_type = FP_SCAN_TYPE_PRESS, }, .flags = FP_IMGDRV_SUPPORTS_UNCONDITIONAL_CAPTURE, .img_height = 288, diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index df648301..5553d8e5 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -1465,6 +1465,7 @@ struct fp_driver upekts_driver = { .name = FP_COMPONENT, .full_name = "UPEK TouchStrip", .id_table = id_table, + .scan_type = FP_SCAN_TYPE_SWIPE, .open = dev_init, .close = dev_exit, .enroll_start = enroll_start, diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index e9e40f99..b230c03c 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -1227,6 +1227,7 @@ struct fp_img_driver uru4000_driver = { .name = FP_COMPONENT, .full_name = "Digital Persona U.are.U 4000/4000B", .id_table = id_table, + .scan_type = FP_SCAN_TYPE_PRESS, }, .flags = FP_IMGDRV_SUPPORTS_UNCONDITIONAL_CAPTURE, .img_height = 289, diff --git a/libfprint/drivers/vcom5s.c b/libfprint/drivers/vcom5s.c index c02873b6..0bc5724e 100644 --- a/libfprint/drivers/vcom5s.c +++ b/libfprint/drivers/vcom5s.c @@ -372,6 +372,7 @@ struct fp_img_driver vcom5s_driver = { .name = FP_COMPONENT, .full_name = "Veridicom 5thSense", .id_table = id_table, + .scan_type = FP_SCAN_TYPE_PRESS, }, .flags = 0, .img_height = IMG_HEIGHT, diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 5483d11f..bebf3241 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -199,6 +199,7 @@ struct fp_driver { const char *full_name; const struct usb_id * const id_table; enum fp_driver_type type; + enum fp_scan_type scan_type; void *priv; diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 96450044..29e6eb18 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -51,10 +51,21 @@ enum fp_finger { RIGHT_LITTLE, /** little finger (right hand) */ }; +/** \ingroup dev + * Numeric codes used to refer to the scan type of the device. Devices require + * either swiping or pressing the finger on the device. This is useful for + * front-ends. + */ +enum fp_scan_type { + FP_SCAN_TYPE_PRESS = 0, /** press */ + FP_SCAN_TYPE_SWIPE, /** swipe */ +}; + /* Drivers */ const char *fp_driver_get_name(struct fp_driver *drv); const char *fp_driver_get_full_name(struct fp_driver *drv); uint16_t fp_driver_get_driver_id(struct fp_driver *drv); +enum fp_scan_type fp_driver_get_scan_type(struct fp_driver *drv); /* Device discovery */ struct fp_dscv_dev **fp_discover_devs(void); From 7c44c86d4c8838a69d93225bbe3e31f4e7427445 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Thu, 20 Nov 2008 17:23:04 +0000 Subject: [PATCH 147/184] Logging control Don't log anything by default, and let the applications change the log level. --- examples/enroll.c | 1 + examples/img_capture.c | 1 + examples/img_capture_continuous.c | 1 + examples/verify.c | 1 + examples/verify_live.c | 1 + libfprint/core.c | 65 +++++++++++++++++++++++++++++-- libfprint/fprint.h | 1 + 7 files changed, 68 insertions(+), 3 deletions(-) diff --git a/examples/enroll.c b/examples/enroll.c index 7d077881..f2ba9bec 100644 --- a/examples/enroll.c +++ b/examples/enroll.c @@ -115,6 +115,7 @@ int main(void) fprintf(stderr, "Failed to initialize libfprint\n"); exit(1); } + fp_set_debug(3); discovered_devs = fp_discover_devs(); if (!discovered_devs) { diff --git a/examples/img_capture.c b/examples/img_capture.c index d45b8b85..65280317 100644 --- a/examples/img_capture.c +++ b/examples/img_capture.c @@ -47,6 +47,7 @@ int main(void) fprintf(stderr, "Failed to initialize libfprint\n"); exit(1); } + fp_set_debug(3); discovered_devs = fp_discover_devs(); if (!discovered_devs) { diff --git a/examples/img_capture_continuous.c b/examples/img_capture_continuous.c index 752f7101..701fd699 100644 --- a/examples/img_capture_continuous.c +++ b/examples/img_capture_continuous.c @@ -146,6 +146,7 @@ int main(void) fprintf(stderr, "Failed to initialize libfprint\n"); exit(1); } + fp_set_debug(3); discovered_devs = fp_discover_devs(); if (!discovered_devs) { diff --git a/examples/verify.c b/examples/verify.c index 1e1dd4fb..60a2ccb6 100644 --- a/examples/verify.c +++ b/examples/verify.c @@ -91,6 +91,7 @@ int main(void) fprintf(stderr, "Failed to initialize libfprint\n"); exit(1); } + fp_set_debug(3); discovered_devs = fp_discover_devs(); if (!discovered_devs) { diff --git a/examples/verify_live.c b/examples/verify_live.c index 9a7b6a98..27acb3ba 100644 --- a/examples/verify_live.c +++ b/examples/verify_live.c @@ -134,6 +134,7 @@ int main(void) fprintf(stderr, "Failed to initialize libfprint\n"); exit(1); } + fp_set_debug(3); discovered_devs = fp_discover_devs(); if (!discovered_devs) { diff --git a/libfprint/core.c b/libfprint/core.c index b3acea6f..37a4e038 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -20,12 +20,16 @@ #include #include #include +#include #include #include #include "fp_internal.h" +static int log_level = 0; +static int log_level_fixed = 0; + libusb_context *fpi_usb_ctx = NULL; GSList *opened_devices = NULL; @@ -41,13 +45,13 @@ GSList *opened_devices = NULL; * designed so that you only have to do this once - by integrating your * software with libfprint, you'll be supporting all the fingerprint readers * that we have got our hands on. As such, the API is rather general (and - * therefore hopefully easy to comprehend!), and does it's best to hide the + * therefore hopefully easy to comprehend!), and does its best to hide the * technical details that required to operate the hardware. * * This documentation is not aimed at developers wishing to develop and * contribute fingerprint device drivers to libfprint. * - * Feedback on this API and it's associated documentation is appreciated. Was + * Feedback on this API and its associated documentation is appreciated. Was * anything unclear? Does anything seem unreasonably complicated? Is anything * missing? Let us know on the * mailing list. @@ -284,6 +288,15 @@ void fpi_log(enum fpi_log_level level, const char *component, FILE *stream = stdout; const char *prefix; +#ifndef ENABLE_DEBUG_LOGGING + if (!log_level) + return; + if (level == LOG_LEVEL_WARNING && log_level < 2) + return; + if (level == LOG_LEVEL_INFO && log_level < 3) + return; +#endif + switch (level) { case LOG_LEVEL_INFO: prefix = "info"; @@ -826,6 +839,44 @@ API_EXPORTED int fp_dev_get_img_height(struct fp_dev *dev) return fpi_imgdev_get_img_height(imgdev); } +/** \ingroup core + * Set message verbosity. + * - Level 0: no messages ever printed by the library (default) + * - Level 1: error messages are printed to stderr + * - Level 2: warning and error messages are printed to stderr + * - Level 3: informational messages are printed to stdout, warning and error + * messages are printed to stderr + * + * The default level is 0, which means no messages are ever printed. If you + * choose to increase the message verbosity level, ensure that your + * application does not close the stdout/stderr file descriptors. + * + * You are advised to set level 3. libfprint is conservative with its message + * logging and most of the time, will only log messages that explain error + * conditions and other oddities. This will help you debug your software. + * + * If the LIBFPRINT_DEBUG environment variable was set when libfprint was + * initialized, this function does nothing: the message verbosity is fixed + * to the value in the environment variable. + * + * If libfprint was compiled without any message logging, this function does + * nothing: you'll never get any messages. + * + * If libfprint was compiled with verbose debug message logging, this function + * does nothing: you'll always get messages from all levels. + * + * \param ctx the context to operate on, or NULL for the default context + * \param level debug level to set + */ +API_EXPORTED void fp_set_debug(int level) +{ + if (log_level_fixed) + return; + + log_level = level; + libusb_set_debug(fpi_usb_ctx, level); +} + /** \ingroup core * Initialise libfprint. This function must be called before you attempt to * use the library in any way. @@ -833,6 +884,7 @@ API_EXPORTED int fp_dev_get_img_height(struct fp_dev *dev) */ API_EXPORTED int fp_init(void) { + char *dbg = getenv("LIBFPRINT_DEBUG"); int r; fp_dbg(""); @@ -840,7 +892,14 @@ API_EXPORTED int fp_init(void) if (r < 0) return r; - libusb_set_debug(fpi_usb_ctx, 3); + if (dbg) { + log_level = atoi(dbg); + if (log_level) { + log_level_fixed = 1; + libusb_set_debug(fpi_usb_ctx, log_level); + } + } + register_drivers(); fpi_poll_init(); return 0; diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 29e6eb18..319b600f 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -297,6 +297,7 @@ void fp_set_pollfd_notifiers(fp_pollfd_added_cb added_cb, /* Library */ int fp_init(void); void fp_exit(void); +void fp_set_debug(int level); /* Asynchronous I/O */ From d4822283256e153b1d8b61c4126617abcf291f43 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Thu, 20 Nov 2008 19:59:43 +0000 Subject: [PATCH 148/184] upekts: Don't choke on non-zero bytes in command response Alon Bar-Lev's device behaves differently, but seems to work fine with upekts even if we ignore the difference. --- libfprint/drivers/upekts.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/libfprint/drivers/upekts.c b/libfprint/drivers/upekts.c index 5553d8e5..a67cd943 100644 --- a/libfprint/drivers/upekts.c +++ b/libfprint/drivers/upekts.c @@ -321,10 +321,13 @@ static int __handle_incoming_msg(struct read_msg_data *udata, fp_err("cmd response without 28 byte?"); return -1; } - if (innerbuf[3] || innerbuf[4]) { - fp_err("non-zero bytes in cmd response"); - return -1; - } + + /* not really sure what these 2 bytes are. on most people's hardware, + * these bytes are always 0. However, Alon Bar-Lev's hardware gives + * 0xfb 0xff during the READ28_OB initsm stage. so don't error out + * if they are different... */ + if (innerbuf[3] || innerbuf[4]) + fp_dbg("non-zero bytes in cmd response"); innerlen = innerbuf[1] | (innerbuf[2] << 8); innerlen = GUINT16_FROM_LE(innerlen) - 3; From 749bb3e30ebfc08be26bd849753a0e169d46b504 Mon Sep 17 00:00:00 2001 From: Bastien Nocera Date: Mon, 24 Nov 2008 15:31:21 +0000 Subject: [PATCH 149/184] Export scan type through HAL Also export the scan type through HAL. --- libfprint/fprint-list-hal-info.c | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/libfprint/fprint-list-hal-info.c b/libfprint/fprint-list-hal-info.c index 6182b130..13d24d60 100644 --- a/libfprint/fprint-list-hal-info.c +++ b/libfprint/fprint-list-hal-info.c @@ -53,16 +53,13 @@ static void print_driver (struct fp_driver *driver) printf (" biometric.fingerprint_reader\n"); printf (" %s\n", driver->name); printf (" true\n"); + printf (" %s\n", + fp_driver_get_scan_type (driver) == FP_SCAN_TYPE_PRESS ? "press" : "swipe"); printf (" \n"); printf (" \n"); } } -static void print_imaging_driver (struct fp_img_driver *driver) -{ - print_driver (&(driver->driver)); -} - int main (int argc, char **argv) { struct fp_driver **list; From d816fed5c384e6d45ae11e2530883d54aacedf4b Mon Sep 17 00:00:00 2001 From: Bastien Nocera Date: Tue, 25 Nov 2008 15:54:25 +0000 Subject: [PATCH 150/184] Disable finger_num_to_str when debugging is disabled One less warning. --- libfprint/data.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libfprint/data.c b/libfprint/data.c index 861c5f34..3371a0c2 100644 --- a/libfprint/data.c +++ b/libfprint/data.c @@ -73,6 +73,7 @@ void fpi_data_exit(void) ((finger) >= LEFT_THUMB && (finger) <= RIGHT_LITTLE) /* for debug messages only */ +#ifdef ENABLE_DEBUG_LOGGING static const char *finger_num_to_str(enum fp_finger finger) { const char *names[] = { @@ -91,6 +92,7 @@ static const char *finger_num_to_str(enum fp_finger finger) return "UNKNOWN"; return names[finger]; } +#endif static struct fp_print_data *print_data_new(uint16_t driver_id, uint32_t devtype, enum fp_print_data_type type, size_t length) From e5da34e80a1cc6f5af480cc5343dd48d52c60a96 Mon Sep 17 00:00:00 2001 From: Bastien Nocera Date: Tue, 25 Nov 2008 15:54:56 +0000 Subject: [PATCH 151/184] Fix fp_get_pollfds() It was increasing i too early, and writing past the allocated structures. --- libfprint/poll.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libfprint/poll.c b/libfprint/poll.c index a8529058..f78b6586 100644 --- a/libfprint/poll.c +++ b/libfprint/poll.c @@ -308,9 +308,10 @@ API_EXPORTED size_t fp_get_pollfds(struct fp_pollfd **pollfds) ret = g_malloc(sizeof(struct fp_pollfd) * cnt); i = 0; - while ((usbfd = usbfds[i++]) != NULL) { + while ((usbfd = usbfds[i]) != NULL) { ret[i].fd = usbfd->fd; ret[i].events = usbfd->events; + i++; } *pollfds = ret; From a51763bd9993da7de78f19701cd62c7b7d147bf4 Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 20 Jun 2009 14:50:23 +0100 Subject: [PATCH 152/184] New sourceforge file upload system --- Makefile.am | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile.am b/Makefile.am index 4c63a157..f85910c1 100644 --- a/Makefile.am +++ b/Makefile.am @@ -18,4 +18,4 @@ ChangeLog: dist-hook: ChangeLog dist-up: dist - ncftpput upload.sourceforge.net incoming $(distdir).tar.bz2 + rsync $(distdir).tar.bz2 frs.sourceforge.net:uploads/ From 911c6bf102760ba49bcc2f851a7bd7d9cebff46e Mon Sep 17 00:00:00 2001 From: Daniel Drake Date: Sat, 20 Jun 2009 14:50:35 +0100 Subject: [PATCH 153/184] v0.1.0-pre2 release --- Makefile.am | 1 + configure.ac | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/Makefile.am b/Makefile.am index f85910c1..aff8410c 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1,4 +1,5 @@ AUTOMAKE_OPTIONS = dist-bzip2 +ACLOCAL_AMFLAGS = -I m4 EXTRA_DIST = THANKS TODO HACKING libfprint.pc.in DISTCLEANFILES = ChangeLog libfprint.pc diff --git a/configure.ac b/configure.ac index 778e7ad4..e53136d4 100644 --- a/configure.ac +++ b/configure.ac @@ -1,5 +1,6 @@ -AC_INIT([libfprint], [0.1.0-pre1]) +AC_INIT([libfprint], [0.1.0-pre2]) AM_INIT_AUTOMAKE +AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_SRCDIR([libfprint/core.c]) AM_CONFIG_HEADER([config.h]) From 014b933b2bf635dab4ccbb9beb15be8d55a9d427 Mon Sep 17 00:00:00 2001 From: Bastien Nocera Date: Wed, 29 Oct 2008 12:53:24 +0000 Subject: [PATCH 154/184] Add gdk-pixbuf support When imaging support is required, we prefer to use gdk-pixbuf, as it's already on things like Live CDs. Also fix the examples building against the system libfprint. --- configure.ac | 30 +++++++++++---- examples/Makefile.am | 10 ++--- libfprint/Makefile.am | 10 ++++- libfprint/gdkpixbuf.c | 88 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 123 insertions(+), 15 deletions(-) create mode 100644 libfprint/gdkpixbuf.c diff --git a/configure.ac b/configure.ac index e53136d4..052ef0e9 100644 --- a/configure.ac +++ b/configure.ac @@ -21,7 +21,7 @@ AC_SUBST(lt_age) all_drivers="upekts upektc upeksonly vcom5s uru4000 fdu2000 aes1610 aes2501 aes4000" -require_imagemagick='no' +require_imaging='no' require_aeslib='no' enable_upekts='no' enable_upektc='no' @@ -77,7 +77,7 @@ for driver in `echo ${drivers} | sed -e 's/,/ /g' -e 's/,$//g'`; do aes4000) AC_DEFINE([ENABLE_AES4000], [], [Build AuthenTec AES4000 driver]) require_aeslib="yes" - require_imagemagick="yes" + require_imaging="yes" enable_aes4000="yes" ;; esac @@ -92,7 +92,6 @@ AM_CONDITIONAL([ENABLE_URU4000], [test "$enable_uru4000" != "no"]) #AM_CONDITIONAL([ENABLE_AES1610], [test "$enable_aes1610" != "no"]) AM_CONDITIONAL([ENABLE_AES2501], [test "$enable_aes2501" != "no"]) AM_CONDITIONAL([ENABLE_AES4000], [test "$enable_aes4000" != "no"]) -AM_CONDITIONAL([REQUIRE_IMAGEMAGICK], [test "$require_imagemagick" != "no"]) AM_CONDITIONAL([REQUIRE_AESLIB], [test "$require_aeslib" != "no"]) @@ -109,11 +108,26 @@ PKG_CHECK_MODULES(GLIB, "glib-2.0") AC_SUBST(GLIB_CFLAGS) AC_SUBST(GLIB_LIBS) -if test "$require_imagemagick" != "no"; then -PKG_CHECK_MODULES(IMAGEMAGICK, "ImageMagick") -AC_SUBST(IMAGEMAGICK_CFLAGS) -AC_SUBST(IMAGEMAGICK_LIBS) -fi; +imagemagick_found=no +gdkpixbuf_found=no + +if test "$require_imaging" != "no"; then + PKG_CHECK_MODULES(IMAGING, gthread-2.0 gdk-pixbuf-2.0, [gdkpixbuf_found=yes], [gdkpixbuf_found=no]) + if test "$gdkpixbuf_found" != "yes"; then + PKG_CHECK_MODULES(IMAGING, ImageMagick, [imagemagick_found=yes], [imagemagick_found=no]) + fi +fi + +if test "$require_imaging" != "no"; then + if test "$gdkpixbuf_found" != "yes" && test "$imagemagick_found" != "yes"; then + AC_MSG_ERROR([gdk-pixbuf or ImageMagick is required for imaging support]) + fi +fi + +AM_CONDITIONAL([REQUIRE_GDKPIXBUF], [test "$gdkpixbuf_found" != "no"]) +AM_CONDITIONAL([REQUIRE_IMAGEMAGICK], [test "$imagemagick_found" != "no"]) +AC_SUBST(IMAGING_CFLAGS) +AC_SUBST(IMAGING_LIBS) # Examples build AC_ARG_ENABLE([examples-build], [AS_HELP_STRING([--enable-examples-build], diff --git a/examples/Makefile.am b/examples/Makefile.am index eb6dedbc..3f891349 100644 --- a/examples/Makefile.am +++ b/examples/Makefile.am @@ -2,22 +2,22 @@ INCLUDES = -I$(top_srcdir) noinst_PROGRAMS = verify_live enroll verify img_capture verify_live_SOURCES = verify_live.c -verify_live_LDADD = ../libfprint/libfprint.la -lfprint +verify_live_LDADD = ../libfprint/libfprint.la enroll_SOURCES = enroll.c -enroll_LDADD = ../libfprint/libfprint.la -lfprint +enroll_LDADD = ../libfprint/libfprint.la verify_SOURCES = verify.c -verify_LDADD = ../libfprint/libfprint.la -lfprint +verify_LDADD = ../libfprint/libfprint.la img_capture_SOURCES = img_capture.c -img_capture_LDADD = ../libfprint/libfprint.la -lfprint +img_capture_LDADD = ../libfprint/libfprint.la if BUILD_X11_EXAMPLES noinst_PROGRAMS += img_capture_continuous img_capture_continuous_CFLAGS = $(X_CFLAGS) $(XV_CFLAGS) img_capture_continuous_SOURCES = img_capture_continuous.c -img_capture_continuous_LDADD = ../libfprint/libfprint.la -lfprint $(X_LIBS) $(X_PRE_LIBS) $(XV_LIBS) -lX11 $(X_EXTRA_LIBS); +img_capture_continuous_LDADD = ../libfprint/libfprint.la $(X_LIBS) $(X_PRE_LIBS) $(XV_LIBS) -lX11 $(X_EXTRA_LIBS); endif diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 0eb5ca65..ebe13f88 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -105,8 +105,14 @@ endif if REQUIRE_IMAGEMAGICK OTHER_SRC += imagemagick.c -libfprint_la_CFLAGS += $(IMAGEMAGICK_CFLAGS) -libfprint_la_LIBADD += $(IMAGEMAGICK_LIBS) +libfprint_la_CFLAGS += $(IMAGING_CFLAGS) +libfprint_la_LIBADD += $(IMAGING_LIBS) +endif + +if REQUIRE_GDKPIXBUF +OTHER_SRC += gdkpixbuf.c +libfprint_la_CFLAGS += $(IMAGING_CFLAGS) +libfprint_la_LIBADD += $(IMAGING_LIBS) endif if REQUIRE_AESLIB diff --git a/libfprint/gdkpixbuf.c b/libfprint/gdkpixbuf.c new file mode 100644 index 00000000..7ffc0990 --- /dev/null +++ b/libfprint/gdkpixbuf.c @@ -0,0 +1,88 @@ +/* + * Imaging utility functions for libfprint + * Copyright (C) 2007-2008 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include + +#include "fp_internal.h" + +struct fp_img *fpi_im_resize(struct fp_img *img, unsigned int factor) +{ + int new_width = img->width * factor; + int new_height = img->height * factor; + GdkPixbuf *orig, *resized; + struct fp_img *newimg; + guchar *pixels; + guint y; + int rowstride; + + g_type_init (); + + /* It is possible to implement resizing using a simple algorithm, however + * we use gdk-pixbuf because it applies some kind of smoothing to the + * result, which improves matching performances in my experiments. */ + + /* Create the original pixbuf, and fill it in from the grayscale data */ + orig = gdk_pixbuf_new (GDK_COLORSPACE_RGB, + FALSE, + 8, + img->width, + img->height); + rowstride = gdk_pixbuf_get_rowstride (orig); + pixels = gdk_pixbuf_get_pixels (orig); + for (y = 0; y < img->height; y++) { + guint x; + for (x = 0; x < img->width; x++) { + guchar *p, *r; + + p = pixels + y * rowstride + x * 3; + r = img->data + y * img->width + x; + p[0] = r[0]; + p[1] = r[0]; + p[2] = r[0]; + } + } + + /* Resize the pixbuf, and create the new fp_img */ + resized = gdk_pixbuf_scale_simple (orig, new_width, new_height, GDK_INTERP_HYPER); + g_object_unref (orig); + + newimg = fpi_img_new(new_width * new_height); + newimg->width = new_width; + newimg->height = new_height; + newimg->flags = img->flags; + + rowstride = gdk_pixbuf_get_rowstride (resized); + pixels = gdk_pixbuf_get_pixels (resized); + for (y = 0; y < newimg->height; y++) { + guint x; + for (x = 0; x < newimg->width; x++) { + guchar *p, *r; + + r = img->data + y * img->width + x; + p = pixels + y * rowstride + x * 3; + r[0] = p[0]; + } + } + + g_object_unref (resized); + + return newimg; +} + From a99e813bbf0cfaa454feda47d11debb98ce6de39 Mon Sep 17 00:00:00 2001 From: Matthew Garrett Date: Thu, 1 Oct 2009 15:08:41 +0100 Subject: [PATCH 155/184] Add udev rules to set devices to autosuspend Most fingerprint readers can be suspended safely, so use the udev rules to autosuspend them when they appear. The script itself contains whitelists and blacklists. --- libfprint/Makefile.am | 13 +++++- libfprint/fprint-list-udev-rules.c | 73 ++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 2 deletions(-) create mode 100644 libfprint/fprint-list-udev-rules.c diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index ebe13f88..c79012bb 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -1,6 +1,6 @@ lib_LTLIBRARIES = libfprint.la -noinst_PROGRAMS = fprint-list-hal-info -MOSTLYCLEANFILES = $(hal_fdi_DATA) +noinst_PROGRAMS = fprint-list-hal-info fprint-list-udev-rules +MOSTLYCLEANFILES = $(hal_fdi_DATA) $(udev_rules_DATA) UPEKTS_SRC = drivers/upekts.c UPEKTC_SRC = drivers/upektc.c @@ -66,6 +66,15 @@ hal_fdidir = $(datadir)/hal/fdi/information/20thirdparty/ $(hal_fdi_DATA): fprint-list-hal-info $(builddir)/fprint-list-hal-info > $@ +fprint_list_udev_rules_SOURCES = fprint-list-udev-rules.c +fprint_list_udev_rules_CFLAGS = -fvisibility=hidden -I$(srcdir)/nbis/include $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) $(IMAGEMAGICK_CFLAGS) $(CRYPTO_CFLAGS) $(AM_CFLAGS) +fprint_list_udev_rules_LDADD = $(builddir)/libfprint.la + +udev_rules_DATA = 60-fprint-autosuspend.rules +udev_rulesdir = $(sysconfdir)/udev/rules.d/ + +$(udev_rules_DATA): fprint-list-udev-rules + $(builddir)/fprint-list-udev-rules > $@ if ENABLE_UPEKTS DRIVER_SRC += $(UPEKTS_SRC) diff --git a/libfprint/fprint-list-udev-rules.c b/libfprint/fprint-list-udev-rules.c new file mode 100644 index 00000000..76a1471c --- /dev/null +++ b/libfprint/fprint-list-udev-rules.c @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2009 Red Hat + * Copyright (C) 2008 Bastien Nocera + * Copyright (C) 2008 Timo Hoenig , + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include + +#include "fp_internal.h" + +static const struct usb_id whitelist_id_table[] = { + { .vendor = 0x08ff, .product = 0x2810 }, + { 0, 0, 0, }, +}; + +static const struct usb_id blacklist_id_table[] = { + { .vendor = 0x0483, .product = 0x2016 }, + { 0, 0, 0 }, +}; + +struct fp_driver whitelist = { + .id_table = whitelist_id_table, +}; + +static void print_driver (struct fp_driver *driver) +{ + int i, j, blacklist; + + for (i = 0; driver->id_table[i].vendor != 0; i++) { + blacklist = 0; + for (j = 0; blacklist_id_table[j].vendor != 0; j++) { + if (driver->id_table[i].vendor == blacklist_id_table[j].vendor && + driver->id_table[j].product == blacklist_id_table[j].product) { + blacklist = 1; + } + } + if (blacklist) + continue; + + printf ("SUBSYSTEM==\"usb\", ATTRS{idVendor}==\"%04x\", ATTRS{idProduct}==\"%04x\", ATTRS{dev}==\"*\", ATTR{power/level}=\"auto\"\n", driver->id_table[i].vendor, driver->id_table[i].product); + } +} + +int main (int argc, char **argv) +{ + struct fp_driver **list; + guint i; + + list = fprint_get_drivers (); + + for (i = 0; list[i] != NULL; i++) { + print_driver (list[i]); + } + + print_driver (&whitelist); + + return 0; +} From 7c7402a697eb7f4d1c2c929922cbd88945d2616f Mon Sep 17 00:00:00 2001 From: Guido Grazioli Date: Tue, 17 Aug 2010 11:36:34 +0100 Subject: [PATCH 156/184] Finish implementation of AES1610 driver Ported to the new internal libfprint API. https://bugzilla.redhat.com/show_bug.cgi?id=499732 --- configure.ac | 2 +- libfprint/Makefile.am | 6 +- libfprint/core.c | 4 +- libfprint/drivers/aes1610.c | 1090 +++++++++++++++++++++++++++-------- 4 files changed, 840 insertions(+), 262 deletions(-) diff --git a/configure.ac b/configure.ac index 052ef0e9..a892a967 100644 --- a/configure.ac +++ b/configure.ac @@ -89,7 +89,7 @@ AM_CONDITIONAL([ENABLE_UPEKSONLY], [test "$enable_upeksonly" != "no"]) AM_CONDITIONAL([ENABLE_VCOM5S], [test "$enable_vcom5s" != "no"]) AM_CONDITIONAL([ENABLE_URU4000], [test "$enable_uru4000" != "no"]) #AM_CONDITIONAL([ENABLE_FDU2000], [test "$enable_fdu2000" != "no"]) -#AM_CONDITIONAL([ENABLE_AES1610], [test "$enable_aes1610" != "no"]) +AM_CONDITIONAL([ENABLE_AES1610], [test "$enable_aes1610" != "no"]) AM_CONDITIONAL([ENABLE_AES2501], [test "$enable_aes2501" != "no"]) AM_CONDITIONAL([ENABLE_AES4000], [test "$enable_aes4000" != "no"]) AM_CONDITIONAL([REQUIRE_AESLIB], [test "$require_aeslib" != "no"]) diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index c79012bb..83167968 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -100,9 +100,9 @@ endif #DRIVER_SRC += $(FDU2000_SRC) #endif -#if ENABLE_AES1610 -#DRIVER_SRC += $(AES1610_SRC) -#endif +if ENABLE_AES1610 +DRIVER_SRC += $(AES1610_SRC) +endif if ENABLE_AES2501 DRIVER_SRC += $(AES2501_SRC) diff --git a/libfprint/core.c b/libfprint/core.c index 37a4e038..724d5e59 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -361,11 +361,11 @@ static struct fp_img_driver * const img_drivers[] = { #ifdef ENABLE_UPEKSONLY &upeksonly_driver, #endif - /* + #ifdef ENABLE_AES1610 &aes1610_driver, #endif -#ifdef ENABLE_UPEKTC +/*#ifdef ENABLE_UPEKTC &upektc_driver, #endif #ifdef ENABLE_FDU2000 diff --git a/libfprint/drivers/aes1610.c b/libfprint/drivers/aes1610.c index 318195fe..8b81a80c 100644 --- a/libfprint/drivers/aes1610.c +++ b/libfprint/drivers/aes1610.c @@ -1,11 +1,11 @@ /* * AuthenTec AES1610 driver for libfprint - * Copyright (C) 2007 Anthony Bretaudeau - * Copyright (C) 2007 Daniel Drake + * Copyright (C) 2007-2008 Daniel Drake * Copyright (C) 2007 Cyrille Bagard * Copyright (C) 2007 Vasily Khoruzhick + * Copyright (C) 2009 Guido Grazioli * - * Based on code from http://home.gna.org/aes2501, relicensed with permission + * Based on code from libfprint aes2501 driver. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -32,15 +32,22 @@ #include #include +static void start_capture(struct fp_img_dev *dev); +static void complete_deactivation(struct fp_img_dev *dev); +static int adjust_gain(unsigned char *buffer, int status); + +#define FIRST_AES1610_REG 0x1B +#define LAST_AES1610_REG 0xFF + +#define GAIN_STATUS_FIRST 1 +#define GAIN_STATUS_NORMAL 2 + /* FIXME these need checking */ #define EP_IN (1 | LIBUSB_ENDPOINT_IN) #define EP_OUT (2 | LIBUSB_ENDPOINT_OUT) #define BULK_TIMEOUT 4000 -#define FIRST_AES1610_REG 0x1B -#define LAST_AES1610_REG 0xFF - /* * The AES1610 is an imaging device using a swipe-type sensor. It samples * the finger at preprogrammed intervals, sending a 128x8 frame to the @@ -53,140 +60,212 @@ * images returned from this driver vary in height. */ -#define FRAME_WIDTH 128 +#define FRAME_WIDTH 128 #define FRAME_HEIGHT 8 -#define FRAME_SIZE (FRAME_WIDTH * FRAME_HEIGHT) +#define FRAME_SIZE (FRAME_WIDTH * FRAME_HEIGHT) /* maximum number of frames to read during a scan */ /* FIXME reduce substantially */ #define MAX_FRAMES 350 -static int read_data(struct fp_img_dev *dev, unsigned char *data, size_t len) -{ - int r; - int transferred; - struct libusb_bulk_transfer msg = { - .endpoint = EP_IN, - .data = data, - .length = len, - }; - fp_dbg("len=%zd", len); +/****** GENERAL FUNCTIONS ******/ + +struct aes1610_dev { + uint8_t read_regs_retry_count; + GSList *strips; + size_t strips_len; + gboolean deactivating; + uint8_t blanks_count; +}; + +typedef void (*aes1610_read_regs_cb)(struct fp_img_dev *dev, int status, + unsigned char *regs, void *user_data); + +struct aes1610_read_regs { + struct fp_img_dev *dev; + aes1610_read_regs_cb callback; + struct aes_regwrite *regwrite; + void *user_data; +}; + +/* FIXME: what to do here? */ +static void stub_capture_stop_cb(struct fp_img_dev *dev, int result, void *user_data) +{ - r = libusb_bulk_transfer(dev->udev, &msg, &transferred, BULK_TIMEOUT); - if (r < 0) { - fp_err("bulk read error %d", r); - return r; - } else if (transferred < len) { - fp_err("unexpected short read %d/%zd", r, len); - return -EIO; - } - return 0; } -static const struct aes_regwrite init[] = { - { 0x82, 0x00 } -}; -static const struct aes_regwrite stop_reader[] = { - { 0xFF, 0x00 } -}; - -static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) +/* check that read succeeded but ignore all data */ +static void generic_ignore_data_cb(struct libusb_transfer *transfer) { + struct fpi_ssm *ssm = transfer->user_data; + + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) + fpi_ssm_mark_aborted(ssm, -EIO); + else if (transfer->length != transfer->actual_length) + fpi_ssm_mark_aborted(ssm, -EPROTO); + else + fpi_ssm_next_state(ssm); + + g_free(transfer->buffer); + libusb_free_transfer(transfer); +} + + +static void read_regs_data_cb(struct libusb_transfer *transfer) +{ + struct aes1610_read_regs *rdata = transfer->user_data; + unsigned char *retdata = NULL; int r; - r = libusb_claim_interface(dev->udev, 0); - if (r < 0) { - fp_err("could not claim interface 0"); - return r; + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { + r = -EIO; + } else if (transfer->length != transfer->actual_length) { + r = -EPROTO; + } else { + r = 0; + retdata = transfer->buffer; } - /* FIXME check endpoints */ - - return aes_write_regv(dev, init, G_N_ELEMENTS(init)); + rdata->callback(rdata->dev, r, retdata, rdata->user_data); + g_free(rdata); + g_free(transfer->buffer); + libusb_free_transfer(transfer); } -static int do_exit(struct fp_img_dev *dev) +static void read_regs_rq_cb(struct fp_img_dev *dev, int result, void *user_data) { - return aes_write_regv(dev, stop_reader, G_N_ELEMENTS(stop_reader)); -} - -static void dev_exit(struct fp_img_dev *dev) -{ - do_exit(dev); - libusb_release_interface(dev->udev, 0); -} - -static const struct aes_regwrite finger_det_reqs[] = { - { 0x80, 0x01 }, - { 0x80, 0x12 }, - { 0x85, 0x00 }, - { 0x8A, 0x00 }, - { 0x8B, 0x0E }, - { 0x8C, 0x90 }, - { 0x8D, 0x83 }, - { 0x8E, 0x07 }, - { 0x8F, 0x07 }, - { 0x96, 0x00 }, - { 0x97, 0x48 }, - { 0xA1, 0x00 }, - { 0xA2, 0x50 }, - { 0xA6, 0xE4 }, - { 0xAD, 0x08 }, - { 0xAE, 0x5B }, - { 0xAF, 0x54 }, - { 0xB1, 0x28 }, - { 0xB5, 0xAB }, - { 0xB6, 0x0E }, - { 0x1B, 0x2D }, - { 0x81, 0x04 } -}; - -static const struct aes_regwrite finger_det_none[] = { - { 0x80, 0x01 }, - { 0x82, 0x00 }, - { 0x86, 0x00 }, - { 0xB1, 0x28 }, - { 0x1D, 0x00 } -}; - -static int detect_finger(struct fp_img_dev *dev) -{ - unsigned char buffer[19]; + struct aes1610_read_regs *rdata = user_data; + struct libusb_transfer *transfer; + unsigned char *data; int r; + + g_free(rdata->regwrite); + if (result != 0) + goto err; + + transfer = libusb_alloc_transfer(0); + if (!transfer) { + result = -ENOMEM; + goto err; + } + + data = g_malloc(126); + libusb_fill_bulk_transfer(transfer, dev->udev, EP_IN, data, 126, + read_regs_data_cb, rdata, BULK_TIMEOUT); + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(data); + libusb_free_transfer(transfer); + result = -EIO; + goto err; + } + + return; +err: + rdata->callback(dev, result, NULL, rdata->user_data); + g_free(rdata); +} + + +// XXX: this comes from aes2501 driver but it is unused here +static void read_regs(struct fp_img_dev *dev, aes1610_read_regs_cb callback, + void *user_data) +{ + /* FIXME: regwrite is dynamic because of asynchronity. is this really + * required? */ + struct aes_regwrite *regwrite = g_malloc(sizeof(*regwrite)); + struct aes1610_read_regs *rdata = g_malloc(sizeof(*rdata)); + + fp_dbg(""); + //regwrite->reg = AES1610_REG_CTRL2; + //regwrite->value = AES1610_CTRL2_READ_REGS; + rdata->dev = dev; + rdata->callback = callback; + rdata->user_data = user_data; + rdata->regwrite = regwrite; + + //aes_write_regv(dev, (const struct aes_regwrite *) regwrite, 1, + // read_regs_rq_cb, rdata); +} + +/* Read the value of a specific register from a register dump */ +static int regval_from_dump(unsigned char *data, uint8_t target) +{ + if (*data != FIRST_AES1610_REG) { + fp_err("not a register dump"); + return -EILSEQ; + } + + if (!(FIRST_AES1610_REG <= target && target <= LAST_AES1610_REG)) { + fp_err("out of range"); + return -EINVAL; + } + + target -= FIRST_AES1610_REG; + target *= 2; + return data[target + 1]; +} + +static void generic_write_regv_cb(struct fp_img_dev *dev, int result, + void *user_data) +{ + struct fpi_ssm *ssm = user_data; + if (result == 0) + fpi_ssm_next_state(ssm); + else + fpi_ssm_mark_aborted(ssm, result); +} + + + +/* read the specified number of bytes from the IN endpoint but throw them + * away, then increment the SSM */ +static void generic_read_ignore_data(struct fpi_ssm *ssm, size_t bytes) +{ + struct libusb_transfer *transfer = libusb_alloc_transfer(0); + unsigned char *data; + int r; + + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + return; + } + + data = g_malloc(bytes); + libusb_fill_bulk_transfer(transfer, ssm->dev->udev, EP_IN, data, bytes, + generic_ignore_data_cb, ssm, BULK_TIMEOUT); + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(data); + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, r); + } +} + +/****** IMAGE PROCESSING ******/ + +static int sum_histogram_values(unsigned char *data, uint8_t threshold) +{ + int r = 0; int i; - int sum = 0; + uint16_t *histogram = (uint16_t *)(data + 1); - r = aes_write_regv(dev, finger_det_reqs, G_N_ELEMENTS(finger_det_reqs)); - if (r < 0) - return r; + if (*data != 0xde) + return -EILSEQ; - r = read_data(dev, buffer, 19); - if (r < 0) - return r; + if (threshold > 0x0f) + return -EINVAL; - for (i = 3; i < 17; i++) - sum += (buffer[i] & 0xf) + (buffer[i] >> 4); - - /* We need to answer something if no finger has been detected */ - if (sum <= 20) { - r = aes_write_regv(dev, finger_det_none, G_N_ELEMENTS(finger_det_none)); - if (r < 0) - return r; - } - - return sum > 20; + /* FIXME endianness */ + for (i = threshold; i < 16; i++) + r += histogram[i]; + + return r; } -static int await_finger_on(struct fp_img_dev *dev) -{ - int r; - do { - r = detect_finger(dev); - } while (r == 0); - return (r < 0) ? r : 0; -} - -/* find overlapping parts of frames */ +/* find overlapping parts of frames */ static unsigned int find_overlap(unsigned char *first_frame, unsigned char *second_frame, unsigned int *min_error) { @@ -199,11 +278,11 @@ static unsigned int find_overlap(unsigned char *first_frame, unsigned int error = 0; for (i = 0; i < FRAME_WIDTH * (FRAME_HEIGHT - dy); i++) { /* Using ? operator to avoid abs function */ - error += first_frame[i] > second_frame[i] ? - (first_frame[i] - second_frame[i]) : - (second_frame[i] - first_frame[i]); + error += first_frame[i] > second_frame[i] ? + (first_frame[i] - second_frame[i]) : + (second_frame[i] - first_frame[i]); } - + /* Normalize error */ error *= 15; error /= i; @@ -213,37 +292,39 @@ static unsigned int find_overlap(unsigned char *first_frame, } first_frame += FRAME_WIDTH; } - - return not_overlapped_height; + + return not_overlapped_height; } /* assemble a series of frames into a single image */ -static unsigned int assemble(unsigned char *input, unsigned char *output, - int num_strips, gboolean reverse, unsigned int *errors_sum) +static unsigned int assemble(struct aes1610_dev *aesdev, unsigned char *output, + gboolean reverse, unsigned int *errors_sum) { uint8_t *assembled = output; int frame; uint32_t image_height = FRAME_HEIGHT; unsigned int min_error; + size_t num_strips = aesdev->strips_len; + GSList *list_entry = aesdev->strips; *errors_sum = 0; if (num_strips < 1) return 0; - - /* Rotating given data by 90 degrees + + /* Rotating given data by 90 degrees * Taken from document describing aes1610 image format * TODO: move reversing detection here */ - + if (reverse) output += (num_strips - 1) * FRAME_SIZE; for (frame = 0; frame < num_strips; frame++) { - aes_assemble_image(input, FRAME_WIDTH, FRAME_HEIGHT, output); - input += FRAME_WIDTH * (FRAME_HEIGHT / 2); + aes_assemble_image(list_entry->data, FRAME_WIDTH, FRAME_HEIGHT, output); if (reverse) - output -= FRAME_SIZE; + output -= FRAME_SIZE; else - output += FRAME_SIZE; + output += FRAME_SIZE; + list_entry = g_slist_next(list_entry); } /* Detecting where frames overlaped */ @@ -256,12 +337,183 @@ static unsigned int assemble(unsigned char *input, unsigned char *output, *errors_sum += min_error; image_height += not_overlapped; assembled += FRAME_WIDTH * not_overlapped; - memcpy(assembled, output, FRAME_SIZE); + memcpy(assembled, output, FRAME_SIZE); } return image_height; } -static const struct aes_regwrite capture_reqs[] = { +static void assemble_and_submit_image(struct fp_img_dev *dev) +{ + struct aes1610_dev *aesdev = dev->priv; + size_t final_size; + struct fp_img *img; + unsigned int errors_sum, r_errors_sum; + + fp_dbg(""); + + BUG_ON(aesdev->strips_len == 0); + + /* reverse list */ + aesdev->strips = g_slist_reverse(aesdev->strips); + + /* create buffer big enough for max image */ + img = fpi_img_new(aesdev->strips_len * FRAME_SIZE); + + img->flags = FP_IMG_COLORS_INVERTED; + img->height = assemble(aesdev, img->data, FALSE, &errors_sum); + img->height = assemble(aesdev, img->data, TRUE, &r_errors_sum); + + if (r_errors_sum > errors_sum) { + img->height = assemble(aesdev, img->data, FALSE, &errors_sum); + img->flags |= FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED; + fp_dbg("normal scan direction"); + } else { + fp_dbg("reversed scan direction"); + } + + /* now that overlap has been removed, resize output image buffer */ + final_size = img->height * FRAME_WIDTH; + img = fpi_img_resize(img, final_size); + /* FIXME: ugly workaround */ + if (img->height < 12) + img->height = 12; + fpi_imgdev_image_captured(dev, img); + + /* free strips and strip list */ + g_slist_foreach(aesdev->strips, (GFunc) g_free, NULL); + g_slist_free(aesdev->strips); + aesdev->strips = NULL; + aesdev->strips_len = 0; + aesdev->blanks_count = 0; +} + + +/****** FINGER PRESENCE DETECTION ******/ + + +static const struct aes_regwrite finger_det_reqs[] = { + { 0x80, 0x01 }, + { 0x80, 0x12 }, + { 0x85, 0x00 }, + { 0x8A, 0x00 }, + { 0x8B, 0x0E }, + { 0x8C, 0x90 }, + { 0x8D, 0x83 }, + { 0x8E, 0x07 }, + { 0x8F, 0x07 }, + { 0x96, 0x00 }, + { 0x97, 0x48 }, + { 0xA1, 0x00 }, + { 0xA2, 0x50 }, + { 0xA6, 0xE4 }, + { 0xAD, 0x08 }, + { 0xAE, 0x5B }, + { 0xAF, 0x54 }, + { 0xB1, 0x28 }, + { 0xB5, 0xAB }, + { 0xB6, 0x0E }, + { 0x1B, 0x2D }, + { 0x81, 0x04 } +}; + +static const struct aes_regwrite finger_det_none[] = { + { 0x80, 0x01 }, + { 0x82, 0x00 }, + { 0x86, 0x00 }, + { 0xB1, 0x28 }, + { 0x1D, 0x00 } +}; + + +static void start_finger_detection(struct fp_img_dev *dev); + +static void finger_det_data_cb(struct libusb_transfer *transfer) +{ + struct fp_img_dev *dev = transfer->user_data; + unsigned char *data = transfer->buffer; + int i; + int sum = 0; + + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { + fpi_imgdev_session_error(dev, -EIO); + goto out; + } else if (transfer->length != transfer->actual_length) { + fpi_imgdev_session_error(dev, -EPROTO); + goto out; + } + + /* examine histogram to determine finger presence */ + for (i = 3; i < 17; i++) + sum += (data[i] & 0xf) + (data[i] >> 4); + if (sum > 20) { + /* reset default gain */ + adjust_gain(data,GAIN_STATUS_FIRST); + /* finger present, start capturing */ + fpi_imgdev_report_finger_status(dev, TRUE); + start_capture(dev); + } else { + /* no finger, poll for a new histogram */ + start_finger_detection(dev); + } + +out: + g_free(data); + libusb_free_transfer(transfer); +} + + +static void finger_det_none_cb(struct fp_img_dev *dev, int result, void *user_data){ + fpi_imgdev_report_finger_status(dev, FALSE); + start_finger_detection(dev); +} + +static void finger_det_reqs_cb(struct fp_img_dev *dev, int result, void *user_data) +{ + struct libusb_transfer *transfer; + unsigned char *data; + int r; + + if (result) { + fpi_imgdev_session_error(dev, result); + return; + } + + transfer = libusb_alloc_transfer(0); + if (!transfer) { + fpi_imgdev_session_error(dev, -ENOMEM); + return; + } + + data = g_malloc(19); + libusb_fill_bulk_transfer(transfer, dev->udev, EP_IN, data, 19, + finger_det_data_cb, dev, BULK_TIMEOUT); + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(data); + libusb_free_transfer(transfer); + fpi_imgdev_session_error(dev, r); + } + +} + +static void start_finger_detection(struct fp_img_dev *dev) +{ + struct aes1610_dev *aesdev = dev->priv; + struct libusb_transfer *transfer; + + if (aesdev->deactivating) { + complete_deactivation(dev); + return; + } + + aes_write_regv(dev, finger_det_reqs, G_N_ELEMENTS(finger_det_reqs), finger_det_reqs_cb, NULL); + +} + +/****** CAPTURE ******/ + +static struct aes_regwrite capture_reqs[] = { { 0x80, 0x01 }, { 0x80, 0x12 }, { 0x84, 0x01 }, @@ -271,8 +523,8 @@ static const struct aes_regwrite capture_reqs[] = { { 0x8B, 0x0E }, { 0x8C, 0x90 }, { 0xBE, 0x23 }, - { 0x29, 0x06 }, - { 0x2A, 0x35 }, + { 0x29, 0x04 }, + { 0x2A, 0xFF }, { 0x96, 0x00 }, { 0x98, 0x03 }, { 0x99, 0x00 }, @@ -387,10 +639,10 @@ static const struct aes_regwrite capture_reqs[] = { { 0x81, 0x01 } }; -static const struct aes_regwrite strip_scan_reqs[] = { +static struct aes_regwrite strip_scan_reqs[] = { { 0xBE, 0x23 }, - { 0x29, 0x06 }, - { 0x2A, 0x35 }, + { 0x29, 0x04 }, + { 0x2A, 0xFF }, { 0xBD, 0x4F }, { 0xFF, 0x00 } }; @@ -399,130 +651,456 @@ static const struct aes_regwrite capture_stop[] = { { 0x81,0x00 } }; -static int capture(struct fp_img_dev *dev, gboolean unconditional, - struct fp_img **ret) -{ - int r; - struct fp_img *img; - unsigned int nstrips; - unsigned int errors_sum, r_errors_sum; - unsigned char *cooked; - unsigned char *imgptr; - unsigned char buf[665]; - int final_size; - int sum; - unsigned int count_blank = 0; - int i; +/* + * The different possible values for 0xBE register */ +static unsigned char list_BE_values[10] = { + 0x23, 0x43, 0x63, 0x64, 0x65, 0x67, 0x6A, 0x6B +}; - /* FIXME can do better here in terms of buffer management? */ +/* + * The different possible values for 0xBD register */ +static unsigned char list_BD_values[10] = { + 0x48, 0x4B, 0x4F, 0x52, 0x57, 0x59, 0x5B +}; + +/* + * Adjust the gain according to the histogram data + * 0xbd, 0xbe, 0x29 and 0x2A registers are affected + * Returns 0 if no problem occured + * TODO: This is a basic support for gain. It needs testing/tweaking. */ +static int adjust_gain(unsigned char *buffer, int status) +{ + // The position in the array of possible values for 0xBE and 0xBD registers + static int pos_list_BE = 0; + static int pos_list_BD = 0; + + // This is the first adjustement (we begin acquisition) + // We adjust strip_scan_reqs for future strips and capture_reqs that is sent just after this step + if (status == GAIN_STATUS_FIRST) { + if (buffer[1] > 0x78) { // maximum gain needed + strip_scan_reqs[0].value = 0x6B; + strip_scan_reqs[1].value = 0x06; + strip_scan_reqs[2].value = 0x35; + strip_scan_reqs[3].value = 0x5B; + } + else if (buffer[1] > 0x55) { + strip_scan_reqs[0].value = 0x63; + strip_scan_reqs[1].value = 0x15; + strip_scan_reqs[2].value = 0x35; + strip_scan_reqs[3].value = 0x4F; + } + else if (buffer[1] > 0x40 || buffer[16] > 0x19) { + strip_scan_reqs[0].value = 0x43; + strip_scan_reqs[1].value = 0x13; + strip_scan_reqs[2].value = 0x35; + strip_scan_reqs[3].value = 0x4B; + } + else { // minimum gain needed + strip_scan_reqs[0].value = 0x23; + strip_scan_reqs[1].value = 0x07; + strip_scan_reqs[2].value = 0x35; + strip_scan_reqs[3].value = 0x48; + } + + // Now copy this values in capture_reqs + capture_reqs[8].value = strip_scan_reqs[0].value; + capture_reqs[9].value = strip_scan_reqs[1].value; + capture_reqs[10].value = strip_scan_reqs[2].value; + capture_reqs[21].value = strip_scan_reqs[3].value; + + fp_dbg("first gain: %x %x %x %x %x %x %x %x", strip_scan_reqs[0].reg, strip_scan_reqs[0].value, strip_scan_reqs[1].reg, strip_scan_reqs[1].value, strip_scan_reqs[2].reg, strip_scan_reqs[2].value, strip_scan_reqs[3].reg, strip_scan_reqs[3].value); + } + + // Every 2/3 strips + // We try to soften big changes of the gain (at least for 0xBE and 0xBD + // FIXME: This softenning will need testing and tweaking too + else if (status == GAIN_STATUS_NORMAL) { + if (buffer[514] > 0x78) { // maximum gain needed + if (pos_list_BE < 7) + pos_list_BE++; + + if (pos_list_BD < 6) + pos_list_BD++; + + strip_scan_reqs[1].value = 0x04; + strip_scan_reqs[2].value = 0x35; + } + else if (buffer[514] > 0x55) { + if (pos_list_BE < 2) + pos_list_BE++; + else if (pos_list_BE > 2) + pos_list_BE--; + + if (pos_list_BD < 2) + pos_list_BD++; + else if (pos_list_BD > 2) + pos_list_BD--; + + strip_scan_reqs[1].value = 0x15; + strip_scan_reqs[2].value = 0x35; + } + else if (buffer[514] > 0x40 || buffer[529] > 0x19) { + if (pos_list_BE < 1) + pos_list_BE++; + else if (pos_list_BE > 1) + pos_list_BE--; + + if (pos_list_BD < 1) + pos_list_BD++; + else if (pos_list_BD > 1) + pos_list_BD--; + + strip_scan_reqs[1].value = 0x13; + strip_scan_reqs[2].value = 0x35; + } + else { // minimum gain needed + if (pos_list_BE > 0) + pos_list_BE--; + + if (pos_list_BD > 0) + pos_list_BD--; + + strip_scan_reqs[1].value = 0x07; + strip_scan_reqs[2].value = 0x35; + } + + strip_scan_reqs[0].value = list_BE_values[pos_list_BE]; + strip_scan_reqs[3].value = list_BD_values[pos_list_BD]; + + fp_dbg("gain: %x %x %x %x %x %x %x %x", strip_scan_reqs[0].reg, strip_scan_reqs[0].value, strip_scan_reqs[1].reg, strip_scan_reqs[1].value, strip_scan_reqs[2].reg, strip_scan_reqs[2].value, strip_scan_reqs[3].reg, strip_scan_reqs[3].value); + } + // Unknown status + else { + fp_err("Unexpected gain status."); + return 1; + } + + return 0; +} + +/* + * Restore the default gain values */ +static void restore_gain() +{ + strip_scan_reqs[0].value = list_BE_values[0]; + strip_scan_reqs[1].value = 0x04; + strip_scan_reqs[2].value = 0xFF; + strip_scan_reqs[3].value = list_BD_values[0]; + + capture_reqs[8].value = list_BE_values[0]; + capture_reqs[9].value = 0x04; + capture_reqs[10].value = 0xFF; + capture_reqs[21].value = list_BD_values[0]; +} + + +/* capture SM movement: + * request and read strip, + * jump back to request UNLESS theres no finger, in which case exit SM, + * report lack of finger presence, and move to finger detection */ + +enum capture_states { + CAPTURE_WRITE_REQS, + CAPTURE_READ_DATA, + CAPTURE_REQUEST_STRIP, + CAPTURE_READ_STRIP, + CAPTURE_NUM_STATES, +}; + +static void capture_read_strip_cb(struct libusb_transfer *transfer) +{ + unsigned char *stripdata; + struct fpi_ssm *ssm = transfer->user_data; + struct fp_img_dev *dev = ssm->priv; + struct aes1610_dev *aesdev = dev->priv; + unsigned char *data = transfer->buffer; + int sum, i; + int threshold; + + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { + fpi_ssm_mark_aborted(ssm, -EIO); + goto out; + } else if (transfer->length != transfer->actual_length) { + fpi_ssm_mark_aborted(ssm, -EPROTO); + goto out; + } + + /* FIXME: would preallocating strip buffers be a decent optimization? */ + //stripdata = g_malloc(128 * 4); + //memcpy(stripdata, data + 1, 128 * 4); + //aesdev->strips = g_slist_prepend(aesdev->strips, stripdata); + //aesdev->strips_len++; + + /*threshold = regval_from_dump(data + 1 + 128*8 + 1 + 16*2 + 1 + 8, + 0x97); + if (threshold < 0) { + fpi_ssm_mark_aborted(ssm, threshold); + goto out; + }*/ + + sum = 0; + for (i = 516; i < 530; i++) + { + /* histogram[i] = number of pixels of value i + Only the pixel values from 10 to 15 are used to detect finger. */ + sum += data[i]; + } + + if (sum > 0) { + /* FIXME: would preallocating strip buffers be a decent optimization? */ + stripdata = g_malloc(128 * 4); + memcpy(stripdata, data + 1, 128 * 4); + aesdev->strips = g_slist_prepend(aesdev->strips, stripdata); + aesdev->strips_len++; + aesdev->blanks_count = 0; + } + + if (sum < 0) { + fpi_ssm_mark_aborted(ssm, sum); + goto out; + } + fp_dbg("sum=%d", sum); + + /* FIXME: 0 might be too low as a threshold */ + /* FIXME: sometimes we get 0 in the middle of a scan, should we wait for + * a few consecutive zeroes? */ + + /* If sum is 0 for a reasonable # of frames, finger has been removed */ + if (sum == 0) { + aesdev->blanks_count++; + fp_dbg("got blank frame"); + } + + /* use histogram data above for gain calibration (0xbd, 0xbe, 0x29 and 0x2A ) */ + adjust_gain(data, GAIN_STATUS_NORMAL); + + /* stop capturing if MAX_FRAMES is reached */ + if (aesdev->blanks_count > 10 || g_slist_length(aesdev->strips) >= MAX_FRAMES) { + fp_dbg("sending stop capture.... blanks=%d frames=%d", aesdev->blanks_count, g_slist_length(aesdev->strips)); + /* send stop capture bits */ + aes_write_regv(dev, capture_stop, G_N_ELEMENTS(capture_stop), stub_capture_stop_cb, NULL); + /* assemble image and submit it to library */ + assemble_and_submit_image(dev); + fpi_imgdev_report_finger_status(dev, FALSE); + /* marking machine complete will re-trigger finger detection loop */ + fpi_ssm_mark_completed(ssm); + /* Acquisition finished: restore default gain values */ + restore_gain(); + } else { + /* obtain next strip */ + fpi_ssm_jump_to_state(ssm, CAPTURE_REQUEST_STRIP); + } + +out: + g_free(data); + libusb_free_transfer(transfer); +} + +static void capture_run_state(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct aes1610_dev *aesdev = dev->priv; + int r; + + switch (ssm->cur_state) { + case CAPTURE_WRITE_REQS: + fp_dbg("write reqs"); + aes_write_regv(dev, capture_reqs, G_N_ELEMENTS(capture_reqs), + generic_write_regv_cb, ssm); + break; + case CAPTURE_READ_DATA: + fp_dbg("read data"); + generic_read_ignore_data(ssm, 665); + break; + case CAPTURE_REQUEST_STRIP: + fp_dbg("request strip"); + if (aesdev->deactivating) + fpi_ssm_mark_completed(ssm); + else + aes_write_regv(dev, strip_scan_reqs, G_N_ELEMENTS(strip_scan_reqs), + generic_write_regv_cb, ssm); + break; + case CAPTURE_READ_STRIP: ; + struct libusb_transfer *transfer = libusb_alloc_transfer(0); + unsigned char *data; + + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + break; + } + + data = g_malloc(665); + libusb_fill_bulk_transfer(transfer, dev->udev, EP_IN, data, 665, + capture_read_strip_cb, ssm, BULK_TIMEOUT); + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(data); + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, r); + } + break; + }; +} + +static void capture_sm_complete(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct aes1610_dev *aesdev = dev->priv; + + fp_dbg(""); + if (aesdev->deactivating) + complete_deactivation(dev); + else if (ssm->error) + fpi_imgdev_session_error(dev, ssm->error); + else + start_finger_detection(dev); + fpi_ssm_free(ssm); +} + +static void start_capture(struct fp_img_dev *dev) +{ + struct aes1610_dev *aesdev = dev->priv; + struct fpi_ssm *ssm; + + if (aesdev->deactivating) { + complete_deactivation(dev); + return; + } + + ssm = fpi_ssm_new(dev->dev, capture_run_state, CAPTURE_NUM_STATES); + fp_dbg(""); + ssm->priv = dev; + fpi_ssm_start(ssm, capture_sm_complete); +} + +/****** INITIALIZATION/DEINITIALIZATION ******/ + +static const struct aes_regwrite init[] = { + { 0x82, 0x00 } +}; + +static const struct aes_regwrite stop_reader[] = { + { 0xFF, 0x00 } +}; + + +enum activate_states { + WRITE_INIT, +// READ_DATA, +// READ_REGS, + ACTIVATE_NUM_STATES, +}; + +/* this come from aes2501 and is unused here +void activate_read_regs_cb(struct fp_img_dev *dev, int status, + unsigned char *regs, void *user_data) +{ + struct fpi_ssm *ssm = user_data; + struct aes1610_dev *aesdev = dev->priv; + + if (status != 0) { + fpi_ssm_mark_aborted(ssm, status); + } else { + fpi_ssm_next_state(ssm); + } +} +*/ + +static void activate_run_state(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + + /* activation on aes1610 seems much more straightforward compared to aes2501 */ + /* verify theres anything missing here */ + switch (ssm->cur_state) { + case WRITE_INIT: + fp_dbg("write init"); + aes_write_regv(dev, init, G_N_ELEMENTS(init), generic_write_regv_cb, ssm); + break; +/* case READ_DATA: + fp_dbg("read data"); + generic_read_ignore_data(ssm, 20); + break; + case READ_REGS: + fp_dbg("read regs"); + read_regs(dev, activate_read_regs_cb, ssm); + break;*/ + } +} + +/* jump to finger detection */ +static void activate_sm_complete(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + fp_dbg("status %d", ssm->error); + fpi_imgdev_activate_complete(dev, ssm->error); + + if (!ssm->error) + start_finger_detection(dev); + fpi_ssm_free(ssm); +} + +static int dev_activate(struct fp_img_dev *dev, enum fp_imgdev_state state) +{ + struct aes1610_dev *aesdev = dev->priv; + struct fpi_ssm *ssm = fpi_ssm_new(dev->dev, activate_run_state, + ACTIVATE_NUM_STATES); + ssm->priv = dev; + aesdev->read_regs_retry_count = 0; + fpi_ssm_start(ssm, activate_sm_complete); + return 0; +} + +static void dev_deactivate(struct fp_img_dev *dev) +{ + struct aes1610_dev *aesdev = dev->priv; + /* FIXME: audit cancellation points, probably need more, specifically + * in error handling paths? */ + aesdev->deactivating = TRUE; +} + +static void complete_deactivation(struct fp_img_dev *dev) +{ + struct aes1610_dev *aesdev = dev->priv; fp_dbg(""); - r = aes_write_regv(dev, capture_reqs, G_N_ELEMENTS(capture_reqs)); - if (r < 0) + /* FIXME: if we're in the middle of a scan, we should cancel the scan. + * maybe we can do this with a master reset, unconditionally? */ + + aesdev->deactivating = FALSE; + g_slist_free(aesdev->strips); + aesdev->strips = NULL; + aesdev->strips_len = 0; + aesdev->blanks_count = 0; + fpi_imgdev_deactivate_complete(dev); +} + +static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) +{ + /* FIXME check endpoints */ + int r; + + r = libusb_claim_interface(dev->udev, 0); + if (r < 0) { + fp_err("could not claim interface 0"); return r; - - /* FIXME: use histogram data above for gain calibration (0x8e xx) */ - - img = fpi_img_new((3 * MAX_FRAMES * FRAME_SIZE) / 2); - imgptr = img->data; - cooked = imgptr + (MAX_FRAMES * FRAME_SIZE) / 2; - - r = read_data(dev, buf, 665); - if (r < 0) - goto err; - memcpy(imgptr, buf + 1, 128*4); - imgptr += 128*4; - - r = read_data(dev, buf, 665); - if (r < 0) - goto err; - memcpy(imgptr, buf + 1, 128*4); - imgptr += 128*4; - - /* we start at 2 because we captured 2 frames above. the above captures - * should possibly be moved into the loop below, or discarded altogether */ - for (nstrips = 2; nstrips < MAX_FRAMES - 2; nstrips++) { - r = aes_write_regv(dev, strip_scan_reqs, G_N_ELEMENTS(strip_scan_reqs)); - if (r < 0) - goto err; - r = read_data(dev, buf, 665); - if (r < 0) - goto err; - memcpy(imgptr, buf + 1, 128*4); - imgptr += 128*4; - - r = read_data(dev, buf, 665); - if (r < 0) - goto err; - memcpy(imgptr, buf + 1, 128*4); - imgptr += 128*4; - - sum = 0; - for (i = 515; i != 530; i++) - { - /* histogram[i] = number of pixels of value i - Only the pixel values from 10 to 15 are used to detect finger. */ - sum += buf[i]; - } - if (sum < 0) { - r = sum; - goto err; - } - fp_dbg("sum=%d", sum); - if (sum == 0) - count_blank++; - else - count_blank = 0; - - /* if we got 50 blank frames, assume scan has ended. */ - if (count_blank >= 50) - break; - } - - r = aes_write_regv(dev, capture_stop, G_N_ELEMENTS(capture_stop)); - if (r < 0) - goto err; - r = read_data(dev, buf, 665); - if (r < 0) - goto err; - memcpy(imgptr, buf + 1, 128*4); - imgptr += 128*4; - nstrips++; - - r = read_data(dev, buf, 665); - if (r < 0) - goto err; - memcpy(imgptr, buf + 1, 128*4); - imgptr += 128*4; - nstrips++; - - if (nstrips == MAX_FRAMES) - fp_warn("swiping finger too slow?"); - - img->flags = FP_IMG_COLORS_INVERTED; - img->height = assemble(img->data, cooked, nstrips, FALSE, &errors_sum); - img->height = assemble(img->data, cooked, nstrips, TRUE, &r_errors_sum); - - if (r_errors_sum > errors_sum) { - img->height = assemble(img->data, cooked, nstrips, FALSE, &errors_sum); - img->flags |= FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED; - fp_dbg("normal scan direction"); - } else { - fp_dbg("reversed scan direction"); } - final_size = img->height * FRAME_WIDTH; - memcpy(img->data, cooked, final_size); - img = fpi_img_resize(img, final_size); - *ret = img; + dev->priv = g_malloc0(sizeof(struct aes1610_dev)); + fpi_imgdev_open_complete(dev, 0); return 0; -err: - fp_img_free(img); - return r; +} + +static void dev_deinit(struct fp_img_dev *dev) +{ + g_free(dev->priv); + libusb_release_interface(dev->udev, 0); + fpi_imgdev_close_complete(dev); } static const struct usb_id id_table[] = { - { .vendor = 0x08ff, .product = 0x1600 }, + { .vendor = 0x08ff, .product = 0x1600 }, /* AES1600 */ { 0, 0, 0, }, }; @@ -544,9 +1122,9 @@ struct fp_img_driver aes1610_driver = { * area) */ .bz3_threshold = 10, - .init = dev_init, - .exit = dev_exit, - .await_finger_on = await_finger_on, - .capture = capture, + .open = dev_init, + .close = dev_deinit, + .activate = dev_activate, + .deactivate = dev_deactivate, }; From 5a1926bb416fa4e5a38fa10b9ac3da04ce9f3f72 Mon Sep 17 00:00:00 2001 From: Jorge Suarez de Lis Date: Tue, 17 Aug 2010 19:36:56 +0100 Subject: [PATCH 157/184] Add (disabled) UPEK EikonII (TCRD4C) driver The device driver is always disabled as it uses the same Device ID as another working reader: https://bugzilla.redhat.com/show_bug.cgi?id=504399#c38 --- configure.ac | 8 +- libfprint/Makefile.am | 5 + libfprint/core.c | 3 + libfprint/drivers/upeke2.c | 1462 ++++++++++++++++++++++++++++++++++++ libfprint/fp_internal.h | 3 + 5 files changed, 1480 insertions(+), 1 deletion(-) create mode 100644 libfprint/drivers/upeke2.c diff --git a/configure.ac b/configure.ac index a892a967..d48e95d6 100644 --- a/configure.ac +++ b/configure.ac @@ -19,10 +19,11 @@ AC_SUBST(lt_major) AC_SUBST(lt_revision) AC_SUBST(lt_age) -all_drivers="upekts upektc upeksonly vcom5s uru4000 fdu2000 aes1610 aes2501 aes4000" +all_drivers="upeke2 upekts upektc upeksonly vcom5s uru4000 fdu2000 aes1610 aes2501 aes4000" require_imaging='no' require_aeslib='no' +enable_upeke2='no' enable_upekts='no' enable_upektc='no' enable_upeksonly='no' @@ -44,6 +45,10 @@ for driver in `echo ${drivers} | sed -e 's/,/ /g' -e 's/,$//g'`; do AC_DEFINE([ENABLE_UPEKTS], [], [Build UPEK TouchStrip driver]) enable_upekts="yes" ;; + upeke2) + AC_DEFINE([ENABLE_UPEKE2], [], [Build UPEK Eikon 2]) + enable_upeke2="yes" + ;; upektc) AC_DEFINE([ENABLE_UPEKTC], [], [Build UPEK TouchChip driver]) enable_upektc="yes" @@ -84,6 +89,7 @@ for driver in `echo ${drivers} | sed -e 's/,/ /g' -e 's/,$//g'`; do done AM_CONDITIONAL([ENABLE_UPEKTS], [test "$enable_upekts" != "no"]) +AM_CONDITIONAL([ENABLE_UPEKE2], [test "$enable_upeke2" != "no"]) #AM_CONDITIONAL([ENABLE_UPEKTC], [test "$enable_upektc" != "no"]) AM_CONDITIONAL([ENABLE_UPEKSONLY], [test "$enable_upeksonly" != "no"]) AM_CONDITIONAL([ENABLE_VCOM5S], [test "$enable_vcom5s" != "no"]) diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 83167968..431f66cb 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -2,6 +2,7 @@ lib_LTLIBRARIES = libfprint.la noinst_PROGRAMS = fprint-list-hal-info fprint-list-udev-rules MOSTLYCLEANFILES = $(hal_fdi_DATA) $(udev_rules_DATA) +UPEKE2_SRC = drivers/upeke2.c UPEKTS_SRC = drivers/upekts.c UPEKTC_SRC = drivers/upektc.c UPEKSONLY_SRC = drivers/upeksonly.c @@ -76,6 +77,10 @@ udev_rulesdir = $(sysconfdir)/udev/rules.d/ $(udev_rules_DATA): fprint-list-udev-rules $(builddir)/fprint-list-udev-rules > $@ +if ENABLE_UPEKE2 +DRIVER_SRC += $(UPEKE2_SRC) +endif + if ENABLE_UPEKTS DRIVER_SRC += $(UPEKTS_SRC) endif diff --git a/libfprint/core.c b/libfprint/core.c index 724d5e59..af97bdf5 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -343,6 +343,9 @@ static struct fp_driver * const primitive_drivers[] = { #ifdef ENABLE_UPEKTS &upekts_driver, #endif +#ifdef ENABLE_UPEKE2 + &upeke2_driver, +#endif }; static struct fp_img_driver * const img_drivers[] = { diff --git a/libfprint/drivers/upeke2.c b/libfprint/drivers/upeke2.c new file mode 100644 index 00000000..4139fc5d --- /dev/null +++ b/libfprint/drivers/upeke2.c @@ -0,0 +1,1462 @@ +/* + * Copyright (C) 2010 Jorge Suarez de Lis + * + * Heavily based on UPEK TouchStrip driver for libfprint + * Copyright (C) 2007-2008 Daniel Drake + * + * Based in part on libthinkfinger: + * Copyright (C) 2006-2007 Timo Hoenig + * Copyright (C) 2006 Pavel Machek + * + * LGPL CRC code copied from GStreamer-0.10.10: + * Copyright (C) <1999> Erik Walthinsen + * Copyright (C) 2004,2006 Thomas Vander Stichele + + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; version + * 2.1 of the License. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#define FP_COMPONENT "upeke2" + +#include +#include + +#include +#include + +#include + +#define EP_IN (1 | LIBUSB_ENDPOINT_IN) +#define EP_OUT (2 | LIBUSB_ENDPOINT_OUT) +#define TIMEOUT 5000 + +#define MSG_READ_BUF_SIZE 0x40 +#define MAX_DATA_IN_READ_BUF (MSG_READ_BUF_SIZE - 9) + +struct upeke2_dev { + gboolean enroll_passed; + gboolean first_verify_iteration; + gboolean stop_verify; + uint8_t seq; /* FIXME: improve/automate seq handling */ +}; + +static const uint16_t crc_table[256] = { + 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, + 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, + 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, + 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, + 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, + 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, + 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, + 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, + 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, + 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, + 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, + 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, + 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, + 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, + 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, + 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, + 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, + 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, + 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, + 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, + 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, + 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, + 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, + 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, + 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, + 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, + 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, + 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, + 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, + 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, + 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, + 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 +}; + +static uint16_t udf_crc(unsigned char *buffer, size_t size) +{ + uint16_t crc = 0; + while (size--) + crc = (uint16_t) ((crc << 8) ^ + crc_table[((crc >> 8) & 0x00ff) ^ *buffer++]); + return crc; +} + +/* + * MESSAGE FORMAT + * + * Messages to and from the device have the same format. + * + * Byte-wise: + * 'C' 'i' 'a' 'o' A B L C1 C2 + * + * Ciao prefixes all messages. The rightmost 4 bits of B become the uppermost + * 4 bits of L, and when combined with the lower 8 bits listed as 'L', L is + * the length of the data, is L bytes long. C1 and C2 are the + * UDF-CRC16 for the whole message minus the Ciao prefix. + * + * When the device wants to command the driver to do something, it sends + * a message where B=0 and A!=0. The A value indicates the type of command. + * If the system is expected to respond to the command, it sends a message back + * with B=0 and A incremented. + * + * When the driver sends a command to the device, A=0 and B is used as a + * sequence counter. It starts at 0, increments by 0x10 on each command, and + * wraps around. + * After each command is sent, the device responds with another message + * indicating completion of the command including any data that was requested. + * This message has the same A and B values. + * + * When the driver is sending commands as above, and when the device is + * responding, the seems to follow this structure: + * + * 28 L1 L2 0 0 S + * + * Where the length of is L-3, and S is some kind of subcommand + * code. L1 is the least significant bits of L, L2 is the most significant. In + * the device's response to a command, the subcommand code will be unchanged. + * + * After deducing and documenting the above, I found a few places where the + * above doesn't hold true. Those are marked with FIXME's below. + */ + +#define CMD_SEQ_INCREMENT 0x10 + +static struct libusb_transfer *alloc_send_cmd_transfer(struct fp_dev *dev, + unsigned char seq_a, unsigned char seq_b, const unsigned char *data, + uint16_t len, libusb_transfer_cb_fn callback, void *user_data) +{ + struct libusb_transfer *transfer = libusb_alloc_transfer(0); + uint16_t crc; + + /* 9 bytes extra for: 4 byte 'Ciao', 1 byte A, 1 byte B | lenHI, + * 1 byte lenLO, 2 byte CRC */ + size_t urblen = len + 9; + unsigned char *buf; + + if (!transfer) + return NULL; + + if (!data && len > 0) { + fp_err("len>0 but no data?"); + return NULL; + } + + buf = g_malloc(urblen); + + /* Write header */ + strncpy(buf, "Ciao", 4); + len = GUINT16_TO_LE(len); + buf[4] = seq_a; + buf[5] = seq_b | ((len & 0xf00) >> 8); + buf[6] = len & 0x00ff; + + /* Copy data */ + if (data) + memcpy(buf + 7, data, len); + + /* Append CRC */ + crc = GUINT16_TO_BE(udf_crc(buf + 4, urblen - 6)); + buf[urblen - 2] = crc >> 8; + buf[urblen - 1] = crc & 0xff; + + libusb_fill_bulk_transfer(transfer, dev->udev, EP_OUT, buf, urblen, + callback, user_data, TIMEOUT); + return transfer; +} + +static struct libusb_transfer *alloc_send_cmd28_transfer(struct fp_dev *dev, + unsigned char subcmd, const unsigned char *data, uint16_t innerlen, + libusb_transfer_cb_fn callback, void *user_data) +{ + uint16_t _innerlen = innerlen; + size_t len = innerlen + 6; + unsigned char *buf = g_malloc0(len); + struct upeke2_dev *upekdev = dev->priv; + uint8_t seq = upekdev->seq + CMD_SEQ_INCREMENT; + struct libusb_transfer *ret; + + fp_dbg("seq=%02x subcmd=%02x with %d bytes of data", seq, subcmd, innerlen); + + _innerlen = GUINT16_TO_LE(innerlen + 3); + buf[0] = 0x28; + buf[1] = _innerlen & 0x00ff; + buf[2] = (_innerlen & 0xff00) >> 8; + buf[5] = subcmd; + memcpy(buf + 6, data, innerlen); + + ret = alloc_send_cmd_transfer(dev, 0, seq, buf, len, callback, user_data); + upekdev->seq = seq; + + g_free(buf); + return ret; +} + +static struct libusb_transfer *alloc_send_cmdresponse_transfer( + struct fp_dev *dev, unsigned char seq, const unsigned char *data, + uint8_t len, libusb_transfer_cb_fn callback, void *user_data) +{ + fp_dbg("seq=%02x len=%d", seq, len); + return alloc_send_cmd_transfer(dev, seq, 0, data, len, callback, user_data); +} + +enum read_msg_status { + READ_MSG_ERROR, + READ_MSG_CMD, + READ_MSG_RESPONSE, +}; + +typedef void (*read_msg_cb_fn)(struct fp_dev *dev, enum read_msg_status status, + uint8_t seq, unsigned char subcmd, unsigned char *data, size_t data_len, + void *user_data); + +struct read_msg_data { + struct fp_dev *dev; + read_msg_cb_fn callback; + void *user_data; +}; + +static int __read_msg_async(struct read_msg_data *udata); + +#define READ_MSG_DATA_CB_ERR(udata) (udata)->callback((udata)->dev, \ + READ_MSG_ERROR, 0, 0, NULL, 0, (udata)->user_data) + +static void busy_ack_sent_cb(struct libusb_transfer *transfer) +{ + struct read_msg_data *udata = transfer->user_data; + + if (transfer->status != LIBUSB_TRANSFER_COMPLETED || + transfer->length != transfer->actual_length) { + READ_MSG_DATA_CB_ERR(udata); + g_free(udata); + } else { + int r = __read_msg_async(udata); + if (r < 0) { + READ_MSG_DATA_CB_ERR(udata); + g_free(udata); + } + } + libusb_free_transfer(transfer); +} + +static int busy_ack_retry_read(struct read_msg_data *udata) +{ + struct libusb_transfer *transfer; + int r; + + transfer = alloc_send_cmdresponse_transfer(udata->dev, 0x09, NULL, 0, + busy_ack_sent_cb, udata); + if (!transfer) + return -ENOMEM; + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(transfer->buffer); + libusb_free_transfer(transfer); + } + return r; +} + +/* Returns 0 if message was handled, 1 if it was a device-busy message, and + * negative on error. */ +static int __handle_incoming_msg(struct read_msg_data *udata, + unsigned char *buf) +{ + uint16_t len = GUINT16_FROM_LE(((buf[5] & 0xf) << 8) | buf[6]); + uint16_t computed_crc = udf_crc(buf + 4, len + 3); + uint16_t msg_crc = GUINT16_FROM_LE((buf[len + 8] << 8) | buf[len + 7]); + unsigned char *retdata = NULL; + unsigned char code_a, code_b; + + if (computed_crc != msg_crc) { + fp_err("CRC failed, got %04x expected %04x", msg_crc, computed_crc); + return -1; + } + + code_a = buf[4]; + code_b = buf[5] & 0xf0; + len = GUINT16_FROM_LE(((buf[5] & 0xf) << 8) | buf[6]); + fp_dbg("A=%02x B=%02x len=%d", code_a, code_b, len); + + if (code_a && !code_b) { + /* device sends command to driver */ + fp_dbg("cmd %x from device to driver", code_a); + + if (code_a == 0x08) { + int r; + fp_dbg("device busy, send busy-ack"); + r = busy_ack_retry_read(udata); + return (r < 0) ? r : 1; + } + + if (len > 0) { + retdata = g_malloc(len); + memcpy(retdata, buf + 7, len); + } + udata->callback(udata->dev, READ_MSG_CMD, code_a, 0, retdata, len, + udata->user_data); + g_free(retdata); + } else if (!code_a) { + /* device sends response to a previously executed command */ + unsigned char *innerbuf = buf + 7; + unsigned char _subcmd; + uint16_t innerlen; + + if (len < 6) { + fp_err("cmd response too short (%d)", len); + return -1; + } + if (innerbuf[0] != 0x28) { + fp_err("cmd response without 28 byte?"); + return -1; + } + + /* not really sure what these 2 bytes are. on most people's hardware, + * these bytes are always 0. However, Alon Bar-Lev's hardware gives + * 0xfb 0xff during the READ28_OB initsm stage. so don't error out + * if they are different... */ + if (innerbuf[3] || innerbuf[4]) + fp_dbg("non-zero bytes in cmd response"); + + innerlen = innerbuf[1] | (innerbuf[2] << 8); + innerlen = GUINT16_FROM_LE(innerlen) - 3; + _subcmd = innerbuf[5]; + fp_dbg("device responds to subcmd %x with %d bytes", _subcmd, innerlen); + if (innerlen > 0) { + retdata = g_malloc(innerlen); + memcpy(retdata, innerbuf + 6, innerlen); + } + udata->callback(udata->dev, READ_MSG_RESPONSE, code_b, _subcmd, + retdata, innerlen, udata->user_data); + g_free(retdata); + } else { + fp_err("don't know how to handle this message"); + return -1; + } + return 0; +} + +static void read_msg_extend_cb(struct libusb_transfer *transfer) +{ + struct read_msg_data *udata = transfer->user_data; + unsigned char *buf = transfer->buffer - MSG_READ_BUF_SIZE; + int handle_result = 0; + + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { + fp_err("extended msg read failed, code %d", transfer->status); + goto err; + } + if (transfer->actual_length < transfer->length) { + fp_err("extended msg short read (%d/%d)", transfer->actual_length, + transfer->length); + goto err; + } + + handle_result = __handle_incoming_msg(udata, buf); + if (handle_result < 0) + goto err; + goto out; + +err: + READ_MSG_DATA_CB_ERR(udata); +out: + if (handle_result != 1) + g_free(udata); + g_free(buf); + libusb_free_transfer(transfer); +} + +static void read_msg_cb(struct libusb_transfer *transfer) +{ + struct read_msg_data *udata = transfer->user_data; + unsigned char *data = transfer->buffer; + uint16_t len; + int handle_result = 0; + + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { + fp_err("async msg read failed, code %d", transfer->status); + goto err; + } + if (transfer->actual_length < 9) { + fp_err("async msg read too short (%d)", transfer->actual_length); + goto err; + } + + if (strncmp(data, "Ciao", 4) != 0) { + fp_err("no Ciao for you!!"); + goto err; + } + + len = GUINT16_FROM_LE(((data[5] & 0xf) << 8) | data[6]); + if (transfer->actual_length != MSG_READ_BUF_SIZE + && (len + 9) > transfer->actual_length) { + /* Check that the length claimed inside the message is in line with + * the amount of data that was transferred over USB. */ + fp_err("msg didn't include enough data, expected=%d recv=%d", + len + 9, transfer->actual_length); + goto err; + } + + /* We use a 64 byte buffer for reading messages. However, sometimes + * messages are longer, in which case we have to do another USB bulk read + * to read the remainder. This is handled below. */ + if (len > MAX_DATA_IN_READ_BUF) { + int needed = len - MAX_DATA_IN_READ_BUF; + struct libusb_transfer *etransfer = libusb_alloc_transfer(0); + int r; + + if (!transfer) + goto err; + + fp_dbg("didn't fit in buffer, need to extend by %d bytes", needed); + data = g_realloc((gpointer) data, MSG_READ_BUF_SIZE + needed); + + libusb_fill_bulk_transfer(etransfer, udata->dev->udev, EP_IN, + data + MSG_READ_BUF_SIZE, needed, read_msg_extend_cb, udata, + TIMEOUT); + + r = libusb_submit_transfer(etransfer); + if (r < 0) { + fp_err("extended read submission failed"); + /* FIXME memory leak here? */ + goto err; + } + libusb_free_transfer(transfer); + return; + } + + handle_result = __handle_incoming_msg(udata, data); + if (handle_result < 0) + goto err; + goto out; + +err: + READ_MSG_DATA_CB_ERR(udata); +out: + libusb_free_transfer(transfer); + if (handle_result != 1) + g_free(udata); + g_free(data); +} + +static int __read_msg_async(struct read_msg_data *udata) +{ + unsigned char *buf = g_malloc(MSG_READ_BUF_SIZE); + struct libusb_transfer *transfer = libusb_alloc_transfer(0); + int r; + + if (!transfer) { + g_free(buf); + return -ENOMEM; + } + + libusb_fill_bulk_transfer(transfer, udata->dev->udev, EP_IN, buf, + MSG_READ_BUF_SIZE, read_msg_cb, udata, TIMEOUT); + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(buf); + libusb_free_transfer(transfer); + } + + return r; +} + +static int read_msg_async(struct fp_dev *dev, read_msg_cb_fn callback, + void *user_data) +{ + struct read_msg_data *udata = g_malloc(sizeof(*udata)); + int r; + + udata->dev = dev; + udata->callback = callback; + udata->user_data = user_data; + r = __read_msg_async(udata); + if (r) + g_free(udata); + return r; +} + +static const unsigned char init_resp03[] = { + 0x01, 0x00, 0xbc, 0x02, 0x00, 0x00, 0x00, 0x00 +}; + +static const unsigned char init28_08[] = { + 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x31, 0x00, 0x00, 0x00, 0x38, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, + 0x00, 0x00, 0x05, 0x1f, 0x88, 0x59, 0x2a, 0x09, 0x7e, 0x35, 0x2f, 0x68, 0xc8, 0x10, 0x4f, 0x19, + 0xd6, 0xea, 0xc8, 0xd9, 0x41, 0x73, 0x14, 0x99, 0xa8, 0x77, 0x94, 0xa0, 0x9c, 0xe3, 0x8b, 0x77, + 0xf8, 0x83, 0xdc, 0x14, 0xef, 0x2b, 0x5f, 0xaa, 0xb7, 0x18, 0x3b, 0x7d, 0x11, 0x71, 0xf5, 0x95, + 0x18, 0x6f, 0x40, 0xcd, 0x5d, 0xbd, 0x13, 0x58, 0x15, 0x10, 0x03, 0xdb, 0x96, 0x86, 0xc6, 0x25, + 0xdd, 0x61, 0x7f, 0x54 +}; + +/* device initialisation state machine */ + +enum initsm_states { + WRITE_CTRL400 = 0, + READ_MSG03, + SEND_RESP03, + READ_MSG05, + SEND28_06, + READ28_06, + SEND28_51, + READ28_51, + SEND28_07, + READ28_07, + SEND28_08, + READ28_08, + INITSM_NUM_STATES +}; + +static void initsm_read_msg_response_cb(struct fpi_ssm *ssm, + enum read_msg_status status, uint8_t seq, + unsigned char expect_subcmd, unsigned char subcmd) +{ + struct fp_dev *dev = ssm->dev; + struct upeke2_dev *upekdev = dev->priv; + + if (status != READ_MSG_RESPONSE) { + fp_err("expected response, got %d seq=%x in state %d", status, seq, + ssm->cur_state); + fpi_ssm_mark_aborted(ssm, -1); + } else if (subcmd != expect_subcmd) { + fp_warn("expected response to subcmd 0x%02x, got response to %02x in " + "state %d", expect_subcmd, subcmd, ssm->cur_state); + fpi_ssm_mark_aborted(ssm, -1); + } else if (seq != upekdev->seq) { + fp_err("expected response to cmd seq=%02x, got response to %02x " + "in state %d", upekdev->seq, seq, ssm->cur_state); + fpi_ssm_mark_aborted(ssm, -1); + } else { + fp_dbg("state %d completed", ssm->cur_state); + fpi_ssm_next_state(ssm); + } +} +static void read28_08_cb(struct fp_dev *dev, enum read_msg_status status, + uint8_t seq, unsigned char subcmd, unsigned char *data, size_t data_len, + void *user_data) +{ + initsm_read_msg_response_cb((struct fpi_ssm *) user_data, status, seq, + 0x08, subcmd); +} + +static void read28_07_cb(struct fp_dev *dev, enum read_msg_status status, + uint8_t seq, unsigned char subcmd, unsigned char *data, size_t data_len, + void *user_data) +{ + initsm_read_msg_response_cb((struct fpi_ssm *) user_data, status, seq, + 0x07, subcmd); +} + +static void read28_51_cb(struct fp_dev *dev, enum read_msg_status status, + uint8_t seq, unsigned char subcmd, unsigned char *data, size_t data_len, + void *user_data) +{ + initsm_read_msg_response_cb((struct fpi_ssm *) user_data, status, seq, + 0x51, subcmd); +} + +static void read28_06_cb(struct fp_dev *dev, enum read_msg_status status, + uint8_t seq, unsigned char subcmd, unsigned char *data, size_t data_len, + void *user_data) +{ + initsm_read_msg_response_cb((struct fpi_ssm *) user_data, status, seq, + 0x06, subcmd); +} + +static void initsm_read_msg_cmd_cb(struct fpi_ssm *ssm, + enum read_msg_status status, uint8_t expect_seq, uint8_t seq) +{ + struct fp_dev *dev = ssm->dev; + struct upeke2_dev *upekdev = dev->priv; + + if (status == READ_MSG_ERROR) { + fpi_ssm_mark_aborted(ssm, -1); + return; + } else if (status != READ_MSG_CMD) { + fp_err("expected command, got %d seq=%x in state %d", status, seq, + ssm->cur_state); + fpi_ssm_mark_aborted(ssm, -1); + return; + } + upekdev->seq = seq; + if (seq != expect_seq) { + fp_err("expected seq=%x, got %x in state %d", expect_seq, seq, + ssm->cur_state); + fpi_ssm_mark_aborted(ssm, -1); + return; + } + + fpi_ssm_next_state(ssm); +} + +static void read_msg05_cb(struct fp_dev *dev, enum read_msg_status status, + uint8_t seq, unsigned char subcmd, unsigned char *data, size_t data_len, + void *user_data) +{ + initsm_read_msg_cmd_cb((struct fpi_ssm *) user_data, status, 5, seq); +} + +static void read_msg03_cb(struct fp_dev *dev, enum read_msg_status status, + uint8_t seq, unsigned char subcmd, unsigned char *data, size_t data_len, + void *user_data) +{ + initsm_read_msg_cmd_cb((struct fpi_ssm *) user_data, status, 3, seq); +} + +static void ctrl400_cb(struct libusb_transfer *transfer) +{ + struct fpi_ssm *ssm = transfer->user_data; + /* FIXME check length? */ + if (transfer->status == LIBUSB_TRANSFER_COMPLETED) + fpi_ssm_next_state(ssm); + else + fpi_ssm_mark_aborted(ssm, -1); + g_free(transfer->buffer); + libusb_free_transfer(transfer); +} + +static void initsm_read_msg_handler(struct fpi_ssm *ssm, + read_msg_cb_fn callback) +{ + int r = read_msg_async(ssm->dev, callback, ssm); + if (r < 0) { + fp_err("async read msg failed in state %d", ssm->cur_state); + fpi_ssm_mark_aborted(ssm, r); + } +} + +static void initsm_send_msg_cb(struct libusb_transfer *transfer) +{ + struct fpi_ssm *ssm = transfer->user_data; + if (transfer->status == LIBUSB_TRANSFER_COMPLETED + && transfer->length == transfer->actual_length) { + fp_dbg("state %d completed", ssm->cur_state); + fpi_ssm_next_state(ssm); + } else { + fp_err("failed, state=%d rqlength=%d actual_length=%d", ssm->cur_state, + transfer->length, transfer->actual_length); + fpi_ssm_mark_aborted(ssm, -1); + } + libusb_free_transfer(transfer); +} + +static void initsm_send_msg28_handler(struct fpi_ssm *ssm, + unsigned char subcmd, const unsigned char *data, uint16_t innerlen) +{ + struct fp_dev *dev = ssm->dev; + struct libusb_transfer *transfer; + int r; + + transfer = alloc_send_cmd28_transfer(dev, subcmd, data, innerlen, + initsm_send_msg_cb, ssm); + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + return; + } + + r = libusb_submit_transfer(transfer); + if (r < 0) { + fp_err("urb submission failed error %d in state %d", r, ssm->cur_state); + g_free(transfer->buffer); + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, -EIO); + } +} + +static void initsm_run_state(struct fpi_ssm *ssm) +{ + struct fp_dev *dev = ssm->dev; + struct upeke2_dev *upekdev = dev->priv; + struct libusb_transfer *transfer; + int r; + + switch (ssm->cur_state) { + case WRITE_CTRL400: ; + unsigned char *data; + + transfer = libusb_alloc_transfer(0); + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + break; + } + + data = g_malloc(LIBUSB_CONTROL_SETUP_SIZE + 1); + libusb_fill_control_setup(data, + LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE, 0x0c, 0x100, 0x0400, 1); + libusb_fill_control_transfer(transfer, ssm->dev->udev, data, + ctrl400_cb, ssm, TIMEOUT); + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(data); + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, r); + } + break; + case READ_MSG03: + initsm_read_msg_handler(ssm, read_msg03_cb); + break; + case SEND_RESP03: ; + transfer = alloc_send_cmdresponse_transfer(dev, ++upekdev->seq, + init_resp03, sizeof(init_resp03), initsm_send_msg_cb, ssm); + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + break; + } + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(transfer->buffer); + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, r); + } + break; + case READ_MSG05: + initsm_read_msg_handler(ssm, read_msg05_cb); + break; + case SEND28_06: ; + unsigned char dummy28_06 = 0x04; + upekdev->seq = 0xf0; + initsm_send_msg28_handler(ssm, 0x06, &dummy28_06, 1); + break; + case READ28_06: + initsm_read_msg_handler(ssm, read28_06_cb); + break; + case SEND28_51: ; + unsigned char dummy28_51[] = { 0x04, 0x0a, 0x00, 0x00, 0x00 }; + initsm_send_msg28_handler(ssm, 0x51, &dummy28_51, 5); + break; + case READ28_51: + initsm_read_msg_handler(ssm, read28_51_cb); + break; + case SEND28_07: ; + unsigned char dummy28_07[] = { 0x04, 0x20, 0x00, 0x00, 0x00 }; + initsm_send_msg28_handler(ssm, 0x07, &dummy28_07, 5); + break; + case READ28_07: + initsm_read_msg_handler(ssm, read28_07_cb); + break; + case SEND28_08: + initsm_send_msg28_handler(ssm, 0x08, init28_08, sizeof(init28_08)); + break; + case READ28_08: + initsm_read_msg_handler(ssm, read28_08_cb); + break; + } +} + +static struct fpi_ssm *initsm_new(struct fp_dev *dev) +{ + return fpi_ssm_new(dev, initsm_run_state, INITSM_NUM_STATES); +} + +enum deinitsm_states { + SEND_RESP07 = 0, + READ_MSG01, + DEINITSM_NUM_STATES, +}; + +static void send_resp07_cb(struct libusb_transfer *transfer) +{ + struct fpi_ssm *ssm = transfer->user_data; + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) + fpi_ssm_mark_aborted(ssm, -EIO); + else if (transfer->length != transfer->actual_length) + fpi_ssm_mark_aborted(ssm, -EPROTO); + else + fpi_ssm_next_state(ssm); + libusb_free_transfer(transfer); +} + +static void read_msg01_cb(struct fp_dev *dev, enum read_msg_status status, + uint8_t seq, unsigned char subcmd, unsigned char *data, size_t data_len, + void *user_data) +{ + struct fpi_ssm *ssm = user_data; + struct upeke2_dev *upekdev = dev->priv; + + if (status == READ_MSG_ERROR) { + fpi_ssm_mark_aborted(ssm, -1); + return; + } else if (status != READ_MSG_CMD) { + fp_err("expected command, got %d seq=%x", status, seq); + fpi_ssm_mark_aborted(ssm, -1); + return; + } + upekdev->seq = seq; + if (seq != 1) { + fp_err("expected seq=1, got %x", seq); + fpi_ssm_mark_aborted(ssm, -1); + return; + } + + fpi_ssm_next_state(ssm); +} + +static void deinitsm_state_handler(struct fpi_ssm *ssm) +{ + struct fp_dev *dev = ssm->dev; + int r; + + switch (ssm->cur_state) { + case SEND_RESP07: ; + struct libusb_transfer *transfer; + unsigned char dummy = 0; + + transfer = alloc_send_cmdresponse_transfer(dev, 0x07, &dummy, 1, + send_resp07_cb, ssm); + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + break; + } + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(transfer->buffer); + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, r); + } + break; + case READ_MSG01: ; + r = read_msg_async(dev, read_msg01_cb, ssm); + if (r < 0) + fpi_ssm_mark_aborted(ssm, r); + break; + } +} + +static struct fpi_ssm *deinitsm_new(struct fp_dev *dev) +{ + return fpi_ssm_new(dev, deinitsm_state_handler, DEINITSM_NUM_STATES); +} + +static int dev_init(struct fp_dev *dev, unsigned long driver_data) +{ + struct upeke2_dev *upekdev = NULL; + int r; + + r = libusb_claim_interface(dev->udev, 0); + if (r < 0) + return r; + + upekdev = g_malloc(sizeof(*upekdev)); + upekdev->seq = 0xf0; /* incremented to 0x00 before first cmd */ + dev->priv = upekdev; + dev->nr_enroll_stages = 5; + + fpi_drvcb_open_complete(dev, 0); + return 0; +} + +static void dev_exit(struct fp_dev *dev) +{ + libusb_release_interface(dev->udev, 0); + g_free(dev->priv); + fpi_drvcb_close_complete(dev); +} + +static const unsigned char enroll_init[] = { + 0x02, 0xc0, 0xd4, 0x01, 0x00, 0x04, 0x00, 0x08 +}; +static const unsigned char scan_comp[] = { + 0x12, 0xff, 0xff, 0xff, 0xff /* scan completion, prefixes print data */ +}; + +/* used for enrollment and verification */ +static const unsigned char poll_data[] = { 0x30, 0x01 }; + +enum enroll_start_sm_states { + RUN_INITSM = 0, + ENROLL_INIT, + READ_ENROLL_MSG28, + ENROLL_START_NUM_STATES, +}; + +/* Called when the device initialization state machine completes */ +static void enroll_start_sm_cb_initsm(struct fpi_ssm *initsm) +{ + struct fpi_ssm *enroll_start_ssm = initsm->priv; + int error = initsm->error; + + fpi_ssm_free(initsm); + if (error) + fpi_ssm_mark_aborted(enroll_start_ssm, error); + else + fpi_ssm_next_state(enroll_start_ssm); +} + +/* called when enroll init URB has completed */ +static void enroll_start_sm_cb_init(struct libusb_transfer *transfer) +{ + struct fpi_ssm *ssm = transfer->user_data; + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) + fpi_ssm_mark_aborted(ssm, -EIO); + else if (transfer->length != transfer->actual_length) + fpi_ssm_mark_aborted(ssm, -EPROTO); + else + fpi_ssm_next_state(ssm); + libusb_free_transfer(transfer); +} + +static void enroll_start_sm_cb_msg28(struct fp_dev *dev, + enum read_msg_status status, uint8_t seq, unsigned char subcmd, + unsigned char *data, size_t data_len, void *user_data) +{ + struct upeke2_dev *upekdev = dev->priv; + struct fpi_ssm *ssm = user_data; + + if (status != READ_MSG_RESPONSE) { + fp_err("expected response, got %d seq=%x", status, seq); + fpi_ssm_mark_aborted(ssm, -1); + } else if (subcmd != 0) { + fp_warn("expected response to subcmd 0, got response to %02x", + subcmd); + fpi_ssm_mark_aborted(ssm, -1); + } else if (seq != upekdev->seq) { + fp_err("expected response to cmd seq=%02x, got response to %02x", + upekdev->seq, seq); + fpi_ssm_mark_aborted(ssm, -1); + } else { + fpi_ssm_next_state(ssm); + } +} + +static void enroll_start_sm_run_state(struct fpi_ssm *ssm) +{ + struct fp_dev *dev = ssm->dev; + int r; + + switch (ssm->cur_state) { + case RUN_INITSM: ; + struct fpi_ssm *initsm = initsm_new(dev); + initsm->priv = ssm; + fpi_ssm_start(initsm, enroll_start_sm_cb_initsm); + break; + case ENROLL_INIT: ; + struct libusb_transfer *transfer; + transfer = alloc_send_cmd28_transfer(dev, 0x02, enroll_init, + sizeof(enroll_init), enroll_start_sm_cb_init, ssm); + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + break; + } + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(transfer->buffer); + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, r); + } + break; + case READ_ENROLL_MSG28: ; + /* FIXME: protocol misunderstanding here. device receives response + * to subcmd 0 after submitting subcmd 2? */ + /* actually this is probably a poll response? does the above cmd + * include a 30 01 poll somewhere? */ + r = read_msg_async(dev, enroll_start_sm_cb_msg28, ssm); + //if (r < 0) + //fpi_ssm_mark_aborted(ssm, r); + break; + } +} + +static void enroll_iterate(struct fp_dev *dev); + +static void e_handle_resp00(struct fp_dev *dev, unsigned char *data, + size_t data_len) +{ + + + struct upeke2_dev *upekdev = dev->priv; + unsigned char status; + int result = 0; + + if (data_len != 14) { + fp_err("received 3001 poll response of %d bytes?", data_len); + fpi_drvcb_enroll_stage_completed(dev, -EPROTO, NULL, NULL); + return; + } + + status = data[5]; + fp_dbg("poll result = %02x", status); + + switch (status) { + case 0x0c: + case 0x0d: + case 0x0e: + case 0x26: + case 0x27: + /* if we previously completed a non-last enrollment stage, we'll + * get this code to indicate successful stage completion */ + if (upekdev->enroll_passed) { + result = FP_ENROLL_PASS; + upekdev->enroll_passed = FALSE; + } + /* otherwise it just means "no news" so we poll again */ + break; + case 0x1c: /* FIXME what does this one mean? */ + case 0x0b: /* FIXME what does this one mean? */ + case 0x23: /* FIXME what does this one mean? */ + result = FP_ENROLL_RETRY; + break; + case 0x0f: /* scan taking too long, remove finger and try again */ + result = FP_ENROLL_RETRY_REMOVE_FINGER; + break; + case 0x1e: /* swipe too short */ + result = FP_ENROLL_RETRY_TOO_SHORT; + break; + case 0x24: /* finger not centered */ + result = FP_ENROLL_RETRY_CENTER_FINGER; + break; + case 0x20: + /* finger scanned successfully */ + /* need to look at the next poll result to determine if enrollment is + * complete or not */ + upekdev->enroll_passed = 1; + break; + case 0x00: /* enrollment complete */ + /* we can now expect the enrollment data on the next poll, so we + * have nothing to do here */ + break; + default: + fp_err("unrecognised scan status code %02x", status); + result = -EPROTO; + break; + } + + if (result) { + fpi_drvcb_enroll_stage_completed(dev, result, NULL, NULL); + if (result > 0){ + enroll_iterate(dev); + } + } else { + enroll_iterate(dev); + } + + /* FIXME: need to extend protocol research to handle the case when + * enrolment fails, e.g. you scan a different finger on each stage */ + /* FIXME: should do proper tracking of when we expect cmd0 results and + * cmd2 results and enforce it */ +} + +static void e_handle_resp02(struct fp_dev *dev, unsigned char *data, + size_t data_len) +{ + struct fp_print_data *fdata = NULL; + int result = -EPROTO; + + if (data_len < sizeof(scan_comp)) { + fp_err("fingerprint data too short (%d bytes)", data_len); + } else if (memcmp(data, scan_comp, sizeof(scan_comp)) != 0) { + fp_err("unrecognised data prefix %x %x %x %x %x", + data[0], data[1], data[2], data[3], data[4]); + } else { + fdata = fpi_print_data_new(dev, data_len - sizeof(scan_comp)); + memcpy(fdata->data, data + sizeof(scan_comp), + data_len - sizeof(scan_comp)); + + result = FP_ENROLL_COMPLETE; + } + + fpi_drvcb_enroll_stage_completed(dev, result, fdata, NULL); +} + +static void enroll_iterate_msg_cb(struct fp_dev *dev, + enum read_msg_status msgstat, uint8_t seq, unsigned char subcmd, + unsigned char *data, size_t data_len, void *user_data) +{ + if (msgstat != READ_MSG_RESPONSE) { + fp_err("expected response, got %d seq=%x", msgstat, seq); + fpi_drvcb_enroll_stage_completed(dev, -EPROTO, NULL, NULL); + return; + } + if (subcmd == 0) { + e_handle_resp00(dev, data, data_len); + } else if (subcmd == 2) { + e_handle_resp02(dev, data, data_len); + } else { + fp_err("unexpected subcmd %d", subcmd); + fpi_drvcb_enroll_stage_completed(dev, -EPROTO, NULL, NULL); + } + +} + +static void enroll_iterate_cmd_cb(struct libusb_transfer *transfer) +{ + struct fp_dev *dev = transfer->user_data; + + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { + fpi_drvcb_enroll_stage_completed(dev, -EIO, NULL, NULL); + } else if (transfer->length != transfer->actual_length) { + fpi_drvcb_enroll_stage_completed(dev, -EPROTO, NULL, NULL); + } else { + int r = read_msg_async(dev, enroll_iterate_msg_cb, NULL); + if (r < 0) + fpi_drvcb_enroll_stage_completed(dev, r, NULL, NULL); + } + libusb_free_transfer(transfer); +} + +static void enroll_iterate(struct fp_dev *dev) +{ + int r; + struct libusb_transfer *transfer = alloc_send_cmd28_transfer(dev, 0x00, + poll_data, sizeof(poll_data), enroll_iterate_cmd_cb, dev); + + if (!transfer) { + fpi_drvcb_enroll_stage_completed(dev, -ENOMEM, NULL, NULL); + return; + } + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(transfer->buffer); + libusb_free_transfer(transfer); + fpi_drvcb_enroll_stage_completed(dev, -EIO, NULL, NULL); + } +} + +static void enroll_started(struct fpi_ssm *ssm) +{ + struct fp_dev *dev = ssm->dev; + fpi_drvcb_enroll_started(dev, ssm->error); + + if (!ssm->error) + enroll_iterate(dev); + + fpi_ssm_free(ssm); +} + +static int enroll_start(struct fp_dev *dev) +{ + struct upeke2_dev *upekdev = dev->priv; + + /* do_init state machine first */ + struct fpi_ssm *ssm = fpi_ssm_new(dev, enroll_start_sm_run_state, + ENROLL_START_NUM_STATES); + + upekdev->enroll_passed = FALSE; + fpi_ssm_start(ssm, enroll_started); + return 0; +} + +static void enroll_stop_deinit_cb(struct fpi_ssm *ssm) +{ + /* don't really care about errors */ + fpi_drvcb_enroll_stopped(ssm->dev); + fpi_ssm_free(ssm); +} + +static int enroll_stop(struct fp_dev *dev) +{ + struct fpi_ssm *ssm = deinitsm_new(dev); + fpi_ssm_start(ssm, enroll_stop_deinit_cb); + return 0; +} + +static void verify_stop_deinit_cb(struct fpi_ssm *ssm) +{ + /* don't really care about errors */ + fpi_drvcb_verify_stopped(ssm->dev); + fpi_ssm_free(ssm); +} + +static void do_verify_stop(struct fp_dev *dev) +{ + struct fpi_ssm *ssm = deinitsm_new(dev); + fpi_ssm_start(ssm, verify_stop_deinit_cb); +} + +static const unsigned char verify_hdr[] = { + 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0xc0, 0xd4, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, + 0x00 +}; + +enum { + VERIFY_RUN_INITSM = 0, + VERIFY_INIT, + VERIFY_NUM_STATES, +}; + +/* Called when the device initialization state machine completes */ +static void verify_start_sm_cb_initsm(struct fpi_ssm *initsm) +{ + struct fpi_ssm *verify_start_ssm = initsm->priv; + if (initsm->error) + fpi_ssm_mark_aborted(verify_start_ssm, initsm->error); + else + fpi_ssm_next_state(verify_start_ssm); + fpi_ssm_free(initsm); +} + +static void verify_init_2803_cb(struct libusb_transfer *transfer) +{ + struct fpi_ssm *ssm = transfer->user_data; + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) + fpi_ssm_mark_aborted(ssm, -EIO); + else if (transfer->length != transfer->actual_length) + fpi_ssm_mark_aborted(ssm, -EPROTO); + else + fpi_ssm_next_state(ssm); + libusb_free_transfer(transfer); +} + +static void verify_start_sm_run_state(struct fpi_ssm *ssm) +{ + struct fp_dev *dev = ssm->dev; + int r; + + switch (ssm->cur_state) { + case VERIFY_RUN_INITSM: ; + struct fpi_ssm *initsm = initsm_new(dev); + initsm->priv = ssm; + fpi_ssm_start(initsm, verify_start_sm_cb_initsm); + break; + case VERIFY_INIT: ; + struct fp_print_data *print = dev->verify_data; + size_t data_len = sizeof(verify_hdr) + print->length; + unsigned char *data = g_malloc(data_len); + struct libusb_transfer *transfer; + + memcpy(data, verify_hdr, sizeof(verify_hdr)); + memcpy(data + sizeof(verify_hdr), print->data, print->length); + transfer = alloc_send_cmd28_transfer(dev, 0x03, data, data_len, + verify_init_2803_cb, ssm); + g_free(data); + if (!transfer) { + fpi_ssm_mark_aborted(ssm, -ENOMEM); + break; + } + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(transfer->buffer); + libusb_free_transfer(transfer); + fpi_ssm_mark_aborted(ssm, -EIO); + } + break; + } +} + +static void verify_iterate(struct fp_dev *dev); + +static void v_handle_resp00(struct fp_dev *dev, unsigned char *data, + size_t data_len) +{ + unsigned char status; + int r = 0; + + if (data_len != 14) { + fp_err("received 3001 poll response of %d bytes?", data_len); + r = -EPROTO; + goto out; + } + + status = data[5]; + fp_dbg("poll result = %02x", status); + + /* These codes indicate that we're waiting for a finger scan, so poll + * again */ + switch (status) { + case 0x0c: /* no news, poll again */ + break; + case 0x20: + fp_dbg("processing scan for verification"); + break; + case 0x00: + fp_dbg("good image"); + break; + case 0x1c: /* FIXME what does this one mean? */ + case 0x0b: /* FIXME what does this one mean? */ + case 0x23: /* FIXME what does this one mean? */ + r = FP_VERIFY_RETRY; + break; + case 0x0f: /* scan taking too long, remove finger and try again */ + r = FP_VERIFY_RETRY_REMOVE_FINGER; + break; + case 0x1e: /* swipe too short */ + r = FP_VERIFY_RETRY_TOO_SHORT; + break; + case 0x24: /* finger not centered */ + r = FP_VERIFY_RETRY_CENTER_FINGER; + break; + default: + fp_err("unrecognised verify status code %02x", status); + r = -EPROTO; + } + +out: + if (r) + fpi_drvcb_report_verify_result(dev, r, NULL); + if (r >= 0) + verify_iterate(dev); +} + +static void v_handle_resp03(struct fp_dev *dev, unsigned char *data, + size_t data_len) +{ + int r; + + if (data_len < 2) { + fp_err("verify result abnormally short!"); + r = -EPROTO; + } else if (data[0] != 0x12) { + fp_err("unexpected verify header byte %02x", data[0]); + r = -EPROTO; + } else if (data[1] == 0x00) { + r = FP_VERIFY_NO_MATCH; + } else if (data[1] == 0x01) { + r = FP_VERIFY_MATCH; + } else { + fp_err("unrecognised verify result %02x", data[1]); + r = -EPROTO; + } + fpi_drvcb_report_verify_result(dev, r, NULL); +} + +static void verify_rd2800_cb(struct fp_dev *dev, enum read_msg_status msgstat, + uint8_t seq, unsigned char subcmd, unsigned char *data, size_t data_len, + void *user_data) +{ + struct upeke2_dev *upekdev = dev->priv; + + if (msgstat != READ_MSG_RESPONSE) { + fp_err("expected response, got %d seq=%x", msgstat, seq); + fpi_drvcb_report_verify_result(dev, -EPROTO, NULL); + return; + } else if (seq != upekdev->seq) { + fp_err("expected response to cmd seq=%02x, got response to %02x", + upekdev->seq, seq); + fpi_drvcb_report_verify_result(dev, -EPROTO, NULL); + return; + } + + if (subcmd == 0) + v_handle_resp00(dev, data, data_len); + else if (subcmd == 3) + v_handle_resp03(dev, data, data_len); + else + fpi_drvcb_report_verify_result(dev, -EPROTO, NULL); +} + +static void verify_wr2800_cb(struct libusb_transfer *transfer) +{ + struct fp_dev *dev = transfer->user_data; + + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { + fpi_drvcb_report_verify_result(dev, -EIO, NULL); + } else if (transfer->length != transfer->actual_length) { + fpi_drvcb_report_verify_result(dev, -EIO, NULL); + } else { + int r = read_msg_async(dev, verify_rd2800_cb, NULL); + if (r < 0) + fpi_drvcb_report_verify_result(dev, r, NULL); + } + libusb_free_transfer(transfer); +} + +static void verify_iterate(struct fp_dev *dev) +{ + struct upeke2_dev *upekdev = dev->priv; + + if (upekdev->stop_verify) { + do_verify_stop(dev); + return; + } + + /* FIXME: this doesn't flow well, should the first cmd be moved from + * verify init to here? */ + if (upekdev->first_verify_iteration) { + int r = read_msg_async(dev, verify_rd2800_cb, NULL); + upekdev->first_verify_iteration = FALSE; + if (r < 0) + fpi_drvcb_report_verify_result(dev, r, NULL); + } else { + int r; + struct libusb_transfer *transfer = alloc_send_cmd28_transfer(dev, + 0x00, poll_data, sizeof(poll_data), verify_wr2800_cb, dev); + + if (!transfer) { + fpi_drvcb_report_verify_result(dev, -ENOMEM, NULL); + return; + } + + r = libusb_submit_transfer(transfer); + if (r < 0) { + g_free(transfer->buffer); + libusb_free_transfer(transfer); + fpi_drvcb_report_verify_result(dev, -EIO, NULL); + } + } +} + +static void verify_started(struct fpi_ssm *ssm) +{ + struct fp_dev *dev = ssm->dev; + struct upeke2_dev *upekdev = dev->priv; + + fpi_drvcb_verify_started(dev, ssm->error); + if (!ssm->error) { + upekdev->first_verify_iteration = TRUE; + verify_iterate(dev); + } + + fpi_ssm_free(ssm); +} + +static int verify_start(struct fp_dev *dev) +{ + struct upeke2_dev *upekdev = dev->priv; + struct fpi_ssm *ssm = fpi_ssm_new(dev, verify_start_sm_run_state, + VERIFY_NUM_STATES); + upekdev->stop_verify = FALSE; + fpi_ssm_start(ssm, verify_started); + return 0; +} + +static int verify_stop(struct fp_dev *dev, gboolean iterating) +{ + struct upeke2_dev *upekdev = dev->priv; + + if (!iterating) + do_verify_stop(dev); + else + upekdev->stop_verify = TRUE; + return 0; +} + +static const struct usb_id id_table[] = { +/* FIXME: Disabled for now, as this clashes with the upeksonly driver */ +/* { .vendor = 0x147e, .product = 0x2016 }, */ + { 0, 0, 0, }, /* terminating entry */ +}; + +struct fp_driver upeke2_driver = { + .id = 1, + .name = FP_COMPONENT, + .full_name = "UPEK Eikon 2", + .id_table = id_table, + .scan_type = FP_SCAN_TYPE_SWIPE, + .open = dev_init, + .close = dev_exit, + .enroll_start = enroll_start, + .enroll_stop = enroll_stop, + .verify_start = verify_start, + .verify_stop = verify_stop, +}; + diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index bebf3241..5196ca20 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -238,6 +238,9 @@ struct fp_img_driver { #ifdef ENABLE_UPEKTS extern struct fp_driver upekts_driver; #endif +#ifdef ENABLE_UPEKE2 +extern struct fp_driver upeke2_driver; +#endif #ifdef ENABLE_UPEKTC extern struct fp_img_driver upektc_driver; #endif From 48af46a2c504b43854a3877d962a301921ef7f86 Mon Sep 17 00:00:00 2001 From: Jorge Suarez de Lis Date: Tue, 17 Aug 2010 19:55:48 +0100 Subject: [PATCH 158/184] upeke2: Add support for 0x2e status code As reported working in: http://www.mail-archive.com/fprint@reactivated.net/msg01426.html --- libfprint/drivers/upeke2.c | 1 + 1 file changed, 1 insertion(+) diff --git a/libfprint/drivers/upeke2.c b/libfprint/drivers/upeke2.c index 4139fc5d..f4a812d7 100644 --- a/libfprint/drivers/upeke2.c +++ b/libfprint/drivers/upeke2.c @@ -1000,6 +1000,7 @@ static void e_handle_resp00(struct fp_dev *dev, unsigned char *data, case 0x0e: case 0x26: case 0x27: + case 0x2e: /* if we previously completed a non-last enrollment stage, we'll * get this code to indicate successful stage completion */ if (upekdev->enroll_passed) { From df4a6f53d2b74f43d453940cebd43d0cd802584d Mon Sep 17 00:00:00 2001 From: Bastien Nocera Date: Tue, 17 Aug 2010 23:14:18 +0100 Subject: [PATCH 159/184] Rework "discover" code for drivers Check all the drivers for one that'll drive our device in question, and prefer ones that have a discover() method that runs successfully to a driver without such a method. This allow drivers to both reject devices (if 2 drivers handle the same USB IDs), or a single driver to handle variants of the same device (through the devtype out value of the discover method). --- libfprint/core.c | 63 ++++++++++++++++++++++++++++---------- libfprint/drivers/upeke2.c | 10 ++++-- libfprint/fp_internal.h | 2 +- 3 files changed, 55 insertions(+), 20 deletions(-) diff --git a/libfprint/core.c b/libfprint/core.c index af97bdf5..1ce3d0ba 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -364,7 +364,7 @@ static struct fp_img_driver * const img_drivers[] = { #ifdef ENABLE_UPEKSONLY &upeksonly_driver, #endif - + #ifdef ENABLE_AES1610 &aes1610_driver, #endif @@ -410,51 +410,80 @@ API_EXPORTED struct fp_driver **fprint_get_drivers (void) } static struct fp_driver *find_supporting_driver(libusb_device *udev, - const struct usb_id **usb_id) + const struct usb_id **usb_id, uint32_t *devtype) { int ret; GSList *elem = registered_drivers; struct libusb_device_descriptor dsc; + const struct usb_id *best_usb_id; + struct fp_driver *best_drv; + uint32_t best_devtype; + int drv_score = 0; + ret = libusb_get_device_descriptor(udev, &dsc); if (ret < 0) { fp_err("Failed to get device descriptor"); return NULL; } - + + best_drv = NULL; + best_devtype = 0; + do { struct fp_driver *drv = elem->data; + uint32_t type = 0; const struct usb_id *id; - for (id = drv->id_table; id->vendor; id++) + for (id = drv->id_table; id->vendor; id++) { if (dsc.idVendor == id->vendor && dsc.idProduct == id->product) { + if (drv->discover) { + int r = drv->discover(&dsc, &type); + if (r < 0) + fp_err("%s discover failed, code %d", drv->name, r); + if (r <= 0) + continue; + /* Has a discover function, and matched our device */ + drv_score = 100; + } else { + /* Already got a driver as good */ + if (drv_score >= 50) + continue; + drv_score = 50; + } fp_dbg("driver %s supports USB device %04x:%04x", drv->name, id->vendor, id->product); - *usb_id = id; - return drv; + best_usb_id = id; + best_drv = drv; + best_devtype = type; + + /* We found the best possible driver */ + if (drv_score == 100) + break; } + } } while ((elem = g_slist_next(elem))); - return NULL; + + fp_dbg("selected driver %s supports USB device %04x:%04x", + best_drv->name, dsc.idVendor, dsc.idProduct); + *devtype = best_devtype; + *usb_id = best_usb_id; + + return best_drv; } static struct fp_dscv_dev *discover_dev(libusb_device *udev) { const struct usb_id *usb_id; - struct fp_driver *drv = find_supporting_driver(udev, &usb_id); + struct fp_driver *drv; struct fp_dscv_dev *ddev; - uint32_t devtype = 0; + uint32_t devtype; + + drv = find_supporting_driver(udev, &usb_id, &devtype); if (!drv) return NULL; - if (drv->discover) { - int r = drv->discover(usb_id, &devtype); - if (r < 0) - fp_err("%s discover failed, code %d", drv->name, r); - if (r <= 0) - return NULL; - } - ddev = g_malloc0(sizeof(*ddev)); ddev->drv = drv; ddev->udev = udev; diff --git a/libfprint/drivers/upeke2.c b/libfprint/drivers/upeke2.c index f4a812d7..5c7129ae 100644 --- a/libfprint/drivers/upeke2.c +++ b/libfprint/drivers/upeke2.c @@ -844,6 +844,12 @@ static struct fpi_ssm *deinitsm_new(struct fp_dev *dev) return fpi_ssm_new(dev, deinitsm_state_handler, DEINITSM_NUM_STATES); } +static int discover(struct libusb_device_descriptor *dsc, uint32_t *devtype) +{ + /* FIXME: Detect whether dsc represents a device that we can handle */ + return 0; +} + static int dev_init(struct fp_dev *dev, unsigned long driver_data) { struct upeke2_dev *upekdev = NULL; @@ -1442,8 +1448,7 @@ static int verify_stop(struct fp_dev *dev, gboolean iterating) } static const struct usb_id id_table[] = { -/* FIXME: Disabled for now, as this clashes with the upeksonly driver */ -/* { .vendor = 0x147e, .product = 0x2016 }, */ + { .vendor = 0x147e, .product = 0x2016 }, { 0, 0, 0, }, /* terminating entry */ }; @@ -1453,6 +1458,7 @@ struct fp_driver upeke2_driver = { .full_name = "UPEK Eikon 2", .id_table = id_table, .scan_type = FP_SCAN_TYPE_SWIPE, + .discover = discover, .open = dev_init, .close = dev_exit, .enroll_start = enroll_start, diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 5196ca20..4a0441de 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -204,7 +204,7 @@ struct fp_driver { void *priv; /* Device operations */ - int (*discover)(const struct usb_id *usb_id, uint32_t *devtype); + int (*discover)(struct libusb_device_descriptor *dsc, uint32_t *devtype); int (*open)(struct fp_dev *dev, unsigned long driver_data); void (*close)(struct fp_dev *dev); int (*enroll_start)(struct fp_dev *dev); From 73561989dd485560e4c62b46a9af31f9fce1bc4e Mon Sep 17 00:00:00 2001 From: Bastien Nocera Date: Tue, 17 Aug 2010 23:41:23 +0100 Subject: [PATCH 160/184] Implement discover() methods for upeke2 and upeksonly upeksonly handles revision 1 devices, upeke2 revision 2 devices. https://bugzilla.redhat.com/show_bug.cgi?id=504399 --- libfprint/drivers/upeke2.c | 5 ++++- libfprint/drivers/upeksonly.c | 10 ++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/libfprint/drivers/upeke2.c b/libfprint/drivers/upeke2.c index 5c7129ae..3a7c2d89 100644 --- a/libfprint/drivers/upeke2.c +++ b/libfprint/drivers/upeke2.c @@ -846,7 +846,10 @@ static struct fpi_ssm *deinitsm_new(struct fp_dev *dev) static int discover(struct libusb_device_descriptor *dsc, uint32_t *devtype) { - /* FIXME: Detect whether dsc represents a device that we can handle */ + /* Revision 2 is what we're interested in */ + if (dsc->bcdDevice == 2) + return 1; + return 0; } diff --git a/libfprint/drivers/upeksonly.c b/libfprint/drivers/upeksonly.c index f41a6be8..08c2ba41 100644 --- a/libfprint/drivers/upeksonly.c +++ b/libfprint/drivers/upeksonly.c @@ -1011,6 +1011,15 @@ static void dev_deinit(struct fp_img_dev *dev) fpi_imgdev_close_complete(dev); } +static int dev_discover(struct libusb_device_descriptor *dsc, uint32_t *devtype) +{ + /* Revision 1 is what we're interested in */ + if (dsc->bcdDevice == 1) + return 1; + + return 0; +} + static const struct usb_id id_table[] = { { .vendor = 0x147e, .product = 0x2016 }, { 0, 0, 0, }, @@ -1023,6 +1032,7 @@ struct fp_img_driver upeksonly_driver = { .full_name = "UPEK TouchStrip Sensor-Only", .id_table = id_table, .scan_type = FP_SCAN_TYPE_SWIPE, + .discover = dev_discover, }, .flags = 0, .img_width = IMG_WIDTH, From 9608ab370763b54c778b27c5b2015d1dda2ecec0 Mon Sep 17 00:00:00 2001 From: Bastien Nocera Date: Wed, 18 Aug 2010 11:17:20 +0100 Subject: [PATCH 161/184] Don't crash when no devices are present --- libfprint/core.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/libfprint/core.c b/libfprint/core.c index 1ce3d0ba..d65a95d1 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -464,10 +464,12 @@ static struct fp_driver *find_supporting_driver(libusb_device *udev, } } while ((elem = g_slist_next(elem))); - fp_dbg("selected driver %s supports USB device %04x:%04x", - best_drv->name, dsc.idVendor, dsc.idProduct); - *devtype = best_devtype; - *usb_id = best_usb_id; + if (best_drv != NULL) { + fp_dbg("selected driver %s supports USB device %04x:%04x", + best_drv->name, dsc.idVendor, dsc.idProduct); + *devtype = best_devtype; + *usb_id = best_usb_id; + } return best_drv; } From daee067c4ffabff9836617b90c547873130087f1 Mon Sep 17 00:00:00 2001 From: Bastien Nocera Date: Thu, 19 Aug 2010 14:43:30 +0100 Subject: [PATCH 162/184] Release 0.2.0 --- NEWS | 6 ++++++ configure.ac | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/NEWS b/NEWS index c0947c37..291d6258 100644 --- a/NEWS +++ b/NEWS @@ -1,6 +1,12 @@ This file lists notable changes in each release. For the full history of all changes, see ChangeLog. +2010-08-19: v0.2.0 release (since 0.1.0-pre2) + * Add gdk-pixbuf support for image manipulation + * Add udev rules to allow devices to autosuspend + * Finish port of AES1610 driver + * Add UPEK EikonII (TCRD4C) driver + 2007-12-07: v0.0.5 release * AES1610 imaging improvements * Internal cleanups for Authentec drivers diff --git a/configure.ac b/configure.ac index d48e95d6..345e961d 100644 --- a/configure.ac +++ b/configure.ac @@ -1,5 +1,5 @@ -AC_INIT([libfprint], [0.1.0-pre2]) -AM_INIT_AUTOMAKE +AC_INIT([libfprint], [0.2.0]) +AM_INIT_AUTOMAKE([1.11 dist-bzip2 no-dist-gzip check-news]) AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_SRCDIR([libfprint/core.c]) AM_CONFIG_HEADER([config.h]) From 4b518bd230ef0f3a26c8eb89736815ed9334b6bb Mon Sep 17 00:00:00 2001 From: Alexia Death Date: Sat, 26 Dec 2009 01:00:59 +0200 Subject: [PATCH 163/184] Fix a segfault if a scan was shorter than 8 lines. This segfault was caused by proceeding to free the conversion result without checking for an error condition in image to print data conversion. http://lists.reactivated.net/pipermail/fprint/2009-December/001405.html --- libfprint/imgdev.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index 4b49c73e..b365d74a 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -228,8 +228,12 @@ void fpi_imgdev_image_captured(struct fp_img_dev *imgdev, struct fp_img *img) fp_img_standardize(img); imgdev->acquire_img = img; - fpi_img_to_print_data(imgdev, img, &print); - if (img->minutiae->num < MIN_ACCEPTABLE_MINUTIAE) { + r = fpi_img_to_print_data(imgdev, img, &print); + if (r < 0) { + fp_dbg("image to print data conversion error: %d", r); + imgdev->action_result = FP_ENROLL_RETRY; + goto next_state; + } else if (img->minutiae->num < MIN_ACCEPTABLE_MINUTIAE) { fp_dbg("not enough minutiae, %d/%d", img->minutiae->num, MIN_ACCEPTABLE_MINUTIAE); fp_print_data_free(print); From 8cd31f6ad81bc2d8e8d3ffdea7cb4f13a6914684 Mon Sep 17 00:00:00 2001 From: Alexia Death Date: Thu, 24 Dec 2009 21:42:01 +0200 Subject: [PATCH 164/184] Try to correct missing packets in image stream If a packet goes missing, use the data from previous row to minimize distortion, or use some neutral dummy data. http://lists.reactivated.net/pipermail/fprint/2009-December/001404.html --- libfprint/drivers/upeksonly.c | 55 +++++++++++++++++++++++++++++++++-- 1 file changed, 52 insertions(+), 3 deletions(-) diff --git a/libfprint/drivers/upeksonly.c b/libfprint/drivers/upeksonly.c index 08c2ba41..f4bc1224 100644 --- a/libfprint/drivers/upeksonly.c +++ b/libfprint/drivers/upeksonly.c @@ -248,6 +248,7 @@ static void add_to_rowbuf(struct fp_img_dev *dev, unsigned char *data, int size) sdev->rowbuf_offset += size; if (sdev->rowbuf_offset >= IMG_WIDTH) row_complete(dev); + } static void start_new_row(struct sonly_dev *sdev, unsigned char *data, int size) @@ -282,11 +283,56 @@ static void handle_packet(struct fp_img_dev *dev, unsigned char *data) int for_rowbuf; int next_row_addr; int diff; + unsigned char dummy_data[62]; + + /* Init dummy data to something neutral */ + memset (dummy_data, 204, 62); data += 2; /* skip sequence number */ if (seqnum != sdev->last_seqnum + 1) { - if (seqnum != 0 && sdev->last_seqnum != 16383) - fp_warn("lost some data"); + if (seqnum != 0 && sdev->last_seqnum != 16383) { + int missing_data = seqnum - sdev->last_seqnum; + int i; + fp_warn("lost %d packets of data between %d and %d", missing_data, sdev->last_seqnum, seqnum ); + + /* Minimize distortions for readers that lose a lot of packets */ + for (i =1; i < missing_data; i++) { + abs_base_addr = (sdev->last_seqnum + 1) * 62; + + /* If possible take the replacement data from last row */ + if (sdev->num_rows > 1) { + int row_left = IMG_WIDTH - sdev->rowbuf_offset; + unsigned char *last_row = g_slist_nth_data (sdev->rows, 0); + + if (row_left >= 62) { + memcpy(dummy_data, last_row + sdev->rowbuf_offset, 62); + } else { + memcpy(dummy_data, last_row + sdev->rowbuf_offset, row_left); + memcpy(dummy_data + row_left, last_row , 62 - row_left); + } + } + + fp_warn("adding dummy input for %d, i=%d", sdev->last_seqnum + i, i); + for_rowbuf = rowbuf_remaining(sdev); + if (for_rowbuf != -1) { + add_to_rowbuf(dev, dummy_data, for_rowbuf); + /* row boundary */ + if (for_rowbuf < 62) { + start_new_row(sdev, dummy_data + for_rowbuf, 62 - for_rowbuf); + } + } else if (abs_base_addr % IMG_WIDTH == 0) { + start_new_row(sdev, dummy_data, 62); + } else { + /* does the data in the packet reside on a row boundary? + * if so capture it */ + next_row_addr = ((abs_base_addr / IMG_WIDTH) + 1) * IMG_WIDTH; + diff = next_row_addr - abs_base_addr; + if (diff < 62) + start_new_row(sdev, dummy_data + diff, 62 - diff); + } + sdev->last_seqnum = sdev->last_seqnum + 1; + } + } } if (seqnum <= sdev->last_seqnum) { fp_dbg("detected wraparound"); @@ -302,7 +348,10 @@ static void handle_packet(struct fp_img_dev *dev, unsigned char *data) for_rowbuf = rowbuf_remaining(sdev); if (for_rowbuf != -1) { add_to_rowbuf(dev, data, for_rowbuf); - /* FIXME: we drop a row here */ + /*row boundary*/ + if (for_rowbuf < 62) { + start_new_row(sdev, data + for_rowbuf, 62 - for_rowbuf); + } return; } From c575afba9ae9c518f208d5834e2ee72f8aede72c Mon Sep 17 00:00:00 2001 From: Alexia Death Date: Fri, 25 Dec 2009 00:04:55 +0200 Subject: [PATCH 165/184] Make the +2 right shift happen on image handoff. Rather than when reading the rows. Doing it there seems a lot more sensible and does not get in the way of minimizing the impact of lost USB packets. http://lists.reactivated.net/pipermail/fprint/2009-December/001404.html --- libfprint/drivers/upeksonly.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/libfprint/drivers/upeksonly.c b/libfprint/drivers/upeksonly.c index f4bc1224..84883f4c 100644 --- a/libfprint/drivers/upeksonly.c +++ b/libfprint/drivers/upeksonly.c @@ -168,8 +168,12 @@ static void handoff_img(struct fp_img_dev *dev) fp_dbg("%d rows", sdev->num_rows); img->height = sdev->num_rows; + /* The scans from this device are rolled right by two colums + * It feels a lot smarter to correct here than mess with it at + * read time*/ do { - memcpy(img->data + offset, elem->data, IMG_WIDTH); + memcpy(img->data + offset, elem->data + 2, IMG_WIDTH - 2); + memcpy(img->data + offset + IMG_WIDTH - 2, elem->data, 2); g_free(elem->data); offset += IMG_WIDTH; } while ((elem = g_slist_next(elem)) != NULL); @@ -255,8 +259,7 @@ static void start_new_row(struct sonly_dev *sdev, unsigned char *data, int size) { if (!sdev->rowbuf) sdev->rowbuf = g_malloc(IMG_WIDTH); - memcpy(sdev->rowbuf + IMG_WIDTH - 2, data, 2); - memcpy(sdev->rowbuf, data + 2, size - 2); + memcpy(sdev->rowbuf, data, size); sdev->rowbuf_offset = size; } From 25161286f5c9bde3a03eb181e8c4db8029f94001 Mon Sep 17 00:00:00 2001 From: Alexia Death Date: Sat, 26 Dec 2009 17:02:03 +0200 Subject: [PATCH 166/184] Only complete scan with MIN_ROWS in print Don't consider the scan complete unless theres at least MIN_ROWS recorded or very long blank read occurred. Typical problem spot: one brief touch before starting the actual scan. Happens most commonly if scan is started from before the first joint resulting in a gap after the inital touch. http://lists.reactivated.net/pipermail/fprint/2009-December/001406.html --- libfprint/drivers/upeksonly.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/libfprint/drivers/upeksonly.c b/libfprint/drivers/upeksonly.c index 84883f4c..9b9adbb8 100644 --- a/libfprint/drivers/upeksonly.c +++ b/libfprint/drivers/upeksonly.c @@ -31,6 +31,7 @@ #define IMG_WIDTH 288 #define NUM_BULK_TRANSFERS 24 #define MAX_ROWS 700 +#define MIN_ROWS 64 struct img_transfer_data { int idx; @@ -218,13 +219,22 @@ static void row_complete(struct fp_img_dev *dev) int total; compute_rows(lastrow, sdev->rowbuf, &diff, &total); + if (total < 52000) { sdev->num_blank = 0; } else { sdev->num_blank++; - if (sdev->num_blank > 500) { + /* Don't consider the scan complete unless theres at least + * MIN_ROWS recorded or very long blank read occurred. + * + * Typical problem spot: one brief touch before starting the + * actual scan. Happens most commonly if scan is started + * from before the first joint resulting in a gap after the inital touch. + */ + if ((sdev->num_blank > 500) + && ((sdev->num_rows > MIN_ROWS) || (sdev->num_blank > 5000))) { sdev->finger_removed = 1; - fp_dbg("detected finger removal"); + fp_dbg("detected finger removal. Blank rows: %d, Full rows: %d", sdev->num_blank, sdev->num_rows); handoff_img(dev); return; } From 375575b701fd1a1187b75c472ea77fb1e89ee7a2 Mon Sep 17 00:00:00 2001 From: Bastien Nocera Date: Wed, 25 Aug 2010 00:42:01 +0100 Subject: [PATCH 167/184] Port OpenSSL using code to NSS As OpenSSL cannot really be used in an LGPLv2+ piece of software without an exception. Adapted from the example code at: http://www.mozilla.org/projects/security/pki/nss/sample-code/sample2.html and: http://github.com/bagder/curl/commit/f3b77e5 --- configure.ac | 2 +- libfprint/drivers/uru4000.c | 73 ++++++++++++++++++++++++++++++++----- 2 files changed, 64 insertions(+), 11 deletions(-) diff --git a/configure.ac b/configure.ac index 345e961d..4147cb57 100644 --- a/configure.ac +++ b/configure.ac @@ -106,7 +106,7 @@ AC_SUBST(LIBUSB_CFLAGS) AC_SUBST(LIBUSB_LIBS) # check for OpenSSL's libcrypto -PKG_CHECK_MODULES(CRYPTO, "libcrypto") +PKG_CHECK_MODULES(CRYPTO, nss) AC_SUBST(CRYPTO_CFLAGS) AC_SUBST(CRYPTO_LIBS) diff --git a/libfprint/drivers/uru4000.c b/libfprint/drivers/uru4000.c index b230c03c..0dbea965 100644 --- a/libfprint/drivers/uru4000.c +++ b/libfprint/drivers/uru4000.c @@ -23,7 +23,8 @@ #include #include -#include +#include +#include #include #include @@ -92,7 +93,7 @@ static const struct uru4k_dev_profile { }, [MS_STANDALONE_V2] = { .name = "Microsoft Fingerprint Reader v2", - .auth_cr = TRUE, + .auth_cr = TRUE, }, [DP_URU4000] = { .name = "Digital Persona U.are.U 4000", @@ -144,7 +145,10 @@ struct uru4k_dev { int fwfixer_offset; unsigned char fwfixer_value; - AES_KEY aeskey; + CK_MECHANISM_TYPE cipher; + PK11SlotInfo *slot; + PK11SymKey *symkey; + SECItem *param; }; /* For 2nd generation MS devices */ @@ -326,8 +330,10 @@ static void challenge_cb(struct fp_img_dev *dev, int status, struct fpi_ssm *ssm = user_data; struct uru4k_dev *urudev = dev->priv; unsigned char *respdata; - int r; + PK11Context *ctx; + int r, outlen; + r = status; if (status != 0) { fpi_ssm_mark_aborted(ssm, status); return; @@ -335,12 +341,21 @@ static void challenge_cb(struct fp_img_dev *dev, int status, /* submit response */ /* produce response from challenge */ - /* FIXME would this work in-place? */ respdata = g_malloc(CR_LENGTH); - AES_encrypt(data, respdata, &urudev->aeskey); - - r = write_regs(dev, REG_RESPONSE, CR_LENGTH, respdata, response_cb, ssm); - g_free(respdata); + ctx = PK11_CreateContextBySymKey(urudev->cipher, CKA_ENCRYPT, + urudev->symkey, urudev->param); + if (PK11_CipherOp(ctx, respdata, &outlen, CR_LENGTH, data, CR_LENGTH) != SECSuccess + || PK11_Finalize(ctx) != SECSuccess) { + fp_err("Failed to encrypt challenge data"); + r = -ECONNABORTED; + g_free(respdata); + } + PK11_DestroyContext(ctx, PR_TRUE); + + if (r >= 0) { + r = write_regs(dev, REG_RESPONSE, CR_LENGTH, respdata, response_cb, ssm); + g_free(respdata); + } if (r < 0) fpi_ssm_mark_aborted(ssm, r); } @@ -1111,6 +1126,8 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) const struct libusb_interface_descriptor *iface_desc; const struct libusb_endpoint_descriptor *ep; struct uru4k_dev *urudev; + SECStatus rv; + SECItem item; int i; int r; @@ -1175,10 +1192,40 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) goto out; } + /* Initialise NSS early */ + rv = NSS_NoDB_Init("."); + if (rv != SECSuccess) { + fp_err("could not initialise NSS"); + goto out; + } + urudev = g_malloc0(sizeof(*urudev)); urudev->profile = &uru4k_dev_info[driver_data]; urudev->interface = iface_desc->bInterfaceNumber; - AES_set_encrypt_key(crkey, 128, &urudev->aeskey); + + /* Set up encryption */ + urudev->cipher = CKM_AES_ECB; + urudev->slot = PK11_GetBestSlot(urudev->cipher, NULL); + if (urudev->slot == NULL) { + fp_err("could not get encryption slot"); + goto out; + } + item.type = siBuffer; + item.data = (unsigned char*) crkey; + item.len = sizeof(crkey); + urudev->symkey = PK11_ImportSymKey(urudev->slot, + urudev->cipher, + PK11_OriginUnwrap, + CKA_ENCRYPT, + &item, NULL); + if (urudev->symkey == NULL) { + fp_err("failed to import key into NSS"); + PK11_FreeSlot(urudev->slot); + urudev->slot = NULL; + goto out; + } + urudev->param = PK11_ParamFromIV(urudev->cipher, NULL); + dev->priv = urudev; fpi_imgdev_open_complete(dev, 0); @@ -1190,6 +1237,12 @@ out: static void dev_deinit(struct fp_img_dev *dev) { struct uru4k_dev *urudev = dev->priv; + if (urudev->symkey) + PK11_FreeSymKey (urudev->symkey); + if (urudev->param) + SECITEM_FreeItem(urudev->param, PR_TRUE); + if (urudev->slot) + PK11_FreeSlot(urudev->slot); libusb_release_interface(dev->udev, urudev->interface); g_free(urudev); fpi_imgdev_close_complete(dev); From f28c5797791edd8b17f05ed3671b45223326dd21 Mon Sep 17 00:00:00 2001 From: Bastien Nocera Date: Wed, 25 Aug 2010 11:17:19 +0100 Subject: [PATCH 168/184] Print out summary of build options At the end of the configure run. --- configure.ac | 102 ++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 85 insertions(+), 17 deletions(-) diff --git a/configure.ac b/configure.ac index 4147cb57..c627241f 100644 --- a/configure.ac +++ b/configure.ac @@ -51,7 +51,8 @@ for driver in `echo ${drivers} | sed -e 's/,/ /g' -e 's/,$//g'`; do ;; upektc) AC_DEFINE([ENABLE_UPEKTC], [], [Build UPEK TouchChip driver]) - enable_upektc="yes" + enable_upektc="no" + # Driver not ported ;; upeksonly) AC_DEFINE([ENABLE_UPEKSONLY], [], [Build UPEK TouchStrip sensor-only driver]) @@ -63,7 +64,8 @@ for driver in `echo ${drivers} | sed -e 's/,/ /g' -e 's/,$//g'`; do ;; fdu2000) AC_DEFINE([ENABLE_FDU2000], [], [Build Secugen FDU 2000 driver]) - enable_fdu2000="yes" + enable_fdu2000="no" + # Driver not ported ;; vcom5s) AC_DEFINE([ENABLE_VCOM5S], [], [Build Veridicom 5thSense driver]) @@ -88,17 +90,17 @@ for driver in `echo ${drivers} | sed -e 's/,/ /g' -e 's/,$//g'`; do esac done -AM_CONDITIONAL([ENABLE_UPEKTS], [test "$enable_upekts" != "no"]) -AM_CONDITIONAL([ENABLE_UPEKE2], [test "$enable_upeke2" != "no"]) -#AM_CONDITIONAL([ENABLE_UPEKTC], [test "$enable_upektc" != "no"]) -AM_CONDITIONAL([ENABLE_UPEKSONLY], [test "$enable_upeksonly" != "no"]) -AM_CONDITIONAL([ENABLE_VCOM5S], [test "$enable_vcom5s" != "no"]) -AM_CONDITIONAL([ENABLE_URU4000], [test "$enable_uru4000" != "no"]) -#AM_CONDITIONAL([ENABLE_FDU2000], [test "$enable_fdu2000" != "no"]) -AM_CONDITIONAL([ENABLE_AES1610], [test "$enable_aes1610" != "no"]) -AM_CONDITIONAL([ENABLE_AES2501], [test "$enable_aes2501" != "no"]) -AM_CONDITIONAL([ENABLE_AES4000], [test "$enable_aes4000" != "no"]) -AM_CONDITIONAL([REQUIRE_AESLIB], [test "$require_aeslib" != "no"]) +AM_CONDITIONAL([ENABLE_UPEKTS], [test "$enable_upekts" = "yes"]) +AM_CONDITIONAL([ENABLE_UPEKE2], [test "$enable_upeke2" = "yes"]) +#AM_CONDITIONAL([ENABLE_UPEKTC], [test "$enable_upektc" = "yes"]) +AM_CONDITIONAL([ENABLE_UPEKSONLY], [test "$enable_upeksonly" = "yes"]) +AM_CONDITIONAL([ENABLE_VCOM5S], [test "$enable_vcom5s" = "yes"]) +AM_CONDITIONAL([ENABLE_URU4000], [test "$enable_uru4000" = "yes"]) +AM_CONDITIONAL([ENABLE_FDU2000], [test "$enable_fdu2000" = "yes"]) +AM_CONDITIONAL([ENABLE_AES1610], [test "$enable_aes1610" = "yes"]) +AM_CONDITIONAL([ENABLE_AES2501], [test "$enable_aes2501" = "yes"]) +AM_CONDITIONAL([ENABLE_AES4000], [test "$enable_aes4000" = "yes"]) +AM_CONDITIONAL([REQUIRE_AESLIB], [test "$require_aeslib" = "yes"]) PKG_CHECK_MODULES(LIBUSB, [libusb-1.0 >= 0.9.1]) @@ -117,21 +119,21 @@ AC_SUBST(GLIB_LIBS) imagemagick_found=no gdkpixbuf_found=no -if test "$require_imaging" != "no"; then +if test "$require_imaging" = "yes"; then PKG_CHECK_MODULES(IMAGING, gthread-2.0 gdk-pixbuf-2.0, [gdkpixbuf_found=yes], [gdkpixbuf_found=no]) if test "$gdkpixbuf_found" != "yes"; then PKG_CHECK_MODULES(IMAGING, ImageMagick, [imagemagick_found=yes], [imagemagick_found=no]) fi fi -if test "$require_imaging" != "no"; then +if test "$require_imaging" = "yes"; then if test "$gdkpixbuf_found" != "yes" && test "$imagemagick_found" != "yes"; then AC_MSG_ERROR([gdk-pixbuf or ImageMagick is required for imaging support]) fi fi -AM_CONDITIONAL([REQUIRE_GDKPIXBUF], [test "$gdkpixbuf_found" != "no"]) -AM_CONDITIONAL([REQUIRE_IMAGEMAGICK], [test "$imagemagick_found" != "no"]) +AM_CONDITIONAL([REQUIRE_GDKPIXBUF], [test "$gdkpixbuf_found" = "yes"]) +AM_CONDITIONAL([REQUIRE_IMAGEMAGICK], [test "$imagemagick_found" = "yes"]) AC_SUBST(IMAGING_CFLAGS) AC_SUBST(IMAGING_LIBS) @@ -200,6 +202,72 @@ AC_DEFINE([API_EXPORTED], [__attribute__((visibility("default")))], [Default vis AM_CFLAGS="-std=gnu99 $inline_cflags -Wall -Wundef -Wunused -Wstrict-prototypes -Werror-implicit-function-declaration -Wno-pointer-sign -Wshadow" AC_SUBST(AM_CFLAGS) +if test "$require_imaging" = "yes"; then + if test x$gdkpixbuf_found != no; then + AC_MSG_NOTICE([** Using gdk-pixbuf for imaging]) + else + AC_MSG_NOTICE([** Using ImageMagick for imaging]) + fi +else + AC_MSG_NOTICE([ Imaging support disabled]) +fi + +if test x$enable_upekts != xno ; then + AC_MSG_NOTICE([** upekts driver enabled]) +else + AC_MSG_NOTICE([ upekts driver disabled]) +fi +if test x$enable_upeke2 != xno ; then + AC_MSG_NOTICE([** upeke2 driver enabled]) +else + AC_MSG_NOTICE([ upeke2 driver disabled]) +fi +if test x$enable_upektc != xno ; then + AC_MSG_NOTICE([** upektc driver enabled]) +else + AC_MSG_NOTICE([ upektc driver disabled]) +fi +if test x$enable_upeksonly != xno ; then + AC_MSG_NOTICE([** upeksonly driver enabled]) +else + AC_MSG_NOTICE([ upeksonly driver disabled]) +fi +if test x$enable_vcom5s != xno ; then + AC_MSG_NOTICE([** vcom5s driver enabled]) +else + AC_MSG_NOTICE([ vcom5s driver disabled]) +fi +if test x$enable_uru4000 != xno ; then + AC_MSG_NOTICE([** uru4000 driver enabled]) +else + AC_MSG_NOTICE([ uru4000 driver disabled]) +fi +if test x$enable_fdu2000 != xno ; then + AC_MSG_NOTICE([** fdu2000 driver enabled]) +else + AC_MSG_NOTICE([ fdu2000 driver disabled]) +fi +if test x$enable_aes1610 != xno ; then + AC_MSG_NOTICE([** aes1610 driver enabled]) +else + AC_MSG_NOTICE([ aes1610 driver disabled]) +fi +if test x$enable_aes2501 != xno ; then + AC_MSG_NOTICE([** aes2501 driver enabled]) +else + AC_MSG_NOTICE([ aes2501 driver disabled]) +fi +if test x$enable_aes4000 != xno ; then + AC_MSG_NOTICE([** aes4000 driver enabled]) +else + AC_MSG_NOTICE([ aes4000 driver disabled]) +fi +if test x$require_aeslib != xno ; then + AC_MSG_NOTICE([** aeslib helper functions enabled]) +else + AC_MSG_NOTICE([ aeslib helper functions disabled]) +fi + AC_CONFIG_FILES([libfprint.pc] [Makefile] [libfprint/Makefile] [examples/Makefile] [doc/Makefile]) AC_OUTPUT From 9f8dd29a553ce61999cd0cee8c81013cbeb07926 Mon Sep 17 00:00:00 2001 From: Bastien Nocera Date: Wed, 25 Aug 2010 11:17:42 +0100 Subject: [PATCH 169/184] Make sure all sources are dist'ed So that you can compile against ImageMagick even if the distter doesn't. --- libfprint/Makefile.am | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 431f66cb..c2c1df11 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -13,6 +13,21 @@ AES4000_SRC = drivers/aes4000.c FDU2000_SRC = drivers/fdu2000.c VCOM5S_SRC = drivers/vcom5s.c +EXTRA_DIST = \ + $(UPEKE2_SRC) \ + $(UPEKTS_SRC) \ + $(UPEKTC_SRC) \ + $(UPEKSONLY_SRC) \ + $(URU4000_SRC) \ + $(AES1610_SRC) \ + $(AES2501_SRC) \ + $(AES4000_SRC) \ + $(FDU2000_SRC) \ + $(VCOM5S_SRC) \ + aeslib.c aeslib.h \ + imagemagick.c \ + gdkpixbuf.c + DRIVER_SRC = OTHER_SRC = From 15b8e8f37617306cbfb03679475bb714a4f28a73 Mon Sep 17 00:00:00 2001 From: Bastien Nocera Date: Wed, 25 Aug 2010 11:20:55 +0100 Subject: [PATCH 170/184] Remove HAL fdi generation HAL is deprecated, and the rules are broken when multiple drivers use the same USB IDs. --- libfprint/Makefile.am | 14 +----- libfprint/fprint-list-hal-info.c | 81 -------------------------------- 2 files changed, 2 insertions(+), 93 deletions(-) delete mode 100644 libfprint/fprint-list-hal-info.c diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index c2c1df11..84cb7b9b 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -1,6 +1,6 @@ lib_LTLIBRARIES = libfprint.la -noinst_PROGRAMS = fprint-list-hal-info fprint-list-udev-rules -MOSTLYCLEANFILES = $(hal_fdi_DATA) $(udev_rules_DATA) +noinst_PROGRAMS = fprint-list-udev-rules +MOSTLYCLEANFILES = $(udev_rules_DATA) UPEKE2_SRC = drivers/upeke2.c UPEKTS_SRC = drivers/upekts.c @@ -72,16 +72,6 @@ libfprint_la_CFLAGS = -fvisibility=hidden -I$(srcdir)/nbis/include $(LIBUSB_CFLA libfprint_la_LDFLAGS = -version-info @lt_major@:@lt_revision@:@lt_age@ libfprint_la_LIBADD = -lm $(LIBUSB_LIBS) $(GLIB_LIBS) $(CRYPTO_LIBS) -fprint_list_hal_info_SOURCES = fprint-list-hal-info.c -fprint_list_hal_info_CFLAGS = -fvisibility=hidden -I$(srcdir)/nbis/include $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) $(IMAGEMAGICK_CFLAGS) $(CRYPTO_CFLAGS) $(AM_CFLAGS) -fprint_list_hal_info_LDADD = $(builddir)/libfprint.la - -hal_fdi_DATA = 10-fingerprint-reader-fprint.fdi -hal_fdidir = $(datadir)/hal/fdi/information/20thirdparty/ - -$(hal_fdi_DATA): fprint-list-hal-info - $(builddir)/fprint-list-hal-info > $@ - fprint_list_udev_rules_SOURCES = fprint-list-udev-rules.c fprint_list_udev_rules_CFLAGS = -fvisibility=hidden -I$(srcdir)/nbis/include $(LIBUSB_CFLAGS) $(GLIB_CFLAGS) $(IMAGEMAGICK_CFLAGS) $(CRYPTO_CFLAGS) $(AM_CFLAGS) fprint_list_udev_rules_LDADD = $(builddir)/libfprint.la diff --git a/libfprint/fprint-list-hal-info.c b/libfprint/fprint-list-hal-info.c deleted file mode 100644 index 13d24d60..00000000 --- a/libfprint/fprint-list-hal-info.c +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Helper binary for creating a HAL FDI file for supported devices - * Copyright (C) 2008 Bastien Nocera - * Copyright (C) 2008 Timo Hoenig , - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include -#include - -#include "fp_internal.h" - -/* FDI entry example: - * - * - * - * - * biometric.fingerprint_reader - * libfprint - * biometric - * biometric.fingerprint_reader - * aes2501 - * true - * - * - * - */ - -static void print_driver (struct fp_driver *driver) -{ - int i; - - for (i = 0; driver->id_table[i].vendor != 0; i++) { - printf (" \n", fp_driver_get_full_name (driver)); - printf (" \n", driver->id_table[i].vendor); - printf (" \n", driver->id_table[i].product); - printf (" biometric.fingerprint_reader\n"); - printf (" libfprint\n"); - printf (" biometric\n"); - printf (" biometric.fingerprint_reader\n"); - printf (" %s\n", driver->name); - printf (" true\n"); - printf (" %s\n", - fp_driver_get_scan_type (driver) == FP_SCAN_TYPE_PRESS ? "press" : "swipe"); - printf (" \n"); - printf (" \n"); - } -} - -int main (int argc, char **argv) -{ - struct fp_driver **list; - guint i; - - list = fprint_get_drivers (); - - printf ("\n"); - printf ("\n", VERSION); - printf ("\n"); - - for (i = 0; list[i] != NULL; i++) { - print_driver (list[i]); - } - - printf ("\n"); - - return 0; -} From a18f318446df01d27f3a8dc677c2a644fb086a60 Mon Sep 17 00:00:00 2001 From: Hugo Grostabussiat Date: Tue, 31 Aug 2010 16:09:22 +0200 Subject: [PATCH 171/184] Added support for UPEK TCS4C (USB ID 147e:1000) https://bugs.freedesktop.org/show_bug.cgi?id=29719 --- AUTHORS | 1 + libfprint/drivers/upeksonly.c | 253 +++++++++++++++++++++++++++++----- 2 files changed, 219 insertions(+), 35 deletions(-) diff --git a/AUTHORS b/AUTHORS index cc829548..1cd2e51a 100644 --- a/AUTHORS +++ b/AUTHORS @@ -7,3 +7,4 @@ Copyright (C) 2007 Cyrille Bagard Copyright (C) 2007 Vasily Khoruzhick Copyright (C) 2007 Jan-Michael Brummer Copyright (C) 2007 Anthony Bretaudeau +Copyright (C) 2010 Hugo Grostabussiat diff --git a/libfprint/drivers/upeksonly.c b/libfprint/drivers/upeksonly.c index 9b9adbb8..e2f5a459 100644 --- a/libfprint/drivers/upeksonly.c +++ b/libfprint/drivers/upeksonly.c @@ -2,6 +2,9 @@ * UPEK TouchStrip Sensor-Only driver for libfprint * Copyright (C) 2008 Daniel Drake * + * TCS4C (USB ID 147e:1000) support: + * Copyright (C) 2010 Hugo Grostabussiat + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either @@ -33,6 +36,11 @@ #define MAX_ROWS 700 #define MIN_ROWS 64 +enum { + UPEKSONLY_2016, + UPEKSONLY_1000, +}; + struct img_transfer_data { int idx; struct fp_img_dev *dev; @@ -61,6 +69,8 @@ struct sonly_dev { gboolean deactivating; uint8_t read_reg_result; + int dev_model; + struct fpi_ssm *loopsm; struct libusb_transfer *img_transfer[NUM_BULK_TRANSFERS]; struct img_transfer_data *img_transfer_data; @@ -658,11 +668,31 @@ static const struct sonly_regwrite awfsm_writev_1[] = { { 0x00, 0x67 }, { 0x00, 0x67 }, }; +static const struct sonly_regwrite awfsm_1000_writev_1[] = { + /* Initialize sensor settings */ + { 0x0a, 0x00 }, { 0x09, 0x20 }, { 0x03, 0x37 }, { 0x00, 0x5f }, + { 0x01, 0x6e }, { 0x01, 0xee }, { 0x0c, 0x13 }, { 0x0d, 0x0d }, + { 0x0e, 0x0e }, { 0x0f, 0x0d }, + + { 0x13, 0x05 }, { 0x13, 0x45 }, + + /* Initialize finger detection registers (not enabling yet) */ + { 0x30, 0xe0 }, { 0x15, 0x26 }, + + { 0x12, 0x01 }, { 0x20, 0x01 }, { 0x07, 0x10 }, + { 0x10, 0x00 }, { 0x11, 0xbf }, +}; + static const struct sonly_regwrite awfsm_writev_2[] = { { 0x01, 0xc6 }, { 0x0c, 0x13 }, { 0x0d, 0x0d }, { 0x0e, 0x0e }, { 0x0f, 0x0d }, { 0x0b, 0x00 }, }; +static const struct sonly_regwrite awfsm_1000_writev_2[] = { + /* Enable finger detection */ + { 0x30, 0xe1 }, { 0x15, 0x06 }, { 0x15, 0x86 }, +}; + static const struct sonly_regwrite awfsm_writev_3[] = { { 0x13, 0x45 }, { 0x30, 0xe0 }, { 0x12, 0x01 }, { 0x20, 0x01 }, { 0x09, 0x20 }, { 0x0a, 0x00 }, { 0x30, 0xe0 }, { 0x20, 0x01 }, @@ -692,6 +722,12 @@ enum awfsm_states { AWFSM_NUM_STATES, }; +enum awfsm_1000_states { + AWFSM_1000_WRITEV_1, + AWFSM_1000_WRITEV_2, + AWFSM_1000_NUM_STATES, +}; + static void awfsm_run_state(struct fpi_ssm *ssm) { struct fp_img_dev *dev = ssm->priv; @@ -739,6 +775,18 @@ static void awfsm_run_state(struct fpi_ssm *ssm) } } +static void awfsm_1000_run_state(struct fpi_ssm *ssm) +{ + switch (ssm->cur_state) { + case AWFSM_1000_WRITEV_1: + sm_write_regs(ssm, awfsm_1000_writev_1, G_N_ELEMENTS(awfsm_1000_writev_1)); + break; + case AWFSM_1000_WRITEV_2: + sm_write_regs(ssm, awfsm_1000_writev_2, G_N_ELEMENTS(awfsm_1000_writev_2)); + break; + } +} + /***** CAPTURE MODE *****/ static const struct sonly_regwrite capsm_writev[] = { @@ -747,6 +795,10 @@ static const struct sonly_regwrite capsm_writev[] = { { 0x05, 0x00 }, }; +static const struct sonly_regwrite capsm_1000_writev[] = { + { 0x08, 0x80 }, { 0x13, 0x55 }, { 0x0b, 0x80 }, /* Enter capture mode */ +}; + enum capsm_states { CAPSM_INIT, CAPSM_WRITE_15, @@ -756,6 +808,43 @@ enum capsm_states { CAPSM_NUM_STATES, }; +enum capsm_1000_states { + CAPSM_1000_INIT, + CAPSM_1000_FIRE_BULK, + CAPSM_1000_WRITEV, + CAPSM_1000_NUM_STATES, +}; + +static void capsm_fire_bulk(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct sonly_dev *sdev = dev->priv; + int i; + for (i = 0; i < NUM_BULK_TRANSFERS; i++) { + int r = libusb_submit_transfer(sdev->img_transfer[i]); + if (r < 0) { + if (i == 0) { + /* first one failed: easy peasy */ + fpi_ssm_mark_aborted(ssm, r); + return; + } + + /* cancel all flying transfers, and request that the SSM + * gets aborted when the last transfer has dropped out of + * the sky */ + sdev->killing_transfers = ABORT_SSM; + sdev->kill_ssm = ssm; + sdev->kill_status_code = r; + cancel_img_transfers(dev); + return; + } + sdev->img_transfer_data[i].flying = TRUE; + sdev->num_flying++; + } + sdev->capturing = TRUE; + fpi_ssm_next_state(ssm); +} + static void capsm_run_state(struct fpi_ssm *ssm) { struct fp_img_dev *dev = ssm->priv; @@ -779,30 +868,7 @@ static void capsm_run_state(struct fpi_ssm *ssm) sm_write_reg(ssm, 0x30, 0xe0); break; case CAPSM_FIRE_BULK: ; - int i; - for (i = 0; i < NUM_BULK_TRANSFERS; i++) { - int r = libusb_submit_transfer(sdev->img_transfer[i]); - if (r < 0) { - if (i == 0) { - /* first one failed: easy peasy */ - fpi_ssm_mark_aborted(ssm, r); - return; - } - - /* cancel all flying transfers, and request that the SSM - * gets aborted when the last transfer has dropped out of - * the sky */ - sdev->killing_transfers = ABORT_SSM; - sdev->kill_ssm = ssm; - sdev->kill_status_code = r; - cancel_img_transfers(dev); - return; - } - sdev->img_transfer_data[i].flying = TRUE; - sdev->num_flying++; - } - sdev->capturing = TRUE; - fpi_ssm_next_state(ssm); + capsm_fire_bulk (ssm); break; case CAPSM_WRITEV: sm_write_regs(ssm, capsm_writev, G_N_ELEMENTS(capsm_writev)); @@ -810,6 +876,31 @@ static void capsm_run_state(struct fpi_ssm *ssm) } } +static void capsm_1000_run_state(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct sonly_dev *sdev = dev->priv; + + switch (ssm->cur_state) { + case CAPSM_1000_INIT: + sdev->rowbuf_offset = -1; + sdev->num_rows = 0; + sdev->wraparounds = -1; + sdev->num_blank = 0; + sdev->finger_removed = 0; + sdev->last_seqnum = 16383; + sdev->killing_transfers = 0; + fpi_ssm_next_state(ssm); + break; + case CAPSM_1000_FIRE_BULK: ; + capsm_fire_bulk (ssm); + break; + case CAPSM_1000_WRITEV: + sm_write_regs(ssm, capsm_1000_writev, G_N_ELEMENTS(capsm_1000_writev)); + break; + } +} + /***** DEINITIALIZATION *****/ static const struct sonly_regwrite deinitsm_writev[] = { @@ -817,11 +908,23 @@ static const struct sonly_regwrite deinitsm_writev[] = { { 0x0b, 0x00 }, { 0x09, 0x20 }, { 0x13, 0x45 }, { 0x13, 0x45 }, }; +static const struct sonly_regwrite deinitsm_1000_writev[] = { + { 0x15, 0x26 }, { 0x30, 0xe0 }, /* Disable finger detection */ + + { 0x0b, 0x00 }, { 0x13, 0x45 }, { 0x08, 0x00 }, /* Disable capture mode */ +}; + + enum deinitsm_states { DEINITSM_WRITEV, DEINITSM_NUM_STATES, }; +enum deinitsm_1000_states { + DEINITSM_1000_WRITEV, + DEINITSM_1000_NUM_STATES, +}; + static void deinitsm_run_state(struct fpi_ssm *ssm) { switch (ssm->cur_state) { @@ -831,6 +934,15 @@ static void deinitsm_run_state(struct fpi_ssm *ssm) } } +static void deinitsm_1000_run_state(struct fpi_ssm *ssm) +{ + switch (ssm->cur_state) { + case DEINITSM_1000_WRITEV: + sm_write_regs(ssm, deinitsm_1000_writev, G_N_ELEMENTS(deinitsm_1000_writev)); + break; + } +} + /***** INITIALIZATION *****/ static const struct sonly_regwrite initsm_writev_1[] = { @@ -846,6 +958,19 @@ static const struct sonly_regwrite initsm_writev_1[] = { { 0x44, 0x00 }, { 0x0b, 0x00 }, }; +static const struct sonly_regwrite initsm_1000_writev_1[] = { + { 0x49, 0x00 }, /* Encryption disabled */ + + /* Setting encryption key. Doesn't need to be random since we don't use any + * encryption. */ + { 0x3e, 0x7f }, { 0x3e, 0x7f }, { 0x3e, 0x7f }, { 0x3e, 0x7f }, + { 0x3e, 0x7f }, { 0x3e, 0x7f }, { 0x3e, 0x7f }, { 0x3e, 0x7f }, + + { 0x04, 0x00 }, { 0x05, 0x00 }, + + { 0x0b, 0x00 }, { 0x08, 0x00 }, /* Initialize capture control registers */ +}; + enum initsm_states { INITSM_WRITEV_1, INITSM_READ_09, @@ -857,6 +982,11 @@ enum initsm_states { INITSM_NUM_STATES, }; +enum initsm_1000_states { + INITSM_1000_WRITEV_1, + INITSM_1000_NUM_STATES, +}; + static void initsm_run_state(struct fpi_ssm *ssm) { struct fp_img_dev *dev = ssm->priv; @@ -887,6 +1017,18 @@ static void initsm_run_state(struct fpi_ssm *ssm) } } +static void initsm_1000_run_state(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct sonly_dev *sdev = dev->priv; + + switch (ssm->cur_state) { + case INITSM_1000_WRITEV_1: + sm_write_regs(ssm, initsm_1000_writev_1, G_N_ELEMENTS(initsm_1000_writev_1)); + break; + } +} + /***** CAPTURE LOOP *****/ enum loopsm_states { @@ -909,8 +1051,17 @@ static void loopsm_run_state(struct fpi_ssm *ssm) if (sdev->deactivating) { fpi_ssm_mark_completed(ssm); } else { - struct fpi_ssm *awfsm = fpi_ssm_new(dev->dev, awfsm_run_state, - AWFSM_NUM_STATES); + struct fpi_ssm *awfsm = NULL; + switch (sdev->dev_model) { + case UPEKSONLY_2016: + awfsm = fpi_ssm_new(dev->dev, awfsm_run_state, + AWFSM_NUM_STATES); + break; + case UPEKSONLY_1000: + awfsm = fpi_ssm_new(dev->dev, awfsm_1000_run_state, + AWFSM_1000_NUM_STATES); + break; + } awfsm->priv = dev; fpi_ssm_start_subsm(ssm, awfsm); } @@ -919,8 +1070,17 @@ static void loopsm_run_state(struct fpi_ssm *ssm) sm_await_intr(ssm); break; case LOOPSM_RUN_CAPSM: ; - struct fpi_ssm *capsm = fpi_ssm_new(dev->dev, capsm_run_state, - CAPSM_NUM_STATES); + struct fpi_ssm *capsm = NULL; + switch (sdev->dev_model) { + case UPEKSONLY_2016: + capsm = fpi_ssm_new(dev->dev, capsm_run_state, + CAPSM_NUM_STATES); + break; + case UPEKSONLY_1000: + capsm = fpi_ssm_new(dev->dev, capsm_1000_run_state, + CAPSM_1000_NUM_STATES); + break; + } capsm->priv = dev; fpi_ssm_start_subsm(ssm, capsm); break; @@ -929,8 +1089,17 @@ static void loopsm_run_state(struct fpi_ssm *ssm) * to push us into next state */ break; case LOOPSM_RUN_DEINITSM: ; - struct fpi_ssm *deinitsm = fpi_ssm_new(dev->dev, deinitsm_run_state, - DEINITSM_NUM_STATES); + struct fpi_ssm *deinitsm = NULL; + switch (sdev->dev_model) { + case UPEKSONLY_2016: + deinitsm = fpi_ssm_new(dev->dev, deinitsm_run_state, + DEINITSM_NUM_STATES); + break; + case UPEKSONLY_1000: + deinitsm = fpi_ssm_new(dev->dev, deinitsm_1000_run_state, + DEINITSM_1000_NUM_STATES); + break; + } sdev->capturing = FALSE; deinitsm->priv = dev; fpi_ssm_start_subsm(ssm, deinitsm); @@ -1039,7 +1208,14 @@ static int dev_activate(struct fp_img_dev *dev, enum fp_imgdev_state state) 4096, img_data_cb, &sdev->img_transfer_data[i], 0); } - ssm = fpi_ssm_new(dev->dev, initsm_run_state, INITSM_NUM_STATES); + switch (sdev->dev_model) { + case UPEKSONLY_2016: + ssm = fpi_ssm_new(dev->dev, initsm_run_state, INITSM_NUM_STATES); + break; + case UPEKSONLY_1000: + ssm = fpi_ssm_new(dev->dev, initsm_1000_run_state, INITSM_1000_NUM_STATES); + break; + } ssm->priv = dev; fpi_ssm_start(ssm, initsm_complete); return 0; @@ -1062,6 +1238,7 @@ static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) } dev->priv = g_malloc0(sizeof(struct sonly_dev)); + ((struct sonly_dev*)dev->priv)->dev_model = (int)driver_data; fpi_imgdev_open_complete(dev, 0); return 0; } @@ -1075,15 +1252,21 @@ static void dev_deinit(struct fp_img_dev *dev) static int dev_discover(struct libusb_device_descriptor *dsc, uint32_t *devtype) { - /* Revision 1 is what we're interested in */ - if (dsc->bcdDevice == 1) - return 1; + if (dsc->idProduct == 0x2016) { + if (dsc->bcdDevice == 1) /* Revision 1 is what we're interested in */ + return 1; + } + if (dsc->idProduct == 0x1000) { + if (dsc->bcdDevice == 0x0033) /* Looking for revision 0.33 */ + return 1; + } return 0; } static const struct usb_id id_table[] = { - { .vendor = 0x147e, .product = 0x2016 }, + { .vendor = 0x147e, .product = 0x2016, .driver_data = UPEKSONLY_2016 }, + { .vendor = 0x147e, .product = 0x1000, .driver_data = UPEKSONLY_1000 }, { 0, 0, 0, }, }; From 712ebb6d44c421543a999227c92d6e08003c7a96 Mon Sep 17 00:00:00 2001 From: Hugo Grostabussiat Date: Tue, 31 Aug 2010 16:57:26 +0200 Subject: [PATCH 172/184] Namespace functions and structs for 147e:2016 Inserted "_2016" in structures, enums and functions names that are related with device 147e:2016. --- libfprint/drivers/upeksonly.c | 158 +++++++++++++++++----------------- 1 file changed, 79 insertions(+), 79 deletions(-) diff --git a/libfprint/drivers/upeksonly.c b/libfprint/drivers/upeksonly.c index e2f5a459..6ca97067 100644 --- a/libfprint/drivers/upeksonly.c +++ b/libfprint/drivers/upeksonly.c @@ -663,7 +663,7 @@ static void sm_await_intr(struct fpi_ssm *ssm) /***** AWAIT FINGER *****/ -static const struct sonly_regwrite awfsm_writev_1[] = { +static const struct sonly_regwrite awfsm_2016_writev_1[] = { { 0x0a, 0x00 }, { 0x0a, 0x00 }, { 0x09, 0x20 }, { 0x03, 0x3b }, { 0x00, 0x67 }, { 0x00, 0x67 }, }; @@ -683,7 +683,7 @@ static const struct sonly_regwrite awfsm_1000_writev_1[] = { { 0x10, 0x00 }, { 0x11, 0xbf }, }; -static const struct sonly_regwrite awfsm_writev_2[] = { +static const struct sonly_regwrite awfsm_2016_writev_2[] = { { 0x01, 0xc6 }, { 0x0c, 0x13 }, { 0x0d, 0x0d }, { 0x0e, 0x0e }, { 0x0f, 0x0d }, { 0x0b, 0x00 }, }; @@ -693,12 +693,12 @@ static const struct sonly_regwrite awfsm_1000_writev_2[] = { { 0x30, 0xe1 }, { 0x15, 0x06 }, { 0x15, 0x86 }, }; -static const struct sonly_regwrite awfsm_writev_3[] = { +static const struct sonly_regwrite awfsm_2016_writev_3[] = { { 0x13, 0x45 }, { 0x30, 0xe0 }, { 0x12, 0x01 }, { 0x20, 0x01 }, { 0x09, 0x20 }, { 0x0a, 0x00 }, { 0x30, 0xe0 }, { 0x20, 0x01 }, }; -static const struct sonly_regwrite awfsm_writev_4[] = { +static const struct sonly_regwrite awfsm_2016_writev_4[] = { { 0x08, 0x00 }, { 0x10, 0x00 }, { 0x12, 0x01 }, { 0x11, 0xbf }, { 0x12, 0x01 }, { 0x07, 0x10 }, { 0x07, 0x10 }, { 0x04, 0x00 },\ { 0x05, 0x00 }, { 0x0b, 0x00 }, @@ -708,18 +708,18 @@ static const struct sonly_regwrite awfsm_writev_4[] = { { 0x15, 0x84 }, }; -enum awfsm_states { - AWFSM_WRITEV_1, - AWFSM_READ_01, - AWFSM_WRITE_01, - AWFSM_WRITEV_2, - AWFSM_READ_13, - AWFSM_WRITE_13, - AWFSM_WRITEV_3, - AWFSM_READ_07, - AWFSM_WRITE_07, - AWFSM_WRITEV_4, - AWFSM_NUM_STATES, +enum awfsm_2016_states { + AWFSM_2016_WRITEV_1, + AWFSM_2016_READ_01, + AWFSM_2016_WRITE_01, + AWFSM_2016_WRITEV_2, + AWFSM_2016_READ_13, + AWFSM_2016_WRITE_13, + AWFSM_2016_WRITEV_3, + AWFSM_2016_READ_07, + AWFSM_2016_WRITE_07, + AWFSM_2016_WRITEV_4, + AWFSM_2016_NUM_STATES, }; enum awfsm_1000_states { @@ -728,49 +728,49 @@ enum awfsm_1000_states { AWFSM_1000_NUM_STATES, }; -static void awfsm_run_state(struct fpi_ssm *ssm) +static void awfsm_2016_run_state(struct fpi_ssm *ssm) { struct fp_img_dev *dev = ssm->priv; struct sonly_dev *sdev = dev->priv; switch (ssm->cur_state) { - case AWFSM_WRITEV_1: - sm_write_regs(ssm, awfsm_writev_1, G_N_ELEMENTS(awfsm_writev_1)); + case AWFSM_2016_WRITEV_1: + sm_write_regs(ssm, awfsm_2016_writev_1, G_N_ELEMENTS(awfsm_2016_writev_1)); break; - case AWFSM_READ_01: + case AWFSM_2016_READ_01: sm_read_reg(ssm, 0x01); break; - case AWFSM_WRITE_01: + case AWFSM_2016_WRITE_01: if (sdev->read_reg_result != 0xc6) sm_write_reg(ssm, 0x01, 0x46); else sm_write_reg(ssm, 0x01, 0xc6); break; - case AWFSM_WRITEV_2: - sm_write_regs(ssm, awfsm_writev_2, G_N_ELEMENTS(awfsm_writev_2)); + case AWFSM_2016_WRITEV_2: + sm_write_regs(ssm, awfsm_2016_writev_2, G_N_ELEMENTS(awfsm_2016_writev_2)); break; - case AWFSM_READ_13: + case AWFSM_2016_READ_13: sm_read_reg(ssm, 0x13); break; - case AWFSM_WRITE_13: + case AWFSM_2016_WRITE_13: if (sdev->read_reg_result != 0x45) sm_write_reg(ssm, 0x13, 0x05); else sm_write_reg(ssm, 0x13, 0x45); break; - case AWFSM_WRITEV_3: - sm_write_regs(ssm, awfsm_writev_3, G_N_ELEMENTS(awfsm_writev_3)); + case AWFSM_2016_WRITEV_3: + sm_write_regs(ssm, awfsm_2016_writev_3, G_N_ELEMENTS(awfsm_2016_writev_3)); break; - case AWFSM_READ_07: + case AWFSM_2016_READ_07: sm_read_reg(ssm, 0x07); break; - case AWFSM_WRITE_07: + case AWFSM_2016_WRITE_07: if (sdev->read_reg_result != 0x10 && sdev->read_reg_result != 0x90) fp_warn("odd reg7 value %x", sdev->read_reg_result); sm_write_reg(ssm, 0x07, sdev->read_reg_result); break; - case AWFSM_WRITEV_4: - sm_write_regs(ssm, awfsm_writev_4, G_N_ELEMENTS(awfsm_writev_4)); + case AWFSM_2016_WRITEV_4: + sm_write_regs(ssm, awfsm_2016_writev_4, G_N_ELEMENTS(awfsm_2016_writev_4)); break; } } @@ -789,7 +789,7 @@ static void awfsm_1000_run_state(struct fpi_ssm *ssm) /***** CAPTURE MODE *****/ -static const struct sonly_regwrite capsm_writev[] = { +static const struct sonly_regwrite capsm_2016_writev[] = { /* enter capture mode */ { 0x09, 0x28 }, { 0x13, 0x55 }, { 0x0b, 0x80 }, { 0x04, 0x00 }, { 0x05, 0x00 }, @@ -799,13 +799,13 @@ static const struct sonly_regwrite capsm_1000_writev[] = { { 0x08, 0x80 }, { 0x13, 0x55 }, { 0x0b, 0x80 }, /* Enter capture mode */ }; -enum capsm_states { - CAPSM_INIT, - CAPSM_WRITE_15, - CAPSM_WRITE_30, - CAPSM_FIRE_BULK, - CAPSM_WRITEV, - CAPSM_NUM_STATES, +enum capsm_2016_states { + CAPSM_2016_INIT, + CAPSM_2016_WRITE_15, + CAPSM_2016_WRITE_30, + CAPSM_2016_FIRE_BULK, + CAPSM_2016_WRITEV, + CAPSM_2016_NUM_STATES, }; enum capsm_1000_states { @@ -845,13 +845,13 @@ static void capsm_fire_bulk(struct fpi_ssm *ssm) fpi_ssm_next_state(ssm); } -static void capsm_run_state(struct fpi_ssm *ssm) +static void capsm_2016_run_state(struct fpi_ssm *ssm) { struct fp_img_dev *dev = ssm->priv; struct sonly_dev *sdev = dev->priv; switch (ssm->cur_state) { - case CAPSM_INIT: + case CAPSM_2016_INIT: sdev->rowbuf_offset = -1; sdev->num_rows = 0; sdev->wraparounds = -1; @@ -861,17 +861,17 @@ static void capsm_run_state(struct fpi_ssm *ssm) sdev->killing_transfers = 0; fpi_ssm_next_state(ssm); break; - case CAPSM_WRITE_15: + case CAPSM_2016_WRITE_15: sm_write_reg(ssm, 0x15, 0x20); break; - case CAPSM_WRITE_30: + case CAPSM_2016_WRITE_30: sm_write_reg(ssm, 0x30, 0xe0); break; - case CAPSM_FIRE_BULK: ; + case CAPSM_2016_FIRE_BULK: ; capsm_fire_bulk (ssm); break; - case CAPSM_WRITEV: - sm_write_regs(ssm, capsm_writev, G_N_ELEMENTS(capsm_writev)); + case CAPSM_2016_WRITEV: + sm_write_regs(ssm, capsm_2016_writev, G_N_ELEMENTS(capsm_2016_writev)); break; } } @@ -903,7 +903,7 @@ static void capsm_1000_run_state(struct fpi_ssm *ssm) /***** DEINITIALIZATION *****/ -static const struct sonly_regwrite deinitsm_writev[] = { +static const struct sonly_regwrite deinitsm_2016_writev[] = { /* reset + enter low power mode */ { 0x0b, 0x00 }, { 0x09, 0x20 }, { 0x13, 0x45 }, { 0x13, 0x45 }, }; @@ -915,9 +915,9 @@ static const struct sonly_regwrite deinitsm_1000_writev[] = { }; -enum deinitsm_states { - DEINITSM_WRITEV, - DEINITSM_NUM_STATES, +enum deinitsm_2016_states { + DEINITSM_2016_WRITEV, + DEINITSM_2016_NUM_STATES, }; enum deinitsm_1000_states { @@ -925,11 +925,11 @@ enum deinitsm_1000_states { DEINITSM_1000_NUM_STATES, }; -static void deinitsm_run_state(struct fpi_ssm *ssm) +static void deinitsm_2016_run_state(struct fpi_ssm *ssm) { switch (ssm->cur_state) { - case DEINITSM_WRITEV: - sm_write_regs(ssm, deinitsm_writev, G_N_ELEMENTS(deinitsm_writev)); + case DEINITSM_2016_WRITEV: + sm_write_regs(ssm, deinitsm_2016_writev, G_N_ELEMENTS(deinitsm_2016_writev)); break; } } @@ -945,7 +945,7 @@ static void deinitsm_1000_run_state(struct fpi_ssm *ssm) /***** INITIALIZATION *****/ -static const struct sonly_regwrite initsm_writev_1[] = { +static const struct sonly_regwrite initsm_2016_writev_1[] = { { 0x49, 0x00 }, /* BSAPI writes different values to register 0x3e each time. I initially @@ -971,15 +971,15 @@ static const struct sonly_regwrite initsm_1000_writev_1[] = { { 0x0b, 0x00 }, { 0x08, 0x00 }, /* Initialize capture control registers */ }; -enum initsm_states { - INITSM_WRITEV_1, - INITSM_READ_09, - INITSM_WRITE_09, - INITSM_READ_13, - INITSM_WRITE_13, - INITSM_WRITE_04, - INITSM_WRITE_05, - INITSM_NUM_STATES, +enum initsm_2016_states { + INITSM_2016_WRITEV_1, + INITSM_2016_READ_09, + INITSM_2016_WRITE_09, + INITSM_2016_READ_13, + INITSM_2016_WRITE_13, + INITSM_2016_WRITE_04, + INITSM_2016_WRITE_05, + INITSM_2016_NUM_STATES, }; enum initsm_1000_states { @@ -987,31 +987,31 @@ enum initsm_1000_states { INITSM_1000_NUM_STATES, }; -static void initsm_run_state(struct fpi_ssm *ssm) +static void initsm_2016_run_state(struct fpi_ssm *ssm) { struct fp_img_dev *dev = ssm->priv; struct sonly_dev *sdev = dev->priv; switch (ssm->cur_state) { - case INITSM_WRITEV_1: - sm_write_regs(ssm, initsm_writev_1, G_N_ELEMENTS(initsm_writev_1)); + case INITSM_2016_WRITEV_1: + sm_write_regs(ssm, initsm_2016_writev_1, G_N_ELEMENTS(initsm_2016_writev_1)); break; - case INITSM_READ_09: + case INITSM_2016_READ_09: sm_read_reg(ssm, 0x09); break; - case INITSM_WRITE_09: + case INITSM_2016_WRITE_09: sm_write_reg(ssm, 0x09, sdev->read_reg_result & ~0x08); break; - case INITSM_READ_13: + case INITSM_2016_READ_13: sm_read_reg(ssm, 0x13); break; - case INITSM_WRITE_13: + case INITSM_2016_WRITE_13: sm_write_reg(ssm, 0x13, sdev->read_reg_result & ~0x10); break; - case INITSM_WRITE_04: + case INITSM_2016_WRITE_04: sm_write_reg(ssm, 0x04, 0x00); break; - case INITSM_WRITE_05: + case INITSM_2016_WRITE_05: sm_write_reg(ssm, 0x05, 0x00); break; } @@ -1054,8 +1054,8 @@ static void loopsm_run_state(struct fpi_ssm *ssm) struct fpi_ssm *awfsm = NULL; switch (sdev->dev_model) { case UPEKSONLY_2016: - awfsm = fpi_ssm_new(dev->dev, awfsm_run_state, - AWFSM_NUM_STATES); + awfsm = fpi_ssm_new(dev->dev, awfsm_2016_run_state, + AWFSM_2016_NUM_STATES); break; case UPEKSONLY_1000: awfsm = fpi_ssm_new(dev->dev, awfsm_1000_run_state, @@ -1073,8 +1073,8 @@ static void loopsm_run_state(struct fpi_ssm *ssm) struct fpi_ssm *capsm = NULL; switch (sdev->dev_model) { case UPEKSONLY_2016: - capsm = fpi_ssm_new(dev->dev, capsm_run_state, - CAPSM_NUM_STATES); + capsm = fpi_ssm_new(dev->dev, capsm_2016_run_state, + CAPSM_2016_NUM_STATES); break; case UPEKSONLY_1000: capsm = fpi_ssm_new(dev->dev, capsm_1000_run_state, @@ -1092,8 +1092,8 @@ static void loopsm_run_state(struct fpi_ssm *ssm) struct fpi_ssm *deinitsm = NULL; switch (sdev->dev_model) { case UPEKSONLY_2016: - deinitsm = fpi_ssm_new(dev->dev, deinitsm_run_state, - DEINITSM_NUM_STATES); + deinitsm = fpi_ssm_new(dev->dev, deinitsm_2016_run_state, + DEINITSM_2016_NUM_STATES); break; case UPEKSONLY_1000: deinitsm = fpi_ssm_new(dev->dev, deinitsm_1000_run_state, @@ -1210,7 +1210,7 @@ static int dev_activate(struct fp_img_dev *dev, enum fp_imgdev_state state) switch (sdev->dev_model) { case UPEKSONLY_2016: - ssm = fpi_ssm_new(dev->dev, initsm_run_state, INITSM_NUM_STATES); + ssm = fpi_ssm_new(dev->dev, initsm_2016_run_state, INITSM_2016_NUM_STATES); break; case UPEKSONLY_1000: ssm = fpi_ssm_new(dev->dev, initsm_1000_run_state, INITSM_1000_NUM_STATES); From ff842125c59ec87028bf53618b0a6acb310702e0 Mon Sep 17 00:00:00 2001 From: Kunal Gangakhedkar Date: Wed, 8 Sep 2010 12:13:17 +0530 Subject: [PATCH 173/184] Add C++ guards to take care of C++ name-mangling. The libfprint library is generally built with C calling conventions. Which makes it difficult to link to C++ programs as it is. This patch adds the support for linking with C++ code - by telling the C++ compiler to use C calling conventions for libfprint functions. Reported-by: Guus Ellenkamp Signed-off-by: Kunal Gangakhedkar --- libfprint/fprint.h | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/libfprint/fprint.h b/libfprint/fprint.h index 319b600f..99fa1e10 100644 --- a/libfprint/fprint.h +++ b/libfprint/fprint.h @@ -20,6 +20,10 @@ #ifndef __FPRINT_H__ #define __FPRINT_H__ +#ifdef __cplusplus +extern "C" { +#endif + #include #include @@ -336,5 +340,9 @@ typedef void (*fp_identify_stop_cb)(struct fp_dev *dev, void *user_data); int fp_async_identify_stop(struct fp_dev *dev, fp_identify_stop_cb callback, void *user_data); +#ifdef __cplusplus +} +#endif + #endif From 6bfc516553b8db1ed3a3d275eb3ff3f0bde24b48 Mon Sep 17 00:00:00 2001 From: Bastien Nocera Date: Wed, 8 Sep 2010 11:03:58 +0100 Subject: [PATCH 174/184] Add test program for C++ support So that we don't regress --- configure.ac | 1 + examples/Makefile.am | 5 ++++- examples/cpp-test.cpp | 11 +++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 examples/cpp-test.cpp diff --git a/configure.ac b/configure.ac index c627241f..714c44e6 100644 --- a/configure.ac +++ b/configure.ac @@ -9,6 +9,7 @@ AC_PROG_CC AC_PROG_LIBTOOL AC_C_INLINE AM_PROG_CC_C_O +AC_PROG_CXX AC_DEFINE([_GNU_SOURCE], [], [Use GNU extensions]) # Library versioning diff --git a/examples/Makefile.am b/examples/Makefile.am index 3f891349..b045ddb0 100644 --- a/examples/Makefile.am +++ b/examples/Makefile.am @@ -1,5 +1,5 @@ INCLUDES = -I$(top_srcdir) -noinst_PROGRAMS = verify_live enroll verify img_capture +noinst_PROGRAMS = verify_live enroll verify img_capture cpp-test verify_live_SOURCES = verify_live.c verify_live_LDADD = ../libfprint/libfprint.la @@ -13,6 +13,9 @@ verify_LDADD = ../libfprint/libfprint.la img_capture_SOURCES = img_capture.c img_capture_LDADD = ../libfprint/libfprint.la +cpp_test_SOURCES = cpp-test.cpp +cpp_test_LDADD = ../libfprint/libfprint.la + if BUILD_X11_EXAMPLES noinst_PROGRAMS += img_capture_continuous diff --git a/examples/cpp-test.cpp b/examples/cpp-test.cpp new file mode 100644 index 00000000..12936132 --- /dev/null +++ b/examples/cpp-test.cpp @@ -0,0 +1,11 @@ +#include +#include +#include + +#include + +int main (int argc, char **argv) +{ + fp_init (); + return 0; +} From aab031ce371e690eb550e8414282180190880ae3 Mon Sep 17 00:00:00 2001 From: Bastien Nocera Date: Wed, 8 Sep 2010 11:11:31 +0100 Subject: [PATCH 175/184] 0.3.0 --- NEWS | 7 +++++++ configure.ac | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/NEWS b/NEWS index 291d6258..a16c25fb 100644 --- a/NEWS +++ b/NEWS @@ -1,6 +1,13 @@ This file lists notable changes in each release. For the full history of all changes, see ChangeLog. +2010-09-08: v0.3.0 release + * Add support for UPEK TCS4C (USB ID 147e:1000) + * Use NSS instead of OpenSSL for GPL compliance + * upeksonly driver bug fixes + * Fix a crash if a scan was shorter than 8 lines + * Fix compilation with C++ compiler + 2010-08-19: v0.2.0 release (since 0.1.0-pre2) * Add gdk-pixbuf support for image manipulation * Add udev rules to allow devices to autosuspend diff --git a/configure.ac b/configure.ac index 714c44e6..87a1fe81 100644 --- a/configure.ac +++ b/configure.ac @@ -1,4 +1,4 @@ -AC_INIT([libfprint], [0.2.0]) +AC_INIT([libfprint], [0.3.0]) AM_INIT_AUTOMAKE([1.11 dist-bzip2 no-dist-gzip check-news]) AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_SRCDIR([libfprint/core.c]) From 3dd905d4e92962a970b877285fa6f39ed997a2ea Mon Sep 17 00:00:00 2001 From: Sergio Cerlesi Date: Wed, 16 Feb 2011 09:34:55 +0100 Subject: [PATCH 176/184] Fix return timeout of fp_get_next_timeout On function fp_get_next_timeout if exist fprint timeout or libusb timeout the function return the smaller of they. But if one of that not exist and have a smaller value the function return a timeout that not exist. --- libfprint/poll.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/libfprint/poll.c b/libfprint/poll.c index f78b6586..e849ea4f 100644 --- a/libfprint/poll.c +++ b/libfprint/poll.c @@ -270,6 +270,14 @@ API_EXPORTED int fp_get_next_timeout(struct timeval *tv) if (r_fprint == 0 && r_libusb == 0) return 0; + /* if fprint have no pending timeouts return libusb timeout */ + else if (r_fprint == 0) + *tv = libusb_timeout; + + /* if libusb have no pending timeouts return fprint timeout */ + else if (r_libusb == 0) + *tv = fprint_timeout; + /* otherwise return the smaller of the 2 timeouts */ else if (timercmp(&fprint_timeout, &libusb_timeout, <)) *tv = fprint_timeout; From a3ae96c2143ee7837225772008872ed0627336e1 Mon Sep 17 00:00:00 2001 From: Sergio Cerlesi Date: Tue, 22 Feb 2011 14:39:11 +0100 Subject: [PATCH 177/184] Fix function fpi_im_resize on create new image The function fpi_im_resize copy the new resized image into old fp_img instead of newimg so, new image is empty and often it generated a segmentation fault error. --- libfprint/gdkpixbuf.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libfprint/gdkpixbuf.c b/libfprint/gdkpixbuf.c index 7ffc0990..ea2d5bcd 100644 --- a/libfprint/gdkpixbuf.c +++ b/libfprint/gdkpixbuf.c @@ -75,7 +75,7 @@ struct fp_img *fpi_im_resize(struct fp_img *img, unsigned int factor) for (x = 0; x < newimg->width; x++) { guchar *p, *r; - r = img->data + y * img->width + x; + r = newimg->data + y * newimg->width + x; p = pixels + y * rowstride + x * 3; r[0] = p[0]; } From d2e957683f5b9bd4781e2216c259e9b10fa3508d Mon Sep 17 00:00:00 2001 From: Sergio Cerlesi Date: Wed, 30 Mar 2011 14:20:22 +0200 Subject: [PATCH 178/184] Added support for Validity VFS101 USB ID 138a:0001 --- configure.ac | 13 +- libfprint/Makefile.am | 6 + libfprint/core.c | 3 + libfprint/drivers/vfs101.c | 1570 ++++++++++++++++++++++++++++++++++++ libfprint/fp_internal.h | 3 + 5 files changed, 1594 insertions(+), 1 deletion(-) create mode 100644 libfprint/drivers/vfs101.c diff --git a/configure.ac b/configure.ac index 87a1fe81..e417317d 100644 --- a/configure.ac +++ b/configure.ac @@ -20,7 +20,7 @@ AC_SUBST(lt_major) AC_SUBST(lt_revision) AC_SUBST(lt_age) -all_drivers="upeke2 upekts upektc upeksonly vcom5s uru4000 fdu2000 aes1610 aes2501 aes4000" +all_drivers="upeke2 upekts upektc upeksonly vcom5s uru4000 fdu2000 aes1610 aes2501 aes4000 vfs101" require_imaging='no' require_aeslib='no' @@ -34,6 +34,7 @@ enable_fdu2000='no' enable_aes1610='no' enable_aes2501='no' enable_aes4000='no' +enable_vfs101='no' AC_ARG_WITH([drivers],[AS_HELP_STRING([--with-drivers], [List of drivers to enable])], @@ -88,6 +89,10 @@ for driver in `echo ${drivers} | sed -e 's/,/ /g' -e 's/,$//g'`; do require_imaging="yes" enable_aes4000="yes" ;; + vfs101) + AC_DEFINE([ENABLE_VFS101], [], [Build Validity VFS101 driver]) + enable_vfs101="yes" + ;; esac done @@ -102,6 +107,7 @@ AM_CONDITIONAL([ENABLE_AES1610], [test "$enable_aes1610" = "yes"]) AM_CONDITIONAL([ENABLE_AES2501], [test "$enable_aes2501" = "yes"]) AM_CONDITIONAL([ENABLE_AES4000], [test "$enable_aes4000" = "yes"]) AM_CONDITIONAL([REQUIRE_AESLIB], [test "$require_aeslib" = "yes"]) +AM_CONDITIONAL([ENABLE_VFS101], [test "$enable_vfs101" = "yes"]) PKG_CHECK_MODULES(LIBUSB, [libusb-1.0 >= 0.9.1]) @@ -263,6 +269,11 @@ if test x$enable_aes4000 != xno ; then else AC_MSG_NOTICE([ aes4000 driver disabled]) fi +if test x$enable_vfs101 != xno ; then + AC_MSG_NOTICE([** vfs101 driver enabled]) +else + AC_MSG_NOTICE([ vfs101 driver disabled]) +fi if test x$require_aeslib != xno ; then AC_MSG_NOTICE([** aeslib helper functions enabled]) else diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 84cb7b9b..95601bce 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -12,6 +12,7 @@ AES2501_SRC = drivers/aes2501.c drivers/aes2501.h AES4000_SRC = drivers/aes4000.c FDU2000_SRC = drivers/fdu2000.c VCOM5S_SRC = drivers/vcom5s.c +VFS101_SRC = drivers/vfs101.c EXTRA_DIST = \ $(UPEKE2_SRC) \ @@ -24,6 +25,7 @@ EXTRA_DIST = \ $(AES4000_SRC) \ $(FDU2000_SRC) \ $(VCOM5S_SRC) \ + $(VFS101_SRC) \ aeslib.c aeslib.h \ imagemagick.c \ gdkpixbuf.c @@ -122,6 +124,10 @@ if ENABLE_AES4000 DRIVER_SRC += $(AES4000_SRC) endif +if ENABLE_VFS101 +DRIVER_SRC += $(VFS101_SRC) +endif + if REQUIRE_IMAGEMAGICK OTHER_SRC += imagemagick.c libfprint_la_CFLAGS += $(IMAGING_CFLAGS) diff --git a/libfprint/core.c b/libfprint/core.c index d65a95d1..401c491d 100644 --- a/libfprint/core.c +++ b/libfprint/core.c @@ -368,6 +368,9 @@ static struct fp_img_driver * const img_drivers[] = { #ifdef ENABLE_AES1610 &aes1610_driver, #endif +#ifdef ENABLE_VFS101 + &vfs101_driver, +#endif /*#ifdef ENABLE_UPEKTC &upektc_driver, #endif diff --git a/libfprint/drivers/vfs101.c b/libfprint/drivers/vfs101.c new file mode 100644 index 00000000..c2d9a1ca --- /dev/null +++ b/libfprint/drivers/vfs101.c @@ -0,0 +1,1570 @@ +/* + * Validity VFS101 driver for libfprint + * Copyright (C) 2011 Sergio Cerlesi + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include +#include + +#define FP_COMPONENT "vfs101" + +#include + +/* Input-Output usb endpoint */ +#define EP_IN(n) (n | LIBUSB_ENDPOINT_IN) +#define EP_OUT(n) (n | LIBUSB_ENDPOINT_OUT) + +/* Usb bulk timeout */ +#define BULK_TIMEOUT 100 + +/* The device send back the image into block of 16 frames of 292 bytes */ +#define VFS_FRAME_SIZE 292 +#define VFS_BLOCK_SIZE 16 * VFS_FRAME_SIZE + +/* Buffer height */ +#define VFS_BUFFER_HEIGHT 5000 + +/* Buffer size */ +#define VFS_BUFFER_SIZE (VFS_BUFFER_HEIGHT * VFS_FRAME_SIZE) + +/* Image width */ +#define VFS_IMG_WIDTH 200 + +/* Maximum image height */ +#define VFS_IMG_MAX_HEIGHT 1023 + +/* Minimum image height */ +#define VFS_IMG_MIN_HEIGHT 200 + +/* Scan level thresold */ +#define VFS_IMG_SLT_BEGIN 768 +#define VFS_IMG_SLT_END 64 +#define VFS_IMG_SLT_LINES 4 + +/* Minimum image level */ +#define VFS_IMG_MIN_IMAGE_LEVEL 144 + +/* Best image contrast */ +#define VFS_IMG_BEST_CONRAST 128 + +/* Number of enroll stages */ +#define VFS_NR_ENROLL 3 + +/* Device parameters address */ +#define VFS_PAR_000E 0x000e +#define VFS_PAR_0011 0x0011 +#define VFS_PAR_THRESHOLD 0x0057 +#define VFS_PAR_STATE_3 0x005e +#define VFS_PAR_STATE_5 0x005f +#define VFS_PAR_INFO_RATE 0x0062 +#define VFS_PAR_0076 0x0076 +#define VFS_PAR_INFO_CONTRAST 0x0077 +#define VFS_PAR_0078 0x0078 + +/* Device regiones address */ +#define VFS_REG_IMG_EXPOSURE 0xff500e +#define VFS_REG_IMG_CONTRAST 0xff5038 + +/* Device settings */ +#define VFS_VAL_000E 0x0001 +#define VFS_VAL_0011 0x0008 +#define VFS_VAL_THRESHOLD 0x0096 +#define VFS_VAL_STATE_3 0x0064 +#define VFS_VAL_STATE_5 0x00c8 +#define VFS_VAL_INFO_RATE 0x0001 +#define VFS_VAL_0076 0x0012 +#define VFS_VAL_0078 0x2230 +#define VFS_VAL_IMG_EXPOSURE 0x21c0 + +/* Structure for Validity device */ +struct vfs101_dev +{ + /* Action state */ + int active; + + /* Sequential number */ + unsigned int seqnum; + + /* Usb transfer */ + struct libusb_transfer *transfer; + + /* Buffer for input/output */ + unsigned char buffer[VFS_BUFFER_SIZE]; + + /* Length of data to send or received */ + unsigned int length; + + /* Ignore usb error */ + int ignore_error; + + /* Timeout */ + struct fpi_timeout *timeout; + + /* Loop counter */ + int counter; + + /* Number of enroll stage */ + int enroll_stage; + + /* Image contrast */ + int contrast; + + /* Best contrast */ + int best_contrast; + + /* Best contrast level */ + int best_clevel; + + /* Bottom line of image */ + int bottom; + + /* Image height */ + int height; +}; + +/* Return byte at specified position */ +static inline unsigned char byte(int position, int value) +{ + return (value >> (position * 8)) & 0xff; +} + +/* Return sequential number */ +static inline unsigned short get_seqnum(int h, int l) +{ + return (h<<8) | l; +} + +/* Check sequential number */ +static inline int check_seqnum(struct vfs101_dev *vdev) +{ + if ((byte(0, vdev->seqnum) == vdev->buffer[0]) && + (byte(1, vdev->seqnum) == vdev->buffer[1])) + return 0; + else + return 1; +} + +/* Internal result codes */ +enum +{ + RESULT_RETRY, + RESULT_RETRY_SHORT, + RESULT_RETRY_REMOVE, + RESULT_COUNT, +}; + +/* Enroll result codes */ +static int result_codes[2][RESULT_COUNT] = +{ + { + FP_ENROLL_RETRY, + FP_ENROLL_RETRY_TOO_SHORT, + FP_ENROLL_RETRY_REMOVE_FINGER, + }, + { + FP_VERIFY_RETRY, + FP_VERIFY_RETRY_TOO_SHORT, + FP_VERIFY_RETRY_REMOVE_FINGER, + }, +}; + +/* Return result code based on current action */ +static int result_code(struct fp_img_dev *dev, int result) +{ + /* Check result value */ + if (result < 0 && result >= RESULT_COUNT) + return result; + + /* Return result code */ + if (dev->action == IMG_ACTION_ENROLL) + return result_codes[0][result]; + else + return result_codes[1][result]; +}; + +/* Dump buffer for debug */ +#define dump_buffer(buf) \ + fp_dbg("%02x %02x %02x %02x %02x %02x %02x %02x", \ + buf[6], buf[7], buf[8], buf[9], buf[10], buf[11], buf[12], buf[13] \ + ) + +/* Callback of asynchronous send */ +static void async_send_cb(struct libusb_transfer *transfer) +{ + struct fpi_ssm *ssm = transfer->user_data; + struct fp_img_dev *dev = ssm->priv; + struct vfs101_dev *vdev = dev->priv; + + /* Cleanup transfer */ + vdev->transfer = NULL; + + /* Skip error check if ignore_error is set */ + if (!vdev->ignore_error) + { + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) + { + /* Transfer not completed, return IO error */ + fp_err("transfer not completed, status = %d", transfer->status); + fpi_imgdev_session_error(dev, -EIO); + fpi_ssm_mark_aborted(ssm, -EIO); + goto out; + } + + if (transfer->length != transfer->actual_length) + { + /* Data sended mismatch with expected, return protocol error */ + fp_err("length mismatch, got %d, expected %d", + transfer->actual_length, transfer->length); + fpi_imgdev_session_error(dev, -EIO); + fpi_ssm_mark_aborted(ssm, -EIO); + goto out; + } + } + else + /* Reset ignore_error flag */ + vdev->ignore_error = FALSE; + + /* Dump buffer for debug */ + dump_buffer(vdev->buffer); + + fpi_ssm_next_state(ssm); + +out: + libusb_free_transfer(transfer); +} + +/* Submit asynchronous send */ +static void async_send(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct vfs101_dev *vdev = dev->priv; + int r; + + /* Allocation of transfer */ + vdev->transfer = libusb_alloc_transfer(0); + if (!vdev->transfer) + { + /* Allocation transfer failed, return no memory error */ + fp_err("allocation of usb transfer failed"); + fpi_imgdev_session_error(dev, -ENOMEM); + fpi_ssm_mark_aborted(ssm, -ENOMEM); + return; + } + + /* Put sequential number into the buffer */ + vdev->seqnum++; + vdev->buffer[0] = byte(0, vdev->seqnum); + vdev->buffer[1] = byte(1, vdev->seqnum); + + /* Prepare bulk transfer */ + libusb_fill_bulk_transfer(vdev->transfer, dev->udev, EP_OUT(1), vdev->buffer, vdev->length, async_send_cb, ssm, BULK_TIMEOUT); + + /* Submit transfer */ + r = libusb_submit_transfer(vdev->transfer); + if (r != 0) + { + /* Submission of transfer failed, return IO error */ + libusb_free_transfer(vdev->transfer); + fp_err("submit of usb transfer failed"); + fpi_imgdev_session_error(dev, -EIO); + fpi_ssm_mark_aborted(ssm, -EIO); + return; + } +} + +/* Callback of asynchronous recv */ +static void async_recv_cb(struct libusb_transfer *transfer) +{ + struct fpi_ssm *ssm = transfer->user_data; + struct fp_img_dev *dev = ssm->priv; + struct vfs101_dev *vdev = dev->priv; + + /* Cleanup transfer */ + vdev->transfer = NULL; + + /* Skip error check if ignore_error is set */ + if (!vdev->ignore_error) + { + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) + { + /* Transfer not completed, return IO error */ + fp_err("transfer not completed, status = %d", transfer->status); + fpi_imgdev_session_error(dev, -EIO); + fpi_ssm_mark_aborted(ssm, -EIO); + goto out; + } + + if (check_seqnum(vdev)) + { + /* Sequential number received mismatch, return protocol error */ + fp_err("seqnum mismatch, got %04x, expected %04x", + get_seqnum(vdev->buffer[1], vdev->buffer[0]), vdev->seqnum); + fpi_imgdev_session_error(dev, -EIO); + fpi_ssm_mark_aborted(ssm, -EIO); + goto out; + } + } + else + /* Reset ignore_error flag */ + vdev->ignore_error = FALSE; + + /* Dump buffer for debug */ + dump_buffer(vdev->buffer); + + /* Set length of received data */ + vdev->length = transfer->actual_length; + + fpi_ssm_next_state(ssm); + +out: + libusb_free_transfer(transfer); +} + +/* Submit asynchronous recv */ +static void async_recv(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct vfs101_dev *vdev = dev->priv; + int r; + + /* Allocation of transfer */ + vdev->transfer = libusb_alloc_transfer(0); + if (!vdev->transfer) + { + /* Allocation transfer failed, return no memory error */ + fp_err("allocation of usb transfer failed"); + fpi_imgdev_session_error(dev, -ENOMEM); + fpi_ssm_mark_aborted(ssm, -ENOMEM); + return; + } + + /* Prepare bulk transfer */ + libusb_fill_bulk_transfer(vdev->transfer, dev->udev, EP_IN(1), vdev->buffer, 0x0f, async_recv_cb, ssm, BULK_TIMEOUT); + + /* Submit transfer */ + r = libusb_submit_transfer(vdev->transfer); + if (r != 0) + { + /* Submission of transfer failed, free transfer and return IO error */ + libusb_free_transfer(vdev->transfer); + fp_err("submit of usb transfer failed"); + fpi_imgdev_session_error(dev, -EIO); + fpi_ssm_mark_aborted(ssm, -EIO); + return; + } +} + +static void async_load(struct fpi_ssm *ssm); + +/* Callback of asynchronous load */ +static void async_load_cb(struct libusb_transfer *transfer) +{ + struct fpi_ssm *ssm = transfer->user_data; + struct fp_img_dev *dev = ssm->priv; + struct vfs101_dev *vdev = dev->priv; + + /* Cleanup transfer */ + vdev->transfer = NULL; + + /* Skip error check if ignore_error is set */ + if (!vdev->ignore_error) + { + if (transfer->status != LIBUSB_TRANSFER_COMPLETED) + { + /* Transfer not completed */ + fp_err("transfer not completed, status = %d, length = %d", transfer->status, vdev->length); + fpi_imgdev_session_error(dev, -EIO); + fpi_ssm_mark_aborted(ssm, -EIO); + goto out; + } + + if (transfer->actual_length % VFS_FRAME_SIZE) + { + /* Received incomplete frame, return protocol error */ + fp_err("received incomplete frame"); + fpi_imgdev_session_error(dev, -EIO); + fpi_ssm_mark_aborted(ssm, -EIO); + goto out; + } + } + + /* Increase image length */ + vdev->length += transfer->actual_length; + + if (transfer->actual_length == VFS_BLOCK_SIZE) + { + if ((VFS_BUFFER_SIZE - vdev->length) < VFS_BLOCK_SIZE) + { + /* Buffer full, image too large, return no memory error */ + fp_err("buffer full, image too large"); + fpi_imgdev_session_error(dev, -ENOMEM); + fpi_ssm_mark_aborted(ssm, -ENOMEM); + goto out; + } + else + /* Image load not completed, submit another asynchronous load */ + async_load(ssm); + } + else + { + /* Reset ignore_error flag */ + if (vdev->ignore_error) + vdev->ignore_error = FALSE; + + /* Image load completed, go to next state */ + vdev->height = vdev->length / VFS_FRAME_SIZE; + fp_dbg("image loaded, height = %d", vdev->height); + fpi_ssm_next_state(ssm); + } + +out: + libusb_free_transfer(transfer); +} + +/* Submit asynchronous load */ +static void async_load(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct vfs101_dev *vdev = dev->priv; + unsigned char *buffer; + int r; + + /* Allocation of transfer */ + vdev->transfer = libusb_alloc_transfer(0); + if (!vdev->transfer) + { + /* Allocation transfer failed, return no memory error */ + fp_err("allocation of usb transfer failed"); + fpi_imgdev_session_error(dev, -ENOMEM); + fpi_ssm_mark_aborted(ssm, -ENOMEM); + return; + } + + /* Append new data into the buffer */ + buffer = vdev->buffer + vdev->length; + + /* Prepare bulk transfer */ + libusb_fill_bulk_transfer(vdev->transfer, dev->udev, EP_IN(2), buffer, VFS_BLOCK_SIZE, async_load_cb, ssm, BULK_TIMEOUT); + + /* Submit transfer */ + r = libusb_submit_transfer(vdev->transfer); + if (r != 0) + { + /* Submission of transfer failed, return IO error */ + libusb_free_transfer(vdev->transfer); + fp_err("submit of usb transfer failed"); + fpi_imgdev_session_error(dev, -EIO); + fpi_ssm_mark_aborted(ssm, -EIO); + return; + } +} + +/* Callback of asynchronous sleep */ +static void async_sleep_cb(void *data) +{ + struct fpi_ssm *ssm = data; + struct fp_img_dev *dev = ssm->priv; + struct vfs101_dev *vdev = dev->priv; + + /* Cleanup timeout */ + vdev->timeout = NULL; + + fpi_ssm_next_state(ssm); +} + +/* Submit asynchronous sleep */ +static void async_sleep(unsigned int msec, struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct vfs101_dev *vdev = dev->priv; + + /* Add timeout */ + vdev->timeout = fpi_timeout_add(msec, async_sleep_cb, ssm); + + if (vdev->timeout == NULL) + { + /* Failed to add timeout */ + fp_err("failed to add timeout"); + fpi_imgdev_session_error(dev, -ETIME); + fpi_ssm_mark_aborted(ssm, -ETIME); + } +} + +/* Swap ssm states */ +enum +{ + M_SWAP_SEND, + M_SWAP_RECV, + M_SWAP_NUM_STATES, +}; + +/* Exec swap sequential state machine */ +static void m_swap_state(struct fpi_ssm *ssm) +{ + switch (ssm->cur_state) + { + case M_SWAP_SEND: + /* Send data */ + async_send(ssm); + break; + + case M_SWAP_RECV: + /* Recv response */ + async_recv(ssm); + break; + } +} + +/* Start swap sequential state machine */ +static void m_swap(struct fpi_ssm *ssm, unsigned char *data, size_t length) +{ + struct fp_img_dev *dev = ssm->priv; + struct vfs101_dev *vdev = dev->priv; + struct fpi_ssm *subsm; + + /* Prepare data for sending */ + memcpy(vdev->buffer, data, length); + memset(vdev->buffer + length, 0, 16 - length); + vdev->length = length; + + /* Start swap ssm */ + subsm = fpi_ssm_new(dev->dev, m_swap_state, M_SWAP_NUM_STATES); + subsm->priv = dev; + fpi_ssm_start_subsm(ssm, subsm); +} + +/* Retrieve fingerprint image */ +static void vfs_get_print(struct fpi_ssm *ssm, unsigned int param, int type) +{ + unsigned char data[2][0x0e] = { + { 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, + 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01 }, + { 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, + 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x01 } + }; + + fp_dbg("param = %04x, type = %d", param, type); + + /* Prepare data for sending */ + data[type][6] = byte(0, param); + data[type][7] = byte(1, param); + + /* Run swap sequential state machine */ + m_swap(ssm, data[type], 0x0e); +} + +/* Set a parameter value on the device */ +static void vfs_set_param(struct fpi_ssm *ssm, unsigned int param, unsigned int value) +{ + unsigned char data[0x0a] = { 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00 }; + + fp_dbg("param = %04x, value = %04x", param, value); + + /* Prepare data for sending */ + data[6] = byte(0, param); + data[7] = byte(1, param); + data[8] = byte(0, value); + data[9] = byte(1, value); + + /* Run swap sequential state machine */ + m_swap(ssm, data, 0x0a); +} + +/* Abort previous print */ +static void vfs_abort_print(struct fpi_ssm *ssm) +{ + unsigned char data[0x06] = { 0x00, 0x00, 0x00, 0x00, 0x0E, 0x00 }; + + fp_dbg(""); + + /* Run swap sequential state machine */ + m_swap (ssm, data, 0x06); +} + +/* Poke a value on a region */ +static void vfs_poke(struct fpi_ssm *ssm, unsigned int addr, unsigned int value, unsigned int size) +{ + unsigned char data[0x0f] = { 0x00, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + + fp_dbg("addr = %04x, value = %04x", addr, value); + + /* Prepare data for sending */ + data[6] = byte(0, addr); + data[7] = byte(1, addr); + data[8] = byte(2, addr); + data[9] = byte(3, addr); + data[10] = byte(0, value); + data[11] = byte(1, value); + data[12] = byte(2, value); + data[13] = byte(3, value); + data[14] = byte(0, size); + + /* Run swap sequential state machine */ + m_swap(ssm, data, 0x0f); +} + +/* Get current finger state */ +static void vfs_get_finger_state(struct fpi_ssm *ssm) +{ + unsigned char data[0x06] = { 0x00, 0x00, 0x00, 0x00, 0x16, 0x00 }; + + fp_dbg(""); + + /* Run swap sequential state machine */ + m_swap (ssm, data, 0x06); +} + +/* Load raw image from reader */ +static void vfs_img_load(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct vfs101_dev *vdev = dev->priv; + + fp_dbg(""); + + /* Reset buffer length */ + vdev->length = 0; + + /* Reset image properties */ + vdev->bottom = 0; + vdev->height = -1; + + /* Asynchronous load */ + async_load(ssm); +} + +/* Check if action is completed */ +static int action_completed(struct fp_img_dev *dev) +{ + struct vfs101_dev *vdev = dev->priv; + + if ((dev->action == IMG_ACTION_ENROLL) && + (vdev->enroll_stage < VFS_NR_ENROLL)) + /* Enroll not completed, return false */ + return FALSE; + + else if (vdev->enroll_stage < 1) + /* Action not completed, return false */ + return FALSE; + + /* Action completed, return true */ + return TRUE; +} + +#define offset(x, y) ((x) + ((y) * VFS_FRAME_SIZE)) + +/* Screen image to remove noise and find bottom line and height od image */ +static void img_screen(struct vfs101_dev *vdev) +{ + int y, x, count, top; + long int level; + int last_line = vdev->height - 1; + + fp_dbg("image height before screen = %d", vdev->height); + + count = 0; + + /* Image returned from sensor can contain many empty lines, + * for remove these lines compare byte 282-283 (scan level information) + * with two differents threshold, one for the begin of finger image and + * one for the end. To increase stability of the code use a counter + * of lines that satisfy the threshold. + */ + for (y = last_line, top = last_line; y >= 0; y--) + { + /* Take image scan level */ + level = vdev->buffer[offset(283, y)] * 256 + + vdev->buffer[offset(282, y)]; + + fp_dbg("line = %d, scan level = %ld", y, level); + + if (level >= VFS_IMG_SLT_BEGIN && top == last_line) + { + /* Begin threshold satisfied */ + if (count < VFS_IMG_SLT_LINES) + /* Increase count */ + count++; + else + { + /* Found top fingerprint line */ + top = y + VFS_IMG_SLT_LINES; + count = 0; + } + } + else if ((level < VFS_IMG_SLT_END || level >= 65535) && + top != last_line) + { + /* End threshold satisfied */ + if (count < VFS_IMG_SLT_LINES) + /* Increase count */ + count++; + else + { + /* Found bottom fingerprint line */ + vdev->bottom = y + VFS_IMG_SLT_LINES + 1; + break; + } + } + else + /* Not threshold satisfied, reset count */ + count = 0; + } + + vdev->height = top - vdev->bottom + 1; + + /* Checkk max height */ + if (vdev->height > VFS_IMG_MAX_HEIGHT) + vdev->height = VFS_IMG_MAX_HEIGHT; + + fp_dbg("image height after screen = %d", vdev->height); + + /* Scan image and remove noise */ + for (y = vdev->bottom; y <= top; y++) + for (x = 6; x < VFS_IMG_WIDTH + 6; x++) + if (vdev->buffer[offset(x, y)] > VFS_IMG_MIN_IMAGE_LEVEL) + vdev->buffer[offset(x, y)] = 255; +}; + +/* Copy image from reader buffer and put it into image data */ +static void img_copy(struct vfs101_dev *vdev, struct fp_img *img) +{ + unsigned int line; + unsigned char *img_buffer = img->data; + unsigned char *vdev_buffer = vdev->buffer + (vdev->bottom * VFS_FRAME_SIZE) + 6; + + for (line = 0; line < img->height; line++) + { + /* Copy image line from reader buffer to image data */ + memcpy(img_buffer, vdev_buffer, VFS_IMG_WIDTH); + + /* Next line of reader buffer */ + vdev_buffer = vdev_buffer + VFS_FRAME_SIZE; + + /* Next line of image buffer */ + img_buffer = img_buffer + VFS_IMG_WIDTH; + } +} + +/* Extract fingerpint image from raw data */ +static void img_extract(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct vfs101_dev *vdev = dev->priv; + struct fp_img *img; + + /* Screen image to remove noise and find top and bottom line */ + img_screen(vdev); + + /* Check image height */ + if (vdev->height < VFS_IMG_MIN_HEIGHT) + { + /* Image too short */ + vdev->height = 0; + return; + } + + /* Fingerprint is present, load image from reader */ + fpi_imgdev_report_finger_status(dev, TRUE); + + /* Create new image */ + img = fpi_img_new(vdev->height * VFS_IMG_WIDTH); + img->width = VFS_IMG_WIDTH; + img->height = vdev->height; + img->flags = FP_IMG_V_FLIPPED; + + /* Copy data into image */ + img_copy(vdev, img); + + /* Notify image captured */ + fpi_imgdev_image_captured(dev, img); + + /* Check captured result */ + if (dev->action_result >= 0 && + dev->action_result != FP_ENROLL_RETRY && + dev->action_result != FP_VERIFY_RETRY) + { + /* Image captured, increase enroll stage */ + vdev->enroll_stage++; + + /* Check if action is completed */ + if (!action_completed(dev)) + dev->action_result = FP_ENROLL_PASS; + } + else + { + /* Image capture failed */ + if (dev->action == IMG_ACTION_ENROLL) + /* Return retry */ + dev->action_result = result_code(dev, RESULT_RETRY); + else + { + /* Return no match */ + vdev->enroll_stage++; + dev->action_result = FP_VERIFY_NO_MATCH; + } + } + + /* Fingerprint is removed from reader */ + fpi_imgdev_report_finger_status(dev, FALSE); +}; + +/* Finger states */ +enum +{ + VFS_FINGER_EMPTY, + VFS_FINGER_PRESENT, + VFS_FINGER_UNKNOWN, +}; + +/* Return finger state */ +static inline int vfs_finger_state(struct vfs101_dev *vdev) +{ + /* Check finger state */ + switch (vdev->buffer[0x0a]) + { + case 0x00: + case 0x01: + /* Finger is empty */ + return VFS_FINGER_EMPTY; + break; + + case 0x02: + case 0x03: + case 0x04: + case 0x05: + case 0x06: + /* Finger is present */ + return VFS_FINGER_PRESENT; + break; + + default: + return VFS_FINGER_UNKNOWN; + } +}; + +/* Check contrast of image */ +static void vfs_check_contrast(struct vfs101_dev *vdev) +{ + int y; + long int count = 0; + + /* Check difference from byte 4 to byte 5 for verify contrast of image */ + for (y = 0; y < vdev->height; y++) + count = count + vdev->buffer[offset(5, y)] - vdev->buffer[offset(4, y)]; + count = count / vdev->height; + + if (count < 16) + { + /* Contrast not valid, retry */ + vdev->contrast++; + return; + } + + fp_dbg("contrast = %d, level = %ld", vdev->contrast, count); + + if (abs(count - VFS_IMG_BEST_CONRAST) < abs(vdev->best_clevel - VFS_IMG_BEST_CONRAST)) + { + /* Better contrast found, use it */ + vdev->best_contrast = vdev->contrast; + vdev->best_clevel = count; + } +} + +/* Loop ssm states */ +enum +{ + /* Step 0 - Scan finger */ + M_LOOP_0_GET_PRINT, + M_LOOP_0_SLEEP, + M_LOOP_0_GET_STATE, + M_LOOP_0_LOAD_IMAGE, + M_LOOP_0_EXTRACT_IMAGE, + M_LOOP_0_CHECK_ACTION, + + /* Step 1 - Scan failed */ + M_LOOP_1_GET_STATE, + M_LOOP_1_CHECK_STATE, + M_LOOP_1_GET_PRINT, + M_LOOP_1_LOAD_IMAGE, + M_LOOP_1_LOOP, + M_LOOP_1_SLEEP, + + /* Step 2 - Abort print */ + M_LOOP_2_ABORT_PRINT, + M_LOOP_2_LOAD_IMAGE, + + /* Step 3 - Wait aborting */ + M_LOOP_3_GET_PRINT, + M_LOOP_3_LOAD_IMAGE, + M_LOOP_3_CHECK_IMAGE, + M_LOOP_3_LOOP, + + /* Number of states */ + M_LOOP_NUM_STATES, +}; + +/* Exec loop sequential state machine */ +static void m_loop_state(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct vfs101_dev *vdev = dev->priv; + + /* Check action state */ + if (!vdev->active) + { + /* Action not active, mark sequential state machine completed */ + fpi_ssm_mark_completed(ssm); + return; + } + + switch (ssm->cur_state) + { + case M_LOOP_0_GET_PRINT: + /* Send get print command to the reader */ + vfs_get_print(ssm, VFS_BUFFER_HEIGHT, 1); + break; + + case M_LOOP_0_SLEEP: + /* Wait fingerprint scanning */ + async_sleep(50, ssm); + break; + + case M_LOOP_0_GET_STATE: + /* Get finger state */ + vfs_get_finger_state(ssm); + break; + + case M_LOOP_0_LOAD_IMAGE: + /* Check finger state */ + switch (vfs_finger_state(vdev)) + { + case VFS_FINGER_EMPTY: + /* Finger isn't present, loop */ + fpi_ssm_jump_to_state(ssm, M_LOOP_0_SLEEP); + break; + + case VFS_FINGER_PRESENT: + /* Load image from reader */ + vdev->ignore_error = TRUE; + vfs_img_load(ssm); + break; + + default: + /* Unknown state */ + fp_err("unknown device state 0x%02x", vdev->buffer[0x0a]); + fpi_imgdev_session_error(dev, -EIO); + fpi_ssm_mark_aborted(ssm, -EIO); + break; + } + break; + + case M_LOOP_0_EXTRACT_IMAGE: + /* Check if image is loaded */ + if (vdev->height > 0) + /* Fingerprint is loaded, extract image from raw data */ + img_extract(ssm); + + /* Wait handling image */ + async_sleep(10, ssm); + break; + + case M_LOOP_0_CHECK_ACTION: + /* Check if action is completed */ + if (action_completed(dev)) + /* Action completed */ + fpi_ssm_mark_completed(ssm); + else + /* Action not completed */ + if (vdev->height > 0) + /* Continue loop */ + fpi_ssm_jump_to_state(ssm, M_LOOP_2_ABORT_PRINT); + else + /* Error found */ + fpi_ssm_next_state(ssm); + break; + + case M_LOOP_1_GET_STATE: + /* Get finger state */ + vfs_get_finger_state(ssm); + break; + + case M_LOOP_1_CHECK_STATE: + /* Check finger state */ + if (vfs_finger_state(vdev) == VFS_FINGER_PRESENT) + { + if (vdev->counter < 20) + { + if (vdev->counter == 1) + { + /* The user should remove their finger from the scanner */ + fp_warn("finger present after scan, remove it"); + fpi_imgdev_session_error(dev, result_code(dev, RESULT_RETRY_REMOVE)); + } + + /* Wait removing finger */ + vdev->counter++; + async_sleep(250, ssm); + } + else + { + /* reach max loop counter, return protocol error */ + fp_err("finger not removed from the scanner"); + fpi_imgdev_session_error(dev, -EIO); + fpi_ssm_mark_aborted(ssm, -EIO); + } + } + else + { + /* Finger not present */ + if (vdev->counter == 0) + { + /* Check image height */ + if (vdev->height == 0) + { + /* Return retry to short */ + fp_warn("image too short, retry"); + fpi_imgdev_session_error(dev, result_code(dev, RESULT_RETRY_SHORT)); + } + else + { + /* Return retry result */ + fp_warn("load image failed, retry"); + fpi_imgdev_session_error(dev, result_code(dev, RESULT_RETRY)); + } + } + + /* Continue */ + vdev->counter = 0; + fpi_ssm_jump_to_state(ssm, M_LOOP_1_SLEEP); + } + break; + + case M_LOOP_1_GET_PRINT: + /* Send get print command to the reader */ + vfs_get_print(ssm, VFS_BUFFER_HEIGHT, 1); + break; + + case M_LOOP_1_LOAD_IMAGE: + /* Load image */ + vdev->ignore_error = TRUE; + vfs_img_load(ssm); + break; + + case M_LOOP_1_LOOP: + /* Loop */ + fpi_ssm_jump_to_state(ssm, M_LOOP_1_GET_STATE); + break; + + case M_LOOP_1_SLEEP: + /* Wait fingerprint scanning */ + async_sleep(10, ssm); + break; + + case M_LOOP_2_ABORT_PRINT: + /* Abort print command */ + vfs_abort_print(ssm); + break; + + case M_LOOP_2_LOAD_IMAGE: + /* Load abort image */ + vdev->ignore_error = TRUE; + vfs_img_load(ssm); + break; + + case M_LOOP_3_GET_PRINT: + /* Get empty image */ + vfs_get_print(ssm, 0x000a, 0); + break; + + case M_LOOP_3_LOAD_IMAGE: + /* Load abort image */ + vdev->ignore_error = TRUE; + vfs_img_load(ssm); + break; + + case M_LOOP_3_CHECK_IMAGE: + if (vdev->height == 10) + { + /* Image load correctly, jump to step 0 */ + vdev->counter = 0; + fpi_ssm_jump_to_state(ssm, M_LOOP_0_GET_PRINT); + } + else if (vdev->counter < 10) + { + /* Wait aborting */ + vdev->counter++; + async_sleep(100, ssm); + } + else + { + /* reach max loop counter, return protocol error */ + fp_err("waiting abort reach max loop counter"); + fpi_imgdev_session_error(dev, -EIO); + fpi_ssm_mark_aborted(ssm, -EIO); + } + break; + + case M_LOOP_3_LOOP: + /* Loop */ + fpi_ssm_jump_to_state(ssm, M_LOOP_3_GET_PRINT); + break; + } +} + +/* Complete loop sequential state machine */ +static void m_loop_complete(struct fpi_ssm *ssm) +{ + /* Free sequential state machine */ + fpi_ssm_free(ssm); +} + +/* Init ssm states */ +enum +{ + /* Step 0 - Cleanup device buffer */ + M_INIT_0_RECV_DIRTY, + M_INIT_0_ABORT_PRINT, + M_INIT_0_LOAD_IMAGE, + + /* Step 1 - Wait aborting */ + M_INIT_1_GET_PRINT, + M_INIT_1_LOAD_IMAGE, + M_INIT_1_CHECK_IMAGE, + M_INIT_1_LOOP, + + /* Step 2 - Handle unexpected finger presence */ + M_INIT_2_GET_STATE, + M_INIT_2_CHECK_STATE, + M_INIT_2_GET_PRINT, + M_INIT_2_LOAD_IMAGE, + M_INIT_2_LOOP, + + /* Step 3 - Set parameters */ + M_INIT_3_SET_000E, + M_INIT_3_SET_0011, + M_INIT_3_SET_0076, + M_INIT_3_SET_0078, + M_INIT_3_SET_THRESHOLD, + M_INIT_3_SET_STATE3_COUNT, + M_INIT_3_SET_STATE5_COUNT, + M_INIT_3_SET_INFO_CONTRAST, + M_INIT_3_SET_INFO_RATE, + + /* Step 4 - Autocalibrate contrast */ + M_INIT_4_SET_EXPOSURE, + M_INIT_4_SET_CONTRAST, + M_INIT_4_GET_PRINT, + M_INIT_4_LOAD_IMAGE, + M_INIT_4_CHECK_CONTRAST, + + /* Step 5 - Set info line parameters */ + M_INIT_5_SET_EXPOSURE, + M_INIT_5_SET_CONTRAST, + M_INIT_5_SET_INFO_CONTRAST, + M_INIT_5_SET_INFO_RATE, + + /* Number of states */ + M_INIT_NUM_STATES, +}; + +/* Exec init sequential state machine */ +static void m_init_state(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct vfs101_dev *vdev = dev->priv; + + /* Check action state */ + if (!vdev->active) + { + /* Action not active, mark sequential state machine completed */ + fpi_ssm_mark_completed(ssm); + return; + } + + switch (ssm->cur_state) + { + case M_INIT_0_RECV_DIRTY: + /* Recv eventualy dirty data */ + vdev->ignore_error = TRUE; + async_recv(ssm); + break; + + case M_INIT_0_ABORT_PRINT: + /* Abort print command */ + vfs_abort_print(ssm); + break; + + case M_INIT_0_LOAD_IMAGE: + /* Load abort image */ + vdev->ignore_error = TRUE; + vfs_img_load(ssm); + break; + + case M_INIT_1_GET_PRINT: + /* Get empty image */ + vfs_get_print(ssm, 0x000a, 0); + break; + + case M_INIT_1_LOAD_IMAGE: + /* Load abort image */ + vdev->ignore_error = TRUE; + vfs_img_load(ssm); + break; + + case M_INIT_1_CHECK_IMAGE: + if (vdev->height == 10) + { + /* Image load correctly, jump to step 2 */ + vdev->counter = 0; + fpi_ssm_jump_to_state(ssm, M_INIT_2_GET_STATE); + } + else if (vdev->counter < 10) + { + /* Wait aborting */ + vdev->counter++; + async_sleep(100, ssm); + } + else + { + /* reach max loop counter, return protocol error */ + fp_err("waiting abort reach max loop counter"); + fpi_imgdev_session_error(dev, -EIO); + fpi_ssm_mark_aborted(ssm, -EIO); + } + break; + + case M_INIT_1_LOOP: + /* Loop */ + fpi_ssm_jump_to_state(ssm, M_INIT_1_GET_PRINT); + break; + + case M_INIT_2_GET_STATE: + /* Get finger state */ + vfs_get_finger_state(ssm); + break; + + case M_INIT_2_CHECK_STATE: + /* Check finger state */ + if (vfs_finger_state(vdev) == VFS_FINGER_PRESENT) + { + if (vdev->counter < 20) + { + if (vdev->counter == 2) + { + /* The user should remove their finger from the scanner */ + fp_warn("unexpected finger find, remove finger from the scanner"); + fpi_imgdev_session_error(dev, result_code(dev, RESULT_RETRY_REMOVE)); + } + + /* Wait removing finger */ + vdev->counter++; + async_sleep(250, ssm); + } + else + { + /* reach max loop counter, return protocol error */ + fp_err("finger not removed from the scanner"); + fpi_imgdev_session_error(dev, -EIO); + fpi_ssm_mark_aborted(ssm, -EIO); + } + } + else + { + /* Finger not present */ + if (vdev->counter == 0) + /* Continue */ + fpi_ssm_jump_to_state(ssm, M_INIT_3_SET_000E); + else + { + /* Finger removed, jump to abort */ + vdev->counter = 0; + fpi_ssm_jump_to_state(ssm, M_INIT_0_ABORT_PRINT); + } + } + break; + + case M_INIT_2_GET_PRINT: + /* Send get print command to the reader */ + vfs_get_print(ssm, VFS_BUFFER_HEIGHT, 1); + break; + + case M_INIT_2_LOAD_IMAGE: + /* Load unexpected image */ + vdev->ignore_error = TRUE; + vfs_img_load(ssm); + break; + + case M_INIT_2_LOOP: + /* Loop */ + fpi_ssm_jump_to_state(ssm, M_INIT_2_GET_STATE); + break; + + case M_INIT_3_SET_000E: + /* Set param 0x000e, required for take image */ + vfs_set_param(ssm, VFS_PAR_000E, VFS_VAL_000E); + break; + + case M_INIT_3_SET_0011: + /* Set param 0x0011, required for take image */ + vfs_set_param(ssm, VFS_PAR_0011, VFS_VAL_0011); + break; + + case M_INIT_3_SET_0076: + /* Set param 0x0076, required for use info line */ + vfs_set_param(ssm, VFS_PAR_0076, VFS_VAL_0076); + break; + + case M_INIT_3_SET_0078: + /* Set param 0x0078, required for use info line */ + vfs_set_param(ssm, VFS_PAR_0078, VFS_VAL_0078); + break; + + case M_INIT_3_SET_THRESHOLD: + /* Set threshold */ + vfs_set_param(ssm, VFS_PAR_THRESHOLD, VFS_VAL_THRESHOLD); + break; + + case M_INIT_3_SET_STATE3_COUNT: + /* Set state 3 count */ + vfs_set_param(ssm, VFS_PAR_STATE_3, VFS_VAL_STATE_3); + break; + + case M_INIT_3_SET_STATE5_COUNT: + /* Set state 5 count */ + vfs_set_param(ssm, VFS_PAR_STATE_5, VFS_VAL_STATE_5); + break; + + case M_INIT_3_SET_INFO_CONTRAST: + /* Set info line contrast */ + vfs_set_param(ssm, VFS_PAR_INFO_CONTRAST, 10); + break; + + case M_INIT_3_SET_INFO_RATE: + /* Set info line rate */ + vfs_set_param(ssm, VFS_PAR_INFO_RATE, 32); + break; + + case M_INIT_4_SET_EXPOSURE: + /* Set exposure level of reader */ + vfs_poke(ssm, VFS_REG_IMG_EXPOSURE, 0x4000, 0x02); + vdev->counter = 1; + break; + + case M_INIT_4_SET_CONTRAST: + /* Set contrast level of reader */ + vfs_poke(ssm, VFS_REG_IMG_CONTRAST, vdev->contrast, 0x01); + break; + + case M_INIT_4_GET_PRINT: + /* Get empty image */ + vfs_get_print(ssm, 0x000a, 0); + break; + + case M_INIT_4_LOAD_IMAGE: + /* Load empty image */ + vfs_img_load(ssm); + break; + + case M_INIT_4_CHECK_CONTRAST: + /* Check contrast */ + vfs_check_contrast(vdev); + + if (vdev->contrast <= 6 || vdev->counter >= 12) + { + /* End contrast scan, continue */ + vdev->contrast = vdev->best_contrast; + vdev->counter = 0; + fp_dbg("use contrast value = %d", vdev->contrast); + fpi_ssm_next_state(ssm); + } + else + { + /* Continue contrast scan, loop */ + vdev->contrast--; + vdev->counter++; + fpi_ssm_jump_to_state(ssm, M_INIT_4_SET_CONTRAST); + } + break; + + case M_INIT_5_SET_EXPOSURE: + /* Set exposure level of reader */ + vfs_poke(ssm, VFS_REG_IMG_EXPOSURE, VFS_VAL_IMG_EXPOSURE, 0x02); + break; + + case M_INIT_5_SET_CONTRAST: + /* Set contrast level of reader */ + vfs_poke(ssm, VFS_REG_IMG_CONTRAST, vdev->contrast, 0x01); + break; + + case M_INIT_5_SET_INFO_CONTRAST: + /* Set info line contrast */ + vfs_set_param(ssm, VFS_PAR_INFO_CONTRAST, vdev->contrast); + break; + + case M_INIT_5_SET_INFO_RATE: + /* Set info line rate */ + vfs_set_param(ssm, VFS_PAR_INFO_RATE, VFS_VAL_INFO_RATE); + break; + } +} + +/* Complete init sequential state machine */ +static void m_init_complete(struct fpi_ssm *ssm) +{ + struct fp_img_dev *dev = ssm->priv; + struct vfs101_dev *vdev = dev->priv; + struct fpi_ssm *ssm_loop; + + if (!ssm->error && vdev->active) + { + /* Notify activate complete */ + fpi_imgdev_activate_complete(dev, 0); + + /* Start loop ssm */ + ssm_loop = fpi_ssm_new(dev->dev, m_loop_state, M_LOOP_NUM_STATES); + ssm_loop->priv = dev; + fpi_ssm_start(ssm_loop, m_loop_complete); + } + + /* Free sequential state machine */ + fpi_ssm_free(ssm); +} + +/* Activate device */ +static int dev_activate(struct fp_img_dev *dev, enum fp_imgdev_state state) +{ + struct vfs101_dev *vdev = dev->priv; + struct fpi_ssm *ssm; + + /* Check if already active */ + if (vdev->active) + { + fp_err("device already activated"); + fpi_imgdev_session_error(dev, -EBUSY); + return 1; + } + + /* Set active state */ + vdev->active = TRUE; + + /* Set contrast */ + vdev->contrast = 15; + vdev->best_clevel = -1; + + /* Reset loop counter and enroll stage */ + vdev->counter = 0; + vdev->enroll_stage = 0; + + /* Start init ssm */ + ssm = fpi_ssm_new(dev->dev, m_init_state, M_INIT_NUM_STATES); + ssm->priv = dev; + fpi_ssm_start(ssm, m_init_complete); + + return 0; +} + +/* Deactivate device */ +static void dev_deactivate(struct fp_img_dev *dev) +{ + struct vfs101_dev *vdev = dev->priv; + + /* Reset active state */ + vdev->active = FALSE; + + /* Handle eventualy existing events */ + while (vdev->transfer || vdev->timeout) + fp_handle_events(); + + /* Notify deactivate complete */ + fpi_imgdev_deactivate_complete(dev); +} + +/* Open device */ +static int dev_open(struct fp_img_dev *dev, unsigned long driver_data) +{ + struct vfs101_dev *vdev = NULL; + int r; + + /* Claim usb interface */ + r = libusb_claim_interface(dev->udev, 0); + if (r < 0) + { + /* Interface not claimed, return error */ + fp_err("could not claim interface 0"); + return r; + } + + /* Set enroll stage number */ + dev->dev->nr_enroll_stages = VFS_NR_ENROLL; + + /* Initialize private structure */ + vdev = g_malloc0(sizeof(struct vfs101_dev)); + vdev->seqnum = -1; + dev->priv = vdev; + + /* Notify open complete */ + fpi_imgdev_open_complete(dev, 0); + + return 0; +} + +/* Close device */ +static void dev_close(struct fp_img_dev *dev) +{ + /* Release private structure */ + g_free(dev->priv); + + /* Release usb interface */ + libusb_release_interface(dev->udev, 0); + + /* Notify close complete */ + fpi_imgdev_close_complete(dev); +} + +/* Usb id table of device */ +static const struct usb_id id_table[] = +{ + { .vendor = 0x138a, .product = 0x0001 }, + { 0, 0, 0, }, +}; + +/* Device driver definition */ +struct fp_img_driver vfs101_driver = +{ + /* Driver specification */ + .driver = + { + .id = 10, + .name = FP_COMPONENT, + .full_name = "Validity VFS101", + .id_table = id_table, + .scan_type = FP_SCAN_TYPE_SWIPE, + }, + + /* Image specification */ + .flags = 0, + .img_width = VFS_IMG_WIDTH, + .img_height = -1, + .bz3_threshold = 24, + + /* Routine specification */ + .open = dev_open, + .close = dev_close, + .activate = dev_activate, + .deactivate = dev_deactivate, +}; diff --git a/libfprint/fp_internal.h b/libfprint/fp_internal.h index 4a0441de..e6134d4d 100644 --- a/libfprint/fp_internal.h +++ b/libfprint/fp_internal.h @@ -265,6 +265,9 @@ extern struct fp_img_driver fdu2000_driver; #ifdef ENABLE_VCOM5S extern struct fp_img_driver vcom5s_driver; #endif +#ifdef ENABLE_VFS101 +extern struct fp_img_driver vfs101_driver; +#endif extern libusb_context *fpi_usb_ctx; extern GSList *opened_devices; From 1451a2dde2ca0651ec3e5711ee6278d89f3cc32a Mon Sep 17 00:00:00 2001 From: Bastien Nocera Date: Fri, 8 Apr 2011 15:38:33 +0100 Subject: [PATCH 179/184] build: Quiet by default --- configure.ac | 3 +++ 1 file changed, 3 insertions(+) diff --git a/configure.ac b/configure.ac index e417317d..1fa3f105 100644 --- a/configure.ac +++ b/configure.ac @@ -4,6 +4,9 @@ AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_SRCDIR([libfprint/core.c]) AM_CONFIG_HEADER([config.h]) +# Enable silent build when available (Automake 1.11) +m4_ifdef([AM_SILENT_RULES],[AM_SILENT_RULES([yes])]) + AC_PREREQ([2.50]) AC_PROG_CC AC_PROG_LIBTOOL From f8aa82a554a0862eb9b83869d42dbefbde666543 Mon Sep 17 00:00:00 2001 From: Bastien Nocera Date: Mon, 18 Apr 2011 18:02:37 +0100 Subject: [PATCH 180/184] 0.4.0 --- NEWS | 6 ++++++ configure.ac | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/NEWS b/NEWS index a16c25fb..b8335a4a 100644 --- a/NEWS +++ b/NEWS @@ -1,6 +1,12 @@ This file lists notable changes in each release. For the full history of all changes, see ChangeLog. +2011-04-18: v0.4.0 release + * Add support for Validity VFS101 (USB ID 138a:0001) + * Fix crasher when resizing a fingerprint image + * Fix wrong timeout being returned when either of + libusb or libfprint doesn't have a timeout + 2010-09-08: v0.3.0 release * Add support for UPEK TCS4C (USB ID 147e:1000) * Use NSS instead of OpenSSL for GPL compliance diff --git a/configure.ac b/configure.ac index 1fa3f105..f5c26f90 100644 --- a/configure.ac +++ b/configure.ac @@ -1,4 +1,4 @@ -AC_INIT([libfprint], [0.3.0]) +AC_INIT([libfprint], [0.4.0]) AM_INIT_AUTOMAKE([1.11 dist-bzip2 no-dist-gzip check-news]) AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_SRCDIR([libfprint/core.c]) From 48ec64f68330452b011d14be67653f1d48fb1405 Mon Sep 17 00:00:00 2001 From: Matthew Garrett Date: Tue, 4 Oct 2011 15:11:08 +0100 Subject: [PATCH 181/184] Fix udev control path Newer kernels uses power/control for USB suspend setup, not power/level. Fix the udev rules generation. --- libfprint/fprint-list-udev-rules.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libfprint/fprint-list-udev-rules.c b/libfprint/fprint-list-udev-rules.c index 76a1471c..e474dd79 100644 --- a/libfprint/fprint-list-udev-rules.c +++ b/libfprint/fprint-list-udev-rules.c @@ -52,7 +52,7 @@ static void print_driver (struct fp_driver *driver) if (blacklist) continue; - printf ("SUBSYSTEM==\"usb\", ATTRS{idVendor}==\"%04x\", ATTRS{idProduct}==\"%04x\", ATTRS{dev}==\"*\", ATTR{power/level}=\"auto\"\n", driver->id_table[i].vendor, driver->id_table[i].product); + printf ("SUBSYSTEM==\"usb\", ATTRS{idVendor}==\"%04x\", ATTRS{idProduct}==\"%04x\", ATTRS{dev}==\"*\", ATTR{power/control}=\"auto\"\n", driver->id_table[i].vendor, driver->id_table[i].product); } } From c96fa32da4a3d93950039fdc176571376dafc8cb Mon Sep 17 00:00:00 2001 From: Benedikt Morbach Date: Thu, 5 Jan 2012 21:49:13 +0100 Subject: [PATCH 182/184] Move udev rules to libdir This moves the dir from /etc/udev/rules.d to /lib/udev/rules.d, which is encouraged by upstream, as /etc is for user overrides only https://bugs.freedesktop.org/show_bug.cgi?id=44507 --- libfprint/Makefile.am | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libfprint/Makefile.am b/libfprint/Makefile.am index 95601bce..656a2f43 100644 --- a/libfprint/Makefile.am +++ b/libfprint/Makefile.am @@ -79,7 +79,7 @@ fprint_list_udev_rules_CFLAGS = -fvisibility=hidden -I$(srcdir)/nbis/include $(L fprint_list_udev_rules_LDADD = $(builddir)/libfprint.la udev_rules_DATA = 60-fprint-autosuspend.rules -udev_rulesdir = $(sysconfdir)/udev/rules.d/ +udev_rulesdir = $(libdir)/udev/rules.d/ $(udev_rules_DATA): fprint-list-udev-rules $(builddir)/fprint-list-udev-rules > $@ From 3d2e54526454ed1436b6436dffb0e8769fdbff1d Mon Sep 17 00:00:00 2001 From: Patrick Marlier Date: Wed, 18 Jan 2012 18:52:02 -0500 Subject: [PATCH 183/184] Fix possible crash without a deactivate callback We were checking for ->activate existing instead of ->deactivate. --- libfprint/imgdev.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libfprint/imgdev.c b/libfprint/imgdev.c index b365d74a..14e41ae7 100644 --- a/libfprint/imgdev.c +++ b/libfprint/imgdev.c @@ -370,7 +370,7 @@ static void dev_deactivate(struct fp_img_dev *imgdev) struct fp_driver *drv = imgdev->dev->drv; struct fp_img_driver *imgdrv = fpi_driver_to_img_driver(drv); - if (!imgdrv->activate) + if (!imgdrv->deactivate) return; return imgdrv->deactivate(imgdev); } From dfff16f3e32519ad071bdb1233c75bfe3ffa5557 Mon Sep 17 00:00:00 2001 From: Bastien Nocera Date: Thu, 2 Feb 2012 05:28:17 +0000 Subject: [PATCH 184/184] Don't print duplicate udev rules https://bugs.freedesktop.org/show_bug.cgi?id=45513 --- libfprint/fprint-list-udev-rules.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/libfprint/fprint-list-udev-rules.c b/libfprint/fprint-list-udev-rules.c index e474dd79..182ee107 100644 --- a/libfprint/fprint-list-udev-rules.c +++ b/libfprint/fprint-list-udev-rules.c @@ -37,21 +37,35 @@ struct fp_driver whitelist = { .id_table = whitelist_id_table, }; +GHashTable *printed = NULL; + static void print_driver (struct fp_driver *driver) { int i, j, blacklist; for (i = 0; driver->id_table[i].vendor != 0; i++) { + char *key; + blacklist = 0; for (j = 0; blacklist_id_table[j].vendor != 0; j++) { if (driver->id_table[i].vendor == blacklist_id_table[j].vendor && driver->id_table[j].product == blacklist_id_table[j].product) { blacklist = 1; + break; } } if (blacklist) continue; + key = g_strdup_printf ("%04x:%04x", driver->id_table[i].vendor, driver->id_table[i].product); + + if (g_hash_table_lookup (printed, key) != NULL) { + g_free (key); + continue; + } + + g_hash_table_insert (printed, key, GINT_TO_POINTER (1)); + printf ("SUBSYSTEM==\"usb\", ATTRS{idVendor}==\"%04x\", ATTRS{idProduct}==\"%04x\", ATTRS{dev}==\"*\", ATTR{power/control}=\"auto\"\n", driver->id_table[i].vendor, driver->id_table[i].product); } } @@ -63,11 +77,15 @@ int main (int argc, char **argv) list = fprint_get_drivers (); + printed = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL); + for (i = 0; list[i] != NULL; i++) { print_driver (list[i]); } print_driver (&whitelist); + g_hash_table_destroy (printed); + return 0; }