diff --git a/Tests/Player/VpeGleSourceTests.cs b/Tests/Player/VpeGleSourceTests.cs index aee32e2..34d2aac 100644 --- a/Tests/Player/VpeGleSourceTests.cs +++ b/Tests/Player/VpeGleSourceTests.cs @@ -28,7 +28,7 @@ public sealed class VpeGleSourceTests [TestCase(DisplayFrameFormat.Dmd8, 255)] public void GrayFramesReachBothDestinations(DisplayFrameFormat format, int max) { - var source = VpeGleSource.Create(new DisplayConfig("dmd0", Width, Height), colorize: false, rgb: false); + var source = VpeGleSource.Create(new DisplayConfig("dmd0", Width, Height), colorize: false, DmdSourceColor.Gray); var everyFormat = new EveryFormatDestination("every format"); var rgbOnly = new RgbOnlyDestination("rgb only"); using (Render(source, everyFormat, rgbOnly)) { @@ -47,7 +47,7 @@ public void GrayFramesReachBothDestinations(DisplayFrameFormat format, int max) [Test] public void RgbFramesReachBothDestinations() { - var source = VpeGleSource.Create(new DisplayConfig("dmd0", Width, Height), colorize: false, rgb: true); + var source = VpeGleSource.Create(new DisplayConfig("dmd0", Width, Height), colorize: false, DmdSourceColor.Rgb24); var everyFormat = new EveryFormatDestination("every format"); var rgbOnly = new RgbOnlyDestination("rgb only"); using (Render(source, everyFormat, rgbOnly)) { @@ -63,6 +63,34 @@ public void RgbFramesReachBothDestinations() Assert.That(rgbOnly.Frames[0].Format, Is.EqualTo("Rgb24")); } + [Test] + public void Rgb565FramesReachBothDestinations() + { + var source = VpeGleSource.Create(new DisplayConfig("dmd0", Width, Height), colorize: false, DmdSourceColor.Rgb565); + var everyFormat = new EveryFormatDestination("every format"); + var rgbOnly = new RgbOnlyDestination("rgb only"); + // red, green, blue, white; black, r16 g32 b16, r1 g1 b1, r11 g23 b11 + ushort[] pixels = { 0xf800, 0x07e0, 0x001f, 0xffff, 0x0000, 0x8410, 0x0821, 0x5aeb }; + var frame = new byte[Width * Height * 2]; + for (var i = 0; i < pixels.Length; i++) { + frame[i * 2] = (byte)pixels[i]; // little-endian + frame[i * 2 + 1] = (byte)(pixels[i] >> 8); + } + using (Render(source, everyFormat, rgbOnly)) { + source.Push(DisplayFrameFormat.Dmd565, frame, frame.Length); + } + + Assert.That(everyFormat.Frames, Has.Count.EqualTo(1), "hardware taking RGB565"); + Assert.That(everyFormat.Frames[0].Format, Is.EqualTo("Rgb565")); + Assert.That(everyFormat.Frames[0].Data, Is.EqualTo(frame), "RGB565 passes through unchanged"); + Assert.That(rgbOnly.Frames, Has.Count.EqualTo(1), "RGB24 only"); + Assert.That(rgbOnly.Frames[0].Format, Is.EqualTo("Rgb24")); + Assert.That(rgbOnly.Frames[0].Data, Is.EqualTo(new byte[] { + 255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255, + 0, 0, 0, 132, 130, 132, 8, 4, 8, 90, 93, 90, + }), "each channel's top bits repeated into its low ones"); + } + private static IDisposable Render(VpeGleSource source, params IDestination[] destinations) { var graph = new RenderGraph(new UndisposedReferences(), runOnMainThread: true) { diff --git a/Tests/Player/VpeTypes.cs b/Tests/Player/VpeTypes.cs index b23cba5..394ec20 100644 --- a/Tests/Player/VpeTypes.cs +++ b/Tests/Player/VpeTypes.cs @@ -17,7 +17,8 @@ public enum DisplayFrameFormat Segment, AlphaNumeric, Numeric, - Video24 + Video24, + Dmd565 } public class DisplayConfig diff --git a/VisualPinball.Engine.DMD.Unity/Runtime/DmdBridgePlayer.cs b/VisualPinball.Engine.DMD.Unity/Runtime/DmdBridgePlayer.cs index ff531cd..cffaeab 100644 --- a/VisualPinball.Engine.DMD.Unity/Runtime/DmdBridgePlayer.cs +++ b/VisualPinball.Engine.DMD.Unity/Runtime/DmdBridgePlayer.cs @@ -104,7 +104,7 @@ public class DmdBridgePlayer : MonoBehaviour, IDiagnosticsSource private IGamelogicEngine _gamelogicEngine; private bool _managed; // whether the frames are RGB rather than gray, which decides the pipeline's source - private bool _sourceRgb; + private DmdSourceColor _sourceColor; private bool _shutdown; private GameObject _managedScene; private Func _presentationDestination; @@ -171,7 +171,7 @@ public void ConfigureManaged(DmdBridgeSettings settings, GameObject scene, Func< if (_pipeline != null) throw new InvalidOperationException("Configure the DMD bridge before starting its pipeline."); _managed = true; _settings = settings.Clone(); _managedScene = scene; _presentationDestination = presentationDestination; _ownerScheduler = ownerScheduler; _managedInput = new ManagedDmdInput(ownerScheduler, (displayId, width, height, encoding) => { - EnsurePipeline(new DisplayConfig(displayId, width, height), force: true, rgb: encoding == DisplayEncoding.Rgb24); + EnsurePipeline(new DisplayConfig(displayId, width, height), force: true, color: VpeGleSource.ColorOf(GamelogicPluginResources.ToLegacy(encoding))); return _pipeline; }, sourceIsCurrent, error => Logger.Warn(error, "[DMD] Could not replace the display graph; the next frame will retry.")); } @@ -302,7 +302,7 @@ private void HandleDisplayUpdateFrame(object sender, DisplayFrameData frame) if (_currentDisplay == null) { if (TryInferDisplayConfig(frame, out var inferredDisplay)) { Logger.Info("[DMD] Inferred display {DisplayId} as {Width}x{Height} from the frame stream.", inferredDisplay.Id, inferredDisplay.Width, inferredDisplay.Height); - EnsurePipeline(inferredDisplay, rgb: frame.Format == DisplayFrameFormat.Dmd24); + EnsurePipeline(inferredDisplay, color: VpeGleSource.ColorOf(frame.Format)); } else if (!_missingDisplayWarningLogged) { Logger.Warn("[DMD] Got a frame for {DisplayId} before its dimensions were requested, and could not infer them from {Length} byte(s).", frame.Id, frame.Data?.Length ?? 0); _missingDisplayWarningLogged = true; @@ -314,9 +314,13 @@ private void HandleDisplayUpdateFrame(object sender, DisplayFrameData frame) } } - // the source carries either gray or RGB frames, see VpeGleSource.Create() + // the source carries gray, RGB or RGB565 frames, see VpeGleSource.Create(); a short frame + // is dropped before it can rebuild a working pipeline + if (frame.Data == null || frame.Data.Length < _currentDisplay.Width * _currentDisplay.Height * VpeGleSource.BytesPerDot(frame.Format)) { + return; + } if (!_pipeline.Accepts(frame.Format)) { - EnsurePipeline(_currentDisplay, force: true, rgb: frame.Format == DisplayFrameFormat.Dmd24); + EnsurePipeline(_currentDisplay, force: true, color: VpeGleSource.ColorOf(frame.Format)); if (_pipeline == null) { return; } @@ -340,10 +344,9 @@ private static bool TryInferDisplayConfig(DisplayFrameData frame, out DisplayCon return false; } - var pixelCount = frame.Format == DisplayFrameFormat.Dmd24 - ? frame.Data.Length / 3 - : frame.Data.Length; - if (frame.Format == DisplayFrameFormat.Dmd24 && frame.Data.Length % 3 != 0) { + var bytesPerDot = VpeGleSource.BytesPerDot(frame.Format); + var pixelCount = frame.Data.Length / bytesPerDot; + if (frame.Data.Length % bytesPerDot != 0) { return false; } @@ -381,12 +384,12 @@ private static bool TryInferDimensions(int pixelCount, out int width, out int he } } - private void EnsurePipeline(DisplayConfig display, bool force = false, bool? rgb = null) + private void EnsurePipeline(DisplayConfig display, bool force = false, DmdSourceColor? color = null) { _currentDisplay = display; // without a frame to go by, keep the format the last pipeline was built for - _sourceRgb = rgb ?? _sourceRgb; - if (!force && _pipeline != null && _pipeline.Matches(display) && _pipeline.Accepts(_sourceRgb ? DisplayFrameFormat.Dmd24 : DisplayFrameFormat.Dmd8)) { + _sourceColor = color ?? _sourceColor; + if (!force && _pipeline != null && _pipeline.Matches(display) && _pipeline.Accepts(FormatOf(_sourceColor))) { return; } @@ -403,15 +406,27 @@ private void EnsurePipeline(DisplayConfig display, bool force = false, bool? rgb return; } - var converter = CreateConverter(); + // colorizers take gray frames: frames that come in color pass through, and the producer keeps its format + AbstractConverter converter = null; + if (_sourceColor == DmdSourceColor.Gray) { + converter = CreateConverter(); + RequestSourceFrameFormat(converter != null ? DisplayFrameFormat.Dmd4 : DisplayFrameFormat.Dmd8); + } else { + _colorization = "none (the game sends color)"; + } _resolvedConverter = converter?.Name ?? "none"; - RequestSourceFrameFormat(converter != null ? DisplayFrameFormat.Dmd4 : DisplayFrameFormat.Dmd8); - _pipeline = new DmdPipeline(display, destinations, converter, _settings.FlipHorizontally, _sourceRgb); + _pipeline = new DmdPipeline(display, destinations, converter, _settings.FlipHorizontally, _sourceColor); Logger.Info("[DMD] Pipeline for {DisplayId} ({Width}x{Height}) created with {Count} destination(s): {Destinations:l}, colorization: {Colorization:l}.", display.Id, display.Width, display.Height, destinations.Count, _destinationNames, _colorization); PublishDiagnostics(); } + private static DisplayFrameFormat FormatOf(DmdSourceColor color) => color switch { + DmdSourceColor.Rgb24 => DisplayFrameFormat.Dmd24, + DmdSourceColor.Rgb565 => DisplayFrameFormat.Dmd565, + _ => DisplayFrameFormat.Dmd8 + }; + private static string[] DestinationNames(List destinations) { var names = new List(destinations.Count); diff --git a/VisualPinball.Engine.DMD.Unity/Runtime/DmdPipeline.cs b/VisualPinball.Engine.DMD.Unity/Runtime/DmdPipeline.cs index a79d610..0577db1 100644 --- a/VisualPinball.Engine.DMD.Unity/Runtime/DmdPipeline.cs +++ b/VisualPinball.Engine.DMD.Unity/Runtime/DmdPipeline.cs @@ -36,7 +36,7 @@ internal sealed class DmdPipeline : IManagedDmdPipeline { private readonly DisplayConfig _display; private readonly VpeGleSource _source; - private readonly bool _rgb; + private readonly DmdSourceColor _color; private readonly List _destinations; private readonly RenderGraph _renderGraph; private readonly IDisposable _renderer; @@ -65,12 +65,12 @@ internal sealed class DmdPipeline : IManagedDmdPipeline private readonly LogThrottle _frameFailureThrottle = new LogThrottle(3, TimeSpan.FromSeconds(30)); private readonly LogThrottle _renderGraphErrorThrottle = new LogThrottle(3, TimeSpan.FromSeconds(30)); - public DmdPipeline(DisplayConfig display, List destinations, AbstractConverter converter, bool flipHorizontally, bool rgb) + public DmdPipeline(DisplayConfig display, List destinations, AbstractConverter converter, bool flipHorizontally, DmdSourceColor color) { _display = display; _destinations = destinations; - _rgb = rgb; - _source = VpeGleSource.Create(display, converter != null, rgb); + _color = color; + _source = VpeGleSource.Create(display, converter != null, color); _renderGraph = new RenderGraph(new UndisposedReferences(), runOnMainThread: true) { Name = $"VPE DMD ({display.Id})", Source = _source, @@ -110,11 +110,11 @@ public bool Matches(string displayId, int width, int height, DisplayEncoding enc { return string.Equals(_display.Id, displayId, StringComparison.OrdinalIgnoreCase) && _display.Width == width && _display.Height == height - && (encoding == DisplayEncoding.Rgb24) == _rgb; + && VpeGleSource.ColorOf(GamelogicPluginResources.ToLegacy(encoding)) == _color; } - /// Whether the source was built for frames of this format, gray or RGB. - public bool Accepts(DisplayFrameFormat format) => (format == DisplayFrameFormat.Dmd24) == _rgb; + /// Whether the source was built for frames of this format: gray, RGB or RGB565. + public bool Accepts(DisplayFrameFormat format) => VpeGleSource.ColorOf(format) == _color; /// Called on the Unity main thread. Copies the frame and signals the worker. public void Push(DisplayFrameData frame) @@ -123,12 +123,18 @@ public void Push(DisplayFrameData frame) return; } + // a short frame would be read past its end further down the graph + int length = _display.Width * _display.Height * VpeGleSource.BytesPerDot(frame.Format); + if (frame.Data.Length < length) { + return; + } + lock (_gate) { - if (_pending == null || _pending.Length < frame.Data.Length) { - _pending = new byte[frame.Data.Length]; + if (_pending == null || _pending.Length < length) { + _pending = new byte[length]; } - Buffer.BlockCopy(frame.Data, 0, _pending, 0, frame.Data.Length); - _pendingLength = frame.Data.Length; + Buffer.BlockCopy(frame.Data, 0, _pending, 0, length); + _pendingLength = length; _pendingFormat = frame.Format; _hasPending = true; } @@ -137,7 +143,7 @@ public void Push(DisplayFrameData frame) public void Push(in PluginDisplayFrame frame) { - int rowBytes = frame.Width * (frame.Encoding == DisplayEncoding.Rgb24 ? 3 : 1); + int rowBytes = frame.Width * PluginDisplayFrame.BytesPerPixel(frame.Encoding); int length = checked(rowBytes * frame.Height); lock (_gate) { if (!_running) return; diff --git a/VisualPinball.Engine.DMD.Unity/Runtime/Plugins/DmdPlugin.cs b/VisualPinball.Engine.DMD.Unity/Runtime/Plugins/DmdPlugin.cs index 0c5ae09..17ab9a7 100644 --- a/VisualPinball.Engine.DMD.Unity/Runtime/Plugins/DmdPlugin.cs +++ b/VisualPinball.Engine.DMD.Unity/Runtime/Plugins/DmdPlugin.cs @@ -73,7 +73,7 @@ public override Task PrepareGameAsync(PluginGameContext game, CancellationToken _bridge.DiagnosticsOwner = this; var selection = new PluginResourceSelection(ResourceKind.Display) { Controller = game.ControllerId, Session = game.Session, Role = "dmd", Intent = asset == null ? ResourceView.Original : ResourceView.Identification, - Accepts = asset == null ? DisplayEncoding.Gray2 | DisplayEncoding.Gray4 | DisplayEncoding.Luminance8 | DisplayEncoding.Rgb24 : DisplayEncoding.Gray2 | DisplayEncoding.Gray4 }; + Accepts = asset == null ? DisplayEncoding.Gray2 | DisplayEncoding.Gray4 | DisplayEncoding.Luminance8 | DisplayEncoding.Rgb24 | DisplayEncoding.Rgb565 : DisplayEncoding.Gray2 | DisplayEncoding.Gray4 }; string source = effective.String("Source", "auto"); if (source != "auto") selection.ResourceId = PluginResourceChoices.Resolve(game.ControllerId, source); _binding = game.Lifetime.Own(game.Resources.Bind(selection)); _bridge.ConfigureManaged(settings, scene.Table, () => { diff --git a/VisualPinball.Engine.DMD.Unity/Runtime/Plugins/DmdPluginFactory.cs b/VisualPinball.Engine.DMD.Unity/Runtime/Plugins/DmdPluginFactory.cs index 53c3f88..0f3033a 100644 --- a/VisualPinball.Engine.DMD.Unity/Runtime/Plugins/DmdPluginFactory.cs +++ b/VisualPinball.Engine.DMD.Unity/Runtime/Plugins/DmdPluginFactory.cs @@ -89,7 +89,7 @@ public Task DiscoverAsync(string provider, PluginChoiceRequ private PluginChoiceCatalog Discover(string provider, PluginChoiceRequest request, CancellationToken cancellation) { cancellation.ThrowIfCancellationRequested(); - if (provider == "sources") return PluginResourceChoices.Displays(request, DisplayEncoding.Gray2 | DisplayEncoding.Gray4 | DisplayEncoding.Luminance8 | DisplayEncoding.Rgb24); + if (provider == "sources") return PluginResourceChoices.Displays(request, DisplayEncoding.Gray2 | DisplayEncoding.Gray4 | DisplayEncoding.Luminance8 | DisplayEncoding.Rgb24 | DisplayEncoding.Rgb565); var choices = new List(); switch (provider) { case "colorizations": diff --git a/VisualPinball.Engine.DMD.Unity/Runtime/VpeGleSource.cs b/VisualPinball.Engine.DMD.Unity/Runtime/VpeGleSource.cs index ec8ce08..540815e 100644 --- a/VisualPinball.Engine.DMD.Unity/Runtime/VpeGleSource.cs +++ b/VisualPinball.Engine.DMD.Unity/Runtime/VpeGleSource.cs @@ -7,6 +7,17 @@ namespace VisualPinball.Engine.DMD.Unity { + /// The colour of an uncolorized source's frames, which picks its format in the render graph. + internal enum DmdSourceColor + { + /// Gray frames of any bit depth, passed on as 8-bit. + Gray, + /// RGB frames, three bytes per dot. + Rgb24, + /// RGB565 frames, two bytes per dot, little-endian, as color DMD hardware takes them. + Rgb565 + } + internal abstract class VpeGleSource : AbstractSource, ISource { public override string Name { get; } @@ -27,19 +38,35 @@ protected VpeGleSource(string displayId, int width, int height) /// /// The render graph connects each destination to one format of the source, the first one /// both support, so an uncolorized source offers only the format its frames come in: gray - /// (any bit depth, as 8-bit) or RGB. The pipeline is rebuilt when frames switch between them. + /// (any bit depth, as 8-bit), RGB or RGB565. The pipeline is rebuilt when frames switch between them. /// - public static VpeGleSource Create(DisplayConfig display, bool colorize, bool rgb) + public static VpeGleSource Create(DisplayConfig display, bool colorize, DmdSourceColor color) { if (colorize) { return new ColorizableVpeGleSource(display.Id, display.Width, display.Height); } - return rgb - ? new Rgb24VpeGleSource(display.Id, display.Width, display.Height) - : new GrayVpeGleSource(display.Id, display.Width, display.Height); + return color switch { + DmdSourceColor.Rgb24 => new Rgb24VpeGleSource(display.Id, display.Width, display.Height), + DmdSourceColor.Rgb565 => new Rgb565VpeGleSource(display.Id, display.Width, display.Height), + _ => new GrayVpeGleSource(display.Id, display.Width, display.Height) + }; } + /// The source colour frames of this format need. + public static DmdSourceColor ColorOf(DisplayFrameFormat format) => format switch { + DisplayFrameFormat.Dmd24 => DmdSourceColor.Rgb24, + DisplayFrameFormat.Dmd565 => DmdSourceColor.Rgb565, + _ => DmdSourceColor.Gray + }; + + /// Bytes per dot of frames of this format. + public static int BytesPerDot(DisplayFrameFormat format) => format switch { + DisplayFrameFormat.Dmd24 => 3, + DisplayFrameFormat.Dmd565 => 2, + _ => 1 + }; + /// /// Pushes a frame from (the pipeline's reused worker buffer) into /// the reactive graph. Called on the DMD worker thread; the graph runs synchronously here. @@ -111,6 +138,24 @@ public override void Push(DisplayFrameFormat format, byte[] data, int length) public IObservable GetRgb24Frames() => _rgb24Frames; } + private sealed class Rgb565VpeGleSource : VpeGleSource, IRgb565Source + { + private readonly Subject _rgb565Frames = new Subject(); + + public Rgb565VpeGleSource(string displayId, int width, int height) : base(displayId, width, height) + { + } + + public override void Push(DisplayFrameFormat format, byte[] data, int length) + { + if (format == DisplayFrameFormat.Dmd565) { + _rgb565Frames.OnNext(CreateFrame(data, length, 16)); + } + } + + public IObservable GetRgb565Frames() => _rgb565Frames; + } + private sealed class ColorizableVpeGleSource : VpeGleSource, IGray2Source, IGray4Source { private readonly Subject _gray2Frames = new Subject(); diff --git a/VisualPinball.Engine.DMD.Unity/package.json b/VisualPinball.Engine.DMD.Unity/package.json index ceeb71a..804eba4 100644 --- a/VisualPinball.Engine.DMD.Unity/package.json +++ b/VisualPinball.Engine.DMD.Unity/package.json @@ -12,7 +12,7 @@ "unity": "6000.5", "unityRelease": "0f1", "dependencies": { - "org.visualpinball.engine.unity": "0.0.1-preview.238" + "org.visualpinball.engine.unity": "0.0.1-preview.255" }, "author": "freezy ", "documentationUrl": "https://docs.visualpinball.org/",