Skip to content

Commit fe383ad

Browse files
committed
Refactor OPL3 FM sound generation to process samples in smaller batches
1 parent 503cd29 commit fe383ad

1 file changed

Lines changed: 17 additions & 3 deletions

File tree

  • src/Spice86.Core/Emulator/Devices/Sound

src/Spice86.Core/Emulator/Devices/Sound/Opl3Fm.cs

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@
1313
/// Virtual device which emulates OPL3 FM sound.
1414
/// </summary>
1515
public class Opl3Fm : DefaultIOPortHandler, IDisposable {
16+
/// <summary>
17+
/// Maximum number of interleaved samples generated per lock acquisition when producing audio.
18+
/// Keep this value even so we always generate whole stereo frames.
19+
/// </summary>
20+
private const int MaxSamplesPerGenerationBatch = 256;
21+
1622
private readonly AdLibGoldDevice? _adLibGold;
1723
private readonly AdLibGoldIo? _adLibGoldIo;
1824
private readonly Opl3Chip _chip = new();
@@ -290,9 +296,17 @@ private void RenderTo(Span<float> destination) {
290296

291297
Span<short> interleaved = _tmpInterleaved.AsSpan(0, samples);
292298

293-
lock (_chipLock) {
294-
interleaved.Clear();
295-
_chip.GenerateStream(interleaved);
299+
int processed = 0;
300+
while (processed < samples) {
301+
int chunkSamples = Math.Min(MaxSamplesPerGenerationBatch, samples - processed);
302+
Span<short> chunk = interleaved.Slice(processed, chunkSamples);
303+
304+
lock (_chipLock) {
305+
chunk.Clear();
306+
_chip.GenerateStream(chunk);
307+
}
308+
309+
processed += chunkSamples;
296310
}
297311

298312
const float scale = 1.0f / 32768f;

0 commit comments

Comments
 (0)