From 6b363f959f1803e85e2ef6bd61a556e16963e1ac Mon Sep 17 00:00:00 2001 From: Florian Enner Date: Fri, 13 May 2016 17:45:29 -0400 Subject: [PATCH] initial commit --- .gitignore | 13 + CHANGELOG.md | 3 + LICENSE.txt | 572 ++++++++++++++++++ README.md | 51 ++ pom.xml | 182 ++++++ .../hebi/matlab/streaming/BackingHebiCam.java | 302 +++++++++ .../streaming/MatlabImageConverter.java | 126 ++++ .../hebi/matlab/streaming/Preconditions.java | 102 ++++ .../us/hebi/matlab/streaming/Resources.java | 86 +++ .../hebi/matlab/streaming/SharedMemory.java | 106 ++++ src/main/resources/matlab/HebiCam.m | 119 ++++ .../hebi/matlab/streaming/ResourcesTest.java | 49 ++ 12 files changed, 1711 insertions(+) create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 LICENSE.txt create mode 100644 README.md create mode 100644 pom.xml create mode 100644 src/main/java/us/hebi/matlab/streaming/BackingHebiCam.java create mode 100644 src/main/java/us/hebi/matlab/streaming/MatlabImageConverter.java create mode 100644 src/main/java/us/hebi/matlab/streaming/Preconditions.java create mode 100644 src/main/java/us/hebi/matlab/streaming/Resources.java create mode 100644 src/main/java/us/hebi/matlab/streaming/SharedMemory.java create mode 100644 src/main/resources/matlab/HebiCam.m create mode 100644 src/test/java/us/hebi/matlab/streaming/ResourcesTest.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a143d7a --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +/target/ + +# Mac +.DS_Store + +# Eclipse +.classpath +.project +.settings + +# IntelliJ +*.iml +.idea diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..4dde22b --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,3 @@ +### May 13, 2016 +Initial public release + diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..816ec18 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,572 @@ +You may use this work under the terms of either the Apache License, +Version 2.0, or the GNU General Public License (GPL), either version 2, +or any later version, with "Classpath" exception (details below). + +You don't have to do anything special to choose one license or the other +and you don't have to notify anyone which license you are using. You are +free to use this work in any project (even commercial projects) as long +as the copyright header is left intact. + +=============================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================== + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 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. + + 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 Lesser 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 Street, 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 Lesser General +Public License instead of this License. + + +"CLASSPATH" EXCEPTION TO THE GPL + + Linking this library statically or dynamically with other modules is making + a combined work based on this library. Thus, the terms and conditions of + the GNU General Public License cover the whole combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent modules, + and to copy and distribute the resulting executable under terms of your + choice, provided that you also meet, for each linked independent module, + the terms and conditions of the license of that module. An independent + module is a module which is not derived from or based on this library. If + you modify this library, you may extend this exception to your version of + the library, but you are not obligated to do so. If you do not wish to do + so, delete this exception statement from your version. diff --git a/README.md b/README.md new file mode 100644 index 0000000..316709a --- /dev/null +++ b/README.md @@ -0,0 +1,51 @@ +HebiCam +====== + +Introduction +------------ + +HebiCam is a MATLAB class that supports live video acquisition from a variety of sources. It is similar in functionality to MATLAB's [IP Camera](http://se.mathworks.com/hardware-support/ip-camera.html) support package, but provides support for a wider range of formats. HebiCam uses [JavaCV](https://github.com/bytedeco/javacv), and thus supports all formats that are supported by OpenCV and FFMpeg, including h264 and mjpeg streams. USB cameras are supported as well. + +Prerequisites +------------ +HebiCam has been tested on Windows7/8, Ubuntu 14.04, and OSX Yosemite using MATLAB 2014a and 2015a. However, it should work on all MATLAB versions after 2009a. It does not require any particular Tooboxes. + +Sample Usage +------------ +```matlab +%% Connect to a device, e.g., an Axis MJPG stream +url = 'http:///mjpg/video.mjpg?resolution=640x480'; +cam = HebiCam(url); + +%% Live display of continuously acquired frames +figure(); +fig = imshow(getsnapshot(cam)); +while true + set(fig, 'CData', getsnapshot(cam)); + drawnow; +end +``` + +Sample Use Cases +------------ +* [Teleop Taxi](https://youtu.be/zaPtxre4tFc) uses HebiCam to access video from an Android phone. The [IP Webcam](https://play.google.com/store/apps/details?id=com.pas.webcam&hl=en) Android App can be downloaded for free in the Play store. +* [ICRA Demo - 4DOF Arm + Vision](https://youtu.be/R0nQSxt8uic) uses HebiCam to simultaneously access streams of two Axis IP cameras, and MATLAB's computer vision toolbox for 3D stereo vision. The robot trajectories were calculated in the same MATLAB instance. + +How it works +------------ +The computationally intensive nature of video decoding can be a problem for languages like MATLAB, which limit users to a single thread. MATLAB does offer bindings for other languages (e.g. Java) that enable background threading, but getting high-resolution images back into MATLAB can be prohibitively expensive. This project aims to get around this limitation by using Java/C++ to acquire images, and shared memory to get these images into MATLAB. Synchronization of shared memory is achieved via Java locks. + +**Workflow** +* MATLAB creates a Java object, which launches a background thread for video acquisition +* The Java thread uses [JavaCV](https://github.com/bytedeco/javacv), which uses JNI to wrap the C++ bindings for OpenCV and FFMpeg, to establish the connection and continuously acquire images +* Acquired images get converted into MATLAB's column major format +* Converted images are written into shared memory +* MATLAB copies the image from shared memory into a local variable + +This enables accessing high quality (1080p h264) video streams with almost no overhead (<50us) to the main MATLAB thread. However, in practice we usually use 640x480 resolution images for any actual computer vision tasks. + +Installation from Source +------------ +* Setup [Maven](https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html) +* Run `mvn package` +* Copy the resulting *-all*.jar file and all *.m files into a directory on your MATLAB path diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..f1bbab4 --- /dev/null +++ b/pom.xml @@ -0,0 +1,182 @@ + + + + 4.0.0 + + us.hebi.matlab + 1.0-SNAPSHOT + hebicam + + HebiCam + MATLAB utility for streaming video acquisition + + + + Apache License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0 + repo + + + GNU General Public License (GPL) version 2, or any later version + http://www.gnu.org/licenses/ + repo + + + GPLv2 with Classpath exception + http://www.gnu.org/software/classpath/license.html + repo + + + + + + Florian Enner + florian@hebirobotics.com + + + + + https://github.com/HebiRobotics/HebiCam + scm:git:git://github.com/HebiRobotics/HebiCam.git + scm:git:ssh://git@github.com/HebiRobotics/HebiCam.git + + + + + 0.11 + 0.11 + 4.11 + + 2.4.11 + 2.6.1 + + + -x86_64 + + + 1.6 + 1.6 + + + UTF-8 + + + + + + + org.bytedeco + javacv + ${javacv.version} + + + + + org.bytedeco.javacpp-presets + opencv + ${opencv.version}-${javacpp.version} + windows${target.arch} + + + org.bytedeco.javacpp-presets + opencv + ${opencv.version}-${javacpp.version} + macosx${target.arch} + + + org.bytedeco.javacpp-presets + opencv + ${opencv.version}-${javacpp.version} + linux${target.arch} + + + + + org.bytedeco.javacpp-presets + ffmpeg + ${ffmpeg.version}-${javacpp.version} + windows${target.arch} + + + org.bytedeco.javacpp-presets + ffmpeg + ${ffmpeg.version}-${javacpp.version} + macosx${target.arch} + + + org.bytedeco.javacpp-presets + ffmpeg + ${ffmpeg.version}-${javacpp.version} + linux${target.arch} + + + + junit + junit + ${junit.version} + test + + + + + + + + maven-resources-plugin + 2.6 + + + copy-resources + validate + + copy-resources + + + ${basedir}/target/ + + + ${basedir}/src/main/resources/matlab/ + true + + + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.3 + + + package + + shade + + + + + + org.bytedeco.javacpp-presets:flycapture:jar:* + org.bytedeco.javacpp-presets:libdc1394:jar:* + org.bytedeco.javacpp-presets:libfreenect:jar:* + org.bytedeco.javacpp-presets:videoinput:jar:* + org.bytedeco.javacpp-presets:artoolkitplus:jar:* + org.bytedeco.javacpp-presets:flandmark:jar:* + + + + + + + ${project.artifactId}-${project.version}-all${target.arch} + + + + + + + \ No newline at end of file diff --git a/src/main/java/us/hebi/matlab/streaming/BackingHebiCam.java b/src/main/java/us/hebi/matlab/streaming/BackingHebiCam.java new file mode 100644 index 0000000..7b7fc68 --- /dev/null +++ b/src/main/java/us/hebi/matlab/streaming/BackingHebiCam.java @@ -0,0 +1,302 @@ +/* + * Copyright (c) 2015-2016 HEBI Robotics + * + * Licensed either under the Apache License, Version 2.0, or (at your option) + * under the terms of the GNU General Public License as published by + * the Free Software Foundation (subject to the "Classpath" exception), + * either version 2, or any later version (collectively, the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.gnu.org/licenses/ + * http://www.gnu.org/software/classpath/license.html + * + * or as provided in the LICENSE.txt file that accompanied this code. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package us.hebi.matlab.streaming; + +import org.bytedeco.javacpp.avutil; +import org.bytedeco.javacv.FFmpegFrameGrabber; +import org.bytedeco.javacv.Frame; +import org.bytedeco.javacv.FrameGrabber; +import org.bytedeco.javacv.OpenCVFrameGrabber; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.URI; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +import static java.util.concurrent.TimeUnit.SECONDS; +import static us.hebi.matlab.streaming.Preconditions.*; +import static us.hebi.matlab.streaming.Resources.*; + +/** + * Backing Java class for MATLAB's VideoInput-like functionality + * + * @author Florian Enner < florian @ hebirobotics.com > + * @since 01 May 2015 + */ +public class BackingHebiCam { + + public static BackingHebiCam open(Object object) throws Exception { + + if (object instanceof Number) { + + // Numbered local device + int matlabIndex = ((Number) object).intValue(); + checkArgument(matlabIndex > 0, "Device can't be below 1"); + int device = matlabIndex - 1; // convert MATLAB (one based) index to Java index (zero based) + final FrameGrabber grabber = new OpenCVFrameGrabber(device); + return new BackingHebiCam(grabber); + + } else if (object instanceof String) { + String device = (String) object; + + // Remote URLs + if (Resources.isRemoteUri(device)) { + return openRemoteUri(new URI(device)); + } + + // Named local device + final FrameGrabber grabber = new OpenCVFrameGrabber(device); + return new BackingHebiCam(grabber); + + } + + throw new IllegalArgumentException("Expected device number, path, or remote URL"); + + } + + private static BackingHebiCam openRemoteUri(URI uri) throws IOException, FrameGrabber.Exception { + InetAddress device = InetAddress.getByName(checkNotNull(uri).getHost()); + checkNotNull(device, "No ip address found"); + + // Check whether the address is reachable (ICMP ping) to avoid an infinite wait (bug?) when + // connecting to ip cameras that are not on the network. + int timeoutMs = 5000; + if (!device.isReachable(timeoutMs)) { + throw new IllegalArgumentException("Could not ping camera on address " + device + ". " + + "Please confirm that the address is correct and that the device is turned on."); + } + + // Use FFmpeg for streaming + final FrameGrabber grabber = new FFmpegFrameGrabber(uri.toString()); + + // Assume that http:// urls are mjpeg streams to avoid errors. This has been true for all ip cameras + // that I've tested (other encodings were rtsp://), but there may needs to be another flag to support + // some more exotic cameras. + if ("http".equalsIgnoreCase(uri.getScheme())) + grabber.setFormat("mjpeg"); + return new BackingHebiCam(grabber); + } + + public int getHeight() { + return grabber.getImageHeight(); + } + + public int getWidth() { + return grabber.getImageWidth(); + } + + public int getChannels() { + switch (grabber.getImageMode()) { + case COLOR: + return 3; + case GRAY: + return 1; + default: + throw new IllegalStateException("Unknown image mode"); + } + } + + public String getBackingFile() { + return sharedMemory.getBackingFile().getPath(); + } + + /** + * @return true if the shared memory has been updated and the memory lock has been acquired. False if + * the lock has not been acquired. + */ + public boolean tryGetNextImageLock() { + // Make sure users don't have the lock already (e.g. ctrl-c in MATLAB while reading the data) + tryReleaseImageLock(); + + // Immediately return if acquisition is not active + if (!active) return false; + + // Try locking immediately in case the image has already updated + if (tryLockUpdatedImage()) { + return true; + } + + // Wait for arrival notification or time out + synchronized (arrivalNotification) { + try { + arrivalNotification.wait(DEFAULT_ACQUISITION_TIMEOUT_MS); + } catch (InterruptedException e) { + } + } + + // Try a final time + return tryLockUpdatedImage(); + + } + + /** + * @return true if the image has updated and the lock has been acquired. + */ + private boolean tryLockUpdatedImage() { + if (hasUpdated) { + memoryAccessLock.lock(); + userHasLock = true; + hasUpdated = false; + return true; + } + return false; + } + + /** + * @return true if the user had the lock and it has been successfully released + */ + public void tryReleaseImageLock() { + if (userHasLock) { + userHasLock = false; + memoryAccessLock.unlock(); + } + } + + public void start() { + checkState(active, "VideoInput must not have been stopped yet"); + Thread thread = new Thread(acquisitionLoop); + thread.setDaemon(true); + thread.setName("VideoInput-" + threadCounter.getAndIncrement()); + thread.start(); + } + + public void stop() throws FrameGrabber.Exception { + // Return immediately if acquisition has already + // stopped, e.g., on multiple calls to stop(). + if (!active) return; + active = false; + + // Make sure that the lock is released. Note that in MATLAB this will always happen in the + // same thread as the lock acquisition, so there can't be user-race conditions here + tryReleaseImageLock(); + + // Close shared memory + memoryAccessLock.lock(); + try { + closeSilently(sharedMemory); + } finally { + memoryAccessLock.unlock(); + } + + // Close grabber + synchronized (grabber) { + grabber.stop(); + } + + } + + private void runAcquisitionLoop() throws FrameGrabber.Exception, IOException, InterruptedException { + checkState(active, "VideoInput must be active"); + + while (active) { + + // Read next image from device + Frame frame = null; + synchronized (grabber) { + frame = grabber.grabFrame(); + } + + // Retry grabbing frames after a timeout. Note that disconnecting IP cameras + // shows up as null frames, and not a FrameGrabber Exception. If a connection + // is legitimately disconnected, the MATLAB script should stop the acquisition. + if (frame == null) { + int retryTimeoutMs = 100; + Thread.sleep(retryTimeoutMs); + continue; + } + + // Acquire lock - note that we time out after a reasonable time in order to avoid deadlocks + // if users don't release locks properly. + boolean hasLock = memoryAccessLock.tryLock(1, SECONDS); + if (!hasLock) + continue; + + try { + // Make sure memory is active and update + if (!sharedMemory.isOpen()) + return; + + // Write to memory in column major (MATLAB) format + rgbConverter.convertFrameInto(frame, sharedMemory.clearBuffer()); + } finally { + memoryAccessLock.unlock(); + } + + // Notify listeners that the data has updated + hasUpdated = true; + synchronized (arrivalNotification) { + arrivalNotification.notifyAll(); + } + + } + + } + + private final Runnable acquisitionLoop = new Runnable() { + @Override + public void run() { + try { + runAcquisitionLoop(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + }; + + private BackingHebiCam(FrameGrabber grabber) throws FrameGrabber.Exception, IOException { + this.grabber = checkNotNull(grabber); + + // Set a timeout in case a camera gets disconnected or shutdown. Note that this only works + // for grabFrame() and not start() + grabber.setTimeout(DEFAULT_ACQUISITION_TIMEOUT_MS); + + // Disable repeated log lines such as errors and warnings + avutil.av_log_set_level(avutil.AV_LOG_SKIP_REPEATED); + + // Grab first frame to initialize converter and shared memory with correct dimensions + grabber.start(); + Frame frame = grabber.grabFrame(); + checkArgument(getChannels() == 3, "Currently only RGB images are supported"); + rgbConverter = MatlabImageConverter.createRgbConverter(frame.imageWidth, frame.imageHeight); + sharedMemory = SharedMemory.allocate(frame.imageWidth * frame.imageHeight * 3); + + } + + // Setup + final FrameGrabber grabber; + final MatlabImageConverter rgbConverter; + final SharedMemory sharedMemory; + final Lock memoryAccessLock = new ReentrantLock(); + final static int DEFAULT_ACQUISITION_TIMEOUT_MS = 1000; + + // State + final Object arrivalNotification = new Object(); + volatile boolean hasUpdated = false; + volatile boolean active = true; + volatile boolean userHasLock = false; + + private static final AtomicInteger threadCounter = new AtomicInteger(0); + +} diff --git a/src/main/java/us/hebi/matlab/streaming/MatlabImageConverter.java b/src/main/java/us/hebi/matlab/streaming/MatlabImageConverter.java new file mode 100644 index 0000000..c2bdd13 --- /dev/null +++ b/src/main/java/us/hebi/matlab/streaming/MatlabImageConverter.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2015-2016 HEBI Robotics + * + * Licensed either under the Apache License, Version 2.0, or (at your option) + * under the terms of the GNU General Public License as published by + * the Free Software Foundation (subject to the "Classpath" exception), + * either version 2, or any later version (collectively, the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.gnu.org/licenses/ + * http://www.gnu.org/software/classpath/license.html + * + * or as provided in the LICENSE.txt file that accompanied this code. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package us.hebi.matlab.streaming; + +import org.bytedeco.javacpp.opencv_core.*; +import org.bytedeco.javacv.Frame; +import org.bytedeco.javacv.OpenCVFrameConverter; + +import java.nio.ByteBuffer; + +import static org.bytedeco.javacpp.opencv_core.*; +import static us.hebi.matlab.streaming.Preconditions.*; + +/** + * Utility classes that convert Frames into MATLAB's column-major format + * + * @author Florian Enner < florian @ hebirobotics.com > + * @since 01 May 2015 + */ +public abstract class MatlabImageConverter { + + public static MatlabImageConverter createRgbConverter(int width, int height) { + return new RgbConverter(width, height); + } + + private static class RgbConverter extends MatlabImageConverter { + + @Override + public void convertMatInto(final Mat source, final ByteBuffer destination) { + checkNotNull(destination); + checkArgument(source != null + && source.rows() == height + && source.cols() == width + && source.channels() == 3, "bad dimensions"); + + // Split into individual colors and and transpose each channel to + // get Matlab-like column major format + split(source, bgr); + transpose(bgr.get(2), rgbTransposed.get(0)); + transpose(bgr.get(1), rgbTransposed.get(1)); + transpose(bgr.get(0), rgbTransposed.get(2)); + + // Write to dest buffer + r.position(0); + g.position(0); + b.position(0); + destination.put(r).put(g).put(b); + + } + + RgbConverter(int width, int height) { + // Initialize all pointers with dummy data + this.width = width; + this.height = height; + Mat mat = new Mat(height, width, CV_8UC3); + + // Convert + split(mat, bgr); + transpose(bgr.get(2), rgbTransposed.get(0)); + transpose(bgr.get(1), rgbTransposed.get(1)); + transpose(bgr.get(0), rgbTransposed.get(2)); + + // Create buffers + r = rgbTransposed.get(0).createBuffer(); + g = rgbTransposed.get(1).createBuffer(); + b = rgbTransposed.get(2).createBuffer(); + + // Cleanup + mat.release(); + } + + // Vectors will be released automatically by the garbage collector + final MatVector bgr = new MatVector(3); + final MatVector rgbTransposed = new MatVector(3); + + final ByteBuffer r; + final ByteBuffer g; + final ByteBuffer b; + + final int width; + final int height; + + } + + public abstract void convertMatInto(Mat mat, ByteBuffer destination); + + public void convertFrameInto(Frame source, ByteBuffer destination) { + checkNotNull(source); + checkNotNull(destination); + + // Convert to OpenCV format + Mat mat = null; + try { + mat = frameConverter.convertToMat(source); + convertMatInto(mat, destination); + } finally { + if (mat != null) { + mat.release(); + } + } + + } + + final OpenCVFrameConverter frameConverter = new OpenCVFrameConverter.ToMat(); + +} diff --git a/src/main/java/us/hebi/matlab/streaming/Preconditions.java b/src/main/java/us/hebi/matlab/streaming/Preconditions.java new file mode 100644 index 0000000..88146d0 --- /dev/null +++ b/src/main/java/us/hebi/matlab/streaming/Preconditions.java @@ -0,0 +1,102 @@ +package us.hebi.matlab.streaming; + +/** + * Static convenience methods that help with runtime checks. Copied + * from Google's Guava library. + * + * https://github.com/google/guava/wiki/PreconditionsExplained + * + * @author Florian Enner < florian @ hebirobotics.com > + * @since 01 May 2015 + */ +class Preconditions { + + /** + * Ensures the truth of an expression involving one or more parameters to the calling method. + * + * @param expression a boolean expression + * @throws IllegalArgumentException if {@code expression} is false + */ + public static void checkArgument(boolean expression) { + if (!expression) { + throw new IllegalArgumentException(); + } + } + + /** + * Ensures the truth of an expression involving one or more parameters to the calling method. + * + * @param expression a boolean expression + * @param errorMessage the exception message to use if the check fails; will be converted to a + * string using {@link String#valueOf(Object)} + * @throws IllegalArgumentException if {@code expression} is false + */ + public static void checkArgument(boolean expression, Object errorMessage) { + if (!expression) { + throw new IllegalArgumentException(String.valueOf(errorMessage)); + } + } + + /** + * Ensures the truth of an expression involving the state of the calling instance, but not + * involving any parameters to the calling method. + * + * @param expression a boolean expression + * @throws IllegalStateException if {@code expression} is false + */ + public static void checkState(boolean expression) { + if (!expression) { + throw new IllegalStateException(); + } + } + + /** + * Ensures the truth of an expression involving the state of the calling instance, but not + * involving any parameters to the calling method. + * + * @param expression a boolean expression + * @param errorMessage the exception message to use if the check fails; will be converted to a + * string using {@link String#valueOf(Object)} + * @throws IllegalStateException if {@code expression} is false + */ + public static void checkState(boolean expression, Object errorMessage) { + if (!expression) { + throw new IllegalStateException(String.valueOf(errorMessage)); + } + } + + /** + * Ensures that an object reference passed as a parameter to the calling method is not null. + * + * @param reference an object reference + * @return the non-null reference that was validated + * @throws NullPointerException if {@code reference} is null + */ + public static T checkNotNull(T reference) { + if (reference == null) { + throw new NullPointerException(); + } + return reference; + } + + /** + * Ensures that an object reference passed as a parameter to the calling method is not null. + * + * @param reference an object reference + * @param errorMessage the exception message to use if the check fails; will be converted to a + * string using {@link String#valueOf(Object)} + * @return the non-null reference that was validated + * @throws NullPointerException if {@code reference} is null + */ + public static T checkNotNull(T reference, Object errorMessage) { + if (reference == null) { + throw new NullPointerException(String.valueOf(errorMessage)); + } + return reference; + } + + + private Preconditions(){ + } + +} diff --git a/src/main/java/us/hebi/matlab/streaming/Resources.java b/src/main/java/us/hebi/matlab/streaming/Resources.java new file mode 100644 index 0000000..c22e22d --- /dev/null +++ b/src/main/java/us/hebi/matlab/streaming/Resources.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2015-2016 HEBI Robotics + * + * Licensed either under the Apache License, Version 2.0, or (at your option) + * under the terms of the GNU General Public License as published by + * the Free Software Foundation (subject to the "Classpath" exception), + * either version 2, or any later version (collectively, the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.gnu.org/licenses/ + * http://www.gnu.org/software/classpath/license.html + * + * or as provided in the LICENSE.txt file that accompanied this code. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package us.hebi.matlab.streaming; + +import java.io.Closeable; +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.ByteBuffer; + +import static us.hebi.matlab.streaming.Preconditions.checkNotNull; + +/** + * @author Florian Enner < florian @ hebirobotics.com > + * @since 01 May 2015 + */ +public class Resources { + + public static void closeSilently(Closeable resource) { + if (resource != null) { + try { + resource.close(); + } catch (IOException e) { + // Ignore + } + } + } + + private Resources() { + + } + + /** + * source: http://stackoverflow.com/a/19447758/3574093 + * + * @param cb + */ + public static void closeDirectBuffer(final ByteBuffer cb) { + checkNotNull(cb); + if (!cb.isDirect()) return; + + // we could use this type cast and call functions without reflection code, + // but static import from sun.* package is risky for non-SUN virtual machine. + //try { ((sun.nio.ch.DirectBuffer)cb).cleaner().clean(); } catch (Exception ex) { } + try { + Method cleaner = cb.getClass().getMethod("cleaner"); + cleaner.setAccessible(true); + Method clean = Class.forName("sun.misc.Cleaner").getMethod("clean"); + clean.setAccessible(true); + clean.invoke(cleaner.invoke(cb)); + } catch (Exception ex) { + throw new AssertionError(ex); + } + } + + public static boolean isRemoteUri(String uri) { + try { + return new URI(uri).getHost() != null; + } catch (URISyntaxException e) { + return false; + } + } + + +} diff --git a/src/main/java/us/hebi/matlab/streaming/SharedMemory.java b/src/main/java/us/hebi/matlab/streaming/SharedMemory.java new file mode 100644 index 0000000..f75bbb2 --- /dev/null +++ b/src/main/java/us/hebi/matlab/streaming/SharedMemory.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2015-2016 HEBI Robotics + * + * Licensed either under the Apache License, Version 2.0, or (at your option) + * under the terms of the GNU General Public License as published by + * the Free Software Foundation (subject to the "Classpath" exception), + * either version 2, or any later version (collectively, the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.gnu.org/licenses/ + * http://www.gnu.org/software/classpath/license.html + * + * or as provided in the LICENSE.txt file that accompanied this code. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package us.hebi.matlab.streaming; + +import java.io.Closeable; +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.text.SimpleDateFormat; +import java.util.Date; + +import static us.hebi.matlab.streaming.Preconditions.*; +import static us.hebi.matlab.streaming.Resources.*; + +/** + * Allocates memory that can be accessed from other processes. Instantiated objects are + * not thread safe. The byte order of the backing buffer is the native order. + * + * @author Florian Enner < florian @ hebirobotics.com > + * @since 02 May 2015 + */ +public class SharedMemory implements Closeable { + + public static SharedMemory allocate(int numBytes) { + return new SharedMemory(numBytes); + } + + public ByteBuffer clearBuffer() { + return (ByteBuffer) buffer.clear(); + } + + @Override + public void close() throws IOException { + closeDirectBuffer(buffer); + closeSilently(channel); + if (!backingFile.delete()) { + backingFile.deleteOnExit(); + throw new IOException("Could not delete the backing file. Are other processes still mapping it?"); + } + } + + public File getBackingFile() { + return backingFile; + } + + public boolean isOpen() { + return channel.isOpen(); + } + + private SharedMemory(int numBytes) { + checkArgument(numBytes > 0, "Allocation must be greater than zero bytes"); + + // Create uniquely named file + backingFile = new File("shared_" + dateFormat.get().format(new Date()) + ".tmp"); + checkState(!backingFile.exists(), "Generated unique name already exists"); + + // Load shared memory + try { + channel = new RandomAccessFile(backingFile, "rw") + .getChannel(); + buffer = channel + .map(FileChannel.MapMode.READ_WRITE, 0, numBytes) + .load(); + buffer.order(ByteOrder.nativeOrder()); + } catch (IOException e) { + throw new RuntimeException(e); + } + + } + + final File backingFile; + final FileChannel channel; + final MappedByteBuffer buffer; + + private static final ThreadLocal dateFormat = new ThreadLocal() { + @Override + protected SimpleDateFormat initialValue() { + return new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss.SSS"); + } + }; + +} diff --git a/src/main/resources/matlab/HebiCam.m b/src/main/resources/matlab/HebiCam.m new file mode 100644 index 0000000..768f00d --- /dev/null +++ b/src/main/resources/matlab/HebiCam.m @@ -0,0 +1,119 @@ +classdef HebiCam < handle + % HebiCam acquires frames from streaming video sources + % cam = HebiCam(uri) returns an object that acquires images + % from the specified URI. The URI can be the URL of an IP camera, the + % the location of a local device (e.g. '/dev/video0'), or the number + % of a local device (e.g. 1). + % + % Possible sources are limited to devices that are supported by + % FFMpeg or OpenCV. + % + % Note that the underlying Java implementation currently only + % supports RGB images. + % + % HebiCam Properties: + % url - video source, e.g., local device or remote ip camera + % width - width of the gathered image + % height - height of the gathered image + % channels - channel, e.g., rgb or grayscale + % + % HebiCam Methods: + % getsnapshot - acquires a single image frame + % + % Example: + % % Connect to a device, e.g., an Axis MJPG stream + % url = 'http:///mjpg/video.mjpg?resolution=640x480'; + % cam = HebiCam(url); + % + % % Live display of continuously acquired frames + % figure(); + % fig = imshow(getsnapshot(cam)); + % while true + % set(fig, 'CData', getsnapshot(cam)); + % drawnow; + % end + + % Copyright (c) 2015-2016 HEBI Robotics + + properties (SetAccess = private, GetAccess = public) + url % video source, e.g., local device or remote ip camera + width % width of the gathered image + height % height of the gathered image + channels % channel, e.g., rgb vs grayscale) + end + + properties (Access = private) + file + cam + end + + methods (Static, Access = private) + function load_resources() + % Loads the backing Java files and native binaries. This + % method assumes that the jar file is located in the same + % directory as this class-script, and that the file name + % matches the string below. + jarFileName = 'hebicam-1.0-SNAPSHOT-all-x86_64.jar'; + + % Load only once + if ~exist('us.hebi.matlab.streaming.BackingHebiCam','class') + javaaddpath(... + fullfile(fileparts(mfilename('fullpath')), jarFileName)); + end + end + end + + methods (Access = public) + + function this = HebiCam(url) + % constructor - connects to the video source + this.url = url; + HebiCam.load_resources(); + this.cam = us.hebi.matlab.streaming.BackingHebiCam.open(url); + + % Get image data and shared memory location + this.height = this.cam.getHeight(); + this.width = this.cam.getWidth(); + this.channels = this.cam.getChannels(); + path = char(this.cam.getBackingFile()); + + % Somehow HxWx1 does not work, so the mapping of + % greyscale images needs to be special cased. + if(this.channels == 1) + % greyscale + this.file = memmapfile(path, 'Format', ... + {'uint8' [this.height this.width] 'pixels';}); + else + % color image + this.file = memmapfile(path, 'Format', ... + {'uint8' [this.height this.width this.channels] 'pixels';}); + end + + % start retrieval + start(this.cam); + end + + function I = getsnapshot(this) + %getsnapshot - acquires a single image frame + hasImage = tryGetNextImageLock(this.cam); + if hasImage + % Mapped memory is accessed by reference, so the data + % needs to be copied manually. + I = this.file.Data.pixels * 1; + tryReleaseImageLock(this.cam); + else + stop(this.cam); + error('Connection to video source was lost. Acquisition stopped.'); + end + end + + end + + methods (Access = private) + function delete(this) + % destructor - frees resources + this.file = []; + stop(this.cam); + end + end +end \ No newline at end of file diff --git a/src/test/java/us/hebi/matlab/streaming/ResourcesTest.java b/src/test/java/us/hebi/matlab/streaming/ResourcesTest.java new file mode 100644 index 0000000..da1ff1c --- /dev/null +++ b/src/test/java/us/hebi/matlab/streaming/ResourcesTest.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2015-2016 HEBI Robotics + * + * Licensed either under the Apache License, Version 2.0, or (at your option) + * under the terms of the GNU General Public License as published by + * the Free Software Foundation (subject to the "Classpath" exception), + * either version 2, or any later version (collectively, the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.gnu.org/licenses/ + * http://www.gnu.org/software/classpath/license.html + * + * or as provided in the LICENSE.txt file that accompanied this code. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package us.hebi.matlab.streaming; + +import org.junit.Test; + +import static org.junit.Assert.*; +import static us.hebi.matlab.streaming.Resources.isRemoteUri; + +/** + * @author Florian Enner < florian @ hebirobotics.com > + * @since 02 May 2015 + */ +public class ResourcesTest { + + @Test + public void testIsValidUrl() throws Exception { + assertTrue(isRemoteUri("http://127.0.0.1:80/axis-cgi/mjpg/video.cgi")); // Axis mjpeg + assertTrue(isRemoteUri("rtsp://127.0.0.2/axis-media/media.amp")); // Axis h264 + assertTrue(isRemoteUri("rtsp://127.0.0.3/media/video1")); // Sony camera + assertTrue(isRemoteUri("rtsp://127.0.0.4:554/live/ch00_0")); // Some other ip cam + + assertFalse(isRemoteUri("/home/user/name/myFile.avi")); // Linux file + assertFalse(isRemoteUri("/dev/video0")); // Linux device + assertFalse(isRemoteUri("C:/myFile.avi")); // Windows file + + } + +} \ No newline at end of file