Gondwana Game Engine Development (master) - 2.7.0
Gondwana is a cross-platform 2.5D game and rendering engine written in C#/.NET 8. It provides fine-grained control over rendering, timing, and scene composition, with built-in support for parallax, z-ordering, pixel overhang, collision detection, and particle effects. Gondwana targets desktop and web platforms using SkiaSharp for graphics and pluggable audio backends for desktop and browser targets.
Loading...
Searching...
No Matches
AudioResourceManager.cs
1using System.Collections.Concurrent;
4using Microsoft.Extensions.Logging;
5
6namespace Gondwana.Audio;
7
11public sealed class AudioResourceManager : IDisposable
12{
13 [Newtonsoft.Json.JsonIgnore] internal DefinitionProvenance? DefinitionProvenance { get; set; }
14
15 private static readonly Lazy<AudioResourceManager> _instance = new(() => new AudioResourceManager());
16 private readonly ConcurrentDictionary<string, AudioResource> _soundResources = new(StringComparer.Ordinal);
17 private readonly object _backendLock = new();
18 private IAudioBackend? _backend;
19 private bool _disposed;
20
25 public event EventHandler<(string Key, AudioResource Resource)>? SoundDisposed;
26
27 private AudioResourceManager() { }
28
32 public static AudioResourceManager Instance => _instance.Value;
33
35 public IAudioBackend? Backend => _backend;
36
38 public bool IsBackendConfigured => _backend is not null;
39
46 public void ConfigureBackend(IAudioBackend backend)
47 {
48 ArgumentNullException.ThrowIfNull(backend);
49
50 lock (_backendLock)
51 {
52 if (ReferenceEquals(_backend, backend))
53 return;
54
55 if (_backend is not null && _soundResources.Count != 0)
56 {
57 throw new InvalidOperationException(
58 $"Cannot replace audio backend '{_backend.Name}' with '{backend.Name}' while audio resources are loaded. Clear the audio resource manager first.");
59 }
60
61 _backend = backend;
62 Engine.Logger.LogInformation("Configured Gondwana audio backend: {AudioBackend}", backend.Name);
63 }
64 }
65
76 string key,
77 string filePath,
78 float volume,
79 float pan)
80 => LoadFromFile(
81 key,
82 filePath,
83 volume,
84 pan,
85 1.0f);
86
97 string key,
98 string filePath,
99 float volume = 1.0f,
100 float pan = 0.0f,
101 float playbackSpeed = 1.0f)
102 => LoadFromFile(
103 key,
104 filePath,
105 null,
106 volume,
107 pan,
108 playbackSpeed);
109
119 string key,
120 string filePath,
121 string? sourceExtension,
122 float volume,
123 float pan,
124 float playbackSpeed)
125 {
126 var bytes = File.ReadAllBytes(filePath);
127
128 var resource = LoadFromBytes(
129 key,
130 bytes,
131 string.IsNullOrWhiteSpace(sourceExtension) ? filePath : sourceExtension,
132 volume,
133 pan,
134 playbackSpeed);
135
136 resource.SetSourceFilePath(filePath);
137 return resource;
138 }
139
151 string key,
152 Stream input,
153 string fileExt,
154 float volume,
155 float pan)
157 key,
158 input,
159 fileExt,
160 volume,
161 pan,
162 1.0f);
163
175 string key,
176 Stream input,
177 string fileExt,
178 float volume = 1.0f,
179 float pan = 0.0f,
180 float playbackSpeed = 1.0f)
181 {
182 using var ms = new MemoryStream();
183 input.CopyTo(ms);
184
185 return LoadFromBytes(
186 key,
187 ms.ToArray(),
188 fileExt,
189 volume,
190 pan,
191 playbackSpeed);
192 }
193
205 string key,
206 string uri,
207 float volume = 1.0f,
208 float pan = 0.0f,
209 float playbackSpeed = 1.0f)
210 {
211 lock (_backendLock)
212 {
213 if (string.IsNullOrWhiteSpace(uri))
214 throw new ArgumentException("Audio URI cannot be empty.", nameof(uri));
215
216 ValidateSettings(
217 key,
218 volume,
219 pan,
220 playbackSpeed);
221
222 var speed = ClampPlaybackSpeed(playbackSpeed);
223
224 var playback = RequireBackend().CreateFromUri(
225 key,
226 uri,
227 Math.Clamp(volume, 0f, 1f),
228 Math.Clamp(pan, -1f, 1f),
229 speed);
230
231 AudioResource? resource = null;
232
233 try
234 {
235 resource = new AudioResource(
236 key,
237 playback,
238 volume,
239 pan,
240 speed);
241
242 resource.SetSourceUri(uri);
243 RegisterLoadedSound(key, resource);
244 return resource;
245 }
246 catch
247 {
248 DisposeFailedLoad(resource, playback);
249 throw;
250 }
251 }
252 }
253
262 public List<AudioResource> LoadFromEngineAssetsFile(AssetsFile resourceFile, float defaultVolume, float defaultPan)
264 resourceFile,
265 defaultVolume,
266 defaultPan,
267 1.0f);
268
277 public List<AudioResource> LoadFromEngineAssetsFile(
278 AssetsFile resourceFile,
279 float defaultVolume = 1.0f,
280 float defaultPan = 0.0f,
281 float defaultPlaybackSpeed = 1.0f)
282 {
283 List<AudioResource> loadedSounds = [];
284
285 foreach (var entry in resourceFile.GetAllEntries())
286 {
287 if (entry.AssetType != AssetTypes.Audio)
288 continue;
289
290 lock (_backendLock)
291 {
292 if (_soundResources.ContainsKey(entry.AssetName))
293 {
294 Engine.Logger.LogDebug("AudioResource '{Key}' already loaded. Skipping.", entry.AssetName);
295 continue;
296 }
297
298 var stream = resourceFile.Get(entry.AssetType, entry.AssetName);
299
300 if (stream is null)
301 {
302 Engine.Logger.LogWarning("Failed to retrieve stream for audio resource: {Key}", entry.AssetName);
303 continue;
304 }
305
306 try
307 {
308 using (stream)
309 using (var ms = new MemoryStream())
310 {
311 stream.CopyTo(ms);
312
313 var sound = LoadFromBytes(
314 entry.AssetName,
315 ms.ToArray(),
316 entry.AssetName,
317 defaultVolume,
318 defaultPan,
319 defaultPlaybackSpeed);
320
321 sound.SetAssetIdentifier(
322 new AssetsFileIdentifier(resourceFile, AssetTypes.Audio, entry.AssetName));
323
324 loadedSounds.Add(sound);
325 }
326
327 Engine.Logger.LogInformation("Loaded sound: {Key}", entry.AssetName);
328 }
329 catch (Exception ex)
330 {
331 Engine.Logger.LogError(ex, "Error loading sound from asset file for key: {Key}", entry.AssetName);
332 throw;
333 }
334 }
335 }
336
337 return loadedSounds;
338 }
339
350 string key,
351 string? newKey,
352 float? volume,
353 float? pan)
354 => Clone(
355 key,
356 newKey,
357 volume,
358 pan,
359 null);
360
372 string key,
373 string? newKey = null,
374 float? volume = null,
375 float? pan = null,
376 float? playbackSpeed = null)
377 {
378 lock (_backendLock)
379 {
380 if (!_soundResources.TryGetValue(key, out var original))
381 {
382 Engine.Logger.LogWarning("Attempted to clone non-existent AudioResource with key: {Key}", key);
383 return null;
384 }
385
386 newKey ??= $"{key}_clone_{Guid.NewGuid()}";
387
388 if (_soundResources.ContainsKey(newKey))
389 {
390 Engine.Logger.LogWarning("AudioResource with key '{Key}' already exists. Cannot clone.", newKey);
391 return null;
392 }
393
394 AudioResource clone;
395
396 if (original.OriginalBytes is not null && !string.IsNullOrEmpty(original.SourceExtension))
397 {
398 using var stream = new MemoryStream(original.OriginalBytes, writable: false);
399
400 clone = LoadFromStream(
401 newKey,
402 stream,
403 original.SourceExtension,
404 volume ?? original.Volume,
405 pan ?? original.Pan,
406 playbackSpeed ?? original.PlaybackSpeed);
407 }
408 else if (!string.IsNullOrWhiteSpace(original.SourceUri))
409 {
410 clone = LoadFromUri(
411 newKey,
412 original.SourceUri,
413 volume ?? original.Volume,
414 pan ?? original.Pan,
415 playbackSpeed ?? original.PlaybackSpeed);
416 }
417 else
418 {
419 Engine.Logger.LogWarning(
420 "Cannot clone AudioResource '{Key}' because its source cannot be recreated.",
421 key);
422
423 return null;
424 }
425
426 clone.CopySourceFrom(original);
427 clone.IsLooping = original.IsLooping;
428 return clone;
429 }
430 }
431
432 private AudioResource LoadFromBytes(
433 string key,
434 byte[] bytes,
435 string fileHint,
436 float volume,
437 float pan,
438 float playbackSpeed)
439 {
440 lock (_backendLock)
441 {
442 var ext = Path.GetExtension(fileHint);
443
444 if (string.IsNullOrWhiteSpace(ext))
445 {
446 throw new InvalidOperationException(
447 $"Audio asset '{key}' has no file extension. Ensure audio AssetsFile entries retain their extension.");
448 }
449
450 ValidateSettings(
451 key,
452 volume,
453 pan,
454 playbackSpeed);
455
456 var speed = ClampPlaybackSpeed(playbackSpeed);
457
458 var playback = RequireBackend().CreateFromBytes(
459 key,
460 bytes,
461 fileHint,
462 Math.Clamp(volume, 0f, 1f),
463 Math.Clamp(pan, -1f, 1f),
464 speed);
465
466 AudioResource? sound = null;
467
468 try
469 {
470 sound = new AudioResource(
471 key,
472 playback,
473 volume,
474 pan,
475 speed,
476 fileHint,
477 bytes);
478
479 RegisterLoadedSound(key, sound);
480 return sound;
481 }
482 catch
483 {
484 DisposeFailedLoad(sound, playback);
485 throw;
486 }
487 }
488 }
489
490 private static void DisposeFailedLoad(AudioResource? resource, IAudioPlaybackHandle playback)
491 {
492 try
493 {
494 if (resource is not null)
495 resource.Dispose();
496 else
497 playback.Dispose();
498 }
499 catch (Exception ex)
500 {
501 // Preserve the original load failure even if a backend also fails to dispose.
502 Engine.Logger.LogError(ex, "Failed to release an audio handle after loading failed.");
503 }
504 }
505
506 private HashSet<AudioResource>? _retainedDefinitionResources;
507
508 private void ReplaceExisting(string key)
509 {
510 if (_soundResources.TryGetValue(key, out var existing))
511 {
512 if (_retainedDefinitionResources?.Contains(existing) == true)
513 _soundResources.TryRemove(key, out _);
514 else
515 existing.Dispose();
516 }
517 }
518
523 internal T LoadDefinitionDocument<T>(Func<T> load)
524 {
525 lock (_backendLock)
526 {
527 if (_retainedDefinitionResources is not null)
528 throw new InvalidOperationException("A definition document load is already in progress.");
529
530 var previous = GetAll();
531
532 var settings = previous.Values.ToDictionary(
533 resource => resource,
534 resource => (resource.Volume, resource.Pan, resource.PlaybackSpeed, resource.IsLooping));
535
536 var provenance = DefinitionProvenance;
537 _retainedDefinitionResources = previous.Values.ToHashSet();
538 T result;
539
540 try
541 {
542 result = load();
543 }
544 catch
545 {
546 foreach (var resource in _soundResources.Values.ToArray())
547 if (!_retainedDefinitionResources.Contains(resource))
548 resource.Dispose();
549
550 _soundResources.Clear();
551
552 foreach (var pair in previous)
553 _soundResources[pair.Key] = pair.Value;
554
555 foreach (var pair in settings)
556 {
557 pair.Key.Volume = pair.Value.Volume;
558 pair.Key.Pan = pair.Value.Pan;
559 pair.Key.PlaybackSpeed = pair.Value.PlaybackSpeed;
560 pair.Key.IsLooping = pair.Value.IsLooping;
561 }
562
563 DefinitionProvenance = provenance;
564 throw;
565 }
566 finally
567 {
568 _retainedDefinitionResources = null;
569 }
570
571 foreach (var pair in previous)
572 if (!_soundResources.TryGetValue(pair.Key, out var current) || !ReferenceEquals(current, pair.Value))
573 pair.Value.Dispose();
574
575 return result;
576 }
577 }
578
579 private static void ValidateSettings(
580 string key,
581 float volume,
582 float pan,
583 float speed)
584 {
585 ArgumentException.ThrowIfNullOrWhiteSpace(key);
586
587 if (float.IsNaN(volume) || float.IsNaN(pan) || float.IsNaN(speed))
588 throw new ArgumentOutOfRangeException(nameof(speed), "Audio settings must not be NaN.");
589 }
590
591 private void RegisterLoadedSound(string key, AudioResource sound)
592 {
593 ReplaceExisting(key);
594 _soundResources[key] = sound;
595
596 sound.Disposed += (_, _) =>
597 {
598 if (((ICollection<KeyValuePair<string, AudioResource>>)_soundResources).Remove(new(key, sound)))
599 {
600 SoundDisposed?.Invoke(this, (key, sound));
601 }
602 };
603 }
604
605 private IAudioBackend RequireBackend() => _backend
606 ?? throw new InvalidOperationException(
607 "No Gondwana audio backend is configured. Install and initialize a backend such as Gondwana.Audio.NAudio or Gondwana.Audio.Browser before loading audio.");
608
609 private static float ClampPlaybackSpeed(float speed) =>
610 Math.Clamp(speed, AudioResource.MinimumPlaybackSpeed, AudioResource.MaximumPlaybackSpeed);
611
616 public void Unload(string key)
617 {
618 lock (_backendLock)
619 {
620 ReplaceExisting(key);
621 }
622 }
623
627 public void Clear()
628 {
629 DefinitionProvenance = null;
630
631 lock (_backendLock)
632 {
633 foreach (var resource in _soundResources.Values.ToArray())
634 resource.Dispose();
635
636 _soundResources.Clear();
637 }
638 }
639
646 public bool TryGet(string key, out AudioResource? resource) => _soundResources.TryGetValue(key, out resource);
647
653 public AudioResource? Get(string key) => _soundResources.TryGetValue(key, out var resource) ? resource : null;
654
660 public bool Contains(string key) => _soundResources.ContainsKey(key);
661
666 public IEnumerable<string> GetAllKeys() => _soundResources.Keys;
667
672 public Dictionary<string, AudioResource> GetAll() => new(_soundResources);
673
677 public void Dispose()
678 {
679 if (_disposed)
680 return;
681
682 Clear();
683 _disposed = true;
684 }
685}
Represents an identifier for a specific asset within a file, including its type and name.
Represents an asset file used by the engine, providing functionality to load, manage,...
Definition AssetsFile.cs:18
AudioResource? Clone(string key, string? newKey=null, float? volume=null, float? pan=null, float? playbackSpeed=null)
Creates a clone of an existing AudioResource. The clone may inherit or override volume,...
List< AudioResource > LoadFromEngineAssetsFile(AssetsFile resourceFile, float defaultVolume=1.0f, float defaultPan=0.0f, float defaultPlaybackSpeed=1.0f)
Loads all audio entries from the provided AssetsFile and returns the loaded resources.
void ConfigureBackend(IAudioBackend backend)
Configures the backend used for subsequently loaded audio resources. A backend cannot be replaced whi...
AudioResource LoadFromStream(string key, Stream input, string fileExt, float volume=1.0f, float pan=0.0f, float playbackSpeed=1.0f)
Loads an audio resource from the provided Stream.
List< AudioResource > LoadFromEngineAssetsFile(AssetsFile resourceFile, float defaultVolume, float defaultPan)
Compatibility overload that loads audio resources from an AssetsFile. Retains the pre-backend-refacto...
bool Contains(string key)
Determines whether an audio resource with the specified key is loaded.
AudioResource LoadFromUri(string key, string uri, float volume=1.0f, float pan=0.0f, float playbackSpeed=1.0f)
Loads an audio source by URI. This is primarily intended for URI-capable backends such as browser aud...
void Unload(string key)
Unloads and disposes the audio resource with the specified key, if it exists.
void Clear()
Disposes and clears all loaded audio resources.
AudioResource LoadFromStream(string key, Stream input, string fileExt, float volume, float pan)
Compatibility overload that loads an audio resource from a stream. Retains the pre-backend-refactor C...
bool IsBackendConfigured
Gets whether an audio backend has been configured.
IAudioBackend? Backend
Gets the currently configured audio backend, or null if none has been configured.
AudioResource LoadFromFile(string key, string filePath, float volume=1.0f, float pan=0.0f, float playbackSpeed=1.0f)
Loads an audio resource from a file on disk.
void Dispose()
Disposes the manager and all loaded audio resources. This method is idempotent.
EventHandler<(string Key, AudioResource Resource)>? SoundDisposed
Occurs when a loaded AudioResource is disposed and removed from the manager. The event payload contai...
Dictionary< string, AudioResource > GetAll()
Returns a snapshot dictionary of all loaded audio resources.
IEnumerable< string > GetAllKeys()
Returns all loaded audio resource keys.
static AudioResourceManager Instance
Gets the singleton AudioResourceManager instance.
AudioResource? Clone(string key, string? newKey, float? volume, float? pan)
Compatibility overload that creates a clone of an existing audio resource. Retains the pre-backend-re...
bool TryGet(string key, out AudioResource? resource)
Attempts to retrieve a loaded audio resource by key.
AudioResource? Get(string key)
Gets the AudioResource with the specified key, or null if not found.
AudioResource LoadFromFile(string key, string filePath, float volume, float pan)
Compatibility overload that loads an audio resource from a file path. Retains the pre-backend-refacto...
Represents an audio resource that can be played, paused, resumed, sought, and disposed....
Represents the core game engine singleton responsible for managing the main update loop,...
Definition Engine.cs:36
static ILogger< Engine > Logger
Gets the logger instance used by the engine for diagnostic and informational messages.
Definition Engine.cs:59
Creates backend-specific playback handles for the engine's common audio API.
IAudioPlaybackHandle CreateFromBytes(string key, byte[] data, string fileNameOrExtension, float volume, float pan, float playbackSpeed)
Creates a playback handle from raw audio bytes. The implementation is responsible for interpreting th...
string Name
Gets the human-readable name of the backend implementation.
AssetTypes
Defines the types of assets that can be stored and managed by the engine.
Definition AssetTypes.cs:8