SOURCE DUMP v1

This commit is contained in:
Rian Drake 2026-10-15 14:09:11 +13:00
commit fb20299e9d
13 changed files with 768360 additions and 0 deletions

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,46 @@
// <auto-generated/>
// Generated by Brutal.Sdl.Generate; do not edit by hand.
#nullable enable
namespace Brutal.SdlApi.Mixer
{
public static unsafe partial class SdlMixer
{
public static class Constants
{
public const int DurationInfinite = -2;
public const int DurationUnknown = -1;
public const string PropAudioDecoderString = "SDL_mixer.audio.decoder";
public const string PropAudioLoadCloseioBoolean = "SDL_mixer.audio.load.closeio";
public const string PropAudioLoadIgnoreLoopsBoolean = "SDL_mixer.audio.load.ignore_loops";
public const string PropAudioLoadIostreamPointer = "SDL_mixer.audio.load.iostream";
public const string PropAudioLoadPredecodeBoolean = "SDL_mixer.audio.load.predecode";
public const string PropAudioLoadPreferredMixerPointer = "SDL_mixer.audio.load.preferred_mixer";
public const string PropAudioLoadSkipMetadataTagsBoolean = "SDL_mixer.audio.load.skip_metadata_tags";
public const string PropMetadataAlbumString = "SDL_mixer.metadata.album";
public const string PropMetadataArtistString = "SDL_mixer.metadata.artist";
public const string PropMetadataCopyrightString = "SDL_mixer.metadata.copyright";
public const string PropMetadataDurationFramesNumber = "SDL_mixer.metadata.duration_frames";
public const string PropMetadataDurationInfiniteBoolean = "SDL_mixer.metadata.duration_infinite";
public const string PropMetadataTitleString = "SDL_mixer.metadata.title";
public const string PropMetadataTotalTracksNumber = "SDL_mixer.metadata.total_tracks";
public const string PropMetadataTrackNumber = "SDL_mixer.metadata.track";
public const string PropMetadataYearNumber = "SDL_mixer.metadata.year";
public const string PropMixerDeviceNumber = "SDL_mixer.mixer.device";
public const string PropPlayAppendSilenceFramesNumber = "SDL_mixer.play.append_silence_frames";
public const string PropPlayAppendSilenceMillisecondsNumber = "SDL_mixer.play.append_silence_milliseconds";
public const string PropPlayFadeInFramesNumber = "SDL_mixer.play.fade_in_frames";
public const string PropPlayFadeInMillisecondsNumber = "SDL_mixer.play.fade_in_milliseconds";
public const string PropPlayFadeInStartGainFloat = "SDL_mixer.play.fade_in_start_gain";
public const string PropPlayHaltWhenExhaustedBoolean = "SDL_mixer.play.halt_when_exhausted";
public const string PropPlayLoopsNumber = "SDL_mixer.play.loops";
public const string PropPlayLoopStartFrameNumber = "SDL_mixer.play.loop_start_frame";
public const string PropPlayLoopStartMillisecondNumber = "SDL_mixer.play.loop_start_millisecond";
public const string PropPlayMaxFrameNumber = "SDL_mixer.play.max_frame";
public const string PropPlayMaxMillisecondsNumber = "SDL_mixer.play.max_milliseconds";
public const string PropPlayStartFrameNumber = "SDL_mixer.play.start_frame";
public const string PropPlayStartMillisecondNumber = "SDL_mixer.play.start_millisecond";
public const string PropPlayStartOrderNumber = "SDL_mixer.play.start_order";
}
}
}

View file

