harddaysengine 0.1.0__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 (187) hide show
  1. harddaysengine/__init__.py +7 -0
  2. harddaysengine/__main__.py +5 -0
  3. harddaysengine/app/__init__.py +39 -0
  4. harddaysengine/app/audio.py +214 -0
  5. harddaysengine/app/audio_stream.py +81 -0
  6. harddaysengine/app/audit.py +1062 -0
  7. harddaysengine/app/campaign_audit.py +259 -0
  8. harddaysengine/app/config.py +331 -0
  9. harddaysengine/app/dice_screen.py +113 -0
  10. harddaysengine/app/ending_audit.py +82 -0
  11. harddaysengine/app/ending_screen.py +163 -0
  12. harddaysengine/app/fight_audit.py +671 -0
  13. harddaysengine/app/fight_runtime.py +688 -0
  14. harddaysengine/app/fight_scene.py +50 -0
  15. harddaysengine/app/game.py +2616 -0
  16. harddaysengine/app/input.py +450 -0
  17. harddaysengine/app/inspector.py +489 -0
  18. harddaysengine/app/intro_player.py +446 -0
  19. harddaysengine/app/loop.py +141 -0
  20. harddaysengine/app/map_runtime.py +76 -0
  21. harddaysengine/app/map_scene.py +142 -0
  22. harddaysengine/app/meeting_audit.py +150 -0
  23. harddaysengine/app/meeting_screen.py +57 -0
  24. harddaysengine/app/module_player.py +207 -0
  25. harddaysengine/app/paula.py +290 -0
  26. harddaysengine/app/scene_assets.py +377 -0
  27. harddaysengine/app/service_screen.py +105 -0
  28. harddaysengine/app/sheet_screen.py +94 -0
  29. harddaysengine/app/sound_front.py +73 -0
  30. harddaysengine/app/stonehenge_screen.py +139 -0
  31. harddaysengine/app/synth.py +595 -0
  32. harddaysengine/app/town_screen.py +89 -0
  33. harddaysengine/app/valley_audit.py +102 -0
  34. harddaysengine/app/valley_screen.py +67 -0
  35. harddaysengine/app/village_audit.py +56 -0
  36. harddaysengine/app/window.py +285 -0
  37. harddaysengine/app/wizard_audit.py +103 -0
  38. harddaysengine/app/wizard_screen.py +153 -0
  39. harddaysengine/assets/__init__.py +223 -0
  40. harddaysengine/assets/adf.py +276 -0
  41. harddaysengine/assets/ai_map_rules.py +51 -0
  42. harddaysengine/assets/arena.py +205 -0
  43. harddaysengine/assets/audio.py +189 -0
  44. harddaysengine/assets/bank_data.py +177 -0
  45. harddaysengine/assets/caster_rules.py +151 -0
  46. harddaysengine/assets/cel.py +201 -0
  47. harddaysengine/assets/computer_knight_rules.py +98 -0
  48. harddaysengine/assets/creature_rules.py +175 -0
  49. harddaysengine/assets/dice_house_data.py +361 -0
  50. harddaysengine/assets/dragon_rules.py +164 -0
  51. harddaysengine/assets/drake_rules.py +124 -0
  52. harddaysengine/assets/ending_data.py +701 -0
  53. harddaysengine/assets/ending_runtime_data.py +298 -0
  54. harddaysengine/assets/extract.py +406 -0
  55. harddaysengine/assets/fight_defs.py +957 -0
  56. harddaysengine/assets/fight_palette.py +251 -0
  57. harddaysengine/assets/fight_program.py +234 -0
  58. harddaysengine/assets/fight_setup.py +72 -0
  59. harddaysengine/assets/fighter_rules.py +293 -0
  60. harddaysengine/assets/flyer_rules.py +98 -0
  61. harddaysengine/assets/guardian_rules.py +122 -0
  62. harddaysengine/assets/hit.py +190 -0
  63. harddaysengine/assets/hunk.py +200 -0
  64. harddaysengine/assets/intro_data.py +800 -0
  65. harddaysengine/assets/lzss.py +110 -0
  66. harddaysengine/assets/manifest.py +159 -0
  67. harddaysengine/assets/map_rules.py +148 -0
  68. harddaysengine/assets/meeting_data.py +113 -0
  69. harddaysengine/assets/mog_code.py +367 -0
  70. harddaysengine/assets/music_data.py +34 -0
  71. harddaysengine/assets/palette.py +97 -0
  72. harddaysengine/assets/picture.py +166 -0
  73. harddaysengine/assets/program_code.py +79 -0
  74. harddaysengine/assets/rnc.py +156 -0
  75. harddaysengine/assets/scene_sound_data.py +68 -0
  76. harddaysengine/assets/screen_fx.py +35 -0
  77. harddaysengine/assets/service_data.py +99 -0
  78. harddaysengine/assets/service_screen_data.py +499 -0
  79. harddaysengine/assets/sheet_data.py +122 -0
  80. harddaysengine/assets/shop_data.py +136 -0
  81. harddaysengine/assets/snatcher_rules.py +96 -0
  82. harddaysengine/assets/sound_rules.py +482 -0
  83. harddaysengine/assets/stalker_rules.py +109 -0
  84. harddaysengine/assets/stonehenge_data.py +210 -0
  85. harddaysengine/assets/synth_data.py +396 -0
  86. harddaysengine/assets/tables.py +500 -0
  87. harddaysengine/assets/town_data.py +153 -0
  88. harddaysengine/assets/town_loading_data.py +58 -0
  89. harddaysengine/assets/turn_rules.py +179 -0
  90. harddaysengine/assets/valley_data.py +151 -0
  91. harddaysengine/assets/village_data.py +33 -0
  92. harddaysengine/assets/wizard_data.py +144 -0
  93. harddaysengine/assets/wizard_screen_data.py +269 -0
  94. harddaysengine/cli/__init__.py +1 -0
  95. harddaysengine/cli/extract.py +80 -0
  96. harddaysengine/cli/inspect_assets.py +189 -0
  97. harddaysengine/cli/main.py +255 -0
  98. harddaysengine/render/__init__.py +41 -0
  99. harddaysengine/render/fight.py +68 -0
  100. harddaysengine/render/overlay.py +147 -0
  101. harddaysengine/render/postfx.py +625 -0
  102. harddaysengine/render/presentation.py +166 -0
  103. harddaysengine/render/renderer.py +538 -0
  104. harddaysengine/render/scene.py +523 -0
  105. harddaysengine/render/shaders/__init__.py +12 -0
  106. harddaysengine/render/shaders/crt.frag +143 -0
  107. harddaysengine/render/shaders/crt.vert +11 -0
  108. harddaysengine/render/shaders/crt_bloom_h.frag +40 -0
  109. harddaysengine/render/shaders/crt_bloom_v.frag +37 -0
  110. harddaysengine/render/shaders/smooth.frag +185 -0
  111. harddaysengine/render/shaders/smooth.vert +11 -0
  112. harddaysengine/render/shaders/surround.frag +58 -0
  113. harddaysengine/render/shaders/surround_blur.frag +37 -0
  114. harddaysengine/render/viewport.py +173 -0
  115. harddaysengine/sim/__init__.py +5 -0
  116. harddaysengine/sim/actor.py +189 -0
  117. harddaysengine/sim/ai_map.py +242 -0
  118. harddaysengine/sim/ai_map_state.py +56 -0
  119. harddaysengine/sim/ai_shop.py +83 -0
  120. harddaysengine/sim/collision.py +445 -0
  121. harddaysengine/sim/dice_house.py +341 -0
  122. harddaysengine/sim/ending.py +444 -0
  123. harddaysengine/sim/ending_jobs.py +253 -0
  124. harddaysengine/sim/ending_palette.py +114 -0
  125. harddaysengine/sim/ending_types.py +373 -0
  126. harddaysengine/sim/fight.py +545 -0
  127. harddaysengine/sim/fight_ai/__init__.py +1 -0
  128. harddaysengine/sim/fight_ai/approach.py +178 -0
  129. harddaysengine/sim/fight_ai/brawler.py +239 -0
  130. harddaysengine/sim/fight_ai/caster.py +361 -0
  131. harddaysengine/sim/fight_ai/dragon.py +301 -0
  132. harddaysengine/sim/fight_ai/drake.py +251 -0
  133. harddaysengine/sim/fight_ai/effects.py +33 -0
  134. harddaysengine/sim/fight_ai/flyer.py +112 -0
  135. harddaysengine/sim/fight_ai/guardian.py +292 -0
  136. harddaysengine/sim/fight_ai/knight.py +131 -0
  137. harddaysengine/sim/fight_ai/snatcher.py +226 -0
  138. harddaysengine/sim/fight_ai/stalker.py +90 -0
  139. harddaysengine/sim/fight_contact.py +125 -0
  140. harddaysengine/sim/fight_hurt.py +315 -0
  141. harddaysengine/sim/fight_moves.py +104 -0
  142. harddaysengine/sim/fight_routines.py +80 -0
  143. harddaysengine/sim/fight_script.py +748 -0
  144. harddaysengine/sim/fight_setup.py +163 -0
  145. harddaysengine/sim/fighter_rules.py +145 -0
  146. harddaysengine/sim/fighters.py +157 -0
  147. harddaysengine/sim/intro.py +484 -0
  148. harddaysengine/sim/intro_types.py +163 -0
  149. harddaysengine/sim/inventory.py +28 -0
  150. harddaysengine/sim/location_state.py +43 -0
  151. harddaysengine/sim/m68k.py +110 -0
  152. harddaysengine/sim/map_dragon.py +133 -0
  153. harddaysengine/sim/map_rules.py +117 -0
  154. harddaysengine/sim/meeting.py +76 -0
  155. harddaysengine/sim/overworld.py +562 -0
  156. harddaysengine/sim/palette_fx.py +355 -0
  157. harddaysengine/sim/rewards.py +190 -0
  158. harddaysengine/sim/rng.py +44 -0
  159. harddaysengine/sim/screen_fx.py +55 -0
  160. harddaysengine/sim/service_screen.py +196 -0
  161. harddaysengine/sim/service_screen_types.py +113 -0
  162. harddaysengine/sim/service_types.py +40 -0
  163. harddaysengine/sim/services.py +128 -0
  164. harddaysengine/sim/sheet_actions.py +181 -0
  165. harddaysengine/sim/sheet_layout.py +310 -0
  166. harddaysengine/sim/sheet_types.py +78 -0
  167. harddaysengine/sim/sheets.py +138 -0
  168. harddaysengine/sim/shop_types.py +27 -0
  169. harddaysengine/sim/shops.py +114 -0
  170. harddaysengine/sim/sound.py +195 -0
  171. harddaysengine/sim/stock.py +63 -0
  172. harddaysengine/sim/stonehenge.py +235 -0
  173. harddaysengine/sim/town_types.py +40 -0
  174. harddaysengine/sim/towns.py +74 -0
  175. harddaysengine/sim/trajectory.py +162 -0
  176. harddaysengine/sim/turn_rules.py +55 -0
  177. harddaysengine/sim/turns.py +129 -0
  178. harddaysengine/sim/types.py +110 -0
  179. harddaysengine/sim/valley.py +82 -0
  180. harddaysengine/sim/village.py +39 -0
  181. harddaysengine/sim/wizard.py +125 -0
  182. harddaysengine/sim/wizard_types.py +95 -0
  183. harddaysengine-0.1.0.dist-info/METADATA +157 -0
  184. harddaysengine-0.1.0.dist-info/RECORD +187 -0
  185. harddaysengine-0.1.0.dist-info/WHEEL +4 -0
  186. harddaysengine-0.1.0.dist-info/entry_points.txt +4 -0
  187. harddaysengine-0.1.0.dist-info/licenses/LICENSE +25 -0
