@joplo-app/plugin-alda 0.7.1 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/guide.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const skill = "# Alda background music: compose, inspect, render\n\nUse original, restrained instrumental music to support an explanation. Install @joplo-app/plugin-alda at the same version as Joplo and explicitly enable it. The author machine needs **Alda 2.4.8** on PATH; run `alda version` and `alda instruments`. Viewers need a browser, with no Alda, SoundFont, or network download.\n\n## Start and verify\n\nKeep named source strings in a project-owned music.ts:\n\n```ts\n// music.ts\nexport const scores = { film: `\npiano: (tempo! 80) (vol 65) o3\n%opening c1/e1/g1 | %chapter f1/a1/>c1 | < c1/e1/g1 |\n` };\n// joplo.config.ts\nimport { config } from '@joplo-app/kit';\nimport alda from '@joplo-app/plugin-alda';\nimport { scores } from './music';\nexport default config({ name: 'Film', plugins: [alda(scores)] });\n// In an existing feature option:\nimport { music } from '@joplo-app/plugin-alda';\n// .system('Open', music.play('film', { from: 'opening', fadeMs: 800, volume: .4 }))\n// .system('Next chapter', music.play('film', { from: 'chapter', fadeMs: 500 }))\n// .system('Finish', music.stop({ fadeMs: 1200 }), done('Complete'))\n```\n\n1. Plan the form and chapter timing below; export a tiny phrase before writing a long score.\n2. Run `npx joplo check`. Each referenced score prints duration, note count for each part, and every marker's time. Match those numbers to the plan. Missing marker is an error (`MUSIC_MARKER_MISSING`); no Alda gives a warning and the other checks continue. Check parses locally; it does not download a sound bank or render audio.\n3. Build, inspect `MEDIA_ASSET` bytes/duration and warnings, then play with sound enabled. Verify pause, resume, jump, speed, narration ducking, a complete ending and a complete loop. Screenshots remain silent. Video export records the generic media mix.\n4. Rendering/check success proves signal plumbing, not good composition. Listen in the actual player. If no listening was possible, explicitly report **\u672A\u7ECF\u4EBA\u8033\u9A8C\u8BC1** and measurement numbers.\n\nPut play on the first step and stop only at the real ending. A scenario that does not continue another starts silent. Playing the same score again keeps it going; playing a different score with fadeMs crossfades (the old one fades out under the new one, no silence). volume is 0\u20131; fadeMs is 0\u201330000. Music is independent of content language. Use hold(seconds) when exact musical pacing matters. Each step's music position is anchored at the moment the step commits; between two commits the anchor advances by the planned time: the previous step's stay (its hold, or reading time with a 3 s floor when no hold is written; estimated narration when that is longer) plus the next step's action demonstration (0.9 s for a system step; cursor travel, press and typing for a user action). npx joplo outline prints the same per-scenario totals, so plan bar counts against those, not against hold alone. During playback the track runs continuously on the engine clock; only a jump, reset or a non-continuing chapter re-aligns it to that anchor.\n\nFor a historical or multi-theme piece, keep original motifs in one score map, reuse a short melodic motif, and change its instrument at the visual transition. Use distinct named scores and instrument programs rather than copyrighted startup recordings. Chapter seams: chain chapters with chapter() default continuation \u2014 a from chapter starts with the music its previous chapter ended with, and sequential playback keeps it playing across the seam. Start the next chapter's score with fadeMs 2000\u20132600 on the beat just before the visual change (a J-cut), not with stop + play; leave space between notes for narration. Direct navigation to an after-action entry also resolves that step's media snapshot.\n\n`from` is a marker name without `%`, resolved by Alda during local compilation. Only a numeric offset enters IR; jump/deep link/screenshot state uses that same offset plus the engine anchor. A non-continuing scenario starts silent. Same-score play continues; a different score with fadeMs crossfades; chapter() default continuation inherits music. An explicit marker selects a numeric seek. Set `loop: true` only for a phrase designed to repeat. Loop repeats the full score; from only selects its initial seek, not a loop region. `volume` is 0\u20131, `fadeMs` 0\u201330000. Put play alongside a chapter's visual change. Stop with done, allowing an ending hold for the fade; a stop at the instant playback ends cannot create extra playback time. Anchors advance with commitGapMs: the preceding step's planned stay (hold or reading time, or estimated narration when that is longer) plus the next step's action demonstration. Use explicit `hold(seconds)` when exact chapter pacing matters. Actual narration or interaction waits do not redefine later planned score anchors.\n\n## Plan the form before notes\n\nWrite a table: **section / bars / chord in each bar / chapter duration / marker**. For fixed meter and BPM:\n\n`seconds = bars \u00D7 beats per bar \u00D7 60 / BPM`\n\nAt 80 BPM, four bars of 4/4 take 12 seconds. A 24-second chapter needs eight such bars; a 10-second chapter needs a different form, tempo, or explicit silence. Do not stretch a two-bar loop over a minute and assume a fade hides the repetition. Let harmony change at meaningful narrative turns; compare the printed part ends to catch a missing bar or a voice that runs ahead; markers are printed in chronological order and only describe the parts where they were declared. Count rests too. For changing tempo/meter, calculate section by section and let Alda's inspected times be the final authority.\n\nFor each section and instrument, define one variable, beginning with an explicit octave and duration; write `|` at every bar. Put a `%section` marker in the **first part only**, then `@section` on other parts where needed. All parts must occupy the same bar count. Bar lines aid counting; they do not fix mismatched durations. End with a held consonant chord and room for its release instead of stopping on the last attack.\n\n```alda\nopenKeys = o3 c1/e1/g1 | f1/a1/>c1 |\nopenBass = o2 c1 | f1 |\nendKeys = o3 c1~1/e1~1/g1~1 |\nendBass = o2 c1~1 |\npiano: (tempo! 80) (vol 60) %opening openKeys %ending endKeys\nmidi-acoustic-bass: (vol 55) @opening openBass @ending endBass\n```\n\nUse `alda parse -f music.alda -o data` to inspect a standalone draft. Do not eyeball octave state or assume variables reset it. Test new instrument names with `alda instruments`: `guitar` means nylon-string guitar, not a universal electric-guitar sound; names such as `midi-electric-piano-1` and `midi-synth-pad-new-age` are explicit.\n\n## Arrange around the narrator\n\n**The narration is the lead instrument.** Under speech, use a bass pulse, a few midrange chord tones and a quiet pad; leave melodic hooks for the opening, transitions and speech-free gaps. Avoid continuous arpeggios competing with syllables. Start with score `(vol 60)`\u2013`(vol 75)` and track volume .3\u2013.5, then measure/listen rather than lowering every gain stage blindly. The player ducks music to 25% during narration.\n\nSeparate registers: bass around o1\u2013o2, accompaniment o3\u2013o4 with small voice-leading movements, pad around o4 in long notes. These are starting points, not rules for every instrument. Keep the narrator's midrange clear. Change one dimension between sections (register, rhythm, instrument, harmonic density), then let the final section settle. Do not run every instrument at the same velocity throughout.\n\n## Restrained GM percussion\n\nUse `midi-percussion`, which exports on the GM percussion channel. Pitch chooses the drum, not a melodic instrument program. Useful mappings (Alda o4 c = MIDI 60):\n\n| Drum | MIDI note | Alda pitch |\n| --- | --- | --- |\n| Bass drum | 36 | o2 c |\n| Side stick | 37 | o2 c+ |\n| Acoustic snare | 38 | o2 d |\n| Hand clap | 39 | o2 d+ |\n| Closed hi-hat | 42 | o2 f+ |\n| Pedal hi-hat | 44 | o2 g+ |\n| Low tom | 45 | o2 a |\n| Open hi-hat | 46 | o2 a+ |\n| Crash | 49 | o3 c+ |\n| Ride | 51 | o3 d+ |\n\nDefine **one bar per variable** and put a drum-grid comment above it. Every grid cell is a note or a rest, with explicit durations. Repeat the bar; add a small fill only at the end of a four/eight-bar phrase, not every bar. These single-line 4/4 patterns deliberately avoid dense overlap:\n\n```alda\n# 1 & 2 & 3 & 4 &: K . H . S . H . (slow documentary)\ndocBeat = o2 c8 r8 f+8 r8 c+8 r8 f+8 r8 |\n# 1 & 2 & 3 & 4 &: K H . H S H . H (quiet forward motion)\nwalkBeat = o2 c8 f+8 r8 f+8 c+8 f+8 r8 f+8 |\n# 1 & 2 & 3 & 4 &: K . . H . . S . (space beneath speech)\nspaceBeat = o2 c8 r8 r8 f+8 r8 r8 c+8 r8 |\nmidi-percussion: (tempo! 80) (vol 40) docBeat*4 walkBeat*4 spaceBeat*4\n```\n\nHere S is a gentle side stick (37); change c+ to d for a stronger snare (38). Layer kick/snare/hats only if needed: enclose voices in `[V1: ... V2: ... V0:]`, reset octave/duration/volume in each voice, and give each exactly the same bar count. Put a cymbal in a separate part/voice at `@section` instead of shifting the shared grid. A crash every bar usually overwhelms narration. The GM bank supplies real drum samples; a passing MIDI export alone does not prove your selected pitches are drums.\n\n## Common Alda failures\n\n- Octave drift: crossing B\u2192C needs `>` when intended; repeated variables retain ending octave. Begin each variable with `oN`, write explicit jumps and restore the next section's register.\n- Sticky duration: a run of eighth notes changes subsequent defaults. Write `c4`/`r4` explicitly when returning to quarters; check every bar's beat sum.\n- Tempo scope: `(tempo 80)` changes the selected part; use `(tempo! 80)` for a global tempo. Otherwise parts and markers drift apart.\n- Voice leakage: `V0:` rejoins voices but octave, duration and volume may have changed. Keep voice-containing variables bracketed and explicitly reset state after them.\n- Variable names need two initial letters; avoid single-letter/pitch-like names and punctuation. Use descriptive names such as `openKeys`, not `c1`.\n- Instrument aliases are not universal; verify exact names. Unknown instruments and malformed ties/chords surface in local parse/export diagnostics.\n- `%marker` declares a time; `@marker` jumps to it. Declare once in the first part and inspect actual numeric times; don't duplicate marker declarations in every part.\n- A terminal rest contributes to the musical cycle. For loops, count intended bars including rests; don't append an arbitrary silence to hide a bad cadence.\n\n## One long score or separate chapter pieces\n\nOne long score with a marker per chapter gives consistent instrumentation, harmonic planning and precise seeking via `music.play('film', { from: 'chapter' })`. Do not issue another play during ordinary uninterrupted music unless a restart is intended. A chapter() slice inherits the previous ending, including its running score; ordinary same-score play continues it. Only an explicit marker play repositions that track and restarts its fade, including a marker at 0ms. The decoded PCM remains reusable.\n\nSeparate named pieces suit contrasting eras or a chapter that changes length independently, and can reduce scoped publication size. Playing a different score with fadeMs crossfades through the generic host: old and new drivers coexist, including when the old slot moves to an outgoing-resource key. The host owns volume, fade and narration ducking exactly once; do not add another player or fade inside this plugin. Both overlapping PCM buffers count toward the shared 32MiB budget until the old driver leaves. At stereo 48kHz this is roughly 87 seconds of combined decoded audio; at 96kHz roughly 43 seconds, including codec guards/padding. An 80s loop crossfading into a 50s loop exceeds the budget even if the MP3 files are small. Shorten overlapping loops or avoid that crossfade; leave headroom and test the actual playback device. check estimates from score duration; build also checks decoded metadata and names simultaneous resources plus the step source. MEDIA_DECODE_BUDGET / MEDIA_DECODE_HEADROOM are author warnings; video export fails if actual decoding fails. Recheck markers after changing any earlier bars in a long piece.\n\n## Rendering, cache and recovery\n\nMEDIA_ASSET_LARGE checks the 2 MiB absolute size for every track; the 0.75 MB/min rate check only applies to clips at least 15 seconds long. Short clips pay fixed codec context overhead: splitting them does not improve bitrate.\n\nPipeline: Alda 2.4.8 \u2192 temporary MIDI \u2192 SpessaSynth Core 4.4.9 with FluidR3Mono GM 2.312 \u2192 44.1kHz stereo PCM \u2192 **MP3 96 kbps stereo at 32kHz**. The deterministic 24-tap/256-phase resampler, fixed LAME encoder (@breezystack/lamejs 1.2.7) and verification decoder (mpg123-decoder 1.0.3) run in Node; no ffmpeg or FluidSynth installation is required. FLAC (libflacjs 5.6.0) is only an author-side master in `.joplo/music-masters`; it never enters the site, and there is no lossless publication switch. First rendering downloads the pinned, SHA-256-verified ~14.5MB SF3 and license to `JOPLO_HOME/plugins/alda/cache/soundfonts/<hash>/` (default ~/.joplo). The bank stays local. Published `credits.txt` and `music-LICENSE.txt` preserve bank attribution and full license even when Alda inspection is unavailable; missing artifact attribution blocks publication.\n\nTo preinstall on a connected author machine, run this **from the project**:\n\n```sh\nnode --input-type=module -e \"import('@joplo-app/plugin-alda/local').then(m=>m.installSoundfont())\"\n```\n\nFor an offline author machine, copy that verified soundfonts/<hash>/ directory (including LICENSE.md) into its JOPLO_HOME/plugins/alda/cache/ (the plugin's private cache; local compilers never receive JOPLO_HOME itself); an absent/corrupt cache fails with the command above. Do not replace files with an unverified bank. If a future upstream decoder range resolves a second version, rendering fails explicitly: pin spessasynth_core\u2019s stb-vorbis dependency to 0.0.7 with your package manager overrides and reinstall. A SoundFont or renderer/encoder upgrade invalidates the cache; the host keys on exact compiler code/version and input, which include bank hash, renderer, SF3 decoder, FLAC/master encoder, MP3 format/bitrate/resampling/context/trim/seam parameters and loop mode. Cache and temporary scores/MIDI are author-only, under .joplo/resources; do not commit them. Only audio bytes, numeric playback-region metadata and media snapshots ship, with attribution text. Build/scope includes only referenced audio.\n\nMP3 is about 0.72 MB/min before base64. Build reports each cue's bytes/duration, all raw audio, embedded base64/data-URI bytes and the complete site. It warns above 0.75 MB/min or 2MiB/cue, and at 18MiB/site against the documented Free 20MiB single-upload budget. Short loops can warn because of fixed context/probe overhead. Base64 adds about one third: measure the built site before sharing. Lowering track volume does not reduce bytes; shorten/split music or narrow the share scope.\n\nLoop period comes from the longest Alda part (including rests). Release/reverb folds into the next cycle, then MP3 receives periodic guards. The build decodes its own MP3 and measures actual delay by correlation, storing only numeric `cycleFrames/sourceSampleRate/contentStartFrame/contentFrames/decodedFrames/encoderDelayFrames/paddingFrames/channels` in `project.mediaInfo` for static builds. Dev IR includes metadata for successfully materialized resources; a resource endpoint response also supplies its `audio` field. Missing metadata means the resource has not been successfully materialized, not zero duration. The browser converts these using the native buffer sample rate, smooths the final decoded 3ms boundary, and uses exact `loopStart/loopEnd`; a marker starts at loopStart + its numeric offset. No calibration probe/guard is played. Unexpected native decoder trimming fails explicitly. Native Chromium 44.1/48kHz is tested; Safari/iOS and Firefox remain unverified in this implementation. Musical harmony/rhythm still needs to repeat naturally.\n\nThe renderer applies one whole-piece RMS gain to -20dBFS over the musical duration, capped at -1dBFS sample peak; this is not LUFS mastering. Non-loop music retains release/reverb until 250ms below -80dB before gain calibration, at most 12s with a guard fade; playback metadata excludes codec padding, not the musical tail.\n\nThe player bounds encoded cache to 4MiB/32 entries (2 loads) and decoded PCM to 32MiB/32 entries (1 decode), using actual channels \u00D7 frames \u00D7 4 bytes and leased LRU. Current and first capture-prefetched cues stay pinned; leaving releases them, inflight work deduplicates, failures can retry, and destroy clears caches/recordings. Long scores can exceed PCM budget despite tiny MP3 files (48kHz stereo float32 is about 23MB/min); shorten or split them instead of assuming compressed bytes are the memory cost. A cue above budget fails before decoding when numeric metadata is available. Capture warms only its first cue; later cues load lazily and can start late under load. Chain recording collects cues from every following chapter in playback order, including music that starts after a silent opening.\n\nVideo BGM uses the same playback engine, including `joplo render --video --chain`. Film strips (`--film`) skip audio capture and decoding so their virtual clock does not wait for a real audio device. A continuously silent capture input keeps Opus PTS intact; an end-of-recording color/pulse calibration reads actual video/audio PTS, centers the video-frame interval, then trims the calibration section. It does not use the wall clock before page creation. This end calibration does not sample-lock a whole long recording: verify independent early/late picture-and-audio events for a chain and report the measured offset; short-clip results do not prove long-chain synchronization. Generated narration clips (npx joplo voice; board export while narration is on) play through the same media engine, are captured on the same track and duck the music; browser Web Speech narration still cannot be captured. **Known issue RM5:** failed audio recording or muxing rejects the export and currently does not retain a silent-video fallback; fix the error and re-export.\n\nIf silent, check the sound switch, click Play (gesture required), and read located local-resource warnings. Missing Alda, syntax errors, download/hash failures, timeout (up to 180s for render) or size limit leave the rest playable. Fix the cause and retry build; for a failed playback slot, switch scenarios or toggle sound off/on or reload before retrying. Published sites cannot regenerate audio. A successful check without Alda is not a rendering pass. If Alda reports a failed/unreachable player or export timeout, inspect its local processes with `alda ps` and run `alda doctor`, repair that environment, then retry. A build can preserve the rest while omitting failed music: verify the expected cue count and MEDIA_ASSET records before calling audio validation successful.\n\n## Measure when listening is unavailable\n\nffmpeg is an **optional measurement tool**, never a Joplo rendering dependency. Extract each data:audio/mpeg;base64 payload and its project.mediaInfo entry from a local build. Measure only the playback region (start = contentStartFrame/sourceSampleRate; duration = contentFrames/sourceSampleRate), excluding the calibration probe and guards:\n\n```sh\nffmpeg -hide_banner -i /tmp/music.mp3 -af \"atrim=start=<start-seconds>:duration=<content-seconds>,asetpts=PTS-STARTPTS,ebur128=peak=true\" -f null -\n```\n\nReport integrated LUFS, true peak dBFS, duration and bytes, plus whether the measurement is before/after track volume and narration ducking. Compare music and narration over the **same speech interval**; as a starting point, aim for music roughly 12\u201320dB below speech, then listen. Gain .4 is about -8dB; narration ducking .25 adds about -12dB. Do not claim the final mix level from the unattenuated bank output alone. For a loop, also measure decoded frame count and sample discontinuity across the join, not just file duration. Write **\u672A\u7ECF\u4EBA\u8033\u9A8C\u8BC1** whenever human listening did not occur.\n";
1
+ export declare const skill = "# Alda background music: compose, inspect, render\n\nUse original, restrained instrumental music to support an explanation. Install @joplo-app/plugin-alda at the same version as Joplo and explicitly enable it. The author machine needs **Alda 2.4.8** on PATH; run `alda version` and `alda instruments`. Viewers need a browser, with no Alda, SoundFont, or network download.\n\n## Start and verify\n\nKeep named source strings in a project-owned music.ts:\n\n```ts\n// music.ts\nexport const scores = { film: `\npiano: (tempo! 80) (vol 65) o3\n%opening c1/e1/g1 | %chapter f1/a1/>c1 | < c1/e1/g1 |\n` };\n// joplo.config.ts\nimport { config } from '@joplo-app/kit';\nimport alda from '@joplo-app/plugin-alda';\nimport { scores } from './music';\nexport default config({ name: 'Film', plugins: [alda(scores)] });\n// In an existing feature option:\nimport { music } from '@joplo-app/plugin-alda';\n// .system('Open', music.play('film', { from: 'opening', fadeMs: 800, volume: .4 }))\n// .system('Next chapter', music.play('film', { from: 'chapter', fadeMs: 500 }))\n// .system('Finish', music.stop({ fadeMs: 1200 }), done('Complete'))\n```\n\n1. Plan the form and chapter timing below; export a tiny phrase before writing a long score.\n2. Run `npx joplo check`. Each referenced score prints duration, note count for each part, and every marker's time. Match those numbers to the plan. Missing marker is an error (`MUSIC_MARKER_MISSING`); no Alda gives a warning and the other checks continue. Check parses locally; it does not download a sound bank or render audio.\n3. Build, inspect `MEDIA_ASSET` bytes/duration and warnings, then play with sound enabled. Verify pause, resume, jump, speed, narration ducking, a complete ending and a complete loop. Screenshots remain silent. Video export records the generic media mix.\n4. Rendering/check success proves signal plumbing, not good composition. Listen in the actual player. If no listening was possible, explicitly report **\u672A\u7ECF\u4EBA\u8033\u9A8C\u8BC1** and measurement numbers.\n\nPut play on the first step and stop only at the real ending. A scenario that does not continue another starts silent. Playing the same score again keeps it going; playing a different score with fadeMs crossfades (the old one fades out under the new one, no silence). volume is 0\u20131; fadeMs is 0\u201330000. Music is independent of content language. Use hold(seconds) when exact musical pacing matters. Each step's music position is anchored at the moment the step commits; between two commits the anchor advances by the planned time: the previous step's stay (its hold, or reading time with a 3 s floor when no hold is written; estimated narration when that is longer) plus the next step's action demonstration (0.9 s for a system step; cursor travel, press and typing for a user action). npx joplo outline prints the same per-scenario totals, so plan bar counts against those, not against hold alone. During playback the track runs continuously on the engine clock; only a jump, reset or a non-continuing chapter re-aligns it to that anchor.\n\nFor a historical or multi-theme piece, keep original motifs in one score map, reuse a short melodic motif, and change its instrument at the visual transition. Use distinct named scores and instrument programs rather than copyrighted startup recordings. Chapter seams: chain chapters with chapter() default continuation \u2014 a from chapter starts with the music its previous chapter ended with, and sequential playback keeps it playing across the seam. Start the next chapter's score with fadeMs 2000\u20132600 on the beat just before the visual change (a J-cut), not with stop + play; leave space between notes for narration. Direct navigation to an after-action entry also resolves that step's media snapshot.\n\n`from` is a marker name without `%`, resolved by Alda during local compilation. Only a numeric offset enters IR; jump/deep link/screenshot state uses that same offset plus the engine anchor. A non-continuing scenario starts silent. Same-score play continues; a different score with fadeMs crossfades; chapter() default continuation inherits music. An explicit marker selects a numeric seek. Set `loop: true` only for a phrase designed to repeat. Loop repeats the full score; from only selects its initial seek, not a loop region. `volume` is 0\u20131, `fadeMs` 0\u201330000. Put play alongside a chapter's visual change. Stop with done, allowing an ending hold for the fade; a stop at the instant playback ends cannot create extra playback time. Anchors advance with commitGapMs: the preceding step's planned stay (hold or reading time, or estimated narration when that is longer) plus the next step's action demonstration. Use explicit `hold(seconds)` when exact chapter pacing matters. Actual narration or interaction waits do not redefine later planned score anchors.\n\n## Delayed starts and crowded crossfades\n\nmusic.play('film', { startDelayMs: 300, duck: false, maxRetiring: 1 }) waits 300 engine ms after the step commits. startDelayMs accepts 0\u201360000; it does not seek or consume notes. from still selects the source marker. Fade-in begins at actual source start. Pause freezes the wait, speed scales its wall duration, and chapter continuation preserves remaining wait. Explicitly issuing delay again creates a new deterministic event even with the same score; omit the option to retain existing behavior.\n\nduck defaults true: narration multiplies the authored gain by .25. duck:false exempts this music track, including its own retiring fades; it does not change narration or other tracks. Use a restrained volume and listen to the mix. maxRetiring is an integer 0\u201332 per named track: 1 means current music plus the most recently retired music; 0 removes exiting music immediately while preserving current. Omit it to retain all exiting fades as before. Limits evict by retirement order, not resource name or remaining fade length, and never cap unrelated tracks or independent SFX. When replacing music with both startDelayMs and fadeMs, the old cue starts fading out at command commit and the new cue starts fading in only after its delay. If delay exceeds fadeMs, there can be a silent gap; this combination does not promise a continuous crossfade. For an ordinary continuous crossfade omit the delay. End holds must include any delay and fade you want the audience to hear; delay adds no automatic hold.\n\nFor offline reconstruction retain timeline media snapshots and packaged audio. startDelayMs is the original plan, delayRemainingMs the remaining wait, startEventId the explicit delayed event identity, and endAfterMs (when present) excludes waiting. For a fresh delayed play observed at commit engineMs, the nominal eligibility time for this observation is engineMs + delayRemainingMs (falling back to startDelayMs only when remaining is absent). On an inherited snapshot use its remaining wait, never add the original plan again; the same startEventId identifies the continued cue, while a new startEventId is a new explicit delayed play even for the same resource. A chapter/deep-link timeline may first observe an inherited cue as play, so deduplicate across joined observations by that identity rather than resource alone. If remaining is zero on a continued identity, it is already eligible: do not emit another start or infer its original onset from that snapshot. Without the earlier play observation, the original start is unknown. Source trim, fade-in and silence inside the audio bytes can shift the first audible sample; scheduling metadata cannot detect that silence. Timeline play events identify observed command commits, not measured acoustic onset; the existing export sampling tolerance still applies. MUSIC_OPTIONS_INVALID means fix these option types/ranges, not reinstall Alda.\n\n## Plan the form before notes\n\nWrite a table: **section / bars / chord in each bar / chapter duration / marker**. For fixed meter and BPM:\n\n`seconds = bars \u00D7 beats per bar \u00D7 60 / BPM`\n\nAt 80 BPM, four bars of 4/4 take 12 seconds. A 24-second chapter needs eight such bars; a 10-second chapter needs a different form, tempo, or explicit silence. Do not stretch a two-bar loop over a minute and assume a fade hides the repetition. Let harmony change at meaningful narrative turns; compare the printed part ends to catch a missing bar or a voice that runs ahead; markers are printed in chronological order and only describe the parts where they were declared. Count rests too. For changing tempo/meter, calculate section by section and let Alda's inspected times be the final authority.\n\nFor each section and instrument, define one variable, beginning with an explicit octave and duration; write `|` at every bar. Put a `%section` marker in the **first part only**, then `@section` on other parts where needed. All parts must occupy the same bar count. Bar lines aid counting; they do not fix mismatched durations. End with a held consonant chord and room for its release instead of stopping on the last attack.\n\n```alda\nopenKeys = o3 c1/e1/g1 | f1/a1/>c1 |\nopenBass = o2 c1 | f1 |\nendKeys = o3 c1~1/e1~1/g1~1 |\nendBass = o2 c1~1 |\npiano: (tempo! 80) (vol 60) %opening openKeys %ending endKeys\nmidi-acoustic-bass: (vol 55) @opening openBass @ending endBass\n```\n\nUse `alda parse -f music.alda -o data` to inspect a standalone draft. Do not eyeball octave state or assume variables reset it. Test new instrument names with `alda instruments`: `guitar` means nylon-string guitar, not a universal electric-guitar sound; names such as `midi-electric-piano-1` and `midi-synth-pad-new-age` are explicit.\n\n## Arrange around the narrator\n\n**The narration is the lead instrument.** Under speech, use a bass pulse, a few midrange chord tones and a quiet pad; leave melodic hooks for the opening, transitions and speech-free gaps. Avoid continuous arpeggios competing with syllables. Start with score `(vol 60)`\u2013`(vol 75)` and track volume .3\u2013.5, then measure/listen rather than lowering every gain stage blindly. The player ducks music to 25% during narration.\n\nSeparate registers: bass around o1\u2013o2, accompaniment o3\u2013o4 with small voice-leading movements, pad around o4 in long notes. These are starting points, not rules for every instrument. Keep the narrator's midrange clear. Change one dimension between sections (register, rhythm, instrument, harmonic density), then let the final section settle. Do not run every instrument at the same velocity throughout.\n\n## Restrained GM percussion\n\nUse `midi-percussion`, which exports on the GM percussion channel. Pitch chooses the drum, not a melodic instrument program. Useful mappings (Alda o4 c = MIDI 60):\n\n| Drum | MIDI note | Alda pitch |\n| --- | --- | --- |\n| Bass drum | 36 | o2 c |\n| Side stick | 37 | o2 c+ |\n| Acoustic snare | 38 | o2 d |\n| Hand clap | 39 | o2 d+ |\n| Closed hi-hat | 42 | o2 f+ |\n| Pedal hi-hat | 44 | o2 g+ |\n| Low tom | 45 | o2 a |\n| Open hi-hat | 46 | o2 a+ |\n| Crash | 49 | o3 c+ |\n| Ride | 51 | o3 d+ |\n\nDefine **one bar per variable** and put a drum-grid comment above it. Every grid cell is a note or a rest, with explicit durations. Repeat the bar; add a small fill only at the end of a four/eight-bar phrase, not every bar. These single-line 4/4 patterns deliberately avoid dense overlap:\n\n```alda\n# 1 & 2 & 3 & 4 &: K . H . S . H . (slow documentary)\ndocBeat = o2 c8 r8 f+8 r8 c+8 r8 f+8 r8 |\n# 1 & 2 & 3 & 4 &: K H . H S H . H (quiet forward motion)\nwalkBeat = o2 c8 f+8 r8 f+8 c+8 f+8 r8 f+8 |\n# 1 & 2 & 3 & 4 &: K . . H . . S . (space beneath speech)\nspaceBeat = o2 c8 r8 r8 f+8 r8 r8 c+8 r8 |\nmidi-percussion: (tempo! 80) (vol 40) docBeat*4 walkBeat*4 spaceBeat*4\n```\n\nHere S is a gentle side stick (37); change c+ to d for a stronger snare (38). Layer kick/snare/hats only if needed: enclose voices in `[V1: ... V2: ... V0:]`, reset octave/duration/volume in each voice, and give each exactly the same bar count. Put a cymbal in a separate part/voice at `@section` instead of shifting the shared grid. A crash every bar usually overwhelms narration. The GM bank supplies real drum samples; a passing MIDI export alone does not prove your selected pitches are drums.\n\n## Common Alda failures\n\n- Octave drift: crossing B\u2192C needs `>` when intended; repeated variables retain ending octave. Begin each variable with `oN`, write explicit jumps and restore the next section's register.\n- Sticky duration: a run of eighth notes changes subsequent defaults. Write `c4`/`r4` explicitly when returning to quarters; check every bar's beat sum.\n- Tempo scope: `(tempo 80)` changes the selected part; use `(tempo! 80)` for a global tempo. Otherwise parts and markers drift apart.\n- Voice leakage: `V0:` rejoins voices but octave, duration and volume may have changed. Keep voice-containing variables bracketed and explicitly reset state after them.\n- Variable names need two initial letters; avoid single-letter/pitch-like names and punctuation. Use descriptive names such as `openKeys`, not `c1`.\n- Instrument aliases are not universal; verify exact names. Unknown instruments and malformed ties/chords surface in local parse/export diagnostics.\n- `%marker` declares a time; `@marker` jumps to it. Declare once in the first part and inspect actual numeric times; don't duplicate marker declarations in every part.\n- A terminal rest contributes to the musical cycle. For loops, count intended bars including rests; don't append an arbitrary silence to hide a bad cadence.\n\n## One long score or separate chapter pieces\n\nOne long score with a marker per chapter gives consistent instrumentation, harmonic planning and precise seeking via `music.play('film', { from: 'chapter' })`. Do not issue another play during ordinary uninterrupted music unless a restart is intended. A chapter() slice inherits the previous ending, including its running score; ordinary same-score play continues it. Only an explicit marker play repositions that track and restarts its fade, including a marker at 0ms. The decoded PCM remains reusable.\n\nSeparate named pieces suit contrasting eras or a chapter that changes length independently, and can reduce scoped publication size. Playing a different score with fadeMs crossfades through the generic host: old and new drivers coexist, including when the old slot moves to an outgoing-resource key. The host owns volume, fade and narration ducking exactly once; do not add another player or fade inside this plugin. Both overlapping PCM buffers count toward the shared 32MiB budget until the old driver leaves. At stereo 48kHz this is roughly 87 seconds of combined decoded audio; at 96kHz roughly 43 seconds, including codec guards/padding. An 80s loop crossfading into a 50s loop exceeds the budget even if the MP3 files are small. Shorten overlapping loops or avoid that crossfade; leave headroom and test the actual playback device. check estimates from score duration; build also checks decoded metadata and names simultaneous resources plus the step source. MEDIA_DECODE_BUDGET / MEDIA_DECODE_HEADROOM are author warnings; video export fails if actual decoding fails. Recheck markers after changing any earlier bars in a long piece.\n\n## Rendering, cache and recovery\n\nMEDIA_ASSET_LARGE checks the 2 MiB absolute size for every track; the 0.75 MB/min rate check only applies to clips at least 15 seconds long. Short clips pay fixed codec context overhead: splitting them does not improve bitrate.\n\n## Stable local lossless files\nFor pitched one-shot effects or external lossless mixing, import renderLossless from @joplo-app/plugin-alda/local. It shares music.play's Alda \u2192 MIDI \u2192 verified bank \u2192 normalized PCM \u2192 FLAC master path, with no MP3 calibration probe, guard or encoder padding. It does not read internal music-masters filenames or choose a JOPLO_HOME for you.\n```ts\nimport { renderLossless } from '@joplo-app/plugin-alda/local';\nimport { mkdtemp, writeFile, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join, resolve } from 'node:path';\nconst directory = await mkdtemp(join(tmpdir(), 'joplo-score-'));\ntry {\n const result = await renderLossless('piano: c1', {\n directory, cacheDir: resolve('.cache/alda'), loop: false,\n maxBytes: 50 * 1024 * 1024,\n });\n await writeFile('cue.flac', result.bytes);\n console.log(result.audio, result.info.markers);\n} finally { await rm(directory, { recursive: true, force: true }); }\n```\ndirectory is a caller-owned writable temporary-work parent; jobs clean their private subdirectory. cacheDir is an explicit persistent private plugin cache (a project-owned .cache/alda is valid); provision its verified SoundFont cache online before offline rendering. First use can download the same pinned bank/license as ordinary music. No cloud/TTS generation occurs. Install Alda 2.4.8 when the tool is missing, verify `alda version`, then retry; the API preserves the existing pinned-version/bank verification failures. Output is fixed 44.1kHz stereo 16-bit FLAC with existing AudioRegion metadata: contentStartFrame/encoderDelayFrames/paddingFrames are zero, contentFrames includes non-loop release/reverb tail, cycleFrames is the musical cycle, and info.durationMs/markers describe score timing. loop:true folds the tail into the cycle; loop:false keeps it. bytes/credit/license use the existing LocalArtifact fields; preserve attribution with downstream files. This is an author-file API, not a larger playback budget: verify encoded 4 MiB and decoded 32 MiB host limits before embedding the file.\n\nPipeline: Alda 2.4.8 \u2192 temporary MIDI \u2192 SpessaSynth Core 4.4.9 with FluidR3Mono GM 2.312 \u2192 44.1kHz stereo PCM \u2192 **MP3 96 kbps stereo at 32kHz**. The deterministic 24-tap/256-phase resampler, fixed LAME encoder (@breezystack/lamejs 1.2.7) and verification decoder (mpg123-decoder 1.0.3) run in Node; no ffmpeg or FluidSynth installation is required. FLAC (libflacjs 5.6.0) is only an author-side master in `.joplo/music-masters`; it never enters the site, and there is no lossless publication switch. First rendering downloads the pinned, SHA-256-verified ~14.5MB SF3 and license to `JOPLO_HOME/plugins/alda/cache/soundfonts/<hash>/` (default ~/.joplo). The bank stays local. Published `credits.txt` and `music-LICENSE.txt` preserve bank attribution and full license even when Alda inspection is unavailable; missing artifact attribution blocks publication.\n\nTo preinstall on a connected author machine, run this **from the project**:\n\n```sh\nnode --input-type=module -e \"import('@joplo-app/plugin-alda/local').then(m=>m.installSoundfont())\"\n```\n\nFor an offline author machine, copy that verified soundfonts/<hash>/ directory (including LICENSE.md) into its JOPLO_HOME/plugins/alda/cache/ (the plugin's private cache; local compilers never receive JOPLO_HOME itself); an absent/corrupt cache fails with the command above. Do not replace files with an unverified bank. If a future upstream decoder range resolves a second version, rendering fails explicitly: pin spessasynth_core\u2019s stb-vorbis dependency to 0.0.7 with your package manager overrides and reinstall. A SoundFont or renderer/encoder upgrade invalidates the cache; the host keys on exact compiler code/version and input, which include bank hash, renderer, SF3 decoder, FLAC/master encoder, MP3 format/bitrate/resampling/context/trim/seam parameters and loop mode. Cache and temporary scores/MIDI are author-only, under .joplo/resources; do not commit them. Only audio bytes, numeric playback-region metadata and media snapshots ship, with attribution text. Build/scope includes only referenced audio.\n\nMP3 is about 0.72 MB/min before base64. Build reports each cue's bytes/duration, all raw audio, embedded base64/data-URI bytes and the complete site. It warns above 0.75 MB/min or 2MiB/cue, and at 18MiB/site against the documented Free 20MiB single-upload budget. Short loops can warn because of fixed context/probe overhead. Base64 adds about one third: measure the built site before sharing. Lowering track volume does not reduce bytes; shorten/split music or narrow the share scope.\n\nLoop period comes from the longest Alda part (including rests). Release/reverb folds into the next cycle, then MP3 receives periodic guards. The build decodes its own MP3 and measures actual delay by correlation, storing only numeric `cycleFrames/sourceSampleRate/contentStartFrame/contentFrames/decodedFrames/encoderDelayFrames/paddingFrames/channels` in `project.mediaInfo` for static builds. Dev IR includes metadata for successfully materialized resources; a resource endpoint response also supplies its `audio` field. Missing metadata means the resource has not been successfully materialized, not zero duration. The browser converts these using the native buffer sample rate, smooths the final decoded 3ms boundary, and uses exact `loopStart/loopEnd`; a marker starts at loopStart + its numeric offset. No calibration probe/guard is played. Unexpected native decoder trimming fails explicitly. Native Chromium 44.1/48kHz is tested; Safari/iOS and Firefox remain unverified in this implementation. Musical harmony/rhythm still needs to repeat naturally.\n\nThe renderer applies one whole-piece RMS gain to -20dBFS over the musical duration, capped at -1dBFS sample peak; this is not LUFS mastering. Non-loop music retains release/reverb until 250ms below -80dB before gain calibration, at most 12s with a guard fade; playback metadata excludes codec padding, not the musical tail.\n\nThe player bounds encoded cache to 4MiB/32 entries (2 loads) and decoded PCM to 32MiB/32 entries (1 decode), using actual channels \u00D7 frames \u00D7 4 bytes and leased LRU. Current and first capture-prefetched cues stay pinned; leaving releases them, inflight work deduplicates, failures can retry, and destroy clears caches/recordings. Long scores can exceed PCM budget despite tiny MP3 files (48kHz stereo float32 is about 23MB/min); shorten or split them instead of assuming compressed bytes are the memory cost. A cue above budget fails before decoding when numeric metadata is available. Capture warms only its first cue; later cues load lazily and can start late under load. Chain recording collects cues from every following chapter in playback order, including music that starts after a silent opening.\n\nVideo BGM uses the same playback engine, including `joplo render --video --chain`. Film strips (`--film`) skip audio capture and decoding so their virtual clock does not wait for a real audio device. A continuously silent capture input keeps Opus PTS intact; an end-of-recording color/pulse calibration reads actual video/audio PTS, centers the video-frame interval, then trims the calibration section. It does not use the wall clock before page creation. This end calibration does not sample-lock a whole long recording: verify independent early/late picture-and-audio events for a chain and report the measured offset; short-clip results do not prove long-chain synchronization. Generated narration clips (npx joplo voice; board export while narration is on) play through the same media engine, are captured on the same track and duck the music; browser Web Speech narration still cannot be captured. **Known issue RM5:** failed audio recording or muxing rejects the export and currently does not retain a silent-video fallback; fix the error and re-export.\n\nIf silent, check the sound switch, click Play (gesture required), and read located local-resource warnings. Missing Alda, syntax errors, download/hash failures, timeout (up to 180s for render) or size limit leave the rest playable. Fix the cause and retry build; for a failed playback slot, switch scenarios or toggle sound off/on or reload before retrying. Published sites cannot regenerate audio. A successful check without Alda is not a rendering pass. If Alda reports a failed/unreachable player or export timeout, inspect its local processes with `alda ps` and run `alda doctor`, repair that environment, then retry. A build can preserve the rest while omitting failed music: verify the expected cue count and MEDIA_ASSET records before calling audio validation successful.\n\n## Measure when listening is unavailable\n\nffmpeg is an **optional measurement tool**, never a Joplo rendering dependency. Extract each data:audio/mpeg;base64 payload and its project.mediaInfo entry from a local build. Measure only the playback region (start = contentStartFrame/sourceSampleRate; duration = contentFrames/sourceSampleRate), excluding the calibration probe and guards:\n\n```sh\nffmpeg -hide_banner -i /tmp/music.mp3 -af \"atrim=start=<start-seconds>:duration=<content-seconds>,asetpts=PTS-STARTPTS,ebur128=peak=true\" -f null -\n```\n\nReport integrated LUFS, true peak dBFS, duration and bytes, plus whether the measurement is before/after track volume and narration ducking. Compare music and narration over the **same speech interval**; as a starting point, aim for music roughly 12\u201320dB below speech, then listen. Gain .4 is about -8dB; narration ducking .25 adds about -12dB. Do not claim the final mix level from the unattenuated bank output alone. For a loop, also measure decoded frame count and sample discontinuity across the join, not just file duration. Write **\u672A\u7ECF\u4EBA\u8033\u9A8C\u8BC1** whenever human listening did not occur.\n";
package/dist/guide.js CHANGED
@@ -35,6 +35,14 @@ For a historical or multi-theme piece, keep original motifs in one score map, re
35
35
 
