Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,9 +169,9 @@ Assert.That(jump.State, Is.EqualTo(AudioSourceState.Stopped));
```

- A source keeps the state SDL_mixer gives it. `Play` plays it from any state. `Pause` pauses only a playing source, and `Resume` resumes only a paused one. `Stop` stops it. A group's `Pause`, `Resume` and `Stop` do the same to each of its sources.
- A sound has no length, so it plays until the game stops it or the test calls `Finish(source)`, which stops it as its end would, looping or not. Clearing the clip of a playing source, or disposing the buffer or stream it plays, stops it, where SDL_mixer stops it once its mixer finds nothing to play. A paused source without a clip stays paused and stops when it resumes. A new clip in place of the old one keeps the source's state, as in SDL_mixer.
- A sound has no length, so it plays until the game stops it or the test calls `Finish(source)`, which stops it as its end would, looping or not. A buffer's `Duration` is zero. `Play(start)` and `Play(start, fadeIn)` play as `Play` does, and a start after the end of a buffer, which throws `ArgumentOutOfRangeException` in the game, does not throw. Clearing the clip of a playing source, or disposing the buffer or stream it plays, stops it, where SDL_mixer stops it once its mixer finds nothing to play. A paused source without a clip stays paused and stops when it resumes. A new clip in place of the old one keeps the source's state, as in SDL_mixer.
- What the game set reads back through the objects it already has: a source's `Clip`, `Gain`, `Group`, `Looping` and `Position`, a group's `Gain`, and the listener's `Position` and `Gain`. `LoadedPath(clip)` returns the path a buffer was loaded from or a stream opened from.
- The checks of the audio system apply as in the game: a negative gain, a clip from another audio system, playing without a clip and a disposed object throw. `Finish` and `LoadedPath` throw `ArgumentException` for an object of another audio system.
- The checks of the audio system apply as in the game: a negative gain, a negative start or fade-in, a clip from another audio system, playing without a clip and a disposed object throw. `Finish` and `LoadedPath` throw `ArgumentException` for an object of another audio system.
- No path is read, so a test does not catch a path missing from the content, which throws in the game. `LoadedPath` of a disposed buffer or stream throws `ObjectDisposedException`.
- The app has an `IAudioSystem` even when the game's `Configure` never calls `RegisterAudio()`, so a game that needs audio without registering it passes its tests and fails to build in the game.

Expand Down
4 changes: 4 additions & 0 deletions src/Pixely.Audio/AudioBuffer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ internal AudioBuffer(AudioSystem audioSystem, Pointer<MIX_Audio> sdlAudio)

internal override AudioSystem AudioSystem => _audioSystem;

// Rounded down to whole milliseconds. Null for a sound that loops forever, such as one with a WAV loop whose play count is zero
// or an OGG LOOPSTART tag without a count.
public TimeSpan? Duration => _audioSystem.GetAudioDurationCore(SdlAudio);

internal Pointer<MIX_Audio> SdlAudio
{
get
Expand Down
26 changes: 23 additions & 3 deletions src/Pixely.Audio/AudioSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,16 +139,34 @@ public AudioSourceState State
internal AudioSystem AudioSystem => _audioSystem;

public void Play()
{
Play(TimeSpan.Zero, TimeSpan.Zero);
}

public void Play(TimeSpan start)
{
Play(start, TimeSpan.Zero);
}

/// <summary>
/// Plays the clip from <paramref name="start"/>, rising from silence to full gain over <paramref name="fadeIn"/>, both rounded down
/// to whole milliseconds. A looping clip loops back to its beginning. A start after the end of an <see cref="AudioBuffer"/> throws
/// <see cref="ArgumentOutOfRangeException"/>. A start that SDL_mixer's decoder cannot seek to throws <see cref="PixelyException"/>,
/// such as one past the file's length in a WAV buffer that loops forever, or one other than zero in an <see cref="AudioStream"/>
/// whose content cannot seek. An OGG or FLAC buffer that loops forever wraps such a start into its loop.
/// </summary>
public void Play(TimeSpan start, TimeSpan fadeIn)
{
ThrowIfDisposed();
if (_clip == null)
{
throw new InvalidOperationException("Cannot play an audio source without a clip.");
}

ApplyLooping();
ArgumentOutOfRangeException.ThrowIfLessThan(start, TimeSpan.Zero);
ArgumentOutOfRangeException.ThrowIfLessThan(fadeIn, TimeSpan.Zero);
ApplyPosition();
_audioSystem.PlayTrackCore(SdlTrack);
_audioSystem.PlayTrackCore(SdlTrack, LoopCount, start, fadeIn);
}

public void Pause()
Expand Down Expand Up @@ -188,9 +206,11 @@ internal void ThrowIfDisposed()
}
}

private int LoopCount => _looping ? -1 : 0;

private void ApplyLooping()
{
ThrowIfDisposed();
_audioSystem.SetTrackLoopsCore(SdlTrack, _looping ? -1 : 0);
_audioSystem.SetTrackLoopsCore(SdlTrack, LoopCount);
}
}
5 changes: 4 additions & 1 deletion src/Pixely.Audio/AudioSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,8 @@ internal static void ThrowIfNegative(float value, string parameterName)

internal abstract void DestroyAudioCore(Pointer<MIX_Audio> audio);

internal abstract TimeSpan? GetAudioDurationCore(Pointer<MIX_Audio> audio);

// A sound decoded while it plays. The content opens here, so a missing path throws from OpenStream.
internal abstract nint OpenStreamCore(ReadOnlySpan<char> path);

Expand All @@ -224,7 +226,8 @@ internal static void ThrowIfNegative(float value, string parameterName)
// A zero stream detaches the track's stream.
internal abstract void SetTrackStreamCore(Pointer<MIX_Track> track, nint stream);

internal abstract void PlayTrackCore(Pointer<MIX_Track> track);
// Restarts a playing or paused track. The loop count is as in SetTrackLoopsCore, and SDL_mixer resets it on each play.
internal abstract void PlayTrackCore(Pointer<MIX_Track> track, int loopCount, TimeSpan start, TimeSpan fadeIn);

internal abstract void PauseTrackCore(Pointer<MIX_Track> track);

Expand Down
43 changes: 41 additions & 2 deletions src/Pixely.Audio/SdlAudioSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,24 @@ internal override void DestroyAudioCore(Pointer<MIX_Audio> audio)
MIX_DestroyAudio(audio);
}

// A buffer decoded in full has a known length. SDL_mixer keeps one that loops forever undecoded, with MIX_DURATION_INFINITE.
internal override TimeSpan? GetAudioDurationCore(Pointer<MIX_Audio> audio)
{
long frames = MIX_GetAudioDuration(audio);
if (frames < 0)
{
return null;
}

long milliseconds = MIX_AudioFramesToMS(audio, frames);
if (milliseconds < 0)
{
SdlError.Throw(nameof(MIX_GetAudioDuration));
}

return TimeSpan.FromMilliseconds(milliseconds);
}

internal override nint OpenStreamCore(ReadOnlySpan<char> path)
{
Stream fileStream = _contentSource.OpenStream(path);
Expand Down Expand Up @@ -94,9 +112,30 @@ internal override void SetTrackStreamCore(Pointer<MIX_Track> track, nint stream)
SdlError.ThrowOnFalse(MIX_SetTrackIOStream(track, ioStream, false), nameof(MIX_SetTrackIOStream));
}

internal override void PlayTrackCore(Pointer<MIX_Track> track)
internal override void PlayTrackCore(Pointer<MIX_Track> track, int loopCount, TimeSpan start, TimeSpan fadeIn)
{
SdlError.ThrowOnFalse(MIX_PlayTrack(track, 0), nameof(MIX_PlayTrack));
// SDL_mixer fails to seek past the end of a buffer without setting an error. A stream's track has no audio here, so its
// decoder decides.
long startMilliseconds = (long)start.TotalMilliseconds;
Pointer<MIX_Audio> audio = MIX_GetTrackAudio(track);
if (!audio.IsNull && GetAudioDurationCore(audio) is { } duration && TimeSpan.FromMilliseconds(startMilliseconds) > duration)
{
throw new ArgumentOutOfRangeException(nameof(start), start, "The start is after the end of the sound.");
}

SDL_PropertiesID options = SDL_CreateProperties();
SdlError.ThrowOnFalse(options != 0, nameof(SDL_CreateProperties));
try
{
SDL_SetNumberProperty(options, MIX_PROP_PLAY_LOOPS_NUMBER, loopCount);
SDL_SetNumberProperty(options, MIX_PROP_PLAY_START_MILLISECOND_NUMBER, startMilliseconds);
SDL_SetNumberProperty(options, MIX_PROP_PLAY_FADE_IN_MILLISECONDS_NUMBER, (long)fadeIn.TotalMilliseconds);
SdlError.ThrowOnFalse(MIX_PlayTrack(track, options), nameof(MIX_PlayTrack));
}
finally
{
SDL_DestroyProperties(options);
}
}

internal override void PauseTrackCore(Pointer<MIX_Track> track)
Expand Down
7 changes: 5 additions & 2 deletions src/Pixely.Testing/StubAudioSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ namespace Pixely.Testing;
/// An <see cref="AudioSystem"/> that plays nothing and reads no file. Each source keeps the state SDL_mixer would give it:
/// <c>Play</c> plays it from any state, <c>Pause</c> pauses only a playing source, <c>Resume</c> resumes only a paused one and
/// <c>Stop</c> stops it, and a group's <c>Pause</c>, <c>Resume</c> and <c>Stop</c> do the same to each of its sources. A sound has
/// no length, so it plays until the game stops it, its clip is cleared or disposed, or the test calls <see cref="Finish"/>. A new
/// no length: a buffer's <c>Duration</c> is zero, a start passed to <c>Play</c> is not checked against the end, and the sound plays
/// until the game stops it, its clip is cleared or disposed, or the test calls <see cref="Finish"/>. A new
/// clip keeps the source's state, and a paused source without a clip stops when it resumes. What the game set reads back through
/// the sources, groups and listener, and <see cref="LoadedPath"/> tells which sound a clip is.
/// </summary>
Expand Down Expand Up @@ -69,6 +70,8 @@ internal override void DestroyAudioCore(Pointer<MIX_Audio> audio)
{
}

internal override TimeSpan? GetAudioDurationCore(Pointer<MIX_Audio> audio) => TimeSpan.Zero;

internal override nint OpenStreamCore(ReadOnlySpan<char> path)
{
nint stream = (nint)NextHandle<byte>();
Expand Down Expand Up @@ -109,7 +112,7 @@ internal override void DestroyTrackCore(Pointer<MIX_Track> track)

internal override void SetTrackStreamCore(Pointer<MIX_Track> track, nint stream) => SetHasClip(track, stream != 0);

internal override void PlayTrackCore(Pointer<MIX_Track> track) => SetState(track, static _ => AudioSourceState.Playing);
internal override void PlayTrackCore(Pointer<MIX_Track> track, int loopCount, TimeSpan start, TimeSpan fadeIn) => SetState(track, static _ => AudioSourceState.Playing);

internal override void PauseTrackCore(Pointer<MIX_Track> track) => SetState(track, Pause);

Expand Down
12 changes: 12 additions & 0 deletions tests/Pixely.Testing.Tests/StubAudioSystemTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,17 @@ public void Play_KeepsPlayingUntilFinished()
Assert.That((oneShot.State, loopingWhileTheOtherFinished, looping.State), Is.EqualTo((AudioSourceState.Stopped, AudioSourceState.Playing, AudioSourceState.Stopped)));
}

[Test]
public void Play_FromAnyStart_PlaysABufferWithoutALength()
{
using StubAudioSystem audio = new();
AudioSource source = CreateSourceWithBuffer(audio);

source.Play(TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(10));

Assert.That((source.State, ((AudioBuffer)source.Clip!).Duration), Is.EqualTo((AudioSourceState.Playing, (TimeSpan?)TimeSpan.Zero)));
}

[Test]
public void Clip_ClearedOrDisposed_StopsTheSource_AndChanged_KeepsItPlaying()
{
Expand Down Expand Up @@ -244,6 +255,7 @@ public void Checks_OfTheAudioSystem_StillApply()
Assert.Multiple(() =>
{
Assert.That(source.Play, Throws.InvalidOperationException);
Assert.That(() => CreateSourceWithBuffer(audio).Play(TimeSpan.FromMilliseconds(-1)), Throws.TypeOf<ArgumentOutOfRangeException>());
Assert.That(() => source.Gain = -1, Throws.TypeOf<ArgumentOutOfRangeException>());
Assert.That(() => audio.MasterGain = -1, Throws.TypeOf<ArgumentOutOfRangeException>());
Assert.That(() => source.Clip = other.LoadBuffer("sounds/jump.wav"), Throws.ArgumentException);
Expand Down
105 changes: 99 additions & 6 deletions tests/Pixely.Tests/AudioSystemTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,14 @@
namespace Pixely.Tests;

// The audio system on SDL_mixer, on SDL's dummy audio driver, which plays in real time. The sound lasts several seconds, so no
// assertion depends on how far playback has advanced.
// assertion depends on how far playback has advanced. A test that plays the sound's last moment waits for it to end instead.
[NonParallelizable]
public sealed class AudioSystemTests
{
private const string SoundPath = "sound.wav";
private const string EndlessSoundPath = "endless.wav";
private static readonly TimeSpan SoundDuration = TimeSpan.FromSeconds(10);
private static readonly TimeSpan NearTheEnd = SoundDuration - TimeSpan.FromMilliseconds(50);

private IPixelyApp _app = null!;
private IAudioSystem _audioSystem = null!;
Expand Down Expand Up @@ -119,6 +122,76 @@ public void Position_SetWhilePlaying_SpatializesRelativeToTheListener_AndNullUnd
Assert.That((positioned, listenerMoved, cleared, source.Position), Is.EqualTo((new Vector3(-3, 2, 3), new Vector3(1, 2, 2), Vector3.Zero, (Vector3?)null)));
}

[Test]
public void Duration_OfABuffer_IsTheSoundsLength()
{
Assert.That(_audioSystem.LoadBuffer(SoundPath).Duration, Is.EqualTo(SoundDuration));
}

// Records SDL_mixer's WAV decoder: its endless loop covers the file's length once, and a seek past it fails.
[Test]
public void Duration_OfASoundThatLoopsForever_IsNull_AndItPlaysFromAStartWithinTheFile()
{
AudioBuffer buffer = _audioSystem.LoadBuffer(EndlessSoundPath);
AudioSource source = _audioSystem.CreateSource();
source.Clip = buffer;

source.Play();
source.Play(NearTheEnd);

Assert.Multiple(() =>
{
Assert.That((buffer.Duration, source.State), Is.EqualTo(((TimeSpan?)null, AudioSourceState.Playing)));
Assert.That(() => source.Play(SoundDuration + TimeSpan.FromSeconds(1)), Throws.TypeOf<PixelyException>());
});
}

[Test]
public void Play_FromAStart_PlaysTheRestOnly()
{
AudioSource buffered = CreateSourceWithBuffer();
AudioSource streamed = _audioSystem.CreateSource();
streamed.Clip = _audioSystem.OpenStream(SoundPath);

buffered.Play(NearTheEnd);
streamed.Play(NearTheEnd, TimeSpan.FromMilliseconds(10));

Assert.Multiple(() =>
{
Assert.That(() => buffered.State, Is.EqualTo(AudioSourceState.Stopped).After(5000, 10));
Assert.That(() => streamed.State, Is.EqualTo(AudioSourceState.Stopped).After(5000, 10));
});
}

// The one-shot source ends first, as both play the same last moment, so the looping one has looped by then.
[Test]
public void Play_LoopingFromAStart_LoopsBack()
{
AudioSource oneShot = CreateSourceWithBuffer();
AudioSource looping = CreateSourceWithBuffer();
looping.Looping = true;

looping.Play(NearTheEnd);
oneShot.Play(NearTheEnd);

Assert.That(() => oneShot.State, Is.EqualTo(AudioSourceState.Stopped).After(5000, 10));
Assert.That(looping.State, Is.EqualTo(AudioSourceState.Playing));
}

[Test]
public void Play_WithAStartAfterTheEndOrANegativeTime_Throws()
{
AudioSource source = CreateSourceWithBuffer();

Assert.Multiple(() =>
{
Assert.That(() => source.Play(SoundDuration + TimeSpan.FromMilliseconds(1)), Throws.TypeOf<ArgumentOutOfRangeException>());
Assert.That(() => source.Play(TimeSpan.FromMilliseconds(-1)), Throws.TypeOf<ArgumentOutOfRangeException>());
Assert.That(() => source.Play(TimeSpan.Zero, TimeSpan.FromMilliseconds(-1)), Throws.TypeOf<ArgumentOutOfRangeException>());
Assert.That(() => source.Play(SoundDuration + TimeSpan.FromTicks(1)), Throws.Nothing);
});
}

[Test]
public void Gains_KeepTheirValues_AndRefuseNegativeOnes()
{
Expand Down Expand Up @@ -336,21 +409,24 @@ private static DictionaryContentSource CreateContent()
{
FrozenDictionary<string, ImmutableArray<ContentFile>> files = new Dictionary<string, ImmutableArray<ContentFile>>
{
["."] = [new ByteContentFile(SoundPath, CreateSilentWav(TimeSpan.FromSeconds(10)))]
["."] = [new ByteContentFile(SoundPath, CreateSilentWav(SoundDuration, loopsForever: false)), new ByteContentFile(EndlessSoundPath, CreateSilentWav(SoundDuration, loopsForever: true))]
}.ToFrozenDictionary();
FrozenDictionary<string, ImmutableArray<string>> directories = new Dictionary<string, ImmutableArray<string>> { ["."] = [] }.ToFrozenDictionary();
return new DictionaryContentSource(files, directories);
}

// 16-bit mono PCM at 8 kHz.
private static byte[] CreateSilentWav(TimeSpan duration)
// 16-bit mono PCM at 8 kHz. A sound that loops forever has a sampler chunk with one forward loop over all of it, with a play count
// of zero.
private static byte[] CreateSilentWav(TimeSpan duration, bool loopsForever)
{
const int SampleRate = 8000;
int dataLength = (int)(SampleRate * duration.TotalSeconds) * sizeof(short);
const int SamplerLength = 60;
int frames = (int)(SampleRate * duration.TotalSeconds);
int dataLength = frames * sizeof(short);
using MemoryStream stream = new();
using BinaryWriter writer = new(stream);
writer.Write("RIFF"u8);
writer.Write(36 + dataLength);
writer.Write(36 + dataLength + (loopsForever ? 8 + SamplerLength : 0));
writer.Write("WAVEfmt "u8);
writer.Write(16);
writer.Write((short)1);
Expand All @@ -362,6 +438,23 @@ private static byte[] CreateSilentWav(TimeSpan duration)
writer.Write("data"u8);
writer.Write(dataLength);
writer.Write(new byte[dataLength]);
if (loopsForever)
{
writer.Write("smpl"u8);
writer.Write(SamplerLength);
// Manufacturer, product, sample period, MIDI unity note, MIDI pitch fraction, SMPTE format and SMPTE offset.
writer.Write(new byte[7 * sizeof(int)]);
writer.Write(1);
writer.Write(0);
// The loop's identifier, type (forward), start, inclusive end, fraction and play count.
writer.Write(0);
writer.Write(0);
writer.Write(0);
writer.Write(frames - 1);
writer.Write(0);
writer.Write(0);
}

writer.Flush();
return stream.ToArray();
}
Expand Down