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 src/Puppis.Driver/Sessions/TunerPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ private sealed class Lease(string deviceId, TuningKey tuning, SessionId holder)
private readonly Dictionary<SessionId, Lease> bySink = [];
private readonly Lock gate = new();
private readonly TimeSpan linger = grace ?? DefaultGrace;
private ITimer? sweeper;
private bool disposed;

public TimeSpan Grace => linger;

Expand Down Expand Up @@ -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();
}
}
Expand Down Expand Up @@ -494,7 +496,7 @@ public void Leave(SessionId sessionId)

if (lease.IsIdle)
{
lease.IdleSince = timeProvider.GetUtcNow();
LetLinger(lease);
}
}
}
Expand Down Expand Up @@ -635,6 +637,10 @@ public void Dispose()

lock (gate)
{
disposed = true;
sweeper?.Dispose();
sweeper = null;

foreach (Lease lease in leases.Values)
{
Forget(lease, closing);
Expand All @@ -653,6 +659,28 @@ public void Dispose()
}
}

/// <summary>
/// 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.
/// </summary>
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<Lease> LeasesFor(PoolRequest request)
{
foreach (string deviceId in request.Allowed)
Expand Down
27 changes: 27 additions & 0 deletions src/Puppis.Driver/Tuning/DescramblingTunerDevice.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Diagnostics;

using Microsoft.Extensions.Logging;

using Puppis.Driver.Descrambling;
Expand Down Expand Up @@ -26,6 +28,12 @@ public sealed class DescramblingTunerDevice : ITunerDevice

private Task<IDescrambler?>? asking;

private readonly long opened = Stopwatch.GetTimestamp();

private int scrambledReads;

private bool firstReadableReported;

private bool closed;

public DescramblingTunerDevice(
Expand Down Expand Up @@ -103,9 +111,12 @@ public byte[] Read(int count, CancellationToken cancellationToken)

if (readable.Length > 0)
{
ReportFirstReadable(readable.Length);

return readable;
}

scrambledReads++;
cancellationToken.ThrowIfCancellationRequested();
}
}
Expand Down Expand Up @@ -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
Expand Down
20 changes: 17 additions & 3 deletions src/Puppis.Driver/Tuning/TunerDeviceFactory.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Diagnostics;

using Microsoft.Extensions.Logging;

using Puppis.Contracts;
Expand Down Expand Up @@ -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<IDvbSystemCalls> systemCalls;
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -208,6 +214,7 @@ private ITunerDevice OpenDvb(DeviceSettings device, TuningRequest tuning, TunePa
/// </summary>
private ITunerDevice ThroughTheCard(Func<ITunerDevice> open, HeadHold hold)
{
long started = Stopwatch.GetTimestamp();
Task<IDescrambler?>? asking = descramblers.Unscrambles ? Task.Run(() => descramblers.Open(hold)) : null;
ITunerDevice opened;

Expand All @@ -227,6 +234,7 @@ private ITunerDevice ThroughTheCard(Func<ITunerDevice> open, HeadHold hold)
return opened;
}

TimeSpan tuned = Stopwatch.GetElapsedTime(started);
IDescrambler? descrambler;

try
Expand All @@ -240,6 +248,12 @@ private ITunerDevice ThroughTheCard(Func<ITunerDevice> 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);
}

Expand Down
22 changes: 11 additions & 11 deletions src/Puppis.Driver/Tuning/Usb/CechZd1/BridgeI2c.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
namespace Puppis.Driver.Tuning.Usb.CechZd1;

/// <summary>
/// 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.
/// </summary>
public sealed class BridgeI2c(BridgeMemory memory)
{
Expand Down Expand Up @@ -85,31 +88,28 @@ private void Begin(byte address, ReadOnlySpan<byte> bytes)
}
}

private void End()
{
memory.Write(Control, Idle);
WaitUntilIdle(0);
}
private void End() => memory.Write(Control, Idle);

private void Release() => memory.Write(Control, Idle);

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)
{
Expand All @@ -118,7 +118,7 @@ private void WaitForTheByte(byte address)

if ((control & ControlByteDone) is not 0)
{
return;
return words[0];
}
}

Expand Down
4 changes: 4 additions & 0 deletions src/Puppis.Driver/Tuning/Usb/CechZd1/BridgeMemory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -59,6 +61,7 @@ public uint[] ReadWords(uint address, int count)

lock (gate)
{
Requests++;
arrived = usb.ControlIn(SetupFor(ReadRequestType, at), asked, Patience);
}

Expand Down Expand Up @@ -98,6 +101,7 @@ public void WriteWords(uint address, ReadOnlySpan<uint> words)

lock (gate)
{
Requests++;
usb.ControlOut(SetupFor(WriteRequestType, at), bytes.AsSpan(0, taking * WordBytes), Patience);
}
}
Expand Down
121 changes: 121 additions & 0 deletions src/Puppis.Driver/Tuning/Usb/CechZd1/CechZd1Standby.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
using Puppis.Driver.Tuning.Dvb;

namespace Puppis.Driver.Tuning.Usb.CechZd1;

/// <summary>
/// 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.
/// </summary>
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;
}
}

/// <summary>
/// Hands out what is kept for <paramref name="path"/>, 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.
/// </summary>
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;
}

/// <summary>
/// Keeps the tuner for the next session. Anything kept before, and anything given after this standby is disposed,
/// is closed instead.
/// </summary>
public void Keep(KeptTuner tuner)
{
KeptTuner? replaced;

lock (gate)
{
replaced = kept;
kept = disposed ? null : tuner;
}

replaced?.Usb.Dispose();

if (disposed)
{
tuner.Usb.Dispose();
}
}

/// <summary>
/// Asks the kept demodulator to identify itself, which is the check a closed device would get by being opened.
/// </summary>
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();
}
}
Loading
Loading