36
36
  \`from\` is a marker name without \`%\`, resolved by Alda during local compilation. Only a numeric offset enters IR; jump/deep link/screenshot state uses that same offset plus the engine anchor. A non-continuing scenario starts silent. Same-score play continues; a different score with fadeMs crossfades; chapter() default continuation inherits music. An explicit marker selects a numeric seek. Set \`loop: true\` only for a phrase designed to repeat. Loop repeats the full score; from only selects its initial seek, not a loop region. \`volume\` is 0–1, \`fadeMs\` 0–30000. Put play alongside a chapter's visual change. Stop with done, allowing an ending hold for the fade; a stop at the instant playback ends cannot create extra playback time. Anchors advance with commitGapMs: the preceding step's planned stay (hold or reading time, or estimated narration when that is longer) plus the next step's action demonstration. Use explicit \`hold(seconds)\` when exact chapter pacing matters. Actual narration or interaction waits do not redefine later planned score anchors.
37
37
 
38
+ ## Delayed starts and crowded crossfades
39
+
40
+ music.play('film', { startDelayMs: 300, duck: false, maxRetiring: 1 }) waits 300 engine ms after the step commits. startDelayMs accepts 0–60000; it does not seek or consume notes. from still selects the source marker. Fade-in begins at actual source start. Pause freezes the wait, speed scales its wall duration, and chapter continuation preserves remaining wait. Explicitly issuing delay again creates a new deterministic event even with the same score; omit the option to retain existing behavior.
41
+
42
+ duck defaults true: narration multiplies the authored gain by .25. duck:false exempts this music track, including its own retiring fades; it does not change narration or other tracks. Use a restrained volume and listen to the mix. maxRetiring is an integer 0–32 per named track: 1 means current music plus the most recently retired music; 0 removes exiting music immediately while preserving current. Omit it to retain all exiting fades as before. Limits evict by retirement order, not resource name or remaining fade length, and never cap unrelated tracks or independent SFX. When replacing music with both startDelayMs and fadeMs, the old cue starts fading out at command commit and the new cue starts fading in only after its delay. If delay exceeds fadeMs, there can be a silent gap; this combination does not promise a continuous crossfade. For an ordinary continuous crossfade omit the delay. End holds must include any delay and fade you want the audience to hear; delay adds no automatic hold.
43
+
44
+ For offline reconstruction retain timeline media snapshots and packaged audio. startDelayMs is the original plan, delayRemainingMs the remaining wait, startEventId the explicit delayed event identity, and endAfterMs (when present) excludes waiting. For a fresh delayed play observed at commit engineMs, the nominal eligibility time for this observation is engineMs + delayRemainingMs (falling back to startDelayMs only when remaining is absent). On an inherited snapshot use its remaining wait, never add the original plan again; the same startEventId identifies the continued cue, while a new startEventId is a new explicit delayed play even for the same resource. A chapter/deep-link timeline may first observe an inherited cue as play, so deduplicate across joined observations by that identity rather than resource alone. If remaining is zero on a continued identity, it is already eligible: do not emit another start or infer its original onset from that snapshot. Without the earlier play observation, the original start is unknown. Source trim, fade-in and silence inside the audio bytes can shift the first audible sample; scheduling metadata cannot detect that silence. Timeline play events identify observed command commits, not measured acoustic onset; the existing export sampling tolerance still applies. MUSIC_OPTIONS_INVALID means fix these option types/ranges, not reinstall Alda.
45
+
38
46
  ## Plan the form before notes
39
47
 
40
48
  Write a table: **section / bars / chord in each bar / chapter duration / marker**. For fixed meter and BPM:
@@ -114,6 +122,25 @@ Separate named pieces suit contrasting eras or a chapter that changes length ind
114
122
 
115
123
  MEDIA_ASSET_LARGE checks the 2 MiB absolute size for every track; the 0.75 MB/min rate check only applies to clips at least 15 seconds long. Short clips pay fixed codec context overhead: splitting them does not improve bitrate.
116
124
 
125
+ ## Stable local lossless files
126
+ For pitched one-shot effects or external lossless mixing, import renderLossless from @joplo-app/plugin-alda/local. It shares music.play's Alda → MIDI → verified bank → normalized PCM → FLAC master path, with no MP3 calibration probe, guard or encoder padding. It does not read internal music-masters filenames or choose a JOPLO_HOME for you.
127
+ \`\`\`ts
128
+ import { renderLossless } from '@joplo-app/plugin-alda/local';
129
+ import { mkdtemp, writeFile, rm } from 'node:fs/promises';
130
+ import { tmpdir } from 'node:os';
131
+ import { join, resolve } from 'node:path';
132
+ const directory = await mkdtemp(join(tmpdir(), 'joplo-score-'));
133
+ try {
134
+ const result = await renderLossless('piano: c1', {
135
+ directory, cacheDir: resolve('.cache/alda'), loop: false,
136
+ maxBytes: 50 * 1024 * 1024,
137
+ });
138
+ await writeFile('cue.flac', result.bytes);
139
+ console.log(result.audio, result.info.markers);
140
+ } finally { await rm(directory, { recursive: true, force: true }); }
141
+ \`\`\`
142
+ directory is a caller-owned writable temporary-work parent; jobs clean their private subdirectory. cacheDir is an explicit persistent private plugin cache (a project-owned .cache/alda is valid); provision its verified SoundFont cache online before offline rendering. First use can download the same pinned bank/license as ordinary music. No cloud/TTS generation occurs. Install Alda 2.4.8 when the tool is missing, verify \`alda version\`, then retry; the API preserves the existing pinned-version/bank verification failures. Output is fixed 44.1kHz stereo 16-bit FLAC with existing AudioRegion metadata: contentStartFrame/encoderDelayFrames/paddingFrames are zero, contentFrames includes non-loop release/reverb tail, cycleFrames is the musical cycle, and info.durationMs/markers describe score timing. loop:true folds the tail into the cycle; loop:false keeps it. bytes/credit/license use the existing LocalArtifact fields; preserve attribution with downstream files. This is an author-file API, not a larger playback budget: verify encoded 4 MiB and decoded 32 MiB host limits before embedding the file.
143
+
117
144
  Pipeline: Alda 2.4.8 → temporary MIDI → SpessaSynth Core 4.4.9 with FluidR3Mono GM 2.312 → 44.1kHz stereo PCM → **MP3 96 kbps stereo at 32kHz**. The deterministic 24-tap/256-phase resampler, fixed LAME encoder (@breezystack/lamejs 1.2.7) and verification decoder (mpg123-decoder 1.0.3) run in Node; no ffmpeg or FluidSynth installation is required. FLAC (libflacjs 5.6.0) is only an author-side master in \`.joplo/music-masters\`; it never enters the site, and there is no lossless publication switch. First rendering downloads the pinned, SHA-256-verified ~14.5MB SF3 and license to \`JOPLO_HOME/plugins/alda/cache/soundfonts/<hash>/\` (default ~/.joplo). The bank stays local. Published \`credits.txt\` and \`music-LICENSE.txt\` preserve bank attribution and full license even when Alda inspection is unavailable; missing artifact attribution blocks publication.
118
145
 
119
146
  To preinstall on a connected author machine, run this **from the project**:
package/dist/index.d.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  export type MusicOptions = {
2
2
  fadeMs?: number;
3
+ startDelayMs?: number;
4
+ duck?: boolean;
5
+ maxRetiring?: number;
3
6
  loop?: boolean;
4
7
  volume?: number;
5
8
  from?: string;
package/dist/index.js CHANGED
@@ -14,6 +14,10 @@ export function alda(scores) {
14
14
  ctx.report('MUSIC_SCORE_MISSING', 'Unknown score; declare the same name in alda({ name: "score text" })', ctx.source, 'error');
15
15
  return;
16
16
  }
17
+ if (payload.startDelayMs !== undefined && (typeof payload.startDelayMs !== 'number' || !Number.isFinite(payload.startDelayMs) || payload.startDelayMs < 0 || payload.startDelayMs > 60000) || payload.duck !== undefined && typeof payload.duck !== 'boolean' || payload.maxRetiring !== undefined && (typeof payload.maxRetiring !== 'number' || !Number.isInteger(payload.maxRetiring) || payload.maxRetiring < 0 || payload.maxRetiring > 32)) {
18
+ ctx.report('MUSIC_OPTIONS_INVALID', 'startDelayMs requires 0–60000 engine milliseconds, duck requires boolean, and maxRetiring requires an integer 0–32 (per named track; current music is excluded)', ctx.source, 'error');
19
+ return;
20
+ }
17
21
  if (payload.from !== undefined && (typeof payload.from !== 'string' || !payload.from || payload.from.startsWith('%'))) {
18
22
  ctx.report('PLUGIN_PROPERTY_INVALID', 'Music from requires a nonempty marker name without %', ctx.source, 'error');
19
23
  return;
@@ -27,7 +31,7 @@ export function alda(scores) {
27
31
  }
28
32
  if (info)
29
33
  ctx.report('MUSIC_SCORE', `${payload.name}: ${(info.durationMs / 1000).toFixed(3)} s; notes ${Object.entries(info.parts ?? {}).map(([name, count]) => `${name}=${count}`).join(', ')}; part ends ${Object.entries(info.partDurationsMs ?? {}).map(([name, ms]) => `${name}=${(ms / 1000).toFixed(3)} s`).join(', ') || '(unavailable)'}; markers ${Object.entries(info.markers ?? {}).sort((a, b) => a[1] - b[1]).map(([name, ms]) => `%${name}=${(ms / 1000).toFixed(3)} s`).join(', ') || '(none)'}`, ctx.source, 'info');
30
- return { media: [{ track: 'bgm', action: 'play', resource, offsetMs: offsetMs ?? 0, fadeMs: payload.fadeMs ?? 0, loop: payload.loop ?? false, volume: payload.volume ?? .25 }] };
34
+ return { media: [{ track: 'bgm', action: 'play', resource, ...(payload.startDelayMs !== undefined ? { startDelayMs: payload.startDelayMs } : {}), ...(payload.duck !== undefined ? { duck: payload.duck } : {}), ...(payload.maxRetiring !== undefined ? { maxRetiring: payload.maxRetiring } : {}), offsetMs: offsetMs ?? 0, fadeMs: payload.fadeMs ?? 0, loop: payload.loop ?? false, volume: payload.volume ?? .25 }] };
31
35
  } },
32
36
  });
33
37
  }
package/dist/local.d.ts CHANGED
@@ -1,6 +1,17 @@
1
- import type { LocalResourceInfo } from '@joplo-app/kit/plugin';
1
+ import type { AudioRegion, LocalArtifact, LocalResourceInfo } from '@joplo-app/kit/plugin';
2
2
  export declare const installSoundfont: () => Promise<void>;
3
3
  export declare function inspectScore(score: string, directory: string): Promise<LocalResourceInfo>;
4
+ export type RenderLosslessOptions = {
5
+ directory: string;
6
+ cacheDir: string;
7
+ loop?: boolean;
8
+ maxBytes?: number;
9
+ };
10
+ /** Stable lossless author API. Uses the same PCM/master encoder as music.play, without MP3 probe/guards. */
11
+ export declare function renderLossless(score: string, options: RenderLosslessOptions): Promise<LocalArtifact & {
12
+ audio: AudioRegion;
13
+ info: LocalResourceInfo;
14
+ }>;
4
15
  declare const _default: {
5
16
  compilers: {
6
17
  audio: {
@@ -9,7 +20,8 @@ declare const _default: {
9
20
  mime: string;
10
21
  timeoutMs: number;
11
22
  inspect(input: string, ctx: {
12
- directory: string;
23
+ readonly directory: string;
24
+ readonly projectDir: string;
13
25
  }): Promise<LocalResourceInfo>;
14
26
  compile(input: string, ctx: {
15
27
  directory: string;
@@ -20,7 +32,7 @@ declare const _default: {
20
32
  maxBytes: number;
21
33
  }): Promise<{
22
34
  bytes: Uint8Array<ArrayBufferLike>;
23
- audio: import("@joplo-app/kit/plugin").AudioRegion;
35
+ audio: AudioRegion;
24
36
  credit: string;
25
37
  license: string;
26
38
  }>;
package/dist/local.js CHANGED
@@ -37,18 +37,45 @@ export async function inspectScore(score, directory) {
37
37
  throw new Error('Score contains no timed music');
38
38
  return { durationMs, parts, partDurationsMs, markers: parsed.markers, credit };
39
39
  }
40
+ async function sourcePCM(score, options) {
41
+ if (typeof score !== 'string' || !score.trim())
42
+ throw new Error('Score must be nonempty');
43
+ if (typeof options.directory !== 'string' || !options.directory.trim())
44
+ throw new Error('Provide a writable work directory');
45
+ await fs.mkdir(options.directory, { recursive: true });
46
+ const job = await fs.mkdtemp(path.join(options.directory, 'alda-'));
47
+ try {
48
+ const version = (await run(['version'], job)).trim();
49
+ if (version !== 'alda 2.4.8')
50
+ throw new Error(`Expected Alda 2.4.8; found ${version}`);
51
+ const info = await inspectScore(score, job), midi = path.join(job, 'score.mid');
52
+ await run(['export', '-f', path.join(job, 'score.alda'), '-o', midi], job);
53
+ const pcm = await renderPCM(await fs.readFile(midi), await soundfont(options.cacheDir), info.durationMs, options.loop ?? false);
54
+ return { pcm, info };
55
+ }
56
+ finally {
57
+ await fs.rm(job, { recursive: true, force: true });
58
+ }
59
+ }
60
+ /** Stable lossless author API. Uses the same PCM/master encoder as music.play, without MP3 probe/guards. */
61
+ export async function renderLossless(score, options) {
62
+ if (typeof options.cacheDir !== 'string' || !options.cacheDir.trim())
63
+ throw new Error('Provide an explicit plugin cacheDir');
64
+ if (options.loop !== undefined && typeof options.loop !== 'boolean')
65
+ throw new Error('loop must be boolean');
66
+ if (options.maxBytes !== undefined && (!Number.isInteger(options.maxBytes) || options.maxBytes <= 0))
67
+ throw new Error('maxBytes must be a positive integer');
68
+ const { pcm, info } = await sourcePCM(score, options), bytes = await encodeFlac(pcm), frames = pcm[0].length;
69
+ if (bytes.length > (options.maxBytes ?? 50 * 1024 * 1024))
70
+ throw new Error('Lossless audio exceeds maxBytes; shorten the score or choose a larger explicit limit');
71
+ return { bytes, audio: { sourceSampleRate: 44100, decodedFrames: frames, contentFrames: frames, cycleFrames: Math.min(frames, Math.round(info.durationMs * 44.1)), contentStartFrame: 0, encoderDelayFrames: 0, paddingFrames: 0, channels: pcm.length }, info, credit, license };
72
+ }
40
73
  export default { compilers: { audio: {
41
74
  requiresAttribution: true, version: `alda-2.4.8-${RENDER_VERSION}-${SOUNDFONT.sha256}-${MP3_VERSION}`, mime: 'audio/mpeg', timeoutMs: 180000,
42
75
  async inspect(input, ctx) { return inspectScore(request(input).score, ctx.directory); },
43
76
  async compile(input, ctx) {
44
77
  const { score, loop } = request(input);
45
- const version = (await run(['version'], ctx.directory)).trim();
46
- if (version !== 'alda 2.4.8')
47
- throw new Error(`Expected Alda 2.4.8; found ${version}`);
48
- const info = await inspectScore(score, ctx.directory);
49
- const output = path.join(ctx.directory, 'score.mid');
50
- await run(['export', '-f', path.join(ctx.directory, 'score.alda'), '-o', output], ctx.directory);
51
- const pcm = await renderPCM(await fs.readFile(output), await soundfont(ctx.cacheDir), info.durationMs, loop);
78
+ const { pcm, info } = await sourcePCM(score, { directory: ctx.directory, cacheDir: ctx.cacheDir, loop });
52
79
  const master = await encodeFlac(pcm);
53
80
  const masters = path.join(ctx.projectDir ?? ctx.directory, '.joplo', 'music-masters');
54
81
  await fs.mkdir(masters, { recursive: true });
package/dist/version.json CHANGED
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.7.1"
2
+ "version": "0.7.2"
3
3
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joplo-app/plugin-alda",
3
- "version": "0.7.1",
3
+ "version": "0.7.2",
4
4
  "type": "module",
5
5
  "joplo": {
6
6
  "api": 2
@@ -26,7 +26,7 @@
26
26
  },
27
27
  "dependencies": {
28
28
  "@breezystack/lamejs": "1.2.7",
29
- "@joplo-app/kit": "0.7.1",
29
+ "@joplo-app/kit": "0.7.2",
30
30
  "libflacjs": "5.6.0",
31
31
  "mpg123-decoder": "1.0.3",
32
32
  "spessasynth_core": "4.4.9",