The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Pin native build dependencies
apoogdk33505ec03d5a
diff --git a/rust/fetch/Cargo.toml b/rust/fetch/Cargo.tomlnew file mode 100644index 00000000..89bb8ed5--- /dev/null+++ b/rust/fetch/Cargo.toml@@ -0,0 +1,10 @@+[package]+name = "fetch"+version = "0.1.0"+edition = "2024"+license = "MIT"+publish = false+description = "Others' sources for a build script: fetched at build time, named by the hash of their files."++[dependencies]+sha2 = "0.11.0"diff --git a/rust/fetch/src/lib.rs b/rust/fetch/src/lib.rsnew file mode 100644index 00000000..8fc957c9--- /dev/null+++ b/rust/fetch/src/lib.rs@@ -0,0 +1,80 @@+//! Others' sources for a build script: the engine's crates hold only manimgx's code, and fetch+//! what they build from others (x264, NASM, FFmpeg, libopus, mitex's Typst package) at build time,+//! each pinned by the hash of its files.++use std::path::{Path, PathBuf};+use std::process::Command;++use sha2::{Digest, Sha256};++/// The tree of files in the archive at `url` (its one top folder, if it has one), unpacked into+/// the build script's OUT_DIR, in a folder named by `hash`: the SHA-256 of its files, each one's+/// path, length and bytes, by path. It names the files, not the archive, which hosts regenerate:+/// any archive of the same files passes, and a tree once checked is found again by its name.+///+/// The archive is kept in the folder MANIMGX_SOURCES names (an absolute path), if it names one:+/// read from there, and downloaded there first unless it is there. So a folder that holds the+/// archives builds offline, and a build into an empty one gathers what it is built from, as a+/// release does for its complete source. A build script fetches the same archives on every+/// target (what it compiles of them may differ), so one build gathers what every build reads.+pub fn tree(url: &str, hash: &str) -> PathBuf {+ println!("cargo:rerun-if-env-changed=MANIMGX_SOURCES");+ let out = PathBuf::from(std::env::var_os("OUT_DIR").expect("a build script's OUT_DIR"));+ let tree = out.join(hash);+ if tree.exists() {+ return tree;+ }+ let folder = std::env::var_os("MANIMGX_SOURCES").map_or(out.clone(), PathBuf::from);+ let archive = folder.join(url.rsplit('/').next().unwrap());+ if !archive.exists() {+ // under another name until it is whole, so a build sharing the folder never reads half+ let part = archive.with_extension(format!("{}.part", std::process::id()));+ std::fs::create_dir_all(&folder).unwrap();+ run(Command::new("curl").args(["-fsSL", "--retry", "3", "-o"]).arg(&part).arg(url));+ std::fs::rename(&part, &archive).unwrap();+ }+ let unpacked = out.join(format!("{hash}.unpacked"));+ let _ = std::fs::remove_dir_all(&unpacked);+ std::fs::create_dir_all(&unpacked).unwrap();+ // the archive named from its own folder: GNU tar reads `C:` in a path as a remote host+ run(Command::new("tar").current_dir(&folder).arg("-xf").arg(archive.file_name().unwrap()).arg("-C").arg(&unpacked));+ let entries: Vec<_> = std::fs::read_dir(&unpacked).unwrap().map(|entry| entry.unwrap().path()).collect();+ let root = match &entries[..] {+ [folder] if folder.is_dir() => folder.clone(),+ _ => unpacked.clone(),+ };+ let found = files_hash(&root);+ assert!(found == hash, "{url}: its files hash to {found}, not {hash}");+ std::fs::rename(&root, &tree).unwrap();+ let _ = std::fs::remove_dir_all(&unpacked);+ tree+}++/// The SHA-256 of a tree's files: each one's path (`/` between its parts), length and bytes, by+/// path.+pub fn files_hash(root: &Path) -> String {+ let mut files = Vec::new();+ let mut folders = vec![PathBuf::new()];+ while let Some(folder) = folders.pop() {+ for entry in std::fs::read_dir(root.join(&folder)).unwrap() {+ let path = folder.join(entry.unwrap().file_name());+ if root.join(&path).is_dir() { folders.push(path) } else { files.push(path) }+ }+ }+ let key = |path: &PathBuf| path.iter().map(|part| part.to_string_lossy()).collect::<Vec<_>>().join("/");+ files.sort_by_cached_key(key);+ let mut sha = Sha256::new();+ for path in &files {+ let bytes = std::fs::read(root.join(path)).unwrap();+ sha.update(key(path).as_bytes());+ sha.update([0]);+ sha.update((bytes.len() as u64).to_le_bytes());+ sha.update(&bytes);+ }+ sha.finalize().iter().map(|byte| format!("{byte:02x}")).collect()+}++fn run(command: &mut Command) {+ let status = command.status().unwrap_or_else(|e| panic!("{command:?}: {e}"));+ assert!(status.success(), "{command:?} failed");+}diff --git a/rust/fetch/tests/folder.rs b/rust/fetch/tests/folder.rsnew file mode 100644index 00000000..cbb1a9d8--- /dev/null+++ b/rust/fetch/tests/folder.rs@@ -0,0 +1,39 @@+//! MANIMGX_SOURCES, a folder of archives: a build into an empty one downloads each archive into+//! it, and a build from a full one reads them there, with nothing to download.++use std::process::Command;++#[test]+fn an_empty_folder_gathers_the_archives_and_a_full_one_builds_offline() {+ let work = std::env::temp_dir().join(format!("fetch-folder-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&work);+ // an archive of a small tree, at a file URL+ let served = work.join("served");+ std::fs::create_dir_all(served.join("tree/sub")).unwrap();+ std::fs::write(served.join("tree/a.txt"), "a").unwrap();+ std::fs::write(served.join("tree/sub/b.txt"), "b").unwrap();+ let tar = Command::new("tar").current_dir(&served).args(["-czf", "tree.tar.gz", "tree"]).status().unwrap();+ assert!(tar.success());+ let hash = fetch::files_hash(&served.join("tree"));+ let path = served.join("tree.tar.gz").display().to_string().replace('\\', "/");+ let url = format!("file:///{}", path.trim_start_matches('/'));+ let sources = work.join("sources");++ // SAFETY: the only test in its binary, so no other thread reads the environment+ unsafe {+ std::env::set_var("OUT_DIR", work.join("first"));+ std::env::set_var("MANIMGX_SOURCES", &sources);+ }+ let tree = fetch::tree(&url, &hash);+ assert_eq!(std::fs::read_to_string(tree.join("sub/b.txt")).unwrap(), "b");+ let gathered: Vec<_> = std::fs::read_dir(&sources).unwrap().map(|entry| entry.unwrap().file_name()).collect();+ assert_eq!(gathered, ["tree.tar.gz"], "the folder holds the archive, whole, and nothing else");++ // the archive no longer at its URL: another build reads it from the folder+ std::fs::remove_file(served.join("tree.tar.gz")).unwrap();+ // SAFETY: as above+ unsafe { std::env::set_var("OUT_DIR", work.join("second")) }+ let tree = fetch::tree(&url, &hash);+ assert_eq!(std::fs::read_to_string(tree.join("a.txt")).unwrap(), "a");+ std::fs::remove_dir_all(&work).unwrap();+}diff --git a/rust/ffmpeg/COPYING.LGPLv2.1 b/rust/ffmpeg/COPYING.LGPLv2.1new file mode 100644index 00000000..40924c2a--- /dev/null+++ b/rust/ffmpeg/COPYING.LGPLv2.1@@ -0,0 +1,502 @@+ GNU LESSER GENERAL PUBLIC LICENSE+ Version 2.1, February 1999++ Copyright (C) 1991, 1999 Free Software Foundation, Inc.+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++[This is the first released version of the Lesser GPL. It also counts+ as the successor of the GNU Library Public License, version 2, hence+ the version number 2.1.]++ Preamble++ The licenses for most software are designed to take away your+freedom to share and change it. By contrast, the GNU General Public+Licenses are intended to guarantee your freedom to share and change+free software--to make sure the software is free for all its users.++ This license, the Lesser General Public License, applies to some+specially designated software packages--typically libraries--of the+Free Software Foundation and other authors who decide to use it. You+can use it too, but we suggest you first think carefully about whether+this license or the ordinary General Public License is the better+strategy to use in any particular case, based on the explanations below.++ When we speak of free software, we are referring to freedom of use,+not price. Our General Public Licenses are designed to make sure that+you have the freedom to distribute copies of free software (and charge+for this service if you wish); that you receive source code or can get+it if you want it; that you can change the software and use pieces of+it in new free programs; and that you are informed that you can do+these things.++ To protect your rights, we need to make restrictions that forbid+distributors to deny you these rights or to ask you to surrender these+rights. These restrictions translate to certain responsibilities for+you if you distribute copies of the library or if you modify it.++ For example, if you distribute copies of the library, whether gratis+or for a fee, you must give the recipients all the rights that we gave+you. You must make sure that they, too, receive or can get the source+code. If you link other code with the library, you must provide+complete object files to the recipients, so that they can relink them+with the library after making changes to the library and recompiling+it. And you must show them these terms so they know their rights.++ We protect your rights with a two-step method: (1) we copyright the+library, and (2) we offer you this license, which gives you legal+permission to copy, distribute and/or modify the library.++ To protect each distributor, we want to make it very clear that+there is no warranty for the free library. Also, if the library is+modified by someone else and passed on, the recipients should know+that what they have is not the original version, so that the original+author's reputation will not be affected by problems that might be+introduced by others.++ Finally, software patents pose a constant threat to the existence of+any free program. We wish to make sure that a company cannot+effectively restrict the users of a free program by obtaining a+restrictive license from a patent holder. Therefore, we insist that+any patent license obtained for a version of the library must be+consistent with the full freedom of use specified in this license.++ Most GNU software, including some libraries, is covered by the+ordinary GNU General Public License. This license, the GNU Lesser+General Public License, applies to certain designated libraries, and+is quite different from the ordinary General Public License. We use+this license for certain libraries in order to permit linking those+libraries into non-free programs.++ When a program is linked with a library, whether statically or using+a shared library, the combination of the two is legally speaking a+combined work, a derivative of the original library. The ordinary+General Public License therefore permits such linking only if the+entire combination fits its criteria of freedom. The Lesser General+Public License permits more lax criteria for linking other code with+the library.++ We call this license the "Lesser" General Public License because it+does Less to protect the user's freedom than the ordinary General+Public License. It also provides other free software developers Less+of an advantage over competing non-free programs. These disadvantages+are the reason we use the ordinary General Public License for many+libraries. However, the Lesser license provides advantages in certain+special circumstances.++ For example, on rare occasions, there may be a special need to+encourage the widest possible use of a certain library, so that it becomes+a de-facto standard. To achieve this, non-free programs must be+allowed to use the library. A more frequent case is that a free+library does the same job as widely used non-free libraries. In this+case, there is little to gain by limiting the free library to free+software only, so we use the Lesser General Public License.++ In other cases, permission to use a particular library in non-free+programs enables a greater number of people to use a large body of+free software. For example, permission to use the GNU C Library in+non-free programs enables many more people to use the whole GNU+operating system, as well as its variant, the GNU/Linux operating+system.++ Although the Lesser General Public License is Less protective of the+users' freedom, it does ensure that the user of a program that is+linked with the Library has the freedom and the wherewithal to run+that program using a modified version of the Library.++ The precise terms and conditions for copying, distribution and+modification follow. Pay close attention to the difference between a+"work based on the library" and a "work that uses the library". The+former contains code derived from the library, whereas the latter must+be combined with the library in order to run.++ GNU LESSER GENERAL PUBLIC LICENSE+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++ 0. This License Agreement applies to any software library or other+program which contains a notice placed by the copyright holder or+other authorized party saying it may be distributed under the terms of+this Lesser General Public License (also called "this License").+Each licensee is addressed as "you".++ A "library" means a collection of software functions and/or data+prepared so as to be conveniently linked with application programs+(which use some of those functions and data) to form executables.++ The "Library", below, refers to any such software library or work+which has been distributed under these terms. A "work based on the+Library" means either the Library or any derivative work under+copyright law: that is to say, a work containing the Library or a+portion of it, either verbatim or with modifications and/or translated+straightforwardly into another language. (Hereinafter, translation is+included without limitation in the term "modification".)++ "Source code" for a work means the preferred form of the work for+making modifications to it. For a library, complete source code means+all the source code for all modules it contains, plus any associated+interface definition files, plus the scripts used to control compilation+and installation of the library.++ Activities other than copying, distribution and modification are not+covered by this License; they are outside its scope. The act of+running a program using the Library is not restricted, and output from+such a program is covered only if its contents constitute a work based+on the Library (independent of the use of the Library in a tool for+writing it). Whether that is true depends on what the Library does+and what the program that uses the Library does.++ 1. You may copy and distribute verbatim copies of the Library's+complete source code as you receive it, in any medium, provided that+you conspicuously and appropriately publish on each copy an+appropriate copyright notice and disclaimer of warranty; keep intact+all the notices that refer to this License and to the absence of any+warranty; and distribute a copy of this License along with the+Library.++ You may charge a fee for the physical act of transferring a copy,+and you may at your option offer warranty protection in exchange for a+fee.++ 2. You may modify your copy or copies of the Library or any portion+of it, thus forming a work based on the Library, and copy and+distribute such modifications or work under the terms of Section 1+above, provided that you also meet all of these conditions:++ a) The modified work must itself be a software library.++ b) You must cause the files modified to carry prominent notices+ stating that you changed the files and the date of any change.++ c) You must cause the whole of the work to be licensed at no+ charge to all third parties under the terms of this License.++ d) If a facility in the modified Library refers to a function or a+ table of data to be supplied by an application program that uses+ the facility, other than as an argument passed when the facility+ is invoked, then you must make a good faith effort to ensure that,+ in the event an application does not supply such function or+ table, the facility still operates, and performs whatever part of+ its purpose remains meaningful.++ (For example, a function in a library to compute square roots has+ a purpose that is entirely well-defined independent of the+ application. Therefore, Subsection 2d requires that any+ application-supplied function or table used by this function must+ be optional: if the application does not supply it, the square+ root function must still compute square roots.)++These requirements apply to the modified work as a whole. If+identifiable sections of that work are not derived from the Library,+and can be reasonably considered independent and separate works in+themselves, then this License, and its terms, do not apply to those+sections when you distribute them as separate works. But when you+distribute the same sections as part of a whole which is a work based+on the Library, the distribution of the whole must be on the terms of+this License, whose permissions for other licensees extend to the+entire whole, and thus to each and every part regardless of who wrote+it.++Thus, it is not the intent of this section to claim rights or contest+your rights to work written entirely by you; rather, the intent is to+exercise the right to control the distribution of derivative or+collective works based on the Library.++In addition, mere aggregation of another work not based on the Library+with the Library (or with a work based on the Library) on a volume of+a storage or distribution medium does not bring the other work under+the scope of this License.++ 3. You may opt to apply the terms of the ordinary GNU General Public+License instead of this License to a given copy of the Library. To do+this, you must alter all the notices that refer to this License, so+that they refer to the ordinary GNU General Public License, version 2,+instead of to this License. (If a newer version than version 2 of the+ordinary GNU General Public License has appeared, then you can specify+that version instead if you wish.) Do not make any other change in+these notices.++ Once this change is made in a given copy, it is irreversible for+that copy, so the ordinary GNU General Public License applies to all+subsequent copies and derivative works made from that copy.++ This option is useful when you wish to copy part of the code of+the Library into a program that is not a library.++ 4. You may copy and distribute the Library (or a portion or+derivative of it, under Section 2) in object code or executable form+under the terms of Sections 1 and 2 above provided that you accompany+it with the complete corresponding machine-readable source code, which+must be distributed under the terms of Sections 1 and 2 above on a+medium customarily used for software interchange.++ If distribution of object code is made by offering access to copy+from a designated place, then offering equivalent access to copy the+source code from the same place satisfies the requirement to+distribute the source code, even though third parties are not+compelled to copy the source along with the object code.++ 5. A program that contains no derivative of any portion of the+Library, but is designed to work with the Library by being compiled or+linked with it, is called a "work that uses the Library". Such a+work, in isolation, is not a derivative work of the Library, and+therefore falls outside the scope of this License.++ However, linking a "work that uses the Library" with the Library+creates an executable that is a derivative of the Library (because it+contains portions of the Library), rather than a "work that uses the+library". The executable is therefore covered by this License.+Section 6 states terms for distribution of such executables.++ When a "work that uses the Library" uses material from a header file+that is part of the Library, the object code for the work may be a+derivative work of the Library even though the source code is not.+Whether this is true is especially significant if the work can be+linked without the Library, or if the work is itself a library. The+threshold for this to be true is not precisely defined by law.++ If such an object file uses only numerical parameters, data+structure layouts and accessors, and small macros and small inline+functions (ten lines or less in length), then the use of the object+file is unrestricted, regardless of whether it is legally a derivative+work. (Executables containing this object code plus portions of the+Library will still fall under Section 6.)++ Otherwise, if the work is a derivative of the Library, you may+distribute the object code for the work under the terms of Section 6.+Any executables containing that work also fall under Section 6,+whether or not they are linked directly with the Library itself.++ 6. As an exception to the Sections above, you may also combine or+link a "work that uses the Library" with the Library to produce a+work containing portions of the Library, and distribute that work+under terms of your choice, provided that the terms permit+modification of the work for the customer's own use and reverse+engineering for debugging such modifications.++ You must give prominent notice with each copy of the work that the+Library is used in it and that the Library and its use are covered by+this License. You must supply a copy of this License. If the work+during execution displays copyright notices, you must include the+copyright notice for the Library among them, as well as a reference+directing the user to the copy of this License. Also, you must do one+of these things:++ a) Accompany the work with the complete corresponding+ machine-readable source code for the Library including whatever+ changes were used in the work (which must be distributed under+ Sections 1 and 2 above); and, if the work is an executable linked+ with the Library, with the complete machine-readable "work that+ uses the Library", as object code and/or source code, so that the+ user can modify the Library and then relink to produce a modified+ executable containing the modified Library. (It is understood+ that the user who changes the contents of definitions files in the+ Library will not necessarily be able to recompile the application+ to use the modified definitions.)++ b) Use a suitable shared library mechanism for linking with the+ Library. A suitable mechanism is one that (1) uses at run time a+ copy of the library already present on the user's computer system,+ rather than copying library functions into the executable, and (2)+ will operate properly with a modified version of the library, if+ the user installs one, as long as the modified version is+ interface-compatible with the version that the work was made with.++ c) Accompany the work with a written offer, valid for at+ least three years, to give the same user the materials+ specified in Subsection 6a, above, for a charge no more+ than the cost of performing this distribution.++ d) If distribution of the work is made by offering access to copy+ from a designated place, offer equivalent access to copy the above+ specified materials from the same place.++ e) Verify that the user has already received a copy of these+ materials or that you have already sent this user a copy.++ For an executable, the required form of the "work that uses the+Library" must include any data and utility programs needed for+reproducing the executable from it. However, as a special exception,+the materials to be distributed need not include anything that is+normally distributed (in either source or binary form) with the major+components (compiler, kernel, and so on) of the operating system on+which the executable runs, unless that component itself accompanies+the executable.++ It may happen that this requirement contradicts the license+restrictions of other proprietary libraries that do not normally+accompany the operating system. Such a contradiction means you cannot+use both them and the Library together in an executable that you+distribute.++ 7. You may place library facilities that are a work based on the+Library side-by-side in a single library together with other library+facilities not covered by this License, and distribute such a combined+library, provided that the separate distribution of the work based on+the Library and of the other library facilities is otherwise+permitted, and provided that you do these two things:++ a) Accompany the combined library with a copy of the same work+ based on the Library, uncombined with any other library+ facilities. This must be distributed under the terms of the+ Sections above.++ b) Give prominent notice with the combined library of the fact+ that part of it is a work based on the Library, and explaining+ where to find the accompanying uncombined form of the same work.++ 8. You may not copy, modify, sublicense, link with, or distribute+the Library except as expressly provided under this License. Any+attempt otherwise to copy, modify, sublicense, link with, or+distribute the Library is void, and will automatically terminate your+rights under this License. However, parties who have received copies,+or rights, from you under this License will not have their licenses+terminated so long as such parties remain in full compliance.++ 9. You are not required to accept this License, since you have not+signed it. However, nothing else grants you permission to modify or+distribute the Library or its derivative works. These actions are+prohibited by law if you do not accept this License. Therefore, by+modifying or distributing the Library (or any work based on the+Library), you indicate your acceptance of this License to do so, and+all its terms and conditions for copying, distributing or modifying+the Library or works based on it.++ 10. Each time you redistribute the Library (or any work based on the+Library), the recipient automatically receives a license from the+original licensor to copy, distribute, link with or modify the Library+subject to these terms and conditions. You may not impose any further+restrictions on the recipients' exercise of the rights granted herein.+You are not responsible for enforcing compliance by third parties with+this License.++ 11. If, as a consequence of a court judgment or allegation of patent+infringement or for any other reason (not limited to patent issues),+conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot+distribute so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you+may not distribute the Library at all. For example, if a patent+license would not permit royalty-free redistribution of the Library by+all those who receive copies directly or indirectly through you, then+the only way you could satisfy both it and this License would be to+refrain entirely from distribution of the Library.++If any portion of this section is held invalid or unenforceable under any+particular circumstance, the balance of the section is intended to apply,+and the section as a whole is intended to apply in other circumstances.++It is not the purpose of this section to induce you to infringe any+patents or other property right claims or to contest validity of any+such claims; this section has the sole purpose of protecting the+integrity of the free software distribution system which is+implemented by public license practices. Many people have made+generous contributions to the wide range of software distributed+through that system in reliance on consistent application of that+system; it is up to the author/donor to decide if he or she is willing+to distribute software through any other system and a licensee cannot+impose that choice.++This section is intended to make thoroughly clear what is believed to+be a consequence of the rest of this License.++ 12. If the distribution and/or use of the Library is restricted in+certain countries either by patents or by copyrighted interfaces, the+original copyright holder who places the Library under this License may add+an explicit geographical distribution limitation excluding those countries,+so that distribution is permitted only in or among countries not thus+excluded. In such case, this License incorporates the limitation as if+written in the body of this License.++ 13. The Free Software Foundation may publish revised and/or new+versions of the Lesser 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 Library+specifies a version number of this License which applies to it and+"any later version", you have the option of following the terms and+conditions either of that version or of any later version published by+the Free Software Foundation. If the Library does not specify a+license version number, you may choose any version ever published by+the Free Software Foundation.++ 14. If you wish to incorporate parts of the Library into other free+programs whose distribution conditions are incompatible with these,+write to the author to ask for permission. For software which is+copyrighted by the Free Software Foundation, write to the Free+Software Foundation; we sometimes make exceptions for this. Our+decision will be guided by the two goals of preserving the free status+of all derivatives of our free software and of promoting the sharing+and reuse of software generally.++ NO WARRANTY++ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR+OTHER PARTIES PROVIDE THE LIBRARY "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+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY+AND/OR REDISTRIBUTE THE LIBRARY 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+LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH+DAMAGES.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Libraries++ If you develop a new library, and you want it to be of the greatest+possible use to the public, we recommend making it free software that+everyone can redistribute and change. You can do so by permitting+redistribution under these terms (or, alternatively, under the terms of the+ordinary General Public License).++ To apply these terms, attach the following notices to the library. It is+safest to attach them to the start of each source file to most effectively+convey the exclusion of warranty; and each file should have at least the+"copyright" line and a pointer to where the full notice is found.++ <one line to give the library's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This library is free software; you can redistribute it and/or+ modify it under the terms of the GNU Lesser General Public+ License as published by the Free Software Foundation; either+ version 2.1 of the License, or (at your option) any later version.++ This library 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+ Lesser General Public License for more details.++ You should have received a copy of the GNU Lesser General Public+ License along with this library; if not, write to the Free Software+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA++Also add information on how to contact you by electronic and paper mail.++You should also get your employer (if you work as a programmer) or your+school, if any, to sign a "copyright disclaimer" for the library, if+necessary. Here is a sample; alter the names:++ Yoyodyne, Inc., hereby disclaims all copyright interest in the+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.++ <signature of Ty Coon>, 1 April 1990+ Ty Coon, President of Vice++That's all there is to it!diff --git a/rust/ffmpeg/COPYING.libopus b/rust/ffmpeg/COPYING.libopusnew file mode 100644index 00000000..75711467--- /dev/null+++ b/rust/ffmpeg/COPYING.libopus@@ -0,0 +1,44 @@+Copyright 2001-2023 Xiph.Org, Skype Limited, Octasic,+ Jean-Marc Valin, Timothy B. Terriberry,+ CSIRO, Gregory Maxwell, Mark Borgerding,+ Erik de Castro Lopo, Mozilla, Amazon++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions+are met:++- Redistributions of source code must retain the above copyright+notice, this list of conditions and the following disclaimer.++- Redistributions in binary form must reproduce the above copyright+notice, this list of conditions and the following disclaimer in the+documentation and/or other materials provided with the distribution.++- Neither the name of Internet Society, IETF or IETF Trust, nor the+names of specific contributors, may be used to endorse or promote+products derived from this software without specific prior written+permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER+OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++Opus is subject to the royalty-free patent licenses which are+specified at:++Xiph.Org Foundation:+https://datatracker.ietf.org/ipr/1524/++Microsoft Corporation:+https://datatracker.ietf.org/ipr/1914/++Broadcom Corporation:+https://datatracker.ietf.org/ipr/1526/diff --git a/rust/ffmpeg/Cargo.toml b/rust/ffmpeg/Cargo.tomlnew file mode 100644index 00000000..3e1224c2--- /dev/null+++ b/rust/ffmpeg/Cargo.toml@@ -0,0 +1,12 @@+[package]+name = "ffmpeg"+version = "9.0.2"+edition = "2024"+license = "MIT AND LGPL-2.1-or-later AND BSD-3-Clause"+publish = false+description = "FFmpeg 9.0.2's audio decoders (libopus 1.6.1's for Opus), fetched and built from their sources, behind one safe call."+links = "ffmpeg"++[build-dependencies]+cc = { version = "1.5.1", features = ["parallel"] }+fetch = { path = "../fetch" }diff --git a/rust/ffmpeg/build.rs b/rust/ffmpeg/build.rsnew file mode 100644index 00000000..91c897c8--- /dev/null+++ b/rust/ffmpeg/build.rs@@ -0,0 +1,209 @@+//! FFmpeg 9.0.2's audio decoders, and libopus 1.6.1 for Opus, from their sources (fetched), with+//! nothing installed: no configure, no make. What FFmpeg's configure resolves for the components+//! manimgx decodes with is the lock below (`ON`, the names it turns on; `SOURCES`, the files it+//! compiles), made once by+//!+//! ```text+//! configure --arch=c --target-os=none --enable-cross-compile --disable-asm --disable-inline-asm+//! --disable-pthreads --disable-network --disable-autodetect --disable-everything+//! --disable-programs --disable-doc --disable-avdevice --disable-avfilter --disable-swscale+//! --disable-faan --enable-swresample --enable-libopus --enable-decoder=aac,mp3float,mp2float,+//! mp1float,libopus,vorbis,flac,alac,pcm_u8,pcm_s8,pcm_s16le,pcm_s16be,pcm_s24le,pcm_s24be,+//! pcm_s32le,pcm_s32be,pcm_f32le,pcm_f32be,pcm_f64le,pcm_f64be,pcm_alaw,pcm_mulaw,+//! adpcm_ima_wav,adpcm_ms --enable-demuxer=mov,mp3,ogg,matroska,wav,w64,aiff,caf,flac,aac+//! --enable-parser=aac,mpegaudio,vorbis,opus,flac+//! ```+//!+//! (its config.h's and config_components.h's names set to 1, but the documentation's and tests';+//! `make -n`'s objects). In portable C, it is the same on every target, the browser's included.+//! The configuration is written from the lock: 1 for its names and for what every C99 library+//! has, 0 for every other name FFmpeg's sources test, and each component FFmpeg declares on or+//! off. libopus's files are read from its own lists. The build has no threads: the crate calls+//! FFmpeg one call at a time.++use std::collections::BTreeSet;+use std::path::Path;++/// The names configure turns on.+const ON: &str = "libopus safe_bitstream_reader avformat avcodec swresample avutil iamf decoders parsers demuxers+ adts_header dirac_parse golomb iamfdec iso_media mpegaudio mpegaudiodsp mpegaudioheader mpeg4audio riffdec+ sinewin aac_decoder alac_decoder flac_decoder mp1float_decoder mp2float_decoder mp3float_decoder vorbis_decoder+ pcm_alaw_decoder pcm_f32be_decoder pcm_f32le_decoder pcm_f64be_decoder pcm_f64le_decoder pcm_mulaw_decoder+ pcm_s8_decoder pcm_s16be_decoder pcm_s16le_decoder pcm_s24be_decoder pcm_s24le_decoder pcm_s32be_decoder+ pcm_s32le_decoder pcm_u8_decoder adpcm_ima_wav_decoder adpcm_ms_decoder libopus_decoder aac_parser flac_parser+ mpegaudio_parser opus_parser vorbis_parser aac_demuxer aiff_demuxer caf_demuxer flac_demuxer matroska_demuxer+ mov_demuxer mp3_demuxer ogg_demuxer w64_demuxer wav_demuxer";++/// The files configure compiles, by library.+const SOURCES: [(&str, &str); 4] = [+ (+ "libavutil",+ "adler32 aes aes_ctr ambient_viewing_environment audio_fifo avsscanf avstring base64 blowfish bprint buffer+ camellia cast5 channel_layout container_fifo cpu crc csp des detection_bbox dict display dovi_meta+ downmix_info encryption_info error eval executor fifo file file_open film_grain_params fixed_dsp float_dsp+ float_scalarproduct frame hash hdr_dynamic_metadata hdr_dynamic_vivid_metadata hmac hwcontext hwcontext_stub+ iamf imgutils integer intmath lfg lls log log2_tab lzo mastering_display_metadata mathematics md5 mem+ murmur3 opt parseutils pixdesc pixelutils random_seed rational raw_color_params rc4 refstruct reverse+ ripemd samplefmt sha sha512 side_data slicethread spherical stereo3d tdrdi tea threadmessage time timecode+ timecode_internal timestamp tree twofish tx tx_double tx_float tx_int32 utils uuid version+ video_enc_params video_hint xga_font_data xtea",+ ),+ (+ "libavcodec",+ "aac/aacdec aac/aacdec_ac aac/aacdec_float aac/aacdec_lpd aac/aacdec_tab aac/aacdec_usac+ aac/aacdec_usac_mps212 aac_ac3_parser aac_parser aacps_common aacps_float aacpsdsp_float aacsbr aactab+ ac3_channel_layout_tab ac3_parser adpcm adpcm_data adts_header adts_parser alac alac_data alacdsp allcodecs+ avcodec avdct bitstream bitstream_filters bsf cbrt_data cbrt_tablegen_common codec_desc codec_par d3d11va+ dct32_fixed dct32_float decode dirac dv_profile encode exif flac flac_parser flacdata flacdec flacdsp+ get_buffer golomb h2645_parse imgconvert jni kbdwin lcevctab libopus libopusdec mathtables mediacodec+ mpeg12framerate mpeg4audio mpeg4audio_sample_rates mpegaudio mpegaudio_parser mpegaudiodata+ mpegaudiodec_common mpegaudiodec_float mpegaudiodecheader mpegaudiodsp mpegaudiodsp_data mpegaudiodsp_fixed+ mpegaudiodsp_float mpegaudiotabs options opus/frame_duration_tab opus/parse opus/parser packet parser+ parsers pcm profiles qsv_api raw sbrdsp sinewin threadprogress tiff_common to_upper4 utils version vlc+ vorbis vorbis_data vorbis_parser vorbisdec vorbisdsp xiph",+ ),+ (+ "libavformat",+ "aacdec aiff aiffdec allformats apetag av1 avformat avio aviobuf caf cafdec codecstring demux demux_utils+ dovi_isom dump dv dvdclut flac_picture flacdec format iamf iamf_parse iamf_reader id3v1 id3v2 img2 isom+ isom_tags lcevc matroska matroskadec metadata mov mov_chan mov_esds mp3dec mux mux_utils nal oggdec+ oggparsedirac oggparseflac oggparseogm oggparseopus oggparseskeleton oggparsespeex oggparsetheora+ oggparsevorbis oggparsevp8 options os_support packet_list pcm protocols qtpalette rawdec replaygain riff+ riffdec rmsipr sdp seek url urldecode utils version vorbiscomment vpcc w64 wavdec",+ ),+ ("libswresample", "audioconvert dither options rematrix resample resample_dsp swresample swresample_frame version"),+];++/// What every C99 library has (FFmpeg defines replacements for the rest, which clash with these).+const C99: &str = "atanf atan2f cbrt cbrtf copysign cosf erf exp2 exp2f expf hypot isfinite isinf isnan ldexpf+ llrint llrintf log2 log2f log10f lrint lrintf powf rint round roundf sinf trunc truncf";++fn main() {+ println!("cargo:rerun-if-changed=build.rs");+ println!("cargo:rerun-if-changed=src/shim.c");+ let ffmpeg = &fetch::tree("https://ffmpeg.org/releases/ffmpeg-9.0.2.tar.gz", "c92e6bbcf8183b80ab4771d4fc07dee2d97dd2af0a72f8a6bf13c4242c756ff0");+ let opus = &fetch::tree(+ "https://downloads.xiph.org/releases/opus/opus-1.6.1.tar.gz",+ "8a88c521e03839005b87575f322c7347f82d77f666f025643a30f495906de8ca",+ );+ let out = &std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap());+ let target = |key: &str| std::env::var(format!("CARGO_CFG_TARGET_{key}")).unwrap_or_default();+ let msvc = target("ENV") == "msvc";+ let mut on: BTreeSet<String> = ON.split_whitespace().map(|name| format!("CONFIG_{}", name.to_uppercase())).collect();+ on.extend(C99.split_whitespace().map(|name| format!("HAVE_{}", name.to_uppercase())));+ // read() and close(), for av_file_map, from the header each system has them in+ on.insert(if target("OS") == "windows" { "HAVE_IO_H" } else { "HAVE_UNISTD_H" }.into());+ if target("POINTER_WIDTH") == "64" {+ on.insert("HAVE_FAST_64BIT".into());+ }++ // config.h: the names FFmpeg's sources test, 1 or 0 (but those they define themselves)+ let (mut tested, mut defined) = (BTreeSet::new(), BTreeSet::new());+ for dir in ["libavutil", "libavcodec", "libavformat", "libswresample", "compat"] {+ scan(&ffmpeg.join(dir), &mut tested, &mut defined);+ }+ let mut config = String::from("#ifndef FFMPEG_CONFIG_H\n#define FFMPEG_CONFIG_H\n#define FFMPEG_CONFIGURATION \"manimgx\"\n");+ config += "#define FFMPEG_LICENSE \"LGPL version 2.1 or later\"\n";+ for name in tested.difference(&defined).chain(&on).collect::<BTreeSet<_>>() {+ config += &format!("#define {name} {}\n", on.contains(name) as u8);+ }+ write(&out.join("config.h"), config + "#endif\n");+ write(&out.join("libavutil/avconfig.h"), "#define AV_HAVE_BIGENDIAN 0\n#define AV_HAVE_FAST_UNALIGNED 0\n".into());+ write(&out.join("libavutil/ffversion.h"), "#define FFMPEG_VERSION \"9.0.2\"\n".into());+ // each component FFmpeg declares, on or off (its sources paste some of those names together,+ // which no scan sees), and the lists of those on, in the order they are declared+ let mut components = String::new();+ for (list, kind, array, file) in [+ ("libavcodec/codec_list.c", "FFCodec", "codec_list", "libavcodec/allcodecs.c"),+ ("libavcodec/parser_list.c", "FFCodecParser", "parser_list", "libavcodec/parsers.c"),+ ("libavcodec/bsf_list.c", "FFBitStreamFilter", "bitstream_filters", "libavcodec/bitstream_filters.c"),+ ("libavformat/demuxer_list.c", "FFInputFormat", "demuxer_list", "libavformat/allformats.c"),+ ("libavformat/muxer_list.c", "FFOutputFormat", "muxer_list", "libavformat/allformats.c"),+ ("libavformat/protocol_list.c", "URLProtocol", "url_protocols", "libavformat/protocols.c"),+ ] {+ let text = std::fs::read_to_string(ffmpeg.join(file)).unwrap();+ let names: Vec<&str> = text+ .lines()+ .filter_map(|line| match line.split_whitespace().collect::<Vec<_>>()[..] {+ ["extern", "const", k, name] if k == kind => name.strip_prefix("ff_")?.strip_suffix(';'),+ _ => None,+ })+ .collect();+ let switch = |name: &str| format!("CONFIG_{}", name.to_uppercase());+ components += &names.iter().map(|name| format!("#define {} {}\n", switch(name), on.contains(&switch(name)) as u8)).collect::<String>();+ let entries: String = names.iter().filter(|name| on.contains(&switch(name))).map(|name| format!(" &ff_{name},\n")).collect();+ write(&out.join(list), format!("static const {kind} * const {array}[] = {{\n{entries} NULL }};\n"));+ }+ write(&out.join("config_components.h"), components);++ let build = || {+ let mut build = cc::Build::new();+ build.warnings(false).opt_level(3).std("c17"); // FFmpeg counts on dead code being removed+ if msvc {+ build.define("_USE_MATH_DEFINES", None).define("_CRT_SECURE_NO_WARNINGS", None).define("_CRT_NONSTDC_NO_WARNINGS", None);+ } else {+ build.flag("-w").flag("-fno-math-errno").flag("-fno-signed-zeros");+ }+ build+ };+ // libopus, its float build: the files its lists name+ let mut libopus = build();+ libopus.includes(["include", "celt", "silk", "silk/float"].map(|dir| opus.join(dir)));+ for define in ["OPUS_BUILD", "USE_ALLOCA", "HAVE_LRINT", "HAVE_LRINTF", "ENABLE_HARDENING"] {+ libopus.define(define, None);+ }+ for (list, names) in [("celt_sources.mk", "CELT_SOURCES"), ("silk_sources.mk", "SILK_SOURCES SILK_SOURCES_FLOAT"), ("opus_sources.mk", "OPUS_SOURCES OPUS_SOURCES_FLOAT")] {+ // but silk/debug.c, empty without SILK_DEBUG (an object with no symbols, which ranlib warns of)+ libopus.files(make_list(&opus.join(list), names).iter().filter(|file| *file != "silk/debug.c").map(|file| opus.join(file)));+ }+ let mut objects = libopus.compile_intermediates();+ // FFmpeg's files, and the shim+ let mut libav = build();+ libav.include(out).include(ffmpeg).include(ffmpeg.join("compat/stdbit")).include(opus.join("include"));+ libav.define("HAVE_AV_CONFIG_H", None).define("_ISOC11_SOURCE", None).define("_FILE_OFFSET_BITS", "64").define("_LARGEFILE_SOURCE", None);+ if msvc {+ libav.include(ffmpeg.join("compat/atomics/win32")); // FFmpeg's <stdatomic.h> for MSVC+ }+ for (library, names) in SOURCES {+ libav.files(names.split_whitespace().map(|name| ffmpeg.join(format!("{library}/{name}.c"))));+ }+ objects.extend(libav.file("src/shim.c").compile_intermediates());+ cc::Build::new().objects(objects).compile("ffmpeg");+}++/// The names in C sources that FFmpeg's configuration sets (HAVE_, CONFIG_, ARCH_): those they+/// test, and those they #define themselves.+fn scan(dir: &Path, tested: &mut BTreeSet<String>, defined: &mut BTreeSet<String>) {+ for entry in std::fs::read_dir(dir).unwrap() {+ let path = entry.unwrap().path();+ if path.is_dir() {+ scan(&path, tested, defined);+ } else if path.extension().is_some_and(|ext| ext == "c" || ext == "h") {+ let text = String::from_utf8_lossy(&std::fs::read(&path).unwrap()).into_owned();+ let mut previous = "";+ for word in text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '#')).filter(|w| !w.is_empty()) {+ let configured = ["HAVE_", "CONFIG_", "ARCH_"].iter().any(|p| word.len() > p.len() && word.starts_with(p))+ && word.bytes().all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_');+ if configured {+ if previous == "#define" || previous == "define" { defined.insert(word.to_owned()) } else { tested.insert(word.to_owned()) };+ }+ previous = word;+ }+ }+ }+}++/// The files a makefile's variables list (`NAME = a.c b.c \` and the lines it continues on).+fn make_list(file: &Path, names: &str) -> Vec<String> {+ let text = std::fs::read_to_string(file).unwrap().replace("\\\n", " ");+ text.lines()+ .filter_map(|line| line.split_once('='))+ .filter(|(name, _)| names.split_whitespace().any(|n| n == name.trim()))+ .flat_map(|(_, files)| files.split_whitespace().map(str::to_owned).collect::<Vec<_>>())+ .collect()+}++fn write(path: &Path, text: String) {+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(path, text).unwrap();+}diff --git a/rust/ffmpeg/src/lib.rs b/rust/ffmpeg/src/lib.rsnew file mode 100644index 00000000..7e379f75--- /dev/null+++ b/rust/ffmpeg/src/lib.rs@@ -0,0 +1,41 @@+//! FFmpeg's audio decoders (libopus's for Opus), built from their sources (see build.rs) and used+//! through a C shim (src/shim.c): a file's bytes in, its sound out.++use std::ffi::{CStr, c_char, c_int, c_void};+use std::sync::Mutex;++unsafe extern "C" {+ fn manimgx_decode(+ data: *const u8,+ size: usize,+ samples: *mut *mut f32,+ frames: *mut usize,+ rate: *mut c_int,+ channels: *mut c_int,+ error: *mut c_char,+ error_size: usize,+ ) -> c_int;+ fn manimgx_free(pointer: *mut c_void);+}++/// FFmpeg is built without threads: it decodes one file at a time.+static ONE_AT_A_TIME: Mutex<()> = Mutex::new(());++/// A file's sound (any container and codec FFmpeg is built with here): interleaved float samples,+/// their rate, and how many channels (1 or 2: wider sound is downmixed to stereo). It starts and+/// ends where the file declares (an MP4's edit list, the encoder's delay and padding).+pub fn decode(file: &[u8]) -> Result<(Vec<f32>, u32, usize), String> {+ let _lock = ONE_AT_A_TIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner());+ let (mut samples, mut frames, mut rate, mut channels) = (std::ptr::null_mut(), 0, 0, 0);+ let mut error = [0 as c_char; 256];+ let status = unsafe {+ manimgx_decode(file.as_ptr(), file.len(), &mut samples, &mut frames, &mut rate, &mut channels, error.as_mut_ptr(), error.len())+ };+ if status < 0 {+ return Err(unsafe { CStr::from_ptr(error.as_ptr()) }.to_string_lossy().into_owned());+ }+ // SAFETY: the shim filled `samples` with `frames` frames of `channels`, which it allocated+ let pcm = unsafe { std::slice::from_raw_parts(samples, frames * channels as usize) }.to_vec();+ unsafe { manimgx_free(samples.cast()) };+ Ok((pcm, rate as u32, channels as usize))+}diff --git a/rust/ffmpeg/src/shim.c b/rust/ffmpeg/src/shim.cnew file mode 100644index 00000000..52028fb6--- /dev/null+++ b/rust/ffmpeg/src/shim.c@@ -0,0 +1,161 @@+// A file's sound through FFmpeg: decoded from memory into interleaved float samples at the+// stream's rate, at most two channels (wider sound downmixed to stereo by swresample, scaled so+// it can't clip). libavformat and libavcodec trim what the file declares: an MP4's edit list,+// the encoder's delay and padding.++#include <stdio.h>++#include <libavcodec/avcodec.h>+#include <libavformat/avformat.h>+#include <libavutil/mem.h>+#include <libavutil/opt.h>+#include <libswresample/swresample.h>++struct memory {+ const uint8_t *data;+ int64_t size, at;+};++static int read_memory(void *opaque, uint8_t *buffer, int size) {+ struct memory *m = opaque;+ int64_t n = FFMIN(size, m->size - m->at);+ if (n <= 0)+ return AVERROR_EOF;+ memcpy(buffer, m->data + m->at, n);+ m->at += n;+ return (int)n;+}++static int64_t seek_memory(void *opaque, int64_t offset, int whence) {+ struct memory *m = opaque;+ if (whence & AVSEEK_SIZE)+ return m->size;+ whence &= ~AVSEEK_FORCE;+ int64_t at = whence == SEEK_CUR ? m->at + offset : whence == SEEK_END ? m->size + offset : offset;+ if (at < 0 || at > m->size)+ return AVERROR(EINVAL);+ return m->at = at;+}++// Appends a frame's samples (NULL: what the converter still holds), as interleaved float of+// `channels` channels at `rate`, to *samples (*frames so far, room for *capacity floats).+static int append(SwrContext *swr, AVFrame *in, int channels, int rate, float **samples, size_t *frames, size_t *capacity) {+ if (in && in->ch_layout.order == AV_CHANNEL_ORDER_UNSPEC) { // PCM without a channel mask+ int n = in->ch_layout.nb_channels;+ av_channel_layout_uninit(&in->ch_layout);+ av_channel_layout_default(&in->ch_layout, n);+ }+ AVFrame *out = av_frame_alloc();+ if (!out)+ return AVERROR(ENOMEM);+ av_channel_layout_default(&out->ch_layout, channels);+ out->format = AV_SAMPLE_FMT_FLT;+ out->sample_rate = rate;+ int ret = swr_convert_frame(swr, out, in);+ if (ret == AVERROR_INPUT_CHANGED && (ret = swr_config_frame(swr, out, in)) >= 0 && (ret = swr_init(swr)) >= 0)+ ret = swr_convert_frame(swr, out, in); // the stream changed its layout or rate+ size_t need = (*frames + out->nb_samples) * channels;+ if (ret >= 0 && need > *capacity) {+ float *grown = av_realloc(*samples, FFMAX(need, *capacity * 2) * sizeof(float));+ if (grown)+ *samples = grown, *capacity = FFMAX(need, *capacity * 2);+ else+ ret = AVERROR(ENOMEM);+ }+ if (ret >= 0 && out->nb_samples) {+ memcpy(*samples + *frames * channels, out->data[0], out->nb_samples * channels * sizeof(float));+ *frames += out->nb_samples;+ }+ av_frame_free(&out);+ return ret;+}++// The sound of the file in data[0..size): *samples (av_malloc'd: manimgx_free), *frames of+// *channels at *rate. 0, or a negative AVERROR, with what went wrong in error[].+int manimgx_decode(const uint8_t *data, size_t size, float **samples, size_t *frames, int *rate, int *channels, char *error, size_t error_size) {+ struct memory m = {data, (int64_t)size, 0};+ AVFormatContext *format = avformat_alloc_context();+ AVIOContext *io = NULL;+ AVCodecContext *decoder = NULL;+ SwrContext *swr = swr_alloc();+ AVPacket *packet = av_packet_alloc();+ AVFrame *frame = av_frame_alloc();+ uint8_t *buffer = av_malloc(1 << 16);+ size_t capacity = 0;+ int ret, stream;+ *samples = NULL, *frames = 0, *error = 0;+ av_log_set_level(AV_LOG_QUIET);+ if (!format || !swr || !packet || !frame || !buffer || !(io = avio_alloc_context(buffer, 1 << 16, 0, &m, read_memory, NULL, seek_memory))) {+ ret = AVERROR(ENOMEM);+ goto end;+ }+ buffer = NULL; // the context's now+ format->pb = io;+ if ((ret = avformat_open_input(&format, NULL, NULL, NULL)) < 0 || (ret = avformat_find_stream_info(format, NULL)) < 0)+ goto end;+ if ((ret = stream = av_find_best_stream(format, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0)) < 0)+ goto end;+ const AVCodecParameters *parameters = format->streams[stream]->codecpar;+ const AVCodec *codec = avcodec_find_decoder(parameters->codec_id);+ if (!codec) {+ snprintf(error, error_size, "its sound is %s, which manimgx doesn't decode", avcodec_get_name(parameters->codec_id));+ ret = AVERROR_DECODER_NOT_FOUND;+ goto end;+ }+ if (!(decoder = avcodec_alloc_context3(codec))) {+ ret = AVERROR(ENOMEM);+ goto end;+ }+ if ((ret = avcodec_parameters_to_context(decoder, parameters)) < 0)+ goto end;+ decoder->pkt_timebase = format->streams[stream]->time_base;+ if ((ret = avcodec_open2(decoder, codec, NULL)) < 0)+ goto end;+ *rate = decoder->sample_rate;+ *channels = FFMIN(decoder->ch_layout.nb_channels, 2);+ if (*channels < 1 || *rate < 1) {+ ret = AVERROR_INVALIDDATA;+ goto end;+ }+ av_opt_set_double(swr, "rematrix_maxval", 1.0, 0); // a downmix that can't clip+ for (int done = 0; !done;) {+ if (av_read_frame(format, packet) < 0) {+ done = 1; // the end (or a file cut short): flush what the decoder holds+ avcodec_send_packet(decoder, NULL);+ } else if (packet->stream_index == stream) {+ avcodec_send_packet(decoder, packet); // a damaged packet is skipped+ av_packet_unref(packet);+ } else {+ av_packet_unref(packet);+ continue;+ }+ while (avcodec_receive_frame(decoder, frame) >= 0) {+ ret = append(swr, frame, *channels, *rate, samples, frames, &capacity);+ av_frame_unref(frame);+ if (ret < 0)+ goto end;+ }+ }+ ret = *frames ? append(swr, NULL, *channels, *rate, samples, frames, &capacity) : AVERROR_INVALIDDATA;+end:+ if (ret < 0) {+ if (!*error)+ av_strerror(ret, error, error_size);+ av_freep(samples);+ *frames = 0;+ }+ av_free(buffer);+ swr_free(&swr);+ av_frame_free(&frame);+ av_packet_free(&packet);+ avcodec_free_context(&decoder);+ avformat_close_input(&format);+ if (io)+ av_freep(&io->buffer);+ avio_context_free(&io);+ return ret < 0 ? ret : 0;+}++void manimgx_free(void *pointer) {+ av_free(pointer);+}diff --git a/rust/mitex-spec-gen/Cargo.toml b/rust/mitex-spec-gen/Cargo.tomlnew file mode 100644index 00000000..fe023a2a--- /dev/null+++ b/rust/mitex-spec-gen/Cargo.toml@@ -0,0 +1,19 @@+[package]+name = "mitex-spec-gen"+version = "0.2.7"+edition = "2024"+license = "MIT AND Apache-2.0"+publish = false+description = "mitex's Typst package (0.2.7's, Apache-2.0, fetched), and its default command spec, made from it"++[dependencies]+mitex-spec = { git = "https://github.com/mitex-rs/mitex", tag = "0.2.7" }++[build-dependencies]+fetch = { path = "../fetch" }++[dev-dependencies]+serde_json = "1"+typst = "0.15.1"+typst-kit = { version = "0.15.1", default-features = false, features = ["embedded-fonts"] }+typst-layout = "0.15.1"diff --git a/rust/mitex-spec-gen/LICENSE b/rust/mitex-spec-gen/LICENSEnew file mode 100644index 00000000..a7e77cb2--- /dev/null+++ b/rust/mitex-spec-gen/LICENSE@@ -0,0 +1,176 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++END OF TERMS AND CONDITIONS\ No newline at end of filediff --git a/rust/mitex-spec-gen/build.rs b/rust/mitex-spec-gen/build.rsnew file mode 100644index 00000000..c0f8a52f--- /dev/null+++ b/rust/mitex-spec-gen/build.rs@@ -0,0 +1,11 @@+//! mitex's Typst package, 0.2.7 as Typst Universe publishes it, fetched: the engine serves its+//! manifest and specs, with this crate's own lib.typ in place of mitex's.++fn main() {+ println!("cargo:rerun-if-changed=build.rs");+ let package = fetch::tree(+ "https://packages.typst.org/preview/mitex-0.2.7.tar.gz",+ "03157cb3ea5c005d43db76291badf057503a2478ceec284d3e7de4de8e65b0f6",+ );+ println!("cargo:rustc-env=MITEX_PACKAGE={}", package.display());+}diff --git a/rust/mitex-spec-gen/lib.typ b/rust/mitex-spec-gen/lib.typnew file mode 100644index 00000000..6345695b--- /dev/null+++ b/rust/mitex-spec-gen/lib.typ@@ -0,0 +1,4 @@+// manimgx takes mitex 0.2.7's package for its scope only: the LaTeX is converted by mitex compiled+// into manimgx's engine, from this package's own specs, and the engine serves this package to+// Typst, with this file for mitex's; its WASM plugin (mitex.typ, mitex.wasm) is left out.+#import "specs/mod.typ": mitex-scopediff --git a/rust/mitex-spec-gen/spec.rkyv b/rust/mitex-spec-gen/spec.rkyvnew file mode 100644index 00000000..c5eefe96Binary files /dev/null and b/rust/mitex-spec-gen/spec.rkyv differdiff --git a/rust/mitex-spec-gen/src/lib.rs b/rust/mitex-spec-gen/src/lib.rsnew file mode 100644index 00000000..70c32153--- /dev/null+++ b/rust/mitex-spec-gen/src/lib.rs@@ -0,0 +1,30 @@+//! mitex, as manimgx builds with it: its Typst package (0.2.7, fetched by build.rs), served to+//! Typst by the engine as `@preview/mitex:{VERSION}`, mitex's own but for `lib.typ`, this crate's,+//! which imports only the scope the converted LaTeX calls; and mitex's default command spec, made+//! from that package's `specs/`: which LaTeX commands mitex converts, and how many arguments each+//! takes. mitex's own crate of this name reads the spec from a git submodule or makes it with a+//! `typst` on the PATH; this one holds the spec made from the package served, so the converter+//! and the scope it converts for come from the same files. `tests/spec.rs` makes the spec from+//! `PACKAGE` and checks that the committed one is still what it makes.++use std::sync::LazyLock;++use mitex_spec::CommandSpec;++/// The spec as rkyv bytes.+pub const SPEC: &[u8] = include_bytes!("../spec.rkyv");++/// The default command spec, which mitex converts with when it isn't given one.+pub static DEFAULT_SPEC: LazyLock<CommandSpec> = LazyLock::new(|| CommandSpec::from_bytes(SPEC));++/// The package's version, this crate's: Typst imports it as `@preview/mitex:{VERSION}`.+pub const VERSION: &str = env!("CARGO_PKG_VERSION");++/// The package's files Typst reads, by their paths in it.+pub const PACKAGE: [(&str, &[u8]); 5] = [+ ("typst.toml", include_bytes!(concat!(env!("MITEX_PACKAGE"), "/typst.toml"))),+ ("lib.typ", include_bytes!("../lib.typ")),+ ("specs/mod.typ", include_bytes!(concat!(env!("MITEX_PACKAGE"), "/specs/mod.typ"))),+ ("specs/prelude.typ", include_bytes!(concat!(env!("MITEX_PACKAGE"), "/specs/prelude.typ"))),+ ("specs/latex/standard.typ", include_bytes!(concat!(env!("MITEX_PACKAGE"), "/specs/latex/standard.typ"))),+];diff --git a/rust/mitex-spec-gen/tests/spec.rs b/rust/mitex-spec-gen/tests/spec.rsnew file mode 100644index 00000000..8c167626--- /dev/null+++ b/rust/mitex-spec-gen/tests/spec.rs@@ -0,0 +1,117 @@+//! The committed spec is the one mitex's package makes, and the package the engine serves is+//! mitex's (but for lib.typ, this crate's). mitex's build makes the spec with `typst query` over the package's+//! `specs/mod.typ` for `<mitex-packages>`; this test does the same with Typst as a library, over+//! `PACKAGE`, the files the engine serves. After upgrading mitex, write the new spec with+//! `MITEX_SPEC=write cargo test -p mitex-spec-gen` (in `rust/`).++use std::collections::{BTreeMap, BTreeSet};+use std::path::Path;++use mitex_spec_gen::{PACKAGE, VERSION};+use typst::diag::{FileError, FileResult};+use typst::foundations::{Bytes, Datetime, Duration, Label};+use typst::introspection::{Introspector, MetadataElem};+use typst::syntax::{FileId, RootedPath, Source, VirtualPath, VirtualRoot};+use typst::text::{Font, FontBook};+use typst::utils::{LazyHash, PicoStr};+use typst::{Library, LibraryExt, World};+use typst_kit::fonts::{FontStore, embedded};+use typst_layout::PagedDocument;++/// The package's files, its `specs/mod.typ` the main one.+struct Package {+ library: LazyHash<Library>,+ fonts: FontStore,+ main: FileId,+}++impl World for Package {+ fn library(&self) -> &LazyHash<Library> {+ &self.library+ }+ fn book(&self) -> &LazyHash<FontBook> {+ self.fonts.book()+ }+ fn main(&self) -> FileId {+ self.main+ }+ fn source(&self, id: FileId) -> FileResult<Source> {+ let text = String::from_utf8(self.file(id)?.to_vec()).map_err(|_| FileError::InvalidUtf8)?;+ Ok(Source::new(id, text))+ }+ fn file(&self, id: FileId) -> FileResult<Bytes> {+ let path = id.get().vpath().get_without_slash();+ let file = PACKAGE.iter().find(|(p, _)| *p == path);+ file.map(|(_, bytes)| Bytes::new(*bytes)).ok_or_else(|| FileError::NotFound(path.into()))+ }+ fn font(&self, index: usize) -> Option<Font> {+ self.fonts.font(index)+ }+ fn today(&self, _: Option<Duration>) -> Option<Datetime> {+ None+ }+}++/// The spec the package makes: every package's commands in one spec, as mitex's build merges them.+fn make() -> mitex_spec::CommandSpec {+ let mut fonts = FontStore::new();+ fonts.extend(embedded());+ let main = RootedPath::new(VirtualRoot::Project, VirtualPath::new("specs/mod.typ").unwrap()).intern();+ let world = Package { library: LazyHash::new(Library::default()), fonts, main };+ let document = typst::compile::<PagedDocument>(&world).output.expect("the specs compile");+ let label = Label::new(PicoStr::intern("mitex-packages")).unwrap();+ let content = document.introspector().query_label(label).expect("one <mitex-packages>");+ let value = &content.to_packed::<MetadataElem>().expect("metadata").value;+ let packages: mitex_spec::query::PackagesVec =+ serde_json::from_value(serde_json::to_value(value).unwrap()).expect("mitex's package specs");+ let mut spec = mitex_spec::JsonCommandSpec::default();+ for package in packages.0 {+ spec.commands.extend(package.spec.commands);+ }+ spec.into()+}++/// A spec's commands, in order, for comparing.+fn commands(spec: &mitex_spec::CommandSpec) -> BTreeMap<String, serde_json::Value> {+ spec.items().map(|(name, item)| (name.to_owned(), serde_json::to_value(item).unwrap())).collect()+}++#[test]+fn the_committed_spec_is_the_packages() {+ let made = make();+ let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("spec.rkyv");+ if std::env::var("MITEX_SPEC").as_deref() == Ok("write") {+ std::fs::write(&path, made.to_bytes()).unwrap();+ }+ let committed = mitex_spec::CommandSpec::from_bytes(&std::fs::read(&path).unwrap());+ let (made, committed) = (commands(&made), commands(&committed));+ assert!(made.len() > 900, "{} commands: the package's specs were not all read", made.len());+ assert!(made == committed, "spec.rkyv is not what mitex's package makes: MITEX_SPEC=write");+}++#[test]+fn the_package_served_is_mitexs() {+ // every Typst file of mitex's package but its WASM plugin's (mitex.typ), whose place lib.typ+ // takes, and these files as mitex publishes them+ let package = Path::new(env!("MITEX_PACKAGE"));+ let mut typst = BTreeSet::new();+ let mut stack = vec![package.to_path_buf()];+ while let Some(dir) = stack.pop() {+ for entry in std::fs::read_dir(dir).unwrap().map(Result::unwrap) {+ let path = entry.path();+ if path.is_dir() {+ stack.push(path);+ } else if path.extension().is_some_and(|e| e == "typ") || path.ends_with("typst.toml") {+ typst.insert(path.strip_prefix(package).unwrap().to_str().unwrap().replace('\\', "/"));+ }+ }+ }+ typst.remove("mitex.typ");+ let served: BTreeSet<String> = PACKAGE.iter().map(|(path, _)| (*path).to_owned()).collect();+ assert_eq!(served, typst, "PACKAGE is not every Typst file of mitex's package");+ for (path, bytes) in PACKAGE.iter().filter(|(path, _)| *path != "lib.typ") {+ assert_eq!(*bytes, &std::fs::read(package.join(path)).unwrap()[..], "{path} is not mitex's");+ }+ let manifest = std::str::from_utf8(PACKAGE[0].1).unwrap();+ assert!(manifest.contains(&format!("version = \"{VERSION}\"")), "typst.toml is not mitex {VERSION}");+}diff --git a/rust/nasm/Cargo.toml b/rust/nasm/Cargo.tomlnew file mode 100644index 00000000..ed8176ed--- /dev/null+++ b/rust/nasm/Cargo.toml@@ -0,0 +1,12 @@+[package]+name = "nasm"+version = "3.2.0"+edition = "2024"+license = "MIT AND BSD-2-Clause"+publish = false+description = "NASM 3.02, fetched and built from its source for build scripts: compiled into the one that depends on it."+links = "nasm"++[build-dependencies]+cc = { version = "1.5.1", features = ["parallel"] }+fetch = { path = "../fetch" }diff --git a/rust/nasm/build.rs b/rust/nasm/build.rsnew file mode 100644index 00000000..417841e7--- /dev/null+++ b/rust/nasm/build.rs@@ -0,0 +1,67 @@+//! NASM 3.02 from its source (nasm.us's release, fetched), as a library whose `main` is+//! `nasm_main`. MSVC reads NASM's own configuration of it (config/msvc.h); other compilers, what+//! NASM's configure finds on every C99 and POSIX system, and the C library's own functions+//! (Apple's, glibc's and musl's).++fn main() {+ println!("cargo:rerun-if-changed=build.rs");+ let source = &fetch::tree(+ "https://www.nasm.us/pub/nasm/releasebuilds/3.02/nasm-3.02.tar.gz",+ "f888713323995fa84af4a5276c01fb54f18cc149c08ac938adb48391de6d7ca0",+ );+ let mut build = cc::Build::new();+ for dir in [".", "include", "x86", "asm", "output", "zlib"] {+ build.include(source.join(dir));+ }+ build.files(SOURCES.split_whitespace().map(|f| source.join(format!("{f}.c"))));+ build.define("main", "nasm_main").warnings(false).opt_level(2);+ let target = |key: &str| std::env::var(format!("CARGO_CFG_TARGET_{key}")).unwrap_or_default();+ if build.get_compiler().is_like_msvc() {+ // as Mkfiles/msvc.mak, and the architecture <windows.h> would define before the SDK's+ // headers, which nasmlib/file.c includes alone+ let arch = match target("ARCH").as_str() {+ "aarch64" => "_ARM64_",+ "x86" => "_X86_",+ _ => "_AMD64_",+ };+ build.std("c11").flag("-bigobj").define(arch, None);+ } else {+ let out = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap());+ let mut have = vec![HAVE];+ if target("VENDOR") == "apple" {+ have.push("STRLCPY DECL_STRLCPY");+ }+ if target("OS") == "linux" {+ have.push("ENDIAN_H HTOLE16 HTOLE32 HTOLE64 MEMPCPY"); // glibc's and musl's+ }+ // configure's system extensions (AC_USE_SYSTEM_EXTENSIONS), then what it found+ let mut config = String::from("#define _GNU_SOURCE 1\n#define _DARWIN_C_SOURCE 1\n");+ config += &have.iter().flat_map(|names| names.split_whitespace()).map(|name| format!("#define HAVE_{name} 1\n")).collect::<String>();+ config += "#include \"config/unconfig.h\"\n";+ std::fs::create_dir_all(out.join("config")).unwrap();+ std::fs::write(out.join("config/config.h"), config).unwrap();+ build.include(&out).define("HAVE_CONFIG_H", None).define("_FORTIFY_SOURCE", "0").flag("-w");+ }+ build.compile("nasm");+}++/// The assembler's sources (Makefile.in's `nasm`, without the disassembler).+const SOURCES: &str = "asm/nasm asm/error asm/floats asm/directiv asm/pragma asm/assemble asm/labels asm/parser+ asm/preproc asm/quote asm/listing asm/eval asm/exprlib asm/exprdump asm/stdscan asm/getbool asm/strfunc+ asm/segalloc asm/rdstrnum asm/srcfile asm/directbl asm/pptok asm/tokhash asm/uncompress asm/warnings+ macros/macros output/outform output/outlib output/nulldbg output/nullout output/outbin output/outaout+ output/outcoff output/outelf output/outobj output/outas86 output/outdbg output/outieee output/outmacho+ output/codeview stdlib/snprintf stdlib/vsnprintf stdlib/strlcpy stdlib/strnlen nasmlib/ver nasmlib/alloc+ nasmlib/asprintf nasmlib/crc32b nasmlib/crc64 nasmlib/md5c nasmlib/string nasmlib/nctype nasmlib/file+ nasmlib/fileio nasmlib/mmap nasmlib/realpath nasmlib/path nasmlib/ilog2 nasmlib/numstr nasmlib/rlimit+ nasmlib/zerobuf nasmlib/bsi nasmlib/rbtree nasmlib/hashtbl nasmlib/raa nasmlib/saa nasmlib/strlist+ nasmlib/perfhash nasmlib/badenum nasmlib/readnum common/common common/errstubs x86/insnsa x86/insnsb+ x86/insnsn x86/regs x86/regvals x86/regflags x86/iflag zlib/adler32 zlib/crc32 zlib/infback zlib/inffast+ zlib/inflate zlib/inftrees zlib/zutil";++/// What NASM's configure finds on every C99 and POSIX system.+const HAVE: &str = "INTTYPES_H STDINT_H STDBOOL_H STDARG_H STDIO_H STDLIB_H STRING_H STRINGS_H UNISTD_H FCNTL_H+ SYS_TYPES_H SYS_STAT_H SYS_MMAN_H SYS_PARAM_H SNPRINTF VSNPRINTF STRCASECMP STRNCASECMP STRNLEN+ DECL_STRCASECMP DECL_STRNCASECMP DECL_STRNLEN STAT FSTAT S_ISREG STRUCT_STAT ACCESS FILENO FTRUNCATE MMAP+ GETPAGESIZE SYSCONF REALPATH PATHCONF FSEEKO UINTPTR_T UINTMAX_T _BOOL STDC_INLINE VARIADIC_MACROS ISASCII+ ISCNTRL";diff --git a/rust/nasm/src/lib.rs b/rust/nasm/src/lib.rsnew file mode 100644index 00000000..7803c856--- /dev/null+++ b/rust/nasm/src/lib.rs@@ -0,0 +1,31 @@+//! NASM for a build script, with nothing installed: NASM is compiled into the build script that+//! depends on this crate, which runs it as a process of itself. Call [`serve`] first in that+//! script's `main`; [`command`] is then NASM.++use std::ffi::{CString, c_char, c_int};+use std::process::Command;++unsafe extern "C" {+ fn nasm_main(argc: c_int, argv: *const *const c_char) -> c_int;+}++/// Set in the environment of the build script started as NASM.+const AS_NASM: &str = "MANIMGX_BUILD_SCRIPT_AS_NASM";++/// Be NASM, if [`command`] started this process: it then exits with NASM's status.+pub fn serve() {+ if std::env::var_os(AS_NASM).is_none() {+ return;+ }+ let args: Vec<CString> = std::env::args_os().skip(1).map(|a| CString::new(a.into_encoded_bytes()).unwrap()).collect();+ let mut argv: Vec<*const c_char> = std::iter::once(c"nasm".as_ptr()).chain(args.iter().map(|a| a.as_ptr())).collect();+ argv.push(std::ptr::null());+ std::process::exit(unsafe { nasm_main(argv.len() as c_int - 1, argv.as_ptr()) });+}++/// NASM, as a command to give arguments to: this build script, started as NASM.+pub fn command() -> Command {+ let mut command = Command::new(std::env::current_exe().expect("the build script's path"));+ command.env(AS_NASM, "1");+ command+}diff --git a/rust/x264/COPYING b/rust/x264/COPYINGnew file mode 100644index 00000000..d60c31a9--- /dev/null+++ b/rust/x264/COPYING@@ -0,0 +1,340 @@+ GNU GENERAL PUBLIC LICENSE+ Version 2, June 1991++ Copyright (C) 1989, 1991 Free Software Foundation, Inc.+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++ Preamble++ The licenses for most software are designed to take away your+freedom to share and change it. By contrast, the GNU General Public+License is intended to guarantee your freedom to share and change free+software--to make sure the software is free for all its users. This+General Public License applies to most of the Free Software+Foundation's software and to any other program whose authors commit to+using it. (Some other Free Software Foundation software is covered by+the GNU Library General Public License instead.) You can apply it to+your programs, too.++ When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+this service if you wish), that you receive source code or can get it+if you want it, that you can change the software or use pieces of it+in new free programs; and that you know you can do these things.++ To protect your rights, we need to make restrictions that forbid+anyone to deny you these rights or to ask you to surrender the rights.+These restrictions translate to certain responsibilities for you if you+distribute copies of the software, or if you modify it.++ For example, if you distribute copies of such a program, whether+gratis or for a fee, you must give the recipients all the rights that+you have. You must make sure that they, too, receive or can get the+source code. And you must show them these terms so they know their+rights.++ We protect your rights with two steps: (1) copyright the software, and+(2) offer you this license which gives you legal permission to copy,+distribute and/or modify the software.++ Also, for each author's protection and ours, we want to make certain+that everyone understands that there is no warranty for this free+software. If the software is modified by someone else and passed on, we+want its recipients to know that what they have is not the original, so+that any problems introduced by others will not reflect on the original+authors' reputations.++ Finally, any free program is threatened constantly by software+patents. We wish to avoid the danger that redistributors of a free+program will individually obtain patent licenses, in effect making the+program proprietary. To prevent this, we have made it clear that any+patent must be licensed for everyone's free use or not licensed at all.++ The precise terms and conditions for copying, distribution and+modification follow.++ GNU GENERAL PUBLIC LICENSE+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++ 0. This License applies to any program or other work which contains+a notice placed by the copyright holder saying it may be distributed+under the terms of this General Public License. The "Program", below,+refers to any such program or work, and a "work based on the Program"+means either the Program or any derivative work under copyright law:+that is to say, a work containing the Program or a portion of it,+either verbatim or with modifications and/or translated into another+language. (Hereinafter, translation is included without limitation in+the term "modification".) Each licensee is addressed as "you".++Activities other than copying, distribution and modification are not+covered by this License; they are outside its scope. The act of+running the Program is not restricted, and the output from the Program+is covered only if its contents constitute a work based on the+Program (independent of having been made by running the Program).+Whether that is true depends on what the Program does.++ 1. You may copy and distribute verbatim copies of the Program's+source code as you receive it, in any medium, provided that you+conspicuously and appropriately publish on each copy an appropriate+copyright notice and disclaimer of warranty; keep intact all the+notices that refer to this License and to the absence of any warranty;+and give any other recipients of the Program a copy of this License+along with the Program.++You may charge a fee for the physical act of transferring a copy, and+you may at your option offer warranty protection in exchange for a fee.++ 2. You may modify your copy or copies of the Program or any portion+of it, thus forming a work based on the Program, and copy and+distribute such modifications or work under the terms of Section 1+above, provided that you also meet all of these conditions:++ a) You must cause the modified files to carry prominent notices+ stating that you changed the files and the date of any change.++ b) You must cause any work that you distribute or publish, that in+ whole or in part contains or is derived from the Program or any+ part thereof, to be licensed as a whole at no charge to all third+ parties under the terms of this License.++ c) If the modified program normally reads commands interactively+ when run, you must cause it, when started running for such+ interactive use in the most ordinary way, to print or display an+ announcement including an appropriate copyright notice and a+ notice that there is no warranty (or else, saying that you provide+ a warranty) and that users may redistribute the program under+ these conditions, and telling the user how to view a copy of this+ License. (Exception: if the Program itself is interactive but+ does not normally print such an announcement, your work based on+ the Program is not required to print an announcement.)++These requirements apply to the modified work as a whole. If+identifiable sections of that work are not derived from the Program,+and can be reasonably considered independent and separate works in+themselves, then this License, and its terms, do not apply to those+sections when you distribute them as separate works. But when you+distribute the same sections as part of a whole which is a work based+on the Program, the distribution of the whole must be on the terms of+this License, whose permissions for other licensees extend to the+entire whole, and thus to each and every part regardless of who wrote it.++Thus, it is not the intent of this section to claim rights or contest+your rights to work written entirely by you; rather, the intent is to+exercise the right to control the distribution of derivative or+collective works based on the Program.++In addition, mere aggregation of another work not based on the Program+with the Program (or with a work based on the Program) on a volume of+a storage or distribution medium does not bring the other work under+the scope of this License.++ 3. You may copy and distribute the Program (or a work based on it,+under Section 2) in object code or executable form under the terms of+Sections 1 and 2 above provided that you also do one of the following:++ a) Accompany it with the complete corresponding machine-readable+ source code, which must be distributed under the terms of Sections+ 1 and 2 above on a medium customarily used for software interchange; or,++ b) Accompany it with a written offer, valid for at least three+ years, to give any third party, for a charge no more than your+ cost of physically performing source distribution, a complete+ machine-readable copy of the corresponding source code, to be+ distributed under the terms of Sections 1 and 2 above on a medium+ customarily used for software interchange; or,++ c) Accompany it with the information you received as to the offer+ to distribute corresponding source code. (This alternative is+ allowed only for noncommercial distribution and only if you+ received the program in object code or executable form with such+ an offer, in accord with Subsection b above.)++The source code for a work means the preferred form of the work for+making modifications to it. For an executable work, complete source+code means all the source code for all modules it contains, plus any+associated interface definition files, plus the scripts used to+control compilation and installation of the executable. However, as a+special exception, the source code distributed need not include+anything that is normally distributed (in either source or binary+form) with the major components (compiler, kernel, and so on) of the+operating system on which the executable runs, unless that component+itself accompanies the executable.++If distribution of executable or object code is made by offering+access to copy from a designated place, then offering equivalent+access to copy the source code from the same place counts as+distribution of the source code, even though third parties are not+compelled to copy the source along with the object code.++ 4. You may not copy, modify, sublicense, or distribute the Program+except as expressly provided under this License. Any attempt+otherwise to copy, modify, sublicense or distribute the Program is+void, and will automatically terminate your rights under this License.+However, parties who have received copies, or rights, from you under+this License will not have their licenses terminated so long as such+parties remain in full compliance.++ 5. You are not required to accept this License, since you have not+signed it. However, nothing else grants you permission to modify or+distribute the Program or its derivative works. These actions are+prohibited by law if you do not accept this License. Therefore, by+modifying or distributing the Program (or any work based on the+Program), you indicate your acceptance of this License to do so, and+all its terms and conditions for copying, distributing or modifying+the Program or works based on it.++ 6. Each time you redistribute the Program (or any work based on the+Program), the recipient automatically receives a license from the+original licensor to copy, distribute or modify the Program subject to+these terms and conditions. You may not impose any further+restrictions on the recipients' exercise of the rights granted herein.+You are not responsible for enforcing compliance by third parties to+this License.++ 7. If, as a consequence of a court judgment or allegation of patent+infringement or for any other reason (not limited to patent issues),+conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot+distribute so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you+may not distribute the Program at all. For example, if a patent+license would not permit royalty-free redistribution of the Program by+all those who receive copies directly or indirectly through you, then+the only way you could satisfy both it and this License would be to+refrain entirely from distribution of the Program.++If any portion of this section is held invalid or unenforceable under+any particular circumstance, the balance of the section is intended to+apply and the section as a whole is intended to apply in other+circumstances.++It is not the purpose of this section to induce you to infringe any+patents or other property right claims or to contest validity of any+such claims; this section has the sole purpose of protecting the+integrity of the free software distribution system, which is+implemented by public license practices. Many people have made+generous contributions to the wide range of software distributed+through that system in reliance on consistent application of that+system; it is up to the author/donor to decide if he or she is willing+to distribute software through any other system and a licensee cannot+impose that choice.++This section is intended to make thoroughly clear what is believed to+be a consequence of the rest of this License.++ 8. If the distribution and/or use of the Program is restricted in+certain countries either by patents or by copyrighted interfaces, the+original copyright holder who places the Program under this License+may add an explicit geographical distribution limitation excluding+those countries, so that distribution is permitted only in or among+countries not thus excluded. In such case, this License incorporates+the limitation as if written in the body of this License.++ 9. The Free Software Foundation may publish revised and/or new versions+of the General Public License from time to time. Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++Each version is given a distinguishing version number. If the Program+specifies a version number of this License which applies to it and "any+later version", you have the option of following the terms and conditions+either of that version or of any later version published by the Free+Software Foundation. If the Program does not specify a version number of+this License, you may choose any version ever published by the Free Software+Foundation.++ 10. If you wish to incorporate parts of the Program into other free+programs whose distribution conditions are different, write to the author+to ask for permission. For software which is copyrighted by the Free+Software Foundation, write to the Free Software Foundation; we sometimes+make exceptions for this. Our decision will be guided by the two goals+of preserving the free status of all derivatives of our free software and+of promoting the sharing and reuse of software generally.++ NO WARRANTY++ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,+REPAIR OR CORRECTION.++ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE+POSSIBILITY OF SUCH DAMAGES.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++ If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++ To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+convey the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software; you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation; either version 2 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License+ along with this program; if not, write to the Free Software+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+++Also add information on how to contact you by electronic and paper mail.++If the program is interactive, make it output a short notice like this+when it starts in an interactive mode:++ Gnomovision version 69, Copyright (C) year name of author+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+ This is free software, and you are welcome to redistribute it+ under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License. Of course, the commands you use may+be called something other than `show w' and `show c'; they could even be+mouse-clicks or menu items--whatever suits your program.++You should also get your employer (if you work as a programmer) or your+school, if any, to sign a "copyright disclaimer" for the program, if+necessary. Here is a sample; alter the names:++ Yoyodyne, Inc., hereby disclaims all copyright interest in the program+ `Gnomovision' (which makes passes at compilers) written by James Hacker.++ <signature of Ty Coon>, 1 April 1989+ Ty Coon, President of Vice++This General Public License does not permit incorporating your program into+proprietary programs. If your program is a subroutine library, you may+consider it more useful to permit linking proprietary applications with the+library. If this is what you want to do, use the GNU Library General+Public License instead of this License.diff --git a/rust/x264/COPYING.x86inc b/rust/x264/COPYING.x86incnew file mode 100644index 00000000..adaf1644--- /dev/null+++ b/rust/x264/COPYING.x86inc@@ -0,0 +1,21 @@+x86inc.asm, x264asm abstraction layer (common/x86/x86inc.asm): unlike the rest of x264, it is+available under this ISC license.++Copyright (C) 2005-2025 x264 project++Authors: Loren Merritt <[email protected]>+ Henrik Gramner <[email protected]>+ Anton Mitrofanov <[email protected]>+ Fiona Glaser <[email protected]>++Permission to use, copy, modify, and/or distribute this software for any+purpose with or without fee is hereby granted, provided that the above+copyright notice and this permission notice appear in all copies.++THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.diff --git a/rust/x264/Cargo.toml b/rust/x264/Cargo.tomlnew file mode 100644index 00000000..0cd11ccd--- /dev/null+++ b/rust/x264/Cargo.toml@@ -0,0 +1,13 @@+[package]+name = "x264"+version = "0.165.3223"+edition = "2024"+license = "MIT AND GPL-2.0-or-later AND ISC"+publish = false+description = "x264 r3223 (0480cb05), the H.264 encoder, fetched and built from its source, behind a few safe calls."+links = "x264"++[build-dependencies]+cc = { version = "1.5.1", features = ["parallel"] }+fetch = { path = "../fetch" }+nasm = { path = "../nasm" }diff --git a/rust/x264/build.rs b/rust/x264/build.rsnew file mode 100644index 00000000..4814cd6a--- /dev/null+++ b/rust/x264/build.rs@@ -0,0 +1,140 @@+//! x264 r3223 from its source (VideoLAN's archive of 0480cb05, fetched), with nothing installed:+//! the configuration its `configure` would write for the target, its C, and its assembly — on+//! x86-64 NASM's (the `nasm` crate: NASM from its source, in this script), on AArch64 the C+//! compiler's. Elsewhere, its C alone.++use std::path::{Path, PathBuf};++fn main() {+ nasm::serve();+ println!("cargo:rerun-if-changed=build.rs");+ println!("cargo:rerun-if-changed=src/shim.c");+ let source = &fetch::tree(+ "https://code.videolan.org/videolan/x264/-/archive/0480cb05fa188d37ae87e8f4fd8f1aea3711f7ee/x264-0480cb05fa188d37ae87e8f4fd8f1aea3711f7ee.tar.gz",+ "f6be0c17bbcea2e79823e0dc953ad86f605deb41602d606108e1182a5118c434",+ );+ let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap());+ let target = |key: &str| std::env::var(format!("CARGO_CFG_TARGET_{key}")).unwrap_or_default();+ let (arch, os, msvc) = (target("ARCH"), target("OS"), target("ENV") == "msvc");+ let (x86, arm) = (arch == "x86_64", arch == "aarch64" && !msvc); // with assembly+ let (linux, windows) = (os == "linux", os == "windows");+ let stack = if x86 && !msvc { 64 } else { 16 };++ // config.h: what configure defines as 1 (x264 tests them with `#if`: the rest are 0)+ let mut defines = vec![+ "HAVE_BITDEPTH8 HAVE_GPL HAVE_INTERLACED HAVE_THREAD HAVE_LOG2F",+ if windows { "HAVE_WIN32THREAD SYS_WINDOWS" } else { "HAVE_POSIXTHREAD HAVE_STRTOK_R HAVE_CLOCK_GETTIME HAVE_SYSCONF HAVE_MMAP" },+ ];+ for (on, names) in [+ (!msvc, "HAVE_VECTOREXT"),+ (os == "macos", "SYS_MACOSX"),+ (linux, "SYS_LINUX HAVE_MALLOC_H HAVE_CPU_COUNT HAVE_GETAUXVAL"),+ (linux && x86, "HAVE_THP"),+ (x86, "ARCH_X86_64 HAVE_MMX"),+ (x86 && !msvc, "HAVE_X86_INLINE_ASM"),+ (x86 && msvc, "__SSE__"),+ (arch == "aarch64", "ARCH_AARCH64"),+ (arm, "HAVE_AARCH64 HAVE_NEON HAVE_DOTPROD HAVE_I8MM HAVE_SVE HAVE_SVE2 HAVE_AS_ARCHEXT_DOTPROD_DIRECTIVE"),+ (arm, "HAVE_AS_ARCHEXT_I8MM_DIRECTIVE HAVE_AS_ARCHEXT_SVE_DIRECTIVE HAVE_AS_ARCHEXT_SVE2_DIRECTIVE"),+ ] {+ if on {+ defines.push(names);+ }+ }+ let mut config: String = defines.iter().flat_map(|names| names.split_whitespace()).map(|name| format!("#define {name} 1\n")).collect();+ config += &format!("#define STACK_ALIGNMENT {stack}\n#define AS_ARCH_LEVEL armv8.2-a\n");+ std::fs::write(out.join("config.h"), config).unwrap();+ let version = "#define X264_VERSION \"\"\n#define X264_POINTVER \"0.165.3223 0480cb0\"\n";+ std::fs::write(out.join("x264_config.h"), format!("#define X264_GPL 1\n#define X264_INTERLACED 1\n#define X264_BIT_DEPTH 8\n#define X264_CHROMA_FORMAT 0\n{version}")).unwrap();++ // configure's compiler flags; the files x264's Makefile compiles once, then those it compiles+ // per bit depth (only 8)+ let build = || {+ let mut build = cc::Build::new();+ build.include(&out).include(source).warnings(false).opt_level(3);+ if msvc {+ build.flag("-fp:fast").flag("-GS-");+ } else {+ build.flag("-w").flag("-ffast-math").flag("-std=gnu99").define("_GNU_SOURCE", None).flag("-fomit-frame-pointer");+ build.flag_if_supported("-fno-tree-vectorize").flag("-fvisibility=hidden");+ if x86 {+ build.flag_if_supported("-mstack-alignment=64").flag_if_supported("-mpreferred-stack-boundary=6");+ }+ }+ build+ };+ let sources = |dir: &str, names: &str, ext: &str| names.split_whitespace().map(|name| source.join(format!("{dir}/{name}.{ext}"))).collect::<Vec<_>>();+ let mut once = build();+ once.files(sources("common", "osdep base cpu tables", "c")).files(sources("encoder", "api", "c")).file("src/shim.c");+ if windows {+ once.file(source.join("common/win32thread.c"));+ }+ let mut objects = once.compile_intermediates();+ let mut depth = build();+ depth.define("HIGH_BIT_DEPTH", "0").define("BIT_DEPTH", "8");+ depth.files(sources("common", "mc predict pixel macroblock frame dct cabac common rectangle set quant deblock vlc mvpred bitstream threadpool", "c"));+ depth.files(sources("encoder", "analyse me ratecontrol set macroblock cabac cavlc encoder lookahead", "c"));+ if x86 {+ depth.files(sources("common/x86", "mc-c predict-c", "c"));+ }+ if arm {+ depth.files(sources("common/aarch64", "asm-offsets mc-c predict-c", "c"));+ depth.files(sources("common/aarch64", "bitstream-a cabac-a dct-a deblock-a mc-a pixel-a predict-a quant-a", "S"));+ depth.files(sources("common/aarch64", "dct-a-sve deblock-a-sve mc-a-sve pixel-a-sve dct-a-sve2", "S"));+ depth.define("PIC", None);+ if os == "macos" {+ depth.define("PREFIX", None);+ }+ }+ objects.extend(depth.compile_intermediates());+ if x86 {+ objects.extend(assemble(source, &out, &os, stack));+ }+ cc::Build::new().objects(objects).compile("x264");+}++/// x264's x86-64 assembly, by NASM, in parallel: in a folder of their copies, so that NASM, which+/// reads its arguments in Windows' ANSI code page, is given ASCII only; with no timestamp in a+/// COFF object, so that a build is the same bytes whenever it is made.+fn assemble(source: &Path, out: &Path, os: &str, stack: u32) -> Vec<PathBuf> {+ let dir = out.join("x86");+ std::fs::create_dir_all(&dir).unwrap();+ for entry in std::fs::read_dir(source.join("common/x86")).unwrap() {+ let path = entry.unwrap().path();+ if path.extension().is_some_and(|ext| ext == "asm") {+ std::fs::copy(&path, dir.join(path.file_name().unwrap())).unwrap();+ }+ }+ let format = match os {+ "macos" => "-fmacho64",+ "windows" => "-fwin64",+ _ => "-felf64",+ };+ // cpu-a is compiled once, the rest per bit depth+ let files = "cpu-a bitstream-a const-a cabac-a dct-a deblock-a mc-a mc-a2 pixel-a predict-a quant-a dct-64 trellis-64 sad-a";+ std::thread::scope(|scope| {+ let jobs: Vec<_> = files+ .split_whitespace()+ .map(|name| {+ let dir = &dir;+ scope.spawn(move || {+ let mut nasm = nasm::command();+ nasm.current_dir(dir).args(["--reproducible", "-I./", format, "-DARCH_X86_64=1", &format!("-DSTACK_ALIGNMENT={stack}")]);+ if os == "macos" {+ nasm.arg("-DPREFIX");+ }+ if os != "windows" {+ nasm.arg("-DPIC");+ }+ if name != "cpu-a" {+ nasm.args(["-DBIT_DEPTH=8", "-Dprivate_prefix=x264_8"]);+ }+ let status = nasm.args(["-o", &format!("{name}.o"), &format!("{name}.asm")]).status().expect("NASM");+ assert!(status.success(), "NASM failed on {name}.asm");+ dir.join(format!("{name}.o"))+ })+ })+ .collect();+ jobs.into_iter().map(|job| job.join().unwrap()).collect()+ })+}diff --git a/rust/x264/src/lib.rs b/rust/x264/src/lib.rsnew file mode 100644index 00000000..41d01242--- /dev/null+++ b/rust/x264/src/lib.rs@@ -0,0 +1,99 @@+//! x264, the H.264 encoder, built from its source (fetched, see build.rs) and used through a C+//! shim (src/shim.c): NV12 pictures in; out, samples for an MP4, each a picture's NAL units+//! prefixed by their sizes, with the parameter sets apart.++use std::ffi::{CString, c_char, c_int, c_void};++unsafe extern "C" {+ fn manimgx_x264_open(+ out: *mut *mut c_void, width: c_int, height: c_int, fps: c_int, preset: *const c_char, crf: f32, count: c_int,+ names: *const *const c_char, values: *const *const c_char, sps: *mut *const u8, sps_size: *mut c_int,+ pps: *mut *const u8, pps_size: *mut c_int,+ ) -> c_int;+ fn manimgx_x264_encode(+ encoder: *mut c_void, nv12: *const u8, pts: i64, constant: *const u8, force_key: c_int, sample: *mut *const u8, size: *mut c_int,+ sample_pts: *mut i64, sample_dts: *mut i64, key: *mut c_int,+ ) -> c_int;+ fn manimgx_x264_delayed(encoder: *mut c_void) -> c_int;+ fn manimgx_x264_close(encoder: *mut c_void);+}++/// A picture as x264 wrote it: its NAL units, together one MP4 sample.+pub struct Sample<'a> {+ pub data: &'a [u8],+ pub pts: i64,+ pub dts: i64,+ pub key: bool,+}++/// An encoder of NV12 pictures, used by one thread at a time (x264 has no thread affinity).+pub struct Encoder {+ raw: *mut c_void,+ picture: usize,+ macroblocks: usize,+ /// The sequence parameter set, without its size prefix.+ pub sps: Vec<u8>,+ /// The picture parameter set, without its size prefix.+ pub pps: Vec<u8>,+}++unsafe impl Send for Encoder {}++impl Encoder {+ /// Pictures of `width` × `height` at `fps`, their times in frames, in BT.601 limited range+ /// over sRGB bytes: x264's `preset` and constant rate factor `crf`, then its own `options`+ /// (name, value), as `-x264-params` gives them.+ pub fn new(width: u32, height: u32, fps: u32, preset: &str, crf: f32, options: &[(String, String)]) -> Result<Self, String> {+ let text = |s: &str| CString::new(s).map_err(|e| e.to_string());+ let preset_c = text(preset)?;+ let names = options.iter().map(|(name, _)| text(name)).collect::<Result<Vec<_>, _>>()?;+ let values = options.iter().map(|(_, value)| text(value)).collect::<Result<Vec<_>, _>>()?;+ let (names_p, values_p): (Vec<_>, Vec<_>) = names.iter().zip(&values).map(|(n, v)| (n.as_ptr(), v.as_ptr())).unzip();+ let (mut raw, mut sps, mut pps, mut sps_size, mut pps_size) = (std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), 0, 0);+ let status = unsafe {+ manimgx_x264_open(+ &mut raw, width as c_int, height as c_int, fps as c_int, preset_c.as_ptr(), crf, options.len() as c_int, names_p.as_ptr(),+ values_p.as_ptr(), &mut sps, &mut sps_size, &mut pps, &mut pps_size,+ )+ };+ match status {+ 0 => {}+ 1 => return Err(format!("unknown x264 preset {preset}")),+ k if k >= 2 => return Err(format!("x264 option {}={}", options[k as usize - 2].0, options[k as usize - 2].1)),+ _ => return Err("x264 could not open an encoder".into()),+ }+ let (sps, pps) = unsafe { (std::slice::from_raw_parts(sps, sps_size as usize).to_vec(), std::slice::from_raw_parts(pps, pps_size as usize).to_vec()) };+ let (width, height) = (width as usize, height as usize);+ Ok(Self { raw, picture: width * height * 3 / 2, macroblocks: width.div_ceil(16) * height.div_ceil(16), sps, pps })+ }++ /// Encode an NV12 picture shown from `pts` — or, with none, one that x264 held back (while+ /// [`delayed`](Self::delayed)). `constant`, a byte per macroblock, marks those unchanged since+ /// the previous picture: x264 skips them. `force_key` makes the picture a keyframe (an IDR+ /// picture, where a player can start). Returns the sample written, if any.+ pub fn encode(&mut self, nv12: Option<&[u8]>, pts: i64, constant: Option<&[u8]>, force_key: bool) -> Result<Option<Sample<'_>>, String> {+ assert!(nv12.is_none_or(|p| p.len() >= self.picture) && constant.is_none_or(|c| c.len() >= self.macroblocks));+ let (mut sample, mut size, mut sample_pts, mut dts, mut key) = (std::ptr::null(), 0, 0, 0, 0);+ let status = unsafe {+ manimgx_x264_encode(+ self.raw, nv12.map_or(std::ptr::null(), <[u8]>::as_ptr), pts, constant.map_or(std::ptr::null(), <[u8]>::as_ptr), force_key as c_int, &mut sample,+ &mut size, &mut sample_pts, &mut dts, &mut key,+ )+ };+ if status < 0 {+ return Err("x264 failed to encode a picture".into());+ }+ Ok((size > 0).then(|| Sample { data: unsafe { std::slice::from_raw_parts(sample, size as usize) }, pts: sample_pts, dts, key: key != 0 }))+ }++ /// Whether x264 still holds pictures back.+ pub fn delayed(&self) -> bool {+ unsafe { manimgx_x264_delayed(self.raw) > 0 }+ }+}++impl Drop for Encoder {+ fn drop(&mut self) {+ unsafe { manimgx_x264_close(self.raw) }+ }+}diff --git a/rust/x264/src/shim.c b/rust/x264/src/shim.cnew file mode 100644index 00000000..a4637a88--- /dev/null+++ b/rust/x264/src/shim.c@@ -0,0 +1,128 @@+/* x264 behind four calls, so that Rust never mirrors its structs: NV12 pictures in, samples+ * for an MP4 out (each picture's NAL units prefixed by their sizes, the parameter sets apart). */++#include <stdint.h>+#include <stdlib.h>++#include "x264.h"++typedef struct {+ x264_t *x264;+ int width, height, macroblocks;+} encoder;++/* An encoder of width × height pictures at fps, in BT.601 limited range over sRGB bytes:+ * x264's preset and constant rate factor, then `count` of its own options, names[k] =+ * values[k]. `*sps` and `*pps` are its parameter sets, without size prefixes, until the next+ * call. Returns 0, or what failed: 1 the preset, 2 + k option k, -1 x264. */+int manimgx_x264_open(encoder **out, int width, int height, int fps, const char *preset,+ float crf, int count, const char *const *names,+ const char *const *values, const uint8_t **sps, int *sps_size,+ const uint8_t **pps, int *pps_size) {+ x264_param_t param;+ if (x264_param_default_preset(¶m, preset, NULL) < 0)+ return 1;+ param.i_width = width;+ param.i_height = height;+ param.i_csp = X264_CSP_NV12;+ param.i_fps_num = param.i_timebase_den = fps;+ param.i_fps_den = param.i_timebase_num = 1;+ param.b_repeat_headers = 0;+ param.b_annexb = 0;+ param.rc.f_rf_constant = crf;+ param.i_log_level = X264_LOG_NONE;+ param.analyse.b_mb_info = 1;+ for (int k = 0; k < count; k++)+ if (x264_param_parse(¶m, names[k], values[k]) < 0)+ return 2 + k;+ param.vui.b_fullrange = 0;+ param.vui.i_colmatrix = 6; /* smpte170m */+ param.vui.i_colorprim = 1; /* bt709 */+ param.vui.i_transfer = 13; /* iec61966-2-1 */+ if (x264_param_apply_profile(¶m, "high") < 0)+ return -1;+ encoder *e = malloc(sizeof *e);+ if (!e || !(e->x264 = x264_encoder_open(¶m))) {+ free(e);+ return -1;+ }+ e->width = width;+ e->height = height;+ e->macroblocks = ((width + 15) / 16) * ((height + 15) / 16);+ x264_nal_t *nals;+ int n;+ *sps = *pps = NULL;+ if (x264_encoder_headers(e->x264, &nals, &n) < 0)+ n = 0;+ for (int k = 0; k < n; k++) {+ if (nals[k].i_type == NAL_SPS) {+ *sps = nals[k].p_payload + 4;+ *sps_size = nals[k].i_payload - 4;+ } else if (nals[k].i_type == NAL_PPS) {+ *pps = nals[k].p_payload + 4;+ *pps_size = nals[k].i_payload - 4;+ }+ }+ if (!*sps || !*pps) {+ x264_encoder_close(e->x264);+ free(e);+ return -1;+ }+ *out = e;+ return 0;+}++/* Encode an NV12 picture shown from `pts` (NULL: one that x264 held back); `constant`, if+ * given, has a byte per macroblock, nonzero where the picture is the previous one's, and x264+ * skips those; `force_key` makes the picture a keyframe (IDR). The sample written is at `*sample` until the next call: `*size` bytes, 0 when+ * x264 holds the picture back. Returns < 0 on failure. */+int manimgx_x264_encode(encoder *e, const uint8_t *nv12, int64_t pts, const uint8_t *constant,+ int force_key, const uint8_t **sample, int *size, int64_t *sample_pts,+ int64_t *sample_dts, int *key) {+ x264_picture_t in, out, *picture = NULL;+ if (nv12) {+ x264_picture_init(&in);+ in.img.i_csp = X264_CSP_NV12;+ in.img.i_plane = 2;+ in.img.i_stride[0] = in.img.i_stride[1] = e->width;+ in.img.plane[0] = (uint8_t *)nv12;+ in.img.plane[1] = (uint8_t *)nv12 + (size_t)e->width * e->height;+ in.i_pts = pts;+ in.i_type = force_key ? X264_TYPE_IDR : X264_TYPE_AUTO;+ if (constant) {+ /* x264 may encode the picture later (frame threads): it frees the array */+ uint8_t *info = malloc(e->macroblocks);+ if (!info)+ return -1;+ for (int k = 0; k < e->macroblocks; k++)+ info[k] = constant[k] ? X264_MBINFO_CONSTANT : 0;+ in.prop.mb_info = info;+ in.prop.mb_info_free = free;+ }+ picture = ∈+ }+ x264_nal_t *nals;+ int n;+ *size = x264_encoder_encode(e->x264, &nals, &n, picture, &out);+ if (*size < 0)+ return -1;+ *sample = NULL;+ if (*size) {+ /* the NAL units of a picture are contiguous: together, one sample */+ *sample = nals[0].p_payload;+ *sample_pts = out.i_pts;+ *sample_dts = out.i_dts;+ *key = out.b_keyframe;+ }+ return 0;+}++/* How many pictures x264 holds back. */+int manimgx_x264_delayed(encoder *e) {+ return x264_encoder_delayed_frames(e->x264);+}++void manimgx_x264_close(encoder *e) {+ x264_encoder_close(e->x264);+ free(e);+}