mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-28 05:58:25 +01:00
first
This commit is contained in:
parent
bd62d51ec9
commit
b578433e37
29 changed files with 784842 additions and 0 deletions
22
Brutal.OpenAl/Manual/Al.Listener.cs
Normal file
22
Brutal.OpenAl/Manual/Al.Listener.cs
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public static unsafe partial class Al
|
||||
{
|
||||
public static partial class Listener
|
||||
{
|
||||
public static (float3 At, float3 Up) Orientation
|
||||
{
|
||||
get
|
||||
{
|
||||
var v = stackalloc float[6];
|
||||
PInvoke.GetListenerfv(Constants.AL_ORIENTATION, v);
|
||||
return (new float3(v[0], v[1], v[2]), new float3(v[3], v[4], v[5]));
|
||||
}
|
||||
set
|
||||
{
|
||||
var v = stackalloc float[6] { value.At.X, value.At.Y, value.At.Z, value.Up.X, value.Up.Y, value.Up.Z };
|
||||
PInvoke.Listenerfv(Constants.AL_ORIENTATION, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
72
Brutal.OpenAl/Manual/Al.Wrapper.Internal.cs
Normal file
72
Brutal.OpenAl/Manual/Al.Wrapper.Internal.cs
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public static unsafe partial class Al
|
||||
{
|
||||
// The EAX reverb pan vectors are the only fv-shaped EFX parameters, so the fv entry points
|
||||
// surface as float3 helpers (no filter has an fv key).
|
||||
|
||||
internal static float3 GetEffectfv3(uint name, int param)
|
||||
{
|
||||
var v = stackalloc float[3];
|
||||
PInvoke.GetEffectfv(name, param, v);
|
||||
return new float3(v[0], v[1], v[2]);
|
||||
}
|
||||
|
||||
internal static void SetEffectfv3(uint name, int param, float3 value)
|
||||
{
|
||||
var v = stackalloc float[3] { value.X, value.Y, value.Z };
|
||||
PInvoke.Effectfv(name, param, v);
|
||||
}
|
||||
|
||||
// Two-element vector forms for the extension pair parameters. The core fv/iv entry points fill
|
||||
// caller memory; float2/int2 are sequential two-field structs, so their address is the buffer.
|
||||
internal static float2 GetSourcefv2(uint name, int param)
|
||||
{
|
||||
var value = default(float2);
|
||||
PInvoke.GetSourcefv(name, param, (float*)&value);
|
||||
return value;
|
||||
}
|
||||
|
||||
internal static void SetSourcefv2(uint name, int param, float2 value) =>
|
||||
PInvoke.Sourcefv(name, param, (float*)&value);
|
||||
|
||||
internal static int2 GetBufferiv2(uint name, int param)
|
||||
{
|
||||
var value = default(int2);
|
||||
PInvoke.GetBufferiv(name, param, (int*)&value);
|
||||
return value;
|
||||
}
|
||||
|
||||
internal static void SetBufferiv2(uint name, int param, int2 value) => PInvoke.Bufferiv(name, param, (int*)&value);
|
||||
|
||||
// Extension double/int64 scalar and pair getters (AL_SOFT_source_latency / ALC_SOFT_device_clock
|
||||
// source halves), over the fnptr-dispatched raw layer.
|
||||
internal static double GetSourcedSOFT(uint name, int param)
|
||||
{
|
||||
var value = 0.0;
|
||||
PInvoke.GetSourcedSOFT(name, param, &value);
|
||||
return value;
|
||||
}
|
||||
|
||||
internal static long GetSourcei64SOFT(uint name, int param)
|
||||
{
|
||||
var value = 0L;
|
||||
PInvoke.GetSourcei64SOFT(name, param, &value);
|
||||
return value;
|
||||
}
|
||||
|
||||
// Tuples, not double2/long2: the two slots hold different quantities.
|
||||
internal static (double A, double B) GetSourcedv2SOFT(uint name, int param)
|
||||
{
|
||||
var pair = stackalloc double[2];
|
||||
PInvoke.GetSourcedvSOFT(name, param, pair);
|
||||
return (pair[0], pair[1]);
|
||||
}
|
||||
|
||||
internal static (long A, long B) GetSourcei64v2SOFT(uint name, int param)
|
||||
{
|
||||
var pair = stackalloc long[2];
|
||||
PInvoke.GetSourcei64vSOFT(name, param, pair);
|
||||
return (pair[0], pair[1]);
|
||||
}
|
||||
}
|
||||
80
Brutal.OpenAl/Manual/Al.Wrapper.cs
Normal file
80
Brutal.OpenAl/Manual/Al.Wrapper.cs
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public static unsafe partial class Al
|
||||
{
|
||||
public static string? GetString(AlGetString param)
|
||||
{
|
||||
// Raw byte* return, copied to managed before anything can invalidate the library-owned
|
||||
// buffer. A null result is either the NULL sentinel or an error.
|
||||
return StringUtils.Utf8ToString(PInvoke.GetString((int)param));
|
||||
}
|
||||
|
||||
public static string[] GetExtensions()
|
||||
{
|
||||
var s = GetString(AlGetString.Extensions);
|
||||
return string.IsNullOrEmpty(s) ? [] : s.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
}
|
||||
|
||||
public static AlDistanceModel DistanceModel
|
||||
{
|
||||
get => (AlDistanceModel)PInvoke.GetInteger(Constants.AL_DISTANCE_MODEL);
|
||||
set => PInvoke.DistanceModel((int)value);
|
||||
}
|
||||
|
||||
public static float DopplerFactor
|
||||
{
|
||||
get => PInvoke.GetFloat(Constants.AL_DOPPLER_FACTOR);
|
||||
set => PInvoke.DopplerFactor(value);
|
||||
}
|
||||
|
||||
public static float SpeedOfSound
|
||||
{
|
||||
get => PInvoke.GetFloat(Constants.AL_SPEED_OF_SOUND);
|
||||
set => PInvoke.SpeedOfSound(value);
|
||||
}
|
||||
|
||||
public static void DeferUpdates() => PInvoke.DeferUpdatesSOFT();
|
||||
|
||||
public static void ProcessUpdates() => PInvoke.ProcessUpdatesSOFT();
|
||||
|
||||
public static DeferredUpdatesScope DeferUpdatesScope()
|
||||
{
|
||||
DeferUpdates();
|
||||
return new DeferredUpdatesScope();
|
||||
}
|
||||
|
||||
public static string[] ResamplerNames
|
||||
{
|
||||
get
|
||||
{
|
||||
var count = PInvoke.GetInteger(Constants.AL_NUM_RESAMPLERS_SOFT);
|
||||
var names = new string[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
names[i] =
|
||||
StringUtils.Utf8ToString(PInvoke.GetStringiSOFT(Constants.AL_RESAMPLER_NAME_SOFT, i))
|
||||
?? string.Empty;
|
||||
}
|
||||
return names;
|
||||
}
|
||||
}
|
||||
|
||||
public static int DefaultResampler => PInvoke.GetInteger(Constants.AL_DEFAULT_RESAMPLER_SOFT);
|
||||
|
||||
public static float GainLimit => PInvoke.GetFloat(Constants.AL_GAIN_LIMIT_SOFT);
|
||||
|
||||
public static void PlaySourcesAt(ReadOnlySpan<AlSource> sources, long deviceClockTime)
|
||||
{
|
||||
if (sources.IsEmpty)
|
||||
return;
|
||||
|
||||
var names = sources.Cast<AlSource, uint>();
|
||||
fixed (uint* p = names)
|
||||
PInvoke.SourcePlayAtTimevSOFT(names.Length, p, deviceClockTime);
|
||||
}
|
||||
}
|
||||
|
||||
public readonly ref struct DeferredUpdatesScope
|
||||
{
|
||||
public void Dispose() => Al.ProcessUpdates();
|
||||
}
|
||||
7
Brutal.OpenAl/Manual/Al.cs
Normal file
7
Brutal.OpenAl/Manual/Al.cs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public static partial class Al
|
||||
{
|
||||
// Logical native library name; mapped to the platform file by NativeLoader's DllImportResolver.
|
||||
internal const string Dll = "openal";
|
||||
}
|
||||
9
Brutal.OpenAl/Manual/AlAuxiliaryEffectSlot.cs
Normal file
9
Brutal.OpenAl/Manual/AlAuxiliaryEffectSlot.cs
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public readonly partial struct AlAuxiliaryEffectSlot
|
||||
{
|
||||
public void Load(AlEffect effect)
|
||||
{
|
||||
Al.PInvoke.AuxiliaryEffectSloti(Name, Al.Constants.AL_EFFECTSLOT_EFFECT, (int)effect.Name);
|
||||
}
|
||||
}
|
||||
14
Brutal.OpenAl/Manual/AlBuffer.cs
Normal file
14
Brutal.OpenAl/Manual/AlBuffer.cs
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public readonly unsafe partial struct AlBuffer
|
||||
{
|
||||
public void SetData(AlFormat format, ReadOnlySpan<byte> data, int sampleRate)
|
||||
{
|
||||
// A successful upload clears any callback; evict its root only once the cookie is gone.
|
||||
var previous = PeekCookie(Name);
|
||||
fixed (byte* p = data)
|
||||
Al.PInvoke.BufferData(Name, (int)format, p, data.Length, sampleRate);
|
||||
if (previous != 0 && BoundCookie(Name) == 0)
|
||||
BufferCallbacks.TryRemove(previous, out _);
|
||||
}
|
||||
}
|
||||
67
Brutal.OpenAl/Manual/AlDebug.Internal.cs
Normal file
67
Brutal.OpenAl/Manual/AlDebug.Internal.cs
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
using System.Collections.Concurrent;
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public static unsafe partial class AlDebug
|
||||
{
|
||||
internal static readonly ConcurrentDictionary<nint, AlDebugCallback> DebugCallbacks = new();
|
||||
|
||||
// Every pull overwrites the arena from offset 0, so returned spans are valid until the next pull.
|
||||
private static byte[]? _arena;
|
||||
|
||||
// Matches the native log capacity; also bounds the stackalloc arrays.
|
||||
private const int LogChunk = 64;
|
||||
|
||||
internal static ReadOnlySpan<byte> ArenaView => _arena;
|
||||
|
||||
private static byte[] EnsureArena()
|
||||
{
|
||||
if (_arena is null)
|
||||
{
|
||||
var messageLength = Al.PInvoke.GetInteger(Al.Constants.AL_MAX_DEBUG_MESSAGE_LENGTH_EXT);
|
||||
var labelLength = Al.PInvoke.GetInteger(Al.Constants.AL_MAX_LABEL_LENGTH_EXT);
|
||||
var size = Math.Max(LogChunk * messageLength, labelLength);
|
||||
|
||||
// Do not cache a zero size; the next call re-queries.
|
||||
if (size <= 0)
|
||||
return [];
|
||||
|
||||
_arena = new byte[size];
|
||||
}
|
||||
return _arena;
|
||||
}
|
||||
|
||||
// Called from Al.EvictContextRoots for every context address that stops being valid.
|
||||
internal static void EvictContextRoots(nint contextPointer) => DebugCallbacks.TryRemove(contextPointer, out _);
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
|
||||
private static void DebugTrampoline(
|
||||
int source,
|
||||
int type,
|
||||
uint id,
|
||||
int severity,
|
||||
int length,
|
||||
byte* message,
|
||||
void* userParam
|
||||
)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (DebugCallbacks.TryGetValue((nint)userParam, out var callback))
|
||||
{
|
||||
callback(
|
||||
(AlDebugSource)source,
|
||||
(AlDebugType)type,
|
||||
id,
|
||||
(AlDebugSeverity)severity,
|
||||
new ReadOnlySpan<byte>(message, length)
|
||||
);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Al.CallbackExceptions.Push("Error in AlDebug callback.", ex);
|
||||
// the message is dropped
|
||||
}
|
||||
}
|
||||
}
|
||||
222
Brutal.OpenAl/Manual/AlDebug.cs
Normal file
222
Brutal.OpenAl/Manual/AlDebug.cs
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
using unsafe DebugTrampolineFn = delegate* unmanaged[Cdecl]<int, int, uint, int, int, byte*, void*, void>;
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public delegate void AlDebugCallback(
|
||||
AlDebugSource source,
|
||||
AlDebugType type,
|
||||
uint id,
|
||||
AlDebugSeverity severity,
|
||||
ReadOnlySpan<byte> message
|
||||
);
|
||||
|
||||
public readonly record struct AlDebugMessageInfo(
|
||||
AlDebugSource Source,
|
||||
AlDebugType Type,
|
||||
uint Id,
|
||||
AlDebugSeverity Severity,
|
||||
int Offset,
|
||||
int Length
|
||||
)
|
||||
{
|
||||
public ReadOnlySpan<byte> Message => AlDebug.ArenaView.Slice(Offset, Length);
|
||||
}
|
||||
|
||||
public readonly ref struct DebugGroupScope
|
||||
{
|
||||
public void Dispose() => AlDebug.PopGroup();
|
||||
}
|
||||
|
||||
public static unsafe partial class AlDebug
|
||||
{
|
||||
public static void Enable() => Al.PInvoke.Enable(Al.Constants.AL_DEBUG_OUTPUT_EXT);
|
||||
|
||||
public static void Disable() => Al.PInvoke.Disable(Al.Constants.AL_DEBUG_OUTPUT_EXT);
|
||||
|
||||
public static void SetCallback(AlDebugCallback? callback)
|
||||
{
|
||||
var context = Alc.PInvoke.GetCurrentContext().Pointer.Value;
|
||||
if (callback is null)
|
||||
{
|
||||
Al.PInvoke.DebugMessageCallbackEXT(null, null);
|
||||
DebugCallbacks.TryRemove(context, out _);
|
||||
return;
|
||||
}
|
||||
|
||||
// Store before the native call so no early event is missed; restore if the call throws.
|
||||
var hadPrevious = DebugCallbacks.TryGetValue(context, out var previous);
|
||||
DebugCallbacks[context] = callback;
|
||||
try
|
||||
{
|
||||
// (&DebugTrampoline) is parenthesized because `(AliasName)&expr` parses as a binary AND, not a cast.
|
||||
Al.PInvoke.DebugMessageCallbackEXT((void*)(DebugTrampolineFn)(&DebugTrampoline), (void*)context);
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (hadPrevious)
|
||||
DebugCallbacks[context] = previous!;
|
||||
else
|
||||
DebugCallbacks.TryRemove(context, out _);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public static void MessageInsert(
|
||||
AlDebugSource source,
|
||||
AlDebugType type,
|
||||
uint id,
|
||||
AlDebugSeverity severity,
|
||||
string message
|
||||
)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(message);
|
||||
using var utf8 = new Utf8Buffer(message, stackalloc byte[Utf8Buffer.StackBufferSize]);
|
||||
fixed (byte* p = utf8.Span)
|
||||
Al.PInvoke.DebugMessageInsertEXT((int)source, (int)type, id, (int)severity, utf8.Length, p);
|
||||
}
|
||||
|
||||
public static void MessageInsert(
|
||||
AlDebugSource source,
|
||||
AlDebugType type,
|
||||
uint id,
|
||||
AlDebugSeverity severity,
|
||||
ReadOnlySpan<byte> message
|
||||
)
|
||||
{
|
||||
fixed (byte* p = message)
|
||||
{
|
||||
// An empty span pins as null, which the native call rejects even at length 0.
|
||||
byte nul = 0;
|
||||
Al.PInvoke.DebugMessageInsertEXT(
|
||||
(int)source,
|
||||
(int)type,
|
||||
id,
|
||||
(int)severity,
|
||||
message.Length,
|
||||
p != null ? p : &nul
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public static void MessageControl(
|
||||
AlDebugSource source,
|
||||
AlDebugType type,
|
||||
AlDebugSeverity severity,
|
||||
ReadOnlySpan<uint> ids,
|
||||
bool enable
|
||||
)
|
||||
{
|
||||
fixed (uint* p = ids)
|
||||
Al.PInvoke.DebugMessageControlEXT((int)source, (int)type, (int)severity, ids.Length, p, enable);
|
||||
}
|
||||
|
||||
public static void PushGroup(AlDebugSource source, uint id, string message)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(message);
|
||||
using var utf8 = new Utf8Buffer(message, stackalloc byte[Utf8Buffer.StackBufferSize]);
|
||||
fixed (byte* p = utf8.Span)
|
||||
Al.PInvoke.PushDebugGroupEXT((int)source, id, utf8.Length, p);
|
||||
}
|
||||
|
||||
public static void PushGroup(AlDebugSource source, uint id, ReadOnlySpan<byte> message)
|
||||
{
|
||||
fixed (byte* p = message)
|
||||
{
|
||||
// Same null-substitution rationale as the span MessageInsert above.
|
||||
byte nul = 0;
|
||||
Al.PInvoke.PushDebugGroupEXT((int)source, id, message.Length, p != null ? p : &nul);
|
||||
}
|
||||
}
|
||||
|
||||
public static void PopGroup() => Al.PInvoke.PopDebugGroupEXT();
|
||||
|
||||
public static DebugGroupScope GroupScope(AlDebugSource source, uint id, string message)
|
||||
{
|
||||
PushGroup(source, id, message);
|
||||
return new DebugGroupScope();
|
||||
}
|
||||
|
||||
public static DebugGroupScope GroupScope(AlDebugSource source, uint id, ReadOnlySpan<byte> message)
|
||||
{
|
||||
PushGroup(source, id, message);
|
||||
return new DebugGroupScope();
|
||||
}
|
||||
|
||||
public static int GetMessageLog(Span<AlDebugMessageInfo> messages)
|
||||
{
|
||||
if (messages.IsEmpty)
|
||||
return 0;
|
||||
|
||||
var arena = EnsureArena();
|
||||
var chunk = Math.Min(messages.Length, LogChunk);
|
||||
Span<int> sources = stackalloc int[chunk];
|
||||
Span<int> types = stackalloc int[chunk];
|
||||
Span<uint> ids = stackalloc uint[chunk];
|
||||
Span<int> severities = stackalloc int[chunk];
|
||||
Span<int> lengths = stackalloc int[chunk];
|
||||
|
||||
uint count;
|
||||
fixed (int* sourcesPtr = sources)
|
||||
fixed (int* typesPtr = types)
|
||||
fixed (uint* idsPtr = ids)
|
||||
fixed (int* severitiesPtr = severities)
|
||||
fixed (int* lengthsPtr = lengths)
|
||||
fixed (byte* textPtr = arena)
|
||||
{
|
||||
count = Al.PInvoke.GetDebugMessageLogEXT(
|
||||
(uint)chunk,
|
||||
arena.Length,
|
||||
sourcesPtr,
|
||||
typesPtr,
|
||||
idsPtr,
|
||||
severitiesPtr,
|
||||
lengthsPtr,
|
||||
textPtr
|
||||
);
|
||||
}
|
||||
|
||||
var offset = 0;
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
// lengths[i] includes the NUL terminator.
|
||||
messages[i] = new AlDebugMessageInfo(
|
||||
(AlDebugSource)sources[i],
|
||||
(AlDebugType)types[i],
|
||||
ids[i],
|
||||
(AlDebugSeverity)severities[i],
|
||||
offset,
|
||||
lengths[i] - 1
|
||||
);
|
||||
offset += lengths[i];
|
||||
}
|
||||
return (int)count;
|
||||
}
|
||||
|
||||
public static void ObjectLabel(AlObjectLabelIdentifier identifier, uint name, string? label)
|
||||
{
|
||||
// A null label pins as a null pointer with length 0, which the native call treats as "clear".
|
||||
using var utf8 = new Utf8Buffer(label, stackalloc byte[Utf8Buffer.StackBufferSize]);
|
||||
fixed (byte* p = utf8.Span)
|
||||
Al.PInvoke.ObjectLabelEXT((int)identifier, name, utf8.Length, p);
|
||||
}
|
||||
|
||||
public static void ObjectLabel(AlObjectLabelIdentifier identifier, uint name, ReadOnlySpan<byte> label)
|
||||
{
|
||||
fixed (byte* p = label)
|
||||
{
|
||||
// An empty span pins as null with length 0, which the native call accepts as "clear" -
|
||||
// no substitution needed here, unlike the message calls.
|
||||
Al.PInvoke.ObjectLabelEXT((int)identifier, name, label.Length, p);
|
||||
}
|
||||
}
|
||||
|
||||
public static ReadOnlySpan<byte> GetObjectLabel(AlObjectLabelIdentifier identifier, uint name)
|
||||
{
|
||||
var arena = EnsureArena();
|
||||
// Native may leave length unwritten or report more than the arena holds.
|
||||
var length = 0;
|
||||
fixed (byte* p = arena)
|
||||
Al.PInvoke.GetObjectLabelEXT((int)identifier, name, arena.Length, &length, p);
|
||||
return arena.AsSpan(0, Math.Clamp(length, 0, arena.Length));
|
||||
}
|
||||
}
|
||||
56
Brutal.OpenAl/Manual/AlSource.Ext.cs
Normal file
56
Brutal.OpenAl/Manual/AlSource.Ext.cs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public readonly record struct AlSampleOffsetLatency(long SampleOffset, long Latency)
|
||||
{
|
||||
public int WholeSamples => (int)(SampleOffset >> 32);
|
||||
}
|
||||
|
||||
public readonly record struct AlSampleOffsetClock(long SampleOffset, long ClockTime)
|
||||
{
|
||||
public int WholeSamples => (int)(SampleOffset >> 32);
|
||||
}
|
||||
|
||||
public readonly record struct AlSecOffsetLatency(double SecOffset, double Latency);
|
||||
|
||||
public readonly record struct AlSecOffsetClock(double SecOffset, double ClockTime);
|
||||
|
||||
public readonly partial struct AlSource
|
||||
{
|
||||
public AlSecOffsetLatency SecOffsetLatency
|
||||
{
|
||||
get
|
||||
{
|
||||
var (offset, latency) = Al.GetSourcedv2SOFT(Name, Al.Constants.AL_SEC_OFFSET_LATENCY_SOFT);
|
||||
return new AlSecOffsetLatency(offset, latency);
|
||||
}
|
||||
}
|
||||
|
||||
public AlSampleOffsetLatency SampleOffsetLatency
|
||||
{
|
||||
get
|
||||
{
|
||||
var (offset, latency) = Al.GetSourcei64v2SOFT(Name, Al.Constants.AL_SAMPLE_OFFSET_LATENCY_SOFT);
|
||||
return new AlSampleOffsetLatency(offset, latency);
|
||||
}
|
||||
}
|
||||
|
||||
public AlSecOffsetClock SecOffsetClock
|
||||
{
|
||||
get
|
||||
{
|
||||
var (offset, clock) = Al.GetSourcedv2SOFT(Name, Al.Constants.AL_SEC_OFFSET_CLOCK_SOFT);
|
||||
return new AlSecOffsetClock(offset, clock);
|
||||
}
|
||||
}
|
||||
|
||||
public AlSampleOffsetClock SampleOffsetClock
|
||||
{
|
||||
get
|
||||
{
|
||||
var (offset, clock) = Al.GetSourcei64v2SOFT(Name, Al.Constants.AL_SAMPLE_OFFSET_CLOCK_SOFT);
|
||||
return new AlSampleOffsetClock(offset, clock);
|
||||
}
|
||||
}
|
||||
|
||||
public void PlayAt(long deviceClockTime) => Al.PInvoke.SourcePlayAtTimeSOFT(Name, deviceClockTime);
|
||||
}
|
||||
29
Brutal.OpenAl/Manual/AlSource.cs
Normal file
29
Brutal.OpenAl/Manual/AlSource.cs
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public readonly unsafe partial struct AlSource
|
||||
{
|
||||
public void QueueBuffers(ReadOnlySpan<AlBuffer> buffers)
|
||||
{
|
||||
if (buffers.IsEmpty)
|
||||
return;
|
||||
|
||||
var names = MemoryMarshal.Cast<AlBuffer, uint>(buffers);
|
||||
fixed (uint* p = names)
|
||||
Al.PInvoke.SourceQueueBuffers(Name, names.Length, p);
|
||||
}
|
||||
|
||||
public void UnqueueBuffers(Span<AlBuffer> buffers)
|
||||
{
|
||||
if (buffers.IsEmpty)
|
||||
return;
|
||||
|
||||
var names = MemoryMarshal.Cast<AlBuffer, uint>(buffers);
|
||||
fixed (uint* p = names)
|
||||
Al.PInvoke.SourceUnqueueBuffers(Name, names.Length, p);
|
||||
}
|
||||
|
||||
public void SetAuxiliarySend(AlAuxiliaryEffectSlot slot, int send, AlFilter filter = default)
|
||||
{
|
||||
Al.PInvoke.Source3i(Name, Al.Constants.AL_AUXILIARY_SEND_FILTER, (int)slot.Name, send, (int)filter.Name);
|
||||
}
|
||||
}
|
||||
117
Brutal.OpenAl/Manual/Alc.Wrapper.Internal.cs
Normal file
117
Brutal.OpenAl/Manual/Alc.Wrapper.Internal.cs
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
using Brutal.Strings;
|
||||
using CommunityToolkit.HighPerformance.Buffers;
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public static unsafe partial class Alc
|
||||
{
|
||||
// Copy returned strings to managed memory before any error query, which may invalidate them.
|
||||
|
||||
// A null result is either the NULL sentinel or an error; the device error is checked only on
|
||||
// that path to disambiguate.
|
||||
internal static string? GetString(AlcDevice device, AlcGetString param)
|
||||
{
|
||||
var p = PInvoke.GetString(device, (int)param);
|
||||
var s = StringUtils.Utf8ToString(p);
|
||||
if (s is null)
|
||||
ThrowIfError(device);
|
||||
return s;
|
||||
}
|
||||
|
||||
internal static string? GetString(AlcCaptureDevice capture, AlcGetString param)
|
||||
{
|
||||
var p = PInvoke.GetString(AsQueryDevice(capture), (int)param);
|
||||
var s = StringUtils.Utf8ToString(p);
|
||||
if (s is null)
|
||||
ThrowIfError(capture);
|
||||
return s;
|
||||
}
|
||||
|
||||
// Zero-copy siblings for the keyed Params.DeviceParams layer. Same error protocol as above,
|
||||
// but the return views the library-owned buffer, so it is only valid until the next ALC string
|
||||
// query. The NULL sentinel becomes an empty span.
|
||||
internal static ReadOnlySpan<byte> GetStringUtf8(AlcDevice device, AlcGetString param)
|
||||
{
|
||||
var p = PInvoke.GetString(device, (int)param);
|
||||
if (p is null)
|
||||
{
|
||||
ThrowIfError(device);
|
||||
return default;
|
||||
}
|
||||
return Utf8.GetNullTerminatedSpan(p);
|
||||
}
|
||||
|
||||
internal static ReadOnlySpan<byte> GetStringUtf8(AlcCaptureDevice capture, AlcGetString param)
|
||||
{
|
||||
var p = PInvoke.GetString(AsQueryDevice(capture), (int)param);
|
||||
if (p is null)
|
||||
{
|
||||
ThrowIfError(capture);
|
||||
return default;
|
||||
}
|
||||
return Utf8.GetNullTerminatedSpan(p);
|
||||
}
|
||||
|
||||
// Backs Alc.GetDefaultDeviceSpecifier and friends: a null pointer means inspect the global
|
||||
// error - throw if set, else the query is legitimately empty.
|
||||
private static string? GetNullDeviceString(AlcGetString param)
|
||||
{
|
||||
var p = PInvoke.GetString(AlcDevice.Null, (int)param);
|
||||
if (p is null)
|
||||
{
|
||||
var err = GetError();
|
||||
if (err != AlcError.NoError)
|
||||
throw new AlcException(err, $"alcGetString(NULL, {param}) failed.");
|
||||
return null;
|
||||
}
|
||||
return StringUtils.Utf8ToString(p);
|
||||
}
|
||||
|
||||
// Backs Alc.GetDeviceSpecifiers and friends; same null-pointer protocol as GetNullDeviceString.
|
||||
private static string[] EnumerateDevices(AlcGetString param)
|
||||
{
|
||||
var p = PInvoke.GetString(AlcDevice.Null, (int)param);
|
||||
if (p is null)
|
||||
{
|
||||
var err = GetError();
|
||||
if (err != AlcError.NoError)
|
||||
throw new AlcException(err, "alcGetString(NULL, ...) device enumeration failed.");
|
||||
return [];
|
||||
}
|
||||
return StringUtils.Utf8ListToStrings(p);
|
||||
}
|
||||
|
||||
internal static int GetInteger(AlcDevice device, AlcInteger param)
|
||||
{
|
||||
int value;
|
||||
PInvoke.GetIntegerv(device, (int)param, 1, &value);
|
||||
return value;
|
||||
}
|
||||
|
||||
internal static int GetInteger(AlcCaptureDevice capture, AlcInteger param) =>
|
||||
GetInteger(AsQueryDevice(capture), param);
|
||||
|
||||
// Capture devices are ALCdevice* natively; the string/integer queries accept either kind.
|
||||
private static AlcDevice AsQueryDevice(AlcCaptureDevice capture) => (void*)capture.Pointer.Value;
|
||||
|
||||
// Flattens an attribute/value list into a rented, zero-terminated buffer (element-wise copy:
|
||||
// ValueTuple layout is not blittable-guaranteed). An empty input returns SpanOwner<int>.Empty,
|
||||
// and fixing an empty span yields a null pointer - the native "no attribute list" - for free.
|
||||
internal static SpanOwner<int> FlattenAttributes(
|
||||
ReadOnlySpan<(AlcContextAttribute Attribute, int Value)> attributes
|
||||
)
|
||||
{
|
||||
if (attributes.IsEmpty)
|
||||
return SpanOwner<int>.Empty;
|
||||
|
||||
var owner = SpanOwner<int>.Allocate(attributes.Length * 2 + 1);
|
||||
var terminated = owner.Span;
|
||||
for (var i = 0; i < attributes.Length; i++)
|
||||
{
|
||||
terminated[i * 2] = (int)attributes[i].Attribute;
|
||||
terminated[i * 2 + 1] = attributes[i].Value;
|
||||
}
|
||||
terminated[attributes.Length * 2] = 0;
|
||||
return owner;
|
||||
}
|
||||
}
|
||||
72
Brutal.OpenAl/Manual/Alc.Wrapper.cs
Normal file
72
Brutal.OpenAl/Manual/Alc.Wrapper.cs
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public static unsafe partial class Alc
|
||||
{
|
||||
public static Device OpenDevice(string? name = null)
|
||||
{
|
||||
// A null name pins as a null native pointer: the default-device case.
|
||||
using var utf8 = new Utf8Buffer(name, stackalloc byte[Utf8Buffer.StackBufferSize]);
|
||||
AlcDevice device;
|
||||
fixed (byte* p = utf8.Span)
|
||||
device = PInvoke.OpenDevice(p);
|
||||
|
||||
// No trustworthy open device yet, so a null return is diagnosed via the global error.
|
||||
if (device.IsNull())
|
||||
throw new AlcException(GetError(), "alcOpenDevice failed.");
|
||||
return new Device(device);
|
||||
}
|
||||
|
||||
public static CaptureDevice CaptureOpenDevice(string? name, uint frequency, AlFormat format, int bufferSize)
|
||||
{
|
||||
// Without a known frame size, CaptureDevice.Samples cannot bound its destination buffer
|
||||
// (alcCaptureSamples writes however many frames it is asked for). Extension formats go
|
||||
// through the overload below, which takes the frame size explicitly.
|
||||
if (CaptureDevice.FrameSize(format) is not { } bytesPerFrame)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(
|
||||
nameof(format),
|
||||
format,
|
||||
"Not one of the four standard AlFormat values, so its frame size is unknown. Use the "
|
||||
+ "CaptureOpenDevice overload taking bytesPerFrame for an extension format."
|
||||
);
|
||||
}
|
||||
|
||||
return CaptureOpenDevice(name, frequency, format, bufferSize, bytesPerFrame);
|
||||
}
|
||||
|
||||
public static CaptureDevice CaptureOpenDevice(
|
||||
string? name,
|
||||
uint frequency,
|
||||
AlFormat format,
|
||||
int bufferSize,
|
||||
int bytesPerFrame
|
||||
)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bytesPerFrame);
|
||||
|
||||
// A null name pins as a null native pointer: the default capture device case.
|
||||
using var utf8 = new Utf8Buffer(name, stackalloc byte[Utf8Buffer.StackBufferSize]);
|
||||
AlcCaptureDevice handle;
|
||||
fixed (byte* p = utf8.Span)
|
||||
handle = PInvoke.CaptureOpenDevice(p, frequency, (int)format, bufferSize);
|
||||
|
||||
if (handle.IsNull())
|
||||
throw new AlcException(GetError(), "alcCaptureOpenDevice failed.");
|
||||
|
||||
return new CaptureDevice(handle, bytesPerFrame);
|
||||
}
|
||||
|
||||
public static string[] GetDeviceSpecifiers() => EnumerateDevices(AlcGetString.DeviceSpecifier);
|
||||
|
||||
public static string[] GetAllDeviceSpecifiers() => EnumerateDevices(AlcGetString.AllDevicesSpecifier);
|
||||
|
||||
public static string[] GetCaptureDeviceSpecifiers() => EnumerateDevices(AlcGetString.CaptureDeviceSpecifier);
|
||||
|
||||
public static string? GetDefaultDeviceSpecifier() => GetNullDeviceString(AlcGetString.DefaultDeviceSpecifier);
|
||||
|
||||
public static string? GetDefaultAllDevicesSpecifier() =>
|
||||
GetNullDeviceString(AlcGetString.DefaultAllDevicesSpecifier);
|
||||
|
||||
public static string? GetCaptureDefaultDeviceSpecifier() =>
|
||||
GetNullDeviceString(AlcGetString.CaptureDefaultDeviceSpecifier);
|
||||
}
|
||||
7
Brutal.OpenAl/Manual/Alc.cs
Normal file
7
Brutal.OpenAl/Manual/Alc.cs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public static partial class Alc
|
||||
{
|
||||
// Logical native library name; mapped to the platform file by NativeLoader's DllImportResolver.
|
||||
internal const string Dll = "openal";
|
||||
}
|
||||
185
Brutal.OpenAl/Manual/Callbacks.Internal.cs
Normal file
185
Brutal.OpenAl/Manual/Callbacks.Internal.cs
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
using System.Collections.Concurrent;
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
// The process-wide latch for exceptions thrown by managed callback handlers. Capped so an
|
||||
// undrained process cannot grow unboundedly: the first Capacity exceptions are kept, the rest
|
||||
// only counted.
|
||||
internal sealed class CallbackExceptionAggregator
|
||||
{
|
||||
private const int Capacity = 16;
|
||||
private readonly List<Exception> _exceptions = [];
|
||||
private int _dropped;
|
||||
private readonly Lock _lock = new();
|
||||
|
||||
public void Push(string message, Exception inner)
|
||||
{
|
||||
try
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_exceptions.Count < Capacity)
|
||||
_exceptions.Add(new Exception(message, inner));
|
||||
else
|
||||
_dropped++;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Never let the latch itself throw back into a native frame.
|
||||
}
|
||||
}
|
||||
|
||||
public void ThrowIfAny()
|
||||
{
|
||||
Exception exception;
|
||||
lock (_lock)
|
||||
{
|
||||
if (_exceptions.Count == 0)
|
||||
return;
|
||||
if (_dropped > 0)
|
||||
_exceptions.Add(new Exception($"{_dropped} further callback exception(s) were dropped."));
|
||||
exception = _exceptions.Count == 1 ? _exceptions[0] : new AggregateException([.. _exceptions]);
|
||||
_exceptions.Clear();
|
||||
_dropped = 0;
|
||||
}
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
public static unsafe partial class Al
|
||||
{
|
||||
internal static readonly CallbackExceptionAggregator CallbackExceptions = new();
|
||||
|
||||
// Keyed by the current context's address, which is passed as userParam.
|
||||
internal static readonly ConcurrentDictionary<nint, AlEventCallback> EventCallbacks = new();
|
||||
|
||||
// Called from Context teardown for every context address that stops being valid.
|
||||
internal static void EvictContextRoots(nint contextPointer)
|
||||
{
|
||||
EventCallbacks.TryRemove(contextPointer, out _);
|
||||
AlDebug.EvictContextRoots(contextPointer);
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
|
||||
private static void AlEventTrampoline(
|
||||
int eventType,
|
||||
uint obj,
|
||||
uint param,
|
||||
int length,
|
||||
byte* message,
|
||||
void* userParam
|
||||
)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (EventCallbacks.TryGetValue((nint)userParam, out var callback))
|
||||
callback((AlEventType)eventType, obj, param, new ReadOnlySpan<byte>(message, length));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
CallbackExceptions.Push("Error in Al event callback.", ex);
|
||||
// the event is dropped
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static unsafe partial class Alc
|
||||
{
|
||||
// ALC_SOFT_system_events is process-global, so a single static field is enough rooting.
|
||||
internal static AlcEventCallback? SystemEventCallback => _systemEventCallback;
|
||||
private static AlcEventCallback? _systemEventCallback;
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
|
||||
private static void AlcEventTrampoline(
|
||||
int eventType,
|
||||
int deviceType,
|
||||
nint device,
|
||||
int length,
|
||||
byte* message,
|
||||
void* userParam
|
||||
)
|
||||
{
|
||||
try
|
||||
{
|
||||
_systemEventCallback?.Invoke(
|
||||
(AlcEventType)eventType,
|
||||
(AlcDeviceType)deviceType,
|
||||
(void*)device,
|
||||
new ReadOnlySpan<byte>(message, length)
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Al.CallbackExceptions.Push("Error in Alc event callback.", ex);
|
||||
// the event is dropped
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public readonly unsafe partial struct AlBuffer
|
||||
{
|
||||
// Keyed by a per-registration cookie, not the buffer name, since names are per-device.
|
||||
private static readonly ConcurrentDictionary<nint, (AlBufferCallback Callback, nint Device)> BufferCallbacks =
|
||||
new();
|
||||
|
||||
private static long _cookieCounter;
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
|
||||
private static int BufferTrampoline(void* userptr, void* sampleData, int numBytes)
|
||||
{
|
||||
try
|
||||
{
|
||||
return BufferCallbacks.TryGetValue((nint)userptr, out var entry)
|
||||
? entry.Callback(new Span<byte>(sampleData, numBytes))
|
||||
: 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Al.CallbackExceptions.Push("Error in AlBuffer callback.", ex);
|
||||
return 0; // the stream goes silent
|
||||
}
|
||||
}
|
||||
|
||||
// The cookie bound to this buffer name, or 0 when no callback is registered.
|
||||
private static nint BoundCookie(uint name)
|
||||
{
|
||||
void* existing = null;
|
||||
Al.PInvoke.GetBufferPtrSOFT(name, Al.Constants.AL_BUFFER_CALLBACK_USER_PARAM_SOFT, &existing);
|
||||
return (nint)existing;
|
||||
}
|
||||
|
||||
private static nint PeekCookie(uint name) => BufferCallbacks.IsEmpty ? 0 : BoundCookie(name);
|
||||
|
||||
// Read cookies before the delete and evict after, only for names that were actually deleted.
|
||||
internal static void DeleteAndEvictCallbackRoots(uint* names, int count)
|
||||
{
|
||||
if (BufferCallbacks.IsEmpty)
|
||||
{
|
||||
Al.PInvoke.DeleteBuffers(count, names);
|
||||
return;
|
||||
}
|
||||
|
||||
// Deletes are not hot enough to justify pooling; the stackalloc covers every sane bulk.
|
||||
Span<nint> cookies = count <= 64 ? stackalloc nint[count] : new nint[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
cookies[i] = BoundCookie(names[i]);
|
||||
|
||||
Al.PInvoke.DeleteBuffers(count, names);
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
if (cookies[i] != 0 && !Al.PInvoke.IsBuffer(names[i]))
|
||||
BufferCallbacks.TryRemove(cookies[i], out _);
|
||||
}
|
||||
}
|
||||
|
||||
internal static void EvictDeviceRoots(nint devicePointer)
|
||||
{
|
||||
foreach (var entry in BufferCallbacks)
|
||||
{
|
||||
if (entry.Value.Device == devicePointer)
|
||||
BufferCallbacks.TryRemove(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
132
Brutal.OpenAl/Manual/Callbacks.cs
Normal file
132
Brutal.OpenAl/Manual/Callbacks.cs
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
using unsafe AlcEventTrampolineFn = delegate* unmanaged[Cdecl]<int, int, nint, int, byte*, void*, void>;
|
||||
using unsafe AlEventTrampolineFn = delegate* unmanaged[Cdecl]<int, uint, uint, int, byte*, void*, void>;
|
||||
using unsafe BufferTrampolineFn = delegate* unmanaged[Cdecl]<void*, void*, int, int>;
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public delegate int AlBufferCallback(Span<byte> destination);
|
||||
|
||||
public delegate void AlEventCallback(AlEventType eventType, uint @object, uint parameter, ReadOnlySpan<byte> message);
|
||||
|
||||
public delegate void AlcEventCallback(
|
||||
AlcEventType eventType,
|
||||
AlcDeviceType deviceType,
|
||||
AlcDevice device,
|
||||
ReadOnlySpan<byte> message
|
||||
);
|
||||
|
||||
public static unsafe partial class Al
|
||||
{
|
||||
public static void ThrowCallbackExceptions() => CallbackExceptions.ThrowIfAny();
|
||||
|
||||
public static void EventControl(ReadOnlySpan<AlEventType> types, bool enable)
|
||||
{
|
||||
var raw = MemoryMarshal.Cast<AlEventType, int>(types);
|
||||
fixed (int* p = raw)
|
||||
PInvoke.EventControlSOFT(raw.Length, p, enable);
|
||||
}
|
||||
|
||||
public static void SetEventCallback(AlEventCallback? callback)
|
||||
{
|
||||
var context = Alc.PInvoke.GetCurrentContext().Pointer.Value;
|
||||
if (callback is null)
|
||||
{
|
||||
PInvoke.EventCallbackSOFT(null, null);
|
||||
EventCallbacks.TryRemove(context, out _);
|
||||
return;
|
||||
}
|
||||
|
||||
// Store before the native call so no early event is missed; restore if the call throws.
|
||||
var hadPrevious = EventCallbacks.TryGetValue(context, out var previous);
|
||||
EventCallbacks[context] = callback;
|
||||
try
|
||||
{
|
||||
// (&Trampoline) is parenthesized because `(AliasName)&expr` parses as a binary AND, not a cast.
|
||||
PInvoke.EventCallbackSOFT((void*)(AlEventTrampolineFn)(&AlEventTrampoline), (void*)context);
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (hadPrevious)
|
||||
EventCallbacks[context] = previous!;
|
||||
else
|
||||
EventCallbacks.TryRemove(context, out _);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static unsafe partial class Alc
|
||||
{
|
||||
public static bool IsEventSupported(AlcEventType eventType, AlcDeviceType deviceType) =>
|
||||
PInvoke.EventIsSupportedSOFT((int)eventType, (int)deviceType) == Constants.ALC_EVENT_SUPPORTED_SOFT;
|
||||
|
||||
public static bool EventControl(ReadOnlySpan<AlcEventType> events, bool enable)
|
||||
{
|
||||
var raw = MemoryMarshal.Cast<AlcEventType, int>(events);
|
||||
fixed (int* p = raw)
|
||||
return PInvoke.EventControlSOFT(raw.Length, p, enable);
|
||||
}
|
||||
|
||||
public static void SetEventCallback(AlcEventCallback? callback)
|
||||
{
|
||||
if (callback is null)
|
||||
{
|
||||
PInvoke.EventCallbackSOFT(null, null);
|
||||
_systemEventCallback = null;
|
||||
return;
|
||||
}
|
||||
|
||||
// Store before the native call so no early event is missed; restore if the call throws.
|
||||
var previous = _systemEventCallback;
|
||||
_systemEventCallback = callback;
|
||||
try
|
||||
{
|
||||
PInvoke.EventCallbackSOFT((AlcEventTrampolineFn)(&AlcEventTrampoline), null);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_systemEventCallback = previous;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public readonly unsafe partial struct AlBuffer
|
||||
{
|
||||
public void SetCallback(AlFormat format, int frequency, AlBufferCallback callback)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(callback);
|
||||
var previous = BoundCookie(Name);
|
||||
var cookie = (nint)Interlocked.Increment(ref _cookieCounter);
|
||||
BufferCallbacks[cookie] = (callback, 0);
|
||||
Al.PInvoke.BufferCallbackSOFT(
|
||||
Name,
|
||||
(int)format,
|
||||
frequency,
|
||||
(BufferTrampolineFn)(&BufferTrampoline),
|
||||
(void*)cookie
|
||||
);
|
||||
|
||||
// Failure is reported only on the error latch, so read back the bound cookie to see if it took.
|
||||
if (BoundCookie(Name) == cookie)
|
||||
{
|
||||
var device = Alc.PInvoke.GetContextsDevice(Alc.PInvoke.GetCurrentContext());
|
||||
BufferCallbacks[cookie] = (callback, device.Pointer.Value);
|
||||
if (previous != 0)
|
||||
BufferCallbacks.TryRemove(previous, out _);
|
||||
}
|
||||
else
|
||||
{
|
||||
BufferCallbacks.TryRemove(cookie, out _);
|
||||
}
|
||||
}
|
||||
|
||||
public void ClearCallback()
|
||||
{
|
||||
// A NULL callback is rejected, so detach by re-specifying empty data.
|
||||
var previous = BoundCookie(Name);
|
||||
Al.PInvoke.BufferData(Name, (int)AlFormat.Mono16, null, 0, 1);
|
||||
if (previous != 0 && BoundCookie(Name) == 0)
|
||||
BufferCallbacks.TryRemove(previous, out _);
|
||||
}
|
||||
}
|
||||
30
Brutal.OpenAl/Manual/CaptureDevice.Internal.cs
Normal file
30
Brutal.OpenAl/Manual/CaptureDevice.Internal.cs
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public sealed partial class CaptureDevice
|
||||
{
|
||||
// The four standard formats are the only values AlFormat defines; anything else is an
|
||||
// extension or invalid format with no fixed frame size.
|
||||
internal static int? FrameSize(AlFormat format) =>
|
||||
format switch
|
||||
{
|
||||
AlFormat.Mono8 => 1,
|
||||
AlFormat.Mono16 => 2,
|
||||
AlFormat.Stereo8 => 2,
|
||||
AlFormat.Stereo16 => 4,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
// Multiply as long so the bound cannot overflow.
|
||||
internal static void CheckBufferLength(int bytesPerFrame, int samples, int bufferLength)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(samples);
|
||||
|
||||
if (bufferLength < (long)samples * bytesPerFrame)
|
||||
{
|
||||
throw new ArgumentException(
|
||||
$"buffer must hold at least {samples} * {bytesPerFrame} = {(long)samples * bytesPerFrame} bytes, but was {bufferLength}.",
|
||||
"buffer"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
92
Brutal.OpenAl/Manual/CaptureDevice.cs
Normal file
92
Brutal.OpenAl/Manual/CaptureDevice.cs
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public sealed partial class CaptureDevice : IDisposable, INullable
|
||||
{
|
||||
public AlcCaptureDevice Handle { get; private set; }
|
||||
|
||||
// Bytes per sample frame of the capture format; bounds Samples().
|
||||
private readonly int _bytesPerFrame;
|
||||
|
||||
private string? _specifier;
|
||||
|
||||
internal CaptureDevice(AlcCaptureDevice handle, int bytesPerFrame)
|
||||
{
|
||||
Handle = handle;
|
||||
_bytesPerFrame = bytesPerFrame;
|
||||
}
|
||||
|
||||
private AlcCaptureDevice CheckedHandle
|
||||
{
|
||||
get
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return Handle;
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsNull() => Handle.IsNull();
|
||||
|
||||
public string? Specifier
|
||||
{
|
||||
get
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return _specifier ??= Alc.GetString(Handle, AlcGetString.CaptureDeviceSpecifier);
|
||||
}
|
||||
}
|
||||
|
||||
public int AvailableSamples => Alc.GetInteger(CheckedHandle, AlcInteger.CaptureSamples);
|
||||
|
||||
public AlcError GetError()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return Alc.GetError(Handle);
|
||||
}
|
||||
|
||||
public void ThrowIfError()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
Alc.ThrowIfError(Handle);
|
||||
}
|
||||
|
||||
public void Start() => Alc.PInvoke.CaptureStart(CheckedHandle);
|
||||
|
||||
public void Stop() => Alc.PInvoke.CaptureStop(CheckedHandle);
|
||||
|
||||
public void Samples(Span<byte> buffer, int samples)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
CheckBufferLength(_bytesPerFrame, samples, buffer.Length);
|
||||
|
||||
unsafe
|
||||
{
|
||||
fixed (byte* p = buffer)
|
||||
Alc.PInvoke.CaptureSamples(Handle, p, samples);
|
||||
}
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
if (!CloseCore())
|
||||
throw new AlcException(Alc.GetError(), "alcCaptureCloseDevice failed.");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (IsNull())
|
||||
return;
|
||||
|
||||
// Dispose must not throw; Close() is the path that reports a failed close.
|
||||
CloseCore();
|
||||
}
|
||||
|
||||
private bool CloseCore()
|
||||
{
|
||||
var closed = Alc.PInvoke.CaptureCloseDevice(Handle);
|
||||
Handle = AlcCaptureDevice.Null;
|
||||
return closed;
|
||||
}
|
||||
|
||||
public static implicit operator AlcCaptureDevice(CaptureDevice capture) => capture.Handle;
|
||||
}
|
||||
37
Brutal.OpenAl/Manual/Context.Internal.cs
Normal file
37
Brutal.OpenAl/Manual/Context.Internal.cs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
using System.Collections.Concurrent;
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public sealed partial class Context
|
||||
{
|
||||
// Weak so an abandoned wrapper is never kept alive; leaked entries are pruned on registration.
|
||||
private static readonly ConcurrentDictionary<AlcContext.Handle, WeakReference<Context>> LiveContexts = new();
|
||||
|
||||
internal static List<Context> EvictDeviceEntries(Device device)
|
||||
{
|
||||
List<Context> orphans = [];
|
||||
|
||||
foreach (var entry in LiveContexts)
|
||||
{
|
||||
if (!entry.Value.TryGetTarget(out var context))
|
||||
{
|
||||
LiveContexts.TryRemove(entry);
|
||||
Al.EvictContextRoots(entry.Key.Value);
|
||||
}
|
||||
else if (ReferenceEquals(context.Device, device))
|
||||
{
|
||||
LiveContexts.TryRemove(entry);
|
||||
Al.EvictContextRoots(entry.Key.Value);
|
||||
orphans.Add(context);
|
||||
}
|
||||
}
|
||||
|
||||
return orphans;
|
||||
}
|
||||
|
||||
internal static void MarkOrphaned(List<Context> orphans)
|
||||
{
|
||||
foreach (var context in orphans)
|
||||
context.Handle = AlcContext.Null;
|
||||
}
|
||||
}
|
||||
156
Brutal.OpenAl/Manual/Context.cs
Normal file
156
Brutal.OpenAl/Manual/Context.cs
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public sealed partial class Context : IDisposable, INullable
|
||||
{
|
||||
public ref struct CreateInfo()
|
||||
{
|
||||
public ReadOnlySpan<(AlcContextAttribute Attribute, int Value)> Attributes = [];
|
||||
}
|
||||
|
||||
public Device Device { get; }
|
||||
|
||||
public AlcContext Handle { get; private set; }
|
||||
|
||||
public static Context? Current
|
||||
{
|
||||
get
|
||||
{
|
||||
var current = Alc.PInvoke.GetCurrentContext();
|
||||
if (current.IsNull())
|
||||
return null;
|
||||
return LiveContexts.TryGetValue(current.Pointer, out var weak) && weak.TryGetTarget(out var context)
|
||||
? context
|
||||
: null;
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsCurrent => !IsNull() && Handle.Pointer == Alc.PInvoke.GetCurrentContext().Pointer;
|
||||
|
||||
internal unsafe Context(Device device, CreateInfo info)
|
||||
{
|
||||
Device = device;
|
||||
|
||||
// An empty attribute list flattens to a null pointer - see Alc.FlattenAttributes.
|
||||
using var owner = Alc.FlattenAttributes(info.Attributes);
|
||||
fixed (int* p = owner.Span)
|
||||
Handle = Alc.PInvoke.CreateContext(device, p);
|
||||
|
||||
// Failure detail is recorded on the input device, not globally.
|
||||
if (Handle.IsNull())
|
||||
throw new AlcException(Alc.GetError(device), "alcCreateContext failed.");
|
||||
|
||||
// Prune entries for leaked wrappers; remove by (key, value) so a re-registered entry survives.
|
||||
foreach (var entry in LiveContexts)
|
||||
{
|
||||
if (!entry.Value.TryGetTarget(out _))
|
||||
LiveContexts.TryRemove(entry);
|
||||
}
|
||||
LiveContexts[Handle.Pointer] = new WeakReference<Context>(this);
|
||||
}
|
||||
|
||||
public bool IsNull() => Handle.IsNull();
|
||||
|
||||
public static void MakeCurrent(Context? context)
|
||||
{
|
||||
if (context is null)
|
||||
{
|
||||
if (!Alc.PInvoke.MakeContextCurrent(AlcContext.Null))
|
||||
throw new AlcException(Alc.GetError(), "alcMakeContextCurrent(NULL) failed.");
|
||||
return;
|
||||
}
|
||||
|
||||
// alcMakeContextCurrent(NULL) detaches, so a disposed context must throw, not pass through.
|
||||
if (context.IsNull())
|
||||
throw new AlcException(AlcError.InvalidContext, "The context has been disposed.");
|
||||
|
||||
// Failure detail is recorded on the context's device.
|
||||
if (!Alc.PInvoke.MakeContextCurrent(context.Handle))
|
||||
throw new AlcException(Alc.GetError(context.Device), "alcMakeContextCurrent failed.");
|
||||
}
|
||||
|
||||
public static bool TryMakeCurrent(Context? context)
|
||||
{
|
||||
if (context is null)
|
||||
return Alc.PInvoke.MakeContextCurrent(AlcContext.Null);
|
||||
return !context.IsNull() && Alc.PInvoke.MakeContextCurrent(context.Handle);
|
||||
}
|
||||
|
||||
public void MakeCurrent() => MakeCurrent(this);
|
||||
|
||||
public bool TryMakeCurrent() => TryMakeCurrent(this);
|
||||
|
||||
public static Context? CurrentThread
|
||||
{
|
||||
get
|
||||
{
|
||||
var current = Alc.PInvoke.GetThreadContext();
|
||||
if (current.IsNull())
|
||||
return null;
|
||||
return LiveContexts.TryGetValue(current.Pointer, out var weak) && weak.TryGetTarget(out var context)
|
||||
? context
|
||||
: null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void MakeThreadCurrent(Context? context)
|
||||
{
|
||||
if (context is null)
|
||||
{
|
||||
if (!Alc.PInvoke.SetThreadContext(AlcContext.Null))
|
||||
throw new AlcException(Alc.GetError(), "alcSetThreadContext(NULL) failed.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (context.IsNull())
|
||||
throw new AlcException(AlcError.InvalidContext, "The context has been disposed.");
|
||||
|
||||
// Failure detail is recorded on the context's device.
|
||||
if (!Alc.PInvoke.SetThreadContext(context.Handle))
|
||||
throw new AlcException(Alc.GetError(context.Device), "alcSetThreadContext failed.");
|
||||
}
|
||||
|
||||
public static bool TryMakeThreadCurrent(Context? context)
|
||||
{
|
||||
if (context is null)
|
||||
return Alc.PInvoke.SetThreadContext(AlcContext.Null);
|
||||
return !context.IsNull() && Alc.PInvoke.SetThreadContext(context.Handle);
|
||||
}
|
||||
|
||||
public void MakeThreadCurrent() => MakeThreadCurrent(this);
|
||||
|
||||
public bool TryMakeThreadCurrent() => TryMakeThreadCurrent(this);
|
||||
|
||||
private AlcContext CheckedHandle
|
||||
{
|
||||
get
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return Handle;
|
||||
}
|
||||
}
|
||||
|
||||
public void Process() => Alc.PInvoke.ProcessContext(CheckedHandle);
|
||||
|
||||
public void Suspend() => Alc.PInvoke.SuspendContext(CheckedHandle);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (IsNull())
|
||||
return;
|
||||
|
||||
// While this context is alive the native object still occupies its address, so the entry
|
||||
// under this key is necessarily our own.
|
||||
LiveContexts.TryRemove(Handle.Pointer, out _);
|
||||
|
||||
// Release any callback handlers rooted under this address (Al events, AlDebug) so a
|
||||
// recycled context address can never resolve to a stale handler.
|
||||
Al.EvictContextRoots(Handle.Pointer.Value);
|
||||
|
||||
// alcDestroyContext returns nothing; an invalid context sets the global error - check
|
||||
// Alc.GetError() explicitly if you need to know.
|
||||
Alc.PInvoke.DestroyContext(Handle);
|
||||
Handle = AlcContext.Null;
|
||||
}
|
||||
|
||||
public static implicit operator AlcContext(Context context) => context.Handle;
|
||||
}
|
||||
311
Brutal.OpenAl/Manual/Device.cs
Normal file
311
Brutal.OpenAl/Manual/Device.cs
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.HighPerformance.Buffers;
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public readonly record struct AlcClockLatency(long ClockTime, long Latency);
|
||||
|
||||
public sealed class Device : IDisposable, INullable
|
||||
{
|
||||
private readonly bool _ownedByLoopback;
|
||||
|
||||
public AlcDevice Handle { get; private set; }
|
||||
|
||||
internal Device(AlcDevice handle, bool ownedByLoopback = false)
|
||||
{
|
||||
Handle = handle;
|
||||
_ownedByLoopback = ownedByLoopback;
|
||||
}
|
||||
|
||||
private AlcDevice CheckedHandle
|
||||
{
|
||||
get
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
return Handle;
|
||||
}
|
||||
}
|
||||
|
||||
internal void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
|
||||
private Efx? _efx;
|
||||
|
||||
// Reopen invalidates the specifier caches; Reset and Reopen invalidate the HRTF cache.
|
||||
private string? _specifier;
|
||||
private string? _allDevicesSpecifier;
|
||||
private ReadOnlyCollection<string>? _extensions;
|
||||
private ReadOnlyCollection<string>? _hrtfSpecifiers;
|
||||
private int? _majorVersion;
|
||||
private int? _minorVersion;
|
||||
|
||||
public Efx Efx
|
||||
{
|
||||
get
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
return _efx ??= new Efx(this);
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsNull() => Handle.IsNull();
|
||||
|
||||
public string? Specifier
|
||||
{
|
||||
get
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return _specifier ??= Alc.GetString(Handle, AlcGetString.DeviceSpecifier);
|
||||
}
|
||||
}
|
||||
|
||||
public string? AllDevicesSpecifier
|
||||
{
|
||||
get
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return _allDevicesSpecifier ??= Alc.GetString(Handle, AlcGetString.AllDevicesSpecifier);
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<string> Extensions
|
||||
{
|
||||
get
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
if (_extensions is null)
|
||||
{
|
||||
var s = Alc.GetString(Handle, AlcGetString.Extensions);
|
||||
_extensions = Array.AsReadOnly(
|
||||
string.IsNullOrEmpty(s) ? [] : s.Split(' ', StringSplitOptions.RemoveEmptyEntries)
|
||||
);
|
||||
}
|
||||
return _extensions;
|
||||
}
|
||||
}
|
||||
|
||||
public int MajorVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return _majorVersion ??= Alc.GetInteger(Handle, AlcInteger.MajorVersion);
|
||||
}
|
||||
}
|
||||
|
||||
public int MinorVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return _minorVersion ??= Alc.GetInteger(Handle, AlcInteger.MinorVersion);
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe (AlcContextAttribute Attribute, int Value)[] Attributes
|
||||
{
|
||||
get
|
||||
{
|
||||
// Two-call native protocol, encapsulated: ALC_ATTRIBUTES_SIZE reports the list length
|
||||
// (including its zero terminator), ALC_ALL_ATTRIBUTES fills the buffer. The terminator
|
||||
// is trimmed and the flat ints paired up.
|
||||
var size = Alc.GetInteger(CheckedHandle, AlcInteger.AttributesSize);
|
||||
if (size <= 0)
|
||||
return [];
|
||||
|
||||
using var owner = SpanOwner<int>.Allocate(size);
|
||||
var flat = owner.Span;
|
||||
fixed (int* p = flat)
|
||||
Alc.PInvoke.GetIntegerv(Handle, (int)AlcInteger.AllAttributes, size, p);
|
||||
|
||||
var count = flat[size - 1] == 0 ? size - 1 : size;
|
||||
var pairs = new (AlcContextAttribute, int)[count / 2];
|
||||
for (var i = 0; i < pairs.Length; i++)
|
||||
pairs[i] = ((AlcContextAttribute)flat[i * 2], flat[i * 2 + 1]);
|
||||
return pairs;
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsExtensionPresent(string name) => Alc.IsExtensionPresent(CheckedHandle, name);
|
||||
|
||||
public unsafe void* GetProcAddress(string name) => Alc.GetProcAddress(CheckedHandle, name);
|
||||
|
||||
public AlcError GetError()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return Alc.GetError(Handle);
|
||||
}
|
||||
|
||||
public void ThrowIfError()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
Alc.ThrowIfError(Handle);
|
||||
}
|
||||
|
||||
public Context CreateContext(Context.CreateInfo info = default)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return new(this, info);
|
||||
}
|
||||
|
||||
public void Pause() => Alc.PInvoke.DevicePauseSOFT(CheckedHandle);
|
||||
|
||||
public void Resume() => Alc.PInvoke.DeviceResumeSOFT(CheckedHandle);
|
||||
|
||||
public bool Connected => Alc.GetInteger(CheckedHandle, AlcInteger.Connected) != 0;
|
||||
|
||||
public unsafe long ClockTime
|
||||
{
|
||||
get
|
||||
{
|
||||
long value = 0;
|
||||
Alc.PInvoke.GetInteger64vSOFT(CheckedHandle, Alc.Constants.ALC_DEVICE_CLOCK_SOFT, 1, &value);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe long Latency
|
||||
{
|
||||
get
|
||||
{
|
||||
long value = 0;
|
||||
Alc.PInvoke.GetInteger64vSOFT(CheckedHandle, Alc.Constants.ALC_DEVICE_LATENCY_SOFT, 1, &value);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe AlcClockLatency ClockLatency
|
||||
{
|
||||
get
|
||||
{
|
||||
var pair = stackalloc long[2];
|
||||
Alc.PInvoke.GetInteger64vSOFT(CheckedHandle, Alc.Constants.ALC_DEVICE_CLOCK_LATENCY_SOFT, 2, pair);
|
||||
return new AlcClockLatency(pair[0], pair[1]);
|
||||
}
|
||||
}
|
||||
|
||||
public AlcHrtfStatus HrtfStatus => (AlcHrtfStatus)Alc.GetInteger(CheckedHandle, AlcInteger.HrtfStatus);
|
||||
|
||||
public IReadOnlyList<string> HrtfSpecifiers
|
||||
{
|
||||
get
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
if (_hrtfSpecifiers is null)
|
||||
{
|
||||
var count = Alc.GetInteger(Handle, AlcInteger.NumHrtfSpecifiers);
|
||||
var names = new string[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
names[i] =
|
||||
StringUtils.Utf8ToString(
|
||||
Alc.PInvoke.GetStringiSOFT(Handle, Alc.Constants.ALC_HRTF_SPECIFIER_SOFT, i)
|
||||
) ?? string.Empty;
|
||||
}
|
||||
}
|
||||
_hrtfSpecifiers = Array.AsReadOnly(names);
|
||||
}
|
||||
return _hrtfSpecifiers;
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe void Reset(ReadOnlySpan<(AlcContextAttribute Attribute, int Value)> attributes = default)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
using var owner = Alc.FlattenAttributes(attributes);
|
||||
fixed (int* p = owner.Span)
|
||||
{
|
||||
if (!Alc.PInvoke.ResetDeviceSOFT(Handle, p))
|
||||
throw new AlcException(Alc.GetError(Handle), "alcResetDeviceSOFT failed.");
|
||||
}
|
||||
|
||||
// A reset renegotiates the attribute list: the HRTF set and the auxiliary-send count can
|
||||
// both change. The device's identity (specifiers) cannot.
|
||||
_hrtfSpecifiers = null;
|
||||
_efx?.InvalidateDeviceCaches();
|
||||
}
|
||||
|
||||
public unsafe void Reopen(
|
||||
string? deviceName,
|
||||
ReadOnlySpan<(AlcContextAttribute Attribute, int Value)> attributes = default
|
||||
)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
using var owner = Alc.FlattenAttributes(attributes);
|
||||
using var utf8 = new Utf8Buffer(deviceName, stackalloc byte[Utf8Buffer.StackBufferSize]);
|
||||
fixed (int* attribs = owner.Span)
|
||||
fixed (byte* name = utf8.Span)
|
||||
{
|
||||
if (!Alc.PInvoke.ReopenDeviceSOFT(Handle, name, attribs))
|
||||
throw new AlcException(Alc.GetError(Handle), "alcReopenDeviceSOFT failed.");
|
||||
}
|
||||
|
||||
// A reopen can change the underlying device (new specifiers) and renegotiates the
|
||||
// attribute list like Reset does. Versions and the extension list are properties of the
|
||||
// loaded implementation, not the device, and survive.
|
||||
_specifier = null;
|
||||
_allDevicesSpecifier = null;
|
||||
_hrtfSpecifiers = null;
|
||||
_efx?.InvalidateDeviceCaches();
|
||||
}
|
||||
|
||||
public AlcOutputMode OutputMode => (AlcOutputMode)Alc.GetInteger(CheckedHandle, AlcInteger.OutputMode);
|
||||
|
||||
public void Close()
|
||||
{
|
||||
if (_ownedByLoopback)
|
||||
throw new InvalidOperationException("Close the owning LoopbackDevice instead.");
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
CloseUnchecked();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_ownedByLoopback)
|
||||
return;
|
||||
DisposeUnchecked();
|
||||
}
|
||||
|
||||
// Close() without the ownership and disposal guards. Also the entry point LoopbackDevice
|
||||
// uses on its plumbing Device, whose public Close() rejects direct use.
|
||||
internal void CloseUnchecked()
|
||||
{
|
||||
if (!CloseCore())
|
||||
throw new AlcException(Alc.GetError(), "alcCloseDevice failed (invalid or already-closed handle).");
|
||||
}
|
||||
|
||||
// Dispose() without the ownership guard. Also the entry point LoopbackDevice uses on its
|
||||
// plumbing Device, whose public Dispose() is a no-op.
|
||||
internal void DisposeUnchecked()
|
||||
{
|
||||
if (IsNull())
|
||||
return;
|
||||
|
||||
// Dispose must not throw; Close() is the path that reports a failed close.
|
||||
CloseCore();
|
||||
}
|
||||
|
||||
private bool CloseCore()
|
||||
{
|
||||
// Evict before the native close so a freed context address is never left mapped.
|
||||
var orphans = Context.EvictDeviceEntries(this);
|
||||
|
||||
// Closing also destroys the device's buffers without any per-buffer delete running, so
|
||||
// the buffer-callback handler roots recorded under this device are swept with it.
|
||||
AlBuffer.EvictDeviceRoots(Handle.Pointer.Value);
|
||||
|
||||
// A successful close frees the device, so it must not be queried afterwards; on failure
|
||||
// the global error holds the reason.
|
||||
var closed = Alc.PInvoke.CloseDevice(Handle);
|
||||
|
||||
// On failure the contexts are still alive natively, so only mark them orphaned on success.
|
||||
if (closed)
|
||||
Context.MarkOrphaned(orphans);
|
||||
|
||||
Handle = AlcDevice.Null;
|
||||
return closed;
|
||||
}
|
||||
|
||||
public static implicit operator AlcDevice(Device device) => device.Handle;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue