using EvilEngine.Music.Decoding; using Godot; namespace EvilEngine.Client; internal sealed class PcmFeeder : IDisposable { private const int Chunk = 2048; private readonly int capacity; private readonly Vector2[] frames = new Vector2[Chunk]; private readonly AudioStreamGeneratorPlayback playback; private readonly float[] samples; private readonly IPcmSource source; private readonly long start; private readonly Thread thread; private volatile bool finished; private long pushed; private volatile bool stopping; public PcmFeeder(IPcmSource source, AudioStreamGeneratorPlayback playback) { this.source = source; this.playback = playback; capacity = playback.GetFramesAvailable(); start = source.Position; samples = new float[Chunk * source.Channels]; Feed(capacity); thread = new Thread(Run) { IsBackground = true, Name = "Music feeder" }; thread.Start(); } public double Seconds { get { var queued = capacity - playback.GetFramesAvailable(); return Math.Max(start, start + Interlocked.Read(ref pushed) - queued) / (double)source.SampleRate; } } public bool Drained => finished && capacity - playback.GetFramesAvailable() <= 0; public void Dispose() { stopping = true; if (thread.IsAlive && Thread.CurrentThread != thread) thread.Join(); } private void Run() { try { while (!stopping && !finished) { var free = playback.GetFramesAvailable(); if (free < Chunk) { Thread.Sleep(5); continue; } Feed(free); } } catch (Exception error) when (error is IOException or InvalidDataException or EndOfStreamException) { GD.PushWarning($"Music: decoding stopped: {error.Message}"); finished = true; } } private void Feed(int free) { var channels = source.Channels; while (free >= Chunk && !stopping) { var read = source.Read(samples); if (read == 0) { finished = true; return; } for (var i = 0; i < read; i++) frames[i] = Stereo(samples.AsSpan(i * channels, channels)); playback.PushBuffer(frames.AsSpan(0, read)); Interlocked.Add(ref pushed, read); free -= read; } } private static Vector2 Stereo(ReadOnlySpan frame) { switch (frame.Length) { case 1: return new Vector2(frame[0], frame[0]); case 2: return new Vector2(frame[0], frame[1]); case >= 6: const float side = 0.7071f; const float scale = 1 / (1 + 2 * side); return new Vector2((frame[0] + side * frame[2] + side * frame[4]) * scale, (frame[1] + side * frame[2] + side * frame[5]) * scale); default: float left = 0, right = 0; for (var c = 0; c < frame.Length; c++) if (c % 2 == 0) left += frame[c]; else right += frame[c]; return new Vector2(left / ((frame.Length + 1) / 2), right / (frame.Length / 2)); } } }