Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.
Python ai-filmmakingai-videoai-video-generatorapple-siliconhailuoimage-to-videolip-synclocal-ailora-trainingltx-2ltx-2-5ltx-videomacosminimax-h3mlxmusic-generationoffline-aipinokiotext-to-videovideo-generation
v4.14.0 — songs, faces and sound
mrbizarrofbc777cc33cf
diff --git a/.gitignore b/.gitignoreindex 94f44d9..df7864e 100644--- a/.gitignore+++ b/.gitignore@@ -148,3 +148,6 @@ notes/# Frontend lint harness (dev-only; see package.json). Never ship node_modules.node_modules/++# YuE2 engine checkout; weights live in the shared mlx_models tree.+yue2-mlx/diff --git a/LICENSES/NOTICE-yue2.md b/LICENSES/NOTICE-yue2.mdnew file mode 100644index 0000000..d6d086f--- /dev/null+++ b/LICENSES/NOTICE-yue2.md@@ -0,0 +1,19 @@+# YuE2 notices++YuE2 by Multimodal Art Projection:+https://huggingface.co/m-a-p/YuE2-3B and+https://huggingface.co/m-a-p/YuE2-Vae.++The MLX port is vanch007/mlx-Yue (https://github.com/vanch007/mlx-Yue),+Apache-2.0, as is the upstream code. Phosphene downloads the generator+converted to MLX by that project from https://huggingface.co/vanch007/mlx-Yue2-3B+(BF16 tensors byte-identical to m-a-p/YuE2-3B; the 8-bit AR file is a+quantization of them) and the unchanged decoder from m-a-p/YuE2-Vae.+Phosphene does not re-host the weights.+Oobleck VAE and SnakeBeta are MIT; their notices travel in the downloaded pack.++The weights are CC BY-NC 4.0 plus an individual-creator permission: individual+creators may monetize songs they create; companies need a license for the+weights. See the complete, unmodified YuE2-MODEL_LICENSE.txt beside this notice+(upstream MODEL_LICENSE, 2026-09-16). The port's older vendored license is not+this permission's source.diff --git a/LICENSES/YuE2-MODEL_LICENSE.txt b/LICENSES/YuE2-MODEL_LICENSE.txtnew file mode 100644index 0000000..ba6e1b2--- /dev/null+++ b/LICENSES/YuE2-MODEL_LICENSE.txt@@ -0,0 +1,499 @@+YuE2 model-weight license++The YuE2-3B, YuE2-Vae and YuE2-Vae-legacy checkpoint weights are+licensed under Creative Commons Attribution-NonCommercial 4.0 International+(CC BY-NC 4.0): https://creativecommons.org/licenses/by-nc/4.0/+Individual creator permission and academic-use terms are set out below.++Scope: the YuE2 checkpoint weights in model.safetensors, or the corresponding+models/<model-name>/model.safetensors files in the inference kit.+For attribution, identify YuE2, the model name and its source repository:+https://huggingface.co/m-a-p/YuE2-3B+https://huggingface.co/m-a-p/YuE2-Vae+https://huggingface.co/m-a-p/YuE2-Vae-legacy++This weight license does not replace separately applicable licenses for code,+text tokenization files, evaluation assets or other bundled material.+Third-party source notices and their original license texts are preserved in+THIRD_PARTY_NOTICES.md and licenses/.++Individual creator permission and academic use (2026-09-16)+---------------------------------------------------------++Individual creators and output monetization+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++In addition to the CC BY-NC 4.0 license below, the YuE2 model licensors+grant personal users, content creators and musicians acting in an+individual capacity permission to use the model weights free of charge+to generate outputs, and to publish, distribute, sell, license or+otherwise monetize those outputs, subject to the responsible-use+conditions below.++For these individual creative activities, the model licensors waive the+NonCommercial restriction to the extent necessary. These users do not+need a separate commercial license from, or owe license fees or+royalties to, the model licensors for this use or for monetizing their+outputs. This includes distributing or licensing their outputs to+clients and publishing them on commercial platforms.++Academic use+~~~~~~~~~~~~++Students, educators, researchers and academic institutions may use YuE2+free of charge for non-commercial research and education under the+CC BY-NC 4.0 license below. This academic-use provision does not itself+grant commercial-use rights to an institution. An academic user+creating work in an individual capacity may rely on the individual+creator permission above.++Credit and other terms+~~~~~~~~~~~~~~~~~~~~~~++We strongly encourage users to credit YuE2 by including the model name+or the #YuE2 tag when sharing generated work. Credit on generated+outputs is optional and is not a condition of this additional permission+or of output monetization. This recommendation does not waive the+attribution requirements for sharing model weights or adapted weights.++The individual creator permission does not authorize commercial use+of the model weights by companies. Companies wishing to use the model weights commercially+should contact [email protected] to discuss a commercial license:+https://github.com/multimodal-art-projection/YuE#contact++Responsible use is a condition of this additional permission. Under+this permission, you must not use the model weights or generated+outputs for illegal, harmful, deceptive or otherwise unethical purposes,+including fraud, harassment or deceptive impersonation. You are+responsible for your inputs, outputs and use of the model, including+obtaining any necessary rights and consent.++To the extent permitted by applicable law, the model weights and the+additional permission are provided as is, without warranties of any+kind. The model licensors and authors disclaim liability for misuse+and any resulting claims, losses or damages. Nothing in this statement+excludes liability that cannot lawfully be excluded.++This permission concerns generating and using outputs; it does not+extend to commercial redistribution or sale of the model weights.+All other applicable CC BY-NC 4.0 conditions continue to apply to the+weights. Generated outputs are not subject to the model weights'+NonCommercial restriction solely because they were generated with YuE2.++This additional permission and its responsible-use conditions are+separate from the unmodified CC BY-NC 4.0 license below. They do not+restrict rights already granted under CC BY-NC 4.0, Apache 2.0 or+earlier grants of additional permission. This permission covers+only rights the model licensors have authority to grant and does not+grant rights in third-party material used in inputs or outputs.++The official license text follows without modification.+Source: https://creativecommons.org/licenses/by-nc/4.0/legalcode.txt++Attribution-NonCommercial 4.0 International++=======================================================================++Creative Commons Corporation ("Creative Commons") is not a law firm and+does not provide legal services or legal advice. Distribution of+Creative Commons public licenses does not create a lawyer-client or+other relationship. Creative Commons makes its licenses and related+information available on an "as-is" basis. Creative Commons gives no+warranties regarding its licenses, any material licensed under their+terms and conditions, or any related information. Creative Commons+disclaims all liability for damages resulting from their use to the+fullest extent possible.++Using Creative Commons Public Licenses++Creative Commons public licenses provide a standard set of terms and+conditions that creators and other rights holders may use to share+original works of authorship and other material subject to copyright+and certain other rights specified in the public license below. The+following considerations are for informational purposes only, are not+exhaustive, and do not form part of our licenses.++ Considerations for licensors: Our public licenses are+ intended for use by those authorized to give the public+ permission to use material in ways otherwise restricted by+ copyright and certain other rights. Our licenses are+ irrevocable. Licensors should read and understand the terms+ and conditions of the license they choose before applying it.+ Licensors should also secure all rights necessary before+ applying our licenses so that the public can reuse the+ material as expected. Licensors should clearly mark any+ material not subject to the license. This includes other CC-+ licensed material, or material used under an exception or+ limitation to copyright. More considerations for licensors:+ wiki.creativecommons.org/Considerations_for_licensors++ Considerations for the public: By using one of our public+ licenses, a licensor grants the public permission to use the+ licensed material under specified terms and conditions. If+ the licensor's permission is not necessary for any reason--for+ example, because of any applicable exception or limitation to+ copyright--then that use is not regulated by the license. Our+ licenses grant only permissions under copyright and certain+ other rights that a licensor has authority to grant. Use of+ the licensed material may still be restricted for other+ reasons, including because others have copyright or other+ rights in the material. A licensor may make special requests,+ such as asking that all changes be marked or described.+ Although not required by our licenses, you are encouraged to+ respect those requests where reasonable. More considerations+ for the public:+ wiki.creativecommons.org/Considerations_for_licensees++=======================================================================++Creative Commons Attribution-NonCommercial 4.0 International Public+License++By exercising the Licensed Rights (defined below), You accept and agree+to be bound by the terms and conditions of this Creative Commons+Attribution-NonCommercial 4.0 International Public License ("Public+License"). To the extent this Public License may be interpreted as a+contract, You are granted the Licensed Rights in consideration of Your+acceptance of these terms and conditions, and the Licensor grants You+such rights in consideration of benefits the Licensor receives from+making the Licensed Material available under these terms and+conditions.+++Section 1 -- Definitions.++ a. Adapted Material means material subject to Copyright and Similar+ Rights that is derived from or based upon the Licensed Material+ and in which the Licensed Material is translated, altered,+ arranged, transformed, or otherwise modified in a manner requiring+ permission under the Copyright and Similar Rights held by the+ Licensor. For purposes of this Public License, where the Licensed+ Material is a musical work, performance, or sound recording,+ Adapted Material is always produced where the Licensed Material is+ synched in timed relation with a moving image.++ b. Adapter's License means the license You apply to Your Copyright+ and Similar Rights in Your contributions to Adapted Material in+ accordance with the terms and conditions of this Public License.++ c. Copyright and Similar Rights means copyright and/or similar rights+ closely related to copyright including, without limitation,+ performance, broadcast, sound recording, and Sui Generis Database+ Rights, without regard to how the rights are labeled or+ categorized. For purposes of this Public License, the rights+ specified in Section 2(b)(1)-(2) are not Copyright and Similar+ Rights.+ d. Effective Technological Measures means those measures that, in the+ absence of proper authority, may not be circumvented under laws+ fulfilling obligations under Article 11 of the WIPO Copyright+ Treaty adopted on December 20, 1996, and/or similar international+ agreements.++ e. Exceptions and Limitations means fair use, fair dealing, and/or+ any other exception or limitation to Copyright and Similar Rights+ that applies to Your use of the Licensed Material.++ f. Licensed Material means the artistic or literary work, database,+ or other material to which the Licensor applied this Public+ License.++ g. Licensed Rights means the rights granted to You subject to the+ terms and conditions of this Public License, which are limited to+ all Copyright and Similar Rights that apply to Your use of the+ Licensed Material and that the Licensor has authority to license.++ h. Licensor means the individual(s) or entity(ies) granting rights+ under this Public License.++ i. NonCommercial means not primarily intended for or directed towards+ commercial advantage or monetary compensation. For purposes of+ this Public License, the exchange of the Licensed Material for+ other material subject to Copyright and Similar Rights by digital+ file-sharing or similar means is NonCommercial provided there is+ no payment of monetary compensation in connection with the+ exchange.++ j. Share means to provide material to the public by any means or+ process that requires permission under the Licensed Rights, such+ as reproduction, public display, public performance, distribution,+ dissemination, communication, or importation, and to make material+ available to the public including in ways that members of the+ public may access the material from a place and at a time+ individually chosen by them.++ k. Sui Generis Database Rights means rights other than copyright+ resulting from Directive 96/9/EC of the European Parliament and of+ the Council of 11 March 1996 on the legal protection of databases,+ as amended and/or succeeded, as well as other essentially+ equivalent rights anywhere in the world.++ l. You means the individual or entity exercising the Licensed Rights+ under this Public License. Your has a corresponding meaning.+++Section 2 -- Scope.++ a. License grant.++ 1. Subject to the terms and conditions of this Public License,+ the Licensor hereby grants You a worldwide, royalty-free,+ non-sublicensable, non-exclusive, irrevocable license to+ exercise the Licensed Rights in the Licensed Material to:++ a. reproduce and Share the Licensed Material, in whole or+ in part, for NonCommercial purposes only; and++ b. produce, reproduce, and Share Adapted Material for+ NonCommercial purposes only.++ 2. Exceptions and Limitations. For the avoidance of doubt, where+ Exceptions and Limitations apply to Your use, this Public+ License does not apply, and You do not need to comply with+ its terms and conditions.++ 3. Term. The term of this Public License is specified in Section+ 6(a).++ 4. Media and formats; technical modifications allowed. The+ Licensor authorizes You to exercise the Licensed Rights in+ all media and formats whether now known or hereafter created,+ and to make technical modifications necessary to do so. The+ Licensor waives and/or agrees not to assert any right or+ authority to forbid You from making technical modifications+ necessary to exercise the Licensed Rights, including+ technical modifications necessary to circumvent Effective+ Technological Measures. For purposes of this Public License,+ simply making modifications authorized by this Section 2(a)+ (4) never produces Adapted Material.++ 5. Downstream recipients.++ a. Offer from the Licensor -- Licensed Material. Every+ recipient of the Licensed Material automatically+ receives an offer from the Licensor to exercise the+ Licensed Rights under the terms and conditions of this+ Public License.++ b. No downstream restrictions. You may not offer or impose+ any additional or different terms or conditions on, or+ apply any Effective Technological Measures to, the+ Licensed Material if doing so restricts exercise of the+ Licensed Rights by any recipient of the Licensed+ Material.++ 6. No endorsement. Nothing in this Public License constitutes or+ may be construed as permission to assert or imply that You+ are, or that Your use of the Licensed Material is, connected+ with, or sponsored, endorsed, or granted official status by,+ the Licensor or others designated to receive attribution as+ provided in Section 3(a)(1)(A)(i).++ b. Other rights.++ 1. Moral rights, such as the right of integrity, are not+ licensed under this Public License, nor are publicity,+ privacy, and/or other similar personality rights; however, to+ the extent possible, the Licensor waives and/or agrees not to+ assert any such rights held by the Licensor to the limited+ extent necessary to allow You to exercise the Licensed+ Rights, but not otherwise.++ 2. Patent and trademark rights are not licensed under this+ Public License.++ 3. To the extent possible, the Licensor waives any right to+ collect royalties from You for the exercise of the Licensed+ Rights, whether directly or through a collecting society+ under any voluntary or waivable statutory or compulsory+ licensing scheme. In all other cases the Licensor expressly+ reserves any right to collect such royalties, including when+ the Licensed Material is used other than for NonCommercial+ purposes.+++Section 3 -- License Conditions.++Your exercise of the Licensed Rights is expressly made subject to the+following conditions.++ a. Attribution.++ 1. If You Share the Licensed Material (including in modified+ form), You must:++ a. retain the following if it is supplied by the Licensor+ with the Licensed Material:++ i. identification of the creator(s) of the Licensed+ Material and any others designated to receive+ attribution, in any reasonable manner requested by+ the Licensor (including by pseudonym if+ designated);++ ii. a copyright notice;++ iii. a notice that refers to this Public License;++ iv. a notice that refers to the disclaimer of+ warranties;++ v. a URI or hyperlink to the Licensed Material to the+ extent reasonably practicable;++ b. indicate if You modified the Licensed Material and+ retain an indication of any previous modifications; and++ c. indicate the Licensed Material is licensed under this+ Public License, and include the text of, or the URI or+ hyperlink to, this Public License.++ 2. You may satisfy the conditions in Section 3(a)(1) in any+ reasonable manner based on the medium, means, and context in+ which You Share the Licensed Material. For example, it may be+ reasonable to satisfy the conditions by providing a URI or+ hyperlink to a resource that includes the required+ information.++ 3. If requested by the Licensor, You must remove any of the+ information required by Section 3(a)(1)(A) to the extent+ reasonably practicable.++ 4. If You Share Adapted Material You produce, the Adapter's+ License You apply must not prevent recipients of the Adapted+ Material from complying with this Public License.+++Section 4 -- Sui Generis Database Rights.++Where the Licensed Rights include Sui Generis Database Rights that+apply to Your use of the Licensed Material:++ a. for the avoidance of doubt, Section 2(a)(1) grants You the right+ to extract, reuse, reproduce, and Share all or a substantial+ portion of the contents of the database for NonCommercial purposes+ only;++ b. if You include all or a substantial portion of the database+ contents in a database in which You have Sui Generis Database+ Rights, then the database in which You have Sui Generis Database+ Rights (but not its individual contents) is Adapted Material; and++ c. You must comply with the conditions in Section 3(a) if You Share+ all or a substantial portion of the contents of the database.++For the avoidance of doubt, this Section 4 supplements and does not+replace Your obligations under this Public License where the Licensed+Rights include other Copyright and Similar Rights.+++Section 5 -- Disclaimer of Warranties and Limitation of Liability.++ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.++ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.++ c. The disclaimer of warranties and limitation of liability provided+ above shall be interpreted in a manner that, to the extent+ possible, most closely approximates an absolute disclaimer and+ waiver of all liability.+++Section 6 -- Term and Termination.++ a. This Public License applies for the term of the Copyright and+ Similar Rights licensed here. However, if You fail to comply with+ this Public License, then Your rights under this Public License+ terminate automatically.++ b. Where Your right to use the Licensed Material has terminated under+ Section 6(a), it reinstates:++ 1. automatically as of the date the violation is cured, provided+ it is cured within 30 days of Your discovery of the+ violation; or++ 2. upon express reinstatement by the Licensor.++ For the avoidance of doubt, this Section 6(b) does not affect any+ right the Licensor may have to seek remedies for Your violations+ of this Public License.++ c. For the avoidance of doubt, the Licensor may also offer the+ Licensed Material under separate terms or conditions or stop+ distributing the Licensed Material at any time; however, doing so+ will not terminate this Public License.++ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public+ License.+++Section 7 -- Other Terms and Conditions.++ a. The Licensor shall not be bound by any additional or different+ terms or conditions communicated by You unless expressly agreed.++ b. Any arrangements, understandings, or agreements regarding the+ Licensed Material not stated herein are separate from and+ independent of the terms and conditions of this Public License.+++Section 8 -- Interpretation.++ a. For the avoidance of doubt, this Public License does not, and+ shall not be interpreted to, reduce, limit, restrict, or impose+ conditions on any use of the Licensed Material that could lawfully+ be made without permission under this Public License.++ b. To the extent possible, if any provision of this Public License is+ deemed unenforceable, it shall be automatically reformed to the+ minimum extent necessary to make it enforceable. If the provision+ cannot be reformed, it shall be severed from this Public License+ without affecting the enforceability of the remaining terms and+ conditions.++ c. No term or condition of this Public License will be waived and no+ failure to comply consented to unless expressly agreed to by the+ Licensor.++ d. Nothing in this Public License constitutes or may be interpreted+ as a limitation upon, or waiver of, any privileges and immunities+ that apply to the Licensor or You, including from the legal+ processes of any jurisdiction or authority.++=======================================================================++Creative Commons is not a party to its public+licenses. Notwithstanding, Creative Commons may elect to apply one of+its public licenses to material it publishes and in those instances+will be considered the “Licensor.” The text of the Creative Commons+public licenses is dedicated to the public domain under the CC0 Public+Domain Dedication. Except for the limited purpose of indicating that+material is shared under a Creative Commons public license or as+otherwise permitted by the Creative Commons policies published at+creativecommons.org/policies, Creative Commons does not authorize the+use of the trademark "Creative Commons" or any other trademark or logo+of Creative Commons without its prior written consent including,+without limitation, in connection with any unauthorized modifications+to any of its public licenses or any other arrangements,+understandings, or agreements concerning use of licensed material. For+the avoidance of doubt, this paragraph does not form part of the+public licenses.++Creative Commons may be contacted at creativecommons.org.diff --git a/README.md b/README.mdindex fc3acb9..e8da020 100644--- a/README.md+++ b/README.md@@ -9,7 +9,7 @@</p><p align="center">- <strong>Generative video, image, and character training on your Mac.</strong><br>+ <strong>Generative video, music, image, and character training on your Mac.</strong><br>MLX. No PyTorch, no CUDA, no cloud, no API key.<br><a href="https://x.com/PhospheneAI">@PhospheneAI</a> on X · <a href="https://github.com/mrbizarro/phosphene">github.com/mrbizarro/phosphene</a></p>@@ -19,7 +19,7 @@</p>-> **Current release: v4.13.2.** **Stop means stop**: pressing Stop while Turbo is still preparing no longer lets the render start afterwards; H3 LoRAs imported before 4.13.1 are applied at their trained strength again; very large Upscale ×2 canvases decode safely (or are refused up front); a failed Turbo companion download is not retried by every job; a silent clip stays silent after Upscale ×2. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).+> **Current release: v4.14.0.** **Songs, faces and sound**: **Audio → Compose** writes whole songs with vocals from your lyrics and a style (YuE2 by Multimodal Art Projection, MLX port by vanch007; about real time on an M4 Max, 11 GB). **Upscale & Face Fix** sharpens faces and doubles the size of any clip in one click, from the player, Outputs, the queue or the Editor. The Editor gets **sound tracks**: A3, A4 and more, a Sound pool, and clip sound on two lanes so neighbouring shots can crossfade. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).## Overview@@ -31,6 +31,29 @@ A 7-second character clip with synced audio renders in roughly 6 minutes on an MThe interface adapts to the machine it runs on. Under 48 GB of unified memory, the panel exposes only what fits in that envelope (text-to-video, image-to-video, and the Image tab). At 48 GB and above, character mode, first/last-frame keyframing, clip extension, and the Q8 HQ pipelines become available. Tier detection runs once at boot and the unsupported surfaces are hidden rather than greyed out.+## Engines++LTX, Hailuo H3 and YuE2 are peers with their own jobs and install sizes:++| Engine | Surface | Weights | Unified memory |+|---|---|---|---|+| **LTX-Video 2.5** | Video, including Audio → Video | ~27.5 GB base; Q8 adds ~37 GB | Adapts to the Mac; advanced modes need more memory |+| **Hailuo H3** | Video with dialogue and sound | ~75 GB; Q8 DiT adds ~22 GB | 36 GB+ with the Q8 DiT; 60 GB+ for full bf16 |+| **YuE2** | Audio → Compose: vocals and arrangement from lyrics and a style | ~11 GB | 24 GB or more |++YuE2 arrives through **Install the music engine** in the Pinokio sidebar.+Compose offers section-tagged lyrics, a prose style, an Instrumental pill,+three score modes, Draft/Final quality and a maximum length. Songs appear as+48 kHz stereo WAVs in the gallery; **Drive video** loads a song into the video+workflow without submitting it. Until the music pack is installed, Audio+keeps its existing layout. [Music engine guide](docs/MUSIC_ENGINE.md).++YuE2 weights use [CC BY-NC 4.0 plus individual-creator permission](LICENSES/YuE2-MODEL_LICENSE.txt):+creators may monetize their songs; companies need a license for the weights.+Code is Apache-2.0. Generated with YuE2 by Multimodal Art Projection · MLX port+by vanch007. On an M4 Max a 3-minute song renders in about 3 minutes (Final)+and a 2-minute Draft in about 1 minute, peaking at 11 GB of memory.+## Features### Videodiff --git a/VERSION b/VERSIONindex 650edfe..c412a4e 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-4.13.2+4.14.0diff --git a/docs/ANALYTICS.md b/docs/ANALYTICS.mdindex 21a14ca..73b802b 100644--- a/docs/ANALYTICS.md+++ b/docs/ANALYTICS.md@@ -364,7 +364,7 @@ what gets *counted*, which is what was wrong.In this order:1. **First line only.** Tracebacks and multi-line detail are discarded.-2. **Exact content redaction.** This job's prompt, negative prompt, image+2. **Exact content redaction.** This job's prompt, negative prompt, music lyrics, music style, imagepath, audio path, output path, character name and training-job id areremoved by exact substring match → `<redacted>`. This is the defense thatmatters: the realistic leak is an exception that quotes your prompt back.diff --git a/docs/API.md b/docs/API.mdindex 7e1975b..8900aff 100644--- a/docs/API.md+++ b/docs/API.md@@ -705,6 +705,7 @@ The Editor is a **top-level workflow**, not a stage of the storyboard: engine-ag| `GET /storyboard/edit/peaks?id=<bid>` | The waveform. Hundreds of KB — fetch once, **never on a poll**. `404` until `prepare` has run. || `GET /storyboard/edit/proxy?id=<bid>&name=<file>.mp4` | A proxy video, served with **range support**. Safari will not seek a `<video>` whose server answers plain `200`, which would undo the entire reason proxies exist. `name` must match `[A-Za-z0-9._-]{1,120}\.mp4` — it is a basename the server minted, so anything else is a probe. || `GET /storyboard/edit/uploads` | Videos the user brought with them (`panel_uploads/timeline/`, newest first, capped at 200). Kept out of `OUTPUT` on purpose, which is why they need a route at all; images do not, they land in the library the gallery already walks. |+| `GET /storyboard/edit/sounds?id=<bid>` | The media pool's **Sound** source: `{sounds: [{path, name, where, mtime}], dir}` — the film's own `audio/` folder (`where: "film"`) first, then the sound files (`.wav .m4a .mp3 .aac .flac .aif .ogg .opus`) at the top of `OUTPUT`, newest first, capped at 300. No probing; the length is read when a sound is added. || `GET /storyboard/edit/drafts?id=<bid>` | `{active, drafts: [...], backup}` — see **Drafts** below. || `GET /storyboard/edit/versions?id=<bid>` | **Metadata only**: name, revision, when kept, clip count, duration, plus `keep` (= `EDIT_HISTORY_KEEP`, 50). The documents themselves are read once, by `restore`, on the user's word. Opening the panel must not be a download. |@@ -714,6 +715,7 @@ The Editor is a **top-level workflow**, not a stage of the storyboard: engine-ag|---|---|---|| `prepare` | `id`, `music`, `target_seconds` | Build proxies + peaks. `400` if `music` is not a file. || `add-clip` | `id`, `from`, `only`, `path`, `title`, `kind` | `kind` is `video` \| `still` \| `slug` — passing it is what stops an image landing as a video with no frames. |+| `add-sound` | `id`, `path` | One file for an **audio track**: probed (`{path, title, duration_s, has_video, imported}`), `400` when it carries no sound. A file outside `OUTPUT` is hardlinked (copied across volumes) into the film's own `audio/` folder first, because `/file` only serves `OUTPUT` and a sound the preview cannot play is half a sound. The strip is placed and saved by the client. || `relink` | `id`, `only` | Re-point clips at their finished (delivery) files. **A finished RETAKE is never part of that batch** — it is offered against its clip with `retake: true` in the payload's `relink` rows and adopted one clip at a time with `only=<clip id>`. || `cancel` | `id` | Cancel the prepare job. || `auto` | `id`, `music`, `target_seconds`, `min_shot`, `max_shot` | Re-run the machine's cut. Lands in the **automatic** lane. |@@ -777,7 +779,24 @@ Video clips only. Same three numbers as the picture, for the SOUND — so the so**The PRESENCE of the field is the switch, not the values in it.** Do not derive "linked" from `audio` equalling the picture window: unlinking writes the window the clip already has, so a clip the user had just unlinked would read as linked and refuse to be dragged. The toggle adds the object or deletes it; nothing else decides. `normalise_edit` rounds the field but **never removes it** for the same reason, and strips it entirely from a still or a slug.-Audio windows may not overlap each other any more than the pictures may. This is still one video track and one music lane — a split edit is a butt join that lands somewhere else, not a mix.+Audio windows may not overlap each other any more than the pictures may. A split edit is a butt join that lands somewhere else, not a mix — the mix is what `audio_tracks` is for.++#### `audio_tracks[]` — A3, A4, … under the music++```jsonc+"audio_tracks": [+ {"id": "t…", "name": "Laughs", "muted": true, "gain": 0.8,+ "strips": [{"id": "k…", "path": "/…/laugh.wav", "start": 0.0, "end": 2.0,+ "film_start": 12.5, "duration": 4.1, "gain": 0.5,+ "muted": true, "locked": true, "title": "laugh (copy)",+ "afx": {"fade_in": 0.5, "fade_out": 0.25, "points": [[1.0, 0.6]]}}]}]+```++Any number of tracks, each holding any number of strips. `start`/`end` are the in/out points inside the file (a strip plays at 1x, so it is `end - start` long on the film); `film_start` is a timeline second, laid out with `adelay` exactly as the bed is. `afx` is the same envelope object a clip's sound and the bed carry, read by `audio_gain_points`; the strip's `gain` and the track's `gain` (linear 0–1) multiply it — `track_strip_gain_points` is the one curve the preview, the render and the export read. **Absent is none and neutral is absent**: an edit with no tracks has no key, so it loads, saves and renders byte-identically; an empty track is kept.++**Strips on the same track may not overlap** (`audio_track_strips_overlap`, an error, `TOUCH_TOLERANCE` for a butt join); strips on different tracks overlap and mix. Shape errors: `audio_tracks_shape`, `audio_track_shape`, `audio_track_name`, `audio_track_muted`, `audio_track_gain(_range)`, `audio_track_strips`, `track_strip_shape`, `track_strip_path`, `track_strip_start`, `track_strip_end`, `track_strip_film_start`, `track_strip_window`, `track_strip_past_the_end`, `track_strip_gain(_range)`, `track_strip_muted`, `track_strip_locked`, `track_strip_title`, `track_strip_afx*`.++**Render:** every audible strip (not muted, track not muted, curve not silent) is one `-vn -i` after the overlays, `atrim` → `volume` (its curve, on the strip clock) → `aresample` → `adelay` (in samples) → `apad` → `atrim` to the film, and all of them are `amix`ed (`normalize=0`, `duration=first`) over the clips' sound and the bed under the one `asoftclip` limiter; the film facts carry `sound_strips` and `mix_peak`. A strip whose file is gone refuses the render with its path and track. **Export:** each track is its own FCP7 audio track (clipitems with in/out, level keyframes, `<enabled>FALSE</enabled>` for a mute) and each strip an After Effects layer named `<track> · <title>`.#### `transitions[]` — a typed object that owns a BOUNDARYdiff --git a/docs/MUSIC_ENGINE.md b/docs/MUSIC_ENGINE.mdnew file mode 100644index 0000000..a4a13de--- /dev/null+++ b/docs/MUSIC_ENGINE.md@@ -0,0 +1,169 @@+# YuE2 — Phosphene's music engine++YuE2 by Multimodal Art Projection writes vocals and an arrangement together+from lyrics and a style description. It sits beside LTX and Hailuo H3 as a+peer engine. Install **the music engine (YuE2, ~11 GB)** from the Phosphene+sidebar in Pinokio, then open **Audio → Compose**. Without its pack, Audio+keeps its existing Drive video surface; Settings → Models offers the install.++## Memory, length and estimates++The floor is **24 GB unified memory** (`MUSIC_MIN_RAM_GB`). Peaks+measured 11.0 GB on this integration's runs (see below). Installation+requires **14 GB free** on the weights volume; the pack occupies about+10.5 GB. Repairs verify existing files and need space only for missing bytes.++Length follows the lyrics. **Max length** is a ceiling, not a requested song+length: it truncates a longer song and never stretches a shorter one. The+form offers 30–360 seconds in 15-second steps, initially 4:00. The runner's+8–360-second clamp also applies to API requests.++The estimate prices a song that runs to Max length, fitted to receipts+taken on an M4 Max 64 GB (8-bit AR): **Final** (32 steps) rendered 177.8 s of+audio in 180.2 s, 120 s in 113.8 s and 60 s in 58.5 s; **Draft** (8 steps)+rendered 120 s in 64.2 s. Score planning and resident loads add about 12 s.+The model is `12 s + seconds × 0.93` (Final) or `× 0.43` (Draft), scaled for+other chips by the LTX speed table. It is always labelled an estimate: most+songs end sooner, and a cold first load is not in the fit. Every run peaked at 11.0 GB of process+footprint (MLX peak 10.5 GiB). The constants sit in one block beside+`music_paths()` in `mlx_ltx_panel.py`.++## How it plugs in++```+POST /queue/add (mode=music, engine=music, music_*)+ → make_job → worker_loop → run_job_inner → run_music_job_inner+ → refuse if a command-line GPU lock exists → park LTX helper+ → yue2-mlx/.venv/bin/python scripts/music/yue2_run.py+ → [music] stdout progress → Now card+ → mlx_outputs/music_<stamp>_<slug>.wav + .wav.json+```++Music shares the queue's GPU mutex, which already serialises every job in+the panel. The panel never creates, deletes or reclaims a shared lock file. It+only reads the two paths command-line GPU jobs use (`/tmp/phosphene_gpu.lock`+and `~/AI/projects/hailuo-mlx/.gpu_lock`) and refuses, naming the path, while+one exists. The LTX helper is killed to release its resident weights and+returns lazily on the next LTX job. Stop sends SIGTERM to the owned music+process group, then SIGKILL after eight seconds if the group is still active.+If a Stop lands while the song is being written, the job's files are removed,+so "Nothing was saved" stays true. `state/music_running.json` registers the+runner with the existing orphan reaper.++### Why a separate venv++The pinned MLX port needs **Python 3.12 and mlx 0.32.2**. LTX's Python 3.11+venv remains pinned to mlx 0.31.1. Install and Update use the music checkout's+lockfile with `uv sync --frozen --no-dev`; music is torch-free.++## Paths and installation++| Item | Default | Override |+|---|---|---|+| Engine checkout | `yue2-mlx/` | `LTX_MUSIC_ROOT` |+| Engine venv | `yue2-mlx/.venv/` | follows engine root |+| Weights | `mlx_models/yue2/` | `LTX_MUSIC_MODELS` |+| Phosphene runner | `scripts/music/yue2_run.py` | owned by the panel |+| Engine revision | `scripts/music/engine_pin.txt` | change only after validation |++Set root overrides in Pinokio's `ENVIRONMENT` file; the menu and panel read+the same names. The engine directory is ignored by git. Install clones+`vanch007/mlx-Yue`, fetches the pinned SHA and checks it out detached with+`--force`. Update repeats that pin and frozen sync only for an installed+engine, then runs the offline pack check. It does not download music weights.+Repair rebuilds a missing/broken Python 3.12 venv and keeps intact weights.++`scripts/pinokio/music_fetch.py` is the single downloader and verifier. It+inherits `HF_HOME`, stages downloads under `.staging/`, checks manifest+SHA-256s and moves files into place. Weights come straight from the public+repos the pinned port documents, each at a pinned revision: the MLX generator+from `vanch007/mlx-Yue2-3B` (its BF16 tensors are byte-identical to+`m-a-p/YuE2-3B`) and the decoder from `m-a-p/YuE2-Vae` (the original file).+Phosphene re-hosts nothing. A receipt, `pack_source.json`, records source+repositories, revisions and every file hash.++The generator directory must contain exactly its `conversion.json` files+map, the manifest, and at most a README. Only the declared `licenses/`+ancestors are allowed. HF's `.cache/` belongs in staging, never in generator;+a repair moves a leftover cache there. The VAE contains its model, config,+manifest and notices. Its model has a pinned SHA-256 as well as a manifest+hash. The current model permission and Phosphene notice live at the pack+root so they do not violate the generator's strict tree.++```sh+yue2-mlx/.venv/bin/python scripts/pinokio/music_fetch.py --check+yue2-mlx/.venv/bin/python scripts/pinokio/music_fetch.py --min-free-gb 14+```++`--check` is offline, prints missing/corrupt/unexpected entries, and exits+0/1. Panel status uses sizes and the manifest shape instead of hashing+10.5 GB on every poll. Install, Repair and Update perform full verification.++## Composing++Write section tags on their own lines, words beneath them, and leave a+blank line between sections:++```+[Verse]+The station lights are fading+Your footsteps find the street++[Chorus]+Carry the morning home+```++`[Pre-Chorus]`, `[Bridge]` and `[Outro]` are also section markers. A section+with no words is instrumental. Style is prose: genre, instruments, singer,+language and tempo in one description. The Instrumental pill keeps the+lyrics text in the browser but sends none of it; it passes `--instrumental`.++Score modes are **Melody + chords** (`full`, default), **Melody only**+(`melody`) and **No score** (`off`). YuE2 writes a sheet-music plan before+the song. Draft maps to 8 synthesis steps; Final maps to 32 (default).+Seed -1 chooses a random seed. All seven `music_*` fields survive the+form-urlencoded queue path and are persisted in the job.++## Outputs and the video handoff++The runner writes **48 kHz stereo PCM-24 WAV** and its `.wav.json` sidecar.+Audio cards use the existing outputs stream, with native audio controls.+The info panel shows style, lyrics, seed, actual length, natural ending+versus the ceiling, and the ABC score. The sidecar also records the job id,+engine pin and weight-source revisions. Delete/Trash carries it with the WAV.++**Drive video** loads a song into the existing Audio → Video workflow and+switches to that mode. It does not submit a render. Its normal video memory+and model requirements still apply. Settings → Storage can remove the music+weights; doing so hides Compose and leaves Drive video available.++## License and attribution++Weights use CC BY-NC 4.0 plus the upstream individual-creator permission:+individual creators may monetize their songs; companies need a license for+the weights. Read [the full current model license](../LICENSES/YuE2-MODEL_LICENSE.txt).+The port and upstream code are Apache-2.0; Oobleck VAE and SnakeBeta are MIT.+[The notice](../LICENSES/NOTICE-yue2.md) identifies the source and conversion.+BF16 weights are byte-identical to their source; 8-bit AR is a quantization.+The Compose footer credits Multimodal Art Projection and vanch007.++## Validation and troubleshooting++`test_music_engine.py` covers status, pack checks, the real HTTP handler's+form parsing, argv/provenance, progress, WAV MIME/ranges/gallery/Trash,+process ownership, and an unchanged Video engine switcher. It uses fake+packs and a stub child; it never loads weights. Run it through pytest with+MLX forced to CPU, then run `bash scripts/release_gates.sh --fast`.++A complete **from-zero Pinokio install, local ETA/memory measurements and+the owner's listening gate remain pending**. No music inference was run for+this integration. A passing fake-pack test does not validate song quality.++- **Weights present, engine unavailable:** choose Repair in Pinokio. It+ restores the interpreter and pinned code without downloading intact weights.+- **Missing file or hash mismatch:** run Repair; `--check` names the file.+- **Unexpected generator entry:** move only the named extra entry out of+ `generator/`; do not put notes or HF cache directories in that tree.+- **GPU busy:** the refusal names a lock file. Let that job finish; if nothing+ is running, the lock was left by a command-line job and can be deleted.+- **Stopped:** no partial WAV is published; the next job starts a fresh child.diff --git a/docs/RELEASE_CHECKLIST.md b/docs/RELEASE_CHECKLIST.mdindex 985cd96..7f4202e 100644--- a/docs/RELEASE_CHECKLIST.md+++ b/docs/RELEASE_CHECKLIST.md@@ -35,6 +35,20 @@ This does NOT replace the sections below. From-zero, the Ideogram eyeball, thesmoke renders, the weight mirror and the update-path gate all need a human anda real machine.+## Music — from-zero install and listening gate++- [ ] On a fresh Pinokio install with empty music weights and no cached HF+ files, use **Install the music engine (YuE2, ~11 GB)**. Verify the isolated+ Python 3.12 venv, pinned checkout, frozen sync, resumable staged downloads,+ full SHA-256 check and clean generator tree. Open Audio → Compose, make a+ real song, play its WAV, inspect the sidecar and credit, and use **Drive+ video** without an automatic submission. Test Stop, Repair with weights+ kept, and Update's offline check. Record memory and timing at Draft/Final;+ the ETA table stays unmeasured until receipts exist. The owner's listening+ verdict and explicit ship instruction are required. YuE2: the owner ordered+ the ship on 2026-09-17 (v4.14.0); the real 10.5 GB download on a clean Mac is+ still unrun.+## 1. Ideogram — from-zero render gate (the one that keeps biting us)```diff --git a/docs/STATE.md b/docs/STATE.mdindex e838b55..47b9214 100644--- a/docs/STATE.md+++ b/docs/STATE.md@@ -1,5 +1,74 @@# Phosphene — project state, history, open work+> **🎵 2026-09-17 — v4.14.0 released (public, tag `v4.14.0`): "Songs, faces and sound".**+> Owner's order: "Let's make a release because I think there are too many things to release at the moment." No further+> Codex round for this release (owner). Ships everything on dev: **Audio → Compose (YuE2)**, **Upscale & Face Fix** (renamed+> ×2 lane, one-click on any clip, optional after-draft pass), and the **Editor sound** work (audio tracks A3/A4…, Sound pool ++> Add sound, track lanes, Duplicate on sound, clip sound on lanes A/B with crossfade, sound lanes that shrink when idle).+> It also announces what 4.13.1/4.13.2 shipped quietly (H3 High 15 steps, full last frame, Turbo adapter, ×2 white flash,+> Stop fixes, LoRA strength restore, CivitAI search #82 by @Viktorminator).+> **History:** dev now CONTAINS public main — merge commit `d9f642a` (parents dev `1729ce0` + public `e1d500e`), a three-way+> merge on base `0e726de` (the dev commit whose tree equals public v4.13.0). Two text conflicts, both dev's side+> (mlx_ltx_panel.py: dev's Face Fix wording, face_fix_form chain, music_pgid in Stop; docs/STATE.md: dev's entries are a+> superset); resolved mlx_ltx_panel.py is byte-identical to dev, i.e. public carried no code dev lacked. Public main still+> advances by ONE snapshot commit (docs/RELEASE_CHECKLIST.md — a dev-branch push would publish ~690 private commits), and+> dev then merges that snapshot (tree-identical), so `git log dev..origin/main` is empty.+> **Credit:** YuE2 by Multimodal Art Projection (m-a-p), CC BY-NC 4.0 + individual-creator permission; MLX port by vanch007+> (Apache-2.0). CivitAI search fix #82 by @Viktorminator.++> **🧑🎨 2026-09-17 — "Upscale ×2 / LTX Upscale" is now Upscale & Face Fix, and a one-click clip action (UNRELEASED, beta; waits for owner use).**+> Owner: the upscaler "that fixes the faces has the wrong name … should be optional and something you can do to an existing clip."+> **Rename (user-visible only):** Remix chip, lane ("Clip to fix"), player button, card chip, history button, queue label, info panel+> (Mode + Recipe), log lines, Models entry, docs (`#docs/remix/upscale-face-fix`; the old name is kept once for search). Internal+> ids unchanged: `mode=upscale`, `h3_upscale=ltx_x2`, `upscale_source_path/keep_shot/upscale_start/upscale_steps`.+> **Recipe:** `FACE_FIX_RECIPE` = keep_shot 1.0 + start=source + **1** refine step (the 09-16 face-safe setting). The lane's+> **Faithful** pill is unchanged (keep_shot 1.0 → **3** steps); a new first pill **Face Fix** (1 step) is the lane default.+> **One click:** `POST /queue/facefix` → `queue_face_fix()` (clip's own prompt/seed/label from its sidecar, One Shot takes use the+> take's top-level prompt; frames = source count rounded UP to 1+8k so long clips are covered; refuses stills / missing adapter /+> size cap / undecodable length up front; a second click on a queued OR rendering fix returns the same job). Doors: player split+> button (click = queue, ⚙ half = open the lane), Outputs card chip (video only), history "Face Fix" on finished videos, Editor+> clip bar "Face Fix ×2" + right-click "Upscale & Face Fix". The fixed clip is a new `<stem>_x2_<stamp>.mp4`; nothing is overwritten.+> **Editor swap:** orders record `state/storyboards/<id>/face_fix.json` (`params.face_fix_targets`, all askers answered; the worker+> writes `to` + `complete`); `_sbe_relinks` offers only while the clip still plays the source and the fix covers every frame.+> The tick fetches offers (never `sbeLoad`) when history shows a done job naming this film (survives reload/retry). **Swap it in**+> is a LOCAL undoable edit (`sbeFaceFixSwap`: path + proxy from add-clip; in/out, speed, fades, place untouched), never a server+> rewrite. `/storyboard/edit/relink` also accepts `to` (a retake and a fix on one clip).+> **Optional:** the H3 after-draft pass is now a checkbox "Also run Upscale & Face Fix after the draft", off by default and no longer+> restored from localStorage on reload (it used to stick). The chain uses the 1-step recipe (was the form's keep_shot → 3 steps),+> carries the draft's frame count, and its queue label finally lands (`preset_label`; the old `label` key was dropped by make_job).+> **Proof:** live 8199 (restarted idle), real click on the player button → job `j-1a0af0dd254-001`, 640×384 124 f H3 draft →+> 1280×768 124 f + audio in 154 s, 1-step refine logged, sidecar `display_name`/`face_fix`. Editor offer + swap verified on a+> scratch panel (:8421, copied film): in/out 0.5–4.0 kept. Screenshots: PM hub `notes/face-fix-rename/`.+> **Gates:** `test_face_fix` 23 new; `release_gates.sh --fast` on the merged tree 98 PASS / 0 FAIL / 2 SKIP (MLX on CPU); editor UI suite run separately, green. Codex: 5 rounds on the diff, every+> confirmed finding fixed (round 5's merge-race items removed by the local-edit swap); stopped on the owner's word before a+> final SHIP-SAFE round.++> **🎵 2026-09-17 — YuE2 is the music engine: Audio → Compose (UNRELEASED, beta; headline feature, waits for owner use).**+> **What:** YuE2-3B (Multimodal Art Projection) writes whole songs, vocals and arrangement, from lyrics and a+> style sentence. Phosphene did NOT port it: the MLX port is vanch007/mlx-Yue, pinned at `9253ed1`, in its+> own Python 3.12 / mlx 0.32.2 venv under `yue2-mlx/`. Weights come straight from the public repos at pinned+> revisions (vanch007/mlx-Yue2-3B `fa66d20`, m-a-p/YuE2-Vae `95535e7`); nothing is re-hosted (owner ruling).+> All 628 BF16 tensors were proven byte-identical to m-a-p/YuE2-3B, and `ar-8bit` re-quantizes bit-for-bit+> on the GPU. Ours: `scripts/music/yue2_run.py` (stage-line progress, SIGTERM stop, a desktop-tolerant+> memory guard, a provenance sidecar), `install_music.js` + `scripts/pinokio/music_*`, and the Compose form+> inside the existing Audio tab (lyrics, style, Instrumental, Score full/melody/off, Draft 8 / Final 32,+> Max length as a ceiling, seed). Songs are WAV cards with a player, info and a Drive video chip. Credit+> appears on the form, the card chip and the docs.+> **Measured (M4 Max 64 GB, 8-bit AR):** Final renders 177.8 s of song in 180.2 s; Draft renders 120 s in+> 64 s; peak is 11.0 GB at every length. Music3 needed 415 s and 53 GB for 60 s. A Whisper lyric check heard+> the lyrics in order (recall 0.75–0.94), and the instrumental carries no vocal line. Receipts and songs:+> PM hub `notes/yue2/`.+> **Validated:** a from-zero install lane (fresh clone, fresh uv Python, empty HF_HOME, pinned checkout,+> frozen sync, fetcher; the big weights were pre-seeded as hard links because disk was at 11 GB, and+> everything else downloaded for real) → the panel boots `available`. `/queue/add` wrote a real song in+> 155 s. Stop mid-song leaves nothing behind. `/file` answers `audio/wav` with ranges. The card, info modal+> and Now card were checked in the browser. Three Codex review rounds (smartest model): 7 + 6 + 3 findings,+> all fixed (the panel never writes shared lock files; Stop targets the exact song; a late Stop deletes the+> job's files; resumable and space-safe fetch; an absolute venv path; menu entries while running).+> `test_music_engine` 40; `release_gates.sh --fast` 97 PASS / 0 FAIL / 2 SKIP (MLX on the CPU).+> **Not yet:** the owner's ear; a real 10.5 GB download on a clean Mac; a cold-first-load timing; the+> Pinokio-driven install click. Public release waits for the owner's use (headline rule).+> **🛑 2026-09-17 — v4.13.2 released (public, tag `v4.13.2`): "Stop means stop" — five fixes from an independent review of 4.13.1.**> **Why:** Codex re-reviewed the shipped 4.13.1 (PM hub `notes/ship-review-0917/REVIEW.md`): NOT ship-safe, 1 P1 + 4 P2.> Each was reproduced on `efe5fcf` with CPU-only probes before fixing (`scratchpad/hotfix/repro_shipped.py`).diff --git a/install_music.js b/install_music.jsnew file mode 100644index 0000000..89c4c3b--- /dev/null+++ b/install_music.js@@ -0,0 +1,27 @@+// YuE2 is a peer engine. Python 3.12 and mlx==0.32.2 require its own venv;+// LTX stays on Python 3.11 / mlx==0.31.1. Repairs keep verified weights.+const fs = require("fs")+const path = require("path")+const MUSIC_PIN = fs.readFileSync(path.join(__dirname, "scripts/music/engine_pin.txt"), "utf8").trim()+if (!/^[0-9a-f]{40}$/.test(MUSIC_PIN)) throw new Error("Invalid YuE2 engine pin")+module.exports = {+ requires: { bundle: "ai" },+ run: [+ { method: "notify", params: {+ html: "<b>Installing YuE2 (the music engine, ~11 GB).</b><br>Writes a full song — vocals, arrangement and all — from lyrics and a style description, and sits beside LTX and Hailuo H3 as a peer. Needs a 24 GB+ Apple Silicon Mac. Resumable if interrupted."+ } },+ { method: "shell.run", params: { message: "bash scripts/pinokio/music_preflight.sh" } },+ { method: "shell.run", params: { message: "bash scripts/pinokio/music_clone.sh" } },+ // Both lanes read and validate engine_pin.txt.+ { method: "shell.run", params: {+ message: "bash scripts/pinokio/music_checkout.sh \"${LTX_MUSIC_ROOT:-$PWD/yue2-mlx}\""+ } },+ { method: "shell.run", params: { message: "bash scripts/pinokio/music_venv.sh \"${LTX_MUSIC_ROOT:-$PWD/yue2-mlx}\"" } },+ { method: "shell.run", params: { message: "bash scripts/pinokio/music_sync.sh \"${LTX_MUSIC_ROOT:-$PWD/yue2-mlx}\"" } },+ // Preserve Pinokio's HF_HOME rather than substituting a different cache.+ { method: "shell.run", params: { message: "\"${LTX_MUSIC_ROOT:-$PWD/yue2-mlx}/.venv/bin/python\" scripts/pinokio/music_fetch.py --min-free-gb 14" } },+ { method: "notify", params: {+ html: "<b>YuE2 ready.</b><br>Open Audio → Compose to write a song. Generated with YuE2 by Multimodal Art Projection · MLX port by vanch007."+ } }+ ]+}diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.pyindex 64fdb45..72f1b07 100644--- a/mlx_ltx_panel.py+++ b/mlx_ltx_panel.py@@ -1525,7 +1525,7 @@ CURATED_LORAS: dict[str, dict] = {"name": "Pixel Spatial Upscaler ×2 (LTX-2.5)","description": "Lightricks' LTX-2.5 IC-LoRA that re-renders a finished ""clip at twice the size, inventing real detail instead of "- "interpolating pixels. Drives the Upscale ×2 mode; takes "+ "interpolating pixels. Drives Upscale & Face Fix; takes ""the source clip on the IC reference channel. Gated on ""HF (license click) — mirrored on the Phosphene release.","repo_id": "Lightricks/LTX-2.5-22b-IC-LoRA-Pixel-Spatial-Upscaler",@@ -5593,6 +5593,11 @@ def storage_rows() -> list[dict]:"planner run on.","removable": False,})+ music_bytes = _dir_size_bytes(MUSIC_MODELS)+ if music_bytes:+ rows.append({"key": "music", "name": "YuE2 weights", "paths": [str(MUSIC_MODELS)],+ "bytes": music_bytes, "size": _fmt_gb(music_bytes), "removable": True,+ "note": "Removing this turns off Compose in the Audio tab. Audio → Video is unaffected — it uses tracks you already have."})return rows@@ -7287,6 +7292,7 @@ STATE: dict = {# video engine — a `caffeinate → python → ffmpeg` tree outside HELPER).# /stop and the atexit hook kill it by pgid, same contract as train_pgid."h3_pgid": None,+ "music_pgid": None,}LOCK = threading.RLock()QUEUE_COND = threading.Condition(LOCK)@@ -12100,9 +12106,9 @@ def _h3_export_notes(w: int, h: int) -> dict[str, str]:_cap = 0_sc = min(2.0, _cap / float(max(w, h))) if _cap else 2.0_tw, _th = ltx_floor_canvas(int(w * _sc), int(h * _sc))- out[mode] = (f"LTX ×2: after the draft, an Upscale ×2 job is queued that re-renders "- f"it at {_tw}×{_th} with LTX-2.5 generated detail and keeps the sound. "- "Faithful preset: about the draft's time again."+ out[mode] = (f"{FACE_FIX_NAME}: after the draft, a second job re-renders it at "+ f"{_tw}×{_th} with LTX-2.5 detail, keeps the face and the sound, and "+ "lands beside the draft. About the draft's time again."+ ("" if _adapter_ok else" Needs the 0.3 GB Upscale adapter first — Settings → Models."))continue@@ -12424,6 +12430,302 @@ def h3_status() -> dict:return result+# YuE2 receipts, measured 2026-09-17 on an M4 Max 64 GB (8-bit AR, runner+# sidecars in the PM hub notes/yue2/MEASUREMENTS.md):+# Final 32 steps: 177.8 s song in 180.2 s · 120.0 s in 113.8 s · 60.0 s in 58.5 s+# Draft 8 steps: 120.0 s song in 64.2 s+# Score planning + resident loads ≈ 12 s per song; peak process footprint+# 11.0 GB (MLX peak 10.5 GiB) on every length. 24 GB Macs are known to work+# (yue2-studio's M5 Pro 24 GB receipts), hence the floor.+# Wall ≈ MUSIC_FIXED_SEC + audio seconds × rate, scaled for other chips by the+# LTX speed table (both are MLX GPU work). The slider is a ceiling, so this+# prices a song that runs to Max length; most songs end sooner.+MUSIC_MIN_RAM_GB = 24.0+MUSIC_SAMPLE_RATE = 48000+MUSIC_CHANNELS = 2+MUSIC_QUALITY_STEPS = {"draft": 8, "final": 32}+MUSIC_FIXED_SEC = 12.0+MUSIC_SECONDS_PER_AUDIO_SECOND = {"draft": 0.43, "final": 0.93}+MUSIC_ROOT = ROOT / Path(os.environ.get("LTX_MUSIC_ROOT", "yue2-mlx")).expanduser()+MUSIC_MODELS = ROOT / Path(os.environ.get("LTX_MUSIC_MODELS", "mlx_models/yue2")).expanduser()+MUSIC_RUNNER = ROOT / "scripts/music/yue2_run.py"+MUSIC_ENGINE_PIN = (ROOT / "scripts/music/engine_pin.txt").read_text().strip()+# Lock paths that command-line GPU jobs (the H3 lab's scripts) create while they+# run. Music only READS them: inside Phosphene the queue already serialises GPU+# work, so the panel never creates, deletes or reclaims a shared lock — which+# is what makes a stale or raced lock impossible on this side.+MUSIC_GPU_DIR_LOCK = Path.home() / "AI/projects/hailuo-mlx/.gpu_lock"+MUSIC_GPU_FILE_LOCK = Path("/tmp/phosphene_gpu.lock")+++def _music_python() -> Path | None:+ for p in (MUSIC_ROOT / ".venv/bin/python", MUSIC_ROOT / ".venv/bin/python3.12"):+ if p.is_file() and os.access(p, os.X_OK):+ return p+ return None+++def music_capable() -> bool:+ return SYSTEM_RAM_GB >= MUSIC_MIN_RAM_GB+++def music_paths() -> dict:+ from scripts.pinokio.music_fetch import pack_problems+ missing = pack_problems(MUSIC_MODELS)+ weights_ok = not missing+ python = _music_python()+ runner_ok = MUSIC_RUNNER.is_file() and (MUSIC_ROOT / "pyproject.toml").is_file()+ built = (MUSIC_ROOT / ".venv/pyvenv.cfg").is_file()+ if not runner_ok:+ missing.append(f"runner / checkout under {MUSIC_ROOT}")+ if python is None:+ missing.append(f"venv python under {MUSIC_ROOT / '.venv'}")+ reason = ("ok" if not missing else+ "not_installed" if not weights_ok and not (built or (MUSIC_ROOT / "pyproject.toml").is_file()) else+ "missing_weights" if not weights_ok else+ "missing_venv" if python is None else "missing_runner")+ return {"root": str(MUSIC_ROOT), "models": str(MUSIC_MODELS),+ "runner": MUSIC_RUNNER, "python": python,+ "generator": MUSIC_MODELS / "generator", "vae": MUSIC_MODELS / "vae",+ "missing": missing, "reason": reason, "weights_ok": weights_ok,+ "runner_ok": runner_ok, "venv_ok": python is not None,+ "venv_broken": built and python is None,+ "repairable": weights_ok and bool(missing)}+++def music_estimate(quality: str, seconds: int) -> dict:+ """A fit to the M4 Max receipts above, scaled by chip. Never a measurement:+ songs usually end before Max length, and cold first loads are unmeasured."""+ wall = (MUSIC_FIXED_SEC + seconds * MUSIC_SECONDS_PER_AUDIO_SECOND[quality]) * _hw_speed_factor("ltx")+ return {"eta_sec": round(wall), "eta": _fmt_eta(wall / 60), "eta_measured": False}+++def music_status() -> dict:+ paths = music_paths()+ return {**{k: paths[k] for k in ("root", "models", "missing", "reason", "repairable",+ "weights_ok", "runner_ok", "venv_ok", "venv_broken")},+ "capable": music_capable(), "available": not paths["missing"],+ "installed": not paths["missing"], "min_ram_gb": MUSIC_MIN_RAM_GB,+ "eta_measured": False,+ "estimates": {q: {str(n): music_estimate(q, n) for n in range(30, 361, 15)}+ for q in MUSIC_QUALITY_STEPS}}+++def music_params(form: dict) -> dict:+ """Explicit allowlist shared by queue construction and dispatch/replays."""+ def value(key, default=""):+ v = form.get(key, default)+ if isinstance(v, list):+ v = v[0] if v else default+ return str(v if v is not None else default).strip()+ def integer(key, default):+ try:+ return int(value(key, default))+ except (TypeError, ValueError):+ return default+ instrumental = value("music_instrumental").lower() in ("1", "true", "yes", "on")+ quality = value("music_quality", "final")+ mode = value("music_mode", "full")+ return {"mode": "music", "engine": "music",+ "music_lyrics": "" if instrumental else value("music_lyrics"),+ "music_style": value("music_style"),+ "music_mode": mode if mode in ("full", "melody", "off") else "full",+ "music_instrumental": instrumental,+ "music_max_seconds": max(8, min(360, integer("music_max_seconds", 240))),+ "music_seed": max(-1, min(2**32 - 1, integer("music_seed", -1))),+ "music_quality": quality if quality in MUSIC_QUALITY_STEPS else "final"}+++def music_argv(job: dict, paths: dict, output: Path) -> list[str]:+ p = music_params(job["params"])+ try:+ sources = json.loads((MUSIC_MODELS / "pack_source.json").read_text())["sources"]+ except (OSError, ValueError, KeyError):+ sources = {} # Manual packs have unknown provenance; never invent it.+ provenance = {"job_id": job["id"], "engine": "music", "engine_pin": MUSIC_ENGINE_PIN,+ "pack_sources": sources, "params": p}+ args = [str(paths["python"]), str(paths["runner"]),+ "--model-dir", str(paths["generator"]), "--vae-dir", str(paths["vae"]),+ "--output", str(output), "--sidecar", str(output) + ".json",+ "--extra-json", json.dumps(provenance, ensure_ascii=False),+ "--style", p["music_style"], "--lyrics", p["music_lyrics"],+ "--mode", p["music_mode"], "--steps", str(MUSIC_QUALITY_STEPS[p["music_quality"]]),+ "--max-seconds", str(p["music_max_seconds"]), "--seed", str(p["music_seed"]),+ "--precision", "8bit"]+ if p["music_instrumental"]:+ args.append("--instrumental")+ return args+++def music_progress(line: str, previous: dict | None = None) -> dict | None:+ """Decode the runner's flushed protocol; percentages describe stages."""+ m = re.match(r"^\[music\] (stage|plan|song|synth|decode|done|error)\s*(.*)$", line.strip())+ if not m:+ return None+ phase, detail = m.groups()+ pct = float((previous or {}).get("pct", 0))+ label = ""+ if phase == "stage":+ label, target = {"loading": ("Loading YuE2", 2), "planning": ("Writing score", 5),+ "writing": ("Writing song", 15), "stopping": ("Stopping music", pct)}.get(detail, (detail, pct))+ pct = max(pct, target)+ elif phase == "plan":+ label = f"Writing score · {detail} tokens"+ pct = max(pct, 5)+ elif phase in ("song", "synth", "decode"):+ count = re.fullmatch(r"(\d+)/(\d+)", detail)+ if not count:+ return None+ k, total = map(int, count.groups())+ if not total:+ return None+ start, span, name = {"song": (15, 45, "Writing song"), "synth": (60, 30, "Synthesizing music"),+ "decode": (90, 8, "Decoding audio")}[phase]+ pct = max(pct, start + span * min(1, k / total))+ label = f"{name} · {k}/{total}"+ elif phase == "done":+ pct, label = 100, "Song ready"+ else:+ label = detail+ return {"phase": phase, "phase_label": label, "pct": pct}+++def _music_external_gpu_lock() -> Path | None:+ """The first external GPU lock that exists (file or directory), else None."""+ for path in (MUSIC_GPU_DIR_LOCK, MUSIC_GPU_FILE_LOCK):+ try:+ if path.exists() or path.is_symlink():+ return path+ except OSError:+ continue+ return None+++def _stop_music_proc(grace: float = 8.0, pgid: int | None = None) -> None:+ """SIGTERM a music runner group, SIGKILL it after `grace` if it is still the+ current one. Callers that decided to stop a SPECIFIC job pass its pgid, read+ in the same locked section as the cancel flag, so a worker that advanced in+ between is never hit."""+ if pgid is None:+ with LOCK:+ pgid = STATE.get("music_pgid")+ if not pgid:+ return+ try:+ os.killpg(pgid, signal.SIGTERM)+ except ProcessLookupError:+ return+ def force():+ time.sleep(grace)+ # An old cancellation timer must never kill the next job's group.+ with LOCK:+ if STATE.get("music_pgid") != pgid:+ return+ try:+ os.killpg(pgid, signal.SIGKILL)+ except ProcessLookupError:+ pass+ threading.Thread(target=force, daemon=True, name="stop-music").start()+++atexit.register(_stop_music_proc)+++def run_music_job_inner(job: dict) -> None:+ p = music_params(job["params"])+ paths = music_paths()+ if not music_capable():+ raise RenderRefused("music_ram", f"YuE2 needs about {MUSIC_MIN_RAM_GB:.0f} GB of unified memory; this Mac reports {SYSTEM_RAM_GB:.0f} GB. The rest of Phosphene is unaffected.")+ if paths["missing"]:+ missing = "; ".join(paths["missing"])+ if paths["repairable"]:+ raise RuntimeError(f"The YuE2 weights are on disk but the engine needs repair — missing: {missing}. Click 'Repair the music engine' in the Phosphene sidebar in Pinokio — it is idempotent and skips every weight already on disk, so this is a couple of minutes, NOT an 11 GB download.")+ raise RuntimeError(f"The music engine isn't installed — missing: {missing}. Click 'Install the music engine' in the Phosphene sidebar in Pinokio (~11 GB, resumable).")+ if not p["music_style"] and not p["music_lyrics"] and not p["music_instrumental"]:+ raise RenderRefused("music_input", "Give it something to work with — lyrics, a style description, or both.")+ held = _music_external_gpu_lock()+ if held is not None:+ raise RenderRefused(+ "gpu_busy",+ f"The GPU is in use by another render (lock {held}). Retry music when it has finished. "+ f"If nothing is rendering, that lock was left behind by a command-line job — delete it and retry.")+ proc = None+ output = None+ try:+ _proc_guard_write("music", 0, 0, note=f"job {job['id']}")+ HELPER.kill() # Park LTX's resident weights before starting the other MLX runtime.+ if job.get("cancel_requested"):+ raise JobStopped("Music stopped")+ OUTPUT.mkdir(parents=True, exist_ok=True)+ slug = _sb_slug(p["music_style"] or p["music_lyrics"] or "instrumental")+ output = _unique_output_path(OUTPUT, f"music_{time.strftime('%Y%m%d_%H%M%S')}_{slug}", ext=".wav")+ job["raw_path"] = str(output)+ cmd = music_argv(job, paths, output)+ job["command"] = shlex.join(cmd)+ t0 = time.time()+ proc = subprocess.Popen(cmd, cwd=str(MUSIC_ROOT), env={**os.environ, "PYTHONUNBUFFERED": "1"},+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,+ start_new_session=True)+ with LOCK:+ STATE["pid"] = proc.pid+ STATE["music_pgid"] = proc.pid+ _proc_guard_write("music", proc.pid, proc.pid, note=f"job {job['id']}")+ if job.get("cancel_requested"):+ _stop_music_proc(pgid=proc.pid)+ tail = collections.deque(maxlen=4)+ progress = None+ assert proc.stdout is not None+ for raw in proc.stdout:+ line = raw.rstrip()+ if not line:+ continue+ push(line)+ tail.append(line)+ parsed = music_progress(line, progress)+ if parsed:+ progress = parsed+ elapsed = time.time() - t0+ parsed.update(elapsed_sec=elapsed,+ eta_sec=music_estimate(p["music_quality"], p["music_max_seconds"])["eta_sec"],+ remaining_sec=max(0, music_estimate(p["music_quality"], p["music_max_seconds"])["eta_sec"] - elapsed),+ eta_measured=False)+ with LOCK:+ job["progress"] = parsed+ rc = proc.wait()+ if job.get("cancel_requested") or rc == 130:+ # A Stop that lands while the runner is publishing can still leave+ # this job's files behind; "Nothing was saved" has to be true.+ for leftover in (output, Path(str(output) + ".json"),+ output.with_name(output.stem + ".partial" + output.suffix)):+ try:+ leftover.unlink()+ except OSError:+ pass+ raise JobStopped("Music stopped")+ if rc != 0:+ raise RuntimeError(f"YuE2 exited with code {rc}: " + " · ".join(tail))+ if not output.is_file() or not Path(str(output) + ".json").is_file():+ raise RuntimeError("YuE2 finished without the WAV and its sidecar. See the log.")+ job["output_path"] = str(output)+ finally:+ if proc is not None:+ if proc.poll() is None:+ try:+ os.killpg(proc.pid, signal.SIGTERM)+ proc.wait(timeout=8)+ except subprocess.TimeoutExpired:+ os.killpg(proc.pid, signal.SIGKILL)+ proc.wait()+ except ProcessLookupError:+ proc.wait()+ if proc.stdout:+ proc.stdout.close()+ with LOCK:+ STATE["pid"] = None+ STATE["music_pgid"] = None+ _proc_guard_clear("music")++ENGINE_DEFAULT = "ltx"ENGINES: tuple[dict, ...] = (@@ -12499,6 +12801,17 @@ ENGINES: tuple[dict, ...] = ("install_size": "~75 GB","state": "ready",},+ {+ "id": "music", "label": "YuE2", "sublabel": "music",+ "tagline": "lyrics and a style in, a finished song out — vocals and arrangement together.",+ "mark": "eng-mark-music", "accent": "#B14AFF",+ "accent_dim": "rgba(177,74,255,0.14)", "accent_soft": "rgba(177,74,255,0.42)",+ "builtin": False, "probe": "music", "modes": ("music",), "excluded_modes": (),+ "serves_label": "Compose", "surfaces": ("music",), "lora_tag": None,+ "strip": "", "hint": "", "strip_label": "Quality", "state": "ready",+ "install_card": "openMusicInstallCard", "install_size": "~11 GB",+ "size_note": f"~11 GB · needs {MUSIC_MIN_RAM_GB:.0f} GB unified memory · YuE2 license (CC BY-NC 4.0 + creator permission)",+ },# ---- Flux Video ---------------------------------------------------------# Weights are announced, not released. The entry is real (and rendered as# an inert "soon" chip) only under LTX_ENGINE_PREVIEW=1 — the same pattern@@ -13231,7 +13544,8 @@ def _analytics_job_secrets(job: dict) -> list:p = (job or {}).get("params") or {}out = []for k in ("prompt", "negative_prompt", "image", "audio", "output",- "first_frame", "last_frame", "character", "train_job_id"):+ "first_frame", "last_frame", "character", "train_job_id",+ "music_lyrics", "music_style"):v = p.get(k)if isinstance(v, str) and v.strip():out.append(v.strip())@@ -14616,14 +14930,14 @@ def _upscale_finish(video_path: Path, audio_source: str, *, frames: int,if ok and state == "unknown":kept = _probe_audio_state(str(tmp)) == "audio"if not ok and want_source:- push(f"Upscale ×2: could not carry the source sound over ({err}) — "+ push(f"{FACE_FIX_NAME}: could not carry the source sound over ({err}) — ""delivering the clip without sound")ok, err = _run(False)if not ok:raise RuntimeError(- (f"Upscale ×2: could not cut the render back to {frames} frames: {err}"+ (f"{FACE_FIX_NAME}: could not cut the render back to {frames} frames: {err}"if trim else- f"Upscale ×2: could not finish the clip (removing the model's own "+ f"{FACE_FIX_NAME}: could not finish the clip (removing the model's own "f"soundtrack failed): {err}"))tmp.replace(video_path)return kept@@ -15059,7 +15373,8 @@ def list_outputs(# Merge-sort videos + images by mtime DESC so the limit applies to the# unified newest-first stream (no kind-specific imbalance).combined: list[tuple[Path, float]] = []- for p in video_files:+ audio_files = [p for p in OUTPUT.glob("*.wav") if not p.name.endswith(".partial.wav")]+ for p in video_files + audio_files:try:combined.append((p, p.stat().st_mtime))except OSError:@@ -15162,9 +15477,11 @@ def list_outputs(if has_sidecar:try:meta = json.loads(sidecar.read_text())- v = meta.get("elapsed_sec")+ v = meta.get("elapsed_sec", meta.get("wall_seconds"))if isinstance(v, (int, float)):elapsed_sec = float(v)+ if p.suffix.lower() == ".wav":+ clip_sec = meta.get("audio_seconds")_sc_params = meta.get("params")if not isinstance(_sc_params, dict):_sc_params = {}@@ -15255,7 +15572,7 @@ def list_outputs(# 'kind' lets the right-pane viewer + filter chips branch# without re-parsing the filename. Mirrors isPhotoOutput() on# the agent-stage pane (commit af5c184).- "kind": "image" if is_image else "video",+ "kind": "image" if is_image else "audio" if p.suffix.lower() == ".wav" else "video","q": search,})total = len(out)@@ -16081,6 +16398,7 @@ def _kill_h3_proc() -> None:# reaped by this one._PROC_GUARDS: dict[str, tuple[Path, str]] = {"h3": (STATE_DIR / "h3_running.json", "generate_staged"),+ "music": (STATE_DIR / "music_running.json", "yue2_run.py"),"helper": (STATE_DIR / "helper_running.json", "mlx_warm_helper"),}@@ -16553,8 +16871,11 @@ def stop_current_job(timeout: float = 5.0) -> None:mux_pgid = STATE.get("mux_pgid")train_pgid = STATE.get("train_pgid")h3_pgid = STATE.get("h3_pgid")+ music_pgid = STATE.get("music_pgid")push("Stop requested — killing helper + ffmpeg post-process + training subprocess to abort current job.")HELPER.kill()+ if music_pgid:+ _stop_music_proc(pgid=music_pgid)# Image-engine subprocesses (HiDream's BF16 helper, mflux's per-family# binaries) live outside HELPER. Without this they would run to# completion regardless of /stop. Each engine registers its Popen via@@ -19531,15 +19852,19 @@ def _sb_split_audio_plan(segs: list[dict]) -> dict:"""Where every clip's SOUND plays in the concatenated film.Returns {"split": bool, "total": float, "lanes": [{idx, start, end, at,- len}]}. `split` is False when nothing is unlinked, and that is what keeps- the ordinary graph byte-identical: the whole decoupled path is skipped.-- ONE LANE, ENFORCED HERE TOO. The validator refuses overlapping sound in- the EDITOR's clock, but the assembler closes gaps, so two clips can slide- into each other on the way out. Rather than emit a graph that would need a- mixer, a later lane's head is trimmed to the one before it — deterministic,- and the only alternative is the second audio track this feature is- explicitly not.+ len}], "lanes_b": [...]}. `split` is False when nothing is unlinked, and+ that is what keeps the ordinary graph byte-identical: the whole decoupled+ path is skipped.++ TWO LANES, EACH ONE A LANE. `lanes` is clip sound lane A — every clip that+ carries no `lane` — and `lanes_b` is lane B (`lane: 2`). Within a lane the+ rule is the old one: the assembler closes gaps, so two clips can slide+ into each other on the way out, and a later strip's arrival trims the+ tail before it — deterministic, and no mixer inside the lane. BETWEEN the+ lanes nothing is trimmed: the two are summed downstream, which is how a+ sound dissolve across a cut is made (`storyboard_editor.clip_sound_lane`).+ A film that never used lane B returns an empty `lanes_b` and everything+ else exactly as before."""cum, rows, split = 0.0, [], Falsefor i, sg in enumerate(segs):@@ -19565,22 +19890,35 @@ def _sb_split_audio_plan(segs: list[dict]) -> dict:split = Truehas_audio = Falseaud = sg.get("audio") if isinstance(sg.get("audio"), dict) else None+ lane_b = sg.get("lane") == 2if has_audio:+ # LANE B CANNOT RIDE THE PLAIN CONCAT — that graph is one lane —+ # so a clip on it takes the lane path like an unlinked one.+ if lane_b:+ split = Trueif aud:split = Truerows.append({"idx": i, "start": float(aud["start"]),"end": float(aud["end"]), "speed": speed,- "at": cum + float(aud.get("delta") or 0.0)})+ "at": cum + float(aud.get("delta") or 0.0),+ "b": lane_b})else:cut = sg.get("window")st = float(cut["start"]) if cut else 0.0# SOURCE seconds on both ends: `n` is film seconds, so the# window a retimed clip plays is `n * speed` of the take.rows.append({"idx": i, "start": st, "end": st + n * speed,- "speed": speed, "at": cum})+ "speed": speed, "at": cum, "b": lane_b})cum += ntotal = round(cum, 6)- rows.sort(key=lambda r: r["at"])+ return {"split": split, "total": total,+ "lanes": _sb_audio_lane_rows([r for r in rows if not r["b"]], total),+ "lanes_b": _sb_audio_lane_rows([r for r in rows if r["b"]], total)}+++def _sb_audio_lane_rows(rows: list[dict], total: float) -> list[dict]:+ """One clip-sound lane's strips, clipped to the film and butt-joined."""+ rows = sorted(rows, key=lambda r: r["at"])lanes = []for r in rows:at, st, en, sp = r["at"], r["start"], r["end"], r["speed"]@@ -19615,23 +19953,25 @@ def _sb_split_audio_plan(segs: list[dict]) -> dict:if abs(L["speed"] - 1.0) > 1e-9:lane["speed"] = L["speed"]out.append(lane)- return {"split": split, "total": total, "lanes": out}+ return outdef _sb_split_audio_chains(lanes: list[dict], total: float, rate: int,- out_label: str) -> list[str]:- """The film's ONE audio lane, as silence and sound laid end to end.-- `concat` and not `amix`, deliberately: concat cannot sum, so this graph is- incapable of becoming the mixer the refuse list bans, and the gaps between- split edits are honest `anullsrc` rather than an input that happens to be- quiet.+ out_label: str, hush_tag: str = "aq") -> list[str]:+ """ONE clip-sound lane, as silence and sound laid end to end.++ `concat` and not `amix`, deliberately: concat cannot sum, so a lane cannot+ become a mixer, and the gaps between split edits are honest `anullsrc`+ rather than an input that happens to be quiet. The SUM of lane A and lane+ B happens once, downstream, in the same `amix` the bed and the audio+ tracks join. `hush_tag` names the silences, so two lanes in one graph+ cannot collide; lane A keeps `aq`, character for character."""chains, parts, cursor, n = [], [], 0.0, 0def hush(seconds: float) -> None:nonlocal n- lab = f"aq{n}"+ lab = f"{hush_tag}{n}"n += 1chains.append(f"anullsrc=channel_layout=stereo:sample_rate={rate}:"f"d={seconds:.6f}[{lab}]")@@ -19690,9 +20030,18 @@ def _sb_film_filtergraph(probes: list[tuple], target_w: int, target_h: int,overlays: list | None = None,overlay_base: int = 0,segments: list[dict] | None = None,- scale_to: int = 0, grain: int = 0) -> tuple[str, str]:+ scale_to: int = 0, grain: int = 0,+ sound_strips: list | None = None,+ sound_base: int = 0) -> tuple[str, str]:"""The concat FILTER graph for a mixed-geometry cut → (graph, video_label).+ `sound_strips` are the audio TRACKS' strips (A3, A4, …), from+ `storyboard_editor.track_render_strips`, and `sound_base` the ffmpeg input+ index of the first of them (one `-i` per row, in order). Each is trimmed to+ its source window, shaped by its own curve, dropped onto its film second+ with `adelay` and MIXED over whatever the clips and the bed made. None or+ empty leaves the graph character-for-character what it was.+A bare concat DEMUXER cannot do this job. The shots in one film are notuniform and never were: the draft pass writes 640×448, delivery writes1024×576, H3's own export lands 768×448 or 1280×720, LTX carries 48 kHz@@ -19757,7 +20106,7 @@ def _sb_film_filtergraph(probes: list[tuple], target_w: int, target_h: int,# loop below only learns that as it goes. `split` False leaves every line# after this exactly as it was.aplan = _sb_split_audio_plan(segs)- alane = {L["idx"]: L for L in aplan["lanes"]}+ alane = {L["idx"]: L for L in aplan["lanes"] + aplan["lanes_b"]}split = bool(aplan["split"])music_mode = str((music or {}).get("mode") or "replace").lower()if music_mode not in ("replace", "under"):@@ -19891,6 +20240,43 @@ def _sb_film_filtergraph(probes: list[tuple], target_w: int, target_h: int,# the clips kept their own sound.bed_env = _sb_volume_term((music or {}).get("gain"))bed_tail = ("," + bed_env.rstrip(",")) if bed_env else ""+ # ---- THE AUDIO TRACKS: a strip is a chain, and the chains are MIXED ----+ # Built before the branches below so each branch can name its own result+ # `[abase]` instead of `[aout]` when there is something to mix over it. The+ # envelope runs on the STRIP's clock (after `asetpts`, t is 0 at the strip's+ # first sample), which is the clock `track_strip_gain_points` speaks, so+ # there is no conversion to get wrong. `adelay` in SAMPLES, after the+ # resample, so a strip lands on its film second to the sample rather than+ # to the millisecond. `apad` + `atrim=0:total` gives every strip exactly+ # the base's length, which is what `amix duration=first` expects of them.+ strip_labels: list[str] = []+ strip_chains: list[str] = []+ # ---- CLIP SOUND LANE B joins that same sum --------------------------+ # Laid end to end exactly like lane A, into its own label, and mixed with+ # everything else under the one `asoftclip`. Only when a clip is on it and+ # the clips keep their sound: `replace` throws both lanes away, and an+ # empty lane B adds nothing, so every film that never used it builds the+ # graph it always did.+ if aplan["lanes_b"] and not silent_segments:+ strip_chains.extend(_sb_split_audio_chains(+ aplan["lanes_b"], total, rate, "[alb]", hush_tag="aqb"))+ strip_labels.append("[alb]")+ for k, row in enumerate(r for r in (sound_strips or []) if isinstance(r, dict)):+ s_at = max(0.0, float(row.get("at") or 0.0))+ s_st = max(0.0, float(row.get("start") or 0.0))+ s_en = float(row.get("end") or 0.0)+ if s_en - s_st <= 1e-6 or s_at >= total - 1e-6:+ continue # nothing of it plays inside the film+ s_vol = _sb_volume_term(row.get("gain"))+ s_delay = (f"adelay=delays={int(round(s_at * rate))}S:all=1,"+ if s_at > 1e-6 else "")+ strip_chains.append(+ f"[{sound_base + k}:a]atrim=start={s_st:.6f}:end={s_en:.6f},"+ f"asetpts=PTS-STARTPTS,{s_vol}aresample={rate},"+ f"aformat=sample_fmts=fltp:channel_layouts=stereo,"+ f"{s_delay}apad,atrim=0:{total:.6f},asetpts=PTS-STARTPTS[ts{k}]")+ strip_labels.append(f"[ts{k}]")+ aout = "[abase]" if strip_labels else "[aout]"if silent_segments:chains.extend(_sb_picture_chains(pads, segs, pic_lens))# `apad` before the trim so a soundtrack shorter than the film ends in@@ -19899,7 +20285,7 @@ def _sb_film_filtergraph(probes: list[tuple], target_w: int, target_h: int,f"{music_head}aresample={rate},"f"aformat=sample_fmts=fltp:channel_layouts=stereo,"f"apad,atrim=0:{total:.6f},asetpts=PTS-STARTPTS"- f"{bed_tail}[aout]")+ f"{bed_tail}{aout}")elif music and music_mode == "under":if split:# The picture concatenates on its own; the sound was already laid@@ -19952,17 +20338,33 @@ def _sb_film_filtergraph(probes: list[tuple], target_w: int, target_h: int,# so a preview could only fake it. It is a safety net, not a mix# decision — and the render MEASURES what it did (`mix_peak`) and says# so, which is what a net owes the person it is under.+ # WITH AUDIO TRACKS THE STRIPS JOIN THIS SAME SUM, so the limiter runs+ # once over everything rather than twice in series.+ chains.extend(strip_chains)chains.append(- "[acat][bed]amix=inputs=2:duration=first:dropout_transition=0:"+ f"[acat][bed]{''.join(strip_labels)}amix=inputs={2 + len(strip_labels)}"+ ":duration=first:dropout_transition=0:"f"normalize=0,asoftclip=type=tanh:threshold={_sb_mix_ceiling():g}""[aout]")+ strip_labels = []elif split:chains.extend(_sb_picture_chains(pads, segs, pic_lens))chains.extend(_sb_split_audio_chains(aplan["lanes"], total, rate,- "[aout]"))+ aout))else:chains.append(- f"{''.join(pads)}concat=n={len(segs)}:v=1:a=1[vcat][aout]")+ f"{''.join(pads)}concat=n={len(segs)}:v=1:a=1[vcat]{aout}")+ if strip_labels:+ # THE SAME SUM AND THE SAME NET the under-mix uses: `normalize=0` so no+ # input is halved behind the user's back, `duration=first` so the film+ # is as long as its picture, and `asoftclip` because nothing else stops+ # a laugh track over a hot line from hard-clipping.+ chains.extend(strip_chains)+ chains.append(+ f"{aout}{''.join(strip_labels)}amix=inputs={1 + len(strip_labels)}"+ ":duration=first:dropout_transition=0:"+ f"normalize=0,asoftclip=type=tanh:threshold={_sb_mix_ceiling():g}"+ "[aout]")# ---- THE OVERLAY LANE, composited over the finished picture ----------# A SECOND VIDEO TRACK, and the alpha is the whole of it. The card arrives# 1536x832 for a 768x416 frame — authored at 2x on purpose — so it is@@ -20134,6 +20536,8 @@ def _sb_timeline_segments(timeline: list) -> tuple[list[dict], list[str], list]:seg["fx"] = dict(entry["fx"])if entry.get("gain"):seg["gain"] = [list(pt) for pt in entry["gain"]]+ if entry.get("lane") == 2:+ seg["lane"] = 2aud = entry.get("audio")if isinstance(aud, dict):# A DELTA, NOT A FILM SECOND. The assembler CONCATENATES, so a@@ -20243,9 +20647,14 @@ def _sb_assemble_film(clips: list, out_path, *, plan: list | None = None,music_delay: float = 0.0,music_mode: str = "replace",music_gain: list | None = None,- deliver: dict | None = None) -> dict:+ deliver: dict | None = None,+ sound_strips: list | None = None) -> dict:"""Concatenate the exported shots into ONE playable film.+ `sound_strips` (from `storyboard_editor.track_render_strips`) are the audio+ tracks' strips; each gets its own `-i` AFTER the overlays, so no index the+ graph already used moves, and they are mixed over the film's sound.+`clips` is the export directory's own copies, in `n` order, alreadyfiltered by the copy loop — the film is exactly what the folder contains,never a second, differently-derived selection.@@ -20397,12 +20806,16 @@ def _sb_assemble_film(clips: list, out_path, *, plan: list | None = None,# UP ONLY, and only when it changes something: a 1080p delivery of a# 1080-high cut is the cut.scale_to = dl["height"] if dl["height"] and dl["height"] != target_h else 0+ strip_rows = [r for r in (sound_strips or []) if isinstance(r, dict)+ and str(r.get("path") or "")]graph, vlabel = _sb_film_filtergraph(probes, target_w, target_h, rate,graph_pix, cuts=cuts,music=music_arg, segments=segments,overlays=ov_rows,overlay_base=overlay_base,- scale_to=scale_to, grain=dl["grain"])+ scale_to=scale_to, grain=dl["grain"],+ sound_strips=strip_rows,+ sound_base=overlay_base + len(ov_inputs))cmd = [str(FFMPEG), "-y"]if segments is not None:@@ -20418,6 +20831,11 @@ def _sb_assemble_film(clips: list, out_path, *, plan: list | None = None,cmd += ["-i", music_arg["path"]]for frag in ov_inputs:cmd += frag+ # THE AUDIO TRACKS' FILES LAST, one per strip, in the order the graph+ # numbered them from `sound_base`. `-vn` so a video used for its sound+ # only is not decoded for a picture nothing maps.+ for row in strip_rows:+ cmd += ["-vn", "-i", str(row["path"])]cmd += ["-filter_complex", graph,"-map", vlabel, "-map", "[aout]",@@ -20465,13 +20883,15 @@ def _sb_assemble_film(clips: list, out_path, *, plan: list | None = None,for k in ("video", "still", "slug")}if segments is not None else None),"unreadable": unreadable}+ if strip_rows:+ facts["sound_strips"] = len(strip_rows)# WHAT THE LIMITER DID, MEASURED. It is the one gain in this graph that is# not a value in the document, because it acts on the sum of two signals# and nothing outside ffmpeg has those samples — so instead of a preview# pretending to apply it, the render reports it. A peak sitting above the# soft-clip knee is the knee working: tanh only pushes a sample past the# threshold when it was already over it.- if music_arg and str(music_arg.get("mode") or "") == "under":+ if strip_rows or (music_arg and str(music_arg.get("mode") or "") == "under"):peak = _sb_audio_peak(out_path)if peak is not None:facts["mix_peak"] = round(peak, 4)@@ -20593,6 +21013,14 @@ def _sbe_render_edit(board: dict, edit: dict, *, music=None,probs = sedit.transition_problems(edit)if probs:return {"ok": False, "error": probs[0]["message"], "status": 400}+ # THE AUDIO TRACKS, refused the way a missing soundtrack is: a film with a+ # hole where the laugh track was is not the film anybody cut.+ strips = sedit.track_render_strips(edit)+ for row in strips:+ if not Path(row["path"]).is_file():+ return {"ok": False, "status": 400,+ "error": f"no sound file at {row['path']} (audio track "+ f"{sedit.track_label(row['track_index'])})"}if any(sedit.overlay_kind(o) == "text" for o in sedit.overlay_items(edit)):problem = sedit.title_font_problem()if problem:@@ -20633,7 +21061,7 @@ def _sbe_render_edit(board: dict, edit: dict, *, music=None,music_end=win["end"], music_delay=win["delay"], music_mode=mmode,music_gain=sedit.bed_render_gain(edit),overlays=sedit.overlay_items(edit),- deliver=dl)+ deliver=dl, sound_strips=strips or None)film["gaps"] = gapsif gaps:# An honest limitation, disclosed rather than discovered: this@@ -21349,6 +21777,145 @@ def _sbe_pool_path_ok(path: str) -> bool:return False+def _sbe_probe_sound(path) -> dict | None:+ """What an AUDIO TRACK needs to know about a file, or None.++ Deliberately not `_sb_probe_clip`, which refuses anything without a+ picture — the right verdict for a shot and exactly the wrong one for a+ laugh track. A file with no audio stream is None: a sound strip made of+ silence is a strip nobody meant to add. Returns+ `{"duration", "has_video", "sample_rate"}`, `duration` being the AUDIO+ stream's own when it says, else the container's.+ """+ try:+ out = subprocess.run(+ [str(FFPROBE), "-v", "error", "-show_entries",+ "stream=codec_type,sample_rate,duration:format=duration",+ "-of", "json", str(path)],+ capture_output=True, text=True, timeout=60)+ except (OSError, subprocess.SubprocessError):+ return None+ if out.returncode != 0:+ return None+ try:+ data = json.loads(out.stdout or "{}")+ except (ValueError, TypeError):+ return None+ a_dur, rate, has_audio, has_video = 0.0, 0, False, False+ for st in (data.get("streams") or []) if isinstance(data, dict) else []:+ if not isinstance(st, dict):+ continue+ kind = str(st.get("codec_type") or "")+ if kind == "audio":+ has_audio = True+ try:+ a_dur = max(a_dur, float(st.get("duration") or 0.0))+ rate = max(rate, int(st.get("sample_rate") or 0))+ except (TypeError, ValueError):+ pass+ elif kind == "video":+ has_video = True+ if not has_audio:+ return None+ if a_dur <= 0:+ try:+ a_dur = float(((data.get("format") or {}).get("duration")) or 0.0)+ except (TypeError, ValueError):+ a_dur = 0.0+ if not (a_dur > 0):+ return None+ return {"duration": round(a_dur, 6), "has_video": has_video,+ "sample_rate": rate}+++def _sbe_sound_dir(board: dict) -> Path:+ """The film's own sound folder: `<film folder>/audio/`.++ Beside the renders of the film it belongs to, and under OUTPUT, which is+ what `/file` serves — so a sound put here can be HEARD in the Editor's+ preview, not only rendered.+ """+ return _sb_film_dir(board) / "audio"+++def _sbe_list_sounds(board: dict, *, limit: int = 300) -> list[dict]:+ """The media pool's Sound source: every sound file the film can use.++ Two places, film first: `<film folder>/audio/` (what "Add sound file…"+ brings in, and what belongs to this film) and the top of OUTPUT (every+ `.wav` the engines and the Audio tab leave there). Newest first, capped,+ and no probing — two hundred ffprobes on a tab switch would be the slow+ part of the Editor; the length is read when a sound is actually added.+ """+ suffixes = set(_sbe_import().SOUND_SUFFIXES)+ rows: list[dict] = []+ seen: set = set()+ for where, root in (("film", _sbe_sound_dir(board)), ("outputs", OUTPUT)):+ if not root.is_dir():+ continue+ try:+ found = [p for p in root.iterdir()+ if p.is_file() and p.suffix.lower() in suffixes+ and not p.name.startswith(".")]+ except OSError:+ continue+ found.sort(key=lambda q: q.stat().st_mtime, reverse=True)+ for p in found:+ key = str(p)+ if key in seen:+ continue+ seen.add(key)+ rows.append({"path": key, "name": p.name, "where": where,+ "mtime": int(p.stat().st_mtime)})+ if len(rows) >= limit:+ return rows+ return rows+++def _sbe_add_sound(board: dict, path: str) -> dict:+ """One file → a sound an audio track can hold, or an honest refusal.++ A file already under OUTPUT is used where it is. Anything else — a path+ typed into "Add sound file…" pointing at a Downloads folder, an uploaded+ clip — is HARDLINKED (copied across volumes) into the film's own `audio/`+ folder first, for two reasons that are the same reason: `/file` only+ serves OUTPUT, so a sound anywhere else renders but cannot be auditioned,+ and a film whose sounds live in the film's folder still has them when the+ folder is moved. The original is never touched.+ """+ raw = str(path or "").strip()+ if raw.startswith("~"):+ raw = str(Path(raw).expanduser())+ try:+ src = Path(raw).resolve()+ except OSError:+ return {"ok": False, "status": 400, "error": "that is not a path"}+ if not raw or not src.is_file():+ return {"ok": False, "status": 404, "error": f"there is no file at {raw}"}+ info = _sbe_probe_sound(src)+ if not info:+ return {"ok": False, "status": 400,+ "error": f"{src.name} has no sound this panel can read"}+ dest = src+ imported = False+ if not src.is_relative_to(OUTPUT.resolve()):+ sdir = _sbe_sound_dir(board)+ sdir.mkdir(parents=True, exist_ok=True)+ dest = sdir / re.sub(r"[^A-Za-z0-9._-]+", "_", src.name)+ if dest.exists() and not dest.samefile(src):+ dest = sdir / f"{int(time.time() * 1000)}_{dest.name}"+ if not dest.exists():+ try:+ os.link(str(src), str(dest))+ except OSError:+ shutil.copy2(str(src), str(dest))+ imported = True+ push(f"[timeline] sound brought into the film: {dest.name}")+ return {"ok": True, "path": str(dest), "title": src.stem[:80],+ "duration_s": info["duration"], "has_video": info["has_video"],+ "imported": imported}++def _sbe_proxy_now(board_dir: Path, paths: list[str], sedit) -> dict:"""Build proxies for EXACTLY these paths, and prune nothing.@@ -21493,6 +22060,12 @@ def _sbe_relinks(board: dict, edit: dict) -> list[dict]:"to": str(new), "n": s.get("n"),"title": (s.get("title") or s.get("prompt") or "")[:80],"retake": True})+ # UPSCALE & FACE FIX ordered from a clip on this timeline — the same+ # one-clip-at-a-time offer as a retake.+ try:+ out.extend(_face_fix_offers(str(board.get("id") or ""), edit))+ except Exception: # noqa: BLE001+ passreturn out@@ -21782,6 +22355,15 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,# make_job() entry point so /queue/add stays mode-agnostic; the# worker dispatches by params.mode in run_job_inner.mode_in = f("mode", "t2v")+ if mode_in == "music" or f("engine") == "music":+ params = music_params(form)+ params["prompt"] = params["music_style"] or params["music_lyrics"] or "Instrumental"+ params["label"] = params["prompt"][:80]+ return {"id": _new_job_id(), "status": "queued", "queued_at": iso_now(),+ "started_at": None, "started_ts": None, "finished_at": None,+ "elapsed_sec": None, "params": params, "command": None,+ "raw_path": None, "output_path": None, "error": None}+if mode_in == "train":# Training jobs don't render anything — they consume a pre-uploaded# dataset directory (TRAIN_DIR / <job_id>) and write a .safetensors@@ -24453,38 +25035,260 @@ def _h3_clip_is_complete(path: Path, started_at: float,return False+# UPSCALE & FACE FIX — the user-facing name of the Upscale ×2 lane (owner,+# 2026-09-17: "this thing we ship that fixes the faces has the wrong name").+# Only the words changed: the mode is still `upscale`, the form keys are still+# `upscale_source_path` / `keep_shot` / `upscale_start` / `upscale_steps`, so+# old sidecars, Load Params and scripts keep working.+FACE_FIX_NAME = "Upscale & Face Fix"+# The face-safe recipe, verified on real character clips 2026-09-16: start from+# the clip's own latent and refine ONCE — the ×2 sharpness without redrawing+# the face. This is NOT the lane's "Faithful" pill (keep_shot 1.0 alone+# resolves to 3 refine steps, see the upscale worker); the one-click clip+# action and the after-the-draft pass send these three keys explicitly.+FACE_FIX_RECIPE = {"keep_shot": "1.0", "upscale_start": "source",+ "upscale_steps": "1"}+_FACE_FIX_VIDEO_SUFFIXES = (".mp4", ".mov", ".m4v", ".webm", ".mkv")+_FACE_FIX_BOARD_RE = re.compile(r"^[A-Za-z0-9_-]{1,120}$")+++def face_fix_form(source_path, *, prompt: str = "", seed="-1",+ label: str = "", frames: int = 0) -> dict:+ """The /queue/add form for one Upscale & Face Fix of `source_path`.++ One builder for every door (clip action, after-the-draft pass), so the+ recipe cannot drift between them. `prompt` and `seed` are the SOURCE's+ own — an empty prompt stays empty and the worker reads the source's+ sidecar for it."""+ name = label or Path(str(source_path)).stem+ return {+ "mode": "upscale",+ "engine": "ltx",+ "upscale_source_path": str(source_path),+ **FACE_FIX_RECIPE,+ "seed": str(seed if seed not in (None, "") else "-1"),+ "prompt": str(prompt or ""),+ # make_job reads the queue label from `preset_label` — a `label` key+ # here was silently dropped, so the queue row showed the prompt.+ "preset_label": f"{name} · {FACE_FIX_NAME}",+ # The whole clip, not make_job's 121-frame default: the ×2 lane only+ # renders past its measured 129-frame ceiling when the form asks.+ # Rounded UP to LTX's 1+8k grid: make_job floors an off-grid count,+ # and the lane cuts the render back to the source's own length.+ **({"frames": str(ltx_grid_frames_up(int(frames)))}+ if frames and int(frames) > 0 else {}),+ }+++def _face_fix_source_meta(source: Path) -> dict:+ """prompt / resolved seed / label from the clip's own sidecar ({} if none)."""+ try:+ sc = json.loads(Path(str(source) + ".json").read_text(encoding="utf-8"))+ except Exception: # noqa: BLE001+ return {}+ sp = sc.get("params") if isinstance(sc.get("params"), dict) else {}+ seed = sp.get("seed_used")+ if seed in (None, ""):+ seed = sp.get("seed")+ prompt = sp.get("prompt")+ label = sp.get("label")+ if isinstance(sc.get("take"), dict):+ # A joined One Shot copies its LAST part's sidecar and writes the+ # whole take's prompt and label on top; those describe the clip.+ if isinstance(sc.get("prompt"), str) and sc.get("prompt"):+ prompt = sc["prompt"]+ if sc.get("label"):+ label = sc["label"]+ if not isinstance(prompt, str):+ prompt = ""+ return {"prompt": prompt, "seed": seed if seed not in (None, "") else "-1",+ "label": str(label or "")}+++def _face_fix_record_path(board_id: str) -> Path:+ return _sbe_board_dir(board_id) / "face_fix.json"+++def _face_fix_records(board_id: str) -> dict:+ try:+ data = json.loads(_face_fix_record_path(board_id).read_text(encoding="utf-8"))+ except Exception: # noqa: BLE001+ return {}+ clips = data.get("clips") if isinstance(data, dict) else None+ return clips if isinstance(clips, dict) else {}+++_FACE_FIX_LOCK = threading.Lock()+++def _face_fix_note(board_id: str, clip_id: str, **fields) -> None:+ """Remember (or update) the Face Fix ordered for one Editor clip."""+ with _FACE_FIX_LOCK:+ recs = _face_fix_records(board_id)+ row = recs.get(clip_id) if isinstance(recs.get(clip_id), dict) else {}+ if fields.get("job") and row.get("job") != fields.get("job"):+ row = {} # a new order replaces the old one+ elif row.get("to") and not fields.get("to"):+ # A late registration for a job that already landed must not+ # erase its result.+ fields = {k: v for k, v in fields.items() if k not in ("to", "complete")}+ row.update(fields)+ recs[clip_id] = row+ # Bounded: a film has at most a few hundred clips.+ if len(recs) > 400:+ for k in sorted(recs, key=lambda k: (recs[k] or {}).get("queued_at") or 0)[:len(recs) - 400]:+ recs.pop(k, None)+ atomic_write_text(_face_fix_record_path(board_id),+ json.dumps({"clips": recs}, indent=2))+++def _face_fix_offers(board_id: str, edit: dict) -> list[dict]:+ """Finished Face Fixes offered against the Editor clip they were made from.++ Same shape as a retake row (`retake: True`, adopted one clip at a time by+ id) and only while that clip still plays the file the fix was made from —+ a clip already swapped, or re-pointed at something else, gets no offer."""+ recs = _face_fix_records(board_id)+ if not recs:+ return []+ by_id = {str(c.get("id")): c for c in (edit.get("clips") or [])+ if isinstance(c, dict) and c.get("id")}+ out: list[dict] = []+ for cid, r in recs.items():+ if not isinstance(r, dict):+ continue+ to, src = str(r.get("to") or ""), str(r.get("from") or "")+ c = by_id.get(str(cid))+ if not (to and c and Path(to).is_file()):+ continue+ if str(c.get("path") or "") != src or src == to:+ continue+ if r.get("complete") is False:+ # A fix that does not cover the whole clip is no swap: the+ # clip's in/out points would point past its end.+ continue+ out.append({"id": str(cid), "path": src, "to": to,+ "title": str(c.get("title") or Path(src).stem)[:80],+ "retake": True, "face_fix": True})+ return out+++def queue_face_fix(source_path: str, *, board_id: str = "",+ clip_id: str = "") -> dict:+ """Queue one Upscale & Face Fix of a finished clip — the one-click action.++ Refuses up front what the worker would only refuse after a wait in the+ queue (not a video, adapter missing, already at this Mac's size cap).+ Returns {ok, id, label, duplicate?} or {ok: False, error}."""+ src = Path(str(source_path or ""))+ if not source_path or not src.is_file():+ return {"ok": False, "error": "That clip is not on disk any more."}+ if src.suffix.lower() not in _FACE_FIX_VIDEO_SUFFIXES:+ return {"ok": False, "error": f"{FACE_FIX_NAME} works on video clips, not stills."}+ if board_id and not _FACE_FIX_BOARD_RE.match(board_id):+ return {"ok": False, "error": "unknown film"}+ if board_id and not (_sbe_board_dir(board_id) / "storyboard.json").is_file():+ return {"ok": False, "error": "unknown film"}+ adapter_path = CURATED_LORAS["upscale_x2"].get("local_path") or ""+ if not (adapter_path and Path(adapter_path).exists()):+ return {"ok": False, "code": "pack_missing",+ "error": f"{FACE_FIX_NAME} needs the LTX-2.5 Pixel Spatial Upscaler "+ "adapter (0.3 GB). Open Settings → Models and download it."}+ sw, sh = _probe_video_dims(str(src))+ src_frames = _probe_video_frames(str(src)) or 0+ if sw and sh:+ cap = int(tier_max_dim("i2v") or 0) or max(sw, sh) * 2+ scale = min(2.0, cap / float(max(sw, sh)))+ if scale < 1.25:+ return {"ok": False, "code": "hardware_tier",+ "error": f"{src.name} is already {sw}×{sh} — {FACE_FIX_NAME} "+ f"can't go above {cap}px on this Mac."}+ if src_frames:+ up_w, up_h = ltx_floor_canvas(int(sw * scale), int(sh * scale))+ _, grid = upscale_frame_plan(src_frames, src_frames)+ if not upscale_canvas_decodable(up_w, up_h, grid):+ return {"ok": False, "code": "hardware_tier",+ "error": f"{src.name} is too long to fix at {up_w}×{up_h} "+ "(the video decoder's limit). Cut it shorter first."}+ meta = _face_fix_source_meta(src)+ form = face_fix_form(src, prompt=meta.get("prompt", ""),+ seed=meta.get("seed", "-1"), label=meta.get("label", ""),+ frames=src_frames)+ job = make_job(form)+ job["params"]["face_fix"] = True+ target = [board_id, str(clip_id)] if (board_id and clip_id) else None+ if target:+ job["params"]["face_fix_targets"] = [target]+ dup = None+ with QUEUE_COND:+ # Same clip, same recipe, same seed = the same file: a second click+ # while the first is waiting OR rendering is not a second order.+ # Checked under the queue lock so two racing clicks cannot both land.+ cands = list(STATE["queue"])+ if STATE.get("current"):+ cands.insert(0, STATE["current"])+ for j in cands:+ jp = (j or {}).get("params") or {}+ if (jp.get("mode") == "upscale" and jp.get("face_fix")+ and jp.get("upscale_source_path") == str(src)):+ dup = j+ break+ if dup is None:+ STATE["queue"].append(job)+ QUEUE_COND.notify_all()+ elif target:+ # Every Editor clip that asked is answered when it lands. The+ # worker snapshots the targets under this same lock, so a target+ # added after its snapshot sees the result here instead.+ tl = dup["params"].setdefault("face_fix_targets", [])+ if target not in tl:+ tl.append(target)+ landed = dict((dup or {}).get("params", {}).get("face_fix_result") or {})+ if target:+ _face_fix_note(board_id, str(clip_id), job=(dup or job)["id"],+ to=landed.get("to", ""), queued_at=time.time(),+ **({"complete": landed["complete"]} if "complete" in landed else {}),+ **{"from": str(src)})+ persist_queue()+ if dup is not None:+ return {"ok": True, "id": dup["id"], "label": dup["params"].get("label"),+ "duplicate": True,+ "running": dup is STATE.get("current")}+ push(f"{FACE_FIX_NAME} queued for {src.name} → job {job['id']}")+ return {"ok": True, "id": job["id"], "label": job["params"].get("label")}++def _chain_upscale_after_h3(job: dict, p: dict, native_path: Path) -> None:- """Queue the Upscale ×2 job for a draft whose form asked for "LTX ×2".+ """Queue the Upscale & Face Fix pass for a draft whose form asked for it+ (h3_upscale = "ltx_x2").Same door as /queue/add (make_job), so every allowlist and refusal- applies; the preset (keep_shot) and seed travel from the draft's form.- The draft stays in the gallery — the ×2 lands beside it as its own card."""- try:- form = {- "mode": "upscale",- "engine": "ltx",- "upscale_source_path": str(native_path),- "keep_shot": str(p.get("keep_shot") or "1.0"),- # The seed THIS render resolved, not the form's "-1".- "seed": str(p.get("seed_used") if p.get("seed_used") is not None- else (p.get("seed") if p.get("seed") not in (None, "") else "-1")),+ applies; the seed and prompt travel from the draft. The draft stays in the+ gallery — the fixed clip lands beside it as its own card."""+ try:+ form = face_fix_form(+ native_path,# The draft's own prompt. An empty one used to be replaced by# make_job's generic "A cinematic atmospheric scene", so the ×2# never read the source's description.- "prompt": str(p.get("prompt") or ""),- "label": f"{p.get('label') or native_path.stem} · LTX ×2",- }+ prompt=str(p.get("prompt") or ""),+ # The seed THIS render resolved, not the form's "-1".+ seed=(p.get("seed_used") if p.get("seed_used") is not None+ else (p.get("seed") if p.get("seed") not in (None, "") else "-1")),+ label=str(p.get("label") or native_path.stem),+ frames=_probe_video_frames(str(native_path)) or 0)nxt = make_job(form)nxt["params"]["source"] = "chain"nxt["params"]["chained_from"] = job.get("id")+ nxt["params"]["face_fix"] = Truewith QUEUE_COND:STATE["queue"].append(nxt)QUEUE_COND.notify_all()persist_queue()- push(f"[h3] LTX ×2 queued behind the draft → job {nxt['id']}")+ push(f"[h3] {FACE_FIX_NAME} queued behind the draft → job {nxt['id']}")except Exception as exc: # noqa: BLE001- push(f"[h3] could not queue the LTX ×2 pass: {exc} — the draft is in "- "the gallery; use its Upscale ×2 button.")+ push(f"[h3] could not queue {FACE_FIX_NAME}: {exc} — the draft is in "+ f"the gallery; use its {FACE_FIX_NAME} button.")def run_h3_job_inner(job: dict) -> None:@@ -25973,6 +26777,8 @@ def run_job_inner(job: dict) -> None:# Image jobs share the queue + worker but use a totally different# params shape (no width/height/frames, etc.). Dispatch to the# image path before any of the video-only validation runs.+ if mode == "music" or p.get("engine") == "music":+ return run_music_job_inner(job)if mode == "image":return run_image_job_inner(job)if mode == "train":@@ -26487,7 +27293,7 @@ def run_job_inner(job: dict) -> None:src = p.get("upscale_source_path") or p.get("restore_video_path") or ""if not src or not Path(src).exists():raise RuntimeError(- f"source clip for Upscale ×2 not found: {src!r}. Pick a finished "+ f"source clip for {FACE_FIX_NAME} not found: {src!r}. Pick a finished ""clip in the Outputs gallery (or paste a path).")source = Path(src)adapter = CURATED_LORAS["upscale_x2"]@@ -26495,7 +27301,7 @@ def run_job_inner(job: dict) -> None:if not (adapter_path and Path(adapter_path).exists()):raise RenderRefused("pack_missing",- "Upscale ×2 needs the LTX-2.5 Pixel Spatial Upscaler adapter, which "+ f"{FACE_FIX_NAME} needs the LTX-2.5 Pixel Spatial Upscaler adapter, which ""isn't downloaded on this Mac yet. Open Settings → Models and ""download it, then render again.")sw, sh = _probe_video_dims(src)@@ -26521,7 +27327,7 @@ def run_job_inner(job: dict) -> None:if scale < 1.25:raise RenderRefused("hardware_tier",- f"Upscale ×2 can't go above {cap}px on the {SYSTEM_CAPS['label']} "+ f"{FACE_FIX_NAME} can't go above {cap}px on the {SYSTEM_CAPS['label']} "f"tier, and {source.name} is already {sw}×{sh}. Use a smaller ""source clip.")up_w, up_h = ltx_floor_canvas(int(sw * scale), int(sh * scale))@@ -26539,11 +27345,11 @@ def run_job_inner(job: dict) -> None:# The helper refuses this too, but only after the whole render.raise RenderRefused("hardware_tier",- f"Upscale ×2 to {up_w}×{up_h} is past what the video decoder can "+ f"{FACE_FIX_NAME} to {up_w}×{up_h} is past what the video decoder can "f"write safely, even in tiles (the GPU kernels' 2^31-element "f"limit). Use a smaller source clip.")if src_frames and out_frames < src_frames:- push(f"Upscale ×2: {source.name} is {src_frames} frames; the ×2 covers "+ push(f"{FACE_FIX_NAME}: {source.name} is {src_frames} frames; the ×2 covers "f"its first {out_frames}")try:keep = float(p.get("keep_shot") or 1.0)@@ -26583,7 +27389,7 @@ def run_job_inner(job: dict) -> None:if p.get("upscale_steps") and start_from == "source":refine_steps = max(1, min(7, int(p["upscale_steps"])))up_model_dir = ltx_model_dir(quant)- ltx_pack_preflight(quant, "Upscale ×2")+ ltx_pack_preflight(quant, FACE_FIX_NAME)out_name = f"{source.stem}_x2_{stamp}.mp4"final_out = OUTPUT / out_namejob["raw_path"] = str(final_out)@@ -26605,9 +27411,9 @@ def run_job_inner(job: dict) -> None:if _r.returncode != 0 or _probe_video_frames(model_src) != frames:shutil.rmtree(work_dir, ignore_errors=True)raise RuntimeError(- f"Upscale ×2: could not extend {source.name} to {frames} frames "+ f"{FACE_FIX_NAME}: could not extend {source.name} to {frames} frames "f"for the model: {(_r.stderr or '')[-200:].strip()}")- push(f"Upscale ×2: {src_frames} frames → the model renders {frames} "+ push(f"{FACE_FIX_NAME}: {src_frames} frames → the model renders {frames} "f"(last frame held), the ×2 is cut back to {out_frames}")job_spec = {"action": "generate_restore",@@ -26640,7 +27446,7 @@ def run_job_inner(job: dict) -> None:"stage2_steps": int(p.get("stage2_steps", 3)),},}- push(f"Upscale ×2 via helper: id={job['id']} src={source.name} {sw}×{sh} → "+ push(f"{FACE_FIX_NAME} via helper: id={job['id']} src={source.name} {sw}×{sh} → "f"{up_w}×{up_h} {frames}f · keep-the-shot {keep:.2f} · {quant.upper()} distilled · "+ (f"from the clip's own latent, {refine_steps}-step refine + Pixel Spatial Upscaler"if start_from == "source" else "full re-render from noise + Pixel Spatial Upscaler"))@@ -26656,10 +27462,16 @@ def run_job_inner(job: dict) -> None:shutil.rmtree(work_dir, ignore_errors=True)delivered = _probe_video_frames(str(final_out))if delivered and delivered != out_frames:- push(f"Upscale ×2: WARNING — {final_out.name} has {delivered} frames, "+ push(f"{FACE_FIX_NAME}: WARNING — {final_out.name} has {delivered} frames, "f"expected {out_frames}")sidecar = {"output": str(final_out), "raw_output": str(final_out),+ # What the gallery and the info panel call this file. The mode+ # stays `upscale` so Load Params and scripts keep working.+ "display_name": FACE_FIX_NAME,+ "face_fix": {"start": start_from,+ "refine_steps": refine_steps if start_from == "source" else None,+ "keep_shot": keep},"params": {**p, "command": "upscale", "keep_shot": keep,"frames": out_frames, "render_frames": frames,"source_frames": src_frames,@@ -26674,7 +27486,23 @@ def run_job_inner(job: dict) -> None:}write_sidecar(final_out.with_suffix(final_out.suffix + ".json"), sidecar)job["output_path"] = str(final_out)- push(f"Upscale ×2 done in {sidecar['elapsed_sec']}s → {final_out.name}"+ # Ordered from Editor clips: each of them is offered the swap. A job+ # still waiting when the targets list grew reads it from the live+ # params (the queue shares this dict).+ _ff_result = {"to": str(final_out),+ "complete": bool(delivered and src_frames+ and delivered == src_frames)}+ with QUEUE_COND:+ p["face_fix_result"] = _ff_result+ _ff_targets = [list(t) for t in (p.get("face_fix_targets") or [])]+ for _t in _ff_targets:+ try:+ _face_fix_note(str(_t[0]), str(_t[1]), job=job["id"],+ **{"from": str(source)}, **_ff_result)+ except Exception as exc: # noqa: BLE001+ push(f"{FACE_FIX_NAME}: could not tell the Editor ({exc}); the "+ "fixed clip is in Outputs.")+ push(f"{FACE_FIX_NAME} done in {sidecar['elapsed_sec']}s → {final_out.name}"+ (" (source audio kept)" if muxed else ""))if p.get("open_when_done"):subprocess.run(["open", str(final_out)], check=False)@@ -29201,7 +30029,7 @@ class Handler(BaseHTTPRequestHandler):safe = safe.replace('"', "").replace("\\", "").strip()return safe or path.name.encode("ascii", "ignore").decode() or "download"- def _serve_video_with_range(self, path: Path) -> None:+ def _serve_video_with_range(self, path: Path, ctype: str = "video/mp4") -> None:"""Serve an mp4 with HTTP byte-range support so the browser <video>tag can seek without redownloading and the gallery's `preload="metadata"`thumbnails only fetch the moov atom range instead of full clips.@@ -29243,7 +30071,7 @@ class Handler(BaseHTTPRequestHandler):returnlength = end - start + 1self.send_response(206)- self.send_header("Content-Type", "video/mp4")+ self.send_header("Content-Type", ctype)self.send_header("Accept-Ranges", "bytes")self.send_header("Content-Range", f"bytes {start}-{end}/{size}")self.send_header("Content-Length", str(length))@@ -29275,7 +30103,7 @@ class Handler(BaseHTTPRequestHandler):# No Range header — full file with Accept-Ranges advertised so the# browser knows it CAN range-request next time.self.send_response(200)- self.send_header("Content-Type", "video/mp4")+ self.send_header("Content-Type", ctype)self.send_header("Content-Length", str(size))self.send_header("Accept-Ranges", "bytes")self.send_header(@@ -30478,6 +31306,11 @@ class Handler(BaseHTTPRequestHandler):# by id, because it replaces a take the user may prefer.if only:rows = [r for r in rows if str(r.get("id")) == only]+ # A clip can have a retake AND a Face Fix waiting;+ # `to` says which file the person chose.+ want_to = f("to", "")+ if want_to:+ rows = [r for r in rows if str(r.get("to")) == want_to]else:rows = [r for r in rows if not r.get("retake")]swaps = {}@@ -30924,7 +31757,8 @@ class Handler(BaseHTTPRequestHandler):res = sedit.export_nle(edit.get("clips") or [], dest,name=Path(_sb_film_name(board)).stem,- fps=FPS, audio=audio, probe=_probe)+ fps=FPS, audio=audio, probe=_probe,+ audio_tracks=edit.get("audio_tracks") or None)except sedit.EditError as exc:self._json({"ok": False, "error": str(exc)}, 400)return@@ -31203,6 +32037,9 @@ def _avg_elapsed(kind: str | None = None) -> float | None:"""with LOCK:history_snap = list(STATE["history"][:10])+ # Music has its own explicitly unmeasured model. Its wall times must not+ # silently re-price the existing image/video estimates or their fallback.+ history_snap = [j for j in history_snap if (j.get("params") or {}).get("engine") != "music"]def _ok(j: dict) -> bool:return j.get("status") == "done" and j.get("elapsed_sec")@@ -31897,6 +32734,7 @@ def page(theme: str = "") -> str:# points at this block by name (its `probe` key), rather than the# switcher knowing anything about H3 in particular."h3": h3_status(),+ "music": music_status(),# LTX's own (quality × length) table, in the SAME shape as `h3` above so# the two strips are rendered by one generalised function rather than# two that drift. Every LTX estimate the page prints is a lookup intodiff --git a/panel/routes_files.py b/panel/routes_files.pyindex 744c216..3ce3b5f 100644--- a/panel/routes_files.py+++ b/panel/routes_files.py@@ -78,7 +78,9 @@ def get_file(h, parsed) -> None:h.send_error(404); returnif not path.exists():h.send_error(404); return- h._serve_video_with_range(path)+ ctype = {".wav": "audio/wav", ".mp4": "video/mp4", ".png": "image/png",+ ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp"}.get(path.suffix.lower(), "video/mp4")+ h._serve_video_with_range(path, ctype=ctype)@get("/image")@@ -164,13 +166,13 @@ def get_sidecar(h, parsed) -> None:# extension. Without this, an attacker who dropped a `.json`# alongside an arbitrary file under OUTPUT/UPLOADS could read# it via /sidecar?path=<that-file>. Sidecars are always- # `<media>.json` where <media> is mp4/png/webp/jpg/jpeg, so+ # `<media>.json` where <media> is mp4/png/webp/jpg/jpeg/wav, so# rejecting other suffixes closes that off without breaking# any legitimate caller. See security-review.md §M1.- _SIDECAR_MEDIA_SUFFIXES = {".mp4", ".png", ".webp", ".jpg", ".jpeg"}+ _SIDECAR_MEDIA_SUFFIXES = {".mp4", ".png", ".webp", ".jpg", ".jpeg", ".wav"}if path.suffix.lower() not in _SIDECAR_MEDIA_SUFFIXES:h.send_error(400, "sidecar requires media path "- "(.mp4/.png/.webp/.jpg)")+ "(.mp4/.png/.webp/.jpg/.jpeg/.wav)")return# Sidecars live next to the output they describe. Videos sit# under OUTPUT (mlx_outputs/*.mp4.json); image-mode queue jobsdiff --git a/panel/routes_models.py b/panel/routes_models.pyindex 461738b..3a04b1e 100644--- a/panel/routes_models.py+++ b/panel/routes_models.py@@ -76,7 +76,14 @@ def post_models_remove(h, path, qs, ctype) -> None:targets: list[P.Path] = []label = ""- if key.startswith("version:"):+ if key == "music":+ with P.LOCK:+ jobs = [P.STATE.get("current")] + list(P.STATE.get("queue") or [])+ if any(j and (j.get("params") or {}).get("engine") == "music" for j in jobs):+ h._json({"error": "Music is queued or rendering — stop or remove those jobs first."}, 409); return+ targets = [P.MUSIC_MODELS] if P.MUSIC_MODELS.is_dir() else []+ label = "YuE2 weights"+ elif key.startswith("version:"):vid = key.split(":", 1)[1]ver = next((v for v in P.MODEL_VERSIONS if v["id"] == vid), None)if not ver:diff --git a/panel/routes_queue.py b/panel/routes_queue.pyindex e0a1c0a..b43b4b2 100644--- a/panel/routes_queue.py+++ b/panel/routes_queue.py@@ -80,6 +80,8 @@ def get_status(h, parsed) -> None:# when history is empty (90s for images, 420s for videos).def _eta_for(job: dict) -> float:params = job.get("params") or {}+ if params.get("engine") == "music":+ return P.music_estimate(params["music_quality"], params["music_max_seconds"])["eta_sec"]if params.get("mode") == "image":return float(avg_image) if avg_image else 90.0return float(avg_video) if avg_video else 420.0@@ -107,7 +109,7 @@ def get_status(h, parsed) -> None:_cur_params = (payload["current"].get("params") or {})_mode = (_cur_params.get("mode") or "").lower()_engine = (_cur_params.get("engine") or "ltx").lower()- if _mode != "train" and _engine != "h3":+ if _mode != "train" and _engine not in ("h3", "music"):payload["current"]["progress"] = P._compute_progress(payload["current"], payload.get("log") or [],)@@ -208,6 +210,7 @@ def get_status(h, parsed) -> None:# Pinokio sidebar unlocks the engine pill without a panel restart,# exactly like the Q8 download already does.payload["h3"] = P.h3_status()+ payload["music"] = P.music_status()payload["train_profile"] = P.TRAIN_PROFILEpayload["train_presets"] = P.TRAIN_PRESETSpayload["train_style_presets"] = P.TRAIN_STYLE_PRESETS@@ -329,6 +332,9 @@ def post_queue_retry(h, path, qs, ctype) -> None:"error": None,}new_job["params"]["open_when_done"] = False+ new_job["params"].pop("face_fix_result", None)+ if new_job["params"].get("face_fix_targets"):+ new_job["params"]["face_fix_targets"] = [list(x) for x in new_job["params"]["face_fix_targets"]]new_job["params"]["source"] = "retry"with P.QUEUE_COND:P.STATE["queue"].append(new_job)@@ -554,6 +560,33 @@ def post_run(h, path, qs, ctype) -> None:h._json({"ok": True, "id": job["id"]})+# UPSCALE & FACE FIX as a clip action: one click on a finished clip (player,+# Outputs card, history row, Editor clip bar) queues the face-safe recipe for+# that clip. Server-side so the prompt/seed come from the clip's own sidecar+# and every door queues exactly the same job.+@post("/queue/facefix")+def post_queue_facefix(h, path, qs, ctype) -> None:+ _rb = h._read_form_body()+ if _rb is None:+ return+ body, form = _rb++ def f(name: str) -> str:+ v = form.get(name, "")+ if isinstance(v, list):+ v = v[0] if v else ""+ return str(v or "").strip()++ try:+ out = P.queue_face_fix(f("path"), board_id=f("board"), clip_id=f("clip"))+ except P.CharacterRequestError as exc:+ h._json({"ok": False, "error": str(exc)}, 400); return+ except Exception as exc: # noqa: BLE001+ h._json({"ok": False, "error": f"could not queue {P.FACE_FIX_NAME}: {exc}"}, 500)+ return+ h._json(out, 200 if out.get("ok") else 400)++# The chain held /stop as TWO arms split on ?mode=early; one path, one# handler, the same two branches.@post("/stop")diff --git a/panel/routes_storyboard.py b/panel/routes_storyboard.pyindex 04057a6..ec75876 100644--- a/panel/routes_storyboard.py+++ b/panel/routes_storyboard.py@@ -112,6 +112,49 @@ def post_storyboard_edit_upload(h, path, qs, ctype) -> None:200 if out.get("ok") else int(out.get("status") or 400))+# ====== the Editor's audio tracks — where a sound comes from ========+# The Sound source of the media pool: the film's own `audio/` folder and+# every sound file at the top of the outputs. A read; it makes nothing.+@get("/storyboard/edit/sounds")+def get_storyboard_edit_sounds(h, parsed) -> None:+ bid = (P.parse_qs(parsed.query).get("id") or [""])[0].strip()+ try:+ board = P.storyboard.load_storyboard(P.STATE_DIR, bid)+ except Exception as exc: # noqa: BLE001+ h._json({"ok": False, "error": str(exc)}, 404)+ return+ h._json({"ok": True, "sounds": P._sbe_list_sounds(board),+ "dir": str(P._sbe_sound_dir(board))})+++# One file → a sound an audio track can hold: probed for its length, and+# brought into the film's `audio/` folder when it lives anywhere the preview+# cannot play it from. The strip itself is placed by the client, which owns+# the arrangement, and saved like every other edit.+@post("/storyboard/edit/add-sound")+def post_storyboard_edit_add_sound(h, path, qs, ctype) -> None:+ _rb = h._read_form_body()+ if _rb is None:+ return+ _body, form = _rb++ def f(name: str) -> str:+ v = form.get(name) or [""]+ return str(v[0] if isinstance(v, list) else v).strip()++ try:+ board = P.storyboard.load_storyboard(P.STATE_DIR, f("id"))+ except Exception as exc: # noqa: BLE001+ h._json({"ok": False, "error": str(exc)}, 404)+ return+ try:+ out = P._sbe_add_sound(board, f("path"))+ except Exception as exc: # noqa: BLE001+ out = {"ok": False, "status": 500, "error": f"could not add that sound: {exc}"}+ h._json({k: v for k, v in out.items() if k != "status"},+ 200 if out.get("ok") else int(out.get("status") or 400))++# ====== Storyboard — plan a film, then shoot it ====================# Sits with the /queue/* cluster on purpose: every one of these routes# ends up going through the SAME make_job -> STATE["queue"] contractdiff --git a/pinokio.js b/pinokio.jsindex 46711b8..c06f64d 100644--- a/pinokio.js+++ b/pinokio.js@@ -44,6 +44,10 @@ function h3Capable() {}}+function musicCapable() {+ try { return os.totalmem() >= 24 * 1000 * 1000 * 1000 } catch (e) { return false }+}+function getInstallRoot(info) {// Pinokio's `info.path` API has shifted across versions:// - older Pinokio: info.path is a STRING property (the install dir itself)@@ -82,7 +86,7 @@ function loadRequired(installRoot) {// Deliberately narrow: `KEY=value`, no continuations, no expansion. Anything// this parser cannot read leaves the caller on its default, which is always the// shipped behaviour.-const ENV_KEYS = ["LTX_MODEL_VERSION", "LTX_H3_ROOT", "LTX_H3_MODELS"]+const ENV_KEYS = ["LTX_MODEL_VERSION", "LTX_H3_ROOT", "LTX_H3_MODELS", "LTX_MUSIC_ROOT", "LTX_MUSIC_MODELS"]function readEnvironment(installRoot) {const out = {}@@ -303,6 +307,50 @@ module.exports = {// made this look like data loss.const h3_repair = h3_weights && !h3_ready+ const musicRoot = underRoot(envFile.LTX_MUSIC_ROOT || "yue2-mlx", "")+ const musicModels = underRoot(envFile.LTX_MUSIC_MODELS || "mlx_models/yue2", "")+ const musicFile = p => { try { return fs.statSync(p).isFile() } catch (e) { return false } }+ let musicWeights = false+ try {+ const generator = path.join(musicModels, "generator")+ const files = JSON.parse(fs.readFileSync(path.join(generator, "conversion.json"), "utf8")).files+ const generatorNames = ["LICENSE", "THIRD_PARTY_NOTICES.md", "ar-8bit.safetensors", "ar-bf16.safetensors",+ "config.json", "licenses/SnakeBeta-NVIDIA-MIT.txt", "licenses/stable-audio-tools-MIT.txt",+ "nar-bf16.safetensors", "qwen.tiktoken"]+ const allowed = new Set([...Object.keys(files), "conversion.json", "README.md"])+ const clean = (dir, prefix = "") => fs.readdirSync(dir, { withFileTypes: true }).every(e => {+ const rel = prefix + e.name+ if (e.isSymbolicLink()) return false+ if (e.isDirectory()) return [...allowed].some(n => n.startsWith(rel + "/")) && clean(path.join(dir, e.name), rel + "/")+ return allowed.has(rel)+ })+ const vae = path.join(musicModels, "vae")+ const vfiles = JSON.parse(fs.readFileSync(path.join(vae, "weights_manifest.json"), "utf8")).files+ const intact = (base, entries) => Object.entries(entries).every(([n, r]) => {+ if (n.includes("..") || path.isAbsolute(n)) return false+ const st = fs.lstatSync(path.join(base, n))+ return st.isFile() && st.size > 0 && st.size === r.bytes && /^[0-9a-f]{64}$/.test(r.sha256)+ })+ musicWeights = Object.keys(files).length === generatorNames.length && generatorNames.every(n => files[n])+ && clean(generator) && intact(generator, files)+ && vfiles["model.safetensors"].bytes === 530512720+ && vfiles["model.safetensors"].sha256 === "807ce9d5149fa27c5ad3e6582058469852e908f6c5acc8c8aa338e7ab7751346"+ && intact(vae, vfiles)+ && ["config.json", "LICENSE", "THIRD_PARTY_NOTICES.md"].every(n => musicFile(path.join(vae, n)))+ && fs.readdirSync(path.join(vae, "licenses")).length > 0+ } catch (e) { /* partial pack: keep the install route available */ }+ const musicReady = musicWeights && ["python", "python3.12"].some(n => {+ const p = path.join(musicRoot, ".venv/bin", n)+ try { fs.accessSync(p, fs.constants.X_OK); return musicFile(p) } catch (e) { return false }+ })+ && musicFile(path.join(musicRoot, "pyproject.toml"))+ && musicFile(path.join(installRoot, "scripts/music/yue2_run.py"))+ const musicRepair = musicWeights && !musicReady+ const musicMenu = () => !musicCapable() ? [] : [musicReady || musicRepair+ ? { icon: "fa-solid fa-screwdriver-wrench", text: "Repair the music engine (weights kept — no re-download)", href: "install_music.js" }+ : { icon: "fa-solid fa-music", text: "Install the music engine (YuE2, ~11 GB)", href: "install_music.js" }]++// Keep the H3 recovery affordance reachable from EVERY menu state, not// only the healthy one. Reset wipes ltx-2-mlx, so env_ready goes false and// the menu early-returns (below) long before it reaches the H3 row — which@@ -311,6 +359,9 @@ module.exports = {// venv, weights in a different tree), so offering the repair mid-reinstall// is safe and never competes with the default action.const pushH3Recovery = (m) => {+ if (musicRepair && musicCapable()) {+ m.push({ icon: "fa-solid fa-screwdriver-wrench", text: "Repair the music engine (weights kept — no re-download)", href: "install_music.js" })+ }if (h3_repair && h3Capable()) {m.push({ icon: "fa-solid fa-screwdriver-wrench",text: "Repair Hailuo H3 (weights kept — no re-download)",@@ -409,6 +460,7 @@ module.exports = {sharp: info.running("install_sharp.js"),qwen: info.running("install_qwen.js"),h3: info.running("install_h3.js"),+ music: info.running("install_music.js"),}// Running states first — show what's in progress, hide everything else.@@ -418,6 +470,7 @@ module.exports = {if (running.q8download) return [{ default: true, icon: "fa-solid fa-download", text: `Downloading ${q8Name} (${q8Size})`, href: "download_q8.js" }]if (running.sharp) return [{ default: true, icon: "fa-solid fa-wand-magic-sparkles", text: "Installing Sharp upscaler", href: "install_sharp.js" }]if (running.qwen) return [{ default: true, icon: "fa-solid fa-images", text: "Installing Qwen-Image-Edit (multi-ref)", href: "install_qwen.js" }]+ if (running.music) return [{ default: true, icon: "fa-solid fa-music", text: "Installing the music engine (~11 GB)", href: "install_music.js" }]if (running.h3) return [{ default: true, icon: "fa-solid fa-comments", text: "Installing Hailuo H3 (~75 GB)", href: "install_h3.js" }]// No env at all → fresh install path. Recovery shortcuts to user content@@ -472,9 +525,13 @@ module.exports = {{ icon: "fa-solid fa-film", text: "Outputs", href: "mlx_outputs?fs=true" },{ icon: "fa-solid fa-cube", text: "Models", href: "mlx_models?fs=true" },{ icon: "fa-solid fa-image", text: "Uploads", href: "panel_uploads?fs=true" },+ // Settings → Models tells a running panel's user to click this, so it+ // has to exist while the panel runs. The install touches only+ // yue2-mlx/ and mlx_models/yue2/; the panel picks it up on /status.+ ...musicMenu(),]}- return [{ default: true, icon: "fa-solid fa-terminal", text: "Terminal", href: "start.js" }]+ return [{ default: true, icon: "fa-solid fa-terminal", text: "Terminal", href: "start.js" }, ...musicMenu()]}// Healthy install — Start path.@@ -507,6 +564,7 @@ module.exports = {// confusion: installing "Qwen" to use Ideogram).baseMenu.push({ icon: "fa-solid fa-images", text: "Reinstall image engines (Ideogram 4 + Qwen-Edit)", href: "install_qwen.js" })}+ baseMenu.push(...musicMenu())if (!h3_ready && h3Capable()) {// Second VIDEO engine — joint picture + dialogue + sound. Opt-in only:// ~75 GB, 36 GB+ Macs (H3_MIN_BYTES above), MiniMax Community Licensediff --git a/required_files.json b/required_files.jsonindex 3879268..7c94468 100644--- a/required_files.json+++ b/required_files.json@@ -227,8 +227,8 @@"_comment": "Pixel Spatial Upscaler x2 IC-LoRA - the OFFICIAL Lightricks LTX-2.5 adapter behind the Upscale x2 mode (a finished clip, typically an H3 draft, rides the IC reference channel and the 2.5 base re-renders it at twice the canvas with generated detail). The upstream repo is GATED (license click), so like the 2.5 packs the bytes come from the `mirror` block on the weights-ltx25-v1 release - one 327,322,640-byte safetensors (sha256 984851b769ea2bcb4c9e0a239a7676239e42c6a6001ddc69943b41ff0b283c1d, verified against the Hub's LFS oid before publishing) plus the LTX-2.x Community License text the adapter carries in its own metadata. Metadata reference_downscale_factor=2 (the IC loader halves the reference; handled in iclora_utils). `repo_id` is attribution; `download_include` is inert on the mirror lane and kept so the entry stays shaped like every other.","key": "ic_upscale_x2","kind": "optional",- "name": "Upscale x2 IC-LoRA (LTX-2.5, official)",- "blurb": "Optional, 0.3 GB. Powers the Upscale x2 mode - re-renders a clip (an H3 draft, say) at twice the size with real generated detail and keeps its sound. Mirrored on the Phosphene release, no HF token.",+ "name": "Upscale & Face Fix IC-LoRA (LTX-2.5, official)",+ "blurb": "Optional, 0.3 GB. Powers Upscale & Face Fix - re-renders a clip (an H3 draft, say) at twice the size with real generated detail and keeps its sound. Mirrored on the Phosphene release, no HF token.","repo_id": "Lightricks/LTX-2.5-22b-IC-LoRA-Pixel-Spatial-Upscaler","local_dir": "mlx_models/loras/ic","size_gb": 0.33,diff --git a/scripts/check_pinokio_scripts.js b/scripts/check_pinokio_scripts.jsindex 5683033..0fc0159 100644--- a/scripts/check_pinokio_scripts.js+++ b/scripts/check_pinokio_scripts.js@@ -73,7 +73,7 @@ const path = require("path")const MAX_DISPATCH = 500const SCRIPTS = [- "install.js", "update.js", "install_h3.js", "install_qwen.js",+ "install.js", "update.js", "install_h3.js", "install_music.js", "install_qwen.js","install_sharp.js", "download_q8.js", "download_upscaler.js","start.js", "reset.js", "pinokio.js",]diff --git a/scripts/measure_editor_layout.py b/scripts/measure_editor_layout.pyindex 1f22782..9d26b42 100644--- a/scripts/measure_editor_layout.py+++ b/scripts/measure_editor_layout.py@@ -719,6 +719,12 @@ JS_HANDLES = r"""const out = { blocks: {}, errors: [] };if (typeof sbeTlSet !== 'function') { out.errors.push('sbeTlSet missing'); return out; }+ // THE HANDLES THIS GATE MEASURES LIVE ON THE SOUND LANES, and those lanes now+ // make themselves small when nobody is working on sound — a grip inside an+ // 18px strip is not the control this gate is about, and the page would have+ // compacted underneath it a couple of seconds after it loaded. Hold them open+ // the way a user does with the ▾ on the A1 head, through the app's own writer.+ if (typeof sbeAudioPinSet === 'function') sbeAudioPinSet('open');sbeTlSet(%(tl)s);if (typeof sbePaint === 'function') sbePaint();await settle();diff --git a/scripts/music/engine_pin.txt b/scripts/music/engine_pin.txtnew file mode 100644index 0000000..6c0b0fc--- /dev/null+++ b/scripts/music/engine_pin.txt@@ -0,0 +1 @@+9253ed133343406947bde7b67d43c7a63fb39d99diff --git a/scripts/music/yue2_run.py b/scripts/music/yue2_run.pynew file mode 100644index 0000000..4d615ae--- /dev/null+++ b/scripts/music/yue2_run.py@@ -0,0 +1,305 @@+#!/usr/bin/env python3+"""Phosphene's YuE2 music runner — one song per process.++Runs inside the music engine's own venv (Python 3.12, mlx 0.32.2, the+`mlx-yue` package from vanch007/mlx-Yue pinned by SHA). The Phosphene panel+spawns it the way it spawns the H3 runner: argv in, parseable progress lines+on stdout, a WAV plus a provenance sidecar out, SIGTERM to stop.++Progress protocol (one line each, stdout, flushed):+ [music] stage <name>+ [music] plan <k> ABC score tokens written so far+ [music] song <k>/<max> semantic tokens (25 per second of audio)+ [music] synth <k>/<n> flow-matching steps+ [music] decode <k>/<n> VAE tiles+ [music] done <seconds> <path>+ [music] error <message>++Exit codes: 0 ok · 2 bad input · 3 memory guard · 130 stopped · 1 other.++YuE2 has no duration input. A song is as long as its lyrics make it; the+only length control is the semantic token budget, which TRUNCATES (25 tokens+= 1 s). `--max-seconds` sets that budget and the sidecar records whether the+song ended naturally or was cut.+"""+from __future__ import annotations++import argparse+import json+import os+import platform+import signal+import sys+import threading+import time+from pathlib import Path++TOKENS_PER_SECOND = 25+MAX_SECONDS = 360 # upstream semantic max_tokens 9000+RUNNER_VERSION = "1"+# YuE2 has no instrumental switch. Its lyrics protocol reads bare section tags+# with no lines under them as instrumental passages, so an instrumental request+# is a skeleton of tags plus an explicit style cue. Validated by ear in the+# bake-off (notes/yue2/MEASUREMENTS.md).+INSTRUMENTAL_LYRICS = "[Intro]\n\n[Instrumental]\n\n[Instrumental]\n\n[Outro]"+INSTRUMENTAL_STYLE = "instrumental, no vocals"+++def say(*parts):+ print("[music]", *parts, flush=True)+++def parse_args(argv=None):+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ p.add_argument("--model-dir", required=True, type=Path, help="converted generator dir (conversion.json)")+ p.add_argument("--vae-dir", required=True, type=Path, help="YuE2-Vae dir (model.safetensors + config.json)")+ p.add_argument("--output", required=True, type=Path, help=".wav or .flac")+ p.add_argument("--style", default="")+ p.add_argument("--lyrics", default=None)+ p.add_argument("--lyrics-file", type=Path, default=None)+ p.add_argument("--abc-file", type=Path, default=None, help="supplied ABC score (full/melody only)")+ p.add_argument("--mode", choices=("full", "melody", "off"), default="full")+ p.add_argument("--instrumental", action="store_true",+ help="no vocal line: lyrics become bare section tags (see INSTRUMENTAL_LYRICS)")+ p.add_argument("--seed", type=int, default=-1)+ p.add_argument("--max-seconds", type=float, default=MAX_SECONDS)+ p.add_argument("--steps", type=int, default=32, help="flow-matching midpoint steps (32 = reference)")+ p.add_argument("--cfg-scale", type=float, default=None)+ p.add_argument("--precision", choices=("bf16", "8bit", "4bit"), default="bf16")+ p.add_argument("--memory-budget-gib", type=float, default=None)+ p.add_argument("--vae-core-frames", type=int, default=256)+ p.add_argument("--artifacts", type=Path, default=None, help="also keep score/tokens/latents here")+ p.add_argument("--sidecar", type=Path, default=None, help="default: <output>.json")+ p.add_argument("--extra-json", default=None, help="merged into the sidecar (panel provenance)")+ return p.parse_args(argv)+++def default_budget_gib():+ """Whole-process footprint budget. Upstream fixes 16 GiB and refuses+ anything that leaves < 4 GiB for the OS; scale with the machine instead."""+ try:+ import psutil+ total = psutil.virtual_memory().total / 2**30+ except Exception:+ return 16.0+ return float(max(12, min(24, int(total) - 8)))+++def relax_guard():+ """The upstream guard samples SYSTEM-WIDE pressure and swap every 0.25 s+ and aborts on any non-normal reading. Inside Phosphene the panel, the+ browser and other apps move those numbers, so a single transient sample+ killed whole songs. Keep the per-process footprint budget strict; tolerate+ transient pressure while real headroom remains; bound swap growth by a+ configurable, larger window. Same idea as yue2-studio's 24 GB patch."""+ from lyra import measure++ gib, mib = measure._GIB, measure._MIB+ min_avail = float(os.environ.get("YUE2_MIN_AVAILABLE_GIB", "1.5"))+ swap_out = float(os.environ.get("YUE2_MAX_SWAP_OUT_MIB", "1024"))+ swap_growth = float(os.environ.get("YUE2_MAX_SWAP_GROWTH_MIB", "2048"))+ counters = {"pressure_warnings": 0, "peak_footprint_gib": 0.0, "min_available_gib": None}++ def check(self, sample):+ if self._baseline is None:+ self._baseline = sample+ footprint = sample["physical_footprint_bytes"]+ counters["peak_footprint_gib"] = max(counters["peak_footprint_gib"], round(footprint / gib, 2))+ avail = round(sample["system_available_bytes"] / gib, 2)+ if counters["min_available_gib"] is None or avail < counters["min_available_gib"]:+ counters["min_available_gib"] = avail+ if footprint > self.memory_budget_gib * gib:+ raise MemoryError(f"Process footprint {footprint / gib:.2f} GiB exceeds "+ f"{self.memory_budget_gib:g} GiB budget")+ if sample["system_available_bytes"] < min_avail * gib:+ raise MemoryError(f"Less than {min_avail:g} GiB of system memory available")+ if sample["system_memory_pressure_level"] != 1:+ counters["pressure_warnings"] += 1+ swapped = sample["system_swap_out_bytes"] - self._baseline["system_swap_out_bytes"]+ growth = sample["system_swap_used_bytes"] - self._baseline["system_swap_used_bytes"]+ if swapped > swap_out * mib or growth > swap_growth * mib:+ raise MemoryError(f"Stopping: the system is swapping ({swapped / mib:.0f} MiB out, "+ f"{growth / mib:.0f} MiB swap growth)")++ measure.GPUExecution._check_sample = check+ return {"min_available_gib": min_avail, "max_swap_out_mib": swap_out,+ "max_swap_growth_mib": swap_growth, "counters": counters}+++def main(argv=None):+ args = parse_args(argv)+ t0 = time.perf_counter()+ out = args.output.expanduser().resolve()+ if out.suffix.lower() not in (".wav", ".flac"):+ say("error", "output must end in .wav or .flac")+ return 2+ if args.lyrics_file is not None:+ lyrics = args.lyrics_file.read_text(encoding="utf-8")+ else:+ lyrics = args.lyrics or ""+ style = (args.style or "").strip()+ lyrics = lyrics.replace("\r\n", "\n").strip("\n")+ if args.instrumental:+ lyrics = INSTRUMENTAL_LYRICS+ if "instrumental" not in style.lower():+ style = f"{style}, {INSTRUMENTAL_STYLE}" if style else INSTRUMENTAL_STYLE+ if not style and not lyrics.strip():+ say("error", "Give it something to work with — lyrics, a style description, or both.")+ return 2+ abc = args.abc_file.read_text(encoding="utf-8") if args.abc_file else None+ if abc is not None and args.mode == "off":+ say("error", "a supplied score needs mode full or melody")+ return 2+ seed = args.seed if args.seed is not None and args.seed >= 0 else int.from_bytes(os.urandom(4), "little")+ max_seconds = max(8.0, min(float(args.max_seconds), float(MAX_SECONDS)))+ max_tokens = int(round(max_seconds * TOKENS_PER_SECOND))+ semantic_sampling = {"max_tokens": max_tokens, "min_tokens": min(200, max_tokens)}++ stop = threading.Event()++ def on_signal(signum, _frame):+ stop.set()+ say("stage", "stopping")++ signal.signal(signal.SIGTERM, on_signal)+ signal.signal(signal.SIGINT, on_signal)++ os.environ.setdefault("MLX_ENABLE_TF32", "0")+ say("stage", "loading")+ import mlx.core as mx+ from yue2.protocol import GenerationConfig+ from lyra.pipeline import YuE2Pipeline++ guard = relax_guard()+ budget = args.memory_budget_gib or default_budget_gib()+ counts = {"abc": 0, "semantic": 0}+ last = {"t": 0.0}++ def on_token(phase, _token):+ counts[phase] = counts.get(phase, 0) + 1+ now = time.monotonic()+ if now - last["t"] >= 0.5:+ last["t"] = now+ if phase == "abc":+ say("plan", counts["abc"])+ else:+ say("song", f"{counts['semantic']}/{max_tokens}")++ config = GenerationConfig(ode_steps=int(args.steps))+ pipe = YuE2Pipeline(+ args.model_dir, args.vae_dir, precision=args.precision, generation_config=config,+ memory_budget_gib=budget, vae_core_frames=args.vae_core_frames, progress=False,+ )+ # Surface the NAR / VAE progress the pipeline only reports when its own+ # stderr progress is enabled.+ from lyra import nar as _nar+ _orig_synth = _nar.synthesize++ def synth_with_progress(*a, on_progress=None, **kw):+ def report(k, n):+ if on_progress is not None:+ on_progress(k, n)+ say("synth", f"{k}/{n}")+ return _orig_synth(*a, on_progress=report, **kw)++ _nar.synthesize = synth_with_progress+ from lyra import vae as _vae+ _orig_decode = _vae.OobleckDecoder.decode++ def decode_with_progress(self, *a, on_progress=None, **kw):+ def report(k, n):+ if on_progress is not None:+ on_progress(k, n)+ say("decode", f"{k}/{n}")+ return _orig_decode(self, *a, on_progress=report, **kw)++ _vae.OobleckDecoder.decode = decode_with_progress+ peak = {"gib": 0.0}+ try:+ with pipe:+ say("stage", "planning" if args.mode != "off" and abc is None else "writing")+ kw = dict(style=style, lyrics=lyrics, cot=args.mode, seed=seed,+ semantic_sampling=semantic_sampling, cancelled=stop.is_set,+ on_token=on_token)+ if abc is not None:+ kw["abc"] = abc+ if args.cfg_scale is not None:+ kw["cfg_scale"] = float(args.cfg_scale)+ result = pipe(**kw)+ # The port checks cancellation before each decode tile, not after+ # the last one: a Stop that lands there must not publish a song.+ if stop.is_set():+ raise InterruptedError("stopped after decoding")+ peak["gib"] = mx.get_peak_memory() / 2**30+ out.parent.mkdir(parents=True, exist_ok=True)+ import soundfile as sf+ subtype = "PCM_24"+ tmp = out.with_name(out.stem + ".partial" + out.suffix)+ sf.write(tmp, result.audio, result.sample_rate, subtype=subtype,+ format="WAV" if out.suffix.lower() == ".wav" else "FLAC")+ # Last chance for Stop: past this line the song is published.+ if stop.is_set():+ tmp.unlink(missing_ok=True)+ raise InterruptedError("stopped before publishing")+ os.replace(tmp, out)+ if args.artifacts is not None:+ result.save_artifacts(args.artifacts)+ except InterruptedError:+ say("error", "stopped")+ return 130+ except MemoryError as exc:+ say("error", f"memory guard: {exc}")+ return 3+ except Exception as exc: # noqa: BLE001 — the panel shows this line+ say("error", f"{type(exc).__name__}: {exc}")+ raise++ seconds = len(result.audio) / result.sample_rate+ truncated = dict(result.truncated) if isinstance(result.truncated, dict) else result.truncated+ sidecar = {+ "engine": "music",+ "model": "YuE2-3B",+ "model_credit": "YuE2 by Multimodal Art Projection (m-a-p), CC BY-NC 4.0 + creator permission",+ "port": "vanch007/mlx-Yue (MLX)",+ "runner": f"phosphene yue2_run v{RUNNER_VERSION}",+ "style": style,+ "lyrics": lyrics,+ "mode": args.mode,+ "instrumental": bool(args.instrumental),+ "abc_supplied": abc is not None,+ "score_abc": result.abc,+ "seed": seed,+ "steps": int(args.steps),+ "cfg_scale": args.cfg_scale,+ "precision": args.precision,+ "max_seconds": max_seconds,+ "audio_seconds": round(seconds, 3),+ "sample_rate": result.sample_rate,+ "channels": int(result.audio.shape[1]) if result.audio.ndim == 2 else 1,+ "truncated": truncated,+ "ended_naturally": not (result.truncated.get("semantic") if isinstance(result.truncated, dict) else bool(result.truncated)),+ "timing": result.timing,+ "wall_seconds": round(time.perf_counter() - t0, 2),+ "mlx_peak_gib": round(peak["gib"], 2),+ "memory_budget_gib": budget,+ "guard": {k: v for k, v in guard.items() if k != "counters"} | guard["counters"],+ "weights": {"mot": (result.weights.get("mot") or {}).get("files") and+ {k: v.get("sha256") for k, v in result.weights["mot"]["files"].items()+ if isinstance(v, dict)}},+ "runtime": {"python": platform.python_version(), "mlx": mx.__version__,+ "macos": platform.mac_ver()[0], "machine": platform.machine()},+ "output": str(out),+ }+ if args.extra_json:+ try:+ sidecar.update(json.loads(args.extra_json))+ except ValueError:+ pass+ side = args.sidecar or out.with_name(out.name + ".json")+ side.write_text(json.dumps(sidecar, indent=2, ensure_ascii=False, default=str), encoding="utf-8")+ say("done", f"{seconds:.2f}", str(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/pinokio/music_checkout.sh b/scripts/pinokio/music_checkout.shnew file mode 100644index 0000000..9accad7--- /dev/null+++ b/scripts/pinokio/music_checkout.sh@@ -0,0 +1,13 @@+#!/usr/bin/env bash+# One checkout implementation for Install and Update. The SHA has one home.+set -euo pipefail+MUSIC_PIN_FILE="$(cd "$(dirname "$0")/../music" && pwd)/engine_pin.txt"+MUSIC_PIN=$(cat "$MUSIC_PIN_FILE")+MUSIC_CHECKOUT="${1:?music checkout required}"+[ -d "$MUSIC_CHECKOUT/.git" ] || { echo 'No music engine checkout to pin'; exit 1; }+cd "$MUSIC_CHECKOUT"+# Fetch succeeds before a forced checkout; app-managed source, external weights.+git fetch --force origin "$MUSIC_PIN"+git checkout --force --detach FETCH_HEAD+[ "$(git rev-parse HEAD)" = "$MUSIC_PIN" ]+echo "YuE2 engine pinned to $MUSIC_PIN"diff --git a/scripts/pinokio/music_clone.sh b/scripts/pinokio/music_clone.shnew file mode 100644index 0000000..baef7e0--- /dev/null+++ b/scripts/pinokio/music_clone.sh@@ -0,0 +1,6 @@+#!/usr/bin/env bash+set -euo pipefail+MUSIC_CHECKOUT="${LTX_MUSIC_ROOT:-$PWD/yue2-mlx}"+if [ ! -d "$MUSIC_CHECKOUT/.git" ]; then+ git clone --no-checkout https://github.com/vanch007/mlx-Yue "$MUSIC_CHECKOUT"+fidiff --git a/scripts/pinokio/music_fetch.py b/scripts/pinokio/music_fetch.pynew file mode 100644index 0000000..286d164--- /dev/null+++ b/scripts/pinokio/music_fetch.py@@ -0,0 +1,254 @@+#!/usr/bin/env python3+"""Resumable YuE2 pack fetch / offline verifier. No model imports.++Downloads go ONLY into .staging. The generator loader rejects HF's .cache+and every undeclared file/directory. Receipts and the current model permission+therefore live at the pack root, outside generator/. HF_HOME is inherited.+"""+from __future__ import annotations++import argparse+import hashlib+import json+import os+from pathlib import Path, PurePosixPath+import re+import shutil+import sys+import time++# The public repos the pinned mlx-Yue port documents, pinned by revision. The+# generator is vanch007's MLX conversion (its BF16 tensors are byte-identical to+# m-a-p/YuE2-3B); the decoder is the original m-a-p/YuE2-Vae file. Phosphene+# re-hosts nothing: bump a revision here only together with engine_pin.txt.+SOURCES = {+ "generator": {"repo": "vanch007/mlx-Yue2-3B", "revision": "fa66d203dd56d7e033e05ee8b32269768984c4cc", "prefix": ""},+ "vae": {"repo": "m-a-p/YuE2-Vae", "revision": "95535e72a97bc0f09b8ada125d26b4009428c0e8", "prefix": ""},+}+GENERATOR_FILES = (+ "LICENSE", "THIRD_PARTY_NOTICES.md", "ar-8bit.safetensors", "ar-bf16.safetensors",+ "config.json", "licenses/SnakeBeta-NVIDIA-MIT.txt", "licenses/stable-audio-tools-MIT.txt",+ "nar-bf16.safetensors", "qwen.tiktoken",+)+VAE_FILES = ("model.safetensors", "config.json", "weights_manifest.json", "LICENSE", "THIRD_PARTY_NOTICES.md")+VAE_SHA256 = "807ce9d5149fa27c5ad3e6582058469852e908f6c5acc8c8aa338e7ab7751346"+VAE_BYTES = 530512720+PACK_BYTES = 10448112576 # approximate; free-space decisions use missing manifest bytes+++def digest(path: Path) -> str:+ h = hashlib.sha256()+ with path.open("rb") as f:+ for block in iter(lambda: f.read(8 * 1024 * 1024), b""):+ h.update(block)+ return h.hexdigest()+++def safe_name(name: str) -> str:+ p = PurePosixPath(name)+ if not name or p.is_absolute() or ".." in p.parts or "\\" in name or str(p) != name:+ raise ValueError(f"unsafe manifest path: {name!r}")+ return name+++def records(path: Path) -> dict:+ data = json.loads(path.read_text(encoding="utf-8"))+ files = data.get("files") if isinstance(data, dict) else None+ if not isinstance(files, dict) or not files:+ raise ValueError(f"empty files map: {path.name}")+ for name, rec in files.items():+ safe_name(name)+ if not isinstance(rec, dict) or not re.fullmatch(r"[0-9a-f]{64}", str(rec.get("sha256", ""))):+ raise ValueError(f"missing sha256: {name}")+ if not isinstance(rec.get("bytes"), int) or rec["bytes"] < 1:+ raise ValueError(f"invalid byte count: {name}")+ return files+++def file_problem(path: Path, rec: dict | None = None, *, hashes: bool = False) -> str | None:+ if not path.is_file() or path.is_symlink():+ return "missing file"+ try:+ size = path.stat().st_size+ if size == 0 or (rec and size != rec["bytes"]):+ return "size mismatch"+ if hashes and rec and digest(path) != rec["sha256"]:+ return "sha256 mismatch"+ except OSError as e:+ return str(e)+ return None+++def pack_problems(root: Path, *, hashes: bool = False) -> list[str]:+ """Stat-only for /status; full hashes for Install/Update/--check."""+ errors = []+ for part, manifest, required in (("generator", "conversion.json", GENERATOR_FILES),+ ("vae", "weights_manifest.json", VAE_FILES)):+ base = root / part+ try:+ recs = records(base / manifest)+ if part == "generator" and set(recs) != set(GENERATOR_FILES):+ errors.append("generator/conversion.json: unexpected files map")+ if part == "vae" and (recs.get("model.safetensors", {}).get("sha256") != VAE_SHA256+ or recs.get("model.safetensors", {}).get("bytes") != VAE_BYTES):+ errors.append("vae/weights_manifest.json: unexpected model identity")+ except (OSError, ValueError, TypeError) as e:+ recs = {}+ errors.append(f"{part}/{manifest}: missing or invalid ({e})")+ for name in sorted(set(required) | set(recs) | {manifest}):+ problem = file_problem(base / name, recs.get(name), hashes=hashes)+ if problem:+ errors.append(f"{part}/{name}: {problem}")+ if part == "generator":+ allowed = set(recs) | {manifest, "README.md"}+ parents = {str(p) for n in allowed for p in PurePosixPath(n).parents if str(p) != "."}+ for p in base.rglob("*"):+ rel = p.relative_to(base).as_posix()+ if p.is_symlink() or (rel not in (parents if p.is_dir() else allowed)):+ errors.append(f"generator/{rel}: unexpected entry")+ elif not any((base / "licenses").glob("*")):+ errors.append("vae/licenses: missing notices")+ # Records all downloaded files, including metadata that has no source hash.+ receipt = root / "pack_source.json"+ if receipt.is_file():+ try:+ for name, rec in records(receipt).items():+ problem = file_problem(root / name, rec, hashes=hashes)+ if problem:+ errors.append(f"{name}: {problem}")+ except (ValueError, OSError, TypeError) as e:+ errors.append(f"pack_source.json: {e}")+ return errors+++def choose_sources(api=None) -> dict:+ return {k: dict(v) for k, v in SOURCES.items()}+++def fetch_pack(root: Path, min_free_gb: float) -> None:+ from huggingface_hub import HfApi, hf_hub_download+ api = HfApi()+ root.mkdir(parents=True, exist_ok=True)+ # Restore the current permission on repairs too, including offline repairs.+ notices = Path(__file__).resolve().parents[2] / "LICENSES"+ for name in ("YuE2-MODEL_LICENSE.txt", "NOTICE-yue2.md"):+ shutil.copyfile(notices / name, root / name)+ # Completely intact repairs are offline and never require another 14 GB.+ if not pack_problems(root, hashes=True) and (root / "pack_source.json").is_file():+ print("YuE2 pack verified; all files intact, no download needed.", flush=True)+ return+ sources = choose_sources(api)+ stage = root / ".staging"+ receipts = {}++ def download(part, name, rec=None):+ safe_name(name)+ src = sources[part]+ dest = root / part / name+ if rec and file_problem(dest, rec, hashes=True) is None:+ print(f"Keep {part}/{name} (sha256 OK)", flush=True)+ receipts[f"{part}/{name}"] = rec+ return dest+ print(f"Fetch {part}/{name} from {src['repo']} @ {src['revision']}", flush=True)+ for attempt in range(2):+ staged = Path(hf_hub_download(repo_id=src["repo"], revision=src["revision"],+ filename=src["prefix"] + name, local_dir=stage / part,+ force_download=bool(attempt)))+ actual = {"bytes": staged.stat().st_size, "sha256": digest(staged)}+ if rec and actual != {"bytes": rec["bytes"], "sha256": rec["sha256"]}:+ if not attempt:+ continue+ raise ValueError(f"sha256/size mismatch after download: {part}/{name}")+ dest.parent.mkdir(parents=True, exist_ok=True)+ os.replace(staged, dest)+ receipts[f"{part}/{name}"] = actual+ return dest+ raise AssertionError("unreachable")++ gen = records(download("generator", "conversion.json"))+ if set(gen) != set(GENERATOR_FILES):+ raise ValueError("generator conversion.json does not describe the expected YuE2 pack")+ vae = records(download("vae", "weights_manifest.json"))+ if (vae.get("model.safetensors", {}).get("bytes") != VAE_BYTES+ or vae.get("model.safetensors", {}).get("sha256") != VAE_SHA256):+ raise ValueError("VAE manifest does not match the pinned model")+ # A file that finished downloading but was interrupted before it was moved+ # into place is still in .staging: verify and promote it now, or it would be+ # priced (and fetched) a second time.+ for part, rs in (("generator", gen), ("vae", vae)):+ for n, r in rs.items():+ dest = root / part / n+ staged = stage / part / (sources[part]["prefix"] + n)+ if file_problem(dest, r, hashes=True) and staged.is_file() and not staged.is_symlink():+ if file_problem(staged, r, hashes=True) is None:+ dest.parent.mkdir(parents=True, exist_ok=True)+ os.replace(staged, dest)+ print(f"Promoted staged {part}/{n} (sha256 OK)", flush=True)+ # Only absent/corrupt bytes need space. os.replace avoids a second copy.+ missing_bytes = sum(r["bytes"] for part, rs in (("generator", gen), ("vae", vae))+ for n, r in rs.items() if file_problem(root / part / n, r, hashes=True))+ # huggingface_hub never resumes: every attempt writes a fresh+ # <name>.<uuid>.incomplete and an interrupted one is simply abandoned. Those+ # are this installer's own staging leftovers, so clear them before pricing+ # the space the missing files need.+ if stage.is_dir():+ for leftover in stage.rglob("*.incomplete"):+ try:+ leftover.unlink()+ except OSError:+ pass+ needed = missing_bytes + max(0, min_free_gb * 1e9 - PACK_BYTES) if missing_bytes else 0+ try:+ free = shutil.disk_usage(root).free+ except OSError:+ print("Cannot read free disk space; continuing (preflight fail-open).", flush=True)+ else:+ if free < needed:+ raise ValueError(f"YuE2 needs {needed / 1e9:.1f} GB free for missing files; {free / 1e9:.1f} GB available")+ for name, rec in gen.items():+ download("generator", name, rec)+ vs = sources["vae"]+ names = api.list_repo_files(vs["repo"], revision=vs["revision"])+ vae_names = set(VAE_FILES) | set(vae)+ vae_names.update(n[len(vs["prefix"]):] for n in names if n.startswith(vs["prefix"] + "licenses/"))+ for name in sorted(vae_names - {"weights_manifest.json"}):+ download("vae", name, vae.get(name))+ # Recover from a previous direct `hf download --local-dir generator`.+ cache = root / "generator" / ".cache"+ if cache.exists():+ quarantine = stage / f"generator-cache-{time.time_ns()}"+ shutil.move(str(cache), str(quarantine))+ print("Moved HF metadata out of generator/ into .staging.", flush=True)+ receipt = {"sources": sources, "files": receipts}+ tmp = root / "pack_source.json.tmp"+ tmp.write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8")+ tmp.replace(root / "pack_source.json")+ errors = pack_problems(root, hashes=True)+ if errors:+ raise ValueError("\n".join(errors))+ print("YuE2 pack verified. Generator tree is clean; every recorded sha256 matches.", flush=True)+++def main(argv=None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--models", type=Path, default=Path(os.environ.get("LTX_MUSIC_MODELS", Path(__file__).resolve().parents[2] / "mlx_models/yue2")))+ parser.add_argument("--check", action="store_true", help="offline verification only; exit 0/1")+ parser.add_argument("--min-free-gb", type=float, default=14.0)+ args = parser.parse_args(argv)+ try:+ if args.check:+ errors = pack_problems(args.models, hashes=True)+ for error in errors:+ print(error, flush=True)+ if not errors:+ print("YuE2 pack verified (sha256 + exact generator tree).", flush=True)+ return int(bool(errors))+ fetch_pack(args.models, max(0, args.min_free_gb))+ return 0+ except (OSError, ValueError, RuntimeError) as e:+ print(f"YuE2 pack: {e}", file=sys.stderr, flush=True)+ return 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/pinokio/music_preflight.sh b/scripts/pinokio/music_preflight.shnew file mode 100644index 0000000..3f02d7f--- /dev/null+++ b/scripts/pinokio/music_preflight.sh@@ -0,0 +1,23 @@+#!/usr/bin/env bash+# Same 24 GB floor as MUSIC_MIN_RAM_GB and the sidebar. Unknown RAM/df is fail-open.+set -u+MUSIC_MEM=$(sysctl -n hw.memsize 2>/dev/null || true)+if [[ "$MUSIC_MEM" =~ ^[0-9]+$ ]] && [ "$MUSIC_MEM" -lt 24000000000 ]; then+ echo "YuE2 needs about 24 GB of unified memory; this Mac reports $((MUSIC_MEM / 1000000000)) GB. The rest of Phosphene is unaffected."+ exit 1+fi+MUSIC_DEST="${LTX_MUSIC_MODELS:-mlx_models/yue2}"+# df must inspect the destination volume even before its directory exists.+while [ ! -d "$MUSIC_DEST" ] && [ "$MUSIC_DEST" != / ] && [ "$MUSIC_DEST" != . ]; do+ MUSIC_DEST=$(dirname "$MUSIC_DEST")+done+MUSIC_FREE=$(df -Pk "$MUSIC_DEST" 2>/dev/null | awk 'NR==2 {print $4}')+# Repair with weights already present needs no second 14 GB reserve.+if [ -f "${LTX_MUSIC_MODELS:-mlx_models/yue2}/generator/conversion.json" ]; then+ echo 'YuE2 repair: the fetcher will check space for missing files only.'+elif [[ "$MUSIC_FREE" =~ ^[0-9]+$ ]] && [ "$MUSIC_FREE" -lt 13671875 ]; then+ echo 'Installing YuE2 needs at least 14 GB free on the weights volume.'+ exit 1+else+ echo 'YuE2 preflight OK (24 GB memory, 14 GB free disk required).'+fidiff --git a/scripts/pinokio/music_sync.sh b/scripts/pinokio/music_sync.shnew file mode 100755index 0000000..6162bf4--- /dev/null+++ b/scripts/pinokio/music_sync.sh@@ -0,0 +1,8 @@+#!/usr/bin/env bash+# Frozen dependency sync for the music engine venv. The checkout path is made+# absolute first: uv resolves a relative UV_PROJECT_ENVIRONMENT against the+# project dir, so LTX_MUSIC_ROOT=engines/yue2 would otherwise install into+# engines/yue2/engines/yue2/.venv while everything else uses engines/yue2/.venv.+set -euo pipefail+MUSIC_CHECKOUT="$(cd "${1:?music checkout required}" && pwd)"+UV_PROJECT_ENVIRONMENT="$MUSIC_CHECKOUT/.venv" uv sync --frozen --no-dev --project "$MUSIC_CHECKOUT"diff --git a/scripts/pinokio/music_venv.sh b/scripts/pinokio/music_venv.shnew file mode 100644index 0000000..7fb4237--- /dev/null+++ b/scripts/pinokio/music_venv.sh@@ -0,0 +1,8 @@+#!/usr/bin/env bash+# Python 3.12 / MLX 0.32.2 must never enter LTX's Python 3.11 / MLX 0.31.1 venv.+set -euo pipefail+MUSIC_CHECKOUT="${1:?music checkout required}"+# A pyvenv.cfg can survive a dangling managed-Python symlink. Probe execution.+if ! "$MUSIC_CHECKOUT/.venv/bin/python" -c 'import sys; assert sys.version_info[:2] == (3, 12)' >/dev/null 2>&1; then+ uv venv --clear --python 3.12 "$MUSIC_CHECKOUT/.venv"+fidiff --git a/scripts/post_update.sh b/scripts/post_update.shindex da9833e..fe6ea73 100644--- a/scripts/post_update.sh+++ b/scripts/post_update.sh@@ -356,4 +356,20 @@ if ! "$PY" -c "import ltx_core_mlx; import ltx_pipelines_mlx; import mlx" 2>/devfirequire "the render engine import gate" -- "$PY" -c "import ltx_core_mlx, ltx_pipelines_mlx, mlx"+# Music is independent of LTX. Update only an installed checkout; never pull+# an 11 GB pack as a side effect of an ordinary panel update.+MUSIC_CHECKOUT="${LTX_MUSIC_ROOT:-$ROOT/yue2-mlx}"+MUSIC_MODELS_ROOT="${LTX_MUSIC_MODELS:-$ROOT/mlx_models/yue2}"+if [ -d "$MUSIC_CHECKOUT/.git" ] && [ -f "$MUSIC_CHECKOUT/.venv/pyvenv.cfg" ]; then+ echo 'Checking the pinned YuE2 engine and installed music pack…'+ if bash "$ROOT/scripts/pinokio/music_checkout.sh" "$MUSIC_CHECKOUT" \+ && bash "$ROOT/scripts/pinokio/music_venv.sh" "$MUSIC_CHECKOUT" \+ && bash "$ROOT/scripts/pinokio/music_sync.sh" "$MUSIC_CHECKOUT" \+ && "$MUSIC_CHECKOUT/.venv/bin/python" "$ROOT/scripts/pinokio/music_fetch.py" --models "$MUSIC_MODELS_ROOT" --check; then+ echo 'YuE2 engine and weights verified.'+ else+ echo 'WARN: YuE2 needs repair. Run Repair the music engine from the sidebar; intact weights are kept.'+ fi+fi+echo "=== post-update complete ==="diff --git a/scripts/release_gates.sh b/scripts/release_gates.shindex 3b7d343..d7f244f 100755--- a/scripts/release_gates.sh+++ b/scripts/release_gates.sh@@ -174,6 +174,11 @@ echo "== root test sweep (unittest) =="for t in test_*.py; do[ -e "$t" ] || continuemod="${t%.py}"+ # Music uses pytest fixtures; unittest would falsely report zero tests.+ if [ "$mod" = "test_music_engine" ]; then+ run_gate "$mod" "$VENV_PY" -m pytest -q "$t"+ continue+ fiif [ "$FAST" = "1" ] && [ "$mod" = "test_storyboard_editor_ui" ]; thenmark_skip "$mod" "--fast"continuediff --git a/storyboard_editor.py b/storyboard_editor.pyindex 2c515c7..bb8a1a8 100644--- a/storyboard_editor.py+++ b/storyboard_editor.py@@ -76,12 +76,18 @@ __all__ = ["migrate_edit", "clip_kind", "clip_brightness", "clip_carries_media","clip_audio", "clip_audio_drift", "clip_audio_resync", "clip_muted","clip_effects", "clip_length",+ "SOUND_LANES", "clip_sound_lane", "sound_lane_label", "alternate_sound_lanes",+ "sound_lane_after","audio_effects", "audio_gain_points", "audio_gain_at","MIX_BED_GAIN", "MIX_DUCK", "MIX_LEGACY_BED_GAIN", "MIX_DUCK_GAIN","MIX_DUCK_ATTACK", "MIX_DUCK_RELEASE", "MIX_CEILING","MIX_REPAIR_VERSION", "audio_mix", "bed_length", "audible_strips","bed_duck_points", "bed_duck_suppressed", "bed_gain_points","bed_gain_at", "bed_render_gain", "heal_mix",+ "SOUND_SUFFIXES", "TRACK_STRIP_MIN", "audio_tracks", "track_strips",+ "track_label", "track_gain", "track_muted", "strip_gain", "strip_muted",+ "strip_window", "track_strip_gain_points", "track_strip_gain_at",+ "track_render_strips","overlay_items", "overlay_kind", "OVERLAY_SUFFIXES","blocking_errors", "WARNING_CODES", "repair_audio_overlaps","edit_digest", "session_token_path", "claim_session", "current_session",@@ -307,10 +313,16 @@ def clip_audio(clip) -> dict:and a clip only carries the field once somebody has actually pulled thetwo apart.- NOT A SECOND AUDIO TRACK. The refuse list still holds: one video track,- one music lane, and per-clip sound that is linked by default. The audio- windows may not overlap each other any more than the pictures may — a- split edit is a butt join that lands somewhere else, not a mix.+ TWO LANES, AND THE OVERLAP LIVES BETWEEN THEM. Until 2026-09-15 this said+ "not a second audio track": one lane, where a split edit is a butt join+ that lands somewhere else. The owner, cutting Saint Feld: "the sound+ between clips should already be intercalated into two different lanes …+ if I want to blend and dissolve from both sides, cut a little, and bring+ the clips together to make it more realistic, it's easy." So a clip's+ sound sits on lane A or lane B (`clip_sound_lane`), windows may still not+ overlap WITHIN a lane, and the two lanes overlap and mix — which is how+ every NLE's A/B roll makes a sound dissolve. The window itself is unchanged+ by the lane; this function does not report it."""if not isinstance(clip, dict):return {"start": 0.0, "end": 0.0, "film_start": 0.0,@@ -396,6 +408,85 @@ SPEED_MIN = 0.25SPEED_MAX = 4.0+# ---- THE TWO CLIP-SOUND LANES (A/B) ----------------------------------------+# THE OWNER, 2026-09-15: "When the app creates a timeline, the sound between+# clips should already be intercalated into two different lanes. Clip 1: the+# sound is in one lane. Clip 2: the sound is in another lane. If I want to+# blend and dissolve from both sides, cut a little, and bring the clips+# together to make it more realistic, it's easy."+#+# That is the A/B roll, the oldest trick in sound editing: alternate shots+# between two tracks so a neighbour's tail and head can overlap and fade+# against each other instead of butting. The A1 track grows a second lane —+# "Clip sound A" and "Clip sound B" on screen — and A2 stays the music.+#+# ABSENT IS LANE A, the migration every field on a clip follows: every+# document ever written plays every clip on A exactly as before, and only a+# clip on B carries `sound_lane: 2`. No-overlap is a rule WITHIN a lane.+SOUND_LANES = (1, 2)+++def clip_sound_lane(clip) -> int:+ """Which clip-sound lane this clip's own sound plays on: 1 (A) or 2 (B).++ Only a VIDEO clip has sound, so a still or a slug is always 1 — the answer+ that asks nothing of the renderer. Anything but the integer 2 is lane A.+ """+ if not isinstance(clip, dict) or clip_kind(clip) != "video":+ return 1+ v = clip.get("sound_lane")+ return 2 if (v == 2 and not isinstance(v, bool)) else 1+++def sound_lane_label(lane: int) -> str:+ """What a person reads: "A" or "B"."""+ return "B" if int(lane or 1) == 2 else "A"+++def alternate_sound_lanes(clips) -> int:+ """Lay every video clip's sound on A, B, A, B… in FILM order. In place.++ Moves no picture and no sound in time — only which lane each strip is on —+ so a timeline re-laid by this plays every second where it did. Clips with+ no picture of their own (stills, slugs) are skipped and do not take a turn:+ alternation is between the sounds that actually meet. Returns how many+ clips changed lane.+ """+ rows = [c for c in (clips or []) if isinstance(c, dict)+ and clip_kind(c) == "video"]+ rows.sort(key=lambda c: (_f(c.get("film_start")), str(c.get("id") or "")))+ changed = 0+ for k, c in enumerate(rows):+ want = 1 if k % 2 == 0 else 2+ if clip_sound_lane(c) != want:+ changed += 1+ if want == 2:+ c["sound_lane"] = 2+ else:+ c.pop("sound_lane", None)+ return changed+++def sound_lane_after(clips, film_start: float) -> int:+ """The lane a clip arriving at `film_start` takes: NOT the previous one's.++ The previous video clip on the film decides, because that is the sound a+ new shot's head meets. With nothing before it, the lane opposite the next+ clip's, so alternation holds from either side; an empty film starts on A.+ """+ fs = _f(film_start)+ vids = sorted((c for c in (clips or []) if isinstance(c, dict)+ and clip_kind(c) == "video"),+ key=lambda c: _f(c.get("film_start")))+ before = [c for c in vids if _f(c.get("film_start")) < fs - 1e-9]+ if before:+ return 2 if clip_sound_lane(before[-1]) == 1 else 1+ after = [c for c in vids if _f(c.get("film_start")) >= fs - 1e-9]+ if after:+ return 2 if clip_sound_lane(after[0]) == 1 else 1+ return 1++def clip_speed(clip) -> float:"""The clip's play rate, clamped. 1.0 when absent, and always 1.0 for astill or a slug — they have no source clock to run fast or slow."""@@ -1104,6 +1195,364 @@ def bed_render_gain(edit) -> list[list[float]]:return [[round(t + d, 6), g] for t, g in curve]+# ---------------------------------------------------------------------------+# THE AUDIO TRACKS — A3, A4, … under the music+# ---------------------------------------------------------------------------+# THE OWNER'S CASE: "You actually need to have multiple audio clips, like we+# have multiple video layers... you stack them on top of each other." A laugh+# track, a slap-bass sting and a looping bed on one film, and nowhere to put+# any of them: A1 is each shot's own sound and A2 holds ONE soundtrack.+#+# SO A LIST OF TRACKS, EACH A LIST OF STRIPS, and the refuse list's old rule+# ("one lane, a split edit is a butt join") moves to where it still belongs:+# strips on the SAME track may not overlap — a track is a lane, and an NLE+# refuses two clips on one lane at one second — while strips on DIFFERENT+# tracks overlap and mix, which is the whole point of having more than one.+#+# edit["audio_tracks"] = [+# {"id", "name", "muted"?, "gain"?,+# "strips": [{"id", "path", "film_start", "start", "end", "duration"?,+# "gain"?, "muted"?, "locked"?, "title"?,+# "afx"?: {"fade_in", "fade_out", "points"}}]}]+#+# `afx` IS THE SAME OBJECT a clip's sound and the bed carry, read by the same+# `audio_effects` / `audio_gain_points` — one envelope model for every sound on+# the timeline, not a fourth. `start`/`end` are SOURCE seconds (the in and out+# points inside the file); a strip plays at 1x, so its length on the film is+# `end - start`. `gain` is a static fader on the strip and `gain` on the track+# is a second one on the lane; both are linear 0..1 like the bed's, and both+# multiply the envelope — exactly the `bed_gain` rule, for the same reason.+#+# ABSENT IS NONE, the migration every field in this file follows: a document+# with no tracks has no key, so every edit.json ever written loads, validates,+# saves and renders byte-identically, and EDIT_VERSION does not move.+#+# THE CLOCK IS THE BED'S. A strip's `film_start` is a timeline second, laid out+# with `adelay` the way the soundtrack is — not re-flowed through the picture+# concat — so a strip sits where the music would sit at the same second.+SOUND_SUFFIXES = (".wav", ".m4a", ".mp3", ".aac", ".flac", ".aif", ".aiff",+ ".ogg", ".opus")+# Shorter than this is not a sound, it is a click — the same idea as a clip's+# `SBE_MIN_CLIP`, and the floor the trim handles stop at.+TRACK_STRIP_MIN = 0.05+++def audio_tracks(edit) -> list[dict]:+ """The tracks, in lane order. Anything that is not an object is dropped."""+ rows = edit.get("audio_tracks") if isinstance(edit, dict) else None+ if not isinstance(rows, list):+ return []+ return [t for t in rows if isinstance(t, dict)]+++def track_strips(track) -> list[dict]:+ """One track's strips, as stored. Non-objects are dropped."""+ rows = track.get("strips") if isinstance(track, dict) else None+ if not isinstance(rows, list):+ return []+ return [s for s in rows if isinstance(s, dict)]+++def track_label(index: int) -> str:+ """What the lane head says: A3 for the first track, because A1 and A2 are+ taken by the clips' own sound and the music."""+ return f"A{int(index) + 3}"+++def _unit_gain(v) -> float:+ """A fader value: 1.0 when absent, clamped to 0..1 like `bed_gain`."""+ if v is None or isinstance(v, bool):+ return 1.0+ g = _f(v, 1.0)+ if g != g:+ return 1.0+ return round(max(0.0, min(1.0, g)), 6)+++def track_gain(track) -> float:+ return _unit_gain((track or {}).get("gain") if isinstance(track, dict) else None)+++def track_muted(track) -> bool:+ return isinstance(track, dict) and track.get("muted") is True+++def strip_gain(strip) -> float:+ return _unit_gain((strip or {}).get("gain") if isinstance(strip, dict) else None)+++def strip_muted(strip) -> bool:+ return isinstance(strip, dict) and strip.get("muted") is True+++def strip_window(strip) -> dict:+ """`{start, end, film_start, film_end, len}` for one strip. 1x, always."""+ s = strip if isinstance(strip, dict) else {}+ st, en = _f(s.get("start")), _f(s.get("end"))+ fs = _f(s.get("film_start"))+ n = max(0.0, en - st)+ return {"start": round(st, 6), "end": round(en, 6),+ "film_start": round(fs, 6), "film_end": round(fs + n, 6),+ "len": round(n, 6)}+++def track_strip_gain_points(track, strip) -> list[list[float]]:+ """THE ONE STRIP CURVE: `[[t, gain], ...]` on the STRIP's own clock.++ The bed's three-term rule with the duck left out (a track is not ducked by+ anything): the authored envelope from `audio_gain_points`, multiplied by the+ strip's fader and the track's fader. Preview, render and export read this+ and nothing else. Empty means unity means no filter, so an untouched strip+ builds the shortest chain the render can make.+ """+ n = strip_window(strip)["len"]+ if n <= 0:+ return []+ g0 = round(strip_gain(strip) * track_gain(track), 6)+ curve = audio_gain_points(strip, n)+ if not curve:+ if abs(g0 - 1.0) < 1e-9:+ return []+ return [[0.0, g0], [round(n, 6), g0]]+ return [[t, round(max(0.0, min(1.0, g * g0)), 6)] for t, g in curve]+++def track_strip_gain_at(track, strip, t: float) -> float:+ """The gain at one second of the strip. The preview's per-frame answer."""+ curve = track_strip_gain_points(track, strip)+ if not curve:+ return 1.0+ return round(_lerp_gain(curve, max(0.0, _f(t))), 6)+++def track_render_strips(edit) -> list[dict]:+ """Every strip the render has to MIX, in film order.++ `[{track, track_index, id, path, start, end, at, len, gain}]` — the source+ window, the film second it lands on, and its curve on its own clock. A muted+ strip, a strip on a muted track and a strip whose curve is silence the whole+ way contribute nothing, so they cost the graph no input and no chain.+ """+ out: list[dict] = []+ for ti, t in enumerate(audio_tracks(edit)):+ if track_muted(t):+ continue+ for s in track_strips(t):+ path = str(s.get("path") or "")+ if strip_muted(s) or not path:+ continue+ w = strip_window(s)+ if w["len"] <= 1e-6:+ continue+ gain = track_strip_gain_points(t, s)+ if gain and all(g <= 1e-9 for _, g in gain):+ continue+ out.append({"track": str(t.get("id") or ""), "track_index": ti,+ "id": str(s.get("id") or ""), "path": path,+ "start": w["start"], "end": w["end"],+ "at": w["film_start"], "len": w["len"],+ "gain": gain})+ out.sort(key=lambda r: (r["at"], r["track_index"], r["id"]))+ return out+++def _is_num(v) -> bool:+ return (isinstance(v, (int, float)) and not isinstance(v, bool)+ and v == v and v not in (float("inf"), float("-inf")))+++def _validate_audio_tracks(edit, bad) -> None:+ """The tracks' half of `validate_edit`. `bad(code, message)` records one.++ Shape errors are errors, and so is two strips on ONE track claiming the+ same second: a lane plays one sound at a time in every NLE, and the client+ never produces the state, so a document carrying it is corrupt rather than+ an edit in progress. Two strips on two tracks at one second is the feature.+ """+ rows = edit.get("audio_tracks")+ if rows is None:+ return+ if not isinstance(rows, list):+ bad("audio_tracks_shape", "audio_tracks must be a list or absent")+ return+ for ti, t in enumerate(rows):+ who = track_label(ti)+ if not isinstance(t, dict):+ bad("audio_track_shape", f"audio track {who} must be an object")+ continue+ if t.get("name") is not None and not isinstance(t.get("name"), str):+ bad("audio_track_name", f"audio track {who}: name must be text")+ if t.get("muted") is not None and not isinstance(t.get("muted"), bool):+ bad("audio_track_muted", f"audio track {who}: muted must be true or false")+ g = t.get("gain")+ if g is not None:+ if not _is_num(g):+ bad("audio_track_gain", f"audio track {who}: gain must be a number")+ elif not 0.0 <= float(g) <= 1.0:+ bad("audio_track_gain_range",+ f"audio track {who}: gain must be between 0 and 1")+ strips = t.get("strips")+ if strips is None:+ continue+ if not isinstance(strips, list):+ bad("audio_track_strips", f"audio track {who}: strips must be a list")+ continue+ spans: list[tuple[float, float, int]] = []+ for si, s in enumerate(strips):+ at = f"audio track {who}, sound {si + 1}"+ if not isinstance(s, dict):+ bad("track_strip_shape", f"{at} must be an object")+ continue+ path = s.get("path")+ if not isinstance(path, str) or not path.strip():+ bad("track_strip_path", f"{at} has no file")+ broken = False+ for key in ("start", "end", "film_start"):+ if not _is_num(s.get(key)):+ bad(f"track_strip_{key}", f"{at}: {key} must be a number")+ broken = True+ if broken:+ continue+ st, en, fs = float(s["start"]), float(s["end"]), float(s["film_start"])+ if st < 0:+ bad("track_strip_start", f"{at}: start must be >= 0")+ if fs < 0:+ bad("track_strip_film_start", f"{at}: film_start must be >= 0")+ if en <= st:+ bad("track_strip_window",+ f"{at}: end ({en}) must be after start ({st})")+ dur = s.get("duration")+ if _is_num(dur) and float(dur) > 0 and en > float(dur) + 1e-3:+ bad("track_strip_past_the_end",+ f"{at}: the sound ends at {en:.3f}s but the file is "+ f"{float(dur):.3f}s long")+ sg = s.get("gain")+ if sg is not None:+ if not _is_num(sg):+ bad("track_strip_gain", f"{at}: gain must be a number")+ elif not 0.0 <= float(sg) <= 1.0:+ bad("track_strip_gain_range", f"{at}: gain must be between 0 and 1")+ for key in ("muted", "locked"):+ if s.get(key) is not None and not isinstance(s.get(key), bool):+ bad(f"track_strip_{key}", f"{at}: {key} must be true or false")+ if s.get("title") is not None and not isinstance(s.get("title"), str):+ bad("track_strip_title", f"{at}: title must be text")+ afx = s.get("afx")+ if afx is not None and not isinstance(afx, dict):+ bad("track_strip_afx", f"{at}: afx must be an object or absent")+ elif isinstance(afx, dict):+ for key in ("fade_in", "fade_out"):+ v = afx.get(key)+ if v is None:+ continue+ if not _is_num(v):+ bad(f"track_strip_{key}", f"{at}: afx.{key} must be a number")+ elif float(v) < 0:+ bad(f"track_strip_{key}_range", f"{at}: afx.{key} must be >= 0")+ pts = afx.get("points")+ if pts is not None and not isinstance(pts, list):+ bad("track_strip_afx_points", f"{at}: afx.points must be a list or absent")+ elif isinstance(pts, list):+ for row in pts:+ if not isinstance(row, (list, tuple)) or len(row) != 2 \+ or not all(_is_num(x) for x in row):+ bad("track_strip_afx_point",+ f"{at}: every afx point is [seconds, gain]")+ break+ if en > st and fs >= 0:+ spans.append((fs, fs + (en - st), si))+ spans.sort()+ for (a_s, a_e, a_i), (b_s, b_e, b_i) in zip(spans, spans[1:]):+ if b_s < a_e - TOUCH_TOLERANCE:+ bad("audio_track_strips_overlap",+ f"audio track {who}: sounds {a_i + 1} and {b_i + 1} overlap "+ f"({a_s:.3f}-{a_e:.3f}s and {b_s:.3f}-{b_e:.3f}s) — one track "+ f"plays one sound at a time; put the other on another track")+++def _normalise_audio_tracks(out: dict) -> None:+ """Round, sort, invent ids, drop neutral fields. Mutates `out`.++ NOTHING IS DECIDED: a strip is never moved, trimmed or re-tracked here. An+ empty track list is an absent key, so a timeline that never had one is+ byte-identical to one written before tracks existed; an empty TRACK is+ kept, because somebody pressed "+ Add audio track" and means to use it.+ """+ rows = audio_tracks(out)+ if not rows:+ out.pop("audio_tracks", None)+ return+ tracks: list[dict] = []+ seen_t: set = set()+ seen_s: set = set()+ for ti, t in enumerate(rows):+ t2 = dict(t)+ tid = str(t2.get("id") or "") or ("t" + _clip_id(f"track{ti}", ti, 0.0)[:10])+ while tid in seen_t:+ tid = tid + "x"+ seen_t.add(tid)+ t2["id"] = tid+ name = t2.get("name")+ if isinstance(name, str) and name.strip():+ t2["name"] = name.strip()[:60]+ else:+ t2.pop("name", None)+ if t2.get("muted") is True:+ t2["muted"] = True+ else:+ t2.pop("muted", None)+ g = track_gain(t2)+ if abs(g - 1.0) > 1e-9:+ t2["gain"] = g+ else:+ t2.pop("gain", None)+ strips = []+ for s in track_strips(t2):+ s2 = {k: v for k, v in s.items() if not str(k).startswith("_")}+ for k in ("start", "end", "film_start"):+ s2[k] = round(_f(s2.get(k)), 6)+ s2["path"] = str(s2.get("path") or "")+ sid = str(s2.get("id") or "") or _clip_id(s2["path"], s2["start"],+ s2["film_start"])+ while sid in seen_s:+ sid = sid + "x"+ seen_s.add(sid)+ s2["id"] = sid+ dur = s2.get("duration")+ if _is_num(dur) and float(dur) > 0:+ s2["duration"] = round(float(dur), 6)+ else:+ s2.pop("duration", None)+ title = s2.get("title")+ if isinstance(title, str) and title.strip():+ s2["title"] = title.strip()[:200]+ else:+ s2.pop("title", None)+ sg = strip_gain(s2)+ if abs(sg - 1.0) > 1e-9:+ s2["gain"] = sg+ else:+ s2.pop("gain", None)+ for key in ("muted", "locked"):+ if s2.get(key) is True:+ s2[key] = True+ else:+ s2.pop(key, None)+ ae = audio_effects(s2, strip_window(s2)["len"])+ akeep = {k: ae[k] for k in ("fade_in", "fade_out") if ae[k] > 1e-9}+ if ae["points"]:+ akeep["points"] = ae["points"]+ if akeep:+ s2["afx"] = akeep+ else:+ s2.pop("afx", None)+ strips.append(s2)+ strips.sort(key=lambda x: (x["film_start"], x["id"]))+ t2["strips"] = strips+ tracks.append(t2)+ out["audio_tracks"] = tracks++def clip_audio_drift(clip) -> float:"""How far an UNLINKED sound has drifted from the picture it came from.@@ -1573,6 +2022,11 @@ def edit_from_plan(plan, *, board_id: str = "", audio: dict | None = None,},**extra,))+ # A FRESH TIMELINE IS LAID A/B. Every new cut alternates its clips' sound+ # between the two lanes by film order, so neighbouring shots can overlap+ # and crossfade the moment somebody trims them together — the owner's+ # default, not a mode.+ alternate_sound_lanes(clips)return normalise_edit({"version": EDIT_VERSION,"board_id": board_id,@@ -2072,6 +2526,13 @@ def validate_edit(edit) -> list[dict]:bad("clip_audio_past_the_end",f"clip {i + 1}: the sound ends at {w['end']:.3f}s but "f"the source is {float(dur):.3f}s long", i)+ sl = c.get("sound_lane")+ if sl is not None and (isinstance(sl, bool) or sl not in SOUND_LANES):+ # Only a VALUE is refused. A stale lane on a still is dropped by+ # `normalise_edit` rather than blocking a save over a field the+ # picture cannot use.+ bad("clip_sound_lane",+ f"clip {i + 1}: sound_lane must be 1, 2 or absent", i)afx = c.get("afx")if afx is not None and not isinstance(afx, dict):bad("clip_afx", f"clip {i + 1}: afx must be an object or absent", i)@@ -2271,24 +2732,32 @@ def validate_edit(edit) -> list[dict]:f"clips {a_i + 1} and {b_i + 1} overlap on the film "f"({a_s:.3f}-{a_e:.3f}s and {b_s:.3f}-{b_e:.3f}s) — one video "f"track can only play one of them", b_i)- # THE SAME RULE FOR THE SOUND, and it is what keeps a split edit from- # becoming the multi-track mixer the refuse list bans. A J-cut is a butt- # join that lands somewhere the picture does not; it is still one lane, so- # two clips' sound may no more overlap than two clips' pictures.- asp: list[tuple[float, float, int]] = []- for i, c in enumerate(clips):- if not isinstance(c, dict) or clip_kind(c) != "video":- continue- w = clip_audio(c)- if w["end"] > w["start"]:- asp.append((w["film_start"], w["film_start"] + w["len"], i))- asp.sort()- for (a_s, a_e, a_i), (b_s, b_e, b_i) in zip(asp, asp[1:]):- if b_s < a_e - TOUCH_TOLERANCE:- bad("clips_audio_overlap",- f"the sound of clips {a_i + 1} and {b_i + 1} overlaps "- f"({a_s:.3f}-{a_e:.3f}s and {b_s:.3f}-{b_e:.3f}s) — a split "- f"edit moves the sound, it does not add a second track", b_i)+ # THE SAME RULE FOR THE SOUND — WITHIN A LANE. Two clips' sound on ONE+ # lane may no more overlap than two pictures may (the render trims the+ # outgoing tail there); on lane A and lane B they overlap and mix, which+ # is the whole point of having two (`clip_sound_lane`).+ for lane in SOUND_LANES:+ asp: list[tuple[float, float, int]] = []+ for i, c in enumerate(clips):+ if not isinstance(c, dict) or clip_kind(c) != "video":+ continue+ if clip_sound_lane(c) != lane:+ continue+ w = clip_audio(c)+ if w["end"] > w["start"]:+ asp.append((w["film_start"], w["film_start"] + w["len"], i))+ asp.sort()+ for (a_s, a_e, a_i), (b_s, b_e, b_i) in zip(asp, asp[1:]):+ if b_s < a_e - TOUCH_TOLERANCE:+ bad("clips_audio_overlap",+ f"the sound of clips {a_i + 1} and {b_i + 1} overlaps on "+ f"sound lane {sound_lane_label(lane)} "+ f"({a_s:.3f}-{a_e:.3f}s and {b_s:.3f}-{b_e:.3f}s) — one lane "+ f"plays one sound at a time; put one of them on the other "+ f"sound lane to hear both", b_i)+ # THE AUDIO TRACKS (A3, A4, …) — where a second sound at the same second+ # DOES belong. Their own rules live beside their model.+ _validate_audio_tracks(edit, bad)return errs@@ -2582,6 +3051,13 @@ def normalise_edit(edit: dict) -> dict:c.pop("afx", None)else:c.pop("afx", None)+ # THE LANE, neutral-is-absent: lane A is no field at all, so a+ # document that never used lane B is byte-identical to one written+ # before there were two.+ if clip_sound_lane(c) == 2:+ c["sound_lane"] = 2+ else:+ c.pop("sound_lane", None)if kind != "video":c.pop("audio", None)elif isinstance(c.get("audio"), dict):@@ -2701,6 +3177,8 @@ def normalise_edit(edit: dict) -> dict:out["transitions"] = txselse:out.pop("transitions", None)+ # THE AUDIO TRACKS. Same discipline, and an empty list is an absent key.+ _normalise_audio_tracks(out)out.setdefault("board_id", "")# NEUTRAL IS ABSENT, the same rule `adjust` follows one block up. Dragging# a trim handle back to the end of the track must leave a document@@ -3501,6 +3979,10 @@ def edit_to_cuts(edit: dict) -> list[dict]:# the identical graph it always did.if clip_muted(c):entry["mute"] = True+ # Lane B only. A film that never used it hands the assembler the+ # list it always did, and the graph cannot change.+ if clip_sound_lane(c) == 2:+ entry["lane"] = 2# EFFECTS RIDE ON EVERY KIND — a still and a slug fade like anything# else, and all three outputs read the same entry.e = clip_effects(c)@@ -3844,6 +4326,8 @@ def _nle_segments(clips, *, probe=None) -> list[dict]:# clipitem rather than dropping it, so the editor on the far end# can see the decision and undo it."muted": clip_muted(c),+ # Which clip-sound lane — the XML writes lane B as its own track.+ "lane": clip_sound_lane(c),"source_duration": _f(info.get("duration"))or (fe - fs if kind != "video" else 0.0),})@@ -3982,7 +4466,8 @@ def _fcp7_file(fid: str, seg: dict, media_abs: Path, *, fps: int,def fcp7_xml(segments, *, name: str, media: dict, width: int, height: int,base, fps: int = NLE_FPS, audio: dict | None = None,- overlays: list | None = None) -> str:+ overlays: list | None = None,+ audio_tracks: list | None = None) -> str:"""The sequence, as the one XML both Premiere and Resolve import.SLUGS ARE GAPS. A slug could be written as a `<generatoritem>` with the@@ -3993,7 +4478,9 @@ def fcp7_xml(segments, *, name: str, media: dict, width: int, height: int,script, which has no such ambiguity, gets real black solids.THE AUDIO IS STEMS, NOT THE MIX. The clips' own sound goes on A1 and the- soundtrack goes on A2, unducked. The under-mix the renderer builds —+ soundtrack goes on A2, unducked. A film that uses the second clip-sound+ lane writes it as its own track straight after the first — "Clip sound A",+ "Clip sound B", then the music — so the A/B roll arrives as an A/B roll. The under-mix the renderer builds —sidechain compression against the dialogue, then a tanh ceiling — has norepresentation in an NLE's timeline at all, so baking it in would hand aneditor a bed they cannot unmix and cannot re-balance. Stems are what the@@ -4010,7 +4497,7 @@ def fcp7_xml(segments, *, name: str, media: dict, width: int, height: int,mdir = Path(str(base)) / "media"file_ids: dict = {}total = max([_frames(s["film_end"], fps) for s in segments] or [0])- v_items, a_items = [], []+ v_items, a_items, b_items = [], [], []for i, seg in enumerate(segments):if seg["kind"] == "slug":continue # a gap on the track IS the slug@@ -4046,7 +4533,7 @@ def fcp7_xml(segments, *, name: str, media: dict, width: int, height: int,# from a source without one. `<enabled>FALSE</enabled>` is the# timeline's own word for "this is here and it is off", and one# click puts it back.- a_items.append(+ (b_items if seg.get("lane") == 2 else a_items).append(f'<clipitem id="clipitem-a{i + 1}">'f"<name>{_xml_text(seg['title'])}</name>"f"<enabled>{'FALSE' if seg.get('muted') else 'TRUE'}</enabled>"@@ -4122,6 +4609,57 @@ def fcp7_xml(segments, *, name: str, media: dict, width: int, height: int,f"<sourcetrack><mediatype>audio</mediatype>"f"<trackindex>1</trackindex></sourcetrack>"f"</clipitem></track>")+ # ---- A3, A4, …: the audio tracks, one XML track each ----------------+ # STEMS, the same promise the music makes: every strip is a clipitem with+ # its own in/out, its level curve as keyframes (the fades folded in, the+ # strip and track faders multiplied through — `track_strip_gain_points`),+ # and a muted strip or track DISABLED rather than dropped, so the decision+ # arrives in the NLE and one click undoes it.+ extra_tracks = ""+ for ti, trk in enumerate(audio_tracks or []):+ if not isinstance(trk, dict):+ continue+ items = []+ for si, s in enumerate(track_strips(trk)):+ src = str(s.get("path") or "")+ if not src or src not in media:+ continue+ w = strip_window(s)+ if w["len"] <= 0:+ continue+ abs_media = mdir / media[src]+ fid = "file-" + str(file_ids.setdefault(src, len(file_ids) + 1))+ if fid in declared:+ fel = f'<file id="{_xml_text(fid)}"/>'+ else:+ declared.add(fid)+ sdur = _f(s.get("duration"))+ fel = (f'<file id="{_xml_text(fid)}">'+ f"<name>{_xml_text(abs_media.name)}</name>"+ f"<pathurl>{_xml_text(_pathurl(abs_media))}</pathurl>"+ f"{_fcp7_rate(fps)}"+ + (f"<duration>{_frames(sdur, fps)}</duration>" if sdur > 0 else "")+ + "<media><audio><samplecharacteristics><depth>16</depth>"+ "<samplerate>48000</samplerate></samplecharacteristics>"+ "<channelcount>2</channelcount></audio></media></file>")+ f_in, f_out = _frames(w["start"], fps), _frames(w["end"], fps)+ f_s = _frames(w["film_start"], fps)+ f_e = max(f_s + 1, _frames(w["film_end"], fps))+ on = not (strip_muted(s) or track_muted(trk))+ items.append(+ f'<clipitem id="clipitem-t{ti + 1}s{si + 1}">'+ f"<name>{_xml_text(str(s.get('title') or Path(src).stem))}</name>"+ f"<enabled>{'TRUE' if on else 'FALSE'}</enabled>"+ f"<duration>{max(1, f_out - f_in)}</duration>"+ f"{_fcp7_rate(fps)}"+ f"<start>{f_s}</start><end>{f_e}</end>"+ f"<in>{f_in}</in><out>{max(f_in + 1, f_out)}</out>"+ f"{fel}"+ f"<sourcetrack><mediatype>audio</mediatype>"+ f"<trackindex>1</trackindex></sourcetrack>"+ f"{_fcp7_levels(track_strip_gain_points(trk, s), fps)}"+ f"</clipitem>")+ extra_tracks += f"<track>{''.join(items)}</track>"return ('<?xml version="1.0" encoding="UTF-8"?>\n'"<!DOCTYPE xmeml>\n"@@ -4148,7 +4686,11 @@ def fcp7_xml(segments, *, name: str, media: dict, width: int, height: int,"</video>""<audio>"f"<track>{''.join(a_items)}</track>"+ # LANE B ONLY WHEN IT IS USED, so an export of a film that never+ # touched it is the file it always was.+ f"{('<track>' + ''.join(b_items) + '</track>') if b_items else ''}"f"{music_track}"+ f"{extra_tracks}""</audio>""</media>""</sequence>\n"@@ -4157,7 +4699,8 @@ def fcp7_xml(segments, *, name: str, media: dict, width: int, height: int,def ae_jsx(segments, *, name: str, media: dict, width: int, height: int,fps: int = NLE_FPS, audio: dict | None = None,- overlays: list | None = None) -> str:+ overlays: list | None = None,+ audio_tracks: list | None = None) -> str:"""An ExtendScript that BUILDS the comp, because AE cannot import a timeline.It locates its own folder (`File($.fileName).parent`) and imports from the@@ -4332,6 +4875,42 @@ def ae_jsx(segments, *, name: str, media: dict, width: int, height: int," lay.inPoint = %.6f;" % win["delay"]," lay.outPoint = %.6f;" % max(win["delay"] + 1e-3, end_film),]+ # ---- A3, A4, …: every strip its own layer, named for its track -------+ # The same stem rule as the soundtrack. A video file used for its sound+ # only keeps its picture switched off, so the comp shows what the film does.+ for ti, trk in enumerate(audio_tracks or []):+ if not isinstance(trk, dict):+ continue+ tname = str(trk.get("name") or track_label(ti))+ for si, s in enumerate(track_strips(trk)):+ src = str(s.get("path") or "")+ if not src or src not in media:+ continue+ w = strip_window(s)+ if w["len"] <= 0:+ continue+ rel = "/media/" + media[src]+ lines += [+ f" // {track_label(ti)} sound {si + 1}",+ " lay = comp.layers.add(bring(%s));" % _jsx_string(rel),+ " lay.name = %s;" % _jsx_string(+ tname + " · " + str(s.get("title") or Path(src).stem)),+ " lay.startTime = %.6f;" % (w["film_start"] - w["start"] + 0.0),+ " lay.inPoint = %.6f;" % w["film_start"],+ " lay.outPoint = %.6f;" % max(w["film_start"] + 1e-3, w["film_end"]),+ ]+ if Path(src).suffix.lower() not in SOUND_SUFFIXES:+ lines.append(" if (lay.hasVideo) { lay.enabled = false; }")+ gain = track_strip_gain_points(trk, s)+ if len(gain) >= 2:+ lines.append(" au = lay.property('ADBE Audio Group')"+ ".property('ADBE Audio Levels');")+ for t, g in gain:+ db = -96.0 if g <= 1e-6 else max(-96.0, 20.0 * math.log10(g))+ lines.append(" au.setValueAtTime(%.6f, [%.3f, %.3f]);"+ % (w["film_start"] + t, db, db))+ if strip_muted(s) or track_muted(trk):+ lines.append(" lay.audioEnabled = false;")lines += [" comp.openInViewer();"," app.endUndoGroup();",@@ -4344,11 +4923,15 @@ def ae_jsx(segments, *, name: str, media: dict, width: int, height: int,def export_nle(clips, dest_dir, *, name: str, fps: int = NLE_FPS,audio: dict | None = None, probe=None, link=None,width: int = 0, height: int = 0,- overlays: list | None = None) -> dict:+ overlays: list | None = None,+ audio_tracks: list | None = None) -> dict:"""Write `<name>_project/` — one XML, one AE script, and the media beside them.Returns {"ok", "dir", "xml", "jsx", "clips", "linked", "copied",- "missing", "width", "height", "duration"}.+ "missing", "width", "height", "duration", "sound_strips"}.++ `audio_tracks` is `edit["audio_tracks"]`: each track becomes its own audio+ track in the XML and its strips their own layers in the AE script."""import shutil # noqa: PLC0415, F401segs = _nle_segments(clips, probe=probe)@@ -4376,6 +4959,9 @@ def export_nle(clips, dest_dir, *, name: str, fps: int = NLE_FPS,wanted += [str(o["path"]) for o in ovs]if audio and audio.get("path"):wanted.append(str(audio["path"]))+ trks = [t for t in (audio_tracks or []) if isinstance(t, dict)]+ for t in trks:+ wanted += [str(s["path"]) for s in track_strips(t) if str(s.get("path") or "")]for src_str in wanted:if src_str in media:continue@@ -4399,16 +4985,19 @@ def export_nle(clips, dest_dir, *, name: str, fps: int = NLE_FPS,xml_path.write_text(fcp7_xml(segs, name=name, media=media, width=width, height=height,overlays=ovs,- base=root, fps=fps, audio=a_arg), encoding="utf-8")+ base=root, fps=fps, audio=a_arg,+ audio_tracks=trks or None), encoding="utf-8")jsx_path.write_text(ae_jsx(segs, name=name, media=media, width=width, height=height,overlays=ovs,- fps=fps, audio=a_arg), encoding="utf-8")+ fps=fps, audio=a_arg, audio_tracks=trks or None), encoding="utf-8")return {"ok": True, "dir": str(root), "xml": str(xml_path),"jsx": str(jsx_path), "clips": len(segs),"linked": linked, "copied": copied, "missing": missing,"media": sorted(media.values()),+ "sound_strips": sum(1 for t in trks for s in track_strips(t)+ if str(s.get("path") or "") in media),"width": width, "height": height,"duration": round(max([s["film_end"] for s in segs] or [0.0]), 3),}diff --git a/test_audio_ab_lanes.py b/test_audio_ab_lanes.pynew file mode 100644index 0000000..3e0fff6--- /dev/null+++ b/test_audio_ab_lanes.py@@ -0,0 +1,551 @@+#!/usr/bin/env python3+"""Clip sound on two lanes (A/B) — alternation, lane-scoped overlap, the mix.++The owner, 2026-09-15: "When the app creates a timeline, the sound between+clips should already be intercalated into two different lanes. Clip 1: the+sound is in one lane. Clip 2: the sound is in another lane. If I want to blend+and dissolve from both sides, cut a little, and bring the clips together to+make it more realistic, it's easy."++Locked here:++ * absent is lane A: `clip_sound_lane`, normalise (lane 1 is no field), and a+ document that never used lane B builds a filter graph BYTE-IDENTICAL to the+ one the code built before lanes existed (golden hashes taken from dev+ 85a7098 over 42 graphs: linked, J-cut, muted, level curve, speed,+ transition, still — each with no music / under / replace, with and without+ audio-track strips);+ * a fresh timeline (`edit_from_plan`) alternates A, B, A… by film order, and+ `alternate_sound_lanes` / `sound_lane_after` are the one-click and the+ insert rule;+ * overlap is refused (warned) WITHIN a lane only;+ * the render lays lane B as its own concat and SUMS it with lane A under the+ one `asoftclip`; a real ffmpeg render of two tones proves both sounds play+ across the cut on two lanes and the old tail-trim on one;+ * the bed duck follows sound on either lane;+ * the FCP7 export writes lane B as its own audio track;+ * the browser's model agrees with the server's (node harness).++Run: python3 -m unittest test_audio_ab_lanes+"""+from __future__ import annotations++import copy+import hashlib+import os+import re+import subprocess+import sys+import tempfile+import unittest+import xml.etree.ElementTree as ET+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))+_SCRATCH = Path(tempfile.mkdtemp(prefix="phos-ablanes-"))+for _k, _d in (("LTX_STATE_DIR", "state"), ("LTX_OUTPUT_DIR", "out"),+ ("LTX_UPLOADS_DIR", "up")):+ os.environ.setdefault(_k, str(_SCRATCH / _d))+ Path(os.environ[_k]).mkdir(parents=True, exist_ok=True)+os.environ.setdefault("PHOSPHENE_ANALYTICS_DISABLED", "1")+os.environ.setdefault("PHOSPHENE_DISABLE_VERSION_CHECK", "1")++import mlx_ltx_panel as panel # noqa: E402+import storyboard_editor as se # noqa: E402++FFMPEG = str(getattr(panel, "FFMPEG", "") or "")+++def _clip(cid, fs, length, **kw):+ c = {"id": cid, "path": f"/x/{cid}.mp4", "start": 0.0, "end": float(length),+ "film_start": float(fs), "film_end": float(fs + length),+ "source": "auto", "locked": False}+ c.update(kw)+ return c+++def _doc(clips, **kw):+ d = {"version": se.EDIT_VERSION, "board_id": "b", "clips": clips, "audio": None}+ d.update(kw)+ return d+++# =============================================================================+# THE MODEL+# =============================================================================+class TheLane(unittest.TestCase):+ def test_absent_is_lane_a_and_only_the_integer_two_is_b(self):+ self.assertEqual(se.clip_sound_lane(_clip("a", 0, 2)), 1)+ self.assertEqual(se.clip_sound_lane(_clip("a", 0, 2, sound_lane=2)), 2)+ self.assertEqual(se.clip_sound_lane(_clip("a", 0, 2, sound_lane=True)), 1)+ self.assertEqual(se.clip_sound_lane(_clip("a", 0, 2, sound_lane="2")), 1)+ still = _clip("s", 0, 2, kind="still", path="/x/s.png", sound_lane=2)+ self.assertEqual(se.clip_sound_lane(still), 1)++ def test_alternate_lays_video_clips_a_b_a_in_film_order(self):+ clips = [_clip("c", 8, 2), _clip("a", 0, 3, sound_lane=2),+ _clip("s", 3, 2, kind="still", path="/x/s.png"), _clip("b", 5, 3)]+ before = copy.deepcopy(clips)+ changed = se.alternate_sound_lanes(clips)+ lanes = {c["id"]: se.clip_sound_lane(c) for c in clips}+ self.assertEqual(lanes, {"a": 1, "b": 2, "c": 1, "s": 1})+ self.assertEqual(changed, 2) # a: B→A, b: A→B+ self.assertNotIn("sound_lane", clips[1]) # A is no field+ # Nothing moved in time.+ for x, y in zip(before, clips):+ for k in ("start", "end", "film_start", "film_end"):+ self.assertEqual(x[k], y[k])+ self.assertEqual(se.alternate_sound_lanes(clips), 0)++ def test_an_arriving_clip_takes_the_lane_its_neighbour_is_not_on(self):+ clips = [_clip("a", 0, 3), _clip("b", 3, 3, sound_lane=2)]+ self.assertEqual(se.sound_lane_after(clips, 6.0), 1)+ self.assertEqual(se.sound_lane_after(clips, 3.0), 2) # after a (A)+ self.assertEqual(se.sound_lane_after(clips, 0.0), 2) # before a: not a's+ self.assertEqual(se.sound_lane_after([], 0.0), 1)++ def test_a_fresh_timeline_alternates(self):+ plan = [{"path": f"/x/{i}.mp4", "start": 0.0, "end": 2.0,+ "film_start": 2.0 * i, "film_end": 2.0 * i + 2} for i in range(5)]+ ed = se.edit_from_plan(plan, board_id="b")+ self.assertEqual([se.clip_sound_lane(c) for c in ed["clips"]], [1, 2, 1, 2, 1])+ self.assertNotIn("sound_lane", ed["clips"][0])+ self.assertEqual(ed["clips"][1]["sound_lane"], 2)+ self.assertEqual(se.blocking_errors(se.validate_edit(ed)), [])++ def test_normalise_writes_b_only(self):+ doc = se.normalise_edit(_doc([+ _clip("a", 0, 2, sound_lane=1), _clip("b", 2, 2, sound_lane=2),+ _clip("s", 4, 2, kind="still", path="/x/s.png", sound_lane=2)]))+ self.assertNotIn("sound_lane", doc["clips"][0])+ self.assertEqual(doc["clips"][1]["sound_lane"], 2)+ self.assertNotIn("sound_lane", doc["clips"][2])++ def test_the_lane_is_content(self):+ a = se.normalise_edit(_doc([_clip("a", 0, 2), _clip("b", 2, 2)]))+ b = copy.deepcopy(a)+ b["clips"][1]["sound_lane"] = 2+ self.assertNotEqual(se.edit_digest(a), se.edit_digest(b))++ def test_cuts_carry_lane_b_and_nothing_for_a(self):+ doc = se.normalise_edit(_doc([_clip("a", 0, 2), _clip("b", 2, 2, sound_lane=2)]))+ cuts = se.edit_to_cuts(doc)+ self.assertNotIn("lane", cuts[0])+ self.assertEqual(cuts[1]["lane"], 2)+++class OverlapIsPerLane(unittest.TestCase):+ def jcut(self, lane_b):+ extra = {"sound_lane": 2} if lane_b else {}+ # b's sound starts 1 s before its picture, under a.+ return _doc([_clip("a", 0, 3),+ _clip("b", 3, 3, audio={"start": 0.0, "end": 3.0, "film_start": 2.0},+ **extra)])++ def test_one_lane_warns(self):+ errs = se.validate_edit(self.jcut(False))+ codes = [e["code"] for e in errs]+ self.assertEqual(codes, ["clips_audio_overlap"])+ self.assertIn("sound lane A", errs[0]["message"])+ self.assertEqual(se.blocking_errors(errs), [])++ def test_two_lanes_are_clean(self):+ self.assertEqual(se.validate_edit(self.jcut(True)), [])++ def test_two_sounds_on_b_still_warn_and_say_b(self):+ doc = self.jcut(True)+ doc["clips"][0]["sound_lane"] = 2+ errs = se.validate_edit(doc)+ self.assertEqual([e["code"] for e in errs], ["clips_audio_overlap"])+ self.assertIn("sound lane B", errs[0]["message"])++ def test_a_bad_value_is_refused(self):+ for v in (3, 0, "2", True):+ doc = _doc([_clip("a", 0, 2, sound_lane=v)])+ self.assertIn("clip_sound_lane",+ [e["code"] for e in se.blocking_errors(se.validate_edit(doc))], v)++ def test_the_duck_follows_either_lane(self):+ # a on A 0-3, b on B from 2.0 to 5.0 → one merged window 0-5 either way.+ both = se.audible_strips(self.jcut(True))+ self.assertEqual(both, [[0.0, 5.0]])+ # A lane-B sound alone in a stretch ducks the bed there too.+ doc = _doc([_clip("a", 0, 2),+ _clip("b", 6, 2, sound_lane=2)])+ self.assertEqual(se.audible_strips(doc), [[0.0, 2.0], [6.0, 8.0]])+ doc["audio"] = {"path": "/x/m.wav", "duration": 10.0, "mix": {"duck": True}}+ curve = se.bed_gain_points(doc)+ self.assertLess(se._lerp_gain(curve, 7.0), 0.3)+ self.assertAlmostEqual(se._lerp_gain(curve, 4.0), 1.0, places=6)+++# =============================================================================+# THE RENDER GRAPH+# =============================================================================+INFO = {"w": 320, "h": 240, "duration": 5.0, "has_audio": True, "sample_rate": 48000}+++def _seg(i, **kw):+ s = {"kind": "video", "input": i, "path": f"/x/{i}.mp4", "duration": 4.0,+ "info": dict(INFO), "window": {"start": 0.5, "end": 4.5}}+ s.update(kw)+ return s+++CASES = {+ "plain": [_seg(0), _seg(1), _seg(2)],+ "jcut": [_seg(0), _seg(1, audio={"start": 0.0, "end": 4.5, "delta": -0.5}), _seg(2)],+ "muted": [_seg(0), _seg(1, mute=True), _seg(2)],+ "gain": [_seg(0, gain=[[0, 1.0], [1, 0.5]]), _seg(1)],+ "speed": [_seg(0, speed=2.0, duration=2.0),+ _seg(1, audio={"start": 0.2, "end": 4.0, "delta": 0.3})],+ "tx": [_seg(0, transition={"kind": "dissolve", "duration": 0.5}), _seg(1, tx_in=0.25),+ _seg(2)],+ "still": [_seg(0), {"kind": "still", "input": 1, "path": "/x/s.png", "duration": 2.0,+ "info": {"w": 320, "h": 240}, "window": None}, _seg(2)],+}+MUSIC = {"path": "/x/m.wav", "start": 0.0, "end": None, "delay": 0.5, "mode": "under",+ "gain": [[0.5, 0.7], [9.0, 0.7]]}+STRIPS = [{"path": "/x/l.wav", "start": 0.0, "end": 1.0, "at": 1.0, "len": 1.0, "gain": []}]++# sha1(graph + "|" + video label)[:16], from dev 85a7098 — BEFORE the lanes.+GOLDEN = {+ "gain/none/nostrips": "26328df2c6a5518c", "gain/none/strips": "1fe1bbd8f7f5e1e3",+ "gain/replace/nostrips": "bc74719a3282928f", "gain/replace/strips": "3891b6ddd8986055",+ "gain/under/nostrips": "4eae2abc183feeb6", "gain/under/strips": "2094c00763dc5e2f",+ "jcut/none/nostrips": "0d06218f449c00ff", "jcut/none/strips": "1e4f665011998733",+ "jcut/replace/nostrips": "e82fab35e281221b", "jcut/replace/strips": "b26ac1bc8cff1206",+ "jcut/under/nostrips": "2c6be62fa54ea27e", "jcut/under/strips": "9b6eac9faf3a72a2",+ "muted/none/nostrips": "bc8e331298c1dfd3", "muted/none/strips": "2501e4eca31f70e8",+ "muted/replace/nostrips": "e82fab35e281221b", "muted/replace/strips": "b26ac1bc8cff1206",+ "muted/under/nostrips": "afb8c03f1551fb6b", "muted/under/strips": "6ff5dfe2883410ff",+ "plain/none/nostrips": "fdafe1778bf98ff9", "plain/none/strips": "375ccc2d3f50bfd2",+ "plain/replace/nostrips": "e82fab35e281221b", "plain/replace/strips": "b26ac1bc8cff1206",+ "plain/under/nostrips": "0512064b984b463c", "plain/under/strips": "36c78562ff78e518",+ "speed/none/nostrips": "cf9cbb71f9ee5be5", "speed/none/strips": "96ab5cf4615dc896",+ "speed/replace/nostrips": "8fa09870321202cc", "speed/replace/strips": "c4932074109a38be",+ "speed/under/nostrips": "b930c957df4ef257", "speed/under/strips": "55c7c04bd6f64c70",+ "still/none/nostrips": "3f51d1683320c9d0", "still/none/strips": "ca87f2cc6c3e4ffa",+ "still/replace/nostrips": "e30198934f2f4611", "still/replace/strips": "2e5b4b941a4ea43f",+ "still/under/nostrips": "157947e6a66be182", "still/under/strips": "d601be1018111d02",+ "tx/none/nostrips": "cb95c34f1f53e095", "tx/none/strips": "f0185d7dd7eab553",+ "tx/replace/nostrips": "f07823f072ebf251", "tx/replace/strips": "63a102609b48d9ad",+ "tx/under/nostrips": "1f3ed50670016d46", "tx/under/strips": "0fac66de0004635f",+}+++def _graph(segs, music=None, strips=None):+ g, v = panel._sb_film_filtergraph([], 320, 240, 48000, "yuv420p",+ segments=copy.deepcopy(segs), music=music,+ sound_strips=strips, sound_base=5)+ return g, v+++class TheLegacyGraphIsByteIdentical(unittest.TestCase):+ def test_every_golden_graph(self):+ seen = 0+ for name, segs in CASES.items():+ for mname, music in (("none", None), ("under", MUSIC),+ ("replace", dict(MUSIC, mode="replace"))):+ for sname, strips in (("nostrips", None), ("strips", STRIPS)):+ g, v = _graph(segs, music, strips)+ key = f"{name}/{mname}/{sname}"+ got = hashlib.sha1((g + "|" + v).encode()).hexdigest()[:16]+ self.assertEqual(got, GOLDEN[key], key)+ seen += 1+ self.assertEqual(seen, len(GOLDEN))++ def test_lane_a_explicitly_is_the_same_graph(self):+ segs = [_seg(0), _seg(1, lane=1), _seg(2)]+ self.assertEqual(_graph(segs), _graph(CASES["plain"]))+++class TheTwoLaneGraph(unittest.TestCase):+ # b's sound J-cuts 1 s under a, on lane B.+ SEGS = [_seg(0), _seg(1, lane=2, audio={"start": 0.0, "end": 4.5, "delta": -1.0}),+ _seg(2)]++ def test_the_plan_does_not_trim_across_lanes(self):+ plan = panel._sb_split_audio_plan(copy.deepcopy(self.SEGS))+ self.assertTrue(plan["split"])+ self.assertEqual([L["idx"] for L in plan["lanes"]], [0, 2])+ self.assertEqual([L["idx"] for L in plan["lanes_b"]], [1])+ self.assertAlmostEqual(plan["lanes"][0]["len"], 4.0) # a's tail intact+ self.assertAlmostEqual(plan["lanes_b"][0]["at"], 3.0)+ self.assertAlmostEqual(plan["lanes_b"][0]["len"], 4.5)+ # The same edit on ONE lane: the incoming sound trims a's tail, as ever.+ one = [dict(s) for s in copy.deepcopy(self.SEGS)]+ one[1].pop("lane")+ p1 = panel._sb_split_audio_plan(one)+ self.assertEqual(p1["lanes_b"], [])+ self.assertAlmostEqual(p1["lanes"][0]["len"], 3.0)++ def test_lane_b_is_its_own_concat_summed_under_one_limiter(self):+ g, _ = _graph(self.SEGS)+ self.assertIn("[a0]", g)+ self.assertIn("[a1]", g)+ lane_a = re.search(r"([^;]*)concat=n=\d+:v=0:a=1\[abase\]", g).group(1)+ lane_b = re.search(r"([^;]*)concat=n=\d+:v=0:a=1\[alb\]", g).group(1)+ self.assertIn("[a0]", lane_a)+ self.assertIn("[a2]", lane_a)+ self.assertNotIn("[a1]", lane_a)+ self.assertIn("[a1]", lane_b)+ self.assertIn("[aqb0]", lane_b) # its own silences+ self.assertIn("[abase][alb]amix=inputs=2:duration=first:dropout_transition=0:"+ "normalize=0,asoftclip=type=tanh:", g)+ self.assertEqual(g.count("asoftclip"), 1)+ self.assertEqual(g.count("[aout]"), 1)++ def test_under_music_and_strips_join_the_same_sum(self):+ g, _ = _graph(self.SEGS, MUSIC, STRIPS)+ self.assertIn("[acat][bed][alb][ts0]amix=inputs=4:", g)+ self.assertEqual(g.count("asoftclip"), 1)++ def test_replace_throws_both_lanes_away(self):+ g, _ = _graph(self.SEGS, dict(MUSIC, mode="replace"))+ self.assertNotIn("[alb]", g)+ self.assertNotIn("[a1]", g)++ def test_a_linked_clip_on_b_leaves_the_plain_concat(self):+ segs = [_seg(0), _seg(1, lane=2)]+ g, _ = _graph(segs)+ self.assertNotIn("v=1:a=1", g)+ self.assertIn("[alb]", g)++ def test_the_timeline_carries_the_lane_into_the_segment(self):+ with tempfile.TemporaryDirectory() as d:+ a, b = Path(d) / "a.mp4", Path(d) / "b.mp4"+ a.write_bytes(b"x")+ b.write_bytes(b"x")+ cap = {}+ info = dict(INFO)+ real_probe, real_run = panel._sb_probe_clip, panel.run_ffmpeg_tracked+ panel._sb_probe_clip = lambda p: dict(info)+ panel.run_ffmpeg_tracked = lambda cmd, label: cap.setdefault("cmd", cmd) and ("", "")+ try:+ panel._sb_assemble_film(+ [str(a), str(b)], Path(d) / "film.mp4",+ timeline=[{"path": str(a), "start": 0.0, "end": 3.0, "film_start": 0.0},+ {"path": str(b), "start": 0.0, "end": 3.0, "film_start": 3.0,+ "lane": 2}])+ finally:+ panel._sb_probe_clip, panel.run_ffmpeg_tracked = real_probe, real_run+ graph = cap["cmd"][cap["cmd"].index("-filter_complex") + 1]+ self.assertIn("[alb]", graph)+++# =============================================================================+# A REAL RENDER, MEASURED+# =============================================================================[email protected](FFMPEG, "ffmpeg not available")+class ARealCrossfadeIsMeasured(unittest.TestCase):+ """Shot a carries a 1 kHz tone, shot b a 3 kHz tone. b's sound is pulled+ 1 s early (2.0 s) under a's last second (a ends at 3.0). On two lanes both+ tones play in 2.0–3.0; on one lane a's tail is cut at 2.0 (the old rule)."""++ @classmethod+ def setUpClass(cls):+ cls.d = Path(tempfile.mkdtemp(prefix="phos-abmix-"))+ run = lambda *a: subprocess.run([FFMPEG, "-y", "-v", "error", *a], check=True) # noqa: E731+ cls.a, cls.b = cls.d / "a.mp4", cls.d / "b.mp4"+ for path, hz in ((cls.a, 1000), (cls.b, 3000)):+ run("-f", "lavfi", "-i", "color=c=gray:s=320x240:r=24:d=4", "-f", "lavfi",+ "-i", f"sine=frequency={hz}:sample_rate=48000:duration=4", "-ac", "2",+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k",+ "-shortest", str(path))+ cls.two = cls.render(lane_b=True, name="two.mp4")+ cls.one = cls.render(lane_b=False, name="one.mp4")+ cls.src = cls.vd(cls.a, 0.5, 1.0)[1]++ @classmethod+ def render(cls, lane_b, name):+ clips = [_clip("a", 0, 3, path=str(cls.a), duration=4.0),+ _clip("b", 3, 3, path=str(cls.b), duration=4.0,+ audio={"start": 0.0, "end": 4.0, "film_start": 2.0})]+ if lane_b:+ clips[1]["sound_lane"] = 2+ real = panel._sb_film_dir+ panel._sb_film_dir = lambda board: cls.d / "film"+ try:+ return panel._sbe_render_edit({"id": "b", "title": "t", "created_at": 0},+ se.normalise_edit(_doc(clips)), out_name=name)+ finally:+ panel._sb_film_dir = real++ @classmethod+ def vd(cls, path, a, d, band=None):+ af = (band + "," if band else "") + "volumedetect"+ r = subprocess.run([FFMPEG, "-hide_banner", "-ss", str(a), "-t", str(d), "-i",+ str(path), "-af", af, "-f", "null", "-"],+ capture_output=True, text=True)+ m = re.search(r"mean_volume: ([-\d.]+) dB", r.stderr)+ x = re.search(r"max_volume: ([-\d.]+) dB", r.stderr)+ return float(m.group(1)), float(x.group(1))++ def band(self, res, a, d, hz):+ return self.vd(res["path"], a, d, f"bandpass=f={hz}:width_type=q:w=8")[1]++ def test_both_rendered(self):+ self.assertTrue(self.two["ok"], self.two.get("error"))+ self.assertTrue(self.one["ok"], self.one.get("error"))++ def test_two_lanes_play_both_sounds_across_the_cut(self):+ self.assertGreater(self.band(self.two, 2.2, 0.6, 1000), self.src - 1.5)+ self.assertGreater(self.band(self.two, 2.2, 0.6, 3000), self.src - 1.5)++ def test_one_lane_keeps_the_old_butt_join(self):+ self.assertLess(self.band(self.one, 2.2, 0.6, 1000), self.src - 20)+ self.assertGreater(self.band(self.one, 2.2, 0.6, 3000), self.src - 1.5)++ def test_outside_the_overlap_each_shot_is_itself(self):+ self.assertGreater(self.band(self.two, 0.5, 1.0, 1000), self.src - 1.5)+ self.assertLess(self.band(self.two, 0.5, 1.0, 3000), self.src - 20)+ self.assertGreater(self.band(self.two, 4.0, 1.0, 3000), self.src - 1.5)+ self.assertLess(self.band(self.two, 4.0, 1.0, 1000), self.src - 20)++ def test_the_sum_does_not_clip(self):+ self.assertLessEqual(self.vd(self.two["path"], 0, 6)[1], 0.0)+++# =============================================================================+# THE NLE EXPORT+# =============================================================================+class TheExport(unittest.TestCase):+ def xml(self, clips):+ segs = se._nle_segments(clips, probe=lambda p: {"w": 320, "h": 240,+ "duration": 5.0, "has_audio": True})+ media = {s["path"]: Path(s["path"]).name for s in segs}+ return ET.fromstring(se.fcp7_xml(segs, name="t", media=media, width=320,+ height=240, base="/tmp/p").split("\n", 2)[2])++ def test_lane_b_is_its_own_audio_track(self):+ root = self.xml([_clip("a", 0, 3), _clip("b", 3, 3, sound_lane=2), _clip("c", 6, 3)])+ tracks = root.findall("./sequence/media/audio/track")+ self.assertEqual(len(tracks), 2)+ self.assertEqual([c.findtext("name") for c in tracks[0].findall("clipitem")],+ ["a", "c"])+ self.assertEqual([c.findtext("name") for c in tracks[1].findall("clipitem")], ["b"])+ self.assertEqual(tracks[1].find("clipitem/start").text, "72")++ def test_no_lane_b_is_one_clip_track_as_before(self):+ root = self.xml([_clip("a", 0, 3), _clip("b", 3, 3)])+ self.assertEqual(len(root.findall("./sequence/media/audio/track")), 1)+++# =============================================================================+# THE CLIENT — the panel's real JavaScript, run in node+# =============================================================================+from test_audio_tracks import run_client # noqa: E402+from test_storyboard_editor_ui import NODE # noqa: E402++[email protected](NODE, "node not on PATH")+class TheClientModel(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.r = run_client(r"""+const mk = (id, fs, len, extra) => Object.assign({ id: id, path: '/x/' + id + '.mp4',+ start: 0, end: len, film_start: fs, film_end: fs + len, source: 'auto', locked: false,+ duration: 10 }, extra || {});+const layAB = (cs) => { sbeAdoptGaps(cs); sbeLayout(cs); return cs; };+let clips = layAB([mk('a', 0, 3, { sound_lane: 2 }), mk('b', 3, 3),+ { id: 's', kind: 'still', path: '/x/s.png', start: 0, end: 2, film_start: 6, film_end: 8,+ source: 'auto', locked: false }, mk('c', 8, 3)]);+const alt = sbeAlternateLanes(clips);+out.alt = alt.clips.map(c => [c.id, sbeSoundLane(c), c.sound_lane === undefined]);+out.altChanged = alt.changed;+out.altTimesKept = alt.clips.map(c => [c.film_start, c.film_end]);+out.altAgain = sbeAlternateLanes(alt.clips).ok;+out.undoable = clips[0].sound_lane === 2; // the input is not mutated+// Insert at the end: after c (A) → B. Insert at the head: before a (A) → B.+let ins = sbeInsertAt(alt.clips, { path: '/x/n.mp4', duration_s: 2, title: 'n' }, 99);+out.insEnd = sbeSoundLane(ins.added);+ins = sbeInsertAt(alt.clips, { path: '/x/h.mp4', duration_s: 2, title: 'h' }, 0);+out.insHead = sbeSoundLane(ins.added);+const dup = sbeDuplicate(alt.clips, 'b'); // b is on B → its copy goes on A+out.dup = [sbeSoundLane(sbeById(dup.clips, 'b')), sbeSoundLane(dup.added)];+const slug = sbeInsertAt(alt.clips, { kind: 'slug', duration_s: 1 }, 99);+out.slugLane = slug.added.sound_lane === undefined;+// One strip, one lane.+out.set = sbeSoundLane(sbeById(sbeSetSoundLane(alt.clips, 'a', 2).clips, 'a'));+out.setStill = sbeSetSoundLane(alt.clips, 's', 2).ok;+out.setLocked = sbeSetSoundLane(layAB([mk('z', 0, 2, { locked: true })]), 'z', 2).why;+out.setSame = sbeSetSoundLane(alt.clips, 'a', 1).ok;+// The save body writes B only.+out.clean = [sbeCleanClip(mk('p', 0, 1, { sound_lane: 1 })).sound_lane === undefined,+ sbeCleanClip(mk('q', 0, 1, { sound_lane: 2 })).sound_lane,+ sbeCleanClip({ id: 'r', kind: 'still', path: '/x/r.png', start: 0, end: 1,+ film_start: 0, film_end: 1, sound_lane: 2 }).sound_lane === undefined];+// THE PREVIEW: b's sound J-cut 1 s under a, on lane B — both play at 2.5.+const jc = layAB([mk('a', 0, 3), mk('b', 3, 3, { sound_lane: 2,+ audio: { start: 0, end: 3, film_start: 2 } })]);+jc[0].audio = { start: 0, end: 3, film_start: 0 };+out.preview = sbeStripsAt(jc, 2.5).map(w => w.id);+""")++ def test_alternation_matches_the_server(self):+ self.assertEqual(self.r["alt"], [["a", 1, True], ["b", 2, False], ["s", 1, True],+ ["c", 1, True]])+ self.assertEqual(self.r["altChanged"], 2)+ self.assertEqual(self.r["altTimesKept"], [[0, 3], [3, 6], [6, 8], [8, 11]])+ self.assertFalse(self.r["altAgain"])+ self.assertTrue(self.r["undoable"])+ server = [_clip("a", 0, 3, sound_lane=2), _clip("b", 3, 3),+ _clip("s", 6, 2, kind="still", path="/x/s.png"), _clip("c", 8, 3)]+ se.alternate_sound_lanes(server)+ self.assertEqual([[c["id"], se.clip_sound_lane(c)] for c in server],+ [[x[0], x[1]] for x in self.r["alt"]])++ def test_new_clips_keep_the_alternation(self):+ self.assertEqual(self.r["insEnd"], 2)+ self.assertEqual(self.r["insHead"], 2)+ self.assertEqual(self.r["dup"], [2, 1])+ self.assertTrue(self.r["slugLane"])++ def test_one_strip_changes_lane_and_refuses_what_it_should(self):+ self.assertEqual(self.r["set"], 2)+ self.assertFalse(self.r["setStill"])+ self.assertEqual(self.r["setLocked"], "locked")+ self.assertFalse(self.r["setSame"])++ def test_the_save_body_writes_b_only(self):+ self.assertEqual(self.r["clean"], [True, 2, True])++ def test_the_preview_plays_both_lanes_at_once(self):+ self.assertEqual(sorted(self.r["preview"]), ["a", "b"])+++class TheScreen(unittest.TestCase):+ """The markup and the words the Docs use are the ones on screen."""++ @classmethod+ def setUpClass(cls):+ cls.html = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+ cls.css = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+ cls.js = (ROOT / "webapp" / "js" / "editor.js").read_text(encoding="utf-8")+ cls.docs = (ROOT / "webapp" / "docs" / "editor.md").read_text(encoding="utf-8")++ def test_both_heads_and_the_one_click(self):+ self.assertIn("<b>Clip sound A</b>", self.html)+ self.assertIn("<b>Clip sound B</b>", self.html)+ self.assertIn('onclick="sbeAlternateSel()"', self.html)+ self.assertIn(">Alternate A/B</button>", self.html)+ self.assertIn("Alternate sound lanes", self.js)++ def test_the_box_is_two_lanes_and_the_timeline_pays_for_the_second(self):+ self.assertIn("#sbeAudioLane { height: calc(var(--sbe-alane-h, 44px) * 2); }", self.css)+ self.assertIn("#sbeAudioLane > .sbe-aclip.is-b", self.css)+ self.assertIn("sbeExtraLanesH(L)) + 'px'", self.js)++ def test_the_docs_use_the_screen_words(self):+ for words in ("Clip sound A", "Clip sound B", "Alternate A/B",+ "Alternate sound lanes", "Move sound to lane B"):+ self.assertIn(words, self.docs)+ self.assertTrue(words in self.html or words in self.js+ or words == "Move sound to lane B"+ and "Move sound to lane ' + sbeLaneName(other)" in self.js, words)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_audio_compact.py b/test_audio_compact.pynew file mode 100644index 0000000..0aa6c7e--- /dev/null+++ b/test_audio_compact.py@@ -0,0 +1,216 @@+#!/usr/bin/env python3+"""The sound lanes make themselves small — the contract, on screen and in code.++The owner, editing a 13-shot film with clip sound on two lanes and four audio+tracks: "the sound expands lower. The picture is so tiny, and it's a problem. I+cannot see anything in the image, and I can also not push it down if I want to+compact it. Think of some way that is really seamless and user-friendly to maybe+compact all audio lanes when I am not working with them and make them little+(because I want to see the image also as I'm working sometimes)."++Three things had to be true for that, and each one is checked here:++ * THE AREA SIZES ITSELF. Every lane in the sound area — clip sound A and B,+ the soundtrack, and every A3+ track — has a second height, and one decision+ function says which one is on screen. It may not collapse mid-drag, during+ playback or under an open menu, which is the difference between "seamless"+ and "jumps".+ * THE FLOOR IS NOT A CONSTANT any more. It is the sum of the lane set that is+ on screen, so with the sound small the handle really does push the timeline+ down — the arithmetic lives in test_storyboard_editor_ui's probe; what is+ checked here is that sbeFitMonitors budgets the monitors against it.+ * IT IS A CONTROL, NOT A TRICK. A ▾ on the A1 head, a key in the one+ SHORTCUTS table, and the manual's own words — a behaviour that only+ happens to you is a bug report waiting to be filed.+"""+from __future__ import annotations++import json+import re+import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function # noqa: E402++WEB = ROOT / "webapp"+++class TheSoundAreaSizesItself(unittest.TestCase):++ @classmethod+ def setUpClass(cls) -> None:+ cls.js = (WEB / "js" / "editor.js").read_text(encoding="utf-8")+ cls.css = (WEB / "style" / "panel.css").read_text(encoding="utf-8")+ cls.html = (WEB / "index.html").read_text(encoding="utf-8")+ cls.docs = (WEB / "docs" / "editor.md").read_text(encoding="utf-8")+ cls.keys = (WEB / "js" / "shortcuts.js").read_text(encoding="utf-8")++ # ---- the lane table ---------------------------------------------------+ def test_every_lane_in_the_sound_area_has_a_second_height(self):+ lanes = re.findall(+ r"\{ key: '(\w+)',\s+base:\s*(\d+), cap:\s*(\d+), share: ([\d.]+)"+ r"(, audio: true, small: (\d+))?", self.js)+ by = {l[0]: l for l in lanes}+ self.assertEqual(sorted(by), ["alane", "ov", "track", "wave"])+ # The two sound lanes, and only them: the picture and the overlay are+ # not the owner's complaint and must not shrink behind his back.+ for key, small in (("alane", "18"), ("wave", "20")):+ self.assertTrue(by[key][4], f"{key} has no small height")+ self.assertEqual(by[key][5], small)+ self.assertLess(int(small), int(by[key][1]))+ for key in ("ov", "track"):+ self.assertFalse(by[key][4], f"{key} is not part of the sound area")+ # A3, A4 … are drawn at the clip lane's height, so they follow it for+ # free — that is the whole reason four tracks cost what they cost.+ self.assertIn("lanes.alane", extract_function("sbeTracksExtraH", self.js))++ def test_the_floor_and_the_ceiling_are_the_lane_set_on_screen(self):+ self.assertIn("globalThis.SBE_TL_MIN_H = sbeTlFloor(false);", self.js)+ self.assertIn("globalThis.SBE_TL_MAX_H = sbeTlRoof(false);", self.js)+ # The monitors' budget: the floor, the ceiling and the extra lanes all+ # read the CURRENT size, which is how compacting reaches the picture.+ fit = extract_function("sbeFitMonitors", self.js)+ self.assertIn("sbeTlFloor()", fit)+ self.assertIn("sbeTlRoof()", fit)+ self.assertIn("avail - SBE_MON_MIN_H - extra", fit)+ # ...and the stacked page still bails out before any of it.+ self.assertIn("(max-width: 900px)", fit)+ self.assertIn("return;", fit[fit.index("(max-width: 900px)"):])++ def test_the_handle_can_ask_for_the_smaller_floor(self):+ for fn in ("sbeApplyTl", "sbeTlReset"):+ self.assertIn("sbeTlFloor()", extract_function(fn, self.js))+ clamp = extract_function("sbeTlClamp", self.js)+ self.assertIn("const floor = sbeTlFloor(small), roof = sbeTlRoof(small);", clamp)+ # Pull the edge up past what thin lanes can use and the sound comes+ # back — there is no other height in the box left to be asking for.+ self.assertIn("sbeAudioTouch({ open: true })", extract_function("sbeTlSet", self.js))++ # ---- when it happens --------------------------------------------------+ def test_it_never_collapses_in_the_middle_of_something(self):+ busy = extract_function("sbeAudioBusy", self.js)+ for held in ("SBE.audioDrag", "SBE.musicDrag", "SBE.tsDrag", "SBE.kfDrag",+ "SBE.tgSliding", "SBE.tlDrag", "SBE.playing", "SBE.aHover",+ "sbePopAnyOpen()", "SBE.selLane", "'@ts:'", "'@music'",+ "ED.src === 'sound'"):+ self.assertIn(held, busy, f"the lanes can collapse while {held}")+ want = extract_function("sbeAudioWant", self.js)+ self.assertIn("if (SBE.aPin === 'open') return false;", want)+ self.assertIn("if (SBE.aPin === 'small') return true;", want)+ self.assertIn("if (sbeAudioBusy()) return false;", want)+ self.assertIn("SBE_ASMALL_IDLE", want)+ # A couple of seconds: long enough that looking away is not a flicker.+ idle = int(re.search(r"const SBE_ASMALL_IDLE = (\d+);", self.js).group(1))+ self.assertGreaterEqual(idle, 1500)+ self.assertLessEqual(idle, 5000)++ def test_touching_sound_opens_it_at_once(self):+ touch = extract_function("sbeAudioTouch", self.js)+ self.assertIn("SBE.aTouch = Date.now();", touch)+ self.assertIn("if (SBE.aSmall && SBE.aPin !== 'small') sbeAudioSet(false);", touch)+ # The verbs aimed at sound say so, because none of them leaves a trace+ # in the selection the busy test reads.+ for fn in ("sbeToggleAudioLink", "sbeResyncSel", "sbeAlternateSel",+ "sbeTrackAdd", "sbeTsAddSoundPath", "edPoolSrc"):+ self.assertIn("sbeAudioTouch({ open: true })",+ extract_function(fn, self.js), fn)+ # The pointer over a lane or a head opens it, which is how anybody+ # discovers that it opens at all.+ for wire in ("alane.addEventListener('pointerenter'",+ "lane.addEventListener('pointerenter'",+ "tlanes.addEventListener('pointerenter'",+ "gutter.addEventListener('pointermove'"):+ self.assertIn(wire, self.js)+ # ...and the idle is restarted by the one function every edit and+ # every selection already ends in.+ self.assertIn("sbeAudioArm();", extract_function("sbePaint", self.js))++ def test_a_small_lane_is_a_picture_and_one_click_opens_it(self):+ for fn in ("sbeOnAudioDown", "sbeOnMusicDown", "sbeOnTsDown"):+ body = extract_function(fn, self.js)+ self.assertIn("if (sbeAudioSmall()) { sbeAudioOpenFrom(ev); return; }", body, fn)+ opener = extract_function("sbeAudioOpenFrom", self.js)+ # One gesture: the area opens AND what was clicked is selected.+ self.assertIn("sbeTsSelectOne(", opener)+ self.assertIn("sbeSelectOne(", opener)+ self.assertIn("'@music'", opener)+ self.assertIn("sbeAudioTouch({ open: true });", opener)+ # The waveform still has a height to be drawn at down there.+ self.assertIn("sbeAudioSmall() ? 8 : 14", extract_function("sbeStripH", self.js))++ def test_the_change_is_animated_and_the_drag_is_not(self):+ setter = extract_function("sbeAudioSet", self.js)+ self.assertIn("classList.add('sbe-aanim')", setter)+ self.assertIn("classList.remove('sbe-aanim')", setter)+ # The waveforms are drawn, not styled: re-issued at the height they+ # landed on, exactly as the drag handle's own correction does it.+ self.assertIn("SBE.laneAt = -1;", setter)+ self.assertIn("transition: height 180ms", self.css)+ # ...and only while the class is on the body, so dragging the timeline's+ # edge — which moves the same numbers 60 times a second — stays instant.+ block = self.css[self.css.index("body.sbe-aanim .sbe-alane"):]+ self.assertLess(block.index("transition:"), block.index("}"))++ # ---- it is this browser's preference, never the film's -----------------+ def test_the_pin_lives_beside_the_timeline_height_and_not_in_the_document(self):+ self.assertIn("localStorage.getItem('phos_sbe_audio')", self.js)+ self.assertIn("localStorage.setItem('phos_sbe_audio'", self.js)+ # The save payload is the whole of what the server is told. A window's+ # shape in there would bump the film's revision — see sbeTlPrefRead.+ save = extract_function("sbeSaveBody", self.js)+ for word in ("aPin", "aSmall", "phos_sbe_audio"):+ self.assertNotIn(word, save)+ self.assertNotIn("audio_small", self.js)++ # ---- and it is a control, not a trick ---------------------------------+ def test_the_control_is_on_the_head_of_the_area_it_acts_on(self):+ self.assertIn('id="sbeAudioSize"', self.html)+ self.assertIn('onclick="sbeAudioPinToggle()"', self.html)+ self.assertIn('aria-expanded="true"', self.html)+ # On the A1 head — the top of the sound area, next to its name.+ head = self.html[self.html.index('class="sbe-gh sbe-gh-aud">'):]+ head = head[:head.index("</div>")]+ self.assertIn("sbeAudioSize", head)+ self.assertIn("<b>Clip sound A</b>", head)+ # Its glyph and its words are painted, so they cannot say "make them+ # small" while the lanes already are.+ heads = extract_function("sbePaintHeads", self.js)+ self.assertIn("sbeAudioSize", heads)+ self.assertIn("'▸' : '▾'", heads)+ self.assertIn("aria-expanded", heads)+ self.assertIn("shortcutHint('editor.soundLanes')", heads)++ def test_the_key_is_in_the_one_table(self):+ row = self.keys[self.keys.index("id: 'editor.soundLanes'"):]+ row = row[:row.index("},")]+ self.assertIn("combos: ['shift+a']", row)+ self.assertIn("calls: 'sbeAudioPinToggle'", row)+ self.assertIn("scope: 'editor'", row)+ # The Editor's own handler answers it — test_docs_and_shortcuts drives+ # the real listener; here it is enough that the branch is there.+ self.assertIn("ev.preventDefault(); sbeAudioPinToggle(); return;", self.js)++ def test_the_manual_says_it_in_the_words_on_screen(self):+ self.assertIn("{#compact}", self.docs)+ for words in ("Sound lanes small", "Clip sound A", "[[sc:editor.soundLanes]]"):+ self.assertIn(words, self.docs)+ # The docs promise the two halves the code has to keep.+ self.assertIn("come back to full height the moment you are", self.docs)+ self.assertIn("remembered in this browser", self.docs)++ def test_the_stacked_page_keeps_its_controls(self):+ # Below the breakpoint the page is the scroller, sbeFitMonitors stands+ # down and the lanes are back on their CSS heights — so the class that+ # takes the grips away may not reach down there.+ i = self.css.index("body.sbe-aanim .sbe-alane")+ guard = self.css.rindex("@media (min-width: 901px) {", 0, i)+ self.assertLess(guard, i)+ self.assertLess(i, self.css.index(".is-asmall .sbe-grip"))+++if __name__ == "__main__":+ unittest.main()diff --git a/test_audio_tracks.py b/test_audio_tracks.pynew file mode 100644index 0000000..32e12b5--- /dev/null+++ b/test_audio_tracks.py@@ -0,0 +1,669 @@+#!/usr/bin/env python3+"""Audio tracks — A3, A4, … under the music. The server half.++The owner needed a laugh track, a slap-bass sting and a looping bed on one+film and had nowhere to put them: A1 is each shot's own sound and A2 holds ONE+soundtrack. `edit["audio_tracks"]` is a list of tracks, each a list of strips.+Locked here, against the real model, the real filtergraph builder and — when+ffmpeg is on the machine — a real render measured with volumedetect:++ * absent is none: an edit with no tracks (or an empty list) normalises and+ builds the graph byte-identically to one written before tracks existed;+ * the shape is validated, and two strips on ONE track may not overlap while+ two strips on two tracks may;+ * normalise rounds, sorts, invents ids and drops neutral fields, deciding+ nothing about where a strip is;+ * the strip curve is the envelope times the strip fader times the track+ fader, and muted strips / muted tracks / silent curves never reach the mix;+ * the render graph trims, shapes, delays and MIXES each strip under the same+ soft limiter, addressing the inputs the argv actually passes;+ * the NLE export writes each track as its own XML audio track and its strips+ as AE layers, with in/out, level keyframes and mutes as editable settings.++Run: python3 -m unittest test_audio_tracks+"""+from __future__ import annotations++import copy+import json+import os+import re+import shutil+import subprocess+import sys+import tempfile+import unittest+import xml.etree.ElementTree as ET+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))+_SCRATCH = Path(tempfile.mkdtemp(prefix="phos-tracks-"))+for _k, _d in (("LTX_STATE_DIR", "state"), ("LTX_OUTPUT_DIR", "out"),+ ("LTX_UPLOADS_DIR", "up")):+ os.environ.setdefault(_k, str(_SCRATCH / _d))+ Path(os.environ[_k]).mkdir(parents=True, exist_ok=True)+os.environ.setdefault("PHOSPHENE_ANALYTICS_DISABLED", "1")+os.environ.setdefault("PHOSPHENE_DISABLE_VERSION_CHECK", "1")++import mlx_ltx_panel as panel # noqa: E402+import storyboard_editor as se # noqa: E402+++def _clip(cid="c1", path="/x/a.mp4", start=0.0, end=6.0, fs=0.0):+ return {"id": cid, "path": path, "start": start, "end": end,+ "film_start": fs, "film_end": fs + (end - start),+ "source": "auto", "locked": False}+++def _base():+ return {"version": se.EDIT_VERSION, "board_id": "b", "clips": [_clip()],+ "audio": None}+++def _tracks():+ return [+ {"id": "t1", "name": "Laughs", "strips": [+ {"id": "s1", "path": "/x/laugh.wav", "start": 0.0, "end": 2.0,+ "film_start": 1.0, "afx": {"fade_in": 0.5}},+ {"id": "s2", "path": "/x/laugh.wav", "start": 0.0, "end": 1.0,+ "film_start": 3.0, "muted": True},+ ]},+ {"id": "t2", "gain": 0.5, "strips": [+ {"id": "s3", "path": "/x/sting.wav", "start": 0.25, "end": 1.25,+ "film_start": 2.5, "gain": 0.5},+ ]},+ ]+++class AbsentIsNone(unittest.TestCase):+ def test_no_key_and_an_empty_list_normalise_identically(self):+ a = se.normalise_edit(_base())+ b = se.normalise_edit(dict(_base(), audio_tracks=[]))+ self.assertNotIn("audio_tracks", a)+ self.assertEqual(json.dumps(a, sort_keys=True), json.dumps(b, sort_keys=True))++ def test_an_old_document_validates_and_digests_the_same(self):+ self.assertEqual(se.validate_edit(_base()), [])+ self.assertEqual(se.edit_digest(se.normalise_edit(_base())),+ se.edit_digest(se.normalise_edit(dict(_base(), audio_tracks=[]))))++ def test_the_graph_is_byte_identical_without_tracks(self):+ seg = {"kind": "video", "input": 0, "path": "/x/a.mp4", "duration": 6.0,+ "info": {"w": 320, "h": 240, "duration": 6.0, "has_audio": True,+ "sample_rate": 48000}, "window": {"start": 0.0, "end": 6.0}}+ for music in (None,+ {"path": "/x/m.wav", "start": 0.0, "end": None, "delay": 0.0,+ "mode": "under", "gain": []},+ {"path": "/x/m.wav", "start": 0.0, "end": None, "delay": 0.0,+ "mode": "replace", "gain": []}):+ with self.subTest(music=bool(music) and music["mode"]):+ g0, l0 = panel._sb_film_filtergraph([], 320, 240, 48000, "yuv420p",+ segments=[dict(seg)], music=music)+ g1, l1 = panel._sb_film_filtergraph([], 320, 240, 48000, "yuv420p",+ segments=[dict(seg)], music=music,+ sound_strips=[], sound_base=7)+ self.assertEqual((g0, l0), (g1, l1))++ def test_the_render_of_an_edit_with_no_tracks_passes_no_strips(self):+ self.assertEqual(se.track_render_strips(_base()), [])+++class Validation(unittest.TestCase):+ def codes(self, doc):+ return [e["code"] for e in se.blocking_errors(se.validate_edit(doc))]++ def test_a_good_document_is_clean(self):+ self.assertEqual(self.codes(dict(_base(), audio_tracks=_tracks())), [])++ def test_same_track_overlap_is_refused(self):+ tr = _tracks()+ tr[0]["strips"][1]["film_start"] = 2.5 # s1 runs 1.0-3.0+ self.assertIn("audio_track_strips_overlap",+ self.codes(dict(_base(), audio_tracks=tr)))++ def test_a_butt_join_is_not_an_overlap(self):+ tr = _tracks()+ tr[0]["strips"][1]["film_start"] = 3.0 - 1e-4+ self.assertEqual(self.codes(dict(_base(), audio_tracks=tr)), [])++ def test_different_tracks_may_overlap(self):+ tr = _tracks()+ tr[1]["strips"][0]["film_start"] = 1.0 # right on top of s1+ self.assertEqual(self.codes(dict(_base(), audio_tracks=tr)), [])++ def test_shape_errors_are_named(self):+ cases = {+ "audio_tracks_shape": "nope",+ "audio_track_shape": ["x"],+ "audio_track_gain_range": [{"gain": 2, "strips": []}],+ "audio_track_strips": [{"strips": {}}],+ "track_strip_path": [{"strips": [{"start": 0, "end": 1, "film_start": 0}]}],+ "track_strip_window": [{"strips": [{"path": "/a.wav", "start": 1, "end": 1,+ "film_start": 0}]}],+ "track_strip_film_start": [{"strips": [{"path": "/a.wav", "start": 0, "end": 1,+ "film_start": -1}]}],+ "track_strip_past_the_end": [{"strips": [{"path": "/a.wav", "start": 0, "end": 5,+ "film_start": 0, "duration": 2}]}],+ "track_strip_gain_range": [{"strips": [{"path": "/a.wav", "start": 0, "end": 1,+ "film_start": 0, "gain": -1}]}],+ "track_strip_muted": [{"strips": [{"path": "/a.wav", "start": 0, "end": 1,+ "film_start": 0, "muted": "yes"}]}],+ "track_strip_afx_point": [{"strips": [{"path": "/a.wav", "start": 0, "end": 1,+ "film_start": 0, "afx": {"points": [[1]]}}]}],+ }+ for code, rows in cases.items():+ with self.subTest(code=code):+ self.assertIn(code, self.codes(dict(_base(), audio_tracks=rows)))++ def test_save_refuses_an_overlap_and_writes_nothing(self):+ with tempfile.TemporaryDirectory() as d:+ se.save_edit(d, dict(_base(), audio_tracks=_tracks()))+ before = (Path(d) / "edit.json").read_text()+ tr = _tracks()+ tr[0]["strips"][1]["film_start"] = 2.0+ with self.assertRaises(se.EditError):+ se.save_edit(d, dict(_base(), audio_tracks=tr))+ self.assertEqual((Path(d) / "edit.json").read_text(), before)++ def test_a_saved_document_round_trips_through_load(self):+ with tempfile.TemporaryDirectory() as d:+ se.save_edit(d, dict(_base(), audio_tracks=_tracks()))+ back = se.load_edit(d)+ self.assertEqual([s["id"] for t in back["audio_tracks"] for s in t["strips"]],+ ["s1", "s2", "s3"])+ self.assertEqual(se.validate_edit(back), [])+++class Normalise(unittest.TestCase):+ def test_neutral_is_absent_and_ids_are_invented(self):+ doc = dict(_base(), audio_tracks=[+ {"name": " ", "muted": False, "gain": 1.0, "strips": [+ {"path": "/a.wav", "start": 0, "end": 1.0000004, "film_start": 2,+ "gain": 1, "muted": False, "locked": False, "afx": {"fade_in": 0},+ "_drag": 1},+ {"path": "/a.wav", "start": 0, "end": 1, "film_start": 0.5},+ ]}])+ t = se.normalise_edit(doc)["audio_tracks"][0]+ self.assertTrue(t["id"])+ for k in ("name", "muted", "gain"):+ self.assertNotIn(k, t)+ self.assertEqual([s["film_start"] for s in t["strips"]], [0.5, 2.0])+ s = t["strips"][1]+ self.assertEqual(s["end"], 1.0)+ for k in ("gain", "muted", "locked", "afx", "_drag"):+ self.assertNotIn(k, s)+ self.assertNotEqual(t["strips"][0]["id"], s["id"])++ def test_an_empty_track_is_kept(self):+ t = se.normalise_edit(dict(_base(), audio_tracks=[{"id": "t9"}]))["audio_tracks"]+ self.assertEqual(t, [{"id": "t9", "strips": []}])++ def test_duplicate_ids_are_made_unique(self):+ doc = dict(_base(), audio_tracks=[+ {"id": "t", "strips": [{"id": "s", "path": "/a.wav", "start": 0, "end": 1,+ "film_start": 0}]},+ {"id": "t", "strips": [{"id": "s", "path": "/a.wav", "start": 0, "end": 1,+ "film_start": 0}]}])+ tr = se.normalise_edit(doc)["audio_tracks"]+ self.assertEqual(len({t["id"] for t in tr}), 2)+ self.assertEqual(len({t["strips"][0]["id"] for t in tr}), 2)+++class TheCurve(unittest.TestCase):+ def test_faders_multiply_the_envelope(self):+ tr = _tracks()+ self.assertEqual(se.track_strip_gain_points(tr[0], tr[0]["strips"][0]),+ [[0.0, 0.0], [0.5, 1.0], [2.0, 1.0]])+ # 0.5 on the strip, 0.5 on the track, no envelope: a flat quarter.+ self.assertEqual(se.track_strip_gain_points(tr[1], tr[1]["strips"][0]),+ [[0.0, 0.25], [1.0, 0.25]])+ self.assertEqual(se.track_strip_gain_at(tr[1], tr[1]["strips"][0], 0.5), 0.25)++ def test_unity_is_no_curve(self):+ t = {"strips": [{"path": "/a.wav", "start": 0, "end": 1, "film_start": 0}]}+ self.assertEqual(se.track_strip_gain_points(t, t["strips"][0]), [])++ def test_the_render_list_skips_what_cannot_be_heard(self):+ tr = _tracks()+ rows = se.track_render_strips(dict(_base(), audio_tracks=tr))+ self.assertEqual([r["id"] for r in rows], ["s1", "s3"]) # s2 muted+ self.assertEqual(rows[1]["start"], 0.25)+ self.assertEqual(rows[1]["at"], 2.5)+ tr[1]["muted"] = True+ self.assertEqual([r["id"] for r in se.track_render_strips(dict(_base(), audio_tracks=tr))],+ ["s1"])+ tr[0]["strips"][0]["gain"] = 0+ self.assertEqual(se.track_render_strips(dict(_base(), audio_tracks=tr)), [])+++class TheRenderGraph(unittest.TestCase):+ SEG = {"kind": "video", "input": 0, "path": "/x/a.mp4", "duration": 6.0,+ "info": {"w": 320, "h": 240, "duration": 6.0, "has_audio": True,+ "sample_rate": 48000}, "window": {"start": 0.0, "end": 6.0}}++ def graph(self, music=None, strips=None, base=3):+ g, _ = panel._sb_film_filtergraph(+ [], 320, 240, 48000, "yuv420p", segments=[dict(self.SEG)], music=music,+ sound_strips=strips, sound_base=base)+ return g++ def rows(self):+ return se.track_render_strips(dict(_base(), audio_tracks=_tracks()))++ def test_each_strip_is_trimmed_shaped_delayed_and_padded(self):+ g = self.graph(strips=self.rows())+ self.assertIn("[3:a]atrim=start=0.000000:end=2.000000,asetpts=PTS-STARTPTS,"+ "volume=volume='", g)+ self.assertIn("adelay=delays=48000S:all=1,apad,atrim=0:6.000000", g) # 1.0 s+ self.assertIn("[4:a]atrim=start=0.250000:end=1.250000", g)+ self.assertIn("adelay=delays=120000S:all=1", g) # 2.5 s+ self.assertIn("[acat_unused]" if False else "[abase][ts0][ts1]amix=inputs=3:"+ "duration=first:dropout_transition=0:normalize=0,asoftclip=", g)+ self.assertIn("[vcat][abase]", g)+ self.assertEqual(g.count("[aout]"), 1)++ def test_under_mix_takes_the_strips_into_one_sum(self):+ music = {"path": "/x/m.wav", "start": 0.0, "end": None, "delay": 0.0,+ "mode": "under", "gain": []}+ g = self.graph(music=music, strips=self.rows())+ self.assertIn("[acat][bed][ts0][ts1]amix=inputs=4:", g)+ self.assertEqual(g.count("asoftclip"), 1)+ self.assertNotIn("[abase]", g)++ def test_a_strip_that_starts_after_the_film_contributes_nothing(self):+ rows = [{"path": "/x/l.wav", "start": 0.0, "end": 1.0, "at": 9.0, "len": 1.0,+ "gain": []}]+ g = self.graph(strips=rows)+ self.assertNotIn("[ts0]", g)+ self.assertEqual(g, self.graph())++ def test_the_argv_passes_the_inputs_the_graph_addresses(self):+ with tempfile.TemporaryDirectory() as d:+ clip, snd = Path(d) / "a.mp4", Path(d) / "s.wav"+ clip.write_bytes(b"x")+ snd.write_bytes(b"x")+ cap = {}+ info = {"w": 320, "h": 240, "duration": 6.0, "has_audio": True,+ "sample_rate": 48000}+ real_probe, real_run = panel._sb_probe_clip, panel.run_ffmpeg_tracked+ panel._sb_probe_clip = lambda p: dict(info)+ panel.run_ffmpeg_tracked = lambda cmd, label: cap.setdefault("cmd", cmd) and ("", "")+ try:+ panel._sb_assemble_film(+ [str(clip)], Path(d) / "film.mp4",+ timeline=[{"path": str(clip), "start": 0.0, "end": 6.0, "film_start": 0.0}],+ sound_strips=[{"path": str(snd), "start": 0.0, "end": 1.0, "at": 1.0,+ "len": 1.0, "gain": []}])+ finally:+ panel._sb_probe_clip, panel.run_ffmpeg_tracked = real_probe, real_run+ cmd = cap["cmd"]+ ins = [cmd[i + 1] for i, c in enumerate(cmd) if c == "-i"]+ self.assertEqual(ins, [str(clip), str(snd)])+ self.assertEqual(cmd[cmd.index(str(snd)) - 2], "-vn")+ graph = cmd[cmd.index("-filter_complex") + 1]+ self.assertIn("[1:a]atrim=start=0.000000:end=1.000000", graph)++ def test_render_refuses_a_missing_sound_file(self):+ doc = dict(_base(), audio_tracks=_tracks())+ with tempfile.TemporaryDirectory() as d:+ clip = Path(d) / "a.mp4"+ clip.write_bytes(b"x")+ doc["clips"][0]["path"] = str(clip)+ res = panel._sbe_render_edit({"id": "b", "title": "t", "created_at": 0}, doc)+ self.assertFalse(res["ok"])+ self.assertEqual(res.get("status"), 400)+ self.assertIn("no sound file at /x/laugh.wav (audio track A3)", res["error"])+++class TheNleExport(unittest.TestCase):+ def export(self, tracks):+ d = Path(tempfile.mkdtemp(prefix="phos-nle-"))+ clip, laugh, sting = d / "a.mp4", d / "laugh.wav", d / "sting.wav"+ for p in (clip, laugh, sting):+ p.write_bytes(b"x")+ tr = copy.deepcopy(tracks)+ for t in tr:+ for s in t["strips"]:+ s["path"] = str(d / Path(s["path"]).name)+ doc = dict(_base())+ doc["clips"][0]["path"] = str(clip)+ probe = lambda p: {"w": 320, "h": 240, "duration": 6.0, "has_audio": True} # noqa: E731+ res = se.export_nle(doc["clips"], d / "out", name="tracks", probe=probe,+ audio_tracks=tr)+ return res, Path(res["xml"]).read_text(), Path(res["jsx"]).read_text()++ def test_each_track_is_its_own_xml_audio_track(self):+ res, xml, _ = self.export(_tracks())+ self.assertEqual(res["sound_strips"], 3)+ seq = ET.fromstring(xml.split("\n", 2)[2]).find("sequence")+ atracks = seq.find("media").find("audio").findall("track")+ self.assertEqual(len(atracks), 3) # A1 clip sound + A3 + A4+ a3 = atracks[1].findall("clipitem")+ self.assertEqual(len(a3), 2)+ first = a3[0]+ self.assertEqual((first.findtext("start"), first.findtext("end"),+ first.findtext("in"), first.findtext("out")),+ ("24", "72", "0", "48"))+ self.assertEqual(first.findtext("enabled"), "TRUE")+ self.assertEqual(a3[1].findtext("enabled"), "FALSE") # muted, not dropped+ kf = first.find("filter/effect/parameter").findall("keyframe")+ self.assertEqual([(k.findtext("when"), k.findtext("value")) for k in kf],+ [("0", "0.0000"), ("12", "1.0000"), ("48", "1.0000")])+ a4 = atracks[2].findall("clipitem")[0]+ self.assertEqual((a4.findtext("in"), a4.findtext("out")), ("6", "30"))+ self.assertIn("0.2500", ET.tostring(a4, encoding="unicode"))+ # One file, described once: the two laugh strips share an id.+ ids = [c.find("file").get("id") for c in a3]+ self.assertEqual(ids[0], ids[1])+ self.assertEqual(xml.count(f'<file id="{ids[0]}">'), 1)++ def test_the_ae_script_gives_every_strip_a_named_layer(self):+ _, _, jsx = self.export(_tracks())+ self.assertIn("lay.name = \"Laughs · laugh\";", jsx)+ self.assertIn("lay.startTime = 2.250000;", jsx) # 2.5 - 0.25+ self.assertIn("lay.inPoint = 2.500000;", jsx)+ self.assertIn("lay.audioEnabled = false;", jsx)+ self.assertIn("au.setValueAtTime(2.500000, [-12.041, -12.041]);", jsx)++ def test_no_tracks_exports_what_it_always_did(self):+ d = Path(tempfile.mkdtemp(prefix="phos-nle0-"))+ clip = d / "a.mp4"+ clip.write_bytes(b"x")+ doc = dict(_base())+ doc["clips"][0]["path"] = str(clip)+ probe = lambda p: {"w": 320, "h": 240, "duration": 6.0, "has_audio": True} # noqa: E731+ a = se.export_nle(doc["clips"], d / "a", name="n", probe=probe)+ b = se.export_nle(doc["clips"], d / "b", name="n", probe=probe, audio_tracks=[])+ norm = lambda p: Path(p).read_text().replace(str(d / "a"), "").replace(str(d / "b"), "") # noqa: E731+ self.assertEqual(norm(a["xml"]), norm(b["xml"]))+ self.assertEqual(norm(a["jsx"]), norm(b["jsx"]))+++FFMPEG = str(getattr(panel, "FFMPEG", "") or "")++[email protected](FFMPEG and Path(FFMPEG).exists(), "ffmpeg not available")+class ARealRenderIsMeasured(unittest.TestCase):+ """Two tones on two tracks over a silent picture, measured per window.++ A 1 kHz "laugh" on A3 from 1.0 s (2 s long, 0.5 s fade in) and a 3 kHz+ "sting" on A4 from 2.5 s at half gain (1 s long). A bandpass around each+ tone tells the two apart inside the one mixed track.+ """++ @classmethod+ def setUpClass(cls):+ cls.d = Path(tempfile.mkdtemp(prefix="phos-mix-"))+ run = lambda *a: subprocess.run([FFMPEG, "-y", "-v", "error", *a], check=True) # noqa: E731+ clip, laugh, sting = cls.d / "clip.mp4", cls.d / "laugh.wav", cls.d / "sting.wav"+ run("-f", "lavfi", "-i", "color=c=gray:s=320x240:r=24:d=6", "-f", "lavfi", "-i",+ "anullsrc=r=48000:cl=stereo", "-t", "6", "-c:v", "libx264", "-pix_fmt", "yuv420p",+ "-c:a", "aac", "-shortest", str(clip))+ run("-f", "lavfi", "-i", "sine=frequency=1000:sample_rate=48000:duration=2", "-ac", "2",+ str(laugh))+ run("-f", "lavfi", "-i", "sine=frequency=3000:sample_rate=48000:duration=1", "-ac", "2",+ str(sting))+ doc = {"version": se.EDIT_VERSION, "board_id": "b",+ "clips": [_clip(path=str(clip))],+ "audio_tracks": [+ {"id": "t1", "strips": [{"id": "s1", "path": str(laugh), "start": 0,+ "end": 2, "film_start": 1.0,+ "afx": {"fade_in": 0.5}}]},+ {"id": "t2", "strips": [{"id": "s2", "path": str(sting), "start": 0,+ "end": 1, "film_start": 2.5, "gain": 0.5}]}]}+ real = panel._sb_film_dir+ panel._sb_film_dir = lambda board: cls.d / "film"+ try:+ cls.res = panel._sbe_render_edit({"id": "b", "title": "t", "created_at": 0},+ se.normalise_edit(doc), out_name="mix.mp4")+ finally:+ panel._sb_film_dir = real+ cls.src_max = cls.vd(laugh, 0, 2)[1]++ @classmethod+ def vd(cls, path, a, d, band=None):+ af = (band + "," if band else "") + "volumedetect"+ r = subprocess.run([FFMPEG, "-hide_banner", "-ss", str(a), "-t", str(d), "-i",+ str(path), "-af", af, "-f", "null", "-"],+ capture_output=True, text=True)+ m = re.search(r"mean_volume: ([-\d.]+) dB", r.stderr)+ x = re.search(r"max_volume: ([-\d.]+) dB", r.stderr)+ return float(m.group(1)), float(x.group(1))++ def win(self, a, d, hz):+ return self.vd(self.res["path"], a, d, f"bandpass=f={hz}:width_type=q:w=8")[1]++ def test_it_rendered_both_strips(self):+ self.assertTrue(self.res["ok"], self.res.get("error"))+ self.assertEqual(self.res["sound_strips"], 2)++ def test_silence_before_and_after(self):+ self.assertLess(self.vd(self.res["path"], 0, 0.9)[1], -80)+ self.assertLess(self.vd(self.res["path"], 3.6, 2.3)[1], -80)++ def test_the_laugh_plays_at_its_own_level_after_its_fade(self):+ self.assertAlmostEqual(self.win(1.6, 0.8, 1000), self.src_max, delta=0.5)++ def test_the_fade_in_rises(self):+ q1, q2 = self.win(1.0, 0.25, 1000), self.win(1.25, 0.25, 1000)+ self.assertLess(q1, q2 - 4.0)+ self.assertLess(q2, self.src_max)++ def test_the_sting_is_six_db_down_and_overlaps_the_laugh(self):+ self.assertAlmostEqual(self.win(3.1, 0.8, 3000), self.src_max - 6.02, delta=0.6)+ self.assertGreater(self.win(2.55, 0.4, 1000), self.src_max - 1.0)+ self.assertGreater(self.win(2.55, 0.4, 3000), self.src_max - 7.0)++ def test_the_laugh_stops_where_its_strip_does(self):+ self.assertLess(self.win(3.1, 0.8, 1000), self.src_max - 25)+++# =============================================================================+# THE CLIENT — the panel's real JavaScript, run in node+# =============================================================================+from test_storyboard_editor_ui import (FUNCTIONS, NODE, SHIM, # noqa: E402+ extract_function, panel_source)++TS_FUNCTIONS = (+ "sbeTrackLabel", "sbeUnitGain", "sbeTrackGain", "sbeTsGain", "sbeTsWindow",+ "sbeTsGainPoints", "sbeTsGainAt", "sbeTsCopy", "sbeTsTrackById", "sbeTsFind",+ "sbeTsSort", "sbeTsFits", "sbeTsNearest", "sbeTsNextFree", "sbeTsNewTrack",+ "sbeTsRemoveTrack", "sbeTsSetTrack", "sbeTsPlace", "sbeTsMove", "sbeTsMoveGroup",+ "sbeTsTrim", "sbeTsSplit", "sbeTsCopyTitle", "sbeTsDuplicate", "sbeTsDelete",+ "sbeTsSetStrip", "sbeTsSetFade", "sbeTsPointsWrite", "sbeTsAddKeyframe",+ "sbeTsMoveKeyframe", "sbeTsDeleteKeyframe", "sbeTsAt", "sbeTsSnaps",+ "sbeTsFromClip", "sbeTsFromBed", "sbeTsClean", "sbeTsSelIds", "sbeTsSelectOne",+ "sbeTsSelectToggle", "sbeTsMutateEach", "sbeTsMutate", "sbeSoundLaneSel",+ "sbeCbarDupRow", "sbeTsSplitWhy", "sbeCbarTsModel", "sbeTsDuplicateSel",+ "sbeTsDeleteSel", "sbeSelNormalise", "sbeSelCount", "sbeNiceName",+)+++def run_client(body: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ src = panel_source()+ consts = "\n".join(m + ";" for m in re.findall(+ r"^const (?:SBE_MIX_\w+|SBE_TRACK_STRIP_MIN|SBE_TADD_H) = [^;]+", src, re.MULTILINE))+ names = list(dict.fromkeys(FUNCTIONS + TS_FUNCTIONS))+ script = (SHIM + consts + "\n"+ + "function sbeKeyHint() { return ''; }\n"+ + "function sbeBlurControl() {}\n"+ + "const SBE_TS_SPLIT_TITLE = 'split';\n"+ + "\n".join(extract_function(n, src) for n in names)+ + "\nconst out = {};\n" + body+ + "\nprocess.stdout.write(JSON.stringify(out));\n")+ with tempfile.TemporaryDirectory() as d:+ f = Path(d) / "harness.js"+ f.write_text(script, encoding="utf-8")+ r = subprocess.run([NODE, str(f)], capture_output=True, text=True, timeout=60)+ if r.returncode != 0:+ raise AssertionError("node harness failed:\n" + r.stderr[-3000:])+ return json.loads(r.stdout)+++TABLE = [+ ({"strips": []}, {"path": "/a.wav", "start": 0, "end": 2, "film_start": 1}),+ ({"gain": 0.5}, {"path": "/a.wav", "start": 0, "end": 2, "film_start": 1, "gain": 0.4}),+ ({}, {"path": "/a.wav", "start": 0.5, "end": 3, "film_start": 0,+ "afx": {"fade_in": 0.3, "fade_out": 0.7}}),+ ({"gain": 0.8}, {"path": "/a.wav", "start": 0, "end": 4, "film_start": 2,+ "afx": {"fade_out": 1, "points": [[1.0, 0.5], [2.5, 0.9]]}}),+ ({}, {"path": "/a.wav", "start": 0, "end": 1, "film_start": 0,+ "afx": {"fade_in": 0.8, "fade_out": 0.8}}),+]++[email protected](NODE, "node not on PATH")+class TheClientModel(unittest.TestCase):+ def test_the_browser_and_the_server_draw_the_same_strip_curve(self):+ out = run_client("out.rows = " + json.dumps(TABLE) + ".map(([t, s]) => ["+ "sbeTsGainPoints(t, s), sbeTsGainAt(t, s, 0.6)]);")+ for (t, s), (curve, at) in zip(TABLE, out["rows"]):+ want = se.track_strip_gain_points(t, s)+ self.assertEqual(len(curve), len(want), (t, s))+ for (a, b), (c, d) in zip(curve, want):+ self.assertAlmostEqual(a, c, places=5)+ self.assertAlmostEqual(b, d, places=5)+ self.assertAlmostEqual(at, se.track_strip_gain_at(t, s, 0.6), places=5)++ def test_every_edit_keeps_a_track_legal_by_the_servers_rule(self):+ out = run_client(r"""+const tr = [{ id: 't1', strips: [+ { id: 'a', path: '/l.wav', start: 0, end: 2, film_start: 1, duration: 5 },+ { id: 'b', path: '/l.wav', start: 1, end: 2, film_start: 4, duration: 5 }] },+ { id: 't2', strips: [] }];+out.moveOnto = sbeTsMove(tr, 'b', 't1', 2.2).tracks; // lands butted, not on top+out.moveAcross = sbeTsMove(tr, 'b', 't2', 1.5).tracks; // other track: exactly there+out.trimR = sbeTsTrim(tr, 'a', 'trimR', 9).tracks; // stops at b+out.trimL = sbeTsTrim(tr, 'b', 'trimL', 0).tracks; // stops at a, keeps its out+out.dup = sbeTsDuplicate(tr, 'a'); // after itself: 3..5 overlaps b+out.split = sbeTsSplit([{ id: 't', strips: [{ id: 's', path: '/l.wav', start: 1, end: 3,+ film_start: 10, afx: { fade_in: 0.2, fade_out: 0.4, points: [[0.5, 0.5], [1.5, 1]] } }] }],+ 's', 11, 'n2').tracks;+out.ripple = sbeTsDelete(tr, 'a', true).tracks;+out.lift = sbeTsDelete(tr, 'a', false).tracks;+out.group = sbeTsMoveGroup(tr, ['a', 'b'], -5);+out.place = sbeTsPlace(tr, '', { path: '/x.wav', start: 0, end: 1, film_start: 0 }, 1.5);+out.placeNew = sbeTsPlace([], 'new', { path: '/x.wav', start: 0, end: 1 }, 3);+out.untouched = tr;+""")+ def legal(tracks):+ doc = dict(_base(), audio_tracks=tracks)+ return [e["code"] for e in se.blocking_errors(se.validate_edit(doc))]++ for key in ("moveOnto", "moveAcross", "trimR", "trimL", "split", "ripple", "lift"):+ with self.subTest(key=key):+ self.assertEqual(legal(out[key]), [])+ self.assertEqual(legal(out["dup"]["tracks"]), [])+ t1 = {s["id"]: s for s in out["moveOnto"][0]["strips"]}+ self.assertEqual(t1["b"]["film_start"], 3.0)+ self.assertEqual(out["moveAcross"][1]["strips"][0]["film_start"], 1.5)+ self.assertEqual([s["end"] for s in out["trimR"][0]["strips"]], [3, 2])+ b = {s["id"]: s for s in out["trimL"][0]["strips"]}["b"]+ # The head comes back one second — as far as the file has, and exactly+ # to where the strip before it ends — and the out-point stays put.+ self.assertEqual((b["film_start"], b["start"], b["end"]), (3.0, 0, 2))+ self.assertEqual(out["dup"]["added"]["film_start"], 5.0)+ self.assertEqual(out["dup"]["added"]["title"], "l.wav (copy)")+ halves = out["split"][0]["strips"]+ self.assertEqual([(h["start"], h["end"], h["film_start"]) for h in halves],+ [(1, 2, 10), (2, 3, 11)])+ self.assertEqual(halves[0]["afx"], {"fade_in": 0.2, "points": [[0.5, 0.5], [1, 0.75]]})+ self.assertEqual(halves[1]["afx"], {"fade_out": 0.4, "points": [[0, 0.75], [0.5, 1]]})+ self.assertEqual(out["ripple"][0]["strips"][0]["film_start"], 2.0)+ self.assertEqual(out["lift"][0]["strips"][0]["film_start"], 4)+ self.assertEqual(out["group"]["moved"], -1) # clamped at second 0+ self.assertEqual(out["place"]["track"], "t2") # t1 has no room at 1.5+ self.assertEqual(len(out["placeNew"]["tracks"]), 1)+ self.assertEqual(out["untouched"][0]["strips"][1]["film_start"], 4) # pure++ def test_duplicate_works_on_every_kind_of_sound_and_undoes(self):+ out = run_client(r"""+function sbeSetMute() {}+SBE.tracks = []; SBE.undo = []; SBE.redo = [];+SBE.clips = [clip({ id: 'c1', path: '/o/c1.mp4', start: 1, end: 4, film_start: 0, film_end: 3,+ duration: 10, afx: { fade_out: 0.5 } }),+ clip({ id: 'c2', path: '/o/c2.mp4', start: 0, end: 2, film_start: 3, film_end: 4,+ speed: 2, duration: 10 })];+SBE.audio = { path: '/o/bed.wav', offset: 0, duration: 8, mix: { bed_gain: 0.5 } };+// A2: the bed, onto a new track right after its own end.+SBE.sel = '@music'; SBE.selSet = [];+out.musicRow = sbeCbarDupRow(0, false, null, 'no');+out.music = sbeTsDuplicateSel();+out.afterMusic = JSON.parse(JSON.stringify(SBE.tracks));+// A1: the clip's SOUND (its window, its envelope), not the shot.+SBE.sel = 'c1'; SBE.selSet = ['c1']; SBE.selLane = 'c1';+out.laneRow = sbeCbarDupRow(1, false, SBE.clips[0], 'no');+out.lane = sbeTsDuplicateSel();+out.afterLane = JSON.parse(JSON.stringify(SBE.tracks));+out.clipsAfter = SBE.clips.length;+// A retimed clip's sound is refused, and says why.+SBE.sel = 'c2'; SBE.selSet = ['c2']; SBE.selLane = 'c2';+out.fastRow = sbeCbarDupRow(1, false, SBE.clips[1], 'no');+// The shot is still the shot when the PICTURE was clicked.+SBE.selLane = '';+out.shotRow = sbeCbarDupRow(1, false, SBE.clips[1], 'no');+// A track strip: after itself on its own track, and the bar says so.+const first = SBE.tracks[0].strips.find(s => s.path === '/o/bed.wav').id;+sbeTsSelectOne(first);+out.tsModel = sbeCbarTsModel(sbeTsSelIds()).rows.map(r => [r.id, r.why]);+out.ts = sbeTsDuplicateSel();+out.afterTs = JSON.parse(JSON.stringify(SBE.tracks));+out.undoDepth = SBE.undo.length;+sbeUndo(); sbeUndo(); sbeUndo();+out.afterUndo = SBE.tracks;+out.body0 = sbeSaveBody({ id: 'b', edit: { audio_tracks: [{ id: 'old', strips: [] }] }, clips: [], tracks: [] }).edit;+out.body1 = sbeSaveBody({ id: 'b', edit: {}, clips: [], tracks: [{ id: 't', strips: [{ id: 's', path: '/a.wav', start: 0, end: 1, film_start: 0, _drag: 1 }] }] }).edit;+""")+ self.assertEqual(out["musicRow"]["why"], "")+ self.assertTrue(out["music"])+ s = out["afterMusic"][0]["strips"][0]+ self.assertEqual((s["path"], s["start"], s["end"], s["film_start"], s["gain"]),+ ("/o/bed.wav", 0, 8, 8, 0.5))+ self.assertEqual(out["laneRow"]["why"], "")+ self.assertIn("sound onto an audio track", out["laneRow"]["title"])+ a1 = [x for t in out["afterLane"] for x in t["strips"] if x["path"] == "/o/c1.mp4"][0]+ self.assertEqual((a1["start"], a1["end"], a1["film_start"], a1["afx"]),+ (1, 4, 3, {"fade_out": 0.5}))+ self.assertEqual(out["clipsAfter"], 2)+ self.assertIn("1x", out["fastRow"]["why"])+ self.assertIn("same shot", out["shotRow"]["title"])+ rows = dict(out["tsModel"])+ self.assertEqual(rows["sbeCbDup"], "")+ self.assertIn("no picture", rows["sbeCbLink"])+ bed_track = [t for t in out["afterTs"] if any(x["path"] == "/o/bed.wav" for x in t["strips"])][0]+ # The bed copy was duplicated right after itself on its own track; the+ # A1 copy found room on that same track at 3 s, before it.+ self.assertEqual([x["film_start"] for x in bed_track["strips"]+ if x["path"] == "/o/bed.wav"], [8, 16])+ self.assertEqual(len(out["afterTs"]), 1)+ self.assertEqual(out["undoDepth"], 3)+ self.assertEqual(out["afterUndo"], [])+ self.assertNotIn("audio_tracks", out["body0"])+ self.assertEqual(out["body1"]["audio_tracks"][0]["strips"][0],+ {"id": "s", "path": "/a.wav", "start": 0, "end": 1, "film_start": 0})+ doc = dict(_base(), audio_tracks=out["afterTs"])+ self.assertEqual(se.blocking_errors(se.validate_edit(doc)), [])++ def test_the_preview_plays_what_the_render_mixes(self):+ tr = _tracks()+ out = run_client("out.at = [0.5, 1.2, 2.7, 3.4].map(t => sbeTsAt("+ + json.dumps(tr) + ", t));")+ rows = se.track_render_strips(dict(_base(), audio_tracks=tr))+ for t, voices in zip((0.5, 1.2, 2.7, 3.4), out["at"]):+ want = [r for r in rows if r["at"] <= t < r["at"] + r["len"]]+ self.assertEqual(sorted(v["id"] for v in voices),+ sorted("ts:" + r["id"] for r in want), t)+ for v in voices:+ r = [x for x in want if "ts:" + x["id"] == v["id"]][0]+ self.assertAlmostEqual(v["at"], r["start"] + (t - r["at"]), places=5)+ track = [x for x in tr if any(s["id"] == r["id"] for s in x["strips"])][0]+ strip = [s for s in track["strips"] if s["id"] == r["id"]][0]+ self.assertAlmostEqual(v["vol"], se.track_strip_gain_at(track, strip, t - r["at"]),+ places=5)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_control_discoverability.py b/test_control_discoverability.pyindex 1dd0d79..714036d 100644--- a/test_control_discoverability.py+++ b/test_control_discoverability.py@@ -259,9 +259,10 @@ class TestSourceDerivedCanvasRidesTheEngineGrid(unittest.TestCase):def test_make_job_shares_the_same_helper(self):"""One rule, one function — or the day the grid changes, two of thethree lanes learn about it."""- # one def + five call sites: make_job, Control, Colorize, Upscale ×2,- # and the H3 form's "LTX ×2" export note (same rule, same helper).- self.assertEqual(PANEL_SRC.count("ltx_floor_canvas("), 6)+ # one def + six call sites: make_job, Control, Colorize, Upscale &+ # Face Fix (the worker and the one-click admission check), and the H3+ # form's after-the-draft export note (same rule, same helper).+ self.assertEqual(PANEL_SRC.count("ltx_floor_canvas("), 7)class TestTheDocumentation(unittest.TestCase):diff --git a/test_face_fix.py b/test_face_fix.pynew file mode 100644index 0000000..1dfded8--- /dev/null+++ b/test_face_fix.py@@ -0,0 +1,438 @@+#!/usr/bin/env python3+"""Upscale & Face Fix — the renamed Upscale ×2 lane as a one-click clip action.++Owner, 2026-09-17: "the upscaler, this thing we ship that fixes the faces, has+the wrong name. It should be called something like 'Upscale and Face Fix', and+it should be optional and also something you can do to an existing clip."++Gated here:+ 1 one recipe (keep_shot 1.0, start=source, 1 refine step) for every door,+ and the queue label actually reaches the job (`preset_label`)+ 2 /queue/facefix queues it for a clip with the clip's own prompt + seed,+ refuses what the worker would refuse late, and dedupes a double click+ 3 an Editor order is remembered and offered against THAT clip only while+ it still plays the source; the relink can pick the file by `to`+ 4 the lane's own "Faithful" pill is unchanged (3 refine steps)+ 5 the UI: player split button, card chip, history button, Editor clip bar,+ after-the-draft checkbox (off, not persisted), renamed labels + docs+ 6 internal ids stay: mode=upscale, h3_upscale=ltx_x2, the form keys++No renders, no GPU: make_job and the queue are exercised directly.+"""+from __future__ import annotations++import json+import os+import re+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+STATE = Path(tempfile.mkdtemp(prefix="phos-facefix-"))+os.environ["LTX_STATE_DIR"] = str(STATE)+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+os.environ.setdefault("LTX_PORT", "8317")+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402+from panel.routes import POST_ROUTES # noqa: E402++SRC = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+QJS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+EJS = (ROOT / "webapp" / "js" / "engines.js").read_text(encoding="utf-8")+EDJS = (ROOT / "webapp" / "js" / "editor.js").read_text(encoding="utf-8")+DOCS = ROOT / "webapp" / "docs"+++class _Env(unittest.TestCase):+ """A clip with a sidecar, the adapter 'installed', a probe that answers."""++ def setUp(self):+ self.dir = Path(tempfile.mkdtemp(prefix="ff-", dir=STATE))+ self.clip = self.dir / "gym_draft.mp4"+ self.clip.write_bytes(b"\0" * 64)+ Path(str(self.clip) + ".json").write_text(json.dumps({"params": {+ "prompt": "A woman lifts a dumbbell", "seed": "-1",+ "seed_used": 52190, "label": "gym", "mode": "t2v"}}), encoding="utf-8")+ self.adapter = self.dir / "adapter.safetensors"+ self.adapter.write_bytes(b"x")+ self._saved = (P.CURATED_LORAS["upscale_x2"].get("local_path"),+ P._probe_video_dims, P.persist_queue, P.tier_max_dim,+ P._probe_video_frames)+ P.CURATED_LORAS["upscale_x2"]["local_path"] = str(self.adapter)+ P._probe_video_dims = lambda path: (640, 384)+ P._probe_video_frames = lambda path: 240+ P.tier_max_dim = lambda kind: 1536+ P.persist_queue = lambda: None+ with P.QUEUE_COND:+ self._queue_before = list(P.STATE["queue"])++ def tearDown(self):+ (P.CURATED_LORAS["upscale_x2"]["local_path"], P._probe_video_dims,+ P.persist_queue, P.tier_max_dim, P._probe_video_frames) = self._saved+ with P.QUEUE_COND:+ P.STATE["queue"] = self._queue_before+ P.STATE["current"] = None++ def queued(self):+ with P.QUEUE_COND:+ return [j for j in P.STATE["queue"] if j not in self._queue_before]+++# ---------------------------------------------------------------- 1+class TestRecipe(unittest.TestCase):+ def test_recipe_is_the_verified_face_safe_one(self):+ self.assertEqual(P.FACE_FIX_RECIPE, {"keep_shot": "1.0",+ "upscale_start": "source",+ "upscale_steps": "1"})+ self.assertEqual(P.FACE_FIX_NAME, "Upscale & Face Fix")++ def test_form_goes_through_make_job_intact(self):+ form = P.face_fix_form("/x/clip.mp4", prompt="p", seed=7, label="clip")+ j = P.make_job({k: [v] for k, v in form.items()})+ p = j["params"]+ self.assertEqual(p["mode"], "upscale")+ self.assertEqual(p["upscale_source_path"], "/x/clip.mp4")+ self.assertEqual(p["keep_shot"], "1.0")+ self.assertEqual(p["upscale_start"], "source")+ self.assertEqual(p["upscale_steps"], "1")+ self.assertEqual(p["prompt"], "p")+ self.assertEqual(str(p["seed"]), "7")+ # the old chain passed `label`, which make_job never reads+ self.assertEqual(p["label"], "clip · Upscale & Face Fix")++ def test_chain_uses_the_same_recipe_and_label(self):+ seen = {}+ old_mj, old_pq = P.make_job, P.persist_queue++ def fake(form):+ seen.update(form)+ return {"id": "ffchain", "params": {}}+ P.make_job, P.persist_queue = fake, (lambda: None)+ try:+ P._chain_upscale_after_h3({"id": "d1"}, {"prompt": "hi", "seed": "-1",+ "seed_used": 9, "label": "gym",+ "keep_shot": "0.4"},+ Path("/tmp/gym.mp4"))+ with P.QUEUE_COND:+ job = next(j for j in P.STATE["queue"] if j.get("id") == "ffchain")+ finally:+ P.make_job, P.persist_queue = old_mj, old_pq+ with P.QUEUE_COND:+ P.STATE["queue"] = [j for j in P.STATE["queue"] if j.get("id") != "ffchain"]+ self.assertEqual(seen["upscale_steps"], "1")+ self.assertEqual(seen["upscale_start"], "source")+ # a leftover Re-imagine pill on the form does not leak into the fix+ self.assertEqual(seen["keep_shot"], "1.0")+ self.assertEqual(seen["preset_label"], "gym · Upscale & Face Fix")+ self.assertEqual(job["params"]["source"], "chain")+ self.assertTrue(job["params"]["face_fix"])++ def test_worker_step_mapping_is_unchanged(self):+ # Faithful (keep_shot 1.0, no explicit steps) still resolves to 3.+ self.assertIn('refine_steps = 3 if keep >= 0.95 else 2', SRC)+ self.assertIn('if p.get("upscale_steps") and start_from == "source":', SRC)+ self.assertIn('"display_name": FACE_FIX_NAME', SRC)+++# ---------------------------------------------------------------- 2+class TestQueueFaceFix(_Env):+ def test_queues_with_the_clips_own_prompt_and_seed(self):+ r = P.queue_face_fix(str(self.clip))+ self.assertTrue(r["ok"], r)+ jobs = self.queued()+ self.assertEqual(len(jobs), 1)+ p = jobs[0]["params"]+ self.assertEqual(p["prompt"], "A woman lifts a dumbbell")+ self.assertEqual(str(p["seed"]), "52190")+ self.assertEqual(p["label"], "gym · Upscale & Face Fix")+ self.assertEqual(p["upscale_steps"], "1")+ self.assertTrue(p["face_fix"])+ self.assertNotIn("face_fix_targets", p)+ # the whole clip, not make_job's 121-frame default: 240 frames asks+ # for the grid above (241, which make_job does not floor) and the+ # lane delivers all 240+ self.assertEqual(p["frames"], 241)+ self.assertEqual(P.upscale_frame_plan(240, p["frames"]), (240, 241))++ def test_a_one_shot_take_uses_the_whole_takes_prompt(self):+ Path(str(self.clip) + ".json").write_text(json.dumps({+ "prompt": "the whole take", "label": "take", "take": {"seconds": 20},+ "params": {"prompt": "part 4 only", "label": "part 4 of 4", "seed_used": 3}}),+ encoding="utf-8")+ P.queue_face_fix(str(self.clip))+ p = self.queued()[0]["params"]+ self.assertEqual(p["prompt"], "the whole take")+ self.assertEqual(p["label"], "take · Upscale & Face Fix")++ def test_double_click_is_one_job(self):+ a = P.queue_face_fix(str(self.clip))+ b = P.queue_face_fix(str(self.clip))+ self.assertEqual(a["id"], b["id"])+ self.assertTrue(b.get("duplicate"))+ self.assertEqual(len(self.queued()), 1)++ def test_click_while_it_renders_is_not_a_second_job(self):+ a = P.queue_face_fix(str(self.clip))+ with P.QUEUE_COND:+ job = next(j for j in P.STATE["queue"] if j["id"] == a["id"])+ P.STATE["queue"].remove(job)+ P.STATE["current"] = job+ b = P.queue_face_fix(str(self.clip))+ self.assertEqual(b["id"], a["id"])+ self.assertTrue(b["running"])+ self.assertEqual(self.queued(), [])++ def test_refusals_come_before_the_queue(self):+ self.assertFalse(P.queue_face_fix(str(self.dir / "gone.mp4"))["ok"])+ still = self.dir / "still.png"+ still.write_bytes(b"x")+ self.assertIn("video", P.queue_face_fix(str(still))["error"])+ self.assertFalse(P.queue_face_fix(str(self.clip), board_id="../etc",+ clip_id="c1")["ok"])+ (STATE / "storyboard.json").write_text("{}", encoding="utf-8")+ try:+ for bad in ("..", ".", "a.b"):+ self.assertFalse(P.queue_face_fix(str(self.clip), board_id=bad,+ clip_id="c1")["ok"], bad)+ self.assertFalse((STATE / "face_fix.json").exists())+ finally:+ (STATE / "storyboard.json").unlink()+ self.assertFalse(P.queue_face_fix(str(self.clip), board_id="nosuchfilm",+ clip_id="c1")["ok"])+ P._probe_video_dims = lambda path: (1280, 768)+ r = P.queue_face_fix(str(self.clip))+ self.assertEqual(r.get("code"), "hardware_tier")+ P._probe_video_dims = lambda path: (640, 384)+ P.CURATED_LORAS["upscale_x2"]["local_path"] = str(self.dir / "missing")+ r = P.queue_face_fix(str(self.clip))+ self.assertEqual(r.get("code"), "pack_missing")+ self.assertEqual(self.queued(), [])++ def test_route_is_registered(self):+ self.assertIn("/queue/facefix", POST_ROUTES)++ def test_route_answers_json(self):+ class H:+ def __init__(s, body):+ s.body, s.out = body, None++ def _read_form_body(s):+ from urllib.parse import parse_qs+ return s.body, parse_qs(s.body)++ def _json(s, obj, code=200):+ s.out = (code, obj)+ from urllib.parse import urlencode+ h = H(urlencode({"path": str(self.clip)}))+ POST_ROUTES["/queue/facefix"](h, "/queue/facefix", {}, "")+ self.assertEqual(h.out[0], 200)+ self.assertTrue(h.out[1]["ok"])+ h = H(urlencode({"path": str(self.dir / "nope.mp4")}))+ POST_ROUTES["/queue/facefix"](h, "/queue/facefix", {}, "")+ self.assertEqual(h.out[0], 400)+++# ---------------------------------------------------------------- 3+class TestEditorOffer(_Env):+ def setUp(self):+ super().setUp()+ self.bid = "fffilm_" + self._testMethodName[-24:]+ bdir = P._sbe_board_dir(self.bid)+ bdir.mkdir(parents=True, exist_ok=True)+ (bdir / "storyboard.json").write_text(json.dumps({"id": self.bid, "shots": []}),+ encoding="utf-8")++ def test_order_is_remembered_and_offered_once_it_lands(self):+ r = P.queue_face_fix(str(self.clip), board_id=self.bid, clip_id="c7")+ self.assertTrue(r["ok"], r)+ p = self.queued()[0]["params"]+ self.assertEqual(p["face_fix_targets"], [[self.bid, "c7"]])+ edit = {"clips": [{"id": "c7", "path": str(self.clip), "title": "gym",+ "in": 0.5, "out": 2.0}]}+ board = {"id": self.bid, "shots": []}+ self.assertEqual(P._sbe_relinks(board, edit), []) # not rendered yet+ fixed = self.dir / "gym_draft_x2_1.mp4"+ fixed.write_bytes(b"x")+ P._face_fix_note(self.bid, "c7", job=r["id"], to=str(fixed),+ **{"from": str(self.clip)})+ # a late registration for the same job does not erase the result+ P._face_fix_note(self.bid, "c7", job=r["id"], to="", **{"from": str(self.clip)})+ rows = P._sbe_relinks(board, edit)+ self.assertEqual(len(rows), 1)+ self.assertTrue(rows[0]["face_fix"] and rows[0]["retake"])+ self.assertEqual(rows[0]["to"], str(fixed))+ # swapped: no more offer+ edit["clips"][0]["path"] = str(fixed)+ self.assertEqual(P._sbe_relinks(board, edit), [])+ # a clip re-pointed at some other file gets no offer either+ edit["clips"][0]["path"] = str(self.dir / "other.mp4")+ self.assertEqual(P._sbe_relinks(board, edit), [])++ def test_one_waiting_job_answers_every_clip_that_asked(self):+ a = P.queue_face_fix(str(self.clip))+ b = P.queue_face_fix(str(self.clip), board_id=self.bid, clip_id="c9")+ c = P.queue_face_fix(str(self.clip), board_id=self.bid, clip_id="c10")+ self.assertEqual({a["id"], b["id"], c["id"]}, {a["id"]})+ p = self.queued()[0]["params"]+ self.assertEqual(p["face_fix_targets"], [[self.bid, "c9"], [self.bid, "c10"]])+ recs = P._face_fix_records(self.bid)+ self.assertEqual((recs["c9"]["job"], recs["c10"]["job"]), (a["id"], a["id"]))++ def test_a_click_after_the_render_landed_gets_the_result(self):+ a = P.queue_face_fix(str(self.clip))+ fixed = self.dir / "landed_x2.mp4"+ fixed.write_bytes(b"x")+ with P.QUEUE_COND:+ job = next(j for j in P.STATE["queue"] if j["id"] == a["id"])+ P.STATE["queue"].remove(job)+ P.STATE["current"] = job+ job["params"]["face_fix_result"] = {"to": str(fixed), "complete": True}+ P.queue_face_fix(str(self.clip), board_id=self.bid, clip_id="c4")+ rec = P._face_fix_records(self.bid)["c4"]+ self.assertEqual((rec["to"], rec["complete"]), (str(fixed), True))++ def test_a_short_fix_is_not_offered_as_a_swap(self):+ fixed = self.dir / "short_x2.mp4"+ fixed.write_bytes(b"x")+ P._face_fix_note(self.bid, "c3", job="j1", to=str(fixed), complete=False,+ **{"from": str(self.clip)})+ edit = {"clips": [{"id": "c3", "path": str(self.clip)}]}+ self.assertEqual(P._sbe_relinks({"id": self.bid, "shots": []}, edit), [])++ def test_worker_and_relink_wiring(self):+ blk = SRC[SRC.index(' if mode == "upscale":'):SRC.index(' if mode == "ingredients":')]+ self.assertIn('p.get("face_fix_targets")', blk)+ self.assertIn("delivered == src_frames", blk)+ # the targets are read under the same lock registration appends under+ i = blk.index('p["face_fix_result"] = _ff_result')+ self.assertIn("with QUEUE_COND:", blk[i - 80:i])+ chain = SRC[SRC.index("def _chain_upscale_after_h3"):SRC.index("def run_h3_job_inner")]+ self.assertIn("frames=_probe_video_frames(str(native_path))", chain)+ rq = (ROOT / "panel" / "routes_queue.py").read_text(encoding="utf-8")+ self.assertIn('new_job["params"].pop("face_fix_result", None)', rq)+ self.assertIn("_face_fix_note(", blk)+ self.assertIn('_face_fix_offers(str(board.get("id")', SRC)+ rel = SRC[SRC.index('if sub == "relink":'):]+ rel = rel[:rel.index('if sub == "cancel":')]+ self.assertIn('want_to = f("to", "")', rel)+ # the swap rewrites the path only: in/out points are the clip's own+ self.assertIn('c["path"] = to', rel)+ self.assertNotIn('c["in"]', rel)+++# ---------------------------------------------------------------- 5+class TestUI(unittest.TestCase):+ def test_player_split_button(self):+ i = HTML.index('id="faceFixWrap"')+ blk = HTML[i:i + 2200]+ self.assertIn('onclick="faceFixActive()"', blk)+ self.assertIn('<span class="po-act-label">Upscale & Face Fix</span>', blk)+ self.assertIn('id="useAsUpscaleBtn"', blk) # the settings half+ self.assertIn('onclick="useAsUpscaleSource()"', blk)+ self.assertNotIn(">LTX Upscale<", HTML)+ self.assertIn("getElementById('faceFixWrap')", QJS)++ def test_card_and_history_buttons_post_to_the_route(self):+ self.assertIn("fetch('/queue/facefix'", QJS)+ self.assertIn("card-action-facefix", QJS)+ self.assertIn("faceFixClip(${escapeHtml(JSON.stringify(o.path))})", QJS)+ self.assertIn("facefix-btn", QJS)+ self.assertRegex(QJS, r"faceFixClip, faceFixActive")++ def test_remix_lane_names_and_presets(self):+ self.assertIn('data-remix="upscale"', HTML)+ self.assertIn('>Upscale & Face Fix<span class="mc-sub sub">', HTML)+ grp = HTML[HTML.index('id="upscalePresetGroup"'):]+ grp = grp[:grp.index('id="keep_shot"')]+ pills = re.findall(r'<button[^>]*data-keep="([^"]+)"([^>]*)>', grp)+ self.assertEqual(len(pills), 4)+ self.assertIn('data-steps="1"', pills[0][1]) # Face Fix first+ self.assertIn('class="pill-btn active"', grp.split("<button")[1])+ for keep, rest in pills[1:]:+ self.assertNotIn("data-steps", rest) # server mapping+ self.assertIn('id="upscale_start" value="source"', HTML)+ self.assertIn('id="upscale_steps" value="1"', HTML)+ fn = QJS[QJS.index("function setUpscalePreset"):]+ fn = fn[:fn.index("\n}\n")]+ self.assertIn("upscale_start", fn)+ self.assertIn("upscale_steps", fn)++ def test_load_params_restores_the_exact_recipe(self):+ lp = QJS[QJS.index(" else if (p.mode === 'upscale') {"):]+ lp = lp[:lp.index(" else if (p.mode === 'extend')")]+ self.assertIn("(b.dataset.start || '') === start && (b.dataset.steps || '') === steps", lp)+ self.assertIn("set('keep_shot', keep); set('upscale_start', start); set('upscale_steps', steps);", lp)+ self.assertIn("p.source_frames || p.frames", lp)+ self.assertIn("1 + 8 * Math.ceil((fr - 1) / 8)", lp)+ self.assertNotIn("getElementById('duration')", lp)+ self.assertIn("Number(b.dataset.keep) === keepN", lp)+ self.assertNotIn("toFixed", lp)+ self.assertIn("(p.seed_used != null) ? p.seed_used : p.seed", lp)++ def test_after_draft_is_an_optional_checkbox_off_by_default(self):+ self.assertNotIn('data-h3-upscale="ltx_x2"', HTML)+ row = HTML[HTML.index('id="h3FaceFixAfterRow"'):]+ row = row[:row.index("</label>")]+ self.assertIn('type="checkbox" id="h3FaceFixAfter"', row)+ tag = row.split('id="h3FaceFixAfter"')[1].split(">")[0]+ self.assertNotRegex(tag, r'(^|\s)checked(\s|=|$)')+ self.assertIn("Also run <b>Upscale & Face Fix</b> after the draft", row)+ self.assertIn('id="h3_upscale" value="fit_720p"', HTML)+ self.assertEqual(P.H3_UPSCALE_DEFAULT, "fit_720p")+ self.assertIn("ltx_x2", P.H3_UPSCALE_MODES) # stored value kept+ # never saved as the preference, never restored on reload+ self.assertIn("if (!fix) { try { localStorage.setItem('phos_h3_upscale', v)", EJS)+ self.assertIn("savedUp !== 'ltx_x2'", EJS)+ self.assertIn("setH3FaceFixAfter", EJS)++ def test_editor_clip_bar_and_offer(self):+ self.assertIn('id="sbeCbFaceFix" onclick="sbeFaceFixSel()"', HTML)+ self.assertIn("<b>Face Fix ×2</b>", HTML)+ self.assertIn("menuLabel: 'Upscale & Face Fix'", EDJS)+ self.assertIn('<g id="ic-facefix">', HTML)+ self.assertEqual(EDJS.count("id: 'sbeCbFaceFix'"), 2) # picture + sound models+ fn = EDJS[EDJS.index("async function sbeFaceFixSel()"):]+ fn = fn[:fn.index("\n}\n")]+ self.assertIn("sbeSave(true)", fn)+ self.assertIn("if (SBE.conflict)", fn)+ self.assertIn("fd.set('to', to)", EDJS)+ self.assertIn("board: film, clip: c.id", EDJS)+ self.assertIn("Swap it in", EDJS)+ self.assertIn("sbeRetakeUse, sbeFaceFixSel,", EDJS)+ # finishing a fix never adopts the arrangement over unsaved edits+ tick = EDJS[EDJS.index("async function sbeTick()"):]+ tick = tick[:tick.index("if (SBE.awaitingClip")]+ self.assertIn("sbeRefreshOffers()", tick)+ self.assertNotIn("sbeLoad(", tick[tick.index("SBE.fixHandled"):])+ self.assertIn("face_fix_targets", tick)+ # handled only after a refresh that worked+ self.assertLess(tick.index("await sbeRefreshOffers()"), tick.index("SBE.fixHandled[j.id] = 1"))+ sw = EDJS[EDJS.index("async function sbeFaceFixSwap("):]+ sw = sw[:sw.index("\n}\n")]+ # a local, undoable edit: no server rewrite, no adoption+ self.assertNotIn("sbeAdopt", sw)+ self.assertNotIn("/storyboard/edit/relink", sw)+ self.assertIn("SBE.undo.push(before)", sw)+ self.assertIn("SBE.dirty = true", sw)+ self.assertIn("String(c.path) !== String(row.path)", sw)+ self.assertIn("r.face_fix ? 'sbeFaceFixSwap(' : 'sbeRetakeUse('", EDJS)+ self.assertNotIn("fixPending", EDJS)++ def test_docs_use_the_new_name(self):+ allmd = "\n".join(f.read_text(encoding="utf-8") for f in DOCS.glob("*.md"))+ # the old name survives once, so a search for it still lands here+ self.assertEqual(allmd.count("LTX Upscale"), 1)+ self.assertIn("Earlier versions called this **LTX Upscale**", allmd)+ self.assertNotIn("Upscale ×2 pass", allmd)+ self.assertIn("## Upscale & Face Fix {#upscale-face-fix}", allmd)+ self.assertIn("#docs/remix/upscale-face-fix", allmd)+ self.assertIn("**Face Fix ×2** (Upscale & Face Fix)", (DOCS / "editor.md").read_text(encoding="utf-8"))+++if __name__ == "__main__":+ unittest.main()diff --git a/test_music_engine.py b/test_music_engine.pynew file mode 100644index 0000000..31da52f--- /dev/null+++ b/test_music_engine.py@@ -0,0 +1,620 @@+"""YuE2 integration contracts. CPU only, fake packs, no model inference."""+from __future__ import annotations++import hashlib+import http.client+import io+import json+import os+from pathlib import Path+import signal+import subprocess+import sys+import tempfile+import time+from types import SimpleNamespace+from urllib.parse import urlencode++import pytest++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="music-test-state-"))+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+import mlx_ltx_panel as P+from scripts.pinokio import music_fetch as F+from scripts.extract_panel_js import extract_function+++def pack(tmp_path, monkeypatch):+ models = tmp_path / "models"+ engine = tmp_path / "engine"+ engine.mkdir()+ (engine / "pyproject.toml").write_text("[project]\nname='fixture'\n")+ (engine / ".venv/bin").mkdir(parents=True)+ (engine / ".venv/pyvenv.cfg").write_text("fixture\n")+ (engine / ".venv/bin/python").symlink_to(sys.executable)+ for part, names, manifest in (("generator", F.GENERATOR_FILES, "conversion.json"),+ ("vae", ("model.safetensors", "config.json", "LICENSE", "THIRD_PARTY_NOTICES.md", "licenses/notice.txt"), "weights_manifest.json")):+ recs = {}+ for name in names:+ target = models / part / name+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_bytes(("fixture: " + name).encode())+ recs[name] = {"bytes": target.stat().st_size, "sha256": F.digest(target)}+ if part == "vae":+ monkeypatch.setattr(F, "VAE_SHA256", recs["model.safetensors"]["sha256"])+ monkeypatch.setattr(F, "VAE_BYTES", recs["model.safetensors"]["bytes"])+ (models / part / manifest).write_text(json.dumps({"files": recs}))+ (models / "pack_source.json").write_text(json.dumps({"sources": F.SOURCES,+ "files": {"generator/config.json": {"bytes": (models / "generator/config.json").stat().st_size,+ "sha256": F.digest(models / "generator/config.json")}}}))+ monkeypatch.setattr(P, "MUSIC_ROOT", engine)+ monkeypatch.setattr(P, "MUSIC_MODELS", models)+ monkeypatch.setattr(P, "SYSTEM_RAM_GB", 24.0)+ monkeypatch.setattr(P, "OUTPUT", tmp_path / "outputs")+ P.OUTPUT.mkdir()+ monkeypatch.setattr(P, "UPLOADS", tmp_path / "uploads")+ monkeypatch.setattr(P, "MUSIC_GPU_DIR_LOCK", tmp_path / "gpu-dir")+ monkeypatch.setattr(P, "MUSIC_GPU_FILE_LOCK", tmp_path / "gpu-file")+ monkeypatch.setattr(P, "_PROC_GUARDS", {"music": (tmp_path / "music_running.json", "yue2_run.py")})+ monkeypatch.setitem(P.STATE, "queue", [])+ monkeypatch.setitem(P.STATE, "history", [])+ monkeypatch.setitem(P.STATE, "current", None)+ monkeypatch.setitem(P.STATE, "music_pgid", None)+ monkeypatch.setitem(P.STATE, "pid", None)+ monkeypatch.setattr(P, "persist_queue", lambda: None)+ return models, engine++[email protected]("ram,capable", [(16, False), (24, True), (64, True)])+def test_status_vocabulary_and_capability(pack, monkeypatch, ram, capable):+ monkeypatch.setattr(P, "SYSTEM_RAM_GB", ram)+ status = P.music_status()+ assert {"capable", "available", "installed", "reason", "repairable", "missing", "root", "min_ram_gb"} <= status.keys()+ assert status["capable"] is capable+ assert status["available"] is status["installed"] is True+ assert status["reason"] == "ok" and status["missing"] == []+ assert status["eta_measured"] is False+ assert status["estimates"]["final"]["240"]["eta_sec"] == round((P.MUSIC_FIXED_SEC + 240 * 0.93) * P._hw_speed_factor("ltx"))+ assert P.music_estimate("draft", 60)["eta_sec"] < P.music_estimate("draft", 120)["eta_sec"] < P.music_estimate("final", 120)["eta_sec"]+++def test_install_repair_missing_matrix(pack, monkeypatch):+ models, engine = pack+ (engine / ".venv/bin/python").unlink()+ s = P.music_status()+ assert s["reason"] == "missing_venv" and s["repairable"] and s["venv_broken"]+ (engine / ".venv/bin/python").symlink_to(sys.executable)+ (engine / "pyproject.toml").unlink()+ assert P.music_status()["reason"] == "missing_runner"+ (models / "generator/ar-8bit.safetensors").unlink()+ assert P.music_status()["reason"] == "missing_weights"+ monkeypatch.setattr(P, "MUSIC_ROOT", engine / "absent")+ assert P.music_status()["reason"] == "not_installed"+++def http_server(pack):+ # Exercise BaseHTTPRequestHandler's real parsing + route dispatch without+ # reserving a port or starting the panel worker (which could launch jobs).+ class Connection:+ def __init__(self, data):+ self.data = data+ self.sent = bytearray()++ def makefile(self, *args):+ return io.BytesIO(self.data)++ def sendall(self, data):+ self.sent.extend(data)++ def request(method, path, data=None, headers=None):+ body = data.encode() if isinstance(data, str) else (data or b"")+ hdr = {"Host": "127.0.0.1:8411", "Content-Length": str(len(body)), **(headers or {})}+ raw = f"{method} {path} HTTP/1.0\r\n" + "".join(f"{k}: {v}\r\n" for k, v in hdr.items()) + "\r\n"+ conn = Connection(raw.encode() + body)+ P.Handler(conn, ("127.0.0.1", 12345), SimpleNamespace(server_port=8411))+ result = http.client.HTTPResponse(Connection(bytes(conn.sent)))+ result.begin()+ status, hdr, body = result.status, dict(result.getheaders()), result.read()+ return status, hdr, body+ return request+++def test_real_form_urlencoded_queue_allowlist(http_server):+ values = {"mode": "music", "engine": "music", "music_lyrics": "[Verse]\nWords\n\n[Chorus]\nMore",+ "music_style": "English piano pop", "music_mode": "melody", "music_instrumental": "off",+ "music_max_seconds": "165", "music_seed": "42", "music_quality": "draft"}+ for instrumental in ("off", "on"):+ values["music_instrumental"] = instrumental+ code, _, body = http_server("POST", "/queue/add", urlencode(values), {"Content-Type": "application/x-www-form-urlencoded"})+ assert code == 200, body+ p = P.STATE["queue"][-1]["params"]+ for key in values.keys() - {"engine", "mode"}:+ assert key in p, key+ assert p["music_instrumental"] is (instrumental == "on")+ assert p["music_lyrics"] == ("" if instrumental == "on" else values["music_lyrics"])+ assert p["music_style"] == values["music_style"]+ assert p["music_mode"] == "melody" and p["music_quality"] == "draft"+ assert p["music_seed"] == 42 and p["music_max_seconds"] == 165+++def test_status_bootstrap_and_own_progress(http_server):+ job = P.make_job({"mode": "music", "music_style": "piano"})+ job["progress"] = P.music_progress("[music] synth 4/8")+ P.STATE["current"] = job+ code, _, body = http_server("GET", "/status")+ payload = json.loads(body)+ assert code == 200 and payload["music"]["available"]+ assert payload["current"]["progress"] == job["progress"]+ code, _, body = http_server("GET", "/")+ assert code == 200 and b'id="musicComposePane" hidden' in body+ boot = json.loads(body.decode().split("const BOOT = ", 1)[1].split(";</script>", 1)[0])+ assert boot["music"]["available"] and boot["music"]["min_ram_gb"] == 24+++def test_music_does_not_reprice_video_history(pack, monkeypatch):+ monkeypatch.setitem(P.STATE, "history", [+ {"status": "done", "elapsed_sec": 2, "params": {"engine": "music", "mode": "music"}},+ {"status": "done", "elapsed_sec": 600, "params": {"engine": "ltx", "mode": "t2v"}},+ ])+ assert P._avg_elapsed("video") == 600+++def test_storage_removal_is_guarded(http_server):+ row = next(r for r in P.storage_rows() if r["key"] == "music")+ assert row["bytes"] > 0 and row["removable"]+ P.STATE["queue"] = [P.make_job({"mode": "music", "music_style": "piano"})]+ code, _, _ = http_server("POST", "/models/remove", urlencode({"repo_key": "music"}), {"Content-Type": "application/x-www-form-urlencoded"})+ assert code == 409 and P.MUSIC_MODELS.exists()+ P.STATE["queue"] = []+ code, _, body = http_server("POST", "/models/remove", urlencode({"repo_key": "music"}), {"Content-Type": "application/x-www-form-urlencoded"})+ assert code == 200, body+ assert not P.MUSIC_MODELS.exists() and not P.music_status()["available"]++[email protected]("quality,steps", [("draft", "8"), ("final", "32")])[email protected]("length,clamped", [(1, "8"), (240, "240"), (999, "360")])+def test_argv_contract(pack, quality, steps, length, clamped):+ job = P.make_job({"mode": "music", "music_instrumental": "on", "music_lyrics": "not sent",+ "music_style": "warm piano", "music_quality": quality, "music_max_seconds": str(length),+ "music_mode": "off", "music_seed": "41"})+ out = P.OUTPUT / "song.wav"+ argv = P.music_argv(job, P.music_paths(), out)+ val = lambda flag: argv[argv.index(flag) + 1]+ assert "--instrumental" in argv and val("--lyrics") == ""+ assert val("--mode") == "off" and val("--steps") == steps+ assert val("--max-seconds") == clamped and val("--seed") == "41"+ assert val("--precision") == "8bit" and "--duration" not in argv+ assert val("--sidecar") == str(out) + ".json"+ extra = json.loads(val("--extra-json"))+ assert extra["job_id"] == job["id"] and extra["engine"] == "music"+ assert extra["engine_pin"] == (ROOT / "scripts/music/engine_pin.txt").read_text().strip()+ assert extra["pack_sources"] == F.SOURCES+++def test_progress_protocol():+ prev = None+ for line, pct, label in (("[music] stage loading", 2, "Loading YuE2"),+ ("[music] stage planning", 5, "Writing score"),+ ("[music] plan 37", 5, "37 tokens"),+ ("[music] song 50/100", 37.5, "Writing song"),+ ("[music] synth 4/8", 75, "Synthesizing music"),+ ("[music] decode 1/2", 94, "Decoding audio"),+ ("[music] done 48.25 /tmp/track.wav", 100, "Song ready")):+ prev = P.music_progress(line, prev)+ assert prev["pct"] == pct and label in prev["phase_label"]+ assert P.music_progress("arbitrary stdout") is None+ assert P.music_progress("[music] synth 1/0") is None+ assert P.music_progress("[music] error memory guard")['phase_label'] == 'memory guard'+ assert P.music_progress("[music] stage stopping", prev)["pct"] == 100++[email protected]("ext,mime", [("wav", "audio/wav"), ("mp4", "video/mp4"), ("png", "image/png")])+def test_file_mime_and_range(http_server, ext, mime):+ p = P.OUTPUT / f"sample.{ext}"+ p.write_bytes(b"0123456789")+ query = "/file?" + urlencode({"path": str(p)})+ code, hdr, body = http_server("GET", query)+ assert (code, hdr["Content-Type"], body) == (200, mime, b"0123456789")+ code, hdr, body = http_server("GET", query, headers={"Range": "bytes=2-5"})+ assert (code, hdr["Content-Type"], body) == (206, mime, b"2345")+ assert hdr["Content-Range"] == "bytes 2-5/10"+++def test_wav_outputs_sidecar_and_trash(http_server, monkeypatch, tmp_path):+ p = P.OUTPUT / "music_song.wav"+ p.write_bytes(b"fixture")+ sidecar = Path(str(p) + ".json")+ meta = {"engine": "music", "model": "YuE2-3B", "audio_seconds": 123.4, "wall_seconds": 98,+ "style": "warm piano", "lyrics": "[Verse]\nHello", "score_abc": "X:1\nK:C\nCDEF",+ "ended_naturally": True, "seed": 17}+ sidecar.write_text(json.dumps(meta))+ os.utime(p, (time.time() - 5, time.time() - 5))+ row = next(o for o in P.list_outputs() if o["path"] == str(p))+ assert row["kind"] == "audio" and row["clip_sec"] == 123.4 and row["elapsed_sec"] == 98+ assert row["url"].startswith("/file?")+ code, _, body = http_server("GET", "/sidecar?" + urlencode({"path": str(p)}))+ assert code == 200 and json.loads(body) == meta+ # Redirect Trash to this fixture; never touch the actual Trash or outputs.+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path / "home"))+ code, _, body = http_server("POST", "/output/delete", urlencode({"path": str(p)}), {"Content-Type": "application/x-www-form-urlencoded"})+ assert code == 200, body+ assert not p.exists() and not sidecar.exists()+ assert (tmp_path / "home/.Trash" / p.name).exists()+ assert (tmp_path / "home/.Trash" / sidecar.name).exists()+++def test_fetch_check_and_strict_tree(pack, capsys):+ models, _ = pack+ assert F.main(["--models", str(models), "--check"]) == 0+ f = models / "generator/config.json"+ f.write_bytes(b"x" * f.stat().st_size)+ assert F.main(["--models", str(models), "--check"]) == 1+ assert "sha256 mismatch" in capsys.readouterr().out+ (models / "generator/.cache").mkdir()+ assert any(".cache: unexpected entry" in e for e in F.pack_problems(models))+ result = subprocess.run([sys.executable, str(ROOT / "scripts/pinokio/music_fetch.py"), "--models", str(models), "--check"], capture_output=True, text=True)+ assert result.returncode == 1 and "sha256 mismatch" in result.stdout+++def test_fetch_sources_are_the_pinned_public_repos():+ sources = F.choose_sources()+ assert sources == F.SOURCES+ assert sources["generator"] == {"repo": "vanch007/mlx-Yue2-3B",+ "revision": "fa66d203dd56d7e033e05ee8b32269768984c4cc", "prefix": ""}+ assert sources["vae"] == {"repo": "m-a-p/YuE2-Vae",+ "revision": "95535e72a97bc0f09b8ada125d26b4009428c0e8", "prefix": ""}+ assert not hasattr(F, "MIRROR_REPO")+++def test_fetch_stages_moves_and_skips_intact(pack, monkeypatch):+ models, _ = pack+ # Force one broken file and a prior direct-download cache; the fake hub+ # serves only fixture bytes, and a healthy second pass makes zero calls.+ originals = {str(p.relative_to(models)): p.read_bytes() for d in (models / "generator", models / "vae") for p in d.rglob("*") if p.is_file()}+ (models / "generator/ar-8bit.safetensors").unlink()+ (models / "generator/.cache").mkdir()+ calls = []+ def download(repo_id, revision, filename, local_dir, force_download):+ part = "generator" if repo_id == F.SOURCES["generator"]["repo"] else "vae"+ assert ".staging" in str(local_dir) and filename != "README.md"+ calls.append((part, filename))+ p = Path(local_dir) / filename+ p.parent.mkdir(parents=True, exist_ok=True)+ (Path(local_dir) / ".cache").mkdir(exist_ok=True)+ p.write_bytes(originals[part + "/" + filename])+ return str(p)+ import huggingface_hub+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", download)+ monkeypatch.setattr(F, "choose_sources", lambda api: F.SOURCES)+ monkeypatch.setattr(huggingface_hub.HfApi, "list_repo_files", lambda *a, **kw: ["licenses/notice.txt"])+ F.fetch_pack(models, 0)+ assert not (models / "generator/.cache").exists()+ assert ("generator", "ar-bf16.safetensors") not in calls+ assert not F.pack_problems(models, hashes=True)+ calls.clear()+ F.fetch_pack(models, 14)+ assert calls == []+++def test_runner_help_and_empty_input():+ music_python = Path.home() / "AI/projects/yue2-mlx/.venv/bin/python"+ runner = ROOT / "scripts/music/yue2_run.py"+ result = subprocess.run([sys.executable, str(runner), "--model-dir", "/missing", "--vae-dir", "/missing", "--output", "/tmp/no-song.wav"], capture_output=True, text=True, timeout=30)+ assert result.returncode == 2 and "Give it something" in result.stdout+ assert "stage loading" not in result.stdout+ if not music_python.exists():+ pytest.skip("music venv unavailable for --help")+ result = subprocess.run([str(music_python), str(runner), "--help"], capture_output=True, text=True, timeout=30)+ assert result.returncode == 0 and "--max-seconds" in result.stdout and "--instrumental" in result.stdout+++def test_invalid_pack_metadata_is_unavailable(pack):+ (P.MUSIC_MODELS / "generator/conversion.json").write_text("[]")+ assert not P.music_status()["available"]+ assert P.music_status()["reason"] == "missing_weights"+++def test_dispatch_stub_process_and_guard_cleanup(pack, monkeypatch, tmp_path):+ stub = tmp_path / "stub_runner.py"+ stub.write_text('''import sys,json,pathlib+args=sys.argv+out=pathlib.Path(args[args.index('--output')+1])+print('[music] stage loading',flush=True)+print('[music] synth 8/8',flush=True)+out.write_bytes(b'fixture WAV')+pathlib.Path(str(out)+'.json').write_text(args[args.index('--extra-json')+1])+print('[music] done 5 '+str(out),flush=True)+''')+ monkeypatch.setattr(P, "MUSIC_RUNNER", stub)+ killed = []+ monkeypatch.setattr(P.HELPER, "kill", lambda: killed.append(True))+ job = P.make_job({"mode": "music", "music_style": "test"})+ P.STATE["current"] = job+ P.run_job_inner(job)+ assert killed and Path(job["output_path"]).is_file()+ assert job["progress"]["pct"] == 100+ assert P.STATE["music_pgid"] is None+ assert not P._PROC_GUARDS["music"][0].exists()+ # The panel never creates a shared lock.+ assert not P.MUSIC_GPU_FILE_LOCK.exists() and not P.MUSIC_GPU_DIR_LOCK.exists()+++def test_stop_escalates_only_the_owned_group(pack, monkeypatch):+ signals = []+ monkeypatch.setattr(P.os, "killpg", lambda pg, sig: signals.append((pg, sig)))+ P.STATE["music_pgid"] = 987654+ P._stop_music_proc(grace=0.01)+ deadline = time.monotonic() + 1+ while len(signals) < 2 and time.monotonic() < deadline:+ time.sleep(.01)+ assert signals == [(987654, signal.SIGTERM), (987654, signal.SIGKILL)]+ signals.clear()+ P._stop_music_proc(grace=0.05)+ P.STATE["music_pgid"] = None+ time.sleep(.1)+ assert signals == [(987654, signal.SIGTERM)]+++def node_eval(source):+ result = subprocess.run(["node", "-e", source], capture_output=True, text=True, timeout=30)+ assert result.returncode == 0, result.stderr+ return json.loads(result.stdout)+++def test_video_switcher_byte_identical_and_music_surface():+ current = (ROOT / "webapp/js/engines.js").read_text()+ before = subprocess.check_output(["git", "show", "d616662:webapp/js/engines.js"], cwd=ROOT, text=True)+ names = ("engineStatus", "engineServesMode", "_currentSurface", "engineOnSurface", "engineRenderable", "_engineRowVisible", "_engineTooltip", "renderEngineSwitch")+ def render(source, engines, workflow, capable=True):+ funcs = '\n'.join(extract_function(n, source) for n in names)+ return node_eval('''const box={innerHTML:'',hidden:false,querySelector:()=>null};+const divider={hidden:false}; const menu={innerHTML:'',querySelectorAll:()=>[]};+const document={body:{dataset:{workflow:WORKFLOW}},getElementById:id=>id==='engineSwitch'?box:divider};+const window={_ENGINE_PROBES:{h3:{capable:CAPABLE,available:true},music:{capable:true,available:true}}};+const ENGINES=REGISTRY; const currentMode='t2v';+const currentEngine=()=> 'ltx'; const musicComposeActive=()=>true;+const escapeHtml=s=>String(s||''); const _engineMenuEl=()=>menu; const closeEngineMenu=()=>{};+'''.replace('WORKFLOW', json.dumps(workflow)).replace('CAPABLE', json.dumps(capable)).replace('REGISTRY', json.dumps(engines)) + funcs + '\nrenderEngineSwitch();console.log(JSON.stringify({box,divider,menu}));')+ registry = P.engines_payload()+ old_registry = [e for e in registry if e["id"] != "music"]+ for capable in (False, True):+ assert render(before, old_registry, "manual", capable) == render(current, registry, "manual", capable)+ music = render(current, registry, "audio")+ assert music["box"]["hidden"] is False and "YuE2" in music["box"]["innerHTML"]+ assert "Hailuo H3" not in music["menu"]["innerHTML"]+++def test_compose_payload_and_chain_do_not_submit():+ src = (ROOT / "webapp/js/characters.js").read_text()+ result = node_eval('''let submits=0,mode='',workflow='';+const els=Object.fromEntries(Object.entries({musicLyrics:'kept lyrics',musicStyle:'warm pop',musicMode:'full',musicMaxSeconds:'240',musicSeed:'-1',musicQuality:'final'}).map(([k,value])=>[k,{value}]));+els.musicInstrumental={checked:true};+const document={getElementById:id=>els[id]}; const AUDIO_STUDIO={};+const findOutputByPath=()=>({clip_sec:120}); const audioModeSet=m=>{mode=m};+const workflowSwitch=w=>{workflow=w};const audioStudioRenderSlots=()=>{}; const phosToast=()=>{};+const fetch=()=>{submits++};+''' + extract_function("musicFormParams", src) + extract_function("useTrackInA2V", src) + '''+const payload=Object.fromEntries(musicFormParams());useTrackInA2V('/tmp/song.wav');+console.log(JSON.stringify({payload,lyrics:els.musicLyrics.value,AUDIO_STUDIO,submits,mode,workflow}));''')+ assert result["payload"]["music_instrumental"] == "on" and result["payload"]["music_lyrics"] == ""+ assert result["lyrics"] == "kept lyrics"+ assert result["mode"] == "drive" and result["workflow"] == "audio" and result["submits"] == 0+ assert result["AUDIO_STUDIO"]["audioPath"] == "/tmp/song.wav"+++def test_compose_visibility_tracks_install_state():+ src = (ROOT / "webapp/js/characters.js").read_text()+ result = node_eval('''let audioModeChoice=null,musicBusy=false;+const window={_ENGINE_PROBES:{music:{available:false,capable:true}}};+const els=Object.fromEntries(['audioModeGroup','musicComposePane','audioDrivePane','musicInstrumental','musicLyrics','musicInstrumentalPill','musicMaxSeconds','musicMaxSecondsVal','musicQuality','musicEstimate','musicGenBtn'].map(id=>[id,{hidden:false,classList:{toggle:()=>{}}}]));+els.musicInstrumental.checked=false;els.musicMaxSeconds.value='240';els.musicQuality.value='final';+const document={body:{dataset:{workflow:'audio'}},getElementById:id=>els[id],querySelectorAll:()=>[]};+const renderEngineSwitch=()=>{};+''' + extract_function("updateMusicAvailability", src) + extract_function("musicFormChanged", src) + '''+const states=[];+for(const available of [false,true,false]) {+ updateMusicAvailability({music:{available,capable:true,estimates:{}}});+ states.push({strip:els.audioModeGroup.hidden,compose:els.musicComposePane.hidden,drive:els.audioDrivePane.hidden});+}+console.log(JSON.stringify(states));''')+ assert result == [{"strip": True, "compose": True, "drive": False},+ {"strip": False, "compose": False, "drive": True},+ {"strip": True, "compose": True, "drive": False}]+++# ---- review fixes (2026-09-17) ------------------------------------------------++def test_progress_eta_is_total_and_remaining_is_separate():+ src = Path(P.__file__).read_text()+ body = src[src.index("def run_music_job_inner"):src.index("ENGINE_DEFAULT = ")]+ assert 'eta_sec=music_estimate(p["music_quality"], p["music_max_seconds"])["eta_sec"],' in body+ assert "remaining_sec=max(0," in body+++def test_runner_reports_decode_and_never_publishes_after_stop():+ src = (ROOT / "scripts/music/yue2_run.py").read_text()+ assert "_vae.OobleckDecoder.decode = decode_with_progress" in src+ assert 'say("decode"' in src+ call = src.index("result = pipe(**kw)")+ assert src.index("if stop.is_set():", call) < src.index("sf.write(", call)+++def test_music_sync_makes_the_checkout_absolute(tmp_path):+ script = ROOT / "scripts/pinokio/music_sync.sh"+ fakebin = tmp_path / "bin"+ fakebin.mkdir()+ (fakebin / "uv").write_text('#!/bin/sh\necho "ENV=$UV_PROJECT_ENVIRONMENT"\necho "ARGS=$*"\n')+ (fakebin / "uv").chmod(0o755)+ (tmp_path / "engines/yue2").mkdir(parents=True)+ out = subprocess.run(["bash", str(script), "engines/yue2"], cwd=tmp_path, capture_output=True, text=True,+ env={**os.environ, "PATH": f"{fakebin}:{os.environ['PATH']}"}, timeout=30)+ assert out.returncode == 0, out.stderr+ real = (tmp_path / "engines/yue2").resolve()+ assert f"ENV={real}/.venv" in out.stdout and f"--project {real}" in out.stdout+ assert "music_sync.sh" in (ROOT / "install_music.js").read_text()+ assert "music_sync.sh" in (ROOT / "scripts/post_update.sh").read_text()+++def test_install_music_is_reachable_while_the_panel_runs():+ probe = (+ "const path=require('path'),fs=require('fs');const root=process.argv[1];"+ "const mod=require(path.join(root,'pinokio.js'));"+ "const info={path:(...a)=>path.join(root,...a),exists:p=>fs.existsSync(path.join(root,p)),"+ "running:s=>s==='start.js',local:s=>s==='start.js'?{url:'http://127.0.0.1:1'}:{}};"+ "mod.menu({},info).then(m=>console.log(JSON.stringify(m.map(i=>i.text))))"+ )+ out = subprocess.run(["node", "-e", probe, str(ROOT)], capture_output=True, text=True, timeout=30)+ if out.returncode != 0 or not out.stdout.strip():+ pytest.skip("pinokio.js menu not evaluable here: " + out.stderr[-200:])+ items = json.loads(out.stdout)+ if "Open Panel" not in items:+ pytest.skip("this checkout is not in the installed/running menu state")+ assert any("music engine" in t for t in items) or P.SYSTEM_RAM_GB < 24+++def test_music_estimate_is_calibrated_and_scaled(monkeypatch):+ monkeypatch.setenv("PHOSPHENE_SPEED_FACTOR", "1")+ final = P.music_estimate("final", 180)+ # 177.8 s of audio took 180.2 s on the M4 Max.+ assert 170 <= final["eta_sec"] <= 190+ assert 60 <= P.music_estimate("draft", 120)["eta_sec"] <= 68+ assert final["eta_measured"] is False # a fit, never a measurement+ monkeypatch.setenv("PHOSPHENE_SPEED_FACTOR", "2")+ assert abs(P.music_estimate("final", 180)["eta_sec"] - 2 * final["eta_sec"]) <= 1+++def test_external_gpu_lock_is_read_never_written(pack, monkeypatch, tmp_path):+ stub = tmp_path / "never_runs.py"+ stub.write_text("raise SystemExit('the runner must not start while a lock exists')\n")+ monkeypatch.setattr(P, "MUSIC_RUNNER", stub)+ monkeypatch.setattr(P.HELPER, "kill", lambda: None)+ for lock, make in ((P.MUSIC_GPU_FILE_LOCK, lambda p: p.write_text("lab job")),+ (P.MUSIC_GPU_DIR_LOCK, lambda p: p.mkdir())):+ make(lock)+ job = P.make_job({"mode": "music", "music_style": "test"})+ with pytest.raises(P.RenderRefused, match=lock.name):+ P.run_job_inner(job)+ assert lock.exists() # left exactly as found+ if lock.is_dir():+ lock.rmdir()+ else:+ lock.unlink()+ src = Path(P.__file__).read_text()+ body = src[src.index("def run_music_job_inner"):src.index("ENGINE_DEFAULT = ")]+ assert "MUSIC_GPU_DIR_LOCK.mkdir" not in src and "MUSIC_GPU_FILE_LOCK.open" not in src+ assert "_music_take_gpu_locks" not in src and "_music_release_gpu_locks" not in src+++def test_late_stop_leaves_nothing_behind(pack, monkeypatch, tmp_path):+ """The runner publishes a song, and Stop lands while it does."""+ import threading+ ran = tmp_path / "ran"+ stub = tmp_path / "late_runner.py"+ stub.write_text(f'''import sys,pathlib,time+args=sys.argv+out=pathlib.Path(args[args.index('--output')+1])+out.with_name(out.stem+'.partial'+out.suffix).write_bytes(b'partial')+out.write_bytes(b'late WAV')+pathlib.Path(str(out)+'.json').write_text('{{}}')+pathlib.Path({str(ran)!r}).write_text(str(out))+time.sleep(1.5)+print('[music] done 1 '+str(out),flush=True)+''')+ monkeypatch.setattr(P, "MUSIC_RUNNER", stub)+ monkeypatch.setattr(P.HELPER, "kill", lambda: None)+ # Another song already in the gallery must survive the cleanup.+ keep = P.OUTPUT / "music_20260101_000000_other.wav"+ keep.write_bytes(b"other song")+ job = P.make_job({"mode": "music", "music_style": "test"})+ P.STATE["current"] = job++ def stop_after_publish():+ for _ in range(200):+ if ran.exists():+ job["cancel_requested"] = True+ return+ time.sleep(0.02)++ t = threading.Thread(target=stop_after_publish)+ t.start()+ with pytest.raises(P.JobStopped):+ P.run_job_inner(job)+ t.join()+ published = Path(ran.read_text())+ assert published.parent == P.OUTPUT and published != keep+ assert not published.exists()+ assert not Path(str(published) + ".json").exists()+ assert not published.with_name(published.stem + ".partial.wav").exists()+ assert keep.read_bytes() == b"other song"+++def test_stop_targets_the_pgid_read_with_the_cancel_flag(pack, monkeypatch):+ hit = []+ monkeypatch.setattr(P.os, "killpg", lambda pg, sig: hit.append(pg))+ monkeypatch.setattr(P.HELPER, "kill", lambda: None)+ job = {"id": "a", "params": {"engine": "music"}}+ P.STATE["current"] = job+ P.STATE["music_pgid"] = 111++ real = P._stop_music_proc++ def advanced(*a, **kw):+ # The worker moves on to the next song between the lock and the signal.+ P.STATE["music_pgid"] = 222+ return real(*a, **kw)++ monkeypatch.setattr(P, "_stop_music_proc", advanced)+ try:+ P.stop_current_job(timeout=0.01)+ except Exception:+ pass+ assert hit and hit[0] == 111 and 222 not in hit+ P.STATE["music_pgid"] = None+ P.STATE["current"] = None+++def test_completed_staged_file_is_promoted_not_refetched(pack, monkeypatch):+ models = P.MUSIC_MODELS+ name = "ar-bf16.safetensors"+ stage = models / ".staging/generator"+ stage.mkdir(parents=True)+ os.replace(models / "generator" / name, stage / name)+ (models / "pack_source.json").unlink()+ fetched = []++ def fake_download(repo_id, revision, filename, local_dir, force_download=False):+ fetched.append(filename)+ src = models / ("generator" if "generator" in str(local_dir) else "vae") / filename+ dest = Path(local_dir) / filename+ dest.parent.mkdir(parents=True, exist_ok=True)+ dest.write_bytes(src.read_bytes())+ return str(dest)++ class API:+ def list_repo_files(self, repo, revision):+ return ["licenses/notice.txt"]++ import huggingface_hub+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", fake_download)+ monkeypatch.setattr(huggingface_hub, "HfApi", lambda: API())+ monkeypatch.setattr(F.shutil, "disk_usage", lambda p: SimpleNamespace(free=0))+ monkeypatch.setattr(F, "PACK_BYTES", 10**12)+ F.fetch_pack(models, 0)+ assert name not in fetched+ assert F.pack_problems(models, hashes=True) == []+++def test_runner_checks_stop_right_before_publishing():+ src = (ROOT / "scripts/music/yue2_run.py").read_text()+ write = src.index("sf.write(tmp")+ assert src.index("if stop.is_set():", write) < src.index("os.replace(tmp, out)", write)+++def test_fetch_clears_abandoned_temporaries_and_does_not_credit_them():+ src = (ROOT / "scripts/pinokio/music_fetch.py").read_text()+ assert 'stage.rglob("*.incomplete")' in src and "leftover.unlink()" in src+ assert "partial_bytes" not in srcdiff --git a/test_storyboard_editor_ui.py b/test_storyboard_editor_ui.pyindex 55701d0..c8c297d 100644--- a/test_storyboard_editor_ui.py+++ b/test_storyboard_editor_ui.py@@ -97,6 +97,10 @@ FUNCTIONS = (# Where a dragged pixel lands is the whole feature and the one thing that# cannot be checked by looking at it."sbeTlClamp", "sbeLaneHeights", "sbeTlPrefRead", "sbeTlPrefWrite",+ # ...and the floor is no longer a number: it is the sum of the lane set+ # that is ON SCREEN, which is what lets the handle push a timeline with+ # small sound lanes 114px lower than one with tall ones.+ "sbeLaneBase", "sbeLaneCap", "sbeTlFloor", "sbeTlRoof", "sbeAudioSmall",# The level line's geometry, which three gestures now share instead of# each carrying a copy of a 20px band."sbeStripY", "sbeStripGain", "sbeStripEditable", "sbeKeysLegend",@@ -175,6 +179,10 @@ FUNCTIONS = (# to stack; this decides which is open and which is a chip."sbePaintNotices", "sbeNoticeOpen", "sbeNoticeClick", "sbeNoticeLater","sbeErrsToggle",+ # The two clip-sound lanes (A/B): the insert paths and the save body call+ # these, so every harness that extracts those needs them too.+ "sbeSoundLane", "sbeLaneName", "sbeSetSoundLane", "sbeAlternateLanes",+ "sbeLaneAfter", "sbeLaneFit",)SHIM = r"""@@ -237,8 +245,8 @@ const SBE_TL_CHROME = 32;const SBE_LANES = [{ key: 'ov', base: 32, cap: 56, share: 0.08 },{ key: 'track', base: 64, cap: 120, share: 0.14 },- { key: 'alane', base: 44, cap: 190, share: 0.44 },- { key: 'wave', base: 108, cap: 240, share: 0.34 },+ { key: 'alane', base: 44, cap: 190, share: 0.44, audio: true, small: 18 },+ { key: 'wave', base: 108, cap: 240, share: 0.34, audio: true, small: 20 },];const SBE_TL_MIN_H = 280;const SBE_TL_MAX_H = 638;@@ -1992,6 +2000,19 @@ out.tlClamp = {ceiling: sbeTlClamp(9000, 99999),junk: sbeTlClamp('kittens', 600),};+// THE SOUND AREA AT ITS TWO SIZES. The floor is the sum of the lane set that+// is on screen, so making the sound lanes small has to MOVE it — that is the+// whole of "I cannot push it down if I want to compact it" — and a lane that+// is supposed to be thin may never take a dragged pixel.+out.tlSmall = {+ floorOpen: sbeTlFloor(false), floorSmall: sbeTlFloor(true),+ roofOpen: sbeTlRoof(false), roofSmall: sbeTlRoof(true),+ lanesSmall: sbeLaneHeights(sbeTlFloor(true), true),+ lanesSmallDragged: sbeLaneHeights(sbeTlFloor(true) + 200, true),+ clampSmall: [sbeTlClamp(10, 600, true), sbeTlClamp(9000, 99999, true)],+ // Defaulted, with nothing small on screen: every existing caller's meaning.+ floorNow: sbeTlFloor(), roofNow: sbeTlRoof(),+};out.lanesAtFloor = sbeLaneHeights(SBE_TL_MIN_H);out.lanesAtCeiling = sbeLaneHeights(SBE_TL_MAX_H);out.lanesMid = sbeLaneHeights(SBE_TL_MIN_H + 100);@@ -3176,16 +3197,29 @@ class SplitEditsInTheBrowser(unittest.TestCase):chrome = int(re.search(r"const SBE_TL_CHROME = (\d+);",self.src).group(1))lanes = re.findall(- r"\{ key: '(\w+)',\s+base:\s*(\d+), cap:\s*(\d+), share: ([\d.]+) \}",+ r"\{ key: '(\w+)',\s+base:\s*(\d+), cap:\s*(\d+), share: ([\d.]+)",self.src)self.assertEqual([l[0] for l in lanes], ["ov", "track", "alane", "wave"])# These two are read by the layout harness's injected probe JS, so# the editor module publishes them as globalThis properties rather# than module-private consts (slice 3, docs/ARCHITECTURE.md).- floor = int(re.search(r"globalThis\.SBE_TL_MIN_H = (\d+);", self.src).group(1))- ceil_ = int(re.search(r"globalThis\.SBE_TL_MAX_H = (\d+);", self.src).group(1))- self.assertEqual(floor, chrome + sum(int(l[1]) for l in lanes))- self.assertEqual(ceil_, chrome + sum(int(l[2]) for l in lanes))+ # AND THE FLOOR IS NO LONGER A NUMBER AT ALL. It is computed from the+ # lane set that is on screen, because the sound lanes have two heights+ # now and a constant floor is what stopped the owner compacting his+ # timeline: "I can also not push it down if I want to compact it."+ self.assertIn("globalThis.SBE_TL_MIN_H = sbeTlFloor(false);", self.src)+ self.assertIn("globalThis.SBE_TL_MAX_H = sbeTlRoof(false);", self.src)+ base_of = extract_function("sbeLaneBase", self.src)+ self.assertIn("(small && L.audio) ? L.small : L.base", base_of)+ for fn, part in (("sbeTlFloor", "sbeLaneBase"), ("sbeTlRoof", "sbeLaneCap")):+ body = extract_function(fn, self.src)+ self.assertIn("let n = SBE_TL_CHROME;", body)+ self.assertIn("for (const L of SBE_LANES) n += " + part + "(L, s);", body)+ # The numbers those rules produce are checked in the browser-side probe+ # (test_small_sound_lanes_lower_the_floor_and_never_grow); here it is+ # enough that nobody can type one in again.+ floor = chrome + sum(int(l[1]) for l in lanes)+ self.assertEqual(floor, 280)# And the CSS fallback — what the page shows for the frame before the# JS runs — is the same number.self.assertIn("min-height: var(--sbe-tl-h, %dpx);" % floor, self.src)@@ -3206,7 +3240,7 @@ class SplitEditsInTheBrowser(unittest.TestCase):# factor would give the picture track 41% of the drag and the sound# strip 14%, which is the opposite of the sentence above.lanes = dict((m[0], float(m[3])) for m in re.findall(- r"\{ key: '(\w+)',\s+base:\s*(\d+), cap:\s*(\d+), share: ([\d.]+) \}",+ r"\{ key: '(\w+)',\s+base:\s*(\d+), cap:\s*(\d+), share: ([\d.]+)",self.src))self.assertAlmostEqual(sum(lanes.values()), 1.0, places=6)self.assertGreaterEqual(lanes["alane"] + lanes["wave"], 0.75)@@ -4708,7 +4742,7 @@ class TheSoundStaysWhereItWasPut(unittest.TestCase):# handle must not be sized against a number somebody can move. The# block inside a lane is inset 6px top and bottom; the strip 3px.lanes = dict(re.findall(- r"\{ key: '(\w+)',\s+base:\s*(\d+), cap:\s*\d+, share: [\d.]+ \}",+ r"\{ key: '(\w+)',\s+base:\s*(\d+), cap:\s*\d+, share: [\d.]+",src))for key, inset in (("track", 12), ("alane", 7)):block = int(lanes[key]) - inset@@ -5116,6 +5150,36 @@ class TheTimelineIsResizable(unittest.TestCase):# dead band under the soundtrack.self.assertEqual(self.r["laneSums"], [0, 0, 0])+ def test_small_sound_lanes_lower_the_floor_and_never_grow(self):+ # "The sound expands lower. The picture is so tiny… and I can also not+ # push it down if I want to compact it." The floor WAS a constant — the+ # sum of every lane's full height — so the handle could never ask for+ # less than the sound lanes' 44 + 108, whatever the user wanted. It is+ # computed from the lane set on screen now, and these are the numbers+ # that make the handle reach lower and hand the difference to the+ # picture (sbeFitMonitors subtracts exactly these two terms).+ s = self.r["tlSmall"]+ self.assertEqual(s["floorOpen"], 280)+ self.assertEqual(s["floorSmall"], 32 + 32 + 64 + 18 + 20)+ self.assertEqual(s["floorOpen"] - s["floorSmall"], 114)+ self.assertEqual(s["roofOpen"], 638)+ self.assertEqual(s["roofSmall"], 32 + 56 + 120 + 18 + 20)+ # Nothing on screen is small, so an unasked question means "as drawn".+ self.assertEqual([s["floorNow"], s["roofNow"]],+ [s["floorOpen"], s["roofOpen"]])+ # A LANE THAT IS SUPPOSED TO BE THIN NEVER TAKES A DRAGGED PIXEL —+ # otherwise "compact" lasts until the first drag.+ self.assertEqual(s["lanesSmall"]["alane"], 18)+ self.assertEqual(s["lanesSmall"]["wave"], 20)+ self.assertEqual(s["lanesSmallDragged"]["alane"], 18)+ self.assertEqual(s["lanesSmallDragged"]["wave"], 20)+ # ...and the 200px that lane could not take was not dropped: the+ # picture and the overlay took it, up to their own caps.+ self.assertEqual(s["lanesSmallDragged"]["track"], 120)+ self.assertEqual(s["lanesSmallDragged"]["ov"], 56)+ # Both ends of the clamp move with the lane set.+ self.assertEqual(s["clampSmall"], [s["floorSmall"], s["roofSmall"]])+def test_the_sound_takes_the_biggest_share_because_that_was_the_ask(self):g = self.r["laneGain"]self.assertEqual(sum(g.values()), 100)@@ -5862,6 +5926,7 @@ class TheClipBar(unittest.TestCase):("sbeCbDelSound", "sbeDeleteStripSel()", "Delete sound"),("sbeCbPoints", "sbeClearPoints()", "Clear points"),("sbeCbLock", "sbeToggleLock()", "Lock"),+ ("sbeCbFaceFix", "sbeFaceFixSel()", "Face Fix ×2"),)def test_every_verb_is_in_the_real_markup_with_a_handler(self):@@ -6472,7 +6537,7 @@ class TimelineMarkup(unittest.TestCase):# row it is sizing, or the budget becomes its own input. The timeline# is counted at its CSS floor for exactly that reason.fn = extract_function("sbeFitMonitors", self.src)- self.assertIn("SBE_TL_MIN_H", fn)+ self.assertIn("sbeTlFloor()", fn)self.assertIn("clientHeight", fn)self.assertIn("sbeMonitorFit(", fn)self.assertIn("--sbe-prog-h", fn)diff --git a/webapp/docs/buttons.md b/webapp/docs/buttons.mdindex f9542dd..2bcde73 100644--- a/webapp/docs/buttons.md+++ b/webapp/docs/buttons.md@@ -20,7 +20,8 @@ The buttons that show a picture instead of a word. Hover any of them in the pane| Button | What it does ||---|---|| **Params** | the settings the selected output was made with |-| **Extend** · **LTX Upscale** · **To film** · **Animate** | use the selected output as the start of something new |+| **Upscale & Face Fix** | queues a 2× re-render of the clip that keeps the face and the sound; the fixed clip lands next to it. The small button beside it opens the [settings](#docs/remix/upscale-face-fix) |+| **Extend** · **To film** · **Animate** | use the selected output as the start of something new || the crossed-out eye (red) | hides this output from the gallery — the file is not deleted || **Expand** | full screen ([[sc:outputs.expand]]; Esc closes it) |@@ -29,6 +30,7 @@ The buttons that show a picture instead of a word. Hover any of them in the pane| Button | What it does ||---|---|| **ⓘ** | how this output was made — prompt, engine, quality, seed, LoRAs |+| **Upscale & Face Fix** (on a video card, on hover) | queues the face-safe 2× of that clip — same as the player button || [[icon:ph-trash-simple]] | moves the file to the macOS Trash, after asking ([[sc:outputs.trash]] on the selected output) || [[icon:ph-folder-simple]] (Outputs header) | reveals the outputs folder in Finder |@@ -37,6 +39,7 @@ The buttons that show a picture instead of a word. Hover any of them in the pane| Button | What it does ||---|---|| **×** on a queued job | removes it from the queue |+| **Face Fix** on a finished video in the history | queues Upscale & Face Fix for that clip || **×** on a failed or stopped card | dismisses the message || **Stop** (under Generate) | stops the render in progress || **Stop early** (on the live preview) | stops it after asking — nothing is saved, the queue carries on |diff --git a/webapp/docs/editor.md b/webapp/docs/editor.mdindex 6474d35..a52b6fa 100644--- a/webapp/docs/editor.md+++ b/webapp/docs/editor.md@@ -13,7 +13,7 @@ The Editor is a timeline for the clips you make — from any engine, from a stor**The header** — the sequence's name, the draft chip, whether it is saved (*unsaved changes*, *saved · revision N*), **Undo**, **Redo**, **Save**, **Render** with its **▾**, and **⋯** (Drafts and versions, Media pool, Auto-edit, Storyboard, Close).-**The media pool** (left) — **This Sequence**, **Other sequences**, **Generations** and **Images**. Click a row to watch it in the Source monitor; **+** puts it at the end of the sequence; drag it onto the track to insert it where you drop it. **Add black** adds that many seconds of black at the end, **Add title** puts a title at the playhead, **Filter by name** searches ([[sc:search.focus]]).+**The media pool** (left) — **This Sequence**, **Other sequences**, **Generations**, **Images** and **Sound**. Click a row to watch it in the Source monitor; **+** puts it at the end of the sequence; drag it onto the track to insert it where you drop it. On **Sound**, **+** puts the sound on an audio track at the playhead; on a video row, **♪** puts only its sound there — see [Audio tracks](#docs/editor/tracks). **Add black** adds that many seconds of black at the end, **Add title** puts a title at the playhead, **Filter by name** searches ([[sc:search.focus]]).**The monitors** — **Source** plays what you clicked in the pool (**Add to timeline** places it). **Program** plays the timeline. Beside them, the inspector (below) and *Rendered but not on the timeline*, with **Place** for each clip that finished but was never put on the track.@@ -23,10 +23,11 @@ The Editor is a timeline for the clips you make — from any engine, from a stor|---|---|| **V2 Overlay** | titles and cards laid over the picture || **V1 Picture** | the shots, in order |-| **A1 Clip sound** | each shot's own sound |+| **A1 Clip sound A** / **Clip sound B** | each shot's own sound, on two lanes — shots alternate A, B, A… so neighbours can overlap and crossfade || **A2 Music** | the soundtrack |+| **A3, A4, …** | audio tracks — laugh tracks, stings, beds, any number of sounds; every track plays together |-**The transport** — **Play**, 🔊 (mutes the preview only), the time, **Snap to beat**, zoom **−** / slider / **+**, the **i** (the preview is approximate at cuts; the render is exact) and **Keys**. Drag the timeline's top edge up for taller tracks; double-click it to reset.+**The transport** — **Play**, 🔊 (mutes the preview only), the time, **Snap to beat**, zoom **−** / slider / **+**, the **i** (the preview is approximate at cuts; the render is exact) and **Keys**. Drag the timeline's top edge up for taller tracks; double-click it to reset. With the sound lanes small (below) the edge goes much further down, and the picture gets what it leaves.## Selecting {#selecting}@@ -55,13 +56,14 @@ Every button is always there. When it cannot act, it is greyed out and its toolt| **Split** [[sc:editor.split]] | cuts the shot under the playhead in two at the playhead; nothing moves, nothing is lost | the playhead is not over a shot, is exactly on a cut, or the shot is locked || **Lift** [[sc:editor.lift]] | takes the selection out and **leaves the hole** as black, so nothing after it moves | nothing is selected || **Ripple delete** [[sc:editor.ripple]] | takes the selection out and **closes the gap** — everything after slides earlier and the film gets shorter | nothing is selected |-| **Duplicate** [[sc:editor.duplicate]] | the same shot again right after itself — trim, speed, fades and grade included; everything after slides | nothing is selected |+| **Duplicate** [[sc:editor.duplicate]] | the same shot again right after itself — trim, speed, fades and grade included; everything after slides. On a **sound on an audio track**: the same sound right after itself on its track (or the next free spot on it). On the **music (A2)** or a **clip's sound (A1)**: a copy of the sound on an audio track, right after it — the first track with room, or a new one | nothing is selected; the music's length is not known yet (press **Prepare**); the clip has no sound, or plays at a speed other than 1× || **Unlink sound** / **Link sound** / **Re-link sound** [[sc:editor.link]] | frees the sound from its picture so you can slide it (the J-cut and the L-cut). **Link sound** keeps the offset you made and makes the pair travel together; **Re-link sound** appears when the sound is back exactly under its picture | the selection is a still or black, which has no sound || **Resync sound** [[sc:editor.resync]] | slides the sound back to where its own picture plays it. Your trim is kept and it stays unlinked | the sound is still linked (so it cannot be out of sync), the clip has no sound, or it is already in sync || **Mute sound** / **Unmute sound** | switches this clip's own sound off — in the preview, the render and the export. The strip stays; the music is not affected | the clip has no sound || **Delete sound** | removes the clip's sound; the picture keeps playing, silent. Undo brings it back | the sound is still linked — unlink it first || **Clear points** | deletes the level points (the dots on the yellow line) from the selected strips. Fades are left alone | the sound has no level points || **Lock** / **Unlock** | pins a shot to its place — everything else flows around it, and it cannot be dragged or trimmed | nothing is selected |+| **Face Fix ×2** (Upscale & Face Fix) | queues a 2× re-render of the clip that keeps the face and the sound. When it lands, a line above the timeline offers **Swap it in** (same cut, same in and out points) or **Keep the old one**; the original file is not changed | nothing, several clips, a still or black is selected |When the pane is too narrow, the last buttons move into **More ▾**. **Right-click** a clip for the same actions at the pointer; right-click a hole for **Close this hole** and **Generate a shot here…**.@@ -85,6 +87,25 @@ A clip's sound starts **linked**: it moves with its picture, shows dimmer, and cA **J-cut** starts the next shot's sound before its picture; an **L-cut** lets a shot's sound run on under the next picture. Both are made the same way: unlink the sound, drag or trim the strip under the neighbouring shot, then **Link sound** to keep that offset.+### Two sound lanes: crossfades {#ab-lanes}++**A1** has two lanes, **Clip sound A** and **Clip sound B**. A new timeline lays its shots' sound on them in turn — the 1st shot on A, the 2nd on B, the 3rd on A — and a shot you add later goes on the lane its neighbour is not on. Sounds on **one** lane play one at a time (if two overlap there, the later one cuts the earlier one off); sounds on **different** lanes overlap and play together. That is what makes a sound dissolve: pull the end of one shot's sound under the start of the next and fade both.++- **Alternate A/B** on the **Clip sound B** head — or right-click any shot or sound → **Alternate sound lanes** — lays an existing timeline's sound A, B, A… in film order. Nothing moves in time; one **Undo** puts the lanes back.+- **Drag a sound up or down** to move it to the other lane — linked sounds too, since changing lane does not move them. Right-click a sound → **Move sound to lane B** / **Move sound to lane A** does the same.+- Everything else works the same on both lanes: unlink, trim, J-cut and L-cut, fades, level points, Mute, Resync, Duplicate, snapping (a dragged edge also snaps to the other sounds' edges).+- The preview plays both lanes, the render mixes them under the same safety limiter as the music (and **Duck under dialogue** follows sound on either lane), and the export puts **Clip sound B** on its own audio track, right after the first.++### Sound lanes small, so you can see the picture {#compact}++**A1**, **A2** and every audio track make themselves **small** — thin strips showing where each sound sits — while you are not working on sound, and come back to full height the moment you are. The picture and the monitors get the height they give up.++- **They open by themselves** when you click, hover or drag any sound or its lane head, when a sound is selected, when you open **Sound** in the media pool, when you add a track or a sound file, and while the film is playing. They never shrink in the middle of a drag, during playback, or under an open menu.+- **They make themselves small again** a couple of seconds after you leave the sound alone.+- **A small lane is a picture, not a control**: the waveform shows where the sound is; the grips, the corner fades and the level line are not there. Moving the pointer onto the lanes is enough to open them, so by the time you click, the sound is at full height and behaves exactly as it always has.+- **▾ on the A1 Clip sound A head** ([[sc:editor.soundLanes]]) pins it: press it once and the lanes stay small whatever you do; press it again (**▸**) and they stay at full height. Clicking a small lane hands the decision back to the automatic one. The choice is remembered in this browser, not in the film.+- With them small, the timeline's top edge can be pushed much lower than before — the box is only as tall as what is in it.+### When sound drifts: Resync {#resync}An unlinked strip that is not under its own picture shows a label with the offset, such as **+0.25s**. Click the label, or select the clip and press **Resync sound** ([[sc:editor.resync]]), to slide it back. It stays unlinked, so you can move it again.@@ -110,6 +131,18 @@ On an **unlinked** strip:- **Duck under dialogue** (off by default) steps the music back wherever a clip's own sound is playing. If you have drawn your own fades or level points on the music, they drive it instead, and the head says *"off — your own level line is driving the bed"*.- The music strip drags, trims, fades and takes level points exactly like a clip's sound.+### Audio tracks {#tracks}++Under **A2 Music** are the audio tracks — **A3**, **A4** and on. A track holds any number of sounds; sounds on **different** tracks play together (a laugh on A3 over a sting on A4 over the music), and sounds on the **same** track play one at a time and never overlap.++- **+ Add audio track** (under the track names) makes an empty one. Each track's head has its **name** (click to rename), **M** to mute the whole track, a **level** slider, and **×** to remove the track with its sounds (Undo brings it back).+- **Put a sound on a track:** open **Sound** in the media pool — this sequence's own audio folder and every sound file in the outputs (.wav .m4a .mp3 .aac) — and press **+** (it lands at the playhead) or drag the row onto a track. **♪** on a video row, or dragging a video onto a track, takes **its sound only**. **♪** beside **+ Add audio track** is **Add sound file…**: paste the path of any sound on this Mac; a file outside the outputs is copied into the sequence's audio folder so the preview can play it.+- Drop a sound on the dashed row under the last track and it gets **a track of its own**.+- A sound on a track works like an unlinked clip sound: **drag** it (up or down onto another track too — onto the dashed row makes a new track), **drag either end** to trim it, **drag a corner** to fade it, **click the yellow line** for a level point. It snaps to cuts, to the other sounds and to the beat; ⌥ while dragging ignores them.+- The clip bar acts on it: **Split** cuts the selected sound at the playhead, **Lift** / **Delete sound** take it off, **Ripple delete** also closes the gap on that track, **Duplicate**, **Mute sound**, **Clear points**, **Lock**. **⇧-click** / **⌘-click** selects several. Right-click it for the same verbs. **Unlink** and **Resync** stay grey — a sound on a track has no picture to link to.+- The inspector shows the selected sound's **Level**, **Fade in** / **Fade out** and **Add point at playhead**. The level you hear is the sound's level times its track's level.+- Everything plays in the preview, mixes into the render under the same safety limiter as the music, and exports: each audio track becomes its own audio track in Premiere / Resolve and its own layers in After Effects, with trims, levels, fades and mutes editable there.+## Titles, cards and black {#titles}- **Add title** (media pool) puts a 3-second title on **V2 Overlay** at the playhead. In the inspector: the text, **Size**, **Colour**, **Align**, **Across** / **Down** position and **Box behind**, plus fades. Drag it to move it, drag its edges to change its length; [[sc:editor.removeOverlay]] removes it.@@ -154,7 +187,7 @@ A transition borrows extra picture from beyond each clip's trim, so the cut does| **Size** | **As cut** · **1080p** · **4K** | only ever up, never a crop; 4K adds pixels, not detail || **Finish** | **Clean** · **Grain** · **Heavy grain** | on the delivered file only — the preview and the export stay clean |-**Export for Premiere / Resolve / AE** (in the same menu) writes a folder with an FCP7 XML (for Premiere and Resolve), an After Effects script and the media, and shows it in Finder. Sound comes out as separate stems, not the mixed track. Cuts, trims, speed, fades, mutes and reframing travel into the project as editable settings; titles do not, and transitions arrive as plain cuts.+**Export for Premiere / Resolve / AE** (in the same menu) writes a folder with an FCP7 XML (for Premiere and Resolve), an After Effects script and the media, and shows it in Finder. Sound comes out as separate stems, not the mixed track — the clips' sound (lane A, then lane B as its own track when it is used), the music, and one audio track per **A3, A4, …**. Cuts, trims, speed, fades, mutes and reframing travel into the project as editable settings; titles do not, and transitions arrive as plain cuts.**Auto-edit…** (⋯) re-cuts the sequence from scratch and throws away this arrangement — it asks first.@@ -185,6 +218,14 @@ A transition borrows extra picture from beyond each clip's trim, so the cut doesFor an L-cut, do the same with the **outgoing** shot and drag its strip's right end later.+### Crossfade two shots' sound {#job-crossfade}++1. Check the two shots' sound sits on different lanes (**Clip sound A** and **Clip sound B**). If not, press **Alternate A/B** on the **Clip sound B** head, or drag one sound to the other lane.+2. Select the **outgoing** shot, press **Unlink sound** ([[sc:editor.link]]) and drag its sound's right end later, under the next shot — it snaps to the next sound's start and to the cut.+3. Drag the right corner handle of that strip for a fade out, and the left corner handle of the incoming sound for a fade in over the same seconds. (The incoming sound can reach back the same way: unlink it and drag its left end earlier.)+4. Play across the cut — both sounds play together while they overlap.+5. **Save**.+### Replace a shot with a retake {#job-retake}1. Select the shot. Retake works on shots that came from a storyboard.diff --git a/webapp/docs/getting-started.md b/webapp/docs/getting-started.mdindex 281e21b..8254246 100644--- a/webapp/docs/getting-started.md+++ b/webapp/docs/getting-started.md@@ -43,7 +43,7 @@ The gallery on the right shows what you have made. Click a card to put it on the- **All / Videos / Photos** filter it, and the search box finds outputs by prompt words, model, LoRA, size or seed ([[sc:search.focus]] jumps to it).- **Show all** loads older renders than the newest 60.- [[sc:outputs.step]] steps through the gallery, [[sc:player.toggle]] plays and pauses, [[sc:outputs.expand]] expands the player to full screen.-- Under the player, the action row offers what you can do next with that clip: **Extend** it, **LTX Upscale** it, send it **To film**, **Animate** a still, see its **Params**.+- Under the player, the action row offers what you can do next with that clip: **Extend** it, run **Upscale & Face Fix** on it, send it **To film**, **Animate** a still, see its **Params**.- The trash button on a card moves the file to the macOS Trash after asking — restore it from Finder if you change your mind. [[sc:outputs.trash]] does the same for the selected output.## Where files go {#files}diff --git a/webapp/docs/remix.md b/webapp/docs/remix.mdindex 25901e7..cf95ed8 100644--- a/webapp/docs/remix.md+++ b/webapp/docs/remix.md@@ -25,20 +25,25 @@ An ordinary video works. A pose, depth or edge sequence you already have follows*B&W clip → color.* Pick the clip in **Source video to colorize** and describe the colours to paint in. The output keeps the source's size and length.-## LTX Upscale {#ltx-upscale}+## Upscale & Face Fix {#upscale-face-fix}-*Any clip → 2× sharper.* Re-renders a clip at twice its size with generated detail — not a filter. Made for Hailuo H3 drafts, works on any clip.+*Any clip → 2× sharper, face kept.* Re-renders a clip at twice its size with generated detail — not a filter — and keeps the face and the sound. Made for Hailuo H3 drafts, works on any clip. (Earlier versions called this **LTX Upscale** / **Upscale ×2**.)-1. Pick the clip in **Clip to upscale**, or press **LTX Upscale** under the player with a clip selected in Outputs.+**One click:** press **Upscale & Face Fix** under the player, on an Outputs card, on a finished row in the queue history, or on the Editor's clip bar. It queues the **Face Fix** recipe for that clip with the clip's own prompt and seed. The fixed clip is a **new file** next to the original, which is not changed. From the Editor, a line above the timeline offers to **swap it in** when it lands — same cut, same in and out points — or to keep the old one.++**With settings:** the small button beside **Upscale & Face Fix** under the player opens the clip here, in Remix.++1. Pick the clip in **Clip to fix**.2. Choose a preset:| Preset | What it does | Time for 5 s at 640×384 on an M4 Max ||---|---|---|-| **Faithful** | sharp, the face stays (default) | about 5.5 min |-| **Quick** | a touch softer | about 3.75 min |-| **Re-imagine** | the sharpest, and faces drift | about 7 min |+| **Face Fix** | one refine step from the clip — sharper, the face is not redrawn (default, and what the one-click button runs) | about 2.5 min |+| **Faithful** | three refine steps — sharper detail, the face can shift a little | about 5.5 min |+| **Quick** | two refine steps, a touch softer | about 3.75 min |+| **Re-imagine** | a full re-render — the sharpest, and faces drift | about 7 min |-3. Generate. The sound is kept, the length and (if you leave it empty) the prompt come from the source, and up to 0.3 s may be trimmed at the end. The result is capped at this Mac's Image-to-Video size.+3. Generate. The sound, the length and the frame count are kept, and (if you leave it empty) the prompt comes from the source. The result is capped at this Mac's Image-to-Video size. A 5 s 1024×576 source takes much longer (about 20 min for Face Fix).It needs the **LTX-2.5 Pixel Spatial Upscaler** adapter (0.3 GB) — download it from the Models window. A source already near the cap is refused, because it cannot grow enough to be worth the render.diff --git a/webapp/docs/troubleshooting.md b/webapp/docs/troubleshooting.mdindex 94f1d04..a164e52 100644--- a/webapp/docs/troubleshooting.md+++ b/webapp/docs/troubleshooting.md@@ -21,7 +21,7 @@ Do that, then choose Settings → **Hailuo H3 model** → Automatic or Compact.## A model or add-on is not downloaded {#missing}- *"Extend needs the LTX-2.5 High add-on (the Q8 model), which isn't downloaded on this Mac yet"* — the same for Keyframes and High quality. Install it from the Models window (click the health chip, then **Models**).-- *"Upscale ×2 needs the LTX-2.5 Pixel Spatial Upscaler adapter"* — download it from the Models window, then render again.+- *"Upscale & Face Fix needs the LTX-2.5 Pixel Spatial Upscaler adapter"* — download it from the Models window, then render again.- *"Stopped before rendering — the model weights are incomplete"* — a download was interrupted. Open the Models window and resume it. Settings → **Verify model files** checks every file and offers a re-download of any that are damaged.## "Click Update" — an engine older than the panel {#stale-engine}diff --git a/webapp/docs/video.md b/webapp/docs/video.mdindex 7b16919..3922a73 100644--- a/webapp/docs/video.md+++ b/webapp/docs/video.md@@ -14,7 +14,7 @@ The chips across the top of the form. Each one says what it takes.| **FFLF** | a start frame and an end frame | a clip that travels from one to the other || **Keyframes** | 3–8 frames | a clip that passes through each || **Extend** | a clip | more of that clip, after or before it |-| **Remix** | your own media | Ingredients, Motion Control, Colorize, LTX Upscale — see [Remix](#docs/remix) |+| **Remix** | your own media | Ingredients, Motion Control, Colorize, Upscale & Face Fix — see [Remix](#docs/remix) |Hailuo H3 renders **Text** and **Image**; the other modes are LTX's.@@ -122,11 +122,11 @@ After the render, the clip can be resized without cropping.- **Native** — as rendered.- **720p fit** / **1080p fit** — scaled and padded to fit. 720p fit is the default.-- **LTX ×2** — *generated detail*: queues an **Upscale ×2** pass right after the draft, which re-renders it at twice the size with LTX-2.5 and keeps the sound. It needs the 0.3 GB Upscale adapter, downloaded from the Models window.+Below the sizes, **Also run Upscale & Face Fix after the draft** is optional and off by default. When it is ticked, the draft ships as rendered and a second job re-renders it at twice the size with LTX-2.5, keeping the face and the sound; the fixed clip lands next to the draft. It needs the 0.3 GB Upscale adapter, downloaded from the Models window, and takes about the draft's time again.**On LTX** (under Customize → **Export**): **Native** (default), **720p fit**, or **2×**. When it is not Native, **Method** chooses **Fast** (instant) or **Sharp** (a sharper upscaler, +30–90 s).-Any finished clip can also go through [LTX Upscale](#docs/remix/ltx-upscale) later.+Any finished clip can also go through [Upscale & Face Fix](#docs/remix/upscale-face-fix) later — one click under the player.## More controls {#more}diff --git a/webapp/index.html b/webapp/index.htmlindex 57ec75e..d6deb5f 100644--- a/webapp/index.html+++ b/webapp/index.html@@ -92,6 +92,7 @@<symbol id="eng-mark-h3" viewBox="0 0 24 24"><path d="M5.4 6.4v11.2M11.4 6.4v11.2M5.4 12h6" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/><path d="M15.6 10v4M18.6 8.4v7.2M21.4 6.8v10.4" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/></symbol><!-- Flux Video — "F" with a flow chevron. Rendered only underLTX_ENGINE_PREVIEW=1; the symbol is free to sit here regardless. -->+<symbol id="eng-mark-music" viewBox="0 0 24 24"><path d="M9 18V5l11-2v13M9 8l11-2" fill="none" stroke="currentColor" stroke-width="2"/><ellipse cx="6" cy="18" rx="3" ry="2" fill="currentColor"/><ellipse cx="17" cy="16" rx="3" ry="2" fill="currentColor"/></symbol><symbol id="eng-mark-flux" viewBox="0 0 24 24"><path d="M7.4 17.6V6.4h6.4M7.4 11.6h5" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/><path d="M16.4 8.6l3.6 3.4-3.6 3.4" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></symbol><symbol id="ph-speaker-slash" viewBox="0 0 256 256"><line x1="48" y1="40" x2="208" y2="216" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M80,168H32a8,8,0,0,1-8-8V96a8,8,0,0,1,8-8H80l72-56V147" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M152,179v45L94.4,179.2" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol></defs>@@ -408,13 +409,14 @@LTX IC-LoRAs elsewhere recognises it here. --><button type="button" class="mode-chip pill-btn" data-remix="control" title="Union Control IC-LoRA — the render copies the motion, camera move, composition and pose of a clip you supply, while the prompt repaints the subject and scene. Feed it an ordinary video, or a pose / depth / canny sequence you already have.">Motion Control<span class="mc-sub sub">its motion → your scene</span></button><button type="button" class="mode-chip pill-btn" data-remix="restore" title="Colorize IC-LoRA — adds natural color to a black-and-white or desaturated clip.">Colorize<span class="mc-sub sub">B&W clip → color</span></button>- <!-- Upscale ×2 — the LTX-2.5 Pixel Spatial Upscaler IC-LoRA. A+ <!-- Upscale & Face Fix (was "Upscale ×2" / "LTX Upscale"; mode stays+ `upscale`) — the LTX-2.5 Pixel Spatial Upscaler IC-LoRA. Agenerative 2× enlarge: the source clip rides the referencechannel and the 2.5 base re-renders every pixel at twice thecanvas (up to this Mac's i2v cap). The natural partner of an H3draft: H3 does the story and the sound at a small canvas, LTX2.5 does the pixels. Works on any clip in Outputs. -->- <button type="button" class="mode-chip pill-btn" data-remix="upscale" title="LTX Upscale — LTX-2.5 Pixel Spatial Upscaler IC-LoRA. Re-renders a clip at twice its size with real generated detail (not a filter). Made for H3 drafts, works on any clip.">LTX Upscale<span class="mc-sub sub">any clip → 2× sharper</span></button>+ <button type="button" class="mode-chip pill-btn" data-remix="upscale" title="Upscale & Face Fix — LTX-2.5 Pixel Spatial Upscaler IC-LoRA. Re-renders a clip at twice its size with real generated detail (not a filter) and keeps the face and the sound. Made for H3 drafts, works on any clip. One click from any clip: the Upscale & Face Fix button under the player.">Upscale & Face Fix<span class="mc-sub sub">any clip → 2× sharper · face kept</span></button></div></div>@@ -716,7 +718,7 @@<div class="hint" style="margin-top:6px">Pick a black-and-white or washed-out clip. The prompt below describes the colors to paint in (e.g. "golden warm sunlight, blue sky, green grass"). Output matches the source's resolution + length. Runs on Q4 — no Q8 needed.</div></div>- <!-- Upscale ×2 (upscale) — source-video picker + one slider. The+ <!-- Upscale & Face Fix (mode `upscale`) — source-video picker + presets. TheLTX-2.5 Pixel Spatial Upscaler IC-LoRA re-renders the clip at2× (capped at this Mac's i2v canvas; frames + prompt come fromthe source and its sidecar). The slider is the IC reference@@ -725,7 +727,7 @@source is carried over. Shown/hidden by updateDerived() whencurrentMode === 'upscale'. --><div class="mode-only" id="upscaleSection">- <h2>Clip to upscale</h2>+ <h2>Clip to fix</h2><select id="upscaleSrcSelect" onchange="document.getElementById('upscale_source_path').value=this.value"></select><input name="upscale_source_path" id="upscale_source_path" placeholder="/path/to/draft.mp4" style="margin-top:6px"><!-- Presets, not a slider: the number (keep_shot) maps server-side@@ -733,10 +735,18 @@own latent for 1/2 steps, Re-imagine is the adapter's fullre-render from noise. Times measured on an M4 Max for a 5 s640×384 draft → 1280×768. -->- <div class="pill-group cols-3" id="upscalePresetGroup" style="margin-top:10px">- <button type="button" class="pill-btn active" data-keep="1.0" onclick="setUpscalePreset(this)"- title="Sharp generated detail on the clip's own frames — the face stays hers, expressions can shift a touch. About 5.5 min per 5 s on an M4 Max.">- <span>Faithful</span><span class="sub">sharp, face stays</span>+ <!-- Face Fix = the one-click recipe (1 refine step from the+ clip's latent, verified on character clips 2026-09-16). It+ pins upscale_start/upscale_steps; the other three pills clear+ them and keep their server-side mapping (Faithful = 3 steps). -->+ <div class="pill-group cols-4" id="upscalePresetGroup" style="margin-top:10px">+ <button type="button" class="pill-btn active" data-keep="1.0" data-start="source" data-steps="1" onclick="setUpscalePreset(this)"+ title="The clip-action recipe: one refine step from the clip's own frames — 2× sharper and the face is not redrawn. About 2.5 min per 5 s 640×384 draft on an M4 Max.">+ <span>Face Fix</span><span class="sub">face kept</span>+ </button>+ <button type="button" class="pill-btn" data-keep="1.0" onclick="setUpscalePreset(this)"+ title="Three refine steps on the clip's own frames — sharper detail, the face can be re-sculpted a little. About 5.5 min per 5 s on an M4 Max.">+ <span>Faithful</span><span class="sub">sharper</span></button><button type="button" class="pill-btn" data-keep="0.8" onclick="setUpscalePreset(this)"title="Same recipe with one step less — a touch softer, noticeably faster. About 3.75 min per 5 s on an M4 Max.">@@ -744,11 +754,13 @@</button><button type="button" class="pill-btn" data-keep="0.4" onclick="setUpscalePreset(this)"title="Full re-render at 2× from the clip as reference — the sharpest detail; faces drift from the draft. About 7 min per 5 s on an M4 Max.">- <span>Re-imagine</span><span class="sub">sharpest, faces drift</span>+ <span>Re-imagine</span><span class="sub">faces drift</span></button></div><input type="hidden" name="keep_shot" id="keep_shot" value="1.0">- <div class="hint" style="margin-top:6px">Doubles the clip's size with generated detail, not a filter — an H3 draft comes out with LTX-2.5 pixels and keeps its sound. Length and (if empty) the prompt come from the source (up to 0.3 s may be trimmed at the tail to fit LTX's frame grid). Output is capped at this Mac's Image-to-Video canvas. Times on the presets are for a 5 s 640×384 draft on an M4 Max (Faithful ≈ 5.5 min, Quick ≈ 3.75, Re-imagine ≈ 6.5); slower Macs take longer in proportion.</div>+ <input type="hidden" name="upscale_start" id="upscale_start" value="source">+ <input type="hidden" name="upscale_steps" id="upscale_steps" value="1">+ <div class="hint" style="margin-top:6px">Doubles the clip's size with generated detail, not a filter, and keeps its sound — an H3 draft comes out with LTX-2.5 pixels. The fixed clip is a new file next to the original. Length, frame count and (if empty) the prompt come from the source. Output is capped at this Mac's Image-to-Video canvas. Times are for a 5 s 640×384 draft on an M4 Max (Face Fix ≈ 2.5 min, Faithful ≈ 5.5, Quick ≈ 3.75, Re-imagine ≈ 6.5); bigger sources and slower Macs take longer. Quicker: the <b>Upscale & Face Fix</b> button under the player queues Face Fix in one click.</div></div><!-- Ingredients (multi-reference) — the flagship IC-LoRA. Pick 2-8@@ -1483,7 +1495,7 @@<div class="cz-label">Upscale<span class="cz-label-hint">after the render · no crop</span></div>- <div class="pill-group cols-4" id="h3UpscaleGroup">+ <div class="pill-group cols-3" id="h3UpscaleGroup"><button type="button" class="pill-btn" data-h3-upscale="off"title="Ship the tier's native canvas with no post-process."><span>Native</span><span class="sub">as rendered</span>@@ -1496,13 +1508,6 @@title="Scale to 1920×1080 — no crop, no distortion. A 16:9 tier scales clean; anything else is padded."><span>1080p fit</span><span class="sub">scale + pad</span></button>- <!-- "H3 mind, LTX pixels": the draft ships native and an Upscale- ×2 job (LTX-2.5 Pixel Spatial Upscaler) is queued behind it.- Not a resize — generated detail, the draft's own sound. -->- <button type="button" class="pill-btn" data-h3-upscale="ltx_x2"- title="Queue an Upscale ×2 pass (LTX-2.5 Pixel Spatial Upscaler) right after the draft: twice the size with generated detail, keeps the sound. Faithful preset — the face and lips stay as drafted.">- <span>LTX ×2</span><span class="sub">generated detail</span>- </button></div><!-- What THIS tier + THIS export target will actually do: "pure1.25× scale, no bars" or "12:7 fits to 1234×720 — 23 px bars@@ -1511,6 +1516,17 @@sentence can never disagree with the ffmpeg command thatruns. Sits UNDER the control it describes now, instead offloating between two unrelated rows. Hidden on Native. -->+ <!-- "H3 mind, LTX pixels", OPTIONAL and OFF by default: the draft+ ships native and an Upscale & Face Fix job is queued behind+ it. Stored as h3_upscale = "ltx_x2" (sidecars, Load Params+ and the API are unchanged); a checkbox because it is an+ extra job, not a size. -->+ <label class="check h3-facefix-after" id="h3FaceFixAfterRow"+ title="Queues a second job right after the draft: the draft at twice the size with LTX-2.5 detail, the face and the sound kept. The draft itself stays as rendered, next to it. Needs the 0.3 GB Upscale adapter (Settings → Models).">+ <input type="checkbox" id="h3FaceFixAfter" onchange="setH3FaceFixAfter(this.checked)">+ <span>Also run <b>Upscale & Face Fix</b> after the draft+ <span class="cz-label-hint">optional · 2× · face and sound kept · about the draft's time again</span></span>+ </label><div class="cz-note" id="h3ExportNote" hidden></div></div>@@ -3042,6 +3058,75 @@</div><div id="audioSectionTab" style="display:none">+ <div class="mode-bar pill-group cols-2" id="audioModeGroup" hidden>+ <button type="button" class="mode-chip pill-btn" data-audio-mode="compose" onclick="audioModeSet('compose')">Compose<span class="mc-sub sub">write a song</span></button>+ <button type="button" class="mode-chip pill-btn" data-audio-mode="drive" onclick="audioModeSet('drive')">Drive video<span class="mc-sub sub">use a track you have</span></button>+ </div>+ <div id="musicComposePane" hidden>+ <div class="composer-card">+ <label for="musicLyrics">Lyrics</label>+ <textarea id="musicLyrics" class="composer-prompt" rows="8" placeholder="[Verse]+Write the words here, one line at a time++[Pre-Chorus]+Build toward the chorus++[Chorus]+The words you want to come back to++[Bridge]+A different turn++[Outro]+The last line"></textarea>+ <div class="hint">Tags in square brackets mark the sections. Everything else is sung. A tag with nothing under it is an instrumental passage.</div>+ <label for="musicStyle">Style</label>+ <textarea id="musicStyle" class="composer-prompt" rows="2" placeholder="Genre, instruments, vocal, language and tempo in plain words — e.g. English, warm piano pop, expressive female voice, acoustic piano, light drums, 88 BPM"></textarea>+ <div class="hint">Prose, not fields. Put the tempo, the language and the singer in the sentence.</div>+ <div class="composer-tools">+ <label class="toggle-pill" id="musicInstrumentalPill" title="When on, the model is asked for a track with no vocal line. Your lyrics stay in the box and are not used.">+ <input type="checkbox" id="musicInstrumental" onchange="musicFormChanged()"><span class="dot"></span><span>Instrumental</span>+ </label>+ </div>+ </div>+ <div class="quick-settings">+ <div class="mf-label">Score</div>+ <div class="pill-group cols-3" id="musicModePills">+ <button type="button" class="pill-btn active" data-value="full" onclick="musicPick('musicMode',this)">Melody + chords</button>+ <button type="button" class="pill-btn" data-value="melody" onclick="musicPick('musicMode',this)">Melody only</button>+ <button type="button" class="pill-btn" data-value="off" onclick="musicPick('musicMode',this)">No score</button>+ </div>+ <input type="hidden" id="musicMode" value="full">+ <div class="hint">YuE2 writes a sheet-music plan first, then the song.</div>+ <div class="mf-label">Quality</div>+ <div class="pill-group cols-2" id="musicQualityPills">+ <button type="button" class="pill-btn" data-value="draft" onclick="musicPick('musicQuality',this)">Draft<span class="sub">8 steps</span></button>+ <button type="button" class="pill-btn active" data-value="final" onclick="musicPick('musicQuality',this)">Final<span class="sub">32 steps</span></button>+ </div>+ <input type="hidden" id="musicQuality" value="final">+ <div class="hint">Draft is several times faster for auditioning ideas.</div>+ <div class="range-strip">+ <label for="musicMaxSeconds">Max length</label>+ <input type="range" id="musicMaxSeconds" min="30" max="360" step="15" value="240" oninput="musicFormChanged()">+ <span id="musicMaxSecondsVal">4:00</span>+ </div>+ <div class="hint">YuE2 writes as long as your lyrics need. This only cuts a longer song off; it never stretches a short one.</div>+ <div class="mini-fields"><div class="mf-cell">+ <label class="mf-label" for="musicSeed">Seed</label>+ <input type="number" id="musicSeed" value="-1" min="-1" max="4294967295" step="1" placeholder="-1 = random" title="-1 = random">+ </div></div>+ </div>+ <div class="form-action-footer">+ <div class="queue-strip"><span class="qchip-spacer"></span><span class="qchip-derived" id="musicEstimate" title="Estimated for a song that runs to Max length, from M4 Max timings (a 3-minute song took about 3 minutes on Final) scaled for this chip. Most songs end sooner; the first song after install also loads the models."></span></div>+ <div class="actions">+ <button type="button" class="primary" id="musicGenBtn" onclick="musicGenerate()">Compose</button>+ <button type="button" class="danger" onclick="api('/stop', 'POST').then(poll)">Stop</button>+ </div>+ <div class="hint" id="musicStatus" role="status"></div>+ <div class="hint" id="musicHint">Generated with YuE2 by Multimodal Art Projection · MLX port by vanch007</div>+ </div>+ </div>+ <div id="audioDrivePane"><div class="composer-card"><div class="composer-refs"><div class="show">@@ -3184,6 +3269,7 @@<button type="button" class="danger" onclick="api('/stop', 'POST').then(poll)">Stop</button></div></div>+ </div></div>@@ -3225,6 +3311,9 @@every render into panel_uploads/library/manual — and until a clipcould be a STILL there was nothing a timeline could do with one. --><button type="button" class="pill-btn" data-src="images">Images</button>+ <!-- SOUND. Laugh tracks, stings, beds: this film's audio/ folder and+ every sound file in the outputs, for the audio tracks. -->+ <button type="button" class="pill-btn" data-src="sound">Sound</button></div><!-- BLACK IS NOT SOMETHING YOU PICK FROM A LIST. It has no file, so ithas no row; it is made, with a length, which is its only property. -->@@ -3403,16 +3492,28 @@</svg><span class="po-act-label">Extend</span></button>- <!-- Upscale ×2 — hands this clip to the LTX-2.5 Pixel Spatial- Upscaler lane (Remix → Upscale ×2). Video-only; the natural- next step after an H3 draft. -->- <button id="useAsUpscaleBtn" class="po-act" type="button"- onclick="useAsUpscaleSource()" title="LTX Upscale — re-render this clip at 2× with LTX-2.5 (generated detail, keeps the sound)">- <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">- <path d="M3 13 L13 3 M8 3 L13 3 L13 8 M3 8 L3 13 L8 13" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>- </svg>- <span class="po-act-label">LTX Upscale</span>- </button>+ <!-- Upscale & Face Fix — ONE CLICK queues the face-safe 2× of this+ clip (a new file lands next to it). The ⋯ half opens the full+ lane (Remix → Upscale & Face Fix) for presets and the prompt.+ Video-only; the natural next step after an H3 draft. -->+ <div class="po-split" id="faceFixWrap">+ <button id="faceFixBtn" class="po-act po-split-main" type="button"+ onclick="faceFixActive()" title="Queue Upscale & Face Fix for this clip: twice the size with LTX-2.5 detail, the face and the sound kept. The fixed clip lands next to this one — nothing is overwritten.">+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">+ <path d="M3 13 L13 3 M8 3 L13 3 L13 8 M3 8 L3 13 L8 13" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+ </svg>+ <span class="po-act-label">Upscale & Face Fix</span>+ </button>+ <button id="useAsUpscaleBtn" class="po-act po-split-more" type="button"+ onclick="useAsUpscaleSource()" aria-label="Upscale & Face Fix settings"+ title="Upscale & Face Fix settings — open this clip in Remix to pick a preset (Face Fix, Faithful, Quick, Re-imagine) or edit the prompt first.">+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">+ <path d="M3 5 H13 M3 11 H13" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>+ <circle cx="6" cy="5" r="1.6" fill="var(--panel, #111)" stroke="currentColor" stroke-width="1.3"/>+ <circle cx="10.5" cy="11" r="1.6" fill="var(--panel, #111)" stroke="currentColor" stroke-width="1.3"/>+ </svg>+ </button>+ </div><!-- Pull a good accident from the Video tab into a film. Hidden untilat least one board exists on disk — nothing about Storyboard showsup in the rest of the panel until there is a film to show it for. -->@@ -3853,6 +3954,20 @@<span class="sbe-bar" id="sbePrepBar" hidden><i style="width:0%"></i></span><span class="sbe-music-warn" id="sbeMusicWarn" hidden></span></div>+ <!-- ADD SOUND FILE… — a sound from anywhere on this Mac onto an audio+ track at the playhead, the way A2's Change… takes a path. A file+ outside the outputs is brought into the film's own audio/ folder so+ the preview can play it. -->+ <div class="sbe-pop sbe-pop-wide" id="sbeSoundMenu" hidden>+ <span class="sbe-pop-note">Add a sound file to an audio track, at the playhead.</span>+ <input type="text" class="sb-input" id="sbeSoundPath" spellcheck="false"+ placeholder="/path/to/the/sound.wav"+ onkeydown="if (event.key === 'Enter') { event.preventDefault(); sbeAddSoundFile(); }">+ <span class="sbe-pop-row">+ <button type="button" class="ghost-btn" onclick="sbeAddSoundFile()"+ title=".wav, .m4a, .mp3, .aac — or a video, for its sound only">Add sound file</button>+ </span>+ </div><!-- ONE SURFACE, NOT FOUR. Conflict, save-alarm, recovery and the@@ -4137,6 +4252,7 @@<g id="ic-delsound"><path d="M4 9v6h3l5 4V5L7 9H4z"/><path d="M15 12h6"/></g><g id="ic-points"><path d="M3 14h18"/><circle cx="8" cy="14" r="1.8"/><circle cx="15" cy="14" r="1.8"/><path d="M17 5l5 5"/><path d="M22 5l-5 5"/></g><g id="ic-lock"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></g>+ <g id="ic-facefix"><path d="M4 20L20 4"/><path d="M13 4h7v7"/><path d="M4 13v7h7"/></g><g id="ic-unlock"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 7.5-2"/></g></defs></svg><div class="sbe-cbar" id="sbeCbar">@@ -4179,6 +4295,11 @@<span class="sbe-cbar-sep"></span><button type="button" class="sbe-cbar-btn" id="sbeCbLock" onclick="sbeToggleLock()"><svg class="sbe-cbar-i"><use href="#ic-lock" id="sbeCbLockUse"/></svg><b>Lock</b></button>+ <span class="sbe-cbar-sep"></span>+ <!-- UPSCALE & FACE FIX on the selected clip: queues the face-safe 2×;+ the swap is offered on the relink line when it lands. -->+ <button type="button" class="sbe-cbar-btn" id="sbeCbFaceFix" onclick="sbeFaceFixSel()">+ <svg class="sbe-cbar-i"><use href="#ic-facefix"/></svg><b>Face Fix ×2</b></button><span class="ch-spacer" style="flex:1 1 auto"></span><!-- OVERFLOW, NOT A DRAWER. It holds nothing of its own: whatever therow cannot fit at this width moves into it, in reverse priority@@ -4256,10 +4377,30 @@<span class="sbe-gh-tag"><i>V1</i><b>Picture</b></span><span class="sbe-gh-sub" id="sbeHeadPic"></span></div>+ <!-- THE SOUND AREA'S SIZE, on the head of the area it acts on. The+ lanes do this by themselves — thin while nobody is on sound, full+ height the moment anything is — and this pins one answer when the+ owner wants one. Its glyph, its tooltip and aria-expanded are+ painted by sbePaintHeads; the keys come from the one SHORTCUTS+ table (editor.soundLanes). --><div class="sbe-gh sbe-gh-aud">- <span class="sbe-gh-tag"><i>A1</i><b>Clip sound</b></span>+ <span class="sbe-gh-tag"><i>A1</i><b>Clip sound A</b>+ <button type="button" class="sbe-gh-more sbe-asize" id="sbeAudioSize"+ onclick="sbeAudioPinToggle()" aria-expanded="true"+ title="Make the sound lanes small — A1, A2 and every audio track become thin strips so the picture gets the height. They come back the moment you touch a sound.">▾</button>+ </span><span class="sbe-gh-sub" id="sbeHeadAud"></span></div>+ <!-- CLIP SOUND LANE B. A1 is two strip lanes: a new timeline lays its+ clips' sound A, B, A… so neighbours can overlap and crossfade, and+ this head carries the one click that does the same to a timeline+ cut before there were two. -->+ <div class="sbe-gh sbe-gh-aud sbe-gh-audb">+ <span class="sbe-gh-tag"><i>A1</i><b>Clip sound B</b></span>+ <button type="button" class="ghost-btn sbe-gh-alt" id="sbeAltLanes"+ onclick="sbeAlternateSel()"+ title="Alternate sound lanes — lays every clip's sound A, B, A, B… in film order, so neighbouring shots sit on different lanes and can overlap and crossfade. Nothing moves in time; one Undo puts it back.">Alternate A/B</button>+ </div><div class="sbe-gh sbe-gh-mus"><span class="sbe-gh-tag"><i>A2</i><b>Music</b><button type="button" class="sbe-gh-more" id="sbeMusicMore"@@ -4300,6 +4441,17 @@<span class="sbe-mix-note" id="sbeBedDuckNote" hidden></span></div></div>+ <!-- A3, A4, …: THE AUDIO TRACKS' HEADS. Painted by sbePaintTracks —+ name, mute, level, remove — each as tall as its lane. -->+ <div class="sbe-trk-heads" id="sbeTrackHeads"></div>+ <div class="sbe-gh sbe-gh-add">+ <button type="button" class="ghost-btn" onclick="sbeTrackAdd()"+ title="A new, empty audio track under the others. Sounds on different tracks play together; sounds on one track play one at a time.">+ Add audio track</button>+ <button type="button" class="sbe-gh-more" id="sbeSoundMore"+ onclick="sbePopToggle('sbeSoundMenu', 'sbeSoundMore')"+ aria-haspopup="menu"+ title="Add sound file… — put a sound from anywhere on this Mac onto an audio track at the playhead">♪</button>+ </div><div class="sbe-gh sbe-gh-foot"></div></div><div class="sbe-tl" id="sbeScroll">@@ -4324,6 +4476,9 @@sound, the music. The owner's list exactly. A clip's strip sitsdirectly under its block and moves with it — until it isunlinked, which is the whole of the J-cut and the L-cut. -->+ <!-- A1 IS TWO LANES IN ONE BOX: clip sound A on top, B below. Sounds+ on one lane play one at a time; across the two they overlap and+ mix — the A/B roll a sound dissolve is made of. --><div class="sbe-alane" id="sbeAudioLane"></div><!-- The soundtrack lane. The canvas is the picture of the track andthe block over it is the OBJECT: drag it to place the music,@@ -4353,6 +4508,11 @@</div></div></div>+ <!-- A3, A4, …: THE AUDIO TRACKS, under the music, and the row that+ makes a new one when a sound is dropped on it. Any number of+ strips per track; tracks play together, a track plays one at a+ time. Painted by sbePaintTracks. -->+ <div class="sbe-tracks" id="sbeTracks"></div><div class="sbe-head-line" id="sbeHead" style="left:0"></div></div></div>@@ -4899,6 +5059,13 @@venv + ~75 GB of weights), not through the panel's `hf download` path, sothis card explains the one sidebar click — the same shape the Sharp andimage-engine optional packs already use. -->+<div id="musicInstallModal" class="models-modal" role="dialog" aria-modal="true" aria-labelledby="musicInstallTitle" hidden onclick="if(event.target===this)closeMusicInstallCard()">+ <div class="models-card">+ <div class="models-head"><h2 id="musicInstallTitle">YuE2 · music engine</h2><button type="button" onclick="closeMusicInstallCard()" aria-label="Close">×</button></div>+ <p id="musicInstallBody"></p>+ <p class="hint">YuE2 license (CC BY-NC 4.0 + creator permission): individual creators may monetize their songs; companies need a license for the weights.</p>+ </div>+</div><div id="h3InstallModal" class="models-modal" style="display:none"role="dialog" aria-modal="true" aria-labelledby="h3InstallTitle"onclick="if(event.target===this) closeH3InstallCard()">@@ -5218,4 +5385,3 @@ const BOOT = __BOOTSTRAP__;</script><div class="phos-toast-container" id="phosToast" aria-live="polite" aria-atomic="false"></div></body></html>-diff --git a/webapp/js/boot.js b/webapp/js/boot.jsindex 152bb8e..b171fc8 100644--- a/webapp/js/boot.js+++ b/webapp/js/boot.js@@ -285,15 +285,15 @@ try {// server now stamps a `kind` field, but the suffix fallback covers// outputs whose sidecar got lost (older entries) and any future caller// that forgets to set kind.-function isPhotoOutputMain(o) {- if (!o) return false;- if (o.kind === 'image') return true;- if (o.kind === 'video') return false;+function outputKind(o) {+ if (!o) return 'video';+ if (['image', 'video', 'audio'].includes(o.kind)) return o.kind;const path = (o.path || o.name || '').toLowerCase();- if (/\.(png|jpg|jpeg|webp)$/.test(path)) return true;- if (/\.mp4$/.test(path)) return false;- return false;+ if (/\.(png|jpg|jpeg|webp)$/.test(path)) return 'image';+ return /\.wav$/.test(path) ? 'audio' : 'video';}+// Compatibility for older gallery harnesses; all UI branches use outputKind.+function isPhotoOutputMain(o) { return outputKind(o) === 'image'; }// Apply the main filter on top of currentOutputs. Returns the filtered// array; callers also use this for the count badge so the filter and// the rendered cells agree.@@ -317,8 +317,8 @@ function filteredMainOutputs() {} else {all = currentOutputs;}- if (mainOutputsFilter === 'photos') all = all.filter(isPhotoOutputMain);- else if (mainOutputsFilter !== 'all') all = all.filter(o => !isPhotoOutputMain(o));+ if (mainOutputsFilter === 'photos') all = all.filter(o => outputKind(o) === 'image');+ else if (mainOutputsFilter !== 'all') all = all.filter(o => outputKind(o) === 'video');return applyOutputsQuery(all);}@@ -531,9 +531,19 @@ function updateModelCredit(path) {try {const p = path || (typeof activePath !== 'undefined' ? activePath : '');const entry = (typeof currentOutputs !== 'undefined' && currentOutputs || []).find(o => o && o.path === p);+ if (entry && entry.kind === 'audio' && entry.engine === 'music') {+ // The slot is a short chip beside the Now/Queue tabs: the full credit+ // lives in the tooltip and on the Compose form.+ el.textContent = 'YuE2 · MLX by vanch007';+ el.title = 'Generated with YuE2 by Multimodal Art Projection · MLX port by vanch007';+ el.href = 'https://github.com/vanch007/mlx-Yue';+ return;+ }if (entry && entry.model) raw = entry.model;} catch (e) {}el.textContent = _modelCreditLabel(raw || BOOT.model);+ el.title = 'MLX port by @dgrauet';+ el.href = 'https://github.com/dgrauet/ltx-2-mlx';}updateModelCredit();// `audio` is still a free-text input (advanced section); `image` is now a@@ -879,7 +889,7 @@ function _portalLoraPicker(dest) {// the global scope; everything NOT listed here is private to this module.Object.assign(globalThis, {applyTierTimes, setKeyframeMode, keyframeTimingSlots, renderKeyframeDynamicSlots,- maybeScaleTouchedKeyframeTiming, syncKeyframeTiming, isPhotoOutputMain, filteredMainOutputs,+ maybeScaleTouchedKeyframeTiming, syncKeyframeTiming, outputKind, isPhotoOutputMain, filteredMainOutputs,applyOutputsQuery, setOutputsQuery, paintOutputsCount, outputsTitleText, outputsQueryText,outputsLoadAll, _updateMainFilterChips, _maybeAutoLoadAllForEmptyFilter, setMainOutputsFilter,updateModelCredit, toggleAvoidRow, syncAvoidRowFromValue, ingredientsServed,diff --git a/webapp/js/characters.js b/webapp/js/characters.jsindex 12f75c4..ca6eed3 100644--- a/webapp/js/characters.js+++ b/webapp/js/characters.js@@ -17,7 +17,125 @@ const AUDIO_STUDIO = {wired: false, // init() runs once};+// Compose shares Audio's existing queue and poll; the server supplies every ETA.+let audioModeChoice = null;+let musicBusy = false;++function musicComposeActive() {+ return document.body.dataset.workflow === 'audio' && audioModeChoice === 'compose'+ && !!window._ENGINE_PROBES.music.available;+}+function musicInit() {+ try { audioModeChoice = localStorage.getItem('phos_audio_mode'); } catch (_) {}+ if (!['compose', 'drive'].includes(audioModeChoice)) audioModeChoice = null;+ updateMusicAvailability({ music: BOOT.music });+}+function updateMusicAvailability(s) {+ if (s && s.music) window._ENGINE_PROBES.music = s.music;+ const ready = !!window._ENGINE_PROBES.music.available;+ if (audioModeChoice == null && ready) audioModeChoice = 'compose';+ const compose = ready && audioModeChoice === 'compose';+ document.getElementById('audioModeGroup').hidden = !ready;+ document.getElementById('musicComposePane').hidden = !compose;+ document.getElementById('audioDrivePane').hidden = compose;+ document.querySelectorAll('#audioModeGroup [data-audio-mode]').forEach(b => {+ const active = b.dataset.audioMode === (compose ? 'compose' : 'drive');+ b.classList.toggle('active', active);+ b.setAttribute('aria-pressed', String(active));+ });+ musicFormChanged();+ if (document.body.dataset.workflow === 'audio') renderEngineSwitch();+}+function audioModeSet(mode) {+ audioModeChoice = mode === 'compose' ? 'compose' : 'drive';+ try { localStorage.setItem('phos_audio_mode', audioModeChoice); } catch (_) {}+ updateMusicAvailability();+ // Music stays in the existing stream even if the last Video visit filtered it.+ if (audioModeChoice === 'compose') setMainOutputsFilter('all');+}+function musicPick(id, button) {+ document.getElementById(id).value = button.dataset.value;+ button.parentElement.querySelectorAll('.pill-btn').forEach(b => {+ b.classList.toggle('active', b === button);+ b.setAttribute('aria-pressed', String(b === button));+ });+ musicFormChanged();+}+function musicFormChanged() {+ const instrumental = document.getElementById('musicInstrumental').checked;+ document.getElementById('musicLyrics').disabled = instrumental;+ document.getElementById('musicInstrumentalPill').classList.toggle('on', instrumental);+ const seconds = Number(document.getElementById('musicMaxSeconds').value);+ document.getElementById('musicMaxSecondsVal').textContent = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;+ const quality = document.getElementById('musicQuality').value;+ const music = window._ENGINE_PROBES.music;+ const estimate = ((music.estimates || {})[quality] || {})[String(seconds)];+ document.getElementById('musicEstimate').textContent = estimate+ ? `≈ ${estimate.eta} at full length · estimate` : '';+ document.getElementById('musicGenBtn').disabled = musicBusy || !music.available || !music.capable;+}+function musicFormParams() {+ const instrumental = document.getElementById('musicInstrumental').checked;+ return new URLSearchParams({+ mode: 'music', engine: 'music',+ music_lyrics: instrumental ? '' : document.getElementById('musicLyrics').value,+ music_style: document.getElementById('musicStyle').value,+ music_mode: document.getElementById('musicMode').value,+ music_instrumental: instrumental ? 'on' : 'off',+ music_max_seconds: document.getElementById('musicMaxSeconds').value,+ music_seed: document.getElementById('musicSeed').value,+ music_quality: document.getElementById('musicQuality').value,+ });+}+async function musicGenerate() {+ if (musicBusy) return;+ const fd = musicFormParams();+ const status = document.getElementById('musicStatus');+ if (!fd.get('music_style').trim() && !fd.get('music_lyrics').trim() && fd.get('music_instrumental') !== 'on') {+ status.textContent = 'Give it something to work with — lyrics, a style description, or both.';+ return;+ }+ musicBusy = true;+ musicFormChanged();+ status.textContent = 'Queueing…';+ try {+ const r = await fetch('/queue/add', { method: 'POST', body: fd });+ const result = await r.json();+ if (!r.ok || result.error) throw new Error(result.error || 'Could not queue music');+ status.textContent = 'Song queued.';+ setMainOutputsFilter('all');+ await poll();+ } catch (e) {+ status.textContent = e.message || String(e);+ } finally {+ musicBusy = false;+ musicFormChanged();+ }+}+function useTrackInA2V(path) {+ const output = findOutputByPath(path);+ AUDIO_STUDIO.audioPath = path;+ AUDIO_STUDIO.audioName = path.split('/').pop();+ AUDIO_STUDIO.audioDuration = output ? output.clip_sec : null;+ audioModeSet('drive');+ workflowSwitch('audio');+ audioStudioRenderSlots();+ phosToast('Track loaded — add a prompt and generate.');+}+function openMusicInstallCard() {+ const music = window._ENGINE_PROBES.music;+ const body = document.getElementById('musicInstallBody');+ body.textContent = music.repairable+ ? 'The YuE2 weights are on disk but the engine needs repair. Click “Repair the music engine (weights kept — no re-download)” in the Phosphene sidebar in Pinokio. It skips every intact weight.'+ : `Click “Install the music engine (YuE2, ~11 GB)” in the Phosphene sidebar in Pinokio. Needs ${music.min_ram_gb} GB unified memory. The download resumes if interrupted. Compose appears in Audio when it is ready.`;+ document.getElementById('musicInstallModal').hidden = false;+}+function closeMusicInstallCard() {+ document.getElementById('musicInstallModal').hidden = true;+}+function audioStudioInit() {+ if (musicComposeActive()) setMainOutputsFilter('all');if (AUDIO_STUDIO.wired) return;AUDIO_STUDIO.wired = true;const audioSlot = document.getElementById('audioStudioAudioSlot');@@ -2703,7 +2821,7 @@ function updateCustomizeSummary() {// actually folded away on H3 is the export target, so that is what it says.if (up === 'fit_720p') parts.push('720p export');else if (up === 'fit_1080p') parts.push('1080p export');- else if (up === 'ltx_x2') parts.push('LTX ×2 after');+ else if (up === 'ltx_x2') parts.push('native export + Upscale & Face Fix after');else parts.push('native export');el.textContent = parts.join(' · ');return;@@ -2859,6 +2977,8 @@ document.querySelectorAll('#extendModeGroup .pill-btn').forEach(b => b.onclick =// Inline handlers in the markup and the other files resolve these through// the global scope; everything NOT listed here is private to this module.Object.assign(globalThis, {+ musicComposeActive, musicInit, updateMusicAvailability, audioModeSet, musicPick, musicFormChanged,+ musicFormParams, musicGenerate, useTrackInA2V, openMusicInstallCard, closeMusicInstallCard,windowPromptsInput,audioStudioInit, audioStudioDurationChanged, audioStudioEnhancePrompt, audioStudioGenerate,trainRecommendedPreset, trainUpdatePresetButtons, trainUpdatePresetNote, downloadSampleCharacter,diff --git a/webapp/js/editor.js b/webapp/js/editor.jsindex f31c9a3..61baef7 100644--- a/webapp/js/editor.js+++ b/webapp/js/editor.js@@ -70,7 +70,16 @@ const SBE_TL_CHROME = 32; // 18 ruler + 12 scrollbar gutter + 2 borderconst SBE_LANES = [{ key: 'ov', base: 32, cap: 56, share: 0.08 }, // overlay: a card is placed, not performed{ key: 'track', base: 64, cap: 120, share: 0.14 }, // the picture: a labelled block, not a poster- { key: 'alane', base: 44, cap: 190, share: 0.44 }, // per-clip sound: waveform, level line, points+ // THE SOUND LANES CARRY A SECOND HEIGHT — `small`. The owner cuts with clip+ // sound on two lanes and four audio tracks, and every one of them is paid+ // for out of the PICTURE: "the sound expands lower. The picture is so tiny…+ // I cannot see anything in the image, and I can also not push it down."+ // `small` is what a sound lane is worth when nobody is working on sound: a+ // strip tall enough to show WHERE the sound sits and what colour it is, and+ // deliberately too short to edit in — which is the point, because the moment+ // you touch one they come back. `audio: true` is what makes a lane part of+ // that area; A3, A4, … are drawn at `alane`'s height, so they follow it.+ { key: 'alane', base: 44, cap: 190, share: 0.44, audio: true, small: 18 },// The soundtrack. Its base rose 72 -> 108 when the bed stopped being a// rectangle you can only slide: it now carries a waveform, a level line,// draggable points and two corner fade handles, exactly like the strip lane@@ -78,7 +87,7 @@ const SBE_LANES = [// is that a control has to be legible AT REST and not only after somebody// has discovered it. The HEAD grew with it (the level and the duck now live// there), and head and lane read the same variable on purpose.- { key: 'wave', base: 108, cap: 240, share: 0.34 }, // the soundtrack+ { key: 'wave', base: 108, cap: 240, share: 0.34, audio: true, small: 20 },];// Both ends are the SUM of the parts, never a hand-picked round number — the// floor is every lane at its base (which is what the box needs to draw itself@@ -88,8 +97,37 @@ const SBE_LANES = [// a comment and the overlay lane was added without moving it: the box has// been 30px short of its own contents, with `overflow-y: hidden` over the// difference, since that lane shipped.-globalThis.SBE_TL_MIN_H = 280;-globalThis.SBE_TL_MAX_H = 638;+// ...and both ends MOVE WITH THE SOUND AREA. A constant floor is exactly what+// stopped the owner compacting his timeline — "I can also not push it down if+// I want to compact it" — because 280 was the sum of the lanes at their FULL+// height and the handle could never ask for less than every lane's base. With+// the sound lanes small the box's own contents are 114px shorter, so that is+// how much further down the handle goes, and sbeFitMonitors hands every one of+// those pixels (plus the second clip lane's and every track's) to the monitors.+function sbeLaneBase(L, small) { return (small && L.audio) ? L.small : L.base; }+function sbeLaneCap(L, small) { return (small && L.audio) ? L.small : L.cap; }+// `small` defaults to WHAT IS ON SCREEN, so every caller that does not pass it+// keeps meaning "the floor of the timeline as it is drawn right now".+function sbeTlFloor(small) {+ const s = (small === undefined) ? sbeAudioSmall() : !!small;+ let n = SBE_TL_CHROME;+ for (const L of SBE_LANES) n += sbeLaneBase(L, s);+ return n;+}+function sbeTlRoof(small) {+ const s = (small === undefined) ? sbeAudioSmall() : !!small;+ let n = SBE_TL_CHROME;+ for (const L of SBE_LANES) n += sbeLaneCap(L, s);+ return n;+}+// The two ends with the sound at full height: the CSS fallback, the timeline's+// remembered preference and the layout gate all stand on these.+globalThis.SBE_TL_MIN_H = sbeTlFloor(false);+globalThis.SBE_TL_MAX_H = sbeTlRoof(false);+// How long the sound lanes wait, with nothing happening on sound, before they+// make themselves small. Long enough that clicking off a strip to look at the+// picture is not a flicker; short enough that it reads as the app noticing.+const SBE_ASMALL_IDLE = 2400;// How far one arrow key moves the edge, and one arrow key with Shift.const SBE_TL_STEP = 12;const SBE_TL_STEP_BIG = 40;@@ -210,7 +248,7 @@ window.SBE = {// used to exist (`superseded`) was set by a passive page load in another// browser and switched this tab's safety net off for seven hours.otherEditor: '', protectedAt: 0,- timer: null, saveTimer: null, raf: 0, drag: null, awaitingClip: 0,+ timer: null, saveTimer: null, raf: 0, drag: null, awaitingClip: 0, fixHandled: {}, fixBusy: false,// The soundtrack's own drag. Separate from `drag` because the two lanes are// separate objects and a pointer is only ever on one of them.musicDrag: null, audioDrag: null,@@ -242,6 +280,21 @@ window.SBE = {// whenever the pointer is not near a line it could edit. It is the whole of// "hover teaches": the control answers before it is used.kfGhost: null,+ // THE AUDIO TRACKS (A3, A4, …). `tracks` is `edit.audio_tracks` as the+ // timeline holds it; `tsSet` the selected strips (the primary is+ // `sel === '@ts:<id>'`); `tsDrag` a gesture on a track lane; `tsDrop` where+ // a pool drag would land on one. `selLane` is the clip whose SOUND strip on+ // A1 was clicked, which is what lets Duplicate copy the sound rather than+ // the shot. `tgSliding` holds the heads still while a level slider moves.+ tracks: [], tsSet: [], tsDrag: null, tsDrop: null, selLane: '',+ tgBefore: null, tgSliding: false, tsGainBefore: null,+ // THE SOUND AREA'S SIZE. `aPin` is this browser's own answer ('auto' — thin+ // until you touch sound — or 'open' / 'small' pinned); `aSmall` is what is on+ // screen; `aTouch` when sound was last worked on; `aHover` whether the pointer+ // is on a lane or a head; `aTimer` the idle that makes them small and `aAnim`+ // the brief transition. See sbeAudioPinRead.+ aPin: sbeAudioPinRead(), aSmall: false, aTouch: 0, aHover: false,+ aTimer: null, aAnim: null,};const SBE_MIN_CLIP = 0.2; // shorter than this is not a shot, it is a blink@@ -752,6 +805,92 @@ function sbeSetClipMute(clips, id, on) {return { clips: out, ok: true };}+// ---- THE TWO CLIP-SOUND LANES (A/B) ---------------------------------------+// THE MIRROR OF `clip_sound_lane()`. The owner, 2026-09-15: "the sound between+// clips should already be intercalated into two different lanes … if I want to+// blend and dissolve from both sides, cut a little, and bring the clips+// together to make it more realistic, it's easy." Lane A is the absence of the+// field, so every clip on every disk is already on A; only lane B is written.+// Sounds on ONE lane never overlap (the render trims the outgoing tail); sounds+// on the two lanes overlap and mix, which is the crossfade.+function sbeSoundLane(c) {+ return (c && c.sound_lane === 2 && sbeKind(c) === 'video') ? 2 : 1;+}++function sbeLaneName(lane) { return lane === 2 ? 'B' : 'A'; }++// One clip's sound onto one lane. Nothing moves in time.+function sbeSetSoundLane(clips, id, lane) {+ const c = sbeById(clips, id);+ if (!c) return { clips: clips, ok: false, why: 'gone' };+ if (sbeKind(c) !== 'video') {+ return { clips: clips, ok: false, why: 'only a video clip has sound of its own' };+ }+ if (c.locked) return { clips: clips, ok: false, why: 'locked' };+ const want = (sbeNum(lane) === 2) ? 2 : 1;+ if (sbeSoundLane(c) === want) return { clips: clips, ok: false, why: '' };+ const out = clips.map(x => Object.assign({}, x));+ const t = sbeById(out, id);+ if (want === 2) t.sound_lane = 2; else delete t.sound_lane;+ t.source = 'human';+ return { clips: out, ok: true, lane: want };+}++// "ALTERNATE SOUND LANES": A, B, A, B… in film order, for a timeline that was+// cut before there were two. The mirror of `alternate_sound_lanes()` — only the+// lane changes, so every sound plays at exactly the second it did. Stills and+// black take no turn: alternation is between the sounds that meet.+function sbeAlternateLanes(clips) {+ const out = (clips || []).map(x => Object.assign({}, x));+ const vids = out.filter(x => sbeKind(x) === 'video')+ .sort((a, b) => (sbeNum(a.film_start) - sbeNum(b.film_start))+ || String(a.id).localeCompare(String(b.id)));+ let changed = 0;+ vids.forEach((c, k) => {+ const want = (k % 2 === 0) ? 1 : 2;+ if (sbeSoundLane(c) !== want) {+ changed++;+ c.source = 'human';+ }+ if (want === 2) c.sound_lane = 2; else delete c.sound_lane;+ });+ if (!changed) {+ return { clips: clips, ok: false, changed: 0,+ why: vids.length ? 'The clip sound already alternates A, B, A… — nothing to change.'+ : 'There is no clip sound on this __SEQ__ to lay out.' };+ }+ return { clips: out, ok: true, changed: changed };+}++// The lane a clip arriving at `filmStart` takes: the one the previous video+// clip is NOT on (with nothing before it, the one the next is not on). The+// mirror of `sound_lane_after()`.+function sbeLaneAfter(clips, filmStart) {+ const fs = sbeNum(filmStart);+ const vids = (clips || []).filter(x => x && sbeKind(x) === 'video')+ .sort((a, b) => sbeNum(a.film_start) - sbeNum(b.film_start));+ let prev = null, next = null;+ for (const v of vids) {+ if (sbeNum(v.film_start) < fs - 1e-9) prev = v;+ else if (!next) next = v;+ }+ if (prev) return sbeSoundLane(prev) === 1 ? 2 : 1;+ if (next) return sbeSoundLane(next) === 1 ? 2 : 1;+ return 1;+}++// A NEW CLIP KEEPS THE ALTERNATION. Called by every path that puts a shot on+// the track (insert, fill a hole, Duplicate) once the film is laid out.+function sbeLaneFit(clips, c) {+ if (!c) return clips;+ delete c.sound_lane;+ if (sbeKind(c) !== 'video') return clips;+ if (sbeLaneAfter((clips || []).filter(x => x !== c), sbeNum(c.film_start)) === 2) {+ c.sound_lane = 2;+ }+ return clips;+}+function sbeAudioIsThePicture(c) {const w = sbeClipAudio(c);if (!w.split) return true;@@ -1443,6 +1582,649 @@ function sbeSetAudioFade(clips, id, edge, seconds) {return { clips: out, ok: true };}+// ---------------------------------------------------------------------------+// THE AUDIO TRACKS — A3, A4, … under the music+// ---------------------------------------------------------------------------+// "You actually need to have multiple audio clips, like we have multiple video+// layers... you stack them on top of each other." The client half of+// `storyboard_editor.audio_tracks`: a list of tracks, each a list of strips,+// and every function here is a mirror of the server's model or a pure edit of+// it — tracks in, a NEW list out, never a mutation — so a drag can be tested+// in node and re-derived from its starting state on every pointer event.+//+// ONE RULE PER LANE, the NLE's: strips on the same track never overlap, strips+// on different tracks overlap and mix. Every edit below lands a strip on the+// nearest LEGAL second rather than refusing, because a drag that stops dead at+// a neighbour is how every timeline answers "there is something there".+//+// THE ENVELOPE IS THE SAME OBJECT a clip's sound and the bed carry (`afx`), read+// by the same `sbeAfx` / `sbeGainPoints`, drawn by the same `sbeStripWave`.+const SBE_TRACK_STRIP_MIN = 0.05; // mirrors TRACK_STRIP_MIN+const SBE_SOUND_EXT = /\.(wav|m4a|mp3|aac|flac|aiff?|ogg|opus)$/i;+// The row under the last track — "+ Add audio track" in the gutter, a drop+// zone in the lanes. Its height rides on top of the timeline's own, see+// sbeApplyTl, so adding a track never squeezes the lanes that were there.+const SBE_TADD_H = 26;++function sbeTrackLabel(i) { return 'A' + (Math.round(sbeNum(i)) + 3); }++// A fader: 1 when absent, clamped 0..1 — the mirror of `_unit_gain`.+function sbeUnitGain(v) {+ if (v === null || v === undefined || typeof v === 'boolean') return 1;+ const g = Number(v);+ if (!(g === g) || !isFinite(g)) return 1;+ return sbeRound(Math.max(0, Math.min(1, g)));+}+function sbeTrackGain(t) { return sbeUnitGain((t || {}).gain); }+function sbeTsGain(s) { return sbeUnitGain((s || {}).gain); }++// `{start, end, film_start, film_end, len}` — the mirror of `strip_window`.+function sbeTsWindow(s) {+ const st = sbeNum((s || {}).start), en = sbeNum((s || {}).end);+ const fs = sbeNum((s || {}).film_start);+ const n = Math.max(0, en - st);+ return { start: sbeRound(st), end: sbeRound(en), film_start: sbeRound(fs),+ film_end: sbeRound(fs + n), len: sbeRound(n) };+}++// THE ONE STRIP CURVE — the mirror of `track_strip_gain_points`: the envelope,+// times the strip's fader, times the track's. Empty is unity.+function sbeTsGainPoints(track, s) {+ const n = sbeTsWindow(s).len;+ if (n <= 0) return [];+ const g0 = sbeRound(sbeTsGain(s) * sbeTrackGain(track));+ const curve = sbeGainPoints(s || {}, n);+ if (!curve.length) {+ if (Math.abs(g0 - 1) < 1e-9) return [];+ return [[0, g0], [sbeRound(n), g0]];+ }+ return curve.map(p => [p[0], sbeRound(Math.max(0, Math.min(1, p[1] * g0)))]);+}++function sbeTsGainAt(track, s, t) {+ const c = sbeTsGainPoints(track, s);+ return c.length ? sbeRound(sbeLerpGain(c, Math.max(0, sbeNum(t)))) : 1;+}++function sbeTsCopy(tracks) { return JSON.parse(JSON.stringify(tracks || [])); }++function sbeTsTrackById(tracks, tid) {+ return (tracks || []).find(t => String(t.id) === String(tid)) || null;+}++function sbeTsFind(tracks, sid) {+ const want = String(sid || '');+ const list = tracks || [];+ for (let ti = 0; ti < list.length; ti++) {+ const ss = (list[ti] && list[ti].strips) || [];+ for (let si = 0; si < ss.length; si++) {+ if (String(ss[si].id) === want) return { track: list[ti], strip: ss[si], ti: ti, si: si };+ }+ }+ return null;+}++function sbeTsSort(track) {+ track.strips = (track.strips || []).slice()+ .sort((a, b) => sbeNum(a.film_start) - sbeNum(b.film_start));+}++// Is [fs, fs + len) free on this track? `skip` is a strip id, or a list of+// them — the strips being moved do not collide with where they were. The+// tolerance is the server's TOUCH_TOLERANCE, so a butt join is never an overlap.+function sbeTsFits(track, fs, len, skip) {+ const a0 = sbeNum(fs), a1 = a0 + Math.max(0, sbeNum(len));+ if (a0 < -1e-9) return false;+ const except = Array.isArray(skip) ? skip.map(String)+ : ((skip === undefined || skip === null) ? [] : [String(skip)]);+ for (const s of ((track || {}).strips || [])) {+ if (except.indexOf(String(s.id)) >= 0) continue;+ const w = sbeTsWindow(s);+ if (a0 < w.film_end - SBE_SYNC_TOL && w.film_start < a1 - SBE_SYNC_TOL) return false;+ }+ return true;+}++// The legal second nearest `want`: where it was asked for when that is free,+// else butted against whichever neighbour is closer. The tail of the last+// strip is always free, so there is always an answer.+function sbeTsNearest(track, want, len, skip) {+ const w0 = Math.max(0, sbeNum(want));+ const n = Math.max(0, sbeNum(len));+ const except = Array.isArray(skip) ? skip.map(String)+ : ((skip === undefined || skip === null) ? [] : [String(skip)]);+ const cands = [w0, 0];+ for (const s of ((track || {}).strips || [])) {+ if (except.indexOf(String(s.id)) >= 0) continue;+ const w = sbeTsWindow(s);+ cands.push(w.film_end, w.film_start - n);+ }+ let best = null;+ for (const c of cands) {+ if (c < -1e-9 || !sbeTsFits(track, c, n, skip)) continue;+ if (best === null || Math.abs(c - w0) < Math.abs(best - w0) - 1e-9) best = c;+ }+ return best === null ? null : sbeRound(Math.max(0, best));+}++// The first free second at or after `from` — where a duplicate goes when the+// spot right after its original is taken.+function sbeTsNextFree(track, from, len, skip) {+ const f0 = Math.max(0, sbeNum(from));+ const cands = [f0];+ for (const s of ((track || {}).strips || [])) {+ const e = sbeTsWindow(s).film_end;+ if (e >= f0 - 1e-9) cands.push(e);+ }+ cands.sort((a, b) => a - b);+ for (const c of cands) if (sbeTsFits(track, c, len, skip)) return sbeRound(c);+ return null;+}++function sbeTsNewTrack(tracks, name) {+ const out = sbeTsCopy(tracks);+ const t = { id: 't' + sbeNewId().slice(1), strips: [] };+ if (name) t.name = String(name).slice(0, 60);+ out.push(t);+ return { tracks: out, ok: true, added: t };+}++function sbeTsRemoveTrack(tracks, tid) {+ const t = sbeTsTrackById(tracks, tid);+ if (!t) return { tracks: tracks, ok: false, why: 'gone' };+ if ((t.strips || []).some(s => s.locked === true)) {+ return { tracks: tracks, ok: false,+ why: 'a sound on this track is locked — unlock it before removing the track' };+ }+ return { tracks: sbeTsCopy(tracks).filter(x => String(x.id) !== String(tid)),+ ok: true, removed: t };+}++// Mute, level and name of one TRACK. Neutral is absent, as on the server.+function sbeTsSetTrack(tracks, tid, patch) {+ const out = sbeTsCopy(tracks);+ const t = sbeTsTrackById(out, tid);+ if (!t) return { tracks: tracks, ok: false, why: 'gone' };+ const p = patch || {};+ if ('muted' in p) { if (p.muted) t.muted = true; else delete t.muted; }+ if ('gain' in p) {+ const g = sbeUnitGain(p.gain);+ if (Math.abs(g - 1) > 1e-9) t.gain = g; else delete t.gain;+ }+ if ('name' in p) {+ const nm = String(p.name || '').trim().slice(0, 60);+ if (nm) t.name = nm; else delete t.name;+ }+ return { tracks: out, ok: true };+}++// A NEW strip onto a track. `tid` '' means the first track with room at+// `want`, 'new' means a track of its own — and when no track has room, one is+// made: a sound from the pool or a copy is never refused for want of a lane.+function sbeTsPlace(tracks, tid, strip, want) {+ let out = sbeTsCopy(tracks);+ const s = JSON.parse(JSON.stringify(strip || {}));+ const len = sbeTsWindow(s).len;+ if (len < SBE_TRACK_STRIP_MIN) {+ return { tracks: tracks, ok: false, why: 'that sound is too short to place' };+ }+ const at = Math.max(0, sbeNum(want));+ let t = null;+ if (tid && tid !== 'new') {+ t = sbeTsTrackById(out, tid);+ if (!t) return { tracks: tracks, ok: false, why: 'gone' };+ s.film_start = sbeTsNearest(t, at, len);+ } else if (tid !== 'new') {+ t = out.find(x => sbeTsFits(x, at, len)) || null;+ if (t) s.film_start = sbeRound(at);+ }+ if (!t) {+ out = sbeTsNewTrack(out).tracks;+ t = out[out.length - 1];+ s.film_start = sbeRound(at);+ }+ if (!s.id) s.id = sbeNewId();+ t.strips = (t.strips || []).concat([s]);+ sbeTsSort(t);+ return { tracks: out, ok: true, added: s, track: String(t.id) };+}++// Drag: onto `toTid` (or its own track), landing on the legal second nearest+// `want`.+function sbeTsMove(tracks, sid, toTid, want) {+ const f = sbeTsFind(tracks, sid);+ if (!f) return { tracks: tracks, ok: false, why: 'gone' };+ if (f.strip.locked === true) return { tracks: tracks, ok: false, why: 'locked' };+ const out = sbeTsCopy(tracks);+ const g = sbeTsFind(out, sid);+ const len = sbeTsWindow(g.strip).len;+ let dest = g.track;+ if (toTid && String(toTid) !== String(g.track.id)) {+ dest = sbeTsTrackById(out, toTid);+ if (!dest) return { tracks: tracks, ok: false, why: 'gone' };+ }+ const spot = sbeTsNearest(dest, want, len, sid);+ if (spot === null) return { tracks: tracks, ok: false, why: 'there is no room there' };+ g.track.strips.splice(g.si, 1);+ g.strip.film_start = spot;+ dest.strips.push(g.strip);+ sbeTsSort(dest);+ return { tracks: out, ok: true, track: String(dest.id), at: spot };+}++// Several strips by one delta, each on its own track. All or nothing: if any+// would land on a neighbour the whole slide is refused, and the drag keeps the+// last position that was legal.+function sbeTsMoveGroup(tracks, ids, delta) {+ const list = (ids || []).map(String);+ const out = sbeTsCopy(tracks);+ let d = sbeNum(delta);+ const found = [];+ for (const id of list) {+ const g = sbeTsFind(out, id);+ if (!g) return { tracks: tracks, ok: false, why: 'gone' };+ if (g.strip.locked === true) return { tracks: tracks, ok: false, why: 'locked' };+ found.push(g);+ d = Math.max(d, -sbeNum(g.strip.film_start));+ }+ for (const g of found) g.strip.film_start = sbeRound(sbeNum(g.strip.film_start) + d);+ for (const g of found) {+ const w = sbeTsWindow(g.strip);+ if (!sbeTsFits(g.track, w.film_start, w.len, list)) {+ return { tracks: tracks, ok: false, why: 'there is no room there' };+ }+ }+ for (const t of out) sbeTsSort(t);+ return { tracks: out, ok: true, moved: sbeRound(d) };+}++// Trim one edge. `edge` is 'trimL' (a new in-point: the rest stays where it+// is) or 'trimR' (a new out-point). Bounded by the file's own ends and by the+// neighbours on the same track — a trim never reaches under another strip.+function sbeTsTrim(tracks, sid, edge, want) {+ const f = sbeTsFind(tracks, sid);+ if (!f) return { tracks: tracks, ok: false, why: 'gone' };+ if (f.strip.locked === true) return { tracks: tracks, ok: false, why: 'locked' };+ const out = sbeTsCopy(tracks);+ const g = sbeTsFind(out, sid);+ const w = sbeTsWindow(g.strip);+ const others = g.track.strips.filter(x => x !== g.strip).map(sbeTsWindow);+ if (edge === 'trimL') {+ let lo = Math.max(0, w.film_start - w.start);+ for (const o of others) if (o.film_end <= w.film_start + 1e-6) lo = Math.max(lo, o.film_end);+ const hi = w.film_end - SBE_TRACK_STRIP_MIN;+ const fs = Math.max(lo, Math.min(hi, sbeNum(want)));+ g.strip.start = sbeRound(Math.max(0, w.start + (fs - w.film_start)));+ g.strip.film_start = sbeRound(fs);+ } else {+ let hi = Infinity;+ const dur = sbeNum(g.strip.duration, 0);+ if (dur > 0) hi = w.film_start + (dur - w.start);+ for (const o of others) if (o.film_start >= w.film_end - 1e-6) hi = Math.min(hi, o.film_start);+ const lo = w.film_start + SBE_TRACK_STRIP_MIN;+ const fe = Math.max(lo, Math.min(hi, sbeNum(want)));+ g.strip.end = sbeRound(w.start + (fe - w.film_start));+ }+ return { tracks: out, ok: true };+}++// Split at film second `t`. The outer fades stay on the outer ends, and the+// level points are divided at the cut with a point on each side of it, so the+// two halves play exactly the curve the whole strip did.+function sbeTsSplit(tracks, sid, t, newId) {+ const f = sbeTsFind(tracks, sid);+ if (!f) return { tracks: tracks, ok: false, why: 'gone' };+ if (f.strip.locked === true) return { tracks: tracks, ok: false, why: 'locked' };+ const w = sbeTsWindow(f.strip);+ const off = sbeNum(t) - w.film_start;+ if (off < SBE_TRACK_STRIP_MIN || w.len - off < SBE_TRACK_STRIP_MIN) {+ return { tracks: tracks, ok: false,+ why: 'the playhead is not inside that sound, or is right on its edge' };+ }+ const out = sbeTsCopy(tracks);+ const g = sbeTsFind(out, sid);+ const a = g.strip;+ const b = JSON.parse(JSON.stringify(a));+ b.id = newId || sbeNewId();+ const e = sbeAfx(a, w.len);+ const mid = sbeLerpGain(e.points, off);+ const pa = e.points.filter(p => p[0] < off - 1e-6);+ const pb = e.points.filter(p => p[0] > off + 1e-6).map(p => [sbeRound(p[0] - off), p[1]]);+ if (e.points.length) { pa.push([sbeRound(off), sbeRound(mid)]); pb.unshift([0, sbeRound(mid)]); }+ a.end = sbeRound(w.start + off);+ b.start = a.end;+ b.film_start = sbeRound(w.film_start + off);+ const afxA = {}, afxB = {};+ if (e.fade_in > 1e-9) afxA.fade_in = sbeRound(Math.min(e.fade_in, off));+ if (e.fade_out > 1e-9) afxB.fade_out = sbeRound(Math.min(e.fade_out, w.len - off));+ if (pa.length) afxA.points = pa;+ if (pb.length) afxB.points = pb;+ if (Object.keys(afxA).length) a.afx = afxA; else delete a.afx;+ if (Object.keys(afxB).length) b.afx = afxB; else delete b.afx;+ g.track.strips.splice(g.si + 1, 0, b);+ return { tracks: out, ok: true, added: b };+}++function sbeTsCopyTitle(s, fallback) {+ const base = String((s || {}).title || String((s || {}).path || '').split('/').pop()+ || fallback || 'sound').replace(/ \(copy( \d+)?\)$/, '');+ return base + ' (copy)';+}++// DUPLICATE: the same sound again, right after itself on the same track — or+// at the next free spot on it. Window, level, fades and points included.+function sbeTsDuplicate(tracks, sid) {+ const f = sbeTsFind(tracks, sid);+ if (!f) return { tracks: tracks, ok: false, why: 'gone' };+ const out = sbeTsCopy(tracks);+ const g = sbeTsFind(out, sid);+ const w = sbeTsWindow(g.strip);+ const b = JSON.parse(JSON.stringify(g.strip));+ b.id = sbeNewId();+ delete b.locked;+ b.title = sbeTsCopyTitle(g.strip);+ b.film_start = sbeTsNextFree(g.track, w.film_end, w.len);+ g.track.strips.push(b);+ sbeTsSort(g.track);+ return { tracks: out, ok: true, added: b, track: String(g.track.id) };+}++// LIFT takes the strip off and leaves the silence. RIPPLE closes the gap on+// THAT track only: the picture and every other track stay where they are.+function sbeTsDelete(tracks, sid, ripple) {+ const f = sbeTsFind(tracks, sid);+ if (!f) return { tracks: tracks, ok: false, why: 'gone' };+ if (f.strip.locked === true) return { tracks: tracks, ok: false, why: 'locked' };+ const out = sbeTsCopy(tracks);+ const g = sbeTsFind(out, sid);+ const w = sbeTsWindow(g.strip);+ g.track.strips.splice(g.si, 1);+ if (ripple) {+ for (const s of g.track.strips) {+ const sw = sbeTsWindow(s);+ if (sw.film_start < w.film_end - 1e-6) continue;+ if (s.locked === true) {+ return { tracks: tracks, ok: false,+ why: 'a locked sound after it on the same track cannot slide — unlock it, or use Lift' };+ }+ s.film_start = sbeRound(Math.max(0, sw.film_start - w.len));+ }+ }+ return { tracks: out, ok: true, removed: g.strip };+}++// The strip's own switches and fader, and its envelope. Neutral is absent.+function sbeTsSetStrip(tracks, sid, patch) {+ const f = sbeTsFind(tracks, sid);+ if (!f) return { tracks: tracks, ok: false, why: 'gone' };+ const p = patch || {};+ if (f.strip.locked === true && !('locked' in p) && !('muted' in p)) {+ return { tracks: tracks, ok: false, why: 'locked' };+ }+ const out = sbeTsCopy(tracks);+ const s = sbeTsFind(out, sid).strip;+ if ('muted' in p) { if (p.muted) s.muted = true; else delete s.muted; }+ if ('locked' in p) { if (p.locked) s.locked = true; else delete s.locked; }+ if ('gain' in p) {+ const g = sbeUnitGain(p.gain);+ if (Math.abs(g - 1) > 1e-9) s.gain = g; else delete s.gain;+ }+ if ('afx' in p) {+ const a = p.afx || {};+ const has = a.fade_in > 1e-9 || a.fade_out > 1e-9 || (a.points && a.points.length);+ if (has) s.afx = a; else delete s.afx;+ }+ return { tracks: out, ok: true };+}++function sbeTsSetFade(tracks, sid, edge, seconds) {+ const f = sbeTsFind(tracks, sid);+ if (!f) return { tracks: tracks, ok: false, why: 'gone' };+ const n = sbeTsWindow(f.strip).len;+ const key = (edge === 'out') ? 'fade_out' : 'fade_in';+ const afx = Object.assign({}, f.strip.afx || {});+ const want = Math.max(0, Math.min(n, sbeNum(seconds)));+ if (want > 1e-9) afx[key] = sbeRound(want); else delete afx[key];+ return sbeTsSetStrip(tracks, sid, { afx: afx });+}++function sbeTsPointsWrite(tracks, sid, pts) {+ const f = sbeTsFind(tracks, sid);+ if (!f) return { tracks: tracks, ok: false, why: 'gone' };+ const n = sbeTsWindow(f.strip).len;+ const afx = Object.assign({}, f.strip.afx || {});+ const kept = (pts || []).slice().sort((x, y) => x[0] - y[0])+ .map(pr => [sbeRound(Math.max(0, Math.min(n, pr[0]))),+ sbeRound(Math.max(0, Math.min(1, pr[1])))]);+ if (kept.length) afx.points = kept; else delete afx.points;+ return sbeTsSetStrip(tracks, sid, { afx: afx });+}++function sbeTsAddKeyframe(tracks, sid, t, gain) {+ const f = sbeTsFind(tracks, sid);+ if (!f) return { tracks: tracks, ok: false, why: 'gone' };+ const n = sbeTsWindow(f.strip).len;+ const at = Math.max(0, Math.min(n, sbeNum(t)));+ const pts = sbeAfx(f.strip, n).points.slice();+ for (const pr of pts) {+ if (Math.abs(pr[0] - at) < 1e-3) {+ return { tracks: tracks, ok: false, why: 'there is already a point here' };+ }+ }+ pts.push([at, Math.max(0, Math.min(1, sbeNum(gain, 1)))]);+ return sbeTsPointsWrite(tracks, sid, pts);+}++function sbeTsMoveKeyframe(tracks, sid, index, t, gain) {+ const f = sbeTsFind(tracks, sid);+ if (!f) return { tracks: tracks, ok: false, why: 'gone' };+ const n = sbeTsWindow(f.strip).len;+ const pts = sbeAfx(f.strip, n).points.slice();+ if (!pts.length) return { tracks: tracks, ok: false, why: 'gone' };+ const i = Math.max(0, Math.min(pts.length - 1, sbeNum(index)));+ pts[i] = [Math.max(0, Math.min(n, sbeNum(t))), Math.max(0, Math.min(1, sbeNum(gain)))];+ return sbeTsPointsWrite(tracks, sid, pts);+}++function sbeTsDeleteKeyframe(tracks, sid, index) {+ const f = sbeTsFind(tracks, sid);+ if (!f) return { tracks: tracks, ok: false, why: 'gone' };+ const pts = sbeAfx(f.strip, sbeTsWindow(f.strip).len).points.slice();+ const i = sbeNum(index, -1);+ if (i < 0 || i >= pts.length) return { tracks: tracks, ok: false, why: 'gone' };+ pts.splice(i, 1);+ return sbeTsPointsWrite(tracks, sid, pts);+}++// EVERY TRACK STRIP AUDIBLE AT FILM SECOND `t`, as the strip player wants it:+// the source second, and the volume the render's curve has there. The mirror+// of `sbeStripsAt`, for the lanes a clip does not own.+function sbeTsAt(tracks, t) {+ const now = sbeNum(t);+ const out = [];+ for (const tr of (tracks || [])) {+ if (tr.muted === true) continue;+ for (const s of (tr.strips || [])) {+ if (s.muted === true || !s.path) continue;+ const w = sbeTsWindow(s);+ if (now < w.film_start - 1e-6 || now >= w.film_end) continue;+ out.push({ id: 'ts:' + s.id, path: String(s.path),+ at: sbeRound(w.start + (now - w.film_start)),+ from: w.film_start, to: w.film_end, speed: 1,+ vol: sbeTsGainAt(tr, s, now - w.film_start) });+ }+ }+ return out;+}++// What a track strip's edge clicks onto: the cuts (the same list a clip's+// sound snaps to), every other strip's ends on every track, and every clip+// strip's ends on A1. The beat grid is added by the drag, near the pointer.+function sbeTsSnaps(tracks, clips, skip) {+ const out = sbeMusicSnaps(clips);+ for (const t of (tracks || [])) {+ for (const s of (t.strips || [])) {+ if (skip !== undefined && String(s.id) === String(skip)) continue;+ const w = sbeTsWindow(s);+ out.push(w.film_start, w.film_end);+ }+ }+ for (const c of (clips || [])) {+ if (sbeKind(c) !== 'video') continue;+ const w = sbeClipAudio(c);+ out.push(sbeRound(w.film_start), sbeRound(w.film_start + w.len));+ }+ return out;+}++// A1 → a strip. The clip's own sound, window and envelope, placed right after+// where it plays. Refused, with the reason, for a clip that has none, and for+// a retimed one: a track strip plays at 1x.+function sbeTsFromClip(c) {+ if (!c || sbeKind(c) !== 'video') return { why: 'Only a video clip has sound of its own to copy.' };+ if (c.has_audio === false) return { why: 'This clip has no sound of its own to copy.' };+ const w = sbeClipAudio(c);+ if (Math.abs(w.speed - 1) > 1e-9) {+ return { why: 'This clip plays at ' + w.speed + 'x and a sound on an audio track plays at 1x — '+ + 'set the clip back to 1x to copy its sound.' };+ }+ const s = { id: sbeNewId(), path: String(c.path || ''), start: w.start, end: w.end,+ film_start: sbeRound(w.film_start + w.len),+ title: sbeTsCopyTitle({ title: c.title, path: c.path }, 'clip sound') };+ if (sbeNum(c.duration, 0) > 0) s.duration = sbeNum(c.duration);+ const e = sbeAfx(c, w.len);+ const afx = {};+ if (e.fade_in > 1e-9) afx.fade_in = e.fade_in;+ if (e.fade_out > 1e-9) afx.fade_out = e.fade_out;+ if (e.points.length) afx.points = e.points;+ if (Object.keys(afx).length) s.afx = afx;+ if (sbeClipMuted(c)) s.muted = true;+ return { strip: s };+}++// A2 → a strip. The played window of the soundtrack, its envelope and its+// fader (the duck is a relationship with A1, not a property of the sound, so+// it does not travel). A2 holds ONE strip, so the copy is always a track's.+function sbeTsFromBed(audio, peaksDur) {+ const a = audio || {};+ if (!a.path) return { why: 'There is no soundtrack on A2 to copy.' };+ const w = sbeMusicWindow(a, peaksDur);+ if (w.film_end === null || w.tail === null) {+ return { why: 'The soundtrack\'s length is not known yet — press Prepare in the A2 head\'s ▾ first.' };+ }+ const len = sbeRound(w.tail - w.head);+ if (len < SBE_TRACK_STRIP_MIN) return { why: 'The soundtrack is trimmed to nothing.' };+ const s = { id: sbeNewId(), path: String(a.path), start: w.head, end: w.tail,+ film_start: sbeRound(w.film_start + len),+ title: sbeTsCopyTitle({ path: a.path }, 'music') };+ if (w.duration > 0) s.duration = sbeRound(w.duration);+ const e = sbeAfx(a, len);+ const afx = {};+ if (e.fade_in > 1e-9) afx.fade_in = e.fade_in;+ if (e.fade_out > 1e-9) afx.fade_out = e.fade_out;+ if (e.points.length) afx.points = e.points;+ if (Object.keys(afx).length) s.afx = afx;+ const g = sbeAudioMix(a).bed_gain;+ if (Math.abs(g - 1) > 1e-9) s.gain = g;+ return { strip: s };+}++// The tracks as the save payload carries them: client bookkeeping stripped,+// numbers rounded. An empty list is sent as no key at all (see sbeSaveBody).+function sbeTsClean(tracks) {+ return (tracks || []).map(t => {+ const o = {};+ for (const k of Object.keys(t || {})) if (k.charAt(0) !== '_') o[k] = t[k];+ o.strips = ((t || {}).strips || []).map(s => {+ const x = {};+ for (const k of Object.keys(s || {})) if (k.charAt(0) !== '_') x[k] = s[k];+ x.start = sbeRound(x.start); x.end = sbeRound(x.end);+ x.film_start = sbeRound(x.film_start);+ return x;+ });+ return o;+ });+}++// ---- the selection, on the tracks ----------------------------------------+// `SBE.sel` names the PRIMARY the way '@music' already does: '@ts:<strip id>'.+// `SBE.tsSet` is every selected strip and always holds the primary. Anything+// that points `SBE.sel` at a clip — every existing click path — therefore+// ends the strip selection without having to know it exists.+function sbeTsSelIds() {+ const sel = String(SBE.sel || '');+ if (sel.indexOf('@ts:') !== 0) return [];+ const primary = sel.slice(4);+ const live = {};+ for (const t of (SBE.tracks || [])) for (const s of (t.strips || [])) live[String(s.id)] = true;+ if (!live[primary]) return [];+ let set = (SBE.tsSet || []).map(String).filter(id => live[id]);+ if (set.indexOf(primary) < 0) set = [primary];+ SBE.tsSet = set;+ return set.slice();+}++function sbeTsSelectOne(sid) {+ SBE.sel = '@ts:' + String(sid);+ SBE.tsSet = [String(sid)];+ SBE.selSet = []; SBE.ovSel = ''; SBE.txSel = ''; SBE.selLane = '';+}++function sbeTsSelectToggle(sid) {+ const want = String(sid);+ const set = sbeTsSelIds();+ if (!set.length) { sbeTsSelectOne(want); return; }+ const i = set.indexOf(want);+ if (i < 0) { set.push(want); SBE.sel = '@ts:' + want; }+ else if (set.length > 1) {+ set.splice(i, 1);+ if (SBE.sel === '@ts:' + want) SBE.sel = '@ts:' + set[0];+ } else return;+ SBE.tsSet = set;+}++// THE DOOR every track edit goes through, the same shape `sbeMutateEach` has:+// one undo step for one gesture however many strips it touched, a refusal on+// one strip reported and the rest done, and the model's pure answers adopted+// only when something landed. Returns the list of answers, or false.+function sbeTsMutateEach(ids, fn) {+ const list = (ids || []).slice();+ if (!list.length) return false;+ const before = sbeSnapshot();+ let tracks = SBE.tracks || [];+ const why = [];+ const done = [];+ for (const id of list) {+ const r = fn(tracks, id);+ if (!r || r.ok === false) { if (r && r.why) why.push(String(r.why)); continue; }+ tracks = r.tracks;+ done.push(r);+ }+ const say = (w) => (w === 'locked' ? 'That sound is locked.' : w);+ if (!done.length) {+ phosToast(say(why[0] || 'Nothing on this selection could take that.'), {});+ return false;+ }+ SBE.undo.push(before);+ if (SBE.undo.length > SBE_UNDO_MAX) SBE.undo.shift();+ SBE.redo.length = 0;+ SBE.tracks = tracks;+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ if (why.length) {+ phosToast(why.length + ' of ' + list.length + ' were left as they were — '+ + say(why[0]), { duration: 6000 });+ }+ sbePaint();+ sbeQueueSave();+ return done;+}++function sbeTsMutate(fn) {+ const r = sbeTsMutateEach(['*'], (ts) => fn(ts));+ return r ? r[0] : false;+}+// ---- THE OVERLAY LANE'S MODEL -------------------------------------------// Overlays do NOT ripple. A card is placed where somebody wants it in the// finished film, so moving one moves one, and trimming one changes only its@@ -2025,6 +2807,9 @@ function sbeDuplicate(clips, id) {out.splice(out.indexOf(c) + 1, 0, b);sbeLayout(out);sbeSyncCarry(out, mark, [b.id]);+ // THE COPY IS A NEIGHBOUR, so its sound goes on the other lane — the two+ // can then be trimmed into each other and crossfaded like any pair.+ sbeLaneFit(out, b);return { clips: out, ok: true, added: b };}@@ -2165,6 +2950,7 @@ function sbePlaceUnplaced(clips, item, filmStart) {sbeLayout(out);}sbeSyncCarry(out, mark, []);+ sbeLaneFit(out, c);return { clips: out, ok: true, added: c };}@@ -2288,6 +3074,7 @@ function sbeInsertAt(clips, item, filmTime) {c._gap = 0; // hard against its new neighboursbeLayout(out); // everything after it rides alongsbeSyncCarry(out, mark, []); // ...sound included+ sbeLaneFit(out, c); // ...on the lane its neighbour is not onreturn { clips: out, ok: true, added: c, index: idx };}@@ -2349,6 +3136,8 @@ function sbeCleanClip(c) {else out.speed = sp;if (kind === 'slug' || sbeFramingIsNeutral(c)) delete out.frame;else out.frame = sbeFraming(c);+ // Lane A is the absence of the field, the same way the server writes it.+ if (sbeSoundLane(c) === 2) out.sound_lane = 2; else delete out.sound_lane;return out;}@@ -2364,6 +3153,11 @@ function sbeSaveBody(state) {});// THE BOUNDARIES TRAVEL TOO. An empty list is the server's absent key.edit.transitions = (state.transitions || []).map(t => Object.assign({}, t));+ // THE AUDIO TRACKS, and NO KEY when there are none — the server's absent+ // key, so a timeline with no tracks sends exactly the document it always+ // did and the backup's digest cannot differ from the save's over `[]`.+ const tracks = (typeof sbeTsClean === 'function') ? sbeTsClean(state.tracks || []) : [];+ if (tracks.length) edit.audio_tracks = tracks; else delete edit.audio_tracks;edit.board_id = state.id;const body = { id: state.id, edit: edit };if (state.expect !== null && state.expect !== undefined) body.expect_revision = state.expect;@@ -2549,11 +3343,10 @@ function sbeMonitorFit(width, budget, opts) {// never take so much that the monitors stop being monitors — `max` is// sbeFitMonitors' measurement of that, and it is clamped again here so a// caller that has not measured yet cannot ask for a screenful.-function sbeTlClamp(want, max) {- const hi = Math.max(SBE_TL_MIN_H,- Math.min(SBE_TL_MAX_H, sbeNum(max, SBE_TL_MAX_H)));- return Math.round(Math.max(SBE_TL_MIN_H,- Math.min(hi, sbeNum(want, SBE_TL_MIN_H))));+function sbeTlClamp(want, max, small) {+ const floor = sbeTlFloor(small), roof = sbeTlRoof(small);+ const hi = Math.max(floor, Math.min(roof, sbeNum(max, roof)));+ return Math.round(Math.max(floor, Math.min(hi, sbeNum(want, floor))));}// WHERE A DRAGGED PIXEL LANDS. Every lane starts at the height it has always@@ -2561,21 +3354,28 @@ function sbeTlClamp(want, max) {// a capped lane cannot take is offered again to the ones still growing, so the// height is spent rather than lost. Pure: px in, px out, no DOM — the// distribution is the whole feature and it is not checkable by eye.-function sbeLaneHeights(tlH) {+function sbeLaneHeights(tlH, small) {+ const s = (small === undefined) ? sbeAudioSmall() : !!small;+ const floor = sbeTlFloor(s);const out = { ruler: 18 };- for (const L of SBE_LANES) out[L.key] = L.base;- let left = Math.max(0, Math.round(sbeNum(tlH, SBE_TL_MIN_H)) - SBE_TL_MIN_H);+ for (const L of SBE_LANES) out[L.key] = sbeLaneBase(L, s);+ let left = Math.max(0, Math.round(sbeNum(tlH, floor)) - floor);// Four passes is one more than the number of lanes that can cap while// another still has room, so this terminates with the height spent or every// lane full. A `while` here would be a loop whose bound is an argument.for (let pass = 0; pass < 4 && left > 0.5; pass++) {let share = 0;- for (const L of SBE_LANES) if (out[L.key] < L.cap) share += L.share;+ // A LANE THAT IS SUPPOSED TO BE THIN NEVER TAKES A DRAGGED PIXEL — a+ // compacted lane that grew with the drag would not be compact.+ for (const L of SBE_LANES) {+ if (out[L.key] < sbeLaneCap(L, s)) share += L.share;+ }if (share <= 0) break;const pool = left;for (const L of SBE_LANES) {- if (out[L.key] >= L.cap) continue;- const take = Math.min(pool * (L.share / share), L.cap - out[L.key]);+ const cap = sbeLaneCap(L, s);+ if (out[L.key] >= cap) continue;+ const take = Math.min(pool * (L.share / share), cap - out[L.key]);out[L.key] += take;left -= take;}@@ -2594,15 +3394,205 @@ function sbeLaneHeights(tlH) {function sbeTlPrefRead() {let v = NaN;try { v = parseInt(localStorage.getItem('phos_sbe_tl_h') || '', 10); } catch (e) {}- return (v === v) ? sbeTlClamp(v, SBE_TL_MAX_H) : SBE_TL_MIN_H;+ // Read and written against the FULL-height ends: the number the user dragged+ // is what he asked for with the sound open, and making the lanes small must+ // not quietly rewrite it to the smaller ceiling.+ return (v === v) ? sbeTlClamp(v, SBE_TL_MAX_H, false) : SBE_TL_MIN_H;}function sbeTlPrefWrite(px) {try {localStorage.setItem('phos_sbe_tl_h',- String(sbeTlClamp(px, SBE_TL_MAX_H)));+ String(sbeTlClamp(px, SBE_TL_MAX_H, false)));} catch (e) {}}+// ---------------------------------------------------------------------------+// THE SOUND LANES MAKE THEMSELVES SMALL+// ---------------------------------------------------------------------------+// "Think of some way that is really seamless and user-friendly to maybe+// compact all audio lanes when I am not working with them and make them little+// (because I want to see the image also as I'm working sometimes)."+//+// So it is AUTOMATIC and it is also a button. Automatic is the default: the+// sound area is thin until you go near it and full height for as long as you+// are on it. The button (the ▾ on the A1 head, ⇧A) is for when you have an+// opinion — it pins one answer, in THIS BROWSER, next to the timeline's height+// and for the same reason: a window's shape is not the film's data. See the+// comment above sbeTlPrefRead, which this follows exactly.+//+// THREE STATES, ONE KEY: 'auto' (the default), 'open', 'small'.+function sbeAudioPinRead() {+ let v = '';+ try { v = localStorage.getItem('phos_sbe_audio') || ''; } catch (e) {}+ return (v === 'open' || v === 'small') ? v : 'auto';+}+function sbeAudioPinWrite(v) {+ try { localStorage.setItem('phos_sbe_audio', String(v || 'auto')); } catch (e) {}+}+function sbeAudioPinSet(v) {+ const want = (v === 'open' || v === 'small') ? v : 'auto';+ SBE.aPin = want;+ sbeAudioPinWrite(want);+ sbeAudioSync();+}++// IS THE SOUND AREA SMALL RIGHT NOW? Every height function asks this, including+// the one the timeline's own preference is read through — which runs inside+// SBE's initialiser, before SBE exists. Hence the guard: this may not throw.+function sbeAudioSmall() {+ try { return !!(SBE && SBE.aSmall); } catch (e) { return false; }+}++// IS SOMEBODY WORKING ON SOUND? Read off the state the audio gestures already+// write, so no click path has to remember to announce itself: a selected strip,+// a drag in progress, the pointer over a lane or a head, the Sound pool open,+// a focused control in the sound heads. Playback and an open menu hold it open+// too — a lane that collapsed mid-play or under an open menu would be the+// "jumps" the request rules out.+function sbeAudioBusy() {+ if (SBE.audioDrag || SBE.musicDrag || SBE.tsDrag || SBE.kfDrag || SBE.tgSliding) return true;+ if (SBE.tlDrag) return true;+ if (SBE.playing) return true;+ if (SBE.aHover) return true;+ if (typeof sbePopAnyOpen === 'function' && sbePopAnyOpen()) return true;+ const sel = String(SBE.sel || '');+ if (sel === '@music' || sel.indexOf('@ts:') === 0) return true;+ if (SBE.selLane) return true;+ if (typeof ED === 'object' && ED && ED.src === 'sound') return true;+ const f = (typeof document === 'object' && document) ? document.activeElement : null;+ if (f && f.closest && f.closest('.sbe-gh-aud, .sbe-gh-mus, .sbe-gh-trk, .sbe-gh-add')) return true;+ return false;+}++// What the area SHOULD be, right now. Pure decision, no DOM.+function sbeAudioWant() {+ if (SBE.aPin === 'open') return false;+ if (SBE.aPin === 'small') return true;+ if (sbeAudioBusy()) return false;+ return (Date.now() - sbeNum(SBE.aTouch, 0)) >= SBE_ASMALL_IDLE;+}++// ASK AGAIN LATER. One timer, always the only one, and it is only ever armed+// while the area is OPEN and unpinned — the way back the other direction is a+// touch, which is immediate.+function sbeAudioArm() {+ if (SBE.aTimer) { clearTimeout(SBE.aTimer); SBE.aTimer = null; }+ if (!SBE.open || SBE.aPin !== 'auto' || SBE.aSmall) return;+ SBE.aTimer = setTimeout(() => { SBE.aTimer = null; sbeAudioSync(); }, SBE_ASMALL_IDLE);+}++function sbeAudioSync() {+ const want = sbeAudioWant();+ if (want !== SBE.aSmall) { sbeAudioSet(want); return; }+ sbeAudioArm();+}++// SOMEBODY IS ON SOUND. Opens the area at once (that half may never wait) and+// restarts the idle. `opts.open` also releases a `small` pin, because the two+// gestures that carry it — clicking a thin lane, dragging the edge up past what+// thin lanes can use — are the user asking for the sound back in so many words.+function sbeAudioTouch(opts) {+ SBE.aTouch = Date.now();+ if (opts && opts.open && SBE.aPin === 'small') {+ SBE.aPin = 'auto';+ sbeAudioPinWrite('auto');+ }+ if (SBE.aSmall && SBE.aPin !== 'small') sbeAudioSet(false);+ else sbeAudioArm();+}++// The pointer over a lane or a head is "working with it" for as long as it is+// there — hovering a thin lane opens it, which is how you find out it opens.+function sbeAudioOver(on) {+ const want = !!on;+ if (SBE.aHover === want) return;+ SBE.aHover = want;+ if (want) sbeAudioTouch();+ else sbeAudioArm();+}++// THE ONE WRITER of the area's size. Nothing here resizes an element either:+// it moves the same lane table the drag handle moves, and sbeFitMonitors gives+// the difference to the picture.+function sbeAudioSet(small) {+ const want = !!small;+ if (SBE.aSmall === want) return;+ SBE.aSmall = want;+ const plan = sbeEl('sbTimeline');+ if (plan && plan.classList) plan.classList.toggle('is-asmall', want);+ // A HEIGHT THAT JUMPS READS AS A BUG, so the lanes and their heads carry a+ // transition — but only while this class is on the body, so the drag handle,+ // which moves the same numbers sixty times a second, stays instant.+ if (typeof document === 'object' && document && document.body) {+ document.body.classList.add('sbe-aanim');+ }+ if (SBE.aAnim) clearTimeout(SBE.aAnim);+ SBE.aAnim = setTimeout(() => {+ SBE.aAnim = null;+ if (typeof document === 'object' && document && document.body) {+ document.body.classList.remove('sbe-aanim');+ }+ // THE WAVEFORMS ARE DRAWN, NOT STYLED: the soundtrack's canvas carries a+ // backing store and every strip's waveform is emitted at its own height, so+ // both have to be re-issued at the height they actually landed on. Same+ // reason sbeFitMonitors redraws them when the drag moves the number.+ SBE.laneAt = -1;+ sbePaint();+ }, 220);+ sbeApplyTl(sbeTlClamp(SBE.tlH, SBE.tlMax));+ if (want) sbeAudioSmallOnce();+ sbePaint();+ sbeAudioArm();+}++// THE FIRST TIME IT HAPPENS BY ITSELF, IT SAYS SO. An area that shrinks with no+// explanation is a bug the user reports; one sentence turns it into a feature+// he knows the handle for. Once per browser, next to the other view preferences.+function sbeAudioSmallOnce() {+ let seen = '';+ try { seen = localStorage.getItem('phos_sbe_audio_seen') || ''; } catch (e) {}+ if (seen) return;+ try { localStorage.setItem('phos_sbe_audio_seen', '1'); } catch (e) {}+ if (typeof phosToast !== 'function') return;+ phosToast('Sound lanes made small so the picture gets the height — touch any sound and they '+ + 'come straight back. The ▾ on the A1 head (⇧A) keeps them small, or open, for good.',+ { duration: 9000 });+}++// THE BUTTON. Two answers, and neither of them is "auto": auto is what you have+// until you have an opinion, and clicking a thin lane hands it back.+function sbeAudioPinToggle() {+ const want = sbeAudioSmall() ? 'open' : 'small';+ SBE.aPin = want;+ sbeAudioPinWrite(want);+ sbeAudioSet(want === 'small');+ if (typeof phosToast === 'function') {+ phosToast(want === 'small'+ ? 'Sound lanes small — A1, A2 and every audio track stay thin and the picture keeps the '+ + 'height. Click any sound to work on it; ⇧A brings them back for good.'+ : 'Sound lanes at full height — they stay open while you work. ⇧A, or the ▾ on the A1 '+ + 'head, makes them small again.', { duration: 6000 });+ }+}++// ONE CLICK ON A THIN LANE OPENS THE AREA AND SELECTS WHAT WAS CLICKED, which+// is the whole gesture: you point at the sound you want and it is there, full+// height, selected, ready for the second click to edit it.+function sbeAudioOpenFrom(ev) {+ const blk = (ev && ev.target && ev.target.closest)+ ? ev.target.closest('.sbe-tstrip, .sbe-aclip, .sbe-music-clip') : null;+ if (blk && blk.classList.contains('sbe-tstrip')) {+ sbeTsSelectOne(blk.dataset.strip);+ } else if (blk && blk.id === 'sbeMusicClip') {+ SBE.sel = '@music'; SBE.selSet = []; SBE.tsSet = []; SBE.selLane = '';+ } else if (blk && blk.dataset && blk.dataset.id) {+ sbeSelectOne(blk.dataset.id);+ SBE.selLane = blk.dataset.id; SBE.tsSet = [];+ }+ sbeAudioTouch({ open: true });+ if (ev && ev.preventDefault) ev.preventDefault();+}+// ---------------------------------------------------------------------------// LOADING AND SAVING// ---------------------------------------------------------------------------@@ -2832,6 +3822,8 @@ function sbeAdopt(r, quiet) {SBE.backupHidden = false; // a NEW offer is not the one dismissedSBE.overlays = (SBE.edit.overlays || []).map(o => Object.assign({}, o));SBE.transitions = (SBE.edit.transitions || []).map(t => Object.assign({}, t));+ SBE.tracks = sbeTsCopy(SBE.edit.audio_tracks || []);+ SBE.tsSet = []; SBE.tsDrag = null; SBE.tsDrop = null; SBE.selLane = '';SBE.ovSel = '';SBE.txSel = '';SBE.clips = sbeAdoptGaps((SBE.edit.clips || []).map(c => Object.assign({}, c)));@@ -2994,6 +3986,9 @@ function sbeSnapshot(audio) {// pictures walked back without it.overlays: SBE.overlays || [],transitions: SBE.transitions || [],+ // THE AUDIO TRACKS ARE THE ARRANGEMENT TOO — a strip placed and undone+ // must leave with the undo, not stay behind on its lane.+ tracks: SBE.tracks || [],audio: (audio === undefined)? (SBE.audio || (SBE.edit && SBE.edit.audio) || null) : audio,});@@ -3008,6 +4003,7 @@ function sbeRestore(json) {// card nobody asked to remove — absent means "unchanged", not "empty".if (s.overlays !== undefined) SBE.overlays = s.overlays || [];if (s.transitions !== undefined) SBE.transitions = s.transitions || [];+ if (s.tracks !== undefined) SBE.tracks = s.tracks || [];SBE.edit = SBE.edit || {};// ...and a restore never COMMITS a discovered track into the document. The// arrangement owns a soundtrack only once somebody has placed it (see@@ -3167,6 +4163,7 @@ function sbeSelectAll() {function sbeSelectNone() {SBE.sel = ''; SBE.selSet = []; SBE.ovSel = ''; SBE.txSel = '';+ SBE.tsSet = []; SBE.selLane = '';sbePaint();}@@ -3438,7 +4435,8 @@ async function sbeBackup(quiet) {let r;try {const body = sbeSaveBody({ id: SBE.id, edit: SBE.edit, clips: SBE.clips,- overlays: SBE.overlays, expect: null });+ overlays: SBE.overlays, tracks: SBE.tracks,+ expect: null });// WHICH DRAFT THIS WAS COMPOSED FROM. The server files the backup under// the draft that is active when the write LANDS, and this one is// debounced — so without the name in the body, a backup of the draft you@@ -3556,7 +4554,7 @@ async function sbeSaveInner(quiet, force) {const order = SBE.clips.map(c => c.id);SBE.sentOrder = order;const body = sbeSaveBody({ id: SBE.id, edit: SBE.edit, clips: SBE.clips,- overlays: SBE.overlays,+ overlays: SBE.overlays, tracks: SBE.tracks,expect: force ? null : SBE.revision });let r;try {@@ -4233,7 +5231,13 @@ function sbeSpan() {const film = sbeFilmDuration(SBE.clips);const w = sbeMusicWindow(SBE.audio, SBE.peaks ? SBE.peaks.duration : 0);const music = (w.film_end === null) ? w.film_start : w.film_end;- const base = Math.max(film, music, 0);+ // ...and the audio tracks, whose strips are placed on the film as freely as+ // the music is and must stay reachable past the last cut.+ let tracksEnd = 0;+ for (const t of (SBE.tracks || [])) {+ for (const s of (t.strips || [])) tracksEnd = Math.max(tracksEnd, sbeTsWindow(s).film_end);+ }+ const base = Math.max(film, music, tracksEnd, 0);const slack = Math.min(SBE_SLACK_MAX,Math.max(SBE_SLACK_MIN, base * SBE_SLACK_RATIO));return Math.max(SBE_SPAN_MIN, base + slack);@@ -4269,6 +5273,7 @@ function sbePaint() {sbeOvPaint();sbePaintTrack();sbePaintAudioLane();+ sbePaintTracks();sbePaintHead();sbePaintCbar();sbePaintInspector();@@ -4280,6 +5285,10 @@ function sbePaint() {// here, so this is the one place that cannot be forgotten. Unforced: the// slip tolerance keeps a drag from re-seeking sixty times a second.sbeStripSync();+ // EVERY EDIT AND EVERY SELECTION LANDS HERE, so this is where the sound+ // area's idle is restarted — a click that deselected the last strip has to+ // start the clock without every click path knowing that it did.+ sbeAudioArm();// LAST, and after the inspector: the row's budget is what the column has// left once everything else has been laid out, and the inspector is the// one that changes height when a clip is selected.@@ -4337,13 +5346,20 @@ function sbeFitMonitors() {// is small but it is still a picture, and it is the same floor sbeMonitorFit// has always refused to go under.const avail = col.clientHeight - used - gap * Math.max(0, shown - 1) - chrome;- SBE.tlMax = Math.max(SBE_TL_MIN_H,- Math.min(SBE_TL_MAX_H, Math.round(avail - SBE_MON_MIN_H)));+ // THE AUDIO TRACKS RIDE ON TOP of the height the handle sets: one strip+ // lane per track plus the add row. The lanes that were there keep what the+ // user gave them, and the monitors pay for the new ones.+ // Both ends read the CURRENT lane set: with the sound lanes small the box+ // can use less height, every track costs a fifth of what it did, and the+ // difference lands in `budget` below — which is the picture.+ const extra = sbeExtraLanesH(sbeLaneHeights(sbeTlClamp(SBE.tlH, sbeTlRoof())));+ SBE.tlMax = Math.max(sbeTlFloor(),+ Math.min(sbeTlRoof(), Math.round(avail - SBE_MON_MIN_H - extra)));// The PREFERENCE is never overwritten by a window that cannot honour it —// shrink the browser and the timeline gives the height back; widen it again// and the drag the user made is still there.const want = sbeTlClamp(SBE.tlH, SBE.tlMax);- const budget = avail - want;+ const budget = avail - want - extra;const apply = (b) => {const fit = sbeMonitorFit(row.clientWidth, b);row.style.setProperty('--sbe-prog-h', Math.round(fit.progH) + 'px');@@ -4361,7 +5377,12 @@ function sbeFitMonitors() {// own floor and cannot give anything back, so whatever the column is// overflowing by has to come off the TIMELINE or it does not come off// anything. Floored, never negative — the box may not shrink into itself.- sbeApplyTl(Math.max(SBE_TL_MIN_H, want + Math.round(b - fit.progH)));+ // ...AND IT MAY NOT HAND THE TIMELINE MORE THAN ITS LANES CAN USE. With+ // the sound lanes small the picture and the overlay reach their caps in+ // the first 80px, so anything past the roof is dead band inside the box+ // rather than a taller lane — the column keeps it instead.+ sbeApplyTl(Math.max(sbeTlFloor(),+ Math.min(sbeTlRoof(), want + Math.round(b - fit.progH))));};apply(budget);// ONE CORRECTION, NEVER A LOOP. Rounding, a sticky bar's own padding and a@@ -4382,6 +5403,7 @@ function sbeFitMonitors() {if (SBE.laneAt !== SBE.tlNow) {SBE.laneAt = SBE.tlNow;sbePaintAudioLane();+ sbePaintTracks();const inner = sbeEl('sbeInner');if (inner) sbePaintWave(sbeSpan(), parseFloat(inner.style.width) || 0);}@@ -4392,12 +5414,13 @@ function sbeFitMonitors() {// strip waveform's viewBox, the soundtrack canvas — reads the same numbers, so// the picture and the pointer maths cannot disagree about where a strip is.function sbeApplyTl(px) {- const tl = Math.max(SBE_TL_MIN_H, Math.round(sbeNum(px, SBE_TL_MIN_H)));+ const floor = sbeTlFloor();+ const tl = Math.max(floor, Math.round(sbeNum(px, floor)));SBE.tlNow = tl;const plan = sbeEl('sbTimeline');if (!plan || !plan.style) return;const L = sbeLaneHeights(tl);- plan.style.setProperty('--sbe-tl-h', tl + 'px');+ plan.style.setProperty('--sbe-tl-h', (tl + sbeExtraLanesH(L)) + 'px');plan.style.setProperty('--sbe-ov-h', L.ov + 'px');plan.style.setProperty('--sbe-track-h', L.track + 'px');plan.style.setProperty('--sbe-alane-h', L.alane + 'px');@@ -4412,7 +5435,11 @@ function sbeStripH() {// SEVEN, not six: the lane is border-box with a 1px top rule, and the strip// inside it is inset 3px top and bottom. Off by that one pixel the viewBox// and the box disagree and every waveform is drawn 4% tall.- return Math.max(14, sbeLaneHeights(SBE.tlNow || SBE.tlH).alane - 7);+ // 14 is the shortest strip that can still hold a level line and a point —+ // and it is the wrong floor for a lane that is deliberately 18px, so a small+ // lane gets the only floor that matters there: the box it is drawn in.+ return Math.max(sbeAudioSmall() ? 8 : 14,+ sbeLaneHeights(SBE.tlNow || SBE.tlH).alane - 7);}// ---- the drag itself ----------------------------------------------------@@ -4449,6 +5476,11 @@ function sbeTlGrabUp(ev) {// sbeFitMonitors (last inside sbePaint) gives the monitors what is left and// corrects tlNow for what the window could actually spare.function sbeTlSet(px) {+ // PULLING THE EDGE UP PAST WHAT THIN LANES CAN USE IS "give me the sound+ // back": there is no other height left in the box to ask for.+ if (sbeAudioSmall() && sbeNum(px, 0) > sbeTlRoof(true) + 8) {+ sbeAudioTouch({ open: true });+ }SBE.tlH = sbeTlClamp(px, SBE.tlMax);sbeApplyTl(SBE.tlH);sbePaint();@@ -4457,7 +5489,7 @@ function sbeTlSet(px) {// DOUBLE-CLICK RESETS, the same gesture the fade corners and the level line// already answer to on this timeline.function sbeTlReset() {- sbeTlSet(SBE_TL_MIN_H);+ sbeTlSet(sbeTlFloor());sbeTlPrefWrite(SBE.tlH);}@@ -4466,7 +5498,7 @@ function sbeTlGrabKey(ev) {const now = SBE.tlNow || SBE.tlH;if (ev.key === 'ArrowUp') sbeTlSet(now + step);else if (ev.key === 'ArrowDown') sbeTlSet(now - step);- else if (ev.key === 'Home') sbeTlSet(SBE_TL_MIN_H);+ else if (ev.key === 'Home') sbeTlSet(sbeTlFloor());else return;// The Editor's own shortcuts own the arrows (a frame at a time) and Home.// A focused handle is not the timeline, so the event stops here.@@ -4760,6 +5792,7 @@ function sbeBedLevelClick(ev) {}function sbeOnMusicDown(ev) {+ if (sbeAudioSmall()) { sbeAudioOpenFrom(ev); return; }const el = sbeEl('sbeMusicClip');if (!el || el.hidden) return;const a = SBE.audio;@@ -5222,7 +6255,9 @@ function sbePaintAudioLane() {// not have.const mute = c.has_audio === false;const off = sbeClipMuted(c);+ const lane = sbeSoundLane(c);const cls = 'sbe-aclip ' + (w.linked ? 'is-linked' : 'is-split')+ + (lane === 2 ? ' is-b' : '')+ (w.coupled ? ' is-coupled' : '')+ (mute ? ' is-mute' : '')+ (off ? ' is-silenced' : '')@@ -5245,8 +6280,9 @@ function sbePaintAudioLane() {: w.coupled? 'Linked at ' + sbeDriftLabel(sbeAudioDrift(c)) + ' — the sound keeps this offset and travels with the picture. Unlink it to slide it on its own.': (w.linked- ? 'This clip\'s sound moves with its picture. Unlink sound, on the bar above the tracks, to slide it under the neighbour (a J-cut or an L-cut).'- : 'Unlinked — drag to slide the sound, pull either end to trim it. The picture does not move.')) + '" '+ ? 'This clip\'s sound moves with its picture. Unlink sound, on the bar above the tracks, to slide it under the neighbour (a J-cut or an L-cut). Drag it up or down to put it on the other sound lane.'+ : 'Unlinked — drag to slide the sound, pull either end to trim it, drag it up or down to the other sound lane. The picture does not move.')+ + ' Sound lane ' + sbeLaneName(lane) + '.') + '" '+ 'style="left:' + x.toFixed(1) + 'px;width:' + Math.max(2, px).toFixed(1) + 'px">'+ (mute ? '' : sbeStripWave(c, w, px))+ (px > 70 ? '<span class="sbe-aclip-t">' + escapeHtml(label) + '</span>' : '')@@ -5267,6 +6303,600 @@ function sbePaintAudioLane() {lane.style.width = sbeEl('sbeInner').style.width;}+// ---------------------------------------------------------------------------+// THE AUDIO TRACKS ON SCREEN — lanes, heads, gestures+// ---------------------------------------------------------------------------+// How much taller the timeline is for its audio tracks: one strip lane per+// track (the same height A1's lane is given) plus the add row.+function sbeTracksExtraH(L) {+ const lanes = L || sbeLaneHeights(SBE.tlNow || SBE.tlH);+ return (SBE.tracks || []).length * lanes.alane + SBE_TADD_H;+}++// EVERYTHING the lane table does not itemise: the audio tracks, and clip sound+// lane B — A1 is drawn as TWO strip lanes in one box (`#sbeAudioLane` is twice+// `--sbe-alane-h` tall), and the second one is paid for here, the way a track+// is, so the lanes the user sized keep their height.+function sbeExtraLanesH(L) {+ const lanes = L || sbeLaneHeights(SBE.tlNow || SBE.tlH);+ return sbeTracksExtraH(lanes) + lanes.alane;+}++// A LANE PER TRACK, directly under the music, and each strip drawn by the+// SAME painter A1's strips use — waveform, level line, points, fade ramps,+// grips and the corner band — handed the strip's render curve.+function sbePaintTracks() {+ const box = sbeEl('sbeTracks');+ if (!box) return;+ const tracks = SBE.tracks || [];+ const sel = {};+ for (const id of sbeTsSelIds()) sel[id] = true;+ const drop = SBE.tsDrop || null;+ let html = '';+ tracks.forEach((t) => {+ const tid = escapeHtml(String(t.id));+ const tmuted = t.muted === true;+ let body = '';+ for (const s of (t.strips || [])) {+ const w = sbeTsWindow(s);+ const px = sbePx(w.len);+ const item = { id: '@ts:' + s.id, path: s.path, afx: s.afx,+ locked: s.locked === true, _ts: true };+ const off = tmuted || s.muted === true;+ const name = s.title || String(s.path || '').split('/').pop() || 'sound';+ const cls = 'sbe-aclip is-split sbe-tstrip' + (sel[String(s.id)] ? ' is-sel' : '')+ + (off ? ' is-silenced' : '') + (s.locked === true ? ' is-locked' : '');+ body += '<div class="' + cls + '" data-strip="' + escapeHtml(String(s.id)) + '" '+ + 'data-track="' + tid + '" title="' + escapeHtml(name + '\n'+ + (off ? 'Muted — silent in the preview, the render and the export.\n' : '')+ + (s.locked === true ? 'Locked — Unlock on the bar above the tracks.'+ : 'Drag to move it, onto another track too · pull either end to trim · '+ + 'the corners fade it · click the yellow line for a level point.')) + '" '+ + 'style="left:' + sbePx(w.film_start).toFixed(1) + 'px;width:'+ + Math.max(2, px).toFixed(1) + 'px">'+ + sbeStripWave(item, w, px, sbeTsGainPoints(t, s))+ + (px > 70 ? '<span class="sbe-aclip-t">' + escapeHtml((off ? 'MUTED · ' : '')+ + sbeNiceName(name)) + '</span>' : '')+ + sbeAudioFadeMarks(item, w)+ + (s.locked === true ? ''+ : '<div class="sbe-grip l"></div><div class="sbe-grip r"></div>'+ + '<div class="sbe-fade-band">'+ + '<div class="sbe-fade-h in" data-afade="in"></div>'+ + '<div class="sbe-fade-h out" data-afade="out"></div></div>')+ + '</div>';+ }+ if (drop && String(drop.tid) === String(t.id)) {+ body += '<div class="sbe-drop-line" style="left:' + sbePx(drop.at).toFixed(1) + 'px"></div>';+ }+ html += '<div class="sbe-alane sbe-tlane' + (tmuted ? ' is-muted' : '') + '" '+ + 'data-track="' + tid + '">' + body + '</div>';+ });+ html += '<div class="sbe-tadd' + ((drop && drop.tid === 'new') ? ' is-drop' : '') + '" '+ + 'data-track="new"><span class="sbe-tadd-t">'+ + escapeHtml(tracks.length+ ? 'Drop a sound here for a track of its own'+ : 'Audio tracks — drop a sound from the media pool here, or press + Add audio track')+ + '</span></div>';+ box.innerHTML = html;+ const inner = sbeEl('sbeInner');+ if (inner) box.style.width = inner.style.width;+ sbePaintTrackHeads();+}++// The heads: name, mute, level, remove. Rewritten only when what they show+// changed, and never while a level slider is being dragged — replacing the+// element under the pointer is how a slider drag dies halfway.+function sbePaintTrackHeads() {+ const heads = sbeEl('sbeTrackHeads');+ if (!heads) return;+ const tracks = SBE.tracks || [];+ const sig = JSON.stringify(tracks.map(t => [t.id, t.name || '', t.muted === true,+ sbeTrackGain(t)]));+ if (SBE.tgSliding || heads.dataset.sig === sig) return;+ heads.dataset.sig = sig;+ heads.innerHTML = tracks.map((t, ti) => {+ const tid = escapeHtml(String(t.id));+ const q = '\'' + tid + '\'';+ const label = sbeTrackLabel(ti);+ const pct = Math.round(sbeTrackGain(t) * 100);+ const muted = t.muted === true;+ return '<div class="sbe-gh sbe-gh-trk' + (muted ? ' is-muted' : '') + '" data-track="' + tid + '">'+ + '<span class="sbe-gh-tag"><i>' + label + '</i>'+ + '<input type="text" class="sbe-trk-name" maxlength="60" spellcheck="false" value="'+ + escapeHtml(t.name || 'Sound') + '" aria-label="Name of audio track ' + label + '" '+ + 'title="Rename this track" onchange="sbeTrackRename(' + q + ', this.value)">'+ + '<button type="button" class="sbe-gh-more sbe-trk-x" onclick="sbeTrackRemove(' + q + ')" '+ + 'title="Remove this track and every sound on it. Undo brings it back.">×</button></span>'+ + '<span class="sbe-trk-row">'+ + '<button type="button" class="sbe-trk-mute' + (muted ? ' is-on' : '') + '" '+ + 'aria-pressed="' + muted + '" onclick="sbeTrackMute(' + q + ')" title="'+ + (muted ? 'Unmute this track'+ : 'Mute this track — silent in the preview, the render and the export') + '">M</button>'+ + '<input type="range" min="0" max="100" step="1" value="' + pct + '" '+ + 'aria-label="Level of audio track ' + label + '" '+ + 'title="How loud everything on this track plays. 100% is the files\' own level; the render applies exactly this." '+ + 'oninput="sbeTrackGainSlide(' + q + ', this.value)" onchange="sbeTrackGainCommit(' + q + ', this.value)">'+ + '<b>' + pct + '%</b></span></div>';+ }).join('');+}++// One undo step for a gesture whose live updates wrote SBE.tracks directly.+function sbeTsCommit(before) {+ SBE.undo.push(before);+ if (SBE.undo.length > SBE_UNDO_MAX) SBE.undo.shift();+ SBE.redo.length = 0;+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ sbePaint();+ sbeQueueSave();+}++function sbeTrackAdd() {+ sbeAudioTouch({ open: true });+ if (!SBE.open) return;+ if (sbeTsMutate(ts => sbeTsNewTrack(ts))) {+ phosToast(sbeTrackLabel(SBE.tracks.length - 1) + ' added — drag a sound from the media '+ + 'pool onto it, or use Add sound file…. Sounds on different tracks play '+ + 'together.', { duration: 6000 });+ }+}++function sbeTrackRemove(tid) {+ const t = sbeTsTrackById(SBE.tracks, tid);+ if (!t) return;+ const n = (t.strips || []).length;+ if (sbeTsMutate(ts => sbeTsRemoveTrack(ts, tid))) {+ phosToast('Track removed' + (n ? ' with its ' + n + ' sound' + (n === 1 ? '' : 's') : '')+ + ' — Undo brings it back.', { duration: 6000 });+ }+}++function sbeTrackMute(tid) {+ const t = sbeTsTrackById(SBE.tracks, tid);+ if (!t) return;+ sbeTsMutate(ts => sbeTsSetTrack(ts, tid, { muted: t.muted !== true }));+}++function sbeTrackRename(tid, v) {+ const t = sbeTsTrackById(SBE.tracks, tid);+ if (!t || String(v || '').trim() === String(t.name || 'Sound')) return;+ sbeTsMutate(ts => sbeTsSetTrack(ts, tid, { name: v }));+}++function sbeTrackGainSlide(tid, v) {+ const r = sbeTsSetTrack(SBE.tracks, tid, { gain: sbeNum(v) / 100 });+ if (!r.ok) return;+ if (!SBE.tgBefore) SBE.tgBefore = sbeSnapshot();+ SBE.tgSliding = true;+ SBE.tracks = r.tracks;+ const head = document.querySelector('.sbe-gh-trk[data-track="' + String(tid).replace(/"/g, '') + '"] b');+ if (head) head.textContent = Math.round(sbeNum(v)) + '%';+ sbePaintTracks();+ sbeStripSync();+}++function sbeTrackGainCommit(tid, v) {+ sbeTrackGainSlide(tid, v);+ SBE.tgSliding = false;+ const before = SBE.tgBefore;+ SBE.tgBefore = null;+ if (!before || JSON.stringify(JSON.parse(before).tracks || []) === JSON.stringify(SBE.tracks)) {+ sbePaint();+ return;+ }+ sbeTsCommit(before);+}++// The selected strip's own level, from the inspector. Live on input, one undo+// step on change — the rule every slider here follows.+function sbeTsGainSlide(v) {+ const sid = String(SBE.sel || '').slice(4);+ const r = sbeTsSetStrip(SBE.tracks, sid, { gain: sbeNum(v) / 100 });+ if (!r.ok) return;+ if (!SBE.tsGainBefore) SBE.tsGainBefore = sbeSnapshot();+ SBE.tracks = r.tracks;+ const el = sbeEl('sbeTsGainVal');+ if (el) el.textContent = Math.round(sbeNum(v)) + '%';+ sbePaintTracks();+ sbeStripSync();+}++function sbeTsGainCommit(v) {+ sbeTsGainSlide(v);+ const before = SBE.tsGainBefore;+ SBE.tsGainBefore = null;+ if (!before || JSON.stringify(JSON.parse(before).tracks || []) === JSON.stringify(SBE.tracks)) {+ sbePaint();+ return;+ }+ sbeTsCommit(before);+}++function sbeTsFadeCommit(edge, v) {+ const sid = String(SBE.sel || '').slice(4);+ if (!sid) return;+ sbeTsMutate(tracks => sbeTsSetFade(tracks, sid, edge, v));+}++// THE INSPECTOR FOR A TRACK SOUND: what it is, where it plays, and its shape —+// level, fades and the level points. True when it painted the box.+function sbePaintTsInspector(box) {+ if (String(SBE.sel || '').indexOf('@ts:') !== 0) return false;+ const f = sbeTsFind(SBE.tracks, String(SBE.sel).slice(4));+ if (!f) return false;+ const s = f.strip;+ const w = sbeTsWindow(s);+ const ae = sbeAfx(s, w.len);+ const g = Math.round(sbeTsGain(s) * 100);+ const name = s.title || String(s.path || '').split('/').pop() || 'sound';+ const n = sbeTsSelIds().length;+ const arow = (edge, val) =>+ '<span class="sbe-fade-row"><label for="sbeTsFade' + edge + '">Fade ' + edge + '</label>'+ + '<input type="number" class="sb-input sbe-fade-num" id="sbeTsFade' + edge + '" min="0" '+ + 'max="' + w.len.toFixed(2) + '" step="0.05" value="' + val.toFixed(2) + '" '+ + 'onchange="sbeTsFadeCommit(\'' + edge + '\', this.value)" '+ + 'title="Seconds. Drag the corner of the strip for the same thing by eye.">'+ + '<span class="sbe-adj-val">s</span></span>';+ box.innerHTML =+ '<b>' + escapeHtml(sbeNiceName(name)) + '</b>'+ + (n > 1 ? '<span class="sbe-sect-lead">' + n + ' sounds selected · these are THIS '+ + 'one\'s properties. The bar above the tracks acts on all ' + n + '.</span>' : '')+ + '<span>' + escapeHtml(sbeTrackLabel(f.ti) + ' · ' + (f.track.name || 'Sound')+ + (f.track.muted === true ? ' (muted)' : '')) + '</span>'+ + '<span>source ' + w.start.toFixed(2) + '–' + w.end.toFixed(2) + 's'+ + (sbeNum(s.duration, 0) > 0 ? ' of ' + sbeNum(s.duration).toFixed(2) + 's' : '') + '</span>'+ + '<span>film ' + w.film_start.toFixed(2) + '–' + w.film_end.toFixed(2) + 's</span>'+ + '<span class="sbe-why">' + escapeHtml('A sound on an audio track plays over everything '+ + 'above it, mixed — in the preview, the render and the export.'+ + (s.locked === true ? ' It is locked.' : '')) + '</span>'+ + '<div class="sbe-sect"><div class="sbe-sect-h">Sound</div><div class="sbe-sect-b">'+ + '<span class="sbe-fade-row"><label for="sbeTsGain">Level</label>'+ + '<input type="range" id="sbeTsGain" min="0" max="100" step="1" value="' + g + '" '+ + 'oninput="sbeTsGainSlide(this.value)" onchange="sbeTsGainCommit(this.value)" '+ + 'title="How loud this sound plays. 100% is the file\'s own level; the track\'s level multiplies it.">'+ + '<span class="sbe-adj-val" id="sbeTsGainVal">' + g + '%</span></span>'+ + arow('in', ae.fade_in) + arow('out', ae.fade_out)+ + '<span class="sbe-fade-row sbe-levels"><label>Levels</label>'+ + '<button type="button" class="ghost-btn" onclick="sbeAddPointAtPlayhead()" '+ + 'title="Puts a level point where the playhead is. On the strip: click the yellow line to add one, drag it to set the level, right-click it to remove it.">'+ + 'Add point at playhead</button>'+ + '<span class="sbe-adj-val">' + ae.points.length + ' point'+ + (ae.points.length === 1 ? '' : 's') + '</span></span>'+ + '</div></div>';+ return true;+}++// ---- the gestures on a track lane ----------------------------------------+// The same precedence A1's lane uses, most specific first: a level point, a+// corner fade handle, the level line, the grips (trim), the body (move — and+// onto another lane). Listeners live on the #sbeTracks container, which+// outlives every repaint of the strips inside it.+function sbeTsStripAt(ev) {+ const blk = (ev.target && ev.target.closest) ? ev.target.closest('.sbe-tstrip') : null;+ if (!blk || ev.target.closest('.sbe-fade-h')) return null;+ const f = sbeTsFind(SBE.tracks, blk.dataset.strip);+ if (!f || f.strip.locked === true) return null;+ const r = blk.getBoundingClientRect();+ const w = sbeTsWindow(f.strip);+ return { f: f, sid: String(f.strip.id), rect: r, len: w.len,+ t: w.len * Math.max(0, Math.min(1, (ev.clientX - r.left) / Math.max(1, r.width))),+ g: sbeStripGain(ev.clientY, r.top, r.height) };+}++// Which lane the pointer is over, by height: a track id, 'new' for the add+// row, or null. By rectangle rather than by target, because a captured+// pointer reports the container as its target wherever it is.+function sbeTsLaneAt(ev) {+ const box = sbeEl('sbeTracks');+ if (!box) return null;+ for (const el of Array.prototype.slice.call(box.children)) {+ const r = el.getBoundingClientRect();+ if (ev.clientY >= r.top && ev.clientY < r.bottom) return el.dataset.track || null;+ }+ return null;+}++// The envelope value that puts the line under the pointer: the line carries+// the strip and track faders, the point does not.+function sbeTsEnvGain(f, g) {+ const g0 = sbeTsGain(f.strip) * sbeTrackGain(f.track);+ return g0 > 1e-6 ? Math.min(1, Math.max(0, g / g0)) : 1;+}++function sbeTsLevelClick(ev) {+ const at = sbeTsStripAt(ev);+ if (!at) return false;+ const onLine = sbeStripY(sbeTsGainAt(at.f.track, at.f.strip, at.t), at.rect.height);+ const near = Math.abs((ev.clientY - at.rect.top) - onLine) <= SBE_LVL_GRAB;+ if (!near && !ev.target.closest('.sbe-lvl-hit')) return false;+ const before = sbeSnapshot();+ const r = sbeTsAddKeyframe(SBE.tracks, at.sid, at.t, sbeTsEnvGain(at.f, at.g));+ if (!r.ok) return false;+ SBE.tracks = r.tracks;+ sbeTsSelectOne(at.sid);+ SBE.kfGhost = null;+ const pts = sbeAfx(sbeTsFind(SBE.tracks, at.sid).strip, at.len).points;+ let idx = 0;+ for (let i = 0; i < pts.length; i++) {+ if (Math.abs(pts[i][0] - sbeRound(at.t)) < 1e-3) { idx = i; break; }+ }+ SBE.tsDrag = { mode: 'kf', sid: at.sid, index: idx, rect: at.rect, before: before, moved: true };+ try { sbeEl('sbeTracks').setPointerCapture(ev.pointerId); } catch (e) {}+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ sbePaint();+ return true;+}++function sbeOnTsDown(ev) {+ if (ev.button !== undefined && ev.button !== 0) return;+ if (sbeAudioSmall()) { sbeAudioOpenFrom(ev); return; }+ if (ev.target.closest && ev.target.closest('button, input')) return;+ sbeStop();+ const box = sbeEl('sbeTracks');+ const blk = ev.target.closest('.sbe-tstrip');+ if (!blk) {+ // EMPTY LANE: nothing selected, and the playhead goes there — the answer+ // every other lane on this timeline gives.+ const lane = ev.target.closest('.sbe-tlane, .sbe-tadd');+ SBE.sel = ''; SBE.selSet = []; SBE.tsSet = []; SBE.ovSel = ''; SBE.txSel = ''; SBE.selLane = '';+ if (lane) sbeSeek(sbeTimeFromEvent(ev, lane));+ sbePaint();+ return;+ }+ const sid = String(blk.dataset.strip);+ const f = sbeTsFind(SBE.tracks, sid);+ if (!f) return;+ const cap = () => { try { box.setPointerCapture(ev.pointerId); } catch (e) {} };+ const locked = f.strip.locked === true;+ const kf = ev.target.closest('.sbe-kf');+ if (kf && !locked) {+ sbeTsSelectOne(sid);+ if (ev.shiftKey) {+ sbeTsMutate(ts => sbeTsDeleteKeyframe(ts, sid, sbeNum(kf.dataset.kf)));+ ev.preventDefault();+ return;+ }+ SBE.tsDrag = { mode: 'kf', sid: sid, index: sbeNum(kf.dataset.kf),+ rect: blk.getBoundingClientRect(), before: sbeSnapshot(), moved: false };+ cap(); ev.preventDefault(); sbePaint();+ return;+ }+ const fh = ev.target.closest('.sbe-fade-h');+ if (fh && !locked) {+ sbeTsSelectOne(sid);+ const e0 = sbeAfx(f.strip, sbeTsWindow(f.strip).len);+ SBE.tsDrag = { mode: 'afade', sid: sid, edge: fh.dataset.afade, x0: ev.clientX,+ f0: (fh.dataset.afade === 'out') ? e0.fade_out : e0.fade_in,+ before: sbeSnapshot(), moved: false };+ cap(); ev.preventDefault(); sbePaint();+ return;+ }+ // SHIFT AND ⌘ ADD OR DROP A STRIP from the selection, as on the picture.+ if (ev.shiftKey || ev.metaKey || ev.ctrlKey) {+ sbeTsSelectToggle(sid);+ ev.preventDefault();+ sbePaint();+ return;+ }+ if (!ev.target.closest('.sbe-grip') && sbeTsLevelClick(ev)) { ev.preventDefault(); return; }+ const already = sbeTsSelIds().indexOf(sid) >= 0;+ const many = already && sbeTsSelIds().length > 1;+ if (!already) sbeTsSelectOne(sid); else SBE.sel = '@ts:' + sid;+ if (locked) {+ sbePaint();+ phosToast('That sound is locked to its place. Press Unlock on the bar above the tracks.',+ { duration: 6000 });+ return;+ }+ const grip = ev.target.closest('.sbe-grip');+ const w = sbeTsWindow(f.strip);+ SBE.tsDrag = { mode: grip ? (grip.classList.contains('r') ? 'trimR' : 'trimL') : 'move',+ sid: sid, tid: String(f.track.id), x0: ev.clientX,+ fs0: w.film_start, fe0: w.film_end,+ ids: (!grip && many) ? sbeTsSelIds() : null, collapse: many ? sid : '',+ base: JSON.stringify(SBE.tracks), before: sbeSnapshot(),+ moved: false, toNew: false };+ blk.classList.add('is-drag');+ cap(); ev.preventDefault(); sbePaint();+}++function sbeOnTsMove(ev) {+ const d = SBE.tsDrag;+ if (!d) { sbeTsGhost(ev); return; }+ if (d.mode === 'kf') {+ const f = sbeTsFind(SBE.tracks, d.sid);+ if (!f) return;+ const w = sbeTsWindow(f.strip);+ const r = d.rect;+ const t = w.len * Math.max(0, Math.min(1, (ev.clientX - r.left) / Math.max(1, r.width)));+ const res = sbeTsMoveKeyframe(SBE.tracks, d.sid, d.index, t,+ sbeTsEnvGain(f, sbeStripGain(ev.clientY, r.top, r.height)));+ if (res.ok) SBE.tracks = res.tracks;+ d.moved = true;+ sbePaint();+ return;+ }+ const lane = (d.mode === 'move') ? sbeTsLaneAt(ev) : null;+ if (Math.abs(ev.clientX - d.x0) > 3 || (lane && lane !== d.tid)) d.moved = true;+ if (!d.moved) return;+ if (d.mode === 'afade') {+ const adt = (d.edge === 'out') ? -(ev.clientX - d.x0) / SBE.pps+ : (ev.clientX - d.x0) / SBE.pps;+ const r2 = sbeTsSetFade(SBE.tracks, d.sid, d.edge, Math.max(0, d.f0 + adt));+ if (r2.ok) SBE.tracks = r2.tracks;+ sbePaint();+ return;+ }+ // RE-DERIVED FROM WHERE THE GESTURE STARTED on every event, so a fast mouse+ // and a slow one land in the same place.+ const base = JSON.parse(d.base);+ const tol = SBE_SNAP_PX / SBE.pps;+ const snapOn = sbeSnapEnabled(ev);+ const anchor = (d.mode === 'trimR') ? d.fe0 : d.fs0;+ let want = Math.max(0, anchor + (ev.clientX - d.x0) / SBE.pps);+ // THE SNAPS: cuts, every other strip's ends, A1's strips, and the beat.+ const marks = sbeTsSnaps(base, SBE.clips, d.sid);+ if (snapOn && SBE.beats && typeof sbeBeatGrid === 'function') {+ for (const b of sbeBeatGrid(SBE.beats, want - tol, want + tol, (SBE.audio || {}).offset)) marks.push(b.t);+ }+ want = sbeSnapToList(want, marks, tol, snapOn);+ let r;+ if (d.mode === 'move') {+ if (d.ids && d.ids.length > 1) {+ r = sbeTsMoveGroup(base, d.ids, want - d.fs0);+ } else {+ d.toNew = (lane === 'new');+ r = sbeTsMove(base, d.sid, (lane && lane !== 'new') ? lane : d.tid, want);+ }+ } else {+ r = sbeTsTrim(base, d.sid, d.mode, want);+ }+ if (r && r.ok) SBE.tracks = r.tracks;+ sbePaint();+}++function sbeOnTsUp(ev) {+ const d = SBE.tsDrag;+ SBE.tsDrag = null;+ if (!d) return;+ if (!d.moved) {+ if (d.collapse) sbeTsSelectOne(d.collapse);+ sbePaint();+ return;+ }+ if (d.mode === 'move' && d.toNew && !(d.ids && d.ids.length > 1)) {+ // DROPPED ON THE ADD ROW: a track of its own, at the second it was held.+ const cur = sbeTsFind(SBE.tracks, d.sid);+ const nt = sbeTsNewTrack(JSON.parse(d.base));+ const r = sbeTsMove(nt.tracks, d.sid, nt.added.id, cur ? cur.strip.film_start : d.fs0);+ if (r.ok) SBE.tracks = r.tracks;+ }+ if (JSON.stringify(SBE.tracks || []) === JSON.stringify(JSON.parse(d.before).tracks || [])) {+ sbePaint();+ return;+ }+ sbeTsCommit(d.before);+}++// HOVER TEACHES, on a track strip as on A1's.+function sbeTsGhost(ev) {+ const at = sbeTsStripAt(ev);+ let want = null;+ if (at) {+ const onLine = sbeStripY(sbeTsGainAt(at.f.track, at.f.strip, at.t), at.rect.height);+ if (Math.abs((ev.clientY - at.rect.top) - onLine) <= SBE_LVL_GRAB) {+ want = { id: '@ts:' + at.sid, t: sbeRound(at.t), g: sbeRound(at.g) };+ }+ }+ const now = SBE.kfGhost;+ const same = (!want && !(now && String(now.id).indexOf('@ts:') === 0))+ || (want && now && want.id === now.id && Math.abs(want.t - now.t) < 1e-4+ && Math.abs(want.g - now.g) < 2e-3);+ if (same) return;+ SBE.kfGhost = want;+ sbePaintTracks();+}++function sbeOnTsDbl(ev) {+ const at = sbeTsStripAt(ev);+ if (!at || ev.target.closest('.sbe-kf')) return;+ // SILENT WHEN A POINT IS ALREADY THERE — the first press of this very+ // double-click is what put it there.+ const r = sbeTsAddKeyframe(SBE.tracks, at.sid, at.t, sbeTsEnvGain(at.f, at.g));+ if (!r.ok) return;+ sbeTsSelectOne(at.sid);+ sbeTsMutate(() => r);+ ev.preventDefault();+}++// RIGHT-CLICK: on a point it removes the point; on a strip it opens the menu.+function sbeOnTsMenu(ev) {+ const blk = (ev.target && ev.target.closest) ? ev.target.closest('.sbe-tstrip') : null;+ if (!blk) return;+ const kf = ev.target.closest('.sbe-kf');+ if (kf) {+ const f = sbeTsFind(SBE.tracks, blk.dataset.strip);+ if (!f || f.strip.locked === true) return;+ ev.preventDefault();+ sbeTsSelectOne(blk.dataset.strip);+ sbeTsMutate(ts => sbeTsDeleteKeyframe(ts, blk.dataset.strip, sbeNum(kf.dataset.kf)));+ return;+ }+ sbeCtxOpen(ev);+}++// ---- where a sound comes from --------------------------------------------+// One door for the pool's +, a drop on a lane and "Add sound file…": the+// server probes the file (and brings it into the film's audio/ folder when+// the preview could not play it where it is), the client places the strip.+async function sbeTsAddSoundPath(path, tid, at) {+ sbeAudioTouch({ open: true });+ if (!SBE.open || !SBE.id) {+ phosToast('Open a __SEQ__ first — a sound belongs to a timeline.', {});+ return false;+ }+ const fd = new URLSearchParams();+ fd.set('id', SBE.id);+ fd.set('path', String(path || ''));+ let r;+ try {+ r = await (await fetch('/storyboard/edit/add-sound', { method: 'POST', body: fd })).json();+ } catch (e) { r = { ok: false, error: String(e) }; }+ if (!r || !r.ok) {+ phosToast((r && r.error) || 'That sound could not be added.', { kind: 'danger' });+ return false;+ }+ const dur = sbeRound(sbeNum(r.duration_s, 0));+ const strip = { id: sbeNewId(), path: r.path, start: 0, end: dur, film_start: 0,+ duration: dur, title: r.title || '' };+ const want = (at === undefined || at === null) ? SBE.playhead : sbeNum(at);+ const res = sbeTsMutate(ts => sbeTsPlace(ts, tid || '', strip, want));+ if (!res) return false;+ const idx = (SBE.tracks || []).findIndex(t => String(t.id) === String(res.track));+ sbeTsSelectOne(res.added.id);+ sbePaint();+ phosToast((r.imported ? 'Brought into this film\'s audio folder and put' : 'Put')+ + ' on ' + sbeTrackLabel(idx) + ' at ' + sbeFmtTime(res.added.film_start)+ + ' — drag it, trim either end, fade its corners.',+ { kind: 'success', duration: 6000 });+ if (ED.src === 'sound' && r.imported) edPoolRefresh(true);+ return true;+}++async function edPoolSound(i, tid, at) {+ if (ED.suppressClick && at === undefined) { ED.suppressClick = false; return; }+ const list = document.getElementById('edPoolList');+ const row = ((list || {})._rows || [])[i];+ if (!row) return;+ await sbeTsAddSoundPath(row.path, tid, at);+}++// "Add sound file…" — a path typed or pasted, the way A2's Change… takes one.+async function sbeAddSoundFile() {+ const inp = sbeEl('sbeSoundPath');+ const p = String((inp || {}).value || '').trim();+ if (!p) { phosToast('Paste the full path of a sound file first.', {}); return; }+ if (await sbeTsAddSoundPath(p, '', SBE.playhead)) {+ sbePopCloseAll('');+ if (inp) inp.value = '';+ }+}++// Where a pool row would land on the audio tracks: {tid, at}, or null.+function edPoolOverTracks(ev) {+ const box = sbeEl('sbeTracks');+ if (!box) return null;+ for (const el of Array.prototype.slice.call(box.children)) {+ const r = el.getBoundingClientRect();+ if (ev.clientX >= r.left && ev.clientX <= r.right+ && ev.clientY >= r.top && ev.clientY < r.bottom) {+ return { tid: el.dataset.track || 'new', at: Math.max(0, sbeTimeFromEvent(ev, el)) };+ }+ }+ return null;+}+async function edPoolOverlay(i) {const rows = (document.getElementById('edPoolList') || {})._rows || [];const r = rows[i];@@ -5594,7 +7224,10 @@ function sbeLvlHitPath(pts, xOf, yOf, x0, x1) {return d;}-function sbeStripWave(c, w, px) {+// `lvl` is the curve to draw when it is not the item's own envelope — an audio+// track strip's line carries its strip and track faders, exactly as the bed's+// carries `bed_gain`. Absent, the clip strip's envelope, as it always was.+function sbeStripWave(c, w, px, lvl) {const peaks = sbeWaveWant(c.path);// THE STRIP IS AS TALL AS THE LANE WAS DRAGGED TO. Everything below is// expressed in H, so a taller lane is not a stretched picture — it is more@@ -5616,7 +7249,7 @@ function sbeStripWave(c, w, px) {// THE LEVEL LINE, drawn ON the waveform because that is what it acts on.// Unity sits at the top: a gain of 1 is "all of it", and a line that fell// to the middle at unity would read as half.- const curve = sbeGainPoints(c, w.len);+ const curve = lvl || sbeGainPoints(c, w.len);const pts = curve.length ? curve : [[0, 1], [w.len, 1]];const yOf = g => sbeStripY(g, H);const xOf = t => (w.len > 0 ? (t / w.len) * px : 0);@@ -5686,6 +7319,8 @@ function sbeStripWave(c, w, px) {// so the line, the ghost, the click and the inspector cannot disagree about it.function sbeStripEditable(c) {if (!c || c.locked) return false;+ // A strip on an audio track has no picture to be linked to.+ if (c._ts) return true;if (c.has_audio === false) return false;return !sbeClipAudio(c).linked;}@@ -5761,6 +7396,7 @@ function sbeLevelClick(ev) {if (!r.ok) return false;SBE.clips = r.clips;SBE.sel = at.id;+ SBE.selLane = at.id;SBE.kfGhost = null;// The point it just made is the point the drag continues on, so a level is// set in one gesture rather than two.@@ -5783,7 +7419,8 @@ function sbeLevelClick(ev) {// other application on this machine keeps "remove".function sbeOnAudioMenu(ev) {const kf = ev.target && ev.target.closest ? ev.target.closest('.sbe-kf') : null;- if (!kf) return;+ // Anywhere else on a strip: the clip-sound menu, with the lane verbs in it.+ if (!kf) { sbeCtxOpen(ev); return; }const blk = ev.target.closest('.sbe-aclip');const c = blk ? sbeById(SBE.clips, blk.dataset.id) : null;if (!c || c.locked) return;@@ -5796,6 +7433,21 @@ function sbeOnAudioMenu(ev) {// put a point exactly where the playhead is, which is also the only way to// place one at a frame you have actually listened to.function sbeAddPointAtPlayhead() {+ if (String(SBE.sel || '').indexOf('@ts:') === 0) {+ const sid = String(SBE.sel).slice(4);+ const f = sbeTsFind(SBE.tracks, sid);+ if (!f) return;+ const w = sbeTsWindow(f.strip);+ const t = sbeNum(SBE.playhead) - w.film_start;+ if (t < -1e-6 || t > w.len + 1e-6) {+ phosToast('Move the playhead over this sound first — a point is placed where you '+ + 'are listening.', { duration: 6000 });+ return;+ }+ const at = Math.max(0, Math.min(w.len, t));+ sbeTsMutate(tracks => sbeTsAddKeyframe(tracks, sid, at, sbeGainAt(f.strip, w.len, at)));+ return;+ }const c = sbeById(SBE.clips, SBE.sel);if (!c) return;if (!sbeStripEditable(c)) {@@ -5827,6 +7479,18 @@ function sbeAddPointAtPlayhead() {// "Clear 4" button that appeared and disappeared in the rail. This is that// button, on the clip bar, over the whole selection.function sbeClearPoints() {+ const ts = sbeTsSelIds().filter(id => {+ const f = sbeTsFind(SBE.tracks, id);+ return f && sbeAfx(f.strip, sbeTsWindow(f.strip).len).points.length;+ });+ if (ts.length) {+ if (sbeTsMutateEach(ts, (tracks, id) => sbeTsPointsWrite(tracks, id, []))) {+ phosToast('Level points removed. The fades are untouched — those are the corner '+ + 'handles.', { duration: 6000 });+ }+ return;+ }+ if (sbeTsSelIds().length) return;const ids = sbeSelIds().filter(x => {const c = sbeById(SBE.clips, x);return c && sbeAfx(c, sbeClipAudio(c).len).points.length;@@ -5909,6 +7573,10 @@ function sbeAudioFadeCommit(edge, v) {}function sbeOnAudioDown(ev) {+ // SMALL IS A PICTURE OF THE SOUND, NOT A CONTROL SURFACE. One click opens+ // the area and selects what was clicked; the second one edits it, at a+ // height where the grips and the level line are big enough to hit.+ if (sbeAudioSmall()) { sbeAudioOpenFrom(ev); return; }// The sync flag is a BUTTON inside the strip, and pointerdown would start a// drag before its click ever fired.const badge = ev.target.closest('.sbe-sync');@@ -5932,7 +7600,7 @@ function sbeOnAudioDown(ev) {const blk1 = ev.target.closest('.sbe-aclip');const c1 = blk1 ? sbeById(SBE.clips, blk1.dataset.id) : null;if (c1 && !c1.locked) {- SBE.sel = c1.id;+ SBE.sel = c1.id; SBE.selLane = c1.id;// SHIFT-CLICK DELETES. A modifier rather than a second affordance// drawn on a 6px target, which would be a delete nobody meant.if (ev.shiftKey) {@@ -5954,7 +7622,7 @@ function sbeOnAudioDown(ev) {const blk0 = ev.target.closest('.sbe-aclip');const c0 = blk0 ? sbeById(SBE.clips, blk0.dataset.id) : null;if (c0) {- SBE.sel = c0.id;+ SBE.sel = c0.id; SBE.selLane = c0.id;const w0 = sbeClipAudio(c0);const e0 = sbeAfx(c0, w0.len);SBE.audioDrag = {@@ -5981,10 +7649,25 @@ function sbeOnAudioDown(ev) {if (!blk) return;const id = blk.dataset.id;SBE.sel = id;+ // THE SOUND WAS CLICKED, not the shot — so the clip bar's Duplicate copies+ // this sound onto an audio track instead of duplicating the picture.+ SBE.selLane = id;SBE.drag = null; // a pointerup lost off the edge must not wedge a laneconst c = sbeById(SBE.clips, id);if (!c) return;const w = sbeClipAudio(c);+ if (w.linked && !c.locked && ev.button === 2) { sbePaint(); return; } // the menu's+ if (w.linked && !c.locked) {+ // A LINKED STRIP CANNOT SLIDE, BUT IT CAN CHANGE LANE: which lane a sound+ // plays on moves nothing in time, so it needs no unlinking. A press that+ // never travels is still the instruction below, given on release.+ SBE.audioDrag = { id: id, mode: 'lane', x0: ev.clientX, y0: ev.clientY,+ before: sbeSnapshot(), moved: false };+ try { sbeEl('sbeAudioLane').setPointerCapture(ev.pointerId); } catch (e) {}+ ev.preventDefault();+ sbePaint();+ return;+ }if (w.linked) {// Not an error — an instruction. The toggle is one click away and the// inspector is already showing this clip.@@ -6006,7 +7689,7 @@ function sbeOnAudioDown(ev) {const grip = ev.target.closest('.sbe-grip');SBE.audioDrag = {id: id, mode: grip ? (grip.classList.contains('r') ? 'trimR' : 'trimL') : 'move',- x0: ev.clientX, fs0: w.film_start, fe0: w.film_start + w.len,+ x0: ev.clientX, y0: ev.clientY, fs0: w.film_start, fe0: w.film_start + w.len,before: sbeSnapshot(), moved: false,};blk.classList.add('is-drag');@@ -6043,8 +7726,21 @@ function sbeOnAudioMove(ev) {}const d = SBE.audioDrag;if (!d) return;- if (Math.abs(ev.clientX - d.x0) > 3) d.moved = true;+ if (Math.abs(ev.clientX - d.x0) > 3) { d.moved = true; d.xmoved = true; }+ if ((d.mode === 'move' || d.mode === 'lane')+ && Math.abs(ev.clientY - sbeNum(d.y0, ev.clientY)) > 6) d.moved = true;if (!d.moved) return;+ // UP OR DOWN IS THE LANE. The body of a strip — linked or not — goes to+ // whichever half of the A1 box the pointer is over; left and right stay time.+ if (d.mode === 'move' || d.mode === 'lane') {+ const want = sbeAudioLaneAtY(ev.clientY);+ const cl = sbeById(SBE.clips, d.id);+ if (want && cl && sbeSoundLane(cl) !== want) {+ const rl = sbeSetSoundLane(SBE.clips, d.id, want);+ if (rl.ok) SBE.clips = rl.clips;+ }+ if (d.mode === 'lane' || !d.xmoved) { sbePaint(); return; }+ }if (d.mode === 'afade') {const adt = (d.edge === 'out') ? -(ev.clientX - d.x0) / SBE.pps: (ev.clientX - d.x0) / SBE.pps;@@ -6056,6 +7752,13 @@ function sbeOnAudioMove(ev) {const dt = (ev.clientX - d.x0) / SBE.pps;const tol = SBE_SNAP_PX / SBE.pps;const marks = sbeMusicSnaps(SBE.clips); // the CUTS: what a J-cut aims at+ // ...and every OTHER clip's sound, on either lane: a crossfade is made by+ // pulling one strip's edge onto its neighbour's.+ for (const o of SBE.clips) {+ if (String(o.id) === String(d.id) || sbeKind(o) !== 'video') continue;+ const ow = sbeClipAudio(o);+ marks.push(ow.film_start, sbeRound(ow.film_start + ow.len));+ }const anchor = (d.mode === 'trimR') ? d.fe0 : d.fs0;const want = sbeSnapToList(Math.max(0, anchor + dt), marks, tol,sbeSnapEnabled(ev));@@ -6083,6 +7786,20 @@ function sbeOnAudioUp(ev) {SBE.audioDrag = null;if (!d) return;document.querySelectorAll('.sbe-aclip.is-drag').forEach(el => el.classList.remove('is-drag'));+ if (!d.moved && d.mode === 'lane') {+ const c0 = sbeById(SBE.clips, d.id);+ sbePaint();+ if (c0) {+ phosToast(sbeClipAudio(c0).coupled+ ? 'This sound is linked to its picture at ' + sbeDriftLabel(sbeAudioDrift(c0))+ + ' and moves with it. Press Unlink sound on the bar above the tracks to slide it on its own'+ + ' — or drag it up or down to the other sound lane.'+ : 'That clip\'s sound is linked to its picture. Press Unlink sound on the bar above the '+ + 'tracks to slide it under the neighbour — or drag it up or down to the other sound lane.',+ { duration: 6000 });+ }+ return;+ }if (!d.moved) { sbePaint(); return; }SBE.undo.push(d.before);if (SBE.undo.length > SBE_UNDO_MAX) SBE.undo.shift();@@ -6093,7 +7810,40 @@ function sbeOnAudioUp(ev) {sbeQueueSave();}+// WHICH LANE OF THE A1 BOX a pointer height is over: the top half is A, the+// bottom half B, clamped at both edges so a drag that strays over the picture+// or the music still means the nearer lane.+function sbeAudioLaneAtY(y) {+ const box = sbeEl('sbeAudioLane');+ if (!box) return 0;+ const r = box.getBoundingClientRect();+ if (!(r.height > 0)) return 0;+ return (sbeNum(y) - r.top) < r.height / 2 ? 1 : 2;+}++// "ALTERNATE SOUND LANES" — the one click that re-lays an existing timeline's+// clip sound A, B, A… without moving a picture or a sound. One undo step.+function sbeAlternateSel() {+ sbeAudioTouch({ open: true });+ sbePopCloseAll('');+ const ok = sbeMutate(cs => sbeAlternateLanes(cs));+ if (ok) {+ phosToast('Clip sound now alternates between lanes A and B — nothing moved in time. '+ + 'To crossfade two shots, unlink a sound, pull its edge under its neighbour on '+ + 'the other lane and fade both. Undo puts the lanes back.',+ { kind: 'success', duration: 9000 });+ }+ sbeBlurControl();+}++// One clip's sound onto the named lane — the right-click menu's verb.+function sbeSoundLaneSet(id, lane) {+ sbePopCloseAll('');+ sbeMutate(cs => sbeSetSoundLane(cs, id, lane));+}+function sbeToggleAudioLink() {+ sbeAudioTouch({ open: true });const c = sbeById(SBE.clips, SBE.sel);if (!c) return;const w = sbeClipAudio(c);@@ -6128,6 +7878,7 @@ function sbeToggleAudioLink() {}function sbeDeleteStripSel() {+ if (sbeTsDeleteSel(false)) return;const ids = sbeSelIds();if (!ids.length) return;if (ids.length > 1) {@@ -6147,6 +7898,13 @@ function sbeDeleteStripSel() {}function sbeToggleClipMute() {+ const ts = sbeTsSelIds();+ if (ts.length) {+ const f = sbeTsFind(SBE.tracks, String(SBE.sel).slice(4));+ const on = !(f && f.strip.muted === true);+ sbeTsMutateEach(ts, (tracks, id) => sbeTsSetStrip(tracks, id, { muted: on }));+ return;+ }const c = sbeById(SBE.clips, SBE.sel);if (!c) return;const on = !sbeClipMuted(c);@@ -6173,6 +7931,7 @@ function sbeToggleClipMute() {// inspector. An explicit `id` is a click on one flag and means that strip// alone; no id means the selection, which may be several.function sbeResyncSel(id) {+ sbeAudioTouch({ open: true });if (!id) {const ids = sbeSelIds().filter(x => {const c = sbeById(SBE.clips, x);@@ -6226,7 +7985,7 @@ function sbePaintHead() {// menu would have been two more chances to add a panel that Escape and a// click elsewhere could not shut.const SBE_POPS = ['sbeRenderMenu', 'sbeMoreMenu', 'sbeKeysPop', 'sbeMusicMenu',- 'sbeCbarMenu', 'sbeCtxMenu'];+ 'sbeCbarMenu', 'sbeCtxMenu', 'sbeSoundMenu'];function sbePopToggle(id, anchorId) {const el = sbeEl(id);@@ -6303,6 +8062,21 @@ function sbePaintHeads() {aud.textContent = bits.length ? bits.join(' · ') : 'linked to the picture';aud.classList.toggle('is-live', split > 0);}+ // THE SOUND AREA'S OWN CONTROL, on the head of the area it acts on — the+ // same place and the same 18px square the soundtrack's ▾ already uses.+ const sz = sbeEl('sbeAudioSize');+ if (sz) {+ const small = sbeAudioSmall();+ const hint = (typeof shortcutHint === 'function')+ ? shortcutHint('editor.soundLanes') : '';+ sz.textContent = small ? '▸' : '▾';+ sz.setAttribute('aria-expanded', small ? 'false' : 'true');+ sz.title = (small+ ? 'Sound lanes are small. Click to put them back at full height and keep them there'+ + (SBE.aPin === 'small' ? '' : ' — or click any sound to open them while you work')+ : 'Make the sound lanes small — A1, A2 and every audio track become thin strips so the '+ + 'picture gets the height. They come back the moment you touch a sound') + '.' + hint;+ }}// The legend is painted rather than written into the markup so there is one@@ -6335,6 +8109,10 @@ function sbePaintKeys() {// playback and every pixel of a scrub. So two callers share this: the full// paint, and the cheap per-frame refresh below.function sbeSplitWhy() {+ // With sounds on an audio track selected, Split cuts THEM — the blade goes+ // where the selection is, the way every NLE targets a selected clip.+ const ts = sbeTsSelIds();+ if (ts.length) return sbeTsSplitWhy(ts);const under = sbeClipAt(SBE.clips, SBE.playhead);if (!under) {return 'Put the playhead over a shot first — this cuts whatever is under '@@ -6361,15 +8139,139 @@ function sbeCbarPlayhead() {const el = sbeEl('sbeCbSplit');if (!el) return;const why = sbeSplitWhy();- const want = why || SBE_SPLIT_TITLE;+ const want = why || (sbeTsSelIds().length ? SBE_TS_SPLIT_TITLE : SBE_SPLIT_TITLE);if (el.title !== want) el.title = want;if (el.disabled !== !!why) el.disabled = !!why;}const SBE_SPLIT_TITLE = 'Cuts the shot under the playhead into two at the '+ 'playhead. Nothing moves and nothing is lost.' + sbeKeyHint('editor.split');+const SBE_TS_SPLIT_TITLE = 'Cuts the selected sound into two at the playhead. '+ + 'Nothing moves; its fades and level points stay where they were.' + sbeKeyHint('editor.split');++// DUPLICATE, READ FOR WHATEVER KIND OF SOUND IS SELECTED. The owner: "the+// duplicate button is disabled when you're touching the sound/music area." The+// A2 bed had no clip id, so the selection was empty and the button grey; an A1+// strip duplicated the SHOT. Both now copy the SOUND onto an audio track.+function sbeSoundLaneSel() {+ const c = sbeById(SBE.clips, SBE.sel);+ return !!(c && SBE.selLane && String(SBE.selLane) === String(c.id)+ && sbeSelCount() === 1);+}++function sbeCbarDupRow(n, many, c, noSel) {+ const hint = sbeKeyHint('editor.duplicate');+ const row = { id: 'sbeCbDup', act: 'sbeDuplicateSel()', label: 'Duplicate' };+ if (SBE.sel === '@music') {+ const r = sbeTsFromBed(SBE.audio, SBE.peaks ? SBE.peaks.duration : 0);+ return Object.assign(row, { why: r.why || '',+ title: 'Copies the soundtrack onto an audio track, right after itself — A2 '+ + 'holds one strip, so the copy lands on the first audio track with '+ + 'room there, or on a new one.' + hint });+ }+ if (c && sbeSoundLaneSel()) {+ const r = sbeTsFromClip(c);+ return Object.assign(row, { why: r.why || '',+ title: 'Copies this clip\'s sound onto an audio track, right after itself — '+ + 'the shot is not copied. It lands on the first audio track with room '+ + 'there, or on a new one.' + hint });+ }+ return Object.assign(row, { why: n ? '' : noSel,+ title: (many ? 'Each selected shot again, right behind itself'+ : 'The same shot again, right after this one')+ + ' — window, speed, fades and grade included. Everything after '+ + 'it slides.' + hint });+}++// WHY SPLIT CANNOT CUT the selected track sounds, or '' when it can.+function sbeTsSplitWhy(ids) {+ let locked = false;+ for (const id of ids || []) {+ const f = sbeTsFind(SBE.tracks, id);+ if (!f) continue;+ const w = sbeTsWindow(f.strip);+ const off = SBE.playhead - w.film_start;+ if (off >= SBE_TRACK_STRIP_MIN && w.len - off >= SBE_TRACK_STRIP_MIN) {+ if (f.strip.locked === true) locked = true; else return '';+ }+ }+ return locked+ ? 'The sound under the playhead is locked. Unlock it to cut it.'+ : 'Put the playhead inside the selected sound first — Split cuts it there.'+ + sbeKeyHint('editor.split');+}++// THE CLIP BAR FOR SOUNDS ON AN AUDIO TRACK. The same ten buttons in the same+// places, saying what each one does to a sound. Link and Resync stay grey and+// say why: a strip on a track has no picture to be linked to.+function sbeCbarTsModel(ids) {+ const n = ids.length;+ const many = n > 1;+ const f = sbeTsFind(SBE.tracks, String(SBE.sel).slice(4)) || sbeTsFind(SBE.tracks, ids[0]);+ const s = f.strip;+ const some = many ? ('all ' + n + ' sounds') : 'this sound';+ const noPic = 'A sound on an audio track has no picture of its own — Link, Unlink and '+ + 'Resync are for a clip\'s sound on A1.';+ const pts = ids.reduce((a, id) => {+ const g = sbeTsFind(SBE.tracks, id);+ return a + (g ? sbeAfx(g.strip, sbeTsWindow(g.strip).len).points.length : 0);+ }, 0);+ const rows = [+ { id: 'sbeCbSplit', act: 'sbeSplitHere()', label: 'Split', why: sbeTsSplitWhy(ids),+ title: SBE_TS_SPLIT_TITLE },+ { id: 'sbeCbLift', act: 'sbeLiftSelected()', label: 'Lift', why: '',+ title: 'Takes ' + some + ' off its track and leaves the silence, so nothing after '+ + 'it moves.' + sbeKeyHint('editor.lift') },+ { id: 'sbeCbRipple', act: 'sbeRippleSelected()', label: 'Ripple delete', why: '',+ title: 'Takes ' + some + ' off and closes the gap on that track — the sounds after '+ + 'it on the same track slide earlier. The picture and the other tracks do '+ + 'not move.' + sbeKeyHint('editor.ripple') },+ { id: 'sbeCbDup', act: 'sbeDuplicateSel()', label: 'Duplicate', why: '',+ title: (many ? 'Each selected sound again, right after itself'+ : 'The same sound again, right after itself')+ + ' on its own track — or at the next free spot on it. Trim, level, fades '+ + 'and points included.' + sbeKeyHint('editor.duplicate') },+ { id: 'sbeCbLink', act: 'sbeToggleAudioLink()', icon: '#ic-unlink',+ label: 'Unlink sound', why: noPic, title: noPic },+ { id: 'sbeCbResync', act: 'sbeResyncSel()', label: 'Resync sound', why: noPic,+ title: noPic },+ { id: 'sbeCbMute', act: 'sbeToggleClipMute()',+ icon: s.muted === true ? '#ic-sound' : '#ic-mute',+ label: s.muted === true ? 'Unmute sound' : 'Mute sound', on: s.muted === true, why: '',+ title: s.muted === true+ ? 'Lets ' + some + ' play again.'+ : 'Switches ' + some + ' off — in the preview, the render and the export. The '+ + 'strip stays where it is.' },+ { id: 'sbeCbDelSound', act: 'sbeDeleteStripSel()', label: 'Delete sound', why: '',+ title: 'Removes ' + some + ' from its track. Nothing else moves. Undo brings it '+ + 'back.' },+ { id: 'sbeCbPoints', act: 'sbeClearPoints()', label: 'Clear points',+ why: pts ? '' : 'This sound has no level anchors on it. Click the yellow line on '+ + 'the strip — or double-click the strip — to put one down.',+ title: 'Deletes the level anchors — the dots on the yellow line — from '+ + (many ? 'every selected sound' : 'this sound') + '. The corner fades are '+ + 'not points and are left alone.' },+ { id: 'sbeCbLock', act: 'sbeToggleLock()',+ icon: s.locked === true ? '#ic-unlock' : '#ic-lock',+ label: s.locked === true ? 'Unlock' : 'Lock', on: s.locked === true, why: '',+ title: s.locked === true+ ? 'Lets ' + some + ' move and trim again.'+ : 'Pins ' + some + ' to its place — it cannot be dragged, trimmed or shaped '+ + 'until it is unlocked.' },+ { id: 'sbeCbFaceFix', act: 'sbeFaceFixSel()', label: 'Face Fix ×2',+ why: 'A sound has no picture to upscale — select a clip on the picture lane.',+ title: 'A sound has no picture to upscale — select a clip on the picture lane.' },+ ];+ const name = s.title || String(s.path || '').split('/').pop() || 'sound';+ return { rows: rows, count: n, many: many,+ who: many ? (n + ' sounds selected') : (sbeNiceName(name) + ' · ' + sbeTrackLabel(f.ti)),+ whoWhy: 'Sounds on audio tracks. Shift-click or ⌘-click a second strip to '+ + 'add it; click a shot to go back to the picture.' };+}function sbeCbarModel() {+ const tsIds = sbeTsSelIds();+ if (tsIds.length) return sbeCbarTsModel(tsIds);const ids = sbeSelIds();const n = ids.length;const many = n > 1;@@ -6385,7 +8287,10 @@ function sbeCbarModel() {const splitWhy = sbeSplitWhy();const pick = 'Click a shot on the track. Shift-click a second one to take '+ 'the range between them, ⌘-click to add or drop one.';- const noSel = (!n && SBE.ovSel) ? 'A title or card is selected, not a shot '+ const noSel = (!n && SBE.sel === '@music')+ ? 'The soundtrack on A2 is selected, not a shot — its file, mode and level '+ + 'are on the A2 head, and Duplicate copies it onto an audio track. ' + pick+ : (!n && SBE.ovSel) ? 'A title or card is selected, not a shot '+ '— its own controls are in the panel on the right, and '+ '⌫ removes it. ' + pick: ((!n && SBE.txSel) ? 'A cut is selected, not a shot — set its '@@ -6403,12 +8308,7 @@ function sbeCbarModel() {why: n ? '' : noSel,title: 'Takes ' + some + ' out and CLOSES the gap — everything after '+ 'slides earlier and the film gets shorter.' + sbeKeyHint('editor.ripple') },- { id: 'sbeCbDup', act: 'sbeDuplicateSel()', label: 'Duplicate',- why: n ? '' : noSel,- title: (many ? 'Each selected shot again, right behind itself'- : 'The same shot again, right after this one')- + ' — window, speed, fades and grade included. Everything after '- + 'it slides.' + sbeKeyHint('editor.duplicate') },+ sbeCbarDupRow(n, many, c, noSel),// THE SOUND GROUP. Link and Resync are adjacent on purpose: the thing// that is hard to hold in your head is the difference between them, and// side by side both tooltips can say it.@@ -6479,10 +8379,28 @@ function sbeCbarModel() {: 'Pins ' + some + ' to its place on the film — everything else '+ 'flows around it, and it cannot be dragged or trimmed until it '+ 'is unlocked.' },+ // UPSCALE & FACE FIX, on the clip itself. Queues the face-safe 2× of the+ // clip's file; the timeline is not touched until the person says so.+ // Short label on the bar (the full name did not fit at 1512 px and fell+ // into More); the tooltip and the right-click menu carry the full name.+ { id: 'sbeCbFaceFix', act: 'sbeFaceFixSel()', label: 'Face Fix ×2', menuLabel: 'Upscale & Face Fix',+ why: !n ? noSel+ : (many ? 'Pick one clip — each fix is its own render.'+ : (!vid ? 'Only a video clip can be upscaled — a still or a black '+ + 'slug has no frames to fix.' : '')),+ title: 'Upscale & Face Fix — renders this clip again at twice the size with LTX-2.5 detail, '+ + 'keeping the face and the sound. It runs in the queue; when it '+ + 'lands, a line above the timeline offers to swap it in — same '+ + 'cut, same in and out points. The original file is not changed.' },];// The one readout that makes the rest of the row legible.+ // A SOUND IS NAMED AS A SOUND, so "Duplicate" beside it reads as copying+ // the sound: the A2 bed, or the A1 strip of the clip that was clicked.let who = 'Nothing selected';- if (many) who = n + ' clips selected';+ if (SBE.sel === '@music') who = 'Soundtrack (A2)';+ else if (c && sbeSoundLaneSel()) {+ who = 'Sound of ' + sbeNiceName(c.title || String(c.path || '').split('/').pop() || 'clip');+ } else if (many) who = n + ' clips selected';else if (c) {who = (kind === 'slug') ? 'Black': sbeNiceName(c.title || String(c.path || '').split('/').pop() || 'clip');@@ -6617,7 +8535,10 @@ function sbeCtxOpen(ev) {if (!menu) return;const gap = ev.target.closest ? ev.target.closest('.sbe-gap') : null;const blk = ev.target.closest ? ev.target.closest('.sbe-clip') : null;- if (!gap && !blk) return;+ const tsb = ev.target.closest ? ev.target.closest('.sbe-tstrip') : null;+ const ablk = (ev.target.closest && ev.target.closest('#sbeAudioLane'))+ ? ev.target.closest('.sbe-aclip') : null;+ if (!gap && !blk && !tsb && !ablk) return;ev.preventDefault();sbePopCloseAll('');let html = '';@@ -6632,6 +8553,47 @@ function sbeCtxOpen(ev) {+ '<button type="button" class="sbe-cbar-btn" onclick="sbeGenOpen('+ at.toFixed(4) + ',' + dur.toFixed(4) + ')" title="Render a new shot '+ 'to fill exactly these seconds.">Generate a shot here…</button>';+ } else if (ablk) {+ // A CLIP'S OWN SOUND: the clip bar's verbs for that sound, then its lane.+ if (!sbeSelHas(ablk.dataset.id) || sbeSelCount() !== 1) sbeSelectOne(ablk.dataset.id);+ SBE.selLane = ablk.dataset.id;+ sbePaint();+ const m = sbeCbarModel();+ html = '<div class="sbe-ctx-h">' + escapeHtml(m.who) + '</div>';+ for (const r of m.rows) {+ if (r.why) continue;+ html += '<button type="button" class="sbe-cbar-btn" onclick="'+ + escapeHtml(r.act) + '" title="' + escapeHtml(r.title) + '">'+ + escapeHtml(r.label) + '</button>';+ }+ const ac = sbeById(SBE.clips, ablk.dataset.id);+ html += '<span class="sbe-pop-sep"></span>';+ if (ac && !ac.locked) {+ const other = sbeSoundLane(ac) === 2 ? 1 : 2;+ html += '<button type="button" class="sbe-cbar-btn" onclick="sbeSoundLaneSet('+ + escapeHtml(JSON.stringify(String(ac.id))) + ',' + other + ')" title="Puts this '+ + 'sound on sound lane ' + sbeLaneName(other) + '. Nothing moves in time; sounds on the '+ + 'two lanes can overlap and crossfade.">Move sound to lane ' + sbeLaneName(other)+ + '</button>';+ }+ html += '<button type="button" class="sbe-cbar-btn" onclick="sbeAlternateSel()" '+ + 'title="Lays every clip\'s sound A, B, A, B… in film order, so neighbouring shots '+ + 'sit on different lanes and can overlap and crossfade. Nothing moves in time; one '+ + 'Undo puts it back.">Alternate sound lanes</button>';+ } else if (tsb) {+ // A SOUND ON AN AUDIO TRACK gets the same table's verbs, for sounds.+ if (sbeTsSelIds().indexOf(String(tsb.dataset.strip)) < 0) {+ sbeTsSelectOne(tsb.dataset.strip);+ sbePaint();+ }+ const m = sbeCbarModel();+ html = '<div class="sbe-ctx-h">' + escapeHtml(m.who) + '</div>';+ for (const r of m.rows) {+ if (r.why) continue;+ html += '<button type="button" class="sbe-cbar-btn" onclick="'+ + escapeHtml(r.act) + '" title="' + escapeHtml(r.title) + '">'+ + escapeHtml(r.label) + '</button>';+ }} else {// A right-click on a shot that is NOT in the selection selects it, which// is what every program does; a right-click INSIDE a selection leaves the@@ -6643,7 +8605,7 @@ function sbeCtxOpen(ev) {if (r.why) continue; // only what can actually firehtml += '<button type="button" class="sbe-cbar-btn" onclick="'+ escapeHtml(r.act) + '" title="' + escapeHtml(r.title) + '">'- + escapeHtml(r.label) + '</button>';+ + escapeHtml(r.menuLabel || r.label) + '</button>';}// REORDER LIVES HERE NOW. It used to be shift+drag, and shift had to go// to the range selection the owner asked for — so the gesture moved to@@ -6662,6 +8624,10 @@ function sbeCtxOpen(ev) {+ 'onclick="sbeReorderSel(1)" title="Swaps this shot with the one '+ 'after it. The film stays exactly as long.">Move later</button>';}+ html += '<button type="button" class="sbe-cbar-btn" onclick="sbeAlternateSel()" '+ + 'title="Lays every clip\'s sound A, B, A, B… in film order, so neighbouring shots '+ + 'sit on different lanes and can overlap and crossfade. Nothing moves in time; one '+ + 'Undo puts it back.">Alternate sound lanes</button>';}menu.innerHTML = html;menu.hidden = false;@@ -6823,6 +8789,7 @@ function sbePaintInspector() {'</div></div>';return;}+ if (sbePaintTsInspector(box)) return;const c = sbeById(SBE.clips, SBE.sel);if (!c) {const n = SBE.clips.length;@@ -7376,6 +9343,7 @@ function sbeOnTrackDown(ev) {return;}const id = blk.dataset.id;+ SBE.selLane = ''; // a click on the PICTURE means the shotSBE.ovSel = ''; // one inspector, one subjectSBE.txSel = '';SBE.audioDrag = null; // same insurance the lane takes against the other@@ -7947,6 +9915,8 @@ window.ED = { src: 'film', rows: [], films: [], film: '', loading: false,function edPoolSrc(name) {ED.src = name;+ // Opening the Sound pool is somebody going to put a sound somewhere.+ if (name === 'sound') sbeAudioTouch({ open: true });const tabs = document.getElementById('edPoolTabs');if (tabs) tabs.querySelectorAll('.pill-btn').forEach(b =>b.classList.toggle('active', b.dataset.src === name));@@ -8061,6 +10031,16 @@ async function edPoolRefresh(force) {const seen = {};ED.rows = (ED.uploaded || []).concat(mine, gallery).filter(row => (row.path && !seen[row.path]) && (seen[row.path] = 1));+ } else if (ED.src === 'sound') {+ // SOUNDS, for the audio tracks: this film's own audio/ folder first,+ // then every sound file the engines left at the top of the outputs.+ const r = SBE.id+ ? await (await fetch('/storyboard/edit/sounds?id=' + encodeURIComponent(SBE.id))).json()+ : null;+ ED.rows = ((r && r.sounds) || []).map(o => ({+ path: o.path, title: o.name, kind: 'sound',+ sub: (o.where === 'film' ? 'this __SEQ__’s audio' : 'outputs') + ' · sound',+ }));} else {const r = await (await fetch('/outputs?limit=400&offset=0')).json();ED.rows = ((r && r.outputs) || [])@@ -8170,7 +10150,9 @@ function edPoolPaint() {// An image has no frame to seek to, so it is an <img> — and the /image// route's own `w=` resize is what keeps a 14 MB PNG from being decoded at// full size for a 44 px thumbnail.- (r.kind === 'still'+ (r.kind === 'sound'+ ? '<span class="ed-pool-snd" aria-hidden="true">♪</span>'+ : r.kind === 'still'? '<img alt="" data-src="/image?w=180&path=' + encodeURIComponent(r.path) + '">': '<video preload="metadata" muted playsinline data-src="/file?path=' +encodeURIComponent(r.path) + '#t=0.1"></video>') +@@ -8178,9 +10160,20 @@ function edPoolPaint() {'<span class="ed-pool-name">' + escapeHtml(sbeNiceName(r.title || '')) + '</span>' +'<span class="ed-pool-sub">' + escapeHtml(r.sub || '') + '</span>' +'</span>' +- '<button type="button" class="ed-pool-add" ' +- 'title="Put this clip at the end of the __SEQ__" ' +- 'onclick="event.stopPropagation();edPoolAdd(' + i + ')">+</button>' ++ (r.kind === 'sound'+ ? '<button type="button" class="ed-pool-add" ' ++ 'title="Put this sound on an audio track at the playhead" ' ++ 'onclick="event.stopPropagation();edPoolSound(' + i + ')">+</button>'+ : '<button type="button" class="ed-pool-add" ' ++ 'title="Put this clip at the end of the __SEQ__" ' ++ 'onclick="event.stopPropagation();edPoolAdd(' + i + ')">+</button>') ++ // A VIDEO CAN GIVE ITS SOUND ALONE — onto an audio track, at the playhead,+ // with no picture.+ ((!r.kind || r.kind === 'video')+ ? '<button type="button" class="ed-pool-add ed-pool-ov" ' ++ 'title="Put only this clip’s sound on an audio track at the playhead" ' ++ 'onclick="event.stopPropagation();edPoolSound(' + i + ')">♪</button>'+ : '') +// AN IMAGE CAN BE A CARD. A transparent PNG belongs on the overlay lane,// not at the end of the picture track, and this is the one click that// says so — it lands at the playhead, where you are looking.@@ -8250,6 +10243,8 @@ async function edPoolAdd(i, dropAt) {// on a <button>, so without this flag every drop would also add the clip a// second time, at the end of the track.if (ED.suppressClick && dropAt === undefined) { ED.suppressClick = false; return; }+ // A SOUND HAS NO PICTURE to put on V1 — it goes on an audio track.+ if (row.kind === 'sound') { await sbeTsAddSoundPath(row.path, '', SBE.playhead); return; }if (!SBE.open || !SBE.id) {phosToast('Open a __SEQ__ first — the Editor holds one timeline at a time.', {});return;@@ -8358,10 +10353,15 @@ function edPoolDragMove(ev) {d.ghost.style.left = (ev.clientX + 12) + 'px';d.ghost.style.top = (ev.clientY + 12) + 'px';const track = sbeEl('sbeTrack');- const over = edPoolOverTrack(ev, track);- track.classList.toggle('is-dropping', over);+ // A SOUND lands on an audio track only; a VIDEO dropped on one gives its+ // sound; anything dropped on the picture track is a clip, as before.+ const onTracks = edPoolOverTracks(ev);+ const over = !onTracks && d.row.kind !== 'sound' && edPoolOverTrack(ev, track);+ track.classList.toggle('is-dropping', !!over);SBE.dropAt = over ? edPoolDropTime(ev, track) : null;+ SBE.tsDrop = (onTracks && d.row.kind !== 'still') ? onTracks : null;sbePaintTrack();+ sbePaintTracks();}// The film time under the pointer, snapped to the boundary a drop would use —@@ -8393,7 +10393,10 @@ async function edPoolDragEnd(ev) {if (track) track.classList.remove('is-dropping');const at = SBE.dropAt;SBE.dropAt = null;+ const tsDrop = SBE.tsDrop;+ SBE.tsDrop = null;sbePaintTrack();+ sbePaintTracks();if (!d.moved) return; // a press that never travelled// ARMED ONLY IF THE CLICK IS ACTUALLY COMING. "A drag ends in a click event// on the row it started from" is true for a press that never left the row@@ -8402,6 +10405,7 @@ async function edPoolDragEnd(ev) {// a clip on the timeline, click another clip to preview it, and the source// monitor does nothing until you click a second time.ED.suppressClick = !!(d.el && ev.target && d.el.contains(ev.target));+ if (tsDrop) { await edPoolSound(d.index, tsDrop.tid, tsDrop.at); return; }if (at === null || at === undefined) return; // dropped in open spaceawait edPoolAdd(d.index, at);}@@ -8449,14 +10453,28 @@ function sbePaintRelink() {if (!tb) return;tb.hidden = !takes.length;if (!takes.length) return;- tb.innerHTML = takes.map(r =>- '<span class="sbe-relink-row">' +- '<span>New take of <b>' + escapeHtml(sbeNiceName(r.title || ('shot ' + r.n))) + '</b> is ready.</span>' +- '<button type="button" class="ghost-btn" onclick="sbeRetakeUse(\'' + escapeHtml(r.id) + '\')" ' +- 'title="Replace the clip with the new take. Same cut, same timings.">Use it</button>' +- '<button type="button" class="ghost-btn" onclick="sbeRetakeKeep(\'' + escapeHtml(r.id) + '\', \'' + escapeHtml(r.to) + '\')" ' +- 'title="Keep the take that is on the timeline. The new one stays in the media pool.">Keep the old one</button>' +- '</span>').join('');+ // Arguments go through JSON inside a double-quoted attribute: a file name+ // with an apostrophe must not end the handler's string.+ const arg = v => escapeHtml(JSON.stringify(String(v == null ? '' : v)));+ tb.innerHTML = takes.map(r => {+ const nm = escapeHtml(sbeNiceName(r.title || ('shot ' + r.n)));+ return '<span class="sbe-relink-row">' ++ (r.face_fix+ ? '<span><b>Upscale & Face Fix</b> of <b>' + nm + '</b> is ready.</span>'+ : '<span>New take of <b>' + nm + '</b> is ready.</span>') ++ '<button type="button" class="ghost-btn" onclick="' + (r.face_fix ? 'sbeFaceFixSwap(' : 'sbeRetakeUse(')+ + arg(r.id) + ', ' + arg(r.to) + ')" ' ++ 'title="' + (r.face_fix+ ? 'Swap the clip for the fixed version. Same cut, same in and out points.'+ : 'Replace the clip with the new take. Same cut, same timings.') + '">' ++ (r.face_fix ? 'Swap it in' : 'Use it') + '</button>' ++ '<button type="button" class="ghost-btn" onclick="sbeRetakeKeep(' + arg(r.id) + ', ' + arg(r.to) + ')" ' ++ 'title="' + (r.face_fix+ ? 'Keep the clip that is on the timeline. The fixed version stays in Outputs.'+ : 'Keep the take that is on the timeline. The new one stays in the media pool.') + '">' ++ 'Keep the old one</button>' ++ '</span>';+ }).join('');}// "Keep the old one" is a decision about ONE file against ONE clip, kept in@@ -8476,7 +10494,7 @@ function sbeRetakeKeep(id, to) {} catch (e) {}sbePaintRelink();}-async function sbeRetakeUse(id) {+async function sbeRetakeUse(id, to) {if (SBE.dirty && !SBE.conflict && !(await sbeSave(true))) {phosToast('Your arrangement could not be saved, and the swap works on the saved file — fix the save first.',{ kind: 'danger', duration: 8000 });@@ -8485,6 +10503,7 @@ async function sbeRetakeUse(id) {const fd = new URLSearchParams();fd.set('id', SBE.id);fd.set('only', id);+ if (to) fd.set('to', to);let r;try { r = await (await fetch('/storyboard/edit/relink', { method: 'POST', body: fd })).json(); }catch (e) { r = { ok: false, error: String(e) }; }@@ -8494,6 +10513,97 @@ async function sbeRetakeUse(id) {phosToast('The new take is on the timeline. Same cut, same timings.', { kind: 'success', duration: 5000 });}+// SWAP IN A FACE FIX — an ordinary local edit, not a server rewrite: the+// clip's file changes, its in/out points, speed, fades and place do not; Undo+// puts the original back and the normal save writes it. Nothing is adopted+// from the server, so an edit made meanwhile can never be lost. The server+// only builds the proxy (add-clip with a bare path changes no timeline).+async function sbeFaceFixSwap(id, to) {+ const film = SBE.id;+ const row = (SBE.relink || []).find(x => x.face_fix && String(x.id) === String(id)+ && String(x.to) === String(to));+ const c0 = sbeById(SBE.clips, id);+ if (!row || !c0 || String(c0.path) !== String(row.path)) {+ phosToast('That clip has changed since the fix was ordered — nothing was swapped.', {});+ return;+ }+ if (c0.locked) { phosToast('That clip is locked — unlock it first.', {}); return; }+ const fd = new URLSearchParams();+ fd.set('id', film);+ fd.set('path', to);+ let r;+ try { r = await (await fetch('/storyboard/edit/add-clip', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r || !r.ok) { phosToast((r && r.error) || 'The fixed clip could not be loaded.', { kind: 'danger' }); return; }+ const c = SBE.id === film ? sbeById(SBE.clips, id) : null;+ if (!c || String(c.path) !== String(row.path) || c.locked) {+ phosToast('That clip changed while the fixed file was loading — nothing was swapped.', {});+ return;+ }+ const before = sbeSnapshot();+ c.path = to;+ c.proxy = (r.clip && r.clip.proxy) || null;+ SBE.undo.push(before);+ if (SBE.undo.length > SBE_UNDO_MAX) SBE.undo.shift();+ SBE.redo.length = 0;+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ SBE.relink = (SBE.relink || []).filter(x => x !== row);+ sbePaint();+ sbePaintRelink();+ sbeQueueSave();+ phosToast('The fixed clip is on the timeline — same cut, same in and out points. Undo puts the original back.',+ { kind: 'success', duration: 6000 });+}++// UPSCALE & FACE FIX from the clip bar / right-click. The same server door as+// the player button (faceFixClip), plus the film and clip ids so the finished+// file is offered against THIS clip. The arrangement is saved first: the offer+// is matched against the saved timeline.+async function sbeFaceFixSel() {+ const film = SBE.id;+ const c = sbeById(SBE.clips, SBE.sel);+ if (!c || sbeKind(c) !== 'video' || sbeSelCount() !== 1) {+ phosToast('Select one video clip first.', {});+ return;+ }+ if (SBE.saving) {+ phosToast('Saving — press it again in a moment.', { duration: 4000 });+ return;+ }+ if (SBE.conflict) {+ phosToast('This film was changed in another tab — resolve that first; the fix is offered ' ++ 'against the saved timeline.', { kind: 'danger', duration: 8000 });+ return;+ }+ if (SBE.dirty && (await sbeSave(true)) !== true) {+ phosToast('Your arrangement could not be saved, and the fix is offered against the saved ' ++ 'timeline — fix the save first.', { kind: 'danger', duration: 8000 });+ return;+ }+ if (SBE.id !== film || !sbeById(SBE.clips, c.id)) return; // another film opened meanwhile+ const r = await faceFixClip(c.path, {+ board: film, clip: c.id,+ doneHint: 'Upscale & Face Fix queued for ' + sbeNiceName(c.title || String(c.path).split('/').pop())+ + '. When it lands, a line above the timeline offers to swap it in.',+ });+}++// Refresh ONLY the swap offers. A full sbeLoad would adopt the whole+// arrangement, and an edit made while the request is out would be lost.+async function sbeRefreshOffers() {+ const id = SBE.id;+ let r;+ try {+ r = await (await fetch('/storyboard/edit?id=' + encodeURIComponent(id)+ + '&session=' + encodeURIComponent(SBE.session))).json();+ } catch (e) { return false; }+ if (!r || !r.ok || SBE.id !== id) return false;+ SBE.relink = r.relink || [];+ sbePaintRelink();+ return true;+}+async function sbeRelink() {const btn = sbeEl('sbeRelinkBtn');if (btn) btn.disabled = true;@@ -8831,9 +10941,13 @@ const SBE_STRIP_VOICES = 3;// stutter; letting it drift further than a quarter second would be audible.const SBE_STRIP_SLIP = 0.25;-function sbeStripPool() {+// `n` is how many voices this frame needs. The pool grows to it (capped — a+// browser allows a document only so many media elements) because audio+// tracks overlap by design: a laugh, a sting and a bed over a J-cut is five.+function sbeStripPool(n) {if (!SBE.stripEls) SBE.stripEls = [];- while (SBE.stripEls.length < SBE_STRIP_VOICES) {+ const need = Math.max(SBE_STRIP_VOICES, Math.min(16, Math.round(sbeNum(n, 0))));+ while (SBE.stripEls.length < need) {const a = new Audio();a.preload = 'auto';a.dataset.clip = '';@@ -8848,8 +10962,10 @@ function sbeStripPool() {// the ground, so "close enough" is the wrong answer.function sbeStripSync(force) {if (!SBE.open) return;- const pool = sbeStripPool();- const want = sbeStripsAt(SBE.clips, SBE.playhead);+ // A1's strips AND every audio track's, one voice each, driven the same way.+ const want = sbeStripsAt(SBE.clips, SBE.playhead)+ .concat(sbeTsAt(SBE.tracks, SBE.playhead));+ const pool = sbeStripPool(want.length + 1);const live = {};for (const w of want) live[w.id] = w;// A voice whose strip has gone quiet is released BEFORE any is claimed, or@@ -8882,12 +10998,20 @@ function sbeStripSync(force) {// or the one place the user checks his work is the one place the fade// does not exist. `w.at - w.start` is the STRIP-relative second, which is// the envelope's own clock.- const c2 = sbeById(SBE.clips, w.id);- const win = c2 ? sbeClipAudio(c2) : null;- // The envelope's clock is the strip AS PLAYED — film seconds into it —- // which is `(source second - in-point) / speed`.- a.volume = win ? sbeGainAt(c2, win.len, (w.at - win.start) / win.speed) : 1;- try { a.playbackRate = win ? win.speed : 1; } catch (e) {}+ if (w.vol !== undefined) {+ // AN AUDIO TRACK STRIP brings its volume with it: the same curve the+ // render's `volume` is built from (envelope × strip fader × track+ // fader), at this second of the strip. It plays at 1x.+ a.volume = Math.max(0, Math.min(1, sbeNum(w.vol, 1)));+ try { a.playbackRate = 1; } catch (e) {}+ } else {+ const c2 = sbeById(SBE.clips, w.id);+ const win = c2 ? sbeClipAudio(c2) : null;+ // The envelope's clock is the strip AS PLAYED — film seconds into it —+ // which is `(source second - in-point) / speed`.+ a.volume = win ? sbeGainAt(c2, win.len, (w.at - win.start) / win.speed) : 1;+ try { a.playbackRate = win ? win.speed : 1; } catch (e) {}+ }try {if (fresh || force || Math.abs(a.currentTime - w.at) > SBE_STRIP_SLIP) {a.currentTime = w.at;@@ -9032,7 +11156,64 @@ function sbeOnTlWheel(ev) {// and on a selection of one they take the SAME path they always did, with the// same toast, because that is the behaviour on disk, in the tests and in the// owner's hands. Only the plural case is new.+// LIFT, RIPPLE AND DELETE SOUND on track strips. Right to left, so a ripple+// never slides a later victim out from under the ids it was handed.+function sbeTsDeleteSel(ripple) {+ const ts = sbeTsSelIds();+ if (!ts.length) return false;+ const order = ts.map(id => sbeTsFind(SBE.tracks, id)).filter(Boolean)+ .sort((a, b) => sbeNum(b.strip.film_start) - sbeNum(a.strip.film_start))+ .map(f => String(f.strip.id));+ const done = sbeTsMutateEach(order, (tracks, id) => sbeTsDelete(tracks, id, ripple));+ if (done) { SBE.sel = ''; SBE.tsSet = []; sbePaint(); }+ return true;+}++// DUPLICATE ON SOUND. A track strip is copied right after itself on its own+// track; the A2 bed and an A1 clip's sound are copied onto an audio track,+// because A2 holds one strip and A1 belongs to its picture. True when the+// selection was a sound (whether or not it could act), false for a shot.+function sbeTsDuplicateSel() {+ const ts = sbeTsSelIds();+ if (ts.length) {+ const done = sbeTsMutateEach(ts, (tracks, id) => sbeTsDuplicate(tracks, id));+ if (done) {+ const made = done.map(r => String(r.added.id));+ SBE.tsSet = made;+ SBE.sel = '@ts:' + made[0];+ sbePaint();+ }+ sbeBlurControl();+ return true;+ }+ let src = null;+ let from = '';+ if (SBE.sel === '@music') {+ src = sbeTsFromBed(SBE.audio, SBE.peaks ? SBE.peaks.duration : 0);+ from = 'soundtrack';+ } else if (sbeSoundLaneSel()) {+ src = sbeTsFromClip(sbeById(SBE.clips, SBE.sel));+ from = 'clip\'s sound';+ } else {+ return false;+ }+ if (!src.strip) { phosToast(src.why, { duration: 7000 }); return true; }+ const r = sbeTsMutate(tracks => sbeTsPlace(tracks, '', src.strip, src.strip.film_start));+ if (r) {+ const i = (SBE.tracks || []).findIndex(t => String(t.id) === String(r.track));+ sbeTsSelectOne(r.added.id);+ sbePaint();+ phosToast('Copied the ' + from + ' onto ' + sbeTrackLabel(i) + ' at '+ + sbeFmtTime(r.added.film_start) + ', right after the original. It plays '+ + 'with everything above it; drag it wherever it belongs.',+ { duration: 7000 });+ }+ sbeBlurControl();+ return true;+}+function sbeRippleSelected() {+ if (sbeTsDeleteSel(true)) return;const ids = sbeSelIds();if (!ids.length) return;if (ids.length === 1) {@@ -9050,6 +11231,7 @@ function sbeRippleSelected() {}function sbeLiftSelected() {+ if (sbeTsDeleteSel(false)) return;const ids = sbeSelIds();if (!ids.length) return;if (ids.length === 1) sbeMutate(cs => sbeLiftDelete(cs, ids[0]));@@ -9059,6 +11241,7 @@ function sbeLiftSelected() {}function sbeDuplicateSel() {+ if (sbeTsDuplicateSel()) return;const many = sbeSelIds();if (many.length > 1) {// Each selected shot gets its own copy right behind it, and the COPIES@@ -9085,10 +11268,33 @@ function sbeDuplicateSel() {}function sbeSplitHere() {+ const ts = sbeTsSelIds();+ if (ts.length) {+ const at = SBE.playhead;+ const under = ts.filter(id => {+ const f = sbeTsFind(SBE.tracks, id);+ if (!f) return false;+ const w = sbeTsWindow(f.strip);+ return at > w.film_start && at < w.film_end;+ });+ if (!under.length) {+ phosToast('Put the playhead inside the selected sound first — Split cuts it there.', {});+ return;+ }+ sbeTsMutateEach(under, (tracks, id) => sbeTsSplit(tracks, id, at));+ return;+ }sbeMutate(cs => sbeSplitAt(cs, SBE.playhead, undefined, SBE.transitions || []));}function sbeToggleLock() {+ const ts = sbeTsSelIds();+ if (ts.length) {+ const f = sbeTsFind(SBE.tracks, String(SBE.sel).slice(4));+ const on = !(f && f.strip.locked === true);+ sbeTsMutateEach(ts, (tracks, id) => sbeTsSetStrip(tracks, id, { locked: on }));+ return;+ }const ids = sbeSelIds();const first = sbeById(SBE.clips, ids[0]);if (!first) return;@@ -9463,6 +11669,29 @@ async function sbeTick() {// A shot generated into a hole is rendering somewhere in the panel's one// queue. Poll for it — but never while the user has unsaved work in flight,// because a reload would be a reload over their arrangement.+ // Face Fixes ordered for this film — including retries and ones ordered+ // before a reload: any finished job in the queue history that names this+ // film is a reason to fetch the offers (only the offers). A job counts as+ // handled only after a fetch that worked.+ if (!SBE.fixBusy) {+ const hist = ((globalThis.LAST_STATUS || {}).history) || [];+ const landed = hist.filter(j => j && j.status === 'done' && !SBE.fixHandled[j.id]+ && ((j.params || {}).face_fix_targets || []).some(t => t && t[0] === SBE.id));+ if (landed.length) {+ SBE.fixBusy = true;+ const before = (SBE.relink || []).filter(x => x.face_fix).length;+ try {+ if (await sbeRefreshOffers()) {+ landed.forEach(j => { SBE.fixHandled[j.id] = 1; });+ const now = (SBE.relink || []).filter(x => x.face_fix && !sbeRetakeDismissed(x)).length;+ if (now > before) {+ phosToast('Upscale & Face Fix is ready — swap it in from the line above the timeline.',+ { kind: 'success', duration: 6000 });+ }+ }+ } finally { SBE.fixBusy = false; }+ }+ }if (SBE.awaitingClip && !SBE.dirty && !SBE.drag && !SBE.saving) {const before = (SBE.unplaced || []).length;await sbeLoad(true);@@ -9536,6 +11765,12 @@ document.addEventListener('keydown', (ev) => {// they cannot be hit while reaching for L or R, and because the bare// letters are worth keeping free for the J/K/L transport this timeline does// not have yet.+ // ⇧A — THE SOUND AREA'S SIZE, on a key, because it is the one thing on this+ // screen you reach for with both hands already on the timeline.+ if (ev.shiftKey && !ev.metaKey && !ev.ctrlKey && !ev.altKey+ && (ev.key === 'A' || ev.key === 'a')) {+ ev.preventDefault(); sbeAudioPinToggle(); return;+ }if (ev.shiftKey && !ev.metaKey && !ev.ctrlKey && (ev.key === 'L' || ev.key === 'l')) {ev.preventDefault(); sbeToggleAudioLink(); return;}@@ -9681,6 +11916,8 @@ document.addEventListener('click', (ev) => {lane.addEventListener('pointerup', sbeOnMusicUp);lane.addEventListener('pointercancel', sbeOnMusicUp);lane.addEventListener('dblclick', sbeOnMusicDbl);+ lane.addEventListener('pointerenter', () => sbeAudioOver(true));+ lane.addEventListener('pointerleave', () => sbeAudioOver(false));// The ghost belongs to the pointer, so it goes when the pointer does.lane.addEventListener('pointerleave', () => {if (SBE.kfGhost && SBE.kfGhost.id === '@music') {@@ -9689,8 +11926,20 @@ document.addEventListener('click', (ev) => {}});}+ // THE POINTER ON THE SOUND AREA OPENS IT, which is also how anybody finds+ // out that it opens: the lanes answer before they are used. On the+ // CONTAINERS, which outlive every repaint of the strips inside them.+ const gutter = document.getElementById('sbeGutter');+ if (gutter) {+ gutter.addEventListener('pointermove', (ev) => sbeAudioOver(+ !!(ev.target.closest+ && ev.target.closest('.sbe-gh-aud, .sbe-gh-mus, .sbe-gh-trk, .sbe-gh-add'))));+ gutter.addEventListener('pointerleave', () => sbeAudioOver(false));+ }const alane = document.getElementById('sbeAudioLane');if (alane) {+ alane.addEventListener('pointerenter', () => sbeAudioOver(true));+ alane.addEventListener('pointerleave', () => sbeAudioOver(false));alane.addEventListener('pointerdown', (ev) => { sbeStop(); sbeOnAudioDown(ev); });alane.addEventListener('dblclick', sbeOnAudioDbl);alane.addEventListener('pointermove', sbeOnAudioMove);@@ -9701,6 +11950,25 @@ document.addEventListener('click', (ev) => {alane.addEventListener('pointerleave', sbeAudioGhostClear);alane.addEventListener('contextmenu', sbeOnAudioMenu);}+ // THE AUDIO TRACKS. On the container, which outlives every repaint of the+ // lanes and strips inside it — the rule the music lane states above.+ const tlanes = document.getElementById('sbeTracks');+ if (tlanes) {+ tlanes.addEventListener('pointerdown', sbeOnTsDown);+ tlanes.addEventListener('pointermove', sbeOnTsMove);+ tlanes.addEventListener('pointerup', sbeOnTsUp);+ tlanes.addEventListener('pointercancel', sbeOnTsUp);+ tlanes.addEventListener('dblclick', sbeOnTsDbl);+ tlanes.addEventListener('pointerenter', () => sbeAudioOver(true));+ tlanes.addEventListener('pointerleave', () => sbeAudioOver(false));+ tlanes.addEventListener('contextmenu', sbeOnTsMenu);+ tlanes.addEventListener('pointerleave', () => {+ if (SBE.kfGhost && String(SBE.kfGhost.id).indexOf('@ts:') === 0) {+ SBE.kfGhost = null;+ sbePaintTracks();+ }+ });+ }const scrubbers = ['sbeRuler', 'sbeWave', 'sbeWaveNone'];for (const id of scrubbers) {const el = document.getElementById(id);@@ -9897,7 +12165,7 @@ Object.assign(globalThis, {sbeDeliverGet, sbeDeliverPick, sbeDeliverPaint, sbeDuplicate, sbeDuplicateSel,sbeFraming, sbeFramingIsNeutral, sbeSetFraming, sbeApplyPreviewFraming, sbeFramingPreview,sbeFramingCommit, sbeFramingReset,- sbeRetakeKeep, sbeRetakeUse,+ sbeRetakeKeep, sbeRetakeUse, sbeFaceFixSel, sbeFaceFixSwap,sbeOvTextPlace, sbeBlurControl,sbeTxById, sbeTxAfter, sbeTxDuration, sbeTxSpare, sbeTxResolve, sbeTxEdges,sbeTxSet, sbeTxDelete, sbeTxPrune, sbeTxRepoint, sbeTxMutate, sbeTxCommit,@@ -9973,4 +12241,28 @@ Object.assign(globalThis, {sbeCbarModel, sbePaintCbar, sbeCbarFit, sbeCbarStamp,sbeSplitWhy, sbeCbarPlayhead,sbeCtxOpen, sbeReorderSel, sbeSplitHere, sbeGenOpen,+ // THE AUDIO TRACKS — the model (for the harnesses) and every name the+ // generated heads, strips, inspector and pool rows call back into.+ sbeTrackLabel, sbeUnitGain, sbeTrackGain, sbeTsGain, sbeTsWindow, sbeTsGainPoints,+ sbeTsGainAt, sbeTsCopy, sbeTsTrackById, sbeTsFind, sbeTsSort, sbeTsFits, sbeTsNearest,+ sbeTsNextFree, sbeTsNewTrack, sbeTsRemoveTrack, sbeTsSetTrack, sbeTsPlace, sbeTsMove,+ sbeTsMoveGroup, sbeTsTrim, sbeTsSplit, sbeTsCopyTitle, sbeTsDuplicate, sbeTsDelete,+ sbeTsSetStrip, sbeTsSetFade, sbeTsPointsWrite, sbeTsAddKeyframe, sbeTsMoveKeyframe,+ sbeTsDeleteKeyframe, sbeTsAt, sbeTsSnaps, sbeTsFromClip, sbeTsFromBed, sbeTsClean,+ sbeTsSelIds, sbeTsSelectOne, sbeTsSelectToggle, sbeTsMutateEach, sbeTsMutate,+ sbeSoundLaneSel, sbeCbarDupRow, sbeTsSplitWhy, sbeCbarTsModel, sbeTsDeleteSel,+ sbeTsDuplicateSel, sbeTracksExtraH, sbePaintTracks, sbePaintTrackHeads, sbeTsCommit,+ sbeTrackAdd, sbeTrackRemove, sbeTrackMute, sbeTrackRename, sbeTrackGainSlide,+ sbeTrackGainCommit, sbeTsGainSlide, sbeTsGainCommit, sbeTsFadeCommit,+ sbePaintTsInspector, sbeTsStripAt, sbeTsLaneAt, sbeTsEnvGain, sbeTsLevelClick,+ sbeOnTsDown, sbeOnTsMove, sbeOnTsUp, sbeTsGhost, sbeOnTsDbl, sbeOnTsMenu,+ sbeTsAddSoundPath, edPoolSound, sbeAddSoundFile, edPoolOverTracks,+ // THE TWO CLIP-SOUND LANES — the model (for the harnesses) and the verbs the+ // head button and the right-click menu call.+ sbeSoundLane, sbeLaneName, sbeSetSoundLane, sbeAlternateLanes, sbeLaneAfter, sbeLaneFit,+ sbeExtraLanesH, sbeAudioLaneAtY, sbeAlternateSel, sbeSoundLaneSet,+ sbeLaneBase, sbeLaneCap, sbeTlFloor, sbeTlRoof, sbeAudioSmall, sbeAudioBusy,+ sbeAudioWant, sbeAudioSync, sbeAudioArm, sbeAudioSet, sbeAudioTouch,+ sbeAudioOver, sbeAudioOpenFrom, sbeAudioPinRead, sbeAudioPinWrite,+ sbeAudioPinSet, sbeAudioPinToggle, sbeAudioSmallOnce,});diff --git a/webapp/js/engines.js b/webapp/js/engines.jsindex 45e3767..78da45b 100644--- a/webapp/js/engines.js+++ b/webapp/js/engines.js@@ -70,6 +70,7 @@ function engineServesMode(e, mode) {// offering a choice that changes nothing.function _currentSurface() {const wf = (document.body.dataset.workflow || 'manual').toLowerCase();+ if (wf === 'audio' && musicComposeActive()) return 'music';// 'storyboard' MUST be in this map. Without it the `|| 'video'` fallback// leaves the engine switcher visible in a tab that has no engine choice to// offer — the film decides per shot, not a global toggle.@@ -97,6 +98,7 @@ function engineRenderable(e) {// download already has with the High pill). A new engine adds a key here the// day it has a status function; nothing else in this file changes.window._ENGINE_PROBES = {+ music: (BOOT.music || { capable: false, available: false, estimates: {} }),h3: (BOOT.h3 || { capable: false, available: false, tiers: [] }),};// H3 keeps its own binding because the H3 tier / Turbo / export code below is@@ -178,7 +180,9 @@ function h3CurrentCell() {let savedUp = null;try { savedUp = localStorage.getItem('phos_h3_upscale'); } catch (e) {}const allowed = H3.upscale_modes || ['off', 'fit_720p', 'fit_1080p'];- if (savedUp && allowed.indexOf(savedUp) !== -1) up.value = savedUp;+ // The after-the-draft Upscale & Face Fix is an extra job, so a reload+ // starts with it OFF even if an older panel saved it as the preference.+ if (savedUp && savedUp !== 'ltx_x2' && allowed.indexOf(savedUp) !== -1) up.value = savedUp;// And again for the sampler-depth pills, same reason.const st = document.getElementById('h3_steps');if (!st) return;@@ -230,17 +234,35 @@ function _h3SyncExportNote() {// Export canvas for an H3 render. Separate from the LTX `upscale` control// (which is data-ltx-only and folds away on H3) so one pill never means two// things. Server-side make_job re-validates — a stale tab must never win.+// "ltx_x2" is the stored value of the OPTIONAL after-the-draft Upscale & Face+// Fix (a checkbox under the pills): the draft ships as rendered and the fix is+// queued behind it. It is never saved as the preference; the size the user had+// is, so unticking the box returns to it.function setH3Upscale(mode) {const allowed = H3.upscale_modes || ['off', 'fit_720p', 'fit_1080p'];const v = allowed.indexOf(mode) !== -1 ? mode : (H3.default_upscale || 'fit_720p');const inp = document.getElementById('h3_upscale');if (inp) inp.value = v;+ const fix = v === 'ltx_x2';+ const shown = fix ? 'off' : v;+ const grp = document.getElementById('h3UpscaleGroup');+ if (grp) grp.classList.toggle('is-overridden', fix);document.querySelectorAll('#h3UpscaleGroup [data-h3-upscale]').forEach(b =>- b.classList.toggle('active', b.dataset.h3Upscale === v));- try { localStorage.setItem('phos_h3_upscale', v); } catch (e) {}+ b.classList.toggle('active', b.dataset.h3Upscale === shown));+ const box = document.getElementById('h3FaceFixAfter');+ if (box) box.checked = fix;+ const row = document.getElementById('h3FaceFixAfterRow');+ if (row) row.hidden = allowed.indexOf('ltx_x2') === -1;+ if (!fix) { try { localStorage.setItem('phos_h3_upscale', v); } catch (e) {} }_h3SyncExportNote();if (typeof updateDerived === 'function') { try { updateDerived(); } catch (e) {} }}+function setH3FaceFixAfter(on) {+ if (on) { setH3Upscale('ltx_x2'); return; }+ let size = null;+ try { size = localStorage.getItem('phos_h3_upscale'); } catch (e) {}+ setH3Upscale(size && size !== 'ltx_x2' ? size : (H3.default_upscale || 'fit_720p'));+}document.querySelectorAll('#h3UpscaleGroup [data-h3-upscale]').forEach(b => {b.onclick = () => setH3Upscale(b.dataset.h3Upscale);});@@ -593,7 +615,8 @@ document.querySelectorAll('#h3LoraSlotGroup [data-h3-lora-slot]').forEach(b => {// gate exists to prevent. (Old name kept: it is what the rest of this file// calls.)function _engineRowVisible() {- return ENGINES.filter(e => engineRenderable(e) && e.state !== 'announced').length > 1;+ const count = ENGINES.filter(e => engineRenderable(e) && e.state !== 'announced').length;+ return count > 1 || (_currentSurface() === 'music' && count === 1);}// ---- The header switcher ----------------------------------------------------@@ -694,7 +717,8 @@ function renderEngineSwitch() {if (div) div.hidden = !show;if (!show) { box.innerHTML = ''; closeEngineMenu(); return; }- const active = currentEngine();+ const active = _currentSurface() === 'music' ? 'music' : currentEngine();+ const surfaceMode = _currentSurface() === 'music' ? 'music' : currentMode;const list = ENGINES.filter(engineRenderable);// ---- The trigger: the active engine, and nothing else ----@@ -703,7 +727,7 @@ function renderEngineSwitch() {box.innerHTML = `<button type="button" class="eng-trigger" aria-haspopup="listbox"aria-expanded="false"style="--eng-accent:${escapeHtml(act.accent)};--eng-dim:${escapeHtml(act.accent_dim)};--eng-soft:${escapeHtml(act.accent_soft)}"- title="${escapeHtml(_engineTooltip(act, engineStatus(act), engineServesMode(act, currentMode)))}">+ title="${escapeHtml(_engineTooltip(act, engineStatus(act), engineServesMode(act, surfaceMode)))}"><span class="eng-mark"><svg class="ph" aria-hidden="true"><use href="#${escapeHtml(act.mark)}"/></svg></span><span class="eng-seg-name">${escapeHtml(act.label)}</span>${act.generation ? `<span class="eng-seg-gen">${escapeHtml(act.generation)}</span>` : ''}@@ -718,7 +742,7 @@ function renderEngineSwitch() {menu.innerHTML = list.map(e => {const st = engineStatus(e);const offer = !e.builtin && !st.announced && st.capable && !st.available;- const modeOk = engineServesMode(e, currentMode);+ const modeOk = engineServesMode(e, surfaceMode);// Four badges, four different sentences. An OFFER (download / repair) is// worth the engine's own colour; a constraint is not.let badge = '', badgeClass = '';@@ -1452,7 +1476,7 @@ function setH3Tier(key) {Object.assign(globalThis, {engineById, defaultEngine, engineStatus, engineServesMode,h3ResolveTierKey, h3TierByKey, h3CellFor, h3CurrentCell,- setH3Upscale, setH3Orientation, setH3Steps, h3TurboPillSub,+ setH3Upscale, setH3FaceFixAfter, setH3Orientation, setH3Steps, h3TurboPillSub,renderH3Turbo, setH3Turbo, syncModeStripToEngine, renderEngineSwitch,renderTierAxes, renderH3Axes, ltxCellFor, ltxCurrentQuality,ltxCurrentLength, ltxCurrentCell, ltxCellEta, ltxCellNeedsInstall,diff --git a/webapp/js/main.js b/webapp/js/main.jsindex 27e6f18..cab37ff 100644--- a/webapp/js/main.js+++ b/webapp/js/main.js@@ -8,6 +8,7 @@// future 'call this once at startup' line belongs HERE, not at the top// level of a feature module.// ====== Init ======+musicInit();// Skip poll when the tab is backgrounded — at 1.5s cadence with a fan-// spinning render in the background, every saved request matters. Pinokio// users park the panel in a tab and switch to other apps for the 5–20 mindiff --git a/webapp/js/preview.js b/webapp/js/preview.jsindex fc34afc..38dee18 100644--- a/webapp/js/preview.js+++ b/webapp/js/preview.js@@ -1862,7 +1862,22 @@ async function refreshModelsModal({ silent = false } = {}) {</li>`;}}- list.innerHTML = (rows + h3Row) || `<li class="empty-state">No model manifest found — required_files.json is missing or unreadable.</li>`;+ let musicRow = '';+ const music = (LAST_STATUS && LAST_STATUS.music) || BOOT.music;+ if (music && music.capable) {+ const statusText = music.available+ ? `Ready · Compose unlocked in the Audio tab · ${escapeHtml(music.root || '')}`+ : music.repairable ? 'Weights on disk · engine needs repair'+ : `Available to install · one click in the Pinokio sidebar · ~11 GB · needs ${music.min_ram_gb} GB unified memory`;+ musicRow = `<li class="${music.available ? 'ready' : 'missing'}">+ <span class="icon">♪</span><div class="meta">+ <span class="ttl">YuE2 · music engine</span>+ <span class="sub">Lyrics and a style description in, a finished song out — vocals and arrangement together</span>+ <span class="sub">${statusText}</span></div>+ ${music.available ? '<button class="ghost" disabled>Installed</button>' : '<button onclick="openMusicInstallCard()">How to install</button>'}+ </li>`;+ }+ list.innerHTML = (rows + h3Row + musicRow) || `<li class="empty-state">No model manifest found — required_files.json is missing or unreadable.</li>`;// Footer summarises required vs optional counts.// Count only what THIS BUILD needs. 2.3's two base rows were inside// "Required: N/M ready", which made §7.1's first-visit contractdiff --git a/webapp/js/queue.js b/webapp/js/queue.jsindex 6ae4d49..b34eb40 100644--- a/webapp/js/queue.js+++ b/webapp/js/queue.js@@ -353,6 +353,7 @@ function _h3ServesMode(mode) {}function setEngine(engine, opts) {+ if (engine === 'music') { audioModeSet('compose'); workflowSwitch('audio'); return; }opts = opts || {};const fallback = defaultEngine();const note = document.getElementById('engineRowNote');@@ -1711,6 +1712,10 @@ async function repairModel(key) {// instead of leaving them with the engine wording.function friendlyJobError(raw) {raw = raw || 'unknown error';+ if (/music engine isn't installed|YuE2 needs about|YuE2 weights.*repair/i.test(raw)) {+ return { friendly: 'Stopped before generating — the music engine is not ready.',+ hint: 'Install or repair it from the Phosphene sidebar in Pinokio. Everything else in the panel is unaffected.' };+ }const rawLower = String(raw).toLowerCase();if (rawLower.includes('sigkill')) {return { friendly: 'Helper killed by the OS — out of memory (jetsam).',@@ -1970,6 +1975,7 @@ async function poll() {// Hailuo H3 install state — refreshes the engine pill in place when the// pack lands (or disappears), same live-unlock contract Q8 already has.if (typeof updateH3Availability === 'function') updateH3Availability(s);+ updateMusicAvailability(s);// The pack-incomplete gate, BEFORE the render rather than 30 s into it.if (typeof applyPackIncompleteGate === 'function') {try { applyPackIncompleteGate(s); } catch (e) {}@@ -2316,8 +2322,12 @@ async function poll() {// A One Shot is named as one: the t2v/i2v underneath is how it is// rendered, not what was asked for.const _take = j.params.take && j.params.take.seconds;- const params = (j.params.mode === 'image')+ const params = j.params.engine === 'music'+ ? `YuE2 · ${j.params.music_quality} · max ${j.params.music_max_seconds}s`+ : (j.params.mode === 'image')? `image · ${j.params.aspect || '?'} · n=${j.params.n || '?'}`+ : (j.params.mode === 'upscale')+ ? `${FACE_FIX_NAME} · 2×`: _take? `One Shot · ${_take} s · ${j.params.width}×${j.params.height}`: `${j.params.mode} · ${j.params.width}×${j.params.height} · ${j.params.frames}f`;@@ -2355,7 +2365,7 @@ async function poll() {const filtered = s.history.filter(j => {if (filterPhotos === 'all') return true;const isPhoto = (j.params && j.params.mode === 'image');- return filterPhotos === 'photos' ? isPhoto : !isPhoto;+ return filterPhotos === 'photos' ? isPhoto : !isPhoto && j.params.engine !== 'music';});// Memoized on the same principle as the queue list above: identical data// must not trigger an innerHTML replacement every 1.5 s. Unmemoized, the 20@@ -2435,10 +2445,17 @@ async function poll() {// cancellation often means "wrong intent, try again with edits" but// sometimes "ran out of RAM, want to retry as-is."const isRetryable = j.status === 'failed' || j.status === 'cancelled';+ const _p = j.params || {};+ const canFaceFix = j.status === 'done' && j.output_path && _p.mode !== 'upscale'+ && _p.mode !== 'train' && /\.(mp4|mov|m4v|webm|mkv)$/i.test(String(j.output_path));const actionHtml = isRetryable? `<button class="retry-btn" type="button"title="Re-submit this job with the same params"onclick='retryJob(${JSON.stringify(j.id)})'>Retry</button>`+ : canFaceFix+ ? `<button class="retry-btn facefix-btn" type="button"+ title="Upscale & Face Fix — queue a 2× re-render of this clip that keeps the face and the sound. The fixed clip lands next to it."+ onclick="faceFixClip(${escapeHtml(JSON.stringify(j.output_path))})">Face Fix</button>`: '';// Same film badge the queue rows carry, so a shot is identifiable// wherever the bottom pane shows it.@@ -2489,7 +2506,7 @@ async function poll() {// mp4 input. Filter to videos so the user can't accidentally pick a// .png as an Extend source (which would 400 server-side).const sel = document.getElementById('extendSrcSelect');- const videoOutputs = currentOutputs.filter(o => !isPhotoOutputMain(o));+ const videoOutputs = currentOutputs.filter(o => outputKind(o) === 'video');const _videoOpts = '<option value="">— pick an output below or paste a path —</option>' +videoOutputs.slice(0, 40).map(o => `<option value="${escapeHtml(o.path)}">${escapeHtml(o.name)}</option>`).join('');sel.innerHTML = _videoOpts;@@ -2904,6 +2921,7 @@ function animateFromPhoto(payload) {// pre-date the elapsed_sec field, or outputs whose sidecar got// deleted) so the slot is never empty.function _outputDurationLabel(o) {+ if (outputKind(o) === 'audio' && o.clip_sec != null) return _humanDuration(o.clip_sec);// Lead with what the file IS (its length), then how long it took, labeled.// "1 h 20 m" alone on a 10-second clip read as a broken duration// (Mr Bizarro 2026-08-10: "preview is not accurate") — same confusion as@@ -2963,7 +2981,8 @@ function renderCarousel() {const _hiddenCount = visible.length - _visibleSlice.length;el.innerHTML = _visibleSlice.map(o => {const pathAttr = JSON.stringify(o.path).replace(/"/g, '"');- const isPhoto = isPhotoOutputMain(o);+ const isPhoto = outputKind(o) === 'image';+ const isAudio = outputKind(o) === 'audio';// Thumbnail markup branches on kind. Videos use <video> with a// mid-clip seek (2.5s — LTX clips are 5s at 24fps and the first// half-second is often a dark fade-in, so seeking to the middle@@ -2984,7 +3003,9 @@ function renderCarousel() {// ~2-screen-tall preload margin. Off-screen cards stay completely// dormant. <img> already has loading="lazy" so it's fine; we keep// the existing markup for photos.- const thumbHtml = isPhoto+ const thumbHtml = isAudio+ ? `<span class="music-card-note" aria-hidden="true">♪</span><audio class="train-voice-audio music-card-player" controls preload="metadata" src="${escapeHtml(o.url)}" onclick="event.stopPropagation()"></audio>`+ : isPhoto? `<img class="car-thumb" src="${_thumbUrl(o.url, 480)}" alt="${escapeHtml(o.name)}" loading="lazy">`// Hover-scrub: on enter, jump to 0 and play silently at 0.6×;// on leave, pause + snap back to the static 2.5s preview frame.@@ -3022,6 +3043,11 @@ function renderCarousel() {title="Re-run this prompt + seed + refs at Quality (auto-submits)"onclick="event.stopPropagation(); remakeInQuality(${remakeArgs})">✦ Quality</button>`: '';+ // Upscale & Face Fix — one click, on video cards only.+ const faceFixChip = (isPhoto || isAudio) ? ''+ : `<button class="card-action card-action-facefix" type="button"+ title="Upscale & Face Fix — queue a 2× re-render of this clip that keeps the face and the sound. The fixed clip lands next to it; this one is not changed."+ onclick="event.stopPropagation(); faceFixClip(${escapeHtml(JSON.stringify(o.path))})">Upscale & Face Fix</button>`;return `<div class="car-card${o.path === activePath ? ' active' : ''}"data-path="${escapeHtml(o.path)}" onclick="selectOutput(${pathAttr})">@@ -3034,6 +3060,8 @@ function renderCarousel() {<div class="card-chrome">${remakeChip}${animateChip}+ ${isAudio ? `<button class="card-action card-action-photo" type="button" title="Load this track into Audio → Video (does not auto-submit)" onclick="event.stopPropagation();useTrackInA2V(${pathAttr})">Drive video</button>` : ''}+ ${faceFixChip}<button class="card-action card-action-danger" type="button" title="Move this file to the Trash — asks first"onclick="event.stopPropagation(); deleteOutput(${pathAttr})"><svg class="ph" aria-hidden="true"><use href="#ph-trash-simple"/></svg></button></div>@@ -3199,7 +3227,8 @@ function selectOutput(path, options) {// the player ends up on the cached stale-bytes URL and re-shows black// until the browser cache expires.const o = findOutputByPath(path);- const isPhoto = isPhotoOutputMain(o);+ const isPhoto = outputKind(o) === 'image';+ const isAudio = outputKind(o) === 'audio';// Photo entries don't go through /file (which is OUTPUT-bound and// serves video with Range headers). Use /image which supports both// OUTPUT and UPLOADS roots, with the right MIME headers. Server-side@@ -3217,7 +3246,9 @@ function selectOutput(path, options) {// Photo viewer is a static <img> — no controls, no autoplay (would// be a no-op on an image element anyway). Video viewer keeps the// existing controls + autoplay behaviour.- if (isPhoto) {+ if (isAudio) {+ wrap.innerHTML = `<audio class="train-voice-audio" controls preload="metadata"${autoplay ? ' autoplay' : ''} src="${escapeHtml(playerSrc)}"></audio>`;+ } else if (isPhoto) {wrap.innerHTML = `<img src="${escapeHtml(playerSrc)}" alt="${o ? escapeHtml(o.name) : ''}">`;} else if (liveBackdrop) {wrap.innerHTML =@@ -3291,7 +3322,7 @@ function selectOutput(path, options) {document.getElementById('playerOverlayName').textContent = o ? o.name : '';const rel = o ? _relTimeFromMtime(o.mtime) : '';const sizeLbl = o ? `${o.size_mb.toFixed(1)} MB` : '';- const kindLbl = isPhoto ? 'Photo' : 'Video';+ const kindLbl = isPhoto ? 'Photo' : isAudio ? 'Audio' : 'Video';document.getElementById('playerOverlayMeta').innerHTML = o? `<span>${kindLbl}</span><span class="po-dot"></span>` +`<span>${escapeHtml(rel)}</span><span class="po-dot"></span>` +@@ -3302,7 +3333,7 @@ function selectOutput(path, options) {// Load params is video-only — image sidecars use the library@1 schema// which doesn't carry the i2v/t2v form fields the loader expects.- document.getElementById('loadParamsBtn').disabled = !(o && o.has_sidecar) || isPhoto;+ document.getElementById('loadParamsBtn').disabled = !(o && o.has_sidecar) || isPhoto || isAudio;// Action button row: swap "Use as Extend" for "Animate" on photo// entries (Extend is video-only, but the still can be the seed for// an i2v render).@@ -3323,11 +3354,11 @@ function selectOutput(path, options) {// /status payload as o.engine) — not the form's current engine, which is// about the next render and says nothing about this clip.const outIsH3 = !!(o && o.engine === 'h3');- if (useExtBtn) useExtBtn.style.display = (isPhoto || outIsH3) ? 'none' : '';- // Upscale ×2 is video-only but engine-agnostic: an H3 draft is exactly the- // clip it was built for.- const useUpBtn = document.getElementById('useAsUpscaleBtn');- if (useUpBtn) useUpBtn.style.display = isPhoto ? 'none' : '';+ if (useExtBtn) useExtBtn.style.display = (isPhoto || isAudio || outIsH3) ? 'none' : '';+ // Upscale & Face Fix is video-only but engine-agnostic: an H3 draft is+ // exactly the clip it was built for.+ const useUpBtn = document.getElementById('faceFixWrap');+ if (useUpBtn) useUpBtn.style.display = (isPhoto || isAudio) ? 'none' : '';if (animBtn) animBtn.style.display = isPhoto ? '' : 'none';// "Finish at …" — for a completed H3 render that has a higher canvas to be// committed at. Decided from o.engine / o.h3_tier (both sidecar-derived,@@ -3349,10 +3380,13 @@ function openExpandLightbox() {const stage = document.getElementById('expandStage');const meta = document.getElementById('expandMeta');if (!lb || !stage) return;- const isPhoto = isPhotoOutputMain(o);+ const isPhoto = outputKind(o) === 'image';+ const isAudio = outputKind(o) === 'audio';// Build the media element fresh each time so the previous selection's// <video> stops decoding immediately.- stage.innerHTML = isPhoto+ stage.innerHTML = isAudio+ ? `<audio class="train-voice-audio" src="${escapeHtml(o.url)}" controls autoplay></audio>`+ : isPhoto? `<img src="${o.url}" alt="${escapeHtml(o.name)}">`: `<video src="${o.url}" controls autoplay></video>`;_wireStageMutePersistence(stage.querySelector('video'));@@ -3538,8 +3572,46 @@ function useAsExtendSourcePath(path) {document.querySelector('aside.form-pane').scrollTop = 0;}function useAsExtendSource() { if (!activePath) return alert('Pick an output first.'); useAsExtendSourcePath(activePath); }-// Upscale ×2 — same hand-off shape as Extend: switch to the Remix tool,-// point the picker at this clip, scroll the form to the top.+// UPSCALE & FACE FIX — the one-click clip action. The server builds the job+// (the face-safe recipe, the clip's own prompt and seed) so the player, the+// Outputs cards, the history rows and the Editor queue exactly the same thing.+// The fixed clip lands NEXT TO the original as a new file; nothing is+// overwritten. `opts.board` + `opts.clip` = ordered from an Editor clip, which+// makes the Editor offer the swap when it lands.+const FACE_FIX_NAME = 'Upscale & Face Fix';+async function faceFixClip(path, opts) {+ opts = opts || {};+ if (!path) { phosToast('Pick a clip first.', {}); return null; }+ const fd = new URLSearchParams();+ fd.set('path', path);+ if (opts.board) fd.set('board', opts.board);+ if (opts.clip) fd.set('clip', opts.clip);+ let r;+ try { r = await (await fetch('/queue/facefix', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ const name = String(path).split('/').pop();+ if (!r || !r.ok) {+ phosToast((r && r.error) || (FACE_FIX_NAME + ' could not be queued.'),+ { kind: 'danger', duration: 9000 });+ return r;+ }+ if (opts.btnId) { try { _flashActionDone(opts.btnId, 'Queued'); } catch (e) {} }+ phosToast(r.duplicate+ ? (FACE_FIX_NAME + (r.running ? ' is already rendering for ' : ' is already waiting in the queue for ')+ + name + '.')+ : (opts.doneHint || (FACE_FIX_NAME + ' queued for ' + name+ + ' — the fixed clip (2× size, same face, same sound) lands next to it in Outputs.')),+ { kind: 'success', duration: 6000 });+ try { poll(); } catch (e) {}+ return r;+}+function faceFixActive() {+ if (!activePath) return phosToast('Pick a clip in Outputs first.', {});+ return faceFixClip(activePath, { btnId: 'faceFixBtn' });+}+// The full lane (Remix → Upscale & Face Fix): presets, source picker, prompt.+// Same hand-off shape as Extend: switch to the Remix tool, point the picker+// at this clip, scroll the form to the top.function useAsUpscaleSourcePath(path) {setMode('upscale');const inp = document.getElementById('upscale_source_path');@@ -3551,12 +3623,18 @@ function useAsUpscaleSourcePath(path) {if (pane) pane.scrollTop = 0;}function useAsUpscaleSource() { if (!activePath) return alert('Pick an output first.'); useAsUpscaleSourcePath(activePath); }-// Upscale ×2 presets — one hidden number (keep_shot) the server maps to how-// the render starts; the pills are the only thing the user touches.+// Upscale & Face Fix presets — hidden numbers the server maps to how the+// render starts; the pills are the only thing the user touches. `keep_shot`+// is the preset; the Face Fix pill also pins the start and the step count+// (the other pills clear them so the server's own mapping applies).function setUpscalePreset(btn) {const v = (btn && btn.dataset && btn.dataset.keep) || '1.0';const inp = document.getElementById('keep_shot');if (inp) inp.value = v;+ const st = document.getElementById('upscale_start');+ if (st) st.value = (btn && btn.dataset && btn.dataset.start) || '';+ const sp = document.getElementById('upscale_steps');+ if (sp) sp.value = (btn && btn.dataset && btn.dataset.steps) || '';document.querySelectorAll('#upscalePresetGroup .pill-btn').forEach(b =>b.classList.toggle('active', b === btn));}@@ -3651,6 +3729,39 @@ async function loadParams() {oneshotOpenFromParams(p);return;}+ else if (p.mode === 'upscale') {+ // Upscale & Face Fix reopens in its own lane on the same source clip with+ // the EXACT recipe that ran. A pill lights only when it names that recipe;+ // old sidecars (keep_shot only) match the pill with that strength.+ useAsUpscaleSourcePath(p.upscale_source_path || '');+ const keepN = Number(p.keep_shot != null && p.keep_shot !== '' ? p.keep_shot : 1);+ const keep = String(keepN); // exact: 0.49 is not 0.5+ const start = String(p.upscale_start || '');+ const steps = String(p.upscale_steps || '');+ const pills = Array.from(document.querySelectorAll('#upscalePresetGroup .pill-btn'));+ const pick = pills.find(b => Number(b.dataset.keep) === keepN+ && (b.dataset.start || '') === start && (b.dataset.steps || '') === steps);+ if (pick) setUpscalePreset(pick);+ else {+ pills.forEach(b => b.classList.remove('active'));+ const set = (idn, v) => { const el = document.getElementById(idn); if (el) el.value = v; };+ set('keep_shot', keep); set('upscale_start', start); set('upscale_steps', steps);+ }+ document.getElementById('prompt').value = p.prompt || '';+ // The source's length, asked on the 1+8k grid ABOVE it: the server floors+ // an off-grid count, and the lane cuts the render back to the source.+ const fr = Number(p.source_frames || p.frames || 0);+ if (fr > 0 && document.getElementById('frames')) {+ const grid = Math.max(9, 1 + 8 * Math.ceil((fr - 1) / 8));+ // frames only: the (hidden) duration box has a 1–20 s range, and a+ // 30 s source written into it would block Generate.+ document.getElementById('frames').value = grid;+ }+ const sd = (p.seed_used != null) ? p.seed_used : p.seed;+ if (sd != null && sd !== '') document.getElementById('seed').value = sd;+ _flashActionDone('loadParamsBtn', 'Loaded');+ return;+ }else if (p.mode === 'extend') setMode('extend');else if (p.mode === 'keyframe') setMode('keyframe');else if (p.mode === 'i2v_clean_audio' || p.mode === 'i2v') { setMode('i2v'); document.getElementById('i2vMode').value = p.mode; document.getElementById('mode').value = p.mode; }@@ -4065,6 +4176,14 @@ function _humanDuration(s) {}function renderOutputInfoBody(path, data) {+ if (data && data.engine === 'music') {+ const fields = [['Style', data.style], ['Lyrics', data.lyrics], ['Seed', data.seed],+ ['Length', _humanDuration(data.audio_seconds)],+ ['Ended naturally', data.ended_naturally == null ? 'Unknown' : data.ended_naturally ? 'Yes' : 'No — max length reached'],+ ['Score (ABC)', data.score_abc || 'No score']];+ return fields.map(([label, value]) => `<div class="oi-section"><h3 class="oi-section-title">${label}</h3><div class="oi-prompt music-info-text">${escapeHtml(String(value == null ? '—' : value))}</div></div>`).join('')+ + '<p class="hint">Generated with YuE2 by Multimodal Art Projection · MLX port by vanch007</p>';+ }const p = (data && data.params) || {};const loras = Array.isArray(p.loras) ? p.loras : [];@@ -4102,6 +4221,10 @@ function renderOutputInfoBody(path, data) {i2v_clean_audio: 'Image → Video (clean audio)',keyframe: keyframeModeLabel,extend: 'Extend',+ upscale: FACE_FIX_NAME,+ restore: 'Colorize',+ control: 'Motion Control',+ ingredients: 'Ingredients',})[p.mode] || (p.mode || '—');// One Shot is the mode the user chose; t2v/i2v is what it ran as.const modeLabel = (p.take && p.take.seconds)@@ -4129,6 +4252,23 @@ function renderOutputInfoBody(path, data) {// ---- Generation parameters ----const genRows = [];genRows.push(`<dt>Mode</dt><dd>${escapeHtml(modeLabel)}</dd>`);+ if (p.mode === 'upscale') {+ // Which recipe ran. `face_fix` is written by the worker since the rename;+ // older sidecars only carry keep_shot, and the words follow the server's+ // own mapping (1.0 → 3 steps, 0.8 → 2, below 0.5 → from noise).+ const ff = data.face_fix || {};+ const keep = Number(ff.keep_shot != null ? ff.keep_shot : (p.keep_shot || 1));+ const start = ff.start || p.upscale_start || (keep < 0.5 ? 'noise' : 'source');+ const steps = ff.refine_steps || (start === 'source'+ ? (Number(p.upscale_steps) || (keep >= 0.95 ? 3 : 2)) : null);+ const how = start === 'noise' ? 'Re-imagine — full re-render from noise'+ : (steps === 1 ? 'Face Fix — 1 refine step from the clip (the face is kept)'+ : `${steps} refine steps from the clip`);+ genRows.push(`<dt>Recipe</dt><dd>${escapeHtml(how)}</dd>`);+ if (p.upscale_source_path) {+ genRows.push(`<dt>From</dt><dd>${escapeHtml(String(p.upscale_source_path).split('/').pop())}</dd>`);+ }+ }// A Hailuo H3 render has no LTX quality preset. `params.quality` is just// whatever the quality strip happened to hold when Generate was pressed —// the H3 TIER defined this render's geometry — so printing "Quality:@@ -4422,7 +4562,7 @@ document.getElementById('genForm').addEventListener('submit', async e => {// 4.12.3). Say it before anything is queued.const _upMode = String(fd.get('mode') || (typeof currentMode !== 'undefined' ? currentMode : '') || '');if (_upMode === 'upscale' && !String(fd.get('upscale_source_path') || '').trim()) {- const _msg = 'Pick the clip to upscale first — choose it in the list, or press LTX Upscale on a clip in Outputs.';+ const _msg = 'Pick the clip to fix first — choose it in the list, or press Upscale & Face Fix on a clip in Outputs.';alert(_msg);return;}@@ -4734,7 +4874,8 @@ Object.assign(globalThis, {retryJob, renderCarousel, findOutputByPath, stageMayAutoSelectOutput,selectOutput, openExpandLightbox, closeExpandLightbox, phosToast,animateActive, hide, openOutputsFolder, hideActive,- useAsExtendSource, useAsUpscaleSource, useAsUpscaleSourcePath, setUpscalePreset, loadParams, _flashActionDone, closeOutputInfoModal,+ useAsExtendSource, useAsUpscaleSource, useAsUpscaleSourcePath, setUpscalePreset,+ faceFixClip, faceFixActive, loadParams, _flashActionDone, closeOutputInfoModal,togglePause, openBatch, closeBatch, queueBatch,// inline-handler targets: generated markup resolves these through the// global scope (the v4.9.0 regression, PR #69)diff --git a/webapp/js/shortcuts.js b/webapp/js/shortcuts.jsindex 2133346..d8c9416 100644--- a/webapp/js/shortcuts.js+++ b/webapp/js/shortcuts.js@@ -105,18 +105,18 @@ const SHORTCUTS = [hidden: ['alt+shift+arrowleft', 'alt+shift+arrowright'], owner: 'editor.js',calls: 'sbeNudge', label: 'Nudge the selected clips one frame earlier / later · add ⇧ for ten' },{ id: 'editor.split', scope: 'editor', combos: ['s', 'mod+k', 'mod+b'], owner: 'editor.js',- calls: 'sbeSplitHere', label: 'Split the shot under the playhead (S, or ⌘K as in Premiere, ⌘B as in Final Cut and Resolve)' },+ calls: 'sbeSplitHere', label: 'Split the shot under the playhead — or, with sounds on an audio track selected, those sounds (S, or ⌘K as in Premiere, ⌘B as in Final Cut and Resolve)' },{ id: 'editor.lift', scope: 'editor', combos: ['backspace'], hidden: ['delete'], owner: 'editor.js',- calls: 'sbeLiftSelected', label: 'Lift — take the selected clips out and leave the hole' },+ calls: 'sbeLiftSelected', label: 'Lift — take the selected clips or sounds out and leave the hole' },{ id: 'editor.ripple', scope: 'editor', combos: ['shift+backspace'], hidden: ['shift+delete'],owner: 'editor.js', calls: 'sbeRippleSelected',- label: 'Ripple delete — take them out and close the gap' },+ label: 'Ripple delete — take them out and close the gap (for sounds, on their own track)' },{ id: 'editor.removeOverlay', scope: 'editor', combos: ['backspace'], hidden: ['delete'],owner: 'editor.js', calls: 'sbeOvDeleteSel', label: 'With a title or card selected: remove it' },{ id: 'editor.removeTransition', scope: 'editor', combos: ['backspace'], hidden: ['delete'],owner: 'editor.js', calls: 'sbeTxRemoveSel', label: 'With a cut selected: remove its transition' },{ id: 'editor.duplicate', scope: 'editor', combos: ['d'], owner: 'editor.js',- calls: 'sbeDuplicateSel', label: 'Duplicate the selected clips' },+ calls: 'sbeDuplicateSel', label: 'Duplicate the selected clips or sounds — the music and a clip\'s sound are copied onto an audio track' },{ id: 'editor.link', scope: 'editor', combos: ['shift+l'], owner: 'editor.js',calls: 'sbeToggleAudioLink', label: 'Unlink / link the sound' },{ id: 'editor.resync', scope: 'editor', combos: ['shift+r'], owner: 'editor.js',@@ -137,6 +137,11 @@ const SHORTCUTS = [{ id: 'editor.mute', scope: 'editor', combos: ['m'], owner: 'editor.js',calls: ['sbeSetMute', 'sbeUnmuteFromRefusal'],label: 'Mute / unmute the preview — the film itself is not changed' },+ // The sound area's size. It manages itself; this is the key for when you+ // want one answer to stick — the ▾ on the A1 head is the same control.+ { id: 'editor.soundLanes', scope: 'editor', combos: ['shift+a'], owner: 'editor.js',+ calls: 'sbeAudioPinToggle',+ label: 'Sound lanes small / full height — A1, A2 and the audio tracks (the ▾ on the A1 head does the same)' },{ id: 'editor.undo', scope: 'editor', combos: ['mod+z'], owner: 'editor.js',calls: 'sbeUndo', label: 'Undo' },{ id: 'editor.redo', scope: 'editor', combos: ['shift+mod+z'], owner: 'editor.js',diff --git a/webapp/style/panel.css b/webapp/style/panel.cssindex 332855f..89f0300 100644--- a/webapp/style/panel.css+++ b/webapp/style/panel.css@@ -670,8 +670,7 @@body[data-workflow="audio"] #trainSection { display: none !important; }body[data-workflow="audio"] #audioSectionTab { display: block; }- /* =========================================================- STORYBOARD — the workflow fold + its own surfaces+ /* ================================================== STORYBOARD — the workflow fold + its own surfaces=========================================================Same shape as the audio fold above, plus one extra move: the shotlist takes the GALLERY's slot in the stage column and the player@@ -1706,6 +1705,48 @@justify-content: flex-start; padding-top: 6px; gap: 4px;}.sbe-gh-foot { flex: 0 0 13px; }+ /* ---- A3, A4, …: THE AUDIO TRACKS' HEADS ----------------------------+ Each head reads the SAME --sbe-alane-h its lane does, so the columns+ cannot drift; the add row is the fixed SBE_TADD_H (26px) on both sides.+ `display: contents` lets the painted heads be flex items of the gutter. */+ .sbe-trk-heads { display: contents; }+ .sbe-gh-trk {+ flex: 0 0 var(--sbe-alane-h, 44px); border-top: 1px solid var(--border);+ justify-content: flex-start; padding-top: 3px; gap: 2px;+ }+ .sbe-gh-trk.is-muted .sbe-trk-name, .sbe-gh-trk.is-muted .sbe-trk-row b { opacity: 0.55; }+ .sbe-trk-name {+ flex: 1 1 auto; min-width: 0; width: 100%; height: 16px; margin: 0; padding: 0 3px;+ border: 1px solid transparent; border-radius: var(--r-xs); background: transparent;+ color: var(--text); font: inherit; font-size: var(--fs-2xs); font-weight: 600;+ }+ .sbe-trk-name:hover, .sbe-trk-name:focus {+ border-color: var(--border); background: var(--panel); outline: none;+ }+ .sbe-trk-row { display: flex; align-items: center; gap: 4px; min-width: 0; }+ .sbe-trk-row input[type=range] {+ flex: 1 1 auto; min-width: 0; height: 12px; margin: 0; accent-color: var(--sbe-trk-c);+ }+ .sbe-trk-row b {+ flex: 0 0 auto; min-width: 28px; text-align: right; color: var(--text);+ font-size: var(--fs-2xs); font-weight: 600; font-variant-numeric: tabular-nums;+ }+ .sbe-trk-mute {+ flex: 0 0 auto; width: 18px; height: 16px; padding: 0; line-height: 1;+ border: 1px solid var(--border); border-radius: var(--r-xs);+ background: var(--panel); color: var(--muted); font-size: 9px; font-weight: 700;+ cursor: pointer;+ }+ .sbe-trk-mute.is-on { background: var(--warning); border-color: var(--warning); color: #14101c; }+ .sbe-gh-add {+ flex: 0 0 26px; border-top: 1px solid var(--border); flex-direction: row;+ align-items: center; justify-content: flex-start; gap: 4px; padding: 0 6px;+ }+ .sbe-gh-add .ghost-btn {+ width: auto; height: 18px; padding: 0 6px; font-size: var(--fs-2xs);+ white-space: nowrap; min-width: 0; overflow: hidden; text-overflow: ellipsis;+ }+ .sbe-gh-add .sbe-gh-more { margin-left: auto; font-size: 10px; }.sbe-gh-tag {display: flex; align-items: center; gap: 5px; min-width: 0;font-size: var(--fs-2xs); color: var(--text); font-weight: 600;@@ -2335,6 +2376,34 @@/* The lane is the positioning context for the block; the canvas keeps itsown borders and heights, so the lane adds nothing to the 164px floor. */.sbe-lane { position: relative; }+ /* ---- A3, A4, …: THE AUDIO TRACKS -----------------------------------+ Every lane IS an A1 strip lane (`.sbe-alane`), so the strip, its+ waveform, level line, points, grips and corner band are the same+ geometry the layout gate measures there. Green, so a sound on a track+ never reads as a clip's own sound. */+ .sbe-tracks { --sbe-trk-c: #3fb978; display: flex; flex-direction: column; }+ .sbe-gutter { --sbe-trk-c: #3fb978; }+ .sbe-tstrip {+ background: rgba(63,185,120,0.16); border-color: var(--sbe-trk-c);+ color: #8fe0b5;+ }+ .sbe-tstrip.is-sel { box-shadow: 0 0 0 1px var(--sbe-trk-c); }+ .sbe-tstrip.is-locked { cursor: not-allowed; border-style: dotted; }+ .sbe-tlane.is-muted .sbe-tstrip { opacity: 0.5; }+ .sbe-tadd {+ position: relative; height: 26px; border-top: 1px dashed var(--border);+ font-size: var(--fs-2xs); color: var(--muted); line-height: 24px;+ white-space: nowrap; overflow: hidden; user-select: none; touch-action: none;+ }+ .sbe-tadd-t { position: sticky; left: 10px; padding-left: 10px; }+ .sbe-tadd.is-drop { background: rgba(63,185,120,0.14); color: var(--text); }+ .sbe-tlane .sbe-drop-line, .sbe-tadd .sbe-drop-line { top: 0; bottom: 0; }+ /* A sound in the media pool has no frame to show. */+ .ed-pool-snd {+ flex: 0 0 auto; display: flex; align-items: center; justify-content: center;+ width: 64px; height: 36px; border-radius: var(--r-xs);+ background: var(--bg-2); color: #3fb978; font-size: 16px;+ }/* The per-clip sound. Slim on purpose: it is a second reading of blocksyou have already read, and a lane as tall as the pictures would say thetwo matter equally. */@@ -2416,6 +2485,61 @@border-top: 1px solid var(--border);user-select: none; touch-action: none;}+ /* A1 IS TWO STRIP LANES: clip sound A over clip sound B, each exactly as+ tall as one `--sbe-alane-h`, so the strip painter, `sbeStripH` and the+ heads in the gutter all read the one number they always did. The audio+ tracks reuse `.sbe-alane` and stay one lane each — hence the id. */+ #sbeAudioLane { height: calc(var(--sbe-alane-h, 44px) * 2); }+ #sbeAudioLane::before {+ content: ''; position: absolute; left: 0; right: 0; pointer-events: none;+ top: calc(var(--sbe-alane-h, 44px) - 1px); border-top: 1px dashed var(--border);+ }+ #sbeAudioLane > .sbe-aclip { bottom: auto; height: calc(var(--sbe-alane-h, 44px) - 7px); }+ #sbeAudioLane > .sbe-aclip.is-b { top: calc(var(--sbe-alane-h, 44px) + 3px); }+ .sbe-gh-alt { margin-top: 2px; padding: 1px 6px; font-size: var(--fs-2xs); }+ /* ---- THE SOUND LANES, MADE SMALL ---------------------------------+ "The picture is so tiny… make them little (because I want to see the+ image also as I'm working sometimes)." Small is a PICTURE OF THE SOUND,+ not a control surface: the waveform silhouette and the strip's own+ colour and selection stay, and everything you would GRAB goes — grips,+ corner fades, the level line, its points, the labels — because an 11px+ target is a control you cannot hit and a lane full of them is not+ compact. One click on a thin lane opens the area and selects what you+ clicked (sbeAudioOpenFrom); the heads keep their name and lose their+ controls, which is what tells you which thin strip is which.+ ABOVE THE STACKING BREAKPOINT ONLY: below it the page is the scroller,+ sbeFitMonitors stands down and every lane is back on its CSS height, so+ a class left on the box may not take the controls away down there. */+ @media (min-width: 901px) {+ body.sbe-aanim .sbe-alane, body.sbe-aanim #sbeAudioLane,+ body.sbe-aanim .sbe-wave, body.sbe-aanim .sbe-wave-none,+ body.sbe-aanim .sbe-gh-aud, body.sbe-aanim .sbe-gh-mus,+ body.sbe-aanim .sbe-gh-trk, body.sbe-aanim .sbe-tlwrap {+ transition: height 180ms cubic-bezier(.2,.8,.2,1),+ min-height 180ms cubic-bezier(.2,.8,.2,1),+ flex-basis 180ms cubic-bezier(.2,.8,.2,1);+ }+ .is-asmall .sbe-grip, .is-asmall .sbe-fade-band, .is-asmall .sbe-cl-fade,+ .is-asmall .sbe-lvl, .is-asmall .sbe-lvl-u, .is-asmall .sbe-kf,+ .is-asmall .sbe-aclip-t, .is-asmall .sbe-sync,+ .is-asmall .sbe-mc-name, .is-asmall .sbe-mc-lvl,+ .is-asmall .sbe-gh-aud .sbe-gh-sub, .is-asmall .sbe-gh-alt,+ .is-asmall .sbe-mix-row, .is-asmall .sbe-music-name,+ .is-asmall .sbe-gh-mode, .is-asmall .sbe-gh-mus .sbe-gh-more,+ .is-asmall .sbe-trk-row { display: none !important; }+ /* The strip is the target now, and it says so. */+ .is-asmall .sbe-aclip, .is-asmall .sbe-tstrip,+ .is-asmall .sbe-music-clip { cursor: pointer; line-height: 0; }+ .is-asmall .sbe-aclip.is-linked { opacity: 0.75; }+ /* The silhouette IS the lane, so it is drawn harder than it is at full+ height, where it sits under a level line and its points. */+ .is-asmall .sbe-wave-p { opacity: 0.8; stroke-width: 1; }+ /* Ten pixels of head, and a name has to fit in it. */+ .is-asmall .sbe-gh-aud, .is-asmall .sbe-gh-mus { padding-top: 1px; }+ .is-asmall .sbe-gh-trk { padding-top: 0; }+ .is-asmall .sbe-trk-name { height: 14px; }+ .is-asmall .sbe-gh-tag i { padding: 0 3px; }+ }.sbe-aclip {position: absolute; top: 3px; bottom: 3px; border-radius: var(--r-xs);background: rgba(88,166,255,0.14); border: 1px solid var(--border-strong);@@ -6483,6 +6607,22 @@color: var(--ok, #2fbf71);background: rgba(47,191,113,0.12);}+ /* Upscale & Face Fix split control: the label half queues the fix in one+ click, the narrow half opens the lane's settings. One hairline shell so+ the two read as one control. */+ .po-split {+ display: inline-flex; align-items: stretch;+ border: 1px solid rgba(255,255,255,0.10);+ border-radius: var(--r-sm);+ }+ .po-split .po-act { border: none; }+ .po-split .po-split-main { border-radius: var(--r-sm) 0 0 var(--r-sm); }+ .po-split .po-split-more {+ padding: 5px 6px;+ border-left: 1px solid rgba(255,255,255,0.10);+ border-radius: 0 var(--r-sm) var(--r-sm) 0;+ }+ .po-split .po-act.po-act-done { border: none; }.po-act.po-act-danger .po-act-label { display: none; }.po-act.po-act-danger:hover {background: rgba(248,81,73,0.18);@@ -6910,6 +7050,16 @@.car-card .card-chrome .card-action-photo {flex: 1;}+ /* Upscale & Face Fix on video cards: the only chip a video card has+ besides Delete, so it takes the row. Ellipsis on a narrow card; the+ title carries the whole sentence. */+ .car-card .card-chrome .card-action-facefix {+ flex: 1 1 auto;+ min-width: 0;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }.car-card .card-chrome .card-action-danger {flex: 0 0 auto;width: 28px;@@ -10476,3 +10626,29 @@ body[data-workflow="oneshot"] #audioSectionTab { display: none !important; }.docs-pagenav { padding: 0 18px; }.docs-keys td.docs-keys-k { width: 42%; }}++/* Audio's two panes use the existing composer/strip grammar. */+#audioModeGroup[hidden], #musicComposePane[hidden], #audioDrivePane[hidden],+#musicInstallModal[hidden] { display: none !important; }+#musicComposePane .composer-card > label { display: block; margin: 12px 14px 4px; }+#musicComposePane .composer-card > .hint { margin: 4px 14px 12px; }+#musicLyrics:disabled { opacity: .45; }+#musicComposePane .quick-settings { display: block; }+#musicComposePane .quick-settings > .hint { margin: 6px 0 14px; }+#musicComposePane .range-strip { margin-top: 16px; }+#musicHint { margin-top: 10px; }+.music-card-player { width: calc(100% - 34px); margin-left: 4px; min-width: 0; position: relative; z-index: 1; }+/* The player sits at the TOP of the thumb: the card's hover chrome slides up+ over the bottom edge and would otherwise cover the play button. */+.music-card-note { position: absolute; inset: auto 0 22%; text-align: center; font-size: 40px; color: var(--muted); }+.car-thumb-wrap:has(.music-card-player) { display: flex; align-items: flex-start; padding-top: 8px; }+.music-info-text { white-space: pre-wrap; overflow-wrap: anywhere; }+=======+ /* After-the-draft Upscale & Face Fix (H3 Customize → Upscale). A checkbox+ under the size pills: it is an extra job, not a size. While it is on,+ the draft ships as rendered, so the size pills step back. */+ .h3-facefix-after { align-items: flex-start; margin: 10px 0 2px; line-height: 1.45; }+ .h3-facefix-after input { margin-top: 2px; }+ .h3-facefix-after .cz-label-hint { display: block; margin-left: 0; }+ #h3UpscaleGroup.is-overridden .pill-btn { opacity: 0.45; }+ #h3UpscaleGroup.is-overridden .pill-btn[data-h3-upscale="off"] { opacity: 1; }