Skip to content

Local AI BGM and sound effects for Claude Code and any MCP client. Stable Audio 3 on Apple Silicon (MLX) and Windows NVIDIA GPUs (PyTorch). No cloud, no API key.

Write OGG Vorbis in blocks to avoid a Windows stack overflow

Kana0d47423da66a
diff --git a/src/audio_studio_mcp/post.py b/src/audio_studio_mcp/post.py
index 2214f25..7722ca5 100644
--- a/src/audio_studio_mcp/post.py
+++ b/src/audio_studio_mcp/post.py
@@ -18,6 +18,8 @@ from pathlib import Path
import numpy as np
import soundfile as sf
+OGG_WRITE_BLOCK = 16384 # frames per Vorbis write call, see write()
+
def db_to_lin(db: float) -> float:
return float(10 ** (db / 20))
@@ -66,8 +68,13 @@ def write(path: Path, audio: np.ndarray, sr: int, fmt: str, ogg_quality: float =
elif fmt == "flac":
sf.write(str(path), data, sr, format="FLAC", subtype="PCM_24")
elif fmt == "ogg":
- sf.write(str(path), data, sr, format="OGG", subtype="VORBIS",
- compression_level=float(np.clip(1.0 - ogg_quality, 0.0, 1.0)))
+ # libsndfile's Vorbis encoder overflows the 1 MB Windows thread stack
+ # (0xC00000FD, the whole process dies) when handed a long clip in one
+ # call; writing in blocks keeps its per-call buffers small.
+ with sf.SoundFile(str(path), "w", sr, data.shape[1], format="OGG", subtype="VORBIS",
+ compression_level=float(np.clip(1.0 - ogg_quality, 0.0, 1.0))) as f:
+ for i in range(0, len(data), OGG_WRITE_BLOCK):
+ f.write(data[i:i + OGG_WRITE_BLOCK])
else:
raise ValueError(f"unknown format {fmt}")
diff --git a/tests/test_post.py b/tests/test_post.py
index 2a8969b..2f5174d 100644
--- a/tests/test_post.py
+++ b/tests/test_post.py
@@ -1,4 +1,6 @@
import shutil
+import subprocess
+import sys
import numpy as np
import pytest
@@ -68,6 +70,25 @@ def test_write_read_roundtrip(tmp_path, fmt, ext):
assert abs(audio.shape[-1] - 22050) < 2000 # vorbis pads a little
+def test_long_ogg_write_does_not_crash_worker_thread(tmp_path):
+ # A long clip handed to libsndfile's Vorbis encoder in one call overflowed
+ # the 1 MB Windows thread stack and killed the process (#10). Run it in a
+ # child process so a crash fails this test instead of pytest.
+ path = tmp_path / "long.ogg"
+ code = (
+ "import sys, threading, numpy as np\n"
+ "from audio_studio_mcp import post\n"
+ "a = (np.random.default_rng(0).random((2, 48000 * 60), dtype=np.float32) - 0.5) * 0.5\n"
+ "t = threading.Thread(target=post.write, args=(sys.argv[1], a, 48000, 'ogg'))\n"
+ "t.start(); t.join()\n"
+ )
+ r = subprocess.run([sys.executable, "-c", code, str(path)], capture_output=True, text=True)
+ assert r.returncode == 0, f"exit {r.returncode:#x}: {r.stderr[-400:]}"
+ audio, sr = post.read(path)
+ assert sr == 48000 and audio.shape[0] == 2
+ assert abs(audio.shape[-1] - 48000 * 60) < 2000
+
+
@needs_ffmpeg
def test_ffmpeg_resample():
out, info = post.ffmpeg_process(sine(1.0), 44100, 48000, None, -1.0)