commit 1a90ed76f3983f582403e5bb468a071f9ccb8e21 Author: Michal Fratczak Date: Fri Nov 2 16:06:08 2018 +0100 Init diff --git a/BuildInstructions.md b/BuildInstructions.md new file mode 100644 index 0000000..951ca86 --- /dev/null +++ b/BuildInstructions.md @@ -0,0 +1,117 @@ +# Building HABDEC from source + +To build habdec from source code, you need to build it's dependecies first: +- FFTW +- boost 1.68 +- CMake version 3.8.2 +- optionally: FLTK + +Below are instructions how to obtain and compile each package. Keep in mind, these are WIP and some adjustment to your build env may be needed. + +For windows, you need to start 64bit build env, ie: `C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars64.bat` + +## CMake + +#### Windows +Just download and install binaries from https://cmake.org/download/ + +#### Linux + wget https://cmake.org/files/v3.12/cmake-3.12.3.tar.gz + tar -xf ./cmake-3.12.3.tar.gz + cd cmake-3.12.3 + ./configure --prefix=`pwd`/install + make -j4 + sudo make install + export PATH=$PATH:`pwd`/install + + +## boost 1.68 + +#### Linux + wget https://dl.bintray.com/boostorg/release/1.68.0/source/boost_1_68_0.tar.gz + tar -xf ./boost_1_68_0.tar.gz + cd boost_1_68_0 + ./bootstrap.sh + ./b2 -j 4 --layout=tagged --build-type=complete stage + +#### Windows +Download from https://www.boost.org/users/download/ and unpack. + + cd boost + bootstrap.bat + b2.exe --layout=tagged --build-type=complete --build-dir=build/static toolset=msvc address-model=64 link=static stage + + +## FFTW +You need to build FFTW with float (single precission) support. Also, enable neon optimizations for ARM. + +#### Linux x86 + wget http://fftw.org/fftw-3.3.8.tar.gz + tar -xf ./fftw-3.3.8.tar.gz + cd fftw-3.3.8 + ./configure --with-slow-timer --enable-single CFLAGS="-O4 -pipe -march=native -Wall" --prefix=`pwd`/install + make + make install + +#### Linux ARM + wget http://fftw.org/fftw-3.3.8.tar.gz + tar -xf ./fftw-3.3.8.tar.gz + cd fftw-3.3.8 + ./configure --with-slow-timer --enable-single --enable-neon CFLAGS="-O4 -pipe -march=native -mfpu=neon -Wall" --prefix=`pwd`/install + make + make install + +#### Windows +Download http://fftw.org/fftw-3.3.8.tar.gz and unpack. + + cmake -D BUILD_SHARED_LIBS=0 -D ENABLE_FLOAT=1 -D CMAKE_INSTALL_PREFIX=d:\dev\c_libs\fftw\3.3.8\install -D CMAKE_BUILD_TYPE=RELEASE -G "NMake Makefiles" ..\src + nmake + nmake install + + +## SoapySDR + +#### Windows +Just go and install binaries from https://github.com/pothosware/PothosCore/wiki/Downloads + +#### Linux + + git clone https://github.com/pothosware/SoapySDR.git + cd SoapySDR + git pull origin master + + mkdir build + cd build + cmake .. + make -j + sudo make install + sudo ldconfig + SoapySDRUtil --info + +### SoapySDR AirSpy Support + + git clone https://github.com/pothosware/SoapyAirspy.git + mkdir build + cd build + cmake ../SoapySDR + make + sudo make install + sudo ldconfig + +### SoapySDR RTL-SDR Support +Refer to https://github.com/pothosware/SoapyRTLSDR + + +## HABDEC Build + +If you managed to build or install dependencies, you're ready do build habdec + + git clone habdec + cd habdec + mkdir build + cd build + cmake cmake -D BOOST_ROOT=/path/to/boost_1.68 -D FFTW_ROOT=/path/to/fftwf/install ../code + make + make install + +You should end up with `install` dir that contains executable and a shell script that runs in loop (for cases where habdec should crash and you wan't continous run). \ No newline at end of file diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. 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 +them 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 prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. 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. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey 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; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If 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 convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + 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. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +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. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + 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 +state 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 3 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, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program 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, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU 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. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..c01cbe5 --- /dev/null +++ b/README.md @@ -0,0 +1,175 @@ +# HABDEC - RTTY decoder for High Altitude Balloons + +![alt text](./webClientScreenshot.png) + +Habdec is a C++11 software to decode RTTY telemetry from High Altitude Balloon and upload it to [UKHAS Habitat](http://habitat.habhub.org/) + +Some facts: +- builds and runs on Windows/Linux and x64/RaspberryPI/OdroixXU4 platforms +- Uses [SoapySDR](https://github.com/pothosware/SoapySDR) to consume IQ stream from your SDR +- runs in command line (headless) +- provides websocket server so can be cotrolled from any web browser [even on your phone](https://www.youtube.com/watch?v=dli8FEFy5tM) +- can be easily integrated into your own code + +Original motivation for habdec was to have a portable tracking device you could take to a chasecar or into a field. + +Fatty laptop with dl-fldigi, full-fledged SDR app and required internet connection is not too comfortable. + +Ultimatelly habdec is intended for integration into bigger app, probably based on OpenStreetmap and running on portable RaspberryPI or OdroidXU4. Right now you can run it on headless board and cotrol from your mobile. + +## Getting habdec + +To get habdec you can download precompiled exec or build it from source. + +#### Getting Binary: +- Install SoapySDR binaries from [here](https://github.com/pothosware/SoapySDR/wiki#installation) +- Download habdec executable for your platform from [here](missing link) + +#### Building from source: +To build habdec you need a C++11 compiler and CMake version 3.8.2 +You also need to build or install some dependencies: +- basic decoder: [FFTW](http://www.fftw.org/) +- websocket server: [SoapySDR](https://github.com/pothosware/SoapySDR), [boost 1.68](https://www.boost.org/) + +Instructions how to build habdec and it's dependencies are described in [BuildInstructions.md](./BuildInstructions.md) + +## Usage + +`habdecWebsocketServer.exe --help` +``` +Command Line Interface options: + --config arg (=./habdecWebsocketServer.opts) + Last run config file. Autosaved on + every successfull decode. + +CLI opts: + --help Display help message + --device arg (=-1) SDR Device Numer + --sampling_rate arg (=0) Sampling Rate, as supported by device + --port arg (=5555) Command Port, example: --port + 127.0.0.1:5555 + --station arg (=habdec) HABHUB station callsign + --freq arg frequency in MHz + --gain arg gain + --print arg live print received chars + --rtty arg rtty: baud bits stops, example -rtty + 300 8 2 + --biast arg biasT + --bias_t arg biasT + --afc arg Auto Frequency Correction +``` + +The only mandatory parameter is --sampling_rate. Provide value that is supported by your SDR device. + +### Examples: +Print available devices + +``` +habdecWebsocketServer.exe --device -1 + + +Reading config from file ./habdecWebsocketServer.opts +Current options: + device: -1 + sampling_rate: 2.048e+06 + command_host: 0.0.0.0 + command_port: 5,555 + station: habdec + freq: 4.3435e+08 + gain: 15 + live_print: 1 + baud: 300 + rtty_ascii_bits: 8 + rtty_ascii_stops: 2 + biast: 0 +ERROR: Unable to find host: Nieznany host. +Found Rafael Micro R820T tuner +[INFO] [UHD] Win32; Microsoft Visual C++ version 14.0; Boost_106700; UHD_3.13.0.2-1-g78745bda + +Available devices: +0: + device_id 0 + driver airspy + label AIRSPY [440464c8:39627b4f] + serial 440464c8:39627b4f + Sampling Rates: + 2.5e+06 + 1e+07 + +1: + available Yes + driver rtlsdr + label Generic RTL2832U OEM :: 00000001 + manufacturer Realtek + product RTL2838UHIDIR + rtl 0 + serial 00000001 + tuner Rafael Micro R820T +Found Rafael Micro R820T tuner + Sampling Rates: + 250,000 + 1.024e+06 + 1.536e+06 + 1.792e+06 + 1.92e+06 + 2.048e+06 + 2.16e+06 + 2.56e+06 + 2.88e+06 + 3.2e+06 + + +No SDR device specified. Select one by specifying it's NUMBER +Failed Device Setup. EXIT. + +``` + +Run with AirSpy + + habdecWebsocketServer.exe --device 0 --sampling_rate 2.5e6 + +Specify websocket address and port + + habdecWebsocketServer.exe --device 0 --sampling_rate 2.5e6 -port 12.13.14.15:5555 + +Some more options +``` +habdecWebsocketServer.exe --device 0 --sampling_rate 2.5e6 + --port 12.13.14.15:5555 --station Fred + --rtty 300 8 2 + --print 1 + --freq 434.5 --gain 20 --biast 1 --afc 1 +``` + + +### Web Client + +To control habdec parameters from your browser, start `webClient/index.html` and connect to ip:port + + +## Known Limitations + +- RTTY Modes **NOT** supported: 5bit baudot, 1.5 bit stop +- SSTV is not supported +- Decoding will stop if decimation setting is too low or too high. It was tested to work with stream around 40kHz bandwidth. +- Automatic Frequency Correction needs more work. Use consciously. +- Connecting from browser is not very reliable yet, sometimes you need to refresh and wait. +- Currently, upload to HABHUB is realized with python habLogger.py which is called with system(). This will get ported to C++. +- habdec was developed and tested with [AirSpy](https://airspy.com/) and [OdroidXU4](http://hardkernel.com/). Support for windows and RtlSdr is less tested. + + +## Reporting Problems + +Use bugtracker, please. + +## Contributions + +Gladly accepted :) + +## Authors + +* **Michał Frątczak** - *parts of code from* - [GQRX](https://github.com/csete/gqrx) + +## License + +This project is licensed under the GNU General Public License diff --git a/code/CMake/FFTW3fConfig.cmake b/code/CMake/FFTW3fConfig.cmake new file mode 100755 index 0000000..b9c397a --- /dev/null +++ b/code/CMake/FFTW3fConfig.cmake @@ -0,0 +1,17 @@ + +# defined since 2.8.3 +if (CMAKE_VERSION VERSION_LESS 2.8.3) + get_filename_component (CMAKE_CURRENT_LIST_DIR ${CMAKE_CURRENT_LIST_FILE} PATH) +endif () + +# Allows loading FFTW3 settings from another project +set (FFTW3_CONFIG_FILE "${CMAKE_CURRENT_LIST_FILE}") + +# set (FFTW3f_LIBRARIES fftw3f.a ) +FIND_LIBRARY( FFTW3f_LIBRARIES NAMES fftw3f.a fftw3f PATHS ${FFTW_ROOT}/lib NO_DEFAULT_PATH ) +set (FFTW3f_LIBRARY_DIRS ${FFTW_ROOT}/lib) +set (FFTW3f_INCLUDE_DIRS ${FFTW_ROOT}/include) + +if (CMAKE_VERSION VERSION_LESS 2.8.3) + set (CMAKE_CURRENT_LIST_DIR) +endif () diff --git a/code/CMake/FFTW3fConfigVersion.cmake b/code/CMake/FFTW3fConfigVersion.cmake new file mode 100644 index 0000000..e750f80 --- /dev/null +++ b/code/CMake/FFTW3fConfigVersion.cmake @@ -0,0 +1,12 @@ + +set (PACKAGE_VERSION "3.3.7") + +# Check whether the requested PACKAGE_FIND_VERSION is compatible +if ("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}") + set (PACKAGE_VERSION_COMPATIBLE FALSE) +else () + set (PACKAGE_VERSION_COMPATIBLE TRUE) + if ("${PACKAGE_VERSION}" VERSION_EQUAL "${PACKAGE_FIND_VERSION}") + set (PACKAGE_VERSION_EXACT TRUE) + endif () +endif () diff --git a/code/CMakeLists.txt b/code/CMakeLists.txt new file mode 100644 index 0000000..ccf782d --- /dev/null +++ b/code/CMakeLists.txt @@ -0,0 +1,25 @@ +cmake_minimum_required( VERSION 3.8.2 ) + +project (habdec) +set ( CMAKE_CXX_STANDARD 11 ) + +# set ( CMAKE_BUILD_TYPE "Debug" ) +# set ( CMAKE_BUILD_TYPE "Release" ) +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE "Release") +endif() + +if ( CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT ) + set ( CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}/install" CACHE PATH "Install dir" FORCE) +endif() +message ( "CMAKE_INSTALL_PREFIX: " ${CMAKE_INSTALL_PREFIX} ) + + +add_subdirectory("Decoder") +add_subdirectory("IQSource") +add_subdirectory("websocketServer") + +option( fltkGUI "fltkGUI" OFF ) +if(fltkGUI) + add_subdirectory("fltkGUI") +endif() diff --git a/code/Decoder/AFC.h b/code/Decoder/AFC.h new file mode 100644 index 0000000..41077f0 --- /dev/null +++ b/code/Decoder/AFC.h @@ -0,0 +1,385 @@ +/* + + Copyright 2018 Michal Fratczak + + This file is part of habdec. + + habdec 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 3 of the License, or + (at your option) any later version. + + habdec 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 habdec. If not, see . +*/ + +#pragma once + +#include +#include +#include +#include + +#include "IQVector.h" +#include "Average.h" + +namespace +{ + +template +bool FftPower(const TIQVector& fft_samples, TRVector& o_power_arr); + +template +double ComputeVariance(const VEC& i_containter, const double mean); + +template +void FindPeaks( const TRVector& v, + const double expected_relative_separation, + int* p_peak1, int* p_peak2 ); + +} + +namespace habdec +{ + +template +class AFC +{ +public: + typedef std::complex TComplex; + typedef std::vector TRVector; + typedef habdec::IQVector TIQVector; + + AFC() = default; + + void setFftSamples(const TIQVector& i_fft_samples) { fft_samples_ = i_fft_samples; } + double process(); + double operator()() { return process(); } + + const TRVector& getPowerSpectrum() const { return power_arr_; } + double getFrequencyCorrection() const { return frequency_correction_; } + void resetFrequencyCorrection(const double frequency_correction); + double getShift() const { return shift_Hz_; } + void getPeaks(int& pl, int& pr) const { pl = gui_peak_left_; pr = gui_peak_right_; } + void getNoiseFloor(double& nf, double& nv) const { nf = noise_floor_; nv = noise_variance_; } + +private: + TIQVector fft_samples_; // input FFT samples + TRVector power_arr_; + + double frequency_correction_ = 0; + + double noise_floor_ = 0; + double noise_variance_ = 0; + habdec::Average noise_floor_avg_ {100}; + habdec::Average noise_variance_avg_ {100}; + + habdec::Average peak_left_avg_ {4}; + habdec::Average peak_right_avg_ {4}; + double shift_Hz_ = 0; // peak separation in Hz + + int gui_peak_left_ = 0; + int gui_peak_right_ = 0; +}; + + +template +double AFC::process() +{ + using namespace std; + + bool b_debug = 0; + + if(b_debug) + cout<<"AFC::process begin"< peak_detect_threshold ) // peak detected + b_p1_detected = true; + + bool b_p2_detected = false; + if( power_arr_[p2] > peak_detect_threshold ) // peak detected + b_p2_detected = true; + + // peaks position stability + const int peak_stability_threshold = 2; // expressed in bins + bool b_peak_left_stable = false; + bool b_peak_right_stable = false; + if(b_p1_detected && b_p2_detected) + { + if(p2 +void AFC::resetFrequencyCorrection(const double frequency_correction) +{ + const double bins_per_Hertz = (double)fft_samples_.size() / fft_samples_.samplingRate(); + peak_left_avg_.reset( std::max((double) 0, peak_left_avg_ - frequency_correction * bins_per_Hertz) ); + peak_right_avg_.reset(std::max((double) 0, peak_right_avg_ - frequency_correction * bins_per_Hertz) ); + frequency_correction_ = 0; +} + + +} // namespace habdec + + +namespace +{ + + +template +bool hasNan(const TReal* v, size_t sz) +{ + for(size_t i=0; i +bool hasInf(const TReal* v, size_t sz) +{ + for(size_t i=0; i +double ComputeVariance(const VEC& i_containter, const double mean) +{ + double var = 0; + for(const auto& v : i_containter ) + var += (v - mean) * (v - mean); + var /= i_containter.size(); + return sqrt(var); +} + + +template +bool FftPower(const TIQVector& fft_samples, TRVector& o_power_arr) +{ + // http://nl.mathworks.com/help/signal/ug/power-spectral-density-estimates-using-fft.html + + using namespace std; + + bool b_debug = 0; + + if(!fft_samples.size()) + return 0; + + if(!fft_samples.samplingRate()) + return 0; + + if(0) + { + size_t i=0; + for(auto c : fft_samples) + cout<(fft_samples.data()); + + if(b_debug) + cout<<"FftPower NaN"<(p_fft_samples_data), fft_samples.size()*2) ) + { + cout<<"FftSpectrum Nan"<(p_fft_samples_data), fft_samples.size()*2) ) + { + cout<<"FftSpectrum Inf"< +void FindPeaks( const TRVector& v, + const double expected_relative_separation, + int* p_peak1, int* p_peak2 ) +{ + using namespace std; + + // FIND TWO MAXIMUMS SEPARATED AT LEAST BY BINS_SEP + // + + int bins_sep = round(expected_relative_separation * v.size()); + bins_sep = std::max(8, bins_sep); + + // first peak + auto i_max = max_element(v.begin(), v.end()); + int p1 = i_max - v.begin(); + float p1_val = *i_max; + + // second peak + int begin = std::max( p1 - 2 * bins_sep, 0 ); + int end = std::min( p1 + 2 * bins_sep, (int) v.size() ); + int p2 = 0; + float p2_val = v[0]; + for(int i=begin; i p2_val && abs(i-p1) > bins_sep/2) + { + p2 = i; + p2_val = v[i]; + } + } + + if(p2. +*/ + +#pragma once + +#include +#include + +namespace habdec +{ + +template +class Average +{ + +public: + Average(size_t max_count, T init_val=0) : sum_(0), count_(0), max_count_(std::max(size_t(1),max_count)) + { + add(init_val); + }; + + double add(const T& val) + { + double diff = get() - val; + + if(count_ == max_count_) + { + sum_ = get() * (max_count_-1) + val; + } + else + { + ++count_; + sum_ += val; + } + + return diff; + + } + + double get() const + { + if(!count_) + return sum_; + return double(sum_)/count_; + } + + operator double() const { double val = get(); return val; } + + void reset(const T& val) + { + sum_ = val; + count_ = 1; + } + + +private: + T sum_; + size_t count_; + const size_t max_count_; + +}; + +} // namespace habdec \ No newline at end of file diff --git a/code/Decoder/CMakeLists.txt b/code/Decoder/CMakeLists.txt new file mode 100755 index 0000000..03064ad --- /dev/null +++ b/code/Decoder/CMakeLists.txt @@ -0,0 +1,55 @@ + + +include_directories( ${PROJECT_SOURCE_DIR} ) +include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ) + +set ( FFTW3f_DIR ../CMake ) +find_package( FFTW3f REQUIRED ) +include_directories( ${FFTW3f_INCLUDE_DIRS} ) +message( "FFTW Include:" ${FFTW3f_INCLUDE_DIRS} ) +message( "FFTW Lib:" ${FFTW3f_LIBRARIES} ) + + +# RTTY DECODER +set ( Decoder_src + AFC.h + Average.h + ${PROJECT_SOURCE_DIR}/common/console_colors.h + ${PROJECT_SOURCE_DIR}/common/console_colors.cpp + CRC.h CRC.cpp + Decimator.h + Decoder.h + FFT.h FFT.cpp + filtercoef.h + FirFilter.h + FSK2_Demod.h + func_timer.h + habdec_windows.h + IQVector.h + print_habhub_sentence.h print_habhub_sentence.cpp + RTTY.h + sentence_extract.h sentence_extract.cpp + SpectrumInfo.h + SymbolExtractor.h + ) + +SET( CMAKE_CXX_FLAGS " -O3 " ) +if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") + # SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wshadow" ) + SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-class-memaccess" ) +elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") + SET(CMAKE_CXX_FLAGS "/EHsc") + add_definitions( -D_USE_MATH_DEFINES ) +endif() + +set (PlatformSpecificLinking "") +if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") + set (PlatformSpecificLinking "pthread") +endif() + +add_library( Decoder ${Decoder_src}) +target_link_libraries( Decoder + #${SoapySDR_LIBRARIES} + ${FFTW3f_LIBRARIES} + ${PlatformSpecificLinking} ) + diff --git a/code/Decoder/CRC.cpp b/code/Decoder/CRC.cpp new file mode 100644 index 0000000..c68fa36 --- /dev/null +++ b/code/Decoder/CRC.cpp @@ -0,0 +1,49 @@ +#include "CRC.h" + +#include + +namespace +{ + +char _hex(char Character) +{ + char _hexTable[] = "0123456789ABCDEF"; + return _hexTable[int(Character)]; +} + +} + + +namespace habdec +{ + + +std::string CRC(std::string i_str) +{ + using std::string; + + unsigned int CRC = 0xffff; + // unsigned int xPolynomial = 0x1021; + + for (size_t i = 0; i < i_str.length(); i++) + { + CRC ^= (((unsigned int)i_str[i]) << 8); + for (int j=0; j<8; j++) + { + if (CRC & 0x8000) + CRC = (CRC << 1) ^ 0x1021; + else + CRC <<= 1; + } + } + + string result; + result += _hex((CRC >> 12) & 15); + result += _hex((CRC >> 8) & 15); + result += _hex((CRC >> 4) & 15); + result += _hex(CRC & 15); + + return result; +} + +} // namespace habdec diff --git a/code/Decoder/CRC.h b/code/Decoder/CRC.h new file mode 100644 index 0000000..1831e18 --- /dev/null +++ b/code/Decoder/CRC.h @@ -0,0 +1,10 @@ +#pragma once + +#include + +namespace habdec +{ + +std::string CRC(std::string i_str); + +} // namespace habdec diff --git a/code/Decoder/Decimator.h b/code/Decoder/Decimator.h new file mode 100644 index 0000000..568a77b --- /dev/null +++ b/code/Decoder/Decimator.h @@ -0,0 +1,149 @@ +/* + + Copyright 2018 Michal Fratczak + + This file is part of habdec. + + habdec 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 3 of the License, or + (at your option) any later version. + + habdec 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 habdec. If not, see . +*/ + +#pragma once + +#include +#include +#include +#include +#include + +namespace habdec +{ + +template +class Decimator +{ +public: + Decimator() {}; + Decimator(int decimation_factor, const Tt* p_taps, const size_t taps_size); + + void setInput(const Ts* p_in, const size_t in_size); + void setOutput(Ts* p_out); + void setFilter(const Tt* p_taps, const size_t taps_size); + + size_t operator()(); + + void setFactor(const int i_f) {decimation_factor_ = i_f;} + int factor() const {return decimation_factor_;} + +private: + int decimation_factor_ = 0; + + const Ts* p_in_ = 0; + size_t p_in_size_ = 0; + Ts* p_out_ = 0; //size is p_in_size_/decimation_factor_ + std::vector p_buff_; + std::vector p_taps_; + size_t decimated_samples_count_ = 0; +}; + + +template +Decimator::Decimator(int decimation_factor, const Tt* p_taps, const size_t taps_size) +{ + setFactor(decimation_factor); + setFilter(p_taps, taps_size); +} + + +template +void Decimator::setInput(const Ts* p_in, const size_t in_size) +{ + p_in_ = p_in; + p_in_size_ = in_size; + + const size_t new_buff_size = p_in_size_ + p_taps_.size() + decimation_factor_; + if(p_buff_.size() < new_buff_size) + { + p_buff_.resize(new_buff_size); + memset( p_buff_.data(), 0, sizeof(Ts) * p_taps_.size() ); + } +} + + +template +void Decimator::setFilter(const Tt *p_taps, const size_t taps_size) +{ + p_taps_.resize(taps_size); + memcpy( (void*) p_taps_.data(), p_taps, taps_size * sizeof(Tt)); +} + + +template +void Decimator::setOutput(Ts* p_out) +{ + p_out_ = p_out; +} + + +template +size_t Decimator::operator()() +{ + if(!decimation_factor_ || !p_in_ || !p_out_ || !p_buff_.size()) + { + std::cout<<"Decimator not fully initialised"<. +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "IQVector.h" +#include "Decimator.h" +#include "FFT.h" +#include "FirFilter.h" +#include "filtercoef.h" +#include "FSK2_Demod.h" +#include "SymbolExtractor.h" +#include "RTTY.h" +#include "sentence_extract.h" +#include "Decoder.h" +#include "AFC.h" +#include "SpectrumInfo.h" +#include "print_habhub_sentence.h" +#include "CRC.h" + +namespace habdec +{ + + +template +class Decoder +{ + + // STEPS: + // + // multi stage Decimation + // FFT + // Auto Frequency Correct + // FIR Filtering + // Demodulation (Polar Discriminant) + // Symbol Extraction + // RTTY + +public: + typedef TReal TValue; + typedef std::complex TComplex; + typedef std::vector TRVector; + typedef habdec::IQVector TIQVector; + typedef habdec::Decimator< std::complex, TReal > TDecimator; + typedef habdec::FirFilter< std::complex, TReal> TFIR; + + // feed decoder + bool pushSamples(const TIQVector& i_stream); + + // configure options + void lowpass_bw(float i_lowpass_bw); + float lowpass_bw() const; + void lowpass_trans(float i_lowpass_trans); + float lowpass_trans() const; + void baud(double i_baud); + double baud() const; + void rtty_bits(size_t i_ascii_bits); + size_t rtty_bits() const; + void rtty_stops(float i_ascii_stops); + float rtty_stops() const; + + size_t setupDecimationStagesFactor(const size_t i_factor); + size_t setupDecimationStagesBW(const double i_max_sampling_rate); + + // get result + std::string getRTTY(); + std::string getLastSentence(); + + // get info + int getDecimationFactor() const; + double getInputSamplingRate() const; + double getDecimatedSamplingRate() const; + double getSymbolRate() const; + + // get data for GUI + size_t getBinsCount() const; + const TIQVector getFFT() const; + const TRVector getDemodulated() const; + const TRVector getPowerSpectrum() const; + void getPeaks(int& pl, int& pr); + void getNoiseFloor(double& nf, double& nv); + double getShift() const; + double getFrequencyCorrection() const; + void resetFrequencyCorrection(double frequency_correction); + + // template + SpectrumInfo getSpectrumInfo(); + + // run it + void process(); + void operator()() + { + typedef std::chrono::nanoseconds TDur; + auto _start = std::chrono::high_resolution_clock::now(); + process(); + TDur _duration = std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - _start); + // std::cout<<"process() duration "<<_duration.count()<<" nS "< decimation_stages_; + int decimation_factor_ = 1; + + // FFT + const size_t fft_bins_cnt_ = 1<<12; + FFT fft_; //TODO ! this is only float ! + TIQVector freq_in_; // FFT of chunk size + TIQVector freq_out_; // FFT of chunk size + mutable std::mutex freq_out_mtx_; + + // AFC + AFC afc_; + mutable std::mutex afc_mtx_; + + // Low Pass FIR + float lowpass_bw_ = 0.05; + float lowpass_trans_ = 0.0025; + TFIR lowpass_fir_; + mutable std::mutex lowpass_fir_mtx_; + + // Demodulation + TRVector demodulated_; // result of Polar Discriminant + mutable std::mutex demodulated_mtx_; + + // Symbol Extraction from demodulated samples + SymbolExtractor symbol_extractor_; + + // RTTY reconstruction from bits + RTTY rtty_; + std::string rtty_char_stream_; // result of rtty + std::string last_sentence_; // result of rtty + // size_t last_sentence_len_ = 0; // optimization for regexp run + + // threading + mutable std::mutex process_mutex_; // mutex for main processing + + bool live_print_ = true; // live print decoded characters +}; + + +template +bool habdec::Decoder::pushSamples(const TIQVector& i_stream) +{ + { + std::lock_guard _lock(iq_in_buffer_mtx_); + const size_t pre_insert_size = iq_in_buffer_.size(); + iq_in_buffer_.resize( pre_insert_size + i_stream.size() ); + memcpy( iq_in_buffer_.data() + pre_insert_size, i_stream.data(), i_stream.size() * sizeof(TComplex) ); + } + + if( !iq_in_buffer_.samplingRate() ) + init( i_stream.samplingRate() ); + + return true; +} + + +template +void habdec::Decoder::init(const float i_sampling_rate) +{ + iq_in_buffer_.samplingRate(i_sampling_rate); + + setupDecimationStagesBW(10.1e6/256); + + std::lock_guard lock(process_mutex_); + + // FFT + freq_in_.reserve(fft_bins_cnt_); + freq_out_.reserve(fft_bins_cnt_); +} + + +template +void habdec::Decoder::lowpass_bw(float i_lowpass_bw) +{ + std::lock_guard _lock(lowpass_fir_mtx_); + lowpass_bw_ = i_lowpass_bw; + lowpass_fir_.LP_BlackmanHarris(lowpass_bw_, lowpass_trans_); +} + +template +float habdec::Decoder::lowpass_bw() const +{ + return lowpass_bw_; +} + +template +void habdec::Decoder::lowpass_trans(float i_lowpass_trans) +{ + std::lock_guard _lock(lowpass_fir_mtx_); + lowpass_trans_ = i_lowpass_trans; + lowpass_fir_.LP_BlackmanHarris(lowpass_bw_, lowpass_trans_); +} + +template +float habdec::Decoder::lowpass_trans() const +{ + return lowpass_trans_; +} + + + +template +size_t habdec::Decoder::setupDecimationStagesFactor(const size_t i_factor) +{ + using namespace std; + + if( i_factor<1 || i_factor>256 ) + { + cout<<"Unsupported decimation factor: "< lock(process_mutex_); + + decimation_stages_.clear(); + decimation_factor_ = 1; + + switch(i_factor) + { + case 256: + decimation_stages_.emplace_back( TDecimator(64, &d_256_r_64_kernel[0], d_256_r_64_len) ); + decimation_stages_.emplace_back( TDecimator(4, &d_4_r_4_kernel[0], d_4_r_4_len) ); + break; + case 128: + decimation_stages_.emplace_back( TDecimator(32, &d_128_r_32_kernel[0], d_128_r_32_len) ); + decimation_stages_.emplace_back( TDecimator(4, &d_4_r_4_kernel[0], d_4_r_4_len) ); + break; + case 64: + decimation_stages_.emplace_back( TDecimator(32, &d_64_r_32_kernel[0], d_64_r_32_len) ); + decimation_stages_.emplace_back( TDecimator(2, &d_2_r_2_kernel[0], d_2_r_2_len) ); + break; + case 32: + decimation_stages_.emplace_back( TDecimator(16, &d_32_r_16_kernel[0], d_32_r_16_len) ); + decimation_stages_.emplace_back( TDecimator(2, &d_2_r_2_kernel[0], d_2_r_2_len) ); + break; + case 16: + decimation_stages_.emplace_back( TDecimator(8, &d_16_r_8_kernel[0], d_16_r_8_len) ); + decimation_stages_.emplace_back( TDecimator(2, &d_2_r_2_kernel[0], d_2_r_2_len) ); + break; + case 8: + decimation_stages_.emplace_back( TDecimator(8, &d_8_r_8_kernel[0], d_8_r_8_len) ); + break; + case 4: + decimation_stages_.emplace_back( TDecimator(4, &d_4_r_4_kernel[0], d_4_r_4_len) ); + break; + case 2: + decimation_stages_.emplace_back( TDecimator(2, &d_2_r_2_kernel[0], d_2_r_2_len) ); + break; + default: + cout<<"Unsupported decimation factor: "<= fft_bins_cnt_) + { + { + lock_guard _lock(freq_out_mtx_); + freq_out_.resize(fft_bins_cnt_); + fft_.setInput( (float*) freq_in_.data(), fft_bins_cnt_ ); + fft_.setOutput( (float*) freq_out_.data() ); + fft_(); + } + freq_in_.clear(); + } + + + const size_t batch_size = 256; // why does it have to be 256 ? + + if(iq_samples_decimated_.size() < batch_size) + { + if(b_debug) + cout<<"Decoder::process() "<<"iq_samples_decimated_.size() < batch_size : "<(afc_mtx_, try_to_lock)) + { + if(unique_lock(freq_out_mtx_, try_to_lock)) + { + if(freq_out_.size() == fft_bins_cnt_) + afc_.setFftSamples(freq_out_); + afc_(); + } + } + + + double frequency_correction = getFrequencyCorrection(); + double shift_Hz = afc_.getShift(); + double nf, nv; + afc_.getNoiseFloor(nf, nv); + + // cout< 4*max_decimated_sampling_rate_) + { + iq_samples_temp_.clear(); + iq_samples_decimated_.clear(); + return; + } + + + // Low Pass FIR + // + const size_t samples_to_filter_cnt = iq_samples_decimated_.size() - iq_samples_decimated_.size() % batch_size; + iq_samples_filtered_.resize(samples_to_filter_cnt); + { + lock_guard _lock(lowpass_fir_mtx_); + lowpass_fir_.setInput (iq_samples_decimated_.data(), samples_to_filter_cnt); + lowpass_fir_.setOutput(iq_samples_filtered_.data()); + lowpass_fir_.LP_BlackmanHarris(lowpass_bw_, lowpass_trans_); + lowpass_fir_(); + iq_samples_filtered_.samplingRate( getDecimatedSamplingRate() ); + } + iq_samples_decimated_.erase( iq_samples_decimated_.begin(), iq_samples_decimated_.begin()+samples_to_filter_cnt ); + + if(b_debug) + cout<<"Decoder::process() "<<"FIR taps : "< _lock(demodulated_mtx_); + demodulated_.resize( iq_samples_filtered_.size() ); + FSK2_Demod( + iq_samples_filtered_.data(), iq_samples_filtered_.size(), + demodulated_.data() ); + + symbol_extractor_.samplingRate( getDecimatedSamplingRate() ); + symbol_extractor_.pushSamples(demodulated_); + } + + + if(b_debug) + cout<<"Decoder::process() "<<"demodulated_.size() "< symbols = symbol_extractor_.get(); + if(b_debug) + cout<<"Decoder::process() "<<"symbols.size() "< 1000) + rtty_char_stream_.erase( 0, rtty_char_stream_.rfind('$') ); + + // scan for sentence from time to time + if( rtty_char_stream_.size() > 20 /*last_sentence_.size()/2*/ ) + { + bool b_scan_for_sentence = true; + while(b_scan_for_sentence) + { + map result = extractSentence(rtty_char_stream_); + if( result["success"] == "OK" ) + { + rtty_char_stream_ = result["stream"]; // rest of stream after sentence + last_sentence_ = result["callsign"] + "," + result["data"] + "*" + result["crc"]; + printHabhubSentence( result["callsign"], result["data"], result["crc"] ); + + if( success_callback_ && + result["crc"] == CRC(result["callsign"] + "," + result["data"]) ) + success_callback_( result["callsign"], result["data"], result["crc"] ); + } + else + { + b_scan_for_sentence = false; + } + } + } +} // process() + + +template +std::string Decoder::getRTTY() +{ + return rtty_char_stream_; +} + + +template +std::string Decoder::getLastSentence() +{ + return last_sentence_; +} + + +template +void Decoder::baud(double i_baud) +{ + std::lock_guard _lock(process_mutex_); + symbol_extractor_.symbolRate(i_baud); +} + + +template +double Decoder::baud() const +{ + return symbol_extractor_.symbolRate(); +} + + +template +void Decoder::rtty_bits(size_t i_ascii_bits) +{ + std::lock_guard _lock(process_mutex_); + rtty_.ascii_bits(i_ascii_bits); +} + + +template +size_t Decoder::rtty_bits() const +{ + return rtty_.ascii_bits(); +} + + +template +void Decoder::rtty_stops(float i_ascii_stops) +{ + std::lock_guard _lock(process_mutex_); + rtty_.ascii_stops(i_ascii_stops); +} + + +template +float Decoder::rtty_stops() const +{ + return rtty_.ascii_stops(); +} + + +template +int Decoder::getDecimationFactor() const +{ + //std::lock_guard _lock(process_mutex_); + // this probably should be locked with process_mutex_ + return decimation_factor_; +} + + +template +double Decoder::getInputSamplingRate() const +{ + return iq_in_buffer_.samplingRate(); +} + + +template +double Decoder::getDecimatedSamplingRate() const +{ + return getInputSamplingRate() / getDecimationFactor(); +} + + +template +double Decoder::getSymbolRate() const +{ + return symbol_extractor_.symbolRate(); +} + + +template +size_t Decoder::getBinsCount() const +{ + return fft_bins_cnt_; +} + + +template +const typename Decoder::TIQVector Decoder::getFFT() const +{ + std::lock_guard _lock(freq_out_mtx_); + return freq_out_; +} + + +template +const typename Decoder::TRVector Decoder::getDemodulated() const +{ + std::lock_guard _lock(demodulated_mtx_); + return demodulated_; +} + + +template +const typename Decoder::TRVector Decoder::getPowerSpectrum() const +{ + std::lock_guard _lock(afc_mtx_); + // std::this_thread::sleep_for( ( std::chrono::duration(1000) )); + return afc_.getPowerSpectrum(); +} + + +template +void Decoder::getPeaks(int& pl, int& pr) +{ + std::lock_guard _lock(afc_mtx_); + afc_.getPeaks(pl, pr); +} + + +template +void habdec::Decoder::getNoiseFloor(double& nf, double& nv) +{ + std::lock_guard _lock(afc_mtx_); + afc_.getNoiseFloor(nf, nv); +} + + +template +double habdec::Decoder::getShift() const +{ + return afc_.getShift(); +} + + +template +double habdec::Decoder::getFrequencyCorrection() const +{ + return afc_.getFrequencyCorrection(); +} + + +template +void habdec::Decoder::resetFrequencyCorrection(double frequency_correction) +{ + afc_.resetFrequencyCorrection(frequency_correction); +} + + +template +SpectrumInfo habdec::Decoder::getSpectrumInfo() +{ + SpectrumInfo spectr_info; + spectr_info = getPowerSpectrum(); + if(!spectr_info.size()) + return spectr_info; + spectr_info.min_ = *std::min_element( spectr_info.cbegin(), spectr_info.cend() ); + spectr_info.max_ = *std::max_element( spectr_info.cbegin(), spectr_info.cend() ); + + int pl, pr; + getPeaks(pl, pr); + spectr_info.peak_left_ = std::abs(pl); + spectr_info.peak_left_valid_ = pl>0; + spectr_info.peak_right_ = std::abs(pr); + spectr_info.peak_right_valid_ = pr>0; + + getNoiseFloor(spectr_info.noise_floor_, spectr_info.noise_variance_); + spectr_info.sampling_rate_ = getDecimatedSamplingRate(); + + spectr_info.shift_ = getShift(); + + return spectr_info; +} + + +template +std::ostream& operator<<( std::ostream& output, const std::vector& v ) +{ + for(const auto& a : v) + output<. +*/ + +#include "FFT.h" + +#include +#include +#include + +namespace habdec +{ + +FFT::~FFT() +{ + if(size_) + fftwf_destroy_plan(fftw_plan_); + if(fft_in_) + fftwf_free(fft_in_); + if(fft_out_) + fftwf_free(fft_out_); +} + + +size_t FFT::size() const +{ + return size_; +} + + +void FFT::setInput(float* p_input, const size_t i_size) +{ + if(i_size != size_) + { + std::cout<<"FFT rebuild to "<* p_samples_float = reinterpret_cast*>(p_out_); + + const size_t half = size()/2; + for(size_t i=0; i) ); + fftwf_execute(fftw_plan_); + memcpy( (void*) p_out_, fft_out_, size() * sizeof(std::complex) ); + + swap_half(); + } + else if(!p_in_) + { + std::cout<<"FFT No Input"<. +*/ + +#pragma once + +#include +#include + +namespace habdec +{ + + +class FFT +{ +public: + FFT() = default; + FFT(const FFT&) = delete; + FFT& operator=(const FFT&) = delete; + ~FFT(); + + void setInput(float* p_input, const size_t i_size); + void setOutput(float* p_output); + size_t size() const; + + void operator()(); + +private: + + void swap_half(); // swaps values on other half of FFT result + + size_t size_ = 0; + + float* p_in_ = 0; + float* p_out_ = 0; + + // fftw stuff + fftwf_plan fftw_plan_; + fftwf_complex* fft_in_ = 0; + fftwf_complex* fft_out_ = 0; + +}; + + +} // namespace habdec diff --git a/code/Decoder/FSK2_Demod.h b/code/Decoder/FSK2_Demod.h new file mode 100644 index 0000000..7510da9 --- /dev/null +++ b/code/Decoder/FSK2_Demod.h @@ -0,0 +1,46 @@ +/* + + Copyright 2018 Michal Fratczak + + This file is part of habdec. + + habdec 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 3 of the License, or + (at your option) any later version. + + habdec 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 habdec. If not, see . +*/ + +#pragma once + +#include + +namespace habdec +{ + + +template +void FSK2_Demod( + const std::complex* p_cmplx_samples, const size_t samples_count, + T* o_demod ) +{ + // TO DO - this should not be static if threads... + static std::complex last_value = p_cmplx_samples[0]; + + for(size_t i=1; i. +*/ + +#pragma once + +#include +#include +#include +#include + +#include "habdec_windows.h" + + +namespace habdec +{ + + +template // Tsamples, Ttaps +class FirFilter +{ +public: + bool setInput(const Ts* p_input, const size_t in_size); + bool setOutput(Ts*); + bool setFilter(const Tt*, const size_t taps_size); + size_t taps_size(); + bool operator()(); + + void LP_BlackmanHarris(const float i_relative_filt_width, const float trans_bw = 0); + +private: + const Ts* p_input_ = 0; + size_t p_input_size_ = 0; + + Ts* p_output_ = 0; + + std::vector taps_; + + std::vector buff_; + + void dotProduct(); +}; + + + + +template +bool inline FirFilter::operator()() +{ + dotProduct(); + return true; +} + + +template +size_t inline FirFilter::taps_size() +{ + return taps_.size() ; +} + + +template +bool inline FirFilter::setInput(const Ts* p_input, const size_t in_size) +{ + if(!p_input || !in_size) + return false; + + p_input_ = p_input; + p_input_size_ = in_size; + + return true; +} + + +template +bool inline FirFilter::setFilter(const Tt* p_filter, const size_t in_size) +{ + if(!p_filter || !in_size) + return false; + + taps_.resize(in_size); + memcpy( taps_.data(), p_filter, in_size * sizeof(Tt) ); + + return true; +} + + +template +bool inline FirFilter::setOutput(Ts* p_output) +{ + if(!p_output) + return false; + + p_output_ = p_output; + + return true; +} + + +template +void FirFilter::dotProduct() +{ + using namespace std; + + if(!taps_.size()) + { + cout<<"FirFilter::dotProduct() no taps. return."< p_input_size_+1 ) + { + cout<<"FirFilter::dotProduct() more taps than samples. return. "< +void FirFilter::LP_BlackmanHarris(const float i_relative_filt_width, const float trans_bw) +{ + if(!p_input_size_) + { + std::cout<<"FirFilter::LP_BlackmanHarris No Input set."<p_input_size_) + taps_sz = p_input_size_; + taps_sz |= 1; // must be odd number + + if(taps_sz <= 4) + return; + + if(taps_sz == taps_.size()) + return; + + taps_.resize(taps_sz); + + double _sum = 0; + const int _mid = int(taps_sz/2); // !! INT IS VERY IMPORTANT HERE !! + for(int i=0; i(size_t(i), taps_sz); + _sum += taps_[i]; + } + + // normalize taps_ + for(size_t i=0; i. +*/ + +#pragma once + +#include +#include +#include + +namespace habdec +{ + +// IQ vector with sampling rate +// +template +class IQVector : public std::vector< std::complex > +{ +public: + typedef T TValue; + typedef std::complex TComplex; + + IQVector() = default; + IQVector(const IQVector& rhs); + IQVector operator=(const IQVector& rhs); + + double samplingRate() const {return sampling_rate_;} + void samplingRate(const double i_samplingRate) {sampling_rate_ = i_samplingRate;} + +private: + std::atomic sampling_rate_ = {0}; +}; + + +template +IQVector::IQVector(const IQVector& rhs) : std::vector< std::complex >::vector(rhs) +{ + sampling_rate_.store(rhs.sampling_rate_); +} + + +template +IQVector IQVector::operator=(const IQVector& rhs) +{ + std::vector< std::complex >::operator=(rhs); + sampling_rate_.store(rhs.sampling_rate_); + return *this; +} + + +template +std::ostream& operator<<( std::ostream& output, const IQVector& iqVector ) +{ + for(size_t i=0; i. +*/ + +#pragma once + +#include "stddef.h" +#include +#include +#include + +#include "common/console_colors.h" + +namespace habdec +{ + +template +class RTTY +{ + +public: + void ascii_bits(size_t i_bits) {nbits_ = i_bits;}; + size_t ascii_bits() const {return nbits_;}; + void ascii_stops(float i_stops) {nstops_ = i_stops;}; + float ascii_stops() const {return nstops_;}; + + void push(const std::vector& i_bits); + size_t size() {return chars_.size();} + std::vector get(); + size_t operator()(); + +private: + size_t nbits_ = 0; + float nstops_ = 0; + + std::vector bits_; + std::vector chars_; +}; + + + +template +void RTTY::push(const std::vector& i_bits) +{ + using namespace std; + bits_.insert( bits_.end(), i_bits.begin(), i_bits.end() ); +} + + +template +std::vector RTTY::get() +{ + auto res = chars_; + chars_.clear(); + return res; +} + + + +template +size_t RTTY::operator()() +{ + if(!nbits_ && !nstops_) + return 0; + + if( bits_.size() < (1+nbits_+nstops_) ) + return 0; + + using namespace std; + + size_t decoded_chars = 0; + size_t last_decoded_bit_index = 0; + + for(size_t i=0; i. +*/ + +#pragma once + +#include +#include + +namespace habdec +{ + +/* + just a vector with spectrum power values + and some extra info +*/ + +template +class SpectrumInfo : public std::vector +{ +public: + typedef T TValue; + + mutable T min_ = 0; + mutable T max_ = 0; + mutable double noise_floor_ = 0; + mutable double noise_variance_ = 0; + mutable double sampling_rate_ = 0; + mutable double shift_ = 0; + mutable int peak_left_ = 0; + mutable int peak_right_ = 0; + mutable bool peak_left_valid_ = false; + mutable bool peak_right_valid_ = false; + + SpectrumInfo() = default; + + template + SpectrumInfo(const SpectrumInfo& rhs) : + std::vector::vector(rhs), + noise_floor_(rhs.noise_floor_), + noise_variance_(rhs.noise_variance_), + peak_left_(rhs.peak_left_), + peak_right_(rhs.peak_right_), + peak_left_valid_(rhs.peak_left_valid_), + peak_right_valid_(rhs.peak_right_valid_) + { + // + } + + template + const SpectrumInfo& operator=(const SpectrumInfo& rhs) + { + std::vector::operator=(rhs); + noise_floor_ = rhs.noise_floor_; + noise_variance_ = rhs.noise_variance_; + peak_left_ = rhs.peak_left_; + peak_right_ = rhs.peak_right_; + peak_left_valid_ = rhs.peak_left_valid_; + peak_right_valid_ = rhs.peak_right_valid_; + return *this; + } + + const SpectrumInfo& operator=(const std::vector& rhs) + { + std::vector::operator=(rhs); + return *this; + } + +}; + + + +} // namespace habdec \ No newline at end of file diff --git a/code/Decoder/SymbolExtractor.h b/code/Decoder/SymbolExtractor.h new file mode 100644 index 0000000..48a53b9 --- /dev/null +++ b/code/Decoder/SymbolExtractor.h @@ -0,0 +1,261 @@ +/* + + Copyright 2018 Michal Fratczak + + This file is part of habdec. + + habdec 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 3 of the License, or + (at your option) any later version. + + habdec 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 habdec. If not, see . +*/ + +#pragma once + +#include +#include +#include +#include +#include + +namespace +{ + +template +inline int sgn(T val) +{ + return (T(0) < val) - (val < T(0)); +} + + +template +inline int _dir(T left, T right) +{ + if( sgn(left) < sgn(right) ) + return 1; + else if( sgn(left) > sgn(right) ) + return -1; + else + return 0; +} + + +template +void FlipPointAvrg( + const TRVector& v, + const size_t i, + const size_t R, + TReal& o_avg_l, + TReal& o_avg_r ) +{ + using namespace std; int _L = max(int(i-R), 0); // left bound + int _R = min(i+R, v.size()); // right bound + o_avg_l = std::accumulate(v.begin()+_L, v.begin()+i, TReal(0)) / (i-_L); + o_avg_r = std::accumulate(v.begin()+i, v.begin()+_R, TReal(0)) / (_R-i); +} + + +} // namespace + + + +namespace habdec +{ + +template +class SymbolExtractor +{ + +public: + typedef std::vector TRVector; + + void pushSamples(const TRVector& v); //REAL samples after Freq demodulation + + void samplingRate(const double sm_r) { sampling_rate_ = sm_r; } + double samplingRate() const { return sampling_rate_; } + + void symbolRate(const double sb_r) { symbol_rate_ = sb_r; } // baud + double symbolRate() const { return symbol_rate_; } + + std::vector get(size_t count=0); + + size_t samplesPerBit() const { return size_t(round( samplingRate()/symbolRate() )); } + + void operator()(); + +private: + double sampling_rate_ = 0; + double symbol_rate_ = 1; + TRVector samples_; + std::vector bits_; + + size_t findFirstFlipPoint(const size_t start_offset); + std::vector findFlipPoints(); +}; + + + + +template +void SymbolExtractor::pushSamples(const TRVector& v) +{ + using namespace std; + + if(!v.size()) + return; + + // safety vent + if(samples_.size() > 1e6) + { + cout<<"SymbolExtractor::pushSamples overflow. Delete samples."< +void SymbolExtractor::operator()() +{ + if( !sampling_rate_ || !symbol_rate_ ) + return; + + if( samples_.size() < samplingRate()/symbolRate()*3 ) // have at least 3 symbols + return; + + std::vector flip_points = findFlipPoints(); + if(!flip_points.size()) + return; + + size_t last_flip_point = 0; + for(const auto flip_point : flip_points) + { + TReal avg = TReal( + std::accumulate( samples_.begin()+last_flip_point, + samples_.begin()+flip_point, (TReal)0 ) + ) / (flip_point-last_flip_point); + + bool bit_value = avg > 0; + size_t bit_count = size_t( round( float(flip_point-last_flip_point) / float(samplesPerBit()) ) ); + last_flip_point = flip_point; + while(bit_count--) + bits_.push_back(bit_value); + } + + size_t erase_to = std::min(last_flip_point, samples_.size()); + samples_.erase( samples_.begin(), samples_.begin() + erase_to ); +} + + +template +size_t SymbolExtractor::findFirstFlipPoint(const size_t start_offset) +{ + if( (samples_.size()-start_offset) < samplesPerBit() ) + return 0; + + // FIND FIRST FLIP POINT + // IT NEEDS TO HAVE DIFFERENT SIGN OF AVERAGE + // ON IT'S LEFT AND RIGHT SIDE OF LENGTH R + const size_t R = std::max(4, int(samplesPerBit() / 4)); + + std::vector flip_points; + + // start at R + size_t flip_point = start_offset + R; + + TReal avg_left; + TReal avg_right; + FlipPointAvrg(samples_, flip_point, R, avg_left, avg_right); + + // SCAN UNTIL FIRST FLIP_POINT + while(sgn(avg_left) == sgn(avg_right)) + { + flip_point += 1; + + if(flip_point >= (samples_.size() - samplesPerBit())) + return 0; + + FlipPointAvrg(samples_, flip_point, R, avg_left, avg_right); + } + + size_t flip_point_left = flip_point; + // int value_change_dir = _dir(avg_left, avg_right); + + // SCAN UNTIL LAST FLIP_POINT WITH CHANGING SIGN OF AVERAGE + while(sgn(avg_left) != sgn(avg_right)) + { + flip_point += 1; + + if(flip_point >= (samples_.size() - samplesPerBit())) + return 0; + + FlipPointAvrg(samples_, flip_point, R, avg_left, avg_right); + } + + size_t flip_point_right = flip_point; + + // in range [flip_point_left, flip_point_right) + // find point with largest difference in average values + + std::vector flip_point_candidates; + std::vector flip_point_candidates_weight; + for(size_t i=flip_point_left; i +std::vector SymbolExtractor::findFlipPoints() +{ + size_t offset = 0; + size_t flip_point = findFirstFlipPoint(offset); + std::vector all_points; + + while(flip_point) + { + all_points.push_back(flip_point); + offset = flip_point; + flip_point = findFirstFlipPoint(offset); + } + return all_points; +} + + +template +std::vector SymbolExtractor::get(size_t count) +{ + if(count == 0) + count = bits_.size(); + const size_t _count = std::min(count, bits_.size()); + + const std::vector res( bits_.begin(), bits_.begin() + _count ); + bits_.erase( bits_.begin(), bits_.begin() + _count ); + + return res; +} + + + +} // namespace habdec + + diff --git a/code/Decoder/filtercoef.h b/code/Decoder/filtercoef.h new file mode 100644 index 0000000..6018862 --- /dev/null +++ b/code/Decoder/filtercoef.h @@ -0,0 +1,1449 @@ +#pragma once + +/* + coefficients taken from + https://github.com/csete/gqrx/blob/master/src/dsp/filter/fir_decim_coef.h +*/ + +/* +d_2_r_2_len = 69 +d_2_r_2_kernel +d_4_r_4_len = 139 +d_4_r_4_kernel +d_8_r_8_len = 280 +d_8_r_8_kernel +d_16_r_8_len = 54 +d_16_r_8_kernel +d_32_r_16_len = 107 +d_32_r_16_kernel +d_64_r_32_len = 212 +d_64_r_32_kernel +d_128_r_32_len = 174 +d_128_r_32_kernel +d_256_r_64_len = 348 +d_256_r_64_kernel +*/ + +static const int d_2_r_2_len = 69; +static const float d_2_r_2_kernel[] = +{ + 0.000399985734121014f, + 0.002073370222476234f, + 0.004853019240304940f, + 0.005977464755456102f, + 0.002625480716699286f, + -0.002713628293157090f, + -0.003379460736391527f, + 0.001637205667907783f, + 0.004080689203761314f, + -0.000982433398470081f, + -0.005119016867477646f, + 0.000177424749467386f, + 0.006424890506348696f, + 0.001008090651156955f, + -0.007915926496343137f, + -0.002717062331286239f, + 0.009511042111613645f, + 0.005077150379032227f, + -0.011151300589456603f, + -0.008251061374053964f, + 0.012781117215688672f, + 0.012490374909303374f, + -0.014344287749952384f, + -0.018209086168089920f, + 0.015778580923975386f, + 0.026178028229057050f, + -0.017029165534577999f, + -0.038051941291319488f, + 0.018060406839966188f, + 0.058210457193828925f, + -0.018831122390764166f, + -0.102778567522516130f, + 0.019291268777910851f, + 0.317182812089170980f, + 0.480536048712957740f, + 0.317182812089170980f, + 0.019291268777910851f, + -0.102778567522516130f, + -0.018831122390764166f, + 0.058210457193828925f, + 0.018060406839966188f, + -0.038051941291319488f, + -0.017029165534577999f, + 0.026178028229057050f, + 0.015778580923975386f, + -0.018209086168089920f, + -0.014344287749952384f, + 0.012490374909303374f, + 0.012781117215688672f, + -0.008251061374053964f, + -0.011151300589456603f, + 0.005077150379032227f, + 0.009511042111613645f, + -0.002717062331286239f, + -0.007915926496343137f, + 0.001008090651156955f, + 0.006424890506348696f, + 0.000177424749467386f, + -0.005119016867477646f, + -0.000982433398470081f, + 0.004080689203761314f, + 0.001637205667907783f, + -0.003379460736391527f, + -0.002713628293157090f, + 0.002625480716699286f, + 0.005977464755456102f, + 0.004853019240304940f, + 0.002073370222476234f, + 0.000399985734121014f +}; + +static const int d_4_r_4_len = 139; +static const float d_4_r_4_kernel[] = +{ + 0.000042167047949931f, + 0.000162480875041441f, + 0.000413474829003805f, + 0.000815488719349860f, + 0.001323484844111109f, + 0.001803932401530970f, + 0.002050805379425780f, + 0.001851476423100084f, + 0.001088358238163842f, + -0.000165599354540670f, + -0.001612840277093291f, + -0.002799173360323900f, + -0.003280737659419560f, + -0.002830930204582274f, + -0.001589296551711622f, + -0.000060142418430366f, + 0.001072157673911288f, + 0.001252059507347206f, + 0.000346781210023729f, + -0.001233491421169468f, + -0.002682865592015316f, + -0.003178340139233828f, + -0.002320119390193667f, + -0.000402092792444196f, + 0.001661437823975322f, + 0.002761727219457103f, + 0.002186981534424376f, + 0.000071307331744879f, + -0.002570893712874658f, + -0.004301512250227543f, + -0.004015094439084645f, + -0.001606879839533175f, + 0.001838674337622738f, + 0.004510048531846937f, + 0.004804547613530567f, + 0.002266863620581679f, + -0.002004704037111716f, + -0.005785548895574678f, + -0.006849655924079080f, + -0.004239720077392586f, + 0.001024318787772757f, + 0.006275193248599259f, + 0.008511512338709764f, + 0.006070603106211769f, + -0.000247611530141919f, + -0.007317511868656072f, + -0.011170336815604164f, + -0.009152698013614463f, + -0.001621157345452147f, + 0.007851435931989321f, + 0.014073238852672171f, + 0.012972692080589394f, + 0.004087473189926854f, + -0.008634954375856124f, + -0.018413964067748419f, + -0.019050011539439745f, + -0.008545626179408438f, + 0.009039966712164142f, + 0.024793283315122296f, + 0.029034181171149441f, + 0.016560363014866013f, + -0.009522346448795137f, + -0.037569562545468192f, + -0.051411140638474247f, + -0.037221789978391415f, + 0.009679493935209005f, + 0.081286213859684806f, + 0.158552299980228740f, + 0.217917169253869340f, + 0.240164834839879550f, + 0.217917169253869340f, + 0.158552299980228740f, + 0.081286213859684806f, + 0.009679493935209005f, + -0.037221789978391415f, + -0.051411140638474247f, + -0.037569562545468192f, + -0.009522346448795137f, + 0.016560363014866013f, + 0.029034181171149441f, + 0.024793283315122296f, + 0.009039966712164142f, + -0.008545626179408438f, + -0.019050011539439745f, + -0.018413964067748419f, + -0.008634954375856124f, + 0.004087473189926854f, + 0.012972692080589394f, + 0.014073238852672171f, + 0.007851435931989321f, + -0.001621157345452147f, + -0.009152698013614463f, + -0.011170336815604164f, + -0.007317511868656072f, + -0.000247611530141919f, + 0.006070603106211769f, + 0.008511512338709764f, + 0.006275193248599259f, + 0.001024318787772757f, + -0.004239720077392586f, + -0.006849655924079080f, + -0.005785548895574678f, + -0.002004704037111716f, + 0.002266863620581679f, + 0.004804547613530567f, + 0.004510048531846937f, + 0.001838674337622738f, + -0.001606879839533175f, + -0.004015094439084645f, + -0.004301512250227543f, + -0.002570893712874658f, + 0.000071307331744879f, + 0.002186981534424376f, + 0.002761727219457103f, + 0.001661437823975322f, + -0.000402092792444196f, + -0.002320119390193667f, + -0.003178340139233828f, + -0.002682865592015316f, + -0.001233491421169468f, + 0.000346781210023729f, + 0.001252059507347206f, + 0.001072157673911288f, + -0.000060142418430366f, + -0.001589296551711622f, + -0.002830930204582274f, + -0.003280737659419560f, + -0.002799173360323900f, + -0.001612840277093291f, + -0.000165599354540670f, + 0.001088358238163842f, + 0.001851476423100084f, + 0.002050805379425780f, + 0.001803932401530970f, + 0.001323484844111109f, + 0.000815488719349860f, + 0.000413474829003805f, + 0.000162480875041441f, + 0.000042167047949931f +}; + +static const int d_8_r_8_len = 280; +static const float d_8_r_8_kernel[] = +{ + 0.000005299484859782f, + 0.000023653198869943f, + 0.000045443155025411f, + 0.000086660616597102f, + 0.000145468147843215f, + 0.000227646032445337f, + 0.000334591194217999f, + 0.000466890457500183f, + 0.000622018386430552f, + 0.000794466626663634f, + 0.000975304575250323f, + 0.001152454785657775f, + 0.001311296864337127f, + 0.001435783630074849f, + 0.001509953148215840f, + 0.001519741581366084f, + 0.001454903824191261f, + 0.001310813201213376f, + 0.001089882810057675f, + 0.000802361759738747f, + 0.000466304093914126f, + 0.000106589241438445f, + -0.000247017317721992f, + -0.000562646941659305f, + -0.000809708828030606f, + -0.000962510996013040f, + -0.001003685261621032f, + -0.000926952775265634f, + -0.000738799897838057f, + -0.000458730744403599f, + -0.000117916487516219f, + 0.000243742648939376f, + 0.000581911777806535f, + 0.000853035291692318f, + 0.001019866746633974f, + 0.001056611000192218f, + 0.000952962453331239f, + 0.000716408838645576f, + 0.000372351073038558f, + -0.000038150274869667f, + -0.000462881782404900f, + -0.000844797294892937f, + -0.001129425716907750f, + -0.001272432677940103f, + -0.001246307890160262f, + -0.001045192378203970f, + -0.000687044203214210f, + -0.000212653183490116f, + 0.000318579724580746f, + 0.000835734644546107f, + 0.001265542439063603f, + 0.001542487733459282f, + 0.001618487960413105f, + 0.001470755262270050f, + 0.001106608046232222f, + 0.000564346197878288f, + -0.000090197750452171f, + -0.000771230463597417f, + -0.001383890554706424f, + -0.001837132239362339f, + -0.002056896211703681f, + -0.001997709076123834f, + -0.001650953765714851f, + -0.001048413504576680f, + -0.000260276733547870f, + 0.000612469118131840f, + 0.001450527381084600f, + 0.002132190093380017f, + 0.002550584440683641f, + 0.002629881881769309f, + 0.002338080196576415f, + 0.001694308341293216f, + 0.000769260408641065f, + -0.000321736170028782f, + -0.001432485915523021f, + -0.002404976322971185f, + -0.003091310085438950f, + -0.003375549372556256f, + -0.003192330168178722f, + -0.002539372888669491f, + -0.001481713556478757f, + -0.000146533823587781f, + 0.001291251516558131f, + 0.002631154368260663f, + 0.003674321213032700f, + 0.004252198884660451f, + 0.004252637433548458f, + 0.003639528435255283f, + 0.002462762274858131f, + 0.000856475239499534f, + -0.000974892854265319f, + -0.002781496880057425f, + -0.004301065594668099f, + -0.005295755541230454f, + -0.005587859925192526f, + -0.005089203765495300f, + -0.003819632950038145f, + -0.001911267954229858f, + 0.000402995000090862f, + 0.002816115056235722f, + 0.004985868963592199f, + 0.006581423530514738f, + 0.007331423828496663f, + 0.007066900231758860f, + 0.005752595831756849f, + 0.003501526672561130f, + 0.000569595914029656f, + -0.002670342281476470f, + -0.005772755486290897f, + -0.008277141861910673f, + -0.009772095428011296f, + -0.009957304065452081f, + -0.008694779007964944f, + -0.006041501906687299f, + -0.002257673645446692f, + 0.002212348869418207f, + 0.006785874581560984f, + 0.010810304734210376f, + 0.013646746123386143f, + 0.014758915386036504f, + 0.013796112346034117f, + 0.010659097540521932f, + 0.005539210274923477f, + -0.001076115841043161f, + -0.008434444147245189f, + -0.015584625308516726f, + -0.021472430244782261f, + -0.025055744331654087f, + -0.025426655616721288f, + -0.021926322954481325f, + -0.014238733805135361f, + -0.002451384366749276f, + 0.012925647002682830f, + 0.030986186274100380f, + 0.050498778538203032f, + 0.070015421670629074f, + 0.088007266252761618f, + 0.103012981470773550f, + 0.113783757663955240f, + 0.119409036455313980f, + 0.119409036455313980f, + 0.113783757663955240f, + 0.103012981470773550f, + 0.088007266252761618f, + 0.070015421670629074f, + 0.050498778538203032f, + 0.030986186274100380f, + 0.012925647002682830f, + -0.002451384366749276f, + -0.014238733805135361f, + -0.021926322954481325f, + -0.025426655616721288f, + -0.025055744331654087f, + -0.021472430244782261f, + -0.015584625308516726f, + -0.008434444147245189f, + -0.001076115841043161f, + 0.005539210274923477f, + 0.010659097540521932f, + 0.013796112346034117f, + 0.014758915386036504f, + 0.013646746123386143f, + 0.010810304734210376f, + 0.006785874581560984f, + 0.002212348869418207f, + -0.002257673645446692f, + -0.006041501906687299f, + -0.008694779007964944f, + -0.009957304065452081f, + -0.009772095428011296f, + -0.008277141861910673f, + -0.005772755486290897f, + -0.002670342281476470f, + 0.000569595914029656f, + 0.003501526672561130f, + 0.005752595831756849f, + 0.007066900231758860f, + 0.007331423828496663f, + 0.006581423530514738f, + 0.004985868963592199f, + 0.002816115056235722f, + 0.000402995000090862f, + -0.001911267954229858f, + -0.003819632950038145f, + -0.005089203765495300f, + -0.005587859925192526f, + -0.005295755541230454f, + -0.004301065594668099f, + -0.002781496880057425f, + -0.000974892854265319f, + 0.000856475239499534f, + 0.002462762274858131f, + 0.003639528435255283f, + 0.004252637433548458f, + 0.004252198884660451f, + 0.003674321213032700f, + 0.002631154368260663f, + 0.001291251516558131f, + -0.000146533823587781f, + -0.001481713556478757f, + -0.002539372888669491f, + -0.003192330168178722f, + -0.003375549372556256f, + -0.003091310085438950f, + -0.002404976322971185f, + -0.001432485915523021f, + -0.000321736170028782f, + 0.000769260408641065f, + 0.001694308341293216f, + 0.002338080196576415f, + 0.002629881881769309f, + 0.002550584440683641f, + 0.002132190093380017f, + 0.001450527381084600f, + 0.000612469118131840f, + -0.000260276733547870f, + -0.001048413504576680f, + -0.001650953765714851f, + -0.001997709076123834f, + -0.002056896211703681f, + -0.001837132239362339f, + -0.001383890554706424f, + -0.000771230463597417f, + -0.000090197750452171f, + 0.000564346197878288f, + 0.001106608046232222f, + 0.001470755262270050f, + 0.001618487960413105f, + 0.001542487733459282f, + 0.001265542439063603f, + 0.000835734644546107f, + 0.000318579724580746f, + -0.000212653183490116f, + -0.000687044203214210f, + -0.001045192378203970f, + -0.001246307890160262f, + -0.001272432677940103f, + -0.001129425716907750f, + -0.000844797294892937f, + -0.000462881782404900f, + -0.000038150274869667f, + 0.000372351073038558f, + 0.000716408838645576f, + 0.000952962453331239f, + 0.001056611000192218f, + 0.001019866746633974f, + 0.000853035291692318f, + 0.000581911777806535f, + 0.000243742648939376f, + -0.000117916487516219f, + -0.000458730744403599f, + -0.000738799897838057f, + -0.000926952775265634f, + -0.001003685261621032f, + -0.000962510996013040f, + -0.000809708828030606f, + -0.000562646941659305f, + -0.000247017317721992f, + 0.000106589241438445f, + 0.000466304093914126f, + 0.000802361759738747f, + 0.001089882810057675f, + 0.001310813201213376f, + 0.001454903824191261f, + 0.001519741581366084f, + 0.001509953148215840f, + 0.001435783630074849f, + 0.001311296864337127f, + 0.001152454785657775f, + 0.000975304575250323f, + 0.000794466626663634f, + 0.000622018386430552f, + 0.000466890457500183f, + 0.000334591194217999f, + 0.000227646032445337f, + 0.000145468147843215f, + 0.000086660616597102f, + 0.000045443155025411f, + 0.000023653198869943f, + 0.000005299484859782f +}; + +static const int d_16_r_8_len = 54; +static const float d_16_r_8_kernel[] = +{ + -0.000010553664672862f, + -0.000061498701563991f, + -0.000169601122616288f, + -0.000389180581238296f, + -0.000769984128346191f, + -0.001370862255977838f, + -0.002239657737237394f, + -0.003399895346870093f, + -0.004830710741492023f, + -0.006448450828431843f, + -0.008091858901382079f, + -0.009515843884697457f, + -0.010397443295914180f, + -0.010356613550454467f, + -0.008992200646607676f, + -0.005930785604319544f, + -0.000883275448312690f, + 0.006298249742162992f, + 0.015572313369334116f, + 0.026677316967261836f, + 0.039125602626276818f, + 0.052226529544645239f, + 0.065138652777540620f, + 0.076946528099683636f, + 0.086753462256061120f, + 0.093778457566739207f, + 0.097444274566674538f, + 0.097444274566674538f, + 0.093778457566739207f, + 0.086753462256061120f, + 0.076946528099683636f, + 0.065138652777540620f, + 0.052226529544645239f, + 0.039125602626276818f, + 0.026677316967261836f, + 0.015572313369334116f, + 0.006298249742162992f, + -0.000883275448312690f, + -0.005930785604319544f, + -0.008992200646607676f, + -0.010356613550454467f, + -0.010397443295914180f, + -0.009515843884697457f, + -0.008091858901382079f, + -0.006448450828431843f, + -0.004830710741492023f, + -0.003399895346870093f, + -0.002239657737237394f, + -0.001370862255977838f, + -0.000769984128346191f, + -0.000389180581238296f, + -0.000169601122616288f, + -0.000061498701563991f, + -0.000010553664672862f +}; + +static const int d_32_r_16_len = 107; +static const float d_32_r_16_kernel[] = +{ + -0.000004024163639795f, + -0.000017672975608646f, + -0.000028369983125930f, + -0.000051841257358260f, + -0.000084114931088978f, + -0.000130374705334955f, + -0.000193165706690690f, + -0.000276282392544972f, + -0.000383294466797586f, + -0.000517836385761646f, + -0.000683246849920059f, + -0.000882378788952720f, + -0.001117308161626894f, + -0.001389043294976996f, + -0.001697213461428019f, + -0.002039760314912465f, + -0.002412643435722481f, + -0.002809577646098091f, + -0.003221818992095683f, + -0.003638016956253216f, + -0.004044149516577933f, + -0.004423556043039536f, + -0.004757080371798020f, + -0.005023332869090757f, + -0.005199075945795754f, + -0.005259732456805450f, + -0.005180010907146506f, + -0.004934635615957972f, + -0.004499164222082719f, + -0.003850869437258024f, + -0.002969657050308204f, + -0.001838988139263688f, + -0.000446770521598867f, + 0.001213817123243464f, + 0.003143605116121320f, + 0.005336851770962665f, + 0.007780833517050342f, + 0.010455633416035585f, + 0.013334149150643793f, + 0.016382334116677784f, + 0.019559676833852839f, + 0.022819914826782396f, + 0.026111969807273771f, + 0.029381081811115123f, + 0.032570111325119062f, + 0.035620970792186964f, + 0.038476140562399175f, + 0.041080219701286683f, + 0.043381459308086866f, + 0.045333225316341701f, + 0.046895339212960678f, + 0.048035248704517766f, + 0.048728985952954711f, + 0.048961878385199747f, + 0.048728985952954711f, + 0.048035248704517766f, + 0.046895339212960678f, + 0.045333225316341701f, + 0.043381459308086866f, + 0.041080219701286683f, + 0.038476140562399175f, + 0.035620970792186964f, + 0.032570111325119062f, + 0.029381081811115123f, + 0.026111969807273771f, + 0.022819914826782396f, + 0.019559676833852839f, + 0.016382334116677784f, + 0.013334149150643793f, + 0.010455633416035585f, + 0.007780833517050342f, + 0.005336851770962665f, + 0.003143605116121320f, + 0.001213817123243464f, + -0.000446770521598867f, + -0.001838988139263688f, + -0.002969657050308204f, + -0.003850869437258024f, + -0.004499164222082719f, + -0.004934635615957972f, + -0.005180010907146506f, + -0.005259732456805450f, + -0.005199075945795754f, + -0.005023332869090757f, + -0.004757080371798020f, + -0.004423556043039536f, + -0.004044149516577933f, + -0.003638016956253216f, + -0.003221818992095683f, + -0.002809577646098091f, + -0.002412643435722481f, + -0.002039760314912465f, + -0.001697213461428019f, + -0.001389043294976996f, + -0.001117308161626894f, + -0.000882378788952720f, + -0.000683246849920059f, + -0.000517836385761646f, + -0.000383294466797586f, + -0.000276282392544972f, + -0.000193165706690690f, + -0.000130374705334955f, + -0.000084114931088978f, + -0.000051841257358260f, + -0.000028369983125930f, + -0.000017672975608646f, + -0.000004024163639795f +}; + +static const int d_64_r_32_len = 212; +static const float d_64_r_32_kernel[] = +{ + -0.000004403823942508f, + -0.000008963059919890f, + -0.000007276052892980f, + -0.000013448546764569f, + -0.000016407338246392f, + -0.000022821877811828f, + -0.000029059859493782f, + -0.000037502053326083f, + -0.000047050128769168f, + -0.000058647705667398f, + -0.000072066821233235f, + -0.000087775432302674f, + -0.000105848488644829f, + -0.000126598475702349f, + -0.000150205141042045f, + -0.000176926965601505f, + -0.000206973701715915f, + -0.000240575602493366f, + -0.000277937749971926f, + -0.000319260777052827f, + -0.000364722541989086f, + -0.000414482134953896f, + -0.000468670554403767f, + -0.000527388854339363f, + -0.000590701722925615f, + -0.000658633566464172f, + -0.000731163061150287f, + -0.000808218604975926f, + -0.000889673345622962f, + -0.000975340650633742f, + -0.001064969616730599f, + -0.001158240957389821f, + -0.001254763178484453f, + -0.001354069203096897f, + -0.001455613461052586f, + -0.001558769541846508f, + -0.001662828458596891f, + -0.001766997597152117f, + -0.001870400403116935f, + -0.001972076865069115f, + -0.002070984841172726f, + -0.002166002272448999f, + -0.002255930317598858f, + -0.002339497436442704f, + -0.002415364439683740f, + -0.002482130514177367f, + -0.002538340220525754f, + -0.002582491452580508f, + -0.002613044332960035f, + -0.002628431011812668f, + -0.002627066321370591f, + -0.002607359228695053f, + -0.002567725018271331f, + -0.002506598123060911f, + -0.002422445514576562f, + -0.002313780550524778f, + -0.002179177170034060f, + -0.002017284317828416f, + -0.001826840471286680f, + -0.001606688137875605f, + -0.001355788185007890f, + -0.001073233860638388f, + -0.000758264360902667f, + -0.000410277798843436f, + -0.000028843430628706f, + 0.000386287004249912f, + 0.000835168966487215f, + 0.001317655958647924f, + 0.001833391650175865f, + 0.002381803404668191f, + 0.002962097316406667f, + 0.003573254853063226f, + 0.004214031187543062f, + 0.004882955288187807f, + 0.005578331822331469f, + 0.006298244909815173f, + 0.007040563748502659f, + 0.007802950114525442f, + 0.008582867722817980f, + 0.009377593413961051f, + 0.010184230117287451f, + 0.010999721518727896f, + 0.011820868346749476f, + 0.012644346170734195f, + 0.013466724590201118f, + 0.014284487677241258f, + 0.015094055520281103f, + 0.015891806704001060f, + 0.016674101548252919f, + 0.017437305919088521f, + 0.018177815416425963f, + 0.018892079736813970f, + 0.019576627004361302f, + 0.020228087861972253f, + 0.020843219113185100f, + 0.021418926707647539f, + 0.021952287867040517f, + 0.022440572154110033f, + 0.022881261295670835f, + 0.023272067580484536f, + 0.023610950665041715f, + 0.023896132633698622f, + 0.024126111175283287f, + 0.024299670755100852f, + 0.024415891678976044f, + 0.024474156966027200f, + 0.024474156966027200f, + 0.024415891678976044f, + 0.024299670755100852f, + 0.024126111175283287f, + 0.023896132633698622f, + 0.023610950665041715f, + 0.023272067580484536f, + 0.022881261295670835f, + 0.022440572154110033f, + 0.021952287867040517f, + 0.021418926707647539f, + 0.020843219113185100f, + 0.020228087861972253f, + 0.019576627004361302f, + 0.018892079736813970f, + 0.018177815416425963f, + 0.017437305919088521f, + 0.016674101548252919f, + 0.015891806704001060f, + 0.015094055520281103f, + 0.014284487677241258f, + 0.013466724590201118f, + 0.012644346170734195f, + 0.011820868346749476f, + 0.010999721518727896f, + 0.010184230117287451f, + 0.009377593413961051f, + 0.008582867722817980f, + 0.007802950114525442f, + 0.007040563748502659f, + 0.006298244909815173f, + 0.005578331822331469f, + 0.004882955288187807f, + 0.004214031187543062f, + 0.003573254853063226f, + 0.002962097316406667f, + 0.002381803404668191f, + 0.001833391650175865f, + 0.001317655958647924f, + 0.000835168966487215f, + 0.000386287004249912f, + -0.000028843430628706f, + -0.000410277798843436f, + -0.000758264360902667f, + -0.001073233860638388f, + -0.001355788185007890f, + -0.001606688137875605f, + -0.001826840471286680f, + -0.002017284317828416f, + -0.002179177170034060f, + -0.002313780550524778f, + -0.002422445514576562f, + -0.002506598123060911f, + -0.002567725018271331f, + -0.002607359228695053f, + -0.002627066321370591f, + -0.002628431011812668f, + -0.002613044332960035f, + -0.002582491452580508f, + -0.002538340220525754f, + -0.002482130514177367f, + -0.002415364439683740f, + -0.002339497436442704f, + -0.002255930317598858f, + -0.002166002272448999f, + -0.002070984841172726f, + -0.001972076865069115f, + -0.001870400403116935f, + -0.001766997597152117f, + -0.001662828458596891f, + -0.001558769541846508f, + -0.001455613461052586f, + -0.001354069203096897f, + -0.001254763178484453f, + -0.001158240957389821f, + -0.001064969616730599f, + -0.000975340650633742f, + -0.000889673345622962f, + -0.000808218604975926f, + -0.000731163061150287f, + -0.000658633566464172f, + -0.000590701722925615f, + -0.000527388854339363f, + -0.000468670554403767f, + -0.000414482134953896f, + -0.000364722541989086f, + -0.000319260777052827f, + -0.000277937749971926f, + -0.000240575602493366f, + -0.000206973701715915f, + -0.000176926965601505f, + -0.000150205141042045f, + -0.000126598475702349f, + -0.000105848488644829f, + -0.000087775432302674f, + -0.000072066821233235f, + -0.000058647705667398f, + -0.000047050128769168f, + -0.000037502053326083f, + -0.000029059859493782f, + -0.000022821877811828f, + -0.000016407338246392f, + -0.000013448546764569f, + -0.000007276052892980f, + -0.000008963059919890f, + -0.000004403823942508f +}; + +static const int d_128_r_32_len = 174; +static const float d_128_r_32_kernel[] = +{ + -0.000007703161797332f, + -0.000007067232655723f, + -0.000010206071983051f, + -0.000014172048980291f, + -0.000019092331824095f, + -0.000025093561850217f, + -0.000032309725460887f, + -0.000040869410108629f, + -0.000050902771287247f, + -0.000062527941809152f, + -0.000075857080877625f, + -0.000090981984892608f, + -0.000107979276021387f, + -0.000126895337525829f, + -0.000147750778600044f, + -0.000170524898241214f, + -0.000195159646270053f, + -0.000221543901544016f, + -0.000249517228886741f, + -0.000278854334896464f, + -0.000309268991706370f, + -0.000340399096744052f, + -0.000371811190567229f, + -0.000402986592324930f, + -0.000433326971103446f, + -0.000462142048725246f, + -0.000488656689255886f, + -0.000512000649038707f, + -0.000531217622524194f, + -0.000545257474301118f, + -0.000552987616398289f, + -0.000553188077307909f, + -0.000544565488882758f, + -0.000525751232639430f, + -0.000495318184744208f, + -0.000451782034515639f, + -0.000393620779029084f, + -0.000319279140356296f, + -0.000227190622760720f, + -0.000115784771504684f, + 0.000016488581452787f, + 0.000171149664304299f, + 0.000349662890884785f, + 0.000553425442457719f, + 0.000783740497411292f, + 0.001041804838025221f, + 0.001328682064289453f, + 0.001645290145967291f, + 0.001992375608565783f, + 0.002370502036550272f, + 0.002780026279675712f, + 0.003221088947286086f, + 0.003693593686280741f, + 0.004197200680900796f, + 0.004731309996663634f, + 0.005295059011515552f, + 0.005887310701543637f, + 0.006506655780921748f, + 0.007151406625936390f, + 0.007819604696828528f, + 0.008509020566706571f, + 0.009217166946123657f, + 0.009941305011649831f, + 0.010678463067957514f, + 0.011425449071796635f, + 0.012178874660574504f, + 0.012935173457761552f, + 0.013690629889370804f, + 0.014441402554104810f, + 0.015183556958199267f, + 0.015913092956531424f, + 0.016625980278750660f, + 0.017318188813430120f, + 0.017985725593062503f, + 0.018624666516886546f, + 0.019231193320663705f, + 0.019801625228558870f, + 0.020332454367773867f, + 0.020820375812973399f, + 0.021262319920613983f, + 0.021655479285054610f, + 0.021997336565315176f, + 0.022285687008084795f, + 0.022518660515178174f, + 0.022694738600454345f, + 0.022812769691468757f, + 0.022871979661449618f, + 0.022871979661449618f, + 0.022812769691468757f, + 0.022694738600454345f, + 0.022518660515178174f, + 0.022285687008084795f, + 0.021997336565315176f, + 0.021655479285054610f, + 0.021262319920613983f, + 0.020820375812973399f, + 0.020332454367773867f, + 0.019801625228558870f, + 0.019231193320663705f, + 0.018624666516886546f, + 0.017985725593062503f, + 0.017318188813430120f, + 0.016625980278750660f, + 0.015913092956531424f, + 0.015183556958199267f, + 0.014441402554104810f, + 0.013690629889370804f, + 0.012935173457761552f, + 0.012178874660574504f, + 0.011425449071796635f, + 0.010678463067957514f, + 0.009941305011649831f, + 0.009217166946123657f, + 0.008509020566706571f, + 0.007819604696828528f, + 0.007151406625936390f, + 0.006506655780921748f, + 0.005887310701543637f, + 0.005295059011515552f, + 0.004731309996663634f, + 0.004197200680900796f, + 0.003693593686280741f, + 0.003221088947286086f, + 0.002780026279675712f, + 0.002370502036550272f, + 0.001992375608565783f, + 0.001645290145967291f, + 0.001328682064289453f, + 0.001041804838025221f, + 0.000783740497411292f, + 0.000553425442457719f, + 0.000349662890884785f, + 0.000171149664304299f, + 0.000016488581452787f, + -0.000115784771504684f, + -0.000227190622760720f, + -0.000319279140356296f, + -0.000393620779029084f, + -0.000451782034515639f, + -0.000495318184744208f, + -0.000525751232639430f, + -0.000544565488882758f, + -0.000553188077307909f, + -0.000552987616398289f, + -0.000545257474301118f, + -0.000531217622524194f, + -0.000512000649038707f, + -0.000488656689255886f, + -0.000462142048725246f, + -0.000433326971103446f, + -0.000402986592324930f, + -0.000371811190567229f, + -0.000340399096744052f, + -0.000309268991706370f, + -0.000278854334896464f, + -0.000249517228886741f, + -0.000221543901544016f, + -0.000195159646270053f, + -0.000170524898241214f, + -0.000147750778600044f, + -0.000126895337525829f, + -0.000107979276021387f, + -0.000090981984892608f, + -0.000075857080877625f, + -0.000062527941809152f, + -0.000050902771287247f, + -0.000040869410108629f, + -0.000032309725460887f, + -0.000025093561850217f, + -0.000019092331824095f, + -0.000014172048980291f, + -0.000010206071983051f, + -0.000007067232655723f, + -0.000007703161797332f +}; + +static const int d_256_r_64_len = 348; +static const float d_256_r_64_kernel[] = +{ + -0.000006032200297229f, + -0.000002790586794678f, + -0.000003423524464373f, + -0.000004141892670381f, + -0.000004959329780957f, + -0.000005880953015414f, + -0.000006916263845337f, + -0.000008064028056128f, + -0.000009336504822940f, + -0.000010742797132820f, + -0.000012302324525658f, + -0.000014003128525449f, + -0.000015868003792231f, + -0.000017906061357310f, + -0.000020111369902626f, + -0.000022508204619172f, + -0.000025093613992638f, + -0.000027881953296601f, + -0.000030875236885189f, + -0.000034086060833210f, + -0.000037517497377010f, + -0.000041176665997414f, + -0.000045067469478981f, + -0.000049199353227621f, + -0.000053568215176887f, + -0.000058185242147041f, + -0.000063047547807853f, + -0.000068158618146586f, + -0.000073517650784389f, + -0.000079124725926570f, + -0.000084976788235246f, + -0.000091070103041806f, + -0.000097399649098627f, + -0.000103959504668590f, + -0.000110738977492950f, + -0.000117729935644196f, + -0.000124919754739577f, + -0.000132293212128623f, + -0.000139836270835869f, + -0.000147529334756596f, + -0.000155353239032747f, + -0.000163284378055491f, + -0.000171298895948762f, + -0.000179368841745378f, + -0.000187464129074148f, + -0.000195552549576070f, + -0.000203599379753965f, + -0.000211565351775375f, + -0.000219411598860001f, + -0.000227093646507866f, + -0.000234565855614429f, + -0.000241779257421431f, + -0.000248682177854843f, + -0.000255220180724547f, + -0.000261335292980978f, + -0.000266967862740791f, + -0.000272054419087176f, + -0.000276528686849870f, + -0.000280322370041046f, + -0.000283363923695878f, + -0.000285578633373008f, + -0.000286890694598539f, + -0.000287220112764771f, + -0.000286486063219693f, + -0.000284603980740463f, + -0.000281488659987540f, + -0.000277051522643753f, + -0.000271202733437524f, + -0.000263850662609383f, + -0.000254902132867105f, + -0.000244261829079865f, + -0.000231834561467387f, + -0.000217522684614226f, + -0.000201228717970838f, + -0.000182854056621652f, + -0.000162300101972573f, + -0.000139467943568298f, + -0.000114258627064630f, + -0.000086574168670878f, + -0.000056316612617103f, + -0.000023389083735015f, + 0.000012303734435184f, + 0.000050856088211618f, + 0.000092360432854175f, + 0.000136906695012963f, + 0.000184583050199368f, + 0.000235474395169584f, + 0.000289663252276950f, + 0.000347228091667187f, + 0.000408244468331575f, + 0.000472783700962668f, + 0.000540912739938505f, + 0.000612694289527581f, + 0.000688186201030564f, + 0.000767440808596336f, + 0.000850505496981770f, + 0.000937421598757782f, + 0.001028224584686942f, + 0.001122943571650730f, + 0.001221601170177604f, + 0.001324213422447449f, + 0.001430788817328081f, + 0.001541329271676986f, + 0.001655828820474164f, + 0.001774273932442011f, + 0.001896643321221287f, + 0.002022907760579356f, + 0.002153029565104709f, + 0.002286963138555204f, + 0.002424654105591249f, + 0.002566039990527927f, + 0.002711049190015392f, + 0.002859602052878106f, + 0.003011609882021581f, + 0.003166975340851216f, + 0.003325592606007947f, + 0.003487347156138999f, + 0.003652115769225347f, + 0.003819766988190932f, + 0.003990160791661657f, + 0.004163149004759460f, + 0.004338575232032592f, + 0.004516275281704776f, + 0.004696077226065694f, + 0.004877801369702575f, + 0.005061261175365414f, + 0.005246262760259225f, + 0.005432605634097002f, + 0.005620082968897619f, + 0.005808481837004595f, + 0.005997583515661679f, + 0.006187164045980849f, + 0.006376994441064236f, + 0.006566841257680600f, + 0.006756466702660143f, + 0.006945629644096785f, + 0.007134085474240178f, + 0.007321586857189369f, + 0.007507884388699728f, + 0.007692726710717013f, + 0.007875861286146892f, + 0.008057034853723447f, + 0.008235993962285608f, + 0.008412485423992495f, + 0.008586256905270668f, + 0.008757057550423931f, + 0.008924638381879985f, + 0.009088752763977616f, + 0.009249157391806035f, + 0.009405612190690901f, + 0.009557881349450560f, + 0.009705733651032743f, + 0.009848943025250930f, + 0.009987289003226731f, + 0.010120557317645952f, + 0.010248540384643352f, + 0.010371037696321509f, + 0.010487856281889540f, + 0.010598811426250850f, + 0.010703726661456589f, + 0.010802434494593470f, + 0.010894776824678817f, + 0.010980605060844476f, + 0.011059780725514858f, + 0.011132175645830765f, + 0.011197672374601442f, + 0.011256164283833567f, + 0.011307555970121824f, + 0.011351763540287503f, + 0.011388714558166329f, + 0.011418348423280301f, + 0.011440616600089638f, + 0.011455482402780947f, + 0.011462921415360990f, + 0.011462921415360990f, + 0.011455482402780947f, + 0.011440616600089638f, + 0.011418348423280301f, + 0.011388714558166329f, + 0.011351763540287503f, + 0.011307555970121824f, + 0.011256164283833567f, + 0.011197672374601442f, + 0.011132175645830765f, + 0.011059780725514858f, + 0.010980605060844476f, + 0.010894776824678817f, + 0.010802434494593470f, + 0.010703726661456589f, + 0.010598811426250850f, + 0.010487856281889540f, + 0.010371037696321509f, + 0.010248540384643352f, + 0.010120557317645952f, + 0.009987289003226731f, + 0.009848943025250930f, + 0.009705733651032743f, + 0.009557881349450560f, + 0.009405612190690901f, + 0.009249157391806035f, + 0.009088752763977616f, + 0.008924638381879985f, + 0.008757057550423931f, + 0.008586256905270668f, + 0.008412485423992495f, + 0.008235993962285608f, + 0.008057034853723447f, + 0.007875861286146892f, + 0.007692726710717013f, + 0.007507884388699728f, + 0.007321586857189369f, + 0.007134085474240178f, + 0.006945629644096785f, + 0.006756466702660143f, + 0.006566841257680600f, + 0.006376994441064236f, + 0.006187164045980849f, + 0.005997583515661679f, + 0.005808481837004595f, + 0.005620082968897619f, + 0.005432605634097002f, + 0.005246262760259225f, + 0.005061261175365414f, + 0.004877801369702575f, + 0.004696077226065694f, + 0.004516275281704776f, + 0.004338575232032592f, + 0.004163149004759460f, + 0.003990160791661657f, + 0.003819766988190932f, + 0.003652115769225347f, + 0.003487347156138999f, + 0.003325592606007947f, + 0.003166975340851216f, + 0.003011609882021581f, + 0.002859602052878106f, + 0.002711049190015392f, + 0.002566039990527927f, + 0.002424654105591249f, + 0.002286963138555204f, + 0.002153029565104709f, + 0.002022907760579356f, + 0.001896643321221287f, + 0.001774273932442011f, + 0.001655828820474164f, + 0.001541329271676986f, + 0.001430788817328081f, + 0.001324213422447449f, + 0.001221601170177604f, + 0.001122943571650730f, + 0.001028224584686942f, + 0.000937421598757782f, + 0.000850505496981770f, + 0.000767440808596336f, + 0.000688186201030564f, + 0.000612694289527581f, + 0.000540912739938505f, + 0.000472783700962668f, + 0.000408244468331575f, + 0.000347228091667187f, + 0.000289663252276950f, + 0.000235474395169584f, + 0.000184583050199368f, + 0.000136906695012963f, + 0.000092360432854175f, + 0.000050856088211618f, + 0.000012303734435184f, + -0.000023389083735015f, + -0.000056316612617103f, + -0.000086574168670878f, + -0.000114258627064630f, + -0.000139467943568298f, + -0.000162300101972573f, + -0.000182854056621652f, + -0.000201228717970838f, + -0.000217522684614226f, + -0.000231834561467387f, + -0.000244261829079865f, + -0.000254902132867105f, + -0.000263850662609383f, + -0.000271202733437524f, + -0.000277051522643753f, + -0.000281488659987540f, + -0.000284603980740463f, + -0.000286486063219693f, + -0.000287220112764771f, + -0.000286890694598539f, + -0.000285578633373008f, + -0.000283363923695878f, + -0.000280322370041046f, + -0.000276528686849870f, + -0.000272054419087176f, + -0.000266967862740791f, + -0.000261335292980978f, + -0.000255220180724547f, + -0.000248682177854843f, + -0.000241779257421431f, + -0.000234565855614429f, + -0.000227093646507866f, + -0.000219411598860001f, + -0.000211565351775375f, + -0.000203599379753965f, + -0.000195552549576070f, + -0.000187464129074148f, + -0.000179368841745378f, + -0.000171298895948762f, + -0.000163284378055491f, + -0.000155353239032747f, + -0.000147529334756596f, + -0.000139836270835869f, + -0.000132293212128623f, + -0.000124919754739577f, + -0.000117729935644196f, + -0.000110738977492950f, + -0.000103959504668590f, + -0.000097399649098627f, + -0.000091070103041806f, + -0.000084976788235246f, + -0.000079124725926570f, + -0.000073517650784389f, + -0.000068158618146586f, + -0.000063047547807853f, + -0.000058185242147041f, + -0.000053568215176887f, + -0.000049199353227621f, + -0.000045067469478981f, + -0.000041176665997414f, + -0.000037517497377010f, + -0.000034086060833210f, + -0.000030875236885189f, + -0.000027881953296601f, + -0.000025093613992638f, + -0.000022508204619172f, + -0.000020111369902626f, + -0.000017906061357310f, + -0.000015868003792231f, + -0.000014003128525449f, + -0.000012302324525658f, + -0.000010742797132820f, + -0.000009336504822940f, + -0.000008064028056128f, + -0.000006916263845337f, + -0.000005880953015414f, + -0.000004959329780957f, + -0.000004141892670381f, + -0.000003423524464373f, + -0.000002790586794678f, + -0.000006032200297229f +}; + diff --git a/code/Decoder/func_timer.h b/code/Decoder/func_timer.h new file mode 100644 index 0000000..0347f72 --- /dev/null +++ b/code/Decoder/func_timer.h @@ -0,0 +1,142 @@ +/* + + Copyright 2018 Michal Fratczak + + This file is part of habdec. + + habdec 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 3 of the License, or + (at your option) any later version. + + habdec 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 habdec. If not, see . +*/ + +#pragma once + +// fancy decorator to measure execution time + +// #if defined(__cpp_decltype_auto) +#if 0 +#define FUNC_TIMER 1 + +#include +#include +#include +#include + +//https://stackoverflow.com/questions/28498852/c-function-decorator/33642149 + + +namespace habdec +{ + + +template +struct RetWrapper +{ + template + RetWrapper(Tfunc &&func, Targs &&... args) + : val(std::forward(func)(std::forward(args)...)) {} + + //T&& value() { return std::move(val); } + T value() { return val; } + + +private: + T val; +}; + + +template <> +struct RetWrapper +{ + template + RetWrapper(Tfunc &&func, Targs &&... args) + { + std::forward(func)(std::forward(args)...); + } + + void value() {} +}; + + + +//template +template +//auto decorate(Tfunc &&func, Tbefore &&before, Tafter &&after) +auto AddTimer(Tfunc&& func, std::string name) +{ + return [ + func = std::forward(func), + name + //before = std::forward(before), + //after = std::forward(after) + ] (auto&& ... args) -> decltype(auto) + { + //before(std::forward(args)...); + + using namespace std; + typedef chrono::microseconds DurT; + static int count = 0; + static DurT dur_min = DurT::max(); + static DurT dur_max = DurT::min(); + static DurT dur_sum = DurT::zero(); + static auto time_start = chrono::high_resolution_clock::now(); + + auto _start = chrono::high_resolution_clock::now(); + //////////////////////////////////////////////////////////// + RetWrapper> ret( + func, std::forward(args)... + ); + //////////////////////////////////////////////////////////// + auto _end = chrono::high_resolution_clock::now(); + + DurT _duration = chrono::duration_cast(_end - _start); + ++count; + dur_sum += _duration; + if(_duration < dur_min) + dur_min = _duration; + if(_duration > dur_max) + dur_max = _duration; + + if( chrono::duration_cast( + chrono::high_resolution_clock::now() - time_start).count() >= 1000 + ) + { + DurT avg = dur_sum / count; + +#define FUNC_TIMER_NO_PRINT 1 +#if !defined(FUNC_TIMER_NO_PRINT) + cout<(args)...); + + // does not work if return directly + return ret.value(); + //auto result = ret.value(); + //return result; + }; +} + + +} // namespace habdec + +#endif //#if defined(__cpp_nontype_template_parameter_auto) diff --git a/code/Decoder/habdec_windows.h b/code/Decoder/habdec_windows.h new file mode 100644 index 0000000..a2471bd --- /dev/null +++ b/code/Decoder/habdec_windows.h @@ -0,0 +1,53 @@ +/* + + Copyright 2018 Michal Fratczak + + This file is part of habdec. + + habdec 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 3 of the License, or + (at your option) any later version. + + habdec 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 habdec. If not, see . +*/ + +#pragma once + +#include +#include + + +template +inline T_flt_ sinc(T_flt_ x) +{ + if(x) + return sin(x)/x; + else + return 1; +} + + +template // float like types... +inline T_flt_ BlackmanHarris(const size_t x, const size_t N) +{ + static const T_flt_ a0 = 0.35874; + static const T_flt_ a1 = 0.48829; + static const T_flt_ a2 = 0.14128; + static const T_flt_ a3 = 0.01168; + static const T_flt_ PI2 = 2.0*M_PI; + static const T_flt_ PI4 = 4.0*M_PI; + static const T_flt_ PI6 = 6.0*M_PI; + + const T_flt_ N_1 = N-1; + + T_flt_ w = a0 - a1*cos(PI2*x / N_1) + a2*cos(PI4*x / N_1) - a3*cos(PI6*x / N_1); + + return w; +} diff --git a/code/Decoder/print_habhub_sentence.cpp b/code/Decoder/print_habhub_sentence.cpp new file mode 100644 index 0000000..f6755e3 --- /dev/null +++ b/code/Decoder/print_habhub_sentence.cpp @@ -0,0 +1,65 @@ +/* + + Copyright 2018 Michal Fratczak + + This file is part of habdec. + + habdec 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 3 of the License, or + (at your option) any later version. + + habdec 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 habdec. If not, see . +*/ + +#include "print_habhub_sentence.h" + +#include +#include +#include "CRC.h" +#include "common/console_colors.h" + + +namespace habdec +{ + + +void printHabhubSentence( + const std::string& callsign, + const std::string& data, + const std::string in_crc ) +{ + using namespace std; + + static int success = 0; + static int failure = 0; + + if( in_crc == CRC(callsign + string(",") + data) ) + { + cout<. +*/ + +#pragma once + +#include + +namespace habdec +{ + +void printHabhubSentence( + const std::string& callsign, + const std::string& data, + const std::string in_crc ); + +} // namespace habdec \ No newline at end of file diff --git a/code/Decoder/sentence_extract.cpp b/code/Decoder/sentence_extract.cpp new file mode 100644 index 0000000..481047c --- /dev/null +++ b/code/Decoder/sentence_extract.cpp @@ -0,0 +1,70 @@ +/* + + Copyright 2018 Michal Fratczak + + This file is part of habdec. + + habdec 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 3 of the License, or + (at your option) any later version. + + habdec 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 habdec. If not, see . +*/ + +#include "sentence_extract.h" + +#include + +namespace habdec +{ + +std::regex HABHUB_REGEX( R"_(.*?(\$+)([\w,\-]+?),(.+?)(\*|\$)(\w\w\w\w).*)_" ); + +std::map extractSentence(std::string stream) +{ + using namespace std; + + // replace '\n' in stream with spaces, otherwise regex will fail (C++ 11 issue) + replace( stream.begin(), stream.end(), '\n', ' '); + + map result; + result["success"] = string("ERR"); + + const int CRC_LEN = 4; // usually 4 chars after * + + if(stream.find("*") < string::npos-CRC_LEN) + { + smatch match; + regex_match(stream, match, HABHUB_REGEX); + + if(match.size() >= 5) + { + const string callsign = match[2]; + const string data = match[3]; + const string data_end = match[4]; // * or another $ + const string _crc = match[5]; + + const size_t cut = min( stream.size(), size_t(match.position(4)+CRC_LEN) ); + stream = stream.substr( cut ); + + result["success"] = string("OK"); + result["callsign"] = callsign; + result["data"] = data; + result["crc"] = _crc; + result["stream"] = stream; + + } + + } + + return result; +} + +} // namespace habdec diff --git a/code/Decoder/sentence_extract.h b/code/Decoder/sentence_extract.h new file mode 100644 index 0000000..e6ae579 --- /dev/null +++ b/code/Decoder/sentence_extract.h @@ -0,0 +1,34 @@ +/* + + Copyright 2018 Michal Fratczak + + This file is part of habdec. + + habdec 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 3 of the License, or + (at your option) any later version. + + habdec 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 habdec. If not, see . +*/ + +#pragma once + +#include +#include +#include +#include + + +namespace habdec +{ + +std::map extractSentence(std::string i_str); + +} // namespace habdec \ No newline at end of file diff --git a/code/IQSource/CMakeLists.txt b/code/IQSource/CMakeLists.txt new file mode 100644 index 0000000..e65b53d --- /dev/null +++ b/code/IQSource/CMakeLists.txt @@ -0,0 +1,29 @@ + + +#include_directories( ${PROJECT_SOURCE_DIR} ) +include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ) + + +find_package(SoapySDR REQUIRED) # this reverts CMAKE_CXX_STANDARD to '11' +#set ( CMAKE_CXX_STANDARD 17 ) +include_directories( ${SoapySDR_INCLUDE_DIRS} ) +message( "SoapySDR_INCLUDE_DIRS:" ${SoapySDR_INCLUDE_DIRS} ) +message( "SoapySDR_LIBRARIESL:" ${SoapySDR_LIBRARIES} ) + +# RTTY DECODER +set ( IQSource_src + IQSource_File.h + IQSource.h + IQSource_SoapySDR.h IQSource_SoapySDR.cpp + ) + + +if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") + SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wshadow" ) + SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-class-memaccess" ) + SET( CMAKE_CXX_FLAGS " -O3 " ) +endif() + + +add_library( IQSource ${IQSource_src}) +target_link_libraries( IQSource ${SoapySDR_LIBRARIES} ) diff --git a/code/IQSource/IQSource.h b/code/IQSource/IQSource.h new file mode 100644 index 0000000..d6c9bec --- /dev/null +++ b/code/IQSource/IQSource.h @@ -0,0 +1,46 @@ +/* + + Copyright 2018 Michal Fratczak + + This file is part of habdec. + + habdec 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 3 of the License, or + (at your option) any later version. + + habdec 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 habdec. If not, see . +*/ + +#pragma once + +#include +#include + +namespace habdec +{ + + +class IQSource +{ +public: + virtual bool init() = 0; + virtual bool start() = 0; + virtual bool stop() = 0; + virtual bool isRunning() const = 0; + virtual std::string type() const = 0; + virtual size_t count() const = 0; + virtual size_t get(void* p_data, const size_t i_count) = 0; + virtual double samplingRate() const = 0; + virtual bool setOption(const std::string& option, const void* p_data) = 0; + virtual bool getOption(const std::string& option, void* p_data) = 0; +}; + + +} // namespace habdec \ No newline at end of file diff --git a/code/IQSource/IQSource_File.h b/code/IQSource/IQSource_File.h new file mode 100644 index 0000000..bc40796 --- /dev/null +++ b/code/IQSource/IQSource_File.h @@ -0,0 +1,262 @@ +/* + + Copyright 2018 Michal Fratczak + + This file is part of habdec. + + habdec 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 3 of the License, or + (at your option) any later version. + + habdec 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 habdec. If not, see . +*/ + +#pragma once + +#include "IQSource.h" + +#include +#include +#include +#include +#include + +#include +#include + + +namespace habdec +{ + +template +class IQSource_File : public habdec::IQSource +{ +public: + typedef T TValue; + typedef std::complex TComplex; + + bool start(); + bool stop(); + bool isRunning() const; + size_t count() const; + size_t get(void* p_data, const size_t i_count); + std::string type() const {return std::string("File");}; + double samplingRate() const; + bool setOption(const std::string& option, const void* p_data); + bool getOption(const std::string& option, void* p_data); + + bool init(); + + ~IQSource_File(); + +private: + bool b_is_running_ = false; + bool b_is_realtime_ = true; + bool b_loop_ = false; + + std::ifstream file_handle_; + std::string file_path_; + + double sampling_rate_ = 0; + size_t count_ = 0; +}; + +} // namespace + + + +namespace +{ +std::ifstream::pos_type filesize(const char* filename) +{ + std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary); + return in.tellg(); +} +} // namespace + +namespace habdec +{ + +template +bool IQSource_File::start() +{ + if(!file_handle_.is_open()) + return false; + b_is_running_ = true; + return true; +} + + +template +bool IQSource_File::stop() +{ + if(!file_handle_.is_open()) + return false; + b_is_running_ = true; + return true; +} + + +template +bool IQSource_File::isRunning() const +{ + if(!file_handle_.is_open()) + return false; + return b_is_running_; +} + + +template +size_t IQSource_File::count() const +{ + return count_; +} + + +template +size_t IQSource_File::get(void* p_data, const size_t i_count) +{ + using namespace std; + + if(!file_handle_.is_open()) + { + std::cout<<"file_handle_ == 0"<(p_data), min(i_count, count_) * sizeof(TComplex) ); + const size_t read_count = file_handle_.gcount() / sizeof(TComplex); + + if(!file_handle_) + { + if(read_count != i_count) + cout<<"IQSource_File::get() read less than desired: "<(wait) ); + } + + return read_count; +} + + +template +double IQSource_File::samplingRate() const +{ + return sampling_rate_; +} + + +template +IQSource_File::~IQSource_File() +{ + if(file_handle_) + { + stop(); + // fclose(file_handle_); + file_handle_.close(); + } +} + + +template +bool IQSource_File::init() +{ + count_ = filesize( file_path_.c_str() ) / sizeof(TComplex); + file_handle_.open( file_path_, std::ios::binary ); + if(!file_handle_.is_open()) + return false; + return true; +} + + +template +bool IQSource_File::setOption(const std::string& option, const void* p_data) +{ + void* p_data_nonconst = const_cast(p_data); + + if(option == "file_string") + { + file_path_ = *reinterpret_cast(p_data_nonconst); + } + if(option == "sampling_rate_double") + { + sampling_rate_ = *reinterpret_cast(p_data_nonconst); + } + else if(option == "realtime_bool") + { + b_is_realtime_ = *reinterpret_cast(p_data_nonconst); + } + else if(option == "loop_bool") + { + b_loop_ = *reinterpret_cast(p_data_nonconst); + } + else + { + std::cout<<"IQSource_File::setOption error. Unknown option: "< +bool IQSource_File::getOption(const std::string& option, void* p_data) +{ + if(option == "file_string") + { + *reinterpret_cast(p_data) = file_path_; + } + if(option == "sampling_rate_double") + { + *reinterpret_cast(p_data) = sampling_rate_; + } + else if(option == "realtime_bool") + { + *reinterpret_cast(p_data) = b_is_realtime_; + } + else if(option == "loop_bool") + { + *reinterpret_cast(p_data) = b_loop_; + } + else + { + std::cout<<"IQSource_File::getOption error. Unknown option: "<. +*/ + + +#include "IQSource_SoapySDR.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace habdec +{ + +bool IQSource_SoapySDR::start() +{ + if(!p_device_) + return false; + + int result = 0; + if(!b_is_running_) + result = p_device_->activateStream(p_stream_); + + if(result) + { + std::cout<<"IQSource_SoapySDR::start error. "<deactivateStream(p_stream_); + + if(result) + { + std::cout<<"IQSource_SoapySDR::stop error. "<(p_data) }; + int reveice_flags = 0; + long long time_ns = 0; + const int result = p_device_->readStream(p_stream_, buffs, i_count, reveice_flags, time_ns); + + if(result<0) + { + std::cout<<"IQSource_SoapySDR::get error."<(result); +} + + +double IQSource_SoapySDR::samplingRate() const +{ + return sampling_rate_; +} + + +IQSource_SoapySDR::~IQSource_SoapySDR() +{ + if(p_device_) + { + stop(); + p_device_->closeStream(p_stream_); + //SoapySDR::Device::unmake(p_device_.get()); + } +} + + +bool IQSource_SoapySDR::init() +{ + p_device_.reset( SoapySDR::Device::make(soapysdr_kwargs_) ); + + if(!p_device_) + return false; + + using namespace std; + + cout<<"IQSource_SoapySDR::init"<getDriverKey(); + cout<<'\t'<<"driver_key "<getHardwareKey(); + + const auto serial_it = soapysdr_kwargs_.find("serial"); + if(serial_it != soapysdr_kwargs_.end()) + hwinfo_serial_ = serial_it->second; + + // hw info + // cout<<'\t'<<"hw_info:"<getHardwareInfo(); + for(const auto& it : hw_info) + { + // cout<<"\t\tproperty:: "<listGains(SOAPY_SDR_RX,0)) + hwinfo_gains_.push_back(gain); + + // freq range + const SoapySDR::RangeList freq_range_list = p_device_->getFrequencyRange(SOAPY_SDR_RX, 0); + hwinfo_freq_min_ = freq_range_list.front().minimum(); + hwinfo_freq_max_ = freq_range_list.back().maximum(); + + // sampling rates + hwinfo_sampling_rates_ = p_device_->listSampleRates(SOAPY_SDR_RX, 0); + sort(hwinfo_sampling_rates_.begin(), hwinfo_sampling_rates_.end()); + + // stream formats + hwinfo_stream_formats_.clear(); + for(const auto stream_format : p_device_->getStreamFormats(SOAPY_SDR_RX, 0)) // doubles + hwinfo_stream_formats_.push_back(stream_format); + + // gain range + const SoapySDR::Range gain_range = p_device_->getGainRange(SOAPY_SDR_RX, 0); + hwinfo_gain_min_ = gain_range.minimum(); + hwinfo_gain_max_ = gain_range.maximum(); + + // init + + sampling_rate_ = hwinfo_sampling_rates_.back(); + if(hwinfo_hwkey_ != "Airspy") + sampling_rate_ = hwinfo_sampling_rates_[3]; + p_device_->setSampleRate(SOAPY_SDR_RX, 0, sampling_rate_); + + p_device_->setGain( SOAPY_SDR_RX, 0, (hwinfo_gain_max_ - hwinfo_gain_min_)/2 ); + p_device_->setFrequency( SOAPY_SDR_RX, 0, 434274500 ); + p_stream_ = p_device_->setupStream(SOAPY_SDR_RX, SOAPY_SDR_CF32); + + + // PRINT INFO + ///////////////// + + // hw info + cout<<'\t'<<"hw_key "<getFrontendMapping(SOAPY_SDR_RX)<listBandwidths(SOAPY_SDR_RX, 0)) // doubles + cout<hasDCOffsetMode(SOAPY_SDR_RX, 0)<hasFrequencyCorrection(SOAPY_SDR_RX, 0)<(p_data); + + bool b_verbose = false; + + if(option == "SoapySDR_Kwargs") + { + soapysdr_kwargs_ = *reinterpret_cast(p_data_nonconst); + return true; + } + + if(!p_device_) + { + cout<<"IQSource_SoapySDR::setOption no device initialized."<(p_data_nonconst); + cout<<"Setting "<setSampleRate(SOAPY_SDR_RX, 0, value); + sampling_rate_ = p_device_->getSampleRate(SOAPY_SDR_RX, 0); + cout<<"Set "<(p_data_nonconst); + if(p_device_) + { + if(b_verbose) + cout<<"Set "<setFrequency( SOAPY_SDR_RX, 0, value ); + } + return true; + } + else if(option == "gain_double") + { + double value = *reinterpret_cast(p_data_nonconst); + if(p_device_) + { + p_device_->setGain( SOAPY_SDR_RX, 0, value ); + if(b_verbose) + cout<<"Set "<(p_data_nonconst); + if(p_device_) + { + if(b_verbose) + cout<<"Set "<writeSetting("biastee", "true"); + else + p_device_->writeSetting("biastee", "false"); + } + return true; + } + else + { + cout<<"IQSource_SoapySDR::setOption error. Unknown option: "<(p_data) = sampling_rate_; + if(b_verbose) + cout<<"getOption "<(p_data)<(p_data) = p_device_->getFrequency( SOAPY_SDR_RX, 0); + if(b_verbose) + cout<<"getOption "<(p_data)<(p_data) = p_device_->getGain( SOAPY_SDR_RX, 0 ); + if(b_verbose) + cout<<"getOption "<(p_data)<readSetting("biastee") == string("true"); + *reinterpret_cast(p_data) = biastee_val; + if(b_verbose) + cout<<"getOption "<. +*/ + +#pragma once + +#include "IQSource.h" + +#include +#include + +#include +#include + + +namespace habdec +{ + + +class IQSource_SoapySDR : public habdec::IQSource +{ +public: + ~IQSource_SoapySDR(); + + bool start(); + bool stop(); + bool isRunning() const; + size_t count() const; + size_t get(void* p_data, const size_t i_count); + std::string type() const {return std::string("SoapySDR");}; + double samplingRate() const; + bool setOption(const std::string& option, const void* p_data); + bool getOption(const std::string& option, void* p_data); + + bool init(); + +private: + std::unique_ptr p_device_ = 0; + SoapySDR::Stream* p_stream_ = 0; + + bool b_is_running_ = false; + double sampling_rate_ = 0; + + // SoapySDR hardware info + SoapySDR::Kwargs soapysdr_kwargs_; // used for init() + std::string hwinfo_hwkey_; + std::string hwinfo_serial_; + size_t hwinfo_device_id_; + + std::vector hwinfo_gains_; + std::vector hwinfo_sampling_rates_; + std::vector hwinfo_stream_formats_; + + double hwinfo_freq_min_ = 0; + double hwinfo_freq_max_ = 0; + double hwinfo_gain_min_ = 0; + double hwinfo_gain_max_ = 0; +}; + + +} // namespace habdec \ No newline at end of file diff --git a/code/common/console_colors.cpp b/code/common/console_colors.cpp new file mode 100644 index 0000000..405c3ee --- /dev/null +++ b/code/common/console_colors.cpp @@ -0,0 +1,28 @@ +#ifdef __linux__ + const char* C_BLACK = "\033[1;30m"; + const char* C_RED = "\033[1;31m"; + const char* C_GREEN = "\033[1;32m"; + const char* C_BROWN = "\033[1;33m"; + const char* C_BLUE = "\033[1;34m"; + const char* C_MAGENTA = "\033[1;35m"; + const char* C_CYAN = "\033[1;36m"; + const char* C_LIGHTGREY = "\033[1;37m"; + const char* C_OFF = "\033[0m"; + const char* C_CLEAR = "\033[2K"; +// #elif _WIN32 +// #elif __APPLE__ +// #elif __unix__ // all unices not caught above +// #elif defined(_POSIX_VERSION) +#else + const char* C_BLACK = ""; + const char* C_RED = ""; + const char* C_GREEN = ""; + const char* C_BROWN = ""; + const char* C_BLUE = ""; + const char* C_MAGENTA = ""; + const char* C_CYAN = ""; + const char* C_LIGHTGREY = ""; + const char* C_OFF = ""; + const char* C_CLEAR = ""; + +#endif \ No newline at end of file diff --git a/code/common/console_colors.h b/code/common/console_colors.h new file mode 100644 index 0000000..047caa4 --- /dev/null +++ b/code/common/console_colors.h @@ -0,0 +1,12 @@ +#pragma once + +extern const char* C_BLACK; +extern const char* C_RED; +extern const char* C_GREEN; +extern const char* C_BROWN; +extern const char* C_BLUE; +extern const char* C_MAGENTA; +extern const char* C_CYAN; +extern const char* C_LIGHTGREY; +extern const char* C_OFF; +extern const char* C_CLEAR; \ No newline at end of file diff --git a/code/fltkGUI/CMakeLists.txt b/code/fltkGUI/CMakeLists.txt new file mode 100644 index 0000000..7129f75 --- /dev/null +++ b/code/fltkGUI/CMakeLists.txt @@ -0,0 +1,17 @@ + +include_directories( ${PROJECT_SOURCE_DIR} ) +include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ) + +set ( FLTK_SKIP_FLUID True ) +find_package( FLTK REQUIRED ) +include_directories( ${FLTK_INCLUDE_DIR} ) +message( "FLTK Include:" ${FLTK_INCLUDE_DIR} ) +message( "FLTK Lib:" ${FLTK_LIBRARIES} ) + +SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-variable") +SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter") + +add_executable (habdec_fltk main.cpp gui_utils.h ) +target_link_libraries( habdec_fltk Decoder ${FLTK_LIBRARIES} IQSource Decoder pthread ) + +install ( TARGETS habdec_fltk DESTINATION ${CMAKE_INSTALL_PREFIX} ) diff --git a/code/fltkGUI/gui_utils.h b/code/fltkGUI/gui_utils.h new file mode 100644 index 0000000..378d95d --- /dev/null +++ b/code/fltkGUI/gui_utils.h @@ -0,0 +1,234 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#define BG_COLOR 45 +#define TICK_COLOR 50 +#define CIRC_COLOR 0 + +typedef uchar LUMA_T; +typedef uchar RGB_T; + +extern const int RES_X; +extern const int RES_Y; + +extern RGB_T SPECTRUM_BITMAP_RGB []; +extern RGB_T TIME_BITMAP_RGB []; + + +template +void SimpleDownsampleVector(std::vector& vec, size_t factor) +{ + using namespace std; + + if(!vec.size()) + return; + + if(factor<2) + return; + + const size_t _S = vec.size() / factor; + + if(factor == 2) + { + for(size_t i=0; i<_S; ++i) + vec[i] = .5 * (vec[2*i] + vec[2*i+1]); + } + else + { //somehow does not work for ractor=2 + for(size_t i=0; i<_S; ++i) + { + for(size_t j=1; j +void Histogram2Bitmap(COLOR_T* p_bitmap, int spectr_res_x, int spectr_res_y, + //float* p_values, int num_values, + const std::vector& values, + float min_value, float max_value, float avg_value, + float offset, float scale, + bool is_rgb) +{ + using namespace std; + + if(min_value == max_value) + { + min_value = *min_element( values.begin(), values.end() ); + max_value = *max_element( values.begin(), values.end() ); + } + + //if(fabs(min_value) > 100 || fabs(max_value) > 100) return; + + static float total_scale = fabs(max_value - min_value); + //cout<<"total_scale "< 1) val_0_1 = 1; + + int y_tip = val_0_1 * (spectr_res_y-1); + y_tip = spectr_res_y - 1 - y_tip; + + int x = pix_x; + for(int y=y_tip; y 1) _b = 1; + + size_t off = y*spectr_res_x+x; + if(is_rgb) + { + off *= 3; + + if(pix_x > .5f * spectr_res_x) + { + p_bitmap[off] = (COLOR_T)(_b * 255); + p_bitmap[off+1] = (COLOR_T)(_b * 0); + p_bitmap[off+2] = 0; + } + else + { + p_bitmap[off] = 0; + p_bitmap[off+1] = (COLOR_T)(_b * 155); + p_bitmap[off+2] = (COLOR_T)(_b * 255); + } + } + else + { + p_bitmap[off] = (COLOR_T)(_b * 255);//220; + } + } + } + + // center vertical line + for(int y=0; y +void VectorToBitmap(COLOR_T* p_bitmap, const std::vector& samples_, int m_res_x, int m_res_y) +{ + auto abs_sum = [&](TReal a, TReal b){return abs(a) + abs(b);}; + const TReal avg = accumulate(samples_.begin(), samples_.end(), .0, abs_sum) / samples_.size(); + + for(int x=0; x= m_res_y) + y = m_res_y - 1; + + size_t off = y*m_res_x+x; + if(samples_[_x_0_1 * samples_.size()] > 0) + { + p_bitmap[3*off+0] = (RGB_T)(255); + p_bitmap[3*off+1] = (RGB_T)(0); + p_bitmap[3*off+2] = (RGB_T)(0); + } + else + { + p_bitmap[3*off+0] = (RGB_T)(0); + p_bitmap[3*off+1] = (RGB_T)(150); + p_bitmap[3*off+2] = (RGB_T)(255); + } + } +} + + +template +void HorizontalLineToBitmap(COLOR_T* p_bitmap, int spectr_res_x, int y, bool is_rgb, + short r=0, short g=200, short b=250) +{ + for(int x=0; x +void VerticalLineToBitmap(COLOR_T* p_bitmap, int spectr_res_x, int spectr_res_y, int x, bool is_rgb, + short r=0, short g=200, short b=250) +{ + //int x = peak.first; + for(int y=0; y +#include +#include +using namespace std; + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#include "IQSource/IQSource_File.h" +#include "IQSource/IQSource_SoapySDR.h" +#include "Decoder/Decoder.h" + +#include "gui_utils.h" + +using namespace std; +using namespace habdec; + +typedef float TReal; +IQVector G_SAMPLES; +Decoder G_DECODER; +IQSource* G_IQ_SRC_PTR = 0; +double G_FREQ = 100e6; // 434.274451e6; +double G_SAMPLING_RATE = 0; +double G_FREQ_SPAN = 0; +bool DO_CORRECTION = false; + + +void SetFrequency(double freq) +{ + if(G_IQ_SRC_PTR) + { + G_FREQ = freq; + double freq_double = freq; + G_IQ_SRC_PTR->setOption("frequency_double", &freq_double); + } +} + +void RunDecoder() +{ + size_t max_samples_num = 256*256; // it doesn't work for small batches and radio ... + G_SAMPLES.resize(max_samples_num); + + while(1) + { + typedef std::chrono::nanoseconds TDur; + + auto _start = std::chrono::high_resolution_clock::now(); + size_t count = G_IQ_SRC_PTR->get( G_SAMPLES.data(), G_SAMPLES.size() ); + G_DECODER.pushSamples(G_SAMPLES); + + G_DECODER(); + TDur _duration = std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - _start); + // std::cout<<"Decoder duration "<<_duration.count()<<" nS "< + (std::chrono::high_resolution_clock::now() - last_afc_time).count() > 1000000 + ) + { + double freq_corr = G_DECODER.getFrequencyCorrection(); + if(DO_CORRECTION) + { + if( 100 < abs(freq_corr) ) + { + G_FREQ += freq_corr; + G_IQ_SRC_PTR->setOption("frequency_double", &G_FREQ); + G_DECODER.resetFrequencyCorrection(freq_corr); + last_afc_time = std::chrono::high_resolution_clock::now(); + } + } + } + } +} + + +int InitProcess(int baud, int a_bits, int a_stops, std::string fname) +{ + if(fname != "") + { + cout<<"File"<; + G_IQ_SRC_PTR->setOption("sampling_rate_double", &G_SAMPLING_RATE); + G_IQ_SRC_PTR->setOption("file_string", &fname); + bool realtime = false; + G_IQ_SRC_PTR->setOption("realtime_bool", &realtime); + bool loop = true; + G_IQ_SRC_PTR->setOption("loop_bool", &loop); + + if( !G_IQ_SRC_PTR->init() ) + { + cout<<"IQSource_File::init failed."<count()<setOption("SoapySDR_Kwargs", &device); + + if( !G_IQ_SRC_PTR->init() ) + { + cout<<"IQSource_SoapySDR::init failed."<getOption("sampling_rate_double", &sr); + cout<setOption("gain_double", &gain); + + G_FREQ = 434.274e6; + SetFrequency(G_FREQ); // RTL + } + + cout<<"G_IQ_SRC_PTR->sampling_rate() "<samplingRate()<start() ) + { + cout<<"IQSource_File::start failed."<isRunning() ) + { + cout<<"IQSource_File::isRunning failed."<(1000) ); + + std::thread* p_thread = new std::thread(RunDecoder); + + return 0; +} + + + +///////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////// + + +typedef uchar LUMA_T; +typedef uchar RGB_T; +#define BG_COLOR 45 +const int RES_X = 1024; +const int RES_Y = 256; + +RGB_T SPECTRUM_BITMAP_RGB [RES_X*RES_Y*3]; // FFT +RGB_T TIME_BITMAP_RGB [RES_X*RES_Y*3]; // Demodulated samples + +class FreqViewport : public Fl_Box +{ +public: + FreqViewport(int X,int Y,int W,int H, const char*L=0) + : Fl_Box(X,Y,W,H,L), m_x(X), m_y(Y), m_res_x(W), m_res_y(H) + { + box(FL_FLAT_BOX); + color(BG_COLOR); + Fl::add_timeout(0.1, FreqViewport_CB, (void*)this); + } + +private: + const int m_x; + const int m_y; + const int m_res_x; + const int m_res_y; + + // frequency drag + int m_xMB; + bool m_DRAG; + int m_xMB_x; + int m_drag_freq_start; + + // IQVector m_frequencies_; + std::vector m_magnitudesArr; + + int handle(int event) + { + if(event == FL_MOUSEWHEEL) + { + size_t decimation_factor = G_DECODER.getDecimationFactor(); + size_t new_decim_exp = log2(decimation_factor) - Fl::event_dy(); + cout<<"Decimation: "< spectr_inf = G_DECODER.getSpectrumInfo(); + if(!spectr_inf.size()) + return; + m_magnitudesArr = spectr_inf; + + if( !m_magnitudesArr.size() ) + { + cout<<"if( !m_magnitudesArr.size() )"< low_level(25, spectr_inf.min_); + low_level.add(spectr_inf.min_); + // double low_level = -300; + + nf = (nf > (double)low_level) ? nf : (double)low_level; + + ClearBitmap(SPECTRUM_BITMAP_RGB, m_res_x, m_res_y, 3); + Histogram2Bitmap(SPECTRUM_BITMAP_RGB, m_res_x, m_res_y, + m_magnitudesArr, + low_level, 0, 0, + .0, .99, true); + + + if(spectr_inf.peak_left_valid_) + VerticalLineToBitmap(SPECTRUM_BITMAP_RGB, m_res_x, m_res_y, pl, true, 200, 50, 0); + else + VerticalLineToBitmap(SPECTRUM_BITMAP_RGB, m_res_x, m_res_y, pl, true, 50, 12, 0); + if(spectr_inf.peak_right_valid_) + VerticalLineToBitmap(SPECTRUM_BITMAP_RGB, m_res_x, m_res_y, pr, true, 0, 80, 250); + else + VerticalLineToBitmap(SPECTRUM_BITMAP_RGB, m_res_x, m_res_y, pr, true, 0, 20, 60); + + HorizontalLineToBitmap(SPECTRUM_BITMAP_RGB, m_res_x, (nf/low_level)*m_res_y, true, 80,80,80); + HorizontalLineToBitmap(SPECTRUM_BITMAP_RGB, m_res_x, ((nf+nv)/low_level)*m_res_y, true, 80,80,80); + + + Fl_Box::draw(); + fl_draw_image(SPECTRUM_BITMAP_RGB, m_x, m_y, m_res_x, m_res_y, 3, 0); + } + + static void FreqViewport_CB(void *userdata) + { + ((FreqViewport*)userdata)->redraw(); + Fl::repeat_timeout(1.0f/500, FreqViewport_CB, userdata); + } +}; + + +class DemodViewport : public Fl_Box +{ + +public: + const int m_x; + const int m_y; + const int m_res_x; + const int m_res_y; + + DemodViewport(int X,int Y,int W,int H, const char*L=0) + : Fl_Box(X,Y,W,H,L), m_x(X), m_y(Y), m_res_x(W), m_res_y(H) + { + box(FL_FLAT_BOX); + color(BG_COLOR); + Fl::add_timeout(0.1, DemodViewport_CB, (void*)this); + } + + +private: + std::vector samples_; + size_t samples_to_show_cnt_ = 0; + + void draw() + { + if(!samples_to_show_cnt_) + samples_to_show_cnt_ = G_DECODER.getDecimatedSamplingRate() / G_DECODER.getSymbolRate() * 10; // 10 symbols + + const size_t samples_size_pre_insert_ = samples_.size(); + auto demod = G_DECODER.getDemodulated(); + samples_.insert( + samples_.end(), + demod.cbegin(), + demod.cbegin() + min(samples_to_show_cnt_,demod.size()) + ); + + // if(!samples_.size()) + if(samples_.size() < samples_to_show_cnt_) + return; + + ClearBitmap(TIME_BITMAP_RGB, m_res_x, m_res_y, 3); + VectorToBitmap(TIME_BITMAP_RGB, samples_, m_res_x, m_res_y); + HorizontalLineToBitmap(TIME_BITMAP_RGB, m_res_x, m_res_y/2, true); + + Fl_Box::draw(); + fl_draw_image(TIME_BITMAP_RGB, m_x, m_y, m_res_x, m_res_y, 3, 0); + + if(samples_.size() > samples_to_show_cnt_) + samples_.erase( samples_.begin(), samples_.end()-samples_size_pre_insert_); + + } + + static void DemodViewport_CB(void *userdata) + { + ((DemodViewport*)userdata)->redraw(); + Fl::repeat_timeout(1.0f/10, DemodViewport_CB, userdata); + } + + +}; +///////////////////////////////// +///////////////////////////////// + + +void DO_AFC_CB(Fl_Widget* p_w, void* p_user) +{ + DO_CORRECTION = !DO_CORRECTION; +} + +int GUI_MAIN() +{ + Fl::visual(FL_RGB); // disable dithering + + Fl_Double_Window* p_window = new Fl_Double_Window(RES_X, 1.5*RES_Y + 50); + + p_window->begin(); + FreqViewport* p_freqVP = new FreqViewport( 0, 0*RES_Y, RES_X, RES_Y); + DemodViewport* p_timeVP = new DemodViewport( 0, 1*RES_Y, RES_X, RES_Y/2); + auto button = new Fl_Button(0, 1*RES_Y + RES_Y/2 + 10, 100, 20, "AFC"); + button->callback( ( Fl_Callback* ) DO_AFC_CB ); + p_window->end(); + p_window->show(0, 0); + + return Fl::run(); +} + + + +int main(int argc, char** argv) +{ + using namespace std; + + struct thousand_separators : numpunct { + char do_thousands_sep() const { return ','; } + string do_grouping() const { return "\3"; } + }; + cout.imbue( locale(locale(""), new thousand_separators) ); + + + string file(""); + if(argc > 4) + file = string(argv[4]); + cout<<"File: "<(3000)); + +} diff --git a/code/habLogger/habLogger.py b/code/habLogger/habLogger.py new file mode 100755 index 0000000..dc57aaa --- /dev/null +++ b/code/habLogger/habLogger.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python + +import string +import os +import sys +import time +import datetime +import argparse +import json +import re +import traceback +from base64 import b64encode +import httplib +from hashlib import sha256 + + +C_BLACK = "\033[1;30m" +C_RED = "\033[1;31m" +C_GREEN = "\033[1;32m" +C_BROWN = "\033[1;33m" +C_BLUE = "\033[1;34m" +C_MAGENTA = "\033[1;35m" +C_CYAN = "\033[1;36m" +C_LIGHTGREY = "\033[1;37m" +C_OFF = "\033[0m" + +# logname = time.strftime("%Y-%m-%d_%H.%M.%S", time.gmtime()) + ".txt" +logname = time.strftime("%Y-%m-%d_%H", time.gmtime()) + ".txt" +with open('./' + logname, 'a') as f: + f.write(logname + "\n") + + +def prog_opts(): + parser = argparse.ArgumentParser(description='arg parser') + parser.add_argument('--addr', dest='port', action='store', help='port') + parser.add_argument('--station',dest='station', action='store', help='listener callsign') + args = parser.parse_args() + return args + + +def get_config(): + opts = prog_opts() + CFG = {} + + CFG['addr'] = "" + CFG['station'] = "" + + if opts.port: CFG['addr'] = opts.port + if opts.station: CFG['station'] = opts.station + return CFG + + +def crc(i_str): + def _hex(Character): + _hexTable = '0123456789ABCDEF' + return _hexTable[Character] + + CRC = 0xffff + xPolynomial = 0x1021 + + for i in xrange(len(i_str)): + CRC ^= (ord(i_str[i]) << 8) + for j in xrange(8): + if CRC & 0x8000: + CRC = (CRC << 1) ^ 0x1021 + else: + CRC <<= 1 + + result = '' + result += _hex((CRC >> 12) & 15) + result += _hex((CRC >> 8) & 15) + result += _hex((CRC >> 4) & 15) + result += _hex(CRC & 15) + + return result + + +def AppendToLogFile(msg): + with open('./' + logname, 'a') as f: + msg = string.strip(msg) + f.write(msg + '\n\r') + + +def sendSentence(sntc, listener_callsign): + # print ("PYTHON ", sntc, listener_callsign) + # return + + sentence = sntc + + if sentence[-1] != '\n': sentence += '\n' + if sentence[0] != '$': sentence = '$' + sentence + if sentence[1] != '$': sentence = '$' + sentence + + print "PY SENTENCE ", sentence + + sentence = b64encode(sentence) + + retries = 5 + + while retries: + date = datetime.datetime.utcnow().isoformat("T") + "Z" + + data = { + "type": "payload_telemetry", + "data": { + "_raw": sentence + }, + "receivers": { + listener_callsign: { + "time_created": date, + "time_uploaded": date, + }, + }, + } + + c = httplib.HTTPConnection("habitat.habhub.org") + c.request( + "PUT", + "/habitat/_design/payload_telemetry/_update/add_listener/%s" % sha256(sentence).hexdigest(), + json.dumps(data), # BODY + {"Content-Type": "application/json"} # HEADERS + ) + + response = c.getresponse() + print response.status, response.reason, response.read() + + if response.status == 201 or response.status == '201': + retries == 0 + break + + retries = retries - 1 + time.sleep(1) + + +def main(): + caller = "habdec" + + if len(sys.argv) > 2: + caller = sys.argv[2] + + if len(sys.argv) > 1: + sendSentence(sys.argv[1], caller) + +if __name__ == '__main__': + try: + main() + except: + print traceback.format_exc() + diff --git a/code/webClient/css/habdec.css b/code/webClient/css/habdec.css new file mode 100644 index 0000000..5d65641 --- /dev/null +++ b/code/webClient/css/habdec.css @@ -0,0 +1,74 @@ + +body, html { + background-color:hsl(210, 15%, 24%); +} + +div{ + font-family: Tahoma, Verdana, Segoe, sans-serif; +} + +label { + color: hsl(32, 93%, 45%); +} + +button { + background-color:hsl(210, 15%, 34%); + border: none; + color: #AAAAAA; + /* padding: 15px 32px; */ + text-align: center; + display: inline-block; + font-size: 20px; + height: 4.0rem; + + border: 0.1rem solid hsl(210, 15%, 20%); + border-radius: .4rem; +} + +input[type=checkbox] +{ + /* Double-sized Checkboxes */ + -ms-transform: scale(2.5); /* IE */ + -moz-transform: scale(2.5); /* FF */ + -webkit-transform: scale(2.5); /* Safari and Chrome */ + -o-transform: scale(2.5); /* Opera */ + padding: 10px; +} + +.checkboxtext +{ + font-size: 130%; + display: inline; +} + +.ctrl_container { + width: 100%; +} + +.habsentence_text { + font-size: 12px; +} + +.ctrl_box { + color: hsl(32, 93%, 60%); + background-color: transparent; + border: 0.1rem solid #000000; + border-radius: .4rem; + height: 2.5rem; + padding: .6rem 1.0rem; + width: 50px; +} + +.increment_button { + background-color:hsl(210, 15%, 34%); + border: none; + color: #AAAAAA; + text-align: center; + display: inline-block; + font-size: 20px; + height: 60px; + width: 80px; + + border: 0.1rem solid hsl(210, 15%, 20%); + border-radius: .4rem; +} \ No newline at end of file diff --git a/code/webClient/index.html b/code/webClient/index.html new file mode 100755 index 0000000..3e757b9 --- /dev/null +++ b/code/webClient/index.html @@ -0,0 +1,94 @@ + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+
+
+
+ +
+ +
+
+ +
+
+
+ +
+
+
+
+
+
+ +
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+ BiasTee

