diff --git a/src/SharpEmu.Libs/Media/MediaFramePlayback.cs b/src/SharpEmu.Libs/Media/MediaFramePlayback.cs index a5eca1b50..e4528cdb6 100644 --- a/src/SharpEmu.Libs/Media/MediaFramePlayback.cs +++ b/src/SharpEmu.Libs/Media/MediaFramePlayback.cs @@ -527,5 +527,26 @@ public void Dispose() } } + /// + /// The state a frame wait depends on, for a test's failure message: whether the decoder produced the frame (queued, + /// decoded count, its thread) or the clock has not reached it (which clock, and where it stands). + /// + internal string DescribeState() + { + lock (_gate) + { + var audioRunning = GuestAudioClock.IsRunning; + return $"current={_currentFrameIndex} queued={_decodedFrames.Count} " + + $"next_queued={(_decodedFrames.Count > 0 ? _decodedFrames.Peek().Index : -1)} " + + $"decoded={_nextDecodedFrameIndex} decoder_completed={_decoderCompleted} " + + $"decoder_thread={_decoderThread.ThreadState} free_buffers={_freeBuffers.Count} " + + $"finished={_finished} paused={_paused} clock_started={_playbackClockStarted} " + + $"target={CurrentTargetFrameIndexLocked()} playback_s={CurrentPlaybackSecondsLocked():F3} " + + $"wall_s={(_playbackClockStarted ? CurrentWallPlaybackSecondsLocked() : 0):F3} " + + $"follows_audio={_followGuestAudioClock && audioRunning} audio_running={audioRunning} " + + $"audio_played_s={GuestAudioClock.PlayedSeconds:F3} audio_start_s={_audioStartSeconds:F3}"; + } + } + private readonly record struct DecodedFrame(long Index, byte[] Pixels); } diff --git a/tests/SharpEmu.Libs.Tests/Font/FontTextLayoutTests.cs b/tests/SharpEmu.Libs.Tests/Font/FontTextLayoutTests.cs index 4ce83ad32..bf93043a9 100644 --- a/tests/SharpEmu.Libs.Tests/Font/FontTextLayoutTests.cs +++ b/tests/SharpEmu.Libs.Tests/Font/FontTextLayoutTests.cs @@ -22,7 +22,13 @@ public sealed class FontTextLayoutTests private readonly FakeCpuMemory _memory = new(Base, 0x10000); private readonly CpuContext _ctx; - public FontTextLayoutTests() => _ctx = new CpuContext(_memory, Generation.Gen5); + // The exports read the process-wide guest font factory: install it here rather than relying on another class + // having run first (a filtered run without FontExportsTests left it unset). + public FontTextLayoutTests() + { + GuestFontServices.Initialize(FontExportsTests.Factory); + _ctx = new CpuContext(_memory, Generation.Gen5); + } [Fact] public void TombRaiderTextLayoutImports_AreRegistered() diff --git a/tests/SharpEmu.Libs.Tests/HLE/HostCompileStallTests.cs b/tests/SharpEmu.Libs.Tests/HLE/HostCompileStallTests.cs index 3dbf6e350..2a5400926 100644 --- a/tests/SharpEmu.Libs.Tests/HLE/HostCompileStallTests.cs +++ b/tests/SharpEmu.Libs.Tests/HLE/HostCompileStallTests.cs @@ -21,6 +21,8 @@ public sealed class HostCompileStallTests // the test makes longer than this). No test asserts on a margin a late thread can cross. private static readonly TimeSpan Prompt = TimeSpan.FromSeconds(1); private static readonly TimeSpan Patience = TimeSpan.FromSeconds(5); + // Longer than any scheduling delay a test tolerates, so a hold that ran to it is told from a late return. + private static readonly TimeSpan MissedEndHold = TimeSpan.FromSeconds(30); [Fact] public void ALongSleepWithNoStallReturnsAtOnce() @@ -115,7 +117,8 @@ public void ALongSleepIsHeldWhileTheRemoteWaitsAndReturnsWhenItEnds() { var reports = new List(); var remote = new FakeChannel(); - var stall = new HostCompileStall(LongSleep, Grace, enabled: true, held => reports.Add(held), MinimumWait) { Remote = remote }; + // A max hold no scheduling delay reaches: a sleep that missed the end returns only after it (or the join gives up). + var stall = new HostCompileStall(LongSleep, Grace, enabled: true, held => reports.Add(held), MinimumWait, maxHold: MissedEndHold) { Remote = remote }; remote.Publish(new HostCompileStallState(1, Stopwatch.GetTimestamp(), 0)); // A wait counts once it lasted the minimum. Thread.Sleep(MinimumWait + TimeSpan.FromMilliseconds(30)); @@ -127,12 +130,20 @@ public void ALongSleepIsHeldWhileTheRemoteWaitsAndReturnsWhenItEnds() Assert.Equal(0, returned()); Assert.True(stall.IsHolding); + var pausedBefore = GC.GetTotalPauseDuration(); var ended = Stopwatch.GetTimestamp(); remote.Publish(new HostCompileStallState(0, 0, ended)); - Assert.True(sleeper.Join(TimeSpan.FromSeconds(5))); + var published = Stopwatch.GetElapsedTime(ended); + Assert.True(sleeper.Join(MissedEndHold + Patience)); var held = Stopwatch.GetElapsedTime(ended, returned()); - // Promptly after the grace: a sleep that missed the end would return at DefaultMaxHold. - Assert.InRange(held, Grace - TimeSpan.FromMilliseconds(20), Grace + Prompt); + // Not before the grace, and because of the end, not the max hold. The held sleep reads the remote every 4 ms and + // returns at the first read past LastEnd + grace, so anything beyond that is the sleeper (or this thread, before + // it published) not running: a full Libs run once kept it 2.4 s, so the upper bound is the max hold's, not a + // scheduling margin. + Assert.True(held >= Grace - TimeSpan.FromMilliseconds(20) && held < MissedEndHold - Patience, + $"held {held.TotalMilliseconds:F0} ms after the end (grace {Grace.TotalMilliseconds:F0} ms, max hold " + + $"{MissedEndHold.TotalSeconds:F0} s); published {published.TotalMilliseconds:F0} ms after the end; GC pauses " + + $"meanwhile {(GC.GetTotalPauseDuration() - pausedBefore).TotalMilliseconds:F0} ms"); Assert.False(stall.IsHolding); Assert.Equal([true, false], reports); } diff --git a/tests/SharpEmu.Libs.Tests/Kernel/JobWakeRuntimeTests.cs b/tests/SharpEmu.Libs.Tests/Kernel/JobWakeRuntimeTests.cs index f7bc593b4..8a394bc77 100644 --- a/tests/SharpEmu.Libs.Tests/Kernel/JobWakeRuntimeTests.cs +++ b/tests/SharpEmu.Libs.Tests/Kernel/JobWakeRuntimeTests.cs @@ -60,7 +60,8 @@ public void AWakeEndsTheWaitLongBeforeItsTimeoutAndOnlyForEligibleSleepers() const int Worker = 42; var bit = 1UL << Worker; var watch = Stopwatch.StartNew(); - var waiter = Task.Run(() => JobWakeRuntime.Wait(Worker, Generation(), 10_000_000, null)); + using var cleanup = new WakeOnExit(bit); + var waiter = StartWaiter(() => JobWakeRuntime.Wait(Worker, Generation(), 10_000_000, null)); WaitForSleeper(bit); Assert.Equal(bit, Pollers() & bit); @@ -90,7 +91,8 @@ public void AQueueCheckingSleeperIsNotAPoller() const int Worker = 45; var bit = 1UL << Worker; - var waiter = Task.Run(() => JobWakeRuntime.Wait(Worker, Generation(), 10_000_000, (FixedWork?)new FixedWork(0))); + using var cleanup = new WakeOnExit(bit); + var waiter = StartWaiter(() => JobWakeRuntime.Wait(Worker, Generation(), 10_000_000, (FixedWork?)new FixedWork(0))); WaitForSleeper(bit); Assert.Equal(0UL, Pollers() & bit); Assert.Equal(1, JobWakeRuntime.Wake(bit, 1, Everyone)); @@ -107,8 +109,9 @@ public void AWakeStopsAtItsCount() } const ulong Pair = (1UL << 43) | (1UL << 44); + using var cleanup = new WakeOnExit(Pair); var waiters = new[] { 43, 44 } - .Select(worker => Task.Run(() => JobWakeRuntime.Wait(worker, Generation(), 10_000_000, null))) + .Select(worker => StartWaiter(() => JobWakeRuntime.Wait(worker, Generation(), 10_000_000, null))) .ToArray(); WaitForSleeper(Pair); @@ -160,6 +163,30 @@ public void GuestQueuesReportWorkersWithAPositiveCountOrAMailbox() private static int BitCount(ulong value) => System.Numerics.BitOperations.PopCount(value); + // A waiter blocks its thread for up to its timeout, so it gets a thread of its own: as a thread-pool item it waited + // for the pool to inject a thread, which a full parallel run saturated by other blocking tests took past the 5 s + // WaitForSleeper allows ("the waiter never went to sleep"). + private static Task StartWaiter(Func wait) => + Task.Factory.StartNew(wait, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + + // Wakes the test's workers when it ends, pass or fail: a waiter left asleep sits in the process-wide sleeper mask for + // its 10 s timeout, and the next test's wake over every other worker's bit found it (after AWakeStopsAtItsCount gave + // up on its late waiters, AWakeEnds... saw "Expected 0, Actual 2"). + private readonly struct WakeOnExit(ulong bits) : IDisposable + { + public void Dispose() + { + var watch = Stopwatch.StartNew(); + while ((Sleepers() & bits) != 0 && watch.Elapsed < TimeSpan.FromSeconds(5)) + { + JobWakeRuntime.Wake(bits, MaximumWorkerCount, Everyone); + Thread.Sleep(1); + } + } + } + + private const long MaximumWorkerCount = JobWakeRuntime.MaximumWorkers; + private static void WaitForSleeper(ulong bits) { var watch = Stopwatch.StartNew(); diff --git a/tests/SharpEmu.Libs.Tests/Media/MediaFramePlaybackTests.cs b/tests/SharpEmu.Libs.Tests/Media/MediaFramePlaybackTests.cs index ea3b8512e..6cf4d1792 100644 --- a/tests/SharpEmu.Libs.Tests/Media/MediaFramePlaybackTests.cs +++ b/tests/SharpEmu.Libs.Tests/Media/MediaFramePlaybackTests.cs @@ -43,11 +43,15 @@ private static byte[] WaitForAdvancedFrame(MediaFramePlayback playback) Thread.Sleep(1); } - throw new TimeoutException("The decoder did not produce a frame."); + throw new TimeoutException($"The decoder did not produce a frame: {playback.DescribeState()}"); } - [Fact] - public void FirstFrameWaitsUntilPresentationStarts() + // pollDelayMs stands for the test thread being held up after it started the clock (a full Libs run froze this + // process for seconds): past the movie's end, a poll swaps in frame 2 and finds its time over in the same call. + [Theory] + [InlineData(0)] + [InlineData(1100)] + public void FirstFrameWaitsUntilPresentationStarts(int pollDelayMs) { using var playback = new MediaFramePlayback(new SequenceDecoder(1, 2)); @@ -62,7 +66,37 @@ public void FirstFrameWaitsUntilPresentationStarts() Assert.True(playback.TryGetFrame(true, out held, out advanced)); Assert.False(advanced); Assert.Equal(1, held[0]); - Assert.Equal(2, WaitForAdvancedFrame(playback)[0]); + Thread.Sleep(pollDelayMs); + AssertMovesOnFromTheFirstFrame(playback, lastFrame: 2); + } + + // Once presentation started, playback leaves the first frame: it shows a later one, or, when the poll came after the + // movie's whole duration (a frame the clock has passed is never shown, the last one included), it has finished. + private static void AssertMovesOnFromTheFirstFrame(MediaFramePlayback playback, byte lastFrame) + { + var duration = lastFrame * (double)playback.FramesPerSecondDenominator / playback.FramesPerSecondNumerator; + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10); + while (DateTime.UtcNow < deadline) + { + if (playback.TryGetFrame(true, out var frame, out var advanced)) + { + if (advanced) + { + Assert.InRange(frame[0], (byte)2, lastFrame); + return; + } + } + else + { + Assert.True(playback.IsFinished, playback.DescribeState()); + Assert.True(playback.PlaybackProgress.Seconds >= duration, playback.DescribeState()); + return; + } + + Thread.Sleep(1); + } + + throw new TimeoutException($"Playback stayed on its first frame: {playback.DescribeState()}"); } [Fact] @@ -120,7 +154,7 @@ private static byte[] WaitForFrame( Thread.Sleep(1); } - throw new TimeoutException("The decoder did not produce a frame."); + throw new TimeoutException($"The decoder did not produce a frame: {playback.DescribeState()}"); } private static byte[] WaitForGuestFrame( @@ -143,7 +177,7 @@ private static byte[] WaitForGuestFrame( Thread.Sleep(1); } - throw new TimeoutException("The decoder did not produce the requested guest frame."); + throw new TimeoutException($"The decoder did not produce the requested guest frame: {playback.DescribeState()}"); } private sealed class SequenceDecoder(params byte[] values) : IMediaFrameDecoder