uppercut-chiptune-synth 1.0.0__tar.gz

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.
@@ -0,0 +1,16 @@
1
+ node_modules/
2
+ dist/
3
+ dist-pack/
4
+ *.tgz
5
+ coverage/
6
+ build/
7
+ build-*/
8
+ *.tar.gz
9
+ .venv/
10
+ __pycache__/
11
+ *.egg-info/
12
+ .pytest_cache/
13
+ uv.lock
14
+ .DS_Store
15
+ .env*
16
+ *.pem
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Uppercut Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,116 @@
1
+ Metadata-Version: 2.5
2
+ Name: uppercut-chiptune-synth
3
+ Version: 1.0.0
4
+ Summary: Deterministic chiptune and procedural audio for console homebrew: square, triangle and noise voices, envelopes, step sequencing, WAV and raw PCM output.
5
+ Project-URL: Source, https://github.com/uppercut-labs/game-kit/tree/main/packages/uppercut-chiptune-synth
6
+ Author-email: Uppercut Labs <packages@uppercut-labs.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Keywords: chiptune,deterministic,homebrew,pcm,procedural-audio,wav
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Games/Entertainment
19
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Sound Synthesis
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+
24
+ # uppercut-chiptune-synth
25
+
26
+ Deterministic chiptune and procedural audio for console homebrew. It has square (pulse), triangle, saw, sine and bell voices, kick, snare and hat drums, envelopes, a step sequencer that turns a melody, a bass line and chords into a song, seeded noise and seeded pattern variation, and output as a WAV file or as raw PCM at 8 or 16 bits. It uses the Python standard library only, and the same inputs give the same bytes on every platform.
27
+
28
+ It is not [`uppercut-sound-effect-synth`](../uppercut-sound-effect-synth). That package renders 48 kHz, 24-bit stereo sound effects (filtered noise, sweeps, saturation) with NumPy. This one is a tracker-style music and effects engine for small fixed-rate output (22,050 Hz, mono, 8 or 16 bits by default) and needs nothing installed.
29
+
30
+ ## Install
31
+
32
+ ```sh
33
+ pip install uppercut-chiptune-synth
34
+ ```
35
+
36
+ ## Example
37
+
38
+ ```python
39
+ import uppercut_chiptune_synth as ct
40
+
41
+ v = ct.voicing() # "accumulated" (default) or "closed-form"
42
+ melody = ct.expand_pattern([(0, 72, 2), (2, 76, 2), (4, 79, 4)], 64) # (step, midi note, steps long)
43
+ bass = ct.expand_pattern([(s, 36, 2) for s in range(0, 64, 2)], 64)
44
+ song = v.render_song(128.0, 4, melody, bass, [[60, 64, 67], [65, 69, 72]],
45
+ lead_kind="pulse", bass_kind="tri", drum_style="drive", seed=1)
46
+
47
+ ct.write_wav("title.wav", song) # 22,050 Hz mono 16-bit; returns the SHA-256
48
+ raw = ct.pcm_bytes(song, bits=16, byteorder="little") # headerless PCM for a console's own loader
49
+ raw8 = ct.pcm_bytes(song, bits=8) # unsigned 8-bit, 128 is silence
50
+ ```
51
+
52
+ A sound effect is a buffer you fill with notes, sweeps or drums:
53
+
54
+ ```python
55
+ v = ct.voicing("accumulated")
56
+ rng = v.new_rng(42)
57
+ blip = v.arpeggio([72, 79], step_s=0.045, kind="sine")
58
+ fall = v.sweep(0.22, 220.0, 55.0, exp_p=0.5, noise_mix=0.35, decay_rate=12.0, rng=rng)
59
+ ct.write_wav("fall.wav", fall)
60
+ ```
61
+
62
+ ## Two voicings, because the copies it came from disagree
63
+
64
+ The code was written three times for three consoles: two NumPy copies and one standard-library copy. They share the file format and the finishing step, but they sound different, and each shipped. Merging them into one set of constants would have changed shipped audio, so the package keeps both as named voicings and each one reproduces its copies' output byte for byte (see Tests below). Choose one by name, `ct.voicing("closed-form")` or `ct.voicing("accumulated")`, or construct `ClosedForm(rate)` / `Accumulated(rate)` directly.
65
+
66
+ | | closed-form (the two NumPy copies) | accumulated (the stdlib copy, the default) |
67
+ | --- | --- | --- |
68
+ | Oscillator phase | computed from the time since the note began | a running phase, one increment per sample |
69
+ | Envelope | attack 8 ms, decay 60 ms to 0.6, release 30 ms; every ramp includes both end values | attack 8 ms, decay 60 ms to 0.62, release 35 ms; ramps are `k / n` and stop one step short |
70
+ | Bell | `0.65 sin(f) + 0.28 sin(2f + 0.4 sin(3f)) e^(-8t)` from frequency | `0.66 sin(p) + 0.26 sin(p2 + 0.4 sin(p3)) e^(-8t)` from phase |
71
+ | Unknown voice name | sine | pulse |
72
+ | Lead and bass pulse duty | 0.28 and 0.50 in `render_song` | 0.35 |
73
+ | Mix gains (lead, bass) | 0.24, 0.28 | 0.28, 0.25 |
74
+ | Chords | sine pads, 15.5 steps long, once per bar, gain `pad_gain` (0.14) | triangle stabs, 3.6 steps long, every fourth step, gain 0.09 |
75
+ | Pattern shorter than the song | repeats | silent past its end |
76
+ | Drum styles | `drive`, `clock`, `light` | `drive`, `clock`, `hyper`, `light` |
77
+ | Drum voices and gains | own kick, snare, hat and gains | own kick, snare, hat and gains |
78
+ | Noise source | `NumpyCompatRng`, which is `numpy.random.default_rng` without NumPy | `random.Random` |
79
+ | Pitch slide inside a note (`slide_to`) | yes (only one of the two copies had it; kept) | raises `ValueError` |
80
+ | Sweeps | no helper (effects were written as formulas of a time axis: `time_axis`, `cumulative_phase`, `adsr`) | `sweep()` and `env_adsr()` |
81
+
82
+ Where the three copies agree, there is one implementation: 22,050 Hz mono 16-bit output, `midi_to_hz`, `expand_pattern`, the 64-sample edge fade and 0.78 peak limit, the WAV writer, sample counts (`round`), and `arpeggio` (notes 0.16 s long at gain 0.5, one every `step_s`). The two NumPy copies are identical to each other except that one has `slide_to`.
83
+
84
+ The note, drum and effect tables of the games themselves are not here: a song is data you pass to `render_song`.
85
+
86
+ ## Functions
87
+
88
+ | Function | What it does |
89
+ | --- | --- |
90
+ | `voicing(name="accumulated", rate=22050)` | The voicing object. Both have `add_note`, `add_drum`, `render_song`, `arpeggio`, `silence(seconds)` and `new_rng(seed)`. |
91
+ | `v.add_note(buf, start_s, dur_s, midi_note, gain, kind="pulse", duty=0.35, slide_to=None)` | Mixes one note into a list of floats. Kinds: `pulse`, `tri`, `saw`, `sine`, `bell`. |
92
+ | `v.add_drum(buf, start_s, kind, gain, rng)` | `kick`, `snare` or `hat` (the accumulated voicing treats any other name as a hat, the closed-form one ignores it). |
93
+ | `v.render_song(bpm, bars, melody, bass, chords, lead_kind, bass_kind, drum_style, seed)` | A song of 16 steps per bar; the closed-form one also takes `pad_gain`. Returns a list of floats. |
94
+ | `v.arpeggio(notes, step_s, kind)` | A run of short notes. |
95
+ | `Accumulated.sweep(dur_s, f0, f1, exp_p, noise_mix, decay_rate, rng)` | A sine sweep with optional noise and decay. |
96
+ | `ClosedForm.adsr(n, ...)`, `.osc(freq, n, kind, duty)`, `.time_axis(n)`, `.cumulative_phase(freqs)` | The closed-form building blocks for writing an effect as a formula. |
97
+ | `expand_pattern(events, length)`, `midi_to_hz(note)`, `linspace(start, stop, num)` | Pattern table, pitch, and a `numpy.linspace` that gives the same numbers. |
98
+ | `vary_events(events, seed, drop=0.0, octave_up=0.0)` | Seeded variation: drops events and lifts some an octave, the same way for the same seed. |
99
+ | `to_int16(x)`, `pcm_bytes(x, bits=16, byteorder="little")`, `wav_bytes(x, rate, bits)`, `write_wav(path, x, rate, bits)` | Finishing (edge fade, peak limit 0.78), raw PCM and WAV output. `write_wav` returns the SHA-256. |
100
+ | `inspect_wav(data)` | Checks a canonical 44-byte PCM WAV header and returns channels, rate, bits and frames. |
101
+ | `log8_encode(pcm16)`, `log8_decode_table()`, `LOG8_MAGNITUDES` | The sign-magnitude logarithmic 8-bit format used by a PS2-style sample bank. |
102
+ | `NumpyCompatRng(seed)`, `stdlib_rng(seed)` | The two noise sources. |
103
+
104
+ ## Errors
105
+
106
+ | Error | Raised when |
107
+ | --- | --- |
108
+ | `ValueError` | The voicing name is unknown, `rate` is not positive, `bits` is not 8 or 16, `byteorder` is not `little` or `big`, a seed is negative, `slide_to` is used on the accumulated voicing, or a WAV header does not check out. |
109
+
110
+ ## Tests
111
+
112
+ `pytest` runs without NumPy. `tests/golden.json` holds the SHA-256 of what each original script produced for synthetic songs, notes, drums, sweeps and finishing cases (51 in all, 25 of them rendered by more than one copy with identical bytes). `tests/make_goldens.py` rebuilds it from the three scripts' paths and refuses to write it if copies that should agree do not. If NumPy happens to be installed, one more test checks `NumpyCompatRng` against `numpy.random.default_rng`.
113
+
114
+ ## License
115
+
116
+ MIT
@@ -0,0 +1,93 @@
1
+ # uppercut-chiptune-synth
2
+
3
+ Deterministic chiptune and procedural audio for console homebrew. It has square (pulse), triangle, saw, sine and bell voices, kick, snare and hat drums, envelopes, a step sequencer that turns a melody, a bass line and chords into a song, seeded noise and seeded pattern variation, and output as a WAV file or as raw PCM at 8 or 16 bits. It uses the Python standard library only, and the same inputs give the same bytes on every platform.
4
+
5
+ It is not [`uppercut-sound-effect-synth`](../uppercut-sound-effect-synth). That package renders 48 kHz, 24-bit stereo sound effects (filtered noise, sweeps, saturation) with NumPy. This one is a tracker-style music and effects engine for small fixed-rate output (22,050 Hz, mono, 8 or 16 bits by default) and needs nothing installed.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ pip install uppercut-chiptune-synth
11
+ ```
12
+
13
+ ## Example
14
+
15
+ ```python
16
+ import uppercut_chiptune_synth as ct
17
+
18
+ v = ct.voicing() # "accumulated" (default) or "closed-form"
19
+ melody = ct.expand_pattern([(0, 72, 2), (2, 76, 2), (4, 79, 4)], 64) # (step, midi note, steps long)
20
+ bass = ct.expand_pattern([(s, 36, 2) for s in range(0, 64, 2)], 64)
21
+ song = v.render_song(128.0, 4, melody, bass, [[60, 64, 67], [65, 69, 72]],
22
+ lead_kind="pulse", bass_kind="tri", drum_style="drive", seed=1)
23
+
24
+ ct.write_wav("title.wav", song) # 22,050 Hz mono 16-bit; returns the SHA-256
25
+ raw = ct.pcm_bytes(song, bits=16, byteorder="little") # headerless PCM for a console's own loader
26
+ raw8 = ct.pcm_bytes(song, bits=8) # unsigned 8-bit, 128 is silence
27
+ ```
28
+
29
+ A sound effect is a buffer you fill with notes, sweeps or drums:
30
+
31
+ ```python
32
+ v = ct.voicing("accumulated")
33
+ rng = v.new_rng(42)
34
+ blip = v.arpeggio([72, 79], step_s=0.045, kind="sine")
35
+ fall = v.sweep(0.22, 220.0, 55.0, exp_p=0.5, noise_mix=0.35, decay_rate=12.0, rng=rng)
36
+ ct.write_wav("fall.wav", fall)
37
+ ```
38
+
39
+ ## Two voicings, because the copies it came from disagree
40
+
41
+ The code was written three times for three consoles: two NumPy copies and one standard-library copy. They share the file format and the finishing step, but they sound different, and each shipped. Merging them into one set of constants would have changed shipped audio, so the package keeps both as named voicings and each one reproduces its copies' output byte for byte (see Tests below). Choose one by name, `ct.voicing("closed-form")` or `ct.voicing("accumulated")`, or construct `ClosedForm(rate)` / `Accumulated(rate)` directly.
42
+
43
+ | | closed-form (the two NumPy copies) | accumulated (the stdlib copy, the default) |
44
+ | --- | --- | --- |
45
+ | Oscillator phase | computed from the time since the note began | a running phase, one increment per sample |
46
+ | Envelope | attack 8 ms, decay 60 ms to 0.6, release 30 ms; every ramp includes both end values | attack 8 ms, decay 60 ms to 0.62, release 35 ms; ramps are `k / n` and stop one step short |
47
+ | Bell | `0.65 sin(f) + 0.28 sin(2f + 0.4 sin(3f)) e^(-8t)` from frequency | `0.66 sin(p) + 0.26 sin(p2 + 0.4 sin(p3)) e^(-8t)` from phase |
48
+ | Unknown voice name | sine | pulse |
49
+ | Lead and bass pulse duty | 0.28 and 0.50 in `render_song` | 0.35 |
50
+ | Mix gains (lead, bass) | 0.24, 0.28 | 0.28, 0.25 |
51
+ | Chords | sine pads, 15.5 steps long, once per bar, gain `pad_gain` (0.14) | triangle stabs, 3.6 steps long, every fourth step, gain 0.09 |
52
+ | Pattern shorter than the song | repeats | silent past its end |
53
+ | Drum styles | `drive`, `clock`, `light` | `drive`, `clock`, `hyper`, `light` |
54
+ | Drum voices and gains | own kick, snare, hat and gains | own kick, snare, hat and gains |
55
+ | Noise source | `NumpyCompatRng`, which is `numpy.random.default_rng` without NumPy | `random.Random` |
56
+ | Pitch slide inside a note (`slide_to`) | yes (only one of the two copies had it; kept) | raises `ValueError` |
57
+ | Sweeps | no helper (effects were written as formulas of a time axis: `time_axis`, `cumulative_phase`, `adsr`) | `sweep()` and `env_adsr()` |
58
+
59
+ Where the three copies agree, there is one implementation: 22,050 Hz mono 16-bit output, `midi_to_hz`, `expand_pattern`, the 64-sample edge fade and 0.78 peak limit, the WAV writer, sample counts (`round`), and `arpeggio` (notes 0.16 s long at gain 0.5, one every `step_s`). The two NumPy copies are identical to each other except that one has `slide_to`.
60
+
61
+ The note, drum and effect tables of the games themselves are not here: a song is data you pass to `render_song`.
62
+
63
+ ## Functions
64
+
65
+ | Function | What it does |
66
+ | --- | --- |
67
+ | `voicing(name="accumulated", rate=22050)` | The voicing object. Both have `add_note`, `add_drum`, `render_song`, `arpeggio`, `silence(seconds)` and `new_rng(seed)`. |
68
+ | `v.add_note(buf, start_s, dur_s, midi_note, gain, kind="pulse", duty=0.35, slide_to=None)` | Mixes one note into a list of floats. Kinds: `pulse`, `tri`, `saw`, `sine`, `bell`. |
69
+ | `v.add_drum(buf, start_s, kind, gain, rng)` | `kick`, `snare` or `hat` (the accumulated voicing treats any other name as a hat, the closed-form one ignores it). |
70
+ | `v.render_song(bpm, bars, melody, bass, chords, lead_kind, bass_kind, drum_style, seed)` | A song of 16 steps per bar; the closed-form one also takes `pad_gain`. Returns a list of floats. |
71
+ | `v.arpeggio(notes, step_s, kind)` | A run of short notes. |
72
+ | `Accumulated.sweep(dur_s, f0, f1, exp_p, noise_mix, decay_rate, rng)` | A sine sweep with optional noise and decay. |
73
+ | `ClosedForm.adsr(n, ...)`, `.osc(freq, n, kind, duty)`, `.time_axis(n)`, `.cumulative_phase(freqs)` | The closed-form building blocks for writing an effect as a formula. |
74
+ | `expand_pattern(events, length)`, `midi_to_hz(note)`, `linspace(start, stop, num)` | Pattern table, pitch, and a `numpy.linspace` that gives the same numbers. |
75
+ | `vary_events(events, seed, drop=0.0, octave_up=0.0)` | Seeded variation: drops events and lifts some an octave, the same way for the same seed. |
76
+ | `to_int16(x)`, `pcm_bytes(x, bits=16, byteorder="little")`, `wav_bytes(x, rate, bits)`, `write_wav(path, x, rate, bits)` | Finishing (edge fade, peak limit 0.78), raw PCM and WAV output. `write_wav` returns the SHA-256. |
77
+ | `inspect_wav(data)` | Checks a canonical 44-byte PCM WAV header and returns channels, rate, bits and frames. |
78
+ | `log8_encode(pcm16)`, `log8_decode_table()`, `LOG8_MAGNITUDES` | The sign-magnitude logarithmic 8-bit format used by a PS2-style sample bank. |
79
+ | `NumpyCompatRng(seed)`, `stdlib_rng(seed)` | The two noise sources. |
80
+
81
+ ## Errors
82
+
83
+ | Error | Raised when |
84
+ | --- | --- |
85
+ | `ValueError` | The voicing name is unknown, `rate` is not positive, `bits` is not 8 or 16, `byteorder` is not `little` or `big`, a seed is negative, `slide_to` is used on the accumulated voicing, or a WAV header does not check out. |
86
+
87
+ ## Tests
88
+
89
+ `pytest` runs without NumPy. `tests/golden.json` holds the SHA-256 of what each original script produced for synthetic songs, notes, drums, sweeps and finishing cases (51 in all, 25 of them rendered by more than one copy with identical bytes). `tests/make_goldens.py` rebuilds it from the three scripts' paths and refuses to write it if copies that should agree do not. If NumPy happens to be installed, one more test checks `NumpyCompatRng` against `numpy.random.default_rng`.
90
+
91
+ ## License
92
+
93
+ MIT
@@ -0,0 +1,36 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "uppercut-chiptune-synth"
7
+ version = "1.0.0"
8
+ description = "Deterministic chiptune and procedural audio for console homebrew: square, triangle and noise voices, envelopes, step sequencing, WAV and raw PCM output."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [{ name = "Uppercut Labs", email = "packages@uppercut-labs.com" }]
13
+ keywords = ["chiptune", "procedural-audio", "homebrew", "wav", "pcm", "deterministic"]
14
+ dependencies = []
15
+ classifiers = [
16
+ "Development Status :: 5 - Production/Stable",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Topic :: Games/Entertainment",
25
+ "Topic :: Multimedia :: Sound/Audio :: Sound Synthesis",
26
+ "Typing :: Typed",
27
+ ]
28
+
29
+ [project.urls]
30
+ Source = "https://github.com/uppercut-labs/game-kit/tree/main/packages/uppercut-chiptune-synth"
31
+
32
+ [tool.hatch.build.targets.wheel]
33
+ packages = ["src/uppercut_chiptune_synth"]
34
+
35
+ [tool.hatch.build.targets.sdist]
36
+ include = ["src", "tests", "README.md"]
@@ -0,0 +1,51 @@
1
+ """Deterministic chiptune and procedural audio for console homebrew. Standard library only."""
2
+
3
+ from .pcm import (
4
+ LOG8_MAGNITUDES,
5
+ WavInfo,
6
+ inspect_wav,
7
+ log8_decode_table,
8
+ log8_encode,
9
+ pcm_bytes,
10
+ prepare,
11
+ to_int16,
12
+ wav_bytes,
13
+ write_wav,
14
+ )
15
+ from .rng import NumpyCompatRng, seed_sequence_state, stdlib_rng
16
+ from .voicings import (
17
+ DEFAULT_RATE,
18
+ Accumulated,
19
+ ClosedForm,
20
+ expand_pattern,
21
+ linspace,
22
+ midi_to_hz,
23
+ vary_events,
24
+ voicing,
25
+ )
26
+
27
+ __version__ = "1.0.0"
28
+
29
+ __all__ = [
30
+ "Accumulated",
31
+ "ClosedForm",
32
+ "DEFAULT_RATE",
33
+ "LOG8_MAGNITUDES",
34
+ "NumpyCompatRng",
35
+ "WavInfo",
36
+ "expand_pattern",
37
+ "inspect_wav",
38
+ "linspace",
39
+ "log8_decode_table",
40
+ "log8_encode",
41
+ "midi_to_hz",
42
+ "pcm_bytes",
43
+ "prepare",
44
+ "seed_sequence_state",
45
+ "stdlib_rng",
46
+ "to_int16",
47
+ "vary_events",
48
+ "voicing",
49
+ "wav_bytes",
50
+ "write_wav",
51
+ ]
@@ -0,0 +1,170 @@
1
+ """Quantising, raw PCM, WAV files and the PS2-style logarithmic 8-bit bank format."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import array
6
+ import hashlib
7
+ import io
8
+ import os
9
+ import sys
10
+ import wave
11
+ from bisect import bisect_left
12
+ from dataclasses import dataclass
13
+ from typing import Iterable, Sequence
14
+
15
+ DEFAULT_LIMIT = 0.78
16
+ FADE_SAMPLES = 64
17
+
18
+
19
+ def prepare(samples: Sequence[float], limit: float = DEFAULT_LIMIT, fade_edges: bool = True) -> list[float]:
20
+ """Edge fade then peak limit, the finishing step both copies share.
21
+
22
+ With `fade_edges` and more than 128 samples, the first and last 64 samples are
23
+ ramped linearly from 0 to 1. If the peak then exceeds `limit` the whole signal is
24
+ scaled so the peak equals `limit`. The input is not changed.
25
+ """
26
+ x = list(samples)
27
+ n = len(x)
28
+ if fade_edges and n > 2 * FADE_SAMPLES:
29
+ last = FADE_SAMPLES - 1.0
30
+ for i in range(FADE_SAMPLES):
31
+ w = i / last
32
+ x[i] *= w
33
+ x[n - 1 - i] *= w
34
+ peak = max((abs(v) for v in x), default=0.0)
35
+ if peak > limit:
36
+ scale = limit / peak
37
+ x = [v * scale for v in x]
38
+ return x
39
+
40
+
41
+ def to_int16(samples: Sequence[float], limit: float = DEFAULT_LIMIT, fade_edges: bool = True) -> list[int]:
42
+ out = []
43
+ for v in prepare(samples, limit, fade_edges):
44
+ iv = int(round(v * 32767.0))
45
+ out.append(32767 if iv > 32767 else -32768 if iv < -32768 else iv)
46
+ return out
47
+
48
+
49
+ def pcm_bytes(
50
+ samples: Sequence[float],
51
+ bits: int = 16,
52
+ byteorder: str = "little",
53
+ limit: float = DEFAULT_LIMIT,
54
+ fade_edges: bool = True,
55
+ ) -> bytes:
56
+ """Raw mono PCM. 16-bit is signed; 8-bit is unsigned with 128 as zero, as WAV stores it."""
57
+ if bits == 16:
58
+ if byteorder not in ("little", "big"):
59
+ raise ValueError("byteorder must be 'little' or 'big'")
60
+ pcm = array.array("h", to_int16(samples, limit, fade_edges))
61
+ if sys.byteorder != byteorder:
62
+ pcm.byteswap()
63
+ return pcm.tobytes()
64
+ if bits == 8:
65
+ out = bytearray()
66
+ for v in prepare(samples, limit, fade_edges):
67
+ iv = int(round(v * 127.0)) + 128
68
+ out.append(255 if iv > 255 else 0 if iv < 0 else iv)
69
+ return bytes(out)
70
+ raise ValueError("bits must be 8 or 16")
71
+
72
+
73
+ def wav_bytes(
74
+ samples: Sequence[float],
75
+ rate: int = 22050,
76
+ bits: int = 16,
77
+ limit: float = DEFAULT_LIMIT,
78
+ fade_edges: bool = True,
79
+ ) -> bytes:
80
+ """A mono PCM WAV file with the canonical 44-byte header."""
81
+ data = pcm_bytes(samples, bits, "little", limit, fade_edges)
82
+ buf = io.BytesIO()
83
+ with wave.open(buf, "wb") as wf:
84
+ wf.setnchannels(1)
85
+ wf.setsampwidth(bits // 8)
86
+ wf.setframerate(rate)
87
+ wf.writeframes(data)
88
+ return buf.getvalue()
89
+
90
+
91
+ def write_wav(
92
+ path: str,
93
+ samples: Sequence[float],
94
+ rate: int = 22050,
95
+ bits: int = 16,
96
+ limit: float = DEFAULT_LIMIT,
97
+ fade_edges: bool = True,
98
+ ) -> str:
99
+ """Writes the WAV (creating folders) and returns its SHA-256 as hex."""
100
+ data = wav_bytes(samples, rate, bits, limit, fade_edges)
101
+ folder = os.path.dirname(path)
102
+ if folder:
103
+ os.makedirs(folder, exist_ok=True)
104
+ with open(path, "wb") as fh:
105
+ fh.write(data)
106
+ return hashlib.sha256(data).hexdigest()
107
+
108
+
109
+ @dataclass(frozen=True)
110
+ class WavInfo:
111
+ channels: int
112
+ rate: int
113
+ bits: int
114
+ frames: int
115
+
116
+
117
+ def inspect_wav(data: bytes) -> WavInfo:
118
+ """Check a canonical 44-byte PCM header (RIFF, WAVE, 16-byte fmt, data) and return its fields.
119
+
120
+ Raises ValueError when the header is not exactly that layout or the sizes do not add up.
121
+ """
122
+ if len(data) < 44:
123
+ raise ValueError("shorter than the 44-byte header")
124
+ if data[0:4] != b"RIFF" or data[8:12] != b"WAVE":
125
+ raise ValueError("not a RIFF/WAVE file")
126
+ le = lambda a, b: int.from_bytes(data[a:b], "little") # noqa: E731
127
+ if data[12:16] != b"fmt " or le(16, 20) != 16:
128
+ raise ValueError("fmt chunk is not the 16-byte PCM form at offset 12")
129
+ if le(20, 22) != 1:
130
+ raise ValueError("not integer PCM")
131
+ channels, rate, byte_rate, align, bits = le(22, 24), le(24, 28), le(28, 32), le(32, 34), le(34, 36)
132
+ if data[36:40] != b"data":
133
+ raise ValueError("data chunk does not follow fmt at offset 36")
134
+ size = le(40, 44)
135
+ if channels < 1 or bits not in (8, 16, 24, 32):
136
+ raise ValueError("unsupported channel count or bit depth")
137
+ if align != channels * bits // 8 or byte_rate != rate * align:
138
+ raise ValueError("block align or byte rate disagrees with the format")
139
+ if le(4, 8) != 36 + size or len(data) != 44 + size or size % align:
140
+ raise ValueError("chunk sizes disagree with the file length")
141
+ return WavInfo(channels, rate, bits, size // align)
142
+
143
+
144
+ LOG8_MAGNITUDES = tuple(round(32767 * (256 ** (i / 127) - 1) / 255) for i in range(128))
145
+ """The 128 magnitudes of the logarithmic 8-bit format: step i is 32767 * (256**(i/127) - 1) / 255."""
146
+
147
+ _log8_table: bytes | None = None
148
+
149
+
150
+ def _log8_quantize(sample: int) -> int:
151
+ magnitude = min(abs(sample), 32767)
152
+ target = min(bisect_left(LOG8_MAGNITUDES, magnitude), 127)
153
+ if target > 0 and magnitude - LOG8_MAGNITUDES[target - 1] < LOG8_MAGNITUDES[target] - magnitude:
154
+ target -= 1
155
+ return target | (128 if sample < 0 else 0)
156
+
157
+
158
+ def log8_encode(pcm16: Iterable[int]) -> bytes:
159
+ """16-bit samples to sign-magnitude logarithmic bytes (bit 7 is the sign, bits 0-6 the
160
+ nearest `LOG8_MAGNITUDES` step). The 65,536-entry lookup table is built on first use."""
161
+ global _log8_table
162
+ if _log8_table is None:
163
+ _log8_table = bytes(_log8_quantize(s) for s in range(-32768, 32768))
164
+ table = _log8_table
165
+ return bytes(table[s + 32768] for s in pcm16)
166
+
167
+
168
+ def log8_decode_table() -> list[int]:
169
+ """The 256 signed 16-bit values a decoder needs: positive steps, then negated steps."""
170
+ return [*LOG8_MAGNITUDES, *(-m for m in LOG8_MAGNITUDES)]
@@ -0,0 +1,102 @@
1
+ """Random sources for the two voicings.
2
+
3
+ The accumulated voicing draws from `random.Random`. The closed-form voicing was
4
+ written against NumPy's `default_rng`, so `NumpyCompatRng` reproduces that
5
+ generator's stream (SeedSequence seeding and PCG64 output, `random()` and
6
+ `uniform()`) in plain Python and the package needs no NumPy.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import random
12
+ from typing import Protocol
13
+
14
+ _M32 = 0xFFFFFFFF
15
+ _M64 = (1 << 64) - 1
16
+ _M128 = (1 << 128) - 1
17
+ _PCG_MULT = 0x2360ED051FC65DA44385DF649FCCF645
18
+
19
+
20
+ class Rng(Protocol):
21
+ def random(self) -> float: ...
22
+
23
+
24
+ def stdlib_rng(seed: int) -> random.Random:
25
+ """The generator the stdlib copy used: `random.Random(seed)`."""
26
+ return random.Random(seed)
27
+
28
+
29
+ def _hashmix(value: int, const: list[int], mult: int) -> int:
30
+ value = (value ^ const[0]) & _M32
31
+ const[0] = (const[0] * mult) & _M32
32
+ value = (value * const[0]) & _M32
33
+ return value ^ (value >> 16)
34
+
35
+
36
+ def _mix(x: int, y: int) -> int:
37
+ result = (0xCA01F9DD * x - 0x4973F715 * y) & _M32
38
+ return result ^ (result >> 16)
39
+
40
+
41
+ def _seed_words(seed: int) -> list[int]:
42
+ if seed < 0:
43
+ raise ValueError("seed must be a non-negative integer")
44
+ words = []
45
+ while seed:
46
+ words.append(seed & _M32)
47
+ seed >>= 32
48
+ return words or [0]
49
+
50
+
51
+ def seed_sequence_state(seed: int) -> list[int]:
52
+ """Four 64-bit words, as `SeedSequence(seed).generate_state(4, uint64)`."""
53
+ entropy = _seed_words(seed)
54
+ pool = [0, 0, 0, 0]
55
+ const = [0x43B0D7E5]
56
+ for i in range(4):
57
+ pool[i] = _hashmix(entropy[i] if i < len(entropy) else 0, const, 0x931E8875)
58
+ for src in range(4):
59
+ for dst in range(4):
60
+ if src != dst:
61
+ pool[dst] = _mix(pool[dst], _hashmix(pool[src], const, 0x931E8875))
62
+ for extra in entropy[4:]:
63
+ for dst in range(4):
64
+ pool[dst] = _mix(pool[dst], _hashmix(extra, const, 0x931E8875))
65
+ const = [0x8B51F9DD]
66
+ words = []
67
+ for i in range(8):
68
+ value = pool[i % 4] ^ const[0]
69
+ const[0] = (const[0] * 0x58F38DED) & _M32
70
+ value = (value * const[0]) & _M32
71
+ words.append(value ^ (value >> 16))
72
+ return [words[2 * i] | (words[2 * i + 1] << 32) for i in range(4)]
73
+
74
+
75
+ class NumpyCompatRng:
76
+ """`numpy.random.default_rng(seed)` for integer seeds, without NumPy."""
77
+
78
+ def __init__(self, seed: int) -> None:
79
+ s = seed_sequence_state(seed)
80
+ initstate = (s[0] << 64) | s[1]
81
+ initseq = (s[2] << 64) | s[3]
82
+ self._inc = ((initseq << 1) | 1) & _M128
83
+ self._state = 0
84
+ self._step()
85
+ self._state = (self._state + initstate) & _M128
86
+ self._step()
87
+
88
+ def _step(self) -> None:
89
+ self._state = (self._state * _PCG_MULT + self._inc) & _M128
90
+
91
+ def next_u64(self) -> int:
92
+ self._step()
93
+ state = self._state
94
+ value = ((state >> 64) ^ state) & _M64
95
+ rot = state >> 122
96
+ return ((value >> rot) | (value << ((-rot) & 63))) & _M64
97
+
98
+ def random(self) -> float:
99
+ return (self.next_u64() >> 11) * (1.0 / 9007199254740992.0)
100
+
101
+ def uniform(self, low: float = 0.0, high: float = 1.0) -> float:
102
+ return low + (high - low) * self.random()