commit 88254d7e24149a43fb20b72820e3b7a82153e775 Author: Brian K. Holman Date: Wed Nov 18 12:28:31 2026 -0700 Publish the reproducible Sound Lab and FPGA Colour Lab sources diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f6dc6fe --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.build/ +__pycache__/ +*.pyc +.DS_Store diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..0464e87 --- /dev/null +++ b/README.md @@ -0,0 +1,72 @@ +# VCC Plus Diagnostics + +Standalone diagnostic disks for the Tandy Color Computer, VCC Plus, and +compatible FPGA implementations. Designed by Brian Holman · Sponsored by +Dezota LLC. + +| Diagnostic | Tagged release | Get started | +| --- | --- | --- | +| Sound Lab | [SL1-44B5F46F](https://vccplus-git.brianholman.com/VCCPlus/VCCPlusDiagnostics/releases/tag/sound-lab-sl1-44b5f46f) | Use Disk BASIC and a Speech/Sound Cartridge. Boot a writable copy in drive 0 with `DOS`. | +| FPGA Colour Lab | [CL1](https://vccplus-git.brianholman.com/VCCPlus/VCCPlusDiagnostics/releases/tag/fpga-colour-lab-cl1) | Use Disk BASIC and enable compatible FPGA 256-color support. Leave the Speech/Sound Cartridge out. Run `RUN"COLORLAB"` from drive 0. | + +Use a fresh machine session and keep a pristine disk master. The release pages +link to the exact disk, checksum and source package hosted in the VCC Plus +download area. The [compatibility paper](https://vccplus.brianholman.com/publications/ssc-fpga256/) +identifies the results obtained with these disk revisions. + +## Build from a tag + +Check out the release tag for the diagnostic you want to reproduce. + +### Sound Lab + +Use Python 3.10 or later and [VCC Plus 3.7.1 build 67's installed Mac toolchain](https://vccplus.brianholman.com/dl/software/VCCPlus/3.7.1-67/VCC-Plus-for-Mac-3.7.1-67-Universal.dmg), +which supplies CMOC 0.1.101, LWTools 4.25, the guest SSC and Disk BASIC +libraries, and the disk writer and boot-loader installer. The macOS command +below assumes the application is installed in Applications. + +```sh +export PYTHONDONTWRITEBYTECODE=1 +python3 examples/sound-lab/check.py \ + --toolchain '/Applications/VCC Plus.app/Contents/Resources/Toolchain' \ + --output .build/sound-lab-sl1 +``` + +This runs the host checks, builds the disk, and records the input and output +hashes. The published source package contains the build inputs for the guest +libraries and the source or build recipes for the toolchain components used by +this release. See [Sound Lab operation and reporting](examples/sound-lab/README.md). + +The optional headless VCC test compiles the retained runner against a local +VCC Plus checkout and built core library. On macOS set +`CPATH` to `/tests/toolchain/ssc`, then add `--core` and +`--roms` with the paths to the core library and your local ROM directory. +The test boots a disposable copy and measures digital behavior and audio +activity. Listening assessments are recorded separately. + +### FPGA Colour Lab + +Use Python 3 and LWASM 4.25. The builder accepts an executable path on Mac +or Windows: + +```sh +python3 examples/fpga256/build.py --lwasm /path/to/lwasm --output .build/colour-lab-cl1 +``` + +On Windows use `py -3` and the path to `lwasm.exe`. See the +[Colour Lab controls](examples/fpga256/README.md) and the +[Windows FPGA handoff](docs/windows-handoff.md). + +## Ownership and attribution + +Maintain standalone diagnostic sources here. App and FPGA tests consume a +specific tagged release and verify the disk hash before making test copies. +The examples at the initial tags preserve the source inputs used to build +the published disks. + +The original diagnostic source is GPL-3.0-or-later. See [COPYING](COPYING). +The Sound Lab bootstrap retains Pierre Sarrazin's public-domain notice and +credits Roger Schrag. The corresponding Sound Lab sources carry their +component notices. FPGA Colour Lab exercises the CoCo3FPGA extension by +Gary Becker and the MiSTer adaptation by Stan Hodge, Gary Becker and Alan +Steremberg. ROMs are supplied locally by the user for emulator tests. diff --git a/docs/windows-handoff.md b/docs/windows-handoff.md new file mode 100644 index 0000000..58bcd17 --- /dev/null +++ b/docs/windows-handoff.md @@ -0,0 +1,30 @@ +# Windows and FPGA diagnostic handoff + +Use this repository as the only maintained home for Sound Lab and FPGA +Colour Lab. Keep the FPGA harness and captures in the research repository. +Pin the diagnostic release in each test receipt. + +| Diagnostic and release | Verified master SHA-256 | +| --- | --- | +| [Sound Lab SL1-44B5F46F](https://vccplus-git.brianholman.com/VCCPlus/VCCPlusDiagnostics/releases/tag/sound-lab-sl1-44b5f46f) | `56030b65202a2cc6fc2c9933327a766aa704febb27d9cca7bfcb42c2af6de6b6` | +| [FPGA Colour Lab CL1](https://vccplus-git.brianholman.com/VCCPlus/VCCPlusDiagnostics/releases/tag/fpga-colour-lab-cl1) | `d0ad804254c03f92de9fc8745fe068fdbd1a8d90bb069bd41ddf5a8541861c36` | + +Download the disk from its release page. In PowerShell, use +`Get-FileHash -Algorithm SHA256 .\SOUNDLAB.DSK` or +`Get-FileHash -Algorithm SHA256 .\COLORLAB.DSK`. Compare it with the expected +master hash, then create a writable copy for each test. Retain Sound Lab +reports from the writable copy separately. Its modified disk hash is a +result of the session. + +For a local Colour Lab rebuild, check out `fpga-colour-lab-cl1`, then run +`py -3 examples/fpga256/build.py --lwasm C:\path\to\lwasm.exe --output .build/colour-lab-cl1` +with LWASM 4.25. The exact Sound Lab build recipe uses VCC Plus's pinned +Mac toolchain. The verified raw disk is the Windows test input. + +If the current test run uses local diagnostic edits or other disk bytes, retain +the original run and its identities. Before switching inputs on the next run, +compare those sources against the tags and report any differences. Include +application and FPGA branch tips, any commits absent from their pushed refs, +uncommitted source changes, generated disk hashes, and which inputs were used +for the run. Coordinate forward changes in this repository after the running +FPGA qualification completes. diff --git a/examples/fpga256/README.md b/examples/fpga256/README.md new file mode 100644 index 0000000..511b92a --- /dev/null +++ b/examples/fpga256/README.md @@ -0,0 +1,54 @@ +# FPGA Colour Lab + +Assembly-only, user-facing diagnostic for the optional CoCo3FPGA/MiSTer +256-color extension and VCC Plus's matching core option. It is **not a standard +CoCo graphics mode**. Use a fresh disposable BASIC machine; the diagnostic uses +physical RAM4000..B7FF as its framebuffer. Eject SSC and enable the extension. +No private ROM bytes are included in the source or disk. + +## Build + +Python3.9+ and LWASM4.25 are sufficient, on Windows or Mac/Linux: + +```sh +python3 examples/fpga256/build.py --lwasm /absolute/path/to/lwasm --output .build/colourlab-run1 +``` + +On Windows, supply `lwasm.exe` and the installed Python executable. The builder +requires a fresh output folder and preserves prior disks. VCC Plus on Mac +bundles LWASM in its compiler stack; no C/CMOC build is needed here. +The tracked `generated.inc` also lets the native assembly workspace assemble +`colorlab.asm` directly. The Python builder regenerates that include and creates +the complete test disk; the include is authored test data, not a private ROM. + +Outputs: COLORLAB.DSK (35-track DECB), COLORLAB.BIN, ASCII COLORLAB.BAS, listing, +generated banner/palette input and a source/artifact SHA256 manifest. Keep the +master and manifest together; copy the disk for interactive tests. + +## Play and inspect + +In the Mac development build, enable **FPGA 256-color support** in Machine +Settings and apply the change. Mount a writable copy in FD0 in Disk BASIC. +Type `RUN"COLORLAB"`, read the instructions, then +press any key. The launch assumes ordinary32-column BASIC and returns to that +mode; it does not attempt to read back write-only GIME registers. + +- **Grid:** 16 columns ×16 rows,256 distinct colors. Small cells are ordered + left-to-right, then top-to-bottom. Look for missing/duplicated cells or colors. +- **Space:** cycle grid, byte ramp and one-pixel alternating stripes. Look for + stable edges and consistent pixel ordering/row alignment. +- **A:** toggle palette animation. Colors move without redrawing the picture; + the black/white header entries are retained for readable controls. +- **Q:** restore the saved MMU mapping, standard BASIC video/ROM setup and caller + stack, then return. The keyboard is scanned directly and debounced, avoiding + patched BASIC POLCAT hooks while in the temporary graphics mapping. + +Take a gallery photograph/screenshot, note platform/core/version and which +controls worked, then report any missing colors, seams or unexpected resets. +The disk does not claim to measure analog calibration. It does not yet save a +result file; automatic native tests record exact pixel/control checks separately. + +Guest validation covers actual assembly on both 6809 and 6309 engines and a real +Disk BASIC RUN/LOADM/EXEC path. This is distinct from native Mac UI or physical +MiSTer acceptance. See the [Mac validation record](../../docs/development/FPGA256_MAC_VALIDATION.md) +for the separate host checks. diff --git a/examples/fpga256/build.py b/examples/fpga256/build.py new file mode 100644 index 0000000..691d9b6 --- /dev/null +++ b/examples/fpga256/build.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-or-later +"""Build the assembly-only FPGA Colour Lab disk with native LWASM/Python.""" +import argparse +import hashlib +import itertools +import json +from pathlib import Path +import shutil +import subprocess + +PROJECT = Path(__file__).resolve().parent +FONT = dict(zip('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ', [ + '25755','65656','34443','65556','74647','74644','34553','55755','72227', + '11152','55655','44447','57755','57775','25552','65644','25573','65655', + '34216','72222','55557','55552','55575','55255','55222','71247', + '75557','26227','61247','61216','55711','74616','34652','71111','25652','25716','00000'])) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--lwasm', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + a = parser.parse_args() + output = a.output.resolve() + if output.exists(): parser.error('Use a fresh output folder; preserve prior disks.') + output.mkdir(parents=True) + version = subprocess.check_output([str(a.lwasm.resolve()), '--version'], text=True).strip() + image = bytearray(160*32) + for text, y in [('FPGA COLOUR LAB 256',2),('SPACE NEXT A AUTO Q QUIT',12),('1 GRID 2 RAMP 3 STRIPES',22)]: + left = (160 - len(text)*4)//2 + for n,c in enumerate(text): + for row, bits in enumerate(FONT[c]): + for bit in range(3): + if int(bits)&(4>>bit): image[(y+row)*160+left+n*4+bit]=255 + runs=[] + for value, group in itertools.groupby(image): + count=len(list(group)) + while count: + part=min(count,255); runs.extend([part,value]);count-=part + runs.append(0) + words=[] + for i in range(256): + r,g,b=i>>5,(i>>2)&7,i&3 + value=((r>>2)<<11)|(((r>>1)&1)<<8)|((r&1)<<5)|((g>>2)<<10)|(((g>>1)&1)<<7)|((g&1)<<4)|((b>>1)<<9)|((b&1)<<6) + words.extend([value>>6,value&63]) + with (output/'generated.inc').open('w') as f: + for label,data in [('colours',words),('banner',runs)]: + f.write(label+'\n') + for start in range(0,len(data),16):f.write(' fcb '+','.join('$%02x'%v for v in data[start:start+16])+'\n') + shutil.copy2(PROJECT/'colorlab.asm',output/'colorlab.asm') + subprocess.run([str(a.lwasm.resolve()),'--format=decb','--output=COLORLAB.BIN','--list=COLORLAB.lst','colorlab.asm'],cwd=output,check=True) + binary=(output/'COLORLAB.BIN').read_bytes() + assert binary[0]==0 and int.from_bytes(binary[3:5],'big')==0x2000 + assert 0x2000+int.from_bytes(binary[1:3],'big')<0x4000,'Code must stay below remapped framebuffer' + basic=b'10 PCLEAR1:CLEAR200,&H1FFF:CLS\r20 PRINT"FPGA COLOUR LAB - EXTENSION ONLY"\r30 PRINT"ENABLE 256 COLOURS; EJECT SSC."\r40 PRINT"GRID: 16 BY 16 DISTINCT COLOURS"\r50 PRINT"SPACE: NEXT PATTERN A: ANIMATE"\r60 PRINT"Q: RETURN. STANDARD COCO UNSUPPORTED"\r70 PRINT"PRESS ANY KEY TO START"\r80 IF INKEY$="" THEN80\r90 LOADM"COLORLAB":EXEC\r100 PRINT"RETURNED FROM COLOUR LAB"\r' + (output/'COLORLAB.BAS').write_bytes(basic) + disk=bytearray(b'\xff'*(35*18*256)); fat=(17*18+1)*256; directory=(17*18+2)*256; nextgranule=0 + for index,(name,data,kind,ascii_flag) in enumerate([('COLORLAB.BAS',basic,0,255),('COLORLAB.BIN',binary,2,0)]): + first=nextgranule; count=(len(data)+2303)//2304 + for n in range(count): + g=nextgranule; nextgranule+=1; chunk=data[n*2304:(n+1)*2304] + offset=((g//2+(g>=34))*18+(g%2)*9)*256 + disk[offset:offset+len(chunk)]=chunk + disk[fat+g]=(g+1) if n+1 len(raw): + raise ValueError("invalid WAV format chunk") + format_tag = int.from_bytes(raw[offset + 8:offset + 10], "little") + break + offset += 8 + size + (size % 2) + if format_tag != 1: + raise ValueError("only WAVE_FORMAT_PCM integer WAV is supported; convert compressed, float or extensible WAV explicitly") + try: + with wave.open(io.BytesIO(raw), "rb") as source: + if source.getcomptype() != "NONE": + raise ValueError("only uncompressed integer PCM WAV is supported") + width = source.getsampwidth() + channels = source.getnchannels() + rate = source.getframerate() + frames = source.getnframes() + if width not in (1, 2, 3, 4): + raise ValueError("supported PCM widths are 8, 16, 24 and 32 bits") + if rate <= 0 or channels <= 0 or frames <= 0: + raise ValueError("WAV must contain samples at a positive rate") + payload = source.readframes(frames) + except (wave.Error, EOFError) as error: + raise ValueError("unsupported or invalid PCM WAV: " + str(error)) from error + if len(payload) != frames * channels * width: + raise ValueError("truncated WAV sample data") + samples = [[] for _ in range(channels)] + for index in range(0, len(payload), width): + value = int.from_bytes(payload[index:index + width], "little", signed=width != 1) + if width == 1: + value -= 128 + samples[(index // width) % channels].append(value) + return samples, { + "filename": Path(path).name, "sha256": sha256(raw), "byte_count": len(raw), + "sample_rate_hz": rate, "channels": channels, "bit_depth": width * 8, + "frame_count": frames, "duration_seconds": frames / rate, + "format": "uncompressed integer PCM", "sample_rate_source": "WAV header; not clock calibration", + } + + +def validate_manifest(document, info): + if isinstance(document, list): + segments = document + elif isinstance(document, dict): + segments = document.get("segments") + else: + segments = None + if not isinstance(segments, list) or not segments: + raise ValueError("manifest must contain a nonempty segments list") + checked = [] + for index, segment in enumerate(segments): + label = "segment " + str(index) + if not isinstance(segment, dict): + raise ValueError(label + " must be an object") + case_id = segment.get("case_id") + if not isinstance(case_id, str) or not case_id.strip(): + raise ValueError(label + " needs a nonempty case_id") + if segment.get("kind") not in KINDS: + raise ValueError(label + " has unsupported kind") + start = finite_number(segment.get("start_seconds"), label + " start_seconds") + end = finite_number(segment.get("end_seconds"), label + " end_seconds") + if start < 0 or end <= start or end > info["duration_seconds"]: + raise ValueError(label + " interval must satisfy 0 <= start < end <= WAV duration") + # Samples at timestamps start <= n/rate < end; no implied counter alignment. + first = math.ceil(start * info["sample_rate_hz"]) + stop = min(info["frame_count"], math.ceil(end * info["sample_rate_hz"])) + if stop <= first: + raise ValueError(label + " interval contains no sample timestamps") + item = dict(segment) + item.update(start_seconds=start, end_seconds=end, start_frame=first, stop_frame=stop) + vector_id = item.get("vector_id") + if vector_id is not None and (not isinstance(vector_id, str) or not vector_id.strip()): + raise ValueError(label + " vector_id must be a nonempty string when supplied") + if "nominal_hz" in item: + nominal = finite_number(item["nominal_hz"], label + " nominal_hz") + if item["kind"] != "tone" or not 0 < nominal < info["sample_rate_hz"] / 2: + raise ValueError(label + " nominal_hz needs a tone below the Nyquist frequency") + item["nominal_hz"] = nominal + tolerance = item.get("frequency_tolerance") + if tolerance is not None: + if not isinstance(tolerance, dict) or "nominal_hz" not in item: + raise ValueError(label + " frequency_tolerance needs nominal_hz") + limit = finite_number(tolerance.get("absolute_hz"), label + " absolute_hz") + qualification = tolerance.get("qualification") + if limit < 0 or not isinstance(qualification, str) or not qualification.strip(): + raise ValueError(label + " tolerance needs a nonnegative absolute_hz and qualification") + checked.append(item) + return checked + + +def tone_estimate(values, rate): + """Interpolated upward crossings after DC removal, meaningful only for pure tones.""" + mean = statistics.fmean(values) + crossings = [] + for index in range(1, len(values)): + before, after = values[index - 1] - mean, values[index] - mean + if before < 0 <= after: + crossings.append(index - 1 + (-before / (after - before))) + result = { + "technique": "DC-removed linearly interpolated upward zero crossings", + "limitations": "Pure-tone estimate only. Harmonics, noise, clipping and transients can add crossings or bias the fundamental. No clock calibration is inferred.", + "upward_crossing_count": len(crossings), "estimated_hz": None, + } + if len(crossings) < 3: + result["availability"] = "INSUFFICIENT_CROSSINGS" + return result + periods = [b - a for a, b in zip(crossings, crossings[1:])] + mean_period = statistics.fmean(periods) + result.update( + availability="OBSERVED", estimated_hz=rate / mean_period, + crossing_period_variation_ratio=statistics.pstdev(periods) / mean_period, + measured_span_seconds=(crossings[-1] - crossings[0]) / rate, + ) + return result + + +def channel_metrics(values, bits, rate, segment): + full_scale = 2 ** (bits - 1) + count = len(values) + dc = statistics.fmean(values) + result = { + "rms_full_scale": math.sqrt(sum(value * value for value in values) / count) / full_scale, + "ac_rms_full_scale": math.sqrt(sum((value - dc) ** 2 for value in values) / count) / full_scale, + "peak_full_scale": max(abs(value) for value in values) / full_scale, + "dc_offset_full_scale": dc / full_scale, + "clipping_count": sum(value in (-full_scale, full_scale - 1) for value in values), + "near_zero_ratio": sum(abs(value) <= 1 for value in values) / count, + "near_zero_definition": "absolute signed PCM value <= 1 LSB; a measurement, not an audibility threshold", + "assessment": "MEASURE_BASELINE", + } + if segment["kind"] == "tone": + estimate = tone_estimate(values, rate) + result["frequency"] = estimate + if "nominal_hz" in segment and estimate["estimated_hz"] is not None: + delta = estimate["estimated_hz"] - segment["nominal_hz"] + estimate["nominal_hz"] = segment["nominal_hz"] + estimate["difference_hz"] = delta + tolerance = segment.get("frequency_tolerance") + if tolerance: + estimate["qualified_tolerance"] = tolerance + result["assessment"] = ("WITHIN_QUALIFIED_TOLERANCE" if abs(delta) <= tolerance["absolute_hz"] + else "OUTSIDE_QUALIFIED_TOLERANCE") + return result + + +def repeated_cases(segments): + groups = {} + for index, segment in enumerate(segments): + if segment.get("vector_id"): + groups.setdefault((segment["case_id"], segment["vector_id"]), []).append(index) + comparisons = [] + for (case_id, vector_id), indexes in groups.items(): + if len(indexes) < 2: + continue + reference = segments[indexes[0]] + for index in indexes[1:]: + current = segments[index] + if current["kind"] != reference["kind"]: + continue + channels = [] + for base, observed in zip(reference["channels"], current["channels"]): + delta = {key + "_difference": observed[key] - base[key] + for key in ("rms_full_scale", "peak_full_scale", "dc_offset_full_scale")} + a = base.get("frequency", {}).get("estimated_hz") + b = observed.get("frequency", {}).get("estimated_hz") + if a is not None and b is not None: + delta["estimated_hz_difference"] = b - a + channels.append(delta) + comparisons.append({ + "case_id": case_id, "vector_id": vector_id, + "reference_segment_index": indexes[0], "observed_segment_index": index, + "duration_difference_seconds": current["sample_duration_seconds"] - reference["sample_duration_seconds"], + "channels": channels, "assessment": "OBSERVED", + }) + return comparisons + + +def analyze(wav_path, manifest_path): + samples, info = load_pcm(wav_path) + manifest_bytes = Path(manifest_path).read_bytes() + try: + document = json.loads(manifest_bytes) + except (ValueError, UnicodeDecodeError) as error: + raise ValueError("invalid JSON manifest: " + str(error)) from error + segments = validate_manifest(document, info) + measurements = [] + for segment in segments: + first, stop = segment["start_frame"], segment["stop_frame"] + item = dict(segment) + item.update( + sample_count_per_channel=stop - first, + first_sample_seconds=first / info["sample_rate_hz"], + exclusive_stop_seconds=stop / info["sample_rate_hz"], + sample_duration_seconds=(stop - first) / info["sample_rate_hz"], + byte_offset_in_pcm_payload=first * info["channels"] * (info["bit_depth"] // 8), + observation_status="OBSERVED", human_status="NOT_OBSERVED", + channels=[channel_metrics(values[first:stop], info["bit_depth"], info["sample_rate_hz"], segment) + for values in samples], + ) + measurements.append(item) + return { + "schema_version": 1, "capture": info, + "manifest": {"filename": Path(manifest_path).name, "sha256": sha256(manifest_bytes)}, + "reported_capture_context": document.get("capture_context", {}) if isinstance(document, dict) else {}, + "assessment": "MEASURE_BASELINE", "human_status": "NOT_OBSERVED", + "interval_convention": "[start_seconds,end_seconds); include sample timestamps n/rate in that interval; frames are zero based", + "limitations": "Measurements do not establish listening success, hardware identity, calibrated clock accuracy, analog equality or cross-target compatibility. Capture context is supplied by the user, not verified.", + "segments": measurements, "repeated_cases": repeated_cases(measurements), + } + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("wav", type=Path) + parser.add_argument("manifest", type=Path) + parser.add_argument("--output", type=Path, help="JSON output; stdout if omitted; existing files protected") + parser.add_argument("--overwrite", action="store_true", help="explicitly replace an existing report (never an input)") + args = parser.parse_args(argv) + try: + if args.output and args.output.resolve() in (args.wav.resolve(), args.manifest.resolve()): + raise ValueError("report output cannot replace either input") + report = analyze(args.wav, args.manifest) + serialized = json.dumps(report, indent=2, allow_nan=False) + "\n" + if args.output: + with args.output.open("w" if args.overwrite else "x", encoding="utf-8") as output: + output.write(serialized) + else: + sys.stdout.write(serialized) + except (ValueError, OSError) as error: + parser.exit(2, "error: " + str(error) + "\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/examples/sound-lab/build.py b/examples/sound-lab/build.py new file mode 100644 index 0000000..7404065 --- /dev/null +++ b/examples/sound-lab/build.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Build the standalone 35-track Sound Lab disk using the pinned CMOC bundle.""" +# SPDX-License-Identifier: GPL-3.0-or-later +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess + +PROJECT = Path(__file__).resolve().parent +REPO = PROJECT.parents[1] + + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def run(*args, **kwargs): + subprocess.run([str(a) for a in args], check=True, **kwargs) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--toolchain', type=Path, default=REPO/'platforms/macos/LocalResources/ToolchainBundle') + parser.add_argument('--output', type=Path, default=REPO/'.build/sound-lab') + args = parser.parse_args() + output, runtime = args.output.resolve(), args.toolchain.resolve() + if output == PROJECT or PROJECT in output.parents: + parser.error('Choose a build output outside the source project so generated files cannot become source inputs.') + output.mkdir(parents=True, exist_ok=True) + env = dict(os.environ, PATH=str(runtime/'bin')+os.pathsep+os.environ.get('PATH', '')) + version = subprocess.check_output([runtime/'bin/cmoc', '--version'], text=True).strip() + if '0.1.101' not in version: + parser.error('This revision is qualified with CMOC 0.1.101; review a different compiler explicitly.') + assembler = subprocess.check_output([runtime/'bin/lwasm', '--version'], text=True).strip() + if assembler != 'lwasm from lwtools 4.25': + parser.error('This revision is qualified with LWTools 4.25.') + run('python3', PROJECT/'vectors/generate.py', '--output', output/'generated') + vectors = json.loads((output/'generated/vectors.json').read_text()) + sources = sorted(p for p in PROJECT.rglob('*') if p.is_file() and '__pycache__' not in p.parts) + source_hash = hashlib.sha256() + for source in sources: + source_hash.update(source.relative_to(PROJECT).as_posix().encode()+b'\0'+source.read_bytes()) + build_id = 'SL1-'+source_hash.hexdigest()[:8].upper() + (output/'generated/build.h').write_text( + '#define SOUNDLAB_BUILD "'+build_id+'"\n#define SOUND_VECTOR_SET_CRC16 0x'+vectors['vector_set_crc16']+'\n') + shutil.copy2(PROJECT/'guest/main.c', output/'main.c') + run(runtime/'bin/cmoc', '--coco', '-O2', '--intermediate', '--org=1600', '--limit=7A00', + '--stack-space=1024', '-Igenerated', '-o', 'SOUNDLAB.BIN', 'main.c', '-lssc', '-ldecbfile', cwd=output, env=env) + (output/'SOUNDLAB.BAS').write_bytes(b'10 PCLEAR1:CLEAR 32\n20 LOADM"SOUNDLAB":EXEC\n') + # Public-domain DOS hook by Pierre Sarrazin, retained with its attribution. + # Keep the hook itself as a normal source, with no Makefile parsing at build time. + shutil.copy2(PROJECT/'guest/boot.c', output/'boot.c') + run(runtime/'bin/cmoc', '--dos', '-O0', '--limit=2800', '-o', 'BOOT.BIN', 'boot.c', cwd=output, env=env) + disk = output/'SOUNDLAB.DSK' + disk.write_bytes(b'\xff'*(35*18*256)) + run(runtime/'bin/install-coco-boot-loader', disk, output/'BOOT.BIN', env=env) + for name in ('SOUNDLAB.BIN', 'SOUNDLAB.BAS'): + run(runtime/'bin/writecocofile', *(['--newlines'] if name.endswith('.BAS') else ['--binary']), disk, name, cwd=output, env=env) + manifest = dict(vectors, build_id=build_id, compiler=version, + assembler=assembler, + toolchain_manifest_sha256=digest(runtime/'manifest.json'), + libraries=[dict(filename=name,sha256=digest(runtime/'share/cmoc/lib'/name)) + for name in ('libssc.a','libdecbfile.a')], + sources=[dict(path=p.relative_to(PROJECT).as_posix(),sha256=digest(p)) for p in sources], + guest_cpu='MC6809', minimum_ram_kib=64, format='DECB 35x18x256', + source_sha256=source_hash.hexdigest(), + artifacts=[dict(filename=name, bytes=(output/name).stat().st_size, sha256=digest(output/name)) + for name in ('SOUNDLAB.BIN', 'SOUNDLAB.BAS', 'SOUNDLAB.DSK')]) + (output/'SOUNDLAB-manifest.json').write_text(json.dumps(manifest, indent=2)+'\n') + (output/'SHA256SUMS').write_text(''.join(f"{item['sha256']} {item['filename']}\n" for item in manifest['artifacts'])) + print(f'Built {build_id}: {disk}') + + +if __name__ == '__main__': + main() diff --git a/examples/sound-lab/check.py b/examples/sound-lab/check.py new file mode 100644 index 0000000..4a1d04c --- /dev/null +++ b/examples/sound-lab/check.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +"""Build/check Sound Lab; optional isolated native qualification uses explicit private inputs.""" +# SPDX-License-Identifier: GPL-3.0-or-later +import argparse +import os +from pathlib import Path +import subprocess +import sys + +PROJECT=Path(__file__).resolve().parent +REPO=PROJECT.parents[1] + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--toolchain',type=Path,default=REPO/'platforms/macos/LocalResources/ToolchainBundle') + parser.add_argument('--output',type=Path,default=REPO/'.build/sound-lab') + parser.add_argument('--core',type=Path,help='Existing libVCCCore.a; never changes or rebuilds the emulator') + parser.add_argument('--roms',type=Path,help='Private local CoCo3/Disk BASIC/PIC/SP ROM directory; not packaged') + args=parser.parse_args() + if bool(args.core)!=bool(args.roms): parser.error('--core and --roms must be supplied together') + output=args.output.resolve() + env=dict(os.environ,PYTHONDONTWRITEBYTECODE='1') + def run(*command): subprocess.run([str(p) for p in command],check=True,env=env) + run(sys.executable,'-m','unittest','discover','-s',PROJECT/'tests','-v') + run(sys.executable,PROJECT/'build.py','--toolchain',args.toolchain,'--output',output) + assembly=(output/'main.s').read_text() + status=assembly.split('_raw_status\tEQU\t*',1)[1].split('funcend_raw_status',1)[0] + if status.upper().count('LDB $FF7E')!=1: + raise RuntimeError('Generated raw status reader must contain exactly one actual FF7E load') + if args.core: + run('xcrun','clang++','-std=c++17','-O2','-mmacosx-version-min=14.0', + PROJECT/'native/run.cpp',args.core.resolve(),'-o',output/'run') + run(output/'run',args.roms.resolve(),output/'SOUNDLAB.DSK',output/'qualification') + run(sys.executable,PROJECT/'verify_reports.py','--build-dir',output) + else: + print('Native execution SKIPPED: provide --core and --roms for real-ROM qualification.') + + +if __name__=='__main__': main() diff --git a/examples/sound-lab/guest/boot.c b/examples/sound-lab/guest/boot.c new file mode 100644 index 0000000..729ef2f --- /dev/null +++ b/examples/sound-lab/guest/boot.c @@ -0,0 +1,38 @@ +/* Public domain. Adapted from Pierre Sarrazin's autostart.c 0.1.2 (2018-08-04). + * http://sarrazip.com/ -- Roger Schrag, The Rainbow, Nov 1984, p.140. + * DOS feeds an ordinary Disk BASIC command; no emulator-specific loader. + */ +#include +static byte oldHookInstr; +static word oldHookAddr; +static const char *basicLineReader; +void feedKeyboard(void) +{ + word preservedX; + byte nextBasicByte; + asm("stx", preservedX); + *(byte *)0x70=0; + nextBasicByte=*basicLineReader++; + if(!nextBasicByte) { + *(byte *)0x016A=oldHookInstr; + *(word *)0x016B=oldHookAddr; + nextBasicByte='\r'; + } + asm { + lda nextBasicByte + ldx preservedX + tfr u,s + leas 4,s + rts + } +} +int main(void) +{ + *(byte *)0=-*(byte *)0; + basicLineReader="PCLEAR1:CLEAR32:LOADM\"SOUNDLAB\":EXEC"; + oldHookInstr=*(byte *)0x016A; oldHookAddr=*(word *)0x016B; + *(byte *)0x016A=0x7E; *(void **)0x016B=(void *)feedKeyboard; + *(word *)0x2600=0; + asm("jmp", "$ac7c"); + return 0; +} diff --git a/examples/sound-lab/guest/main.c b/examples/sound-lab/guest/main.c new file mode 100644 index 0000000..6388be4 --- /dev/null +++ b/examples/sound-lab/guest/main.c @@ -0,0 +1,317 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Sound Lab: ordinary 6809/Disk BASIC guest. No emulator-private API. + * Audio routing uses the existing GPL VCC Plus SSC SDK unchanged. + */ +#include +#include +#include +#include +#include "vectors.h" +#include "build.h" + +#define LOG_CAPACITY 1536 +/* PCLEAR1 reserves the one unused PMODE page at $0E00..$13FF. + * Sound Lab is text-only; using that page leaves ample native stack space. */ +#define logbuf ((char *)0x0E00) +static char linebuf[180], note[49]; +static unsigned used, records, checksum, runno=1, route, transmitted, elapsed; +static unsigned saved_used, saved_records, saved_checksum; +static unsigned char saved_complete, have_checkpoint; +static unsigned char disk_mode, created, aborted, timedout, before, after, busy_seen; +static unsigned char disk_error, group, target, video, model; +static unsigned attempt; +static DECBDrive drives[1]; +static DECBFile report; +static char filename[13]; +static const char *targets[]={"VCCPLUS","REAL_COCO","MISTER"}; +static const char *models[]={"COCO3","COCO2_64K","UNKNOWN_64K"}; + +/* Unlike a C volatile expression, each call really reads the bus once. */ +asm unsigned char raw_status(void) { asm { ldb $FF7E } } +asm unsigned ticks(void) { asm { ldd $0112 } } +asm void put_byte(unsigned char value) { asm { ldb 3,s + stb $FF7E } } + +static unsigned crc_byte(unsigned crc, unsigned char c) +{ + unsigned char bit; + crc ^= (unsigned)c << 8; + for(bit=0;bit<8;++bit) crc=(crc&0x8000)?(crc<<1)^0x1021:crc<<1; + return crc; +} + +static void record(const char *s) +{ + unsigned n=strlen(s), i; + if(used+n+2>=LOG_CAPACITY) return; /* Caller reserves one full case. */ + for(i=0;i256) n=256; + for(i=0;i256) n=256; + memset(sector,0,256); + for(i=0;i=180 || ++polls>=150000UL) { timedout=1; return 0; } + if((polls&255)==0 && toupper(inkey())=='X') { aborted=1; return 0; } + } +} + +static void settle(const SoundVector *v) +{ + unsigned start=ticks(), d; + unsigned long polls=0; + unsigned char status; + for(;;) { + status=raw_status(); + d=ticks()-start; + if(v->wait_mask && (status&v->wait_mask)!=v->wait_mask) busy_seen=1; + if(d>=v->hold_ticks && (!v->wait_mask || ((status&v->wait_mask)==v->wait_mask && (busy_seen || d>=45)))) break; + if(d>=1800 || ++polls>=1500000UL) { timedout=1; break; } + if((polls&255)==0 && toupper(inkey())=='X') { aborted=1; break; } + } + elapsed=ticks()-start; +} + +static void stop_case(void) +{ + if(aborted || timedout) ssc_reset(); /* Partial packets require reset. */ + else if(!ready_write(0)) ssc_reset(); /* Manual: stop speech + sound. */ +} + +static void get_note(void) +{ + unsigned char c, n=0; + printf("NOTE (48 CHARS, ENTER ENDS):\n"); + while((c=key())!='\r') { + if(c==8 && n) { --n; putchar(8); } + else if(c>=32 && c<=126 && c!='\\' && n<48) { note[n++]=c; putchar(c); } + } + note[n]=0; +} + +static unsigned char run_case(const SoundVector *v) +{ + unsigned i, sent; + unsigned char answer; + unsigned repeat; + const char *human, *automatic; + do { + if(used>LOG_CAPACITY-450) { + if(!disk_mode) { + printf("RAM REPORT FULL. PHOTOGRAPH IT.\nX MENU / C CLEAR FOR NEXT RUN\n"); + if(key()!='C') return 0; + } + disk_error=save_report(1); + if(disk_error) { printf("REPORT FULL. SAVE FIRST.\n"); key(); return 0; } + ++runno; begin_report(); + } + repeat=attempt++; + header(v->id); + ssc_reset(); /* Declared per-case baseline; never inherited timer state. */ + printf("%s\n\n%s\n\nX: PANIC / RETURN TO MENU\n",v->title,v->prompt); + printf("\nENTER TO PLAY / X MENU\n"); + do answer=key(); while(answer!='\r' && answer!='X'); + if(answer=='X') return 0; + printf("PLAYING...\n"); + transmitted=elapsed=0; aborted=timedout=busy_seen=0; + before=raw_status(); + for(i=0;ilength;++i) if(!ready_write(v->tx[i])) break; + sent=transmitted; + if(!aborted && !timedout) settle(v); + after=raw_status(); + stop_case(); + header(v->id); + printf("ATTEMPT %u CRC %04X TX %u/%u\nSTATUS %02X > %02X TICKS %u\n%s\n\n", + repeat,v->crc16,sent,v->length,before,after,elapsed,aborted?"ABORTED":timedout?"TIMEOUT / RESET":"AUTO: OBSERVED ONLY"); + printf("H HEARD W WRONG\nN NO SOUND U UNSURE\nR REPEAT S SKIP\nT ADD NOTE X MENU\n\n"); + note[0]=0; + do { answer=key(); if(answer=='T') get_note(); } + while(!strchr("HWNURSX",answer)); + human=answer=='H'?"HEARD":answer=='W'?"WRONG":answer=='N'?"NO_SOUND":answer=='U'?"UNSURE":answer=='S'?"SKIPPED":"NOT_OBSERVED"; + automatic=timedout?"TIMEOUT":aborted&&!sent?"NOT_RUN":"OBSERVED"; + sprintf(linebuf,"CASE=%s VECTOR_CRC16=%04X AUTO=%s HUMAN=%s",v->id,v->crc16,automatic,human); record(linebuf); + sprintf(linebuf,"TX_COUNT=%u TX_EXPECTED=%u TICKS=%u STATUS_BEFORE=%02X STATUS_AFTER=%02X BUSY_SEEN=%s",sent,v->length,elapsed,before,after,busy_seen?"YES":"NO"); record(linebuf); + record("PRELUDE=RESET_01_00 TIMER=RESET_DEFAULT"); + sprintf(linebuf,"ABORTED=%s CLEANUP=%s REPEAT=%u",aborted?"YES":"NO",(aborted||timedout)?"RESET":"00",repeat); record(linebuf); + sprintf(linebuf,"NOTE_LENGTH=%u",strlen(note)); record(linebuf); + sprintf(linebuf,"NOTE=%s",note); record(linebuf); + sprintf(linebuf,"ENDCASE=%s",v->id); record(linebuf); + disk_error=save_report(0); + if(disk_error) { printf("DISK ERROR %u: RAM RETAINED\n",disk_error); key(); } + if(answer=='X') return 0; + } while(answer=='R'); + return 1; +} + +static void show_report(void) +{ + unsigned offset=0, rows; + header("FROZEN REPORT"); + while(offset'3'); target=choice-'1'; + header("SETUP"); + printf("1 COCO 3 2 COCO 2 3 OTHER\n"); + do choice=key(); while(choice<'1'||choice>'3'); model=choice-'1'; + printf("N NTSC / P PAL\n"); do choice=key(); while(choice!='N'&&choice!='P'); video=choice=='P'; + printf("\nD SAVE REPORTS TO THIS FD0\nM SCREEN ONLY / NO DISK I/O\nUSE A DISPOSABLE DISK COPY!\n"); + do choice=key(); while(choice!='D'&&choice!='M'); disk_mode=choice=='D'; + if(disk_mode) { + disk_error=decb_init(drives,1); + if(!disk_error) disk_error=decb_registerDrive(0); + if(disk_error) disk_mode=0; + } + route=ssc_route_audio(); + ssc_reset(); + begin_report(); + for(;;) { + header("MAIN MENU"); + printf("1 MEET THE ROBOT\n2 GUIDED LISTENING LAB\n3 ENGINEERING (OPT IN)\n4 CHOOSE A CASE\n5 VIEW RAM REPORT\n6 RETRY SAVE\nQ SAVE AND QUIT TO BASIC\n\nRUN %04u %s\n%s\n",runno,filename,!disk_mode?"SCREEN ONLY":disk_error?"DISK ERROR / RAM RETAINED":"REPORT SAVED BETWEEN CASES"); + choice=key(); + if(choice=='Q') { + disk_error=save_report(1); + if(disk_error) { printf("SAVE FAILED. X DISCARD OR RETRY\n"); if(key()!='X') continue; } + break; + } + if(choice=='5') { show_report(); continue; } + if(choice=='6') { disk_error=save_report(0); continue; } + if(choice=='4') { + char id[16]; unsigned char n=0,c; + header("CHOOSE CASE"); printf("CASE ID (UPPERCASE), ENTER:\n"); + while((c=key())!='\r') if(n<15 && ((c>='A'&&c<='Z')||(c>='0'&&c<='9')||c=='-')) { id[n++]=c; putchar(c); } + id[n]=0; + for(i=0;i'3') continue; + group=(unsigned char)(1<<(choice-'1')); + if(group==4) { header("ENGINEERING"); printf("MANY LOUD/REPEATED EXAMPLES.\nLOWER VOLUME. Y CONTINUE\n"); if(key()!='Y') continue; } + for(i=0;i int: + """CRC-16/CCITT-FALSE: polynomial 1021, initial FFFF, no reflection/xor.""" + result = 0xFFFF + for value in data: + result ^= value << 8 + for _ in range(8): + result = ((result << 1) ^ (0x1021 if result & 0x8000 else 0)) & 0xFFFF + return result + + +def granule_offset(granule: int) -> int: + track = granule // 2 + (1 if granule >= 34 else 0) + return (track * 18 + (granule % 2) * 9) * 256 + + +def extract_reports(disk: bytes) -> list[dict[str, Any]]: + """Validate active DECB files, return SNDnnnn.TXT ASCII bytes; never mutate disk. + + All active files are walked to catch crosslinks into a selected report. Unused + FAT allocations are tolerated: they can remain after an interrupted write. + """ + if len(disk) != DISK_SIZE: + raise SoundLabError(f"Expected raw 35-track DSK ({DISK_SIZE} bytes), got {len(disk)}") + fat = disk[FAT_OFFSET:FAT_OFFSET + 68] + for index, value in enumerate(fat): + if not (value < 68 or 0xC0 <= value <= 0xC9 or value == 0xFF): + raise SoundLabError(f"Invalid FAT value {value:02X} at granule {index}") + owned: dict[int, str] = {} + names: set[str] = set() + reports = [] + for index in range(72): + entry = disk[DIRECTORY_OFFSET + index * 32:DIRECTORY_OFFSET + (index + 1) * 32] + if entry[0] in (0, 0xFF): + continue + try: + base = entry[:8].decode("ascii").rstrip(" ") + ext = entry[8:11].decode("ascii").rstrip(" ") + except UnicodeDecodeError as error: + raise SoundLabError(f"Non-ASCII directory name at entry {index}") from error + if not base or any(ord(c) < 33 or c in '/\\:.' for c in base + ext): + raise SoundLabError(f"Unsafe directory name at entry {index}") + name = f"{base}.{ext}" if ext else base + normalized = name.upper() + if normalized in names: + raise SoundLabError(f"Duplicate directory name: {name}") + names.add(normalized) + if entry[11] > 3 or entry[12] not in (0, 0xFF): + raise SoundLabError(f"Invalid file type/ASCII flag for {name}") + last_bytes = int.from_bytes(entry[14:16], "big") + if last_bytes > 256: + raise SoundLabError(f"Invalid final-sector byte count for {name}") + chain = [] + current = entry[13] + while True: + if current >= 68: + raise SoundLabError(f"Out-of-range granule {current} for {name}") + if current in chain: + raise SoundLabError(f"FAT loop for {name}") + if current in owned: + raise SoundLabError(f"Crosslinked granule {current}: {name} and {owned[current]}") + chain.append(current) + owned[current] = name + value = fat[current] + if 0xC0 <= value <= 0xC9: + final_sectors = value - 0xC0 + if final_sectors == 0 and (len(chain) != 1 or last_bytes != 0): + raise SoundLabError(f"Invalid empty final granule for {name}") + if final_sectors > 0 and last_bytes == 0: + # DOS stores 256, not zero, for a completely used last sector. + raise SoundLabError(f"Missing final-sector bytes for {name}") + break + if value == 0xFF: + raise SoundLabError(f"Allocated file {name} points to free granule {current}") + current = value + length = (len(chain) - 1) * 2304 + if final_sectors: + length += (final_sectors - 1) * 256 + last_bytes + if REPORT_NAME.fullmatch(name): + if entry[12] != 0xFF: + raise SoundLabError(f"Report {name} is not marked Disk BASIC ASCII") + content = b"".join(disk[granule_offset(g):granule_offset(g) + 2304] for g in chain)[:length] + reports.append({"filename": normalized, "data": content, + "byte_count": len(content), "sha256": hashlib.sha256(content).hexdigest(), + "granules": chain, "directory_type": entry[11]}) + return sorted(reports, key=lambda item: item["filename"]) + + +def decode_note(value: str) -> str: + decoded = bytearray() + i = 0 + while i < len(value): + char = value[i] + if char != "\\": + if not 32 <= ord(char) <= 126: + raise SoundLabError("Notes must use printable ASCII or escaped control bytes") + decoded.append(ord(char)) + i += 1 + continue + i += 1 + if i >= len(value): + raise SoundLabError("Incomplete note escape") + escaped = value[i] + if escaped in "\\nrt": + decoded.append({"\\": 92, "n": 10, "r": 13, "t": 9}[escaped]) + i += 1 + elif escaped == "x" and i + 2 < len(value) and re.fullmatch(r"[0-9A-Fa-f]{2}", value[i + 1:i + 3]): + byte = int(value[i + 1:i + 3], 16) + if byte > 127: + raise SoundLabError("Escaped notes must remain ASCII") + decoded.append(byte) + i += 3 + else: + raise SoundLabError(f"Unknown note escape at position {i}") + return decoded.decode("ascii") + + +def parse_tokens(line: str) -> dict[str, str]: + fields = {} + for token in line.split(): + if "=" not in token: + raise SoundLabError(f"Expected KEY=VALUE token: {token}") + key, value = token.split("=", 1) + if not KEY.fullmatch(key) or not value or key in fields: + raise SoundLabError(f"Invalid or duplicate token: {token}") + fields[key] = value + if not fields: + raise SoundLabError("Empty record") + return fields + + +def parse_report(data: bytes, source: str = "") -> dict[str, Any]: + """Parse evidence without turning automatic observations into listening results. + + Incomplete files are useful evidence, returned with complete=False and issues. + Structural and integrity failures likewise remain visible in JSON/HTML; a + malformed header/encoding is rejected because it is not a SOUNDLAB-1 report. + """ + try: + text = data.decode("ascii") + except UnicodeDecodeError as error: + raise SoundLabError("Report is not ASCII") from error + if "\x00" in text or re.search(r"[\x01-\x08\x0b\x0c\x0e-\x1f\x7f]", text): + raise SoundLabError("Report contains unescaped control bytes") + if "\r" in text.replace("\r\n", ""): + raise SoundLabError("Report has bare CR line endings") + lines = [line for line in text.replace("\r\n", "\n").split("\n") if line.strip()] + if not lines or lines[0] != "FORMAT=SOUNDLAB-1": + raise SoundLabError("Missing supported FORMAT=SOUNDLAB-1 header") + result: dict[str, Any] = {"format": "SOUNDLAB-1", "source": source, + "source_sha256": hashlib.sha256(data).hexdigest(), + "metadata": {}, "cases": [], "issues": [], "complete": False, + "integrity": {"record_count": "NOT_PROVIDED", "checksum_crc16": "NOT_PROVIDED"}} + current = None + footer = None + note_length = None + records = [] + + def issue(message: str) -> None: + result["issues"].append(message) + + def merge(target: dict[str, str], fields: dict[str, str], number: int) -> None: + for key, value in fields.items(): + if key in target: + issue(f"Line {number}: duplicate field {key}") + else: + target[key] = value + + for number, line in enumerate(lines, 1): + if footer is not None: + issue(f"Line {number}: record after ENDRUN") + continue + if line.startswith("NOTE="): + records.append(line) + try: + note = decode_note(line[5:]) + if current is None: + issue(f"Line {number}: NOTE outside CASE") + elif note_length is None: + issue(f"Line {number}: NOTE without NOTE_LENGTH") + else: + current["notes"].append(note) + if len(note.encode("ascii")) != note_length: + issue(f"Line {number}: NOTE_LENGTH mismatch") + except SoundLabError as error: + issue(f"Line {number}: {error}") + note_length = None + continue + if note_length is not None: + issue(f"Line {number}: NOTE_LENGTH not followed by NOTE") + note_length = None + try: + fields = parse_tokens(line) + except SoundLabError as error: + records.append(line) + issue(f"Line {number}: {error}") + continue + controls = set(fields) & {"FORMAT", "RUN", "CASE", "ENDCASE", "ENDRUN", "NOTE_LENGTH"} + if len(controls) > 1: + issue(f"Line {number}: conflicting control records") + if "FORMAT" in fields and number != 1: + issue(f"Line {number}: repeated FORMAT header") + if "RUN" in fields and (current is not None or result["cases"]): + issue(f"Line {number}: RUN header after CASE") + if "ENDRUN" in fields: + footer = fields + result["footer"] = fields + if current is not None: + issue(f"Line {number}: ENDRUN before ENDCASE") + if fields["ENDRUN"] != result["metadata"].get("RUN"): + issue(f"Line {number}: ENDRUN does not match RUN") + if fields.get("COMPLETE", "").upper() not in ("YES", "NO"): + issue(f"Line {number}: COMPLETE must be YES or NO") + continue + records.append(line) + if number == 1: + continue + if "CASE" in fields: + if current is not None: + issue(f"Line {number}: CASE before previous ENDCASE") + identifier = fields["CASE"].upper() + current = {"id": identifier, "fields": {}, "notes": [], "closed": False} + result["cases"].append(current) + merge(current["fields"], fields, number) + elif "ENDCASE" in fields: + if current is None: + issue(f"Line {number}: ENDCASE outside CASE") + else: + if fields["ENDCASE"].upper() != current["id"]: + issue(f"Line {number}: ENDCASE does not match CASE") + else: + current["closed"] = True + current = None + if len(fields) != 1: + issue(f"Line {number}: unexpected ENDCASE fields") + elif "NOTE_LENGTH" in fields: + if len(fields) != 1 or current is None: + issue(f"Line {number}: NOTE_LENGTH must be alone inside CASE") + try: + note_length = int(fields["NOTE_LENGTH"]) + if note_length < 0 or note_length > 65535: + raise ValueError() + except ValueError: + note_length = None + issue(f"Line {number}: invalid NOTE_LENGTH") + else: + merge(current["fields"] if current is not None else result["metadata"], fields, number) + if note_length is not None: + issue("Truncated NOTE after NOTE_LENGTH") + if not result["metadata"].get("RUN"): + issue("Missing RUN identity") + attempts: set[tuple[str, int]] = set() + for case in result["cases"]: + try: + repeat_text = case["fields"].get("REPEAT", "0") + if not re.fullmatch(r"[0-9]+", repeat_text): + raise ValueError() + repeat = int(repeat_text) + if repeat > 65535: + raise ValueError() + case["repeat"] = repeat + identity = (case["id"], repeat) + if identity in attempts: + issue(f"CASE {case['id']}: duplicate REPEAT={repeat}") + attempts.add(identity) + except ValueError: + case["repeat"] = None + issue(f"CASE {case['id']}: invalid REPEAT") + for key, allowed in (("AUTO", AUTO), ("HUMAN", HUMAN)): + value = case["fields"].get(key) + if value is None: + # UNKNOWN is deliberate: absence is not a positive or negative observation. + case[key.lower()] = "UNKNOWN" + issue(f"CASE {case['id']}: missing {key}") + else: + case[key.lower()] = value.upper() + if value.upper() not in allowed: + issue(f"CASE {case['id']}: unknown {key} value {value}") + vector_crc = case["fields"].get("VECTOR_CRC16", "") + if not re.fullmatch(r"[0-9A-Fa-f]{4}", vector_crc): + issue(f"CASE {case['id']}: missing or invalid VECTOR_CRC16") + if not case["closed"]: + issue(f"CASE {case['id']}: missing ENDCASE") + if footer is None: + issue("Missing ENDRUN; partial run") + else: + if "RECORD_COUNT" in footer: + try: + valid_count = int(footer["RECORD_COUNT"]) == len(records) + except ValueError: + valid_count = False + result["integrity"]["record_count"] = "VERIFIED" if valid_count else "FAILED" + if not valid_count: + issue("RECORD_COUNT mismatch") + if "CHECKSUM_CRC16" in footer: + canonical = ("\r\n".join(records) + "\r\n").encode("ascii") + expected = f"{crc16(canonical):04X}" + valid_crc = footer["CHECKSUM_CRC16"].upper() == expected + result["integrity"]["checksum_crc16"] = "VERIFIED" if valid_crc else "FAILED" + if not valid_crc: + issue(f"CHECKSUM_CRC16 mismatch (calculated {expected})") + if footer.get("COMPLETE", "").upper() != "YES": + issue("Run marked incomplete") + result["record_count"] = len(records) + result["complete"] = footer is not None and footer.get("COMPLETE", "").upper() == "YES" and not result["issues"] + result["valid"] = not result["issues"] + return result + + +def validate_manifest(report: dict[str, Any], manifest: dict[str, Any]) -> list[str]: + """Return exact identity failures; a manifest is evidence, not a trust signature.""" + if not isinstance(manifest, dict): + raise SoundLabError("Manifest must be a JSON object") + problems = [] + metadata = report["metadata"] + + def crc_text(value: Any) -> str: + if isinstance(value, int): + return f"{value:04X}" + return str(value).upper().removeprefix("0X") + + for key in ("BUILD_ID", "VECTOR_SET_CRC16"): + expected = manifest.get(key.lower(), manifest.get(key)) + expected_text = crc_text(expected) if key.endswith("CRC16") else str(expected).upper() + if expected is None or expected_text != metadata.get(key, "").upper(): + problems.append(f"{key} differs from manifest or is absent") + vectors = manifest.get("vectors", {}) + if isinstance(vectors, list): + if not all(isinstance(item, dict) for item in vectors): + raise SoundLabError("Manifest vectors must be objects") + vectors = {item.get("id", item.get("case_id", "")): item.get("crc16", item.get("vector_crc16", "")) for item in vectors} + if not isinstance(vectors, dict): + raise SoundLabError("Manifest vectors must be a list or object") + vectors = {str(key).upper(): crc_text(value) for key, value in vectors.items()} + for case in report["cases"]: + expected = vectors.get(case["id"]) + if expected is None or expected != case["fields"].get("VECTOR_CRC16", "").upper(): + problems.append(f"CASE {case['id']}: vector differs from manifest or is absent") + return problems + + +def compare_reports(left: dict[str, Any], right: dict[str, Any], manifest: dict[str, Any] | None = None) -> dict[str, Any]: + problems = [] + for key in ("BUILD_ID", "VECTOR_SET_CRC16"): + a, b = left["metadata"].get(key), right["metadata"].get(key) + if not a or not b or a.upper() != b.upper(): + problems.append(f"{key} differs or is absent") + if manifest is not None: + problems.extend("Left: " + value for value in validate_manifest(left, manifest)) + problems.extend("Right: " + value for value in validate_manifest(right, manifest)) + if not left["valid"] or not right["valid"]: + problems.append("One or both reports are partial or invalid; outcomes are provisional") + by_id = [{(case["id"], case["repeat"]): case for case in report["cases"]} for report in (left, right)] + rows = [] + for identity in sorted(set(by_id[0]) | set(by_id[1]), key=lambda item: (item[0], -1 if item[1] is None else item[1])): + identifier, repeat = identity + a, b = by_id[0].get(identity), by_id[1].get(identity) + reason = list(problems) + if a is None or b is None: + reason.append("CASE missing from one report") + elif a["fields"].get("VECTOR_CRC16", "").upper() != b["fields"].get("VECTOR_CRC16", "").upper(): + reason.append("VECTOR_CRC16 differs") + row = {"case": identifier, "repeat": repeat, "left_auto": a["auto"] if a else "UNKNOWN", + "right_auto": b["auto"] if b else "UNKNOWN", "left_human": a["human"] if a else "UNKNOWN", + "right_human": b["human"] if b else "UNKNOWN", "reasons": reason} + changes = {} + if a is not None and b is not None: + for key in sorted(set(a["fields"]) | set(b["fields"])): + if key in ("CASE", "REPEAT", "VECTOR_CRC16", "AUTO", "HUMAN"): + continue + av, bv = a["fields"].get(key), b["fields"].get(key) + if av != bv: + changes[key] = {"left": av, "right": bv} + if a["notes"] != b["notes"]: + changes["NOTES"] = {"left": a["notes"], "right": b["notes"]} + row["recorded_differences"] = changes + outcomes_equal = row["left_auto"] == row["right_auto"] and row["left_human"] == row["right_human"] + row["comparison"] = "NOT_COMPARABLE" if reason else ("SAME" if outcomes_equal and not changes else "DIFFERENT") + rows.append(row) + return {"left": left["source"], "right": right["source"], "identity_issues": problems, + "manifest_checked": manifest is not None, "identity_basis": "MANIFEST" if manifest is not None else "REPORT_CLAIMS_ONLY", "cases": rows, + "notice": "Matching automatic observations do not establish audible equivalence. HUMAN is independent."} + + +def render_html(document: dict[str, Any]) -> str: + esc = lambda value: html.escape(str(value)) + comparison = "left" in document + title = "Sound Lab comparison" if comparison else "Sound Lab report" + pieces = [f'{title}', + '', f'

