pianobooster-src-0.6.4/0000755000175000017500000000000011304222711014053 5ustar louislouispianobooster-src-0.6.4/win32/0000755000175000017500000000000011304222711015015 5ustar louislouispianobooster-src-0.6.4/src/0000755000175000017500000000000011304222711014642 5ustar louislouispianobooster-src-0.6.4/build/0000755000175000017500000000000011304222711015152 5ustar louislouispianobooster-src-0.6.4/src/rtmidi/0000755000175000017500000000000011304222711016132 5ustar louislouispianobooster-src-0.6.4/src/precompile/0000755000175000017500000000000011304222711017001 5ustar louislouispianobooster-src-0.6.4/src/images/0000755000175000017500000000000011304222711016107 5ustar louislouispianobooster-src-0.6.4/license.txt0000644000175000017500000000135711304222711016244 0ustar louislouis Copyright (c) 2008,2009 L. J. Barman, all rights reserved The PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . pianobooster-src-0.6.4/gplv3.txt0000644000175000017500000010451311304222711015653 0ustar louislouis 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 . pianobooster-src-0.6.4/README.txt0000644000175000017500000000774311304222711015564 0ustar louislouis=============================================================================================== INTRODUCTION =============================================================================================== Piano Booster is a MIDI file player that displays the musical notes AND teaches you how to play the piano. You can play along to any track in the midi file and PianoBooster will follow YOUR playing. PianoBooster makes sight reading fun! Piano Booster is a free (Open Source) program available from: =============================================================================================== REQUIREMENTS =============================================================================================== To run Piano Booster you need a MIDI Piano Keyboard and a MIDI interface for the PC. (If you don't have a MIDI keyboard you can still try out PianoBooster using the PC keyboard, 'x' is middle C -- but a MIDI piano is recommend). To hear the music you will need a General Midi compatible sound synthesizer. Unfortunately the "Microsoft GS Wavetable software synthesizer" that comes with Windows XP introduces an unacceptable delay (latency) between pressing a note and hearing the sound. For this reason the use of "Microsoft GS Wavetable software synthesizer" is not recommend. Please see the forum section of the PianoBooster website for possible solutions. =============================================================================================== MIDI FILES =============================================================================================== To run PianoBooster you will need some Midi files preferably with right and left piano parts on channels 4 and 3. Some high quality demo MIDI files that are compatible with PianoBooster are available on the PianoBooster download page see: =============================================================================================== INSTRUCTIONS =============================================================================================== Once the Piano Booster application starts up you must first setup the midi input and midi output interface from the Setup menu. Next open a midi file ".mid" or a karaoke ".kar" file using File/Open from the Piano Booster menu. Now choose the skill level, if you want to just listen to the midi music -- select 'listen', to play along with a midi keyboard with the music following your playing -- select 'follow you'. Finally click on the Play icon to start. It is recommended that you shut down all other programs whilst running Piano Booster so that the scrolling notes move smoothly across the screen. =============================================================================================== LICENSE =============================================================================================== Piano Booster is fully copyrighted by the author and all rights are reserved. PianoBooster is free software (Open Source 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. PianoBooster 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 in the file "gplv3.txt" or from the web site . =============================================================================================== SOURCE CODE =============================================================================================== As part of GNU General Public License the source code for PianoBooster is available from the Source Forge site pianobooster-src-0.6.4/README-OSX.txt0000644000175000017500000001032411304222711016220 0ustar louislouis=============================================================================================== INTRODUCTION =============================================================================================== Piano Booster is a MIDI file player that displays the musical notes AND teaches you how to play the piano. You can play along to any track in the midi file and PianoBooster will follow YOUR playing. PianoBooster makes sight reading fun! Piano Booster is a free (Open Source) program available from: =============================================================================================== REQUIREMENTS =============================================================================================== To run Piano Booster you need a MIDI Piano Keyboard and a MIDI-USB interface if the keyboard does not have a USB interface. (If you don't have a MIDI keyboard you can still try out PianoBooster using the computer's keyboard, 'x' is middle C). To hear music from the computer you will need a General Midi compatible sound synthesizer. While there are many possible choices for the Mac (Timidity, FluidSynth or an external MIDI Synth), the easiest way is to use SimplSynth, which can be obtained for free (MIT license) from: This must be started before Pianobooster, and also allows to load custom Soundfonts. =============================================================================================== MIDI FILES =============================================================================================== To run PianoBooster you will need some Midi files preferably with right and left piano parts on channels 4 and 3. Some high quality demo MIDI files that are compatible with PianoBooster are available on the PianoBooster download page see: =============================================================================================== INSTRUCTIONS =============================================================================================== Double Click on the DMG file containing PianoBooster, then just drag the pianobooster.app file wherever you wish (/Application folder is suggested). Once the Piano Booster application starts up you must first setup the midi input and midi output interface from the Setup menu. Next open a midi file ".mid" or a karaoke ".kar" file using File/Open from the Piano Booster menu. Now choose the skill level, if you want to just listen to the midi music -- select 'listen', to play along with a midi keyboard with the music following your playing -- select 'follow you'. Finally click on the Play icon to start. It is recommended that you shut down all other programs whilst running Piano Booster so that the scrolling notes move smoothly across the screen. =============================================================================================== LICENSE =============================================================================================== Piano Booster is fully copyrighted by the author and all rights are reserved. PianoBooster is free software (Open Source 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. PianoBooster 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 in the file "gplv3.txt" or from the web site . =============================================================================================== SOURCE CODE =============================================================================================== As part of GNU General Public License the source code for PianoBooster is available from the Source Forge site pianobooster-src-0.6.4/BUILD.txt0000644000175000017500000000642311304222711015460 0ustar louislouis=============================================================================================== TO COMPILE THE SOURCE CODE IN LINUX =============================================================================================== Ensure that the following packages 'cmake', 'libqt4-dev', 'libasound2-dev' and 'build-essential" are installed . In the PianoBooster directory type "cd build" to change to the "build" directory then type "cmake ../src", followed by "make". Finally as root type "make install". To build a debug version create a dir called "debug" and change to that dir and then type "cmake -DCMAKE_BUILD_TYPE=Debug ../src" (Alternatively you can use qmake followed by make in the src directory.) If you make changes to the source code then please post details on the forum. =============================================================================================== TO COMPILE THE SOURCE CODE IN MacOSX =============================================================================================== Install latest XCode (from Apple Developer Connection, free registration required) Install CMake and QT libraries (either from source or via Fink or MacPorts) Generate XCode project file, via 'cmake -G Xcode ../src' Open the project file in XCode, set whatever options you like (universal or single architecture, debug or release etc.) and compile To make a self contained application bundle use QT's macdeployqt tool (included in QT 4.5.0) If you make changes to the source code then please post details on the forum. =============================================================================================== TO COMPILE THE SOURCE CODE IN WINDOWS =============================================================================================== To compile in Windows install the Open Source version of Qt and CMake and optionally Geany. When installing Qt select the option to download and install the MinGW compiler. Open the Qt Command Prompt and then change to the "PianoBooster\build" directory and then type the command below. "C:\Program Files\CMake 2.6\bin\cmake.exe" -G "MinGW Makefiles" ..\src Once this is completed type "make". Or alternatively you can install QtCreator and then open the painobooster.pro If you make changes to the source code then please post details on the forum. =============================================================================================== LICENSE =============================================================================================== Piano Booster is fully copyrighted by the author and all rights are reserved. PianoBooster is free software (Open Source 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. PianoBooster 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 in the file "gplv3.txt" or from the web site . pianobooster-src-0.6.4/win32/pianobooster.nsi0000644000175000017500000001040311304222711020232 0ustar louislouis;NSIS Modern User Interface ;create the windows install exectuable ;Piano Booster ;-------------------------------- ;Include Modern UI !include "MUI2.nsh" ;-------------------------------- ;General ; The name of the installer Name "Piano Booster" ; The file to write OutFile "PianoBoosterInstall.exe" ; The default installation directory InstallDir "$PROGRAMFILES\Piano Booster" ; Registry key to check for directory (so if you install again, it will ; overwrite the old one automatically) InstallDirRegKey HKCU "Software\NSIS_PianoBooster" "" ;Request application privileges for Windows Vista RequestExecutionLevel admin ;-------------------------------- ;Variables Var StartMenuFolder ;-------------------------------- ;Interface Settings !define MUI_ABORTWARNING ;-------------------------------- ;Pages !insertmacro MUI_PAGE_WELCOME #!insertmacro MUI_PAGE_LICENSE "${NSISDIR}\Docs\Modern UI\License.txt" #!insertmacro MUI_PAGE_COMPONENTS !insertmacro MUI_PAGE_DIRECTORY ;Start Menu Folder Page Configuration !define MUI_STARTMENUPAGE_REGISTRY_ROOT "HKCU" !define MUI_STARTMENUPAGE_REGISTRY_KEY "Software\NSIS_PianoBooster" !define MUI_STARTMENUPAGE_REGISTRY_VALUENAME "Start Menu Folder" !insertmacro MUI_PAGE_STARTMENU Application $StartMenuFolder !insertmacro MUI_PAGE_INSTFILES !insertmacro MUI_PAGE_FINISH !insertmacro MUI_UNPAGE_WELCOME !insertmacro MUI_UNPAGE_CONFIRM !insertmacro MUI_UNPAGE_INSTFILES !insertmacro MUI_UNPAGE_FINISH ;-------------------------------- ;Languages !insertmacro MUI_LANGUAGE "English" ;-------------------------------- ;Installer Sections Section "Dummy Section" SecDummy SetOutPath "$INSTDIR" ; Put file there File FilesForRelease\pianobooster.exe #File FilesForRelease\libfluidsynth-1.dll File FilesForRelease\QtCore4.dll File FilesForRelease\QtGui4.dll File FilesForRelease\QtXml4.dll File FilesForRelease\QtOpenGL4.dll File FilesForRelease\mingwm10.dll CreateDirectory $INSTDIR\doc SetOutPath $INSTDIR\doc File FilesForRelease\README.txt File FilesForRelease\license.txt File FilesForRelease\gplv3.txt SetOutPath $INSTDIR ; Write the installation path into the registry WriteRegStr HKCU SOFTWARE\NSIS_PianoBooster "" "$INSTDIR" ;Create uninstaller WriteUninstaller "$INSTDIR\Uninstall.exe" !insertmacro MUI_STARTMENU_WRITE_BEGIN Application ;Create shortcuts CreateDirectory "$SMPROGRAMS\$StartMenuFolder" CreateShortCut "$SMPROGRAMS\$StartMenuFolder\Piano Booster.lnk" "$INSTDIR\pianobooster.exe" "" "$INSTDIR\pianobooster.exe" 0 CreateShortCut "$SMPROGRAMS\$StartMenuFolder\ReadMe.lnk" "$INSTDIR\doc\ReadMe.txt" "" "$INSTDIR\doc\ReadMe.txt" 0 CreateShortCut "$SMPROGRAMS\$StartMenuFolder\Uninstall.lnk" "$INSTDIR\Uninstall.exe" !insertmacro MUI_STARTMENU_WRITE_END SectionEnd ;-------------------------------- ;Descriptions ;Language strings ; LangString DESC_SecDummy ${LANG_ENGLISH} "A test section." ;Assign language strings to sections ; !insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN ; !insertmacro MUI_DESCRIPTION_TEXT ${SecDummy} $(DESC_SecDummy) ; !insertmacro MUI_FUNCTION_DESCRIPTION_END ;-------------------------------- ;Uninstaller Section Section "Uninstall" ; Remove files and uninstaller Delete $INSTDIR\pianobooster.exe Delete $INSTDIR\mingwm10.dll #Delete $INSTDIR\libfluidsynth-1.dll Delete $INSTDIR\QtCore4.dll Delete $INSTDIR\QtGui4.dll Delete $INSTDIR\QtXml4.dll Delete $INSTDIR\QtOpenGL4.dll Delete $INSTDIR\mingwm10.dll Delete $INSTDIR\doc\README.txt Delete $INSTDIR\doc\license.txt Delete $INSTDIR\doc\gplv3.txt RMDir "$INSTDIR\doc" Delete $INSTDIR\uninstall.exe RMDir "$INSTDIR" !insertmacro MUI_STARTMENU_GETFOLDER Application $StartMenuFolder ; Remove shortcuts, if any Delete "$SMPROGRAMS\$StartMenuFolder\*.*" RMDir "$SMPROGRAMS\$StartMenuFolder" ; Remove registry keys DeleteRegKey /ifempty HKCU "Software\NSIS_PianoBooster" SectionEnd pianobooster-src-0.6.4/src/pianobooster.rc0000644000175000017500000000010311304222711017666 0ustar louislouisIDI_ICON1 ICON DISCARDABLE "pianobooster.ico" pianobooster-src-0.6.4/src/pianobooster.pro0000644000175000017500000000615711304222711020101 0ustar louislouis#CONFIG += USE_FLUIDSYNTH CONFIG += release USE_FLUIDSYNTH { # Note The FLUIDSYNTH_INPLACE_DIR dir is used mainly used when compiling on windows # You normally do not need to set it #FLUIDSYNTH_INPLACE_DIR = ../../fluidsynth-1.0.9 message(building using fluidsynth) DEFINES += PB_USE_FLUIDSYNTH } CONFIG += precompile_header PRECOMPILED_HEADER = precompile/precompile.h HEADERS = precompile/precompile.h \ QtWindow.h \ GlView.h \ GuiTopBar.h \ GuiSidePanel.h \ GuiMidiSetupDialog.h \ GuiKeyboardSetupDialog.h \ GuiPreferencesDialog.h \ GuiSongDetailsDialog.h \ GuiLoopingPopup.h FORMS = GuiTopBar.ui \ GuiSidePanel.ui \ GuiMidiSetupDialog.ui \ GuiKeyboardSetupDialog.ui \ GuiPreferencesDialog.ui \ GuiSongDetailsDialog.ui \ GuiLoopingPopup.ui RESOURCES = application.qrc SOURCES = QtMain.cpp \ QtWindow.cpp \ GuiTopBar.cpp \ GuiSidePanel.cpp \ GuiMidiSetupDialog.cpp \ GuiKeyboardSetupDialog.cpp \ GuiPreferencesDialog.cpp \ GuiSongDetailsDialog.cpp \ GuiLoopingPopup.cpp \ GlView.cpp \ MidiFile.cpp \ MidiTrack.cpp \ Song.cpp \ Conductor.cpp \ Util.cpp \ Chord.cpp \ Tempo.cpp \ MidiDevice.cpp \ MidiDeviceRt.cpp \ rtmidi/RtMidi.cpp \ StavePosition.cpp \ Score.cpp \ Cfg.cpp \ Piano.cpp \ Draw.cpp \ Scroll.cpp \ Notation.cpp \ TrackList.cpp \ Rating.cpp \ Bar.cpp \ Settings.cpp \ Merge.cpp \ RC_FILE = pianobooster.rc INCLUDEPATH += rtmidi OBJECTS_DIR = tmp win32 { DEFINES += __WINDOWS_MM__ _WIN32 LIBS += libwinmm } unix { DEFINES += __LINUX_ALSASEQ__ LIBS += -lasound } USE_FLUIDSYNTH { SOURCES += MidiDeviceFluidSynth.cpp !isEmpty(FLUIDSYNTH_INPLACE_DIR) { !exists( $${FLUIDSYNTH_INPLACE_DIR}/include/fluidsynth.h ) { error( "No $${FLUIDSYNTH_INPLACE_DIR}/include/fluidsynth.h file found" ) } message(fluidsynth FLUIDSYNTH_INPLACE_DIR = $${FLUIDSYNTH_INPLACE_DIR}) INCLUDEPATH += $${FLUIDSYNTH_INPLACE_DIR}/include/ win32:LIBS += $${FLUIDSYNTH_INPLACE_DIR}/src/.libs/libfluidsynth.dll.a unix:LIBS += $${FLUIDSYNTH_INPLACE_DIR}/src/.libs/libfluidsynth.a } } QT += xml opengl # enable the console window #QT+=testlib unix { isEmpty( PREFIX ) { PREFIX = /usr/local } target.path = $$PREFIX/bin desktop.path = $$PREFIX/share/applications desktop.files = pianobooster.desktop pixmaps.path = $$PREFIX/share/pixmaps pixmaps.files = images/pianobooster.png docs.path = $$PREFIX/share/doc/pianobooster docs.files = ../README.txt INSTALLS += target desktop pixmaps docs } pianobooster-src-0.6.4/src/pianobooster.ico0000644000175000017500000000137611304222711020051 0ustar louislouis ( @DDDDDDDDDDDDDD""""""""B""""""""""""""b""""b""DDDDDDDDDDDDDDDDDDDDDADDDDDDDGwDDDDDDDwxDDDDDDD&h""""""""B"""""b""""b""xwwxDDDDDDwwxwwwtDDDDD`wwwxDDDDDwwwwDDUTDDwwwDEDDwxD]D""""""""""""""""""""""bDDD]TDDDD]DDDDDDUTDDDDDDDDDDDDDDDDDDDDDD""""""""b""""b""""""""""b""""b""DDDDDDDDDDDDDDDDDDDDDDDDDDDDpianobooster-src-0.6.4/src/pianobooster.icns0000644000175000017500000000725511304222711020235 0ustar louislouisicnsis32  '   !  C:  QH Uvpdă e+g]_tyVW% LWDgE9 WukAA3       IETdEHGFGFF%(7  >+B@MLMOLLI?NDBe}v_&+04;ecL r3 hab$HgMIIMMALLweF4OOTUOAM@MM&0  TNNMRQM  WQPPTRQ '  >:89:d;9!MGFFKFF YPPJJSK USM_t  <5-f` %c}ºF !JWM images/Logo32x32.png images/copy.png images/cut.png images/flag.png images/new.png images/open.png images/paste.png images/play-from-start.png images/play.png images/save.png images/stop.png pianobooster-src-0.6.4/src/Util.h0000644000175000017500000000424111304222711015731 0ustar louislouis/*********************************************************************************/ /*! @file Util.h @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __UTIL_H__ #define __UTIL_H__ #include #include #include using namespace std; #define MAX_MIDI_CHANNELS 16 #define MIDDLE_C 60 #define MIDI_OCTAVE 12 #define MIDI_BOTTOM_C (MIDDLE_C - MIDI_OCTAVE*2) #define MIDI_TOP_C (MIDDLE_C + MIDI_OCTAVE*2) #define MAX_MIDI_NOTES 128 typedef unsigned char byte; #define arraySize(a) (sizeof(a)/sizeof(a[0])) /* Returns (at compile time) the number of elements in an array */ #define ppDEBUG(args) ppLogDebug args typedef enum { PB_LOG_error, PB_LOG_warn, PB_LOG_info, PB_LOG_verbose, } logLevel_t; void fatal(const char *msg, ...); void ppLogTrace(const char *msg, ...); void ppLogDebug(const char *msg, ...); void ppLog(logLevel_t level, const char *msg, ...); void ppLogInfo(const char *msg, ...); void ppLogWarn(const char *msg, ...); void ppLogError(const char *msg, ...); void ppTiming(const char *msg, ...); #define SPEED_ADJUST_FACTOR 1000 #define deltaAdjust(delta) ((delta)/SPEED_ADJUST_FACTOR ) void benchMarkInit(); void benchMark(unsigned int id, QString message); void benchMarkResults(); #endif //__UTIL_H__ pianobooster-src-0.6.4/src/Util.cpp0000644000175000017500000001235511304222711016271 0ustar louislouis/*********************************************************************************/ /*! @file Util.cpp @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include #include #include #include #include #include "Util.h" #include "Cfg.h" #include static QTime s_realtime; /* prints an error message to stderr, and dies */ void fatal(const char *msg, ...) { va_list ap; va_start(ap, msg); vfprintf(stderr, msg, ap); va_end(ap); fputc('\n', stderr); exit(EXIT_FAILURE); } void ppLog(logLevel_t level, const char *msg, ...) { va_list ap; if (Cfg::logLevel < level) return; va_start(ap, msg); vfprintf(stdout, msg, ap); va_end(ap); fputc('\n', stdout); } void ppLogInfo(const char *msg, ...) { va_list ap; //fixme should call ppLog if (Cfg::logLevel < 1) return; fputs("Info: ", stdout); va_start(ap, msg); vfprintf(stdout, msg, ap); va_end(ap); fputc('\n', stdout); } void ppLogWarn(const char *msg, ...) { va_list ap; if (Cfg::logLevel < 2) return; fputs("Warn: ", stdout); va_start(ap, msg); vfprintf(stdout, msg, ap); va_end(ap); fputc('\n', stdout); } void ppLogTrace(const char *msg, ...) { va_list ap; fputs("Trace: ", stdout); va_start(ap, msg); vfprintf(stdout, msg, ap); va_end(ap); fputc('\n', stdout); } void ppLogDebug( const char *msg, ...) { va_list ap; fputs("Debug: ", stdout); va_start(ap, msg); vfprintf(stdout, msg, ap); va_end(ap); fputc('\n', stdout); } void ppLogError(const char *msg, ...) { va_list ap; fputs("ERROR: ", stdout); va_start(ap, msg); vfprintf(stdout, msg, ap); va_end(ap); fputc('\n', stdout); } void ppTiming(const char *msg, ...) { va_list ap; va_start(ap, msg); fprintf(stdout, "T %4d " , s_realtime.restart() ); vfprintf(stdout, msg, ap); va_end(ap); fputc('\n', stdout); } ////////////////////// BENCH MARK ////////////////////// static QTime s_benchMarkTime; static int s_previousTime; static int s_previousFrameTime; typedef struct { int time; QString msg; int deltaTotal; int deltaCount; int maxDelta; int minDelta; int frameRatePrevious; int frameRateCurrent; } benchData_t; benchData_t s_benchData[20]; benchData_t s_frameRate; void benchMarkReset(benchData_t *pBench) { pBench->deltaTotal = 0; pBench->deltaCount = 0; pBench->maxDelta = 0; pBench->minDelta = 9999999; pBench->frameRatePrevious = pBench->frameRateCurrent; } void benchMarkInit() { s_benchMarkTime.start(); s_previousTime = 0; s_previousFrameTime = 0; for (unsigned int i=0; i < arraySize( s_benchData ); i++) benchMarkReset(&s_benchData[i]); benchMarkReset(&s_frameRate); s_frameRate.msg = " *** Frame Rate ***"; } int benchMarkUpdate(benchData_t *pBench, int previousTime) { int time = s_benchMarkTime.elapsed(); int delta = time - previousTime; pBench->deltaTotal += delta; pBench->deltaCount++; pBench->frameRateCurrent = time; pBench->maxDelta = qMax(pBench->maxDelta, delta); pBench->minDelta = qMin(pBench->minDelta, delta); return time; } void benchMark(unsigned int id, QString message) { if (id >= arraySize(s_benchData)) return; if (s_benchData[id].msg.size() == 0 ) s_benchData[id].msg = message; s_previousTime = benchMarkUpdate(&s_benchData[id], s_previousTime); } void printResult(int i, benchData_t *pBench) { if (pBench->deltaCount == 0) return; if (i>=0) fprintf(stdout, "Bench%2d: ", i); else fputs("Bench : ", stdout); fprintf(stdout, "ct %4d, min %2d, avg %4.3f, max %2d frame %4.3f %s\n", pBench->deltaCount, pBench->minDelta, static_cast(pBench->deltaTotal)/pBench->deltaCount, pBench->maxDelta, (static_cast(pBench->frameRateCurrent - pBench->frameRatePrevious))/pBench->deltaCount, qPrintable(pBench->msg)); benchMarkReset(pBench); } void benchMarkResults() { int ticks; ticks = s_benchMarkTime.elapsed(); if ( (ticks - s_previousFrameTime) < 5000) return; s_previousFrameTime = ticks; for (unsigned int i=0; i < arraySize( s_benchData ); i++) { printResult(i, &s_benchData[i]); } } pianobooster-src-0.6.4/src/TrackList.h0000644000175000017500000000507011304222711016715 0ustar louislouis/*********************************************************************************/ /*! @file TrackList.h @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __TRACK_LIST_H__ #define __TRACK_LIST_H__ #include #include #include #include "MidiEvent.h" #include "Chord.h" #define CONVENTION_LEFT_HAND_CHANNEL (3-1) #define CONVENTION_RIGHT_HAND_CHANNEL (4-1) class CSong; class CSettings; class CTrackListItem { public: int midiChannel; }; class CTrackList { public: CTrackList() { m_song = 0; m_settings = 0; clear(); } void init(CSong* songObj, CSettings* settings); void refresh(); void clear(); void currentRowChanged(int currentRow); void examineMidiEvent(CMidiEvent event); bool pianoPartConvetionTest(); int guessKeySignature(int chanA, int chanB); // The programme name now starts at 1 with 0 = "(none)" static QString getProgramName(int program); QStringList getAllChannelProgramNames(bool raw=false); int getActiveItemIndex(); int getActiveHandIndex(whichPart_t whichPart); // set the midi channels to use for the left and right hand piano parts void setActiveHandsIndex(int leftIndex, int rightIndex); int getHandTrackIndex(whichPart_t whichPart); void changeListWidgetItemView(unsigned int index, QListWidgetItem* listWidgetItem); private: QString getChannelProgramName(int chan); CSong* m_song; CSettings* m_settings; QList m_trackQtList; bool m_midiActiveChannels[MAX_MIDI_CHANNELS]; int m_midiFirstPatchChannels[MAX_MIDI_CHANNELS]; int m_noteFrequency[MAX_MIDI_CHANNELS][MAX_MIDI_NOTES]; }; #endif //__TRACK_LIST_H__ pianobooster-src-0.6.4/src/TrackList.cpp0000644000175000017500000003510511304222711017252 0ustar louislouis/*********************************************************************************/ /*! @file TrackList.cpp @brief The Design. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include #include "TrackList.h" #include "Song.h" #include "Settings.h" void CTrackList::init(CSong* songObj, CSettings* settings) { m_song = songObj; m_settings = settings; } void CTrackList::clear() { int chan; for (chan = 0; chan < MAX_MIDI_CHANNELS; chan++) { m_midiActiveChannels[chan] = false; m_midiFirstPatchChannels[chan] = -1; for (int i = 0; i < MAX_MIDI_NOTES; i++) m_noteFrequency[chan][i]=0; } m_trackQtList.clear(); } void CTrackList::currentRowChanged(int currentRow) { if (!m_song) return; if (currentRow >= m_trackQtList.size()|| currentRow < 0) return; m_song->setActiveChannel(m_trackQtList[currentRow].midiChannel); } void CTrackList::examineMidiEvent(CMidiEvent event) { int chan; chan = event.channel(); assert (chan < MAX_MIDI_CHANNELS && chan >= 0); if (chan < MAX_MIDI_CHANNELS && chan >= 0) { if (event.type() == MIDI_NOTE_ON) { m_midiActiveChannels[chan] = true; // count each note so we can guess the key signature if (event.note() >= 0 && event.note() < MAX_MIDI_NOTES) m_noteFrequency[chan][event.note()]++; // If we have a note and no patch then default to grand piano patch if (m_midiFirstPatchChannels[chan] == -1) m_midiFirstPatchChannels[chan] = GM_PIANO_PATCH; } if (event.type() == MIDI_PROGRAM_CHANGE && m_midiActiveChannels[chan] == false) m_midiFirstPatchChannels[chan] = event.programme(); } } // Returns true if there is a piano part on channels 3 & 4 bool CTrackList::pianoPartConvetionTest() { if ((m_midiFirstPatchChannels[CONVENTION_LEFT_HAND_CHANNEL] == GM_PIANO_PATCH && m_midiActiveChannels[CONVENTION_LEFT_HAND_CHANNEL] == true && m_midiFirstPatchChannels[CONVENTION_RIGHT_HAND_CHANNEL] <= GM_PIANO_PATCH)) return true; if (m_midiFirstPatchChannels[CONVENTION_RIGHT_HAND_CHANNEL] == GM_PIANO_PATCH && m_midiActiveChannels[CONVENTION_RIGHT_HAND_CHANNEL] == true && m_midiFirstPatchChannels[CONVENTION_LEFT_HAND_CHANNEL] <= GM_PIANO_PATCH) return true; if (m_midiFirstPatchChannels[CONVENTION_LEFT_HAND_CHANNEL] == GM_PIANO_PATCH && m_midiActiveChannels[CONVENTION_LEFT_HAND_CHANNEL] == true && m_midiFirstPatchChannels[CONVENTION_RIGHT_HAND_CHANNEL] <= GM_PIANO_PATCH) return true; return false; } int CTrackList::guessKeySignature(int chanA, int chanB) { int chan; int i; int keySignature = 0; int highScore = 0; int scale[MIDI_OCTAVE]; for (i=0; i < MIDI_OCTAVE; i++) scale[i] = 0; for (chan = 0 ; chan < MAX_MIDI_CHANNELS; chan++) { if (chanA == -1 || chan == chanA || chan == chanB) { for (int note = 0; note < MAX_MIDI_NOTES; note++) scale[note % MIDI_OCTAVE] += m_noteFrequency[chan][note]; } } for (i = 0; i < MIDI_OCTAVE; i++) { int score = 0; struct { int offset; int key; } keyLookUp[MIDI_OCTAVE] = { {0, 0}, // 0 C {7, 1}, // 1 G 1# {5, -1}, // 2 F 1b {2, 2}, // 3 D 2# {10,-2}, // 4 Bb 2b {9, 3}, // 5 A 3# {3, -3}, // 6 Eb 3b {4, 4}, // 7 E 4# {8, -4}, // 8 Ab 4b {11, 5}, // 9 B 5# {1, -5}, // 10 Db 5b {6, 6}, // 11 F# 6# }; int idx = keyLookUp[i].offset; score += scale[(idx + 0 )%MIDI_OCTAVE]; // First note in the scale score += scale[(idx + 2 )%MIDI_OCTAVE]; // Tone score += scale[(idx + 4 )%MIDI_OCTAVE]; // Tone score += scale[(idx + 5 )%MIDI_OCTAVE]; // Semi tone score += scale[(idx + 7 )%MIDI_OCTAVE]; // Tone score += scale[(idx + 9 )%MIDI_OCTAVE]; // Tone score += scale[(idx + 11)%MIDI_OCTAVE]; // Tone // the Last note don't count it if (score > highScore) { highScore = score; keySignature = keyLookUp[i].key; } /* printf("key %2d score %3d :: ", keyLookUp[i].key, score); for (int j=0; j < MIDI_OCTAVE; j++) printf(" %d", scale[(keyLookUp[i].offset + j)%MIDI_OCTAVE]); printf("\n"); */ } return keySignature; } void CTrackList::refresh() { int chan; int rowCount = 0; m_trackQtList.clear(); for (chan = 0; chan < MAX_MIDI_CHANNELS; chan++) { if (m_midiActiveChannels[chan] == true) { CTrackListItem trackItem; trackItem.midiChannel = chan; m_trackQtList.append(trackItem); rowCount++; } } if (pianoPartConvetionTest()) { if (CNote::bothHandsChan() == -2 ) // -2 for not set -1 for not used CNote::setChannelHands(CONVENTION_LEFT_HAND_CHANNEL, CONVENTION_RIGHT_HAND_CHANNEL); m_song->setActiveChannel(CNote::bothHandsChan()); ppLogInfo("Active both"); } else { if (m_trackQtList.count() > 0) { m_song->setActiveChannel(m_trackQtList[0].midiChannel); } } if (CStavePos::getKeySignature() == NOT_USED) CStavePos::setKeySignature(guessKeySignature(CNote::rightHandChan(),CNote::leftHandChan()), 0); int goodChan = -1; // Find an unused channel that we can use for the keyboard for (chan = 0; chan < MAX_MIDI_CHANNELS; chan++) { if (m_midiActiveChannels[chan] == false) { if (goodChan != -1) { m_song->setPianistChannels(goodChan,chan); ppLogInfo("Using Pianist Channels %d + %d", goodChan +1, chan +1); return; } goodChan = chan; } } // As we have not returned we have not found to empty channels to use if (goodChan == -1) goodChan = 15 -1; m_song->setPianistChannels(goodChan,16-1); } int CTrackList::getActiveItemIndex() { int chan; for (int i = 0; i < m_trackQtList.size(); ++i) { chan = m_trackQtList.at(i).midiChannel; if (chan == CNote::rightHandChan() ) return i; } return 0; // Not found so return first item on the list } QStringList CTrackList::getAllChannelProgramNames(bool raw) { QStringList items; int chan; QString text; QString hand; for (int i = 0; i < m_trackQtList.size(); ++i) { hand.clear(); chan = m_trackQtList.at(i).midiChannel; if (raw == false) { if (CNote::leftHandChan() == chan) hand += "L"; if (CNote::rightHandChan() == chan) hand += "R"; } text = QString::number(chan+1) + hand + " " + getChannelProgramName(chan); items += text; } return items; } int CTrackList::getActiveHandIndex(whichPart_t whichPart) { int index = 0; for (int i = 0; i < m_trackQtList.size(); ++i) if (m_trackQtList.at(i).midiChannel == CNote::getHandChannel( whichPart)) return index; return index; } void CTrackList::setActiveHandsIndex(int leftIndex, int rightIndex) { int leftChannel = -1; int rightChannel = -1; if (leftIndex>=0) leftChannel = m_trackQtList.at(leftIndex).midiChannel; if (rightIndex>=0) rightChannel = m_trackQtList.at(rightIndex).midiChannel; m_settings->setChannelHands(leftChannel, rightChannel); refresh(); m_song->rewind(); } // get the track index number of the selected hand int CTrackList::getHandTrackIndex(whichPart_t whichPart) { int index = 0; int midiHand = CNote::getHandChannel(whichPart); for (int i = 0; i < m_trackQtList.size(); ++i) { if (m_trackQtList.at(i).midiChannel == midiHand) return index; index++; } return -1; } void CTrackList::changeListWidgetItemView( unsigned int index, QListWidgetItem* listWidgetItem ) { int chan = m_trackQtList[index].midiChannel; if ( CNote::hasPianoPart( chan )) { QFont font = listWidgetItem->font(); if (CNote::rightHandChan() >= 0 && CNote::leftHandChan() >= 0 ) font.setBold(true); listWidgetItem->setFont(font); listWidgetItem->setForeground(Qt::darkBlue); } else if ( m_song->hasPianistKeyboardChannel( chan ) ) listWidgetItem->setForeground(Qt::lightGray); } QString CTrackList::getChannelProgramName(int chan) { if(chan<0 || chan>= static_cast(arraySize(m_midiFirstPatchChannels))) { assert(true); return QString(); } int program = m_midiFirstPatchChannels[chan]; if (chan==10-1) return "Drums"; QString name = getProgramName(program +1); // Skip if (name.isEmpty()) name = "Unknown"; return name; } QString CTrackList::getProgramName(int program) { const char * const gmInstrumentNames[] = { "(None)", // Don't use /* 1. */ "Grand Piano", /* 2. */ "Bright Piano", /* 3. */ "Electric Grand", /* 4. */ "Honky-tonk Piano", /* 5. */ "Electric Piano 1", /* 6. */ "Electric Piano 2", /* 7. */ "Harpsichord", /* 8. */ "Clavi", /* 9. */ "Celesta", /* 10. */ "Glockenspiel", /* 11. */ "Music Box", /* 12. */ "Vibraphone", /* 13. */ "Marimba", /* 14. */ "Xylophone", /* 15. */ "Tubular Bells", /* 16. */ "Dulcimer", /* 17. */ "Drawbar Organ", /* 18. */ "Percussive Organ", /* 19. */ "Rock Organ", /* 20. */ "Church Organ", /* 21. */ "Reed Organ", /* 22. */ "Accordion", /* 23. */ "Harmonica", /* 24. */ "Tango Accordion", /* 25. */ "Acoustic Guitar (nylon)", /* 26. */ "Acoustic Guitar (steel)", /* 27. */ "Electric Guitar (jazz)", /* 28. */ "Electric Guitar (clean)", /* 29. */ "Electric Guitar (muted)", /* 30. */ "Overdriven Guitar", /* 31. */ "Distortion Guitar", /* 32. */ "Guitar harmonics", /* 33. */ "Acoustic Bass", /* 34. */ "Electric Bass (finger)", /* 35. */ "Electric Bass (pick)", /* 36. */ "Fretless Bass", /* 37. */ "Slap Bass 1", /* 38. */ "Slap Bass 2", /* 39. */ "Synth Bass 1", /* 40. */ "Synth Bass 2", /* 41. */ "Violin", /* 42. */ "Viola", /* 43. */ "Cello", /* 44. */ "Contrabass", /* 45. */ "Tremolo Strings", /* 46. */ "Pizzicato Strings", /* 47. */ "Orchestral Harp", /* 48. */ "Timpani", /* 49. */ "String Ensemble 1", /* 50. */ "String Ensemble 2", /* 51. */ "SynthStrings 1", /* 52. */ "SynthStrings 2", /* 53. */ "Choir Aahs", /* 54. */ "Voice Oohs", /* 55. */ "Synth Voice", /* 56. */ "Orchestra Hit", /* 57. */ "Trumpet", /* 58. */ "Trombone", /* 59. */ "Tuba", /* 60. */ "Muted Trumpet", /* 61. */ "French Horn", /* 62. */ "Brass Section", /* 63. */ "SynthBrass 1", /* 64. */ "SynthBrass 2", /* 65. */ "Soprano Sax", /* 66. */ "Alto Sax", /* 67. */ "Tenor Sax", /* 68. */ "Baritone Sax", /* 69. */ "Oboe", /* 70. */ "English Horn", /* 71. */ "Bassoon", /* 72. */ "Clarinet", /* 73. */ "Piccolo", /* 74. */ "Flute", /* 75. */ "Recorder", /* 76. */ "Pan Flute", /* 77. */ "Blown Bottle", /* 78. */ "Shakuhachi", /* 79. */ "Whistle", /* 80. */ "Ocarina", /* 81. */ "Lead 1 (square)", /* 82. */ "Lead 2 (sawtooth)", /* 83. */ "Lead 3 (calliope)", /* 84. */ "Lead 4 (chiff)", /* 85. */ "Lead 5 (charang)", /* 86. */ "Lead 6 (voice)", /* 87. */ "Lead 7 (fifths)", /* 88. */ "Lead 8 (bass + lead)", /* 89. */ "Pad 1 (new age)", /* 90. */ "Pad 2 (warm)", /* 91. */ "Pad 3 (polysynth)", /* 92. */ "Pad 4 (choir)", /* 93. */ "Pad 5 (bowed)", /* 94. */ "Pad 6 (metallic)", /* 95. */ "Pad 7 (halo)", /* 96. */ "Pad 8 (sweep)", /* 97. */ "FX 1 (rain)", /* 98. */ "FX 2 (soundtrack)", /* 99. */ "FX 3 (crystal)", /* 100. */ "FX 4 (atmosphere)", /* 101. */ "FX 5 (brightness)", /* 102. */ "FX 6 (goblins)", /* 103. */ "FX 7 (echoes)", /* 104. */ "FX 8 (sci-fi)", /* 105. */ "Sitar", /* 106. */ "Banjo", /* 107. */ "Shamisen", /* 108. */ "Koto", /* 109. */ "Kalimba", /* 110. */ "Bag pipe", /* 111. */ "Fiddle", /* 112. */ "Shanai", /* 113. */ "Tinkle Bell", /* 114. */ "Agogo", /* 115. */ "Steel Drums", /* 116. */ "Woodblock", /* 117. */ "Taiko Drum", /* 118. */ "Melodic Tom", /* 119. */ "Synth Drum", /* 120. */ "Reverse Cymbal", /* 121. */ "Guitar Fret Noise", /* 122. */ "Breath Noise", /* 123. */ "Seashore", /* 124. */ "Bird Tweet", /* 125. */ "Telephone Ring", /* 126. */ "Helicopter", /* 127. */ "Applause", /* 128. */ "Gunshot", }; if (program >= 0 && program < static_cast(arraySize(gmInstrumentNames))) return gmInstrumentNames[program]; else return QString(); } pianobooster-src-0.6.4/src/Tempo.h0000644000175000017500000000574011304222711016105 0ustar louislouis/*********************************************************************************/ /*! @file Tempo.h @brief Tries to automatically calculate the tempo. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __TEMPO_H__ #define __TEMPO_H__ #include "MidiEvent.h" #include "MidiFile.h" #include "Chord.h" // Define a chord class CTempo { public: CTempo() { m_savedwantedChord = 0; reset(); } void setSavedwantedChord(CChord * savedwantedChord) { m_savedwantedChord = savedwantedChord; } void reset() { m_midiTempo = 1000000 * 120 / 60;// 120 beats per minute is the default m_jumpAheadDelta = 0; } void setMidiTempo(int tempo) { m_midiTempo = float (tempo) * DEFAULT_PPQN / CMidiFile::getPulsesPerQuarterNote(); ppLogWarn("Midi Tempo %f %d", m_midiTempo, CMidiFile::getPulsesPerQuarterNote()); } void setSpeed(float speed) { // limit the allowed speed if (speed > 2.0f) speed = 2.0f; if (speed < 0.1f) speed = 0.1f; m_userSpeed = speed; } float getSpeed() {return m_userSpeed;} int mSecToTicks(int mSec) { return static_cast(mSec * m_userSpeed * 100000000.0 /m_midiTempo); } void insertPlayingTicks(int ticks) { m_jumpAheadDelta -= ticks; if (m_jumpAheadDelta < CMidiFile::ppqnAdjust(-10)*SPEED_ADJUST_FACTOR) m_jumpAheadDelta = CMidiFile::ppqnAdjust(-10)*SPEED_ADJUST_FACTOR; } void removePlayingTicks(int ticks) { if (m_cfg_maxJumpAhead != 0) m_jumpAheadDelta = ticks; } void clearPlayingTicks() { m_jumpAheadDelta = 0; } void adjustTempo(int * ticks); static void enableFollowTempo(bool enable); private: float m_userSpeed; // controls the speed of the piece playing float m_midiTempo; // controls the speed of the piece playing int m_jumpAheadDelta; static int m_cfg_maxJumpAhead; static int m_cfg_followTempoAmount; CChord *m_savedwantedChord; // A copy of the wanted chord complete with both left and right parts }; #endif // __TEMPO_H__ pianobooster-src-0.6.4/src/Tempo.cpp0000644000175000017500000000363711304222711016443 0ustar louislouis/*********************************************************************************/ /*! @file Tempo.cpp @brief Tries to automatically calculate the tempo. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include "Tempo.h" int CTempo::m_cfg_followTempoAmount = 0; int CTempo::m_cfg_maxJumpAhead = 0; void CTempo::enableFollowTempo(bool enable) { if (enable) { m_cfg_maxJumpAhead = 1; m_cfg_followTempoAmount = 1; } else { m_cfg_maxJumpAhead = 0; m_cfg_followTempoAmount = 0; } } void CTempo::adjustTempo(int * ticks) { if (m_jumpAheadDelta && m_cfg_maxJumpAhead && m_savedwantedChord) { if (m_jumpAheadDelta > 0) *ticks += m_jumpAheadDelta; // Automatically adjust the speed m_userSpeed = m_userSpeed + m_userSpeed * m_jumpAheadDelta * 0.00002; if (m_userSpeed> 2.0) m_userSpeed = 2.0; if (m_userSpeed < 0.2) m_userSpeed = 0.2; printf("%03.0f %5d\r",m_userSpeed *100, m_jumpAheadDelta ); fflush(stdout); m_jumpAheadDelta = 0; } } pianobooster-src-0.6.4/src/Symbol.h0000644000175000017500000001214611304222711016264 0ustar louislouis/*********************************************************************************/ /*! @file Symbol.h @brief A single musical symbols (eg note, rest, slur) that can appear on the page. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef _SYMBOL_H_ #define _SYMBOL_H_ #include "Util.h" #include "Cfg.h" #include "StavePosition.h" typedef enum { PB_SYMBOL_none, PB_SYMBOL_note, PB_SYMBOL_drum, PB_SYMBOL_gClef, // The Treble Clef PB_SYMBOL_fClef, // The Base Clef PB_SYMBOL_sharp, PB_SYMBOL_flat, PB_SYMBOL_natural, PB_SYMBOL_barLine, PB_SYMBOL_barMarker, PB_SYMBOL_beatMarker, PB_SYMBOL_playingZone, PB_SYMBOL_theEnd } musicalSymbol_t; typedef enum { PB_ACCIDENTAL_MODIFER_noChange, PB_ACCIDENTAL_MODIFER_suppress, PB_ACCIDENTAL_MODIFER_force // force a natural/accidental to be played } accidentalModifer_t; #define BEAT_MARKER_OFFSET 20 // used to ensure that beat markers are drawn under the note by drawing them early class CSymbol { public: //////////////////////////////////////////////////////////////////////////////// //@brief constructors CSymbol(musicalSymbol_t type, whichPart_t hand, int midiNote, int midiDuration = 0) { init(); m_symbolType = type; m_midiNote = midiNote; m_hand = hand; m_midiDuration = midiDuration; m_stavePos.notePos(hand, midiNote); } CSymbol() { init(); } CSymbol(musicalSymbol_t type, CStavePos stavePos, CColour colour = Cfg::noteColour()) { init(); m_symbolType = type; m_stavePos = stavePos; m_colour = colour; m_hand = stavePos.getHand(); } //////////////////////////////////////////////////////////////////////////////// //@brief Get the type of symbol musicalSymbol_t getType(){return m_symbolType;} //////////////////////////////////////////////////////////////////////////////// //@brief how long is the note int getMidiDuration(){return m_midiDuration;} //////////////////////////////////////////////////////////////////////////////// //@brief returns the midi note number int getNote(){return m_midiNote;} //////////////////////////////////////////////////////////////////////////////// //@brief returns the midi note number whichPart_t getHand(){return m_hand;} //////////////////////////////////////////////////////////////////////////////// //@brief get the Stave Position CStavePos getStavePos(){return m_stavePos;} void setColour(CColour colour){ m_colour = colour;} CColour getColour(){return m_colour;} void setPianistTiming(int timing){ m_pianistTiming = timing;} int getPianistTiming(){ return m_pianistTiming; } void transpose(int amount) { if (m_symbolType == PB_SYMBOL_note) { m_midiNote += amount; m_stavePos.notePos(m_hand, m_midiNote); // The save position has now moved } } void setIndex(int index, int total) { m_index = index; m_total = total; } int getNoteIndex() { return m_index; } int getNoteTotal() { return m_total; } //////////////////////////////////////////////////////////////////////////////// //! @brief The accidental //! return 0 = none, 1=sharp, -1 =flat, 2=natural. int getAccidental() { return getStavePos().getAccidental(); } void setAccidentalModifer(accidentalModifer_t value) {m_accidentalModifer = value;} accidentalModifer_t getAccidentalModifer() {return m_accidentalModifer;} private: void init() { m_symbolType = PB_SYMBOL_none; m_midiNote = 0; m_hand = PB_PART_none; m_midiDuration = 0; m_pianistTiming = NOT_USED; setIndex(0,0); m_accidentalModifer = PB_ACCIDENTAL_MODIFER_noChange; } CStavePos m_stavePos; musicalSymbol_t m_symbolType; byte m_midiNote; accidentalModifer_t m_accidentalModifer; // Used to suppress the second sharp in the same bar unsigned long m_midiDuration; whichPart_t m_hand; CColour m_colour; int m_pianistTiming; int m_index; // the number of the note per hand starting from the bottom. int m_total; // the number of the notes per hand; }; #endif // _SYMBOL_H_ pianobooster-src-0.6.4/src/StavePosition.h0000644000175000017500000001364311304222711017631 0ustar louislouis/*********************************************************************************/ /*! @file StavePosition.h @brief xxxxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __STAVE_POS_H__ #define __STAVE_POS_H__ #include "Util.h" #include "Chord.h" #include typedef struct { int pianoNote; // 1 is Middle C, 2 is D int accidental; } staveLookup_t; #define NOT_USED 0x7fffffff #define MAX_STAVE_INDEX 16 #define MIN_STAVE_INDEX -16 //---------------------------------------------------------------------------- // CStavePos //---------------------------------------------------------------------------- //! @brief Calculates the position on the stave from the stave index number. class CStavePos { public: //////////////////////////////////////////////////////////////////////////////// //! @brief The default constructor. CStavePos() { m_staveIndex = 0; m_accidental = 0; setHand(PB_PART_none); }; //////////////////////////////////////////////////////////////////////////////// //! @brief Constructs the Stave position object. //! @param hand the top (right hand) or the bottom the (left hand) see @ref whichPart_t. //! @param index the save index number: 0 central line, 5 = top line, -5 the bottom line. //! @param accidental Indicates an accidental 0 = none, 1=sharp, -1 =flat. CStavePos(whichPart_t hand, int index, int accidental = 0) { m_staveIndex = index; m_accidental = accidental; setHand(hand); }; //////////////////////////////////////////////////////////////////////////////// //! @brief Sets which stave the note will appear on //! @param hand the top (right hand) or the bottom the (left hand) see @ref whichPart_t. void setHand(whichPart_t hand) { m_hand = hand; m_offsetY = getStaveCenterY(); if (m_hand == PB_PART_right) m_offsetY += staveCentralOffset(); else if (m_hand == PB_PART_left) m_offsetY -= staveCentralOffset(); } void notePos(whichPart_t hand, int midiNote); //////////////////////////////////////////////////////////////////////////////// //! @brief Sets which stave the note will appear on //! return The position on the stave. float getPosY() { return verticalNoteSpacing() * m_staveIndex + m_offsetY ; } float getPosYAccidental() { int accidental = m_accidental; if (accidental == 2) accidental = 1; else if (accidental == -2) accidental = -1; return getPosY() + accidental*verticalNoteSpacing()/2; } float getPosYRelative() { return getPosY() - m_staveCenterY;} // get the Y position relative to the stave centre //////////////////////////////////////////////////////////////////////////////// //! @brief The accidental //! return 0 = none, 1=sharp, -1 =flat, 2=natural. int getAccidental() {return m_accidental;} int getStaveIndex() {return m_staveIndex;} whichPart_t getHand() {return m_hand;} static float getVerticalNoteSpacing(){return verticalNoteSpacing();} static float getStaveCenterY(){return m_staveCenterY;} static void setStaveCenterY(float y) { m_staveCenterY = y; } static void setKeySignature(int key, int majorMinor); static int getKeySignature() {return m_KeySignature;} static void setStaveCentralOffset(float gap) { m_staveCentralOffset = gap; } static float verticalNoteSpacing() {return 7;} static float staveHeight() {return verticalNoteSpacing() * 8;} static float staveCentralOffset() {return m_staveCentralOffset;} // convert the midi note to the note name A B C D E F G static staveLookup_t midiNote2Name(int midiNote); static const staveLookup_t* getstaveLookupTable(int key); // do we show a sharp or a flat for this key signature // returns 0 = none, 1=sharp, -1 =flat, 2=natural (# Key) , -2=natural (b Key) static int getStaveAccidental(int midiNote) { return m_staveLookUpTable[midiNote%12].accidental; } // returns 0 = none, 1=above, -1 =below, (a natural is either above or below) static int getStaveAccidentalDirection(int midiNote) { int accidentalDirection = getStaveAccidental(midiNote); if (accidentalDirection == 2) // A natural so change to above accidentalDirection = 1; else if (accidentalDirection == -2) // A natural so change to below accidentalDirection = -1; return accidentalDirection; } private: // fixme TODO This could be improved as the calculations could a done in the constructor char m_staveIndex; // 0 central line, 5 = top line, -5 the bottom line, int m_accidental; // 0 = none, 1=sharp, -1 =flat, 2=natural float m_offsetY; whichPart_t m_hand; static int m_KeySignature; static int m_KeySignatureMajorMinor; static const staveLookup_t* m_staveLookUpTable; static float m_staveCentralOffset; static float m_staveCenterY; }; #endif //__STAVE_POS_H__ pianobooster-src-0.6.4/src/StavePosition.cpp0000644000175000017500000002137511304222711020165 0ustar louislouis/*********************************************************************************/ /*! @file StavePos.h @brief xxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include "StavePosition.h" #include "Draw.h" float CStavePos::m_staveCenterY; int CStavePos::m_KeySignature; int CStavePos::m_KeySignatureMajorMinor; const staveLookup_t* CStavePos::m_staveLookUpTable; float CStavePos::m_staveCentralOffset = (staveHeight() * 3)/2; //////////////////////////////////////////////////////////////////////////////// //! @brief Calculates the position of a note on the stave void CStavePos::notePos(whichPart_t hand, int midiNote) { const int notesInAnOctive = 7; // Don't count middle C twice const int semitonesInAnOctive = 12; setHand(hand); int index = midiNote % semitonesInAnOctive; const staveLookup_t* lookUpItem; lookUpItem = &m_staveLookUpTable[index]; if (m_hand == PB_PART_right) m_staveIndex = lookUpItem->pianoNote - 7; else if (m_hand == PB_PART_left) m_staveIndex = lookUpItem->pianoNote + 5; m_staveIndex += (midiNote/semitonesInAnOctive)*notesInAnOctive - notesInAnOctive*5 ; m_accidental = lookUpItem->accidental; //ppLogTrace("chan %d Note %2d - %2d (%d %d %d),\n", midiNote, m_staveIndex, m_accidental, //index%semitonesInAnOctive, lookUpItem->pianoNote, (midiNote/semitonesInAnOctive)*notesInAnOctive); } // convert the midi note to the note name C=1, D=2, E=3, F=4, G=5, A=6, B=7 staveLookup_t CStavePos::midiNote2Name(int midiNote) { const staveLookup_t* staffLookupC = getstaveLookupTable(0); // Key of C so we get all the not names const int semitonesInAnOctive = 12; int index = midiNote % semitonesInAnOctive; staveLookup_t item = staffLookupC[index]; if (item.accidental != 0) // should it be a sharp or a flat { // Should it be called for example G# or Ab if (item.pianoNote != m_staveLookUpTable[index].pianoNote) { item.pianoNote = m_staveLookUpTable[index].pianoNote; if (m_KeySignature > 0) item.accidental = 1; // And change to sharp else item.accidental = -1; // But use a flat } } return item; } void CStavePos::setKeySignature(int key, int majorMinor) { m_KeySignature = key; m_KeySignatureMajorMinor = majorMinor; if (key == NOT_USED) key = 0; m_staveLookUpTable = getstaveLookupTable(key); CDraw::forceCompileRedraw(); } const staveLookup_t* CStavePos::getstaveLookupTable(int key) { const staveLookup_t* staveLookup; static const staveLookup_t staffLookupFlat6[] = { // Gb [Bb Eb Ab Db Gb Cb] {1, 2}, // Cn {2, 0}, //.Db {2, 2}, // Dn {3, 0}, //.Eb {3, 2}, // En {4, 0}, //.F {5, 0}, //-Gb {5, 2}, // Gn {6, 0}, //.Ab {6, 2}, // An {7, 0}, //.Bb {8, 0} //.Cb also called Bn }; static const staveLookup_t staffLookupFlat5[] = { // Db [Bb Eb Ab Db Gb] {1, 0}, //.C {2, 0}, //-Db {2, 2}, // Dn {3, 0}, //.Eb {3, 2}, // En {4, 0}, //.F {5, 0}, //.Gb {5, 2}, // Gn {6, 0}, //.Ab {6, 2}, // An {7, 0}, //.Bb {7, 2} // Bn }; static const staveLookup_t staffLookupFlat4[] = { // Ab [Bb Eb Ab Db] {1, 0}, //.C {2, 0}, //.Db {2, 2}, // Dn {3, 0}, //.Eb {3, 2}, // En {4, 0}, //.F {5,-1}, // Gb {5, 0}, //.G {6, 0}, //-Ab {6, 2}, // An {7, 0}, //.Bb {7, 2} // Bn }; static const staveLookup_t staffLookupFlat3[] = { // Eb [Bb Eb Ab] {1, 0}, //.C {2,-1}, // Db {2, 0}, //.D {3, 0}, //-Eb {3, 2}, // En {4, 0}, //.F {5,-1}, // Gb {5, 0}, //.G {6, 0}, //.Ab {6, 2}, // An {7, 0}, //.Bb {7, 2} // Bn }; static const staveLookup_t staffLookupFlat2[] = { // Bb [Bb Eb] {1, 0}, //.C {2,-1}, // Db {2, 0}, //.D {3, 0}, //.Eb {3, 2}, // En {4, 0}, //.F {4, 1}, // F# (Gb) {5, 0}, //.G {6,-1}, // Ab {6, 0}, //.A {7, 0}, //-Bb {7, 2} // Bn }; static const staveLookup_t staffLookupFlat1[] = { // F [Bb] {1, 0}, //.C {1, 1}, // C# (Db) {2, 0}, //.D {3,-1}, // Eb {3, 0}, //.E {4, 0}, //-F {4, 1}, // F# {5, 0}, //.G {6,-1}, // Ab {6, 0}, //.A {7, 0}, //.Bb {7, 2} // Bn }; // more flats Cb Gb Db Ab Eb Bb <--> F# C# G# D# A# E# more sharps static const staveLookup_t staffLookupC[] = { {1, 0}, //-C {1, 1}, // C# {2, 0}, //.D {3,-1}, // Eb {3, 0}, //.E {4, 0}, //.F {4, 1}, // F# {5, 0}, //.G {5, 1}, // G# (or Ab) {6, 0}, //.A {7,-1}, // Bb {7, 0} //.B }; static const staveLookup_t staffLookupSharp1[] = { // G [F#] {1, 0}, //.C {1, 1}, // C# {2, 0}, //.D {2, 1}, // D# (Eb) {3, 0}, //.E {4,-2}, // Fn {4, 0}, //.F# {5, 0}, //-G {5, 1}, // G# {6, 0}, //.A {7,-1}, // Bb {7, 0} //.B }; static const staveLookup_t staffLookupSharp2[] = { // D [F# C#] {1,-2}, // Cn {1, 0}, //.C# {2, 0}, //-D {2, 1}, // D# {3, 0}, //.E {4,-2}, // Fn {4, 0}, //.F# {5, 0}, //.G {5, 1}, // G# {6, 0}, //.A {6, 1}, // A# (Bb) {7, 0} //.B }; static const staveLookup_t staffLookupSharp3[] = { // A [F# C# G#] {1,-2}, // Cn {1, 0}, //.C# {2, 0}, //.D {2, 1}, // D# {3, 0}, //.E {4,-2}, // Fn {4, 0}, //.F# {5,-2}, // Gn {5, 0}, //.G# {6, 0}, //-A {6, 1}, // A# {7, 0} //.B }; static const staveLookup_t staffLookupSharp4[] = { // E [F# C# G# D#] {1,-2}, // Cn {1, 0}, //.C# {2,-2}, // Dn {2, 0}, //.D# {3, 0}, //-E {4,-2}, // Fn {4, 0}, //.F# {5,-2}, // Gn {5, 0}, //.G# {6, 0}, //.A {6, 1}, // A# {7, 0} //.B }; static const staveLookup_t staffLookupSharp5[] = { // B [F# C# G# D# A#] {1,-2}, // Cn {1, 0}, //.C# {2,-2}, // Dn {2, 0}, //.D# {3, 0}, //.E {4,-2}, // Fn {4, 0}, //.F# {5,-2}, // Gn {5, 0}, //.G# {6,-2}, // An {6, 0}, //.A# {7, 0} //-B }; // I think there should be some double sharps here ?? static const staveLookup_t staffLookupSharp6[] = { // F# [F# C# G# D# A# E#] {1,-2}, // Cn {1, 0}, //.C# {2,-2}, // Dn {2, 0}, //.D# {3,-2}, // En {3, 0}, //.E# (really F natural!!!!) {4, 0}, //-F# {5,-2}, // Gn {5, 0}, //.G# {6,-2}, // An {6, 0}, //.A# {7, 0} //.B }; // Cb Gb Db Ab Eb Bb <> F# C# G# D# A# E# switch (key) { case -6: staveLookup = staffLookupFlat6; break; case -5: staveLookup = staffLookupFlat5; break; case -4: staveLookup = staffLookupFlat4; break; case -3: staveLookup = staffLookupFlat3; break; case -2: staveLookup = staffLookupFlat2; break; case -1: staveLookup = staffLookupFlat1; break; case 0: staveLookup = staffLookupC; break; case 1: staveLookup = staffLookupSharp1; break; case 2: staveLookup = staffLookupSharp2; break; case 3: staveLookup = staffLookupSharp3; break; case 4: staveLookup = staffLookupSharp4; break; case 5: staveLookup = staffLookupSharp5; break; case 6: staveLookup = staffLookupSharp6; break; default: staveLookup = staffLookupC; break; } return staveLookup; } pianobooster-src-0.6.4/src/Song.h0000644000175000017500000000467711304222711015737 0ustar louislouis/*********************************************************************************/ /*! @file Song.h @brief xxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __SONG_H__ #define __SONG_H__ #include #include "Notation.h" #include "Conductor.h" #include "TrackList.h" #define PC_KEY_LOWEST_NOTE 58 #define PC_KEY_HIGHEST_NOTE 75 class CSong : public CConductor { public: CSong() { CStavePos::setKeySignature( NOT_USED, 0 ); m_midiFile = new CMidiFile; m_trackList = new CTrackList; reset(); } ~CSong() { delete m_midiFile; delete m_trackList; } void reset() { m_reachedMidiEof = false; m_findChord.reset(); } void init(CScore * scoreWin, CSettings* settings); eventBits_t task(int ticks); bool pcKeyPress(int key, bool down); void loadSong(const QString &filename); void regenerateChordQueue(); void rewind(); void playFromStartBar() { rewind(); playMusic(true); } void setActiveHand(whichPart_t hand); whichPart_t getActiveHand(){return CNote::getActiveHand();} void setActiveChannel(int part); void setPlayMode(playMode_t mode); CTrackList* getTrackList() {return m_trackList;} void refreshScroll(); QString getSongTitle() {return m_songTitle;} private: void midiFileInfo(); CMidiFile * m_midiFile; CFindChord m_findChord; bool m_reachedMidiEof; CChord m_fakeChord; // the chord played with the tab key CTrackList* m_trackList; QString m_songTitle; }; #endif // __SONG_H__ pianobooster-src-0.6.4/src/Song.cpp0000644000175000017500000001644711304222711016270 0ustar louislouis/*********************************************************************************/ /*! @file Song.cpp @brief xxxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include "Song.h" #include "Score.h" void CSong::init(CScore * scoreWin, CSettings* settings) { CNote::setChannelHands(-2, -2); // -2 for not set -1 for none this->CConductor::init(scoreWin, settings); setActiveHand(PB_PART_both); setPlayMode(PB_PLAY_MODE_followYou); setSpeed(1.0); setSkill(3); } void CSong::loadSong(const QString & filename) { CNote::setChannelHands(-2, -2); // -2 for not set -1 for none m_songTitle = filename; int index = m_songTitle.lastIndexOf("/"); if (index >= 0) m_songTitle = m_songTitle.right( m_songTitle.length() - index - 1); QString fn = filename; #ifdef _WIN32 fn = fn.replace('/','\\'); #endif m_midiFile->setLogLevel(3); m_midiFile->openMidiFile(string(fn.toAscii())); ppLogInfo("Opening song %s", string(fn.toAscii()).c_str()); transpose(0); midiFileInfo(); m_midiFile->setLogLevel(99); playMusic(false); rewind(); setPlayFromBar(0.0); setLoopingBars(0.0); setEventBits(EVENT_BITS_playingStopped); if (!m_midiFile->getSongTitle().isEmpty()) m_songTitle = m_midiFile->getSongTitle(); } // read the file ahead to collect info about the song first void CSong::midiFileInfo() { m_trackList->clear(); setTimeSig(0,0); CStavePos::setKeySignature( NOT_USED, 0 ); // Read the next events to find the active channels CMidiEvent event; while ( true ) { event = m_midiFile->readMidiEvent(); m_trackList->examineMidiEvent(event); if (event.type() == MIDI_PB_timeSignature) { setTimeSig(event.data1(),event.data2()); } if (event.type() == MIDI_PB_EOF) break; } } void CSong::rewind() { m_midiFile->rewind(); this->CConductor::rewind(); m_scoreWin->reset(); reset(); forceScoreRedraw(); } void CSong::setActiveHand(whichPart_t hand) { if (hand < PB_PART_both) hand = PB_PART_both; if (hand > PB_PART_left) hand = PB_PART_left; this->CConductor::setActiveHand(hand); m_scoreWin->setDisplayHand(hand); } void CSong::setActiveChannel(int chan) { this->CConductor::setActiveChannel(chan); m_scoreWin->setActiveChannel(chan); regenerateChordQueue(); } void CSong::setPlayMode(playMode_t mode) { regenerateChordQueue(); this->CConductor::setPlayMode(mode); forceScoreRedraw(); } void CSong::regenerateChordQueue() { int i; int length; CMidiEvent event; m_wantedChordQueue->clear(); m_findChord.reset(); length = m_songEventQueue->length(); for (i = 0; i < length; i++) { event = m_songEventQueue->index(i); // Find the next chord if (m_findChord.findChord(event, getActiveChannel(), PB_PART_both) == true) chordEventInsert( m_findChord.getChord() ); // give the Conductor the chord event } resetWantedChord(); } void CSong::refreshScroll() { m_scoreWin->refreshScroll(); forceScoreRedraw(); } eventBits_t CSong::task(int ticks) { realTimeEngine(ticks); while (true) { if (m_reachedMidiEof == true) goto exitTask; while (true) { // Check that there is space if (midiEventSpace() <= 10 || chordEventSpace() <= 10) break; // and that the Score has space also if (m_scoreWin->midiEventSpace() <= 100) break; // Read the next events CMidiEvent event = m_midiFile->readMidiEvent(); //ppLogTrace("Song event delta %d type 0x%x chan %d Note %d", event.deltaTime(), event.type(), event.channel(), event.note()); // Find the next chord if (m_findChord.findChord(event, getActiveChannel(), PB_PART_both) == true) chordEventInsert( m_findChord.getChord() ); // give the Conductor the chord event // send the events to the other end m_scoreWin->midiEventInsert(event); // send the events to the other end midiEventInsert(event); if (event.type() == MIDI_PB_EOF) { m_reachedMidiEof = true; break; } } // carry on with the data until we reach the bar we want if (seekingBarNumber() && m_reachedMidiEof == false && playingMusic()) { realTimeEngine(0); m_scoreWin->drawScrollingSymbols(false); // don't display any thing just remove from the queue } else break; } exitTask: eventBits_t eventBits = m_realTimeEventBits; m_realTimeEventBits = 0; return eventBits; } static const struct pcNote_s { int key; int note; } pcNoteLookup[] = { { 'a', PC_KEY_LOWEST_NOTE }, { 'z', 59 }, // B { 'x', 60 }, // Middle C { 'd', 61 }, { 'c', 62 }, // D { 'f', 63 }, { 'v', 64 }, // E { 'b', 65 }, // F { 'h', 66 }, { 'n', 67 }, // G { 'j', 68 }, { 'm', 69 }, // A { 'k', 70 }, { ',', 71 }, // B { '.', 72 }, // C { ';', 73 }, { '/', 74 }, // D { '\'', PC_KEY_HIGHEST_NOTE }, }; // Fakes a midi piano keyboard using the PC keyboard bool CSong::pcKeyPress(int key, bool down) { int i; size_t j; CMidiEvent midi; const int cfg_pcKeyVolume = 64; const int cfg_pcKeyChannel = 1-1; if (key == '\t') // the tab key on the PC fakes good notes { if (down) m_fakeChord = getWantedChord(); for (i = 0; i < m_fakeChord.length(); i++) { if (down) midi.noteOnEvent(0, cfg_pcKeyChannel, m_fakeChord.getNote(i).pitch() + getTranspose(), cfg_pcKeyVolume); else midi.noteOffEvent(0, cfg_pcKeyChannel, m_fakeChord.getNote(i).pitch() + getTranspose(), cfg_pcKeyVolume); pianistInput(midi); } return true; } for (j = 0; j < arraySize(pcNoteLookup); j++) { if ( key==pcNoteLookup[j].key) { if (down) midi.noteOnEvent(0, cfg_pcKeyChannel, pcNoteLookup[j].note, cfg_pcKeyVolume); else midi.noteOffEvent(0, cfg_pcKeyChannel, pcNoteLookup[j].note, cfg_pcKeyVolume); pianistInput(midi); return true; } } //printf("pcKeyPress %d %d\n", m_pcNote, key); return false; } pianobooster-src-0.6.4/src/Settings.h0000644000175000017500000001062211304222711016614 0ustar louislouis/*! @file Settings.h @brief Save all the settings for the programme in the right place. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ #ifndef __SETTINGS_H__ #define __SETTINGS_H__ #include #include #include "Song.h" #include "Notation.h" class GuiSidePanel; class GuiTopBar; class QtWindow; /// Save all the settings for the programme in the right place. class CSettings : public QSettings { public: CSettings(QtWindow *mainWindow); void init(CSong* song, GuiSidePanel* sidePanel, GuiTopBar* topBar); /// returns true if the users wants to see the note names bool isNoteNamesEnabled() { return m_noteNamesEnabled; } bool displayCourtesyAccidentals() { return CNotation::displayCourtesyAccidentals(); } /// Saves in the .ini file whether the user wants to show the note names void setNoteNamesEnabled(bool value); void setCourtesyAccidentals(bool value); void setAdvancedMode(bool value) { m_advancedMode = value;} /// returns true if the users wants to see the note names bool showNoteNames(){ return m_noteNamesEnabled; } void openSongFile(const QString & filename); QString getCurrentSongName() { return m_currentSongName; } void setCurrentSongName(const QString & name); QString getCurrentBookName() { return m_currentBookName; } void setCurrentBookName(const QString & name, bool clearSongName); QStringList getBookList(); QStringList getSongList(); void writeSettings(); void loadSettings(); QString getCurrentSongLongFileName() { if (getCurrentSongName().isEmpty()) return QString(); return m_bookPath + getCurrentBookName() + '/' + getCurrentSongName(); } QStringList getFluidSoundFontNames() { return m_fluidSoundFontNames; } void addFluidSoundFontName(QString sfName) { m_fluidSoundFontNames.append(sfName); } void removeFluidSoundFontName(QString sfName) { m_fluidSoundFontNames.removeAll(sfName); } void pianistActive() { m_pianistActive = true;} void setActiveHand(whichPart_t hand); void setChannelHands(int left, int right); void fastUpdateRate(bool fullSpeed); QString getWarningMessage() {return m_warningMessage;} void updateWarningMessages(); private: QDomElement openDomElement(QDomElement parent, const QString & elementName, const QString & attributeName = QString()); void loadHandSettings(); void saveHandSettings(); void loadPartSettings(); void savePartSettings(); void loadSongSettings(); void saveSongSettings(); void loadBookSettings(); void saveBookSettings(); void loadXmlFile(); void saveXmlFile(); void setDefaultValue(const QString & key, const QVariant & value ); // returns either 'left' 'right' or 'both' const QString partToHandString(whichPart_t part) { if (part == PB_PART_left) return "left"; else if (part == PB_PART_right) return "right"; return "both"; } QDomDocument m_domDocument; // The Complete XML DOM document for one book QDomElement m_domBook; // only one book QDomElement m_domSong; // The Elements for each song QDomElement m_domHand; // The saved settings for each hand QtWindow *m_mainWindow; CSong* m_song; GuiSidePanel* m_guiSidePanel; GuiTopBar* m_guiTopBar; bool m_noteNamesEnabled; bool m_advancedMode; QString m_bookPath; QString m_currentBookName; QString m_currentSongName; QString m_warningMessage; QStringList m_fluidSoundFontNames; bool m_pianistActive; }; #endif // __SETTINGS_H__ pianobooster-src-0.6.4/src/Settings.cpp0000644000175000017500000002630011304222711017147 0ustar louislouis/*! @file Settings.cpp @brief Save all the settings for the programme in the right place. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*! * The following attributes are save in the pb.cfg xml file * BOOK: * name the name of the book * lastsong the name of the last song played so it can be restored * * SONG: * name * hand * leftHandMidiChannel * rightHandMidiChannel * * HAND: * speed * */ #include #include #include "Settings.h" #include "GuiTopBar.h" #include "GuiSidePanel.h" #include "QtWindow.h" #include "ReleaseNote.txt" #define OPTION_DEBUG_SETTINGS 0 #if OPTION_DEBUG_SETTINGS #define debugSettings(args) qDebug args #else #define debugSettings(args) #endif CSettings::CSettings(QtWindow *mainWindow) : QSettings(CSettings::IniFormat, CSettings::UserScope, "PianoBooster", "Piano Booster"), m_mainWindow(mainWindow) { // It is all done in the initialisation list m_advancedMode = false; m_pianistActive = false; m_noteNamesEnabled = value("Score/NoteNames", true ).toBool(); CNotation::setCourtesyAccidentals(value("Score/CourtesyAccidentals", false ).toBool()); } void CSettings::setDefaultValue(const QString & key, const QVariant & value ) { if (contains(key)) // Do not change the value if it already set return; setValue(key, value); } void CSettings::init(CSong* song, GuiSidePanel* sidePanel, GuiTopBar* topBar) { m_song = song; m_guiSidePanel = sidePanel; m_guiTopBar = topBar; // Set defualt values setValue("PianoBooster/Version",PB_VERSION); setDefaultValue("ShortCuts/LeftHand", "F2"); setDefaultValue("ShortCuts/BothHands","F3"); setDefaultValue("ShortCuts/RightHand","F4"); setDefaultValue("ShortCuts/PlayFromStart","space"); setDefaultValue("ShortCuts/PlayPause","P"); setDefaultValue("ShortCuts/Faster","="); setDefaultValue("ShortCuts/Slower","-"); setDefaultValue("ShortCuts/NextSong","]"); setDefaultValue("ShortCuts/PreviousSong","["); } void CSettings::setNoteNamesEnabled(bool value) { m_noteNamesEnabled = value; setValue("Score/NoteNames", value ); } void CSettings::setCourtesyAccidentals(bool value) { CNotation::setCourtesyAccidentals(value); setValue("Score/CourtesyAccidentals", value ); } // Open a document if it exists or else create it (also delete an duplicates QDomElement CSettings::openDomElement(QDomElement parent, const QString & elementName, const QString & attributeName) { QDomElement wantedElement; debugSettings(("openDomElement1 %s %s %s", qPrintable(parent.tagName()), qPrintable(elementName), qPrintable(elementName))); // There should be only a single element without a name // there should be lots of elemens but only one with this tag name QDomNode n = parent.firstChild(); while(!n.isNull()) { QDomElement e = n.toElement(); // try to convert the node to an element. debugSettings(("openDomElement2 tagName %s %s", qPrintable(e.tagName()), qPrintable(elementName))); if(!e.isNull() && e.tagName() == elementName) { if (attributeName.isEmpty() || e.attribute("name") == attributeName) { debugSettings(("openDomElement3 ragName %s %s", qPrintable(e.attribute("name")), qPrintable(attributeName))); if (wantedElement.isNull()) wantedElement = e; // we have found a match else parent.removeChild(e); // remove unwanted duplicates } } n = n.nextSibling(); } if (wantedElement.isNull()) { // Create the element because it does not exsist wantedElement = m_domDocument.createElement(elementName); if (!attributeName.isEmpty() ) wantedElement.setAttribute("name", attributeName); parent.appendChild(wantedElement); } return wantedElement; } void CSettings::loadHandSettings() { if (m_domSong.isNull()) return; m_domHand = openDomElement(m_domSong, "hand", partToHandString(m_song->getActiveHand())); //m_guiTopBar->setSpeed(m_domHand.attribute("speed", "100" ).toInt()); } void CSettings::saveHandSettings() { //m_domHand.setAttribute("speed", m_guiTopBar->getSpeed()); } void CSettings::loadSongSettings() { m_domSong = openDomElement(m_domBook, "song", m_currentSongName); m_guiSidePanel->setCurrentHand(m_domSong.attribute("hand", "both" )); m_guiTopBar->setSpeed(m_domSong.attribute("speed", "100" ).toInt()); // -1 means none and -2 means not set int left = m_domSong.attribute("leftHandMidiChannel", "-2").toInt(); int right = m_domSong.attribute("rightHandMidiChannel", "-2").toInt(); CNote::setChannelHands(left, right); loadHandSettings(); } void CSettings::saveSongSettings() { m_domSong.setAttribute("hand", partToHandString(m_song->getActiveHand())); m_domSong.setAttribute("speed", m_guiTopBar->getSpeed()); saveHandSettings(); } void CSettings::loadBookSettings() { QDomElement root = m_domDocument.documentElement(); m_domBook = openDomElement(root, "book"); QString lastSong = m_domBook.attribute("lastsong"); if (!lastSong.isEmpty() && m_currentSongName.isEmpty()) m_currentSongName = lastSong; } void CSettings::saveBookSettings() { if (!m_currentBookName.isEmpty()) m_domBook.setAttribute("name", m_currentBookName); if (!m_currentSongName.isEmpty()) m_domBook.setAttribute("lastsong", m_currentSongName); saveSongSettings(); } void CSettings::loadXmlFile() { m_domDocument.documentElement().clear(); m_domDocument.clear(); m_domBook.clear(); m_domSong.clear(); m_domHand.clear(); QFile file(m_bookPath + getCurrentBookName() + '/' + "pb.cfg"); if (file.open(QIODevice::ReadOnly)) { if (!m_domDocument.setContent(&file)) { ppLogError("Cannot setContent on XLM file"); } file.close(); } QDomElement root = m_domDocument.documentElement(); if (root.tagName() != "pianobooster") { m_domDocument.clear(); QDomComment comment = m_domDocument.createComment("Piano Booster Configuration file"); m_domDocument.appendChild(comment); root = m_domDocument.createElement("pianobooster"); m_domDocument.appendChild(root); } loadBookSettings(); } // save the xml void CSettings::saveXmlFile() { saveBookSettings(); const int IndentSize = 4; QFile file(m_bookPath + getCurrentBookName() + '/' + "pb.cfg"); // don't save the config file unless the user really is using the system if (m_pianistActive == false && file.exists() == false) return; m_pianistActive = false; if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { ppLogError("Cannot save xml file %s", qPrintable(file.fileName())); return; } QTextStream out(&file); m_domDocument.save(out, IndentSize); file.close(); } void CSettings::openSongFile(const QString & filename) { if (!QFile::exists(filename)) { ppLogWarn( "File does not exists %s", qPrintable(filename)); return; } QDir dirBooks; QString currentSongName; if (filename.isEmpty()) { dirBooks.setPath( QDir::homePath()); } else { dirBooks.setPath(filename); currentSongName = dirBooks.dirName(); dirBooks.cdUp(); m_currentBookName = dirBooks.dirName(); dirBooks.cdUp(); } m_bookPath = dirBooks.path() + '/'; m_currentSongName = currentSongName; m_guiSidePanel->loadBookList(); updateWarningMessages(); } void CSettings::setActiveHand(whichPart_t hand) { saveHandSettings(); m_song->setActiveHand(hand); loadHandSettings(); } QStringList CSettings::getSongList() { debugSettings(("getSongList %s + %s", qPrintable(getCurrentBookName()), qPrintable(m_bookPath))); QDir dirSongs = QDir(m_bookPath + getCurrentBookName()); dirSongs.setFilter(QDir::Files); QStringList fileNames = dirSongs.entryList(); QStringList songNames; for (int i = 0; i < fileNames.size(); i++) { if ( fileNames.at(i).endsWith(".mid", Qt::CaseInsensitive ) || fileNames.at(i).endsWith(".midi", Qt::CaseInsensitive ) || fileNames.at(i).endsWith(".kar", Qt::CaseInsensitive ) ) { songNames += fileNames.at(i); } } return songNames; } QStringList CSettings::getBookList() { QDir dirBooks( m_bookPath); dirBooks.setFilter(QDir::Dirs | QDir::NoDotAndDotDot); return dirBooks.entryList(); } void CSettings::writeSettings() { if (QFile::exists(getCurrentSongLongFileName() )) setValue("CurrentSong", getCurrentSongLongFileName()); saveXmlFile(); } void CSettings::loadSettings() { QString songName = value("CurrentSong").toString(); if (!songName.isEmpty()) openSongFile( songName ); updateWarningMessages(); } void CSettings::setCurrentSongName(const QString & name) { if (name.isEmpty()) return; saveSongSettings(); m_currentSongName = name; debugSettings(("setCurrentSongName %s -- %s", qPrintable(name), qPrintable(getCurrentSongLongFileName()))); setValue("CurrentSong", getCurrentSongLongFileName()); m_song->loadSong(getCurrentSongLongFileName()); loadSongSettings(); m_guiSidePanel->refresh(); m_guiTopBar->refresh(true); m_mainWindow->setWindowTitle("Piano Booster - " + m_song->getSongTitle()); } void CSettings::setCurrentBookName(const QString & name, bool clearSongName) { if (name.isEmpty()) return; if (!m_currentBookName.isEmpty() && m_currentBookName != name) saveXmlFile(); m_currentBookName = name; if (clearSongName) m_currentSongName.clear(); debugSettings(("setCurrentBookName %s --- %s ", qPrintable(name), qPrintable(getCurrentSongLongFileName()))); loadXmlFile(); } void CSettings::setChannelHands(int left, int right) { CNote::setChannelHands(left, right); m_domSong.setAttribute("leftHandMidiChannel", left); m_domSong.setAttribute("rightHandMidiChannel", right); m_guiSidePanel->refresh(); } void CSettings::updateWarningMessages() { if (!m_song->validMidiOutput()) m_warningMessage = tr("NO MIDI OUTPUT DEVICE: Use menu Setup/Midi Setup ..."); else if (m_currentSongName.isEmpty()) m_warningMessage = tr("NO MIDI FILE LOADED: Use menu File/Open ..."); else m_warningMessage.clear(); } pianobooster-src-0.6.4/src/Scroll.h0000644000175000017500000000715111304222711016255 0ustar louislouis/*********************************************************************************/ /*! @file Scroll.h @brief The Design. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __SCROLL_H__ #define __SCROLL_H__ #include "Draw.h" #include "Song.h" #include "Queue.h" #define QUEUE_LENGTH 1000 class CSettings; class CScroll : public CDraw { public: CScroll(int id, CSettings* settings) : CDraw(settings) { m_id = id; m_symbolID = 0; m_notation = new CNotation(); m_scrollQueue = new CQueue(QUEUE_LENGTH); reset(); m_show = false; m_noteSpacingFactor = 1.0; m_ppqnFactor = 1.0; m_transpose = 0; } ~CScroll() { delete m_scrollQueue; delete m_notation; } void reset(); void scrollDeltaTime(int ticks); void transpose(int transpose); void refresh(); void setPlayedNoteColour(int note, CColour colour, int wantedDelta, int pianistTimming); void setChannel(int chan) { m_notation->setChannel( chan ); } //! add a midi event to be analysed and displayed on the score void midiEventInsert(CMidiEvent event) { m_notation->midiEventInsert(event);} //! first check if there is space to add a midi event int midiEventSpace() { return m_notation->midiEventSpace(); } void drawScrollingSymbols(bool show); void showScroll(bool show); private: class CSlotDisplayList : public CSlot { public: CSlotDisplayList(): m_displayListId(0){}; CSlotDisplayList(const CSlot &slot, GLuint displayListId, GLuint nextDisplayListId); GLuint m_displayListId; // the open GL display list id for this slot GLuint m_nextDisplayListId; // and this points to the next one }; void compileSlot(CSlotDisplayList info); bool validPianistChord(int index); bool insertSlots(); void removeSlots(); void removeEarlyTimingMakers(); int findWantedChord(int note, CColour colour, int wantedDelta); int m_id; // There are lots of these class running but each class has a unique id CNotation *m_notation; int m_deltaHead; int m_deltaTail; GLuint m_symbolID; // the next Display List name (or ID) to use CSlot m_headSlot; // The next slot to be put in at the head of the queue; int m_transpose; int m_wantedIndex; // The index number of the wanted call in the scrollQueue int m_wantedDelta; // The running delta time of the wanted chord CQueue* m_scrollQueue; // The current active display list of notes/chords on the screen bool m_show; // set to true to show on the screen float m_noteSpacingFactor; float m_ppqnFactor; // if PulsesPerQuarterNote is 96 then the factor is 1.0 }; #endif //__SCROLL_H__ pianobooster-src-0.6.4/src/Scroll.cpp0000644000175000017500000002452111304222711016610 0ustar louislouis/*********************************************************************************/ /*! @file Scroll.c @brief xxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include "Cfg.h" #include "Scroll.h" //#define NOTE_AHEAD_GAP 50 //#define NOTE_BEHIND_GAP 14 #define NOTE_AHEAD_GAP 22 // the notes on the left hand side of the score #define NOTE_BEHIND_GAP 14 void CScroll::compileSlot(CSlotDisplayList info) { int i; if (m_show == false || info.m_displayListId == 0) return; glNewList (info.m_displayListId, GL_COMPILE); glTranslatef (info.getDeltaTime() * m_noteSpacingFactor, 0.0, 0.0); /* move position */ info.transpose(m_transpose); CStavePos stavePos; int av8Left = info.getAv8Left(); for (i=0; i < info.length(); i++) { stavePos.notePos(info.getSymbol(i).getHand(), info.getSymbol(i).getNote()); //ppLogTrace ("compileSlot len %d id %2d next %2d time %2d type %2d note %2d", info.length(), info.m_displayListId, //info.m_nextDisplayListId, info.getDeltaTime(), info.getSymbol(i).getType(), info.getSymbol(i).getNote()); drawSymbol(info.getSymbol(i), 0.0, stavePos.getPosYRelative()); // we add this back when drawing this symbol } glCallList (info.m_nextDisplayListId); /* Automatically draw the next slot even if it is not there yet */ glEndList (); } /*! Insert a symbol into the display list * @return false when we have run out of symbols */ bool CScroll::insertSlots() { GLuint nextListId = 0; if (m_headSlot.length() == 0) m_headSlot = m_notation->nextSlot(); if (m_headSlot.length() == 0 || m_headSlot.getSymbolType(0) == PB_SYMBOL_theEnd) // this means we have reached the end of the file return false; while (true) { float headDelta = deltaAdjust(m_deltaHead) * m_noteSpacingFactor; float slotDetlta = Cfg::staveEndX() - Cfg::playZoneX() - m_headSlot.getDeltaTime() * m_noteSpacingFactor - NOTE_BEHIND_GAP; if (headDelta > slotDetlta) break; if (m_show) { if (m_symbolID == 0) m_symbolID = glGenLists (1); nextListId = glGenLists (1); } else { nextListId = m_symbolID = 0; } CSlotDisplayList info(m_headSlot, m_symbolID, nextListId); m_deltaHead += info.getDeltaTime() * SPEED_ADJUST_FACTOR; compileSlot(info); m_scrollQueue->push(info); m_symbolID = nextListId; m_headSlot = m_notation->nextSlot(); if (m_headSlot.length() == 0 || m_headSlot.getSymbolType(0) == PB_SYMBOL_theEnd) // this means we have reached the end of the file return false; } return true; } void CScroll::removeEarlyTimingMakers() { float delta = deltaAdjust(m_deltaTail) * m_noteSpacingFactor + Cfg::playZoneX() - Cfg::scrollStartX() - NOTE_AHEAD_GAP; // only look a few steps (10) into the scroll queue for (int i = 0; i < 10 && i < m_scrollQueue->length(); i++ ) { if (delta < -(m_scrollQueue->index(i).getLeftSideDeltaTime() * m_noteSpacingFactor)) { m_scrollQueue->indexPtr(i)->clearAllNoteTimmings(); compileSlot(m_scrollQueue->index(i)); } delta += m_scrollQueue->index(i).getDeltaTime() * m_noteSpacingFactor; } } void CScroll::removeSlots() { while (m_scrollQueue->length() > 0) { if (deltaAdjust(m_deltaTail) * m_noteSpacingFactor > -Cfg::playZoneX() + Cfg::scrollStartX() + NOTE_AHEAD_GAP -(m_scrollQueue->index(0).getLeftSideDeltaTime() * m_noteSpacingFactor) ) break; CSlotDisplayList info = m_scrollQueue->pop(); m_deltaTail += info.getDeltaTime() * SPEED_ADJUST_FACTOR; //ppLogTrace("Remove slot id %2d time %2d type %2d note %2d", info.m_displayListId, info.getDeltaTime(), info.getSymbol(0).getType(), info.getSymbol(0).getNote()); if (info.m_displayListId) glDeleteLists( info.m_displayListId, 1); if (m_wantedIndex > 0) m_wantedIndex--; // also the Chord has moved down one place else { m_wantedIndex = 0; m_wantedDelta = m_deltaTail; } } } //! Draw all the symbols that we have in the list void CScroll::drawScrollingSymbols(bool show) { insertSlots(); // new symbols at the end of the score removeSlots(); // delete old symbols no longer required removeEarlyTimingMakers(); if (show == false) // Just update the queue only return; if (m_scrollQueue->length() == 0 || m_scrollQueue->indexPtr(0)->m_displayListId == 0) return; glPushMatrix(); glTranslatef (Cfg::playZoneX() + deltaAdjust(m_deltaTail) * m_noteSpacingFactor, CStavePos::getStaveCenterY(), 0.0); BENCHMARK(8, "glTranslatef"); if (m_scrollQueue->length() > 0) glCallList (m_scrollQueue->indexPtr(0)->m_displayListId); BENCHMARK(9, "glCallList"); glPopMatrix(); } void CScroll::scrollDeltaTime(int ticks) { m_deltaHead -= ticks; m_deltaTail -= ticks; m_wantedDelta -= ticks; } bool CScroll::validPianistChord(int index) { CSlot* pSlot = m_scrollQueue->indexPtr(index); assert(pSlot->length()!=0); if (pSlot->getSymbol(0).getType() == PB_SYMBOL_note) { if (m_displayHand == PB_PART_both) return true; //eventually we need two slot queues one for each hand for (int i = 0; i < pSlot->length(); i++) { if (pSlot->getSymbol(i).getHand() == m_displayHand) return true; } } return false; } int CScroll::findWantedChord(int note, CColour colour, int wantedDelta) { if (colour == Cfg::playedBadColour()) // fixme should be an enum return m_wantedIndex; { while ( m_wantedIndex + 1 < m_scrollQueue->length()) { if ((m_wantedDelta + m_scrollQueue->indexPtr(m_wantedIndex)->getDeltaTime() * SPEED_ADJUST_FACTOR) >= -wantedDelta) { if (validPianistChord(m_wantedIndex) == true) break; } m_wantedDelta += m_scrollQueue->indexPtr(m_wantedIndex)->getDeltaTime() * SPEED_ADJUST_FACTOR; m_wantedIndex++; } } return m_wantedIndex; } void CScroll::setPlayedNoteColour(int note, CColour colour, int wantedDelta, int pianistTimming) { int index; if (m_wantedIndex >= m_scrollQueue->length()) return; index = findWantedChord(note, colour, wantedDelta); note -= m_transpose; m_scrollQueue->indexPtr(index)->setNoteColour(note, colour); if (pianistTimming != NOT_USED) { pianistTimming = deltaAdjust(pianistTimming) * DEFAULT_PPQN / CMidiFile::getPulsesPerQuarterNote(); m_scrollQueue->indexPtr(index)->setNoteTimming(note, pianistTimming); } compileSlot(m_scrollQueue->index(index)); } void CScroll::refresh() { int i; if (m_show == false) return; for ( i = 0; i < m_scrollQueue->length(); i++) compileSlot(m_scrollQueue->index(i)); } void CScroll::transpose(int transpose) { if (m_transpose == transpose) return; m_transpose = transpose; refresh(); } void CScroll::showScroll(bool show) { int i; GLuint nextListId = 0; m_show = show; if (show == true) { if (m_symbolID == 0) m_symbolID = glGenLists (1); // add in the missing GL display list for ( i = 0; i < m_scrollQueue->length(); i++) { //assert (m_scrollQueue->indexPtr(i)->m_displayListId == 0); nextListId = glGenLists (1); m_scrollQueue->indexPtr(i)->m_displayListId = m_symbolID; m_scrollQueue->indexPtr(i)->m_nextDisplayListId = nextListId; m_symbolID = nextListId; } // And now compile the slot (remember that each slot points to the next one) for ( i = 0; i < m_scrollQueue->length(); i++) { compileSlot(m_scrollQueue->index(i)); } } else { // Remove all the gl items for ( i = 0; i < m_scrollQueue->length(); i++) { if (m_scrollQueue->indexPtr(i)->m_displayListId != 0 && m_scrollQueue->indexPtr(i)->m_displayListId != nextListId) glDeleteLists(m_scrollQueue->index(i).m_displayListId, 1); m_scrollQueue->indexPtr(i)->m_displayListId = 0; nextListId = m_scrollQueue->indexPtr(i)->m_nextDisplayListId; m_scrollQueue->indexPtr(i)->m_nextDisplayListId = 0; if (nextListId != 0) glDeleteLists(nextListId, 1); } if (m_symbolID != 0) glDeleteLists(m_symbolID, 1); m_symbolID = 0; } } CScroll::CSlotDisplayList::CSlotDisplayList(const CSlot& slot, GLuint displayListId, GLuint nextDisplayListId) : CSlot(slot), m_displayListId(displayListId), m_nextDisplayListId(nextDisplayListId) { // It is all done in the initialisation list } void CScroll::reset() { int i; m_wantedIndex = 0; m_wantedDelta = 0; m_deltaHead = m_deltaTail = 0; m_notation->reset(); m_headSlot.clear(); for ( i = 0; i < m_scrollQueue->length(); i++) { if (m_scrollQueue->index(i).m_displayListId) glDeleteLists(m_scrollQueue->index(i).m_displayListId, 1); } if (m_symbolID != 0) glDeleteLists(m_symbolID, 1); m_symbolID = 0; m_scrollQueue->clear(); m_ppqnFactor = static_cast(DEFAULT_PPQN) / CMidiFile::getPulsesPerQuarterNote(); m_noteSpacingFactor = m_ppqnFactor * HORIZONTAL_SPACING_FACTOR; } pianobooster-src-0.6.4/src/Score.h0000644000175000017500000000723211304222711016072 0ustar louislouis/*********************************************************************************/ /*! @file Score.h @brief xxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef _SCORE_H_ #define _SCORE_H_ #include "Scroll.h" #include "Piano.h" #include "Settings.h" class CScore : public CDraw { public: CScore(CSettings* settings); ~CScore(); //! add a midi event to be analysed and displayed on the score void midiEventInsert(CMidiEvent event) { size_t i; for (i=0; i < arraySize(m_scroll); i++) { m_scroll[i]->midiEventInsert(event); } } //! first check if there is space to add a midi event int midiEventSpace() { size_t i; int minSpace; int space; minSpace = 1000; for (i=0; i< arraySize(m_scroll); i++) // this maybe slow { space = m_scroll[i]->midiEventSpace(); if (space < minSpace) minSpace = space; } return minSpace; } void transpose(int semitones) { size_t i; for (i=0; i< arraySize(m_scroll); i++) m_scroll[i]->transpose(semitones); } void reset() { size_t i; for (i=0; i< arraySize(m_scroll); i++) m_scroll[i]->reset(); } void drawScrollingSymbols(bool show = true) { size_t i; for (i=0; i< arraySize(m_scroll); i++) m_scroll[i]->drawScrollingSymbols(show); } void scrollDeltaTime(int ticks) { size_t i; for (i=0; i< arraySize(m_scroll); i++) m_scroll[i]->scrollDeltaTime(ticks); } void setRatingObject(CRating* rating) { m_rating = rating; } CPiano* getPianoObject() { return m_piano;} void setPlayedNoteColour(int note, CColour colour, int wantedDelta, int pianistTimming = NOT_USED) { m_scroll[m_activeScroll]->setPlayedNoteColour(note, colour, wantedDelta, pianistTimming); } void setActiveChannel(int channel) { int newActiveSroll; if (channel < 0 || channel >= static_cast(arraySize(m_scroll))) return; newActiveSroll = channel; if (m_activeScroll != newActiveSroll) { m_scroll[m_activeScroll]->showScroll(false); m_activeScroll = newActiveSroll; m_scroll[m_activeScroll]->showScroll(true); } } void refreshScroll() { m_scroll[m_activeScroll]->refresh(); } void setDisplayHand(whichPart_t hand) { CDraw::setDisplayHand(hand); refreshScroll(); } void drawScore(); void drawScroll(bool refresh); protected: CPiano* m_piano; private: CRating* m_rating; CScroll* m_scroll[MAX_MIDI_CHANNELS]; int m_activeScroll; GLuint m_scoreDisplayListId; GLuint m_stavesDisplayListId; }; #endif // _SCORE_H_ pianobooster-src-0.6.4/src/Score.cpp0000644000175000017500000000674711304222711016437 0ustar louislouis/*********************************************************************************/ /*! @file Score.cpp @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include #include "Cfg.h" #include "Draw.h" #include "Score.h" CScore::CScore(CSettings* settings) : CDraw(settings) { size_t i; m_piano = new CPiano(settings); m_rating = 0; m_activeScroll = -1; for (i=0; i< arraySize(m_scroll); i++) { m_scroll[i] = new CScroll(i, settings); m_scroll[i]->setChannel(i); } m_activeScroll = 0; m_scroll[m_activeScroll]->showScroll(true); m_scoreDisplayListId = 0;//glGenLists (1); m_stavesDisplayListId = glGenLists (1); } CScore::~CScore() { delete m_piano; size_t i; for (i=0; i< arraySize(m_scroll); i++) delete m_scroll[i]; if (m_scoreDisplayListId != 0) glDeleteLists(m_scoreDisplayListId, 1); m_scoreDisplayListId = 0; if (m_stavesDisplayListId != 0) glDeleteLists(m_stavesDisplayListId, 1); m_stavesDisplayListId = 0; } void CScore::drawScroll(bool refresh) { if (refresh == false) { float topY = CStavePos(PB_PART_right, MAX_STAVE_INDEX).getPosY(); float bottomY = CStavePos(PB_PART_left, MIN_STAVE_INDEX).getPosY(); drColour (Cfg::backgroundColour()); glRectf(Cfg::scrollStartX(), topY, Cfg::getAppWidth(), bottomY); } if (getCompileRedrawCount()) { if (m_stavesDisplayListId == 0) m_stavesDisplayListId = glGenLists (1); glNewList (m_stavesDisplayListId, GL_COMPILE_AND_EXECUTE); drawSymbol(CSymbol(PB_SYMBOL_playingZone, CStavePos(PB_PART_both, 0)), Cfg::playZoneX()); drawStaves(Cfg::scrollStartX(), Cfg::staveEndX()); glEndList (); // decrement the compile count until is reaches zero forceCompileRedraw(0); } else glCallList(m_stavesDisplayListId); drawScrollingSymbols(true); m_piano->drawPianoInput(); } void CScore::drawScore() { if (getCompileRedrawCount()) { if (m_scoreDisplayListId == 0) m_scoreDisplayListId = glGenLists (1); glNewList (m_scoreDisplayListId, GL_COMPILE_AND_EXECUTE); drColour (Cfg::staveColour()); drawSymbol(CSymbol(PB_SYMBOL_gClef, CStavePos(PB_PART_right, -1)), Cfg::clefX()); // The Treble Clef drawSymbol(CSymbol(PB_SYMBOL_fClef, CStavePos(PB_PART_left, 1)), Cfg::clefX()); drawKeySignature(CStavePos::getKeySignature()); drawStaves(Cfg::staveStartX(), Cfg::scrollStartX()); glEndList (); } else glCallList(m_scoreDisplayListId); } pianobooster-src-0.6.4/src/ReleaseNote.txt0000644000175000017500000000530311304222711017612 0ustar louislouis#define PB_VERSION "0.6.4" /* v0.6.4: (28 November 2009) - Added note names for beginners (to be used with a piano note name cut-out.) - Added assignable left and right midi channels. - Improved the MIDI timing accuracy. - Greatly reduced the memory footprint. - Reduced the CPU load. - Reduced the screen flicker (recommend setting screen refresh rate to 60Hz and for Intel Graphic chips updating the drivers). - Added keyboard shortcuts. These are - speed up/down, play from start, play/pause, next previous song, left right both hands. - Remembers the song settings in a configuration file called "pb.cfg". These are the midi channels, speed, left right or both hands. - Now works well Ubuntu 9.10 and Intel graphic chips. (Those with Ubuntu 9.04 and Intel should upgrade to 9.10 and this version) - Fixed various startup issues. - Now correctly displays repeated accidentals in one bar.. - Added the option to display courtesy accidentals. - Added a simple help page. - Added an installer for windows. - Make install now works for Linux. - Now works with small screens eg an EEE-701 (for Trev) v0.6.2: (01 April 2009) - added "" as instrument sound. - when setting a latency fix of >0 the instrument is automatically set to 'None' - turn all the sound off when exiting the program. - Added looping to continually play between to bars. - Added the option to change the follow mode stop point. - Automatically switches the follow mode stop point if you are playing well enough. - Added a logo to the source tree in "images/logo64x64.png" v0.6.1: (11 March 2009) - Added a play from bar (so you can start from playing any bar) - Added a latency fix for high latency sound generators (e.g. the windows GS software synth) (requires a piano keyboard _with_ it's own speakers/sound generator) - Added the ability to "mute your part when playing" along. - May have reduced the flickering especially on windows with a low spec machine - Added a piano volume slider (so you can adjust the volume of your piano with compared to the accompaniment) - Added an icon for the Piano Booster main window. - Fix a bug when swapping hands in the middle of a piece. - Fix a bug left or right now correctly dim the other stave. - Added start-up checks that Open GL is present. - Fix the pulse of sound when stopping the music - Added "timing markers" which show when the pianist pressed the note. - Changed the build so that it now works on the Mac (thanks to Christian) v0.5.1: (1 January 2009) - fixed the windows file open bug - changed the default wrong note sound to Harpsichord - changed the wrong note sound to use a separate midi channel. - on Windows removed the dos console v0.5.0: (28 November 2008) - first release */ pianobooster-src-0.6.4/src/Rating.h0000644000175000017500000000435511304222711016246 0ustar louislouis/*********************************************************************************/ /*! @file Rating.h @brief The generates a score on how well the pianist is doing. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __RATING_H__ #define __RATING_H__ #include "Util.h" #include "Cfg.h" class CRating { public: CRating() { reset(); } void reset(); void totalNotes(int count) { m_totalNotesCount += count;} void wrongNotes(int count) { m_wrongNoteCount += count;} void lateNotes(int count) { m_lateNoteCount += count;} int totalNoteCount() {return m_totalNotesCount;} int wrongNoteCount() {return m_wrongNoteCount;} int lateNoteCount() {return m_lateNoteCount;} double rating() { double percent = 100; if (m_totalNotesCount > 0) percent = ((m_totalNotesCount - m_lateNoteCount) * 100.0) /m_totalNotesCount; return percent; } void calculateAccuracy(); float getAccuracyValue(){ return m_currentAccuracy; } CColour getAccuracyColour() { return m_currentColour; } bool isAccuracyGood() { return m_goodAccuracyFlag; } private: int m_totalNotesCount; int m_previousNoteCount; int m_lateNoteCount; int m_previousLateNoteCount; int m_wrongNoteCount; float m_currentAccuracy; float m_factor; CColour m_currentColour; bool m_goodAccuracyFlag; }; #endif //__RATING_H__ pianobooster-src-0.6.4/src/Rating.cpp0000644000175000017500000000662411304222711016602 0ustar louislouis/*********************************************************************************/ /*! @file Rating.cpp @brief The generates a score on how well the pianist is doing. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include "Rating.h" #include "Conductor.h" void CRating::reset() { m_totalNotesCount = 0; m_wrongNoteCount = 0; m_lateNoteCount = 0; m_currentAccuracy = 0.5; m_previousNoteCount = -1; m_previousLateNoteCount = 0; m_factor = 2.0; m_goodAccuracyFlag = false; } void CRating::calculateAccuracy() { int direction = 0; if (m_previousNoteCount != m_totalNotesCount) { m_previousNoteCount = m_totalNotesCount; direction = 1; } if (m_previousLateNoteCount != m_lateNoteCount) { m_previousLateNoteCount = m_lateNoteCount; direction = -1; } if (direction != 0) { typedef struct { float value; float stepUp; float stepDown; CColour colour; } accuracyItem_t; const accuracyItem_t accuracyTable[] = { {1.00, 0.01, -0.08, CColour(0.5, 0.5, 1.0)}, // Only the colour is used on the top score {0.75, 0.01, -0.07, CColour(0.7, 0.3, 1.0)}, {0.50, 0.01, -0.05, CColour(1.0, 0.6, 0.4)}, {0.25, 0.01, -0.03, CColour(1.0, 0.3, 1.0)}, {0.0 , 0.015, -0.02, CColour(1.0, 0.4, 0.2)} }; size_t i; for (i = 0; i< arraySize(accuracyTable); i++) { if (m_currentAccuracy >= accuracyTable[i].value || i+1 == arraySize(accuracyTable)) { float stepAmount = (direction > 0) ? accuracyTable[i].stepUp : accuracyTable[i].stepDown; if (stepAmount < 0 && CConductor::getPlayMode() == PB_PLAY_MODE_playAlong) stepAmount = accuracyTable[i].stepUp + accuracyTable[i].stepDown; m_currentAccuracy += stepAmount *m_factor; break; } } if (m_currentAccuracy < 0) m_currentAccuracy = 0; if (m_currentAccuracy > 1) m_currentAccuracy = 1; m_goodAccuracyFlag = false; for (i = 0; i< arraySize(accuracyTable); i++) { if (m_currentAccuracy >= accuracyTable[i].value || i+1 == arraySize(accuracyTable)) { m_currentColour = accuracyTable[i].colour; if (m_currentAccuracy >= accuracyTable[ 1 ].value) // the second row in the table m_goodAccuracyFlag = true; break; } } } } pianobooster-src-0.6.4/src/Queue.h0000644000175000017500000000540511304222711016103 0ustar louislouis/*********************************************************************************/ /*! @file Queue.h @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __QUEUE_H__ #define __QUEUE_H__ #include // A Queue or circular buffer also also call a FIFO a First In First Out buffer // different threads could be running each end of the queue // template class CQueue { public: explicit CQueue(int size) { m_size = size; m_buffer = new TYPE[size]; clear(); } ~CQueue() { delete [] m_buffer; } void clear() { m_count = m_head = m_tail=0; } void push(TYPE c) { if (!space()) { assert(false); return; } m_buffer[m_head++] = c; if (m_head >= m_size) m_head = 0; // This must be last if a different thread is using pop() m_count++; } TYPE pop() { TYPE c; if (!length()) { assert(false); return m_buffer[m_tail]; } c = m_buffer[m_tail++]; if (m_tail >= m_size) m_tail = 0; // This must be last if a different thread is using push() m_count--; return c; } TYPE * indexPtr(int index) { int offset; if (index >= length()) { assert(false); return &m_buffer[m_head]; } offset = m_tail + index; if (offset >= m_size) offset -= m_size; return &m_buffer[offset]; } TYPE index(int index){ return *indexPtr(index);} int length() {return m_count;} int space() {return m_size - m_count;} private: TYPE * m_buffer; int m_size; int m_head; int m_tail; // this should be atomic operation when two different threads are at each end of the queue volatile int m_count; }; #endif //__QUEUE_H__ pianobooster-src-0.6.4/src/QtWindow.h0000644000175000017500000001143311304222711016571 0ustar louislouis/*! @file QtWindow.h @brief xxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ #ifndef __QT_WINDOW_H__ #define __QT_WINDOW_H__ #include #include "Song.h" #include "Score.h" #include "GuiMidiSetupDialog.h" #include "GuiKeyboardSetupDialog.h" #include "GuiSidePanel.h" #include "GuiTopBar.h" #include "GuiPreferencesDialog.h" #include "GuiSongDetailsDialog.h" #include "GuiLoopingPopup.h" #include "Settings.h" class CGLView; class QAction; class QMenu; class QSlider; class QPushButton; class QtWindow : public QMainWindow { Q_OBJECT public: QtWindow(); ~QtWindow(); void songEventUpdated(int eventBits) { if ((eventBits & EVENT_BITS_playingStopped) != 0) m_topBar->setPlayButtonState(false, true); } private slots: void open(); void help(); void website(); void about(); void keyboardShortcuts(); void showMidiSetup() { GuiMidiSetupDialog midiSetupDialog(this); midiSetupDialog.init(m_song, m_settings); midiSetupDialog.exec(); } void showPreferencesDialog() { GuiPreferencesDialog preferencesDialog(this); preferencesDialog.init(m_song, m_settings, m_glWidget); preferencesDialog.exec(); } void showSongDetailsDialog() { GuiSongDetailsDialog songDetailsDialog(this); songDetailsDialog.init(m_song, m_settings); songDetailsDialog.exec(); } void showKeyboardSetup() { GuiKeyboardSetupDialog keyboardSetup(this); keyboardSetup.init(m_song, m_settings); keyboardSetup.exec(); } void toggleSidePanel() { m_sidePanel->setVisible(!m_sidePanel->isVisible()); } void enableFollowTempo() { CTempo::enableFollowTempo(Cfg::experimentalTempo); } void disableFollowTempo() { CTempo::enableFollowTempo(false); } void on_rightHand() { m_sidePanel->setActiveHand(PB_PART_right); } void on_bothHands() { m_sidePanel->setActiveHand(PB_PART_both); } void on_leftHand() { m_sidePanel->setActiveHand(PB_PART_left); } void on_playFromStart() { if(m_song->playingMusic()) m_topBar->on_playButton_clicked(true); // Stop the music first if playing else m_topBar->on_playFromStartButton_clicked(true); } void on_playPause() { m_topBar->on_playButton_clicked(true); } void on_faster() { float speed = m_song->getSpeed() + 0.04; m_song->setSpeed(speed); speed = m_song->getSpeed(); m_topBar->setSpeed(static_cast(speed*100 + 0.5)); } void on_slower() { float speed = m_song->getSpeed() - 0.04; m_song->setSpeed(speed); speed = m_song->getSpeed(); m_topBar->setSpeed(static_cast(speed*100 + 0.5)); } void on_nextSong() { m_sidePanel->nextSong(+1); } void on_previousSong() { m_sidePanel->nextSong(-1); } protected: void closeEvent(QCloseEvent *event); void keyPressEvent ( QKeyEvent * event ); void keyReleaseEvent ( QKeyEvent * event ); private: void decodeCommandLine(); int decodeIntegerParam(QString arg, int defaultParam); void decodeMidiFileArg(QString arg); QString displayShortCut(QString code, QString description); void addShortcutAction(const QString & key, const char * method); void displayUsage(); void createActions(); void createMenus(); void readSettings(); void writeSettings(); CSettings* m_settings; GuiSidePanel *m_sidePanel; GuiTopBar *m_topBar; CGLView *m_glWidget; QAction *m_openAct; QAction *m_exitAct; QAction *m_aboutAct; QAction *m_shortcutAct; QAction *m_songPlayAct; QAction *m_setupMidiAct; QAction *m_setupKeyboardAct; QAction *m_toggleSidePanelAct; QAction *m_setupPreferencesAct; QAction *m_songDetailsAct; QMenu *m_fileMenu; QMenu *m_viewMenu; QMenu *m_songMenu; QMenu *m_setupMenu; QMenu *m_helpMenu; CSong* m_song; CScore* m_score; }; #endif // __QT_WINDOW_H__ pianobooster-src-0.6.4/src/QtWindow.cpp0000644000175000017500000004515011304222711017127 0ustar louislouis/*! @file QtWindow.cpp @brief xxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ #include "GlView.h" #include "QtWindow.h" #include "ReleaseNote.txt" #ifdef __linux__ #ifndef USE_REALTIME_PRIORITY #define USE_REALTIME_PRIORITY 0 #endif #endif #if USE_REALTIME_PRIORITY #include /* sets the process to "policy" policy at given priority */ static int set_realtime_priority(int policy, int prio) { struct sched_param schp; memset(&schp, 0, sizeof(schp)); schp.sched_priority = prio; if (sched_setscheduler(0, policy, &schp) != 0) { perror("sched_setscheduler"); return -1; } return 0; } #endif QtWindow::QtWindow() { QCoreApplication::setOrganizationName("PianoBooster"); QCoreApplication::setOrganizationDomain("pianobooster.sourceforge.net/"); QCoreApplication::setApplicationName("Piano Booster"); m_settings = new CSettings(this); setWindowIcon(QIcon(":/images/Logo32x32.png")); setWindowTitle(tr("Piano Booster")); decodeCommandLine(); if (Cfg::experimentalSwapInterval != -1) { QGLFormat fmt; fmt.setSwapInterval(Cfg::experimentalSwapInterval); int value = fmt.swapInterval(); ppLogInfo("Open GL Swap Interval %d", value); QGLFormat::setDefaultFormat(fmt); } #if USE_REALTIME_PRIORITY int rt_prio = sched_get_priority_max(SCHED_FIFO); set_realtime_priority(SCHED_FIFO, rt_prio); #endif m_glWidget = new CGLView(this, m_settings); m_song = m_glWidget->getSongObject(); m_score = m_glWidget->getScoreObject(); QHBoxLayout *mainLayout = new QHBoxLayout; QVBoxLayout *columnLayout = new QVBoxLayout; m_sidePanel = new GuiSidePanel(this, m_settings); m_topBar = new GuiTopBar(this, m_settings); m_settings->init(m_song, m_sidePanel, m_topBar); mainLayout->addWidget(m_sidePanel); columnLayout->addWidget(m_topBar); columnLayout->addWidget(m_glWidget); mainLayout->addLayout(columnLayout); m_song->init(m_score, m_settings); m_glWidget->init(); m_sidePanel->init(m_song, m_song->getTrackList(), m_topBar); m_topBar->init(m_song, m_song->getTrackList()); createActions(); createMenus(); readSettings(); QWidget *centralWin = new QWidget(); centralWin->setLayout(mainLayout); setCentralWidget(centralWin); m_glWidget->setFocus(Qt::ActiveWindowFocusReason); m_song->setPianoSoundPatches(m_settings->value("Keyboard/RightSound", Cfg::defaultRightPatch()).toInt() - 1, m_settings->value("Keyboard/WrongSound", Cfg::defaultWrongPatch()).toInt() - 1, true); QString midiInputName = m_settings->value("Midi/Input").toString(); if (midiInputName.startsWith("None")) CChord::setPianoRange(PC_KEY_LOWEST_NOTE, PC_KEY_HIGHEST_NOTE); else CChord::setPianoRange(m_settings->value("Keyboard/LowestNote", 0).toInt(), m_settings->value("Keyboard/HighestNote", 127).toInt()); m_song->setLatencyFix(m_settings->value("Midi/Latency", 0).toInt()); #ifdef _WIN32 m_glWidget->m_cfg_openGlOptimise = true; // don't default to true on windows #else m_glWidget->m_cfg_openGlOptimise = true; // changed to default to false on platforms #endif m_glWidget->m_cfg_openGlOptimise = m_settings->value("Display/OpenGlOptimise", m_glWidget->m_cfg_openGlOptimise ).toBool(); m_song->cfg_timingMarkersFlag = m_settings->value("Score/TimingMarkers", m_song->cfg_timingMarkersFlag ).toBool(); m_song->cfg_stopPointMode = static_cast (m_settings->value("Score/StopPointMode", m_song->cfg_stopPointMode ).toInt()); m_song->openMidiPort(CMidiDevice::MIDI_INPUT, midiInputName); m_song->openMidiPort(CMidiDevice::MIDI_OUTPUT,m_settings->value("midi/output").toString()); m_settings->loadSettings(); show(); } QtWindow::~QtWindow() { delete m_settings; } /////////////////////////////////////////////////////////////////////////////// //! @brief Displays the usage void QtWindow::displayUsage() { fprintf(stderr, "Usage: pianobooster [flags] [midifile]\n"); fprintf(stderr, " -d: Increase the debug level\n"); fprintf(stderr, " -q: Quick start\n"); fprintf(stderr, " -h: --help: Displays this help message\n"); fprintf(stderr, " -v: Displays version number and then exits\n"); } int QtWindow::decodeIntegerParam(QString arg, int defaultParam) { int n = arg.lastIndexOf('='); if (n == -1 || (n + 1) >= arg.size()) return defaultParam; bool ok; int value = arg.mid(n+1).toInt(&ok); if (ok) return value; return defaultParam; } void QtWindow::decodeMidiFileArg(QString arg) { QFileInfo fileInfo(arg); if (!fileInfo.exists() ) { QMessageBox::warning(0, "PianoBooster Midi File Error", "Cannot Open\"" + fileInfo.absoluteFilePath() + "\""); exit(1); } else if ( !(fileInfo.fileName().endsWith(".mid", Qt::CaseInsensitive ) || fileInfo.fileName().endsWith(".midi", Qt::CaseInsensitive ) || fileInfo.fileName().endsWith(".kar", Qt::CaseInsensitive )) ) { QMessageBox::warning(0, "PianoBooster Midi File Error", "Not a Midi File \"" + fileInfo.fileName() + "\""); exit(1); } else { bool vaildMidiFile = true; QFile file(fileInfo.absoluteFilePath()); if (!file.open(QIODevice::ReadOnly)) vaildMidiFile = false; else { QByteArray bytes = file.read(4); for (int i = 0; i < 4; i++) { if (bytes[i] !="MThd"[i] ) vaildMidiFile = false; } file.close(); } if (vaildMidiFile == true) m_settings->setValue("CurrentSong", fileInfo.absoluteFilePath()); else { QMessageBox::warning(0, "PianoBooster Midi File Error", "Not a valid MIDI file \"" + fileInfo.absoluteFilePath() + "\""); exit(1); } } } void QtWindow::decodeCommandLine() { bool hasMidiFile = false; QStringList argList = QCoreApplication::arguments(); QString arg; for (int i = 0; i < argList.size(); ++i) { arg = argList[i]; if (arg.startsWith("-")) { if (arg.startsWith("-d")) Cfg::logLevel++; else if (arg.startsWith("-q")) Cfg::quickStart = true; else if (arg.startsWith("-X1")) Cfg::experimentalTempo = true; else if (arg.startsWith("-Xswap")) Cfg::experimentalSwapInterval = decodeIntegerParam(arg, 100); else if (arg.startsWith("-h") || arg.startsWith("-?") ||arg.startsWith("--help")) { displayUsage(); exit(0); } else if (arg.startsWith("-v")) { fprintf(stderr, "pianobooster Version " PB_VERSION"\n"); exit(0); } else { fprintf(stderr, "ERROR: Unknown arguments \n"); displayUsage(); exit(0); } } else { if ( hasMidiFile == false && i > 0) { hasMidiFile = true; decodeMidiFileArg(arg); } } } } void QtWindow::addShortcutAction(const QString & key, const char * method) { QAction* act = new QAction(this); act->setShortcut(m_settings->value(key).toString()); connect(act, SIGNAL(triggered()), this, method); addAction(act); } void QtWindow::createActions() { m_openAct = new QAction(QIcon(":/images/open.png"), tr("&Open..."), this); m_openAct->setShortcut(tr("Ctrl+O")); m_openAct->setStatusTip(tr("Open an existing file")); connect(m_openAct, SIGNAL(triggered()), this, SLOT(open())); m_exitAct = new QAction(tr("E&xit"), this); m_exitAct->setShortcut(tr("Ctrl+Q")); m_exitAct->setStatusTip(tr("Exit the application")); connect(m_exitAct, SIGNAL(triggered()), this, SLOT(close())); m_aboutAct = new QAction(tr("&About"), this); m_aboutAct->setStatusTip(tr("Show the application's About box")); connect(m_aboutAct, SIGNAL(triggered()), this, SLOT(about())); m_shortcutAct = new QAction(tr("&PC Shortcut Keys"), this); m_shortcutAct->setStatusTip(tr("The PC Keyboard shortcut keys")); connect(m_shortcutAct, SIGNAL(triggered()), this, SLOT(keyboardShortcuts())); m_setupMidiAct = new QAction(tr("&Midi Setup ..."), this); m_setupMidiAct->setShortcut(tr("Ctrl+S")); m_setupMidiAct->setStatusTip(tr("Setup the Midi input an output")); connect(m_setupMidiAct, SIGNAL(triggered()), this, SLOT(showMidiSetup())); m_setupKeyboardAct = new QAction(tr("Piano &Keyboard Setting ..."), this); m_setupKeyboardAct->setShortcut(tr("Ctrl+K")); m_setupKeyboardAct->setStatusTip(tr("Change the piano keybaord settings")); connect(m_setupKeyboardAct, SIGNAL(triggered()), this, SLOT(showKeyboardSetup())); m_toggleSidePanelAct = new QAction(tr("&Show/Hide the Side Panel"), this); m_toggleSidePanelAct->setShortcut(tr("F11")); connect(m_toggleSidePanelAct, SIGNAL(triggered()), this, SLOT(toggleSidePanel())); m_setupPreferencesAct = new QAction(tr("&Preferences ..."), this); m_setupPreferencesAct->setShortcut(tr("Ctrl+P")); connect(m_setupPreferencesAct, SIGNAL(triggered()), this, SLOT(showPreferencesDialog())); m_songDetailsAct = new QAction(tr("&Song Details ..."), this); m_songDetailsAct->setShortcut(tr("Ctrl+S")); connect(m_songDetailsAct, SIGNAL(triggered()), this, SLOT(showSongDetailsDialog())); QAction* act = new QAction(this); act->setShortcut(tr("Shift+F1")); connect(act, SIGNAL(triggered()), this, SLOT(enableFollowTempo())); addAction(act); act = new QAction(this); act->setShortcut(tr("Alt+F1")); connect(act, SIGNAL(triggered()), this, SLOT(disableFollowTempo())); addAction(act); addShortcutAction("ShortCuts/RightHand", SLOT(on_rightHand())); addShortcutAction("ShortCuts/BothHands", SLOT(on_bothHands())); addShortcutAction("ShortCuts/LeftHand", SLOT(on_leftHand())); addShortcutAction("ShortCuts/PlayFromStart", SLOT(on_playFromStart())); addShortcutAction("ShortCuts/PlayPause", SLOT(on_playPause())); addShortcutAction("ShortCuts/Faster", SLOT(on_faster())); addShortcutAction("ShortCuts/Slower", SLOT(on_slower())); addShortcutAction("ShortCuts/NextSong", SLOT(on_nextSong())); addShortcutAction("ShortCuts/PreviousSong", SLOT(on_previousSong())); } void QtWindow::createMenus() { m_fileMenu = menuBar()->addMenu(tr("&File")); m_fileMenu->addAction(m_openAct); m_fileMenu->addSeparator(); m_fileMenu->addAction(m_exitAct); m_viewMenu = menuBar()->addMenu(tr("&View")); m_viewMenu->addAction(m_toggleSidePanelAct); m_songMenu = menuBar()->addMenu(tr("&Song")); m_songMenu->addAction(m_songDetailsAct); m_setupMenu = menuBar()->addMenu(tr("Set&up")); m_setupMenu->addAction(m_setupMidiAct); m_setupMenu->addAction(m_setupKeyboardAct); m_setupMenu->addAction(m_setupPreferencesAct); m_helpMenu = menuBar()->addMenu(tr("&Help")); QAction* act; act = new QAction(tr("&Help"), this); connect(act, SIGNAL(triggered()), this, SLOT(help())); m_helpMenu->addAction(act); act = new QAction(tr("&Website"), this); connect(act, SIGNAL(triggered()), this, SLOT(website())); m_helpMenu->addAction(act); m_helpMenu->addAction(m_shortcutAct); m_helpMenu->addAction(m_aboutAct); } void QtWindow::website() { QDesktopServices::openUrl(QUrl("http://pianobooster.sourceforge.net")); } void QtWindow::help() { QMessageBox msgBox(this); msgBox.setWindowTitle (tr("Piano Booster Help")); msgBox.setText( tr( "

Getting Started

" "

You need a MIDI Piano Keyboard and a MIDI interface for the PC. If you " "don't have a MIDI keyboard you can still try out PianoBooster using the PC keyboard, 'X' is " "middle C.

" "

To hear the music you will need a General Midi sound synthesizer. " "The \"Microsoft GS Wavetable software synthesizer\" that comes with Windows can be used " "but it introduces an unacceptable delay (latency).

" "

PianoBooster does not come with any MIDI Files and so you will need to get them from the net. " "See the PianoBooster FAQ " "for where to get MIDI files. " "PianoBooster works best with MIDI files that have separate left and right piano parts " "using MIDI channels 3 and 4." "

Setting Up

" "

First use the Setup/Midi Setup menu and in the dialog box select the MIDI input and MIDI " "output interfaces that match your hardware. " "Next use File/Open to open the MIDI file \".mid\" or a karaoke \".kar\" file. " "Now select whether you want to just listen to the music or " "play along on the piano keyboard by setting the skill level on the side panel. Finally when " "you are ready click the play icon (or press the space bar) to roll the music." "

Hints on Playing the Piano

" "

For hints on how to play the piano see: " "Piano Hints

" "

More Information

" "

For more help please visit the PianoBooster " "website, " "the PianoBooster FAQ " "and the user forum. " )); msgBox.setMinimumWidth(600); msgBox.exec(); } void QtWindow::about() { QMessageBox msgBox(this); msgBox.setWindowTitle (tr("About Piano Booster")); msgBox.setText( tr( "PainoBooster - Version " PB_VERSION "

" "Boost your Piano playing skills!

" "http://pianobooster.sourceforge.net

" "Copyright(c) L. J. Barman, 2008-2009; All rights reserved.

" "This program is made available " "under the terms of the GNU General Public License version 3 as published by " "the Free Software Foundation.

" "This program also contains RtMIDI: realtime MIDI i/o C++ classes
" "Copyright(c) 2003-2007 Gary P. Scavone" )); msgBox.setMinimumWidth(600); msgBox.exec(); } QString QtWindow::displayShortCut(QString key, QString description) { QString str = QString("" "%1" "%2" "").arg( description ).arg( m_settings->value(key).toString()); return str; } void QtWindow::keyboardShortcuts() { QMessageBox msgBox(this); msgBox.setWindowTitle (tr("PC Keyboard Short Cuts")); QString msg = tr( "

Keyboard short cuts

" "

The following PC keyboard short cuts have been defined.

" "
" ); msg += tr( "" "" "" "" ); msg += displayShortCut("ShortCuts/RightHand","Choose the right hand"); msg += displayShortCut("ShortCuts/BothHands","Choose both hands"); msg += displayShortCut("ShortCuts/LeftHand","Choose the left Hand"); msg += displayShortCut("ShortCuts/PlayFromStart","Play from start toggle"); msg += displayShortCut("ShortCuts/PlayPause","Play Pause Toggle"); msg += displayShortCut("ShortCuts/Faster","Increase the speed by 5%"); msg += displayShortCut("ShortCuts/Slower","Increase the speed by 5%"); msg += displayShortCut("ShortCuts/NextSong","Change to the Next Song"); msg += displayShortCut("ShortCuts/PreviousSong","Change to the Previous Song"); msg += tr( "" "
ActionKey
Fake Piano keysX is middle C

" ); msgBox.setText(msg); msgBox.setMinimumWidth(600); msgBox.exec(); } void QtWindow::open() { QString currentSong = m_settings->getCurrentSongLongFileName(); if (currentSong.isEmpty()) currentSong = QDir::homePath(); QString fileName = QFileDialog::getOpenFileName(this,tr("Open Midi File"), currentSong, tr("Midi Files (*.mid *.MID *.midi *.kar *.KAR)")); if (!fileName.isEmpty()) m_settings->openSongFile(fileName); } void QtWindow::readSettings() { QPoint pos = m_settings->value("Window/Pos", QPoint(25, 25)).toPoint(); QSize size = m_settings->value("Window/Size", QSize(800, 600)).toSize(); resize(size); move(pos); } void QtWindow::writeSettings() { m_settings->setValue("Window/Pos", pos()); m_settings->setValue("Window/Size", size()); m_settings->writeSettings(); } void QtWindow::closeEvent(QCloseEvent *event) { if (m_song->playingMusic()) { m_song->playMusic(false); } writeSettings(); } void QtWindow::keyPressEvent ( QKeyEvent * event ) { if (event->text().length() == 0) return; if (event->isAutoRepeat() == true) return; if (event->key() == Qt::Key_F1) return; int c = event->text().toAscii().at(0); m_song->pcKeyPress( c, true); } void QtWindow::keyReleaseEvent ( QKeyEvent * event ) { if (event->isAutoRepeat() == true) return; if (event->text().length() == 0) return; int c = event->text().toAscii().at(0); m_song->pcKeyPress( c, false); } pianobooster-src-0.6.4/src/QtMain.cpp0000644000175000017500000000251411304222711016541 0ustar louislouis/**************************************************************************** Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . ****************************************************************************/ #include #include #include "QtWindow.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); if (!QGLFormat::hasOpenGL()) { QMessageBox::information(0, "OpenGL support", "This system does not support OpenGL which is needed to run Piano Booster."); return -1; } QtWindow window; window.show(); return app.exec(); } pianobooster-src-0.6.4/src/Piano.h0000644000175000017500000000436311304222711016067 0ustar louislouis/*********************************************************************************/ /*! @file Piano.h @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __PIANO_H__ #define __PIANO_H__ #include "Draw.h" #include "Chord.h" #include "Settings.h" typedef struct { float posY; float posYOriginal; int type; // not used int pitch; } noteNameItem_t; class CPiano : protected CDraw { public: CPiano(CSettings* settings) : CDraw(settings) { } void drawPianoInput(); void addPianistNote(whichPart_t part, int note, bool good); bool removePianistNote(int note); int pianistAllNotesDown(); // Counts the number of notes the pianist has down int pianistBadNotesDown(); void clear(); private: void spaceNoteBunch(unsigned int bottomIndex, unsigned int topIndex); void drawPianoInputLines(CChord* chord, CColour colour, int lineLength); void drawPianoInputNoteNames(); void spaceNoteNames(); void addNoteNameItem(float posY, int pitch, int type); void removeNoteNameItem(int pitch); void noteNameListClear(); noteNameItem_t m_noteNameList[20]; unsigned int m_noteNameListLength; CChord m_goodChord; // The coloured note lines that appear on the score when the pianist plays CChord m_badChord; }; #endif //__PIANO_H__ pianobooster-src-0.6.4/src/Piano.cpp0000644000175000017500000001663711304222711016431 0ustar louislouis/*********************************************************************************/ /*! @file Piano.cpp @brief xxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include #include "Util.h" #include "Piano.h" #include "Cfg.h" #include "StavePosition.h" #include "Settings.h" #define PIANO_LINE_LENGTH_LONG 64 #define PIANO_LINE_LENGTH_SHORT 48 static const float minNameGap = 14.0; void CPiano::spaceNoteBunch(unsigned int bottomIndex, unsigned int topIndex) { unsigned int midPoint; int i; float lastY; float gap; int range; range = topIndex - bottomIndex; if (range <= 1) return; midPoint = range/2 + bottomIndex; if (range%2 == 0) // test for an even number of notes { gap = m_noteNameList[midPoint].posY - m_noteNameList[midPoint -1].posY; if (gap < minNameGap) { gap = (minNameGap - gap)/2; m_noteNameList[midPoint].posY += gap; // then move the middle two notes apart by the same amout m_noteNameList[midPoint-1].posY -= gap; } } lastY = m_noteNameList[midPoint].posY; // Search from the middle upwards for (i = midPoint + 1; i < static_cast(topIndex); i++) { gap = m_noteNameList[i].posY - lastY; // If the gap is too small make it bigger if (gap < minNameGap) m_noteNameList[i].posY = lastY + minNameGap; lastY = m_noteNameList[i].posY; } lastY = m_noteNameList[midPoint].posY; // now go the other way for (i = midPoint - 1; i >= 0; i--) { gap = lastY - m_noteNameList[i].posY; if (gap < minNameGap) m_noteNameList[i].posY = lastY - minNameGap; lastY = m_noteNameList[i].posY; } } void CPiano::drawPianoInputNoteNames() { unsigned int i; if (m_noteNameListLength >8) // too many notes so don't name any of them return; for (i = 0; i < m_noteNameListLength; i++) { drawNoteName(m_noteNameList[i].pitch, Cfg::playZoneX() - PIANO_LINE_LENGTH_SHORT - 14, m_noteNameList[i].posY, m_noteNameList[i].type); } } void CPiano::drawPianoInputLines(CChord* chord, CColour colour, int lineLength) { int i; drColour(colour); CStavePos stavePos; for ( i = 0; i < chord->length(); i++) { int pitch = chord->getNote(i).pitch(); stavePos.notePos(chord->getNote(i).part(), pitch); glLineWidth (3.0); if (stavePos.getAccidental() != 0) { glEnable (GL_LINE_STIPPLE); glLineStipple (1, 0x0f0f); /* dashed */ glLineWidth (3.0); } float posY; posY = stavePos.getPosYAccidental(); oneLine(Cfg::playZoneX() - lineLength, posY, Cfg::playZoneX(), posY); glDisable (GL_LINE_STIPPLE); } } void CPiano::spaceNoteNames() { unsigned int bottomIndex; unsigned int topIndex; bool foundBunch = false; m_noteNameList[0].posY = m_noteNameList[0].posYOriginal; if (m_noteNameListLength <= 1) return; bottomIndex = m_noteNameListLength; topIndex = 0; foundBunch = false; for (unsigned int i=1; i < m_noteNameListLength; i++) { m_noteNameList[i].posY = m_noteNameList[i].posYOriginal; if (m_noteNameList[i].posY - m_noteNameList[i-1].posY < minNameGap) { if (bottomIndex>i) bottomIndex = i; if (topIndex= arraySize(m_noteNameList)) return; noteNameItem.posY = noteNameItem.posYOriginal = posY; noteNameItem.type = type; noteNameItem.pitch = pitch; // Sort the entries low to high for (i = m_noteNameListLength - 1; i >= 0; i--) { if (m_noteNameList[i].pitch <= pitch) break; // move the previous entry up one position m_noteNameList[i+1] = m_noteNameList[i]; } if (m_noteNameList[i].pitch == pitch) return; // ignore duplicates m_noteNameList[i+1] = noteNameItem; m_noteNameListLength++; spaceNoteNames(); } void CPiano::addPianistNote(whichPart_t part, int note, bool good) { CStavePos stavePos; float posY; stavePos.notePos(part, note); if (stavePos.getStaveIndex() >= MAX_STAVE_INDEX || stavePos.getStaveIndex() <= MIN_STAVE_INDEX ) return; if (good == true) m_goodChord.addNote(part, note); else m_badChord.addNote(part, note); posY = stavePos.getPosYAccidental(); addNoteNameItem(posY, note, 0); } void CPiano::removeNoteNameItem(int pitch) { unsigned int i; bool foundMatch = false; for (i=0; i < m_noteNameListLength; i++) { if (foundMatch == true) m_noteNameList[i-1] = m_noteNameList[i]; // found a match so move every thing else up if (m_noteNameList[i].pitch == pitch) foundMatch = true; } if (m_noteNameListLength>0 && foundMatch) m_noteNameListLength--; spaceNoteNames(); } // returns true only if the note is in the bad note list bool CPiano::removePianistNote(int note) { removeNoteNameItem( note); m_goodChord.removeNote(note); return m_badChord.removeNote(note); } void CPiano::noteNameListClear() { m_noteNameListLength = 0; } // Counts the number of notes the pianist has down int CPiano::pianistAllNotesDown() { return m_goodChord.length() + m_badChord.length(); } int CPiano::pianistBadNotesDown() { return m_badChord.length(); } void CPiano::clear() { m_goodChord.clear(); m_badChord.clear(); noteNameListClear(); } void CPiano::drawPianoInput() { bool showNoteName = m_settings->showNoteNames(); int lineLength = (showNoteName) ? PIANO_LINE_LENGTH_SHORT : PIANO_LINE_LENGTH_LONG; if (m_goodChord.length() > 0) drawPianoInputLines(&m_goodChord, Cfg::pianoGoodColour(), lineLength); if (m_badChord.length() > 0) drawPianoInputLines(&m_badChord, Cfg::pianoBadColour(), lineLength); if (showNoteName) drawPianoInputNoteNames(); } pianobooster-src-0.6.4/src/Notation.h0000644000175000017500000001312211304222711016605 0ustar louislouis/*********************************************************************************/ /*! @file Notation.h @brief xxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __NOTATION_H__ #define __NOTATION_H__ #include #include "MidiFile.h" #include "Queue.h" #include "Symbol.h" #include "Chord.h" #include "Bar.h" #define MAX_SYMBOLS 20 // The maximum number of symbols that can be stored in one slot class CSlot { public: CSlot() { clear(); } void clear() { m_length = 0; m_deltaTime = 0; m_av8Left = 0; m_av8Right = 0; m_maxLeftEdge = 0; } CSymbol getSymbol(int index) {return m_symbols[index];} musicalSymbol_t getSymbolType(int index) {return m_symbols[index].getType();} int length() {return m_length;} void setDeltaTime(int delta) {m_deltaTime = delta;} void addDeltaTime(int delta) {m_deltaTime += delta;} int getDeltaTime() {return m_deltaTime;} int getLeftSideDeltaTime() {return m_deltaTime + m_maxLeftEdge;} void setAv8Left(int val) {m_av8Left = val;} int getAv8Left() {return m_av8Left;} // return false on error bool addSymbol(CSymbol symbol); void analyse(); void setSymbol(int delta, CSymbol symbol) { clear(); setDeltaTime(delta); addSymbol(symbol); } void transpose(int amount) { for (int i = 0; i < m_length; i++) { m_symbols[i].transpose(amount); } } void setNoteColour(int note, CColour colour ) { for (int i = 0; i < m_length; i++) { if (note == m_symbols[i].getNote() || note == 0) m_symbols[i].setColour(colour); } } void setNoteTimming(int note, int timing) { for (int i = 0; i < m_length; i++) { if (note == m_symbols[i].getNote() || note == 0) m_symbols[i].setPianistTiming(timing); } if (timing < m_maxLeftEdge) m_maxLeftEdge = timing; } void clearAllNoteTimmings() { for (int i = 0; i < m_length; i++) { m_symbols[i].setPianistTiming(NOT_USED); } m_maxLeftEdge = 0; } protected: private: int m_deltaTime; CSymbol m_symbols[MAX_SYMBOLS]; int m_length; int m_av8Left; int m_av8Right; int m_maxLeftEdge; // the furthest the note will appear on the left hand edge (used when removing the note) }; // remembers the state of a running accidental // Don't display the accidental twice in the same bar class CNoteState { public: CNoteState() { clear(); } void clear() { m_barChangeCounter = -1; m_accidentalState = PB_ACCIDENTAL_MODIFER_noChange; m_noteLength = 0; m_backLink = 0; } void setBarChange(int value){m_barChangeCounter = value;} int getBarChange(){return m_barChangeCounter;} void setAccidentalState(accidentalModifer_t value){m_accidentalState = value;} accidentalModifer_t getAccidentalState(){return m_accidentalState;} void setBackLink(CNoteState * link){m_backLink = link;} CNoteState * getBackLink(){return m_backLink;} private: int m_barChangeCounter; accidentalModifer_t m_accidentalState; int m_noteLength; // Used to determine the note length CNoteState* m_backLink; }; // Define a chord class CNotation { public: CNotation() { m_midiInputQueue = new CQueue(1000); m_slotQueue = new CQueue(200); reset(); m_displayChannel = 0; } ~CNotation() { delete m_midiInputQueue; delete m_slotQueue; } void reset(); void setChannel(int channel) {m_displayChannel = channel;} CSlot nextSlot(); void midiEventInsert(CMidiEvent event); int midiEventSpace() { return m_midiInputQueue->space();} static void setCourtesyAccidentals(bool setting){m_cfg_displayCourtesyAccidentals = setting;} static bool displayCourtesyAccidentals(){return m_cfg_displayCourtesyAccidentals; } private: CSlot nextBeatMarker(); int nextMergeSlot(); void findNoteSlots(); CSlot nextNoteSlot(); accidentalModifer_t detectSuppressedNatural(int note); CQueue* m_slotQueue; // Queue of symbol slots that have not been read yet CQueue* m_midiInputQueue; // A Queue of midi events CSlot m_currentSlot; int m_currentDeltaTime; int m_beatPerBarCounter; int m_earlyBarChangeCounter; int m_earlyBarChangeDelta; // Counts the ppqn in one bar CSlot m_mergeSlots[2]; int m_displayChannel; CFindChord m_findScrollerChord; CBar m_bar; CNoteState m_noteState[MAX_MIDI_NOTES]; static bool m_cfg_displayCourtesyAccidentals; }; #endif // __NOTATION_H__ pianobooster-src-0.6.4/src/Notation.cpp0000644000175000017500000002452111304222711017145 0ustar louislouis/*********************************************************************************/ /*! @file Notation.cpp @brief xxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include "Notation.h" #include "Cfg.h" #define OPTION_DEBUG_NOTATION 0 #if OPTION_DEBUG_NOTATION #define ppDEBUG_NOTATION(args) ppLogDebug args #else #define ppDEBUG_NOTATION(args) #endif #define MERGESLOT_NOTE_INDEX 0 #define MERGESLOT_BEATMARK_INDEX 1 bool CSlot::addSymbol(CSymbol symbol) { int i; if (m_length >= MAX_SYMBOLS) return false; // Sort the entries low to high for (i = m_length - 1; i >= 0; i--) { if (m_symbols[i].getNote() <= symbol.getNote()) { // don't add duplicates if (m_symbols[i].getNote() == symbol.getNote() && m_symbols[i].getType() == symbol.getType() && m_symbols[i].getHand() == symbol.getHand()) return true; break; } // move the previous entry up one possition m_symbols[i+1] = m_symbols[i]; } m_symbols[i+1] = symbol; m_length++; return true; } // find void CSlot::analyse() { int i; int rightIndex = 0; int leftIndex = 0; int rightTotal = 0; int leftTotal = 0; for (i = 0; i < m_length; i++) { if (m_symbols[i].getType() == PB_SYMBOL_note) { if (m_symbols[i].getHand() == PB_PART_right) rightTotal++; else if (m_symbols[i].getHand() == PB_PART_left) leftTotal++; } } for (i = 0; i < m_length; i++) { if (m_symbols[i].getType() == PB_SYMBOL_note) { if (m_symbols[i].getHand() == PB_PART_right) m_symbols[i].setIndex(rightIndex++, rightTotal); else if (m_symbols[i].getHand() == PB_PART_left) m_symbols[i].setIndex(leftIndex++, leftTotal ); } } } bool CNotation::m_cfg_displayCourtesyAccidentals = false; /////////////////////////////////////////////////////////////////////////// CSlot CNotation::nextBeatMarker() { const int cfg_barGap = CMidiFile::ppqnAdjust(30); CSlot slot; m_beatPerBarCounter++; if (m_beatPerBarCounter >= m_bar.getTimeSigTop()) m_beatPerBarCounter = -1; if (m_beatPerBarCounter == -1) // Sneak in a bar line slot.setSymbol( m_bar.getBeatLength() - cfg_barGap, CSymbol( PB_SYMBOL_barLine, PB_PART_both, 0 )); else if (m_beatPerBarCounter == 0) slot.setSymbol( cfg_barGap, CSymbol( PB_SYMBOL_barMarker, PB_PART_both, 0 )); else slot.setSymbol( m_bar.getBeatLength(), CSymbol( PB_SYMBOL_beatMarker, PB_PART_both, 0 )); return slot; } int CNotation::nextMergeSlot() { size_t i; CSlot nearestSlot; size_t nearestIndex; nearestSlot = m_mergeSlots[0]; nearestIndex = 0; for( i = 1; i < arraySize(m_mergeSlots); i++) { // find the slot with the lowest delta time if (m_mergeSlots[i].getDeltaTime() < nearestSlot.getDeltaTime()) { nearestSlot = m_mergeSlots[i]; nearestIndex = i; } } // Now subtract the delta time from all the others for( i = 0; i < arraySize(m_mergeSlots); i++) { if (i == nearestIndex) continue; m_mergeSlots[i].addDeltaTime( -nearestSlot.getDeltaTime() ); } return nearestIndex; } accidentalModifer_t CNotation::detectSuppressedNatural(int note) { if (note <= 0 || note +1 >= MAX_MIDI_NOTES) return PB_ACCIDENTAL_MODIFER_noChange; accidentalModifer_t modifer = PB_ACCIDENTAL_MODIFER_noChange; while (m_earlyBarChangeDelta >= m_bar.getBarLength()) { m_earlyBarChangeDelta -= m_bar.getBarLength(); m_earlyBarChangeCounter++; } CNoteState * pNoteState = &m_noteState[note]; CNoteState * pBackLink = pNoteState->getBackLink(); int direction = -CStavePos::getStaveAccidentalDirection(note); ppDEBUG_NOTATION(("Note %d %d %d", note, direction, pBackLink)); // check if this note has occurred in this bar before if (pNoteState->getBarChange() == m_earlyBarChangeCounter) { if (pBackLink) { ppDEBUG_NOTATION(("Force %d", note)); modifer = PB_ACCIDENTAL_MODIFER_force; } else if (direction != 0 && m_cfg_displayCourtesyAccidentals == false) { ppDEBUG_NOTATION(("Suppress %d %d", note, direction)); modifer = PB_ACCIDENTAL_MODIFER_suppress; } } if (direction != 0) { // we are display a accidental so force the note above (or below) to display m_noteState[note + direction].setBackLink(pNoteState); // point back to this note m_noteState[note + direction].setBarChange(m_earlyBarChangeCounter); ppDEBUG_NOTATION(("setting backlink %d %d", note + direction, direction)); } if (pBackLink) { pNoteState->setBackLink(0); pBackLink->setBarChange(-1); // this prevents further suppression on the original note } pNoteState->setBarChange(m_earlyBarChangeCounter); return modifer; } void CNotation::findNoteSlots() { CMidiEvent midi; CSlot slot; while (true) { // Check that some body has put in some events for us if (m_midiInputQueue->length() == 0) break; midi = m_midiInputQueue->pop(); m_currentDeltaTime += midi.deltaTime(); m_earlyBarChangeDelta += midi.deltaTime(); if (midi.type() == MIDI_PB_chordSeparator || midi.type() == MIDI_PB_EOF) { if (m_currentSlot.length() > 0) { // the cord separator arrives very late so we are behind the times m_currentSlot.analyse(); m_slotQueue->push(m_currentSlot); m_currentSlot.clear(); } if (midi.type() == MIDI_PB_EOF) { slot.setSymbol(0, CSymbol( PB_SYMBOL_theEnd, PB_PART_both, 0 )); m_slotQueue->push(slot); } break; } else if (midi.type() == MIDI_PB_timeSignature) m_bar.setTimeSig(midi.data1(), midi.data2()); else if (midi.type() == MIDI_PB_keySignature) CStavePos::setKeySignature(midi.data1(), midi.data2()); else if (midi.type() == MIDI_NOTE_ON) { whichPart_t hand = CNote::findHand( midi, m_displayChannel, PB_PART_both ); if (hand != PB_PART_none) { musicalSymbol_t symbolType; if (midi.channel() == MIDI_DRUM_CHANNEL) symbolType = PB_SYMBOL_drum; else symbolType = PB_SYMBOL_note; CSymbol symbol(symbolType, hand, midi.note()); symbol.setColour(Cfg::noteColour()); // check if this note has occurred in this bar before symbol.setAccidentalModifer(detectSuppressedNatural(midi.note())); if (m_currentSlot.addSymbol(symbol) == false) { ppLogWarn("[%d] Over the Max symbols limit", m_displayChannel + 1); } m_currentSlot.addDeltaTime(m_currentDeltaTime); m_currentDeltaTime = 0; if (hand == PB_PART_left) { if (midi.note() < MIDI_BOTTOM_C) m_currentSlot.setAv8Left(MIDI_OCTAVE); } } } } } CSlot CNotation::nextNoteSlot() { // only if the slot queue is empty should we try to find some more if (m_slotQueue->length() == 0) findNoteSlots(); if (m_slotQueue->length() > 0) return m_slotQueue->pop(); else return CSlot(); // this is an empty slot which means end of file } CSlot CNotation::nextSlot() { int mergeIdx; CSlot slot; if (m_mergeSlots[MERGESLOT_BEATMARK_INDEX].length() == 0) { // load up the two slots on start up m_mergeSlots[MERGESLOT_NOTE_INDEX] = nextNoteSlot(); m_mergeSlots[MERGESLOT_BEATMARK_INDEX] = nextBeatMarker(); // This inserts the beat marksers into the queue early (so they get drawn underneath) m_mergeSlots[MERGESLOT_BEATMARK_INDEX].addDeltaTime( -CMidiFile::getPulsesPerQuarterNote() * BEAT_MARKER_OFFSET / DEFAULT_PPQN); } if (m_mergeSlots[0].getSymbolType(0) == PB_SYMBOL_theEnd) return m_mergeSlots[0]; mergeIdx = nextMergeSlot(); slot = m_mergeSlots[mergeIdx]; if (mergeIdx == 0) m_mergeSlots[mergeIdx] = nextNoteSlot(); else m_mergeSlots[mergeIdx] = nextBeatMarker(); return slot; } void CNotation::midiEventInsert(CMidiEvent event) { if (m_findScrollerChord.findChord(event, m_displayChannel, PB_PART_both ) == true) { // the Score works differently we just send down a chord separator CMidiEvent separator; separator.chordSeparator(event); m_midiInputQueue->push(separator); } m_midiInputQueue->push(event); } void CNotation::reset() { const int cfg_earlBarLead = CMidiFile::ppqnAdjust(8); size_t i; m_currentDeltaTime = 0; m_midiInputQueue->clear(); m_slotQueue->clear(); for( i = 0; i < arraySize(m_mergeSlots); i++) m_mergeSlots[i].clear(); m_currentSlot.clear(); m_beatPerBarCounter=0; m_earlyBarChangeCounter = 0; m_earlyBarChangeDelta = cfg_earlBarLead; // We want to detect the bar change early m_bar.reset(); m_findScrollerChord.reset(); for( i = 0; i < MAX_MIDI_NOTES; i++) { m_noteState[i].clear(); } } pianobooster-src-0.6.4/src/MidiTrack.h0000644000175000017500000000752111304222711016667 0ustar louislouis/*********************************************************************************/ /*! @file MidiTrack.h @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __MIDITRACK_H__ #define __MIDITRACK_H__ #include #include #include #include "Queue.h" #include "MidiEvent.h" using namespace std; typedef enum { SMF_NO_ERROR, SMF_CANNOT_OPEN_FILE, SMF_CORRUPTED_MIDI_FILE, SMF_UNKNOW_EVENT, SMF_ERROR_TOO_MANY_TRACK, SMF_END_OF_FILE } midiErrors_t; typedef unsigned char byte_t; typedef unsigned short word_t; typedef unsigned long dword_t; // Reads data from a standard MIDI file class CMidiTrack { public: CMidiTrack(fstream& file, int no); ~CMidiTrack() { delete m_trackEventQueue; } int readDelaTime() { int deltaTime = m_deltaTime; m_deltaTime = 0; return deltaTime; } dword_t getTrackLength() {return m_trackLength;} void decodeTrack(); bool failed() { return (m_midiError != SMF_NO_ERROR) ? true : false;} midiErrors_t getMidiError() { return m_midiError;} int length() {return m_trackEventQueue->length();} CMidiEvent pop() {return m_trackEventQueue->pop();} QString getTrackName() {return m_trackName;} static void setLogLevel(int level){m_logLevel = level;} private: void errorFail(midiErrors_t error) { if (m_midiError != SMF_NO_ERROR || error != SMF_NO_ERROR) { m_midiError = error; if (m_midiError != SMF_NO_ERROR) ppLogError("Midi error %d", m_midiError); } } void midiFailReset() { m_midiError = SMF_NO_ERROR;} void ppDebugTrack(int level, const char *msg, ...); byte_t readByte(void) { int c; if (m_trackLengthCounter != 0 ) { c = m_file.get(); if (m_file.fail() == true) errorFail(SMF_END_OF_FILE); m_trackLengthCounter--; } else c = 0; return c; } word_t readWord(void) { word_t value; value = (readByte()&0x0ff) <<8 ; value |= readByte()&0x0ff; return value; } dword_t readDWord(void) { dword_t value; value = (readWord()&0x0ffff) <<16 ; value |= readWord()&0x0ffff; return value; } void decodeMidiEvent(); dword_t readVarLen(); string readTextEvent(); dword_t readDataEvent(int expectedLength); void readMetaEvent(byte_t type); void ignoreSysexEvent(byte_t data); void readTimeSignatureEvent(); void readKeySignatureEvent(); void decodeSystemMessage( byte_t status, byte_t data1 ); fstream& m_file; int m_trackNumber; streampos m_filePos; dword_t m_trackLength; dword_t m_trackLengthCounter; CQueue* m_trackEventQueue; int m_savedRunningStatus; int m_deltaTime; midiErrors_t m_midiError; QString m_trackName; static int m_logLevel; }; #endif // __MIDITRACK_H__ pianobooster-src-0.6.4/src/MidiTrack.cpp0000644000175000017500000003176111304222711017225 0ustar louislouis/*********************************************************************************/ /*! @file MidiTrack.cpp @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include #include "MidiTrack.h" #include "Util.h" #include "StavePosition.h" #define OPTION_DEBUG_TRACK 0 #if OPTION_DEBUG_TRACK #define ppDEBUG_TRACK(args) ppDebugTrack args #else #define ppDEBUG_TRACK(args) #endif int CMidiTrack::m_logLevel; CMidiTrack::CMidiTrack(fstream& file, int no) :m_file(file), m_trackNumber(no) { m_trackEventQueue = 0; m_savedRunningStatus = 0; m_trackLengthCounter = 0; m_deltaTime = 0; midiFailReset(); int i; m_trackName.clear(); m_trackLengthCounter = 8; for ( i=0; i < 4; i++) { if (m_file.get() !="MTrk"[i] ) { ppLogError("No valid Midi tracks"); errorFail(SMF_CORRUPTED_MIDI_FILE); return; } } m_trackLengthCounter = readDWord(); ppDEBUG_TRACK((9, "Track Length %d", m_trackLengthCounter)); m_filePos = m_file.tellg(); m_trackLength = m_trackLengthCounter + 8; // 4 bytes for the "MTrk" + 4 bytes for the track length m_trackEventQueue = new CQueue(m_trackLength/3); // The minimum bytes per event is 3 } void CMidiTrack::ppDebugTrack(int level, const char *msg, ...) { va_list ap; if (level =3) errorFail(SMF_END_OF_FILE); } } #if OPTION_DEBUG_TRACK if (value > 400) ppDEBUG_TRACK((2,"Large variable length data %d", value)); #endif return ( value ); } string CMidiTrack::readTextEvent() { dword_t length; string text; length = readVarLen(); if (length >= 100) { ppLogError("Text Event too large %d", length); errorFail(SMF_END_OF_FILE); return text; } while (length--) { if (failed() == true) return text; text += readByte(); } return text; } dword_t CMidiTrack::readDataEvent(int expectedLength) { int length; dword_t data; length = readByte(); if (length != expectedLength) { errorFail(SMF_CORRUPTED_MIDI_FILE); return 0; } data = 0; while (length--) { data <<= 8; data |= readByte(); } return data; } void CMidiTrack::ignoreSysexEvent(byte_t data) { word_t length; if (data >= 127) { // this could be a variable length word ppLogWarn("SysexEvent, is too long %d", data); errorFail(SMF_CORRUPTED_MIDI_FILE); return; } else length = data; while (length-- > 0 ) { if (failed() == true) return; readByte(); } } /* Time Signature */ void CMidiTrack::readTimeSignatureEvent() { byte_t len; byte_t timeSigNumerator; byte_t timeSigDenominator; CMidiEvent event; byte_t b3, b4; len = readVarLen(); if (len!=4) { errorFail(SMF_CORRUPTED_MIDI_FILE); return; } timeSigNumerator = readByte(); // The number on the top timeSigDenominator = readByte(); // the number on the bottom if (timeSigDenominator >= 5) { errorFail(SMF_CORRUPTED_MIDI_FILE); return; } if (timeSigNumerator > 20) { errorFail(SMF_CORRUPTED_MIDI_FILE); return; } len = (1<push(event); ppDEBUG_TRACK((4,"Key Signature %d/%d metronome %d quarter %d", timeSigNumerator, 1<(readByte()); // force sign conversion The key sig 0=middle C majorKey =readByte(); // Major or Minor if (keySig >= 7 || keySig <= -7 ) { errorFail(SMF_CORRUPTED_MIDI_FILE); return; } event.metaEvent(readDelaTime(), MIDI_PB_keySignature, keySig, majorKey); m_trackEventQueue->push(event); ppDEBUG_TRACK((4,"Key Signature %d maj/min %d", keySig, majorKey)); if (CStavePos::getKeySignature() == NOT_USED) CStavePos::setKeySignature(event.data1(), event.data2()); } void CMidiTrack::readMetaEvent(byte_t type) { string text; dword_t data; if (failed() == true) return; CMidiEvent event; switch (type) { case METASEQN: /* Sequence Number */ data = readDataEvent(2); ppDEBUG_TRACK((3,"Sequence Number %lu", data)); break; case METACOPYR: /* Copyright Notice */ text = readTextEvent(); ppDEBUG_TRACK((3,"Copyright %s", text.c_str())); break; case METATNAME: /* Seq/Track Name */ text = readTextEvent(); m_trackName = QString(text.c_str()); ppDEBUG_TRACK((3,"Seq/Track Name %s", text.c_str())); break; case METAINAME: /* Instrument */ text = readTextEvent(); ppDEBUG_TRACK((2,"Instrument %s", text.c_str())); break; case METAEOT: /* End of Track */ readVarLen(); ppDEBUG_TRACK((2,"End of Track")); break; case METATEMPO: /* Set Tempo */ { register byte b1,b2, b3; int tempo; b1 = readVarLen(); if (b1 != 3) { errorFail(SMF_CORRUPTED_MIDI_FILE); break; } b1 = readByte(); b2 = readByte(); b3 = readByte(); tempo = b1 << 16 | b2 << 8 | b3; // microseconds per quarter-note# event.metaEvent(readDelaTime(), MIDI_PB_tempo, tempo, 0); m_trackEventQueue->push(event); ppDEBUG_TRACK((2,"Set Tempo %d", tempo)); break; } case METATIMESIG: /* Time Signature */ readTimeSignatureEvent(); break; case METAKEYSIG: /* Key Signature */ readKeySignatureEvent(); break; case METATEXT: /* Text Event */ text = readTextEvent(); ppDEBUG_TRACK((2,"Text %s", text.c_str())); break; case METALYRIC: /* Lyric */ text = readTextEvent(); ppDEBUG_TRACK((2,"Lyric %s", text.c_str())); break; case METAMARKER: text = readTextEvent(); ppDEBUG_TRACK((2,"METAMARKER %s", text.c_str())); break; case METACUEPT: text = readTextEvent(); ppDEBUG_TRACK((2,"METACUEPT %s", text.c_str())); break; case METACHANPFX: /* Midi Channel Prefix */ data = readDataEvent(1); ppDEBUG_TRACK((2,"MIDI Channel Prefix %lu", data)); break; case METASMPTEOFF: /* SMPTE Offset */ text = readTextEvent(); ppDEBUG_TRACK((2,"SMPTE Offset %s", text.c_str())); break; case METASEQEVENT: /* sequencer Specific */ text = readTextEvent(); ppDEBUG_TRACK((2,"sequencer Specific %s", text.c_str())); break; case 0x21: /* MIDI Port */ data = readDataEvent(1); ppDEBUG_TRACK((2,"MIDI Port %lu", data)); break; case 0x09: // meta type text = readTextEvent(); ppDEBUG_TRACK((2,"midi meta event 0x%02x %s", type, text.c_str())); break; default: /* Unknown meta type */ text = readTextEvent(); ppLogWarn("unknown midi meta event 0x%02x %s", type, text.c_str()); //errorFail(SMF_UNKNOW_EVENT); break; } } void CMidiTrack::decodeSystemMessage( byte_t status, byte_t data1 ) { switch ( status ) { case MIDI_SYSEXEVENT: /* System exclusive Transmitted */ case 0xf7: /* System exclusive Not transmitted */ ppDEBUG_TRACK((2,"SYSEXEVENT xx")); /*ignore_sysex_event();*/ ignoreSysexEvent(data1); break; case METAEVENT: readMetaEvent(data1); break; default: ppDEBUG_TRACK((99,"UNKNOWN")); ignoreSysexEvent(data1); errorFail(SMF_UNKNOW_EVENT); break; } } void CMidiTrack::decodeMidiEvent() { CMidiEvent event; byte_t c; byte_t status, data1, data2; int channel; m_deltaTime += readVarLen(); c = readByte(); if ((c & 0x80) == 0 ) { status = m_savedRunningStatus; data1 = c; } else { status = c; m_savedRunningStatus = status; data1=readByte(); } channel = status & 0x0f; switch ( status & 0xf0 ) { case MIDI_NOTE_OFF: /* Note off */ data2 = readByte(); event.noteOffEvent(readDelaTime(), channel, data1, data2); m_trackEventQueue->push(event); ppDEBUG_TRACK((1,"Chan %d Note off", channel + 1)); break; case MIDI_NOTE_ON: /* Note on */ data2 = readByte(); if (data2 != 0 ) { event.noteOnEvent(readDelaTime(), channel, data1, data2); ppDEBUG_TRACK((1,"Chan %d note on %d",channel + 1, data1)); } else { event.noteOffEvent(readDelaTime(),channel, data1, 0); ppDEBUG_TRACK((1,"Chan %d note OFF %d",channel + 1, data1)); } m_trackEventQueue->push(event); break; case MIDI_NOTE_PRESSURE : /* Key pressure After touch (POLY_AFTERTOUCH) 3 bytes */ data2 = readByte(); event.notePressure(readDelaTime(), channel, data1, data2); m_trackEventQueue->push(event); ppDEBUG_TRACK((2,"Chan %d After touch", channel + 1)); break; case MIDI_PROGRAM_CHANGE : /* program change */ event.programChangeEvent(readDelaTime(), channel, data1); m_trackEventQueue->push(event); ppDEBUG_TRACK((2,"Chan %d Program change %d", channel + 1, data1 + 1)); break; case MIDI_CONTROL_CHANGE : /* Control Change */ data2 = readByte(); event.controlChangeEvent(readDelaTime(), channel, data1, data2); m_trackEventQueue->push(event); ppDEBUG_TRACK((2,"Chan %d Control Change %d %d", channel + 1, data1, data2)); break; case MIDI_CHANNEL_PRESSURE: /* Channel Pressure (AFTERTOUCH)*/ event.channelPressure(readDelaTime(), channel, data1); m_trackEventQueue->push(event); ppDEBUG_TRACK((2,"Chan %d Channel Pressure", channel + 1)); break; case MIDI_PITCH_BEND: /* Pitch bend */ data2 = readByte(); event.pitchBendEvent(readDelaTime(), channel, data1, data2); m_trackEventQueue->push(event); ppDEBUG_TRACK((2,"Chan %d Pitch bend",channel + 1)); break; case MIDI_SYSEXEVENT : /* System EX */ decodeSystemMessage(status, data1); m_savedRunningStatus=0; break; } } void CMidiTrack::decodeTrack() { CMidiEvent event; m_file.seekg(m_filePos, ios::beg); while (true) { if (m_trackLengthCounter== 0) break; if (m_trackEventQueue->space() <= 1) { ppLogError("Out of Space"); break; } decodeMidiEvent(); if (failed() == true) break; } m_filePos = m_file.tellg(); } pianobooster-src-0.6.4/src/MidiFile.h0000644000175000017500000000462211304222711016501 0ustar louislouis/*********************************************************************************/ /*! @file MidiFile.h @brief xxxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ ///////////////////////////////////////////////////////////////////////////// #ifndef __MIDIFILE_H__ #define __MIDIFILE_H__ #include #include #include "MidiEvent.h" #include "MidiTrack.h" #include "Merge.h" #define DEFAULT_PPQN 96 /* Standard value for pulse per quarter note */ using namespace std; #define MAX_TRACKS 40 // Reads data from a standard MIDI file class CMidiFile : public CMerge { public: CMidiFile() { size_t i; midiError(SMF_NO_ERROR); m_ppqn = DEFAULT_PPQN; setSize(MAX_TRACKS); for (i = 0; i < arraySize(m_tracks); i++) m_tracks[i] = 0; } void openMidiFile(string filename); int readWord(void); int readHeader(void); void rewind(); static int getPulsesPerQuarterNote(){return m_ppqn;} static int ppqnAdjust(float value) { return static_cast((value * static_cast(CMidiFile::getPulsesPerQuarterNote()))/DEFAULT_PPQN ); } QString getSongTitle() {return m_songTitle;} void setLogLevel(int level){CMidiTrack::setLogLevel(level);} midiErrors_t getMidiError() { return m_midiError;} private: bool checkMidiEventFromStream(int streamIdx); CMidiEvent fetchMidiEventFromStream(int streamIdx); void midiError(midiErrors_t error) {m_midiError = error;} fstream m_file; static int m_ppqn; midiErrors_t m_midiError; CMidiTrack* m_tracks[MAX_TRACKS]; QString m_songTitle; }; #endif // __MIDIFILE_H__ pianobooster-src-0.6.4/src/MidiFile.cpp0000644000175000017500000001021311304222711017025 0ustar louislouis/* oooOOO MidiFile.cpp OOOooo * Reads a Standard MIDI File Copyright (c) 1993, 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ #include #include #include #include "MidiFile.h" int CMidiFile::m_ppqn = DEFAULT_PPQN; /* Read 16 bits from the Standard MIDI file */ int CMidiFile::readWord(void) { int value; value = (m_file.get()&0x0ff) <<8 ; value |= m_file.get()&0x0ff; return value; } int CMidiFile::readHeader(void) { size_t i; int c; for ( i=0; i < 4; i++) { c = m_file.get(); if (c !="MThd"[i] ) { midiError(SMF_CORRUPTED_MIDI_FILE); return 0; } } /* length */ if ( readWord() != 0) { midiError(SMF_CORRUPTED_MIDI_FILE); return 0; } if ( readWord() != 6) { midiError(SMF_CORRUPTED_MIDI_FILE); return 0; } readWord(); /* midi file format */ i = readWord(); /* ntrks (see Standard MIDI File Spec) */ m_ppqn=readWord(); /* division */ ppLogInfo("Tracks %d PPQN %d", i, m_ppqn); if (i == 0) { midiError(SMF_CORRUPTED_MIDI_FILE); return 0; } return i; } void CMidiFile::openMidiFile(string filename) { if (m_file.is_open()) m_file.close(); m_file.clear(); // clear any errors m_file.open(filename.c_str(), ios_base::in | ios_base::binary); if (m_file.fail() == true) { QMessageBox::warning(0, "Midi File Error", "Cannot open \"" + QString(filename.c_str()) + "\""); midiError(SMF_CANNOT_OPEN_FILE); return; } rewind(); if (getMidiError() != SMF_NO_ERROR) QMessageBox::warning(0, "Midi File Error", "Midi file\"" + QString(filename.c_str()) + "\" is corrupted"); } void CMidiFile::rewind() { size_t ntrks; size_t trk; dword_t trackLength; streampos filePos; midiError(SMF_NO_ERROR); m_ppqn = DEFAULT_PPQN; m_file.seekg (0, ios::beg); ntrks = readHeader(); if (ntrks == 0) { midiError(SMF_CORRUPTED_MIDI_FILE); ppLogError("Zero tracks in SMF file"); return; } if (ntrks > arraySize(m_tracks)) { midiError(SMF_ERROR_TOO_MANY_TRACK); ppLogError("Too many tracks in SMF file"); return; } for (trk = 0; trk < arraySize(m_tracks); trk++) { if (m_tracks[trk]!= 0) { delete (m_tracks[trk]); m_tracks[trk] = 0; } } filePos = m_file.tellg(); for (trk = 0; trk < ntrks; trk++) { m_tracks[trk] = new CMidiTrack(m_file, trk); trackLength = m_tracks[trk]->getTrackLength(); m_tracks[trk]->decodeTrack(); if (m_tracks[trk]->failed()) { midiError(m_tracks[trk]->getMidiError()); break; } //now move onto the next track filePos += trackLength; m_file.seekg (filePos, ios::beg); } m_songTitle = m_tracks[0]->getTrackName(); initMergedEvents(); } bool CMidiFile::checkMidiEventFromStream(int streamIdx) { if (streamIdx < 0 || streamIdx >= MAX_TRACKS) { assert("streamIdx out of range"); return false; } if (m_tracks[streamIdx] != 0 && m_tracks[streamIdx]->length() > 0) return true; return false; } CMidiEvent CMidiFile::fetchMidiEventFromStream(int streamIdx) { return m_tracks[streamIdx]->pop(); } pianobooster-src-0.6.4/src/MidiEvent.h0000644000175000017500000001577611304222711016717 0ustar louislouis/*********************************************************************************/ /*! @file MidiEvent.h @brief xxxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __MIDI_EVENT_H__ #define __MIDI_EVENT_H__ #include "Util.h" #define MIDI_NOTE_OFF 0x80 /* MIDI voice messages */ #define MIDI_NOTE_ON 0x90 #define MIDI_NOTE_PRESSURE 0xA0 //POLY_AFTERTOUCH: 3 bytes #define MIDI_CONTROL_CHANGE 0xB0 #define MIDI_PROGRAM_CHANGE 0xC0 #define MIDI_CHANNEL_PRESSURE 0xD0 //AFTERTOUCH: 2 bytes #define MIDI_PITCH_BEND 0xE0 #define MIDI_SYSTEM_EVENT 0xF0 #define MIDI_SUSTAIN 0x40 #define MIDI_MAIN_VOLUME 0x07 #define MIDI_RESET_ALL_CONTROLLERS 121 #define MIDI_ALL_SOUND_OFF 120 #define MIDI_ALL_NOTES_OFF 123 //0x7B channel mode message // now define some of our own events #define MIDI_NONE 0x0ff0 #define MIDI_ERROR 0x0ff1 #define MIDI_PB_EOF 0x0ff2 #define MIDI_PB_chordSeparator 0x0ff3 // All the notes (note on) between these counts as one chord #define MIDI_PB_tempo 0x0ff4 #define MIDI_PB_timeSignature 0x0ff5 #define MIDI_PB_keySignature 0x0ff6 #define MIDI_PB_collateRawMidiData 0x0ff7 #define MIDI_PB_outputRawMidiData 0x0ff8 // Raw data is used for used for a SYSTEM_EVENT /*===================================*/ /* */ /* Standard MIDI file events */ /* */ /*===================================*/ #define MIDI_SYSEXEVENT 0xF0 #define METAEVENT 0xFF #define METASEQN 0 #define METATEXT 1 #define METACOPYR 2 #define METATNAME 3 #define METAINAME 4 #define METALYRIC 5 #define METAMARKER 6 #define METACUEPT 7 #define METACHANPFX 0x20 #define METAEOT 0x2F #define METATEMPO 0x51 #define METASMPTEOFF 0x54 #define METATIMESIG 0x58 #define METAKEYSIG 0x59 #define METASEQEVENT 0x7F #define MIDI_DRUM_CHANNEL (10-1) #define MAX_MIDI_CHANNELS 16 // There are always at most 16 midi channels #define GM_PIANO_PATCH 0 // The default grand piano sound /*! * @brief xxxxx. */ class CMidiEvent { public: CMidiEvent() { clear(); } void clear() { m_type = MIDI_NONE; m_deltaTime = 0; m_channel = 0; m_note = 0; m_velocity = 0; } int deltaTime(){return m_deltaTime;} void addDeltaTime(int delta){m_deltaTime +=delta;} void setDeltaTime(int delta){m_deltaTime = delta;} //////////////////////////////////////////////////////////////////////////////// //@brief returns the midi note number int note() const {return m_note;} int programme() const {return m_note;} int channel() const {return m_channel;} void setChannel(int chan){m_channel = chan;} int velocity() const {return m_velocity;} int type() const {return m_type;} void setType(int type){m_type = type;} void transpose(int amount) {m_note += amount;} int data1() const {return m_note;} // Meta data is stored here int data2() const {return m_velocity;} void setDatat2(int value) {m_velocity = value;} void noteOffEvent( int deltaTime, int channel, int note, int velocity) { m_type = MIDI_NOTE_OFF; m_deltaTime = deltaTime; m_channel = channel; m_note = note; m_velocity = velocity; } void noteOnEvent( int deltaTime, int channel, int note, int velocity) { m_type = MIDI_NOTE_ON; m_deltaTime = deltaTime; m_channel = channel; m_note = note; m_velocity = velocity; } void notePressure( int deltaTime, int channel, int data1, int data2) { m_type = MIDI_NOTE_PRESSURE; //POLY_AFTERTOUCH: 3 bytes m_deltaTime = deltaTime; m_channel = channel; m_note = data1; m_velocity = data2; } void programChangeEvent( int deltaTime, int channel, int program) { m_type = MIDI_PROGRAM_CHANGE; m_deltaTime = deltaTime; m_channel = channel; m_note = program; m_velocity = 0; } void controlChangeEvent( int deltaTime, int channel, int data1, int data2) { m_type = MIDI_CONTROL_CHANGE; m_deltaTime = deltaTime; m_channel = channel; m_note = data1; m_velocity = data2; } void channelPressure( int deltaTime, int channel, int data1) { m_type = MIDI_CHANNEL_PRESSURE; //AFTERTOUCH: 2 bytes m_deltaTime = deltaTime; m_channel = channel; m_note = data1; m_velocity = 0; } void pitchBendEvent( int deltaTime, int channel, int data1, int data2) { m_type = MIDI_PITCH_BEND; m_deltaTime = deltaTime; m_channel = channel; m_note = data1; m_velocity = data2; } void chordSeparator(CMidiEvent &event) { m_type = MIDI_PB_chordSeparator; m_note = 0; m_channel = event.channel(); m_deltaTime = 0; m_velocity = 0; } void metaEvent( int deltaTime, int type, int data1, int data2) { m_type = type; m_deltaTime = deltaTime; m_channel = 0; m_note = data1; m_velocity = data2; } // Raw data is used for used for a SYSTEM_EVENT void collateRawByte( int deltaTime, int nextByte) { m_type = MIDI_PB_collateRawMidiData; m_deltaTime = deltaTime; m_note = nextByte; m_velocity = 0; } // Raw data is used for used for a SYSTEM_EVENT void outputCollatedRawBytes(int deltaTime) { m_type = MIDI_PB_outputRawMidiData; m_deltaTime = deltaTime; m_note = 0; m_velocity = 0; } void printDetails() { ppTiming("chan %2d type %2X note %3d", channel(), type(), note() ); } private: int m_type; int m_deltaTime; int m_channel; int m_note; int m_velocity; }; #endif //__MIDI_EVENT_H__ pianobooster-src-0.6.4/src/MidiDeviceRt.h0000644000175000017500000000467211304222711017334 0ustar louislouis/*********************************************************************************/ /*! @file MidiDeviceRt.h @brief xxxxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __MIDI_DEVICE_RT_H__ #define __MIDI_DEVICE_RT_H__ #include "MidiDeviceBase.h" #include "rtmidi/RtMidi.h" class CMidiDeviceRt : public CMidiDeviceBase { virtual void init(); //! add a midi event to be played immediately virtual void playMidiEvent(const CMidiEvent & event); virtual int checkMidiInput(); virtual CMidiEvent readMidiInput(); virtual QStringList getMidiPortList(midiType_t type); virtual bool openMidiPort(midiType_t type, QString portName); virtual void closeMidiPort(midiType_t type, int index); // based on the fluid synth settings virtual int midiSettingsSetStr(QString name, QString str); virtual int midiSettingsSetNum(QString name, double val); virtual int midiSettingsSetInt(QString name, int val); virtual QString midiSettingsGetStr(QString name); virtual double midiSettingsGetNum(QString name); virtual int midiSettingsGetInt(QString name); public: CMidiDeviceRt(); ~CMidiDeviceRt(); private: RtMidiOut *m_midiout; RtMidiIn *m_midiin; // 0 for input, 1 for output int m_midiPorts[2]; // select which MIDI output port to open std::vector m_inputMessage; unsigned char m_savedRawBytes[40]; // Raw data is used for used for a SYSTEM_EVENT unsigned int m_rawDataIndex; }; #endif //__MIDI_DEVICE_RT_H__ pianobooster-src-0.6.4/src/MidiDeviceRt.cpp0000644000175000017500000001727311304222711017670 0ustar louislouis/*********************************************************************************/ /*! @file MidiDeviceRt.cpp @brief MidiDeviceRt talks to the MidiRt Real Time Version. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include "MidiDeviceRt.h" CMidiDeviceRt::CMidiDeviceRt() { m_midiout = new RtMidiOut(); m_midiin = new RtMidiIn(); m_midiPorts[0] = -1; m_midiPorts[1] = -1; m_rawDataIndex = 0; } CMidiDeviceRt::~CMidiDeviceRt() { delete m_midiout; delete m_midiin; } void CMidiDeviceRt::init() { } QStringList CMidiDeviceRt::getMidiPortList(midiType_t type) { unsigned int nPorts; QString name; RtMidi* midiDevice; QStringList portNameList; if (type == MIDI_INPUT) midiDevice = m_midiin; else midiDevice = m_midiout; nPorts = midiDevice->getPortCount(); for(unsigned int i=0; i< nPorts; i++) { name = midiDevice->getPortName(i).c_str(); if (name.startsWith("RtMidi")) continue; portNameList << name; } return portNameList; } bool CMidiDeviceRt::openMidiPort(midiType_t type, QString portName) { unsigned int nPorts; QString name; RtMidi* midiDevice; if (portName.length() == 0) return false; int dev; if (type == MIDI_INPUT) { midiDevice = m_midiin; dev = 0; } else { midiDevice = m_midiout; dev = 1; } nPorts = midiDevice->getPortCount(); for(unsigned int i=0; i< nPorts; i++) { name = midiDevice->getPortName(i).c_str(); if (name == portName) // Test for a match { if (m_midiPorts[dev] >= 0) midiDevice->closePort(); m_midiPorts[dev] = i; m_rawDataIndex = 0; midiDevice->openPort( i ); return true; } } return false; } void CMidiDeviceRt::closeMidiPort(midiType_t type, int index) { if (type == MIDI_INPUT) m_midiin->closePort(); else m_midiout->closePort(); } //! add a midi event to be played immediately void CMidiDeviceRt::playMidiEvent(const CMidiEvent & event) { if (m_midiPorts[1] < 0) return; unsigned int channel; std::vector message; channel = event.channel() & 0x0f; switch(event.type()) { case MIDI_NOTE_OFF: // NOTE_OFF message.push_back( channel | MIDI_NOTE_OFF ); message.push_back( event.note()); message.push_back( event.velocity()); break; case MIDI_NOTE_ON: // NOTE_ON message.push_back( channel | MIDI_NOTE_ON ); message.push_back( event.note()); message.push_back( event.velocity()); break; case MIDI_NOTE_PRESSURE: //POLY_AFTERTOUCH: 3 bytes message.push_back( channel | MIDI_NOTE_PRESSURE); message.push_back( event.data1()); message.push_back( event.data2()); break; case MIDI_CONTROL_CHANGE: //CONTROL_CHANGE: message.push_back( channel | MIDI_CONTROL_CHANGE); message.push_back( event.data1()); message.push_back( event.data2()); break; case MIDI_PROGRAM_CHANGE: //PROGRAM_CHANGE: message.push_back( channel | MIDI_PROGRAM_CHANGE); message.push_back( event.programme()); break; case MIDI_CHANNEL_PRESSURE: //AFTERTOUCH: 2 bytes only message.push_back( channel | MIDI_CHANNEL_PRESSURE); message.push_back( event.data1()); break; case MIDI_PITCH_BEND: //PITCH_BEND: message.push_back( channel | MIDI_PITCH_BEND); message.push_back( event.data1()); message.push_back( event.data2()); break; case MIDI_PB_collateRawMidiData: //used for a SYSTEM_EVENT if (m_rawDataIndex < arraySize(m_savedRawBytes)) m_savedRawBytes[m_rawDataIndex++] = event.data1(); return; // Don't output any thing yet so just return case MIDI_PB_outputRawMidiData: //used for a SYSTEM_EVENT for (size_t i = 0; i < m_rawDataIndex; i++) message.push_back( m_savedRawBytes[i]); m_rawDataIndex = 0; break; } m_midiout->sendMessage( &message ); //event.printDetails(); // useful for debugging } // Return the number of events waiting to be read from the midi device int CMidiDeviceRt::checkMidiInput() { if (m_midiPorts[0] < 0) return 0; m_midiin->getMessage( &m_inputMessage ); return m_inputMessage.size(); } // reads the real midi event CMidiEvent CMidiDeviceRt::readMidiInput() { CMidiEvent midiEvent; unsigned int channel; channel = m_inputMessage[0] & 0x0f; switch (m_inputMessage[0] & 0xf0 ) { case MIDI_NOTE_ON: if (m_inputMessage[2] != 0 ) midiEvent.noteOnEvent(0, channel, m_inputMessage[1], m_inputMessage[2]); else midiEvent.noteOffEvent(0,channel, m_inputMessage[1], m_inputMessage[2]); break; case MIDI_NOTE_OFF: midiEvent.noteOffEvent(0, channel, m_inputMessage[1], m_inputMessage[2]); break; case MIDI_NOTE_PRESSURE: //MIDI_CMD_NOTE_PRESSURE: //POLY_AFTERTOUCH: // fixme fill in the blanks //midi_input_bytes[midi_input_length++] = channel | MIDI_CMD_NOTE_PRESSURE; //midi_input_bytes[midi_input_length++] = ev->data.note.note; //midi_input_bytes[midi_input_length++] = ev->data.note.velocity; break; case MIDI_CONTROL_CHANGE: //CONTROL_CHANGE: midiEvent.controlChangeEvent(0, channel, m_inputMessage[1], m_inputMessage[2]); break; case MIDI_PROGRAM_CHANGE: //PROGRAM_CHANGE: //midiEvent.programChangeEvent(0, ev->data.control.channel, ev->data.control.value); break; case MIDI_CHANNEL_PRESSURE: //AFTERTOUCH: // fixme fill in the blanks //midi_input_bytes[midi_input_length++] = ev->data.control.channel | MIDI_CMD_CHANNEL_PRESSURE; //midi_input_bytes[midi_input_length++] = ev->data.control.value; break; case MIDI_PITCH_BEND: //PITCH_BEND: // fixme fill in the blanks //midi_input_bytes[midi_input_length++] = ev->data.control.channel | MIDI_CMD_CHANNEL_PRESSURE; //midi_input_bytes[midi_input_length++] = ev->data.control.value; break; } m_inputMessage.clear(); return midiEvent; } int CMidiDeviceRt::midiSettingsSetStr(QString name, QString str) { return 0; } int CMidiDeviceRt::midiSettingsSetNum(QString name, double val) { return 0; } int CMidiDeviceRt::midiSettingsSetInt(QString name, int val) { return 0; } QString CMidiDeviceRt::midiSettingsGetStr(QString name) { return QString(); } double CMidiDeviceRt::midiSettingsGetNum(QString name) { return 0.0; } int CMidiDeviceRt::midiSettingsGetInt(QString namel) { return 0; } pianobooster-src-0.6.4/src/MidiDeviceFluidSynth.h0000644000175000017500000000465311304222711021037 0ustar louislouis/*********************************************************************************/ /*! @file MidiDeviceFluidSynth.h @brief xxxxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __MIDI_DEVICE_FLUIDSYNTH_H__ #define __MIDI_DEVICE_FLUIDSYNTH_H__ #include "MidiDeviceBase.h" #include class CMidiDeviceFluidSynth : public CMidiDeviceBase { virtual void init(); //! add a midi event to be played immediately virtual void playMidiEvent(const CMidiEvent & event); virtual int checkMidiInput(); virtual CMidiEvent readMidiInput(); virtual QStringList getMidiPortList(midiType_t type); virtual bool openMidiPort(midiType_t type, QString portName); virtual void closeMidiPort(midiType_t type, int index); // based on the fluid synth settings virtual int midiSettingsSetStr(QString name, QString str); virtual int midiSettingsSetNum(QString name, double val); virtual int midiSettingsSetInt(QString name, int val); virtual QString midiSettingsGetStr(QString name); virtual double midiSettingsGetNum(QString name); virtual int midiSettingsGetInt(QString name); public: CMidiDeviceFluidSynth(); ~CMidiDeviceFluidSynth(); private: unsigned char m_savedRawBytes[40]; // Raw data is used for used for a SYSTEM_EVENT unsigned int m_rawDataIndex; fluid_settings_t* m_fluidSettings; fluid_synth_t* m_synth; fluid_audio_driver_t* m_audioDriver; int m_soundFontId; }; #endif //__MIDI_DEVICE_FLUIDSYNTH_H__ pianobooster-src-0.6.4/src/MidiDeviceFluidSynth.cpp0000644000175000017500000001730611304222711021371 0ustar louislouis/*********************************************************************************/ /*! @file MidiDeviceFluidSynth.cpp @brief MidiDeviceFluidSynth talks to the MidiRt Real Time Version. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include "MidiDeviceFluidSynth.h" #include #include #include CMidiDeviceFluidSynth::CMidiDeviceFluidSynth() { m_synth = 0; m_fluidSettings = 0; m_audioDriver = 0; m_rawDataIndex = 0; } CMidiDeviceFluidSynth::~CMidiDeviceFluidSynth() { closeMidiPort(MIDI_OUTPUT, -1); } void CMidiDeviceFluidSynth::init() { } QStringList CMidiDeviceFluidSynth::getMidiPortList(midiType_t type) { if (type != MIDI_OUTPUT) // Only has an output return QStringList(); //debugSettings(("getSongList %s + %d", qPrintable(getCurrentBookName()), qPrintable(m_bookPath))); QDir dirSoundFont("soundfont"); dirSoundFont.setFilter(QDir::Files); QStringList fileNames = dirSoundFont.entryList(); QStringList portNames; for (int i = 0; i < fileNames.size(); i++) { if ( fileNames.at(i).endsWith(".sf2", Qt::CaseInsensitive ) ) { portNames += fileNames.at(i); } } return portNames; } bool CMidiDeviceFluidSynth::openMidiPort(midiType_t type, QString portName) { closeMidiPort(MIDI_OUTPUT, -1); if (portName.length() == 0) return false; if (type == MIDI_INPUT) return false; /* Create the settings. */ m_fluidSettings = new_fluid_settings(); /* Change the settings if necessary*/ fluid_settings_setnum(m_fluidSettings, (char *)"synth.sample-rate", 22050.0); fluid_settings_setint(m_fluidSettings, "audio.periods", 5); fluid_settings_setint(m_fluidSettings, "audio.period-size", 128); fluid_settings_setstr(m_fluidSettings, "audio.alsa.device", "plughw:0"); /* Create the synthesizer. */ m_synth = new_fluid_synth(m_fluidSettings); fluid_synth_set_reverb_on(m_synth, 0); fluid_synth_set_chorus_on(m_synth, 0); /* Create the audio driver. The synthesizer starts playing as soon as the driver is created. */ m_audioDriver = new_fluid_audio_driver(m_fluidSettings, m_synth); /* Load a SoundFont*/ m_soundFontId = fluid_synth_sfload(m_synth, "FluidR3_GM.sf2", 0); //m_soundFontId = fluid_synth_sfload(m_synth, "VintageDreamsWaves-v2.sf2", 0); /* Select bank 0 and preset 0 in the SoundFont we just loaded on channel 0 */ //fluid_synth_program_select(m_synth, 0, m_soundFontId, 0, 0); for (int channel = 0; channel < MAX_MIDI_CHANNELS ; channel++) { //fluid_synth_program_select(m_synth, channel, m_soundFontId, 0, GM_PIANO_PATCH); fluid_synth_program_change(m_synth, channel, GM_PIANO_PATCH); } fluid_synth_set_gain(m_synth, 0.4); return true; } void CMidiDeviceFluidSynth::closeMidiPort(midiType_t type, int index) { if (type != MIDI_OUTPUT) return; if (m_fluidSettings == 0) return; /* Clean up */ delete_fluid_audio_driver(m_audioDriver); delete_fluid_synth(m_synth); delete_fluid_settings(m_fluidSettings); m_fluidSettings = 0; m_rawDataIndex = 0; } //! add a midi event to be played immediately void CMidiDeviceFluidSynth::playMidiEvent(const CMidiEvent & event) { if (m_synth == 0) return; unsigned int channel; channel = event.channel() & 0x0f; switch(event.type()) { case MIDI_NOTE_OFF: // NOTE_OFF fluid_synth_noteoff(m_synth, channel, event.note()); break; case MIDI_NOTE_ON: // NOTE_ON fluid_synth_noteon(m_synth, channel, event.note(), event.velocity()); break; case MIDI_NOTE_PRESSURE: //POLY_AFTERTOUCH: 3 bytes //message.push_back( channel | MIDI_NOTE_PRESSURE); //message.push_back( event.data1()); //message.push_back( event.data2()); break; case MIDI_CONTROL_CHANGE: //CONTROL_CHANGE: fluid_synth_cc(m_synth, channel, event.data1(), event.data2()); //ppLogTrace("MIDI_CONTROL_CHANGE %d %d %d", channel, event.data1(), event.data2()); break; case MIDI_PROGRAM_CHANGE: //PROGRAM_CHANGE: fluid_synth_program_change(m_synth, channel, event.programme()); break; case MIDI_CHANNEL_PRESSURE: //AFTERTOUCH: 2 bytes only //message.push_back( channel | MIDI_CHANNEL_PRESSURE); //message.push_back( event.data1()); // FIXME missing break; case MIDI_PITCH_BEND: //PITCH_BEND: // a 14 bit number LSB first 0x4000 is the off posintions fluid_synth_pitch_bend(m_synth, channel, (event.data2() << 7) | event.data1()); break; case MIDI_PB_collateRawMidiData: //used for a SYSTEM_EVENT if (m_rawDataIndex < arraySize(m_savedRawBytes)) m_savedRawBytes[m_rawDataIndex++] = event.data1(); return; // Don't output any thing yet so just return case MIDI_PB_outputRawMidiData: //used for a SYSTEM_EVENT //for (size_t i = 0; i < m_rawDataIndex; i++) //message.push_back( m_savedRawBytes[i]); m_rawDataIndex = 0; // FIXME missing break; } //event.printDetails(); // useful for debugging } // Return the number of events waiting to be read from the midi device int CMidiDeviceFluidSynth::checkMidiInput() { return 0; } // reads the real midi event CMidiEvent CMidiDeviceFluidSynth::readMidiInput() { CMidiEvent midiEvent; return midiEvent; } int CMidiDeviceFluidSynth::midiSettingsSetStr(QString name, QString str) { if (!m_fluidSettings) return 0; return fluid_settings_setstr(m_fluidSettings, (char *)qPrintable(name), (char *)qPrintable(str)); } int CMidiDeviceFluidSynth::midiSettingsSetNum(QString name, double val) { if (!m_fluidSettings) return 0; return fluid_settings_setnum(m_fluidSettings, (char *)qPrintable(name), val); } int CMidiDeviceFluidSynth::midiSettingsSetInt(QString name, int val) { if (!m_fluidSettings) return 0; return fluid_settings_setint(m_fluidSettings, (char *)qPrintable(name), val); } QString CMidiDeviceFluidSynth::midiSettingsGetStr(QString name) { char buffer[200]; if (!m_fluidSettings) return QString(); //fluid_settings_getstr(m_fluidSettings, (char *)qPrintable(name), buffer ); return QString( buffer ); } double CMidiDeviceFluidSynth::midiSettingsGetNum(QString name) { if (!m_fluidSettings) return 0.0; double val; fluid_settings_getnum(m_fluidSettings, (char *)qPrintable(name), &val); return val; } int CMidiDeviceFluidSynth::midiSettingsGetInt(QString name) { if (!m_fluidSettings) return 0; int val = 0; fluid_settings_getint(m_fluidSettings, (char *)qPrintable(name),&val); return val; } pianobooster-src-0.6.4/src/MidiDeviceBase.h0000644000175000017500000000446411304222711017620 0ustar louislouis/*********************************************************************************/ /*! @file MidiDevice.h @brief xxxxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __MIDI_DEVICE_BASE_H__ #define __MIDI_DEVICE_BASE_H__ #include #include "Util.h" /*! * @brief xxxxx. */ #include "MidiEvent.h" class CMidiDeviceBase { public: virtual void init() = 0; //! add a midi event to be played immediately virtual void playMidiEvent(const CMidiEvent & event) = 0; virtual int checkMidiInput() = 0; virtual CMidiEvent readMidiInput() = 0; typedef enum {MIDI_INPUT, MIDI_OUTPUT} midiType_t; virtual QStringList getMidiPortList(midiType_t type) = 0; virtual bool openMidiPort(midiType_t type, QString portName) = 0; virtual void closeMidiPort(midiType_t type, int index) = 0; // based on the fluid synth settings virtual int midiSettingsSetStr(QString name, QString str) = 0; virtual int midiSettingsSetNum(QString name, double val) = 0; virtual int midiSettingsSetInt(QString name, int val) = 0; virtual QString midiSettingsGetStr(QString name) = 0; virtual double midiSettingsGetNum(QString name) = 0; virtual int midiSettingsGetInt(QString name) = 0; //you should always have a virtual destructor when using virtual functions virtual ~CMidiDeviceBase() {}; private: }; #endif //__MIDI_DEVICE_H__ pianobooster-src-0.6.4/src/MidiDevice.h0000644000175000017500000000456211304222711017024 0ustar louislouis/*********************************************************************************/ /*! @file MidiDevice.h @brief xxxxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __MIDI_DEVICE_H__ #define __MIDI_DEVICE_H__ #include "Util.h" /*! * @brief xxxxx. */ #include "MidiEvent.h" #include "MidiDeviceBase.h" class CMidiDevice : public CMidiDeviceBase { public: CMidiDevice(); ~CMidiDevice(); void init(); //! add a midi event to be played immediately void playMidiEvent(const CMidiEvent & event); int checkMidiInput(); CMidiEvent readMidiInput(); bool validMidiOutput() { return m_validOutput; } QStringList getMidiPortList(midiType_t type); bool openMidiPort(midiType_t type, QString portName); void closeMidiPort(midiType_t type, int index); // based on the fluid synth settings virtual int midiSettingsSetStr(QString name, QString str); virtual int midiSettingsSetNum(QString name, double val); virtual int midiSettingsSetInt(QString name, int val); virtual QString midiSettingsGetStr(QString name); virtual double midiSettingsGetNum(QString name); virtual int midiSettingsGetInt(QString name); private: CMidiDeviceBase* m_rtMidiDevice; #if PB_USE_FLUIDSYNTH CMidiDeviceBase* m_fluidSynthMidiDevice; #endif CMidiDeviceBase* m_selectedMidiInputDevice; CMidiDeviceBase* m_selectedMidiOutputDevice; bool m_validOutput; }; #endif //__MIDI_DEVICE_H__ pianobooster-src-0.6.4/src/MidiDevice.cpp0000644000175000017500000001110611304222711017347 0ustar louislouis/*********************************************************************************/ /*! @file MidiDevice.cpp @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include "MidiDevice.h" #include "MidiDeviceRt.h" #if PB_USE_FLUIDSYNTH #include "MidiDeviceFluidSynth.h" #endif CMidiDevice::CMidiDevice() { m_rtMidiDevice = new CMidiDeviceRt(); #if PB_USE_FLUIDSYNTH m_fluidSynthMidiDevice = new CMidiDeviceFluidSynth(); #endif m_selectedMidiInputDevice = m_rtMidiDevice; m_selectedMidiOutputDevice = m_rtMidiDevice; m_validOutput = false; } CMidiDevice::~CMidiDevice() { delete m_rtMidiDevice; #if PB_USE_FLUIDSYNTH delete m_fluidSynthMidiDevice; #endif } void CMidiDevice::init() { } QStringList CMidiDevice::getMidiPortList(midiType_t type) { QStringList list; #if PB_USE_FLUIDSYNTH list << m_fluidSynthMidiDevice->getMidiPortList(type); #endif list << m_rtMidiDevice->getMidiPortList(type); return list; } bool CMidiDevice::openMidiPort(midiType_t type, QString portName) { closeMidiPort(type, -1); if (type == MIDI_INPUT) { if (m_rtMidiDevice->openMidiPort(type, portName)) { m_selectedMidiOutputDevice = m_rtMidiDevice; return true; } } else { m_validOutput = false; //m_selectedMidiOutputDevice->closeMidiPort(type, portName); if ( m_rtMidiDevice->openMidiPort(type, portName) ) { m_selectedMidiOutputDevice = m_rtMidiDevice; m_validOutput = true; return true; } #if PB_USE_FLUIDSYNTH if ( m_fluidSynthMidiDevice->openMidiPort(type, portName) ) { m_selectedMidiOutputDevice = m_fluidSynthMidiDevice; m_validOutput = true; return true; } #endif } return false; } void CMidiDevice::closeMidiPort(midiType_t type, int index) { if (m_selectedMidiOutputDevice == 0) return; m_selectedMidiOutputDevice->closeMidiPort(type, index); m_selectedMidiOutputDevice = 0; } //! add a midi event to be played immediately void CMidiDevice::playMidiEvent(const CMidiEvent & event) { if (m_selectedMidiOutputDevice == 0) return; m_selectedMidiOutputDevice->playMidiEvent(event); //event.printDetails(); // useful for debugging } // Return the number of events waiting to be read from the midi device int CMidiDevice::checkMidiInput() { if (m_selectedMidiOutputDevice == 0) return 0; return m_selectedMidiInputDevice->checkMidiInput(); } // reads the real midi event CMidiEvent CMidiDevice::readMidiInput() { return m_selectedMidiInputDevice->readMidiInput(); } int CMidiDevice::midiSettingsSetStr(QString name, QString str) { if (m_selectedMidiOutputDevice) return m_selectedMidiOutputDevice->midiSettingsSetStr(name, str); return 0; } int CMidiDevice::midiSettingsSetNum(QString name, double val) { if (m_selectedMidiOutputDevice) return m_selectedMidiOutputDevice->midiSettingsSetNum(name, val); return 0; } int CMidiDevice::midiSettingsSetInt(QString name, int val) { if (m_selectedMidiOutputDevice) return m_selectedMidiOutputDevice->midiSettingsSetInt(name, val); return 0; } QString CMidiDevice::midiSettingsGetStr(QString name) { if (m_selectedMidiOutputDevice) return m_selectedMidiOutputDevice->midiSettingsGetStr(name); return QString(); } double CMidiDevice::midiSettingsGetNum(QString name) { if (m_selectedMidiOutputDevice) return m_selectedMidiOutputDevice->midiSettingsGetNum(name); return 0.0; } int CMidiDevice::midiSettingsGetInt(QString name) { if (m_selectedMidiOutputDevice) return m_selectedMidiOutputDevice->midiSettingsGetInt(name); return 0; } pianobooster-src-0.6.4/src/Merge.h0000644000175000017500000000325411304222711016056 0ustar louislouis/*********************************************************************************/ /*! @file Merge.h @brief Merge Midi Events from multiple streams into a single stream. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ ///////////////////////////////////////////////////////////////////////////// #ifndef __MERGE_H__ #define __MERGE_H__ #include #include "MidiEvent.h" // Reads data from a standard MIDI file class CMerge { public: CMerge() { } CMidiEvent readMidiEvent(); //you should always have a virtual destructor when using virtual functions virtual ~CMerge() {}; protected: void setSize(int size) {m_mergeEvents.resize(size);} void initMergedEvents(); int nextMergedEvent(); virtual bool checkMidiEventFromStream(int streamIdx) = 0; virtual CMidiEvent fetchMidiEventFromStream(int streamIdx) = 0; private: QVector m_mergeEvents; }; #endif // __MERGE_H__ pianobooster-src-0.6.4/src/Merge.cpp0000644000175000017500000000561711304222711016416 0ustar louislouis/*********************************************************************************/ /*! @file Merge.cpp @brief Merge Midi Events from multiple streams into a single stream. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ ///////////////////////////////////////////////////////////////////////////// #include "Merge.h" void CMerge::initMergedEvents() { int i; for( i = 0; i < m_mergeEvents.size(); i++) { m_mergeEvents[i].clear(); if (checkMidiEventFromStream(i) ) m_mergeEvents[i] = fetchMidiEventFromStream(i); } } int CMerge::nextMergedEvent() { int nearestIndex = 0; int i; CMidiEvent* nearestEvent; int deltaTime; nearestEvent = 0; // find the first active slot for( i = 0; i < m_mergeEvents.size(); i++) { if (m_mergeEvents[i].type() != MIDI_NONE) { nearestEvent = &m_mergeEvents[i]; nearestIndex = i; break; } } if (nearestEvent == 0) return 0; // now search the remaining active slots for( i = nearestIndex + 1; i < m_mergeEvents.size(); i++) { if (m_mergeEvents[i].type() != MIDI_NONE) { // find the slot with the lowest delta time if (m_mergeEvents[i].deltaTime() < nearestEvent->deltaTime()) { nearestEvent = &m_mergeEvents[i]; nearestIndex = i; } } } deltaTime = -nearestEvent->deltaTime(); // Now subtract the delta time from all the others for( i = 0; i < m_mergeEvents.size(); i++) { if (i == nearestIndex) continue; if (m_mergeEvents[i].type() != MIDI_NONE) m_mergeEvents[i].addDeltaTime( deltaTime ); } return nearestIndex; } CMidiEvent CMerge::readMidiEvent() { int mergeIdx; CMidiEvent event; mergeIdx = nextMergedEvent(); event = m_mergeEvents[mergeIdx]; m_mergeEvents[mergeIdx].clear(); if (checkMidiEventFromStream(mergeIdx) ) m_mergeEvents[mergeIdx] = fetchMidiEventFromStream(mergeIdx); if (event.type() == MIDI_NONE) event.setType(MIDI_PB_EOF); return event; } pianobooster-src-0.6.4/src/GuiTopBar.ui0000644000175000017500000001210311304222711017032 0ustar louislouis GuiTopBar 0 0 839 34 0 0 0 34 524287 524287 Form QLayout::SetMaximumSize 0 0 6 QLayout::SetFixedSize Start playing music from the start :/images/play-from-start.png:/images/play-from-start.png 24 24 false Start and stop playing music :/images/play.png:/images/play.png 24 24 false Speed: Key: Transpose: 12 24 true Qt::DownArrow Start Bar: 1 999.899999999999977 Save this Bar Number :/images/flag.png:/images/flag.png 24 24 Qt::Horizontal 0 30 pianobooster-src-0.6.4/src/GuiTopBar.h0000644000175000017500000000445511304222711016657 0ustar louislouis/*********************************************************************************/ /*! @file GuiTopBar.cpp @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __GUITOPBAR_H__ #define __GUITOPBAR_H__ #include #include "Song.h" #include "Score.h" #include "TrackList.h" #include "Settings.h" #include "ui_GuiTopBar.h" class GuiTopBar : public QWidget, private Ui::GuiTopBar { Q_OBJECT public: GuiTopBar(QWidget *parent, CSettings* settings); void init(CSong* songObj, CTrackList* trackList); void refresh(bool reset); void setPlayButtonState(bool checked, bool atTheEnd = false); void setSpeed(int value){ speedSpin->setValue(value); } int getSpeed(){return speedSpin->value();} public slots: void on_playFromStartButton_clicked(bool clicked); void on_playButton_clicked(bool clicked); private slots: void on_speedSpin_valueChanged(int speed); void on_startBarSpin_valueChanged(double bar); void on_transposeSpin_valueChanged(int value); void on_keyCombo_activated(int index); void on_majorCombo_activated(int index) { reloadKeyCombo((index == 0)?true:false); } void on_saveBarButton_clicked(bool clicked); void on_loopingBarsPopupButton_clicked(bool clicked); private: bool eventFilter(QObject *obj, QEvent *event); void reloadKeyCombo(bool major); CSong* m_song; CSettings* m_settings; bool m_atTheEndOfTheSong; }; #endif //__GUITOPBAR_H__ pianobooster-src-0.6.4/src/GuiTopBar.cpp0000644000175000017500000001540011304222711017202 0ustar louislouis/*********************************************************************************/ /*! @file GuiTopBar.cpp @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include #include "GuiTopBar.h" #include "TrackList.h" #include "GuiLoopingPopup.h" GuiTopBar::GuiTopBar(QWidget *parent, CSettings* settings) : QWidget(parent), m_settings(settings) { m_atTheEndOfTheSong = false; m_song = 0; setupUi(this); parent->installEventFilter(this); speedSpin->setMaximum(200); speedSpin->setMinimum(20); speedSpin->setSuffix(" %"); speedSpin->setSingleStep(2); speedSpin->setValue(100); transposeSpin->setMaximum(12); transposeSpin->setMinimum(-12); majorCombo->addItem("Major"); majorCombo->addItem("Minor"); setMaximumHeight(30); setMaximumSize(QSize(16777215, 30)); } void GuiTopBar::init(CSong* songObj, CTrackList* trackList) { m_song = songObj; reloadKeyCombo(true); } void GuiTopBar::refresh(bool reset) { if (reset == true) { majorCombo->setCurrentIndex(0); reloadKeyCombo(true); transposeSpin->setValue(0); startBarSpin->setValue(0); } int index = 0; if (m_song) index = CStavePos::getKeySignature() + 6; if (index >= 0 && index < keyCombo->count()) keyCombo->setCurrentIndex(index); } void GuiTopBar::reloadKeyCombo(bool major) { keyCombo->clear(); if (major) { keyCombo->addItem("Gb"); // -6 keyCombo->addItem("Db"); // -5 keyCombo->addItem("Ab"); // -4 keyCombo->addItem("Eb"); // -3 keyCombo->addItem("Bb"); // -2 keyCombo->addItem("F "); // -1 keyCombo->addItem("C"); // 0 keyCombo->addItem("G "); // 1 keyCombo->addItem("D "); // 2 keyCombo->addItem("A "); // 3 keyCombo->addItem("E "); // 4 keyCombo->addItem("B "); // 5 keyCombo->addItem("F#"); // 6 } else { keyCombo->addItem("Eb"); keyCombo->addItem("Bb"); keyCombo->addItem("F"); keyCombo->addItem("C"); keyCombo->addItem("G"); keyCombo->addItem("D "); keyCombo->addItem("A"); keyCombo->addItem("E "); keyCombo->addItem("B "); keyCombo->addItem("F#"); keyCombo->addItem("G#"); keyCombo->addItem("C#"); keyCombo->addItem("D#"); } refresh(false); } void GuiTopBar::on_keyCombo_activated(int index) { CStavePos::setKeySignature(index - 6, 0); m_song->refreshScroll(); } void GuiTopBar::on_transposeSpin_valueChanged(int value) { unsigned int i; //C Db D Eb E F F# G Ab A Bb B const int nextKey[] = { 0, -5, 2, -3, 4, -1, 6, 1, -4, 3, -2, 5}; if (!m_song) return; int diff = value - m_song->getTranspose(); int oldValue = CStavePos::getKeySignature(); if (oldValue == -6) oldValue = 6; // if key is Eb change to D# // Find the old value in the table for (i=0; i < arraySize(nextKey); i++) { if (oldValue == nextKey[i]) break; } int newValue = nextKey[(diff + i + arraySize(nextKey)) % arraySize(nextKey) ]; CStavePos::setKeySignature( newValue, 0 ); newValue += 6; keyCombo->setCurrentIndex(newValue); if (newValue >= 0 && newValue < keyCombo->count()) keyCombo->setCurrentIndex(newValue); m_song->transpose(value); m_song->forceScoreRedraw(); } void GuiTopBar::setPlayButtonState(bool checked, bool atTheEnd) { if (atTheEnd) m_atTheEndOfTheSong = true; playButton->setChecked(checked); if (checked) { playButton->setIcon(QIcon(":/images/stop.png")); playButton->setToolTip(""); playFromStartButton->setToolTip(""); } else { playButton->setIcon(QIcon(":/images/play.png")); playButton->setToolTip("Start and stop playing music"); playFromStartButton->setToolTip("Playing music from the beginning"); } } void GuiTopBar::on_playButton_clicked(bool clicked) { if (!m_song) return; if (m_atTheEndOfTheSong) m_song->rewind(); m_atTheEndOfTheSong = false; bool start = !m_song->playingMusic(); m_song->playMusic(start); setPlayButtonState(start); } void GuiTopBar::on_playFromStartButton_clicked(bool clicked) { if (!m_song) return; m_atTheEndOfTheSong = false; m_song->playFromStartBar(); setPlayButtonState(true); } void GuiTopBar::on_speedSpin_valueChanged(int speed) { if (!m_song) return; m_song->setSpeed(speed/100.0); } void GuiTopBar::on_startBarSpin_valueChanged(double bar) { if (!m_song) return; // Stop the muisc playing m_song->playMusic(false); setPlayButtonState(false); m_song->setPlayFromBar( bar); } void GuiTopBar::on_saveBarButton_clicked(bool clicked) { if (!m_song) return; double barNumber = m_song->getCurrentBarPos(); startBarSpin->setValue(barNumber); } void GuiTopBar::on_loopingBarsPopupButton_clicked(bool clicked) { if (!m_song) return; m_song->playMusic(false); setPlayButtonState(false); QPoint pos = mapToGlobal(loopingBarsPopupButton->pos()) ; pos.ry() += loopingBarsPopupButton->height() + 2; pos.rx() += -5; // Tweak the position slightly GuiLoopingPopup *loopingPopup = new GuiLoopingPopup(loopingBarsPopupButton); loopingPopup->init(m_song); loopingPopup->move (pos); loopingPopup->show(); } bool GuiTopBar::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast(event); if (keyEvent->key()==Qt::Key_Up) { speedSpin->stepUp(); return true; } else if (keyEvent->key()==Qt::Key_Down) { speedSpin->stepDown(); return true; } else { return false; } } else { // it's not a key event, lets do standard event processing return QObject::eventFilter(obj, event); } } pianobooster-src-0.6.4/src/GuiSongDetailsDialog.ui0000644000175000017500000000711011304222711021201 0ustar louislouis GuiSongDetailsDialog 0 0 388 265 Dialog Song Details MIDI Channels for left and right hand piano parts: false Right Hand MIDI Channel: 0 0 180 0 Left Hand MIDI Channel: 0 0 150 0 Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::Ok buttonBox accepted() GuiSongDetailsDialog accept() 248 254 157 274 buttonBox rejected() GuiSongDetailsDialog reject() 316 260 286 274 pianobooster-src-0.6.4/src/GuiSongDetailsDialog.h0000644000175000017500000000330411304222711021014 0ustar louislouis/*********************************************************************************/ /*! @file GuiSongDetailsDialog.h @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __GUISONGDETAILSDIALOG_H__ #define __GUISONGDETAILSDIALOG_H__ #include #include "Song.h" #include "Settings.h" #include "ui_GuiSongDetailsDialog.h" class CGLView; class GuiSongDetailsDialog : public QDialog, private Ui::GuiSongDetailsDialog { Q_OBJECT public: GuiSongDetailsDialog(QWidget *parent = 0); void init(CSong* song, CSettings* settings); private slots: void accept(); void on_leftHandChannelCombo_activated (int index); void on_rightHandChannelCombo_activated (int index); private: void updateSongInfoText(); CSettings* m_settings; CSong* m_song; CTrackList* m_trackList; }; #endif //__GUISONGDETAILSDIALOG_H__ pianobooster-src-0.6.4/src/GuiSongDetailsDialog.cpp0000644000175000017500000000660711304222711021360 0ustar louislouis/*! @file GuiSongDetailsDialog.cpp @brief xxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ #include #include "GuiSongDetailsDialog.h" #include "GlView.h" GuiSongDetailsDialog::GuiSongDetailsDialog(QWidget *parent) : QDialog(parent) { setupUi(this); m_song = 0; m_settings = 0; m_trackList = 0; setWindowTitle("Song Details"); } void GuiSongDetailsDialog::init(CSong* song, CSettings* settings) { m_song = song; m_settings = settings; m_trackList = m_song->getTrackList(); leftHandChannelCombo->addItem(tr("No channel assigned")); leftHandChannelCombo->addItems(m_trackList->getAllChannelProgramNames(true)); rightHandChannelCombo->addItem(tr("No channel assigned")); rightHandChannelCombo->addItems(m_trackList->getAllChannelProgramNames(true)); leftHandChannelCombo->setCurrentIndex(m_trackList->getHandTrackIndex(PB_PART_left) + 1); rightHandChannelCombo->setCurrentIndex(m_trackList->getHandTrackIndex(PB_PART_right) +1); updateSongInfoText(); } void GuiSongDetailsDialog::updateSongInfoText() { QString str; songInfoText->clear(); bool activateOkButton = false; if (leftHandChannelCombo->currentIndex() != 0 && leftHandChannelCombo->currentIndex() == rightHandChannelCombo->currentIndex()) songInfoText->append("The left and rignt hand channels must be different"); else if ((leftHandChannelCombo->currentIndex() == 0 && rightHandChannelCombo->currentIndex() != 0 ) || (rightHandChannelCombo->currentIndex() == 0 && leftHandChannelCombo->currentIndex() != 0 ) ) songInfoText->append("Both left and rignt hand channels must be none to disable this feature"); else { songInfoText->append("Set the MIDI Channels to be used for left and right hand piano parts:"); songInfoText->append("the left hand piano part is using MIDI Channels 1"); songInfoText->append("the right hand piano part is using MIDI Channels 1"); activateOkButton = true; } buttonBox->button(QDialogButtonBox::Ok)->setEnabled(activateOkButton); } void GuiSongDetailsDialog::on_leftHandChannelCombo_activated (int index) { updateSongInfoText(); } void GuiSongDetailsDialog::on_rightHandChannelCombo_activated (int index) { updateSongInfoText(); } void GuiSongDetailsDialog::accept() { m_trackList->setActiveHandsIndex(leftHandChannelCombo->currentIndex() -1, rightHandChannelCombo->currentIndex() -1); this->QDialog::accept(); } pianobooster-src-0.6.4/src/GuiSidePanel.ui0000644000175000017500000001706011304222711017516 0ustar louislouis GuiSidePanel 0 0 255 424 255 16777215 Form 0 4 9 0 Book: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 0 0 0 0 Song: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 0 0 0 0 0 0 16777215 16777215 Skill Listen Follow you Play Along 0 0 Hands Right Both Left 0 0 Adjust the volume of your piano Qt::Vertical QSlider::TicksBelow 25 Parts 0 0 180 0 300 500 Adjust the volume of the selected part Qt::Vertical QSlider::TicksBelow 25 Mute the currently selected part Mute your part when playing Qt::Vertical 100 11 pianobooster-src-0.6.4/src/GuiSidePanel.h0000644000175000017500000001077711304222711017340 0ustar louislouis/*********************************************************************************/ /*! @file GuiSidePanel.h @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __GUISIDEPANEL_H__ #define __GUISIDEPANEL_H__ #include #include "Song.h" #include "Score.h" #include "TrackList.h" #include "Settings.h" #include "ui_GuiSidePanel.h" class GuiTopBar; class GuiSidePanel : public QWidget, private Ui::GuiSidePanel { Q_OBJECT public: GuiSidePanel(QWidget *parent, CSettings* settings); void init(CSong* songObj, CTrackList* trackList, GuiTopBar* topBar); void refresh(); void loadBookList(); void setBookName(QString bookName); void setSongName(QString songName); int getSongIndex() {return songCombo->currentIndex();} void setSongIndex(int index){songCombo->setCurrentIndex(index);} void setCurrentHand(QString hand); void setActiveHand(whichPart_t hand) { if (hand == PB_PART_right) rightHandRadio->setChecked(true); if (hand == PB_PART_both) bothHandsRadio->setChecked(true); if (hand == PB_PART_left) leftHandRadio->setChecked(true); } void nextSong(int amount) { int n = songCombo->currentIndex() + amount; if (n < 0 || n >= songCombo->count()) return; songCombo->setCurrentIndex(n); on_songCombo_activated(n); } private slots: void on_songCombo_activated (int index); void on_bookCombo_activated (int index); void on_rightHandRadio_toggled (bool checked); void on_bothHandsRadio_toggled (bool checked); void on_leftHandRadio_toggled (bool checked); void on_trackListWidget_currentRowChanged(int currentRow) { if (m_trackList){ m_trackList->currentRowChanged(currentRow); autoSetMuteYourPart(); } } void on_boostSlider_valueChanged(int value) { if (m_song) m_song->boostVolume(value); } void on_pianoSlider_valueChanged(int value) { if (m_song) m_song->pianoVolume(value); } void on_listenRadio_toggled (bool checked) { if (!m_song || !checked) return; m_song->setPlayMode(PB_PLAY_MODE_listen); } void on_followYouRadio_toggled (bool checked) { if (!m_song || !checked) return; m_song->setPlayMode(PB_PLAY_MODE_followYou); } void on_playAlongRadio_toggled (bool checked) { if (!m_song || !checked) return; m_song->setPlayMode(PB_PLAY_MODE_playAlong); } void on_muteYourPartCheck_toggled (bool checked) { if (m_song) m_song->mutePianistPart(checked); } void setTrackRightHandPart() { int row = trackListWidget->currentRow(); int otherRow = m_trackList->getHandTrackIndex(PB_PART_left); if (otherRow == row) otherRow = -1; m_trackList->setActiveHandsIndex(otherRow, row); trackListWidget->setCurrentRow(row); m_song->refreshScroll(); } void setTrackLeftHandPart() { int row = trackListWidget->currentRow(); int otherRow = m_trackList->getHandTrackIndex(PB_PART_right); if (otherRow == row) otherRow = -1; m_trackList->setActiveHandsIndex(row, otherRow); trackListWidget->setCurrentRow(row); m_song->refreshScroll(); } void clearTrackPart() { int row = trackListWidget->currentRow(); m_trackList->setActiveHandsIndex( -1, -1); trackListWidget->setCurrentRow(row); m_song->refreshScroll(); } private: void autoSetMuteYourPart(); CSong* m_song; CScore* m_score; CTrackList* m_trackList; GuiTopBar* m_topBar; CSettings* m_settings; QWidget *m_parent; }; #endif //__GUISIDEPANEL_H__ pianobooster-src-0.6.4/src/GuiSidePanel.cpp0000644000175000017500000001213711304222711017663 0ustar louislouis/*********************************************************************************/ /*! @file GuiSidePanel.cpp @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include #include "GuiSidePanel.h" #include "GuiTopBar.h" #include "TrackList.h" GuiSidePanel::GuiSidePanel(QWidget *parent, CSettings* settings) : QWidget(parent), m_parent(parent) { m_song = 0; m_score = 0; m_trackList = 0; m_topBar = 0; m_settings = settings; setupUi(this); } void GuiSidePanel::init(CSong* songObj, CTrackList* trackList, GuiTopBar* topBar) { m_song = songObj; m_trackList = trackList; m_topBar = topBar; m_trackList->init(songObj, m_settings); followYouRadio->setChecked(true); bothHandsRadio->setChecked(true); boostSlider->setMinimum(-100); boostSlider->setMaximum(100); pianoSlider->setMinimum(-100); pianoSlider->setMaximum(100); QAction* act; act = new QAction("Set as Right Hand Part", this); trackListWidget->addAction(act); connect(act, SIGNAL(triggered()), this, SLOT(setTrackRightHandPart())); act = new QAction("Set as Left Hand Part", this); trackListWidget->addAction(act); connect(act, SIGNAL(triggered()), this, SLOT(setTrackLeftHandPart())); act = new QAction("Reset Both Parts", this); trackListWidget->addAction(act); connect(act, SIGNAL(triggered()), this, SLOT(clearTrackPart())); trackListWidget->setContextMenuPolicy(Qt::ActionsContextMenu); } void GuiSidePanel::refresh() { if (m_trackList) { m_trackList->refresh(); trackListWidget->clear(); trackListWidget->addItems(m_trackList->getAllChannelProgramNames()); trackListWidget->setCurrentRow(m_trackList->getActiveItemIndex()); for (int i = 0; i < trackListWidget->count(); i++) m_trackList->changeListWidgetItemView(i, trackListWidget->item(i)); } autoSetMuteYourPart(); } void GuiSidePanel::loadBookList() { QStringList bookNames = m_settings->getBookList(); bookCombo->clear(); for (int i = 0; i < bookNames.size(); i++) { bookCombo->addItem( bookNames.at(i)); if (bookNames.at(i) == m_settings->getCurrentBookName()) bookCombo->setCurrentIndex(i); } on_bookCombo_activated(-1); } void GuiSidePanel::on_bookCombo_activated (int index) { QString currentSong; m_settings->setCurrentBookName(bookCombo->currentText(), (index >= 0)? true : false); currentSong = m_settings->getCurrentSongName(); songCombo->clear(); QStringList songNames = m_settings->getSongList(); for (int i = 0; i < songNames.size(); ++i) { songCombo->addItem( songNames.at(i)); if (songNames.at(i) == currentSong) songCombo->setCurrentIndex(i); } on_songCombo_activated(0); // Now load the selected song } void GuiSidePanel::on_songCombo_activated(int index) { m_settings->setCurrentSongName(songCombo->currentText()); } void GuiSidePanel::on_rightHandRadio_toggled (bool checked) { if (checked) m_settings->setActiveHand(PB_PART_right); } void GuiSidePanel::on_bothHandsRadio_toggled (bool checked) { if (checked) m_settings->setActiveHand(PB_PART_both); } void GuiSidePanel::on_leftHandRadio_toggled (bool checked) { if (checked) m_settings->setActiveHand(PB_PART_left); } void GuiSidePanel::autoSetMuteYourPart() { bool checked = false; if ( CNote::hasPianoPart(m_song->getActiveChannel())) checked = true; muteYourPartCheck->setChecked(checked); m_song->mutePianistPart(checked); } void GuiSidePanel::setSongName(QString songName) { for (int i = 0; i < songCombo->count(); ++i) { if (songCombo->itemText(i) == songName) songCombo->setCurrentIndex(i); } } void GuiSidePanel::setBookName(QString bookName) { for (int i = 0; i < bookCombo->count(); ++i) { if (bookCombo->itemText(i) == bookName) bookCombo->setCurrentIndex(i); } } // pass either 'left' 'right' or 'both' void GuiSidePanel::setCurrentHand(QString hand) { if (hand == "left") leftHandRadio->setChecked(true); else if (hand == "right") rightHandRadio->setChecked(true); else bothHandsRadio->setChecked(true); //on_bothHandsRadio_toggled } pianobooster-src-0.6.4/src/GuiPreferencesDialog.ui0000644000175000017500000001102011304222711021221 0ustar louislouis GuiPreferencesDialog 0 0 362 267 Dialog Score Settings 0 0 Timing Markers Follow stop point: 0 0 QComboBox::AdjustToContents Qt::Horizontal 40 20 Show Note Names Qt::Horizontal 40 20 Courtesy Accidentals Video Settings Video optimisation Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::Ok buttonBox accepted() GuiPreferencesDialog accept() 248 254 157 274 buttonBox rejected() GuiPreferencesDialog reject() 316 260 286 274 pianobooster-src-0.6.4/src/GuiPreferencesDialog.h0000644000175000017500000000307711304222711021050 0ustar louislouis/*********************************************************************************/ /*! @file GuiPreferencesDialog.h @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __GUIPREFERENCESDIALOG_H__ #define __GUIPREFERENCESDIALOG_H__ #include #include "Song.h" #include "Settings.h" #include "ui_GuiPreferencesDialog.h" class CGLView; class GuiPreferencesDialog : public QDialog, private Ui::GuiPreferencesDialog { Q_OBJECT public: GuiPreferencesDialog(QWidget *parent = 0); void init(CSong* song, CSettings* settings, CGLView* glView); private slots: void accept(); private: CSettings* m_settings; CSong* m_song; CGLView *m_glView; }; #endif //__GUIPREFERENCESDIALOG_H__ pianobooster-src-0.6.4/src/GuiPreferencesDialog.cpp0000644000175000017500000000501511304222711021375 0ustar louislouis/*! @file GuiPreferencesDialog.cpp @brief xxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ #include #include "GuiPreferencesDialog.h" #include "GlView.h" GuiPreferencesDialog::GuiPreferencesDialog(QWidget *parent) : QDialog(parent) { setupUi(this); m_song = 0; m_settings = 0; m_glView = 0; setWindowTitle("Preferences"); } void GuiPreferencesDialog::init(CSong* song, CSettings* settings, CGLView * glView) { m_song = song; m_settings = settings; m_glView = glView; videoOptimiseCheck->setChecked(m_glView->m_cfg_openGlOptimise); timingMarkersCheck->setChecked(m_song->cfg_timingMarkersFlag); showNoteNamesCheck->setChecked(m_settings->isNoteNamesEnabled()); courtesyAccidentalsCheck->setChecked(m_settings->displayCourtesyAccidentals()); followStopPointCombo->addItem("Automatic (Recommended)"); followStopPointCombo->addItem("On the Beat"); followStopPointCombo->addItem("After the Beat"); followStopPointCombo->setCurrentIndex(m_song->cfg_stopPointMode); } void GuiPreferencesDialog::accept() { m_glView->m_cfg_openGlOptimise = videoOptimiseCheck->isChecked(); m_settings->setValue("Display/OpenGlOptimise", m_glView->m_cfg_openGlOptimise ); m_song->cfg_timingMarkersFlag = timingMarkersCheck->isChecked(); m_settings->setValue("Score/TimingMarkers", m_song->cfg_timingMarkersFlag ); m_settings->setNoteNamesEnabled( showNoteNamesCheck->isChecked()); m_settings->setCourtesyAccidentals( courtesyAccidentalsCheck->isChecked()); m_song->cfg_stopPointMode = static_cast (followStopPointCombo->currentIndex()); m_settings->setValue("Score/StopPointMode", m_song->cfg_stopPointMode ); m_song->refreshScroll(); this->QDialog::accept(); } pianobooster-src-0.6.4/src/GuiMidiSetupDialog.ui0000644000175000017500000002744311304222711020703 0ustar louislouis GuiMidiSettingsDialog 0 0 465 369 Dialog QTabWidget::Rounded 1 MIDI input && output Qt::Vertical QSizePolicy::Expanding 396 28 Select the MIDI devices 0 0 16777215 100 false true QLayout::SetMinimumSize Midi Input Device: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Midi Output Device: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Qt::Vertical QSizePolicy::Expanding 396 28 FluidSynth Sound Fonts Add Remove Qt::Vertical 20 40 Settings 150 0 Audio Device: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Master Gain: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Audio Driver: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Sample Rate: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Bufer Size Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Buffer counts Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Reverb Chorus Latency Fix 40 120 121 29 Latency 200 130 195 17 0 (msec) Qt::AlignCenter Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::Ok buttonBox midiSetupTabWidget buttonBox accepted() GuiMidiSettingsDialog accept() 248 254 157 274 buttonBox rejected() GuiMidiSettingsDialog reject() 316 260 286 274 pianobooster-src-0.6.4/src/GuiMidiSetupDialog.h0000644000175000017500000000361311304222711020506 0ustar louislouis/*********************************************************************************/ /*! @file GuiMidiSetupDialog.h @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __GUIMIDISETUPDIALOG_H__ #define __GUIMIDISETUPDIALOG_H__ #include #include "Song.h" #include "Settings.h" #include "ui_GuiMidiSetupDialog.h" class GuiMidiSetupDialog : public QDialog, private Ui::GuiMidiSettingsDialog { Q_OBJECT public: GuiMidiSetupDialog(QWidget *parent = 0); void init(CSong* song, CSettings* settings); private slots: void accept(); void on_midiInputCombo_activated (int index); void on_midiOutputCombo_activated (int index); void on_latencyFixButton_clicked ( bool checked ); void on_fluidAddButton_clicked ( bool checked ); void on_fluidRemoveButton_clicked ( bool checked ); private: void updateMidiInfoText(); void updateFluidInfoText(); CSettings* m_settings; CSong* m_song; int m_latencyFix; bool m_latencyChanged; bool m_midiChanged; }; #endif //__GUIMIDISETUPDIALOG_H__ pianobooster-src-0.6.4/src/GuiMidiSetupDialog.cpp0000644000175000017500000001743211304222711021045 0ustar louislouis/*! @file GuiMidiSetupDialog.cpp @brief xxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ #include #include "GuiMidiSetupDialog.h" GuiMidiSetupDialog::GuiMidiSetupDialog(QWidget *parent) : QDialog(parent) { m_song = 0; m_settings = 0; setupUi(this); m_latencyFix = 0; m_latencyChanged = false; m_midiChanged = false; midiSetupTabWidget->setCurrentIndex(0); #if !PB_USE_FLUIDSYNTH midiSetupTabWidget->removeTab(1); #endif setWindowTitle("Midi Setup"); } void GuiMidiSetupDialog::init(CSong* song, CSettings* settings) { m_song = song; m_settings = settings; // Check inputs. QString portName; int i = 0; m_latencyFix = m_song->getLatencyFix(); midiInputCombo->addItem(tr("None (PC Keyboard)")); midiInputCombo->addItems(song->getMidiPortList(CMidiDevice::MIDI_INPUT)); // Check outputs. midiOutputCombo->addItem(tr("None")); midiOutputCombo->addItems(song->getMidiPortList(CMidiDevice::MIDI_OUTPUT)); i = midiInputCombo->findText(m_settings->value("Midi/Input").toString()); if (i!=-1) midiInputCombo->setCurrentIndex(i); i = midiOutputCombo->findText(m_settings->value("Midi/Output").toString()); if (i!=-1) midiOutputCombo->setCurrentIndex(i); sampleRateCombo->addItem("44100"); sampleRateCombo->addItem("22050"); i = sampleRateCombo->findText(m_settings->value("Fliudsynth/SampleRate").toString()); if (i!=-1) sampleRateCombo->setCurrentIndex(i); //midiSettingsSetnum updateMidiInfoText(); } void GuiMidiSetupDialog::updateMidiInfoText() { QString str; midiInfoText->clear(); if (midiInputCombo->currentIndex() == 0) midiInfoText->append("If you don't have a MIDI keyboard you can use the PC keyboard; 'X' is middle C."); else if (midiInputCombo->currentText().startsWith("Midi Through", Qt::CaseInsensitive)) midiInfoText->append("The use of Midi Through is not recommended!"); else midiInfoText->append("Midi Input Device: " + midiInputCombo->currentText() +""); if (midiOutputCombo->currentText() == "None") midiInfoText->append("No Sound Output Device selected; Choose a Midi Output Device "); else if (midiOutputCombo->currentText().startsWith("Midi Through", Qt::CaseInsensitive)) midiInfoText->append("The use of Midi Through is not recommended!"); else if (midiOutputCombo->currentText().startsWith("Microsoft GS Wavetable SW Synth", Qt::CaseInsensitive)) midiInfoText->append("Note: the Microsoft SW Synth introduces an unwanted delay!"); else midiInfoText->append("Midi Output Device: " + midiOutputCombo->currentText() +""); latencyFixLabel->setText(tr("%1 mSec").arg(m_latencyFix)); updateFluidInfoText(); } void GuiMidiSetupDialog::on_midiInputCombo_activated (int index) { m_midiChanged = true; updateMidiInfoText(); } void GuiMidiSetupDialog::on_midiOutputCombo_activated (int index) { m_midiChanged = true; updateMidiInfoText(); } void GuiMidiSetupDialog::on_latencyFixButton_clicked ( bool checked ) { bool ok; int latencyFix = QInputDialog::getInteger(this, tr("Enter a value for the latency fix in milliseconds"), tr( "The latency fix works by running the music ahead of what you
" "are playing to counteract the delay within the sound generator.

" "You will need a piano with speakers that are turned up.

" "Enter the time in milliseconds for the delay (1000 mSec = 1 sec)
" "(For the Microsoft GS Wavetable SW Synth try a value of 150)
" "If you are not sure enter a value of zero."), m_latencyFix, 0, 1000, 50, &ok); if (ok) { m_latencyFix = latencyFix; m_latencyChanged = true; updateMidiInfoText(); } } void GuiMidiSetupDialog::accept() { m_settings->setValue("Midi/Input", midiInputCombo->currentText()); m_song->openMidiPort(CMidiDevice::MIDI_INPUT, midiInputCombo->currentText() ); if (midiInputCombo->currentText().startsWith("None")) CChord::setPianoRange(PC_KEY_LOWEST_NOTE, PC_KEY_HIGHEST_NOTE); else CChord::setPianoRange(m_settings->value("Keyboard/LowestNote", 0).toInt(), m_settings->value("Keyboard/HighestNote", 127).toInt()); if (m_latencyChanged == false || m_midiChanged == true) { m_settings->setValue("Midi/Output", midiOutputCombo->currentText()); m_song->openMidiPort(CMidiDevice::MIDI_OUTPUT, midiOutputCombo->currentText() ); m_settings->updateWarningMessages(); } m_settings->setValue("Midi/Latency", m_latencyFix); m_song->setLatencyFix(m_latencyFix); m_song->regenerateChordQueue(); if (m_latencyChanged) { if( m_latencyFix> 0) { int rightSound = m_settings->value("Keyboard/RightSound", Cfg::defaultRightPatch()).toInt(); m_settings->setValue("Keyboard/RightSoundPrevious", rightSound); // Save the current right sound // Mute the Piano if we are using the latency fix; m_settings->setValue("Keyboard/RightSound", 0); m_song->setPianoSoundPatches( -1, -2); // -1 means no sound and -2 means ignore this parameter } else { int previousRightSound = m_settings->value("Keyboard/RightSoundPrevious", Cfg::defaultRightPatch()).toInt(); m_settings->setValue("Keyboard/RightSound", previousRightSound); m_song->setPianoSoundPatches(previousRightSound, -2); // -2 means ignore this parameter } } this->QDialog::accept(); } void GuiMidiSetupDialog::updateFluidInfoText() { QStringList soundFontNames = m_settings->getFluidSoundFontNames(); soundFontList->clear(); for (int i=0; i < soundFontNames.count(); i++) { int n = soundFontNames.at(i).lastIndexOf("/"); soundFontList->addItem(soundFontNames.at(i).mid(n+1)); } bool fontLoaded = (soundFontList->count() > 0) ? true : false; fluidRemoveButton->setEnabled(fontLoaded); fluidAddButton->setEnabled(soundFontList->count() < 2 ? true : false); fluidSettingsGroupBox->setEnabled(fontLoaded); } void GuiMidiSetupDialog::on_fluidAddButton_clicked ( bool checked ) { QString lastSoundFont; QStringList sfList = m_settings->getFluidSoundFontNames(); if (sfList.size() > 0) lastSoundFont = sfList.last(); QString soundFontName = QFileDialog::getOpenFileName(this,tr("Open SoundFont2 File for fluid synth"), lastSoundFont, tr("SoundFont2 Files (*.sf2)")); if (!soundFontName.isEmpty()) m_settings->addFluidSoundFontName(soundFontName); updateFluidInfoText(); } void GuiMidiSetupDialog::on_fluidRemoveButton_clicked ( bool checked ) { } pianobooster-src-0.6.4/src/GuiLoopingPopup.ui0000644000175000017500000000404211304222711020301 0ustar louislouis GuiLoopingPopup 0 0 157 70 0 0 Form 0 QLayout::SetMinimumSize 2 4 0 0 Repeat Bars: 62 16777215 true 1 99.900000000000006 End bar pianobooster-src-0.6.4/src/GuiLoopingPopup.h0000644000175000017500000000301111304222711020106 0ustar louislouis/*********************************************************************************/ /*! @file GuiLoopingPopup.h @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __GUILOOPINGPOPUP_H__ #define __GUILOOPINGPOPUP_H__ #include #include "Song.h" #include "ui_GuiLoopingPopup.h" class CGLView; class GuiLoopingPopup : public QWidget, private Ui::GuiLoopingPopup { Q_OBJECT public: GuiLoopingPopup(QWidget *parent = 0); void init(CSong* song); private slots: void on_loopBarsSpin_valueChanged(double bars); void closeEvent(QCloseEvent *event); private: void updateInfo(); CSong* m_song; }; #endif //__GUILOOPINGPOPUP_H__ pianobooster-src-0.6.4/src/GuiLoopingPopup.cpp0000644000175000017500000000347511304222711020457 0ustar louislouis/*! @file GuiLoopingPopup.cpp @brief xxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ #include #include "GuiLoopingPopup.h" #include "GlView.h" GuiLoopingPopup::GuiLoopingPopup(QWidget *parent) : QWidget(parent) { setupUi(this); m_song = 0; setWindowTitle(tr("Continuous Looping")); setWindowFlags(Qt::Popup); } void GuiLoopingPopup::init(CSong* song) { m_song = song; loopBarsSpin->setValue(m_song->getLoopingBars()); updateInfo(); } void GuiLoopingPopup::updateInfo() { if (m_song->getLoopingBars() > 0.0) loopingText->setText(tr("Repeat End Bar: ") + QString().setNum(m_song->getPlayUptoBar())); else loopingText->setText(tr("Repeat Bar is disabled")); } void GuiLoopingPopup::on_loopBarsSpin_valueChanged(double bars) { if (!m_song) return; m_song->setLoopingBars( bars); updateInfo(); } void GuiLoopingPopup::closeEvent(QCloseEvent *event) { QPushButton* parent = static_cast (parentWidget()); if (parent) parent->setChecked(false); } pianobooster-src-0.6.4/src/GuiKeyboardSetupDialog.ui0000644000175000017500000002445411304222711021560 0ustar louislouis GuiKeyboardSetupDialog 0 0 501 348 501 16777215 Dialog Setup Your Piano Keyboard 0 0 16777215 60 false true Right Notes sound: 200 0 volume: % 1 200 100 Qt::Horizontal 40 20 Test Wrong Notes sound: 0 0 200 0 volume: % 1 200 100 Qt::Horizontal 40 20 Test Keyboard Note Range Lowest Note: 60 16777215 The note number between 0 and 127 000; Qt::Horizontal 40 20 Highest Note: 60 16777215 The note number between 0 and 127 000; Qt::Horizontal 40 20 Reset Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::NoButton|QDialogButtonBox::Ok buttonBox accepted() GuiKeyboardSetupDialog accept() 248 254 157 274 buttonBox rejected() GuiKeyboardSetupDialog reject() 316 260 286 274 pianobooster-src-0.6.4/src/GuiKeyboardSetupDialog.h0000644000175000017500000000527411304222711021371 0ustar louislouis/*********************************************************************************/ /*! @file GuiKeyboardSetupDialog.h @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __GUILEYBOARDSETUPDIALOG_H__ #define __GUILEYBOARDSETUPDIALOG_H__ #include #include "Song.h" #include "Settings.h" #include "ui_GuiKeyboardSetupDialog.h" class GuiKeyboardSetupDialog : public QDialog, private Ui::GuiKeyboardSetupDialog { Q_OBJECT public: GuiKeyboardSetupDialog(QWidget *parent = 0); void init(CSong* song, CSettings* settings); private slots: void accept(); void reject(); void on_rightTestButton_pressed() { m_song->testWrongNoteSound(false); m_song->pcKeyPress( 'x', true); } void on_rightTestButton_released() { m_song->pcKeyPress( 'x', false); } void on_wrongTestButton_pressed() { m_song->testWrongNoteSound(true); m_song->pcKeyPress( 'x', true); } void on_wrongTestButton_released() { m_song->pcKeyPress( 'x', false); } void on_resetButton_clicked(bool clicked) { lowestNoteEdit->setText("0"); highestNoteEdit->setText("127"); updateInfoText(); } void on_rightSoundCombo_activated (int index){ updateSounds(); } void on_wrongSoundCombo_activated (int index){ updateSounds(); } void on_lowestNoteEdit_editingFinished(){updateInfoText();} void on_highestNoteEdit_editingFinished(){updateInfoText();} private: void keyPressEvent ( QKeyEvent * event ); void keyReleaseEvent ( QKeyEvent * event ); void updateSounds (){ m_song->setPianoSoundPatches(rightSoundCombo->currentIndex() -1, wrongSoundCombo->currentIndex() -1, true); } void updateInfoText(); CSettings* m_settings; CSong* m_song; }; #endif //__GUILEYBOARDSETUPDIALOG_H__ pianobooster-src-0.6.4/src/GuiKeyboardSetupDialog.cpp0000644000175000017500000001326611304222711021724 0ustar louislouis/*********************************************************************************/ /*! @file GuiKeyboardSetupDialog.cpp @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include #include "GuiKeyboardSetupDialog.h" #include "rtmidi/RtMidi.h" GuiKeyboardSetupDialog::GuiKeyboardSetupDialog(QWidget *parent) : QDialog(parent) { m_song = 0; setupUi(this); setWindowTitle(tr("Piano Keyboard Settings")); } void GuiKeyboardSetupDialog::init(CSong* song, CSettings* settings) { m_song = song; m_settings = settings; // Check inputs. QString programName; int i; i = 0; while (true) { programName = CTrackList::getProgramName(i); if (programName.isEmpty()) break; rightSoundCombo->addItem(programName); wrongSoundCombo->addItem(programName); i++; } int program = m_settings->value("Keyboard/RightSound", Cfg::defaultRightPatch()).toInt(); rightSoundCombo->setCurrentIndex(program); program = m_settings->value("Keyboard/WrongSound", Cfg::defaultWrongPatch()).toInt(); wrongSoundCombo->setCurrentIndex(program); int lowestNote = m_settings->value("Keyboard/LowestNote", "0").toInt(); int highestNote = m_settings->value("Keyboard/HighestNote", "127").toInt(); QString midiInputName = m_settings->value("Midi/I/nput").toString(); if (midiInputName.startsWith("None", Qt::CaseInsensitive)) { lowestNote = PC_KEY_LOWEST_NOTE; highestNote = PC_KEY_HIGHEST_NOTE; lowestNoteEdit->setEnabled(false); highestNoteEdit->setEnabled(false); resetButton->setEnabled(false); } lowestNoteEdit->setText(QString().setNum(lowestNote)); highestNoteEdit->setText(QString().setNum(highestNote)); updateInfoText(); rightVolumeLabel->hide(); // fixme Hide for now rightVolumeSpin->hide(); wrongVolumeLabel->hide(); wrongVolumeSpin->hide(); } void GuiKeyboardSetupDialog::updateInfoText() { QString str; keyboardInfoText->clear(); int lowestNote = lowestNoteEdit->text().toInt(); int highestNote = highestNoteEdit->text().toInt(); lowestNote = qBound(0, lowestNote, 127); highestNote = qBound(0, highestNote, 127); lowestNoteEdit->setText(QString().setNum(lowestNote)); highestNoteEdit->setText(QString().setNum(highestNote)); int noteRange = highestNote - lowestNote; keyboardInfoText->append("Choose the right and wrong sound for your playing."); if (!lowestNoteEdit->isEnabled()) str.sprintf("You can use the PC keyboard instead of a MIDI keyboard; 'x' is middle C."); else if (noteRange > 0) str.sprintf("Your keyboard range is octaves %d and semitones %d; 60 is middle C.", noteRange/MIDI_OCTAVE, noteRange%MIDI_OCTAVE); else str.sprintf("Oops, you have 0 notes on your keyboard!"); keyboardInfoText->append(str); } void GuiKeyboardSetupDialog::keyPressEvent ( QKeyEvent * event ) { if (event->text().length() == 0) return; if (event->isAutoRepeat() == true) return; int c = event->text().toAscii().at(0); m_song->pcKeyPress( c, true); } void GuiKeyboardSetupDialog::keyReleaseEvent ( QKeyEvent * event ) { if (event->isAutoRepeat() == true) return; if (event->text().length() == 0) return; int c = event->text().toAscii().at(0); m_song->pcKeyPress( c, false); } void GuiKeyboardSetupDialog::accept() { m_settings->setValue("Keyboard/RightSound", rightSoundCombo->currentIndex()); m_settings->setValue("Keyboard/WrongSound", wrongSoundCombo->currentIndex()); m_settings->setValue("Keyboard/RightSoundPrevious", rightSoundCombo->currentIndex()); int lowestNote = lowestNoteEdit->text().toInt(); int highestNote = highestNoteEdit->text().toInt(); lowestNote = qBound(0, lowestNote, 127); highestNote = qBound(0, highestNote, 127); CChord::setPianoRange(lowestNote, highestNote); if (lowestNoteEdit->isEnabled()) { m_settings->setValue("Keyboard/LowestNote", lowestNote); m_settings->setValue("Keyboard/HighestNote", highestNote); } m_song->testWrongNoteSound(false); m_song->regenerateChordQueue(); this->QDialog::accept(); } void GuiKeyboardSetupDialog::reject() { m_song->testWrongNoteSound(false); m_song->setPianoSoundPatches(m_settings->value("Keyboard/RightSound", Cfg::defaultRightPatch()).toInt() - 1, m_settings->value("Keyboard/WrongSound", Cfg::defaultWrongPatch()).toInt() - 1, true); this->QDialog::reject(); } pianobooster-src-0.6.4/src/GuiHighScoreWindow.ui0000644000175000017500000000255011304222711020713 0ustar louislouis GuiPreferences 0 0 578 399 Form High Scores Your Name: Qt::Horizontal 40 20 pianobooster-src-0.6.4/src/GlView.h0000644000175000017500000000466111304222711016217 0ustar louislouis/*********************************************************************************/ /*! @file GlView.h @brief xxx @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __GLVIEW_H__ #define __GLVIEW_H__ #include #include #include #include "Song.h" #include "Score.h" #include "Settings.h" //#include "rtmidi/RtTimer.h" class Window; class CGLView : public QGLWidget//, RtTimer { Q_OBJECT public: CGLView(QtWindow *parent, CSettings* settings); ~CGLView(); QSize minimumSizeHint() const; QSize sizeHint() const; CSong* getSongObject() {return m_song;} CScore* getScoreObject() {return m_score;} void init(); bool m_cfg_openGlOptimise; protected: void timerEvent(QTimerEvent *event); void mediaTimerEvent(int ticks); void initializeGL(); void paintGL(); void resizeGL(int width, int height); void mousePressEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); private: void drawDisplayText(); void drawTimeSignature(); void drawAccurracyBar(); void drawBarNumber(); void updateMidiTask(); QColor m_backgroundColour; QtWindow* m_qtWindow; // The parent Window CSettings* m_settings; CSong* m_song; CScore* m_score; QBasicTimer m_timer; QTime m_realtime; int m_displayUpdateTicks; CRating* m_rating; QFont m_timeSigFont; QFont m_timeRatingFont; bool m_fullRedrawFlag; int m_forcefullRedraw; int m_forceRatingRedraw; int m_forceBarRedraw; int m_titleHeight; eventBits_t m_eventBits; }; #endif // __GLVIEW_H__ pianobooster-src-0.6.4/src/GlView.cpp0000644000175000017500000002614711304222711016555 0ustar louislouis/*********************************************************************************/ /*! @file GlView.cpp @brief xxxx @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include #include #include #include "QtWindow.h" #include "GlView.h" #include "Cfg.h" #include "Draw.h" // This defines the PB Open GL frame per seconds. // Try to make sure this runs a bit faster than the screen refresh rate of 60z (or 16.6 msec) #define SCREEN_FRAME_RATE 12 // That 12 msec or 83.3 frames per second CGLView::CGLView(QtWindow* parent, CSettings* settings) : QGLWidget(parent) { m_qtWindow = parent; m_settings = settings; m_rating = 0; m_fullRedrawFlag = true; m_forcefullRedraw = 0; m_forceRatingRedraw = 0; m_forceBarRedraw = 0; m_backgroundColour = QColor(0, 0, 0); m_song = new CSong(); m_score = new CScore(m_settings); m_displayUpdateTicks = 0; m_cfg_openGlOptimise = true; m_eventBits = 0; BENCHMARK_INIT(); } CGLView::~CGLView() { makeCurrent(); delete m_song; delete m_score; m_titleHeight = 0; } QSize CGLView::minimumSizeHint() const { return QSize(50, 50); } QSize CGLView::sizeHint() const { return QSize(200, 400); //fixme this does not work } void CGLView::initializeGL() { qglClearColor(m_backgroundColour.dark()); } void CGLView::paintGL() { BENCHMARK(2, "enter"); m_displayUpdateTicks = 0; if (m_fullRedrawFlag) m_forcefullRedraw = m_forceRatingRedraw = m_forceBarRedraw = REDRAW_COUNT; if (m_forcefullRedraw) // clear the screen only if we are doing a full redraw glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); //BENCHMARK(3, "glLoadIdentity"); drawDisplayText(); BENCHMARK(4, "drawDisplayText"); drawAccurracyBar(); BENCHMARK(5, "drawAccurracyBar"); drawBarNumber(); BENCHMARK(6, "drawBarNumber"); if (m_forcefullRedraw) m_score->drawScore(); drawTimeSignature(); updateMidiTask(); m_score->drawScroll(m_forcefullRedraw); BENCHMARK(10, "drawScroll"); if (m_forcefullRedraw) m_forcefullRedraw--; BENCHMARK(11, "exit"); BENCHMARK_RESULTS(); } void CGLView::drawTimeSignature() { if (Cfg::quickStart) return; if (m_forcefullRedraw == 0) return; float x,y; int topNumber, bottomNumber; if (m_song == 0) return; m_song->getTimeSig(&topNumber, &bottomNumber); if (topNumber == 0 ) return; char bufferTop[10], bufferBottom[10]; sprintf(bufferTop, "%d", topNumber); sprintf(bufferBottom, "%d", bottomNumber); x = Cfg::timeSignatureX(); CDraw::drColour ((CDraw::getDisplayHand() != PB_PART_left) ? Cfg::noteColour() : Cfg::noteColourDim()); y = CStavePos(PB_PART_right, 0).getPosY() + 5; renderText(x,y, 0, bufferTop, m_timeSigFont); y = CStavePos(PB_PART_right, -3).getPosY() - 2; renderText(x,y, 0, bufferBottom, m_timeSigFont); CDraw::drColour ((CDraw::getDisplayHand() != PB_PART_right) ? Cfg::noteColour() : Cfg::noteColourDim()); y = CStavePos(PB_PART_left, 0).getPosY() + 5; renderText(x,y, 0, bufferTop, m_timeSigFont); y = CStavePos(PB_PART_left, -3).getPosY() - 2; renderText(x,y, 0, bufferBottom, m_timeSigFont); } void CGLView::drawAccurracyBar() { if (m_song->getPlayMode() == PB_PLAY_MODE_listen || !m_settings->getWarningMessage().isEmpty()) return; if (m_forceRatingRedraw == 0) return; m_forceRatingRedraw--; float accuracy; CColour colour; float y = Cfg::getAppHeight() - 14; const float x = 120; const int width = 360; const int lineWidth = 8/2; m_rating->calculateAccuracy(); accuracy = m_rating->getAccuracyValue(); colour = m_rating->getAccuracyColour(); CDraw::drColour (colour); glRectf(x, y - lineWidth, x + width * accuracy, y + lineWidth); CDraw::drColour (Cfg::backgroundColour()); glRectf(x + width * accuracy, y - lineWidth, x + width, y + lineWidth); glLineWidth (1); CDraw::drColour (CColour(1.0, 1.0, 1.0)); glBegin(GL_LINE_LOOP); glVertex2f (x, y + lineWidth); glVertex2f (x+ width, y + lineWidth); glVertex2f (x + width, y - lineWidth); glVertex2f (x, y - lineWidth); glEnd(); } void CGLView::drawDisplayText() { if (m_rating == 0) { m_rating = m_song->getRating(); return; // don't run this func the first time it is called } if (Cfg::quickStart) return; if (m_forcefullRedraw == 0) return; int y = Cfg::getAppHeight() - 14; if (!m_settings->getWarningMessage().isEmpty()) { glColor3f(1.0,0.0,0.0); renderText(30, y-4, 0, m_settings->getWarningMessage(), m_timeRatingFont); return; } glColor3f(1.0,1.0,1.0); if (m_song->getPlayMode() != PB_PLAY_MODE_listen) renderText(30, y-4,0 ,"Accuracy:", m_timeRatingFont); if (m_titleHeight < 45 ) return; y = Cfg::getAppHeight() - m_titleHeight; renderText(30, y+6, 0,"Song: " + m_song->getSongTitle(), m_timeRatingFont); /* char buffer[100]; sprintf(buffer, "Notes %d wrong %d Late %d Score %4.1f%%", m_rating->totalNoteCount(), m_rating->wrongNoteCount(), m_rating->lateNoteCount(), m_rating->rating()); renderText(10,20, buffer, m_timeRatingFont); */ } void CGLView::drawBarNumber() { if (m_forceBarRedraw == 0 || Cfg::quickStart) return; m_forceBarRedraw--; float y = Cfg::getAppHeight() - m_titleHeight - 34; float x = 30; //CDraw::drColour (Cfg::backgroundColour()); //CDraw::drColour (Cfg::noteColourDim()); //glRectf(x+30+10, y-2, x + 80, y + 16); glColor3f(1.0,1.0,1.0); renderText(x, y, 0,"Bar: " + QString::number(m_song->getBarNumber()), m_timeRatingFont); } void CGLView::resizeGL(int width, int height) { const int maxSoreWidth = 1024; const int staveEndGap = 20; const int heightAboveStave = static_cast(CStavePos::verticalNoteSpacing() * MAX_STAVE_INDEX); const int heightBelowStave = static_cast(CStavePos::verticalNoteSpacing() * - MIN_STAVE_INDEX); const int minTitleHeight = 20; const int minStaveGap = 120; int staveGap; int maxSoreHeight; int space = height - (heightAboveStave + heightBelowStave + minTitleHeight + minStaveGap); //m_titleHeight = qBound(minTitleHeight, minTitleHeight + space/2, 70); // staveGap = qBound(minStaveGap, minStaveGap+ space/2, static_cast(CStavePos::staveHeight() * 3)); if (height < 450) // So it works on an eeepc 701 (for Trev) { staveGap = minStaveGap; m_titleHeight = minTitleHeight; } else { staveGap = static_cast(CStavePos::staveHeight() * 3); m_titleHeight = 60; } maxSoreHeight = heightAboveStave + heightBelowStave + staveGap + m_titleHeight; int sizeX = qMin(width, maxSoreWidth); int sizeY = qMin(height, maxSoreHeight); int x = (width - sizeX)/2; int y = (height - sizeY)/2; y = (height - sizeY) - 5; x = 0; glViewport (x, y, sizeX, sizeY); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, sizeX, 0, sizeY, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); CStavePos::setStaveCenterY(sizeY - maxSoreHeight/2 - m_titleHeight/2); Cfg::setAppDimentions(x, y, sizeX, sizeY); Cfg::setStaveEndX(sizeX - staveEndGap); CStavePos::setStaveCentralOffset(staveGap/2); CDraw::forceCompileRedraw(); } void CGLView::mousePressEvent(QMouseEvent *event) { } void CGLView::mouseMoveEvent(QMouseEvent *event) { } void CGLView::init() { CColour colour = Cfg::backgroundColour(); glClearColor (colour.red, colour.green, colour.blue, 0.0); glPixelStorei (GL_UNPACK_ALIGNMENT, 1); glShadeModel (GL_FLAT); //glEnable(GL_TEXTURE_2D); // Enable Texture Mapping //from initCheck(); glShadeModel(GL_FLAT); //glEnable(GL_DEPTH_TEST); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); //glGenTextures(1, &texName); //glBindTexture(GL_TEXTURE_2D, texName); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); //enableAntialiasedLines(); m_timeSigFont = QFont("Arial", 22 ); m_timeRatingFont = QFont("Arial", 12 ); Cfg::setStaveEndX(400); //This value get changed by the resizeGL func m_song->setActiveHand(PB_PART_both); if (!Cfg::quickStart) { renderText(10,10,QString("~"), m_timeRatingFont); //fixme this is a work around for a QT bug. renderText(10,10,QString("~"), m_timeSigFont); //this is a work around for a QT bug. } setFocusPolicy(Qt::ClickFocus); // increased the tick time for Midi handling m_timer.start(4, this ); // was 12 m_realtime.start(); //startMediaTimer(12, this ); } void CGLView::updateMidiTask() { int ticks; ticks = m_realtime.restart(); m_displayUpdateTicks += ticks; m_eventBits |= m_song->task(ticks); } void CGLView::timerEvent(QTimerEvent *event) { BENCHMARK(0, "timer enter"); if (event->timerId() != m_timer.timerId()) { QWidget::timerEvent(event); return; } updateMidiTask(); BENCHMARK(1, "m_song task"); if (m_displayUpdateTicks < SCREEN_FRAME_RATE) return; m_displayUpdateTicks = 0; if (m_eventBits != 0) { if ((m_eventBits & EVENT_BITS_UptoBarReached) != 0) m_song->playFromStartBar(); if ((m_eventBits & EVENT_BITS_forceFullRedraw) != 0) m_forcefullRedraw = m_forceRatingRedraw = m_forceBarRedraw = REDRAW_COUNT; if ((m_eventBits & EVENT_BITS_forceRatingRedraw) != 0) m_forceRatingRedraw = REDRAW_COUNT; if ((m_eventBits & EVENT_BITS_newBarNumber) != 0) m_forcefullRedraw = m_forceRatingRedraw = m_forceBarRedraw = REDRAW_COUNT; // fixme this did not work so redraw everything m_qtWindow->songEventUpdated(m_eventBits); m_eventBits = 0; } if(m_cfg_openGlOptimise) m_fullRedrawFlag = false; else m_fullRedrawFlag = true; glDraw(); //update(); m_fullRedrawFlag = true; BENCHMARK(19, "timer exit"); } void CGLView::mediaTimerEvent(int ticks) { } pianobooster-src-0.6.4/src/Draw.h0000644000175000017500000000647611304222711015725 0ustar louislouis/*********************************************************************************/ /*! @file Draw.h @brief . @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __DRAW_H__ #define __DRAW_H__ #ifdef __APPLE__ #include #include #else #include #include #endif #define HORIZONTAL_SPACING_FACTOR (0.75) // defines the speed of the scrolling #include "StavePosition.h" #include "Symbol.h" #define REDRAW_COUNT 1 // there are two gl buffers but redrawing once is best (set 2 with buggy gl drivers) class CSettings; class CScrollProperties { public: CScrollProperties() { m_horizontal = false; } bool horizontal() { return m_horizontal; } private: bool m_horizontal; }; class CDraw { public: CDraw(CSettings* settings) { m_settings = settings; m_displayHand = PB_PART_both; m_forceCompileRedraw = 1; m_scrollProperties = &m_scrollPropertiesHorizontal; } void scrollVertex(float x, float y) { if (m_scrollProperties->horizontal()) glVertex2f (x,y); else glVertex2f (y,x); } void drawSymbol(CSymbol symbol, float x, float y); void drawSymbol(CSymbol symbol, float x); static void setDisplayHand(whichPart_t hand) { m_displayHand = hand; m_forceCompileRedraw = 1; } static whichPart_t getDisplayHand() {return m_displayHand;} static void drColour(CColour colour) { glColor3f(colour.red, colour.green, colour.blue);} static void forceCompileRedraw(int value = 1) { m_forceCompileRedraw = value; } protected: static whichPart_t m_displayHand; static int getCompileRedrawCount() { return m_forceCompileRedraw; } void oneLine(float x1, float y1, float x2, float y2); void drawStaves(float startX, float endX); void drawKeySignature(int key); void drawNoteName(int midiNote, float x, float y, int type); CSettings* m_settings; private: void drawStaveNoteName(CSymbol symbol, float x, float y); void checkAccidental(CSymbol symbol, float x, float y); void drawStaveExtentsion(CSymbol symbol, float x, int noteWidth, bool playable); static int m_forceCompileRedraw; const static int m_beatMarkerHeight = 10; // The height of the beat markers in the stave positions CScrollProperties *m_scrollProperties; CScrollProperties m_scrollPropertiesHorizontal; CScrollProperties m_scrollPropertiesVertical; }; #endif //__DRAW_H__ pianobooster-src-0.6.4/src/Draw.cpp0000644000175000017500000006240211304222711016247 0ustar louislouis/*********************************************************************************/ /*! @file Draw.cpp @brief xxxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include "Draw.h" #include "Cfg.h" #include "Settings.h" typedef unsigned int guint; typedef unsigned char guint8; whichPart_t CDraw::m_displayHand; int CDraw::m_forceCompileRedraw; void CDraw::oneLine(float x1, float y1, float x2, float y2) { glBegin(GL_LINES); glVertex2f ((x1),(y1)); glVertex2f ((x2),(y2)); glEnd(); //ppLogTrace("oneLine %f %f %f %f", x1, y1, x2, y2); } void CDraw::drawStaveExtentsion(CSymbol symbol, float x, int noteWidth, bool playable) { int index; index = symbol.getStavePos().getStaveIndex(); if (index < 6 && index > -6) return; index = index & ~1; // Force index to be even whichPart_t hand = symbol.getStavePos().getHand(); if (playable) drColour(Cfg::staveColour()); else drColour(Cfg::staveColourDim()); glLineWidth (Cfg::staveThickness()); glBegin(GL_LINES); while (index >= 6 || index <= -6) { glVertex2f (x - noteWidth/2 - 4, CStavePos(hand, index).getPosYRelative()); glVertex2f (x + noteWidth/2 + 4, CStavePos(hand, index).getPosYRelative()); // Move the index closer to the stave centre if (index > 0) index -= 2; else index += 2; } glEnd(); } #define scaleGlVertex(xa, xb, ya, yb) glVertex2f( ((xa) * 1.2) + (xb), ((ya) * 1.2) + (yb)) void CDraw::drawNoteName(int midiNote, float x, float y, int type) { // Ignore note that are too high if (midiNote > MIDI_TOP_C + 6) return; staveLookup_t item = CStavePos::midiNote2Name(midiNote); drColour(Cfg::noteNameColour()); glLineWidth (1.0); if (item.accidental != 0) { const float accidentalOffset = 10; x += accidentalOffset/2; if (item.accidental == 1) { glBegin(GL_LINES); // letterSharp4 scaleGlVertex( -1.317895, x, 5.794585, y); // 1 scaleGlVertex( -1.265845, x, -6.492455, y); // 2 scaleGlVertex( 1.252305, x, 6.492455, y); // 3 scaleGlVertex( 1.322655, x, -5.422335, y); // 4 scaleGlVertex( -2.645765, x, 1.967805, y); // 5 scaleGlVertex( 2.648325, x, 3.625485, y); // 6 scaleGlVertex( -2.648325, x, -3.306965, y); // 7 scaleGlVertex( 2.596205, x, -1.675765, y); // 8 glEnd(); } else { glBegin(GL_LINE_STRIP); // letterFlat scaleGlVertex( -2.52933, x, 6.25291, y); // 1 scaleGlVertex( -2.50344, x, -6.25291, y); // 2 scaleGlVertex( 0.76991, x, -3.63422, y); // 3 scaleGlVertex( 2.07925, x, -1.67021, y); // 4 scaleGlVertex( 2.52933, x, 0.25288, y); // 5 scaleGlVertex( 1.42458, x, 1.07122, y); // 6 scaleGlVertex( -0.53943, x, 0.90755, y); // 7 scaleGlVertex( -2.46252, x, -1.01554, y); // 8 scaleGlVertex( -2.50344, x, -1.67021, y); // 9 glEnd(); } x -= accidentalOffset; } switch(item.pianoNote) { case 1: glBegin(GL_LINE_STRIP); // letterC scaleGlVertex( 3.513445, x, 2.17485, y); // 1 scaleGlVertex( 1.880175, x, 4.47041, y); // 2 scaleGlVertex( -1.598825, x, 4.4321, y); // 3 scaleGlVertex( -3.692215, x, 2.26571, y); // 4 scaleGlVertex( -3.702055, x, -1.88958, y); // 5 scaleGlVertex( -1.630675, x, -4.47041, y); // 6 scaleGlVertex( 1.932545, x, -4.44064, y); // 7 scaleGlVertex( 3.702055, x, -1.88554, y); // 8 glEnd(); break; case 2: glBegin(GL_LINE_STRIP); // letterD scaleGlVertex( -3.30696, x, 4.31878, y); // 1 scaleGlVertex( -3.3428, x, -4.31878, y); // 2 scaleGlVertex( 0.9425, x, -4.28164, y); // 3 scaleGlVertex( 3.31415, x, -1.42302, y); // 4 scaleGlVertex( 3.3428, x, 1.66626, y); // 5 scaleGlVertex( 0.70825, x, 4.31317, y); // 6 scaleGlVertex( -3.22083, x, 4.29495, y); // 7 glEnd(); break; case 3: // E glBegin(GL_LINE_STRIP); // letterE2 scaleGlVertex( 2.966065, x, 4.416055, y); // 1 scaleGlVertex( -3.007275, x, 4.403495, y); // 2 scaleGlVertex( -3.037615, x, -4.416055, y); // 3 scaleGlVertex( 3.037615, x, -4.415435, y); // 4 glEnd(); glBegin(GL_LINES); scaleGlVertex( 3.011705, x, 0.197675, y); // 5 scaleGlVertex( -2.990845, x, 0.196615, y); // 6 glEnd(); break; case 4: // F glBegin(GL_LINE_STRIP); // letterF2 scaleGlVertex( -2.55172, x, -4.434285, y); // 1 scaleGlVertex( -2.51956, x, 4.433665, y); // 2 scaleGlVertex( 2.39942, x, 4.434285, y); // 3 glEnd(); glBegin(GL_LINES); scaleGlVertex( 2.58143, x, 0.244465, y); // 4 scaleGlVertex( -2.58143, x, 0.243405, y); // 5 glEnd(); break; case 5: glBegin(GL_LINE_STRIP); // letterG scaleGlVertex( 0.58123, x, -0.34005, y); // 1 scaleGlVertex( 3.66047, x, -0.48722, y); // 2 scaleGlVertex( 3.70461, x, -3.23595, y); // 3 scaleGlVertex( 1.96234, x, -4.41694, y); // 4 scaleGlVertex( -0.96712, x, -4.57846, y); // 5 scaleGlVertex( -3.70461, x, -2.29011, y); // 6 scaleGlVertex( -3.67245, x, 2.14034, y); // 7 scaleGlVertex( -1.25347, x, 4.57846, y); // 8 scaleGlVertex( 1.90018, x, 4.55293, y); // 9 scaleGlVertex( 3.54236, x, 2.38612, y); // 10 glEnd(); break; case 6: // A glBegin(GL_LINE_STRIP); // letterA2 scaleGlVertex( -3.91146, x, -4.907395, y); // 1 scaleGlVertex( 0.06571, x, 4.907395, y); // 2 scaleGlVertex( 3.91146, x, -4.803315, y); // 3 glEnd(); glBegin(GL_LINES); scaleGlVertex( 2.60111, x, -1.400435, y); // 4 scaleGlVertex( -2.56175, x, -1.357305, y); // 5 glEnd(); break; case 7: glBegin(GL_LINE_STRIP); // letterB scaleGlVertex( 1.038555, x, 0.105285, y); // 1 scaleGlVertex( -3.001935, x, 0.121925, y); // 2 scaleGlVertex( -3.027615, x, 4.417905, y); // 3 scaleGlVertex( 1.325925, x, 4.451255, y); // 4 scaleGlVertex( 2.737985, x, 3.048615, y); // 5 scaleGlVertex( 2.721765, x, 1.366235, y); // 6 scaleGlVertex( 1.022635, x, 0.120235, y); // 7 scaleGlVertex( 3.026015, x, -1.282295, y); // 8 scaleGlVertex( 3.027615, x, -3.046285, y); // 9 scaleGlVertex( 1.176815, x, -4.451255, y); // 10 scaleGlVertex( -2.981475, x, -4.445735, y); // 11 scaleGlVertex( -3.021355, x, 0.176035, y); // 12 glEnd(); break; default: glBegin(GL_LINES); glVertex2f( 3 + x, -15 + y); // 1 glVertex2f( 3 + x, 8 + y); // 2 glVertex2f( -3 + x, -8 + y); // 3 glVertex2f( -3 + x, 15 + y); // 4 glVertex2f( 3 + x, 8 + y); // 5 glVertex2f( -3 + x, 2 + y); // 6 glVertex2f( 3 + x, -2 + y); // 7 glVertex2f( -3 + x, -8 + y); // 8 glEnd(); break; } } void CDraw::drawStaveNoteName(CSymbol symbol, float x, float y) { if ( symbol.getNoteIndex() + 1 != symbol.getNoteTotal()) return; if (m_settings->showNoteNames() == false) return; y += CStavePos::getVerticalNoteSpacing()*2 +3; drawNoteName(symbol.getNote(), x, y, true); } void CDraw::checkAccidental(CSymbol symbol, float x, float y) { int accidental; const int xGap = 16; accidental = symbol.getStavePos().getAccidental(); if (symbol.getAccidentalModifer() == PB_ACCIDENTAL_MODIFER_suppress) accidental = 0; // Suppress the accidental if it is the same bar if (symbol.getAccidentalModifer() == PB_ACCIDENTAL_MODIFER_force) { // Force the display of an accidental including naturals if it is the same bar accidental = CStavePos::midiNote2Name(symbol.getNote()).accidental; if (accidental == 0) accidental = 2; } if (accidental != 0) { //drColour (Cfg::lineColour()); if (accidental == 1) drawSymbol(CSymbol(PB_SYMBOL_sharp, symbol.getStavePos()), x - xGap, y); else if (accidental == -1) drawSymbol(CSymbol(PB_SYMBOL_flat, symbol.getStavePos()), x - xGap, y); else drawSymbol(CSymbol(PB_SYMBOL_natural, symbol.getStavePos()), x - xGap, y); } } void CDraw::drawSymbol(CSymbol symbol, float x, float y) { CColour colour = symbol.getColour(); bool playable = true; if (m_displayHand != symbol.getHand() && m_displayHand != PB_PART_both) { if (colour == Cfg::noteColour()) colour = Cfg::noteColourDim(); if (colour == Cfg::staveColour()) colour = Cfg::staveColourDim(); playable = false; } switch (symbol.getType()) { case PB_SYMBOL_gClef: // The Treble Clef y += 4; drColour(colour); glLineWidth (3.0); glBegin(GL_LINE_STRIP); glVertex2f( -0.011922 + x, -16.11494 + y); // 1 glVertex2f( -3.761922 + x, -12.48994 + y); // 2 glVertex2f( -4.859633 + x, -8.85196 + y); // 3 glVertex2f( -4.783288 + x, -5.42815 + y); // 4 glVertex2f( -0.606711 + x, -1.11108 + y); // 5 glVertex2f( 5.355545 + x, 0.48711 + y); // 6 glVertex2f( 10.641104 + x, -1.6473 + y); // 7 glVertex2f( 14.293812 + x, -6.18241 + y); // 8 glVertex2f( 14.675578 + x, -11.42744 + y); // 9 glVertex2f( 12.550578 + x, -17.30244 + y); // 10 glVertex2f( 7.912166 + x, -20.944 + y); // 11 glVertex2f( 3.049705 + x, -21.65755 + y); // 12 glVertex2f( -1.711005 + x, -21.36664 + y); // 13 glVertex2f( -6.283661 + x, -19.66739 + y); // 14 glVertex2f( -10.123329 + x, -16.79162 + y); // 15 glVertex2f( -13.363008 + x, -12.28184 + y); // 16 glVertex2f( -14.675578 + x, -5.79969 + y); // 17 glVertex2f( -13.66821 + x, 0.20179 + y); // 18 glVertex2f( -10.385341 + x, 6.27562 + y); // 19 glVertex2f( 5.539491 + x, 20.32671 + y); // 20 glVertex2f( 10.431588 + x, 28.20584 + y); // 21 glVertex2f( 11.00141 + x, 34.71585 + y); // 22 glVertex2f( 9.204915 + x, 39.62875 + y); // 23 glVertex2f( 7.854166 + x, 42.08262 + y); // 24 glVertex2f( 5.481415 + x, 42.66649 + y); // 25 glVertex2f( 3.57972 + x, 41.4147 + y); // 26 glVertex2f( 1.507889 + x, 37.35642 + y); // 27 glVertex2f( -0.381338 + x, 31.14317 + y); // 28 glVertex2f( -0.664306 + x, 25.51354 + y); // 29 glVertex2f( 8.296044 + x, -32.22694 + y); // 30 glVertex2f( 8.050507 + x, -36.6687 + y); // 31 glVertex2f( 6.496615 + x, -39.52999 + y); // 32 glVertex2f( 3.368583 + x, -41.7968 + y); // 33 glVertex2f( 0.253766 + x, -42.66649 + y); // 34 glVertex2f( -3.599633 + x, -42.23514 + y); // 35 glVertex2f( -8.098754 + x, -39.46637 + y); // 36 glVertex2f( -9.463279 + x, -35.49796 + y); // 37 glVertex2f( -7.08037 + x, -31.36512 + y); // 38 glVertex2f( -3.336421 + x, -31.14057 + y); // 39 glVertex2f( -1.360313 + x, -34.07738 + y); // 40 glVertex2f( -1.608342 + x, -37.11828 + y); // 41 glVertex2f( -5.729949 + x, -39.24759 + y); // 42 glVertex2f( -7.480646 + x, -36.2136 + y); // 43 glVertex2f( -6.826918 + x, -33.36919 + y); // 44 glVertex2f( -4.069083 + x, -32.9226 + y); // 45 glVertex2f( -3.040669 + x, -34.433 + y); // 46 glVertex2f( -3.737535 + x, -36.38759 + y); // 47 glVertex2f( -5.496558 + x, -36.97633 + y); // 48 glVertex2f( -5.295932 + x, -34.01951 + y); // 49 glEnd(); break; case PB_SYMBOL_fClef: // The Base Clef drColour(colour); glLineWidth (3.0); glBegin(GL_LINE_STRIP); glVertex2f( -15.370325 + x, -17.42068 + y); // 1 glVertex2f( -7.171025 + x, -13.75432 + y); // 2 glVertex2f( -2.867225 + x, -10.66642 + y); // 3 glVertex2f( 0.925165 + x, -7.03249 + y); // 4 glVertex2f( 4.254425 + x, -0.65527 + y); // 5 glVertex2f( 4.762735 + x, 7.77848 + y); // 6 glVertex2f( 2.693395 + x, 13.92227 + y); // 7 glVertex2f( -1.207935 + x, 16.80317 + y); // 8 glVertex2f( -5.526425 + x, 17.42068 + y); // 9 glVertex2f( -10.228205 + x, 15.65609 + y); // 10 glVertex2f( -13.453995 + x, 10.7128 + y); // 11 glVertex2f( -13.133655 + x, 5.43731 + y); // 12 glVertex2f( -9.475575 + x, 3.00714 + y); // 13 glVertex2f( -5.846445 + x, 4.72159 + y); // 14 glVertex2f( -5.395545 + x, 9.72918 + y); // 15 glVertex2f( -8.850025 + x, 11.64372 + y); // 16 glVertex2f( -11.519385 + x, 10.35816 + y); // 17 glVertex2f( -11.706365 + x, 6.8704 + y); // 18 glVertex2f( -9.463505 + x, 5.01391 + y); // 19 glVertex2f( -7.172075 + x, 5.81649 + y); // 20 glVertex2f( -7.189565 + x, 8.62975 + y); // 21 glVertex2f( -9.175055 + x, 9.82019 + y); // 22 glVertex2f( -10.696425 + x, 8.08395 + y); // 23 glVertex2f( -8.843065 + x, 6.66726 + y); // 24 glVertex2f( -8.995775 + x, 8.71136 + y); // 25 glEnd(); glBegin(GL_POLYGON); glVertex2f( 10 + x, 14 + y); // 26 glVertex2f( 14 + x, 14 + y); // 27 glVertex2f( 14 + x, 10 + y); // 28 glVertex2f( 10 + x, 10 + y); // 29 glVertex2f( 10 + x, 14 + y); // 30 glEnd(); glBegin(GL_POLYGON); glVertex2f( 10 + x, 4 + y); // 31 glVertex2f( 14 + x, 4 + y); // 32 glVertex2f( 14 + x, 0 + y); // 33 glVertex2f( 10 + x, 0 + y); // 34 glVertex2f( 10 + x, 4 + y); // 35 glEnd(); break; case PB_SYMBOL_note: //ppLogTrace("PB_SYMBOL_note x %f y %f", x, y); if (!CChord::isNotePlayable(symbol.getNote(), 0)) { colour = Cfg::noteColourDim(); playable = false; } drawStaveExtentsion(symbol, x, 16, playable); drColour(colour); glBegin(GL_POLYGON); glVertex2f(-7.0 + x, 2.0 + y); // 1 glVertex2f(-5.0 + x, 4.0 + y); // 2 glVertex2f(-1.0 + x, 6.0 + y); // 3 glVertex2f( 4.0 + x, 6.0 + y); // 4 glVertex2f( 7.0 + x, 4.0 + y); // 5 glVertex2f( 7.0 + x, 1.0 + y); // 6 glVertex2f( 6.0 + x, -2.0 + y); // 7 glVertex2f( 4.0 + x, -4.0 + y); // 8 glVertex2f( 0.0 + x, -6.0 + y); // 9 glVertex2f(-4.0 + x, -6.0 + y); // 10 glVertex2f(-8.0 + x, -3.0 + y); // 11 glVertex2f(-8.0 + x, -0.0 + y); // 12 glEnd(); checkAccidental(symbol, x, y); break; case PB_SYMBOL_drum: if (!CChord::isNotePlayable(symbol.getNote(), 0)) colour = Cfg::noteColourDim(); drColour(colour); glLineWidth (3.0); glBegin(GL_LINES); glVertex2f( 5.0 + x,-5.0 + y); glVertex2f(-5.0 + x, 5.0 + y); glVertex2f(-5.0 + x,-5.0 + y); glVertex2f( 5.0 + x, 5.0 + y); glEnd(); checkAccidental(symbol, x, y); break; case PB_SYMBOL_sharp: glLineWidth (2.0); glBegin(GL_LINES); glVertex2f(-2.0 + x, -14.0 + y); glVertex2f(-2.0 + x, 14.0 + y); glVertex2f( 2.0 + x, -13.0 + y); glVertex2f( 2.0 + x, 15.0 + y); glVertex2f(-5.0 + x, 4.0 + y); glVertex2f( 5.0 + x, 7.0 + y); glVertex2f(-5.0 + x, -6.0 + y); glVertex2f( 5.0 + x, -3.0 + y); glEnd(); break; case PB_SYMBOL_flat: glLineWidth (2.0); glBegin(GL_LINE_STRIP); glVertex2f(-4.0 + x, 17.0 + y); // 1 glVertex2f(-4.0 + x, -6.0 + y); // 2 glVertex2f( 2.0 + x, -2.0 + y); // 3 glVertex2f( 5.0 + x, 2.0 + y); // 4 glVertex2f( 5.0 + x, 4.0 + y); // 5 glVertex2f( 3.0 + x, 5.0 + y); // 6 glVertex2f( 0.0 + x, 5.0 + y); // 7 glVertex2f(-4.0 + x, 2.0 + y); // 8 glEnd(); break; case PB_SYMBOL_natural: glLineWidth (2.0); glBegin(GL_LINES); glVertex2f( 3 + x, -15 + y); // 1 glVertex2f( 3 + x, 8 + y); // 2 glVertex2f( -3 + x, -8 + y); // 3 glVertex2f( -3 + x, 15 + y); // 4 glVertex2f( 3 + x, 8 + y); // 5 glVertex2f( -3 + x, 2 + y); // 6 glVertex2f( 3 + x, -2 + y); // 7 glVertex2f( -3 + x, -8 + y); // 8 glEnd(); break; case PB_SYMBOL_barLine: x += BEAT_MARKER_OFFSET * HORIZONTAL_SPACING_FACTOR; // the beat markers where entered early so now move them correctly glLineWidth (4.0); drColour ((m_displayHand == PB_PART_left) ? Cfg::staveColourDim() : Cfg::staveColour()); oneLine(x, CStavePos(PB_PART_right, 4).getPosYRelative(), x, CStavePos(PB_PART_right, -4).getPosYRelative()); drColour ((m_displayHand == PB_PART_right) ? Cfg::staveColourDim() : Cfg::staveColour()); oneLine(x, CStavePos(PB_PART_left, 4).getPosYRelative(), x, CStavePos(PB_PART_left, -4).getPosYRelative()); break; case PB_SYMBOL_barMarker: x += BEAT_MARKER_OFFSET * HORIZONTAL_SPACING_FACTOR; // the beat markers where entered early so now move them correctly glLineWidth (5.0); drColour(Cfg::barMarkerColour()); oneLine(x, CStavePos(PB_PART_right, m_beatMarkerHeight).getPosYRelative(), x, CStavePos(PB_PART_left, -m_beatMarkerHeight).getPosYRelative()); glDisable (GL_LINE_STIPPLE); break; case PB_SYMBOL_beatMarker: x += BEAT_MARKER_OFFSET * HORIZONTAL_SPACING_FACTOR; // the beat markers where entered early so now move them correctly glLineWidth (4.0); drColour(Cfg::beatMarkerColour()); oneLine(x, CStavePos(PB_PART_right, m_beatMarkerHeight).getPosYRelative(), x, CStavePos(PB_PART_left, -m_beatMarkerHeight).getPosYRelative()); glDisable (GL_LINE_STIPPLE); break; case PB_SYMBOL_playingZone: { float topY = CStavePos(PB_PART_right, m_beatMarkerHeight).getPosY(); float bottomY = CStavePos(PB_PART_left, -m_beatMarkerHeight).getPosY(); float early = Cfg::playZoneEarly() * HORIZONTAL_SPACING_FACTOR; float late = Cfg::playZoneLate() * HORIZONTAL_SPACING_FACTOR; //glColor3f (0.7, 1.0, 0.7); glColor3f (0.0, 0.0, 0.3); glRectf(x-late, topY, x + early, bottomY); glLineWidth (2.0); glColor3f (0.0, 0.0, 0.8); oneLine(x, topY, x, bottomY ); glLineWidth (1.0); glColor3f (0.0, 0.0, 0.6); oneLine(x-late, topY, x-late, bottomY ); oneLine(x+early, topY, x+early, bottomY ); } break; default: ppDEBUG(("ERROR drawSymbol unhandled symbol\n")); break; } if (symbol.getType() == PB_SYMBOL_note) { float pianistX = symbol.getPianistTiming(); if ( pianistX != NOT_USED) { pianistX = x + pianistX * HORIZONTAL_SPACING_FACTOR; drColour(CColour(1.0, 1.0, 1.0)); glLineWidth (2.0); glBegin(GL_LINES); glVertex2f( 4.0 + pianistX, 4.0 + y); glVertex2f(-5.0 + pianistX,-5.0 + y); glVertex2f( 4.0 + pianistX,-4.0 + y); // draw pianist note timing markers glVertex2f(-5.0 + pianistX, 5.0 + y); glEnd(); } if ( playable ) drawStaveNoteName(symbol, x, y); } } void CDraw::drawSymbol(CSymbol symbol, float x) { drawSymbol(symbol, x, symbol.getStavePos().getPosY()); } void CDraw::drawStaves(float startX, float endX) { int i; glLineWidth (Cfg::staveThickness()); /* select colour for all lines */ drColour ((m_displayHand != PB_PART_left) ? Cfg::staveColour() : Cfg::staveColourDim()); glBegin(GL_LINES); for (i = -4; i <= 4; i+=2 ) { CStavePos pos = CStavePos(PB_PART_right, i); glVertex2f (startX, pos.getPosY()); glVertex2f (endX, pos.getPosY()); } drColour ((m_displayHand != PB_PART_right) ? Cfg::staveColour() : Cfg::staveColourDim()); for (i = -4; i <= 4; i+=2 ) { CStavePos pos = CStavePos(PB_PART_left, i); glVertex2f (startX, pos.getPosY()); glVertex2f (endX, pos.getPosY()); } glEnd(); } void CDraw::drawKeySignature(int key) { const int sharpLookUpRight[] = { 4, 1, 5, 2,-1, 3, 0}; const int sharpLookUpLeft[] = { 2,-1, 3, 0,-3, 1,-2}; const int flatLookUpRight[] = { 0, 3,-1, 2,-2, 1,-3}; const int flatLookUpLeft[] = {-2, 1,-3, 0,-4,-1,-5}; const int gapX = 11; CStavePos pos; size_t i; if (key == NOT_USED) return; i = 0; while (key != 0 ) { if (key > 0) { if (i < arraySize(sharpLookUpRight)) { drColour ((m_displayHand != PB_PART_left) ? Cfg::noteColour() : Cfg::noteColourDim()); pos = CStavePos(PB_PART_right, sharpLookUpRight[i]); drawSymbol( CSymbol(PB_SYMBOL_sharp, pos), Cfg::keySignatureX() + gapX*i ); } if (i < arraySize(sharpLookUpLeft)) { drColour ((m_displayHand != PB_PART_right) ? Cfg::noteColour() : Cfg::noteColourDim()); pos = CStavePos(PB_PART_left, sharpLookUpLeft[i]); drawSymbol( CSymbol(PB_SYMBOL_sharp, pos), Cfg::keySignatureX() + gapX*i ); } key--; } else { if (i < arraySize(flatLookUpRight)) { drColour ((m_displayHand != PB_PART_left) ? Cfg::noteColour() : Cfg::noteColourDim()); pos = CStavePos(PB_PART_right, flatLookUpRight[i]); drawSymbol( CSymbol(PB_SYMBOL_flat, pos), Cfg::keySignatureX() + gapX*i ); } if (i < arraySize(flatLookUpLeft)) { drColour ((m_displayHand != PB_PART_right) ? Cfg::noteColour() : Cfg::noteColourDim()); pos = CStavePos(PB_PART_left, flatLookUpLeft[i]); drawSymbol( CSymbol(PB_SYMBOL_flat, pos), Cfg::keySignatureX() + gapX*i ); } key++; } i++; } } pianobooster-src-0.6.4/src/Doxyfile0000644000175000017500000016267611304222711016372 0ustar louislouis# Doxyfile 1.5.6 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project # # All text after a hash (#) is considered a comment and will be ignored # The format is: # TAG = value [value, ...] # For lists items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (" ") #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the config file # that follow. The default is UTF-8 which is also the encoding used for all # text before the first occurrence of this tag. Doxygen uses libiconv (or the # iconv built into libc) for the transcoding. See # http://www.gnu.org/software/libiconv for the list of possible encodings. DOXYFILE_ENCODING = UTF-8 # The PROJECT_NAME tag is a single word (or a sequence of words surrounded # by quotes) that should identify the project. PROJECT_NAME = Piano Booster # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. OUTPUT_DIRECTORY = DoxygenOutput # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create # 4096 sub-directories (in 2 levels) under the output directory of each output # format and will distribute the generated files over these directories. # Enabling this option can be useful when feeding doxygen a huge amount of # source files, where putting all generated files in the same directory would # otherwise cause performance problems for the file system. CREATE_SUBDIRS = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, # Croatian, Czech, Danish, Dutch, Farsi, Finnish, French, German, Greek, # Hungarian, Italian, Japanese, Japanese-en (Japanese with English messages), # Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, Polish, # Portuguese, Romanian, Russian, Serbian, Slovak, Slovene, Spanish, Swedish, # and Ukrainian. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator # that is used to form the text in various listings. Each string # in this list, if found as the leading text of the brief description, will be # stripped from the text and the result after processing the whole list, is # used as the annotated text. Otherwise, the brief description is used as-is. # If left blank, the following values are used ("$name" is automatically # replaced with the name of the entity): "The $name class" "The $name widget" # "The $name file" "is" "provides" "specifies" "contains" # "represents" "a" "an" "the" ABBREVIATE_BRIEF = # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = YES # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user-defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the # path to strip. STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of # the path mentioned in the documentation of a class, which tells # the reader which header file to include in order to use a class. # If left blank only the name of the header file containing the class # definition is used. Otherwise one should specify the include paths that # are normally passed to the compiler using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter # (but less readable) file names. This can be useful is your file systems # doesn't support long names like on DOS, Mac, or CD-ROM. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the JavaDoc # comments will behave just like regular Qt-style comments # (thus requiring an explicit @brief command for a brief description.) JAVADOC_AUTOBRIEF = NO # If the QT_AUTOBRIEF tag is set to YES then Doxygen will # interpret the first line (until the first dot) of a Qt-style # comment as the brief description. If set to NO, the comments # will behave just like regular Qt-style comments (thus requiring # an explicit \brief command for a brief description.) QT_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen # treat a multi-line C++ special comment block (i.e. a block of //! or /// # comments) as a brief description. This used to be the default behaviour. # The new default is to treat a multi-line C++ comment block as a detailed # description. Set this tag to YES if you prefer the old behaviour instead. MULTILINE_CPP_IS_BRIEF = NO # If the DETAILS_AT_TOP tag is set to YES then Doxygen # will output the detailed description near the top, like JavaDoc. # If set to NO, the detailed description appears after the member # documentation. DETAILS_AT_TOP = NO # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # re-implements. INHERIT_DOCS = YES # If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce # a new page for each member. If set to NO, the documentation of a member will # be part of the file/class/namespace that contains it. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 4 # This tag can be used to specify a number of aliases that acts # as commands in the documentation. An alias has the form "name=value". # For example adding "sideeffect=\par Side Effects:\n" will allow you to # put the command \sideeffect (or @sideeffect) in the documentation, which # will result in a user-defined paragraph with heading "Side Effects:". # You can put \n's in the value part of an alias to insert newlines. ALIASES = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C # sources only. Doxygen will then generate output that is more tailored for C. # For instance, some of the names that are used will be different. The list # of all members will be omitted, etc. OPTIMIZE_OUTPUT_FOR_C = YES # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java # sources only. Doxygen will then generate output that is more tailored for # Java. For instance, namespaces will be presented as packages, qualified # scopes will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources only. Doxygen will then generate output that is more tailored for # Fortran. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for # VHDL. OPTIMIZE_OUTPUT_VHDL = NO # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should # set this tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); v.s. # func(std::string) {}). This also make the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. BUILTIN_STL_SUPPORT = NO # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. # Doxygen will parse them like normal C++ but will assume all classes use public # instead of private inheritance when no explicit protection keyword is present. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate getter # and setter methods for a property. Setting this option to YES (the default) # will make doxygen to replace the get and set methods by a property in the # documentation. This will only work if the methods are indeed getting or # setting a simple type. If this is not the case, or you want to show the # methods anyway, you should set this option to NO. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. DISTRIBUTE_GROUP_DOC = NO # Set the SUBGROUPING tag to YES (the default) to allow class member groups of # the same type (for instance a group of public functions) to be put as a # subgroup of that type (e.g. under the Public Functions section). Set it to # NO to prevent subgrouping. Alternatively, this can be done per class using # the \nosubgrouping command. SUBGROUPING = YES # When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum # is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically # be useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. TYPEDEF_HIDES_STRUCT = NO #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES EXTRACT_ALL = NO # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = NO # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. EXTRACT_LOCAL_CLASSES = YES # This flag is only useful for Objective-C code. When set to YES local # methods, which are defined in the implementation section but not in # the interface are included in the documentation. # If set to NO (the default) only methods in the interface are included. EXTRACT_LOCAL_METHODS = NO # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base # name of the file that contains the anonymous namespace. By default # anonymous namespace are hidden. EXTRACT_ANON_NSPACES = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these classes will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. HIDE_FRIEND_COMPOUNDS = NO # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any # documentation blocks found inside the body of a function. # If set to NO (the default) these blocks will be appended to the # function's detailed documentation block. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower-case letters. If set to YES upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put a list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = YES # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the # brief documentation of file, namespace and class members alphabetically # by member name. If set to NO (the default) the members will appear in # declaration order. SORT_BRIEF_DOCS = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the # hierarchy of group names into alphabetical order. If set to NO (the default) # the group names will appear in their defined order. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be # sorted by fully-qualified names, including namespaces. If set to # NO (the default), the class list will be sorted only by class name, # not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the # alphabetical list. SORT_BY_SCOPE_NAME = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = YES # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting # \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= YES # The ENABLED_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if sectionname ... \endif. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines # the initial value of a variable or define consists of for it to appear in # the documentation. If the initializer consists of more lines than specified # here it will be hidden. Use a value of 0 to hide initializers completely. # The appearance of the initializer of individual variables and defines in the # documentation can be controlled using \showinitializer or \hideinitializer # command in the documentation regardless of this setting. MAX_INITIALIZER_LINES = 30 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated # at the bottom of the documentation of classes and structs. If set to YES the # list will mention the files that were used to generate the documentation. SHOW_USED_FILES = YES # If the sources in your project are distributed over multiple directories # then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy # in the documentation. The default is NO. SHOW_DIRECTORIES = NO # Set the SHOW_FILES tag to NO to disable the generation of the Files page. # This will remove the Files entry from the Quick Index and from the # Folder Tree View (if specified). The default is YES. SHOW_FILES = YES # Set the SHOW_NAMESPACES tag to NO to disable the generation of the # Namespaces page. This will remove the Namespaces entry from the Quick Index # and from the Folder Tree View (if specified). The default is YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command , where is the value of # the FILE_VERSION_FILTER tag, and is the name of an input file # provided by doxygen. Whatever the program writes to standard output # is used as the file version. See the manual for examples. FILE_VERSION_FILTER = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = YES # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some # parameters in a documented function, or documenting parameters that # don't exist or using markup commands wrongly. WARN_IF_DOC_ERROR = YES # This WARN_NO_PARAMDOC option can be abled to get warnings for # functions that are documented, but have no documentation for their parameters # or return value. If set to NO (the default) doxygen will only warn about # wrong or incomplete parameter documentation, but not about the absence of # documentation. WARN_NO_PARAMDOC = NO # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. Optionally the format may contain # $version, which will be replaced by the version of the file (if it could # be obtained via FILE_VERSION_FILTER) WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning # and error messages should be written. If left blank the output is written # to stderr. WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = . rtmidi # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is # also the default input encoding. Doxygen uses libiconv (or the iconv built # into libc) for the transcoding. See http://www.gnu.org/software/libiconv for # the list of possible encodings. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank the following patterns are tested: # *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx # *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90 FILE_PATTERNS = *.c *.cpp *.h # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = NO # The EXCLUDE tag can be used to specify files and/or directories that should # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. EXCLUDE = # The EXCLUDE_SYMLINKS tag can be used select whether or not files or # directories that are symbolic links (a Unix filesystem feature) are excluded # from the input. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. Note that the wildcards are matched # against the file with absolute path, so to exclude all test directories # for example use the pattern */test/* EXCLUDE_PATTERNS = # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test EXCLUDE_SYMBOLS = # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = NO # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command , where # is the value of the INPUT_FILTER tag, and is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. If FILTER_PATTERNS is specified, this tag will be # ignored. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. Doxygen will compare the file name with each pattern and apply the # filter if there is a match. The filters are a list of the form: # pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further # info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER # is applied to all files. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. # Note: To get rid of all source code in the generated output, make sure also # VERBATIM_HEADERS is set to NO. SOURCE_BROWSER = NO # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C and C++ comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = NO # If the REFERENCES_RELATION tag is set to YES # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = NO # If the REFERENCES_LINK_SOURCE tag is set to YES (the default) # and SOURCE_BROWSER tag is set to YES, then the hyperlinks from # functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will # link to the source code. Otherwise they will link to the documentstion. REFERENCES_LINK_SOURCE = YES # If the USE_HTAGS tag is set to YES then the references to source code # will point to the HTML generated by the htags(1) tool instead of doxygen # built-in source browser. The htags tool is part of GNU's global source # tagging system (see http://www.gnu.org/software/global/global.html). You # will need version 4.8.6 or higher. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = YES #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = NO # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 5 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for # each generated HTML page (for example: .htm,.php,.asp). If it is left blank # doxygen will generate files with .html extension. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. HTML_HEADER = # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If the tag is left blank doxygen # will generate a default style sheet. Note that doxygen will try to copy # the style sheet file to the HTML output directory, so don't put your own # stylesheet in the HTML output directory as well, or it will be erased! HTML_STYLESHEET = # If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, # files or namespaces will be aligned in HTML using tables. If set to # NO a bullet list will be used. HTML_ALIGN_MEMBERS = YES # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compiled HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO # If the GENERATE_DOCSET tag is set to YES, additional index files # will be generated that can be used as input for Apple's Xcode 3 # integrated development environment, introduced with OSX 10.5 (Leopard). # To create a documentation set, doxygen will generate a Makefile in the # HTML output directory. Running make will produce the docset in that # directory and running "make install" will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find # it at startup. GENERATE_DOCSET = NO # When GENERATE_DOCSET tag is set to YES, this tag determines the name of the # feed. A documentation feed provides an umbrella under which multiple # documentation sets from a single provider (such as a company or product suite) # can be grouped. DOCSET_FEEDNAME = "Doxygen generated docs" # When GENERATE_DOCSET tag is set to YES, this tag specifies a string that # should uniquely identify the documentation set bundle. This should be a # reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen # will append .docset to the name. DOCSET_BUNDLE_ID = org.doxygen.Project # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. For this to work a browser that supports # JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox # Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). HTML_DYNAMIC_SECTIONS = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output directory. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non-empty doxygen will try to run # the HTML help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING # is used to encode HtmlHelp index (hhk), content (hhc) and project file # content. CHM_INDEX_ENCODING = # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the HTML help documentation and to the tree view. TOC_EXPAND = NO # The DISABLE_INDEX tag can be used to turn on/off the condensed index at # top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. DISABLE_INDEX = NO # This tag can be used to set the number of enum values (range [1..20]) # that doxygen will group on one line in the generated HTML documentation. ENUM_VALUES_PER_LINE = 4 # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. # If the tag value is set to FRAME, a side panel will be generated # containing a tree-like index structure (just like the one that # is generated for HTML Help). For this to work a browser that supports # JavaScript, DHTML, CSS and frames is required (for instance Mozilla 1.0+, # Netscape 6.0+, Internet explorer 5.0+, or Konqueror). Windows users are # probably better off using the HTML help feature. Other possible values # for this tag are: HIERARCHIES, which will generate the Groups, Directories, # and Class Hiererachy pages using a tree view instead of an ordered list; # ALL, which combines the behavior of FRAME and HIERARCHIES; and NONE, which # disables this behavior completely. For backwards compatibility with previous # releases of Doxygen, the values YES and NO are equivalent to FRAME and NONE # respectively. GENERATE_TREEVIEW = NONE # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be # used to set the initial width (in pixels) of the frame in which the tree # is shown. TREEVIEW_WIDTH = 250 # Use this tag to change the font size of Latex formulas included # as images in the HTML documentation. The default is 10. Note that # when you change the font size after a successful doxygen run you need # to manually remove any form_*.png images from the HTML output directory # to force them to be regenerated. FORMULA_FONTSIZE = 10 #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = NO # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. If left blank `latex' will be used as the default command name. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the # default command name. MAKEINDEX_CMD_NAME = makeindex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, a4wide, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4wide # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = YES # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # plain latex in the generated Makefile. Set this option to YES to get a # higher quality PDF documentation. USE_PDFLATEX = YES # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO # If LATEX_HIDE_INDICES is set to YES then doxygen will not # include the index chapters (such as File Index, Compound Index, etc.) # in the output. LATEX_HIDE_INDICES = NO #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # The RTF output is optimized for Word 97 and may not look very pretty with # other RTF readers or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using WORD or other # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO # Load stylesheet definitions from file. Syntax is similar to doxygen's # config file, i.e. a series of assignments. You only have to provide # replacements, missing definitions are set to their default value. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an rtf document. # Syntax is similar to doxygen's config file. RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 # If the MAN_LINKS tag is set to YES and Doxygen generates man output, # then it will generate one additional man file for each entity # documented in the real man page(s). These additional files # only source the real man page, but without them the man command # would be unable to find the correct page. The default is NO. MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES Doxygen will # generate an XML file that captures the structure of # the code including all documentation. GENERATE_XML = NO # The XML_OUTPUT tag is used to specify where the XML pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `xml' will be used as the default path. XML_OUTPUT = xml # The XML_SCHEMA tag can be used to specify an XML schema, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_SCHEMA = # The XML_DTD tag can be used to specify an XML DTD, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_DTD = # If the XML_PROGRAMLISTING tag is set to YES Doxygen will # dump the program listings (including syntax highlighting # and cross-referencing information) to the XML output. Note that # enabling this will significantly increase the size of the XML output. XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will # generate an AutoGen Definitions (see autogen.sf.net) file # that captures the structure of the code including all # documentation. Note that this feature is still experimental # and incomplete at the moment. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES Doxygen will # generate a Perl module file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_PERLMOD = NO # If the PERLMOD_LATEX tag is set to YES Doxygen will generate # the necessary Makefile rules, Perl scripts and LaTeX code to be able # to generate PDF and DVI output from the Perl module output. PERLMOD_LATEX = NO # If the PERLMOD_PRETTY tag is set to YES the Perl module output will be # nicely formatted so it can be parsed by a human reader. This is useful # if you want to understand what is going on. On the other hand, if this # tag is set to NO the size of the Perl module output will be much smaller # and Perl will parse it just the same. PERLMOD_PRETTY = YES # The names of the make variables in the generated doxyrules.make file # are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. # This is useful so different doxyrules.make files included by the same # Makefile don't overwrite each other's variables. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. MACRO_EXPANSION = NO # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_DEFINED tags. EXPAND_ONLY_PREDEF = NO # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # in the INCLUDE_PATH (see below) will be search if a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will # be used. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. To prevent a macro definition from being # undefined via #undef or recursively expanded use the := operator # instead of the = operator. PREDEFINED = # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. # The macro definition that is found in the sources will be used. # Use the PREDEFINED tag if you want to use a different macro definition. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then # doxygen's preprocessor will remove all function-like macros that are alone # on a line, have an all uppercase name, and do not end with a semicolon. Such # function macros are typically used for boiler-plate code, and will confuse # the parser if not removed. SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- # The TAGFILES option can be used to specify one or more tagfiles. # Optionally an initial location of the external documentation # can be added for each tagfile. The format of a tag file without # this location is as follows: # TAGFILES = file1 file2 ... # Adding location for the tag files is done as follows: # TAGFILES = file1=loc1 "file2 = loc2" ... # where "loc1" and "loc2" can be relative or absolute paths or # URLs. If a location is present for each tag, the installdox tool # does not have to be run to correct the links. # Note that each tag file must have a unique name # (where the name does NOT include the path) # If a tag file is not located in the directory in which doxygen # is run, you must also specify the path to the tagfile here. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed # in the modules index. If set to NO, only the current project's groups will # be listed. EXTERNAL_GROUPS = YES # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base # or super classes. Setting the tag to NO turns the diagrams off. Note that # this option is superseded by the HAVE_DOT option below. This is only a # fallback. It is recommended to install and use dot, since it yields more # powerful graphs. CLASS_DIAGRAMS = YES # You can define message sequence charts within doxygen comments using the \msc # command. Doxygen will then run the mscgen tool (see # http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the # documentation. The MSCGEN_PATH tag allows you to specify the directory where # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. MSCGEN_PATH = # If set to YES, the inheritance and collaboration graphs will hide # inheritance and usage relations if the target is undocumented # or is not a class. HIDE_UNDOC_RELATIONS = YES # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = NO # By default doxygen will write a font called FreeSans.ttf to the output # directory and reference it in all dot files that doxygen generates. This # font does not include all possible unicode characters however, so when you need # these (or just want a differently looking font) you can specify the font name # using DOT_FONTNAME. You need need to make sure dot is able to find the font, # which can be done by putting it in a standard location or by setting the # DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory # containing the font. DOT_FONTNAME = FreeSans # By default doxygen will tell dot to use the output directory to look for the # FreeSans.ttf font (which doxygen will put there itself). If you specify a # different font using DOT_FONTNAME you can set the path where dot # can find it using this tag. DOT_FONTPATH = # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # the CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen # will generate a graph for groups, showing the direct groups dependencies GROUP_GRAPHS = YES # If the UML_LOOK tag is set to YES doxygen will generate inheritance and # collaboration diagrams in a style similar to the OMG's Unified Modeling # Language. UML_LOOK = NO # If set to YES, the inheritance and collaboration graphs will show the # relations between templates and their instances. TEMPLATE_RELATIONS = NO # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT # tags are set to YES then doxygen will generate a graph for each documented # file showing the direct and indirect include dependencies of the file with # other documented files. INCLUDE_GRAPH = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and # HAVE_DOT tags are set to YES then doxygen will generate a graph for each # documented header file showing the documented files that directly or # indirectly include this file. INCLUDED_BY_GRAPH = YES # If the CALL_GRAPH and HAVE_DOT options are set to YES then # doxygen will generate a call dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable call graphs # for selected functions only using the \callgraph command. CALL_GRAPH = NO # If the CALLER_GRAPH and HAVE_DOT tags are set to YES then # doxygen will generate a caller dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable caller # graphs for selected functions only using the \callergraph command. CALLER_GRAPH = NO # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = YES # If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES # then doxygen will show the dependencies a directory has on other directories # in a graphical way. The dependency relations are determined by the #include # relations between the files in the directories. DIRECTORY_GRAPH = YES # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are png, jpg, or gif # If left blank png will be used. DOT_IMAGE_FORMAT = png # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found in the path. DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of # nodes that will be shown in the graph. If the number of nodes in a graph # becomes larger than this value, doxygen will truncate the graph, which is # visualized by representing a node as a red box. Note that doxygen if the # number of direct children of the root node in a graph is already larger than # DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note # that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. DOT_GRAPH_MAX_NODES = 50 # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the # graphs generated by dot. A depth value of 3 means that only nodes reachable # from the root by following a path via at most 3 edges will be shown. Nodes # that lay further from the root node will be omitted. Note that setting this # option to 1 or 2 may greatly reduce the computation time needed for large # code bases. Also note that the size of a graph can be further restricted by # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. MAX_DOT_GRAPH_DEPTH = 0 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is enabled by default, which results in a transparent # background. Warning: Depending on the platform used, enabling this option # may lead to badly anti-aliased labels on the edges of a graph (i.e. they # become hard to read). DOT_TRANSPARENT = YES # Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output # files in one run (i.e. multiple -o and -T options on the command line). This # makes dot run faster, but since only newer versions of dot (>1.8.10) # support this, this feature is disabled by default. DOT_MULTI_TARGETS = NO # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermediate dot files that are used to generate # the various graphs. DOT_CLEANUP = YES #--------------------------------------------------------------------------- # Configuration::additions related to the search engine #--------------------------------------------------------------------------- # The SEARCHENGINE tag specifies whether or not a search engine should be # used. If set to NO the values of all tags below this one will be ignored. SEARCHENGINE = NO pianobooster-src-0.6.4/src/Conductor.h0000644000175000017500000002252411304222711016760 0ustar louislouis/*********************************************************************************/ /*! @file Conductor.h @brief The realtime midi engine. Send notes to the midi device and responds to the midi keyboard. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __CONDUCTOR_H__ #define __CONDUCTOR_H__ #include "MidiEvent.h" #include "Queue.h" #include "MidiDevice.h" #include "Cfg.h" #include "Chord.h" #include "Rating.h" #include "Tempo.h" #include "Bar.h" class CScore; class CPiano; class CSettings; typedef enum { PB_FOLLOW_searching, PB_FOLLOW_earlyNotes, PB_FOLLOW_waiting } followState_t; enum { PB_PLAY_MODE_listen, PB_PLAY_MODE_followYou, PB_PLAY_MODE_playAlong }; typedef int playMode_t; typedef enum { PB_STOP_POINT_MODE_automatic, PB_STOP_POINT_MODE_onTheBeat, PB_STOP_POINT_MODE_afterTheBeat } stopPointMode_t; /*! * @brief xxxxx. */ class CConductor : public CMidiDevice { public: CConductor(); ~CConductor(); void init(CScore * scoreWin, CSettings* settings); //! add a midi event to be analysed and played void midiEventInsert(CMidiEvent event); //! first check if there is space to add a midi event int midiEventSpace(); //! add a chord to be played by the pianist void chordEventInsert(CChord chord) {m_wantedChordQueue->push(chord);} //! first check if there is space to add a chord event int chordEventSpace() { return m_wantedChordQueue->space();} void rewind(); void realTimeEngine(int mSecTicks); void playMusic(bool start); bool playingMusic() {return m_playing;} float getSpeed() {return m_tempo.getSpeed();} void setSpeed(float speed) { m_tempo.setSpeed(speed); m_leadLagAdjust = m_tempo.mSecToTicks( -getLatencyFix() ); } void setLatencyFix(int latencyFix) { m_latencyFix = latencyFix; m_leadLagAdjust = m_tempo.mSecToTicks( -getLatencyFix()); } int getLatencyFix() { return m_latencyFix; } void muteChannel(int channel, bool state); void mutePart(int channel, bool state); void transpose(int transpose); int getTranspose() {return m_transpose;} int getSkill() {return m_skill;} void setSkill(int skill) { m_skill = skill; if (m_skill > 5) m_skill = 5; if (m_skill < 0) m_skill = 0; } void pianistInput(CMidiEvent inputNote); void setPlayMode(playMode_t mode) { m_playMode = mode; if (m_playMode < 0 ) m_playMode = 0; if (m_playMode > 2 ) m_playMode = 2; if ( m_playMode == PB_PLAY_MODE_listen ) resetWantedChord(); activatePianistMutePart(); outputBoostVolume(); } int getBoostVolume() {return m_boostVolume;} void boostVolume(int boostVolume) { m_boostVolume = boostVolume; if (m_boostVolume < -100 ) m_boostVolume = -100; if (m_boostVolume > 100 ) m_boostVolume = 100; outputBoostVolume(); } int getPianoVolume() {return m_pianoVolume;} void pianoVolume(int pianoVolume) { m_pianoVolume = pianoVolume; if (m_pianoVolume < -100 ) m_pianoVolume = -100; if (m_pianoVolume > 100 ) m_pianoVolume = 100; outputBoostVolume(); } static playMode_t getPlayMode() {return m_playMode;} CChord getWantedChord() {return m_wantedChord;} void setActiveHand(whichPart_t hand); void setActiveChannel(int channel); int getActiveChannel(){return m_activeChannel;} void setPianistChannels(int goodChan, int badChan){ m_pianistGoodChan = goodChan; m_pianistBadChan = badChan; } bool hasPianistKeyboardChannel(int chan) { return (m_pianistGoodChan == chan || m_pianistBadChan == chan ) ? true : false;} CRating* getRating(){return &m_rating;} // You MUST clear the time sig to 0 first before setting an new start time Sig void setTimeSig(int top, int bottom) { m_bar.setTimeSig(top, bottom);} void getTimeSig(int *top, int *bottom) {m_bar.getTimeSig(top, bottom);} void testWrongNoteSound(bool enable); // -1 means no sound -2 means ignore this parameter void setPianoSoundPatches(int rightSound, int wrongSound, bool update = false){ m_cfg_rightNoteSound = rightSound; if ( wrongSound != -2) m_cfg_wrongNoteSound = wrongSound; if (update) updatePianoSounds(); } void setEventBits(eventBits_t bits) { m_realTimeEventBits |= bits; } // don't change the other bits // set to true to force the score to be redrawn void forceScoreRedraw(){ setEventBits( EVENT_BITS_forceFullRedraw); } int getBarNumber(){ return m_bar.getBarNumber();} double getCurrentBarPos(){ return m_bar.getCurrentBarPos();} void setPlayFromBar(double bar){ m_bar.setPlayFromBar(bar);} void setPlayUptoBar(double bar){ m_bar.setPlayUptoBar(bar);} double getPlayUptoBar(){ return m_bar.getPlayUptoBar();} void setLoopingBars(double bars){ m_bar.setLoopingBars(bars);} double getLoopingBars(){ return m_bar.getLoopingBars();} void mutePianistPart(bool state); bool cfg_timingMarkersFlag; stopPointMode_t cfg_stopPointMode; protected: CScore* m_scoreWin; CSettings* m_settings; CQueue* m_songEventQueue; CQueue* m_wantedChordQueue; eventBits_t m_realTimeEventBits; //used to signal real time events to the caller of task() void outputSavedNotes(); void activatePianistMutePart(); void resetWantedChord(); bool validatePianistNote( const CMidiEvent& inputNote); bool validatePianistChord(); bool seekingBarNumber() { return m_bar.seekingBarNumber();} private: void allSoundOff(); void resetAllChannels(); void outputBoostVolume(); void outputPianoVolume(); void channelSoundOff(int channel); void findSplitPoint(); void fetchNextChord(); void playTransposeEvent(CMidiEvent event); void outputSavedNotesOff(); void findImminentNotesOff(); void updatePianoSounds(); void followPlaying(); void missedNotesColour(CColour colour); int calcBoostVolume(int chan, int volume); void addDeltaTime(int ticks); int m_playingDeltaTime; int m_chordDeltaTime; bool m_playing; int m_transpose; // the number of semitones to transpose the music followState_t m_followState; followState_t getfollowState() { if ( m_playMode == PB_PLAY_MODE_listen ) return PB_FOLLOW_searching; return m_followState; } CRating m_rating; CQueue* m_savedNoteQueue; CQueue* m_savedNoteOffQueue; CMidiEvent m_nextMidiEvent; bool m_muteChannels[MAX_MIDI_CHANNELS]; bool isChannelMuted(int chan) { if (chan < 0 || chan >= MAX_MIDI_CHANNELS) return true; return m_muteChannels[chan]; } void setFollowSkillAdvanced(bool enable); CPiano* m_piano; CBar m_bar; int m_leadLagAdjust; // Synchronise the sound the the video int m_silenceTimeOut; // used to create silence if the student stops for toooo long CChord m_wantedChord; // The chord the pianist needs to play CChord m_savedwantedChord; // A copy of the wanted chord complete with both left and right parts CChord m_goodPlayedNotes; // The good notes the pianist plays CTempo m_tempo; int m_pianistSplitPoint; // Defines which notes go in the base and treble clef bool m_followSkillAdvanced; int m_lastSound; int m_stopPoint; // Were we stop the music if the pianist is late int m_cfg_rightNoteSound; int m_cfg_wrongNoteSound; int m_pianistGoodChan; int m_pianistBadChan; int m_cfg_earlyNotesPoint; // don't press the note too early int m_cfg_stopPointAdvanced; // Were we stop the music if the pianist is late int m_cfg_stopPointBeginner; // Were we stop the music if the pianist is late int m_cfg_imminentNotesOffPoint; int m_cfg_playZoneEarly; // when playing along int m_cfg_playZoneLate; int m_pianistTiming; //measure whether the pianist is playing early or late bool m_followPlayingTimeOut; // O dear, the student is too slow bool m_testWrongNoteSound; int m_boostVolume; int m_pianoVolume; int m_activeChannel; // The current part that is being displayed (used for boost and activatePianistMutePart) int m_savedMainVolume[MAX_MIDI_CHANNELS]; static playMode_t m_playMode; int m_skill; bool m_mutePianistPart; int m_latencyFix; // Try to fix the latency (put the time in msec, 0 disables it) }; #endif //__CONDUCTOR_H__ pianobooster-src-0.6.4/src/Conductor.cpp0000644000175000017500000006404611304222711017320 0ustar louislouis/*********************************************************************************/ /*! @file Conductor.cpp @brief xxxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #define OPTION_DEBUG_CONDUCTOR 0 #if OPTION_DEBUG_CONDUCTOR #define ppDEBUG_CONDUCTOR(args) ppLogDebug args #else #define ppDEBUG_CONDUCTOR(args) #endif #include "Conductor.h" #include "Score.h" #include "Piano.h" #include "Cfg.h" playMode_t CConductor::m_playMode = PB_PLAY_MODE_listen; CConductor::CConductor() { int i; m_scoreWin = 0; m_piano = 0; m_songEventQueue = new CQueue(1000); m_wantedChordQueue = new CQueue(1000); m_savedNoteQueue = new CQueue(200); m_savedNoteOffQueue = new CQueue(200); m_playing = false; m_transpose = 0; m_latencyFix = 0; m_leadLagAdjust = 0; setSpeed(1.0); setLatencyFix(0); m_boostVolume = 0; m_pianoVolume = 0; m_activeChannel = 0; m_skill = 0; m_silenceTimeOut = 0; m_realTimeEventBits = 0; m_mutePianistPart = false; setPianistChannels(1-1,2-1); cfg_timingMarkersFlag = false; cfg_stopPointMode = PB_STOP_POINT_MODE_automatic; setPianoSoundPatches(1-1, 7-1); // 6-1 m_tempo.setSavedwantedChord(&m_savedwantedChord); for ( i = 0; i < MAX_MIDI_CHANNELS; i++) { m_muteChannels[i] = false; } rewind(); testWrongNoteSound(false); } CConductor::~CConductor() { delete m_songEventQueue; delete m_wantedChordQueue; delete m_savedNoteQueue; delete m_savedNoteOffQueue; } //! add a midi event to be analysed and displayed on the score void CConductor::midiEventInsert(CMidiEvent event) { m_songEventQueue->push(event); } //! first check if there is space to add a midi event int CConductor::midiEventSpace() { return m_songEventQueue->space(); } void CConductor::channelSoundOff(int channel) { if (channel < 0 || channel >= MAX_MIDI_CHANNELS) { return; } CMidiEvent midi; midi.controlChangeEvent(0, channel, MIDI_ALL_NOTES_OFF, 0); playMidiEvent(midi); // remove the sustain pedal as well midi.controlChangeEvent(0, channel, MIDI_SUSTAIN, 0); playMidiEvent(midi); } void CConductor::allSoundOff() { int channel; for ( channel = 0; channel < MAX_MIDI_CHANNELS; channel++) { if (channel != m_pianistGoodChan) channelSoundOff(channel); } m_savedNoteQueue->clear(); m_savedNoteOffQueue->clear(); } void CConductor::resetAllChannels() { int channel; CMidiEvent midi; for ( channel = 0; channel < MAX_MIDI_CHANNELS; channel++) { midi.controlChangeEvent(0, channel, MIDI_RESET_ALL_CONTROLLERS, 0); playMidiEvent(midi); } } void CConductor::muteChannel(int channel, bool state) { if (channel < 0 || channel >= MAX_MIDI_CHANNELS) return; m_muteChannels[ channel] = state; if (state == true) channelSoundOff(channel); // fixme this is called too often } void CConductor::mutePart(int part, bool state) { int channel; if ( part < MAX_MIDI_CHANNELS) { muteChannel(part, state); return; } for ( channel = 0; channel < MAX_MIDI_CHANNELS; channel++) { muteChannel( channel, state); } if (state == true) channelSoundOff(channel); } /* calculate the new solo_volume */ int CConductor::calcBoostVolume(int channel, int volume) { int returnVolume; bool activePart; if (volume == -1) volume = m_savedMainVolume[channel]; else m_savedMainVolume[channel] = volume; returnVolume = volume; activePart = false; if (CNote::hasPianoPart(m_activeChannel)) { if (m_playMode == PB_PLAY_MODE_listen) // only boost one hand in listen mode { if (channel == CNote::leftHandChan() && CNote::getActiveHand() != PB_PART_right) activePart = true; if (channel == CNote::rightHandChan() && CNote::getActiveHand() != PB_PART_left) activePart = true; } else // otherwise always boost both hands { if ( CNote::hasPianoPart(channel)) activePart = true; } } else { if (channel == m_activeChannel) activePart= true; } if (channel == m_activeChannel) activePart= true; //if (channel == 5) activePart= true; // for debugging if (activePart) { if (returnVolume == 0 ) ; /* Don't adjust the volume if zero */ else if (m_boostVolume < 0 ) returnVolume = (returnVolume * (m_boostVolume + 100)) / 100; else returnVolume += m_boostVolume; } else { if (m_boostVolume > 0) returnVolume = (returnVolume * (100 - m_boostVolume)) / 100; } // The piano volume can reduce the volume of the music if (m_pianoVolume>0) returnVolume = (returnVolume * (100 - m_pianoVolume)) / 100;; if (returnVolume > 127) returnVolume = 127; return returnVolume; } /* send boost volume by adjusting all channels */ void CConductor::outputBoostVolume() { int chan; for ( chan =0; chan 12) m_transpose = 12; if (m_transpose < -12) m_transpose = -12; m_scoreWin->transpose(m_transpose); } } void CConductor::activatePianistMutePart() { mutePart(PB_PART_all, false); if (m_playMode != PB_PLAY_MODE_listen && m_mutePianistPart == true) { if (CNote::hasPianoPart(m_activeChannel)) { if (CNote::getActiveHand() == PB_PART_both || CNote::getActiveHand() == PB_PART_left) mutePart(CNote::leftHandChan(), true); if (CNote::getActiveHand() == PB_PART_both || CNote::getActiveHand() == PB_PART_right) mutePart(CNote::rightHandChan(), true); } else mutePart(m_activeChannel, true); } } void CConductor::mutePianistPart(bool state) { m_mutePianistPart = state; activatePianistMutePart(); } void CConductor::setActiveHand(whichPart_t hand) { if (CNote::getActiveHand() == hand) return; CNote::setActiveHand(hand); activatePianistMutePart(); outputBoostVolume(); m_wantedChord = m_savedwantedChord; if (m_wantedChord.trimOutOfRangeNotes(m_transpose)==0) fetchNextChord(); int note; int i; // Reset the note colours for(i = 0; i < m_savedwantedChord.length(); i++) { note = m_savedwantedChord.getNote(i).pitch(); m_scoreWin->setPlayedNoteColour(note, Cfg::noteColour(), m_chordDeltaTime); } for(i = 0; i < m_wantedChord.length(); i++) { note = m_wantedChord.getNote(i).pitch(); m_scoreWin->setPlayedNoteColour(note, Cfg::playedStoppedColour(), m_chordDeltaTime); } findSplitPoint(); forceScoreRedraw(); } void CConductor::setActiveChannel(int channel) { m_activeChannel = channel; outputBoostVolume(); resetWantedChord(); fetchNextChord(); activatePianistMutePart(); } void CConductor::outputPianoVolume() { CMidiEvent event; int volume = 127; // if piano volume is between -100 and 0 reduce the volume accordingly if (m_pianoVolume < 0) volume = (volume * (100 + m_pianoVolume)) / 100; event.controlChangeEvent(0, m_pianistGoodChan, MIDI_MAIN_VOLUME, volume); playMidiEvent(event); // Play the midi note or event event.controlChangeEvent(0, m_pianistBadChan, MIDI_MAIN_VOLUME, volume); playMidiEvent(event); // Play the midi note or event } void CConductor::updatePianoSounds() { CMidiEvent event; if (m_cfg_rightNoteSound>=0) // ignore if set to -1 ("None") { event.programChangeEvent(0, m_pianistGoodChan, m_cfg_rightNoteSound); playMidiEvent( event ); } if (m_cfg_wrongNoteSound>=0) { event.programChangeEvent(0, m_pianistBadChan, m_cfg_wrongNoteSound); playMidiEvent( event ); } } void CConductor::testWrongNoteSound(bool enable) { m_testWrongNoteSound = enable; updatePianoSounds(); } void CConductor::playMusic(bool start) { m_playing = start; allSoundOff(); if (start) { resetAllChannels(); activatePianistMutePart(); testWrongNoteSound(false); if (seekingBarNumber()) resetWantedChord(); /* const unsigned char gsModeEnterData[] = {0xf0, 0x41, 0x10, 0x42, 0x12, 0x40, 0x00, 0x7f, 0x00, 0x41, 0xf7}; for (size_t i = 0; i < arraySize(gsModeEnterData); i++) { event.collateRawByte(0, gsModeEnterData[i]); playMidiEvent(event); } event.outputCollatedRawBytes(0); playMidiEvent(event); */ } } void CConductor::playTransposeEvent(CMidiEvent event) { if (m_transpose != 0 && event.channel() != MIDI_DRUM_CHANNEL && (event.type() == MIDI_NOTE_ON || event.type() == MIDI_NOTE_OFF) ) event.transpose(m_transpose); if (event.type() == MIDI_NOTE_ON && isChannelMuted(event.channel()) == true && CChord::isNotePlayable(event.note(), m_transpose) == true) return; // mute the note by not playing it // boost any volume events if (event.type() == MIDI_CONTROL_CHANGE && event.data1() == MIDI_MAIN_VOLUME) event.setDatat2(calcBoostVolume(event.channel(), event.data2() )); // Don't output note on if we are seeking to bar if (!seekingBarNumber()) playMidiEvent(event); // Play the midi note or event else { if (event.type() == MIDI_PROGRAM_CHANGE || event.type() == MIDI_CONTROL_CHANGE) playMidiEvent(event); // Play the midi note or event } } void CConductor::outputSavedNotes() { // The saved notes off are note needed any more // (as the are also in the savedNoteQueue m_savedNoteOffQueue->clear(); // output any the saved up notes while (m_savedNoteQueue->length() > 0) playTransposeEvent(m_savedNoteQueue->pop()); } void CConductor::resetWantedChord() { m_wantedChord.clear(); ppDEBUG_CONDUCTOR(("resetWantedChord m_chordDeltaTime %d m_playingDeltaTime %d", m_chordDeltaTime, m_playingDeltaTime )); m_followPlayingTimeOut = false; m_chordDeltaTime = m_playingDeltaTime; m_pianistTiming = m_chordDeltaTime; m_pianistSplitPoint = MIDDLE_C; outputSavedNotes(); m_followState = PB_FOLLOW_searching; } // switch modes if we are playing well enough (i.e. don't slow down if we are playing late) void CConductor::setFollowSkillAdvanced(bool enable) { if (m_settings==0 || m_scoreWin == 0) return; m_settings-> setAdvancedMode(enable); if (getLatencyFix() > 0) { // behave differently if we are using the latency fix m_cfg_earlyNotesPoint = m_cfg_imminentNotesOffPoint; //disable the early notes } if (cfg_stopPointMode == PB_STOP_POINT_MODE_onTheBeat) enable = false; if (cfg_stopPointMode == PB_STOP_POINT_MODE_afterTheBeat) enable = true; m_followSkillAdvanced = enable; m_stopPoint = (enable) ? m_cfg_stopPointAdvanced: m_cfg_stopPointBeginner ; } void CConductor::findSplitPoint() { // find the split point int lowestTreble = MIDDLE_C + 37; int highestBase = MIDDLE_C - 37; CNote note; // Find where to put the split point for(int i = 0; i < m_wantedChord.length(); i++) { note = m_wantedChord.getNote(i); if (note.part() == PB_PART_right && note.pitch() < lowestTreble) lowestTreble = note.pitch(); if (note.part() == PB_PART_left && note.pitch() > highestBase) highestBase = note.pitch(); } //put the split point in the middle m_pianistSplitPoint = ((lowestTreble + highestBase) /2 ) + m_transpose; } void CConductor::fetchNextChord() { m_followState = PB_FOLLOW_searching; m_followPlayingTimeOut = false; outputSavedNotes(); do // Remove notes or chords that are out of our range { if (m_wantedChordQueue->length() == 0) { m_wantedChord.clear(); m_pianistSplitPoint = MIDDLE_C; return; } m_wantedChord = m_wantedChordQueue->pop(); m_savedwantedChord = m_wantedChord; m_chordDeltaTime -= m_wantedChord.getDeltaTime() * SPEED_ADJUST_FACTOR; m_pianistTiming = m_chordDeltaTime; } while (m_wantedChord.trimOutOfRangeNotes(m_transpose)==0); // now find the split point findSplitPoint(); } bool CConductor::validatePianistNote( const CMidiEvent & inputNote) { if ( m_chordDeltaTime <= -m_cfg_playZoneEarly) return false; return m_wantedChord.searchChord(inputNote.note(), m_transpose); } bool CConductor::validatePianistChord() { if (m_piano->pianistBadNotesDown() >= 2) return false; if (m_skill>=3) { if (m_goodPlayedNotes.length() == m_wantedChord.length()) return true; } else { if (m_goodPlayedNotes.length() >= 1) return true; } return false; } void CConductor::pianistInput(CMidiEvent inputNote) { bool goodSound = true; if (m_testWrongNoteSound) goodSound = false; if (inputNote.type() == MIDI_NOTE_ON) { whichPart_t hand; hand = (inputNote.note() >= m_pianistSplitPoint)? PB_PART_right : PB_PART_left; if ( validatePianistNote(inputNote) == true) { m_goodPlayedNotes.addNote(hand, inputNote.note()); m_piano->addPianistNote(hand, inputNote.note(),true); int pianistTiming = ( cfg_timingMarkersFlag && m_followSkillAdvanced) ? m_pianistTiming : NOT_USED; m_scoreWin->setPlayedNoteColour(inputNote.note(), (!m_followPlayingTimeOut)? Cfg::playedGoodColour():Cfg::playedBadColour(), m_chordDeltaTime, pianistTiming); if (validatePianistChord() == true) { if (m_chordDeltaTime < 0) m_tempo.removePlayingTicks(-m_chordDeltaTime); m_goodPlayedNotes.clear(); fetchNextChord(); // count the good notes so that the live percentage looks OK m_rating.totalNotes(m_wantedChord.length()); m_rating.calculateAccuracy(); m_settings->pianistActive(); if (m_rating.isAccuracyGood() || m_playMode == PB_PLAY_MODE_playAlong) setFollowSkillAdvanced(true); // change the skill level only when they are good enough else setFollowSkillAdvanced(false); setEventBits( EVENT_BITS_forceRatingRedraw); } } else { if (m_playing == true) { goodSound = false; m_piano->addPianistNote(hand, inputNote.note(), false); m_rating.wrongNotes(1); } else m_piano->addPianistNote(hand, inputNote.note(), true); } } else if (inputNote.type() == MIDI_NOTE_OFF) { if (m_piano->removePianistNote(inputNote.note()) == true) goodSound = false; bool hasNote = m_goodPlayedNotes.removeNote(inputNote.note()); if (hasNote) m_scoreWin->setPlayedNoteColour(inputNote.note(), (!m_followPlayingTimeOut)? Cfg::noteColour():Cfg::playedStoppedColour(), m_chordDeltaTime); outputSavedNotesOff(); } if (goodSound == true || m_cfg_wrongNoteSound < 0) { if (m_cfg_rightNoteSound >= 0) // don't play anything if the sound is set to -1 (none) { inputNote.setChannel(m_pianistGoodChan); playMidiEvent( inputNote ); } } else { inputNote.setChannel(m_pianistBadChan); playMidiEvent( inputNote ); } /* // use the same channel for the right and wrong note int pianoSound = (goodSound == true) ? m_cfg_rightNoteSound : m_cfg_wrongNoteSound; if (pianoSound != m_lastSound) { m_lastSound = pianoSound; CMidiEvent midiSound; midiSound.programChangeEvent(0,inputNote.channel(),pianoSound); playMidiEvent( midiSound ); } */ } void CConductor::addDeltaTime(int ticks) { m_scoreWin->scrollDeltaTime(ticks); m_playingDeltaTime += ticks; m_chordDeltaTime +=ticks; } void CConductor::followPlaying() { if ( m_playMode == PB_PLAY_MODE_listen ) return; if (m_wantedChord.length() == 0) fetchNextChord(); if (m_wantedChord.length() == 0) return; if (seekingBarNumber()) { if (deltaAdjust(m_chordDeltaTime) > -m_stopPoint ) fetchNextChord(); } else if ( m_playMode == PB_PLAY_MODE_followYou) { if (deltaAdjust(m_chordDeltaTime) > -m_cfg_earlyNotesPoint ) m_followState = PB_FOLLOW_earlyNotes; if (deltaAdjust(m_chordDeltaTime) > -m_stopPoint ) { m_followState = PB_FOLLOW_waiting; // Throw away the time past the stop point (by adding a negative ticks) addDeltaTime( -m_stopPoint*SPEED_ADJUST_FACTOR - m_chordDeltaTime); } } else // m_playMode == PB_PLAY_MODE_playAlong { if (m_chordDeltaTime > m_cfg_playZoneLate ) { missedNotesColour(Cfg::playedStoppedColour()); fetchNextChord(); m_rating.lateNotes(m_wantedChord.length() - m_goodPlayedNotes.length()); setEventBits( EVENT_BITS_forceRatingRedraw); } } } void CConductor::outputSavedNotesOff() { while (m_savedNoteOffQueue->length() > 0) playTransposeEvent(m_savedNoteOffQueue->pop()); // Output the saved note off events } // untangle the sound in case there is any notes off just after we have stopped void CConductor::findImminentNotesOff() { int i; CMidiEvent event; int aheadDelta = 0; i = 0; event = m_nextMidiEvent; while (deltaAdjust(m_playingDeltaTime) + aheadDelta > m_cfg_imminentNotesOffPoint) { if (event.type() == MIDI_NOTE_OFF ) m_savedNoteOffQueue->push(event); if ( i >= m_songEventQueue->length()) break; event = m_songEventQueue->index(i); aheadDelta -= event.deltaTime(); i++; } } void CConductor::missedNotesColour(CColour colour) { int i; CNote note; for (i = 0; i < m_wantedChord.length(); i++) { note = m_wantedChord.getNote(i); if (m_goodPlayedNotes.searchChord(note.pitch(),m_transpose) == false) m_scoreWin->setPlayedNoteColour(note.pitch() + m_transpose, colour, m_chordDeltaTime); } } void CConductor::realTimeEngine(int mSecTicks) { int type; int ticks; // Midi ticks //mSecTicks = 2; // for debugging only ticks = m_tempo.mSecToTicks(mSecTicks); if (!m_followPlayingTimeOut) m_pianistTiming += ticks; while (checkMidiInput() > 0) pianistInput(readMidiInput()); if (getfollowState() == PB_FOLLOW_waiting ) { if (m_silenceTimeOut > 0) { m_silenceTimeOut -= mSecTicks; if (m_silenceTimeOut <= 0) { allSoundOff(); m_silenceTimeOut = 0; } } m_tempo.insertPlayingTicks(ticks); if (m_pianistTiming > m_cfg_playZoneLate) { if (m_followPlayingTimeOut == false) { m_followPlayingTimeOut = true; m_tempo.clearPlayingTicks(); m_rating.lateNotes(m_wantedChord.length() - m_goodPlayedNotes.length()); setEventBits( EVENT_BITS_forceRatingRedraw); missedNotesColour(Cfg::playedStoppedColour()); findImminentNotesOff(); // Don't keep any saved notes off if there are no notes down if (m_piano->pianistAllNotesDown() == 0) outputSavedNotesOff(); m_silenceTimeOut = Cfg::silenceTimeOut(); } } return; } m_silenceTimeOut = 0; if (m_playing == false) return; if (seekingBarNumber()) ticks = 0; m_tempo.adjustTempo(&ticks); ticks = m_bar.addDeltaTime(ticks); if (seekingBarNumber()) ticks = m_bar.goToBarNumer(); setEventBits( m_bar.readEventBits()); #if OPTION_DEBUG_CONDUCTOR if (m_realTimeEventBits | EVENT_BITS_newBarNumber) { ppDEBUG_CONDUCTOR(("m_savedNoteQueue %d m_playingDeltaTime %d",m_savedNoteQueue->space() , m_playingDeltaTime )); ppDEBUG_CONDUCTOR(("getfollowState() %d %d %d",getfollowState() , m_leadLagAdjust, m_songEventQueue->length() )); } #endif addDeltaTime(ticks); followPlaying(); while ( m_playingDeltaTime >= m_leadLagAdjust) { type = m_nextMidiEvent.type(); if (m_songEventQueue->length() == 0 && type == MIDI_PB_EOF) { ppLogInfo("The End of the song"); setEventBits(EVENT_BITS_playingStopped); m_playing = false; break; } if (type == MIDI_PB_tempo) { m_tempo.setMidiTempo(m_nextMidiEvent.data1()); m_leadLagAdjust = m_tempo.mSecToTicks( -getLatencyFix() ); } else if (type == MIDI_PB_timeSignature) { m_bar.setTimeSig(m_nextMidiEvent.data1(), m_nextMidiEvent.data2()); ppLogDebug("Midi Time Signature %d/%d", m_nextMidiEvent.data1(),m_nextMidiEvent.data2()); } else if ( type != MIDI_NONE ) // this marks the end of the piece of music { int channel = m_nextMidiEvent.channel(); // Is this this channel_muted if (!hasPianistKeyboardChannel(channel)) { if (getfollowState() >= PB_FOLLOW_earlyNotes && m_playMode == PB_PLAY_MODE_followYou && !seekingBarNumber() && m_followSkillAdvanced == false) { // Save up the notes until the pianist presses the right key if (m_savedNoteQueue->space()>0) m_savedNoteQueue->push(m_nextMidiEvent); else ppLogWarn("Warning the m_savedNoteQueue is full"); if (type == MIDI_NOTE_OFF) { if (m_savedNoteOffQueue->space()>0) m_savedNoteOffQueue->push(m_nextMidiEvent); else ppLogDebug("Warning the m_savedNoteOffQueue is full"); } } else { playTransposeEvent(m_nextMidiEvent); // Play the midi note or event ppDEBUG_CONDUCTOR(("playEvent() chan %d type %d note %d", m_nextMidiEvent.channel() , m_nextMidiEvent.type() , m_nextMidiEvent.note(), m_songEventQueue->length() )); } } } if (m_songEventQueue->length() > 0) m_nextMidiEvent = m_songEventQueue->pop(); else { ppDEBUG_CONDUCTOR(("no data in song queue")); m_nextMidiEvent.clear(); break; } m_playingDeltaTime -= m_nextMidiEvent.deltaTime() * SPEED_ADJUST_FACTOR; followPlaying(); } } void CConductor::rewind() { int chan; for ( chan = 0; chan < MAX_MIDI_CHANNELS; chan++) { m_savedMainVolume[chan] = 100; } m_lastSound = -1; m_rating.reset(); m_playingDeltaTime = 0; m_tempo.reset(); m_songEventQueue->clear(); m_savedNoteQueue->clear(); m_savedNoteOffQueue->clear(); m_wantedChordQueue->clear(); m_nextMidiEvent.clear(); m_bar.rewind(); m_goodPlayedNotes.clear(); // The good notes the pianist plays if (m_piano) m_piano->clear(); resetWantedChord(); setFollowSkillAdvanced(false); m_cfg_earlyNotesPoint = CMidiFile::ppqnAdjust(15); // was 10 playZoneEarly m_cfg_stopPointBeginner = CMidiFile::ppqnAdjust(-0); //was -3; // stop just after the beat m_cfg_stopPointAdvanced = CMidiFile::ppqnAdjust(-15); //was -3; // stop just after the beat m_cfg_imminentNotesOffPoint = CMidiFile::ppqnAdjust(-15); // look ahead and find an Notes off coming up // Annie song 25 m_cfg_playZoneEarly = CMidiFile::ppqnAdjust(Cfg::playZoneEarly()) * SPEED_ADJUST_FACTOR; // when playing along m_cfg_playZoneLate = CMidiFile::ppqnAdjust(Cfg::playZoneLate()) * SPEED_ADJUST_FACTOR; } void CConductor::init(CScore * scoreWin, CSettings* settings) { int channel; m_scoreWin = scoreWin; m_settings = settings; setFollowSkillAdvanced(false); m_followState = PB_FOLLOW_searching; this->CMidiDevice::init(); for ( channel = 0; channel < MAX_MIDI_CHANNELS; channel++) muteChannel(channel, false); assert(m_scoreWin); if (m_scoreWin) { m_scoreWin->setRatingObject(&m_rating); m_piano = m_scoreWin->getPianoObject(); } rewind(); } pianobooster-src-0.6.4/src/Chord.h0000644000175000017500000001303211304222711016051 0ustar louislouis/*********************************************************************************/ /*! @file Chord.h @brief Find the all the chords in a piece of music. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __CHORD_H__ #define __CHORD_H__ #include #include "Cfg.h" #include "MidiFile.h" #include "Queue.h" //////////////////////////////////////////////////////////////////////////////// //! @brief The part for each hand uses a different midi channel typedef enum { PB_PART_both = 200, // keep well clear of real midi channels PB_PART_right, PB_PART_left, PB_PART_accump, PB_PART_all, PB_PART_none, } whichPart_t; #define MAX_CHORD_NOTES 20 // The maximum notes in a chord well we only have 10 fingers class CNote { public: CNote() { m_part = PB_PART_none; m_pitch = 0; m_duration = 0; } CNote(whichPart_t part, int note, int duration = 0) { m_part = part; m_pitch = note; m_duration = duration; } void transpose(int amount) { m_pitch += amount; } int pitch() {return m_pitch;} whichPart_t part() {return m_part;} void setPart(whichPart_t part) {m_part = part;} static whichPart_t findHand(int midiNote, int midiChannel, int whichChannel, whichPart_t whichPart); static whichPart_t findHand(CMidiEvent midi, int channel, whichPart_t part) { return findHand(midi.note(), midi.channel(), channel, part); } static void setChannelHands(int left, int right); static void setActiveHand(whichPart_t hand){m_activeHand = hand;} static whichPart_t getActiveHand(){return m_activeHand;} static int rightHandChan() {return m_rightHandChannel;} static int leftHandChan() {return m_leftHandChannel;} static int bothHandsChan() {return m_leftHandChannel;} static int getHandChannel(whichPart_t whichPart) { return (whichPart == PB_PART_right) ? m_rightHandChannel : m_leftHandChannel;} static bool hasPianoPart(int chan) { return (m_leftHandChannel == chan || m_rightHandChannel == chan ) ? true : false;} private: whichPart_t m_part; int m_pitch; int m_duration; static int m_leftHandChannel; static int m_rightHandChannel; static whichPart_t m_activeHand; }; class CNoteRange { public: int highestNote; // The highest note in the range (often on the users piano keyboard) int lowestNote; }; class CChord { public: CChord() { clear(); } CNote getNote(int index) {return m_notes[index];} int length() {return m_length;} void setDeltaTime(int delta) {m_deltaTime = delta;} int getDeltaTime() {return m_deltaTime;} void clear() { m_length = 0; m_deltaTime = 0;} void addNote(whichPart_t part, int note, int duration = 0); bool removeNote(int note); bool searchChord(int note, int transpose = 0); int trimOutOfRangeNotes(int transpose); void transpose(int amount) { for (int i = 0; i < m_length; i++) { m_notes[i].transpose(amount); } } static void setPianoRange(int lowestNote, int highestNote ){ m_cfg_highestPianoNote = highestNote; // The highest note on the users piano keyboard; m_cfg_lowestPianoNote = lowestNote; } static bool isNotePlayable(int note, int transpose ) { note += transpose; if (note >= m_cfg_lowestPianoNote && note <= m_cfg_highestPianoNote) return true; return false; } static bool isHandPlayable(whichPart_t hand) { if (CNote::getActiveHand() == PB_PART_both) return true; if (CNote::getActiveHand() == hand) return true; return false; } private: int m_deltaTime; CNote m_notes[MAX_CHORD_NOTES]; int m_length; static int m_cfg_highestPianoNote; // The highest note on the users piano keyboard; static int m_cfg_lowestPianoNote; }; // Define a chord class CFindChord { public: CFindChord() { reset(); } void reset() { m_noteGapTime = 0; m_cordSpanGapTime = 0; m_completeChord.clear(); m_currentChord.clear(); m_cfg_ChordNoteGap = CMidiFile::ppqnAdjust(Cfg::chordNoteGap()); m_cfg_ChordMaxLength = CMidiFile::ppqnAdjust(Cfg::chordMaxLength()); } CChord getChord() { CChord chord; chord = m_completeChord; m_completeChord.clear(); return chord; } bool findChord(CMidiEvent midi, int channel, whichPart_t part); private: int m_noteGapTime; int m_cordSpanGapTime; CChord m_currentChord; CChord m_completeChord; int m_cfg_ChordNoteGap; int m_cfg_ChordMaxLength; }; #endif // __CHORD_H__ pianobooster-src-0.6.4/src/Chord.cpp0000644000175000017500000001225011304222711016405 0ustar louislouis/*********************************************************************************/ /*! @file Chord.cpp @brief Reads ahead from the songdata and collects chords to be matched. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include "Chord.h" #include "Cfg.h" int CNote::m_leftHandChannel = -2; int CNote::m_rightHandChannel = -2; whichPart_t CNote::m_activeHand = PB_PART_both; int CChord::m_cfg_highestPianoNote = 127; // The highest note on the users piano keyboard; int CChord::m_cfg_lowestPianoNote = 0; whichPart_t CNote::findHand(int midiNote, int midiChannel, int whichChannel, whichPart_t whichPart) { whichPart_t hand = PB_PART_none; // exit if it is not for this channel if (midiChannel != whichChannel) { // return none if this is not being used with the other hand. if (CNote::hasPianoPart(whichChannel) == false || CNote::hasPianoPart(midiChannel) == false) return PB_PART_none; } if (midiChannel == CNote::rightHandChan()) hand = PB_PART_right; else if (midiChannel == CNote::leftHandChan()) hand = PB_PART_left; else { if (midiChannel == whichChannel) { if (midiNote >= MIDDLE_C) hand = PB_PART_right; else hand = PB_PART_left; } } if (whichPart == PB_PART_left && hand == PB_PART_right) hand = PB_PART_none; if (whichPart == PB_PART_right && hand == PB_PART_left) hand = PB_PART_none; return hand; } void CChord::addNote(whichPart_t part, int note, int duration) { if (m_length >= MAX_CHORD_NOTES) { ppDEBUG(("Over the chord note limit")); return; } if (searchChord(note)) // don't add duplicates return; m_notes[m_length] = CNote(part, note, duration); m_length++; } void CNote::setChannelHands(int left, int right) { m_leftHandChannel = left; m_rightHandChannel = right; } //////////////// CChord ///////////////////// bool CChord::removeNote(int note) { int i; bool noteFound = false; for (i = 0; i < MAX_CHORD_NOTES; i++) { if (i >= m_length) break; if (noteFound == false) { if (getNote(i).pitch() == note) noteFound = true; } else { // shove everything else up to remove the note m_notes[i-1] = getNote(i); } } if (noteFound) m_length--; return noteFound; } bool CChord::searchChord(int note, int transpose) { int i; for (i = 0; i < m_length; i++) { if (getNote(i).pitch() + transpose == note) return true; } return false; } int CChord::trimOutOfRangeNotes(int transpose) { int i; int removedNotes = 0; for (i = 0; i < MAX_CHORD_NOTES; i++) { if (i >= m_length) break; if (!isNotePlayable(getNote(i).pitch(), transpose) || !isHandPlayable(getNote(i).part())) removedNotes++; // remove the note else if (removedNotes) { // shove everything else up to remove the note m_notes[i-removedNotes] = getNote(i); } } m_length -= removedNotes; return m_length; } bool CFindChord::findChord(CMidiEvent midi, int channel, whichPart_t part) { bool foundChord = false; if (midi.type() == MIDI_PB_EOF) { if (m_currentChord.length() > 0) { m_completeChord = m_currentChord; foundChord = true; } return foundChord; } m_noteGapTime += midi.deltaTime(); if ((m_noteGapTime >= m_cfg_ChordNoteGap || m_cordSpanGapTime > m_cfg_ChordMaxLength) && m_currentChord.length() > 0 ) { foundChord = true; m_completeChord = m_currentChord; m_currentChord.clear(); } if (midi.type() == MIDI_NOTE_ON) { whichPart_t hand = CNote::findHand( midi, channel, part ); if ( hand != PB_PART_none) { m_currentChord.addNote(hand, midi.note()); m_currentChord.setDeltaTime(m_noteGapTime + m_currentChord.getDeltaTime()); if (m_currentChord.length() <= 1) m_cordSpanGapTime = 0; else m_cordSpanGapTime += m_noteGapTime; // measure the span of the cord m_noteGapTime = 0; } } return foundChord; } pianobooster-src-0.6.4/src/Cfg.h0000644000175000017500000001211211304222711015507 0ustar louislouis/*********************************************************************************/ /*! @file Cfg.h @brief Contains all the configuration Information. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __CFG_H__ #define __CFG_H__ #define OPTION_BENCHMARK_TEST 0 #if OPTION_BENCHMARK_TEST #define BENCHMARK_INIT() benchMarkInit() #define BENCHMARK(id,mesg) benchMark(id,mesg) #define BENCHMARK_RESULTS() benchMarkResults() #else #define BENCHMARK_INIT() #define BENCHMARK(id,mesg) #define BENCHMARK_RESULTS() #endif class CColour { public: CColour() { red = green = blue = 0; } CColour(double r, double g, double b) { red = static_cast(r); green = static_cast(g); blue = static_cast(b); } float red, green, blue; bool operator==(CColour colour) { if (red == colour.red && green == colour.green && blue == colour.blue) return true; return false; } }; /*! * @brief Contains all the configuration Information. */ class Cfg { public: static float staveStartX() {return 20;} static float staveEndX() {return m_staveEndX;} static float playZoneX() {return scrollStartX() + ( staveEndX() - scrollStartX())* 0.4f;} static float clefX() {return staveStartX() + 20;} static float timeSignatureX() {return clefX() + 25;} static float keySignatureX() {return timeSignatureX() + 25;} static float scrollStartX() {return keySignatureX() + 64;} static float pianoX() {return 25;} static float staveThickness() {return 1;} static int playZoneEarly() {return m_playZoneEarly;} static int playZoneLate() {return m_playZoneLate;} static int silenceTimeOut() {return 8000;} // the time in msec before everything goes quiet static int chordNoteGap() {return 10;} // all notes in a cord must be spaced less than this a gap static int chordMaxLength() {return 20;} // the max time between the start and end of a cord static CColour menuColour() {return CColour(0.1, 0.6, 0.6);} static CColour menuSelectedColour(){return CColour(0.7, 0.7, 0.1);} static CColour staveColour() {return CColour(0.1, 0.7, 0.1);} // green static CColour staveColourDim() {return CColour(0.15, 0.40, 0.15);} // grey static CColour noteColour() {return CColour(0.1, 0.9, 0.1);} // green static CColour noteColourDim() {return CColour(0.25, 0.45, 0.25);} // green //static CColour playedGoodColour() {return CColour(0.6, 0.6, 1.0);} // grey static CColour playedGoodColour() {return CColour(0.5, 0.6, 1.0);} // purple 0.6, 0.6, 1.0 static CColour playedBadColour() {return CColour(0.8, 0.3, 0.8);} // orange 0.7, 0.0, 0.0 static CColour playedStoppedColour() {return CColour(1.0, 0.8, 0.0);} // bright orange static CColour backgroundColour() {return CColour(0.0, 0.0, 0.0);} // black static CColour barMarkerColour() {return CColour(0.3, 0.25, 0.25);} // grey static CColour beatMarkerColour() {return CColour(0.25, 0.2, 0.2);} // grey static CColour pianoGoodColour() {return playedGoodColour();} static CColour pianoBadColour() {return CColour(1.0, 0.0, 0.0);} static CColour noteNameColour() {return CColour(1.0, 1.0, 1.0);} static void setStaveEndX(float x) { m_staveEndX = x; } static int getAppX(){return m_appX;} static int getAppY(){return m_appY;} static int getAppWidth(){return m_appWidth;} static int getAppHeight(){return m_appHeight;} static void setAppDimentions(int x, int y,int width, int height) { m_appX = x; m_appY = y; m_appWidth = width; m_appHeight = height; } static int defaultWrongPatch() {return 7;} // Starts at 1 static int defaultRightPatch() {return 1;} // Starts at 1 static int logLevel; static bool quickStart; static bool experimentalTempo; static int experimentalSwapInterval; private: static float m_staveEndX; static int m_appX, m_appY, m_appWidth, m_appHeight; static const int m_playZoneEarly; static const int m_playZoneLate; }; #endif //__CFG_H__ pianobooster-src-0.6.4/src/Cfg.cpp0000644000175000017500000000252411304222711016050 0ustar louislouis/*********************************************************************************/ /*! @file Cfg.cpp @brief xxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include "Cfg.h" float Cfg::m_staveEndX; int Cfg::logLevel = 1; bool Cfg::quickStart = false; int Cfg::m_appX; int Cfg::m_appY; int Cfg::m_appWidth; int Cfg::m_appHeight; bool Cfg::experimentalTempo = false; int Cfg::experimentalSwapInterval = -1; const int Cfg::m_playZoneEarly = 25; // Was 25 const int Cfg::m_playZoneLate = 25; pianobooster-src-0.6.4/src/CMakeLists.txt0000644000175000017500000001514711304222711017412 0ustar louislouis# Cmake File for Piano Booster # for the debug build type cmake -DCMAKE_BUILD_TYPE=Debug SET(CMAKE_BUILD_TYPE Release) SET(CMAKE_VERBOSE_MAKEFILE OFF) SET(USE_FLUIDSYNTH OFF) # The inplace directory is mainly for windows builds # SET(FLUIDSYNTH_INPLACE_DIR C:/download/misc/ljb/fluidsynth-1.0.9) SET(FLUIDSYNTH_INPLACE_DIR /home/louis/build/fluidsynth-1.0.9) # Testing precompiled headers it does not work -- leave as OFF. SET(USE_PCH OFF) cmake_minimum_required(VERSION 2.4) if(COMMAND cmake_policy) cmake_policy(SET CMP0003 NEW) endif(COMMAND cmake_policy) IF(WIN32) MESSAGE("GUI system is WIN32 ${CMAKE_GENERATOR}") SET(CMAKE_COLOR_MAKEFILE OFF) ENDIF(WIN32) # set project's name PROJECT( pianobooster ) # enable warnings ADD_DEFINITIONS(-Wall) # by default only QtCore and QtGui modules are enabled # other modules must be enabled like this: SET(QT_USE_QTOPENGL TRUE) SET(QT_USE_QTXML TRUE) FIND_PACKAGE( OpenGL REQUIRED ) # this command finds Qt4 libraries and sets all required variables # note that it's Qt4, not QT4 or qt4 FIND_PACKAGE( Qt4 REQUIRED ) # add some useful macros and variables # (QT_USE_FILE is a variable defined by FIND_PACKAGE( Qt4 ) that contains a path to CMake script) INCLUDE( ${QT_USE_FILE} ) IF (USE_PCH) INCLUDE(precompile/PCHSupport_26.cmake) INCLUDE_DIRECTORIES( precompile .) ENDIF(USE_PCH) # Add in the link libraries for each operating system IF(${CMAKE_SYSTEM} MATCHES "Linux") #FIND_PACKAGE(PkgConfig REQUIRED) #PKG_CHECK_MODULES(ALSA REQUIRED alsa>=1.0) #IF(ALSA_FOUND) ADD_DEFINITIONS(-D__LINUX_ALSASEQ__) LINK_LIBRARIES (asound) #ELSE(ALSA_FOUND) # MESSAGE(FATAL_ERROR "Please install the 'libasound2-dev' package and then try again") #ENDIF(ALSA_FOUND) ENDIF(${CMAKE_SYSTEM} MATCHES "Linux") IF(${CMAKE_SYSTEM} MATCHES "Windows") # FIND_PACKAGE(WINDRES REQUIRED) ADD_DEFINITIONS(-D__WINDOWS_MM__ -D_WIN32) LINK_LIBRARIES(winmm opengl32) ENDIF(${CMAKE_SYSTEM} MATCHES "Windows") IF(${CMAKE_SYSTEM} MATCHES "Darwin") ADD_DEFINITIONS(-D__MACOSX_CORE__) LINK_LIBRARIES("-framework CoreMidi -framework CoreAudio -framework CoreFoundation -framework OpenGL") ENDIF(${CMAKE_SYSTEM} MATCHES "Darwin") IF(USE_FLUIDSYNTH) ADD_DEFINITIONS(-DPB_USE_FLUIDSYNTH) MESSAGE("Building using fluidsynth") SET( PB_BASE_SRCS MidiDeviceFluidSynth.cpp ) IF(FLUIDSYNTH_INPLACE_DIR) INCLUDE_DIRECTORIES(${FLUIDSYNTH_INPLACE_DIR}/include/) IF(WIN32) LINK_LIBRARIES( ${FLUIDSYNTH_INPLACE_DIR}/src/.libs/libfluidsynth.dll.a) ENDIF(WIN32) IF(UNIX) LINK_LIBRARIES(${FLUIDSYNTH_INPLACE_DIR}/src/.libs/libfluidsynth.so) ENDIF(UNIX) ELSEIF(FLUIDSYNTH_INPLACE_DIR) LINK_LIBRARIES( fluidsynth) ENDIF(FLUIDSYNTH_INPLACE_DIR) ENDIF(USE_FLUIDSYNTH) # we need this to be able to include headers produced by uic in our code # (CMAKE_BINARY_DIR holds a path to the build directory, while INCLUDE_DIRECTORIES() works just like INCLUDEPATH from qmake) INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_BINARY_DIR} ${OPENGL_INCLUDE_DIR} ) # tell CMake what libraries our executable needs, # luckily FIND_PACKAGE prepared QT_LIBRARIES variable for us: LINK_LIBRARIES( ${QT_LIBRARIES} ) SET(PB_BASE_SRCS MidiFile.cpp MidiTrack.cpp Song.cpp Conductor.cpp Util.cpp Chord.cpp Tempo.cpp MidiDevice.cpp MidiDeviceRt.cpp rtmidi/RtMidi.cpp ${PB_BASE_SRCS}) SET(PB_BASE_HDR MidiFile.h MidiTrack.h Song.h Conductor.h Rating.h Util.h Chord.h Tempo.h MidiDevice.h rtmidi/RtMidi.h) # with SET() command you can change variables or define new ones # here we define PIANOBOOSTER_SRCS variable that contains a list of all .cpp files # note that we don't need \ at the end of line SET( PIANOBOOSTER_SRCS QtMain.cpp QtWindow.cpp GuiTopBar.cpp GuiSidePanel.cpp GuiMidiSetupDialog.cpp GuiKeyboardSetupDialog.cpp GuiPreferencesDialog.cpp GuiSongDetailsDialog.cpp GuiLoopingPopup.cpp GlView.cpp ${PB_BASE_SRCS} StavePosition.cpp Score.cpp Cfg.cpp Piano.cpp Draw.cpp Scroll.cpp Notation.cpp TrackList.cpp Rating.cpp Bar.cpp Settings.cpp Merge.cpp #Band.cpp pianobooster.rc pianobooster.ico # precompile.h ) # another list, this time it includes all header files that should be treated with moc SET( PIANOBOOSTER_MOC_HDRS QtWindow.h GlView.h GuiTopBar.h GuiSidePanel.h GuiMidiSetupDialog.h GuiKeyboardSetupDialog.h GuiPreferencesDialog.h GuiSongDetailsDialog.h GuiLoopingPopup.h ) # some .ui files SET( PIANOBOOSTER_UIS ./GuiTopBar.ui ./GuiSidePanel.ui ./GuiMidiSetupDialog.ui ./GuiKeyboardSetupDialog.ui ./GuiPreferencesDialog.ui ./GuiSongDetailsDialog.ui ./GuiLoopingPopup.ui ) # and finally an resource file SET( PIANOBOOSTER_RCS ./application.qrc ) # this command will generate rules that will run rcc on all files from PIANOBOOSTER_RCS # in result PIANOBOOSTER_RC_SRCS variable will contain paths to files produced by rcc QT4_ADD_RESOURCES( PIANOBOOSTER_RC_SRCS ${PIANOBOOSTER_RCS} ) # this will run uic on .ui files: QT4_WRAP_UI( PIANOBOOSTER_UI_HDRS ${PIANOBOOSTER_UIS} ) # and finally this will run moc: QT4_WRAP_CPP( PIANOBOOSTER_MOC_SRCS ${PIANOBOOSTER_MOC_HDRS} ) # here we instruct CMake to build "pianobooster" executable from all of the source files IF(APPLE) ADD_EXECUTABLE( pianobooster MACOSX_BUNDLE ${PIANOBOOSTER_SRCS} ${PIANOBOOSTER_MOC_SRCS} ${PIANOBOOSTER_RC_SRCS} ${PIANOBOOSTER_UI_HDRS}) ENDIF(APPLE) IF(UNIX) ADD_EXECUTABLE( pianobooster pianobooster.rc ${PIANOBOOSTER_SRCS} ${PIANOBOOSTER_MOC_SRCS} ${PIANOBOOSTER_RC_SRCS} ${PIANOBOOSTER_UI_HDRS} ) ENDIF(UNIX) IF(WIN32) ADD_EXECUTABLE( pianobooster WIN32 pianobooster.rc ${PIANOBOOSTER_SRCS} ${PIANOBOOSTER_MOC_SRCS} ${PIANOBOOSTER_RC_SRCS} ${PIANOBOOSTER_UI_HDRS} ) ENDIF(WIN32) SET_TARGET_PROPERTIES(pianobooster PROPERTIES LINK_FLAGS "-mwindows") IF (USE_PCH) ADD_PRECOMPILED_HEADER( pianobooster ${CMAKE_CURRENT_SOURCE_DIR}/precompile/precompile.h ) ENDIF (USE_PCH) INSTALL( FILES pianobooster.desktop DESTINATION share/applications ) INSTALL(TARGETS pianobooster RUNTIME DESTINATION bin) #INSTALL( index.docbook INSTALL_DESTINATION ${HTML_INSTALL_DIR}/en SUBDIR kmidimon ) INSTALL( FILES ../README.txt DESTINATION share/doc/pianobooster ) INSTALL ( FILES images/pianobooster.png DESTINATION share/pixmaps ) pianobooster-src-0.6.4/src/Bar.h0000644000175000017500000001050211304222711015515 0ustar louislouis/*********************************************************************************/ /*! @file Bar.h @brief xxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #ifndef __BAR_H__ #define __BAR_H__ #include "MidiFile.h" // The event bits can be ORed together #define EVENT_BITS_playingStopped 0x0001 //set when we reach the end of piece #define EVENT_BITS_forceFullRedraw 0x0002 // force the whole screen to be redrawn #define EVENT_BITS_forceRatingRedraw 0x0004 // force the score to be redrawn #define EVENT_BITS_newBarNumber 0x0008 // force the bar number to be redrawn #define EVENT_BITS_UptoBarReached 0x0010 // Used for looping when playing between two bars. typedef unsigned long eventBits_t; // controls the bar numbers class CBar { public: CBar() { reset(); } // You MUST clear the time sig to 0 first before setting an new start Time Signature // at the start of the piece of music void setTimeSig(int top, int bottom); int getTimeSigTop() {return m_currentTimeSigTop;} // The Numerator int getBeatLength() {return m_beatLength;} int getBarLength() {return m_barLength;} // in ppqn void setPlayFromBar(double bar); void setPlayFromBar(int bar, int beat = 0, int ticks = 0); void reset() { setTimeSig( 0 , 0); m_playFromBar = 0.0; m_playUptoBar = 0.0; m_loopingBars = 0.0; m_seekingBarNumber = false; m_flushTicks = false; m_eventBits = 0; setupEnableFlags(); } void setPlayUptoBar(double bar); double getPlayUptoBar(){ return m_playUptoBar;} void setLoopingBars(double bars); double getLoopingBars(){ return m_loopingBars;} void rewind() { int top = m_startTimeSigTop; int bottom = m_startTimeSigBottom; setTimeSig( 0 , 0); setTimeSig(top, bottom); checkGotoBar(); } void getTimeSig(int *top, int *bottom) { *top = m_currentTimeSigTop; *bottom = m_currentTimeSigBottom; } //return true if bar number has changed int addDeltaTime(int ticks); // int getBarNumber(){ return m_barCounter;} double getCurrentBarPos() { return m_barCounter + static_cast(m_beatCounter)/m_currentTimeSigBottom + static_cast(m_deltaTime)/(m_beatLength * m_currentTimeSigBottom * SPEED_ADJUST_FACTOR); } bool seekingBarNumber() { return m_seekingBarNumber;} // get and reset the current bar event bits eventBits_t readEventBits() { eventBits_t bits = m_eventBits; m_eventBits = 0; return bits; } int goToBarNumer(); private: void checkGotoBar(); void setupEnableFlags() { m_enableLooping = (m_loopingBars > 0.0)?true:false; m_enablePlayFromBar = (m_enableLooping || m_playFromBar > 0.0)?true:false; } int m_deltaTime; int m_beatLength; //in ppqn ticks int m_barLength; // m_beatLength * getTimeSigTop() (also in ppqn ticks) int m_startTimeSigTop; // The time Sig at the start of the piece int m_startTimeSigBottom; int m_currentTimeSigTop; // The current time Sig at the start of the piece int m_currentTimeSigBottom; int m_barCounter; int m_beatCounter; double m_playFromBar; double m_playUptoBar; double m_loopingBars; int m_playFromBeat; int m_playFromTicks; bool m_seekingBarNumber; bool m_flushTicks; eventBits_t m_eventBits; bool m_enableLooping; bool m_enablePlayFromBar; }; #endif // __BAR_H__ pianobooster-src-0.6.4/src/Bar.cpp0000644000175000017500000000733311304222711016060 0ustar louislouis/*********************************************************************************/ /*! @file Bar.cpp @brief xxx. @author L. J. Barman Copyright (c) 2008-2009, L. J. Barman, all rights reserved This file is part of the PianoBooster application PianoBooster 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. PianoBooster 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 PianoBooster. If not, see . */ /*********************************************************************************/ #include "Bar.h" #define OPTION_DEBUG_BAR 0 #if OPTION_DEBUG_BAR #define ppDEBUG_BAR(args) ppLogDebug args #else #define ppDEBUG_BAR(args) #endif void CBar::setTimeSig(int top, int bottom) { m_currentTimeSigTop = top; m_currentTimeSigBottom = bottom; if (bottom == 0 || m_startTimeSigBottom == 0) { m_startTimeSigTop = top; m_startTimeSigBottom = bottom; if (bottom == 0 ) { m_currentTimeSigTop = 4; m_currentTimeSigBottom = 4; m_deltaTime = 0; m_beatCounter = 0; m_barCounter = 0; } } m_beatLength = (CMidiFile::getPulsesPerQuarterNote() *4)/ m_currentTimeSigBottom; m_barLength = m_beatLength * getTimeSigTop(); } int CBar::addDeltaTime(int ticks) { if (m_flushTicks == true && ticks != 0) // ignore this set of ticks { ppDEBUG_BAR(("addDeltaTime m_flushTicks ticks %d", ticks)); m_flushTicks = false; return 0; } m_deltaTime +=ticks; if (ticks && m_enablePlayFromBar) checkGotoBar(); while (m_deltaTime > m_beatLength * SPEED_ADJUST_FACTOR) { m_deltaTime -= m_beatLength * SPEED_ADJUST_FACTOR; m_beatCounter++; if (m_beatCounter >= m_currentTimeSigTop) { m_barCounter++; m_beatCounter=0; ppLogWarn("Bar number %d", m_barCounter); m_eventBits |= EVENT_BITS_newBarNumber; } } return ticks; } int CBar::goToBarNumer() { int ticks; ticks = static_cast((m_playFromBar - getCurrentBarPos()) * m_beatLength * SPEED_ADJUST_FACTOR + 1); addDeltaTime(ticks); return ticks; } void CBar::checkGotoBar() { double currentBar = getCurrentBarPos(); ppDEBUG_BAR(("checkGotoBar currentBarPos %.1f", currentBar)); if (currentBar < m_playFromBar ) m_seekingBarNumber = true; else { if (m_seekingBarNumber == true) m_flushTicks = true; // now throw away ticks before we start the music m_seekingBarNumber = false; if (m_enableLooping && currentBar > m_playUptoBar ) m_eventBits |= EVENT_BITS_UptoBarReached; } } void CBar::setPlayFromBar(double bar) { m_playFromBar = bar; m_playUptoBar = m_playFromBar + m_loopingBars; setupEnableFlags(); checkGotoBar(); } void CBar::setPlayFromBar(int bar, int beat, int ticks) { double playFromBar = bar; setPlayFromBar( playFromBar); } void CBar::setPlayUptoBar(double endBar) { setLoopingBars(endBar - m_playUptoBar); } void CBar::setLoopingBars(double bars) { if (bars < 0.0) bars = 0; m_loopingBars = bars; m_playUptoBar = m_playFromBar + m_loopingBars; setupEnableFlags(); checkGotoBar(); } pianobooster-src-0.6.4/build/BUILD.txt0000644000175000017500000000642311304222711016557 0ustar louislouis=============================================================================================== TO COMPILE THE SOURCE CODE IN LINUX =============================================================================================== Ensure that the following packages 'cmake', 'libqt4-dev', 'libasound2-dev' and 'build-essential" are installed . In the PianoBooster directory type "cd build" to change to the "build" directory then type "cmake ../src", followed by "make". Finally as root type "make install". To build a debug version create a dir called "debug" and change to that dir and then type "cmake -DCMAKE_BUILD_TYPE=Debug ../src" (Alternatively you can use qmake followed by make in the src directory.) If you make changes to the source code then please post details on the forum. =============================================================================================== TO COMPILE THE SOURCE CODE IN MacOSX =============================================================================================== Install latest XCode (from Apple Developer Connection, free registration required) Install CMake and QT libraries (either from source or via Fink or MacPorts) Generate XCode project file, via 'cmake -G Xcode ../src' Open the project file in XCode, set whatever options you like (universal or single architecture, debug or release etc.) and compile To make a self contained application bundle use QT's macdeployqt tool (included in QT 4.5.0) If you make changes to the source code then please post details on the forum. =============================================================================================== TO COMPILE THE SOURCE CODE IN WINDOWS =============================================================================================== To compile in Windows install the Open Source version of Qt and CMake and optionally Geany. When installing Qt select the option to download and install the MinGW compiler. Open the Qt Command Prompt and then change to the "PianoBooster\build" directory and then type the command below. "C:\Program Files\CMake 2.6\bin\cmake.exe" -G "MinGW Makefiles" ..\src Once this is completed type "make". Or alternatively you can install QtCreator and then open the painobooster.pro If you make changes to the source code then please post details on the forum. =============================================================================================== LICENSE =============================================================================================== Piano Booster is fully copyrighted by the author and all rights are reserved. PianoBooster is free software (Open Source 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. PianoBooster 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 in the file "gplv3.txt" or from the web site . pianobooster-src-0.6.4/src/rtmidi/RtMidi.h0000644000175000017500000002520111304222711017473 0ustar louislouis/**********************************************************************/ /*! \class RtMidi \brief An abstract base class for realtime MIDI input/output. This class implements some common functionality for the realtime MIDI input/output subclasses RtMidiIn and RtMidiOut. RtMidi WWW site: http://music.mcgill.ca/~gary/rtmidi/ RtMidi: realtime MIDI i/o C++ classes Copyright (c) 2003-2009 Gary P. Scavone Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Any person wishing to distribute modifications to the Software is requested to send the modifications to the original developer so that they can be incorporated into the canonical version. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /**********************************************************************/ // RtMidi: Version 1.0.8 #ifndef RTMIDI_H #define RTMIDI_H #include "RtError.h" #include class RtMidi { public: //! Pure virtual openPort() function. virtual void openPort( unsigned int portNumber = 0, const std::string portName = std::string( "RtMidi" ) ) = 0; //! Pure virtual openVirtualPort() function. virtual void openVirtualPort( const std::string portName = std::string( "RtMidi" ) ) = 0; //! Pure virtual getPortCount() function. virtual unsigned int getPortCount() = 0; //! Pure virtual getPortName() function. virtual std::string getPortName( unsigned int portNumber = 0 ) = 0; //! Pure virtual closePort() function. virtual void closePort( void ) = 0; protected: RtMidi(); virtual ~RtMidi() {}; // A basic error reporting function for internal use in the RtMidi // subclasses. The behavior of this function can be modified to // suit specific needs. void error( RtError::Type type ); void *apiData_; bool connected_; std::string errorString_; }; /**********************************************************************/ /*! \class RtMidiIn \brief A realtime MIDI input class. This class provides a common, platform-independent API for realtime MIDI input. It allows access to a single MIDI input port. Incoming MIDI messages are either saved to a queue for retrieval using the getMessage() function or immediately passed to a user-specified callback function. Create multiple instances of this class to connect to more than one MIDI device at the same time. With the OS-X and Linux ALSA MIDI APIs, it is also possible to open a virtual input port to which other MIDI software clients can connect. by Gary P. Scavone, 2003-2008. */ /**********************************************************************/ #include #include class RtMidiIn : public RtMidi { public: //! User callback function type definition. typedef void (*RtMidiCallback)( double timeStamp, std::vector *message, void *userData); //! Default constructor that allows an optional client name. /*! An exception will be thrown if a MIDI system initialization error occurs. */ RtMidiIn( const std::string clientName = std::string( "RtMidi Input Client") ); //! If a MIDI connection is still open, it will be closed by the destructor. ~RtMidiIn(); //! Open a MIDI input connection. /*! An optional port number greater than 0 can be specified. Otherwise, the default or first port found is opened. */ void openPort( unsigned int portNumber = 0, const std::string Portname = std::string( "RtMidi Input" ) ); //! Create a virtual input port, with optional name, to allow software connections (OS X and ALSA only). /*! This function creates a virtual MIDI input port to which other software applications can connect. This type of functionality is currently only supported by the Macintosh OS-X and Linux ALSA APIs (the function does nothing for the other APIs). */ void openVirtualPort( const std::string portName = std::string( "RtMidi Input" ) ); //! Set a callback function to be invoked for incoming MIDI messages. /*! The callback function will be called whenever an incoming MIDI message is received. While not absolutely necessary, it is best to set the callback function before opening a MIDI port to avoid leaving some messages in the queue. */ void setCallback( RtMidiCallback callback, void *userData = 0 ); //! Cancel use of the current callback function (if one exists). /*! Subsequent incoming MIDI messages will be written to the queue and can be retrieved with the \e getMessage function. */ void cancelCallback(); //! Close an open MIDI connection (if one exists). void closePort( void ); //! Return the number of available MIDI input ports. unsigned int getPortCount(); //! Return a string identifier for the specified MIDI input port number. /*! An exception is thrown if an invalid port specifier is provided. */ std::string getPortName( unsigned int portNumber = 0 ); //! Set the maximum number of MIDI messages to be saved in the queue. /*! If the queue size limit is reached, incoming messages will be ignored. The default limit is 1024. */ void setQueueSizeLimit( unsigned int queueSize ); //! Specify whether certain MIDI message types should be queued or ignored during input. /*! By default, MIDI timing and active sensing messages are ignored during message input because of their relative high data rates. MIDI sysex messages are ignored by default as well. Variable values of "true" imply that the respective message type will be ignored. */ void ignoreTypes( bool midiSysex = true, bool midiTime = true, bool midiSense = true ); //! Fill the user-provided vector with the data bytes for the next available MIDI message in the input queue and return the event delta-time in seconds. /*! This function returns immediately whether a new message is available or not. A valid message is indicated by a non-zero vector size. An exception is thrown if an error occurs during message retrieval or an input connection was not previously established. */ double getMessage( std::vector *message ); // A MIDI structure used internally by the class to store incoming // messages. Each message represents one and only one MIDI message. struct MidiMessage { std::vector bytes; double timeStamp; // Default constructor. MidiMessage() :bytes(3), timeStamp(0.0) {} }; // The RtMidiInData structure is used to pass private class data to // the MIDI input handling function or thread. struct RtMidiInData { std::queue queue; MidiMessage message; unsigned int queueLimit; unsigned char ignoreFlags; bool doInput; bool firstMessage; void *apiData; bool usingCallback; void *userCallback; void *userData; bool continueSysex; // Default constructor. RtMidiInData() : queueLimit(1024), ignoreFlags(7), doInput(false), firstMessage(true), apiData(0), usingCallback(false), userCallback(0), userData(0), continueSysex(false) {} }; private: void initialize( const std::string& clientName ); RtMidiInData inputData_; }; /**********************************************************************/ /*! \class RtMidiOut \brief A realtime MIDI output class. This class provides a common, platform-independent API for MIDI output. It allows one to probe available MIDI output ports, to connect to one such port, and to send MIDI bytes immediately over the connection. Create multiple instances of this class to connect to more than one MIDI device at the same time. by Gary P. Scavone, 2003-2008. */ /**********************************************************************/ class RtMidiOut : public RtMidi { public: //! Default constructor that allows an optional client name. /*! An exception will be thrown if a MIDI system initialization error occurs. */ RtMidiOut( const std::string clientName = std::string( "RtMidi Output Client" ) ); //! The destructor closes any open MIDI connections. ~RtMidiOut(); //! Open a MIDI output connection. /*! An optional port number greater than 0 can be specified. Otherwise, the default or first port found is opened. An exception is thrown if an error occurs while attempting to make the port connection. */ void openPort( unsigned int portNumber = 0, const std::string portName = std::string( "RtMidi Output" ) ); //! Close an open MIDI connection (if one exists). void closePort(); //! Create a virtual output port, with optional name, to allow software connections (OS X and ALSA only). /*! This function creates a virtual MIDI output port to which other software applications can connect. This type of functionality is currently only supported by the Macintosh OS-X and Linux ALSA APIs (the function does nothing with the other APIs). An exception is thrown if an error occurs while attempting to create the virtual port. */ void openVirtualPort( const std::string portName = std::string( "RtMidi Output" ) ); //! Return the number of available MIDI output ports. unsigned int getPortCount(); //! Return a string identifier for the specified MIDI port type and number. /*! An exception is thrown if an invalid port specifier is provided. */ std::string getPortName( unsigned int portNumber = 0 ); //! Immediately send a single message out an open MIDI output port. /*! An exception is thrown if an error occurs during output or an output connection was not previously established. */ void sendMessage( std::vector *message ); private: void initialize( const std::string& clientName ); }; #endif pianobooster-src-0.6.4/src/rtmidi/RtMidi.cpp0000644000175000017500000021564611304222711020044 0ustar louislouis/**********************************************************************/ /*! \class RtMidi \brief An abstract base class for realtime MIDI input/output. This class implements some common functionality for the realtime MIDI input/output subclasses RtMidiIn and RtMidiOut. RtMidi WWW site: http://music.mcgill.ca/~gary/rtmidi/ RtMidi: realtime MIDI i/o C++ classes Copyright (c) 2003-2009 Gary P. Scavone Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Any person wishing to distribute modifications to the Software is requested to send the modifications to the original developer so that they can be incorporated into the canonical version. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /**********************************************************************/ // RtMidi: Version 1.0.8 #include "RtMidi.h" #include //*********************************************************************// // Common RtMidi Definitions //*********************************************************************// RtMidi :: RtMidi() : apiData_( 0 ), connected_( false ) { } void RtMidi :: error( RtError::Type type ) { if (type == RtError::WARNING) { std::cerr << '\n' << errorString_ << "\n\n"; } else if (type == RtError::DEBUG_WARNING) { #if defined(__RTMIDI_DEBUG__) std::cerr << '\n' << errorString_ << "\n\n"; #endif } else { std::cerr << '\n' << errorString_ << "\n\n"; throw RtError( errorString_, type ); } } //*********************************************************************// // Common RtMidiIn Definitions //*********************************************************************// RtMidiIn :: RtMidiIn( const std::string clientName ) : RtMidi() { this->initialize( clientName ); } void RtMidiIn :: setCallback( RtMidiCallback callback, void *userData ) { if ( inputData_.usingCallback ) { errorString_ = "RtMidiIn::setCallback: a callback function is already set!"; error( RtError::WARNING ); return; } if ( !callback ) { errorString_ = "RtMidiIn::setCallback: callback function value is invalid!"; error( RtError::WARNING ); return; } inputData_.userCallback = (void *) callback; inputData_.userData = userData; inputData_.usingCallback = true; } void RtMidiIn :: cancelCallback() { if ( !inputData_.usingCallback ) { errorString_ = "RtMidiIn::cancelCallback: no callback function was set!"; error( RtError::WARNING ); return; } inputData_.userCallback = 0; inputData_.userData = 0; inputData_.usingCallback = false; } void RtMidiIn :: setQueueSizeLimit( unsigned int queueSize ) { inputData_.queueLimit = queueSize; } void RtMidiIn :: ignoreTypes( bool midiSysex, bool midiTime, bool midiSense ) { inputData_.ignoreFlags = 0; if ( midiSysex ) inputData_.ignoreFlags = 0x01; if ( midiTime ) inputData_.ignoreFlags |= 0x02; if ( midiSense ) inputData_.ignoreFlags |= 0x04; } double RtMidiIn :: getMessage( std::vector *message ) { message->clear(); if ( inputData_.usingCallback ) { errorString_ = "RtMidiIn::getNextMessage: a user callback is currently set for this port."; error( RtError::WARNING ); return 0.0; } if ( inputData_.queue.size() == 0 ) return 0.0; // Copy queued message to the vector pointer argument and then "pop" it. std::vector *bytes = &(inputData_.queue.front().bytes); message->assign( bytes->begin(), bytes->end() ); double deltaTime = inputData_.queue.front().timeStamp; inputData_.queue.pop(); return deltaTime; } //*********************************************************************// // Common RtMidiOut Definitions //*********************************************************************// RtMidiOut :: RtMidiOut( const std::string clientName ) : RtMidi() { this->initialize( clientName ); } //*********************************************************************// // API: Macintosh OS-X //*********************************************************************// // API information found at: // - http://developer. apple .com/audio/pdf/coreaudio.pdf #if defined(__MACOSX_CORE__) // The CoreMIDI API is based on the use of a callback function for // MIDI input. We convert the system specific time stamps to delta // time values. // OS-X CoreMIDI header files. #include #include // A structure to hold variables related to the CoreMIDI API // implementation. struct CoreMidiData { MIDIClientRef client; MIDIPortRef port; MIDIEndpointRef endpoint; MIDIEndpointRef destinationId; unsigned long long lastTime; }; //*********************************************************************// // API: OS-X // Class Definitions: RtMidiIn //*********************************************************************// void midiInputCallback( const MIDIPacketList *list, void *procRef, void *srcRef ) { RtMidiIn::RtMidiInData *data = static_cast (procRef); CoreMidiData *apiData = static_cast (data->apiData); unsigned char status; unsigned short nBytes, iByte, size; unsigned long long time; bool& continueSysex = data->continueSysex; RtMidiIn::MidiMessage& message = data->message; const MIDIPacket *packet = &list->packet[0]; for ( unsigned int i=0; inumPackets; ++i ) { // My interpretation of the CoreMIDI documentation: all message // types, except sysex, are complete within a packet and there may // be several of them in a single packet. Sysex messages can be // broken across multiple packets and PacketLists but are bundled // alone within each packet (these packets do not contain other // message types). If sysex messages are split across multiple // MIDIPacketLists, they must be handled by multiple calls to this // function. nBytes = packet->length; if ( nBytes == 0 ) continue; // Calculate time stamp. message.timeStamp = 0.0; if ( data->firstMessage ) data->firstMessage = false; else { time = packet->timeStamp; time -= apiData->lastTime; time = AudioConvertHostTimeToNanos( time ); message.timeStamp = time * 0.000000001; } apiData->lastTime = packet->timeStamp; iByte = 0; if ( continueSysex ) { // We have a continuing, segmented sysex message. if ( !( data->ignoreFlags & 0x01 ) ) { // If we're not ignoring sysex messages, copy the entire packet. for ( unsigned int j=0; jdata[j] ); } continueSysex = packet->data[nBytes-1] != 0xF7; if ( !continueSysex ) { // If not a continuing sysex message, invoke the user callback function or queue the message. if ( data->usingCallback && message.bytes.size() > 0 ) { RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback; callback( message.timeStamp, &message.bytes, data->userData ); } else { // As long as we haven't reached our queue size limit, push the message. if ( data->queueLimit > data->queue.size() ) data->queue.push( message ); else std::cerr << "\nRtMidiIn: message queue limit reached!!\n\n"; } message.bytes.clear(); } } else { while ( iByte < nBytes ) { size = 0; // We are expecting that the next byte in the packet is a status byte. status = packet->data[iByte]; if ( !(status & 0x80) ) break; // Determine the number of bytes in the MIDI message. if ( status < 0xC0 ) size = 3; else if ( status < 0xE0 ) size = 2; else if ( status < 0xF0 ) size = 3; else if ( status == 0xF0 ) { // A MIDI sysex if ( data->ignoreFlags & 0x01 ) { size = 0; iByte = nBytes; } else size = nBytes - iByte; continueSysex = packet->data[nBytes-1] != 0xF7; } else if ( status < 0xF3 ) { if ( status == 0xF1 && (data->ignoreFlags & 0x02) ) { // A MIDI time code message and we're ignoring it. size = 0; iByte += 3; } else size = 3; } else if ( status == 0xF3 ) size = 2; else if ( status == 0xF8 ) { size = 1; if ( data->ignoreFlags & 0x02 ) { // A MIDI timing tick message and we're ignoring it. size = 0; iByte += 3; } } else if ( status == 0xFE && (data->ignoreFlags & 0x04) ) { // A MIDI active sensing message and we're ignoring it. size = 0; iByte += 1; } else size = 1; // Copy the MIDI data to our vector. if ( size ) { message.bytes.assign( &packet->data[iByte], &packet->data[iByte+size] ); if ( !continueSysex ) { // If not a continuing sysex message, invoke the user callback function or queue the message. if ( data->usingCallback ) { RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback; callback( message.timeStamp, &message.bytes, data->userData ); } else { // As long as we haven't reached our queue size limit, push the message. if ( data->queueLimit > data->queue.size() ) data->queue.push( message ); else std::cerr << "\nRtMidiIn: message queue limit reached!!\n\n"; } message.bytes.clear(); } iByte += size; } } } packet = MIDIPacketNext(packet); } } void RtMidiIn :: initialize( const std::string& clientName ) { // Set up our client. MIDIClientRef client; OSStatus result = MIDIClientCreate( CFStringCreateWithCString( NULL, clientName.c_str(), kCFStringEncodingASCII ), NULL, NULL, &client ); if ( result != noErr ) { errorString_ = "RtMidiIn::initialize: error creating OS-X MIDI client object."; error( RtError::DRIVER_ERROR ); } // Save our api-specific connection information. CoreMidiData *data = (CoreMidiData *) new CoreMidiData; data->client = client; data->endpoint = 0; apiData_ = (void *) data; inputData_.apiData = (void *) data; } void RtMidiIn :: openPort( unsigned int portNumber, const std::string portName ) { if ( connected_ ) { errorString_ = "RtMidiIn::openPort: a valid connection already exists!"; error( RtError::WARNING ); return; } unsigned int nSrc = MIDIGetNumberOfSources(); if (nSrc < 1) { errorString_ = "RtMidiIn::openPort: no MIDI input sources found!"; error( RtError::NO_DEVICES_FOUND ); } std::ostringstream ost; if ( portNumber >= nSrc ) { ost << "RtMidiIn::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); error( RtError::INVALID_PARAMETER ); } MIDIPortRef port; CoreMidiData *data = static_cast (apiData_); OSStatus result = MIDIInputPortCreate( data->client, CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ), midiInputCallback, (void *)&inputData_, &port ); if ( result != noErr ) { MIDIClientDispose( data->client ); errorString_ = "RtMidiIn::openPort: error creating OS-X MIDI input port."; error( RtError::DRIVER_ERROR ); } // Get the desired input source identifier. MIDIEndpointRef endpoint = MIDIGetSource( portNumber ); if ( endpoint == NULL ) { MIDIPortDispose( port ); MIDIClientDispose( data->client ); errorString_ = "RtMidiIn::openPort: error getting MIDI input source reference."; error( RtError::DRIVER_ERROR ); } // Make the connection. result = MIDIPortConnectSource( port, endpoint, NULL ); if ( result != noErr ) { MIDIPortDispose( port ); MIDIClientDispose( data->client ); errorString_ = "RtMidiIn::openPort: error connecting OS-X MIDI input port."; error( RtError::DRIVER_ERROR ); } // Save our api-specific port information. data->port = port; connected_ = true; } void RtMidiIn :: openVirtualPort( const std::string portName ) { CoreMidiData *data = static_cast (apiData_); // Create a virtual MIDI input destination. MIDIEndpointRef endpoint; OSStatus result = MIDIDestinationCreate( data->client, CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ), midiInputCallback, (void *)&inputData_, &endpoint ); if ( result != noErr ) { errorString_ = "RtMidiIn::openVirtualPort: error creating virtual OS-X MIDI destination."; error( RtError::DRIVER_ERROR ); } // Save our api-specific connection information. data->endpoint = endpoint; } void RtMidiIn :: closePort( void ) { if ( connected_ ) { CoreMidiData *data = static_cast (apiData_); MIDIPortDispose( data->port ); connected_ = false; } } RtMidiIn :: ~RtMidiIn() { // Close a connection if it exists. closePort(); // Cleanup. CoreMidiData *data = static_cast (apiData_); MIDIClientDispose( data->client ); if ( data->endpoint ) MIDIEndpointDispose( data->endpoint ); delete data; } unsigned int RtMidiIn :: getPortCount() { return MIDIGetNumberOfSources(); } std::string RtMidiIn :: getPortName( unsigned int portNumber ) { CFStringRef nameRef; MIDIEndpointRef portRef; std::ostringstream ost; char name[128]; if ( portNumber >= MIDIGetNumberOfSources() ) { ost << "RtMidiIn::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); error( RtError::INVALID_PARAMETER ); } portRef = MIDIGetSource( portNumber ); MIDIObjectGetStringProperty( portRef, kMIDIPropertyName, &nameRef ); CFStringGetCString( nameRef, name, sizeof(name), 0); CFRelease( nameRef ); std::string stringName = name; return stringName; } //*********************************************************************// // API: OS-X // Class Definitions: RtMidiOut //*********************************************************************// unsigned int RtMidiOut :: getPortCount() { return MIDIGetNumberOfDestinations(); } std::string RtMidiOut :: getPortName( unsigned int portNumber ) { CFStringRef nameRef; MIDIEndpointRef portRef; std::ostringstream ost; char name[128]; if ( portNumber >= MIDIGetNumberOfDestinations() ) { ost << "RtMidiOut::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); error( RtError::INVALID_PARAMETER ); } portRef = MIDIGetDestination( portNumber ); MIDIObjectGetStringProperty( portRef, kMIDIPropertyName, &nameRef ); CFStringGetCString( nameRef, name, sizeof(name), 0); CFRelease( nameRef ); std::string stringName = name; return stringName; } void RtMidiOut :: initialize( const std::string& clientName ) { // Set up our client. MIDIClientRef client; OSStatus result = MIDIClientCreate( CFStringCreateWithCString( NULL, clientName.c_str(), kCFStringEncodingASCII ), NULL, NULL, &client ); if ( result != noErr ) { errorString_ = "RtMidiOut::initialize: error creating OS-X MIDI client object."; error( RtError::DRIVER_ERROR ); } // Save our api-specific connection information. CoreMidiData *data = (CoreMidiData *) new CoreMidiData; data->client = client; data->endpoint = 0; apiData_ = (void *) data; } void RtMidiOut :: openPort( unsigned int portNumber, const std::string portName ) { if ( connected_ ) { errorString_ = "RtMidiOut::openPort: a valid connection already exists!"; error( RtError::WARNING ); return; } unsigned int nDest = MIDIGetNumberOfDestinations(); if (nDest < 1) { errorString_ = "RtMidiOut::openPort: no MIDI output destinations found!"; error( RtError::NO_DEVICES_FOUND ); } std::ostringstream ost; if ( portNumber >= nDest ) { ost << "RtMidiOut::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); error( RtError::INVALID_PARAMETER ); } MIDIPortRef port; CoreMidiData *data = static_cast (apiData_); OSStatus result = MIDIOutputPortCreate( data->client, CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ), &port ); if ( result != noErr ) { MIDIClientDispose( data->client ); errorString_ = "RtMidiOut::openPort: error creating OS-X MIDI output port."; error( RtError::DRIVER_ERROR ); } // Get the desired output port identifier. MIDIEndpointRef destination = MIDIGetDestination( portNumber ); if ( destination == NULL ) { MIDIPortDispose( port ); MIDIClientDispose( data->client ); errorString_ = "RtMidiOut::openPort: error getting MIDI output destination reference."; error( RtError::DRIVER_ERROR ); } // Save our api-specific connection information. data->port = port; data->destinationId = destination; connected_ = true; } void RtMidiOut :: closePort( void ) { if ( connected_ ) { CoreMidiData *data = static_cast (apiData_); MIDIPortDispose( data->port ); connected_ = false; } } void RtMidiOut :: openVirtualPort( std::string portName ) { CoreMidiData *data = static_cast (apiData_); if ( data->endpoint ) { errorString_ = "RtMidiOut::openVirtualPort: a virtual output port already exists!"; error( RtError::WARNING ); return; } // Create a virtual MIDI output source. MIDIEndpointRef endpoint; OSStatus result = MIDISourceCreate( data->client, CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ), &endpoint ); if ( result != noErr ) { errorString_ = "RtMidiOut::initialize: error creating OS-X virtual MIDI source."; error( RtError::DRIVER_ERROR ); } // Save our api-specific connection information. data->endpoint = endpoint; } RtMidiOut :: ~RtMidiOut() { // Close a connection if it exists. closePort(); // Cleanup. CoreMidiData *data = static_cast (apiData_); MIDIClientDispose( data->client ); if ( data->endpoint ) MIDIEndpointDispose( data->endpoint ); delete data; } void RtMidiOut :: sendMessage( std::vector *message ) { // The CoreMidi documentation indicates a maximum PackList size of // 64K, so we may need to break long sysex messages into pieces and // send via separate lists. unsigned int nBytes = message->size(); if ( nBytes == 0 ) { errorString_ = "RtMidiOut::sendMessage: no data in message argument!"; error( RtError::WARNING ); return; } if ( nBytes > 3 && ( message->at(0) != 0xF0 ) ) { errorString_ = "RtMidiOut::sendMessage: message format problem ... not sysex but > 3 bytes?"; error( RtError::WARNING ); return; } unsigned int packetBytes, bytesLeft = nBytes; unsigned int messageIndex = 0; MIDITimeStamp timeStamp = 0; CoreMidiData *data = static_cast (apiData_); while ( bytesLeft > 0 ) { packetBytes = ( bytesLeft > 32736 ) ? 32736 : bytesLeft; Byte buffer[packetBytes + 32]; // extra memory for other structure variables MIDIPacketList *packetList = (MIDIPacketList *) buffer; MIDIPacket *curPacket = MIDIPacketListInit( packetList ); curPacket = MIDIPacketListAdd( packetList, packetBytes+32, curPacket, timeStamp, packetBytes, (const Byte *) &message->at( messageIndex ) ); if ( !curPacket ) { errorString_ = "RtMidiOut::sendMessage: could not allocate packet list"; error( RtError::DRIVER_ERROR ); } messageIndex += packetBytes; bytesLeft -= packetBytes; // Send to any destinations that may have connected to us. OSStatus result; if ( data->endpoint ) { result = MIDIReceived( data->endpoint, packetList ); if ( result != noErr ) { errorString_ = "RtMidiOut::sendMessage: error sending MIDI to virtual destinations."; error( RtError::WARNING ); } } // And send to an explicit destination port if we're connected. if ( connected_ ) { result = MIDISend( data->port, data->destinationId, packetList ); if ( result != noErr ) { errorString_ = "RtMidiOut::sendMessage: error sending MIDI message to port."; error( RtError::WARNING ); } } } } #endif // __MACOSX_CORE__ //*********************************************************************// // API: LINUX ALSA SEQUENCER //*********************************************************************// // API information found at: // - http://www.alsa-project.org/documentation.php#Library #if defined(__LINUX_ALSASEQ__) // The ALSA Sequencer API is based on the use of a callback function for // MIDI input. // // Thanks to Pedro Lopez-Cabanillas for help with the ALSA sequencer // time stamps and other assorted fixes!!! #include #include // ALSA header file. #include // A structure to hold variables related to the ALSA API // implementation. struct AlsaMidiData { snd_seq_t *seq; int vport; snd_seq_port_subscribe_t *subscription; snd_midi_event_t *coder; unsigned int bufferSize; unsigned char *buffer; pthread_t thread; unsigned long long lastTime; int queue_id; // an input queue is needed to get timestamped events }; #define PORT_TYPE( pinfo, bits ) ((snd_seq_port_info_get_capability(pinfo) & (bits)) == (bits)) //*********************************************************************// // API: LINUX ALSA // Class Definitions: RtMidiIn //*********************************************************************// extern "C" void *alsaMidiHandler( void *ptr ) { RtMidiIn::RtMidiInData *data = static_cast (ptr); AlsaMidiData *apiData = static_cast (data->apiData); long nBytes; unsigned long long time, lastTime; bool continueSysex = false; RtMidiIn::MidiMessage message; snd_seq_event_t *ev; int result; apiData->bufferSize = 32; result = snd_midi_event_new( 0, &apiData->coder ); if ( result < 0 ) { data->doInput = false; std::cerr << "\nRtMidiIn::alsaMidiHandler: error initializing MIDI event parser!\n\n"; return 0; } unsigned char *buffer = (unsigned char *) malloc( apiData->bufferSize ); if ( buffer == NULL ) { data->doInput = false; std::cerr << "\nRtMidiIn::alsaMidiHandler: error initializing buffer memory!\n\n"; return 0; } snd_midi_event_init( apiData->coder ); snd_midi_event_no_status( apiData->coder, 1 ); // suppress running status messages while ( data->doInput ) { if ( snd_seq_event_input_pending( apiData->seq, 1 ) == 0 ) { // No data pending ... sleep a bit. usleep( 1000 ); continue; } // If here, there should be data. result = snd_seq_event_input( apiData->seq, &ev ); if ( result == -ENOSPC ) { std::cerr << "\nRtMidiIn::alsaMidiHandler: MIDI input buffer overrun!\n\n"; continue; } else if ( result <= 0 ) { std::cerr << "RtMidiIn::alsaMidiHandler: unknown MIDI input error!\n"; continue; } // This is a bit weird, but we now have to decode an ALSA MIDI // event (back) into MIDI bytes. We'll ignore non-MIDI types. if ( !continueSysex ) message.bytes.clear(); switch ( ev->type ) { case SND_SEQ_EVENT_PORT_SUBSCRIBED: #if defined(__RTMIDI_DEBUG__) std::cout << "RtMidiIn::alsaMidiHandler: port connection made!\n"; #endif break; case SND_SEQ_EVENT_PORT_UNSUBSCRIBED: #if defined(__RTMIDI_DEBUG__) std::cerr << "RtMidiIn::alsaMidiHandler: port connection has closed!\n"; // FIXME: this is called for all unsubscribe events, even ones //not related to this particular connection. As it stands, I //see no data provided in the "source" and "dest" fields so //there is nothing we can do about this at this time. // std::cout << "sender = " << ev->source.client << ", dest = " << ev->dest.port << std::endl; #endif //data->doInput = false; break; case SND_SEQ_EVENT_QFRAME: // MIDI time code if ( data->ignoreFlags & 0x02 ) break; case SND_SEQ_EVENT_TICK: // MIDI timing tick if ( data->ignoreFlags & 0x02 ) break; case SND_SEQ_EVENT_SENSING: // Active sensing if ( data->ignoreFlags & 0x04 ) break; case SND_SEQ_EVENT_SYSEX: if ( (data->ignoreFlags & 0x01) ) break; if ( ev->data.ext.len > apiData->bufferSize ) { apiData->bufferSize = ev->data.ext.len; free( buffer ); buffer = (unsigned char *) malloc( apiData->bufferSize ); if ( buffer == NULL ) { data->doInput = false; std::cerr << "\nRtMidiIn::alsaMidiHandler: error resizing buffer memory!\n\n"; break; } } default: nBytes = snd_midi_event_decode( apiData->coder, buffer, apiData->bufferSize, ev ); if ( nBytes <= 0 ) { #if defined(__RTMIDI_DEBUG__) std::cerr << "\nRtMidiIn::alsaMidiHandler: event parsing error or not a MIDI event!\n\n"; #endif break; } // The ALSA sequencer has a maximum buffer size for MIDI sysex // events of 256 bytes. If a device sends sysex messages larger // than this, they are segmented into 256 byte chunks. So, // we'll watch for this and concatenate sysex chunks into a // single sysex message if necessary. if ( !continueSysex ) message.bytes.assign( buffer, &buffer[nBytes] ); else message.bytes.insert( message.bytes.end(), buffer, &buffer[nBytes] ); continueSysex = ( ( ev->type == SND_SEQ_EVENT_SYSEX ) && ( message.bytes.back() != 0xF7 ) ); if ( continueSysex ) break; // Calculate the time stamp: message.timeStamp = 0.0; // Method 1: Use the system time. //(void)gettimeofday(&tv, (struct timezone *)NULL); //time = (tv.tv_sec * 1000000) + tv.tv_usec; // Method 2: Use the ALSA sequencer event time data. // (thanks to Pedro Lopez-Cabanillas!). time = ( ev->time.time.tv_sec * 1000000 ) + ( ev->time.time.tv_nsec/1000 ); lastTime = time; time -= apiData->lastTime; apiData->lastTime = lastTime; if ( data->firstMessage == true ) data->firstMessage = false; else message.timeStamp = time * 0.000001; } snd_seq_free_event(ev); if ( message.bytes.size() == 0 ) continue; if ( data->usingCallback && !continueSysex ) { RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback; callback( message.timeStamp, &message.bytes, data->userData ); } else { // As long as we haven't reached our queue size limit, push the message. if ( data->queueLimit > data->queue.size() ) data->queue.push( message ); else std::cerr << "\nRtMidiIn: message queue limit reached!!\n\n"; } } if ( buffer ) free( buffer ); snd_midi_event_free( apiData->coder ); apiData->coder = 0; return 0; } void RtMidiIn :: initialize( const std::string& clientName ) { // Set up the ALSA sequencer client. snd_seq_t *seq; int result = snd_seq_open(&seq, "default", SND_SEQ_OPEN_DUPLEX, SND_SEQ_NONBLOCK); if ( result < 0 ) { errorString_ = "RtMidiIn::initialize: error creating ALSA sequencer input client object."; error( RtError::DRIVER_ERROR ); } // Set client name. snd_seq_set_client_name( seq, clientName.c_str() ); // Save our api-specific connection information. AlsaMidiData *data = (AlsaMidiData *) new AlsaMidiData; data->seq = seq; data->vport = -1; apiData_ = (void *) data; inputData_.apiData = (void *) data; // Create the input queue data->queue_id = snd_seq_alloc_named_queue(seq, "RtMidi Queue"); // Set arbitrary tempo (mm=100) and resolution (240) snd_seq_queue_tempo_t *qtempo; snd_seq_queue_tempo_alloca(&qtempo); snd_seq_queue_tempo_set_tempo(qtempo, 600000); snd_seq_queue_tempo_set_ppq(qtempo, 240); snd_seq_set_queue_tempo(data->seq, data->queue_id, qtempo); snd_seq_drain_output(data->seq); } // This function is used to count or get the pinfo structure for a given port number. unsigned int portInfo( snd_seq_t *seq, snd_seq_port_info_t *pinfo, unsigned int type, int portNumber ) { snd_seq_client_info_t *cinfo; int client; int count = 0; snd_seq_client_info_alloca( &cinfo ); snd_seq_client_info_set_client( cinfo, -1 ); while ( snd_seq_query_next_client( seq, cinfo ) >= 0 ) { client = snd_seq_client_info_get_client( cinfo ); if ( client == 0 ) continue; // Reset query info snd_seq_port_info_set_client( pinfo, client ); snd_seq_port_info_set_port( pinfo, -1 ); while ( snd_seq_query_next_port( seq, pinfo ) >= 0 ) { unsigned int atyp = snd_seq_port_info_get_type( pinfo ); if ( ( atyp & SND_SEQ_PORT_TYPE_MIDI_GENERIC ) == 0 ) continue; unsigned int caps = snd_seq_port_info_get_capability( pinfo ); if ( ( caps & type ) != type ) continue; if ( count == portNumber ) return 1; count++; } } // If a negative portNumber was used, return the port count. if ( portNumber < 0 ) return count; return 0; } void RtMidiIn :: openPort( unsigned int portNumber, const std::string portName ) { if ( connected_ ) { errorString_ = "RtMidiIn::openPort: a valid connection already exists!"; error( RtError::WARNING ); return; } unsigned int nSrc = this->getPortCount(); if (nSrc < 1) { errorString_ = "RtMidiIn::openPort: no MIDI input sources found!"; error( RtError::NO_DEVICES_FOUND ); } snd_seq_port_info_t *pinfo; snd_seq_port_info_alloca( &pinfo ); std::ostringstream ost; AlsaMidiData *data = static_cast (apiData_); if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, (int) portNumber ) == 0 ) { ost << "RtMidiIn::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); error( RtError::INVALID_PARAMETER ); } snd_seq_addr_t sender, receiver; sender.client = snd_seq_port_info_get_client( pinfo ); sender.port = snd_seq_port_info_get_port( pinfo ); receiver.client = snd_seq_client_id( data->seq ); if ( data->vport < 0 ) { snd_seq_port_info_set_client( pinfo, 0 ); snd_seq_port_info_set_port( pinfo, 0 ); snd_seq_port_info_set_capability( pinfo, SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE ); snd_seq_port_info_set_type( pinfo, SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION ); snd_seq_port_info_set_midi_channels(pinfo, 16); snd_seq_port_info_set_timestamping(pinfo, 1); snd_seq_port_info_set_timestamp_real(pinfo, 1); snd_seq_port_info_set_timestamp_queue(pinfo, data->queue_id); snd_seq_port_info_set_name(pinfo, portName.c_str() ); data->vport = snd_seq_create_port(data->seq, pinfo); if ( data->vport < 0 ) { errorString_ = "RtMidiIn::openPort: ALSA error creating input port."; error( RtError::DRIVER_ERROR ); } } receiver.port = data->vport; // Make subscription snd_seq_port_subscribe_malloc( &data->subscription ); snd_seq_port_subscribe_set_sender(data->subscription, &sender); snd_seq_port_subscribe_set_dest(data->subscription, &receiver); if ( snd_seq_subscribe_port(data->seq, data->subscription) ) { errorString_ = "RtMidiIn::openPort: ALSA error making port connection."; error( RtError::DRIVER_ERROR ); } if ( inputData_.doInput == false ) { // Start the input queue snd_seq_start_queue( data->seq, data->queue_id, NULL ); snd_seq_drain_output( data->seq ); // Start our MIDI input thread. pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_attr_setschedpolicy(&attr, SCHED_OTHER); inputData_.doInput = true; int err = pthread_create(&data->thread, &attr, alsaMidiHandler, &inputData_); pthread_attr_destroy(&attr); if (err) { snd_seq_unsubscribe_port( data->seq, data->subscription ); snd_seq_port_subscribe_free( data->subscription ); inputData_.doInput = false; errorString_ = "RtMidiIn::openPort: error starting MIDI input thread!"; error( RtError::THREAD_ERROR ); } } connected_ = true; } void RtMidiIn :: openVirtualPort( std::string portName ) { AlsaMidiData *data = static_cast (apiData_); if ( data->vport < 0 ) { snd_seq_port_info_t *pinfo; snd_seq_port_info_alloca( &pinfo ); snd_seq_port_info_set_capability( pinfo, SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE ); snd_seq_port_info_set_type( pinfo, SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION ); snd_seq_port_info_set_midi_channels(pinfo, 16); snd_seq_port_info_set_timestamping(pinfo, 1); snd_seq_port_info_set_timestamp_real(pinfo, 1); snd_seq_port_info_set_timestamp_queue(pinfo, data->queue_id); snd_seq_port_info_set_name(pinfo, portName.c_str()); data->vport = snd_seq_create_port(data->seq, pinfo); if ( data->vport < 0 ) { errorString_ = "RtMidiIn::openVirtualPort: ALSA error creating virtual port."; error( RtError::DRIVER_ERROR ); } } if ( inputData_.doInput == false ) { // Start the input queue snd_seq_start_queue( data->seq, data->queue_id, NULL ); snd_seq_drain_output( data->seq ); // Start our MIDI input thread. pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_attr_setschedpolicy(&attr, SCHED_OTHER); inputData_.doInput = true; int err = pthread_create(&data->thread, &attr, alsaMidiHandler, &inputData_); pthread_attr_destroy(&attr); if (err) { snd_seq_unsubscribe_port( data->seq, data->subscription ); snd_seq_port_subscribe_free( data->subscription ); inputData_.doInput = false; errorString_ = "RtMidiIn::openPort: error starting MIDI input thread!"; error( RtError::THREAD_ERROR ); } } } void RtMidiIn :: closePort( void ) { if ( connected_ ) { AlsaMidiData *data = static_cast (apiData_); snd_seq_unsubscribe_port( data->seq, data->subscription ); snd_seq_port_subscribe_free( data->subscription ); // Stop the input queue snd_seq_stop_queue( data->seq, data->queue_id, NULL ); snd_seq_drain_output( data->seq ); connected_ = false; } } RtMidiIn :: ~RtMidiIn() { // Close a connection if it exists. closePort(); // Shutdown the input thread. AlsaMidiData *data = static_cast (apiData_); if ( inputData_.doInput ) { inputData_.doInput = false; pthread_join( data->thread, NULL ); } // Cleanup. if ( data->vport >= 0 ) snd_seq_delete_port( data->seq, data->vport ); snd_seq_free_queue( data->seq, data->queue_id ); snd_seq_close( data->seq ); delete data; } unsigned int RtMidiIn :: getPortCount() { snd_seq_port_info_t *pinfo; snd_seq_port_info_alloca( &pinfo ); AlsaMidiData *data = static_cast (apiData_); return portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, -1 ); } std::string RtMidiIn :: getPortName( unsigned int portNumber ) { snd_seq_client_info_t *cinfo; snd_seq_port_info_t *pinfo; snd_seq_client_info_alloca( &cinfo ); snd_seq_port_info_alloca( &pinfo ); AlsaMidiData *data = static_cast (apiData_); if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, (int) portNumber ) ) { int cnum = snd_seq_port_info_get_client( pinfo ); snd_seq_get_any_client_info( data->seq, cnum, cinfo ); std::ostringstream os; os << snd_seq_client_info_get_name( cinfo ); os << ":"; os << snd_seq_port_info_get_port( pinfo ); std::string stringName = os.str(); return stringName; } // If we get here, we didn't find a match. errorString_ = "RtMidiIn::getPortName: error looking for port name!"; error( RtError::INVALID_PARAMETER ); return 0; } //*********************************************************************// // API: LINUX ALSA // Class Definitions: RtMidiOut //*********************************************************************// unsigned int RtMidiOut :: getPortCount() { snd_seq_port_info_t *pinfo; snd_seq_port_info_alloca( &pinfo ); AlsaMidiData *data = static_cast (apiData_); return portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, -1 ); } std::string RtMidiOut :: getPortName( unsigned int portNumber ) { snd_seq_client_info_t *cinfo; snd_seq_port_info_t *pinfo; snd_seq_client_info_alloca( &cinfo ); snd_seq_port_info_alloca( &pinfo ); AlsaMidiData *data = static_cast (apiData_); if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, (int) portNumber ) ) { int cnum = snd_seq_port_info_get_client(pinfo); snd_seq_get_any_client_info( data->seq, cnum, cinfo ); std::ostringstream os; os << snd_seq_client_info_get_name(cinfo); os << ":"; os << snd_seq_port_info_get_port(pinfo); std::string stringName = os.str(); return stringName; } // If we get here, we didn't find a match. errorString_ = "RtMidiOut::getPortName: error looking for port name!"; error( RtError::INVALID_PARAMETER ); return 0; } void RtMidiOut :: initialize( const std::string& clientName ) { // Set up the ALSA sequencer client. snd_seq_t *seq; int result = snd_seq_open( &seq, "default", SND_SEQ_OPEN_OUTPUT, SND_SEQ_NONBLOCK ); if ( result < 0 ) { errorString_ = "RtMidiOut::initialize: error creating ALSA sequencer client object."; error( RtError::DRIVER_ERROR ); } // Set client name. snd_seq_set_client_name( seq, clientName.c_str() ); // Save our api-specific connection information. AlsaMidiData *data = (AlsaMidiData *) new AlsaMidiData; data->seq = seq; data->vport = -1; data->bufferSize = 32; data->coder = 0; data->buffer = 0; result = snd_midi_event_new( data->bufferSize, &data->coder ); if ( result < 0 ) { delete data; errorString_ = "RtMidiOut::initialize: error initializing MIDI event parser!\n\n"; error( RtError::DRIVER_ERROR ); } data->buffer = (unsigned char *) malloc( data->bufferSize ); if ( data->buffer == NULL ) { delete data; errorString_ = "RtMidiOut::initialize: error allocating buffer memory!\n\n"; error( RtError::MEMORY_ERROR ); } snd_midi_event_init( data->coder ); apiData_ = (void *) data; } void RtMidiOut :: openPort( unsigned int portNumber, const std::string portName ) { if ( connected_ ) { errorString_ = "RtMidiOut::openPort: a valid connection already exists!"; error( RtError::WARNING ); return; } unsigned int nSrc = this->getPortCount(); if (nSrc < 1) { errorString_ = "RtMidiOut::openPort: no MIDI output sources found!"; error( RtError::NO_DEVICES_FOUND ); } snd_seq_port_info_t *pinfo; snd_seq_port_info_alloca( &pinfo ); std::ostringstream ost; AlsaMidiData *data = static_cast (apiData_); if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, (int) portNumber ) == 0 ) { ost << "RtMidiOut::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); error( RtError::INVALID_PARAMETER ); } snd_seq_addr_t sender, receiver; receiver.client = snd_seq_port_info_get_client( pinfo ); receiver.port = snd_seq_port_info_get_port( pinfo ); sender.client = snd_seq_client_id( data->seq ); if ( data->vport < 0 ) { data->vport = snd_seq_create_simple_port( data->seq, portName.c_str(), SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, SND_SEQ_PORT_TYPE_MIDI_GENERIC ); if ( data->vport < 0 ) { errorString_ = "RtMidiOut::openPort: ALSA error creating output port."; error( RtError::DRIVER_ERROR ); } } sender.port = data->vport; // Make subscription snd_seq_port_subscribe_malloc( &data->subscription ); snd_seq_port_subscribe_set_sender(data->subscription, &sender); snd_seq_port_subscribe_set_dest(data->subscription, &receiver); snd_seq_port_subscribe_set_time_update(data->subscription, 1); snd_seq_port_subscribe_set_time_real(data->subscription, 1); if ( snd_seq_subscribe_port(data->seq, data->subscription) ) { errorString_ = "RtMidiOut::openPort: ALSA error making port connection."; error( RtError::DRIVER_ERROR ); } connected_ = true; } void RtMidiOut :: closePort( void ) { if ( connected_ ) { AlsaMidiData *data = static_cast (apiData_); snd_seq_unsubscribe_port( data->seq, data->subscription ); snd_seq_port_subscribe_free( data->subscription ); connected_ = false; } } void RtMidiOut :: openVirtualPort( std::string portName ) { AlsaMidiData *data = static_cast (apiData_); if ( data->vport < 0 ) { data->vport = snd_seq_create_simple_port( data->seq, portName.c_str(), SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, SND_SEQ_PORT_TYPE_MIDI_GENERIC ); if ( data->vport < 0 ) { errorString_ = "RtMidiOut::openVirtualPort: ALSA error creating virtual port."; error( RtError::DRIVER_ERROR ); } } } RtMidiOut :: ~RtMidiOut() { // Close a connection if it exists. closePort(); // Cleanup. AlsaMidiData *data = static_cast (apiData_); if ( data->vport >= 0 ) snd_seq_delete_port( data->seq, data->vport ); if ( data->coder ) snd_midi_event_free( data->coder ); if ( data->buffer ) free( data->buffer ); snd_seq_close( data->seq ); delete data; } void RtMidiOut :: sendMessage( std::vector *message ) { int result; AlsaMidiData *data = static_cast (apiData_); unsigned int nBytes = message->size(); if ( nBytes > data->bufferSize ) { data->bufferSize = nBytes; result = snd_midi_event_resize_buffer ( data->coder, nBytes); if ( result != 0 ) { errorString_ = "RtMidiOut::sendMessage: ALSA error resizing MIDI event buffer."; error( RtError::DRIVER_ERROR ); } free (data->buffer); data->buffer = (unsigned char *) malloc( data->bufferSize ); if ( data->buffer == NULL ) { errorString_ = "RtMidiOut::initialize: error allocating buffer memory!\n\n"; error( RtError::MEMORY_ERROR ); } } snd_seq_event_t ev; snd_seq_ev_clear(&ev); snd_seq_ev_set_source(&ev, data->vport); snd_seq_ev_set_subs(&ev); snd_seq_ev_set_direct(&ev); for ( unsigned int i=0; ibuffer[i] = message->at(i); result = snd_midi_event_encode( data->coder, data->buffer, (long)nBytes, &ev ); if ( result < (int)nBytes ) { errorString_ = "RtMidiOut::sendMessage: event parsing error!"; error( RtError::WARNING ); return; } // Send the event. result = snd_seq_event_output(data->seq, &ev); if ( result < 0 ) { errorString_ = "RtMidiOut::sendMessage: error sending MIDI message to port."; error( RtError::WARNING ); } snd_seq_drain_output(data->seq); } #endif // __LINUX_ALSA__ //*********************************************************************// // API: IRIX MD //*********************************************************************// // API information gleamed from: // http://techpubs.sgi.com/library/tpl/cgi-bin/getdoc.cgi?cmd=getdoc&coll=0650&db=man&fname=3%20mdIntro // If the Makefile doesn't work, try the following: // CC -o midiinfo -LANG:std -D__IRIX_MD__ -I../ ../RtMidi.cpp midiinfo.cpp -lpthread -lmd // CC -o midiout -LANG:std -D__IRIX_MD__ -I../ ../RtMidi.cpp midiout.cpp -lpthread -lmd // CC -o qmidiin -LANG:std -D__IRIX_MD__ -I../ ../RtMidi.cpp qmidiin.cpp -lpthread -lmd // CC -o cmidiin -LANG:std -D__IRIX_MD__ -I../ ../RtMidi.cpp cmidiin.cpp -lpthread -lmd #if defined(__IRIX_MD__) #include #include #include // Irix MIDI header file. #include // A structure to hold variables related to the IRIX API // implementation. struct IrixMidiData { MDport port; pthread_t thread; }; //*********************************************************************// // API: IRIX // Class Definitions: RtMidiIn //*********************************************************************// extern "C" void *irixMidiHandler( void *ptr ) { RtMidiIn::RtMidiInData *data = static_cast (ptr); IrixMidiData *apiData = static_cast (data->apiData); bool continueSysex = false; unsigned char status; unsigned short size; MDevent event; int fd = mdGetFd( apiData->port ); if ( fd < 0 ) { data->doInput = false; std::cerr << "\nRtMidiIn::irixMidiHandler: error getting port descriptor!\n\n"; return 0; } fd_set mask, rmask; FD_ZERO( &mask ); FD_SET( fd, &mask ); struct timeval timeout = {0, 0}; RtMidiIn::MidiMessage message; int result; while ( data->doInput ) { rmask = mask; timeout.tv_sec = 0; timeout.tv_usec = 0; if ( select( fd+1, &rmask, NULL, NULL, &timeout ) <= 0 ) { // No data pending ... sleep a bit. usleep( 1000 ); continue; } // If here, there should be data. result = mdReceive( apiData->port, &event, 1); if ( result <= 0 ) { std::cerr << "\nRtMidiIn::irixMidiHandler: MIDI input read error!\n\n"; continue; } message.timeStamp = event.stamp * 0.000000001; size = 0; status = event.msg[0]; if ( !(status & 0x80) ) continue; if ( status == 0xF0 ) { // Sysex message ... can be segmented across multiple messages. if ( !(data->ignoreFlags & 0x01) ) { if ( continueSysex ) { // We have a continuing, segmented sysex message. Append // the new bytes to our existing message. for ( int i=0; iusingCallback && message.bytes.size() > 0 ) { RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback; callback( message.timeStamp, &message.bytes, data->userData ); } else { // As long as we haven't reached our queue size limit, push the message. if ( data->queueLimit > data->queue.size() ) data->queue.push( message ); else std::cerr << "\nRtMidiIn: message queue limit reached!!\n\n"; } message.bytes.clear(); } } } mdFree( NULL ); continue; } else if ( status < 0xC0 ) size = 3; else if ( status < 0xE0 ) size = 2; else if ( status < 0xF0 ) size = 3; else if ( status < 0xF3 ) { if ( status == 0xF1 && !(data->ignoreFlags & 0x02) ) { // A MIDI time code message and we're not ignoring it. size = 3; } } else if ( status == 0xF3 ) size = 2; else if ( status == 0xF8 ) { if ( !(data->ignoreFlags & 0x02) ) { // A MIDI timing tick message and we're not ignoring it. size = 1; } } else if ( status == 0xFE ) { // MIDI active sensing if ( !(data->ignoreFlags & 0x04) ) size = 1; } else size = 1; // Copy the MIDI data to our vector. if ( size ) { message.bytes.assign( &event.msg[0], &event.msg[size] ); // Invoke the user callback function or queue the message. if ( data->usingCallback ) { RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback; callback( message.timeStamp, &message.bytes, data->userData ); } else { // As long as we haven't reached our queue size limit, push the message. if ( data->queueLimit > data->queue.size() ) data->queue.push( message ); else std::cerr << "\nRtMidiIn: message queue limit reached!!\n\n"; } message.bytes.clear(); } } return 0; } void RtMidiIn :: initialize( const std::string& /*clientName*/ ) { // Initialize the Irix MIDI system. At the moment, we will not // worry about a return value of zero (ports) because there is a // chance the user could plug something in after instantiation. int nPorts = mdInit(); // Create our api-specific connection information. IrixMidiData *data = (IrixMidiData *) new IrixMidiData; apiData_ = (void *) data; inputData_.apiData = (void *) data; } void RtMidiIn :: openPort( unsigned int portNumber, const std::string /*portName*/ ) { if ( connected_ ) { errorString_ = "RtMidiIn::openPort: a valid connection already exists!"; error( RtError::WARNING ); return; } int nPorts = mdInit(); if (nPorts < 1) { errorString_ = "RtMidiIn::openPort: no Irix MIDI input sources found!"; error( RtError::NO_DEVICES_FOUND ); } std::ostringstream ost; if ( portNumber >= nPorts ) { ost << "RtMidiIn::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); error( RtError::INVALID_PARAMETER ); } IrixMidiData *data = static_cast (apiData_); data->port = mdOpenInPort( mdGetName(portNumber) ); if ( data->port == NULL ) { ost << "RtMidiIn::openPort: Irix error opening the port (" << portNumber << ")."; errorString_ = ost.str(); error( RtError::DRIVER_ERROR ); } mdSetStampMode(data->port, MD_DELTASTAMP); // Start our MIDI input thread. pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_attr_setschedpolicy(&attr, SCHED_RR); inputData_.doInput = true; int err = pthread_create(&data->thread, &attr, irixMidiHandler, &inputData_); pthread_attr_destroy(&attr); if (err) { mdClosePort( data->port ); inputData_.doInput = false; errorString_ = "RtMidiIn::openPort: error starting MIDI input thread!"; error( RtError::THREAD_ERROR ); } connected_ = true; } void RtMidiIn :: openVirtualPort( std::string portName ) { // This function cannot be implemented for the Irix MIDI API. errorString_ = "RtMidiIn::openVirtualPort: cannot be implemented in Irix MIDI API!"; error( RtError::WARNING ); } void RtMidiIn :: closePort( void ) { if ( connected_ ) { IrixMidiData *data = static_cast (apiData_); mdClosePort( data->port ); connected_ = false; // Shutdown the input thread. inputData_.doInput = false; pthread_join( data->thread, NULL ); } } RtMidiIn :: ~RtMidiIn() { // Close a connection if it exists. closePort(); // Cleanup. IrixMidiData *data = static_cast (apiData_); delete data; } unsigned int RtMidiIn :: getPortCount() { int nPorts = mdInit(); if ( nPorts >= 0 ) return nPorts; else return 0; } std::string RtMidiIn :: getPortName( unsigned int portNumber ) { int nPorts = mdInit(); std::ostringstream ost; if ( portNumber >= nPorts ) { ost << "RtMidiIn::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); error( RtError::INVALID_PARAMETER ); } std::string stringName = std::string( mdGetName( portNumber ) ); return stringName; } //*********************************************************************// // API: IRIX MD // Class Definitions: RtMidiOut //*********************************************************************// unsigned int RtMidiOut :: getPortCount() { int nPorts = mdInit(); if ( nPorts >= 0 ) return nPorts; else return 0; } std::string RtMidiOut :: getPortName( unsigned int portNumber ) { int nPorts = mdInit(); std::ostringstream ost; if ( portNumber >= nPorts ) { ost << "RtMidiIn::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); error( RtError::INVALID_PARAMETER ); } std::string stringName = std::string( mdGetName( portNumber ) ); return stringName; } void RtMidiOut :: initialize( const std::string& /*clientName*/ ) { // Initialize the Irix MIDI system. At the moment, we will not // worry about a return value of zero (ports) because there is a // chance the user could plug something in after instantiation. int nPorts = mdInit(); // Create our api-specific connection information. IrixMidiData *data = (IrixMidiData *) new IrixMidiData; apiData_ = (void *) data; } void RtMidiOut :: openPort( unsigned int portNumber, const std::string /*portName*/ ) { if ( connected_ ) { errorString_ = "RtMidiOut::openPort: a valid connection already exists!"; error( RtError::WARNING ); return; } int nPorts = mdInit(); if (nPorts < 1) { errorString_ = "RtMidiOut::openPort: no Irix MIDI output sources found!"; error( RtError::NO_DEVICES_FOUND ); } std::ostringstream ost; if ( portNumber >= nPorts ) { ost << "RtMidiOut::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); error( RtError::INVALID_PARAMETER ); } IrixMidiData *data = static_cast (apiData_); data->port = mdOpenOutPort( mdGetName(portNumber) ); if ( data->port == NULL ) { ost << "RtMidiOut::openPort: Irix error opening the port (" << portNumber << ")."; errorString_ = ost.str(); error( RtError::DRIVER_ERROR ); } mdSetStampMode(data->port, MD_NOSTAMP); connected_ = true; } void RtMidiOut :: closePort( void ) { if ( connected_ ) { IrixMidiData *data = static_cast (apiData_); mdClosePort( data->port ); connected_ = false; } } void RtMidiOut :: openVirtualPort( std::string portName ) { // This function cannot be implemented for the Irix MIDI API. errorString_ = "RtMidiOut::openVirtualPort: cannot be implemented in Irix MIDI API!"; error( RtError::WARNING ); } RtMidiOut :: ~RtMidiOut() { // Close a connection if it exists. closePort(); // Cleanup. IrixMidiData *data = static_cast (apiData_); delete data; } void RtMidiOut :: sendMessage( std::vector *message ) { int result; MDevent event; IrixMidiData *data = static_cast (apiData_); char *buffer = 0; unsigned int nBytes = message->size(); if ( nBytes == 0 ) return; event.stamp = 0; if ( message->at(0) == 0xF0 ) { if ( nBytes < 3 ) return; // check for bogus sysex event.msg[0] = 0xF0; event.msglen = nBytes; buffer = (char *) malloc( nBytes ); for ( int i=0; iat(i); event.sysexmsg = buffer; } else { for ( int i=0; iat(i); } // Send the event. result = mdSend( data->port, &event, 1 ); if ( buffer ) free( buffer ); if ( result < 1 ) { errorString_ = "RtMidiOut::sendMessage: IRIX error sending MIDI message!"; error( RtError::WARNING ); return; } } #endif // __IRIX_MD__ //*********************************************************************// // API: Windows Multimedia Library (MM) //*********************************************************************// // API information deciphered from: // - http://msdn.microsoft.com/library/default.asp?url=/library/en-us/multimed/htm/_win32_midi_reference.asp // Thanks to Jean-Baptiste Berruchon for the sysex code. #if defined(__WINDOWS_MM__) // The Windows MM API is based on the use of a callback function for // MIDI input. We convert the system specific time stamps to delta // time values. // Windows MM MIDI header files. #include #include // A structure to hold variables related to the CoreMIDI API // implementation. struct WinMidiData { HMIDIIN inHandle; // Handle to Midi Input Device HMIDIOUT outHandle; // Handle to Midi Output Device DWORD lastTime; RtMidiIn::MidiMessage message; LPMIDIHDR sysexBuffer; }; #define RT_SYSEX_BUFFER_SIZE 1024 //*********************************************************************// // API: Windows MM // Class Definitions: RtMidiIn //*********************************************************************// static void CALLBACK midiInputCallback( HMIDIOUT hmin, UINT inputStatus, DWORD instancePtr, DWORD midiMessage, DWORD timestamp ) { if ( inputStatus != MIM_DATA && inputStatus != MIM_LONGDATA ) return; //RtMidiIn::RtMidiInData *data = static_cast (instancePtr); RtMidiIn::RtMidiInData *data = (RtMidiIn::RtMidiInData *)instancePtr; WinMidiData *apiData = static_cast (data->apiData); // Calculate time stamp. apiData->message.timeStamp = 0.0; if ( data->firstMessage == true ) data->firstMessage = false; else apiData->message.timeStamp = (double) ( timestamp - apiData->lastTime ) * 0.001; apiData->lastTime = timestamp; if ( inputStatus == MIM_DATA ) { // Channel or system message // Make sure the first byte is a status byte. unsigned char status = (unsigned char) (midiMessage & 0x000000FF); if ( !(status & 0x80) ) return; // Determine the number of bytes in the MIDI message. unsigned short nBytes = 1; if ( status < 0xC0 ) nBytes = 3; else if ( status < 0xE0 ) nBytes = 2; else if ( status < 0xF0 ) nBytes = 3; else if ( status < 0xF3 ) { // A MIDI time code message and we're ignoring it. if ( status == 0xF1 && (data->ignoreFlags & 0x02) ) return; nBytes = 3; } else if ( status == 0xF3 ) nBytes = 2; else if ( status == 0xF8 && (data->ignoreFlags & 0x02) ) { // A MIDI timing tick message and we're ignoring it. return; } else if ( status == 0xFE && (data->ignoreFlags & 0x04) ) { // A MIDI active sensing message and we're ignoring it. return; } // Copy bytes to our MIDI message. unsigned char *ptr = (unsigned char *) &midiMessage; for ( int i=0; imessage.bytes.push_back( *ptr++ ); } else { // Sysex message ( MIM_LONGDATA ) MIDIHDR *sysex = ( MIDIHDR *) midiMessage; if ( !( data->ignoreFlags & 0x01 ) ) { // Sysex message and we're not ignoring it for ( int i=0; i<(int)sysex->dwBytesRecorded; i++ ) apiData->message.bytes.push_back( sysex->lpData[i] ); } // The WinMM API requires that the sysex buffer be requeued after // input of each sysex message. Even if we are ignoring sysex // messages, we still need to requeue the buffer in case the user // decides to not ignore sysex messages in the future. However, // it seems that WinMM calls this function with an empty sysex // buffer when an application closes and in this case, we should // avoid requeueing it, else the computer suddenly reboots after // one or two minutes. if ( apiData->sysexBuffer->dwBytesRecorded > 0 ) { //if ( sysex->dwBytesRecorded > 0 ) { MMRESULT result = midiInAddBuffer( apiData->inHandle, apiData->sysexBuffer, sizeof(MIDIHDR) ); if ( result != MMSYSERR_NOERROR ) std::cerr << "\nRtMidiIn::midiInputCallback: error sending sysex to Midi device!!\n\n"; if ( data->ignoreFlags & 0x01 ) return; } else return; } if ( data->usingCallback ) { RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback; callback( apiData->message.timeStamp, &apiData->message.bytes, data->userData ); } else { // As long as we haven't reached our queue size limit, push the message. if ( data->queueLimit > data->queue.size() ) data->queue.push( apiData->message ); else std::cerr << "\nRtMidiIn: message queue limit reached!!\n\n"; } // Clear the vector for the next input message. apiData->message.bytes.clear(); } void RtMidiIn :: initialize( const std::string& /*clientName*/ ) { // We'll issue a warning here if no devices are available but not // throw an error since the user can plugin something later. unsigned int nDevices = midiInGetNumDevs(); if ( nDevices == 0 ) { errorString_ = "RtMidiIn::initialize: no MIDI input devices currently available."; error( RtError::WARNING ); } // Save our api-specific connection information. WinMidiData *data = (WinMidiData *) new WinMidiData; apiData_ = (void *) data; inputData_.apiData = (void *) data; data->message.bytes.clear(); // needs to be empty for first input message } void RtMidiIn :: openPort( unsigned int portNumber, const std::string /*portName*/ ) { if ( connected_ ) { errorString_ = "RtMidiIn::openPort: a valid connection already exists!"; error( RtError::WARNING ); return; } unsigned int nDevices = midiInGetNumDevs(); if (nDevices == 0) { errorString_ = "RtMidiIn::openPort: no MIDI input sources found!"; error( RtError::NO_DEVICES_FOUND ); } std::ostringstream ost; if ( portNumber >= nDevices ) { ost << "RtMidiIn::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); error( RtError::INVALID_PARAMETER ); } WinMidiData *data = static_cast (apiData_); MMRESULT result = midiInOpen( &data->inHandle, portNumber, (DWORD)&midiInputCallback, (DWORD)&inputData_, CALLBACK_FUNCTION ); if ( result != MMSYSERR_NOERROR ) { errorString_ = "RtMidiIn::openPort: error creating Windows MM MIDI input port."; error( RtError::DRIVER_ERROR ); } // Allocate and init the sysex buffer. data->sysexBuffer = (MIDIHDR*) new char[ sizeof(MIDIHDR) ]; data->sysexBuffer->lpData = new char[ RT_SYSEX_BUFFER_SIZE ]; data->sysexBuffer->dwBufferLength = RT_SYSEX_BUFFER_SIZE; data->sysexBuffer->dwFlags = 0; result = midiInPrepareHeader( data->inHandle, data->sysexBuffer, sizeof(MIDIHDR) ); if ( result != MMSYSERR_NOERROR ) { midiInClose( data->inHandle ); errorString_ = "RtMidiIn::openPort: error starting Windows MM MIDI input port (PrepareHeader)."; error( RtError::DRIVER_ERROR ); } // Register the buffer. result = midiInAddBuffer( data->inHandle, data->sysexBuffer, sizeof(MIDIHDR) ); if ( result != MMSYSERR_NOERROR ) { midiInClose( data->inHandle ); errorString_ = "RtMidiIn::openPort: error starting Windows MM MIDI input port (AddBuffer)."; error( RtError::DRIVER_ERROR ); } result = midiInStart( data->inHandle ); if ( result != MMSYSERR_NOERROR ) { midiInClose( data->inHandle ); errorString_ = "RtMidiIn::openPort: error starting Windows MM MIDI input port."; error( RtError::DRIVER_ERROR ); } connected_ = true; } void RtMidiIn :: openVirtualPort( std::string portName ) { // This function cannot be implemented for the Windows MM MIDI API. errorString_ = "RtMidiIn::openVirtualPort: cannot be implemented in Windows MM MIDI API!"; error( RtError::WARNING ); } void RtMidiIn :: closePort( void ) { if ( connected_ ) { WinMidiData *data = static_cast (apiData_); midiInReset( data->inHandle ); midiInStop( data->inHandle ); int result = midiInUnprepareHeader(data->inHandle, data->sysexBuffer, sizeof(MIDIHDR)); delete [] data->sysexBuffer->lpData; delete [] data->sysexBuffer; if ( result != MMSYSERR_NOERROR ) { midiInClose( data->inHandle ); errorString_ = "RtMidiIn::openPort: error closing Windows MM MIDI input port (midiInUnprepareHeader)."; error( RtError::DRIVER_ERROR ); } midiInClose( data->inHandle ); connected_ = false; } } RtMidiIn :: ~RtMidiIn() { // Close a connection if it exists. closePort(); // Cleanup. WinMidiData *data = static_cast (apiData_); delete data; } unsigned int RtMidiIn :: getPortCount() { return midiInGetNumDevs(); } std::string RtMidiIn :: getPortName( unsigned int portNumber ) { unsigned int nDevices = midiInGetNumDevs(); if ( portNumber >= nDevices ) { std::ostringstream ost; ost << "RtMidiIn::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); error( RtError::INVALID_PARAMETER ); } MIDIINCAPS deviceCaps; midiInGetDevCaps( portNumber, &deviceCaps, sizeof(MIDIINCAPS)); // For some reason, we need to copy character by character with // UNICODE (thanks to Eduardo Coutinho!). //std::string stringName = std::string( deviceCaps.szPname ); char nameString[MAXPNAMELEN]; for( int i=0; i= nDevices ) { std::ostringstream ost; ost << "RtMidiOut::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); error( RtError::INVALID_PARAMETER ); } MIDIOUTCAPS deviceCaps; midiOutGetDevCaps( portNumber, &deviceCaps, sizeof(MIDIOUTCAPS)); // For some reason, we need to copy character by character with // UNICODE (thanks to Eduardo Coutinho!). //std::string stringName = std::string( deviceCaps.szPname ); char nameString[MAXPNAMELEN]; for( int i=0; i= nDevices ) { ost << "RtMidiOut::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); error( RtError::INVALID_PARAMETER ); } WinMidiData *data = static_cast (apiData_); MMRESULT result = midiOutOpen( &data->outHandle, portNumber, (DWORD)NULL, (DWORD)NULL, CALLBACK_NULL ); if ( result != MMSYSERR_NOERROR ) { errorString_ = "RtMidiOut::openPort: error creating Windows MM MIDI output port."; error( RtError::DRIVER_ERROR ); } connected_ = true; } void RtMidiOut :: closePort( void ) { if ( connected_ ) { WinMidiData *data = static_cast (apiData_); midiOutReset( data->outHandle ); midiOutClose( data->outHandle ); connected_ = false; } } void RtMidiOut :: openVirtualPort( std::string portName ) { // This function cannot be implemented for the Windows MM MIDI API. errorString_ = "RtMidiOut::openVirtualPort: cannot be implemented in Windows MM MIDI API!"; error( RtError::WARNING ); } RtMidiOut :: ~RtMidiOut() { // Close a connection if it exists. closePort(); // Cleanup. WinMidiData *data = static_cast (apiData_); delete data; } void RtMidiOut :: sendMessage( std::vector *message ) { unsigned int nBytes = message->size(); if ( nBytes == 0 ) { errorString_ = "RtMidiOut::sendMessage: message argument is empty!"; error( RtError::WARNING ); return; } MMRESULT result; WinMidiData *data = static_cast (apiData_); if ( message->at(0) == 0xF0 ) { // Sysex message // Allocate buffer for sysex data. char *buffer = (char *) malloc( nBytes ); if ( buffer == NULL ) { errorString_ = "RtMidiOut::sendMessage: error allocating sysex message memory!"; error( RtError::MEMORY_ERROR ); } // Copy data to buffer. for ( unsigned int i=0; iat(i); // Create and prepare MIDIHDR structure. MIDIHDR sysex; sysex.lpData = (LPSTR) buffer; sysex.dwBufferLength = nBytes; sysex.dwFlags = 0; result = midiOutPrepareHeader( data->outHandle, &sysex, sizeof(MIDIHDR) ); if ( result != MMSYSERR_NOERROR ) { free( buffer ); errorString_ = "RtMidiOut::sendMessage: error preparing sysex header."; error( RtError::DRIVER_ERROR ); } // Send the message. result = midiOutLongMsg( data->outHandle, &sysex, sizeof(MIDIHDR) ); if ( result != MMSYSERR_NOERROR ) { free( buffer ); errorString_ = "RtMidiOut::sendMessage: error sending sysex message."; error( RtError::DRIVER_ERROR ); } // Unprepare the buffer and MIDIHDR. while ( MIDIERR_STILLPLAYING == midiOutUnprepareHeader( data->outHandle, &sysex, sizeof (MIDIHDR) ) ) Sleep( 1 ); free( buffer ); } else { // Channel or system message. // Make sure the message size isn't too big. if ( nBytes > 3 ) { errorString_ = "RtMidiOut::sendMessage: message size is greater than 3 bytes (and not sysex)!"; error( RtError::WARNING ); return; } // Pack MIDI bytes into double word. DWORD packet; unsigned char *ptr = (unsigned char *) &packet; for ( unsigned int i=0; iat(i); ptr++; } // Send the message immediately. result = midiOutShortMsg( data->outHandle, packet ); if ( result != MMSYSERR_NOERROR ) { errorString_ = "RtMidiOut::sendMessage: error sending MIDI message."; error( RtError::DRIVER_ERROR ); } } } #endif // __WINDOWS_MM__ pianobooster-src-0.6.4/src/rtmidi/RtError.h0000644000175000017500000000374611304222711017714 0ustar louislouis/************************************************************************/ /*! \class RtError \brief Exception handling class for RtAudio & RtMidi. The RtError class is quite simple but it does allow errors to be "caught" by RtError::Type. See the RtAudio and RtMidi documentation to know which methods can throw an RtError. */ /************************************************************************/ #ifndef RTERROR_H #define RTERROR_H #include #include class RtError { public: //! Defined RtError types. enum Type { WARNING, /*!< A non-critical error. */ DEBUG_WARNING, /*!< A non-critical error which might be useful for debugging. */ UNSPECIFIED, /*!< The default, unspecified error type. */ NO_DEVICES_FOUND, /*!< No devices found on system. */ INVALID_DEVICE, /*!< An invalid device ID was specified. */ INVALID_STREAM, /*!< An invalid stream ID was specified. */ MEMORY_ERROR, /*!< An error occured during memory allocation. */ INVALID_PARAMETER, /*!< An invalid parameter was specified to a function. */ DRIVER_ERROR, /*!< A system driver error occured. */ SYSTEM_ERROR, /*!< A system error occured. */ THREAD_ERROR /*!< A thread error occured. */ }; protected: std::string message_; Type type_; public: //! The constructor. RtError(const std::string& message, Type type = RtError::UNSPECIFIED) : message_(message), type_(type) {} //! The destructor. virtual ~RtError(void) {}; //! Prints thrown error message to stderr. virtual void printMessage(void) { std::cerr << '\n' << message_ << "\n\n"; } //! Returns the thrown error message type. virtual const Type& getType(void) { return type_; } //! Returns the thrown error message string. virtual const std::string& getMessage(void) { return message_; } //! Returns the thrown error message as a C string. virtual const char *getMessageString(void) { return message_.c_str(); } }; #endif pianobooster-src-0.6.4/src/precompile/precompile.h0000644000175000017500000000334211304222711021313 0ustar louislouis#if defined __cplusplus //#include //#include //#include //#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include //#include #include #include #include #include #include #include #include //* //#include "Bar.h" /* #include "Cfg.h" #include "Chord.h" #include "Conductor.h" #include "Draw.h" #include "GlView.h" #include "GuiKeyboardSetupDialog.h" #include "GuiLoopingPopup.h" #include "GuiMidiSetupDialog.h" #include "GuiPreferencesDialog.h" #include "GuiSidePanel.h" #include "GuiSongDetailsDialog.h" #include "GuiTopBar.h" #include "MidiDevice.h" #include "MidiDeviceBase.h" #include "MidiDeviceFluidSynth.h" #include "MidiDeviceRt.h" #include "MidiEvent.h" #include "MidiFile.h" #include "MidiTrack.h" #include "Notation.h" #include "Piano.h" #include "QtWindow.h" #include "Queue.h" #include "Rating.h" #include "ReleaseNote.txt" #include "Score.h" #include "Scroll.h" #include "Settings.h" #include "Song.h" #include "StavePosition.h" #include "Symbol.h" #include "Tempo.h" #include "TrackList.h" #include "Util.h" #include "rtmidi/RtMidi.h" #include "ui_GuiKeyboardSetupDialog.h" #include "ui_GuiLoopingPopup.h" #include "ui_GuiMidiSetupDialog.h" #include "ui_GuiPreferencesDialog.h" #include "ui_GuiSidePanel.h" #include "ui_GuiSongDetailsDialog.h" #include "ui_GuiTopBar.h" //#include "rtmidi/RtTimer.h" */ #endif pianobooster-src-0.6.4/src/precompile/PCHSupport_26.cmake0000644000175000017500000002470111304222711022325 0ustar louislouis# - Try to find precompiled headers support for GCC 3.4 and 4.x # Once done this will define: # # Variable: # PCHSupport_FOUND # # Macro: # ADD_PRECOMPILED_HEADER _targetName _input _dowarn # ADD_PRECOMPILED_HEADER_TO_TARGET _targetName _input _pch_output_to_use _dowarn # ADD_NATIVE_PRECOMPILED_HEADER _targetName _input _dowarn # GET_NATIVE_PRECOMPILED_HEADER _targetName _input IF(CMAKE_COMPILER_IS_GNUCXX) EXEC_PROGRAM( ${CMAKE_CXX_COMPILER} ARGS ${CMAKE_CXX_COMPILER_ARG1} -dumpversion OUTPUT_VARIABLE gcc_compiler_version) #MESSAGE("GCC Version: ${gcc_compiler_version}") IF(gcc_compiler_version MATCHES "4\\.[0-9]\\.[0-9]") SET(PCHSupport_FOUND TRUE) ELSE(gcc_compiler_version MATCHES "4\\.[0-9]\\.[0-9]") IF(gcc_compiler_version MATCHES "3\\.4\\.[0-9]") SET(PCHSupport_FOUND TRUE) ENDIF(gcc_compiler_version MATCHES "3\\.4\\.[0-9]") ENDIF(gcc_compiler_version MATCHES "4\\.[0-9]\\.[0-9]") SET(_PCH_include_prefix "-I") ELSE(CMAKE_COMPILER_IS_GNUCXX) IF(WIN32) SET(PCHSupport_FOUND TRUE) # for experimental msvc support SET(_PCH_include_prefix "/I") ELSE(WIN32) SET(PCHSupport_FOUND FALSE) ENDIF(WIN32) ENDIF(CMAKE_COMPILER_IS_GNUCXX) MACRO(_PCH_GET_COMPILE_FLAGS _out_compile_flags) STRING(TOUPPER "CMAKE_CXX_FLAGS_${CMAKE_BUILD_TYPE}" _flags_var_name) SET(${_out_compile_flags} ${${_flags_var_name}} ) IF(CMAKE_COMPILER_IS_GNUCXX) GET_TARGET_PROPERTY(_targetType ${_PCH_current_target} TYPE) IF(${_targetType} STREQUAL SHARED_LIBRARY) LIST(APPEND ${_out_compile_flags} "${${_out_compile_flags}} -fPIC") ENDIF(${_targetType} STREQUAL SHARED_LIBRARY) ELSE(CMAKE_COMPILER_IS_GNUCXX) ## TODO ... ? or does it work out of the box ENDIF(CMAKE_COMPILER_IS_GNUCXX) GET_DIRECTORY_PROPERTY(DIRINC INCLUDE_DIRECTORIES ) FOREACH(item ${DIRINC}) LIST(APPEND ${_out_compile_flags} "${_PCH_include_prefix}${item}") ENDFOREACH(item) GET_DIRECTORY_PROPERTY(_directory_flags DEFINITIONS) #MESSAGE("_directory_flags ${_directory_flags}" ) LIST(APPEND ${_out_compile_flags} ${_directory_flags}) LIST(APPEND ${_out_compile_flags} ${CMAKE_CXX_FLAGS} ) SEPARATE_ARGUMENTS(${_out_compile_flags}) ENDMACRO(_PCH_GET_COMPILE_FLAGS) MACRO(_PCH_WRITE_PCHDEP_CXX _targetName _include_file _dephelp) SET(${_dephelp} ${CMAKE_CURRENT_BINARY_DIR}/${_targetName}_pch_dephelp.cxx) FILE(WRITE ${${_dephelp}} "#include \"${_include_file}\" int testfunction() { return 0; } " ) ENDMACRO(_PCH_WRITE_PCHDEP_CXX ) MACRO(_PCH_GET_COMPILE_COMMAND out_command _input _output) FILE(TO_NATIVE_PATH ${_input} _native_input) FILE(TO_NATIVE_PATH ${_output} _native_output) IF(CMAKE_COMPILER_IS_GNUCXX) IF(CMAKE_CXX_COMPILER_ARG1) # remove leading space in compiler argument STRING(REGEX REPLACE "^ +" "" pchsupport_compiler_cxx_arg1 ${CMAKE_CXX_COMPILER_ARG1}) SET(${out_command} ${CMAKE_CXX_COMPILER} ${pchsupport_compiler_cxx_arg1} ${_compile_FLAGS} -x c++-header -o ${_output} ${_input} ) ELSE(CMAKE_CXX_COMPILER_ARG1) SET(${out_command} ${CMAKE_CXX_COMPILER} ${_compile_FLAGS} -x c++-header -o ${_output} ${_input} ) ENDIF(CMAKE_CXX_COMPILER_ARG1) ELSE(CMAKE_COMPILER_IS_GNUCXX) SET(_dummy_str "#include <${_input}>") FILE(WRITE ${CMAKE_CURRENT_BINARY_DIR}/pch_dummy.cpp ${_dummy_str}) SET(${out_command} ${CMAKE_CXX_COMPILER} ${_compile_FLAGS} /c /Fp${_native_output} /Yc${_native_input} pch_dummy.cpp ) #/out:${_output} ENDIF(CMAKE_COMPILER_IS_GNUCXX) ENDMACRO(_PCH_GET_COMPILE_COMMAND ) MACRO(_PCH_GET_TARGET_COMPILE_FLAGS _cflags _header_name _pch_path _dowarn ) FILE(TO_NATIVE_PATH ${_pch_path} _native_pch_path) IF(CMAKE_COMPILER_IS_GNUCXX) # for use with distcc and gcc >4.0.1 if preprocessed files are accessible # on all remote machines set # PCH_ADDITIONAL_COMPILER_FLAGS to -fpch-preprocess # if you want warnings for invalid header files (which is very inconvenient # if you have different versions of the headers for different build types # you may set _pch_dowarn IF (_dowarn) SET(${_cflags} "${PCH_ADDITIONAL_COMPILER_FLAGS} -include ${CMAKE_CURRENT_BINARY_DIR}/${_header_name} -Winvalid-pch " ) ELSE (_dowarn) SET(${_cflags} "${PCH_ADDITIONAL_COMPILER_FLAGS} -include ${CMAKE_CURRENT_BINARY_DIR}/${_header_name} " ) ENDIF (_dowarn) ELSE(CMAKE_COMPILER_IS_GNUCXX) set(${_cflags} "/Fp${_native_pch_path} /Yu${_header_name}" ) ENDIF(CMAKE_COMPILER_IS_GNUCXX) ENDMACRO(_PCH_GET_TARGET_COMPILE_FLAGS ) MACRO(GET_PRECOMPILED_HEADER_OUTPUT _targetName _input _output) GET_FILENAME_COMPONENT(_name ${_input} NAME) GET_FILENAME_COMPONENT(_path ${_input} PATH) SET(_output "${CMAKE_CURRENT_BINARY_DIR}/${_name}.gch/${_targetName}_${CMAKE_BUILD_TYPE}.h++") ENDMACRO(GET_PRECOMPILED_HEADER_OUTPUT _targetName _input) MACRO(ADD_PRECOMPILED_HEADER_TO_TARGET _targetName _input _pch_output_to_use ) # to do: test whether compiler flags match between target _targetName # and _pch_output_to_use GET_FILENAME_COMPONENT(_name ${_input} NAME) IF( "${ARGN}" STREQUAL "0") SET(_dowarn 0) ELSE( "${ARGN}" STREQUAL "0") SET(_dowarn 1) ENDIF("${ARGN}" STREQUAL "0") _PCH_GET_TARGET_COMPILE_FLAGS(_target_cflags ${_name} ${_pch_output_to_use} ${_dowarn}) # MESSAGE("Add flags ${_target_cflags} to ${_targetName} " ) SET_TARGET_PROPERTIES(${_targetName} PROPERTIES COMPILE_FLAGS ${_target_cflags} ) ADD_CUSTOM_TARGET(pch_Generate_${_targetName} DEPENDS ${_pch_output_to_use} ) ADD_DEPENDENCIES(${_targetName} pch_Generate_${_targetName} ) ENDMACRO(ADD_PRECOMPILED_HEADER_TO_TARGET) MACRO(ADD_PRECOMPILED_HEADER _targetName _input) SET(_PCH_current_target ${_targetName}) IF(NOT CMAKE_BUILD_TYPE) MESSAGE(FATAL_ERROR "This is the ADD_PRECOMPILED_HEADER macro. " "You must set CMAKE_BUILD_TYPE!" ) ENDIF(NOT CMAKE_BUILD_TYPE) IF( "${ARGN}" STREQUAL "0") SET(_dowarn 0) ELSE( "${ARGN}" STREQUAL "0") SET(_dowarn 1) ENDIF("${ARGN}" STREQUAL "0") GET_FILENAME_COMPONENT(_name ${_input} NAME) GET_FILENAME_COMPONENT(_path ${_input} PATH) GET_PRECOMPILED_HEADER_OUTPUT( ${_targetName} ${_input} _output) GET_FILENAME_COMPONENT(_outdir ${_output} PATH ) GET_TARGET_PROPERTY(_targetType ${_PCH_current_target} TYPE) _PCH_WRITE_PCHDEP_CXX(${_targetName} ${_input} _pch_dephelp_cxx) IF(${_targetType} STREQUAL SHARED_LIBRARY) ADD_LIBRARY(${_targetName}_pch_dephelp SHARED ${_pch_dephelp_cxx} ) ELSE(${_targetType} STREQUAL SHARED_LIBRARY) ADD_LIBRARY(${_targetName}_pch_dephelp STATIC ${_pch_dephelp_cxx}) ENDIF(${_targetType} STREQUAL SHARED_LIBRARY) FILE(MAKE_DIRECTORY ${_outdir}) _PCH_GET_COMPILE_FLAGS(_compile_FLAGS) #MESSAGE("_compile_FLAGS: ${_compile_FLAGS}") #message("COMMAND ${CMAKE_CXX_COMPILER} ${_compile_FLAGS} -x c++-header -o ${_output} ${_input}") SET_SOURCE_FILES_PROPERTIES(${CMAKE_CURRENT_BINARY_DIR}/${_name} PROPERTIES GENERATED 1) ADD_CUSTOM_COMMAND( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${_name} COMMAND ${CMAKE_COMMAND} -E copy ${_input} ${CMAKE_CURRENT_BINARY_DIR}/${_name} # ensure same directory! Required by gcc DEPENDS ${_input} ) #message("_command ${_input} ${_output}") _PCH_GET_COMPILE_COMMAND(_command ${CMAKE_CURRENT_BINARY_DIR}/${_name} ${_output} ) #message(${_input} ) #message("_output ${_output}") ADD_CUSTOM_COMMAND( OUTPUT ${_output} COMMAND ${_command} DEPENDS ${_input} ${CMAKE_CURRENT_BINARY_DIR}/${_name} ${_targetName}_pch_dephelp ) ADD_PRECOMPILED_HEADER_TO_TARGET(${_targetName} ${_input} ${_output} ${_dowarn}) ENDMACRO(ADD_PRECOMPILED_HEADER) # Generates the use of precompiled in a target, # without using depency targets (2 extra for each target) # Using Visual, must also add ${_targetName}_pch to sources # Not needed by Xcode MACRO(GET_NATIVE_PRECOMPILED_HEADER _targetName _input) if(CMAKE_GENERATOR MATCHES Visual*) SET(_dummy_str "#include \"${_input}\"\n" "// This is required to suppress LNK4221. Very annoying.\n" "void *g_${_targetName}Dummy = 0\;\n") # Use of cxx extension for generated files (as Qt does) SET(${_targetName}_pch ${CMAKE_CURRENT_BINARY_DIR}/${_targetName}_pch.cxx) if(EXISTS ${${_targetName}_pch}) # Check if contents is the same, if not rewrite # todo else(EXISTS ${${_targetName}_pch}) FILE(WRITE ${${_targetName}_pch} ${_dummy_str}) endif(EXISTS ${${_targetName}_pch}) endif(CMAKE_GENERATOR MATCHES Visual*) ENDMACRO(GET_NATIVE_PRECOMPILED_HEADER) MACRO(ADD_NATIVE_PRECOMPILED_HEADER _targetName _input) IF( "${ARGN}" STREQUAL "0") SET(_dowarn 0) ELSE( "${ARGN}" STREQUAL "0") SET(_dowarn 1) ENDIF("${ARGN}" STREQUAL "0") if(CMAKE_GENERATOR MATCHES Visual*) # Auto include the precompile (useful for moc processing, since the use of # precompiled is specified at the target level # and I don't want to specifiy /F- for each moc/res/ui generated files (using Qt) GET_TARGET_PROPERTY(oldProps ${_targetName} COMPILE_FLAGS) if (${oldProps} MATCHES NOTFOUND) SET(oldProps "") endif(${oldProps} MATCHES NOTFOUND) SET(newProperties "${oldProps} /Yu\"${_input}\" /FI\"${_input}\"") SET_TARGET_PROPERTIES(${_targetName} PROPERTIES COMPILE_FLAGS "${newProperties}") #also inlude ${oldProps} to have the same compile options SET_SOURCE_FILES_PROPERTIES(${${_targetName}_pch} PROPERTIES COMPILE_FLAGS "${oldProps} /Yc\"${_input}\"") else(CMAKE_GENERATOR MATCHES Visual*) if (CMAKE_GENERATOR MATCHES Xcode) # For Xcode, cmake needs my patch to process # GCC_PREFIX_HEADER and GCC_PRECOMPILE_PREFIX_HEADER as target properties GET_TARGET_PROPERTY(oldProps ${_targetName} COMPILE_FLAGS) if (${oldProps} MATCHES NOTFOUND) SET(oldProps "") endif(${oldProps} MATCHES NOTFOUND) # When buiding out of the tree, precompiled may not be located # Use full path instead. GET_FILENAME_COMPONENT(fullPath ${_input} ABSOLUTE) SET_TARGET_PROPERTIES(${_targetName} PROPERTIES XCODE_ATTRIBUTE_GCC_PREFIX_HEADER "${fullPath}") SET_TARGET_PROPERTIES(${_targetName} PROPERTIES XCODE_ATTRIBUTE_GCC_PRECOMPILE_PREFIX_HEADER "YES") else (CMAKE_GENERATOR MATCHES Xcode) #Fallback to the "old" precompiled suppport #ADD_PRECOMPILED_HEADER(${_targetName} ${_input} ${_dowarn}) endif(CMAKE_GENERATOR MATCHES Xcode) endif(CMAKE_GENERATOR MATCHES Visual*) ENDMACRO(ADD_NATIVE_PRECOMPILED_HEADER) pianobooster-src-0.6.4/src/precompile/PCHSupport.cmake0000644000175000017500000001716611304222711022025 0ustar louislouis# - Try to find precompiled headers support for GCC 3.4 and 4.x # Once done this will define: # # Variable: # PCHSupport_FOUND # # Macro: # ADD_PRECOMPILED_HEADER _targetName _input _dowarn # ADD_PRECOMPILED_HEADER_TO_TARGET _targetName _input _pch_output_to_use _dowarn IF(CMAKE_COMPILER_IS_GNUCXX) EXEC_PROGRAM( ${CMAKE_CXX_COMPILER} ARGS ${CMAKE_CXX_COMPILER_ARG1} -dumpversion OUTPUT_VARIABLE gcc_compiler_version) MESSAGE("GCC Version: ${gcc_compiler_version}") IF(gcc_compiler_version MATCHES "4\\.[0-9]\\.[0-9]") SET(PCHSupport_FOUND TRUE) ELSE(gcc_compiler_version MATCHES "4\\.[0-9]\\.[0-9]") IF(gcc_compiler_version MATCHES "3\\.4\\.[0-9]") SET(PCHSupport_FOUND TRUE) ENDIF(gcc_compiler_version MATCHES "3\\.4\\.[0-9]") ENDIF(gcc_compiler_version MATCHES "4\\.[0-9]\\.[0-9]") SET(_PCH_include_prefix "-I") ELSE(CMAKE_COMPILER_IS_GNUCXX) IF(WIN32) SET(PCHSupport_FOUND TRUE) # for experimental msvc support SET(_PCH_include_prefix "/I") ELSE(WIN32) SET(PCHSupport_FOUND FALSE) ENDIF(WIN32) ENDIF(CMAKE_COMPILER_IS_GNUCXX) MACRO(_PCH_GET_COMPILE_FLAGS _out_compile_flags) STRING(TOUPPER "CMAKE_CXX_FLAGS_${CMAKE_BUILD_TYPE}" _flags_var_name) SET(${_out_compile_flags} ${${_flags_var_name}} ) IF(CMAKE_COMPILER_IS_GNUCXX) GET_TARGET_PROPERTY(_targetType ${_PCH_current_target} TYPE) IF(${_targetType} STREQUAL SHARED_LIBRARY) LIST(APPEND ${_out_compile_flags} "${${_out_compile_flags}} -fPIC") ENDIF(${_targetType} STREQUAL SHARED_LIBRARY) ELSE(CMAKE_COMPILER_IS_GNUCXX) ## TODO ... ? or does it work out of the box ENDIF(CMAKE_COMPILER_IS_GNUCXX) GET_DIRECTORY_PROPERTY(DIRINC INCLUDE_DIRECTORIES ) FOREACH(item ${DIRINC}) LIST(APPEND ${_out_compile_flags} "${_PCH_include_prefix}${item}") ENDFOREACH(item) GET_DIRECTORY_PROPERTY(_directory_flags DEFINITIONS) #MESSAGE("_directory_flags ${_directory_flags}" ) LIST(APPEND ${_out_compile_flags} ${_directory_flags}) LIST(APPEND ${_out_compile_flags} ${CMAKE_CXX_FLAGS} ) SEPARATE_ARGUMENTS(${_out_compile_flags}) ENDMACRO(_PCH_GET_COMPILE_FLAGS) MACRO(_PCH_WRITE_PCHDEP_CXX _targetName _include_file _dephelp) SET(${_dephelp} ${CMAKE_CURRENT_BINARY_DIR}/${_targetName}_pch_dephelp.cxx) FILE(WRITE ${${_dephelp}} "#include \"${_include_file}\" int testfunction() { return 0; } " ) ENDMACRO(_PCH_WRITE_PCHDEP_CXX ) MACRO(_PCH_GET_COMPILE_COMMAND out_command _input _output) FILE(TO_NATIVE_PATH ${_input} _native_input) FILE(TO_NATIVE_PATH ${_output} _native_output) IF(CMAKE_COMPILER_IS_GNUCXX) IF(CMAKE_CXX_COMPILER_ARG1) # remove leading space in compiler argument STRING(REGEX REPLACE "^ +" "" pchsupport_compiler_cxx_arg1 ${CMAKE_CXX_COMPILER_ARG1}) SET(${out_command} ${CMAKE_CXX_COMPILER} ${pchsupport_compiler_cxx_arg1} ${_compile_FLAGS} -x c++-header -o ${_output} ${_input} ) ELSE(CMAKE_CXX_COMPILER_ARG1) SET(${out_command} ${CMAKE_CXX_COMPILER} ${_compile_FLAGS} -x c++-header -o ${_output} ${_input} ) ENDIF(CMAKE_CXX_COMPILER_ARG1) ELSE(CMAKE_COMPILER_IS_GNUCXX) SET(_dummy_str "#include <${_input}>") FILE(WRITE ${CMAKE_CURRENT_BINARY_DIR}/pch_dummy.cpp ${_dummy_str}) SET(${out_command} ${CMAKE_CXX_COMPILER} ${_compile_FLAGS} /c /Fp${_native_output} /Yc${_native_input} pch_dummy.cpp ) #/out:${_output} ENDIF(CMAKE_COMPILER_IS_GNUCXX) ENDMACRO(_PCH_GET_COMPILE_COMMAND ) MACRO(_PCH_GET_TARGET_COMPILE_FLAGS _cflags _header_name _pch_path _dowarn ) FILE(TO_NATIVE_PATH ${_pch_path} _native_pch_path) message(${_native_pch_path}) IF(CMAKE_COMPILER_IS_GNUCXX) # for use with distcc and gcc >4.0.1 if preprocessed files are accessible # on all remote machines set # PCH_ADDITIONAL_COMPILER_FLAGS to -fpch-preprocess # if you want warnings for invalid header files (which is very inconvenient # if you have different versions of the headers for different build types # you may set _pch_dowarn IF (_dowarn) SET(${_cflags} "${PCH_ADDITIONAL_COMPILER_FLAGS} -include ${CMAKE_CURRENT_BINARY_DIR}/${_header_name} -Winvalid-pch " ) ELSE (_dowarn) SET(${_cflags} "${PCH_ADDITIONAL_COMPILER_FLAGS} -include ${CMAKE_CURRENT_BINARY_DIR}/${_header_name} " ) ENDIF (_dowarn) ELSE(CMAKE_COMPILER_IS_GNUCXX) set(${_cflags} "/Fp${_native_pch_path} /Yu${_header_name}" ) ENDIF(CMAKE_COMPILER_IS_GNUCXX) ENDMACRO(_PCH_GET_TARGET_COMPILE_FLAGS ) MACRO(GET_PRECOMPILED_HEADER_OUTPUT _targetName _input _output) GET_FILENAME_COMPONENT(_name ${_input} NAME) GET_FILENAME_COMPONENT(_path ${_input} PATH) SET(_output "${CMAKE_CURRENT_BINARY_DIR}/${_name}.gch/${_targetName}_${CMAKE_BUILD_TYPE}.h++") ENDMACRO(GET_PRECOMPILED_HEADER_OUTPUT _targetName _input) MACRO(ADD_PRECOMPILED_HEADER_TO_TARGET _targetName _input _pch_output_to_use ) # to do: test whether compiler flags match between target _targetName # and _pch_output_to_use GET_FILENAME_COMPONENT(_name ${_input} NAME) IF( "${ARGN}" STREQUAL "0") SET(_dowarn 0) ELSE( "${ARGN}" STREQUAL "0") SET(_dowarn 1) ENDIF("${ARGN}" STREQUAL "0") _PCH_GET_TARGET_COMPILE_FLAGS(_target_cflags ${_name} ${_pch_output_to_use} ${_dowarn}) # MESSAGE("Add flags ${_target_cflags} to ${_targetName} " ) SET_TARGET_PROPERTIES(${_targetName} PROPERTIES COMPILE_FLAGS ${_target_cflags} ) ADD_CUSTOM_TARGET(pch_Generate_${_targetName} DEPENDS ${_pch_output_to_use} ) ADD_DEPENDENCIES(${_targetName} pch_Generate_${_targetName} ) ENDMACRO(ADD_PRECOMPILED_HEADER_TO_TARGET) MACRO(ADD_PRECOMPILED_HEADER _targetName _input) SET(_PCH_current_target ${_targetName}) IF(NOT CMAKE_BUILD_TYPE) MESSAGE(FATAL_ERROR "This is the ADD_PRECOMPILED_HEADER macro. " "You must set CMAKE_BUILD_TYPE!" ) ENDIF(NOT CMAKE_BUILD_TYPE) IF( "${ARGN}" STREQUAL "0") SET(_dowarn 0) ELSE( "${ARGN}" STREQUAL "0") SET(_dowarn 1) ENDIF("${ARGN}" STREQUAL "0") GET_FILENAME_COMPONENT(_name ${_input} NAME) GET_FILENAME_COMPONENT(_path ${_input} PATH) GET_PRECOMPILED_HEADER_OUTPUT( ${_targetName} ${_input} _output) GET_FILENAME_COMPONENT(_outdir ${_output} PATH ) GET_TARGET_PROPERTY(_targetType ${_PCH_current_target} TYPE) _PCH_WRITE_PCHDEP_CXX(${_targetName} ${_input} _pch_dephelp_cxx) IF(${_targetType} STREQUAL SHARED_LIBRARY) ADD_LIBRARY(${_targetName}_pch_dephelp SHARED ${_pch_dephelp_cxx} ) ELSE(${_targetType} STREQUAL SHARED_LIBRARY) ADD_LIBRARY(${_targetName}_pch_dephelp STATIC ${_pch_dephelp_cxx}) ENDIF(${_targetType} STREQUAL SHARED_LIBRARY) FILE(MAKE_DIRECTORY ${_outdir}) _PCH_GET_COMPILE_FLAGS(_compile_FLAGS) #MESSAGE("_compile_FLAGS: ${_compile_FLAGS}") #message("COMMAND ${CMAKE_CXX_COMPILER} ${_compile_FLAGS} -x c++-header -o ${_output} ${_input}") SET_SOURCE_FILES_PROPERTIES(${CMAKE_CURRENT_BINARY_DIR}/${_name} PROPERTIES GENERATED 1) ADD_CUSTOM_COMMAND( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${_name} COMMAND ${CMAKE_COMMAND} -E copy ${_input} ${CMAKE_CURRENT_BINARY_DIR}/${_name} # ensure same directory! Required by gcc DEPENDS ${_input} ) #message("_command ${_input} ${_output}") _PCH_GET_COMPILE_COMMAND(_command ${CMAKE_CURRENT_BINARY_DIR}/${_name} ${_output} ) #message(${_input} ) #message("_output ${_output}") ADD_CUSTOM_COMMAND( OUTPUT ${_output} COMMAND ${_command} DEPENDS ${_input} ${CMAKE_CURRENT_BINARY_DIR}/${_name} ${_targetName}_pch_dephelp ) ADD_PRECOMPILED_HEADER_TO_TARGET(${_targetName} ${_input} ${_output} ${_dowarn}) ENDMACRO(ADD_PRECOMPILED_HEADER) pianobooster-src-0.6.4/src/images/stop.png0000644000175000017500000000030611304222711017601 0ustar louislouisPNG  IHDR szzIDATXc,))a````ap0a%PKZD>G 4v1'mMTo0]hQ:`$8{c@PRRw4:`$dFJ{Ci`$'Bl v|PMvIENDB`pianobooster-src-0.6.4/src/images/save.png0000644000175000017500000000224311304222711017554 0ustar louislouisPNG  IHDR szzgAMAOX2tEXtSoftwareAdobe ImageReadyqe<5IDATX͏TE{n@FM4DHČL\.M\kXÎč΂htA\ =`PQ` ^` QVR{:ԩz~6>>]vN5ػ」;v<:̗7XSڠkg|p?0x.ory #ӟd}k@E@xp,#˲m00aP|#%"+Օs΃* ,I Iw:琷Ղv+m(r8 㯼IkFؽ{k놮ZVmQg5 ,# /#&|#!Я'aa%% 4M:ólc V_)Fara-р: TIO4/!g iXvj#wPE x:Tx3x$wh6h߱R^DM_ 8ňKvRPZ0}@Ű&WU.2p}Ʉ-Jsf+7QW?תd~')Ü wl 55Y1{X0+WVU!ѐS,-޸Wj'WڣU<_o|w__sl}5ځ?MKFIENDB`pianobooster-src-0.6.4/src/images/play.png0000644000175000017500000000055311304222711017565 0ustar louislouisPNG  IHDR szz2IDATXŖ1R0E, .(n(\pC*%ƭ[$D4h&$+-kpSXlL9":֎n섿&}6۝q1[? jfu"(=EB${Ӓکq o(( F*R%ڶ%c%Ԃl(T"k5 Xx{4M`u8 '/iC 0つb$-Y ܒkw/#IENDB`pianobooster-src-0.6.4/src/images/play-from-start.png0000644000175000017500000000057111304222711021661 0ustar louislouisPNG  IHDR szz@IDATX;r0+q(\xhiRP>LT]r7YW/ V#@kv>k=^,;@fL=E,ӝ/q}m?&ޚwZZB?AQ@?~ RnL@!l~W"xBDID6@]QS#k_I=dpYx a2U9Z 1˲|~=ې'0 g$+C-Yq< &0C@[+E<xqo_Si17ٿ{`aIENDB`pianobooster-src-0.6.4/src/images/pianobooster.png0000644000175000017500000000234611304222711021326 0ustar louislouisPNG  IHDR IDATHOhU?i_7eYHaW@hւBP=U֞ڋ؛x' "(d R=3إ>ٝ6{~F<Aj2.-ɩs!ă=L X" U|5 V`jvKXu$FI5fzcqpժ ]~I jWŴԮ bm!bPF1(1GgBl0j1FV@uQ).Rʃ (JEނez"lʦb6YԎtR2ĩ#dDcщb:7| y F yoH0 [8l::^tDM6g^Uoe Dn.lM ,^uuFz;ugݶ=yԼ=hy`TǂQ0@H8[+n1J@Cv`i7zq P=Z?yqŸ uA<2w űbBu~7yvw%^Vܕz lM#fO;IzM;w`XRkn./* *A>$XNSs QV;TtscA5}mF4/~t U>3q12q4X]N ]*X[bªalSQ0bTrM£U瑂:"ډ/{AqD_cM~1o3+4XaO_"{mUm9Ul:ro{^|ɕ,/??d ;d}p: Z5踛[AI q]l?緼Ul_h"#*/!ϰkZ/ΎgܘS1"9t4ʮVR-8C?^^O7@r<z F ; (4gwVd:E$0U;PIENDB`pianobooster-src-0.6.4/src/images/paste.png0000644000175000017500000000315511304222711017735 0ustar louislouisPNG  IHDR szz4IDATx^[lTsًic$BJ!"-b/Kh+U`UڴV U')ċRy9iӄcj;z޳ghrl'}~sJ)$xxkH)w(' ChRcdY@9&`]DDnΉ+WP]S@Pe(A)fi^/Nl;G|[CL;D2Ķ!!p>Sl;D*@P4`Hi$N8!҇g em(AXW%DBs\=AX\$}-ZܱcGYUU~ХKܮ֪DU,s1O(Ja Aرlr?+ M"fxGuuPKի(ZA-ڶ8XŒL{;76|/g2f>v&.A,٩:l!Y-BPDz8`Yx555 rȑbmt0f#6,2cy.Er<,A65fm8Xt SˍӲ}: /s$$IR躬3Νѣ>|^,Ok/&7|k.-dk{N^VsogwMܝvrugk?x<8%8#%A:߽Mծ(bBYlArfOfrad^g2ƅ퇡ʹ755 FqolH;L^Éy[Iy%c fܝ2 L'ط+%3{=ku*2J+Zpc(,R{}$eLM|`ƸP#Sxv}hL aXx!B-iC#jc! s߃ʣ2G(akK!%0*\@X*#plYD\ϓ=RPjYVL v_=gӺ2y_hίp%x LO3DŗY\N`S(%mR}[tjWo7SpSx3i %Ղ)3u3}r7oDT_p =?~Bv;su]pW@2 ~*ӽi9thӶ}%XXX'O>Iʭ*;nLRYt= АӓNΞ.)055U/"SN%/g~쮸 KvO&@@aZ`;ߊ$^saw3n`pt___̙3ťЏxc!DxOis*_IENDB`pianobooster-src-0.6.4/src/images/open.png0000644000175000017500000000403111304222711017554 0ustar louislouisPNG  IHDR szzgAMAOX2tEXtSoftwareAdobe ImageReadyqe<IDATXíW[Pgb/nٛκ;{z:vTpuֶT mQB!@Hs$!grB GTx~0X}g/>ߗ]v uH W*e`[ '3">vH~Y2ϭB9DQ臆={XSR,::NI1>I,`]YSMM4 1y`Ż?ū)LOϮ׼tCO3@{=.4W S2^5C`\&K|H$8As''H׻ "U77N,V>V:q,k,'6?F}oY1~ Z{?0L(CF&e-,!4{Z;~m$~CF=5iu?PZlY]/sq 1% cbjC'ݼ-Ӱ;3&SXO!,CPF BBsZ*tȼE lϛ'Ào%Q(/bM$"R-BySt < ] /yƪԳs LŔbK˫#7G<<b~/=/-:C(QNܿ}3i 3Th58 X\3>GelAC'b ER$nPD΋J~ m['Ѡe")(Ȑx5 >c f]KcNzI1N[;|%jJ0("3 t.| J*qQF@7 jH7'@L{RE qAAͷ]lC(N#KQWHoXQG `4QɫgA@?noiқ*/ru)S)+vQŕky8n3cjs@"mDžPt +4X$ |J8aVU;:!z/]&o8=cn*F׃H:381 ^QO`+] 9g=JUmCeS@%`+njǩD9|6ZZ8/95j'zLIdnFڍv9,9=NrG ;Fc9=pOJnX,P(@!F.[! o<<5iEX?7Ǎ: !p5U!4[7*4nI:rsm$Jesp)>|c.2*\"]~M 6tvw䈶"I m2JxLKIõ.|me6Y\Q{ %&6ǝՂ^NEXx]\UPuTA/ rjQCO-H/5z-Wxܯ\u˯Ev2g`§ҩ;P 9 /"mak^2/f_=IENDB`pianobooster-src-0.6.4/src/images/new.png0000644000175000017500000000152411304222711017410 0ustar louislouisPNG  IHDR szzgAMAOX2tEXtSoftwareAdobe ImageReadyqe<IDATX՗Na5{q\\0&bXX ѝRHECey{QJ!Iޜ3MN"SsՐn==d 12<S(CfIkR׾TUNK޷’=Oޣqnl4kZS YoK|mu5e<7ɺx&oFh?B~Ql% wIENDB`pianobooster-src-0.6.4/src/images/logo64x64.png0000644000175000017500000000652211304222711020276 0ustar louislouisPNG  IHDR@@% sRGB pHYs  tIME + IDAThZkp]u>,i$zX-&*ƱҐ:LL tBI IBpml,6~Zҽ}^q%Y:J{h4g^k}[ÇI.*ovOxQ;uǝ !K4@vn=@ke` L-m#"EQ,Z8usssKKKǎ{衇TնB3q0`;Y8\@PRMxq7s=/z߾?1 G1MͣoJ)0 ^^'O%S[c%(ݛlvBx 6mڴ(RǏ@8~ׯAϗ5Ux=y!@D9+iee'-cfn3DO9 vks;<\*++Mu9iǏwfկ>Orp+#2r$-r#sl14<Z459!׭+ZGk`Ů e?8%lz~n* +^U 8Qc!@q)߁^@Fu¸ 2SR7+Yr"(wثJfZCFDp:NM ^07P5Ƕazg,$S-B2uA}@P_/tt*Ri1F,Gq*KV`-HH fpyf *u{OOMsrF^i3gϬ@R:+Ls7$HHA F.'?J$E׺q9= &:# HFY\&Vğr6'#@97TWW[_Wly`Ez4ͮwt]_@|uo͐aH]Ddu}_Я7<*ŌCCm5`F +R "4ғRL )>^pv1RU1Iϊ^8J"-\D>bfm-|d$~QQ^[L$GGH,ԙ\صar/Zd)HH7:C"*I>0MFŜd !ӲbS{:Ouȏd$ɨ7x 2,q2s(Sf.(ZgI(G:\}o?d-WQ{~$H, 0w\\2"KƽiaT |9hnoK^&HE>`.*)(O% ٵRG];>&B*򳁷b%xp$2$i*&; MѢ`ܱƿ{kP鵟 MOL֔HCf>^/ _PAm!n@lXɖ{WMB wڭur̓3;/+=BKRHм55ӡ}kt|Rs ML ~8<1"SY0Vf@4 >>YHzU'BDs@#0h7nP __WcA#8yuEHRIy>%@Qm& REc2x/ eWxr|cA;qmc~NWֶXztqo^>tywX쐒<EAڗcJ\Ʃ:ȜZ 3Pf^+K}||NcFE~gǑ?[WB*]X*Y9Y lVI-T մ4+"9Q-O@M.?uC߿cKOX؞UMLE2'=wL)$K[VVtZ[clBຠ69tC^^*o:P ,YFm&cRD/[H1A͂ lBVLZ`vETB%viz + ]c_> VRlv-㯾t^-EQ47\p<ˆ7uȱUYI9ߙ泭Dz74+)5=X?5x2nV~ﻑH$/[nZ_BtWVV3ODN"$X,<6-ӊ5@؁}@%Han@50t\]VZe7"Z[[[[[dLJ O>Y8i=:)W6S@"8Tt5.Ev|@:]\ kL;3N*]IENDB`pianobooster-src-0.6.4/src/images/cut.png0000644000175000017500000000245311304222711017414 0ustar louislouisPNG  IHDR szzgAMAOX2tEXtSoftwareAdobe ImageReadyqe<IDATXWkLW>#q2Te82f,[p0`.:N1[ X^f 1F-ܨji ܸ aٲ<}^J t (Dq+Fdf"LċGȡȎ;82a+A 0H.݀@2yMrhd^QGнM @t/2= ?H,1yK&B+6F\N 9c6 +A )*7G{̉@DT+, 6FHd*{.T74*TbR,XtzEUȠmts!sQ唃.ݯ˰>`y>^/'g`^3vshG .7wsaؽ^/fߩ6Bϥ-~mTk__sbrVNćԌ08@1~m%[ . $6{B o<ѽVw\Rz0L u5QdQD>v̴@O_~2 D"T*Jh K[9Sy,"džS)⠠ x`X@[^& -Sg L[{` b̄"P`ɹۧu.K)pjx)>+![cG&ؒrdo-- 8b\iF&2,3;3zb<{fO[5XCC=4442e<(6]*2x}.Zl1 %q/'_D Lh>u Ɩ1 f6m8h*>]XGZY Cɑ8 9!\ ϳ7ODIENDB`pianobooster-src-0.6.4/src/images/copy.png0000644000175000017500000000247211304222711017574 0ustar louislouisPNG  IHDR szzgAMAOX2tEXtSoftwareAdobe ImageReadyqe<IDATXõ]L[ewoI q&NpхDP+.&J'Тl9@lC +(іJ{*<9o!,/zc@}}P2Ff dn:~E"+*0@mWڪ4|S5@f:eCբcw*wڻeyBgg'zzz8PIiniog%3 @(cmm | =@A677vVUG;%$3O$(+6Z0'<=MIɩJ=0|qɘPzHk朙WdSjF< fd(;dH=sӹ@ eU-:c}iv]=&rJ*pW=~g.@DqL+++X__'Yt POe24XdNi)9D@|[O~uqq,~Nm7d,m72%#'hf[O5xGJ.7RR:)"E\---n`җ `}iiC ͲТRNxT;5`Zy `0$g@SS[gJO"7@GGG#mmm|A'@ss3JGT?U???h4:ô]L0xGRv:bJJo>ޙ#gSuVnłHmm377WVFLAnC9VpIENDB`pianobooster-src-0.6.4/src/images/README.txt0000644000175000017500000000036311304222711017607 0ustar louislouis == TO COMPILE THE SOURCE CODE == In the PianoBooster directory type "cd build" to change to the "build" directory then type "cmake ../src", followed by "make". There is no installer yet (the command "make install" has not been tested) pianobooster-src-0.6.4/src/images/Logo32x32.png0000644000175000017500000000234611304222711020224 0ustar louislouisPNG  IHDR IDATHOhU?i_7eYHaW@hւBP=U֞ڋ؛x' "(d R=3إ>ٝ6{~F<Aj2.-ɩs!ă=L X" U|5 V`jvKXu$FI5fzcqpժ ]~I jWŴԮ bm!bPF1(1GgBl0j1FV@uQ).Rʃ (JEނez"lʦb6YԎtR2ĩ#dDcщb:7| y F yoH0 [8l::^tDM6g^Uoe Dn.lM ,^uuFz;ugݶ=yԼ=hy`TǂQ0@H8[+n1J@Cv`i7zq P=Z?yqŸ uA<2w űbBu~7yvw%^Vܕz lM#fO;IzM;w`XRkn./* *A>$XNSs QV;TtscA5}mF4/~t U>3q12q4X]N ]*X[bªalSQ0bTrM£U瑂:"ډ/{AqD_cM~1o3+4XaO_"{mUm9Ul:ro{^|ɕ,/??d ;d}p: Z5踛[AI q]l?緼Ul_h"#*/!ϰkZ/ΎgܘS1"9t4ʮVR-8C?^^O7@r<z F ; (4gwVd:E$0U;PIENDB`