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
32 changes: 30 additions & 2 deletions Tests/Player/VpeGleSourceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand All @@ -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)) {
Expand All @@ -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) {
Expand Down
3 changes: 2 additions & 1 deletion Tests/Player/VpeTypes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ public enum DisplayFrameFormat
Segment,
AlphaNumeric,
Numeric,
Video24
Video24,
Dmd565
}

public class DisplayConfig
Expand Down
45 changes: 30 additions & 15 deletions VisualPinball.Engine.DMD.Unity/Runtime/DmdBridgePlayer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<IDestination> _presentationDestination;
Expand Down Expand Up @@ -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."));
}
Expand Down Expand Up @@ -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;
Expand All @@ -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;
}
Expand All @@ -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;
}

Expand Down Expand Up @@ -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;
}

Expand All @@ -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<IDestination> destinations)
{
var names = new List<string>(destinations.Count);
Expand Down
30 changes: 18 additions & 12 deletions VisualPinball.Engine.DMD.Unity/Runtime/DmdPipeline.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<IDestination> _destinations;
private readonly RenderGraph _renderGraph;
private readonly IDisposable _renderer;
Expand Down Expand Up @@ -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<IDestination> destinations, AbstractConverter converter, bool flipHorizontally, bool rgb)
public DmdPipeline(DisplayConfig display, List<IDestination> 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,
Expand Down Expand Up @@ -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;
}

/// <summary>Whether the source was built for frames of this format, gray or RGB.</summary>
public bool Accepts(DisplayFrameFormat format) => (format == DisplayFrameFormat.Dmd24) == _rgb;
/// <summary>Whether the source was built for frames of this format: gray, RGB or RGB565.</summary>
public bool Accepts(DisplayFrameFormat format) => VpeGleSource.ColorOf(format) == _color;

/// <summary>Called on the Unity main thread. Copies the frame and signals the worker.</summary>
public void Push(DisplayFrameData frame)
Expand All @@ -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;
}
Expand All @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<IPluginDisplaySource>(selection));
_bridge.ConfigureManaged(settings, scene.Table, () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public Task<PluginChoiceCatalog> 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<PluginChoice>();
switch (provider) {
case "colorizations":
Expand Down
55 changes: 50 additions & 5 deletions VisualPinball.Engine.DMD.Unity/Runtime/VpeGleSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@

namespace VisualPinball.Engine.DMD.Unity
{
/// <summary>The colour of an uncolorized source's frames, which picks its format in the render graph.</summary>
internal enum DmdSourceColor
{
/// <summary>Gray frames of any bit depth, passed on as 8-bit.</summary>
Gray,
/// <summary>RGB frames, three bytes per dot.</summary>
Rgb24,
/// <summary>RGB565 frames, two bytes per dot, little-endian, as color DMD hardware takes them.</summary>
Rgb565
}

internal abstract class VpeGleSource : AbstractSource, ISource
{
public override string Name { get; }
Expand All @@ -27,19 +38,35 @@ protected VpeGleSource(string displayId, int width, int height)
/// <summary>
/// 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.
/// </summary>
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)
};
}

/// <summary>The source colour frames of this format need.</summary>
public static DmdSourceColor ColorOf(DisplayFrameFormat format) => format switch {
DisplayFrameFormat.Dmd24 => DmdSourceColor.Rgb24,
DisplayFrameFormat.Dmd565 => DmdSourceColor.Rgb565,
_ => DmdSourceColor.Gray
};

/// <summary>Bytes per dot of frames of this format.</summary>
public static int BytesPerDot(DisplayFrameFormat format) => format switch {
DisplayFrameFormat.Dmd24 => 3,
DisplayFrameFormat.Dmd565 => 2,
_ => 1
};

/// <summary>
/// Pushes a frame from <paramref name="data"/> (the pipeline's reused worker buffer) into
/// the reactive graph. Called on the DMD worker thread; the graph runs synchronously here.
Expand Down Expand Up @@ -111,6 +138,24 @@ public override void Push(DisplayFrameFormat format, byte[] data, int length)
public IObservable<DmdFrame> GetRgb24Frames() => _rgb24Frames;
}

private sealed class Rgb565VpeGleSource : VpeGleSource, IRgb565Source
{
private readonly Subject<DmdFrame> _rgb565Frames = new Subject<DmdFrame>();

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<DmdFrame> GetRgb565Frames() => _rgb565Frames;
}

private sealed class ColorizableVpeGleSource : VpeGleSource, IGray2Source, IGray4Source
{
private readonly Subject<DmdFrame> _gray2Frames = new Subject<DmdFrame>();
Expand Down
2 changes: 1 addition & 1 deletion VisualPinball.Engine.DMD.Unity/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 <freezy@vpdb.io>",
"documentationUrl": "https://docs.visualpinball.org/",
Expand Down
Loading