AIStoreHub Package Vault: earshot
Package Slug: earshot
Archetype: mcp_server
Upstream Repository: https://github.com/Leonxlnx/earshot
Workspace Files & Specifications (68 files)
- .claude-plugin/marketplace.json (687 bytes)
{ "name": "earshot", "description": "earshot for Claude Code: the earshot and real-sound skills, the earshot MCP server and two commands.", "owner": { "name": "Leon Lin", "url": "https://github.com/Leonxlnx" }, "plugins": [ { "name": "earshot", "source": "./", "description": "Make sound effects from a request in words: interface sounds, everyday foley, ambience, game, film and motion sounds and drums, computed when asked (the realistic ones learned from public-domain recordings, no audio shipped), and build what the catalogue lacks from its parts. Listen to sound an agent cannot hear: describe, match, measure and critique it." } ] } - .claude-plugin/plugin.json (911 bytes)
{ "name": "earshot", "version": "1.0.0", "description": "Make sound effects from a request in words: interface sounds, everyday foley, ambience, game, film and motion sounds and drums, computed when asked (the realistic ones learned from public-domain recordings, no audio shipped), and build what the catalogue lacks from its parts. Listen to sound an agent cannot hear: describe, match, measure and critique it.", "author": { "name": "Leon Lin" }, "homepage": "https://github.com/Leonxlnx/earshot", "repository": "https://github.com/Leonxlnx/earshot", "license": "MIT", "keywords": ["audio", "sound", "sound-effects", "sound-design", "procedural-audio", "synthesis", "game-audio", "ui-sounds", "audio-analysis", "mcp"], "mcpServers": { "earshot": { "command": "earshot", "args": ["mcp"], "env": { "EARSHOT_THREADS": "3" } } } } - aistorehub.json (492 bytes)
{ "name": "earshot", "slug": "earshot", "version": "1.0.0", "type": "mcp_server", "description": "Sound effects for coding agents: ask in plain words and earshot renders the sound in code. CPU-only, no audio model, open source.", "owner": "community", "repository": "catalog", "github_repo_url": "https://github.com/Leonxlnx/earshot", "tags": [ "claude-code", "mcp", "sound-design", "ai-agents", "audio" ], "imported_at": "2026-11-24T20:32:30.731Z" } - CHANGELOG.md (52879 bytes)
# Changelog ## 1.0.0 - 2026-11-20 earshot now makes sounds as well as listening to them. An agent asks for a sound in words and earshot renders a new take of a design from its catalogue, with no model and no network. When the catalogue lacks the thing, the answer says so, and `earshot build` makes it from recorded parts named in words, heard and tuned by earshot's listening model. Realistic sounds are learned from recordings in the public domain and kept as numbers, not audio. Fixes from the community: thanks to @Bortlesboat, @anascherif and @liugedragon. The base install is lighter than before: numba is the one new requirement, and the listening stack moved to an extra. ### Added **Asking for a sound** - `earshot make "WORDS" -o FILE` (`earshot/make.py`, MCP `make`, `api.make`) reads the request, ranks the catalogue, renders the best design with the request's controls, checks the take (clicks, cut tails, clipping, DC, comb ring, rising glides, stacked attacks; a failed take is rendered again on up to three more seeds) and writes wav, flac, ogg, mp3, m4a or webm. A one-shot takes a few seconds from the command line on one thread. - The answer is a few plain lines: the design, its length, where its loudest moment is (`peak at`), its loudness, `clean` or what the check found, and the words that chose it; three alternatives (`also`); and what the sound does not cover, does not follow or did not understand. Every take also carries `peak_s`, `onset_s` and, for a row of events, `events_s`. - Every request gets a sound. When the catalogue lacks the thing, the answer says "earshot makes no X; Y is only the nearest sound it has", offers three starting points from other families and names the `earshot build` call that builds it. - The options of `make`: `--n`, `--seed`, `--sound ID`, `--theme`, `--pitch`, `--dur`, `--voice`, `--material`, `--events`, the eight axes, `--lufs`, `--mono`, `--no-loop`, `--listen` and `--recipe`. Out-of-range values are refused with one plain sentence. - `earshot sounds` (MCP `sounds`) lists and searches the catalogue. - The reader (`earshot/brief.py`, `earshot/sounds/lexicon.py`) needs no model. It reads the thing, the job and the sound; feelings as offsets on eight axes (bright, hard, ring, size, space, width, energy, motion); negation and comparison; voices and materials; lengths, gaps, counts, pitches and keys; loop or one-shot; the moment a sound plays ("when the pricing card settles"); and words for the product or the place, which choose nothing. - What follows "on" or "in" is the sound's surface or place ("rain on wood"). A surface the sound has no design on gets the nearest one and says so ("rain on a tarp": `rain/tent is the nearest surface`). - A request in German is read through a table of about 400 sound words ("Regen auf Holz"), with inflected adjectives and participles ("ein leiser Klick", "schwere Schritte", "eine knarrende Tür") and requests whose every word is English too ("ein lauter Donner"); a request in another language gets "write it in English". - A request for a thing earshot lacks says so in more wordings: an unknown thing doing a known thing ("a zeppelin arriving at the station", "a flock of geese flying over"), a thing named in -ey, -way or -ory ("a monkey", "a subway", "a factory"), a word only another design lists as a job ("a trap springing shut") and a name made of an unknown word and a known one ("a conveyor belt"); a known thing doing something unknown ("plates clattering", "a siren getting closer") is answered without that doubt. - The nearest of a thing the cookbook only sketches is a part its sketch is built on, and the sketch's other parts are the first starting points; when no word of a request found anything the starting points are a knock, a drill and a whoosh; a synthesized sound or an instrument's note is never a starting point for a thing of the world. - A plain film request in a few words ("a title hit", "a logo reveal", "a riser", "an impact", "a glint") gets the film set's sound of real things first; a request that names a design word for word keeps that design. - A recording answers the words of its own thing only: not the place in its name ("a car on gravel" is no hail on a car), its family's word said as what something else does ("air blowing", "darting forward"), a thing the sound is only compared with ("BRAAM, like a giant ship horn") or the window a product's job is done to ("putting a window away"); things recorded since ("a foghorn", "a refrigerator hum", "mice squeaking") are no longer called missing. - A request that asks for a change as the sound plays ("getting louder"), for a sound heard through something ("behind a closed door"), for a sound that moves from left to right, or for a length the design does not keep, says so in the answer. **Building what the catalogue lacks** - `earshot build "WORDS" -o FILE` (`earshot/build.py`, MCP `build`, `docs/BUILD.md`) builds a sound with earshot as the ears: it drafts one to three recipes from the words (a structure by the kind of sound, the recorded designs nearest the words as parts), renders and hears them with the listening model, tunes their numbers in a seeded search and writes the sound and its recipe. The answer gives the fit to the words beside the design `make` would hand over, what it is heard as and what is still off, each with the recipe field to change; `--recipe` hears an edited recipe again. Without the listen extra it drafts, renders, audits and measures. - Parts in words: an agent names what the sound is made of (`--part "hundreds of hoofbeats on dirt, for 6 s, getting louder"`, MCP `parts`). A small grammar turns how many, when, how long, motion, pitch, distance and force into the layer's fields, the rest of the phrase is grounded in a recorded design, and the answer says which design each part became, the next nearest, what the catalogue has no recording of and every word it did not understand. - A part's thing is also looked up in the designs' own words: "hoofbeats" finds the horse's hooves, "a low rumble" a rumble and not whatever is low, "a train whistle" a design with both words; a synthesized design only when no recording names the thing, and then the line says it is synthesized. - The automatic draft scatters many of one thing ("a stampede of horses", "applause"), lets the head of the words lead ("a fire alarm" is an alarm), and always tries the plain design `make` would hand over, saying so when that wins. A second ear (the AudioSet tagger), which the tuner never sees, must not contradict a "sounds like it"; a remark that compares with another design is made only when that design is of the same thing and following it does not lower the fit. - Recipes (`earshot/recipe.py`; `earshot make --recipe FILE`; `earshot recipe --example`, `--list`, `NAME` and `--check`; MCP `make` with `recipe`; a spec entry's `recipe`) build a sound from recordings as a small JSON form of up to 12 layers: designs, noise or a low sine, with pitch, glide, reverse, cut, halt, filters, gain, fades, swell, decay, repeated events and one layer's loudness following another's; `scatter` (one take many times at random moments, up to 400 a second: rain from drops, applause from claps), `level` and `bend` (loudness and pitch drawn over time), `pan` to a side or across, `pass` (a thing going by, its pitch falling as it passes), `spin` (rotor, wings, purring), `stretch` (longer at the same pitch, 0.5 to 2) and a cookbook recipe as a layer. A recipe is rendered and checked like every sound. - A cookbook of 99 recipes (`earshot/data/recipes`). 59 answer a request for their thing on their own (a car crash, a cannon, a woodpecker, marbles pouring, rocks tumbling, a tornado, and what no recording holds: a fireball spell, an energy shield going up, a plasma shot, a robot arm and more); 40 are sketches that an answer names as a starting point. A recording of the thing itself answers before a recipe. A length, far away, up close, soft and a count asked of a cookbook sound are followed, or the answer says they are not. **The catalogue** - 922 designs in 384 families (`earshot/sounds/`; the `@design` contract in `registry.py`). - 309 learned designs (`earshot/sounds/learned.py`, `earshot/synth/resyn.py`, `earshot/data/resyn/`) of everyday, interface, game and film sounds, animals, people without words, street, house and kitchen sounds, learned from 692 recordings in the public domain (BigSoundBank, Kenney, VCSL, VSCO-2 CE, Karoryfer and CC0 uploads on Freesound; each credited in a `CREDITS.md`). Each recording is kept as numbers (56 bands, 2 ms envelopes, 0.25 ms around onsets, tonal carriers, the stereo image; 17.93 MB in all, no audio), and every render is a new take of it. Seeds walk through a design's recordings, the fullest clean one first; `meta['member']` names the recording by number. A learned design answers only a request that names its thing, and wins over an invented design of the same thing. - Performances (`earshot/synth/perform.py`, `--events`): a thing a person does several times in a row (a walk, a knock, typing, coins, keys, clinking glasses) is played as the action when the words ask for it, from a recording of the whole action or from single recordings in a pattern a person plays. A length or a gap asked with it sets the file's length or the time between events. - 25 learned ambience beds (`earshot/synth/quilt.py`, `earshot/data/textures/`, `earshot/sounds/nature.py`), stitched from pieces of 24 recordings so that they play for any length without a loop point: a campfire, three shores, crickets, a brook, a cafe, a street, rain on wood, on a tin roof and on an umbrella and more. 18 more ambience scenes are made from rules. - 60 things and 9 beds that requests asked for and the catalogue lacked are learned from public-domain recordings: a chainsaw, a lawn mower, a tractor, a truck reversing, a ship's horn, a monkey, a parrot, knuckles, a hiccup, ping pong, pinball, darts, a ratchet, an angle grinder, a coffee machine, a kettle boiling and whistling and more; hail, a dishwasher, a washing machine, a fridge, a shower, a jungle at night, a factory and a gale as beds. - The interface sounds are things a hand does, built from learned recordings (`earshot/sounds/interface.py`, 29 designs): a mechanical key going down and coming up, a page, a drawer, a cork, knocks, a camera shutter, a cut of scissors. A plain request for an interface job gets the design the `ui` set plays, and a thing of the world named in words ("a door closing") gets its own recording. - 69 film and motion designs (`earshot/sounds/motion.py`, `earshot/synth/design.py`). 55 are built from learned recordings the way motion films use them (short dry hits, a 50 ms thump, a bright tick, whooshes and risers of air, a tape stop, a braam of real brass), following measurements of 39 professional motion videos; 14 small ones are invented. A motion request gets no instrument note unless its words ask for music. - 40 drum designs (`earshot/sounds/drums.py`, `earshot/data/drums/`): the acoustic kit and hand percussion are played from 130 recorded strokes in the public domain; the drum-machine voices, a brush snare, a finger snap and a stick count are invented. - Tonal figures for interfaces, games and brands (45, and 3 material ticks), played on real instruments learned note by note (`earshot/synth/played.py`, `earshot/data/notes/`: marimba, harp, pizzicato strings and an upright piano, 97 notes). They answer an interface request only when its words ask for music or a theme is named. - 51 notes of other voices, 14 synthesizer sounds, 24 chip sounds (only when asked for), 83 sounds of actions and objects invented from physics, three short music loops, and the 209 named members of the sound bank. **Sets** - `earshot make --set ui|game|arcade|film` and `--spec FILE` (MCP `make_set`) make a family of sounds in one call with a `manifest.json`, in several formats at once (`--format webm,mp3`) and with a sprite (`--sprite`). One-shots are as loud as they are made alone and within 2.5 dB of each other; loops and beds are levelled by kind; a loop is written as flac in place of mp3 or m4a, whose padding leaves a gap at the seam. - Four ready-made sets (`earshot/sounds/sets.py`: `ui` 17, `game` 22, `arcade` 16, `film` 17) and nine theme presets (`theme.py`) that give a family one voice, key, room and axis offsets. - The `film` set plays small real actions cut to the measurements of motion videos, each naming its recordings by file: a door falling shut when something appears, a mechanical key's tick, a page sliding, a stick and a broom through the air, a heavy bag dropped under a title and a logo, a car door for an impact, a breath of air rising, a sword drawn. - `earshot pack` lays many sounds in one file with a map in the format howler.js reads. **Listening** - The sound atlas (`earshot/sounds/atlas.py`, `earshot/data/sounds_atlas.npz`, numbers only): a CLAP embedding of every design. `make --listen` blends how the designs sound into the ranking and says what the result is heard as; `build` hears with it and with the AudioSet tagger. **Install and around it** - The Claude Code plugin (`.claude-plugin/plugin.json`, `.claude-plugin/marketplace.json`, `commands/`): the repository is a plugin and its own marketplace (`/plugin marketplace add Leonxlnx/earshot`, `/plugin install earshot@earshot`) with the two skills, the MCP server of the installed `earshot`, and the commands `/earshot:make` and `/earshot:make-set`. - The earshot skill opens with a complete part on making and building sounds. `docs/MAKE.md` is the reference of making, `docs/BUILD.md` of building; `docs/VALIDATION.md` and `docs/LIMITS.md` cover the made and built sounds. - Tests for the catalogue contract, the learned sounds and their engines, the beds, drums, music loops, the reader, `make`, sets, recipes, `build` and `pack`; the long renders and the tests that load CLAP run with `--slow`. - CI (#32; thanks, @liugedragon): a Linux job runs the fast tests without the models (`.github/workflows/fast-tests.yml`, `docs/TESTING.md`). - `earshot --version`, and earshot's version on the first line of `earshot doctor`; a base install starts without a word about the listen extra, and the first listening call says in one line what it downloads, how large and where. ### Changed - A lighter install: the base install is numpy, scipy, soundfile, soxr and numba (new: it compiles the synthesis loops), which is all that making sounds needs. torch, transformers and librosa moved to the `listen` extra, librosa also to `measure`, matplotlib and pillow to `images`, and `all` brings every extra. - A command, MCP tool or Python function that needs a missing extra stops with one sentence that names the package an - commands/make-set.md (2058 bytes)
--- description: Make a whole set of sounds with earshot as one family (one voice, key and room, levels balanced) and write it into the project argument-hint: "[ui|game|arcade|film or the product's sounds in words] [theme]" --- Make a set of sounds with earshot: $ARGUMENTS 1. Read the words: a ready-made set (`ui` 17 interface sounds, each a normal thing a hand does: a key, a page, a drawer, knocks, a camera shutter, no instrument; `game` 22; `arcade` 16 chip sounds; `film` 17 motion-design sounds), a theme (soft, glass, wood, felt, tine, metal, electric, digital, retro; it sets the voice, key and room of the tonal sounds, and turns `ui` into its tonal figures: name one only when the words ask for that), and any sounds of their own (each a `name` for the file and a `want` in words, or a `sound` id). Pick the folder this project keeps sounds in, else `sounds/`; format `webm,mp3` for a web project (every browser plays one of the two), `wav` otherwise, unless the words name one. 2. Call the `make_set` tool of the earshot MCP server once, with `out` = the absolute folder, `set`, `theme`, `format` and, for sounds of their own, `sounds: [{"name": "tap", "want": "a soft tap"}, ...]`. If no earshot MCP server is connected, run `earshot make --set NAME --theme THEME -o FOLDER --format FMT`, or write the list as a JSON spec (`{"set": ..., "sounds": [...]}`) and run `earshot make --spec FILE -o FOLDER`. One call for the whole set, never one `make` per sound. If `earshot` is not found, say it must be installed first: `uv tool install "earshot[mcp] @ git+https://github.com/Leonxlnx/earshot"`. 3. Report the answer as given: the folder and count, one line per file, and any file whose line does not say `clean` (not usable: make that sound again with another `seed`). A line `another recording of ...` says two names play two recordings of one learned design, as intended; a line `same design as ...` means two names got one sound: ask for another with `sound`. The folder also holds `manifest.json`. - commands/make.md (2543 bytes)
--- description: Make one sound with earshot from the words given and write it into the project argument-hint: "[the sound in words, e.g. a soft success chime for a finance app, a wooden drawer closing]" --- Make this sound with earshot: $ARGUMENTS 1. Pick the file: the folder this project keeps sounds in (for example `public/sounds/` or `assets/audio/`), else `sounds/`; a short name from the job (`success.mp3`); `.mp3` for a web project (`.webm` for a loop: an mp3 loop has a gap at its seam), `.wav` otherwise, unless the request names a format. If the request asks for variations ("three variations of a footstep"), keep the words: one call writes `name_1 .. name_N`. Keep the number of a thing a person does in a row as written too: "footsteps on gravel" or "knocking" is played as the action, "a footstep" or "a single knock" as one event, "three claps" is one file of three claps, and a length asked with an action ("clapping, 4 seconds") is the file's length. For a motion video or an interface do not add words of music: without them earshot gives normal sounds, no instrument notes. 2. Call the `make` tool of the earshot MCP server once, with `want` = the request as written and `out` = the absolute path. If no earshot MCP server is connected, run `earshot make "REQUEST" -o PATH` instead. No `full=true`, `--json` or `--listen`. If `earshot` is not found, say it must be installed first: `uv tool install "earshot[mcp] @ git+https://github.com/Leonxlnx/earshot"`. 3. Report the answer as given: the file line (design, length, where its loudest moment is, pitch and voice for a tonal sound, loudness, `clean` or what the check found), `also: ...`, a `played: ...` line (one event or the action), any `not understood` / `not followed` line, and a line about the length (a cut, the shortest loop, whole bars, a counted action that could not fill it). A take that is not `clean` is not usable: make it again with another `seed`. If the answer says "earshot makes no ...", the file is only the nearest sound: say so plainly, name the starting points it offers, and do not present it as the thing; it can be built from recorded parts with `earshot build "REQUEST" -o PATH` (the earshot skill has the loop). Do not say how it sounds beyond what the answer says. If the design is a learned one (a real thing such as a footstep, a switch, a door or a drum), say it is a new take of a public-domain recording, computed from a model of it (no audio file is shipped or played back). - docs/BUILD.md (20865 bytes)
# earshot build: a sound the catalogue lacks, built with earshot as the ears `earshot make` answers from a catalogue of 922 designs. For a thing it has nothing of it says so (`earshot makes no whale song; wolf/howl is only the nearest sound it has`). `earshot build` is the workbench for that case: it drafts a recipe (`earshot.recipe`) from the words, renders it, listens to it with earshot's listening model, moves its numbers until it fits the words better, and says what is still off in lines an agent can act on. ``` earshot build "hail on a tin roof" -o hail.wav # draft, render, hear, tune: hail.wav, hail.recipe.json earshot build "a stampede of horses" -o stampede.wav \ --part "hundreds of hoofbeats on dirt, for 6 s, getting louder" \ --part "a low rumble under everything" \ --part "a horse neighing, twice, far" # you name the parts, earshot finds the recordings earshot build "hail on a tin roof" --recipe hail.recipe.json # your edited recipe: render it, hear it, say what is off earshot build "a stampede" --rounds 40 --without step/gravel rain --json ``` ```python from earshot.build import build, draft, hear, tune, from_parts r = build('hail on a tin roof', out='hail.wav') print(r['summary']) # the lines below; r['heard'] holds every number r = build('a stampede of horses', out='stampede.wav', parts=['hundreds of hoofbeats on dirt, for 6 s', 'a low rumble under everything']) recipe, parts = from_parts('a stampede of horses', ['a horse neighing, twice, far']) # the recipe, not rendered drafts = draft('a whale singing') # one to three recipes from the words alone heard = hear('hail.recipe.json', 'hail on a tin roof') better = tune(drafts[0], 'a whale singing', rounds=20)['recipe'] ``` The MCP server has the same as the tool `build` (`want`, `out`, `parts`, `recipe`, `rounds`, `without`, `seed`). No model generates audio here. The material is the catalogue's designs, most of them learned from public-domain recordings; the recipe gives the structure; the listening model (CLAP, the `listen` extra) only judges. ## The loop an agent runs 1. Say what physically makes the sound, one `--part` a thing: `earshot build "X" -o x.wav --part "..." --part "..."`. Without `--part` earshot drafts the parts itself (below). It writes `x.wav` and `x.recipe.json`. 2. Read the `part N` lines: which design each part became and why, the next nearest designs, the thing earshot has no recording of (`earshot has no ...`) and the words it did not understand (`not understood in part N: ...`). Swap a part by naming its design in the phrase (`"hoofbeats sound=horse/trot, many"`) or by editing the layer's `sound`. 3. Read `fit:`: the z of the sound for the words, beside the z of the design `make` would hand over, and the verdict: "sounds like it" when the sound is clean, its z is at least 3.0 and at least 1.0 over that design, and the second ear does not contradict it; otherwise "a sketch". `heard as:` names the designs it sounds most like, the words it is nearest to and the second ear's top labels. 4. Read `still off:`. Each line names the field of the recipe to change ("layer 1 (rain/tin_roof) covers the rest: the fit rises to z +4.10 without it; lower its `gain` by about 6 dB or leave it out"). 5. Change one thing in `x.recipe.json` and hear it again: `earshot build "X" --recipe x.recipe.json` (add `--rounds 20` to let the tuner move its numbers again from there). 6. Hand it over as what `fit` says. A sketch is a sketch. A person should listen once. ## Parts in words A part is one plain phrase: the thing that sounds, and how. earshot reads the phrase with this grammar; what the grammar leaves is the thing, which earshot's reader and the listening model's atlas find the nearest recorded design for (never an instrument or a synthesized design; for a many, a row or a bed it prefers a take of that shape among the near ones). `sound=<id>` names the design instead. | the phrase says | the layer gets | |---|---| | once, a single | one event | | twice, a few, several, three times, 5 times | `events` (count 2, 3, 4, 3, 5; a few and several looser) | | many, lots of, constant, steady, dozens / hundreds / thousands of, a crowd / swarm / shower / stampede / flock / hail / herd / pile of | `scatter` at a rate that fits (many 12 a second, hundreds 40, a swarm 30, a flock 8; a long take less densely) | | at 1.5 s, after 2 s; at the start; at the end; after the hit | `at` | | under everything, in the background, underneath | a bed: the whole length, `gain` -8 dB | | for 4 s | `dur` (a bed or a long take), the scatter's `dur`, or `stretch` up to 2 | | long, short | `stretch` 1.6, 0.7 | | passing, going by, flying over, racing past | `pass` (closest at the middle of the layer, 25 m/s) | | from left to right, from right to left | `pan` [-0.8, 0.8] | | getting louder, approaching, building up; fading, dying away | `level` from -18 dB up; down to -24 dB | | swelling | `swell` | | lower, deeper, higher; much lower, much higher | `pitch` -4, +4; -8, +7 | | rising, falling (on their own between commas, or "in pitch") | `bend` up or down by about 5 semitones | | reversed, backwards | `reverse` | | far, distant | `lowpass` 2500 Hz and -8 dB | | close, loud, soft, quiet, muffled | +2 dB, +3 dB, -6 dB, -6 dB, `lowpass` 800 Hz | | pulsing, throbbing, chopping, fluttering (at N a second, at N Hz) | `spin` (4 a second when no rate; chopping: `chop`) | | sound=<id> | that design | Gains are set against the first part. Everything else stays with the thing ("a low rumble", "hoofbeats on dirt"). A word neither the grammar, the reader nor the catalogue knows is answered with `not understood in part N: ...`; a thing the catalogue has no recording of with `part N: earshot has no X; Y is only the nearest it has`. The thing is looked up in the designs' own words too (ids, tags, uses, descriptions, as `earshot sounds --search` reads them): a recording whose own words name it comes before one the reader reached by a single loose word, one that names both words of a thing ("train whistle") before one that names one, and a word that only describes ("low", "big") never chooses. A sound word ("a rumble", "a hiss") is looked up the same way. A synthesized design is taken only when no recording names the thing, and the line says so: `no recording of 'X'; Y is synthesized`. The first layer may say "falling" as an action ("books falling") without a bend: only a lone "falling" between commas bends. ## What each step does **draft(words)** reads the request with earshot's reader (the thing, what it does, on what, where, how many, how long) and picks a structure by the kind of sound its words name: | structure | for | layers | |---|---|---| | one | a single event (a slam, a crack) | the nearest part, a second under it, a third lower and darker | | row | a few events ("three knocks", footsteps, galloping) | the part as `events` | | scatter | very many small events (rain, hail, applause, a swarm, a stampede) | a short part `scatter`ed, a bed under it | | run | something that runs (a motor, a machine) | a long part with `spin`, a second, a little rumble | | pass | something that passes (a car, a jet) | the part with `pass` (Doppler and distance) | | voice | a creature's voice | the nearest voice moved in `pitch` (lower for big, higher for small) with a `bend` | | long | something drawn out (a creak, a groan) | the part `stretch`ed and lower | | magic | something made up (a portal, a spell, a force field) | a reversed part as the swell, a hit at its end, air | | place | a place (a station, a forest at night) | two or three beds | The parts are recorded designs only (never an instrument, a note or a synthesized design), the nearest to the whole request and to each thing it names: with the listen extra by the listening model (half the atlas's ranking of a design's sound and descriptions, half how well its sound alone fits the words), without it by the reader's ranking. The head of the words leads ("a fire alarm" is an alarm: "fire" counts less). Many of one thing ("a stampede of horses", "a flock of geese", "a shower of books", "applause") is a scatter of the single thing. A cookbook recipe of the thing is the first draft, and the plain design `make` would hand over is always one of the drafts: when no build beats it, the answer says so and hands it over as it is. `--without` leaves out designs (an id) or families (a name). **hear(recipe, words)** renders and measures: clean or what the audit found; the length, where the hit is, how bright (the median spectral centroid) and how dense (onsets a second), beside the design `make` would hand over; with the listen extra also the fit (the same z as `earshot match`), what it is heard as, whether it is heard as recorded (`earshot realness`, from the same embedding), a steady tone heard as a note, and per layer the fit with that layer left out. When a design of the catalogue fits the words better than the build, it says which. The verdict has a second ear that the tuner never sees: the AudioSet tagger of the listen extra (527 classes, hears up to 8 kHz). Where it has a class of the thing (a label that shares a word with the request: Horse for horses), that class must be among its ten top labels; where it has none, it must not put a clearly different sound first (music, speech, a synth tone, at p 0.3 or more). Otherwise the verdict is "a sketch: the second ear does not hear it". Its top four labels are printed in `heard as:`. A remark that compares the build with the nearest design (brighter, duller, sparser, busier) is only made when that design is of the thing the words name (it shares a word with them: rain/tin_roof for heavy rain), and only when following it does not lower the fit: hear tries the change it proposes once; a remark whose change lowers the fit is printed as `not advised: ...` instead. **tune(recipe, words, rounds)** keeps the layers and their parts and moves only numbers: gains (layer 0 stays the reference), pitch and glide, cutoffs, starts, lengths, stretch, the counts, gaps and spreads of `events`, `scatter`, `pass` and `spin`, each within the range `earshot.recipe` checks (read from that module). Each round changes one or two numbers, renders, hears once and keeps the change when the score rises. The score is the fit minus penalties: not clean (1), heard as synthesized (up to 2), a steady tone (1.5), a length far from the one asked (2 for a doubling past a quarter off). The same seed gives the same result; the result always passes `earshot recipe --check`. Without the listen extra it can only keep the sound clean and near the length asked. **build(words)** drafts, hears the drafts, tunes the best, hears it again and writes the sound and the recipe. ## Time Loading the listening model takes 20 to 60 s on a laptop CPU (once per process; the MCP server keeps it warm). A round is a render and one embedding: under a second for a short event, a few seconds for a long bed of several layers. A default build (20 rounds) of a short sound takes about a minute after the model is loaded; a build of three to five named parts with beds of 6 to 10 s takes one to two minutes, as long beds cost more per round. ## Without the listen extra It drafts by the reader, renders, audits and measures (length, hit, brightness, density) and says in one line that it did not hear: `pip install "earshot[listen] @ git+https://github.com/Leonxlnx/earshot"` gives it ears. ## Worked examples **A thing the catalogue lacks.** The words name a creature's song, so the draft is a voice: the recorded calls nearest the words, moved down an octave, the first bent and stretched. Twenty rounds moved the pitches and a gain. ``` $ earshot build "a whale singing" -o whale.wav whale.wav: recipe/a_whale_singing (10.00 s, peak at 2.09 s, -14 LUFS, clean) [built] built from: owl/hoot (-11.8 semitones, bent through +0, -2 semitones, stretched 2 times); wolf/howl (-14.2 semitones) heard as: wolf/howl, downlifter/synth_fall, cat/meow; words: 'a cat meowing' (z +3.1), 'being underwater' (z +2.5), 'an explosion' (z +2.4); second ear: Howl 0.76, Animal 0.68, Canidae, dogs, wolves 0.45, Dog 0.40 fit: z +4.09 for 'a whale singing' (the nearest design wolf/howl: z +2.71): sounds like it; recorded: p_real 0.75 tuned in 20 rounds: layer 0 (owl/hoot) pitch -9 -> -11.8 semitones; layer 0 (owl/hoot) stretch 1.6 -> 2; layer 1 (wolf/howl) pitch -9 -> -14.2 semitones; layer 1 (wolf/howl) gain -9 -> -11.4 dB; fit z +3.07 -> +4.09 still off: nothing the measures find; a person should listen once next: edit whale.recipe.json, then: earshot build "a whale singing" --recipe whale.recipe.json ``` The nearest design is a wolf, so no line compares the whale's brightness with it: a whale is darker than a wolf, and raising the pitch to match the wolf lowered the fit from +4.09 to +3.71. The second ear's top labels are a wolf's: the tagger has a class for a whale, and whether it is among its top ten decides the verdict at the margin. A person is the last judge. **Parts named by an agent.** ``` $ earshot build "a stampede of horses" -o stampede.wav --part "hundreds of hoofbeats on dirt, for 6 s, getting louder" --part "a low rumble under everything" --part "a horse neighing, twice, far" part 1 'hundreds of hoofbeats on dirt, for 6 s, getting louder': horse/trot (scattered 16.5 a second over 6 s, its level drawn: -18, +0 dB); horse/trot names 'hoofbeats' in its own words (atlas and own words +3.5, a short take to repeat); next nearest: heart/beat, whisk/beat, step/concrete part 2 'a low rumble under everything': thunder/roll; thunder/roll names 'low rumble' in its own words (atlas and own words +3.2, a long take for a bed); next nearest: roll/drum, explosion/far, cat/purr part 3 'a horse neighing, twice, far': horse/neigh (2 times, under 2500 Hz); horse/neigh names 'horse neighing' in its own words (atlas and own words +6.6, a short take to repeat); next nearest: cow/moo, elephant/trumpet, bear/growl fit: z +3.56 for 'a stampede of horses' (the nearest design horse/neigh: z +2.61): a sketch: not clearly it yet; recorded: p_real 0.96 still off: layer 1 (thunder/roll) covers the rest: the fit rises to z +3.88 without it; lower its `gain` by about 6 dB or leave it out ``` "hoofbeats" is not a word of the reader, but horse/trot's own words have hooves: the part finds it as `earshot sounds --search hooves` does. The second ear hears Neigh, Horse and Clip-clop; the thunder under it is the part to turn down. With the rumble said "soft" (6 dB lower) and the hoofbeats without "on dirt", the same build is "sounds like it" at z +3.72, the second ear hearing Neigh, Horse and Clip-clop (the run is pasted in full in the README). **Without the listen extra.** The words ask for many small events on a surface, so the draft is a scatter; the read - docs/CREDITS_FIT.md (3142 bytes)
# Credits: the fitted sounds The bank's fitted sounds (`earshot/forge/bank/fit.json`, version `fit1`) are recipes measured from these recordings on [Freesound](https://freesound.org). Every one is released under [CC0 1.0](https://creativecommons.org/publicdomain/zero/1.0/) (public domain), which asks for no attribution; the recordists are credited here anyway, with thanks. A fit stores the structure of a sound (modes, partials, band envelopes), not its samples: no recording ships with earshot. | sound id | recording | recordist | Freesound | licence | |---|---|---|---|---| | `fit/bell/small_bell` | Small Bell #2 | steffcaffrey | [fs-452379](https://freesound.org/people/steffcaffrey/sounds/452379/) | CC0 1.0 | | `fit/click/floss_lid` | Plastic Clicks.flac | qubodup | [fs-167829](https://freesound.org/people/qubodup/sounds/167829/) | CC0 1.0 | | `fit/hit/bamboo_tok` | Bamboo hit | michorvath | [fs-386888](https://freesound.org/people/michorvath/sounds/386888/) | CC0 1.0 | | `fit/key.space/thock_space` | Keychron k10 space_bar | Sadiquecat | [fs-789630](https://freesound.org/people/Sadiquecat/sounds/789630/) | CC0 1.0 | | `fit/key/lubed` | Keyboard typing sounds: Unidentified Technics keyboard | zrrion | [fs-665075](https://freesound.org/people/zrrion/sounds/665075/) | CC0 1.0 | | `fit/key/medium` | mechanical key medium.wav | bigmonmulgrew | [fs-378084](https://freesound.org/people/bigmonmulgrew/sounds/378084/) | CC0 1.0 | | `fit/key/thock` | Keychron k10 A to + individual keys | Sadiquecat | [fs-789628](https://freesound.org/people/Sadiquecat/sounds/789628/) | CC0 1.0 | | `fit/land.light/finger_phone` | Finger Tapping Phone | jentlemen | [fs-704862](https://freesound.org/people/jentlemen/sounds/704862/) | CC0 1.0 | | `fit/land.light/finger_wood` | finger tap table counter wood various.wav | kyles | [fs-452621](https://freesound.org/people/kyles/sounds/452621/) | CC0 1.0 | | `fit/land.light/fingertip_book` | Light Footsteps On Book | IENBA | [fs-760337](https://freesound.org/people/IENBA/sounds/760337/) | CC0 1.0 | | `fit/pop/lip_pop` | Pop sound | deraj | [fs-202230](https://freesound.org/people/deraj/sounds/202230/) | CC0 1.0 | | `fit/pop/mouth_plop` | Mouth Plops.wav | CapsLok | [fs-181907](https://freesound.org/people/CapsLok/sounds/181907/) | CC0 1.0 | | `fit/snap/switch_flip` | Switch Flip #1 | IanStarGem | [fs-278205](https://freesound.org/people/IanStarGem/sounds/278205/) | CC0 1.0 | | `fit/tick/domino` | Domino pieces hit | Macif | [fs-329098](https://freesound.org/people/Macif/sounds/329098/) | CC0 1.0 | | `fit/whoosh.short/bamboo_swish` | Short Whoosh, 13x | Kinoton | [fs-427979](https://freesound.org/people/Kinoton/sounds/427979/) | CC0 1.0 | Chosen from 46 CC0 fits by measurement: fit grade high (CLAP to the recording >= 0.92 and mel distance within 2.5 dB of the model's own floor) and five takes that pass the take check at the shipped `vary` ([docs/SFX.md](SFX.md#fit-entries-from-public-domain-recordings)). Recordings whose title, author or page names a commercial sound library were left out, whatever their stated licence. Adding your own: same page, "Add your own fit".
- docs/DESIGN.md (9038 bytes)
# earshot: design notes earshot gives coding agents "ears": an agent cannot hear, so earshot turns sound into things an agent can reason about: calibrated text-audio match scores, the best moment inside a long recording, similarity to real reference recordings, real-vs-synthesized judgement, a second-by-second listening transcript of a soundtrack, an annotated picture of it (agents can look at images), a launch-video scorecard against professional references, and (only with the user's own key) an audio-LLM critique. Everything runs on CPU; no GPU is ever used. The repo also ships `skills/real-sound/`: the agent skill for building premium soundtracks for code-made films from real licensed recordings (sourcing + licence audit + design JSON + mixer + mastering + credits), which uses earshot to pick and verify sounds. ## Principles 1. **Honest numbers.** Every score says what it is (cosine, z vs background, probability) and how much to trust it. Never present CLAP cosine as a probability. Validation results live in `docs/VALIDATION.md` with the exact commands. 2. **Agent-readable first.** Every command prints a short plain-language `summary` first, then details; `--json` for the full dict. Timestamps as seconds (3 decimals) and m:ss.ss in text. Levels in dBFS / LUFS / dBTP. 3. **Deterministic and cached.** No random crops; fixed windows; embeddings cached on disk (EARSHOT_HOME/emb). 4. **Gentle on the machine.** CPU only, bf16 by default, `EARSHOT_THREADS` (default min(4, cores/2)). Batch work. This laptop (Ryzen 7 260, 8 cores / 16 threads) is shared with other jobs: when developing set `EARSHOT_THREADS=3`, keep any single job under ~10 minutes, run jobs in the foreground, one heavy job at a time per agent. 5. **No media in git.** Never commit audio/video (reference films, downloaded recordings, renders). Derived numbers (profiles, trained weights, eval tables) are fine. 6. **No synthesized deliverables.** earshot may synthesize test signals for tests/evaluation only. ## Layout and ownership (one owner per file during the build) | file | owner | purpose | |---|---|---| | `earshot/config.py`, `audio.py`, `features.py`, `video.py`, `report.py`, `cli.py`, `doctor.py`, `__init__.py`, `models/clap.py`, `models/ast.py` | core (lead) | shared base: read-only for builders. Need a change? Work around it in your module and report it. | | `earshot/data/vocab.json`, `earshot/vocab.py`, `describe.py`, `match.py`, `search.py`, `compare.py` | semantics | describe / match / rank / find / compare / ab | | `earshot/timeline.py`, `earshot/sheet.py` | timeline | listening transcript, sync analysis, annotated PNG | | `earshot/realness.py`, `earshot/data/realness*.json`, `eval/realness/*` | realness | real vs synthesized detector + its evaluation | | `earshot/profile.py`, `earshot/critique.py`, `earshot/data/launch_profile.json`, `docs/launch-video-sound.md` | launch | reference profile from pro launch films + scorecard | | `earshot/llm.py`, `earshot/mcp_server.py`, `skills/earshot/SKILL.md` | interfaces | optional audio-LLM critique, MCP server, agent skill for using earshot | | `skills/real-sound/**`, `docs/INTEGRATION.md` | real-sound | the soundtrack skill (moved from the Clawd project) + Cinetic integration notes | | `tests/test_<module>.py` | that module's owner | fast tests (synthetic fixtures, no network). Model tests marked `@pytest.mark.slow`. | | `README.md`, `docs/VALIDATION.md`, `docs/LIMITS.md` | lead (integration) | builders send their numbers in their final report | ## Core API (already built; use it) - `earshot.audio`: `load(path, sr=48000, mono=False, start=None, end=None)` -> float32 (n,2)|(n,), any ffmpeg-readable file incl. the audio of mp4; `probe(path)`; `windows(x, win, hop)`; `list_media(paths)`; `resample`; `to_mono`; `file_id(path)`; `SR = 48000`. - `earshot.features`: `measure(path_or_array, music=False, light=False)` -> dict (see module doc: lufs, true peak, noise floor, digital_silence_frac, attack_ms, decay_ms, centroid, bands_db, flatness, tonal_peak_ratio_db, harmonic_ratio, f0, onsets, tempo/beats/key); `loudness_curve(x, win, hop)`; `integrated_lufs`; `lra`; `onsets`. - `earshot.models.clap.get()` -> `Clap`: `embed_text(list)` (n,512) unit; `embed_audio(list_of_arrays, pad= 'repeatpad'|'zero', per_window=False)`; `embed_file(path, start, end, pad)` (cached); `embed_files(paths)`; `logit_scale` (~38.7). ~0.3-1.2 s per 10 s window on 4 threads (bf16). Every input costs one 10 s window (short sounds are padded), so batch and avoid needless tiny windows. - `earshot.models.ast.get()` -> `AST`: `probs(list_of_arrays, reduce='max'|'mean')` (n,527) sigmoid; `probs_file`; `top(p, k)`; `labels`; `prob_of(p, label)`. AudioSet ontology labels. Hears up to 8 kHz (16 kHz input). - `earshot.video`: `cuts(path, threshold=0.3)`, `frame(path, t, width)`, `frames`, `info`, `has_video`. - `earshot.report`: `emit(result, args)`, `fmt_t`, `to_json`. `earshot.cli.common(parser)` adds `--json --out`. ## Public functions (the contract other modules and the MCP server rely on) All return JSON-serialisable dicts with a `summary` string. Paths may be audio or video files. - `describe(path, start=None, end=None, top=8)` -> tags per vocab category with calibrated scores, AST top labels, key measurements, one-paragraph `summary`. - `match(path, query, alts=None, start=None, end=None)` -> `{'query', 'cosine', 'z', 'percentile', 'rank_in_vocab', 'p_vs_alts' (softmax over query+alts with logit_scale), 'verdict' ('strong'|'plausible'|'weak'|'no match'), ...}`. - `rank(paths, query, top=None)` -> files sorted by calibrated match. `find(path, query, win=None, hop=None, top=5, start=None, end=None, kind='auto')` -> best segments inside a long recording `[{'start','end','score','z','kind', 'head_db','tail_db','cut'}]`: sample trims, except one marked 'head cut' / 'tail cut'. - `compare(path, refs, k=5, start=None, end=None)` -> nearest references + typicality vs the reference set; `ab(a, b, query=None, refs=None, k=5, a_start=None, a_end=None, b_start=None, b_end=None)` -> which is closer to the query / refs and how they differ (feature deltas in words); the trims judge only part of a file. - `realness(path)` -> `{'p_real', 'verdict', 'evidence': [...]}` (+ per-segment for long files). - `timeline(path, video=None, cues=None, ...)` -> events (time, level, tags, AST labels), windows tags, loudness curve, cuts, sync stats (event-to-cut / event-to-cue offsets), `text` = the listening transcript. - `sheet(path, out_png, video=None, ...)` -> writes an annotated PNG an agent can open; returns its path + summary. - `critique(path, profile=None, video=None)` -> scorecard: each metric, the soundtrack's value, the reference range, status (ok/low/high), what to do. - `profile` CLI builds a profile JSON from a folder of reference videos/soundtracks. - `llm.critique(path, prompt=None, provider='gemini')` -> only when GEMINI_API_KEY / GOOGLE_API_KEY is set and the caller passes consent (`--yes-upload`); otherwise a clear message how to enable it. Never hardcode keys. CLI: each module implements `add_cli(sub)` registering its subcommand(s) (names in `earshot/cli.py COMMANDS`; `search` registers `rank` and `find`; `compare` registers `compare` and `ab`). Use `from .cli import common` for `--json/--out`. ## Evaluation data (not redistributed) Evaluation data: licensed recordings and third-party films, not redistributed. The evaluation scripts in `eval/` read their locations from environment variables or a gitignored `eval/local_paths.json` (see `eval/README.md`). What was used: - A library of real licensed recordings (Freesound / Mixkit) in 8 categories (ambience, foley, garden, keyboard, magic, motion, music, toy): 219 files used for tuning, plus 126 real recordings rejected for quality, used as the held-out set. Labels come from per-file manifests (category, title, need, notes). - Code-synthesized audio: a retired synthesized film score with its stems, and one-shots rendered by an open synth engine (kick, sub_boom, clap, hat, tick, tock, key_click, thock, ui_click, snap, blip, fm_bell, whoosh, riser, swell, pluck, bass, drone, keys ...). - A finished 60 s real-recordings film soundtrack with ground truth: stems (sfx, amb, music), every placement with time and sample in a mix report, picture cue events at 60 fps, and the same film with the old synthesized soundtrack. - 7 professional launch films as the quality bar (measured only, never copied), referred to as ref_1..ref_7 with neutral style descriptions in `eval/launch/refs.json`. ## Environment - Python 3.10+ with torch (CPU), transformers, librosa, scikit-learn, mcp. Run from the repo root (package importable as `earshot`), e.g. `.venv/bin/python -m earshot describe file.wav`. - Models are cached in `.cache/hf` inside the repo or `EARSHOT_HOME` (CLAP laion/larger_clap_general, AST MIT/ast-finetuned-audioset). - Scratch output: `out/<area>/` (gitignored). - ffmpeg / ffprobe on PATH. - docs/FIT.md (36847 bytes)
# earshot fit: translate a recording into code **Can an audio file be translated into code? Yes, within limits.** The method is *analysis by synthesis*. You pick a small synthesis model with readable parameters and fit those parameters until the model's render matches the recording. The fitted model is then written out as a Python module whose `render()` makes the sound. Examples of the parameters: the frequency, decay and level of each ringing mode, a noise band's loudness over time, a partial's pitch glide. The code does not store the recording's samples. It stores the structure of the sound: modes, partials, band envelopes. From that structure it can make new takes (fresh noise each seed), variations (knobs: size, damping, pitch, brightness, decay, width, ...), and morphs between two recordings. On 12 real references, the renders of the generated code sit close to the originals: - median CLAP cosine 0.945 (minimum 0.881); - spectrograms a median 0.75 dB further apart than two renders of the same model are from each other; - `earshot describe` gives the same top tag for both in 10 of 12. They are close but not identical: measured differences remain in onsets, tone balance and noise texture, listed below. In the mini blind test (below) the listener could not tell the recordings from the renders. ## How it works Four fitters, each analysis by synthesis, each producing a plain-JSON model: | fitter | for | the model | |---|---|---| | `fit/modal.py` | struck, ringing sounds (clicks, taps, keys, impacts) | per strike, damped sinusoids `[Hz, decay, amplitude, phase]` (ESPRIT on sub-bands + least squares); the contact as fast modes; a sub-20 Hz pulse; band noise envelopes; for a stereo recording the side over time per octave band (`side_t`, 0.4) | | `fit/sines.py` | tonal sounds (dings, chimes, pops with a pitch) | tracked partials with frequency and level breakpoints (McAulay-Quatieri / SMS; glides kept); strike atoms; 1/3-octave residual noise including the recording's own floor; for a stereo recording the side over time per octave band (`side`, 0.4) | | `fit/spectral.py` | noisy sounds (whooshes, swishes, cloth) | a time-varying 48-band noise gesture, stereo per band group, flutter / crackle texture statistics, tonal ridges; motion knobs (doppler, proximity, pan, motion) read from its trajectory (0.4) | | `fit/gesture.py` (0.4) | designed gestures (whooshes, swells, risers, camera moves), and short sounds where tones plus a little air beat partials plus residual noise | tones (the deterministic part of the sines candidate) + air: a detail noise model of what the tones leave in the recording, split in the magnitude domain (an STFT mask), so a take is fresh air around the same tones, not a re-jittered bank of noise partials | `fit/space.py` (0.4) adds a fitted diffuse tail to the chosen model of a stereo recording whose tail is decorrelated (a seeded room in the side: the mono sum and every mono measure stay as they were). `fit/auto.py` is the engine on top of them. 0. **Strip a bed.** A recording with a steady pre-roll 12-40 dB under the sound (a film's music under an effect) is stripped (`bed_of`, `strip_bed`) and the sound alone is fitted from its onset. The bed's spectrum is kept as `post['bed']`: `render()` puts a steady noise with it back under the sound, so the fit is scored against the recording as it is; `render(bed=False)` gives the sound alone. `earshot fit --keep-bed` fits the recording as it is. Analysis by synthesis decides whether it was a bed (0.4 round C2, `BED_CHECK`): after the choice (step 4) the winning candidate's kind is fitted on the recording as it is too, and the bed is dropped when that scores lower on the same seeds. A whoosh's own steady approach 13.6 dB under its peak had been stripped as music, and every candidate fitted on the rest fell (CLAP 0.88 -> 0.64); on the 12 dev clips with a bed the plain fit won on 8. 1. **Measure the sound.** `character()` measures attack, decay, crest, tonal share, partial persistence, glide (2 semitones over 15 ms count; before 0.4 the gate never fired on the reference clips' 2-6 semitone pops and dings) and flatness, and names a class (glide, ringing, struck, gesture, mixed). The class orders the candidates. 2. **Fit every candidate.** Under 1 s that is all seven: modal, sines, gesture, spectral, and three hybrids. Longer sounds get the class's four (a long gesture, mixed, glide or ringing sound gets the gesture model second). - In a **hybrid**, each layer but the last keeps only its deterministic part, and the next layer is fitted on what is left. Example: sines partials, then modal modes on the rest, then spectral noise on what remains. - So a pop becomes chirp + body + air, and a key press becomes body + air. - A sines layer of a stereo recording keeps its fitted side (0.4), so what it leaves for the next layers is taken out in stereo: the air models only the side the tones do not hold (a panned tone's side, counted twice before, came out about 3 dB too wide). 3. **Measure each candidate's post stage** from two renders (analysis by synthesis again): - a smooth third-octave EQ that moves the render's average balance onto the original's; - the level; - the original's attack envelope. Before the onset a render may not stand above it: band noise and window smear leak energy before a strike, which softens the attack. Over the first 6-25 ms after a sharp onset the render follows the original's contour within ±9 dB. This fixed a ding whose onset the sines fit had blunted from 60 to 4 dB/ms, and noise up to 12 dB above the original in the 4 ms before a key's strike. For a noise model (spectral, gesture) the clamp's correction is high-passed at 200 Hz and kept only when it lowers the score (its gain steps follow the noise's own flicker and put energy into empty low bands); - the gate (0.4): a cut-only gain curve where the renders stand over the original after the onset: the gaps of a run of pulses, a hard stop, a tail the model lets ring on (modes and partials decay exponentially and cannot stop; a gated pulse falls 30-60 dB in 5 ms). Kept only when it lowers the score and, with `--clap`, costs at most 0.005 of CLAP. Knobs that move time move it: a sines stretch and a gesture length about the first strike (the attack clamp too), a spectral length / speed about the start, and a modal spacing strike by strike (the cut after a strike moves with it and holds across a longer gap or ends where a shorter one does; the reopening in the last 2 ms before a strike moves with that strike). A morph warps each source's gate through its strike, onset or peak anchors before the two mix, so the cuts sit in the morph's gaps. 4. **Score each candidate's render against the original** and keep the lowest (`quality.score`, metrics below). `--clap` adds CLAP to the score; loading CLAP takes about 50 s. With seed 0 alone, the best three are scored on two more seeds and the choice is made on the mean (`CONFIRM`): on short noise-led sounds one seed's CLAP spread 0.84-0.92, and the seed-0 choice took the lucky draws. Then the CLAP margin rule (0.4 round C2, `CLAP_MARGIN`): a candidate whose CLAP is at least 0.02 higher on seed 0 and on the mean over the confirm seeds, whose score is at most 1.5 higher (both) and whose envelope r is at most 0.05 lower, is chosen instead. The model-free terms (mel, onset, envelope, excess) had decided near-ties against a clearly closer sound: on the first held-out check five of six regressions were the gesture model chosen with 0.015-0.06 less CLAP than another candidate. 5. **Finish** (0.4). A stereo recording with a decorrelated tail gives the chosen model `fit/space.py`'s side layer. Every render ends with a fade-in (2 ms, shorter when the onset comes earlier) and a gain down to -1 dBFS when it peaks over that (18 of 464 takes of the reference clips' fits had peaked over 0 dBFS). A model fitted before 0.4 (modal, sines or hybrid without the `coherent` flag: the 0.3 bank's fit entries; spectral without the `finish` flag every 0.4 spectral fit carries) renders as it did, without either (`auto.finished()`): the presets' takes stay byte-identical to 0.3.0, and a 0.3 spectral fit or its recipe module renders sample for sample. `fit/codegen.py` then writes the model as a **forge recipe module**. It contains: - `TARGET` / `ALTS`: from the refset category's recipe when the source is a refset file; - `REFSET` / `REFS`; - `SPACE`: the kind's knobs with search ranges around the identity; - `DEFAULTS`: the identity, which re-renders the fit; - `MODEL`: the fitted parameters as a readable literal, one mode, partial or keyframe per line; - `render(p, r)` and `render_seed(seed, **knobs)`. The module's render is **bitwise identical** to the engine's render of the model. This is tested, and true for all 12 validation fits. Variation comes in three forms: - **Knob perturbations:** the `SPACE` of the recipe, searched by the forge critic with `earshot fit --forge`. - **`vary`:** seeded jitter of modes and partials, so each take sounds like a new take of the same object. - **Morph:** two fits of the same kind. - Paired modes and partials interpolate: frequency, decay and level geometrically, phase circularly. Pairing is an optimal assignment on log frequency within one octave. - Unpaired ones fade with their side's weight. - Envelopes interpolate in dB on a time axis warped through the strikes or the loudness peak. - Hybrids morph layer by layer, and the post stages interpolate too. - A morph recipe has a `morph` knob (0.2-0.8 in `SPACE`), so a search explores sounds between two recordings, not copies of either. ## Commands ``` earshot fit click.wav -o made/click_fit.py # recipe + made/click_fit.wav + .png (side by side) + .json earshot fit click.wav -o made/click_fit.py --report # + render-vs-render floor + CLAP cosine -> click_fit.report.json earshot fit pop.wav --kind hybrid --layers sines,modal,spectral --render pop_fit.wav earshot fit whoosh.wav --clap # let CLAP help choose the fit (loads CLAP, ~50 s) earshot fit swell.wav --kind gesture # tones + air (0.4) earshot fit film_clip.wav --keep-bed # fit a clip with music under it as it is (0.4 strips the bed) earshot fit --morph a.wav b.wav --amount 0.5 -o made/ab_morph.py earshot fit --forge made/click_fit.py --budget 96 --dir made/click_variations # critic-searched variations python made/click_fit.py 3 take3.wav # the module renders on its own (seed 3) ``` `--forge` loads the recipe from its path and runs the forge search (pre-screen, robust re-renders, report.md, compare.png, audition.wav). Alternatively, copy the file into `earshot/forge/recipes/` and run `earshot forge <name>`. Picks of a recipe loaded from a path cannot be re-rendered by `earshot forge --check`, which needs an importable module name. ```python from earshot.forge import fit from earshot.forge.fit.quality import quality m = fit.fit('click.wav') # kind='auto' | 'modal' | 'sines' | 'spectral' | 'gesture' | 'hybrid' y = fit.render(m, seed=0, vary=0.3) # knobs: earshot.forge.fit.auto.knobs_of(m) q = quality('click.wav', fit.render(m)) # the metrics below; clap=True / describe=True add the model checks src = fit.to_recipe(m, name='click_fit', source='click.wav') mm = fit.morph(m_a, m_b, 0.5) ``` ## Quality metrics (`fit/quality.py`) Both sounds are mono-summed (except for the stereo measures). Both are cut at the original's onset, so a timing error still counts. Each is levelled to its own loudest 50 ms; the level difference is reported separately. | metric | what | |---|---| | `mel_db` | multi-resolution log-mel distance (64 bands, FFT 256 / 1024 / 4096), mean \|dB\| over cells within 60 dB of the top; 0 = the same spectrogram | | `env_corr` | correlation of the 5 ms dB envelopes | | `onset_err` | \|log2\| of the onset-sharpness ratio. Sharpness: 17 dB over the time the first onset takes from 20 to 3 dB under its local peak (0.125 ms frames, interpolated) | | `tone_db` | RMS third-octave balance difference (`earshot.forge.tone`) | | `excess_db` / `missing_db` | energy the resynthesis has where the recording is quiet, or the reverse. Mean dB beyond 6 dB over third-octave band x 10 ms cells, looking 100 dB deep. It catches hiss bands, noise floors and rings that outlive the original, where mel and envelope stop looking. It tracks CLAP's verdicts closely | | `side_db`, `width_db` (0.4) | side / mid energy of each sound over the original's active span, and the per-octave-band width error weighted by the original's band level | | `tail_corr`, `tail_corr_err` (0.4) | L/R correlation over the original's tail (from its loudest 10 ms + 30 ms to the end of its tail) of each sound, and their difference: a reverberant space decorrelates | | `clap_cos`, `describe` | the model checks (optional) | **floor**: `quality(render seed 11, render seed 12)`. A model with noise in it can never beat its own floor on `mel_db`. **score** = mel + 0.3 tone + 8 (1 - env r) + onset (capped at 2) + 1.5 excess + missing + 0.04 width (capped at 20 dB) + tail correlation error [+ 20 (1 - CLAP)]. The stereo terms (0.4) cost a mono re-make of a wide recording about what 0.06 of CLAP costs: they decide between candidates that sound alike (before 0.4 a sines render of a wide ding at side / mid -16 dB against -5 scored as well as a wide one). - With excess and missing, the model-free score's choices had a mean CLAP of 0.927 on the 12 refs; without them, 0.856 (the worst choice 0.52). Measured on the same refs, so in-sample. - The CLAP-including choice agreed with the model-free one on 11 of 12. ## Measured quality The **12 forge-split refs** (never bench) are 2 each of click, typing_key, pop, impact, whoosh_fast and notify: the first file of each category and the first from another source. For each ref: every candidate was fitted, the engine chose (with `--clap`), the recipe module was written and imported, and **its** render (seed 0) was measured. Results are in `out/fit/validation/` on the dev machine (`summary.md`, `all_metrics.json`, `<category>/<stem>/pair.png`, the recipe modules, the WAVs; local, because they are derived from licensed recordings). | category | ref | chosen | mel dB (floor) | env r | tone dB | onset err | excess dB | CLAP (floor) | |---|---|---|---|---|---|---|---|---| | click | fs-167829_1 | sines | 3.15 (2.35) | 0.997 | 1.14 | 0.27 | 0.16 | 0.959 (0.967) | | click | kit-ui_click_01 | sines + modal + spectral | 3.26 (2.69) | 0.993 | 1.38 | 0.03 | 0.06 | 0.948 (0.962) | | typing_key | fs-561697_1 | modal | 4.65 (2.49) | 0.975 | 1.93 | 0.60 | 1.06 | 0.881 (0.976) | | typing_key | kit-kb_thock_01 | modal | 4.25 (3.28) | 0.946 | 4.40 | 0.87 | 0.49 | 0.944 (0 - docs/FORGE_V2.md (24086 bytes)
# forge v2: review notes for the `forge-v2` branch > Released in 0.2.0 ([CHANGELOG.md](../CHANGELOG.md)). These notes were written on the branch before the merge, so > "not merged" and "nobody has listened" below describe that time. Paths under `out/` are local to the dev machine: > the made sounds, galleries and blind-test kits hold audio, and the reference recordings are licensed. What changed in `earshot forge` during the overnight iteration of 2026-10-16, how to try it, what the held-out measurements say, what is still weak, and what to check before merging. The branch is not merged; `main` is untouched. The round-by-round log with every number is [the forge v2 log](history/FORGE_V2_LOG.md). Per-category verdicts are in [eval/forge/results_v2r6.md](../eval/forge/results_v2r6.md) (Judge notes, round 6), [results_v2r5.md](../eval/forge/results_v2r5.md) (round 5), [results_v2r4.md](../eval/forge/results_v2r4.md) (round 4) and [results_v2r3.md](../eval/forge/results_v2r3.md) (round 3). **Status (round 6 benchmarked at 19:03; round 5 at 15:58):** - 34 categories, 183 sounds made in code, 0 artifact flags on the held-out benchmark. - Every judgement so far is a measurement or a model check: **nobody had listened to the sounds yet.** - The clean blind test is ready in `out/showcase/blind_v2/`: 20 trials, loudness-matched, randomised, real refs from the held-out side, rebuilt on the final finals. Its cleanliness report passes: both clips of a trial are trimmed the same way, play 0.00 LU apart at their loudest moment, and peak at most -1 dBTP. It is the deciding test, and its result belongs in this document and in the README before a merge. - The overnight showcase is `out/showcase/SHOWCASE.md` (local). ## 1. What was built | piece | where | what it does | |---|---|---| | reference sets | `earshot/forge/refsets.py`, `eval/forge/build_refsets.py` | 18 motion-design categories, 81 'forge' refs (the search may use them) and 71 'bench' refs (only the benchmark hears them), split by source family (author / library / file) so sister takes never cross the split; 0 leaks. `held_out()` keeps bench files and 8 bench-source kit WAVs out of every search. The licensed audio and the registry stay local. | | held-out benchmark | `eval/forge/bench.py`, `frozen_tone.py`, `results_*.json / .md` | per category, made sounds against the bench refs with checks the forge never optimises: 1/3-octave tone distance (a frozen copy of round 0's tone.py), envelope (attack, t40, length, curve), independent CLAP phrasings, AudioSet names, artifacts, variety between variants; next to the same checks for real recordings ("real x" = forge refs vs bench, "loo" = bench vs bench) and an "inside the real 80% limits" count. Run once per round; additions only. | | critic v2 | `earshot/forge/critic.py`, `polish.py`, `tone.py` | the v1 model terms (CLAP match, realness, typicality) plus model-free penalties: tonal balance, spectro-temporal envelope (a tail that dies too fast), artifacts (clicks, aliasing, DC, harsh resonance, comb ring, cut tails, clipping) and polish (attack, onset, tail smoothness); a designed mode for categories without real refs; study targets where refs are thin. `version=1` reproduces v1. | | search v2 | `earshot/forge/search.py`, `earshot/forge/__init__.py` | model-free pre-screen (many renders ranked by tone / envelope / polish, CLAP only hears the best), CMA-ES option, threaded renders, robust re-renders on new seeds with a shortlist, seed bank, `report.md` / `compare.png` / audition reel; `forge(families=)` searches each member of a character family in its own box and `palette()` loudness-matches the set. | | DSP toolkit | `earshot/forge/dsp.py`, `fx.py` | sources (air, Shepard risers, sub drops, bells, FM, sweeps, layering) and effects (hybrid FDN / noise-tail reverb, saturation, transient shaping, limiter, EQ match, Doppler, glitch, granular). | | pro study | `docs/motion-sfx-study.md`, `docs/motion-sfx-techniques.md`, `eval/forge/pro/` | 58 designed SFX events measured in 8 professional launch films (anonymous ids ref_1..ref_8; one SFX-only film supplies 39 of them), bed-subtracted balance, attack, decay shape, level over music; plus a cited research note on how pros build each kind of effect. Gives the 16 `pro_*` categories their targets and local refs. | | recipes and families | `earshot/forge/recipes/` (20 modules) | 34 categories (18 real-recording categories + 16 `pro_*` designed ones), each a family of 4-6 named characters (crisp / heavy / sleeve ..., length, brightness, sweep, weight, texture). 183 finals in `out/forge_v2/<category>/final/` (local). | | gallery | `earshot/gallery.py` (`earshot gallery`) | one static listening page per run: players, spectrogram thumbnails, loudness, critic and benchmark numbers, parameters, before / after rows (`--compare`), one self-contained file (`--embed-compressed`). Bench refs never reach a page. | | blind test + progress | `eval/forge/blind_v2.py` | builds the 20-trial blind test (made finals vs held-out real recordings, loudness-matched, answer sheet, scorer, sealed key) and the v1 -> v2 report with a listening reel, from whatever is in `final/` now. | | path scrub | `eval/forge/scrub_paths.py` | rewrites machine paths in benchmark results to `<refs>/...`, `<refs_pro>/...`, `<EARSHOT_HOME>/...` or repo-relative; `--check` for a pre-merge test. | Rounds: 1 = tooling (refsets, benchmark, critic v2, search v2, DSP); 2 = families for 34 categories (168 finals); 3 = fixes for the round-2 judge's faults in 29 categories (183 finals; round-2 finals kept in `final_r2/`), core fixes (polish false flags, critic thin-ref fallback, reverb IR cache), `forge(families=)`, the gallery. Round 4 re-delivered the finals of 14 categories: whoosh_fast, whoosh_big, swish, swipe, riser, impact, pro_impact, logo_sting, pro_logo_sting, tap, pro_tap, toggle, pro_pop and notify. Their round-3 finals are in `final_r3/`. The full benchmark (`results_v2r4.json`) kept all 14; the close calls are in its Judge notes. Round 5 re-delivered whoosh_fast, tap, logo_sting, pro_logo_sting, pro_pop and pro_notify (round-4 finals in `final_r4/`) and fixed the core fill bug (section 4). The full benchmark (`results_v2r5.json`) kept 4 of the 6 and put round 4 back for tap and pro_pop (their round-5 attempts are in `final_r5/`). Everything measured below is the final round-5 tree. ## 2. How to try it On the dev machine (the outputs in `out/` and the licensed refs are local; on a fresh clone the forge runs in designed mode or against your own refs, see `earshot/forge/refsets.py`): ```bash # listen: one self-contained page (MP3 previews of the WAVs, every number measured on the WAVs), opens anywhere out/showcase/gallery_embedded.html # v1 (main) above v2 (final) for the five categories v1 had, with both benchmark runs, one self-contained file out/showcase/v1_vs_v2_embedded.html # private pages: the nearest forge ref under each sound (plays licensed refs), and round 4 vs round 5 rows for the 6 # categories round 5 touched (links local files) out/showcase/gallery.html out/showcase/compare.html # the blind test: 20 trials, real (held-out) vs made, loudness-matched; write A / B per trial, then score out/showcase/blind_v2/answer_sheet.txt blind_test.wav (score_answers.py; do not open KEY_open_after.json first) # v1 -> v2 per check, per category, with a listening reel out/showcase/progress/progress.md v1_vs_v2.wav # rebuild the pages earshot gallery out/forge_v2 -o out/showcase/gallery_embedded.html --embed-compressed \ --results eval/forge/results_v2r5.json --title "earshot forge v2: sound gallery" earshot gallery out/forge_v2 -o out/showcase/gallery.html --refs forge --results eval/forge/results_v2r5.json earshot gallery --compare r4:out/forge_v2/whoosh_fast/final_r4 r5:out/forge_v2/whoosh_fast/final ... \ -o out/showcase/compare.html --results r4:eval/forge/results_v2r4.json r5:<the as-run round-5 results> # (one r4: / r5: pair per round-5 category; for tap and pro_pop r4 = final, r5 = final_r5) earshot gallery --compare "v1:demo/forge-test/*/final" v2:out/forge_v2/typing_key/final v2:out/forge_v2/click/final \ v2:out/forge_v2/pop/final v2:out/forge_v2/whoosh_fast/final v2:out/forge_v2/impact/final \ --alias keypress=typing_key whoosh=whoosh_fast --results v1:eval/forge/results_v1.json \ v2:eval/forge/results_v2r5.json --embed-compressed -o out/showcase/v1_vs_v2_embedded.html # re-render a delivered final from its parameters (same samples up to the palette's level match, max error ~1e-7); # the argument is the recipe MODULE: logo_sting -> sting, typing_key -> keypress, sub_drop -> subdrop (section 4) earshot forge --render click --params out/forge_v2/click/final/report.json --dir made/click_again # forge new sounds earshot forge --list # recipes, their targets, refsets earshot forge whoosh --refset whoosh_fast --budget 96 --variants 4 --dir made/whoosh python -c "from earshot.forge import forge; forge('click', refset='click', budget=48, robust=2, \ families={'soft': {'pitch': 3000.0, 'body': 0.2}, 'tink': {'pitch': 5000.0}}, out='made/click_palette')" # (a palette: one search per member in a narrow box around its preset, budget per member, then the members scored # together and loudness-matched; the recipes' own presets are in FAMILIES / PRESETS in each recipe module) # the held-out benchmark (loads CLAP + AudioSet; a few minutes at EARSHOT_THREADS=2; writes scrubbed paths) EARSHOT_THREADS=2 python eval/forge/bench.py --made out/forge_v2 --out eval/forge/results_v2rN.json python eval/forge/scrub_paths.py --check # tests (fast suite, no models; 5-9 min on this laptop) python -m pytest -q ``` ## 3. Before / after on the held-out benchmark v1 = the five recipes of `main` (3 sounds each, `eval/forge/results_v1.json`). v2 = the final round-5 delivery (`results_v2r5.json`); pop is the round-2 family, which the round-3 judge kept. Both use the same frozen benchmark and the same bench refs. The brackets show what real recordings score on the same check: the bench refs among themselves for variety; real x = the forge refs scored against the bench; loo = bench vs bench. | category | variety: CLAP cos between variants, lower = more varied | tail t40 / bench median (1 = same) | tone distance dB, lower = closer | curve dB | checks inside the real limits | |---|---|---|---|---|---| | typing_key | 0.965 -> **0.713** (0.673) | 1.67 -> **1.00** (1.29 / 1.00) | 8.20 -> **7.44** (8.88) | 14.3 -> **9.1** | 7 -> 4 of 7 (real 6) | | click | 0.886 -> **0.723** (0.576) | 0.56 -> **1.44** (1.33 / 0.86) | 7.60 -> 8.79 (11.33) | 8.9 -> 8.8 | 7 -> 7 of 7 (6) | | pop | 0.917 -> **0.735** (0.522) | 1.00 -> 0.82 (0.91 / 1.02) | 8.59 -> 11.42 (16.06) | 6.3 -> 11.0 | 7 -> 7 of 7 (6) | | whoosh_fast | 0.957 -> **0.831** (0.772) | 0.51 -> **0.88** (0.60 / 1.08) | 8.58 -> **6.21** (10.31) | 15.9 -> **10.1** | 7 -> 4 of 7 (6.5) | | impact | 0.931 -> **0.849** (forge refs 0.659) | 0.50 -> 0.58 (0.46 / -) | 6.70 -> **4.38** (6.19) | 24.9 -> 30.1 | 5 -> 6 of 6 (3) | How to read it: - **Clones fixed.** v1's variants were near copies (0.89-0.97). v2's sit at or near the real sets' spread: whoosh_fast (0.83) is inside its real rows (bench 0.77, forge refs 0.83). impact is still more alike than its forge refs. - **Tails fixed** where v1 died too fast: click 0.56 -> 1.44, whoosh_fast 0.51 -> 0.88. typing_key's long tail went 1.67 -> 1.00. impact's tail is still short against the one long bench hit; the forge refs score 0.46 there too. - **Tone.** Closer in 3 of 5: typing_key, whoosh_fast, impact. click and pop are further, but still closer than a different set of real recordings of the same kind (real x). - **The model checks fell, on purpose.** v1 sat *above* real recordings on CLAP typicality and phrasings: the Goodhart problem in the README. It was tuned until the models were pleased, partly against kit refs that are bench refs now, so v1's benchmark numbers are optimistic. impact most of all: its bench hit was a v1 forge ref. typing_key's and whoosh_fast's lower "inside" counts are CLAP / AudioSet misses. Breadth (no v1 counterpart): 29 new categories. - **Tone.** 21 categories have a bench tone number. In 18 of them (round 3: 17) the made median is at least as close to the held-out balance as the real forge refs. The exceptions are pro_logo_sting (15.6 vs 15.5 dB), pro_pop (22.9 vs 18.4) and shimmer (10.7 vs 9.7). - **Inside the real limits.** In 11 of 22 categories the made median lands inside on at least as many checks as a real recording. - **Artifact flags:** 0 of 183 (round 2: 3 of 168). - **Thin coverage.** Ten categories have no bench refs at all (downlifter, glitch, pro_glitch, pro_impact, pro_notify, pro_pop_in, pro_shimmer, pro_tap, pro_typing_run, pro_whoosh_big). They are measured on phrasings, AudioSet, artifacts and variety only. Three more (sub_drop, pro_sub_drop, pro_zip) have bench refs but no forge refs to compare against. Round 3 -> round 4, in the 14 categories round 4 changed (full table in `results_v2r4.md`): - **whoosh_fast:** variety 0.886 -> 0.768. AudioSet's top label is door-like on 6 of 6 -> 3 of 6. - **swish:** AudioSet names it 0 -> 0.8, and typ z goes -3.1 -> 0.6. - **swipe:** stereo corr 0.90 -> 0.64 (bench 0.68), and the tail no longer darkens. - **whoosh_big:** variety 0.854 -> 0.760. - **toggle:** tone 10.4 -> 7.8 dB. - **tap:** tone 8.2 -> 5.8 dB, t40 x 1.82 -> 1.00. - **notify:** tone 18.3 -> 15.6 dB. - **impact:** variety 0.905 -> 0.849, tone 5.3 -> 4.4 dB, and the onset tick is 6.5 dB darker. - **pro_logo_sting:** tone 24.4 -> 15.9 dB. - **logo_sting:** tone 16.4 -> 13.1 dB, but env oct is worse. - **riser:** tone 11.3 -> 9.3 dB, but env oct and curve are worse. - **pro_impact:** the model checks prefer round 3. It was kept on the spectrogram, because round 3 carried an accidental onset tick. Round 5 -> round 6 (18:00-19:40, after the showcase), full table and reasons in `results_v2r6.md`: - **pro_pop (round 6 kept):** six natural pops with a gliding pitch (`n6` in pop.py); variety 0.649 -> 0.617, tone 22.9 -> 19.5 dB (real 18.4); CLAP '8-bit' in the top 3 on 0 of 6 (was 3). Phrase z and margin fell. - **riser (round 6 kept):** a new render for 3 of 5 members (`r6=1`: rising band without a resonant peak, rising chord, accelerating gate, reverse swell); margin -0.30 -> +0.08, variety 0.801 -> 0.772, env oct 2.35 -> 2.05; tone 9.3 -> 12.8 dB (inside the real rows). - **tap (round 6 kept):** the better of round 4 / 5 per member; variety 0.782 -> 0.761, env oct 1.40 -> 1.22; margin and typicality slightly down. - **glitch (round 6 kept):** a chopped-repeat / bit-crush / dropout path (`roll0`); all three model checks up (no real glitch refs exist). - **pro_impact (round 4 kept):** round 6's boom made it recognisable (AudioSet 0.6 -> 1.0) but less varied (0.788 -> 0.820) and narrower (corr 0.35 -> - docs/history/FORGE_V2_LOG.md (36514 bytes)
# forge v2: overnight iteration log (historical; forge v2 shipped in 0.2.0) Goal (from the user, 2026-10-16 ~02:40): iterate ~12 h to make earshot much better, above all **forge**: sound effects that are genuinely great for motion-design launch videos (whooshes, swishes, risers, downlifters, impacts, sub drops, UI clicks / taps / toggles / hovers, pops, notification dings, shimmers, glitches, typing, logo stings), and better outputs. At the end (~15 h): a showcase of the progress and a new clean blind test. Work only on this branch; the user verifies before anything reaches `main`. ## How progress is measured (so the overnight work cannot fool itself) - A fixed **forge benchmark** (`eval/forge/`): per category, held-out real / pro reference recordings that the forge never optimises against, independent text phrasings, model-free tone and envelope distances, AudioSet labels, artifact checks and variant diversity. Run at the start (baseline = the v1 recipes) and after every round. - The forge's own critic may change; the benchmark does not (only additions, recorded here). - Human ears decide at the end: a clean, loudness-matched, randomised blind test. ## Rounds | round | when | what | result | |---|---|---|---| | 0 | 02:40 | branch, plan | | | 1 | 02:50-05:15 | **forge v2 tooling.** Refsets: 18 motion-design categories, 81 forge / 71 bench refs, split by source family, 0 leaks (`earshot/forge/refsets.py`, `eval/forge/build_refsets.py`). Fixed benchmark `eval/forge/bench.py` + baseline. Critic v2: model-free envelope (EnvRef), artifact detectors and polish (`polish.py`), designed mode; `version=1` reproduces v1. Search v2: model-free pre-screen (tone + envelope + polish, CLAP only on the best), CMA-ES option, threaded renders, robust shortlist, seed bank, report.md / compare.png / audition.wav. DSP v2: `dsp.py` sources (air, shepard, sub_drop, bell, fm, sweeps, stack) + `fx.py` (hybrid FDN / noise-tail reverb, saturation, transient, limiter, eq_match, doppler, glitch, granular). Integration: recipes get `REFSET` (CLI default refs = its forge split), held-out guard (`refsets.held_out`: bench files and the 8 bench-source kit WAVs never reach a search), v2 components in report history / ref rows / report.md, CLI `--mode`, `--tone` default = critic v2 weight (0 = report only), critic typicality needs >= 3 refs (2 refs gave z ~1e5), compare.png envelopes smoothed for long sounds. | Tests: 236 passed, 15 skipped (full fast suite, 197 s). Smoke (critic v2 + pre-screen + forge refsets, budget 24-32): whoosh 0.7 min, impact 2.4 min; all outputs written. Baseline (v1 finals vs bench, `eval/forge/results_v1.md`): variety (CLAP cos between variants) 0.89-0.97 vs real 0.50-0.83; tail t40 x click 0.56 / whoosh 0.51 (real 0.86-1.33 / 0.60-1.08); tone dB click 7.6, pop 8.6, key 8.2, whoosh 8.6, impact 6.7 (real forge-vs-bench 11.3 / 16.1 / 8.9 / 10.3 / 6.2); model checks saturated (typ z, phrasings above real everywhere). | | 2 | 05:20-08:55 | **forge v2 families.** Six maker areas (whoosh, sweep, impact, ui, tonal, digital) rewrote or added 22 recipes with CHARACTER parameters (length, brightness, sweep / pitch range, weight, texture) and FAMILIES of presets per category: 34 categories (18 real + 16 pro designed), 168 finals, 4-6 variants each, every member searched inside a narrow box around its preset, then one final run scoring the members together with robust re-renders; per-recipe model-free study checks (`measure` / `target_check` / `study_extra`) from docs/motion-sfx-study.md. Judge / integrator: benchmark additions (pro_* phrasings, `<cat>/final/` layout, audition.wav skipped), five core fixes (8-line reverb IR NaN, single-ref `score_refs` crash, flat_top false positive on subs, seed-bank cap 12 -> 48, `optimize` keeps DEFAULTS outside a narrow recipe SPACE), notify_04 start click re-rendered away, logo_sting audition rebuilt without the rejected variants. | Tests: 355 passed, 15 skipped (full fast suite, 416 s). Held-out bench `eval/forge/results_v2r2.md`: clones fixed (var cos v1 -> v2: click 0.886 -> 0.681, typing_key 0.965 -> 0.705, pop 0.917 -> 0.735, impact 0.931 -> 0.881, whoosh_fast 0.957 -> 0.856; real 0.48-0.86); tails fixed for click (t40 x 0.56 -> 1.22) and typing_key (1.67 -> 1.29 = real x), not for whoosh_fast (0.51 -> 0.49); 3 artifact flags in 168 sounds, all deliberate; critic passes 60 / 168. Best: whoosh_big (inside 7/7, real 5; AudioSet 'Whoosh' 5/5), typing_key, pro_pop_in. Worst: swipe (4-12 kHz 17 dB under the bench cloth), whoosh_fast + swish (tail 2x short, 8 dB boom, 15 dB hiss), logo_sting (rings 2.5x long). | | 3 | 08:55-11:30 | **forge v2 fixes + core r3.** Five maker areas fixed the round-2 judge's faults in 29 categories (183 finals, round-2 finals kept in `<category>/final_r2/`): whoosh engine (continuous hiss band, long concave tail, `low_lag`, shelves, fabric rustle) for whoosh_fast / swish / swipe / whoosh_big / pro_whoosh_big; logo_sting redefined as a composed reveal (lead-in -> strike -> note / dyad -> short tail); impact contact sheen; UI (click room fed only the transient, toggle first contact loudest, tap contact + two-stage body, pro_click bodies, pro_hover_tick spike + grains, pro_pop_in families, pop snap); tonal (shimmer / notify free rings, pro_notify head, pro_pop chirp controls, riser / pro_riser / pro_zip noise layers); digital (typing_key width + thock, pro_typing grain / blip members, pro_glitch burst drama). Core: polish false flags (aliasing on the fold grid, ring narrow / pitch guards, designed / gated gates), critic thin-ref fallback (`Critic(category=)`, STUDY_TARGETS), reverb IR cache + fixed rooms, holdout / score_refs caches, `palette()` and `forge(families=)`. New: `earshot gallery` (static listening page, compare mode). Judge: full bench, own spectrogram sheets, round-2 finals put back for pop and pro_zip (r3 worse on the bench; r3 kept in `final_r3/`). | Tests: 400 passed, 15 skipped (full fast suite, 316 s). Held-out bench `eval/forge/results_v2r3.md`: swipe tone 13.5 -> 6.1 dB (4-12 kHz -35.9 -> -20.7, bench -19.2); whoosh_fast t40 x 0.49 -> 0.90, tone 9.4 -> 5.8 dB; swish t40 x 0.68 -> 1.04; logo_sting t40 x 2.48 -> 1.03, inside 3.5 -> 6 of 6; shimmer t40 x 0.48 -> 0.97, curve 14.1 -> 4.1 dB; typing_key stereo corr 0.34 -> 0.96; pro_click tone 25.8 -> 15.4 dB; clones fixed in pro_typing_key / run (0.93 -> 0.81) and pro_pop_in (0.90 -> 0.75); 0 artifact flags in 183 (r2: 3). Costs: AudioSet still hears door / knock in whoosh_fast / swish, impact contact now 11 dB brighter than the bench, model checks fell in typing_key / notify. | | 4 | 11:30-14:00 | **forge v2 polish + finalize.** Three polish areas re-delivered 14 categories (round-3 finals in `<category>/final_r3/`). whoosh: the 'door' reading measured to the tail (a dark room ringing on the peak band), hiss that outlives the body, an accelerating 130 ms approach for whoosh_fast, side-signal width for swipe, new optional keys (`hiss_pre/tail/mfloor/width`, `low_width`, `room_damp`). impact: a quieter band-limited sheen, `plate` / `scatter` layers, a low strike under logo_sting, `zap` / `ctick` and five gestures for pro_logo_sting, `grain_jit` for pro_impact (its r3 0 dB onset tick came from forge's mid-range fill of missing SPACE keys). ui-tonal: toggle spring -> noisy rattle + steep high-pass (`hp_steep`), tap contact low-pass (`contact_lp_x`), pro_tap kick cue capped, notify `strike_max`, riser without drones, pro_pop `c_air` on one member; pro_notify tried twice, not delivered. Every new key defaults to the old behaviour. Also: the launch film re-scored with forge v2 (`earshot_launch_v2.mp4` in the local earshot-launch project). Then a clean blind test and a v1 -> v2 progress file (`eval/forge/blind_v2.py`). The gallery now has `--embed-compressed` and `--alias`. New: `docs/FORGE_V2.md` and `eval/forge/scrub_paths.py` (`bench.py` now writes scrubbed paths). The finalizer ran one full bench, kept r4 in all 14 categories and rebuilt the blind test, progress file, galleries and film. | Tests: 416 passed, 15 skipped (fast suite, final tree). Held-out bench `eval/forge/results_v2r4.md`, r3 -> r4: whoosh_fast variety 0.886 -> 0.768, darken -0.64 -> -0.05, AudioSet door-like top-1 6/6 -> 3/6. swish: AudioSet names 0 -> 0.8, typ z -3.1 -> 0.6. swipe: stereo corr 0.90 -> 0.64 (bench 0.68). toggle tone 10.4 -> 7.8 dB; tap tone 8.2 -> 5.8 dB, t40 x 1.82 -> 1.00. impact tone 5.3 -> 4.4 dB, variety 0.905 -> 0.849, onset tick 6.5 dB darker. pro_logo_sting tone 24.4 -> 15.9 dB; logo_sting 16.4 -> 13.1 dB (env oct worse); riser 11.3 -> 9.3 dB (env / curve worse). pro_impact's model checks fell; it was kept on the spectrogram. Breadth: tone at least as close as real forge refs in 18 of 21 categories (r3 17); 0 artifact flags in 183. Film: critique 16 -> 19 of 22 in range, realness 0.73 -> 0.85, cues within 1 frame 86 -> 95 %, -14.0 LUFS / TP -2.3. | | 5 | 14:05-16:30 | **forge v2 polish 2 + clean blind test + finalize.** polish-ui re-delivered whoosh_fast (the hiss band keeps sinking through the tail: new optional `tail_sweep` / `tail_tau` / `hiss_q` / `tail_gust` keys; per-member door fixes), tap (round-3 picks with per-member overrides) and logo_sting (smooth shimmer wash `shimmer_smooth`, round-3 leads, reverse_bloom `swell_trim`). polish-pro re-delivered pro_logo_sting (new sting mode 'gesture': five launch gestures from sines, filtered noise and a reverb fed above 250 Hz), pro_pop (natural chirp `c_nat`: no drive, no stepped gates) and pro_notify (the film ding made clean: no drive, no noise breath, a semitone ladder). Core fixed the round-4 fill bug (`search.fill_start`: start, recipe DEFAULTS, render-module DEFAULTS; mid-range only with a `MidRangeFill` warning), pinned every delivered member in the seed banks (`save_seeds(delivered=)`, `pin_delivered()`; 183 pins) and audited all 34 finals (hidden mid-range values only in pro_impact, kept). The blind test was rebuilt with symmetric trims and a cleanliness report that stops the build on a fail (`blind_v2.py --dry-run / --allow-fail`). Film: computed presence harmonics for phones (`v2lib.presence()`), a gentler logo limiter, the riser apex on its cue, a round-1 bug that skipped the sub drop / sting gates. The finalizer ran one full bench, kept r5 in 4 categories and put r4 back for tap and pro_pop (r5 in `final_r5/`), re-pinned the seed banks and rebuilt the blind test, progress file, galleries and film. | Tests: 433 passed, 15 skipped (fast suite, final tree, two halves 7.4 + 1.3 min). Held-out bench `eval/forge/results_v2r5.md`, r4 -> r5: pro_logo_sting variety 0.908 -> 0.642, tone 15.9 -> 15.6 dB, env oct 2.50 -> 2.15, margin -1.30 -> -0.68; whoosh_fast darken -0.05 -> -0.24 (bench -0.2), AudioSet names 0.5 -> 1.0 (variety 0.768 -> 0.831, inside the real rows); logo_sting decay roughness 0.46 -> 0.34 dB, pre-hit dip 14.6 -> 2.0 dB (reverse_bloom); pro_notify without the round-4 hiss, variety 0.822 -> 0.936. Not kept: tap (variety, curve, width worse) and pro_pop (variety 0.649 -> 0.780, phrase z and margin down; four members became steady beeps). Breadth unchanged: tone at least as close as real forge refs in 18 of 21, inside counts 11 of 22, 0 artifact flags in 183. Blind test: cleanliness PASS, 20 trials, 0.00 LU apart at the loudest moment, true peaks <= -1 dBTP, 118 s. Film: cues within 1 frame 95 -> 98 %, logo limiting 7.1 -> 3.3 dB, logo rise on a phone curve +1.1 -> +8.8 dB, critique 19 of 22, -14.0 LUFS / TP -2.2. | | 6 | 18:00-19:40 | **forge v2 round 6 (after the showcase).** Four areas. pop-notify: pro_pop rebuilt as natural pops (`n6` in pop.py: a gliding sine body, soft partials, exponential decay, optional puff / thump / pre-blip / room / double pop); pro_notify as five struck materials (`chime` in notify.py: film, glass, bowl, tine, wood, FM bell), not delivered by the area. tap-riser: a new riser render (`r6=1`: a rising noise band without a resonant peak, a rising root-fifth-octave chord, an accelerating gate, a reverse swell from a computed tail) for 3 of 5 members; tap = the better of round 4 / 5 per family. impact-glitch: pro_impact gets a designed boom, a delayed rumble and denser grains; glitch a new chopped-repeat / bit-crush / dropout path (`roll0`). code: one report schema (`earshot/forge/schema.py`: a `render` block per pick, `check_final`, `upgrade`, `earshot forge --check`), `forge.variant_recipe()`, pro_typing_run and pro_shimmer re-render again (`r2_path`). Every new key defaults to the old render. The finalizer ran one full bench, kept r6 for pro_pop, riser, tap and glitch, put r4 back for pro_impact (r6 in `final_r6/`), applied the schema to all 34 finals, re-pinned the seed banks and rebuilt the gallery and a round-5 vs round-6 page. | Tests: 485 passed, 15 skipped (fast suite, final tree, 11.4 min; the untracked fit tests left out). Held-out bench `eval/forge/results_v2r6.md`, r5 -> r6: pro_pop variety 0.649 -> 0.617, tone 22.93 -> 19.51 dB (real x 18.43), CLAP '8-bit' top-3 3/6 -> 0/6 (phrase z 3.29 -> 2.68, margin 1.76 -> 1.27); riser margin -0.30 -> +0.08 (jet-engine reading), variety 0.801 -> 0.772, env oct 2.35 -> 2.05 (tone 9.33 -> 12.75 dB, inside the real rows); tap variety 0.782 -> 0.761, env oct 1.40 -> 1.22, inside 4 -> 5 of 7 (margin 0.77 -> 0.55); glitch phrase z 2.03 -> 2.62, margin -0.13 -> 0.88, AudioSet 0 -> 0.17. Not kept: pro_impact (variety 0.788 -> 0.820, width 0.35 -> 0.67, though AudioSet 0.6 -> 1.0), pro_notify (phrase z 2.16 -> 1.45). Reproducibility: 183 of 183 picks re-render from report.json within 1.19e-7 (round 5: 32 of 34 categories). | ### Round 1 notes (integrator) - What works end to end: `earshot forge <recipe> [--refset CAT]` -> critic v2 inside search v2 (pre-screen reuses the critic's PolishRef) -> picks re-rendered on new seeds -> WAVs + report.md + compare.png + audition.wav; then `eval/forge/bench.py --made made_<tag>` against the held-out side. The smoke picks ran through the benchmark too (out/forge-r1/results_smoke.md; tiny budgets, not a progress claim): whoosh var cos 0.966, t40 x 0.47 (still clones, still short); impact var cos 0.72, t40 x 0.67, tone 9.1 dB (v1's 6.7 was optimistic: it used the bench impact). - Gaps the smoke runs show (compare.png): made whooshes reach -70 dB by ~270 ms where refs still sit at -50 dB at 300-400 ms, but the critic sees no problem because the whoosh_fast *forge* refs are themselves short (real x t40 x 0.6): optimising against them cannot fix the tail. Made impacts are 5-15 dB thin at 1-10 kHz and carry a narrow ~70-80 Hz partial; the impact refs' tails end in the trim fade (a curved drop at 4.5-6 s), which the envelope check reads as natural. - Known limits for round 2: impact has 2 forge refs (no typicality, LOO ref rows get no env / polish ranges, so real refs score 0 penalties by construction); downlifter / glitch / sub_drop have no forge refs (designed mode, the pre-screen ranks artifacts only); polish on 7 s sounds
- docs/INTEGRATION.md (15585 bytes)
# Integration: earshot inside a Cinetic film Cinetic (`~/.claude/skills/cinetic`) directs and renders launch films from code. Its Step 5 builds the soundtrack (`scripts/audio/score.py`) from a beat-locked timeline. Two routes give that soundtrack better sounds: an **earshot sound kit** (the first section: forge sounds rendered from earshot's bank, the route cinetic 1.1 takes by default when earshot is installed), and a **real-recordings soundtrack** from `skills/real-sound` (sections 1-4, which use Cinetic exactly as it was before 1.1). Either way earshot gives Cinetic's review loop ears (section 3). ## cinetic uses earshot The effects of a cinetic film come from an earshot kit; cinetic keeps the conductor (timing, typing plan, levels, ducks, arc, master, report, stems) and earshot supplies the voices. Rendering a kit is pure DSP: no models, no torch import, seconds per film once cached. ``` src/sync.ts --export-cues--> out/cues.json ---------------------------------+ audio/score.json "sfx": {"engine": "auto", "kit": "audio/kit.json"} ------+--> score.py --> master.py --> soundtrack.wav audio/kit.json --scripts/audio/kit.py--> earshot kit render --> audio/kit/*.wav + kit.lock.json --^ ``` 1. **The kit.** `audio/kit.json` starts from a preset (`earshot kit init --preset calm|crisp|minimal|launch`; calm is the default for text-led films, launch for films cut to music) and is edited per film: the lockup hit tuned to the film's root (`edits.pitch`), another member for a role, a fitted sound. Roles are cinetic's cue kinds and their variants (below); `null` roles are not sounded. 2. **The bridge.** cinetic's `scripts/audio/kit.py` finds earshot (importable in cinetic's Python, `sfx.python` in `score.json`, `EARSHOT_PYTHON`, or `earshot` on PATH), runs `earshot kit render audio/kit.json --out audio/kit` in one process (cached: an unchanged kit re-renders nothing) and keeps the takes in `audio/kit/`, so the film rebuilds on a machine without earshot. 3. **Placement.** score.py plays one take per event (a new take per event by hash; typing cycles through the takes), placed by the sync point the lock measured for the role's `align`: the take's onset on the cue frame, a whoosh's loudest 5 ms on its apex, a riser's end on the hit (or its climax, for a riser or swell aligned on its `peak` as the launch preset's are: their 0.4 members fall after the climax). `level_db` and the event weight set its level; a cue whose role is `null` is skipped with a report line. A role with the 0.4 mix keys (the launch preset) asks for more: its `offset_ms` moves the sync point off the frame (`kit.place`), its `bed_db` sets the take against the music under the cue (`kit.bed_level` + `kit.gain_db`, instead of `level_db`), its `min_gap_ms` spaces a run (`kit.space_run`), and the lock's `mix.stop_down` asks for a music dip before hits rather than a duck after them ([docs/SFX.md](SFX.md#mix-keys-04)). A renderer that ignores them still gets valid takes and `level_db`. 4. **Fallback.** earshot render -> the vendored `audio/kit/` takes -> cinetic's own synth voices with a loud warning. The build never fails only because earshot is missing. 5. **Listening.** `scripts/audio/listen.py` runs `earshot timeline --cues`, `sheet` and `critique` in one process and writes `out/qa/listen.json`. 6. **The lockup** is a stop-down and one clean element. `earshot kit check` warns when the hit role has two attacks or a build before the hit, and when any role's pitch climbs (the rising synth whip); score.py's stack guard warns on a second designed effect within 3 frames of the lockup or payoff. | cinetic cue (kind, variant) | kit role | align | |---|---|---| | tick / tick crisp | `tick` / `tick.crisp` | onset | | tock | `tock` | onset | | hit | `hit` | onset | | land / land light | `land` / `land.light` | onset | | pop | `pop` | onset | | whoosh (short / long move) | `whoosh.short` / `whoosh.long` | peak | | suck, riser, swell | `suck`, `riser`, `swell` (off in calm, crisp, minimal; launch sounds riser and swell, both aligned on the peak) | end | | drop | `drop` | onset | | key / key space / key return | `key` / `key.space` / `key.return` | onset | | click / click confirm | `click` / `click.confirm` | onset | | snap | `snap` | onset | | bell (motif notes, progress steps) | `bell` (one take per pitch) | onset | | a text fragment resolving | `text` | onset | What earshot guarantees the bridge: the role vocabulary, kit and lock schema 1 (docs/SFX.md#kits), the CLI flags above, deterministic takes, and a lock that names the bank version (a new bank version re-renders the kit, because it is part of every take's cache key). The bank, knobs, audit and presets are documented in [docs/SFX.md](SFX.md). ## 1. What Cinetic produces that the soundtrack needs | Cinetic output | content | used by real-sound / earshot as | |---|---|---| | `out/cues.json` (`npx tsx scripts/export-cues.ts`) | `{fps, bpm, total, acts, cue, events: [{f, kind, weight, pan, pitch?, apexFrac?, dur?, variant?, id?}]}`, sync frames computed from the picture code | **the cue file, unchanged**: `mix.py --cues out/cues.json` (mix.py's cue format is this format). Rules match `kind` (regex), `id` (regex), `variant`, a time window; `weight` drives `weight_db`; `pan` drives `pan: "cue"` | | `src/timeline.ts` (`FPS`, `BPM`, `TOTAL`, `ACT`, `CUE`) | the grid | `TOTAL / FPS` = the design's `duration`; `BPM` = `arrange.py --film-bpm`; `ACT` (exported as `acts`) = qa.py's per-act loudness | | `audio/score.json` | key, bpm, one chord per bar, sections (`intro / build / groove / drive / breakdown / resolve / hold`), drops + silences, `payoff`, signature tick/tock/motif, typing mode, mix, `master.lufs` | the musical intent: sections -> `arc.json` for `arrange.py`; `payoff` / drops -> `drop_film_bar`; key and chords -> which tuned recordings to source and whether a splice keeps the harmony; `master` -> the design's `master` | | `TREATMENT.md` / `BRIEF.md` | the brand's three adjectives, the personality row (`references/sound.md` §5.5a), the beat sheet with a sound column | the SOUND_BRIEF's concept and picture map | | `public/audio/soundtrack.wav` (written by `npm run audio`) | the master Cinetic's `render.sh --audio` muxes | **replaced by `mix.py`'s `out/audio/soundtrack.wav`**, passed to `render.sh --audio` (render.sh takes any WAV; keeping it out of `public/` keeps the premaster and stems out of the Remotion bundle) | | `out/stems/` | stems for `av-audit.py --stems` | `mix.py --stems out/stems` writes `sfx.wav`, `amb.wav`, `music.wav`: av-audit picks `sfx*.wav` as the effects and `music.wav` as the music bus | ### score.json sections -> an arrange.py arc One number per film bar (dB relative to the track's loudest sections): `intro` -14 (rising to -10), `build` -10 -> -4 across its bars, `groove` -6, `drive` -2..0, `breakdown` -10, `resolve` -8 -> -14 over its bars, `hold` / `tail` -20. `payoff` (usually the drop's bar) becomes `drop_film_bar`; a drop's `silence` becomes a deliberate hole in the music edit (the segment before the drop ends `silence` early; qa.py lists it as a note, not a defect). ### Synth voices -> real recordings | Cinetic kind | synthesized today | real-sound replacement (category / source / rule) | |---|---|---| | music stems: drums, bass, pad, arp, bells, reverb | generated per chord and section | ONE licensed track edited at bar lines (`arrange.py` draft, music supervisor); its own drop lands on `payoff` | | `tick` / `tock` (signature clock) | tuned wooden mallet | a real wood block / soft mechanical switch, two takes a fourth apart, resampled within +-2 st to the key | | `key` (typing) | dark modal tock per key, thinned to ~12/s | slices of one real keyboard recording (`slices` + `mode: cycle`); `variant: "space"/"return"` -> a deeper spacebar / enter take; per-word style -> a rule on `variant: "word"` only | | `click` | bright 2 kHz voice + release | a real mouse / trackpad press + release (two rules, `offset` ~0.085) | | `pop` | pitched blip | a real cork / mouth pop / plastic tick, `pitch_ramp` up across a run | | `snap` | click + body on the chord root | a real latch / Lego / magnet clack, layered with a low body | | `land` | wooden knock + sub | real foley thumps by weight (`weight_db`), light taps for `variant: "light"` | | `hit` | sub boom + clap + burst | a real drum / taiko / kick hit + a short top transient (two rules) | | `drop` | long sub boom | the music's own drop (edit), optionally a real low impact under it | | `whoosh` | noise band sweep | a real swish (bamboo, stick, cloth), `align: "peak"` | | `riser` / `swell` | noise + saw glide / reverse chord | a real cymbal roll or orchestral swell, `align: "end"` (or the track's own build) | | `suck` | reverse whoosh | a real air-suck recording, or nothing (mix.py does not reverse recordings) | | `bell` (`variant: "motif"`) | FM bell / the motif | a real celesta / bell / glass note in the key (one sample per note; the Clawd film built its motif this way) | Cinetic's sound rules stay valid (the sound map, levels, the drop on the hero reveal, the resolved logo, restraint); `skills/real-sound/references/sound-design.md` restates them for recordings. ## 2. The bridge, step by step (Cinetic untouched) Inside a Cinetic film project (`films/<name>/`), with `<rs>` = `skills/real-sound` of this repo: 1. Cinetic Steps 0-4 as usual. In `BRIEF.md` write the spec line with `audio: real recordings (real-sound)`. 2. Cues: `npx tsx scripts/export-cues.ts` -> `out/cues.json`. 3. Brief: copy `<rs>/templates/SOUND_BRIEF.md` to `audio/SOUND_BRIEF.md`; take the picture map from the treatment's beat sheet (its sound column) and `out/cues.json`; take the personality row and the arc from `audio/score.json` (write it even though score.py will not run: it is the musical intent). 4. Sourcing, licence audit, music edit, design fragments, critique and fix: the real-sound process (`<rs>/SKILL.md`, prompts in `<rs>/templates/prompts/`), with every path relative to the film project. 5. Render the soundtrack: ``` python -I <rs>/scripts/mix.py --root . --design audio/sounddesign.json --cues out/cues.json \ --out out/audio/soundtrack.wav --stems out/stems --report out/qa/mix_report.json --trace out/qa/adds.json ``` Set the design's `master.lufs` to `audio/score.json`'s `master.lufs` (-14 for launch films). Do not run `npm run audio` for this film (it writes the synthesized score). 6. Cinetic Step 6 with the real soundtrack: `bash scripts/render.sh Film out/preview.mp4 --preview --audio out/audio/soundtrack.wav` (and `--blur` for the master; never `--build-audio`, which re-runs score.py). Its `check-sync.py` gates lag and true peak on the decoded MP4 as before: `python3 scripts/check-sync.py out/film.mp4 out/audio/soundtrack.wav`. 7. Cinetic Step 7 (review loop) with ears (section 3). 8. Credits: `audit.py --report out/qa/mix_report.json` and `credits.py`; put `out/CREDITS_description.txt` into the delivery's README / video description. `real-sound`'s own `mux.mjs` is not needed in a Cinetic film: `render.sh` muxes. Use `mux.mjs` for films rendered outside Cinetic. ## 3. Where earshot slots into Cinetic's self-critique loop Cinetic's loop (§8): render -> measure (probe, forensics, av-audit) -> sheets -> critic lenses -> verify -> fix. earshot adds hearing to the measure and lens steps: | Cinetic step | add | what it gives the critics | |---|---|---| | Step 5 gate (after the soundtrack is written) | `python -I <rs>/scripts/qa.py --layers --stems out/stems` | clicks / cuts with the guilty sample, masked events, harsh 2-6 kHz peaks, chopped music splices, sync per event, partial coverage, loudness and LRA | | Step 7 measure | `python -m earshot timeline out/preview.mp4 --cues out/qa/cues_sounded.json` | a second-by-second listening transcript of the decoded film: events with tags, sections, loudness curve, beat grid, sound-to-cut and sound-to-cue offsets | | Step 7 measure | `python -m earshot sheet out/audio/soundtrack.wav -o out/qa/sound_sheet.png --video out/preview.mp4 --cues out/qa/cues_sounded.json` | one PNG (frames, sections, tagged events, spectrogram, loudness, cue sync) the director and sound lenses look at next to the contact sheets | | Step 7 measure | `python -m earshot critique out/audio/soundtrack.wav --video out/preview.mp4` | the scorecard against the profile of professional launch films (metric, value, reference range, what to do) | | av-audit | `python3 scripts/av-audit.py out/preview.mp4 --cues out/qa/cues_sounded.json --stems out/stems` | Cinetic's own onset/sync audit on the real soundtrack; `cues_sounded.json` (written by mix.py) lists only events that received a sound, so deliberate silences are not counted as misses | | sound-sync lens (`assets/critics/sound-sync.md`) | hand the lens `qa.json`, the earshot transcript, sheet and scorecard with `av.json` | the lens can name the exact rule / sample to change; with real recordings its fixes are design operations (`<rs>/templates/prompts/fixer.md`), not score.py parameters | | verifier (`assets/critics/verifier.md`) | refute a sound issue with earshot evidence (`earshot match` on the placed sample, the transcript at that time) | fewer false P1s from reading code alone | | a synthesized score already exists | `python -m earshot realness public/audio/soundtrack.wav` (score.py's output) | shows (per 4 s window) where the synthesized score reads as code-made: useful when the brief asks for recorded sound | ## 4. A minimal change list for a future Cinetic Each item is small and keeps the synthesized path as the default. 1. **One switch in `audio/score.json`:** `"engine": "synth" | "real"` and `"design": "audio/sounddesign.json"`. With `real`, `npm run audio` runs real-sound's `mix.py` with the same `--cues/--stems`, `--out` outside `public/` (render.sh's `--audio` default and `--build-audio` follow it) and `--json` mapped to `--report`; `score.py` stays for `synth`. 2. **`export-cues.ts --thin-typing`:** apply `plan_typing()`'s thinning (<= 12 keys/s, per-word above 25 chars/s) at export, marking skipped keys `variant: "silent"`, so a recordings design sounds exactly the keys score.py would. 3. **`av-audit.py`:** when `engine` is `real`, read `out/qa/cues_sounded.json` and skip the score.py typing replay. 4. **`references/sound.md`:** a §1b "Real recordings" pointing at real-sound, and a "real palette" column in the personality table (calm: soft wood, cloth; fast: tight drum hits, metal latches; bright: claps, cork pops, ticks; precise: clicks, glass taps; raw: switches, latches; warm: soft taps, paper; no instrument notes). 5. **`assets/critics/sound-sync.md`:** with `engine: real`, replace "Never propose stock or sampled sounds" by "propose recordings from the manifests or a new sourcing need; never synthesized sounds", and read `qa.json` and the earshot transcript / sco - docs/launch-video-sound.md (16962 bytes)
# Launch-film sound: the playbook for coding agents You cannot hear the film you are making. This page tells you what professional launch films do with sound, how to build that from real recordings, and how to check your result with earshot until the numbers say it is there. It is written for films meant to sound like those references; when synthesized sound is the point of a film, read the realness numbers as information, not as defects. How to read it: - **[measured]** = measured by earshot on the 7 professional launch films the author chose as the quality bar (modern SaaS / AI product launches and motion reels, web-delivered MP4s with 128 kbps AAC audio). Numbers come from `earshot/data/launch_profile.json`; the commands and the leave-one-out check are in `eval/launch/RESULTS.md`. Seven films are a small sample: treat the numbers as "what pros did here", not as laws. - **[practice]** = established professional practice for web video and trailer / motion-design sound. earshot did not measure these claims. The references (anonymised as in the profile): | id | style | |---|---| | ref_1 | AI video-search SaaS launch: white UI walkthrough, chat prompts and cursor, kinetic type, logo end card; voice-over (93 s) | | ref_2 | AI workspace explainer: white minimal kinetic type, app icons, chat UI, photographic logo reveal; voice-over (29 s) | | ref_3 | editorial kinetic collage: grainy paper, typewriter text, photo cut-outs, pixel icons, fast cuts; voice-over (20 s) | | ref_4 | fintech brand film: bold black / green kinetic typography, grids, numerals, flicker cuts, logo stings (32 s) | | ref_5 | AI image-generation launch: gradients, typed prompt, photo collage, sound design with hard silences (30 s) | | ref_6 | creator-commerce SaaS: blue UI walkthrough, notifications, cursor clicks, tagline end card; voice-over (49 s) | | ref_7 | gaming motion-design reel: logo stings, 3D explosions, very fast cuts, brickwall-loud music (42 s) | ## The short version 1. **Music leads.** Music runs under (nearly) the whole film: AudioSet hears it in 89-100 % of 5 s windows in 6 of 7 films [measured]. Pick the track first and cut the picture to it [practice]. 2. **Loud, steady body.** Median -14.8 LUFS integrated; the loudest 3 s sit only 1.1-3.5 LU above the integrated level (median 2.3 LU); loudness range 1.7-12.2 LU, median 5.5 [measured]. 3. **Start at once.** First sound within 0.04-0.48 s (median 0.13 s); 6 of 7 open within -1.8..+2.2 LU of the integrated level [measured]. No silent cold open. 4. **Land the ending.** The last 3 s of sound reach body level (median +0.2 LU vs integrated, range -2.2..+5.6); fades are short (0.08-2.54 s, median 0.27 s); dead air after the sound is short (median 0.04 s) [measured]. 5. **Dense rhythm, a few big accents.** 2.5-8.2 onsets per second (median 5.7) but only ~1.2-1.7 salient hits per second (6 of 7 films) [measured]: a busy groove with a handful of moments that jump out. 6. **Not a hit on every cut.** Sound on visual events is no better than chance in most references (details below) [measured]. Dense music covers the cuts; deliberate accents go on the moments that matter (reveal, logo, key UI action) [practice]. 7. **Real recordings, produced music.** Synthesized beeps and oscillator whooshes read as cheap next to films like these [practice]. Build from licensed recordings (`skills/real-sound/`) and check with `earshot realness`. 8. **Master for the web.** -14 LUFS integrated, true peak <= -1 dBTP on the master [practice]. 6 of 7 references clip after AAC decoding (true peak +0.1..+2.0 dBTP) [measured]: a common flaw, do not copy it. ## 1. Music leads the edit - [measured] Music presence (AudioSet 'Music' >= 0.3 per 5 s window; music under voice or SFX scores 0.4-0.7, a bare track ~0.9): 100 % in 5 films, 89 % in the reel (all but its last, 1.8 s window), 67 % in ref_5, whose 5-15 s stretch is sound design with hard silences. - [measured] Tempo 108-136 BPM, median 123 (librosa beat tracker; double / half tempo errors are possible). - [practice] Choose the track before animating; place section changes, the reveal and the logo on downbeats or bar lines; edit music on bar lines with short crossfades, never mid-phrase. If the film is a different length than the track, cut whole bars out of the middle, and keep the track's own ending. - [practice] One track, or one composed edit of a track. Hopping between unrelated cues breaks the energy. ## 2. Loudness and peaks for web delivery - [measured] Integrated loudness -22.2 .. -7.3 LUFS, median -14.8 (4 of 7 inside -16..-9). The quiet outlier (ref_5, -22.2) is the sound-design film with silences; the loud one (ref_7, -7.3, LRA 3.3) is a brickwalled reel. - [measured] True peak of the decoded AAC: -0.8 .. +2.0 dBTP; 6 of 7 above 0 dBTP, i.e. they clip on playback. - [practice] YouTube normalises playback to about -14 LUFS and only turns loud uploads down (a quiet master stays quiet); Apple's players aim at about -16; X, LinkedIn and website autoplay players do not normalise at all. So: about -14 LUFS integrated (up to about -10 for a punchy social cut), true peak <= -1 dBTP on the master (AAC / MP3 encoding adds up to ~1 dB of overshoot), limiter last in the chain. - earshot: `lufs_i` (web window -16..-9 LUFS), `true_peak` (<= -1 dBTP for a lossless master, <= 0 dBTP for an already decoded MP4 / MP3), `lra`, `crest_lu`. ## 3. The arc: open strong, hold the body, land the ending - [measured] Opening level (first 10 % of the film vs integrated): -1.8 .. +2.2 LU in 6 films; ref_4 builds from -17.5 LU over ~4 s. Where the loudest 3 s sit varies (0.03-0.88 of the duration); 5 of 7 put it after 60 %. - [measured] Body: loudness range median 5.5 LU, loudest 3 s median +2.3 LU over integrated. The references stay loud; they do not make you wait for a climax. - [measured] The median loudness arc (LU vs integrated at 0 %, 10 % .. 100 % of the film) is flat: -1.3, -0.8, +0.3, -0.3, -0.2, +0.2, 0.0, -0.4, +0.9, -0.3, then -7.4 at the very end (ring-out / fade); between 10 % and 90 % the p10-p90 band is -5.8..+2.0 LU. A story-film arc (quiet start, climax at 70-80 %) is the opposite: the Clawd film's real soundtrack starts at -9.8 LU and peaks at +3.9 LU. `earshot critique` prints your arc next to the median. - [measured] Silent holes: none longer than 0.04 s except ref_5's deliberate silences (1.66 s). - [practice] Shape the energy with arrangement (layers in / out, filter sweeps, a stop-down before the reveal) rather than with big level changes. - earshot: `intro_lu`, `end_lu`, `peak_pos`, `first_sound_s`, `max_gap_s`. ## 4. Picture and sound: what the references actually sync earshot detects visual events (hard cuts and big picture changes: a frame-difference spike >= 4x its surroundings, or a mean change >= 15 % of the grey scale) and compares them with audio onsets and salient hits. "Chance" = the same events shifted off the picture by fixed offsets, so it is what random edit points would score with that music. | [measured] share of visual events with ... | median of 7 | chance median | films >= 10 points above their chance | |---|---|---|---| | an onset within +-100 ms | 81 % | 86 % | ref_3 88 vs 68, ref_7 60 vs 44 | | a salient hit within +-100 ms | 29 % | 27 % | ref_1 46 vs 30, ref_3 53 vs 35 | | an onset within +-1 frame | 44 % | 44 % | ref_3 47 vs 36, ref_5 38 vs 24 | | a tracked beat within +-70 ms | 22 % | 28 % | ref_4 40 vs 28, ref_5 38 vs 25, ref_6 52 vs 31 | For comparison, the code-made Clawd film (its sound placed on picture cues by a script) scores 38 % vs 10 % chance within +-1 frame and 69 % vs 25 % on the beat grid: earshot does see tight sync when it is there. What that means: in these films the music is so dense (median 5.7 onsets/s) that almost every cut has *some* sound under it, and they do **not** put a measurable hit on every cut. Some lock part of the edit to the beat. Caveat: earshot measures the final mix; quiet SFX under loud music can be present without being separable. - [measured] 4 of 7 use stop-downs: the sound drops >= 10 dB for 0.15-1.5 s and comes back on a hit (1.2-18.3 per minute). - [measured] Visual events: 0.3-1.6 per second (median 0.63). - [practice] **Whoosh into transitions**: the whoosh peaks on the cut (or on the fastest frame of the move) and starts 0.2-0.6 s before it; match its length to the move. - [practice] **Riser -> stop-down -> impact** for the big reveal: a 1-4 s riser, cut everything for 0.1-0.5 s, then an impact (with a sub drop) exactly on the reveal frame. Use it once or twice per film, not on every scene. - [practice] **Accents with priority**: the reveal, the logo, the key UI action and the section changes get a designed sound; small motion rides on the music. - [practice] For a sparse soundtrack (no dense music) every cut needs sound: `earshot critique` scores the share of visual events with an onset (a new attack) within +-100 ms (`cuts_with_sound`, the references' definition) and lists the events with no sound at all - no onset, no whoosh / riser peak, no level peak - by the same matcher as `earshot timeline` (an action when `cuts_with_sound` fails, a tip otherwise). Soft build-ups can still be missed: look at the sheet before adding a sound. Align samples on their attack, to the frame. - earshot: `cuts_with_sound` (scored), `cut_hit_frac`, `cut_frame_sync`, `cuts_on_beat`, `stopdowns_min` (context). ## 5. UI foley (clicks, typing, notifications) - [practice] One click per on-screen click, on the frame the cursor presses (not when the UI reacts). Typing: one key sound per typed character, from a multi-take recording so no two consecutive keys are the same sample; slightly irregular timing. Notifications: short, soft, tonal; avoid alarm-like beeps. - [practice] Keep UI foley short, bright (2-6 kHz) and low: it should read as detail under the music, ~10-15 dB below the music peaks, panned toward where it happens on screen. - earshot: `earshot find typing.wav "a single soft key press"` to cut takes; `earshot match` to check a sample is what its name says; the critique's `onset_rate` tells you if the track is too sparse. ## 6. Logo sting and endings - [measured] The final moment lands at body level (median +0.2 LU); fade / ring-out median 0.27 s, longest 2.54 s; the strongest hit of the last 4 s rings out 2.0-3.6 s in 5 films; ref_7 ends without a final hit. - [practice] End on a designed sting: a hit plus a tonal tail (2-4 s), with the music resolving into it or stopping for it, finishing within ~0.5 s of the last frame. Avoid long fade-outs and dead air. - earshot: `final_lu`, `fade_s`, `end_silence_s` (scored), `tail_s` (context). ## 7. Frequency space - [measured] Energy share per band (median, dB of the total): sub 20-60 Hz -6.6, low 60-250 Hz -4.2, low-mid 250 Hz-1 kHz -5.3, mid 1-4 kHz -12.4, presence 4-8 kHz -17.8, air 8-16 kHz -23.6; brightness (median magnitude-weighted spectral centroid) 1169-3633 Hz, median 1966 Hz. Bass-led mixes, as expected for music-led films. (Above 16 kHz is not compared: AAC cuts it.) - [measured] Stereo: side 14.5-5.0 dB below mid (median -8.5 dB), L/R correlation 0.52-0.93. - [practice] Give every layer its own place: high-pass SFX and ambience (unless they are impacts), keep one element in charge of the sub at a time, dip the music 2-5 kHz and duck it 3-6 dB under voice, keep UI sounds out of the music's lead range. Check the mono fold-down; phones are mono. - earshot: `band_*`, `side_to_mid_db` (scored minor; a mono mix, identical left and right, counts as -40 dB and is flagged), `brightness_hz`, `correlation` (context). ## 8. Density and restraint - [measured] 2.5-8.2 onsets per second; salient hits ~1.2-1.7 per second in 6 films (the brickwalled reel 0.1). - [practice] More sounds is not better. Sound the moments that carry meaning, let the music carry the rest, leave room (a stop-down, a breath before the logo). A cluttered SFX layer on top of busy music turns into noise. - earshot: `onset_rate`, `hit_rate` (scored both ways: too sparse and too busy; salient hits need at least 0.05 /s, half the sparsest reference). ## 9. Voice-over - [measured] 4 of 7 have a voice-over (AudioSet hears speech in 83-100 % of windows); 3 are music-only. - [practice] If you use VO: duck the music 3-6 dB under it (sidechain or automation), keep SFX out of 1-4 kHz while it speaks, and never put a big hit on top of a key word. ## 10. Real recordings, not synthesis - [practice] Code-synthesized "random" sounds (oscillator beeps, filtered-noise whooshes) are the fastest way to sound amateur next to films like these. Use licensed real recordings and produced music, with a licence audit and credits: `skills/real-sound/`. - [measured] The Clawd film scores p_real 0.94 with its real-recordings soundtrack and 0.33 with the retired synthesized one (eval/realness/RESULTS.md, application files; eval/launch/RESULTS.md); that line is what separates them in the critique: the real one reads "close" (90 %), the synthesized one "needs work" (80 %, 1 critical). The structural metrics alone rate both close. Not an independent test: the realness model was trained on related material (eval/launch/RESULTS.md). - earshot: `earshot realness mix.wav` gives p_real, a verdict and the 4 s windows that sound synthesized; `earshot critique` uses the same thresholds: the film's mean p_real against the file thresholds (ok at "real or pro-produced", critical below 0.5, where synthesized is the more likely reading, minor in between; a minor miss with no window leaning synthesized is only a tip), and its listed 4 s windows against the window threshold, as `earshot realness` lists them. A finished mix is harder to judge than its sources: run `earshot realness` on each stem. ## Checklist (run it, read it, fix, repeat) ``` earshot critique film.mp4 # scorecard + concrete fixes with timestamps (start here) earshot critique film.mp4 --fast # quick pass, no AudioSet / realness: a PARTIAL verdict earshot critique mix.wav --video film.mp4 # a separate soundtrack checked against its picture earshot timeline film.mp4 # listening transcript: what sounds when, next to the cuts earshot sheet film.mp4 -o out/sheet.png # annotated picture of the soundtrack (open the PNG) earshot realness mix.wav # which 4 s windows sound code-synthesized earshot profile my_refs/ -o my_refs.json # measure your own reference films ... earshot critique film.mp4 --profile my_refs.json # ... and score against them instead of the bundled 7 ``` 1. Pick the music first; cut the picture to it. Check `music_frac` (whole film) and `tempo`. 2. Lay the accents: reveal (riser -> stop-down -> impact), logo sting, key UI actions, section changes. Check `hit_rate`, `stopdowns_min` and the
- docs/LIMITS.md (24482 bytes)
# What earshot can and cannot judge, and cannot make earshot gives an agent measured evidence about sound, not taste. Read this before trusting a verdict. What `make` cannot do and where it is weak is [below](#making-sounds-make), and what `build` cannot do [at the end](#building-sounds-build). ## Trustworthy - **Measurements**: loudness (LUFS, true peak, LRA), timing (onsets, offsets to cuts and cue frames, to the millisecond), levels, spectrum, envelope, clipping, silence, tempo of steady music. These are meters, not opinions. - **"Is this the kind of sound I asked for?"** on single, exposed sounds (a key press, a whoosh, rain, a glass ting): a "strong" match is very reliable on held-out recordings; "plausible" and "weak" are hints worth a second check. - **Picking among candidates** (`rank`) and **finding the clean moment** (`find`) in real recordings. - **Obvious code-synthesized sources** (noise risers, simple FM bells, steady test tones): flagged with ~92% precision when the verdict is firm (6.7% of real clips get called synthesized, 5.5% of synthesized clips real). Bare beeps are less reliable than that list suggests: with the beep family held out, beeps were among the most-missed types (accuracy 0.71). - **Whether sounds land on the picture**: offsets of hard hits to cuts / cue frames (median 0 ms on Clawd, 96% within a frame). ## Hints only - **Tags of events inside a busy mix** (what each hit "is"): right about half the time for exposed events, a quarter for events under the music. Times and levels are right; the label is a guess. - **Music genre and mood**: often wrong (an upbeat track's top mood was a dark one 18% of the time); describe keeps them apart as unvalidated hints. Instruments, rain, birds and voice are usually right. - **"Uncertain" from realness** on designed library sounds ("magic" chimes/celesta, "motion" whooshes) and on real electronic music: they sit between real and synthesized. Read it as "sounds designed", not "fake". - **The launch scorecard ranges** come from 7 films the author picked. They describe that style (modern SaaS / AI launch films, kinetic type, UI demos), not every good film. A cinematic short or a quiet piano piece will break rules that do not apply to it. Build your own profile from films you admire (`earshot profile`). - **The "cuts without a hit" list** (timeline, sheet, critique tips): soft build-ups (whooshes, risers, swells) can still be missed - on Clawd both cues it named were sounded whooshes. Look at the sheet before adding a sound. - **critique's "onset on visual events" share** counts only new attacks within +-100 ms (the definition the reference ranges were measured with), so a whoosh swelling through a cut does not count; its fixes and tips name only the cuts with no sound at all (timeline's matcher). critique's stop-downs (short drop-outs before a hit, per minute) and timeline's gaps (silences of any kind) are different counts. - **realness verdicts depend on length**: a sound up to 6 s is judged with the clip thresholds (lo 0.17), a longer file by the mean of its 4 s windows with the weakly calibrated file thresholds (lo 0.40), so a lower p_real can get the milder verdict. Judge the trim you will actually use (`--start / --end`), not a multi-take file. - **AudioSet labels on one-shots under ~0.5 s**: often 'unsure' or a near class (Zipper for a swish, Finger snapping for a click). Treat those as neutral; only an outright different class (Speech, Music, Engine) is a red flag. ## Cannot judge - **Taste and emotion**: whether a sound is beautiful, whether the music fits the brand, whether a moment feels satisfying. earshot can say "a strong match for a deep thocky key press, 3 ms attack, lands 4 ms after the cut"; it cannot say the film feels premium. - **A code-made layer hidden under a louder real mix**: usually missed. Judge source files and stems, not only the final mix. - **Provenance**: realness hears synthesis, not licences. A professionally made, licensed synthetic UI sound can read "likely code-synthesized"; code-made noise beds that imitate nature (rain, wind) or telephone tones can read real. - **Anything above 14 kHz from the models** (CLAP's front end stops there; the AudioSet tagger at 8 kHz). Use `measure` (bandwidth, bands) for air, hiss and codec cut-offs. - **Speech content**: no transcription; voice is detected, words are not. - **Licences**: earshot never decides whether a file may be used. The real-sound skill's `audit.py` checks manifests; the licence itself must be read on the item's page. ## Known engineering limits - Cold start: every CLI call is a fresh process that loads the models (~20-40 s on a busy laptop), even for a cached file; the MCP server or one Python script (`from earshot import api`) loads them once. `doctor` without `--load` loads nothing heavy. - bf16 is used only on CPUs with native bf16 (AVX512-BF16 / AMX); elsewhere earshot runs fp32 (bf16 emulation was measured 16x slower). The bundled calibration was measured with bf16 embeddings (fp32 agrees to cosine >= 0.9993 on 12 real clips, `eval/semantics/precision.json`). - Caches are keyed on path, size, modification time and 16 sampled 4 KB blocks of the file: a re-render that differs only between those blocks and keeps the old size and timestamp would still read stale. Use `timeline --fresh` or touch the file when in doubt. - The models were evaluated on one sound library (Freesound / Mixkit picks for one film), 7 launch films and three synthesis code bases. Other domains (orchestral recording sessions, field recordings in other climates, other synth engines) are untested. - The optional Gemini critique has not been validated against real answers (it needs the user's key and consent to upload). - Cut detection marks big visual changes (a blinking cursor counts); slow crossfades are missed. ## Making sounds (`make`) **What was measured and what was judged by ear.** Measured, by code: every take's audit (clicks, cut tails, clipping, DC), its loudness and length, how close a learned take stays to its recording, and how well requests are read ([VALIDATION.md](VALIDATION.md#8-made-sounds-10)). Judged by ear, by one listener (the maintainer) on pages that were not blind: which kinds of sound are good enough ([VALIDATION.md](VALIDATION.md#listening-by-ear)). On 24 recordings each learned take was judged as good as its source, but the store as a whole has not been judged. The sounds built last (the `ui` set as it is now, the film and motion hits, the drums from recorded strokes, the figures on real instruments, the newer learned things and beds, and the cookbook's recipes) were measured and checked by the audit, and no one has judged them by ear yet. earshot's own models did not predict the judgements by ear and are not a measure of how good a made sound is; a `heard as` line says what a model hears, nothing more. **What it cannot do.** - Make a sound no design covers from a free description. `make` chooses one design and shapes it with the controls, or renders a recipe that layers designs. A request for a thing the catalogue lacks still gets a file: the nearest design, with a line that says `earshot makes no X; Y is only the nearest sound it has`, three starting points of other families, and the `earshot build` line that builds it (see [Building sounds](#building-sounds-build)). A cookbook recipe answers on its own for 59 things; the other 40 of the 99 are sketches that are starting points, and a recipe is judged by a model and the audit, not by ear. - Realistic sounds for things nobody recorded. A learned sound exists only where someone recorded the thing and put the recording in the public domain; the store has 309 things. For other real things the catalogue has designs invented from physics (`action`, `object`), which sound clearly less real. - Pan a catalogue sound. A request to `make` cannot place or move a sound in the stereo field: "from left to right" is said not followed. A layer of a recipe can be set to a side or moved across (`pan` [from, to]), and a part of a build that says "from left to right" gets that move. - One sound ringing through the body of another ("rain on a tin can"). It was tried and came no nearer the real thing; where the catalogue has the real surface (`rain/wood`, `rain/tin_roof`, `step/floorboard`), that design is the answer. - New sounds from a class of recordings. Sampling new members from a model of several recordings was tried and judged poor by ear; it was dropped. A learned design plays its own recordings and new takes of them. - Music. earshot is a sound-effects tool: three short loops (`bed/warm`, `bed/playful`, `bed/8bit`), notes, chords of a pad, short motifs and logos. No melodies, songs or scores, and no music generation. - Speech, singing and the melodies of instruments. Animals, people without words and vehicles exist as learned recordings: a dog barking (a big and a small one), a cat, a robin, a crow, a rooster, an owl, a horse neighing and trotting, a cow, a wolf; applause, a crowd cheering, laughter, a gasp, a cough, a kiss, a heartbeat, a baby crying; a car horn, a siren passing, an engine starting, a train's horn and a train passing, a helicopter, a bicycle bell; a woman's scream, a sneeze, a yawn, a sigh, snoring, a burp, a bite into an apple; a sheep, a goat, a chicken, a cat purring, a duck, a pig, a frog, a fly; cutlery on a plate, a broom, a running tap, a spray can, velcro, a glass and a plate breaking, a cash register; tyres screeching, a motorcycle passing, a gun reloaded; in the kitchen one knife chop on a board, a pot boiling, a pot lid set down, a gas stove lit, a spoon stirring in a mug, a plate set on a table, a toaster popping, a blender, an egg cracked, a whisk beating in a bowl; a crowd booing, a cat hissing, a lion roaring, an elephant trumpeting, a bee, a rocket launch, a record scratch, a squeaky toy, an elevator's arrival ding; steps in mud, through puddles and in dry leaves; machines started, run and stopped (a chainsaw, a lawn mower, a tractor, an angle grinder, a jackhammer, a paper shredder, a coffee machine, an electric kettle, a microwave, a hard drive, a fax), a kettle whistling, a truck reversing, a ship's horn, a steam engine, a metro arriving, wipers, a turn signal, a garage door, a motorboat; a monkey, a parrot, a donkey, a bear, geese, a puppy, a mouse, a rattlesnake, a mosquito; knuckles, teeth chattering, a hiccup, a whistle, panting, hands rubbed, a puff of breath, sitting down on a sofa; a skateboard, ping pong, pinball, darts, a crossbow, ice skates; a screwdriver, a ratchet, a trap, a binder clip, a party popper, a curtain, an office chair, a bed, a window, a swing, an envelope, a crisp packet, a drain, a garden hose, a sprinkler, a bicycle freewheeling, a tree falling; beds of hail on a roof and on a car, a dishwasher, a washing machine, a fridge, a shower, a jungle at night, a factory workshop and a gale. Instruments play single notes, chords of a pad and short figures, no melody. To a request for speech, a voice that says or sings words, a shout or a yell, sobbing, a violin, a cello, a viola, a saxophone, a flute, a clarinet, an oboe, bagpipes, a trumpet, an electric guitar, a guitar or drum solo, an air horn or a ringtone, `make` answers "earshot makes no ...". Crying is a baby's: asked of another person it is not made. Other everyday things have no recording yet and get the nearest design (a few of them a cookbook recipe): a gulp, chewing, a seagull, a pigeon, a snake's hiss, a whale's song, a dial-up modem, a padlock, a pan set on a stove, a fridge door, a quick row of chops (one chop is made), a printer, a shopping cart, a bus, an airplane passing close, a tennis or basketball hit, a clockwork, a car alarm, a hole punch, a throat cleared; steps on sand, on carpet and on metal stairs. No public-domain recording of a real snake hissing or of a whale was found (the ones offered are voices or made sounds); a modem's tones and a clockwork's ticks were learned and smeared (a take further from the recording than two takes from each other), so they were left out. - Make two sounds in one call. A request that names two ("a water drop and a coin") makes one of them and says `not in this sound: ...` for the other; ask again for it, or make a set. - Follow every word. Words that matched nothing come back as `not understood`; controls a design does not read, or a length it cannot keep, come back in plain words (`not followed: ...`, `0.43 s, not the 2 s asked ...`). A material picks the voice of a tonal sound only among six (wood, glass, metal, soft, digital, retro); other materials ("plastic", "ceramic") only steer the ranking. A theme's scale changes a figure only when it is minor. Bank sounds read pitch and length where their recipe has those knobs, and no axes. A learned sound keeps a length only within 0.6-1.8 times its natural one and a pitch only on tonal recordings (7 semitones at most). - Exact lengths. A length sets how long a figure sounds before its room dies away, so the file runs longer than the number; a struck one-shot rings as it rings, and a voice cannot ring longer than it does (a marimba chime asked for 2 s came out 0.55 s); both say so. A loop has a shortest length per scene: an ambience asked shorter is a cut, not a loop, and a music loop keeps whole bars ("8 seconds" is 8.57 s). - Choose by taste. The ranking reads words, not the product; two good designs for one job can differ a lot. Use `also`, `--sound` and a person's ears. **What is weak or unverified.** - **The rebuilt motion sounds are not judged by ear.** The motion and film sounds follow measurements of professional motion videos: short, dry hits, thumps, ticks and whooshes of air, built from learned recordings. The `film` set plays small real actions cut to those measurements (a door falling shut for the thump, the top of a mechanical key for the tick, a heavy bag dropped under the title and the logo, a stick and a broom through the air, a breath of air rising, a sword drawn). Of the earlier film sounds the fast whoosh was judged good and the hits, booms, risers and the tape stop poor; the rebuilt ones have not been judged. The measurements come from 39 videos and find effects only where they stand out of the music, so quieter effects under the music are not counted. 14 of the 69 motion designs (pops, tocks, a blip, glints, a sparkle, key ticks, a sliding panel, a soft knock, the soft sting) are still invented. - **The interface set is not judged by ear as a set.** The seventeen roles of `ui` are things a hand does, built from learned recordings. Which object a role uses is a choice of taste: the other candidates are in the catalogue by name. - **Drums.** The acoustic kit and the hand percussion are takes of 13 - docs/MAKE.md (112316 bytes)
# Making sounds: `make`, `sounds`, `pack` An agent asks for a sound in words; earshot reads the request, ranks its catalogue of designs, renders a new take of the best one, audits it without models and writes the file. No model is loaded and nothing is downloaded. A design is either written in code (figures, chip sound, the drum-machine voices, ambience from rules, notes, the music loops) or learned from recordings in the public domain and kept as numbers ([Learned sounds](#learned-sounds)): everyday things, the interface sounds, the film and motion effects, most ambience beds, the acoustic drums and hand percussion. Either way every sound is computed when it is asked for; no audio file is shipped or played back. Everything rendered belongs to whoever rendered it: free for any use, commercial too, without credit. - [make](#make) - [learned sounds](#learned-sounds) - [make --set / --spec](#a-whole-set) - [sounds](#sounds) - [pack](#pack) - [The request language](#the-request-language) - [The eight axes](#the-eight-axes) - [Themes](#themes) - [Recipes: build what is missing](#when-earshot-has-no-such-sound-build-it) - [The catalogue](#the-catalogue-family-by-family) - [Voices](#voices) - [The engines](#the-engines) - Recipes: [a web page](#recipe-a-web-page) - [a game](#recipe-a-game) - [a film](#recipe-a-film) - [add a design](#add-a-design) ## make ``` earshot make "WORDS" [-o FILE] [--n N] [--seed S] [--theme NAME] [--sound ID] [--pitch NOTE] [--dur S] [--voice NAME] [--material NAME] [--bright X] [--hard X] [--ring X] [--size X] [--space X] [--width X] [--energy X] [--motion X] [--lufs L] [--mono] [--no-loop] [--listen] [--json] [--out F] ``` ``` $ earshot make "a soft success sound for a finance app" -o success.ogg success.ogg: success/shutter (0.36 s, peak at 0.10 s, -15 LUFS, clean) [success] also: complete/shutter, success/click, complete/chop $ earshot make "a mouse click" -o click.wav --n 2 click_1.wav: click/mouse (0.19 s, peak at 0.01 s, -20 LUFS, clean) [mouse click] click_2.wav: click/mouse (0.36 s, peak at 0.14 s, -19 LUFS, clean) also (the pick is a guess: another kind of sound fits almost as well): mouse/squeak (a mouse squeaking), pen/click (a ballpoint pen clicked), switch/small (a small switch flipped). Name one with sound=<id> ``` The answer is the whole result. Each file gets one line: the design chosen, its length, where its loudest moment is (`peak at`, seconds from the start of the file), the note and voice it played (tonal designs), its momentary-max loudness, `seamless loop` for a loop, and `clean` or the audit's warnings; the first line ends with the words that decided, as you wrote them (`[success, chime]`, or `[named]` for `--sound`). Then: | line | meaning | what to do | |---|---|---| | `not in this sound: ...` | sounds or jobs the request named that the chosen design does not cover | ask for them in a second call, or pick from `also` | | `also: ...` | up to three alternatives, always: the next ranked designs, then the nearest of the same family, kind or domain | take one with `--sound ID` if the pick does not fit the job | | `also (the pick is a guess: ...): id (a few words), ... Name one with sound=<id>` | no job or sound word matched (and, when listening, the request does not clearly sound like the pick), or another kind of sound scored almost as high, or the thing or what it does is a word earshot does not know (`earshot makes no dial up modem; dial/click is only the nearest sound it has`); the alternatives then come from other families first, each with the start of its description | name one with `--sound ID`, or describe the sound by what it is made of ("a screeching run of electronic tones and static") instead of by its name, or tell the user that this thing is missing | | `no rain on a tarp: rain/tent is the nearest surface; also: ...` | the sound exists, but not on the surface, ground or place said after "on", "in", "against" or "into"; the pick is the same sound on the nearest surface it has, the alternatives its other surfaces | leave it, or name another surface with `--sound ID` | | `not followed: "slow"; this sound has no control of its speed ...` | a control the request asked for (in words or as an argument) that this design does not have; the line says what it does instead. A word that named the design ("fast" in "a fast whoosh") is never listed | leave it, or ask for a design that has that control | | `0.43 s, not the 2 s asked: a single struck sound rings as long as it rings` | a length a one-shot cannot keep | leave it, or ask for a whoosh, a figure or a bed | | `a cut of 4 s, not a loop: the shortest seamless loop of this sound is 8.00 s` | an ambience asked shorter than its shortest loop: the length asked, cut from the bed with a 30 ms fade in and a fade out (10 % of it, at most 0.5 s) | say "a seamless loop of ..." if it must repeat | | `a seamless loop of 8.00 s, the shortest this sound has; 4 s was asked ...` | the request said "loop" or "seamless": the seam wins over the length | nothing, or drop "loop" for a cut | | `8.57 s: a music loop is whole bars, and these are the nearest to the 8 s asked` | a music loop keeps its bar grid | nothing | | `9.87 s, shorter than the 10 s asked: the longest this sound is made` | a looping design came out shorter than the length asked | nothing, or ask for a loop | | `3 knocks 1.5 s apart: 3.25 s, not the 10 s asked (knocks further apart than 1.5 s are no longer one action)` | a counted action whose events cannot fill the length asked: they are played at the widest (or closest) gap a person keeps, or a countdown at one a second, and the file is as long as that ([Performances](#performances)) | nothing, or ask for more or fewer events | | `not understood: ...` | words that matched nothing in the catalogue or the lexicon | rephrase if they mattered | | `x.mp3: a loop in mp3 has a gap at its seam ...` | a single `make` of a loop to mp3 or m4a | write loops as ogg, webm, wav or flac | | ` a loop: flac instead of mp3, which leaves a gap at the seam` | in a set with several formats, a loop was written as flac in place of mp3 / m4a | nothing | | ` same design as NAME: ask for a different one with "sound" (the nearest: ID)` | in a set, two names got the same sound | in your own spec: give the second one `"sound": ID`, or reword its `want` | | ` another recording of ID than NAME: recording N of M` | in a set, two names play different recordings of one learned design (toggle_on and toggle_off, back and next in `ui`) | nothing: the pair is meant | | `heard as: '...' (z +x.x, verdict)` | with `--listen` only (below) | | | `not listened: ...` | `--listen` was asked and the model or the atlas is missing | `earshot doctor` | A guess, as `make` writes it (the alternatives without a guess stay bare ids): ``` $ earshot make "a frobnicating zorp" -o x.wav x.wav: thump/soft (0.09 s, peak at 0.02 s, -19 LUFS, clean) also (the pick is a guess: earshot makes no frobnicating zorp; thump/soft is only the nearest sound it has): knock/wood (a knock on a wooden block), drill/electric (an electric drill whirring), whoosh/soft (a soft short whoosh). Name one with sound=<id> build it from parts: earshot recipe --example not understood: frobnicating, zorp ``` ``` $ earshot make "a marimba success chime, 2 seconds" -o mar2.wav mar2.wav: success/rise (1.85 s, peak at 0.20 s, G4, marimba, -14 LUFS, clean) [success, chime] also: success/triad, success/done, success/fifth ``` | option | what it does | |---|---| | `-o FILE` | the file; its extension picks the format (wav, flac, ogg, mp3, m4a, webm). None: `<family>_<name>.wav` here | | `--n N` | N takes on seeds S .. S+N-1, written `name_1 .. name_N`; "three variations" in the words does the same. For a learned design these are its other recordings first | | `--seed S` | another take of the same sound (default 0); the same arguments always give the same samples | | `--sound ID` | a design id from `earshot sounds` instead of the ranking; the words still set feel and numbers | | `--theme NAME` | a theme preset ([Themes](#themes)): voice, key, room and axis offsets shared by a product's sounds | | `--pitch` | a note (`C5`) or Hz. Overrides the words | | `--dur` | seconds: how long a figure of notes sounds, the hold of a pad, the length of a loop (each has a shortest one) or a whoosh; a learned sound within 0.6-1.8 times its natural length; a counted action ("three knocks", footsteps) is a file of that length with its events spread over it; a single struck sound (a tap, a hit) rings as it rings and says so (`0.43 s, not the 2 s asked ...`); an ambience asked shorter than its shortest loop is a cut, not a loop (unless the words say "loop"), a music loop keeps whole bars | | `--voice` | the instrument or patch of a tonal sound ([Voices](#voices)); a voice asked for by name is always played | | `--material` | what a tap, click or knock is made of; on a tonal sound without a voice it picks the voice made of it (wood: marimba, glass: glockenspiel, metal: vibraphone, soft: felt_piano, digital: glass_pluck, retro: square_lead) | | `--events N` | for a thing a person does several times in a row (footsteps, a knock, typing, coins, keys, clinking glasses): 1 = one event, 2 or more = the action with that many events; without it the words decide ([Performances](#performances)) | | `--bright` ... `--motion` | the axes, -1 .. 1, added to what the words say ([The eight axes](#the-eight-axes)) | | `--lufs L` | a momentary-max loudness instead of the default level | | `--mono` | sum to one channel | | `--no-loop` | an ambience once, with a fade in and out, instead of a seamless loop | | `--listen` | also rank by how each design sounds (the sound atlas, below) and say what the result is heard as | | `--json` | the full result: files, chosen id, `why`, `also`, `not_in_sound`, `unknown`, every take's measurements, audit and, for a learned design, the recording it played (`member`) | | `--out F` | also write that JSON result to the file F | **What happens.** `earshot.brief` reads the words into a brief (the thing, job or sound, the feel as axis offsets, a material or voice, numbers, the key); `brief.rank` scores every design; the best is rendered with those controls (`earshot.sounds.registry.render`), finished (low cut at 25 Hz, leading silence dropped, a 0.4 ms fade-in, the silent end trimmed and faded, the level below) and audited by `forge.sfx.check` (clicks, cut tails, clipping, DC, comb ring, a pitch that climbs more than 4 semitones, a hit with stacked attacks or a build before it; findings a design declares as its own, such as a power-up's rising pitch, are notes). A take that fails is rendered again on seed + 101, + 202, + 303; if all four fail the first is written and its line names the warnings. A request that matches nothing is no error: it gets the nearest sound there is, and the guess line says that it is only that (`earshot make "a frobnicating zorp" -o x.wav` writes `thump/soft` and says `also (the pick is a guess: earshot makes no frobnicating zorp; thump/soft is only the nearest sound it has): ...`). **`--listen` and the sound atlas.** `earshot/data/sounds_atlas.npz` (numbers only) holds a CLAP embedding of every design's default render and of its own descriptions. With `--listen`, the request's CLAP text embedding is scored against it (a z per design over the whole atlas) and blended into the ranking (`earshot.brief.blend`): a named job keeps its word-based winner, a request that only describes a sound is decided by how the designs sound, and the hard filters (chip sound, loop, a job ruled out) still hold. The written sound is then matched (`earshot match`) against the request and its own descriptions, and the result gains `heard as: '<the description that fit best>' (z +x.x, verdict)`. It loads CLAP once (20-40 s); the MCP server's `make` blends the atlas in without being asked once the model is loaded in that process. `make --set` and `make_set` rank by words only. The atlas must be rebuilt after designs are added or changed: `python -m earshot.sounds.atlas build --work DIR`, repeated until it says it is done (`python -m earshot.sounds.atlas status` checks it). The `heard as` line is what a model hears, not a judgement of quality: judgements by ear did not follow the models' scores ([VALIDATION.md](VALIDATION.md#listening-by-ear)). **Level.** A single sound is set to a true peak of -1 dBFS, but no louder than a momentary-max loudness by kind: -14 LUFS, pads and textures -18, ambience beds -22, music loops -16. A dense sound at full peak is far louder than a tap at full peak, so short sounds are brought forward: a one-shot under 1 s whose one spike would hold its body far down is raised by up to 14 dB, until its loudest 5 ms sit 3.5 dB under the peak, and the spike above is folded over smoothly rather than limited, so the strike stays as bright as it was (`master.finish`, `registry.LIFT`). An ambience bed held under its cap by a few peaks (a fire's cracks) is raised the same way by up to 8 dB. `--lufs` sets the momentary-max loudness exactly, with the peaks limited to -1 dBFS. Files are 48 kHz stereo unless `--mono`; every file starts when its sound does (within 2 ms) and ends faded, never cut. **Formats.** wav and flac are written directly (24-bit; 16-bit wav in a set) and are lossless; ogg (Vorbis, 96k), mp3 (128k), m4a (AAC, 96k) and webm (Opus, 64k) go through ffmpeg, which must be on PATH for them. For the web: Ogg Vorbis does not play in Safari before 18.4, so write `webm,mp3` (or `webm,m4a`) and let the browser take the first it can play. Loops: mp3 and m4a encoders pad the start and end and record it only in a note some players ignore, so a loop written as mp3 or m4a has a gap at its seam there. A single `make` to mp3 or m4a warns; a set with several formats writes its loops as flac in place of mp3 / m4a. Write loops as ogg, webm, wav or flac. ``` $ earshot make "campfire" -o fire.mp3 --dur 16 fire.mp3: fire/camp (16.00 s, peak at 14.33 s, -23 LUFS, seamless loop, clean) [campfire] also: fire/large, fire/small, fire/whoosh fire.mp3: a loop in mp3 has a gap at its seam in players that ignore the encoder's padding note; for loops use ogg, webm, wav or flac ``` **Speed** (one thread, no models): a one-shot takes about a second plus Python start-up. A learned ambience bed renders in 1.0-1.7 s of CPU per second of sound, so a 30 s bed takes 30-50 s; the beds from rules are faster. In Python: `from earshot.make import make; make('a door shutting', 'door.wav', size=0.3)` returns the same result as a dict (`summary`, `sound`, `files`, `why`, `also`, `not_in_sound`, `unknown`, `takes`, and `heard` with `listen=True`). `make()` also takes `sr` and `bits` for the written file. Every take (`takes` in Python, `--json`, the MCP result) also says where things happen, in seconds from the start of the file: `peak_s` (the loudest moment), `onset_s` (where the sound starts to - docs/motion-sfx-study.md (30116 bytes)
# What professional motion-design SFX are made of A measured study of the sound design in eight professional launch / motion films (third-party, kept local, called ref_1 .. ref_8 here), done to give earshot forge concrete targets: what a "pro designed" whoosh, riser, impact, click, pop or sting actually looks like in numbers, and how it sits against music and picture. Tools: `eval/forge/pro/` (earshot timeline at detail high + sheet per film, paged spectrogram overviews, zoomed crops, bed-subtracted measurements, trims). Local data: `out/refs_pro/` (never committed: trims, `manifest.json`, `registry.json`, `stats.json`, `films.json`, sheets and crops under `_work/`). ## How to read the numbers (and how far to trust them) - **58 events** were picked by looking: earshot sheets, 8 s overview pages, then zoomed crops of every candidate. Only events that stand out over the bed were kept (an exposed accent, or an SFX-only stretch). - **One film dominates.** ref_2 is a pure sound-design piece with no music bed; it supplies 39 of the 58 events and most of the clean ones. The other seven are music- or voice-led, and their effects are sparse or buried. The per-category numbers below are often 1-10 examples from 1-2 films: they are measurements of real pro work, not population statistics. - **Bed subtraction.** Each event is measured as (event power - bed power), with the bed taken as the quietest 150 ms in the 0.6 s before the event (`measure.quiet_bed`, so a run of clicks or a previous hit does not count as bed). Bands where the event adds under 1 dB are marked masked and left out of the spectral medians. Over a music bed this removes most of the music, not all of it. - **Levels** are K-weighted (BS.1770 filter): `over_bed` = loudest 100 ms of the event minus the quiet bed. Because the bed is the *quietest* stretch between beats, the figure reads a few dB higher than "over the average music level". A silent bed counts as -70 LUFS. - **Balance** = bed-subtracted power per 1/3-octave band in dB relative to the event's own total (level never decides). `tilt` = least-squares slope of that balance from 100 Hz to 10 kHz, in dB per octave. - **Attack** = from the first millisecond within 20 dB of the peak to the peak (1 ms bed-subtracted envelope). `t20` / `t40` = peak to the first fall 20 / 40 dB under it (10 ms smoothing). Decay shape: `convex` = holds, then drops (a gate or a fade), `exp` = straight in dB, `concave` = drops fast, then a long tail. - **Pitch** = the dominant spectral ridge (or the centroid for noise). Where a film's tonal music sat under a zip, the automatic ridge locked onto the music, and the sweep was read off the zoomed spectrogram instead (marked *read*). - All audio is the films' decoded AAC at 48 kHz stereo. ## The films: music first, effects placed | film | dur s | LUFS | LRA | cuts/s | beat | voice-over | cuts with an onset within 1 frame (chance) | strong accent within 1 frame (chance) | |---|---|---|---|---|---|---|---|---| | ref_1 | 20.5 | -10.4 | 6.4 | 0.78 | 107 BPM, weak | yes | 31% (35%) | 6% (8%) | | ref_2 | 29.5 | -22.2 | 12.2 | 0.54 | none | no | 50% (44%) | 19% (10%) | | ref_3 | 49.3 | -17.4 | 5.5 | 0.63 | 133 BPM, weak | yes | 58% (46%) | 16% (9%) | | ref_4 | 8.7 | -23.1 | 0.7 | 1.71 | 111 BPM, clear | no | 20% (20%) | 7% (4%) | | ref_5 | 28.9 | -14.8 | 3.6 | 0.31 | none | yes | 67% (46%) | 22% (9%) | | ref_6 | 32.3 | -14.8 | 7.0 | 1.27 | 122 BPM, clear | no | 81% (71%) | 22% (15%) | | ref_7 | 41.8 | -7.3 | 3.3 | 1.60 | 92 BPM | no | 33% (31%) | 4% (7%) | | ref_8 | 93.1 | -12.1 | 1.7 | 0.30 | none | yes | 71% (60%) | 25% (11%) | What this says: - **Six of eight films let the music (and the voice) carry the cut rhythm.** Their cuts have some onset within a frame 20-81% of the time against a chance level of 20-71% (a few points above chance; ref_5 is the clearest at 67% vs 46%), and a strong accent within a frame only 4-25% of the time. Designed effects show up at a few chosen moments: opening UI ticks over a near-silent bed (ref_6), tonal zips into cuts (ref_5, ref_6), a noise riser at the very end (ref_1), a sub drop under a cut and an end chord (ref_8). ref_4 (a cut-down) has no designed effects at all; ref_3 and ref_7 bury theirs under voice or a -7 LUFS wall of music. - **ref_2 is the other model:** a film scored entirely with effects. No beat, 12 stop-downs (drops to silence between ideas), LRA 12 LU, integrated -22 LUFS. Every effect is exposed, and every one is short, band-limited and shaped (see below). - So "pro" is mostly **restraint and placement**: few sounds, each with one clear gesture (a pitch move, a gate, a thump), cut on the picture, sitting about 13-17 dB over the music when there is music. ## Per category Counts are measured events (exported trims in brackets: forge / bench). Ranges are min-max, "med" = median. ### Whoosh / swell into a cut (`whoosh_big`), 5 (2 / 0) - **Made of:** in the SFX-only film a whoosh is a **low swell, not air**: energy almost all under 150 Hz (bed-subtracted octave balance, re total: 31 Hz -19, 63 Hz -14, 125 Hz -14, 250 Hz -19, 1 kHz -28, 4 kHz -31, 16 kHz -37 dB), centroid 51-150 Hz, tilt -3 to -13 dB/oct, a faint high air layer on top at -20..-30 dB. The two buried whooshes in ref_1 are brighter (centroid 0.5-0.9 kHz) but the music makes that uncertain. - **Envelope:** 0.5-1.0 s, symmetric to slightly front-loaded: rise (-20 dB -> peak) 190 ms, fall to -20 dB 90 ms, to -40 dB 240 ms; rise shape straight-to-concave in dB (it accelerates into the peak). - **Pitch:** the centroid falls about 2.3 octaves across the pass (8.28-9.30 in ref_2): a pass-by, not a static noise. - **Stereo:** mono or near-mono (side 30-40 dB under mid); no pan travel in any example. The width in these films comes from textures, not from whooshes. - **Timing:** peak 127 ms *after* the cut (ref_2 8.64), or a swell that peaks 313 ms before the cut and dies into it (ref_2 2.88); the buried one in ref_1 peaks 100 ms before its cut. So: peak within about +-150 ms of the cut, with the energy straddling it. - **Level over music:** +15 to +21 dB (ref_1, two examples). ### Riser (`riser`), 3 (1 / 1; one music riser measured only) - **Designed riser (ref_2, 0.84 s):** three layers you can see: (1) a **stutter gate**, 34 pulses at 22 ms median spacing (45/s), speeding up from 24 ms to 20 ms toward the cut; (2) a **rising tonal layer**, about 2 kHz -> 8 kHz (+2 oct; the last 0.22 s climbs 4.2 -> 8.1 kHz, about +4 oct/s); (3) a steady low drone (50-500 Hz) under it all. It ends on the cut (+20 ms) and hands over to a low whoosh / boom that blooms just after. - **Noise riser (ref_1, 1.15 s, film end):** high band (> 4 kHz) climbs about 35 dB, centroid +1.4 oct (360 Hz -> 1.1 kHz ridge), rise concave in dB (slow start, fast finish), side 14 dB under mid. - **Music riser (ref_7, measured only):** high band +20 dB over 0.45 s into the drop, only +5 dB over the music. - **Rise shape:** concave in all three: the level accelerates; most of the rise happens in the last third. - **Level over music:** +15 dB (ref_1). ### Impact (`impact`), 3 (2 / 0) - **Made of:** sub-dominated: 31 Hz -15, 63 Hz -9, 125 Hz -12, 250 Hz -18, 500 Hz -36, 1 kHz -45 dB re total; under 150 Hz holds all but 0.7 dB of the energy in ref_2 4.71; tilt -3.6 to -5.7 dB/oct; ridge at 82 Hz. - **Layers:** a broadband transient on top (full-band vertical line at the onset), the sub body, and **a textured tail**: ref_2 4.71 has a granular low rumble (pulses every 28 ms, 36/s, slowing slightly) lasting 1.2 s; ref_2 14.02 has a sustained high air band (5-10 kHz) over the body. - **Envelope:** attack 50-290 ms to the loudest point (they swell into the body rather than peak on the transient); tail: t40 230 ms to 1.08 s, decay 38 dB/s for the rumble; **both designed impacts end with a hard gate** (the tail is cut, not left to ring). - **Stereo:** the body is centred, the rumble / air tails are decorrelated (correlation -0.01 and 0.24, side about level with mid, pan travel 28-30 dB). - **Timing:** the swell starts 110-200 ms *before* the cut; the loudest point lands 65 ms before to 82 ms after it. ### Sub drop (`sub_drop`), 1 (0 / 1) - ref_8 85.58: a **sub tone 64 -> 44 Hz** (-0.55 oct over 0.75 s) entering on a cut with a bright transient on top; energy share under 150 Hz -0.5 dB of total; rise to the sub peak 430 ms (it blooms after the cut: peak +380 ms), decay 42 dB/s (straight in dB), t20 360 ms; narrow (side 13.5 dB under mid); +13 dB over the voice + music. ### Logo / end sting (`logo_sting`), 2 (1 / 1) - **Designed (ref_2 28.62):** a **falling chirp 1.5 kHz -> 150 Hz in 85 ms** (-3.3 oct, about -38 oct/s) landing on a **low tonal hum** (fundamental about 64-80 Hz with harmonics to 160 Hz, sinking -0.6 oct) that rings about 0.8 s; mono (correlation 1.0); balance peaks at 250-500 Hz (-13 / -6 dB re total), tilt -6.9 dB/oct; t20 58 ms, t40 260 ms with a concave tail. It starts 28 ms after the cut that ends the glitch. - **Music ending (ref_8):** a struck end chord with a 4 s ringing tail (centroid 1.9 kHz, decays about 130 dB/s at first, then the tail). ### Glitch / stutter (`glitch`), 1 (1 / 0) - ref_2 27.90-28.60: crackle first (sparse high grains, 4-12 kHz), then a dense broadband stutter: 11 bursts at 28 ms median spacing (36/s), **speeding up from 32 ms to 22 ms** into the cut; bright (centroid 9.2 kHz, tilt +3.8 dB/oct, 8 kHz band strongest); **fully decorrelated** (correlation 0.04, side as loud as mid, pan travel 9 dB). **It ends exactly on the cut (0 ms)** and the sting takes over. ### Shimmer (`shimmer`), 2 (2 / 0) - **Granular sparkle (ref_2 6.15, 1.95 s):** dense short partial grains every 20 ms (50/s) between 1 and 10 kHz over one steady tone at about 500 Hz; swells 0.5 s, fades about 0.8 s; balance 500 Hz -11, 1 kHz -15, 2 kHz -9, 4 kHz -15, 8 kHz -20, 16 kHz -36 dB; tilt +6.5 dB/oct; **wide** (correlation 0.08, side 0.3 dB under mid, pan travel 14 dB). - **Melodic chime run (ref_2 24.25, 1.95 s):** glockenspiel-like notes (270 Hz - 10 kHz partials) panned note by note (pan travel 94 dB = hard-panned notes), cut off by a gate at the end. ### Notification ding (`notify`), 4 (4 / 0) - **A struck tone with one inharmonic partial:** fundamental about 1.8-2.2 kHz plus a partial near 3.4x (6.3 kHz), attack 1-15 ms, t20 27-42 ms, t40 30-180 ms (short, convex: they ring briefly and stop), 0.23-0.36 s in all. - **Successive dings step up a semitone:** fundamentals 1822, 1934, 2045, 2168 Hz (ratios 1.061, 1.057, 1.060). - Balance: 1 kHz -6, 2 kHz -5 dB, nothing under 500 Hz (< -38 dB); stereo moderate (side 5.5-13 dB under mid). - +16 to +17 dB over the bed they ride on. ### Pop (`pop`), 3 (2 / 1) - **Chirp pop (ref_2 13.10):** a sine **falling 9.8 kHz -> 350 Hz in 110 ms** (-4.8 oct, about -43 oct/s), preceded by a 20 ms blip at 3 kHz; attack 32 ms (the loudest point is mid-sweep, around 1-6 kHz), t20 14 ms after it. - **Blip pop (ref_2 13.30):** a 1.2 kHz tone with harmonics, gated on and off (70 ms box, 2 ms attack, 7 ms release). - **Over music (ref_5 16.84):** a tonal blip falling 1.1 kHz -> 100 Hz with a click, +14 dB over the music. - All three are **mono** (correlation 1.0 or side 40 dB down). ### Element pop-in (`pop_in`, not a forge category yet), 10 (10 / 0) - The most used effect in ref_2: one per element appearing, fired in a run (17 events over 3.3 s, spacing 120-310 ms, median about 205 ms, settling into a steady 200 ms pulse). - **Made of:** a **thump body at 80-150 Hz** (ridge peak about 105 Hz; under 150 Hz holds all but 0.5 dB of the energy; tilt -4 to -6 dB/oct) plus a **short noise tick** (1-10 kHz, about 30 ms, 30-40 dB under the body), often as a quick double hit (two bodies 60-70 ms apart). - **Envelope:** 0.14-0.27 s, attack 6-19 ms (median 16), t20 16-35 ms (median 20), t40 30-80 ms; convex (holds, then stops) in 7 of 10. - **Stereo:** moderately wide (side 3.5-9 dB under mid, correlation 0.38-0.78). - **Timing:** lands 25-40 ms after its cut (first and last of the run). ### Tap (`tap`), 1 (1 / 0) - ref_2 18.70: a 150 Hz thump (ridge 130-160 Hz) with a faint broadband click, 0.1 s, attack 11 ms, t20 18 ms, t40 27 ms, tilt -6.5 dB/oct, side 5 dB under mid; 86 ms before its cut. ### Click (`click`), 5 (1 / 2; two measured only) - **Bright UI clicks (ref_2, ref_6, ref_8):** attack 0-3 ms, t20 6-16 ms; centroid 5-10 kHz, tilt +4 to +12 dB/oct; the ref_2 click has tonal partials at 5-8 kHz (a "tink" rather than a noise snap). - **Mouse-like click over music (ref_5):** broadband with a low body (centroid 430 Hz, tilt -3.7 dB/oct), attack 10 ms, t20 11 ms, t40 37 ms, +13 dB over the music. - Mostly mono (side 10-14 dB under mid). ref_6's opening click lands 31 ms before its cut. ### Hover tick (`hover_tick`), 6 (3 / 3) - Tiny high ticks: 35-80 ms windows, attack 0-5 ms, t20 6-25 ms; centroid 2.8-9.5 kHz; tilt +2.4 to +6.2 dB/oct; balance: 1 kHz -23, 2 kHz -18, 4 kHz -13, 8 kHz -8 dB re total, almost nothing under 500 Hz. - Two kinds: **tonal pings** (ref_2: a single partial at 6-15 kHz, about 10 ms) and **filtered noise ticks** (ref_6: 2-12 kHz noise, 25-40 ms, the spectral peak falling as it decays). - Over a quiet bed: +15 to +20 dB. ### Typing (`typing_key`, `typing_run`), 7 keys (6 / 1) + 1 run - **Designed typing is high-passed noise, nothing else:** each key a noise burst at 3-12 kHz (ridge 8.6-11 kHz), **essentially nothing under 2 kHz** (bands up to 1 kHz at -60 dB, the floor; 2 kHz -28, 4 kHz -13, 8 kHz -7, 16 kHz -14 dB re total), tilt +12 to +19 dB/oct; attack 2-5 ms, t20 11-18 ms, t40 about 60 ms; convex; mono. - **The run (ref_2 10.40-11.95):** keys at 62-148 ms spacing (median about 87 ms, about 11.5 keys/s), level and timing jittered, a soft low swell rising under the end of the run. - The bench key (ref_8, in a voice-over gap) is a more realistic mid-range key (centroid 3.2 kHz). ### Zip (`zip`, not a forge category yet), 4 (0 / 4) - **Fast tonal pitch sweeps** (a sine-like glide plus harmonics), 0.18-0.28 s, sitting only **+7 to +9 dB over the music** (lower than the hits): - up: about 100 Hz -> 1.5 kHz in 0.2 s (*read*, about +20 oct/s), starting 39 ms before a cut (ref_6 1.60); - up: about 100-150 Hz -> 10 kHz in 0.22-0.25 s (*read*, about +30 oct/s), **ending on the cut** (+20 ms, ref_6 3.78); - down: 7.2 kHz -> 420 Hz in about 60 ms (*read*, about -60 oct/s), across a cut (peak 65 ms before it, ref_5 22.80); - arc: about 1 -> 3 -> 1 kHz over 0.25 s (*read*, ref_5 28.22). - Straight lines on a log-frequency axis: the sweeps are exponential (constant octaves per second). ## What the pro sounds have in common 1. **One gesture each, and it is mostly pitch or gate.** Zips at 20-60 oct/s, pop chirps at about -43 oct/s, the sting chirp at -38 oct/s, dings stepping up a semitone, a riser's tonal layer climbing 2 octaves. Rise
- docs/motion-sfx-techniques.md (51590 bytes)
# Motion-design SFX: how the pros build them, as synthesis recipes For anyone writing an earshot forge recipe (`earshot/forge/recipes/*.py`) who wants sound effects that hold up in a motion-design launch video. Research notes, 2026-10-16, branch `forge-v2`. How to read the numbers: - **(src N)**: the number or claim comes from reference N at the bottom of this page. - **[sv]**: a *starting value*. This is synthesis practice, not something a cited source states. Tune it by listening and measuring (earshot's tone, polish and envelope checks). - **(earshot)**: measured by earshot itself, either in `docs/launch-video-sound.md` (7 pro launch films) or in a recipe's notes on its real reference recordings. The web sources are mostly practitioner tutorials and vendor guides. They agree on structure (layers, movement, processing). They give few hard numbers, and the numbers they do give vary. Where only a search summary was available and the page itself was not read, the reference says so. --- ## 0. The difference between a "real" sound and a motion-design sound The forge's v1 recipes are physical models fitted to raw recordings: a button click, a key press, a bubble pop, a swung stick, a drum boom. Launch-video SFX are a different product. They are **designed**, which means: 1. **Several layers, each with one job.** Every source describes a pro SFX as 2-4 layers that peak together: transient / body / sub / tail for hits (src 9, 10), and air / texture / tonal / landing for whooshes (src 2, 3, 4). The usual fix for a flat hit is another layer, not another plugin (src 10). A single layer is the amateur signature (src 1, 42). 2. **Each layer owns a band.** Layers are EQ'd so they do not fight. Two body layers sharing ~200 Hz cancel each other and turn to mud (src 10). Keep 3-4 elements at most (src 7). 3. **Movement.** A whoosh or riser with a static spectrum sounds cheap. "Movement is the whole effect" (src 1). Filter, pitch, level and pan move together, along curves that accelerate into the peak (src 7). 4. **Processed and glued.** Light saturation for harmonics (so it survives small speakers), transient shaping, bus compression that glues without squashing, one shared space, then a limiter (src 9, 10, 41). 5. **Edited clean.** The file starts on the first sample of the transient with no leading silence (src 16) and has no noise floor or room tone unless that is the point. The tail is trimmed but never chopped. Pops in a pro kit last 0.19-0.41 s, with almost nothing below 150 Hz or above 4 kHz (earshot, `pop.py` notes). 6. **Exaggerated, not literal.** Pitching a sound down makes it bigger and heavier; pitching it up makes it smaller and lighter (src 42). Bigger whooshes are lower and slower (src 3, search summary). Designers pitch bright recordings down 2-3 octaves to make sub-heavy material (src 9). 7. **A palette.** UI sounds come from one patch, with only pitch and envelope changed (src 16). Earcon families share timbre, register and rhythm (src 17). The tonal parts are tuned to the music's key (src 10). 8. **Synced to the frame and used sparingly.** A sound a frame or two off breaks the illusion (src 42). Most motion needs no sound, because the music carries it. The big accents are rare (src 18, src 4, earshot). So for the forge, a physical model is a good **source layer**. A motion-design SFX recipe needs a **design stage** on top of it: layers, per-layer EQ and saturation, glue, space and an edit. Its references should be designed library SFX, not raw foley recordings. ### The universal design chain (per sound) | step | what | start values | |---|---|---| | 1 | Band each layer (HP / LP, one static EQ move) | sub < 120 Hz, body 80-800 Hz, transient > 1-2 kHz, air > 2 kHz [sv] | | 2 | Saturate body and transient lightly, never the clean sub | tanh/tape, drive 3-9 dB [sv]; distortion adds overtones, so EQ and compress after it (src 9) | | 3 | Shape transients | keep the crack, shorten its tail (src 10) | | 4 | Glue the sum | bus comp 2:1-4:1, attack 10-30 ms (lets the transient through), release 60-150 ms, 2-4 dB gain reduction [sv]; glue, not squash (src 10) | | 5 | Space | reverb on body and tail only, sub dry (src 10); pre-delay 10-30 ms keeps the attack clear [sv]; darken the return (LP 3-6 kHz) [sv] | | 6 | Stereo | transient and sub centred; width from reverb and decorrelated layers; delays of 2-50 ms fuse into one sound rather than an echo (src 36), but check the mono fold-down (src 4) | | 7 | Finish | HP at 20-25 Hz (energy below 25 Hz wastes headroom, src 10); look-ahead limiter at -1 dBFS true peak; loudness-match the family (src 16) | The round-1 `earshot/forge/fx.py` (in progress; names may change) already has most steps: `saturate`, `transient`, `reverb`, `limit`, `width` / `decorrelate` / `pan`, `doppler`, `sweep_filter`, `tape_stop`, `crush`, `stutter`, `glitch`, `granular` and `reverse_swell`. `earshot/forge/polish.py` detects the artifacts that make a sound cheap: clicks, aliasing, DC, rings, chopped tails, leading silence and loudness spread. ### Variation (round robin) Repeated sounds need variants: a few, chosen at random (src 22, search summary). Typing must never repeat the same sample twice in a row (earshot). Per-render jitter: pitch +-0.3-1 semitone, level +-1-2 dB, timing and decay +-10 %, with fresh noise seeds [sv]. Timbre stays fixed per *family*, so a set sounds like one product. --- ## 1. Whoosh / swish / swipe **Anatomy** (src 1-5) | layer | job | notes | |---|---|---| | air body | the motion itself | filtered noise band that moves; pink is smoother than white (src 1) | | texture | material and distance | cloth, paper, brush (src 4); cymbal swells exaggerate the peak (src 2) | | tonal / style | identity, "digital" or "designed" feel | optional, and it gets repetitive if overused (src 4) | | low weight | size | sine or hum for big moves (src 2, 3) | | landing | the stop | a separate impact, click or pop, only when the object visibly stops (src 4) | All layers share one peak moment (src 2, 3). Doppler: the pitch rises on approach and falls after the pass (src 1). **Durations, matched to the move.** For quick UI swipes or fast cuts, 0.25-0.5 s (src 1). A small card crossing ~10 % of the screen takes about 180 ms (src 4). A title reveal is about 0.48 s (src 4). A general whoosh is ~0.8 s (src 1). A product fly-by is 1.15 s with its peak at 620 ms, i.e. 54 % (src 4). A heavy close pass is about 1.2 s (src 4), and big reveals run 1 s or more (src 1). Make separate short, medium and long variants rather than time-stretching one file, because stretching smears transients (src 4). **Envelope.** The sound starts quietly, builds quickly to its loudest point, then trails off (src 3). Mark three points: prepare (motion starts), cross (fastest frame or cut), release (src 4). Put the peak at 50-70 % of the length. The rise follows an accelerating curve (power 2-3, or exponential in dB); the fall is an exponential decay at about twice the rate of the rise [sv]. Loudness of a moving object goes roughly as speed³ (dipole radiation ~U⁶), which gives a crisp, short top (earshot `whoosh.py` notes). Shorter, steeper rises read as sudden; keep anticipation short when the visual should feel sudden (src 4). **Synthesis** [sv unless marked] - Source: pink noise (src 1). Use 2-3 band-pass bands at fixed ratios, e.g. 1 : 1.6 : 2.5, moving together. One band is a noise wash. - Air whoosh: band-pass Q 1-3. The centre sweeps from 300-600 Hz up to 1.5-5 kHz at the peak, then falls back to 400-800 Hz. The sweep follows the speed curve: centre ∝ speed^0.5-1. - Heavy whoosh: centre 150 Hz - 2 kHz, longer, plus a sine at 40-80 Hz swelling with the peak, about 12 dB under the body. For a cymbal-like peak, reverse a short noise-burst reverb tail into the peak (src 2). - Swish (cane, whip, blade, thin fast object): 80-250 ms, brighter (2-10 kHz), steeper rise. Add a narrow aeolian whistle at f = 0.2·U/d (Strouhal; e.g. 30 m/s past a 1 cm rod ≈ 600 Hz), as band-passed noise at Q 15-40. - UI swipe (digital): 100-250 ms. High-passed noise (HP 300-800 Hz) plus an optional tiny tonal chirp (a sine gliding up an octave across the swipe, ~10 dB under the noise). No low end. - Doppler: the frequency ratio across a pass is (c+v)/(c−v). At 20 m/s that is ≈ 2 semitones in total; at 50 m/s, ≈ 5 semitones (c = 343 m/s, src 39). Apply it to the tonal layer and the filter centre. Designed whooshes often exaggerate it to 3-12 semitones on the tonal layer. - Pan: equal-power L→R following tanh((t−t_peak)/w), with narrow-wide-narrow width across the pass (src 4). Keep the mono sum intact. - Tail: a short reverb for size (src 1), or a pitched delay for a sci-fi feel (src 1). If an impact follows, leave ~80 ms of silence before it (src 4). **Processing.** Carve each layer's band, compress lightly to tie the layers together (src 2), give the tail a short room or plate, and add a little distortion only for aggressive whooshes (src 1). **In the mix.** The loudest point lands on the cut or the fastest frame (src 1, 4). It starts 0.2-0.6 s before (earshot). It sits under the picture; it does not shout (src 1). Reserve the longest, widest whoosh for the biggest move (src 4). **Cheap-sounding mistakes.** Static noise with a volume fade and no filter or pitch movement. Harsh unfiltered white noise. Too slow (it drags) or too fast (it reads as a click). Mono with no movement. One layer (src 1). The same envelope on every edit. A tail running into the next event. A stereo sweep on every sideways move. Making it louder to make it "better". A whoosh on a scene change where nothing actually moves (src 4). --- ## 2. Riser (uplifter, build) **Anatomy.** A noise riser (the filter opens), a tonal riser (the pitch rises), an optional texture or granular layer, a rhythmic element (accelerating LFO, tremolo or roll), and a growing reverb (src 6, 9). Use 3-4 elements at most (src 7). **Let one motion lead**: filter for noise sources, pitch for tonal ones; the others support it (src 7). **Synthesis** - Noise: low-pass or band-pass at 24 dB/oct, cutoff 150 Hz → 10 kHz over the length, resonance 15-20 % (src 6; Q ≈ 1.5-3 [sv]). The noise layer peaks slightly earlier than the tonal layer (src 6). - Tonal: saw or triangle, 5-7 unison voices detuned 10-15 cents (src 6). Pitch rises +12 to +24 semitones, narrowing to 12 near the peak (src 6). Stack layers at 0 / +12 / −12 st that fade in at different times (src 6). Detune can widen as it rises (src 8). - Accelerating modulation: LFO rate 1/2 note → 1/16 note (at 120 BPM, 1 Hz → 8 Hz), depth 10 % → 70 % (src 6). LFO speed and intensity rise together (src 9). - A frequency shifter from 0 to +200 Hz (src 6) gives an inharmonic, sci-fi lift. - **Curves are exponential, not linear**: most of the change lands in the last beat or two (src 7). For example p(x) = p0 + (p1 − p0)·x³, with x = t/T, or exponential in log-frequency [sv]. - Level: −20 dB → 0 dB across the riser (src 6), on the same accelerating curve. - Endless rise (Shepard-Risset): octave-spaced sine (or saw) partials under a raised-cosine loudness envelope over log-frequency, all gliding up together (src 35). Each layer must cover a full octave, or the reset is audible (src 6). Fade the top and bottom layers (src 7). - "Convergence" reveal riser (THX Deep Note): 30 voices start at random pitches between 200 and 400 Hz and glide to a chord spanning three octaves (src 34). That is a riser that resolves into the logo chord. - Width grows into the peak (src 7). Reverb grows too: size 30 % → 70 %; 2-3 s decay at 20-30 % wet for short risers, up to 6 s at 40 % for long ones (src 6). - Reverse swell: reverse a reverb tail so it rises into the hit (src 40). `fx.reverse_swell` does this. **Length.** In a launch film, 1-4 s (earshot). In music, 4 bars for short transitions and 8-16 bars before a drop (src 6). **Ending.** The peak lands exactly on the downbeat or the reveal frame; a climax that arrives late steps on the new section (src 7). Then cut it abruptly, duck it 3-6 dB just before the drop (src 6), or leave silence for 0.1-0.5 s (earshot) or one beat (src 7), then the impact. A riser ends in a hit or a short silence (src 9). **Cheap-sounding mistakes.** Energy piling up below 100 Hz (high-pass it, ~150 Hz). A climax that lands after the downbeat. No release, so it feels relentless. Too many layers. The same riser on every transition (src 7). Too much white noise or saturation (src 6). Linear curves (src 7). --- ## 3. Downlifter (downsweep, fall) The mirror of a riser, placed on beat one of the new section or right after an impact. It is a push-and-release after the build (src 7). Length 0.5-4 s [sv]. **Synthesis** - Noise: the filter starts fully open and closes, low-pass from 8-12 kHz down to 200-400 Hz (src 49, forum answer via search summary; values [sv]). Band-pass with extra bandwidth and resonance also works (src 8). - Tonal: pitch falls 12-24 st [sv]. For the pitch-down impact, a sine-square wave with an envelope on pitch *and* on the low-pass cutoff keeps the harmonics audible as the fundamental drops below hearing (src 8). - **Decelerating curves**: fast at first, slowing at the end, i.e. exponential decay with a time constant ≈ length/3 [sv]. - Level decays while the reverb gets wetter: the dry part dies first [sv]. An LFO whose rate is shaped by a reversed envelope, plus phase modulation and flanger, gives the classic synth downlifter (src 50). - Tape-stop variant: playback rate glides to 0 over 0.3-1 s (`fx.tape_stop`) [sv]. How steep the fall is sets whether it feels like a lazy sag or a hard yank (src 51, search summary). **Mistakes.** The same as risers, plus a downlifter that masks the drop it follows: keep it 6-10 dB under the impact [sv]. --- ## 4. Impact / hit (and braam) **Anatomy** (src 9, 10, 11) | layer | job | sources and numbers | |---|---|---| | transient | the timing, the "crack" the ear locks onto | short bright burst, mostly above 1 kHz: snare, clap, stick or a noise burst; shorten its tail (src 10) | | body | weight and character | kick, tom, taiko, metal resonance, gong (src 9, 10) | | sub | punch you feel | sine at 30-60 Hz with a pitch drop over 200-400 ms (src 10) | | tail | size and space | long dark reverb on the body; sub stays dry (src 10); the tail is typically a long reverb that fades (src 9) | | sheen / atmos | top and air | processed cymbal, metal, an atmospheric sound (src 9) | An example stack: distorted kick + high percussive element + processed cymbal + sub + atmosphere (src 9). Before the impact: pull back to near silence, because dynamic contrast makes the slam (src 11). Or use a reverse swell into it (src 40). **Synthesis** [sv unless marked] - Transient: a noise burst of 2-10 ms with an envelope raised to the 2nd-4th power (Farnell's bell striker: 10 ms of noise, env⁴, src 15/06), high-p
- docs/SFX.md (48856 bytes)
# Sound for films: the bank, `earshot sfx`, `earshot kit` earshot 0.4.0 ships its forge sounds, 51 sounds made in 0.4 for music-led launch films, three tuned voices and 15 sounds fitted from public-domain recordings as a bank that renders by id, aims a take at the picture, audits it without models, and renders a whole film's kit into takes with measured sync points (placed against the music bed and the cut by the launch preset). Everything here is pure DSP (numpy / scipy): no models, no network, no recorded audio (a fitted sound is stored as its modes, partials and band envelopes, not as samples). It is the sound engine of a code-made film: a film pipeline renders from the bank in seconds and only ever searches (`earshot forge`) or fits (`earshot fit`) offline. ```bash earshot sfx list --kind whoosh # what is in the bank earshot sfx render whoosh_fast/crisp -o w.wav --dur 0.8 --apex 0.32 # one take aimed at a move earshot sfx render pluck/kalimba -o e5.wav --pitch E5 # a tuned note earshot sfx check w.wav # the model-free audit of any sound effect earshot kit init --preset calm -o audio/kit.json # a film's kit from a preset (or --preset launch) earshot kit render audio/kit.json --out audio/kit # takes + audio/kit/kit.lock.json (cached) earshot kit check audio/kit.json --out audio/kit # ids, knobs, the audit of every take earshot kit audition audio/kit.json -o audition.wav # every take, role by role, at its level ``` Contents: [the bank](#the-bank) · [the 0.4 members](#the-04-members) · [knobs](#knobs-dur-apex-pitch-level) · [the audit](#the-audit-sfx-check) · [kits](#kits) · [mix keys](#mix-keys-04) · [presets](#the-presets) · [launch](#the-launch-preset-04) · [Python, MCP](#python-and-mcp) · [fit entries](#fit-entries-from-public-domain-recordings) · [cost](#cost) · [limits](#limits) ## The bank `earshot/forge/bank/*.json` (package data; the forge file is 275 KB, 64 KB gzipped; the 0.4 file 70 KB; the fit file 0.5 MB): 252 sounds today. `earshot doctor` reports the version and the counts. | file | version | entries | what | |---|---|---|---| | `forge_v2.json` | `forge_v2r6` | 183 | every delivered forge v2 final (34 categories, 4-6 named members each) | | `forge04.json` | `forge04r1` | 51 | the 0.4 recipe members: 7 new categories and new members of 6 old ones ([below](#the-04-members)) | | `fit.json` | `fit1` | 15 | recipes fitted from CC0 recordings (`fit/<role>/<name>`, [below](#fit-entries-from-public-domain-recordings)) | | `pluck.json` | `pluck1` | 3 | the tuned kalimba voices (`pluck/kalimba`, `pluck/kalimba_soft`, `pluck/kalimba_ring`) | `bank.VERSION` joins the file versions (`forge_v2r6+forge04r1+fit1+pluck1`: forge_v2 first, the other forge files, then by name); extra bank files load from `EARSHOT_BANK` (paths joined by the OS path separator, `os.pathsep`: `;` on Windows, `:` elsewhere; a missing or unreadable file is an error that names it). Ids are `<category>/<member>`: the category is the public name (a user never needs the recipe module behind it: `typing_key` renders with `recipes/keypress.py`, `pro_pop` with `pop.render_v2`, `pro_typing_run` with `typing.render_run`). **Faithful.** An entry is the final's schema-2 render block (`earshot.forge.schema`): recipe module, render function, member, the complete parameters at full precision, seed, peak and palette gain. The build re-renders every pick and compares it with its delivered WAV; one pick off by more than one 24-bit step (1e-6) and nothing is written: ```bash python -m earshot.forge.bank build out/forge_v2/*/final -o earshot/forge/bank/forge_v2.json # 183 / 183 within 1.2e-7 python -m earshot.forge.bank build --pluck -o earshot/forge/bank/pluck.json python -m earshot.forge.bank build --forge04 -o earshot/forge/bank/forge04.json # the 0.4 members, from the recipes python -m earshot.forge.bank check [IDS ...] # re-render against the stored fingerprints: 252 / 252 ``` The forge's seed banks (`earshot/forge/seeds/`) are search starting points, not this: rounded parameters without their render function; re-rendered from them, 34 of 94 checked finals come out as different sounds. **Meta.** Each entry stores, measured on its render at -1 dBFS: `dur_s`, `onset_s` (the 1 ms envelope's first point within 30 dB of its maximum), `peak_s` (the loudest 5 ms, 1 ms hop), `end_s` (the last 5 ms within 50 dB of the loudest), `attack_ms`, `centroid_hz`, `lufs_m_max`, `channels` and a fingerprint (50 ms RMS frames in dB re the loudest, to where the sound stays 60 dB down). A re-render on another machine is checked against it: length exact, peak within 5 ms, envelope within 0.5 dB (`bank.check`, `tests/test_bank.py`). On the build machine every entry re-renders bit-exactly. **Categories** (`earshot sfx list` has every member; `kinds` = the cue kinds / kit roles a category serves): | category | kinds | for | |---|---|---| | click, pro_click | click, tick.crisp | cursor presses; bright designed UI ticks | | hover_tick, pro_hover_tick | tick, tick.crisp | hover, rows passing, cursor blinks, counters | | tap, pro_tap | tock, land.light, click, tick | taps and touches on a surface; the soft thump of a touch | | toggle | snap, click | switches and lock-ins (press + latch) | | pop, pro_pop, pro_pop_in | pop, land, snap | bubble pops; tonal pops; an element popping in (round low thump) | | notify, pro_notify | bell, hit, text, click.confirm | struck bell chimes A4-E6; short clean dings a semitone apart | | shimmer, pro_shimmer | shimmer | chimes ringing out, granular sparkle | | whoosh_fast, whoosh_big, pro_whoosh_big | whoosh.short, whoosh.long, suck, swell | fast passes; big air transitions; the designed low sub swell | | swish, swipe | whoosh.short | thin flicks and text slides; cloth and paper swipes | | riser, pro_riser, downlifter | riser, drop | builds into a cut (forge_v2's stop on their loudest sample; 0.4's riser members peak and then fall, so a kit aligns them on `peak`); energy falling away | | pro_zip | zip | tonal sweeps across a cut (up / up_hi / arc rise in pitch) | | impact, pro_impact | hit, land | a cinematic hit (3-6 s tails); a designed gated sub impact (0.7-1.3 s) | | sub_drop, pro_sub_drop | drop | weight under a hit; the designed drop that blooms after the cut | | logo_sting, pro_logo_sting | sting | composite logo reveals; launch gestures onto a tone | | glitch, pro_glitch | glitch | glitch transitions; a designed stutter ending on the cut | | typing_key, pro_typing_key, pro_typing_run | key, key.space, key.return, key.run | mechanical keys; designed key ticks; a whole run | | pluck | bell, text, hit | a kalimba tine: tuned notes (native C5) | | fit | the role in the id, plus its `kinds` | recordings fitted as code: clicks, a tick, pops, light touches, keys, a space bar, a snap, a bell, a whoosh, a knock | | ui_pop (0.4) | pop, land.light | soft rounded mid pops: chips, bubbles, rows arriving | | knock (0.4) | tock, land.light | mid-band wood and plastic knocks | | cut_hit (0.4) | hit, drop, land | a short sub hit with a kick, or a short punchy hit, on a cut | | mallet (0.4) | bell, text | short gated mallet notes (glockenspiel, celesta, marimba), a soft pluck, chime runs | | drip (0.4) | pop | water drops: a bubble whose pitch rises | | shutter (0.4) | snap, click | camera shutters: a two-stage mechanical click for snap zooms and whip-cuts | | reverse_swell (0.4) | swell | reverse cymbals and swells that peak just after a cut (at most one a film) | ## The 0.4 members `forge04.json` holds 51 sounds made from earshot 0.4's recipes for the soft, short, mid-register style of music-led launch films, tuned toward measurements of a private set of licensed reference clips (not in the repo: no audio, no clip name and no per-clip model ships; aggregate measurements of them (medians, IQRs), CLAP cosines to them and parameters tuned toward them do). Each entry is a palette member of its recipe module (`FAMILY` / `FAMILIES` / `FAMILY_MID` / `RUNS` by name) on its seed, so `python -m earshot.forge.bank build --forge04` re-makes the file from the code (`bank.FORGE04` lists the members, their seeds and kinds). Besides the render block, meta and fingerprint, every entry carries: | key | what | |---|---| | `profile` | the catalog's model-free measures of its render (`recipes/_tonal.measure`): dur_s, attack_ms, t20_ms / t40_ms, centroid_hz, lo150 / hi4k (energy shares under 150 Hz / over 4 kHz), tonal (share within a quarter octave of the strongest bin), glide_st, corr (L / R correlation) | | `audit` | its takes audited in its first kind's role, seeds n .. n+5: `clean` of 6 and the warning codes seen (50 members 6 / 6, glitch/mid 5 / 6: one take rings, which a kit re-rolls) | | `original` | `{made: 'recipe', max_ref_clap}`: the largest CLAP cosine of its render to any reference clip (116 clean clips and 28 more, three excerpt conventions: fixed 1.0 s and 2.5 s windows and the trimmed span, repeat-padded), 0.53-0.84 over the 51 | The build refuses a member whose own take is not clean, with fewer than 5 of 6 clean takes, or whose originality is unmeasured, stale or over 0.96 (`bank.FORGE04_REF_MAX`). The recorded cosines (`bank.FORGE04_REF_CLAP`) hold for the renders they were measured on: `bank.FORGE04_REF_ON` names each one's render block (recipe, fn, params, seed), and a member whose block changed, or whose render no longer matches the shipped fingerprint, needs a fresh measurement (`--ref-clap fresh.json`, `{id: cosine}`) instead of keeping the old number. Siblings differ: the largest CLAP cosine between two members of a new category is 0.93 (cut_hit sub and kick; the two mid dings 0.95), under the ~0.97 two renders of one sound reach. | category | members (profile: length, centroid, attack, L/R correlation) | |---|---| | `ui_pop` | soft (0.14 s, 550 Hz, 22 ms, 0.98), step (0.16 s, 710 Hz, 43 ms), boop (0.14 s, 770 Hz, a rounder falling boop), blip (0.04 s, 1030 Hz, 0.07: fully wide), fall (0.16 s, 890 Hz, an eased fall with a faint second pop), wide (0.14 s, 890 Hz, 0.51) | | `knock` | wood (0.11 s, 670 Hz: a 400 Hz block and its rattle), plastic (2.4 kHz, bounces 18 ms later), snap (3 kHz), desk (a knuckle on a desk, 81 % under 150 Hz), double (a knock-knock 55 ms apart) | | `cut_hit` | sub (0.26 s, 210 Hz: 225 -> 46 Hz with a kick), kick (0.22 s, 275 Hz), punch (0.28 s, 180 Hz, 83 % under 150 Hz), rumble (1.4 s, a wide granular tail), air (0.49 s, a wide air band, 0.18) | | `mallet` | glock (0.35 s, 1.3 kHz, doubled an octave under, 0.85), celesta (G5, 0.31 s, 0.48: wide), marimba (G4, 0.33 s), pluck (0.29 s, 460 Hz); runs flourish (3 notes in an arc), up4 (4 notes 110 ms apart, panned note by note) | | `drip` | drop (306 Hz rising 8 st), bubble (255 Hz rising 10 st, a daughter bubble), plink (690 Hz), bloop (420 Hz, ~5 st over 0.1-0.15 s: the drip allowance), tiny (1.15 kHz, 0.1 s) | | `shutter` | dslr (0.19 s, 1.07 kHz), snap (a dry 2 kHz snap-zoom), mirror (a slower mirror box), film (0.25 s, 625 Hz box after 95 ms of travel), quick (release and curtain 21 ms apart, 1.6 kHz) | | `reverse_swell` | cymbal (3.3 kHz, 0.16: wide, a plateau then a stop), ring (rings out), dark (420 Hz, near mono, a low body), short (0.33 s to the peak, 3.7 kHz), breath (1.3 kHz noise, half wide) | | whoosh_big | thump, thump_deep, thump_airy: a low whoosh that lands with a thump ~80 ms in and rings ~0.35 s | | riser | dark (0.8 s, 450 Hz), build (1.1 s, sub-heavy), snatch (0.63 s): noise, sub and a speeding stutter, no synth sweep | | swish / whoosh_fast | swish bright (2.4 kHz), swish flick (4.3 kHz, stops dead, wide); whoosh_fast whip (a wide ring that falls ~45 st) | | glitch | burst, mid, chirp: the first burst is the loudest (a glitch that hits first) | | notify | mid_tine, mid_wood: rounded mid dings (~690 Hz, 32 ms onsets, t20 90-130 ms) | Knobs: `pitch` on ui_pop (f0 250-1200 Hz), mallet (f0 150-3200 Hz, runs too), knock (f1 250-2600 Hz), drip (f0 250-1600 Hz, not measured: the heard pitch is where it has risen to) and cut_hit (the sub's landing pitch, 36-130 Hz, not measured); `dur` on reverse_swell (its swell length) and the whoosh family members (shape, apex); risers and glitches through their length keys; the rest are trims. The tonal knobs (`knobs.apply(..., decay=, onset=, bright=, width=)`) reach ui_pop, knock, mallet, drip, shutter and notify. ## Knobs: dur, apex, pitch, level `bank.render(id, seed=None, dur=None, apex=None, pitch=None, peak_db=-1.0, sr=48000, weight=None)`; `earshot sfx render ID -o out.wav [--seed N] [--dur S] [--apex S] [--pitch NOTE|HZ] [--peak DB] [--weight W] [--sr R]`. Knobs edit the recipe's own parameters (`earshot/forge/knobs.py`); nothing is resampled or time-stretched. `meta['edits']` reports what each knob did and how close it landed. - **seed**: `None` renders the delivered final (its own seed). Any other seed is a new take of the same member: the noise, jitter and micro-timing change, the character stays (the finals were picked on robust re-renders). - **dur** (seconds, the file length): the whoosh family (whoosh_fast, whoosh_big, pro_whoosh_big, swish, swipe) scales rise, hold and fall together, so the pass keeps its shape; recipes with a length key (risers, downlifters, sub drops, shimmers, zips, glitches, typing runs, pro_logo_sting, the UI sounds' end gate) scale that key, render, measure and correct along a secant through the renders so far (at most 2 corrections, keeping the closest); the rest (impact, toggle, typing_key, logo_sting, pluck) keep their sound as it is. Then every dur lands exactly: a longer file is faded out to the length (raised cosine over a quarter of it, 10-150 ms; with apex as well the fade starts at least 5 ms after the apex, shortening to as little as 2 ms), a shorter one padded with silence. A riser's length is exact by construction (`length` 1.0 -> a 1.000 s file that stops on its loudest 5 ms). - **apex** (seconds to the loudest 5 ms, the whoosh family only): the pass engine's peak is analytic, `tp = rise * (|start_db| / 30) ** (1 / rise_k)`; rise is solved for the target, measured, corrected up to twice, then the closest render's peak is placed on the target by trimming the quiet approach (a head at least 20 dB under the peak, with a 3 ms fade-in) or padding silence before it, in whole 1 ms steps of the peak measure (a shift off that grid can re-read a fluttering pass's near-equal maxima, 0.2 dB and 15 ms apart on whoosh_big/swell). With dur as well, the candidates are ranked on apex error plus the error of the tail after it, and the apex is measured again on the file after its fit to dur, so `edits['apex']` describes the delivered file. Measured: the closed form lands within about 12 ms on the fast family, but a broad fluttering pass's 5 ms peak moves non-monotonically - docs/TESTING.md (2386 bytes)
# Fast tests without models The fast-test workflow runs the existing default pytest suite on Linux with Python 3.12, Node 24, and FFmpeg/ffprobe. Tests use synthetic media. It does not pass `--slow`, download model weights, or run licensed-reference benchmarks. Node is needed by the real-sound mux test; omitting it silently skips that test. For the same reduced environment locally, make those executables available on PATH, then run from a clone: ```sh python3.12 -m venv .venv-fast .venv-fast/bin/python -m pip --isolated install --no-cache-dir --only-binary=:all: --index-url https://pypi.org/simple -r tests/requirements-fast.txt .venv-fast/bin/python -m pip --isolated install --no-deps --no-build-isolation --no-cache-dir -e . EARSHOT_OFFLINE=1 HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 MPLBACKEND=Agg OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 .venv-fast/bin/python -m pytest -q -p no:cacheprovider -rs tests ``` This intentionally leaves out Torch and Transformers, which remain required by the normal package metadata. It is **not** a full installation or a packaging dependency check. Follow the README's installation instructions when running model-dependent features. Do not run `doctor --load` in this reduced environment. `tests/requirements-fast.txt` mirrors the non-model runtime requirements and adds the optional MCP/HTTP test dependencies, pytest, the real Hugging Face hub package used by fast loader tests, and the existing setuptools build backend. Keep it in sync when those requirements or tests change. Direct and transitive dependencies are not locked; package versions, Python patch releases, and the runner's FFmpeg can change between runs. The action implementations are pinned separately by commit SHA. Offline flags prevent normal model fetching; they are not a general network firewall. Installation needs network access. The workflow does not supply service credentials, persist checkout credentials, upload artifacts, or run with write permissions. External PR jobs may still require a maintainer to approve execution. Keep the repository's normal skip rules: slow/model tests and the optional delivered-final rerender fixture are outside this job's coverage. A passing fast job does not establish model quality, cross-platform behavior, full package installation correctness, or compatibility with every Python version advertised by the package.
- docs/VALIDATION.md (21665 bytes)
# Validation Every number here comes from a command in this repo, run on a Ryzen 7 260 laptop CPU (bf16, `EARSHOT_THREADS` 2-3, other jobs running). Full tables, data descriptions and "what was tuned on what" live in each area's results file; this page is the summary. Data: the Clawd film's licensed recordings (219 used + 125 rejected Freesound/Mixkit files), its finished 60 s soundtrack with every placement logged, the code-synthesized score that project retired, renders of the Cinetic synth engine, independent numpy generators, and 7 professional launch films (measured locally, never committed). Section 8 covers the sounds earshot makes (1.0). Their yardstick is listening by ear: earshot's own listening models did not predict how a person judged the made sounds, so their scores are not used as a measure of quality there. ## 1. Matching descriptions, ranking, finding moments ([eval/semantics/RESULTS.md](../eval/semantics/RESULTS.md)) `EARSHOT_THREADS=2 .venv/Scripts/python.exe eval/semantics/run_eval.py analyze` (tuning library) and `... heldout`. - Calibration (shipped: 5 prompt templates, term-bias removal + per-sound z): pooled AUC of (recording, description) pairs 0.966 on the tuning library (raw cosine 0.951). Tuning-library numbers are optimistic: 67 of the 322 vocabulary terms were added after seeing its classes. - **Held-out library (125 files labelled from file names before any scoring, nothing tuned on it)**, per verdict band: | verdict | z | true : wrong (lenient) | precision at a 3% base rate | at even odds | strict (close variant = wrong) | |---|---|---|---|---|---| | strong | >= 3 | ~1300 : 1 (126 true vs 3 wrong pairs) | 0.98 | 1.00 | 51 : 1 (precision 0.61 at 3%) | | plausible | 2.5-3 | 21 : 1 | 0.41 | 0.95 | 9.1 : 1 | | weak | 2-2.5 | 12 : 1 | 0.28 | 0.92 | 6.6 : 1 | | no match | < 2 | 0.25 : 1 | 0.008 | 0.20 | 0.25 : 1 | Half of the true matches reach "strong" (recall 0.51); 76% reach at least "weak". The strong band's ratio rests on only 3 wrong pairs: with that count's 95% Poisson range (0.6-8.8) it lies anywhere from ~440:1 to ~6000:1, and the tuning library gave 170:1. In a library search (~3% of candidate pairs true) a "strong" hit is the right kind of sound 98% of the time but the exact variant only 61% of the time (an Enter key for a spacebar counts as wrong). - Concrete needs, **tuning library only** (24 queries written from its manifests, such as "a deep thocky keyboard press", "a glass ting", "rain on a window"; optimistic, never scored on the held-out library): a correct file in the top 3 for 23/24 (miss: "a cork pop", mouth pops rank first), rank 1 for 19/24. - `find`: on a recording of 17 single key presses, 16 usable trims on 16 distinct presses (the 17th is a false positive on a double hit the curator marked to skip), each starting 5-54 ms before the attack, never after; 9/10 on a 32-press board; in a 44 s scene of 8 real one-shots the right event is top-1 for 8/8 (7 tight trims, one 5 s window); in a 300 s scene every planted event is found as a tight trim (the first build never looked past ~95 s; fixed with gap-free windows and a two-stage search). Re-run after the final review's find changes (snapped windows for one-shot queries, no events across edit gaps, `--kind event` = onset-based trims only): the same numbers. - **Real sound effects** (195 real licensed one-shots filed by the film job they play, `eval/semantics/real_effects.py`): asked by its own title, a real effect passes (weak or better) 168 times of 195, 124 strong. Asked by job words ("a soft rounded pop, something appearing", "one clean low hit under a logo") real pops and logo hits pass none; the best of two phrasings of the sound itself plus the job's description passes 176 of 195 (152 with the description alone) at AUC 0.922 own vs other jobs (0.912). Describe the sound, never its job; a forced choice against "a video game blip" is not a realness test. - Speed (`eval/semantics/timing.json`, models already loaded, nothing cached): model load 27 s once per process; `describe` of a 0.56 s key 17 s; `match`, new query on a cached file 2.0 s; `find` on an 18 s file 29.9 s for a new file, 1.2 s for a new query; `rank` 2.8 s per new file. Every CLI call is a new process and pays the model load, so for more than a few calls use the MCP server or one Python script (`from earshot import api`). ## 2. Real vs code-synthesized ([eval/realness/RESULTS.md](../eval/realness/RESULTS.md)) `EARSHOT_THREADS=2 .venv/Scripts/python.exe eval/realness/run_eval.py --stage report` (data and training scripts in `eval/realness/`; `train.py` reproduces the shipped weights bit for bit). - 1484 clean clips (691 real / pro, 793 synthesized), grouped cross-validation that never tests on a trained group: | scheme | ROC-AUC | [email protected] | |---|---|---| | leave one real category / synth family out (headline) | 0.922 | 0.860 | | leave one synth generator type out | 0.958 | 0.902 | | retired score never trained on: real vs retired | **0.948** | 0.862 | | retired score + the whole engine that made it never trained on: real vs retired | 0.909 | 0.839 | | zero-shot CLAP prompts (no training, baseline) | 0.858 | 0.749 | - Verdict bands (held-out): "real or pro-produced" p_real >= 0.77 and "likely code-synthesized" <= 0.17 are each right ~92% of the time on a pool that is 47% real / 53% synthesized, with both thresholds chosen on these same held-out predictions (so the 92% is in-sample for that choice); 79% of clips get a firm verdict, the rest "uncertain". The base-rate-free error rates: 6.7% of real clips are called synthesized, 5.5% of synthesized clips are called real. Long files use file-level thresholds (lo 0.40) on the mean of their 4 s windows, read from only 23 synthesized long files (weak calibration; the tool says so). - Pro-produced music held out by provider: mean p_real 0.86, 44 of 52 files called real, none called synthesized. - A deterministic rule catches pure, dead-steady test tones: a 30 s 440 Hz sine gets 0.48 from the model alone and 0.03 with the rule; the rule fired on none of 4741 audible clips of the 345 real recordings (`eval/realness/tone_guard.py` -> `tone_guard.json`). ## 3. Listening through a soundtrack ([eval/timeline/RESULTS.md](../eval/timeline/RESULTS.md)) `EARSHOT_THREADS=2 .venv/Scripts/python.exe eval/timeline/run_eval.py` (ground truth: the Clawd mixer's placement log). - Event detection vs the 147 placed sound effects: recall 93.2% (96.4% of those louder than the bed, 89.1% of those under it; 64.7% of the ones more than 6 dB under the music). - Sync against the picture cue frames: for the 140 of the 153 cues with an attack-aligned placement, measured offsets within 5 ms of the true placement offset for 84%, within one frame for 96%. The "without a hit" list is the weak part: both cues it named on Clawd were sounded whooshes. Beat grid of the 120 BPM score found at 120.0 BPM. - Event tags are hints: right kind for about 1 in 2 exposed events and 1 in 4 events buried in a bed; whooshes 56%, keyboard presses 58-82%, grass footsteps under music 0%. - Time: 60 s soundtrack 81 s, 93 s film 93 s (detail normal, 2 threads, 2-4 other processes busy). ## 4. Launch scorecard ([eval/launch/RESULTS.md](../eval/launch/RESULTS.md)) `EARSHOT_THREADS=2 .venv/Scripts/python.exe eval/launch/run_eval.py` - Leave-one-out: each of the 7 reference films vs a profile of the other six: 120/140 reference-range metric checks in range (86%; the no-overfit baseline for min-max ranges of six is ~71%). Not a blind test: some rules were changed after the first leave-one-out run (listed in the results file). `critique` on one of these 7 films now detects it and scores it leave-one-out automatically. - The Clawd film: with its real-recordings soundtrack "close" (21/23 metrics, p_real 0.94; flags a quiet first second and one loud stretch), with the old code-synthesized soundtrack "needs work" (critical: p_real 0.33, the code-synthesized windows listed; major: fades away instead of ending on a hit, sparse). - Known-bad variants written before the run (quiet, hot, mono, muffled, late start, dead air, long fade, hole, squashed, SFX-only, ambience-only, synth bed, sine, pink noise) and how each is flagged: in the results file. ## 5. Interfaces `.venv/Scripts/python.exe -m pytest tests/test_interfaces.py -q` (+ `--slow`) - The server lists 20 tools: the 13 listening tools, the three of the sound bank and `make`, `make_set`, `sounds` and `build`. The 13 listening tools were exercised over a real stdio connection on real files (silence, clicks, mono/stereo, ogg, mp3, the 60 s soundtrack, an mp4 film); bad input returns readable errors, never a crash; every JSON part valid. - Models stay loaded between MCP calls (the stdio handshake takes a few seconds; not benchmarked). - The Gemini critique has never been called live (no key on this machine, and a live call uploads audio): every path is tested against a fake HTTP layer, including the key never being printed and uploads deleted after use. ## 6. The real-sound skill reproduces the Clawd soundtrack exactly ``` .venv/Scripts/python.exe -I skills/real-sound/scripts/mix.py --root "<film project>" --design audio/sounddesign.json \ --cues out/cues_all.json --out out/repro/soundtrack.wav --stems out/repro/stems --report out/repro/mix_report.json \ --cues-out out/repro/cues_sounded.json --cache out/repro/cache ``` Bit-identical to the shipped `out/audio/soundtrack.wav` (sha1 `b48c5e8872fe96765624f88db18a0b49a0a05d68`), with an empty decode cache, and `mix_report.json` byte-identical. (`--cache` must point to a writable folder.) ## 7. Tests `.venv/Scripts/python.exe -m pytest -q` (fast; synthetic fixtures, no network) and `--slow` (loads the models / long end-to-end runs). What the tests of the made sounds check is in section 8. On the released tree the fast run has 4059 passed, 1685 skipped (the 1684 slow ones and one that needs renders a fresh clone lacks) and none failed; the slow tests alone (`--slow -m slow`) 1672 passed, 12 skipped (two known faults of the learning engine, ten real whooshes the pitch detector reads as gliding) and none failed. ## 8. Made sounds (1.0) ### Listening by ear The made sounds were judged by ear by one listener, the maintainer, on listening pages in a browser. The sounds were labelled on the page and were not loudness-matched beyond each page's own levelling: a strict judgement by one person, not a blind test. What it found, in plain words: - **Passed.** Chip sounds. The soft tonal figures (success, notify, error, level up, coin). Rain on a window and the forest bed, both made from rules. Takes of learned recordings: on 24 public-domain recordings, each played next to a take of its learned model and a varied take, the take was judged exactly as good as its recording in every row, so a learned design is as good as the recording it was learned from. - **Failed.** Sounds invented from formulas for real things (footsteps, jumps, landings, punches, explosions, doors, switches, taps and toggles), whether written by hand or fitted from a recording. Nine of twelve music beds. Most drums invented from physics. Bells, glass and glockenspiel timbres for interface sounds. New sounds sampled from a model of several recordings. Many short sounds were too quiet to be heard well. - **What changed because of it.** Realistic sounds are learned from public-domain recordings; the interface sounds are things a hand does with an object, and instruments answer only when music is asked for; weak ambience beds were replaced by learned textures; nine music beds were removed; the acoustic drums are played from recorded strokes; the figures are played on real instruments learned note by note; short sounds are raised (`master.finish`). - **Not yet judged by ear.** The sounds built last: the `ui` set as it is now, the rebuilt film and motion hits, thumps and risers, the drums from recorded strokes, the figures on the real instruments, the newer learned things and beds (animals, people, street, house and kitchen sounds; rain on wood, on a tin roof and on an umbrella), and the cookbook's recipes. They were measured against their recordings and checked by the audit. **The listening models did not predict the ear.** The CLAP match scores and the realness score that earshot uses to listen did not predict these judgements: sounds that failed by ear had passed the models' checks. These docs no longer quote model scores as the quality of a made sound. A predictor trained on the judgements (nearest neighbours on CLAP embeddings) ranks kinds of sound apart but cannot tell a good recording from a poor one of the same kind; it was used only to order the recordings of a learned design, never to admit or drop a design. ### Learned sounds, measured - **Fidelity** (`earshot/synth/resyn.py`, 41 CC0 sources): the band envelopes of a take sit a median 2.4-3.2 dB from the recording's at 2 ms resolution (the earlier fitting engine: 5.9 dB), the spectral shape within 0.7-1.3 dB, a click's rise within 1 ms; a model is 3.6-35 kB (median 9.1 kB); a render takes 0.26-0.33 s per second of sound. Weak: soft onsets smear (a bag drop's rise went from 61 to 99 ms); a fast swipe; impacts whose mid band is partly carried as noise (takes differ by about 3 dB there). - **The store**: 309 designs, 692 recorded members, 17.93 MB (some designs are material of the film sounds, below; 30 members hold several events, such as a whole walk or a knock, and 21 designs have such members). No duplicates, nothing judged poor by ear. Seed 0 plays the fullest clean member. Admission rules of the build: no chopped start or end, a full band, a natural tail, not faint, a clear onset; the build tool is not in the repository. - **Ambience textures** (`earshot/synth/quilt.py`, 24 textures, 9.46 MB; `wind/trees` is learned from wind through a field of dry leaves (maize), whose leaf band carries two thirds of the power and is dry, after no recording of trees passed that check; the fire is learned with an onset at every crackle and its two sides are two takes sharing the crackles; the waves from a recording at the water's edge, joined where they were cut; the rain on a window without its gutter's ringing drip). Measured on the first twelve (the rain on wood, on a tin roof and on an umbrella came later and are checked by the audit only), a take differs from its recording by 2.4-3.6 dB at band-envelope level, the same as two takes differ from each other, except the crickets (4.4 dB against 2.2: two crickets in one band lose their beating). The joints of a stitched bed differ by 0.9-1.5 times the texture's own variation (the pebble and rock shores about 1.5). The sea beds are 26-30 s with five waves each, the fire 24 s. A bed renders in 1.0-1.7 s of CPU per second of sound. - **Drums** (`earshot/sounds/drums.py`, - earshot/__init__.py (1714 bytes)
"""earshot: ears for coding agents. Python API (models load lazily on first use and stay warm): import earshot earshot.describe('whoosh.wav') earshot.match('key.ogg', 'a deep thocky mechanical keyboard press', alts=['a clicky blue switch']) earshot.find('typing.ogg', 'a single isolated key press') earshot.timeline('soundtrack.wav', video='film.mp4') or explicitly: `from earshot import api` / `from earshot.describe import describe`. Sounds made from a request in words (no models): `from earshot.make import make; make('a soft success chime', 'a.wav')`. Making sounds needs only the base install; the listening and measuring functions need an extra (earshot.extras), and without it they raise earshot.extras.MissingExtra, whose message is the install command. """ import importlib __version__ = '1.0.0' # modules that are callable as their main function (see _callable.py) _CALLABLE = {'describe', 'match', 'compare', 'realness', 'timeline', 'sheet', 'critique', 'profile'} # functions whose name is not a module name _FUNCS = {'rank': ('search', 'rank'), 'find': ('search', 'find'), 'ab': ('compare', 'ab'), 'measure': ('features', 'measure'), 'llm_critique': ('llm', 'critique')} def __getattr__(name): if name in _CALLABLE or name in _FUNCS: from . import extras extras.check(name) # earshot.describe without the listen extra: one sentence with the install command if name in _CALLABLE: return importlib.import_module(f'earshot.{name}') if name in _FUNCS: mod, fn = _FUNCS[name] return getattr(importlib.import_module(f'earshot.{mod}'), fn) raise AttributeError(name) # anything else: normal submodule import - earshot/__main__.py (51 bytes)
import sys from .cli import main sys.exit(main())
- earshot/_callable.py (540 bytes)
"""Make a module callable as its main function, so `earshot.describe(path)` works whether or not the submodule `earshot.describe` has been imported (Python binds a submodule over a package attribute of the same name).""" import sys import types def callable_module(name, fn_name=None): mod = sys.modules[name] fn = fn_name or name.rsplit('.', 1)[-1] class CallableModule(types.ModuleType): def __call__(self, *args, **kwargs): return getattr(self, fn)(*args, **kwargs) mod.__class__ = CallableModule - earshot/api.py (2935 bytes)
"""The Python API in one namespace (models load lazily on first use and stay warm in this process). from earshot import api api.describe('whoosh.wav') api.match('key.ogg', 'a deep thocky mechanical keyboard press', alts=['a clicky blue switch']) api.find('typing.ogg', 'a single isolated key press') api.timeline('soundtrack.wav', video='film.mp4') api.sfx_render('whoosh_fast/crisp', 'w.wav', dur=0.8, apex=0.32) # the sound bank (earshot.forge.bank) api.kit_render('audio/kit.json', 'audio/kit') # a film's kit: takes + kit.lock.json api.make('a soft success chime', 'success.ogg') # a sound made from words (earshot.make) """ import functools import importlib _FUNCS = { 'describe': ('describe', 'describe'), 'match': ('match', 'match'), 'rank': ('search', 'rank'), 'find': ('search', 'find'), 'compare': ('compare', 'compare'), 'ab': ('compare', 'ab'), 'realness': ('realness', 'realness'), 'realness_many': ('realness', 'realness_many'), 'timeline': ('timeline', 'timeline'), 'sheet': ('sheet', 'sheet'), 'critique': ('critique', 'critique'), 'profile': ('profile', 'profile'), 'measure': ('features', 'measure'), 'llm_critique': ('llm', 'critique'), 'doctor': ('doctor', 'check'), # the sound bank and film kits (no models): earshot.forge.sfx / earshot.forge.kit 'sfx_list': ('forge.sfx', 'sfx_list'), 'sfx_render': ('forge.sfx', 'sfx_render'), 'sfx_check': ('forge.sfx', 'sfx_check'), 'kit_init': ('forge.kit', 'kit_init'), 'kit_render': ('forge.kit', 'kit_render'), 'kit_check': ('forge.kit', 'kit_check'), 'kit_audition': ('forge.kit', 'kit_audition'), # sounds made from a request in words (no models): earshot.make 'make': ('make', 'make'), 'make_set': ('make', 'make_set'), 'sounds': ('make', 'sounds'), 'pack': ('pack', 'pack'), } def _fn(name): """the function `name`; a package it needs that the base install leaves out raises MissingExtra (an ImportError) with the plain sentence of earshot.extras, on import or on the call, never a bare ModuleNotFoundError""" from . import extras mod, fn = _FUNCS[name] try: f = getattr(importlib.import_module(f'earshot.{mod}'), fn) except ImportError as e: msg = extras.plain(e, name) if msg is None: raise raise extras.MissingExtra(msg, name=getattr(e, 'name', None)) from e @functools.wraps(f) def call(*args, **kwargs): try: return f(*args, **kwargs) except ImportError as e: msg = None if isinstance(e, extras.MissingExtra) else extras.plain(e, name) if msg is None: raise raise extras.MissingExtra(msg, name=getattr(e, 'name', None)) from e return call def __getattr__(name): if name in _FUNCS: return _fn(name) raise AttributeError(name) __all__ = sorted(_FUNCS) - earshot/audio.py (10421 bytes)
"""Audio I/O shared by every earshot module. Any file ffmpeg can read works (wav/flac/ogg/mp3/m4a and the audio track of mp4/mov/webm). Audio is decoded once to float32 at 48 kHz and cached under EARSHOT_HOME/decoded (keyed on path, size, mtime and 16 sampled 4 KB blocks of the content, so a same-size replacement that kept its timestamp is still noticed), so repeated calls are fast. x = load('kick.ogg') # (n, 2) float32 at 48 kHz m = load('kick.ogg', mono=True) # (n,) seg = load('long.wav', start=1.2, end=1.8, mono=True) Levels: the stereo decode keeps true sample levels (a mono file is duplicated to both channels at unity gain), so measure peaks and loudness on it (features.measure does). mono=True is ffmpeg's downmix, which sums a stereo source at -3 dB per channel: correlated stereo reads up to +3 dB hotter than mean(L, R). It is the models' input convention (their calibration was measured with it), so keep it for model input and timing, not for level readings. """ import hashlib import json import os import subprocess import numpy as np from . import config SR = 48000 AUDIO_EXTS = {'.wav', '.flac', '.ogg', '.oga', '.opus', '.mp3', '.m4a', '.aac', '.aif', '.aiff', '.wma'} VIDEO_EXTS = {'.mp4', '.mov', '.m4v', '.webm', '.mkv', '.avi'} MEDIA_EXTS = AUDIO_EXTS | VIDEO_EXTS LOSSY = {'aac', 'mp3', 'mp2', 'opus', 'vorbis', 'wmav2', 'ac3', 'eac3'} class AudioError(RuntimeError): pass DECODE_VERSION = 2 # bump when decoded samples change (derived caches may key on it) def _sample_hash(path, size, blocks=16, block=4096): """sha1 of `blocks` evenly spaced 4 KB blocks (first and last included): cheap, and catches a same-size file swapped in with its old timestamp kept (cp -p, robocopy, unzip)""" h = hashlib.sha1() try: with open(path, 'rb') as fh: for off in sorted({int(i * max(0, size - block) / max(1, blocks - 1)) for i in range(blocks)}): fh.seek(off) h.update(fh.read(block)) except OSError: return 'unreadable' return h.hexdigest()[:12] def _state(path): st = os.stat(path) return f'{os.path.abspath(path)}|{st.st_size}|{st.st_mtime_ns}|{_sample_hash(path, st.st_size)}' def _key(path, sr, ch): return hashlib.sha1(f'{_state(path)}|{sr}|{ch}|v{DECODE_VERSION}'.encode()).hexdigest()[:20] def replace_quietly(tmp, dst, tries=5): """os.replace(tmp, dst) for a cache write: retried briefly (Windows: another process may hold dst for a moment), then given up (tmp removed) - a cache write must never fail the call""" import time for attempt in range(tries): try: os.replace(tmp, dst) return True except OSError: time.sleep(0.05 * (attempt + 1)) try: os.remove(tmp) except OSError: pass return False def _src_channels(path): try: out = subprocess.run(['ffprobe', '-v', 'error', '-select_streams', 'a:0', '-show_entries', 'stream=channels', '-of', 'csv=p=0', path], capture_output=True, text=True, timeout=60).stdout.strip() return int(out.splitlines()[0]) if out else 0 except Exception: # noqa: BLE001 return 0 def file_id(path): """stable id of a file's content state (path + size + mtime + sampled content); used as a cache key by the models""" return hashlib.sha1(_state(path).encode()).hexdigest()[:20] def array_id(x): x = np.ascontiguousarray(x, dtype=np.float32) return hashlib.sha1(x.tobytes() + str(x.shape).encode()).hexdigest()[:20] def _ffmpeg_reason(err): """the last meaningful line of ffmpeg's stderr, without its [component @ 0x...] prefix, on one line""" import re lines = [re.sub(r'^\[[^\]]*@ [0-9a-fA-Fx]+\]\s*', '', ln).strip() for ln in err.splitlines()] lines = [ln for ln in lines if ln and not ln.lower().startswith(('error opening output', 'conversion failed'))] return (lines[-1] if lines else 'ffmpeg failed')[:200] def _decode(path, sr, ch): up = ch == 2 and _src_channels(path) == 1 # ffmpeg would upmix mono at -3 dB; duplicate at unity instead p = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-i', path, '-vn', '-f', 'f32le', '-acodec', 'pcm_f32le', '-ac', '1' if up else str(ch), '-ar', str(sr), '-'], capture_output=True) err = p.stderr.decode(errors='replace') if p.returncode != 0 or not p.stdout: pr = probe(path) if not pr.get('probe_error') and pr.get('has_video') and not pr.get('codec'): raise AudioError(f'{path} has no audio track (a silent render? mux the soundtrack in first)') if p.returncode == 0 or 'does not contain any stream' in err: raise AudioError(f'{path}: no audio stream') raise AudioError(f'cannot decode {path}: {_ffmpeg_reason(err)}') x = np.frombuffer(p.stdout, np.float32).copy() if up: return np.repeat(x[:, None], 2, axis=1) return x.reshape(-1, ch) if ch > 1 else x def load(path, sr=SR, mono=False, start=None, end=None, cache=True): """decode `path` to float32 (n, 2) or (n,) when mono; optional [start, end) in seconds""" if not os.path.exists(path): raise AudioError(f'no such file: {path}') ch = 1 if mono else 2 x = None npy = None if cache: config.ensure_dirs() npy = os.path.join(config.DEC_CACHE, _key(path, sr, ch) + '.npy') if os.path.exists(npy): try: x = np.load(npy) except Exception: x = None if x is None: x = _decode(path, sr, ch) if npy: tmp = f'{npy}.{os.getpid()}.tmp.npy' np.save(tmp, x) replace_quietly(tmp, npy) bad = ~np.isfinite(x) if bad.any(): # one NaN / Inf sample breaks every analysis downstream (#12) bad = bad.any(axis=-1) if x.ndim == 2 else bad raise AudioError(f'{path}: {int(bad.sum())} NaN / Inf sample(s), first at {int(np.argmax(bad)) / sr:.3f} s: ' 'the file is corrupt or the code that made it divided by zero') if start is not None or end is not None: a = max(0, int(round((start or 0.0) * sr))) b = len(x) if end is None else min(len(x), int(round(end * sr))) x = x[a:b] return x def to_mono(x): return x.mean(axis=1) if x.ndim == 2 else x def resample(x, sr_from, sr_to): if sr_from == sr_to: return x import soxr return soxr.resample(x, sr_from, sr_to, quality='HQ').astype(np.float32) def duration(path): return len(load(path, mono=True)) / SR def probe(path): """ffprobe summary: codec, sample rate, channels, kbps, duration, has_video""" try: out = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'stream=codec_type,codec_name,sample_rate,channels,bit_rate,width,height,r_frame_rate:' 'stream_disposition=attached_pic:' 'format=duration,bit_rate', '-of', 'json', path], capture_output=True, text=True, timeout=60).stdout j = json.loads(out or '{}') except Exception as e: # noqa: BLE001 return {'probe_error': str(e)[:200]} streams = j.get('streams') or [] a = next((s for s in streams if s.get('codec_type') == 'audio'), {}) v = next((s for s in streams if s.get('codec_type') == 'video' and not (s.get('disposition') or {}).get('attached_pic')), None) # cover art is not a picture track fmt = j.get('format') or {} br = a.get('bit_rate') if not (br and str(br).isdigit() and int(br) < 10_000_000): # Vorbis can report 2^32-1: use the container's rate br = fmt.get('bit_rate') if not v else None res = {'codec': a.get('codec_name'), 'src_rate': int(a.get('sample_rate') or 0), 'channels': int(a.get('channels') or 0), 'kbps': round(int(br) / 1000) if br and str(br).isdigit() else None, 'lossy': a.get('codec_name') in LOSSY, 'duration': round(float(fmt.get('duration') or 0), 3), 'has_video': v is not None} if v is not None: num, _, den = (v.get('r_frame_rate') or '0/1').partition('/') res['video'] = {'width': v.get('width'), 'height': v.get('height'), 'fps': round(float(num) / float(den or 1), 3) if float(den or 1) else None} return res def windows(x, win, hop, sr=SR, pad_last=False): """[(t0_seconds, segment)] over the first axis""" n, w, h = len(x), int(round(win * sr)), int(round(hop * sr)) out = [] if n <= w: return [(0.0, x)] for s in range(0, n - w + 1, h): out.append((s / sr, x[s:s + w])) if pad_last and (n - w) % h: out.append(((n - w) / sr, x[n - w:])) return out def list_media(paths, recursive=True, exts=MEDIA_EXTS): """expand files / folders / glob results into a sorted list of media files""" if isinstance(paths, str): paths = [paths] out = [] for p in paths: if os.path.isdir(p): for root, dirs, files in os.walk(p): dirs.sort() for f in sorted(files): if os.path.splitext(f)[1].lower() in exts: out.append(os.path.join(root, f)) if not recursive: break elif os.path.isfile(p): out.append(p) else: import glob out += sorted(g for g in glob.glob(p, recursive=True) if os.path.isfile(g) and os.path.splitext(g)[1].lower() in exts) seen, res = set(), [] for p in out: k = os.path.normcase(os.path.abspath(p)) if k not in seen: seen.add(k) res.append(p) return res def check_paths(paths, what='paths'): """raise AudioError naming every given path that yields no media file (a typo must not vanish from a batch)""" paths = [paths] if isinstance(paths, str) else list(paths or []) bad = [f"{p} ({'no such file or folder' if not os.path.exists(p) else 'no audio or video files in it'})" for p in paths if not list_media([p])] if bad: raise AudioError(f'{what}: nothing playable in ' + ', '.join(bad[:5]) + (' ...' if len(bad) > 5 else '')) def db(v, floor=1e-12): return float(20 * np.log10(max(float(v), floor))) - earshot/brief.py (143028 bytes)
"""Read a request for a sound, and find the designs that answer it. from earshot import brief b = brief.read('a soft wooden success chime for a finance app, 400 ms, in D') # {'concepts': ['success', 'bell'], 'axes': {'hard': -0.5, 'energy': -0.3}, 'material': 'wood', 'domain': 'ui', # 'dur': 0.4, 'key': 'D', ...} brief.rank(b)[:3] # [{'id': ..., 'score': ..., 'why': [...]}, ...] A request names a job ("success", "coin pickup", "logo reveal") or a sound ("chime", "whoosh", "rain"), often both, plus how it should feel ("soft", "bigger", "not harsh"), what it is made of or played by ("wooden", "on a kalimba", "8-bit"), where it plays ("for a platformer") and hard numbers (length, pitch, key, how many). `read` separates those with the tables in earshot.sounds.lexicon, without any model: - jobs and sounds become canonical words, the longest phrase first ("level complete" before "complete"), articles inside a phrase skipped ("beat the level" = "beat level"); - the first one named is the head of the request; what follows "with" describes a part of it ("a bell with an airy whoosh") and what follows "for", "when", "during" ... once the head is named is its context (where it plays): both count less; - the app, site, store or video it plays in ("in my running app, a success sound", "piano lessons website hover sound") names no sound once the request names one outside it; with nothing else named its words count as ever; - "like a ..." is a comparison, not the job "like"; what follows "than" is a reference and is skipped; "the opposite of X" and "X but the other way" turn X into its opposite; - negations flip adjectives ("not harsh") and turn a named job into one to avoid ("not an error"); - adjectives become offsets on the shared axes (intensifiers scale them) and hints that break ties in a family; - an instrument named as the thing itself ("a kalimba note", "marimba hit") is asked for as a note of that voice, one named as the player ("a chime on a kalimba", "a bass boom") only sets the voice; - "rising", "falling" ... give the direction of the gesture; "8-bit", "retro" ... make chip sound a hard filter; - words nothing knows are returned as `unknown` and count only a little. `rank` scores every design by what it shares with the request: a design's jobs (`uses`) count most, then its name, then how it is described (`says`) and tagged; rare words count more than common ones (idf), the design's own family job gets a bonus, and the result is scaled by the design's prior, the domain, material, loop, length and direction. `why` names the words that decided. `rank(b, semantic=atlas.zmap(text))` blends in how much each design sounds like the request (earshot.sounds.atlas, CLAP; `blend`): a named job keeps its lexical winner, a request that only describes a sound is decided by the sound, and the hard filters (chip sound, loop, a job ruled out) still hold. """ import json import math import os import re from .sounds import lexicon as L NOTE = re.compile(r'(?<![A-Za-z0-9#])([A-Ga-g])([#b]?)(-?\d)(?![A-Za-z0-9])') HZ = re.compile(r'(\d+(?:\.\d+)?)\s*(k?hz)\b', re.I) DUR = re.compile(r'(?<![\w.-])(\d+(?:\.\d+)?)\s*(ms|msec|milliseconds?|s|sec|secs|seconds?|min|minutes?|h|hrs?|hours?)' r'\b', re.I) # "200 ms apart", "0.2 seconds between each": the time from one event of a row to the next, not the file's length GAP = re.compile(DUR.pattern + r'\s+(?:apart|between\s+(?:each|them|every))\b', re.I) LIMIT = re.compile(r'\b(under|below|less than|at most|max|maximum|no longer than|within|up to|shorter than|tops)\s*$', re.I) NUMBER_WORDS = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10, 'eleven': 11, 'twelve': 12, 'a couple of': 2, 'a few': 3, 'several': 4} COUNT = re.compile(r'\b(\d+|' + '|'.join(NUMBER_WORDS) + r')\s+(?:different\s+|unique\s+)?' r'(?:variations?|variants?|versions?|takes?|options?|alternatives?)\b', re.I) FIGURE = re.compile(r'\b(one|two|three|four|five|\d)-(note|tone|step|pulse|beat)s?\b', re.I) KEY = re.compile(r'\b(?:in|key of|in the key of)\s+([A-G][#b]?)(?:[\s-]*(major|minor|maj|min))?(?![A-Za-z0-9#])') # a word is letters (also accented ones: "für" is one word, not "f" and "r"), digits and '#' WORD = re.compile(r"[a-z0-9#ßà-öø-ÿ]+(?:[-'][a-z0-9#ßà-öø-ÿ]+)*") TOKEN = re.compile(r"[a-z0-9#ßà-öø-ÿ]+(?:[-'][a-z0-9#ßà-öø-ÿ]+)*|[,.;:!?()]") PUNCT = frozenset(',.;:!?()') LOOP_WORDS = ('loop', 'looping', 'loopable', 'seamless', 'looped', 'endless') ONCE_WORDS = ('one-shot', 'oneshot') CONTEXT_WORDS = ('for', 'when', 'while', 'as', 'after', 'before', 'during', 'whenever', 'once', 'where', 'until', 'whilst', 'if', 'into') # "a whoosh into the logo": where it lands PLACE_WORDS = ('in', 'under', 'over', 'across', 'behind', 'beneath', 'inside') # a sound that tells something ("a ring that says the eggs are done"): what follows is what it means, not its sound MEANING_WORDS = ('says', 'say', 'tells', 'tell', 'means', 'signals', 'announces', 'lets') ROOM_WORDS = ('room', 'door', 'apartment', 'flat', 'house', 'office', 'building', 'cell', 'cabin') # a sound that moves between the speakers ("a car passing from left to right"): read into b['pan'] PAN = re.compile(r'\b(?:from (?:the )?(?:left|right) to (?:the )?(?:left|right)|(?:left|right) to (?:left|right)' r'|panning|panned|pans|(?:from|on|to) the (?:left|right)(?: side)?|in stereo)\b') # the place or product a sound plays in ("my running app", "a coffee shop checkout", "a video about dogs"): the # words of that phrase say where it plays, not what it is, once the request names its sound elsewhere (`_settings`). # A game is not one of them: its world shapes the sound ("an impact in a boxing game" is a punch) SETTING_WORDS = frozenset(('app', 'apps', 'webapp', 'site', 'website', 'webpage', 'homepage', 'page', 'dashboard', 'panel', 'screen', 'store', 'shop', 'checkout', 'platform', 'tool', 'brand', 'channel', 'podcast', 'video', 'reel', 'trailer', 'presentation', 'menu', 'widget', 'tab', 'tracker', 'inbox')) # places that also name a part of a thing ("a shop door", "screen time", "a panel slide"): they end the phrase only # where nothing but a sound word or the end of a clause follows SETTING_LOOSE = frozenset(('screen', 'store', 'shop', 'panel', 'menu')) SETTING_TOPIC = ('video', 'reel', 'trailer', 'podcast', 'channel', 'presentation') # "a video about dogs" # the phrase begins the request or a clause, or follows one of these ("for my app", "the menu of a website") SETTING_OPEN = ('for', 'in', 'on', 'inside', 'within', 'at', 'of', 'from') SETTING_BREAK = ('with', 'to', 'about', 'by', 'than', 'like', 'but') # these end a phrase that is no place # words whose ending is not an ending ('evening' is not 'even', 'string' is not 'str') STEM_KEEP = frozenset(('evening', 'morning', 'ceiling', 'string', 'strings', 'thing', 'things', 'ring', 'rings', 'spring', 'springs', 'swing', 'sling', 'wing', 'wings', 'king', 'bring', 'during', 'nothing', 'something', 'anything', 'everything', 'bus', 'gas', 'news', 'lens', 'chaos', 'canvas', 'tape', 'tapes', 'setting', 'settings', 'paste', 'pasted', 'cute')) # (a tape is no tap, a setting no set, paste no past, cute no cut) # a figure's shape in any words: "two-tone", "two-pulse", "two quick notes", "twice" -> '2-note' FIGURE_TEXT = re.compile(r'\b(one|two|three|four|five|six|seven|\d)(?:-(?:note|tone|step|pulse|beat)s?\b' r'|(?:\s+[a-z]+){0,2}\s+notes\b)', re.I) ARTICLES = frozenset(('a', 'an', 'the', 'my', 'our', 'your', 'their', 'some', 'this', 'that', 'its', 'his', 'her')) LIKE_JOB_NEXT = ('button', 'buttons', 'sound', 'tap', 'icon', 'animation', 'reaction', 'count', 'counter', 'feedback', 'click', 'action', 'and') VOICE_PARAM_PREV = ('on', 'by', 'played', 'using', 'with', 'via', 'through') # the sounds an instrument itself makes: "a piano key", "a bass note", "a bell ding" ask for a note of the voice VOICE_OK = frozenset(('note', 'bass', 'piano', 'pluck', 'bell', 'beep', 'knock', 'hit', 'tap', 'cue')) HYPHEN_SUFFIX = ('like', 'ish', 'style', 'styled', 'esque', 'type', 'themed', 'y') OTHER_WAY = ('other way', 'the other way', 'opposite way', 'reverse direction', 'other direction') TOGGLE_ON_NEXT = ('in', 'for', 'at', 'when', 'with', 'and', 'sound', 'click', 'snap', 'state', 'mode') SCOPE_END = ('sound', 'sounds', 'noise', 'noises', 'thing', 'effect', 'sfx', 'but') # after one of these a request that has named its sound says what it happens on or in: a surface, a ground, a # material or a place ("rain ON wood", "footsteps IN mud", "a ball AGAINST a wall"), never another thing to make SURFACE_WORDS = ('on', 'onto', 'upon', 'against', 'in', 'into') # the words that end the phrase a request names its own sound with ("a cat hissing | at a dog") HEAD_END = frozenset(CONTEXT_WORDS + PLACE_WORDS + ( 'on', 'onto', 'upon', 'against', 'with', 'at', 'from', 'through', 'by', 'to', 'like', 'than', 'but', 'and', 'or', 'near', 'off', 'out', 'then', 'that', 'which', 'between', 'among', 'around', 'along', 'toward', 'towards', 'beside', 'above', 'below', 'within', 'outside', 'past', 'aside', 'sideways', 'away', 'together', 'apart', 'plus')) # endings of a word that describes or says what was done: an unknown word with one at the end of the phrase is no # thing ("something squishy", "a cork pop followed by fizz"); what a thing is doing keeps its -ing ("a cat hissing") DESCRIBING = ('y', 'ed', 'ish', 'ful', 'ous', 'al', 'ic', 'ive', 'less', 'able', 'ible', 'ly', 'est') THING_ENDS = ('ey', 'way', 'ory') # endings in -y of things: "a monkey", "a subway", "a factory" # German articles that are no English words: with one of them, a request whose every word is in lexicon.GERMAN is # German even when each word is English too ("ein lauter Donner"; brief.german) GERMAN_ARTICLES = frozenset(('ein', 'eine', 'einen', 'einem', 'einer', 'der', 'das', 'dem', 'des', 'im', 'vom', 'zum', 'zur', 'und')) PARTICLES = frozenset(('over', 'by', 'past', 'away', 'off', 'up', 'down', 'in', 'out', 'around')) # "flying OVER" def describes(w): """True when a word ends as one that describes (DESCRIBING: "squeaky", "windy") and not as a thing does (THING_ENDS)""" return w.endswith(DESCRIBING) and not w.endswith(THING_ENDS) QUOTED = re.compile(r"(?:^|[\s(])['\"‘“](.+?)['\"’”](?=[\s,.!?)]|$)") # words said as a caption: 'you did it!' # weights of the query's parts and of the fields of a design HEAD_WEIGHT, CONCEPT_WEIGHT, PART_WEIGHT, CONTEXT_WEIGHT, BROADER_WEIGHT, REF_WEIGHT = 1.0, 0.8, 0.6, 0.5, 0.4, 0.25 WORD_WEIGHT, HINT_WEIGHT, AXIS_WEIGHT, SAID_WEIGHT = 0.6, 0.35, 0.12, 0.005 FIELD_WEIGHT = {'uses': 3.0, 'name': 2.2, 'says': 1.6, 'tags': 1.2} # the design's own family named in the request (by its very name: + EXACT_BONUS); its first job FAMILY_BONUS, EXACT_BONUS, FIRST_USE_BONUS = 1.2, 0.3, 0.6 CONCEPT_IDF = 0.6 # how much rarity counts for canonical words (1 = as for plain words) STRETCH_KINDS = ('bed', 'pad', 'texture') # rendered at any length asked for LENGTH_SLOPE = 0.15 # how much a length mismatch costs per octave beyond the free half octave # the blend of the lexical score with the semantic z (`blend`; chosen on eval/requests.json + requests_b.json) LEX_FLOOR, LEX_POWER, SEM_WEIGHT, Z_FLOOR, Z_SAYS = 1.0, 0.25, 0.4, -1.0, 2.5 MEMBER_SHARE = 0.8 # how close a member named in the request must score to the family's best # the same for a named design of another family found by the very same words, of the same kind ("tape stop": # downlifter/tape at 0.77 of fall/air, the downlifter concept's default) KIN_SHARE = 0.7 UNNAMED_LEX = 0.25 # the most a lexical score counts in the blend when no job or sound word matched # the tonal interface figures a plain request no longer gets (lexicon.BY_NAME_ONLY): their score is multiplied by # this unless the request asks for a tone ("a tonal tap", "a tap with a note in it") BY_NAME = 0.5 # a learned design whose interface job (its `roles`) is the request's head: a plain "tap", "hover", "toggle on", # "next", "type" gets the recorded tap, tick, switch or key chosen for that job (earshot.sounds.sets 'ui') ROLE = 2.0 # the sound of a real thing chosen for an interface job (lexicon.INTERFACE_JOBS), for a request of that job without # musical words: the pitched figures step back by BY_NAME, so this only needs to win among its own alternatives and # things that merely share a word; outside an interface job these designs step back by BY_NAME ("a knock cue when a # guest arrives" is a door knocked on, "a capture button" a camera's shutter) REAL = 1.4 # an interface design (earshot.sounds.interface) for a request that is not an interface job: what it is made of ("a # door closing" is door/shut, not the interface's close/door) WORLD = 0.2 _rev = None _cache = {} IRREGULAR = {'mice': 'mouse', 'geese': 'goose'} # plurals no ending rule reaches def stem(w): """a word without its plural or verb ending and a final e or doubled consonant (a crude stemmer: enough to match 'chimes', 'chiming', 'popped', 'rising' / 'rise')""" w = w.lower() if w.endswith("'s"): w = w[:-2] if w in STEM_KEEP: return w if w in IRREGULAR: w = IRREGULAR[w] # 'mice' is a mouse, 'geese' a goose for end, keep in (('sses', 'ss'), ('ies', 'y'), ('ied', 'y'), ('ing', ''), ('ed', ''), ('es', ''), ('s', '')): if (w.endswith(end) and len(w) - len(end) >= 3 and not (end == 's' and w.endswith(('ss', 'us', 'is'))) and not (end == 'ed' and w.endswith('eed'))): w = w[:len(w) - len(end)] + keep if end in ('ing', 'ed') and len(w) >= 6 and w.endswith('ell'): w = w[:-1] # British doubling: 'levelling', 'cancelled' (not 'spelling') break if len(w) > 3 and w.endswith('e') and not w.endswith(('ee', 'ie')): w = w[:-1] if len(w) > 3 and w[-1] == w[-2] and w[-1] not in 'slz' and w[-1].isalpha(): w = w[:-1] return w # a request that says one of these asks for a tone: the tonal interface figures answer it (BY_NAME) TONE_STEMS = frozenset(stem(w) for w in ('tone', 'tonal', 'note', 'musical', 'melodic', 'pitched', 'chime', 'marimba')) # a request that says one of these (or names an instrument, a voice, or music as its domain) asks for music: only then # does an interface job get a pitched design (lexicon.INTERFACE_JOBS); otherwise it gets the sound of a real thing MUSIC_STEMS = TONE_STEMS | frozenset(stem(w) for w in ( 'notes', 'melody', 'jingle', 'arpeggio', 'arpeggiated', 'tune', 'tuneful', 'instr - earshot/build.py (93129 bytes)
"""earshot build: the workbench on which a sound the catalogue lacks is built from its recorded parts, with earshot as the ears. earshot build "hail on a tin roof" -o hail.wav # draft, render, hear, tune: hail.wav, hail.recipe.json earshot build "a whale singing" --recipe whale.json # your own recipe: render it, hear it, say what is off earshot build "a stampede" --rounds 40 --without step/gravel rain --json from earshot.build import build, draft, hear, tune build('hail on a tin roof', out='hail.wav')['summary'] Four steps, each its own call: draft(words) one to three first recipes (earshot.recipe) from the words alone, without a language model. The reader (earshot.brief) says what the thing is and what it does; the words choose a structure: one event, a row of events, very many small events (`scatter`: rain, hail, applause, a swarm), something that runs (a bed that turns: `spin`), something that passes (`pass`), a creature's voice (moved in pitch, `bend`), something drawn out (`stretch`), something made up (a reversed swell into a hit, air), or a place (two or three beds). The parts are the recorded designs nearest to the words and to each thing they name: by the listening model's text-to-audio atlas when the listen extra is installed, by the reader's ranking otherwise; never an instrument, a note or a synthesized design. A cookbook recipe of the thing is the first draft. `without` forbids designs (an id) or whole families (a family name). hear(recipe, words) renders and says in plain lines what an agent can act on: clean or what the audit found; length, where the hit is, how bright and how dense, against what the words ask and against the nearest real design of the catalogue; with the listen extra also what it is heard as (the nearest designs by sound, the nearest words), its fit to the words as a z beside the z of the design `make` would hand over (the verdict: "sounds like it" when clean, z >= 3.0 and at least 1.0 over that design; else "a sketch"), recorded or synthesized (earshot.realness), a steady tone heard as a note, and per layer what it adds (the fit with the layer left out). Every remark names the field of the recipe to change. tune(recipe, words, rounds) keeps the structure and moves the numbers (gain, pitch, cutoffs, at, rates, depths, lengths) within the ranges earshot.recipe checks, by a seeded search: each round changes one or two numbers, renders, hears once and keeps the change when the score rises. The score is the fit to the words minus penalties: not clean, heard as synthesized, a steady tone, far from the length asked. The same seed gives the same result. Without the listen extra it can only keep the sound clean and near the length. build(words) draft, hear the drafts, tune the best, hear it again; writes the sound and the recipe beside it. The listening model only judges; nothing here generates audio with a model. Every sound is the catalogue's own designs (most of them learned from public-domain recordings) layered, moved and placed by the recipe. """ import copy import json import math import os import re import time from . import brief, recipe as R ROUNDS = 20 # tuning rounds of a default build: a render and one embedding each SEED = 0 GOOD_Z = 3.0 # the fit a sound needs to be heard as its words (match.VERDICTS 'strong') OVER = 1.0 # and its lead over the design `make` would hand over PLAYED = {'synth', 'instrument', 'tonal', 'chip', '8-bit', 'arcade', 'retro', 'glitch', 'drums', 'kit', 'music'} PLAYED_KINDS = {'note', 'chime', 'figure', 'music', 'pad', 'stinger'} PLAYED_FAMILIES = {'braam', 'brass', 'strings', 'piano', 'guitar', 'organ', 'choir'} # played, whatever the tags say BED_S = 4.0 # a scatter, a running thing or a place is drafted this long when the words give no length # (long enough to hear it, short enough for a round of tuning to stay quick) STRUCTURES = ('one', 'row', 'scatter', 'run', 'pass', 'voice', 'long', 'magic', 'place') # words that say what kind of sound a request is, by structure; the first structure in ORDER whose words the # request holds is drafted first WORDS = { 'magic': 'magic magical spell spells portal force field energy laser plasma teleport teleporting shield alien ' 'scifi sci fi spaceship ufo warp hologram enchanted cursed ghost ghostly phaser beam charging', 'pass': 'passing pass passes past flyover flying overhead by zooming zooms whizzing whizzes driving', 'place': 'ambience ambient atmosphere atmo tone city street forest jungle beach market office cafe restaurant ' 'station village park underwater cave harbour harbor countryside room', 'scatter': 'rain raining hail hailstorm drizzle sleet pouring crackle crackling crackles fizz fizzing sizzle ' 'sizzling applause clapping crowd swarm bees insects marbles popcorn stampede rustle rustling ' 'chattering bubbling bubbles shower confetti hooves herd gravel pebbles coins clatter clattering flock ' 'pack pile shoal hundreds thousands', 'run': 'motor engine machine fan drill mower lawnmower blender hum humming idle idling running runs treadmill ' 'generator compressor pump turbine printer conveyor saw grinder vacuum washing spinning whirring ' 'rotor helicopter propeller wheel modem projector', 'voice': 'roar roaring growl growling howl howling call calling song singing sings moo mooing bark barking cry ' 'crying screech screeching whimper whimpering squeal squeak squeaking chirp chirping purr ' 'croak croaking snort grunt grunting bleat neigh whinny bray braying hoot hooting yelp trumpeting', 'row': 'steps footsteps stomping stomp knocking knocks hammering ticking clockwork typing dripping clicking ' 'galloping gallop chopping sawing marching tapping', 'long': 'slowly slow drawn creaking creak groan groaning stretching sinking', } ORDER = ('magic', 'pass', 'place', 'scatter', 'run', 'voice', 'row', 'long') # many of one thing: a collective word and the rate a second its single events come at; the thing is what follows # "of" ("a stampede of horses": horses), or the single event of the word itself (applause: a clap) COLLECTIVE = {'stampede': 30.0, 'herd': 12.0, 'flock': 8.0, 'swarm': 30.0, 'crowd': 20.0, 'shower': 25.0, 'hail': 40.0, 'pile': 12.0, 'pack': 1.5, 'shoal': 15.0, 'cloud': 30.0, 'rain': 30.0, 'applause': 40.0, 'hundreds': 40.0, 'thousands': 80.0, 'dozens': 15.0} SINGLE = {'stampede': 'hooves galloping', 'herd': 'hooves', 'applause': 'a clap', 'swarm': 'a buzz', 'hail': 'a hailstone'} OF = re.compile(r'\b(?:a|an|the)?\s*(' + '|'.join(COLLECTIVE) + r')\s+of\s+([a-z][a-z\s-]*)') SAID = re.compile(r'\b(' + '|'.join(COLLECTIVE) + r')\b') # words between the collective's thing and what the request goes on to say ("a pile of plates falling over") THEN = re.compile(r'\s+(?:falling|falls|fall|running|flying|over|on|in|at|across|into|onto|through|with|and)\b.*$') def collective(words): """(the single thing, its rate a second) when the words ask for many of one thing, else None: "a stampede of horses" -> ("horses", 30), "applause" -> ("a clap", 40)""" low = (words or '').lower() m = OF.search(low) if m: thing = THEN.sub('', m.group(2)).strip() if m.group(1) in SINGLE: thing = f'{thing} {SINGLE[m.group(1)]}' return thing or SINGLE.get(m.group(1), m.group(1)), COLLECTIVE[m.group(1)] m = SAID.search(low) if m and m.group(1) in SINGLE: return SINGLE[m.group(1)], COLLECTIVE[m.group(1)] return None # a steady tone heard as a note (earshot.realness.signal_features): nearly every frame one line, most of the energy in # a few lines, a level that hardly moves; a creature's call drifts and breathes and stays under it TONE = {'frames': 0.9, 'lines': 0.75, 'crest': 12.0} # the second ear (the AudioSet tagger) in hear's verdict: its top labels, those shown, the labels that are clearly # another kind of sound than a thing of the world, and how sure it must be of one to take a verdict back SECOND_K = 10 SHOWN = 4 OTHER = {'Music', 'Musical instrument', 'Speech', 'Synthesizer', 'Sine wave', 'Beep, bleep', 'Silence', 'Electronic music', 'Ringtone', 'Narration, monologue', 'Singing', 'Male speech, man speaking', 'Female speech, woman speaking', 'Song', 'Theme music', 'Electronic tuner', 'Dial tone', 'Busy signal', 'Piano', 'Guitar', 'Organ', 'Electronic organ', 'Keyboard (musical)', 'Bell', 'Chime', 'Tuning fork'} SPOKEN = {'Speech', 'Narration, monologue', 'Male speech, man speaking', 'Female speech, woman speaking', 'Singing'} VOICED = {'voice', 'speak', 'speaking', 'talk', 'talking', 'whisper', 'whispering', 'sing', 'singing', 'man', 'woman', 'child', 'children', 'people', 'person', 'crowd', 'chatter', 'chattering', 'shout', 'shouting', 'someone'} OTHER_P = 0.3 # what a thing does, which names a tagger class of its own that is not the thing ("running": Run, "singing": Singing) ACTS = {'running', 'opening', 'singing', 'moving', 'playing', 'working', 'falling', 'rolling', 'climbing', 'apart'} # words too general to tie a tagger class or a design to the thing GENERIC = {'sound', 'sounds', 'noise', 'effect', 'small', 'large', 'big', 'giant', 'low', 'high', 'old', 'new', 'soft', 'loud', 'long', 'short', 'and', 'the', 'over', 'from', 'with', 'into', 'onto', 'moving', 'making'} BIG = {'giant', 'huge', 'big', 'enormous', 'massive', 'whale', 'monster', 'deep', 'heavy', 'colossal', 'titan'} SMALL = {'tiny', 'small', 'little', 'mini', 'baby', 'mouse', 'bird', 'chick', 'fairy', 'toy'} # ------------------------------------------------------------------------------------------------------------ parts def _family(sid): return sid.split('/')[0] def _forbidden(sid, without): """True when `without` names the design itself or its family""" return sid in without or _family(sid) in without def _real(row): """a design that is a recording of a thing of the world (learned or tagged real) and not played music""" tags = set(row.get('tags') or ()) return (('real' in tags or row['id'] in brief._roles()) and not tags & PLAYED and row['kind'] not in PLAYED_KINDS and _family(row['id']) not in PLAYED_FAMILIES) def _without(without): if not without: return frozenset() if isinstance(without, str): without = re.split(r'[,\s]+', without) return frozenset(w.strip().strip('/') for w in without if w and w.strip()) def _content(text): return [w for w in brief.WORD.findall((text or '').lower()) if w not in brief.L.STOP and len(w) > 2] def _phrases(b, words): """the parts of a request to find material for, each with its weight: the whole, the single thing of a collective ("a stampede of horses": horses), the thing it names, what it happens on, and each content word on its own; a word that only qualifies the next one ("fire" in "a fire alarm") counts less than the head""" out = [(words, 1.0)] many = collective(words) if many: out.append((many[0], 1.0)) sur = b.get('surface') or {} if sur.get('of'): out.append((sur['of'], 0.8)) if sur.get('words'): out.append((' '.join(sur['words']), 0.8)) if b.get('absent'): out.append((b['absent'], 0.8)) toks = brief.WORD.findall((b.get('text') or words).lower()) content = set(_content(b.get('text') or words)) for j, w in enumerate(toks): if w in content: # a compound of two nouns ("fire alarm"): the second is the thing; a noun and what it does ("lion # growling") stay equal modifier = j + 1 < len(toks) and toks[j + 1] in content and not toks[j + 1].endswith('ing') head = not modifier and j > 0 and toks[j - 1] in content and not many and not w.endswith('ing') out.append((w, 0.6 if modifier else 0.9 if head else 0.8)) seen, res = set(), [] for p, wt in out: if p and p.strip() and p not in seen: seen.add(p) res.append((p, wt)) return res def candidates(words, without=(), ears=None, k=12): """the recorded designs nearest to a request, best first: [{'id', 'score', 'for', 'kind', 'dur', 'loop'}], at most one design of a family; each found for the whole request or for one of its parts (`for`). With ears, the listening model's atlas scores them (how each design sounds and is described against the words), else the reader's ranking does""" from .sounds import registry without = _without(without) b = brief.read(words) rows = {r['id']: r for r in registry.rows()} ok = {i for i, r in rows.items() if _real(r) and not _forbidden(i, without)} best = {} phrases = _phrases(b, words) for ph, weight in phrases: if ears is not None: try: zs = ears.atlas_z(ph) except Exception: # noqa: BLE001 (no atlas: the reader ranks) zs = None else: zs = None if zs is None: cands = brief.rank(brief.read(ph), top=40) top = max((c['score'] or 0.0) for c in cands) if cands else 0.0 zs = {c['id']: 3.0 * (c['score'] or 0.0) / top for c in cands if top > 0} for sid, z in zs.items(): if sid in ok: s = weight * float(z) if s > best.get(sid, (-9.0, ''))[0]: best[sid] = (s, ph) out, fams = [], set() for sid, (s, ph) in sorted(best.items(), key=lambda kv: (-kv[1][0], kv[0])): if _family(sid) in fams: continue fams.add(_family(sid)) r = rows[sid] out.append({'id': sid, 'score': round(s, 2), 'for': ph, 'kind': r['kind'], 'dur': r['dur_s'] or 0.5, 'loop': bool(r['loop'])}) if len(out) >= k: break return out # ------------------------------------------------------------------------------------------------------- structure def structure(words): """the kind of sound a request is (STRUCTURES): what its words say, then how many events it asks for""" b = brief.read(words) said = set(brief.WORD.findall((b.get('text') or words).lower())) if collective(words) and not said & set(WORDS['magic'].split()): return 'scatter' for s in ORDER: if said & set(WORDS[s].split()): if (b.get('events') or 0) > 1 and s in ('voice', 'long', 'magic'): return 'row' # - earshot/cli.py (8995 bytes)
"""earshot command line. Every subcommand lives in its own module, which exposes add_cli(subparsers). earshot [--threads N] <command> [args] [--json] [--out result.json] [--threads N] Run `earshot -h` for the list and `earshot <command> -h` for details. Only the module of the requested command is imported (fast start); `-h` imports them all to list them. Errors: one line on stderr, 'earshot <command>: error: ...', exit 1 (with --json, describe / match / rank / find / compare / ab also print it as JSON on stdout). """ import argparse import contextlib import importlib import os import sys # command -> module (order = order in --help) COMMANDS = { 'make': 'make', # make a sound from a request in words, or a whole set from a spec 'sounds': 'make', # the catalogue of sounds make can make 'recipe': 'recipe', # sounds the catalogue lacks, built from its parts: the form, the cookbook 'build': 'build', # build a sound the catalogue lacks: draft, render, hear, tune 'pack': 'pack', # many sounds in one file with a map (an audio sprite) 'describe': 'describe', # what does this sound like? tags + measurements 'match': 'match', # how well does a sound match a text description (calibrated) 'rank': 'search', # rank many files by a description 'find': 'search', # find the best moments inside a long recording (sample trims) 'compare': 'compare', # similarity to reference recordings 'ab': 'compare', # A/B two sounds 'realness': 'realness', # real recording vs code-synthesized sound 'timeline': 'timeline', # listen through a whole soundtrack or film: events, tags, sync, loudness 'sheet': 'sheet', # annotated picture of a soundtrack (spectrogram + events + frames) for agents with eyes 'critique': 'critique', # launch-video sound scorecard against a profile of professional references 'profile': 'profile', # build a reference profile from your own reference films 'forge': 'forge', # make sounds in code and improve them by listening 'fit': 'forge.fit', # translate a recording into code (analysis by synthesis) and vary it 'sfx': 'forge.sfx', # one sound of the shipped bank by id, aimed at the picture; audit any sound effect 'kit': 'forge.kit', # a film's sound kit: one bank sound per role, rendered to takes with sync points 'gallery': 'gallery', # one static HTML page of forge results: players, spectrograms, numbers 'measure': 'features', # objective measurements only (no models) 'llm': 'llm', # optional audio-LLM critique (only with your own API key + consent) 'mcp': 'mcp_server', # run earshot as an MCP server for coding agents 'doctor': 'doctor', # check the install, models and CPU settings } def _parser(): ap = argparse.ArgumentParser(prog='earshot', description='earshot makes sound effects from a request in words ' '(make, sounds, recipe, pack; no model, no network) and listens to sound files for ' 'you: describe, match, rank, find, compare, realness, timeline, sheet, critique and ' 'measure (the listening commands need the listen extra).') ap.add_argument('--threads', type=int, help='CPU threads for torch and BLAS (default: EARSHOT_THREADS or ' 'min(4, cores/2))') ap.add_argument('--version', action='version', version=_version()) return ap def _version(): from . import __version__ return f'earshot {__version__}' def _hold_blas(argv): """numpy and scipy each bundle an OpenBLAS that starts a worker thread per logical CPU and, on Windows, commits a buffer for each when first imported: ~0.4 GB per process on 12 CPUs before any audio is read, ~0.9 GB once a tool has loaded scipy, for no speed-up (the heavy work is torch, already held to EARSHOT_THREADS). Give BLAS the same limit, from --threads or EARSHOT_THREADS, unless OPENBLAS_NUM_THREADS is set. It only counts before numpy is first imported, so main() calls this before any command module loads.""" if 'OPENBLAS_NUM_THREADS' in os.environ or 'numpy' in sys.modules: return n = None for i, a in enumerate(argv): # the last one wins, as in argparse if a == '--threads' and i + 1 < len(argv): n = argv[i + 1] elif a.startswith('--threads='): n = a.split('=', 1)[1] from . import config try: n = int(n or 0) n = n if n > 0 else config.threads() # --threads 0 means the default, as in main() except ValueError: # a bad value: argparse (or the first model load) reports it return os.environ['OPENBLAS_NUM_THREADS'] = str(n) def _register(sub, modules, absent=None): """add the commands of `modules`; return {module: why} for a module that is broken. A module that only lacks an extra (a base install) is no fault: its commands are listed with a note and, when called, say what to install; `absent` collects {module: the plain sentence}""" failed = {} done = set() for mod in modules: if mod in done: continue done.add(mod) try: importlib.import_module(f'earshot.{mod}').add_cli(sub) except Exception as e: # a broken module must not break the others from . import extras said = extras.plain(e) if said is None: failed[mod] = f'{type(e).__name__}: {e}' continue if absent is not None: absent[mod] = said for name in (c for c, m in COMMANDS.items() if m == mod and c not in sub.choices): extra = extras.NEEDS.get(name) or extras.EXTRA.get(getattr(e, 'name', None) or '', ('listen',))[0] p = sub.add_parser(name, help=f'(needs the {extra} extra)', add_help=False) p.add_argument('rest', nargs='*', help=argparse.SUPPRESS) p.set_defaults(func=lambda a, said=said: _absent(said)) return failed def _absent(said): from .extras import MissingExtra raise MissingExtra(said) def _missing_line(cmd, said): """the one-line error of a command whose module needs an extra that is not installed""" from . import extras from .report import error_line try: extras.check(cmd) except extras.MissingExtra as m: said = str(m) error_line(cmd, said) return 1 def main(argv=None): argv = sys.argv[1:] if argv is None else list(argv) _hold_blas(argv) ap = _parser() sub = ap.add_subparsers(dest='command', metavar='<command>') cmd = next((a for a in argv if not a.startswith('-')), None) if '--version' in (argv[:argv.index(cmd)] if cmd in argv else argv): # no command module needs to load print(_version()) return 0 if cmd in COMMANDS: absent = {} failed = _register(sub, [COMMANDS[cmd]], absent) if failed: print(f'earshot: the "{cmd}" command is unavailable: {failed[COMMANDS[cmd]]}', file=sys.stderr) return 2 if absent: return _missing_line(cmd, absent[COMMANDS[cmd]]) else: failed = _register(sub, list(COMMANDS.values())) for m, e in failed.items(): print(f'(earshot: module {m} unavailable: {e})', file=sys.stderr) args = ap.parse_args(argv) if args.threads: os.environ['EARSHOT_THREADS'] = str(args.threads) if not getattr(args, 'func', None): ap.print_help() return 0 if args.command != 'mcp': # a file name outside the console code page must never crash a print with contextlib.suppress(Exception): sys.stdout.reconfigure(errors='backslashreplace') from . import extras try: extras.check(args.command) # a command whose extra is missing says so before it starts return args.func(args) or 0 except Exception as e: # readable one-line errors for agents; EARSHOT_DEBUG=1 shows the traceback if os.environ.get('EARSHOT_DEBUG'): raise from .report import error_line error_line(args.command, extras.plain(e, args.command) or f'{type(e).__name__}: {e}') return 1 def common(p): """flags shared by every command""" p.add_argument('--json', action='store_true', help='print the full result as JSON') p.add_argument('--out', help='also write the JSON result to this file') p.add_argument('--threads', type=int, default=argparse.SUPPRESS, help='CPU threads for torch and BLAS (also accepted before the command; default EARSHOT_THREADS or ' 'min(4, cores/2))') return p if __name__ == '__main__': sys.exit(main()) - INSTRUCTIONS.md (15521 bytes)
--- name: real-sound description: Build premium, realistic soundtracks for code-made videos and animations from real licensed recordings - launch films, product and feature videos, UI walkthroughs, logo stings, explainers, trailers and animated shorts made with Remotion, HyperFrames, three.js, GSAP or any renderer. Use this whenever a video or animation needs sound design, SFX, foley, ambience, music, a soundtrack, a score, UI click / whoosh / riser / impact / logo-sting sounds, or a music edit to picture; whenever a synthesized or "random" sounding soundtrack must be replaced with real recordings; or when the user asks to source, license, credit, mix, master, critique or mux audio for a film. It covers cue lists from the picture, sourcing from Freesound / Mixkit / composer libraries with licence checks, a music edit at bar lines, a JSON sound design rendered by a deterministic mixer, measured QA (clicks, masking, harshness, sync, loudness) plus earshot listening, a multi-agent critique, mastering, credits and the mux. --- # real-sound You are the sound supervisor of a film you cannot hear. The soundtrack is built ONLY from real, professionally recorded or produced audio (one licensed music track, real foley and SFX, real ambiences), placed on the picture's cue frames by a deterministic mixer, measured instead of listened to, critiqued through five lenses, fixed by one agent, mastered, credited and muxed. Code selects, trims, places, levels, pans, EQs, pitches by resampling, time-stretches the music and masters; code never generates a sound. The bar is a professional launch film: every sound caused by something on screen, one material palette, the music's drop on the hero reveal, restraint everywhere else, a resolved logo, a tail into silence. Rules: `references/sound-design.md` (and the earshot repo's `docs/launch-video-sound.md` for the bundled reference profile: 7 professional launch films). `<skill>` below is this folder. **Python:** `{{PY}}` below (and in every prompt template) is ONE interpreter that has numpy, scipy, soundfile and the earshot package: the earshot repo's venv (`<earshot repo>/.venv/Scripts/python.exe` on Windows, `<earshot repo>/.venv/bin/python` elsewhere), or any Python where `<python> -c "import earshot"` works. Bare `python` on Windows is often the Microsoft Store stub and fails. Substitute the full path for `{{PY}}` when you run a command or hand a prompt to a sub-agent (the other placeholders are listed in `references/process.md`). Run the scripts with `-I` (isolated: downloaded files can never shadow a module); every script except `scripts/licences.py` (the licence policy module that audit.py and credits.py import) prints `--help`. ## The process | step | who | output | gate | |---|---|---|---| | 0. cue list | lead | `out/cues.json` | sync frames computed from the picture code | | 1. brief | lead | `audio/SOUND_BRIEF.md` | every cue has a sound need (or "nothing") | | 2. sourcing (per category, parallel) | sourcing agents | `audio/assets/<cat>/`, manifests | each file measured + earshot `realness` "real or pro-produced" on the trim used (an "uncertain" only with its evidence and a trim-level re-check written in the manifest) | | 3. licence audit | auditor | `audit.json` | `audit.py` exit 0 for what the film uses | | 4. music edit | music supervisor | `audio/design/music.json` | grid verified, drop on the reveal, splices clean | | 5. design fragments (per category, parallel) | designers | `audio/design/<cat>.json` | solo render + qa clean | | 6. integrate | lead | soundtrack, stems, report, trace | master gate (+-0.5 LU, <= -1.5 dBTP) | | 7. QA + listening | lead | `out/qa/qa.json`, earshot timeline / sheet / critique | no qa fail | | 8. critique (5 lenses, parallel, read-only) | critics | ranked issues + tested operations | | | 9. fix | ONE fixer | the design | qa: no regression | | 10. master, credits, mux | lead | `CREDITS.md`, description text, the film | credits exit 0, lag 0 | The detail of every step, the roles and what each critic measures: `references/process.md`. Every sub-agent prompt is a ready-to-fill brief in `templates/prompts/`. ### 0. Cue list from the picture Every sound sits on a frame the picture code computes: a contact frame, a pop-in's 50 % frame, a move's velocity peak, a riser's hit, the frame the wordmark becomes readable. Cinetic films already have `out/cues.json` (`export-cues.ts`); for anything else write the same format (`templates/cues.json`) from the timeline constants. Stable ids (`act:thing:n`) let rules match classes of action with a regex. ### 1. Brief Copy `templates/SOUND_BRIEF.md` to `audio/SOUND_BRIEF.md`: concept (palette, the music's arc, places), the picture map (every cue: what is on screen, the sound need), ambience zones, allowed licences, quality bar, file layout. It is the contract every sub-agent gets verbatim. Pick the brand's personality row (`references/sound-design.md` §3). ### 2. Sourcing, per category (`templates/prompts/sourcing.md`) Typical launch-film categories: `ui` (clicks, taps, toggles, pops), `keyboard`, `motion` (whooshes, risers), `impacts` (reveal hits, the logo), `ambience`, `music`; a character film adds `foley`, its worlds, its objects. Freesound (CC0 / CC BY; HQ preview `cdn.freesound.org/previews/<id//1000>/<id>_<user>-hq.ogg`), Mixkit (WAV `assets.mixkit.co/active_storage/sfx/<id>/<id>.wav`), composer libraries for music; licences read on each item's own page (`references/licences.md`); polite sequential downloads; every file measured: ``` {{PY}} -I <skill>/scripts/analyze.py audio/assets/ui/* --png out/audio-review/ui --out out/audio-review/ui.json {{PY}} -m earshot realness audio/assets/ui/ # gate: "real or pro-produced" (re-check trims: --start --end) {{PY}} -m earshot rank "a single crisp trackpad click" audio/assets/ui/ --top 5 {{PY}} -m earshot match <file> "a soft cork pop" --alts "a gunshot" "a balloon burst" {{PY}} -m earshot find <long take> "a single mechanical key press" --top 8 # trims; skip any marked head cut / tail cut ``` ### 3. Licence audit (`templates/prompts/licence_audit.md`) The auditor records what each page says (`licence_seen`, `licence_confirmed`) in `audio/assets/manifests/audit.json`; the script checks the rest (classification, ids vs URLs, files decode, durations, credit lines): ``` {{PY}} -I <skill>/scripts/audit.py --root . --report out/qa/mix_report.json [--fetch] ``` Allowed: CC0, public domain, CC BY 2.0-4.0, Mixkit free licences, Pixabay. Forbidden: NC, ND, SA, Sampling+, personal, custom, disputed. Unverified = blocked. ### 4. Music (`templates/prompts/music_supervisor.md`) One licensed track whose structure fits the film. Write the arc per film bar (`templates/arc.json`), then: ``` {{PY}} -I <skill>/scripts/arrange.py audio/assets/music/<track> --film-bpm 120 --arc audio/arc.json --out out/audio-review/music/arrange.json ``` It fits the tempo, moves the grid onto the measured attacks (beat trackers lag 20-50 ms), proposes the downbeat phase, anchors the drop film bar on the strongest drop candidate and drafts segments at bar lines (a ready-to-paste `music` block). The downbeat is the weak spot: when it prints LOW confidence (on one of the two tracks it was tested on it was half a bar off), decide between the two printed grids from the first note, the section entrances and the chord changes in the bar table, and re-run with `--phase N`. Then edit by judgement: harmony continues across each splice, the drop's downbeat on the hero frame, the final chord on the logo, `tail_fade` into the end. ### 5. Design fragments, per category (`templates/prompts/designer.md`) `audio/design/<category>.json` with samples (trims), slices (cut a take of many hits into single hits), pools, rules on cue events, free placements, ambience beds, the music block. Reference with every key and real examples: `references/design-format.md`; a complete launch-video example: `templates/design_fragment.json` (its file names are placeholders such as `mk-0000_mouse-click.wav`: it renders once each one is replaced by a real recording from your manifests; mix.py stops and lists the missing files until then). Verify alone: ``` {{PY}} -I <skill>/scripts/mix.py --only ui --dump out/audio-review/ui/dump # every trim as WAV + numbers {{PY}} -I <skill>/scripts/mix.py --only ui --trace out/audio-review/ui/adds.json --out out/audio-review/ui/solo.wav {{PY}} -I <skill>/scripts/qa.py --only ui --report out/audio-review/ui/solo_report.json --stems out/audio-review/ui/solo_stems --trace out/audio-review/ui/adds.json --out out/audio-review/ui/qa.json {{PY}} -m earshot timeline out/audio-review/ui/solo.wav --cues out/cues.json ``` ### 6-7. Integrate, QA, listen ``` {{PY}} -I <skill>/scripts/mix.py --root . --design audio/sounddesign.json --cues out/cues.json --trace out/qa/adds.json {{PY}} -I <skill>/scripts/qa.py --layers # clicks, edges, audibility, harshness, loudness, coverage, sync, density {{PY}} -I <skill>/scripts/qa.py --listen --realness --video out/film.mp4 # + earshot timeline, sheet, critique, realness {{PY}} -m earshot critique out/audio/soundtrack.wav --video out/film.mp4 # scorecard vs professional launch films {{PY}} -m earshot sheet out/audio/soundtrack.wav -o out/qa/sheet.png --video out/film.mp4 --cues out/qa/cues_sounded.json ``` `qa.py` ties every finding to the rule and sample that caused it (the trace). It is usable without the models; `--listen` adds earshot's transcript (`out/qa/qa_timeline.txt`), annotated sheet and scorecard. ### 8-9. Critique and fix Five read-only critics in parallel, each with its prompt: `critic_sync.md`, `critic_edges.md`, `critic_masking.md`, `critic_tonal.md`, `critic_director.md`. Each tests its fixes as a variant in its own folder: ``` {{PY}} -I <skill>/scripts/variant.py --ops out/audio-review/critic_tonal/ops_v1.json --out out/audio-review/critic_tonal/v1 --render --qa ``` and returns ranked issues with exact operations and before -> after numbers. Then ONE fixer (`fixer.md`) merges the operations, resolves conflicts, checks the merged variant against the previous qa.json, and applies it (`variant.py --apply`, originals backed up). Acknowledge confirmed deliberate exceptions with `"qa_ok": "<reason>"`. At least one round; a second when levels or the music edit changed. ### 10. Master, credits, mux `mix.py` masters with `master.py` (-14 LUFS, true-peak limiter, ceiling 0.77 linear; gate +-0.5 LU and <= -1.5 dBTP). ``` {{PY}} -I <skill>/scripts/audit.py --root . --report out/qa/mix_report.json # exit 0 {{PY}} -I <skill>/scripts/credits.py --root . --design audio/sounddesign.json --audit audio/assets/manifests/audit.json node <skill>/scripts/mux.mjs --video out/film.mp4 --audio out/audio/soundtrack.wav --out out/film_sound.mp4 {{PY}} -m earshot timeline out/film_sound.mp4 --cues out/qa/cues_sounded.json # the finished file, heard ``` `CREDITS.md` + `out/CREDITS_description.txt` (paste into the video description: CC BY credits are required there). `mux.mjs` stream-copies the picture and cuts the AAC audio to the picture's duration. ## Launch videos: the sound map | picture | sound | sits on | |---|---|---| | cursor moves, hovers, scrolls, progress, streaming text | nothing (the music carries it) | | | click / tap | ONE real click voice for the film, press + release ~85 ms later, same level every time | the press frame | | typing | one real keyboard, sliced; <= ~12 keys/s, one per word above ~25 chars/s; music dips 6-10 dB | each sounded character | | a card / chip / badge appears | a soft real pop or tick, climbing across a run | 50 % of its travel | | toggle, lock-in, a counter's final value | a real latch / click / crisp tick | the contact / lock frame | | camera-scale move, whip, zoom (~2 per film) | a real swish, apex on the velocity peak | velocity peak | | hard cuts | nothing | | | tension into the reveal | the music's build, or a real riser ending 30-250 ms before the hit | the hit | | hero reveal | the music's DROP (edit the track so its downbeat lands here) + optionally one real impact | the frame | | logo / lockup | music stops on a bar line or filters down, 0.2-0.7 s near-silence, ONE soft note in key, tail to silence | the frame the wordmark reads | Levels: -14 LUFS, true peak <= -1 dBTP after AAC, LRA 5-9 LU, the loudest moment on the drop (30-60 % in), the logo 8-20 dB under it, about 5 designed effects per 10 s, effects dry and centred. Measured norms and the cheap tells: `references/sound-design.md`. ## Tools | need | tool | |---|---| | measure recordings (format, floor, bandwidth, onsets, spikes, tempo / key) + spectrogram PNGs | `scripts/analyze.py` | | hear recordings: real vs synthesized, what it sounds like, best match, best take inside a long file | `{{PY}} -m earshot realness / describe / match / rank / find / compare / ab` | | levels / brightness / onsets of one file or a stretch of it (`--start --end`) | `{{PY}} -m earshot measure` (Python: `from earshot import api; api.measure(...)`, likewise `api.find`, `api.realness` ...) | | licence + file audit | `scripts/audit.py` (policy in `scripts/licences.py`) | | music grid, downbeats, bar-line edit draft | `scripts/arrange.py` | | render the design (+ solo `--only`, `--dump` trims, `--trace` for QA) | `scripts/mix.py` | | master and loudness measurement | `scripts/master.py` (`--measure`) | | objective QA tied to placements | `scripts/qa.py` (`--layers`, `--listen`, `--realness`) | | critic variants, the fixer's apply | `scripts/variant.py` | | credits for CREDITS.md and the video description | `scripts/credits.py` | | put the soundtrack on the picture | `scripts/mux.mjs` | | listen to a whole mix / film; annotated picture; launch-film scorecard | `{{PY}} -m earshot timeline / sheet / critique` | ## Files ``` audio/SOUND_BRIEF.md the contract (templates/SOUND_BRIEF.md) audio/assets/<category>/ downloaded recordings (<source>-<id>_<slug>.<ext>; never commit or publish them) audio/assets/manifests/<cat>.json one entry per recording (templates/manifest_entry.json) audio/assets/manifests/audit.json licence audit (templates/audit_entry.json) audio/sounddesign.json top level: includes, buses, master (templates/sounddesign.json) audio/design/<category>.json one fragment per designer (templates/design_fragment.json) out/cues.json the picture's cue events (templates/cues.json) out/audio/soundtrack.wav, stems/ the master and its stems out/qa/ mix_report.json, adds.json, cues_sounded.json, master.json, qa.json out/audio-review/ per-category and per-critic work, variants, dumps (the audit trail) CREDITS.md, out/CREDITS_description.txt ``` ## References - `references/process.md`: roles, steps, what each critic measures, thresholds and the - LICENSE (1065 bytes)
MIT License Copyright (c) 2026 Leon Lin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- pyproject.toml (3620 bytes)
[build-system] requires = ["setuptools>=69"] build-backend = "setuptools.build_meta" [project] name = "earshot" version = "1.0.0" description = "Make sound effects for interfaces, motion videos, games and films, everyday foley, drums and ambience from a request in words (computed at request time; the realistic ones from models learned from public-domain recordings, no audio shipped), build what the catalogue lacks from recorded parts named in words, and describe, match, measure and critique sound an agent cannot hear." readme = "README.md" requires-python = ">=3.10" license = { text = "MIT" } authors = [{ name = "Leon Lin" }] keywords = ["audio", "sound", "ai-agents", "mcp", "claude-code", "clap", "audio-analysis", "sound-design", "sound-effects", "procedural-audio", "synthesis", "game-audio", "ui-sounds", "audio-sprite", "video", "cpu"] classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Topic :: Multimedia :: Sound/Audio :: Analysis", "Topic :: Multimedia :: Sound/Audio :: Sound Synthesis", "Topic :: Games/Entertainment", "Topic :: Scientific/Engineering :: Artificial Intelligence", ] # the base install makes sounds (make, make_set, sounds, the bank, kits, pack: CLI, Python and MCP tools); listening, # measuring files and pictures come with the extras below (earshot.extras says which call needs which) dependencies = [ "numpy>=1.26", "scipy>=1.11", "soundfile>=0.12", "soxr>=0.3", # resampling: a sound written at another rate than 48 kHz, files read at another rate "numba>=0.58", # the hot loops of the synthesis; without it they run in plain Python ] [project.urls] Homepage = "https://github.com/Leonxlnx/earshot" Repository = "https://github.com/Leonxlnx/earshot" Issues = "https://github.com/Leonxlnx/earshot/issues" [project.optional-dependencies] # the listening models (CLAP, the AudioSet tagger) and librosa: describe, match, rank, find, compare, ab, realness, # timeline, critique, profile, vocab, make with listen. CPU wheels of torch: # pip install torch --index-url https://download.pytorch.org/whl/cpu listen = ["torch>=2.6", "transformers>=4.40", "librosa>=0.10"] measure = ["librosa>=0.10"] # measure, find and profile's onsets, without the models images = ["matplotlib>=3.8", "pillow>=10"] # sheet, gallery, video frames, plots mcp = ["mcp>=2"] llm = ["requests>=2.31"] all = ["earshot[listen,measure,images,mcp,llm]"] dev = ["pytest>=8"] [project.scripts] earshot = "earshot.cli:main" [tool.setuptools.packages.find] include = ["earshot*"] [tool.setuptools.package-data] earshot = ["data/*.json", "data/*.npz", "data/recipes/*.json", "data/resyn/*.npz", "data/resyn/*.json", "data/resyn/*.md", "data/textures/*.npz", "data/textures/*.json", "data/textures/*.md", "data/drums/*.npz", "data/drums/*.json", "data/drums/*.md", "data/notes/*.json", "data/notes/*.md", "data/notes/*/*.npz", "forge/bank/*.json", "forge/kits/*.json", "forge/seeds/*.json"] [tool.pytest.ini_options] testpaths = ["tests"] # uv (`uv tool install`) takes torch from the CPU-only wheel index; pip ignores this [tool.uv.sources] torch = { index = "pytorch-cpu" } [[tool.uv.index]] name = "pytorch-cpu" url = "https://download.pytorch.org/whl/cpu" explicit = true - README.md (40209 bytes)
# earshot earshot makes sound effects for a coding agent, which cannot hear them. The agent asks in words; earshot answers from a catalogue of 922 designs, most of the realistic ones recorded things rebuilt in code, and renders a new take of the best one. When the catalogue has no such thing, the answer says so plainly, and `earshot build` makes it from recorded parts: the agent names the parts in words, earshot finds a recording for each, lays them out as a recipe and listens to the result with its own ears (a listening model) to say how well it fits and what is still off. earshot also listens to any sound file and describes it in words and numbers. It is made for agents such as Claude Code, which write the code of interfaces, games and films, and for the people who work with them. It runs on your own computer's CPU as a command line, a Python package, an MCP server and a Claude Code plugin, and every sound it makes is yours to use. ``` $ earshot make "three variations of a footstep on gravel" -o step.ogg step_1.ogg: step/pebbles (0.51 s, peak at 0.10 s, -15 LUFS, clean) [gravel, footstep] step_2.ogg: step/pebbles (0.40 s, peak at 0.07 s, -16 LUFS, clean) step_3.ogg: step/pebbles (0.60 s, peak at 0.02 s, -16 LUFS, clean) played: one event; the action: events=<n> or say it ("footsteps", "knocking", "three knocks") also: step/gravel, step/floorboard, step/heels ``` The three files are three different real footsteps: `step/pebbles` is learned from recordings of steps on gravel that are in the public domain, and each file is a new take rendered from them. What the catalogue lacks, the agent builds with `earshot build`: [Build what is missing](#build-what-is-missing). ```bash npx skills add Leonxlnx/earshot # the agent skills pip install "earshot @ git+https://github.com/Leonxlnx/earshot" # the tool ``` Install from GitHub: the name `earshot` on PyPI belongs to another project. [The earshot site](https://leonxlnx.github.io/earshot-site/) plays all 922 sounds in the browser. What is in the box: - **Making sounds** (`earshot make`): a catalogue of 922 designs in 384 families holds interface sounds, everyday foley, ambience beds, game sounds, chip sound, drums, film and motion effects and three short music loops. 309 are learned from 692 recordings in the public domain; no audio file is in the repository, and every sound is rendered by code when it is asked for. Ready-made sets give an app, a game or a film its sounds in one call. - **Building what is missing** (`earshot build`, recipes): a sound made of recorded parts, laid out as a small JSON recipe (scattered, repeated, bent in pitch, passing by, pulsing, drawn longer), heard and tuned by the listening model. A cookbook of 99 recipes ships with it. - **Listening** (an extra): what a file sounds like, how well it fits a description, the best moment in a long recording, whether it sounds recorded or synthesized, and a second-by-second account of a film's soundtrack. - **Tools for film sound**: a bank of 252 sound effects stored as code, film sound kits, a search that writes synthesis code by listening (`forge`), and `fit`, which turns a recording into code. - An MCP server with 20 tools, a Claude Code plugin with two commands, and two agent skills. ## Contents - [Install](#install) - [Make sounds](#make-sounds): how to ask, what it can make, sets for an app, a game or a film, files - [Build what is missing](#build-what-is-missing): `earshot build`, parts in words, recipes - [Listen](#listen) - [Film sound: bank, kits, forge, fit](#film-sound-bank-kits-forge-fit) - [Use it from an agent](#use-it-from-an-agent): MCP server, Claude Code plugin, Python, skills - [How good is it](#how-good-is-it) and [limits](#limits) - [History](#history), [repo map](#repo-map), [licence](#licence) ## Install Python 3.10 or newer, CPU only; no GPU is used. ffmpeg on PATH is needed only to write ogg, mp3, m4a and webm (wav and flac are written without it) and to read video. The base install makes sounds: `make`, `make_set`, `sounds`, recipes, the sound bank and film kits, and `pack`, on the command line, in Python and as MCP tools. It brings numpy, scipy, soundfile, soxr and numba (about 350 MB installed) and no model; nothing is downloaded when a sound is made. ```bash pip install "earshot @ git+https://github.com/Leonxlnx/earshot" earshot make "a soft success sound" -o success.wav ``` The first sound of a fresh install takes longer: numba compiles the synthesis loops once and keeps them on disk, so later calls start at once. Listening, measuring and drawing come with extras, named in the brackets (several at once: `earshot[listen,mcp]`): | extra | brings | for | |---|---|---| | `mcp` | the MCP SDK | `earshot mcp`, the MCP server and the plugin | | `listen` | torch, transformers, librosa; the two listening models (about 1.1 GB to download, about 2.2 GB on disk) download on first use | `describe`, `match`, `rank`, `find`, `compare`, `ab`, `realness`, `timeline`, `critique`, `profile`, `make --listen`, the ears of `build` | | `measure` | librosa | `measure` and `find` without the models | | `images` | matplotlib, pillow | `sheet`, `gallery`, frames of a video, plots | | `llm` | requests | the optional Gemini critique (`earshot llm`, your own API key) | | `all` | every extra above | | A call that needs an extra that is not installed stops with one sentence that names the missing package and the `pip install` command that adds it; `earshot doctor` lists what is installed. torch from the default index is large on Linux (it brings CUDA); the CPU build is smaller: ```bash pip install torch --index-url https://download.pytorch.org/whl/cpu # before the listen extra, optional pip install "earshot[listen,mcp] @ git+https://github.com/Leonxlnx/earshot" earshot doctor --fetch # downloads the listening models now (about 1.1 GB; 2.2 GB on disk), not on first use ``` As a uv tool, with the extras in the brackets (uv takes torch from the CPU index); update with `uv tool upgrade earshot`: ```bash uv tool install "earshot[mcp] @ git+https://github.com/Leonxlnx/earshot" ``` To work on earshot itself, install from a clone: ```bash git clone https://github.com/Leonxlnx/earshot && cd earshot python -m venv .venv .venv/bin/python -m pip install torch --index-url https://download.pytorch.org/whl/cpu # Windows: .venv/Scripts/python .venv/bin/python -m pip install -e ".[all,dev]" .venv/bin/python -m earshot doctor --load ``` **The listening models.** The first listening call downloads two open models (about 1.1 GB to download, about 2.2 GB on disk) into `.cache/hf` inside a clone, `~/.cache/earshot/hf` otherwise (or `EARSHOT_HOME`), each at a pinned revision with safetensors weights: CLAP `laion/larger_clap_general` @ `16c8cc3` (text-audio embeddings) and the AudioSet tagger `MIT/ast-finetuned-audioset-10-10-0.4593` @ `f826b80`. After that earshot loads them from that cache only and never contacts the Hub; a damaged cache is an error that names the folder, not a silent new download. A cache made before 0.2.1 holds CLAP's revision `ada0c23` as a pickle; earshot still loads it, never downloads it, and `earshot doctor --fetch` replaces it with the pinned safetensors (776 MB). **Offline.** `EARSHOT_OFFLINE=1`, `HF_HUB_OFFLINE=1` and `TRANSFORMERS_OFFLINE=1` all mean the same to earshot: it never downloads, and a model missing from the cache is an error that says so. earshot never sets or clears them. **Settings** (environment variables): `EARSHOT_THREADS` (torch CPU threads, default min(4, cores/2); the CLI and the MCP server hold numpy and scipy's OpenBLAS to it too, unless `OPENBLAS_NUM_THREADS` is set), `EARSHOT_HOME` (the cache root), `EARSHOT_PRECISION` (`bf16` by default, used only on CPUs with native bf16 such as AVX512-BF16 or AMX, fp32 everywhere else; `fp32` forces fp32), `EARSHOT_CLAP` / `EARSHOT_AST` (another Hub model id, or a local model folder with `config.json` and `model.safetensors`, loaded from disk as it is) and `EARSHOT_CLAP_REVISION` / `EARSHOT_AST_REVISION` (another Hub revision; safetensors weights only). `earshot doctor` reports the revisions and what the cache holds; `--load` also what loads. ## Make sounds `earshot make` reads a request, ranks the catalogue, renders a new take of the best design, checks it without models (clicks, cut tails, clipping, DC) and writes the file. It loads no model and takes a few seconds for a one-shot. ``` $ earshot make "a soft success sound for a finance app" -o success.ogg success.ogg: success/shutter (0.36 s, peak at 0.10 s, -15 LUFS, clean) [success] also: complete/shutter, success/click, complete/chop $ earshot make "a campfire" -o fire.ogg --dur 24 fire.ogg: fire/camp (24.00 s, peak at 19.96 s, -22 LUFS, seamless loop, clean) [campfire] also: fire/large, fire/small, fire/whoosh ``` The first line of each file is the result: the design chosen, the length, where the loudest moment is (`peak at`), the loudness, `seamless loop` for a loop, `clean` or what the check found, and the words that decided. `also` gives three alternatives, to be taken with `--sound ID`. A request that names something the catalogue does not have still gets a file, and the answer says so: `earshot makes no fire alarm; timer/done is only the nearest sound it has`, with three starting points and the `earshot build` line that builds it. Lines such as `not followed`, `not in this sound` and `not understood` name what the request asked that this sound does not do. Every line and option: [docs/MAKE.md](docs/MAKE.md). ### How to ask Name the thing, the job or the sound first; then feelings, material and numbers. | the words | what they do | example | |---|---|---| | the thing, the job or the sound | choose the design: things ("a light switch", "a cork"), jobs ("success", "coin pickup", "toggle") and sounds ("chime", "whoosh", "rain") | `"a notification"` -> `notify/knock` | | feelings | offsets on eight shared axes: bright, hard, ring, size, space, width, energy, motion | `"a much bigger, darker whoosh"`: size +0.84, bright -0.6 | | negation, comparison | "not harsh", "not too loud", "the opposite of a success sound", "like a ..." | `"the opposite of a success sound"` -> `error/knock` | | a surface or a place | what follows "on" or "in" is where the sound happens; a surface it lacks gets the nearest and says so | `"rain on a tarp"` -> `rain/tent`, "the nearest surface" | | one event or the action | a plural, an action word, a count or a length plays the action a person performs; a singular or "a single" one event | `"footsteps on gravel"` (a walk), `"a footstep on gravel"` (one step), `"three knocks"` | | voice | the instrument that plays a tonal sound, when the words ask for music | `"a notification on a harp"`, `"a kalimba note in E"` | | material | picks the voice of a tonal sound (wooden: a marimba) and steers the ranking; "8-bit", "retro", "chiptune" allow only chip sound | `"8-bit coin pickup"` -> `coin/chip` | | numbers | length, gap, pitch, key, how many takes, how many events | `"400 ms"`, `"200 ms apart"`, `"in D minor"`, `"three variations"` | | loop or not | ambience loops by default; "no loop" or `--no-loop` renders it once with fades | `"rain on a tent, no loop"` | The moment may follow the sound ("a soft thump when the pricing card settles"); words for the place or the product ("in my running app, a success sound") choose nothing. A request in German is read through a table of common sound words ("Regen auf Holz" as rain on wood); other languages get "write it in English". Options win over the words: `--pitch`, `--dur`, `--voice`, `--events`, `--lufs` and the axes `--bright` ... `--motion` (each -1 to 1), and `--sound ID` takes a design by name. To steer, ask again with adjectives ("softer", "drier", "longer") rather than browsing. ### What it can make `earshot sounds` lists every design (`--search`, `--domain`, `--family` narrow it). Ids are `family/name`: what the sound is, then its character. | group | designs | how it is made | examples | |---|---|---|---| | learned things | 309 | learned from 692 recordings in the public domain: footsteps, doors, switches, keyboards, glass, water, animals, people without words, street, house and kitchen sounds | `step/pebbles`, `door/shut`, `switch/lamp`, `camera/shutter`, `dog/bark`, `rocket/launch` | | interface | 29 | things a hand does, built from those recordings: a key going down and coming up, a page, a drawer, a cork, knocks, a camera shutter, scissors | `toggle/key_down`, `next/page`, `notify/knock`, `success/shutter`, `delete/snip` | | interface and game figures | 45 (and 3 ticks) | notes in time on a real instrument (a marimba by default); for interfaces only when the words ask for music or a theme is named | `success/rise`, `coin/bright`, `level_up/fanfare`, `logo/bloom` | | ambience | 43 | 25 learned from recordings of real places and textures, 18 from rules | `fire/camp`, `waves/sand`, `rain/tin_roof`, `cafe/busy`; `rain/window`, `forest/morning` | | film and motion | 69 | 55 built from learned recordings as motion films use them (small real actions cut short: a door falling shut, a heavy bag dropped, a stick swung, a breath of air; hits, whooshes and risers); 14 small ones invented | `thump/door`, `title/bag`, `logo/bag`, `whoosh/sweep`, `rise/breath` | | drums | 40 | 33 played from recorded strokes in the public domain (the acoustic kit and hand percussion); 7 invented | `kick/soft`, `snare/tight`, `conga/muted`; `kick/electro` | | chip | 24 | the channels of 8-bit consoles; only when asked for | `coin/chip`, `jump/chip`, `laser/chip` | | action and objects | 83 | invented from physics | `jump/soft`, `hit/punch`, `coin/drop`, `bell/desk` | | notes and synthesizer | 51 and 14 | real instruments learned note by note, struck and string models, synth patches | `note/kalimba`, `pad/warm` | | music loops | 3 | short beds for a game menu or a demo; earshot does not make music | `bed/warm`, `bed/playful`, `bed/8bit` | | bank | 209 | the film sound bank, stored as code | `whoosh_fast/crisp`, `riser/tension` | When a learned design and an invented one answer the same request, the learned one wins. When the two are the same thing (`knock/door` and `door/knock`: 34 such pairs), a request that names the thing gets the learned one, and the invented one is still there by its id. **Learned sounds.** A learned design is not a recording that is played back. earshot keeps each recording as numbers (the level of 56 bands every 2 ms, how tonal each band is, the stereo image) and renders a new take from them with fresh noise and the request's controls. Seeds 0, 1, 2 walk through a design's recordings, the fullest clean one first. A thing a person does several times in a row (a walk, a knock, typing, coins) is played as that action when the words ask for it. Every recording is credited in a `CREDITS.md` next to its numbers ([Licence](#licence)). # - SKILL.md (47768 bytes)
--- name: earshot description: Make sounds with earshot whenever a product, game, page, animation or film needs a sound and no recording is at hand - interface sounds (taps, toggles, hovers, typing, success, error, notifications), everyday foley for games, 3D and video (footsteps, doors, drawers, switches, keys, cloth, glass, water, metal, swings, punches, explosions, animals, kitchen and street sounds), ambience beds (fire, sea, rain, wind, crickets, a cafe, a street), game sounds (coins, fanfares, 8-bit), drums, motion-design effects and a few short music loops, one at a time (earshot make) or as one family (earshot make --set / make_set), and build what the catalogue lacks from recorded parts named in words, heard and tuned by earshot's ears (earshot build, recipes). Listen with earshot whenever you must judge, choose, trim, verify or compare sound you cannot hear - picking a sound effect, music or ambience from candidates, finding the cleanest moment in a recording, checking whether audio reads as a real recording or as code-synthesized, reviewing a soundtrack or a video's audio (what happens when, sync to picture, loudness, mix), A/B-ing a mix change, searching a recipe by listening (earshot forge), or giving a code-made film its sound effects from the shipped bank (earshot sfx / kit). Use it before telling anyone how audio sounds. --- # earshot: making and hearing sound ## Making sounds earshot turns a request in words into a sound file: it picks a design from its catalogue and renders a new take. No model is loaded and nothing is downloaded; a one-shot takes a few seconds. When the catalogue lacks the thing, the answer says so, and you build it from recorded parts with `earshot build` (below). If the `earshot` command is missing, see Setup at the end. The shortest path: `earshot make "WORDS" -o FILE`; read the first line (`clean` or not) and any `earshot makes no X` line; if it says that, `earshot build "WORDS" -o FILE --part "..." --part "..."`, read `fit:` and `still off:`, and hand it over as what `fit` says. The catalogue holds 922 designs. Realistic things are learned from recordings in the public domain (309 things: footsteps on many surfaces, doors, drawers, switches, keyboards, cloth, paper, glass, water, metal, punches, falls, explosions, animals, people without words, street, house and kitchen sounds) and so are 25 ambience beds (fire, shores, crickets, a brook, a cafe, a street, rain on wood, on a tin roof and on an umbrella), the acoustic drums and the four real instruments that play tonal figures (marimba, harp, pizzicato strings, upright piano). The interface sounds and the film and motion effects are built from those recordings. Written in code: the tonal figures (success, coin, level up), chip sound, the drum-machine voices, some beds made from rules, three short music loops and the film sound bank. Only numbers ship, no audio file: every sound is computed when it is asked for. Invented designs of real things (jumps, magic, game hits) sound clearly less real: prefer a learned thing when one fits. ### When a sound, and when none Most moments get none. A sound belongs where something happened that a person should notice without looking. What follows is common practice; only the motion-video numbers are measured. - A page or an app: a sound for what the user did on purpose and for what came of it (a switch thrown, a form sent, a payment gone through, an error, a message arriving). None for what happens by itself or all the time: the page loading, scrolling, an animation, the pointer crossing links. A landing page needs three to six of the `ui` roles, not all 17; `hover` is for tools in which hovering is a choice. - A game: every action the player repeats gets a short sound in several takes (steps, jumps, hits, coins); a reward and the end of a level get the longer figures on an instrument; a menu gets one small sound for moving and one for choosing. - A motion video (a launch film, a product demo): two to five effects in a film that music leads (below). - A scene of real footage: one bed for the place, then the real sound of each thing the picture shows being done, asked for as that thing. A thing the catalogue has no recording of is better recorded, built or left silent than replaced by a stand-in. ### How to ask **One sound**: `earshot make "WORDS" -o sounds/success.ogg` (MCP `make`: `want`, `out`; optional `sound`, `n`, `theme`, `pitch`, `dur`, `voice`, `material`, `loop`, `events`, `seed`, `recipe`; MCP paths absolute). One call per sound. ``` $ earshot make "a soft success sound for a finance app" -o success.ogg success.ogg: success/shutter (0.36 s, peak at 0.10 s, -15 LUFS, clean) [success] also: complete/shutter, success/click, complete/chop ``` - Name the thing, the sound or the job first, then feelings, material, numbers: "a footstep on gravel", "a wooden drawer closing", "a camera shutter", "coin pickup, 8-bit", "waves on a beach, 30 seconds". - The moment comes after the sound, behind "when", "as" or "each time": "a soft low thump when the pricing card settles" (thump/soft). Put first, the words of the moment are taken for the sound. Words for the product or the place ("in my running app, a success sound") choose nothing. - What follows "on" or "in" is the surface or the place: "rain on wood" is `rain/wood`. A surface the sound has no design on gets the nearest and says so ("rain on a tarp": `no rain on a tarp: rain/tent is the nearest surface`). - A learned sound answers only when its thing is named: "a heavy impact" gets a designed film hit, "a dumbbell dropped" the recording. - Feelings steer: "softer", "darker", "bigger", "longer", "drier", "not harsh". To steer, ask again with adjectives rather than browsing. - Interface and motion requests get normal sounds. Notes on an instrument answer only when the words ask for music (an instrument, a chime, a jingle, a melody) or a theme is named; an instrument named as the player sets the voice ("a notification on a harp", `voice`: marimba, harp, pizzicato, felt_piano, kalimba ...). Chip sound only with "8-bit", "retro" or "chiptune". A bell or glass timbre only when you ask for one. - English; German is read through a table of common sound words ("Regen auf Holz" is rain on wood). Other languages get "write it in English". **One event or the action.** A thing a person does several times in a row (footsteps, knocking, typing, coins, keys, clinking glasses) is played as the action when the words ask for it: "footsteps on gravel", "knocking", "three knocks", "5 seconds of typing". "a footstep on gravel" or "a single knock on a door" is one event. `--events N` (MCP `events`) overrides: 1 is one event, 2 or more the action with N events. A counted action is one file ("four knocks on the table", "three claps", "a countdown 3 2 1"); a count of separate things is that many files ("five coin pickups", "3 variations"). A length with an action ("three knocks, 2 seconds") is the file's length, the events spread over it; "200 ms apart" sets the gap. The `played:` line says what was played. **Takes.** For a learned design, seeds 0, 1, 2 play its different recordings, the fullest clean one first, then new takes of them. Ask for 6 to 12 takes of anything a game repeats (`--n 8` or "eight variations"), and make them in a set (`"n": 8` in a spec) so they share one level. **Several sounds that belong together** (an interface, a game, a film's kit): ONE call, never a loop of `make`. - A ready-made set: `earshot make --set ui|game|arcade|film -o FOLDER --format webm,mp3 --sprite sprite` (MCP `make_set` with `set`, `theme`, `format`, `sprite`). `ui` (17): every role a thing a hand does, no instrument: tap a mechanical key (keyboard/mechanical), hover a fingertip on wood (hover/fingertip), toggle_on and toggle_off that key going down and coming up (toggle/key_down, toggle/key_up), type (type/mechanical), next and back a page (next/page, back/turn), open and close a wooden drawer (open/drawer, close/drawer), send a stick swung through the air (send/swoosh), receive a cork (receive/cork), notify two light knocks (notify/knock), success a camera shutter (success/shutter), complete a bigger shutter (complete/shutter), warning two firm knocks (warning/knock), error two heavier knocks that fall (error/knock), delete a cut of scissors (delete/snip). A plain request for one of these jobs gets the same design. With a theme named (soft, glass, wood, felt, tine, metal, electric, digital, retro), `ui` plays tonal figures in that theme's voice instead. `game` (22: menus, rewards, jingles, actions; its jump, land, hit, explosion and door are invented, so name learned ones in a spec where a real sound matters, such as `{"name": "door", "sound": "door/shut"}`), `arcade` (16 chip sounds), `film` (17 motion-design sounds). - A spec: your own list, on top of a set or alone. `{"sounds": [{"name": "tap", "want": "a soft tap"}, ...]}` in a JSON file, then `earshot make --spec FILE -o FOLDER` (MCP `make_set` with `sounds`). Fields of an entry: name, want, sound, recipe, pitch, dur, voice, material, seed, n, axes, lufs, events, loop; an unknown field is an error that lists them. With `"set": "ui"` your entries add to the set (an entry with a set's name replaces it); without `set` only your list is made, which is the call for the handful of sounds a landing page or a scene needs. Every one-shot is as loud as it is made alone, within 2.5 dB of the others; loops and beds are levelled by kind. A re-run rewrites the files and `manifest.json`; it does not delete files of names you removed. ``` $ earshot make --spec landing.json -o sounds 5 sounds in sounds (wav), manifest.json open.wav: open/drawer (0.68 s, peak at 0.39 s, -14 LUFS, clean) [opening] toast.wav: notify/knock (0.40 s, peak at 0.01 s, -18 LUFS, clean) [toast notification] error.wav: error/knock (0.58 s, peak at 0.19 s, -18 LUFS, clean) [error] not understood: address card.wav: thump/soft (0.09 s, peak at 0.03 s, -24 LUFS, clean) [thump, card, settles, soft] not understood: pricing paid.wav: success/shutter (0.36 s, peak at 0.10 s, -15 LUFS, clean) [payment success] ``` (the `want`s: "a modal opening", "a toast notification", "an error sound for a wrong email address", "a soft low thump when the pricing card settles", "a payment success sound"). **The catalogue**, only when a pick was wrong and `also` does not help: `earshot sounds --search WORDS` (top 20) or `earshot sounds --family step`, then `earshot make "WORDS" --sound ID`. Never list the whole catalogue. ### Reading the answer The answer is the whole result; ask for `--json` (MCP `full=true`) only for measurements. - `x.ogg: design/id (0.88 s, peak at 0.05 s, G5, marimba, -14 LUFS, clean) [words]`: the design, its length, its loudest moment, the note and voice of a tonal sound, the loudness, and `clean` or what the audit found. Report this line. Anything other than `clean` means not usable: make it again with another `seed`. - `also: a, b, c`: alternatives. If the chosen id does not fit the job, call again with `--sound ID`. - `also (the pick is a guess: ...): id (a few words), ...`: treat the pick as unverified. Choose an alternative by its words (`--sound ID`), or ask again naming the sound or the job. - `earshot makes no THING; ID is only the nearest sound it has`: the catalogue lacks the thing, and the file is a stand-in. Build it with `earshot build` (below), take one of the three starting points by id, or tell the user it is missing. Never pass a stand-in off as the thing. There is no error for an unknown thing: every request gets a file, and this line is the only sign. - `built from parts by the cookbook recipe NAME`: a recipe answered; `earshot recipe NAME` prints it to change. `a start from parts: earshot make --recipe NAME`: the catalogue answered, and a cookbook sketch is a start. - `not in this sound: WORDS`: part of the request is not in this file. A second thing wants its own call; a verb or an adjective of the same thing is no missing sound. - `not followed: ...` or `0.43 s, not the 2 s asked: ...`: the design has no such control or could not keep that length, and the line says what it did instead. "from left to right" is never followed: earshot does not pan. - `a cut of 4 s, not a loop: ...`, `a seamless loop of 8.00 s, ...`, `8.57 s: a music loop is whole bars ...`: what was made of a length asked for a bed or a loop; ask "a seamless loop of ..." when it must repeat without a seam. - `not understood: WORDS`: those words did nothing; rephrase plainly if they mattered. - `same design as NAME: ...` (sets): two names got one sound; give the second `"sound": ID`. `another recording of ID than NAME` is not a problem. - `... a loop in mp3 has a gap at its seam ...`: write that loop as ogg, webm, wav or flac. ### Length, level and where the hit is - **Length.** An interface sound is 0.2 to 0.7 s; a motion tick 0.04 s, a thump 0.06 to 0.09 s, a logo hit about 0.3 s, a whoosh about 0.4 s, a riser 2.5 s; a game's figures 0.7 s (a coin) to 2.9 s (the win fanfare); real things take their time (a door falling shut 2.5 s, distant thunder 7.7 s); a bed is 20 s unless a length is asked. Seconds in the words, or `--dur`, set the length of a whoosh, a riser, a figure, a bed and an action; a single struck sound rings as it rings and says so. - **Level.** A single file is as loud as its kind allows (true peak -1 dBFS, at most -14 LUFS, a bed -22), so single files are not a mix. `--lufs L` (`"lufs"` in a spec entry) sets one file's loudness. Sounds made as ONE spec are levelled against each other, a first balance to mix from: in a scene's spec the bed came out 9 to 16 LU under the things done in it. - **Where the hit is.** Every file starts when its sound does (within 2 ms), but its loudest moment is often later: the line says `peak at`, and `--json` gives `peak_s`, `onset_s` and, for a row, `events_s` (each event's start), in seconds from the start of the file. To put the hit on the frame at t, start the file at t minus `peak_s`: "a whoosh for a transition" answered `whoosh/sweep (0.42 s, peak at 0.30 s, ...)`, so for its peak on 12.000 s start it at 11.70 s. A riser ends on its peak, so it starts its own length before the reveal. earshot does not place files on a timeline: the editor, ffmpeg or the page's code does. - **A row in one file**: `earshot make "a soft ui tick" -o count.wav --events 8 --dur 1.5` answered `tick/key (1.50 s, peak at 0.81 s, -16 LUFS, clean)` and `played: 8 events as a row at 6.2 a second`: a number counting up. ### Scoring a motion video Measured on 39 reference motion-design videos (`docs/motion-sfx-study.md`); [measured] is a number from them, [convention] common practice they did not test. - Music carries the film. 34 of the 35 videos with sound are music-led [measured]; where effects stand out of t - skills/earshot/SKILL.md (47768 bytes)
--- name: earshot description: Make sounds with earshot whenever a product, game, page, animation or film needs a sound and no recording is at hand - interface sounds (taps, toggles, hovers, typing, success, error, notifications), everyday foley for games, 3D and video (footsteps, doors, drawers, switches, keys, cloth, glass, water, metal, swings, punches, explosions, animals, kitchen and street sounds), ambience beds (fire, sea, rain, wind, crickets, a cafe, a street), game sounds (coins, fanfares, 8-bit), drums, motion-design effects and a few short music loops, one at a time (earshot make) or as one family (earshot make --set / make_set), and build what the catalogue lacks from recorded parts named in words, heard and tuned by earshot's ears (earshot build, recipes). Listen with earshot whenever you must judge, choose, trim, verify or compare sound you cannot hear - picking a sound effect, music or ambience from candidates, finding the cleanest moment in a recording, checking whether audio reads as a real recording or as code-synthesized, reviewing a soundtrack or a video's audio (what happens when, sync to picture, loudness, mix), A/B-ing a mix change, searching a recipe by listening (earshot forge), or giving a code-made film its sound effects from the shipped bank (earshot sfx / kit). Use it before telling anyone how audio sounds. --- # earshot: making and hearing sound ## Making sounds earshot turns a request in words into a sound file: it picks a design from its catalogue and renders a new take. No model is loaded and nothing is downloaded; a one-shot takes a few seconds. When the catalogue lacks the thing, the answer says so, and you build it from recorded parts with `earshot build` (below). If the `earshot` command is missing, see Setup at the end. The shortest path: `earshot make "WORDS" -o FILE`; read the first line (`clean` or not) and any `earshot makes no X` line; if it says that, `earshot build "WORDS" -o FILE --part "..." --part "..."`, read `fit:` and `still off:`, and hand it over as what `fit` says. The catalogue holds 922 designs. Realistic things are learned from recordings in the public domain (309 things: footsteps on many surfaces, doors, drawers, switches, keyboards, cloth, paper, glass, water, metal, punches, falls, explosions, animals, people without words, street, house and kitchen sounds) and so are 25 ambience beds (fire, shores, crickets, a brook, a cafe, a street, rain on wood, on a tin roof and on an umbrella), the acoustic drums and the four real instruments that play tonal figures (marimba, harp, pizzicato strings, upright piano). The interface sounds and the film and motion effects are built from those recordings. Written in code: the tonal figures (success, coin, level up), chip sound, the drum-machine voices, some beds made from rules, three short music loops and the film sound bank. Only numbers ship, no audio file: every sound is computed when it is asked for. Invented designs of real things (jumps, magic, game hits) sound clearly less real: prefer a learned thing when one fits. ### When a sound, and when none Most moments get none. A sound belongs where something happened that a person should notice without looking. What follows is common practice; only the motion-video numbers are measured. - A page or an app: a sound for what the user did on purpose and for what came of it (a switch thrown, a form sent, a payment gone through, an error, a message arriving). None for what happens by itself or all the time: the page loading, scrolling, an animation, the pointer crossing links. A landing page needs three to six of the `ui` roles, not all 17; `hover` is for tools in which hovering is a choice. - A game: every action the player repeats gets a short sound in several takes (steps, jumps, hits, coins); a reward and the end of a level get the longer figures on an instrument; a menu gets one small sound for moving and one for choosing. - A motion video (a launch film, a product demo): two to five effects in a film that music leads (below). - A scene of real footage: one bed for the place, then the real sound of each thing the picture shows being done, asked for as that thing. A thing the catalogue has no recording of is better recorded, built or left silent than replaced by a stand-in. ### How to ask **One sound**: `earshot make "WORDS" -o sounds/success.ogg` (MCP `make`: `want`, `out`; optional `sound`, `n`, `theme`, `pitch`, `dur`, `voice`, `material`, `loop`, `events`, `seed`, `recipe`; MCP paths absolute). One call per sound. ``` $ earshot make "a soft success sound for a finance app" -o success.ogg success.ogg: success/shutter (0.36 s, peak at 0.10 s, -15 LUFS, clean) [success] also: complete/shutter, success/click, complete/chop ``` - Name the thing, the sound or the job first, then feelings, material, numbers: "a footstep on gravel", "a wooden drawer closing", "a camera shutter", "coin pickup, 8-bit", "waves on a beach, 30 seconds". - The moment comes after the sound, behind "when", "as" or "each time": "a soft low thump when the pricing card settles" (thump/soft). Put first, the words of the moment are taken for the sound. Words for the product or the place ("in my running app, a success sound") choose nothing. - What follows "on" or "in" is the surface or the place: "rain on wood" is `rain/wood`. A surface the sound has no design on gets the nearest and says so ("rain on a tarp": `no rain on a tarp: rain/tent is the nearest surface`). - A learned sound answers only when its thing is named: "a heavy impact" gets a designed film hit, "a dumbbell dropped" the recording. - Feelings steer: "softer", "darker", "bigger", "longer", "drier", "not harsh". To steer, ask again with adjectives rather than browsing. - Interface and motion requests get normal sounds. Notes on an instrument answer only when the words ask for music (an instrument, a chime, a jingle, a melody) or a theme is named; an instrument named as the player sets the voice ("a notification on a harp", `voice`: marimba, harp, pizzicato, felt_piano, kalimba ...). Chip sound only with "8-bit", "retro" or "chiptune". A bell or glass timbre only when you ask for one. - English; German is read through a table of common sound words ("Regen auf Holz" is rain on wood). Other languages get "write it in English". **One event or the action.** A thing a person does several times in a row (footsteps, knocking, typing, coins, keys, clinking glasses) is played as the action when the words ask for it: "footsteps on gravel", "knocking", "three knocks", "5 seconds of typing". "a footstep on gravel" or "a single knock on a door" is one event. `--events N` (MCP `events`) overrides: 1 is one event, 2 or more the action with N events. A counted action is one file ("four knocks on the table", "three claps", "a countdown 3 2 1"); a count of separate things is that many files ("five coin pickups", "3 variations"). A length with an action ("three knocks, 2 seconds") is the file's length, the events spread over it; "200 ms apart" sets the gap. The `played:` line says what was played. **Takes.** For a learned design, seeds 0, 1, 2 play its different recordings, the fullest clean one first, then new takes of them. Ask for 6 to 12 takes of anything a game repeats (`--n 8` or "eight variations"), and make them in a set (`"n": 8` in a spec) so they share one level. **Several sounds that belong together** (an interface, a game, a film's kit): ONE call, never a loop of `make`. - A ready-made set: `earshot make --set ui|game|arcade|film -o FOLDER --format webm,mp3 --sprite sprite` (MCP `make_set` with `set`, `theme`, `format`, `sprite`). `ui` (17): every role a thing a hand does, no instrument: tap a mechanical key (keyboard/mechanical), hover a fingertip on wood (hover/fingertip), toggle_on and toggle_off that key going down and coming up (toggle/key_down, toggle/key_up), type (type/mechanical), next and back a page (next/page, back/turn), open and close a wooden drawer (open/drawer, close/drawer), send a stick swung through the air (send/swoosh), receive a cork (receive/cork), notify two light knocks (notify/knock), success a camera shutter (success/shutter), complete a bigger shutter (complete/shutter), warning two firm knocks (warning/knock), error two heavier knocks that fall (error/knock), delete a cut of scissors (delete/snip). A plain request for one of these jobs gets the same design. With a theme named (soft, glass, wood, felt, tine, metal, electric, digital, retro), `ui` plays tonal figures in that theme's voice instead. `game` (22: menus, rewards, jingles, actions; its jump, land, hit, explosion and door are invented, so name learned ones in a spec where a real sound matters, such as `{"name": "door", "sound": "door/shut"}`), `arcade` (16 chip sounds), `film` (17 motion-design sounds). - A spec: your own list, on top of a set or alone. `{"sounds": [{"name": "tap", "want": "a soft tap"}, ...]}` in a JSON file, then `earshot make --spec FILE -o FOLDER` (MCP `make_set` with `sounds`). Fields of an entry: name, want, sound, recipe, pitch, dur, voice, material, seed, n, axes, lufs, events, loop; an unknown field is an error that lists them. With `"set": "ui"` your entries add to the set (an entry with a set's name replaces it); without `set` only your list is made, which is the call for the handful of sounds a landing page or a scene needs. Every one-shot is as loud as it is made alone, within 2.5 dB of the others; loops and beds are levelled by kind. A re-run rewrites the files and `manifest.json`; it does not delete files of names you removed. ``` $ earshot make --spec landing.json -o sounds 5 sounds in sounds (wav), manifest.json open.wav: open/drawer (0.68 s, peak at 0.39 s, -14 LUFS, clean) [opening] toast.wav: notify/knock (0.40 s, peak at 0.01 s, -18 LUFS, clean) [toast notification] error.wav: error/knock (0.58 s, peak at 0.19 s, -18 LUFS, clean) [error] not understood: address card.wav: thump/soft (0.09 s, peak at 0.03 s, -24 LUFS, clean) [thump, card, settles, soft] not understood: pricing paid.wav: success/shutter (0.36 s, peak at 0.10 s, -15 LUFS, clean) [payment success] ``` (the `want`s: "a modal opening", "a toast notification", "an error sound for a wrong email address", "a soft low thump when the pricing card settles", "a payment success sound"). **The catalogue**, only when a pick was wrong and `also` does not help: `earshot sounds --search WORDS` (top 20) or `earshot sounds --family step`, then `earshot make "WORDS" --sound ID`. Never list the whole catalogue. ### Reading the answer The answer is the whole result; ask for `--json` (MCP `full=true`) only for measurements. - `x.ogg: design/id (0.88 s, peak at 0.05 s, G5, marimba, -14 LUFS, clean) [words]`: the design, its length, its loudest moment, the note and voice of a tonal sound, the loudness, and `clean` or what the audit found. Report this line. Anything other than `clean` means not usable: make it again with another `seed`. - `also: a, b, c`: alternatives. If the chosen id does not fit the job, call again with `--sound ID`. - `also (the pick is a guess: ...): id (a few words), ...`: treat the pick as unverified. Choose an alternative by its words (`--sound ID`), or ask again naming the sound or the job. - `earshot makes no THING; ID is only the nearest sound it has`: the catalogue lacks the thing, and the file is a stand-in. Build it with `earshot build` (below), take one of the three starting points by id, or tell the user it is missing. Never pass a stand-in off as the thing. There is no error for an unknown thing: every request gets a file, and this line is the only sign. - `built from parts by the cookbook recipe NAME`: a recipe answered; `earshot recipe NAME` prints it to change. `a start from parts: earshot make --recipe NAME`: the catalogue answered, and a cookbook sketch is a start. - `not in this sound: WORDS`: part of the request is not in this file. A second thing wants its own call; a verb or an adjective of the same thing is no missing sound. - `not followed: ...` or `0.43 s, not the 2 s asked: ...`: the design has no such control or could not keep that length, and the line says what it did instead. "from left to right" is never followed: earshot does not pan. - `a cut of 4 s, not a loop: ...`, `a seamless loop of 8.00 s, ...`, `8.57 s: a music loop is whole bars ...`: what was made of a length asked for a bed or a loop; ask "a seamless loop of ..." when it must repeat without a seam. - `not understood: WORDS`: those words did nothing; rephrase plainly if they mattered. - `same design as NAME: ...` (sets): two names got one sound; give the second `"sound": ID`. `another recording of ID than NAME` is not a problem. - `... a loop in mp3 has a gap at its seam ...`: write that loop as ogg, webm, wav or flac. ### Length, level and where the hit is - **Length.** An interface sound is 0.2 to 0.7 s; a motion tick 0.04 s, a thump 0.06 to 0.09 s, a logo hit about 0.3 s, a whoosh about 0.4 s, a riser 2.5 s; a game's figures 0.7 s (a coin) to 2.9 s (the win fanfare); real things take their time (a door falling shut 2.5 s, distant thunder 7.7 s); a bed is 20 s unless a length is asked. Seconds in the words, or `--dur`, set the length of a whoosh, a riser, a figure, a bed and an action; a single struck sound rings as it rings and says so. - **Level.** A single file is as loud as its kind allows (true peak -1 dBFS, at most -14 LUFS, a bed -22), so single files are not a mix. `--lufs L` (`"lufs"` in a spec entry) sets one file's loudness. Sounds made as ONE spec are levelled against each other, a first balance to mix from: in a scene's spec the bed came out 9 to 16 LU under the things done in it. - **Where the hit is.** Every file starts when its sound does (within 2 ms), but its loudest moment is often later: the line says `peak at`, and `--json` gives `peak_s`, `onset_s` and, for a row, `events_s` (each event's start), in seconds from the start of the file. To put the hit on the frame at t, start the file at t minus `peak_s`: "a whoosh for a transition" answered `whoosh/sweep (0.42 s, peak at 0.30 s, ...)`, so for its peak on 12.000 s start it at 11.70 s. A riser ends on its peak, so it starts its own length before the reveal. earshot does not place files on a timeline: the editor, ffmpeg or the page's code does. - **A row in one file**: `earshot make "a soft ui tick" -o count.wav --events 8 --dur 1.5` answered `tick/key (1.50 s, peak at 0.81 s, -16 LUFS, clean)` and `played: 8 events as a row at 6.2 a second`: a number counting up. ### Scoring a motion video Measured on 39 reference motion-design videos (`docs/motion-sfx-study.md`); [measured] is a number from them, [convention] common practice they did not test. - Music carries the film. 34 of the 35 videos with sound are music-led [measured]; where effects stand out of t - skills/real-sound/references/design-format.md (16712 bytes)
# Design format: the JSON that mix.py renders The soundtrack is data. One top-level design (`audio/sounddesign.json`) includes one fragment per category (`audio/design/<category>.json`); `mix.py` places real recordings on the picture's cue events, mixes three buses (sfx, amb, music) and masters. Nothing is synthesized: the only processing is trim, fade, gain, pan, EQ, resampling (pitch), a gain envelope, Rubber Band tempo stretch of the music, summing and mastering. Templates: `templates/sounddesign.json` (top level), `templates/design_fragment.json` (every feature; its file names are placeholders, so it renders with `templates/cues.json` once each one is replaced by a real recording from your manifests), `templates/cues.json` (the cue file). `python` below = the interpreter `{{PY}}` described in SKILL.md. ``` python -I <skill>/scripts/mix.py --root . --design audio/sounddesign.json --cues out/cues.json --trace out/qa/adds.json python -I <skill>/scripts/mix.py --only keyboard # solo render of the fragments whose path contains "keyboard" python -I <skill>/scripts/mix.py --only keyboard --dump out/audio-review/keyboard/dump # every sample as a WAV ``` Every relative path (design, cues, outputs, each sample's `file`) resolves against `--root`. Keys starting with `_` are comments (write the reason for every non-obvious number there: `_doc`, `_about`, `_buses_doc`); `mix.py` ignores unknown keys everywhere except inside `buses` (each key there must be `sfx`, `amb` or `music`). ## Contents 1. Top level and includes 2. The cue file 3. samples 4. slices 5. pools 6. rules (cue-driven placements) 7. place (free placements) 8. ambience 9. music 10. buses and master 11. What mix.py writes 12. qa_ok: acknowledging a deliberate exception 13. Worked examples from a shipped film ## 1. Top level and includes | key | meaning | |---|---| | `duration` | film length in seconds (default: cue `total` / `fps`) | | `cues` | default cue file (the `--cues` flag wins; default `out/cues.json`) | | `include` | fragment paths; their `samples`, `slices`, `pools` are merged (a name defined twice is an error), `rules`, `place`, `ambience` are concatenated, `music` is taken when the top level has none | | `samples`, `slices`, `pools`, `rules`, `place`, `ambience`, `music` | as below (allowed at the top level too) | | `buses`, `master` | read from the top-level file only | Name everything with the fragment's prefix (`kb.`, `ui.`, `mo.`, `am.`, `mu.`): fragments are built by different agents in parallel and must never collide. Variation (cycle order, jitter, random pitch) is keyed on rule names, so a solo render (`--only`) plays exactly the same sounds as the full mix. ## 2. The cue file `{fps, total, events: [{f, kind, id?, weight?, pan?, variant?, dur?, apexFrac?, pitch?}], acts?, cue?}` or a list whose first element is that object. This is Cinetic's `out/cues.json` format (`scripts/export-cues.ts`), so a Cinetic film plugs in directly (`docs/INTEGRATION.md`). `f` is the absolute frame the sound belongs on (fractional is fine). Compute cue frames from the picture code (contact frames, 50 % pop frames, velocity peaks); typed-in sync points land 8-11 frames off in practice. A design with no rules needs no cue file. ## 3. samples `name -> {file, start?, end?, gain_db?, norm_peak_db?, mono?, fade_in?, fade_out?, eq?, pitch?, glide?, env?}`: a trimmed piece of a recording. | key | default | meaning | |---|---|---| | `file` | required | the recording (any format ffmpeg reads; decoded to 48 kHz float stereo, cached) | | `start`, `end` | 0, end of file | the trim in source seconds. Start 3-5 ms before the attack; end after the decay, before the next event | | `mono` | false | fold to mono (point sources: keys, clicks, steps). Keep stereo for whooshes, beds, wide impacts | | `eq` | none | `{hp, hp_order (2), lp, lp_order (2), peq: [[f0, q, gain_db], ...], lowshelf: [f0, gain_db], highshelf: [f0, gain_db]}` (Butterworth HP/LP, RBJ biquads) | | `pitch` | 0 | semitones by resampling (tape-style: pitch AND length change together). +2..+6 makes a hand-sized sound miniature; keep tuned material within +-2 | | `glide` | none | `[from, to]` semitones: a varispeed glide across the sample (band-limited, no aliasing) | | `env` | none | `[[t_from_sample_start, dB], ...]` piecewise-linear gain inside the sample (shape a riser, duck a tail) | | `norm_peak_db` | none | normalise the processed sample's peak to this level (makes a pool even before rule gains) | | `fade_in`, `fade_out` | 0.002, 0.012 | raised-cosine fades in seconds, applied after normalisation | | `gain_db` | 0 | static gain after everything | Processing order: mono -> eq -> pitch -> glide -> env -> norm_peak_db -> fades -> gain_db. `reverse` is refused (a reversed recording is still real, but the design keeps to what the recording is). ## 4. slices `name -> {file, start?, end?, delta?, min_gap?, gate_db?, pre?, len?, stop_before_next?, pick?, max?, ...sample opts}`: cuts a recording of many hits (typing, clicks, steps, dominoes) into single hits at its detected onsets. The slices are named `name#0`, `name#1` ... in the order they are kept. | key | default | meaning | |---|---|---| | `delta` | 0.07 | onset detector sensitivity (librosa, hop 128, backtracked); lower finds softer hits | | `min_gap` | 0.06 | seconds between onsets | | `gate_db` | -18 | drop onsets whose first 30 ms peak is this far below the loudest (handling noise, far keys) | | `pre` | 0.004 | seconds kept before each onset | | `len` | 0.16 | maximum slice length | | `stop_before_next` | true | end each slice `pre` before the next onset (never two hits in one slice) | | `pick` | all | list of onset indices to keep, in this order (after `pick`, `name#0` is the first picked) | | `max` | all | keep at most this many | | sample opts | | `mono`, `eq`, `pitch`, `glide`, `env`, `norm_peak_db`, `gain_db`, `fade_in` (0.002), `fade_out` (0.02) | Always `--dump` a slice group and read `_samples.json` (duration, peak, attack, head/tail level per slice) before using it; qa.py's edges section flags slices that start mid-sound or are cut mid-decay. ## 5. pools `name -> [sample names]`; `"group#*"` expands to every slice of a slice group (sorted by index). An unknown name or an empty pool is an error. A rule plays from a pool: one name = always that sound; several = variation. ## 6. rules (cue-driven placements) `[{name, match, pool, mode?, gain_db?, weight_db?, weight_ref?, jitter_db?, pitch?, pitch_ramp?, gain_ramp?, pan?, pan_scale?, align?, offset?, bus?, no_cue?, cycle_start?}]`. Every cue event that matches a rule gets a sound from the rule's pool; several rules matching one event LAYER it (a key: thock + bottom-out + tiny motif note). | key | default | meaning | |---|---|---| | `name` | rule index | stable name: the hash key for jitter / pitch / hash picks (renaming a rule changes its variation) | | `match` | {} | `kind` (regex, full match), `id` (regex, search), `from` / `to` (film seconds, `[from, to)`), `variant` (exact) | | `pool` | required | the pool to play | | `mode` | cycle | `cycle`: round-robin, never the same sound twice in a row (`cycle_start` = first index); `hash`: picked per event by a hash of id + frame + rule name; `fixed`: always the first | | `gain_db` | 0 | level | | `weight_db` | 0 | dB per doubling of the event's `weight` vs `weight_ref` (default 1.0): bigger events play louder | | `jitter_db` | 0 | +- random level per event (hashed: deterministic) | | `pitch` | [0, 0] | `[lo, hi]` random semitones per event (hashed) | | `pitch_ramp`, `gain_ramp` | none | `[a, b]` added across the matched events in time order: a climbing build, a decrescendo | | `pan` | "cue" | `"cue"` = the event's `pan` x `pan_scale`, or a number -1..1 | | `align` | attack | which point of the sound lands on the cue: `attack` (first ms within 20 dB of the peak; impacts, clicks, keys), `peak` (5 ms envelope maximum; whooshes), `end` (risers into a hit), `start` | | `offset` | 0 | seconds added to the cue time (a release 85 ms after a press; a tail that trails the move) | | `bus` | sfx | `sfx`, `amb` or `music` | | `no_cue` | false | the placement does not mark the event as sounded (sweeteners; the A/V audit ignores it) | Cue events no rule sounds are listed as `unsounded_events` in the report. ## 7. place (free placements) `[{sample, at, gain_db?, pan?, align?, offset?, pitch?, bus?}]`: sounds with no cue event (a crowd bed, a lift before a logo, a one-off sweetener). `at` is film seconds; `align` as in rules. ## 8. ambience `[{name?, file, src_start?, src_end?, at, until, fade_in?, fade_out?, gain_db?, eq?, width?, auto?}]`: beds on the amb bus. `src_start..src_end` is the clean window of the recording (no voices, dogs, bumps); if the bed needs more than the window it is looped with a 1.5 s equal-power crossfade (the report says `looped`). `fade_in` / `fade_out` default 1 s. `width` scales the side signal (0 = mono, 1 = as recorded, 1.15 = a little wider). `auto` = `[[film t, dB], ...]` rides inside the bed (duck birds under a run, open the room on a cut). ## 9. music `{file, src_bpm, target_bpm?, stretch?, gain_db?, eq?, segments: [{src_from, src_to, at, fade_in?, fade_out?, fade_in_at_start?, tail_fade?, gain_db?, label?}]}` | key | default | meaning | |---|---|---| | `src_bpm` | required | the track's measured tempo (arrange.py) | | `target_bpm` | 120 | the picture's tempo | | `stretch` | rubberband | `none` plays the source untouched (use it when the track is within ~0.2 % of the film tempo); otherwise the whole file is time-stretched by target/src with Rubber Band (keep the ratio within about +-6 %) | | `segments[].src_from`, `src_to` | | ORIGINAL source seconds (before any stretch), on the track's downbeats | | `segments[].at` | | film seconds where `src_from` lands; nudge by a few ms so the measured downbeat transient sits on the picture's downbeat | | `fade_in`, `fade_out` | 0.008, 0.06 | the segment starts `fade_in` before `src_from` (a pre-roll, so the downbeat's own attack is kept) and fades out over `fade_out` after `src_to` | | `fade_in_at_start` | true | false = no fade at the head (a hard cut on purpose) | | `tail_fade` | none | seconds of a longer musical fade over the end of the segment (the last chord rings out) | | `gain_db`, `label` | | per-segment level; a label that says which bars and why | Edit at bar lines: a splice from bar n's end to bar m's start works when the harmony continues (V -> I, the same chord) and the energy of the next bar is what the picture wants. `arrange.py` drafts the segment list; check every splice (qa.py edges section, earshot timeline) and write the bars and the reason in each `label`. ## 10. buses and master `buses: {sfx|amb|music: {gain_db?, eq?, auto?}}`: after everything is placed, each bus gets eq, then the `auto` ride (`[[film t, dB], ...]`, piecewise linear), then `gain_db` (the music bus first gets `music.eq` and `music.gain_db`). Rides shape the arc: the music dips under typing, lifts into the drop, settles under the logo. Put each step on a musical splice or under a transient, never in the middle of a sustained note. `master: {lufs?, ceiling?, no_glue?, no_comp?, mono_hz?}` (defaults -14, 0.77, true, false, 120): `master.py` high-passes at 28 Hz, folds below `mono_hz` to mono, compresses gently (2:1 above -14 dBFS, unless `no_comp`), then runs loudness passes with a 4x-oversampled true-peak limiter to `ceiling` (linear), a 3 ms fade-in at sample 0, a fade onto the last sample and 480 zero samples at the end. The gate passes at |LUFS - target| <= 0.5 and true peak <= -1.5 dBTP. ## 11. What mix.py writes - `--out` (default `out/audio/soundtrack.wav`): the master, 48 kHz 24-bit; the unmastered sum `premaster.wav` next to it. With `--no-master` or `--only`, `--out` is the unmastered sum itself (solo default `out/audio-review/solo/<name>.wav`). - `--stems` (default `out/audio/stems`): `sfx.wav`, `amb.wav`, `music.wav` (pre-master, they sum to the premaster). - `--report` (default `out/qa/mix_report.json`): `placements` (t, event, kind, rule, sample, gain_db, pitch, pan, align), `unsounded_events`, `buses` (peak / RMS), `ambience` (looped, body level), `music_segments`, `files_used` (every recording that is audible: the input of `credits.py` and `audit.py --report`), `premaster_peak_dbfs`; `master.json` (loudness gate) next to it. - `--cues-out` (default `out/qa/cues_sounded.json`): the cue events that received an sfx-bus sound (for an A/V audit). - `--trace FILE`: every `Mix.add()` (bus, start sample, length, gain, pan, sample / name / label, rule, kind): qa.py rebuilds every placement from it to attribute clicks, masking and harshness to a rule and a sample. - `--dump DIR`: every sample and slice as WAV + `_samples.json` (duration, peak, RMS, attack, head/tail level), then exits. ## 12. qa_ok: acknowledging a deliberate exception A sample, rule, free placement or music segment may carry `"qa_ok": "reason"` (mix.py ignores it). qa.py then lists that item's edge / sync / audibility / harshness finding as acknowledged instead of a warning: e.g. a riser choked 25 ms before a pop on purpose, a chime that rings past its cue, a hard music cut into a quiet breakdown. Use it only for decisions a critic has already confirmed, and say why. ## 13. Worked examples from a shipped film From the Clawd film (60 s, 264 placements, real recordings only), trimmed for reading. A key thock from a recording of single presses, shaped for a deep "thocky" board: ```json "kb.thock.1": {"file": "audio/assets/keyboard/fs-789628_keychron-linear-individual-keys.ogg", "start": 1.168, "end": 1.598, "mono": true, "eq": {"hp": 115, "hp_order": 6, "peq": [[190, 0.8, 3.0], [380, 0.9, 3.0], [3300, 1.3, -1.5]], "highshelf": [5000, -4.5]}, "norm_peak_db": -10.0, "fade_in": 0.004, "fade_out": 0.16} ``` Typing on 16th notes: one key per typed pixel, climbing a semitone across the run, never the same key twice: ```json {"name": "kb.type", "match": {"kind": "pop", "id": "^genesis:type"}, "pool": "kb.type", "mode": "cycle", "jitter_db": 1.5, "pitch": [1.0, 2.0], "pitch_ramp": [0.0, 1.0], "pan": 0.0, "align": "attack"} ``` Dominoes sliced into single clacks, 13 picked after measuring every slice (--dump): ```json "ty.dom": {"file": "audio/assets/toy/fs-329098_domino-pieces-hit.ogg", "start": 0.2, "end": 16.4, "pre": 0.004, "len": 0.3, "min_gap": 0.2, "gate_db": -12, "pick": [2, 10, 11, 3, 17, 22, 23, 21, 24, 9, 16, 19, 4], "mono": true, "norm_peak_db": -3, "fade_out": 0.04, "eq": {"hp": 250, "hp_order": 4}} ``` A stacking flurry that ends ON each row's lock (aligned by its end): ```json {"name": "ty.row.flurry", "match": {"kind": "pop", "id": "^swarm:row:"}, "pool": "ty.p.row.flurry", "mode": "cycle", "gain_db": -20.5, "gain_ramp": [-3, 2], "pitch_ramp": [0, 4], "jitter_db": 1.5, "pan": 0.12, "align": "end", "offset": 0.004} ``` Birdsong ducked under the hero's run (an ` - skills/real-sound/references/licences.md (7346 bytes)
# Licences: what may go into a film, how to verify it, how to credit it A launch video is commercial use, it is edited (trimmed, layered, synced to picture: legally a derivative), and it is published on platforms that scan audio. Every recording in the film needs a licence that allows all three, read on the item's own page, recorded in its manifest, confirmed by the licence audit and credited. When in doubt, leave it out: there is always another recording. ## Allowed / forbidden | licence | status | why | credit | |---|---|---|---| | CC0 1.0, Public Domain Mark | allowed | no conditions | courtesy only | | CC BY 4.0 / 3.0 / 2.5 / 2.0 | allowed | commercial use and edits allowed with attribution | REQUIRED (title, author, source link, licence link, "edited") | | Mixkit Sound Effects Free License / Stock Music Free License | allowed | free for commercial video, no attribution; read the current text at https://mixkit.co/license/ | courtesy only; never redistribute the raw files, never register the film with Content ID | | Pixabay Content License | allowed | free for commercial use, no attribution (Pixabay blocks scripted access: the user downloads by hand) | courtesy only | | CC BY-NC (any version) | forbidden | NonCommercial: a launch video is commercial | | | CC BY-ND | forbidden | NoDerivatives: trimming and syncing to picture are derivatives | | | CC BY-SA | forbidden | ShareAlike: the whole film would have to be released under CC BY-SA | | | Sampling+, Sampling | forbidden | retired, restrictive | | | "personal use", "editorial", "custom", "free with credit on social media", all rights reserved | forbidden | not a standard licence the audit can trust | | | two sources disagree ("DISPUTED") | forbidden | the strictest reading wins: reject it | | | "royalty free" with no licence text, YouTube rips, anything behind a login or paywall you would bypass, AI-generated or code-synthesized audio | not used | unknown terms, or not a real recording | | `scripts/licences.py` encodes this table (`classify()`); audit.py and credits.py use it. ## Verify on the item's own page (never from a search result, an aggregator or memory) **Freesound** (most foley, ambiences, whooshes): - The page is `https://freesound.org/people/<user>/sounds/<id>/`; the licence is in the sidebar of THAT page ("Creative Commons 0", "Attribution 4.0", "Attribution NonCommercial 4.0" ...). Licences are per sound, not per user. - Record: licence text as shown, page author, title, the date you read it (`licence_seen` in audit.json). - Originals need a login; the public high-quality preview is `https://cdn.freesound.org/previews/<id // 1000>/<id>_<user_id>-hq.ogg` (Ogg Vorbis, about 192 kbps; `-hq.mp3` also exists). `<user_id>` is the uploader's number: it must belong to the same page. audit.py checks that the id in the entry, the page and the preview URL agree. - Read the description: some authors ask for a specific credit form (e.g. "<title> by <name> (www.site) of Freesound.org"), or forbid putting raw files online. Copy the requested form into the manifest's `attribution` and any restriction into the audit's `agent_notes`. **Mixkit** (lossless WAV effects, some music): - No per-item page exists for sound effects: record the category page that lists the item and its title there. - WAV download: `https://assets.mixkit.co/active_storage/sfx/<id>/<id>.wav`. Read the licence text itself (https://mixkit.co/license/) once per session and quote what it allows in `licence_seen`. - Do not publish the raw assets folder; do not register the film's audio with Content ID or a rights-management service. **Music sites** (one licensed track carries the film): - Composer libraries that release CC BY music (e.g. Scott Buckley, scottbuckley.com.au): the licence line is on the track's page; many ask for a specific credit line: use it verbatim. - Aggregators (chosic.com and similar) are not authoritative: confirm on the artist's own page. A real case: an aggregator listed a track as CC BY 3.0 while the artist's page said "free with credit on social media" (copyrighted): rejected as disputed. - Free Music Archive, Internet Archive, SoundCloud: the licence is per track and often NC or ND: read it every time. - YouTube Audio Library, platform libraries: terms tied to one platform: ask the user before using. **Pixabay**: scripted downloads are blocked (bot protection). If a Pixabay item is the best choice, give the user the page link and ask them to download it into the assets folder; then audit it like any other file. ## Attribution (CC BY) A complete credit names the Title, the Author, the Source (link to the item page), the Licence (name + link) and says it was modified. The manifest's `attribution` holds the line the author asked for (or this default): ``` "Rain on Windows, Interior, A.wav" by InspectorJ (www.jshaw.co.uk) of Freesound.org (https://freesound.org/people/InspectorJ/sounds/346642/), licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/) ``` `credits.py` writes `CREDITS.md` (music + every sound, grouped by licence, with the sentence saying how the recordings were edited) and `out/CREDITS_description.txt` (paste it into the video description). It completes a requested line with the source link and the licence link when the author's form leaves them out. Credits never need to be on screen. ## Content ID and CC BY music Some composers register their CC BY tracks with YouTube Content ID through a distributor. A video using the track correctly can still get an automatic claim. The licence still allows the use: put the credit in the description, and if a claim arrives, dispute it citing the licence and the credit (many composers also clear claims on request). Choose a track whose composer explains this on their site, and tell the user before publishing. Mixkit and Pixabay forbid the reverse: never register a film that contains their items with Content ID. ## The audit (scripts/audit.py, prompts/licence_audit.md) 1. The licence auditor opens every in-scope item's page, reads the licence and writes `licence_seen` (quote + URL + date + page author/title) and `licence_confirmed: true` into `audio/assets/manifests/audit.json` (format: `templates/audit_entry.json`). Never confirm a page you did not read in this session. 2. `audit.py --report out/qa/mix_report.json` classifies every manifest entry, checks ids and URLs, checks every file (exists, codec, rate, channels, duration vs the manifest, decodes without errors), merges the auditor's fields and writes audit.json + a Markdown table. In-scope = audible in the film. Exit 1 while any in-scope recording is blocked. 3. `--fetch` compares the local bytes with `download_url` (sequential, 1.5 s apart, a clear User-Agent, in memory, nothing executed; never Pixabay). Re-encoded or edited files show up here. 4. `credits.py --audit audio/assets/manifests/audit.json` refuses to call the credits clean while a used recording is unconfirmed. On the Clawd film this caught four used recordings (celesta notes added after the hand audit) with no audit record. Their manifest notes do say the licence was read on the Freesound page, so it was a bookkeeping gap, not an unverified licence: audit.py quotes such a note and asks the auditor to copy it into `licence_seen`. - skills/real-sound/references/process.md (14064 bytes)
# The process: how a real-recordings soundtrack gets built by agents who cannot hear This is the process that built the Clawd film's soundtrack (60 s, 83 real recordings, 264 placements, reproduced bit-identically by `scripts/mix.py`), generalised. Agents cannot listen, so every decision is measured, every claim is backed by a command, and the work is split so that parallel agents never edit the same file. ## Contents 1. Roles and files 2. The steps 3. What each critic measures (and the qa.py section that automates it) 4. Thresholds and where they come from 5. Variants: how critics test a fix without touching the design 6. Rounds, stopping, reporting ## 1. Roles and files | role | prompt | owns (writes) | reads | |---|---|---|---| | lead | SKILL.md | `audio/SOUND_BRIEF.md`, `audio/sounddesign.json` (top level: include list, buses, master), final reports | everything | | sourcing agent (one per category) | `templates/prompts/sourcing.md` | `audio/assets/<category>/`, `audio/assets/manifests/<category>.json`, `out/audio-review/<category>/` | brief | | licence auditor | `templates/prompts/licence_audit.md` | agent fields of `audio/assets/manifests/audit.json` | manifests, item pages | | music supervisor | `templates/prompts/music_supervisor.md` | `audio/assets/manifests/music_choice.json`, `audio/design/music.json` | music candidates, picture map | | designer (one per category) | `templates/prompts/designer.md` | `audio/design/<category>.json` | its manifest, cues, solo renders | | critic (one per lens) | `templates/prompts/critic_*.md` | only `out/audio-review/critic_<lens>/` (variants, measurements) | the whole render, design, trace | | fixer (exactly one) | `templates/prompts/fixer.md` | every fragment + top-level buses/master during the fix round | all critic reports | **Filling a prompt.** The lead replaces every `{{NAME}}` before handing a prompt to a sub-agent; an unfilled placeholder must never reach one. The common ones: `{{PY}}` = the full path of the Python that has numpy, scipy, soundfile and earshot (see SKILL.md, e.g. `<earshot repo>/.venv/Scripts/python.exe`); `{{SKILL}}` = this skill's folder; `{{ROOT}}` = the film project root; `{{CATEGORY}}` = the sound category the agent owns; `{{FILM}}` = the film's name; `{{ROUND}}` = the critique round number; `{{RENDER}}` = the folder of the render under review (soundtrack.wav, stems); `{{REPORT}}` / `{{TRACE}}` / `{{QA_JSON}}` = its mix report, placement trace and qa.py report; `{{VIDEO}}` = the rendered film; `{{CUES}}` = the cue file. The rest (`{{NEED_DESCRIPTION}}`, `{{KEY}}`, `{{BPM}}`, `{{DROP_T}}` ...) are explained in the prompt that uses them. ## 2. The steps 1. **Cue list from the picture.** `out/cues.json` (format in `templates/cues.json`; Cinetic writes it with `export-cues.ts`). Sync frames are computed from the picture code (contact frames, 50 % pops, velocity peaks), never typed. Check the event kinds and ids are stable enough for rules to match with a regex (`act:thing:n`). 2. **Brief.** `audio/SOUND_BRIEF.md` from `templates/SOUND_BRIEF.md`: concept, picture map (every cue with what is on screen and the sound need), ambience zones, licences, quality bar, file layout, manifest format. The brief is the contract every sub-agent receives verbatim. 3. **Sourcing, per category, in parallel.** 15-40 candidates per category, licences read on each item's page, downloads polite (sequential, a pause between requests), each file measured (`analyze.py`, spectrogram PNG) and heard through earshot (`realness` gate, `describe` / `match` / `rank` against the need, `find` for the best take), ranked per need in the manifest with notes saying exactly what to use and what to avoid. 4. **Licence audit.** The auditor reads every candidate's page and records `licence_seen`; `audit.py` checks the rest. Nothing unconfirmed reaches the design. 5. **Music supervisor.** Measures every music candidate (`analyze.py --music`, `arrange.py`), verifies the beat grid and the downbeats against transients (the beat tracker lags attacks by 20-50 ms; arrange.py corrects the phase), picks the winner with reasons, and writes the edit: segments at bar lines, the drop's downbeat on the hero frame, each splice labelled with its bars and why it works. 6. **Design fragments, per category, in parallel.** Each designer trims samples (earshot `find` gives trims; `--dump` checks them), builds pools and rules on the cue events, and verifies the fragment alone: `mix.py --only <category>` (solo render, same variation as the full mix), `qa.py --only <category>`, `earshot timeline` of the solo with the cues. A designer never touches another fragment or the top level. 7. **Integrate.** The lead runs the full mix with `--trace`, then `qa.py` and earshot (`timeline`, `sheet`, `critique` against the launch-film profile). Fix blockers (missing files, failed gate) before critique. 8. **Critique, in parallel, read-only.** Five lenses (sync, edges, masking, tonal, director), each with its own prompt. Each critic measures, tests its proposed fixes as variants in its own folder (section 5) and returns ranked issues with exact JSON operations. Critics never edit the design. 9. **One fixer.** Merges the critics' operations, resolves conflicts (masking wants a hit louder, tonal wants its 2-6 kHz softer: the fixer finds the change that satisfies both, e.g. louder low body + softer top), applies them, re-renders, re-runs qa.py and compares with the previous round (nothing that passed may now fail). One writer avoids lost edits and contradictory fixes. 10. **Master and gate.** `mix.py` masters (`master.py`): integrated LUFS within 0.5 of the target, true peak at most -1.5 dBTP on the WAV; then check again after the AAC encode (about -1 dBTP). 11. **Credits.** `audit.py --report out/qa/mix_report.json` (exit 0) then `credits.py --audit ...` (exit 0): CREDITS.md and the video-description text. 12. **Mux.** `mux.mjs` (stream copy of the picture, AAC 320k, cut to the picture's duration); verify the audio track of the MP4 against the WAV (lag 0 samples) and run `earshot timeline film.mp4 --cues out/qa/cues_sounded.json` on the finished file. ## 3. What each critic measures | lens | question | measurements (Clawd critic scripts, now qa.py) | typical fixes | |---|---|---|---| | **sync** | does every sound land on its cause? | per event: attack, 5 ms peak and 50 ms apex of the rebuilt event vs its cue (qa.py sync); risers by their end; per-frame picture motion around the event (frame differences of the film, earshot timeline cut/cue sync); envelope shape of each dumped sample (attack, -3/-6 dB span); solo renders of one rule | `align` (attack/peak/end), `offset`, a trim that starts closer to the attack, a different take whose peak is earlier | | **edges** (clicks) | is anything cut, clicked or truncated? | > 14 kHz bursts concentrated in 1 ms in the master and every stem, attributed to the layer carrying the burst (qa.py clicks); unfaded head / tail of each used sample vs its peak and the source just outside the trim; second hits inside a sample; slices; placements past the film ends; music splices (the source level just after a segment end vs what enters) (qa.py edges) | longer `fade_in`/`fade_out`, move `start` 3-5 ms before the attack, end after the decay, `stop_before_next`, a different splice bar, `tail_fade` | | **masking** (audibility, density) | can every effect be heard, and is the effect layer dense or repetitive? | per event: 1/3-octave margin vs the bed and vs everything else over its loudest 60 ms and its first 20 ms (`read_db`), per layer (dead layers); onsets per second; sample and take reuse; per-rule regularity (inter-onset CV, gain and pitch spread, distinct samples) (qa.py audibility, density); A/B variants of crowd beds | gain, EQ that carves the effect's band (or the bed's), a brighter take, fewer layers, a bus ride under the moment, more takes in a pool, `jitter_db` | | **tonal** | is it pleasant on phones and laptops? | per event 2-6 kHz 5 ms peak vs the music's loudest (qa.py harshness) and its centroid; band levels over time of master vs stems (2-6k, 6-10k, 10-16k, >16k); low end under 120 Hz (mono, the impact's low partials vs the music's at the drop: beating); stereo width per section; tuned samples vs the key; limiter gain reduction at candidate (lufs, ceiling) settings | `highshelf` / `peq` cuts, `norm_peak_db` down, `mono`, `lp`, a pitch to the key, `master.lufs` / `ceiling` | | **director** | does the soundtrack tell the film's story? | momentary / short-term loudness of the master and each stem across the picture map's beats, LRA, section medians, the loudest moment's position, the drop vs the logo, every beat's sfx and music peaks, ambience sources per zone (qa.py loudness + earshot timeline + sheet + critique) | bus rides, the music edit, which events are sounded, the ending | ## 4. Thresholds and where they come from | check | threshold | source | |---|---|---| | click | > 14 kHz sample > 9x its 20 ms RMS and > 6x its 4 ms RMS, >= 80 % of the burst's energy in 1 ms | Cinetic av-audit's detector, ported (the same 7 click times as av-audit on the Clawd master: a check of the port, not independent validation) | | click at an edge = a cut | the carrying layer's start or end within 2 ms | qa.py (fail); inside a recording = warn (the recording's own crisp transient, or a defect in the source) | | abrupt entry | source 20 ms before the trim within 20 dB of the trim's peak, fade-in < 5 ms, and no attack within 10 ms to cover it (or the source within 10 dB) | Clawd critic_clicks edges.py (-30 dB listing), tightened so attacks that follow at once are not flagged | | chopped decay | unfaded tail > -35 dB re peak, the source after the trim > -35 dB, fade-out < 30 ms | Clawd critic_clicks edges.py | | chopped music | the source keeps sounding after `src_to` (within 6 dB) and is 6 dB above what enters, fade-out < 100 ms, no `tail_fade` | qa.py (generalises the supervisor's splice listings) | | audibility | read = max(60 ms margin vs everything, 20 ms margin vs everything) over bands within 30 dB of the effect's strongest: >= 6 clear, 3-6 ok, 0-3 barely, < 0 masked | Clawd critic_masking measure.py | | harshness | an event's 2-6 kHz 5 ms RMS more than 6 dB over the music's loudest 2-6 kHz 5 ms RMS | qa.py (the critic listed both levels; the 6 dB margin is a judgement); centroid > 6.5 kHz noted (norm) | | sync | impacts: attack >= -45 ms and peak <= +75 ms from the cue; whooshes and peak-aligned swells: apex within +-45 ms; risers and end- / attack-aligned swells: audible end (last sample above -20 dB re its peak) -250..+30 ms (checked at -300..+60); a deviation that one layer's rule offset removes is listed as deliberate, naming that rule | measured norms of pro launch films (Cinetic sound.md §13) | | machine gun | a rule with >= 4 events, one sample, pitch sd < 0.1 st, gain sd < 0.5 dB | Clawd critic_density metrics.py (regularity table) | | loudness | integrated within 0.5 LU of the target (fail), true peak <= -1.0 dBTP (fail), last 50 ms <= -45 dBFS RMS and last 10 ms <= -60 dBFS peak (fail), first 5 ms <= -40 dBFS (warn), LRA 4-10 LU (warn), loudest moment before 85 % of the runtime (warn) | master.py gate, Cinetic av-audit head/tail, norms | What qa.py flagged on the finished Clawd mix (which had been through five critics and a supervisor): 7 clicks in the master, all inside recordings (the detector is av-audit's, so these are the transients the critics had already heard about and accepted as crisp), 5 of 153 events masked (busy stacking moments), 3 events hot at 2-6 kHz, 2 edge defects (one a deliberate 25 ms choke, one a deliberate music cut into the meadow), no sync defect (4 events sit off their cue by exactly a rule offset, listed as deliberate with the rule that explains each), 2 cue events unsounded. Treat findings as questions for a critic, not as orders; acknowledge confirmed exceptions with `qa_ok` (design-format.md §12). ## 5. Variants: how critics test a fix without touching the design A critic writes its proposed operations to a JSON list and lets `variant.py` copy the design (top level + fragments) into its own folder, apply them, render with every output inside that folder and run qa.py on the result: ``` python -I <skill>/scripts/variant.py --ops out/audio-review/critic_tonal/ops_v1.json \ --out out/audio-review/critic_tonal/v1 --render --qa [--cues out/cues.json] ``` It prints every change as old -> new (an operation that matches nothing writes nothing), then the mix's gate line and the qa digest; `v1/qa.json` sits next to the base render's `out/qa/qa.json` for a before / after comparison. The critic reports those numbers next to each proposed operation. Operations are exact and small: `{"f": "keyboard", "sample": "kb.thock.1", "set": {"norm_peak_db": -10}}`, `{"f": "motion", "rule": "mo.leap.air", "set": {"offset": 0.30}}`, `{"sd": "buses.music.auto", "value": [[0, 0], ...]}` (all forms in `templates/prompts/fixer.md`). The fixer applies the merged list to the real files with `variant.py --apply` (originals copied to `--backup` first). Variants catch interactions nobody predicts by reading JSON. A real case on the Clawd design: a 4 dB high-shelf cut on a plastic "toy open" sample made its event LOUDER at 2-6 kHz (-15.8 -> -15.2 dBFS), because `norm_peak_db` renormalises the sample after EQ (design-format.md §3, processing order); the fix is a lower `norm_peak_db` with the cut. ## 6. Rounds, stopping, reporting - One critique round + one fix round is the minimum; a second round when the first fix round changed levels or the music edit. Stop when qa.py shows no fail, every remaining warn is acknowledged with a reason, and the director lens has no P0. - Every number in a report comes from a command that was run; the report lists the commands. - Keep `out/audio-review/` (critic folders, variants, dumps): it is the audit trail of why each number is what it is. - skills/real-sound/references/sound-design.md (11143 bytes)
# Sound design rules: launch videos and code-made films The rules the designers, critics and fixer work from. Numbers marked *(norm)* are measured norms of top-tier launch films (from the Cinetic skill's measurements, `references/sound.md` §13 there); the rest is practice that held up on shipped films. The earshot repo's `docs/launch-video-sound.md` profiles 7 professional reference launch films in depth (earshot's bundled launch profile); use it for the targets of a specific film, this file stands alone for the craft. ## 1. The bar - **Every sound has a visible cause**, at a loudness that matches the cause: a caret blink whispers, the hero reveal hits. Not every picture event gets a sound; once a class of action is sounded, every instance is, at one level. - **Real and close.** Professional recordings: close-miked, dry, clean (floor under -55 dBFS between events), full bandwidth (95 % rolloff above 12 kHz), no clipping, no room of their own, no background events. - **One palette.** One material family per film (felt + wood, glass + soft plastic, metal + air), one click voice, one keyboard, one music track. A different material for every sound is the fastest way to sound cheap. - **The music carries the film.** Effects punctuate; the music's own events (drop, stop, re-entry) carry the big moments and most cuts. - **Restraint.** About 5 designed effects per 10 s *(norm; 0-28)*, clustered where the music is sparse (cold open, typing, logo build) and thinning out after the drop. Good sound design mostly disappears. ## 2. Launch-video grammar (picture event -> sound) | picture | sound (real source) | where it sits | level / notes | |---|---|---|---| | cursor moves, hovers, scrolls, progress bars, streaming text, rolling counters | nothing | | the music carries continuous motion | | cursor click / tap / press | one real click voice for the whole film: mouse, trackpad, phone tap on glass; press + release 60-110 ms later (about 85, release 0-3 dB quieter) *(norm)* | the press frame (clicks land 10-30 ms before the visible press in pro films) | about 3 dB under the music's short-term level, 12-20 dB over it above 3 kHz *(norm)*; bright but short (-20 dB within 6-10 ms); centred; the same level every time | | typing | sliced real keyboard (mechanical or laptop, one board per film); space / return deeper and longer | each sounded key on its character frame; at most ~12 keys/s; above ~25 chars/s one key per word or silence *(norm)* | music dips 6-10 dB under the run; vary the key sample and level (sigma ~2 dB, no jump over 6 dB), not random pitch; most on-screen typing in pro films is silent *(norm: ~75 %)* | | a card / chip / toast / badge appears | a soft real pop or tick: cork, mouth pop, plastic click, wood block, pitched up for size | 50 % of its travel | a run climbs (`pitch_ramp` +1..+3 st); +2..+9 dB over the music for word-like pops *(norm)* | | toggle, switch, lock-in, snap into place | a real latch, switch, magnet clack, Lego click | the contact frame | short; in sync within a frame | | a counter or metric locks on its value | one crisp tick on the final value only | the lock frame | about 8 dB under the music *(norm)* | | a camera-scale move, whip, zoom into the product, logo zoom | a real swish (bamboo, stick, cloth, cape, air past the mic) | apex on the move's velocity peak, onset 100-450 ms ahead *(norm)* | about 2 per film, never on every cut; may be wide; travels with the motion (pan) | | hard cuts | nothing | | about 85 % of cuts in pro films have no sound of their own *(norm)* | | tension into the reveal | a real riser: cymbal roll (yarn mallets), orchestral swell, the music's own build | ends 30-250 ms before the hit (a beat of air), or stops on it | in about 40 % of films *(norm)*; never a crash cymbal on the hit | | the hero reveal / the turn | the music's DROP lands on it (edit the track so its downbeat is on the frame); optionally one real impact: drum, taiko, kick, felt sub hit, with a short top transient | the contact / cut frame | the loudest moment of the film, at 30-60 % of the runtime, +2..+7 LU over integrated *(norm)* | | the logo / lockup | the music stops on a bar line or filters down, 0.2-0.7 s of near-silence, then ONE soft resolved element: a bell, celesta or piano note in the track's key, a soft swell | the frame the wordmark becomes readable (its settle), never later | 8-20 dB under the film's peak *(norm)*; a 0.5-2.5 s tail to below -60 dBFS, then silence | | product objects (a phone, a card, a box) | real foley of the object's material | contacts | dry, centred | ## 3. Music - **One licensed track** at 110-130 BPM (or half-time 55-65) whose structure fits the film: soft intro, groove, a breakdown or stop at 40-80 % of the runtime, a drop for the hero reveal, a resolve. Steady tempo, 4/4, professionally mastered, full bandwidth, instrumental. - **Avoid:** vocals, corporate ukulele + whistling, EDM brostep, lo-fi hiss, trailer braams on a product film, dark/tense moods for a friendly product, famous overused stock tracks. - **Match the brand's personality:** calm/literary -> soft piano, felt, strings, no booms; fast/exact -> tight drums, plucks, a drop on true silence; bright/friendly -> marimba, claps, pops, major key; precise/expensive -> sparse piano, low strings, air; raw/mechanical -> ticks, latches, metallic hits; warm/kind -> plucked strings, soft pads. - **Edit at bar lines** (`arrange.py`): the picture is cut on the grid (120 BPM = 2 s bars at 4/4), the music is cut on its downbeats, splices continue the harmony (V -> I, or the same chord), and the drop's downbeat lands on the hero frame. Stretch only when the tempo is off by more than ~0.2 %, and by at most ~6 %. - **Shape with rides, not with new music:** dip under typing, lift into the drop, settle under the logo (`buses.music.auto`). ## 4. Levels, arc and mix - -14 LUFS integrated for web and social; true peak at most -1 dBTP after the AAC encode (`master.ceiling` 0.77 gives that). -15/-16 only for a stated reason (a dynamic orchestral track the limiter would squash). - LRA 5-9 LU for a film with an arc *(norm: 1-2 sounds crushed)*; the intro 5-12 LU under the body for its first 2-3 s, entering with intent on frame 0 (no fade over the first bar, no click on sample 0). - The loudest momentary sits on the drop / hero reveal, not on the logo, not in the last 15 %. - Effects are dry, mono and centred (+-0.15 pan); only whooshes, risers, ambiences and the music are wide. Low end below ~120 Hz is mono (master.py folds it). - Every effect at least +3 dB over the bed in its own best band (qa.py `read_db`; >= 6 is clear); a layer that adds nothing measurable is a wasted placement (qa.py `--layers`). - Nothing in the 2-6 kHz band much louder than the music's own loudest presence peaks (qa.py harshness): that band hurts first on phones and laptops. Effect centroids at or below 6.5 kHz *(norm)*; pings at 9-14 kHz fatigue. ## 5. Sync - Impacts, clicks, keys, pops: `align: attack` on the contact / press / 50 % frame. Whooshes: `align: peak` on the velocity peak. Risers: `align: end` on (or 30-250 ms before) the hit. Beds and crowds: `align: start`. - A sound that leads its picture by more than ~45 ms reads as "sound first"; one that peaks more than ~75 ms late reads as late *(norm: accents land -45..+75 ms, median +8)*. Move the picture to the beat, not the sound off its cause. - Check slow-attack samples: an attack-aligned sample whose peak comes 80 ms after its first transient lands late (qa.py sync reports attack and peak per event). - Cue frames are computed from the picture code; typed-in times land 8-11 frames off *(Cinetic, in practice)*. ## 6. Variation without randomness - A repeated action draws from a pool of 4+ takes (`mode: cycle`: never the same take twice in a row), +-1-2 dB jitter, +-0.3-0.5 st pitch at most (real keyboards do not change pitch per key: vary the take, not the pitch). - The UI click is the exception: one voice, one level, every time. - A progression climbs: `pitch_ramp` across a run of pops or stacking blocks, `gain_ramp` into a build. - Machine-gun (one sample, no variation, regular rhythm) is the second-fastest cheap tell; qa.py density flags it. ## 7. Tuning - Tuned elements (chimes, bells, celesta, a motif) play in the track's key (`analyze.py --music` and `arrange.py` estimate it); tune a recording by resampling (`pitch`) within +-2 semitones; choose a recording near the right note rather than shifting far. - Booms and subs on the track's root, or neutral (unpitched) at least; an untuned boom under a resolving chord sounds cheap even to people who cannot say why. ## 8. Film foley (character pieces, miniatures, worlds) - **Scale through pitch and closeness:** a 1 cm character's steps are fingertip taps pitched +2..+6 st, close and dry; a giant's are slowed (-3..-6 st) heavy foley with a longer tail. - **Layer by role:** body (the weight, 100-400 Hz) + transient (the crisp contact, 2-6 kHz, short) + detail (material: rattle, creak, rustle). Each layer is one rule on the same cue; check each adds something (`--layers`). - **Ambience zones:** one bed per location, from clean windows of real field recordings (no voices, traffic, planes, dogs unless the story wants them), cut with the picture's cuts, ducked under key actions with `auto`. - **Materials stay consistent:** the same key always sounds like the same key; the same surface like the same surface. ## 9. Choosing a recording (agents cannot listen: measure) - `analyze.py` (format, floor, bandwidth, clipping, onsets, spikes in an ambience, tempo/key for music) and the spectrogram PNG; `earshot describe / match` (does it sound like the description? use earshot's verdict words: strong z >= 3, plausible 2.5-3, weak 2-2.5, no match below 2), `earshot rank` (sort candidates), `earshot find` (the best take inside a long recording: ready-made trims), `earshot compare --refs` / `earshot ab` (closer to approved references?), `earshot realness` (a real recording, not code-synthesized: require "real or pro-produced" on the trim you use; an "uncertain" needs its evidence read and written down). - Prefer: lossless or HQ previews (Freesound -hq.ogg, Mixkit WAV), 44.1/48 kHz or higher, many takes of the same object (variation for free), a clean floor between takes. - Reject: clipped, low-bitrate (a cliff above 16 kHz), roomy foley, anything with voices or bumps inside the window you need, anything whose licence you cannot read on its own page. ## 10. The cheap tells (what makes a soundtrack sound like random stock effects) Code-synthesized beeps, sine pings and noise sweeps; one sample machine-gunned; a whoosh on every cut; a boom on every logo; sparkle / shimmer sweeps standing in for "magic"; reverb on tiny sounds; random pitch on typing; partial coverage (some presses heard, others silent); clicks at cuts; music chopped mid-note at a splice; an audible ambience loop; a different room on every sound; the logo louder than the drop; an ending that stops mid-note instead of a tail into silence.
- skills/real-sound/references/troubleshooting.md (6281 bytes)
# Troubleshooting ## mix.py | symptom | cause | fix | |---|---|---| | `cue file out/cues.json not found (the design has cue rules)` | no cue file at the default path | pass `--cues path` or set `"cues"` in the design | | `set "duration" (seconds) in the design or "total" (frames) in the cue file` | neither is known | add `"duration"` to the top-level design | | `KeyError: 'pool X: unknown sample Y'` | a typo, or a slice group without `#*` | fix the name; `"kb.type#*"` expands every slice | | `ValueError: pool X is empty` / `slices F: no onsets found` | the slice window has no onsets above the gate | widen `start`/`end`, lower `delta` (0.05), lower `gate_db` (-24), check the file with `analyze.py` | | `KeyError: 'fragment.json: samples "x" is defined twice'` | two fragments use one name | prefix every name with its category (`kb.`, `mo.`) | | `KeyError: '_doc'` in the bus loop | a comment key inside `buses` | move comments to `_buses_doc` at the top level | | `ValueError: reverse is not used` | a sample asks for `reverse` | find a recording that already has the shape (a real swell, a reverse cymbal recorded as such) | | `rubberband failed` | the ffmpeg build has no librubberband | use `"stretch": "none"` when the track is within ~0.2 % of the film tempo, else ask the user for an ffmpeg with rubberband (`ffmpeg -filters | grep rubberband`) | | `master gate FAILED` | integrated loudness or true peak missed | read `master.json` next to the report: lower `master.lufs` by 1 for a dynamic track, or trim the loudest peaks (often one impact or the drop's first beat) with a bus ride; `ceiling` 0.77 leaves AAC headroom | | the first run is slow | every recording is decoded once (and the music stretched once) | later runs read `out/audio/cache` (keyed on path, size, mtime); `--cache DIR` moves it | | a solo render "has no file" | older habit: looking for premaster.wav | `--only NAME` writes the unmastered mix to `--out` (default `out/audio-review/solo/<NAME>.wav`) | | the solo sounds different from the full mix | a rule without `name` (variation keyed on its index) | name every rule; then solo and full mix play identical placements | | an event is in `unsounded_events` | no rule matches its kind / id / time | add a rule, or accept it on purpose (qa.py coverage lists partial classes, which read as mistakes) | ## qa.py | symptom | cause | fix | |---|---|---| | sections "skipped: needs the trace" | the mix ran without `--trace` | re-run `mix.py ... --trace out/qa/adds.json` | | `trace (N placements) and report (M) disagree` | the trace and the report come from different runs or a different `--only` | re-render with both from one run; pass the same `--only` to qa.py | | `placement(s) could not be rebuilt` | the design changed after the mix | re-render before qa | | a click "inside a recording" | the recording itself has a crisp transient (a tick, a pop) or a defect (a digital click, a bump) | `--dump` the sample and look at its spectrogram (`analyze.py --png`); if it is a defect, trim around it or use another take; if it is the sound itself, acknowledge with `qa_ok` | | a music splice "chops the music" | the outgoing segment ends while its note still sounds and the next one is quieter | end the segment where the chord has decayed, splice into a louder bar, add `tail_fade`, or acknowledge a deliberate hard cut with `qa_ok` | | many "bright" notes | a tiny-object palette (plastic, glass, bells) is bright by nature | fine when it is the film's palette; otherwise a `highshelf` cut or a darker take | | `--listen` says earshot is not importable | earshot is not installed in this Python | `pip install -e <earshot repo>`, or run qa.py without `--listen` and call `python -m earshot ...` separately | ## audit.py / credits.py | symptom | fix | |---|---| | every recording "licence not verified" | the auditor has not recorded `licence_seen` / `licence_confirmed` in `audio/assets/manifests/audit.json` yet: run `templates/prompts/licence_audit.md` | | `licence_seen reads as X but the manifest says Y` | the page and the manifest disagree: re-read the page, fix the manifest's `license`, or reject the item | | `used in the film but in no manifest` | a file was added to a fragment without a manifest entry: add the entry (and audit it) or remove the sound | | `entry id ... but the Freesound page is sound ...` | the entry, the page and the download URL describe different sounds: re-download from the right page | | credits list "PROBLEMS" | a used recording is forbidden, unknown, unconfirmed or lacks author / title / page_url: fix before publishing | ## Sources and downloads | symptom | fix | |---|---| | Freesound preview 404 | the preview folder is `id // 1000` and the number after `_` is the uploader's user id (take it from the page's player) | | Pixabay returns 403 / a challenge page | Pixabay blocks scripted downloads: give the user the link and ask them to download the file | | a Mixkit item has no page | Mixkit SFX have none: record the category page and the listed title | | a file decodes with errors | re-download; prefer the lossless (Mixkit WAV) or HQ (Freesound -hq.ogg) version | ## Mux and delivery | symptom | fix | |---|---| | true peak over -1 dBTP after AAC | lower `master.ceiling` (0.77 -> 0.72) and re-render; measure the MP4's decoded audio with `python -m earshot measure film.mp4` (`master.py --measure` reads WAV / FLAC only) | | the audio ends early | the soundtrack is shorter than the picture: set `duration` to the picture's length (mux.mjs reports the mismatch) | | sync looks off | `mux.mjs` stream-copies the picture and cuts the audio to the picture's duration; cross-correlate the MP4's decoded audio with the WAV (lag must be 0) and check the cue frames; never re-time the audio to fix a picture-side offset | ## Platform - Run the scripts with `python -I` (isolated: downloaded files can never shadow a module); the scripts add their own folder to the path themselves. - Console output is ASCII (Windows cp1252 consoles); quote paths with spaces (`--root "/path/to/my film"`). - `mix.py`'s audio maths are frozen: the Clawd soundtrack reproduces bit-identically (`sha1 b48c5e8872fe96765624f88db18a0b49a0a05d68`). Change the DSP only with a new version and a new reference.
- skills/real-sound/scripts/analyze.py (13724 bytes)
#!/usr/bin/env python """Objective analysis of downloaded audio assets (we cannot listen, so we measure). python -I <skill>/scripts/analyze.py FILE [FILE ...] [--music] [--png DIR] [--out OUT.json] [--json] Prints one plain-language line per file (then a summary line; exit code 1 when a file is missing or does not decode); --out writes every measurement as a JSON list, --json prints that list instead of the lines. Every file is decoded with ffmpeg to 48 kHz float stereo (a mono source is duplicated at unity gain). Reports per file: format (codec, source rate, channels, bitrate), duration, peak / RMS / integrated LUFS, noise floor (10th percentile of 20 ms RMS), clipping, DC, the first transient (attack) time, onset times, spectral centroid, bandwidth (95% rolloff), and "spikes" (sudden events far above the median level: useful to catch dogs, voices, bumps inside an ambience). With --music also: tempo + beat times (librosa), tempo stability, key estimate (Krumhansl), loudness per 2 s and per bar, and novelty-based section boundaries. With --png: a spectrogram + waveform image per file (ffmpeg showspectrumpic), to look at with an image viewer. Reading the numbers (rules of thumb for picking recordings): foley / SFX noise_floor_dbfs < -55 between events, clipped_samples 0, rolloff95_hz > 12 kHz (not dull), a band_db_rel_1_4k['16-19k'] cliff far below '12-16k' means a low-bitrate encode; spikes_over_12db inside an ambience = single events (dog, voice, bump) to avoid or cut around. ambience level_std_db_100ms small (steady bed), side_to_mid_db > -12 (real stereo; null = mono), no spikes, >= 40 s usable. music tempo + ibi_std_ms small (steady grid), key, rms_db_per_bar (the arc), sections_at (edit points). """ import argparse, json, os, subprocess, sys, math, warnings import numpy as np SR = 48000 def probe(path): try: out = subprocess.run(['ffprobe', '-v', 'error', '-select_streams', 'a:0', '-show_entries', 'stream=codec_name,sample_rate,channels,bit_rate:format=bit_rate,duration', '-of', 'json', path], capture_output=True, text=True, timeout=60).stdout j = json.loads(out) s = (j.get('streams') or [{}])[0] f = j.get('format') or {} brs = [int(b) for b in (s.get('bit_rate'), f.get('bit_rate')) if str(b).isdigit() and 0 < int(b) < 10 ** 7] return {'codec': s.get('codec_name'), 'src_rate': int(s.get('sample_rate', 0) or 0), 'channels': int(s.get('channels', 0) or 0), 'kbps': round(brs[0] / 1000) if brs else None} except Exception as e: # noqa return {'probe_error': str(e)} def decode(path, channels=2): """(n, 2) float32 at SR; a mono source is duplicated at unity gain (ffmpeg's own upmix is 3 dB down)""" ch = 1 if channels == 1 else 2 p = subprocess.run(['ffmpeg', '-v', 'error', '-i', path, '-map', '0:a:0', '-f', 'f32le', '-acodec', 'pcm_f32le', '-ac', str(ch), '-ar', str(SR), '-'], capture_output=True, timeout=600) if p.returncode != 0 or not p.stdout: raise RuntimeError(p.stderr.decode(errors='replace').strip()[:400] or 'no audio decoded') x = np.frombuffer(p.stdout, dtype=np.float32).reshape(-1, ch) return np.repeat(x, 2, axis=1) if ch == 1 else x.copy() def db(x): return float(20 * np.log10(max(float(x), 1e-12))) def frame_rms(mono, win): n = len(mono) // win if n == 0: return np.array([np.sqrt(np.mean(mono ** 2) + 1e-20)]) f = mono[: n * win].reshape(n, win) return np.sqrt(np.mean(f ** 2, axis=1) + 1e-20) KK_MAJ = np.array([6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88]) KK_MIN = np.array([6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17]) NAMES = ['C', 'C#', 'D', 'Eb', 'E', 'F', 'F#', 'G', 'Ab', 'A', 'Bb', 'B'] def key_estimate(chroma_mean): best = [] for mode, prof in (('major', KK_MAJ), ('minor', KK_MIN)): for k in range(12): r = np.corrcoef(chroma_mean, np.roll(prof, k))[0, 1] best.append((float(r), f'{NAMES[k]} {mode}')) best.sort(reverse=True) return [{'key': b[1], 'r': round(b[0], 3)} for b in best[:3]] def analyze(path, music=False): import librosa warnings.filterwarnings('ignore', message='n_fft=') # very short sounds: librosa pads, the numbers stay usable info = {'file': path.replace('\\', '/'), **probe(path)} y = decode(path, info.get('channels')) mono = y.mean(axis=1) n = len(mono) info['duration'] = round(n / SR, 3) if n < SR * 0.02: info['error'] = 'too short' return info peak = float(np.max(np.abs(y))) info['peak_dbfs'] = round(db(peak), 2) info['rms_dbfs'] = round(db(np.sqrt(np.mean(y ** 2))), 2) info['clipped_samples'] = int(np.sum(np.abs(y) >= 0.999)) info['dc'] = round(float(np.mean(mono)), 5) try: import pyloudnorm as pyln if n > SR * 0.45: v = float(pyln.Meter(SR).integrated_loudness(y.astype(np.float64))) info['lufs'] = round(v, 2) if math.isfinite(v) else None # None: silence except Exception: pass r20 = frame_rms(mono, int(0.02 * SR)) info['noise_floor_dbfs'] = round(db(np.percentile(r20, 10)), 1) info['loudest_20ms_dbfs'] = round(db(np.max(r20)), 1) info['dynamic_range_db'] = round(info['loudest_20ms_dbfs'] - info['noise_floor_dbfs'], 1) # stereo width: side/mid energy mid, side = (y[:, 0] + y[:, 1]) / 2, (y[:, 0] - y[:, 1]) / 2 info['side_to_mid_db'] = (round(db(np.sqrt(np.mean(side ** 2))) - db(np.sqrt(np.mean(mid ** 2))), 1) if np.any(side) else None) # None: both channels identical (mono) # first transient: first 1 ms window whose envelope gets within 20 dB of the peak envelope r1 = frame_rms(mono, int(0.001 * SR)) thr = np.max(r1) * 0.1 idx = int(np.argmax(r1 >= thr)) info['attack_at'] = round(idx * 0.001, 4) pk = int(np.argmax(r1)) info['peak_at'] = round(pk * 0.001, 4) # spectral shape (on a 22.05k copy for speed) ys = librosa.resample(mono, orig_sr=SR, target_sr=22050) if n < SR * 400 else mono[:: 2] sr2 = 22050 S = np.abs(librosa.stft(ys, n_fft=2048, hop_length=512)) cen = librosa.feature.spectral_centroid(S=S, sr=sr2)[0] roll = librosa.feature.spectral_rolloff(S=S, sr=sr2, roll_percent=0.95)[0] act = r20[: len(cen)] if len(r20) else None info['centroid_hz'] = int(np.median(cen)) info['rolloff95_hz'] = int(np.percentile(roll, 90)) # high-band levels relative to 1-4 kHz (an encoder lowpass shows up as a cliff, e.g. 16-19k far below 12-16k) m30 = mono[: min(n, SR * 60)] Sf = np.abs(np.fft.rfft(m30 * np.hanning(len(m30)))) ** 2 fr = np.fft.rfftfreq(len(m30), 1 / SR) band = lambda a, b: float(np.mean(Sf[(fr >= a) & (fr < b)]) + 1e-30) ref = band(1000, 4000) info['band_db_rel_1_4k'] = {k: round(10 * np.log10(band(a, b) / ref), 1) for k, (a, b) in {'40-120': (40, 120), '8-12k': (8000, 12000), '12-16k': (12000, 16000), '16-19k': (16000, 19000), '19-22k': (19000, 22000)}.items()} onsets = librosa.onset.onset_detect(y=ys, sr=sr2, units='time', backtrack=False) info['onset_count'] = int(len(onsets)) info['onsets'] = [round(float(o), 3) for o in onsets[:40]] # spikes: 100 ms windows more than 12 dB above the median level r100 = frame_rms(mono, int(0.1 * SR)) med = np.median(r100) sp = np.where(r100 > med * 4)[0] info['spikes_over_12db'] = [round(i * 0.1, 1) for i in sp[:30]] info['level_std_db_100ms'] = round(float(np.std(20 * np.log10(r100 + 1e-12))), 2) if music: tempo, beats = librosa.beat.beat_track(y=ys, sr=sr2, start_bpm=120, units='time', tightness=200) tempo = float(np.atleast_1d(tempo)[0]) info['tempo'] = round(tempo, 2) if len(beats) > 4: ibi = np.diff(beats) info['tempo_from_ibi'] = round(60 / float(np.median(ibi)), 2) info['ibi_std_ms'] = round(float(np.std(ibi)) * 1000, 1) info['beats'] = [round(float(b), 3) for b in beats] chroma = librosa.feature.chroma_cqt(y=ys, sr=sr2, hop_length=512) info['key'] = key_estimate(chroma.mean(axis=1)) r2 = frame_rms(mono, SR * 2) info['rms_db_per_2s'] = [round(db(v), 1) for v in r2] # loudness per bar (assuming 4/4 on the tracked beats) if len(beats) > 8: bars = beats[::4] pb = [] for a, b in zip(bars[:-1], bars[1:]): seg = mono[int(a * SR): int(b * SR)] pb.append(round(db(np.sqrt(np.mean(seg ** 2) + 1e-20)), 1)) info['bar_starts_if_beat0_is_downbeat'] = [round(float(b), 3) for b in bars] info['rms_db_per_bar'] = pb # sections: novelty on stacked chroma + mfcc try: mf = librosa.feature.mfcc(y=ys, sr=sr2, n_mfcc=13, hop_length=512) F = np.vstack([librosa.util.normalize(chroma, axis=1), librosa.util.normalize(mf, axis=1)]) k = max(4, min(12, int(info['duration'] // 15))) bounds = librosa.segment.agglomerative(F, k) info['sections_at'] = [round(float(t), 2) for t in librosa.frames_to_time(bounds, sr=sr2, hop_length=512)] except Exception as e: info['sections_error'] = str(e)[:200] return info def png(path, outdir): os.makedirs(outdir, exist_ok=True) base = os.path.splitext(os.path.basename(path))[0] out = os.path.join(outdir, base + '_spec.png') p = subprocess.run(['ffmpeg', '-v', 'error', '-y', '-i', path, '-lavfi', 'showspectrumpic=s=1400x420:mode=combined:color=intensity:scale=log:legend=1', out], capture_output=True, timeout=300) if p.returncode or not os.path.exists(out): raise RuntimeError(p.stderr.decode(errors='replace').strip()[:200] or 'no image written') return out.replace('\\', '/') def describe(r): """one plain-language line: format, level, noise, timing, tone, and what looks wrong""" if r.get('error'): return f"{os.path.basename(r['file'])}: ERROR {r['error']}" fmt = f"{r.get('codec')} {r.get('kbps') or '?'} kbps {(r.get('src_rate') or 0) / 1000:g} kHz {r.get('channels')}ch" lufs = f"{r['lufs']} LUFS" if r.get('lufs') is not None else 'LUFS n.a.' s = (f"{os.path.basename(r['file'])}: {fmt}, {r['duration']} s, peak {r['peak_dbfs']} dBFS, {lufs}, noise floor " f"{r['noise_floor_dbfs']} dBFS, attack {r['attack_at']} s, centroid {r['centroid_hz']} Hz, rolloff95 " f"{r['rolloff95_hz']} Hz, " + ('mono' if r.get('side_to_mid_db') is None else f"side/mid {r['side_to_mid_db']} dB")) if r.get('tempo'): s += f", {r.get('tempo_from_ibi', r['tempo'])} BPM (ibi std {r.get('ibi_std_ms')} ms), key {r['key'][0]['key']}" warn = [] if r['peak_dbfs'] <= -90: warn.append('digital silence') if r.get('clipped_samples'): warn.append(f"{r['clipped_samples']} clipped samples") if r.get('kbps') and r.get('codec') == 'mp3' and r['kbps'] < 192: warn.append('low-bitrate mp3') if r.get('src_rate') and r['src_rate'] < 44100: warn.append(f"sample rate {r['src_rate']} Hz") if r['rolloff95_hz'] < 8000 and r['peak_dbfs'] > -90: warn.append('dull (little above 8 kHz)') if r.get('spikes_over_12db'): warn.append(f"{len(r['spikes_over_12db'])} spike(s) > 12 dB over the median level") return s + ('; CHECK: ' + ', '.join(warn) if warn else '') def clean(o): if isinstance(o, dict): return {k: clean(v) for k, v in o.items()} if isinstance(o, list): return [clean(v) for v in o] return None if isinstance(o, float) and not math.isfinite(o) else o def main(): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument('files', nargs='+') ap.add_argument('--music', action='store_true', help='also tempo, beats, key, loudness per bar, sections') ap.add_argument('--png', metavar='DIR', help='write a spectrogram image per file here') ap.add_argument('--out', metavar='OUT.json', help='write every measurement as a JSON list') ap.add_argument('--json', action='store_true', help='print the JSON list instead of one line per file') a = ap.parse_args() res = [] for f in a.files: if not os.path.isfile(f): r = {'file': f, 'error': 'file not found'} else: try: r = analyze(f, a.music) except Exception as e: # noqa: BLE001 r = {'file': f, 'error': str(e)[:400]} if a.png: try: r['png'] = png(f, a.png) except Exception as e: # noqa: BLE001 r['png_error'] = str(e)[:200] r = clean(r) r['summary'] = describe(r) res.append(r) if not a.json: print(r['summary'].encode('ascii', 'replace').decode()) bad = [os.path.basename(r['file']) for r in res if r.get('error')] summary = f"{len(res)} file(s) analysed, {len(bad)} failed" + (f" ({', '.join(bad[:6])})" if bad else '') if a.out: os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) with open(a.out, 'w', encoding='utf-8') as fh: json.dump(res, fh, indent=1) summary += f'; wrote {a.out}' print(json.dumps(res, indent=1, ensure_ascii=True) if a.json else summary) return 1 if bad else 0 if __name__ == '__main__': sys.exit(main()) - skills/real-sound/scripts/arrange.py (21412 bytes)
#!/usr/bin/env python """Fit a music track to the film's bar structure by editing it at bar lines (no generation). python -I <skill>/scripts/arrange.py TRACK [--bpm 123.97] [--phase auto|0..3] [--film-bpm 120] [--beats-per-bar 4] [--bars 30 | --arc arc.json | --arc "-14,-12,...,0,0,-7"] [--drop-film-bar 21] [--drop auto|none|SRC_BAR] [--start-bar SRC_BAR] [--end-bar SRC_BAR] [--phrase 2] [--film-offset 0] [--file audio/assets/music/track.mp3] [--out out/audio-review/arrange.json] [--json] The film's arc is a target loudness per film bar in dB relative to the track's loud bars (0 = the loudest sections, -14 = a soft intro). Give it as a comma list, or a JSON file (templates/arc.json: {"arc": [...], "film_bpm": 120, "beats_per_bar": 4, "drop_film_bar": 21}), or let the script build a generic one from --bars and --drop-film-bar (soft open, groove, breakdown, build, big section from the drop, resolve). Write the arc from the picture map in SOUND_BRIEF.md. 1. Beat grid: librosa beats, a robust linear fit beats ~ t0 + k*T over the whole track (precise BPM), then the phase is moved onto the measured attacks (a 23 ms-window spectral flux at 2.9 ms resolution, folded at the beat period): the beat tracker's onset envelope lags real attacks by 20-50 ms, and a splice cut on a lagging grid chops the downbeat's own attack. 2. Downbeat: which beat phase starts bars (low-band onsets + harmonic change), with a confidence (z-score gap) and a local check in 8-bar windows (sections where another phase clearly wins are listed). Measured on the two hand-labelled tracks of the Clawd project (both seen while building this): Born Of The Sky correct (confidence 0.93); Bring Me The Sky half a bar off (confidence 0.15, flagged LOW: its bass plays on beats 1 and 3 and its accents move by half a bar later in the track). Under LOW confidence the downbeat is a guess between the two printed grids: decide from the music (the first note, section entrances, chord changes in the bar table) and pass --phase N. 3. Bar features: chroma, MFCC, loudness, low-band energy, onset density; novelty = change from the previous bar. 4. Arrangement by dynamic programming over the film's bars (film bar k spans bar_len*(k-1)..bar_len*k s): cost = energy-curve mismatch (the film's arc) + jump costs (a jump must land on a bar that sounds like the one that would naturally follow: chroma/MFCC/loudness distance) + phrase penalties (jumps prefer phrase starts) + hard anchors (--drop-film-bar = --drop source bar, the last film bar = --end-bar, film bar 1 = --start-bar). By default (--drop auto) the drop film bar is anchored on the strongest drop candidate (a bar within 3 dB of the loud sections that stays loud, scored by its lift over the 4 bars before + novelty); --drop none lets the arc decide. On the two Clawd tracks the top candidate is a section start the music supervisor marked by hand (Born Of The Sky bar 50 = the crash into big section 1; Bring Me The Sky the re-entry at 127.8 s); developed on those same tracks. Prints the summary, the bar table, the chosen map and a ready-to-paste "music" block for the design (source seconds, film seconds); --json prints the full result as JSON instead, --out writes it to a file. It is a first draft: check every splice (qa.py edges, earshot timeline) and the bar table, then fine-tune "at" by a few ms so the measured downbeat transients land on the picture's downbeats. """ import argparse, json, os, subprocess, sys import numpy as np SR = 22050 def default_arc(n, drop): """a generic short-film arc over n film bars with the big section starting at film bar `drop` (1-based): soft open -> groove -> breakdown -> build -> big section -> resolve""" arc = [] big_until = drop + max(2, int(round((n - drop) * 0.6))) for k in range(1, n + 1): if k < drop: x = (k - 1) / max(1, drop - 2) # 0..1 up to the bar before the drop v = -14 + 10 * min(1.0, x / 0.45) # opening rises to the groove (-4) if 0.55 <= x < 0.8: v = -9.5 # breakdown before the build elif x >= 0.8: v = -9 + 4 * (x - 0.8) / 0.2 # build elif k < big_until: v = 0.0 # the big section else: v = -13 + 2 * min(3, n - k) # resolve to the end arc.append(round(v, 1)) return arc def decode(path): p = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-i', path, '-f', 'f32le', '-ac', '1', '-ar', str(SR), '-'], capture_output=True) if p.returncode != 0 or not p.stdout: sys.exit(f'cannot decode {path}: {p.stderr.decode(errors="replace")[:300]}') return np.frombuffer(p.stdout, np.float32).copy() def fit_grid(beats, T0): """robust fit of beat times to t0 + k*T, starting from period T0""" k = np.r_[0, np.cumsum(np.maximum(1, np.round(np.diff(beats) / T0)))] A = np.vstack([k, np.ones_like(k)]).T inl = np.ones(len(beats), bool) T, t0 = T0, float(beats[0]) for _ in range(5): T, t0 = np.linalg.lstsq(A[inl], beats[inl], rcond=None)[0] res = beats - (t0 + k * T) inl = np.abs(res) < 0.035 if inl.sum() < 8: inl[:] = True res = beats - (t0 + k * T) return float(T), float(t0), float(np.median(np.abs(res))), float(np.mean(np.abs(res) < 0.035)) def flux(y, n_fft=512, hop=64, block=4096): """log-compressed spectral flux with a short (23 ms) window at 2.9 ms resolution, computed in blocks of frames (bounded memory); returns (flux, frame centre times)""" win = np.hanning(n_fft).astype(np.float32) nfr = max(0, (len(y) - n_fft) // hop + 1) out, prev = np.zeros(nfr, np.float32), None for f0 in range(0, nfr, block): f = np.arange(f0, min(nfr, f0 + block)) L = np.log1p(100 * np.abs(np.fft.rfft(y[f[:, None] * hop + np.arange(n_fft)] * win, axis=1))) d = np.diff(L, axis=0, prepend=L[:1] if prev is None else prev[None]) out[f] = np.maximum(0, d).sum(axis=1) prev = L[-1] return out, (np.arange(nfr) * hop + n_fft / 2) / SR def transient_phase(y, T, t0): """shift (s) that puts the grid on the measured attacks: the short-window flux folded at the beat period over the whole track, searched within +-min(100 ms, 0.3 beat); returns (shift, score ratio best / median)""" fl, tt = flux(y) hop_s = tt[1] - tt[0] search = min(0.1, 0.3 * T) offs = np.arange(-search, search + 1e-9, 0.001) k = np.arange(int(np.ceil((tt[0] - t0 + search) / T)), int((tt[-1] - t0 - search) / T)) score = np.array([fl[np.round((t0 + o + k * T - tt[0]) / hop_s).astype(int)].mean() for o in offs]) b = int(np.argmax(score)) return float(offs[b]), float(score[b] / (np.median(score) + 1e-9)) def local_phases(score, grid, bpb, phase, win=8, hop=4, min_gap=0.5): """stretches where another downbeat phase clearly wins (by >= min_gap, the global LOW threshold) in windows of `win` bars: [{'from', 'to', 'phase', 'gap'}]""" out, W = [], win * bpb for s in range(0, len(grid) - W + 1, hop * bpb): seg = score[s:s + W] sc = [float(np.mean(seg[(p - s) % bpb::bpb])) for p in range(bpb)] o = np.argsort(sc)[::-1] gap = sc[o[0]] - sc[o[1]] if o[0] == phase or gap < min_gap: continue t0, t1 = round(float(grid[s]), 2), round(float(grid[min(len(grid) - 1, s + W)]), 2) if out and out[-1]['phase'] == int(o[0]) and t0 <= out[-1]['to']: out[-1].update({'to': t1, 'gap': max(out[-1]['gap'], round(gap, 2))}) else: out.append({'from': t0, 'to': t1, 'phase': int(o[0]), 'gap': round(gap, 2)}) return out def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.splitlines()[1]) ap.add_argument('track') ap.add_argument('--bpm', type=float, help='the track\'s tempo if you know it (the phase is still fitted)') ap.add_argument('--phase', default='auto', help='downbeat phase 0..beats-per-bar-1, or auto') ap.add_argument('--film-bpm', type=float, default=120.0, help='tempo the picture is cut to (after any stretch)') ap.add_argument('--beats-per-bar', type=int, default=4) ap.add_argument('--bars', type=int, default=30, help='film bars (ignored when --arc is given)') ap.add_argument('--arc', help='target dB per film bar: comma list or JSON file') ap.add_argument('--drop-film-bar', type=int, help='1-based film bar of the drop / big section') ap.add_argument('--drop', default='auto', help='source bar for the drop film bar: auto (the top drop candidate), ' 'none, or a 0-based bar index') ap.add_argument('--end-bar', type=int, help='source bar index for the film\'s last bar') ap.add_argument('--start-bar', type=int, help='source bar index for film bar 1') ap.add_argument('--phrase', type=int, default=2, help='jumps prefer film bars that start a phrase of this length') ap.add_argument('--film-offset', type=float, default=0.0, help='film time of film bar 1 (s)') ap.add_argument('--jump', type=float, default=3.0, help='base cost per jump') ap.add_argument('--no-snap', action='store_true', help='keep the beat tracker\'s phase (skip the transient fit)') ap.add_argument('--file', help='the track path as the design should reference it (default: TRACK as given)') ap.add_argument('--out', help='write the full result as JSON here') ap.add_argument('--json', action='store_true', help='print the full result as JSON instead of the table') a = ap.parse_args(argv) if a.drop not in ('auto', 'none') and not a.drop.lstrip('-').isdigit(): sys.exit(f'--drop must be auto, none or a source bar index, not {a.drop!r}') if not os.path.isfile(a.track): sys.exit(f'track not found: {a.track}') cfg = {} if a.arc and a.arc.strip().endswith('.json'): cfg = json.load(open(a.arc, encoding='utf-8')) arc_list = [float(v) for v in cfg['arc']] elif a.arc: arc_list = [float(v) for v in a.arc.split(',') if v.strip()] else: arc_list = None film_bpm = float(cfg.get('film_bpm', a.film_bpm)) bpb = int(cfg.get('beats_per_bar', a.beats_per_bar)) FILM_BARS = len(arc_list) if arc_list else a.bars drop_k = int(a.drop_film_bar or cfg.get('drop_film_bar') or round(FILM_BARS * 0.7)) ARC = arc_list or default_arc(FILM_BARS, drop_k) bar_len = bpb * 60.0 / film_bpm import librosa y = decode(a.track) dur = len(y) / SR hop = 256 oenv = librosa.onset.onset_strength(y=y, sr=SR, hop_length=hop) tempo, beats = librosa.beat.beat_track(onset_envelope=oenv, sr=SR, hop_length=hop, start_bpm=a.bpm or 120, tightness=400, units='time') beats = np.asarray(beats, float) if len(beats) < 8: sys.exit(f'only {len(beats)} beats tracked in {a.track}: not a steady-tempo track, or too short') T0 = 60.0 / a.bpm if a.bpm else float(np.median(np.diff(beats))) T, t0, med_res, inlier = fit_grid(beats, T0) if a.bpm: # trust a given tempo but keep the fitted phase T = 60.0 / a.bpm shift, snap_ratio = (0.0, None) if a.no_snap else transient_phase(y, T, t0) t0 += shift bpm = 60.0 / T first = t0 - np.floor(t0 / T) * T grid = np.arange(first, dur, T) # downbeat phase: low-band onset strength + chroma change at each beat S = np.abs(librosa.stft(y, n_fft=2048, hop_length=hop)) freqs = librosa.fft_frequencies(sr=SR, n_fft=2048) low = S[freqs < 150].sum(axis=0) low_on = np.maximum(0, np.diff(low, prepend=low[0])) chroma = librosa.feature.chroma_stft(S=S ** 2, sr=SR, hop_length=hop) fr = lambda t: min(int(t * SR / hop), S.shape[1] - 1) beat_low = np.array([low_on[max(0, fr(t) - 2): fr(t) + 4].max() for t in grid]) beat_chg = [] for t in grid: a0, a1, b1 = fr(max(0, t - T)), fr(t), fr(min(dur, t + T)) pa = chroma[:, a0:a1].mean(axis=1) if a1 > a0 else chroma[:, a1] pb = chroma[:, a1:b1].mean(axis=1) if b1 > a1 else chroma[:, a1] beat_chg.append(1 - float(np.dot(pa, pb) / (np.linalg.norm(pa) * np.linalg.norm(pb) + 1e-9))) beat_chg = np.array(beat_chg) zl = (beat_low - beat_low.mean()) / (beat_low.std() + 1e-9) zc = (beat_chg - beat_chg.mean()) / (beat_chg.std() + 1e-9) ph_score = [float(np.mean(zl[p::bpb]) + np.mean(zc[p::bpb])) for p in range(bpb)] order = np.argsort(ph_score)[::-1] phase = int(order[0]) if a.phase == 'auto' else int(a.phase) conf = ph_score[order[0]] - ph_score[order[1]] alt = int(order[1]) if order[0] == phase else int(order[0]) local = local_phases(zl + zc, grid, bpb, phase) bars = grid[phase::bpb] bars = bars[bars + bpb * T <= dur + 1e-3] nb = len(bars) if nb < 2: sys.exit('the track is shorter than two bars') # bar features mf = librosa.feature.mfcc(S=librosa.power_to_db(S ** 2), sr=SR, n_mfcc=13) feats, loud, dens = [], [], [] for b in bars: s0, s1 = int(b * SR), int((b + bpb * T) * SR) f0, f1 = fr(b), fr(b + bpb * T) loud.append(20 * np.log10(np.sqrt(np.mean(y[s0:s1] ** 2)) + 1e-9)) dens.append(float((oenv[f0:f1] > np.median(oenv) * 1.5).mean())) c = chroma[:, f0:f1].mean(axis=1); c = c / (np.linalg.norm(c) + 1e-9) m = mf[1:, f0:f1].mean(axis=1); m = m / (np.linalg.norm(m) + 1e-9) feats.append(np.concatenate([c, m])) feats, loud = np.array(feats), np.array(loud) rel = loud - np.percentile(loud, 90) nov = np.r_[0, np.linalg.norm(np.diff(feats, axis=0), axis=1)] rise = np.r_[0, np.diff(loud)] # a drop: a loud bar (within 3 dB of the loud sections) that stays loud for 4 bars, lifted over the 4 bars before it lift = np.array([rel[i] - np.median(rel[max(0, i - 4):i]) if i else 0.0 for i in range(nb)]) loud_now = (rel > -3) & (np.array([rel[i:i + 4].mean() for i in range(nb)]) > -4) drop_score = np.where(loud_now if loud_now.any() else rel > np.percentile(rel, 75), lift / 3 + nov * 2, -np.inf) drop_cands = [int(i) for i in np.argsort(drop_score)[::-1][:6] if np.isfinite(drop_score[i])] drop_src = drop_cands[0] if a.drop == 'auto' else None if a.drop == 'none' else int(a.drop) for what, v in (('--drop', drop_src), ('--start-bar', a.start_bar), ('--end-bar', a.end_bar)): if v is not None and not 0 <= v < nb: sys.exit(f'{what} {v} is outside the source bars 0..{nb - 1}') if not 1 <= drop_k <= FILM_BARS: sys.exit(f'--drop-film-bar {drop_k} is outside the film bars 1..{FILM_BARS}') # how different bar j sounds from bar i D = np.linalg.norm(feats[:, None] - feats[None], axis=2) + np.abs(loud[:, None] - loud[None]) / 6 nxt = np.minimum(np - skills/real-sound/scripts/audit.py (23878 bytes)
#!/usr/bin/env python """Licence + file audit of every recording in the manifests: is each one allowed, verified, credited and intact? python -I <skill>/scripts/audit.py [--root .] [--manifests audio/assets/manifests] [--report out/qa/mix_report.json] [--out audio/assets/manifests/audit.json] [--table out/qa/audit.md] [--fetch] [--fetch-all] [--decode scope|all|none] [--json] Per manifest entry (references/licences.md has the policy; templates/manifest_entry.json the fields): licence classified from the manifest's "license": allowed (CC0, public domain, CC BY 2.0-4.0, Mixkit free licences, Pixabay) / forbidden (NC, ND, SA, Sampling+, personal, custom, editorial, disputed) / unknown verified the agent's own reading of the licence on the item's page: "licence_seen" (+ "licence_confirmed") merged from an existing audit.json (the --out file); the script never verifies a licence itself, it only checks that what the agent saw classifies the same as the manifest attribution CC BY items need a ready-to-paste "attribution" credit line (and author, title, page_url) urls Freesound / Mixkit ids agree between the entry id, the page and the download URL file exists, ffprobe codec / rate / channels / duration, decodes without errors (ffmpeg -f null; in-scope recordings unless --decode all), duration matches the manifest's analysis; with --fetch the bytes are compared with download_url (sequential, 1.5 s apart, in memory, never executed; only for recordings used in the film unless --fetch-all) in_scope = used in the film (report.files_used) when --report is given, else the existing audit's value, else true. Severity: blocker (in scope and forbidden / unknown / unverified licence, missing or broken file, CC BY without a credit line), warning, ok. Exit code 1 when an in-scope recording has a blocker. Writes audit.json (a list, one record per entry; agent notes kept under "agent_notes") and a Markdown table. """ import argparse, hashlib, json, os, re, shutil, subprocess, sys, time sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import licences as L # noqa: E402 TOOL = 'real-sound audit.py v2' NEEDED = ('id', 'file', 'title', 'author', 'page_url', 'license') NO_SCRIPTS = ('pixabay.com',) # sites that block scripted downloads: never fetch UA = 'real-sound-licence-audit/1.0 (polite single-file check; contact: project owner)' def say(s): print(str(s).encode('ascii', 'replace').decode()) COMPUTED = ('path', 'exists', 'codec', 'sample_rate', 'channels', 'kbps', 'duration_s', 'video', 'decodes_clean', 'max_volume_db', 'bytes_match_download_url', 'fetch_note') AUDIT_KEYS = ('id', 'manifest', 'need', 'rank', 'in_scope', 'severity', 'licence_in_manifest', 'licence', 'licence_status', 'licence_seen', 'licence_confirmed', 'attribution_required', 'attribution_ok', 'attribution_in_manifest', 'file_ok', 'file_check', 'earlier_file_check', 'problems', 'warnings', 'agent_notes', 'audit_tool', 'problem', 'fix', 'duplicate_of') SENT = r'(?:[^.]|\.(?=\d))' # inside one sentence ("4.0" does not end it) READ_NOTE = re.compile(SENT + r'*\blicen[cs]e' + SENT + r'{0,40}\b(read|verified|checked|seen|confirmed)\b' + SENT + '*', re.I) def ffprobe(path): """first audio stream's codec / rate / channels / bit rate, the duration, and any real video stream (not cover art)""" p = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'stream=codec_type,codec_name,sample_rate,channels,' 'bit_rate:stream_disposition=attached_pic:format=duration,bit_rate', '-of', 'json', path], capture_output=True, text=True, timeout=120) j = json.loads(p.stdout or '{}') st = j.get('streams') or [] s = next((x for x in st if x.get('codec_type') == 'audio'), {}) f = j.get('format') or {} brs = [int(b) for b in (s.get('bit_rate'), f.get('bit_rate')) if str(b).isdigit() and 0 < int(b) < 10 ** 7] video = [x.get('codec_name') for x in st if x.get('codec_type') == 'video' and not (x.get('disposition') or {}).get('attached_pic')] return {'codec': s.get('codec_name'), 'sample_rate': int(s.get('sample_rate') or 0), 'channels': int(s.get('channels') or 0), 'kbps': round(brs[0] / 1000) if brs else None, 'duration_s': round(float(f.get('duration') or 0), 3), **({'video': video[0]} if video else {})} def decodes_clean(path): """(decodes without errors, first error line, max volume dBFS) from one full ffmpeg decode of the audio stream""" p = subprocess.run(['ffmpeg', '-hide_banner', '-nostdin', '-loglevel', 'level+info', '-i', path, '-map', '0:a:0', '-af', 'volumedetect', '-f', 'null', '-'], capture_output=True, timeout=600) lines = p.stderr.decode(errors='replace').splitlines() err = [ln for ln in lines if '[error]' in ln or '[fatal]' in ln] vol = [float(m.group(1)) for ln in lines for m in [re.search(r'max_volume: (-?[\d.]+|-inf) dB', ln)] if m and m.group(1) != '-inf'] or [None] return p.returncode == 0 and not err, err[0][:200] if err else None, vol[-1] def url_checks(e): """id consistency for the two sites whose URLs encode it""" out = [] page, dl, eid = e.get('page_url') or '', e.get('download_url') or '', str(e.get('id') or '') m = re.search(r'freesound\.org/people/([^/]+)/sounds/(\d+)', page) if m: sid = m.group(2) if re.match(r'fs-\d+', eid) and eid[3:] != sid: out.append(f'entry id {eid} but the Freesound page is sound {sid}') d = re.search(r'previews/(\d+)/(\d+)_(\d+)-(hq|lq)\.(ogg|mp3)', dl) if d: if d.group(2) != sid: out.append(f'download_url is sound {d.group(2)}, the page is sound {sid}') if d.group(1) != str(int(sid) // 1000): out.append(f'preview folder {d.group(1)} should be {int(sid) // 1000}') if d.group(4) == 'lq': out.append('low-quality Freesound preview (-lq): use the -hq preview') if e.get('author') and m.group(1).lower() != str(e['author']).lower(): out.append(f'author "{e["author"]}" differs from the page owner "{m.group(1)}"') d = re.search(r'assets\.mixkit\.co/active_storage/sfx/(\d+)/(\d+)\.(wav|mp3)', dl) if d: if d.group(1) != d.group(2): out.append('Mixkit download_url ids disagree') if re.match(r'mk-\d+', eid) and eid[3:] != d.group(1): out.append(f'entry id {eid} but the Mixkit download is item {d.group(1)}') return out def fetch_match(url, path): """True / False when the bytes at url equal the local file; None + reason when not checked""" host = re.sub(r'^[a-z]+://', '', url.lower()).split('/')[0] if any(host.endswith(h) for h in NO_SCRIPTS): return None, f'{host} blocks scripted downloads: compare by hand' import urllib.request try: req = urllib.request.Request(url, headers={'User-Agent': UA}) with urllib.request.urlopen(req, timeout=60) as r: data = r.read(200 * 1024 * 1024 + 1) except Exception as ex: # noqa: BLE001 return None, f'fetch failed: {str(ex)[:160]}' local = open(path, 'rb').read() return hashlib.sha1(data).hexdigest() == hashlib.sha1(local).hexdigest(), None def agent_fields(old): """what the agent wrote into an earlier audit record (licence reading, notes, hand-recorded file checks such as a byte comparison); script findings are recomputed, earlier evidence is kept under earlier_file_check""" if not old: return {} keep = {k: old[k] for k in ('licence_seen', 'licence_confirmed') if k in old} fc = old.get('file_check') or {} earlier = dict(old.get('earlier_file_check') or {}) if old.get('audit_tool'): notes = old.get('agent_notes') or [] earlier.update({k: fc[k] for k in ('bytes_match_download_url', 'fetch_note') if k in fc}) else: # a hand-written audit: its warnings / problem / fix are the agent's notes, its file checks earlier evidence notes = list(old.get('warnings') or []) + [old[k] for k in ('problem', 'fix') if old.get(k)] earlier.update({k: v for k, v in fc.items() if k not in COMPUTED or k in ('bytes_match_download_url', 'fetch_note')}) keep.update({k: v for k, v in old.items() if k not in AUDIT_KEYS}) if earlier: keep['earlier_file_check'] = earlier if notes: keep['agent_notes'] = notes if 'in_scope' in old: keep['_in_scope'] = old['in_scope'] return keep def audit_entry(e, root, used, old, decode='scope'): path = os.path.join(root, e['file']) if not os.path.isabs(e['file']) else e['file'] f = L.rel(e['file'], root) lic = L.classify(e.get('license')) ag = agent_fields(old) in_scope = (f.lower() in used) if used is not None else bool(ag.get('_in_scope', True)) problems, warnings = [], [] for k in NEEDED: if not e.get(k): (problems if k in ('file', 'license') else warnings).append(f'missing "{k}"') if lic['status'] == 'forbidden': problems.append(f'licence forbidden: {lic["reason"]}') elif lic['status'] == 'unknown': problems.append(f'licence unknown: {lic["reason"]}') seen = ag.get('licence_seen') confirmed = bool(ag.get('licence_confirmed')) and bool(seen) if not seen: m = READ_NOTE.search(str(e.get('notes') or '')) problems.append('no licence record in audit.json' + ( f' (the manifest notes say: "{m.group(0).strip()[:90]}"): copy that reading into "licence_seen" and set ' '"licence_confirmed"' if m else ': read the licence on the item page and record "licence_seen"')) else: sk = L.classify(seen)['key'] if sk not in ('unknown', 'none', lic['key']): warnings.append(f'licence_seen reads as {sk} but the manifest says {lic["key"]}') if not ag.get('licence_confirmed'): problems.append('licence_seen recorded but licence_confirmed is not true') attr_ok = True if lic['attribution']: attr_ok = bool(e.get('attribution')) and bool(e.get('author')) and bool(e.get('page_url')) if not attr_ok: problems.append('CC BY needs "attribution" (a ready-to-paste credit line), "author" and "page_url"') else: at = e['attribution'] if str(e['author']).split(' (')[0].lower() not in at.lower(): warnings.append('the attribution line does not name the author') if not re.search(r'cc[ -]?by|attribution|creativecommons\.org', at, re.I): warnings.append('the attribution line does not name the licence (credits.py adds the licence link)') warnings += url_checks(e) fc = {'path': f, 'exists': os.path.isfile(path)} if not fc['exists']: problems.append('file missing') else: try: fc.update(ffprobe(path)) except Exception as ex: # noqa: BLE001 problems.append(f'ffprobe failed: {str(ex)[:120]}') if fc.get('video'): warnings.append(f"the file carries a {fc['video']} video stream: extract the audio to its own file and make " 'sure the licence covers the audio') if decode == 'all' or (decode == 'scope' and in_scope): ok, err, vol = decodes_clean(path) fc['decodes_clean'], fc['max_volume_db'] = ok, vol if not ok: problems.append(f'decode errors: {err}') if vol is not None and vol <= -90: problems.append(f'the recording is digital silence (max {vol} dB)') elif vol is not None and vol < -60: warnings.append(f'the recording is near-silent (max {vol} dB): the wrong file?') an = (e.get('analysis') or {}).get('duration') if an and fc.get('duration_s') and abs(float(an) - fc['duration_s']) > 0.05: warnings.append(f'duration {fc["duration_s"]} s differs from the manifest analysis ({an} s): file replaced?') if fc.get('sample_rate') and fc['sample_rate'] < 44100: warnings.append(f'sample rate {fc["sample_rate"]} Hz (dull above {fc["sample_rate"] // 2000} kHz)') if fc.get('codec') == 'mp3' and fc.get('kbps') and fc['kbps'] < 192: warnings.append(f'MP3 at {fc["kbps"]} kbps: look for a lossless or higher-rate source') r = {'id': e.get('id'), 'manifest': e['_manifest'], 'need': e.get('need'), 'rank': e.get('rank'), 'in_scope': in_scope, 'severity': None, 'licence_in_manifest': e.get('license'), 'licence': lic['key'], 'licence_status': lic['status'], 'licence_seen': seen, 'licence_confirmed': confirmed, 'attribution_required': lic['attribution'], 'attribution_ok': attr_ok, 'attribution_in_manifest': e.get('attribution'), 'file_ok': fc['exists'] and fc.get('decodes_clean', True) is not False, 'file_check': fc, **({'earlier_file_check': ag['earlier_file_check']} if ag.get('earlier_file_check') else {}), 'problems': problems, 'warnings': warnings, 'agent_notes': ag.get('agent_notes', []), 'audit_tool': TOOL, **{k: v for k, v in ag.items() if k not in AUDIT_KEYS and not k.startswith('_')}} r['severity'] = severity(r) return r def severity(r): sev = 'blocker' if r['problems'] else 'warning' if r['warnings'] else 'ok' return sev if r['in_scope'] else 'info' if sev != 'ok' else 'ok' def audit(root='.', manifests='audio/assets/manifests', report=None, existing=None, fetch=False, fetch_all=False, decode='scope'): """audit every manifest entry; returns {'summary', 'counts', 'entries', 'notes'}""" mdir = manifests if os.path.isabs(manifests) else os.path.join(root, manifests) if not os.path.isdir(mdir): raise FileNotFoundError(f'manifest folder not found: {mdir} (pass --manifests)') entries, notes = L.load_manifests(mdir) if not entries: raise FileNotFoundError(f'no manifest entries in {mdir}' + (f' ({"; ".join(notes)})' if notes else '')) used = None if report: rp = report if os.path.isabs(report) else os.path.join(root, report) used = {L.rel(u, root).lower() for u in json.load(open(rp, encoding='utf-8')).get('files_used', [])} old = {} existing = existing and (existing if os.path.isabs(existing) else os.path.join(root, existing)) if existing and os.path.exists(existing): for r in json.load(open(existing, encoding='utf-8')): p = L.rel(((r.get('file_check') or {}).get('path') or ''), root).lower() old[(str(r.get('id')), p)] = old[(str(r.get('id')), '')] = r rows, first = [], {} for e in entries: f = L.rel(e[' - skills/real-sound/scripts/credits.py (11933 bytes)
#!/usr/bin/env python """Credits for every recording audible in the film, built from the mix report and the licence manifests. python -I <skill>/scripts/credits.py [--root .] [--report out/qa/mix_report.json] [--manifests audio/assets/manifests] [--design audio/sounddesign.json] [--audit audio/assets/manifests/audit.json] [--out CREDITS.md] [--desc out/CREDITS_description.txt] [--title "Film name"] Reads report.files_used (written by mix.py: every recording that is audible), matches each file to its manifest entry and writes: CREDITS.md music + every sound with title, author, link and licence (grouped by licence); a CC BY entry uses the manifest's "attribution" line (the form the author asked for) when there is one CREDITS_description.txt plain text to paste into the video description (CC BY credits are REQUIRED there; CC0 / Mixkit / Pixabay items are listed as a courtesy) The processing sentence (trimmed, equalised, pitch-shifted ...) and the music edit sentence come from the design when --design is given; the source names (Freesound.org, Mixkit ...) come from the manifests. With --audit, recordings the licence audit did not confirm are listed as problems. Both texts say that every work was modified (CC BY 4.0 s.3(a)(1)(B)). Exit code 1 when anything needs fixing before publishing, 2 when the report or manifests are missing. """ import argparse, json, os, sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import licences as L # noqa: E402 ORDER = ['by4', 'by3', 'by25', 'by2', 'cc0', 'pd', 'mixkit-sfx', 'mixkit-music', 'pixabay'] SHORT = {'cc0': 'CC0', 'pd': 'public domain', 'mixkit-sfx': 'Mixkit free licence', 'mixkit-music': 'Mixkit free licence', 'pixabay': 'Pixabay licence'} def say(s): print(str(s).encode('ascii', 'replace').decode()) def and_join(xs): xs = list(xs) return ' and '.join([', '.join(xs[:-1]), xs[-1]]) if len(xs) > 1 else ''.join(xs) def processing(design_path, root): """(sentence for the effects, sentence for the music edit, music stretched?) derived from the design""" if not design_path: return ('trimmed, layered, level-adjusted, equalised and panned for the film', 'Edited for the film: cut to fit the picture and levels adjusted.', False) import mix # read-only use of the design loader mix.ROOT = root d = mix.load_design(design_path) opts = list((d.get('samples') or {}).values()) + list((d.get('slices') or {}).values()) rules, place = d.get('rules') or [], d.get('place') or [] did = ['trimmed'] if d.get('slices'): did.append('cut into single hits') did.append('layered' if len(rules) + len(place) > len(opts) * 0.5 or len(rules) > 1 else 'placed') did.append('level-adjusted') if any(s.get('eq') for s in opts) or any((b or {}).get('eq') for b in (d.get('buses') or {}).values()): did.append('equalised') if any(r.get('pan') not in (None, 0, 0.0) for r in rules) or any(p.get('pan') for p in place): did.append('panned') if any(s.get('pitch') or s.get('glide') for s in opts) or any(r.get('pitch') or r.get('pitch_ramp') for r in rules): did.append('pitch-shifted by resampling') fx = and_join(did) mu = d.get('music') if not mu: return fx + ' for the film', None, False segs = mu.get('segments') or [] stretched = mu.get('stretch', 'rubberband') != 'none' and abs(mu.get('target_bpm', 120) / mu['src_bpm'] - 1) > 1e-6 parts = ['cut and rearranged at bar lines to fit the picture' if len(segs) > 1 else 'trimmed to the picture'] if stretched: parts.append(f"time-stretched from {mu['src_bpm']:g} to {mu.get('target_bpm', 120):g} BPM") parts.append('levels adjusted') if any(s.get('tail_fade') for s in segs): parts.append('a fade at the end') return fx + ' for the film', 'Edited for the film: ' + ', '.join(parts) + '.', stretched def credits(root='.', report='out/qa/mix_report.json', manifests='audio/assets/manifests', design=None, audit=None, title=None): """build the CREDITS.md and description texts; returns {'summary', 'markdown', 'description', 'rows', 'problems'}""" R = lambda p: p if os.path.isabs(p) else os.path.join(root, p) if not os.path.exists(R(report)): raise FileNotFoundError(f'mix report not found: {R(report)} (run mix.py first, or pass --report)') if not os.path.isdir(R(manifests)): raise FileNotFoundError(f'manifest folder not found: {R(manifests)} (pass --manifests)') rep = json.load(open(R(report), encoding='utf-8')) used = [L.rel(f, root) for f in rep.get('files_used', [])] entries, notes = L.load_manifests(R(manifests)) by_file = {} for e in entries: by_file.setdefault(L.rel(e['file'], root).lower(), e) confirmed = None if audit and os.path.exists(R(audit)): confirmed = {L.rel((r.get('file_check') or {}).get('path') or '', root).lower(): r for r in json.load(open(R(audit), encoding='utf-8'))} rows, problems = [], [] for f in used: e = by_file.get(f.lower()) if not e: problems.append(f'no manifest entry for {f}') continue lic = L.classify(e.get('license')) if lic['status'] != 'allowed': problems.append(f'{f}: licence "{e.get("license")}" is {lic["status"]} ({lic["reason"]})') if lic['attribution'] and not (e.get('author') and e.get('title') and e.get('page_url')): problems.append(f'{f}: CC BY needs author, title and page_url for the credit') if confirmed is not None: a = confirmed.get(f.lower()) if not a: problems.append(f'{f}: the licence audit has no record of this file (run audit.py, record licence_seen)') elif not a.get('licence_confirmed'): problems.append(f'{f}: audit.json does not confirm this licence (licence_seen / licence_confirmed missing)') rows.append({'file': f, 'id': e.get('id'), 'title': e.get('title'), 'author': e.get('author'), 'url': e.get('page_url'), 'lic': lic, 'attribution': e.get('attribution'), 'category': e.get('category'), 'source': L.source_name(e)}) music = [r for r in rows if r['category'] == 'music' or '/music/' in '/' + r['file'].lower()] sfx = [r for r in rows if r not in music] rank = lambda k: ORDER.index(k) if k in ORDER else len(ORDER) sfx.sort(key=lambda r: (rank(r['lic']['key']), (r['author'] or '').lower(), r['title'] or '')) fx_did, mu_did, stretched = processing(design and R(design), root) def line(r): """the author's requested credit (manifest "attribution") or a built one, completed with the source link and the licence link when the requested form leaves them out (CC BY asks for both)""" name, url = r['lic']['name'] or r['lic']['key'], r['lic']['url'] if not (r['lic']['attribution'] and r['attribution']): return f'"{r["title"]}" by {r["author"]} ({r["url"]}), licensed under {name}' + (f' ({url})' if url else '') base = r['attribution'].strip().rstrip('.') if r['url'] and 'http' not in base and 'www.' not in base: base += f' ({r["url"]})' if url and 'creativecommons.org' not in base: base += f' ({url})' return base srcs = {} for r in sfx: srcs[r['source']] = srcs.get(r['source'], 0) + 1 src_txt = and_join(s for s, _ in sorted(srcs.items(), key=lambda kv: -kv[1])) md = [f'# Credits{": " + title if title else ""}', '', 'All credits live here and in the video description (CC BY credits are required there).', ''] if music: md += ['## Music', ''] for r in music: md.append(f'- {line(r)}.') if mu_did: md.append(f' {mu_did}') md.append('') if sfx: md += ['## Sound effects and ambience', '', f'Real recordings from {src_txt or "the sources below"}, {fx_did}. Nothing in the soundtrack is ' 'synthesized.', ''] cur = None for r in sfx: if r['lic']['key'] != cur: cur = r['lic']['key'] md += ['', f'### {r["lic"]["name"] or cur}', ''] md.append(f'- {line(r)}') tools = 'ffmpeg, NumPy/SciPy, soxr, librosa and pyloudnorm' + (', Rubber Band (music tempo)' if stretched else '') md += ['', '## Tools', '', f'Edited, mixed and mastered with the real-sound skill (mix.py, master.py) using {tools}.', ''] if problems: md += ['', '## PROBLEMS (fix before publishing)', ''] + [f'- {p}' for p in problems] d = [] if music: # CC BY 4.0 s.3(a)(1)(B): say that the work was modified d.append('Music:') d += [line(r) for r in music] + ([mu_did] if mu_did else []) + [''] by = [r for r in sfx if r['lic']['attribution']] if by: d.append('Sound effects (CC BY):') d += [line(r) for r in by] d += [f'All sound effects and ambiences were modified: {fx_did}.', ''] rest = sorted({r['author'] for r in sfx if not r['lic']['attribution'] and r['author']}, key=str.lower) if rest: kinds = sorted({SHORT.get(r['lic']['key'], r['lic']['key']) for r in sfx if not r['lic']['attribution']}) d.append(f'More sounds ({", ".join(kinds)}) by: ' + ', '.join(rest)) if sfx and not by: d.append(f'All sound effects and ambiences were {fx_did}.') n_by = sum(1 for r in rows if r['lic']['attribution']) summary = (f'{len(rows)} recordings credited ({len(music)} music, {len(sfx)} sound effects / ambience; {n_by} CC BY ' f'need the credit in the video description)' + (f'; {len(problems)} PROBLEM(S) to fix before publishing' if problems else '; no problems')) if any(r['lic']['attribution'] for r in music): summary += ('. CC BY music: put the credit in the description; if a Content ID claim appears, dispute it with ' 'the licence link (references/licences.md)') return {'summary': summary, 'markdown': '\n'.join(md) + '\n', 'description': '\n'.join(d) + '\n', 'rows': [ {k: (v['key'] if k == 'lic' else v) for k, v in r.items()} for r in rows], 'problems': problems, 'notes': notes} def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument('--root', default='.', help='project root: relative paths resolve against it') ap.add_argument('--report', default='out/qa/mix_report.json') ap.add_argument('--manifests', default='audio/assets/manifests') ap.add_argument('--design', help='the design file (derives the processing and music-edit sentences)') ap.add_argument('--audit', help='audit.json from audit.py: unconfirmed licences become problems') ap.add_argument('--out', default='CREDITS.md') ap.add_argument('--desc', default='out/CREDITS_description.txt') ap.add_argument('--title', help='film name for the heading') a = ap.parse_args(argv) root = os.path.abspath(a.root) try: res = credits(root, a.report, a.manifests, a.design, a.audit, a.title) except FileNotFoundError as e: say(f'credits.py: {e}') return 2 for p, text in ((a.out, res['markdown']), (a.desc, res['description'])): p = p if os.path.isabs(p) else os.path.join(root, p) os.makedirs(os.path.dirname(p) or '.', exist_ok=True) open(p, 'w', encoding='utf-8').write(text) say(res['summary']) say(f'wrote {a.out} and {a.desc}') for p in res['problems']: say(f'PROBLEM: {p}') return 1 if res['problems'] else 0 if __name__ == '__main__': sys.exit(main()) - skills/real-sound/scripts/licences.py (6954 bytes)
"""Licence classification and manifest loading shared by audit.py and credits.py (real-sound skill). import licences as L L.classify('CC BY 4.0') # {'key': 'by4', 'status': 'allowed', 'name': 'CC BY 4.0', 'url': ..., 'attribution': True} L.classify('CC BY-NC 4.0') # status 'forbidden', reason 'NonCommercial: ...' entries, notes = L.load_manifests('audio/assets/manifests') status is 'allowed' (CC0, public domain, CC BY 2.0-4.0, Mixkit free licences, Pixabay Content License), 'forbidden' (NonCommercial, NoDerivatives, ShareAlike, Sampling+, personal-use, custom, editorial or disputed licences) or 'unknown' (anything else: read the item's own page and fix the manifest). The policy and how to verify a licence on each site: references/licences.md. """ import glob import json import os import re CC = 'https://creativecommons.org/' FIXED = { 'cc0': ('CC0 1.0 (public domain dedication)', CC + 'publicdomain/zero/1.0/', False), 'pd': ('Public Domain Mark 1.0', CC + 'publicdomain/mark/1.0/', False), 'mixkit-sfx': ('Mixkit Sound Effects Free License', 'https://mixkit.co/license/#sfxFree', False), 'mixkit-music': ('Mixkit Stock Music Free License', 'https://mixkit.co/license/#musicFree', False), 'pixabay': ('Pixabay Content License', 'https://pixabay.com/service/license-summary/', False), } FORBID = [ # (pattern on the lower-cased licence text, reason) (r'disputed', 'disputed: the sources disagree about the licence'), (r'\bnc\b|non-?commercial', 'NonCommercial: a launch video is commercial use'), (r'\bnd\b|no-?deriv', 'NoDerivatives: syncing to picture, trimming and editing are derivatives'), (r'\bsa\b|share-?alike', 'ShareAlike: the whole film would have to be released under CC BY-SA'), (r'sampling', 'Sampling+ / Sampling licences are retired and restrict use'), (r'personal', 'personal use only'), (r'custom|free with credit|social media', 'a custom licence: not a standard licence the audit can trust'), (r'editorial', 'editorial use only'), ] RESERVED = r'all rights reserved|\bcopyrighted\b' # forbidden alone; next to a free licence it is ambiguous def classify(text): """licence text (as written in a manifest or seen on a page) -> {key, status, name, url, attribution, reason}""" s = (text or '').strip().lower() if not s: return {'key': 'none', 'status': 'unknown', 'name': None, 'url': None, 'attribution': False, 'reason': 'no licence recorded'} for pat, why in FORBID: if re.search(pat, s.replace('_', ' ')): return {'key': 'forbidden', 'status': 'forbidden', 'name': text, 'url': None, 'attribution': False, 'reason': why} if 'restricted' in s: return {'key': 'restricted', 'status': 'unknown', 'name': text, 'url': None, 'attribution': False, 'reason': 'a restricted licence (e.g. Mixkit Restricted): read its terms for this use'} key = None if re.search(r'\bcc0\b|cc-0|creative commons 0|publicdomain/zero|\bzero\b|public domain dedication', s): key = 'cc0' elif 'public domain' in s or 'publicdomain/mark' in s: key = 'pd' elif 'mixkit' in s: key = 'mixkit-music' if 'music' in s else 'mixkit-sfx' elif 'pixabay' in s: key = 'pixabay' res = None if key: name, url, attr = FIXED[key] res = {'key': key, 'status': 'allowed', 'name': name, 'url': url, 'attribution': attr, 'reason': None} m = re.search(r'(?:\bby\b|attribution)[^0-9]{0,24}([1-4](?:\.[05])?)', s) if m and not res: ver = {'1': '1.0', '2': '2.0', '3': '3.0', '4': '4.0'}.get(m.group(1), m.group(1)) if ver.startswith('1'): return {'key': 'by1', 'status': 'unknown', 'name': f'CC BY {ver}', 'url': None, 'attribution': True, 'reason': 'CC BY 1.0 is rare: confirm it on the item page'} res = {'key': 'by' + ver.replace('.0', '').replace('.', ''), 'status': 'allowed', 'name': f'CC BY {ver}', 'url': f'{CC}licenses/by/{ver}/', 'attribution': True, 'reason': None} reserved = re.search(RESERVED, s) if reserved and not res: return {'key': 'forbidden', 'status': 'forbidden', 'name': text, 'url': None, 'attribution': False, 'reason': 'all rights reserved'} if reserved and 'all rights reserved' in s: # a free licence and "all rights reserved" contradict each other return {'key': 'unknown', 'status': 'unknown', 'name': text, 'url': None, 'attribution': res['attribution'], 'reason': f'names {res["name"]} and "all rights reserved": read the item page'} return res or {'key': 'unknown', 'status': 'unknown', 'name': text, 'url': None, 'attribution': False, 'reason': 'not a licence this skill recognises: read the item page and record the exact licence'} def rel(path, root): """path relative to the project root with forward slashes (case-insensitive prefix match, for Windows)""" p = (path or '').replace('\\', '/') r = os.path.abspath(root).replace('\\', '/').rstrip('/') + '/' return p[len(r):] if p.lower().startswith(r.lower()) else p def load_manifests(folder, skip=('audit.json',)): """every manifest entry (dicts with a "file") from folder/*.json, each with "_manifest"; plus notes on skipped files. A manifest is a JSON list of entries, or an object holding one under "entries" / "items".""" entries, notes = [], [] for m in sorted(glob.glob(os.path.join(folder, '*.json'))): if os.path.basename(m) in skip or os.path.basename(m).startswith('audit.'): # audits and their backups continue try: d = json.load(open(m, encoding='utf-8')) except Exception as e: # noqa: BLE001 notes.append(f'{os.path.basename(m)}: not valid JSON ({e})') continue if isinstance(d, dict): d = d.get('entries') or d.get('items') if not isinstance(d, list): notes.append(f'{os.path.basename(m)}: not a list of entries (a decision record?), skipped') continue for e in d: if isinstance(e, dict) and e.get('file'): entries.append({**e, '_manifest': m.replace('\\', '/')}) return entries, notes def source_name(entry): """a readable source name from the entry's page_url host (Freesound.org, Mixkit, ...) or its "source" field""" url = entry.get('page_url') or entry.get('download_url') or '' host = re.sub(r'^www\.', '', re.sub(r'^[a-z]+://', '', url.lower()).split('/')[0]) known = {'freesound.org': 'Freesound.org', 'mixkit.co': 'Mixkit', 'pixabay.com': 'Pixabay', 'archive.org': 'the Internet Archive', 'commons.wikimedia.org': 'Wikimedia Commons', 'github.com': 'GitHub'} for k, v in known.items(): if host.endswith(k): return v return host or (entry.get('source') or 'unknown source').split(' (')[0] - skills/real-sound/scripts/master.py (15202 bytes)
#!/usr/bin/env python3 """ master.py: cinetic's mix bus and mastering chain, plus loudness measurement. Chain (finish): 28 Hz high-pass -> mono below 120 Hz -> 2:1 bus compressor above -14 dBFS (5 ms RMS detector, 15 ms attack, 120 ms release) -> soft saturation + air -> loudness passes to the target LUFS, each followed by a true-peak lookahead limiter (4x oversampled detection, 4 ms lookahead, 80 ms release, ceiling 0.77 linear = -2.3 dBFS, which leaves room for AAC overshoot) -> edge fades, always: a 3 ms raised-cosine fade-in from exact zero at sample 0 (a sound already at level on sample 0 clicks and cuts in mid-action) and a raised-cosine fade-out of at least 10 ms (60 ms by default) onto the last sample -> last 480 samples zeroed. score.py imports sidechain_times(), finish() and measure(). Standalone use: python3 master.py mix.wav public/audio/soundtrack.wav --lufs -14 --ceiling 0.77 python3 master.py music.wav ducked.wav --sidechain kick.wav --sc-depth 0.55 --lufs -14 python3 master.py --measure public/audio/soundtrack.wav --json out/qa/loudness.json Exit code 0 when the output meets the gate (|LUFS - target| <= --tol and true peak <= --max-tp), 1 when it does not or on error. The JSON report holds integrated LUFS, true peak (dBTP, 4x oversampled), LRA, the loudest momentary block and its time, limiter gain reduction and tail level. """ import argparse import json import os import sys import numpy as np from scipy import signal from scipy.ndimage import maximum_filter1d, minimum_filter1d SR = 48000 HEAD_FADE = 0.003 # s, raised-cosine fade-in at sample 0, applied after the limiter on every master END_FADE_MIN = 0.010 # s, the shortest fade-out onto the last sample, whatever end_fade asks for # ------------------------------------------------------------------------------------------ # measurement # ------------------------------------------------------------------------------------------ def _stereo(x): x = np.asarray(x, dtype=np.float64) return np.stack([x, x], axis=1) if x.ndim == 1 else x def _kw(x): """BS.1770 K-weighting (48 kHz coefficients): high shelf then RLB high-pass.""" b1, a1 = [1.53512485958697, -2.69169618940638, 1.19839281085285], [1.0, -1.69065929318241, 0.73248077421585] b2, a2 = [1.0, -2.0, 1.0], [1.0, -1.99004745483398, 0.99007225036621] return signal.lfilter(b2, a2, signal.lfilter(b1, a1, x, axis=0), axis=0) def blocks(x, win=0.4, hop=0.1): """Loudness (LUFS) of sliding blocks; 0.4 s = momentary, 3 s = short-term. Returns (t_mid, L).""" y = _kw(_stereo(x)) p = np.cumsum(np.concatenate([np.zeros((1, 2)), y ** 2]), axis=0) w, h = int(win * SR), int(hop * SR) if len(y) < w: return np.array([len(y) / SR / 2]), np.array([-70.0]) starts = np.arange(0, len(y) - w + 1, h) ms = (p[starts + w] - p[starts]) / w L = -0.691 + 10 * np.log10(np.maximum(ms.sum(axis=1), 1e-12)) return (starts + w / 2) / SR, L def integrated(x): import pyloudnorm as pyln return float(pyln.Meter(SR).integrated_loudness(_stereo(x))) def lra(x): """EBU loudness range: 10th-95th percentile of gated 3 s short-term loudness.""" _, st = blocks(x, 3.0, 0.1) st = st[st > -70] if len(st) < 2: return 0.0 rel = 10 * np.log10(np.mean(10 ** (st / 10))) - 20 st = st[st > rel] return float(np.percentile(st, 95) - np.percentile(st, 10)) if len(st) > 1 else 0.0 def true_peak_db(x): up = signal.resample_poly(_stereo(x), 4, 1, axis=0) return float(20 * np.log10(np.max(np.abs(up)) + 1e-12)) def measure(x): x = _stereo(x) tm, m = blocks(x, 0.4, 0.1) k = int(np.argmax(m)) tail = x[-int(0.05 * SR):] return { 'lufs': round(integrated(x), 2), 'true_peak_db': round(true_peak_db(x), 2), 'sample_peak_db': round(float(20 * np.log10(np.max(np.abs(x)) + 1e-12)), 2), 'lra': round(lra(x), 2), 'momentary_max': round(float(m[k]), 2), 'momentary_max_t': round(float(tm[k]), 3), 'tail_50ms_db': round(float(20 * np.log10(np.sqrt(np.mean(tail ** 2)) + 1e-12)), 1), 'last_480_zero': bool(np.all(x[-480:] == 0)), 'seconds': round(len(x) / SR, 4), } # ------------------------------------------------------------------------------------------ # dynamics # ------------------------------------------------------------------------------------------ def sidechain_times(hits, n, depth=0.55, tau=0.14, attack=0.003, length=0.6): """Duck gain (n, 1) from (t_seconds, weight) pairs: each hit pulls the music down by depth*weight with a 3 ms attack and recovers with time constant tau.""" g = np.ones(n) a = int(attack * SR) ramp = 0.5 - 0.5 * np.cos(np.linspace(0, np.pi, max(a, 1))) seg_t = np.arange(int(length * SR)) / SR shape = np.exp(-seg_t / tau) shape[:a] *= ramp for t, w in hits: i = int(round(t * SR)) if i >= n: continue j = min(n, i + len(shape)) s0 = max(0, -i) g[max(i, 0):j] = np.minimum(g[max(i, 0):j], 1 - depth * w * shape[s0:j - i]) return g[:, None] def sidechain_key(key, depth=0.55, tau=0.14, hop=48): """Duck gain (n, 1) that follows a key signal (a kick stem): instant attack, release tau.""" k = np.abs(_stereo(key)).max(axis=1) nb = int(np.ceil(len(k) / hop)) v = np.pad(k, (0, nb * hop - len(k))).reshape(nb, hop).max(axis=1) v = v / (np.percentile(v[v > 0], 99.9) if np.any(v > 0) else 1.0) rel = np.exp(-hop / (tau * SR)) e = np.empty(nb) cur = 0.0 for i, x in enumerate(v.tolist()): cur = x if x > cur else cur * rel e[i] = cur g = 1 - depth * np.clip(e, 0, 1) return np.interp(np.arange(len(k)), np.arange(nb) * hop + hop / 2, g)[:, None] def mono_below(x, fc=120): """Sum the stereo image to mono below fc so the low end is centred and translates to phones.""" x = _stereo(x) mid = x.mean(axis=1, keepdims=True) side = signal.sosfilt(signal.butter(2, fc, 'high', fs=SR, output='sos'), (x[:, :1] - x[:, 1:]) / 2, axis=0) return np.concatenate([mid + side, mid - side], axis=1) def bus_comp(x, thr=-14.0, ratio=2.0, attack=0.015, release=0.12, rms=0.005, hop=48): """Glue compressor: true RMS detector (rms seconds), gain computed at a 1 ms control rate. Returns (y, gain_reduction_db per sample).""" x = _stereo(x) det = signal.sosfilt(signal.butter(1, 1 / (2 * np.pi * rms), 'low', fs=SR, output='sos'), np.mean(x ** 2, axis=1)) nb = int(np.ceil(len(x) / hop)) d = np.pad(det, (0, nb * hop - len(det)), mode='edge').reshape(nb, hop).max(axis=1) over = np.maximum(0, 10 * np.log10(np.maximum(d, 1e-12)) - thr) target = -over * (1 - 1 / ratio) att, rel = np.exp(-hop / (attack * SR)), np.exp(-hop / (release * SR)) g = np.empty(nb) cur = 0.0 for i, v in enumerate(target.tolist()): cur = v + (cur - v) * (att if v < cur else rel) g[i] = cur gr = np.interp(np.arange(len(x)), np.arange(nb) * hop + hop / 2, g) return x * (10 ** (gr / 20))[:, None], gr def limiter(x, ceiling=0.77, look=0.004, release=0.08, hop=16): """True-peak lookahead limiter. Detection on a 4x oversampled copy catches inter-sample overs; the gain is computed per 16-sample block (min over neighbouring blocks, so the interpolated gain never exceeds what any sample needs), attacks over the lookahead and releases with time constant `release`. Returns (y, gain per sample).""" x = _stereo(x) n = len(x) up = np.abs(signal.resample_poly(x, 4, 1, axis=0)).max(axis=1) a = np.pad(up, (0, max(0, 4 * n - len(up))))[:4 * n].reshape(n, 4).max(axis=1) la = max(hop, int(look * SR)) peak = maximum_filter1d(a, size=la, origin=-(la // 2), mode='nearest') # max over [i, i+la) need = np.minimum(1.0, ceiling / np.maximum(peak, 1e-9)) nb = int(np.ceil(n / hop)) gb = np.pad(need, (0, nb * hop - n), mode='edge').reshape(nb, hop).min(axis=1) k = max(3, la // hop) win = np.hanning(k + 2)[1:-1] win /= win.sum() gb = np.minimum(gb, np.convolve(np.pad(gb, (len(win) // 2, len(win) - 1 - len(win) // 2), mode='edge'), win, mode='valid')) rel = np.exp(-hop / (release * SR)) out = np.empty(nb) cur = 1.0 for i, v in enumerate(gb.tolist()): cur = v if v < cur else v + (cur - v) * rel out[i] = cur out = minimum_filter1d(out, 3, mode='nearest') g = np.minimum(np.interp(np.arange(n), np.arange(nb) * hop + hop / 2, out), need) return x * g[:, None], g def loudness_passes(x, target=-14.0, ceiling=0.77, passes=3, tol=0.05, max_passes=8): """Normalize to target LUFS then limit; repeat (limiting lowers loudness) until within tol.""" g = np.ones(len(x)) for p in range(max_passes): x = x * 10 ** ((target - integrated(x)) / 20) x, g = limiter(x, ceiling) if p + 1 >= passes and abs(integrated(x) - target) <= tol: break return x, g def glue(x, drive=1.15, air=0.25): """Soft saturation and a gentle high shelf (air).""" x = np.tanh(x * 0.9 * drive) / np.tanh(drive) if air: x = x + signal.sosfilt(signal.butter(1, 2500, 'high', fs=SR, output='sos'), x, axis=0) * air return x def edge_fades(x, head=HEAD_FADE, tail=END_FADE_MIN): """Raised-cosine fade-in over `head` s from exact zero at sample 0, and fade-out over `tail` s to zero on the last sample. Run after the limiter, so nothing raises the edges again.""" x = _stereo(x).copy() n = len(x) for d, rising in ((head, True), (tail, False)): k = min(n, int(round(d * SR))) if k > 1: w = 0.5 - 0.5 * np.cos(np.pi * np.arange(k) / (k - 1)) # 0 -> 1, raised cosine if rising: x[:k] *= w[:, None] else: x[-k:] *= w[::-1, None] return x def finish(mix, lufs=-14.0, ceiling=0.77, mono_hz=120, comp=True, drive=1.15, air=0.25, hp_hz=28, fade=0.0, end_fade=0.06, tail_zero=480): """Full chain for a summed mix. Returns (master, info) where info has the limiter trace.""" x = _stereo(mix) if hp_hz: x = signal.sosfilt(signal.butter(2, hp_hz, 'high', fs=SR, output='sos'), x, axis=0) if mono_hz: x = mono_below(x, mono_hz) gr = np.zeros(len(x)) if comp: x, gr = bus_comp(x) if drive: x = glue(x, drive, air) if fade and fade > 0: t = np.arange(len(x)) / SR x = x * (np.clip((len(x) / SR - 0.03 - t) / fade, 0, 1) ** 2)[:, None] x, g = loudness_passes(x, lufs, ceiling) x = edge_fades(x, HEAD_FADE, max(end_fade or 0.0, END_FADE_MIN)) if tail_zero: x[-tail_zero:] = 0 lim_db = -20 * np.log10(np.maximum(g, 1e-9)) return x, {'limiter_gr_db': lim_db, 'comp_gr_db': -gr} def gate(report, target, tol, max_tp): fails = [] if abs(report['lufs'] - target) > tol: fails.append(f"integrated {report['lufs']} LUFS not within {target}+-{tol}") if report['true_peak_db'] > max_tp: fails.append(f"true peak {report['true_peak_db']} dBTP above {max_tp}") if not report['last_480_zero']: fails.append('last 480 samples are not digital zero') return fails # ------------------------------------------------------------------------------------------ # CLI # ------------------------------------------------------------------------------------------ def _read(path): import soundfile as sf x, sr = sf.read(path, always_2d=True, dtype='float64') if x.shape[1] == 1: x = np.repeat(x, 2, axis=1) x = x[:, :2] if sr != SR: from math import gcd g = gcd(SR, sr) x = signal.resample_poly(x, SR // g, sr // g, axis=0) return x def main(argv=None): ap = argparse.ArgumentParser(description='Master a WAV to target loudness, or measure one (--measure).') ap.add_argument('input', help='input WAV (any rate; resampled to 48 kHz)') ap.add_argument('output', nargs='?', help='output WAV (48 kHz, 24-bit)') ap.add_argument('--measure', action='store_true', help='only measure the input') ap.add_argument('--lufs', type=float, default=-14.0, help='target integrated loudness (default -14)') ap.add_argument('--ceiling', type=float, default=0.77, help='limiter ceiling, linear (default 0.77)') ap.add_argument('--tol', type=float, default=0.5, help='gate tolerance in LU (default 0.5)') ap.add_argument('--max-tp', type=float, default=-1.5, help='gate: max true peak dBTP (default -1.5)') ap.add_argument('--sidechain', metavar='KEY.wav', help='duck the input from this key signal first') ap.add_argument('--sc-depth', type=float, default=0.55) ap.add_argument('--sc-tau', type=float, default=0.14) ap.add_argument('--mono-hz', type=float, default=120, help='mono below this frequency; 0 disables') ap.add_argument('--no-comp', action='store_true', help='skip the bus compressor') ap.add_argument('--no-glue', action='store_true', help='skip saturation and air') ap.add_argument('--fade', type=float, default=0.0, help='quadratic fade-out over the last N seconds') ap.add_argument('--tail-zero', type=int, default=480, help='samples zeroed at the end (default 480)') ap.add_argument('--json', metavar='PATH', help="write the report JSON here ('-' for stdout)") a = ap.parse_args(argv) try: x = _read(a.input) if a.measure: rep = measure(x) fails = gate(rep, a.lufs, a.tol, a.max_tp) else: if not a.output: ap.error('output path required unless --measure') if a.sidechain: key = _read(a.sidechain) key = np.pad(key, ((0, max(0, len(x) - len(key))), (0, 0)))[:len(x)] x = x * sidechain_key(key, a.sc_depth, a.sc_tau) y, info = finish(x, a.lufs, a.ceiling, a.mono_hz, not a.no_comp, 0 if a.no_glue else 1.15, 0 if a.no_glue else 0.25, fade=a.fade, tail_zero=a.tail_zero) import soundfile as sf os.makedirs(os.path.dirname(os.path.abspath(a.output)), exist_ok=True) sf.write(a.output, y.astype(np.float32), SR, subtype='PCM_24') rep = measure(y) rep['limiter_max_gr_db'] = round(float(info['limiter_gr_db'].max()), 2) rep['output'] = a.output fails = gate(rep, a.lufs, a.tol, a.max_tp) rep['pass'] = not fails rep['fails'] = fails except Exception as e: # noqa: BLE001 print('error:', e, file=sys.stderr) return 1 if a.json == '-': print(json.dumps(rep, indent=1)) elif a.json: os.makedirs(os.path.dirname(os.path.abspath(a.json)), exist_ok=True) json.dump(rep, open(a.json, 'w'), indent=1) print(f"{'PASS' if not fails else 'FAIL'} {rep['lufs']} LUFS TP {rep['true_peak_db']} dBTP " f"LRA {rep['lra']} LU - skills/real-sound/scripts/mix.py (34125 bytes)
#!/usr/bin/env python """real-sound mixer: real recordings placed on the picture's cues. Nothing is synthesized here. python -I <skill>/scripts/mix.py [--root .] [--design audio/sounddesign.json] [--cues out/cues.json] [--out out/audio/soundtrack.wav] [--stems out/audio/stems] [--no-master] [--only keyboard] [--dump out/audio-review/dump] [--trace out/qa/adds.json] Run it from the project root (or pass --root). Every relative path (design, cues, outputs, the "file" of every sample) is relative to the root. Full reference with examples: references/design-format.md. The cue file (JSON, from the picture's timeline): {fps, total (frames), events: [{f, kind, id?, weight?, pan?, ...}]} (or a list whose first element is that object). A design without rules needs no cue file. The design file (JSON) describes, in film seconds: duration film length in seconds (default: cue total / fps) cues optional default cue file path (the --cues flag wins) include [other design fragments to merge: samples / slices / pools / rules / place / ambience / music] samples name -> {file, start?, end?, gain_db?, norm_peak_db?, mono?, fade_in?, fade_out?, eq?, pitch?, glide?: [from, to] semitones (tape-style varispeed across the sample), env?: [[t, dB], ...]} a trimmed piece of a downloaded recording (file paths are relative to the project root) slices name -> {file, start?, end?, pre?, len?, min_gap?, max?, pick?, ...sample opts} cut a recording of many hits (typing, clicks) into single hits at its detected onsets: name#0, name#1... pools name -> [sample names; "slicegroup#*" expands to all of its slices] rules [{match: {kind?, id?, from?, to?}, pool, mode: cycle|hash|fixed, gain_db?, weight_db?, jitter_db?, pitch?: [lo, hi] semitones, pitch_ramp?: [a, b], gain_ramp?: [a, b] (across the matched events), pan?: "cue"|number, pan_scale?, align: attack|peak|end|start, offset?, bus?}] every cue event matching a rule gets a sound from the rule's pool (several rules may layer one event) place [{sample, at, gain_db?, pan?, align?, offset?, pitch?, bus?}] sounds with no cue event ambience [{name?, file, src_start?, src_end?, at, until, fade_in?, fade_out?, gain_db?, eq?, width?, auto?: [[t, db], ...]}] (src_start..src_end is the clean window; it is looped with a 1.5 s crossfade if the bed is longer) music {file, src_bpm, target_bpm?, stretch?: "rubberband"|"none", gain_db?, eq?, segments: [{src_from, src_to, at, fade_in?, fade_out?, gain_db?}]} src_* in ORIGINAL source seconds buses {sfx|amb|music: {gain_db?, eq?, auto?: [[t, db], ...]}} master {lufs?, ceiling?, no_glue?, no_comp?, mono_hz?} Processing is limited to trimming, fades, gain, pan, EQ, resampling (pitch variation), tempo stretch of the music, summing and mastering (master.py next to this script). Writes the soundtrack, stems (sfx.wav, music.wav, amb.wav), out/qa/mix_report.json (every placement, unsounded cue events, bus levels, files_used for the credits) and out/qa/cues_sounded.json (the cue events that received a sound, for an A/V sync audit). --only NAME solo render: keep only the include fragments whose path contains NAME (no master; the unmastered mix is written to --out, default out/audio-review/solo/<NAME>.wav). Variation is keyed on rule names, so a solo render plays exactly the same sounds as the full mix. --no-master write the unmastered mix to --out (with master: --out is mastered, the unmastered sum is premaster.wav next to it). --dump DIR write every sample / slice of the design as its own WAV + _samples.json (check trims), then exit. --trace FILE also write every Mix.add() (bus, start sample, length, gain, pan, sample, rule) for QA attribution. """ import argparse, hashlib, json, math, os, re, subprocess, sys, zlib import numpy as np import soundfile as sf from scipy import signal SR = 48000 ROOT = os.getcwd() # the project root (set by --root) CACHE = os.path.join(ROOT, 'out', 'audio', 'cache') MASTER = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'master.py') def P(p): return p if os.path.isabs(p) else os.path.join(ROOT, p) def db2a(d): return 10.0 ** (d / 20.0) # ------------------------------------------------------------------ decoding (cached) _dec = {} def decode(path): path = P(path) if path in _dec: return _dec[path] os.makedirs(CACHE, exist_ok=True) st = os.stat(path) key = hashlib.sha1(f'{path}|{st.st_size}|{st.st_mtime}'.encode()).hexdigest()[:16] npy = os.path.join(CACHE, key + '.npy') if os.path.exists(npy): x = np.load(npy) else: p = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-i', path, '-f', 'f32le', '-acodec', 'pcm_f32le', '-ac', '2', '-ar', str(SR), '-'], capture_output=True) if p.returncode != 0: raise RuntimeError(f'decode failed {path}: {p.stderr.decode(errors="replace")[:300]}') x = np.frombuffer(p.stdout, np.float32).reshape(-1, 2).copy() tmp = f'{npy}.{os.getpid()}.tmp.npy' np.save(tmp, x) os.replace(tmp, npy) # atomic: other mixers may read the cache at the same time _dec[path] = x return x def stretched(path, ratio): """Whole-file tempo change with Rubber Band (ffmpeg filter). ratio = target_bpm / src_bpm (speed factor).""" if abs(ratio - 1) < 1e-6: return decode(path) src = P(path) st = os.stat(src) key = hashlib.sha1(f'{src}|{st.st_size}|{st.st_mtime}|{ratio:.6f}|rb2'.encode()).hexdigest()[:16] out = os.path.join(CACHE, f'stretch_{key}.wav') if not os.path.exists(out): os.makedirs(CACHE, exist_ok=True) af = (f'rubberband=tempo={ratio:.6f}:transients=mixed:detector=compound:phase=laminar:window=standard:' f'smoothing=off:formant=shifted:pitchq=quality:channels=together') tmp = out.replace('.wav', f'.{os.getpid()}.tmp.wav') r = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-y', '-i', src, '-af', af, '-ar', str(SR), '-ac', '2', '-c:a', 'pcm_f32le', tmp], capture_output=True) if r.returncode != 0: raise RuntimeError('rubberband failed: ' + r.stderr.decode(errors='replace')[:400]) os.replace(tmp, out) return decode(out) # ------------------------------------------------------------------ DSP helpers (processing only) def rc_fade(n, rising=True): if n <= 0: return np.ones(0) w = 0.5 - 0.5 * np.cos(np.linspace(0, np.pi, n)) return w if rising else w[::-1] def apply_fades(x, fin, fout): x = x.copy() a, b = int(fin * SR), int(fout * SR) a, b = min(a, len(x)), min(b, len(x)) if a: x[:a] *= rc_fade(a)[:, None] if b: x[len(x) - b:] *= rc_fade(b, False)[:, None] return x def biquad(kind, f0, q=0.707, gain_db=0.0): A = 10 ** (gain_db / 40) w0 = 2 * np.pi * f0 / SR al = np.sin(w0) / (2 * q) c = np.cos(w0) if kind == 'peak': b = [1 + al * A, -2 * c, 1 - al * A]; a = [1 + al / A, -2 * c, 1 - al / A] elif kind == 'lowshelf': s = 2 * np.sqrt(A) * al b = [A * ((A + 1) - (A - 1) * c + s), 2 * A * ((A - 1) - (A + 1) * c), A * ((A + 1) - (A - 1) * c - s)] a = [(A + 1) + (A - 1) * c + s, -2 * ((A - 1) + (A + 1) * c), (A + 1) + (A - 1) * c - s] elif kind == 'highshelf': s = 2 * np.sqrt(A) * al b = [A * ((A + 1) + (A - 1) * c + s), -2 * A * ((A - 1) + (A + 1) * c), A * ((A + 1) + (A - 1) * c - s)] a = [(A + 1) - (A - 1) * c + s, 2 * ((A - 1) - (A + 1) * c), (A + 1) - (A - 1) * c - s] else: raise ValueError(kind) return np.array(b) / a[0], np.array(a) / a[0] def eq(x, spec): if not spec: return x y = x.astype(np.float64) if spec.get('hp'): sos = signal.butter(spec.get('hp_order', 2), spec['hp'], 'highpass', fs=SR, output='sos') y = signal.sosfilt(sos, y, axis=0) if spec.get('lp'): sos = signal.butter(spec.get('lp_order', 2), spec['lp'], 'lowpass', fs=SR, output='sos') y = signal.sosfilt(sos, y, axis=0) for f0, q, g in spec.get('peq', []): b, a = biquad('peak', f0, q, g); y = signal.lfilter(b, a, y, axis=0) if spec.get('lowshelf'): f0, g = spec['lowshelf']; b, a = biquad('lowshelf', f0, 0.707, g); y = signal.lfilter(b, a, y, axis=0) if spec.get('highshelf'): f0, g = spec['highshelf']; b, a = biquad('highshelf', f0, 0.707, g); y = signal.lfilter(b, a, y, axis=0) return y.astype(np.float32) def pan_gains(p): p = max(-1.0, min(1.0, float(p))) th = (p + 1) * np.pi / 4 return np.cos(th) * np.sqrt(2), np.sin(th) * np.sqrt(2) def resample_pitch(x, semis): if abs(semis) < 1e-4: return x import soxr r = 2 ** (semis / 12.0) return soxr.resample(x, SR * r, SR, quality='VHQ').astype(np.float32) def varispeed(x, s0, s1): """tape-style pitch glide from s0 to s1 semitones across the sample (resampling a recording; no synthesis)""" import soxr r0, r1 = 2 ** (s0 / 12.0), 2 ** (s1 / 12.0) up = 4 xo = soxr.resample(x.astype(np.float64), SR, SR * up, quality='VHQ') rmax = max(r0, r1, 1.0) if rmax > 1.0: # band-limit before reading faster, so the glide never aliases sos = signal.butter(8, 0.95 * (SR / 2) / rmax, 'lowpass', fs=SR * up, output='sos') xo = signal.sosfiltfilt(sos, xo, axis=0) L = max(2, int(len(x) / ((r0 + r1) / 2))) r = np.linspace(r0, r1, L) pos = np.concatenate([[0.0], np.cumsum(r[:-1])]) * up pos = np.clip(pos, 0, len(xo) - 1.001) i = pos.astype(np.int64) f = (pos - i)[:, None] y = xo[i] * (1 - f) + xo[np.minimum(i + 1, len(xo) - 1)] * f return y.astype(np.float32) def env_index(x, mode): m = np.abs(x).max(axis=1) if mode == 'start': return 0 if mode == 'end': nz = np.where(m > m.max() * 0.003)[0] return int(nz[-1]) if len(nz) else len(x) - 1 w = int(0.001 * SR) if mode == 'attack' else int(0.005 * SR) n = len(m) // w if n == 0: return 0 e = m[: n * w].reshape(n, w).max(axis=1) if mode == 'peak': return int(np.argmax(e) * w + w // 2) return int(np.argmax(e >= e.max() * 0.1) * w) # attack: first 1 ms within 20 dB of the peak def auto_curve(points, n, default=0.0): """piecewise-linear dB automation over film time -> linear gain per sample""" if not points: return None pts = sorted(points) t = np.arange(n) / SR d = np.interp(t, [p[0] for p in pts], [p[1] for p in pts]) return db2a(d).astype(np.float32) # ------------------------------------------------------------------ samples class Lib: def __init__(self, design): self.d = design self.samples = {} self.meta = {} for name, s in (design.get('samples') or {}).items(): self.samples[name] = self._make(s) self.meta[name] = {'file': s['file'], 'start': s.get('start', 0), 'end': s.get('end'), 'pitch': s.get('pitch', 0)} for name, s in (design.get('slices') or {}).items(): for i, (x, t0) in enumerate(self._slice(s)): self.samples[f'{name}#{i}'] = x self.meta[f'{name}#{i}'] = {'file': s['file'], 'start': round(t0, 4), 'pitch': s.get('pitch', 0)} self.pools = {} for name, items in (design.get('pools') or {}).items(): out = [] for it in items: if it.endswith('#*'): g = it[:-2] out += sorted([k for k in self.samples if k.startswith(g + '#')], key=lambda k: int(k.split('#')[1])) else: if it not in self.samples: raise KeyError(f'pool {name}: unknown sample {it}') out.append(it) if not out: raise ValueError(f'pool {name} is empty') self.pools[name] = out self._pitched = {} def _finish(self, x, s): if s.get('mono'): m = x.mean(axis=1, keepdims=True) x = np.repeat(m, 2, axis=1) if s.get('reverse'): raise ValueError('reverse is not used') x = eq(x, s.get('eq')) if s.get('pitch'): x = resample_pitch(x, s['pitch']) if s.get('glide'): # [from, to] semitones across the sample x = varispeed(x, *s['glide']) if s.get('env'): # [[t_seconds_from_sample_start, dB], ...] gain envelope inside the sample pts = sorted(s['env']) t = np.arange(len(x)) / SR x = x * db2a(np.interp(t, [p[0] for p in pts], [p[1] for p in pts]))[:, None].astype(np.float32) if s.get('norm_peak_db') is not None: pk = float(np.abs(x).max()) or 1.0 x = x * (db2a(s['norm_peak_db']) / pk) x = apply_fades(x, s.get('fade_in', 0.002), s.get('fade_out', 0.012)) return (x * db2a(s.get('gain_db', 0.0))).astype(np.float32) def _make(self, s): x = decode(s['file']) a = int(s.get('start', 0) * SR) b = int(s['end'] * SR) if s.get('end') is not None else len(x) return self._finish(x[a:b], s) def _slice(self, s): import librosa x = decode(s['file']) a = int(s.get('start', 0) * SR) b = int(s['end'] * SR) if s.get('end') is not None else len(x) seg = x[a:b] mono = seg.mean(axis=1) hop = 128 on = librosa.onset.onset_detect(y=mono, sr=SR, hop_length=hop, backtrack=True, units='samples', delta=s.get('delta', 0.07), wait=int(s.get('min_gap', 0.06) * SR / hop)) on = [int(o) for o in on] # loudness gate: drop onsets far below the loudest (handling noise, the far keys) pk = [] for o in on: w = mono[o: o + int(0.03 * SR)] pk.append(float(np.abs(w).max()) if len(w) else 0) if pk: top = max(pk) on = [o for o, p in zip(on, pk) if p >= top * db2a(s.get('gate_db', -18))] pre, ln = int(s.get('pre', 0.004) * SR), int(s.get('len', 0.16) * SR) out = [] for i, o in enumerate(on): st = max(0, o - pre) en = min(len(seg), o + ln) if s.get('stop_before_next', True) and i + 1 < len(on): en = min(en, on[i + 1] - pre) if en - st < int(0.02 * SR): continue out.append((self._finish(seg[st:en], {**s, 'fade_out': s.get('fade_out', 0.02)}), (a + st) / SR)) if s.get('pick') is not None: out = [out[i] for i in s['pick'] if i < len(out)] if s.get('max'): out = out[: s['max']] if not out: raise V - skills/real-sound/scripts/mux.mjs (4488 bytes)
#!/usr/bin/env node // Put a soundtrack on the finished picture without re-encoding the video (stream copy; AAC 48 kHz stereo audio). // node <skill>/scripts/mux.mjs --video out/film.mp4 [--audio out/audio/soundtrack.wav] [--out out/film_sound.mp4] // [--abr 320k] [--keep-old out/superseded/film_prev.mp4] [--root .] // Relative paths resolve against --root (default: the current directory). The audio is cut to the video's own duration // (ffprobe), so a soundtrack that runs long never extends the film; a length mismatch over one frame is reported. // When --out is the --video file itself, the old file is moved to --keep-old first (default // out/superseded/<name>_prev<ext>); an existing keep-old file is never overwritten. Exit 0 = written and verified. import { spawnSync } from 'node:child_process'; import path from 'node:path'; import fs from 'node:fs'; const argv = process.argv.slice(2); if (argv.includes('-h') || argv.includes('--help')) { console.log(fs.readFileSync(new URL(import.meta.url), 'utf8').split('\n').slice(1, 8).map((l) => l.replace(/^\/\/ ?/, '')).join('\n')); process.exit(0); } const opt = (k, d) => { const i = argv.indexOf(`--${k}`); return i >= 0 && argv[i + 1] ? argv[i + 1] : d; }; const ROOT = path.resolve(opt('root', '.')); const R = (p) => (path.isAbsolute(p) ? p : path.join(ROOT, p)); const rel = (p) => path.relative(ROOT, p) || p; const fail = (m) => { console.error(`mux: ${m}`); process.exit(1); }; function probe(file) { const r = spawnSync('ffprobe', ['-v', 'error', '-show_entries', 'stream=codec_type,codec_name,r_frame_rate,duration:format=duration', '-of', 'json', file], { encoding: 'utf8' }); if (r.status !== 0) fail(`ffprobe failed on ${file}: ${(r.stderr || '').slice(0, 300)}`); const j = JSON.parse(r.stdout || '{}'); const v = (j.streams || []).find((s) => s.codec_type === 'video'); const a = (j.streams || []).find((s) => s.codec_type === 'audio'); const [n, d] = ((v && v.r_frame_rate) || '0/1').split('/').map(Number); const fmt = Number((j.format || {}).duration || 0); return { video: v, audio: a, fps: d ? n / d : 0, duration: Number((v && v.duration) || fmt), audioDuration: Number((a && a.duration) || fmt) }; } const audio = R(opt('audio', 'out/audio/soundtrack.wav')); let video = R(opt('video', 'out/film.mp4')); const out = R(opt('out', video)); const abr = opt('abr', '320k'); if (!fs.existsSync(audio)) fail(`no audio ${audio} (pass --audio)`); if (!fs.existsSync(video)) fail(`no video ${video} (pass --video)`); const pv = probe(video); if (!pv.video) fail(`${video} has no video stream`); const pa = probe(audio); const frame = pv.fps ? 1 / pv.fps : 1 / 60; const diff = pa.audioDuration - pv.duration; if (Math.abs(diff) > frame) { console.log(`note: the audio is ${diff > 0 ? 'longer' : 'SHORTER'} than the picture by ${Math.abs(diff).toFixed(3)} s ` + `(${(Math.abs(diff) / frame).toFixed(1)} frames)` + (diff > 0 ? ': it is cut at the picture\'s end' : ': the end will be silent')); } if (path.resolve(out) === path.resolve(video)) { const ext = path.extname(video); const keep = R(opt('keep-old', path.join('out', 'superseded', path.basename(video, ext) + '_prev' + ext))); fs.mkdirSync(path.dirname(keep), { recursive: true }); if (fs.existsSync(keep)) fail(`refusing to overwrite ${keep}; pass --keep-old <new path>`); fs.renameSync(video, keep); video = keep; console.log(`previous version kept at ${rel(keep)}`); } fs.mkdirSync(path.dirname(out), { recursive: true }); const ext = path.extname(out) || '.mp4'; const tmp = out.slice(0, out.length - path.extname(out).length) + '.muxing' + ext; const args = ['-v', 'error', '-y', '-i', video, '-i', audio, '-map', '0:v:0', '-map', '1:a:0', '-c:v', 'copy', '-c:a', 'aac', '-b:a', abr, '-ar', '48000', '-ac', '2', '-t', pv.duration.toFixed(6)]; if (/\.(mp4|m4v|mov)$/i.test(ext)) args.push('-movflags', '+faststart'); const r = spawnSync('ffmpeg', [...args, tmp], { stdio: 'inherit' }); if (r.status !== 0) { try { fs.unlinkSync(tmp); } catch { /* nothing to clean */ } fail('ffmpeg failed'); } const po = probe(tmp); if (!po.video || !po.audio) fail(`${tmp} lacks a video or audio stream`); fs.renameSync(tmp, out); console.log(`wrote ${rel(out)} (${(fs.statSync(out).size / 1e6).toFixed(1)} MB): video copied (${pv.video.codec_name}, ` + `${pv.fps.toFixed(3)} fps, ${pv.duration.toFixed(3)} s), audio ${po.audio.codec_name} ${abr} ${po.audioDuration.toFixed(3)} s`); - skills/real-sound/scripts/qa.py (54768 bytes)
#!/usr/bin/env python """Objective QA of a real-sound mix: what the critic lenses measure, in one pass, tied to the placements that caused it. python -I <skill>/scripts/qa.py [--root .] [--design audio/sounddesign.json] [--report out/qa/mix_report.json] [--trace out/qa/adds.json] [--stems out/audio/stems] [--master out/audio/soundtrack.wav] [--cues out/cues.json] [--only NAME] [--cache out/audio/cache] [--video out/film.mp4] [--out out/qa/qa.json] [--layers] [--listen] [--realness] [--json] Run it after `mix.py --trace out/qa/adds.json` (same design, same --only): the trace ties every click, masked hit and harsh peak to the placement that caused it. With --only, the report / stems default to mix.py's solo outputs (out/audio-review/solo/<only>_report.json, _stems) and there is no master (levels at stem scale). Without the trace only clicks, loudness and coverage run. No models needed; --listen / --realness add earshot's ears when installed. Sections (status ok / warn / fail + a plain summary): clicks > 14 kHz bursts concentrated in 1 ms (the av-audit detector) in the master and each stem, attributed to the placements whose start / end / body they sit in edges used samples that start mid-sound or are cut mid-decay (unfaded head / tail level vs their peak, and the source just outside the trim), a second hit inside a sample, steps in a stem at a placement's start / end (second-difference ratio), placements cut by the film's ends audibility every cue event's effect (its layers summed, rebuilt from the trace) vs the bed (music + amb) and vs everything else, in 1/3-octave bands over its loudest 60 ms and its first 20 ms: read >= 6 dB clear, 3-6 ok, 0-3 barely, < 0 masked (margins capped at +-60 dB); an effect peaking under -70 dBFS is SILENT (a trim that missed the sound: fail); not judged when the render has no bed (a solo); --layers also lists single layers that add nothing measurable harshness each event's 2-6 kHz peak (5 ms RMS, master scale) vs the music's loudest 2-6 kHz 5 ms level loudness integrated LUFS vs the design's target, true peak, LRA, loudest momentary (time, share of the runtime), short-term curve, per-act medians when the cue file has acts, head and tail of the master coverage cue events with no sound (unsounded or placed but silent); classes of action sounded only in part sync impacts by attack / peak (-45..+75 ms), whooshes and peak-aligned swells by their apex (+-45 ms), risers and end-aligned swells by their audible end vs the hit (-250..+30 ms); measured norms of professional launch films. A deviation that exactly one layer's rule offset explains is listed apart as deliberate density events per second, the most reused samples, "machine-gun" rules (one sample, no pitch or level change) listen --listen: earshot timeline + sheet + critique of the master; --realness: earshot realness of every source Thresholds and where they come from: references/process.md. Writes --out (JSON) and prints a digest. Exit code 1 when a section fails (a click at a placement edge in the master, a silent effect, stems of pure digital silence, the loudness gate), 2 on missing or mismatched inputs (one line says which flag to pass), else 0. """ import argparse, json, math, os, re, sys import numpy as np import soundfile as sf from scipy import signal sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import master as M # noqa: E402 import mix # noqa: E402 (read-only: the design loader, the sample library, envelope helpers) SR = mix.SR LONG = ('whoosh', 'riser', 'swell', 'suck') FC = 10 ** (np.arange(20, 42) / 10) # 1/3-octave centres 100 Hz .. 12.6 kHz BLO, BHI = FC * 2 ** (-1 / 6), FC * 2 ** (1 / 6) SILENT_DB = -70.0 # an event whose peak (master scale) is below this makes no sound: a trim that missed the recording CAP_DB = 60.0 # margins against a (near-)silent bed are reported as at most +60 dB class InputError(Exception): pass def db(v): return 20 * math.log10(max(float(v), 1e-12)) def pdb(p): return 10 * math.log10(max(float(p), 1e-20)) def fmt_t(t): m = int(t // 60) return f'{m}:{t - 60 * m:05.2f}' def say(s): print(str(s).encode('ascii', 'replace').decode()) def lufs(x): """integrated LUFS, or None for audio shorter than one 400 ms block or with no gated signal (silence)""" if x is None or len(x) < int(0.4 * SR): return None v = M.integrated(x) return v if math.isfinite(v) else None def clean(o): """JSON-safe: numpy scalars to Python, NaN / inf to None""" if isinstance(o, dict): return {k: clean(v) for k, v in o.items()} if isinstance(o, (list, tuple)): return [clean(v) for v in o] if isinstance(o, np.integer): return int(o) if isinstance(o, (float, np.floating)): return float(o) if math.isfinite(o) else None return o # ------------------------------------------------------------------ context class Ctx: def __init__(self, a): self.root = os.path.abspath(a.root) mix.ROOT = self.root mix.CACHE = os.path.join(self.root, a.cache) if a.cache else os.path.join(self.root, 'out', 'audio', 'cache') R = self.R = lambda p: os.path.normpath(p if os.path.isabs(p) else os.path.join(self.root, p)) def need(path, what, flag): if not os.path.exists(R(path)): raise InputError(f'{what} not found: {R(path)} ({flag})') return R(path) need(a.design, 'design file', 'pass --design') self.design = mix.load_design(a.design, a.only) self.report = json.load(open(need(a.report, 'mix report', 'run mix.py first or pass --report'), encoding='utf-8')) self.trace = json.load(open(R(a.trace))) if a.trace and os.path.exists(R(a.trace)) else None self.stems = {} for k in ('sfx', 'amb', 'music'): p = need(os.path.join(a.stems, k + '.wav'), f'stem {k}.wav', 'pass the --stems folder mix.py wrote') self.stems[k] = sf.read(p, dtype='float32', always_2d=True)[0] self.N = len(self.stems['sfx']) if {len(v) for v in self.stems.values()} != {self.N}: raise InputError(f'the stems in {R(a.stems)} have different lengths: re-render them with one mix.py run') if a.master and getattr(a, 'master_given', False): need(a.master, 'master', 'pass --master none to skip it') self.master = (sf.read(R(a.master), dtype='float64', always_2d=True)[0] if a.master and os.path.exists(R(a.master)) else None) if self.master is not None and abs(len(self.master) - self.N) > 1: raise InputError(f'the master {R(a.master)} ({len(self.master) / SR:.3f} s) does not match the stems ' f'({self.N / SR:.3f} s): pass the --master rendered with these stems, or --master none') cp = a.cues or self.design.get('cues') or 'out/cues.json' c = json.load(open(R(cp))) if os.path.exists(R(cp)) else {'fps': 60, 'events': []} self.cues = c[0] if isinstance(c, list) else c self.fps = self.cues.get('fps', 60) m = self.design.get('master') or {} self.target = m.get('lufs', -14) pre = sum(self.stems[k].astype(np.float64) for k in self.stems) self.pre_lufs = lufs(pre) self.master_lufs = lufs(self.master) both = self.master_lufs is not None and self.pre_lufs is not None self.G = self.master_lufs - self.pre_lufs if both else 0.0 # no master (or silence): stem scale self.scale = ('master' if both else 'stem') if self.master is not None else 'stem' self.no_bed = not (np.any(self.stems['music']) or np.any(self.stems['amb'])) self.lib = None self.only = a.only def bus_curve(design, bus, n): b = (design.get('buses') or {}).get(bus) or {} c = mix.auto_curve(b.get('auto'), n) return (np.ones(n) if c is None else c.astype(np.float64)) * mix.db2a(b.get('gain_db', 0.0)) def build_layers(ctx): """every sfx-bus placement rebuilt as it sits in the stem (sample, pitch, gain, pan, bus ride), grouped into events""" recs = [a for a in ctx.trace if 'sample' in a] pl = ctx.report.get('placements', []) if len(recs) != len(pl): return None, f'trace ({len(recs)} placements) and report ({len(pl)}) disagree: re-run mix.py with --trace' ctx.lib = ctx.lib or mix.Lib(ctx.design) places = iter(ctx.design.get('place') or []) rules = {str(r.get('name', i)): r for i, r in enumerate(ctx.design.get('rules') or [])} curve = bus_curve(ctx.design, 'sfx', ctx.N) out, bad = [], 0 for a, p in zip(recs, pl): if p['kind'] == 'place': pp = next(places) pitch, off, align, cue, rule = pp.get('pitch', 0.0), pp.get('offset', 0.0), pp.get('align', 'attack'), pp['at'], 'place' ok = pp.get('qa_ok') else: r = rules.get(str(p.get('rule')), {}) pitch, off, align, rule = p.get('pitch', 0.0), r.get('offset', 0.0), p.get('align', 'attack'), str(p.get('rule')) cue, ok = p['t'] - off, r.get('qa_ok') x = ctx.lib.get(a['sample'], pitch) if len(x) != a['n']: bad += 1 continue if a['bus'] != 'sfx': continue s0, s1 = max(0, a['start']), min(ctx.N, a['start'] + a['n']) if s1 <= s0: continue seg = x[s0 - a['start']: s1 - a['start']].astype(np.float64) * a['gain'] if a['pan']: seg = seg * np.array(mix.pan_gains(a['pan'])) seg = seg * curve[s0:s1, None] out.append({'sample': a['sample'], 'rule': rule, 'kind': p['kind'], 'event': p.get('event'), 'cue': cue, 'offset': off, 'align': align, 'start': a['start'], 'n': a['n'], 'a': s0, 'b': s1, 'sig': seg, 'qa_ok': ok, 'att': a['start'] + mix.env_index(x, 'attack'), 'peak_db': db(np.abs(seg).max())}) ctx.layers = out groups, by_cue = [], {} for L in sorted(out, key=lambda L: L['att']): if L['kind'] != 'place': # layers of one cue event share its exact cue time k = (L['event'], round(L['cue'], 4)) if k in by_cue: by_cue[k]['layers'].append(L) else: by_cue[k] = {'att0': L['att'], 'layers': [L]} groups.append(by_cue[k]) continue for g in groups[::-1][:12]: # free placements: layers whose attacks sit within 140 ms if g.get('place') and abs(L['att'] - g['att0']) < 0.14 * SR: g['layers'].append(L) break else: groups.append({'place': True, 'att0': L['att'], 'layers': [L]}) for g in groups: ls = g['layers'] g['a'], g['b'] = min(L['a'] for L in ls), max(L['b'] for L in ls) g['sig'] = np.zeros((g['b'] - g['a'], 2)) for L in ls: g['sig'][L['a'] - g['a']: L['b'] - g['a']] += L['sig'] g['cue'] = min(L['cue'] for L in ls) g['loud'] = max(ls, key=lambda L: L['peak_db']) g['kind'] = g['loud']['kind'] g['label'] = (ls[0]['event'] or 'place:' + ls[0]['sample']) g['long'] = any(L['kind'] in LONG or L['align'] == 'peak' for L in ls) g['builds'] = any(L['kind'] in ('riser', 'swell') for L in ls) g['qa_ok'] = next((L['qa_ok'] for L in ls if L['qa_ok']), None) g['peak_db'] = db(np.abs(g['sig']).max()) + ctx.G g['silent'] = g['peak_db'] < SILENT_DB note = f'{bad} placement(s) could not be rebuilt (sample length differs from the trace)' if bad else None return groups, note # ------------------------------------------------------------------ clicks HP14 = signal.butter(4, 14000, 'high', fs=SR, output='sos') def detect_clicks(x): """> 14 kHz samples > 9x the RMS of their 20 ms and > 6x their 4 ms neighbourhood; conc >= 0.8 of the burst's > 14 kHz energy inside 1 ms = a click (a cut), else a designed attack""" out = [] for ch in range(x.shape[1]): hp = signal.sosfilt(HP14, x[:, ch].astype(np.float64)) e, e2 = np.abs(hp), hp ** 2 loc = np.sqrt(signal.fftconvolve(e2, np.ones(960) / 960, mode='same').clip(0)) + 1e-5 near = np.sqrt(signal.fftconvolve(e2, np.ones(192) / 192, mode='same').clip(0)) + 1e-5 last = -10 ** 9 for i in np.nonzero((e / loc > 9) & (e / near > 6) & (e > 0.01))[0]: if i - last > SR * 0.01: conc = float(e2[max(0, i - 24):i + 24].sum() / (e2[max(0, i - 240):i + 240].sum() + 1e-15)) out.append({'t': round(i / SR, 4), 'i': int(i), 'ch': ch, 'level_db': round(db(e[i]), 1), 'conc': round(conc, 2), 'kind': 'click' if conc >= 0.8 else 'attack'}) last = i out.sort(key=lambda c: (c['t'], c['ch'])) return [c for k, c in enumerate(out) if k == 0 or c['t'] - out[k - 1]['t'] > 0.001] def owners(trace, i, bus=None, win=960): """trace records around sample i, edge-near (within 2 ms of a start / end) first""" res = [] for a in trace or []: if bus and a['bus'] != bus: continue s, e = a['start'], a['start'] + a['n'] if s - win <= i <= e + win: d = min(abs(i - s), abs(i - e)) where = 'start' if abs(i - s) <= 96 else 'end' if abs(i - e) <= 96 else 'body' what = a.get('sample') or a.get('name') or a.get('label') or f"{a.get('kind', a['bus'])} at {s / SR:.3f} s" res.append((where == 'body', d, {'bus': a['bus'], 'what': what, 'rule': a.get('rule', a.get('kind')), 'where': where, 'from_start_ms': round((i - s) / SR * 1000, 1), 'from_end_ms': round((i - e) / SR * 1000, 1)})) return [r for _, _, r in sorted(res, key=lambda r: (r[0], r[1]))[:3]] def hf_owner(ctx, i, ch): """the rebuilt sfx layer carrying the > 14 kHz burst at sample i (its level in the stem, where in the layer)""" best = None for L in getattr(ctx, 'layers', None) or []: if not L['a'] - 480 <= i < L['b'] + 480: continue j = i - L['a'] lo, hi = max(0, j - 480), min(len(L['sig']), j + 480) if hi - lo < 64: continue hp = signal.sosfilt(HP14, L['sig'][lo:hi, ch]) c = j - lo v = float(np.abs(hp[max(0, c - 24):c + 24]).max()) if 0 <= c < len(hp) else 0.0 if best is None or v > best[0]: off = i - L['start'] where = 'start' if abs(off) <= 96 else 'end' if abs(i - L['start'] - L['n']) <= 96 else 'body' best = (v, {'bus': 'sfx', - skills/real-sound/scripts/variant.py (16103 bytes)
#!/usr/bin/env python """Apply design operations: build a variant to test (critics) or apply the agreed fix (the fixer). python -I <skill>/scripts/variant.py --ops ops.json --out out/audio-review/critic_tonal/v1 [--render] [--qa] [--cues out/cues.json] [--cache DIR] python -I <skill>/scripts/variant.py --ops ops.json --apply [--backup out/audio-review/backup_round1] [--root .] [--design audio/sounddesign.json] A variant is a copy of the top-level design and its fragments in --out (design/<fragment>.json, include paths rewritten), with the operations applied; --render mixes it with every output inside --out (soundtrack.wav, stems/, report.json, cues.json, adds.json) and --qa runs qa.py on it (qa.json). --apply edits the real files instead, after copying them to --backup (never overwritten). Operations (a JSON list, applied in order; "f" = fragment file name without .json, "sd" = a dotted path in the top-level design): {"f": "keyboard", "sample": "kb.thock.1", "set": {"norm_peak_db": -10}} also "slice": name {"f": "keyboard", "sample": "kb.thock.1", "eq": {"highshelf": [5000, -6]}} merge into its eq {"f": "motion", "rule": "mo.leap.air", "set": {"offset": 0.3}} {"..., "rule": name, "delete": true} {"f": "motion", "rule_add": {...}} {"f": "garden", "place": "gd.crowd_a", "set": {...}} {"f": ..., "place_add": {...}} {"f": "ambience", "amb": "am.room", "set": {"gain_db": -3}} {"f": "music", "segment": 2, "set": {...}} {"f": "toy", "pool": "ty.p.row", "value": ["ty.row.a", "ty.row.b"]} {"sd": "buses.music.auto", "value": [[0, 0], [12, -3]]} {"sd": "master.lufs", "value": -15} Prints every change as old -> new (or unchanged); an operation that matches nothing is an error (nothing is written). Only files whose content changes are written, and only the changed values are rewritten in place (hand alignment, key order, comments and number spelling elsewhere stay as they were), so the fix reads as a small diff; the files written are listed. """ import argparse, copy, difflib, json, os, re, shutil, subprocess, sys HERE = os.path.dirname(os.path.abspath(__file__)) WS = re.compile(r'[ \t\r\n]*') DEC = json.JSONDecoder() # ------------------------------------------------------------------ format-preserving JSON edits def scan(t, i, path, sp, kids): """parse the JSON value at t[i:], recording sp[path] = (item_start, value_start, value_end) for every value and kids[path] = child keys / indices in order; returns the end index""" i = WS.match(t, i).end() item = sp.get(path, (i,))[0] if t[i] in '{[': close, kids[path] = '}' if t[i] == '{' else ']', [] j = WS.match(t, i + 1).end() n = 0 while t[j] != close: if close == '}': key, k = json.decoder.scanstring(t, j + 1) k = WS.match(t, k).end() + 1 # past the colon sub = path + (key,) else: k, sub = j, path + (n,) sp[sub] = (j,) kids[path].append(sub[-1]) j = WS.match(t, scan(t, k, sub, sp, kids)).end() if t[j] == ',': j = WS.match(t, j + 1).end() n += 1 sp[path] = (item, i, j + 1) return j + 1 _, j = DEC.raw_decode(t, i) sp[path] = (item, i, j) return j def dump1(v): return json.dumps(v, ensure_ascii=False) def edits_for(t, old, new, path, sp, kids, out): """text edits (start, end, replacement) that turn the value at path from old into new, touching only what changed""" if old == new and type(old) is type(new): return if isinstance(old, dict) and isinstance(new, dict) and path in kids: ks = kids[path] m = 0 while m < len(ks): if ks[m] in new: edits_for(t, old[ks[m]], new[ks[m]], path + (ks[m],), sp, kids, out) m += 1 continue m1 = m # a run of deleted entries m..m1, removed with one separator while m1 + 1 < len(ks) and ks[m1 + 1] not in new: m1 += 1 at = lambda n, w: sp[path + (ks[n],)][w] out.append((at(m, 0), at(m1 + 1, 0), '') if m1 + 1 < len(ks) else (at(m - 1, 2), at(m1, 2), '') if m else (at(m, 0), at(m1, 2), '')) m = m1 + 1 add = [k for k in new if k not in old] if add: insert(t, path, sp, kids, [f'{dump1(k)}: {dump1(new[k])}' for k in add], out) return if isinstance(old, list) and isinstance(new, list) and path in kids: sm = difflib.SequenceMatcher(None, list(map(ident, old)), list(map(ident, new)), autojunk=False) for op, a0, a1, b0, b1 in sm.get_opcodes(): if op == 'equal' or (op == 'replace' and a1 - a0 == b1 - b0): # the same items (or one for one): patch inside for d in range(a1 - a0): edits_for(t, old[a0 + d], new[b0 + d], path + (a0 + d,), sp, kids, out) elif op == 'insert': insert(t, path, sp, kids, [dump1(x) for x in new[b0:b1]], out, after=a0 - 1) else: # delete / uneven replace: the old items' whole stretch (with one separator) -> the new items s0 = sp[path + (a0,)][0] e0 = sp[path + (a1 - 1,)][2] txt = sep(t, path, sp, kids).join(dump1(x) for x in new[b0:b1]) if not txt: if a1 < len(old): e0 = sp[path + (a1,)][0] elif a0: s0 = sp[path + (a0 - 1,)][2] out.append((s0, e0, txt)) return _, s0, e0 = sp[path] out.append((s0, e0, dump1(new))) def ident(x): """what makes a list item the same item after an edit: a dict's name / sample / label, else its whole value""" k = [(key, dump1(x[key])) for key in ('name', 'sample', 'label') if isinstance(x, dict) and key in x] return json.dumps(k) if k else dump1(x) def sep(t, path, sp, kids): """the separator used between the container's items (',' + its line break and indent), from its last item""" ks = kids[path] if len(ks) < 2: return ', ' a, b = sp[path + (ks[-2],)][2], sp[path + (ks[-1],)][0] return t[a:b] if t[a:b].strip() == ',' else ', ' def insert(t, path, sp, kids, items, out, after=None): ks = kids[path] if not ks: _, s0, e0 = sp[path] out.append((s0 + 1, s0 + 1, ', '.join(items))) return s = sep(t, path, sp, kids) if after is None: after = len(ks) - 1 if after < 0: out.append((sp[path + (ks[0],)][0],) * 2 + (s.join(items) + s,)) else: e = sp[path + (ks[after],)][2] out.append((e, e, s + s.join(items))) def patch_text(text, new): """text of a JSON file with only the values that differ from `new` rewritten; None when that is not possible""" try: old = json.loads(text) sp, kids, out = {}, {}, [] scan(text, 0, (), sp, kids) edits_for(text, old, new, (), sp, kids, out) out.sort() if any(out[n][1] > out[n + 1][0] for n in range(len(out) - 1)): return None for s0, e0, rep in reversed(out): text = text[:s0] + rep + text[e0:] return text if json.loads(text) == new else None except (ValueError, KeyError, IndexError): return None def write_json(path, new, base_text=None): """write `new` to path keeping base_text's formatting where possible; returns 'patched' or 'reformatted'""" txt = patch_text(base_text, new) if base_text is not None else None how = 'patched' if txt is not None else 'reformatted' if txt is None: txt = json.dumps(new, indent=1, ensure_ascii=False) + '\n' with open(path, 'w', encoding='utf-8', newline='') as fh: fh.write(txt) return how def find(items, key, name): for i, it in enumerate(items): if str(it.get(key)) == str(name): return i raise KeyError(f'no item with {key} = {name!r}') def change(what, old, new): if old == new and type(old) is type(new): return f'{what}: unchanged ({json.dumps(old)[:80]})' return f'{what}: {json.dumps(old)[:80]} -> {json.dumps(new)[:80]}' def apply_ops(top, frags, ops): """apply operations to in-memory copies; returns a list of change lines""" log = [] for op in ops: if 'sd' in op: node, keys = top, op['sd'].split('.') for k in keys[:-1]: node = node.setdefault(k, {}) log.append(change(f"sounddesign.{op['sd']}", node.get(keys[-1]), op['value'])) node[keys[-1]] = op['value'] continue f = op['f'] if f not in frags: raise KeyError(f'no fragment "{f}" (have {", ".join(sorted(frags))})') d = frags[f] if 'sample' in op or 'slice' in op: kind = 'samples' if 'sample' in op else 'slices' name = op.get('sample') or op.get('slice') s = d.get(kind, {}).get(name) if s is None: raise KeyError(f'{f}: no {kind[:-1]} "{name}"') for k, v in (op.get('set') or {}).items(): log.append(change(f'{f}.{name}.{k}', s.get(k), v)) s[k] = v if 'eq' in op: old = copy.deepcopy(s.get('eq')) s.setdefault('eq', {}).update(op['eq']) log.append(change(f'{f}.{name}.eq', old, s['eq'])) elif 'rule' in op or 'place' in op or 'amb' in op: kind, key, name = (('rules', 'name', op['rule']) if 'rule' in op else ('place', 'sample', op['place']) if 'place' in op else ('ambience', 'name', op['amb'])) items = d.get(kind, []) i = find(items, key, name) if op.get('delete'): log.append(f'{f}.{kind}[{name}]: deleted') items.pop(i) continue for k, v in (op.get('set') or {}).items(): log.append(change(f'{f}.{kind}[{name}].{k}', items[i].get(k), v)) items[i][k] = v elif 'rule_add' in op or 'place_add' in op: kind = 'rules' if 'rule_add' in op else 'place' d.setdefault(kind, []).append(op.get('rule_add') or op.get('place_add')) log.append(f'{f}.{kind}: added {json.dumps(d[kind][-1])[:100]}') elif 'segment' in op: sg = d['music']['segments'][int(op['segment'])] for k, v in (op.get('set') or {}).items(): log.append(change(f"{f}.music.segments[{op['segment']}].{k}", sg.get(k), v)) sg[k] = v elif 'pool' in op: log.append(change(f"{f}.pools.{op['pool']}", d.get('pools', {}).get(op['pool']), op['value'])) d.setdefault('pools', {})[op['pool']] = op['value'] else: raise ValueError(f'unknown operation {op}') return log def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument('--root', default='.') ap.add_argument('--design', default='audio/sounddesign.json') ap.add_argument('--ops', required=True, help='JSON list of operations (or [] for an unchanged copy)') ap.add_argument('--out', help='variant folder (critics)') ap.add_argument('--apply', action='store_true', help='edit the real design files (the fixer)') ap.add_argument('--backup', default='out/audio-review/backup_before_fix', help='with --apply: copy the originals here first') ap.add_argument('--render', action='store_true', help='mix the variant (outputs inside --out)') ap.add_argument('--qa', action='store_true', help='also run qa.py on the rendered variant') ap.add_argument('--cache', help='decode cache for --render / --qa (default: <root>/out/audio/cache, as mix.py)') ap.add_argument('--cues', help='cue file for the variant (written into its design; default: the design\'s "cues", ' 'else out/cues.json)') a = ap.parse_args(argv) root = os.path.abspath(a.root) R = lambda p: os.path.normpath(p if os.path.isabs(p) else os.path.join(root, p)) if bool(a.out) == bool(a.apply): sys.exit('give exactly one of --out (a variant) or --apply (edit the design)') if not os.path.exists(R(a.design)): sys.exit(f'design file not found: {R(a.design)} (pass --design)') text = {p: open(R(p), encoding='utf-8', newline='').read() for p in [a.design] + json.load( open(R(a.design), encoding='utf-8')).get('include', [])} top = json.loads(text[a.design]) paths = {os.path.splitext(os.path.basename(p))[0]: p for p in top.get('include', [])} frags = {k: json.loads(text[p]) for k, p in paths.items()} ops = json.load(open(R(a.ops), encoding='utf-8')) if os.path.exists(R(a.ops)) else json.loads(a.ops) new_top, new_frags = copy.deepcopy(top), copy.deepcopy(frags) try: log = apply_ops(new_top, new_frags, ops) except (KeyError, ValueError, IndexError) as e: sys.exit(f'nothing written: {e}') if a.apply: bk = R(a.backup) if os.path.exists(bk): sys.exit(f'backup {bk} exists: pass a new --backup') os.makedirs(os.path.join(bk, 'design')) shutil.copy(R(a.design), os.path.join(bk, os.path.basename(a.design))) for k, p in paths.items(): shutil.copy(R(p), os.path.join(bk, 'design', os.path.basename(p))) todo = [(a.design, new_top, top)] + [(p, new_frags[k], frags[k]) for k, p in paths.items()] written = [(p, write_json(R(p), new, text[p])) for p, new, old in todo if new != old] dest = f'the design (originals in {bk})' else: out = R(a.out) os.makedirs(os.path.join(out, 'design'), exist_ok=True) new_top['include'] = [os.path.join(out, 'design', os.path.basename(p)).replace('\\', '/') for p in top['include']] if a.cues or top.get('cues'): new_top['cues'] = R(a.cues or top['cues']).replace('\\', '/') dpath = os.path.join(out, 'sounddesign.json').replace('\\', '/') written = [(os.path.join(out, 'design', os.path.basename(p)), write_json( os.path.join(out, 'design', os.path.basename(p)), new_frags[k], text[p])) for k, p in paths.items()] written.append((dpath, write_json(dpath, new_top, text[a.design]))) dest = dpath n = sum(1 for line in log if ': unchanged (' not in line) print(f'{n} change(s), {len(log) - n} already as asked -> {dest}' if n < len(log) else f'{n} change(s) -> {dest}') for line in log: print(' ' + line.encode('ascii', 'replace').decode()) for p, how in written: print(f' wrote {p} ({how}' + (', only the changed values rewritten)' if how == 'patched' else ': could not pa - skills/real-sound/SKILL.md (15521 bytes)
--- name: real-sound description: Build premium, realistic soundtracks for code-made videos and animations from real licensed recordings - launch films, product and feature videos, UI walkthroughs, logo stings, explainers, trailers and animated shorts made with Remotion, HyperFrames, three.js, GSAP or any renderer. Use this whenever a video or animation needs sound design, SFX, foley, ambience, music, a soundtrack, a score, UI click / whoosh / riser / impact / logo-sting sounds, or a music edit to picture; whenever a synthesized or "random" sounding soundtrack must be replaced with real recordings; or when the user asks to source, license, credit, mix, master, critique or mux audio for a film. It covers cue lists from the picture, sourcing from Freesound / Mixkit / composer libraries with licence checks, a music edit at bar lines, a JSON sound design rendered by a deterministic mixer, measured QA (clicks, masking, harshness, sync, loudness) plus earshot listening, a multi-agent critique, mastering, credits and the mux. --- # real-sound You are the sound supervisor of a film you cannot hear. The soundtrack is built ONLY from real, professionally recorded or produced audio (one licensed music track, real foley and SFX, real ambiences), placed on the picture's cue frames by a deterministic mixer, measured instead of listened to, critiqued through five lenses, fixed by one agent, mastered, credited and muxed. Code selects, trims, places, levels, pans, EQs, pitches by resampling, time-stretches the music and masters; code never generates a sound. The bar is a professional launch film: every sound caused by something on screen, one material palette, the music's drop on the hero reveal, restraint everywhere else, a resolved logo, a tail into silence. Rules: `references/sound-design.md` (and the earshot repo's `docs/launch-video-sound.md` for the bundled reference profile: 7 professional launch films). `<skill>` below is this folder. **Python:** `{{PY}}` below (and in every prompt template) is ONE interpreter that has numpy, scipy, soundfile and the earshot package: the earshot repo's venv (`<earshot repo>/.venv/Scripts/python.exe` on Windows, `<earshot repo>/.venv/bin/python` elsewhere), or any Python where `<python> -c "import earshot"` works. Bare `python` on Windows is often the Microsoft Store stub and fails. Substitute the full path for `{{PY}}` when you run a command or hand a prompt to a sub-agent (the other placeholders are listed in `references/process.md`). Run the scripts with `-I` (isolated: downloaded files can never shadow a module); every script except `scripts/licences.py` (the licence policy module that audit.py and credits.py import) prints `--help`. ## The process | step | who | output | gate | |---|---|---|---| | 0. cue list | lead | `out/cues.json` | sync frames computed from the picture code | | 1. brief | lead | `audio/SOUND_BRIEF.md` | every cue has a sound need (or "nothing") | | 2. sourcing (per category, parallel) | sourcing agents | `audio/assets/<cat>/`, manifests | each file measured + earshot `realness` "real or pro-produced" on the trim used (an "uncertain" only with its evidence and a trim-level re-check written in the manifest) | | 3. licence audit | auditor | `audit.json` | `audit.py` exit 0 for what the film uses | | 4. music edit | music supervisor | `audio/design/music.json` | grid verified, drop on the reveal, splices clean | | 5. design fragments (per category, parallel) | designers | `audio/design/<cat>.json` | solo render + qa clean | | 6. integrate | lead | soundtrack, stems, report, trace | master gate (+-0.5 LU, <= -1.5 dBTP) | | 7. QA + listening | lead | `out/qa/qa.json`, earshot timeline / sheet / critique | no qa fail | | 8. critique (5 lenses, parallel, read-only) | critics | ranked issues + tested operations | | | 9. fix | ONE fixer | the design | qa: no regression | | 10. master, credits, mux | lead | `CREDITS.md`, description text, the film | credits exit 0, lag 0 | The detail of every step, the roles and what each critic measures: `references/process.md`. Every sub-agent prompt is a ready-to-fill brief in `templates/prompts/`. ### 0. Cue list from the picture Every sound sits on a frame the picture code computes: a contact frame, a pop-in's 50 % frame, a move's velocity peak, a riser's hit, the frame the wordmark becomes readable. Cinetic films already have `out/cues.json` (`export-cues.ts`); for anything else write the same format (`templates/cues.json`) from the timeline constants. Stable ids (`act:thing:n`) let rules match classes of action with a regex. ### 1. Brief Copy `templates/SOUND_BRIEF.md` to `audio/SOUND_BRIEF.md`: concept (palette, the music's arc, places), the picture map (every cue: what is on screen, the sound need), ambience zones, allowed licences, quality bar, file layout. It is the contract every sub-agent gets verbatim. Pick the brand's personality row (`references/sound-design.md` §3). ### 2. Sourcing, per category (`templates/prompts/sourcing.md`) Typical launch-film categories: `ui` (clicks, taps, toggles, pops), `keyboard`, `motion` (whooshes, risers), `impacts` (reveal hits, the logo), `ambience`, `music`; a character film adds `foley`, its worlds, its objects. Freesound (CC0 / CC BY; HQ preview `cdn.freesound.org/previews/<id//1000>/<id>_<user>-hq.ogg`), Mixkit (WAV `assets.mixkit.co/active_storage/sfx/<id>/<id>.wav`), composer libraries for music; licences read on each item's own page (`references/licences.md`); polite sequential downloads; every file measured: ``` {{PY}} -I <skill>/scripts/analyze.py audio/assets/ui/* --png out/audio-review/ui --out out/audio-review/ui.json {{PY}} -m earshot realness audio/assets/ui/ # gate: "real or pro-produced" (re-check trims: --start --end) {{PY}} -m earshot rank "a single crisp trackpad click" audio/assets/ui/ --top 5 {{PY}} -m earshot match <file> "a soft cork pop" --alts "a gunshot" "a balloon burst" {{PY}} -m earshot find <long take> "a single mechanical key press" --top 8 # trims; skip any marked head cut / tail cut ``` ### 3. Licence audit (`templates/prompts/licence_audit.md`) The auditor records what each page says (`licence_seen`, `licence_confirmed`) in `audio/assets/manifests/audit.json`; the script checks the rest (classification, ids vs URLs, files decode, durations, credit lines): ``` {{PY}} -I <skill>/scripts/audit.py --root . --report out/qa/mix_report.json [--fetch] ``` Allowed: CC0, public domain, CC BY 2.0-4.0, Mixkit free licences, Pixabay. Forbidden: NC, ND, SA, Sampling+, personal, custom, disputed. Unverified = blocked. ### 4. Music (`templates/prompts/music_supervisor.md`) One licensed track whose structure fits the film. Write the arc per film bar (`templates/arc.json`), then: ``` {{PY}} -I <skill>/scripts/arrange.py audio/assets/music/<track> --film-bpm 120 --arc audio/arc.json --out out/audio-review/music/arrange.json ``` It fits the tempo, moves the grid onto the measured attacks (beat trackers lag 20-50 ms), proposes the downbeat phase, anchors the drop film bar on the strongest drop candidate and drafts segments at bar lines (a ready-to-paste `music` block). The downbeat is the weak spot: when it prints LOW confidence (on one of the two tracks it was tested on it was half a bar off), decide between the two printed grids from the first note, the section entrances and the chord changes in the bar table, and re-run with `--phase N`. Then edit by judgement: harmony continues across each splice, the drop's downbeat on the hero frame, the final chord on the logo, `tail_fade` into the end. ### 5. Design fragments, per category (`templates/prompts/designer.md`) `audio/design/<category>.json` with samples (trims), slices (cut a take of many hits into single hits), pools, rules on cue events, free placements, ambience beds, the music block. Reference with every key and real examples: `references/design-format.md`; a complete launch-video example: `templates/design_fragment.json` (its file names are placeholders such as `mk-0000_mouse-click.wav`: it renders once each one is replaced by a real recording from your manifests; mix.py stops and lists the missing files until then). Verify alone: ``` {{PY}} -I <skill>/scripts/mix.py --only ui --dump out/audio-review/ui/dump # every trim as WAV + numbers {{PY}} -I <skill>/scripts/mix.py --only ui --trace out/audio-review/ui/adds.json --out out/audio-review/ui/solo.wav {{PY}} -I <skill>/scripts/qa.py --only ui --report out/audio-review/ui/solo_report.json --stems out/audio-review/ui/solo_stems --trace out/audio-review/ui/adds.json --out out/audio-review/ui/qa.json {{PY}} -m earshot timeline out/audio-review/ui/solo.wav --cues out/cues.json ``` ### 6-7. Integrate, QA, listen ``` {{PY}} -I <skill>/scripts/mix.py --root . --design audio/sounddesign.json --cues out/cues.json --trace out/qa/adds.json {{PY}} -I <skill>/scripts/qa.py --layers # clicks, edges, audibility, harshness, loudness, coverage, sync, density {{PY}} -I <skill>/scripts/qa.py --listen --realness --video out/film.mp4 # + earshot timeline, sheet, critique, realness {{PY}} -m earshot critique out/audio/soundtrack.wav --video out/film.mp4 # scorecard vs professional launch films {{PY}} -m earshot sheet out/audio/soundtrack.wav -o out/qa/sheet.png --video out/film.mp4 --cues out/qa/cues_sounded.json ``` `qa.py` ties every finding to the rule and sample that caused it (the trace). It is usable without the models; `--listen` adds earshot's transcript (`out/qa/qa_timeline.txt`), annotated sheet and scorecard. ### 8-9. Critique and fix Five read-only critics in parallel, each with its prompt: `critic_sync.md`, `critic_edges.md`, `critic_masking.md`, `critic_tonal.md`, `critic_director.md`. Each tests its fixes as a variant in its own folder: ``` {{PY}} -I <skill>/scripts/variant.py --ops out/audio-review/critic_tonal/ops_v1.json --out out/audio-review/critic_tonal/v1 --render --qa ``` and returns ranked issues with exact operations and before -> after numbers. Then ONE fixer (`fixer.md`) merges the operations, resolves conflicts, checks the merged variant against the previous qa.json, and applies it (`variant.py --apply`, originals backed up). Acknowledge confirmed deliberate exceptions with `"qa_ok": "<reason>"`. At least one round; a second when levels or the music edit changed. ### 10. Master, credits, mux `mix.py` masters with `master.py` (-14 LUFS, true-peak limiter, ceiling 0.77 linear; gate +-0.5 LU and <= -1.5 dBTP). ``` {{PY}} -I <skill>/scripts/audit.py --root . --report out/qa/mix_report.json # exit 0 {{PY}} -I <skill>/scripts/credits.py --root . --design audio/sounddesign.json --audit audio/assets/manifests/audit.json node <skill>/scripts/mux.mjs --video out/film.mp4 --audio out/audio/soundtrack.wav --out out/film_sound.mp4 {{PY}} -m earshot timeline out/film_sound.mp4 --cues out/qa/cues_sounded.json # the finished file, heard ``` `CREDITS.md` + `out/CREDITS_description.txt` (paste into the video description: CC BY credits are required there). `mux.mjs` stream-copies the picture and cuts the AAC audio to the picture's duration. ## Launch videos: the sound map | picture | sound | sits on | |---|---|---| | cursor moves, hovers, scrolls, progress, streaming text | nothing (the music carries it) | | | click / tap | ONE real click voice for the film, press + release ~85 ms later, same level every time | the press frame | | typing | one real keyboard, sliced; <= ~12 keys/s, one per word above ~25 chars/s; music dips 6-10 dB | each sounded character | | a card / chip / badge appears | a soft real pop or tick, climbing across a run | 50 % of its travel | | toggle, lock-in, a counter's final value | a real latch / click / crisp tick | the contact / lock frame | | camera-scale move, whip, zoom (~2 per film) | a real swish, apex on the velocity peak | velocity peak | | hard cuts | nothing | | | tension into the reveal | the music's build, or a real riser ending 30-250 ms before the hit | the hit | | hero reveal | the music's DROP (edit the track so its downbeat lands here) + optionally one real impact | the frame | | logo / lockup | music stops on a bar line or filters down, 0.2-0.7 s near-silence, ONE soft note in key, tail to silence | the frame the wordmark reads | Levels: -14 LUFS, true peak <= -1 dBTP after AAC, LRA 5-9 LU, the loudest moment on the drop (30-60 % in), the logo 8-20 dB under it, about 5 designed effects per 10 s, effects dry and centred. Measured norms and the cheap tells: `references/sound-design.md`. ## Tools | need | tool | |---|---| | measure recordings (format, floor, bandwidth, onsets, spikes, tempo / key) + spectrogram PNGs | `scripts/analyze.py` | | hear recordings: real vs synthesized, what it sounds like, best match, best take inside a long file | `{{PY}} -m earshot realness / describe / match / rank / find / compare / ab` | | levels / brightness / onsets of one file or a stretch of it (`--start --end`) | `{{PY}} -m earshot measure` (Python: `from earshot import api; api.measure(...)`, likewise `api.find`, `api.realness` ...) | | licence + file audit | `scripts/audit.py` (policy in `scripts/licences.py`) | | music grid, downbeats, bar-line edit draft | `scripts/arrange.py` | | render the design (+ solo `--only`, `--dump` trims, `--trace` for QA) | `scripts/mix.py` | | master and loudness measurement | `scripts/master.py` (`--measure`) | | objective QA tied to placements | `scripts/qa.py` (`--layers`, `--listen`, `--realness`) | | critic variants, the fixer's apply | `scripts/variant.py` | | credits for CREDITS.md and the video description | `scripts/credits.py` | | put the soundtrack on the picture | `scripts/mux.mjs` | | listen to a whole mix / film; annotated picture; launch-film scorecard | `{{PY}} -m earshot timeline / sheet / critique` | ## Files ``` audio/SOUND_BRIEF.md the contract (templates/SOUND_BRIEF.md) audio/assets/<category>/ downloaded recordings (<source>-<id>_<slug>.<ext>; never commit or publish them) audio/assets/manifests/<cat>.json one entry per recording (templates/manifest_entry.json) audio/assets/manifests/audit.json licence audit (templates/audit_entry.json) audio/sounddesign.json top level: includes, buses, master (templates/sounddesign.json) audio/design/<category>.json one fragment per designer (templates/design_fragment.json) out/cues.json the picture's cue events (templates/cues.json) out/audio/soundtrack.wav, stems/ the master and its stems out/qa/ mix_report.json, adds.json, cues_sounded.json, master.json, qa.json out/audio-review/ per-category and per-critic work, variants, dumps (the audit trail) CREDITS.md, out/CREDITS_description.txt ``` ## References - `references/process.md`: roles, steps, what each critic measures, thresholds and the - skills/real-sound/templates/arc.json (736 bytes)
{ "_doc": "Input for arrange.py --arc: the target loudness of each FILM bar in dB relative to the track's loud bars (0 = its biggest sections, -6 = a groove, -10 = a breakdown, -14 = a soft intro). One number per film bar (bar = beats_per_bar beats at film_bpm). Write it from the picture map in SOUND_BRIEF.md: soft under the cold open and typing, the groove for the feature beats, a breakdown before the turn, the build, the big section from the drop (the hero reveal), a resolve under the logo. This example: a 30 s launch film at 120 BPM = 15 bars, drop on film bar 9 (16.0 s), logo from bar 13.", "film_bpm": 120, "beats_per_bar": 4, "drop_film_bar": 9, "arc": [-14, -12, -7, -6, -6, -6, -10, -6, 0, 0, 0, -2, -8, -11, -14] } - skills/real-sound/templates/audit_entry.json (1587 bytes)
{ "_doc": "One record of audio/assets/manifests/audit.json. The licence auditor (prompts/licence_audit.md) writes ONLY the three agent fields below after reading the licence on the item's own page; audit.py computes everything else on every run and keeps the agent fields (matched by id + file). Never set licence_confirmed without having read the page in this session.", "id": "fs-000000", "licence_seen": "Freesound page https://freesound.org/people/uploader_name/sounds/000000/: licence 'Attribution 4.0' -> https://creativecommons.org/licenses/by/4.0/ (read 2026-10-14); page author 'uploader_name', title 'Trackpad click close.wav'; preview id/user match download_url", "licence_confirmed": true, "agent_notes": ["the author asks for credit as \"<title> by uploader_name (freesound.org)\": the manifest attribution follows it"], "_computed_by_audit_py": { "manifest": "audio/assets/manifests/ui.json", "need": "ui_click", "rank": 1, "in_scope": true, "severity": "ok", "licence_in_manifest": "CC BY 4.0", "licence": "by4", "licence_status": "allowed", "attribution_required": true, "attribution_ok": true, "attribution_in_manifest": "\"Trackpad click close.wav\" by uploader_name (...), licensed under CC BY 4.0 (...)", "file_ok": true, "file_check": {"path": "audio/assets/ui/fs-000000_trackpad-click.ogg", "exists": true, "codec": "vorbis", "sample_rate": 48000, "channels": 1, "kbps": 192, "duration_s": 0.84, "decodes_clean": true, "bytes_match_download_url": true}, "problems": [], "warnings": [], "audit_tool": "real-sound audit.py v1" } } - skills/real-sound/templates/cues.json (2784 bytes)
{ "_doc": "The picture's cue file: the contract between picture and sound (Cinetic's scripts/export-cues.ts writes this exact format from the picture code; write it from the timeline for any other engine). f = absolute frame the sound belongs on (fractional is fine); kind = what happens (tick, tock, key, click, pop, snap, land, hit, drop, whoosh, riser, swell, suck, bell, or your own word); id = a stable label rules match with a regex ('act:thing:n'); weight 0..2 (1 = normal), pan -1..1 (the object's screen x), variant (key: word/space/return/back; land: light; click: confirm), dur in frames for whoosh / riser / swell. Optional: acts {name: {from, dur}} and cue {name: frame} (qa.py reports loudness per act). mix.py also accepts a list whose first element is this object. Sync points belong where the eye reads them: an impact on its contact frame, a pop-in at 50 % of its travel, a whoosh on the move's velocity peak, a riser on the frame of the hit it leads into, a logo sound on the frame the wordmark becomes readable.", "fps": 60, "bpm": 120, "total": 720, "acts": {"ui": {"from": 0, "dur": 240}, "cards": {"from": 240, "dur": 240}, "reveal": {"from": 480, "dur": 240}}, "cue": {"click": 60, "typeStart": 120, "transition": 240, "reveal": 480, "lockup": 600}, "events": [ {"f": 60, "kind": "click", "weight": 1, "pan": 0.2, "id": "demo:cursor:click"}, {"f": 120, "kind": "key", "weight": 0.6, "id": "demo:type:key:0", "variant": "word"}, {"f": 125, "kind": "key", "weight": 0.5, "id": "demo:type:key:1"}, {"f": 130, "kind": "key", "weight": 0.5, "id": "demo:type:key:2"}, {"f": 135, "kind": "key", "weight": 0.5, "id": "demo:type:key:3"}, {"f": 141, "kind": "key", "weight": 0.5, "id": "demo:type:space", "variant": "space"}, {"f": 146, "kind": "key", "weight": 0.6, "id": "demo:type:key:4", "variant": "word"}, {"f": 151, "kind": "key", "weight": 0.5, "id": "demo:type:key:5"}, {"f": 156, "kind": "key", "weight": 0.5, "id": "demo:type:key:6"}, {"f": 162, "kind": "key", "weight": 0.5, "id": "demo:type:key:7"}, {"f": 168, "kind": "key", "weight": 0.5, "id": "demo:type:key:8"}, {"f": 210, "kind": "click", "weight": 1, "pan": 0.35, "id": "demo:cursor:submit", "variant": "confirm"}, {"f": 240, "kind": "whoosh", "weight": 1, "pan": -0.6, "dur": 24, "apexFrac": 0.5, "id": "demo:transition"}, {"f": 330, "kind": "pop", "weight": 0.8, "pan": -0.4, "id": "demo:card:0"}, {"f": 345, "kind": "pop", "weight": 0.8, "pan": 0.0, "id": "demo:card:1"}, {"f": 360, "kind": "pop", "weight": 0.8, "pan": 0.4, "id": "demo:card:2"}, {"f": 480, "kind": "riser", "weight": 1, "dur": 120, "id": "demo:build"}, {"f": 480, "kind": "hit", "weight": 1.5, "id": "demo:reveal"}, {"f": 600, "kind": "bell", "weight": 0.7, "id": "demo:lockup"} ] } - skills/real-sound/templates/design_fragment.json (8087 bytes)
{ "_doc": "A complete design showing every feature mix.py understands, for a 12 s launch-video beat (cursor click, typing, whoosh into a transition, cards popping in, riser -> hero reveal hit, logo sting). It works as a single-file design (mix.py --design this.json) or as one category fragment listed in sounddesign.json 'include' (then 'duration', 'buses' and 'master' are read only from the top-level file). Keys starting with _ are comments. Every 'file' is a real licensed recording listed in a manifest (audio/assets/manifests/*.json). Prefix every name with the fragment's category so fragments never collide. Reference: references/design-format.md.", "duration": 12.0, "cues": "out/cues.json", "samples": { "ui.press": {"_doc": "the press half of a real mouse click: trim 3-5 ms before the attack, end before the release", "file": "audio/assets/ui/mk-0000_mouse-click.wav", "start": 0.096, "end": 0.150, "mono": true, "eq": {"hp": 400}, "norm_peak_db": -12, "fade_in": 0.002, "fade_out": 0.008}, "ui.release": {"file": "audio/assets/ui/mk-0000_mouse-click.wav", "start": 0.180, "end": 0.230, "mono": true, "eq": {"hp": 400}, "norm_peak_db": -15, "fade_in": 0.002, "fade_out": 0.008}, "kb.space": {"file": "audio/assets/keyboard/fs-000001_mech-spacebar.ogg", "start": 0.48, "end": 0.78, "mono": true, "eq": {"hp": 90, "highshelf": [5000, -3]}, "norm_peak_db": -10, "fade_out": 0.08}, "mo.whoosh": {"_doc": "a real swish (stick / cloth / bamboo past the mic); placed by its peak on the move's velocity peak", "file": "audio/assets/motion/fs-000002_stick-swish.ogg", "start": 0.0, "end": 0.55, "eq": {"hp": 150, "lp": 12000}, "norm_peak_db": -6, "fade_in": 0.01, "fade_out": 0.12}, "mo.whoosh.tail": {"file": "audio/assets/motion/fs-000002_stick-swish.ogg", "start": 0.05, "end": 0.55, "pitch": -3, "eq": {"hp": 120, "lp": 6000}, "norm_peak_db": -8, "fade_in": 0.02, "fade_out": 0.2}, "fx.pop": {"file": "audio/assets/ui/fs-000003_cork-pop.ogg", "start": 0.02, "end": 0.20, "mono": true, "eq": {"hp": 250, "peq": [[3200, 1.2, -2]]}, "norm_peak_db": -10, "fade_out": 0.04}, "fx.riser": {"_doc": "a real cymbal roll / orchestral swell; aligned by its END so it stops on the reveal", "file": "audio/assets/motion/fs-000004_cymbal-roll.ogg", "start": 0.3, "end": 2.3, "eq": {"hp": 200}, "norm_peak_db": -9, "fade_in": 0.6, "fade_out": 0.03, "env": [[0, -12], [1.5, -2], [2.0, 0]]}, "fx.hit": {"file": "audio/assets/impacts/mk-0005_deep-drum-impact.wav", "start": 0.0, "end": 1.6, "eq": {"hp": 30, "peq": [[300, 1.0, -3]]}, "norm_peak_db": -4, "fade_out": 0.4}, "fx.hit.top": {"file": "audio/assets/impacts/fs-000006_wood-slam.ogg", "start": 0.01, "end": 0.35, "mono": true, "eq": {"hp": 500}, "norm_peak_db": -10, "fade_out": 0.08}, "logo.chime": {"_doc": "the sting: one soft real bell / celesta note, in the music's key (resample with pitch to tune, within +-2 st)", "file": "audio/assets/magic/fs-000007_celesta-E5.ogg", "start": 0.0, "end": 2.4, "pitch": 0.0, "norm_peak_db": -9, "fade_out": 0.9}, "logo.air": {"file": "audio/assets/motion/fs-000002_stick-swish.ogg", "start": 0.0, "end": 0.5, "glide": [2, -1], "eq": {"hp": 300, "lp": 9000}, "norm_peak_db": -14, "fade_in": 0.05, "fade_out": 0.25} }, "slices": { "kb.type": {"_doc": "one recording of a mechanical keyboard typing, cut at its onsets into single keys: kb.type#0, kb.type#1 ... (check them with --dump)", "file": "audio/assets/keyboard/fs-000008_mech-typing.ogg", "start": 0.5, "end": 9.0, "pre": 0.004, "len": 0.14, "min_gap": 0.07, "gate_db": -15, "mono": true, "eq": {"hp": 110, "highshelf": [5000, -4]}, "norm_peak_db": -12, "fade_out": 0.03, "max": 16} }, "pools": { "ui.press": ["ui.press"], "ui.release": ["ui.release"], "kb.type": ["kb.type#*"], "kb.space": ["kb.space"], "mo.whoosh": ["mo.whoosh"], "mo.whoosh.tail": ["mo.whoosh.tail"], "fx.pop": ["fx.pop"], "fx.riser": ["fx.riser"], "fx.hit": ["fx.hit"], "fx.hit.top": ["fx.hit.top"], "logo.chime": ["logo.chime"] }, "rules": [ {"name": "ui.click press", "match": {"kind": "click"}, "pool": "ui.press", "mode": "fixed", "gain_db": 0, "pan": 0, "align": "attack", "_doc": "one voice at one level for every click in the film"}, {"name": "ui.click release", "match": {"kind": "click"}, "pool": "ui.release", "mode": "fixed", "gain_db": -2, "pan": 0, "align": "attack", "offset": 0.085}, {"name": "kb.type", "match": {"kind": "key", "id": "^demo:type:key"}, "pool": "kb.type", "mode": "cycle", "gain_db": -2, "jitter_db": 1.5, "pitch": [-0.3, 0.3], "pan": 0, "align": "attack"}, {"name": "kb.space", "match": {"kind": "key", "id": "^demo:type:space"}, "pool": "kb.space", "mode": "fixed", "gain_db": -1, "pan": 0, "align": "attack"}, {"name": "mo.whoosh", "match": {"kind": "whoosh"}, "pool": "mo.whoosh", "mode": "fixed", "align": "peak", "gain_db": -6, "pan": "cue", "pan_scale": 0.8}, {"name": "mo.whoosh tail", "match": {"kind": "whoosh"}, "pool": "mo.whoosh.tail", "mode": "fixed", "align": "peak", "offset": 0.06, "gain_db": -12, "pan": "cue", "pan_scale": 0.5}, {"name": "fx.pops", "match": {"kind": "pop", "from": 5.0, "to": 7.0}, "pool": "fx.pop", "mode": "cycle", "gain_db": -4, "jitter_db": 1.0, "pitch": [-0.2, 0.2], "pitch_ramp": [0, 2], "gain_ramp": [-1, 1], "pan": "cue", "pan_scale": 0.3, "align": "attack"}, {"name": "fx.riser", "match": {"kind": "riser"}, "pool": "fx.riser", "mode": "fixed", "align": "end", "offset": -0.03, "gain_db": -6, "pan": 0, "_doc": "ends 30 ms before the reveal: a beat of air before the hit"}, {"name": "fx.hit", "match": {"kind": "hit", "id": "^demo:reveal$"}, "pool": "fx.hit", "mode": "fixed", "gain_db": -2, "pan": 0, "align": "attack"}, {"name": "fx.hit top", "match": {"kind": "hit", "id": "^demo:reveal$"}, "pool": "fx.hit.top", "mode": "fixed", "gain_db": -8, "pan": 0, "align": "attack", "offset": 0.004}, {"name": "logo.chime", "match": {"kind": "bell", "id": "^demo:lockup$"}, "pool": "logo.chime", "mode": "fixed", "gain_db": -3, "pan": 0, "align": "attack", "_doc": "on the frame the wordmark becomes readable (its settle), never later"} ], "place": [ {"sample": "logo.air", "at": 9.98, "align": "peak", "gain_db": -6, "pan": 0.0, "_doc": "a free placement (no cue event): a soft air lift that peaks just before the chime"} ], "ambience": [ {"name": "am.room", "_doc": "a quiet real room tone under the UI part; src_start..src_end is a clean window (no events), looped with a 1.5 s crossfade if needed", "file": "audio/assets/ambience/fs-000009_quiet-office-roomtone.ogg", "src_start": 5.0, "src_end": 45.0, "at": 0.0, "until": 8.2, "fade_in": 0.3, "fade_out": 0.4, "gain_db": -6, "width": 0.8, "eq": {"hp": 80, "lp": 12000}, "auto": [[0, 0], [7.5, 0], [8.0, -8]]} ], "music": { "_doc": "one licensed track, edited at bar lines (arrange.py drafts the segments). src_* are ORIGINAL source seconds; 'at' is film time. 'at' can be nudged a few ms so the measured downbeat transient lands on the picture's downbeat.", "file": "audio/assets/music/sb-0000_bright-launch-track.mp3", "src_bpm": 120, "target_bpm": 120, "stretch": "none", "gain_db": -4, "eq": {"hp": 30}, "segments": [ {"label": "intro bars 1-4 (soft, no drums) under the UI", "src_from": 0.5, "src_to": 8.5, "at": 0.0, "fade_in": 0.15, "fade_out": 0.03}, {"label": "drop bars 17-18 on the hero reveal, ring out under the logo", "src_from": 32.5, "src_to": 36.5, "at": 8.0, "fade_in": 0.008, "fade_out": 0.06, "tail_fade": 1.2} ] }, "_buses_doc": "buses and master are read from the top-level design only. auto = [[film t, dB], ...] piecewise-linear fader rides: here the music dips 6 dB under the typing and comes back for the whoosh", "buses": { "music": {"gain_db": 0.0, "auto": [[0, 0], [1.9, 0], [2.0, -6], [3.6, -6], [3.8, 0], [12, 0]]}, "amb": {"gain_db": 0.0}, "sfx": {"gain_db": 0.0, "eq": {"hp": 40}} }, "master": {"_doc": "read from the top-level design only. -14 LUFS for web/social; ceiling 0.77 linear (-2.3 dBFS): measure about -1 dBTP after AAC", "lufs": -14, "ceiling": 0.77, "no_glue": true} } - skills/real-sound/templates/manifest_entry.json (2727 bytes)
[ { "_doc": "One object per downloaded recording, in audio/assets/manifests/<category>.json (a JSON list). Values here are placeholders: copy the shape, never the data. Every field is read from the item's own page; never guess a licence. 'attribution' is required for CC BY (paste the form the author asks for on their page, else: \"<title>\" by <author> (<page_url>), licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/)); null for CC0 / Mixkit / Pixabay. 'analysis' is what analyze.py measured; 'best_segment' the clean part in seconds.", "id": "fs-000000", "category": "ui", "file": "audio/assets/ui/fs-000000_trackpad-click.ogg", "title": "Trackpad click close.wav", "author": "uploader_name", "source": "freesound", "page_url": "https://freesound.org/people/uploader_name/sounds/000000/", "download_url": "https://cdn.freesound.org/previews/0/000000_0000000-hq.ogg", "license": "CC BY 4.0", "license_url": "https://creativecommons.org/licenses/by/4.0/", "attribution": "\"Trackpad click close.wav\" by uploader_name (https://freesound.org/people/uploader_name/sounds/000000/), licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/)", "need": "ui_click", "rank": 1, "best_segment": [0.10, 0.32], "notes": "What it is and how it was recorded (from the page), what you measured, what to use and avoid: e.g. 'close-miked laptop trackpad, press at 0.12 + release at 0.21 (85 ms later, 3 dB quieter), floor -78 dBFS, no room; use as the film's one click voice'.", "analysis": {"duration": 0.84, "codec": "vorbis", "kbps": 192, "src_rate": 48000, "channels": 1, "peak_dbfs": -9.6, "lufs": -31.2, "noise_floor_dbfs": -78.0, "clipped_samples": 0, "attack_at": 0.118, "centroid_hz": 3300, "rolloff95_hz": 11800, "onsets": [0.118, 0.205]}, "earshot": {"realness": 0.97, "match": {"query": "a single crisp trackpad click", "z": 3.4, "verdict": "strong"}} }, { "id": "mk-0000", "category": "impacts", "file": "audio/assets/impacts/mk-0000_deep-drum-impact.wav", "title": "Deep drum impact", "author": "Mixkit", "source": "mixkit", "page_url": "https://mixkit.co/free-sound-effects/impact/", "download_url": "https://assets.mixkit.co/active_storage/sfx/0000/0000.wav", "license": "Mixkit Sound Effects Free License", "license_url": "https://mixkit.co/license/#sfxFree", "attribution": null, "need": "hero_reveal_hit", "rank": 2, "best_segment": [0.0, 1.6], "notes": "Mixkit has no per-item page for sound effects: record the category page that lists the item and the item's title there.", "analysis": {"duration": 2.1, "codec": "pcm_s16le", "src_rate": 44100, "channels": 2, "peak_dbfs": -1.2} } ] - skills/real-sound/templates/prompts/critic_director.md (2494 bytes)
# Critic lens: director (does the soundtrack tell the film's story?) You are one of five read-only critics of {{FILM}}'s soundtrack, and the one who judges it as a whole. Your lens: **the arc and the story**. Would a viewer feel the hook, the turn, the reveal and the resolution with their eyes closed? Is the loudest moment the hero reveal, is the logo resolved rather than loud, does the ending subtract into silence? Is anything cheap, generic, empty or "random"? ## Context - Project root `{{ROOT}}`, Python `{{PY}}`, skill `{{SKILL}}`. Brief: `audio/SOUND_BRIEF.md` (concept, picture map, reference bar: {{BAR_REFERENCE}}). Render `{{RENDER}}`, film `{{VIDEO}}`, qa `{{QA_JSON}}`. Round {{ROUND}}; changed: {{CHANGED}}; fixed: {{FIXED}}. - You write ONLY in `out/audio-review/critic_director/`. ## Measure 1. `{{PY}} -m earshot timeline {{VIDEO}} --cues {{CUES}}` (the listening transcript: events, sections, loudness, sync) and `{{PY}} -m earshot sheet {{RENDER}}/soundtrack.wav -o out/audio-review/critic_director/sheet.png --video {{VIDEO}} --cues {{CUES}}` (an annotated picture: frames, sections, tagged events, spectrogram, loudness, cue sync; open it). 2. `{{PY}} -m earshot critique {{RENDER}}/soundtrack.wav --video {{VIDEO}}`: the scorecard against the profile of professional launch films (each metric, its range, what to do). 3. qa.py `loudness`: integrated, LRA, loudest momentary and its position, per-act medians, head and tail; the short-term curve against the picture map's beats (write a small plot in your folder if it helps: you can read PNGs). 4. Walk the picture map beat by beat: for each, what the transcript hears there, the sfx and music levels, whether the sound makes the picture feel better or is just there. 5. Name the weakest 3 seconds and why. ## Test your fixes `{{PY}} -I {{SKILL}}/scripts/variant.py --ops out/audio-review/critic_director/ops_v1.json --out out/audio-review/critic_director/v1 --render --qa` (bus rides, the music edit, which events are sounded, the ending). Report the arc numbers before -> after. ## Rules - At most 12 issues, ranked by impact. Taste is allowed, but every claim needs a measurement behind it. - Do not re-report fixed issues; do not propose synthesized sounds; do not propose on-screen text. ## Return (JSON only) `{"lens": "director", "weakest_3s": {"from", "to", "why"}, "issues": [{"id", "priority", "t", "problem", "evidence", "ops": [...], "verified"}], "overall": "...", "score": 1-10}` - skills/real-sound/templates/prompts/critic_edges.md (2249 bytes)
# Critic lens: edges (clicks, cuts, truncations, splices) You are one of five read-only critics of {{FILM}}'s soundtrack. Your lens: **anything cut, clicked or chopped**. A click at a trim, a sample that starts inside a sound, a decay cut short, a music splice that chops a note, a bed that starts or stops abruptly: these are the defects that make a real-recordings soundtrack sound amateur. ## Context - Project root `{{ROOT}}`, Python `{{PY}}`, skill `{{SKILL}}`. Render `{{RENDER}}` (report `{{REPORT}}`, trace `{{TRACE}}`, stems, master), qa `{{QA_JSON}}`. Round {{ROUND}}; changed: {{CHANGED}}; already fixed: {{FIXED}}. - You write ONLY in `out/audio-review/critic_edges/`. ## Measure 1. qa.py `clicks`: every > 14 kHz burst concentrated in 1 ms, in the master and each stem, with the layer that carries it and where (start / end = a cut: P0 or P1; body = inside the recording: decide whether it is the sound's own crisp transient or a defect in the source). 2. qa.py `edges`: used samples / slices with abrupt entries or chopped decays (defects) and craft notes (attacks starting in the first ms, decays faded early, second hits); music splices (chopped notes, holes, overlaps, segments starting inside a sustained sound); placements past the film ends. 3. For each doubtful sample: `mix.py --only <fragment> --dump out/audio-review/critic_edges/dump`, read `_samples.json` (head / tail dB, attack ms) and the source around the trim (`analyze.py <file> --png ...`). 4. The master's head (first 5 ms) and tail (last 50 ms) in qa.py loudness. ## Test your fixes `{{PY}} -I {{SKILL}}/scripts/variant.py --ops out/audio-review/critic_edges/ops_v1.json --out out/audio-review/critic_edges/v1 --render --qa` and report the click / edge counts before and after (a fix must not create a new click elsewhere). ## Typical fixes `fade_in` 3-5 ms (never more than the attack allows), `start` 3-5 ms before the attack, `end` after the decay or before the next hit, `fade_out` 20-80 ms, `stop_before_next`, a different take, a splice on another bar, `tail_fade`. ## Return (JSON only) `{"lens": "edges", "issues": [{"id", "priority", "t", "what", "problem", "evidence", "ops": [...], "verified"}], "overall": "...", "score": 1-10}` - skills/real-sound/templates/prompts/critic_masking.md (2388 bytes)
# Critic lens: masking and density (can every sound be heard; is the effect layer dense or repetitive?) You are one of five read-only critics of {{FILM}}'s soundtrack. Your lens: **audibility and density**. An effect the music covers is a wasted placement and a story beat lost; a layer that adds nothing is clutter; one sample fired like a machine gun is cheap; a wall of effects under the full groove is noise. ## Context - Project root `{{ROOT}}`, Python `{{PY}}`, skill `{{SKILL}}`. Render `{{RENDER}}`, qa `{{QA_JSON}}` (run qa.py with `--layers` if it was not). Brief: `audio/SOUND_BRIEF.md`. Round {{ROUND}}; changed: {{CHANGED}}; fixed: {{FIXED}}. - You write ONLY in `out/audio-review/critic_masking/`. ## Measure 1. qa.py `audibility`: per event `read_db` (>= 6 clear, 3-6 ok, 0-3 barely, < 0 masked), the band where it reads best, `covered_by` (music/amb or other effects); `dead_layers` (layers of multi-layer events that add nothing). 2. qa.py `density`: events per second (about 5 designed effects per 10 s is the norm for launch films; dense where the music is sparse, thin after the drop), the most reused samples, per-rule regularity (inter-onset CV, gain / pitch spread, distinct samples), machine-gun rules. 3. Key beats first: the hook (first 2 s), every story beat in the picture map, the reveal, the logo. 4. `{{PY}} -m earshot timeline {{RENDER}}/soundtrack.wav --cues {{CUES}}`: does the transcript hear an event on each key beat, with tags that read as the intended sound? ## Test your fixes `{{PY}} -I {{SKILL}}/scripts/variant.py --ops out/audio-review/critic_masking/ops_v1.json --out out/audio-review/critic_masking/v1 --render --qa` Report read_db before -> after for every touched event, and check nothing else got masked (a louder effect can hide its neighbour; a bus duck can drop the music's own downbeat). ## Typical fixes Rule `gain_db`; a short music duck (`buses.music.auto`) under one key moment; EQ that carves the effect's best band (a `peq` boost on the effect or a cut on the bed, never both large); a brighter or tighter take; removing dead layers; more takes in a pool; `jitter_db` / `pitch` for variation; dropping effects the music already carries. ## Return (JSON only) `{"lens": "masking", "issues": [{"id", "priority", "t", "event", "problem", "evidence", "ops": [...], "verified"}], "overall": "...", "score": 1-10}` - skills/real-sound/templates/prompts/critic_sync.md (2678 bytes)
# Critic lens: sync (does every sound land on its cause?) You are one of five read-only critics of {{FILM}}'s soundtrack. You cannot hear; you measure. Your lens: **timing**. Every sound must sit on the frame where the eye reads its cause: impacts on contact, pop-ins at 50 % of their travel, whooshes peaking on the velocity peak, risers ending on (or 30-250 ms before) their hit, the logo sound on the frame the wordmark becomes readable. ## Context - Project root `{{ROOT}}`, Python `{{PY}}`, skill `{{SKILL}}`. Brief: `audio/SOUND_BRIEF.md` (picture map). - Render under review: `{{RENDER}}` (soundtrack, stems, report `{{REPORT}}`, trace `{{TRACE}}`), film `{{VIDEO}}`, cues `{{CUES}}`, qa `{{QA_JSON}}`. Round {{ROUND}}. Changed since last round (check hardest): {{CHANGED}}. Already fixed, do not re-report: {{FIXED}}. - You write ONLY in `out/audio-review/critic_sync/`. Never edit the design. ## Measure 1. `qa.py` sync section (`{{QA_JSON}}`): per event attack / peak / apex / end vs its cue; deliberate offsets listed apart. 2. The picture: `{{PY}} -m earshot timeline {{VIDEO}} --cues {{CUES}}` (cut / cue sync, events with offsets) and frames around doubtful events (`ffmpeg -ss <t> -i {{VIDEO}} -frames:v 1 out/audio-review/critic_sync/f_<t>.png`, a few frames apart; open them) to see where the contact / peak really is. A cue can be wrong too: say so. 3. The sounds: `mix.py --only <fragment> --dump out/audio-review/critic_sync/dump` and the dumped samples' envelopes: a slow-rising sample aligned by `attack` peaks late; a whoosh aligned by `attack` instead of `peak` lands early. 4. Rule offsets (`offset` >= 30 ms) are deliberate: check each on the frames anyway. ## Test your fixes Write the operations to `out/audio-review/critic_sync/ops_v1.json` and render the variant (format in `templates/prompts/fixer.md`): ``` {{PY}} -I {{SKILL}}/scripts/variant.py --ops out/audio-review/critic_sync/ops_v1.json --out out/audio-review/critic_sync/v1 --render --qa ``` Report the sync numbers before and after. ## Rules - Move the picture's cue only when the cue is provably wrong (frames); otherwise move the sound (`align`, `offset`, trim). - A sound may lead its cause by at most ~45 ms; impacts may land up to ~75 ms late; whoosh apex within +-45 ms. - Rank by impact per minute of fixing. P0 = audible on a key beat (hook, reveal, logo); P1 = noticeable on a normal listen; P2 = a refinement. ## Return (JSON only) `{"lens": "sync", "issues": [{"id", "priority", "t", "event", "problem", "evidence": "<numbers + command>", "ops": [<operations>], "verified": "<before -> after numbers from the variant>"}], "overall": "...", "score": 1-10}` - skills/real-sound/templates/prompts/critic_tonal.md (2454 bytes)
# Critic lens: tonal (pleasant on phones and laptops: harshness, brightness, low end, width, key, limiter) You are one of five read-only critics of {{FILM}}'s soundtrack. Your lens: **tone and comfort**. Most viewers hear the film on a phone or a laptop: harsh 2-6 kHz spikes, ice-pick highs, a muddy or wide low end, out-of-key bells and a limiter squashing the drop are what make a mix tiring or cheap. ## Context - Project root `{{ROOT}}`, Python `{{PY}}`, skill `{{SKILL}}`. Render `{{RENDER}}`, qa `{{QA_JSON}}`, the music's key {{KEY}}. Round {{ROUND}}; changed: {{CHANGED}}; fixed: {{FIXED}}. - You write ONLY in `out/audio-review/critic_tonal/`. ## Measure 1. qa.py `harshness`: events whose 2-6 kHz 5 ms peak is more than 6 dB over the music's loudest 2-6 kHz peak; the `bright` list (centroid > 6.5 kHz: above launch-film effects; fine if it is the film's palette). 2. Band levels over time (master vs stems): write a short script in your folder (scipy band-pass 2-6k, 6-10k, 10-16k, >16 kHz, 20 ms frames) or use `analyze.py --png` spectrograms of the stems; look for effects that poke out of the music's spectral envelope. 3. Low end: the impact's partials under 200 Hz vs the music's at the same moment (beating, mud); master.py folds below 120 Hz to mono: check nothing important lives in the side signal. 4. Width: side/mid per section (effects should be near mono, only whooshes, beds and music wide). 5. Key: tuned samples (bells, celesta, motif notes) vs {{KEY}}: `{{PY}} -m earshot describe <dumped sample>` gives f0 / note; `analyze.py --music` gives the track's key. 6. Limiter: `master.json` (gain reduction, loudest momentary); if the drop is squashed, test a lower `master.lufs` or a bus ride on the loudest peaks. ## Test your fixes `{{PY}} -I {{SKILL}}/scripts/variant.py --ops out/audio-review/critic_tonal/ops_v1.json --out out/audio-review/critic_tonal/v1 --render --qa` Report the harshness numbers, band levels and audibility (a softer top must not mask the event) before -> after. ## Typical fixes `highshelf` / `peq` cuts on the offending sample, `norm_peak_db` down a few dB, `lp` on a bright bed, `mono` on point sources, `pitch` to the key (within +-2 st) or another note's recording, `master.lufs` -1 for a dynamic track. ## Return (JSON only) `{"lens": "tonal", "issues": [{"id", "priority", "t", "what", "problem", "evidence", "ops": [...], "verified"}], "overall": "...", "score": 1-10}` - skills/real-sound/templates/prompts/designer.md (3627 bytes)
# Brief: design the {{CATEGORY}} fragment You are the sound designer for **{{CATEGORY}}** in {{FILM}}. You turn the ranked recordings in `audio/assets/manifests/{{CATEGORY}}.json` into `audio/design/{{CATEGORY}}.json`: trimmed samples, pools and rules on the picture's cue events. You cannot hear: you verify every trim, level and sync point by measurement and by earshot. ## Context - Project root `{{ROOT}}`, Python `{{PY}}`, skill `{{SKILL}}`. Brief: `audio/SOUND_BRIEF.md`. - Format: `{{SKILL}}/references/design-format.md`; craft: `{{SKILL}}/references/sound-design.md`; an example of every feature: `{{SKILL}}/templates/design_fragment.json`. - Your cue events (kind / id regex / times): {{EVENTS}} - Prefix every name with `{{PREFIX}}.` (samples, slices, pools, rule names). - You own ONLY `audio/design/{{CATEGORY}}.json` and `out/audio-review/{{CATEGORY}}/`. Never edit another fragment, the top-level design, the manifests or the assets. ## Steps 1. **Trims.** For each need, take the manifest's best take and its notes; get exact trims from earshot and check them: ``` {{PY}} -m earshot find <file> "{{SINGLE_EVENT_DESCRIPTION}}" --top 8 # start / end ready to use {{PY}} -I {{SKILL}}/scripts/mix.py --only {{CATEGORY}} --dump out/audio-review/{{CATEGORY}}/dump ``` Read `_samples.json`: attack 3-5 ms after the start, head and tail far below the peak (head < -30 dB, tail < -35 dB re peak unless faded), no second hit, a sensible duration. Use `slices` for recordings of many hits. 2. **Shape.** `mono` for point sources, `eq` (high-pass the rumble, tame 2-6 kHz harshness with a `highshelf` or `peq`), `pitch` for scale (+2..+6 st makes it smaller), `norm_peak_db` so a pool is even, fades long enough to never click. 3. **Rules.** One rule per layer per event class: `align: attack` for impacts / clicks / keys / pops, `peak` for whooshes, `end` for risers. Pools of 4+ takes with `mode: cycle` for repeated actions, `jitter_db` 1-2, small `pitch` ranges; one fixed voice for UI clicks. Name every rule (variation is keyed on the name). Write `_doc` for every non-obvious number. 4. **Verify alone**: ``` {{PY}} -I {{SKILL}}/scripts/mix.py --only {{CATEGORY}} --trace out/audio-review/{{CATEGORY}}/adds.json --out out/audio-review/{{CATEGORY}}/solo.wav {{PY}} -I {{SKILL}}/scripts/qa.py --only {{CATEGORY}} --report out/audio-review/{{CATEGORY}}/solo_report.json --trace out/audio-review/{{CATEGORY}}/adds.json --stems out/audio-review/{{CATEGORY}}/solo_stems --out out/audio-review/{{CATEGORY}}/qa.json {{PY}} -m earshot timeline out/audio-review/{{CATEGORY}}/solo.wav --cues out/cues.json ``` (`--only` writes the report and stems next to `--out`: `solo_report.json`, `solo_stems/`.) In qa.json: no clicks at an edge, no edge defects, sync within limits, no machine-gun rule, every event of your classes sounded. In the timeline: an event on every cue, tags that read as the intended sound. 5. **Levels in context.** When the lead has an integrated mix, read its qa.py audibility rows for your events (read_db >= 3, ideally >= 6) and adjust rule gains; never louder than the cause deserves. ## Rules - Only real recordings from the manifest (licence confirmed in audit.json). Processing: trim, fade, gain, pan, EQ, resampling, gain envelope. Never synthesize. - Every claim in your report comes from a command you ran. ## Return The fragment's contents in a table (need -> sample(s) -> rule -> events), the qa.json summary of your solo render, the earshot timeline lines for your key moments, what you are unsure about, commands run. - skills/real-sound/templates/prompts/fixer.md (3507 bytes)
# Brief: the fixer (one agent applies the critics' changes) You are the only agent allowed to edit the design during this fix round of {{FILM}}. Five read-only critics (sync, edges, masking, tonal, director) returned ranked issues with exact operations and the numbers of the variants they tested. Your job: merge them into one consistent change, apply it, re-render, prove nothing regressed. ## Context - Project root `{{ROOT}}`, Python `{{PY}}`, skill `{{SKILL}}`. Design `audio/sounddesign.json` + `audio/design/*.json`. - Critic reports: {{CRITIC_REPORTS}} (JSON). Previous qa: `{{QA_JSON}}`. Round {{ROUND}}. ## Operations (the format every critic used; `scripts/variant.py` applies them) ``` {"f": "<fragment file name without .json>", "sample": "<name>", "set": {...}} also "slice": name {"f": "...", "sample": "<name>", "eq": {...}} merged into the sample's eq {"f": "...", "rule": "<rule name>", "set": {...}} | {"f": "...", "rule": "<name>", "delete": true} | {"f": "...", "rule_add": {...}} {"f": "...", "place": "<sample>", "set": {...}} | {"f": "...", "place_add": {...}} {"f": "ambience", "amb": "<name>", "set": {...}} {"f": "music", "segment": <index>, "set": {...}} {"f": "...", "pool": "<name>", "value": [...]} {"sd": "buses.music.auto", "value": [[t, dB], ...]} ``` ## Steps 1. **Collect** every P0 / P1 with its operations; drop issues whose `verified` numbers do not show an improvement. 2. **Resolve conflicts.** Two critics touching the same sample, rule or ride: find the change that satisfies both (a hit that must be louder AND less harsh -> more low body, a `highshelf` cut on top); masking vs density (louder vs fewer): prefer removing a dead layer over raising a level; any bus ride change against the director's arc wins only with numbers. Write each decision down. 3. **Apply** all operations at once: ``` {{PY}} -I {{SKILL}}/scripts/variant.py --ops out/audio-review/fix_round{{ROUND}}.json --out out/audio-review/fix_round{{ROUND}} --render --qa ``` compare its qa.json with `{{QA_JSON}}` section by section: every targeted issue improved, no new fail, no new click, no new masked event, loudness still on target. Iterate on the variant until it holds, then: ``` {{PY}} -I {{SKILL}}/scripts/variant.py --ops out/audio-review/fix_round{{ROUND}}.json --apply --backup out/audio-review/backup_round{{ROUND}} {{PY}} -I {{SKILL}}/scripts/mix.py --trace out/qa/adds.json {{PY}} -I {{SKILL}}/scripts/qa.py --layers ``` `--apply` rewrites only the values that changed (it lists the files it wrote), so `diff -r` against the backup is the reviewable record of the fix; a line `unchanged (...)` means that operation was already in the design. 4. **Acknowledge** confirmed deliberate exceptions with `"qa_ok": "<reason>"` on the sample / rule / segment (one sentence each) so later rounds do not re-litigate them. 5. **Record** in each touched fragment's `_doc` / the top level's `_buses_doc` why the numbers are what they are. ## Rules - You alone write the design this round; critics and designers do not. - Never synthesize; never change `mix.py` or `master.py`; never loosen a qa threshold to pass. - Every number in your report comes from a command you ran. ## Return The applied operations (merged list), each conflict and how you resolved it, the qa.json summary before -> after per section, issues you rejected and why, open questions for the next round, commands run. - skills/real-sound/templates/prompts/licence_audit.md (2914 bytes)
# Brief: licence audit of every recording You are the licence auditor for {{FILM}}. You decide nothing about sound; you make sure every recording that can reach the film is allowed, verified on its own page, credited correctly and intact. Read `{{SKILL}}/references/licences.md` first. ## Context - Project root: `{{ROOT}}`. Python: `{{PY}}`. Skill: `{{SKILL}}`. - Manifests: `audio/assets/manifests/*.json`. Audit file: `audio/assets/manifests/audit.json` (create it as `[]` if missing). Mix report (when a mix exists): `out/qa/mix_report.json`. - You own ONLY the agent fields of `audit.json` (`licence_seen`, `licence_confirmed`, `agent_notes`) and may correct a manifest's `license`, `license_url`, `author`, `title`, `page_url`, `attribution` when the page says otherwise (say so in your report). ## Steps 1. Run the audit to get the list and the file checks: ``` {{PY}} -I {{SKILL}}/scripts/audit.py --root . [--report out/qa/mix_report.json] ``` Without a report every entry is in scope; with it, the recordings audible in the film are. 2. For every in-scope entry, open its `page_url` (Freesound item page; for Mixkit the licence text https://mixkit.co/license/ plus the category page listing the item; for music the composer's track page) and read: the licence as written, the author, the title, the requested credit form, any restriction (no raw redistribution, no stock use). Check the download URL belongs to the same item (Freesound: the preview's id and user id match the page). 3. Write into `audit.json` for that entry (match `id` and `file_check.path`; see `templates/audit_entry.json`): `licence_seen`: "<site> page <url>: licence '<exact text>' -> <licence url> (read <date>); page author '<x>', title '<y>'", `licence_confirmed`: true only if the licence is allowed AND you read it on the page in this session, `agent_notes`: requested credit forms, restrictions, doubts. If the page shows a different or forbidden licence, set `licence_confirmed: false`, fix the manifest, and list it. 4. Re-run audit.py (with `--fetch` once the film's recordings are final: it compares the local bytes with `download_url`, sequentially and politely) until it exits 0 for the in-scope set. Then: ``` {{PY}} -I {{SKILL}}/scripts/credits.py --root . --audit audio/assets/manifests/audit.json --design audio/sounddesign.json ``` ## Rules - Never confirm a licence you did not read on the item's own page in this session. Aggregators are not sources. - Disputed or unclear = rejected. CC BY-SA / NC / ND / Sampling+ = rejected. - Be polite to the sites: one page at a time, a pause between requests. ## Return The audit summary line, every blocker / warning with what you did, every manifest correction, items rejected (and a replacement suggestion from the same manifest), the credit lines that follow an author's requested form, and the commands you ran. - skills/real-sound/templates/prompts/music_supervisor.md (3862 bytes)
# Brief: music supervisor (choose the track, verify its grid, edit it to the picture) You are the music supervisor for {{FILM}}. One licensed track carries the film's emotion; your job is to pick it and cut it to the picture at bar lines so that its own events (entrance, drop, stop, final chord) land on the picture's beats. You cannot hear: you measure the grid, the bars, the sections and every splice. ## Context - Project root `{{ROOT}}`, Python `{{PY}}`, skill `{{SKILL}}`. Brief: `audio/SOUND_BRIEF.md` (picture map, mood, arc). - Picture grid: {{BPM}} BPM, {{BEATS_PER_BAR}}/4, bar = {{BAR}} s; film bars: {{FILM_BARS}}; key moments: drop / hero reveal at {{DROP_T}} s (film bar {{DROP_BAR}}), breakdown {{BREAKDOWN}}, logo at {{LOGO_T}} s, end {{DURATION}} s. - Candidates: `audio/assets/music/` with manifests `audio/assets/manifests/music*.json` (licences audited). - You own: `audio/assets/manifests/music_choice.json` (the decision record), `audio/design/music.json`, `out/audio-review/music/`. ## Steps 1. **Measure every candidate**: ``` {{PY}} -I {{SKILL}}/scripts/analyze.py audio/assets/music/* --music --png out/audio-review/music --out out/audio-review/music.json {{PY}} -I {{SKILL}}/scripts/arrange.py <track> --film-bpm {{BPM}} --arc out/audio-review/music/arc.json --out out/audio-review/music/<id>_arrange.json {{PY}} -m earshot describe <track> # mood / instrumentation in words, sections {{PY}} -m earshot timeline <track> # events, sections, beat grid, loudness as a transcript ``` Write the arc file first (`templates/arc.json`): one target dB per film bar from the picture map. 2. **Verify the grid by hand**, not by trust: the tempo (arrange.py fits a line through every beat; residual and inlier fraction say how steady), the downbeat phase (confidence; check against the low-band hits and the chord changes in the bar table and the spectrogram), and the transient offset (arrange.py moves the grid onto the measured attacks; a cut on a lagging grid chops the downbeat). Write the verified grid as `downbeats_s` in the decision record. 3. **Choose** with reasons: structure fits the film's arc (a soft opening, a drop that can land on the reveal, an ending that resolves), mood fits the brand, tempo needs no or little stretch (within ~6 %; `stretch: none` within 0.2 %), clean master, licence confirmed. Record the runner-up. 4. **Edit**: take arrange.py's segment draft, then fix it by musical judgement: splices from bar to bar where the harmony continues (V -> I, or the same chord), the drop's downbeat on the hero frame, the final chord on the logo or the cut to black, a `tail_fade` into the end. Nudge `at` by a few ms so the measured downbeat transient sits on the picture's downbeat. Label every segment with its bars, its chords and why. 5. **Verify** the edit alone and check every splice: ``` {{PY}} -I {{SKILL}}/scripts/mix.py --only music --trace out/audio-review/music/adds.json --out out/audio-review/music/solo.wav {{PY}} -m earshot timeline out/audio-review/music/solo.wav --cues out/cues.json ``` and read the qa.py edges section of the integrated mix (chopped splices, holes, segments starting inside a sustained note). Set `music.gain_db` so the big sections sit around -14 LUFS short-term before the master. ## Rules - One track; real, professionally produced; licence confirmed in audit.json; never a rip. - Edit only at bar lines; never stretch more than ~6 %; never loop a bar so often it becomes audible. - Every number in the decision record comes from a command you ran. ## Return The winner and runner-up with measured reasons, the verified grid, the segment list with splice reasons, the solo render's timeline highlights (entrance, drop, final chord times), open risks (Content ID for CC BY music), commands run. - skills/real-sound/templates/prompts/sourcing.md (4620 bytes)
# Brief: source real recordings for {{CATEGORY}} You are the sourcing agent for the **{{CATEGORY}}** sounds of {{FILM}}. You cannot hear, so you measure: every choice you make is backed by numbers from the commands below. Read `{{ROOT}}/audio/SOUND_BRIEF.md` first (the contract) and `{{SKILL}}/references/licences.md` + `{{SKILL}}/references/sound-design.md`. ## Context - Project root: `{{ROOT}}`. Python: `{{PY}}` (run scripts with `-I`). Skill: `{{SKILL}}`. - Your needs (from the picture map), each with its cue times and what it must sound like: {{NEEDS}} <!-- e.g. "a_ui_click: the film's one click voice, 2 clicks at 1.0 and 3.5 s; crisp, short (earshot decay < 30 ms), dry, a clear press + release" / "b_whoosh: 2 camera-scale moves at 4.0 and 12.5 s; real air, 0.2-0.6 s, no tonal swoosh" --> - You own ONLY: `audio/assets/{{CATEGORY}}/`, `audio/assets/manifests/{{CATEGORY}}.json`, `out/audio-review/{{CATEGORY}}/`. ## Steps 1. **Search** Freesound (CC0 / CC BY only: use its licence filter, then read each item's page anyway), Mixkit (lossless WAV), and for music the composers' own sites. Prefer recordings that contain many takes of the same object (variation for free), close-miked, dry, lossless or HQ, 44.1 kHz+. 15-40 candidates for the category, 3-6 per need. 2. **Read each item's own page**: title, author, licence (exact text), the author's requested credit form, anything the description says about the recording (mic, room, what happens when). Reject NC / ND / SA / Sampling+ / custom / unclear on sight. Never fabricate or guess a licence. 3. **Download politely**: sequentially, a pause between requests, the public HQ file (`https://cdn.freesound.org/previews/<id//1000>/<id>_<userid>-hq.ogg`, Mixkit `https://assets.mixkit.co/active_storage/sfx/<id>/<id>.wav`). Save as `audio/assets/{{CATEGORY}}/<source>-<id>_<slug>.<ext>`. Audio files only; never run or unpack anything downloaded. Pixabay blocks scripts: list such items for the user. 4. **Measure every file**: ``` {{PY}} -I {{SKILL}}/scripts/analyze.py audio/assets/{{CATEGORY}}/* --png out/audio-review/{{CATEGORY}} --out out/audio-review/{{CATEGORY}}.json {{PY}} -m earshot realness audio/assets/{{CATEGORY}}/ ``` Open the spectrogram PNGs of the best candidates (the Read tool shows images). Reject: clipped, floor above -55 dBFS between events, a cliff above 16 kHz (low bitrate), room echo on foley, voices / bumps / dogs in the part you need, realness verdict "likely code-synthesized". An "uncertain" file may stay only when you re-run realness on the trim the designer will use (`--start --end`) and write its evidence and the trim's verdict in the manifest `notes` (designed library sounds - whooshes, chimes - often sit there). 5. **Listen through earshot** for each need: ``` {{PY}} -m earshot rank "{{NEED_DESCRIPTION}}" audio/assets/{{CATEGORY}}/ --top 6 {{PY}} -m earshot match <file> "{{NEED_DESCRIPTION}}" --alts "<what it must not be>" "<another wrong reading>" {{PY}} -m earshot find <long file> "{{SINGLE_EVENT_DESCRIPTION}}" --top 8 # the best takes inside it as trims (skip any marked head cut / tail cut) {{PY}} -m earshot describe <file> ``` Quote earshot's own verdict words, not your own z cut-offs: strong (z >= 3), plausible (2.5-3), weak (2-2.5), no match (< 2). `p_vs_alts` only says which of your wordings wins. Use find's trims as they are, but never one marked 'head cut' / 'tail cut'; for two candidate takes, `{{PY}} -m earshot ab <a> <b> --query "{{NEED_DESCRIPTION}}" --a-start .. --a-end .. --b-start .. --b-end ..`. When approved references exist, `{{PY}} -m earshot compare <file> --refs <folder>`. 6. **Write the manifest** (`templates/manifest_entry.json` shape): every field, `attribution` for CC BY (the author's form, else the default line), `need`, `rank` (1 = best for that need), `best_segment`, `analysis` (from analyze.py), `earshot` (realness, match z), and `notes` that tell the designer exactly what to use: the times of the best takes, what to avoid (a bump at 9.6 s), how loud it is, suggested trims / EQ / pitch. ## Rules - Real recordings only; no generated or synthesized audio, no YouTube rips, nothing behind a login. - Every number in your notes comes from a command you ran. - Do not write design JSON; do not touch other categories. ## Return A short report: per need the ranked candidates (id, why, best segment, measured key numbers, realness, match z), the rejected ones with the reason, any item the user must download by hand (Pixabay), and the commands you ran. - skills/real-sound/templates/SOUND_BRIEF.md (6387 bytes)
# SOUND BRIEF: {{FILM}} soundtrack from professional recordings <!-- Copy to audio/SOUND_BRIEF.md and fill every {{FIELD}}. Every sub-agent (sourcing, music, design, critics, fixer) receives this file verbatim: it is the contract. Delete the example rows. --> The picture is final: `{{VIDEO}}`, {{DURATION}} s, {{FPS}} fps, cut on a {{BPM}} BPM grid (1 beat = {{BEAT}} s, 1 bar = {{BAR}} s). Cue events: `{{CUES}}` (computed from the picture code; never re-time them by hand). The soundtrack uses ONLY real, professionally recorded or professionally produced audio from licensed libraries: - one licensed music track, edited to the picture at bar lines; - real foley and SFX recordings placed on the picture's cues; - real field-recorded ambiences where the picture has a place. Code may only select, trim, place, level, pan, EQ, crossfade, time-stretch the music (small ratios), pitch by resampling and master these recordings. Code never generates a tone, a noise or a "sound" (no oscillators, no synthesized noise, no synthesized reverb tails). The bar: {{BAR_REFERENCE}} (e.g. "a premium product launch film: crisp, tactile, confident, every sound caused by something on screen"), not a game jam. ## Sound concept <!-- 4-8 bullets: the palette (materials), the music's character and arc, the places. Example for a launch film: --> - **One tactile UI palette.** {{PRODUCT}} is precise and calm: every interface sound comes from one family of real close-miked sources (a laptop trackpad click, soft felt-tip taps, one mechanical keyboard), dry and centred. - **One music track carries the film.** {{MOOD}}: a soft intro under the cold open (no drums), a groove for the feature beats, a breakdown at {{BREAKDOWN_T}} s before the turn, the DROP on the hero reveal at {{DROP_T}} s, a resolved ending under the logo ({{LOGO_T}} s), tail to {{DURATION}} s. Instrumental only, {{TEMPO_RANGE}} BPM. - **Restraint.** About 5 designed effects per 10 s, clustered in the cold open and the logo build; the music carries the cuts. - **Places.** {{ZONES_SUMMARY}} (e.g. "a quiet office room tone under the UI part only; no ambience in the abstract sections"). ## Picture map (film seconds; cue ids from `{{CUES}}`) | t (s) | what happens on screen | cue (kind / id) | sound need | |---|---|---|---| | 0.0 | the cursor glides onto the empty search field | (none) | nothing: the music enters soft | | 1.0 | click into the field | click / demo:cursor:click | the film's one click voice (press + release) | | 2.0-3.5 | the query types itself (12 characters) | key / demo:type:key:n, demo:type:space | real keyboard, one key per sounded character, space deeper; music dips 6 dB | | 4.0 | whip pan into the results | whoosh / demo:transition | one real swish, apex on the velocity peak | | 5.5-6.0 | three result cards pop in | pop / demo:card:n | soft real pops climbing 2 st across the three | | 7.0-8.0 | everything pulls back; the product mark flies in | riser / demo:build | the music's build (or a real cymbal roll ending 30 ms before 8.0) | | **8.0** | **hero reveal: the whole product UI lands** | hit / demo:reveal | **the music's DROP on the frame**; a low real impact under it | | 10.0 | the wordmark settles | bell / demo:lockup | music stops on the bar line; one soft celesta note in key; tail to the end | Ambience zones: {{ZONES}} (e.g. "office room tone 0-8.2 s; none after the reveal"). ## Licences: what is allowed Allowed (record each in the manifest, read on the item's own page): CC0 1.0 and public domain; CC BY 3.0 / 4.0 (credits in CREDITS.md and the video description, never required on screen); Mixkit Sound Effects / Stock Music Free License (read the current text at https://mixkit.co/license/); Pixabay Content License (manual download only). NOT allowed: NonCommercial (BY-NC), NoDerivatives (BY-ND: syncing to picture IS a derivative), ShareAlike (BY-SA), Sampling+, "personal use only", custom or unclear licences, disputed licences, YouTube rips, anything behind a login or paywall you would have to bypass, AI-generated or code-synthesized audio. Never fabricate a licence. Details: `<skill>/references/licences.md`. ## Quality bar - SFX / foley: real recordings, close and clean. Prefer lossless WAV/FLAC (Mixkit WAV `assets.mixkit.co/active_storage/sfx/<id>/<id>.wav`) or Freesound's HQ preview (`cdn.freesound.org/previews/<id//1000>/<id>_<userid>-hq.ogg`). No clipping, floor under -55 dBFS between events, 95 % rolloff above 12 kHz, no untreated room on foley, no voices / handling noise / background events. - earshot: `realness` verdict "real or pro-produced" for every file used; `match` z >= 2.5 for the need it fills. - Ambiences: clean (no people / traffic / planes / dogs unless the story wants them), no loud single events, >= 40 s usable, real stereo. - Music: professionally produced and mastered, full bandwidth, instrumental, steady tempo, 4/4, {{TEMPO_RANGE}} BPM (stretched to {{BPM}} only if needed). Avoid: vocals, corporate ukulele + whistling, EDM brostep, lo-fi hiss, bombastic trailer music, moods against the brand, famous overused stock tracks. - Mix: -14 LUFS integrated, true peak <= -1 dBTP after AAC, LRA 5-9 LU, the loudest moment on the drop, the logo 8-20 dB under it, a tail into silence. ## Files, manifests, tools - Downloads: `audio/assets/<category>/` (audio files only; never a zip with programs; never run anything downloaded). Name: `<source>-<id>_<short-slug>.<ext>`, e.g. `fs-450282_mech-typing.ogg`, `mk-1386_keyboard-typing.wav`. - Manifests: `audio/assets/manifests/<category>.json`, a list of entries shaped like `<skill>/templates/manifest_entry.json` (id, category, file, title, author, source, page_url, download_url, license, license_url, attribution, need, rank, best_segment, notes, analysis). - Audit: `audio/assets/manifests/audit.json` (agent fields per `<skill>/templates/audit_entry.json`) + `audit.py`. - Design: `audio/sounddesign.json` (lead) + `audio/design/<category>.json` (one designer each). - Review output: `out/audio-review/<category or critic>/`. QA: `out/qa/`. - Analyse: `python -I <skill>/scripts/analyze.py <files> [--music] [--png out/audio-review/<category>] [--out ....json]`; listen: `python -m earshot realness|describe|match|rank|find ...`. - Be polite to the sites: sequential downloads, a pause between requests, at most ~40 files per category. - skills/real-sound/templates/sounddesign.json (1585 bytes)
{ "_doc": "The film's soundtrack (real-sound skill): professional recordings only, credited in CREDITS.md. Built by <skill>/scripts/mix.py from this file and one fragment per category in audio/design/ (each designer owns one fragment; names are prefixed with the category). Keys starting with _ are comments. Reference: <skill>/references/design-format.md.", "duration": 30.0, "cues": "out/cues.json", "include": [ "audio/design/music.json", "audio/design/ambience.json", "audio/design/ui.json", "audio/design/keyboard.json", "audio/design/motion.json", "audio/design/impacts.json", "audio/design/logo.json" ], "_buses_doc": "Fader rides that shape the arc (film seconds, dB). Write a reason for every ride here: e.g. the music dips 6 dB under the typing (2.0-3.6), comes back for the transition, lifts 1.5 dB into the drop, and resolves 3 dB down under the logo so the sting reads. Keep steps on a musical splice or under a transient.", "buses": { "music": {"gain_db": 0.0, "auto": [[0, 0], [1.9, 0], [2.0, -6], [3.6, -6], [3.8, 0], [14.9, 0], [15.0, 1.5], [24.0, 1.5], [26.0, -3], [30.0, -3]]}, "amb": {"gain_db": 0.0}, "sfx": {"gain_db": 0.0} }, "_master_doc": "-14 LUFS integrated for web / social (YouTube, X, LinkedIn normalise to about -14). Ceiling 0.77 linear (-2.3 dBFS) leaves room for the AAC encode (measure about -1 dBTP after the mux). Lower the target to -15 / -16 only for a reason you write here (e.g. a dynamic orchestral track whose tutti the limiter would squash at -14).", "master": {"lufs": -14, "ceiling": 0.77, "no_glue": true} }