mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-28 14:08:25 +01:00
SOURCE DUMP v1
This commit is contained in:
parent
bd62d51ec9
commit
fb20299e9d
29 changed files with 768360 additions and 0 deletions
38
brutal.openal/Brutal.OpenAl/Manual/Al.Listener.cs
Normal file
38
brutal.openal/Brutal.OpenAl/Manual/Al.Listener.cs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
// The hand-written half of Al.Listener: only Orientation, the 6-float fv pair (two float3s in one
|
||||
// native array - no generated property shape). The scalar/3f properties (Gain, Position, Velocity,
|
||||
// MetersPerUnit) are generated - see Generated/Al/Al.Listener.Properties.gen.cs.
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public static unsafe partial class Al
|
||||
{
|
||||
/// <summary>
|
||||
/// The listener - the single per-context point OpenAL renders audio for. Accessors act on the
|
||||
/// context current on the calling thread.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// For parameter access keyed by enum, see
|
||||
/// <see cref="Brutal.OpenAlApi.Params.ListenerParams"/>.
|
||||
/// </remarks>
|
||||
public static partial class Listener
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets/sets the listener's orientation (<c>AL_ORIENTATION</c>): an "at" (forward)
|
||||
/// vector and an "up" vector.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
80
brutal.openal/Brutal.OpenAl/Manual/Al.Wrapper.Internal.cs
Normal file
80
brutal.openal/Brutal.OpenAl/Manual/Al.Wrapper.Internal.cs
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
// The internal half of the handle-less AL surface (public half: Al.Wrapper.cs): the vector-shaped
|
||||
// marshalling helpers covering the shapes the generated scalar getters don't.
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public static unsafe partial class Al
|
||||
{
|
||||
// --- EFX fv helpers ------------------------------------------------------------------------------
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// --- alext.h pair/scalar helpers -------------------------------------------------------------------
|
||||
|
||||
// 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 (see the AlSource.Ext.cs
|
||||
// header); the callers name the halves via record structs.
|
||||
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]);
|
||||
}
|
||||
}
|
||||
142
brutal.openal/Brutal.OpenAl/Manual/Al.Wrapper.cs
Normal file
142
brutal.openal/Brutal.OpenAl/Manual/Al.Wrapper.cs
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
// Handle-less AL operations: listener and global state, and GetString/GetExtensions. Handle-first
|
||||
// operations are members on AlSource/AlBuffer; the Gen*/Delete* span methods are generated.
|
||||
// Nothing here checks the AL error state automatically (call Al.ThrowIfError() explicitly), and
|
||||
// handle inputs are not pre-validated: a bad object name sets AL_INVALID_NAME natively.
|
||||
//
|
||||
// Public half of the partial class; the vector-shaped marshalling helpers live in
|
||||
// Al.Wrapper.Internal.cs.
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public static unsafe partial class Al
|
||||
{
|
||||
// --- Strings -----------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Gets an AL string property (<c>alGetString</c>): vendor, version, renderer, or the
|
||||
/// extension list. <see langword="null"/> when OpenAL returns its NULL sentinel.
|
||||
/// </summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>Gets the space-separated AL extension list (<c>AL_EXTENSIONS</c>) as an array.</summary>
|
||||
public static string[] GetExtensions()
|
||||
{
|
||||
var s = GetString(AlGetString.Extensions);
|
||||
return string.IsNullOrEmpty(s) ? [] : s.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
}
|
||||
|
||||
// --- Global state ----------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>Gets/sets the distance attenuation model (<c>AL_DISTANCE_MODEL</c>).</summary>
|
||||
public static AlDistanceModel DistanceModel
|
||||
{
|
||||
get => (AlDistanceModel)PInvoke.GetInteger(Constants.AL_DISTANCE_MODEL);
|
||||
set => PInvoke.DistanceModel((int)value);
|
||||
}
|
||||
|
||||
/// <summary>Gets/sets the Doppler factor (<c>AL_DOPPLER_FACTOR</c>, default 1).</summary>
|
||||
public static float DopplerFactor
|
||||
{
|
||||
get => PInvoke.GetFloat(Constants.AL_DOPPLER_FACTOR);
|
||||
set => PInvoke.DopplerFactor(value);
|
||||
}
|
||||
|
||||
/// <summary>Gets/sets the speed of sound used for Doppler (<c>AL_SPEED_OF_SOUND</c>, default 343.3).</summary>
|
||||
public static float SpeedOfSound
|
||||
{
|
||||
get => PInvoke.GetFloat(Constants.AL_SPEED_OF_SOUND);
|
||||
set => PInvoke.SpeedOfSound(value);
|
||||
}
|
||||
|
||||
// --- Deferred updates, resampler queries, gain limit, and start-delay --------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Defers applying source/effect-slot state changes until <see cref="ProcessUpdates"/>
|
||||
/// (<c>alDeferUpdatesSOFT</c>), so a batch of changes takes effect atomically instead of one at a
|
||||
/// time. Provided by <c>AL_SOFT_deferred_updates</c>.
|
||||
/// </summary>
|
||||
public static void DeferUpdates() => PInvoke.DeferUpdatesSOFT();
|
||||
|
||||
/// <summary>
|
||||
/// Applies state changes deferred since <see cref="DeferUpdates"/> (<c>alProcessUpdatesSOFT</c>).
|
||||
/// Provided by <c>AL_SOFT_deferred_updates</c>.
|
||||
/// </summary>
|
||||
public static void ProcessUpdates() => PInvoke.ProcessUpdatesSOFT();
|
||||
|
||||
/// <summary>
|
||||
/// Defers updates for the returned scope's lifetime (pairs <see cref="DeferUpdates"/> with
|
||||
/// <see cref="ProcessUpdates"/> for a <see langword="using"/> block). Provided by
|
||||
/// <c>AL_SOFT_deferred_updates</c>.
|
||||
/// </summary>
|
||||
public static DeferredUpdatesScope DeferUpdatesScope()
|
||||
{
|
||||
DeferUpdates();
|
||||
return new DeferredUpdatesScope();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The names of the available resamplers (<c>AL_RESAMPLER_NAME_SOFT</c>), indexed the same
|
||||
/// as a source's resampler property value. Allocates a fresh array on every access -
|
||||
/// startup-tier enumeration, not a per-frame query. Provided by
|
||||
/// <c>AL_SOFT_source_resampler</c>.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The index into <see cref="ResamplerNames"/> of the implementation's default resampler
|
||||
/// (<c>AL_DEFAULT_RESAMPLER_SOFT</c>). Provided by <c>AL_SOFT_source_resampler</c>.
|
||||
/// </summary>
|
||||
public static int DefaultResampler => PInvoke.GetInteger(Constants.AL_DEFAULT_RESAMPLER_SOFT);
|
||||
|
||||
/// <summary>
|
||||
/// The implementation's maximum per-source gain multiplier (<c>AL_GAIN_LIMIT_SOFT</c>); a
|
||||
/// source's <c>Gain</c> is silently clamped to this value. Provided by
|
||||
/// <c>AL_SOFT_gain_clamp_ex</c>.
|
||||
/// </summary>
|
||||
public static float GainLimit => PInvoke.GetFloat(Constants.AL_GAIN_LIMIT_SOFT);
|
||||
|
||||
/// <summary>
|
||||
/// Schedules playback of several sources to start together at a device-clock time, in
|
||||
/// nanoseconds (<c>alSourcePlayAtTimevSOFT</c>; the clock is
|
||||
/// <see cref="OpenAlApi.Device.ClockTime"/>). Provided by <c>AL_SOFT_source_start_delay</c>.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A <see langword="using"/>-able scope pairing <see cref="Al.DeferUpdates"/> with
|
||||
/// <see cref="Al.ProcessUpdates"/>: state changes made while the scope is open are applied
|
||||
/// atomically when it is disposed. Provided by <c>AL_SOFT_deferred_updates</c>.
|
||||
/// </summary>
|
||||
public readonly ref struct DeferredUpdatesScope
|
||||
{
|
||||
/// <summary>Applies the deferred updates (<c>alProcessUpdatesSOFT</c>).</summary>
|
||||
public void Dispose() => Al.ProcessUpdates();
|
||||
}
|
||||
29
brutal.openal/Brutal.OpenAl/Manual/Al.cs
Normal file
29
brutal.openal/Brutal.OpenAl/Manual/Al.cs
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
// The Al class root: the `Dll` const shared by the generated Al.PInvoke imports and the hand-written
|
||||
// partials (Al.Wrapper.cs, Al.Listener.cs, Errors.cs).
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
/// <summary>
|
||||
/// Wrappers over core OpenAL (<c>al.h</c>): buffers, sources, the listener, and playback state.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Most AL calls do not return errors. OpenAL records the first error per context/thread and
|
||||
/// holds it until it is read with <c>alGetError</c>, which also clears it.
|
||||
/// <see cref="ThrowIfError"/> reads the error and throws <see cref="AlException"/> if one was
|
||||
/// set; <see cref="GetError"/> reads it without throwing. Methods here never check for errors
|
||||
/// automatically - call <see cref="ThrowIfError"/> yourself, for example after initialization,
|
||||
/// after loading a resource, and per-frame in debug builds.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Because only the first error is recorded, an unchecked error is attributed to whichever call
|
||||
/// checks next - check promptly if you need to know which call failed. AL calls act on the
|
||||
/// context current on the calling thread; with no current context, <see cref="ThrowIfError"/>
|
||||
/// throws (openal-soft reports <c>AL_INVALID_OPERATION</c>).
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static partial class Al
|
||||
{
|
||||
// Logical native library name; mapped to the platform file by NativeLoader's DllImportResolver.
|
||||
internal const string Dll = "openal";
|
||||
}
|
||||
18
brutal.openal/Brutal.OpenAl/Manual/AlAuxiliaryEffectSlot.cs
Normal file
18
brutal.openal/Brutal.OpenAl/Manual/AlAuxiliaryEffectSlot.cs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
// The identity half and the Gain/SendAuto properties are generated. Load is hand-written, and is a
|
||||
// verb rather than a settable Effect property because the native call COPIES the effect's
|
||||
// parameters at call time - property-assignment syntax would falsely suggest a live link.
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public readonly partial struct AlAuxiliaryEffectSlot
|
||||
{
|
||||
/// <summary>
|
||||
/// Loads an effect into the slot (<c>AL_EFFECTSLOT_EFFECT</c>). OpenAL copies the effect's
|
||||
/// parameters into the slot NOW: changing the effect's parameters afterwards has no audible
|
||||
/// effect until it is loaded again. Pass <see cref="AlEffect.Null"/> to detach.
|
||||
/// </summary>
|
||||
public void Load(AlEffect effect)
|
||||
{
|
||||
Al.PInvoke.AuxiliaryEffectSloti(Name, Al.Constants.AL_EFFECTSLOT_EFFECT, (int)effect.Name);
|
||||
}
|
||||
}
|
||||
25
brutal.openal/Brutal.OpenAl/Manual/AlBuffer.cs
Normal file
25
brutal.openal/Brutal.OpenAl/Manual/AlBuffer.cs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
// OpenAL buffers are ALuint object *names*, not pointers, so this is a value type over a uint.
|
||||
// Hand-written half: data upload only; the identity half is generated.
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public readonly unsafe partial struct AlBuffer
|
||||
{
|
||||
/// <summary>
|
||||
/// Uploads PCM sample data to the buffer (<c>alBufferData</c>); the rate is in Hz. On a
|
||||
/// callback buffer a successful upload also detaches the callback and releases its handler
|
||||
/// (uploading data is the spec's own detach idiom - see <see cref="ClearCallback"/>).
|
||||
/// </summary>
|
||||
public void SetData(AlFormat format, ReadOnlySpan<byte> data, int sampleRate)
|
||||
{
|
||||
// Same protocol as ClearCallback: upstream clears the buffer's callback on a successful
|
||||
// upload, which reports failure only on the error latch - so the handler root is evicted
|
||||
// only once the buffer no longer holds its cookie. PeekCookie keeps this free for
|
||||
// non-callback consumers.
|
||||
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 _);
|
||||
}
|
||||
}
|
||||
83
brutal.openal/Brutal.OpenAl/Manual/AlDebug.Internal.cs
Normal file
83
brutal.openal/Brutal.OpenAl/Manual/AlDebug.Internal.cs
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
// The internal half of AlDebug (public half: AlDebug.cs): the per-context callback rooting and its
|
||||
// trampoline, plus the shared text arena the pull side writes into. ArenaView is internal rather
|
||||
// than private only so AlDebugMessageInfo.Message can slice the arena.
|
||||
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public static unsafe partial class AlDebug
|
||||
{
|
||||
// Per-context rooting, identical in shape to Al.EventCallbacks (Callbacks.Internal.cs): the
|
||||
// current context's raw address round-trips as userParam and keys the handler here, never a
|
||||
// managed pointer. internal so Al.EvictContextRoots can prune entries on context teardown and
|
||||
// tests can observe it.
|
||||
internal static readonly ConcurrentDictionary<nint, AlDebugCallback> DebugCallbacks = new();
|
||||
|
||||
// The shared text arena the pull side writes into. Allocated lazily on the first pull (only
|
||||
// debug-tooling apps pay for it), sized to drain a full log chunk or hold the largest possible
|
||||
// label. Every pull overwrites it from offset 0 - that is what makes returned spans "valid
|
||||
// until the next pull" - and one arena means the pull side is single-threaded by design.
|
||||
private static byte[]? _arena;
|
||||
|
||||
// Messages drained per native call. openal-soft's log holds at most 64 (al/debug.h), so one
|
||||
// chunk empties it; larger caller spans are served by the drain loop callers write anyway.
|
||||
// Also bounds the per-call stackalloc side-arrays.
|
||||
private const int LogChunk = 64;
|
||||
|
||||
/// <summary>The current arena, or empty if nothing has been pulled yet.</summary>
|
||||
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);
|
||||
|
||||
// With no context current (or no AL_EXT_debug) both queries answer 0. Do NOT cache
|
||||
// that: a zero-length arena cached here would poison every pull for the rest of the
|
||||
// process. Serve this call with an empty arena and let the next call re-query.
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
351
brutal.openal/Brutal.OpenAl/Manual/AlDebug.cs
Normal file
351
brutal.openal/Brutal.OpenAl/Manual/AlDebug.cs
Normal file
|
|
@ -0,0 +1,351 @@
|
|||
// AL_EXT_debug: a KHR_debug-style message log, debug groups, and object labels. Public half of
|
||||
// AlDebug; the callback rooting, trampoline, and shared text arena live in AlDebug.Internal.cs;
|
||||
// the typed ObjectLabel/GetObjectLabel overloads (one trio per object-name handle type) are
|
||||
// generated - see Generated/Al/AlDebug.ObjectLabels.gen.cs.
|
||||
//
|
||||
// The callback roots per-context the same way as Al.SetEventCallback (see Callbacks.cs) and is
|
||||
// pruned through the same Al.EvictContextRoots hook. The string-taking push side (MessageInsert/
|
||||
// PushGroup/ObjectLabel) may allocate - outbound dev-tool calls, never on the delivery path. The
|
||||
// pull side (GetMessageLog/GetObjectLabel) never allocates: results land in the shared arena.
|
||||
//
|
||||
// Verified against openal-soft's al/debug.cpp:
|
||||
// - The message log writes each entry's length INCLUDING the trailing NUL; alGetObjectLabelEXT
|
||||
// writes it EXCLUDING the NUL. GetMessageLog and GetObjectLabel below slice accordingly.
|
||||
// - The callback runs synchronously on the calling thread (unlike AL_SOFT_events' event thread).
|
||||
// - alDebugMessageInsertEXT accepts only the Application/ThirdParty sources, and message/group
|
||||
// delivery requires a context created with ALC_CONTEXT_DEBUG_BIT_EXT - see the class doc.
|
||||
|
||||
using unsafe DebugTrampolineFn = delegate* unmanaged[Cdecl]<int, int, uint, int, int, byte*, void*, void>;
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
/// <summary>Reports a debug message from the AL implementation, a debug group push/pop, or an application-inserted message.</summary>
|
||||
/// <remarks>
|
||||
/// Called synchronously on whichever thread triggers the message (unlike the AL_SOFT_events
|
||||
/// callback, which runs on openal-soft's event thread). Must not throw (a thrown exception is
|
||||
/// caught, queued on <see cref="Al.ThrowCallbackExceptions"/>, and the message dropped) and
|
||||
/// must not block. The message span is valid only for the duration of the call. See
|
||||
/// <see cref="AlDebug.SetCallback"/>.
|
||||
/// </remarks>
|
||||
public delegate void AlDebugCallback(
|
||||
AlDebugSource source,
|
||||
AlDebugType type,
|
||||
uint id,
|
||||
AlDebugSeverity severity,
|
||||
ReadOnlySpan<byte> message
|
||||
);
|
||||
|
||||
/// <summary>A logged debug message, as drained by <see cref="AlDebug.GetMessageLog"/>.</summary>
|
||||
public readonly record struct AlDebugMessageInfo(
|
||||
AlDebugSource Source,
|
||||
AlDebugType Type,
|
||||
uint Id,
|
||||
AlDebugSeverity Severity,
|
||||
int Offset,
|
||||
int Length
|
||||
)
|
||||
{
|
||||
/// <summary>
|
||||
/// The UTF-8 message text (no trailing NUL). A view into <see cref="AlDebug"/>'s shared
|
||||
/// text arena: valid only until the next <see cref="AlDebug.GetMessageLog"/> or
|
||||
/// <c>AlDebug.GetObjectLabel</c> call.
|
||||
/// </summary>
|
||||
public ReadOnlySpan<byte> Message => AlDebug.ArenaView.Slice(Offset, Length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A <see langword="using"/>-able scope pairing
|
||||
/// <see cref="AlDebug.PushGroup(AlDebugSource, uint, string)"/> with
|
||||
/// <see cref="AlDebug.PopGroup"/>: the group pushed to obtain this scope is popped when it is
|
||||
/// disposed.
|
||||
/// </summary>
|
||||
public readonly ref struct DebugGroupScope
|
||||
{
|
||||
/// <summary>Pops the debug group (<c>alPopDebugGroupEXT</c>).</summary>
|
||||
public void Dispose() => AlDebug.PopGroup();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The AL_EXT_debug surface: a KHR_debug-style message log, debug groups, object labels, and a
|
||||
/// debug message callback.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Message/group delivery (the log and the callback) requires a DEBUG context - create one by
|
||||
/// passing <c>ALC_CONTEXT_DEBUG_BIT_EXT</c> among the context flags, then call
|
||||
/// <see cref="Enable"/>:
|
||||
/// <code>
|
||||
/// using var context = device.CreateContext(
|
||||
/// new Context.CreateInfo
|
||||
/// {
|
||||
/// Attributes = [(AlcContextAttribute.ContextFlags, Alc.Constants.ALC_CONTEXT_DEBUG_BIT_EXT)],
|
||||
/// }
|
||||
/// );
|
||||
/// context.MakeCurrent();
|
||||
/// AlDebug.Enable();
|
||||
/// </code>
|
||||
/// Object labels (<see cref="ObjectLabel(AlObjectLabelIdentifier,uint,string)"/> /
|
||||
/// <see cref="GetObjectLabel(AlObjectLabelIdentifier, uint)"/>) work on any context; they carry
|
||||
/// no message-delivery requirement. Provided by <c>AL_EXT_debug</c>.
|
||||
/// </remarks>
|
||||
public static unsafe partial class AlDebug
|
||||
{
|
||||
/// <summary>Enables debug message/group delivery (<c>alEnable(AL_DEBUG_OUTPUT_EXT)</c>).</summary>
|
||||
public static void Enable() => Al.PInvoke.Enable(Al.Constants.AL_DEBUG_OUTPUT_EXT);
|
||||
|
||||
/// <summary>Disables debug message/group delivery (<c>alDisable(AL_DEBUG_OUTPUT_EXT)</c>).</summary>
|
||||
public static void Disable() => Al.PInvoke.Disable(Al.Constants.AL_DEBUG_OUTPUT_EXT);
|
||||
|
||||
/// <summary>
|
||||
/// Registers (or, with <see langword="null"/>, deregisters) the debug callback for the
|
||||
/// context current on this thread (<c>alDebugMessageCallbackEXT</c>).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Binds to whichever context is current AT THE CALL - the same currency and disposal model
|
||||
/// as <see cref="Al.SetEventCallback"/> (see its remarks). While a callback is registered,
|
||||
/// messages are delivered to it instead of accumulating in the log, so
|
||||
/// <see cref="GetMessageLog"/> then always returns empty.
|
||||
/// </remarks>
|
||||
public static void SetCallback(AlDebugCallback? callback)
|
||||
{
|
||||
// With nothing current the registration simply keys on address 0 - same stance as
|
||||
// Al.SetEventCallback: never pre-validate state the native call would itself diagnose.
|
||||
var context = Alc.PInvoke.GetCurrentContext().Pointer.Value;
|
||||
if (callback is null)
|
||||
{
|
||||
Al.PInvoke.DebugMessageCallbackEXT(null, null);
|
||||
DebugCallbacks.TryRemove(context, out _);
|
||||
return;
|
||||
}
|
||||
|
||||
// Stored before the native call, restored if it throws - see the Callbacks.cs header.
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inserts an application message into the debug log/callback
|
||||
/// (<c>alDebugMessageInsertEXT</c>). Only <see cref="AlDebugSource.Application"/> and
|
||||
/// <see cref="AlDebugSource.ThirdParty"/> are valid for <paramref name="source"/>.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="MessageInsert(AlDebugSource, AlDebugType, uint, AlDebugSeverity, string)"/>
|
||||
/// <remarks>UTF-8 byte variant: no transcode, no allocation.</remarks>
|
||||
public static void MessageInsert(
|
||||
AlDebugSource source,
|
||||
AlDebugType type,
|
||||
uint id,
|
||||
AlDebugSeverity severity,
|
||||
ReadOnlySpan<byte> message
|
||||
)
|
||||
{
|
||||
fixed (byte* p = message)
|
||||
{
|
||||
// `fixed` pins an empty span as null, and openal-soft rejects a null message pointer
|
||||
// even at length 0 (al/debug.cpp) - substitute a real empty string.
|
||||
byte nul = 0;
|
||||
Al.PInvoke.DebugMessageInsertEXT(
|
||||
(int)source,
|
||||
(int)type,
|
||||
id,
|
||||
(int)severity,
|
||||
message.Length,
|
||||
p != null ? p : &nul
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enables or disables delivery of debug messages matching a filter
|
||||
/// (<c>alDebugMessageControlEXT</c>). <c>DontCare</c> enum values act as wildcards. A
|
||||
/// non-empty <paramref name="ids"/> filters on specific message IDs instead, and then
|
||||
/// REQUIRES a concrete <paramref name="source"/> and <paramref name="type"/> and a
|
||||
/// <c>DontCare</c> <paramref name="severity"/> - openal-soft rejects any other combination
|
||||
/// with <see cref="AlError.InvalidOperation"/>.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pushes a named debug group (<c>alPushDebugGroupEXT</c>); pair with <see cref="PopGroup"/>,
|
||||
/// or use <see cref="GroupScope(AlDebugSource, uint, string)"/> for a
|
||||
/// <see langword="using"/>-able pairing.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="PushGroup(AlDebugSource, uint, string)"/>
|
||||
/// <remarks>UTF-8 byte variant: no transcode, no allocation.</remarks>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Pops the innermost debug group (<c>alPopDebugGroupEXT</c>).</summary>
|
||||
public static void PopGroup() => Al.PInvoke.PopDebugGroupEXT();
|
||||
|
||||
/// <summary>
|
||||
/// Pushes a named debug group and returns a scope whose <see cref="DebugGroupScope.Dispose"/>
|
||||
/// pops it (pairs <see cref="PushGroup(AlDebugSource, uint, string)"/> with
|
||||
/// <see cref="PopGroup"/> for a <see langword="using"/> block).
|
||||
/// </summary>
|
||||
public static DebugGroupScope GroupScope(AlDebugSource source, uint id, string message)
|
||||
{
|
||||
PushGroup(source, id, message);
|
||||
return new DebugGroupScope();
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="GroupScope(AlDebugSource, uint, string)"/>
|
||||
public static DebugGroupScope GroupScope(AlDebugSource source, uint id, ReadOnlySpan<byte> message)
|
||||
{
|
||||
PushGroup(source, id, message);
|
||||
return new DebugGroupScope();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pulls up to <c>messages.Length</c> entries (at most 64 per call - drain in a loop) from
|
||||
/// the debug message log (<c>alGetDebugMessageLogEXT</c>), removing them, and returns how
|
||||
/// many were pulled. Never allocates: message text lands in a shared internal arena that
|
||||
/// each <see cref="AlDebugMessageInfo.Message"/> views, so drained entries stay valid only
|
||||
/// until the next <see cref="GetMessageLog"/> or <c>GetObjectLabel</c> call, and pulls must
|
||||
/// not run concurrently. With a callback registered (<see cref="SetCallback"/>) the log
|
||||
/// stays empty and this returns 0.
|
||||
/// </summary>
|
||||
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 trailing NUL terminator (openal-soft's al/debug.cpp writes
|
||||
// `msg.size() + 1` per entry) - the text itself is lengths[i] - 1 bytes.
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Labels an AL object for diagnostics (<c>alObjectLabelEXT</c>); a <see langword="null"/>
|
||||
/// label clears it.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="ObjectLabel(AlObjectLabelIdentifier, uint, string)"/>
|
||||
/// <remarks>UTF-8 byte variant: no transcode, no allocation; an empty label clears it.</remarks>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets an AL object's diagnostic label (<c>alGetObjectLabelEXT</c>) as UTF-8 bytes, or an
|
||||
/// empty span if none was set. Never allocates: the returned span views the shared internal
|
||||
/// arena and stays valid only until the next <see cref="GetMessageLog"/> or
|
||||
/// <see cref="GetObjectLabel(AlObjectLabelIdentifier, uint)"/> call.
|
||||
/// </summary>
|
||||
public static ReadOnlySpan<byte> GetObjectLabel(AlObjectLabelIdentifier identifier, uint name)
|
||||
{
|
||||
var arena = EnsureArena();
|
||||
// Explicitly zeroed: with no context current the native call is a no-op that never
|
||||
// writes length, and an empty arena pins as a NULL pointer, which openal-soft answers by
|
||||
// reporting the full label length without copying anything - so also clamp the slice, so
|
||||
// a native/managed size disagreement can never throw out of a getter.
|
||||
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));
|
||||
}
|
||||
}
|
||||
103
brutal.openal/Brutal.OpenAl/Manual/AlSource.Ext.cs
Normal file
103
brutal.openal/Brutal.OpenAl/Manual/AlSource.Ext.cs
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
// AL_SOFT_source_latency / ALC_SOFT_device_clock source-side queries, dispatched through the
|
||||
// extension d/i64 entry points rather than the core f/i ones.
|
||||
//
|
||||
// Hand-written rather than generated because the registry can't supply the docs (al.xml has no
|
||||
// prose for these enums) and misdescribes their shape (the *_OFFSET_CLOCK_SOFT params are declared
|
||||
// scalar though openal-soft fills two slots).
|
||||
//
|
||||
// The pair types are record structs, not vectors: each native result is a 2-element array whose
|
||||
// slots hold DIFFERENT quantities (an offset paired with a latency or clock reading), co-sampled
|
||||
// in one call. A math vector would offer meaningless arithmetic across the two.
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
/// <summary>A source's playback sample offset paired with its output latency. Provided by <c>AL_SOFT_source_latency</c>.</summary>
|
||||
/// <param name="SampleOffset">32.32 fixed-point sample offset (high 32 bits: whole samples).</param>
|
||||
/// <param name="Latency">Nanoseconds until the sample at the offset is audible.</param>
|
||||
public readonly record struct AlSampleOffsetLatency(long SampleOffset, long Latency)
|
||||
{
|
||||
/// <summary>The whole-sample part of <see cref="SampleOffset"/> (its high 32 bits).</summary>
|
||||
public int WholeSamples => (int)(SampleOffset >> 32);
|
||||
}
|
||||
|
||||
/// <summary>A source's playback sample offset paired with the device clock. Provided by <c>ALC_SOFT_device_clock</c>.</summary>
|
||||
/// <param name="SampleOffset">32.32 fixed-point sample offset (high 32 bits: whole samples).</param>
|
||||
/// <param name="ClockTime">The device clock, in nanoseconds, at which the offset was sampled.</param>
|
||||
public readonly record struct AlSampleOffsetClock(long SampleOffset, long ClockTime)
|
||||
{
|
||||
/// <summary>The whole-sample part of <see cref="SampleOffset"/> (its high 32 bits).</summary>
|
||||
public int WholeSamples => (int)(SampleOffset >> 32);
|
||||
}
|
||||
|
||||
/// <summary>A source's playback offset in seconds paired with its output latency. Provided by <c>AL_SOFT_source_latency</c>.</summary>
|
||||
/// <param name="SecOffset">Playback offset, in seconds.</param>
|
||||
/// <param name="Latency">Seconds until the sample at the offset is audible.</param>
|
||||
public readonly record struct AlSecOffsetLatency(double SecOffset, double Latency);
|
||||
|
||||
/// <summary>A source's playback offset in seconds paired with the device clock. Provided by <c>ALC_SOFT_device_clock</c>.</summary>
|
||||
/// <param name="SecOffset">Playback offset, in seconds.</param>
|
||||
/// <param name="ClockTime">The device clock, in seconds, at which the offset was sampled.</param>
|
||||
public readonly record struct AlSecOffsetClock(double SecOffset, double ClockTime);
|
||||
|
||||
public readonly partial struct AlSource
|
||||
{
|
||||
/// <summary>
|
||||
/// The playback offset and the output latency, in seconds, read atomically
|
||||
/// (<c>AL_SEC_OFFSET_LATENCY_SOFT</c>). Provided by <c>AL_SOFT_source_latency</c>.
|
||||
/// </summary>
|
||||
public AlSecOffsetLatency SecOffsetLatency
|
||||
{
|
||||
get
|
||||
{
|
||||
var (offset, latency) = Al.GetSourcedv2SOFT(Name, Al.Constants.AL_SEC_OFFSET_LATENCY_SOFT);
|
||||
return new AlSecOffsetLatency(offset, latency);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The playback sample offset and output latency, read atomically
|
||||
/// (<c>AL_SAMPLE_OFFSET_LATENCY_SOFT</c>). Provided by <c>AL_SOFT_source_latency</c>.
|
||||
/// </summary>
|
||||
public AlSampleOffsetLatency SampleOffsetLatency
|
||||
{
|
||||
get
|
||||
{
|
||||
var (offset, latency) = Al.GetSourcei64v2SOFT(Name, Al.Constants.AL_SAMPLE_OFFSET_LATENCY_SOFT);
|
||||
return new AlSampleOffsetLatency(offset, latency);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The playback offset and the device clock, in seconds, read atomically
|
||||
/// (<c>AL_SEC_OFFSET_CLOCK_SOFT</c>). Provided by <c>ALC_SOFT_device_clock</c>.
|
||||
/// </summary>
|
||||
public AlSecOffsetClock SecOffsetClock
|
||||
{
|
||||
get
|
||||
{
|
||||
var (offset, clock) = Al.GetSourcedv2SOFT(Name, Al.Constants.AL_SEC_OFFSET_CLOCK_SOFT);
|
||||
return new AlSecOffsetClock(offset, clock);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The playback sample offset and the device clock, read atomically
|
||||
/// (<c>AL_SAMPLE_OFFSET_CLOCK_SOFT</c>). Provided by <c>ALC_SOFT_device_clock</c>.
|
||||
/// </summary>
|
||||
public AlSampleOffsetClock SampleOffsetClock
|
||||
{
|
||||
get
|
||||
{
|
||||
var (offset, clock) = Al.GetSourcei64v2SOFT(Name, Al.Constants.AL_SAMPLE_OFFSET_CLOCK_SOFT);
|
||||
return new AlSampleOffsetClock(offset, clock);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Schedules playback to start at a device-clock time (<c>alSourcePlayAtTimeSOFT</c>). See
|
||||
/// <see cref="OpenAlApi.Device.ClockTime"/> for the clock this is measured against. Provided by
|
||||
/// <c>AL_SOFT_source_start_delay</c>.
|
||||
/// </summary>
|
||||
/// <param name="deviceClockTime">The device clock time, in nanoseconds, at which to start playback.</param>
|
||||
public void PlayAt(long deviceClockTime) => Al.PInvoke.SourcePlayAtTimeSOFT(Name, deviceClockTime);
|
||||
}
|
||||
52
brutal.openal/Brutal.OpenAl/Manual/AlSource.cs
Normal file
52
brutal.openal/Brutal.OpenAl/Manual/AlSource.cs
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
// Like AlBuffer, an OpenAL source is an ALuint object *name*, not a pointer - a value type over a
|
||||
// uint.
|
||||
//
|
||||
// Hand-written half: the queue span operations and the auxiliary send. Everything else is
|
||||
// generated (identity, playback verbs, named properties) or lives elsewhere (keyed access in the
|
||||
// opt-in Params namespace, the latency/clock getters in AlSource.Ext.cs).
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public readonly unsafe partial struct AlSource
|
||||
{
|
||||
/// <summary>
|
||||
/// Queues buffers onto the source, in playback order, for streaming playback
|
||||
/// (<c>alSourceQueueBuffers</c>).
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes processed buffers from the front of the source's queue
|
||||
/// (<c>alSourceUnqueueBuffers</c>), filling <paramref name="buffers"/> with the removed
|
||||
/// buffer names. The span's length determines how many are unqueued and must not exceed the
|
||||
/// number of processed buffers on the source.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Routes this source to an auxiliary effect slot (<c>AL_AUXILIARY_SEND_FILTER</c>,
|
||||
/// <c>alSource3i</c>), optionally through a wet-path filter (<see cref="AlFilter.Null"/>,
|
||||
/// the default, means unfiltered). Pass <see cref="AlAuxiliaryEffectSlot.Null"/> to disable
|
||||
/// the send. Send indices run <c>0</c> to <see cref="Efx.MaxAuxiliarySends"/> - 1.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
138
brutal.openal/Brutal.OpenAl/Manual/Alc.Wrapper.Internal.cs
Normal file
138
brutal.openal/Brutal.OpenAl/Manual/Alc.Wrapper.Internal.cs
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
// The internal half of the handle-less ALC surface (public half: Alc.Wrapper.cs): the shared
|
||||
// query/marshalling helpers the wrapper classes, the keyed Params.DeviceParams layer, and the
|
||||
// public statics are written against.
|
||||
|
||||
using Brutal.Strings;
|
||||
using CommunityToolkit.HighPerformance.Buffers;
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public static unsafe partial class Alc
|
||||
{
|
||||
// --- Strings -----------------------------------------------------------------------------------------
|
||||
//
|
||||
// The string-returning helpers copy the returned pointer into managed memory before checking
|
||||
// errors, in case the error query invalidates the library-owned buffer; the GetStringUtf8 pair
|
||||
// instead returns a zero-copy view, safe because no ALC call happens before the return on the
|
||||
// success path.
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// --- Integers ----------------------------------------------------------------------------------------
|
||||
//
|
||||
// alcGetIntegerv fills a caller buffer; these flatten the single-value case to a return value.
|
||||
// No automatic error poll, matching the explicit error model. The one vector query,
|
||||
// ALC_ALL_ATTRIBUTES, is encapsulated by Device.Attributes.
|
||||
|
||||
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);
|
||||
|
||||
// --- Device handle crossing ------------------------------------------------------------------------
|
||||
|
||||
// The native string/integer queries take ALCdevice* for playback AND capture devices; the
|
||||
// split handle types exist to make the mismatched close ops unrepresentable, not to forbid
|
||||
// shared queries. This one internal reinterpret is the sanctioned crossing.
|
||||
private static AlcDevice AsQueryDevice(AlcCaptureDevice capture) => (void*)capture.Pointer.Value;
|
||||
|
||||
// --- Attribute lists -----------------------------------------------------------------------------
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
111
brutal.openal/Brutal.OpenAl/Manual/Alc.Wrapper.cs
Normal file
111
brutal.openal/Brutal.OpenAl/Manual/Alc.Wrapper.cs
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
// Handle-less ALC operations: opening devices (playback and capture) and the null-device string
|
||||
// queries. Opens check the returned handle and throw via the global error latch. All other ALC
|
||||
// surface lives on the owning wrapper classes (Device/Context/CaptureDevice).
|
||||
//
|
||||
// Public half of the partial class; the shared query/marshalling helpers live in
|
||||
// Alc.Wrapper.Internal.cs.
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public static unsafe partial class Alc
|
||||
{
|
||||
// --- Device lifetime -------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Opens a playback device (<c>alcOpenDevice</c>); a <see langword="null"/> name means the
|
||||
/// default device.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
// --- Capture ---------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Opens a capture device (<c>alcCaptureOpenDevice</c>); a <see langword="null"/> name means
|
||||
/// the default capture device. <paramref name="format"/> must be one of the four standard
|
||||
/// <see cref="AlFormat"/> values; for an extension format, use the overload taking
|
||||
/// <c>bytesPerFrame</c>. The buffer size is the internal ring-buffer size, in samples.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens a capture device using a format this binding has no fixed frame size for - an
|
||||
/// extension format cast into <see cref="AlFormat"/>. <paramref name="bytesPerFrame"/> is
|
||||
/// the size of one sample-frame in <paramref name="format"/>, in bytes:
|
||||
/// <see cref="CaptureDevice.Samples"/> validates its destination buffer against it, so an
|
||||
/// incorrect value reintroduces the out-of-bounds native write the check exists to prevent.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
// --- Strings (null-device enumeration and defaults) ---------------------------------------------------
|
||||
|
||||
/// <summary>Enumerates the available playback devices (<c>ALC_DEVICE_SPECIFIER</c>).</summary>
|
||||
public static string[] GetDeviceSpecifiers() => EnumerateDevices(AlcGetString.DeviceSpecifier);
|
||||
|
||||
/// <summary>Enumerates all playback devices (<c>ALC_ALL_DEVICES_SPECIFIER</c>).</summary>
|
||||
public static string[] GetAllDeviceSpecifiers() => EnumerateDevices(AlcGetString.AllDevicesSpecifier);
|
||||
|
||||
/// <summary>Enumerates the available capture devices (<c>ALC_CAPTURE_DEVICE_SPECIFIER</c>).</summary>
|
||||
public static string[] GetCaptureDeviceSpecifiers() => EnumerateDevices(AlcGetString.CaptureDeviceSpecifier);
|
||||
|
||||
/// <summary>Gets the default playback device name (<c>ALC_DEFAULT_DEVICE_SPECIFIER</c>).</summary>
|
||||
public static string? GetDefaultDeviceSpecifier() => GetNullDeviceString(AlcGetString.DefaultDeviceSpecifier);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the default playback device name from the full device list
|
||||
/// (<c>ALC_DEFAULT_ALL_DEVICES_SPECIFIER</c>).
|
||||
/// </summary>
|
||||
public static string? GetDefaultAllDevicesSpecifier() =>
|
||||
GetNullDeviceString(AlcGetString.DefaultAllDevicesSpecifier);
|
||||
|
||||
/// <summary>Gets the default capture device name (<c>ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER</c>).</summary>
|
||||
public static string? GetCaptureDefaultDeviceSpecifier() =>
|
||||
GetNullDeviceString(AlcGetString.CaptureDefaultDeviceSpecifier);
|
||||
}
|
||||
31
brutal.openal/Brutal.OpenAl/Manual/Alc.cs
Normal file
31
brutal.openal/Brutal.OpenAl/Manual/Alc.cs
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
// The Alc class root: the `Dll` const shared by the generated Alc.PInvoke imports and the hand-written
|
||||
// partials (Alc.Wrapper.cs, Errors.cs).
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
/// <summary>
|
||||
/// Wrappers over the OpenAL context layer (<c>alc.h</c>): device and context lifetime, and audio
|
||||
/// capture.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Lifetime is owned by <see cref="Device"/>, <see cref="Context"/>, and
|
||||
/// <see cref="CaptureDevice"/>, returned by <see cref="OpenDevice"/>,
|
||||
/// <see cref="Device.CreateContext"/>, and
|
||||
/// <see cref="CaptureOpenDevice(string?, uint, AlFormat, int)"/>. The raw
|
||||
/// <see cref="AlcDevice"/>, <see cref="AlcContext"/>, and <see cref="AlcCaptureDevice"/> structs
|
||||
/// are non-owning handles used at the P/Invoke boundary; each wrapper class converts implicitly
|
||||
/// to its raw handle.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Tear down in order: detach the current context (<see cref="Context.MakeCurrent(Context?)"/>
|
||||
/// with <see langword="null"/>), dispose every context, then dispose the device. Closing or
|
||||
/// destroying the same native object twice - including through copies of a raw handle - is
|
||||
/// undefined behavior.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static partial class Alc
|
||||
{
|
||||
// Logical native library name; mapped to the platform file by NativeLoader's DllImportResolver.
|
||||
internal const string Dll = "openal";
|
||||
}
|
||||
216
brutal.openal/Brutal.OpenAl/Manual/Callbacks.Internal.cs
Normal file
216
brutal.openal/Brutal.OpenAl/Manual/Callbacks.Internal.cs
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
// The internal half of the callback marshalling (public half: Callbacks.cs): the exception latch,
|
||||
// the rooting dictionaries and fields, and the [UnmanagedCallersOnly] trampolines. See the
|
||||
// Callbacks.cs header for the pattern these all follow.
|
||||
|
||||
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();
|
||||
|
||||
// AL events are per-context, but the native callback has no per-context registration - so
|
||||
// registration passes the current context's raw address as userParam, and this dictionary
|
||||
// roots the handler keyed by that same address. The key is a plain nint, never a managed
|
||||
// pointer. internal so Context teardown can prune entries via EvictContextRoots below (a
|
||||
// recycled context address must never resolve to a stale handler) and tests can observe it.
|
||||
internal static readonly ConcurrentDictionary<nint, AlEventCallback> EventCallbacks = new();
|
||||
|
||||
// Called from Context teardown for every context address that stops being valid. AlDebug's
|
||||
// per-context callback dictionary joins here rather than adding a second Context hook.
|
||||
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
|
||||
{
|
||||
// Rooting and identity: userptr round-trips a process-unique cookie (never a managed pointer,
|
||||
// and never the buffer name - see the Callbacks.cs header), and this dictionary keeps the
|
||||
// delegate alive while native code may call it. The owning device's address rides along
|
||||
// (recorded once registration is confirmed) so Device.Dispose can sweep the roots of buffers
|
||||
// destroyed with their device.
|
||||
private static readonly ConcurrentDictionary<nint, (AlBufferCallback Callback, nint Device)> BufferCallbacks =
|
||||
new();
|
||||
|
||||
// Minted per registration via Interlocked.Increment; not derived from any AL object identity,
|
||||
// so it can never collide across devices or re-registrations.
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// Queries the cookie currently bound to this buffer name (alGetBufferPtrSOFT); 0 when no
|
||||
// callback is registered. SetCallback/ClearCallback read this before and after their native
|
||||
// call to decide which dictionary entry to evict: native registration and reset report
|
||||
// failure only on the error latch, so the bound cookie is the one reliable signal of whether
|
||||
// the call actually took.
|
||||
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;
|
||||
}
|
||||
|
||||
// Fast-path guard for the hot upload/delete paths: with no registration rooted anywhere there
|
||||
// is nothing to evict, and the extension query is skipped entirely - non-callback consumers
|
||||
// pay one dictionary emptiness check.
|
||||
private static nint PeekCookie(uint name) => BufferCallbacks.IsEmpty ? 0 : BoundCookie(name);
|
||||
|
||||
// Deleting a buffer ends its native callback registration, so the managed root must go with
|
||||
// it - otherwise the delegate (and everything its closure captures) stays reachable for the
|
||||
// rest of the process. The generated Delete/DeleteBuffers route here. Cookies are read BEFORE
|
||||
// the native delete (a freed name cannot answer) and evicted AFTER, keyed on per-name
|
||||
// liveness: deletion reports failure only on the error latch, and a rejected delete (buffer
|
||||
// in use by a source) leaves the native callback registered, so its root must survive.
|
||||
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 _);
|
||||
}
|
||||
}
|
||||
|
||||
// Called from Device.Dispose: closing a device destroys its buffers without any per-buffer
|
||||
// delete running, so every root recorded under the device is swept wholesale. Removing by
|
||||
// (key, value) pair never evicts an entry re-registered under a recycled cookie (cookies are
|
||||
// never recycled, but the discipline matches Context.EvictDeviceEntries).
|
||||
internal static void EvictDeviceRoots(nint devicePointer)
|
||||
{
|
||||
foreach (var entry in BufferCallbacks)
|
||||
{
|
||||
if (entry.Value.Device == devicePointer)
|
||||
BufferCallbacks.TryRemove(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
254
brutal.openal/Brutal.OpenAl/Manual/Callbacks.cs
Normal file
254
brutal.openal/Brutal.OpenAl/Manual/Callbacks.cs
Normal file
|
|
@ -0,0 +1,254 @@
|
|||
// Callback marshalling for the alext.h callback extensions. Public half: the delegate types and
|
||||
// the register/deregister/control surface; the exception latch, handler dictionaries, and
|
||||
// trampolines live in Callbacks.Internal.cs.
|
||||
//
|
||||
// The pattern throughout: [UnmanagedCallersOnly] static trampolines (no GCHandles needed), managed
|
||||
// handlers rooted by strong references, and userParam never carrying a managed pointer. Exceptions
|
||||
// never cross into native frames - every trampoline catches, pushes onto Al.CallbackExceptions,
|
||||
// and returns a neutral value. No callback path allocates managed memory.
|
||||
//
|
||||
// Registration stores the handler BEFORE the native call, not after: openal-soft can deliver an
|
||||
// event from its own thread as soon as the native call returns, and a handler stored afterwards
|
||||
// would miss it. The native call only throws when the extension entry point is missing, so each
|
||||
// register hook puts the previous handler back in that case instead of leaving a dead one stored.
|
||||
//
|
||||
// AlBuffer callbacks are keyed by a process-unique cookie, NOT the buffer name: names are
|
||||
// per-device in openal-soft, so two open devices can each hand out buffer 1 and a name-keyed
|
||||
// dictionary would resolve to the wrong device's handler.
|
||||
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Fills a callback buffer with sample data; returns the number of BYTES written. Return less
|
||||
/// than <c>destination.Length</c> to signal the end of the stream. Provided by
|
||||
/// <c>AL_SOFT_callback_buffer</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Called from openal-soft's mixer thread. Must not throw (a thrown exception is caught, queued
|
||||
/// on <see cref="Al.ThrowCallbackExceptions"/>, and the stream goes silent) and must not block.
|
||||
/// </remarks>
|
||||
public delegate int AlBufferCallback(Span<byte> destination);
|
||||
|
||||
/// <summary>
|
||||
/// Reports an AL event (buffer completion, source state change, or disconnect). Provided by
|
||||
/// <c>AL_SOFT_events</c>; see <see cref="Al.SetEventCallback"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Called on openal-soft's internal event thread, not necessarily the thread that registered
|
||||
/// the callback. Must not throw (a thrown exception is caught, queued on
|
||||
/// <see cref="Al.ThrowCallbackExceptions"/>, and the event is dropped) and must not block. The
|
||||
/// message span is valid only for the duration of the call.
|
||||
/// </remarks>
|
||||
public delegate void AlEventCallback(AlEventType eventType, uint @object, uint parameter, ReadOnlySpan<byte> message);
|
||||
|
||||
/// <summary>
|
||||
/// Reports an ALC system event (default device change, device added, or device removed).
|
||||
/// Provided by <c>ALC_SOFT_system_events</c>; see <see cref="Alc.SetEventCallback"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Called synchronously on whichever backend thread noticed the change, under openal-soft's
|
||||
/// global event lock - re-entering <see cref="Alc.SetEventCallback"/> or
|
||||
/// <see cref="Alc.EventControl"/> from the handler can deadlock. Must not throw (a thrown
|
||||
/// exception is caught, queued on <see cref="Al.ThrowCallbackExceptions"/>, and the event is
|
||||
/// dropped) and must not block. The message span is valid only for the duration of the call.
|
||||
/// </remarks>
|
||||
public delegate void AlcEventCallback(
|
||||
AlcEventType eventType,
|
||||
AlcDeviceType deviceType,
|
||||
AlcDevice device,
|
||||
ReadOnlySpan<byte> message
|
||||
);
|
||||
|
||||
public static unsafe partial class Al
|
||||
{
|
||||
/// <summary>
|
||||
/// Rethrows (and clears) any exceptions thrown by callback handlers since the last call.
|
||||
/// Callbacks run on openal-soft's internal threads, where an exception cannot propagate;
|
||||
/// each trampoline catches, queues here, and degrades (a buffer callback renders silence,
|
||||
/// a notification is dropped). Call this from your update loop when using callbacks.
|
||||
/// <see cref="LoopbackDevice.Render(Span{byte}, int)"/> drains automatically after each render.
|
||||
/// </summary>
|
||||
public static void ThrowCallbackExceptions() => CallbackExceptions.ThrowIfAny();
|
||||
|
||||
/// <summary>
|
||||
/// Enables or disables delivery of the given AL event types to the callback registered with
|
||||
/// <see cref="SetEventCallback"/> (<c>alEventControlSOFT</c>). Provided by
|
||||
/// <c>AL_SOFT_events</c>.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers (or, with <see langword="null"/>, deregisters) the AL event callback for the
|
||||
/// context current on this thread (<c>alEventCallbackSOFT</c>). Provided by
|
||||
/// <c>AL_SOFT_events</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Registration AND deregistration bind to whichever context is current AT THE CALL: each
|
||||
/// context has its own independent registration, and passing <see langword="null"/> with a
|
||||
/// different context current deregisters nothing on the original one. Disposing a context
|
||||
/// releases its own rooted handler automatically.
|
||||
/// </remarks>
|
||||
public static void SetEventCallback(AlEventCallback? callback)
|
||||
{
|
||||
// With nothing current the registration/removal simply keys on address 0 - this codebase
|
||||
// never pre-validates state the native call would itself diagnose (see the Errors.cs
|
||||
// header).
|
||||
var context = Alc.PInvoke.GetCurrentContext().Pointer.Value;
|
||||
if (callback is null)
|
||||
{
|
||||
PInvoke.EventCallbackSOFT(null, null);
|
||||
EventCallbacks.TryRemove(context, out _);
|
||||
return;
|
||||
}
|
||||
|
||||
// Stored before the native call, restored if it throws - see the file header.
|
||||
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
|
||||
{
|
||||
/// <summary>
|
||||
/// Whether the given ALC system event type is supported for the given device kind
|
||||
/// (<c>alcEventIsSupportedSOFT</c>). Provided by <c>ALC_SOFT_system_events</c>.
|
||||
/// </summary>
|
||||
public static bool IsEventSupported(AlcEventType eventType, AlcDeviceType deviceType) =>
|
||||
PInvoke.EventIsSupportedSOFT((int)eventType, (int)deviceType) == Constants.ALC_EVENT_SUPPORTED_SOFT;
|
||||
|
||||
/// <summary>
|
||||
/// Enables or disables delivery of the given ALC system event types to the callback
|
||||
/// registered with <see cref="SetEventCallback"/> (<c>alcEventControlSOFT</c>). Provided by
|
||||
/// <c>ALC_SOFT_system_events</c>.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers (or, with <see langword="null"/>, deregisters) the ALC system event callback
|
||||
/// (<c>alcEventCallbackSOFT</c>). Unlike <see cref="Al.SetEventCallback"/>, there is exactly
|
||||
/// one registration for the whole process. Provided by <c>ALC_SOFT_system_events</c>.
|
||||
/// </summary>
|
||||
public static void SetEventCallback(AlcEventCallback? callback)
|
||||
{
|
||||
if (callback is null)
|
||||
{
|
||||
PInvoke.EventCallbackSOFT(null, null);
|
||||
_systemEventCallback = null;
|
||||
return;
|
||||
}
|
||||
|
||||
// Stored before the native call, restored if it throws - see the file header.
|
||||
var previous = _systemEventCallback;
|
||||
_systemEventCallback = callback;
|
||||
try
|
||||
{
|
||||
PInvoke.EventCallbackSOFT((AlcEventTrampolineFn)(&AlcEventTrampoline), null);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_systemEventCallback = previous;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public readonly unsafe partial struct AlBuffer
|
||||
{
|
||||
/// <summary>
|
||||
/// Makes this a callback buffer: openal-soft pulls sample data from
|
||||
/// <paramref name="callback"/> on its mixer thread instead of storing data
|
||||
/// (<c>alBufferCallbackSOFT</c>). Provided by <c>AL_SOFT_callback_buffer</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// On success the handler stays referenced until the registration ends:
|
||||
/// <see cref="ClearCallback"/>, re-registration, a data upload
|
||||
/// (<see cref="SetData(AlFormat, ReadOnlySpan{byte}, int)"/>), a successful delete, and
|
||||
/// disposal of the owning <see cref="Device"/> all release it. Registration is
|
||||
/// rejected while the buffer is attached to a source (<c>AL_INVALID_OPERATION</c>, silently
|
||||
/// unless you check <see cref="Al.GetError"/>); a rejected registration releases the new
|
||||
/// handler and leaves any existing callback fully in place.
|
||||
/// </remarks>
|
||||
public void SetCallback(AlFormat format, int frequency, AlBufferCallback callback)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(callback);
|
||||
var previous = BoundCookie(Name);
|
||||
var cookie = (nint)Interlocked.Increment(ref _cookieCounter);
|
||||
// Root before registering - see the file header pattern. The owning device is not known to
|
||||
// be resolvable yet (registration may be a context-less no-op), so it is recorded below,
|
||||
// once the read-back proves the registration took.
|
||||
BufferCallbacks[cookie] = (callback, 0);
|
||||
Al.PInvoke.BufferCallbackSOFT(
|
||||
Name,
|
||||
(int)format,
|
||||
frequency,
|
||||
(BufferTrampolineFn)(&BufferTrampoline),
|
||||
(void*)cookie
|
||||
);
|
||||
|
||||
// Registration reports failure only on the error latch (AL_INVALID_OPERATION while the
|
||||
// buffer is attached to a source), so read back which cookie the buffer actually holds:
|
||||
// on success evict the handler this call replaced, on failure unroot the new handler and
|
||||
// leave the existing registration untouched.
|
||||
if (BoundCookie(Name) == cookie)
|
||||
{
|
||||
// Registration took, so a context is necessarily current: record the buffer's owning
|
||||
// device so Device.Dispose can sweep this root if the buffer is destroyed with the
|
||||
// device rather than deleted individually.
|
||||
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 _);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Detaches the callback (the buffer reverts to an empty non-callback buffer) and releases
|
||||
/// the handler reference. Detach the buffer from any source first - the underlying reset
|
||||
/// rejects an attached buffer with <c>AL_INVALID_OPERATION</c>, silently unless you check
|
||||
/// <see cref="Al.GetError"/>, and a rejected reset leaves the callback registered and its
|
||||
/// handler referenced.
|
||||
/// </summary>
|
||||
public void ClearCallback()
|
||||
{
|
||||
// The spec's sanctioned detach is re-specifying the buffer's data; openal-soft rejects a
|
||||
// NULL callback pointer with AL_INVALID_VALUE (verified in CallbackTests), so an empty
|
||||
// BufferData reset is used instead. The format is irrelevant at zero length. As in
|
||||
// SetCallback, the reset fails only on the error latch - release the handler only once
|
||||
// the buffer no longer holds its cookie.
|
||||
var previous = BoundCookie(Name);
|
||||
Al.PInvoke.BufferData(Name, (int)AlFormat.Mono16, null, 0, 1);
|
||||
if (previous != 0 && BoundCookie(Name) == 0)
|
||||
BufferCallbacks.TryRemove(previous, out _);
|
||||
}
|
||||
}
|
||||
35
brutal.openal/Brutal.OpenAl/Manual/CaptureDevice.Internal.cs
Normal file
35
brutal.openal/Brutal.OpenAl/Manual/CaptureDevice.Internal.cs
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
// The internal half of CaptureDevice (public half: CaptureDevice.cs): FrameSize gates the format
|
||||
// in Alc.CaptureOpenDevice, CheckBufferLength bounds the destination in Samples().
|
||||
|
||||
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,
|
||||
};
|
||||
|
||||
// Factored out of Samples() so a headless unit test can reach it. Widens to long before
|
||||
// multiplying: samples * frameSize can overflow 32 bits, which would wrap and silently defeat
|
||||
// the guard.
|
||||
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"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
154
brutal.openal/Brutal.OpenAl/Manual/CaptureDevice.cs
Normal file
154
brutal.openal/Brutal.OpenAl/Manual/CaptureDevice.cs
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
// Sealed IDisposable wrapper over the raw AlcCaptureDevice handle: Alc.CaptureOpenDevice
|
||||
// constructs it, Dispose closes it. No finalizer and no Destroy() alias - disposal is explicit.
|
||||
// Capture and playback devices are both a native ALCdevice*, but are closed with different native
|
||||
// calls; the distinct handle type makes passing one to the wrong close op a compile error.
|
||||
//
|
||||
// Public half of the type; the format/buffer-size helpers live in CaptureDevice.Internal.cs.
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
/// <summary>
|
||||
/// An OpenAL capture device, opened by
|
||||
/// <see cref="Alc.CaptureOpenDevice(string?, uint, AlFormat, int)"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Owns the underlying native capture device: call <see cref="Dispose"/> when done. Converts
|
||||
/// implicitly to the raw, non-owning <see cref="AlcCaptureDevice"/> handle.
|
||||
/// </remarks>
|
||||
public sealed partial class CaptureDevice : IDisposable, INullable
|
||||
{
|
||||
/// <summary>The raw capture-device handle.</summary>
|
||||
public AlcCaptureDevice Handle { get; private set; }
|
||||
|
||||
// The frame size (bytes per sample-frame) for the format this device was opened with. Always
|
||||
// known: Alc.CaptureOpenDevice derives it for the four standard AlFormat values and rejects any
|
||||
// other format unless the caller states the size explicitly. Samples() below relies on it.
|
||||
private readonly int _bytesPerFrame;
|
||||
|
||||
// Lifetime-constant query result, cached on first access instead of re-querying native (and
|
||||
// re-allocating) every time. A capture device has no reopen path, so this is never invalidated.
|
||||
private string? _specifier;
|
||||
|
||||
internal CaptureDevice(AlcCaptureDevice handle, int bytesPerFrame)
|
||||
{
|
||||
Handle = handle;
|
||||
_bytesPerFrame = bytesPerFrame;
|
||||
}
|
||||
|
||||
// Disposal guard shared by every member that touches native state or returns cached native
|
||||
// answers - a disposed capture device must never answer plausibly. Handle, IsNull() and the
|
||||
// implicit conversion stay unguarded (the raw escape hatch), matching Device.
|
||||
private AlcCaptureDevice CheckedHandle
|
||||
{
|
||||
get
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return Handle;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Returns <see langword="true"/> if this capture device has already been disposed.</summary>
|
||||
public bool IsNull() => Handle.IsNull();
|
||||
|
||||
/// <summary>The capture device's name (<c>ALC_CAPTURE_DEVICE_SPECIFIER</c>). Cached.</summary>
|
||||
public string? Specifier
|
||||
{
|
||||
get
|
||||
{
|
||||
// Guard before the cache, not just before the query - as in Device's cached getters.
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return _specifier ??= Alc.GetString(Handle, AlcGetString.CaptureDeviceSpecifier);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The number of captured sample-frames available to read (<c>ALC_CAPTURE_SAMPLES</c>).
|
||||
/// Poll this between <see cref="Start"/> and <see cref="Samples"/> to size the read.
|
||||
/// </summary>
|
||||
public int AvailableSamples => Alc.GetInteger(CheckedHandle, AlcInteger.CaptureSamples);
|
||||
|
||||
/// <summary>
|
||||
/// Reads and clears this capture device's ALC error (<c>alcGetError</c>), without throwing
|
||||
/// on a latched error.
|
||||
/// </summary>
|
||||
public AlcError GetError()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return Alc.GetError(Handle);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads and clears this capture device's ALC error, throwing <see cref="AlcException"/> if
|
||||
/// one was set. Never called automatically by wrapper methods, as with
|
||||
/// <see cref="Al.ThrowIfError"/>.
|
||||
/// </summary>
|
||||
public void ThrowIfError()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
Alc.ThrowIfError(Handle);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Alc.PInvoke.CaptureStart"/>
|
||||
public void Start() => Alc.PInvoke.CaptureStart(CheckedHandle);
|
||||
|
||||
/// <inheritdoc cref="Alc.PInvoke.CaptureStop"/>
|
||||
public void Stop() => Alc.PInvoke.CaptureStop(CheckedHandle);
|
||||
|
||||
/// <summary>
|
||||
/// Reads captured samples out of the device's internal buffer (<c>alcCaptureSamples</c>).
|
||||
/// Native code writes <paramref name="samples"/> frames regardless of the buffer's length,
|
||||
/// so the length is validated against the frame size the device was opened with (throws
|
||||
/// <see cref="ArgumentException"/> on a too-small buffer).
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes the capture device (<c>alcCaptureCloseDevice</c>), throwing
|
||||
/// <see cref="AlcException"/> if the native close reports failure - the explicit-lifetime
|
||||
/// counterpart of <see cref="Dispose"/>, which swallows it. The wrapper is disposed either
|
||||
/// way, so a later <see cref="Dispose"/> (a <see langword="using"/> safety net) is a no-op.
|
||||
/// </summary>
|
||||
public void Close()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
if (!CloseCore())
|
||||
throw new AlcException(Alc.GetError(), "alcCaptureCloseDevice failed.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes the capture device (<c>alcCaptureCloseDevice</c>). Never throws: a failed close
|
||||
/// leaves its reason on the global ALC error latch - call <see cref="Close"/> instead when
|
||||
/// failure should surface. Idempotent but not safe to call concurrently; no finalizer - an
|
||||
/// undisposed capture device leaks.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (IsNull())
|
||||
return;
|
||||
|
||||
// Same rationale as Device.Dispose: never replace a using-body exception; the reason
|
||||
// stays on the global latch.
|
||||
CloseCore();
|
||||
}
|
||||
|
||||
private bool CloseCore()
|
||||
{
|
||||
// The wrapper dies either way - see Device.CloseCore.
|
||||
var closed = Alc.PInvoke.CaptureCloseDevice(Handle);
|
||||
Handle = AlcCaptureDevice.Null;
|
||||
return closed;
|
||||
}
|
||||
|
||||
/// <summary>Implicitly converts to the raw <see cref="AlcCaptureDevice"/> handle.</summary>
|
||||
public static implicit operator AlcCaptureDevice(CaptureDevice capture) => capture.Handle;
|
||||
}
|
||||
56
brutal.openal/Brutal.OpenAl/Manual/Context.Internal.cs
Normal file
56
brutal.openal/Brutal.OpenAl/Manual/Context.Internal.cs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
// The internal half of Context (public half: Context.cs): the weak ledger mapping native context
|
||||
// addresses back to the wrappers this layer created, and the eviction pair Device.Dispose drives
|
||||
// when closing a device destroys the live contexts on it.
|
||||
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
public sealed partial class Context
|
||||
{
|
||||
// Ledger of live wrappers keyed by native address. AlcContext.Handle is the generated record
|
||||
// struct, so the default comparer is value-based and non-boxing. Registered in the ctor, removed
|
||||
// in Dispose; entries for leaked wrappers die with their targets and are pruned on the next
|
||||
// registration.
|
||||
private static readonly ConcurrentDictionary<AlcContext.Handle, WeakReference<Context>> LiveContexts = new();
|
||||
|
||||
// Closing a device natively destroys any live contexts on it without their Dispose running -
|
||||
// the one path that frees a context's address while its ledger entry survives, after which a
|
||||
// recycled address would resolve to the stale wrapper and make Current lie. Device.Dispose
|
||||
// calls this BEFORE the native close, so a freed address is never mapped; if the close then
|
||||
// fails, the evicted contexts merely stop resolving (a miss, never a lie).
|
||||
internal static List<Context> EvictDeviceEntries(Device device)
|
||||
{
|
||||
List<Context> orphans = [];
|
||||
|
||||
foreach (var entry in LiveContexts)
|
||||
{
|
||||
// Removing by (key, value) pair, as in the ctor prune, never evicts a re-registered
|
||||
// entry. Both arms evict and prune any rooted callback handlers keyed by the address;
|
||||
// they differ only in whether a live wrapper survives for MarkOrphaned below.
|
||||
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;
|
||||
}
|
||||
|
||||
// The native contexts are gone, so their wrappers must stop claiming to hold one - otherwise
|
||||
// every later call on them (Dispose included) targets a freed address. Device.Dispose calls
|
||||
// this only AFTER the close succeeds; on failure the contexts are still alive natively, and
|
||||
// invalidating their wrappers would strand them.
|
||||
internal static void MarkOrphaned(List<Context> orphans)
|
||||
{
|
||||
foreach (var context in orphans)
|
||||
context.Handle = AlcContext.Null;
|
||||
}
|
||||
}
|
||||
261
brutal.openal/Brutal.OpenAl/Manual/Context.cs
Normal file
261
brutal.openal/Brutal.OpenAl/Manual/Context.cs
Normal file
|
|
@ -0,0 +1,261 @@
|
|||
// Sealed IDisposable wrapper over the raw AlcContext handle: Device.CreateContext constructs it,
|
||||
// Dispose destroys it. No finalizer and no Destroy() alias - disposal is explicit.
|
||||
//
|
||||
// Currency (which context is current) is native process state; this type never mirrors it. The
|
||||
// LiveContexts ledger (Context.Internal.cs) only maps native addresses back to the wrappers this
|
||||
// layer created, so Current can return the owning object. The ledger is weak (it must never keep
|
||||
// an abandoned wrapper alive); do not extend the pattern to per-object types like AlSource.
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
/// <summary>
|
||||
/// An OpenAL context, created on a <see cref="OpenAlApi.Device"/> by <see cref="OpenAlApi.Device.CreateContext"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Owns the underlying native context: call <see cref="Dispose"/> exactly once. Disposing it
|
||||
/// while current detaches it globally and on the calling thread. A thread-local context made
|
||||
/// current on another thread must be detached on that thread first.
|
||||
/// </remarks>
|
||||
public sealed partial class Context : IDisposable, INullable
|
||||
{
|
||||
/// <summary>
|
||||
/// Options for <see cref="OpenAlApi.Device.CreateContext"/>.
|
||||
/// </summary>
|
||||
public ref struct CreateInfo()
|
||||
{
|
||||
/// <summary>
|
||||
/// Attribute/value pairs; no trailing zero (appended internally). Extension keys not on
|
||||
/// <see cref="AlcContextAttribute"/> are passed by casting the constant.
|
||||
/// </summary>
|
||||
public ReadOnlySpan<(AlcContextAttribute Attribute, int Value)> Attributes = [];
|
||||
}
|
||||
|
||||
/// <summary>The device this context was created on.</summary>
|
||||
/// <remarks>
|
||||
/// Not necessarily the owning wrapper. For a context created on a
|
||||
/// <see cref="LoopbackDevice"/> this is an internal plumbing <see cref="OpenAlApi.Device"/>
|
||||
/// around the same handle: its <see cref="OpenAlApi.Device.Dispose"/> is a no-op and its
|
||||
/// <see cref="OpenAlApi.Device.Close"/> throws - dispose the owning
|
||||
/// <see cref="LoopbackDevice"/> instead.
|
||||
/// </remarks>
|
||||
public Device Device { get; }
|
||||
|
||||
/// <summary>The raw context handle.</summary>
|
||||
public AlcContext Handle { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// The context current in the process, or <see langword="null"/> if none is current.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Reads the native state (<c>alcGetCurrentContext</c>) on every access, then resolves the
|
||||
/// handle to the wrapper that created it. <see langword="null"/> therefore does not prove
|
||||
/// nothing is current natively: a context made current via raw interop, or whose wrapper was
|
||||
/// garbage-collected undisposed, also reads as <see langword="null"/> - code mixing in raw
|
||||
/// interop should query <see cref="Alc.PInvoke"/> directly.
|
||||
/// </remarks>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether this context is current in the process (compares against
|
||||
/// <c>alcGetCurrentContext</c>). A disposed context is never current.
|
||||
/// </summary>
|
||||
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 ledger entries whose wrapper was collected without Dispose (a leaked context).
|
||||
// Removing by (key, value) pair never evicts an entry another thread re-registered under a
|
||||
// recycled address between the read and the remove.
|
||||
foreach (var entry in LiveContexts)
|
||||
{
|
||||
if (!entry.Value.TryGetTarget(out _))
|
||||
LiveContexts.TryRemove(entry);
|
||||
}
|
||||
LiveContexts[Handle.Pointer] = new WeakReference<Context>(this);
|
||||
}
|
||||
|
||||
/// <summary>Returns <see langword="true"/> if this context has already been disposed.</summary>
|
||||
public bool IsNull() => Handle.IsNull();
|
||||
|
||||
/// <summary>
|
||||
/// Makes a context current in the process, or detaches the current context when
|
||||
/// <paramref name="context"/> is <see langword="null"/> (<c>alcMakeContextCurrent</c>; a null
|
||||
/// context is the native detach idiom). Throws <see cref="AlcException"/> on a disposed
|
||||
/// context rather than silently detaching.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
// A disposed context's null handle is not passed through: alcMakeContextCurrent(NULL)
|
||||
// SUCCEEDS by detaching, so a disposed Context would silently detach instead of failing.
|
||||
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.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to make a context current (or detach with <see langword="null"/>), without throwing.
|
||||
/// </summary>
|
||||
public static bool TryMakeCurrent(Context? context)
|
||||
{
|
||||
if (context is null)
|
||||
return Alc.PInvoke.MakeContextCurrent(AlcContext.Null);
|
||||
return !context.IsNull() && Alc.PInvoke.MakeContextCurrent(context.Handle);
|
||||
}
|
||||
|
||||
/// <summary>Makes this context current in the process (<c>alcMakeContextCurrent</c>).</summary>
|
||||
public void MakeCurrent() => MakeCurrent(this);
|
||||
|
||||
/// <summary>Tries to make this context current, without throwing (<c>alcMakeContextCurrent</c>).</summary>
|
||||
public bool TryMakeCurrent() => TryMakeCurrent(this);
|
||||
|
||||
/// <summary>
|
||||
/// The context current on the calling thread, or <see langword="null"/> if no thread-local
|
||||
/// context is set. Provided by <c>ALC_EXT_thread_local_context</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Reads <c>alcGetThreadContext</c> and resolves the wrapper as <see cref="Current"/> does;
|
||||
/// the same caveats apply. With no thread-local override, the thread follows the
|
||||
/// process-wide context (<see cref="Current"/>) - which this still reports as
|
||||
/// <see langword="null"/>.
|
||||
/// </remarks>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes a context current on the calling thread only, overriding process-wide currency for
|
||||
/// this thread, or clears the override when <paramref name="context"/> is
|
||||
/// <see langword="null"/> (<c>alcSetThreadContext</c>). Throws <see cref="AlcException"/> on
|
||||
/// a disposed context rather than silently detaching. Provided by
|
||||
/// <c>ALC_EXT_thread_local_context</c>.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
// As in MakeCurrent: a disposed context's null handle is not passed through, since
|
||||
// alcSetThreadContext(NULL) SUCCEEDS by detaching rather than failing.
|
||||
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.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to make a context current on the calling thread (or clear the override with
|
||||
/// <see langword="null"/>), without throwing. Provided by <c>ALC_EXT_thread_local_context</c>.
|
||||
/// </summary>
|
||||
public static bool TryMakeThreadCurrent(Context? context)
|
||||
{
|
||||
if (context is null)
|
||||
return Alc.PInvoke.SetThreadContext(AlcContext.Null);
|
||||
return !context.IsNull() && Alc.PInvoke.SetThreadContext(context.Handle);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes this context current on the calling thread (<c>alcSetThreadContext</c>). Provided
|
||||
/// by <c>ALC_EXT_thread_local_context</c>.
|
||||
/// </summary>
|
||||
public void MakeThreadCurrent() => MakeThreadCurrent(this);
|
||||
|
||||
/// <summary>
|
||||
/// Tries to make this context current on the calling thread, without throwing
|
||||
/// (<c>alcSetThreadContext</c>). Provided by <c>ALC_EXT_thread_local_context</c>.
|
||||
/// </summary>
|
||||
public bool TryMakeThreadCurrent() => TryMakeThreadCurrent(this);
|
||||
|
||||
// Disposal guard for the handle-bearing instance members (a disposed context must not pass
|
||||
// its nulled handle to native, where it reads as "no context"). MakeCurrent keeps its own
|
||||
// documented AlcException contract; Handle, IsNull() and the implicit conversion stay
|
||||
// unguarded as the raw escape hatch, matching Device.
|
||||
private AlcContext CheckedHandle
|
||||
{
|
||||
get
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return Handle;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Alc.PInvoke.ProcessContext"/>
|
||||
public void Process() => Alc.PInvoke.ProcessContext(CheckedHandle);
|
||||
|
||||
/// <inheritdoc cref="Alc.PInvoke.SuspendContext"/>
|
||||
public void Suspend() => Alc.PInvoke.SuspendContext(CheckedHandle);
|
||||
|
||||
/// <summary>
|
||||
/// Destroys the context (<c>alcDestroyContext</c>). If it is current, the bundled
|
||||
/// openal-soft detaches it globally and on the calling thread. A context made current on
|
||||
/// another thread via <see cref="MakeThreadCurrent(Context?)"/> must be detached there first.
|
||||
/// Idempotent but not safe to call concurrently; no finalizer - an undisposed context leaks.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Implicitly converts to the raw <see cref="AlcContext"/> handle.</summary>
|
||||
public static implicit operator AlcContext(Context context) => context.Handle;
|
||||
}
|
||||
451
brutal.openal/Brutal.OpenAl/Manual/Device.cs
Normal file
451
brutal.openal/Brutal.OpenAl/Manual/Device.cs
Normal file
|
|
@ -0,0 +1,451 @@
|
|||
// Sealed IDisposable wrapper over the raw AlcDevice handle: Alc.OpenDevice constructs it, Dispose
|
||||
// closes it. No finalizer and no Destroy() alias - disposal is explicit. AlcDevice stays the raw,
|
||||
// non-owning handle used at the [LibraryImport] boundary.
|
||||
|
||||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.HighPerformance.Buffers;
|
||||
|
||||
namespace Brutal.OpenAlApi;
|
||||
|
||||
/// <summary>A device's clock time paired with its output latency. Provided by <c>ALC_SOFT_device_clock</c>.</summary>
|
||||
/// <param name="ClockTime">The device clock, in nanoseconds.</param>
|
||||
/// <param name="Latency">The device's output latency, in nanoseconds.</param>
|
||||
public readonly record struct AlcClockLatency(long ClockTime, long Latency);
|
||||
|
||||
/// <summary>
|
||||
/// An OpenAL playback device, opened by <see cref="Alc.OpenDevice"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Owns the underlying native device: call <see cref="Dispose"/> after disposing every
|
||||
/// <see cref="Context"/> created on it (see <see cref="Alc"/> for the full teardown order).
|
||||
/// Converts implicitly to the raw, non-owning <see cref="AlcDevice"/> handle.
|
||||
/// </remarks>
|
||||
public sealed class Device : IDisposable, INullable
|
||||
{
|
||||
private readonly bool _ownedByLoopback;
|
||||
|
||||
/// <summary>The raw device handle.</summary>
|
||||
public AlcDevice Handle { get; private set; }
|
||||
|
||||
internal Device(AlcDevice handle, bool ownedByLoopback = false)
|
||||
{
|
||||
Handle = handle;
|
||||
_ownedByLoopback = ownedByLoopback;
|
||||
}
|
||||
|
||||
// The disposal guard shared by every member that touches native state or returns cached
|
||||
// native answers: a disposed device must never answer plausibly (a nulled handle reads as
|
||||
// Connected == false, MajorVersion == 1, ...). Handle itself, IsNull() and the implicit
|
||||
// conversion stay unguarded - they are the raw escape hatch, and a null handle there is an
|
||||
// honest answer. Efx shares the guard through ThrowIfDisposed and reads Handle itself.
|
||||
private AlcDevice CheckedHandle
|
||||
{
|
||||
get
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
return Handle;
|
||||
}
|
||||
}
|
||||
|
||||
internal void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
|
||||
private Efx? _efx;
|
||||
|
||||
// Lifetime-constant query results, cached on first access. Reopen can change the device's
|
||||
// identity, so it drops the specifier caches; Reset and Reopen can both renegotiate the HRTF
|
||||
// set, so both drop that cache. Versions and the extension list are fixed by the loaded
|
||||
// implementation and never invalidated.
|
||||
private string? _specifier;
|
||||
private string? _allDevicesSpecifier;
|
||||
private ReadOnlyCollection<string>? _extensions;
|
||||
private ReadOnlyCollection<string>? _hrtfSpecifiers;
|
||||
private int? _majorVersion;
|
||||
private int? _minorVersion;
|
||||
|
||||
/// <summary>
|
||||
/// The EFX surface for this device. The pinned openal-soft always implements
|
||||
/// <c>ALC_EXT_EFX</c>, so this needs no presence gate.
|
||||
/// </summary>
|
||||
public Efx Efx
|
||||
{
|
||||
get
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
return _efx ??= new Efx(this);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Returns <see langword="true"/> if this device has not been opened, or has already been disposed.</summary>
|
||||
public bool IsNull() => Handle.IsNull();
|
||||
|
||||
/// <summary>
|
||||
/// The device's name (<c>ALC_DEVICE_SPECIFIER</c>). Cached; <see cref="Reopen"/> drops the cache.
|
||||
/// </summary>
|
||||
public string? Specifier
|
||||
{
|
||||
get
|
||||
{
|
||||
// Guard before the cache, not just before the query: a cached answer on a disposed
|
||||
// device is still an answer a disposed device must not give. Same in every cached
|
||||
// getter below.
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return _specifier ??= Alc.GetString(Handle, AlcGetString.DeviceSpecifier);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The device's full name from the extended enumeration (<c>ALC_ALL_DEVICES_SPECIFIER</c>).
|
||||
/// Cached; <see cref="Reopen"/> drops the cache.
|
||||
/// </summary>
|
||||
public string? AllDevicesSpecifier
|
||||
{
|
||||
get
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return _allDevicesSpecifier ??= Alc.GetString(Handle, AlcGetString.AllDevicesSpecifier);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The device's ALC extension list (<c>ALC_EXTENSIONS</c>) as a read-only view over the
|
||||
/// cached list. Queried once per device; no allocation per access.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The major version of the device's ALC implementation (<c>ALC_MAJOR_VERSION</c>).</summary>
|
||||
public int MajorVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return _majorVersion ??= Alc.GetInteger(Handle, AlcInteger.MajorVersion);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The minor version of the device's ALC implementation (<c>ALC_MINOR_VERSION</c>).</summary>
|
||||
public int MinorVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return _minorVersion ??= Alc.GetInteger(Handle, AlcInteger.MinorVersion);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The device's context attribute list (<c>ALC_ALL_ATTRIBUTES</c>) as attribute/value pairs.
|
||||
/// Attribute keys not surfaced on <see cref="AlcContextAttribute"/> (extension tokens) appear
|
||||
/// as their raw constant values cast to the enum.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Queries whether an ALC extension is present for this device (<c>alcIsExtensionPresent</c>).</summary>
|
||||
public bool IsExtensionPresent(string name) => Alc.IsExtensionPresent(CheckedHandle, name);
|
||||
|
||||
/// <summary>
|
||||
/// Resolves an extension entry point scoped to this device (<c>alcGetProcAddress</c>), or
|
||||
/// throws <see cref="AlExtensionException"/> if it is unavailable.
|
||||
/// </summary>
|
||||
public unsafe void* GetProcAddress(string name) => Alc.GetProcAddress(CheckedHandle, name);
|
||||
|
||||
/// <summary>
|
||||
/// Reads and clears this device's ALC error (<c>alcGetError</c>), without throwing on a
|
||||
/// latched error.
|
||||
/// </summary>
|
||||
public AlcError GetError()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return Alc.GetError(Handle);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads and clears this device's ALC error, throwing <see cref="AlcException"/> if one was
|
||||
/// set. Never called automatically by wrapper methods, as with <see cref="Al.ThrowIfError"/>.
|
||||
/// </summary>
|
||||
public void ThrowIfError()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
Alc.ThrowIfError(Handle);
|
||||
}
|
||||
|
||||
/// <summary>Creates a context on this device (<c>alcCreateContext</c>).</summary>
|
||||
public Context CreateContext(Context.CreateInfo info = default)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
return new(this, info);
|
||||
}
|
||||
|
||||
/// <summary>Pauses device processing (<c>alcDevicePauseSOFT</c>). Provided by <c>ALC_SOFT_pause_device</c>.</summary>
|
||||
public void Pause() => Alc.PInvoke.DevicePauseSOFT(CheckedHandle);
|
||||
|
||||
/// <summary>
|
||||
/// Resumes device processing after <see cref="Pause"/> (<c>alcDeviceResumeSOFT</c>). Provided by
|
||||
/// <c>ALC_SOFT_pause_device</c>.
|
||||
/// </summary>
|
||||
public void Resume() => Alc.PInvoke.DeviceResumeSOFT(CheckedHandle);
|
||||
|
||||
/// <summary>
|
||||
/// Whether the device is still connected (<c>ALC_CONNECTED</c>). Provided by
|
||||
/// <c>ALC_EXT_disconnect</c>.
|
||||
/// </summary>
|
||||
public bool Connected => Alc.GetInteger(CheckedHandle, AlcInteger.Connected) != 0;
|
||||
|
||||
/// <summary>
|
||||
/// The device clock, in nanoseconds (<c>ALC_DEVICE_CLOCK_SOFT</c>). Provided by
|
||||
/// <c>ALC_SOFT_device_clock</c>.
|
||||
/// </summary>
|
||||
public unsafe long ClockTime
|
||||
{
|
||||
get
|
||||
{
|
||||
long value = 0;
|
||||
Alc.PInvoke.GetInteger64vSOFT(CheckedHandle, Alc.Constants.ALC_DEVICE_CLOCK_SOFT, 1, &value);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The device's output latency, in nanoseconds (<c>ALC_DEVICE_LATENCY_SOFT</c>). Provided by
|
||||
/// <c>ALC_SOFT_device_clock</c>.
|
||||
/// </summary>
|
||||
public unsafe long Latency
|
||||
{
|
||||
get
|
||||
{
|
||||
long value = 0;
|
||||
Alc.PInvoke.GetInteger64vSOFT(CheckedHandle, Alc.Constants.ALC_DEVICE_LATENCY_SOFT, 1, &value);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The device clock and output latency, read atomically (<c>ALC_DEVICE_CLOCK_LATENCY_SOFT</c>).
|
||||
/// Provided by <c>ALC_SOFT_device_clock</c>.
|
||||
/// </summary>
|
||||
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]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why HRTF is or is not in use on the device (<c>ALC_HRTF_STATUS_SOFT</c>). Provided by
|
||||
/// <c>ALC_SOFT_HRTF</c>.
|
||||
/// </summary>
|
||||
public AlcHrtfStatus HrtfStatus => (AlcHrtfStatus)Alc.GetInteger(CheckedHandle, AlcInteger.HrtfStatus);
|
||||
|
||||
/// <summary>
|
||||
/// The available HRTF specifiers (<c>ALC_HRTF_SPECIFIER_SOFT</c>, indexed up to
|
||||
/// <c>ALC_NUM_HRTF_SPECIFIERS_SOFT</c>) as a read-only view over the cached list. No
|
||||
/// allocation per access. <see cref="Reset"/> and <see cref="Reopen"/> drop the cache, so
|
||||
/// the result is a snapshot: a list held across either call keeps describing the device as
|
||||
/// it was, and the next access re-queries. Provided by <c>ALC_SOFT_HRTF</c>.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the device with a new attribute list, without closing it (<c>alcResetDeviceSOFT</c>).
|
||||
/// Provided by <c>ALC_SOFT_HRTF</c>.
|
||||
/// </summary>
|
||||
/// <param name="attributes">Attribute/value pairs; no trailing zero (appended internally).</param>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reopens the device, optionally under a different name, with a new attribute list
|
||||
/// (<c>alcReopenDeviceSOFT</c>). Provided by <c>ALC_SOFT_reopen_device</c>.
|
||||
/// </summary>
|
||||
/// <param name="deviceName">The device name, or <see langword="null"/> to keep the current device.</param>
|
||||
/// <param name="attributes">Attribute/value pairs; no trailing zero (appended internally).</param>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The device's channel output mode (<c>ALC_OUTPUT_MODE_SOFT</c>). Provided by
|
||||
/// <c>ALC_SOFT_output_mode</c>.
|
||||
/// </summary>
|
||||
public AlcOutputMode OutputMode => (AlcOutputMode)Alc.GetInteger(CheckedHandle, AlcInteger.OutputMode);
|
||||
|
||||
/// <summary>
|
||||
/// Closes the device (<c>alcCloseDevice</c>), throwing <see cref="AlcException"/> if the
|
||||
/// native close reports failure - the explicit-lifetime counterpart of
|
||||
/// <see cref="Dispose"/>, which swallows it. Dispose every context created on this device
|
||||
/// first; any still live are destroyed with the device and their wrappers invalidated. The
|
||||
/// wrapper is disposed either way, so a later <see cref="Dispose"/> (a <see langword="using"/>
|
||||
/// safety net) is a no-op.
|
||||
/// </summary>
|
||||
public void Close()
|
||||
{
|
||||
if (_ownedByLoopback)
|
||||
throw new InvalidOperationException("Close the owning LoopbackDevice instead.");
|
||||
ObjectDisposedException.ThrowIf(IsNull(), this);
|
||||
CloseUnchecked();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes the device (<c>alcCloseDevice</c>). Dispose every context created on this device
|
||||
/// first; any still live are destroyed with the device and their wrappers invalidated.
|
||||
/// Never throws: a failed close leaves its reason on the global ALC error latch - call
|
||||
/// <see cref="Close"/> instead when failure should surface. Idempotent but not safe to call
|
||||
/// concurrently; no finalizer - an undisposed device leaks. On the plumbing
|
||||
/// <see cref="Context.Device"/> of a <see cref="LoopbackDevice"/> context this is a no-op:
|
||||
/// the loopback wrapper owns the handle.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
// Dispose must never throw (see below), so ownership misuse cannot surface here the way
|
||||
// Close() surfaces it. Nothing is owned, so there is nothing to do.
|
||||
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 never throw: inside a `using` whose body already threw, an exception here
|
||||
// would REPLACE the original fault. A failed close leaves its reason on the global latch;
|
||||
// Close() is the path that surfaces it.
|
||||
CloseCore();
|
||||
}
|
||||
|
||||
private bool CloseCore()
|
||||
{
|
||||
// Closing destroys any live contexts on this device without their Dispose running, so
|
||||
// their ledger entries are evicted first - a freed, recyclable address must never stay
|
||||
// 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);
|
||||
|
||||
// Only once the close succeeded are the orphaned contexts definitely gone and their
|
||||
// wrappers safe to invalidate; on failure they are still alive natively (see
|
||||
// Context.MarkOrphaned).
|
||||
if (closed)
|
||||
Context.MarkOrphaned(orphans);
|
||||
|
||||
// The wrapper dies either way: a failed close means an invalid or already-closed handle
|
||||
// (openal-soft destroys live contexts rather than refusing), and a deterministic dead
|
||||
// wrapper beats a half-alive one no caller will retry.
|
||||
Handle = AlcDevice.Null;
|
||||
return closed;
|
||||
}
|
||||
|
||||
/// <summary>Implicitly converts to the raw <see cref="AlcDevice"/> handle.</summary>
|
||||
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