diff --git a/.agents/skills/spice86-config/SKILL.md b/.agents/skills/spice86-config/SKILL.md index 68cb04866b..6082848fe9 100644 --- a/.agents/skills/spice86-config/SKILL.md +++ b/.agents/skills/spice86-config/SKILL.md @@ -56,7 +56,9 @@ dotnet run --project src/Spice86 -- -e program.exe --HttpApiPort 0 --McpHttpPort | `--TimeMultiplier` | 1.0 | Scales emulated time (>1 faster, <1 slower, 0 freezes emulated time) | | `--InstructionTimeScale` | (none) | PIT timer scale (alternative to TimeMultiplier) | | `--ClockJitterSeed` | (none) | Deterministic clock jitter offset (0 to 0.01 ms) | -| `--ReproducibleRun` | (none) | Deterministic preset: sets `--InstructionTimeScale`, `--RenderingMode Sync`, and default `--ClockStartTime` (1993-06-01T00:00:00Z) | +| `--ReproducibleRun` | (none) | Deterministic preset: sets `--InstructionTimeScale`, `--RenderingMode Sync`, default `--ClockStartTime` (1993-06-01T00:00:00Z), and writes applied host input events to `spice86dumpInputRecording.jsonl` with the other dump files (CD audio is out of scope) | +| `--ReplayInput` | (none) | Path to a `spice86dumpInputRecording.jsonl` file to replay (ignores live input until finished) | +| `--ReplayInputBy` | Cycle | Replay scheduling key: `Cycle` (exact at same speed/mode) or `Time` (best effort by emulated time) | | `--ClockStartTime` | UtcNow | Fixed emulated start date/time (ISO 8601) | ### Audio & Sound diff --git a/README.md b/README.md index e3254d5573..62283f7bec 100644 --- a/README.md +++ b/README.md @@ -132,7 +132,9 @@ Spice86 -e program.exe --CpuHeavyLog \ -u, --UseCodeOverride (Default: true) if false it will use the names provided by overrideSupplierClassName but not the code -i, --InstructionTimeScale if blank will use time based timer. --ClockJitterSeed Optional integer seed enabling a small deterministic clock jitter (0 to 0.01 ms, a function of the emulated time). Omit to disable. - --ReproducibleRun Deterministic run preset: sets --InstructionTimeScale to , --RenderingMode Sync, and --ClockStartTime to 1993-06-01T00:00:00Z when omitted. Cannot be combined with --InstructionTimeScale, --Cycles, or --RenderingMode Async. + --ReproducibleRun Deterministic run preset: sets --InstructionTimeScale to , --RenderingMode Sync, and --ClockStartTime to 1993-06-01T00:00:00Z when omitted, and writes the applied host input events to spice86dumpInputRecording.jsonl with the other dump files. Cannot be combined with --InstructionTimeScale, --Cycles, or --RenderingMode Async. Note: CD audio advances on the mixer thread and is out of scope for deterministic replay. + --ReplayInput Path to a recorded input JSON Lines file (spice86dumpInputRecording.jsonl) to replay. Live host input is ignored until all recorded events are applied. + --ReplayInputBy (Default: Cycle) Key used to schedule replayed events: Cycle (exact at the same speed and mode) or Time (best effort by emulated time). --GeneratedCode Comma list selecting what generated overrides contain: +name enables, -name disables (no sign enables), applied left to right. Names: AsmComments, CheckBuild (a preset for the service-call notifications, branch probes and split port accesses of a check build), BranchProbes, ServiceCallNotifications, DeviceOperations, AssumeUnknownMemoryIsRam, AssumeAccessesStayInSegment, AssumeAbandonedStackSlotsUnobserved, AssumeSavedSlotsWrittenOnlyByPops. Every dump writes manifest.json next to the sources, whatever the selection. --ClockStartTime Optional UTC start date/time for the emulated clock (parseable by DateTime.Parse, e.g. 1993-06-01T00:00:00Z). When omitted defaults to the current UTC time. -t, --TimeMultiplier (Default: 1) Scales emulated time: if >1 emulated time goes faster, if <1 slower, 0 stops emulated time. diff --git a/src/Spice86.Core/CLI/Configuration.cs b/src/Spice86.Core/CLI/Configuration.cs index cba16d7984..b190ca553b 100644 --- a/src/Spice86.Core/CLI/Configuration.cs +++ b/src/Spice86.Core/CLI/Configuration.cs @@ -172,6 +172,19 @@ public override Spectre.Console.ValidationResult Validate() { [CommandOption("--ReproducibleRun ")] public long? ReproducibleRun { get; set; } + /// + /// Path to a recorded input JSON Lines file (spice86dumpInputRecording.jsonl) to replay. + /// + [CommandOption("--ReplayInput ")] + public string? ReplayInput { get; init; } + + /// + /// Selects whether schedules events by CPU cycle or by emulated elapsed time. + /// + [CommandOption("--ReplayInputBy ")] + [DefaultValue(ReplayInputKey.Cycle)] + public ReplayInputKey ReplayInputBy { get; init; } + /// /// Optional fixed start date/time for the emulated clock. Accepts any value parseable by /// (e.g. an ISO 8601 string like diff --git a/src/Spice86.Core/CLI/ReplayInputKey.cs b/src/Spice86.Core/CLI/ReplayInputKey.cs new file mode 100644 index 0000000000..e5a8f012f6 --- /dev/null +++ b/src/Spice86.Core/CLI/ReplayInputKey.cs @@ -0,0 +1,12 @@ +namespace Spice86.Core.CLI; + +/// +/// Selects which key schedules replayed input events. +/// +public enum ReplayInputKey { + /// Schedule each replayed event at its recorded CPU cycle count. + Cycle, + + /// Schedule each replayed event at its recorded emulated elapsed time in milliseconds. + Time +} diff --git a/src/Spice86.Core/Emulator/ProgramExecutor.cs b/src/Spice86.Core/Emulator/ProgramExecutor.cs index e27faa852e..2dc79bee3b 100644 --- a/src/Spice86.Core/Emulator/ProgramExecutor.cs +++ b/src/Spice86.Core/Emulator/ProgramExecutor.cs @@ -4,6 +4,7 @@ namespace Spice86.Core.Emulator; using Spice86.Core.Emulator.StateSerialization; using Spice86.Core.Emulator.VM; +using Spice86.Core.Emulator.VM.Input.Recording; using Spice86.Shared.Interfaces; /// @@ -19,6 +20,7 @@ public sealed class ProgramExecutor : IDisposable { private readonly EmulatorStateSerializer _emulatorStateSerializer; private readonly IShutdownCoordinator _shutdownCoordinator; private readonly ExecutionPolicy _executionPolicy; + private readonly InputReplayDriver _inputReplayDriver; /// /// Initializes a new instance of . The initial program is loaded eagerly @@ -29,6 +31,7 @@ public sealed class ProgramExecutor : IDisposable { /// The core emulation loop driver. /// Writes the recorded emulation state on normal exit. /// Coordinates idempotent post-run teardown. + /// Arms the recorded input replay when the run starts. /// The logging service to use. internal ProgramExecutor( ProgramBootstrapper programBootstrapper, @@ -36,11 +39,13 @@ internal ProgramExecutor( EmulationLoop emulationLoop, EmulatorStateSerializer emulatorStateSerializer, IShutdownCoordinator shutdownCoordinator, + InputReplayDriver inputReplayDriver, ILogger loggerService) { _emulationLoop = emulationLoop; _emulatorStateSerializer = emulatorStateSerializer; _shutdownCoordinator = shutdownCoordinator; _executionPolicy = executionPolicy; + _inputReplayDriver = inputReplayDriver; _loggerService = loggerService; programBootstrapper.LoadInitialProgram(); } @@ -57,6 +62,7 @@ public void Run() { _executionPolicy.ApplyStartupBreakpoints(); _executionPolicy.StartGdbServer(); _executionPolicy.RegisterStopAfterCyclesBreakpoint(); + _inputReplayDriver.Start(); _emulationLoop.Run(); diff --git a/src/Spice86.Core/Emulator/StateSerialization/DumpProgressReporter.cs b/src/Spice86.Core/Emulator/StateSerialization/DumpProgressReporter.cs index a45ac2ea8b..c43a2e8d14 100644 --- a/src/Spice86.Core/Emulator/StateSerialization/DumpProgressReporter.cs +++ b/src/Spice86.Core/Emulator/StateSerialization/DumpProgressReporter.cs @@ -63,7 +63,10 @@ public enum DumpPhase { Symbols, /// Writing the breakpoints JSON dump. - Breakpoints + Breakpoints, + + /// Writing the input recording of a reproducible run. + InputRecording } /// @@ -91,7 +94,8 @@ public sealed class DumpProgressReporter { [DumpPhase.CodeSource] = "Generated C# source", [DumpPhase.CodeProject] = "Generated project", [DumpPhase.Symbols] = "Ghidra symbols", - [DumpPhase.Breakpoints] = "Breakpoints" + [DumpPhase.Breakpoints] = "Breakpoints", + [DumpPhase.InputRecording] = "Input recording" }; private static readonly IReadOnlyDictionary StepLabels = diff --git a/src/Spice86.Core/Emulator/StateSerialization/EmulationStateDataIoHandler.cs b/src/Spice86.Core/Emulator/StateSerialization/EmulationStateDataIoHandler.cs index c2eb64997c..b8ad5c6729 100644 --- a/src/Spice86.Core/Emulator/StateSerialization/EmulationStateDataIoHandler.cs +++ b/src/Spice86.Core/Emulator/StateSerialization/EmulationStateDataIoHandler.cs @@ -55,6 +55,11 @@ protected EmulationStateDataIoHandler(EmulatorStateSerializationFolder emulatorS /// protected string BreakpointsFile => $"{DataDirectory}/Breakpoints.json"; + /// + /// Gets name of the file the input recording dump. + /// + internal string InputRecordingFile => GenerateDumpFileName("InputRecording.jsonl"); + /// /// Gets name of the file the CFG blocks JSON dump. /// diff --git a/src/Spice86.Core/Emulator/StateSerialization/EmulationStateDataReader.cs b/src/Spice86.Core/Emulator/StateSerialization/EmulationStateDataReader.cs index b21cc292da..2ffb5fee0f 100644 --- a/src/Spice86.Core/Emulator/StateSerialization/EmulationStateDataReader.cs +++ b/src/Spice86.Core/Emulator/StateSerialization/EmulationStateDataReader.cs @@ -4,6 +4,7 @@ namespace Spice86.Core.Emulator.StateSerialization; using Spice86.Core.Emulator.Function; using Spice86.Core.Emulator.StateSerialization.CfgReload; +using Spice86.Core.Emulator.VM.Input.Recording; using Spice86.Shared.Emulator.VM.Breakpoint.Serializable; using System.Text.Json; @@ -37,6 +38,11 @@ public IEnumerable ReadGhidraSymbolsFromFileOrCreate() { return new GhidraSymbolsExporter(LoggerService).ReadFromFileOrCreate(SymbolsFile); } + /// Reads the recorded input events to replay, or none when no replay file is given. + internal IReadOnlyList ReadInputRecordingOrEmpty(string? path) { + return path is null ? [] : InputRecordingReader.Read(path); + } + public SerializableUserBreakpointCollection ReadBreakpointsFromFileOrCreate() { if (!File.Exists(BreakpointsFile) || new FileInfo(BreakpointsFile).Length == 0) { return new(); diff --git a/src/Spice86.Core/Emulator/StateSerialization/EmulationStateDataWriter.cs b/src/Spice86.Core/Emulator/StateSerialization/EmulationStateDataWriter.cs index 26d3aa46a9..40eec15c9f 100644 --- a/src/Spice86.Core/Emulator/StateSerialization/EmulationStateDataWriter.cs +++ b/src/Spice86.Core/Emulator/StateSerialization/EmulationStateDataWriter.cs @@ -13,6 +13,7 @@ namespace Spice86.Core.Emulator.StateSerialization; using Spice86.Core.Emulator.ReverseEngineer.CfgCodeGeneration.Model; using Spice86.Core.Emulator.ReverseEngineer.ControlFlowGraph; using Spice86.Core.Emulator.StateSerialization.CfgReload; +using Spice86.Core.Emulator.VM.Input.Recording; using Spice86.Shared.Emulator.Memory; using Spice86.Shared.Emulator.VM.Breakpoint.Serializable; using Spice86.Shared.Interfaces; @@ -43,6 +44,7 @@ public class EmulationStateDataWriter : EmulationStateDataIoHandler { private readonly Configuration _configuration; private readonly CfgNodeIndex _nodeIndex; private readonly RecordedRunFacts _recordedRunFacts; + private readonly InputRecording _inputRecording; private readonly DumpProgressReporter _progress; private readonly Lock _writeLock = new(); @@ -64,6 +66,7 @@ public class EmulationStateDataWriter : EmulationStateDataIoHandler { /// The emulator configuration, used to derive the program checksum baked into the generated project. /// The persistent graph index whose poison set is serialized with the CFG reload dump. /// The recorded run facts serialized with the CFG reload dump. + /// The host input events recorded during a reproducible run. /// Reports dump phases and steps to the log and to UI subscribers. /// The logger service implementation. internal EmulationStateDataWriter(State state, @@ -81,6 +84,7 @@ internal EmulationStateDataWriter(State state, Configuration configuration, CfgNodeIndex nodeIndex, RecordedRunFacts recordedRunFacts, + InputRecording inputRecording, DumpProgressReporter progress, ILogger loggerService) : base(emulatorStateSerializationFolder, loggerService) { _executionAddressesExtractor = executionAddressesExtractor; @@ -97,6 +101,7 @@ internal EmulationStateDataWriter(State state, _configuration = configuration; _nodeIndex = nodeIndex; _recordedRunFacts = recordedRunFacts; + _inputRecording = inputRecording; _progress = progress; } @@ -137,6 +142,10 @@ public void Write() { } WritePhase(DumpPhase.Symbols, SymbolsFile, () => new GhidraSymbolsExporter(LoggerService).Write(executionAddresses, _functionCatalogue, dataSymbolLabels, SymbolsFile)); WritePhase(DumpPhase.Breakpoints, BreakpointsFile, () => WriteBreakpoints(BreakpointsFile)); + if (_inputRecording.IsEnabled) { + WritePhase(DumpPhase.InputRecording, InputRecordingFile, + () => InputRecordingWriter.Write(InputRecordingFile, _inputRecording.Snapshot())); + } succeeded = true; } finally { _progress.EndDump(succeeded); @@ -197,4 +206,4 @@ private void WriteBreakpoints(string filePath) { using FileStream fileStream = File.Open(filePath, FileMode.Create); fileStream.Write(Encoding.UTF8.GetBytes(jsonString)); } -} \ No newline at end of file +} diff --git a/src/Spice86.Core/Emulator/VM/Input/Recording/InputEventSerialization.cs b/src/Spice86.Core/Emulator/VM/Input/Recording/InputEventSerialization.cs new file mode 100644 index 0000000000..5ab8cfda0c --- /dev/null +++ b/src/Spice86.Core/Emulator/VM/Input/Recording/InputEventSerialization.cs @@ -0,0 +1,37 @@ +namespace Spice86.Core.Emulator.VM.Input.Recording; + +using Spice86.Core.Emulator.VM.Input.Events; +using Spice86.Shared.Emulator.Keyboard; +using Spice86.Shared.Emulator.Mouse; +using Spice86.Shared.Interfaces; + +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; + +/// Shared JSON serializer options for input event recordings. +public static class InputEventSerialization { + /// JSON options using web defaults, string enum names and a "kind" discriminator for input events. + public static readonly JsonSerializerOptions Options = new(JsonSerializerDefaults.Web) { + Converters = { new JsonStringEnumConverter() }, + TypeInfoResolver = new DefaultJsonTypeInfoResolver { Modifiers = { DescribeInputEventKinds } } + }; + + /// Registers the queued input kinds on , which lives in + /// Spice86.Shared and cannot name the Core command records in attributes. + private static void DescribeInputEventKinds(JsonTypeInfo typeInfo) { + if (typeInfo.Type != typeof(IInputEvent)) { + return; + } + typeInfo.PolymorphismOptions = new JsonPolymorphismOptions { + TypeDiscriminatorPropertyName = "kind", + DerivedTypes = { + new JsonDerivedType(typeof(KeyboardEventArgs), "key"), + new JsonDerivedType(typeof(MouseMoveEventArgs), "mouseMove"), + new JsonDerivedType(typeof(MouseButtonEventArgs), "mouseButton"), + new JsonDerivedType(typeof(ReleaseAllKeysInput), "releaseAllKeys"), + new JsonDerivedType(typeof(TimeMultiplierInput), "timeMultiplier") + } + }; + } +} diff --git a/src/Spice86.Core/Emulator/VM/Input/Recording/InputRecording.cs b/src/Spice86.Core/Emulator/VM/Input/Recording/InputRecording.cs new file mode 100644 index 0000000000..a8bdc9ffb0 --- /dev/null +++ b/src/Spice86.Core/Emulator/VM/Input/Recording/InputRecording.cs @@ -0,0 +1,44 @@ +namespace Spice86.Core.Emulator.VM.Input.Recording; + +using System.Linq; + +/// +/// Collects the host input events applied during a reproducible run, for the dump to write. +/// +public sealed class InputRecording { + private readonly List _events = []; + private readonly Lock _lock = new(); + + /// + /// Creates a recording; a disabled one ignores every event and is not dumped. + /// + public InputRecording(bool isEnabled) { + IsEnabled = isEnabled; + } + + /// + /// Whether events are collected and dumped (set by --ReproducibleRun). + /// + public bool IsEnabled { get; } + + /// + /// Adds an applied event; does nothing when the recording is disabled. + /// + public void Add(RecordedInputEvent recordedEvent) { + if (!IsEnabled) { + return; + } + lock (_lock) { + _events.Add(recordedEvent); + } + } + + /// + /// Copy of the events recorded so far, safe to take while emulation runs. + /// + public IReadOnlyList Snapshot() { + lock (_lock) { + return _events.ToList(); + } + } +} diff --git a/src/Spice86.Core/Emulator/VM/Input/Recording/InputRecordingReader.cs b/src/Spice86.Core/Emulator/VM/Input/Recording/InputRecordingReader.cs new file mode 100644 index 0000000000..3c721d62d5 --- /dev/null +++ b/src/Spice86.Core/Emulator/VM/Input/Recording/InputRecordingReader.cs @@ -0,0 +1,32 @@ +namespace Spice86.Core.Emulator.VM.Input.Recording; + +using Spice86.Shared.Emulator.Errors; + +using System.IO; +using System.Text.Json; + +internal static class InputRecordingReader { + internal static IReadOnlyList Read(string path) { + List events = []; + int lineNumber = 0; + foreach (string line in File.ReadLines(path)) { + lineNumber++; + if (!string.IsNullOrWhiteSpace(line)) { + events.Add(Parse(path, lineNumber, line)); + } + } + return events; + } + + private static RecordedInputEvent Parse(string path, int lineNumber, string line) { + try { + RecordedInputEvent? recorded = JsonSerializer.Deserialize(line, InputEventSerialization.Options); + if (recorded?.Event is null) { + throw new JsonException("The line holds no event."); + } + return recorded; + } catch (JsonException exception) { + throw new UnrecoverableException($"Invalid input recording {path} at line {lineNumber}: {exception.Message}", exception); + } + } +} diff --git a/src/Spice86.Core/Emulator/VM/Input/Recording/InputRecordingWriter.cs b/src/Spice86.Core/Emulator/VM/Input/Recording/InputRecordingWriter.cs new file mode 100644 index 0000000000..e728ed8f5c --- /dev/null +++ b/src/Spice86.Core/Emulator/VM/Input/Recording/InputRecordingWriter.cs @@ -0,0 +1,14 @@ +namespace Spice86.Core.Emulator.VM.Input.Recording; + +using System.IO; +using System.Linq; +using System.Text.Json; + +/// +/// Writes recorded host input events as JSON Lines, the counterpart of . +/// +internal static class InputRecordingWriter { + internal static void Write(string path, IReadOnlyList events) { + File.WriteAllLines(path, events.Select(e => JsonSerializer.Serialize(e, InputEventSerialization.Options))); + } +} diff --git a/src/Spice86.Core/Emulator/VM/Input/Recording/InputReplay.cs b/src/Spice86.Core/Emulator/VM/Input/Recording/InputReplay.cs new file mode 100644 index 0000000000..355a32b8fe --- /dev/null +++ b/src/Spice86.Core/Emulator/VM/Input/Recording/InputReplay.cs @@ -0,0 +1,25 @@ +namespace Spice86.Core.Emulator.VM.Input.Recording; + +/// +/// Holds the ordered stream of recorded input events being replayed. +/// +public sealed class InputReplay { + private readonly IReadOnlyList _events; + private int _index; + + /// + /// Initializes a new instance of the class. + /// + public InputReplay(IReadOnlyList events) { + _events = events; + } + + /// Gets a value indicating whether recorded events remain to be replayed. + public bool IsReplaying => _index < _events.Count; + + /// Gets the next recorded event to be applied. + public RecordedInputEvent Next => _events[_index]; + + /// Consumes and returns the next recorded event. + public RecordedInputEvent TakeNext() => _events[_index++]; +} diff --git a/src/Spice86.Core/Emulator/VM/Input/Recording/InputReplayDriver.cs b/src/Spice86.Core/Emulator/VM/Input/Recording/InputReplayDriver.cs new file mode 100644 index 0000000000..0238b7bec6 --- /dev/null +++ b/src/Spice86.Core/Emulator/VM/Input/Recording/InputReplayDriver.cs @@ -0,0 +1,58 @@ +namespace Spice86.Core.Emulator.VM.Input.Recording; + +using Spice86.Core.CLI; +using Spice86.Core.Emulator.VM.Breakpoint; +using Spice86.Core.Emulator.VM.DeviceScheduler; +using Spice86.Shared.Emulator.VM.Breakpoint; + +/// +/// Schedules recorded input events through a CPU cycle breakpoint or the emulation loop scheduler. +/// Only one batch is armed at a time: applying a batch arms the next, so a long recording neither fills +/// the scheduler queue nor leaves a breakpoint per event. +/// +public sealed class InputReplayDriver { + private readonly InputReplay _replay; + private readonly ReplayInputKey _key; + private readonly InputEventHub _hub; + private readonly EmulatorBreakpointsManager _breakpoints; + private readonly DeviceScheduler _emulationLoopScheduler; + + /// + /// Initializes a new instance of the class. + /// + public InputReplayDriver( + InputReplay replay, + ReplayInputKey key, + InputEventHub hub, + EmulatorBreakpointsManager breakpoints, + DeviceScheduler emulationLoopScheduler) { + _replay = replay; + _key = key; + _hub = hub; + _breakpoints = breakpoints; + _emulationLoopScheduler = emulationLoopScheduler; + } + + /// Arms the first recorded batch, if any events are queued for replay. + public void Start() => ScheduleNext(); + + private void ScheduleNext() { + if (!_replay.IsReplaying) { + return; + } + RecordedInputEvent next = _replay.Next; + if (_key == ReplayInputKey.Cycle) { + _breakpoints.ToggleBreakPoint(new AddressBreakPoint(BreakPointType.CPU_CYCLES, next.Cycle, + (_, _) => ApplyGroup(next), isRemovedOnTrigger: true), true); + } else { + _emulationLoopScheduler.AddEvent(_ => ApplyGroup(next), next.TimeMs - _emulationLoopScheduler.EventTimeMs); + } + } + + private void ApplyGroup(RecordedInputEvent first) { + while (_replay.IsReplaying && _replay.Next.Cycle == first.Cycle) { + _hub.ApplyAndRecord(_replay.TakeNext().Event); + } + ScheduleNext(); + } +} diff --git a/src/Spice86.Core/Emulator/VM/Input/Recording/RecordedInputEvent.cs b/src/Spice86.Core/Emulator/VM/Input/Recording/RecordedInputEvent.cs new file mode 100644 index 0000000000..acfd2153e8 --- /dev/null +++ b/src/Spice86.Core/Emulator/VM/Input/Recording/RecordedInputEvent.cs @@ -0,0 +1,6 @@ +namespace Spice86.Core.Emulator.VM.Input.Recording; + +using Spice86.Shared.Interfaces; + +/// One recorded host input event with the cycle count and emulated time at which it was applied. +public sealed record RecordedInputEvent(long Cycle, double TimeMs, IInputEvent Event); diff --git a/src/Spice86.Core/Emulator/VM/InputEventHub.cs b/src/Spice86.Core/Emulator/VM/InputEventHub.cs index c63babe490..f03203bc17 100644 --- a/src/Spice86.Core/Emulator/VM/InputEventHub.cs +++ b/src/Spice86.Core/Emulator/VM/InputEventHub.cs @@ -1,7 +1,9 @@ namespace Spice86.Core.Emulator.VM; +using Spice86.Core.Emulator.CPU; using Spice86.Core.Emulator.VM.Clock; using Spice86.Core.Emulator.VM.Input.Events; +using Spice86.Core.Emulator.VM.Input.Recording; using Spice86.Shared.Emulator.Keyboard; using Spice86.Shared.Emulator.Mouse; using Spice86.Shared.Interfaces; @@ -21,6 +23,9 @@ public class InputEventHub : IKeyboardInputEvents, IGuiMouseEvents, ITimeMultipl // A thread-safe queue shared by UI producers and the emulation thread. private readonly ConcurrentQueue _eventQueue = new(); private readonly IEmulatedClock _clock; + private readonly State _state; + private readonly InputRecording _recording; + private readonly InputReplay _replay; private readonly IGuiMouseEvents? _mouseEvents; private readonly IGuiKeyboardEvents? _keyboardEvents; @@ -45,9 +50,12 @@ public class InputEventHub : IKeyboardInputEvents, IGuiMouseEvents, ITimeMultipl /// /// Initializes a new instance of the class. /// - public InputEventHub(IEmulatedClock clock, IGuiKeyboardEvents? keyboardEvents = null, - IGuiMouseEvents? mouseEvents = null) { + public InputEventHub(IEmulatedClock clock, State state, InputRecording recording, InputReplay replay, + IGuiKeyboardEvents? keyboardEvents = null, IGuiMouseEvents? mouseEvents = null) { _clock = clock; + _state = state; + _recording = recording; + _replay = replay; if (keyboardEvents is not null) { _keyboardEvents = keyboardEvents; _keyboardEvents.KeyDown += OnKeyDown; @@ -62,7 +70,9 @@ public InputEventHub(IEmulatedClock clock, IGuiKeyboardEvents? keyboardEvents = } private void Enqueue(IInputEvent inputEvent) { - _eventQueue.Enqueue(inputEvent); + if (!_replay.IsReplaying) { + _eventQueue.Enqueue(inputEvent); + } } /// @@ -108,10 +118,17 @@ private void Enqueue(IInputEvent inputEvent) { internal void ProcessAllPendingInputEvents() { while (_eventQueue.TryDequeue(out IInputEvent? inputEvent)) { - Apply(inputEvent); + ApplyAndRecord(inputEvent); } } + internal void ApplyAndRecord(IInputEvent inputEvent) { + long cycle = _state.Cycles; + double timeMs = _clock.ElapsedTimeMs; + Apply(inputEvent); + _recording.Add(new RecordedInputEvent(cycle, timeMs, inputEvent)); + } + private void Apply(IInputEvent inputEvent) { switch (inputEvent) { case KeyboardEventArgs { IsPressed: true } key: diff --git a/src/Spice86.Shared/Emulator/Mouse/MouseButtonEventArgs.cs b/src/Spice86.Shared/Emulator/Mouse/MouseButtonEventArgs.cs index e96dd124ed..80c653a325 100644 --- a/src/Spice86.Shared/Emulator/Mouse/MouseButtonEventArgs.cs +++ b/src/Spice86.Shared/Emulator/Mouse/MouseButtonEventArgs.cs @@ -2,6 +2,8 @@ namespace Spice86.Shared.Emulator.Mouse; using Spice86.Shared.Interfaces; +using System.Text.Json.Serialization; + /// /// Contains the details of the mouse event. /// @@ -11,6 +13,7 @@ namespace Spice86.Shared.Emulator.Mouse; /// /// Which, if any, button triggered the event /// True if that button is pressed + [JsonConstructor] public MouseButtonEventArgs(MouseButton button, bool buttonDown) { Button = button; ButtonDown = buttonDown; diff --git a/src/Spice86.Shared/Emulator/Mouse/MouseMoveEventArgs.cs b/src/Spice86.Shared/Emulator/Mouse/MouseMoveEventArgs.cs index bf16295415..c0c140a108 100644 --- a/src/Spice86.Shared/Emulator/Mouse/MouseMoveEventArgs.cs +++ b/src/Spice86.Shared/Emulator/Mouse/MouseMoveEventArgs.cs @@ -2,6 +2,8 @@ namespace Spice86.Shared.Emulator.Mouse; using Spice86.Shared.Interfaces; +using System.Text.Json.Serialization; + /// /// Contains the details of a mouse movement event. /// @@ -11,6 +13,7 @@ namespace Spice86.Shared.Emulator.Mouse; /// /// The horizontal mouse position on a scale from 0 to 1 /// The vertical mouse position on a scale from 0 to 1 + [JsonConstructor] public MouseMoveEventArgs(double x, double y) { X = x; Y = y; diff --git a/src/Spice86/Spice86DependencyInjection.cs b/src/Spice86/Spice86DependencyInjection.cs index d0d06ff509..5a8d0cb746 100644 --- a/src/Spice86/Spice86DependencyInjection.cs +++ b/src/Spice86/Spice86DependencyInjection.cs @@ -70,6 +70,7 @@ namespace Spice86; using Spice86.Core.Emulator.VM.Clock; using Spice86.Core.Emulator.VM.CpuSpeedLimit; using Spice86.Core.Emulator.VM.DeviceScheduler; +using Spice86.Core.Emulator.VM.Input.Recording; using Spice86.Shared.Diagnostics; using Spice86.Shared.Emulator.Memory; using Spice86.Shared.Emulator.VM.Breakpoint.Serializable; @@ -513,9 +514,10 @@ internal Spice86DependencyInjection(Configuration configuration, MainWindow? mai maxLinesPerFile: CfgCSharpGenerator.MaxLinesPerFile), loggerService); DumpProgressReporter dumpProgressReporter = new(loggerService, new SystemTimeProvider()); DumpProgressReporter = dumpProgressReporter; + InputRecording inputRecording = new(isEnabled: configuration.ReproducibleRun is not null); EmulationStateDataWriter emulationStateDataWriter = new(state, executionAddressesExtractor, memoryDataExporter, listingExporter, cfgCpuSnapshotBuilder, changedMemoryMap, cfgBlocksJsonExporter, cfgCSharpDumper, cfgCpu.ExecutionContextManager, functionCatalogue, emulatorStateSerializationFolder, emulatorBreakpointsManager, - configuration, cfgCpu.CfgNodeFeeder.NodeIndex, recordedRunFacts, dumpProgressReporter, loggerService); + configuration, cfgCpu.CfgNodeFeeder.NodeIndex, recordedRunFacts, inputRecording, dumpProgressReporter, loggerService); EmulatorStateSerializer emulatorStateSerializer = new(emulatorStateSerializationFolder, emulationStateDataReader, emulationStateDataWriter); EmulatorStateSerializer = emulatorStateSerializer; @@ -569,6 +571,7 @@ internal Spice86DependencyInjection(Configuration configuration, MainWindow? mai ManualDumpRunner manualDumpRunner = new(); MainWindowServices? mainWindowServices = null; + InputReplay inputReplay = new(emulationStateDataReader.ReadInputRecordingOrEmpty(configuration.ReplayInput)); InputEventHub inputEventHub; if (mainWindow != null) { @@ -589,7 +592,7 @@ internal Spice86DependencyInjection(Configuration configuration, MainWindow? mai EmulatorDisplayViewModel displayViewModel = new EmulatorDisplayViewModel(uiDispatcher, pauseHandler, sharedMouseData, loggerService); vgaFunctionality.VideoModeChanged += displayViewModel.OnVideoModeChanged; - inputEventHub = new(_emulatedClock, displayViewModel, displayViewModel); + inputEventHub = new(_emulatedClock, state, inputRecording, inputReplay, displayViewModel, displayViewModel); _gui = displayViewModel; mainWindowServices = new MainWindowServices(mainWindow, uiDispatcher, hostStorageProvider, @@ -597,9 +600,13 @@ internal Spice86DependencyInjection(Configuration configuration, MainWindow? mai } else { HeadlessGui headlessGui = new HeadlessGui(); _gui = headlessGui; - inputEventHub = new InputEventHub(_emulatedClock, headlessGui, headlessGui); + inputEventHub = new InputEventHub(_emulatedClock, state, inputRecording, inputReplay, headlessGui, headlessGui); } + InputReplayDriver inputReplayDriver = new( + inputReplay, configuration.ReplayInputBy, inputEventHub, + emulatorBreakpointsManager, emulationLoopScheduler); + EmulationLoop emulationLoop = new( functionHandler, cfgCpu, state, emulationLoopScheduler, emulatorBreakpointsManager, @@ -765,7 +772,7 @@ internal Spice86DependencyInjection(Configuration configuration, MainWindow? mai emulatorBreakpointsManager, emulationLoop, emulatorStateSerializer, loggerService); ProgramExecutor createdProgramExecutor = new( programBootstrapper, executionPolicy, emulationLoop, - emulatorStateSerializer, shutdownCoordinator, loggerService); + emulatorStateSerializer, shutdownCoordinator, inputReplayDriver, loggerService); if (loggerService.IsEnabled(LogLevel.Information)) { loggerService.LogInformation("Program executor created..."); diff --git a/tests/Spice86.Tests/AsmFixtures/AsmFixtureCatalog.cs b/tests/Spice86.Tests/AsmFixtures/AsmFixtureCatalog.cs index dece37c4fa..298185c339 100644 --- a/tests/Spice86.Tests/AsmFixtures/AsmFixtureCatalog.cs +++ b/tests/Spice86.Tests/AsmFixtures/AsmFixtureCatalog.cs @@ -8,11 +8,13 @@ namespace Spice86.Tests.AsmFixtures; using NSubstitute; using Spice86.Core.Emulator.CPU; +using Spice86.Core.Emulator.Devices.Input.Mouse; using Spice86.Core.Emulator.Devices.Sound; using Spice86.Core.Emulator.Devices.Sound.Blaster; using Spice86.Core.Emulator.InterruptHandlers.VGA; using Spice86.Core.Emulator.VM; using Spice86.Core.Emulator.VM.Breakpoint; +using Spice86.Core.Emulator.VM.Input.Recording; using Spice86.Shared.Emulator.VM.Breakpoint; using Spice86.Core.CLI; using Spice86.Shared.Emulator.Keyboard; @@ -745,6 +747,120 @@ public static AsmFixture InputTimerKeysReleaseAll() { }); } + /// Runs input_timer_keys with a mouse move, a left click and a release of all keys before key A, + /// injected keys A, B and C and a clock change to 2x in between, recording the applied input, so the + /// recording holds every input event kind. No key is down at the release, so it sends no break code, and + /// the machine has no mouse, so the mouse events change nothing in the program. + /// The oracle checks the result bytes and that the dumped recording holds the + /// same events as the committed resource; the exact recorded cycles and times are compared line for line by + /// the engine assertion, because generated code applies input enqueued by a cycle breakpoint at that + /// breakpoint's cycle while the interpreter applies it after the next instruction. + public static AsmFixture InputTimerKeysRecord(AsmRunScope scope) { + AsmRunSettings settings = InputTimerKeysRecordingSettings(scope, "record"); + settings = settings with { + HeadlessKeyInjections = [ + new HeadlessKeyInjection(5000, gui => gui.SimulateKeyPress(PhysicalKey.A)), + new HeadlessKeyInjection(30000, gui => gui.SimulateKeyPress(PhysicalKey.B)), + new HeadlessKeyInjection(150000, gui => gui.SimulateKeyPress(PhysicalKey.C)) + ], + ConfigureMachine = machine => { + InputEventHub hub = machine.InputEventHub; + InjectAtCycle(machine, 2000, () => hub.PostMouseMoveEvent(new MouseMoveEventArgs(0.25, 0.75))); + InjectAtCycle(machine, 3000, () => hub.PostMouseButtonEvent(new MouseButtonEventArgs(MouseButton.Left, true))); + InjectAtCycle(machine, 3500, () => hub.PostMouseButtonEvent(new MouseButtonEventArgs(MouseButton.Left, false))); + InjectAtCycle(machine, 4000, hub.ReleaseAllKeys); + InjectAtCycle(machine, 20000, () => hub.SetTimeMultiplier(2)); + } + }; + return ResultFixture(settings, result => { + result.Memory.ReadRam(8, 0x500).Should().Equal(ExpectedRecordedResult, + "input_timer_keys record: the injected input produced the recorded scan codes and tick counts"); + AssertRecordedEventsEqualResource(result, "record"); + }).WithEngineAssertions((engineScope, _) => + AssertRecordedFileEqualsResource(engineScope, "record")); + } + + private static void InjectAtCycle(Machine machine, long cycle, Action inject) { + machine.EmulatorBreakpointsManager.ToggleBreakPoint(new AddressBreakPoint(BreakPointType.CPU_CYCLES, cycle, + (_, _) => inject(), isRemovedOnTrigger: true), true); + } + + /// Runs input_timer_keys replaying the committed recording scheduled by + /// at cycles per second: the recorded key presses and clock change are + /// applied while the live X injection is discarded, so the result bytes are the recorded scan codes and + /// the timer ticks counted at each key. When is set the dumped + /// recording's events and (as an engine assertion) its exact cycles and times must match the committed + /// resource — see for why the two checks differ. + public static AsmFixture InputTimerKeysReplay(AsmRunScope scope, string variantName, long cyclesPerSecond, + ReplayInputKey key, byte[] expectedResult, bool verifyRecordingFile = false) { + AsmRunSettings settings = InputTimerKeysRecordingSettings(scope, variantName, verifyRecordingFile); + settings = settings with { + ReproducibleRun = cyclesPerSecond, + InstructionTimeScale = cyclesPerSecond, + ReplayInput = "Resources/cpuTests/input_timer_keys.recording.jsonl", + ReplayInputBy = key, + HeadlessKeyInjections = [ + new HeadlessKeyInjection(1000, gui => gui.SimulateKeyPress(PhysicalKey.X)) + ] + }; + AsmFixture fixture = ResultFixture(settings, result => { + result.Memory.ReadRam(8, 0x500).Should().Equal(expectedResult, + $"input_timer_keys {variantName}: the replayed input produced the recorded scan codes and tick counts"); + if (verifyRecordingFile) { + AssertRecordedEventsEqualResource(result, variantName); + } + }); + if (!verifyRecordingFile) { + return fixture; + } + return fixture.WithEngineAssertions((engineScope, _) => AssertRecordedFileEqualsResource(engineScope, variantName)); + } + + /// The result bytes at 0x500 of the recorded input_timer_keys run and of a replay at the + /// recorded speed: make A, two timer ticks, make B, make C and the recorded tick count. + private static readonly byte[] ExpectedRecordedResult = [0x1E, 0x06, 0x30, 0x36, 0x2E, 0x7C, 0x7C, 0x01]; + + private const string InputRecordingObservation = "inputRecording"; + private const string InputRecordingResource = "Resources/cpuTests/input_timer_keys.recording.jsonl"; + + private static AsmRunSettings InputTimerKeysRecordingSettings(AsmRunScope scope, string variantName, bool observe = true) { + AsmRunSettings settings = new() { + BinName = "input_timer_keys", + VariantName = variantName, + MaxCycles = 400000, + ReproducibleRun = 100000, + InstructionTimeScale = 100000, + RenderingMode = RenderingMode.Sync, + // The program has no mouse interrupt handler: the recorded mouse events reach no device. + Mouse = MouseType.None + }; + if (!observe) { + return settings; + } + string directory = scope.CreateWorkingDirectory($"input_timer_keys_{variantName}"); + scope.AddObservationProvider(InputRecordingObservation, + _ => Directory.GetFiles(directory, "spice86dumpInputRecording.jsonl", + SearchOption.AllDirectories).Single()); + return settings with { RecordedDataDirectory = directory }; + } + + /// Both modes apply the same recorded events: the engine differs only on the cycle and time + /// recorded for each of them, which the engine assertion compares instead. + private static void AssertRecordedEventsEqualResource(AsmFixtureResult result, string variantName) { + string dumpedPath = result.Observations.Get(InputRecordingObservation); + InputRecordingReader.Read(dumpedPath).Select(e => e.Event).Should().Equal( + InputRecordingReader.Read(InputRecordingResource).Select(e => e.Event), + $"input_timer_keys {variantName}: the dumped recording holds the committed resource's events"); + } + + /// Emulated runs record the input at deterministic cycles and times, so the dumped file equals + /// the committed resource line for line. + private static void AssertRecordedFileEqualsResource(AsmRunScope scope, string variantName) { + File.ReadAllLines(scope.Observations.Get(InputRecordingObservation)).Should().Equal( + File.ReadAllLines(InputRecordingResource), + $"input_timer_keys {variantName}: the dumped recording equals the committed resource line for line"); + } + /// Runs speculative_branch on the observed or unobserved arm and checks the arm's result bytes. public static AsmFixture SpeculativeBranch(SpeculativeArm arm) { if (arm == SpeculativeArm.Unobserved) { diff --git a/tests/Spice86.Tests/AsmFixtures/AsmRunSettings.cs b/tests/Spice86.Tests/AsmFixtures/AsmRunSettings.cs index 20abc5ccfc..fb2497421b 100644 --- a/tests/Spice86.Tests/AsmFixtures/AsmRunSettings.cs +++ b/tests/Spice86.Tests/AsmFixtures/AsmRunSettings.cs @@ -2,6 +2,7 @@ namespace Spice86.Tests.AsmFixtures; using Spice86.Core.CLI; using Spice86.Core.Emulator.CPU; +using Spice86.Core.Emulator.Devices.Input.Mouse; using Spice86.Core.Emulator.Devices.Sound; using Spice86.Core.Emulator.Devices.Sound.Blaster; using Spice86.Core.Emulator.Function; @@ -99,6 +100,18 @@ public string HandlerSegmentGoldenSuffix { /// Seed of the deterministic clock jitter, or null for no jitter. public int? ClockJitterSeed { get; init; } + /// Reproducible run speed in cycles per second, or null to disable input recording. + public long? ReproducibleRun { get; init; } + + /// Path to a recorded input file to replay, or null for live input. + public string? ReplayInput { get; init; } + + /// Key used to schedule replayed input events. + public ReplayInputKey ReplayInputBy { get; init; } = ReplayInputKey.Cycle; + + /// Mouse the machine exposes. + public MouseType Mouse { get; init; } = MouseType.Ps2; + /// Sound Blaster model the machine exposes. public SbType SbType { get; init; } = SbType.None; diff --git a/tests/Spice86.Tests/AsmFixtures/AsmScenarioCatalog.cs b/tests/Spice86.Tests/AsmFixtures/AsmScenarioCatalog.cs index fb68dae74a..4a0534a95c 100644 --- a/tests/Spice86.Tests/AsmFixtures/AsmScenarioCatalog.cs +++ b/tests/Spice86.Tests/AsmFixtures/AsmScenarioCatalog.cs @@ -6,6 +6,7 @@ namespace Spice86.Tests.AsmFixtures; using NSubstitute; +using Spice86.Core.CLI; using Spice86.Core.Emulator.CPU; using Spice86.Core.Emulator.OperatingSystem.Structures; using Spice86.Core.Emulator.ReverseEngineer.CfgCodeGeneration; @@ -845,6 +846,25 @@ private static IReadOnlyList BuildCpuScenarios() { .WithTimingDependentState("the IRQ1 frame lands at a run-dependent instruction boundary, so the stale pushed frame bytes differ between modes"), AsmScenario.FromFixture("input_timer_keys", AsmFixtureCatalog.InputTimerKeysReleaseAll) .WithTimingDependentState("the injected-key and timer interrupts land at run-dependent instruction boundaries between modes, so the stale frame bytes left on the stack differ"), + new AsmScenario("input_timer_keys", + scope => AsmFixtureCatalog.InputTimerKeysRecord(scope), + ["cpuTests/input_timer_keys.recording.jsonl"]) + .WithTimingDependentState("the injected-key and timer interrupts land at run-dependent instruction boundaries between modes, so the stale frame bytes left on the stack differ"), + new AsmScenario("input_timer_keys", + scope => AsmFixtureCatalog.InputTimerKeysReplay(scope, "replay-cycle", 100000, ReplayInputKey.Cycle, + [0x1E, 0x06, 0x30, 0x36, 0x2E, 0x7C, 0x7C, 0x01], verifyRecordingFile: true), + ["cpuTests/input_timer_keys.recording.jsonl"]) + .WithTimingDependentState("the replayed key and timer interrupts land at run-dependent instruction boundaries between modes, so the stale frame bytes left on the stack differ"), + new AsmScenario("input_timer_keys", + scope => AsmFixtureCatalog.InputTimerKeysReplay(scope, "replay-time-50000", 50000, ReplayInputKey.Time, + [0x1E, 0x06, 0x30, 0x36, 0x2E, 0x7C, 0x7C, 0x01]), + ["cpuTests/input_timer_keys.recording.jsonl"]) + .WithTimingDependentState("the replayed key and timer interrupts land at run-dependent instruction boundaries between modes, so the stale frame bytes left on the stack differ"), + new AsmScenario("input_timer_keys", + scope => AsmFixtureCatalog.InputTimerKeysReplay(scope, "replay-cycle-50000", 50000, ReplayInputKey.Cycle, + [0x1E, 0x0D, 0x30, 0x6C, 0x2E, 0xF8, 0xF8, 0x02]), + ["cpuTests/input_timer_keys.recording.jsonl"]) + .WithTimingDependentState("the replayed key and timer interrupts land at run-dependent instruction boundaries between modes, so the stale frame bytes left on the stack differ"), PartitionScenario("data_global_offset_fault"), PartitionScenario("data_jump_tables_segments"), AsmScenario.FromFixture("data_jump_tables", AsmFixtureCatalog.DataJumpTablesPatched), diff --git a/tests/Spice86.Tests/MouseDriverTests.cs b/tests/Spice86.Tests/MouseDriverTests.cs index af6a7e249e..276604f000 100644 --- a/tests/Spice86.Tests/MouseDriverTests.cs +++ b/tests/Spice86.Tests/MouseDriverTests.cs @@ -25,6 +25,8 @@ namespace Spice86.Tests; using Spice86.Core.Emulator.VM; using Spice86.Core.Emulator.VM.Clock; using Spice86.Core.Emulator.VM.DeviceScheduler; +using Spice86.Core.Emulator.VM.Input.Recording; + using Spice86.Shared.Emulator.Memory; using Spice86.Shared.Emulator.Mouse; @@ -51,7 +53,7 @@ public MouseDriverTests() { IOPortDispatcher ports = new(new(), _state, NullLogger.Instance, false); DualPic pic = new(ports, _state, NullLogger.Instance, false); CyclesClock clock = new(_state, 1000, null, DateTimeOffset.UnixEpoch, NullLogger.Instance); - _inputEventHub = new(clock); + _inputEventHub = new(clock, _state, new Spice86.Core.Emulator.VM.Input.Recording.InputRecording(isEnabled: false), new InputReplay([])); DeviceScheduler scheduler = new(clock, NullLogger.Instance, "Mouse driver test"); Mouse mouse = new(_state, _sharedMouseData, pic, MouseType.Ps2, NullLogger.Instance, false, clock, scheduler, _inputEventHub); IVgaFunctionality video = Substitute.For(); diff --git a/tests/Spice86.Tests/MouseInputTests.cs b/tests/Spice86.Tests/MouseInputTests.cs index 6c993d6c04..227aaa0648 100644 --- a/tests/Spice86.Tests/MouseInputTests.cs +++ b/tests/Spice86.Tests/MouseInputTests.cs @@ -14,6 +14,8 @@ namespace Spice86.Tests; using Spice86.Core.Emulator.VM; using Spice86.Core.Emulator.VM.Clock; using Spice86.Core.Emulator.VM.DeviceScheduler; +using Spice86.Core.Emulator.VM.Input.Recording; + using Spice86.Shared.Emulator.Mouse; using Xunit; @@ -26,8 +28,8 @@ public sealed class MouseInputTests { private readonly DualPic _pic; public MouseInputTests() { - _hub = new(_clock); State state = new(CpuModel.INTEL_80286); + _hub = new(_clock, state, new Spice86.Core.Emulator.VM.Input.Recording.InputRecording(isEnabled: false), new InputReplay([])); IOPortDispatcher ports = new(new(), state, NullLogger.Instance, false); _pic = new(ports, state, NullLogger.Instance, false); _scheduler = new(_clock, NullLogger.Instance, "Mouse input test"); diff --git a/tests/Spice86.Tests/MouseStateTests.cs b/tests/Spice86.Tests/MouseStateTests.cs index b081306f6e..377363b057 100644 --- a/tests/Spice86.Tests/MouseStateTests.cs +++ b/tests/Spice86.Tests/MouseStateTests.cs @@ -14,6 +14,8 @@ namespace Spice86.Tests; using Spice86.Core.Emulator.VM; using Spice86.Core.Emulator.VM.Clock; using Spice86.Core.Emulator.VM.DeviceScheduler; +using Spice86.Core.Emulator.VM.Input.Recording; + using Spice86.Shared.Emulator.Mouse; using System.Text.Json; @@ -36,8 +38,8 @@ public sealed class MouseStateTests { private readonly DualPic _pic; public MouseStateTests() { - _hub = new(_clock); State state = new(CpuModel.INTEL_80286); + _hub = new(_clock, state, new Spice86.Core.Emulator.VM.Input.Recording.InputRecording(isEnabled: false), new InputReplay([])); IOPortDispatcher ports = new(new(), state, NullLogger.Instance, false); _pic = new(ports, state, NullLogger.Instance, false); _scheduler = new(_clock, NullLogger.Instance, "Mouse state test"); diff --git a/tests/Spice86.Tests/Resources/cpuTests/input_timer_keys.recording.jsonl b/tests/Spice86.Tests/Resources/cpuTests/input_timer_keys.recording.jsonl new file mode 100644 index 0000000000..a72bf85674 --- /dev/null +++ b/tests/Spice86.Tests/Resources/cpuTests/input_timer_keys.recording.jsonl @@ -0,0 +1,8 @@ +{"cycle":2001,"timeMs":20.01,"event":{"kind":"mouseMove","x":0.25,"y":0.75}} +{"cycle":3001,"timeMs":30.01,"event":{"kind":"mouseButton","buttonDown":true,"button":"Left"}} +{"cycle":3501,"timeMs":35.01,"event":{"kind":"mouseButton","buttonDown":false,"button":"Left"}} +{"cycle":4001,"timeMs":40.01,"event":{"kind":"releaseAllKeys"}} +{"cycle":5001,"timeMs":50.01,"event":{"kind":"key","key":"A","isPressed":true}} +{"cycle":20002,"timeMs":200.02,"event":{"kind":"timeMultiplier","multiplier":2}} +{"cycle":30002,"timeMs":400.02,"event":{"kind":"key","key":"B","isPressed":true}} +{"cycle":150001,"timeMs":2800,"event":{"kind":"key","key":"C","isPressed":true}} diff --git a/tests/Spice86.Tests/Spice86Creator.cs b/tests/Spice86.Tests/Spice86Creator.cs index d2e2dcf212..37f5132589 100644 --- a/tests/Spice86.Tests/Spice86Creator.cs +++ b/tests/Spice86.Tests/Spice86Creator.cs @@ -63,7 +63,9 @@ internal Spice86Creator(AsmFixtures.AsmRunSettings settings, JitMode jitMode, IO settings.RecordedDataDirectory, settings.ReloadCfgGraph, settings.RenderingMode, settings.AsmHandlersSegment, settings.CpuModel, settings.EnableSpeculativeCfgExploration, TestClockStartTime, - settings.CheckBuild, clockJitterSeed: settings.ClockJitterSeed) { + settings.CheckBuild, clockJitterSeed: settings.ClockJitterSeed, + reproducibleRun: settings.ReproducibleRun, + replayInput: settings.ReplayInput, replayInputBy: settings.ReplayInputBy, mouse: settings.Mouse) { EnableUmb = settings.EnableUmb; HltStopsEmulation = settings.HltStopsEmulation; _settings = settings; @@ -81,7 +83,9 @@ private Spice86Creator(string binName, long maxCycles, bool installInterruptVect bool failOnInvalidOpcode, string? recordedDataDirectory, bool reloadCfgGraph, RenderingMode renderingMode, ushort asmHandlersSegment, CpuModel? cpuModel, bool enableSpeculativeCfgExploration, DateTimeOffset? clockStartTime, - bool checkBuild, double timeMultiplier = 1, int? clockJitterSeed = null) { + bool checkBuild, double timeMultiplier = 1, int? clockJitterSeed = null, + long? reproducibleRun = null, string? replayInput = null, + ReplayInputKey replayInputBy = ReplayInputKey.Cycle, MouseType mouse = MouseType.Ps2) { string executablePath = Path.IsPathRooted(binName) ? binName : $"Resources/cpuTests/{binName}.bin"; if (overrideSupplierClassName != null && overrideSupplier != null) { throw new ArgumentException("Provide either an override supplier instance or an override supplier class name, not both."); @@ -111,7 +115,7 @@ private Spice86Creator(string binName, long maxCycles, bool installInterruptVect TimeMultiplier = timeMultiplier, //Don"t need nor want to instantiate the UI in emulator unit tests HeadlessMode = HeadlessType.Minimal, - Mouse = MouseType.Ps2, + Mouse = mouse, AudioEngine = AudioEngine.Dummy, SbType = sbType, SbBase = sbBase, @@ -134,6 +138,9 @@ private Spice86Creator(string binName, long maxCycles, bool installInterruptVect // wall-clock non-determinism in tests. // 333333 is the value that allowed most wall clock based tests to pass without changing all the expected values. InstructionTimeScale = instructionTimeScale ?? 333333, + ReproducibleRun = reproducibleRun, + ReplayInput = replayInput, + ReplayInputBy = replayInputBy, JitMode = jitMode, JitGeneratorIr = TestJitSettings.GeneratorIr, FailOnInvalidOpcode = failOnInvalidOpcode,