commit b979ac26a9dad77ca66c3f9171efac4acfa8c19d Author: Mike Welsh Date: Mon Aug 29 00:51:32 2016 -0700 Initial commit diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 000000000..a3d2b97a2 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "swf" +version = "0.1.0" +authors = ["Mike Welsh"] + +[dependencies] +byteorder = "*" +#clippy = "*" +flate2 = "*" +#xz2 = "*" +xz2 = { git = "c:/projects/xz2-rs" } \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 000000000..3c5675063 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,675 @@ +### 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 . \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 000000000..6815f06fe --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,26 @@ +//! # swf-rs +//! +//! Library for reading and writing Adobe Flash SWF files. +//! +//! # Organization +//! +//! This library consits of a `read` module for decoding SWF data, and a `write` library for +//! writing SWF data. + +extern crate byteorder; +extern crate flate2; +extern crate xz2; + +mod read; +mod tag_codes; +mod types; +mod write; + +/// Parses an SWF from a `Read` stream. +pub use read::read_swf; + +/// Writes an SWF to a `Write` stream. +pub use write::write_swf; + +/// Types used to represent a parsed SWF. +pub use types::*; \ No newline at end of file diff --git a/src/read.rs b/src/read.rs new file mode 100644 index 000000000..6cb5ac8cf --- /dev/null +++ b/src/read.rs @@ -0,0 +1,789 @@ +// SWF decoding from streams +use byteorder::{LittleEndian, ReadBytesExt}; +use flate2::read::ZlibDecoder; +use std::io::{Error, ErrorKind, Read, Result}; +use types::*; +use xz2::read::XzDecoder; + +/// Reads SWF data from a stream. +pub fn read_swf(mut input: R) -> Result { + // Read SWF header. + let compression = try!(Reader::read_compression_type(&mut input)); + let version = try!(input.read_u8()); + let uncompressed_length = try!(input.read_u32::()); + + // Now the SWF switches to a compressed stream. + let decompressed_input: Box = match compression { + Compression::None => Box::new(input), + Compression::Zlib => Box::new(ZlibDecoder::new(input)), + Compression::Lzma => { + // Flash uses a mangled LZMA header, so we have to massage it into the normal + // format. + use std::io::{Cursor, Write}; + use xz2::stream::{Action, Stream}; + use byteorder::WriteBytesExt; + try!(input.read_u32::()); // Compressed length + let mut lzma_properties = [0u8; 5]; + try!(input.read_exact(&mut lzma_properties)); + let mut lzma_header = Cursor::new(Vec::with_capacity(13)); + try!(lzma_header.write_all(&lzma_properties)); + try!(lzma_header.write_u64::(uncompressed_length as u64)); + let mut lzma_stream = try!(Stream::new_lzma_decoder(u64::max_value())); + try!(lzma_stream.process(&lzma_header.into_inner(), &mut [0u8; 1], Action::Run)); + Box::new(XzDecoder::new_stream(input, lzma_stream)) + } + }; + + let mut reader = Reader::new( decompressed_input, version ); + + let stage_size = try!(reader.read_rectangle()); + let frame_rate = try!(reader.read_fixed88()); + let num_frames = try!(reader.read_u16()); + + let tags = try!(reader.read_tag_list()); + + Ok(Swf { + version: version, + compression: compression, + stage_size: stage_size, + frame_rate: frame_rate, + num_frames: num_frames, + tags: tags, + }) +} + + +pub struct Reader { + input: R, + version: u8, + + byte: u8, + bit_index: u8, + + num_fill_bits: u8, + num_line_bits: u8, +} + +impl Reader { + fn new(input: R, version: u8) -> Reader { + Reader { input: input, version: version, byte: 0, bit_index: 0, num_fill_bits: 0, num_line_bits: 0 } + } + + fn read_compression_type(mut input: R) -> Result { + let mut signature = [0u8; 3]; + try!(input.read_exact(&mut signature)); + let compression = match &signature { + b"FWS" => Compression::None, + b"CWS" => Compression::Zlib, + b"ZWS" => Compression::Lzma, + _ => return Err(Error::new(ErrorKind::InvalidData, "Invalid SWF")), + }; + Ok(compression) + } + + fn read_rectangle(&mut self) -> Result { + self.byte_align(); + let num_bits = try!(self.read_ubits(5)) as usize; + Ok(Rectangle { + x_min: try!(self.read_sbits(num_bits)) as f32 / 20f32, + x_max: try!(self.read_sbits(num_bits)) as f32 / 20f32, + y_min: try!(self.read_sbits(num_bits)) as f32 / 20f32, + y_max: try!(self.read_sbits(num_bits)) as f32 / 20f32, + }) + } + + fn read_u8(&mut self) -> Result { + self.byte_align(); + self.input.read_u8() + } + + fn read_u16(&mut self) -> Result { + self.byte_align(); + self.input.read_u16::() + } + + fn read_u32(&mut self) -> Result { + self.byte_align(); + self.input.read_u32::() + } + + fn read_i16(&mut self) -> Result { + self.byte_align(); + self.input.read_i16::() + } + + fn read_bit(&mut self) -> Result { + if self.bit_index == 0 { + self.byte = try!(self.input.read_u8()); + self.bit_index = 8; + } + self.bit_index -= 1; + let val = self.byte & (1 << self.bit_index) != 0; + Ok(val) + } + + fn byte_align(&mut self) { + self.bit_index = 0; + } + + fn read_ubits(&mut self, num_bits: usize) -> Result { + let mut val = 0u32; + for _ in 0..num_bits { + val <<= 1; + val |= if try!(self.read_bit()) { 1 } else { 0 }; + } + Ok(val) + } + + fn read_sbits(&mut self, num_bits: usize) -> Result { + if num_bits > 0 { + self.read_ubits(num_bits).map(|n| (n as i32) << (32 - num_bits) >> (32 - num_bits)) + } + else + { + Ok(0) + } + } + + fn read_fbits(&mut self, num_bits: usize) -> Result { + self.read_sbits(num_bits).map(|n| (n as f32) / 65536f32) + } + + fn read_fixed88(&mut self) -> Result { + self.input.read_i16::().map(|n| n as f32 / 256f32) + } + + fn read_encoded_u32(&mut self) -> Result { + let mut val = 0u32; + for i in 0..5 { + let byte = try!(self.read_u8()); + val |= ((byte & 0b01111111) as u32) << (i*7); + if byte & 0b10000000 == 0 + { + break; + } + } + Ok(val) + } + + fn read_c_string(&mut self) -> Result { + let mut bytes = Vec::new(); + loop { + let byte = try!(self.read_u8()); + if byte == 0 { + break; + } + bytes.push(byte) + } + // TODO: There is probably a better way to do this. + // TODO: Verify ANSI for SWF 5 and earlier. + String::from_utf8(bytes).map_err(|_| Error::new(ErrorKind::InvalidData, "Invalid string data")) + } + + fn read_rgb(&mut self) -> Result { + let r = try!(self.read_u8()); + let g = try!(self.read_u8()); + let b = try!(self.read_u8()); + Ok(Color { r: r, g: g, b: b, a: 255 }) + } + + fn read_rgba(&mut self) -> Result { + let r = try!(self.read_u8()); + let g = try!(self.read_u8()); + let b = try!(self.read_u8()); + let a = try!(self.read_u8()); + Ok(Color { r: r, g: g, b: b, a: a }) + } + + fn read_matrix(&mut self) -> Result { + self.byte_align(); + let mut m = Matrix::new(); + // Scale + if try!(self.read_bit()) { + let num_bits = try!(self.read_ubits(5)) as usize; + m.scale_x = try!(self.read_fbits(num_bits)); + m.scale_y = try!(self.read_fbits(num_bits)); + } + // Rotate/Skew + if try!(self.read_bit()) { + let num_bits = try!(self.read_ubits(5)) as usize; + m.rotate_skew_0 = try!(self.read_fbits(num_bits)); + m.rotate_skew_1 = try!(self.read_fbits(num_bits)); + } + // Translate (always present) + let num_bits = try!(self.read_ubits(5)) as usize; + m.translate_x = try!(self.read_fbits(num_bits)); + m.translate_y = try!(self.read_fbits(num_bits)); + Ok(m) + } + + fn read_tag_list(&mut self) -> Result> { + let mut tags = Vec::new(); + while let Some(tag) = try!(self.read_tag()) { + tags.push(tag); + } + // TODO: Verify that we read at least one tag? + // Are zero-length tag lists allowed? + Ok(tags) + } + + fn read_tag(&mut self) -> Result> { + let tag_code_and_length = try!(self.read_u16()); + let tag_code = tag_code_and_length >> 6; + let mut length = (tag_code_and_length & 0b111111) as u32; + if length == 0b111111 { + // Extended tag. + length = try!(self.read_u32()); + } + + let mut tag_reader = Reader::new( self.input.by_ref().take(length as u64), self.version ); + use tag_codes::TagCode; + let tag = match tag_code { + x if x == TagCode::End as u16 => return Ok(None), + x if x == TagCode::ShowFrame as u16 => Tag::ShowFrame, + x if x == TagCode::DefineShape as u16 => try!(tag_reader.read_define_shape(1)), + + x if x == TagCode::SetBackgroundColor as u16 => Tag::SetBackgroundColor(try!(tag_reader.read_rgb())), + +// PLACE_OBJECT_2 => unimplemented!(), + + x if x == TagCode::FileAttributes as u16 => { + let flags = try!(tag_reader.read_u32()); + Tag::FileAttributes(FileAttributes { + use_direct_blit: (flags & 0b01000000) != 0, + use_gpu: (flags & 0b00100000) != 0, + has_metadata: (flags & 0b00010000) != 0, + is_action_script_3: (flags & 0b00001000) != 0, + use_network_sandbox: (flags & 0b00000001) != 0, + }) + }, + + x if x == TagCode::DefineSceneAndFrameLabelData as u16 => try!(tag_reader.read_define_scene_and_frame_label_data()), + + _ => { + let mut data = Vec::new(); + data.resize(length as usize, 0); + try!(tag_reader.input.read_exact(data.as_mut_slice())); + Tag::Unknown { tag_code: tag_code, data: data } + }, + }; + + Ok(Some(tag)) + } + + fn read_define_scene_and_frame_label_data(&mut self) -> Result { + let num_scenes = try!(self.read_encoded_u32()) as usize; + let mut scenes = Vec::with_capacity(num_scenes); + for _ in 0..num_scenes { + scenes.push(FrameLabel { + frame_num: try!(self.read_encoded_u32()), + label: try!(self.read_c_string()), + }); + } + + let num_frame_labels = try!(self.read_encoded_u32()) as usize; + let mut frame_labels = Vec::with_capacity(num_frame_labels); + for _ in 0..num_frame_labels { + frame_labels.push(FrameLabel { + frame_num: try!(self.read_encoded_u32()), + label: try!(self.read_c_string()), + }); + } + + Ok(Tag::DefineSceneAndFrameLabelData { scenes: scenes, frame_labels: frame_labels }) + } + + fn read_define_shape(&mut self, version: u8) -> Result { + let id = try!(self.read_u16()); + let shape_bounds = try!(self.read_rectangle()); + let styles = try!(self.read_shape_styles(version)); + let mut records = Vec::new(); + while let Some(record) = try!(self.read_shape_record(version)) { + records.push(record); + } + Ok(Tag::DefineShape(Shape { + version: version, + id: id, + shape_bounds: shape_bounds.clone(), + edge_bounds: shape_bounds, + styles: styles, + shape: records, + })) + } + + fn read_shape_styles(&mut self, shape_version: u8) -> Result { + let num_fill_styles = match try!(self.read_u8()) { + 0xff if shape_version >= 2 => try!(self.read_u16()) as usize, + n => n as usize, + }; + let mut fill_styles = Vec::with_capacity(num_fill_styles); + for _ in 0..num_fill_styles { + fill_styles.push(try!(self.read_fill_style(shape_version))); + } + + let num_line_styles = match try!(self.read_u8()) { + // TODO: is this true for linestyles too? SWF19 says not. + 0xff if shape_version >= 2 => try!(self.read_u16()) as usize, + n => n as usize, + }; + let mut line_styles = Vec::with_capacity(num_line_styles); + for _ in 0..num_line_styles { + line_styles.push(try!(self.read_line_style(shape_version))); + } + + self.num_fill_bits = try!(self.read_ubits(4)) as u8; + self.num_line_bits = try!(self.read_ubits(4)) as u8; + Ok(ShapeStyles { + fill_styles: fill_styles, + line_styles: line_styles, + num_fill_bits: self.num_fill_bits, + num_line_bits: self.num_line_bits, + }) + } + + fn read_fill_style(&mut self, shape_version: u8) -> Result { + let fill_style_type = try!(self.read_u8()); + let fill_style = match fill_style_type { + 0x00 => { + let color = if shape_version >= 3 { try!(self.read_rgba()) } else { try!(self.read_rgb()) }; + FillStyle::Color(color) + }, + + 0x10 => { + FillStyle::LinearGradient(try!(self.read_gradient(shape_version))) + }, + + 0x12 => { + FillStyle::RadialGradient(try!(self.read_gradient(shape_version))) + }, + + 0x13 => { + if self.version < 8 { + return Err(Error::new(ErrorKind::InvalidData, "Focal gradients are only supported in SWF version 8 or higher.")); + } + FillStyle::FocalGradient { + gradient: try!(self.read_gradient(shape_version)), + focal_point: try!(self.read_fixed88()) + } + }, + + 0x40 => { + FillStyle::Bitmap { + id: try!(self.read_u16()), + matrix: try!(self.read_matrix()), + is_smoothed: (fill_style_type & 0b10) == 0, + is_repeating: (fill_style_type & 0b01) == 0, + } + }, + + _ => return Err(Error::new(ErrorKind::InvalidData, "Invalid fill style.")), + }; + Ok(fill_style) + } + + fn read_line_style(&mut self, shape_version: u8) -> Result { + Ok(LineStyle { + width: try!(self.read_u16()), // TODO: Twips + color: if shape_version >= 3 { try!(self.read_rgba()) } else { try!(self.read_rgb()) }, + }) + } + + fn read_gradient(&mut self, shape_version: u8) -> Result { + let spread = match try!(self.read_ubits(2)) { + 0 => GradientSpread::Pad, + 1 => GradientSpread::Reflect, + 2 => GradientSpread::Repeat, + _ => return Err(Error::new(ErrorKind::InvalidData, "Invalid gradient spread mode.")), + }; + let interpolation = match try!(self.read_ubits(2)) { + 0 => GradientInterpolation::RGB, + 1 => GradientInterpolation::LinearRGB, + _ => return Err(Error::new(ErrorKind::InvalidData, "Invalid gradient interpolation mode.")), + }; + let num_records = try!(self.read_ubits(4)) as usize; + let mut records = Vec::with_capacity(num_records); + for _ in 0..num_records { + records.push(GradientRecord { + ratio: try!(self.read_u8()), + color: if shape_version >= 3 { try!(self.read_rgba()) } else { try!(self.read_rgb()) }, + }); + }; + Ok(Gradient { + spread: spread, + interpolation: interpolation, + records: records, + }) + } + + fn read_shape_record(&mut self, shape_version: u8) -> Result> { + // TODO: Twips + let is_edge_record = try!(self.read_bit()); + let shape_record = if is_edge_record { + let is_straight_edge = try!(self.read_bit()); + if is_straight_edge { + // StraightEdge + let num_bits = try!(self.read_ubits(4)) as usize + 2; + let is_axis_aligned = !try!(self.read_bit()); + let is_vertical = is_axis_aligned && try!(self.read_bit()); + let delta_x = if !is_axis_aligned || !is_vertical { try!(self.read_sbits(num_bits)) } else { 0 }; + let delta_y = if !is_axis_aligned || is_vertical { try!(self.read_sbits(num_bits)) } else { 0 }; + Some(ShapeRecord::StraightEdge { delta_x: (delta_x as f32) / 20f32, delta_y: (delta_y as f32) / 20f32 }) + } + else + { + // CurvedEdge + let num_bits = try!(self.read_ubits(4)) as usize + 2; + Some(ShapeRecord::CurvedEdge { + control_delta_x: (try!(self.read_sbits(num_bits)) as f32) / 20f32, + control_delta_y: (try!(self.read_sbits(num_bits)) as f32) / 20f32, + anchor_delta_x: (try!(self.read_sbits(num_bits)) as f32) / 20f32, + anchor_delta_y: (try!(self.read_sbits(num_bits)) as f32) / 20f32, + }) + } + } else { + let flags = try!(self.read_ubits(5)); + if flags != 0 { + // StyleChange + let num_fill_bits = self.num_fill_bits as usize; + let num_line_bits = self.num_line_bits as usize; + let mut new_style = StyleChangeData { + move_delta_x: 0f32, + move_delta_y: 0f32, + fill_style_0: None, + fill_style_1: None, + line_style: None, + new_styles: None, + }; + if (flags & 0b1) != 0 { + // move + let num_bits = try!(self.read_ubits(5)) as usize; + new_style.move_delta_x = (try!(self.read_sbits(num_bits)) as f32) / 20f32; + new_style.move_delta_y = (try!(self.read_sbits(num_bits)) as f32) / 20f32; + } + if (flags & 0b10) != 0 { + new_style.fill_style_0 = Some(try!(self.read_ubits(num_fill_bits))); + } + if (flags & 0b100) != 0 { + new_style.fill_style_1 = Some(try!(self.read_ubits(num_fill_bits))); + } + if (flags & 0b1000) != 0 { + new_style.line_style = Some(try!(self.read_ubits(num_line_bits))); + } + if shape_version >= 2 && (flags & 0b10000) != 0 { + let new_styles = try!(self.read_shape_styles(shape_version)); + // TODO: Is this the proper time to apply the new bit sizes? + self.num_fill_bits = new_styles.num_fill_bits; + self.num_line_bits = new_styles.num_line_bits; + new_style.new_styles = Some(new_styles); + } + Some(ShapeRecord::StyleChange(new_style)) + } else { + None + } + }; + Ok(shape_record) + } + +} + +#[cfg(test)] +mod tests { + use std::fs::File; + use types::*; + use super::*; + use std::io::{Cursor, Read}; + use std::vec::Vec; + + fn reader(data: &[u8]) -> Reader<&[u8]> { + let default_version = 13; + Reader::new(data, default_version) + } + + fn reader_with_version(data: &[u8], version: u8) -> Reader<&[u8]> { + Reader::new(data, version) + } + + fn read_from_file(path: &str) -> Swf { + let mut file = File::open(path).unwrap(); + let mut data = Vec::new(); + file.read_to_end(&mut data).unwrap(); + read_swf(&data[..]).unwrap() + } + + fn reader_from_file(path: &str, version: u8) -> Reader>> { + let mut file = File::open(path).unwrap(); + let mut data = Vec::new(); + file.read_to_end(&mut data).unwrap(); + Reader::new(Cursor::new(data), version) + } + + fn read_tag_from_file(path: &str, version: u8) -> Tag { + let mut file = File::open(path).unwrap(); + let mut data = Vec::new(); + file.read_to_end(&mut data).unwrap(); + Reader::new(&data[..], version).read_tag().unwrap().unwrap() + } + + #[test] + fn read_swfs() { + assert_eq!(read_from_file("test/swfs/uncompressed.swf").compression, Compression::None); + assert_eq!(read_from_file("test/swfs/zlib.swf").compression, Compression::Zlib); + assert_eq!(read_from_file("test/swfs/lzma.swf").compression, Compression::Lzma); + } + + #[test] + fn read_invalid_swf() { + let junk = [0u8; 128]; + let result = read_swf(&junk[..]); + // TODO: Verify correct error. + assert!(result.is_err()); + } + + #[test] + fn read_compression_type() { + assert_eq!(Reader::read_compression_type(&b"FWS"[..]).unwrap(), Compression::None); + assert_eq!(Reader::read_compression_type(&b"CWS"[..]).unwrap(), Compression::Zlib); + assert_eq!(Reader::read_compression_type(&b"ZWS"[..]).unwrap(), Compression::Lzma); + assert!(Reader::read_compression_type(&b"ABC"[..]).is_err()); + } + + #[test] + fn read_bit() { + let mut buf: &[u8] = &[0b01010101, 0b00100101]; + let mut reader = Reader::new(&mut buf, 1); + assert_eq!( + (0..16).map(|_| reader.read_bit().unwrap()).collect::>(), + [false, true, false, true, false, true, false, true, + false, false, true, false, false, true, false, true] + ); + } + + #[test] + fn read_ubits() { + let mut buf: &[u8] = &[0b01010101, 0b00100101]; + let mut reader = Reader::new(&mut buf, 1); + assert_eq!( + (0..8).map(|_| reader.read_ubits(2).unwrap()).collect::>(), + [1, 1, 1, 1, 0, 2, 1, 1] + ); + } + + #[test] + fn read_sbits() { + let mut buf: &[u8] = &[0b01010101, 0b00100101]; + let mut reader = Reader::new(&mut buf, 1); + assert_eq!( + (0..8).map(|_| reader.read_sbits(2).unwrap()).collect::>(), + [1, 1, 1, 1, 0, -2, 1, 1] + ); + } + + #[test] + fn read_fbits() { + assert_eq!(Reader::new(&[0][..], 1).read_fbits(5).unwrap(), 0f32); + assert_eq!(Reader::new(&[0b01000000, 0b00000000, 0b0_0000000][..], 1).read_fbits(17).unwrap(), 0.5f32); + assert_eq!(Reader::new(&[0b10000000, 0b00000000][..], 1).read_fbits(16).unwrap(), -0.5f32); + } + + #[test] + fn read_fixed88() { + let buf = [ + 0b00000000, 0b00000000, + 0b00000000, 0b00000001, + 0b10000000, 0b00000110, + 0b01000000, 0b11101011, + ]; + let mut reader = Reader::new( &buf[..], 1 ); + assert_eq!(reader.read_fixed88().unwrap(), 0f32); + assert_eq!(reader.read_fixed88().unwrap(), 1f32); + assert_eq!(reader.read_fixed88().unwrap(), 6.5f32); + assert_eq!(reader.read_fixed88().unwrap(), -20.75f32); + } + + #[test] + fn read_encoded_u32() { + let read = |data: &[u8]| { reader(data).read_encoded_u32().unwrap() }; + assert_eq!(read(&[0]), 0); + assert_eq!(read(&[2]), 2); + assert_eq!(read(&[0b1_0000001, 0b0_0000001]), 129); + assert_eq!(read(&[0b1_0000001, 0b1_0000001, 0b0_1100111]), 0b1100111_0000001_0000001); + assert_eq!(read(&[0b1_0000000, 0b1_0000000, 0b1_0000000, 0b1_0000000, 0b0000_1111]), 0b1111_0000000_0000000_0000000_0000000); + assert_eq!(read(&[0b1_0000000, 0b1_0000000, 0b1_0000000, 0b1_0000000, 0b1111_1111]), 0b1111_0000000_0000000_0000000_0000000); + } + + #[test] + fn read_rectangle_zero() { + let buf = [0b00000_000]; + let mut reader = Reader::new( &buf[..], 1 ); + let rectangle = reader.read_rectangle().unwrap(); + assert_eq!(rectangle, Rectangle { x_min: 0f32, x_max: 0f32, y_min: 0f32, y_max: 0f32 }); + } + + #[test] + fn read_rectangle_signed() { + let buf = [0b00110_101, 0b100_01010, 0b0_101100_0, 0b10100_000]; + let mut reader = Reader::new( &buf[..], 1 ); + let rectangle = reader.read_rectangle().unwrap(); + assert_eq!(rectangle, Rectangle { x_min: -1f32, x_max: 1f32, y_min: -1f32, y_max: 1f32 }); + } + + #[test] + fn read_matrix() { + { + let buf = [0b0_0_00001_0, 0b0_0000000]; + let mut reader = Reader::new( &buf[..], 1 ); + let matrix = reader.read_matrix().unwrap(); + assert_eq!(matrix, Matrix { translate_x: 0f32, translate_y: 0f32, scale_x: 1f32, scale_y: 1f32, rotate_skew_0: 0f32, rotate_skew_1: 0f32 }); + } + } + + #[test] + fn read_color() { + { + let buf = [1, 128, 255]; + let mut reader = Reader::new( &buf[..], 1 ); + assert_eq!(reader.read_rgb().unwrap(), Color { r: 1, g: 128, b: 255, a: 255 }); + } + { + let buf = [1, 128, 235, 44]; + let mut reader = Reader::new( &buf[..], 1 ); + assert_eq!(reader.read_rgba().unwrap(), Color { r: 1, g: 128, b: 235, a: 44 }); + } + } + + #[test] + fn read_c_string() { + { + let buf = "Testing\0".as_bytes(); + let mut reader = Reader::new( &buf[..], 1 ); + assert_eq!(reader.read_c_string().unwrap(), "Testing"); + } + { + let buf = "12🤖12\0".as_bytes(); + let mut reader = Reader::new( &buf[..], 1 ); + assert_eq!(reader.read_c_string().unwrap(), "12🤖12"); + } + } + + // TAGS + #[test] + fn read_unknown_tag() { + { + let buf = &[0b00_000000, 0b10000000]; + let mut reader = Reader::new(&buf[..], 1); + assert_eq!(reader.read_tag().unwrap().unwrap(), Tag::Unknown { tag_code: 512, data: [].to_vec() }); + } + + { + let buf = &[0b01_000010, 0b10000000, 1, 2]; + let mut reader = Reader::new(&buf[..], 1); + assert_eq!(reader.read_tag().unwrap().unwrap(), Tag::Unknown { tag_code: 513, data: [1, 2].to_vec() }); + } + + { + let buf = &[0b01_111111, 0b10000000, 3, 0, 0, 0, 1, 2, 3]; + let mut reader = Reader::new(&buf[..], 1); + assert_eq!(reader.read_tag().unwrap().unwrap(), Tag::Unknown { tag_code: 513, data: [1, 2, 3].to_vec() }); + } + } + + #[test] + fn read_end_tag() { + let buf = [0, 0]; + let mut reader = Reader::new(&buf[..], 1); + assert_eq!(reader.read_tag().unwrap(), None); + } + + #[test] + fn read_show_frame() { + let buf = [0b01_000000, 0]; + let mut reader = Reader::new(&buf[..], 1); + assert_eq!(reader.read_tag().unwrap().unwrap(), Tag::ShowFrame); + } + + #[test] + fn read_define_shape() { + unimplemented!() + } + + #[test] + fn read_shape_styles() { + unimplemented!() + } + + #[test] + fn read_fill_style() { + unimplemented!() + } + + #[test] + fn read_line_style() { + unimplemented!() + } + + #[test] + fn read_gradient() { + unimplemented!() + } + + #[test] + fn read_shape_record() { + unimplemented!() + } + + #[test] + fn read_file_attributes() { + let file_attributes = FileAttributes { + use_direct_blit: false, + use_gpu: true, + has_metadata: false, + is_action_script_3: true, + use_network_sandbox: false, + }; + let buf = [0b01_000100, 0b00010001, 0b00101000, 0, 0, 0]; + let mut reader = Reader::new(&buf[..], 1); + assert_eq!(reader.read_tag().unwrap().unwrap(), Tag::FileAttributes(file_attributes)); + } + + #[test] + fn read_set_background_color() { + let buf = [0b01_000011, 0b00000010, 64, 150, 255]; + let mut reader = Reader::new(&buf[..], 1); + assert_eq!(reader.read_tag().unwrap().unwrap(), Tag::SetBackgroundColor(Color { r: 64, g: 150, b: 255, a: 255 })); + } + + #[test] + fn read_define_scene_and_frame_label_data() { + assert_eq!( + read_tag_from_file("test/swfs/define_scene_and_frame_label_data.bin", 8), + Tag::DefineSceneAndFrameLabelData { + scenes: vec![ + FrameLabel { frame_num: 0, label: "Scene 1".to_string() }, + FrameLabel { frame_num: 25, label: "Scene2Scene2Scene2Scene2Scene2".to_string() }, + FrameLabel { frame_num: 26, label: "test日本語test".to_string() }, + ], + frame_labels: vec![ + FrameLabel { frame_num: 0, label: "a".to_string() }, + FrameLabel { frame_num: 9, label: "b".to_string() }, + FrameLabel { frame_num: 17, label: "❤😁aaa".to_string() }, + FrameLabel { frame_num: 25, label: "frameInScene2".to_string() }, + ], + } + ); + } + + #[test] + fn read_tag_list() { + { + let buf = [0, 0]; + let mut reader = Reader::new(&buf[..], 1); + assert_eq!(reader.read_tag_list().unwrap(), []); + } + + { + let buf = [0b01_000000, 0b00000000, 0, 0]; + let mut reader = Reader::new(&buf[..], 1); + assert_eq!(reader.read_tag_list().unwrap(), [Tag::ShowFrame]); + } + } +} diff --git a/src/tag_codes.rs b/src/tag_codes.rs new file mode 100644 index 000000000..627e93484 --- /dev/null +++ b/src/tag_codes.rs @@ -0,0 +1,85 @@ +#[derive(Debug,PartialEq,Clone)] +pub enum TagCode { + End = 0, + ShowFrame = 1, + DefineShape = 2, + + PlaceObject = 4, + RemoveObject = 5, + DefineBits = 6, + DefineButton = 7, + JpefTables = 8, + SetBackgroundColor = 9, + DefineFont = 10, + DefineText = 11, + DoAction = 12, + DefineFontInfo = 13, + DefineSound = 14, + StartSound = 15, + + DefineButtonSound = 17, + SoundStreamHead = 18, + SoundStreamBlock = 19, + DefineBitsLossless = 20, + DefineBitsJpeg = 21, + DefineShape2 = 22, + DefineButtonCxform = 23, + Protect = 24, + + PlaceObject2 = 26, + + RemoveObject2 = 28, + + DefineShape3 = 32, + DefineText2 = 33, + DefineButton2 = 34, + DefineBitsJpeg3 = 35, + DefineBitsLossless2 = 36, + DefineEditText = 37, + + DefineSprite = 39, + + FrameLabel = 43, + + SoundStreamHead2 = 45, + DefineMorphShape = 46, + + DefineFont2 = 48, + + ExportAssets = 56, + ImportAssets = 57, + EnableDebugger = 58, + DoInitAction = 59, + DefineVideoStream = 60, + VideoFrame = 61, + DefineFontInfo2 = 62, + + EnableDebugger2 = 64, + ScriptLimits = 65, + SetTabIndex = 66, + + FileAttributes = 69, + + PlaceObject3 = 70, + ImportAssets2 = 71, + + DefineFontAlignZones = 73, + CsmTextSettings = 74, + DefineFont3 = 75, + SymbolClass = 76, + Metadata = 77, + DefineScalingGrid = 78, + + DoAbc = 82, + DefineShape4 = 83, + DefineMorphShape2 = 84, + + DefineSceneAndFrameLabelData = 86, + DefineBinaryData = 87, + DefineFontName = 88, + StartSound2 = 89, + DefineBitsJpeg4 = 90, + DefineFont4 = 91, + + EnableTelemetry = 93, +} \ No newline at end of file diff --git a/src/types.rs b/src/types.rs new file mode 100644 index 000000000..e025c5a9a --- /dev/null +++ b/src/types.rs @@ -0,0 +1,208 @@ + + +#[derive(Debug,PartialEq)] +pub struct Swf { + pub version: u8, + pub compression: Compression, + pub stage_size: Rectangle, + pub frame_rate: f32, + pub num_frames: u16, + pub tags: Vec, +} + +/// Defines the compression type used in an SWF. +#[derive(Debug,PartialEq,Eq)] +pub enum Compression { + None, + Zlib, + Lzma, +} + +#[derive(Debug,PartialEq,Clone)] +pub struct Rectangle { + pub x_min: f32, + pub x_max: f32, + pub y_min: f32, + pub y_max: f32, +} + +#[derive(Debug,PartialEq)] +pub struct Color { + pub r: u8, + pub g: u8, + pub b: u8, + pub a: u8, +} + +#[derive(Debug,PartialEq)] +pub struct ColorTransform { + pub r_multiply: i16, + pub g_multiply: i16, + pub b_multiply: i16, + pub a_multiply: i16, + pub r_add: i16, + pub g_add: i16, + pub b_add: i16, + pub a_add: i16, +} + +#[derive(Debug,PartialEq)] +pub struct Matrix { + pub translate_x: f32, + pub translate_y: f32, + pub scale_x: f32, + pub scale_y: f32, + pub rotate_skew_0: f32, + pub rotate_skew_1: f32, +} + +impl Matrix { + pub fn new() -> Matrix { + Matrix { translate_x: 0f32, translate_y: 0f32, scale_x: 1f32, scale_y: 1f32, rotate_skew_0: 1f32, rotate_skew_1: 1f32 } + } +} + +#[derive(Debug,PartialEq)] +pub struct FileAttributes { + pub use_direct_blit: bool, + pub use_gpu: bool, + pub has_metadata: bool, + pub is_action_script_3: bool, + pub use_network_sandbox: bool, +} + +#[derive(Debug,PartialEq)] +pub struct FrameLabel { + pub frame_num: u32, + pub label: String, +} + +pub type Depth = i16; +pub type CharacterId = u16; +pub type Ratio = u16; +pub type Twips = i32; + +#[derive(Debug,PartialEq)] +pub struct PlaceObject { + pub depth: Depth, + pub id: Option, + pub matrix: Option, + //pub color_transform: CxformA, + pub ratio: Option, + pub name: Option, + pub clip_depth: Option, + //pub clip_actions +} + +#[derive(Debug,PartialEq)] +pub enum Tag { + ShowFrame, + + DefineShape(Shape), + + SetBackgroundColor(Color), + + PlaceObject(PlaceObject), + + FileAttributes(FileAttributes), + + DefineSceneAndFrameLabelData { scenes: Vec, frame_labels: Vec }, + + Unknown { tag_code: u16, data: Vec }, +} + +#[derive(Debug,PartialEq)] +pub struct Shape { + pub version: u8, + pub id: CharacterId, + pub shape_bounds: Rectangle, + pub edge_bounds: Rectangle, + pub styles: ShapeStyles, + pub shape: Vec, +} + +#[derive(Debug,PartialEq)] +pub struct ShapeStyles { + pub fill_styles: Vec, + pub line_styles: Vec, + pub num_fill_bits: u8, + pub num_line_bits: u8, +} + +#[derive(Debug,PartialEq)] +pub enum ShapeRecord { + // TODO: Twips + StyleChange(StyleChangeData), + StraightEdge { delta_x: f32, delta_y: f32 }, + CurvedEdge { control_delta_x: f32, control_delta_y: f32, anchor_delta_x: f32, anchor_delta_y: f32 }, +} + +#[derive(Debug,PartialEq)] +pub struct StyleChangeData { + pub move_delta_x: f32, + pub move_delta_y: f32, + pub fill_style_0: Option, + pub fill_style_1: Option, + pub line_style: Option, + pub new_styles: Option, +} + +#[derive(Debug,PartialEq)] +pub enum FillStyle { + Color(Color), + LinearGradient(Gradient), + RadialGradient(Gradient), + FocalGradient{ gradient: Gradient, focal_point: f32 }, + Bitmap { id: CharacterId, matrix: Matrix, is_smoothed: bool, is_repeating: bool }, +} + +#[derive(Debug,PartialEq)] +pub struct Gradient { + pub spread: GradientSpread, + pub interpolation: GradientInterpolation, + pub records: Vec, +} + +#[derive(Debug,PartialEq)] +pub enum GradientSpread { + Pad, + Reflect, + Repeat, +} + +#[derive(Debug,PartialEq)] +pub enum GradientInterpolation { + RGB, + LinearRGB, +} + +#[derive(Debug,PartialEq)] +pub struct GradientRecord { + pub ratio: u8, + pub color: Color, +} + +#[derive(Debug,PartialEq)] +pub struct BitmapFill { + +} + +#[derive(Debug,PartialEq)] +pub struct LineStyle { + pub width: u16, // Twips + pub color: Color, +} + +// TODO: LineStyle2. +#[derive(Debug,PartialEq)] +pub enum LineCapStyle { + Round, + None, + Square, +} +#[derive(Debug,PartialEq)] +pub enum LineJoinStyle { + Round, + Bevel, + Miter(f32), +} \ No newline at end of file diff --git a/src/write.rs b/src/write.rs new file mode 100644 index 000000000..a6eb6789d --- /dev/null +++ b/src/write.rs @@ -0,0 +1,934 @@ +use byteorder::{LittleEndian, WriteBytesExt}; +use flate2::Compression as ZlibCompression; +use flate2::write::ZlibEncoder; +use std::cmp::{min, max}; +use std::io::{Error, ErrorKind, Result, Write}; +use tag_codes::TagCode; +use types::*; +use xz2::write::XzEncoder; + +pub fn write_swf(swf: &Swf, mut output: W) -> Result<()> { + let signature = match swf.compression { + Compression::None => b"FWS", + Compression::Zlib => b"CWS", + Compression::Lzma => b"ZWS", + }; + try!(output.write_all(&signature[..])); + try!(output.write_u8(swf.version)); + + let uncompressed_length; + let mut buf = Vec::new(); + { + let mut compressed_output: Box = match swf.compression { + Compression::None => { + Box::new(&mut buf) + }, + + Compression::Zlib => { + Box::new(CountWriter::new(ZlibEncoder::new(&mut buf, ZlibCompression::Best))) + }, + + Compression::Lzma => { + //SWF uses an LZMA1 stream, not XZ2. + use xz2::stream::{LzmaOptions, Stream}; + let stream = try!(Stream::new_lzma_encoder(&try!(LzmaOptions::new_preset(9)))); + Box::new(XzEncoder::new_stream(&mut buf, stream)) + } + }; + + let mut writer = Writer::new(compressed_output, swf.version); + try!(writer.write_rectangle(&swf.stage_size)); + try!(writer.write_fixed88(swf.frame_rate)); + try!(writer.write_u16(swf.num_frames)); + + // Write main timeline tag list. + try!(writer.write_tag_list(&swf.tags)); + + uncompressed_length = writer.into_inner().total_in(); + } + + // TODO: This is the uncompressed length. + // I'm writing the compressed length. + try!(output.write_u32::((uncompressed_length + 8) as u32)); + + if let Compression::Lzma = swf.compression { + // LZMA header. + // SWF format has a mangled LZMA header. + // https://helpx.adobe.com/flash-player/kb/exception-thrown-you-decompress-lzma-compressed.html + let lzma_properties = &buf[0..5]; + try!(output.write_u32::(buf.len() as u32)); + try!(output.write_all(lzma_properties)); + try!(output.write_all(&buf[13..])); + } + + try!(output.write_all(&buf)); + + Ok(()) +} + +// TODO: We need to keep track of the uncompressed size of the SWF stream. +// This is placed in the SWF header. +// Unfortunately, flate2 ZlibEncoder does not provide a total_in method. +// There's probably a better way to do this, and/or contribute total_in +// to ZlibEncoder. +trait CountWrite : Write { + fn total_in(&self) -> usize; +} + +impl<'a> CountWrite for &'a mut Vec { + fn total_in(&self) -> usize { + self.len() + } +} + +impl CountWrite for XzEncoder { + fn total_in(&self) -> usize { + self.total_in() as usize + } +} + +struct CountWriter { + inner: W, + total_in: usize, +} + +impl CountWriter { + pub fn new(inner: W) -> CountWriter { + CountWriter { inner: inner, total_in: 0 } + } +} + +impl Write for CountWriter { + fn write(&mut self, buf: &[u8]) -> Result { + let result = self.inner.write(buf); + if let Ok(n) = result { + self.total_in += n; + } + result + } + + fn flush(&mut self) -> Result<()> { + self.inner.flush() + } +} + +impl CountWrite for CountWriter { + fn total_in(&self) -> usize { + self.total_in + } +} + +struct Writer { + pub output: W, + pub version: u8, + pub byte: u8, + pub bit_index: u8, + pub num_fill_bits: u8, + pub num_line_bits: u8, +} + +impl Writer { + fn new(output: W, version: u8) -> Writer { + Writer { + output: output, + version: version, + byte: 0, + bit_index: 8, + num_fill_bits: 0, + num_line_bits: 0, + } + } + + fn into_inner(self) -> W { + self.output + } + + fn write_u8(&mut self, n: u8) -> Result<()> { + try!(self.flush_bits()); + self.output.write_u8(n) + } + + fn write_u16(&mut self, n: u16) -> Result<()> { + try!(self.flush_bits()); + self.output.write_u16::(n) + } + + fn write_u32(&mut self, n: u32) -> Result<()> { + try!(self.flush_bits()); + self.output.write_u32::(n) + } + + fn write_i16(&mut self, n: i16) -> Result<()> { + try!(self.flush_bits()); + self.output.write_i16::(n) + } + + fn write_fixed88(&mut self, n: f32) -> Result<()> { + self.output.write_i16::((n * 256f32) as i16) + } + + fn write_bit(&mut self, set: bool) -> Result<()> { + self.bit_index -= 1; + if set { + self.byte |= 1 << self.bit_index; + } + if self.bit_index == 0 { + try!(self.flush_bits()); + } + Ok(()) + } + + fn flush_bits(&mut self) -> Result<()> { + if self.bit_index != 8 { + try!(self.output.write_u8(self.byte)); + self.bit_index = 8; + self.byte = 0; + } + Ok(()) + } + + + fn write_ubits(&mut self, num_bits: u8, n: u32) -> Result<()> { + for i in 0..num_bits { + try!(self.write_bit(n & (1 << ((num_bits-i-1) as u32)) != 0)); + } + Ok(()) + } + + fn write_sbits(&mut self, num_bits: u8, n: i32) -> Result<()> { + self.write_ubits(num_bits, n as u32) + } + + fn write_fbits(&mut self, num_bits: u8, n: f32) -> Result<()> { + self.write_ubits(num_bits, (n * 65536f32) as u32) + } + + fn write_encoded_u32(&mut self, mut n: u32) -> Result<()> { + loop { + let mut byte = (n & 0b01111111) as u8; + n >>= 7; + if n != 0 { + byte |= 0b10000000; + } + try!(self.write_u8(byte)); + if n == 0 { + break; + } + } + Ok(()) + } + + fn write_c_string(&mut self, s: &str) -> Result<()> { + try!(self.flush_bits()); + try!(self.output.write_all(s.as_bytes())); + self.write_u8(0) + } + + fn write_rectangle(&mut self, rectangle: &Rectangle) -> Result<()> { + try!(self.flush_bits()); + let num_bits: u8 = [rectangle.x_min, rectangle.x_max, rectangle.y_min, rectangle.y_max].iter().map(|x| count_sbits((*x * 20f32) as i32)).max().unwrap(); + try!(self.write_ubits(5, num_bits as u32)); + try!(self.write_sbits(num_bits, (rectangle.x_min * 20f32) as i32)); + try!(self.write_sbits(num_bits, (rectangle.x_max * 20f32) as i32)); + try!(self.write_sbits(num_bits, (rectangle.y_min * 20f32) as i32)); + try!(self.write_sbits(num_bits, (rectangle.y_max * 20f32) as i32)); + Ok(()) + } + + fn write_rgb(&mut self, color: &Color) -> Result<()> { + try!(self.write_u8(color.r)); + try!(self.write_u8(color.g)); + try!(self.write_u8(color.b)); + Ok(()) + } + + fn write_rgba(&mut self, color: &Color) -> Result<()> { + try!(self.write_u8(color.r)); + try!(self.write_u8(color.g)); + try!(self.write_u8(color.b)); + try!(self.write_u8(color.a)); + Ok(()) + } + + fn write_matrix(&mut self, m: &Matrix) -> Result<()> { + try!(self.flush_bits()); + // Scale + let has_scale = m.scale_x != 1f32 || m.scale_y != 1f32; + try!(self.write_bit(has_scale)); + if has_scale { + let num_bits = max(count_fbits(m.scale_x), count_fbits(m.scale_y)); + try!(self.write_ubits(5, num_bits as u32)); + try!(self.write_fbits(num_bits, m.scale_x)); + try!(self.write_fbits(num_bits, m.scale_y)); + } + // Rotate/Skew + let has_rotate_skew = m.rotate_skew_0 != 0f32 || m.rotate_skew_1 != 0f32; + try!(self.write_bit(has_rotate_skew)); + if has_rotate_skew { + let num_bits = max(count_fbits(m.rotate_skew_0), count_fbits(m.rotate_skew_1)); + try!(self.write_ubits(5, num_bits as u32)); + try!(self.write_fbits(num_bits, m.rotate_skew_0)); + try!(self.write_fbits(num_bits, m.rotate_skew_1)); + } + // Translate (always written) + let num_bits = max(count_fbits(m.translate_x), count_fbits(m.translate_y)); + try!(self.write_ubits(5, num_bits as u32)); + try!(self.write_fbits(num_bits, m.translate_x)); + try!(self.write_fbits(num_bits, m.translate_y)); + Ok(()) + } + + fn write_tag(&mut self, tag: &Tag) -> Result<()> { + match tag { + &Tag::ShowFrame => try!(self.write_tag_header(TagCode::ShowFrame, 0)), + + &Tag::DefineShape(ref shape) => try!(self.write_define_shape(shape)), + + // TODO: Allow clone of color. + &Tag::SetBackgroundColor(ref color) => { + try!(self.write_tag_header(TagCode::SetBackgroundColor, 3)); + try!(self.write_rgb(color)); + } + + &Tag::PlaceObject(ref place_object) => unimplemented!(), + + &Tag::FileAttributes(ref attributes) => { + try!(self.write_tag_header(TagCode::FileAttributes, 4)); + let mut flags = 0u32; + if attributes.use_direct_blit { flags |= 0b01000000; } + if attributes.use_gpu { flags |= 0b00100000; } + if attributes.has_metadata { flags |= 0b00010000; } + if attributes.is_action_script_3 { flags |= 0b00001000; } + if attributes.use_network_sandbox { flags |= 0b00000001; } + try!(self.write_u32(flags)); + }, + + &Tag::DefineSceneAndFrameLabelData { ref scenes, ref frame_labels } => try!(self.write_define_scene_and_frame_label_data(scenes, frame_labels)), + + &Tag::Unknown { tag_code, ref data } => { + try!(self.write_tag_code_and_length(tag_code, data.len() as u32)); + try!(self.output.write_all(data)); + } + } + Ok(()) + } + + fn write_define_scene_and_frame_label_data(&mut self, scenes: &Vec, frame_labels: &Vec) -> Result<()> { + + let mut buf = Vec::with_capacity((scenes.len() + frame_labels.len()) * 4); + { + let mut writer = Writer::new(&mut buf, self.version); + try!(writer.write_encoded_u32(scenes.len() as u32)); + for scene in scenes { + try!(writer.write_encoded_u32(scene.frame_num)); + try!(writer.write_c_string(&scene.label)); + } + try!(writer.write_encoded_u32(frame_labels.len() as u32)); + for frame_label in frame_labels { + try!(writer.write_encoded_u32(frame_label.frame_num)); + try!(writer.write_c_string(&frame_label.label)); + } + } + try!(self.write_tag_header(TagCode::DefineSceneAndFrameLabelData, buf.len() as u32)); + try!(self.output.write_all(&buf)); + Ok(()) + } + + fn write_define_shape(&mut self, shape: &Shape) -> Result<()> { + let mut buf = Vec::new(); + { + let mut writer = Writer::new(&mut buf, self.version); + try!(writer.write_u16(shape.id)); + try!(writer.write_rectangle(&shape.shape_bounds)); + try!(writer.write_shape_styles(&shape.styles, shape.version)); + + writer.num_fill_bits = shape.styles.num_fill_bits; + writer.num_line_bits = shape.styles.num_line_bits; + for shape_record in &shape.shape { + try!(writer.write_shape_record(shape_record, shape.version)); + } + // End shape record. + try!(writer.write_ubits(6, 0)); + try!(writer.flush_bits()); + } + + let tag_code = match shape.version { + 1 => TagCode::DefineShape, + 2 => TagCode::DefineShape2, + 3 => TagCode::DefineShape3, + 4 => TagCode::DefineShape4, + _ => return Err(Error::new(ErrorKind::InvalidData, "Invalid DefineShape version.")), + }; + try!(self.write_tag_header(tag_code, buf.len() as u32)); + try!(self.output.write_all(&buf)); + Ok(()) + } + + fn write_shape_styles(&mut self, styles: &ShapeStyles, shape_version: u8) -> Result<()> { + // TODO: Check shape_version. + if styles.fill_styles.len() >= 0xff { + try!(self.write_u8(0xff)); + try!(self.write_u16(styles.fill_styles.len() as u16)); + } + else { + try!(self.write_u8(styles.fill_styles.len() as u8)); + } + for fill_style in &styles.fill_styles { + try!(self.write_fill_style(fill_style, shape_version)); + } + + if styles.line_styles.len() >= 0xff { + try!(self.write_u8(0xff)); + try!(self.write_u16(styles.line_styles.len() as u16)); + } + else { + try!(self.write_u8(styles.line_styles.len() as u8)); + } + for line_style in &styles.line_styles { + try!(self.write_line_style(line_style, shape_version)); + } + try!(self.write_ubits(4, styles.num_fill_bits as u32)); + try!(self.write_ubits(4, styles.num_line_bits as u32)); + Ok(()) + } + + fn write_shape_record(&mut self, record: &ShapeRecord, shape_version: u8) -> Result<()> { + match record { + &ShapeRecord::StraightEdge { delta_x, delta_y } => { + try!(self.write_ubits(2, 0b11)); // Straight edge + let delta_x_twips = (delta_x * 20f32) as i32; + let delta_y_twips = (delta_y * 20f32) as i32; + let num_bits = max(2, max(count_sbits(delta_x_twips), count_sbits(delta_y_twips))); // TODO: Underflow? + let is_axis_aligned = delta_x_twips == 0 || delta_y_twips == 0; + try!(self.write_ubits(4, num_bits as u32 - 2)); + try!(self.write_bit(!is_axis_aligned)); + if is_axis_aligned { try!(self.write_bit(delta_x_twips == 0)); } + if delta_x_twips != 0 { try!(self.write_sbits(num_bits, delta_x_twips)); } + if delta_y_twips != 0 { try!(self.write_sbits(num_bits, delta_y_twips)); } + }, + &ShapeRecord::CurvedEdge { control_delta_x, control_delta_y, anchor_delta_x, anchor_delta_y } => { + try!(self.write_ubits(2, 0b10)); // Curved edge + let control_twips_x = (control_delta_x * 20f32) as i32; + let control_twips_y = (control_delta_y * 20f32) as i32; + let anchor_twips_x = (anchor_delta_x * 20f32) as i32; + let anchor_twips_y = (anchor_delta_y * 20f32) as i32; + let num_bits = [control_twips_x, control_twips_y, anchor_twips_x, anchor_twips_y].iter().map(|x| count_sbits(*x)).max().unwrap(); + try!(self.write_ubits(4, num_bits as u32 - 2)); + try!(self.write_sbits(num_bits, control_twips_x)); + try!(self.write_sbits(num_bits, control_twips_y)); + try!(self.write_sbits(num_bits, anchor_twips_x)); + try!(self.write_sbits(num_bits, anchor_twips_y)); + }, + &ShapeRecord::StyleChange(ref style_change) => { + try!(self.write_bit(false)); // Style change + let num_fill_bits = self.num_fill_bits; + let num_line_bits = self.num_line_bits; + try!(self.write_bit(style_change.new_styles.is_some())); + try!(self.write_bit(style_change.line_style.is_some())); + try!(self.write_bit(style_change.fill_style_1.is_some())); + try!(self.write_bit(style_change.fill_style_0.is_some())); + try!(self.write_bit(style_change.move_delta_x != 0f32 || style_change.move_delta_y != 0f32)); + if style_change.move_delta_x != 0f32 || style_change.move_delta_y != 0f32 { + let move_twips_x = (style_change.move_delta_x * 20f32) as i32; + let move_twips_y = (style_change.move_delta_y * 20f32) as i32; + let num_bits = max(count_sbits(move_twips_x), count_sbits(move_twips_y)); + try!(self.write_ubits(5, num_bits as u32)); + try!(self.write_sbits(num_bits, move_twips_x)); + try!(self.write_sbits(num_bits, move_twips_y)); + } + if let Some(fill_style_index) = style_change.fill_style_0 { + try!(self.write_ubits(num_fill_bits, fill_style_index)); + } + if let Some(fill_style_index) = style_change.fill_style_1 { + try!(self.write_ubits(num_fill_bits, fill_style_index)); + } + if let Some(line_style_index) = style_change.line_style { + try!(self.write_ubits(num_line_bits, line_style_index)); + } + if let Some(ref new_styles) = style_change.new_styles { + if shape_version < 2 { + return Err(Error::new(ErrorKind::InvalidData, "Only DefineShape2 and higher may change styles.")); + } + try!(self.write_shape_styles(new_styles, shape_version)); + } + }, + } + Ok(()) + } + + fn write_fill_style(&mut self, fill_style: &FillStyle, shape_version: u8) -> Result<()> { + match fill_style { + &FillStyle::Color(ref color) => { + try!(self.write_u8(0x00)); // Solid color. + if shape_version >= 3 { try!(self.write_rgba(color)) } else { try!(self.write_rgb(color)); } + } + + &FillStyle::LinearGradient(ref gradient) => { + try!(self.write_u8(0x10)); // Linear gradient. + try!(self.write_gradient(gradient, shape_version)); + }, + + &FillStyle::RadialGradient(ref gradient) => { + try!(self.write_u8(0x12)); // Linear gradient. + try!(self.write_gradient(gradient, shape_version)); + }, + + &FillStyle::FocalGradient { ref gradient, focal_point } => { + if self.version < 8 { + return Err(Error::new(ErrorKind::InvalidData, "Focal gradients are only support in SWF version 8 and higher.")); + } + + try!(self.write_u8(0x13)); // Focal gradient. + try!(self.write_gradient(gradient, shape_version)); + try!(self.write_fixed88(focal_point)); + }, + + &FillStyle::Bitmap { id, ref matrix, is_smoothed, is_repeating } => { + let fill_style_type = match (is_smoothed, is_repeating) { + (true, true) => 0x40, + (true, false) => 0x41, + (false, true) => 0x42, + (false, false) => 0x43, + }; + try!(self.write_u8(fill_style_type)); + try!(self.write_u16(id)); + try!(self.write_matrix(matrix)); + } + } + Ok(()) + } + + fn write_line_style(&mut self, line_style: &LineStyle, shape_version: u8) -> Result<()> { + try!(self.write_u16(line_style.width)); + if shape_version >= 3 { try!(self.write_rgba(&line_style.color)); } else { try!(self.write_rgb(&line_style.color)); } + Ok(()) + } + + fn write_gradient(&mut self, gradient: &Gradient, shape_version: u8) -> Result<()> { + let spread_bits = match gradient.spread { + GradientSpread::Pad => 0, + GradientSpread::Reflect => 1, + GradientSpread::Repeat => 2, + }; + try!(self.write_ubits(2, spread_bits)); + let interpolation_bits = match gradient.interpolation { + GradientInterpolation::RGB => 0, + GradientInterpolation::LinearRGB => 1, + }; + try!(self.write_ubits(2, interpolation_bits)); + // TODO: Check overflow. + try!(self.write_ubits(4, gradient.records.len() as u32)); + for record in &gradient.records { + try!(self.write_u8(record.ratio)); + if shape_version >= 3 { try!(self.write_rgba(&record.color)); } else { try!(self.write_rgb(&record.color)); } + } + Ok(()) + } + + fn write_tag_header(&mut self, tag_code: TagCode, length: u32) -> Result<()> { + self.write_tag_code_and_length(tag_code as u16, length) + } + + fn write_tag_code_and_length(&mut self, tag_code: u16, length: u32) -> Result<()> { + // TODO: Test for tag code/length overflow. + let mut tag_code_and_length: u16 = tag_code << 6; + if length < 0b111111 { + tag_code_and_length |= length as u16; + self.write_u16(tag_code_and_length) + } else { + tag_code_and_length |= 0b111111; + try!(self.write_u16(tag_code_and_length)); + self.write_u32(length) + } + } + + fn write_tag_list(&mut self, tags: &Vec) -> Result<()> { + // TODO: Better error handling. Can skip errored tags, unless EOF. + for tag in tags { + try!(self.write_tag(tag)); + } + // Write End tag. + self.write_u16(0) + } +} + +fn count_ubits(mut n: u32) -> u8 { + if n == 0 { 1 } else { + let mut num_bits = 0; + while n > 0 { + n >>= 1; + num_bits += 1; + } + num_bits + } +} + +fn count_sbits(n: i32) -> u8 { + if n == 0 || n == -1 { + 1 + } else if n < 0 { + count_ubits((!n) as u32) + 1 + } else { + count_ubits(n as u32) + 1 + } +} + +fn count_fbits(n: f32) -> u8 { + count_sbits( (n * 65536f32) as i32 ) +} + +#[cfg(test)] +mod tests { + use super::*; + use super::Writer; + use std::io::{Read, Result}; + use std::fs::File; + use types::*; + + fn new_swf() -> Swf { + Swf { + version: 13, + compression: Compression::Zlib, + stage_size: Rectangle { x_min: 0f32, x_max: 640f32, y_min: 0f32, y_max: 480f32 }, + frame_rate: 60.0, + num_frames: 1, + tags: vec![], + } + } + + fn write_tag_to_buf(tag: &Tag, swf_version: u8) -> Vec { + let mut buf = Vec::new(); + Writer::new(&mut buf, swf_version).write_tag(tag).unwrap(); + buf + } + + fn get_file_contents(file: &str) -> Vec { + let mut buf = Vec::new(); + let mut file = File::open(file).unwrap(); + file.read_to_end(&mut buf).unwrap(); + buf + } + + #[test] + fn write_swfs() { + fn write_dummy_swf(compression: Compression) -> Result<()> { + let mut buf = Vec::new(); + let mut swf = new_swf(); + swf.compression = compression; + write_swf(&swf, &mut buf) + } + assert!(write_dummy_swf(Compression::None).is_ok(), "Failed to write uncompressed SWF."); + assert!(write_dummy_swf(Compression::Zlib).is_ok(), "Failed to write zlib SWF."); + assert!(write_dummy_swf(Compression::Lzma).is_ok(), "Failed to write LZMA SWF."); + } + + #[test] + fn write_fixed88() { + let mut buf = Vec::new(); + { + let mut writer = Writer::new( &mut buf, 1 ); + writer.write_fixed88(0f32).unwrap(); + writer.write_fixed88(1f32).unwrap(); + writer.write_fixed88(6.5f32).unwrap(); + writer.write_fixed88(-20.75f32).unwrap(); + } + assert_eq!(buf, [ + 0b00000000, 0b00000000, + 0b00000000, 0b00000001, + 0b10000000, 0b00000110, + 0b01000000, 0b11101011, + ]); + } + + #[test] + fn write_encoded_u32() { + fn write_to_buf(n: u32) ->Vec { + let mut buf = Vec::new(); + { + let mut writer = Writer::new(&mut buf, 1); + writer.write_encoded_u32(n).unwrap(); + } + buf + } + + assert_eq!(write_to_buf(0), [0]); + assert_eq!(write_to_buf(2), [2]); + assert_eq!(write_to_buf(129), [0b1_0000001, 0b0_0000001]); + assert_eq!(write_to_buf(0b1100111_0000001_0000001), [0b1_0000001, 0b1_0000001, 0b0_1100111]); + assert_eq!(write_to_buf(0b1111_0000000_0000000_0000000_0000000u32), [0b1_0000000, 0b1_0000000, 0b1_0000000, 0b1_0000000, 0b0000_1111]); + } + + #[test] + fn write_bit() { + let bits = [false, true, false, true, false, true, false, true, + false, false, true, false, false, true, false, true]; + let mut buf = Vec::new(); + { + let mut writer = Writer::new( &mut buf, 1 ); + for b in bits.iter() { + writer.write_bit(*b).unwrap(); + } + } + assert_eq!(buf, [0b01010101, 0b00100101]); + } + + #[test] + fn write_ubits() { + let num_bits = 2; + let nums = [1, 1, 1, 1, 0, 2, 1, 1]; + let mut buf = Vec::new(); + { + let mut writer = Writer::new( &mut buf, 1 ); + for n in nums.iter() { + writer.write_ubits(num_bits, *n).unwrap(); + } + writer.flush_bits().unwrap(); + } + assert_eq!(buf, [0b01010101, 0b00100101]); + } + + #[test] + fn write_sbits() { + let num_bits = 2; + let nums = [1, 1, 1, 1, 0, -2, 1, 1]; + let mut buf = Vec::new(); + { + let mut writer = Writer::new( &mut buf, 1 ); + for n in nums.iter() { + writer.write_sbits(num_bits, *n).unwrap(); + } + writer.flush_bits().unwrap(); + } + assert_eq!(buf, [0b01010101, 0b00100101]); + } + + #[test] + fn write_fbits() { + let num_bits = 18; + let nums = [1f32, -1f32]; + let mut buf = Vec::new(); + { + let mut writer = Writer::new( &mut buf, 1 ); + for n in nums.iter() { + writer.write_fbits(num_bits, *n).unwrap(); + } + writer.flush_bits().unwrap(); + } + assert_eq!(buf, [0b01_000000, 0b00000000, 0b00_11_0000, 0b00000000, 0b0000_0000]); + } + + #[test] + fn count_ubits() { + assert_eq!(super::count_ubits(0), 1u8); + assert_eq!(super::count_ubits(1u32), 1); + assert_eq!(super::count_ubits(2u32), 2); + assert_eq!(super::count_ubits(0b_00111101_00000000u32), 14); + } + + #[test] + fn count_sbits() { + assert_eq!(super::count_sbits(0), 1u8); + assert_eq!(super::count_sbits(1), 2u8); + assert_eq!(super::count_sbits(2), 3u8); + assert_eq!(super::count_sbits(0b_00111101_00000000), 15u8); + + assert_eq!(super::count_sbits(-1), 1u8); + assert_eq!(super::count_sbits(-2), 2u8); + assert_eq!(super::count_sbits(-0b_00110101_01010101), 15u8); + } + + #[test] + fn write_c_string() { + { + let mut buf = Vec::new(); + { + // TODO: What if I use a cursor instead of buf ? + let mut writer = Writer::new( &mut buf, 1 ); + writer.write_c_string("Hello!").unwrap(); + } + assert_eq!(buf, "Hello!\0".bytes().into_iter().collect::>()); + } + + { + let mut buf = Vec::new(); + { + // TODO: What if I use a cursor instead of buf ? + let mut writer = Writer::new( &mut buf, 1 ); + writer.write_c_string("😀😂!🐼").unwrap(); + } + assert_eq!(buf, "😀😂!🐼\0".bytes().into_iter().collect::>()); + } + } + + #[test] + fn write_rectangle_zero() { + let rect = Rectangle { x_min: 0f32, x_max: 0f32, y_min: 0f32, y_max: 0f32}; + let mut buf = Vec::new(); + { + let mut writer = Writer::new( &mut buf, 1 ); + writer.write_rectangle(&rect).unwrap(); + writer.flush_bits().unwrap(); + } + assert_eq!(buf, [0b_00001_0_0_0, 0b0_0000000]); + } + + #[test] + fn write_rectangle_signed() { + let rect = Rectangle { x_min: -1f32, x_max: 1f32, y_min: -1f32, y_max: 1f32 }; + let mut buf = Vec::new(); + { + let mut writer = Writer::new( &mut buf, 1 ); + writer.write_rectangle(&rect).unwrap(); + writer.flush_bits().unwrap(); + } + assert_eq!(buf, [0b_00110_101, 0b100_01010, 0b0_101100_0, 0b_10100_000]); + } + + #[test] + fn write_color() { + { + let color = Color { r: 1, g: 128, b: 255, a: 255 }; + let mut buf = Vec::new(); + { + let mut writer = Writer::new( &mut buf, 1 ); + writer.write_rgb(&color).unwrap(); + } + assert_eq!(buf, [1, 128, 255]); + } + { + let color = Color { r: 1, g: 2, b: 3, a: 11 }; + let mut buf = Vec::new(); + { + let mut writer = Writer::new( &mut buf, 1 ); + writer.write_rgba(&color).unwrap(); + } + assert_eq!(buf, [1, 2, 3, 11]); + } + } + + #[test] + fn write_matrix() { + unimplemented!() + } + + // TAGS + #[test] + fn write_unknown_tag() { + { + let tag = Tag::Unknown { tag_code: 512, data: vec![0, 1, 2, 3] }; + let mut buf = Vec::new(); + { + let mut writer = Writer::new( &mut buf, 1 ); + writer.write_tag(&tag).unwrap(); + } + assert_eq!(buf, [0b00_000100, 0b10000000, 0, 1, 2, 3]); + } + { + let tag = Tag::Unknown { tag_code: 513, data: vec![0; 63] }; + let mut buf = Vec::new(); + { + let mut writer = Writer::new( &mut buf, 1 ); + writer.write_tag(&tag).unwrap(); + } + let mut expected: Vec = vec![0b01_111111, 0b10000000, 0b00111111, 0, 0, 0]; + expected.extend_from_slice(&[0; 63]); + assert_eq!(buf, expected); + } + } + + #[test] + fn write_simple_tags() { + { + let mut buf = Vec::new(); + { + let mut writer = Writer::new( &mut buf, 1 ); + writer.write_tag(&Tag::ShowFrame).unwrap(); + } + assert_eq!(buf, [0b01_000000, 0b00000000]); + } + } + + #[test] + fn write_set_background_color() { + let mut buf = Vec::new(); + { + let mut writer = Writer::new( &mut buf, 1 ); + writer.write_tag(&Tag::SetBackgroundColor(Color { r: 255, g: 128, b: 0, a: 255 })).unwrap(); + } + assert_eq!(buf, [0b01_000011, 0b00000010, 255, 128, 0]); + } + + #[test] + fn write_file_attributes() { + let file_attributes = FileAttributes { + use_direct_blit: false, + use_gpu: true, + has_metadata: false, + is_action_script_3: true, + use_network_sandbox: false, + }; + let mut buf = Vec::new(); + { + let mut writer = Writer::new( &mut buf, 1 ); + writer.write_tag(&Tag::FileAttributes(file_attributes)).unwrap(); + } + assert_eq!(buf, [0b01_000100, 0b00010001, 0b00101000, 0, 0, 0]); + } + + #[test] + fn write_define_scene_and_frame_label_data() { + let frame_labels_tag = Tag::DefineSceneAndFrameLabelData { + scenes: vec![ + FrameLabel { frame_num: 0, label: "Scene 1".to_string() }, + FrameLabel { frame_num: 25, label: "Scene2Scene2Scene2Scene2Scene2".to_string() }, + FrameLabel { frame_num: 26, label: "test日本語test".to_string() }, + ], + frame_labels: vec![ + FrameLabel { frame_num: 0, label: "a".to_string() }, + FrameLabel { frame_num: 9, label: "b".to_string() }, + FrameLabel { frame_num: 17, label: "❤😁aaa".to_string() }, + FrameLabel { frame_num: 25, label: "frameInScene2".to_string() }, + ], + }; + assert_eq!( + write_tag_to_buf(&frame_labels_tag, 8), + get_file_contents("test/swfs/define_scene_and_frame_label_data.bin") + ); + } + + #[test] + fn write_define_shape() { + unimplemented!() + } + + #[test] + fn write_tag_to_buf_list() { + { + let mut buf = Vec::new(); + { + let mut writer = Writer::new( &mut buf, 1 ); + writer.write_tag_list(&vec![]).unwrap(); + } + assert_eq!(buf, [0, 0]); + } + { + let mut buf = Vec::new(); + { + let mut writer = Writer::new( &mut buf, 1 ); + writer.write_tag_list(&vec![Tag::ShowFrame]).unwrap(); + } + assert_eq!(buf, [0b01_000000, 0b00000000, 0, 0]); + } + { + let mut buf = Vec::new(); + { + let mut writer = Writer::new( &mut buf, 1 ); + writer.write_tag_list(&vec![Tag::Unknown { tag_code: 512, data: vec![0; 100] }, Tag::ShowFrame]).unwrap(); + } + let mut expected = vec![0b00_111111, 0b10000000, 100, 0, 0, 0]; + expected.extend_from_slice(&[0; 100]); + expected.extend_from_slice(&[0b01_000000, 0b00000000, 0, 0]); + assert_eq!(buf, expected); + } + } +} diff --git a/test/swfs/define_scene_and_frame_label_data.bin b/test/swfs/define_scene_and_frame_label_data.bin new file mode 100644 index 000000000..5bb17a5ba Binary files /dev/null and b/test/swfs/define_scene_and_frame_label_data.bin differ diff --git a/test/swfs/define_scene_and_frame_label_data.fla b/test/swfs/define_scene_and_frame_label_data.fla new file mode 100644 index 000000000..bba8f39c4 Binary files /dev/null and b/test/swfs/define_scene_and_frame_label_data.fla differ diff --git a/test/swfs/lzma.fla b/test/swfs/lzma.fla new file mode 100644 index 000000000..158fb29e4 Binary files /dev/null and b/test/swfs/lzma.fla differ diff --git a/test/swfs/lzma.swf b/test/swfs/lzma.swf new file mode 100644 index 000000000..2540baa80 Binary files /dev/null and b/test/swfs/lzma.swf differ diff --git a/test/swfs/square.fla b/test/swfs/square.fla new file mode 100644 index 000000000..1dd8b8ca0 Binary files /dev/null and b/test/swfs/square.fla differ diff --git a/test/swfs/uncompressed.fla b/test/swfs/uncompressed.fla new file mode 100644 index 000000000..137bea917 Binary files /dev/null and b/test/swfs/uncompressed.fla differ diff --git a/test/swfs/uncompressed.swf b/test/swfs/uncompressed.swf new file mode 100644 index 000000000..1923256e0 Binary files /dev/null and b/test/swfs/uncompressed.swf differ diff --git a/test/swfs/zlib.fla b/test/swfs/zlib.fla new file mode 100644 index 000000000..b84055cd6 Binary files /dev/null and b/test/swfs/zlib.fla differ diff --git a/test/swfs/zlib.swf b/test/swfs/zlib.swf new file mode 100644 index 000000000..05acebae5 Binary files /dev/null and b/test/swfs/zlib.swf differ