From f986af157f7482197ae67a0a24dea847b77b24f1 Mon Sep 17 00:00:00 2001 From: fyui001 Date: Sun, 8 Nov 2026 00:21:13 +0900 Subject: [PATCH 1/3] =?UTF-8?q?torne=20=E3=81=AE=20I2C=20=E3=81=A7=201=20?= =?UTF-8?q?=E3=83=90=E3=82=A4=E3=83=88=E3=81=94=E3=81=A8=E3=81=AE=20USB=20?= =?UTF-8?q?=E8=A6=81=E6=B1=82=E3=82=92=204=20=E5=9B=9E=E3=81=8B=E3=82=89?= =?UTF-8?q?=203=20=E5=9B=9E=E3=81=AB=E6=B8=9B=E3=82=89=E3=81=99(=E7=8A=B6?= =?UTF-8?q?=E6=85=8B=E3=81=A8=E5=88=B6=E5=BE=A1=E3=81=AE=E8=AA=9E=E3=82=92?= =?UTF-8?q?=201=20=E5=9B=9E=E3=81=AE=E8=AA=AD=E3=81=BF=E3=81=A7=E5=8F=96?= =?UTF-8?q?=E3=82=8A=E3=80=81=E5=81=9C=E6=AD=A2=E6=9D=A1=E4=BB=B6=E3=82=92?= =?UTF-8?q?=E5=BE=85=E3=81=A4=E3=81=AE=E3=81=AF=E6=AC=A1=E3=81=AE=E9=80=81?= =?UTF-8?q?=E4=BF=A1=E3=81=AE=E5=89=8D=E3=81=AE=201=20=E5=9B=9E=E3=81=A0?= =?UTF-8?q?=E3=81=91=E3=81=AB=E3=81=99=E3=82=8B=E3=80=821=20=E8=A6=81?= =?UTF-8?q?=E6=B1=82=E3=81=AF=E5=AE=9F=E6=B8=AC=200.23=E3=80=9C0.3=20ms=20?= =?UTF-8?q?=E3=81=A7=E3=80=81=E9=96=8B=E3=81=8F=E3=81=82=E3=81=84=E3=81=A0?= =?UTF-8?q?=E3=81=AB=E7=B4=84=2017,000=20=E5=9B=9E=E5=87=BA=E3=81=A6?= =?UTF-8?q?=E3=81=84=E3=81=9F)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.1 --- .../Tuning/Usb/CechZd1/BridgeI2c.cs | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/Puppis.Driver/Tuning/Usb/CechZd1/BridgeI2c.cs b/src/Puppis.Driver/Tuning/Usb/CechZd1/BridgeI2c.cs index 6f874c1..49b1af1 100644 --- a/src/Puppis.Driver/Tuning/Usb/CechZd1/BridgeI2c.cs +++ b/src/Puppis.Driver/Tuning/Usb/CechZd1/BridgeI2c.cs @@ -3,7 +3,10 @@ namespace Puppis.Driver.Tuning.Usb.CechZd1; /// -/// The bridge's I2C master, driven one byte at a time through memory requests. +/// The bridge's I2C master, driven one byte at a time through memory requests. Each byte costs three requests: the +/// data, the control word that sends it, and one read of the status and control words together, which says whether +/// the byte is done and whether it was acknowledged. A transaction ends by writing the idle control word, and the +/// next one waits for the bus to be idle before it starts, so the stop condition is waited for once, not twice. /// public sealed class BridgeI2c(BridgeMemory memory) { @@ -85,11 +88,7 @@ private void Begin(byte address, ReadOnlySpan bytes) } } - private void End() - { - memory.Write(Control, Idle); - WaitUntilIdle(0); - } + private void End() => memory.Write(Control, Idle); private void Release() => memory.Write(Control, Idle); @@ -97,19 +96,20 @@ private void Send(uint value, uint control, byte address, string what) { memory.Write(Data, value); memory.Write(Control, control); - WaitForTheByte(address); + uint status = WaitForTheByte(address); - if ((memory.Read(Status) & StatusNoAcknowledge) is not 0) + if ((status & StatusNoAcknowledge) is not 0) { throw Fault($"the device at 0x{address:X2} did not acknowledge {what}"); } } - private void WaitForTheByte(byte address) + private uint WaitForTheByte(byte address) { for (int poll = 0; poll < MostPolls; poll++) { - uint control = memory.Read(Control); + uint[] words = memory.ReadWords(Status, 2); + uint control = words[1]; if ((control & ControlBusError) is not 0) { @@ -118,7 +118,7 @@ private void WaitForTheByte(byte address) if ((control & ControlByteDone) is not 0) { - return; + return words[0]; } } From 2ae54b953cfba9294a6df5724f65decaf9bc8f36 Mon Sep 17 00:00:00 2001 From: fyui001 Date: Sun, 8 Nov 2026 00:21:13 +0900 Subject: [PATCH 2/3] =?UTF-8?q?=E8=AA=B0=E3=82=82=E6=88=BB=E3=81=A3?= =?UTF-8?q?=E3=81=A6=E6=9D=A5=E3=81=AA=E3=81=8B=E3=81=A3=E3=81=9F=E3=83=81?= =?UTF-8?q?=E3=83=A5=E3=83=BC=E3=83=8A=E3=83=BC=E3=81=AF=E7=8C=B6=E4=BA=88?= =?UTF-8?q?=E3=81=AE=205=20=E7=A7=92=E3=81=8C=E9=81=8E=E3=81=8E=E3=81=9F?= =?UTF-8?q?=E3=81=A8=E3=81=8D=E3=81=AB=E3=82=BF=E3=82=A4=E3=83=9E=E3=83=BC?= =?UTF-8?q?=E3=81=A7=E9=96=89=E3=81=98=E3=80=81=E6=AC=A1=E3=81=AE=E8=A6=81?= =?UTF-8?q?=E6=B1=82=E3=81=AE=E6=99=82=E9=96=93=E3=81=AB=E9=96=89=E3=81=98?= =?UTF-8?q?=E3=82=8B=E4=BD=9C=E6=A5=AD=E3=82=92=E4=B9=97=E3=81=9B=E3=81=AA?= =?UTF-8?q?=E3=81=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.1 --- src/Puppis.Driver/Sessions/TunerPool.cs | 32 +++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/src/Puppis.Driver/Sessions/TunerPool.cs b/src/Puppis.Driver/Sessions/TunerPool.cs index 820d541..06c2fa6 100644 --- a/src/Puppis.Driver/Sessions/TunerPool.cs +++ b/src/Puppis.Driver/Sessions/TunerPool.cs @@ -84,6 +84,8 @@ private sealed class Lease(string deviceId, TuningKey tuning, SessionId holder) private readonly Dictionary bySink = []; private readonly Lock gate = new(); private readonly TimeSpan linger = grace ?? DefaultGrace; + private ITimer? sweeper; + private bool disposed; public TimeSpan Grace => linger; @@ -395,7 +397,7 @@ public void TuningFailed(string deviceId, SessionId tuner, Exception cause) lease.Sinks.Clear(); lease.TuneFailure = cause; lease.Established = false; - lease.IdleSince = timeProvider.GetUtcNow(); + LetLinger(lease); lease.Ready.TrySetResult(); } } @@ -494,7 +496,7 @@ public void Leave(SessionId sessionId) if (lease.IsIdle) { - lease.IdleSince = timeProvider.GetUtcNow(); + LetLinger(lease); } } } @@ -635,6 +637,10 @@ public void Dispose() lock (gate) { + disposed = true; + sweeper?.Dispose(); + sweeper = null; + foreach (Lease lease in leases.Values) { Forget(lease, closing); @@ -653,6 +659,28 @@ public void Dispose() } } + /// + /// Marks the lease idle and arranges for the pool to be swept once the grace has passed, so that a device nobody + /// came back for is closed then and not on the next request's time. + /// + private void LetLinger(Lease lease) + { + lease.IdleSince = timeProvider.GetUtcNow(); + + if (disposed) + { + return; + } + + sweeper ??= timeProvider.CreateTimer( + static pool => ((TunerPool)pool!).Sweep(), + this, + Timeout.InfiniteTimeSpan, + Timeout.InfiniteTimeSpan + ); + sweeper.Change(linger + TimeSpan.FromMilliseconds(20), Timeout.InfiniteTimeSpan); + } + private IEnumerable LeasesFor(PoolRequest request) { foreach (string deviceId in request.Allowed) From e0656e36451f31e2c49631f0c42a21f9fd7cc58a Mon Sep 17 00:00:00 2001 From: fyui001 Date: Sun, 8 Nov 2026 00:21:13 +0900 Subject: [PATCH 3/3] =?UTF-8?q?=E9=96=89=E3=81=98=E3=81=9F=20torne=20?= =?UTF-8?q?=E3=82=92=E7=9C=A0=E3=82=89=E3=81=9B=E3=81=9F=E3=81=BE=E3=81=BE?= =?UTF-8?q?=E9=96=8B=E3=81=84=E3=81=A6=E3=81=8A=E3=81=8D=E3=80=81=E6=AC=A1?= =?UTF-8?q?=E3=81=AE=E3=82=BB=E3=83=83=E3=82=B7=E3=83=A7=E3=83=B3=E3=81=A7?= =?UTF-8?q?=E3=81=AF=E8=B5=B7=E3=81=93=E3=81=97=E3=81=A6=E5=90=88=E3=82=8F?= =?UTF-8?q?=E3=81=9B=E3=82=8B=E3=81=A0=E3=81=91=E3=81=AB=E3=81=99=E3=82=8B?= =?UTF-8?q?(=E3=83=96=E3=83=AA=E3=83=83=E3=82=B8=E3=81=AE=E8=B5=B7?= =?UTF-8?q?=E5=8B=95=E3=81=A8=E5=88=9D=E6=9C=9F=E5=8C=96=E3=81=AE=E7=B4=84?= =?UTF-8?q?=201.7=20=E7=A7=92=E3=82=92=E7=9C=81=E3=81=8F=E3=80=82=E8=B5=B7?= =?UTF-8?q?=E3=81=8D=E3=81=9F=E3=81=A8=E3=81=8D=E3=81=AF=E3=82=AD=E3=83=A3?= =?UTF-8?q?=E3=83=AA=E3=83=96=E3=83=AC=E3=83=BC=E3=82=B7=E3=83=A7=E3=83=B3?= =?UTF-8?q?=E3=81=A8=E5=B8=AF=E5=9F=9F=E3=81=AE=E8=A8=AD=E5=AE=9A=E3=82=92?= =?UTF-8?q?=E9=9B=BB=E6=BA=90=E6=8A=95=E5=85=A5=E5=BE=8C=E3=81=A8=E5=90=8C?= =?UTF-8?q?=E3=81=98=E3=81=AB=E3=82=84=E3=82=8A=E7=9B=B4=E3=81=97=E3=80=81?= =?UTF-8?q?=E5=90=88=E3=82=8F=E3=81=AA=E3=81=91=E3=82=8C=E3=81=B0=E9=96=89?= =?UTF-8?q?=E3=81=98=E3=81=A6=E6=9C=80=E5=88=9D=E3=81=8B=E3=82=89=E9=96=8B?= =?UTF-8?q?=E3=81=8F)=E3=80=82=E9=96=8B=E3=81=8F=E3=81=A8=E3=81=8D?= =?UTF-8?q?=E3=81=AE=E6=AE=B5=E3=81=94=E3=81=A8=E3=81=AE=E6=89=80=E8=A6=81?= =?UTF-8?q?=E3=81=A8=E8=A6=81=E6=B1=82=E6=95=B0=E3=80=81=E3=82=AB=E3=83=BC?= =?UTF-8?q?=E3=83=89=E3=81=AE=E5=88=B0=E7=9D=80=E3=80=81=E6=9C=80=E5=88=9D?= =?UTF-8?q?=E3=81=AB=E8=AA=AD=E3=82=81=E3=82=8B=E5=B8=AF=E3=81=AE=E6=99=82?= =?UTF-8?q?=E5=88=BB=E3=82=92=E3=83=AD=E3=82=B0=E3=81=AB=E5=87=BA=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.1 --- .../Tuning/DescramblingTunerDevice.cs | 27 ++ .../Tuning/TunerDeviceFactory.cs | 20 +- .../Tuning/Usb/CechZd1/BridgeMemory.cs | 4 + .../Tuning/Usb/CechZd1/CechZd1Standby.cs | 121 +++++++++ .../Tuning/Usb/CechZd1/CechZd1TunerDevice.cs | 248 +++++++++++++++--- .../Tuning/Usb/CechZd1/Dib0090.cs | 14 +- tests/Puppis.Driver.Tests/CechZd1Tests.cs | 156 +++++++++++ 7 files changed, 549 insertions(+), 41 deletions(-) create mode 100644 src/Puppis.Driver/Tuning/Usb/CechZd1/CechZd1Standby.cs diff --git a/src/Puppis.Driver/Tuning/DescramblingTunerDevice.cs b/src/Puppis.Driver/Tuning/DescramblingTunerDevice.cs index d6230ce..baa3140 100644 --- a/src/Puppis.Driver/Tuning/DescramblingTunerDevice.cs +++ b/src/Puppis.Driver/Tuning/DescramblingTunerDevice.cs @@ -1,3 +1,5 @@ +using System.Diagnostics; + using Microsoft.Extensions.Logging; using Puppis.Driver.Descrambling; @@ -26,6 +28,12 @@ public sealed class DescramblingTunerDevice : ITunerDevice private Task? asking; + private readonly long opened = Stopwatch.GetTimestamp(); + + private int scrambledReads; + + private bool firstReadableReported; + private bool closed; public DescramblingTunerDevice( @@ -103,9 +111,12 @@ public byte[] Read(int count, CancellationToken cancellationToken) if (readable.Length > 0) { + ReportFirstReadable(readable.Length); + return readable; } + scrambledReads++; cancellationToken.ThrowIfCancellationRequested(); } } @@ -157,6 +168,22 @@ public byte[] Read(int count, CancellationToken cancellationToken) } } + private void ReportFirstReadable(int bytes) + { + if (firstReadableReported) + { + return; + } + + firstReadableReported = true; + logger?.LogInformation( + "The first readable bytes, {Bytes} of them, came {Seconds:0.000} s after the card was in hand, after {Reads} reads that gave nothing readable.", + bytes, + Stopwatch.GetElapsedTime(opened).TotalSeconds, + scrambledReads + ); + } + private IDescrambler? Ask() { try diff --git a/src/Puppis.Driver/Tuning/TunerDeviceFactory.cs b/src/Puppis.Driver/Tuning/TunerDeviceFactory.cs index f10dd7d..7e20b52 100644 --- a/src/Puppis.Driver/Tuning/TunerDeviceFactory.cs +++ b/src/Puppis.Driver/Tuning/TunerDeviceFactory.cs @@ -1,3 +1,5 @@ +using System.Diagnostics; + using Microsoft.Extensions.Logging; using Puppis.Contracts; @@ -28,8 +30,9 @@ public interface ITunerDeviceCheck void Check(DeviceSettings device); } -public sealed class TunerDeviceFactory : ITunerDeviceFactory, ITunerDeviceCheck +public sealed class TunerDeviceFactory : ITunerDeviceFactory, ITunerDeviceCheck, IDisposable { + private readonly CechZd1Standby standby = new(); private readonly TunerBackend backend; private readonly TimeProvider time; private readonly Lazy systemCalls; @@ -133,7 +136,7 @@ public void Check(DeviceSettings device) return; case TunerBackend.Usb: - CechZd1TunerDevice.OpenAndClose(usbHost.Value, UsbPathOf(device)); + CechZd1TunerDevice.OpenAndClose(usbHost.Value, UsbPathOf(device), standby); return; default: @@ -174,12 +177,15 @@ private ITunerDevice OpenUsb(DeviceSettings device, TuningRequest tuning, TunePa DvbFrequency.TerrestrialHertz(channel.PhysicalChannel), pacing, settings.BytePatience, - logger + logger, + standby ), hold ); } + public void Dispose() => standby.Dispose(); + private static ITunerDevice Synthetic(TuningRequest tuning) => new FakeTunerDevice(tuning.PhysicalChannel, tuning.ServiceId); @@ -208,6 +214,7 @@ private ITunerDevice OpenDvb(DeviceSettings device, TuningRequest tuning, TunePa /// private ITunerDevice ThroughTheCard(Func open, HeadHold hold) { + long started = Stopwatch.GetTimestamp(); Task? asking = descramblers.Unscrambles ? Task.Run(() => descramblers.Open(hold)) : null; ITunerDevice opened; @@ -227,6 +234,7 @@ private ITunerDevice ThroughTheCard(Func open, HeadHold hold) return opened; } + TimeSpan tuned = Stopwatch.GetElapsedTime(started); IDescrambler? descrambler; try @@ -240,6 +248,12 @@ private ITunerDevice ThroughTheCard(Func open, HeadHold hold) throw; } + logger?.LogInformation( + "The tuner was open after {Tuned:0.000} s and the card was in hand after {Card:0.000} s.", + tuned.TotalSeconds, + Stopwatch.GetElapsedTime(started).TotalSeconds + ); + return Unscrambling(opened, descrambler, hold); } diff --git a/src/Puppis.Driver/Tuning/Usb/CechZd1/BridgeMemory.cs b/src/Puppis.Driver/Tuning/Usb/CechZd1/BridgeMemory.cs index 0b1fc28..ab75355 100644 --- a/src/Puppis.Driver/Tuning/Usb/CechZd1/BridgeMemory.cs +++ b/src/Puppis.Driver/Tuning/Usb/CechZd1/BridgeMemory.cs @@ -32,6 +32,8 @@ public sealed class BridgeMemory(IUsbConnection usb) public string Path => usb.Path; + public long Requests { get; private set; } + public static UsbSetup SetupFor(byte requestType, uint address) => new( requestType, @@ -59,6 +61,7 @@ public uint[] ReadWords(uint address, int count) lock (gate) { + Requests++; arrived = usb.ControlIn(SetupFor(ReadRequestType, at), asked, Patience); } @@ -98,6 +101,7 @@ public void WriteWords(uint address, ReadOnlySpan words) lock (gate) { + Requests++; usb.ControlOut(SetupFor(WriteRequestType, at), bytes.AsSpan(0, taking * WordBytes), Patience); } } diff --git a/src/Puppis.Driver/Tuning/Usb/CechZd1/CechZd1Standby.cs b/src/Puppis.Driver/Tuning/Usb/CechZd1/CechZd1Standby.cs new file mode 100644 index 0000000..6ddd739 --- /dev/null +++ b/src/Puppis.Driver/Tuning/Usb/CechZd1/CechZd1Standby.cs @@ -0,0 +1,121 @@ +using Puppis.Driver.Tuning.Dvb; + +namespace Puppis.Driver.Tuning.Usb.CechZd1; + +/// +/// The bridge and the frontend of a tuner that was closed, kept open and asleep so that the next session on the same +/// device wakes and tunes them instead of starting the bridge and initialising the chips again. +/// +public sealed class CechZd1Standby : IDisposable +{ + private readonly Lock gate = new(); + private KeptTuner? kept; + private bool disposed; + + public sealed record KeptTuner( + string Path, + IUsbConnection Usb, + BridgeMemory Memory, + CechZd1Frontend Frontend, + TransportCapture Capture + ); + + public bool Holds(string path) + { + lock (gate) + { + return kept?.Path == path; + } + } + + /// + /// Hands out what is kept for , or null when nothing is. Whatever is kept for another path + /// is closed, since the tuner it belonged to is no longer where it was. + /// + public KeptTuner? Take(string path) + { + KeptTuner? taken; + + lock (gate) + { + taken = kept; + kept = null; + } + + if (taken is null) + { + return null; + } + + if (taken.Path == path) + { + return taken; + } + + taken.Usb.Dispose(); + + return null; + } + + /// + /// Keeps the tuner for the next session. Anything kept before, and anything given after this standby is disposed, + /// is closed instead. + /// + public void Keep(KeptTuner tuner) + { + KeptTuner? replaced; + + lock (gate) + { + replaced = kept; + kept = disposed ? null : tuner; + } + + replaced?.Usb.Dispose(); + + if (disposed) + { + tuner.Usb.Dispose(); + } + } + + /// + /// Asks the kept demodulator to identify itself, which is the check a closed device would get by being opened. + /// + public void Check(string path) + { + KeptTuner? taken = Take(path); + + if (taken is null) + { + throw new InvalidOperationException($"Nothing is kept for {path}."); + } + + try + { + taken.Frontend.Demodulator.Identify(path); + } + catch (DvbDeviceException) + { + taken.Usb.Dispose(); + + throw; + } + + Keep(taken); + } + + public void Dispose() + { + KeptTuner? closing; + + lock (gate) + { + disposed = true; + closing = kept; + kept = null; + } + + closing?.Usb.Dispose(); + } +} diff --git a/src/Puppis.Driver/Tuning/Usb/CechZd1/CechZd1TunerDevice.cs b/src/Puppis.Driver/Tuning/Usb/CechZd1/CechZd1TunerDevice.cs index ebf01c1..d3279d7 100644 --- a/src/Puppis.Driver/Tuning/Usb/CechZd1/CechZd1TunerDevice.cs +++ b/src/Puppis.Driver/Tuning/Usb/CechZd1/CechZd1TunerDevice.cs @@ -1,3 +1,5 @@ +using System.Diagnostics; + using Microsoft.Extensions.Logging; using Puppis.Driver.Transport; @@ -18,33 +20,39 @@ public sealed class CechZd1TunerDevice : ITunerDevice, ISignalQualitySource public static readonly TimeSpan TransferPatience = TimeSpan.FromMilliseconds(300); + private readonly CechZd1Standby.KeptTuner kept; private readonly IUsbConnection usb; private readonly CechZd1Frontend frontend; private readonly TransportCapture capture; private readonly IUsbBulkReader reader; private readonly DevicePacing pacing; private readonly TimeSpan bytePatience; + private readonly CechZd1Standby? standby; private readonly CaptureUnpacker unpacker = new(); private readonly List packets = []; private readonly byte[] transfer = new byte[TransportCapture.TransferBytes]; private readonly Lock gate = new(); + private ILogger? logger; + private long opened; + private bool firstBytesReported; private bool closed; private CechZd1TunerDevice( - IUsbConnection usb, - CechZd1Frontend frontend, - TransportCapture capture, + CechZd1Standby.KeptTuner kept, IUsbBulkReader reader, DevicePacing pacing, - TimeSpan bytePatience + TimeSpan bytePatience, + CechZd1Standby? standby ) { - this.usb = usb; - this.frontend = frontend; - this.capture = capture; + this.kept = kept; + usb = kept.Usb; + frontend = kept.Frontend; + capture = kept.Capture; this.reader = reader; this.pacing = pacing; this.bytePatience = bytePatience; + this.standby = standby; } public long Overflows => unpacker.Realignments; @@ -69,40 +77,72 @@ public static CechZd1TunerDevice Open( long hertz, DevicePacing pacing, TimeSpan bytePatience, - ILogger? logger = null + ILogger? logger = null, + CechZd1Standby? standby = null ) { Recognise(host, path); + + if (standby?.Take(path) is { } kept) + { + try + { + return WakeAndTune(kept, hertz, pacing, bytePatience, logger, standby); + } + catch (DvbDeviceException fault) + { + logger?.LogWarning( + fault, + "{Path}: the tuner kept open since the last session did not lock, so it is started afresh.", + path + ); + } + } + + return StartAndTune(host, path, hertz, pacing, bytePatience, logger, standby); + } + + public static void OpenAndClose(IUsbHost host, string path, CechZd1Standby? standby = null) + { + Recognise(host, path); + + if (standby?.Holds(path) is true) + { + standby.Check(path); + + return; + } + + host.Open(path, Interface).Dispose(); + } + + private static CechZd1TunerDevice StartAndTune( + IUsbHost host, + string path, + long hertz, + DevicePacing pacing, + TimeSpan bytePatience, + ILogger? logger, + CechZd1Standby? standby + ) + { + long started = Stopwatch.GetTimestamp(); IUsbConnection usb = host.Open(path, Interface); CechZd1Frontend? frontend = null; try { var memory = new BridgeMemory(usb); + var stages = new OpeningStages(started, memory); BridgeStartup.Start(memory, pacing); + stages.Mark("bridge"); var i2c = new BridgeI2c(memory); frontend = new CechZd1Frontend(new Dib8000Bus(i2c), new Dib0090Bus(i2c), pacing, path); frontend.Initialise(); - var capture = new TransportCapture(memory); - capture.Prepare(); + stages.Mark("frontend"); + var kept = new CechZd1Standby.KeptTuner(path, usb, memory, frontend, new TransportCapture(memory)); - if (frontend.Tune(hertz) is SearchOutcome.Failed) - { - throw DvbFailure.NoLock( - $"{path}: the demodulator did not synchronise on {hertz / 1000} kHz. Nothing was received, so no bytes will follow." - ); - } - - IUsbBulkReader reader = usb.ReadBulk( - TransportCapture.Endpoint, - TransportCapture.TransferBytes, - TransportCapture.TransfersInFlight - ); - capture.Start(); - var device = new CechZd1TunerDevice(usb, frontend, capture, reader, pacing, bytePatience); - device.Report(logger, hertz); - - return device; + return Tune(kept, hertz, pacing, bytePatience, logger, standby, stages, "started"); } catch { @@ -114,10 +154,87 @@ public static CechZd1TunerDevice Open( } } - public static void OpenAndClose(IUsbHost host, string path) + /// + /// Tunes a tuner kept from the last session. Whatever goes wrong, the kept tuner is closed, so that the device is + /// started from its bridge again rather than kept in a state that does not lock. + /// + private static CechZd1TunerDevice WakeAndTune( + CechZd1Standby.KeptTuner kept, + long hertz, + DevicePacing pacing, + TimeSpan bytePatience, + ILogger? logger, + CechZd1Standby standby + ) { - Recognise(host, path); - host.Open(path, Interface).Dispose(); + var stages = new OpeningStages(Stopwatch.GetTimestamp(), kept.Memory); + + try + { + return Tune(kept, hertz, pacing, bytePatience, logger, standby, stages, "woken"); + } + catch + { + Quietly(kept.Frontend.Sleep); + Quietly(() => kept.Frontend.Demodulator.LedGreen()); + kept.Usb.Dispose(); + + throw; + } + } + + private static CechZd1TunerDevice Tune( + CechZd1Standby.KeptTuner kept, + long hertz, + DevicePacing pacing, + TimeSpan bytePatience, + ILogger? logger, + CechZd1Standby? standby, + OpeningStages stages, + string how + ) + { + kept.Capture.Prepare(); + stages.Mark("capture"); + + if (kept.Frontend.Tune(hertz) is SearchOutcome.Failed) + { + throw DvbFailure.NoLock( + $"{kept.Path}: the demodulator did not synchronise on {hertz / 1000} kHz. Nothing was received, so no bytes will follow." + ); + } + + stages.Mark("tune"); + IUsbBulkReader reader = kept.Usb.ReadBulk( + TransportCapture.Endpoint, + TransportCapture.TransferBytes, + TransportCapture.TransfersInFlight + ); + kept.Capture.Start(); + stages.Mark("start"); + var device = new CechZd1TunerDevice(kept, reader, pacing, bytePatience, standby); + device.logger = logger; + device.opened = stages.Started; + device.Report(logger, hertz, stages, how); + + return device; + } + + /// + /// Puts the frontend to sleep and keeps it for the next session, or closes the device when it will not sleep. + /// + private static void Rest(CechZd1Standby.KeptTuner kept, CechZd1Standby? standby) + { + bool asleep = Quietly(() => kept.Frontend.Demodulator.LedGreen()) & Quietly(kept.Frontend.Sleep); + + if (asleep && standby is not null) + { + standby.Keep(kept); + } + else + { + kept.Usb.Dispose(); + } } public SignalQuality Measure() @@ -149,6 +266,7 @@ public byte[] Read(int count, CancellationToken cancellationToken) if (arrived > 0) { unpacker.Unpack(transfer.AsSpan(0, arrived), packets); + ReportFirstBytes(arrived); } else if (pacing.Now >= deadline) { @@ -175,11 +293,24 @@ public void Dispose() } closed = true; - Quietly(capture.Stop); - Quietly(reader.Dispose); - Quietly(() => frontend.Demodulator.LedGreen()); - Quietly(frontend.Sleep); - usb.Dispose(); + long began = Stopwatch.GetTimestamp(); + bool stopped = Quietly(capture.Stop) & Quietly(reader.Dispose); + + if (stopped) + { + Rest(kept, standby); + } + else + { + usb.Dispose(); + } + + logger?.LogInformation( + "{Path}: closing took {Milliseconds:0} ms; the tuner is {State}.", + usb.Path, + Stopwatch.GetElapsedTime(began).TotalMilliseconds, + standby?.Holds(usb.Path) is true ? "kept asleep for the next session" : "closed" + ); } } @@ -211,13 +342,31 @@ private DvbDeviceException NothingArrived() ); } - private void Report(ILogger? logger, long hertz) + private void ReportFirstBytes(int arrived) + { + if (firstBytesReported) + { + return; + } + + firstBytesReported = true; + logger?.LogInformation( + "{Path}: the first bulk read, {Bytes} bytes, arrived {Seconds:0.000} s after the tuner was opened.", + usb.Path, + arrived, + Stopwatch.GetElapsedTime(opened).TotalSeconds + ); + } + + private void Report(ILogger? logger, long hertz, OpeningStages stages, string how) { if (logger is null) { return; } + logger.LogInformation("{Path}: {How} and tuned in {Stages}.", usb.Path, how, stages); + SignalRegisters registers = frontend.ReadSignal(); double? decibels = CechZd1Signal.Decibels( CechZd1Signal.Expand(registers.Signal), @@ -233,17 +382,42 @@ private void Report(ILogger? logger, long hertz) ); } - private static void Quietly(Action action) + private static bool Quietly(Action action) { try { action(); + + return true; } catch (DvbDeviceException) { + return false; } catch (InvalidOperationException) { + return false; } } } + +internal sealed class OpeningStages(long started, BridgeMemory memory) +{ + private readonly List marks = []; + private long last = started; + private long requests = memory.Requests; + + public long Started { get; } = started; + + public void Mark(string stage) + { + long now = Stopwatch.GetTimestamp(); + long sent = memory.Requests; + marks.Add($"{stage} {Stopwatch.GetElapsedTime(last, now).TotalMilliseconds:0} ms/{sent - requests} requests"); + last = now; + requests = sent; + } + + public override string ToString() => + $"{Stopwatch.GetElapsedTime(Started).TotalMilliseconds:0} ms in all ({string.Join(", ", marks)})"; +} diff --git a/src/Puppis.Driver/Tuning/Usb/CechZd1/Dib0090.cs b/src/Puppis.Driver/Tuning/Usb/CechZd1/Dib0090.cs index 7cc9a30..9118234 100644 --- a/src/Puppis.Driver/Tuning/Usb/CechZd1/Dib0090.cs +++ b/src/Puppis.Driver/Tuning/Usb/CechZd1/Dib0090.cs @@ -138,7 +138,19 @@ public static bool Recognise(ushort identity, string path) ); } - public void Wake() => t.Modify(0x23, 0, Awake); + /// + /// Wakes the tuner. The calibrations are done again and the band and synthesiser are written again at the next + /// tune, as they are after power-up, because the calibration clears the enable register that a tune to the + /// frequency already requested would otherwise leave as it is. + /// + public void Wake() + { + t.Modify(0x23, 0, Awake); + dcPending = true; + widebandPending = true; + temperaturePending = true; + RequestedKilohertz = 0; + } public void RequestTemperature() => temperaturePending = true; diff --git a/tests/Puppis.Driver.Tests/CechZd1Tests.cs b/tests/Puppis.Driver.Tests/CechZd1Tests.cs index 9dbb953..4637114 100644 --- a/tests/Puppis.Driver.Tests/CechZd1Tests.cs +++ b/tests/Puppis.Driver.Tests/CechZd1Tests.cs @@ -727,3 +727,159 @@ private sealed class CountingDescramblers(bool unscrambles) : IDescramblerFactor } } } + +public sealed class CechZd1StandbyTests +{ + private const string Device = "/dev/bus/usb/001/002"; + + private static readonly long Channel22 = BroadcastStandards.TerrestrialCentreHz(22); + + private static readonly long Channel27 = BroadcastStandards.TerrestrialCentreHz(27); + + private static (FakeUsbHost Host, FakeBridge Bridge, FakeChip Demodulator, FakeChip Tuner, DevicePacing Pacing) Parts() + { + (FakeChip demodulator, FakeChip tuner) = UsbTestSupport.LockingChips(); + FakeBridge bridge = UsbTestSupport.BridgeWith(demodulator, tuner); + (DevicePacing pacing, ManualTimeProvider clock, _) = UsbTestSupport.Pacing(); + bridge.Idle = clock.Advance; + + return (new FakeUsbHost(bridge), bridge, demodulator, tuner, pacing); + } + + private static CechZd1TunerDevice Open(FakeUsbHost host, long hertz, DevicePacing pacing, CechZd1Standby standby) => + CechZd1TunerDevice.Open(host, Device, hertz, pacing, TimeSpan.FromSeconds(5), null, standby); + + [Fact] + public void AClosedTunerStaysOpenAsleepAndIsWokenAndTunedForTheNextSession() + { + (FakeUsbHost host, FakeBridge bridge, FakeChip demodulator, FakeChip tuner, DevicePacing pacing) = Parts(); + using var standby = new CechZd1Standby(); + CechZd1TunerDevice first = Open(host, Channel22, pacing, standby); + first.Dispose(); + int bridgeStarts = bridge.WritesAt(0xF1010C).Count; + int identifications = demodulator.ReadFrom.Count(register => register is 896); + int calibrations = tuner.WritesTo(0x07).Count; + + Assert.False(bridge.Disposed); + Assert.True(standby.Holds(Device)); + Assert.Equal(0, demodulator.Last(1286)); + + CechZd1TunerDevice second = Open(host, Channel27, pacing, standby); + + Assert.Equal(1, host.Opened); + Assert.False(standby.Holds(Device)); + Assert.Equal(bridgeStarts, bridge.WritesAt(0xF1010C).Count); + Assert.Equal(identifications, demodulator.ReadFrom.Count(register => register is 896)); + Assert.True(tuner.WritesTo(0x07).Count > calibrations); + Assert.Equal(0x0400, demodulator.Last(1286)); + Assert.Equal(0x03000000u, bridge.Word(0xD01040)); + Assert.Equal(TransportCapture.CoreRunning, bridge.Word(TransportCapture.FirstCore)); + second.Dispose(); + Assert.True(standby.Holds(Device)); + } + + [Fact] + public void AKeptTunerThatNoLongerAnswersIsClosedAndTheDeviceStartedAfresh() + { + (FakeUsbHost host, FakeBridge bridge, _, _, DevicePacing pacing) = Parts(); + using var standby = new CechZd1Standby(); + Open(host, Channel22, pacing, standby).Dispose(); + bridge.NotAcknowledging = true; + + DvbDeviceException refused = UsbTestSupport.Refusal(() => Open(host, Channel22, pacing, standby)); + + Assert.Equal(TuningFailure.DeviceUnusable, refused.Failure); + Assert.Equal(2, host.Opened); + Assert.True(bridge.Disposed); + Assert.False(standby.Holds(Device)); + } + + [Fact] + public void AKeptTunerThatDoesNotLockIsClosedAndTheDeviceStartedAfresh() + { + (FakeUsbHost host, FakeBridge bridge, FakeChip demodulator, _, DevicePacing pacing) = Parts(); + using var standby = new CechZd1Standby(); + Open(host, Channel22, pacing, standby).Dispose(); + int bridgeStarts = bridge.WritesAt(0xF1010C).Count; + demodulator.Answer(1284, 0x0001); + + DvbDeviceException refused = UsbTestSupport.Refusal(() => Open(host, Channel27, pacing, standby)); + + Assert.Equal(TuningFailure.NoLock, refused.Failure); + Assert.Equal(2, host.Opened); + Assert.Equal(bridgeStarts + 1, bridge.WritesAt(0xF1010C).Count); + Assert.True(bridge.Disposed); + Assert.False(standby.Holds(Device)); + } + + [Fact] + public void AWokenTunerWritesItsBandAgainEvenForTheFrequencyItWasOn() + { + (FakeUsbHost host, _, _, FakeChip tuner, DevicePacing pacing) = Parts(); + using var standby = new CechZd1Standby(); + Open(host, Channel22, pacing, standby).Dispose(); + int bandWrites = tuner.WritesTo(0x0B).Count; + int synthesiserWrites = tuner.WritesTo(0x15).Count; + + CechZd1TunerDevice again = Open(host, Channel22, pacing, standby); + + Assert.Equal(bandWrites + 1, tuner.WritesTo(0x0B).Count); + Assert.Equal(synthesiserWrites + 1, tuner.WritesTo(0x15).Count); + again.Dispose(); + } + + [Fact] + public void CheckingAKeptTunerAsksTheDemodulatorWhoItIsWithoutOpeningTheDeviceAgain() + { + (FakeUsbHost host, FakeBridge bridge, FakeChip demodulator, _, DevicePacing pacing) = Parts(); + using var standby = new CechZd1Standby(); + Open(host, Channel22, pacing, standby).Dispose(); + + CechZd1TunerDevice.OpenAndClose(host, Device, standby); + + Assert.Equal(1, host.Opened); + Assert.True(standby.Holds(Device)); + + demodulator.Answer(896, 0x0000); + + UsbTestSupport.Refusal(() => CechZd1TunerDevice.OpenAndClose(host, Device, standby)); + + Assert.False(standby.Holds(Device)); + Assert.True(bridge.Disposed); + } + + [Fact] + public void AKeptTunerOnAnotherPathIsClosedWhenThisPathIsOpened() + { + (FakeUsbHost host, FakeBridge bridge, _, _, DevicePacing pacing) = Parts(); + using var standby = new CechZd1Standby(); + Open(host, Channel22, pacing, standby).Dispose(); + + CechZd1TunerDevice moved = CechZd1TunerDevice.Open( + host, + "/dev/bus/usb/001/007", + Channel22, + pacing, + TimeSpan.FromSeconds(5), + null, + standby + ); + + Assert.True(bridge.Disposed); + Assert.Equal(2, host.Opened); + moved.Dispose(); + } + + [Fact] + public void DisposingTheStandbyClosesWhatItKeeps() + { + (FakeUsbHost host, FakeBridge bridge, _, _, DevicePacing pacing) = Parts(); + var standby = new CechZd1Standby(); + Open(host, Channel22, pacing, standby).Dispose(); + + standby.Dispose(); + + Assert.True(bridge.Disposed); + Assert.False(standby.Holds(Device)); + } +}