audial-live 0.1.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. audial_live/__init__.py +3 -0
  2. audial_live/align/METHOD.md +235 -0
  3. audial_live/align/__init__.py +5 -0
  4. audial_live/align/decode.py +98 -0
  5. audial_live/align/drums.py +154 -0
  6. audial_live/align/dsp.py +591 -0
  7. audial_live/align/fit.py +381 -0
  8. audial_live/align/kind.py +125 -0
  9. audial_live/align/livepad.py +137 -0
  10. audial_live/align/pipeline.py +897 -0
  11. audial_live/align/pitched.py +289 -0
  12. audial_live/align/timemap.py +84 -0
  13. audial_live/align/types.py +30 -0
  14. audial_live/align/validate.py +299 -0
  15. audial_live/applog.py +139 -0
  16. audial_live/audio_io.py +105 -0
  17. audial_live/cli.py +130 -0
  18. audial_live/client.py +200 -0
  19. audial_live/install.py +104 -0
  20. audial_live/live.py +79 -0
  21. audial_live/midi_io.py +165 -0
  22. audial_live/remote_script/Audial/__init__.py +7 -0
  23. audial_live/remote_script/Audial/core.py +252 -0
  24. audial_live/remote_script/Audial/dispatch.py +316 -0
  25. audial_live/remote_script/Audial/framing.py +80 -0
  26. audial_live/remote_script/Audial/launcher.py +32 -0
  27. audial_live/remote_script/Audial/lom.py +908 -0
  28. audial_live/remote_script/Audial/ops_browser.py +378 -0
  29. audial_live/remote_script/Audial/ops_dev.py +79 -0
  30. audial_live/remote_script/Audial/ops_env.py +158 -0
  31. audial_live/remote_script/Audial/ops_events.py +135 -0
  32. audial_live/remote_script/Audial/ops_media.py +255 -0
  33. audial_live/remote_script/Audial/ops_mirror.py +648 -0
  34. audial_live/remote_script/Audial/ops_notes.py +144 -0
  35. audial_live/remote_script/Audial/ops_set.py +957 -0
  36. audial_live/remote_script/Audial/ops_turns.py +280 -0
  37. audial_live/remote_script/Audial/server.py +259 -0
  38. audial_live/remote_script/Audial/surface.py +104 -0
  39. audial_live/remote_script/__init__.py +1 -0
  40. audial_live/server.py +148 -0
  41. audial_live/theory.py +355 -0
  42. audial_live/tools/__init__.py +9 -0
  43. audial_live/tools/_common.py +70 -0
  44. audial_live/tools/align.py +509 -0
  45. audial_live/tools/clips.py +320 -0
  46. audial_live/tools/content.py +113 -0
  47. audial_live/tools/creative.py +289 -0
  48. audial_live/tools/devices.py +229 -0
  49. audial_live/tools/extras.py +202 -0
  50. audial_live/tools/groups.py +60 -0
  51. audial_live/tools/media.py +510 -0
  52. audial_live/tools/session.py +385 -0
  53. audial_live/tools/snapshots.py +264 -0
  54. audial_live/tools/tracks.py +214 -0
  55. audial_live-0.1.8.dist-info/METADATA +128 -0
  56. audial_live-0.1.8.dist-info/RECORD +60 -0
  57. audial_live-0.1.8.dist-info/WHEEL +4 -0
  58. audial_live-0.1.8.dist-info/entry_points.txt +2 -0
  59. audial_live-0.1.8.dist-info/licenses/LICENSE +202 -0
  60. audial_live-0.1.8.dist-info/licenses/NOTICE +8 -0