+ AFC +

+
+ +
+
+ + +
+ + + + + + diff --git a/code/webClient/js/NetTransport.js b/code/webClient/js/NetTransport.js new file mode 100644 index 0000000..a363d56 --- /dev/null +++ b/code/webClient/js/NetTransport.js @@ -0,0 +1,80 @@ + + +function DecodeSpectrum(i_buffer, i_offset) +{ + var header = + { + header_size_ : 0, // int32_t + noise_floor_ : 0, // float + noise_variance_ : 0, // float + sampling_rate_: 0, // float + shift_ : 0, // float + peak_left_ : 0, // int32_t + peak_right_ : 0, // int32_t + peak_left_valid_ : 0, // int32_t + peak_right_valid_ : 0, // int32_t + min_ : 0, // float + max_ : 0, // float + + type_size_ : 0, // int32_t. value:s 1/2/4 for uint8 uint16 float32 + size_ : 0 // int32_t + }; + + var dv = new DataView(i_buffer, i_offset); + + var offset = 0; + header.header_size_ = dv.getInt32 (offset, true); offset += 4; + header.noise_floor_ = dv.getFloat32 (offset, true); offset += 4; + header.noise_variance_ = dv.getFloat32 (offset, true); offset += 4; + header.sampling_rate_= dv.getFloat32 (offset, true); offset += 4; + header.shift_ = dv.getFloat32 (offset, true); offset += 4; + header.peak_left_ = dv.getInt32 (offset, true); offset += 4; + header.peak_right_ = dv.getInt32 (offset, true); offset += 4; + header.peak_left_valid_= dv.getInt32 (offset, true); offset += 4; + header.peak_right_valid_= dv.getInt32 (offset, true); offset += 4; + header.min_ = dv.getFloat32 (offset, true); offset += 4; + header.max_ = dv.getFloat32 (offset, true); offset += 4; + header.type_size_ = dv.getInt32 (offset, true); offset += 4; + header.size_ = dv.getInt32 (offset, true); offset += 4; + + // add data + if(header.type_size_ == 1) // 8 bit char + header.values_ = new Uint8Array( i_buffer, offset, header.size_); + else if(header.type_size_ == 2) // uint16_t + header.values_ = new Uint16Array( i_buffer, offset, header.size_); + else if(header.type_size_ == 4) // 32float + header.values_ = new Float32Array( i_buffer, offset, header.size_); + + return header; +} + +function DecodeDemod(i_buffer, i_offset) +{ + var header = + { + header_size_ : 0, // int32_t + min_ : 0, // float + max_ : 0, // float + type_size_ : 0, // int32_t. value:s 1/2/4 for uint8 uint16 float32 + size_ : 0 // int32_t + }; + + var dv = new DataView(i_buffer, i_offset); + + var offset = 0; + header.header_size_ = dv.getInt32 (offset, true); offset += 4; + header.min_ = dv.getFloat32 (offset, true); offset += 4; + header.max_ = dv.getFloat32 (offset, true); offset += 4; + header.type_size_ = dv.getInt32 (offset, true); offset += 4; + header.size_ = dv.getInt32 (offset, true); offset += 4; + + // add data + if(header.type_size_ == 1) // 8 bit char + header.values_ = new Uint8Array( i_buffer, offset, header.size_); + else if(header.type_size_ == 2) // uint16_t + header.values_ = new Uint16Array( i_buffer, offset, header.size_); + else if(header.type_size_ == 4) // 32float + header.values_ = new Float32Array( i_buffer, offset, header.size_); + + return header; +} diff --git a/code/webClient/js/drawing.js b/code/webClient/js/drawing.js new file mode 100644 index 0000000..78863e2 --- /dev/null +++ b/code/webClient/js/drawing.js @@ -0,0 +1,194 @@ +function DrawPowerSpectrum(i_canvas, i_spectrum) +{ + var ctx = i_canvas.getContext("2d"); + + // CLEAR THE CANVAS + // + ctx.clearRect(0, 0, i_canvas.width-1, i_canvas.height-1); + + // BG + // + var grd_bg = ctx.createLinearGradient(0, 0, 0, i_canvas.height-1); + grd_bg.addColorStop(0, "hsl(210, 15%, 24%)"); + grd_bg.addColorStop(.5, "hsl(210, 15%, 40%)"); + grd_bg.addColorStop(1, "hsl(210, 15%, 24%)"); + ctx.fillStyle = grd_bg; + ctx.fillRect(0, 0, i_canvas.width-1, i_canvas.height-1); + + G_SPECTRUM_ZOOM = Math.max(0, Math.min(1, G_SPECTRUM_ZOOM)); + + var zoom = G_SPECTRUM_ZOOM; + + // LOWPASS FILTER DRAW + // + var _lowpass_bw = GLOBALS.lowpass_bw / (1.0 - .999*zoom); + var _lowpass_trans = GLOBALS.lowpass_trans / (1.0 - .999*zoom); + var grd_lowpass = ctx.createLinearGradient(0, 0, i_canvas.width-1, 0); + var _l = Math.max(0, .5 - .5 * _lowpass_bw); + var _ll = Math.max(0, .5 - .5 * (_lowpass_bw + _lowpass_trans)); + var _r = Math.min(1, .5 + .5 * _lowpass_bw); + var _rr = Math.min(1, .5 + .5 * (_lowpass_bw + _lowpass_trans)); + + grd_lowpass.addColorStop(0, "rgba(15,25,50,0)"); + grd_lowpass.addColorStop(_ll, "rgba(15,25,50,0)"); + grd_lowpass.addColorStop(_l, "#113555"); + grd_lowpass.addColorStop(_r, "#113555"); + grd_lowpass.addColorStop(_rr, "rgba(15,25,50,0)"); + grd_lowpass.addColorStop(1, "rgba(15,25,50,0)"); + ctx.fillStyle = grd_lowpass; + ctx.fillRect(0, 0, i_canvas.width-1, i_canvas.height-1); + + // SPECTRUM + // + var power_grd = ctx.createLinearGradient(0, 0, 0, i_canvas.height-1); + power_grd.addColorStop(0.2, "yellow"); + power_grd.addColorStop(.6, "#993311"); + power_grd.addColorStop(1, "black"); + + ctx.strokeStyle = power_grd; + ctx.beginPath(); + if(i_spectrum.type_size_ == 1) // 8 bit char + { + for(var x=0; x")); + + var incr_big = document.createElement("button"); + incr_big.classList.add("increment_button"); + incr_big.appendChild(document.createTextNode(">>>")); + + // arrows callbacks + decr_big.onclick = function() { + widget.value = parseFloat(widget.value) - parseFloat(widget.getAttribute("step_big")); + i_callback("set:" + i_parameter + "=" + widget.value); + }; + decr_small.onclick = function() { + widget.value = parseFloat(widget.value) - parseFloat(widget.getAttribute("step_small")); + i_callback("set:" + i_parameter + "=" + widget.value); + }; + incr_small.onclick = function() { + widget.value = parseFloat(widget.value) + parseFloat(widget.getAttribute("step_small")); + i_callback("set:" + i_parameter + "=" + widget.value); + }; + incr_big.onclick = function() { + widget.value = parseFloat(widget.value) + parseFloat(widget.getAttribute("step_big")); + i_callback("set:" + i_parameter + "=" + widget.value); + }; + + document.getElementById(i_cnt).style.textAlign = "right"; + + document.getElementById(i_cnt).appendChild(lab); + + document.getElementById(i_cnt).appendChild(widget); + + document.getElementById(i_cnt).appendChild(decr_big); + document.getElementById(i_cnt).appendChild(decr_small); + document.getElementById(i_cnt).appendChild(incr_small); + document.getElementById(i_cnt).appendChild(incr_big); + + return widget; +} + + +function SetGuiToGlobals(i_globals) +{ + for(var param in i_globals) + { + var value = i_globals[param]; + // console.debug("setting ", param, value); + try {document.getElementById(param).value = value; } catch(err) {}; + try {document.getElementById(param + "_box").value = value; } catch(err) {}; + try {document.getElementById(param).checked = value; } catch(err) {}; + } +} + + +function CreateControls() +{ + var freq_widget = CreateFloatBoxWithArrows("cnt_frequency", "frequency", + SendCommand, 25, 1200, 434.355, 20.0/1e6, 1000.0/1e6, 1e-6); + freq_widget.style.width = "100px"; + CreateFloatBoxWithArrows("cnt_decimation", "decimation", + SendCommand, 0, 8, 8, 1, 1); + CreateFloatBoxWithArrows("cnt_gain", "gain", + SendCommand, 0, 49, 21, 1, 5); + CreateFloatBoxWithArrows("cnt_lowpass_bw", "lowpass_bw", + SendCommand, .0, 1.0, .05, .002, .02); + CreateFloatBoxWithArrows("cnt_lowpass_trans", "lowpass_trans", + SendCommand, .0025, 0.1, .05, .0025, .01); + CreateFloatBoxWithArrows("cnt_baud", "baud", + SendCommand, 50, 1200, 300, 25, 100); + CreateFloatBoxWithArrows("cnt_rtty_bits", "rtty_bits", + SendCommand, 7, 8, 8, 1, 1); + CreateFloatBoxWithArrows("cnt_rtty_stops", "rtty_stops", + SendCommand, 1, 2, 2, 1, 1); + CreateFloatBoxWithArrows("cnt_datasize", "datasize", + SendCommand, 1, 4, 1, 1, 1); +} + + +function toggleFullscreen(elem) +{ + elem = elem || document.documentElement; + if (!document.fullscreenElement && !document.mozFullScreenElement && + !document.webkitFullscreenElement && !document.msFullscreenElement) + { + if (elem.requestFullscreen) { + elem.requestFullscreen(); + } else if (elem.msRequestFullscreen) { + elem.msRequestFullscreen(); + } else if (elem.mozRequestFullScreen) { + elem.mozRequestFullScreen(); + } else if (elem.webkitRequestFullscreen) { + elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); + } + } + else + { + if (document.exitFullscreen) { + document.exitFullscreen(); + } else if (document.msExitFullscreen) { + document.msExitFullscreen(); + } else if (document.mozCancelFullScreen) { + document.mozCancelFullScreen(); + } else if (document.webkitExitFullscreen) { + document.webkitExitFullscreen(); + } + } +} diff --git a/code/webClient/js/habdec_commands.js b/code/webClient/js/habdec_commands.js new file mode 100644 index 0000000..7fc23e7 --- /dev/null +++ b/code/webClient/js/habdec_commands.js @@ -0,0 +1,285 @@ + +var websocket; +var connected = 0; +var LastHabSentences = []; +var G_SPECTRUM_ZOOM = 0; +var G_SENTECES_OK_COUNT = 0; + +var GLOBALS = +{ + frequency: 0, + sampling_rate: 0, + gain: 0, + baud: 0, + rtty_bits: 0, + rtty_stops: 0, + lowpass_bw: 0, + lowpass_trans: 0, + biastee: 0, + decimation: 0, + afc: 0 +}; + + +function debug_print() +{ + console.debug(arguments); + /* + document.getElementById("cnt_debug").innerHTML = ""; + for (i = 0; i < arguments.length; i++) + document.getElementById("cnt_debug").innerHTML += arguments[i] + " "; + */ +} + + +function OpenConnection() +{ + if(connected) + return; + + var server = document.getElementById("server_address").value; + debug_print("Connecting to ", server, " ..."); + websocket = new WebSocket("ws://" + server); + websocket.binaryType = 'arraybuffer'; // or 'blob' + + websocket.onopen = function(evt) { ws_onOpen(evt) }; + websocket.onclose = function(evt) { ws_onClose(evt) }; + websocket.onmessage = function(evt) { ws_onMessage(evt) }; + websocket.onerror = function(evt) { ws_onError(evt) }; +} + + +function ws_onClose(evt) +{ + connected = 0; + debug_print("DISCONNECTED"); + setTimeout(function () { OpenConnection(); }, 5000); +} + + +function ws_onError(evt) +{ + debug_print("ws_onError: ", evt.data); +} + + +function ws_onOpen(evt) +{ + connected = 1; + debug_print("ws_onOpen: ", "Connected."); + + websocket.send("hi"); + for(var param in GLOBALS) + SendCommand("get:" + param); + + console.debug("ws_onOpen: init refresh."); + RefreshPowerSpectrum(); + RefreshDemod(); + RefreshLivePrint(); +} + + +function ws_onMessage(evt) +{ + if(!connected) + { + debug_print("ws_onMessage: not connected."); + return; + } + + // console.debug("ON_MSG", evt); + + if(typeof evt.data === "string") + { + HandleMessage(evt.data) + } + else if(evt.data instanceof ArrayBuffer) + { + var what = String.fromCharCode.apply( null, new Uint8Array(evt.data,0,4) ); + if(what == "PWR_") + { + var spectrum = DecodeSpectrum(evt.data, 4); + if(GLOBALS.sampling_rate != spectrum.sampling_rate_) + { + GLOBALS.sampling_rate = spectrum.sampling_rate_; + var widget = document.getElementById("frequency"); + widget.setAttribute("step_big", GLOBALS.sampling_rate / 1e6 / 30); + widget.setAttribute("step_small", GLOBALS.sampling_rate / 1e6 / 500); + } + DrawPowerSpectrum(document.getElementById("powerSpectrumCanvas"), spectrum); + } + else if(what == "DEM_") + { + var demod = DecodeDemod(evt.data, 4); + DrawDemod(document.getElementById("demodCanvas"), demod); + } + } + else + { + debug_print("ws_onMessage: unknown data type."); + return; + } +} + + +function SendCommand(i_cmd) +{ + if(!connected) + { + debug_print("SendCommand: not connected."); + return; + } + var msg = "cmd::" + i_cmd; + // debug_print("SendCommand: ", msg); + websocket.send(msg); +} + + +function HandleMessage(i_data) +{ + if(!connected) + { + debug_print("HandleMessage: not connected."); + return; + } + + if( !i_data.startsWith("cmd::info:liveprint") ) + debug_print("Received Message: ", i_data); + + // cmd::set + // + var set_rex = String.raw`cmd\:\:set\:(\D+)=(.+)`; + var set_re = new RegExp(set_rex); + var set_match = set_re.exec(i_data); + if(set_match != null && set_match.length == 3) + { + if(set_match[1] == "frequency") + GLOBALS.frequency = parseFloat(set_match[2]); + if(set_match[1] == "decimation") + GLOBALS.decimation = parseInt(set_match[2]); + else if(set_match[1] == "gain") + GLOBALS.gain = parseFloat(set_match[2]); + else if(set_match[1] == "baud") + GLOBALS.baud = parseInt(set_match[2]); + else if(set_match[1] == "lowpass_bw") + GLOBALS.lowpass_bw = parseFloat(set_match[2]); + else if(set_match[1] == "lowpass_trans") + GLOBALS.lowpass_trans = parseFloat(set_match[2]); + else if(set_match[1] == "rtty_bits") + GLOBALS.rtty_bits = parseFloat(set_match[2]); + else if(set_match[1] == "rtty_stops") + GLOBALS.rtty_stops = parseFloat(set_match[2]); + else if(set_match[1] == "lowPass") + { + GLOBALS.lowpass_bw = parseFloat(set_match[2].split(',')[0]); + GLOBALS.lowpass_trans = parseFloat(set_match[2].split(',')[1]); + } + else if(set_match[1] == "biastee") + { + GLOBALS.biastee = parseFloat(set_match[2]); + debug_print("Received Message: ", i_data); + } + else if(set_match[1] == "afc") + { + GLOBALS.afc = parseFloat(set_match[2]); + debug_print("Received Message: ", i_data); + } + + SetGuiToGlobals(GLOBALS); + + return true; + } + + // cmd::info + // + var data_without_new_lines = i_data.replace(/(\r\n|\n|\r)/gm," "); + var info_rex = String.raw`cmd\:\:info\:(\D+)=(.+)`; + var info_re = new RegExp(info_rex); + var info_match = info_re.exec(data_without_new_lines); + // if (info_match && info_match.length == 3) + { + if(info_match[1] == "sentence") + { + G_SENTECES_OK_COUNT += 1; + document.getElementById("cnt_habsentence_count").innerHTML = "OK: " + G_SENTECES_OK_COUNT; + + var sntnc = info_match[2]; + + var cnt_habsentence_list = document.getElementById("cnt_habsentence_list") + cnt_habsentence_list.innerHTML = '' + sntnc + '';; + + while(LastHabSentences.length > 12) + LastHabSentences.pop(); + LastHabSentences.forEach( function(i_snt){ + cnt_habsentence_list.innerHTML += '
' + i_snt + ''; + } + ); + + LastHabSentences.unshift( info_match[2] ); + } + else if(info_match[1] == "liveprint") + { + var livestream = info_match[2]; + if(livestream.length > 100) + livestream = livestream.substr(livestream.length-100, livestream.length); + document.getElementById("cnt_liveprint").innerHTML = livestream; + } + + return true; + } + + return false; + +} + + +function RefreshPowerSpectrum() +{ + if(!connected) + return; + + G_SPECTRUM_ZOOM = Math.max(0, Math.min(1, G_SPECTRUM_ZOOM)); + var zoom = Math.max(0, Math.min(1, G_SPECTRUM_ZOOM)); + var canvas = document.getElementById("powerSpectrumCanvas"); + SendCommand("power:res=" + canvas.width + ",zoom=" + zoom); + setTimeout(function () {RefreshPowerSpectrum();}, 1000 / 15); +} + + +function RefreshDemod() +{ + if(!connected) + return; + var canvas = document.getElementById("demodCanvas"); + SendCommand("demod:res=" + canvas.width); + setTimeout(function () {RefreshDemod();}, 1000 / 3); +} + + +function RefreshLivePrint() +{ + if(!connected) + return; + SendCommand("liveprint"); + setTimeout(function () {RefreshLivePrint();}, 1000 / 4); +} + + +function SetBiasT() +{ + var value = document.getElementById("biastee").checked; + if(value) + SendCommand("set:biastee=1"); + else + SendCommand("set:biastee=0"); +} + + +function SetAFC() +{ + var value = document.getElementById("afc").checked; + if(value) + SendCommand("set:afc=1"); + else + SendCommand("set:afc=0"); +} diff --git a/code/websocketServer/CMakeLists.txt b/code/websocketServer/CMakeLists.txt new file mode 100755 index 0000000..49d8673 --- /dev/null +++ b/code/websocketServer/CMakeLists.txt @@ -0,0 +1,65 @@ + + +include_directories( ${PROJECT_SOURCE_DIR} ) +include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ) + +set ( FFTW3f_DIR ../CMake ) +find_package( FFTW3f REQUIRED ) +include_directories( ${FFTW3f_INCLUDE_DIRS} ) + +# boost +set ( Boost_NO_BOOST_CMAKE ON ) +set ( Boost_NO_SYSTEM_PATHS ON ) +set ( Boost_USE_STATIC_LIBS ON ) +add_definitions ( -DBOOST_ALL_NO_LIB ) +find_package(Boost REQUIRED COMPONENTS program_options system ) +include_directories( ${Boost_INCLUDE_DIRS} ) +message ( "Boost_INCLUDE_DIRS " ${Boost_INCLUDE_DIRS} ) +message ( "Boost_LIBRARY_DIRS " ${Boost_LIBRARY_DIRS} ) + +find_package(SoapySDR REQUIRED) # this reverts CMAKE_CXX_STANDARD to '11' +#set ( CMAKE_CXX_STANDARD 17 ) +include_directories( ${SoapySDR_INCLUDE_DIRS} ) + + +set( CMAKE_CXX_FLAGS " -O3 " ) +if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") + # set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wshadow" ) + set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-class-memaccess" ) + set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-variable" ) + set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter" ) +elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") + SET(CMAKE_CXX_FLAGS "/EHsc") + add_definitions( -D_USE_MATH_DEFINES ) +endif() + +set (PlatformSpecificLinking "") +if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") + set (PlatformSpecificLinking "pthread") +endif() + + +set ( websocketServer_src + program_options.h program_options.cpp + server.h server.cpp + main.cpp + ) + +add_executable ( habdecWebsocketServer ${websocketServer_src} ) +target_link_libraries( habdecWebsocketServer + Decoder + IQSource + ${Boost_LIBRARIES} + ${PlatformSpecificLinking} ) + +install ( TARGETS habdecWebsocketServer DESTINATION ${CMAKE_INSTALL_PREFIX} ) +install ( FILES ${PROJECT_SOURCE_DIR}/habLogger/habLogger.py + PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ + DESTINATION ${CMAKE_INSTALL_PREFIX} ) + + +file( WRITE ${CMAKE_CURRENT_BINARY_DIR}/run_loop.sh "#!/bin/sh\n while true; do ./habdecWebsocketServer --config ./habdecWebsocketServer.opts; done\n" ) +install ( FILES ${CMAKE_CURRENT_BINARY_DIR}/run_loop.sh + PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ + DESTINATION ${CMAKE_INSTALL_PREFIX} ) + diff --git a/code/websocketServer/CompressedVector.h b/code/websocketServer/CompressedVector.h new file mode 100644 index 0000000..9ef7508 --- /dev/null +++ b/code/websocketServer/CompressedVector.h @@ -0,0 +1,311 @@ +/* + + Copyright 2018 Michal Fratczak + + This file is part of habdec. + + habdec 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 3 of the License, or + (at your option) any later version. + + habdec 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 habdec. If not, see . +*/ + +#pragma once + +#include +#include +#include + +namespace habdec +{ + +template +class CompressedVector +{ +public: + + typedef T TValue; + + mutable double min_ = 0; + mutable double max_ = 0; + std::vector values_; + + virtual ~CompressedVector() = default; + CompressedVector() = default; + + template + CompressedVector(const CompressedVector& rhs) : + min_(rhs.min_), + max_(rhs.max_) + // normalized_(rhs.normalized_) + { + copyValues(rhs); + } + + template + CompressedVector(const std::vector& rhs_vec) + { + min_ = *std::min_element(rhs_vec.begin(), rhs_vec.end()); + max_ = *std::max_element(rhs_vec.begin(), rhs_vec.end()); + copyValues(rhs_vec, min_, max_); + } + + template + const CompressedVector& operator=(const CompressedVector& rhs) + { + min_ = rhs.min_; + max_ = rhs.max_; + copyValues(rhs); + return *this; + } + + double calcMin() const + { + if(!values_.size()) + return 0; + min_ = *std::min_element(values_.begin(), values_.end()); + return min_; + } + + double calcMax() const + { + if(!values_.size()) + return 0; + max_ = *std::max_element(values_.begin(), values_.end()); + return max_; + } + +private: + template + void copyValues(const std::vector& rhs, double i_min, double i_max) + { + if(!rhs.size()) + { + values_.clear(); + return; + } + values_.resize(rhs.size()); + std::copy(rhs.begin(), rhs.end(), values_.begin()); + } + +}; + + +// specialization: float --> double +template<> +template<> +void CompressedVector::copyValues(const std::vector& rhs, double i_min, double i_max) +{ + if(!rhs.size()) + { + values_.clear(); + return; + } + + values_.resize(rhs.size()); + std::copy(rhs.begin(), rhs.end(), values_.begin()); +} + + +// specialization: double --> float +template<> +template<> +void CompressedVector::copyValues(const std::vector& rhs, double i_min, double i_max) +{ + // std::cout<<"specialization: double --> float"< unsigned char +template<> +template<> +void CompressedVector::copyValues(const std::vector& rhs, double i_min, double i_max) +{ + // std::cout<<"specialization: float --> unsigned char"<::max(); + values_.push_back(v_out); + } +} + + +// specialization: float --> uint16_t +template<> +template<> +void CompressedVector::copyValues(const std::vector& rhs, double i_min, double i_max) +{ + // std::cout<<"specialization: float --> uint16_t"<::max(); + values_.push_back(v_out); + } +} + + +// specialization: double --> unsigned char +template<> +template<> +void CompressedVector::copyValues(const std::vector& rhs, double i_min, double i_max) +{ + // std::cout<<"specialization: double --> unsigned char"<::max(); + values_.push_back(v_out); + } +} + + +// specialization: double --> uint16_t +template<> +template<> +void CompressedVector::copyValues(const std::vector& rhs, double i_min, double i_max) +{ + // std::cout<<"specialization: double --> uint16_t"<::max(); + values_.push_back(v_out); + } +} + + +// specialization: unsigned char --> float +template<> +template<> +void CompressedVector::copyValues(const std::vector& rhs, double i_min, double i_max) +{ + // std::cout<<"specialization: unsigned char --> float"<::max(); + values_.push_back(rhs_v_0_1); + } +} + + +// specialization: uint16_t --> float +template<> +template<> +void CompressedVector::copyValues(const std::vector& rhs, double i_min, double i_max) +{ + // std::cout<<"specialization: uint16_t --> float"<::max(); + values_.push_back(rhs_v_0_1); + } +} + + +// specialization: unsigned char --> double +template<> +template<> +void CompressedVector::copyValues(const std::vector& rhs, double i_min, double i_max) +{ + // std::cout<<"specialization: unsigned char --> double"<::max(); + values_.push_back(rhs_v_0_1); + } +} + + +// specialization: uint16_t --> double +template<> +template<> +void CompressedVector::copyValues(const std::vector& rhs, double i_min, double i_max) +{ + // std::cout<<"specialization: uint16_t --> double"<::max(); + values_.push_back(rhs_v_0_1); + } +} + + +} // namespace habdec \ No newline at end of file diff --git a/code/websocketServer/GLOBALS.h b/code/websocketServer/GLOBALS.h new file mode 100644 index 0000000..9d7db51 --- /dev/null +++ b/code/websocketServer/GLOBALS.h @@ -0,0 +1,117 @@ +/* + + Copyright 2018 Michal Fratczak + + This file is part of habdec. + + habdec 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 3 of the License, or + (at your option) any later version. + + habdec 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 habdec. If not, see . +*/ + +#pragma once + +#include +#include +#include +#include +#include + + +#include "IQSource/IQSource.h" +#include "Decoder/Decoder.h" + + +typedef float TReal; // we operate on float IQ samples +typedef habdec::Decoder TDecoder; + + +// singleton class keeping all global data +class GLOBALS +{ +public: + GLOBALS(GLOBALS const&) = delete; + void operator=(GLOBALS const&) = delete; + + static GLOBALS& get() + { + static GLOBALS instance_; + return instance_; + } + + // decoder and IQ source + TDecoder decoder_; + std::unique_ptr p_iq_source_; + + enum class TransportDataType {kUnknown=0, kChar, kShort, kFloat}; // 8, 16, 32 bits + TransportDataType transport_data_type_ = TransportDataType::kChar; + + std::vector demod_accumulated_; // acuumulated demod samples, used for GUI display + std::mutex demod_accumulated_mtx_; + + // decoded sentences que + std::vector senteces_to_log_; + std::mutex senteces_to_log_mtx_; + std::vector senteces_to_web_; + std::mutex senteces_to_web_mtx_; + + // outgoing commands. used to sync webgui + std::vector out_commands_; + std::mutex out_commands_mtx_; + + // OPTS: + int device_ = -1; // index to SoapySDR::Device::enumerate() + std::string command_host_ = "0.0.0.0"; + int command_port_ = 5555; + std::string station_callsign_ = ""; // habitat upload + double sampling_rate_ = 0; + double frequency_ = 434349500.0f; + double gain_ = 15; + bool biast_ = false; + float baud_ = 300; + int rtty_ascii_bits_ = 8; + float rtty_ascii_stops_ = 2; + bool live_print_ = true; + bool afc_ = false; + + static bool DumpToFile(std::string fName) + { + using namespace std; + try{ + fstream oFile(fName, fstream::out); + + oFile<<"device = "<. +*/ + +#pragma once + +#include +#include + +#include "Decoder/SpectrumInfo.h" +#include "CompressedVector.h" + +struct SpectrumInfoHeader +{ + int32_t header_size_ = (int32_t)sizeof(SpectrumInfoHeader); + float noise_floor_ = 0; + float noise_variance_ = 0; + float sampling_rate_ = 0; + float shift_ = 0; + int32_t peak_left_ = 0; + int32_t peak_right_ = 0; + int32_t peak_left_valid_ = 0; + int32_t peak_right_valid_ = 0; + float min_ = 0; + float max_ = 0; + // int32_t normalized_ = 0; + + int32_t type_size_ = 0; + int32_t size_ = 0; +}; + + +struct DemodHeader +{ + int32_t header_size_ = sizeof(DemodHeader); + float min_ = 0; + float max_ = 0; + int32_t type_size_ = 0; + int32_t size_ = 0; +}; + + + +template +void SerializeSpectrum(const TSpectrumInfo& spectrum_info, std::stringstream& ostr, TTransport* unused) +{ + // convert spectrum_info values to type TTransport + habdec::CompressedVector compressed(spectrum_info); + + // make header + SpectrumInfoHeader header; + header.noise_floor_ = spectrum_info.noise_floor_; + header.noise_variance_ = spectrum_info.noise_variance_; + header.sampling_rate_ = spectrum_info.sampling_rate_; + header.shift_ = spectrum_info.shift_; + header.peak_left_ = spectrum_info.peak_left_; + header.peak_right_ = spectrum_info.peak_right_; + header.peak_left_valid_ = spectrum_info.peak_left_valid_; + header.peak_right_valid_ = spectrum_info.peak_right_valid_; + header.size_ = spectrum_info.size(); + + header.min_ = compressed.min_; + header.max_ = compressed.max_; + + header.type_size_ = sizeof(TTransport); + + ostr.write( reinterpret_cast(&header), sizeof(header) ); + ostr.write( reinterpret_cast( compressed.values_.data()), compressed.values_.size() * sizeof(TTransport) ); +} + + +template +void SerializeDemodulation(const DemodVector& vec, std::stringstream& ostr, TTransport* unused) +{ + habdec::CompressedVector compressed(vec); + + // make header + DemodHeader header; + header.size_ = vec.size(); + header.min_ = compressed.min_; + header.max_ = compressed.max_; + header.type_size_ = sizeof(TTransport); + + ostr.write( reinterpret_cast(&header), sizeof(header) ); + ostr.write( reinterpret_cast( compressed.values_.data()), compressed.values_.size() * sizeof(TTransport) ); +} diff --git a/code/websocketServer/main.cpp b/code/websocketServer/main.cpp new file mode 100755 index 0000000..43f855c --- /dev/null +++ b/code/websocketServer/main.cpp @@ -0,0 +1,338 @@ +/* + + Copyright 2018 Michal Fratczak + + This file is part of habdec. + + habdec 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 3 of the License, or + (at your option) any later version. + + habdec 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 habdec. If not, see . +*/ + +#include "program_options.h" + +#include +#include +#include +#include + +#include +#include + + +#include "IQSource/IQSource_SoapySDR.h" +#include "Decoder/Decoder.h" +#include "common/console_colors.h" +#include "GLOBALS.h" +#include "server.h" + + +bool G_DO_EXIT = false; + +using namespace std; + + +void PrintDevicesList(const SoapySDR::KwargsList& device_list) +{ + int DEV_NUM = 0; + cout< sampling_rates = p_device->listSampleRates(SOAPY_SDR_RX, 0); + sort(sampling_rates.begin(), sampling_rates.end()); + + cout<<"\tSampling Rates:"<= int(device_list.size()) ) + { + cout<setOption("SoapySDR_Kwargs", &device); + + if( !GLOBALS::get().p_iq_source_->init() ) + { + cout<setOption("frequency_double", &freq); + double gain = GLOBALS::get().gain_; + GLOBALS::get().p_iq_source_->setOption("gain_double", &gain); + double biastee = GLOBALS::get().biast_; + GLOBALS::get().p_iq_source_->setOption("biastee_double", &biastee); + GLOBALS::get().p_iq_source_->setOption("sampling_rate_double", &GLOBALS::get().sampling_rate_); + + return true; +} + + +void DECODER_FEED_THREAD() +{ + using namespace std; + cout<<"Start DECODER_FEED_THREAD"<start()) + { + cout<isRunning()) + { + cout< samples; + samples.resize(256*256); + samples.samplingRate( p_iq_src->samplingRate() ); + + while(!G_DO_EXIT) + { + auto _start = std::chrono::high_resolution_clock::now(); + + size_t count = p_iq_src->get( samples.data(), samples.size() ); + DECODER.pushSamples(samples); + DECODER(); // DECODE ! + + // AFC - don't do this too often. Too unstable, needs more work. + static auto last_afc_time = std::chrono::high_resolution_clock::now(); + if( std::chrono::duration_cast< std::chrono::seconds > + (std::chrono::high_resolution_clock::now() - last_afc_time).count() > 5 + ) + { + double freq_corr = DECODER.getFrequencyCorrection(); + if(GLOBALS::get().afc_) + { + if( 100 < abs(freq_corr) ) + { + GLOBALS::get().frequency_ += freq_corr; + double f = GLOBALS::get().frequency_; + p_iq_src->setOption("frequency_double", &f); + DECODER.resetFrequencyCorrection(freq_corr); + last_afc_time = std::chrono::high_resolution_clock::now(); + + // notify webgui + { + lock_guard _lock( GLOBALS::get().out_commands_mtx_ ); + GLOBALS::get().out_commands_.emplace_back("cmd::set:frequency=" + to_string(f / 1e6)); + } + } + } + } + + + TDur _duration = std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - _start); + + // accumulate demod samples to display more + { + std::lock_guard _lock(GLOBALS::get().demod_accumulated_mtx_); + + const size_t max_sz = DECODER.getDecimatedSamplingRate() / + DECODER.getSymbolRate() * 50; // 50 symbols + + auto demod = DECODER.getDemodulated(); + auto& demod_acc = GLOBALS::get().demod_accumulated_; + demod_acc.insert( demod_acc.end(), demod.cbegin(), demod.cend() ); + + // remove leading values + if( demod_acc.size() > max_sz) + demod_acc.erase( demod_acc.begin(), demod_acc.begin() + demod_acc.size() - max_sz ); + } + } +} + +void HAB_UPLOAD_THREAD() +{ + using namespace std; + + while(!G_DO_EXIT) + { + this_thread::sleep_for( chrono::duration(500) ); + + vector sentences; + { + lock_guard _lock( GLOBALS::get().senteces_to_log_mtx_ ); + sentences = move( GLOBALS::get().senteces_to_log_ ); + } + if(GLOBALS::get().station_callsign_ != "") + { + for(auto& sentence : sentences) + { + string cmd = "python ./habLogger.py "; + cmd += sentence; + cmd += " "; + cmd += GLOBALS::get().station_callsign_; + + auto res = system(cmd.c_str()); + cout<<"HAB upload res: "< + { + char do_thousands_sep() const { return ','; } + string do_grouping() const { return "\3"; } + }; + try{ + std::cout.imbue( std::locale(locale(""), new thousand_separators) ); + } + catch(exception& e) { + + } + + // setup GLOBALS + prog_opts(argc, argv); + + // setup SoapySDR device + if(!SetupDevice()) + { + cout< _lock( GLOBALS::get().senteces_to_log_mtx_ ); + GLOBALS::get().senteces_to_log_.emplace_back( callsign + "," + data + "*" + crc ); + } + { + lock_guard _lock( GLOBALS::get().senteces_to_web_mtx_ ); + GLOBALS::get().senteces_to_web_.emplace_back( callsign + "," + data + "*" + crc ); + } + GLOBALS::DumpToFile("./habdecWebsocketServer.opts"); + }; + + // feed decoder with IQ samples + std::thread* decoder_feed_thread = new std::thread(DECODER_FEED_THREAD); + + // HAB upload + std::thread* hab_upload_thread = new std::thread(HAB_UPLOAD_THREAD); + + // websocket server thread. this call is blocking + RunCommandServer( GLOBALS::get().command_host_ , GLOBALS::get().command_port_ ); + + G_DO_EXIT = true; + decoder_feed_thread->join(); + hab_upload_thread->join(); + + return 0; +} diff --git a/code/websocketServer/program_options.cpp b/code/websocketServer/program_options.cpp new file mode 100644 index 0000000..ededf64 --- /dev/null +++ b/code/websocketServer/program_options.cpp @@ -0,0 +1,193 @@ +/* + + Copyright 2018 Michal Fratczak + + This file is part of habdec. + + habdec 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 3 of the License, or + (at your option) any later version. + + habdec 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 habdec. If not, see . +*/ + + +#include +#include +#include +#include + +#include + +#include "GLOBALS.h" +#include "common/console_colors.h" + +void prog_opts(int ac, char* av[]) +{ + namespace po = boost::program_options; + using namespace std; + + try + { + po::options_description generic("CLI opts"); + generic.add_options() + ("help", "Display help message") + ("device", po::value()->default_value(-1), "SDR Device Numer") + ("sampling_rate", po::value()->default_value(0), "Sampling Rate, as supported by device") + + ("port", po::value()->default_value("5555"), "Command Port, example: --port 127.0.0.1:5555") + ("station", po::value()->default_value(""), "HABHUB station callsign") + + ("freq", po::value(), "frequency in MHz") + ("gain", po::value(), "gain") + ("print", po::value(), "live print received chars, values: 0, 1") + ("rtty", po::value< std::vector >()->multitoken(), "rtty: baud bits stops, example: -rtty 300 8 2") + ("biast", po::value(), "biasT, values: 0, 1") + ("bias_t", po::value(), "biasT, values: 0, 1") + ("afc", po::value(), "Auto Frequency Correction, values: 0, 1") + ; + + po::options_description cli_options("Command Line Interface options"); + cli_options.add(generic); + + string config_file; + cli_options.add_options() + ("config", po::value(&config_file), "Last run config file. Autosaved on every successfull decode."); + // ("config", po::value(&config_file)->default_value("./habdecWebsocketServer.opts"), "Last run config file. Autosaved on every successfull decode."); + + po::options_description file_options; + file_options.add(generic); + + po::variables_map vm; + store( po::command_line_parser(ac, av).options(cli_options).allow_unregistered().run(), vm ); + notify(vm); + + if(vm.count("help")) + { + cout<(); + } + if (vm.count("sampling_rate")) + { + GLOBALS::get().sampling_rate_ = vm["sampling_rate"].as(); + } + if (vm.count("port")) // [host:][port] + { + smatch match; + regex_match( vm["port"].as(), match, std::regex(R"_(([\w\.]*)(\:?)(\d*))_") ); + + if(match.size() == 4) + { + if(match[2] == "" && match[3] == "") // special case when only port is given: --port 5555 + { + GLOBALS::get().command_port_ = stoi(match[1]); + } + else + { + if(match[1] != "") GLOBALS::get().command_host_ = match[1]; + if(match[3] != "") GLOBALS::get().command_port_ = stoi(match[3]); + } + } + } + if (vm.count("station")) + { + GLOBALS::get().station_callsign_ = vm["station"].as(); + } + if (vm.count("freq")) + { + GLOBALS::get().frequency_ = vm["freq"].as() * 1e6; + } + if (vm.count("gain")) + { + GLOBALS::get().gain_ = vm["gain"].as(); + } + if (vm.count("print")) + { + GLOBALS::get().live_print_ = vm["print"].as(); + } + if (vm.count("biast")) + { + GLOBALS::get().biast_ = vm["biast"].as(); + } + if (vm.count("bias_t")) + { + GLOBALS::get().biast_ = vm["bias_t"].as(); + } + if (vm.count("afc")) + { + GLOBALS::get().afc_ = vm["afc"].as(); + } + if (vm.count("rtty")) + { + vector rtty_tokens = vm["rtty"].as< vector >(); + if( rtty_tokens.size() != 3 ) + { + cout<. +*/ + +#pragma once +void prog_opts(int ac, char* av[]); diff --git a/code/websocketServer/server.cpp b/code/websocketServer/server.cpp new file mode 100755 index 0000000..138c8fc --- /dev/null +++ b/code/websocketServer/server.cpp @@ -0,0 +1,471 @@ +/* + + Copyright 2018 Michal Fratczak + + This file is part of habdec. + + habdec 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 3 of the License, or + (at your option) any later version. + + habdec 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 habdec. If not, see . +*/ + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +using boost::asio::ip::tcp; +namespace beast = boost::beast; +namespace websocket = boost::beast::websocket; + + +#include "common/console_colors.h" +#include "CompressedVector.h" +#include "GLOBALS.h" +#include "NetTransport.h" + +extern bool G_DO_EXIT; + + +bool HandleCommand(const std::string i_command, websocket::stream& ws) +{ + if(!GLOBALS::get().p_iq_source_) + return false; + + using namespace std; + smatch match; + + // GET + if(i_command == "get:frequency") + { + double frequency = 0; + GLOBALS::get().p_iq_source_->getOption("frequency_double", &frequency); + frequency /= 1e6; + string o_command = "cmd::set:frequency=" + to_string(frequency); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + else if(i_command == "get:gain") + { + double gain = 0; + GLOBALS::get().p_iq_source_->getOption("gain_double", &gain); + string o_command = "cmd::set:gain=" + to_string(gain); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + else if(i_command == "get:baud") + { + size_t baud = GLOBALS::get().decoder_.baud(); + string o_command = "cmd::set:baud=" + to_string(baud); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + else if(i_command == "get:rtty_bits") + { + size_t rtty_bits = GLOBALS::get().decoder_.rtty_bits(); + string o_command = "cmd::set:rtty_bits=" + to_string(rtty_bits); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + else if(i_command == "get:rtty_stops") + { + float rtty_stops = GLOBALS::get().decoder_.rtty_stops(); + string o_command = "cmd::set:rtty_stops=" + to_string(rtty_stops); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + else if(i_command == "get:lowpass_bw") + { + string o_command = "cmd::set:lowpass_bw=" + to_string(GLOBALS::get().decoder_.lowpass_bw()); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + else if(i_command == "get:lowpass_trans") + { + string o_command = "cmd::set:lowpass_trans=" + to_string(GLOBALS::get().decoder_.lowpass_trans()); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + else if(i_command == "get:biastee") + { + double biastee = 0; + GLOBALS::get().p_iq_source_->getOption("biastee_double", &biastee); + string o_command = "cmd::set:biastee=" + to_string(biastee); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + else if(i_command == "get:afc") + { + string o_command = "cmd::set:afc=" + to_string(GLOBALS::get().afc_); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + else if(i_command == "get:decimation") + { + int decim_factor_log = std::log2( GLOBALS::get().decoder_.getDecimationFactor() ); + string o_command = "cmd::set:decimation=" + to_string(decim_factor_log); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + else if(i_command == "get:sampling_rate") + { + double sr = 0; + GLOBALS::get().p_iq_source_->getOption("sampling_rate_double", &sr); + string o_command = "cmd::info:sampling_rate=" + to_string(sr); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + // SET + else if( regex_match(i_command, match, regex(R"_(set\:frequency=([+-]?([0-9]*[.])?[0-9]+))_")) && match.size() > 1 ) + { + double frequency = stod(match[1]); + frequency *= 1e6; + GLOBALS::get().p_iq_source_->setOption("frequency_double", &frequency); + GLOBALS::get().frequency_ = frequency; + + string o_command = "cmd::set:frequency=" + to_string(frequency/1e6); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + else if( regex_match(i_command, match, regex(R"_(set\:decimation=(\d+))_")) && match.size() > 1 ) + { + int decim_factor_log = stoi(match[1]); + GLOBALS::get().decoder_.setupDecimationStagesFactor( pow(2,decim_factor_log) ); + string o_command = "cmd::set:decimation=" + to_string(decim_factor_log); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + else if( regex_match(i_command, match, regex(R"_(set\:gain=([+-]?([0-9]*[.])?[0-9]+))_")) && match.size() > 1 ) + { + double gain = stod(match[1]); + GLOBALS::get().p_iq_source_->setOption("gain_double", &gain); + string o_command = "cmd::set:gain=" + to_string(gain); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + GLOBALS::get().gain_ = gain; + } + else if( regex_match(i_command, match, regex(R"_(set\:lowpass_bw=([+-]?([0-9]*[.])?[0-9]+))_")) && match.size() > 1 ) + { + cout<<"set lowpass_bw "< 1 ) + { + GLOBALS::get().decoder_.lowpass_trans(stof(match[1])); + string o_command = "cmd::set:lowpass_trans=" + to_string(GLOBALS::get().decoder_.lowpass_trans()); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + else if( regex_match(i_command, match, regex(R"_(set\:baud=([+-]?([0-9]*[.])?[0-9]+))_")) && match.size() > 1 ) + { + GLOBALS::get().decoder_.baud( stof(match[1]) ); + string o_command = "cmd::set:baud=" + to_string(GLOBALS::get().decoder_.baud()); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + else if( regex_match(i_command, match, regex(R"_(set\:rtty_bits=(\d+))_")) && match.size() > 1 ) + { + GLOBALS::get().decoder_.rtty_bits(stoi(match[1])); + string o_command = "cmd::set:rtty_bits=" + to_string(GLOBALS::get().decoder_.rtty_bits()); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + else if( regex_match(i_command, match, regex(R"_(set\:rtty_stops=([+-]?([0-9]*[.])?[0-9]+))_")) && match.size() > 1 ) + { + GLOBALS::get().decoder_.rtty_stops(stof(match[1])); + string o_command = "cmd::set:rtty_stops=" + to_string(GLOBALS::get().decoder_.rtty_stops()); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + else if( regex_match(i_command, match, regex(R"_(set\:datasize=(\d+))_")) && match.size() > 1 ) + { + int datasize = stoi(match[1]); + if(datasize != 1 && datasize != 2 && datasize != 4) + datasize = 1; + + if(datasize == 1) GLOBALS::get().transport_data_type_ = GLOBALS::TransportDataType::kChar; // 8bit + if(datasize == 2) GLOBALS::get().transport_data_type_ = GLOBALS::TransportDataType::kShort;// 16 bit + if(datasize == 4) GLOBALS::get().transport_data_type_ = GLOBALS::TransportDataType::kFloat;// 32bit + string o_command = "cmd::set:datasize=" + to_string(datasize); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + else if( regex_match(i_command, match, regex(R"_(set\:biastee=([0-9])+)_")) && match.size() > 1 ) + { + double value = stod(match[1]); + GLOBALS::get().p_iq_source_->setOption("biastee_double", &value); + GLOBALS::get().biast_ = value; + string o_command = "cmd::set:biastee=" + to_string(value); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + else if( regex_match(i_command, match, regex(R"_(set\:afc=([0-9])+)_")) && match.size() > 1 ) + { + int value = stoi(match[1]); + GLOBALS::get().afc_ = value; + string o_command = "cmd::set:afc=" + to_string(value); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + else + { + cout< +void ShrinkVector(T& vec, size_t new_size) +{ + if(new_size >= vec.size()) + return; + + for(size_t i=0; i spectrum_info.size()) + { + spectrum_info.peak_left_ = 0; + spectrum_info.peak_left_valid_ = false; + } + + spectrum_info.peak_right_ -= zoom_slice_begin; + if(spectrum_info.peak_right_ < 0 || spectrum_info.peak_right_ > spectrum_info.size()) + { + spectrum_info.peak_right_ = 0; + spectrum_info.peak_right_valid_ = false; + } + + // transfer resolution - leave only 'resolution' number of bins + // + if(resolution < spectrum_info.size()) + { + spectrum_info.peak_left_ = double(spectrum_info.peak_left_) * resolution / spectrum_info.size(); + spectrum_info.peak_right_ = double(spectrum_info.peak_right_) * resolution / spectrum_info.size(); + ShrinkVector(spectrum_info, resolution); + } + + // choose transport bit resolution: 8, 16, 32 bit + // + if( GLOBALS::get().transport_data_type_ == GLOBALS::TransportDataType::kChar ) + SerializeSpectrum( spectrum_info, res_stream, (unsigned char*)0 ); + if( GLOBALS::get().transport_data_type_ == GLOBALS::TransportDataType::kShort ) + SerializeSpectrum( spectrum_info, res_stream, (unsigned short int*)0 ); + if( GLOBALS::get().transport_data_type_ == GLOBALS::TransportDataType::kFloat ) + SerializeSpectrum( spectrum_info, res_stream, (float*)0 ); + + return spectrum_info.size(); +} + + +// serialize demod +size_t DemodToStream(std::stringstream& res_stream, int resolution) +{ + std::vector demod_acc; + { + std::lock_guard _lock(GLOBALS::get().demod_accumulated_mtx_); + demod_acc = GLOBALS::get().demod_accumulated_; + } + if(demod_acc.size()) + { + ShrinkVector(demod_acc, resolution); + // choose transport datatype: 8, 16, 32 bit + if( GLOBALS::get().transport_data_type_ == GLOBALS::TransportDataType::kChar ) + SerializeDemodulation( demod_acc, res_stream, (unsigned char*)0 ); + if( GLOBALS::get().transport_data_type_ == GLOBALS::TransportDataType::kShort ) + SerializeDemodulation( demod_acc, res_stream, (unsigned short int*)0 ); + if( GLOBALS::get().transport_data_type_ == GLOBALS::TransportDataType::kFloat ) + SerializeDemodulation( demod_acc, res_stream, (float*)0 ); + } + + return demod_acc.size(); +} + +void DoSession(tcp::socket& i_socket) +{ + using namespace std; + + // allow just one session + static std::atomic close_session{false}; + static std::atomic session_running{false}; + + // close previous session + while(session_running) + { + close_session = true; + std::this_thread::sleep_for( ( std::chrono::duration(300) )); + } + + try { + websocket::stream ws{std::move(i_socket)}; + ws.accept(); + session_running = true; + // this line does not work + // ws.accept_ex([](websocket::response_type &m) { m.insert(beast::http::field::server, "habdec_server"); }); + + ws.auto_fragment(false); + + while(!G_DO_EXIT) + { + if(close_session) + { + cout<<"Closing Session."< 2 ) + { + stringstream res_stream; + res_stream<<"PWR_"; + if(SpectrumToStream( res_stream, stof(match[2]), stoi(match[1]) )) + { + ws.binary(true); + ws.write( boost::asio::buffer(res_stream.str()) ); + } + } + // demod=resolution + else if( regex_match(command, match, regex(R"_(cmd\:\:demod\:res=(\d+))_")) && match.size() > 1 ) + { + stringstream res_stream; + res_stream<<"DEM_"; + if( DemodToStream( res_stream, stoi(match[1]) ) ) + { + ws.binary(true); + ws.write( boost::asio::buffer(res_stream.str()) ); + } + } + // cmd::liveprint + else if( regex_match(command, match, regex(R"_(cmd\:\:liveprint)_")) && match.size() > 0 ) + { + string o_command = "cmd::info:liveprint=" + GLOBALS::get().decoder_.getRTTY(); + ws.text(true); + ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) ); + } + // cmd::**** + else if(command.size()>5 && command.substr(0,5) == "cmd::") + { + cout< sentences; + { + lock_guard _lock( GLOBALS::get().senteces_to_web_mtx_ ); + sentences = std::move(GLOBALS::get().senteces_to_web_); + } + for(auto& sentence : sentences) + { + string o_command = "cmd::info:sentence=" + sentence; + ws.text(true); + ws.write( boost::asio::buffer( o_command.c_str(), o_command.size()) ); + } + + // check for out commands + vector out_cmds; + { + lock_guard _lock( GLOBALS::get().out_commands_mtx_ ); + out_cmds = std::move(GLOBALS::get().out_commands_); + } + for(auto& cmd : out_cmds) + { + ws.text(true); + ws.write( boost::asio::buffer( cmd.c_str(), cmd.size()) ); + } + + } + } + catch(const boost::system::system_error& se) { + if(se.code() != websocket::error::closed) + cout << "Error: boost::system::system_error: " << se.code().message() << endl; + else + cout << "Session Closed. " << se.code().message() << endl; + + } + catch(const exception& e) { + cout << "Session Error: " << e.what() << endl; + } + + session_running = false; + cout << "Session END."<( command_port ); + + boost::asio::io_context ioc{1}; + tcp::acceptor acceptor{ioc, {address, port}}; + + while(!G_DO_EXIT) + { + + tcp::socket socket{ioc}; + acceptor.accept(socket); // Block until we get a connection + cout<(1000) )); + } + } +} \ No newline at end of file diff --git a/code/websocketServer/server.h b/code/websocketServer/server.h new file mode 100644 index 0000000..80678f3 --- /dev/null +++ b/code/websocketServer/server.h @@ -0,0 +1,26 @@ +/* + + Copyright 2018 Michal Fratczak + + This file is part of habdec. + + habdec 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 3 of the License, or + (at your option) any later version. + + habdec 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 habdec. If not, see . +*/ + +#pragma once + +#include +#include + +void RunCommandServer(const std::string command_host, const int command_port); diff --git a/webClientScreenshot.png b/webClientScreenshot.png new file mode 100644 index 0000000..01d0668 Binary files /dev/null and b/webClientScreenshot.png differ