@ -0,0 +1,36 @@
// <auto-generated/>
// Generated by Brutal.Sdl.Generate; do not edit by hand.
#nullable enable
namespace Brutal.SdlApi.Mixer
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void MixTrackStoppedCallback(void* userdata, MixTrack track);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void MixTrackMixCallback(
void* userdata,
MixTrack track,
SdlAudioSpec* spec,
float* pcm,
int samples
);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void MixGroupMixCallback(
void* userdata,
MixGroup group,
SdlAudioSpec* spec,
float* pcm,
int samples
);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void MixPostMixCallback(
void* userdata,
MixMixer mixer,
SdlAudioSpec* spec,
float* pcm,
int samples
);
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,98 @@
// <auto-generated/>
// Generated by Brutal.Sdl.Generate; do not edit by hand.
#nullable enable
using System;
using Brutal.Interop;
namespace Brutal.SdlApi.Mixer;
/// <summary>
/// A strongly-typed interop handle wrapping the opaque SDL <c>MIX_Audio</c> pointer.
/// </summary>
[InteropHandle]
public readonly unsafe partial struct MixAudio : IDisposable
{
/// <inheritdoc/>
public void Dispose()
{
// A default/zeroed handle owns nothing; forwarding it to the native destructor is at
// best a wasted call and at worst undefined behaviour. Guard so Dispose is a safe no-op
// on a null handle (and so a double-dispose after the value was cleared is harmless).
if (IsNull())
return;
SdlMixer.PInvoke.DestroyAudio(this);
}
}
/// <summary>
/// A strongly-typed interop handle wrapping the opaque SDL <c>MIX_AudioDecoder</c> pointer.
/// </summary>
[InteropHandle]
public readonly unsafe partial struct MixAudioDecoder : IDisposable
{
/// <inheritdoc/>
public void Dispose()
{
// A default/zeroed handle owns nothing; forwarding it to the native destructor is at
// best a wasted call and at worst undefined behaviour. Guard so Dispose is a safe no-op
// on a null handle (and so a double-dispose after the value was cleared is harmless).
if (IsNull())
return;
SdlMixer.PInvoke.DestroyAudioDecoder(this);
}
}
/// <summary>
/// A strongly-typed interop handle wrapping the opaque SDL <c>MIX_Group</c> pointer.
/// </summary>
[InteropHandle]
public readonly unsafe partial struct MixGroup : IDisposable
{
/// <inheritdoc/>
public void Dispose()
{
// A default/zeroed handle owns nothing; forwarding it to the native destructor is at
// best a wasted call and at worst undefined behaviour. Guard so Dispose is a safe no-op
// on a null handle (and so a double-dispose after the value was cleared is harmless).
if (IsNull())
return;
SdlMixer.PInvoke.DestroyGroup(this);
}
}
/// <summary>
/// A strongly-typed interop handle wrapping the opaque SDL <c>MIX_Mixer</c> pointer.
/// </summary>
[InteropHandle]
public readonly unsafe partial struct MixMixer : IDisposable
{
/// <inheritdoc/>
public void Dispose()
{
// A default/zeroed handle owns nothing; forwarding it to the native destructor is at
// best a wasted call and at worst undefined behaviour. Guard so Dispose is a safe no-op
// on a null handle (and so a double-dispose after the value was cleared is harmless).
if (IsNull())
return;
SdlMixer.PInvoke.DestroyMixer(this);
}
}
/// <summary>
/// A strongly-typed interop handle wrapping the opaque SDL <c>MIX_Track</c> pointer.
/// </summary>
[InteropHandle]
public readonly unsafe partial struct MixTrack : IDisposable
{
/// <inheritdoc/>
public void Dispose()
{
// A default/zeroed handle owns nothing; forwarding it to the native destructor is at
// best a wasted call and at worst undefined behaviour. Guard so Dispose is a safe no-op
// on a null handle (and so a double-dispose after the value was cleared is harmless).
if (IsNull())
return;
SdlMixer.PInvoke.DestroyTrack(this);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,21 @@
// <auto-generated/>
// Generated by Brutal.Sdl.Generate; do not edit by hand.
#nullable enable
namespace Brutal.SdlApi.Mixer
{
[StructLayout(LayoutKind.Sequential)]
public partial struct MixStereoGains
{
public float left;
public float right;
}
[StructLayout(LayoutKind.Sequential)]
public partial struct MixPoint3D
{
public float x;
public float y;
public float z;
}
}

View file

@ -0,0 +1,3 @@
global using System.Runtime.CompilerServices;
global using System.Runtime.InteropServices;
global using Brutal.SdlApi;

View file

@ -0,0 +1,237 @@
THIRD-PARTY LICENSE NOTICES
RocketWerkz.Brutal.Sdl.Mixer
This package redistributes third-party software. The licenses governing that software
are reproduced below in full.
WHAT THIS PACKAGE CONTAINS
One native library, on every runtime identifier the package supports
(win-x64, linux-x64, osx-arm64):
SDL_mixer 3.2.4 SDL3_mixer.dll / libSDL3_mixer.so / libSDL3_mixer.dylib
Three decoders maintained by third parties are compiled into that library and are
governed by their own licenses, one section each below:
stb_vorbis Ogg Vorbis decoding
dr_flac FLAC decoding
dr_mp3 MP3 decoding
A NOTE ON SCOPE
This package depends on RocketWerkz.Brutal.Sdl and links against SDL3 at runtime.
SDL3 is not contained in this package and is covered by that package's own notices.
SDL_mixer can optionally be built against libmpg123, libFLAC, libvorbis, libopus,
libxmp, libgme, WavPack and FluidSynth. This build enables none of them and
substitutes the header-only decoders named above. None of those optional libraries
is contained in the shipped library, and none is attributed here.
==============================================================================
SDL_mixer
==============================================================================
Name SDL_mixer
Version 3.2.4
Upstream https://github.com/libsdl-org/SDL_mixer
SPDX Zlib
Shipped as SDL3_mixer.dll, libSDL3_mixer.so, libSDL3_mixer.dylib
Copyright (C) 1997-2026 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
==============================================================================
stb_vorbis
==============================================================================
Name stb_vorbis
Version as vendored by SDL_mixer 3.2.4
Upstream https://github.com/nothings/stb
SPDX MIT OR Unlicense
Shipped as compiled into SDL3_mixer.dll, libSDL3_mixer.so, libSDL3_mixer.dylib
stb_vorbis is offered under two mutually exclusive licenses, both reproduced below
as upstream states them.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2017 Sean Barrett
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
==============================================================================
dr_flac
==============================================================================
Name dr_flac
Version 0.13.4 (as vendored by SDL_mixer 3.2.4)
Upstream https://github.com/mackron/dr_libs
SPDX Unlicense OR MIT-0
Shipped as compiled into SDL3_mixer.dll, libSDL3_mixer.so, libSDL3_mixer.dylib
This software is available as a choice of the following licenses. Choose
whichever you prefer.
===============================================================================
ALTERNATIVE 1 - Public Domain (www.unlicense.org)
===============================================================================
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
===============================================================================
ALTERNATIVE 2 - MIT No Attribution
===============================================================================
Copyright 2023 David Reid
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
==============================================================================
dr_mp3
==============================================================================
Name dr_mp3
Version 0.7.4 (as vendored by SDL_mixer 3.2.4)
Upstream https://github.com/mackron/dr_libs
SPDX Unlicense OR MIT-0
Shipped as compiled into SDL3_mixer.dll, libSDL3_mixer.so, libSDL3_mixer.dylib
dr_mp3's decoding core derives from minimp3 -- "where the real work was done",
in dr_mp3's own words. The dr_libs terms come first, then minimp3's dedication,
both as dr_mp3 carries them. minimp3 names no copyright holder.
This software is available as a choice of the following licenses. Choose
whichever you prefer.
===============================================================================
ALTERNATIVE 1 - Public Domain (www.unlicense.org)
===============================================================================
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
===============================================================================
ALTERNATIVE 2 - MIT No Attribution
===============================================================================
Copyright 2023 David Reid
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
----------------------------------------------------------------------------
minimp3 -- the dedication carried for the code dr_mp3 derives from
----------------------------------------------------------------------------
https://github.com/lieff/minimp3
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide.
This software is distributed without any warranty.
See <http://creativecommons.org/publicdomain/zero/1.0/>.

View file

@ -0,0 +1,130 @@
namespace Brutal.SdlApi.Mixer;
/// <summary>
/// Collects exceptions thrown inside SDL_mixer callbacks and rethrows them from managed code.
/// </summary>
/// <remarks>
/// This is the SDL_mixer analogue of core's <c>Brutal.SdlApi.ExceptionAggregator</c>, replicated here
/// (rather than shared) because core's type is <c>internal</c> to <c>Brutal.Sdl</c> and because the
/// two aggregators serve threads with fundamentally different concurrency: core's callbacks fire on
/// the single event-pump thread, whereas SDL_mixer invokes its track-stopped / mix hooks on its own
/// audio device thread(s). A callback exception cannot legally unwind across the native stack frame
/// that called it, so the trampolines catch every exception and hand it here via <see cref="Push"/>,
/// which also logs it immediately so it is never silently lost. Pending exceptions are rethrown from
/// managed code either at the next mixer/track/group-touching ergonomic method (each drains via
/// <see cref="CheckExceptions"/>) or explicitly via
/// <see cref="SdlMixer.ThrowPendingCallbackExceptions"/>. The reused public
/// <see cref="SdlCallbackException"/> type (from <c>Brutal.Sdl</c>) carries each wrapped failure.
/// <para>
/// <b>Thread safety:</b> every mutating and draining operation takes <see cref="_lock"/>, so an
/// audio thread calling <see cref="Push"/> and the game thread calling <see cref="CheckExceptions"/>
/// (or two audio threads pushing concurrently) never race on the pending list. To bound memory when
/// no drain point is reached for a while, only the first <see cref="MaxRetained"/> exceptions are
/// kept; further ones are counted and reported but not stored.
/// </para>
/// </remarks>
internal sealed class ExceptionAggregator
{
/// <summary>The maximum number of pending exceptions retained; beyond this only a count is kept.</summary>
public const int MaxRetained = 16;
private readonly List<Exception> _exceptions = [];
private int _dropped;
private readonly Lock _lock = new();
/// <summary>
/// Records an exception raised inside a native-to-managed SDL_mixer callback so it can be rethrown
/// from managed code at the next <see cref="CheckExceptions"/>. The exception is logged immediately
/// at error level (so it is visible even if no drain point is ever reached) and retained up to
/// <see cref="MaxRetained"/> entries; further exceptions increment a dropped counter. Safe to call
/// concurrently from any audio thread.
/// </summary>
/// <param name="message">A description of the callback in which the exception occurred.</param>
/// <param name="innerException">The exception that was caught, preserved as the inner exception.</param>
public void Push(string message, Exception? innerException = null)
{
var wrapped = innerException is null
? new SdlCallbackException(message)
: new SdlCallbackException(message, innerException);
// Store FIRST (under the lock) so the parked exception is durably retained before anything that
// can fail runs — a faulting logger must never be able to drop it. This is the "never lost"
// guarantee.
lock (_lock)
{
if (_exceptions.Count < MaxRetained)
_exceptions.Add(wrapped);
else
_dropped++;
}
// Then log for promptness (the exception may sit pending until a drain point). This runs on the
// SDL_mixer audio device thread, so it is wrapped in its own catch: a logging failure here must
// never re-escape into native code (a managed exception unwinding into the audio thread is the
// exact UB / hard crash this whole trampoline design exists to prevent) — and the payload is
// already retained above, so swallowing the logging fault loses nothing. This is the one place
// an empty catch is correct: it is a native-boundary firewall on a real-time thread.
try
{
SdlMixer.TraceLog.Error(wrapped);
}
catch
{
// Intentionally swallowed: the exception is already parked; a logging fault must not cross
// the native boundary.
}
}
/// <summary>
/// Rethrows any exceptions captured since the last check, then clears the pending set. Does
/// nothing when nothing is pending. A single pending exception (with none dropped) is rethrown
/// directly; otherwise the pending exceptions are wrapped in an <see cref="AggregateException"/>
/// whose message notes how many further exceptions were dropped.
/// </summary>
/// <exception cref="SdlCallbackException">Exactly one callback exception was pending.</exception>
/// <exception cref="AggregateException">More than one callback exception was pending, or some were dropped.</exception>
public void CheckExceptions()
{
Exception exception;
lock (_lock)
{
if (_exceptions.Count == 0)
return;
var dropped = _dropped;
if (_exceptions.Count == 1 && dropped == 0)
{
exception = _exceptions[0];
}
else
{
var message =
$"{_exceptions.Count} SDL_mixer callback exception(s) occurred."
+ (
dropped > 0
? $" A further {dropped} were dropped (only the first {MaxRetained} are retained)."
: ""
);
exception = new AggregateException(message, _exceptions.ToArray());
}
_exceptions.Clear();
_dropped = 0;
}
throw exception;
}
/// <summary>
/// Discards all pending exceptions without throwing. Used during <see cref="SdlMixer.Quit"/>
/// teardown, where the parked exceptions refer to a session that is ending.
/// </summary>
public void Clear()
{
lock (_lock)
{
_exceptions.Clear();
_dropped = 0;
}
}
}

View file

@ -0,0 +1,401 @@
namespace Brutal.SdlApi.Mixer;
/// <summary>
/// A managed handler for <c>MIX_SetTrackStoppedCallback</c>: invoked when a track stops mixing (it
/// reached the end of its input, was stopped, or had its input removed).
/// </summary>
/// <remarks>
/// SDL_mixer fires this on its audio device thread. Any exception the handler throws is caught at the
/// native boundary, logged, and rethrown from managed code at the next mixer/track/group-touching
/// <see cref="SdlMixer"/> call or <see cref="SdlMixer.ThrowPendingCallbackExceptions"/> — it never
/// unwinds into native code.
/// </remarks>
/// <param name="track">The track that stopped.</param>
public delegate void MixTrackStoppedHandler(MixTrack track);
/// <summary>
/// A managed handler for <c>MIX_SetTrackRawCallback</c> / <c>MIX_SetTrackCookedCallback</c>: invoked
/// with a track's audio as it is mixed, so the handler can inspect or modify the PCM in place.
/// </summary>
/// <remarks>
/// Fired on SDL_mixer's audio device thread; exceptions are aggregated, never allowed to escape into
/// native code (see <see cref="MixTrackStoppedHandler"/>). The <paramref name="pcm"/> span aliases the
/// native buffer directly — writes to it modify the audio; do not retain it beyond the call.
/// </remarks>
/// <param name="track">The track being mixed.</param>
/// <param name="spec">The audio format of <paramref name="pcm"/>.</param>
/// <param name="pcm">The track's PCM sample buffer, writable in place.</param>
public delegate void MixTrackMixHandler(MixTrack track, in SdlAudioSpec spec, Span<float> pcm);
/// <summary>
/// A managed handler for <c>MIX_SetGroupPostMixCallback</c>: invoked with a group's combined audio
/// after its tracks are mixed together but before it is mixed into the final output.
/// </summary>
/// <remarks>Fired on SDL_mixer's audio device thread; exceptions are aggregated (see
/// <see cref="MixTrackStoppedHandler"/>). The <paramref name="pcm"/> span aliases the native buffer.</remarks>
/// <param name="group">The group being mixed.</param>
/// <param name="spec">The audio format of <paramref name="pcm"/>.</param>
/// <param name="pcm">The group's PCM sample buffer, writable in place.</param>
public delegate void MixGroupMixHandler(MixGroup group, in SdlAudioSpec spec, Span<float> pcm);
/// <summary>
/// A managed handler for <c>MIX_SetPostMixCallback</c>: invoked with the mixer's final audio, after
/// all tracks and groups are combined, just before it is sent to the audio device.
/// </summary>
/// <remarks>Fired on SDL_mixer's audio device thread; exceptions are aggregated (see
/// <see cref="MixTrackStoppedHandler"/>). The <paramref name="pcm"/> span aliases the native buffer.</remarks>
/// <param name="mixer">The mixer being mixed down.</param>
/// <param name="spec">The audio format of <paramref name="pcm"/>.</param>
/// <param name="pcm">The final PCM sample buffer, writable in place.</param>
public delegate void MixPostMixHandler(MixMixer mixer, in SdlAudioSpec spec, Span<float> pcm);
public static unsafe partial class SdlMixer
{
// Which callback slot a registration occupies. SDL_mixer allows one callback of each kind per
// object; a track can have all three of TrackStopped / TrackRaw / TrackCooked at once, so the kind
// is part of the registry key (setting Raw must not disturb Cooked, and vice versa).
private enum CallbackKind
{
TrackStopped,
TrackRaw,
TrackCooked,
GroupPostMix,
PostMix,
}
// Registered callback delegates, keyed by (native object pointer, kind). Each GCHandle roots the
// managed delegate for as long as SDL_mixer holds the native trampoline pointer against that
// object, and its IntPtr is the userdata SDL threads back to the trampoline so it can dispatch to
// the right delegate. Guarded by a lock because SDL_mixer permits (un)registering from any thread,
// and the audio thread reads the GCHandle target concurrently. Freed on replace, on clear (setting
// a null handler), and wholesale on Quit.
private static readonly Dictionary<(nint Object, CallbackKind Kind), GCHandle> Callbacks = new();
private static readonly Lock CallbackLock = new();
// ---- Race-safe callback (un)registration ---------------------------------------------------
//
// The order of "free the old GCHandle" vs "tell SDL_mixer to stop using its userdata" is a
// memory-safety contract, not a nicety. SDL_mixer fires each callback from the audio device thread
// (TrackGetCallback / MixerCallback in SDL_mixer.c) while holding the relevant SDL_AudioStream's
// internal lock, and every MIX_Set*Callback setter takes that SAME lock (LockTrack/LockMixer ->
// SDL_LockAudioStream) while it overwrites both the callback function pointer AND its userdata.
// SDL_audio.h documents this explicitly: "this lock is held during callbacks ... locking the stream
// guarantees that the callback is not running while the lock is held." Therefore, the instant a
// MIX_Set*Callback call RETURNS, SDL guarantees the mixing thread can never again invoke the OLD
// callback with the OLD userdata (to do so it would have to hold the stream lock, which the setter
// held while atomically replacing both). So the old GCHandle is safe to free only AFTER the native
// set returns — never before. The three helpers below split registration into that exact order:
// PrepareCallback (alloc the new handle, touching nothing native yet) -> caller performs the native
// MIX_Set*Callback -> CommitCallback on success (now race-safe to free the old handle) or
// RollbackCallback on failure (native callback was NOT changed, so the old registration stays live
// and only the speculative new handle is freed). Caller must hold CallbackLock for all three.
// Phase 1: root the new delegate (if any) WITHOUT disturbing the existing registration, and return
// the handle plus its IntPtr for use as native userdata. Returns (default, 0) for a null callback.
private static (GCHandle NewHandle, nint Userdata) PrepareCallback(Delegate? callback)
{
if (callback is null)
return (default, 0);
var handle = GCHandle.Alloc(callback);
return (handle, GCHandle.ToIntPtr(handle));
}
// Phase 2 (native set SUCCEEDED): SDL now points at the new callback/userdata and, per the stream
// lock the setter took, will never invoke the old userdata again — so freeing the old GCHandle here
// is race-safe. Records the new handle (or, for a clear, leaves the slot empty).
private static void CommitCallback((nint, CallbackKind) key, GCHandle newHandle)
{
if (Callbacks.Remove(key, out var old))
old.Free();
if (newHandle.IsAllocated)
Callbacks[key] = newHandle;
}
// Phase 2 (native set FAILED): MIX_Set*Callback failed before changing anything (it validates the
// object and returns false without touching the callback), so the OLD registration is still live and
// must be kept intact; free only the handle we speculatively allocated in PrepareCallback.
private static void RollbackCallback(GCHandle newHandle)
{
if (newHandle.IsAllocated)
newHandle.Free();
}
/// <summary>
/// Sets (or, with a null <paramref name="callback"/>, clears) the handler invoked when
/// <paramref name="track"/> stops mixing. Replaces any previously set track-stopped handler.
/// </summary>
/// <remarks>
/// The handler is rooted by a <see cref="System.Runtime.InteropServices.GCHandle"/> for as long as it
/// is registered. Replacing it (another call with a different handler) or clearing it (a call with
/// <c>null</c>) frees the previous handle only AFTER SDL_mixer has stopped referencing it, and
/// <see cref="SdlMixer.Quit"/> frees any still-registered handles after <c>MIX_Quit</c> returns — so a
/// registered handler is retained until it is replaced, cleared, or the library is shut down (a bounded
/// retention matching SDL_mixer's own model, not an unbounded leak). Prefer registering a callback
/// before the object is driving audio rather than hot-swapping it under active playback.
/// </remarks>
/// <param name="track">The track to configure.</param>
/// <param name="callback">The handler to invoke, or <c>null</c> to remove the current one.</param>
/// <exception cref="SdlException">SDL_mixer failed to set the callback.</exception>
/// <exception cref="SdlCallbackException">A previously parked callback exception surfaced.</exception>
/// <exception cref="AggregateException">More than one parked callback exception surfaced.</exception>
public static void SetTrackStoppedCallback(MixTrack track, MixTrackStoppedHandler? callback)
{
ExceptionAggregator.CheckExceptions();
var key = (track.Pointer.Value, CallbackKind.TrackStopped);
lock (CallbackLock)
{
var (newHandle, userdata) = PrepareCallback(callback);
delegate* unmanaged[Cdecl]<void*, MixTrack, void> fn = callback is null ? null : &TrackStoppedTrampoline;
if (PInvoke.SetTrackStoppedCallback(track, fn, (void*)userdata) == 0)
{
RollbackCallback(newHandle);
throw SdlException.FromError("MIX_SetTrackStoppedCallback failed");
}
CommitCallback(key, newHandle);
}
}
/// <summary>
/// Sets (or, with a null <paramref name="callback"/>, clears) the raw (pre-processing) mix handler
/// for <paramref name="track"/> — the track's audio before SDL_mixer applies gain, fades, etc.
/// </summary>
/// <remarks>
/// The handler is rooted by a <see cref="System.Runtime.InteropServices.GCHandle"/> for as long as it
/// is registered. Replacing it (another call with a different handler) or clearing it (a call with
/// <c>null</c>) frees the previous handle only AFTER SDL_mixer has stopped referencing it, and
/// <see cref="SdlMixer.Quit"/> frees any still-registered handles after <c>MIX_Quit</c> returns — so a
/// registered handler is retained until it is replaced, cleared, or the library is shut down (a bounded
/// retention matching SDL_mixer's own model, not an unbounded leak). Prefer registering a callback
/// before the object is driving audio rather than hot-swapping it under active playback.
/// </remarks>
/// <param name="track">The track to configure.</param>
/// <param name="callback">The handler to invoke, or <c>null</c> to remove the current one.</param>
/// <exception cref="SdlException">SDL_mixer failed to set the callback.</exception>
/// <exception cref="SdlCallbackException">A previously parked callback exception surfaced.</exception>
/// <exception cref="AggregateException">More than one parked callback exception surfaced.</exception>
public static void SetTrackRawCallback(MixTrack track, MixTrackMixHandler? callback)
{
ExceptionAggregator.CheckExceptions();
var key = (track.Pointer.Value, CallbackKind.TrackRaw);
lock (CallbackLock)
{
var (newHandle, userdata) = PrepareCallback(callback);
delegate* unmanaged[Cdecl]<void*, MixTrack, SdlAudioSpec*, float*, int, void> fn = callback is null
? null
: &TrackMixTrampoline;
if (PInvoke.SetTrackRawCallback(track, fn, (void*)userdata) == 0)
{
RollbackCallback(newHandle);
throw SdlException.FromError("MIX_SetTrackRawCallback failed");
}
CommitCallback(key, newHandle);
}
}
/// <summary>
/// Sets (or, with a null <paramref name="callback"/>, clears) the cooked (post-processing) mix
/// handler for <paramref name="track"/> — the track's audio after SDL_mixer applies its transforms.
/// </summary>
/// <remarks>
/// The handler is rooted by a <see cref="System.Runtime.InteropServices.GCHandle"/> for as long as it
/// is registered. Replacing it (another call with a different handler) or clearing it (a call with
/// <c>null</c>) frees the previous handle only AFTER SDL_mixer has stopped referencing it, and
/// <see cref="SdlMixer.Quit"/> frees any still-registered handles after <c>MIX_Quit</c> returns — so a
/// registered handler is retained until it is replaced, cleared, or the library is shut down (a bounded
/// retention matching SDL_mixer's own model, not an unbounded leak). Prefer registering a callback
/// before the object is driving audio rather than hot-swapping it under active playback.
/// </remarks>
/// <param name="track">The track to configure.</param>
/// <param name="callback">The handler to invoke, or <c>null</c> to remove the current one.</param>
/// <exception cref="SdlException">SDL_mixer failed to set the callback.</exception>
/// <exception cref="SdlCallbackException">A previously parked callback exception surfaced.</exception>
/// <exception cref="AggregateException">More than one parked callback exception surfaced.</exception>
public static void SetTrackCookedCallback(MixTrack track, MixTrackMixHandler? callback)
{
ExceptionAggregator.CheckExceptions();
var key = (track.Pointer.Value, CallbackKind.TrackCooked);
lock (CallbackLock)
{
var (newHandle, userdata) = PrepareCallback(callback);
delegate* unmanaged[Cdecl]<void*, MixTrack, SdlAudioSpec*, float*, int, void> fn = callback is null
? null
: &TrackMixTrampoline;
if (PInvoke.SetTrackCookedCallback(track, fn, (void*)userdata) == 0)
{
RollbackCallback(newHandle);
throw SdlException.FromError("MIX_SetTrackCookedCallback failed");
}
CommitCallback(key, newHandle);
}
}
/// <summary>
/// Sets (or, with a null <paramref name="callback"/>, clears) the post-mix handler for
/// <paramref name="group"/> — its tracks' combined audio, before it mixes into the final output.
/// </summary>
/// <remarks>
/// The handler is rooted by a <see cref="System.Runtime.InteropServices.GCHandle"/> for as long as it
/// is registered. Replacing it (another call with a different handler) or clearing it (a call with
/// <c>null</c>) frees the previous handle only AFTER SDL_mixer has stopped referencing it, and
/// <see cref="SdlMixer.Quit"/> frees any still-registered handles after <c>MIX_Quit</c> returns — so a
/// registered handler is retained until it is replaced, cleared, or the library is shut down (a bounded
/// retention matching SDL_mixer's own model, not an unbounded leak). Prefer registering a callback
/// before the object is driving audio rather than hot-swapping it under active playback.
/// </remarks>
/// <param name="group">The group to configure.</param>
/// <param name="callback">The handler to invoke, or <c>null</c> to remove the current one.</param>
/// <exception cref="SdlException">SDL_mixer failed to set the callback.</exception>
/// <exception cref="SdlCallbackException">A previously parked callback exception surfaced.</exception>
/// <exception cref="AggregateException">More than one parked callback exception surfaced.</exception>
public static void SetGroupPostMixCallback(MixGroup group, MixGroupMixHandler? callback)
{
ExceptionAggregator.CheckExceptions();
var key = (group.Pointer.Value, CallbackKind.GroupPostMix);
lock (CallbackLock)
{
var (newHandle, userdata) = PrepareCallback(callback);
delegate* unmanaged[Cdecl]<void*, MixGroup, SdlAudioSpec*, float*, int, void> fn = callback is null
? null
: &GroupMixTrampoline;
if (PInvoke.SetGroupPostMixCallback(group, fn, (void*)userdata) == 0)
{
RollbackCallback(newHandle);
throw SdlException.FromError("MIX_SetGroupPostMixCallback failed");
}
CommitCallback(key, newHandle);
}
}
/// <summary>
/// Sets (or, with a null <paramref name="callback"/>, clears) the post-mix handler for
/// <paramref name="mixer"/> — its final combined audio, just before it is sent to the device.
/// </summary>
/// <remarks>
/// The handler is rooted by a <see cref="System.Runtime.InteropServices.GCHandle"/> for as long as it
/// is registered. Replacing it (another call with a different handler) or clearing it (a call with
/// <c>null</c>) frees the previous handle only AFTER SDL_mixer has stopped referencing it, and
/// <see cref="SdlMixer.Quit"/> frees any still-registered handles after <c>MIX_Quit</c> returns — so a
/// registered handler is retained until it is replaced, cleared, or the library is shut down (a bounded
/// retention matching SDL_mixer's own model, not an unbounded leak). Prefer registering a callback
/// before the object is driving audio rather than hot-swapping it under active playback.
/// </remarks>
/// <param name="mixer">The mixer to configure.</param>
/// <param name="callback">The handler to invoke, or <c>null</c> to remove the current one.</param>
/// <exception cref="SdlException">SDL_mixer failed to set the callback.</exception>
/// <exception cref="SdlCallbackException">A previously parked callback exception surfaced.</exception>
/// <exception cref="AggregateException">More than one parked callback exception surfaced.</exception>
public static void SetPostMixCallback(MixMixer mixer, MixPostMixHandler? callback)
{
ExceptionAggregator.CheckExceptions();
var key = (mixer.Pointer.Value, CallbackKind.PostMix);
lock (CallbackLock)
{
var (newHandle, userdata) = PrepareCallback(callback);
delegate* unmanaged[Cdecl]<void*, MixMixer, SdlAudioSpec*, float*, int, void> fn = callback is null
? null
: &PostMixTrampoline;
if (PInvoke.SetPostMixCallback(mixer, fn, (void*)userdata) == 0)
{
RollbackCallback(newHandle);
throw SdlException.FromError("MIX_SetPostMixCallback failed");
}
CommitCallback(key, newHandle);
}
}
// Frees every GCHandle rooting a registered callback delegate and empties the registry. Called by
// Quit AFTER MIX_Quit() has returned — by then the audio device thread is stopped and the native
// callback registrations are gone, so no trampoline can fire against these handles and freeing them
// is race-safe (see Quit for why the order matters). Without this the GCHandles would leak across a
// MIX_Quit/MIX_Init cycle and a re-registration of the same object pointer could mis-resolve.
// Mirrors core's Sdl.Events.ClearWatches.
internal static void ClearCallbacks()
{
lock (CallbackLock)
{
foreach (var (_, handle) in Callbacks)
handle.Free();
Callbacks.Clear();
}
}
// ---- Trampolines ---------------------------------------------------------------------------
//
// The single native entry point for each callback family. SDL_mixer passes the GCHandle IntPtr back
// as userdata; we resolve it to the managed delegate and invoke it inside a try/catch so NO
// exception ever escapes into the native audio thread. Failures (and a dead/foreign GCHandle) are
// parked on the shared aggregator and rethrown from managed code at the next drain point.
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
private static void TrackStoppedTrampoline(void* userdata, MixTrack track)
{
try
{
if (GCHandle.FromIntPtr((nint)userdata).Target is MixTrackStoppedHandler handler)
handler(track);
else
ExceptionAggregator.Push(DeadHandleMessage("track-stopped"));
}
catch (Exception ex)
{
ExceptionAggregator.Push("An exception occurred in an SDL_mixer track-stopped callback.", ex);
}
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
private static void TrackMixTrampoline(void* userdata, MixTrack track, SdlAudioSpec* spec, float* pcm, int samples)
{
try
{
if (GCHandle.FromIntPtr((nint)userdata).Target is MixTrackMixHandler handler)
handler(track, in *spec, new Span<float>(pcm, samples));
else
ExceptionAggregator.Push(DeadHandleMessage("track mix"));
}
catch (Exception ex)
{
ExceptionAggregator.Push("An exception occurred in an SDL_mixer track mix callback.", ex);
}
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
private static void GroupMixTrampoline(void* userdata, MixGroup group, SdlAudioSpec* spec, float* pcm, int samples)
{
try
{
if (GCHandle.FromIntPtr((nint)userdata).Target is MixGroupMixHandler handler)
handler(group, in *spec, new Span<float>(pcm, samples));
else
ExceptionAggregator.Push(DeadHandleMessage("group post-mix"));
}
catch (Exception ex)
{
ExceptionAggregator.Push("An exception occurred in an SDL_mixer group post-mix callback.", ex);
}
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
private static void PostMixTrampoline(void* userdata, MixMixer mixer, SdlAudioSpec* spec, float* pcm, int samples)
{
try
{
if (GCHandle.FromIntPtr((nint)userdata).Target is MixPostMixHandler handler)
handler(mixer, in *spec, new Span<float>(pcm, samples));
else
ExceptionAggregator.Push(DeadHandleMessage("post-mix"));
}
catch (Exception ex)
{
ExceptionAggregator.Push("An exception occurred in an SDL_mixer post-mix callback.", ex);
}
}
// The GCHandle resolved but its target is not the expected handler type: it was freed (dead) or
// belongs to something else (foreign). Falling through silently would hide a real lifecycle bug, so
// surface it through the aggregator rather than swallowing it.
private static string DeadHandleMessage(string family) =>
$"An SDL_mixer {family} callback fired with a dead or foreign GCHandle (its target was not the "
+ "expected handler); the callback was skipped.";
}

View file

@ -0,0 +1,30 @@
namespace Brutal.SdlApi.Mixer;
public static unsafe partial class SdlMixer
{
/// <summary>
/// Shuts down SDL_mixer, releasing all mixers, tracks, audio and decoders it still owns.
/// </summary>
/// <remarks>
/// Hand-written (rather than generated) so it also tears down this binding's managed callback
/// state: it frees the <see cref="System.Runtime.InteropServices.GCHandle"/>s rooting any
/// registered callback delegates and discards any parked callback exceptions (they refer to a
/// session that is ending, so they are cleared rather than rethrown). Mirrors core's
/// <c>Sdl.Init.Quit</c> teardown. Calling a mixer/track/group ergonomic method after this and
/// before a fresh <c>MIX_Init</c> is undefined, exactly as in native SDL_mixer.
/// </remarks>
public static void Quit()
{
// Order is a memory-safety contract. MIX_Quit stops all audio output, closes the audio devices,
// and destroys every mixer/track/group (see its header docs), so ONLY after it returns is the
// audio device thread guaranteed to have stopped and no trampoline can fire again. The callback
// GCHandles are the userdata those trampolines dereference, so they must be freed strictly AFTER
// MIX_Quit — freeing them first (the previous order) left a window in which the still-running
// audio thread could resolve a freed handle (undefined behaviour). Parked callback exceptions
// refer to the session that is ending, so they are discarded (not rethrown) once no more can be
// pushed.
PInvoke.Quit();
ClearCallbacks();
ExceptionAggregator.Clear();
}
}

View file

@ -0,0 +1,145 @@
using System.Reflection;
using Brutal.Logging;
namespace Brutal.SdlApi.Mixer;
/// <summary>
/// Provides access to the SDL_mixer library.
/// </summary>
public static unsafe partial class SdlMixer
{
/// <summary>
/// The name the generated P/Invoke surface imports against. The <see cref="PInvoke"/> static
/// constructor registers a <see cref="NativeLibrary.SetDllImportResolver"/> that normalizes
/// this name to the platform-specific SDL3_mixer shared library.
/// </summary>
internal const string Dll = "SDL3_mixer";
/// <summary>
/// The logging category for the per-call trace logs the generated P/Invoke surface emits. An
/// internal implementation detail mirroring core's <c>Sdl.TraceLog</c>; the generated
/// <c>SdlMixer.PInvoke</c> wrappers call <c>SdlMixer.TraceLog.Trace()</c> on every invocation.
/// </summary>
internal static readonly LogCategory TraceLog = LogCategory.Make("SdlMixer");
/// <summary>
/// Captures exceptions thrown inside SDL_mixer callbacks (track-stopped, per-track/group/mixer mix
/// hooks) so they can be rethrown safely from managed code instead of unwinding across the native
/// boundary. Unlike core's aggregator — which fires on the single event-pump thread — SDL_mixer
/// invokes these callbacks on its own audio device thread(s), so this aggregator is drained from
/// every ergonomic method that touches a mixer/track/group (the generated
/// <c>ExceptionAggregator.CheckExceptions()</c> prelude) and from the public
/// <see cref="ThrowPendingCallbackExceptions"/> for long device-driven playback that makes no other
/// API calls. The aggregator itself is thread-safe (see <see cref="ExceptionAggregator"/>).
/// </summary>
internal static readonly ExceptionAggregator ExceptionAggregator = new();
/// <summary>
/// Rethrows any exception captured inside an SDL_mixer callback since the last drain, then clears
/// the pending set. Callbacks fire on SDL_mixer's audio thread(s), where a managed exception cannot
/// legally unwind; each is caught, logged, and parked on the shared aggregator instead. Every
/// ergonomic method that touches a mixer, track or group drains automatically, but during long
/// device-driven playback that makes no such calls, invoke this periodically (e.g. once per frame)
/// to surface a failing callback promptly.
/// </summary>
/// <exception cref="SdlCallbackException">Exactly one callback exception was pending.</exception>
/// <exception cref="AggregateException">More than one callback exception was pending, or some were dropped.</exception>
public static void ThrowPendingCallbackExceptions() => ExceptionAggregator.CheckExceptions();
/// <summary>
/// Hosts the raw generated P/Invoke surface (filled in by a later task) and, for now, the
/// native library resolver that makes loading <c>SDL3_mixer</c> work.
/// </summary>
public static unsafe partial class PInvoke
{
// The native SDL3_mixer handle, resolved lazily by the DllImportResolver below and cached
// so the library is loaded at most once regardless of how many entry points are resolved.
private static nint _nativeHandle;
// Serializes resolution — see Brutal.Sdl's Sdl.PInvoke for the full rationale (two threads
// resolving different entry points concurrently must not race to load two handles).
private static readonly Lock ResolveLock = new();
// The resolver is registered in this static constructor rather than at first use so it is
// in place before ANY P/Invoke against this assembly is resolved. Accessing a member of the
// nested PInvoke type triggers this constructor (mirrors Brutal.Sdl's Sdl.PInvoke pattern).
static PInvoke()
{
// GUARANTEE: SDL3 must actually be loaded into the process before SDL3_mixer's own
// resolve runs below — SDL3_mixer's dylib/so/dll has a dynamic-link dependency on
// libSDL3 (@rpath/libSDL3.0.dylib on macOS, libSDL3.so.0 on Linux, SDL3.dll on
// Windows) that a nupkg-deployed app's probe layout cannot always be relied on to
// satisfy via rpath/loader-path alone (the CMake wrapper's INSTALL_RPATH is a second,
// belt-and-braces line of defense, not the primary guarantee).
//
// Merely running Sdl's or Sdl.PInvoke's static constructor is NOT sufficient: those
// constructors only *register* Brutal.Sdl's DllImportResolver
// (NativeLibrary.SetDllImportResolver) — the resolver is not invoked, and libSDL3 is
// not actually loaded, until the CLR resolves a real P/Invoke against it. So instead of
// RunClassConstructor, we make one real, side-effect-free P/Invoke call into core:
// Sdl.PInvoke.GetVersion() just reads SDL's compiled-in version number, requires no
// SDL_Init and has no observable side effects, but its LibraryImport binding is exactly
// what triggers Brutal.Sdl's resolver to actually NativeLibrary.Load libSDL3. By the
// time this call returns, libSDL3 is resident in the process, so SDL3_mixer's own
// dynamic-link dependency on it is satisfiable regardless of rpath/loader-path probing.
_ = Sdl.PInvoke.GetVersion();
NativeLibrary.SetDllImportResolver(typeof(SdlMixer).Assembly, Resolve);
}
// Normalizes the "SDL3_mixer" import name to the platform-specific shared library filename
// (SDL3_mixer.dll on Windows, libSDL3_mixer.dylib on macOS, libSDL3_mixer.so.0 on Linux).
// SDL_mixer's Linux build installs a versioned soname (libSDL3_mixer.so.0), same convention
// as core's SDL3, so the candidate list is spelled out explicitly, most-specific first, with
// the default probing convention name as a fallback.
private static nint Resolve(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
{
// Only ever asked to resolve SDL3_mixer; anything else is left to the default resolver.
if (libraryName != Dll)
return IntPtr.Zero;
lock (ResolveLock)
{
if (_nativeHandle != IntPtr.Zero)
return _nativeHandle;
var search = searchPath ?? DllImportSearchPath.AssemblyDirectory;
// Try each candidate with Load (not TryLoad): TryLoad reports only pass/fail and
// discards the OS diagnostic, so a candidate that *exists but fails to load* (a
// missing transitive dependency, an ABI mismatch) would vanish silently. Load throws
// with the real dlerror/LoadLibrary text, which we aggregate so the final exception
// names every attempt and why it failed.
var failures = new List<string>();
foreach (var candidate in Candidates())
{
try
{
_nativeHandle = NativeLibrary.Load(candidate, assembly, search);
return _nativeHandle;
}
catch (Exception ex)
{
failures.Add($"'{candidate}': {ex.Message}");
}
}
throw new DllNotFoundException(
"Could not load the SDL3_mixer native library. Attempts (most specific first): "
+ string.Join("; ", failures)
+ "."
);
}
}
private static string[] Candidates()
{
if (OperatingSystem.IsWindows())
return ["SDL3_mixer.dll", "SDL3_mixer"];
if (OperatingSystem.IsMacOS())
return ["libSDL3_mixer.dylib", "SDL3_mixer"];
// Linux and other Unix-likes.
return ["libSDL3_mixer.so.0", "libSDL3_mixer.so", "SDL3_mixer"];
}
}
}