{title}

', '

Automatic observations and human listening results are separate evidence. Unknown means unreported; it never means heard.

'] + issues = document.get("identity_issues", document.get("issues", [])) + if issues: + pieces.append('
Incomplete or unverified evidence
    ' + ''.join(f'
  • {esc(value)}
  • ' for value in issues) + '
') + if comparison: + keys = ["case", "repeat", "left_auto", "right_auto", "left_human", "right_human", "comparison", "recorded_differences", "reasons"] + rows = document["cases"] + else: + pieces.append(f'

Source: {esc(document["source"])}
SHA-256: {esc(document["source_sha256"])}
Complete: {esc(document["complete"])}

') + pieces.append('

Run metadata and integrity

' + esc(json.dumps({"metadata": document["metadata"], "integrity": document["integrity"]}, indent=2)) + '
') + keys = ["case", "repeat", "auto", "human", "closed", "notes", "recorded_fields"] + rows = [{"case": case["id"], "repeat": case["repeat"], "auto": case["auto"], "human": case["human"], "closed": case["closed"], "notes": "\n".join(case["notes"]), "recorded_fields": json.dumps(case["fields"], sort_keys=True)} for case in document["cases"]] + pieces.append('

Cases

' + ''.join(f'' for key in keys) + '') + for row in rows: + pieces.append('' + ''.join(f'' for key in keys) + '') + pieces.append('
{esc(key)}
{esc(row.get(key, ""))}
') + return '\n'.join(pieces) + + +def render_csv(document: dict[str, Any]) -> str: + stream = io.StringIO(newline="") + if "left" in document: + fields = ["case", "repeat", "left_auto", "right_auto", "left_human", "right_human", "comparison", "recorded_differences", "reasons"] + rows = document["cases"] + else: + # Union preserves timing/status fields, rather than reducing reports to outcomes. + extra = sorted({key for case in document["cases"] for key in case["fields"]} - {"CASE", "REPEAT", "AUTO", "HUMAN"}) + fields = ["case", "repeat", "auto", "human", "closed", "notes"] + extra + rows = [{"case": case["id"], "repeat": case["repeat"], "auto": case["auto"], "human": case["human"], "closed": case["closed"], "notes": '\n'.join(case["notes"]), **{key: case["fields"].get(key, "") for key in extra}} for case in document["cases"]] + writer = csv.DictWriter(stream, fieldnames=fields) + writer.writeheader() + writer.writerows(rows) + return stream.getvalue() + + +def write_outputs(outputs: dict[Path, bytes], overwrite: bool = False) -> None: + """Preflight every target before any writes; originals are never implicitly replaced.""" + for path in outputs: + if path.is_symlink() or (path.exists() and (not overwrite or not path.is_file())): + raise SoundLabError(f"Refusing to replace {path}; select a fresh folder or use --overwrite for regular files") + for path, data in outputs.items(): + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("wb" if overwrite else "xb") as handle: + handle.write(data) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="operation", required=True) + for operation in ("extract", "convert", "compare"): + command = sub.add_parser(operation) + command.add_argument("source", type=Path) + if operation == "compare": + command.add_argument("other", type=Path) + command.add_argument("--output", required=True, type=Path) + command.add_argument("--overwrite", action="store_true") + if operation != "extract": + command.add_argument("--manifest", type=Path, help="Authoritative build/vector JSON manifest") + args = parser.parse_args(argv) + try: + outputs = {} + if args.operation == "extract": + disk = args.source.read_bytes() + reports = extract_reports(disk) + if not reports: + raise SoundLabError("No SNDnnnn.TXT ASCII reports found") + receipt = {"disk": args.source.name, "disk_byte_count": len(disk), "disk_sha256": hashlib.sha256(disk).hexdigest(), "reports": []} + for report in reports: + outputs[args.output / report["filename"]] = report["data"] + receipt["reports"].append({key: value for key, value in report.items() if key != "data"}) + outputs[args.output / "extraction.json"] = (json.dumps(receipt, indent=2) + '\n').encode() + else: + left = parse_report(args.source.read_bytes(), args.source.name) + manifest = json.loads(args.manifest.read_text()) if args.manifest else None + if args.manifest and not isinstance(manifest, dict): + raise SoundLabError("Manifest must be a JSON object") + if args.operation == "compare": + document = compare_reports(left, parse_report(args.other.read_bytes(), args.other.name), manifest) + stem = "comparison" + else: + document = left + if manifest is not None: + document["manifest_issues"] = validate_manifest(document, manifest) + document["issues"].extend(document["manifest_issues"]) + document["valid"] = document["valid"] and not document["manifest_issues"] + document["complete"] = document["complete"] and document["valid"] + stem = args.source.stem + outputs = {args.output / f"{stem}.json": (json.dumps(document, indent=2) + '\n').encode(), args.output / f"{stem}.csv": render_csv(document).encode(), args.output / f"{stem}.html": render_html(document).encode()} + # Never allow an output to alias any supplied source, even with --overwrite. + sources = [args.source] + ([args.other] if args.operation == "compare" else []) + if getattr(args, "manifest", None): + sources.append(args.manifest) + source_paths = {path.resolve() for path in sources} + if any(path.resolve() in source_paths or any(path.exists() and path.samefile(source) for source in sources) for path in outputs): + raise SoundLabError("Output would replace an input; choose another folder") + write_outputs(outputs, args.overwrite) + print(f"Wrote {len(outputs)} files to {args.output}") + if args.operation != "extract" and (document.get("issues") or document.get("identity_issues") or any(row.get("comparison") == "NOT_COMPARABLE" for row in document["cases"])): + print("Warning: evidence is incomplete, invalid, or not comparable; inspect JSON/HTML", file=sys.stderr) + return 2 + return 0 + except (OSError, SoundLabError, json.JSONDecodeError) as error: + print(f"soundlab: {error}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/sound-lab/native/run.cpp b/examples/sound-lab/native/run.cpp new file mode 100644 index 0000000..9799432 --- /dev/null +++ b/examples/sound-lab/native/run.cpp @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Isolated headless test: real Disk BASIC/FD502 path, private local ROM inputs. +#include "../../../tests/toolchain/ssc/session.h" + +static void type(Session& run, const std::string& text) { + for(char c:text) { + if(c>='A' && c<='Z') run.press(c-'@'); + else if(c>='0' && c<='9') run.press(32+c-'0'); + else if(c=='-') run.press(45); + else if(c=='"') run.press(34,true); + else if(c=='\r') run.press(48); + else throw std::runtime_error("Unsupported input character"); + } +} +static void capture(Session& run,const fs::path& path) { + for(unsigned i=0;i<3;++i) run.tick(); + auto frame=run.machine.snapshot().frame; + require(frame && frame->pixels.size()==Frame::width*Frame::height,"No guest raster"); + std::ofstream file(path,std::ios::binary); + file<<"P6\n"<pixels) { file.put(char(pixel>>16));file.put(char(pixel>>8));file.put(char(pixel)); } +} +static void select(Session& run,const std::string& id) { + type(run,"4"); run.until("CASE ID"); type(run,id+"\r"); + run.until("ENTER TO PLAY",2400); type(run,"\r"); run.until("H HEARD",2400); +} +struct NeverReady final:CartridgeDevice { + unsigned reads=0,writes=0; + void reset() override {} + void horizontalSync(DeviceHost&) override {} + std::uint8_t readMemory(std::uint16_t)const override{return 0;} + std::uint8_t readPort(std::uint8_t p,DeviceHost&)override {if(p==0x7e){++reads;return 1;}return 0;} + void writePort(std::uint8_t p,std::uint8_t,DeviceHost&)override {if(p==0x7e)++writes;} +}; +static void writeFile(const fs::path& path,const Bytes& bytes) { + std::ofstream file(path,std::ios::binary); + file.write(reinterpret_cast(bytes.data()),bytes.size()); + require(bool(file),"Cannot write owned test output"); +} +int main(int argc,char**argv) { + try { + require(argc==4,"Usage: run ROM_DIRECTORY SOUNDLAB.DSK OUTPUT_DIRECTORY"); + fs::path roms=argv[1], out=argv[3]; fs::create_directories(out); + auto system=readFile(roms/"coco3.rom"), diskrom=readFile(roms/"disk11.rom"); + auto chips=readFile(roms/"pic-7040-510.bin"), speech=readFile(roms/"sp0256-al2.bin"); + chips.insert(chips.end(),speech.begin(),speech.end()); + for(auto cpu:{Processor::MC6809,Processor::HD6309}) { + std::string label=cpu==Processor::MC6809?"6809":"6309"; + Session run(cpu,system,diskrom,std::make_shared(chips)); + run.floppy->mount(0,DiskImage::load(readFile(argv[2]))); + type(run,"DOS\r"); run.until("WELCOME, LISTENER",1200); + type(run,"11ND"); run.until("MAIN MENU",2400); + if(cpu==Processor::MC6809) { run.until("REPORT SAVED",2400); capture(run,out/"main-menu.ppm"); } + run.audio.clear(); + type(run,"1"); run.until("ENTER TO PLAY",2400); type(run,"\r"); run.until("H HEARD",2400); + run.checkSignal(0); // PCM signal only; never a listening verdict. + type(run,"R"); run.until("ENTER TO PLAY",2400); type(run,"\r"); run.until("ATTEMPT 1",2400); run.until("H HEARD",2400); + type(run,"U"); run.until("ENTER TO PLAY",2400); type(run,"\r"); run.until("H HEARD",2400); + type(run,"X"); run.until("MAIN MENU",2400); + type(run,"Q"); run.until("SOUND LAB FINISHED",2400); + for(unsigned i=0;i<30;++i) run.tick(); + require(run.contains("OK"),"Did not return to BASIC"); + require(run.floppy->writeEvents(0)>0,"No report disk writes"); + writeFile(out/(label+"-reports.dsk"),run.floppy->image(0)->bytes()); + saveWav(out/(label+"-showcase.wav"),run.audio); + std::ofstream(out/(label+"-final.txt"))<mount(0,DiskImage::load(readFile(argv[2]),true)); + type(absent,"RUN\"SOUNDLAB\"\r"); absent.until("WELCOME, LISTENER",1200); + type(absent,"11NM"); absent.until("MAIN MENU"); + type(absent,"1"); absent.until("ENTER TO PLAY"); type(absent,"\r"); absent.until("H HEARD",3000); + type(absent,"X"); absent.until("MAIN MENU"); type(absent,"Q"); absent.until("SOUND LAB FINISHED"); + require(absent.floppy->writeEvents(0)==0,"Screen-only run wrote disk"); + std::cout<<"PASS absent SSC bounded observation and screen-only return without writes\n"; + } + { + Session engineering(Processor::MC6809,system,diskrom,std::make_shared(chips)); + engineering.floppy->mount(0,DiskImage::load(readFile(out/"6809-reports.dsk"))); + type(engineering,"DOS\r"); engineering.until("WELCOME, LISTENER",1200); + type(engineering,"11ND"); engineering.until("MAIN MENU",2400); + engineering.until("REPORT SAVED",2400); + require(!engineering.contains("SND0001.TXT"),"Existing report filename was reused on relaunch"); + for(const auto&id:{"REG01","REG02","NOI01","ENV01-10","ALP01-00"}) { + auto first=engineering.audio.size(); + select(engineering,id); + if(std::string(id)!="ALP01-00") engineering.checkSignal(first); + if(std::string(id)=="REG01") capture(engineering,out/"direct-register-result.ppm"); + type(engineering,"X"); engineering.until("MAIN MENU",2400); + } + type(engineering,"Q"); engineering.until("SOUND LAB FINISHED",2400); + for(unsigned i=0;i<30;++i) engineering.tick(); + writeFile(out/"engineering-reports.dsk",engineering.floppy->image(0)->bytes()); + std::cout<<"PASS held AY/direct FF data, noise, envelope, silent pause, report rollover and filename preservation\n"; + } + { + auto stall=std::make_shared(); + Session stopped(Processor::MC6809,system,diskrom,nullptr,false,stall); + stopped.floppy->mount(0,DiskImage::load(readFile(argv[2]),true)); + type(stopped,"DOS\r"); stopped.until("WELCOME, LISTENER",1200); + type(stopped,"11NM"); stopped.until("MAIN MENU"); + type(stopped,"1"); stopped.until("ENTER TO PLAY"); type(stopped,"\r"); stopped.until("TIMEOUT / RESET",1200); + require(stall->reads>1 && stall->writes==0,"Bounded ready polling wrote to a not-ready device"); + type(stopped,"X"); stopped.until("MAIN MENU"); type(stopped,"Q"); stopped.until("SOUND LAB FINISHED"); + std::cout<<"PASS never-ready bounded timeout with zero command writes\n"; + } + { + Session panic(Processor::MC6809,system,diskrom,std::make_shared(chips)); + panic.floppy->mount(0,DiskImage::load(readFile(argv[2]),true)); + type(panic,"DOS\r"); panic.until("WELCOME, LISTENER",1200); + type(panic,"11NM"); panic.until("MAIN MENU"); type(panic,"1"); panic.until("ENTER TO PLAY"); type(panic,"\r"); panic.until("PLAYING"); + type(panic,"X"); panic.until("ABORTED",1200); panic.until("H HEARD"); + type(panic,"X"); panic.until("MAIN MENU"); type(panic,"Q"); panic.until("SOUND LAB FINISHED"); + require(panic.floppy->writeEvents(0)==0,"Panic screen-only path wrote disk"); + std::cout<<"PASS panic during playback and safe return\n"; + } + return 0; + } catch(const std::exception&e) { std::cerr<repeat', reports.render_html(left)) + duplicate = reports.parse_report(finish(header + case0 + case0)) + self.assertFalse(duplicate['valid']) + self.assertTrue(any('duplicate REPEAT=0' in issue for issue in duplicate['issues'])) + + def test_bad_repeat_and_missing_repeat_are_honest(self): + baseline = make_report(ending=False) + for value in ('-1', '65536', 'abc'): + invalid = baseline.replace(b'ENDCASE=', f'REPEAT={value}\r\nENDCASE='.encode()) + b'ENDRUN=0001 COMPLETE=YES\r\n' + parsed = reports.parse_report(invalid) + self.assertFalse(parsed['valid']) + self.assertIsNone(parsed['cases'][0]['repeat']) + self.assertEqual(reports.parse_report(make_report())['cases'][0]['repeat'], 0) + + def test_raw_metric_differences_visible_even_with_same_outcomes(self): + a = make_report() + b = a.replace(b'TX_COUNT=11', b'TX_COUNT=12').split(b' RECORD_COUNT=')[0] + b'\r\n' + # Remove optional integrity from both: this fixture isolates metrics comparison. + a = a.split(b' RECORD_COUNT=')[0] + b'\r\n' + result = reports.compare_reports(reports.parse_report(a), reports.parse_report(b)) + self.assertEqual(result['cases'][0]['comparison'], 'DIFFERENT') + self.assertEqual(result['cases'][0]['recorded_differences']['TX_COUNT'], {'left': '11', 'right': '12'}) + + def test_manifest_crc_aliases_and_invalid_schema(self): + report = reports.parse_report(make_report()) + manifest = {'build_id': 'TEST-1', 'vector_set_crc16': 0x1234, 'vectors': {'TON01-A': '0x7abc'}} + self.assertEqual(reports.validate_manifest(report, manifest), []) + for bad in ([], {'vectors': 3}, {'vectors': ['not an object']}): + with self.subTest(manifest=bad), self.assertRaises(reports.SoundLabError): + reports.validate_manifest(report, bad) + + def test_repeated_header_or_conflicting_controls(self): + for changed in (make_report().replace(b'ENDCASE=TON01-A', b'FORMAT=SOUNDLAB-1\r\nENDCASE=TON01-A'), + make_report().replace(b'CASE=TON01-A VECTOR', b'CASE=TON01-A RUN=0001 VECTOR')): + self.assertFalse(reports.parse_report(changed)['valid']) + + def test_html_escapes_notes_and_csv_keeps_timing(self): + result = reports.parse_report(make_report(note='')) + rendered = reports.render_html(result) + self.assertNotIn('