using System;
using System.Collections.Generic;
using System.IO;
using OpenTK.Audio;
using OpenTK.Audio.OpenAL;
using System.Runtime.InteropServices;
public class AudioEngine : IDisposable
{
public class Voice
{
public string Path;
public int Buffer;
public int Source;
public float Gain;
}
private class SharedBuffer
{
public int Id;
public int Refs;
}
private AudioContext _context;
private readonly Dictionary<string, Voice> _voices =
new Dictionary<string, Voice>(StringComparer.OrdinalIgnoreCase);
// One AL buffer per WAV file, shared by every voice that plays it
// (legacy cases often use the same file for several regions).
private readonly Dictionary<string, SharedBuffer> _buffers =
new Dictionary<string, SharedBuffer>(StringComparer.OrdinalIgnoreCase);
private readonly object _lock = new object();
public event Action<string> Log;
public bool Init()
{
try
{
_context = new AudioContext(); // opens default device + context
_context.MakeCurrent();
AudioOutput.RegisterCurrentDevice();
Emit("OpenAL ready: " + AudioContext.CurrentContext.CurrentDevice);
return true;
}
catch (Exception ex)
{
Emit("OpenAL init failed: " + ex.Message);
return false;
}
}
/// Load + start looping at gain 0. Idempotent per key.
public Voice Warm(string wavPath) { return Warm(wavPath, wavPath); }
public Voice Warm(string wavPath, string key)
{
wavPath = AudioOutput.SoundFor(wavPath); // ← add: speaker copy in legacy speaker mode
if (string.IsNullOrEmpty(wavPath) || !File.Exists(wavPath))
{
Emit("Sound file not found: " + wavPath);
return null;
}
lock (_lock)
{
Voice v;
if (_voices.TryGetValue(key, out v)) return v;
int buf = 0;
try
{
buf = AcquireBuffer(wavPath);
int src = AL.GenSource();
AL.Source(src, ALSourcei.Buffer, buf);
AL.Source(src, ALSourceb.Looping, true);
AL.Source(src, ALSourcef.Gain, 0.0f);
AL.SourcePlay(src);
CheckError("Warm " + Path.GetFileName(wavPath));
v = new Voice { Path = wavPath, Buffer = buf, Source = src, Gain = 0f };
_voices[key] = v;
Emit("Warmed " + Path.GetFileName(wavPath) + " [" + key + "] voices=" + _voices.Count);
return v;
}
catch (Exception ex)
{
if (buf != 0) ReleaseBuffer(wavPath);
Emit("Load failed " + wavPath + ": " + ex.Message);
return null;
}
}
}
private int AcquireBuffer(string wavPath)
{
SharedBuffer sb;
if (_buffers.TryGetValue(wavPath, out sb)) { sb.Refs++; return sb.Id; }
WavFile w = WavFile.Load(wavPath);
int buf = AL.GenBuffer();
AL.BufferData(buf, w.Format, w.Data, w.Data.Length, w.SampleRate);
CheckError("BufferData " + Path.GetFileName(wavPath));
_buffers[wavPath] = new SharedBuffer { Id = buf, Refs = 1 };
return buf;
}
private void ReleaseBuffer(string wavPath)
{
SharedBuffer sb;
if (!_buffers.TryGetValue(wavPath, out sb)) return;
if (--sb.Refs > 0) return;
AL.DeleteBuffer(sb.Id);
_buffers.Remove(wavPath);
}
/// Stops and frees every voice whose key starts with prefix.
/// Legacy uses "R" so each case's 7 region voices don't pile up
/// (every source keeps looping and being mixed, even at gain 0).
public void ReleaseWhereKeyStarts(string prefix)
{
lock (_lock)
{
var dead = new List<string>();
foreach (var kv in _voices)
if (kv.Key.StartsWith(prefix, StringComparison.Ordinal)) dead.Add(kv.Key);
foreach (string k in dead)
{
Voice v = _voices[k];
AL.SourceStop(v.Source);
AL.Source(v.Source, ALSourcei.Buffer, 0); // detach before the buffer can be deleted
AL.DeleteSource(v.Source);
ReleaseBuffer(v.Path);
_voices.Remove(k);
if (v == _main) _main = null;
}
if (dead.Count > 0)
Emit("Released " + dead.Count + " voice(s) '" + prefix + "*' voices=" + _voices.Count);
}
}
/// Rewinds the given voices and starts them in ONE OpenAL call, so they
/// share sample position 0. Gains are left as they are (normally 0).
public void RestartTogether(IList<Voice> voices)
{
if (voices == null || voices.Count == 0) return;
var ids = new List<int>();
foreach (var v in voices) if (v != null) ids.Add(v.Source);
if (ids.Count == 0) return;
int[] arr = ids.ToArray();
lock (_lock)
{
AL.SourceRewind(arr.Length, arr);
AL.SourcePlay(arr.Length, arr);
CheckError("RestartTogether");
}
}
/// Replaces SourceVoice.SetVolume. Linear 0..1.
public void SetGain(Voice v, float gain)
{
if (v == null) return;
if (gain < 0f) gain = 0f;
if (gain > 1f) gain = 1f;
if (Math.Abs(gain - v.Gain) < 0.001f) return; // skip redundant AL calls
lock (_lock)
{
v.Gain = gain;
AL.Source(v.Source, ALSourcef.Gain, gain);
if (gain > 0f && AL.GetSourceState(v.Source) != ALSourceState.Playing)
AL.SourcePlay(v.Source);
}
}
/// Form2's PlayColorFromStart — restart with no leading gap.
public void PlayFromStart(Voice v, float gain)
{
if (v == null) return;
lock (_lock)
{
AL.SourceRewind(v.Source);
v.Gain = gain;
AL.Source(v.Source, ALSourcef.Gain, gain);
AL.SourcePlay(v.Source);
}
}
public void MuteAll()
{
lock (_lock)
foreach (var v in _voices.Values)
{
v.Gain = 0f;
AL.Source(v.Source, ALSourcef.Gain, 0f);
}
}
public void StopAll()
{
lock (_lock)
foreach (var v in _voices.Values)
{
AL.SourceStop(v.Source);
v.Gain = 0f;
}
}
/// Form2's Volume_Control_XAudio2, unchanged — keeps Linux loudness
/// matched to the Windows build.
public static float VolumeCurve(int range)
{
const double CURVE = 9.5;
double y = Math.Pow(range / 255.0, 1.0 / CURVE);
int db = (int)(10000.0 * y - 10000);
if (db > 0) db = 0;
if (db < -10000) db = -10000;
float lin = (float)Math.Pow(10.0, db / 2000.0);
return Math.Max(0f, Math.Min(1f, lin));
}
// ── shims so MapWindow's existing calls still compile ──
private Voice _main;
public void Start(string wavPath)
{
_main = Warm(wavPath);
SetGain(_main, 0f);
}
public void Stop() { MuteAll(); }
public Voice MainVoice { get { return _main; } }
public void Dispose()
{
lock (_lock)
{
foreach (var v in _voices.Values)
{
AL.SourceStop(v.Source);
AL.Source(v.Source, ALSourcei.Buffer, 0);
AL.DeleteSource(v.Source);
}
_voices.Clear();
foreach (var b in _buffers.Values) AL.DeleteBuffer(b.Id);
_buffers.Clear();
}
if (_context != null) { _context.Dispose(); _context = null; }
}
private void CheckError(string where)
{
ALError e = AL.GetError();
if (e != ALError.NoError) Emit(where + ": " + AL.GetErrorString(e));
}
private void Emit(string m)
{
var h = Log;
if (h != null) h(m); else Console.WriteLine("[audio] " + m);
}
}