@@ -0,0 +1,3 @@
1
+ """Audial for Ableton Live."""
2
+
3
+ __version__ = "0.1.8"
@@ -0,0 +1,235 @@
1
+ # Align MIDI to audio: the method, and where each step lives
2
+
3
+ The method is the author's (his private research copy, `reference/alignment/`, is not in this repository). This package is its numpy
4
+ port, so users install nothing (no ffmpeg, no compiler). The MCP tool is `align_midi_to_audio` in
5
+ `audial_live/tools/align.py`.
6
+
7
+ ## His files → the port
8
+
9
+ | His step | His file | Port |
10
+ |---|---|---|
11
+ | decode: `ffmpeg -ac 1 -ar 20000` | (shell) | `decode.load` (mono 20 kHz), `decode.load_native` (file rate, for his filters); soundfile, macOS `afconvert` for M4A/AAC |
12
+ | Live's decode offset | `livepad.py` | `livepad.pad_for` / `live_pad` / `mp3_header` (reads the file's header, see below) |
13
+ | onset envelope, score, grid, coarse, DP warp | `core.c` | `dsp.onset_env`, `dsp.Stem` + `dsp.score`, `dsp.grid`, `dsp.coarse`, `dsp.dtw` |
14
+ | band energy, 1 ms hop | `bandenv.c` | `dsp.band_env` |
15
+ | per-pitch harmonic energy, 2 ms hop | `pitchenv.c` | `dsp.pitch_env` |
16
+ | sample cross-correlation | `xc.c` | `dsp.xcorr` |
17
+ | ffmpeg band filters of his House2 test run | (shell) | `dsp.BANDS` (drums), `dsp.MONO` (single voice), `dsp.band_signal` |
18
+ | song map | `fit2.py` | `fit.fit_song` |
19
+ | drum pass | `refine_drums.py` | `drums.refine` |
20
+ | pitched pass, `MONO=`, `FIXBIAS=` | `refine_pitched.py` | `pitched.refine`, `pitched.FIXBIAS` |
21
+ | part weights | `songs.json` | `pipeline.DRUM_WEIGHT` / `PITCHED_WEIGHT` (2 / 1), `PairInput.weight` |
22
+ | "validate every part" | README step 3 (by hand) | `validate.judge` / `validate.choose` |
23
+ | convert to Live time and apply | README step 4 | `timemap.ClipTime`, `tools/align.py` (notes edited in place by id, no re-import) |
24
+ | drums or pitched, which envelope | (his choice per part) | `kind.part_kind`, `kind.drum_band`, `kind.mono_filter`, `kind.is_single_voice` |
25
+
26
+ `pipeline.align_pairs(pairs, mode)` runs the steps in his order for one song: time model → kind → song map (all
27
+ pairs together) → note-by-note pass → correction → validation. Constants keep his names or say which of his
28
+ literals they are.
29
+
30
+ ## Two modes
31
+
32
+ - `mode="fit2"`: his method as he ran it, decision for decision (parity, `scripts/align_parity.py`). His full
33
+ search only, his frame and rounding, his passes on his inputs (drums on the MIDI as placed, pitched on his linear
34
+ map + DT), the uniform candidate his FIXBIAS path. Validation still picks per part.
35
+ - `mode="product"` (the tool) adds, each behind a named constant:
36
+ - `pipeline`, the clip's current placement (the author's local mode, 2026-11-26), checked before any song-level
37
+ search: its position passes its check when at least `REAL_ON_ATTACK` (30 %) of its notes over the audio already
38
+ sit on an attack and at least 8 notes sit over the audio (`validate.placement_passes`: `validate.measure`'s
39
+ share of notes with a flux peak within ±50 ms of where the flux peaks for a note on its attack, `FLUX_LEAD_MS`
40
+ before it, so ±50 ms around the attack, early and late alike; measured: clips on their audio 42–88 %, the wrong
41
+ audio 0–20 %). The song map is unusable for a
42
+ part when it failed, is missing, or is implausible (`map_implausible`: it puts more than max(2, 1 %) of the notes
43
+ over half a beat before the audio's start or after its end). Then, per part:
44
+ - map usable, position failing: the map path below, unchanged;
45
+ - map usable, position passing: the note-by-note pass from both (the map's and the notes' own placement), each
46
+ judged by validation (`pipeline.choose_basis`): a basis whose validated result is "original" has no result;
47
+ with one result, that one is kept; with two, the map's only when it finds more attacks (`validate.measure`
48
+ hits) than the notes' own by more than validation's counting slack (5 % of the notes), else the notes' own
49
+ (basis "identity"); with none, nothing changes. But when the map would move the part over half a beat without
50
+ verdict OK and its evidence says the MIDI sits far off (the map path's arbiter below), nothing changes (flag
51
+ `far_off`);
52
+ - map unusable, position passing: local mode, the pass and the uniform candidate from where the notes are,
53
+ judged as under a confident fit (flag `own_placement`; confidence medium); when validation finds nothing
54
+ better, the clip is left as it was with a neutral reason (flag `no_better_fit`), not the hold text;
55
+ - neither: the clip is held (basis "none", flag `no_fit_no_placement`: move the clip onto its audio, or check
56
+ it's the right audio, and run it again).
57
+ The pad goes through `ClipTime` both ways on every path. Limits: a part displaced onto other attacks of its own
58
+ stem (a dense or repeating part a beat off) passes its check, and with the map unusable it is tightened in place
59
+ and stays off (accepted: no onset check can tell).
60
+ Reported only, gating nothing: the clip's onset score against the same score with every note moved by ±0.7,
61
+ ±1.3, ±1.9 s, as a z (`validate.placement_z`: the best mean flux-envelope value at the notes, 5 ms steps, within
62
+ ±40 ms of where the envelope peaks for a note on its attack, `FLUX_LEAD_MS`; a drum part's on its kick and snare
63
+ bands' attack envelopes, `validate.drum_placement_z`, `BAND_LEAD_MS`, `PLACEMENT_BANDS`). It was the gate until
64
+ 2026-11-26 and was dropped (the author, "A"): offsets fixed in seconds land on a musical grid at some tempo (these
65
+ within 20–40 ms of the 16ths near 120–125 BPM, ±1.9 s within 40 ms of four beats near 123–130 BPM), so clips
66
+ that sat on their audio scored low (House2 drums 1.0, Afro drums 1.75 with 90 % of their notes on an attack),
67
+ each tweak (drum bands, a centred window) moved the failure elsewhere, and drum MIDI over a chords stem on its
68
+ grid scored 3.3. The tool reports per part `basis`, `placement_on_attack` and `map_implausible`; the pipeline's
69
+ stats also `placement_real` (passed), `placement_z`, `placement_z_from` ("flux", or the drum band) and, for
70
+ drums, `placement_z_bands` (diagnostics; not in the tool's report, as they would mislead a reader).
71
+ - `fit`: the near search first (the MIDI was made in place: offset ±2 bars, scale ±3 % around 1, ½, 2), his full
72
+ search only when that is weak (`NEAR_*`, `FULL_GAIN`); three guards against luck and false drift (`LUCK`,
73
+ `DRIFT_HOLDOUT`, `MIN_BETTER_FRAC`).
74
+ - `pipeline`: on the map path, when the map would move a part by more than half a beat without verdict OK, the
75
+ note-by-note pass runs from the map's placement and from the MIDI's own, and the share of note groups that find an attack decides
76
+ (`PLACED_CONF`, `FULL_GAIN`): the identity basis (a repeating-material tie, or one instrument of a full stem
77
+ that misleads the map), "far" (the MIDI sits N beats from where the audio plays it: nothing changes, flag
78
+ `far_off`), or "unsure" (neither: nothing changes, flag `placement_unsure`); a fit that fails on its z alone
79
+ with a strength and margin far above luck is "too loose", not "wrong audio" (`LOOSE_STRENGTH`); "doesn't span
80
+ the audio" is measured against what the audio clip plays (`Part.span`); the
81
+ uniform correction measured as the onset detector's lag over drum and single-voice notes (`correction`,
82
+ `FIXBIAS` when fewer than 8); the uniform candidate as the part's own map-free flux shift (`FLUX_MIN`,
83
+ `FLUX_MAX`, `FLUX_AGREE`).
84
+ - `pitched.reanchor`: his per-pitch envelope finds clean attacks early by a constant per window (10–18 ms at
85
+ 1024, 34–42 ms at 2048/4096); per window class it is replaced by the run's detector lag.
86
+ - `drums`: notes without a confident attack follow the part's own shift (map-free); lengths never pass the next
87
+ note on the same key (also in `pitched`, with same-key spacing).
88
+ - `validate`: the rule in its module doc (onset / uniform / original; "no worse" within 5 % of the notes; a move
89
+ over half a beat needs verdict OK and a clear gain).
90
+
91
+ ## The time model (`timemap.ClipTime`)
92
+
93
+ song beat → clip beat (`start_time`, `start_marker`) → Live seconds in the file (warp markers when warped,
94
+ else the start marker and the tempo) → analysis seconds = Live seconds − pad. Every result goes back the same way.
95
+
96
+ - **Warp marker unit, verified on Live 12.4.16 (2026-11-26, read-only):** a marker's `sample` is **seconds** into
97
+ the file; `Clip.beat_to_sample_time` is **samples**. Two warped MP3 clips in the author's test set
98
+ (one with 2 markers; one with 3, one of them at a negative beat): the markers' piecewise-linear value at the
99
+ start and end markers × 44100 equals `beat_to_sample_time` there (ratio 44100.000, also extrapolated past the last
100
+ marker). `timemap.WARP_SAMPLE_SECONDS = 1.0` stays.
101
+ - **MP3 pad** (`livepad`): Live plays an MP3 with its encoder delay, the decoder's 529 samples and the Info frame;
102
+ ffmpeg and soundfile drop them. The header decides, not the name:
103
+ - the verified kind, MPEG-1 Layer III at 44.1 kHz with an Info/Xing frame (and LAME delay 576 when tagged):
104
+ 2257 / 44100 s (his measurement with Live's Crop);
105
+ - any other MP3: LAME delay + 529 + one frame (1152 MPEG-1, 576 MPEG-2/2.5) from its LAME tag (LAME/Lavc/Lavf), or
106
+ 0 without one, and the tool flags "this MP3's timing in Live isn't verified; check it by ear";
107
+ - not MPEG audio (an M4A named .mp3 has an `ftyp` box; WAV, AIFF, FLAC, OGG): 0. `decode` sends MP4 containers
108
+ to afconvert whatever their name (soundfile's MP3 decoder would resync through them and return noise).
109
+
110
+ ## The tool (`tools/align.py`)
111
+
112
+ 1. Reads (existing ops only): `song.info`; `lom.get song.master_track.mixer_device.song_tempo automation_state`;
113
+ the MIDI clip (`clip.info`, `notes.get` with ids), its track (`track.info` devices: a DrumGroupDevice and its
114
+ pads' names); the audio track (`track.info` clips): the arrangement clip with the largest overlap with the MIDI
115
+ clip, then its `clip.info` with warp markers and its file.
116
+ 2. Refuses with a plain reason: a Session View clip; tempo automation anywhere (Live says only whether, not where);
117
+ a looping audio clip that repeats under the MIDI, or a looping MIDI clip that repeats (both: the arrangement is
118
+ longer than loop end − start marker, where playback wraps); not a MIDI clip; not an audio track; no audio clip
119
+ under the MIDI clip; a missing file; duplicate note ids. A MIDI clip named as {"track", "beat"} is the one that
120
+ starts at that beat to 3 decimals (the picker's request), else the one playing there.
121
+ 3. Notes outside the part of the clip that plays are left alone (flag `outside_clip`); the rest go in, in song
122
+ beats, in his `midi_notes` order (start, length, pitch, velocity).
123
+ 4. Analysis in the server process (`pipeline.align_pairs`), in a worker thread, with progress every second.
124
+ 5. A note that would start before the clip's start or after its end is held at that edge (`held_at_edge`; an
125
+ arrangement clip can't grow earlier in place). The whole clip is refused instead — nothing written, reported as
126
+ a dry run would report it plus `refused` — when its result moves any note by more than half a beat, or pushes
127
+ more than max(2, 1 % of its notes) past one edge: "move or extend the clip first".
128
+ 6. Backup first: `./exports/backups/<clip name> <YYYY-MM-DD HHMMSS>.mid` when `./exports` exists in the working
129
+ folder (the set's folder when the app runs it), else `~/Documents/Audial/MIDI backups/`; written as
130
+ `export_midi` writes a clip, but with its muted notes too (the tool can move them).
131
+ 7. All changes in one round trip (one `notes.modify` per clip, in one batch; the app's turn closes after 30 s
132
+ without a write), then one read back: if Live merged notes (his FIXBIAS lengths can overlap a same-key note
133
+ under 25 ms away), the count changed and the part says so (`notes_merged`).
134
+
135
+ ## Bringing in the author's update
136
+
137
+ 1. Replace `reference/alignment/` with his new files (keep `REFERENCE.md`, update its date).
138
+ 2. Port the diff into the module of the same name (table above); keep `mode="fit2"` his exactly.
139
+ 3. `uv run --frozen pytest -q` (the C-parity tests compile his C at test time) and `scripts/align_parity.py` on his
140
+ songs; update the numbers below.
141
+
142
+ ## Parity on the author's House2 test song (2026-11-26, `scripts/align_parity.py`)
143
+
144
+ Material: the author's House2 test song, drums + six parts (guitar, two synths, a pad, bass, vocals) on four MP3 stems
145
+ (44.1 kHz, LAME-tagged, 6.5 min). Run: `uv run --frozen python scripts/align_parity.py --samples <his project's Samples
146
+ folder> --midi <his .mid files> --exports <his session's exports>` (137 s).
147
+ His set: tempo 122.00013732910156, MP3 pad 2257/44100. Times compared in analysis seconds; his outputs are 960-ppq
148
+ ticks (0.51 ms at 122 BPM), so ±0.26 ms is his rounding. Fresh runs of his scripts reproduce his saved aligned
149
+ outputs exactly, every part.
150
+
151
+ **Decoders** (port vs `ffmpeg -ac 1 -ar 20000`): the drum stem (MP3) same length (7,816,302 samples at 20 kHz), lag 0,
152
+ max |diff| 4e-6; an M4A from the same set (afconvert) lag 0, max |diff| 1e-6, 36 samples shorter at the end
153
+ (afconvert's AAC tail).
154
+
155
+ **Song map** (`fit2.py` vs `fit_song(mode="fit2")`, seven parts jointly, weights from songs.json):
156
+
157
+ | | spb | offset | z | margin | drift |
158
+ |---|---|---|---|---|---|
159
+ | his fit2.py | 0.4651117 | 0.127 | 10.1 | 1.37 | no |
160
+ | port, his frame (x = his beats) | 0.4651117 | 0.12700 | 10.1 | 1.37 | no |
161
+ | port through the pipeline (clip at 129 BPM) | 0.4651118 | 0.12700 | 10.1 | 1.37 | no |
162
+
163
+ Every part's dt, z, margin and verdict equal his (drums/guitar/pad/bass/vocals check, Synth 1 OK, Synth 2 fail).
164
+ Map difference over each part's onsets: 0.0 ms in his frame, ≤ 0.054 ms through the pipeline.
165
+ Fixed on the way: fit2 takes his audio length, the envelope's (frames × 5 ms = 390.815 s), not the file's
166
+ (390.8151 s). It sets his coarse spb grid; the file's length moved spb by 1e-7, the DP's last units by up to 0.25 s,
167
+ and his drift rule then counted a second "better" window (352 s: warp 0.714 vs threshold 0.697; his 0.650), drift on.
168
+ `pipeline._fit` passes `len(flux) × HS` in fit2 mode (test `test_fit2_audio_length_is_his_envelopes`).
169
+
170
+ **Note by note, mode="fit2"** (port vs his scripts on the same inputs; drums from his drum clip as it was before his pass, with
171
+ PAD 0, as he ran it before the pad was known). "his map": the port's passes fed his SPB/OFF/DT; "port": end to
172
+ end with the port's own map. Starts: median / p90 / max |difference| in ms; L = median length ratio.
173
+
174
+ | Part | method port / his | onset cand., his map | uniform cand., his map | winner (port map) vs his saved | L |
175
+ |---|---|---|---|---|---|
176
+ | Guitar | uniform / uniform | 70/70 ticks equal | 70/70 | 0.13 / 0.23 / 0.28 | 1.00 |
177
+ | Synth 1 | onset / onset | 1120/1120 | 1120/1120 | 0.13 / 0.23 / 0.26 | 1.00 |
178
+ | Synth Pad | uniform / uniform | 318/318 | 318/318 | 0.13 / 0.25 / 0.29 | 1.00 |
179
+ | Synth 2 | **original** / onset | 51/51 | 51/51 | (kept: verdict fail) | — |
180
+ | Bass (single voice) | uniform / uniform | 692/694 (2 notes 26.6 ms) | 694/694 | 0.13 / 0.24 / 0.30 | 1.00 |
181
+ | Vocals | uniform / uniform | 320/320 | 320/320 | 0.13 / 0.24 / 0.28 | 1.00 |
182
+ | Drums | onset / onset | 2608/2614 (max 1.96 ms) | — | 0.14 / 0.23 / 1.96 | 1.00 |
183
+
184
+ Tolerance (p90 ≤ 3 ms note by note, ≤ 2 ms uniform, length ratio within 5 %): met on every part. Methods: 6 of 7.
185
+ The miss, Synth 2: his own fit2 gave it verdict fail (z 1.4, margin 0.47) and he ran the note-by-note pass anyway;
186
+ validation's rule 1 keeps the original timing on a fail. The port's onset candidate for it is his output tick for
187
+ tick, so only that rule stands between them. Drum part bias and moved count equal his (14.6 ms, 2388).
188
+
189
+ **Product mode** (the tool's frame: stems un-warped at beat 64, real pad; the MIDI "made in place": his map applied,
190
+ drums moved by the pad into Live time). Signed median vs his saved outputs (+ = later than his):
191
+
192
+ | Part | joint (7 pairs): method, vs his | one pair at a time: method, vs his |
193
+ |---|---|---|
194
+ | Drums | onset, +0.03 ms (p90 0.23) | onset, +0.03 ms (p90 0.23) |
195
+ | Guitar | uniform, −0.08 ms | uniform, +0.32 ms |
196
+ | Synth 1 | onset, **+15.4 ms** (p90 15.7), lengths ×0.88 | onset, **+15.7 ms** (p90 24.5), lengths ×0.88 |
197
+ | Synth Pad | uniform, −0.77 ms | **original**: its fit alone wanted a ~100 s move, refused |
198
+ | Synth 2 | original (verdict fail) | original (verdict fail) |
199
+ | Bass | uniform, +1.4 ms (correction 14.2 ms, measured) | uniform, **−3.6 ms** (its own detector lag 9.2 ms) |
200
+ | Vocals | uniform, −0.37 ms | **original**: its fit alone moved it 3.5 s, refused |
201
+
202
+ - Synth 1 sits ~15 ms later than his: the product's re-anchoring takes out his per-pitch envelope's early lag
203
+ (ruling 2026-11-26); his note-to-note timing stays (p90 of the difference 15.7 ms jointly). Lengths are measured
204
+ ends, so they shorten by that shift. Which is right is an ear check.
205
+ - Bass alone measures its own detector lag (9.2 ms) instead of his 14.6 ms, so it lands 3.6 ms earlier than his.
206
+ - Vocals alone: its near fit was weak, the full search found a placement 3.5 s away (a repeated phrase); validation
207
+ refused the move (safe), but the part then keeps its timing instead of getting his 14.6 ms correction.
208
+ - Joint with the drums 51 ms early, as his set had them before the pad was known: the drums still go note by note,
209
+ but only 72 % of groups found their attack and p90 vs his is 33.9 ms; Synth 1's p90 grows to 64.9 ms. Parts of one
210
+ run should share one placement.
211
+ - Local mode (2026-11-26) changes none of these timings (the script before and after: decoders, song map and
212
+ every fit2 number identical; product starts and lengths identical). Placement z of the parts as made in place:
213
+ guitar 6.9 and pad 4.1 (real: the pass ran from both bases, a tie, so the notes' own was kept, same result);
214
+ drums 1.0, Synth 1 1.7, bass 1.2, vocals 0.9, Synth 2 −1.0 (not real: the map path). Synth 2 (fit fail) now
215
+ reports `no_fit_no_placement`. Dense 16th-note parts near 120–125 BPM score low because the ±0.7 s (and at
216
+ 120 BPM ±1.9 s) wrong offsets land within 40 ms of their own 16th grid, so local mode can't confirm them.
217
+ - Drum bands and the centred window (2026-11-26, later the same day): again decoders, song map and every fit2
218
+ number identical, and every product method and timing the same except the drums: judged on their bands they are
219
+ real (kick band z 3.1; snare 1.9, hats 2.0, flux 1.2), so the pass ran from both bases (a tie, the notes' own
220
+ kept) and the largest difference from his saved drums fell from 37 ms to 2 ms. Centred, pad 4.1 → 6.1, guitar
221
+ 6.9 → 6.6; the rest stay under 2.5. Limits: four-on-the-floor kicks at ~123–130 BPM can't be confirmed either
222
+ (±1.9 s is within 40 ms of four beats there), and the centred window is the old score taken 18 ms earlier, so a
223
+ clip that sits ~30 ms early could fall under the z gate (2.5) where it used to pass (the window moves onto the
224
+ grid's late side).
225
+ - The on-attack gate (2026-11-26, last): decoders, song map and every fit2 number identical again. Synth 1, bass
226
+ and vocals (on-attack 80 / 81 / 56 %; z 1.6 / 1.4 / 1.1) now pass their check, so both bases run: bass and vocals
227
+ tie (same timing); Synth 1 alone and in the drums-early run keeps the notes' own placement (p90 vs his 24.5 → 16.1
228
+ and 64.9 → 15.8 ms, as jointly); vocals alone, whose own fit wanted 3.5 s, now gets his uniform +14.6 ms (p90 vs
229
+ his 0.2 ms) instead of keeping its timing. The drums 51 ms early pass too (47 %), and the map's result is kept.
230
+ Synth 2 (22 %, fit fail) is still held.
231
+
232
+ **Read-only check of the tool's read path on the real set** (`Live(client="audial-check")`, dry run, nothing
233
+ written; his current clips, already aligned by him): the drums → original ("correction under 3 ms", fit OK
234
+ z 10.0); Bass → uniform −3.5 ms (its 9.2 ms lag vs his 14.6); Synth 1 → uniform +17.3 ms (his envelope's lag). The
235
+ stems read as un-warped MP3 clips at beat 64, pad 51.179 ms verified, tempo automation off.
@@ -0,0 +1,5 @@
1
+ """Align MIDI to audio: a numpy port of the author's alignment method (reference/alignment, kept verbatim beside the package).
2
+
3
+ One module per file of his: dsp (core.c, bandenv.c, pitchenv.c, xc.c and his ffmpeg band filters), decode (his
4
+ `ffmpeg -ac 1 -ar 20000` step), livepad (livepad.py). METHOD.md maps every one of his steps to its module.
5
+ """
@@ -0,0 +1,98 @@
1
+ """Audio file → the analysis signal: mono float32 at 20 kHz, the same samples as his
2
+ `ffmpeg -i FILE -ac 1 -ar 20000 -f f32le` (ffmpeg's stereo downmix and its default swr resampler, `dsp.resample`), so
3
+ his envelopes and Live's pad constants carry over unchanged. `load_native` stops before the resampling, for his
4
+ filtered envelopes (`ffmpeg -af <chain> -ac 1 -ar 20000`, see `dsp.band_signal`).
5
+
6
+ soundfile reads WAV/AIFF/FLAC/OGG/MP3 (its MP3 decode matches ffmpeg's sample for sample); macOS `afconvert`
7
+ decodes M4A/AAC/MP4, and anything soundfile can't read, to a temporary WAV. The container decides, not the name: an
8
+ M4A named .mp3 (an `ftyp` box) goes to afconvert (soundfile's MP3 decoder would resync through it and return noise).
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import shutil
13
+ import subprocess
14
+ import tempfile
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+ import soundfile as sf
19
+
20
+ from .dsp import SR, downmix, resample
21
+
22
+ AFCONVERT = "/usr/bin/afconvert"
23
+ AFCONVERT_TYPES = (".m4a", ".mp4", ".aac")
24
+ # The sample format ffmpeg's decoder hands its filters, by soundfile subtype: integer PCM takes ffmpeg's integer filter
25
+ # path (each stage's output truncated and clipped to that grid, see dsp.band_filter); everything else is float.
26
+ FFMPEG_FMT = {"PCM_S8": "s16", "PCM_U8": "s16", "PCM_16": "s16", "ULAW": "s16", "ALAW": "s16", "ALAC_16": "s16",
27
+ "PCM_24": "s32", "PCM_32": "s32", "ALAC_20": "s32", "ALAC_24": "s32", "ALAC_32": "s32",
28
+ "DOUBLE": "dbl"}
29
+
30
+
31
+ def load(path: str) -> tuple[np.ndarray, float]:
32
+ """Decode `path` to mono float32 at 20 kHz; returns (signal, the file's own sample rate)."""
33
+ mono, sr, _ = _read(Path(path), mono=True)
34
+ return resample(mono, sr, SR), float(sr)
35
+
36
+
37
+ def load_native(path: str) -> tuple[np.ndarray, int, str]:
38
+ """Decode `path` at the file's own rate, channels kept: returns ((frames, channels) float32, sample rate, ffmpeg's
39
+ sample format "s16" | "s32" | "flt" | "dbl"). For his filtered envelopes, `dsp.band_signal(x, sr, chain, fmt)`."""
40
+ return _read(Path(path), mono=False)
41
+
42
+
43
+ def _read(p: Path, mono: bool) -> tuple[np.ndarray, int, str]:
44
+ if not p.is_file():
45
+ raise ValueError(f"can't read {p.name}")
46
+ if p.suffix.lower() not in AFCONVERT_TYPES and not _is_mp4(p):
47
+ try:
48
+ return _read_sf(p, mono)
49
+ except (RuntimeError, OSError, ValueError, TypeError):
50
+ pass
51
+ got = _afconvert(p, mono)
52
+ if got is None:
53
+ raise ValueError(f"can't read {p.name}")
54
+ return got
55
+
56
+
57
+ def _is_mp4(p: Path) -> bool:
58
+ """An MP4/M4A container (its first box is `ftyp`), whatever the file is called."""
59
+ try:
60
+ with open(p, "rb") as f:
61
+ return f.read(8)[4:8] == b"ftyp"
62
+ except OSError:
63
+ return False
64
+
65
+
66
+ def _read_sf(p: Path, mono: bool) -> tuple[np.ndarray, int, str]:
67
+ """soundfile decode in blocks; with `mono`, downmixed block by block (a long stereo file never sits in memory whole)."""
68
+ with sf.SoundFile(str(p)) as f:
69
+ sr, fmt, ch = int(f.samplerate), FFMPEG_FMT.get(f.subtype, "flt"), f.channels
70
+ shape = (lambda k: (k,)) if mono else (lambda k: (k, ch))
71
+ out, i = np.empty(shape(max(f.frames, 0)), np.float32), 0
72
+ for b in f.blocks(blocksize=1 << 18, dtype="float32", always_2d=True):
73
+ m = downmix(b) if mono else b
74
+ if i + len(m) > len(out): # the header undercounted (possible for compressed files)
75
+ out = np.concatenate([out[:i], np.empty(shape(max(len(out), len(m))), np.float32)])
76
+ out[i:i + len(m)] = m
77
+ i += len(m)
78
+ return out[:i], sr, fmt
79
+
80
+
81
+ def _afconvert(p: Path, mono: bool) -> tuple[np.ndarray, int, str] | None:
82
+ """AAC & co. → a temporary float WAV (ffmpeg's AAC decoder is float too)."""
83
+ exe = AFCONVERT if Path(AFCONVERT).exists() else shutil.which("afconvert")
84
+ if not exe:
85
+ return None
86
+ with tempfile.TemporaryDirectory(prefix="audial-align-") as d:
87
+ out = Path(d) / "decoded.wav"
88
+ src = p
89
+ try:
90
+ if _is_mp4(p) and p.suffix.lower() not in AFCONVERT_TYPES: # afconvert goes by the name: give it .m4a
91
+ src = Path(d) / "source.m4a"
92
+ src.symlink_to(p.resolve())
93
+ r = subprocess.run([exe, "-f", "WAVE", "-d", "LEF32", str(src), str(out)], capture_output=True, timeout=600)
94
+ if r.returncode != 0 or not out.is_file():
95
+ return None
96
+ return _read_sf(out, mono)
97
+ except (OSError, RuntimeError, ValueError, subprocess.SubprocessError):
98
+ return None
@@ -0,0 +1,154 @@
1
+ """Per-note drum pass: the author's refine_drums.py (reference/alignment/src) on his band envelopes (dsp.band_env, 1 ms hop).
2
+
3
+ Every note is kept (same pitch, velocity, count); only start and length change. His steps, in his order:
4
+ 1. a part bias: the median offset of the confident attacks (rise > 8 dB) within ±60 ms of each note's prediction;
5
+ 2. each note to its sharpest attack (the half-rise point) within ±35 ms of prediction + bias, when it rises > 6 dB;
6
+ otherwise prediction + bias;
7
+ 3. same-key notes kept in order and at least 20 ms apart;
8
+ 4. lengths: until the band falls 15 dB below the hit's peak (at most 2 s), capped 5 ms before the next hit on the
9
+ same key, at least 30 ms.
10
+
11
+ His script read the notes at a fixed tempo (t = beat·60/122) with no song map; here `pred` is each note's predicted
12
+ analysis time (the song map plus the part's shift, see pipeline.py), so the tempo comes from the inputs.
13
+ Additions of mine (product only; mode="fit2" is his script exactly, for parity): a length never runs past the next
14
+ note on the same key (his 30 ms floor could, when two hits on one key are 20–35 ms apart); and, given `anchor` (the
15
+ notes' current times), a note without a confident attack goes to its current time + the part's own measured shift
16
+ (the median of attack − current time over the notes on attacks) instead of prediction + bias, so a song map that is
17
+ a little off (a tilt over the song) doesn't carry into those notes (controller ruling).
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import statistics as stt
22
+
23
+ import numpy as np
24
+
25
+ HOP = 0.001 # bandenv: 1 ms per frame
26
+ WIDE, NEAR = 0.06, 0.035 # pass 1 / pass 2 search: ± s around the prediction (pass 2: + bias)
27
+ RISE_BIAS, RISE = 8.0, 6.0 # dB: a confident attack for the bias (>), for a note (>)
28
+ SPACING = 0.02 # s: same-key notes at least 20 ms apart
29
+ END_DB = 15.0 # a hit ends when its band falls 15 dB below its peak
30
+ PEAK_FRAMES = 20 # the hit's peak: max over its first 20 ms (and the length search starts there)
31
+ MAX_FRAMES = 2000 # lengths at most 2 s
32
+ GAP = 0.005 # s: a length stops 5 ms before the next hit on the same key
33
+ MIN_LEN = 0.03 # s
34
+
35
+
36
+ def rises(e: np.ndarray) -> np.ndarray:
37
+ """His rise at every frame i: mean(e[i+2..i+4]) − mean(e[i−4..i−2]) in his float arithmetic (−inf where it isn't
38
+ defined)."""
39
+ e = np.asarray(e, dtype=np.float64)
40
+ r = np.full(len(e), -np.inf)
41
+ if len(e) >= 9:
42
+ a = (e[6:-2] + e[7:-1]) + e[8:]
43
+ b = (e[:-8] + e[1:-7]) + e[2:-6]
44
+ r[4:-4] = a / 3 - b / 3
45
+ return r
46
+
47
+
48
+ def onset(e: np.ndarray, r: np.ndarray, t: float, rng: float) -> tuple[float | None, float]:
49
+ """His onset(): the sharpest log-energy rise within ±rng of t (s) — (time of its half-rise point, rise dB), or
50
+ (None, 0) when the window is empty. `r` = rises(e)."""
51
+ i0, i1 = max(6, int((t - rng) * 1000)), min(len(e) - 7, int((t + rng) * 1000))
52
+ if i1 <= i0:
53
+ return None, 0.0
54
+ bi = i0 + int(np.argmax(r[i0:i1])) # first maximum, as his `r > best`
55
+ best = float(r[bi])
56
+ lo = (float(e[bi - 4]) + float(e[bi - 3]) + float(e[bi - 2])) / 3
57
+ hi = float(np.max(e[bi:bi + 15]))
58
+ thr = lo + 0.5 * (hi - lo)
59
+ below = np.asarray(e[bi - 4:bi + 10], dtype=np.float64) < thr
60
+ j = bi - 4 + (int(np.argmin(below)) if not below.all() else len(below))
61
+ return j / 1000, best
62
+
63
+
64
+ def _length(e: np.ndarray, t: float) -> float:
65
+ """His length: from the hit until its band falls END_DB below the peak of its first 20 ms (≤ 2 s)."""
66
+ n = len(e)
67
+ i = min(max(int(t * 1000), 0), max(n - 1, 0))
68
+ pk = float(np.max(e[i:i + PEAK_FRAMES])) if i + PEAK_FRAMES < n else -99.0
69
+ j0, j1 = i + PEAK_FRAMES, min(n - 1, i + MAX_FRAMES) # his loop: j from i + 20 while j < len − 1 and j − i < 2000
70
+ stop = np.flatnonzero(np.asarray(e[j0:j1], dtype=np.float64) <= pk - END_DB) if j1 > j0 else []
71
+ j = j0 + int(stop[0]) if len(stop) else max(j0, j1)
72
+ return (j - i) / 1000
73
+
74
+
75
+ def refine(pred: np.ndarray, durs_s: np.ndarray, pitches: list[int], bands: dict[str, np.ndarray],
76
+ band_of: dict[int, str], mode: str = "product", anchor: np.ndarray | None = None
77
+ ) -> tuple[list[tuple[float, float, str]], dict]:
78
+ """pred: each note's predicted analysis time (s); durs_s: its current length (s, for the stats); pitches: its MIDI
79
+ pitch; bands: band name -> band envelope (1 ms hop); band_of: pitch -> band name (kind.drum_band).
80
+ anchor (product): the notes' current times (s), for the unconfident notes (module doc).
81
+ Returns (t, length, how) per note, in input order — how "onset" (on its own attack) or "uniform" (prediction +
82
+ the part's bias; with anchor, current time + the part's shift) — and the stats: bias (s), confident (pass-1
83
+ attacks), total, moved, kept, fallback_shift_ms, groups_confident (moved / total), spaced (notes pushed to keep
84
+ 20 ms on a key), move_ms, length_s."""
85
+ if mode not in ("product", "fit2"):
86
+ raise ValueError(f"unknown mode {mode!r}")
87
+ pred = np.asarray(pred, dtype=np.float64)
88
+ n = len(pred)
89
+ E = {p: bands[band_of[p]] for p in set(pitches)}
90
+ R = {b: rises(bands[b]) for b in set(band_of[p] for p in set(pitches))}
91
+
92
+ def hit(p: int, t: float, rng: float):
93
+ b = band_of[p]
94
+ return onset(bands[b], R[b], t, rng)
95
+
96
+ # pass 1: residuals at the prediction, wide search, confident only
97
+ res = []
98
+ for k in range(n):
99
+ t = float(pred[k])
100
+ o, r = hit(pitches[k], t, WIDE)
101
+ if o is not None and r > RISE_BIAS:
102
+ res.append((o - t) * 1000)
103
+ bias = stt.median(res) if res else 0.0
104
+ # pass 2: per note, ±35 ms around prediction + bias
105
+ t_new, how, dev = [], [], []
106
+ for k in range(n):
107
+ t = float(pred[k]) + bias / 1000
108
+ o, r = hit(pitches[k], t, NEAR)
109
+ if o is not None and r > RISE:
110
+ dev.append((o - t) * 1000)
111
+ t = o
112
+ how.append("onset")
113
+ else:
114
+ how.append("uniform")
115
+ t_new.append(t)
116
+ shift = None
117
+ if anchor is not None and mode == "product": # mine: unconfident notes at current time + the part's own shift
118
+ a = np.asarray(anchor, dtype=np.float64)
119
+ on = [k for k in range(n) if how[k] == "onset"]
120
+ if on:
121
+ shift = stt.median(t_new[k] - float(a[k]) for k in on)
122
+ for k in range(n):
123
+ if how[k] != "onset":
124
+ t_new[k] = float(a[k]) + shift
125
+ # same-pitch collisions: keep order, at least 20 ms apart
126
+ by: dict[int, list[int]] = {}
127
+ for k in sorted(range(n), key=lambda k: (t_new[k], float(durs_s[k]), k)):
128
+ by.setdefault(pitches[k], []).append(k)
129
+ spaced = 0
130
+ for ks in by.values():
131
+ for a, c in zip(ks, ks[1:]):
132
+ if t_new[c] - t_new[a] < SPACING:
133
+ t_new[c] = t_new[a] + SPACING
134
+ spaced += 1
135
+ # lengths: until the band falls 15 dB below the hit's peak, before the next hit on the same key, 30 ms min
136
+ lens = [0.0] * n
137
+ for p, ks in by.items():
138
+ for i, k in enumerate(ks):
139
+ L = _length(E[p], t_new[k])
140
+ nxt = t_new[ks[i + 1]] - t_new[k] - GAP if i + 1 < len(ks) else L
141
+ L = max(MIN_LEN, min(L, nxt))
142
+ if i + 1 < len(ks) and mode == "product":
143
+ L = min(L, nxt) # mine: never past the next note on the same key
144
+ lens[k] = L
145
+ moved = how.count("onset")
146
+ ad = sorted(abs(x) for x in dev)
147
+ stats = dict(kind="drums", bias=bias / 1000, confident=len(res), total=n, moved=moved, kept=n - moved,
148
+ fallback_shift_ms=round(shift * 1000, 2) if shift is not None else None,
149
+ groups_confident=moved / n if n else 0.0, spaced=spaced,
150
+ move_ms=dict(median_abs=round(stt.median(ad), 1) if ad else None,
151
+ p90=round(ad[int(0.9 * len(ad))], 1) if ad else None),
152
+ length_s=dict(median=round(stt.median(lens), 3) if lens else None,
153
+ old_median=round(float(np.median(durs_s)), 3) if n else None))
154
+ return [(t_new[k], lens[k], how[k]) for k in range(n)], stats