@@ -0,0 +1,7 @@
1
+ """HardDaysEngine: clean-room reimplementation of Moonstone: A Hard Days Knight (1991).
2
+
3
+ Layers (enforced by `.importlinter` and `tests/unit/test_layering.py`):
4
+ ``cli -> app -> render -> assets -> sim``. ``sim`` is the pure, deterministic 50 Hz kernel.
5
+ """
6
+
7
+ __version__ = "0.1.0"
@@ -0,0 +1,5 @@
1
+ """``python -m harddaysengine``: same as the ``harddaysengine`` console script."""
2
+
3
+ from harddaysengine.cli.main import main
4
+
5
+ raise SystemExit(main())
@@ -0,0 +1,39 @@
1
+ """pygame-ce application host, 50 Hz fixed-timestep loop, and asset inspector."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from harddaysengine.app.config import ConfigError, find_adf_images, resolve_adf_dir
6
+ from harddaysengine.app.inspector import (
7
+ BackgroundItem,
8
+ InspectorState,
9
+ SpriteSetItem,
10
+ build_inspector_state,
11
+ run_inspector_headless,
12
+ run_inspector_window,
13
+ )
14
+ from harddaysengine.app.loop import (
15
+ FIGHT_FRAME_DIVISOR_FAST,
16
+ FIGHT_FRAME_DIVISOR_NORMAL,
17
+ MAX_FRAME_DELTA_NS,
18
+ PAL_HZ,
19
+ TICK_NS,
20
+ Accumulator50Hz,
21
+ )
22
+
23
+ __all__ = [
24
+ "FIGHT_FRAME_DIVISOR_FAST",
25
+ "FIGHT_FRAME_DIVISOR_NORMAL",
26
+ "MAX_FRAME_DELTA_NS",
27
+ "PAL_HZ",
28
+ "TICK_NS",
29
+ "Accumulator50Hz",
30
+ "BackgroundItem",
31
+ "ConfigError",
32
+ "InspectorState",
33
+ "SpriteSetItem",
34
+ "build_inspector_state",
35
+ "find_adf_images",
36
+ "resolve_adf_dir",
37
+ "run_inspector_headless",
38
+ "run_inspector_window",
39
+ ]
@@ -0,0 +1,214 @@
1
+ """Audio engine: the ``mog`` synth on a Paula model, and ``program`` music (ARCHITECTURE.md §6).
2
+
3
+ Each host VBL runs the synth tick, then the sound requests reported during that tick, then
4
+ renders one fiftieth of a second (§6.2.9). Without synth data the channels stay silent.
5
+
6
+ Rendered PCM goes into a ring that an SDL audio callback drains at the device rate, so VBL
7
+ bursts from the host loop never drop or starve audio (ADR-051).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from functools import partial
13
+ from typing import TYPE_CHECKING
14
+
15
+ import pygame
16
+ from pygame._sdl2 import audio as sdl_audio
17
+
18
+ from harddaysengine.app.audio_stream import PcmRing
19
+ from harddaysengine.app.module_player import ModulePlayer
20
+ from harddaysengine.app.paula import Paula, SampleMemory, address
21
+ from harddaysengine.app.sound_front import SoundFront
22
+ from harddaysengine.app.synth import WAVE_REGION, Synth
23
+
24
+ if TYPE_CHECKING:
25
+ from collections.abc import Callable, Sequence
26
+
27
+ import numpy as np
28
+ from numpy.typing import NDArray
29
+
30
+ from harddaysengine.assets.audio import DecodedModule
31
+ from harddaysengine.assets.bank_data import BankData, BankLoad
32
+ from harddaysengine.assets.music_data import MusicData
33
+ from harddaysengine.assets.synth_data import FrontEndData, SynthData
34
+ from harddaysengine.sim.sound import SoundRequest
35
+
36
+ DEFAULT_MIX_RATE = 22050
37
+ DEVICE_CHUNK = 512
38
+ _BYTES_PER_FRAME = 4
39
+
40
+
41
+ class AudioEngine:
42
+ """The synth, its front end and Paula, with ``pygame.mixer`` output and module music."""
43
+
44
+ def __init__(self, sample_rate: int = DEFAULT_MIX_RATE, *, headless: bool = False) -> None:
45
+ """Render at ``sample_rate``; ``headless`` never opens an audio device."""
46
+ self.memory = SampleMemory()
47
+ self.paula = Paula(self.memory, sample_rate)
48
+ self.synth: Synth | None = None
49
+ self.front: SoundFront | None = None
50
+ self.banks: BankData | None = None
51
+ self.music_data: MusicData | None = None
52
+ self.module_player: ModulePlayer | None = None
53
+ self._pending: list[Callable[[], None]] = []
54
+ self._headless = headless
55
+ self._mixer_initialized = False
56
+ self._device: sdl_audio.AudioDevice | None = None
57
+ self._ring = PcmRing.for_device(sample_rate, DEVICE_CHUNK)
58
+ self._current_music_title: str | None = None
59
+ self._is_music_playing = False
60
+ if not headless:
61
+ self._init_pygame_mixer(sample_rate)
62
+
63
+ def _init_pygame_mixer(self, sample_rate: int) -> None:
64
+ """Bring up SDL audio, then open a callback device at exactly ``sample_rate``."""
65
+ try:
66
+ if pygame.mixer.get_init() is None:
67
+ pygame.mixer.init(frequency=sample_rate, size=-16, channels=2, buffer=DEVICE_CHUNK)
68
+ self._device = sdl_audio.AudioDevice(
69
+ devicename=None,
70
+ iscapture=False,
71
+ frequency=sample_rate,
72
+ audioformat=sdl_audio.AUDIO_S16,
73
+ numchannels=2,
74
+ chunksize=DEVICE_CHUNK,
75
+ allowed_changes=0,
76
+ callback=self._fill_device,
77
+ )
78
+ self._device.pause(0)
79
+ self._mixer_initialized = True
80
+ except pygame.error:
81
+ self._headless = True
82
+ self._mixer_initialized = False
83
+ self._device = None
84
+
85
+ def _fill_device(self, _device: sdl_audio.AudioDevice, stream: memoryview) -> None:
86
+ """SDL audio thread: copy the next queued frames, or silence, into ``stream``."""
87
+ stream[:] = self._ring.read(len(stream) // _BYTES_PER_FRAME).tobytes()
88
+
89
+ @property
90
+ def headless(self) -> bool:
91
+ """Whether the engine is running without an active `pygame.mixer` device."""
92
+ return self._headless
93
+
94
+ @property
95
+ def mixer_initialized(self) -> bool:
96
+ """Whether `pygame.mixer` was successfully initialized."""
97
+ return self._mixer_initialized
98
+
99
+ @property
100
+ def current_music_title(self) -> str | None:
101
+ """Title of the currently loaded `.cmp` ProTracker module, if any."""
102
+ return self._current_music_title
103
+
104
+ @property
105
+ def is_music_playing(self) -> bool:
106
+ """Whether ProTracker module playback is active."""
107
+ return self._is_music_playing
108
+
109
+ def attach_synth(self, synth: SynthData, front: FrontEndData) -> None:
110
+ """Enter ``mog``: load the waveform hunk, then run the synth init and front-end set-up."""
111
+ self.memory.clear()
112
+ self.banks = None
113
+ self.memory.load(WAVE_REGION, synth.waves)
114
+ self.synth = Synth(synth, self.paula)
115
+ self.paula.handler = self.synth.interrupt
116
+ self.front = SoundFront(front, self._start)
117
+ self.module_player = None
118
+ self._is_music_playing = False
119
+ self._pending.clear()
120
+ self.synth.init()
121
+ self.paula.commit()
122
+ self.front.load()
123
+ self.front.clear_busy()
124
+
125
+ def _start(self, sequence: int, channel: int) -> None:
126
+ if self.synth is None:
127
+ raise ValueError("synth start without synth data")
128
+ self.synth.start(sequence, channel)
129
+ self.paula.commit()
130
+
131
+ def attach_banks(self, banks: BankData) -> None:
132
+ """Resolve the original instrument addresses once (§6.2.10)."""
133
+ if self.synth is None:
134
+ raise ValueError("bank relocation requires synth data")
135
+ if len(banks.samples) != len(self.synth.samples):
136
+ raise ValueError("bank relocation does not match the instrument table")
137
+ self.banks = banks
138
+ self.synth.samples[:] = [
139
+ address(slot + WAVE_REGION, offset) for slot, offset in banks.samples
140
+ ]
141
+
142
+ def load_bank(self, bank: BankLoad, data: bytes) -> None:
143
+ """Copy the exact original file slice into its persistent slot (§6.2.10)."""
144
+ if self.banks is None:
145
+ raise ValueError("bank load requires relocation data")
146
+ start = self.banks.header_bytes
147
+ if len(data) < start:
148
+ raise ValueError(f"truncated sound bank header {bank.name!r}")
149
+ self.memory.write(bank.slot + WAVE_REGION, data[start : start + bank.size], bank.size)
150
+
151
+ def handle_requests(self, requests: Sequence[SoundRequest]) -> None:
152
+ """Queue requests reported by ``sim``; they run after the next synth tick (§6.2.9)."""
153
+ front = self.front
154
+ if front is not None:
155
+ self._pending.extend(partial(front.request, request) for request in requests)
156
+
157
+ def stop_all(self) -> None:
158
+ """Queue the front end's stop all (§6.2.1)."""
159
+ front = self.front
160
+ if front is not None:
161
+ self._pending.append(front.stop_all)
162
+
163
+ def fade_step(self, flag: bool) -> None:
164
+ """One palette fade step: the synth's fade attenuation (§6.2.8)."""
165
+ if self.synth is not None and self.module_player is None:
166
+ self.synth.fade(flag)
167
+
168
+ def step_vbl(self) -> NDArray[np.int16]:
169
+ """Advance one PAL VBL: tick, queued requests, then render and queue the PCM."""
170
+ if self.module_player is not None:
171
+ self.module_player.tick()
172
+ self.paula.commit()
173
+ elif self.synth is not None:
174
+ self.synth.tick()
175
+ self.paula.commit()
176
+ pending, self._pending = self._pending, []
177
+ for action in pending:
178
+ action()
179
+ pcm = self.paula.render_frame()
180
+ if self._device is not None:
181
+ self._ring.write(pcm)
182
+ return pcm
183
+
184
+ def play_music(self, module: DecodedModule, *, loops: int = -1) -> bool:
185
+ """Start the original 50 Hz program player, including in headless mode (§6.3.1)."""
186
+ if loops != -1:
187
+ raise ValueError("the original module player repeats its arrangement")
188
+ if self.music_data is None:
189
+ raise ValueError("module playback requires the original program player tables")
190
+ self._pending.clear()
191
+ self.paula.handler = None
192
+ self.module_player = ModulePlayer(module, self.music_data, self.paula)
193
+ self._current_music_title = module.title
194
+ self._is_music_playing = True
195
+ return True
196
+
197
+ def stop_music(self) -> None:
198
+ """Remove the program music tick job, retaining Paula's last buffers (§6.3.1)."""
199
+ self._is_music_playing = False
200
+ if self.module_player is not None:
201
+ self.module_player.running = False
202
+
203
+ def close(self) -> None:
204
+ """Stop music and shut down `pygame.mixer` if initialized."""
205
+ self.stop_music()
206
+ if self._device is not None:
207
+ self._device.close()
208
+ self._device = None
209
+ if self._mixer_initialized:
210
+ self._mixer_initialized = False
211
+ try:
212
+ pygame.mixer.quit()
213
+ except pygame.error:
214
+ return
@@ -0,0 +1,81 @@
1
+ """PCM ring between the 50 Hz simulation and the audio device callback (ARCHITECTURE.md §6.2.9).
2
+
3
+ The simulation produces one fiftieth of a second of PCM per VBL, but the host runs VBLs in
4
+ bursts that follow the display rate (0, 1 or 2 per frame at 60 Hz). The device consumes
5
+ samples at its own steady rate on another thread. This ring decouples the two:
6
+
7
+ * playback waits until ``prebuffer`` frames are queued, and waits again after any underrun,
8
+ so a late burst causes one short silence instead of many clicks;
9
+ * when the host clock runs ahead of the device clock and more than ``limit`` frames are
10
+ queued, the oldest frames are dropped down to the middle of the window, bounding latency.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import threading
16
+ from typing import TYPE_CHECKING
17
+
18
+ import numpy as np
19
+
20
+ if TYPE_CHECKING:
21
+ from numpy.typing import NDArray
22
+
23
+ STEREO = 2
24
+
25
+
26
+ class PcmRing:
27
+ """Thread-safe stereo ``int16`` FIFO with prebuffering and a latency bound."""
28
+
29
+ def __init__(self, prebuffer: int, limit: int) -> None:
30
+ """Start playback at ``prebuffer`` queued frames; trim when above ``limit``."""
31
+ if prebuffer <= 0 or limit <= prebuffer:
32
+ raise ValueError("PCM ring needs 0 < prebuffer < limit")
33
+ self.prebuffer = prebuffer
34
+ self.limit = limit
35
+ self.underruns = 0
36
+ self.dropped = 0
37
+ self._lock = threading.Lock()
38
+ self._frames: NDArray[np.int16] = np.zeros((0, STEREO), dtype=np.int16)
39
+ self._primed = False
40
+
41
+ @classmethod
42
+ def for_device(cls, rate: int, chunk: int) -> PcmRing:
43
+ """Size the window for a device of ``rate`` Hz pulling ``chunk`` frames per callback.
44
+
45
+ Prebuffer one device chunk plus two VBLs; allow six more VBLs before trimming.
46
+ """
47
+ vbl = max(1, rate // 50)
48
+ prebuffer = chunk + 2 * vbl
49
+ return cls(prebuffer, prebuffer + 6 * vbl)
50
+
51
+ @property
52
+ def buffered(self) -> int:
53
+ """Frames queued and not yet read."""
54
+ with self._lock:
55
+ return len(self._frames)
56
+
57
+ def write(self, pcm: NDArray[np.int16]) -> None:
58
+ """Append one VBL of stereo PCM, trimming the oldest frames above ``limit``."""
59
+ with self._lock:
60
+ frames = np.concatenate((self._frames, pcm.reshape(-1, STEREO)))
61
+ if len(frames) > self.limit:
62
+ keep = (self.prebuffer + self.limit) // 2
63
+ self.dropped += len(frames) - keep
64
+ frames = frames[len(frames) - keep :]
65
+ self._frames = frames
66
+
67
+ def read(self, count: int) -> NDArray[np.int16]:
68
+ """Remove ``count`` frames; silence while priming and for any missing tail."""
69
+ out = np.zeros((count, STEREO), dtype=np.int16)
70
+ with self._lock:
71
+ if not self._primed:
72
+ if len(self._frames) < self.prebuffer:
73
+ return out
74
+ self._primed = True
75
+ taken = self._frames[:count]
76
+ self._frames = self._frames[len(taken) :]
77
+ if len(taken) < count:
78
+ self.underruns += 1
79
+ self._primed = False
80
+ out[: len(taken)] = taken
81
+ return out