Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ wheels/
.venv

*_bank.json
*_patterns.json
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ dependencies = [

[project.scripts]
simplesampler = "simplesampler.main:main"
simplesampler-seq = "simplesampler.sequencer.app:main"

[build-system]
requires = ["hatchling"]
Expand Down
11 changes: 11 additions & 0 deletions src/seq.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
"""Dev entry point for the sequencer. Run with: uv run src/seq.py bank.json"""

import sys
import os

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "simplesampler", ".."))

from simplesampler.sequencer.app import main

if __name__ == "__main__":
main()
61 changes: 41 additions & 20 deletions src/simplesampler/audio/playback.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,44 @@
import wave
import numpy as np
from collections import deque
from typing import List, Dict
import os
import sys


class _Voice:
"""Lightweight voice object for the audio callback hot path.

Uses __slots__ for fast attribute access — dict key hashing is
measurably slower when called thousands of times per second.
"""

__slots__ = ("data", "idx")

def __init__(self, data: np.ndarray):
self.data = data
self.idx = 0


class AudioPlayer:
RATE = 44100
CHANNELS = 2
BLOCKSIZE = 256 # ~5.8ms at 44100 Hz
MAX_VOICES = 64 # Drop oldest voices beyond this limit

# Absolute ceiling: ~33ms at 44100 Hz. Keeps latency bounded
# even if the caller passes a huge value.
_MAX_BLOCKSIZE = 1456

def __init__(self, blocksize: int = 256):
self.blocksize = min(blocksize, self._MAX_BLOCKSIZE)

def __init__(self):
# Lock-free pending queue: play_data() appends here,
# callback drains into its own local list each cycle.
self._pending: deque = deque()
self._voices: List[Dict] = []
self._pending: deque[_Voice] = deque()
self._voices: list[_Voice] = []

self.stream = sd.OutputStream(
samplerate=self.RATE,
blocksize=self.BLOCKSIZE,
blocksize=self.blocksize,
channels=self.CHANNELS,
dtype="float32",
latency="low",
Expand All @@ -36,7 +55,7 @@ def play_data(self, data: np.ndarray):
if data is None or len(data) == 0:
return
# deque.append is atomic in CPython — no lock needed
self._pending.append({"data": data, "idx": 0})
self._pending.append(_Voice(data))

def play_wave_file(self, file_path: str):
"""Loads and plays a wav file immediately."""
Expand All @@ -56,33 +75,35 @@ def _callback(self, outdata: np.ndarray, frames: int, time, status):
print(f"Audio status: {status}", file=sys.stderr)

# Drain pending voices into our local list (lock-free reads)
while True:
try:
voice = self._pending.popleft()
self._voices.append(voice)
except IndexError:
break
pending = self._pending
voices = self._voices
while pending:
voices.append(pending.popleft())

# Enforce voice cap — drop oldest voices first
if len(voices) > self.MAX_VOICES:
del voices[: len(voices) - self.MAX_VOICES]

# Zero the output buffer
outdata[:] = 0.0

# Mix active voices
i = len(self._voices) - 1
i = len(voices) - 1
while i >= 0:
voice = self._voices[i]
data = voice["data"]
idx = voice["idx"]
voice = voices[i]
data = voice.data
idx = voice.idx

remaining = len(data) - idx
to_read = min(frames, remaining)

if to_read > 0:
outdata[:to_read] += data[idx : idx + to_read]
voice["idx"] += to_read
voice.idx += to_read

# Remove finished voices
if voice["idx"] >= len(data):
self._voices.pop(i)
if voice.idx >= len(data):
voices.pop(i)

i -= 1

Expand Down
64 changes: 64 additions & 0 deletions src/simplesampler/schemas/ss_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""
Master configuration for SimpleSampler (ss_config.toml).

Search order:
1. $XDG_CONFIG_HOME/simplesampler/ss_config.toml
2. ./ss_config.toml (working directory)

If not found, all defaults apply silently.
"""

import os
import sys
import tomllib
from pydantic import BaseModel, ValidationError
from typing import Tuple


class MetronomeConfig(BaseModel):
enabled: bool = True
sound: str = "" # Path to WAV — empty means generated sine click
volume: float = 0.7 # 0.0 – 1.0
accent_beat_1: bool = True # Louder click on beat 1


class SequencerConfig(BaseModel):
default_bpm: int = 120
steps_per_beat: int = 4
time_signature: Tuple[int, int] = (4, 4)
pattern_count: int = 4 # Default number of empty patterns to create


class SSConfig(BaseModel):
metronome: MetronomeConfig = MetronomeConfig()
sequencer: SequencerConfig = SequencerConfig()


def load_config(override_path: str | None = None) -> SSConfig:
"""
Load ss_config.toml from the override path, XDG config dir, or cwd.
Returns defaults if no file is found.
"""
paths: list[str] = []

if override_path:
paths.append(override_path)

# XDG_CONFIG_HOME (default ~/.config)
xdg = os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config"))
paths.append(os.path.join(xdg, "simplesampler", "ss_config.toml"))

# Current working directory
paths.append(os.path.join(os.getcwd(), "ss_config.toml"))

for path in paths:
if os.path.isfile(path):
try:
with open(path, "rb") as f:
data = tomllib.load(f)
return SSConfig.model_validate(data)
except (tomllib.TOMLDecodeError, ValidationError) as e:
print(f"Warning: ignoring bad config {path}: {e}", file=sys.stderr)
continue

return SSConfig()
Empty file.
Loading